Compare commits

...
26 Commits
Author SHA1 Message Date
lucioandClaude Fable 5 1c20549cfa Release 0.36.0 — lint severities, per-rule editor toggles, nineteen new rules
ci / checks (push) Successful in 53s
ci / corpus (push) Successful in 28s
release / build-and-publish (push) Failing after 11m8s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 17:57:22 -07:00
lucio 97f7296b8f Merge branch 'lint-1' 2026-09-03 17:49:03 -07:00
lucioandClaude Fable 5 cebeff45b4 Linter expansion, wave 1: severities end to end, per-rule editor toggles generated from the registry, and nineteen Error/Warning-class rules
TODO section 33. Every rule states a Severity (error: would likely fail
to compile or elaborate, or silently mis-synthesize; warning: a probable
bug; style), printed in lucisv check text and JSON, mapped to
ERROR/WARNING/INFORMATION in the editor, grouped in --rules-doc, and
accepted by --select/--ignore and [lint] as a class word. VS Code gains
lucisv.lint.severity.{error,warning,style} and one tri-state
lucisv.lint.rules.<rule> per rule (default/on/off - a client sends
every key, so a boolean cannot say unset), generated by
vlog_linter::vscode with a drift test, and lint::enabled_rules is the
one documented ladder: defaults -> select -> class switches -> per-rule
-> ignore. Nineteen new rules (17 -> 36), one file each with true
positives and near-misses: Error - mismatched-labels,
duplicate-declaration (Semantics::duplicates(), additive),
undeclared-identifier (with a project; silent for macro text, included
fragments, hierarchical tails, any name another file mentions),
unknown-port, unknown-parameter; Warning - forbid-defparam,
invalid-system-task-function, truncated-numeric-literal,
undersized-binary-literal (safe fix), suspicious-semicolon,
packed-dimensions-range-ordering, module-port, module-parameter,
explicit-function-task-parameter-type, plusarg-assignment,
instance-shadowing, forbid-negative-array-dim, void-cast,
incomplete-assignment. Every false-positive class found on opentitan
closed with a named test; 3 383 tests / 48 binaries; corpus 814/820
and byte-identical (formatter untouched); vsix smoke OK.

docs/features/linter-expansion-1/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 17:49:03 -07:00
lucioandClaude Fable 5 4d70de1976 tools/guard.sh: kill a command's process tree past a memory or time cap; CLAUDE.md requires it for every suite, fuzzer and sweep
ci / checks (push) Successful in 54s
ci / corpus (push) Successful in 27s
A background test run consumed 100 GB and crashed the machine on
2026-09-03 (the process did not survive; the likely source was the
half-finished tolerant-parser recovery under the truncate-anywhere
fuzzers). macOS enforces no memory cap, so this poller is the cap:
8 GB / 30 min by default, TERM then KILL over the whole tree, exit 137
with the reason. Proved on a deliberate runaway allocator.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 17:47:41 -07:00
lucioandClaude Fable 5 63bbc23e37 Release 0.35.0 — format fences at statement level and inside class bodies
ci / checks (push) Successful in 54s
ci / corpus (push) Successful in 26s
release / build-and-publish (push) Successful in 5m16s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 03:46:24 -07:00
lucioandClaude Fable 5 a0ae5e5fa8 Format fences at statement level and inside class bodies
TODO section 31 (coverage_gaps M9, docs/topo.md 2.9-3).
fence::collect enters class bodies, functions, tasks and always/
initial/final blocks, and statement lists - begin/end, fork/join and
every compound body - through scan_stmt_scope/scan_nested_stmt on the
one scan_units both scope kinds share; stmt_docs/stmt_seq obey the two
swallowed-unit rules item_docs/item_seq had; fence regions merge into
range.rs's plan, which was load-bearing (a fenced statement has no
verbatim run behind it; proved by disabling it). A region opens only at
a line start (opens_line) - the rule the format-fences README has
stated since round 1 - so a fence after code on the same line is an
ordinary comment everywhere, which narrows one accidental item-level
shape (module m; // lucisv: off) and is ruled a drift fix. Deferred
with reasons: port lists, case-item label lists, same-line fences, a
property's locals. verify.rs, lucisv/src/lint.rs and
lucisv_server/src/lint.rs untouched.
Proof: 3 244 tests / 48 binaries, fences.cases 25 -> 38 with the
statement-level entry inverted, corpus 814/820 and 860 files byte-
identical to 0.34.0, opentitan: 4 of its 9 fenced files now keep their
fenced bytes and are fixed points, --check counts identical; 3 348
fence-injection trials with no new refusals.

docs/features/statement-fences/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 03:40:12 -07:00
lucioandClaude Fable 5 965c4ee25a TODO §33/§34 planned: linter expansion — severities, per-rule VS Code toggles, Error/Warning-class rules (wave 1); the Style class and per-rule options (wave 2)
ci / checks (push) Successful in 1m4s
ci / corpus (push) Successful in 29s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 02:57:31 -07:00
lucioandClaude Fable 5 999edd0203 Release 0.34.0 — rename macro-argument warnings, modport prototypes, unnamed DPI formals, --rules-doc
ci / checks (push) Successful in 1m3s
ci / corpus (push) Successful in 28s
release / build-and-publish (push) Successful in 5m53s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 02:48:12 -07:00
lucioandClaude Fable 5 1c6ed7e70d docs: topo — §2.9-5 and §2.9-18 struck; macro-word-census and interface-dpi-arms rows; FACTS 17 handshake
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 02:41:55 -07:00
lucio ef9ce984b7 Merge branch 'small-1' 2026-09-03 02:41:15 -07:00
lucioandClaude Fable 5 40a7b478c5 Rename warns about macro arguments it did not read; Scope at the crate root; lucisv check --rules-doc
TODO section 29; closes docs/topo.md 2.9-18 (server half) and 2.9-5;
the second half of coverage_gaps M12.
FileFacts::macro_words - the identifier-shaped words seen inside macro
invocations, directive lines and attributes (words::harvest_raw, which
shares its raw-token match with harvest so the two cannot drift) -
tag MW, FACTS_FORMAT 16 -> 17 (+3.1 percent corpus / +1.7 percent
opentitan store, measured). WorkspaceIndex::files_naming_in_macros is
files_mentioning's twin, and lucisv_server::rename appends one warning
per such file that lies outside the set rename_sources built: no new
rung, nothing read, 58 files in 186 microseconds for clk on opentitan.
Pinned by a three-file case and its no-double-warning control, run by
QA against the real server; QA also found an organic instance in
opentitan (cipher_crypt inside a DV_CHECK_FATAL) that 0.33.0 never
mentioned. vlog_refactor's Scope moves to the crate root (pure move,
counts identical). lucisv check --rules-doc prints rules_markdown(),
takes no files, is lint-only; the example binary is gone.
3 226 tests / 48 binaries, corpus 814/820, opentitan check byte-
identical to 0.33.0.

docs/features/macro-word-census/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 02:41:15 -07:00
lucio 5461179e18 Merge branch 'small-2'
ci / checks (push) Failing after 1m36s
ci / corpus (push) Successful in 43s
# Conflicts:
#	docs/coverage_gaps.md
2026-09-03 02:28:28 -07:00
lucioandClaude Fable 5 bff31bb80f docs: pre-existing docs pass found uncommitted in the tree — the three stale README claims closed, [lint] in README.md, docs site content and dist refresh
Committed by the lead as found on 2026-09-02 so lane merges can proceed;
content reviewed (README claims match delivered features).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 02:28:11 -07:00
lucioandClaude Fable 5 ee0faa2e18 Modport method prototypes, unnamed DPI formals, and the const ref comment gap
TODO section 30 (coverage_gaps M13, corrected).
A modport port may be a method prototype - import task drive(int x),
export function int get() - parsed by Parser::parse_tf_header, the
one header parse parse_function_decl and parse_task_decl now
destructure, printed by Fmt::tf_header, bound as Target::InScope
(IEEE 1800-2017 25.5: a modport names a member of its own interface)
with the formals declared in a scope of their own; one prototype per
import/export group, the LRM's comma list still a clean error
(recorded narrowing). A DPI import's formals may be unnamed
(35.5.5) behind parse_tf_ports(allow_unnamed), the empty-name
convention documented on TfArg::name, every other caller unchanged
and a non-DPI unnamed formal still an error at its position. M13's
const half was misfiled - const ref already parsed - but the probe
found the unowned gap in const /*c*/ ref, now TfArg::after_const.
Proof: 3 223 tests / 48 binaries, corpus 814/820, 4 807 corpus +
opentitan files byte-identical to 0.33.0 (zero population), QA's
adversarial probes and consumer audit of the possibly-empty names.

docs/features/interface-dpi-arms/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 02:27:24 -07:00
lucioandClaude Fable 5 15c78c1c32 TODO §32 planned: error recovery inside headers and lists (M10) — error elements, a list-local bracket-seeded sync, headers keep their node
ci / checks (push) Successful in 1m6s
ci / corpus (push) Successful in 30s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 22:19:01 -07:00
lucioandClaude Fable 5 132f6e9186 TODO §31 planned: format fences at statement level and inside class bodies (M9, §2.9-3)
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 22:17:28 -07:00
lucioandClaude Fable 5 d1821ff859 TODO §29/§30 planned: Scope promotion, macro-word census for rename warnings, --rules-doc; M13 modport prototypes, const arguments, unnamed DPI formals
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 22:15:53 -07:00
lucioandClaude Fable 5 3d0a0af893 docs: §28 closed — topo and CLAUDE.md name every decomposed module; post-round census (two files over 600: perf.rs 895, lexer.rs 762)
ci / checks (push) Successful in 56s
ci / corpus (push) Successful in 25s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 22:01:01 -07:00
lucio eb87a555b3 Merge branch 'decomp-semantic' 2026-09-02 21:55:55 -07:00
lucioandClaude Fable 5 b57ae35be4 Decomposition, lane D: vlog_semantic's bind.rs and workspace.rs, vlog_refactor's ports.rs and rename.rs become modules, a pure move
TODO section 28, lane D (the file-size rule in CLAUDE.md).
bind.rs (1 718 production lines) becomes bind/{mod, item, decl, class,
cover, stmt, sva, expr}.rs; workspace.rs (1 111) becomes workspace/
{mod, index, update, record, external}.rs with facts.rs and
FACTS_FORMAT untouched; ports.rs (1 391) becomes ports/{mod, find, add,
remove, propagate, list}.rs, one file per refactoring; rename.rs (760)
becomes rename/{mod, scope, warnings, tests}.rs. No function split, no
file over 600 production lines (largest add.rs at 432), every public
path unchanged (crate-root doc pages identical; only private-module
pages relocated). Carved by a range manifest that had to tile the
original byte for byte. Proof: per-binary test counts identical
(vlog_semantic 345 / 17, vlog_refactor 206 / 5, workspace 3 215 / 48),
corpus --stdout byte-identical, and the lucisv check finding lists
byte-identical between this build and the base over the corpus and the
opentitan hw tree - done by the dev and redone from scratch by QA.

docs/features/decomposition-semantic/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 21:55:55 -07:00
lucioandClaude Fable 5 96425f6cb9 docs: topo §1.3/§3.3 and the README architecture table name the decomposed modules (lanes A–C)
ci / checks (push) Successful in 1m5s
ci / corpus (push) Successful in 28s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 21:36:27 -07:00
lucio de6f04bf7d Merge branch 'decomp-server'
ci / checks (push) Successful in 1m3s
ci / corpus (push) Successful in 41s
2026-09-02 21:33:48 -07:00
lucioandClaude Fable 5 b96827c51d Decomposition, lane C: lucisv_server's server.rs and completion.rs become modules, a pure move
TODO section 28, lane C (the file-size rule in CLAUDE.md).
server.rs (2 559 production + 6 293 test lines) becomes server/{mod,
dispatch, client, index, notification, progress, diagnostics, batch,
formatting, large_file, semantic_tokens}.rs with the tests in
server/tests/ (16 files, one per former banner section, 15 shared
helpers hoisted into the harness); completion.rs (1 716 + 2 463)
becomes completion/{mod, member, module, tiers, word, site,
harness}.rs with each provider's tests beside it. answer_request (393)
and handle_notification (197) stay whole as the dispatch tables they
are; perf.rs stays whole because its one sentence has no and. Every
import elsewhere in the crate resolves through pub(crate) re-exports,
so main.rs, inline.rs, instantiate.rs, hover.rs, nav.rs and state.rs
are byte-identical. Proof: per-binary counts identical (1 435 / 85 / 3;
workspace 3 215 / 48), e2e and the vsix smoke green, a live LSP session
against opentitan answering byte-identically from this build and the
base, and a line-multiset + signature census (360/360, 188/188) done
by the dev and redone from scratch by QA.

docs/features/decomposition-server/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 21:33:48 -07:00
lucio a426c4dbfe Merge branch 'decomp-parser'
ci / checks (push) Successful in 1m4s
ci / corpus (push) Successful in 28s
# Conflicts:
#	TODO.md
2026-09-02 21:13:33 -07:00
lucioandClaude Fable 5 9b93f33ae3 Decomposition, lane A: vlog_parser's parser.rs and ast.rs become twenty-seven modules, a pure move
TODO section 28, lane A (the file-size rule in CLAUDE.md).
parser.rs (8 786 production + 5 044 test lines) becomes parser/{mod,
cursor, recover, directive, split, verbatim, item, module, decl, tf,
instance, stmt, keyword_stmt, expr, primary, class, covergroup,
assertion, sva}.rs with the tests regrouped into parser/tests/ (14
files, 309 tests, same names and bodies); ast.rs (3 313) becomes
ast/{mod, module, decl, stmt, expr, class, covergroup, sva}.rs, every
type re-exported so vlog_parser::ast::X is unchanged. Nothing over 800
production lines; the two keyword dispatch tables kept whole and
documented as such, parse_keyword_stmt in a file of its own. Carved by
a line-range manifest that had to concatenate back to the original
byte for byte before writing; 149 methods and 18 items pub(super) as
the compiler demanded. Proof: per-binary test counts identical
(workspace 3 215 / 48), 4 807 corpus + opentitan files byte-identical
to the v0.33.0 binary, cargo doc item list unchanged, and a multiset +
signature census done by the dev, redone by QA, re-run by the lead.

docs/features/decomposition-parser/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 21:13:32 -07:00
lucioandClaude Fable 5 35f0b8d371 Decomposition, lane B: vlog_formatter's format.rs becomes fifteen modules, a pure move
ci / checks (push) Successful in 1m1s
ci / corpus (push) Successful in 28s
TODO section 28, lane B (the file-size rule in CLAUDE.md).
format.rs (5 444 production lines) becomes format/{mod, verbatim,
comment, phrase, list, item, module, instance, decl, routine, class,
cover, sva, stmt, expr}.rs - no file over 600 production lines, the
three dispatch tables (stmt_kind, expr, prop_expr) left whole and
documented as such, sibling modules private with pub(super) entry
points, every public path unchanged (cargo doc item list identical).
Proof: per-binary test counts identical (31/1/5/6/2/22/208/0; workspace
3 215 / 48), 4 807 corpus + opentitan files byte-identical to the
v0.33.0 binary in stdout, exit code and stderr, and a line-multiset +
function-signature census showing only use lines, visibility keywords,
banners and doc comments differ - done by the dev and re-done from
scratch by QA. verify.rs untouched.

docs/features/decomposition-formatter/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 16:39:08 -07:00
277 changed files with 58466 additions and 43723 deletions

No files matched your search

+55
View File
@@ -4,6 +4,61 @@ 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
+25 -2
View File
@@ -58,8 +58,17 @@ Measured 2026-09-02 (production lines): `vlog_parser/src/parser.rs`
`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.
These are decomposition work (TODO §28), and every one of them is where
feature lanes collide, which is the other reason to split them.
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
@@ -119,6 +128,20 @@ Rules:
- Update `TODO.md`: check items your feature completes (leave the item
text intact).
## Runaway guard (never run a suite or sweep bare)
On 2026-09-03 a background test run consumed 100 GB and crashed the
machine. macOS enforces no memory cap, so the cap is ours:
`tools/guard.sh [-m GB] [-t SECONDS] -- <command>` kills a command's
process tree when its resident set or wall clock exceeds the limits
(defaults 8 GB / 30 min).
- **Every `cargo test`, every fuzzer, every corpus or opentitan sweep,
and every `lucisv`/`lucisv-server` run over a tree goes through
`tools/guard.sh`** — dev, QA and lead alike, foreground or background.
- A guard kill is a finding: report the command and the limit it hit;
do not raise the limit to make it pass.
## Parallel lanes (the 2-agent loop)
Up to **two dev/QA lanes may run concurrently** when — and only when —
Generated
+8 -8
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.33.0"
version = "0.36.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.33.0"
version = "0.36.0"
[[package]]
name = "lucisv_server"
version = "0.33.0"
version = "0.36.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.33.0"
version = "0.36.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.33.0"
version = "0.36.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -264,11 +264,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.33.0"
version = "0.36.0"
[[package]]
name = "vlog_refactor"
version = "0.33.0"
version = "0.36.0"
dependencies = [
"vlog_parser",
"vlog_semantic",
@@ -276,7 +276,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.33.0"
version = "0.36.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.33.0"
version = "0.36.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+154 -55
View File
@@ -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
@@ -167,11 +172,13 @@ would format — same walk, same `--exclude`, same `.gitignore` handling, same
`lucisv.toml` discovery.
```bash
lucisv check rtl/ # FILE:LINE:COL: message [rule-name]
lucisv check rtl/ # FILE:LINE:COL: severity: message [rule]
lucisv check --output-format json rtl/ # one JSON array, for editors and CI
lucisv check --select no-tabs rtl/ # only these rules (comma-separated)
lucisv check --ignore module-filename rtl/ # everything but these
lucisv check --select error rtl/ # a whole severity class, by name
lucisv check --fix rtl/ # apply the safe fixes, write files back
lucisv check --rules-doc # the generated reference for every rule
```
Exit codes are the frozen contract above: 0 clean (or everything fixed), 1
@@ -179,28 +186,84 @@ violations remain, 2 error. Unlike the formatter, `check` uses the
error-tolerant parser, so a file lucisv cannot fully parse is still linted for
what it can see.
| Rule | Fix | What it wants |
|---|---|---|
| `no-tabs` | safe | spaces, not tabs (a tab inside a string is left alone) |
| `no-trailing-whitespace` | safe | nothing but code before the newline |
| `case-missing-default` | — | every `case`/`casex`/`casez` has a `default` |
| `always-ff-non-blocking` | — | `<=` inside `always_ff` |
| `always-comb-blocking` | — | `=` inside `always_comb` |
| `explicit-parameter-storage-type` | — | `parameter int W = 8`, not `parameter W = 8` |
| `module-filename` | — | a one-module file is named after its module |
| `unused-waiver` | — | waivers that suppress nothing |
| `unused-signal` † | — | no net or variable nothing uses |
| `undriven-net` † | — | everything read is driven by something |
| `multiply-driven` † | — | one driver per variable |
### Severities
† 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
`cargo run -p vlog_linter --example rules_markdown` prints the generated
reference for every rule with its default.
Every rule is in one of three classes, and the class is the word that stands
in the diagnostic line, in the JSON `severity` field, and in the editor's
squiggle colour:
| Class | Means | Editor |
|---|---|---|
| `error` | would very likely fail to compile, elaborate or synthesize | red (LSP Error) |
| `warning` | compiles, and very likely does not mean what it says | yellow (LSP Warning) |
| `style` | correct, and reads badly | blue (LSP Information) |
A class name is accepted **wherever a rule name is** — on `--select`, on
`--ignore`, and in `select`/`ignore` under `[lint]` in `lucisv.toml`:
```bash
lucisv check --select error rtl/ # only the compile-breakers
lucisv check --ignore style rtl/ # everything but the naming rules
```
Every `error`-class rule follows one discipline: **silence beats a wrong
accusation**. Each of them goes quiet whenever the run cannot answer — a file
that did not fully parse, a module the project does not hold or holds twice, a
name a macro produces, a fragment written to be `` `include``d. That is what
makes an editor's red squiggle worth believing.
### The rules
| Rule | Severity | Fix | What it wants |
|---|---|---|---|
| `multiply-driven` † | error | — | one driver per variable |
| `wire-reg-mixup` | error | — | `logic`, not `reg`, in a `.sv` file |
| `mismatched-labels` | error | — | `end : name` names the block it closes |
| `duplicate-declaration` | error | — | each name declared once per scope |
| `undeclared-identifier` † | error | — | every name is declared somewhere in the project |
| `unknown-port` † | error | — | `.name(…)` is a port the module declares |
| `unknown-parameter` † | error | — | `#(.NAME(…))` is a parameter it declares |
| `always-ff-non-blocking` | warning | — | `<=` inside `always_ff` |
| `always-comb-blocking` | warning | — | `=` inside `always_comb` |
| `case-missing-default` | warning | — | every `case`/`casex`/`casez` has a `default` |
| `incomplete-assignment` | warning | — | an `always_comb` assigns on every path |
| `suspicious-semicolon` | warning | — | no `if (x);` / `for (…);` / `while (…);` |
| `forbid-defparam` | warning | — | override at the instantiation, not with `defparam` |
| `invalid-system-task-function` | warning | — | no `$random`, `$psprintf`, `$dist_*`, `$srandom` |
| `plusarg-assignment` | warning | — | `$value$plusargs`, not `$test$plusargs` |
| `truncated-numeric-literal` | warning | — | a sized literal fits its width |
| `undersized-binary-literal` | warning | safe | every bit of a sized binary literal is written |
| `packed-dimensions-range-ordering` | warning | — | a packed dimension is `[N-1:0]` |
| `forbid-negative-array-dim` | warning | — | no negative literal in a dimension |
| `module-port` | warning | — | more than one port is connected by name |
| `module-parameter` | warning | — | more than one parameter is overridden by name |
| `explicit-function-task-parameter-type` | warning | — | every tf argument has a storage type |
| `void-cast` | warning | — | `void'(…)` wraps a call |
| `instance-shadowing` | warning | — | no declaration hides an enclosing one |
| `undriven-net` † | warning | — | everything read is driven by something |
| `unused-signal` † | warning | — | no net or variable nothing uses |
| `no-tabs` | style | safe | spaces, not tabs (a tab inside a string is left alone) |
| `no-trailing-whitespace` | style | safe | nothing but code before the newline |
| `empty-item` | style | safe | no `;` standing where an item belongs |
| `explicit-parameter-storage-type` | style | — | `parameter int W = 8`, not `parameter W = 8` |
| `module-filename` | style | — | a one-module file is named after its module |
| `enum-name-style` | style | — | `lower_snake_case` ending `_e`/`_t` |
| `struct-union-name-style` | style | — | `lower_snake_case` ending `_t` |
| `parameter-name-style` | style | — | `CamelCase` or `ALL_CAPS` |
| `module-name-style` | style | — | `lower_snake_case` (off by default) |
| `unused-waiver` | style | — | waivers that suppress nothing |
† 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 rules read the file's *symbol table* and ask the project about
names, not just the file's 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` and
`docs/features/linter-expansion-1/README.md`.
`lucisv check --rules-doc` prints the whole reference — every rule, its class,
its default, its fix and the paragraph saying why it exists — generated from
the registry, so it can never be out of date.
Fixes follow ruff's applicability model: `--fix` applies *safe* fixes (those
that cannot change what the code means), `--unsafe-fixes` widens that — no
@@ -233,7 +296,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 +360,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 +375,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 +478,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 +508,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 +549,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 +576,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 +667,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 +692,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.
+665 -6
View File
@@ -3002,14 +3002,673 @@ lane a subsection with its module map, line-range table and pinned
counts), `docs/topo.md` §3.1 primary-home matrix updated to the new
module names, `README.md`'s architecture section updated. Runs AFTER
§27 (every lane touches its files).
- [ ] Lane A `vlog_parser` — parser/ and ast/ module maps; tests moved;
- [x] Lane A `vlog_parser` — parser/ and ast/ module maps; tests moved;
counts pinned; byte-identity proven
- [ ] Lane B `vlog_formatter` — format/ module map; counts; byte-identity
- [ ] Lane C `lucisv_server` — server/ and completion/ module maps;
- [x] Lane B `vlog_formatter` — format/ module map; counts; byte-identity
- [x] Lane C `lucisv_server` — server/ and completion/ module maps;
tests out of server.rs first; counts; e2e unchanged; vsix smoke
- [ ] Lane D `vlog_semantic` + `vlog_refactor`
- [ ] Docs: decomposition README, topo §3.1, README.md architecture
- [ ] QA per lane: `cargo test` counts equal to the lane's baseline,
- [x] Lane D `vlog_semantic` + `vlog_refactor`
- [x] Docs: decomposition README (one per lane: decomposition-{parser,
formatter,server,semantic}), topo §1.3/§3.3, README.md architecture
- [x] QA per lane: `cargo test` counts equal to the lane's baseline,
corpus + opentitan `--stdout` byte-identical (0 differing), no
public path changed (`cargo doc` item list diffed against the
baseline), longest-function census reported before/after
## 29. Small items, round 1 (planned 2026-09-02) — `Scope` promotion, the macro-word census for rename warnings (§2.9-18 server half), `lucisv check --rules-doc` (§2.9-5, M12's second half)
Three independent items in one lane; disjoint from §30's files. Dev
Opus 5, QA Sonnet 5. Feature README: `docs/features/macro-word-census/
README.md` (Goal names all three; Work log per item).
**29.1 `vlog_refactor::rename::scope` → crate root.** `rename/scope.rs`
(69 production lines) holds `Scope`/`Analysis`/`display` — the in-scope
files, the index built from them, the analyses computed so far — and its
own `//!` says nothing in it is rename-specific; `ports/`, `references`
and `instantiate` reach it through `rename`. Pure move: `git mv
crates/vlog_refactor/src/rename/scope.rs crates/vlog_refactor/src/scope.rs`;
`lib.rs` gains `mod scope;` (crate-private); `rename/mod.rs` keeps
`pub(crate) use crate::scope::{display, Scope};` so every in-crate path
(`crate::rename::Scope`, `super::scope::…` in `warnings.rs`) still
resolves — change the importers to `crate::scope::` where you touch
them anyway and leave the re-export for the rest; the `//!` loses its
"it lives under `rename` because …" sentence. Proof: `cargo test -p
vlog_refactor` counts identical (86/5/52/63/0), workspace green, no
public path changes (`Scope` is `pub(crate)`).
**29.2 Macro-word census, and the rename warning it enables.** Today
`FileFacts::words` (§24) is one sorted list of every identifier-shaped
word in a file, plain tokens and raw text (macro invocations, directive
lines, attributes) folded together, so it cannot say *where* a word was
seen. Rename's `macro_use_warnings` (engine, pinned in §27 by
`a_file_whose_only_relationship_to_the_name_is_a_macro_argument_is_warned_about`)
only runs over the files `Workspace::rename_sources` hands the engine,
and a file whose only relationship to the name is a macro argument is
in none of its rungs — the lead's ruling in `docs/topo.md` §2.9-18: no
`files_mentioning` rung (untagged, so it would re-read every file
spelling `clk` and bring back the 2.5–3.0 s `prepareRename` cost), but a
separate census the server can *warn from without reading*. Plan:
(a) `vlog_semantic::words`: alongside `harvest`, a `harvest_raw(tokens)
-> Vec<String>` (sorted, deduped) of the words `raw_words` finds inside
macro-invocation `Ident`s, `Directive` and `Attribute` tokens only —
factor the raw-token match out of `harvest` so the two cannot drift;
pin `harvest_raw ⊆ harvest` and that a word seen only as a plain
identifier is absent from it. (b) `FileFacts::macro_words: Vec<String>`
written and read beside `words` (tag `M`), `FACTS_FORMAT` 16 → 17 with
the reason in the doc comment (a 0.33.0 store has no `M` records and
would answer "no file names it in a macro"), `fingerprint` unchanged
(the census is derived from the same text). (c) `WorkspaceIndex::
files_naming_in_macros(name) -> impl Iterator<Item = FileId>` by binary
search, the twin of `files_mentioning`; `update_file`/`remove_file`/
`absorb` carry the field the way they carry `words` (they do, if it
lives in `FileFacts`; say so). (d) `lucisv_server/src/rename.rs`: after
the engine returns `(edit, warnings)`, append one warning per file in
`files_naming_in_macros(old_name)` that is **not** among the paths the
engine was handed (`rename_sources` result) and not an open buffer:
"`old` also appears inside a macro invocation in <path>, which this
rename did not read; check it by hand — a macro argument cannot be
edited." Same for `prepareRename`? No — a prepare answers a range, not
warnings. (e) Pins: `vlog_semantic` unit tests for `harvest_raw` and the
codec round-trip (FACTS 17 record with and without `M`); a server test
with three files — `sub.sv` declares `wire sig`, `top.sv` uses `u.sig`,
`far.svh` contains only `` `uvm_info("x", $sformatf("%0d", sig), UVM_LOW) ``
and nothing else naming `sub` — asserting the rename edits `sub.sv` and
`top.sv`, that `far.svh` is not in `rename_sources`, and that the
returned warnings name `far.svh`; a control where `far.svh` also
instantiates `sub` (then it IS a source and the engine's own warning
appears exactly once — no double warning). (f) `docs/topo.md` §2.9-18
struck by the lead; the refactor-rename and semantic-lints-on READMEs
amended; index-persistence README notes format 17.
**29.3 `lucisv check --rules-doc`.** `vlog_linter::rules_markdown()` has
existed since lint-rules-2 with only an example binary
(`crates/vlog_linter/examples/rules_markdown.rs`) to print it. Plan:
`args.rs` — `Options::rules_doc: bool`, parsed from `--rules-doc`,
listed in `check_flag_scopes` as lint-only, documented in the usage
text under `lucisv check`; `main.rs::run_check` — when set, print
`rules_markdown()` to stdout and return exit 0 before `select_rules`
and before any path is gathered (paths given alongside are an error:
"--rules-doc takes no files"); a `crates/lucisv/tests/` case running
the binary with `--rules-doc` and asserting the first line and that
every registered rule name appears once; if `docs/lint-rules.md` (or
the docs-site rules page) is checked in, a drift test that it equals
the generated text, and regenerate it in this round; the example
binary's doc comment updated (or the example removed — the lead
prefers removed, the flag is the tool now). `docs/topo.md` §2.9-5
struck by the lead; the lint-rules-2 README's handshake ticked.
Files: crates/vlog_refactor/src/{lib.rs, scope.rs (moved),
rename/mod.rs, rename/warnings.rs, ports/*.rs, references.rs,
instantiate.rs (imports only)}, crates/vlog_semantic/src/{words.rs,
facts.rs, workspace/{mod,index,update,record}.rs} + tests,
crates/lucisv_server/src/rename.rs (+ state.rs only if
`rename_sources` must expose its path set — prefer returning it from
the existing function rather than a new rung) + tests/e2e.rs,
crates/lucisv/src/{args.rs, main.rs} + tests, crates/vlog_linter/
examples/rules_markdown.rs (removed), docs/lint-rules.md (regenerated
if present), docs/features/macro-word-census/README.md (new),
amendments in refactor-rename / semantic-lints-on / index-persistence /
lint-rules-2 READMEs, TODO §29. Runs in parallel with §30 (disjoint
files; topo: §29 touches the FACTS handshake, §30 the AST — no shared
edge).
- [x] 29.1 `Scope` at the crate root, counts identical
- [x] 29.2 `harvest_raw` + `FileFacts::macro_words` (FACTS 17) +
`files_naming_in_macros` + the server warning; the three-file pin
and its control — the group's tag is `MW`, not `M` (already the
member group); no new `Workspace` rung (`rename_sources` returns
the path set the server subtracts)
- [x] 29.3 `--rules-doc`; usage text; tests; example removed;
`docs/lint-rules.md` regenerated if present — it is not present,
and the docs-site rules page is hand-written prose, not generated
text, so there was nothing to regenerate and no drift test
- [x] Gates: fmt/clippy/`cargo test --workspace` (3 226/0/42 over 48
binaries, from 3 215/0/40); corpus gate 814/820, the same six;
store measurement +123 402 bytes (+3.11 %) on the corpus and
+743 873 (+1.66 %) on opentitan; opentitan `lucisv check` sweep
byte-identical, working tree untouched
- [ ] QA: rename of `clk` in an opentitan IP with the server, timing
before/after (must not regress; the warning list must name only
files outside the source set), the pins re-derived
## 30. Small items, round 2 (planned 2026-09-02) — M13: modport method prototypes, `const` tf arguments, unnamed DPI formals
Three grammar arms `docs/coverage_gaps.md` M13 lists as "each a small
grammar arm"; zero corpus population, so the value is that an interface
or DPI file written by the book opens without an error node. Dev Opus 5,
QA Sonnet 5. Feature README: `docs/features/interface-dpi-arms/README.md`.
**30.1 Modport method prototypes** (IEEE 1800-2017 §25.5.4,
`modport_tf_port ::= method_prototype | tf_identifier`). Today
`parse_modport` (`parser/module.rs`) reads `import`/`export` followed
by a name list; `import task drive(int x)` errors at `task`. Plan:
(a) `ast/module.rs`: `ModportPort` gains `prototype: Option<Box<
TfPrototype>>` where `TfPrototype { kind: TfKind (Function|Task), ret:
Option<DataType>, name: Name, ports: TfPorts, after_kw/before_name/
before_args comment slots }` — one struct, since a modport prototype is
a header with no body; `names` is empty when `prototype` is `Some`.
(b) `parser/tf.rs`: factor the header parse — keyword, lifetime
qualifiers, return type, name, `parse_tf_ports` — out of
`parse_function_decl`/`parse_task_decl` into `parse_tf_header(kind) ->
PResult<TfPrototype>`-shaped code both call (a pure refactor inside
the file; counts unchanged), and call it from `parse_modport` when the
token after `import`/`export` is `task` or `function`; the prototype
ends at the `,`/`)` of the modport list, never at `;`. Comments in
every new gap get an owner (the comment-slots rule); a `/*c*/` before
`task`, before the name, inside `()` are the cases. (c) `format/
module.rs`: print `import task name(args)` through the same header
printer `routine.rs` uses (factor it the same way), one prototype per
list element, alignment untouched. (d) `bind/item.rs`: the prototype's
name is a use (`Target::Lexical`, resolving to the interface's task or
function) and its formals are declared in a `ScopeKind::Block` opened
for the prototype so they neither leak nor go unbound; types bind as
types. (e) `tests/spans.rs` arm; parser tests; `interfaces.cases`
entries (import and export, task and function, with and without
formals, mixed with `input` groups, comments); a semantic test that
hover on `drive` in the prototype lands on the interface's task.
**30.2 `const` task/function arguments.** `parse_tf_ports` already
accepts `const ref` (tf.rs:177, the corpus shape). Verify with a probe
whether anything M13 meant is still missing — `const ref int q[$]`
formats today; a bare `const` direction is not legal (LRM 13.5.2 only
has `const ref`) — and close the item with a pinned case rather than
code, unless the probe finds a real gap (then fix it in the same arm).
Correct the M13 row in `docs/coverage_gaps.md` either way.
**30.3 Unnamed DPI formals** (§35.5.5: `import "DPI-C" function int
f(int, chandle);` — a formal may omit its name in a DPI import
prototype only). Today `parse_tf_ports` does `expect_name` and errors
at `,`. Plan: (a) `parse_tf_ports(allow_unnamed: bool)` — the DPI path
(`parse_dpi_import` → `parse_function_decl(Some(dpi))`/`parse_task_decl`)
passes `true`, every other caller `false`; when allowed and the token
after the type is `,` or `)`, the formal has **no name**. (b) AST: keep
`TfArg::name: Name` and use the crate's existing empty-name convention
(`foreach (arr[, j])`, `declare` ignores an empty name) — `name.text`
empty, `name_span` empty — rather than an `Option` that would touch
every consumer (formatter, binder, ports refactoring, signature help);
document it on the field. (c) Formatter: an unnamed formal prints its
direction and type only; `tf_args` alignment treats the missing name
as zero width. (d) Binder: `declare` already ignores empty names — pin
it. (e) Signature help (`lucisv_server/src/signature.rs`) shows the
type alone for such a parameter — check and pin. (f) Cases in
`dpi.cases` (or the file DPI imports live in): `int`, `chandle`,
`logic [7:0]`, a mix of named and unnamed, `input int` unnamed, and
the negative: an unnamed formal in a non-DPI function is still an
error naming the position.
Files: crates/vlog_parser/src/{ast/module.rs, ast/decl.rs (TfArg doc),
parser/module.rs, parser/tf.rs, parser/item.rs}, tests/spans.rs +
parser tests, crates/vlog_formatter/src/format/{module.rs, routine.rs},
tests/cases/{interfaces.cases, dpi.cases or where DPI lives},
crates/vlog_semantic/src/bind/item.rs + tests, crates/lucisv_server/
src/signature.rs (check + pin only) + tests, docs/coverage_gaps.md
(M13 row), docs/features/interface-dpi-arms/README.md (new),
amendments in interfaces / dpi-export READMEs, TODO §30. Runs in
parallel with §29.
- [x] 30.1 modport prototypes end to end (parse, format, bind, spans,
hover pin) — `TfPrototype` on `ModportPort`, one shared header
parse (`parse_tf_header`) and one shared header printer
(`Fmt::tf_header`); the name resolves with `Target::InScope`, not
`Lexical` (reason in the feature README). One prototype per
`import`/`export` group, not the LRM's list.
- [x] 30.2 `const` arguments verified and pinned (or fixed), M13 row
corrected — `const ref` already worked; the probe found one real
gap, a comment *between* `const` and `ref`, now `TfArg::after_const`
- [x] 30.3 unnamed DPI formals (parse behind the DPI flag, format,
bind, signature help pin, negative pin) — signature help turned
out not to apply (it answers only for instantiation lists), so
that pin is a recorded finding rather than a test
- [x] Gates: fmt/clippy/`cargo test --workspace`; `cargo test -p
vlog_formatter`; corpus 814/820 byte-identical to 0.33.0 (zero
population, so nothing may move); opentitan read-only sweep
unchanged — 3 223/48 tests, 0 clippy warnings, 814/820 with the
same six failures, 0 diffs over 860 corpus and 3 947 opentitan
files
- [ ] QA: hand-written interface + DPI files in every listed shape,
idempotent, comments kept; the negative pin; sweep unchanged
## 31. Format fences at statement level and inside class bodies (planned 2026-09-02) — M9, §2.9-3
Mapped (read-only exploration, file:line in the feature README to be):
fences are an exact-match `//` comment (`verilog_format: off|on`,
`lucisv: off|on`, `fence.rs::fence_of`) turned into `Region { fence,
start, end }` by `fence::collect`, a **comment scan over item scopes**
(`scan_scope` walks one `Vec<Item>` plus its `dangling`; `scan_nested`
enters Module/Package/GenerateRegion/GenIf/GenFor/GenCase and nothing
else — `_ => {}` is why a fence inside a class body, an `always`
block, a case item or a port list is inert). The formatter asks three
questions of the list (`verbatim.rs`: `slot`, `is_verbatim`,
`opens_at`) and splices `Doc::Verbatim(src[start..end])`, a column-0,
break-forcing leaf that must follow a line break; `region_at` is a
`partition_point` binary search that needs the list sorted by both
ends. `protected_regions` (the `--fix`/quick-fix backstop) is already
the union with a line scan, so it sees class-body and statement fences
today — this round closes that asymmetry, it does not open one. The
corpus holds zero fences (any output movement is a bug). Dev Opus 5,
QA Sonnet 5. Feature README: `docs/features/statement-fences/README.md`.
**31.1 Class bodies — one arm.** `ClassDecl` holds `items: Vec<Item>` +
`dangling` and the formatter already prints them through the
fence-aware `item_seq`/`dangling`; add `ItemKind::Class(c) =>
scan_scope(src, &c.items, &c.dangling, out)` in `scan_nested` (and the
same for any other item that carries an item list and is printed by
`item_seq` — check `Interface`/`Program`/`Checker`, say which). Cases:
a fence around one class item, around a nested class, an unmatched
`off` running to `endclass` only (not past it), comments before the
`off`. Closes §2.9-3; the classes README's handshake ticked; the QA-log
probe in that README re-run.
**31.2 Statement lists.** A `Stmt` is fence-ready (`meta.leading` with
spans; `span` = code extent, comments out). Add `scan_stmt_scope(src,
stmts, dangling, out)` mirroring `scan_scope` (leading comments as
units, `scope_end` = last statement's `span.end` extended by
`with_trailing_comments`, an unmatched `off` runs to the list's end
only), and `scan_nested_stmt` entering `StmtKind::{Block, ForkJoin,
If (both arms), For, Foreach, While, DoWhile, Forever, Repeat, Case
(each item's body), Timing/Wait bodies}` — **statement lists only**:
`begin … end`, `fork … join*`, function/task bodies, `initial`/`always`
bodies reached from the item (`ItemKind::{Always, Initial, Final,
Function, Task}` and a class method); a bodyless `if (x) y = 1;` is not
a scope, for the reason `scan_gen_block` refuses `!is_block`. Merge
statement regions into `collect`'s output through the same global sort
+ "drop a region whose `fence` precedes the previous `end`" filter so
`region_at`'s precondition holds; `range.rs` manufactures regions into
the same list — re-check its planner with a statement region inside a
selected range (a fence outranks a range, as today). Formatter:
`stmt_seq` gains `item_seq`'s two rules (a swallowed statement emits
nothing and contributes no separator); `Fmt::stmt` checks `opens_at`/
`is_verbatim` before `with_meta` and drops the dangling `HardLine` the
way `item_docs` does; `block_doc`'s `dangling` already goes through the
fence-aware path. Idempotency gate: a region may only open at a
`line_start` (a fence written after `begin` on the same line is an
ordinary comment — pin it); comment preservation: a statement scope's
end includes the last statement's trailing comment and never leaks past
the enclosing `end`/`endfunction`/`join`.
**31.3 Not this round, written down**: port lists and case-item label
lists (elements printed inside a `Group` mid-line; `Doc::Verbatim` is
column-0 and `Doc::Inline` carries no region indentation — a different
primitive), same-line fences (trailing trivia; unblocked since `Meta.
trailing` carries a span, still deferred). The cross-level pairing rule
stays: an item-level `off` closed by a statement-level `on` is an
unmatched `off` today and becomes a stray `on` in another scope —
behaviour unchanged, the fences.cases entry "a statement-level fence has
no effect this round" inverts, and `docs/features/format-fences/
README.md` §"Out of scope" plus `README.md` "Turning the formatter off"
are rewritten in the same change.
Proof: the `tests/fences.rs` triple (byte-exact + `verify_equivalence`
+ second-pass fixed point) for every new scope; corrupted-region attack
pairs for a statement region and a class-body region (the five in
`fences.rs` as the model; `verify.rs` untouched — a region is source
bytes, equivalence holds by construction); `protected_regions` and
`is_protected` signatures untouched so `lucisv/src/lint.rs` and
`lucisv_server/src/lint.rs` are byte-identical; corpus 814/820 and
byte-identical to 0.33.0 (zero fences); opentitan sweep unchanged
(grep its fence count first; if any exist inside statements, their
files may now move — list them).
Files: crates/vlog_formatter/src/{fence.rs, format/{stmt.rs, item.rs,
verbatim.rs, class.rs}, range.rs (planner check)}, tests/{fences.rs,
cases/fences.cases, ranges.rs}, docs/features/statement-fences/README.md
(new), amendments in format-fences / classes / shared-fence-filter
READMEs, README.md "Turning the formatter off", docs/topo.md §2.9-3
struck (lead), TODO §31. Runs after §29/§30 merge (format/ collides
with §30's routine.rs only at merge; disjoint files otherwise — the
lead may start it in parallel if §30's files are settled).
- [x] 31.1 class bodies (+ any other item-list carrier), cases, §2.9-3 —
`Interface`/`Program` are `ItemKind::Module` and were already scanned,
there is no `Checker` node, and `PropSeqDecl.locals` is deferred (it is
the one `Vec<Item>` not printed through `item_seq`)
- [x] 31.2 statement lists: scan, merge, `stmt_seq`/`stmt` rules,
line-start gate, trailing-comment end, range planner re-check — the
planner now merges `collect`'s fences into `Plan.regions`, without
which `--lines` would have reformatted a fenced statement
- [x] 31.3 docs rewritten (format-fences README, README.md, the
inverted case), deferrals listed with reasons
- [x] Attack pairs + the fences.rs triple per scope; verify.rs untouched
- [x] Gates: fmt/clippy/`cargo test --workspace` 3 244/0/42 (was
3 234/0/42); corpus 814/820, 860 files byte-identical to the 0.34.0
binary; opentitan census 9 fenced files of 3 947 — 4 moved, each
keeping its own fenced bytes, `--check` counts unchanged
- [ ] QA: fences in every statement scope listed and in the three
deferred places (must be inert, never corrupt); an `off` with no
`on` in each scope (runs to the scope end only); nested fences;
`--lines` over a fenced statement; `--fix` still declines inside
## 32. Error recovery inside headers and lists (planned 2026-09-02) — M10
Mapped (read-only exploration; file:line to be carried into the feature
README): tolerant parsing is one grammar with a `tolerant` flag; the
only recovery is `recover` (`parser/recover.rs`: push the diagnostic,
`skip_to_sync` to the next depth-0 `;` or a sync keyword, slice the
skipped source into `ItemKind::Error`/`StmtKind::Error`) at eleven
list sites (file scope, module/package/generate/class bodies, tf
bodies, `begin`/`fork` lists, case items). **Two facts make headers the
damage:** (1) an error anywhere inside a header escapes to the nearest
enclosing *item/statement list*, so a typo in a port list, parameter
list or tf-port list destroys the whole `Module`/`FunctionDecl` — the
body then re-parses at the wrong scope and the orphaned `endmodule`/
`endfunction` is a second (third) error; (2) `skip_to_sync`'s bracket
counter starts at zero at the failure point, so brackets consumed
before the failure are invisible and the skip stops at a `;` inside
`for (…; …; …)` or runs past a `)`. QA's shape: `module m #(parameter
W = , parameter X = 4) (input a); wire ok; endmodule` → three items
(error, a top-level `wire ok;`, an error for `endmodule`), 2
diagnostics. The server publishes one diagnostic per `ParseDiagnostic`
with no suppression; document symbols, scoped completion, inlay, lens,
hierarchy and linked editing all read `doc.tree.items`/`semantics` and
lose the module. Nothing asserts today that symbols above the cursor
survive a header typo. Dev Opus 5, QA Sonnet 5. Feature README:
`docs/features/header-recovery/README.md`.
**32.1 A third error shape, not a third mechanism.** An `Error(RawText)`
*element* in the list element types: `AnsiPort`/`NonAnsiPort` (or the
port-list item enum), `ParamPort`, `Connection` (named and ordered),
`TfArg` — one new arm each, so every exhaustive match (formatter,
`bind/`, `spans.rs`) must decide; the formatter prints it through
`raw_text` (unreachable from `format_source`, as `ItemKind::Error` is),
`bind/` ignores it (mirroring `bind/item.rs`'s `Error` arm), the linter
treats it as an opaque span (mirroring `signals.rs`). Pre-agreed
cross-crate one-liners; nothing else in those crates changes.
**32.2 One shared helper, `element_or_recover`**, on the
`item_or_recover` model: mark, call the element parser, on `Err` in
tolerant mode record the diagnostic, skip to a **list-local** sync set
and wrap the skipped source. The set: `,` (not consumed — it separates
the next element), the list's own closer `)` (not consumed), `;` (not
consumed — the header was abandoned), and a **line change** (the next
token's line differs from the failing token's — the one line-based
rule, and the one that pays for `input logic a, inp⏎`). Bracket-
balanced like `skip_to_sync`, with the counter **seeded from the list's
own open bracket** — the root-cause fix. Strict mode is untouched
(`Err` propagates as today).
**32.3 Headers keep their node.** `parse_port_list`,
`parse_param_port_list`, `parse_tf_ports` and `parse_connections` cannot
fail in tolerant mode: they return the elements that were typed plus
error elements, and the caller closes the list (`expect_closer`-style:
a missing `)` is a diagnostic, not a failure). `parse_module`,
`parse_function_decl`/`parse_task_decl` and `parse_instantiation`
therefore always return their node with the name, the typed elements
and the body, so the body binds in the right scope and there is no
orphaned closer.
**32.4 `for` headers and `if`/`while`/`case` conditions** get the
smallest version: on a failure inside the parentheses, skip to the
matching `)` with the seeded counter (the header's inner `;` are
invisible) and substitute `ExprKind::Error(RawText)` (new arm; formatter
`raw_inline`, binder ignores, `spans.rs` arm); the statement survives
with its body. Kills the documented second diagnostic of the `for`
case (error-recovery README §"known shapes").
**32.5 Pins.** In `crates/vlog_parser/tests/error_recovery.rs`, one test
per shape with exact counts: the QA source above → 1 diagnostic, 1
item, `ItemKind::Module` named `m` holding `wire ok;`, `param_ports`
of length 2 with `[0]` an error element; `module m (input logic a,
inp⏎ output b);` (line-change sync, `b` survives); `#(parameter W = 8,`
at end of file; `for (int i = 0; i <` inside `begin…end` (1 diagnostic,
the `for` a `StmtKind::For` with an `Error` condition, the next
statement intact); `sub u (.a(x), .b(` followed by `wire w;` (the
existing pin inverts: `wire w;` is now a sibling item); `function int
f(input int a,` followed by a body and `endfunction` (1 diagnostic, the
function and the module both intact); `if (a &&` with a then-branch.
`tolerant_parse_equals_strict_parse_on_valid_sources` (550 sources)
stays green unchanged — the regression net for "no cost on a clean
file"; every new branch sits behind `self.tolerant` on the error path.
Extend `error_recovery.rs`'s `walk_item`/`walk_stmt` and `spans.rs`'s
nesting walker for the new shapes (do not add a second walker), so
span nesting and `source[span] == text` hold for them automatically.
Fuzz: the existing truncate-anywhere / delete-any-character tests must
stay green (no panic, no infinite loop — the list-local skip must
always advance).
**32.6 The user-visible contract, pinned in the server.** In
`crates/lucisv_server`: a test that opens a buffer with a broken port
list and asserts `document_symbols` still lists the module and its
already-typed ports, that `visible_symbols` at a cursor inside the
broken list still answers from the module's scope (completion), that
exactly one diagnostic is published, and that `pairs::missing_end_
diagnostics` adds nothing for it. Re-check the three validity probes
that assert `parse_source_tolerant(probe).1.is_empty()`
(`inline.rs`, `templates.rs`, `completion/tiers.rs`): they must keep
their verdicts (a probe that is broken must still produce a
diagnostic — recovery does not mean silence).
**32.7 Docs.** The error-recovery README: Assumptions gain the header
sentence its Review claims is there (the discrepancy the exploration
found); Status/TODO's "Not done" line inverts; the "known shapes" table
updated. `docs/coverage_gaps.md` M10 row closed. Measure: `perf.rs`'s
`parse_tolerant` harness before/after on the largest corpus file (must
be within noise), and the diagnostics count over the corpus with every
file truncated at its midpoint (a census: before/after totals; expect a
drop).
Files: crates/vlog_parser/src/{ast/{module,decl,expr,stmt}.rs (the
error arms), parser/{recover.rs, module.rs, tf.rs, instance.rs,
stmt.rs, keyword_stmt.rs, expr.rs}}, tests/{error_recovery.rs,
spans.rs}, crates/vlog_formatter/src/format/{module,instance,routine,
expr,stmt}.rs (one arm each), crates/vlog_semantic/src/bind/{item,
decl,expr,stmt}.rs (ignore arms), crates/vlog_linter/src/{signals.rs,
visit.rs, context.rs} (opaque-span arms, if the match is exhaustive),
crates/lucisv_server/src/{symbols.rs, diagnostics.rs}/tests (pins
only), crates/lucisv_server/src/perf.rs (measurement only), docs/
features/header-recovery/README.md (new), amendments in error-recovery
README, docs/coverage_gaps.md M10, TODO §32. Runs after §31 (parser +
formatter collide with §30's tf.rs/module.rs at merge; sequential).
- [ ] 32.1 error elements in the four list types + `ExprKind::Error`;
cross-crate arms pre-agreed
- [ ] 32.2 `element_or_recover` with the list-local, bracket-seeded
sync set (`,` `)` `;` line change)
- [ ] 32.3 headers keep their node (port, param, tf-port, connection
lists infallible in tolerant mode; closers via `expect_closer`)
- [ ] 32.4 `for`/`if`/`while`/`case` conditions recover inside the
parentheses
- [ ] 32.5 parser pins per shape with exact counts; walkers extended;
550-source equality and the fuzzers green
- [ ] 32.6 server pins: symbols survive, completion scope survives, one
diagnostic, validity probes unchanged
- [ ] 32.7 docs + measurements (parse_tolerant timing, truncated-corpus
diagnostic census)
- [ ] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
byte-identical (strict path untouched); opentitan read-only sweep
unchanged
- [ ] QA: type each of the (a)–(f) shapes into the real server against
an opentitan file and read the published diagnostics and the
outline; the fuzzers re-run; strict-mode parity re-derived
## 33. Linter expansion, wave 1 (planned 2026-09-02) — severities, per-rule editor toggles, and the Error/Warning-class rules
Owner's ask: expand the linter toward what Verible's linter covers (62
rules, https://chipsalliance.github.io/verible/lint.html), expose every
rule in VS Code as a toggle grouped by severity so a user can enable or
disable rules one at a time or a whole severity at once, and put the
style rules and the "would likely fail to compile or synthesize" rules
first. Today: 17 rules, no severity notion (`Rule` has `name`,
`summary`, `doc`, `default_on`, `needs_workspace`, `fix`, `check`), every
editor diagnostic is `WARNING`, the editor surface is
`lucisv.lint.select`/`ignore` lists. Dev Opus 5, QA Sonnet 5. Feature
README: `docs/features/linter-expansion-1/README.md`. Runs in a
worktree in parallel with §31 (fences: `vlog_formatter`, README.md's
"Turning the formatter off" section only); this lane owns
`vlog_linter`, `lucisv/src/lint.rs` + args, `lucisv_server/src/
{settings,lint}.rs`, `editors/vscode/{package.json,README.md}`, README.md's
"Linting" section, `docs/site/.../reference/rules.md`.
**33.0 Severity, end to end.**
(a) `vlog_linter`: `pub enum Severity { Error, Warning, Style }` with
`as_str` (`error`/`warning`/`style`) and `Rule::severity(&self) ->
Severity` (no default — every rule states it; the reason goes in the
rule's `doc`). Assignments for the 17: **Error** — `multiply-driven`
(two procedural drivers of one variable is an elaboration error in
SystemVerilog), `wire-reg-mixup` (a procedural assignment to a net is a
compile error); **Warning** — `always-comb-blocking`,
`always-ff-non-blocking`, `case-missing-default`, `undriven-net`,
`unused-signal`; **Style** — `empty-item`, `enum-name-style`,
`explicit-parameter-storage-type`, `module-filename`,
`module-name-style`, `no-tabs`, `no-trailing-whitespace`,
`parameter-name-style`, `struct-union-name-style`, `unused-waiver`.
`Violation` carries the severity (set by the runner from the rule, not
by each rule). (b) `select_rules(select, ignore, …)` accepts a severity
name wherever a rule name is accepted — `--select style`, `--ignore
warning`, `[lint] ignore = ["style"]` — expanding to every rule of that
severity; an unknown name still fails naming the file. (c) CLI text
output becomes `FILE:LINE:COL: error|warning|style: message [rule]`
(the severity word is new; pin the old tests to the new shape); JSON
gains `"severity"`. Exit codes unchanged. (d) Editor:
`DiagnosticSeverity::ERROR` / `WARNING` / `INFORMATION` respectively;
`source` unchanged. (e) `--rules-doc` and `rules_markdown()`: a
Severity column, sections grouped by severity, the intro explaining the
three words.
**33.1 Editor toggles, generated from the registry.** In
`editors/vscode/package.json`: three master switches
`lucisv.lint.severity.error`, `.warning`, `.style` (boolean, default
true, `order` 10/11/12, description naming what each class means), and
one boolean per rule `lucisv.lint.rules.<rule-name>` (default = the
rule's default; `markdownDescription` = `**severity** — summary`; the
project-only rules say "on where lucisv can see the project"; `order`
sorted by severity then name so the Settings UI groups them; the
existing `lucisv.lint.select`/`ignore` stay, documented as the
power-user spelling). Generated, not hand-written: a
`crates/vlog_linter/examples/vscode_lint_settings.rs` (or a `tools/`
script driving `cargo run --example`) that prints the JSON fragment,
and a `crates/lucisv_server` test that parses package.json and asserts
the `lucisv.lint.rules.*` set, defaults and descriptions equal the
registry — the drift guard, so a new rule cannot ship without its
toggle. The server (`settings.rs`) reads all of them; the enabled set
is computed in one documented function `enabled_rules(settings,
has_oracle)` with this precedence, top to bottom: (1) the base set is
the defaults (`default_on`, and `needs_workspace` rules only with an
oracle); (2) a non-empty `select` replaces the base set; (3) a severity
switch that is off removes every rule of that severity; (4) an
explicitly set per-rule toggle sets or clears that rule; (5) `ignore`
removes — the off switch of last resort. Pinned by a table test.
Changing any of them republishes every open file, as select/ignore do.
The CLI has parity through select/ignore with severity names; no
per-rule flags (`--ignore rule` is that).
**33.2 New rules, Error class** (each a file under `rules/`, its own
tests, its doc with the Verible name where one exists, and a measured
false-positive count on opentitan — see QA):
- `mismatched-labels` (Verible, off there; **on** here, Error): an end
label that does not match its block's name (`end : wrong`, `endmodule
: other`) — a compile error. Reuse what linked-editing already pairs.
- `duplicate-declaration` (Error): the same name declared twice in one
scope (port and signal, two signals, two params). Ask the binder:
`Binder::declare` sees the second declaration — record it (a
`Semantics` query `duplicates()` or a per-scope check), skip generate
scopes and macro-expanded text; no false positive on `input clk`
+ `logic clk` non-ANSI redeclaration (legal) — pin it.
- `undeclared-identifier` (Error, `needs_workspace`): a use the file
did not resolve and the workspace overlay left `StillUnresolved`/
`NotFound`, excluding: names inside macro invocations, system names,
names a `` `define`` in scope produces, names the file's macro-word
census contains, hierarchical tails, names in a package this file
wildcard-imports when that package is not indexed. Measured on
opentitan; ships default-on only if the count of unexplained
findings on that tree is 0 — otherwise default-off with the
measurement and the reason in the doc.
- `unknown-port` and `unknown-parameter` (Error, `needs_workspace`): a
named connection `.x(…)` / override `.P(…)` naming a port or
parameter the instantiated module does not declare (the index
exports both). Silent when the module is not indexed or is declared
twice with different shapes.
**33.3 New rules, Warning class** (Verible name, default there → here):
- `forbid-defparam` (on → on): `defparam` is deprecated and rejected by
some tools.
- `invalid-system-task-function` (on → on): `$psprintf`, `$random`
(use `$urandom`), `$dist_*`, `$srandom` … Verible's list, cited.
- `truncated-numeric-literal` (on → on): a sized literal whose value
does not fit its width (`4'hFFF`).
- `undersized-binary-literal` (on → on, safe fix pads): `8'b1`; binary
only by default, as Verible.
- `suspicious-semicolon` (off → **on**): `if (x);`, `for (…);`,
`while (…);` — a body that is a null statement.
- `packed-dimensions-range-ordering` (on → on): a packed dimension
written `[0:N-1]`.
- `module-port` and `module-parameter` (on → on): positional
connections/overrides when more than one port/parameter.
- `explicit-function-task-parameter-type` (on → on): an untyped tf
argument is a 1-bit `logic` — a silent truncation.
- `plusarg-assignment` (on → on): `$value$plusargs` result unused /
`$test$plusargs` misuse, as Verible defines it.
- `instance-shadowing` (off → **on**): a declaration shadowing one in
an enclosing scope of the same unit (the binder knows).
- `forbid-negative-array-dim` (off → on): a negative literal in a
dimension.
- `void-cast` (on → on): `void'(…)` around anything but a function
call that has a return value (Verible's rule).
- `incomplete-assignment` (no Verible equivalent; Warning): in an
`always_comb`, a variable assigned in the `then` branch of an `if`
with no `else` (or in some `case` items, not `default`) and not
assigned unconditionally earlier in the block — latch inference.
Conservative by construction: only flag when the block has no
unconditional assignment to that variable before the `if`/`case`;
measured on opentitan.
**33.4 Docs and measurement.** README.md "Linting" (severities, the
toggles, select/ignore with severity names), `editors/vscode/README.md`
settings table, the docs-site rules page (hand-written prose today —
add the new rules with their severity and a note that `--rules-doc` is
the generated truth), CHANGELOG untouched (the lead writes it). For
every new rule: findings on the corpus and on opentitan `hw/`
(read-only `lucisv check`), with ten findings read and classified per
rule (true / false positive / needs judgment); opentitan is lint-clean
under Verible, so a Verible-equivalent rule that fires there needs an
explanation (their config disables it, or our reading differs — say
which). Timing: `lucisv check` over opentitan before/after (the
semantic rules already dominate; the new ones must not add more than a
few percent).
Files: crates/vlog_linter/src/{registry.rs, rule_docs.rs, violation.rs,
lib.rs, rules/mod.rs, rules/<new>.rs, context.rs (if a semantics query
is needed), visit.rs (new walkers)} + tests/cases/*.lint,
crates/vlog_linter/examples/vscode_lint_settings.rs (new),
crates/vlog_semantic (only if `duplicates()`/shadowing needs a query —
additive, say so in Handshakes), crates/lucisv/src/{lint.rs, args.rs}
+ tests, crates/lucisv_server/src/{settings.rs, lint.rs} + tests,
editors/vscode/{package.json, README.md}, README.md "Linting",
docs/site/src/content/docs/reference/rules.md, docs/features/
linter-expansion-1/README.md (new), TODO §33. Worktree `lint-1`.
- [x] 33.0 `Severity` on every rule; select/ignore by severity; CLI
text/JSON; editor severities; `--rules-doc` grouped
- [x] 33.1 package.json toggles generated + drift test; `enabled_rules`
precedence pinned; republish on change
- [x] 33.2 Error rules: mismatched-labels, duplicate-declaration,
undeclared-identifier (measured; default decided by the count),
unknown-port, unknown-parameter
- [x] 33.3 Warning rules: the thirteen listed, each with tests and an
opentitan count
- [x] 33.4 docs; measurements table in the README
- [x] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
byte-identical (formatter untouched); opentitan read-only
`lucisv check` census + timing
- [ ] QA: every new rule attacked with hand-written true positives and
near-misses; the false-positive census re-read; toggles exercised
through the real server (`workspace/didChangeConfiguration`)
## 34. Linter expansion, wave 2 (planned 2026-09-02, after §33) — the Style class and per-rule options
The style family from Verible, with the per-rule configuration the
naming rules need: `signal-name-style`, `interface-name-style`,
`macro-name-style`, `constraint-name-style`, `parameter-type-name-style`,
`dff-name-style`, `port-name-suffix`, `banned-declared-name-patterns`
(each with a `pattern`/style option), `line-length` (reads the
formatter's `line-length`), `posix-eof` (safe fix), `endif-comment`,
`forbid-line-continuations`, `one-module-per-file`, `package-filename`,
`typedef-enums`, `typedef-structs-unions`, `module-begin-block`,
`generate-label` + `generate-label-prefix`, `always-comb` (`@*` →
`always_comb`, safe fix), `legacy-generate-region`,
`legacy-genvar-declaration`, `v2001-generate-begin`,
`explicit-function-lifetime`/`explicit-task-lifetime`,
`positive-meaning-parameter-name`, `suggest-parentheses`,
`forbid-consecutive-null-statements`, `unpacked-dimensions-range-
ordering`, `uvm-macro-semicolon`, `create-object-name-match`,
`numeric-format-string-style`, `macro-string-concatenation`,
`disable-statement`, `forbidden-macro`/`forbidden-symbol` (list
options). Options: `[lint.<rule>]` tables in `lucisv.toml` (today
rejected by name — the parser exists) and `lucisv.lint.options.<rule>`
in the editor, validated against a per-rule option schema declared by
the rule (`Rule::options() -> &[OptionSpec]`), shown in `--rules-doc`.
Detailed plan to be written when §33 lands.
+32 -3
View File
@@ -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`].
@@ -200,6 +203,11 @@ CHECK OPTIONS (`lucisv check` only):
--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>` /
@@ -290,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(),
};
@@ -369,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);
@@ -382,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
@@ -427,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"),
@@ -595,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);
}
}
+82 -12
View File
@@ -50,6 +50,11 @@ pub struct Plan {
/// a rule asks about one name at a time and never about a file.
pub struct Census {
files: HashMap<String, u32>,
/// Module or interface name → what it declares, `None` for a unit the run
/// cannot answer for: a header carrying a compiler directive, or two
/// declarations that disagree. Empty when no enabled rule asked for it —
/// building it costs a parse of every file in the run.
interfaces: HashMap<String, Option<vlog_linter::ModuleInterface>>,
}
impl Census {
@@ -58,27 +63,61 @@ impl Census {
/// 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
///
/// `interfaces` says whether the run also needs each unit's ports and
/// parameters (`unknown-port`, `unknown-parameter`). It costs a **parse**
/// of every file on top of the lex the word census already pays for, so
/// it is built only when some enabled rule asks — measured on opentitan
/// `hw/` in `docs/features/linter-expansion-1/README.md`.
fn of(jobs: &[Job], interfaces: bool) -> Census {
type PerFile = (Vec<String>, Vec<(String, Option<vlog_linter::ModuleInterface>)>);
let per_file: Vec<PerFile> = jobs
.par_iter()
.map(|job| match std::fs::read_to_string(&job.path) {
Ok(src) => words::harvest_text(&src),
Err(_) => Vec::new(),
.map(|job| {
let Ok(src) = std::fs::read_to_string(&job.path) else {
return (Vec::new(), Vec::new());
};
if !interfaces {
return (words::harvest_text(&src), Vec::new());
}
// One lex for both halves: the parse is what the interface
// table needs, and its tokens are the word census's.
let parsed = ParsedSource::parse(&src);
(words::harvest(parsed.tokens()), vlog_linter::module_interfaces(parsed.file()))
})
.collect();
let mut files: HashMap<String, u32> = HashMap::new();
for words in per_file {
let mut units: HashMap<String, Option<vlog_linter::ModuleInterface>> = HashMap::new();
for (words, declared) in per_file {
for word in words {
*files.entry(word).or_default() += 1;
}
for (name, interface) in declared {
// Two declarations of one name answer only when they agree;
// anything else is a question the run cannot settle.
units
.entry(name)
.and_modify(|held| {
if *held != interface {
*held = None;
}
})
.or_insert(interface);
}
}
Census { files }
Census { files, interfaces: units }
}
/// How many files in the run write `name` down.
fn count(&self, name: &str) -> u32 {
self.files.get(name).copied().unwrap_or(0)
}
/// What the run says `name` declares, or `None` when it cannot say.
fn interface(&self, name: &str) -> Option<vlog_linter::ModuleInterface> {
self.interfaces.get(name)?.clone()
}
}
/// One file's view of the census: everything the project says, minus what
@@ -96,6 +135,13 @@ impl MentionOracle for Elsewhere<'_> {
let mine = u32::from(self.own.binary_search_by(|w| w.as_str().cmp(name)).is_ok());
self.census.count(name) > mine
}
/// The run's interface table, which covers **every** file including this
/// one: a module is instantiated as often in the file that declares it as
/// anywhere else, and there is nothing to subtract here.
fn module_interface(&self, name: &str) -> Option<vlog_linter::ModuleInterface> {
self.census.interface(name)
}
}
/// Resolve the run: the rules for each file, and whether a census is owed.
@@ -120,10 +166,25 @@ pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Res
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));
let interfaces = jobs.iter().any(|job| job.rules.iter().any(|rule| reads_interfaces(*rule)));
let census = (workspace && wanted).then(|| Census::of(&jobs, workspace && interfaces));
Ok(Plan { jobs, census })
}
/// Whether this rule reads the census's **interface** half, which costs a
/// parse of every file in the run rather than a lex.
///
/// By name, because the alternative is a fourth boolean on the `Rule` trait
/// for two rules: `Rule::needs_workspace` already says "this rule asks the
/// project something", and which *question* it asks is between the rule and
/// the oracle. A name that is not in the registry cannot reach here — the
/// rules are `&'static dyn Rule` values from that registry — and a rule added
/// to the pair without being added here answers `None` and goes quiet, which
/// is the safe direction.
fn reads_interfaces(rule: &'static dyn Rule) -> bool {
matches!(rule.name(), "unknown-port" | "unknown-parameter")
}
/// 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() {
@@ -348,15 +409,23 @@ fn finish(opts: &Options, reports: Vec<Report>) -> ExitCode {
}
}
/// Verible's diagnostic line: `FILE:LINE:COL: message [rule-name]`.
/// Verible's diagnostic line with the severity word in front of the message:
/// `FILE:LINE:COL: error|warning|style: message [rule-name]`.
///
/// The word sits where a compiler puts it, so the line greps and reads the way
/// every other tool's does, and `grep ': error:'` is the whole of "show me
/// what would not compile".
fn print_text(reports: &[Report]) {
let mut out = String::new();
for report in reports {
for violation in &report.violations {
let (line, col) = position(report, violation);
out.push_str(&format!(
"{}:{line}:{col}: {} [{}]\n",
report.path, violation.message, violation.rule
"{}:{line}:{col}: {}: {} [{}]\n",
report.path,
violation.severity.as_str(),
violation.message,
violation.rule
));
}
}
@@ -372,12 +441,13 @@ fn print_json(reports: &[Report]) {
let (line, col) = position(report, violation);
let (end_line, end_col) = end_position(report, violation);
items.push(format!(
"{{\"filename\":{},\"rule\":{},\"message\":{},\
"{{\"filename\":{},\"rule\":{},\"severity\":{},\"message\":{},\
\"location\":{{\"line\":{line},\"column\":{col}}},\
\"end_location\":{{\"line\":{end_line},\"column\":{end_col}}},\
\"range\":{{\"start\":{},\"end\":{}}},\"fix\":{}}}",
quote(&report.path),
quote(violation.rule),
quote(violation.severity.as_str()),
quote(&violation.message),
violation.span.start,
violation.span.end,
+6
View File
@@ -84,6 +84,12 @@ fn run(opts: &Options) -> ExitCode {
/// `lucisv check`: the linter over the same file set the formatter would take.
fn run_check(opts: &Options) -> ExitCode {
// 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.
+68 -1
View File
@@ -753,7 +753,9 @@ fn check_reports_violations_and_exits_1() {
let out = run(&["check", &path]);
assert_eq!(code(&out), 1, "violations must exit 1: {}", stderr(&out));
let text = stdout(&out);
assert!(text.contains(&format!("{path}:2:1: tab character")), "{text}");
// `FILE:LINE:COL: severity: message [rule]` — the severity word is part
// of the line since §33.0, and both of these are style findings.
assert!(text.contains(&format!("{path}:2:1: style: tab character")), "{text}");
assert!(text.contains("[no-tabs]"), "{text}");
assert!(text.contains("[module-filename]"), "{text}");
assert!(stderr(&out).contains("found 2 violations"), "{}", stderr(&out));
@@ -797,6 +799,7 @@ fn check_json_is_one_array_with_positions_and_fixes() {
assert!(text.starts_with('['), "{text}");
assert!(text.trim_end().ends_with(']'), "{text}");
assert_eq!(text.matches("\"rule\":\"no-tabs\"").count(), 1, "{text}");
assert!(text.contains("\"severity\":\"style\""), "{text}");
assert!(text.contains("\"location\":{\"line\":2,\"column\":1}"), "{text}");
assert!(text.contains("\"applicability\":\"safe\""), "{text}");
assert!(text.contains("\"content\":\" \""), "{text}");
@@ -895,6 +898,30 @@ fn check_select_and_ignore_pick_the_rule_set() {
assert!(stderr(&out).contains("unknown rule"), "{}", stderr(&out));
}
/// A severity word stands for its whole class wherever a rule name fits —
/// §33.0's headline for the command line.
#[test]
fn check_select_and_ignore_accept_a_severity_word() {
let dir = TempDir::new("check-severity");
// `reg` is an error-class finding, the tab and the name are style ones.
let path = dir.write("bar.sv", "module foo;\n\treg a;\nendmodule\n");
let out = run(&["check", "--select", "error", &path]);
assert_eq!(code(&out), 1, "{}", stdout(&out));
let text = stdout(&out);
assert_eq!(text.lines().count(), 1, "{text}");
assert!(text.contains(": error: "), "{text}");
assert!(text.contains("[wire-reg-mixup]"), "{text}");
let out = run(&["check", "--ignore", "style", &path]);
assert_eq!(stdout(&out).lines().count(), 1, "{}", stdout(&out));
assert!(stdout(&out).contains("[wire-reg-mixup]"), "{}", stdout(&out));
// Ignoring every class leaves nothing to report.
let out = run(&["check", "--ignore", "error,warning,style", &path]);
assert_eq!(code(&out), 0, "{}", stdout(&out));
}
#[test]
fn check_honors_inline_waivers_and_reports_dead_ones() {
let dir = TempDir::new("check-waive");
@@ -1880,3 +1907,43 @@ fn a_signal_named_only_inside_a_macro_argument_is_not_reported_unused() {
"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)
);
}
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
+837
View File
@@ -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());
}
}
+264
View File
@@ -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), ["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));
}
}
+246
View File
@@ -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'))
}
+4 -3
View File
@@ -135,11 +135,12 @@ mod tests {
#[test]
fn one_list_carries_both_sources() {
// A file that parses cleanly and violates a lint rule: the publish is
// one list, and the lint finding is in it as a warning.
// one list, and the lint finding is in it at its rule's own severity
// — `no-tabs` is a style rule, so INFORMATION (§33.0).
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
let published = all(ws.document(&uri).expect("open"));
assert_eq!(published.len(), 1);
assert_eq!(published[0].severity, Some(DiagnosticSeverity::WARNING));
assert_eq!(published[0].severity, Some(DiagnosticSeverity::INFORMATION));
assert_eq!(published[0].code, Some(lsp_types::NumberOrString::String("no-tabs".into())));
}
@@ -149,7 +150,7 @@ mod tests {
let published = all(ws.document(&uri).expect("open"));
let severities: Vec<_> = published.iter().map(|d| d.severity).collect();
assert!(severities.contains(&Some(DiagnosticSeverity::ERROR)), "{published:#?}");
assert!(severities.contains(&Some(DiagnosticSeverity::WARNING)), "{published:#?}");
assert!(severities.contains(&Some(DiagnosticSeverity::INFORMATION)), "{published:#?}");
assert!(published.iter().all(|d| d.source.as_deref() == Some("lucisv")));
// Errors first: a parse error is what the user must fix.
assert_eq!(published[0].severity, Some(DiagnosticSeverity::ERROR));
+247 -14
View File
@@ -11,15 +11,19 @@
//! `docs/features/semantic-lints-on/README.md` and
//! `docs/features/server-lint/README.md`.
use std::collections::BTreeSet;
use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString};
use vlog_formatter::fence::{self, Region};
use vlog_linter::{
default_rules, lint, workspace_rules, LintContext, MentionOracle, Rule, Violation,
default_rules, lint, workspace_rules, LintContext, MentionOracle, ModuleInterface, Rule,
Severity, Violation,
};
use vlog_semantic::{FileId, WorkspaceIndex};
use vlog_semantic::{FileId, SymbolKind, WorkspaceIndex};
use crate::convert::Positions;
use crate::diagnostics::SOURCE;
use crate::settings::ClientSettings;
use crate::state::{Document, Workspace};
/// What one lint pass runs: which rules, and what it may ask about the files
@@ -52,12 +56,7 @@ impl<'a> 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 rules = enabled_rules(ws.client_settings(), workspace);
let oracle = workspace.then_some(IndexMentions { index, own });
LintRun { rules, oracle }
}
@@ -72,6 +71,63 @@ impl<'a> LintRun<'a> {
}
}
/// Which rules a buffer is linted with, given what the editor's settings say.
///
/// **The one ladder**, top rung last — every rung may undo the one above it:
///
/// 1. the base set is what the rules themselves declare: `default_on`, plus
/// the `needs_workspace` rules when `has_oracle`;
/// 2. a non-empty `lucisv.lint.select` **replaces** that base set, exactly as
/// `--select` replaces it on the command line;
/// 3. a `lucisv.lint.severity.<class>` switched off **removes** every rule of
/// that class;
/// 4. a `lucisv.lint.rules.<name>` set to `on` or `off` sets or clears that
/// one rule — the per-rule word beats the class word, which is what makes
/// "all style off except `no-tabs`" expressible;
/// 5. `lucisv.lint.ignore` **removes** — the off switch of last resort, the
/// one a user reaches for when nothing else worked.
///
/// Rungs 2 and 5 accept a severity word wherever a rule name fits.
pub fn enabled_rules(settings: &ClientSettings, has_oracle: bool) -> Vec<&'static dyn Rule> {
let base = if settings.lint_select.is_empty() {
if has_oracle {
workspace_rules()
} else {
default_rules()
}
} else {
named(&settings.lint_select)
};
let mut on: BTreeSet<&'static str> = base.iter().map(|rule| rule.name()).collect();
for (severity, class_on) in &settings.lint_severity {
if !class_on {
on.retain(|name| {
vlog_linter::rule_by_name(name).is_some_and(|rule| rule.severity() != *severity)
});
}
}
for (name, wanted) in &settings.lint_rules {
let Some(rule) = vlog_linter::rule_by_name(name) else { continue };
if *wanted {
on.insert(rule.name());
} else {
on.remove(rule.name());
}
}
for rule in named(&settings.lint_ignore) {
on.remove(rule.name());
}
vlog_linter::all_rules().into_iter().filter(|rule| on.contains(rule.name())).collect()
}
/// Every rule a list of `--select`-style words names, unknown words skipped —
/// they were already dropped when the settings were parsed, and a name that
/// survived that filter always resolves.
fn named(words: &[String]) -> Vec<&'static dyn Rule> {
words.iter().filter_map(|word| vlog_linter::rules_named(word)).flatten().collect()
}
/// The workspace index, asked the one question a lint rule may ask about other
/// files.
///
@@ -97,6 +153,32 @@ impl MentionOracle for IndexMentions<'_> {
fn mentioned_elsewhere(&self, name: &str) -> bool {
self.index.mentioned_outside(name, self.own)
}
/// The ports and overridable parameters of an indexed module or interface,
/// read off the index's member table — the very table a `.port` completion
/// list is offered from, so a connection lucisv would have completed is
/// never one it then calls unknown.
///
/// `None` for a unit the index does not hold, and for one it holds **more
/// than once**: two modules of a name are two different headers, and
/// answering with either would make an Error-class rule guess. A
/// `localparam` is left out, because it is not overridable.
fn module_interface(&self, name: &str) -> Option<ModuleInterface> {
let units = self.index.units(name);
let [unit] = units else { return None };
if !unit.kind.is_instantiable() {
return None;
}
let mut interface = ModuleInterface::default();
for (member, defs) in self.index.members_of(name) {
match defs.first().map(|def| def.kind) {
Some(SymbolKind::Port) => interface.ports.push(member.to_string()),
Some(SymbolKind::Param) => interface.parameters.push(member.to_string()),
_ => {}
}
}
Some(interface)
}
}
/// The document's own parse products, lent to the linter — "one parse, two
@@ -175,14 +257,13 @@ pub fn diagnostics_in(doc: &Document, run: &LintRun) -> Vec<Diagnostic> {
/// The diagnostic a violation becomes.
///
/// **Warning**, never Error: a lint finding is an opinion about style, and a
/// parse error is the compiler refusing. The `code` is the rule's stable name,
/// which is what a user needs to write a waiver or an `--ignore`, and what a
/// code action matches on.
/// The editor's severity is the rule's own class ([`severity_of`]). The `code`
/// is the rule's stable name, which is what a user needs to write a waiver or
/// an `--ignore`, and what a code action matches on.
pub fn diagnostic(positions: &Positions<'_>, violation: &Violation) -> Diagnostic {
Diagnostic {
range: positions.diagnostic_range(violation.span),
severity: Some(DiagnosticSeverity::WARNING),
severity: Some(severity_of(violation.severity)),
code: Some(NumberOrString::String(violation.rule.to_string())),
source: Some(SOURCE.to_string()),
message: violation.message.clone(),
@@ -190,6 +271,21 @@ pub fn diagnostic(positions: &Positions<'_>, violation: &Violation) -> Diagnosti
}
}
/// How an editor is asked to paint one class.
///
/// `error` is the red squiggle a compiler error gets — a rule only claims it
/// when the code would very likely not build, which is why the Error class is
/// held to the silence-when-unsure rule. `style` deliberately stops short of
/// `HINT`: a hint is invisible in most themes and would make the style rules
/// look broken rather than quiet.
fn severity_of(severity: Severity) -> DiagnosticSeverity {
match severity {
Severity::Error => DiagnosticSeverity::ERROR,
Severity::Warning => DiagnosticSeverity::WARNING,
Severity::Style => DiagnosticSeverity::INFORMATION,
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -211,13 +307,35 @@ mod tests {
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
let diags = diagnostics(ws.document(&uri).expect("open"));
assert_eq!(diags.len(), 1);
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::WARNING));
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::INFORMATION), "no-tabs is style");
assert_eq!(diags[0].code, Some(NumberOrString::String("no-tabs".into())));
assert_eq!(diags[0].source.as_deref(), Some("lucisv"));
assert_eq!(diags[0].range.start.line, 1);
assert!(diags[0].range.start < diags[0].range.end, "never zero-width");
}
/// Each class paints its own squiggle: a compile-error rule reads as an
/// error, a latch-shaped one as a warning, a naming one as information.
#[test]
fn a_diagnostics_severity_is_its_rules_class() {
assert_eq!(severity_of(Severity::Error), DiagnosticSeverity::ERROR);
assert_eq!(severity_of(Severity::Warning), DiagnosticSeverity::WARNING);
assert_eq!(severity_of(Severity::Style), DiagnosticSeverity::INFORMATION);
// `reg` is error-class, the tab is style-class, and the two arrive in
// one publish wearing different colours.
let (ws, uri) = doc_of("module m;\n\treg a;\nendmodule\n");
let diags = diagnostics(ws.document(&uri).expect("open"));
let by_code = |name: &str| {
diags
.iter()
.find(|d| d.code == Some(NumberOrString::String(name.into())))
.and_then(|d| d.severity)
};
assert_eq!(by_code("wire-reg-mixup"), Some(DiagnosticSeverity::ERROR), "{diags:#?}");
assert_eq!(by_code("no-tabs"), Some(DiagnosticSeverity::INFORMATION), "{diags:#?}");
}
#[test]
fn a_waived_violation_is_never_published() {
let (ws, uri) = doc_of("module m;\n\twire a; // lucisv: waive no-tabs\nendmodule\n");
@@ -368,6 +486,121 @@ mod tests {
let _ = std::fs::remove_dir_all(dir);
}
/// The ladder of §33.1, one row per rung, asserted against the rule set
/// `enabled_rules` produces. Each row is (what the settings say, what must
/// be true of the result).
#[test]
fn the_enabled_rules_ladder_is_the_documented_one() {
let names = |settings: &ClientSettings, oracle: bool| -> Vec<&'static str> {
enabled_rules(settings, oracle).into_iter().map(|rule| rule.name()).collect()
};
let with = |f: &dyn Fn(&mut ClientSettings)| {
let mut settings = ClientSettings::default();
f(&mut settings);
settings
};
// 1. the base set is the rules' own defaults, and a workspace adds
// exactly the rules that asked for one.
let base = ClientSettings::default();
assert_eq!(
names(&base, false),
default_rules().iter().map(|r| r.name()).collect::<Vec<_>>()
);
assert_eq!(
names(&base, true),
workspace_rules().iter().map(|r| r.name()).collect::<Vec<_>>()
);
// 2. a non-empty `select` replaces the base set — including rules that
// ship off, exactly as `--select` does.
let selected = with(&|s| s.lint_select = vec!["module-name-style".to_string()]);
assert_eq!(names(&selected, false), vec!["module-name-style"]);
// ... and a severity word may stand there.
let styled = with(&|s| s.lint_select = vec!["style".to_string()]);
assert!(names(&styled, true)
.iter()
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
== Severity::Style));
// 3. a class switched off removes every rule of that class.
let no_style = with(&|s| {
s.lint_severity.insert(Severity::Style, false);
});
assert!(!names(&no_style, true).contains(&"no-tabs"));
assert!(names(&no_style, true).contains(&"unused-signal"), "other classes stay");
// 4. a per-rule toggle beats the class switch, in both directions.
let style_off_but_tabs = with(&|s| {
s.lint_severity.insert(Severity::Style, false);
s.lint_rules.insert("no-tabs".to_string(), true);
});
assert!(names(&style_off_but_tabs, true).contains(&"no-tabs"));
let one_off = with(&|s| {
s.lint_rules.insert("no-tabs".to_string(), false);
});
assert!(!names(&one_off, true).contains(&"no-tabs"));
// A toggle also adds a rule `select` did not name, and one that ships
// off entirely.
let added = with(&|s| {
s.lint_select = vec!["no-tabs".to_string()];
s.lint_rules.insert("module-name-style".to_string(), true);
});
assert_eq!(names(&added, false), vec!["module-name-style", "no-tabs"]);
// 5. `ignore` is the last word, over a toggle that says `on`.
let ignored = with(&|s| {
s.lint_rules.insert("no-tabs".to_string(), true);
s.lint_ignore = vec!["no-tabs".to_string()];
});
assert!(!names(&ignored, true).contains(&"no-tabs"));
// ... and it takes a severity word too.
let quiet = with(&|s| s.lint_ignore = vec!["style".to_string()]);
assert!(names(&quiet, true)
.iter()
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
!= Severity::Style));
// The result is always in registry order, whatever order the settings
// named things in — two runs must print findings the same way.
let jumbled = with(&|s| {
s.lint_select = vec!["no-trailing-whitespace".to_string(), "no-tabs".to_string()];
});
assert_eq!(names(&jumbled, false), vec!["no-tabs", "no-trailing-whitespace"]);
}
/// The toggles reach the real published diagnostics, not just the rule
/// list: a class switched off silences its squiggles.
#[test]
fn a_class_switch_changes_what_the_server_publishes() {
let (mut ws, dir, uri) = two_file_project("classes");
ws.set_document(uri.clone(), "module dut;\n\tlogic dead;\nendmodule\n".to_string());
let doc = ws.document(&uri).expect("open");
let mut both = codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc)));
both.sort();
assert_eq!(both, vec!["no-tabs", "unused-signal"], "premise");
let mut off = ClientSettings::default();
off.lint_severity.insert(Severity::Style, false);
ws.set_client_settings(off);
let doc = ws.document(&uri).expect("open");
assert_eq!(
codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc))),
vec!["unused-signal"],
"the style class went quiet"
);
let mut back = ClientSettings::default();
back.lint_severity.insert(Severity::Style, false);
back.lint_rules.insert("no-tabs".to_string(), true);
ws.set_client_settings(back);
let doc = ws.document(&uri).expect("open");
let mut with_tabs = codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc)));
with_tabs.sort();
assert_eq!(with_tabs, vec!["no-tabs", "unused-signal"], "the per-rule word wins");
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]
+124 -3
View File
@@ -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
+188
View File
@@ -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(&notification.params)
}
_ => None,
})
.filter_map(|uri| crate::uri::uri_to_path(&uri))
.collect()
}
+341
View File
@@ -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(&section));
}
/// 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()
}
}
+528
View File
@@ -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(), &params.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(), &params.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(), &params.options);
let result = format::ranges_formatting(doc, &settings.config, &params.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(), &params.options);
let edits = on_type::on_type_formatting(doc, at.position, &params.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())
}
}
}
}
+325
View File
@@ -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(),
)
}
}
+540
View File
@@ -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,307 @@
//! `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(&notification) {
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.
///
/// All four lint settings, not just the two lists: since §33.1 a class
/// switch (`lucisv.lint.severity.*`) and a per-rule toggle
/// (`lucisv.lint.rules.*`) change which rules run too, and a change to one
/// of them must republish exactly as a change to `select`/`ignore` does.
fn lint_selection(&self) -> settings::LintSelection {
settings::lint_selection(self.workspace.client_settings())
}
}
/// 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()
}
+272
View File
@@ -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(&notification),
"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(&params.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(&params.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(&nothing["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);
}
+202 -3
View File
@@ -13,9 +13,11 @@
//! Not to be confused with `format::Settings`, which is what one formatting
//! request resolved to after every rung of that ladder was applied.
use std::collections::BTreeMap;
use std::ops::RangeInclusive;
use serde_json::Value;
use vlog_linter::Severity;
/// Accepted `line-length`, and accepted `indent`.
///
@@ -174,6 +176,20 @@ pub struct ClientSettings {
/// `lucisv.lint.ignore`: rules dropped from whatever `select` left. Same
/// validation, same reason.
pub lint_ignore: Vec<String>,
/// `lucisv.lint.severity.error` / `.warning` / `.style`: the master switch
/// of each class. Every class is present and `true` unless a client turned
/// one off — see `lint::enabled_rules` for where it sits in the ladder.
pub lint_severity: BTreeMap<Severity, bool>,
/// `lucisv.lint.rules.<rule-name>`: the rules a client said something
/// **explicit** about — `true` for `on`, `false` for `off`.
///
/// A rule left at `default` is *absent from this map*, and that is the
/// whole reason the setting is a three-word enum rather than a boolean: a
/// client sends the whole section, every key at its default, so "unset"
/// and "set to the shipped value" would arrive identically and a per-rule
/// toggle nobody touched would silently override `select` and the class
/// switches.
pub lint_rules: BTreeMap<String, bool>,
}
/// The settings a client that said nothing is treated as having asked for.
@@ -200,10 +216,35 @@ impl Default for ClientSettings {
large_file_threshold: DEFAULT_LARGE_FILE_THRESHOLD,
lint_select: Vec::new(),
lint_ignore: Vec::new(),
lint_severity: every_class_on(),
lint_rules: BTreeMap::new(),
}
}
}
/// Every severity class switched on — what a client that said nothing means.
fn every_class_on() -> BTreeMap<Severity, bool> {
Severity::ALL.into_iter().map(|severity| (severity, true)).collect()
}
/// Everything about a settings value that decides **which rules run**: the two
/// name lists, the class switches and the per-rule toggles.
///
/// Its only use is equality — the server compares it across a settings change
/// to decide whether every open file must be published again.
pub type LintSelection =
(Vec<String>, Vec<String>, BTreeMap<Severity, bool>, BTreeMap<String, bool>);
/// The four lint settings of `settings`, as one comparable value.
pub fn lint_selection(settings: &ClientSettings) -> LintSelection {
(
settings.lint_select.clone(),
settings.lint_ignore.clone(),
settings.lint_severity.clone(),
settings.lint_rules.clone(),
)
}
/// Read the `lucisv` section out of a `workspace/didChangeConfiguration` payload.
///
/// **Nothing here trusts the client.** `package.json`'s JSON schema constrains
@@ -274,17 +315,53 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
.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"))),
// `lucisv.lint.severity.<class>` and `lucisv.lint.rules.<name>` nest
// one level deeper again, for the same reason `index.*` does.
lint_severity: severity_switches(lint.and_then(|l| l.get("severity"))),
lint_rules: rule_toggles(lint.and_then(|l| l.get("rules"))),
}
}
/// The rule names in a settings array, dropping every one the registry does
/// not know.
/// The rule names in a settings array, dropping every one that names neither a
/// rule nor a severity class.
///
/// 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()
strings(value).into_iter().filter(|name| vlog_linter::rules_named(name).is_some()).collect()
}
/// The three class master switches, each `true` unless a client turned it off.
///
/// A missing or wrong-typed switch leaves its class on: the safe direction for
/// a switch that silences a whole family of diagnostics is the one that shows
/// them, exactly as an unreadable size cap leaves the cap on.
fn severity_switches(value: Option<&Value>) -> BTreeMap<Severity, bool> {
Severity::ALL
.into_iter()
.map(|severity| {
let on = flag(value.and_then(|v| v.get(severity.as_str()))).unwrap_or(true);
(severity, on)
})
.collect()
}
/// The rules a client said something explicit about: `on` and `off` only.
///
/// `default` — and any word that is neither, and any key that is not a rule —
/// contributes nothing, which is what leaves the rule wherever the rest of the
/// ladder put it. See [`ClientSettings::lint_rules`].
fn rule_toggles(value: Option<&Value>) -> BTreeMap<String, bool> {
let Some(Value::Object(map)) = value else { return BTreeMap::new() };
map.iter()
.filter(|(name, _)| vlog_linter::rule_by_name(name).is_some())
.filter_map(|(name, choice)| match choice.as_str() {
Some("on") => Some((name.clone(), true)),
Some("off") => Some((name.clone(), false)),
_ => None,
})
.collect()
}
/// One of the two `lucisv.index.scope` words, or nothing. Matched exactly —
@@ -623,6 +700,128 @@ mod tests {
}
}
/// **The drift guard.** `editors/vscode/package.json` declares one switch
/// per severity class and one per rule, generated by
/// `vlog_linter::vscode_lint_settings`. This compares the two as JSON
/// *values*, so formatting is free but a rule added without its toggle —
/// or a summary, default or severity edited on one side only — fails here.
///
/// Regenerate with
/// `cargo run -p vlog_linter --example vscode_lint_settings`.
#[test]
fn the_vscode_lint_toggles_match_the_registry() {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../editors/vscode/package.json");
let text = std::fs::read_to_string(&path).expect("the extension manifest");
let manifest: Value = serde_json::from_str(&text).expect("valid json");
let properties = manifest["contributes"]["configuration"]["properties"]
.as_object()
.expect("a properties object");
let declared: serde_json::Map<String, Value> = properties
.iter()
.filter(|(key, _)| {
key.starts_with("lucisv.lint.severity.") || key.starts_with("lucisv.lint.rules.")
})
.map(|(key, value)| (key.clone(), value.clone()))
.collect();
let generated: Value = serde_json::from_str(&vlog_linter::vscode_lint_settings())
.expect("the generator emits valid json");
let generated = generated.as_object().expect("an object");
let names = |map: &serde_json::Map<String, Value>| {
let mut keys: Vec<String> = map.keys().cloned().collect();
keys.sort();
keys
};
assert_eq!(
names(&declared),
names(generated),
"package.json and the rule registry disagree about which lint settings exist; \
regenerate with `cargo run -p vlog_linter --example vscode_lint_settings`"
);
for (key, value) in generated {
assert_eq!(declared.get(key), Some(value), "{key} drifted");
}
// And every rule really does have one, which is the promise the whole
// generator exists to keep.
for rule in vlog_linter::all_rules() {
assert!(declared.contains_key(&vlog_linter::rule_setting(rule)), "{}", rule.name());
}
}
/// A default-everything payload — which is what a client sends for a user
/// who has touched nothing — must say nothing about any rule.
#[test]
fn the_shipped_lint_toggles_are_no_opinion() {
let mut rules = serde_json::Map::new();
for rule in vlog_linter::all_rules() {
rules.insert(rule.name().to_string(), json!("default"));
}
let found = settings(json!({"lucisv": {"lint": {
"severity": {"error": true, "warning": true, "style": true},
"rules": Value::Object(rules),
}}}));
assert_eq!(found, ClientSettings::default(), "every shipped value is silence");
}
#[test]
fn the_severity_switches_and_rule_toggles_are_read() {
let found = settings(json!({"lucisv": {"lint": {
"severity": {"style": false, "warning": "yes"},
"rules": {"no-tabs": "on", "unused-signal": "off", "empty-item": "default",
"no-such-rule": "on", "case-missing-default": 3},
}}}));
assert!(!found.lint_severity[&Severity::Style]);
assert!(found.lint_severity[&Severity::Warning], "a wrong type leaves it on");
assert!(found.lint_severity[&Severity::Error], "and so does absence");
assert_eq!(
found.lint_rules,
[("no-tabs".to_string(), true), ("unused-signal".to_string(), false)]
.into_iter()
.collect::<BTreeMap<_, _>>(),
"`default`, an unknown rule and a wrong-typed choice all say nothing"
);
// A `lint` that is not an object leaves every class on and nothing said.
let junk = settings(json!({"lucisv": {"lint": 7}}));
assert_eq!(junk.lint_severity, every_class_on());
assert!(junk.lint_rules.is_empty());
}
/// A severity word is a legal `select`/`ignore` entry since §33.0, so the
/// validating filter must keep it.
#[test]
fn a_severity_word_survives_the_select_and_ignore_filter() {
let found = settings(json!({"lucisv": {"lint": {
"select": ["style", "no-tabs", "nope"],
"ignore": ["warning"],
}}}));
assert_eq!(found.lint_select, vec!["style", "no-tabs"]);
assert_eq!(found.lint_ignore, vec!["warning"]);
}
/// What the server compares two settings pushes by, to decide whether the
/// squiggles it already drew are still right.
#[test]
fn the_lint_selection_notices_every_setting_that_changes_the_rule_set() {
let base = ClientSettings::default();
let mut severity = base.clone();
severity.lint_severity.insert(Severity::Style, false);
let mut toggled = base.clone();
toggled.lint_rules.insert("no-tabs".to_string(), false);
let mut selected = base.clone();
selected.lint_select = vec!["error".to_string()];
let mut ignored = base.clone();
ignored.lint_ignore = vec!["no-tabs".to_string()];
for changed in [severity, toggled, selected, ignored] {
assert_ne!(lint_selection(&base), lint_selection(&changed));
}
// A setting that does not change which rules run does not republish.
let mut unrelated = base.clone();
unrelated.indent = Some(4);
assert_eq!(lint_selection(&base), lint_selection(&unrelated));
}
#[test]
fn the_default_vscode_payload_is_no_opinion_about_anything() {
// Every setting at its `package.json` default: nulls and an empty
+3 -1
View File
@@ -455,7 +455,9 @@ fn lint_diagnostics_and_a_code_action_round_trip_over_the_wire() {
assert!(codes.contains(&"no-tabs"), "{codes:?}");
assert!(codes.contains(&"no-trailing-whitespace"), "{codes:?}");
for diagnostic in diagnostics {
assert_eq!(diagnostic["severity"], 2, "a lint finding is a warning");
// Both rules here are style-class, which is LSP severity 3
// (INFORMATION) since §33.0.
assert_eq!(diagnostic["severity"], 3, "a style finding is information");
assert_eq!(diagnostic["source"], "lucisv");
}
+153 -20
View File
@@ -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
+369
View File
@@ -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)
}
}
+301
View File
@@ -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)),
}
}
+418
View File
@@ -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),
}
}
}
+452
View File
@@ -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("}")])
}
}
+481
View File
@@ -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),
}
}
+535
View File
@@ -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)
}
}
+335
View File
@@ -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
}
}
+259
View File
@@ -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
}
+379
View File
@@ -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)
}
}
}
}
+257
View File
@@ -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)
}
}
+285
View File
@@ -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
}
+691
View File
@@ -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()
}
+519
View File
@@ -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
}
+8 -1
View File
@@ -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.
@@ -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
@@ -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
+246 -2
View File
@@ -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;
@@ -341,3 +341,81 @@ module tb;
clk_rst_if #(.IfName("main")) clk_rst_if_inst (.clk(clk), .rst_n(rst_n));
dut u_dut (.bus(bus_if_inst.master));
endmodule
====
# a modport method prototype, imported and exported, task and function
# IEEE 1800-2017 25.5.4
interface bus_if;
logic [7:0] data;
task drive(input int x); endtask
function int peek(); return 0; endfunction
modport mp (input data, import task drive(input int x), export function int peek());
endinterface
----
interface bus_if;
logic [7:0] data;
task drive(input int x);
endtask
function int peek();
return 0;
endfunction
modport mp (input data, import task drive(input int x), export function int peek());
endinterface
====
# a prototype with no formals at all, beside the bare-name spelling
# IEEE 1800-2017 25.5.4: modport_tf_port ::= method_prototype | tf_identifier
interface i;
modport a (import task drive);
modport b (import drive);
modport c (export function void flush());
endinterface
----
interface i;
modport a (import task drive);
modport b (import drive);
modport c (export function void flush());
endinterface
====
# every gap of a modport prototype owns its comment
interface i;
modport mp (import /*a*/ task /*b*/ drive /*c*/ (/*d*/ input /*e*/ int /*f*/ x /*g*/));
endinterface
----
interface i;
modport mp (
import /*a*/ task /*b*/ drive /*c*/ (
/*d*/
input /*e*/ int /*f*/ x /*g*/
)
);
endinterface
====
# the two gaps a function prototype's return type sits between
interface i;
modport mp (export function /*x*/ int /*y*/ peek(), import task drive());
endinterface
----
interface i;
modport mp (export function /*x*/ int /*y*/ peek(), import task drive());
endinterface
====
# a comment between a modport direction keyword and the names it governs
interface i;
modport mp (input /*c*/ a, b, output /*d*/ c);
endinterface
----
interface i;
modport mp (input /*c*/ a, b, output /*d*/ c);
endinterface
====
# a long prototype list breaks one entry to a line, like any modport list
interface long_if;
modport very_long_modport_name (input a_long_signal_name, import task a_long_task_name(input int a_long_formal_name), output another_signal);
endinterface
----
interface long_if;
modport very_long_modport_name (
input a_long_signal_name,
import task a_long_task_name(input int a_long_formal_name),
output another_signal
);
endinterface
+136
View File
@@ -93,6 +93,142 @@ fn a_corrupted_fenced_region_is_still_rejected_by_the_safety_net() {
}
}
#[test]
fn a_statement_region_is_emitted_byte_for_byte() {
// A fence between two statements of an `always` block: the hand-aligned
// interior, the blank line and the trailing comment all survive, and the
// statement after the `on` is formatted normally.
let src = "module m;\n always_ff @(posedge clk) begin\n // lucisv: off\n q0 <= d0; // lo\n\n q1 <= d1;\n // lucisv: on\n q2 <= d2;\n end\nendmodule\n";
let region =
" // lucisv: off\n q0 <= d0; // lo\n\n q1 <= d1;\n // lucisv: on";
let out = fenced(src, region);
assert!(out.contains("\n q2 <= d2;\n"), "formatting did not resume in the block:\n{out}");
}
#[test]
fn an_unmatched_off_in_a_statement_list_stops_at_the_end_of_that_list() {
// It must stop at the block's last statement — its trailing comment
// included — and never swallow the `end`, the `endfunction` or anything
// after them.
let src = "module m;\n initial begin\n // lucisv: off\n x = 1;\n y = 2; // note\n end\n\n function int f();\n return 1;\n endfunction\nendmodule\n";
let out = fenced(src, " // lucisv: off\n x = 1;\n y = 2; // note");
assert!(out.contains("\n end\n"), "the block's `end` was swallowed:\n{out}");
assert!(out.contains("function int f();"), "the next item was not formatted:\n{out}");
assert!(out.contains(" return 1;"), "the next body was not formatted:\n{out}");
}
#[test]
fn a_fork_body_and_a_task_body_are_each_their_own_scope() {
let src = "module m;\n task automatic t();\n fork\n // lucisv: off\n p1 ();\n p2 ();\n // lucisv: on\n p3 ();\n join\n z = 1;\n endtask\nendmodule\n";
let out =
fenced(src, " // lucisv: off\n p1 ();\n p2 ();\n // lucisv: on");
assert!(out.contains(" p3();"), "the statement after the `on` was not formatted:\n{out}");
assert!(out.contains(" z = 1;"), "the task body after the fork was not formatted:\n{out}");
}
#[test]
fn a_class_body_is_a_fenceable_scope() {
let src = "class c;\n int a;\n // lucisv: off\n int b = 2;\n int cc =3;\n // lucisv: on\n int d;\nendclass\n";
let out = fenced(src, " // lucisv: off\n int b = 2;\n int cc =3;\n // lucisv: on");
assert!(out.contains(" int a;\n"), "{out}");
assert!(out.contains(" int d;\n"), "{out}");
}
#[test]
fn an_unmatched_off_in_a_class_body_stops_at_endclass() {
let src = "class c;\n // lucisv: off\n int a; // note\nendclass\n\nclass d;\n int b;\nendclass\n";
let out = fenced(src, " // lucisv: off\n int a; // note");
assert!(out.contains("class d;\n int b;\n"), "the next class was not formatted:\n{out}");
}
#[test]
fn a_fence_sharing_its_line_with_code_is_an_ordinary_comment() {
// `begin // lucisv: off` reaches the scan as the *leading* comment of the
// first statement, mid-line. Honouring it would open a region whose first
// line came from the wrong column; it is an ordinary comment instead.
let src = "module m;\n always @(*) begin // lucisv: off\n x = 1;\n y = 2;\n end\nendmodule\n";
let out = fmt(src);
verify_equivalence(src, &out).expect("equivalent");
assert_eq!(fmt(&out), out, "second pass changed the output");
assert!(out.contains(" x = 1;"), "the fence fired mid-line:\n{out}");
// The same rule at item level: a header's own line is not a fence line.
let src = "module m; // lucisv: off\n wire a;\nendmodule\n";
let out = fmt(src);
verify_equivalence(src, &out).expect("equivalent");
assert_eq!(fmt(&out), out, "second pass changed the output");
assert!(out.contains(" wire a;"), "the fence fired mid-line:\n{out}");
}
#[test]
fn the_three_deferred_places_are_inert_and_never_corrupt() {
// A port list, a case-item label list, and the single-statement body of a
// bodyless `if`: a fence in each is an ordinary comment, and the code
// around it is laid out exactly as it would be without one.
let cases = [
"module m (\n // lucisv: off\n input logic a,\n output logic b\n);\nendmodule\n",
"module m;\n always @(*) case (s)\n // lucisv: off\n 2'b00: a = 1;\n 2'b01: a = 2;\n endcase\nendmodule\n",
"module m;\n always @(*)\n // lucisv: off\n if (c) x = 1;\nendmodule\n",
];
for src in cases {
let out = fmt(src);
verify_equivalence(src, &out).expect("output is token-equivalent to the input");
assert_eq!(fmt(&out), out, "second pass changed the output:\n{out}");
assert!(out.contains("lucisv: off"), "the fence comment was dropped:\n{out}");
assert!(!out.contains(" a = 1"), "the fence fenced:\n{out}");
assert!(!out.contains("input logic"), "the fence fenced:\n{out}");
}
}
#[test]
fn a_corrupted_statement_or_class_region_is_still_rejected_by_the_safety_net() {
// The same attack as at item level, aimed at the two new scopes: a fence
// is not a licence to change bytes, and a hand-built "output" that
// reformats, drops or adds anything inside one must fail equivalence.
// Every pair changes the *token stream*, which is the question
// `verify_equivalence` answers; that a region's bytes are also reproduced
// exactly — spacing included, which no token check can see — is what the
// `fenced` helper asserts in the tests above.
let stmt = "module m;\n initial begin\n // lucisv: off\n x = 1;\n y = 2; // note\n // lucisv: on\n end\nendmodule\n";
let stmt_corrupted = [
// a literal rewritten inside the region
"module m;\n initial begin\n // lucisv: off\n x = 7;\n y = 2; // note\n // lucisv: on\n end\nendmodule\n",
// the region's trailing comment dropped
"module m;\n initial begin\n // lucisv: off\n x = 1;\n y = 2;\n // lucisv: on\n end\nendmodule\n",
// the `off` fence itself dropped
"module m;\n initial begin\n x = 1;\n y = 2; // note\n // lucisv: on\n end\nendmodule\n",
// a statement added inside the region
"module m;\n initial begin\n // lucisv: off\n x = 1;\n z = 0;\n y = 2; // note\n // lucisv: on\n end\nendmodule\n",
// a statement dropped from inside the region
"module m;\n initial begin\n // lucisv: off\n x = 1;\n // lucisv: on\n end\nendmodule\n",
// the `on` fence turned into an ordinary comment
"module m;\n initial begin\n // lucisv: off\n x = 1;\n y = 2; // note\n // lucisv: onward\n end\nendmodule\n",
// the block's `end` swallowed into the region's last line
"module m;\n initial begin\n // lucisv: off\n x = 1;\n y = 2; // note\n // lucisv: on\nendmodule\n",
];
let class = "class c;\n // lucisv: off\n int b = 2;\n int cc =3;\n // lucisv: on\n int d;\nendclass\n";
let class_corrupted = [
// a type rewritten inside the region
"class c;\n // lucisv: off\n bit b = 2;\n int cc =3;\n // lucisv: on\n int d;\nendclass\n",
// a member dropped from inside the region
"class c;\n // lucisv: off\n int b = 2;\n // lucisv: on\n int d;\nendclass\n",
// a member added inside the region
"class c;\n // lucisv: off\n int b = 2;\n int cc =3;\n int e;\n // lucisv: on\n int d;\nendclass\n",
// `endclass` swallowed
"class c;\n // lucisv: off\n int b = 2;\n int cc =3;\n // lucisv: on\n int d;\n",
// a fence comment dropped
"class c;\n int b = 2;\n int cc =3;\n // lucisv: on\n int d;\nendclass\n",
];
for (src, corrupted) in [(stmt, &stmt_corrupted[..]), (class, &class_corrupted[..])] {
verify_equivalence(src, &fmt(src)).expect("the real output is equivalent");
for bad in corrupted {
assert!(
verify_equivalence(src, bad).is_err(),
"a corrupted fenced region was accepted:\n{bad}"
);
}
}
}
#[test]
fn the_matcher_agrees_with_what_the_formatter_honours() {
// The unit tests in `fence.rs` pin the matcher; this pins that the
+34
View File
@@ -218,6 +218,40 @@ fn a_fence_outranks_a_range() {
assert!(out.contains(" wire b;\n wire c;\n"), "the region is untouched: {out}");
}
const WITH_STMT_FENCE: &str = "\
module m;
initial begin
a = 1;
// lucisv: off
b = 2;
cc = 3;
// lucisv: on
d = 4;
end
endmodule
";
#[test]
fn a_statement_fence_outranks_a_range_too() {
// A fenced *statement* sits inside an item the caller's lines select, so
// there is no verbatim run behind it: the plan has to carry the fence
// itself or the region would be laid out. Selecting any line of it, or
// the whole block, must leave those bytes exactly as written.
for spec in ["4", "5", "6", "7", "2-10"] {
let out = fixed_point(WITH_STMT_FENCE, spec);
assert!(
out.contains(" // lucisv: off\n b = 2;\n cc = 3;\n // lucisv: on\n"),
"spec {spec} reformatted the region:\n{out}"
);
}
// Laying out the whole block still formats what is outside the region.
let out = fixed_point(WITH_STMT_FENCE, "2-10");
assert!(out.contains(" a = 1;"), "{out}");
assert!(out.contains(" d = 4;"), "{out}");
// And a range that misses the block entirely changes nothing at all.
assert_eq!(fixed_point(WITH_STMT_FENCE, "1"), WITH_STMT_FENCE);
}
const ALIGNED: &str = "\
module m;
localparam int A = 1;
@@ -1,10 +0,0 @@
//! Prints the generated rule reference.
//!
//! `cargo run -p vlog_linter --example rules_markdown > docs/lint-rules.md`.
//! This exists because the CLI flag that will do the same (`lucisv check
//! --rules-doc`) belongs to `crates/lucisv` and is not wired yet — see the
//! Handshakes section of `docs/features/lint-rules-2/README.md`.
fn main() {
print!("{}", vlog_linter::rules_markdown());
}
@@ -0,0 +1,16 @@
//! Prints the `lucisv.lint.severity.*` and `lucisv.lint.rules.*` settings for
//! `editors/vscode/package.json`, generated from the rule registry.
//!
//! ```text
//! cargo run -p vlog_linter --example vscode_lint_settings
//! ```
//!
//! Paste the body of the printed object into that file's
//! `contributes.configuration.properties`, replacing the block that is there.
//! The drift test in `lucisv_server` (`settings::tests::
//! the_vscode_lint_toggles_match_the_registry`) fails whenever the two
//! disagree, so a rule cannot ship without its toggle.
fn main() {
print!("{}", vlog_linter::vscode_lint_settings());
}
+89
View File
@@ -84,6 +84,16 @@ impl ParsedSource {
&self.tokens
}
/// The tolerant parse itself — public for the same reason [`tokens`] is:
/// a caller that has already paid for the parse can read the tree for
/// something else (`lucisv check` harvests its interface census off it)
/// instead of parsing the same text twice.
///
/// [`tokens`]: ParsedSource::tokens
pub fn file(&self) -> &SourceFile {
&self.file
}
/// A lint context borrowing this parse. `path` is the file the text came
/// from, or `None` for a buffer (stdin) — rules that need a filename skip.
pub fn context(&self, path: Option<PathBuf>) -> LintContext<'_> {
@@ -125,6 +135,42 @@ enum Backing<'a> {
pub trait MentionOracle: Sync {
/// Whether any file **other than** the one being linted mentions `name`.
fn mentioned_elsewhere(&self, name: &str) -> bool;
/// What the project says the module or interface `name` declares, or
/// `None` when it cannot say — the unit is not in the project, or it is
/// declared more than once and the declarations disagree.
///
/// The second question a rule may ask about other files, added by TODO
/// §33.2 for `unknown-port` and `unknown-parameter`. It is deliberately
/// still a *closed* question — the names a connection list may use, and
/// nothing about them — and `None` is a first-class answer that every
/// caller must treat as silence rather than as an empty list. A front end
/// with no such table at all answers `None` to everything, which leaves
/// those two rules quiet and every other rule exactly where it was.
fn module_interface(&self, _name: &str) -> Option<ModuleInterface> {
None
}
}
/// The names a module or interface declares that an instantiation may write.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ModuleInterface {
/// Port names, as written.
pub ports: Vec<String>,
/// Overridable parameter names, as written — a `localparam` is not one.
pub parameters: Vec<String>,
}
impl ModuleInterface {
/// Whether the unit declares a port called `name`.
pub fn has_port(&self, name: &str) -> bool {
self.ports.iter().any(|port| port == name)
}
/// Whether the unit declares an overridable parameter called `name`.
pub fn has_parameter(&self, name: &str) -> bool {
self.parameters.iter().any(|parameter| parameter == name)
}
}
/// Where a context's symbol table comes from: lent by a caller that already
@@ -134,6 +180,12 @@ pub trait MentionOracle: Sync {
/// Lazy rather than eager because most rules are syntactic: a run with no
/// semantic rule enabled — which is every default `lucisv check`, since all
/// three semantic rules ship off — must not pay for an analysis nobody reads.
// The `Lazy` variant is the table itself, held inline on purpose: it is one
// per lint run, it is written exactly once, and boxing it would add an
// allocation to the path that already avoided one by not analyzing at all.
// `Semantics` grew past clippy's variant-size threshold when it gained its
// `duplicates` table (§33.2); nothing about the trade changed with it.
#[allow(clippy::large_enum_variant)]
enum SemanticsSlot<'a> {
Lent(&'a Semantics),
Lazy(OnceCell<Semantics>),
@@ -156,6 +208,9 @@ pub struct LintContext<'a> {
/// The signal table the semantic rules read, built once for all of them
/// the first time one asks — and never for a run with none enabled.
signals: OnceCell<Signals>,
/// Whether the tolerant parse produced no `Error` leaf, answered once for
/// the rules that read structure. See [`LintContext::parsed_cleanly`].
clean: OnceCell<bool>,
/// What the workspace says about a name, when the caller has a workspace.
/// `None` is a run that cannot see other files — a single-file
/// `lucisv check`, stdin, a unit test — and every rule that would consult
@@ -202,6 +257,7 @@ impl<'a> LintContext<'a> {
strings: Vec::new(),
semantics: SemanticsSlot::Lazy(OnceCell::new()),
signals: OnceCell::new(),
clean: OnceCell::new(),
oracle: None,
};
ctx.strings =
@@ -245,6 +301,13 @@ impl<'a> LintContext<'a> {
self.oracle.is_some_and(|oracle| oracle.mentioned_elsewhere(name))
}
/// What the project says the unit `name` declares. `None` — no oracle, no
/// such unit, or two that disagree — means the run cannot answer, and a
/// rule that asked must then say nothing.
pub fn module_interface(&self, name: &str) -> Option<ModuleInterface> {
self.oracle?.module_interface(name)
}
/// Whether this run can see other files at all.
pub fn has_oracle(&self) -> bool {
self.oracle.is_some()
@@ -266,6 +329,32 @@ impl<'a> LintContext<'a> {
self.signals.get_or_init(|| Signals::scan(self))
}
/// Whether the whole file fit the grammar — no `Error` leaf anywhere in
/// the tolerant parse.
///
/// The tolerant parse is what makes a text rule work in a half-written
/// buffer, and most rules are right to ignore the difference. A rule that
/// reads **structure** is not: error recovery unwinds out of the construct
/// it failed in, so the declarations that followed are bound in whatever
/// scope recovery landed in — a class method's locals end up at file
/// scope, and every one of them looks like a redeclaration of the last
/// method's. Measured on opentitan: `spi_device_scoreboard.sv` (454 parse
/// errors, a macro-heavy UVM file) produced sixteen such phantoms, which
/// is sixteen wrong accusations from one file. A rule that would rather be
/// silent than wrong asks this first.
pub fn parsed_cleanly(&self) -> bool {
*self.clean.get_or_init(|| {
let mut clean = true;
crate::visit::walk_items(self.file(), &mut |item| {
clean &= !matches!(item.kind, vlog_parser::ast::ItemKind::Error(_));
});
crate::visit::walk_all_stmts(self.file(), &mut |stmt| {
clean &= !matches!(stmt.kind, vlog_parser::ast::StmtKind::Error(_));
});
clean
})
}
/// The source text being linted.
pub fn source(&self) -> &str {
match &self.backing {
+229
View File
@@ -0,0 +1,229 @@
//! Every declared type and every dimension in a file.
//!
//! A `DataType` is written in a dozen places — a port, a parameter, a
//! declarator, a typedef's base, a struct member, a subroutine's return type
//! and its arguments — and the rules that judge a *type* (the packed-dimension
//! ordering, a negative array bound) care about all of them equally. Collecting
//! them lives here rather than in `visit`, which is about the item and
//! statement spines; keeping the two apart is what stops either file from
//! becoming "everything a rule might want to walk".
use vlog_parser::ast::{
DataType, Dim, EnumType, FunctionDecl, ItemKind, SourceFile, StmtKind, StructType, TaskDecl,
TfArg, TypeExtra, TypedefKind,
};
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
/// Where a dimension was written. The two are different constructs with
/// different conventions — `[N-1:0]` for a packed vector, `[N]` for an array —
/// so a rule that judges one must not judge the other by accident.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Packing {
/// Written before the declared name: a vector's width.
Packed,
/// Written after it: an array's extent.
Unpacked,
}
/// Calls `f` on every data type written in the file, an anonymous aggregate's
/// members and base included.
pub(crate) fn walk_data_types(file: &SourceFile, f: &mut dyn FnMut(&DataType)) {
let mut visit = |ty: &DataType| descend(ty, f);
walk_param_ports(file, &mut |port| visit(&port.ty));
walk_items(file, &mut |item| match &item.kind {
ItemKind::Module(module) => {
if let vlog_parser::ast::PortList::Ansi(ports) = &module.ports {
for port in ports {
visit(&port.ty);
}
}
}
ItemKind::Typedef(typedef) => typedef_types(&typedef.kind, &mut visit),
ItemKind::ParamDecl(decl) => visit(&decl.ty),
ItemKind::DataDecl(decl) => visit(&decl.ty),
ItemKind::PortDecl(decl) => visit(&decl.ty),
ItemKind::Function(decl) => function_types(decl, &mut visit),
ItemKind::Task(decl) => task_types(decl, &mut visit),
_ => {}
});
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
StmtKind::VarDecl(decl) => visit(&decl.ty),
StmtKind::ParamDecl(decl) => visit(&decl.ty),
StmtKind::PortDecl(decl) => visit(&decl.ty),
StmtKind::Typedef(typedef) => typedef_types(&typedef.kind, &mut visit),
_ => {}
});
}
/// Calls `f` on every dimension in the file, saying which kind it is.
pub(crate) fn walk_dims(file: &SourceFile, f: &mut dyn FnMut(Packing, &Dim)) {
walk_data_types(file, &mut |ty| {
for dim in &ty.packed {
f(Packing::Packed, dim);
}
});
walk_unpacked(file, f);
}
/// The unpacked half: the `[…]` written *after* a declared name.
fn walk_unpacked(file: &SourceFile, f: &mut dyn FnMut(Packing, &Dim)) {
let mut unpacked = |dims: &[Dim]| {
for dim in dims {
f(Packing::Unpacked, dim);
}
};
walk_param_ports(file, &mut |port| unpacked(&port.unpacked));
walk_items(file, &mut |item| match &item.kind {
ItemKind::Module(module) => {
if let vlog_parser::ast::PortList::Ansi(ports) = &module.ports {
for port in ports {
unpacked(&port.unpacked);
}
}
}
ItemKind::Typedef(typedef) => unpacked(&typedef.unpacked),
ItemKind::ParamDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
ItemKind::DataDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
ItemKind::PortDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
ItemKind::Function(decl) => arg_dims(&decl.args, &mut unpacked),
ItemKind::Task(decl) => arg_dims(&decl.args, &mut unpacked),
_ => {}
});
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
StmtKind::VarDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
StmtKind::ParamDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
StmtKind::PortDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
StmtKind::Typedef(typedef) => unpacked(&typedef.unpacked),
_ => {}
});
}
fn declarator_dims(declarators: &[vlog_parser::ast::Declarator], unpacked: &mut dyn FnMut(&[Dim])) {
for declarator in declarators {
unpacked(&declarator.unpacked);
}
}
fn arg_dims(args: &[TfArg], unpacked: &mut dyn FnMut(&[Dim])) {
for arg in args {
unpacked(&arg.unpacked);
}
}
fn typedef_types(kind: &TypedefKind, visit: &mut dyn FnMut(&DataType)) {
match kind {
TypedefKind::Alias(ty) => visit(ty),
TypedefKind::Enum(enum_ty) => enum_types(enum_ty, visit),
TypedefKind::Struct(struct_ty) => struct_types(struct_ty, visit),
TypedefKind::ForwardClass => {}
}
}
fn function_types(decl: &FunctionDecl, visit: &mut dyn FnMut(&DataType)) {
if let Some(ret) = &decl.ret {
visit(ret);
}
for arg in &decl.args {
visit(&arg.ty);
}
}
fn task_types(decl: &TaskDecl, visit: &mut dyn FnMut(&DataType)) {
for arg in &decl.args {
visit(&arg.ty);
}
}
fn enum_types(enum_ty: &EnumType, visit: &mut dyn FnMut(&DataType)) {
if let Some(base) = &enum_ty.base {
visit(base);
}
}
fn struct_types(struct_ty: &StructType, visit: &mut dyn FnMut(&DataType)) {
for member in &struct_ty.members {
visit(&member.ty);
}
}
/// One type and whatever aggregate it *is*: an anonymous `enum`'s base and an
/// anonymous `struct`'s members are types written inside this one.
fn descend(ty: &DataType, f: &mut dyn FnMut(&DataType)) {
f(ty);
match ty.inline() {
Some(TypeExtra::Enum(enum_ty)) => enum_types(enum_ty, &mut |inner| descend(inner, f)),
Some(TypeExtra::Struct(struct_ty)) => {
struct_types(struct_ty, &mut |inner| descend(inner, f))
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::parse_source_tolerant;
fn packed_widths(src: &str) -> Vec<String> {
let (file, _) = parse_source_tolerant(src);
let mut out = Vec::new();
walk_dims(&file, &mut |packing, dim| {
if packing == Packing::Packed {
out.push(src[dim.span.as_range()].to_string());
}
});
out
}
fn unpacked_extents(src: &str) -> Vec<String> {
let (file, _) = parse_source_tolerant(src);
let mut out = Vec::new();
walk_dims(&file, &mut |packing, dim| {
if packing == Packing::Unpacked {
out.push(src[dim.span.as_range()].to_string());
}
});
out
}
#[test]
fn reaches_the_packed_dimensions_of_every_declaration_shape() {
let src = "module m #(parameter logic [1:0] P = 0) (\n\
input logic [2:0] a\n\
);\n\
logic [3:0] b;\n\
typedef logic [4:0] w_t;\n\
function logic [5:0] f(input logic [6:0] x);\n\
logic [7:0] local_v;\n\
return 0;\n\
endfunction\n\
endmodule\n";
assert_eq!(
packed_widths(src),
vec!["[1:0]", "[2:0]", "[3:0]", "[4:0]", "[5:0]", "[6:0]", "[7:0]"]
);
}
#[test]
fn reaches_an_anonymous_aggregates_members_and_base() {
let src = "module m;\n\
struct packed { logic [1:0] a; logic [2:0] b; } s;\n\
enum logic [3:0] { A } e;\n\
endmodule\n";
assert_eq!(packed_widths(src), vec!["[1:0]", "[2:0]", "[3:0]"]);
}
#[test]
fn packed_and_unpacked_are_told_apart() {
let src = "module m;\n logic [1:0] q [4];\nendmodule\n";
assert_eq!(packed_widths(src), vec!["[1:0]"]);
assert_eq!(unpacked_extents(src), vec!["[4]"]);
}
#[test]
fn a_struct_member_is_reached_through_a_typedef() {
let src = "typedef struct packed {\n logic [9:0] wide;\n} w_t;\n";
assert_eq!(packed_widths(src), vec!["[9:0]"]);
}
}
+178
View File
@@ -0,0 +1,178 @@
//! What each module in one file declares that an instantiation may name.
//!
//! The language server answers [`MentionOracle::module_interface`] from its
//! workspace index, which already records every module's ports and parameters.
//! `lucisv check` has no index, so it reads the same facts off the parse it
//! makes anyway — this file is that reading, and it lives here so the CLI and
//! the linter cannot come to disagree about what "a port of this module" is.
//!
//! Erring is one-directional on purpose: a unit whose header lucisv cannot see
//! whole is reported as **unknowable** rather than as a short list, because a
//! short list is what turns a legal connection into an accusation.
use vlog_parser::ast::{ItemKind, Module, ParamPort, PortList, SourceFile};
use crate::context::ModuleInterface;
use crate::visit::walk_items;
/// Every module, interface and program the file declares, with what it
/// exposes. `None` for a unit whose header cannot be read whole.
///
/// A file may declare a name twice (two `` `ifdef`` arms, a copy-paste); the
/// caller merges across files and must treat any disagreement as unknowable,
/// so both entries are returned rather than one.
pub fn module_interfaces(file: &SourceFile) -> Vec<(String, Option<ModuleInterface>)> {
let mut out = Vec::new();
walk_items(file, &mut |item| {
if let ItemKind::Module(module) = &item.kind {
out.push((module.name.clone(), interface_of(module)));
}
});
out
}
/// One unit's surface, or `None` when its header is not fully visible.
fn interface_of(module: &Module) -> Option<ModuleInterface> {
// A directive written *between* ports or parameters may be a conditional
// — whose arms are all in the list, so the list stays a superset — or a
// macro invocation standing where a port belongs, whose expansion lucisv
// never sees. Telling the two apart would be a second preprocessor; a
// header with any directive in it is simply not answered for.
if !module.port_directives.is_empty() || !module.param_directives.is_empty() {
return None;
}
Some(ModuleInterface { ports: ports_of(module), parameters: parameters_of(module) })
}
/// The port names of either header style. A header with no port list at all
/// declares none, which is a fact rather than a gap: nothing may be connected
/// to it by name.
fn ports_of(module: &Module) -> Vec<String> {
match &module.ports {
PortList::Ansi(ports) => ports.iter().map(|port| port.name.clone()).collect(),
PortList::NonAnsi(ports) => ports.iter().map(|port| port.name.clone()).collect(),
PortList::None | PortList::Empty => Vec::new(),
}
}
/// The names an `#(.NAME(value))` override may write: every `parameter` in the
/// header and in the body.
///
/// A `localparam` is **not** one — it is the module's own constant and is not
/// overridable (IEEE 1800 §6.20.4), which is exactly the distinction
/// `SymbolKind::LocalParam` was parted out for. A header parameter written
/// without a keyword continues the previous declaration and inherits its
/// keyword, which is how `#(parameter int A = 1, B = 2)` declares two
/// overridable parameters.
fn parameters_of(module: &Module) -> Vec<String> {
let mut out = Vec::new();
let mut overridable = true;
for port in module.param_ports.iter().flatten() {
overridable = is_parameter(port, overridable);
if overridable {
out.push(port.name.clone());
}
}
for item in &module.items {
if let ItemKind::ParamDecl(decl) = &item.kind {
if decl.kw == "parameter" {
out.extend(decl.declarators.iter().map(|d| d.name.clone()));
}
}
}
out
}
/// Whether this header parameter is overridable, given whether the one before
/// it was: a written keyword decides, and no keyword continues.
fn is_parameter(port: &ParamPort, previous: bool) -> bool {
match port.kw.as_deref() {
Some("localparam") => false,
Some(_) => true,
None => previous,
}
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::parse_source_tolerant;
fn interfaces(src: &str) -> Vec<(String, Option<ModuleInterface>)> {
let (file, _) = parse_source_tolerant(src);
module_interfaces(&file)
}
fn only(src: &str) -> ModuleInterface {
let found = interfaces(src);
assert_eq!(found.len(), 1, "{found:?}");
found.into_iter().next().and_then(|(_, i)| i).expect("a readable header")
}
#[test]
fn reads_an_ansi_header() {
let read = only(
"module m #(parameter int Width = 8, localparam int Derived = Width + 1) (\n\
input logic clk_i,\n\
output logic [7:0] data_o\n\
);\n\
endmodule\n",
);
assert_eq!(read.ports, vec!["clk_i", "data_o"]);
assert_eq!(read.parameters, vec!["Width"], "a localparam is not overridable");
}
#[test]
fn reads_a_non_ansi_header() {
let read = only("module m (clk, rst_n);\n input clk;\n input rst_n;\nendmodule\n");
assert_eq!(read.ports, vec!["clk", "rst_n"]);
}
#[test]
fn a_continuation_parameter_inherits_its_keyword() {
let read = only("module m #(parameter int A = 1, B = 2) ();\nendmodule\n");
assert_eq!(read.parameters, vec!["A", "B"]);
let local = only("module m #(localparam int A = 1, B = 2) ();\nendmodule\n");
assert!(local.parameters.is_empty(), "both continue the localparam");
}
#[test]
fn a_body_parameter_is_overridable_and_a_body_localparam_is_not() {
let read =
only("module m ();\n parameter int Depth = 4;\n localparam int W = 2;\nendmodule\n");
assert_eq!(read.parameters, vec!["Depth"]);
}
#[test]
fn a_header_with_a_directive_in_it_is_unknowable() {
let src = "module m (\n\
`ifdef X\n\
input logic a,\n\
`endif\n\
input logic b\n\
);\n\
endmodule\n";
assert_eq!(interfaces(src), vec![("m".to_string(), None)]);
}
#[test]
fn a_port_less_module_declares_no_ports() {
let read = only("module m;\nendmodule\n");
assert!(read.ports.is_empty());
assert!(read.parameters.is_empty());
let empty = only("module m ();\nendmodule\n");
assert!(empty.ports.is_empty());
}
#[test]
fn an_interface_is_read_the_same_way() {
let read = only("interface bus_if (input logic clk);\nendinterface\n");
assert_eq!(read.ports, vec!["clk"]);
}
#[test]
fn every_unit_of_a_file_is_returned() {
let found = interfaces("module a ();\nendmodule\nmodule b ();\nendmodule\n");
assert_eq!(found.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(), vec!["a", "b"]);
}
}
+48 -2
View File
@@ -21,26 +21,36 @@
//! `docs/features/linter-core/README.md`.
mod context;
mod decls;
mod interfaces;
mod literal;
mod naming;
mod registry;
mod rule_docs;
mod rules;
mod severity;
mod signals;
mod violation;
mod visit;
mod vscode;
mod waiver;
use std::path::PathBuf;
pub use context::{LintContext, MentionOracle, ParsedSource};
pub use registry::{all_rules, default_rules, rule_by_name, select_rules, workspace_rules, Rule};
pub use context::{LintContext, MentionOracle, ModuleInterface, ParsedSource};
pub use interfaces::module_interfaces;
pub use registry::{
all_rules, default_rules, rule_by_name, rules_named, select_rules, workspace_rules, Rule,
};
pub use rule_docs::rules_markdown;
pub use severity::Severity;
pub use violation::{apply_fixes, Applicability, Fix, Fixed, Violation};
/// The identifier census a [`MentionOracle`] is answered from, re-exported
/// from `vlog_semantic` so a front end that implements the oracle needs this
/// crate alone. One harvest for the whole workspace — see
/// `docs/features/semantic-lints-on/README.md`.
pub use vlog_semantic::words;
pub use vscode::{rule_setting, severity_setting, vscode_lint_settings, RULE_CHOICES};
pub use waiver::UNUSED_WAIVER;
use waiver::Waivers;
@@ -87,9 +97,24 @@ pub fn lint(ctx: &LintContext, enabled: &[&'static dyn Rule]) -> Vec<Violation>
kept.sort_by(|a, b| {
(a.span.start, a.span.end, a.rule).cmp(&(b.span.start, b.span.end, b.rule))
});
stamp_severities(&mut kept);
kept
}
/// Gives every finding the class its rule declares.
///
/// One place rather than one per rule: a rule's `check` builds violations
/// without knowing what it is called, the `unused-waiver` findings are built by
/// the waiver scanner and not by a rule at all, and a severity written twice
/// would eventually be written differently. See [`Violation::severity`].
fn stamp_severities(violations: &mut [Violation]) {
for violation in violations {
if let Some(rule) = rule_by_name(violation.rule) {
violation.severity = rule.severity();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -211,6 +236,27 @@ mod tests {
assert!(run(src, None, &enabled).is_empty());
}
/// Every finding the runner returns carries its rule's class — including
/// the `unused-waiver` ones, which no rule's `check` produced.
#[test]
fn the_runner_stamps_every_finding_with_its_rules_severity() {
let src = "module m;\n\
\treg a; // lucisv: waive no-such-rule\n\
\talways_comb a <= 1'b0;\n\
endmodule\n";
let found = run(src, Some(PathBuf::from("rtl/m.sv")), &default_rules());
assert!(found.len() >= 3, "{found:#?}");
for violation in &found {
let rule = rule_by_name(violation.rule).expect("a registered rule");
assert_eq!(violation.severity, rule.severity(), "{}", violation.rule);
}
let by_rule =
|name: &str| found.iter().find(|v| v.rule == name).map(|v| v.severity).expect(name);
assert_eq!(by_rule("wire-reg-mixup"), Severity::Error);
assert_eq!(by_rule("always-comb-blocking"), Severity::Warning);
assert_eq!(by_rule(UNUSED_WAIVER), Severity::Style);
}
#[test]
fn a_file_that_does_not_parse_still_gets_its_text_rules() {
let src = "module m;\n\t@@@ this is not verilog\nendmodule\n";
+156
View File
@@ -0,0 +1,156 @@
//! Sized based literals, read the way the two width rules need them.
//!
//! `truncated-numeric-literal` asks "how many bits does what is written
//! actually need?" and `undersized-binary-literal` asks "how many digits were
//! written?". Both questions are about the same `<size>'<base><digits>` shape,
//! so it is parsed once here rather than twice, slightly differently.
/// One `<size>'[s]<base><digits>` literal, as written.
///
/// Only the *sized* spelling is modelled: an unsized `'h1f` takes its width
/// from context, so neither rule has anything to compare against and
/// [`parse`] returns `None` for it.
pub(crate) struct SizedLiteral<'a> {
/// The declared width, in bits.
pub width: u32,
/// The base letter, lower-cased: `b`, `o`, `d` or `h`.
pub base: char,
/// The digits as written, `_` separators included.
pub digits: &'a str,
}
impl SizedLiteral<'_> {
/// The digits with the `_` separators taken out.
pub fn packed_digits(&self) -> String {
self.digits.chars().filter(|c| *c != '_').collect()
}
/// How many bits the written value really needs, or `None` when that
/// cannot be said: an empty or malformed digit run, or a decimal value
/// carrying `x`/`z`.
///
/// A digit that is `x`, `z` or `?` counts as full-width — `4'hxF` needs
/// eight bits, because the unknown nibble is still a nibble.
pub fn significant_bits(&self) -> Option<u32> {
let digits = self.packed_digits();
let digits = digits.trim_start_matches('0');
if digits.is_empty() {
return Some(0);
}
let Some(per_digit) = bits_per_digit(self.base) else {
// Decimal: the whole run is one number, so an `x` in it makes the
// value unknown rather than one unknown digit.
let value: u128 = digits.parse().ok()?;
return Some(128 - value.leading_zeros());
};
let mut chars = digits.chars();
let first = chars.next()?;
let rest = chars.count() as u32;
let head = match first.to_ascii_lowercase() {
'x' | 'z' | '?' => per_digit,
c => bits_of(c, self.base)?,
};
Some(rest * per_digit + head)
}
}
/// Reads a sized based literal, or `None` for anything else — an unsized
/// literal, a plain decimal, a real, a time literal.
pub(crate) fn parse(text: &str) -> Option<SizedLiteral<'_>> {
let (size, rest) = text.split_once('\'')?;
let width: u32 = size.chars().filter(|c| *c != '_').collect::<String>().parse().ok()?;
// `8'sh1f` — the signedness marker sits between the tick and the base.
let rest = rest.strip_prefix(['s', 'S']).unwrap_or(rest);
let mut chars = rest.chars();
let base = chars.next()?.to_ascii_lowercase();
if !matches!(base, 'b' | 'o' | 'd' | 'h') {
return None;
}
let digits = rest.get(1..)?;
if digits.is_empty() || !digits.chars().all(|c| is_digit_of(c, base) || c == '_') {
return None;
}
Some(SizedLiteral { width, base, digits })
}
/// How many bits one digit of `base` carries; `None` for decimal, which is not
/// a per-digit base at all.
fn bits_per_digit(base: char) -> Option<u32> {
match base {
'b' => Some(1),
'o' => Some(3),
'h' => Some(4),
_ => None,
}
}
/// How many bits one known digit's value needs (`7` needs three, `1` needs
/// one), or `None` when the character is not a digit of this base.
fn bits_of(c: char, base: char) -> Option<u32> {
let value = c.to_digit(16)?;
let per_digit = bits_per_digit(base)?;
if value >= 1 << per_digit {
return None;
}
Some(32 - value.leading_zeros())
}
/// True when `c` may stand among `base`'s digits, unknowns included.
fn is_digit_of(c: char, base: char) -> bool {
let c = c.to_ascii_lowercase();
if matches!(c, 'x' | 'z' | '?') {
return true;
}
match base {
'b' => matches!(c, '0' | '1'),
'o' => c.is_digit(8),
'd' => c.is_ascii_digit(),
_ => c.is_ascii_hexdigit(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn bits(text: &str) -> Option<u32> {
parse(text)?.significant_bits()
}
#[test]
fn a_sized_literal_is_read_in_every_base() {
for (text, width, base, digits) in [
("8'hFF", 8, 'h', "FF"),
("4'b1010", 4, 'b', "1010"),
("3'o7", 3, 'o', "7"),
("16'd1000", 16, 'd', "1000"),
("8'sh1f", 8, 'h', "1f"),
("32'hdead_beef", 32, 'h', "dead_beef"),
] {
let found = parse(text).unwrap_or_else(|| panic!("{text}"));
assert_eq!((found.width, found.base, found.digits), (width, base, digits), "{text}");
}
}
#[test]
fn anything_that_is_not_a_sized_based_literal_is_declined() {
for text in ["'h1f", "42", "1.5", "10ns", "8'", "8'q1", "8'h", "8'hG", "'0"] {
assert!(parse(text).is_none(), "{text}");
}
}
#[test]
fn significant_bits_counts_what_is_written() {
assert_eq!(bits("4'h0"), Some(0));
assert_eq!(bits("4'h1"), Some(1));
assert_eq!(bits("4'h8"), Some(4));
assert_eq!(bits("4'hFFF"), Some(12), "three full nibbles");
assert_eq!(bits("8'b0000_0001"), Some(1), "leading zeros do not count");
assert_eq!(bits("4'o7"), Some(3));
assert_eq!(bits("8'd255"), Some(8));
assert_eq!(bits("8'd256"), Some(9));
assert_eq!(bits("4'hx"), Some(4), "an unknown nibble is still a nibble");
assert_eq!(bits("4'h0x"), Some(4), "and leading zeros still do not count");
assert_eq!(bits("8'dx"), None, "a decimal unknown says nothing about width");
}
}
+155 -11
View File
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::rules;
use crate::severity::Severity;
use crate::violation::{Applicability, Violation};
/// One lint rule.
@@ -17,6 +18,14 @@ pub trait Rule: Sync {
/// One line, imperative, no trailing period.
fn summary(&self) -> &'static str;
/// How bad this rule's findings are.
///
/// Deliberately without a default: a class is a claim about what a finding
/// means to the user, and a rule that inherited one silently would be
/// making that claim by accident. The reason for the class chosen belongs
/// in [`Rule::doc`].
fn severity(&self) -> Severity;
/// Why the rule exists — the style-guide rationale, in prose.
fn doc(&self) -> &'static str;
@@ -60,19 +69,38 @@ pub fn all_rules() -> Vec<&'static dyn Rule> {
&rules::always_comb_blocking::AlwaysCombBlocking,
&rules::always_ff_non_blocking::AlwaysFfNonBlocking,
&rules::case_missing_default::CaseMissingDefault,
&rules::duplicate_declaration::DuplicateDeclaration,
&rules::empty_item::EmptyItem,
&rules::enum_name_style::EnumNameStyle,
&rules::explicit_function_task_parameter_type::ExplicitFunctionTaskParameterType,
&rules::explicit_parameter_storage_type::ExplicitParameterStorageType,
&rules::forbid_defparam::ForbidDefparam,
&rules::forbid_negative_array_dim::ForbidNegativeArrayDim,
&rules::incomplete_assignment::IncompleteAssignment,
&rules::instance_shadowing::InstanceShadowing,
&rules::invalid_system_task_function::InvalidSystemTaskFunction,
&rules::mismatched_labels::MismatchedLabels,
&rules::module_filename::ModuleFilename,
&rules::module_name_style::ModuleNameStyle,
&rules::module_parameter::ModuleParameter,
&rules::module_port::ModulePort,
&rules::multiply_driven::MultiplyDriven,
&rules::no_tabs::NoTabs,
&rules::no_trailing_whitespace::NoTrailingWhitespace,
&rules::packed_dimensions_range_ordering::PackedDimensionsRangeOrdering,
&rules::parameter_name_style::ParameterNameStyle,
&rules::plusarg_assignment::PlusargAssignment,
&rules::struct_union_name_style::StructUnionNameStyle,
&rules::suspicious_semicolon::SuspiciousSemicolon,
&rules::truncated_numeric_literal::TruncatedNumericLiteral,
&rules::undeclared_identifier::UndeclaredIdentifier,
&rules::undersized_binary_literal::UndersizedBinaryLiteral,
&rules::undriven_net::UndrivenNet,
&rules::unknown_parameter::UnknownParameter,
&rules::unknown_port::UnknownPort,
&rules::unused_signal::UnusedSignal,
&rules::unused_waiver::UnusedWaiver,
&rules::void_cast::VoidCast,
&rules::wire_reg_mixup::WireRegMixup,
]
}
@@ -112,10 +140,25 @@ pub fn rule_by_name(name: &str) -> Option<&'static dyn Rule> {
all_rules().into_iter().find(|rule| rule.name() == name)
}
/// The rules one `--select` / `--ignore` name stands for.
///
/// A rule name stands for itself; a **severity name** (`error`, `warning`,
/// `style`) stands for every rule of that class, so `--ignore style` is one
/// word for the whole family. `None` for a name that is neither, which is what
/// makes a typo a failed run rather than a silently empty selection.
pub fn rules_named(name: &str) -> Option<Vec<&'static dyn Rule>> {
if let Some(rule) = rule_by_name(name) {
return Some(vec![rule]);
}
let severity = Severity::from_name(name)?;
Some(all_rules().into_iter().filter(|rule| rule.severity() == severity).collect())
}
/// The rules a run should use: `select` replaces the default set (empty means
/// keep it), then `ignore` removes from whatever is left. An unknown name on
/// either list is an error rather than a silent no-op — a typo'd `--select`
/// that quietly ran everything would be worse than a failed run.
/// keep it), then `ignore` removes from whatever is left. Either list may name
/// a rule or a whole severity ([`rules_named`]). An unknown name on either
/// list is an error rather than a silent no-op — a typo'd `--select` that
/// quietly ran everything would be worse than a failed run.
///
/// `workspace` only reaches [`default_rules`]: an explicit `select` names the
/// rules it wants and gets them, oracle or no oracle, exactly as an explicit
@@ -128,25 +171,27 @@ pub fn select_rules(
let mut chosen = if select.is_empty() {
enabled_rules(workspace)
} else {
let mut chosen = Vec::new();
let mut chosen: Vec<&'static dyn Rule> = Vec::new();
for name in select {
let rule = rule_by_name(name).ok_or_else(|| unknown(name))?;
if !chosen.iter().any(|r: &&'static dyn Rule| r.name() == rule.name()) {
chosen.push(rule);
for rule in rules_named(name).ok_or_else(|| unknown(name))? {
if !chosen.iter().any(|r| r.name() == rule.name()) {
chosen.push(rule);
}
}
}
chosen
};
for name in ignore {
rule_by_name(name).ok_or_else(|| unknown(name))?;
chosen.retain(|rule| rule.name() != name);
let dropped = rules_named(name).ok_or_else(|| unknown(name))?;
chosen.retain(|rule| !dropped.iter().any(|d| d.name() == rule.name()));
}
Ok(chosen)
}
fn unknown(name: &str) -> String {
let known = all_rules().iter().map(|r| r.name()).collect::<Vec<_>>().join(", ");
format!("unknown rule: {name} (known rules: {known})")
let severities = Severity::ALL.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
format!("unknown rule: {name} (severities: {severities}; known rules: {known})")
}
#[cfg(test)]
@@ -211,7 +256,17 @@ mod tests {
let project: Vec<&str> = workspace_rules().iter().map(|r| r.name()).collect();
let added: Vec<&str> =
project.iter().copied().filter(|name| !alone.contains(name)).collect();
assert_eq!(added, vec!["multiply-driven", "undriven-net", "unused-signal"]);
assert_eq!(
added,
vec![
"multiply-driven",
"undeclared-identifier",
"undriven-net",
"unknown-parameter",
"unknown-port",
"unused-signal",
]
);
assert!(alone.iter().all(|name| project.contains(name)), "a workspace never removes one");
for rule in all_rules() {
assert_eq!(rule.needs_workspace(), added.contains(&rule.name()), "{}", rule.name());
@@ -283,6 +338,95 @@ mod tests {
assert!(message.contains("no-tabs"), "the error must list what is known: {message}");
}
/// Every rule states a class, and no rule name collides with a class
/// name — otherwise `--select error` would mean two things.
#[test]
fn every_rule_has_a_severity_and_no_name_shadows_a_class() {
for rule in all_rules() {
assert!(Severity::ALL.contains(&rule.severity()), "{}", rule.name());
assert!(
Severity::from_name(rule.name()).is_none(),
"{} shadows a severity word",
rule.name()
);
}
}
/// The assignments §33.0 wrote down for the seventeen rules that predate
/// severities. A rule moving class is a user-visible change, so it moves
/// here first.
#[test]
fn the_original_seventeen_keep_the_classes_they_were_given() {
let expected: &[(&str, Severity)] = &[
("multiply-driven", Severity::Error),
("wire-reg-mixup", Severity::Error),
("always-comb-blocking", Severity::Warning),
("always-ff-non-blocking", Severity::Warning),
("case-missing-default", Severity::Warning),
("undriven-net", Severity::Warning),
("unused-signal", Severity::Warning),
("empty-item", Severity::Style),
("enum-name-style", Severity::Style),
("explicit-parameter-storage-type", Severity::Style),
("module-filename", Severity::Style),
("module-name-style", Severity::Style),
("no-tabs", Severity::Style),
("no-trailing-whitespace", Severity::Style),
("parameter-name-style", Severity::Style),
("struct-union-name-style", Severity::Style),
("unused-waiver", Severity::Style),
];
for (name, severity) in expected {
let rule = rule_by_name(name).unwrap_or_else(|| panic!("{name} exists"));
assert_eq!(rule.severity(), *severity, "{name}");
}
}
#[test]
fn a_severity_name_stands_for_every_rule_of_that_class() {
for severity in Severity::ALL {
let named = rules_named(severity.as_str()).unwrap_or_default();
let expected: Vec<&str> = all_rules()
.into_iter()
.filter(|rule| rule.severity() == severity)
.map(|rule| rule.name())
.collect();
assert_eq!(named.iter().map(|r| r.name()).collect::<Vec<_>>(), expected);
assert!(!expected.is_empty(), "{severity:?} has no rules");
}
assert!(rules_named("no-tabs").is_some_and(|rules| rules.len() == 1));
assert!(rules_named("no-such-thing").is_none());
}
/// `--select style`, `--ignore warning`: the whole point of the words.
#[test]
fn select_and_ignore_accept_a_severity_wherever_a_rule_fits() {
let styled = select_rules(&["style".to_string()], &[], true).unwrap();
assert!(styled.iter().all(|rule| rule.severity() == Severity::Style));
assert!(styled.iter().any(|rule| rule.name() == "no-tabs"));
let quiet = select_rules(&[], &["style".to_string()], true).unwrap();
assert!(quiet.iter().all(|rule| rule.severity() != Severity::Style));
assert!(quiet.iter().any(|rule| rule.name() == "unused-signal"), "warnings survive");
// A severity and a rule name mix on one list, and the same rule named
// twice is still selected once.
let mixed =
select_rules(&["style".to_string(), "no-tabs".to_string()], &[], false).unwrap();
assert_eq!(mixed.iter().filter(|rule| rule.name() == "no-tabs").count(), 1);
// Ignoring a class removes it from an explicit selection too.
let none = select_rules(&["no-tabs".to_string()], &["style".to_string()], false).unwrap();
assert!(none.is_empty());
}
#[test]
fn the_unknown_name_error_names_the_severity_words_too() {
let message = select_rules(&["styles".to_string()], &[], false).err().unwrap_or_default();
assert!(message.contains("style"), "{message}");
assert!(message.contains("no-tabs"), "{message}");
}
#[test]
fn lookup_by_name_finds_every_rule_and_nothing_else() {
for rule in all_rules() {
+78 -18
View File
@@ -7,6 +7,7 @@
//! this.
use crate::registry::all_rules;
use crate::severity::Severity;
/// The whole rule reference as one markdown document.
pub fn rules_markdown() -> String {
@@ -15,6 +16,12 @@ pub fn rules_markdown() -> String {
out.push_str(
"Generated from the rule registry by `vlog_linter::rules_markdown` — \
do not edit by hand.\n\n\
Every rule is in one of three **severity** classes, and the class is \
a word `--select` and `--ignore` accept wherever a rule name fits \
(`--ignore style`, `--select error`). **error** is code that would \
very likely fail to compile, elaborate or synthesize; **warning** is \
code that compiles but very likely does not mean what it says; \
**style** is code that is correct and reads badly.\n\n\
A rule marked **on** runs for a plain `lucisv check`; the others need \
`--select <name>`. A rule marked **on (project)** runs by default \
only where lucisv can see the other files of the project — \
@@ -26,23 +33,32 @@ pub fn rules_markdown() -> String {
<name>`.\n\n",
);
out.push_str("| Rule | Default | Fix |\n|---|---|---|\n");
out.push_str("| Rule | Severity | Default | Fix |\n|---|---|---|---|\n");
for rule in all_rules() {
out.push_str(&format!(
"| [`{name}`](#{name}) | {default} | {fix} |\n",
"| [`{name}`](#{name}) | {severity} | {default} | {fix} |\n",
name = rule.name(),
severity = rule.severity().as_str(),
default = default_word(rule),
fix = fix_word(rule),
));
}
out.push('\n');
for rule in all_rules() {
out.push_str(&format!("## {}\n\n", rule.name()));
out.push_str(&format!("{}.\n\n", capitalize(rule.summary())));
out.push_str(&format!("- Default: {}\n- Fix: {}\n\n", default_word(rule), fix_word(rule)));
out.push_str(rule.doc());
out.push_str("\n\n");
for severity in Severity::ALL {
out.push_str(&format!("# {} — {}\n\n", severity.as_str(), severity.describes()));
for rule in all_rules().into_iter().filter(|rule| rule.severity() == severity) {
out.push_str(&format!("## {}\n\n", rule.name()));
out.push_str(&format!("{}.\n\n", capitalize(rule.summary())));
out.push_str(&format!(
"- Severity: {}\n- Default: {}\n- Fix: {}\n\n",
severity.as_str(),
default_word(rule),
fix_word(rule),
));
out.push_str(rule.doc());
out.push_str("\n\n");
}
}
out
}
@@ -98,7 +114,7 @@ mod tests {
fn the_index_lists_every_rule_once() {
let markdown = rules_markdown();
for rule in all_rules() {
let row = format!("| [`{0}`](#{0}) |", rule.name());
let row = format!("| [`{0}`](#{0}) | ", rule.name());
assert_eq!(markdown.matches(&row).count(), 1, "{}", rule.name());
}
}
@@ -106,27 +122,62 @@ mod tests {
#[test]
fn defaults_and_fixes_are_rendered_from_the_registry() {
let markdown = rules_markdown();
assert!(markdown.contains("| [`no-tabs`](#no-tabs) | **on** | safe |"));
assert!(markdown.contains("| [`module-name-style`](#module-name-style) | off | none |"));
assert!(markdown.contains("| [`no-tabs`](#no-tabs) | style | **on** | safe |"));
assert!(
markdown.contains("| [`module-name-style`](#module-name-style) | style | off | none |")
);
// The three semantic rules are fixless, and default on exactly where
// there is a project to ask about a name — see
// docs/features/semantic-lints-on/README.md.
for name in ["multiply-driven", "undriven-net", "unused-signal"] {
for (name, severity) in [
("multiply-driven", "error"),
("undriven-net", "warning"),
("unused-signal", "warning"),
] {
assert!(
markdown.contains(&format!("| [`{name}`](#{name}) | **on (project)** | none |")),
markdown.contains(&format!(
"| [`{name}`](#{name}) | {severity} | **on (project)** | none |"
)),
"{name}"
);
}
assert_eq!(fix_word(&crate::rules::no_tabs::NoTabs), Applicability::Safe.as_str());
}
/// Every rule sits under the heading of its own class, and the three
/// headings are written worst-first.
#[test]
fn the_sections_are_grouped_by_severity() {
let markdown = rules_markdown();
let heading = |severity: Severity| {
markdown
.find(&format!("\n# {} — ", severity.as_str()))
.unwrap_or_else(|| panic!("{severity:?} heading"))
};
let (error, warning, style) =
(heading(Severity::Error), heading(Severity::Warning), heading(Severity::Style));
assert!(error < warning && warning < style, "worst first");
for rule in all_rules() {
let at = markdown
.find(&format!("\n## {}\n", rule.name()))
.unwrap_or_else(|| panic!("{}", rule.name()));
let own = heading(rule.severity());
let next = [error, warning, style]
.into_iter()
.filter(|start| *start > own)
.min()
.unwrap_or(markdown.len());
assert!(own < at && at < next, "{} is under the wrong heading", rule.name());
}
}
#[test]
fn the_document_shape_is_pinned() {
// A golden test on the *shape*, not on the prose: the heading, the
// generated-by note, the index table header, and the first per-rule
// section, which together are what a reader (and any renderer) sees.
let markdown = rules_markdown();
let head: Vec<&str> = markdown.lines().take(8).collect();
let head: Vec<&str> = markdown.lines().take(10).collect();
assert_eq!(
head,
vec![
@@ -135,6 +186,12 @@ mod tests {
"Generated from the rule registry by `vlog_linter::rules_markdown` — do not edit \
by hand.",
"",
"Every rule is in one of three **severity** classes, and the class is a word \
`--select` and `--ignore` accept wherever a rule name fits (`--ignore style`, \
`--select error`). **error** is code that would very likely fail to compile, \
elaborate or synthesize; **warning** is code that compiles but very likely does \
not mean what it says; **style** is code that is correct and reads badly.",
"",
"A rule marked **on** runs for a plain `lucisv check`; the others need \
`--select <name>`. A rule marked **on (project)** runs by default only where \
lucisv can see the other files of the project — `lucisv check <dir>`, or the \
@@ -143,13 +200,16 @@ mod tests {
rule can be turned off with `--ignore <name>`, with `ignore` under `[lint]` in \
`lucisv.toml`, or waived in the source with `// lucisv: waive <name>`.",
"",
"| Rule | Default | Fix |",
"|---|---|---|",
"| Rule | Severity | Default | Fix |",
"|---|---|---|---|",
]
);
let first_rule = all_rules()[0];
let first_rule = all_rules()
.into_iter()
.find(|rule| rule.severity() == Severity::Error)
.expect("some rule is an error");
let section = format!(
"## {}\n\n{}.\n\n- Default: {}\n- Fix: {}\n\n{}\n\n",
"## {}\n\n{}.\n\n- Severity: error\n- Default: {}\n- Fix: {}\n\n{}\n\n",
first_rule.name(),
capitalize(first_rule.summary()),
default_word(first_rule),
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_items, walk_stmts};
use vlog_parser::ast::{ItemKind, StmtKind};
@@ -20,6 +21,10 @@ impl Rule for AlwaysCombBlocking {
"assign with `=` inside always_comb"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A non-blocking assignment in a combinational block schedules its \
update for the end of the time step, so a value read later in the same \
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_items, walk_stmts};
use vlog_parser::ast::{ItemKind, StmtKind};
@@ -20,6 +21,10 @@ impl Rule for AlwaysFfNonBlocking {
"assign with `<=` inside always_ff"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A blocking assignment in a clocked block updates immediately, so two \
flops written in one `always_ff` can see each other's new value in \
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_all_stmts, walk_items};
use vlog_parser::ast::{CaseItem, GenCaseItem, ItemKind, StmtKind};
@@ -21,6 +22,10 @@ impl Rule for CaseMissingDefault {
"give every case statement a default branch"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A case statement with no `default` infers a latch in combinational \
logic and leaves the unlisted patterns unspecified in simulation — the \
@@ -0,0 +1,197 @@
//! `duplicate-declaration` — one name declared twice in one scope.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_semantic::{ScopeKind, SymbolKind};
/// See [`Rule::doc`].
pub struct DuplicateDeclaration;
const NAME: &str = "duplicate-declaration";
impl Rule for DuplicateDeclaration {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"declare each name once per scope"
}
fn severity(&self) -> Severity {
Severity::Error
}
fn doc(&self) -> &'static str {
"Two declarations of one name in one scope is an elaboration error in \
every tool (IEEE 1800 §3.13 — an identifier is unique within its \
namespace and scope). It happens when a signal is copied and the \
paste is not renamed, when two parameters are merged from different \
branches, or when a `logic` is declared beside the `input` of the \
same name. Verible has no equivalent rule; this is TODO §33's own, \
and it is an **Error** because the file will not compile.\n\n\
**Silent whenever the second declaration might be legal**, which is \
the rule every Error-class check here follows. It says nothing when \
either declaration is a **port** — a non-ANSI port is *completed* by \
a body `input clk;` and then by a `logic clk;`, all three of which \
are the same port and all three legal — nor about a function, task, \
class, constraint, covergroup, property, sequence, modport or \
clocking name, each of which has a legal prototype-plus-definition \
or forward-declaration shape. It says nothing inside a `generate` \
scope, where only one arm is ever elaborated, and nothing when a \
conditional-compilation directive stands between the two \
declarations, which is that same exclusivity written for the \
preprocessor. What is left is two ordinary declarations of one name, \
side by side, in one scope. No automatic fix: which of the two the \
author meant to keep is not something a linter can know."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
// Error recovery rebinds whatever followed a construct it could not
// parse into whatever scope it unwound to, which turns every later
// local into a phantom redeclaration. An Error-class rule says nothing
// about a file it cannot trust the shape of.
if !ctx.parsed_cleanly() {
return Vec::new();
}
let semantics = ctx.semantics();
let mut out = Vec::new();
for duplicate in semantics.duplicates() {
let Some(first) = semantics.symbol(duplicate.first) else { continue };
if !plain(duplicate.kind) || !plain(first.kind) {
continue;
}
let scope = semantics.scope(duplicate.scope).map(|scope| scope.kind);
// A generate scope elaborates one arm at a time; the file scope is
// where a `` `include``d fragment and a recovered construct both
// land, and two file-scope units of one name are the workspace's
// business rather than this file's.
if matches!(scope, Some(ScopeKind::Generate) | Some(ScopeKind::File)) {
continue;
}
let spans = [first.name_span.start, duplicate.name_span.start];
if ctx.signals().conditional_between(&spans) {
continue;
}
out.push(Violation::new(
NAME,
format!("`{}` is already declared in this scope", duplicate.name),
duplicate.name_span,
));
}
out
}
}
/// True for the declaration kinds that may be written **once** and once only.
///
/// Everything left out has a legal shape in which the same name is written
/// twice: a port is completed by its body declaration, a function or task by
/// its out-of-body definition, a class by its `typedef class` forward
/// declaration, and a constraint, covergroup, property or sequence by its own
/// prototype. An **enum member** is left out for a different reason: IEEE 1800
/// §6.19's name *range* (`RvCoreCsrGprT[0:2]`) declares a run of members under
/// one written identifier, and the binder records the identifier — so two
/// disjoint ranges of one base name look like one name declared twice when the
/// members they declare do not collide at all (measured on opentitan:
/// `jtag_rv_debugger_pkg.sv`). Listed positively rather than as an exclusion
/// list, so a kind added to `vlog_semantic` later is silent until somebody
/// decides it belongs.
fn plain(kind: SymbolKind) -> bool {
matches!(
kind,
SymbolKind::Net
| SymbolKind::Var
| SymbolKind::Param
| SymbolKind::LocalParam
| SymbolKind::Genvar
| SymbolKind::Typedef
| SymbolKind::Instance
| SymbolKind::TfArg
| SymbolKind::StructMember
)
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
DuplicateDeclaration.check(&LintContext::new(src, None))
}
#[test]
fn flags_two_signals_of_one_name() {
let src = "module m;\n logic a;\n logic a;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`a`"), "{}", found[0].message);
assert_eq!(found[0].span.start as usize, src.rfind('a').map(|i| i - 1).unwrap_or(0) + 1);
assert!(found[0].fix.is_none());
}
#[test]
fn flags_two_parameters_two_typedefs_and_two_instances() {
for src in [
"module m;\n parameter int W = 1;\n parameter int W = 2;\nendmodule\n",
"module m;\n typedef logic t;\n typedef bit t;\nendmodule\n",
"module m;\n sub u ();\n sub u ();\nendmodule\n",
] {
assert_eq!(violations(src).len(), 1, "{src}");
}
}
/// The non-ANSI shape: the header names the port, the body declares its
/// direction and then its type. Three declarations, one port, all legal.
#[test]
fn a_non_ansi_port_completed_in_the_body_is_never_flagged() {
let src = "module m (clk);\n input clk;\n logic clk;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
assert!(violations("module m (clk);\n input wire clk;\nendmodule\n").is_empty());
// An ANSI port redeclared in the body is left alone too, for the same
// reason: a rule that cannot tell the two apart must not accuse.
assert!(violations("module m (input logic clk);\n logic clk;\nendmodule\n").is_empty());
}
#[test]
fn a_prototype_and_its_definition_are_one_declaration() {
let src = "class c;\n extern function void f();\nendclass\n\
function void c::f();\nendfunction\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
let forward = "package p;\n typedef class c;\n class c;\n endclass\nendpackage\n";
assert!(violations(forward).is_empty(), "{:?}", violations(forward));
}
#[test]
fn conditional_arms_are_exclusive_so_they_are_not_flagged() {
let src = "module m;\n`ifdef X\n logic b;\n`else\n logic b;\n`endif\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_generate_scope_elaborates_one_arm_at_a_time() {
let src = "module m;\n\
generate\n\
if (A) begin : g\n\
logic x;\n\
end else begin : g\n\
logic x;\n\
end\n\
endgenerate\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_name_reused_in_a_nested_scope_is_not_a_duplicate() {
// That is shadowing, which is `instance-shadowing`'s subject.
let src =
"module m;\n logic a;\n always_comb begin : blk\n logic a;\n end\nendmodule\n";
assert!(violations(src).is_empty());
// And two modules may each declare `a`.
let two = "module m;\n logic a;\nendmodule\nmodule n;\n logic a;\nendmodule\n";
assert!(violations(two).is_empty());
}
}
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use crate::visit::walk_items;
use vlog_parser::ast::ItemKind;
@@ -21,6 +22,10 @@ impl Rule for EmptyItem {
"drop a `;` that stands where an item belongs"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A lone `;` in a module, generate, package, interface, program or class \
body is a *null item* (IEEE 1800-2017 A.1.4). It is legal and it means \
@@ -4,6 +4,7 @@
use crate::context::LintContext;
use crate::naming::{is_escaped, is_lower_snake_case};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::{ItemKind, TypedefKind};
@@ -22,6 +23,10 @@ impl Rule for EnumNameStyle {
"name enum typedefs in lower_snake_case ending in _e or _t"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A type name that looks like a type name is what makes a declaration \
readable at a glance: `state_e cur_state` says which identifier is the \
@@ -0,0 +1,152 @@
//! `explicit-function-task-parameter-type` — every formal gets a storage type.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::{ItemKind, TfArg};
/// See [`Rule::doc`].
pub struct ExplicitFunctionTaskParameterType;
const NAME: &str = "explicit-function-task-parameter-type";
impl Rule for ExplicitFunctionTaskParameterType {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"declare a storage type on every function and task argument"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A task or function formal written without a type is a **one-bit \
`logic`** (IEEE 1800 §13.3), so `function f(input a);` truncates \
every caller's argument to its low bit and nothing complains — the \
function simply returns the wrong answer for anything wider than a \
flag. Verible's `explicit-function-task-parameter-type` (\"Checks \
that every function and task parameter is declared with an explicit \
storage type.\", enabled by default) is the same rule and the same \
default. **A continuation formal inherits**: in `f(input int a, b)` \
the `b` is an `int`, so only the argument that *opens* a declaration \
— the first one, or the first after a direction keyword — is judged, \
which is exactly the language's own rule. A DPI import's unnamed \
formal (`import \"DPI-C\" function int f(int);`) names a type and no \
identifier and is not this rule's subject. No automatic fix: only the \
author knows how wide the argument was meant to be."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let (kw, args) = match &item.kind {
ItemKind::Function(decl) => ("function", &decl.args),
ItemKind::Task(decl) => ("task", &decl.args),
_ => return,
};
out.extend(untyped(kw, args));
});
out
}
}
/// The formals of one argument list that end up implicitly typed.
///
/// Walked in order with the declaration's type carried along, which is how the
/// language reads them: a formal that writes a type sets it, a formal that
/// writes a direction keyword opens a new declaration (and so a new type,
/// implicit until written), and a formal that writes neither inherits whatever
/// is in force.
fn untyped(kw: &'static str, args: &[TfArg]) -> Vec<Violation> {
let mut out = Vec::new();
let mut opened = false;
for arg in args {
let opens = !opened || arg.dir.is_some() || !arg.ty.is_implicit();
opened = true;
if !opens || !arg.ty.is_implicit() || arg.name.is_empty() {
continue;
}
out.push(Violation::new(
NAME,
format!("{kw} argument `{}` has no storage type; it is a 1-bit `logic`", arg.name),
arg.span,
));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ExplicitFunctionTaskParameterType.check(&LintContext::new(src, None))
}
fn wrap(header: &str) -> String {
format!("module m;\n {header}\n endfunction\nendmodule\n")
}
#[test]
fn flags_an_untyped_formal() {
let src = wrap("function void f(input a);");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`a`"), "{}", found[0].message);
assert!(found[0].message.contains("1-bit"), "{}", found[0].message);
assert!(found[0].fix.is_none());
}
#[test]
fn a_typed_formal_is_what_the_rule_wants() {
for header in [
"function void f(input logic a);",
"function void f(input int a);",
"function void f(input logic [7:0] a);",
"function void f(my_t a);",
"function void f();",
] {
assert!(
violations(&wrap(header)).is_empty(),
"{header}: {:?}",
violations(&wrap(header))
);
}
}
#[test]
fn a_continuation_formal_inherits_the_type_before_it() {
// `b` is an `int`, so only a genuinely untyped run may be reported.
assert!(violations(&wrap("function void f(input int a, b);")).is_empty());
// ... and a new direction keyword opens a new, untyped declaration.
let found = violations(&wrap("function void f(input int a, output b);"));
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`b`"), "{}", found[0].message);
}
#[test]
fn a_task_is_judged_the_same_way() {
let src = "module m;\n task t(input a);\n endtask\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("task"), "{}", found[0].message);
}
#[test]
fn an_unnamed_dpi_formal_is_not_this_rules_subject() {
let src = "import \"DPI-C\" function int f(int, chandle);\n";
assert!(violations(src).is_empty());
}
#[test]
fn a_class_method_is_reached() {
let src = "class c;\n function void f(input a);\n endfunction\nendclass\n";
assert_eq!(violations(src).len(), 1);
}
}
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
use vlog_parser::ast::{ItemKind, ParamDecl, StmtKind};
@@ -20,6 +21,10 @@ impl Rule for ExplicitParameterStorageType {
"declare a storage type on every parameter"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A parameter with no declared type takes its type from whatever it is \
assigned — and an override at instantiation can change that type, not \
@@ -0,0 +1,93 @@
//! `forbid-defparam` — `defparam` is deprecated; override at instantiation.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::ItemKind;
/// See [`Rule::doc`].
pub struct ForbidDefparam;
const NAME: &str = "forbid-defparam";
impl Rule for ForbidDefparam {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"override a parameter at the instantiation, not with `defparam`"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"`defparam` reaches into another scope and changes a parameter there, \
so the value a module elaborates with is written somewhere the module \
does not name and a reader has no way to find without grepping the \
whole design. It was deprecated in IEEE 1800-2009 (§A.11, and the LRM \
says it may be removed from a future revision), several synthesis \
tools reject it outright, and the `#(.NAME(value))` override at the \
instantiation says the same thing where the instance is. Verible's \
`forbid-defparam` (\"Do not use defparam.\", enabled by default) is \
the same rule. No automatic fix: moving the value to the right \
instantiation needs the instantiation, which may be in another file."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
if matches!(item.kind, ItemKind::Defparam(_)) {
out.push(Violation::new(
NAME,
"`defparam` is deprecated; override the parameter at its instantiation",
item.span,
));
}
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ForbidDefparam.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_defparam_wherever_it_stands() {
let src = "module m;\n sub u ();\n defparam u.WIDTH = 8;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "defparam u.WIDTH = 8;");
assert!(found[0].fix.is_none());
}
#[test]
fn a_named_override_is_what_the_rule_wants() {
assert!(violations("module m;\n sub #(.WIDTH(8)) u ();\nendmodule\n").is_empty());
// Nor is a parameter declaration one.
assert!(violations("module m;\n parameter int WIDTH = 8;\nendmodule\n").is_empty());
// And a signal that merely spells the word is not one either.
assert!(violations("module m;\n logic defparam_n;\nendmodule\n").is_empty());
}
#[test]
fn a_defparam_inside_generate_is_reached() {
let src = "module m;\n\
generate\n\
if (A) begin : g\n\
defparam u.W = 1;\n\
end\n\
endgenerate\n\
endmodule\n";
assert_eq!(violations(src).len(), 1);
}
}
@@ -0,0 +1,144 @@
//! `forbid-negative-array-dim` — a negative literal inside a dimension.
use crate::context::LintContext;
use crate::decls::walk_dims;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::ast::{DimKind, Expr, ExprKind};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct ForbidNegativeArrayDim;
const NAME: &str = "forbid-negative-array-dim";
impl Rule for ForbidNegativeArrayDim {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not write a negative constant in a dimension"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"`logic q [-1]` and `logic [-1:0] v` are what a parameter that came \
out zero or one too small looks like after the subtraction: \
`[WIDTH-1:0]` with `WIDTH = 0` is `[-1:0]`, which tools variously \
reject, treat as empty, or size as two bits. Written as a literal it \
is never intentional. Verible's `forbid-negative-array-dim` (\"Check \
for negative constant literals inside array dimensions.\") is the \
same rule; **lucisv turns it on by default where Verible ships it \
off**, because a negative literal spelled out in a dimension has no \
legitimate reading. Only a written `-<literal>` is flagged — an \
expression that would *evaluate* negative needs the parameter values, \
which lucisv does not have. No automatic fix."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_dims(ctx.file(), &mut |_, dim| {
let DimKind::Range { a, b } = &dim.kind else { return };
for expr in [Some(a), b.as_ref()].into_iter().flatten() {
for span in negative_literals(expr) {
out.push(Violation::new(NAME, "negative constant in a dimension", span));
}
}
});
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
out
}
}
/// The spans of every written `-<literal>` inside `expr`.
///
/// A whole expression tree rather than the top node alone, because the shape
/// that turns up in real code is `[-1:0]` on one side and `[WIDTH-1:-1]` on
/// the other, and the offending term can sit anywhere in an arithmetic
/// expression.
fn negative_literals(expr: &Expr) -> Vec<TextRange> {
let mut out = Vec::new();
collect(expr, &mut out);
out
}
fn collect(expr: &Expr, out: &mut Vec<TextRange>) {
match &expr.kind {
ExprKind::Unary { op, expr: inner, .. } => {
if op == "-" && matches!(inner.kind, ExprKind::Number(_)) {
out.push(expr.span);
return;
}
collect(inner, out);
}
ExprKind::Binary { lhs, rhs, .. } => {
collect(lhs, out);
collect(rhs, out);
}
ExprKind::Paren { inner, .. } => collect(inner, out),
ExprKind::Ternary { cond, then, els, .. } => {
collect(cond, out);
collect(then, out);
collect(els, out);
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ForbidNegativeArrayDim.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_negative_packed_bound() {
let src = "module m;\n logic [-1:0] v;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "-1");
assert!(found[0].fix.is_none());
}
#[test]
fn flags_a_negative_unpacked_extent_and_one_buried_in_arithmetic() {
assert_eq!(violations("module m;\n logic q [-1];\nendmodule\n").len(), 1);
assert_eq!(violations("module m;\n logic [W + -2:0] v;\nendmodule\n").len(), 1);
// Both ends count.
assert_eq!(violations("module m;\n logic [-1:-2] v;\nendmodule\n").len(), 2);
}
#[test]
fn ordinary_dimensions_are_silent() {
for decl in [
"logic [7:0] v;",
"logic [WIDTH-1:0] v;",
"logic q [4];",
"logic q [0:3];",
"logic v;",
"logic q [];",
] {
let src = format!("module m;\n {decl}\nendmodule\n");
assert!(violations(&src).is_empty(), "{decl}: {:?}", violations(&src));
}
}
#[test]
fn a_negative_outside_a_dimension_is_not_this_rules_business() {
assert!(violations("module m;\n assign x = -1;\nendmodule\n").is_empty());
assert!(violations("module m;\n parameter int P = -1;\nendmodule\n").is_empty());
}
#[test]
fn a_subtraction_is_not_a_negative_literal() {
// `WIDTH-1` is the ordinary way to write a width and must never fire.
assert!(violations("module m;\n logic [WIDTH-1:0] v;\nendmodule\n").is_empty());
}
}
@@ -0,0 +1,349 @@
//! `incomplete-assignment` — a latch inferred in an `always_comb`.
use std::collections::BTreeSet;
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_items, walk_stmts};
use vlog_parser::ast::{Expr, ExprKind, ItemKind, Stmt, StmtKind};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct IncompleteAssignment;
const NAME: &str = "incomplete-assignment";
impl Rule for IncompleteAssignment {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"assign every variable on every path of an always_comb"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A variable an `always_comb` writes on some paths and not on others \
has to *hold its value* on the others, and holding a value is a \
latch: the synthesized circuit grows storage nobody asked for, the \
timing closes differently, and in simulation the block reads back \
whatever it left there last time. `always_comb` was added to the \
language precisely so tools could catch this, and most of them do — \
but only at elaboration, long after the edit. There is no Verible \
equivalent; this is TODO §33's own rule.\n\n\
**Conservative by construction.** It speaks only about the \
*top level* of an `always_comb` body, and only in the two shapes that \
are unambiguous: an `if` with no `else`, and a `case` with no \
`default`. A variable is reported only when the block writes it \
inside such a statement and nothing **earlier in the block** already \
covered it — where covering it means a plain assignment (a partial \
one, through a bit select or a field, counts), or an `if`/`else` or a \
`case` with a `default` that writes it in *every* arm. That last one \
is the usual style, and the usual repair is the other: a default \
assignment at the top of the block.\n\n\
Everything else stays silent, deliberately: a name the block \
**declares for itself** (a local temporary is not a latched output), \
a left-hand side that is not a plain name or a concatenation of them, \
a conditional nested inside another, and every `always` that is not \
an `always_comb`. Measured on opentitan: three findings before those \
exemptions, all three false, none after. No automatic fix: what the \
missing branch should assign is a design decision."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::Always { kw, stmt } = &item.kind else { return };
if kw != "always_comb" {
return;
}
out.extend(latches(ctx.source(), stmt));
});
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
out
}
}
/// The findings of one `always_comb` body.
fn latches(source: &str, body: &Stmt) -> Vec<Violation> {
// Names the block declares for itself are never reported: a temporary
// written inside the branch it was declared in is a local, not a latched
// output, and deciding which of the two it is needs elaboration.
let local = declared_names(body);
let mut covered: BTreeSet<String> = BTreeSet::new();
let mut out = Vec::new();
for stmt in top_level(body) {
match &stmt.kind {
// Any write at all counts as coverage, a partial one included: a
// block that sets `cfg.mode` at the top and the whole `cfg` under
// an `if` has written the variable before the branch.
StmtKind::Assign { lhs, .. } => covered.extend(written_names(lhs)),
StmtKind::If { cond, then, els: None, .. } => {
let at = header(source, stmt.span, cond.span);
report(&mut out, &covered, &local, at, branch_names(then));
}
// An `if` with an `else`, and a `case` with a `default`, cover
// every name their branches agree on — which is how the usual
// "assign it in every arm" style is written.
StmtKind::If { then, els: Some(els), .. } => {
covered.extend(intersect(&[branch_names(then), branch_names(els)]));
}
StmtKind::Case { expr, items, .. } => {
let per_branch: Vec<BTreeSet<String>> =
items.iter().map(|item| branch_names(&item.stmt)).collect();
if items.iter().any(|item| item.labels.is_empty()) {
covered.extend(intersect(&per_branch));
} else {
let mut names = BTreeSet::new();
for branch in &per_branch {
names.extend(branch.iter().cloned());
}
let at = header(source, stmt.span, expr.span);
report(&mut out, &covered, &local, at, names);
}
}
_ => {}
}
}
out
}
/// The names every one of these branches writes.
fn intersect(branches: &[BTreeSet<String>]) -> BTreeSet<String> {
let Some((first, rest)) = branches.split_first() else { return BTreeSet::new() };
first.iter().filter(|name| rest.iter().all(|set| set.contains(*name))).cloned().collect()
}
/// Every name the block declares anywhere inside itself.
fn declared_names(body: &Stmt) -> BTreeSet<String> {
let mut names = BTreeSet::new();
walk_stmts(body, &mut |stmt| {
if let StmtKind::VarDecl(decl) = &stmt.kind {
names.extend(decl.declarators.iter().map(|d| d.name.clone()));
}
});
names
}
/// The statements written directly in the body — the body itself when it is
/// one statement, and a `begin ... end`'s own list when it is a block.
fn top_level(body: &Stmt) -> Vec<&Stmt> {
match &body.kind {
StmtKind::Block { stmts, .. } => stmts.iter().collect(),
// The body of an `always_comb` carries no timing control of its own,
// so anything else is a single statement standing as the whole block.
_ => vec![body],
}
}
/// Every plain name a branch assigns, however deep inside it.
fn branch_names(stmt: &Stmt) -> BTreeSet<String> {
let mut names = BTreeSet::new();
walk_stmts(stmt, &mut |inner| {
if let StmtKind::Assign { lhs, .. } = &inner.kind {
names.extend(assigned_name(lhs));
}
});
names
}
/// Adds one finding per name the branch writes that nothing covered before it
/// and that the block does not declare for itself.
fn report(
out: &mut Vec<Violation>,
covered: &BTreeSet<String>,
local: &BTreeSet<String>,
span: TextRange,
names: BTreeSet<String>,
) {
for name in names {
if covered.contains(&name) || local.contains(&name) {
continue;
}
out.push(Violation::new(
NAME,
format!("`{name}` is not assigned on every path; this infers a latch"),
span,
));
}
}
/// The `if (cond)` / `case (subject)` header alone, so a whole branch is not
/// painted red for a problem that lives on one line. The subject's own span
/// stops inside the parentheses, so the underline runs on to the `)` that
/// closes it — the same shape `case-missing-default` underlines.
fn header(source: &str, stmt: TextRange, subject: TextRange) -> TextRange {
let close = source
.get(subject.end as usize..)
.and_then(|rest| rest.find(')'))
.map(|i| subject.end + i as u32 + 1)
.unwrap_or(subject.end);
TextRange::new(stmt.start, close.max(stmt.start))
}
/// The plain name a left-hand side writes, or nothing when the target is not
/// one identifier.
///
/// A bit or field select (`x[3] = …`, `s.f = …`) writes *part* of a variable,
/// and deciding whether the rest is covered needs ranges resolved — so those
/// are not names this rule will accuse. A concatenation lvalue is every name
/// in it, each of which is written whole.
fn assigned_name(lhs: &Expr) -> Vec<String> {
match &lhs.kind {
ExprKind::Ident(name) => vec![name.clone()],
ExprKind::Concat(items) => {
items.iter().flat_map(|item| assigned_name(&item.expr)).collect()
}
_ => Vec::new(),
}
}
/// Every name a left-hand side touches, a *part* of one included.
///
/// The wider question — "was this variable written here at all?" — which is
/// what the coverage set wants: a block that writes `cfg.mode` before an `if`
/// that writes the whole `cfg` has already spoken for `cfg`, and reporting it
/// would be a latch that is not there.
fn written_names(lhs: &Expr) -> Vec<String> {
match &lhs.kind {
ExprKind::Ident(name) => vec![name.clone()],
ExprKind::Concat(items) => {
items.iter().flat_map(|item| written_names(&item.expr)).collect()
}
ExprKind::Index { base, .. }
| ExprKind::Range { base, .. }
| ExprKind::Member { base, .. } => written_names(base),
_ => Vec::new(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
IncompleteAssignment.check(&LintContext::new(src, None))
}
fn wrap(body: &str) -> String {
format!("module m;\n always_comb begin\n{body} end\nendmodule\n")
}
#[test]
fn flags_a_variable_written_only_under_an_if() {
let src = wrap(" if (en) y = a;\n");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`y`"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "if (en)", "the header, not the branch");
assert!(found[0].fix.is_none());
}
#[test]
fn a_default_assignment_before_the_if_is_the_repair() {
assert!(violations(&wrap(" y = 1'b0;\n if (en) y = a;\n")).is_empty());
// ... and it must come *before*: assigning after the `if` does not
// stop the branch from inferring one.
assert_eq!(violations(&wrap(" if (en) y = a;\n y = 1'b0;\n")).len(), 1);
}
#[test]
fn an_if_with_an_else_covers_every_path() {
assert!(violations(&wrap(" if (en) y = a; else y = b;\n")).is_empty());
}
#[test]
fn a_case_without_default_is_flagged_and_one_with_it_is_not() {
let with_default = " case (s)\n 0: y = a;\n default: y = b;\n endcase\n";
assert!(violations(&wrap(with_default)).is_empty());
let without = " case (s)\n 0: y = a;\n 1: y = b;\n endcase\n";
let found = violations(&wrap(without));
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`y`"), "{}", found[0].message);
}
#[test]
fn every_variable_of_a_branch_is_named_once() {
let found = violations(&wrap(" if (en) begin\n y = a;\n z = b;\n end\n"));
assert_eq!(found.len(), 2, "{found:?}");
assert!(found[0].message.contains("`y`") || found[0].message.contains("`z`"));
// And a variable written twice in the branch is still one finding.
let twice = violations(&wrap(" if (en) begin\n y = a;\n y = b;\n end\n"));
assert_eq!(twice.len(), 1, "{twice:?}");
}
#[test]
fn only_always_comb_is_judged() {
for kw in ["always", "always_ff", "always_latch"] {
let src = format!("module m;\n {kw} @(posedge clk) if (en) y <= a;\nendmodule\n");
assert!(violations(&src).is_empty(), "{kw}");
}
assert!(violations("module m;\n always @* if (en) y = a;\nendmodule\n").is_empty());
}
#[test]
fn a_partial_write_is_not_accused() {
// Deciding whether the other bits are covered needs ranges resolved,
// which this rule does not do.
assert!(violations(&wrap(" if (en) y[3] = a;\n")).is_empty());
assert!(violations(&wrap(" if (en) s.f = a;\n")).is_empty());
}
#[test]
fn a_concatenation_lvalue_names_every_target() {
let found = violations(&wrap(" if (en) {y, z} = a;\n"));
assert_eq!(found.len(), 2, "{found:?}");
}
#[test]
fn a_nested_conditional_is_left_to_the_top_level_one() {
// The outer `if` has an `else`, so the block covers every path as far
// as this rule is willing to claim.
let src = wrap(" if (en) begin\n if (x) y = a;\n end else y = b;\n");
assert!(violations(&src).is_empty());
}
/// The three shapes the opentitan census turned up as false positives, each
/// pinned so it stays quiet.
#[test]
fn the_shapes_that_are_not_latches_stay_quiet() {
// 1. A variable the block declares for itself, written in the branch
// it was declared in (`entropy_src_core.sv`).
let local = wrap(" if (en) begin\n logic [3:0] tmp;\n tmp = a;\n end\n");
assert!(violations(&local).is_empty(), "{:?}", violations(&local));
// 2. A partial write before the branch covers the variable
// (`kmac_app.sv`).
let partial = wrap(" cfg.mode = a;\n if (en) cfg = b;\n");
assert!(violations(&partial).is_empty(), "{:?}", violations(&partial));
// 3. A `case` with a `default` that writes it in every arm, followed
// by an `if` that writes it again (`ibex_alu.sv`).
let after_case = wrap(
" case (s)\n 0: y = a;\n default: y = b;\n endcase\n\
\x20 if (en) y = 1'b1;\n",
);
assert!(violations(&after_case).is_empty(), "{:?}", violations(&after_case));
}
#[test]
fn an_if_else_before_the_branch_also_covers_it() {
let src = wrap(" if (a) y = 1; else y = 0;\n if (en) y = 2;\n");
assert!(violations(&src).is_empty(), "{:?}", violations(&src));
// ... but only for the names *both* arms write.
let partial = wrap(" if (a) y = 1; else z = 0;\n if (en) y = 2;\n");
assert_eq!(violations(&partial).len(), 1, "{:?}", violations(&partial));
}
#[test]
fn a_body_that_is_one_statement_is_still_a_body() {
let src = "module m;\n always_comb if (en) y = a;\nendmodule\n";
assert_eq!(violations(src).len(), 1);
}
}
@@ -0,0 +1,204 @@
//! `instance-shadowing` — a declaration hiding one from an enclosing scope.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_semantic::{Scope, ScopeKind, Semantics, SymbolKind};
/// See [`Rule::doc`].
pub struct InstanceShadowing;
const NAME: &str = "instance-shadowing";
impl Rule for InstanceShadowing {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not hide an enclosing declaration with a new one of the same name"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A `logic count;` inside a `begin : blk` where the module already has \
a `count` compiles, and from then on every mention of `count` inside \
the block means the inner one — including the ones written before the \
inner declaration was added, which is how this arrives in a review \
diff that looks like it changed nothing. Verible's `instance-\
shadowing` (\"Warns if there are multiple declarations in the same \
scope that shadow each other with the same name.\") is the same rule; \
**lucisv turns it on by default where Verible ships it off**, because \
the finding is always worth a second look and the repair is a rename \
in one block.\n\n\
Only the scopes **inside one design unit** are compared: a module, a \
package or a class opens a fresh namespace, and a signal called `data` \
in two different modules shadows nothing. A generate scope is \
compared like any other block — the shadowing is real there too. No \
automatic fix: renaming reaches every use inside the block."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
// Shadowing is a claim about *which scope* a name was declared in,
// and error recovery moves declarations between scopes — so a file
// that did not fully parse gets no opinion, exactly as
// `duplicate-declaration` gives it none.
if !ctx.parsed_cleanly() {
return Vec::new();
}
let semantics = ctx.semantics();
let mut out = Vec::new();
for scope in semantics.scopes() {
if opens_a_unit(scope.kind) {
continue;
}
for &id in &scope.symbols {
let Some(symbol) = semantics.symbol(id) else { continue };
let Some(hidden) = shadowed(semantics, scope, &symbol.name) else { continue };
if !judged(symbol.kind) {
continue;
}
// The two are exclusive when a conditional-compilation
// directive stands between them, exactly as they are for
// `duplicate-declaration`.
if ctx.signals().conditional_between(&[hidden, symbol.name_span.start]) {
continue;
}
out.push(Violation::new(
NAME,
format!(
"`{}` shadows a declaration of the same name outside this scope",
symbol.name
),
symbol.name_span,
));
}
}
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
out
}
}
/// The name span of the enclosing declaration `name` hides, if there is one
/// **within the same design unit**.
///
/// The walk stops at the scope that opens a unit — a module, package or class
/// body — because a name declared in a different unit is reached by a
/// qualified path, never by shadowing.
fn shadowed(semantics: &Semantics, scope: &Scope, name: &str) -> Option<u32> {
let mut parent = scope.parent;
while let Some(id) = parent {
let outer = semantics.scope(id)?;
if let Some(hidden) = outer.lookup_local(name) {
return semantics.symbol(hidden).map(|symbol| symbol.name_span.start);
}
if opens_a_unit(outer.kind) {
return None;
}
parent = outer.parent;
}
None
}
/// True for the scopes that open a design unit's own namespace.
fn opens_a_unit(kind: ScopeKind) -> bool {
matches!(kind, ScopeKind::File | ScopeKind::Module | ScopeKind::Package | ScopeKind::Class)
}
/// True for the declarations worth reporting.
///
/// A subroutine argument named after an enclosing signal is idiomatic
/// (`function automatic f(input logic clk)`), a block label is not a value,
/// and a `genvar` is scoped to its own loop by construction — so those stay
/// out. What is left is data and instances, which is where the surprise is.
fn judged(kind: SymbolKind) -> bool {
matches!(
kind,
SymbolKind::Net | SymbolKind::Var | SymbolKind::Instance | SymbolKind::LocalParam
)
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
InstanceShadowing.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_block_local_that_hides_a_module_signal() {
let src = "module m;\n\
logic count;\n\
always_comb begin : blk\n\
logic count;\n\
count = 1'b0;\n\
end\n\
endmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`count`"), "{}", found[0].message);
assert!(found[0].span.start as usize > src.find("blk").unwrap_or(0), "the inner one");
assert!(found[0].fix.is_none());
}
#[test]
fn a_name_declared_once_is_never_flagged() {
let src = "module m;\n\
logic count;\n\
always_comb begin : blk\n\
logic other;\n\
end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_different_unit_shadows_nothing() {
let src = "module a;\n logic data;\nendmodule\nmodule b;\n logic data;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
// Nor does a package-level name reached from a module.
let pkg = "package p;\n logic data;\nendpackage\nmodule m;\n logic data;\nendmodule\n";
assert!(violations(pkg).is_empty(), "{:?}", violations(pkg));
}
#[test]
fn a_generate_block_is_compared_like_any_other() {
let src = "module m;\n\
logic x;\n\
generate\n\
if (A) begin : g\n\
logic x;\n\
end\n\
endgenerate\n\
endmodule\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn a_subroutine_argument_named_after_a_signal_is_idiomatic() {
let src = "module m;\n\
logic clk;\n\
function automatic void f(input logic clk);\n\
endfunction\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn conditional_arms_are_exclusive() {
let src = "module m;\n\
logic x;\n\
always_comb begin : blk\n\
`ifdef A\n\
logic x;\n\
`endif\n\
end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
}
@@ -0,0 +1,132 @@
//! `invalid-system-task-function` — system tasks nothing should still call.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::token::TokenKind;
/// See [`Rule::doc`].
pub struct InvalidSystemTaskFunction;
const NAME: &str = "invalid-system-task-function";
/// The forbidden names and what to write instead — Verible's list
/// (`invalid-system-task-function`), name for name.
///
/// The `$dist_*` family and `$random` all draw from the *global* seed that
/// `$random` shares, so one extra call anywhere in a testbench reshuffles
/// every other stream; `$urandom` and `$urandom_range` are per-thread and
/// reproducible. `$psprintf` is a vendor extension for the standard
/// `$sformatf`, and `$srandom` seeds that same global generator rather than
/// the calling process.
const FORBIDDEN: &[(&str, &str)] = &[
("$psprintf", "$sformatf"),
("$random", "$urandom"),
("$srandom", "process::self().srandom()"),
("$dist_chi_square", "$urandom"),
("$dist_erlang", "$urandom"),
("$dist_exponential", "$urandom"),
("$dist_normal", "$urandom"),
("$dist_poisson", "$urandom"),
("$dist_t", "$urandom"),
("$dist_uniform", "$urandom"),
];
impl Rule for InvalidSystemTaskFunction {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not call a deprecated or non-reproducible system task"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"`$random`, `$srandom` and the `$dist_*` family all draw from one \
global generator, so adding a call anywhere in a testbench reshuffles \
every other random stream in it and a failing seed stops reproducing \
— the reason IEEE 1800 added the per-process `$urandom` / \
`$urandom_range` and `process::self().srandom()`. `$psprintf` is a \
vendor spelling of the standard `$sformatf` and is not portable. \
Verible's `invalid-system-task-function` (\"Checks that no forbidden \
system tasks or functions are used.\", enabled by default) forbids \
exactly this list, and lucisv names the replacement in the message. \
No automatic fix: `$random` and `$urandom` return different value \
streams, so swapping them changes what the test does."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
ctx.tokens()
.iter()
.filter(|token| token.kind == TokenKind::SystemIdent)
.filter_map(|token| {
let (name, instead) =
FORBIDDEN.iter().find(|(name, _)| *name == token.text.as_str())?;
Some(Violation::new(
NAME,
format!("`{name}` is forbidden; use `{instead}`"),
token.span,
))
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
InvalidSystemTaskFunction.check(&LintContext::new(src, None))
}
#[test]
fn flags_every_forbidden_name_and_says_what_to_use() {
for (name, instead) in FORBIDDEN {
let src = format!("module m;\n initial x = {name}();\nendmodule\n");
let found = violations(&src);
assert_eq!(found.len(), 1, "{name}: {found:?}");
assert!(found[0].message.contains(name), "{}", found[0].message);
assert!(found[0].message.contains(instead), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], *name, "the call, underlined");
}
}
#[test]
fn the_replacements_and_their_neighbours_are_left_alone() {
let src = "module m;\n\
initial begin\n\
a = $urandom();\n\
b = $urandom_range(0, 7);\n\
c = $sformatf(\"%0d\", a);\n\
$display(\"%0d\", b);\n\
end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_near_miss_name_is_not_a_hit() {
// Matched whole, not by prefix: `$random_stable` and a signal called
// `random` are neither of them `$random`.
let src = "module m;\n\
logic random;\n\
initial begin\n\
a = $randomize_helper();\n\
b = random;\n\
end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_forbidden_name_inside_a_string_is_data() {
let src = "module m;\n initial $display(\"call $random here\");\nendmodule\n";
assert!(violations(src).is_empty());
}
}
@@ -0,0 +1,299 @@
//! `mismatched-labels` — an end label that does not name its own block.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_all_stmts, walk_items};
use vlog_parser::ast::{GenBlock, GenElse, Item, ItemKind, Name, StmtKind};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct MismatchedLabels;
const NAME: &str = "mismatched-labels";
impl Rule for MismatchedLabels {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"make an end label name the block it closes"
}
fn severity(&self) -> Severity {
Severity::Error
}
fn doc(&self) -> &'static str {
"`begin : fetch … end : decode` is a compile error (IEEE 1800 §9.3.4: \
if both labels are given they must be identical), and so is an \
`end : name` on a block that was never labelled. It is the classic \
result of copying a block and renaming only one half — which is also \
why it survives review: the two halves are pages apart. Verible's \
`mismatched-labels` (\"Check for matching begin/end labels.\") is the \
same rule; **lucisv turns it on by default where Verible ships it \
off**, and files it as an **Error** rather than a style finding, \
because the file does not compile.\n\n\
Every construct that may carry a footer label is checked with one \
answer: `module`/`interface`/`program`, `package`, `class`, \
`function`, `task`, `begin`, `fork`/`join`, a generate block, a \
`clocking` block, a `covergroup`, and a `property`/`sequence`. It is \
a comparison of two spellings and nothing more, so an escaped \
identifier is compared as written. No automatic fix: which of the two \
names is the right one is exactly what a linter cannot know."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| item_labels(&mut out, item));
walk_all_stmts(ctx.file(), &mut |stmt| match &stmt.kind {
StmtKind::Block { label, end_label, end_label_span, .. } => {
check_pair(&mut out, label.as_deref(), end_label.as_deref(), *end_label_span, "end")
}
StmtKind::ForkJoin { label, end_label, end_label_span, .. } => check_pair(
&mut out,
label.as_deref(),
end_label.as_deref(),
*end_label_span,
"join",
),
_ => {}
});
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
out
}
}
/// The label pair one item carries, checked. One arm per construct that may
/// write a footer label, so a construct that gains one later has an obvious
/// place to go.
fn item_labels(out: &mut Vec<Violation>, item: &Item) {
match &item.kind {
ItemKind::Module(module) => check_pair(
out,
Some(&module.name),
module.end_label.as_deref(),
module.end_label_span,
match module.kw.as_str() {
"interface" => "endinterface",
"program" => "endprogram",
_ => "endmodule",
},
),
ItemKind::Package { name, end_label, end_label_span, .. } => {
check_pair(out, Some(name), end_label.as_deref(), *end_label_span, "endpackage")
}
ItemKind::Class(class) => check_pair(
out,
Some(&class.name),
class.end_label.as_deref(),
class.end_label_span,
"endclass",
),
ItemKind::Function(decl) => check_pair(
out,
Some(&decl.name),
decl.end_label.as_deref(),
decl.end_label_span,
"endfunction",
),
ItemKind::Task(decl) => check_pair(
out,
Some(&decl.name),
decl.end_label.as_deref(),
decl.end_label_span,
"endtask",
),
ItemKind::Clocking(decl) => check_pair(
out,
decl.name.as_ref().map(|name| name.text.as_str()),
decl.end_label.as_deref(),
decl.end_label_span,
"endclocking",
),
ItemKind::Covergroup(decl) => {
check_name_pair(out, Some(&decl.name.text), decl.end_label.as_ref(), "endgroup")
}
ItemKind::PropSeqDecl(decl) => check_name_pair(
out,
Some(&decl.name.text),
decl.end_label.as_ref(),
if decl.kw == "sequence" { "endsequence" } else { "endproperty" },
),
// The item walk descends into a generate block's *items* but never
// visits the block itself, so its own label pair is collected here.
ItemKind::GenIf(gen_if) => {
check_gen_block(out, &gen_if.then);
let mut els = gen_if.els.as_deref();
while let Some(branch) = els {
match branch {
GenElse::If(_, nested) => {
check_gen_block(out, &nested.then);
els = nested.els.as_deref();
}
GenElse::Block(block) => {
check_gen_block(out, block);
els = None;
}
}
}
}
ItemKind::GenFor(gen_for) => check_gen_block(out, &gen_for.body),
ItemKind::GenCase(gen_case) => {
for case_item in &gen_case.items {
check_gen_block(out, &case_item.body);
}
}
_ => {}
}
}
fn check_gen_block(out: &mut Vec<Violation>, block: &GenBlock) {
check_pair(
out,
block.label.as_deref(),
block.end_label.as_deref(),
block.end_label_span,
"end",
);
}
/// Compares one header/footer pair, when a footer label was written at all.
fn check_pair(
out: &mut Vec<Violation>,
opened: Option<&str>,
closed: Option<&str>,
at: Option<TextRange>,
kw: &'static str,
) {
let (Some(closed), Some(at)) = (closed, at) else { return };
if at.is_empty() {
return;
}
let message = match opened {
Some(opened) if opened == closed => return,
Some(opened) => format!("`{kw} : {closed}` closes `{opened}`"),
None => format!("`{kw} : {closed}` closes a block with no label"),
};
out.push(Violation::new(NAME, message, at));
}
/// The same, for the constructs whose footer label is a [`Name`].
fn check_name_pair(
out: &mut Vec<Violation>,
opened: Option<&str>,
closed: Option<&Name>,
kw: &'static str,
) {
check_pair(
out,
opened,
closed.map(|name| name.text.as_str()),
closed.map(|name| name.span),
kw,
);
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
MismatchedLabels.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_footer_that_names_another_block() {
let src = "module m;\n\
always_comb begin : fetch\n\
x = 1;\n\
end : decode\n\
endmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "decode");
assert!(found[0].message.contains("fetch"), "{}", found[0].message);
assert!(found[0].fix.is_none());
}
#[test]
fn flags_a_footer_label_on_an_unlabelled_block() {
let src = "module m;\n always_comb begin\n x = 1;\n end : blk\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("no label"), "{}", found[0].message);
}
#[test]
fn a_matching_pair_and_a_missing_footer_are_both_fine() {
for src in [
"module m;\n always_comb begin : blk\n x = 1;\n end : blk\nendmodule\n",
"module m;\n always_comb begin : blk\n x = 1;\n end\nendmodule\n",
"module m;\n always_comb begin\n x = 1;\n end\nendmodule\n",
"module m;\nendmodule : m\n",
] {
assert!(violations(src).is_empty(), "{src}: {:?}", violations(src));
}
}
#[test]
fn every_construct_with_a_footer_label_is_checked() {
for (src, wrong) in [
("module m;\nendmodule : other\n", "other"),
("interface i;\nendinterface : other\n", "other"),
("package p;\nendpackage : other\n", "other"),
("class c;\nendclass : other\n", "other"),
("module m;\n function void f();\n endfunction : other\nendmodule\n", "other"),
("module m;\n task t();\n endtask : other\nendmodule\n", "other"),
(
"interface i;\n clocking cb @(posedge clk);\n endclocking : other\nendinterface\n",
"other",
),
(
"module m;\n covergroup cg;\n endgroup : other\nendmodule\n",
"other",
),
(
"module m;\n property p;\n a |-> b;\n endproperty : other\nendmodule\n",
"other",
),
] {
let found = violations(src);
assert_eq!(found.len(), 1, "{src}: {found:?}");
assert_eq!(&src[found[0].span.as_range()], wrong, "{src}");
}
}
#[test]
fn a_fork_join_and_a_generate_block_are_checked() {
let fork = "module m;\n\
initial fork : spawn\n\
x = 1;\n\
join : other\n\
endmodule\n";
assert_eq!(violations(fork).len(), 1, "{:?}", violations(fork));
let generate = "module m;\n\
generate\n\
if (A) begin : g\n\
wire a;\n\
end : other\n\
endgenerate\n\
endmodule\n";
assert_eq!(violations(generate).len(), 1, "{:?}", violations(generate));
}
#[test]
fn a_nested_block_is_matched_against_its_own_header() {
let src = "module m;\n\
always_comb begin : outer\n\
begin : inner\n\
x = 1;\n\
end : inner\n\
end : outer\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
}
+25 -4
View File
@@ -1,24 +1,45 @@
//! The rules themselves, one module each.
//!
//! Most rules are **syntactic** — text, tokens or tree shape. The three that
//! are not (`unused-signal`, `undriven-net`, `multiply-driven`) read the
//! symbol table through `crate::signals`; see
//! `docs/features/semantic-lints/README.md`.
//! Most rules are **syntactic** — text, tokens or tree shape. The ones that
//! are not read the symbol table: `unused-signal`, `undriven-net` and
//! `multiply-driven` through `crate::signals` (see
//! `docs/features/semantic-lints/README.md`), and `duplicate-declaration` and
//! `instance-shadowing` through `vlog_semantic::Semantics` directly (see
//! `docs/features/linter-expansion-1/README.md`).
pub mod always_comb_blocking;
pub mod always_ff_non_blocking;
pub mod case_missing_default;
pub mod duplicate_declaration;
pub mod empty_item;
pub mod enum_name_style;
pub mod explicit_function_task_parameter_type;
pub mod explicit_parameter_storage_type;
pub mod forbid_defparam;
pub mod forbid_negative_array_dim;
pub mod incomplete_assignment;
pub mod instance_shadowing;
pub mod invalid_system_task_function;
pub mod mismatched_labels;
pub mod module_filename;
pub mod module_name_style;
pub mod module_parameter;
pub mod module_port;
pub mod multiply_driven;
pub mod no_tabs;
pub mod no_trailing_whitespace;
pub mod packed_dimensions_range_ordering;
pub mod parameter_name_style;
pub mod plusarg_assignment;
pub mod struct_union_name_style;
pub mod suspicious_semicolon;
pub mod truncated_numeric_literal;
pub mod undeclared_identifier;
pub mod undersized_binary_literal;
pub mod undriven_net;
pub mod unknown_parameter;
pub mod unknown_port;
pub mod unused_signal;
pub mod unused_waiver;
pub mod void_cast;
pub mod wire_reg_mixup;
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::ast::ItemKind;
@@ -19,6 +20,10 @@ impl Rule for ModuleFilename {
"name a one-module file after its module"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"Every Verilog tool that finds a module by searching a library \
directory — simulators, synthesis `-y` paths, most build systems — \
Loaded 100 of 277 files, more files were not shown because too many files have changed in this diff. Show more