Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
66f38987ac | ||
|
|
8145a67be6 | ||
|
|
f7956060b3 | ||
|
|
f302b471a7 | ||
|
|
7aedfe2554 | ||
|
|
73799f3d53 | ||
|
|
ec9ec42276 | ||
|
|
4b2dad87fe | ||
|
|
3b08c0753c | ||
|
|
972bd1cff1 | ||
|
|
8a92e79fc0 | ||
|
|
f6f18de10d | ||
|
|
d5abf81563 | ||
|
|
97aa2fefd8 | ||
|
|
9604753b6c | ||
|
|
797ef86d47 | ||
|
|
a30dda167a |
No files matched your search
+121
@@ -4,6 +4,127 @@ 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.44.0 — 2026-09-05
|
||||
|
||||
### Opening a file no longer stalls the editor
|
||||
|
||||
- **`undriven-net` asked the workspace census once per declaration**,
|
||||
ahead of the local guards that silence almost every one, so a
|
||||
`didOpen` — and every keystroke flush — of a large file paid a walk
|
||||
over every indexed file thousands of times. Asked last now, the way
|
||||
its twin `unused-signal` always did. Opening opentitan's 42 192-line
|
||||
`pinmux_reg_top.sv` at workspace scope: 1 742 ms → 117 ms; typical
|
||||
IP files 51–95 ms → 5–8 ms. Same findings in the same order.
|
||||
- **Walk warnings.** An unreadable directory, an unreadable `.gitignore`
|
||||
or a dangling source-file symlink no longer fails a run: the CLI
|
||||
prints `warning: <path>: <message>` on stderr before the report with
|
||||
the exit code unchanged, and the server logs once per scan.
|
||||
- **A typo in `lucisv.lint.select` or `ignore`** is logged once
|
||||
(`lucisv.lint.select: unknown rule: <name>`) instead of silently
|
||||
emptying the selection.
|
||||
- **Inline aggregate types as parameter-override arguments**
|
||||
(`m #(.T(struct packed { logic a; })) u ();`) parse, format and are
|
||||
emitted by the instantiation skeleton.
|
||||
- **Comment slots inside delay lists** (`#( /*a*/ 1 : 2 : 3 )`, gate
|
||||
`#(rise, fall)`), and a line comment after a gate instance's comma
|
||||
now ends the line.
|
||||
|
||||
## 0.43.0 — 2026-09-05
|
||||
|
||||
### The repository analysis's three findings
|
||||
|
||||
- **Atomic writers cannot collide.** In-place writes use an exclusive,
|
||||
per-operation temp file (`.{name}.{pid}.{n}.lucisv-tmp`, created
|
||||
0600 when a target exists and given the target's mode before the bytes
|
||||
land); the CLI deduplicates its inputs by canonical identity, so a
|
||||
symlink alias of a file reaches one worker and is reported once. Two
|
||||
processes on one target remain last-writer-wins, which the formatter's
|
||||
idempotence makes safe.
|
||||
- **One lint-configuration contract.** The editor now honours a project's
|
||||
`[lint] select` and `[lint] ignore` the way the CLI honours its flags:
|
||||
`lucisv.lint.select` when set, else the project's, key by key, with the
|
||||
editor-only severity switches and per-rule toggles applied over whichever
|
||||
stands. A project entry the server cannot use — a rejected `[lint.<rule>]`
|
||||
option, an unknown rule name, a bad waiver directive — is logged once with
|
||||
file and line in `lucisv check`'s wording and dropped; the buffer keeps
|
||||
linting. The CLI's and the server's rule lists are asserted equal over
|
||||
the wire.
|
||||
- **Directory walks terminate on symlink cycles.** Each directory is
|
||||
entered once by identity; a link to a directory already entered is
|
||||
skipped, one not yet entered is followed once, a dangling directory link
|
||||
is skipped and a dangling source-file link is still reported. Both the
|
||||
CLI and the server's index scan.
|
||||
- A comment before a net delay's `#` (`wire /* c */ #5 w;`) now formats.
|
||||
|
||||
## 0.42.0 — 2026-09-05
|
||||
|
||||
### External waiver files, and the two vendor shapes the sweep skipped
|
||||
|
||||
- **External waiver files** in Verible's format: `waive --rule=<rule>
|
||||
[--line=N|N-M] [--location=<pattern>]`, `#` comments. Read from
|
||||
`[lint] waivers` in `lucisv.toml`, `lucisv check --waiver-file` (repeatable)
|
||||
and the editor setting `lucisv.lint.waivers`; the three add up.
|
||||
`--location` is an `--exclude`-style pattern, not a regex, and a
|
||||
regex-looking one is refused by name. Union with inline waivers; unused
|
||||
external waivers are reported under `unused-waiver` at their line of the
|
||||
waiver file by `lucisv check`, after the whole run. The editor's quick
|
||||
fixes and fix-on-save honour external waivers too.
|
||||
- **Rival module/interface headers across an `ifdef`/`else`** (opentitan's
|
||||
`jtag_if.sv`) now parse: the unit is kept verbatim as a whole, the
|
||||
standing directive-split trade, instead of nesting and losing its
|
||||
closer.
|
||||
- **A net delay after the type** (`wire [31:0] #0.1 x = y;`, where the LRM
|
||||
puts it) is accepted and printed where it was written.
|
||||
- Documentation: the repository analysis audit's README and site rewrite
|
||||
(architecture across all eight crates, topo facts at codec 17) is
|
||||
committed; its three findings are planned as TODO §41–§43.
|
||||
|
||||
## 0.41.0 — 2026-09-04
|
||||
|
||||
### Code actions off the fan-out
|
||||
|
||||
- **Lazy port refactorings.** For a client that supports
|
||||
`codeAction/resolve` (VS Code does), the port actions are offered from
|
||||
the buffer and the instantiated module's declaration alone, and the
|
||||
edit is computed when the action is picked. The request VS Code sends
|
||||
on nearly every cursor move no longer reads the module's fan-out:
|
||||
flat at ~55 µs in-process from a 3-file to a 128-file fan-out, where
|
||||
it was linear (15 ms at 128). A resolve for an action that no longer
|
||||
applies is an error, not an empty edit. Clients without resolve
|
||||
support get the edit up front, as before.
|
||||
- **Definitions from the index.** `textDocument/definition` and
|
||||
workspace symbols for a file-scope declaration in a closed file now
|
||||
build the location from the positions the index already records
|
||||
instead of reading the file: 0.4 µs against 28 µs per answer.
|
||||
- **inlayHint at the default scope**: investigated, not changed. The
|
||||
hints missing at that scope belong to a module declared outside what
|
||||
the scope reaches; definition and hover say the same. A scope
|
||||
question, recorded in the feature README.
|
||||
|
||||
## 0.40.0 — 2026-09-04
|
||||
|
||||
### Two parser residues and atomic writes
|
||||
|
||||
- **A bare `begin … end` at module scope, or straight inside
|
||||
`generate … endgenerate`, is recovered** in error-tolerant mode as an
|
||||
unnamed generate block (`ItemKind::GenBlock`) with a diagnostic at the
|
||||
keyword, instead of being refused and taking the rest of the unit with
|
||||
it. The items inside and after the block are now visible to the
|
||||
editor and to every lint rule; `module-begin-block`,
|
||||
`v2001-generate-begin` and `mismatched-labels` read the node. Strict
|
||||
parsing is unchanged, so the formatter still refuses the file exactly
|
||||
as before.
|
||||
- **A half-typed `#(` override or connection whose value would read as
|
||||
the next instance** (`sub #(.W(8), .DEPTH(` ⏎ `u0 (.a(x));`) now costs
|
||||
one error element: `.W(8)` survives, `u0` is an instance with its
|
||||
connections, one diagnostic on the unclosed `(`. The balanced-parens
|
||||
spelling stays ambiguous and is still parsed greedily, by design.
|
||||
- **In-place writes are atomic.** `lucisv format`, `lucisv check --fix`
|
||||
and the cache write a sibling temp file and rename it over the target,
|
||||
so a crash or a full disk never leaves a source file truncated. The
|
||||
target's permissions are kept, a symlink's *target* is what gets
|
||||
replaced, and a read-only file is refused as it always was.
|
||||
|
||||
## 0.39.0 — 2026-09-04
|
||||
|
||||
### The rest of Verible's rules
|
||||
|
||||
Generated
+9
-8
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.39.0"
|
||||
version = "0.44.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.39.0"
|
||||
version = "0.44.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.39.0"
|
||||
version = "0.44.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,15 +248,16 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.39.0"
|
||||
version = "0.44.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.39.0"
|
||||
version = "0.44.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
@@ -264,11 +265,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.39.0"
|
||||
version = "0.44.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.39.0"
|
||||
version = "0.44.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
@@ -276,7 +277,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.39.0"
|
||||
version = "0.44.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.39.0"
|
||||
version = "0.44.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -2,6 +2,12 @@
|
||||
|
||||
A Verilog and SystemVerilog formatter, linter, and language server written in Rust.
|
||||
|
||||
Start with the [repository analysis](docs/repository-analysis.md) for a code-based
|
||||
assessment and [dependency topology](docs/topo.md) for interfaces and change
|
||||
impact. The [documentation site source](docs/site/README.md) contains usage
|
||||
guides and references; [CHANGELOG.md](CHANGELOG.md) records releases, and
|
||||
[TODO.md](TODO.md) tracks work in progress.
|
||||
|
||||
An opinionated, fast formatter and linter for Verilog-2001 and SystemVerilog
|
||||
RTL, built in the image of [ruff](https://github.com/astral-sh/ruff), with
|
||||
layout conventions and lint ergonomics borrowed from
|
||||
@@ -160,9 +166,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 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:
|
||||
supported subset (tables other than `[lint]` and `[lint.<rule>]`, multi-line
|
||||
arrays, unsupported string escapes) is a hard error naming the file and
|
||||
line — exit 2, with nothing written. This is deliberate:
|
||||
a silently ignored `line_length` typo costs more than a strict parser does.
|
||||
|
||||
## Linting
|
||||
@@ -387,13 +393,61 @@ wire a; // lucisv: waive no-tabs suppresses that rule on this line
|
||||
works unedited — including waivers naming Verible rules lucisv has not
|
||||
implemented, which are ignored rather than reported. A waiver of lucisv's own
|
||||
that suppresses nothing, names an unknown rule or is malformed is reported
|
||||
under `unused-waiver`. External waiver files are not supported. Full rules:
|
||||
under `unused-waiver`.
|
||||
|
||||
Findings can also be suppressed from **outside** the RTL, in Verible's
|
||||
waiver-file format — one directive per line, `#` comments and blank lines
|
||||
ignored:
|
||||
|
||||
```text
|
||||
# every line of every file
|
||||
waive --rule=no-tabs
|
||||
# one line, or a range with both ends included
|
||||
waive --rule=line-length --line=12
|
||||
waive --rule=line-length --line=12-20
|
||||
# only the files a pattern names
|
||||
waive --rule=no-tabs --location=legacy/top.sv
|
||||
```
|
||||
|
||||
`--rule` is required and names exactly one rule (a severity word is not
|
||||
accepted). `--line` is 1-based. `--location` is matched the way an
|
||||
`--exclude` pattern is — `*` within one path component, a pattern with `/`
|
||||
matching a path suffix, one without matching the file name at any depth — and
|
||||
**not** as a regular expression; a pattern that looks like one (`.*`, `\.`,
|
||||
`[…]`) is an error naming the difference.
|
||||
|
||||
Waiver files come from three places, and they add up: `lucisv check
|
||||
--waiver-file <path>` (repeatable, relative to the working directory),
|
||||
`waivers` under `[lint]` in `lucisv.toml` (relative to that file; read by the
|
||||
CLI and the editor), and the editor setting `lucisv.lint.waivers` (relative to
|
||||
the first workspace folder). External and inline waivers are a union: a
|
||||
finding either covers is suppressed, and one both cover leaves neither
|
||||
reported as dead. A missing file or an unparsable directive fails `lucisv
|
||||
check` with `<file>:<line>: <message>` and exit 2; in an editor the bad line
|
||||
is dropped and the rest of the file applies, and the bad line is written once
|
||||
to the lucisv log whether the file was named by the editor setting or by
|
||||
`lucisv.toml`. Unused external waivers
|
||||
are reported under `unused-waiver` at their line of the waiver file, by
|
||||
`lucisv check` only and only after the whole run.
|
||||
Both front ends read the same configuration, and the editor's settings play
|
||||
the role the CLI's flags play: `lucisv.lint.select` when it is set, else
|
||||
`[lint] select` from the buffer's `lucisv.toml`, else the default set — and
|
||||
the same for `ignore`, decided independently. `lucisv.lint.severity.*` and
|
||||
`lucisv.lint.rules.*` have no project counterpart and apply over whichever
|
||||
selection stands. Project per-rule options are read by both front ends. A
|
||||
project entry lucisv cannot use — an unknown rule name in `[lint]
|
||||
select`/`ignore`, a rejected `[lint.<rule>]` option, an unreadable waiver
|
||||
file or a directive that does not parse — fails `lucisv check` with
|
||||
`<file>:<line>: <message>` and exit 2; in an editor it is dropped, written
|
||||
once to the lucisv log in the same words, and everything lucisv did
|
||||
understand still lints the buffer. Full rules:
|
||||
`docs/features/linter-core/README.md`.
|
||||
|
||||
## Architecture (the ruff mapping)
|
||||
|
||||
The workspace mirrors ruff's crate layout — a comment-preserving parser, a
|
||||
generic pretty-printing IR, language formatting rules, and a thin CLI:
|
||||
The eight-crate workspace separates source syntax, reusable engines, project
|
||||
inputs, and the CLI/LSP front ends. The formatter follows ruff's separation
|
||||
of document layout from language rules:
|
||||
|
||||
| This repo | ruff equivalent | Role |
|
||||
|---|---|---|
|
||||
@@ -401,7 +455,20 @@ generic pretty-printing IR, language formatting rules, and a thin CLI:
|
||||
| `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/` | `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 |
|
||||
| `crates/vlog_semantic` | — | File scopes and references, workspace index, conservative cross-file resolution |
|
||||
| `crates/vlog_refactor` | — | Verified rename, references, port refactors, instantiation plans |
|
||||
| `crates/lucisv_core` | — | Shared config, filelists, walks, format cache, atomic replacement |
|
||||
| `crates/lucisv` | the `ruff` CLI | Parallel per-file formatting/linting, reports, stdin, in-place writes |
|
||||
| `crates/lucisv_server` | — | Synchronous LSP loop, open-buffer overlays, indexing, editor capabilities |
|
||||
|
||||
`vlog_parser` and `lucisv_core` have no dependencies. The formatter depends
|
||||
only on the parser; semantic analysis also depends only on the parser.
|
||||
Linting consumes the parser, semantics and `lucisv_core` (for the one
|
||||
`--exclude`-style matcher a waiver file's `--location` shares with the CLI);
|
||||
refactoring consumes the parser and semantics. The CLI reaches
|
||||
semantics through the linter and has no refactoring dependency. The server
|
||||
composes all six libraries. See [topo.md](docs/topo.md) for the full graph,
|
||||
including the linter's formatter dependency used only by tests.
|
||||
|
||||
Key ideas carried over from ruff/prettier:
|
||||
|
||||
@@ -414,8 +481,15 @@ Key ideas carried over from ruff/prettier:
|
||||
lists, expressions, concatenations) is a `Group`: it renders on one line if
|
||||
it fits within the line limit, otherwise it breaks one-element-per-line.
|
||||
A comment inside a group forces it to break.
|
||||
- **Idempotency as a hard invariant.** The test suite formats every fixture
|
||||
twice and asserts a fixed point.
|
||||
- **Verification on every formatting call.** The engine re-lexes input and
|
||||
output and compares normalized tokens, including comments. It then parses
|
||||
and formats the output again and requires a fixed point. Either check can
|
||||
reject the result; the caller retains the original file. This is a lexical
|
||||
safety net, not compiler elaboration or a proof of hardware equivalence.
|
||||
- **Two parsing modes.** Formatting uses strict parsing. Linting and the
|
||||
editor use tolerant parsing: failed elements become error leaves while
|
||||
valid siblings remain available for analysis. A lexer failure is still
|
||||
all-or-nothing. Neither mode performs cross-file macro expansion.
|
||||
|
||||
## Style
|
||||
|
||||
@@ -871,8 +945,11 @@ vim.lsp.enable('lucisv')
|
||||
**Which files the server indexes.** A filelist if the project has one — the
|
||||
`filelist` key of its `lucisv.toml`, or the editor setting `lucisv.filelist`
|
||||
(a path, absolute or relative to the workspace folder) — and then exactly the
|
||||
files it names. Otherwise the workspace folder, walked as the CLI walks it;
|
||||
and with no folder open at all, the current file's own directory. Open buffers
|
||||
files it names. Otherwise the default `lucisv.index.scope = "folder"` starts
|
||||
from open-file folders, widens by `lucisv.index.scopeDepth` (default 2), and stays bounded by
|
||||
the workspace roots; `"workspace"` walks the full roots. With no folder open,
|
||||
the server stays in the current file's directory: depth 0 scans it flat; a
|
||||
positive depth walks its descendants but never climbs to a parent. Open buffers
|
||||
are always indexed on top. A filelist that cannot be read warns and falls back
|
||||
to the folder walk, so the index is never silently empty.
|
||||
|
||||
@@ -903,11 +980,20 @@ expected; no PRs or review required.
|
||||
|
||||
```bash
|
||||
cargo build --release # binaries at target/release/{lucisv,lucisv-server}
|
||||
cargo test # unit + snapshot + idempotency tests
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
tools/guard.sh -- cargo test --workspace # unit, integration, snapshots, doc tests
|
||||
```
|
||||
|
||||
Snapshot tests live in `crates/vlog_formatter/tests/fixtures/`; regenerate
|
||||
expected outputs with `UPDATE_SNAPSHOTS=1 cargo test -p vlog_formatter`.
|
||||
expected outputs only for intentional formatting changes with
|
||||
`UPDATE_SNAPSHOTS=1 tools/guard.sh -- cargo test -p vlog_formatter`.
|
||||
Table-driven cases live in `crates/vlog_formatter/tests/cases/`; lint cases
|
||||
live in `crates/vlog_linter/tests/cases/`. All tests, fuzzers, and corpus/tree
|
||||
sweeps must run through `tools/guard.sh` (8 GiB RSS / 30 minutes by default),
|
||||
as required by [CLAUDE.md](CLAUDE.md). A guard kill is a finding, not a reason
|
||||
to increase the limit. Documentation build instructions are in
|
||||
[docs/site/README.md](docs/site/README.md).
|
||||
|
||||
## Install and releases
|
||||
|
||||
|
||||
@@ -71,6 +71,12 @@ pub struct Options {
|
||||
pub select: Vec<String>,
|
||||
/// `check` only: rules to drop from whatever `--select` left.
|
||||
pub ignore: Vec<String>,
|
||||
/// `check` only: external waiver files, relative to the current
|
||||
/// directory. They *add* to whatever `[lint] waivers` in a `lucisv.toml`
|
||||
/// names — a waiver file suppresses findings and can only ever suppress
|
||||
/// fewer of them by being left out, so there is nothing here for a
|
||||
/// command line flag to override.
|
||||
pub waiver_files: Vec<String>,
|
||||
/// `check` only: print the generated rule reference and exit, reading no
|
||||
/// file at all.
|
||||
pub rules_doc: bool,
|
||||
@@ -203,6 +209,9 @@ 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)
|
||||
--waiver-file <PATH> read waiver directives from this file; may be
|
||||
repeated, and adds to whatever `[lint] waivers`
|
||||
in a lucisv.toml already names
|
||||
--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
|
||||
@@ -215,6 +224,31 @@ CHECK OPTIONS (`lucisv check` only):
|
||||
accepted in place of `lucisv:`. A waiver that suppresses nothing is
|
||||
reported under the `unused-waiver` rule.
|
||||
|
||||
WAIVER FILES:
|
||||
Findings can also be suppressed from outside the RTL, in Verible's waiver
|
||||
file format — one directive per line, `#` comments and blank lines ignored:
|
||||
|
||||
waive --rule=<rule> every line of every file
|
||||
waive --rule=<rule> --line=12 one line
|
||||
waive --rule=<rule> --line=12-20 a range, both ends included
|
||||
waive --rule=<rule> --location=legacy.sv the files that pattern names
|
||||
|
||||
`--rule` is required and names one rule (a severity word is not accepted);
|
||||
`--line` is 1-based and a range includes both ends; `--location` is matched
|
||||
the way an `--exclude` pattern is — `*` within one path component, a
|
||||
pattern with `/` against a path suffix and one without against the file
|
||||
name. Unlike Verible's, it is **not** a regular expression, and a pattern
|
||||
that looks like one is an error rather than a silent mismatch.
|
||||
|
||||
lucisv reads `--waiver-file <PATH>` (relative to the current directory) and
|
||||
every path in `waivers` under `[lint]` in a `lucisv.toml` (relative to that
|
||||
file). An external waiver and an inline one are a union: a finding either
|
||||
covers is suppressed, and neither is then reported as dead. A file that
|
||||
does not exist, or a directive that does not parse, fails the run with
|
||||
`<file>:<line>: message` and exit 2. An external waiver that suppressed
|
||||
nothing anywhere in the run is reported under `unused-waiver`, at the line
|
||||
of the waiver file it was written on.
|
||||
|
||||
IGNORE FILES:
|
||||
While walking a directory, lucisv reads a `.gitignore` in every directory it
|
||||
enters and skips what it names; a deeper file overrides a shallower one and
|
||||
@@ -250,8 +284,11 @@ CONFIGURATION:
|
||||
read by lucisv-server only — the CLI reads a filelist only when `-f` names
|
||||
one, so `lucisv rtl/` always means the directory it was given). One table
|
||||
is recognized, `[lint]`, with `select` and `ignore` (arrays of rule names,
|
||||
`--select`/`--ignore` semantics). A command line flag overrides the file's
|
||||
corresponding key; the other keys still apply.
|
||||
`--select`/`--ignore` semantics) and `waivers` (an array of waiver file
|
||||
paths, resolved against the config file's own directory). A command line
|
||||
flag overrides the file's corresponding key; the other keys still apply —
|
||||
`--waiver-file` is the exception, and adds to `waivers` rather than
|
||||
replacing it.
|
||||
|
||||
RANGE FORMATTING:
|
||||
`--lines` formats one construct at a time: an item whose lines meet a range
|
||||
@@ -298,6 +335,7 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
unsafe_fixes: false,
|
||||
select: Vec::new(),
|
||||
ignore: Vec::new(),
|
||||
waiver_files: Vec::new(),
|
||||
rules_doc: false,
|
||||
inputs: Vec::new(),
|
||||
filelists: Vec::new(),
|
||||
@@ -378,6 +416,10 @@ 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));
|
||||
}
|
||||
"--waiver-file" => {
|
||||
let v = args.next().ok_or("--waiver-file requires a value")?;
|
||||
opts.waiver_files.push(v);
|
||||
}
|
||||
"--rules-doc" => opts.rules_doc = true,
|
||||
"-h" | "--help" => {
|
||||
print_help();
|
||||
@@ -444,6 +486,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.waiver_files.is_empty(), "--waiver-file"),
|
||||
(opts.rules_doc, "--rules-doc"),
|
||||
];
|
||||
let format_only = [
|
||||
@@ -614,6 +657,16 @@ mod tests {
|
||||
assert!(parse(&["--no-gitignore", "rtl"]).unwrap().no_gitignore);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn waiver_files_are_collected_in_order_and_are_lint_only() {
|
||||
let opts = parse(&["check", "--waiver-file", "a.waiver", "--waiver-file", "b", "rtl"])
|
||||
.expect("parsed");
|
||||
assert_eq!(opts.waiver_files, vec!["a.waiver", "b"]);
|
||||
assert!(parse(&["check", "rtl"]).unwrap().waiver_files.is_empty());
|
||||
assert!(parse(&["check", "--waiver-file"]).is_err(), "a value is required");
|
||||
assert!(parse(&["--waiver-file", "a.waiver", "rtl"]).is_err(), "not a formatter flag");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_doc_is_the_one_check_that_needs_no_input() {
|
||||
assert!(parse(&["check", "--rules-doc"]).unwrap().rules_doc);
|
||||
|
||||
+165
-41
@@ -9,13 +9,15 @@ use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
|
||||
use lucisv_core::atomic::write_atomic;
|
||||
use lucisv_core::config::FileConfig;
|
||||
use rayon::prelude::*;
|
||||
use vlog_formatter::fence::{self, Region};
|
||||
use vlog_formatter::Config;
|
||||
use vlog_linter::words;
|
||||
use vlog_linter::{
|
||||
apply_fixes, lint, Fix, MentionOracle, ParsedSource, Rule, RuleOptions, Violation,
|
||||
apply_fixes, lint_with, ExternalWaivers, Fix, MentionOracle, ParsedSource, Rule, RuleOptions,
|
||||
Violation, WaiverUse,
|
||||
};
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
@@ -45,6 +47,15 @@ pub struct Plan {
|
||||
/// The project's identifier census, built when at least one selected rule
|
||||
/// asks for a workspace and there is more than one file to ask about.
|
||||
census: Option<Census>,
|
||||
/// Every external waiver file the run reads, applied to every job.
|
||||
///
|
||||
/// One set for the whole run rather than one per file, because a
|
||||
/// `--location` pattern names files and a waiver is only *unused* when no
|
||||
/// file in the run matched it — a question only the whole run can answer.
|
||||
external: ExternalWaivers,
|
||||
/// Every rule name any job in the run has switched on, for deciding which
|
||||
/// external waivers never had a chance to fire.
|
||||
enabled: Vec<&'static str>,
|
||||
}
|
||||
|
||||
/// How many of the run's files write each identifier down.
|
||||
@@ -162,6 +173,7 @@ impl MentionOracle for Elsewhere<'_> {
|
||||
/// already says about itself.
|
||||
pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Result<Plan, String> {
|
||||
let workspace = gathered.len() > 1;
|
||||
let external = external_waivers(opts, gathered.iter().map(|(_, _, file)| file))?;
|
||||
let mut jobs = Vec::with_capacity(gathered.len());
|
||||
for (path, config, file_config) in gathered {
|
||||
let select = pick(&opts.select, file_config.lint_select.as_deref());
|
||||
@@ -174,7 +186,56 @@ pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Res
|
||||
let wanted = jobs.iter().any(|job| job.rules.iter().any(|rule| rule.needs_workspace()));
|
||||
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 })
|
||||
let mut enabled: Vec<&'static str> =
|
||||
jobs.iter().flat_map(|job| job.rules.iter().map(|rule| rule.name())).collect();
|
||||
enabled.sort_unstable();
|
||||
enabled.dedup();
|
||||
Ok(Plan { jobs, census, external, enabled })
|
||||
}
|
||||
|
||||
/// The run's external waiver files, read once each: `--waiver-file` in flag
|
||||
/// order, then every `[lint] waivers` entry of a config file governing an
|
||||
/// input.
|
||||
///
|
||||
/// The two **add up** rather than override: a waiver file only ever suppresses
|
||||
/// findings, so there is nothing for a command line to take back. A file named
|
||||
/// twice over — the flag and a `lucisv.toml`, or one `lucisv.toml` governing
|
||||
/// five hundred files — is read once, or its directives would each be reported
|
||||
/// unused as many times as the file was read.
|
||||
///
|
||||
/// A file that cannot be read, or a directive that does not parse, fails the
|
||||
/// run naming the file and the line, exactly as a bad `[lint.<rule>]` entry
|
||||
/// does and for the same reason: a user wrote it and is watching.
|
||||
pub fn external_waivers<'a>(
|
||||
opts: &Options,
|
||||
configs: impl Iterator<Item = &'a FileConfig>,
|
||||
) -> Result<ExternalWaivers, String> {
|
||||
let mut paths: Vec<PathBuf> = opts.waiver_files.iter().map(PathBuf::from).collect();
|
||||
for config in configs {
|
||||
for path in config.lint_waivers.iter().flatten() {
|
||||
paths.push(path.clone());
|
||||
}
|
||||
}
|
||||
let mut read: Vec<PathBuf> = Vec::new();
|
||||
let mut waivers = ExternalWaivers::default();
|
||||
for path in paths {
|
||||
// Compared canonically, because the flag's path is relative to the
|
||||
// working directory and a `lucisv.toml`'s is absolute: the same file
|
||||
// named both ways is still one file, and reading it twice would report
|
||||
// each of its dead directives twice. Only the *comparison* is
|
||||
// canonical — the path a diagnostic names stays the one written.
|
||||
let key = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
|
||||
if read.contains(&key) {
|
||||
continue;
|
||||
}
|
||||
let (file, problems) = ExternalWaivers::read(&path)?;
|
||||
if let Some(problem) = problems.first() {
|
||||
return Err(problem.clone());
|
||||
}
|
||||
waivers.absorb(file);
|
||||
read.push(key);
|
||||
}
|
||||
Ok(waivers)
|
||||
}
|
||||
|
||||
/// The `[lint.<rule>]` entries of one file's config, resolved against the
|
||||
@@ -233,12 +294,30 @@ struct Report {
|
||||
violations: Vec<Violation>,
|
||||
/// Violations whose fix was applied and written back.
|
||||
fixed: usize,
|
||||
/// Which of the run's external waivers suppressed something in this file.
|
||||
/// Merged across every file before the dead ones are reported.
|
||||
used: WaiverUse,
|
||||
/// Set when the file could not be fully checked: unreadable, unwritable,
|
||||
/// or — because the lexer is all-or-nothing — unlexable, in which case
|
||||
/// only the text-level rules saw it.
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
/// Everything one file's lint pass reads besides the file itself.
|
||||
///
|
||||
/// One value rather than six parameters: every function below the driver
|
||||
/// needs the same set, and the `--fix` loop passes it down another level
|
||||
/// again.
|
||||
struct Pass<'a> {
|
||||
config: &'a Config,
|
||||
rules: &'a [&'static dyn Rule],
|
||||
options: &'a RuleOptions,
|
||||
census: Option<&'a Census>,
|
||||
/// The run's external waiver files. Empty unless `--waiver-file` or a
|
||||
/// `[lint] waivers` named one, and then costing nothing.
|
||||
external: &'a ExternalWaivers,
|
||||
}
|
||||
|
||||
/// Lints every gathered file and reports. Exit 1 if anything is left over,
|
||||
/// 2 if a file could not be read, written, or lexed.
|
||||
pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
|
||||
@@ -246,9 +325,20 @@ pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
|
||||
.jobs
|
||||
.par_iter()
|
||||
.map(|job| {
|
||||
check_one(&job.path, &job.config, opts, &job.rules, &job.options, plan.census.as_ref())
|
||||
let pass = Pass {
|
||||
config: &job.config,
|
||||
rules: &job.rules,
|
||||
options: &job.options,
|
||||
census: plan.census.as_ref(),
|
||||
external: &plan.external,
|
||||
};
|
||||
check_one(&job.path, opts, &pass)
|
||||
})
|
||||
.collect();
|
||||
// The dead external waivers are found once every file has been linted,
|
||||
// and reported against the waiver file, which then sorts in among the
|
||||
// sources like any other path.
|
||||
reports.extend(dead_waivers(&plan.external, &reports, &plan.enabled));
|
||||
// Diagnostics are printed sorted by path, then by position within the
|
||||
// file (`lint` already sorts those), so a run over a directory reads
|
||||
// top to bottom whatever order the walk or the worker pool produced.
|
||||
@@ -256,6 +346,37 @@ pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
|
||||
finish(opts, reports)
|
||||
}
|
||||
|
||||
/// The `unused-waiver` reports for external waivers no file in the run used.
|
||||
///
|
||||
/// **After the whole run**, which is the whole reason this is the CLI's job
|
||||
/// and not the linter's: a `--location` pattern may match a file the run has
|
||||
/// not reached yet, so a waiver is only dead once every file has been asked.
|
||||
fn dead_waivers(
|
||||
external: &ExternalWaivers,
|
||||
reports: &[Report],
|
||||
enabled: &[&'static str],
|
||||
) -> Vec<Report> {
|
||||
if external.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut used = WaiverUse::default();
|
||||
for report in reports {
|
||||
used.merge(&report.used);
|
||||
}
|
||||
external
|
||||
.unused(&used, enabled)
|
||||
.into_iter()
|
||||
.map(|dead| Report {
|
||||
path: dead.path.display().to_string(),
|
||||
index: LineIndex::new(&dead.text),
|
||||
violations: dead.violations,
|
||||
fixed: 0,
|
||||
used: WaiverUse::default(),
|
||||
error: None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Lints a buffer piped in on stdin. `--stdin-filename` names it, and is
|
||||
/// what the rules that need a file name see.
|
||||
pub fn check_stdin(
|
||||
@@ -264,32 +385,34 @@ pub fn check_stdin(
|
||||
config: &Config,
|
||||
rules: &[&'static dyn Rule],
|
||||
options: &RuleOptions,
|
||||
external: &ExternalWaivers,
|
||||
) -> ExitCode {
|
||||
let name = opts.stdin_filename.clone().unwrap_or_else(|| "<stdin>".to_string());
|
||||
let path = opts.stdin_filename.as_ref().map(PathBuf::from);
|
||||
let (violations, lex_error) = run_rules(src, path, config, rules, options, None);
|
||||
let pass = Pass { config, rules, options, census: None, external };
|
||||
let (violations, used, lex_error) = run_rules(src, path, &pass);
|
||||
// Nothing is ever written back for stdin, so `--fix` has nothing to do
|
||||
// here; the violations are reported as they are.
|
||||
let error = lex_error.map(|e| format!("{name}: {e}"));
|
||||
let report = Report { path: name, index: LineIndex::new(src), violations, fixed: 0, error };
|
||||
finish(opts, vec![report])
|
||||
let report =
|
||||
Report { path: name, index: LineIndex::new(src), violations, fixed: 0, used, error };
|
||||
// One buffer is a whole run too, so a waiver that covered nothing in it is
|
||||
// as dead as one that covered nothing in a directory.
|
||||
let names: Vec<&'static str> = rules.iter().map(|rule| rule.name()).collect();
|
||||
let mut reports = vec![report];
|
||||
reports.extend(dead_waivers(external, &reports, &names));
|
||||
finish(opts, reports)
|
||||
}
|
||||
|
||||
/// Lints one file, optionally fixing it, and never panics out of its worker.
|
||||
fn check_one(
|
||||
file: &Path,
|
||||
config: &Config,
|
||||
opts: &Options,
|
||||
rules: &[&'static dyn Rule],
|
||||
options: &RuleOptions,
|
||||
census: Option<&Census>,
|
||||
) -> Report {
|
||||
fn check_one(file: &Path, opts: &Options, pass: &Pass) -> Report {
|
||||
let path = file.display().to_string();
|
||||
let failed = |error: String| Report {
|
||||
path: path.clone(),
|
||||
index: LineIndex::new(""),
|
||||
violations: Vec::new(),
|
||||
fixed: 0,
|
||||
used: WaiverUse::default(),
|
||||
error: Some(error),
|
||||
};
|
||||
|
||||
@@ -299,20 +422,19 @@ fn check_one(
|
||||
};
|
||||
let outcome = crate::catch_panic(|| {
|
||||
if opts.fix {
|
||||
fix_source(&src, file, config, opts, rules, options, census)
|
||||
fix_source(&src, file, opts, pass)
|
||||
} else {
|
||||
let (violations, lex_error) =
|
||||
run_rules(&src, Some(file.to_path_buf()), config, rules, options, census);
|
||||
(violations, None, 0, lex_error)
|
||||
let (violations, used, lex_error) = run_rules(&src, Some(file.to_path_buf()), pass);
|
||||
(violations, used, None, 0, lex_error)
|
||||
}
|
||||
});
|
||||
let (violations, rewritten, fixed, lex_error) = match outcome {
|
||||
let (violations, used, rewritten, fixed, lex_error) = match outcome {
|
||||
Ok(outcome) => outcome,
|
||||
Err(msg) => return failed(format!("{path}: panicked while linting: {msg}")),
|
||||
};
|
||||
let index = LineIndex::new(rewritten.as_deref().unwrap_or(&src));
|
||||
if let Some(text) = rewritten {
|
||||
if let Err(e) = std::fs::write(file, &text) {
|
||||
if let Err(e) = write_atomic(file, text.as_bytes()) {
|
||||
return failed(format!("{path}: {e}"));
|
||||
}
|
||||
}
|
||||
@@ -321,21 +443,20 @@ fn check_one(
|
||||
// so the file must not pass as checked. It is an error (exit 2), exactly
|
||||
// as `lucisv format` treats the same file.
|
||||
let error = lex_error.map(|e| format!("{path}: {e}"));
|
||||
Report { path, index, violations, fixed, error }
|
||||
Report { path, index, violations, fixed, used, error }
|
||||
}
|
||||
|
||||
/// Runs the rules over one text. The second half of the answer is the lex
|
||||
/// error when the text does not lex — rendered `line:col: message`, ready
|
||||
/// for a path prefix — because a file with no tokens was only text-linted
|
||||
/// and must be reported as an error, not passed off as clean.
|
||||
/// Runs the rules over one text, reporting which external waivers fired. The
|
||||
/// last part of the answer is the lex error when the text does not lex —
|
||||
/// rendered `line:col: message`, ready for a path prefix — because a file with
|
||||
/// no tokens was only text-linted and must be reported as an error, not passed
|
||||
/// off as clean.
|
||||
fn run_rules(
|
||||
src: &str,
|
||||
path: Option<PathBuf>,
|
||||
config: &Config,
|
||||
rules: &[&'static dyn Rule],
|
||||
options: &RuleOptions,
|
||||
census: Option<&Census>,
|
||||
) -> (Vec<Violation>, Option<String>) {
|
||||
pass: &Pass,
|
||||
) -> (Vec<Violation>, WaiverUse, Option<String>) {
|
||||
let Pass { config, rules, options, census, external } = *pass;
|
||||
// One parse per file (TODO §4): the products are built here, once, and
|
||||
// lent to the context. Under `--fix` each *round* re-enters through this
|
||||
// function with rewritten text — that re-parse is inherent (the old
|
||||
@@ -359,7 +480,8 @@ fn run_rules(
|
||||
Some(elsewhere) => ctx.with_oracle(elsewhere),
|
||||
None => ctx,
|
||||
};
|
||||
(lint(&ctx, rules), lex_error)
|
||||
let (violations, used) = lint_with(&ctx, rules, external);
|
||||
(violations, used, lex_error)
|
||||
}
|
||||
|
||||
/// The violations whose fix may be applied: everything except a fix that
|
||||
@@ -398,16 +520,15 @@ fn touches_fence(fix: &Fix, regions: &[Region]) -> bool {
|
||||
fn fix_source(
|
||||
src: &str,
|
||||
file: &Path,
|
||||
config: &Config,
|
||||
opts: &Options,
|
||||
rules: &[&'static dyn Rule],
|
||||
options: &RuleOptions,
|
||||
census: Option<&Census>,
|
||||
) -> (Vec<Violation>, Option<String>, usize, Option<String>) {
|
||||
pass: &Pass,
|
||||
) -> (Vec<Violation>, WaiverUse, Option<String>, usize, Option<String>) {
|
||||
let mut text = src.to_string();
|
||||
let mut fixed = 0;
|
||||
let (mut violations, mut lex_error) =
|
||||
run_rules(&text, Some(file.to_path_buf()), config, rules, options, census);
|
||||
let mut used = WaiverUse::default();
|
||||
let (mut violations, mut round_used, mut lex_error) =
|
||||
run_rules(&text, Some(file.to_path_buf()), pass);
|
||||
used.merge(&round_used);
|
||||
for _ in 0..MAX_FIX_ROUNDS {
|
||||
let round =
|
||||
apply_fixes(&text, &fixable_outside_fences(&text, &violations), opts.unsafe_fixes);
|
||||
@@ -416,11 +537,14 @@ fn fix_source(
|
||||
}
|
||||
fixed += round.applied;
|
||||
text = round.output;
|
||||
(violations, lex_error) =
|
||||
run_rules(&text, Some(file.to_path_buf()), config, rules, options, census);
|
||||
(violations, round_used, lex_error) = run_rules(&text, Some(file.to_path_buf()), pass);
|
||||
// A waiver that covered a finding in an earlier round did its job even
|
||||
// though the fix then removed the finding, so usage accumulates over
|
||||
// the rounds rather than being the last round's.
|
||||
used.merge(&round_used);
|
||||
}
|
||||
let rewritten = (text != src).then_some(text);
|
||||
(violations, rewritten, fixed, lex_error)
|
||||
(violations, used, rewritten, fixed, lex_error)
|
||||
}
|
||||
|
||||
/// Prints the run and turns it into an exit code.
|
||||
|
||||
@@ -27,6 +27,7 @@ use std::process::ExitCode;
|
||||
use rayon::prelude::*;
|
||||
|
||||
use args::{Command, Options};
|
||||
use lucisv_core::atomic::write_atomic;
|
||||
use lucisv_core::cache::{content_hash, Cache, Entry};
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use lucisv_core::filelist;
|
||||
@@ -127,7 +128,17 @@ fn run_check(opts: &Options) -> ExitCode {
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
return lint::check_stdin(opts, &src, &config, &rules, &options);
|
||||
// A stdin buffer has one config file too — the one governing
|
||||
// `--stdin-filename`, or the working directory's — so `[lint] waivers`
|
||||
// reaches it exactly as `[lint] select` does.
|
||||
let external = match lint::external_waivers(opts, std::iter::once(&file_config)) {
|
||||
Ok(external) => external,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
return lint::check_stdin(opts, &src, &config, &rules, &options, &external);
|
||||
}
|
||||
let jobs = match gather(opts).and_then(|jobs| build_pool(opts).map(|()| jobs)) {
|
||||
Ok(jobs) => jobs,
|
||||
@@ -306,7 +317,7 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
|
||||
FileResult::plain(Outcome::Changed(diff::unified(&name.to_string(), &src, &out)))
|
||||
} else if opts.check {
|
||||
FileResult::plain(Outcome::Changed(format!("would reformat: {name}\n")))
|
||||
} else if let Err(e) = std::fs::write(file, &out) {
|
||||
} else if let Err(e) = write_atomic(file, out.as_bytes()) {
|
||||
FileResult::plain(Outcome::Failed(format!("{name}: {e}")))
|
||||
} else {
|
||||
// The bytes now on disk are formatted, so they are what the cache
|
||||
@@ -355,7 +366,12 @@ fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config, FileConfig)>, String>
|
||||
return Err(format!("--lines needs a file, not a directory: {input}"));
|
||||
}
|
||||
let exclude = opts.exclude_with(&discovery.for_input(Path::new(input))?);
|
||||
collect_files(input, &exclude, !opts.no_gitignore, &mut files)?;
|
||||
// The walk's own warnings — an unreadable directory, a source file
|
||||
// that is only a broken link — go to stderr as they are found, before
|
||||
// the report and exactly as a filelist's do. A warning is not a
|
||||
// failure: the exit code is the formatting's alone.
|
||||
let mut warn = |w| eprintln!("warning: {w}");
|
||||
collect_files(input, &exclude, !opts.no_gitignore, &mut files, &mut warn)?;
|
||||
}
|
||||
// Filelists come after the command line's own inputs, in flag order: they
|
||||
// add files, they never replace or reorder what was named directly.
|
||||
@@ -404,13 +420,25 @@ fn filelist_files(opts: &Options) -> Result<Vec<PathBuf>, String> {
|
||||
fn dedup(files: Vec<PathBuf>) -> Vec<PathBuf> {
|
||||
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
|
||||
let mut seen = HashSet::new();
|
||||
files.into_iter().filter(|file| seen.insert(absolute(&cwd, file))).collect()
|
||||
files.into_iter().filter(|file| seen.insert(identity(&cwd, file))).collect()
|
||||
}
|
||||
|
||||
/// The key two spellings of one file share: the file's canonical path when it
|
||||
/// is there, and the lexical fold when it is not.
|
||||
///
|
||||
/// Canonical means symlinks resolved, which is the only way to see that
|
||||
/// `b.sv -> a.sv` is the file `a.sv` already named — two rayon workers on one
|
||||
/// target otherwise, each rewriting what the other just wrote. A path with no
|
||||
/// file behind it has no canonical form, and the lexical fold is then the
|
||||
/// best two names for it can be compared by. Neither is ever the path lucisv
|
||||
/// reports: that stays the first spelling seen.
|
||||
fn identity(cwd: &Path, path: &Path) -> PathBuf {
|
||||
std::fs::canonicalize(path).unwrap_or_else(|_| absolute(cwd, path))
|
||||
}
|
||||
|
||||
/// `path` folded to the absolute, `.`/`..`-free spelling two names for one
|
||||
/// file share. Lexical, like `lucisv_core`'s own normalization: symlinks are
|
||||
/// deliberately left unresolved, so this is only ever a dedup key and never
|
||||
/// the path lucisv reports.
|
||||
/// file share. Purely lexical, like `lucisv_core`'s own normalization — it
|
||||
/// answers for paths that do not exist, where there is nothing to resolve.
|
||||
fn absolute(cwd: &Path, path: &Path) -> PathBuf {
|
||||
let joined = if path.is_absolute() { path.to_path_buf() } else { cwd.join(path) };
|
||||
let mut out = PathBuf::new();
|
||||
@@ -591,6 +619,37 @@ mod tests {
|
||||
assert_eq!(dedup(files), [cwd.join("rtl/a.sv")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dedup_folds_a_symlink_onto_the_file_it_points_at() {
|
||||
// A directory walk lists `b.sv` as a file of its own; lexically the
|
||||
// two names share nothing, and two workers would rewrite one file.
|
||||
let dir = std::env::temp_dir().join(format!("lucisv-dedup-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
let real = dir.join("a.sv");
|
||||
let link = dir.join("b.sv");
|
||||
std::fs::write(&real, "module m;\nendmodule\n").expect("seed");
|
||||
std::os::unix::fs::symlink(&real, &link).expect("symlink");
|
||||
|
||||
assert_eq!(dedup(vec![real.clone(), link.clone()]), std::slice::from_ref(&real));
|
||||
// Whichever spelling comes first is the one kept and reported.
|
||||
assert_eq!(dedup(vec![link.clone(), real.clone()]), std::slice::from_ref(&link));
|
||||
// And a `..` detour through the same link is still the same file.
|
||||
std::fs::create_dir(dir.join("sub")).expect("sub dir");
|
||||
let detour = dir.join("sub/../b.sv");
|
||||
assert_eq!(dedup(vec![real.clone(), detour]), std::slice::from_ref(&real));
|
||||
|
||||
// A file that is not there has no canonical path: the key is lexical,
|
||||
// which still folds `.` and `..`, and two missing files stay two.
|
||||
let gone = dir.join("gone.sv");
|
||||
let same = dir.join("./sub/../gone.sv");
|
||||
let other = dir.join("other.sv");
|
||||
assert_eq!(dedup(vec![gone.clone(), same, other.clone()]), [gone, other]);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_contained_reports_parse_errors() {
|
||||
let err = format_contained("module", &Config::default(), None).unwrap_err();
|
||||
|
||||
@@ -136,6 +136,57 @@ fn formats_files_in_place() {
|
||||
assert!(stderr(&out).contains("2 files left unchanged"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
/// A directory walk lists a symlink as a file of its own, so `b.sv -> a.sv`
|
||||
/// used to put two workers on one file: two report lines for one file, and
|
||||
/// two writers racing to replace it. It is one file now, named once.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_symlink_and_its_target_are_one_file() {
|
||||
let dir = TempDir::new("alias");
|
||||
dir.write("a.sv", UNFORMATTED);
|
||||
std::os::unix::fs::symlink(dir.path.join("a.sv"), dir.path.join("b.sv")).expect("symlink");
|
||||
|
||||
let out = run(&["--check", &dir.root()]);
|
||||
assert_eq!(code(&out), 1, "{}", stderr(&out));
|
||||
let reported = stdout(&out);
|
||||
let named: Vec<&str> = reported.lines().filter(|l| l.contains("would reformat")).collect();
|
||||
assert_eq!(named.len(), 1, "one file, one line: {named:?}");
|
||||
assert!(named[0].ends_with("a.sv"), "the first spelling walked is the one reported: {named:?}");
|
||||
assert!(stderr(&out).contains("1 file would be reformatted"), "{}", stderr(&out));
|
||||
|
||||
let out = run(&[&dir.root()]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("1 file reformatted"), "{}", stderr(&out));
|
||||
assert_eq!(dir.read("a.sv"), FORMATTED);
|
||||
assert_eq!(dir.read("b.sv"), FORMATTED, "and the link still reaches it");
|
||||
assert!(
|
||||
std::fs::symlink_metadata(dir.path.join("b.sv")).expect("stat").file_type().is_symlink(),
|
||||
"the link was not replaced by a copy"
|
||||
);
|
||||
}
|
||||
|
||||
/// A directory that links back into itself. Before the walk kept a visited
|
||||
/// set (`docs/features/walk-cycles/README.md`) this run recursed until the
|
||||
/// OS refused the path; now each directory is entered once, so each file is
|
||||
/// named once — under the first spelling that reaches it.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_symlink_cycle_terminates_and_names_each_file_once() {
|
||||
let dir = TempDir::new("cycle");
|
||||
dir.write("rtl/a.sv", UNFORMATTED);
|
||||
dir.write("rtl/sub/b.sv", UNFORMATTED);
|
||||
// `rtl/self` is `rtl` itself; `rtl/sub/up` is `rtl` from one level down.
|
||||
std::os::unix::fs::symlink("../rtl", dir.path.join("rtl/self")).expect("symlink");
|
||||
std::os::unix::fs::symlink("..", dir.path.join("rtl/sub/up")).expect("symlink");
|
||||
|
||||
let out = run(&["--check", &dir.root()]);
|
||||
assert_eq!(code(&out), 1, "{}", stderr(&out));
|
||||
let reported = stdout(&out);
|
||||
let named: Vec<&str> = reported.lines().filter(|l| l.contains("would reformat")).collect();
|
||||
assert_eq!(named.len(), 2, "two files, two lines: {named:?}");
|
||||
assert!(stderr(&out).contains("2 files would be reformatted"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_reports_without_writing() {
|
||||
let dir = TempDir::new("check");
|
||||
@@ -935,6 +986,89 @@ fn check_honors_inline_waivers_and_reports_dead_ones() {
|
||||
assert!(stdout(&out).contains("[unused-waiver]"), "{}", stdout(&out));
|
||||
}
|
||||
|
||||
/// Two tabbed lines, one of which a waiver file's `--line` covers.
|
||||
const TABBED: &str = "module foo;\n\twire a;\n\twire b;\nendmodule\n";
|
||||
|
||||
/// `--waiver-file`: the suppression, the flag repeated, and the dead directive
|
||||
/// reported at the waiver file's own line. TODO §39.
|
||||
#[test]
|
||||
fn check_reads_external_waiver_files() {
|
||||
let dir = TempDir::new("check-waiver-file");
|
||||
let path = dir.write("foo.sv", TABBED);
|
||||
let one = dir.write("one.waiver", "# just line 2\nwaive --rule=no-tabs --line=2\n");
|
||||
let out = run(&["check", "--waiver-file", &one, &path]);
|
||||
assert_eq!(code(&out), 1, "{}", stdout(&out));
|
||||
assert_eq!(stdout(&out).lines().count(), 1, "one tab left: {}", stdout(&out));
|
||||
assert!(stdout(&out).contains("foo.sv:3:1"), "{}", stdout(&out));
|
||||
|
||||
// A second file adds to the first rather than replacing it, and both are
|
||||
// then used, so neither is reported.
|
||||
let two = dir.write("two.waiver", "waive --rule=no-tabs --line=3 --location=foo.sv\n");
|
||||
let out = run(&["check", "--waiver-file", &one, "--waiver-file", &two, &path]);
|
||||
assert_eq!(code(&out), 0, "{}", stdout(&out));
|
||||
|
||||
// A directive that covered nothing is reported against the waiver file.
|
||||
let dead = dir.write("dead.waiver", "waive --rule=no-tabs --location=elsewhere.sv\n");
|
||||
let out = run(&["check", "--waiver-file", &dead, &path]);
|
||||
assert_eq!(code(&out), 1);
|
||||
let text = stdout(&out);
|
||||
assert!(text.contains("dead.waiver:1:1: style: unused waiver for `no-tabs`"), "{text}");
|
||||
assert!(text.contains("[unused-waiver]"), "{text}");
|
||||
}
|
||||
|
||||
/// The `[lint] waivers` key, and that `--waiver-file` adds to it. TODO §39.
|
||||
#[test]
|
||||
fn check_reads_the_waiver_files_a_config_file_names() {
|
||||
let dir = TempDir::new("check-waiver-toml");
|
||||
let path = dir.write("rtl/foo.sv", TABBED);
|
||||
dir.write("lucisv.toml", "[lint]\nwaivers = [ \"project.waiver\" ]\n");
|
||||
dir.write("project.waiver", "waive --rule=no-tabs --line=2\n");
|
||||
// Relative to the config file, not to the working directory.
|
||||
let out = run_raw(&["check", "--no-cache", &path]);
|
||||
assert_eq!(code(&out), 1, "{}", stdout(&out));
|
||||
assert!(stdout(&out).contains("foo.sv:3:1"), "only line 3 survives: {}", stdout(&out));
|
||||
|
||||
let extra = dir.write("extra.waiver", "waive --rule=no-tabs --line=3\n");
|
||||
let out = run_raw(&["check", "--no-cache", "--waiver-file", &extra, &path]);
|
||||
assert_eq!(code(&out), 0, "the two lists add up: {}", stdout(&out));
|
||||
|
||||
// `--no-config` drops the config file's list with everything else in it.
|
||||
let out = run_raw(&["check", "--no-cache", "--no-config", &path]);
|
||||
assert_eq!(code(&out), 1);
|
||||
assert_eq!(stdout(&out).lines().count(), 2, "both tabs are back: {}", stdout(&out));
|
||||
}
|
||||
|
||||
/// A waiver file that cannot be read, or that has a line that does not parse,
|
||||
/// fails the run with `<file>:<line>: message` and exit 2. TODO §39.
|
||||
#[test]
|
||||
fn a_broken_waiver_file_fails_the_run() {
|
||||
let dir = TempDir::new("check-waiver-bad");
|
||||
let path = dir.write("foo.sv", TABBED);
|
||||
|
||||
let out = run(&["check", "--waiver-file", &dir.write("x.waiver", "hush\n"), &path]);
|
||||
assert_eq!(code(&out), 2, "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("x.waiver:1: expected a `waive` directive"), "{}", stderr(&out));
|
||||
|
||||
let bad = dir.write("y.waiver", "# fine\nwaive --rule=no-such-rule\n");
|
||||
let out = run(&["check", "--waiver-file", &bad, &path]);
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(stderr(&out).contains("y.waiver:2: unknown rule"), "{}", stderr(&out));
|
||||
|
||||
let regexy = dir.write("z.waiver", "waive --rule=no-tabs --location=.*foo.sv\n");
|
||||
let out = run(&["check", "--waiver-file", ®exy, &path]);
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(stderr(&out).contains("looks like a regular expression"), "{}", stderr(&out));
|
||||
|
||||
let out = run(&[
|
||||
"check",
|
||||
"--waiver-file",
|
||||
&dir.path.join("gone.waiver").display().to_string(),
|
||||
&path,
|
||||
]);
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(stderr(&out).contains("gone.waiver:"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_reads_stdin_and_names_it() {
|
||||
let out = run_with_stdin(&["check", "--stdin-filename", "rtl/z.sv", "-"], LINTY);
|
||||
@@ -2012,3 +2146,88 @@ fn rules_doc_refuses_files_and_belongs_to_check() {
|
||||
stderr(&out)
|
||||
);
|
||||
}
|
||||
|
||||
// --- the walk's own warnings (docs/features/small-items-4/README.md) -------
|
||||
|
||||
/// A tree with the two things the walk can only warn about: a directory it
|
||||
/// cannot read, and a source file that is only a broken link.
|
||||
#[cfg(unix)]
|
||||
fn unwalkable_tree(tag: &str) -> TempDir {
|
||||
use std::os::unix::fs::{symlink, PermissionsExt};
|
||||
let dir = TempDir::new(tag);
|
||||
dir.write("a.sv", UNFORMATTED);
|
||||
dir.write("z/late.sv", UNFORMATTED);
|
||||
dir.write("locked/hidden.sv", UNFORMATTED);
|
||||
symlink("nowhere.sv", dir.path.join("gone.sv")).expect("symlink");
|
||||
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o000))
|
||||
.expect("chmod");
|
||||
dir
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn lock(dir: &TempDir) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o000))
|
||||
.expect("chmod");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn unlock(dir: &TempDir) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let _ =
|
||||
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o755));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_unreadable_directory_is_a_warning_and_the_rest_of_the_tree_is_formatted() {
|
||||
// The finding TODO §45.2 closes: one permission-denied directory used to
|
||||
// propagate `read_dir`'s error and fail the whole run.
|
||||
let dir = unwalkable_tree("walk-warn");
|
||||
let out = run(&[&dir.root()]);
|
||||
unlock(&dir);
|
||||
|
||||
assert_eq!(code(&out), 0, "a warning is not a failure: {}", stderr(&out));
|
||||
let said = stderr(&out);
|
||||
assert_eq!(said.matches("warning: ").count(), 2, "{said}");
|
||||
assert!(said.contains("locked"), "{said}");
|
||||
assert!(said.contains("gone.sv: broken symbolic link"), "{said}");
|
||||
assert_eq!(dir.read("a.sv"), FORMATTED, "the other files were formatted");
|
||||
assert_eq!(dir.read("z/late.sv"), FORMATTED, "including the ones sorted after it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn the_walks_warnings_leave_check_modes_exit_code_alone() {
|
||||
let dir = unwalkable_tree("walk-warn-check");
|
||||
let out = run(&["--check", &dir.root()]);
|
||||
unlock(&dir);
|
||||
|
||||
// `--check` answers on formatting alone: two files would be reformatted.
|
||||
assert_eq!(code(&out), 1, "{}", stderr(&out));
|
||||
assert_eq!(stderr(&out).matches("warning: ").count(), 2, "{}", stderr(&out));
|
||||
assert!(!stdout(&out).contains("warning"), "warnings stay off stdout: {}", stdout(&out));
|
||||
|
||||
// And with nothing left to reformat the run is clean, warnings and all.
|
||||
dir.write("a.sv", FORMATTED);
|
||||
dir.write("z/late.sv", FORMATTED);
|
||||
lock(&dir);
|
||||
let out = run(&["--check", &dir.root()]);
|
||||
unlock(&dir);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(stderr(&out).matches("warning: ").count(), 2, "{}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_dangling_source_link_named_on_the_command_line_is_still_an_error() {
|
||||
// The walk drops the link; a path the user typed is not walked at all, so
|
||||
// "no such file or directory" is still what naming one gets.
|
||||
let dir = TempDir::new("walk-warn-named");
|
||||
std::os::unix::fs::symlink("nowhere.sv", dir.path.join("gone.sv")).expect("symlink");
|
||||
let named = dir.path.join("gone.sv").to_string_lossy().into_owned();
|
||||
|
||||
let out = run(&[&named]);
|
||||
assert_eq!(code(&out), 2, "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("no such file or directory"), "{}", stderr(&out));
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
//! Replacing a file's contents without ever leaving it half written.
|
||||
//!
|
||||
//! `fs::write` truncates the target and then writes into it, so a crash, a
|
||||
//! full disk or a `^C` between the two leaves the user's source truncated —
|
||||
//! and lucisv's first invariant is that it never corrupts code. Every
|
||||
//! in-place write goes through [`write_atomic`] instead: a sibling temp file
|
||||
//! gets the bytes, and a `rename` over the target publishes them in one step
|
||||
//! that either happened or did not.
|
||||
//!
|
||||
//! Two threads of one process may write one target: the temp names carry a
|
||||
//! per-process counter as well as the pid and are created with `O_EXCL`, so
|
||||
//! each writer owns its own file and neither can see the other's bytes.
|
||||
//!
|
||||
//! Two *processes* writing one target are not coordinated, and deliberately
|
||||
//! so. Both renames are atomic, the later one wins, and the loser's bytes are
|
||||
//! discarded whole — never merged. Both processes formatted the same input
|
||||
//! and `format` is idempotent, so whichever rename lands last leaves the
|
||||
//! file complete and correctly formatted. A lock would buy nothing and would
|
||||
//! be one more thing to leave behind after a `^C`.
|
||||
//!
|
||||
//! See `docs/features/small-items-3/README.md` and
|
||||
//! `docs/features/atomic-write-coordination/README.md`.
|
||||
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// Writes `bytes` to `path`, replacing whatever was there in one step.
|
||||
///
|
||||
/// A temp file beside the target takes the bytes, inherits the target's
|
||||
/// permissions when there is a target, and is renamed onto it — `rename` is
|
||||
/// atomic within a directory on every platform lucisv ships to, so a reader
|
||||
/// sees either the old file or the new one and never a truncated one. A
|
||||
/// failure anywhere after the temp exists removes it before returning.
|
||||
///
|
||||
/// The temp is the caller's alone: [`temp_path`] hands out a name no other
|
||||
/// writer in this process will be given, and the file is created with
|
||||
/// `create_new`, so a name that somehow exists is an error and not a shared
|
||||
/// file. Two threads writing one target therefore both succeed, and the
|
||||
/// target ends up holding one thread's whole buffer.
|
||||
///
|
||||
/// A symlinked target is resolved first: `fs::write` writes *through* a
|
||||
/// symlink, so replacing the link itself would silently redirect it at a new
|
||||
/// file and leave the real one stale. The canonical path is what gets
|
||||
/// replaced, which is also what makes the temp land on the target's own
|
||||
/// filesystem — `rename` cannot cross one.
|
||||
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
let target = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
|
||||
let perms = target_permissions(&target);
|
||||
// A rename replaces a file whatever its mode, so a read-only target would
|
||||
// be silently overwritten where `fs::write` refuses it. Keep the refusal:
|
||||
// a file someone made read-only is asking not to be rewritten in place.
|
||||
if perms.as_ref().is_some_and(fs::Permissions::readonly) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
format!("{} is read-only", path.display()),
|
||||
));
|
||||
}
|
||||
let (tmp, mut file) = create_temp(&target, perms.is_some())?;
|
||||
if let Err(e) = fill_temp(&mut file, &tmp, perms, bytes) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(e);
|
||||
}
|
||||
drop(file);
|
||||
if let Err(e) = fs::rename(&tmp, &target) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How many temp names one write tries before giving up.
|
||||
///
|
||||
/// A name is only ever handed out once per process, so a collision means a
|
||||
/// leftover from a *previous* process that crashed mid-write and whose pid
|
||||
/// this process now has. A handful of those may sit in one directory; a
|
||||
/// hundred is a directory to clean up by hand, not a race to retry through.
|
||||
const TEMP_ATTEMPTS: u32 = 32;
|
||||
|
||||
/// Creates the temp file, exclusively, and returns it with its path.
|
||||
///
|
||||
/// `replacing` says there is a target whose mode the temp is about to take.
|
||||
/// Then it is born 0600 on unix rather than at the umask's mode: a chmod does
|
||||
/// not revoke a descriptor someone already opened, so the only way a private
|
||||
/// file's replacement can never be read by anyone else is for the temp to be
|
||||
/// private from the moment it exists. With no target there is no earlier mode
|
||||
/// to honour and the umask decides, as `fs::write` would.
|
||||
fn create_temp(target: &Path, replacing: bool) -> io::Result<(PathBuf, File)> {
|
||||
let mut opts = OpenOptions::new();
|
||||
opts.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
if replacing {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
opts.mode(0o600);
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = replacing;
|
||||
for _ in 0..TEMP_ATTEMPTS {
|
||||
let tmp = temp_path(target)?;
|
||||
match opts.open(&tmp) {
|
||||
Ok(file) => return Ok((tmp, file)),
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::AlreadyExists,
|
||||
format!("no free temp file name beside {} after {TEMP_ATTEMPTS} tries", target.display()),
|
||||
))
|
||||
}
|
||||
|
||||
/// Puts the target's mode on the temp, then the bytes in it.
|
||||
///
|
||||
/// The order is the point on unix: a 0600 target's replacement must not spend
|
||||
/// even an instant holding the file's contents under the umask's broader
|
||||
/// bits. Chmod does not close the handle opened before it, so a mode without
|
||||
/// an owner-write bit still takes the write. Elsewhere `set_permissions`
|
||||
/// takes a path rather than a handle and the mode goes on after the bytes,
|
||||
/// which is the order this always had.
|
||||
fn fill_temp(
|
||||
file: &mut File,
|
||||
tmp: &Path,
|
||||
perms: Option<fs::Permissions>,
|
||||
bytes: &[u8],
|
||||
) -> io::Result<()> {
|
||||
if cfg!(unix) {
|
||||
copy_mode(file, perms);
|
||||
file.write_all(bytes)
|
||||
} else {
|
||||
file.write_all(bytes)?;
|
||||
if let Some(perms) = perms {
|
||||
let _ = fs::set_permissions(tmp, perms);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts the target's mode on the temp through its open handle, which is what
|
||||
/// lets it happen while the temp is still empty. No target means no earlier
|
||||
/// mode to honour, and the umask's stands.
|
||||
fn copy_mode(file: &File, perms: Option<fs::Permissions>) {
|
||||
if let Some(perms) = perms {
|
||||
let _ = file.set_permissions(perms);
|
||||
}
|
||||
}
|
||||
|
||||
/// The mode the temp must end up with: a file someone made executable, or
|
||||
/// private, keeps its bits, because the temp was created with the process
|
||||
/// umask (or 0600) and not with the target's. `None` means there is no target
|
||||
/// — a new file, which takes the umask as `fs::write` would.
|
||||
fn target_permissions(target: &Path) -> Option<fs::Permissions> {
|
||||
fs::metadata(target).ok().map(|m| m.permissions())
|
||||
}
|
||||
|
||||
/// Names handed out by [`temp_path`], one per call for the life of the
|
||||
/// process. Wrapping after 2^64 names is not a scenario.
|
||||
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// The temp file's path: hidden, in the target's own directory, and stamped
|
||||
/// with the process id and a per-process counter — the pid keeps two lucisv
|
||||
/// runs apart, the counter keeps two threads of one run apart, and together
|
||||
/// they mean no two writers anywhere are ever given the same name.
|
||||
fn temp_path(target: &Path) -> io::Result<PathBuf> {
|
||||
let dir = target.parent().unwrap_or_else(|| Path::new("."));
|
||||
let name = target
|
||||
.file_name()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no file name to write"))?;
|
||||
let n = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
let mut tmp = std::ffi::OsString::from(".");
|
||||
tmp.push(name);
|
||||
tmp.push(format!(".{}.{n}.lucisv-tmp", std::process::id()));
|
||||
Ok(dir.join(tmp))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A directory that removes itself, the way `cache.rs`'s own tests have
|
||||
/// one — no dependency, and no leftovers under `target/`.
|
||||
struct TempDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"lucisv-atomic-{tag}-{}-{:?}",
|
||||
std::process::id(),
|
||||
std::thread::current().id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("create temp dir");
|
||||
TempDir { path }
|
||||
}
|
||||
|
||||
fn file(&self, name: &str) -> PathBuf {
|
||||
self.path.join(name)
|
||||
}
|
||||
|
||||
/// Every name in the directory, so a test can say what is *not* there.
|
||||
fn names(&self) -> Vec<String> {
|
||||
let mut out: Vec<String> = fs::read_dir(&self.path)
|
||||
.expect("read dir")
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bytes_land_and_no_temp_file_is_left_behind() {
|
||||
let dir = TempDir::new("plain");
|
||||
let file = dir.file("a.sv");
|
||||
fs::write(&file, "old\n").expect("seed");
|
||||
write_atomic(&file, b"new\n").expect("write");
|
||||
assert_eq!(fs::read_to_string(&file).expect("read"), "new\n");
|
||||
assert_eq!(dir.names(), vec!["a.sv".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_exist_yet_is_created() {
|
||||
let dir = TempDir::new("create");
|
||||
let file = dir.file("new.sv");
|
||||
write_atomic(&file, b"hello\n").expect("write");
|
||||
assert_eq!(fs::read_to_string(&file).expect("read"), "hello\n");
|
||||
assert_eq!(dir.names(), vec!["new.sv".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_that_cannot_happen_is_an_error_and_leaves_no_temp() {
|
||||
// A directory standing where the file should be: the write succeeds,
|
||||
// the rename cannot.
|
||||
let dir = TempDir::new("dirtarget");
|
||||
let target = dir.file("occupied");
|
||||
fs::create_dir(&target).expect("create dir");
|
||||
let err = write_atomic(&target, b"x\n").expect_err("a directory cannot be replaced");
|
||||
assert!(err.to_string().len() > 1, "{err}");
|
||||
assert_eq!(dir.names(), vec!["occupied".to_string()], "the temp file was cleaned up");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writing_the_same_path_twice_leaves_one_file() {
|
||||
let dir = TempDir::new("twice");
|
||||
let file = dir.file("a.sv");
|
||||
write_atomic(&file, b"one\n").expect("write");
|
||||
write_atomic(&file, b"two\n").expect("write");
|
||||
assert_eq!(fs::read_to_string(&file).expect("read"), "two\n");
|
||||
assert_eq!(dir.names(), vec!["a.sv".to_string()]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_targets_permissions_are_preserved() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = TempDir::new("modes");
|
||||
for mode in [0o600, 0o755] {
|
||||
let file = dir.file(&format!("m{mode:o}.sv"));
|
||||
fs::write(&file, "old\n").expect("seed");
|
||||
fs::set_permissions(&file, fs::Permissions::from_mode(mode)).expect("chmod");
|
||||
write_atomic(&file, b"new\n").expect("write");
|
||||
let got = fs::metadata(&file).expect("stat").permissions().mode() & 0o777;
|
||||
assert_eq!(got, mode, "mode {mode:o} was not preserved");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_read_only_target_is_refused_and_left_alone() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = TempDir::new("readonly");
|
||||
let file = dir.file("ro.sv");
|
||||
fs::write(&file, "old\n").expect("seed");
|
||||
fs::set_permissions(&file, fs::Permissions::from_mode(0o444)).expect("chmod");
|
||||
let err = write_atomic(&file, b"new\n").expect_err("a read-only file is not replaced");
|
||||
assert_eq!(err.kind(), io::ErrorKind::PermissionDenied, "{err}");
|
||||
assert_eq!(fs::read_to_string(&file).expect("read"), "old\n");
|
||||
assert_eq!(dir.names(), vec!["ro.sv".to_string()], "no temp file was made");
|
||||
fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).expect("restore");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn writing_through_a_symlink_replaces_the_target_not_the_link() {
|
||||
let dir = TempDir::new("symlink");
|
||||
let real = dir.file("real.sv");
|
||||
let link = dir.file("link.sv");
|
||||
fs::write(&real, "old\n").expect("seed");
|
||||
std::os::unix::fs::symlink(&real, &link).expect("symlink");
|
||||
write_atomic(&link, b"new\n").expect("write");
|
||||
assert_eq!(fs::read_to_string(&real).expect("read"), "new\n", "the target got the bytes");
|
||||
assert!(
|
||||
fs::symlink_metadata(&link).expect("stat").file_type().is_symlink(),
|
||||
"the link is still a link"
|
||||
);
|
||||
assert_eq!(fs::read_to_string(&link).expect("read"), "new\n", "and still points at it");
|
||||
}
|
||||
|
||||
/// The audit's probe (`docs/repository-analysis.md` finding 1), which
|
||||
/// used to produce 100 write errors in 200 calls: both threads derived
|
||||
/// the same temp name from the target and the pid, so one deleted the
|
||||
/// other's file under it. Now every writer owns its own temp, so every
|
||||
/// call succeeds and the target holds one writer's whole buffer.
|
||||
#[test]
|
||||
fn two_threads_writing_one_target_never_collide() {
|
||||
const MIB: usize = 1024 * 1024;
|
||||
const ROUNDS: usize = 100;
|
||||
let dir = TempDir::new("race");
|
||||
let file = dir.file("a.sv");
|
||||
fs::write(&file, "seed\n").expect("seed");
|
||||
|
||||
// Three parties: the two writers and this thread, which inspects the
|
||||
// target between rounds. Nobody starts a round until everyone has
|
||||
// finished the last one.
|
||||
let start = std::sync::Arc::new(std::sync::Barrier::new(3));
|
||||
let done = std::sync::Arc::new(std::sync::Barrier::new(3));
|
||||
let writers: Vec<_> = (*b"ab")
|
||||
.into_iter()
|
||||
.map(|tag| {
|
||||
let (path, start, done) = (file.clone(), start.clone(), done.clone());
|
||||
std::thread::spawn(move || {
|
||||
let bytes = vec![tag; MIB];
|
||||
let mut errors = Vec::new();
|
||||
for _ in 0..ROUNDS {
|
||||
start.wait();
|
||||
if let Err(e) = write_atomic(&path, &bytes) {
|
||||
errors.push(e.to_string());
|
||||
}
|
||||
done.wait();
|
||||
}
|
||||
errors
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
for round in 0..ROUNDS {
|
||||
start.wait();
|
||||
done.wait();
|
||||
let got = fs::read(&file).expect("read");
|
||||
assert_eq!(got.len(), MIB, "round {round}: a partial buffer landed");
|
||||
let tag = got[0];
|
||||
assert!(tag == b'a' || tag == b'b', "round {round}: neither writer's byte");
|
||||
assert!(got.iter().all(|&b| b == tag), "round {round}: two buffers were mixed");
|
||||
assert_eq!(dir.names(), vec!["a.sv".to_string()], "round {round}: a temp was left");
|
||||
}
|
||||
|
||||
let errors: Vec<String> =
|
||||
writers.into_iter().flat_map(|w| w.join().expect("writer thread")).collect();
|
||||
assert!(
|
||||
errors.is_empty(),
|
||||
"{} write errors in {} calls: {errors:?}",
|
||||
errors.len(),
|
||||
2 * ROUNDS
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_thread_gets_its_own_temp_name() {
|
||||
const PER_THREAD: usize = 200;
|
||||
let dir = TempDir::new("names");
|
||||
let target = dir.file("a.sv");
|
||||
let threads: Vec<_> = (0..4)
|
||||
.map(|_| {
|
||||
let target = target.clone();
|
||||
std::thread::spawn(move || {
|
||||
(0..PER_THREAD)
|
||||
.map(|_| temp_path(&target).expect("temp name"))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let names: Vec<PathBuf> =
|
||||
threads.into_iter().flat_map(|t| t.join().expect("name thread")).collect();
|
||||
let unique: std::collections::HashSet<&PathBuf> = names.iter().collect();
|
||||
assert_eq!(unique.len(), names.len(), "a temp name was handed out twice");
|
||||
}
|
||||
|
||||
/// The mode goes on while the temp is still empty, so a 0600 file's
|
||||
/// replacement never holds its contents under the umask's wider bits.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_temp_takes_the_targets_mode_before_any_bytes() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = TempDir::new("modewindow");
|
||||
let target = dir.file("secret.sv");
|
||||
fs::write(&target, "old\n").expect("seed");
|
||||
fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).expect("chmod");
|
||||
|
||||
let perms = target_permissions(&target);
|
||||
let (tmp, mut file) = create_temp(&target, perms.is_some()).expect("temp");
|
||||
// Born private, before any mode is copied onto it: an fd opened by
|
||||
// someone else in this instant would not see the bytes to come.
|
||||
assert_eq!(
|
||||
fs::metadata(&tmp).expect("stat").permissions().mode() & 0o777,
|
||||
0o600,
|
||||
"the temp was created readable by others"
|
||||
);
|
||||
copy_mode(&file, perms.clone());
|
||||
let meta = fs::metadata(&tmp).expect("stat");
|
||||
assert_eq!(meta.len(), 0, "the mode is set before a single byte is written");
|
||||
assert_eq!(meta.permissions().mode() & 0o777, 0o600, "the temp is not world-readable");
|
||||
// And the chmod does not close the door on the handle opened before it.
|
||||
fill_temp(&mut file, &tmp, perms, b"new\n").expect("fill");
|
||||
assert_eq!(fs::read_to_string(&tmp).expect("read"), "new\n");
|
||||
let _ = fs::remove_file(&tmp);
|
||||
}
|
||||
|
||||
/// The same window seen from outside, through a real `write_atomic`: a
|
||||
/// big enough buffer that the temp is usually observable while it is
|
||||
/// being filled. It asserts about what it sees and never about seeing it,
|
||||
/// so a scheduler that hides the window cannot fail the test.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_temp_seen_mid_write_is_never_world_readable() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = TempDir::new("window");
|
||||
let target = dir.file("secret.sv");
|
||||
fs::write(&target, "old\n").expect("seed");
|
||||
fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).expect("chmod");
|
||||
|
||||
let path = target.clone();
|
||||
let writer = std::thread::spawn(move || {
|
||||
let bytes = vec![b'x'; 8 * 1024 * 1024];
|
||||
write_atomic(&path, &bytes)
|
||||
});
|
||||
while !writer.is_finished() {
|
||||
for entry in fs::read_dir(&dir.path).expect("read dir").flatten() {
|
||||
if !entry.file_name().to_string_lossy().ends_with(".lucisv-tmp") {
|
||||
continue;
|
||||
}
|
||||
let Ok(meta) = entry.metadata() else { continue };
|
||||
assert_eq!(
|
||||
meta.permissions().mode() & 0o777,
|
||||
0o600,
|
||||
"a temp for a 0600 target was readable by others"
|
||||
);
|
||||
}
|
||||
}
|
||||
writer.join().expect("writer thread").expect("write");
|
||||
assert_eq!(fs::metadata(&target).expect("stat").permissions().mode() & 0o777, 0o600);
|
||||
}
|
||||
}
|
||||
@@ -87,10 +87,7 @@ impl Cache {
|
||||
if !ignore.exists() {
|
||||
let _ = std::fs::write(&ignore, "*\n");
|
||||
}
|
||||
let tmp = dir.join(format!("{FILE}.{}.tmp", std::process::id()));
|
||||
if std::fs::write(&tmp, self.render()).is_ok() && std::fs::rename(&tmp, path).is_err() {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
}
|
||||
let _ = crate::atomic::write_atomic(path, self.render().as_bytes());
|
||||
}
|
||||
|
||||
/// The file's text: one line per entry, sorted by path so that two
|
||||
@@ -397,7 +394,7 @@ mod tests {
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.filter(|n| n.ends_with(".tmp"))
|
||||
.filter(|n| n.ends_with(".tmp") || n.ends_with("-tmp"))
|
||||
.collect();
|
||||
assert!(leftovers.is_empty(), "{leftovers:?}");
|
||||
}
|
||||
|
||||
@@ -37,6 +37,15 @@ pub struct FileConfig {
|
||||
pub lint_select: Option<Vec<String>>,
|
||||
/// `[lint] ignore`: rules dropped from whatever `select` left.
|
||||
pub lint_ignore: Option<Vec<String>>,
|
||||
/// `[lint] waivers`: external waiver files, in the order written.
|
||||
///
|
||||
/// Like [`FileConfig::filelist`], these name *other files*: [`parse`]
|
||||
/// records them exactly as written and [`Discovery`] resolves each one
|
||||
/// against the config file's own directory, so every `FileConfig` a
|
||||
/// `Discovery` hands out carries usable paths. Nothing here reads them —
|
||||
/// their contents name lint rules, and this crate does not know the rule
|
||||
/// registry any more than it does for `select`.
|
||||
pub lint_waivers: Option<Vec<PathBuf>>,
|
||||
/// `[lint.<rule>]` tables, **as written**: one entry per key, in file
|
||||
/// order.
|
||||
///
|
||||
@@ -93,7 +102,7 @@ pub fn parse(text: &str) -> Result<FileConfig, String> {
|
||||
enum Table {
|
||||
/// Before any header: the formatter's own keys.
|
||||
Top,
|
||||
/// `[lint]`: `select` and `ignore`.
|
||||
/// `[lint]`: `select`, `ignore` and `waivers`.
|
||||
Lint,
|
||||
/// `[lint.<rule>]`: that rule's options.
|
||||
Rule(String),
|
||||
@@ -106,7 +115,7 @@ fn parse_entry(
|
||||
number: usize,
|
||||
) -> Result<(), String> {
|
||||
if line.starts_with('[') {
|
||||
// `[lint]` carries `select`/`ignore`; `[lint.<rule>]` carries that
|
||||
// `[lint]` carries `select`/`ignore`/`waivers`; `[lint.<rule>]` carries that
|
||||
// rule's options, which are stored raw and checked by whoever knows
|
||||
// the registry.
|
||||
if line == "[lint]" {
|
||||
@@ -155,19 +164,28 @@ fn parse_entry(
|
||||
}
|
||||
_ => Err(format!(
|
||||
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
|
||||
select, ignore under `[lint]`; and a rule's own options under \
|
||||
`[lint.<rule-name>]`)"
|
||||
select, ignore, waivers under `[lint]`; and a rule's own options \
|
||||
under `[lint.<rule-name>]`)"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// One key of the `[lint]` table.
|
||||
fn parse_lint_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
|
||||
if key == "waivers" {
|
||||
if config.lint_waivers.is_some() {
|
||||
return Err(format!("duplicate key `{key}`"));
|
||||
}
|
||||
config.lint_waivers = Some(parse_array(value)?.into_iter().map(PathBuf::from).collect());
|
||||
return Ok(());
|
||||
}
|
||||
let slot = match key {
|
||||
"select" => &mut config.lint_select,
|
||||
"ignore" => &mut config.lint_ignore,
|
||||
_ => {
|
||||
return Err(format!("unknown key `{key}` under `[lint]` (known keys: select, ignore)"))
|
||||
return Err(format!(
|
||||
"unknown key `{key}` under `[lint]` (known keys: select, ignore, waivers)"
|
||||
))
|
||||
}
|
||||
};
|
||||
if slot.is_some() {
|
||||
@@ -359,10 +377,16 @@ fn load(path: &Path) -> Result<FileConfig, String> {
|
||||
// `filelist` is the one value that names another file, so it is resolved
|
||||
// here — against the config file's own directory, which `parse` cannot
|
||||
// know. An absolute path is left alone (`join` already does that).
|
||||
let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();
|
||||
if let Some(filelist) = config.filelist.take() {
|
||||
let dir = path.parent().unwrap_or(Path::new("."));
|
||||
config.filelist = Some(dir.join(filelist));
|
||||
}
|
||||
// `[lint] waivers` names other files the same way, and is resolved the
|
||||
// same way: against the config file's directory, an absolute path left
|
||||
// alone by `join`.
|
||||
if let Some(waivers) = config.lint_waivers.take() {
|
||||
config.lint_waivers = Some(waivers.into_iter().map(|file| dir.join(file)).collect());
|
||||
}
|
||||
// So an error about a `[lint.<rule>]` entry can name the file to edit.
|
||||
config.source = Some(path.to_path_buf());
|
||||
Ok(config)
|
||||
@@ -428,6 +452,34 @@ exclude = [ \"build\", \"*_gen.sv\", ]
|
||||
);
|
||||
}
|
||||
|
||||
/// `[lint] waivers` names other files, so it resolves the way `filelist`
|
||||
/// does: against the config file's own directory, absolute paths left
|
||||
/// alone. See `docs/features/waiver-files/README.md`.
|
||||
#[test]
|
||||
fn lint_waivers_are_a_list_resolved_against_the_config_files_directory() {
|
||||
assert_eq!(
|
||||
ok("[lint]\nwaivers = [ \"a.waiver\", \"deep/b.waiver\" ]").lint_waivers,
|
||||
Some(vec![PathBuf::from("a.waiver"), PathBuf::from("deep/b.waiver")])
|
||||
);
|
||||
assert_eq!(
|
||||
ok("[lint]\nselect = [\"no-tabs\"]").lint_waivers,
|
||||
None,
|
||||
"absent unless written"
|
||||
);
|
||||
assert!(err("[lint]\nwaivers = \"a.waiver\"").contains("multi-line arrays"));
|
||||
assert!(err("[lint]\nwaivers = []\nwaivers = []").contains("duplicate key `waivers`"));
|
||||
assert!(err("[lint]\nwaiver = []").contains("unknown key `waiver` under `[lint]`"));
|
||||
|
||||
let tree = TempTree::new();
|
||||
tree.write("lucisv.toml", "[lint]\nwaivers = [ \"rtl/a.waiver\", \"/opt/b.waiver\" ]\n");
|
||||
let deep = tree.write("a/b/x.sv", "");
|
||||
let found = Discovery::new(true).for_file(&deep).unwrap();
|
||||
assert_eq!(
|
||||
found.lint_waivers,
|
||||
Some(vec![tree.path.join("rtl/a.waiver"), PathBuf::from("/opt/b.waiver")])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_file_sets_nothing() {
|
||||
assert_eq!(ok(""), FileConfig::default());
|
||||
|
||||
@@ -6,11 +6,14 @@
|
||||
//! the same `lucisv.toml` and skip the same files as CI's `lucisv --check`.
|
||||
//! `cache` answers the third question of the same family — whether a file
|
||||
//! needs to be processed at all, and `filelist` answers the first one the way
|
||||
//! an EDA project already does, from a `.f` file. See
|
||||
//! an EDA project already does, from a `.f` file. `atomic` is the one write
|
||||
//! path all of them share: nothing here ever truncates a file it is
|
||||
//! replacing. See
|
||||
//! `docs/features/lucisv-core-lift/README.md`, and
|
||||
//! `docs/features/{config-discovery,parallel-files,format-cache,filelist}/README.md`
|
||||
//! for the rules themselves.
|
||||
|
||||
pub mod atomic;
|
||||
pub mod cache;
|
||||
pub mod config;
|
||||
pub mod filelist;
|
||||
|
||||
+383
-23
@@ -2,6 +2,7 @@
|
||||
//! `.gitignore` subset documented in
|
||||
//! `docs/features/parallel-files/README.md`.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// File extensions lucisv formats when walking a directory.
|
||||
@@ -10,20 +11,56 @@ pub const EXTENSIONS: &[&str] = &["v", "sv", "vh", "svh"];
|
||||
/// The name of the per-directory ignore file that is honoured by default.
|
||||
const GITIGNORE: &str = ".gitignore";
|
||||
|
||||
/// Something the walk could not do and went on regardless: a directory it
|
||||
/// could not read, an ignore file it could not open, a source file that is
|
||||
/// only a broken link.
|
||||
///
|
||||
/// The walk's warning channel exists because none of these is worth failing a
|
||||
/// run over — one unreadable directory used to drop every file already found
|
||||
/// — and because a silent skip loses the user the fact entirely. Rendering is
|
||||
/// the front end's job: the CLI writes `warning: <path>: <message>` to stderr,
|
||||
/// the server logs the same text once per scan.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Warning {
|
||||
/// What could not be used.
|
||||
pub path: PathBuf,
|
||||
/// Why, in the operating system's own words where there are any.
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Warning {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}: {}", self.path.display(), self.message)
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `input` to `files`: the file itself, or every Verilog file under
|
||||
/// it if it is a directory. Exclude patterns and `.gitignore` rules apply
|
||||
/// to directory walks only — a path named on the command line is always
|
||||
/// formatted.
|
||||
///
|
||||
/// `warn` is called once for everything the walk skipped and wants said; see
|
||||
/// [`Warning`]. Only `input` itself naming nothing is an error — that is the
|
||||
/// user's own typo, and the run has nothing to do.
|
||||
pub fn collect_files(
|
||||
input: &str,
|
||||
exclude: &[String],
|
||||
gitignore: bool,
|
||||
files: &mut Vec<PathBuf>,
|
||||
warn: &mut dyn FnMut(Warning),
|
||||
) -> Result<(), String> {
|
||||
let path = Path::new(input);
|
||||
if path.is_dir() {
|
||||
let mut walk = Walk { exclude, gitignore, ignores: Vec::new(), rel: Vec::new(), files };
|
||||
walk.dir(path).map_err(|e| format!("{input}: {e}"))?;
|
||||
let mut walk = Walk {
|
||||
exclude,
|
||||
gitignore,
|
||||
ignores: Vec::new(),
|
||||
rel: Vec::new(),
|
||||
visited: HashSet::new(),
|
||||
files,
|
||||
warn,
|
||||
};
|
||||
walk.dir(path);
|
||||
} else if path.is_file() {
|
||||
files.push(path.to_path_buf());
|
||||
} else {
|
||||
@@ -32,57 +69,166 @@ pub fn collect_files(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How a directory is recognised as one the walk has already entered. Two
|
||||
/// names for the same directory — a symlink and its target, or two symlinks
|
||||
/// pointing at one place — must map to the same identity, or a cycle has no
|
||||
/// end. On unix that is `(dev, ino)`, the pair the filesystem itself uses;
|
||||
/// elsewhere it is the canonical path, which resolves symlinks the same way
|
||||
/// at the cost of a real path lookup.
|
||||
#[cfg(unix)]
|
||||
type DirId = (u64, u64);
|
||||
#[cfg(not(unix))]
|
||||
type DirId = PathBuf;
|
||||
|
||||
/// The identity of the directory at `path`, or `None` when it cannot be
|
||||
/// read — a dangling symlink, or a directory that vanished mid-walk.
|
||||
#[cfg(unix)]
|
||||
fn dir_id(path: &Path) -> Option<DirId> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let meta = std::fs::metadata(path).ok()?;
|
||||
Some((meta.dev(), meta.ino()))
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn dir_id(path: &Path) -> Option<DirId> {
|
||||
std::fs::canonicalize(path).ok()
|
||||
}
|
||||
|
||||
/// True when `path` names one of the source files lucisv formats.
|
||||
fn is_source(path: &Path) -> bool {
|
||||
path.extension().and_then(|e| e.to_str()).is_some_and(|ext| EXTENSIONS.contains(&ext))
|
||||
}
|
||||
|
||||
/// One directory walk. `rel` is the path of the directory currently being
|
||||
/// read, in components relative to the walk root, which is what
|
||||
/// `.gitignore` rules are matched against; `ignores` is the stack of
|
||||
/// ignore files seen from the root down to it.
|
||||
/// ignore files seen from the root down to it; `visited` is every directory
|
||||
/// already entered, by identity rather than by spelling.
|
||||
struct Walk<'a> {
|
||||
exclude: &'a [String],
|
||||
gitignore: bool,
|
||||
ignores: Vec<Ignore>,
|
||||
rel: Vec<String>,
|
||||
visited: HashSet<DirId>,
|
||||
files: &'a mut Vec<PathBuf>,
|
||||
warn: &'a mut dyn FnMut(Warning),
|
||||
}
|
||||
|
||||
impl Walk<'_> {
|
||||
fn dir(&mut self, dir: &Path) -> std::io::Result<()> {
|
||||
let pushed = self.push_ignore(dir)?;
|
||||
let mut entries: Vec<_> = std::fs::read_dir(dir)?.collect::<Result<_, _>>()?;
|
||||
fn dir(&mut self, dir: &Path) {
|
||||
if !self.enter(dir) {
|
||||
return;
|
||||
}
|
||||
let pushed = self.push_ignore(dir);
|
||||
self.entries(dir);
|
||||
if pushed {
|
||||
self.ignores.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/// One directory's entries, in name order. A directory that cannot be read
|
||||
/// — the permission-denied one somewhere under the start — is said and
|
||||
/// skipped: everything already found stays found and the walk goes on,
|
||||
/// which is the whole reason this channel exists.
|
||||
fn entries(&mut self, dir: &Path) {
|
||||
let read = match std::fs::read_dir(dir) {
|
||||
Ok(read) => read,
|
||||
Err(e) => return self.say(dir, e.to_string()),
|
||||
};
|
||||
let mut entries = Vec::new();
|
||||
for entry in read {
|
||||
match entry {
|
||||
Ok(entry) => entries.push(entry),
|
||||
Err(e) => self.say(dir, e.to_string()),
|
||||
}
|
||||
}
|
||||
entries.sort_by_key(|e| e.path());
|
||||
for entry in entries {
|
||||
let path = entry.path();
|
||||
if is_excluded(&path, self.exclude) {
|
||||
continue;
|
||||
}
|
||||
let is_dir = path.is_dir();
|
||||
// One `metadata` call per entry, exactly as before — it follows
|
||||
// symlinks, so it answers "directory?" for a symlinked directory
|
||||
// the way `is_dir()` did. A dangling symlink has no metadata at
|
||||
// all. One that *names a source file* is warned about and dropped:
|
||||
// §43's QA was right that a silent skip loses the user the fact,
|
||||
// and §45.2 gives that fact a home of its own rather than handing
|
||||
// the path on to fail as "no such file" in the front end. One that
|
||||
// names anything else was never going to be read, and is skipped
|
||||
// as quietly as it always was.
|
||||
let Ok(meta) = std::fs::metadata(&path) else {
|
||||
if is_source(&path) {
|
||||
let why = broken_link_reason(&path);
|
||||
self.say(&path, why);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
self.rel.push(entry.file_name().to_string_lossy().into_owned());
|
||||
if !is_ignored(&self.ignores, &self.rel, is_dir) {
|
||||
if is_dir {
|
||||
self.dir(&path)?;
|
||||
} else if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
|
||||
if EXTENSIONS.contains(&ext) {
|
||||
self.files.push(path);
|
||||
}
|
||||
if !is_ignored(&self.ignores, &self.rel, meta.is_dir()) {
|
||||
if meta.is_dir() {
|
||||
self.dir(&path);
|
||||
} else if meta.is_file() && is_source(&path) {
|
||||
self.files.push(path);
|
||||
}
|
||||
}
|
||||
self.rel.pop();
|
||||
}
|
||||
if pushed {
|
||||
self.ignores.pop();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Hand one warning to the front end.
|
||||
fn say(&mut self, path: &Path, message: String) {
|
||||
(self.warn)(Warning { path: path.to_path_buf(), message });
|
||||
}
|
||||
|
||||
/// Records `dir` as entered, and answers whether it had not been entered
|
||||
/// already. Identity, not spelling: `a/loop -> a` and `a/b/up -> ..` name
|
||||
/// a directory the walk is already inside, and following either is the
|
||||
/// cycle that only ends when the OS refuses a path. A symlink to a
|
||||
/// directory the walk has *not* seen is followed once, so
|
||||
/// `rtl -> ../shared/rtl` still contributes its files; the second link to
|
||||
/// one target contributes nothing further, and the files are reported
|
||||
/// under the first spelling that reached them.
|
||||
///
|
||||
/// A directory whose identity cannot be read is not entered.
|
||||
fn enter(&mut self, dir: &Path) -> bool {
|
||||
dir_id(dir).is_some_and(|id| self.visited.insert(id))
|
||||
}
|
||||
|
||||
/// Reads `dir`'s `.gitignore`, if there is one, onto the rule stack.
|
||||
/// Returns whether anything was pushed, so `dir` can pop it again.
|
||||
fn push_ignore(&mut self, dir: &Path) -> std::io::Result<bool> {
|
||||
///
|
||||
/// An ignore file that cannot be read is said and ignored, for the same
|
||||
/// reason an unreadable directory is: the walk that finds too much is a
|
||||
/// better failure than the walk that finds nothing.
|
||||
fn push_ignore(&mut self, dir: &Path) -> bool {
|
||||
let path = dir.join(GITIGNORE);
|
||||
if !self.gitignore || !path.is_file() {
|
||||
return Ok(false);
|
||||
return false;
|
||||
}
|
||||
let rules = parse_gitignore(&std::fs::read_to_string(&path)?);
|
||||
self.ignores.push(Ignore { base: self.rel.len(), rules });
|
||||
Ok(true)
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(text) => {
|
||||
self.ignores.push(Ignore { base: self.rel.len(), rules: parse_gitignore(&text) });
|
||||
true
|
||||
}
|
||||
Err(e) => {
|
||||
self.say(&path, e.to_string());
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a directory entry has no metadata, said the way a person would.
|
||||
///
|
||||
/// A broken symbolic link is what this is nearly always about, and naming it
|
||||
/// as one is worth more than the bare `No such file or directory` the follow
|
||||
/// produced; anything else keeps the operating system's own words.
|
||||
fn broken_link_reason(path: &Path) -> String {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(meta) if meta.file_type().is_symlink() => "broken symbolic link".to_string(),
|
||||
Ok(_) => "cannot be read".to_string(),
|
||||
Err(e) => e.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,6 +360,8 @@ fn glob_component(pattern: &str, name: &str) -> bool {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[cfg(unix)]
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn excluded(path: &str, pattern: &str) -> bool {
|
||||
is_excluded(Path::new(path), &[pattern.to_string()])
|
||||
@@ -320,6 +468,218 @@ mod tests {
|
||||
assert!(!ignored_at(&[(0, "/x.sv")], "sub/x.sv"));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Symlink cycles — `docs/features/walk-cycles/README.md`
|
||||
//
|
||||
// Every test below builds a real tree with real symlinks, because the
|
||||
// question is what the filesystem answers, not what a mock does. Each
|
||||
// one would run until the OS refused a path before the visited set.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A throwaway directory tree under the system temp dir, removed on
|
||||
/// drop. `remove_dir_all` unlinks a symlink instead of following it, so
|
||||
/// a tree with a cycle in it is cleaned up like any other.
|
||||
#[cfg(unix)]
|
||||
struct TempTree {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl TempTree {
|
||||
fn new(tag: &str) -> TempTree {
|
||||
static COUNTER: AtomicUsize = AtomicUsize::new(0);
|
||||
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("lucisv-walk-{}-{tag}-{n}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(&path).expect("create temp dir");
|
||||
TempTree { path }
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, text: &str) {
|
||||
let path = self.path.join(rel);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).expect("create parent");
|
||||
}
|
||||
std::fs::write(&path, text).expect("write");
|
||||
}
|
||||
|
||||
/// A source file with enough in it to be worth finding.
|
||||
fn source(&self, rel: &str) {
|
||||
self.write(rel, "module m;\nendmodule\n");
|
||||
}
|
||||
|
||||
/// Set `rel`'s permission bits. `0o000` is how a test builds the
|
||||
/// directory the walk cannot read; the test puts them back so the
|
||||
/// temp tree can be removed.
|
||||
fn chmod(&self, rel: &str, mode: u32) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let path = self.path.join(rel);
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode))
|
||||
.expect("set permissions");
|
||||
}
|
||||
|
||||
/// `rel` as a symlink to `target`, which is relative to `rel`'s own
|
||||
/// directory — the spelling a checked-in symlink actually uses.
|
||||
fn link(&self, rel: &str, target: &str) {
|
||||
let path = self.path.join(rel);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).expect("create parent");
|
||||
}
|
||||
std::os::unix::fs::symlink(target, &path).expect("symlink");
|
||||
}
|
||||
|
||||
/// The walk from `rel` (empty for the root), as sorted paths
|
||||
/// relative to the tree root. Warnings are dropped; the tests that
|
||||
/// care about them call [`TempTree::warned`].
|
||||
fn walk(&self, rel: &str) -> Vec<String> {
|
||||
self.walked(rel).0
|
||||
}
|
||||
|
||||
/// The same, plus what the walk said, each warning's path made
|
||||
/// relative to the tree root so the assertions read.
|
||||
fn warned(&self, rel: &str) -> (Vec<String>, Vec<String>) {
|
||||
self.walked(rel)
|
||||
}
|
||||
|
||||
fn walked(&self, rel: &str) -> (Vec<String>, Vec<String>) {
|
||||
let start = if rel.is_empty() { self.path.clone() } else { self.path.join(rel) };
|
||||
let mut files = Vec::new();
|
||||
let mut warnings = Vec::new();
|
||||
collect_files(
|
||||
start.to_str().expect("utf-8 temp path"),
|
||||
&[],
|
||||
true,
|
||||
&mut files,
|
||||
&mut |w| warnings.push(format!("{}: {}", self.rel_of(&w.path), w.message)),
|
||||
)
|
||||
.expect("the walk finishes");
|
||||
let mut out: Vec<String> = files.iter().map(|p| self.rel_of(p)).collect();
|
||||
out.sort();
|
||||
warnings.sort();
|
||||
(out, warnings)
|
||||
}
|
||||
|
||||
fn rel_of(&self, path: &Path) -> String {
|
||||
path.strip_prefix(&self.path).unwrap_or(path).to_string_lossy().into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_directory_linking_to_itself_is_entered_once() {
|
||||
let tree = TempTree::new("selfloop");
|
||||
tree.source("a/x.sv");
|
||||
tree.link("a/loop", "../a");
|
||||
assert_eq!(tree.walk(""), ["a/x.sv"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_link_to_an_ancestor_terminates_from_a_nested_start() {
|
||||
let tree = TempTree::new("uplink");
|
||||
tree.source("root.sv");
|
||||
tree.source("a/x.sv");
|
||||
tree.link("a/up", "..");
|
||||
// Starting *inside* the cycle: `a` is entered, then `a/up` is the
|
||||
// root, which the walk has not seen yet and so does enter — once.
|
||||
// Its own `a` is the directory already being walked, and stops.
|
||||
assert_eq!(tree.walk("a"), ["a/up/root.sv", "a/x.sv"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn two_links_to_one_directory_yield_its_files_once() {
|
||||
let tree = TempTree::new("twolinks");
|
||||
tree.source("shared/x.sv");
|
||||
// Sorted after `shared`, so the real directory is the spelling that
|
||||
// reaches the file first; whichever name wins, the file is reported
|
||||
// exactly once.
|
||||
tree.link("z1", "shared");
|
||||
tree.link("z2", "shared");
|
||||
assert_eq!(tree.walk(""), ["shared/x.sv"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_link_to_a_directory_not_yet_walked_is_still_followed() {
|
||||
let tree = TempTree::new("sibling");
|
||||
tree.source("shared/rtl/x.sv");
|
||||
tree.link("proj/rtl", "../shared/rtl");
|
||||
// The `rtl -> ../shared/rtl` of a real checkout: the target is
|
||||
// outside the walk, so the link is the only way to it.
|
||||
assert_eq!(tree.walk("proj"), ["proj/rtl/x.sv"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_dangling_source_link_is_warned_about_and_not_handed_on() {
|
||||
// §43's review kept the dangling source link in the file list so the
|
||||
// front end's "no such file" error survived. TODO §45.2 reverses that
|
||||
// on purpose: the warning is now the error's home, so the link is said
|
||||
// once here and never reaches the formatter. A dangling link that
|
||||
// names no source file was never going to be read and stays silent.
|
||||
let tree = TempTree::new("dangling");
|
||||
tree.source("a/x.sv");
|
||||
tree.link("a/gone.sv", "nowhere.sv");
|
||||
tree.link("a/gonedir", "nowhere");
|
||||
let (files, warnings) = tree.warned("");
|
||||
assert_eq!(files, ["a/x.sv"]);
|
||||
assert_eq!(warnings, ["a/gone.sv: broken symbolic link"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_unreadable_directory_is_skipped_and_the_walk_goes_on() {
|
||||
// The finding this channel exists for: one permission-denied directory
|
||||
// used to propagate `read_dir`'s error out of the whole walk, dropping
|
||||
// every file already found and failing the run.
|
||||
let tree = TempTree::new("unreadable");
|
||||
tree.source("a.sv");
|
||||
tree.source("locked/hidden.sv");
|
||||
tree.source("z/late.sv");
|
||||
tree.chmod("locked", 0o000);
|
||||
let (files, warnings) = tree.warned("");
|
||||
tree.chmod("locked", 0o755);
|
||||
assert_eq!(files, ["a.sv", "z/late.sv"], "the walk finished");
|
||||
assert_eq!(warnings.len(), 1, "{warnings:?}");
|
||||
assert!(warnings[0].starts_with("locked: "), "the warning names it: {warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_unreadable_ignore_file_is_said_and_the_directory_is_still_walked() {
|
||||
let tree = TempTree::new("lockedignore");
|
||||
tree.write(".gitignore", "build\n");
|
||||
tree.source("keep.sv");
|
||||
tree.chmod(".gitignore", 0o000);
|
||||
let (files, warnings) = tree.warned("");
|
||||
tree.chmod(".gitignore", 0o644);
|
||||
assert_eq!(files, ["keep.sv"]);
|
||||
assert_eq!(warnings.len(), 1, "{warnings:?}");
|
||||
assert!(warnings[0].starts_with(".gitignore: "), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_clean_walk_says_nothing() {
|
||||
let tree = TempTree::new("quiet");
|
||||
tree.source("a/x.sv");
|
||||
tree.source("b/y.sv");
|
||||
assert_eq!(tree.warned(""), (vec!["a/x.sv".to_string(), "b/y.sv".to_string()], Vec::new()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_cycle_inside_an_ignored_directory_is_never_entered() {
|
||||
let tree = TempTree::new("ignoredcycle");
|
||||
tree.write(".gitignore", "build\n");
|
||||
tree.source("keep.sv");
|
||||
tree.source("build/y.sv");
|
||||
tree.link("build/loop", "../build");
|
||||
assert_eq!(tree.walk(""), ["keep.sv"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_syntax_degrades_to_plain_globbing() {
|
||||
// `**` is just two stars inside one component; documented.
|
||||
|
||||
@@ -14,6 +14,7 @@ use lsp_types::{
|
||||
use vlog_linter::{apply_fixes, rule_by_name, Applicability, Violation};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::lint::LintRun;
|
||||
use crate::state::Document;
|
||||
|
||||
/// The kind of the fix-everything action, namespaced under `source.fixAll` so
|
||||
@@ -27,6 +28,7 @@ pub const FIX_ALL: &str = "source.fixAll.lucisv";
|
||||
/// client, because a fix-on-save request asks for `source.fixAll.lucisv` alone
|
||||
/// and computing every quick fix for it would be work nobody reads.
|
||||
pub fn code_actions(
|
||||
run: &LintRun,
|
||||
uri: &Uri,
|
||||
doc: &Document,
|
||||
range: Range,
|
||||
@@ -34,7 +36,7 @@ pub fn code_actions(
|
||||
tab_width: usize,
|
||||
) -> Vec<CodeActionOrCommand> {
|
||||
let positions = doc.positions();
|
||||
let violations = crate::lint::fixable(doc, tab_width);
|
||||
let violations = crate::lint::fixable(run, doc, tab_width);
|
||||
let mut actions = Vec::new();
|
||||
if wanted(only, &CodeActionKind::QUICKFIX) {
|
||||
let quick = violations.iter().filter_map(|v| quick_fix(uri, &positions, v, range));
|
||||
@@ -170,7 +172,7 @@ mod tests {
|
||||
fn actions_of(ws: &Workspace) -> Vec<CodeAction> {
|
||||
let doc = ws.document(&uri()).expect("open");
|
||||
let whole = doc.positions().whole_document();
|
||||
code_actions(&uri(), doc, whole, None, 2)
|
||||
code_actions(&LintRun::default(), &uri(), doc, whole, None, 2)
|
||||
.into_iter()
|
||||
.map(|a| match a {
|
||||
CodeActionOrCommand::CodeAction(action) => action,
|
||||
@@ -248,7 +250,14 @@ mod tests {
|
||||
start: Position { line: 1, character: 0 },
|
||||
end: Position { line: 1, character: 0 },
|
||||
};
|
||||
let actions = code_actions(&uri(), doc, line1, Some(&[CodeActionKind::QUICKFIX]), 2);
|
||||
let actions = code_actions(
|
||||
&LintRun::default(),
|
||||
&uri(),
|
||||
doc,
|
||||
line1,
|
||||
Some(&[CodeActionKind::QUICKFIX]),
|
||||
2,
|
||||
);
|
||||
assert_eq!(actions.len(), 1, "the cursor's line only: {actions:#?}");
|
||||
}
|
||||
|
||||
@@ -320,14 +329,32 @@ mod tests {
|
||||
start: Position { line: fenced_line, character: 0 },
|
||||
end: Position { line: fenced_line, character: 0 },
|
||||
};
|
||||
let actions = code_actions(&uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]), 2);
|
||||
let actions = code_actions(
|
||||
&LintRun::default(),
|
||||
&uri(),
|
||||
doc,
|
||||
at,
|
||||
Some(&[CodeActionKind::QUICKFIX]),
|
||||
2,
|
||||
);
|
||||
assert!(actions.is_empty(), "no quick fix inside a fence: {actions:#?}");
|
||||
// The unfenced tab one line further down still has one.
|
||||
let at = Range {
|
||||
start: Position { line: 4, character: 0 },
|
||||
end: Position { line: 4, character: 0 },
|
||||
};
|
||||
assert_eq!(code_actions(&uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]), 2).len(), 1);
|
||||
assert_eq!(
|
||||
code_actions(
|
||||
&LintRun::default(),
|
||||
&uri(),
|
||||
doc,
|
||||
at,
|
||||
Some(&[CodeActionKind::QUICKFIX]),
|
||||
2
|
||||
)
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -370,14 +397,19 @@ mod tests {
|
||||
let doc = ws.document(&uri()).expect("open");
|
||||
let whole = doc.positions().whole_document();
|
||||
let fix_all_only = [CodeActionKind::new(FIX_ALL)];
|
||||
let actions = code_actions(&uri(), doc, whole, Some(&fix_all_only), 2);
|
||||
let actions = code_actions(&LintRun::default(), &uri(), doc, whole, Some(&fix_all_only), 2);
|
||||
assert_eq!(actions.len(), 1, "no quick fixes when only fixAll was asked for");
|
||||
// `source` is a prefix filter for `source.fixAll.lucisv`.
|
||||
let source = [CodeActionKind::SOURCE];
|
||||
assert_eq!(code_actions(&uri(), doc, whole, Some(&source), 2).len(), 1);
|
||||
assert_eq!(
|
||||
code_actions(&LintRun::default(), &uri(), doc, whole, Some(&source), 2).len(),
|
||||
1
|
||||
);
|
||||
// And an unrelated filter selects nothing.
|
||||
let refactor = [CodeActionKind::REFACTOR];
|
||||
assert!(code_actions(&uri(), doc, whole, Some(&refactor), 2).is_empty());
|
||||
assert!(
|
||||
code_actions(&LintRun::default(), &uri(), doc, whole, Some(&refactor), 2).is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -386,7 +418,14 @@ mod tests {
|
||||
let ws = workspace(text);
|
||||
let doc = ws.document(&uri()).expect("open");
|
||||
let whole = doc.positions().whole_document();
|
||||
let actions = code_actions(&uri(), doc, whole, Some(&[CodeActionKind::QUICKFIX]), 4);
|
||||
let actions = code_actions(
|
||||
&LintRun::default(),
|
||||
&uri(),
|
||||
doc,
|
||||
whole,
|
||||
Some(&[CodeActionKind::QUICKFIX]),
|
||||
4,
|
||||
);
|
||||
let CodeActionOrCommand::CodeAction(fix) = &actions[0] else { panic!("an action") };
|
||||
assert_eq!(applied(text, fix), "module m;\n wire a;\nendmodule\n");
|
||||
}
|
||||
@@ -407,4 +446,28 @@ mod tests {
|
||||
assert!(out.contains("é 🎉"), "comments are never dropped: {out:?}");
|
||||
assert_eq!(out, "module m;\n // é 🎉 wire a;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_externally_waived_finding_gets_no_quick_fix_and_fix_all_leaves_it() {
|
||||
// §39 QA's HIGH: `fixable` used `default_rules()` and no waivers, so
|
||||
// fix-on-save rewrote a line a checked-in waiver file had waived.
|
||||
let src = "module m;\n\twire a;\nendmodule\n";
|
||||
let ws = workspace(src);
|
||||
let doc = ws.document(&uri()).expect("open");
|
||||
let whole = doc.positions().whole_document();
|
||||
let (external, problems) = vlog_linter::ExternalWaivers::parse(
|
||||
std::path::Path::new("team.waiver"),
|
||||
"waive --rule=no-tabs\n",
|
||||
);
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
let waived = LintRun::default().with_external(external);
|
||||
assert!(
|
||||
code_actions(&waived, &uri(), doc, whole, None, 2).is_empty(),
|
||||
"no quick fix and no fix-all for a waived finding"
|
||||
);
|
||||
assert!(
|
||||
!code_actions(&LintRun::default(), &uri(), doc, whole, None, 2).is_empty(),
|
||||
"the same buffer without the waiver is fixable"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -755,6 +755,92 @@ endmodule
|
||||
assert_eq!(labels, ["clk_renamed:", "rst_n:", "data:"]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the default scope (TODO §37.2 / `performance_take2.md` §4b, §8)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// An opentitan-shaped tree: an IP block with its RTL and its testbench,
|
||||
/// and a shared library folder outside that block. Opening
|
||||
/// `ip/aes/dv/tb/tb.sv` at the shipped `scopeDepth` of 2 raises to
|
||||
/// `ip/aes`, so `ip/aes/rtl/sub.sv` is indexed and `dv/common/far.sv` is
|
||||
/// not — which is exactly the shape `hw/ip/aes/dv/tb/tb.sv` has against
|
||||
/// `hw/dv/sv/common_ifs/pins_if.sv`.
|
||||
fn default_scoped(name: &str) -> (Tree, Workspace, Uri, &'static str) {
|
||||
const TB: &str =
|
||||
"module tb;\n sub u_sub (clk, rst_n, data);\n far u_far (a);\nendmodule\n";
|
||||
let tree = Tree::new(name);
|
||||
fs::create_dir_all(tree.path.join("ip/aes/rtl")).expect("dirs");
|
||||
fs::create_dir_all(tree.path.join("ip/aes/dv/tb")).expect("dirs");
|
||||
fs::create_dir_all(tree.path.join("dv/common")).expect("dirs");
|
||||
tree.write("ip/aes/rtl/sub.sv", SUB);
|
||||
tree.write("dv/common/far.sv", "module far (\n input logic a\n);\nendmodule\n");
|
||||
let tb = tree.write("ip/aes/dv/tb/tb.sv", TB);
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
// The shipped default: no `index.scope`, `scopeDepth` 2.
|
||||
ws.set_client_settings(crate::settings::ClientSettings::default());
|
||||
ws.adopt_roots(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&tb).expect("uri");
|
||||
ws.set_document(uri.clone(), TB.to_string());
|
||||
ws.rebuild_index();
|
||||
(tree, ws, uri, TB)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_scope_hints_a_module_the_didopen_widen_reached() {
|
||||
// `performance_take2.md` §4b measured 0 hints at the default scope
|
||||
// where the workspace scope gives 4, and §8 filed it as a correctness
|
||||
// gap. It is not one: the hints that scope answers are exactly the
|
||||
// instantiations whose module the widen reached.
|
||||
let (tree, ws, uri, _) = default_scoped("default_scope");
|
||||
assert!(
|
||||
ws.index().files().iter().any(|f| f.ends_with("sub.sv")),
|
||||
"the widen reached the block's own RTL: {:?}",
|
||||
ws.index().files()
|
||||
);
|
||||
assert!(
|
||||
!ws.index().files().iter().any(|f| f.ends_with("far.sv")),
|
||||
"and not the library folder beside it"
|
||||
);
|
||||
|
||||
let hints = inlay_hints(&ws, &uri, everything());
|
||||
let labels: Vec<String> = hints
|
||||
.into_iter()
|
||||
.map(|h| {
|
||||
let InlayHintLabel::String(s) = h.label else { panic!("string") };
|
||||
s
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(labels, ["clk:", "rst_n:", "data:"], "the in-scope instantiation is hinted");
|
||||
drop(tree);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_out_of_scope_module_is_unhinted_exactly_as_it_is_undefined() {
|
||||
// The other half of the same finding: the `far` instantiation gets no
|
||||
// hints — and go-to-definition and hover give nothing for it either.
|
||||
// The zero is the scope's, not this module's; inlay uses the same
|
||||
// `module_definition` lookup its neighbours do.
|
||||
let (tree, ws, uri, tb) = default_scoped("out_of_scope");
|
||||
let hints = inlay_hints(&ws, &uri, everything());
|
||||
assert!(
|
||||
hints.iter().all(|hint| hint.position.line != 2),
|
||||
"nothing on the `far` line: {hints:#?}"
|
||||
);
|
||||
|
||||
let far = tb.find("far u_far").expect("the instantiation") as u32;
|
||||
assert!(crate::nav::definition(&ws, &uri, far).is_empty(), "nor does F12 answer");
|
||||
assert!(crate::hover::hover(&ws, &uri, far).is_none(), "nor does hover");
|
||||
|
||||
// And the moment the scope reaches it, all three answer.
|
||||
let mut wide = Workspace::default();
|
||||
wide.open_whole_workspace(vec![tree.path.clone()]);
|
||||
wide.set_document(uri.clone(), tb.to_string());
|
||||
let hints = inlay_hints(&wide, &uri, everything());
|
||||
assert_eq!(hints.len(), 4, "three ports plus `far`'s one: {hints:#?}");
|
||||
assert_eq!(crate::nav::definition(&wide, &uri, far).len(), 1);
|
||||
}
|
||||
|
||||
/// Order-of-magnitude perf checks, not run as part of the ordinary suite:
|
||||
/// timing assertions in a shared CI runner are flaky by nature. Run with
|
||||
/// `cargo test --release -p lucisv_server --bin lucisv-server qa_perf -- --ignored --nocapture`.
|
||||
|
||||
@@ -575,6 +575,7 @@ mod tests {
|
||||
use crate::uri::path_to_uri;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
use vlog_parser::PARSE_STACK_SIZE;
|
||||
|
||||
/// A one-file workspace with `path` open and the cursor at `needle`'s end.
|
||||
/// No files on disk: nothing here reads the index.
|
||||
@@ -1081,10 +1082,31 @@ endmodule
|
||||
// A trailing newline, so this test isolates depth from the separate
|
||||
// true-end-of-file `Eof`-adjacency case pinned above.
|
||||
text.push_str("initial begin\n");
|
||||
let (ws, uri, position) = asking(&text, "initial begin");
|
||||
assert!(!ws.document(&uri).expect("open").tokens.is_empty(), "the lexer never recurses");
|
||||
let items = inline_completions(&ws, &uri, position);
|
||||
assert!(items.is_some(), "the innermost, truly unclosed `begin` still offers its `end`");
|
||||
// Opening the document *parses* it, and since §36.1 a bare `begin` at
|
||||
// item scope is a generate block the tolerant parser descends into —
|
||||
// so this text nests the parser to `MAX_NESTING_DEPTH` and costs ~4
|
||||
// MiB of stack in a debug build. That is exactly what
|
||||
// `PARSE_STACK_SIZE` is for; every production thread that may reach a
|
||||
// parse is given it (`main.rs`), libtest's own thread is not, so the
|
||||
// body runs on one of its own. Nothing here is about the inline path,
|
||||
// which still never recurses.
|
||||
std::thread::Builder::new()
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(move || {
|
||||
let (ws, uri, position) = asking(&text, "initial begin");
|
||||
assert!(
|
||||
!ws.document(&uri).expect("open").tokens.is_empty(),
|
||||
"the lexer never recurses"
|
||||
);
|
||||
let items = inline_completions(&ws, &uri, position);
|
||||
assert!(
|
||||
items.is_some(),
|
||||
"the innermost, truly unclosed `begin` still offers its `end`"
|
||||
);
|
||||
})
|
||||
.expect("spawn")
|
||||
.join()
|
||||
.expect("the inline path crashed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -144,6 +144,7 @@ fn item_pairs(item: &Item, out: &mut Vec<Pair>) {
|
||||
ItemKind::Task(t) => task_pairs(t, out),
|
||||
ItemKind::Clocking(c) => clocking_pairs(c, out),
|
||||
ItemKind::GenerateRegion { items, .. } => items_pairs(items, out),
|
||||
ItemKind::GenBlock(b) => items_pairs(&b.items, out),
|
||||
ItemKind::GenIf(g) => gen_if_pairs(g, out),
|
||||
ItemKind::GenFor(g) => gen_block_pairs(&g.body, out),
|
||||
ItemKind::GenCase(g) => {
|
||||
|
||||
@@ -10,14 +10,26 @@
|
||||
//! table `lucisv.toml` now carries. See
|
||||
//! `docs/features/semantic-lints-on/README.md` and
|
||||
//! `docs/features/server-lint/README.md`.
|
||||
//!
|
||||
//! Since §42 the two halves of that selection are one contract: the editor's
|
||||
//! settings play the role the CLI's flags play, and the project's `[lint]`
|
||||
//! table is what stands when the editor says nothing —
|
||||
//! `docs/features/lint-config-contract/README.md`, and [`project`] for the
|
||||
//! project's half.
|
||||
|
||||
mod project;
|
||||
|
||||
pub use project::{ConfigProblems, ProblemLog, ProjectLint};
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString};
|
||||
use lucisv_core::config::FileConfig;
|
||||
use vlog_formatter::fence::{self, Region};
|
||||
use vlog_linter::{
|
||||
default_rules, lint, workspace_rules, LintContext, MentionOracle, ModuleInterface, Rule,
|
||||
RuleOptions, Severity, Violation,
|
||||
default_rules, lint_with, workspace_rules, ExternalWaivers, LintContext, MentionOracle,
|
||||
ModuleInterface, Rule, RuleOptions, Severity, Violation,
|
||||
};
|
||||
use vlog_semantic::{FileId, SymbolKind, WorkspaceIndex};
|
||||
|
||||
@@ -41,6 +53,14 @@ pub struct LintRun<'a> {
|
||||
/// The width `line-length` holds this buffer to — the width the formatter
|
||||
/// would wrap it to, so the two halves of lucisv cannot disagree.
|
||||
line_length: usize,
|
||||
/// The external waiver files in force for this buffer, from its
|
||||
/// `lucisv.toml` and from `lucisv.lint.waivers`. Empty unless one is
|
||||
/// configured, and then costing the pass nothing.
|
||||
external: ExternalWaivers,
|
||||
/// What the buffer's `lucisv.toml` asked for and did not get. Reported by
|
||||
/// whoever can talk to the client — [`ProblemLog`] keeps it to once per
|
||||
/// (config file, message) — and never fatal here: §42.2.
|
||||
problems: ConfigProblems,
|
||||
}
|
||||
|
||||
impl Default for LintRun<'_> {
|
||||
@@ -50,6 +70,8 @@ impl Default for LintRun<'_> {
|
||||
oracle: None,
|
||||
options: RuleOptions::new(),
|
||||
line_length: DEFAULT_LINE_LENGTH,
|
||||
external: ExternalWaivers::default(),
|
||||
problems: ConfigProblems::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -71,10 +93,36 @@ 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 rules = enabled_rules(ws.client_settings(), workspace);
|
||||
let oracle = workspace.then_some(IndexMentions { index, own });
|
||||
let (options, line_length) = configured(ws.client_settings(), doc);
|
||||
LintRun { rules, oracle, options, line_length }
|
||||
// One discovery for the whole pass: the selection, the options, the
|
||||
// width and the waiver paths all read the same `FileConfig`, so
|
||||
// reading the project's rules costs no extra stat and no extra open.
|
||||
let (options, line_length, file, mut messages) = configured(ws.client_settings(), doc);
|
||||
let (from_file, bad_names) = ProjectLint::read(&file);
|
||||
messages.extend(bad_names);
|
||||
let rules = enabled_rules(ws.client_settings(), &from_file, workspace);
|
||||
let (mut external, bad_waivers) = external_waivers(&project_waivers(&file));
|
||||
messages.extend(bad_waivers);
|
||||
// The editor's own waiver files are read separately and their
|
||||
// problems dropped: `notification::apply_settings` already said them
|
||||
// once, where the setting arrived.
|
||||
external.absorb(external_waivers(&editor_waivers(ws.client_settings(), ws.roots())).0);
|
||||
let problems = ConfigProblems::new(&file, messages);
|
||||
LintRun { rules, oracle, options, line_length, external, problems }
|
||||
}
|
||||
|
||||
/// What this buffer's `lucisv.toml` asked for and did not get, for a
|
||||
/// caller that can tell the user about it.
|
||||
pub fn config_problems(&self) -> &ConfigProblems {
|
||||
&self.problems
|
||||
}
|
||||
|
||||
/// A run carrying these external waivers — for the tests that pin what a
|
||||
/// waiver keeps out of the code actions.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_external(mut self, external: ExternalWaivers) -> Self {
|
||||
self.external = external;
|
||||
self
|
||||
}
|
||||
|
||||
/// This run's context over a buffer's own parse products.
|
||||
@@ -109,51 +157,139 @@ impl<'a> LintRun<'a> {
|
||||
/// reads it per formatting request: a `lucisv.toml` edited while the server
|
||||
/// runs takes effect at the next publish, and the read is a few stats beside
|
||||
/// a parse and an analysis the same pass already paid for.
|
||||
fn configured(client: &ClientSettings, doc: &Document) -> (RuleOptions, usize) {
|
||||
fn configured(
|
||||
client: &ClientSettings,
|
||||
doc: &Document,
|
||||
) -> (RuleOptions, usize, FileConfig, Vec<String>) {
|
||||
let file = doc
|
||||
.path
|
||||
.as_deref()
|
||||
.and_then(|path| lucisv_core::config::Discovery::new(true).for_file(path).ok())
|
||||
.unwrap_or_default();
|
||||
let mut options = RuleOptions::new();
|
||||
let mut problems = Vec::new();
|
||||
for entry in &file.lint_options {
|
||||
// A broken entry in the file is dropped here rather than reported:
|
||||
// `format::settings_for` already surfaces a `lucisv.toml` problem to
|
||||
// the user, and `lucisv check` fails the run over it with file and
|
||||
// line, which is where a config error belongs.
|
||||
let _ = options.set_raw(&entry.rule, &entry.key, &entry.raw);
|
||||
// A broken entry in the file is dropped rather than fatal — an editor
|
||||
// cannot fail a run — but it is *said*, in the words `lucisv check`
|
||||
// fails with, once per (config file, entry): §42.2. Silently dropping
|
||||
// it left a user's option doing nothing with nothing to read about it.
|
||||
if let Err(problem) = options.set_raw(&entry.rule, &entry.key, &entry.raw) {
|
||||
let source = file
|
||||
.source
|
||||
.as_ref()
|
||||
.map_or_else(|| "lucisv.toml".to_string(), |path| path.display().to_string());
|
||||
problems.push(format!("{source}:{}: rule `{}` {problem}", entry.line, entry.rule));
|
||||
}
|
||||
}
|
||||
options.overlay(&client.lint_options);
|
||||
let width = file.line_length.or(client.line_length).unwrap_or(DEFAULT_LINE_LENGTH);
|
||||
(options, width)
|
||||
(options, width, file, problems)
|
||||
}
|
||||
|
||||
/// Which rules a buffer is linted with, given what the editor's settings say.
|
||||
/// The waiver files governing one buffer: its `lucisv.toml`'s `[lint] waivers`
|
||||
/// first, then `lucisv.lint.waivers` from the editor.
|
||||
///
|
||||
/// The two **add up**, the way they do on the command line — a waiver file
|
||||
/// only ever suppresses findings, so there is nothing here for one list to
|
||||
/// take back from the other. A relative setting path is resolved against the
|
||||
/// first workspace root, exactly as `lucisv.filelist` is; a `lucisv.toml`'s
|
||||
/// paths were already resolved against that file's own directory.
|
||||
pub fn waiver_paths(client: &ClientSettings, roots: &[PathBuf], file: &FileConfig) -> Vec<PathBuf> {
|
||||
let mut paths = project_waivers(file);
|
||||
paths.extend(editor_waivers(client, roots));
|
||||
paths
|
||||
}
|
||||
|
||||
/// The `[lint] waivers` of one config file, already resolved by `Discovery`
|
||||
/// against that file's own directory.
|
||||
///
|
||||
/// Read apart from the editor's since §42.2, because a problem in one of
|
||||
/// *these* is the project's and belongs in the output channel with the
|
||||
/// `lucisv.toml` that named it, while a problem in the editor's was already
|
||||
/// said where the setting arrived.
|
||||
fn project_waivers(file: &FileConfig) -> Vec<PathBuf> {
|
||||
file.lint_waivers.iter().flatten().cloned().collect()
|
||||
}
|
||||
|
||||
/// The waiver files `lucisv.lint.waivers` names, a relative one anchored at
|
||||
/// the first workspace root exactly as `lucisv.filelist` is.
|
||||
fn editor_waivers(client: &ClientSettings, roots: &[PathBuf]) -> Vec<PathBuf> {
|
||||
client
|
||||
.lint_waivers
|
||||
.iter()
|
||||
.map(|setting| {
|
||||
let path = Path::new(setting);
|
||||
match roots.first() {
|
||||
Some(root) if path.is_relative() => root.join(path),
|
||||
_ => path.to_path_buf(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Those files, read: the waivers and one message per file or line that could
|
||||
/// not be used.
|
||||
///
|
||||
/// **Nothing here is fatal.** A push arrives on a socket and a bad path in it
|
||||
/// must never cost a user every diagnostic in their file — this module's
|
||||
/// standing rule, and `settings::rule_options`'. The messages are logged once,
|
||||
/// when the settings arrive (`server::notification::apply_settings`); the lint
|
||||
/// pass, which runs on every keystroke, drops them silently rather than
|
||||
/// logging the same line a hundred times.
|
||||
pub fn external_waivers(paths: &[PathBuf]) -> (ExternalWaivers, Vec<String>) {
|
||||
let mut waivers = ExternalWaivers::default();
|
||||
let mut problems = Vec::new();
|
||||
for path in paths {
|
||||
match ExternalWaivers::read(path) {
|
||||
Ok((file, bad)) => {
|
||||
problems.extend(bad);
|
||||
waivers.absorb(file);
|
||||
}
|
||||
Err(problem) => problems.push(problem),
|
||||
}
|
||||
}
|
||||
(waivers, problems)
|
||||
}
|
||||
|
||||
/// Which rules a buffer is linted with, given what the editor's settings and
|
||||
/// the buffer's own `lucisv.toml` 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;
|
||||
/// `--select` replaces it on the command line; when the editor names
|
||||
/// nothing, the project's `[lint] select` replaces it instead — the flag
|
||||
/// when there is one, else the file, which is `lucisv check`'s own `pick`;
|
||||
/// 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.
|
||||
/// one a user reaches for when nothing else worked; when the editor names
|
||||
/// nothing there either, the project's `[lint] ignore` removes instead.
|
||||
///
|
||||
/// 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() {
|
||||
/// Rungs 3 and 4 are the **editor's alone**: a `lucisv.toml` has no such
|
||||
/// keys, and the command line has no such flags. Rungs 2 and 5 are decided
|
||||
/// independently — a project that selects and a user who only ignores keep
|
||||
/// both halves. Every list accepts a severity word wherever a rule name fits,
|
||||
/// the project's as much as the editor's.
|
||||
pub fn enabled_rules(
|
||||
settings: &ClientSettings,
|
||||
project: &ProjectLint,
|
||||
has_oracle: bool,
|
||||
) -> Vec<&'static dyn Rule> {
|
||||
let select = pick(&settings.lint_select, &project.select);
|
||||
let base = if select.is_empty() {
|
||||
if has_oracle {
|
||||
workspace_rules()
|
||||
} else {
|
||||
default_rules()
|
||||
}
|
||||
} else {
|
||||
named(&settings.lint_select)
|
||||
named(select)
|
||||
};
|
||||
let mut on: BTreeSet<&'static str> = base.iter().map(|rule| rule.name()).collect();
|
||||
|
||||
@@ -172,12 +308,22 @@ pub fn enabled_rules(settings: &ClientSettings, has_oracle: bool) -> Vec<&'stati
|
||||
on.remove(rule.name());
|
||||
}
|
||||
}
|
||||
for rule in named(&settings.lint_ignore) {
|
||||
for rule in named(pick(&settings.lint_ignore, &project.ignore)) {
|
||||
on.remove(rule.name());
|
||||
}
|
||||
vlog_linter::all_rules().into_iter().filter(|rule| on.contains(rule.name())).collect()
|
||||
}
|
||||
|
||||
/// The editor's list when it said anything, else the project's — the twin of
|
||||
/// `lucisv/src/lint.rs`'s `pick`, which is the whole of §42's contract.
|
||||
fn pick<'a>(editor: &'a [String], project: &'a [String]) -> &'a [String] {
|
||||
if editor.is_empty() {
|
||||
project
|
||||
} else {
|
||||
editor
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -256,8 +402,13 @@ fn context(doc: &Document) -> LintContext<'_> {
|
||||
///
|
||||
/// This is the diagnostics path, which never looks at a fix, so the width a
|
||||
/// `no-tabs` fix would expand a tab to is left at the linter's own default.
|
||||
/// The external waivers apply here exactly as the inline ones do, as a union.
|
||||
/// Which of them *fired* is discarded: only a whole run can tell whether a
|
||||
/// waiver was dead, and a server never has one — it lints the buffers a user
|
||||
/// happens to have open. `lucisv check` is what reports an unused external
|
||||
/// waiver; see `docs/features/waiver-files/README.md`.
|
||||
pub fn violations_in(doc: &Document, run: &LintRun) -> Vec<Violation> {
|
||||
lint(&run.context(doc), &run.rules)
|
||||
lint_with(&run.context(doc), &run.rules, &run.external).0
|
||||
}
|
||||
|
||||
/// The findings a code action may offer a fix for, with their fixes built for
|
||||
@@ -274,8 +425,14 @@ pub fn violations_in(doc: &Document, run: &LintRun) -> Vec<Violation> {
|
||||
/// just has no lightbulb. Which bytes count as fenced is
|
||||
/// [`fence::protected_regions`]' answer, the one the CLI asks too; see
|
||||
/// `docs/features/shared-fence-filter/README.md`.
|
||||
pub fn fixable(doc: &Document, tab_width: usize) -> Vec<Violation> {
|
||||
let found = lint(&context(doc).with_tab_width(tab_width), &default_rules());
|
||||
pub fn fixable(run: &LintRun, doc: &Document, tab_width: usize) -> Vec<Violation> {
|
||||
// The buffer's own run: its enabled rules and its external waiver files,
|
||||
// so a fix is never offered — nor applied by fix-on-save — for a finding
|
||||
// the diagnostics pass would not have shown. Found by §39's QA: with
|
||||
// `default_rules()` and no waivers here, `source.fixAll.lucisv` rewrote a
|
||||
// line a checked-in waiver file had waived.
|
||||
let ctx = run.context(doc).with_tab_width(tab_width);
|
||||
let found = lint_with(&ctx, &run.rules, &run.external).0;
|
||||
// One tolerant parse per code-action request: `protected_regions` takes
|
||||
// text and parses internally, on purpose — one fence answer for every
|
||||
// front end, none of which can feed it a stale tree (see
|
||||
@@ -449,7 +606,7 @@ mod tests {
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let diags = diagnostics(doc);
|
||||
assert_eq!(diags.len(), 2, "both tabs are reported: {diags:#?}");
|
||||
let offered = fixable(doc, 2);
|
||||
let offered = fixable(&LintRun::default(), doc, 2);
|
||||
assert_eq!(offered.len(), 1, "only the unfenced one may be fixed: {offered:#?}");
|
||||
let free = text.find("\twire b").expect("the unfenced tab") as u32;
|
||||
assert_eq!(offered[0].span.start, free);
|
||||
@@ -469,7 +626,7 @@ mod tests {
|
||||
.any(|d| d.code == Some(NumberOrString::String("no-tabs".into()))),
|
||||
"still reported"
|
||||
);
|
||||
assert!(fixable(doc, 2).is_empty(), "and still not fixable");
|
||||
assert!(fixable(&LintRun::default(), doc, 2).is_empty(), "and still not fixable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -548,8 +705,14 @@ mod tests {
|
||||
/// be true of the result).
|
||||
#[test]
|
||||
fn the_enabled_rules_ladder_is_the_documented_one() {
|
||||
// The project's half of the ladder is `lint::project`'s own table
|
||||
// test; this one holds it empty, which is the editor-only ladder
|
||||
// §33.1 wrote.
|
||||
let names = |settings: &ClientSettings, oracle: bool| -> Vec<&'static str> {
|
||||
enabled_rules(settings, oracle).into_iter().map(|rule| rule.name()).collect()
|
||||
enabled_rules(settings, &ProjectLint::default(), oracle)
|
||||
.into_iter()
|
||||
.map(|rule| rule.name())
|
||||
.collect()
|
||||
};
|
||||
let with = |f: &dyn Fn(&mut ClientSettings)| {
|
||||
let mut settings = ClientSettings::default();
|
||||
@@ -711,7 +874,7 @@ mod tests {
|
||||
#[test]
|
||||
fn an_unfenced_file_offers_every_fix() {
|
||||
let (ws, uri) = doc_of("module m;\n// just a note\n\twire a;\nendmodule\n");
|
||||
assert_eq!(fixable(ws.document(&uri).expect("open"), 2).len(), 1);
|
||||
assert_eq!(fixable(&LintRun::default(), ws.document(&uri).expect("open"), 2).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -719,9 +882,60 @@ mod tests {
|
||||
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
for width in [2usize, 4] {
|
||||
let found = fixable(doc, width);
|
||||
let found = fixable(&LintRun::default(), doc, width);
|
||||
let fix = found[0].fix.as_ref().expect("no-tabs offers a fix");
|
||||
assert_eq!(fix.edits[0].1, " ".repeat(width));
|
||||
}
|
||||
}
|
||||
|
||||
/// The two waiver lists add up, and only the setting's relative paths are
|
||||
/// anchored at the first root — a `lucisv.toml`'s were resolved against
|
||||
/// that file's own directory before they got here. TODO §39.
|
||||
#[test]
|
||||
fn the_config_files_waivers_come_first_and_the_settings_are_rooted() {
|
||||
let file = FileConfig {
|
||||
lint_waivers: Some(vec![PathBuf::from("/proj/rtl/project.waiver")]),
|
||||
..Default::default()
|
||||
};
|
||||
let client = ClientSettings {
|
||||
lint_waivers: vec!["team.waiver".to_string(), "/etc/global.waiver".to_string()],
|
||||
..Default::default()
|
||||
};
|
||||
let roots = vec![PathBuf::from("/work/top")];
|
||||
assert_eq!(
|
||||
waiver_paths(&client, &roots, &file),
|
||||
vec![
|
||||
PathBuf::from("/proj/rtl/project.waiver"),
|
||||
PathBuf::from("/work/top/team.waiver"),
|
||||
PathBuf::from("/etc/global.waiver"),
|
||||
]
|
||||
);
|
||||
// With no root at all a relative path is left as written rather than
|
||||
// guessed at, exactly as `filelist_path` leaves it.
|
||||
assert_eq!(
|
||||
waiver_paths(&client, &[], &FileConfig::default()),
|
||||
vec![PathBuf::from("team.waiver"), PathBuf::from("/etc/global.waiver")]
|
||||
);
|
||||
assert!(waiver_paths(&ClientSettings::default(), &roots, &FileConfig::default()).is_empty());
|
||||
}
|
||||
|
||||
/// A waiver file that is missing, and one with a bad line, are both
|
||||
/// described rather than fatal — and the good directives of the second
|
||||
/// still apply. TODO §39.
|
||||
#[test]
|
||||
fn a_bad_waiver_file_is_described_and_its_good_directives_still_apply() {
|
||||
let dir = std::env::temp_dir().join(format!("lucisv_waiver_paths_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
let good = dir.join("good.waiver");
|
||||
std::fs::write(&good, "waive --rule=no-tabs\nwaive --rule=nope\n").expect("write");
|
||||
|
||||
let (waivers, problems) = external_waivers(&[good.clone(), dir.join("missing.waiver")]);
|
||||
assert!(!waivers.is_empty(), "the good directive survived its neighbour");
|
||||
assert_eq!(problems.len(), 2, "{problems:?}");
|
||||
assert!(problems[0].contains("good.waiver:2: unknown rule `nope`"), "{problems:?}");
|
||||
assert!(problems[1].contains("missing.waiver"), "{problems:?}");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
//! What a buffer's `lucisv.toml` says about linting, and what could not be
|
||||
//! used from it.
|
||||
//!
|
||||
//! The contract (§42): **the editor's settings play the role the CLI's flags
|
||||
//! play**. `lucisv check` picks the flag when one was given and the project
|
||||
//! file otherwise (`lucisv/src/lint.rs`'s `pick`); the server picks
|
||||
//! `lucisv.lint.select` when it is non-empty and `[lint] select` otherwise,
|
||||
//! key by key, so one buffer linted two ways is linted the same way. See
|
||||
//! `docs/features/lint-config-contract/README.md`.
|
||||
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use lucisv_core::config::FileConfig;
|
||||
|
||||
/// The selection a buffer's `lucisv.toml` carries: `[lint] select` and
|
||||
/// `[lint] ignore`, exactly as `--select` and `--ignore` carry them.
|
||||
///
|
||||
/// [`ProjectLint::default`] — both lists empty — is a buffer with no config
|
||||
/// file, or one whose `[lint]` table says nothing about rules: the editor's
|
||||
/// settings and the base set then decide everything, which is what this
|
||||
/// server did before §42.
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct ProjectLint {
|
||||
/// `[lint] select`: run exactly these rules, replacing the base set —
|
||||
/// unless the editor named some, which outranks it.
|
||||
pub select: Vec<String>,
|
||||
/// `[lint] ignore`: rules dropped from whatever `select` left — unless
|
||||
/// the editor named some.
|
||||
pub ignore: Vec<String>,
|
||||
}
|
||||
|
||||
impl ProjectLint {
|
||||
/// One config file's selection, with every name the registry does not
|
||||
/// know dropped and reported.
|
||||
///
|
||||
/// `lucisv check` *fails the run* over an unknown name, which an editor
|
||||
/// cannot do — but it must not silently obey a typo either: a
|
||||
/// `select = ["no-tab"]` taken at face value would resolve to no rules at
|
||||
/// all and blank the file's squiggles, which reads as "lucisv is happy"
|
||||
/// rather than "lucisv could not understand your config". So the name is
|
||||
/// dropped, said once, and the rest of the list still applies; a `select`
|
||||
/// left empty by the dropping falls back to the base set.
|
||||
pub fn read(file: &FileConfig) -> (ProjectLint, Vec<String>) {
|
||||
let mut problems = Vec::new();
|
||||
let select = known(file, "select", file.lint_select.as_deref(), &mut problems);
|
||||
let ignore = known(file, "ignore", file.lint_ignore.as_deref(), &mut problems);
|
||||
(ProjectLint { select, ignore }, problems)
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of one `[lint]` list that name something, the others reported.
|
||||
fn known(
|
||||
file: &FileConfig,
|
||||
key: &str,
|
||||
list: Option<&[String]>,
|
||||
problems: &mut Vec<String>,
|
||||
) -> Vec<String> {
|
||||
let mut kept = Vec::new();
|
||||
for name in list.unwrap_or(&[]) {
|
||||
if vlog_linter::rules_named(name).is_some() {
|
||||
kept.push(name.clone());
|
||||
} else {
|
||||
// No line number: `lucisv_core::config` records one per
|
||||
// `[lint.<rule>]` entry, because those are checked one by one,
|
||||
// and the list keys are one value each.
|
||||
problems.push(format!("{}: [lint] {key}: unknown rule: {name}", source_of(file)));
|
||||
}
|
||||
}
|
||||
kept
|
||||
}
|
||||
|
||||
/// The config file's path as an error should name it.
|
||||
fn source_of(file: &FileConfig) -> String {
|
||||
file.source.as_ref().map_or_else(|| "lucisv.toml".to_string(), |p| p.display().to_string())
|
||||
}
|
||||
|
||||
/// What one buffer's `lucisv.toml` asked for and did not get: a
|
||||
/// `[lint.<rule>]` entry the registry refused, a name in `[lint] select` that
|
||||
/// is not a rule, a `[lint] waivers` file that is not there or holds a
|
||||
/// directive that does not parse.
|
||||
///
|
||||
/// Every message is written the way `lucisv check` writes it —
|
||||
/// `<file>:<line>: <message>` — so the same mistake reads the same in CI and
|
||||
/// in an editor's output channel. **Nothing here is fatal**: the entry is
|
||||
/// dropped and the buffer is still linted with everything that was
|
||||
/// understood, because a server cannot fail a run the way a command can.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct ConfigProblems {
|
||||
/// The config file they came from. `None` — no config file was found —
|
||||
/// means there is nothing to complain about and `messages` is empty.
|
||||
source: Option<PathBuf>,
|
||||
/// A stamp of that file's lint content, so an edited config gets a fresh
|
||||
/// hearing: see [`ProblemLog`].
|
||||
stamp: u64,
|
||||
/// The messages, in file order.
|
||||
messages: Vec<String>,
|
||||
}
|
||||
|
||||
impl ConfigProblems {
|
||||
/// The problems found in this config file.
|
||||
pub fn new(file: &FileConfig, messages: Vec<String>) -> ConfigProblems {
|
||||
ConfigProblems { source: file.source.clone(), stamp: stamp_of(file), messages }
|
||||
}
|
||||
|
||||
/// Whether anything at all could not be used.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.messages.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// A stamp over everything in a config file that [`ConfigProblems`] can be
|
||||
/// about, so that editing the file re-arms the report and editing a source
|
||||
/// beside it does not.
|
||||
///
|
||||
/// A hash rather than a modification time: the file is re-read on every lint
|
||||
/// pass anyway (`configured`), and a hash of what was parsed cannot be fooled
|
||||
/// by a filesystem whose timestamps are coarse.
|
||||
fn stamp_of(file: &FileConfig) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
file.lint_select.hash(&mut hasher);
|
||||
file.lint_ignore.hash(&mut hasher);
|
||||
file.lint_waivers.hash(&mut hasher);
|
||||
for entry in &file.lint_options {
|
||||
entry.rule.hash(&mut hasher);
|
||||
entry.key.hash(&mut hasher);
|
||||
entry.raw.hash(&mut hasher);
|
||||
entry.line.hash(&mut hasher);
|
||||
}
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// Which config problems have already been said, so each is said **once**.
|
||||
///
|
||||
/// Once per (config file, message), not once per lint pass: the pass runs on
|
||||
/// every keystroke and every index rebuild, and a hundred copies of one line
|
||||
/// in the output channel is not a report, it is noise. The editor-settings
|
||||
/// path has said its own problems once since §34 — this is the same promise
|
||||
/// for the file a project checks in.
|
||||
///
|
||||
/// A config file whose lint content changed clears its own memo, so a user
|
||||
/// who edits `lucisv.toml` and gets it wrong again is told again. The memo is
|
||||
/// keyed by path, so it holds one small entry per config file a session ever
|
||||
/// linted through.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ProblemLog {
|
||||
said: HashMap<PathBuf, Said>,
|
||||
}
|
||||
|
||||
/// One config file's memo: the content it was taken under, and what was said.
|
||||
#[derive(Debug, Default)]
|
||||
struct Said {
|
||||
stamp: u64,
|
||||
messages: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl ProblemLog {
|
||||
/// The messages that have not been said yet for this config file, marked
|
||||
/// as said. An empty answer means the user has already been told.
|
||||
pub fn unsaid(&mut self, problems: &ConfigProblems) -> Vec<String> {
|
||||
let Some(source) = problems.source.clone() else { return Vec::new() };
|
||||
if problems.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let said = self.said.entry(source).or_default();
|
||||
if said.stamp != problems.stamp {
|
||||
said.stamp = problems.stamp;
|
||||
said.messages.clear();
|
||||
}
|
||||
problems
|
||||
.messages
|
||||
.iter()
|
||||
.filter(|message| said.messages.insert((*message).clone()))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::state::{Document, Workspace};
|
||||
use lsp_types::Uri;
|
||||
use std::str::FromStr;
|
||||
use vlog_linter::Severity;
|
||||
|
||||
fn config(text: &str) -> FileConfig {
|
||||
let mut file = lucisv_core::config::parse(text).expect("the config parses");
|
||||
file.source = Some(PathBuf::from("/rtl/lucisv.toml"));
|
||||
file
|
||||
}
|
||||
|
||||
fn names(settings: &ClientSettings, project: &ProjectLint, oracle: bool) -> Vec<&'static str> {
|
||||
super::super::enabled_rules(settings, project, oracle)
|
||||
.into_iter()
|
||||
.map(|rule| rule.name())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn editor(select: &[&str], ignore: &[&str]) -> ClientSettings {
|
||||
ClientSettings {
|
||||
lint_select: select.iter().map(|s| (*s).to_string()).collect(),
|
||||
lint_ignore: ignore.iter().map(|s| (*s).to_string()).collect(),
|
||||
..ClientSettings::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn project(select: &[&str], ignore: &[&str]) -> ProjectLint {
|
||||
ProjectLint {
|
||||
select: select.iter().map(|s| (*s).to_string()).collect(),
|
||||
ignore: ignore.iter().map(|s| (*s).to_string()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// §42.1's table: every combination of {toml select, editor select} ×
|
||||
/// {toml ignore, editor ignore}, against the ladder. The editor's list
|
||||
/// wins when it says anything, the project's is used when it does not,
|
||||
/// and the two keys are decided **independently** — the CLI's `pick`,
|
||||
/// applied twice.
|
||||
#[test]
|
||||
fn the_editor_outranks_the_project_key_by_key() {
|
||||
// Four rules stand in for the whole registry: two the project may
|
||||
// name and two the editor may, so a row's answer says which list was
|
||||
// consulted rather than which happened to be shorter.
|
||||
// (toml select, editor select, toml ignore, editor ignore, expected).
|
||||
type Row = (
|
||||
&'static [&'static str],
|
||||
&'static [&'static str],
|
||||
&'static [&'static str],
|
||||
&'static [&'static str],
|
||||
&'static [&'static str],
|
||||
);
|
||||
let rows: [Row; 8] = [
|
||||
// (toml select, editor select, toml ignore, editor ignore) => rules
|
||||
(&[], &[], &[], &[], &[]),
|
||||
(&["no-tabs"], &[], &[], &[], &["no-tabs"]),
|
||||
(&[], &["no-tabs"], &[], &[], &["no-tabs"]),
|
||||
(&["module-name-style"], &["no-tabs"], &[], &[], &["no-tabs"]),
|
||||
(&["no-tabs", "module-name-style"], &[], &["no-tabs"], &[], &["module-name-style"]),
|
||||
(&["no-tabs", "module-name-style"], &[], &[], &["no-tabs"], &["module-name-style"]),
|
||||
(
|
||||
&["no-tabs", "module-name-style"],
|
||||
&[],
|
||||
&["module-name-style"],
|
||||
&["no-tabs"],
|
||||
&["module-name-style"],
|
||||
),
|
||||
(
|
||||
&["module-name-style"],
|
||||
&["no-tabs", "module-name-style"],
|
||||
&["no-tabs"],
|
||||
&["module-name-style"],
|
||||
&["no-tabs"],
|
||||
),
|
||||
];
|
||||
for (toml_select, ed_select, toml_ignore, ed_ignore, want) in rows {
|
||||
let settings = editor(ed_select, ed_ignore);
|
||||
let from_file = project(toml_select, toml_ignore);
|
||||
let got = names(&settings, &from_file, false);
|
||||
if want.is_empty() {
|
||||
// The empty row is the base set, which is too long to spell.
|
||||
assert_eq!(
|
||||
got,
|
||||
super::super::default_rules().iter().map(|r| r.name()).collect::<Vec<_>>(),
|
||||
"neither list said anything, so the base set stands"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(
|
||||
got, want,
|
||||
"{toml_select:?} {ed_select:?} {toml_ignore:?} {ed_ignore:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A severity word stands for its whole class in the toml's lists exactly
|
||||
/// as it does in the editor's, and as `--select style` does.
|
||||
#[test]
|
||||
fn a_severity_word_works_in_the_projects_lists_too() {
|
||||
let styled = names(&ClientSettings::default(), &project(&["style"], &[]), true);
|
||||
assert!(!styled.is_empty());
|
||||
assert!(styled
|
||||
.iter()
|
||||
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
|
||||
== Severity::Style));
|
||||
|
||||
let quiet = names(&ClientSettings::default(), &project(&[], &["style"]), true);
|
||||
assert!(!quiet.is_empty());
|
||||
assert!(quiet
|
||||
.iter()
|
||||
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
|
||||
!= Severity::Style));
|
||||
}
|
||||
|
||||
/// A rung 3 or 4 switch is the editor's alone, and still applies over a
|
||||
/// selection the project made.
|
||||
#[test]
|
||||
fn the_editor_only_rungs_still_apply_over_a_project_selection() {
|
||||
let mut settings = ClientSettings::default();
|
||||
settings.lint_severity.insert(Severity::Style, false);
|
||||
let from_file = project(&["no-tabs", "wire-reg-mixup"], &[]);
|
||||
assert_eq!(
|
||||
names(&settings, &from_file, false),
|
||||
vec!["wire-reg-mixup"],
|
||||
"the class switch removes the project's style rule"
|
||||
);
|
||||
|
||||
settings.lint_rules.insert("no-tabs".to_string(), true);
|
||||
assert_eq!(
|
||||
names(&settings, &from_file, false),
|
||||
vec!["no-tabs", "wire-reg-mixup"],
|
||||
"and the per-rule word puts it back"
|
||||
);
|
||||
}
|
||||
|
||||
/// A name the registry does not know is dropped and reported — the run
|
||||
/// `lucisv check` would have failed keeps going here with what was
|
||||
/// understood.
|
||||
#[test]
|
||||
fn an_unknown_name_in_the_projects_list_is_dropped_and_said() {
|
||||
let (from_file, problems) =
|
||||
ProjectLint::read(&config("[lint]\nselect = [\"no-tab\", \"no-tabs\"]\n"));
|
||||
assert_eq!(from_file.select, vec!["no-tabs"]);
|
||||
assert_eq!(problems, vec!["/rtl/lucisv.toml: [lint] select: unknown rule: no-tab"]);
|
||||
assert_eq!(names(&ClientSettings::default(), &from_file, false), vec!["no-tabs"]);
|
||||
|
||||
// Every name unknown leaves the list empty, which is the base set —
|
||||
// the safe direction: some rules rather than none.
|
||||
let (none, problems) = ProjectLint::read(&config("[lint]\nselect = [\"nope\"]\n"));
|
||||
assert!(none.select.is_empty());
|
||||
assert_eq!(problems.len(), 1);
|
||||
assert_eq!(
|
||||
names(&ClientSettings::default(), &none, false),
|
||||
super::super::default_rules().iter().map(|r| r.name()).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
/// §42.2: a `[lint.<rule>]` entry the registry refuses is reported once,
|
||||
/// however many lint passes run, and the buffer keeps being linted.
|
||||
#[test]
|
||||
fn a_rejected_option_is_said_once_and_the_lint_still_runs() {
|
||||
let dir = std::env::temp_dir()
|
||||
.join(format!("lucisv_lint_project_{}_rejected", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
std::fs::write(dir.join("lucisv.toml"), "[lint.line-length]\nlength = \"wide\"\n")
|
||||
.expect("write config");
|
||||
let path = dir.join("m.sv");
|
||||
let text = "module m;\n\twire a;\nendmodule\n";
|
||||
std::fs::write(&path, text).expect("write source");
|
||||
|
||||
let uri = Uri::from_str(&format!("file://{}", path.display())).expect("uri");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
let mut log = ProblemLog::default();
|
||||
|
||||
let mut said = Vec::new();
|
||||
for _ in 0..3 {
|
||||
let doc: &Document = ws.document(&uri).expect("open");
|
||||
let run = super::super::LintRun::for_document(&ws, doc);
|
||||
// The lint still runs: the tab is still a finding.
|
||||
assert!(
|
||||
super::super::violations_in(doc, &run).iter().any(|v| v.rule == "no-tabs"),
|
||||
"the buffer is still linted with the entry dropped"
|
||||
);
|
||||
said.extend(log.unsaid(run.config_problems()));
|
||||
}
|
||||
assert_eq!(said.len(), 1, "said once across three passes: {said:#?}");
|
||||
let expected = format!("{}:2: rule `line-length` ", dir.join("lucisv.toml").display());
|
||||
assert!(said[0].starts_with(&expected), "the wording `lucisv check` prints: {}", said[0]);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// An edited config gets a fresh hearing: the memo is keyed by the file's
|
||||
/// lint content, so the same mistake made again after a change is said
|
||||
/// again.
|
||||
#[test]
|
||||
fn an_edited_config_re_arms_the_report() {
|
||||
let first = config("[lint.line-length]\nlength = \"wide\"\n");
|
||||
let problems = ConfigProblems::new(&first, vec!["/rtl/lucisv.toml:2: bad".to_string()]);
|
||||
let mut log = ProblemLog::default();
|
||||
assert_eq!(log.unsaid(&problems).len(), 1);
|
||||
assert!(log.unsaid(&problems).is_empty(), "and not twice");
|
||||
|
||||
// Same message, different file content: the user has been editing.
|
||||
let edited = config("# a comment\n[lint.line-length]\nlength = \"wide\"\n");
|
||||
let again = ConfigProblems::new(&edited, vec!["/rtl/lucisv.toml:3: bad".to_string()]);
|
||||
assert_eq!(log.unsaid(&again).len(), 1, "a changed config is heard again");
|
||||
|
||||
// A buffer with no config file has nothing to report.
|
||||
let nowhere = ConfigProblems::new(&FileConfig::default(), vec!["never".to_string()]);
|
||||
assert!(log.unsaid(&nowhere).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -7,11 +7,18 @@
|
||||
//! buffer's own line index when there is one, and otherwise through
|
||||
//! `Workspace::file_view`, which reads a closed file at most once per
|
||||
//! generation of it rather than once per question about it.
|
||||
//!
|
||||
//! One span never needs that read at all: a **file-scope declaration**'s own
|
||||
//! name, whose client-side range the index recorded when the file was scanned
|
||||
//! ([`vlog_semantic::DeclPositions`]). [`definition_location`] is that path,
|
||||
//! and it is what `textDocument/definition` and `workspace/symbol` answer
|
||||
//! from — see `docs/features/lazy-code-action/README.md`.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_types::Location;
|
||||
use lsp_types::{Location, Position, Range};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{Def, Utf16Range};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::state::Workspace;
|
||||
@@ -27,6 +34,40 @@ pub fn location(ws: &Workspace, path: &Path, span: TextRange) -> Option<Location
|
||||
Some(Location { uri, range: Positions::new(&view.text, &view.lines).range(span) })
|
||||
}
|
||||
|
||||
/// Where an **indexed** declaration is written — its name's own range.
|
||||
///
|
||||
/// The index converted that range to client positions while it was scanning
|
||||
/// the file ([`vlog_semantic::DeclLines::positions`]), so pointing an editor
|
||||
/// at a module nobody has open is a map lookup rather than a file read: the
|
||||
/// same eight numbers, computed once at index time instead of once per
|
||||
/// question. Only **file-scope** declarations carry them; a member (a port, a
|
||||
/// parameter, a class field) records none and falls through to
|
||||
/// [`location`]'s read, which is the whole reason this is a separate function
|
||||
/// rather than a change inside that one.
|
||||
///
|
||||
/// **An open buffer keeps the read.** Its text may have moved since it was
|
||||
/// indexed, and every other answer about that buffer is computed against the
|
||||
/// text it holds now; answering this one from the index instead would make
|
||||
/// go-to-definition disagree with the document symbols beside it.
|
||||
pub fn definition_location(ws: &Workspace, path: &Path, def: &Def) -> Option<Location> {
|
||||
if ws.document_for_path(path).is_none() {
|
||||
if let Some(recorded) = def.lines.positions {
|
||||
return Some(Location { uri: path_to_uri(path)?, range: range(recorded.name) });
|
||||
}
|
||||
}
|
||||
location(ws, path, def.name_span)
|
||||
}
|
||||
|
||||
/// An index-recorded range as the protocol's own — the same four numbers,
|
||||
/// both already counted in UTF-16 code units by the file's own
|
||||
/// `LineIndex::utf16_position`, which is the converter `Positions` uses too.
|
||||
fn range(recorded: Utf16Range) -> Range {
|
||||
Range {
|
||||
start: Position { line: recorded.start.line, character: recorded.start.character },
|
||||
end: Position { line: recorded.end.line, character: recorded.end.character },
|
||||
}
|
||||
}
|
||||
|
||||
/// The 1-based line a byte offset falls on, for hover text that names a file
|
||||
/// and a line rather than jumping to it.
|
||||
///
|
||||
@@ -49,3 +90,197 @@ pub fn line_number(ws: &Workspace, path: &Path, offset: u32) -> Option<u32> {
|
||||
pub fn display_name(path: &Path) -> String {
|
||||
path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A scratch workspace root. Removed on drop.
|
||||
struct Tree {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl Tree {
|
||||
fn new(name: &str) -> Tree {
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("lucisv_server_locate_{}_{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("temp dir");
|
||||
Tree { path }
|
||||
}
|
||||
|
||||
/// Write a file as **bytes**, so a test can put a BOM or CRLF in one.
|
||||
fn write(&self, rel: &str, text: &str) -> PathBuf {
|
||||
let path = self.path.join(rel);
|
||||
fs::write(&path, text.as_bytes()).expect("write");
|
||||
path
|
||||
}
|
||||
|
||||
/// An indexed workspace over everything written so far.
|
||||
fn indexed(&self) -> Workspace {
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![self.path.clone()]);
|
||||
ws
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
/// The one declaration of `name` in the index, and the file it is in.
|
||||
fn only_def<'w>(ws: &'w Workspace, name: &str) -> (&'w Def, &'w Path) {
|
||||
let index = ws.index();
|
||||
let [def] = index.units(name) else { panic!("exactly one `{name}`") };
|
||||
(def, index.path(def.file).expect("a path"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_scope_definition_is_located_without_reading_its_file() {
|
||||
let tree = Tree::new("no_read");
|
||||
tree.write("sub.sv", "module sub (\n input logic clk\n);\nendmodule\n");
|
||||
let ws = tree.indexed();
|
||||
let (def, path) = only_def(&ws, "sub");
|
||||
|
||||
let indexed = definition_location(&ws, path, def).expect("a location");
|
||||
assert!(ws.held_views().is_empty(), "no file was read: {:?}", ws.held_views());
|
||||
|
||||
// Only now, so the comparison cannot be what filled the cache.
|
||||
let read = location(&ws, path, def.name_span).expect("a location");
|
||||
assert_eq!(indexed, read);
|
||||
assert_eq!(ws.held_views().len(), 1, "the file-read path really does read one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_two_paths_agree_over_multi_byte_astral_crlf_and_a_bom() {
|
||||
// Everything that has ever made a UTF-16 conversion disagree, in one
|
||||
// file: a BOM at offset 0, CRLF line endings, a two-byte character, a
|
||||
// three-byte one, and an astral character that is *two* UTF-16 code
|
||||
// units on its own.
|
||||
let tree = Tree::new("encodings");
|
||||
tree.write(
|
||||
"wide.sv",
|
||||
"\u{feff}// é ✓ 𝛼𝛽 — a comment\r\n\
|
||||
// 𝟘𝟙𝟚 more\r\n\
|
||||
module wide (\r\n input logic clk\r\n);\r\nendmodule\r\n",
|
||||
);
|
||||
let ws = tree.indexed();
|
||||
let (def, path) = only_def(&ws, "wide");
|
||||
|
||||
let indexed = definition_location(&ws, path, def).expect("a location");
|
||||
assert!(ws.held_views().is_empty(), "still no read");
|
||||
let read = location(&ws, path, def.name_span).expect("a location");
|
||||
assert_eq!(indexed, read, "the index-only range must be the file-read one");
|
||||
// And it really is the name, not the line: `module ` is seven UTF-16
|
||||
// units into line 2 (0-based), whatever the lines above it hold.
|
||||
assert_eq!(indexed.range.start.line, 2);
|
||||
assert_eq!(indexed.range.start.character, 7);
|
||||
assert_eq!(indexed.range.end.character, 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_still_answers_from_the_buffer() {
|
||||
// The index saw the file on disk; the buffer has since gained a line
|
||||
// above the declaration, and has not been re-indexed. An indexed span
|
||||
// is stale either way — the byte offset is the disk file's — and what
|
||||
// this pins is that the *conversion* is unchanged by this round: the
|
||||
// buffer's own line index, exactly as before, so go-to-definition and
|
||||
// the document symbols beside it still agree with each other.
|
||||
let tree = Tree::new("open_buffer");
|
||||
let path = tree.write("sub.sv", "module sub;\nendmodule\n");
|
||||
let mut ws = tree.indexed();
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri, "// typed since\nmodule sub;\nendmodule\n".to_string());
|
||||
|
||||
let (def, path) = only_def(&ws, "sub");
|
||||
let located = definition_location(&ws, path, def).expect("a location");
|
||||
assert_eq!(
|
||||
located,
|
||||
location(&ws, path, def.name_span).expect("a location"),
|
||||
"an open buffer takes the file-read path, index positions or not"
|
||||
);
|
||||
assert_eq!(located.range.start.line, 0, "byte 7 of the buffer, not of the index's file");
|
||||
assert!(ws.held_views().is_empty(), "an open buffer is never viewed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_keeps_the_file_read_path() {
|
||||
// Members carry no `DeclPositions` — see `DeclLines` — so the fallback
|
||||
// is not decoration: it is the only answer for a port.
|
||||
let tree = Tree::new("member");
|
||||
tree.write("sub.sv", "module sub (\n input logic clk\n);\nendmodule\n");
|
||||
let ws = tree.indexed();
|
||||
let index = ws.index();
|
||||
let [port] = index.member("sub", "clk") else { panic!("one `clk`") };
|
||||
assert!(port.lines.positions.is_none(), "a member records no client positions");
|
||||
let path = index.path(port.file).expect("a path");
|
||||
assert_eq!(
|
||||
definition_location(&ws, path, port),
|
||||
location(&ws, path, port.name_span),
|
||||
"and the fallback answers exactly what it always did"
|
||||
);
|
||||
assert_eq!(ws.held_views().len(), 1, "which cost the read");
|
||||
}
|
||||
|
||||
/// `LUCISV_PERF_CORPUS=/path/to/project cargo test --release -p lucisv_server --bin lucisv-server locate::tests::defining -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement over a corpus this repository does not ship — see docs/perf/README.md"]
|
||||
fn defining_over_a_real_project() {
|
||||
// TODO §37.3's own number, beside the code it measures rather than in
|
||||
// `perf.rs` — the precedent `perf::mean`'s `pub(crate)` exists for.
|
||||
// Two columns over the same corpus and the same targets: converting an
|
||||
// indexed span by reading its file, and reading it off the index.
|
||||
// **Read-only** — the corpus is opened, never written.
|
||||
let Ok(root) = std::env::var("LUCISV_PERF_CORPUS") else {
|
||||
eprintln!("LUCISV_PERF_CORPUS is unset — nothing to measure");
|
||||
return;
|
||||
};
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(crate::settings::ClientSettings {
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
..Default::default()
|
||||
});
|
||||
let started = std::time::Instant::now();
|
||||
ws.open_whole_workspace(vec![PathBuf::from(&root)]);
|
||||
let scan = started.elapsed();
|
||||
|
||||
// The targets: modules the corpus instantiates somewhere, whose single
|
||||
// declaration the index can name — what an F12 on an instantiation
|
||||
// lands on, and each in a different file.
|
||||
let names: Vec<String> =
|
||||
ws.index().instantiations().map(|(name, _)| name.to_string()).collect();
|
||||
let targets: Vec<(PathBuf, vlog_semantic::Def)> = names
|
||||
.iter()
|
||||
.filter_map(|name| {
|
||||
let path = vlog_refactor::module_definition(ws.index(), name).ok()?;
|
||||
let [def] = ws.index().units(name) else { return None };
|
||||
def.lines.positions.is_some().then(|| (path.to_path_buf(), def.clone()))
|
||||
})
|
||||
.take(200)
|
||||
.collect();
|
||||
|
||||
let indexed = crate::perf::mean(5, || {
|
||||
for (path, def) in &targets {
|
||||
std::hint::black_box(definition_location(&ws, path, def));
|
||||
}
|
||||
});
|
||||
let read = crate::perf::mean(5, || {
|
||||
for (path, def) in &targets {
|
||||
std::hint::black_box(location(&ws, path, def.name_span));
|
||||
}
|
||||
});
|
||||
let each = targets.len().max(1) as u32;
|
||||
eprintln!(
|
||||
"definition over {} indexed files of {root} (scan {scan:?}), {} targets:\n \
|
||||
index-only {indexed:?}, file-read {read:?} — {:?} vs {:?} per definition",
|
||||
ws.index().files().len(),
|
||||
targets.len(),
|
||||
indexed / each,
|
||||
read / each,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -126,6 +126,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
configuration: configuration_support(¶ms),
|
||||
token_server_cancel: token_server_cancel_support(¶ms),
|
||||
hierarchy_view,
|
||||
code_action_resolve: code_action_resolve_support(¶ms),
|
||||
};
|
||||
connection.initialize_finish(id, initialize_value(ranges_formatting)?)?;
|
||||
|
||||
@@ -261,8 +262,13 @@ fn capabilities() -> ServerCapabilities {
|
||||
CodeActionKind::new(ports::REFACTOR_PORTS),
|
||||
]),
|
||||
work_done_progress_options: WorkDoneProgressOptions::default(),
|
||||
// Every action is returned complete; there is nothing to resolve.
|
||||
resolve_provider: None,
|
||||
// The quick fixes are complete when they are offered; the port
|
||||
// refactorings are not, for a client that can ask
|
||||
// (`docs/features/lazy-code-action/README.md`). Advertised
|
||||
// unconditionally because the server can always answer a resolve
|
||||
// — including for an action that already carries its edit, which
|
||||
// it hands straight back.
|
||||
resolve_provider: Some(true),
|
||||
})),
|
||||
// The port refactorings. `lucisv.addPort` needs a declaration typed by
|
||||
// the user, which no code action can carry, and a Vim user has no
|
||||
@@ -499,6 +505,24 @@ fn snippet_support(params: &InitializeParams) -> bool {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the client can fetch a code action's `edit` after the fact —
|
||||
/// `textDocument.codeAction.resolveSupport.properties` listing `"edit"`.
|
||||
///
|
||||
/// The property list is the capability: a client that can resolve `title`
|
||||
/// alone cannot be offered an action without its edit, so nothing short of
|
||||
/// `"edit"` counts. A client that says nothing gets every action complete, as
|
||||
/// every client did before this was read
|
||||
/// (`docs/features/lazy-code-action/README.md`).
|
||||
fn code_action_resolve_support(params: &InitializeParams) -> bool {
|
||||
params
|
||||
.capabilities
|
||||
.text_document
|
||||
.as_ref()
|
||||
.and_then(|text_document| text_document.code_action.as_ref())
|
||||
.and_then(|code_action| code_action.resolve_support.as_ref())
|
||||
.is_some_and(|resolve| resolve.properties.iter().any(|property| property == "edit"))
|
||||
}
|
||||
|
||||
/// Whether the client applies a `workspace/applyEdit` request.
|
||||
///
|
||||
/// A client that did not say so gets a command's edit back as the request
|
||||
@@ -1148,6 +1172,46 @@ mod tests {
|
||||
assert!(kinds.contains(&CodeActionKind::QUICKFIX));
|
||||
assert!(kinds.contains(&CodeActionKind::new(code_action::FIX_ALL)));
|
||||
assert!(kinds.contains(&CodeActionKind::new(ports::REFACTOR_PORTS)));
|
||||
assert_eq!(
|
||||
options.resolve_provider,
|
||||
Some(true),
|
||||
"the port refactorings are offered without their edits to a client that can ask"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_action_resolve_support_is_read_from_the_clients_own_capabilities() {
|
||||
use lsp_types::{
|
||||
ClientCapabilities, CodeActionCapabilityResolveSupport, CodeActionClientCapabilities,
|
||||
TextDocumentClientCapabilities,
|
||||
};
|
||||
assert!(
|
||||
!code_action_resolve_support(&InitializeParams::default()),
|
||||
"silence means the whole edit up front"
|
||||
);
|
||||
|
||||
let saying = |properties: &[&str]| InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
text_document: Some(TextDocumentClientCapabilities {
|
||||
code_action: Some(CodeActionClientCapabilities {
|
||||
resolve_support: Some(CodeActionCapabilityResolveSupport {
|
||||
properties: properties.iter().map(|p| p.to_string()).collect(),
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert!(code_action_resolve_support(&saying(&["edit"])));
|
||||
assert!(code_action_resolve_support(&saying(&["documentation", "edit"])));
|
||||
assert!(
|
||||
!code_action_resolve_support(&saying(&["documentation"])),
|
||||
"resolving anything but the edit is no use to us"
|
||||
);
|
||||
assert!(!code_action_resolve_support(&saying(&[])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -7,7 +7,7 @@ use vlog_semantic::{Def, Definition, ExternalTarget, Semantics, Symbol, SymbolId
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::includes;
|
||||
use crate::locate::location;
|
||||
use crate::locate::{definition_location, location};
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
@@ -60,7 +60,9 @@ pub fn definition(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<Location> {
|
||||
.iter()
|
||||
.filter_map(|def| {
|
||||
let path = ws.index().path(def.file)?;
|
||||
location(ws, path, def.name_span)
|
||||
// A file-scope declaration's range is already in the index, so
|
||||
// the jump costs no read of the file it lands in.
|
||||
definition_location(ws, path, def)
|
||||
})
|
||||
.collect(),
|
||||
None => Vec::new(),
|
||||
@@ -691,6 +693,36 @@ mod tests {
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cross_file_definition_reads_no_file() {
|
||||
// The jump above, asked again for what it *costs*: the target module's
|
||||
// range is in the index (`DeclPositions`), so nothing opens `sub.sv`.
|
||||
// Pinned through the view cache, which is where a read would land.
|
||||
let dir = temp_dir("no_read");
|
||||
let sub = dir.join("sub.sv");
|
||||
fs::write(&sub, "module sub (input clk);\nendmodule\n").expect("write");
|
||||
let top_path = dir.join("top.sv");
|
||||
let top_text = "module top;\n sub u_sub (.clk(1'b0));\nendmodule\n";
|
||||
fs::write(&top_path, top_text).expect("write");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let uri = path_to_uri(&top_path).expect("uri");
|
||||
ws.set_document(uri.clone(), top_text.to_string());
|
||||
|
||||
let locations = definition(&ws, &uri, at(top_text, "sub u_sub"));
|
||||
assert_eq!(locations.len(), 1);
|
||||
assert_eq!(locations[0].range.start.character, 7, "and it is still the right answer");
|
||||
assert!(ws.held_views().is_empty(), "no file was read: {:?}", ws.held_views());
|
||||
|
||||
// `workspace/symbol` answers the same way, over the same index.
|
||||
let hits = crate::symbols::workspace_symbols(&ws, "sub");
|
||||
assert!(hits.iter().any(|hit| hit.name == "sub"), "{hits:#?}");
|
||||
assert!(ws.held_views().is_empty(), "nor did the symbol search");
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ambiguous_workspace_name_returns_every_location() {
|
||||
let dir = temp_dir("ambig");
|
||||
|
||||
@@ -1022,6 +1022,14 @@ fn a_code_action_at_an_instantiation_before_and_after() {
|
||||
let after = mean(20, || {
|
||||
black_box(crate::ports::code_actions(&ws, &uri, black_box(offset)));
|
||||
});
|
||||
// TODO §37.1's column: the *offer* a client that can resolve receives,
|
||||
// which reads the buffer and — at an instantiation — one more file,
|
||||
// whatever the fan-out is. The edit is computed by `resolve`, which is the
|
||||
// `after` column above, once, when the user clicks.
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
let offer = mean(20, || {
|
||||
black_box(crate::ports::offers(&ws, &uri, black_box(position), black_box(offset)));
|
||||
});
|
||||
let read = mean(3, || {
|
||||
black_box(ws.sources());
|
||||
});
|
||||
@@ -1035,9 +1043,10 @@ fn a_code_action_at_an_instantiation_before_and_after() {
|
||||
});
|
||||
// A measurement of an answer that was not given is worthless.
|
||||
assert_eq!(crate::ports::code_actions(&ws, &uri, offset).len(), 1);
|
||||
assert_eq!(crate::ports::offers(&ws, &uri, position, offset).len(), 1);
|
||||
eprintln!(
|
||||
"codeAction on a port of a module instantiated in 3 of {} files ({lines} lines each): \
|
||||
whole workspace {before:?}, fan-out {after:?} \
|
||||
whole workspace {before:?}, fan-out {after:?}, offer {offer:?} \
|
||||
(`sources()` alone: {read:?}; prepareRename, untouched: {prepare:?})",
|
||||
ws.index().files().len()
|
||||
);
|
||||
|
||||
@@ -12,6 +12,13 @@
|
||||
//! and `lucisv.propagatePorts` take a position and exist for the same reason a
|
||||
//! Vim user has no lightbulb: a command works everywhere a keybinding does.
|
||||
//! See `docs/features/refactor-ports/README.md`.
|
||||
//!
|
||||
//! **Two shapes of code action.** A client that can resolve is *offered*
|
||||
//! actions with no edit ([`offers`]) and asks for the edit when the user picks
|
||||
//! one ([`resolve`]); a client that cannot gets the edit up front
|
||||
//! ([`code_actions`]). The offer reads one or two files whatever the module's
|
||||
//! fan-out is, which is the whole point — see
|
||||
//! `docs/features/lazy-code-action/README.md`.
|
||||
|
||||
// See `rename.rs` for why this is a `WorkspaceEdit`'s problem and not ours.
|
||||
#![allow(clippy::mutable_key_type)]
|
||||
@@ -22,6 +29,7 @@ use std::path::{Path, PathBuf};
|
||||
use lsp_types::{
|
||||
CodeAction, CodeActionKind, CodeActionOrCommand, Position, TextEdit, Uri, WorkspaceEdit,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use vlog_parser::LineIndex;
|
||||
use vlog_refactor::{ModuleRef, RefactorEdit};
|
||||
@@ -48,6 +56,12 @@ pub fn commands() -> Vec<String> {
|
||||
|
||||
/// The port actions available at a position, each carrying its own computed
|
||||
/// edit — nothing to resolve, and nothing offered that would be refused.
|
||||
///
|
||||
/// What a client without `codeAction/resolve` gets, and what [`resolve`]
|
||||
/// re-runs to answer one that has. It reads the module's whole fan-out
|
||||
/// ([`Workspace::module_sources`]), which is ~1.4 ms per instantiating file:
|
||||
/// fine once, when the user has clicked, and not fine on every cursor move,
|
||||
/// which is why [`offers`] exists.
|
||||
pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrCommand> {
|
||||
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
||||
let Some(path) = doc.path.clone() else { return Vec::new() };
|
||||
@@ -76,6 +90,183 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrC
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What a lazily-offered action carries in place of its edit: enough to ask
|
||||
/// the same question again when the user picks it.
|
||||
///
|
||||
/// The position rather than the offset, because that is what the client
|
||||
/// speaks and what the buffer it will be re-read against is indexed by.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Offer {
|
||||
uri: Uri,
|
||||
position: Position,
|
||||
title: String,
|
||||
}
|
||||
|
||||
/// The sentence a resolve that finds nothing answers with. Not a silent empty
|
||||
/// edit: an action that has stopped applying is news, and applying nothing
|
||||
/// while saying nothing is how a user comes to distrust the lightbulb.
|
||||
const GONE: &str = "the action is no longer available.";
|
||||
/// A resolve of something this server never offered.
|
||||
const NOT_OURS: &str = "this code action carries no lucisv port refactoring to resolve.";
|
||||
|
||||
/// The port actions available at a position, **without their edits** — the
|
||||
/// offer a client that can `codeAction/resolve` is sent.
|
||||
///
|
||||
/// The question "is there an action here at all" is answered over the buffer
|
||||
/// itself plus, for a cursor on an instantiation, the instantiated module's
|
||||
/// own declaration ([`offer_sources`]) — one or two files, whatever the
|
||||
/// module's fan-out is. The edits those two files produce are thrown away;
|
||||
/// [`resolve`] computes the real one over the whole fan-out when the user
|
||||
/// clicks.
|
||||
///
|
||||
/// **The count in the title comes from the index**, since the fan-out has not
|
||||
/// been read: [`instances_of`] counts every *instance* the index has seen of
|
||||
/// the module, so `sub u1(), u2();` counts two. The eager title counts the
|
||||
/// instances the plan really rewrites, which is the same number except where
|
||||
/// the index cannot know — an unsaved buffer's new instantiation, a
|
||||
/// file-scope instantiation site (which records no edge), an instance
|
||||
/// connecting with `.*`. The two are therefore matched on the part of the
|
||||
/// title *before* that count; see [`key`].
|
||||
pub fn offers(
|
||||
ws: &Workspace,
|
||||
uri: &Uri,
|
||||
position: Position,
|
||||
offset: u32,
|
||||
) -> Vec<CodeActionOrCommand> {
|
||||
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
||||
let Some(path) = doc.path.clone() else { return Vec::new() };
|
||||
let modules = vlog_refactor::port_action_modules(&doc.text, offset);
|
||||
// A name the workspace declares twice is a refusal the engine makes over
|
||||
// the fan-out, where it can see both declarations. The offer cannot, so it
|
||||
// asks the index the same question rather than offering an action that
|
||||
// resolve would then decline.
|
||||
if modules.is_empty() || modules.iter().any(|name| declared_twice(ws, name)) {
|
||||
return Vec::new();
|
||||
}
|
||||
let sources = offer_sources(ws, &path, &doc.text, &modules);
|
||||
vlog_refactor::port_actions(&sources, &path, offset)
|
||||
.into_iter()
|
||||
.map(|action| {
|
||||
let title = counted(ws, action.title, &modules);
|
||||
let data =
|
||||
serde_json::to_value(Offer { uri: uri.clone(), position, title: title.clone() })
|
||||
.ok();
|
||||
CodeActionOrCommand::CodeAction(CodeAction {
|
||||
title,
|
||||
kind: Some(CodeActionKind::new(REFACTOR_PORTS)),
|
||||
data,
|
||||
..Default::default()
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The files an [`offers`] call reads: the buffer the request names, and the
|
||||
/// declaration of every module an instantiation under the cursor names.
|
||||
///
|
||||
/// The second is the same two steps `inlay.rs`'s `Plans::read` takes — the
|
||||
/// index says which file declares the module, and that one file is read —
|
||||
/// and it is what lets the engine answer "this instantiation is missing
|
||||
/// ports" without any file that *instantiates* the module. A cursor on a port
|
||||
/// declaration names its own module, whose declaring file is the buffer
|
||||
/// itself, so that case reads nothing at all.
|
||||
///
|
||||
/// `pub(crate)` for the test that pins exactly this set.
|
||||
pub(crate) fn offer_sources(
|
||||
ws: &Workspace,
|
||||
path: &Path,
|
||||
text: &str,
|
||||
modules: &[String],
|
||||
) -> Vec<(PathBuf, String)> {
|
||||
let mut sources = vec![(path.to_path_buf(), text.to_string())];
|
||||
for name in modules {
|
||||
let Ok(declared_in) = vlog_refactor::module_definition(ws.index(), name) else { continue };
|
||||
if sources.iter().any(|(held, _)| held == declared_in) {
|
||||
continue;
|
||||
}
|
||||
if let Some(text) = ws.text_of(declared_in) {
|
||||
sources.push((declared_in.to_path_buf(), text));
|
||||
}
|
||||
}
|
||||
sources
|
||||
}
|
||||
|
||||
/// The edit for one offered action, computed now that the user has picked it.
|
||||
///
|
||||
/// Today's eager answer at the offer's own position, narrowed to the action
|
||||
/// whose title the client is holding. An action already carrying its edit is
|
||||
/// returned untouched — a client may resolve anything it likes, and the quick
|
||||
/// fixes in `code_action.rs` are complete when they are offered.
|
||||
pub fn resolve(ws: &Workspace, action: CodeAction) -> Result<CodeAction, String> {
|
||||
if action.edit.is_some() {
|
||||
return Ok(action);
|
||||
}
|
||||
let offer: Offer = action
|
||||
.data
|
||||
.clone()
|
||||
.and_then(|data| serde_json::from_value(data).ok())
|
||||
.ok_or_else(|| NOT_OURS.to_string())?;
|
||||
// A `codeAction/resolve` carries a `CodeAction`, not a `textDocument`, so
|
||||
// the large-file fast path's gate (which reads the URI out of the params)
|
||||
// never sees this request. A buffer that has grown past the threshold
|
||||
// since it was offered an action is refused here instead: the fast path's
|
||||
// whole contract is that a large buffer is never parsed, and one stale
|
||||
// lightbulb is not a reason to break it.
|
||||
let doc = ws.document(&offer.uri).filter(|doc| !doc.large).ok_or_else(|| GONE.to_string())?;
|
||||
let offset = doc.positions().offset(offer.position);
|
||||
code_actions(ws, &offer.uri, offset)
|
||||
.into_iter()
|
||||
.find_map(|offered| match offered {
|
||||
CodeActionOrCommand::CodeAction(found) if key(&found.title) == key(&offer.title) => {
|
||||
Some(found)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.map(|mut resolved| {
|
||||
resolved.data = action.data;
|
||||
resolved
|
||||
})
|
||||
.ok_or_else(|| GONE.to_string())
|
||||
}
|
||||
|
||||
/// An action's identity: its title without the count phrase the offer and the
|
||||
/// eager path can honestly disagree about.
|
||||
///
|
||||
/// `"lucisv: remove port `rst` (updates 3 instantiations)"` keys as
|
||||
/// ``"lucisv: remove port `rst`"``; a title with no such suffix
|
||||
/// (`"lucisv: connect 1 missing port"`, whose count is the cursor's own file's
|
||||
/// and therefore exact) keys as itself. An escaped identifier cannot contain a
|
||||
/// space, so `" ("` never occurs inside a port name.
|
||||
fn key(title: &str) -> &str {
|
||||
title.strip_suffix(')').and_then(|head| head.rsplit_once(" (")).map_or(title, |(head, _)| head)
|
||||
}
|
||||
|
||||
/// An offered title with the workspace's own instantiation count in it,
|
||||
/// replacing the one the offer's one or two files could see.
|
||||
fn counted(ws: &Workspace, title: String, modules: &[String]) -> String {
|
||||
let Some(head) = title.strip_suffix(')').and_then(|head| head.rsplit_once(" (")) else {
|
||||
return title;
|
||||
};
|
||||
let sites = modules.iter().map(|name| instances_of(ws, name)).sum();
|
||||
format!("{} ({})", head.0, vlog_refactor::sites_phrase(sites))
|
||||
}
|
||||
|
||||
/// Every instance of `name` the index has seen. An edge is one written
|
||||
/// statement, so its instances are counted rather than the edges themselves —
|
||||
/// `sub u1 (), u2 ();` is two connection lists to rewrite and the title says
|
||||
/// two.
|
||||
fn instances_of(ws: &Workspace, name: &str) -> usize {
|
||||
ws.index().instantiations_of(name).iter().map(|edge| edge.instances.len()).sum()
|
||||
}
|
||||
|
||||
/// Whether the index holds more than one declaration of `name` a module
|
||||
/// reference could mean — the ambiguity `vlog_refactor::module_definition`
|
||||
/// refuses to guess between, and the one the engine refuses a refactoring
|
||||
/// over.
|
||||
fn declared_twice(ws: &Workspace, name: &str) -> bool {
|
||||
ws.index().units(name).iter().filter(|def| def.kind.is_instantiable()).count() > 1
|
||||
}
|
||||
|
||||
/// Run one of the three commands, or say why it cannot run.
|
||||
///
|
||||
/// The answer is the `WorkspaceEdit` to apply plus the engine's warnings. How
|
||||
@@ -809,6 +1000,322 @@ mod tests {
|
||||
assert_eq!(edits_for(action.edit.as_ref().expect("edit"), &new_uri).len(), 2);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the lazy offer and its resolve (TODO §37.1)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The offer a client that can resolve receives at `offset`.
|
||||
fn offered(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrCommand> {
|
||||
let position = ws.document(uri).expect("an open document").positions().position(offset);
|
||||
offers(ws, uri, position, offset)
|
||||
}
|
||||
|
||||
/// One action's title and kind — what a lightbulb draws, and all an offer
|
||||
/// promises.
|
||||
fn menu(actions: &[CodeActionOrCommand]) -> Vec<(String, Option<String>)> {
|
||||
actions
|
||||
.iter()
|
||||
.map(|action| {
|
||||
let CodeActionOrCommand::CodeAction(action) = action else {
|
||||
return ("a command".to_string(), None);
|
||||
};
|
||||
(action.title.clone(), action.kind.as_ref().map(|k| k.as_str().to_string()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The one action an offer holds.
|
||||
fn only(actions: &[CodeActionOrCommand]) -> &CodeAction {
|
||||
let [CodeActionOrCommand::CodeAction(action)] = actions else {
|
||||
panic!("exactly one action, got {actions:#?}")
|
||||
};
|
||||
action
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lazy_offer_names_exactly_what_the_eager_one_names() {
|
||||
let tree = Tree::new("lazy_menu");
|
||||
let mut ws = crowded(&tree, 40);
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
let lazy = offered(&ws, &sub_uri, offset);
|
||||
assert_eq!(menu(&lazy), menu(&code_actions(&ws, &sub_uri, offset)));
|
||||
assert_eq!(
|
||||
menu(&lazy)[0].0,
|
||||
"lucisv: remove port `rst` (updates 3 instantiations)",
|
||||
"counted from the index, and it agrees with the plan's own count"
|
||||
);
|
||||
let action = only(&lazy);
|
||||
assert!(action.edit.is_none(), "an offer carries no edit");
|
||||
assert!(action.data.is_some(), "it carries what resolve needs instead");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offer_reads_the_buffer_and_at_most_the_declaring_file() {
|
||||
// The pin `the_files_a_code_action_reads_are_the_modules_own_fan_out`
|
||||
// is to the eager path; this is the same question asked of the offer,
|
||||
// through the set it hands the engine. Neither the 40 noise files nor
|
||||
// — and this is the point — any of the three instantiating tops.
|
||||
let tree = Tree::new("lazy_reads");
|
||||
let mut ws = crowded(&tree, 40);
|
||||
let sub = tree.path.join("sub.sv");
|
||||
let sub_uri = path_to_uri(&sub).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
assert_eq!(ws.sources().len(), 44, "the whole workspace");
|
||||
assert_eq!(ws.module_sources(&sub, &["sub".to_string()]).len(), 4, "the eager fan-out");
|
||||
|
||||
// A cursor on a port declaration: the module is the buffer's own.
|
||||
let read = offer_sources(&ws, &sub, SUB, &["sub".to_string()]);
|
||||
let names: Vec<String> = read
|
||||
.iter()
|
||||
.map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string())
|
||||
.collect();
|
||||
assert_eq!(names, ["sub.sv"], "one file, and it is the buffer itself");
|
||||
|
||||
// A cursor on an instantiation: the buffer, plus the one file the
|
||||
// index says declares the module.
|
||||
let top = tree.path.join("top0.sv");
|
||||
let top_text = std::fs::read_to_string(&top).expect("read");
|
||||
let read = offer_sources(&ws, &top, &top_text, &["sub".to_string()]);
|
||||
let mut names: Vec<String> = read
|
||||
.iter()
|
||||
.map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string())
|
||||
.collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["sub.sv", "top0.sv"], "and never top1, top2 or a noise file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resolved_action_carries_the_eager_edit_at_a_port_declaration() {
|
||||
let tree = Tree::new("resolve_port");
|
||||
let mut ws = crowded(&tree, 40);
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
let resolved = resolve(&ws, only(&offered(&ws, &sub_uri, offset)).clone()).expect("edit");
|
||||
let eager = only(&code_actions(&ws, &sub_uri, offset)).clone();
|
||||
assert_eq!(resolved.title, eager.title);
|
||||
assert_eq!(resolved.kind, eager.kind);
|
||||
assert_eq!(resolved.edit, eager.edit, "the same WorkspaceEdit, to the byte");
|
||||
assert!(resolved.data.is_some(), "the offer's own data survives the round trip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resolved_action_carries_the_eager_edit_at_an_instantiation() {
|
||||
// The other cursor shape: an instantiation missing a connection, where
|
||||
// the offer has to read the *instantiated* module's declaration to
|
||||
// know there is anything to offer at all.
|
||||
let tree = Tree::new("resolve_inst");
|
||||
let text = "module top;\n logic clk, rst;\n sub u_sub (.clk(clk));\nendmodule\n";
|
||||
tree.write("sub.sv", SUB);
|
||||
let top = tree.write("top.sv", text);
|
||||
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(), text.to_string());
|
||||
let offset = text.find("sub u_sub").expect("the instantiation") as u32;
|
||||
|
||||
let lazy = offered(&ws, &uri, offset);
|
||||
assert_eq!(menu(&lazy), menu(&code_actions(&ws, &uri, offset)));
|
||||
assert_eq!(menu(&lazy)[0].0, "lucisv: connect 1 missing port");
|
||||
assert!(only(&lazy).edit.is_none());
|
||||
|
||||
let resolved = resolve(&ws, only(&lazy).clone()).expect("edit");
|
||||
assert_eq!(resolved.edit, only(&code_actions(&ws, &uri, offset)).edit);
|
||||
assert_eq!(
|
||||
edits_for(resolved.edit.as_ref().expect("edit"), &uri)[0].new_text,
|
||||
", .rst(rst)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_resolved_edit_sees_an_unsaved_buffer_the_offer_could_not_count() {
|
||||
// The pin `an_unsaved_buffer_contributes_the_instantiation_the_index
|
||||
// _has_not_seen` moved to the lazy path. The offer counts instances
|
||||
// from the index, which has not seen the unsaved one, so the title
|
||||
// says three; the *edit* is computed over the fan-out plus every open
|
||||
// buffer, so it disconnects all four. Exactness lives in the edit,
|
||||
// which is what the user actually applies.
|
||||
let tree = Tree::new("lazy_unsaved");
|
||||
let mut ws = crowded(&tree, 20);
|
||||
let extra = tree.path.join("noise0.sv");
|
||||
let extra_uri = path_to_uri(&extra).expect("uri");
|
||||
let typed = "module noise0;\n logic c, r;\n sub u_new (.clk(c), .rst(r));\nendmodule\n";
|
||||
ws.set_document(extra_uri.clone(), typed.to_string());
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
let lazy = offered(&ws, &sub_uri, offset);
|
||||
assert_eq!(
|
||||
menu(&lazy)[0].0,
|
||||
"lucisv: remove port `rst` (updates 3 instantiations)",
|
||||
"the index has not seen the fourth"
|
||||
);
|
||||
let resolved = resolve(&ws, only(&lazy).clone()).expect("edit");
|
||||
assert_eq!(
|
||||
resolved.title, "lucisv: remove port `rst` (updates 4 instantiations)",
|
||||
"and the resolve says so"
|
||||
);
|
||||
let edit = resolved.edit.as_ref().expect("an edit");
|
||||
assert_eq!(edits_for(edit, &extra_uri).len(), 2, "the unsaved buffer is disconnected too");
|
||||
assert_eq!(resolved.edit, only(&code_actions(&ws, &sub_uri, offset)).edit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resolve_of_an_action_the_buffer_no_longer_carries_is_refused() {
|
||||
let tree = Tree::new("lazy_stale");
|
||||
let mut ws = crowded(&tree, 10);
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
let offered = only(&offered(&ws, &sub_uri, offset)).clone();
|
||||
|
||||
// The user kept typing: the port the lightbulb was about is gone.
|
||||
ws.set_document(sub_uri.clone(), "module sub (\n input logic clk\n);\nendmodule\n".into());
|
||||
let message = resolve(&ws, offered.clone()).expect_err("nothing to resolve");
|
||||
assert_eq!(message, GONE);
|
||||
|
||||
// And a document that has been closed altogether says the same.
|
||||
ws.close_document(&sub_uri);
|
||||
assert_eq!(resolve(&ws, offered).expect_err("no buffer"), GONE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resolve_against_a_buffer_on_the_large_file_fast_path_is_refused() {
|
||||
// `codeAction/resolve`'s params are a `CodeAction`, so the fast path's
|
||||
// own gate — which reads a `textDocument` out of the params — never
|
||||
// sees this request. A buffer that grew past the threshold since it
|
||||
// was offered an action must still not be parsed.
|
||||
let tree = Tree::new("lazy_large");
|
||||
let mut ws = crowded(&tree, 5);
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
let offered = only(&offered(&ws, &sub_uri, offset)).clone();
|
||||
|
||||
let _ = ws.set_client_settings(crate::settings::ClientSettings {
|
||||
large_file_threshold: 8,
|
||||
..Default::default()
|
||||
});
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
assert!(ws.document(&sub_uri).expect("open").large, "the buffer is on the fast path");
|
||||
assert_eq!(resolve(&ws, offered).expect_err("not parsed"), GONE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resolve_of_something_this_server_never_offered_says_so() {
|
||||
let tree = Tree::new("lazy_foreign");
|
||||
let (ws, uri, _) = opened(&tree);
|
||||
let bare = CodeAction { title: "someone else's action".to_string(), ..Default::default() };
|
||||
assert_eq!(resolve(&ws, bare.clone()).expect_err("no data"), NOT_OURS);
|
||||
|
||||
// Data that is not ours either — a shape `serde` cannot read as an
|
||||
// offer. Refused, not guessed at.
|
||||
let junk = CodeAction { data: Some(serde_json::json!({"nope": 1})), ..bare.clone() };
|
||||
assert_eq!(resolve(&ws, junk).expect_err("junk data"), NOT_OURS);
|
||||
|
||||
// An action that already carries its edit — every quick fix in
|
||||
// `code_action.rs`, and the port actions a non-resolving client is
|
||||
// sent — comes straight back, because there is nothing to add to it.
|
||||
let complete =
|
||||
CodeAction { edit: Some(WorkspaceEdit::new(HashMap::from([(uri, vec![])]))), ..bare };
|
||||
assert_eq!(resolve(&ws, complete.clone()).expect("nothing to do"), complete);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_the_workspace_declares_twice_is_not_offered_either() {
|
||||
// The eager path refuses because both declaring files are in the set
|
||||
// it reads (`a_module_declared_twice_is_refused_through_the_subset_as
|
||||
// _well`). The offer reads neither, so it asks the index the same
|
||||
// question — otherwise it would offer an action resolve then refuses.
|
||||
let tree = Tree::new("lazy_ambiguous");
|
||||
let mut ws = crowded(&tree, 10);
|
||||
tree.write("clone.sv", SUB);
|
||||
ws.rebuild_index();
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
assert!(offered(&ws, &sub_uri, offset).is_empty());
|
||||
assert!(code_actions(&ws, &sub_uri, offset).is_empty(), "as the eager path does");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_title_keys_on_everything_but_its_count() {
|
||||
assert_eq!(
|
||||
key("lucisv: remove port `rst` (updates 3 instantiations)"),
|
||||
key("lucisv: remove port `rst` (no instantiation in scope)")
|
||||
);
|
||||
assert_eq!(key("lucisv: connect 1 missing port"), "lucisv: connect 1 missing port");
|
||||
assert_ne!(
|
||||
key("lucisv: remove port `rst` (updates 1 instantiation)"),
|
||||
key("lucisv: remove port `clk` (updates 1 instantiation)")
|
||||
);
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server --bin lucisv-server ports::tests::the_offer_is_flat -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn the_offer_is_flat_where_the_eager_answer_grows() {
|
||||
// `performance_take2.md` §6a measured the eager answer growing with
|
||||
// the module's fan-out — ~1.4 ms per instantiating file plus a ~13 ms
|
||||
// floor, 185 ms at 128 files, to offer *zero* actions. The offer reads
|
||||
// one file (a cursor on a port declaration) or two (a cursor on an
|
||||
// instantiation), so its column should be flat. Beside the code it
|
||||
// measures rather than in `perf.rs`, which is what `perf::mean` is
|
||||
// `pub(crate)` for.
|
||||
for instantiators in [3usize, 40, 128] {
|
||||
let tree = Tree::new(&format!("perf_offer_{instantiators}"));
|
||||
tree.write("sub.sv", SUB);
|
||||
for n in 0..instantiators {
|
||||
tree.write(
|
||||
&format!("top{n:03}.sv"),
|
||||
&format!(
|
||||
"module top{n:03};\n logic c, r;\n \
|
||||
sub u_sub (.clk(c), .rst(r));\nendmodule\n"
|
||||
),
|
||||
);
|
||||
}
|
||||
for n in 0..200 {
|
||||
tree.write(
|
||||
&format!("noise{n:03}.sv"),
|
||||
&format!(
|
||||
"module noise{n:03};\n logic a;\n wire b;\n \
|
||||
assign b = a;\nendmodule\n"
|
||||
),
|
||||
);
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
|
||||
for (what, file, needle, skip) in [
|
||||
("a port declaration", "sub.sv", "input logic rst", 12u32),
|
||||
("an instantiation ", "top000.sv", "sub u_sub", 0),
|
||||
] {
|
||||
let path = tree.path.join(file);
|
||||
let text = std::fs::read_to_string(&path).expect("read");
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), text.clone());
|
||||
let offset = text.find(needle).expect("the cursor") as u32 + skip;
|
||||
let eager = crate::perf::mean(5, || {
|
||||
std::hint::black_box(code_actions(&ws, &uri, offset));
|
||||
});
|
||||
let offer = crate::perf::mean(20, || {
|
||||
std::hint::black_box(offered(&ws, &uri, offset));
|
||||
});
|
||||
eprintln!(
|
||||
" fan-out {instantiators:>3}, cursor on {what}: eager {eager:?}, \
|
||||
offer {offer:?} ({} actions)",
|
||||
offered(&ws, &uri, offset).len()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_command_is_declined() {
|
||||
let tree = Tree::new("unknown");
|
||||
|
||||
@@ -117,6 +117,7 @@ fn items(list: &[Item], offset: u32, out: &mut Vec<TextRange>) {
|
||||
ItemKind::Class(class) => items(&class.items, offset, out),
|
||||
ItemKind::Package { items: inner, .. } => items(inner, offset, out),
|
||||
ItemKind::GenerateRegion { items: inner, .. } => items(inner, offset, out),
|
||||
ItemKind::GenBlock(b) => items(&b.items, offset, out),
|
||||
ItemKind::GenIf(gen_if) => gen_if_blocks(gen_if, offset, out),
|
||||
ItemKind::GenFor(gen_for) => gen_block(&gen_for.body, offset, out),
|
||||
ItemKind::GenCase(gen_case) => {
|
||||
|
||||
@@ -94,10 +94,44 @@ impl Server {
|
||||
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))
|
||||
// `lucisv.lint.*` and the buffer's `[lint]` table 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/`).
|
||||
let run = crate::lint::LintRun::for_document(&self.workspace, doc);
|
||||
self.report_config_problems(&run);
|
||||
diagnostics::all_in(doc, &run)
|
||||
}
|
||||
|
||||
/// Say, once, what this buffer's `lucisv.toml` asked for and did not get.
|
||||
///
|
||||
/// Once per (config file, entry), not once per pass: this runs on every
|
||||
/// keystroke and every index rebuild. The words are the ones `lucisv
|
||||
/// check` fails the run with, `<file>:<line>: <message>`, so one mistake
|
||||
/// reads the same in CI and here — but nothing is fatal, the entry is
|
||||
/// dropped and the buffer is still linted with everything understood
|
||||
/// (§42.2). Logged, not shown: a typo in a checked-in config is not worth
|
||||
/// a popup on every editor in the project.
|
||||
fn report_config_problems(&self, run: &crate::lint::LintRun) {
|
||||
let problems = run.config_problems();
|
||||
if problems.is_empty() {
|
||||
return;
|
||||
}
|
||||
// The borrow is released before anything is sent: `notify` takes
|
||||
// `&self` and could otherwise reach a second borrow one day.
|
||||
let unsaid = match self.lint_config_problems.try_borrow_mut() {
|
||||
Ok(mut log) => log.unsaid(problems),
|
||||
Err(_) => return,
|
||||
};
|
||||
for message in unsaid {
|
||||
self.notify(
|
||||
LogMessage::METHOD,
|
||||
LogMessageParams {
|
||||
typ: MessageType::WARNING,
|
||||
message: format!("lucisv: {message}; ignored"),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Publish everything known about a buffer — parse errors and lint
|
||||
|
||||
@@ -14,22 +14,22 @@
|
||||
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,
|
||||
CodeActionRequest, CodeActionResolveRequest, 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,
|
||||
CodeAction, CodeActionKind, CodeActionParams, CodeLensParams, CompletionParams,
|
||||
DocumentDiagnosticParams, DocumentDiagnosticReportResult, DocumentHighlightParams,
|
||||
DocumentLinkParams, DocumentSymbolParams, DocumentSymbolResponse, ExecuteCommandParams,
|
||||
FoldingRangeParams, GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams,
|
||||
InlineCompletionParams, LinkedEditingRangeParams, Position, ReferenceParams, RenameFilesParams,
|
||||
RenameParams, SelectionRangeParams, SemanticTokens, SemanticTokensDeltaParams,
|
||||
SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeResult,
|
||||
@@ -45,7 +45,7 @@ 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,
|
||||
includes, inlay, inline, lens, linked, lint, nav, pairs, ports, rename, selection, signature,
|
||||
symbols, tokens, type_def, type_hierarchy,
|
||||
};
|
||||
|
||||
@@ -251,17 +251,34 @@ impl Server {
|
||||
// or from the built-in default.
|
||||
let tab_width =
|
||||
format::indent_width(doc.path.as_deref(), self.workspace.client_settings());
|
||||
let run = lint::LintRun::for_document(&self.workspace, doc);
|
||||
let mut actions =
|
||||
code_action::code_actions(&uri, doc, p.range, only.as_deref(), tab_width);
|
||||
code_action::code_actions(&run, &uri, doc, p.range, only.as_deref(), tab_width);
|
||||
// The port refactorings answer for the cursor, not for a range:
|
||||
// the request's start is where the user is.
|
||||
if code_action::wanted(only.as_deref(), &CodeActionKind::new(ports::REFACTOR_PORTS))
|
||||
{
|
||||
let offset = doc.positions().offset(p.range.start);
|
||||
actions.extend(ports::code_actions(&self.workspace, &uri, offset));
|
||||
// A client that can resolve is offered the actions without
|
||||
// their edits, which is what keeps a cursor resting on an
|
||||
// instantiation off the module's fan-out; one that cannot
|
||||
// gets the whole edit, exactly as before.
|
||||
actions.extend(match self.abilities.code_action_resolve {
|
||||
true => ports::offers(&self.workspace, &uri, p.range.start, offset),
|
||||
false => ports::code_actions(&self.workspace, &uri, offset),
|
||||
});
|
||||
}
|
||||
to_value(actions)
|
||||
}),
|
||||
// The edit for an action offered without one. An action that
|
||||
// already carries its edit comes straight back, so a client that
|
||||
// resolves everything it is offered is answered too.
|
||||
CodeActionResolveRequest::METHOD => decode(request).and_then(|action: CodeAction| {
|
||||
match ports::resolve(&self.workspace, action) {
|
||||
Ok(resolved) => to_value(resolved),
|
||||
Err(message) => Err(Failure::Request(message)),
|
||||
}
|
||||
}),
|
||||
// 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.
|
||||
|
||||
@@ -104,6 +104,13 @@ pub struct ClientAbilities {
|
||||
/// Whether the client hosts the custom lucisv hierarchy sidebar and wants
|
||||
/// a notification whenever the installed workspace index changes.
|
||||
pub hierarchy_view: bool,
|
||||
/// Whether the client can fetch a code action's `edit` through
|
||||
/// `codeAction/resolve` — `textDocument.codeAction.resolveSupport`
|
||||
/// listing `"edit"`. Only then are the port refactorings *offered* without
|
||||
/// their edits; a client that said nothing gets the whole edit up front,
|
||||
/// which is what every client got before this was read
|
||||
/// (`docs/features/lazy-code-action/README.md`).
|
||||
pub code_action_resolve: bool,
|
||||
}
|
||||
|
||||
/// Everything the server owns.
|
||||
@@ -114,6 +121,19 @@ pub struct Server {
|
||||
/// 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>,
|
||||
/// Which `[lint]` entries of which `lucisv.toml` have already been
|
||||
/// reported (§42.2). Interior-mutable because a lint pass runs behind
|
||||
/// `&self` — the pull models compute diagnostics inside a `map` over the
|
||||
/// open buffers — and the memo is the one thing a pass has to write.
|
||||
/// Nothing is called while it is borrowed.
|
||||
lint_config_problems: std::cell::RefCell<crate::lint::ProblemLog>,
|
||||
/// The unknown-rule-name lines already logged for the **editor's**
|
||||
/// `lucisv.lint.select`/`ignore` (§45.1), exactly as the last settings
|
||||
/// value produced them. A client that re-pushes the same section — VS Code
|
||||
/// does, whenever anything in it changes — says nothing again; a list the
|
||||
/// user edited re-arms every name that is new to it. The project file's
|
||||
/// twin memo is `lint_config_problems` above.
|
||||
said_lint_names: Vec<String>,
|
||||
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
|
||||
@@ -293,6 +313,8 @@ impl Server {
|
||||
connection,
|
||||
workspace: Workspace::default(),
|
||||
config_warnings: HashSet::new(),
|
||||
lint_config_problems: std::cell::RefCell::default(),
|
||||
said_lint_names: Vec::new(),
|
||||
abilities,
|
||||
watchers: None,
|
||||
registrations: 0,
|
||||
|
||||
@@ -25,7 +25,7 @@ use serde::de::DeserializeOwned;
|
||||
use super::batch::{widen_of, Widen};
|
||||
use super::client::ms;
|
||||
use super::Server;
|
||||
use crate::{file_ops, settings, sync, watch};
|
||||
use crate::{file_ops, lint, settings, sync, watch};
|
||||
|
||||
impl Server {
|
||||
/// Handle one notification, timing it when `--verbose` asked. A
|
||||
@@ -259,6 +259,38 @@ impl Server {
|
||||
},
|
||||
);
|
||||
}
|
||||
// A name in `lucisv.lint.select`/`ignore` the registry does not know is
|
||||
// dropped just as silently, and the same typo in a `lucisv.toml`'s
|
||||
// `[lint] select` has been said since §42. Said here too — but **once**
|
||||
// per (setting, name): unlike the options warnings above, which cost a
|
||||
// line each time the setting arrives, a client that re-pushes its whole
|
||||
// section on every keystroke must not repeat these. A list the user
|
||||
// edited re-arms whatever is new in it. See §2.9-29.
|
||||
for warning in unsaid(&settings.lint_name_warnings, &self.said_lint_names) {
|
||||
self.notify(
|
||||
LogMessage::METHOD,
|
||||
LogMessageParams {
|
||||
typ: MessageType::WARNING,
|
||||
message: format!("lucisv: {warning}"),
|
||||
},
|
||||
);
|
||||
}
|
||||
self.said_lint_names.clone_from(&settings.lint_name_warnings);
|
||||
// And the same for `lucisv.lint.waivers`: a file that is not there, or
|
||||
// a directive that does not parse, is dropped and said once — here,
|
||||
// where the setting arrives, rather than on every keystroke from the
|
||||
// lint pass that reads the files. Only the setting's own files are
|
||||
// checked; a `lucisv.toml`'s `[lint] waivers` is that file's problem
|
||||
// and `lucisv check` fails the run over it.
|
||||
for problem in waiver_problems(&settings, self.workspace.roots()) {
|
||||
self.notify(
|
||||
LogMessage::METHOD,
|
||||
LogMessageParams {
|
||||
typ: MessageType::WARNING,
|
||||
message: format!("lucisv: lucisv.lint.waivers: {problem}; ignored"),
|
||||
},
|
||||
);
|
||||
}
|
||||
// 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.
|
||||
@@ -322,3 +354,32 @@ fn closing_uri(notification: &Notification) -> Option<Uri> {
|
||||
fn folder_paths(folders: &[WorkspaceFolder]) -> Vec<std::path::PathBuf> {
|
||||
folders.iter().filter_map(|folder| crate::uri::uri_to_path(&folder.uri)).collect()
|
||||
}
|
||||
|
||||
/// What `lucisv.lint.waivers` names that could not be used: a file that is not
|
||||
/// there, or a directive that does not parse.
|
||||
///
|
||||
/// Read here rather than trusted, because a path is not something a settings
|
||||
/// parser can validate: only opening the file says whether it exists. The
|
||||
/// files are read again by the lint pass that actually applies them — a few
|
||||
/// small files beside a parse and an analysis — which keeps one reader for
|
||||
/// both and no cache to go stale when the user edits a waiver file.
|
||||
fn waiver_problems(
|
||||
settings: &settings::ClientSettings,
|
||||
roots: &[std::path::PathBuf],
|
||||
) -> Vec<String> {
|
||||
if settings.lint_waivers.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let paths = lint::waiver_paths(settings, roots, &lucisv_core::config::FileConfig::default());
|
||||
lint::external_waivers(&paths).1
|
||||
}
|
||||
|
||||
/// The lines of `warnings` that `said` does not already hold, in order.
|
||||
///
|
||||
/// The whole of §45.1's "once": the memo is the previous settings value's own
|
||||
/// warning list, so re-pushing a section says nothing and editing the list
|
||||
/// says exactly what is new in it. Both lists are a handful of entries at
|
||||
/// most — one per typo — so a scan is cheaper than a set.
|
||||
fn unsaid<'a>(warnings: &'a [String], said: &[String]) -> Vec<&'a String> {
|
||||
warnings.iter().filter(|w| !said.contains(w)).collect()
|
||||
}
|
||||
@@ -408,3 +408,95 @@ fn an_answer_to_a_request_the_server_never_tracked_is_silently_ignored() {
|
||||
session.answer(RequestId::from("never-sent".to_string()), serde_json::json!([{ "indent": 2 }]));
|
||||
assert_eq!(session.server.workspace.client_settings().indent, Some(4));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the editor's unknown rule name (TODO §45.1, docs/topo.md §2.9-29)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A `didChangeConfiguration` push with the given `lucisv.lint` section.
|
||||
fn push_lint(session: &mut Session, lint: Value) {
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "lint": lint } } }),
|
||||
);
|
||||
}
|
||||
|
||||
/// The unknown-rule lines the server logged since the last drain.
|
||||
fn unknown_rule_lines(session: &Session) -> Vec<String> {
|
||||
session
|
||||
.logged()
|
||||
.into_iter()
|
||||
.map(|(_, message)| message)
|
||||
.filter(|message| message.contains("unknown rule"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_rule_name_in_the_editors_select_is_logged_once() {
|
||||
let tree = Tree::new("unknownrule");
|
||||
tree.write("m.sv", "module m;\nendmodule\n");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
|
||||
push_lint(&mut session, serde_json::json!({ "select": ["no-tabs", "no-tab"] }));
|
||||
assert_eq!(
|
||||
unknown_rule_lines(&session),
|
||||
["lucisv: lucisv.lint.select: unknown rule: no-tab"],
|
||||
"said once, naming the list and the name"
|
||||
);
|
||||
|
||||
// Four diagnostics passes later it has not been said again: the pass runs
|
||||
// on every keystroke and the log is not a place to shout from.
|
||||
for _ in 0..4 {
|
||||
session.server.publish(&uri);
|
||||
}
|
||||
assert!(unknown_rule_lines(&session).is_empty(), "not repeated by a diagnostics pass");
|
||||
|
||||
// Nor by the same section arriving again, which is what VS Code sends
|
||||
// whenever anything at all in it changes.
|
||||
push_lint(&mut session, serde_json::json!({ "select": ["no-tabs", "no-tab"] }));
|
||||
assert!(unknown_rule_lines(&session).is_empty(), "not repeated by an identical push");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_list_re_arms_the_log() {
|
||||
let tree = Tree::new("unknownrulearm");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let _ = session.drain();
|
||||
|
||||
push_lint(&mut session, serde_json::json!({ "select": ["no-tab"] }));
|
||||
assert_eq!(unknown_rule_lines(&session).len(), 1);
|
||||
|
||||
// A second typo added to the list is new, and is said; the first is not.
|
||||
push_lint(&mut session, serde_json::json!({ "select": ["no-tab", "nope"] }));
|
||||
assert_eq!(
|
||||
unknown_rule_lines(&session),
|
||||
["lucisv: lucisv.lint.select: unknown rule: nope"],
|
||||
"only what is new in the list"
|
||||
);
|
||||
|
||||
// Cleared and re-typed: the memo is the previous value, so it is armed
|
||||
// again.
|
||||
push_lint(&mut session, serde_json::json!({ "select": [] }));
|
||||
assert!(unknown_rule_lines(&session).is_empty(), "an empty list has nothing to say");
|
||||
push_lint(&mut session, serde_json::json!({ "select": ["no-tab"] }));
|
||||
assert_eq!(unknown_rule_lines(&session).len(), 1, "re-armed by the change");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_select_emptied_by_the_dropping_falls_through_the_ladder_unchanged() {
|
||||
// §42's ladder: a `select` that named nothing the registry knows is an
|
||||
// empty `select`, which is no opinion at all — the project's list, then
|
||||
// the base set. The log line is the whole of what §45.1 changed.
|
||||
let tree = Tree::new("unknownruleladder");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let base = settings::lint_selection(session.server.workspace.client_settings());
|
||||
let _ = session.drain();
|
||||
|
||||
push_lint(&mut session, serde_json::json!({ "select": ["no-tab", "nope"] }));
|
||||
assert_eq!(unknown_rule_lines(&session).len(), 2, "both names said");
|
||||
let now = session.server.workspace.client_settings();
|
||||
assert!(now.lint_select.is_empty(), "the dropping left an empty select");
|
||||
assert_eq!(settings::lint_selection(now), base, "and the rule set is untouched");
|
||||
}
|
||||
@@ -202,6 +202,27 @@ pub struct ClientSettings {
|
||||
/// One line per refused `lucisv.lint.options` entry, ready for a
|
||||
/// `window/logMessage`. Empty for a settings push that was all valid.
|
||||
pub lint_option_warnings: Vec<String>,
|
||||
/// One line per name in `lucisv.lint.select` / `lucisv.lint.ignore` that
|
||||
/// the registry does not know, in the shape
|
||||
/// `lucisv.lint.select: unknown rule: <name>`.
|
||||
///
|
||||
/// Separate from [`ClientSettings::lint_option_warnings`] because the two
|
||||
/// are said differently: an options warning is raised every time the
|
||||
/// setting arrives, while an unknown name is said **once** per (setting,
|
||||
/// name) and re-armed only when the list changes — a client that re-pushes
|
||||
/// its whole section on every keystroke must not repeat it
|
||||
/// (`docs/features/small-items-4/README.md`).
|
||||
pub lint_name_warnings: Vec<String>,
|
||||
/// `lucisv.lint.waivers`: external waiver files, each absolute or relative
|
||||
/// to the first workspace root — the editor's spelling of
|
||||
/// `lucisv check --waiver-file` and of `waivers` under `[lint]` in a
|
||||
/// `lucisv.toml`. They **add** to whatever that table names.
|
||||
///
|
||||
/// The paths are taken as written and nothing is read here: whether a file
|
||||
/// exists and whether its directives parse is answered where the files are
|
||||
/// read (`lint::external_waivers`), and reported once through the log when
|
||||
/// this value arrives.
|
||||
pub lint_waivers: Vec<String>,
|
||||
}
|
||||
|
||||
/// The settings a client that said nothing is treated as having asked for.
|
||||
@@ -232,6 +253,8 @@ impl Default for ClientSettings {
|
||||
lint_rules: BTreeMap::new(),
|
||||
lint_options: RuleOptions::new(),
|
||||
lint_option_warnings: Vec::new(),
|
||||
lint_name_warnings: Vec::new(),
|
||||
lint_waivers: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -246,8 +269,14 @@ fn every_class_on() -> BTreeMap<Severity, bool> {
|
||||
///
|
||||
/// 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>, RuleOptions);
|
||||
pub type LintSelection = (
|
||||
Vec<String>,
|
||||
Vec<String>,
|
||||
BTreeMap<Severity, bool>,
|
||||
BTreeMap<String, bool>,
|
||||
RuleOptions,
|
||||
Vec<String>,
|
||||
);
|
||||
|
||||
/// The lint settings of `settings`, as one comparable value.
|
||||
///
|
||||
@@ -262,6 +291,9 @@ pub fn lint_selection(settings: &ClientSettings) -> LintSelection {
|
||||
settings.lint_severity.clone(),
|
||||
settings.lint_rules.clone(),
|
||||
settings.lint_options.clone(),
|
||||
// A waiver file added or dropped changes which findings survive, so it
|
||||
// republishes for exactly the reason a changed option does.
|
||||
settings.lint_waivers.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -293,6 +325,11 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
||||
// And `lucisv.lint.select` / `lucisv.lint.ignore` the same way again.
|
||||
let lint = lucisv.get("lint");
|
||||
let (options, warnings) = rule_options(lint.and_then(|l| l.get("options")));
|
||||
// The names the registry did not know, collected as the two lists are
|
||||
// filtered so the user hears about a typo instead of losing a rule to it.
|
||||
let mut names = Vec::new();
|
||||
let lint_select = rules(lint.and_then(|l| l.get("select")), "select", &mut names);
|
||||
let lint_ignore = rules(lint.and_then(|l| l.get("ignore")), "ignore", &mut names);
|
||||
ClientSettings {
|
||||
line_length: bounded(lucisv.get("lineLength"), LINE_LENGTH_RANGE),
|
||||
indent: bounded(lucisv.get("indent"), INDENT_RANGE),
|
||||
@@ -334,25 +371,44 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
||||
// prevent.
|
||||
large_file_threshold: count(large_file.and_then(|f| f.get("threshold")))
|
||||
.unwrap_or(DEFAULT_LARGE_FILE_THRESHOLD),
|
||||
lint_select: rules(lint.and_then(|l| l.get("select"))),
|
||||
lint_ignore: rules(lint.and_then(|l| l.get("ignore"))),
|
||||
lint_select,
|
||||
lint_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"))),
|
||||
lint_options: options,
|
||||
lint_option_warnings: warnings,
|
||||
lint_name_warnings: names,
|
||||
// Paths, not rule names: nothing to validate against the registry, and
|
||||
// a path that names nothing is reported when the file is read.
|
||||
lint_waivers: strings(lint.and_then(|l| l.get("waivers"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The rule names in a settings array, dropping every one that names neither a
|
||||
/// rule nor a severity class.
|
||||
/// rule nor a severity class and describing each drop in `warnings`.
|
||||
///
|
||||
/// 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::rules_named(name).is_some()).collect()
|
||||
/// The drop itself is 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,
|
||||
/// so a name the registry does not know leaves the rule where it was. Silence
|
||||
/// about it was not the rule, only the state of things — `[lint] select` in a
|
||||
/// `lucisv.toml` has said the same mistake out loud since §42, and this is the
|
||||
/// editor's half of that (`docs/topo.md` §2.9-29).
|
||||
///
|
||||
/// `setting` is `select` or `ignore`, so the line names the list the user
|
||||
/// typed in.
|
||||
fn rules(value: Option<&Value>, setting: &str, warnings: &mut Vec<String>) -> Vec<String> {
|
||||
strings(value)
|
||||
.into_iter()
|
||||
.filter(|name| {
|
||||
let known = vlog_linter::rules_named(name).is_some();
|
||||
if !known {
|
||||
warnings.push(format!("lucisv.lint.{setting}: unknown rule: {name}"));
|
||||
}
|
||||
known
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The three class master switches, each `true` unless a client turned it off.
|
||||
@@ -878,6 +934,39 @@ mod tests {
|
||||
}}}));
|
||||
assert_eq!(found.lint_select, vec!["style", "no-tabs"]);
|
||||
assert_eq!(found.lint_ignore, vec!["warning"]);
|
||||
// And the one name that is neither is described, not just dropped.
|
||||
assert_eq!(found.lint_name_warnings, vec!["lucisv.lint.select: unknown rule: nope"]);
|
||||
}
|
||||
|
||||
/// TODO §45.1: a name the registry does not know is still dropped — the
|
||||
/// rule stays where it was — and now says so, once per name, naming the
|
||||
/// list the user typed it in.
|
||||
#[test]
|
||||
fn an_unknown_rule_name_is_described_for_each_list_it_appears_in() {
|
||||
let found = settings(json!({"lucisv": {"lint": {
|
||||
"select": ["no-tabs", "nope", "also-nope"],
|
||||
"ignore": ["nope"],
|
||||
}}}));
|
||||
assert_eq!(found.lint_select, vec!["no-tabs"]);
|
||||
assert!(found.lint_ignore.is_empty());
|
||||
assert_eq!(
|
||||
found.lint_name_warnings,
|
||||
vec![
|
||||
"lucisv.lint.select: unknown rule: nope",
|
||||
"lucisv.lint.select: unknown rule: also-nope",
|
||||
"lucisv.lint.ignore: unknown rule: nope",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_lists_of_known_names_describe_nothing() {
|
||||
let found = settings(json!({"lucisv": {"lint": {
|
||||
"select": ["no-tabs", "error"],
|
||||
"ignore": ["unused-signal"],
|
||||
}}}));
|
||||
assert!(found.lint_name_warnings.is_empty(), "{:?}", found.lint_name_warnings);
|
||||
assert!(settings(json!({"lucisv": {}})).lint_name_warnings.is_empty());
|
||||
}
|
||||
|
||||
/// What the server compares two settings pushes by, to decide whether the
|
||||
@@ -957,6 +1046,30 @@ mod tests {
|
||||
assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE);
|
||||
}
|
||||
|
||||
/// `lucisv.lint.waivers` is a list of paths, taken as written: this module
|
||||
/// has no filesystem to check them against, and whether a file exists or
|
||||
/// parses is answered where it is read. TODO §39.
|
||||
#[test]
|
||||
fn the_waivers_setting_is_a_list_of_paths_taken_as_written() {
|
||||
let found = settings(json!({"lucisv": {"lint": {
|
||||
"waivers": ["project.waiver", "/abs/other.waiver", 7, null]
|
||||
}}}));
|
||||
assert_eq!(found.lint_waivers, vec!["project.waiver", "/abs/other.waiver"]);
|
||||
assert!(settings(json!({"lucisv": {"lint": {}}})).lint_waivers.is_empty());
|
||||
// Wrong-typed altogether: the whole list is "no opinion", never a
|
||||
// guess, exactly as `select` and `exclude` are.
|
||||
for bad in [json!("project.waiver"), json!(3), json!(null), json!({"a": 1})] {
|
||||
assert!(
|
||||
settings(json!({"lucisv": {"lint": {"waivers": bad}}})).lint_waivers.is_empty(),
|
||||
"waivers {bad} must be ignored"
|
||||
);
|
||||
}
|
||||
// A changed list republishes, for the reason a changed option does.
|
||||
let one = settings(json!({"lucisv": {"lint": {"waivers": ["a.waiver"]}}}));
|
||||
let two = settings(json!({"lucisv": {"lint": {"waivers": ["b.waiver"]}}}));
|
||||
assert_ne!(lint_selection(&one), lint_selection(&two));
|
||||
}
|
||||
|
||||
/// A settings payload with no options object is exactly today's
|
||||
/// behaviour: every rule reads its own default.
|
||||
#[test]
|
||||
|
||||
@@ -625,6 +625,15 @@ impl Workspace {
|
||||
!self.roots.is_empty()
|
||||
}
|
||||
|
||||
/// The workspace folders, in the order the client named them.
|
||||
///
|
||||
/// The first one is what a relative path in a setting is resolved against,
|
||||
/// which is what [`Workspace::filelist_path`] does inline and what
|
||||
/// `lucisv.lint.waivers` needs too.
|
||||
pub fn roots(&self) -> &[PathBuf] {
|
||||
&self.roots
|
||||
}
|
||||
|
||||
/// The directories the folder scope walks: every directory a buffer has
|
||||
/// been opened from this session, each raised `lucisv.index.scopeDepth`
|
||||
/// levels. **Empty when the folder scope is not the active rung** — a
|
||||
@@ -999,11 +1008,12 @@ impl Workspace {
|
||||
self.docs.values().filter_map(|doc| doc.path.as_deref()).collect();
|
||||
let mut skipped = 0usize;
|
||||
let mut texts: Vec<(PathBuf, String)> = Vec::new();
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
// The walk of the *added* directories alone, by the same rung-3 rules
|
||||
// `folder_files` follows — the whole scope is the union of these walks,
|
||||
// so the files this one finds beyond what is already indexed are
|
||||
// exactly the ones the widen owes.
|
||||
for path in self.widened_files(added) {
|
||||
for path in self.widened_files(added, &mut |w| warnings.push(w)) {
|
||||
// Already indexed: by another scope directory this walk overlaps,
|
||||
// or by an earlier scan. Re-reading it is the cost this path
|
||||
// exists to avoid.
|
||||
@@ -1064,9 +1074,9 @@ impl Workspace {
|
||||
// `+incdir+`. Carried from the graph in hand rather than assumed
|
||||
// empty, so folding a widen in never *changes* the search path.
|
||||
incdirs: self.includes.incdirs().to_vec(),
|
||||
// Warnings come from resolving the scope, and a widen resolves no
|
||||
// filelist: rung 1 is not a scope an open buffer can widen.
|
||||
warnings: Vec::new(),
|
||||
// A widen resolves no filelist — rung 1 is not a scope an open
|
||||
// buffer can widen — so the only warnings here are the walk's own.
|
||||
warnings,
|
||||
at: 0,
|
||||
staged: Vec::new(),
|
||||
staged_at: Vec::new(),
|
||||
@@ -1079,11 +1089,11 @@ impl Workspace {
|
||||
/// The files the directories a widen added bring into scope, by the same
|
||||
/// rules [`Workspace::folder_files`] applies to the whole scope — including
|
||||
/// the rootless-at-depth-0 flat read.
|
||||
fn widened_files(&self, added: &[PathBuf]) -> Vec<PathBuf> {
|
||||
fn widened_files(&self, added: &[PathBuf], warn: &mut dyn FnMut(String)) -> Vec<PathBuf> {
|
||||
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
|
||||
return sibling_files(added);
|
||||
}
|
||||
self.walked_files(added)
|
||||
self.walked_files(added, warn)
|
||||
}
|
||||
|
||||
/// Index the next file of `scan`, reporting whether there was one.
|
||||
@@ -1797,6 +1807,17 @@ impl Workspace {
|
||||
Some(view)
|
||||
}
|
||||
|
||||
/// The files the view cache is holding, newest first.
|
||||
///
|
||||
/// Test-only, and it exists for one question: whether an answer read a
|
||||
/// file at all. A `Location` computed from the index alone must leave this
|
||||
/// empty, which is the whole point of `locate::definition_location` — see
|
||||
/// `docs/features/lazy-code-action/README.md`.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn held_views(&self) -> Vec<PathBuf> {
|
||||
self.views.borrow().iter().map(|view| view.path.clone()).collect()
|
||||
}
|
||||
|
||||
/// The held view for `path`, moved to the front so the bounds below drop
|
||||
/// whatever has gone longest unused.
|
||||
fn cached_view(&self, path: &Path) -> Option<Rc<FileView>> {
|
||||
@@ -1847,16 +1868,21 @@ impl Workspace {
|
||||
/// none, so an `` `include`` there resolves against the including file's
|
||||
/// own directory alone (`docs/features/include-nav/README.md`).
|
||||
fn source_files(&self) -> Scope {
|
||||
// The walk's own warnings join the scope's, so an unreadable directory
|
||||
// reaches the output channel by the road a filelist's problems already
|
||||
// travel — said once per scan and never per keystroke.
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
let Some(path) = self.filelist_path() else {
|
||||
return Scope { files: self.default_files(), ..Default::default() };
|
||||
let files = self.default_files(&mut |w| warnings.push(w));
|
||||
return Scope { files, warnings, ..Default::default() };
|
||||
};
|
||||
match lucisv_core::filelist::read(&path) {
|
||||
Ok(list) => Scope { files: list.files, incdirs: list.incdirs, warnings: list.warnings },
|
||||
Err(problem) => Scope {
|
||||
files: self.default_files(),
|
||||
incdirs: Vec::new(),
|
||||
warnings: vec![format!("{problem} — indexing the workspace instead")],
|
||||
},
|
||||
Err(problem) => {
|
||||
let files = self.default_files(&mut |w| warnings.push(w));
|
||||
warnings.insert(0, format!("{problem} — indexing the workspace instead"));
|
||||
Scope { files, incdirs: Vec::new(), warnings }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1883,11 +1909,11 @@ impl Workspace {
|
||||
|
||||
/// Rungs 2 and 3 of the ladder: the whole-workspace walk when the client
|
||||
/// asked for it, else the folder scope.
|
||||
fn default_files(&self) -> Vec<PathBuf> {
|
||||
fn default_files(&self, warn: &mut dyn FnMut(String)) -> Vec<PathBuf> {
|
||||
if self.walks_the_workspace() {
|
||||
return self.walked_files(&self.roots);
|
||||
return self.walked_files(&self.roots, warn);
|
||||
}
|
||||
self.folder_files()
|
||||
self.folder_files(warn)
|
||||
}
|
||||
|
||||
/// Rung 3: the folder scope — [`Workspace::scope_dirs`], walked with every
|
||||
@@ -1899,12 +1925,12 @@ impl Workspace {
|
||||
/// case, where descending a tree the user never named would be a surprise
|
||||
/// — and the moment the user raises `scopeDepth` they have named one, so
|
||||
/// the walk is what they asked for.
|
||||
fn folder_files(&self) -> Vec<PathBuf> {
|
||||
fn folder_files(&self, warn: &mut dyn FnMut(String)) -> Vec<PathBuf> {
|
||||
let dirs = self.scope_dirs();
|
||||
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
|
||||
return sibling_files(&dirs);
|
||||
}
|
||||
self.walked_files(&dirs)
|
||||
self.walked_files(&dirs, warn)
|
||||
}
|
||||
|
||||
/// Every source file under `dirs`, found by the CLI's own walk: the same
|
||||
@@ -1918,7 +1944,7 @@ impl Workspace {
|
||||
/// written in a root's `.gitignore` does not apply to a rung-3 walk that
|
||||
/// starts below it. The `exclude` patterns are matched against whole
|
||||
/// paths and so behave identically either way.
|
||||
fn walked_files(&self, dirs: &[PathBuf]) -> Vec<PathBuf> {
|
||||
fn walked_files(&self, dirs: &[PathBuf], warn: &mut dyn FnMut(String)) -> Vec<PathBuf> {
|
||||
let mut discovery = Discovery::new(true);
|
||||
let mut out = Vec::new();
|
||||
for root in dirs {
|
||||
@@ -1938,8 +1964,9 @@ impl Workspace {
|
||||
exclude.extend(self.client.exclude.iter().cloned());
|
||||
// `.gitignore` is always honoured: it is the CLI's default, and an
|
||||
// editor has no `--no-gitignore` to type. An unreadable directory
|
||||
// is simply not indexed, exactly as before this walk was shared.
|
||||
let _ = collect_files(input, &exclude, true, &mut out);
|
||||
// is skipped and said — the warning rides out on the scope's own
|
||||
// warnings, which `server/notification.rs` logs once per scan.
|
||||
let _ = collect_files(input, &exclude, true, &mut out, &mut |w| warn(w.to_string()));
|
||||
}
|
||||
out.sort();
|
||||
out.dedup();
|
||||
@@ -2710,6 +2737,33 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A workspace whose tree links back into itself. Before the walk kept a
|
||||
/// visited set (`docs/features/walk-cycles/README.md`) this scan never
|
||||
/// finished — the editor's index simply never came up. Each directory is
|
||||
/// entered once now, so each package is registered exactly once: a second
|
||||
/// registration would make the name *ambiguous*, and `indexed` only
|
||||
/// counts a name found exactly once.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_cyclic_workspace_is_scanned_once_and_finishes() {
|
||||
let tree = Tree::new("cycle");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/sub/b.sv", "b");
|
||||
// `rtl/self` is `rtl` itself; `rtl/sub/up` is `rtl` from one level
|
||||
// down. Either one alone runs until the OS refuses a path.
|
||||
std::os::unix::fs::symlink("../rtl", tree.path.join("rtl/self")).expect("symlink");
|
||||
std::os::unix::fs::symlink("..", tree.path.join("rtl/sub/up")).expect("symlink");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["a", "b"]), ["a", "b"]);
|
||||
assert_eq!(
|
||||
ws.walked_files(from_ref(&tree.path), &mut |_| {}).len(),
|
||||
2,
|
||||
"two files, once each"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_change_that_changes_nothing_asks_for_no_rescan() {
|
||||
// Every no-op shape a client can send. Each must leave the root set
|
||||
@@ -3317,6 +3371,35 @@ mod tests {
|
||||
assert!(warnings[0].contains("indexing the workspace instead"), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_unreadable_directory_is_said_once_per_scan_and_the_rest_is_indexed() {
|
||||
// TODO §45.2: the walk's warnings ride out on the scope's own
|
||||
// warnings, which the server logs once per scan. Before the channel
|
||||
// existed the walk returned an error the index simply dropped, so a
|
||||
// permission-denied directory cost every file after it silently.
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tree = Tree::new("walkwarn");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/z.sv", "z");
|
||||
tree.package("locked/hidden.sv", "hidden");
|
||||
std::os::unix::fs::symlink("nowhere.sv", tree.path.join("rtl/gone.sv")).expect("symlink");
|
||||
let locked = tree.path.join("locked");
|
||||
fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).expect("chmod");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
let warnings = ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let _ = fs::set_permissions(&locked, fs::Permissions::from_mode(0o755));
|
||||
|
||||
assert_eq!(indexed(&ws, &["a", "z", "hidden"]), ["a", "z"], "the scan finished");
|
||||
assert_eq!(warnings.len(), 2, "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains("locked")), "{warnings:?}");
|
||||
assert!(
|
||||
warnings.iter().any(|w| w.contains("gone.sv: broken symbolic link")),
|
||||
"{warnings:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filelists_own_warnings_reach_the_caller() {
|
||||
let tree = filelist_tree("filelistwarn");
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use lsp_types::{Location, SymbolInformation, SymbolKind as LspKind};
|
||||
use vlog_semantic::{Symbol, SymbolKind};
|
||||
|
||||
use crate::locate::location;
|
||||
use crate::locate::definition_location;
|
||||
use crate::state::{Document, Workspace, WORKSPACE_SYMBOL_LIMIT};
|
||||
|
||||
/// How a declaration reads in hover text.
|
||||
@@ -129,7 +129,11 @@ pub fn workspace_symbols(ws: &Workspace, query: &str) -> Vec<SymbolInformation>
|
||||
.take(WORKSPACE_SYMBOL_LIMIT)
|
||||
.filter_map(|hit| {
|
||||
let path = index.path(hit.def.file)?;
|
||||
let location: Location = location(ws, path, hit.def.name_span)?;
|
||||
// A unit's range is in the index; a member's is not, and falls
|
||||
// back to the file read. `workspace/symbol` answers up to
|
||||
// `WORKSPACE_SYMBOL_LIMIT` hits at once, so this is the request
|
||||
// the index-carried positions matter most to.
|
||||
let location: Location = definition_location(ws, path, hit.def)?;
|
||||
// `deprecated` is a deprecated protocol field that is still a
|
||||
// named field of the struct.
|
||||
#[allow(deprecated)]
|
||||
|
||||
@@ -180,6 +180,7 @@ fn item_site(item: &Item, offset: u32) -> Option<Site<'_>> {
|
||||
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => {
|
||||
site_at(items, offset)
|
||||
}
|
||||
ItemKind::GenBlock(b) => gen_block_site(b, offset),
|
||||
ItemKind::GenIf(g) => gen_if_site(g, offset),
|
||||
ItemKind::GenFor(g) => gen_block_site(&g.body, offset),
|
||||
ItemKind::GenCase(g) => g.items.iter().find_map(|arm| gen_block_site(&arm.body, offset)),
|
||||
|
||||
@@ -1484,6 +1484,106 @@ fn a_port_code_action_and_the_port_commands_round_trip_over_the_wire() {
|
||||
);
|
||||
assert!(conditional["result"].is_null(), "a refusal carries no edits: {conditional:#?}");
|
||||
|
||||
// 7. The client above sent `"capabilities":{}`, so every action came back
|
||||
// complete — which is the whole of the no-resolveSupport contract.
|
||||
assert!(port_action["data"].is_null(), "nothing to resolve for this client: {port_action:#?}");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_resolves_is_offered_the_port_action_without_its_edit() {
|
||||
// The lazy half of the same feature (TODO §37.1): a client that declares
|
||||
// `codeAction.resolveSupport.properties: ["edit"]` is offered the action
|
||||
// with `data` and no `edit`, and gets the edit from `codeAction/resolve`.
|
||||
// Only an e2e test can check that the `data` really survives the round
|
||||
// trip through the client — it is opaque JSON the server never sees again
|
||||
// until the client hands it back.
|
||||
let dir = temp_dir("resolve");
|
||||
let sub = dir.join("sub.sv");
|
||||
std::fs::write(&sub, PORTS_SUB).expect("write");
|
||||
let top = dir.join("top.sv");
|
||||
std::fs::write(&top, PORTS_TOP).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let top_uri = format!("file://{}", top.display());
|
||||
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"codeAction":{{"resolveSupport":{{"properties":["edit"]}}}}}}}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(PORTS_TOP).expect("json")
|
||||
)),
|
||||
// The cursor on `u_sub`, whose instantiation is missing `.rst`.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{top_uri}"}},"range":{{"start":{{"line":2,"character":6}},"end":{{"line":2,"character":6}}}},"context":{{"diagnostics":[]}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
let messages = talk(&session);
|
||||
|
||||
// 1. The capability says a resolve is answered.
|
||||
let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
|
||||
let provider = &initialize["result"]["capabilities"]["codeActionProvider"];
|
||||
assert_eq!(provider["resolveProvider"], true, "{provider:#?}");
|
||||
|
||||
// 2. The offer carries `data` and no `edit`.
|
||||
let actions = messages.iter().find(|m| m["id"] == 2).expect("codeAction response");
|
||||
let offered = actions["result"].as_array().expect("an array of actions");
|
||||
let action = offered
|
||||
.iter()
|
||||
.find(|a| a["kind"] == "refactor.rewrite.lucisv.ports")
|
||||
.unwrap_or_else(|| panic!("no port action in {offered:#?}"));
|
||||
assert_eq!(action["title"], "lucisv: connect 1 missing port");
|
||||
assert!(action["edit"].is_null(), "an offer carries no edit: {action:#?}");
|
||||
assert_eq!(action["data"]["uri"], top_uri.as_str());
|
||||
assert_eq!(action["data"]["title"], action["title"]);
|
||||
|
||||
// 3. Handing that same action back gets the edit. A second session,
|
||||
// because the action has to be echoed verbatim and it is only known now.
|
||||
let resolve = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"codeAction":{{"resolveSupport":{{"properties":["edit"]}}}}}}}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(PORTS_TOP).expect("json")
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":3,"method":"codeAction/resolve","params":{}}}"#,
|
||||
serde_json::to_string(action).expect("json")
|
||||
)),
|
||||
// ...and an action this server never offered is refused with a
|
||||
// sentence rather than an empty edit.
|
||||
frame(
|
||||
r#"{"jsonrpc":"2.0","id":4,"method":"codeAction/resolve","params":{"title":"someone else's action"}}"#,
|
||||
),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
let messages = talk(&resolve);
|
||||
let resolved = messages.iter().find(|m| m["id"] == 3).expect("resolve response");
|
||||
let edits = resolved["result"]["edit"]["changes"][&top_uri]
|
||||
.as_array()
|
||||
.unwrap_or_else(|| panic!("no edit in {resolved:#?}"));
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert_eq!(edits[0]["newText"], ", .rst(rst)");
|
||||
assert_eq!(edits[0]["range"]["start"]["line"], 2);
|
||||
assert_eq!(resolved["result"]["title"], "lucisv: connect 1 missing port");
|
||||
|
||||
let foreign = messages.iter().find(|m| m["id"] == 4).expect("refusal response");
|
||||
assert_eq!(foreign["error"]["code"], -32803, "LSP's RequestFailed");
|
||||
assert!(
|
||||
foreign["error"]["message"].as_str().is_some_and(|m| m.contains("no lucisv port")),
|
||||
"{foreign:#?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -7442,6 +7542,87 @@ fn the_lint_options_setting_changes_what_is_published_and_a_bad_entry_is_logged(
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `lucisv.lint.waivers` over the wire — TODO §39.
|
||||
///
|
||||
/// Four claims a unit test cannot make: that a `[lint] waivers` in a checked-in
|
||||
/// `lucisv.toml` suppresses a finding the editor would otherwise draw; that the
|
||||
/// setting *adds* a second file mid-session and the squiggle goes away without
|
||||
/// a reload; that a waiver file with one bad directive is dropped **line by
|
||||
/// line** — the good directives still apply — and logged once; and that the
|
||||
/// server never publishes an `unused-waiver` for an external waiver, because
|
||||
/// it never sees a whole run.
|
||||
#[test]
|
||||
fn the_waivers_setting_suppresses_findings_and_a_bad_directive_is_logged() {
|
||||
let dir = temp_dir("lintwaivers");
|
||||
std::fs::write(dir.join("lucisv.toml"), "[lint]\nwaivers = [ \"project.waiver\" ]\n")
|
||||
.expect("write");
|
||||
std::fs::write(dir.join("project.waiver"), "waive --rule=no-tabs --line=2\n").expect("write");
|
||||
// One good directive and one that does not parse: the good one must still
|
||||
// apply, which is what "drops the line, never the file" means.
|
||||
std::fs::write(
|
||||
dir.join("extra.waiver"),
|
||||
"waive --rule=no-tabs --line=3\nwaive --rule=no-such-rule\n",
|
||||
)
|
||||
.expect("write");
|
||||
let file = dir.join("tabs.sv");
|
||||
let text = "module tabs;\n\twire a;\n\twire b;\nendmodule\n";
|
||||
std::fs::write(&file, text).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(text).expect("json")
|
||||
)),
|
||||
// The editor's list adds to the `lucisv.toml`'s, relative to the root.
|
||||
frame(
|
||||
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"lint":{"waivers":["extra.waiver","gone.waiver"]}}}}}"#,
|
||||
),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&session);
|
||||
let tabs: Vec<Vec<&str>> = messages
|
||||
.iter()
|
||||
.filter(|m| m["method"] == "textDocument/publishDiagnostics")
|
||||
.filter(|m| m["params"]["uri"] == uri.as_str())
|
||||
.map(|m| {
|
||||
m["params"]["diagnostics"]
|
||||
.as_array()
|
||||
.map(|list| list.iter().filter_map(|d| d["code"].as_str()).collect())
|
||||
.unwrap_or_default()
|
||||
})
|
||||
.collect();
|
||||
assert!(tabs.len() >= 2, "one publish per state: {tabs:?}");
|
||||
assert_eq!(tabs[0], vec!["no-tabs"], "the toml waived line 2, line 3 is left: {tabs:?}");
|
||||
assert!(
|
||||
tabs[tabs.len() - 1].is_empty(),
|
||||
"the setting's good directive waived line 3 without a reload: {tabs:?}"
|
||||
);
|
||||
for published in &tabs {
|
||||
assert!(!published.contains(&"unused-waiver"), "never from the server: {tabs:?}");
|
||||
}
|
||||
|
||||
let logged: Vec<&str> = messages
|
||||
.iter()
|
||||
.filter(|m| m["method"] == "window/logMessage")
|
||||
.filter_map(|m| m["params"]["message"].as_str())
|
||||
.filter(|text| text.contains("lucisv.lint.waivers"))
|
||||
.collect();
|
||||
assert_eq!(logged.len(), 2, "the bad directive and the missing file: {logged:?}");
|
||||
assert!(logged.iter().any(|line| line.contains("unknown rule")), "{logged:?}");
|
||||
assert!(logged.iter().any(|line| line.contains("gone.waiver")), "{logged:?}");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `lucisv.instantiate` — `docs/topo.md` §2.9-19. What only an e2e test can
|
||||
/// check: that the command is advertised in `initialize`, that its three
|
||||
/// arguments survive the wire, and that the skeleton arrives as a
|
||||
@@ -7577,3 +7758,412 @@ fn a_property_declaration_hovers_and_appears_in_the_outline() {
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// §42 — one lint-configuration contract for the project file and the editor.
|
||||
//
|
||||
// `docs/features/lint-config-contract/README.md`: the editor's settings play
|
||||
// the role the CLI's flags play, so a `lucisv.toml` a project checks in
|
||||
// governs an editor exactly as it governs CI, and a `lucisv.lint.*` setting
|
||||
// replaces it the way a flag replaces it.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// A buffer with one tab and one trailing space: two style findings from two
|
||||
/// rules, so a selection that keeps one and drops the other is visible.
|
||||
const TWO_FINDINGS: &str = "module lint_contract;\n\twire a; \nendmodule\n";
|
||||
|
||||
/// The rule codes of every `publishDiagnostics` for one URI, in the order
|
||||
/// they arrived, with a repeat of the previous answer collapsed: a republish
|
||||
/// that says the same thing is not a step.
|
||||
fn published_codes(messages: &[serde_json::Value], uri: &str) -> Vec<Vec<String>> {
|
||||
let mut steps: Vec<Vec<String>> = Vec::new();
|
||||
for message in messages {
|
||||
if message["method"] != "textDocument/publishDiagnostics"
|
||||
|| message["params"]["uri"] != serde_json::Value::String(uri.to_string())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut codes: Vec<String> = message["params"]["diagnostics"]
|
||||
.as_array()
|
||||
.expect("an array")
|
||||
.iter()
|
||||
.filter_map(|d| d["code"].as_str().map(str::to_string))
|
||||
.collect();
|
||||
codes.sort();
|
||||
codes.dedup();
|
||||
if steps.last() != Some(&codes) {
|
||||
steps.push(codes);
|
||||
}
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
/// The `initialize`/`didOpen` prefix every session below opens with.
|
||||
fn lint_session_start(dir: &Path, uri: &str, text: &str) -> String {
|
||||
let root = format!("file://{}", dir.display());
|
||||
[
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(text).expect("json")
|
||||
)),
|
||||
]
|
||||
.concat()
|
||||
}
|
||||
|
||||
/// A `didChangeConfiguration` carrying one `lucisv.lint.select` list.
|
||||
fn select_push(rules: &str) -> String {
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"lucisv":{{"lint":{{"select":[{rules}]}}}}}}}}}}"#
|
||||
))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_projects_lint_select_governs_an_editor_until_a_setting_replaces_it() {
|
||||
let dir = temp_dir("lint_contract_select");
|
||||
std::fs::write(dir.join("lucisv.toml"), "[lint]\nselect = [\"no-tabs\"]\n")
|
||||
.expect("write config");
|
||||
let file = dir.join("lint_contract.sv");
|
||||
std::fs::write(&file, TWO_FINDINGS).expect("write");
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
let session = [
|
||||
lint_session_start(&dir, &uri, TWO_FINDINGS),
|
||||
// The editor names a rule of its own: it replaces the project's, as
|
||||
// `--select` replaces it on the command line.
|
||||
select_push("\"no-trailing-whitespace\""),
|
||||
// ... and taking the setting back restores the project's.
|
||||
select_push(""),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let steps = published_codes(&talk(&session), &uri);
|
||||
assert_eq!(
|
||||
steps,
|
||||
vec![
|
||||
vec!["no-tabs".to_string()],
|
||||
vec!["no-trailing-whitespace".to_string()],
|
||||
vec!["no-tabs".to_string()],
|
||||
],
|
||||
"the project selects, the editor replaces, and an emptied setting hands it back"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A `[lint.<rule>]` entry the registry refuses is said **once** in the
|
||||
/// output channel — in the words `lucisv check` fails the run with — and the
|
||||
/// buffer keeps being linted with the entry dropped (§42.2).
|
||||
#[test]
|
||||
fn a_rejected_project_option_is_logged_once_and_the_buffer_is_still_linted() {
|
||||
let dir = temp_dir("lint_contract_option");
|
||||
let config = dir.join("lucisv.toml");
|
||||
std::fs::write(&config, "[lint.line-length]\nlength = \"wide\"\n").expect("write config");
|
||||
let file = dir.join("lint_contract.sv");
|
||||
std::fs::write(&file, TWO_FINDINGS).expect("write");
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
// Three settings pushes, each of which republishes every open buffer, so
|
||||
// the lint pass runs at least four times over the same bad config.
|
||||
let session = [
|
||||
lint_session_start(&dir, &uri, TWO_FINDINGS),
|
||||
select_push("\"no-tabs\""),
|
||||
select_push("\"no-trailing-whitespace\""),
|
||||
select_push(""),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
let messages = talk(&session);
|
||||
|
||||
let complaints: Vec<&str> = messages
|
||||
.iter()
|
||||
.filter(|m| m["method"] == "window/logMessage")
|
||||
.filter_map(|m| m["params"]["message"].as_str())
|
||||
.filter(|line| line.contains("line-length"))
|
||||
.collect();
|
||||
assert_eq!(complaints.len(), 1, "said once, not once per pass: {complaints:#?}");
|
||||
assert!(
|
||||
complaints[0].starts_with(&format!("lucisv: {}:2: rule `line-length` ", config.display())),
|
||||
"the file and line `lucisv check` would name: {}",
|
||||
complaints[0]
|
||||
);
|
||||
assert!(
|
||||
!messages.iter().any(|m| m["method"] == "window/showMessage"),
|
||||
"logged, not shown: {messages:#?}"
|
||||
);
|
||||
|
||||
// And the lint kept running with the entry dropped.
|
||||
let steps = published_codes(&messages, &uri);
|
||||
assert!(
|
||||
steps.iter().any(|codes| codes.contains(&"no-tabs".to_string())),
|
||||
"the buffer is still linted: {steps:#?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The rules `lucisv check` runs over a file and the rules the server runs
|
||||
/// over the same buffer, for three `lucisv.toml`s. Equal, or the two halves
|
||||
/// of lucisv disagree about what a violation is — which is the whole reason
|
||||
/// §42 exists.
|
||||
#[test]
|
||||
fn the_cli_and_the_server_run_the_same_rules_for_the_same_buffer() {
|
||||
let Some(lucisv) = lucisv_binary() else {
|
||||
eprintln!("skipped: the `lucisv` binary is not built next to `lucisv-server`");
|
||||
return;
|
||||
};
|
||||
let configs = [
|
||||
// No `[lint]` table at all: both front ends fall back to the base set.
|
||||
("none", "line-length = 80\n"),
|
||||
// A selection of one rule.
|
||||
("one", "[lint]\nselect = [\"no-tabs\"]\n"),
|
||||
// A severity word, and an `ignore` that takes one back out of it.
|
||||
("class", "[lint]\nselect = [\"style\"]\nignore = [\"no-trailing-whitespace\"]\n"),
|
||||
];
|
||||
for (tag, config) in configs {
|
||||
let dir = temp_dir(&format!("lint_contract_agree_{tag}"));
|
||||
std::fs::write(dir.join("lucisv.toml"), config).expect("write config");
|
||||
let file = dir.join("lint_contract.sv");
|
||||
std::fs::write(&file, TWO_FINDINGS).expect("write");
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
let output = Command::new(&lucisv)
|
||||
.args(["check", "--output-format", "json"])
|
||||
.arg(&file)
|
||||
.output()
|
||||
.expect("the lucisv binary runs");
|
||||
let json: serde_json::Value =
|
||||
serde_json::from_slice(&output.stdout).expect("the CLI prints one JSON array");
|
||||
let mut from_cli: Vec<String> = json
|
||||
.as_array()
|
||||
.expect("an array")
|
||||
.iter()
|
||||
.filter_map(|item| item["rule"].as_str().map(str::to_string))
|
||||
.collect();
|
||||
from_cli.sort();
|
||||
from_cli.dedup();
|
||||
|
||||
let session = [
|
||||
lint_session_start(&dir, &uri, TWO_FINDINGS),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
let from_server =
|
||||
published_codes(&talk(&session), &uri).pop().expect("the server published something");
|
||||
|
||||
assert_eq!(from_server, from_cli, "the two front ends disagree under {config:?}");
|
||||
assert!(!from_cli.is_empty(), "a config that reports nothing proves nothing: {config:?}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TODO.md §46 — what a `didOpen` costs the request behind it
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// `talk` writes a whole session before reading a byte, which is what every
|
||||
// test above wants and what a *timing* test cannot use: the number this round
|
||||
// is about is the gap between the `didOpen` frame going out and the next
|
||||
// response coming back. `Live` — the held-open session two hundred lines up —
|
||||
// is the one that can measure it. The three tests below are §46's contract:
|
||||
// the open returns to the loop fast, the first request after it is answered
|
||||
// from the **buffer**, and the diagnostics still arrive with no edit and no
|
||||
// further request behind them.
|
||||
|
||||
/// A started session over `root`, indexed at the whole-workspace scope with
|
||||
/// the scan already run — the barrier request at the end is what makes that
|
||||
/// true, since the loop answers nothing until a rescan a message asked for has
|
||||
/// finished.
|
||||
fn live_at(root: &Path) -> Live {
|
||||
let mut live = Live::start();
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"file://{}","capabilities":{{}}}}}}"#,
|
||||
root.display()
|
||||
));
|
||||
live.wait_for(|m| m["id"] == 1);
|
||||
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
|
||||
live.send(WIDE_SCOPE);
|
||||
live.send(r#"{"jsonrpc":"2.0","id":2,"method":"workspace/symbol","params":{"query":"zzz"}}"#);
|
||||
live.wait_for(|m| m["id"] == 2);
|
||||
live
|
||||
}
|
||||
|
||||
/// The `didOpen` frame for a buffer.
|
||||
fn open_frame(uri: &str, text: &str) -> String {
|
||||
format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(text).expect("json")
|
||||
)
|
||||
}
|
||||
|
||||
/// Open `uri` and ask for a `hover` in the same write, and report how long the
|
||||
/// hover took to come back.
|
||||
///
|
||||
/// That wait *is* the open: the loop is synchronous, so whatever the open does
|
||||
/// before returning to it is what the hover queues behind.
|
||||
fn open_then_hover(live: &mut Live, id: u32, uri: &str, text: &str) -> std::time::Duration {
|
||||
let hover = format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":0,"character":8}}}}}}"#
|
||||
);
|
||||
let started = std::time::Instant::now();
|
||||
live.send(&open_frame(uri, text));
|
||||
live.send(&hover);
|
||||
live.wait_for(|m| m["id"] == id);
|
||||
started.elapsed()
|
||||
}
|
||||
|
||||
/// A workspace of `files` small packages, so the index holds a *project*
|
||||
/// rather than one buffer — which is what switches the cross-file lint rules
|
||||
/// on at all (`LintRun::for_document`).
|
||||
fn indexed_neighbours(dir: &Path, files: usize) {
|
||||
for k in 0..files {
|
||||
std::fs::write(
|
||||
dir.join(format!("pkg{k}.sv")),
|
||||
format!("package pkg{k};\n localparam int K{k} = {k};\nendpackage\n"),
|
||||
)
|
||||
.expect("write neighbour");
|
||||
}
|
||||
}
|
||||
|
||||
/// §46's contract, on the wire: a `didOpen` of a 2 000-line buffer must not
|
||||
/// leave the request behind it waiting.
|
||||
///
|
||||
/// **An upper bound, not a benchmark, and a debug-build one.** `cargo test`
|
||||
/// builds unoptimized, where one tolerant parse of 2 000 lines is ~53 ms all
|
||||
/// by itself — measured on this machine, and stable to a millisecond across
|
||||
/// runs. So the 200 ms here is that floor with room for a loaded CI box, not
|
||||
/// the ≤ 25 ms §46 asked for: **that figure is a release number**, and the
|
||||
/// release binary opens the same buffer in 2–4 ms.
|
||||
///
|
||||
/// **What this test does and does not catch.** It catches an open that starts
|
||||
/// doing something *unbounded* — the shape §46 fixed. It cannot catch the
|
||||
/// §46 defect itself at this size: the census walk that cost 1.6 s on
|
||||
/// opentitan's 42 000-line `pinmux_reg_top.sv` costs milliseconds over a
|
||||
/// forty-file fixture, and a fixture of opentitan's four thousand files has
|
||||
/// no business in a unit-test suite. The exact pin for that is
|
||||
/// `undriven_net`'s `the_project_is_asked_only_about_the_signals_that_would_be_reported`,
|
||||
/// which counts the questions instead of timing them
|
||||
/// (`docs/features/didopen-cost/README.md`).
|
||||
///
|
||||
/// Best of three distinct buffers: the first open of a process pays cold code
|
||||
/// paths that have nothing to do with the buffer, and a wall-clock assertion
|
||||
/// that cannot tolerate one scheduling hiccup is a flake, not a pin.
|
||||
#[test]
|
||||
fn opening_a_two_thousand_line_buffer_does_not_delay_the_request_behind_it() {
|
||||
let dir = temp_dir("didopen_cost");
|
||||
indexed_neighbours(&dir, 40);
|
||||
let mut generated = Vec::new();
|
||||
for n in 0..3 {
|
||||
let name = format!("gen{n}");
|
||||
// The generator the perf tables use: a thousand declarations, every
|
||||
// one declared, driven and read — the cheap case for the *findings*
|
||||
// and the expensive one for the walk that decides there are none.
|
||||
let text = generated_module(&name, 2_000);
|
||||
assert!(text.lines().count() >= 2_000, "the premise: a 2 000-line buffer");
|
||||
let path = dir.join(format!("{name}.sv"));
|
||||
std::fs::write(&path, &text).expect("write");
|
||||
generated.push((path, text));
|
||||
}
|
||||
let mut live = live_at(&dir);
|
||||
// A warm-up open of a small buffer, for the cold code paths.
|
||||
let warm = format!("file://{}", dir.join("pkg0.sv").display());
|
||||
open_then_hover(&mut live, 10, &warm, "package pkg0;\n localparam int K0 = 0;\nendpackage\n");
|
||||
|
||||
let mut best = std::time::Duration::MAX;
|
||||
for (n, (path, text)) in generated.iter().enumerate() {
|
||||
let uri = format!("file://{}", path.display());
|
||||
best = best.min(open_then_hover(&mut live, 20 + n as u32, &uri, text));
|
||||
}
|
||||
live.finish();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
assert!(
|
||||
best <= std::time::Duration::from_millis(200),
|
||||
"a didOpen of a 2 000-line buffer delayed the next request by {best:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The other half of §46's contract: the request after an open is answered
|
||||
/// from the **buffer**, not from what is on disk.
|
||||
///
|
||||
/// Nothing about the open was deferred — it still analyzes the buffer before
|
||||
/// it returns to the loop — and this is what says so out loud. The buffer
|
||||
/// names something the file on disk does not, and declares it on a line the
|
||||
/// disk file does not, and the very first hover and the very first definition
|
||||
/// after the open both find the buffer's.
|
||||
#[test]
|
||||
fn the_first_hover_after_an_open_sees_the_buffer_and_not_the_disk() {
|
||||
let dir = temp_dir("didopen_buffer_wins");
|
||||
indexed_neighbours(&dir, 4);
|
||||
let file = dir.join("m.sv");
|
||||
std::fs::write(
|
||||
&file,
|
||||
"module m;\n localparam int ON_DISK = 1;\n logic a;\n assign a = ON_DISK;\nendmodule\n",
|
||||
)
|
||||
.expect("write");
|
||||
let uri = format!("file://{}", file.display());
|
||||
// What the editor holds: a different name, declared on a different line.
|
||||
let buffer = "module m;\n\n localparam int IN_BUFFER = 2;\n logic a;\n \
|
||||
assign a = IN_BUFFER;\nendmodule\n";
|
||||
|
||||
let mut live = live_at(&dir);
|
||||
live.send(&open_frame(&uri, buffer));
|
||||
// The cursor on `IN_BUFFER` where line 4 reads it.
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":30,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":4,"character":16}}}}}}"#
|
||||
));
|
||||
let card = live.wait_for(|m| m["id"] == 30)["result"]["contents"]["value"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":31,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":4,"character":16}}}}}}"#
|
||||
));
|
||||
let definition = live.wait_for(|m| m["id"] == 31);
|
||||
live.finish();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
assert!(card.contains("IN_BUFFER"), "the first hover did not read the buffer: {card:?}");
|
||||
assert!(!card.contains("ON_DISK"), "the first hover read the disk file: {card:?}");
|
||||
let locations = definition["result"].as_array().expect("an array of locations");
|
||||
assert_eq!(locations.len(), 1, "one declaration, got {locations:#?}");
|
||||
assert_eq!(locations[0]["range"]["start"]["line"], 2, "the buffer's line, not the disk's");
|
||||
}
|
||||
|
||||
/// And the third: the open still publishes, with no edit and no further
|
||||
/// request to trigger it.
|
||||
///
|
||||
/// **There is no debounce on the open.** §46 allowed the diagnostics to be
|
||||
/// moved onto the change debounce and to arrive one quiet period later; they
|
||||
/// were not, because the cost was never the publish — it was one rule inside
|
||||
/// it. So the guarantee is the one this server has always had: the diagnostics
|
||||
/// for an opened buffer go out inside the `didOpen`, ahead of anything queued
|
||||
/// behind it.
|
||||
#[test]
|
||||
fn an_open_still_publishes_its_diagnostics_with_no_edit_behind_it() {
|
||||
let dir = temp_dir("didopen_publishes");
|
||||
indexed_neighbours(&dir, 4);
|
||||
let file = dir.join("tabbed.sv");
|
||||
let text = "module tabbed;\n\twire a;\nendmodule\n";
|
||||
std::fs::write(&file, text).expect("write");
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
let mut live = live_at(&dir);
|
||||
live.send(&open_frame(&uri, text));
|
||||
let published = live.wait_for(|m| {
|
||||
m["method"] == "textDocument/publishDiagnostics" && m["params"]["uri"] == uri
|
||||
});
|
||||
live.finish();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
let items = published["params"]["diagnostics"].as_array().expect("a diagnostics array");
|
||||
let codes: Vec<&str> = items.iter().filter_map(|d| d["code"].as_str()).collect();
|
||||
assert!(codes.contains(&"no-tabs"), "the open published nothing about the tab: {items:#?}");
|
||||
}
|
||||
@@ -245,6 +245,7 @@ fn scan_nested(src: &str, item: &Item, out: &mut Vec<Region>) {
|
||||
ItemKind::Module(m) => scan_scope(src, &m.items, &m.dangling, out),
|
||||
ItemKind::Package { items, dangling, .. } => scan_scope(src, items, dangling, out),
|
||||
ItemKind::GenerateRegion { items, dangling } => scan_scope(src, items, dangling, out),
|
||||
ItemKind::GenBlock(b) => scan_gen_block(src, b, out),
|
||||
ItemKind::GenIf(g) => scan_gen_if(src, g, out),
|
||||
ItemKind::GenFor(g) => scan_gen_block(src, &g.body, out),
|
||||
ItemKind::GenCase(g) => {
|
||||
|
||||
@@ -296,22 +296,44 @@ impl<'a> Fmt<'a> {
|
||||
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(" "));
|
||||
docs.push(text(net.clone()));
|
||||
self.net_delay(d, false, &mut docs);
|
||||
}
|
||||
self.qualifier_run(&d.qualifiers, &mut docs);
|
||||
if let Some(t) = self.data_type(&d.ty) {
|
||||
docs.push(t);
|
||||
docs.push(text(" "));
|
||||
self.net_delay(d, true, &mut docs);
|
||||
}
|
||||
// Neither arm needs an `else`: a delay before the type is only read
|
||||
// after a net keyword, and one after the type only when a type was
|
||||
// actually written, so an implicit type has none to print.
|
||||
docs.push(self.declarators(&d.declarators));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// The separator that follows the word just emitted, and then `#5` when
|
||||
/// the declaration's net delay was written on the side of the data type
|
||||
/// `after_type` names. IEEE 1800 §6.7 allows either side and lucisv
|
||||
/// prints it where the source put it; moving it across the type would
|
||||
/// reorder tokens, which `verify.rs` refuses.
|
||||
///
|
||||
/// The separator is the delay's `before_hash` comments when it has any
|
||||
/// (`wire /* c */ #5 w;`) and a plain space otherwise — so a declaration
|
||||
/// with no comment there is laid out exactly as it was before the slot
|
||||
/// existed, delay or no delay.
|
||||
fn net_delay(&self, d: &DataDecl, after_type: bool, docs: &mut Vec<Doc>) {
|
||||
let delay = d.delay.as_ref().filter(|n| n.after_type == after_type);
|
||||
match delay.map(|n| &n.before_hash).filter(|c| !c.is_empty()) {
|
||||
Some(comments) => self.inline_comments_spaced(comments, docs),
|
||||
None => docs.push(text(" ")),
|
||||
}
|
||||
let Some(delay) = delay else { return };
|
||||
docs.push(text("#"));
|
||||
self.slot_comments(&delay.after_hash, docs);
|
||||
docs.push(self.expr(&delay.expr));
|
||||
docs.push(text(" "));
|
||||
}
|
||||
|
||||
pub(super) fn port_decl(&self, d: &PortDecl) -> Doc {
|
||||
let mut docs = vec![text(format!("{} ", d.dir))];
|
||||
if let Some(net) = &d.net {
|
||||
|
||||
@@ -310,8 +310,17 @@ impl<'a> Fmt<'a> {
|
||||
// strictly. Printed verbatim so nothing is lost if that ever
|
||||
// changes — see `ListItem::from_raw`.
|
||||
ExprKind::Error(raw) => self.raw_inline(raw),
|
||||
ExprKind::MinTypMax { min, typ, max } => {
|
||||
concat(vec![self.expr(min), text(":"), self.expr(typ), text(":"), self.expr(max)])
|
||||
ExprKind::MinTypMax { min, typ, max, comments } => {
|
||||
let mut docs = vec![self.expr(min)];
|
||||
self.slot_comments(&comments.before_typ, &mut docs);
|
||||
docs.push(text(":"));
|
||||
self.slot_comments(&comments.after_typ, &mut docs);
|
||||
docs.push(self.expr(typ));
|
||||
self.slot_comments(&comments.before_max, &mut docs);
|
||||
docs.push(text(":"));
|
||||
self.slot_comments(&comments.after_max, &mut docs);
|
||||
docs.push(self.expr(max));
|
||||
concat(docs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -342,30 +342,83 @@ impl<'a> Fmt<'a> {
|
||||
if let Some(s) = &g.strength {
|
||||
docs.push(text(format!(" {}", drive_strength(s))));
|
||||
}
|
||||
if !g.delay.is_empty() {
|
||||
// The gap in front of the `#` is a space unless the source wrote
|
||||
// a comment in it, exactly as a net delay's `before_hash` is.
|
||||
match g.before_hash.is_empty() {
|
||||
true => docs.push(text(" ")),
|
||||
false => self.inline_comments_spaced(&g.before_hash, &mut docs),
|
||||
}
|
||||
docs.push(text("#"));
|
||||
self.slot_comments(&g.after_hash, &mut docs);
|
||||
}
|
||||
if let [delay] = g.delay.as_slice() {
|
||||
// One value prints itself, brackets and all (`#5`, `#(5)`).
|
||||
docs.push(text(" #"));
|
||||
docs.push(self.expr(delay));
|
||||
docs.push(self.expr(&delay.expr));
|
||||
} else if !g.delay.is_empty() {
|
||||
// `#(rise, fall[, turn-off])` — the parens are the list's own.
|
||||
docs.push(text(" #("));
|
||||
// `#(rise, fall[, turn-off])` — the parens and the commas are the
|
||||
// list's own, so the comments written around them are too.
|
||||
docs.push(text("("));
|
||||
for (i, d) in g.delay.iter().enumerate() {
|
||||
if i > 0 {
|
||||
docs.push(text(", "));
|
||||
docs.push(text(","));
|
||||
match d.leading.is_empty() {
|
||||
true => docs.push(text(" ")),
|
||||
false => self.inline_comments_spaced(&d.leading, &mut docs),
|
||||
}
|
||||
} else {
|
||||
self.slot_comments(&d.leading, &mut docs);
|
||||
}
|
||||
docs.push(self.expr(d));
|
||||
docs.push(self.expr(&d.expr));
|
||||
self.slot_comments(&d.trailing, &mut docs);
|
||||
}
|
||||
docs.push(text(")"));
|
||||
}
|
||||
let last = g.instances.len().saturating_sub(1);
|
||||
// True once a trailing comment has ended the previous instance's line:
|
||||
// the next instance then starts on a fresh, indented line, and the
|
||||
// space that normally separates it from the `,` is not written.
|
||||
let mut broke = false;
|
||||
for (i, inst) in g.instances.iter().enumerate() {
|
||||
docs.push(if i > 0 { text(", ") } else { text(" ") });
|
||||
// What stands between the delay (or the previous instance's `,`)
|
||||
// and this instance's name — a space when nothing does.
|
||||
match (broke, inst.meta.leading.is_empty()) {
|
||||
(true, true) => {}
|
||||
(false, true) => docs.push(text(" ")),
|
||||
(_, false) => self.inline_comments_spaced(&inst.meta.leading, &mut docs),
|
||||
}
|
||||
broke = false;
|
||||
if let Some(name) = &inst.name {
|
||||
docs.push(name_doc(name));
|
||||
docs.push(text(" "));
|
||||
match inst.before_args.is_empty() {
|
||||
true => docs.push(text(" ")),
|
||||
false => self.inline_comments_spaced(&inst.before_args, &mut docs),
|
||||
}
|
||||
}
|
||||
docs.push(self.expr_list("(", &inst.args, ")"));
|
||||
if i == last {
|
||||
continue;
|
||||
}
|
||||
// Comments written between the instance and its `,` print on the
|
||||
// instance's side of it, as every list element's do.
|
||||
if self.inline_comments(&inst.meta.before_sep, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(","));
|
||||
if let Some(tr) = &inst.meta.trailing {
|
||||
docs.push(text(" "));
|
||||
docs.push(self.comment(tr));
|
||||
// A line comment ends the line (a `// p` would otherwise
|
||||
// swallow the next instance on re-lex — §45's QA); the next
|
||||
// instance continues one level in. A block comment stays
|
||||
// inline, as the case table for this slot expects.
|
||||
if is_line_comment(&tr.text) {
|
||||
docs.push(indent(vec![Doc::HardLine]));
|
||||
broke = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
docs.push(text(";"));
|
||||
docs.push(self.semi(&g.before_semi));
|
||||
concat(docs)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,6 +274,21 @@ impl<'a> Fmt<'a> {
|
||||
body.extend(self.dangling(dangling));
|
||||
concat(vec![text("generate"), indent(body), Doc::HardLine, text("endgenerate")])
|
||||
}
|
||||
// A bare `begin … end` standing where an item belongs. Never
|
||||
// reached from `format_source`: the parser records a diagnostic
|
||||
// beside it and a file with a diagnostic is emitted unchanged.
|
||||
// The arm exists so a range or tolerant printer has nothing to
|
||||
// invent — the block prints the way a generate block's does,
|
||||
// without the separator `gen_block` puts in front of the keyword
|
||||
// for the header it usually hangs off.
|
||||
ItemKind::GenBlock(b) => {
|
||||
let mut docs = Vec::new();
|
||||
if self.inline_comments(&b.before_kw, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
self.begin_block(&mut docs, b, depth);
|
||||
concat(docs)
|
||||
}
|
||||
ItemKind::GenIf(g) => self.gen_if(g, depth),
|
||||
ItemKind::GenFor(g) => self.gen_for(g, depth),
|
||||
ItemKind::GenCase(g) => self.gen_case(g, depth),
|
||||
@@ -347,8 +362,12 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
if let Some(delay) = &a.delay {
|
||||
docs.push(text("#"));
|
||||
self.slot_comments(&a.after_hash, &mut docs);
|
||||
docs.push(self.expr(delay));
|
||||
docs.push(text(" "));
|
||||
match a.after_delay.is_empty() {
|
||||
true => docs.push(text(" ")),
|
||||
false => self.inline_comments_spaced(&a.after_delay, &mut docs),
|
||||
}
|
||||
}
|
||||
let items: Vec<ListItem> = a
|
||||
.assigns
|
||||
@@ -464,26 +483,7 @@ impl<'a> Fmt<'a> {
|
||||
} 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));
|
||||
self.begin_block(docs, b, depth);
|
||||
true
|
||||
} else {
|
||||
let item = &b.items[0];
|
||||
@@ -492,6 +492,33 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A generate block's `begin … end` and everything between, from the
|
||||
/// keyword on — the separator in front of it is the caller's, because a
|
||||
/// block hanging off an `if (…)` header needs one and a block standing on
|
||||
/// its own as an item ([`ItemKind::GenBlock`]) does not.
|
||||
fn begin_block(&self, docs: &mut Vec<Doc>, b: &GenBlock, depth: usize) {
|
||||
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));
|
||||
}
|
||||
|
||||
fn gen_for(&self, g: &GenFor, depth: usize) -> Doc {
|
||||
let mut header = Vec::new();
|
||||
self.for_open(&g.comments, &mut header);
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
# TODO §45.4 — the comment slots inside a delay list. `parse_delay_values`
|
||||
# serves `#(1:2:3)` on nets and continuous assignments and `#(rise, fall)` on
|
||||
# gates; the gaps around the `(`, the two `:` and the `,` had no owner, so a
|
||||
# comment written in one moved and `verify.rs` refused the file.
|
||||
#
|
||||
# The `min:typ:max` colons: `MinTypMaxComments`, four slots, one grammar
|
||||
# shared with the parenthesized `(a:b:c)` expression.
|
||||
module m;
|
||||
wire #(1 /* b */ : /* c */ 2 /* d */ : /* e */ 3) w;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire #(1 /* b */ : /* c */ 2 /* d */ : /* e */ 3) w;
|
||||
endmodule
|
||||
====
|
||||
# The parentheses of a one-value delay are its own `ExprKind::Paren`, which
|
||||
# has had the two slots all along — and a comment inside a bracket pair forces
|
||||
# that pair open, as it does everywhere else in the formatter.
|
||||
module m;
|
||||
wire #( /* a */ 1:2:3 /* f */ ) w;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire #(
|
||||
/* a */
|
||||
1:2:3 /* f */
|
||||
) w;
|
||||
endmodule
|
||||
====
|
||||
# A continuous assignment's delay: the gap after its `#` and the gap between
|
||||
# the delay and the first left-hand side. Without the second slot the comment
|
||||
# joins the first pair's leading comments, which print in front of the delay.
|
||||
module m;
|
||||
assign # /* g */ (1:2:3) /* h */ z = a;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign # /* g */ (1:2:3) /* h */ z = a;
|
||||
endmodule
|
||||
====
|
||||
# A gate's multi-value list writes its own parentheses and commas, so it owns
|
||||
# the comments around them: `DelayValue::{leading, trailing}`. With them the
|
||||
# gate's `before_hash`, `after_hash`, the instance's `before_args` and the
|
||||
# item's `before_semi`.
|
||||
module m;
|
||||
and /* i */ # /* j */ ( /* k */ 2 /* l */ , /* m */ 3 /* n */ ) g1 /* o */ (y, a, b) /* p */ ;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
and /* i */ # /* j */ ( /* k */ 2 /* l */ , /* m */ 3 /* n */ ) g1 /* o */ (y, a, b) /* p */ ;
|
||||
endmodule
|
||||
====
|
||||
# A line comment runs to end of line, so what follows it starts a new one —
|
||||
# the same rule every other slot in the formatter obeys.
|
||||
module m;
|
||||
wire #(1 // why
|
||||
:2:3) w;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire #(
|
||||
1 // why
|
||||
:2:3
|
||||
) w;
|
||||
endmodule
|
||||
====
|
||||
# Nothing written in any of the slots costs a byte: the comment-free spellings
|
||||
# are laid out exactly as they were before the slots existed.
|
||||
module m;
|
||||
wire #(1:2:3) a;
|
||||
assign #(1:2:3) z = a;
|
||||
and #(1, 2, 3) g1 (o, a, b);
|
||||
not #(1:2:3, 4:5:6) n0 (o, a);
|
||||
buf #(5) b1 (o, a);
|
||||
buf #5 b2 (o, a);
|
||||
buf b3 (o, a);
|
||||
nand (weak0, weak1) #2 n1 (o, a, b);
|
||||
and #(2, 3) g0 (y, a), g2 (z, b);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire #(1:2:3) a;
|
||||
assign #(1:2:3) z = a;
|
||||
and #(1, 2, 3) g1 (o, a, b);
|
||||
not #(1:2:3, 4:5:6) n0 (o, a);
|
||||
buf #(5) b1 (o, a);
|
||||
buf #5 b2 (o, a);
|
||||
buf b3 (o, a);
|
||||
nand (weak0, weak1) #2 n1 (o, a, b);
|
||||
and #(2, 3) g0 (y, a), g2 (z, b);
|
||||
endmodule
|
||||
====
|
||||
# A comment between two gate instances, and one written before the `,` that
|
||||
# separates them: the element's own `leading` and `before_sep`.
|
||||
module m;
|
||||
and #(2, 3) g0 (y, a) /* before */ , /* after */ g1 (z, b);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
and #(2, 3) g0 (y, a) /* before */, /* after */ g1 (z, b);
|
||||
endmodule
|
||||
@@ -224,3 +224,42 @@ module tb;
|
||||
sub #() u1 (.a(x));
|
||||
sub #(.W(8)) u2 (.a(x));
|
||||
endmodule
|
||||
====
|
||||
# TODO §45.3 — an inline aggregate as a parameter-override argument. It is a
|
||||
# type where a type is legal (IEEE 1800 §6.19, §7.2), the override a
|
||||
# `parameter type` defaulting to one takes, and it prints through the existing
|
||||
# type printer: a struct or union body opens, an enum body stays inline.
|
||||
module m;
|
||||
sub #(.T(struct packed { logic a; })) u0 ();
|
||||
sub #(.T(union packed { logic [7:0] a; })) u1 ();
|
||||
sub #(.T(enum logic [1:0] {A, B})) u2 ();
|
||||
sub #(.T(struct packed { /* why */ logic a; })) u3 ();
|
||||
sub #(.T(logic [7:0])) u4 ();
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub #(
|
||||
.T(
|
||||
struct packed {
|
||||
logic a;
|
||||
}
|
||||
)
|
||||
) u0 ();
|
||||
sub #(
|
||||
.T(
|
||||
union packed {
|
||||
logic [7:0] a;
|
||||
}
|
||||
)
|
||||
) u1 ();
|
||||
sub #(.T(enum logic [1:0] {A, B})) u2 ();
|
||||
sub #(
|
||||
.T(
|
||||
struct packed {
|
||||
/* why */
|
||||
logic a;
|
||||
}
|
||||
)
|
||||
) u3 ();
|
||||
sub #(.T(logic [7:0])) u4 ();
|
||||
endmodule
|
||||
@@ -0,0 +1,121 @@
|
||||
# TODO §38.2 — a net delay is printed on the side of the data type it was
|
||||
# written on. IEEE 1800 §6.7 puts `delay3` after the type; the rest of the
|
||||
# corpus puts it before. Neither spelling is normalised into the other.
|
||||
# docs/features/parser-skips/README.md
|
||||
module m;
|
||||
wire #5 before_the_type;
|
||||
wire [31:0] #0.1 after_the_type = y;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire #5 before_the_type;
|
||||
wire [31:0] #0.1 after_the_type = y;
|
||||
endmodule
|
||||
====
|
||||
# after a packed dimension, after a plain `logic`-typed net, and after a
|
||||
# signing keyword — with the min:typ:max spelling of the delay itself
|
||||
module m;
|
||||
wire [7:0] #1 a;
|
||||
wire logic #2 b;
|
||||
wire signed [7:0] #(1:2:3) c;
|
||||
wire #(1:2:3) signed [7:0] d;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire [7:0] #1 a;
|
||||
wire logic #2 b;
|
||||
wire signed [7:0] #(1:2:3) c;
|
||||
wire #(1:2:3) signed [7:0] d;
|
||||
endmodule
|
||||
====
|
||||
# the real lines: hw/vendor/pulp_riscv_dbg/tb/unused/SimDTM.sv:38-41
|
||||
# (opentitan, read-only there), the §11 skip this item closes
|
||||
module SimDTM (
|
||||
input clk,
|
||||
output [31:0] exit
|
||||
);
|
||||
|
||||
bit r_reset;
|
||||
|
||||
wire #0.1 __debug_req_ready = debug_req_ready;
|
||||
wire #0.1 __debug_resp_valid = debug_resp_valid;
|
||||
wire [31:0] #0.1 __debug_resp_bits_resp = {30'b0, debug_resp_bits_resp};
|
||||
wire [31:0] #0.1 __debug_resp_bits_data = debug_resp_bits_data;
|
||||
|
||||
endmodule
|
||||
----
|
||||
module SimDTM (input clk, output [31:0] exit);
|
||||
bit r_reset;
|
||||
|
||||
wire #0.1 __debug_req_ready = debug_req_ready;
|
||||
wire #0.1 __debug_resp_valid = debug_resp_valid;
|
||||
wire [31:0] #0.1 __debug_resp_bits_resp = {30'b0, debug_resp_bits_resp};
|
||||
wire [31:0] #0.1 __debug_resp_bits_data = debug_resp_bits_data;
|
||||
endmodule
|
||||
====
|
||||
# a comment written directly in front of the `#` is the delay's own —
|
||||
# `NetDelay::before_hash`, TODO §43.2. It was the `#SKIP` §38 recorded and
|
||||
# `verify.rs` refused the file for; the slot prints it back where it was
|
||||
# written, on either side of the data type.
|
||||
module m;
|
||||
wire /* c */ #5 x;
|
||||
wire [7:0] /* d */ #1 z;
|
||||
wire [3:0] /* one */ /* two */ #3 w;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire /* c */ #5 x;
|
||||
wire [7:0] /* d */ #1 z;
|
||||
wire [3:0] /* one */ /* two */ #3 w;
|
||||
endmodule
|
||||
====
|
||||
# the delay's other gap, between the `#` and the value: `after_hash`. Both
|
||||
# slots at once on one declaration, since the fuzzer asks for both
|
||||
module m;
|
||||
wire # /* why */ 5 x;
|
||||
wire [7:0] /* a */ # /* b */ 1 z = q;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire # /* why */ 5 x;
|
||||
wire [7:0] /* a */ # /* b */ 1 z = q;
|
||||
endmodule
|
||||
====
|
||||
# a line comment in the same slot runs to end of line, so the `#` cannot
|
||||
# follow it: it starts the next one, the way the `wire #5 /* after */` case
|
||||
# below breaks before its declarator
|
||||
module m;
|
||||
wire // why the delay
|
||||
#2 y;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire // why the delay
|
||||
#2 y;
|
||||
endmodule
|
||||
====
|
||||
# the other three gaps around a delay do have slots and round-trip
|
||||
module m;
|
||||
(* keep *) wire [3:0] #2 k = j;
|
||||
wire #5 /* after */ x;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
(* keep *)
|
||||
wire [3:0] #2 k = j;
|
||||
wire #5 /* after */
|
||||
x;
|
||||
endmodule
|
||||
====
|
||||
# a line comment after a gate instance's comma ends the line: the next
|
||||
# instance continues one level in (§45's QA; the module-instantiation
|
||||
# printer already did this)
|
||||
module m;
|
||||
and #(2, 3) g0 (y, a), // p
|
||||
g1 (z, b);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
and #(2, 3) g0 (y, a), // p
|
||||
g1 (z, b);
|
||||
endmodule
|
||||
@@ -0,0 +1,386 @@
|
||||
# TODO §38.1 — two rival, bracket-balanced unit headers written across the
|
||||
# arms of one `ifdef region. The whole unit is one verbatim item, so it comes
|
||||
# back byte for byte apart from the block's own re-indent.
|
||||
# docs/features/parser-skips/README.md
|
||||
`ifdef A
|
||||
interface i ();
|
||||
`else
|
||||
interface i ();
|
||||
`endif
|
||||
wire tck;
|
||||
endinterface
|
||||
|
||||
parameter int AFTER = 1;
|
||||
----
|
||||
`ifdef A
|
||||
interface i ();
|
||||
`else
|
||||
interface i ();
|
||||
`endif
|
||||
wire tck;
|
||||
endinterface
|
||||
|
||||
parameter int AFTER = 1;
|
||||
====
|
||||
# a module spelling with a real port list and a closing label
|
||||
`ifdef SYNTHESIS
|
||||
module m (input a, output b);
|
||||
`else
|
||||
module m (input a, output b);
|
||||
`endif
|
||||
wire x;
|
||||
endmodule : m
|
||||
----
|
||||
`ifdef SYNTHESIS
|
||||
module m (input a, output b);
|
||||
`else
|
||||
module m (input a, output b);
|
||||
`endif
|
||||
wire x;
|
||||
endmodule : m
|
||||
====
|
||||
# the block's *relative* layout is what survives: the whole unit is dedented
|
||||
# to the item's own indent, exactly as every other verbatim block is
|
||||
`ifdef A
|
||||
interface i #(parameter int P = 1) ();
|
||||
`else
|
||||
interface i #(parameter int P = 2) ();
|
||||
`endif
|
||||
wire tck;
|
||||
endinterface
|
||||
----
|
||||
`ifdef A
|
||||
interface i #(parameter int P = 1) ();
|
||||
`else
|
||||
interface i #(parameter int P = 2) ();
|
||||
`endif
|
||||
wire tck;
|
||||
endinterface
|
||||
====
|
||||
# the real file: hw/dv/sv/jtag_agent/jtag_if.sv (opentitan), the §11
|
||||
# skip this item closes. Read-only there; copied here verbatim.
|
||||
// Copyright lowRISC contributors (OpenTitan project).
|
||||
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// TODO(#24580): A JTAG UVM agent should configure the JTAG frequency (and not this interface)
|
||||
`ifdef GATE_LEVEL
|
||||
// jtag interface with default 24MHz tck for GLS
|
||||
interface jtag_if #(parameter int unsigned JtagDefaultTckPeriodPs = 41_664) ();
|
||||
`else
|
||||
// jtag interface with default 50MHz tck for faster DV simulations
|
||||
interface jtag_if #(parameter int unsigned JtagDefaultTckPeriodPs = 20_000) ();
|
||||
`endif
|
||||
|
||||
// interface pins
|
||||
wire tck;
|
||||
wire trst_n;
|
||||
wire tms;
|
||||
wire tdi;
|
||||
wire tdo;
|
||||
|
||||
// Is this interface being driven (through _drive_active and the clocking blocks), or is it just
|
||||
// observing some signals from the wider simulation?
|
||||
//
|
||||
// The flag is defined as a wire with a weak pull-up. This ensures that a testbench that doesn't
|
||||
// customise is_active will see the interface be driven actively, but allows a testbench that
|
||||
// *does* want to customise the signal to pull it low.
|
||||
wire is_active;
|
||||
assign (weak0, weak1) is_active = 1'b1;
|
||||
|
||||
// Should this interface generate a local tck signal? To enable that, set tck_en as well as
|
||||
// is_active.
|
||||
bit tck_en;
|
||||
|
||||
// Output-enable flags for tms, tdi, tdo (which only have an effect if is_active is true). The
|
||||
// default configuration enables tms and tdi, so acts as the root of the JTAG tree plus the
|
||||
// "previous device in the scan chain".
|
||||
bit tms_oe = 1'b1;
|
||||
bit tdi_oe = 1'b1;
|
||||
bit tdo_oe = 1'b0;
|
||||
|
||||
logic _tck_internal, _trst_n_internal, _tms_internal, _tdi_internal, _tdo_internal;
|
||||
assign tck = (is_active === 1'b1) ? _tck_internal : 'z;
|
||||
assign trst_n = (is_active === 1'b1) ? _trst_n_internal : 'z;
|
||||
assign tms = ((is_active === 1'b1) && tms_oe) ? _tms_internal : 'z;
|
||||
assign tdi = ((is_active === 1'b1) && tdi_oe) ? _tdi_internal : 'z;
|
||||
assign tdo = ((is_active === 1'b1) && tdo_oe) ? _tdo_internal : 'z;
|
||||
|
||||
// Use negedge to drive jtag inputs because design also use posedge clock edge to sample.
|
||||
clocking host_cb @(negedge tck);
|
||||
default output #1ns;
|
||||
output tms = _tms_internal;
|
||||
output tdi = _tdi_internal;
|
||||
input tdo;
|
||||
endclocking
|
||||
modport host_mp(clocking host_cb, output trst_n);
|
||||
|
||||
clocking device_cb @(posedge tck);
|
||||
input tms;
|
||||
input tdi;
|
||||
output tdo = _tdo_internal;
|
||||
endclocking
|
||||
modport device_mp(clocking device_cb, input trst_n);
|
||||
|
||||
clocking mon_cb @(posedge tck);
|
||||
input tms;
|
||||
input tdi;
|
||||
input tdo;
|
||||
endclocking
|
||||
modport mon_mp (clocking mon_cb, input trst_n);
|
||||
|
||||
// Signals for local tck
|
||||
int unsigned _tck_period_ps = JtagDefaultTckPeriodPs;
|
||||
int unsigned _clk_hi_ps, _clk_lo_ps;
|
||||
assign _clk_hi_ps = _tck_period_ps / 2;
|
||||
assign _clk_lo_ps = _tck_period_ps - _clk_hi_ps;
|
||||
|
||||
// Sets the TCK frequency.
|
||||
function automatic void set_tck_period_ps(int unsigned value);
|
||||
_tck_period_ps = value;
|
||||
endfunction
|
||||
|
||||
function automatic int unsigned get_tck_period_ps();
|
||||
return _tck_period_ps;
|
||||
endfunction
|
||||
|
||||
// Wait for one TCK cycle
|
||||
//
|
||||
// This waits for TCK to clear and then be asserted (so is waiting for the next posedge), but
|
||||
// bounds the wait by _tck_period_ps (in case the clock has stopped).
|
||||
//
|
||||
// Waiting for !tck, then for tck ensures that we don't get any strange races when the clock is
|
||||
// enabled: no matter what the relative phase, we will definitely wait at least a half cycle.
|
||||
task automatic wait_one_tck();
|
||||
fork : isolation_fork begin
|
||||
fork
|
||||
begin
|
||||
wait(!tck);
|
||||
wait(tck);
|
||||
end
|
||||
#(_tck_period_ps * 1ps);
|
||||
join_any
|
||||
disable fork;
|
||||
end join
|
||||
endtask
|
||||
|
||||
// Wait for the given number of cycles of TCK
|
||||
task automatic wait_tck(int cycles);
|
||||
repeat (cycles) wait_one_tck();
|
||||
endtask
|
||||
|
||||
// Start asserting a test reset through trst_n (no effect if the interface is not active)
|
||||
function automatic void assert_test_reset();
|
||||
_trst_n_internal <= 1'b0;
|
||||
endfunction
|
||||
|
||||
// Clear any test reset asserted through trst_n (no effect if the interface is not active)
|
||||
function automatic void clear_test_reset();
|
||||
_trst_n_internal <= 1'b1;
|
||||
endfunction
|
||||
|
||||
// Assert a test reset through trst_n (no effect if the interface is not active)
|
||||
task automatic do_trst_n(int cycles = $urandom_range(5, 20));
|
||||
assert_test_reset();
|
||||
wait_tck(cycles);
|
||||
clear_test_reset();
|
||||
endtask
|
||||
|
||||
// Drive _tck_internal with period _tck_period_ps whenever tck_en is high. If active is true, this
|
||||
// gets used to drive the tck signal.
|
||||
task automatic _drive_active();
|
||||
forever begin
|
||||
wait(tck_en);
|
||||
fork : isolation_fork begin
|
||||
fork
|
||||
wait(!tck_en);
|
||||
forever begin
|
||||
_tck_internal = 1'b1;
|
||||
#(_clk_hi_ps * 1ps);
|
||||
_tck_internal = 1'b0;
|
||||
#(_clk_lo_ps * 1ps);
|
||||
end
|
||||
join_any
|
||||
disable fork;
|
||||
end join
|
||||
end
|
||||
endtask
|
||||
|
||||
initial begin
|
||||
_tck_internal = 1'b1;
|
||||
forever begin
|
||||
wait(is_active === 1'b1);
|
||||
fork : isolation_fork begin
|
||||
fork
|
||||
wait(is_active !== 1'b1);
|
||||
_drive_active();
|
||||
join_any
|
||||
disable fork;
|
||||
end join
|
||||
end
|
||||
end
|
||||
|
||||
endinterface
|
||||
----
|
||||
// Copyright lowRISC contributors (OpenTitan project).
|
||||
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// TODO(#24580): A JTAG UVM agent should configure the JTAG frequency (and not this interface)
|
||||
`ifdef GATE_LEVEL
|
||||
// jtag interface with default 24MHz tck for GLS
|
||||
interface jtag_if #(parameter int unsigned JtagDefaultTckPeriodPs = 41_664) ();
|
||||
`else
|
||||
// jtag interface with default 50MHz tck for faster DV simulations
|
||||
interface jtag_if #(parameter int unsigned JtagDefaultTckPeriodPs = 20_000) ();
|
||||
`endif
|
||||
|
||||
// interface pins
|
||||
wire tck;
|
||||
wire trst_n;
|
||||
wire tms;
|
||||
wire tdi;
|
||||
wire tdo;
|
||||
|
||||
// Is this interface being driven (through _drive_active and the clocking blocks), or is it just
|
||||
// observing some signals from the wider simulation?
|
||||
//
|
||||
// The flag is defined as a wire with a weak pull-up. This ensures that a testbench that doesn't
|
||||
// customise is_active will see the interface be driven actively, but allows a testbench that
|
||||
// *does* want to customise the signal to pull it low.
|
||||
wire is_active;
|
||||
assign (weak0, weak1) is_active = 1'b1;
|
||||
|
||||
// Should this interface generate a local tck signal? To enable that, set tck_en as well as
|
||||
// is_active.
|
||||
bit tck_en;
|
||||
|
||||
// Output-enable flags for tms, tdi, tdo (which only have an effect if is_active is true). The
|
||||
// default configuration enables tms and tdi, so acts as the root of the JTAG tree plus the
|
||||
// "previous device in the scan chain".
|
||||
bit tms_oe = 1'b1;
|
||||
bit tdi_oe = 1'b1;
|
||||
bit tdo_oe = 1'b0;
|
||||
|
||||
logic _tck_internal, _trst_n_internal, _tms_internal, _tdi_internal, _tdo_internal;
|
||||
assign tck = (is_active === 1'b1) ? _tck_internal : 'z;
|
||||
assign trst_n = (is_active === 1'b1) ? _trst_n_internal : 'z;
|
||||
assign tms = ((is_active === 1'b1) && tms_oe) ? _tms_internal : 'z;
|
||||
assign tdi = ((is_active === 1'b1) && tdi_oe) ? _tdi_internal : 'z;
|
||||
assign tdo = ((is_active === 1'b1) && tdo_oe) ? _tdo_internal : 'z;
|
||||
|
||||
// Use negedge to drive jtag inputs because design also use posedge clock edge to sample.
|
||||
clocking host_cb @(negedge tck);
|
||||
default output #1ns;
|
||||
output tms = _tms_internal;
|
||||
output tdi = _tdi_internal;
|
||||
input tdo;
|
||||
endclocking
|
||||
modport host_mp(clocking host_cb, output trst_n);
|
||||
|
||||
clocking device_cb @(posedge tck);
|
||||
input tms;
|
||||
input tdi;
|
||||
output tdo = _tdo_internal;
|
||||
endclocking
|
||||
modport device_mp(clocking device_cb, input trst_n);
|
||||
|
||||
clocking mon_cb @(posedge tck);
|
||||
input tms;
|
||||
input tdi;
|
||||
input tdo;
|
||||
endclocking
|
||||
modport mon_mp (clocking mon_cb, input trst_n);
|
||||
|
||||
// Signals for local tck
|
||||
int unsigned _tck_period_ps = JtagDefaultTckPeriodPs;
|
||||
int unsigned _clk_hi_ps, _clk_lo_ps;
|
||||
assign _clk_hi_ps = _tck_period_ps / 2;
|
||||
assign _clk_lo_ps = _tck_period_ps - _clk_hi_ps;
|
||||
|
||||
// Sets the TCK frequency.
|
||||
function automatic void set_tck_period_ps(int unsigned value);
|
||||
_tck_period_ps = value;
|
||||
endfunction
|
||||
|
||||
function automatic int unsigned get_tck_period_ps();
|
||||
return _tck_period_ps;
|
||||
endfunction
|
||||
|
||||
// Wait for one TCK cycle
|
||||
//
|
||||
// This waits for TCK to clear and then be asserted (so is waiting for the next posedge), but
|
||||
// bounds the wait by _tck_period_ps (in case the clock has stopped).
|
||||
//
|
||||
// Waiting for !tck, then for tck ensures that we don't get any strange races when the clock is
|
||||
// enabled: no matter what the relative phase, we will definitely wait at least a half cycle.
|
||||
task automatic wait_one_tck();
|
||||
fork : isolation_fork begin
|
||||
fork
|
||||
begin
|
||||
wait(!tck);
|
||||
wait(tck);
|
||||
end
|
||||
#(_tck_period_ps * 1ps);
|
||||
join_any
|
||||
disable fork;
|
||||
end join
|
||||
endtask
|
||||
|
||||
// Wait for the given number of cycles of TCK
|
||||
task automatic wait_tck(int cycles);
|
||||
repeat (cycles) wait_one_tck();
|
||||
endtask
|
||||
|
||||
// Start asserting a test reset through trst_n (no effect if the interface is not active)
|
||||
function automatic void assert_test_reset();
|
||||
_trst_n_internal <= 1'b0;
|
||||
endfunction
|
||||
|
||||
// Clear any test reset asserted through trst_n (no effect if the interface is not active)
|
||||
function automatic void clear_test_reset();
|
||||
_trst_n_internal <= 1'b1;
|
||||
endfunction
|
||||
|
||||
// Assert a test reset through trst_n (no effect if the interface is not active)
|
||||
task automatic do_trst_n(int cycles = $urandom_range(5, 20));
|
||||
assert_test_reset();
|
||||
wait_tck(cycles);
|
||||
clear_test_reset();
|
||||
endtask
|
||||
|
||||
// Drive _tck_internal with period _tck_period_ps whenever tck_en is high. If active is true, this
|
||||
// gets used to drive the tck signal.
|
||||
task automatic _drive_active();
|
||||
forever begin
|
||||
wait(tck_en);
|
||||
fork : isolation_fork begin
|
||||
fork
|
||||
wait(!tck_en);
|
||||
forever begin
|
||||
_tck_internal = 1'b1;
|
||||
#(_clk_hi_ps * 1ps);
|
||||
_tck_internal = 1'b0;
|
||||
#(_clk_lo_ps * 1ps);
|
||||
end
|
||||
join_any
|
||||
disable fork;
|
||||
end join
|
||||
end
|
||||
endtask
|
||||
|
||||
initial begin
|
||||
_tck_internal = 1'b1;
|
||||
forever begin
|
||||
wait(is_active === 1'b1);
|
||||
fork : isolation_fork begin
|
||||
fork
|
||||
wait(is_active !== 1'b1);
|
||||
_drive_active();
|
||||
join_any
|
||||
disable fork;
|
||||
end join
|
||||
end
|
||||
end
|
||||
|
||||
endinterface
|
||||
@@ -2350,6 +2350,16 @@ const RTL_FIXTURES: &[&str] = &[
|
||||
"package p;\n typedef struct packed {\n logic [3:0] hi;\n logic [3:0] lo;\n } word_t;\n typedef enum logic [1:0] {A = 2'd0, B, C} st_e;\nendpackage\n",
|
||||
"module m;\n sub #(.W(8)) u0 (.clk(clk), .d(d[3:0]), .q());\nendmodule\n",
|
||||
"module m;\n assign y = cond ? a[3:0] : pkg::f(b).c;\nendmodule\n",
|
||||
// A net delay on either side of the data type: the gap in front of the
|
||||
// `#` is `NetDelay::before_hash` (TODO §43.2), and the fuzzer is what
|
||||
// says the other gaps around it kept their owners.
|
||||
"module m;\n wire #5 a;\n wire [7:0] #1 b = c;\nendmodule\n",
|
||||
// A delay *list*: the `min:typ:max` spelling a net and a continuous
|
||||
// assignment take, and the `(rise, fall)` spelling only a gate takes
|
||||
// (TODO §45.4). The gaps around the `(`, the two `:` and the `,` had no
|
||||
// owner until this round — `MinTypMaxComments`, `DelayValue`, and the
|
||||
// gate's own `before_hash`/`after_hash`/`before_args`/`before_semi`.
|
||||
"module m;\n wire #(1:2:3) a;\n assign #(1:2:3) z = a;\n and #(2, 3) g1 (y, a, b);\nendmodule\n",
|
||||
];
|
||||
|
||||
#[test]
|
||||
@@ -2357,8 +2367,9 @@ fn a_comment_in_every_rtl_gap_still_formats() {
|
||||
assert_no_failing_gaps("RTL", RTL_FIXTURES, EXPECTED_RTL_GAPS);
|
||||
}
|
||||
|
||||
/// Inter-token gaps across [`RTL_FIXTURES`].
|
||||
const EXPECTED_RTL_GAPS: usize = 352;
|
||||
/// Inter-token gaps across [`RTL_FIXTURES`]. 374 before TODO §45.4 added the
|
||||
/// delay-list fixture, whose 45 gaps brought the total here.
|
||||
const EXPECTED_RTL_GAPS: usize = 419;
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Vendor and formal collateral — `vendor-formal-grammar`
|
||||
@@ -2888,3 +2899,106 @@ fn a_structured_assertion_may_be_relaid_out() {
|
||||
assert!(out.contains("lbl: assert property (@(posedge clk) disable iff (rst)"), "{out}");
|
||||
assert_eq!(format_source(&out, &Config::default()).expect("and is a fixed point"), out);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The delay list's new comment slots — `docs/features/small-items-4/README.md`
|
||||
//
|
||||
// `verify.rs` was not touched and no normalization was widened; these are the
|
||||
// standing attack pairs CLAUDE.md invariant 4 asks for anyway, one per token
|
||||
// a slot added by TODO §45.4 is defined *between*. Each moves the comment
|
||||
// across exactly that token, and each must be refused.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_delay_comment_moved_across_a_min_typ_max_colon_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n wire #(1 /*c*/ : 2 : 3) w;\nendmodule\n",
|
||||
"module m;\n wire #(1 : /*c*/ 2 : 3) w;\nendmodule\n",
|
||||
);
|
||||
expect_divergence(
|
||||
"module m;\n wire #(1 : 2 /*c*/ : 3) w;\nendmodule\n",
|
||||
"module m;\n wire #(1 : 2 : /*c*/ 3) w;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delay_comment_moved_across_the_lists_brackets_is_rejected() {
|
||||
// The `(` of a one-value delay, whose slots are its `ExprKind::Paren`'s.
|
||||
expect_divergence(
|
||||
"module m;\n wire # /*c*/ (1:2:3) w;\nendmodule\n",
|
||||
"module m;\n wire #( /*c*/ 1:2:3) w;\nendmodule\n",
|
||||
);
|
||||
// And the `)`.
|
||||
expect_divergence(
|
||||
"module m;\n wire #(1:2:3 /*c*/ ) w;\nendmodule\n",
|
||||
"module m;\n wire #(1:2:3) /*c*/ w;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gate_delay_comment_moved_across_the_hash_or_a_comma_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n and /*c*/ #(2, 3) g (y, a);\nendmodule\n",
|
||||
"module m;\n and # /*c*/ (2, 3) g (y, a);\nendmodule\n",
|
||||
);
|
||||
expect_divergence(
|
||||
"module m;\n and #(2 /*c*/, 3) g (y, a);\nendmodule\n",
|
||||
"module m;\n and #(2, /*c*/ 3) g (y, a);\nendmodule\n",
|
||||
);
|
||||
// The gate instance's own two new slots: before its `(` and before the `;`.
|
||||
expect_divergence(
|
||||
"module m;\n and #(2, 3) g /*c*/ (y, a);\nendmodule\n",
|
||||
"module m;\n and #(2, 3) g ( /*c*/ y, a);\nendmodule\n",
|
||||
);
|
||||
expect_divergence(
|
||||
"module m;\n and #(2, 3) g (y, a) /*c*/ ;\nendmodule\n",
|
||||
"module m;\n and #(2, 3) g (y, a); /*c*/\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_continuous_assignments_delay_comment_moved_across_it_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n assign # /*c*/ (5) y = a;\nendmodule\n",
|
||||
"module m;\n assign /*c*/ #(5) y = a;\nendmodule\n",
|
||||
);
|
||||
expect_divergence(
|
||||
"module m;\n assign #(5) /*c*/ y = a;\nendmodule\n",
|
||||
"module m;\n assign /*c*/ #(5) y = a;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_delay_list_comment_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n and #(2 /*c*/, 3) g (y, a);\nendmodule\n",
|
||||
"module m;\n and #(2, 3) g (y, a);\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The inline aggregate as a parameter-override argument — TODO §45.3
|
||||
//
|
||||
// A construct the parser refused until this round is a construct the safety
|
||||
// net had never been asked about. These say it is asked now.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_dropped_member_of_an_inline_aggregate_override_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n sub #(.T(struct packed {logic a; logic b;})) u ();\nendmodule\n",
|
||||
"module m;\n sub #(.T(struct packed {logic a;})) u ();\nendmodule\n",
|
||||
);
|
||||
expect_divergence(
|
||||
"module m;\n sub #(.T(enum logic [1:0] {A, B})) u ();\nendmodule\n",
|
||||
"module m;\n sub #(.T(enum logic [1:0] {A})) u ();\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_packed_keyword_in_an_override_argument_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n sub #(.T(struct packed {logic a;})) u ();\nendmodule\n",
|
||||
"module m;\n sub #(.T(struct {logic a;})) u ();\nendmodule\n",
|
||||
);
|
||||
}
|
||||
@@ -12,6 +12,12 @@ vlog_parser = { path = "../vlog_parser" }
|
||||
# workspace crate that answers that, and it depends on `vlog_parser` alone, so
|
||||
# this adds no external code — see docs/features/semantic-lints/README.md.
|
||||
vlog_semantic = { path = "../vlog_semantic" }
|
||||
# A waiver file's `--location` is matched exactly the way an `--exclude`
|
||||
# pattern is, and that matcher is `lucisv_core::walk::is_excluded`. Depending
|
||||
# on it rather than copying it is the only way the two can be *the same*
|
||||
# semantics; `lucisv_core` itself has no dependencies at all, so this adds no
|
||||
# external code and closes no loop — see docs/features/waiver-files/README.md.
|
||||
lucisv_core = { path = "../lucisv_core" }
|
||||
|
||||
[dev-dependencies]
|
||||
# Tests only: the .lint case harness asserts that a lint fix never produces
|
||||
|
||||
@@ -39,6 +39,7 @@ mod violation;
|
||||
mod visit;
|
||||
mod vscode;
|
||||
mod waiver;
|
||||
mod waiver_file;
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -58,6 +59,7 @@ pub use violation::{apply_fixes, Applicability, Fix, Fixed, Violation};
|
||||
pub use vlog_semantic::words;
|
||||
pub use vscode::{rule_setting, severity_setting, vscode_lint_settings, RULE_CHOICES};
|
||||
pub use waiver::UNUSED_WAIVER;
|
||||
pub use waiver_file::{ExternalWaivers, UnusedReport, WaiverUse};
|
||||
|
||||
use waiver::Waivers;
|
||||
|
||||
@@ -74,14 +76,32 @@ pub fn run(source: &str, path: Option<PathBuf>, enabled: &[&'static dyn Rule]) -
|
||||
/// The result is sorted by position, then by rule name, so two runs over the
|
||||
/// same file print in the same order whatever order the registry has.
|
||||
pub fn lint(ctx: &LintContext, enabled: &[&'static dyn Rule]) -> Vec<Violation> {
|
||||
lint_with(ctx, enabled, &ExternalWaivers::default()).0
|
||||
}
|
||||
|
||||
/// [`lint`] with the run's external waiver files applied too, reporting which
|
||||
/// of their directives fired.
|
||||
///
|
||||
/// **Precedence is union**: a violation is dropped when an inline waiver *or*
|
||||
/// an external one covers it, and one both cover marks both used, so neither
|
||||
/// is then reported as dead. The usage half is the caller's to keep — only a
|
||||
/// whole run knows whether a `--location` matched some file somewhere, which
|
||||
/// is why `lucisv check` reports unused external waivers and the server does
|
||||
/// not. See `docs/features/waiver-files/README.md`.
|
||||
pub fn lint_with(
|
||||
ctx: &LintContext,
|
||||
enabled: &[&'static dyn Rule],
|
||||
external: &ExternalWaivers,
|
||||
) -> (Vec<Violation>, WaiverUse) {
|
||||
let names: Vec<&'static str> = enabled.iter().map(|rule| rule.name()).collect();
|
||||
let mut waivers = Waivers::collect(ctx);
|
||||
let mut used = WaiverUse::default();
|
||||
|
||||
let mut found = Vec::new();
|
||||
for rule in enabled {
|
||||
found.extend(rule.check(ctx));
|
||||
}
|
||||
let mut kept = waivers.filter(ctx, found);
|
||||
let mut kept = waive(ctx, &mut waivers, external, &mut used, found);
|
||||
|
||||
if names.contains(&UNUSED_WAIVER) {
|
||||
// `unused-waiver` findings are themselves waivable, which is circular:
|
||||
@@ -92,7 +112,7 @@ pub fn lint(ctx: &LintContext, enabled: &[&'static dyn Rule]) -> Vec<Violation>
|
||||
loop {
|
||||
let before = waivers.used_count();
|
||||
let unused = waivers.unused(&names);
|
||||
let surviving = waivers.filter(ctx, unused);
|
||||
let surviving = waive(ctx, &mut waivers, external, &mut used, unused);
|
||||
if waivers.used_count() == before {
|
||||
kept.extend(surviving);
|
||||
break;
|
||||
@@ -104,7 +124,31 @@ pub fn lint(ctx: &LintContext, enabled: &[&'static dyn Rule]) -> Vec<Violation>
|
||||
(a.span.start, a.span.end, a.rule).cmp(&(b.span.start, b.span.end, b.rule))
|
||||
});
|
||||
stamp_severities(&mut kept);
|
||||
kept
|
||||
(kept, used)
|
||||
}
|
||||
|
||||
/// The violations neither an inline waiver nor an external one covers.
|
||||
///
|
||||
/// Both are always asked — never `||` short-circuited — because a violation
|
||||
/// two waivers cover has to mark both of them used.
|
||||
fn waive(
|
||||
ctx: &LintContext,
|
||||
inline: &mut Waivers,
|
||||
external: &ExternalWaivers,
|
||||
used: &mut WaiverUse,
|
||||
violations: Vec<Violation>,
|
||||
) -> Vec<Violation> {
|
||||
let path = ctx.path();
|
||||
violations
|
||||
.into_iter()
|
||||
.filter(|violation| {
|
||||
let (line, _) = ctx.line_index().line_col(violation.span.start);
|
||||
let inline_waived = inline.covers(violation.rule, line);
|
||||
let external_waived =
|
||||
!external.is_empty() && external.covers(path, violation.rule, line, used);
|
||||
!(inline_waived || external_waived)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Gives every finding the class its rule declares.
|
||||
|
||||
@@ -90,6 +90,7 @@ fn collect_body(item: &Item, out: &mut Vec<SignalDecl>) {
|
||||
collect_body(inner, out);
|
||||
}
|
||||
}
|
||||
ItemKind::GenBlock(b) => block(b, out),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
block(&gen_if.then, out);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
|
||||
@@ -141,6 +141,9 @@ fn item_labels(out: &mut Vec<Violation>, item: &Item) {
|
||||
}
|
||||
}
|
||||
ItemKind::GenFor(gen_for) => check_gen_block(out, &gen_for.body),
|
||||
// A bare `begin … end` standing as an item (§36.1) is the same node
|
||||
// without a header: its label pair is checked exactly like an arm's.
|
||||
ItemKind::GenBlock(block) => check_gen_block(out, block),
|
||||
ItemKind::GenCase(gen_case) => {
|
||||
for case_item in &gen_case.items {
|
||||
check_gen_block(out, &case_item.body);
|
||||
@@ -285,6 +288,23 @@ mod tests {
|
||||
assert_eq!(violations(generate).len(), 1, "{:?}", violations(generate));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_block_at_module_scope_is_checked_like_a_generate_arm() {
|
||||
// §36.1: the block is a node now, so its own footer is checked. Not
|
||||
// legal at module scope at all (`module-begin-block` says so), but a
|
||||
// mismatched footer is the compile error this rule exists for.
|
||||
let src = "module m;\n\
|
||||
begin : fetch\n\
|
||||
wire a;\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");
|
||||
let ok = "module m;\n begin : fetch\n wire a;\n end : fetch\nendmodule\n";
|
||||
assert!(violations(ok).is_empty(), "{:?}", violations(ok));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nested_block_is_matched_against_its_own_header() {
|
||||
let src = "module m;\n\
|
||||
|
||||
@@ -4,7 +4,7 @@ use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::ast::{Item, ItemKind, RawText};
|
||||
use vlog_parser::ast::{Item, ItemKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
@@ -34,14 +34,15 @@ impl Rule for ModuleBeginBlock {
|
||||
against them is wrong. Verible's `module-begin-block` (\"Checks that \
|
||||
there are no begin-end blocks declared at the module level.\", \
|
||||
enabled by default) is the same rule and the same default.\n\n\
|
||||
lucisv's **parser rejects** the construct rather than recovering it \
|
||||
as a block, so what this rule reads is the error leaf error recovery \
|
||||
left at module scope whose first token is `begin`. The finding is \
|
||||
exact — no legal module item starts with that keyword — but the rest \
|
||||
of the module is lost to recovery, so a file with one of these \
|
||||
reports little else. No automatic fix: whether the block should \
|
||||
become a generate block, an `always` or nothing at all is the \
|
||||
author's to decide."
|
||||
lucisv's parser **recovers** the construct: in error-tolerant mode \
|
||||
the block is read as the unnamed generate block every tool that \
|
||||
accepts it makes of it, and a diagnostic is recorded at the `begin` \
|
||||
— so the file is still reported as not parsing cleanly and the \
|
||||
formatter still refuses to format it, but the items written inside \
|
||||
the block are visible to this rule and to every other one. What this \
|
||||
rule reads is that block standing where a module item belongs. No \
|
||||
automatic fix: whether the block should become a generate block, an \
|
||||
`always` or nothing at all is the author's to decide."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
@@ -61,28 +62,17 @@ impl Rule for ModuleBeginBlock {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `begin` keyword of an error leaf that is a `begin … end` block, or
|
||||
/// `None` for any other leaf.
|
||||
/// The `begin` keyword of an item that is a bare `begin … end` block, or
|
||||
/// `None` for any other item.
|
||||
///
|
||||
/// Shared with `v2001-generate-begin`, which asks the same question one scope
|
||||
/// further in: the two rules must agree about what a stray `begin` looks like,
|
||||
/// and one reading is how that is guaranteed.
|
||||
pub(crate) fn begin_block(item: &Item) -> Option<TextRange> {
|
||||
let ItemKind::Error(raw) = &item.kind else { return None };
|
||||
if !first_word_is_begin(raw) {
|
||||
return None;
|
||||
}
|
||||
Some(TextRange::new(raw.span.start, raw.span.start + 5))
|
||||
}
|
||||
|
||||
/// True when the leaf's first token is exactly the keyword `begin`.
|
||||
fn first_word_is_begin(raw: &RawText) -> bool {
|
||||
let rest = match raw.text.strip_prefix("begin") {
|
||||
Some(rest) => rest,
|
||||
None => return false,
|
||||
};
|
||||
// `beginning` is an identifier, not the keyword.
|
||||
!rest.starts_with(|c: char| c.is_alphanumeric() || c == '_' || c == '$')
|
||||
let ItemKind::GenBlock(block) = &item.kind else { return None };
|
||||
// The node's span opens at the keyword, whatever the item's own span does
|
||||
// with the attributes written in front of it.
|
||||
Some(TextRange::new(block.span.start, block.span.start + 5))
|
||||
}
|
||||
|
||||
/// Calls `f` on every item written directly in a module, interface or program
|
||||
@@ -156,6 +146,33 @@ mod tests {
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_block_keeps_its_items_and_the_module_keeps_the_items_after_it() {
|
||||
// §36.1: the block is a node now, not an error leaf, so what is
|
||||
// written inside it and after it is still there for every rule.
|
||||
// Before, recovery skipped to `endmodule` and the `defparam` was
|
||||
// inside one opaque leaf.
|
||||
let src = "module m;\n begin\n defparam u.P = 1;\n end\n wire a;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "begin");
|
||||
let ctx = LintContext::new(src, None);
|
||||
let inside = crate::rules::forbid_defparam::ForbidDefparam.check(&ctx);
|
||||
assert_eq!(inside.len(), 1, "a rule reading the block's items: {inside:?}");
|
||||
assert_eq!(ctx.file().items.len(), 1, "one module");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_outermost_block_of_a_nest_is_reported_at_module_scope() {
|
||||
// The inner block is written inside a block, not at module scope, so
|
||||
// it is not this rule's finding — exactly as before §36.1, when the
|
||||
// whole nest was one leaf whose first token was the outer `begin`.
|
||||
let src = "module m;\n begin\n begin\n wire a;\n end\n end\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(found[0].span.start, 12, "the outer `begin`");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_parses_cleanly_has_nothing_to_report() {
|
||||
let src = "module m;\n wire a;\nendmodule\n";
|
||||
|
||||
@@ -68,13 +68,6 @@ impl Rule for UndrivenNet {
|
||||
if intentionally_unused(&decl.name) || !signals.judgeable(decl) || decl.has_init {
|
||||
continue;
|
||||
}
|
||||
// A name another file in the project writes down may be driven
|
||||
// from there — a hierarchical assignment, a `force` in a
|
||||
// testbench, a `bind`-ed override — none of which this file can
|
||||
// see. Silence is the only honest answer.
|
||||
if ctx.mentioned_elsewhere(&decl.name) {
|
||||
continue;
|
||||
}
|
||||
let Some(usage) = signals.usage(decl) else { continue };
|
||||
// A `release`/`deassign` is a write that establishes no value, so
|
||||
// it is not what saves a signal from this rule.
|
||||
@@ -82,6 +75,25 @@ impl Rule for UndrivenNet {
|
||||
if signals.connected(decl) || driven || usage.reads == 0 {
|
||||
continue;
|
||||
}
|
||||
// A name another file in the project writes down may be driven
|
||||
// from there — a hierarchical assignment, a `force` in a
|
||||
// testbench, a `bind`-ed override — none of which this file can
|
||||
// see. Silence is the only honest answer.
|
||||
//
|
||||
// **Asked last, of the handful of declarations that would
|
||||
// otherwise be reported**, and not second, of every declaration in
|
||||
// the file: the oracle walks every indexed file's word list per
|
||||
// question (`WorkspaceIndex::files_mentioning`), so at the position
|
||||
// this check used to sit at, a 42 000-line buffer asked it four
|
||||
// thousand times and the rule cost 1.6 s of every `didOpen` and
|
||||
// every keystroke flush. The guards above are all local and all
|
||||
// O(1)-ish, the whole condition is one conjunction of `continue`s,
|
||||
// and `unused-signal` — the twin rule with the same oracle — has
|
||||
// always asked last. Same findings, in the same order
|
||||
// (`docs/features/didopen-cost/README.md`).
|
||||
if ctx.mentioned_elsewhere(&decl.name) {
|
||||
continue;
|
||||
}
|
||||
found.push(Violation::new(
|
||||
NAME,
|
||||
format!("`{}` is read but never driven", decl.name),
|
||||
@@ -107,17 +119,56 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// An oracle that says exactly these names are mentioned in another file.
|
||||
struct Elsewhere(&'static [&'static str]);
|
||||
/// An oracle that says exactly these names are mentioned in another file,
|
||||
/// and counts how often it was asked.
|
||||
struct Elsewhere(&'static [&'static str], std::sync::atomic::AtomicUsize);
|
||||
|
||||
impl Elsewhere {
|
||||
fn new(names: &'static [&'static str]) -> Elsewhere {
|
||||
Elsewhere(names, std::sync::atomic::AtomicUsize::new(0))
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::MentionOracle for Elsewhere {
|
||||
fn mentioned_elsewhere(&self, name: &str) -> bool {
|
||||
self.1.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
self.0.contains(&name)
|
||||
}
|
||||
}
|
||||
|
||||
/// TODO.md §46: the oracle is asked about the declarations that would
|
||||
/// otherwise be **reported**, not about every declaration in the file.
|
||||
///
|
||||
/// One question per real candidate is the whole of the fix: the server's
|
||||
/// oracle walks every indexed file's word list per question, so asking it
|
||||
/// ahead of the local guards cost 1.6 s of every `didOpen` of opentitan's
|
||||
/// 42 000-line `pinmux_reg_top.sv` — see
|
||||
/// `docs/features/didopen-cost/README.md`. Asserted on the count, because
|
||||
/// the findings alone cannot tell the two orders apart.
|
||||
#[test]
|
||||
fn the_project_is_asked_only_about_the_signals_that_would_be_reported() {
|
||||
// Ten signals: nine driven and read, one read and undriven.
|
||||
let mut src = String::from("module m (output logic q);\n");
|
||||
for k in 0..9 {
|
||||
src.push_str(&format!(" wire d{k};\n assign d{k} = 1'b0;\n"));
|
||||
}
|
||||
src.push_str(" wire lonely;\n assign q = lonely");
|
||||
for k in 0..9 {
|
||||
src.push_str(&format!(" ^ d{k}"));
|
||||
}
|
||||
src.push_str(";\nendmodule\n");
|
||||
|
||||
let oracle = Elsewhere::new(&[]);
|
||||
let ctx = LintContext::new(&src, None).with_oracle(&oracle);
|
||||
let found = UndrivenNet.check(&ctx);
|
||||
assert_eq!(found.len(), 1, "only the undriven one: {found:#?}");
|
||||
assert!(found[0].message.contains("lonely"), "{:?}", found[0].message);
|
||||
let asked = oracle.1.load(std::sync::atomic::Ordering::Relaxed);
|
||||
assert_eq!(asked, 1, "the project was asked about the driven signals too");
|
||||
}
|
||||
|
||||
fn names_in_a_project(src: &str, elsewhere: &'static [&'static str]) -> Vec<String> {
|
||||
let oracle = Elsewhere(elsewhere);
|
||||
let oracle = Elsewhere::new(elsewhere);
|
||||
let ctx = LintContext::new(src, None).with_oracle(&oracle);
|
||||
UndrivenNet
|
||||
.check(&ctx)
|
||||
|
||||
@@ -36,11 +36,13 @@ impl Rule for V2001GenerateBegin {
|
||||
`v2001-generate-begin` (\"Checks that there are no generate-begin \
|
||||
blocks inside a generate region.\", enabled by default) is the same \
|
||||
rule and the same default.\n\n\
|
||||
Like `module-begin-block`, this reads the error leaf lucisv's parser \
|
||||
leaves where it refused the construct: an item inside a \
|
||||
`generate … endgenerate` whose first token is `begin`. No automatic \
|
||||
fix — deleting the two keywords re-indents the whole block, and \
|
||||
giving it a label instead is a different repair."
|
||||
Like `module-begin-block`, this reads the block lucisv's parser \
|
||||
recovers where it refuses the construct: an unnamed generate block \
|
||||
written directly inside a `generate … endgenerate`, kept in the tree \
|
||||
beside a diagnostic at its `begin`, so everything declared inside it \
|
||||
is still visible to the other rules. No automatic fix — deleting the \
|
||||
two keywords re-indents the whole block, and giving it a label \
|
||||
instead is a different repair."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
@@ -95,6 +97,18 @@ mod tests {
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_blocks_items_stay_visible_to_the_other_rules() {
|
||||
let src = "module m;\n generate\n begin : b\n defparam u.P = 1;\n end\n \
|
||||
endgenerate\n wire ok;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "begin");
|
||||
let inside =
|
||||
crate::rules::forbid_defparam::ForbidDefparam.check(&LintContext::new(src, None));
|
||||
assert_eq!(inside.len(), 1, "a rule reading the block's items: {inside:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_with_no_generate_region_is_silent() {
|
||||
assert!(violations("module m;\n wire a;\nendmodule\n").is_empty());
|
||||
|
||||
@@ -369,6 +369,7 @@ impl Scanner {
|
||||
}
|
||||
}
|
||||
ItemKind::GenerateRegion { items, .. } => self.items(items, module, true),
|
||||
ItemKind::GenBlock(b) => self.items(&b.items, module, true),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
self.items(&gen_if.then.items, module, true);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
|
||||
@@ -24,6 +24,7 @@ fn items(list: &[Item], f: &mut dyn FnMut(&Item)) {
|
||||
ItemKind::Class(class) => items(&class.items, f),
|
||||
ItemKind::Package { items: inner, .. } => items(inner, f),
|
||||
ItemKind::GenerateRegion { items: inner, .. } => items(inner, f),
|
||||
ItemKind::GenBlock(b) => items(&b.items, f),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
gen_block(&gen_if.then, f);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
@@ -103,6 +104,7 @@ fn scoped_items(list: &[Item], scope: ItemScope, f: &mut dyn FnMut(ItemScope, &I
|
||||
ItemKind::Package { items: inner, .. } => scoped_items(inner, ItemScope::Package, f),
|
||||
// A generate construct keeps the scope it was written in.
|
||||
ItemKind::GenerateRegion { items: inner, .. } => scoped_items(inner, scope, f),
|
||||
ItemKind::GenBlock(b) => scoped_items(&b.items, scope, f),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
scoped_items(&gen_if.then.items, scope, f);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
|
||||
@@ -113,26 +113,20 @@ impl Waivers {
|
||||
Waivers { entries }
|
||||
}
|
||||
|
||||
/// Drops the violations a waiver covers, marking those waivers used.
|
||||
pub(crate) fn filter(
|
||||
&mut self,
|
||||
ctx: &LintContext,
|
||||
violations: Vec<Violation>,
|
||||
) -> Vec<Violation> {
|
||||
violations
|
||||
.into_iter()
|
||||
.filter(|violation| {
|
||||
let (line, _) = ctx.line_index().line_col(violation.span.start);
|
||||
let mut waived = false;
|
||||
for entry in &mut self.entries {
|
||||
if entry.rule == violation.rule && entry.scope.covers(line) {
|
||||
entry.used = true;
|
||||
waived = true;
|
||||
}
|
||||
}
|
||||
!waived
|
||||
})
|
||||
.collect()
|
||||
/// True when some waiver covers `rule` at `line`, marking every waiver
|
||||
/// that does used.
|
||||
///
|
||||
/// Every one, not the first: a finding two waivers cover has both of them
|
||||
/// doing their job, and reporting the second as dead would be a lie.
|
||||
pub(crate) fn covers(&mut self, rule: &str, line: u32) -> bool {
|
||||
let mut waived = false;
|
||||
for entry in &mut self.entries {
|
||||
if entry.rule == rule && entry.scope.covers(line) {
|
||||
entry.used = true;
|
||||
waived = true;
|
||||
}
|
||||
}
|
||||
waived
|
||||
}
|
||||
|
||||
/// How many waivers have suppressed something so far. Grows only, which
|
||||
|
||||
@@ -0,0 +1,570 @@
|
||||
//! External waiver files: Verible's `waive` directives, written in a file of
|
||||
//! their own rather than in a comment in the RTL.
|
||||
//!
|
||||
//! Grammar (Verible's, so an existing `.waiver` file carries over unchanged) —
|
||||
//! one directive per line, `#` comments and blank lines ignored:
|
||||
//!
|
||||
//! ```text
|
||||
//! waive --rule=<rule> every line of every file
|
||||
//! waive --rule=<rule> --line=12 one line
|
||||
//! waive --rule=<rule> --line=12-20 a range, both ends included
|
||||
//! waive --rule=<rule> --location=legacy_top.sv the files that pattern names
|
||||
//! ```
|
||||
//!
|
||||
//! The one deliberate difference from Verible: `--location` is **not** a
|
||||
//! regular expression. It is matched exactly the way an `--exclude` pattern is
|
||||
//! ([`lucisv_core::walk::is_excluded`]), so a pattern means one thing across
|
||||
//! the whole tool; a pattern that looks like a regex is refused with a message
|
||||
//! saying so rather than silently matching nothing.
|
||||
//!
|
||||
//! Precedence is **union** with the inline waivers of `waiver.rs`: a violation
|
||||
//! is suppressed when either covers it, and a violation both cover marks both
|
||||
//! used. See `docs/features/waiver-files/README.md`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
use crate::registry::rule_by_name;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::waiver::UNUSED_WAIVER;
|
||||
|
||||
/// Every external waiver of one run, from any number of files.
|
||||
#[derive(Default)]
|
||||
pub struct ExternalWaivers {
|
||||
sources: Vec<Source>,
|
||||
directives: Vec<Directive>,
|
||||
}
|
||||
|
||||
/// One waiver file that was read. Its text is kept because an unused
|
||||
/// directive is reported at the line it was written on, and only the text
|
||||
/// turns that directive's span into a line and a column.
|
||||
struct Source {
|
||||
path: PathBuf,
|
||||
text: String,
|
||||
}
|
||||
|
||||
/// One `waive` directive.
|
||||
struct Directive {
|
||||
/// Index into [`ExternalWaivers::sources`].
|
||||
source: usize,
|
||||
/// The directive's own line, where an `unused-waiver` finding points.
|
||||
span: TextRange,
|
||||
/// The rule waived; always a name the registry knows.
|
||||
rule: String,
|
||||
/// `--line`: 1-based, both ends included. `None` is the whole file.
|
||||
lines: Option<(u32, u32)>,
|
||||
/// `--location`: an `--exclude` pattern. `None` is every file.
|
||||
location: Option<String>,
|
||||
}
|
||||
|
||||
/// Which external waivers have suppressed something.
|
||||
///
|
||||
/// One run's worth: the CLI lints its files in parallel and merges what each
|
||||
/// one used, because a `--location` pattern may cover files linted on several
|
||||
/// workers. Usage only ever grows.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct WaiverUse {
|
||||
used: Vec<bool>,
|
||||
}
|
||||
|
||||
impl WaiverUse {
|
||||
/// Folds another pass's usage into this one.
|
||||
pub fn merge(&mut self, other: &WaiverUse) {
|
||||
if self.used.len() < other.used.len() {
|
||||
self.used.resize(other.used.len(), false);
|
||||
}
|
||||
for (slot, fired) in self.used.iter_mut().zip(&other.used) {
|
||||
*slot |= *fired;
|
||||
}
|
||||
}
|
||||
|
||||
fn mark(&mut self, index: usize) {
|
||||
if self.used.len() <= index {
|
||||
self.used.resize(index + 1, false);
|
||||
}
|
||||
self.used[index] = true;
|
||||
}
|
||||
|
||||
fn fired(&self, index: usize) -> bool {
|
||||
self.used.get(index).copied().unwrap_or(false)
|
||||
}
|
||||
}
|
||||
|
||||
/// One waiver file's dead directives, ready to be reported: the file, its
|
||||
/// text — for the line and column — and one finding each.
|
||||
pub struct UnusedReport {
|
||||
/// The waiver file the directives were written in.
|
||||
pub path: PathBuf,
|
||||
/// That file's text.
|
||||
pub text: String,
|
||||
/// One `unused-waiver` violation per directive that suppressed nothing.
|
||||
pub violations: Vec<Violation>,
|
||||
}
|
||||
|
||||
impl ExternalWaivers {
|
||||
/// Reads one waiver file: the directives that parsed, and one
|
||||
/// `<file>:<line>: message` per line that did not.
|
||||
///
|
||||
/// A file that cannot be read at all is the `Err`; a file that reads and
|
||||
/// has bad lines is an `Ok` carrying both halves, so a front end may
|
||||
/// choose between failing the run (the CLI) and dropping the line and
|
||||
/// logging it (the server).
|
||||
pub fn read(path: &Path) -> Result<(ExternalWaivers, Vec<String>), String> {
|
||||
let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
Ok(ExternalWaivers::parse(path, &text))
|
||||
}
|
||||
|
||||
/// [`ExternalWaivers::read`] over text already in hand.
|
||||
pub fn parse(path: &Path, text: &str) -> (ExternalWaivers, Vec<String>) {
|
||||
let source = Source { path: path.to_path_buf(), text: text.to_string() };
|
||||
let mut waivers = ExternalWaivers { sources: vec![source], directives: Vec::new() };
|
||||
let mut problems = Vec::new();
|
||||
// `split_inclusive` rather than `lines`, so the offsets stay right in
|
||||
// a file with CRLF endings: `lines` drops bytes this has to count.
|
||||
let mut offset: u32 = 0;
|
||||
for (index, raw) in text.split_inclusive('\n').enumerate() {
|
||||
let trimmed = raw.trim_end_matches(['\n', '\r']);
|
||||
let span = TextRange::new(offset, offset + trimmed.len() as u32);
|
||||
offset += raw.len() as u32;
|
||||
// A BOM is not a directive, and an editor that writes one should
|
||||
// not turn the first line into an error naming an invisible byte.
|
||||
let line = trimmed.trim().trim_start_matches('\u{feff}');
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
match parse_directive(line, span) {
|
||||
Ok(directive) => waivers.directives.push(directive),
|
||||
Err(problem) => {
|
||||
problems.push(format!("{}:{}: {problem}", path.display(), index + 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
(waivers, problems)
|
||||
}
|
||||
|
||||
/// Adds another file's directives to these.
|
||||
pub fn absorb(&mut self, other: ExternalWaivers) {
|
||||
let offset = self.sources.len();
|
||||
self.sources.extend(other.sources);
|
||||
self.directives.extend(other.directives.into_iter().map(|mut directive| {
|
||||
directive.source += offset;
|
||||
directive
|
||||
}));
|
||||
}
|
||||
|
||||
/// True when no waiver file contributed a directive — the everyday case,
|
||||
/// and the one the linter must pay nothing for.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.directives.is_empty()
|
||||
}
|
||||
|
||||
/// True when some directive waives this finding, marking every directive
|
||||
/// that does used.
|
||||
///
|
||||
/// Every one, not the first: a finding two waivers cover has both of them
|
||||
/// doing their job, and reporting the second as dead afterwards would be a
|
||||
/// lie.
|
||||
pub(crate) fn covers(
|
||||
&self,
|
||||
path: Option<&Path>,
|
||||
rule: &str,
|
||||
line: u32,
|
||||
used: &mut WaiverUse,
|
||||
) -> bool {
|
||||
let mut waived = false;
|
||||
for (index, directive) in self.directives.iter().enumerate() {
|
||||
if directive.covers(path, rule, line) {
|
||||
used.mark(index);
|
||||
waived = true;
|
||||
}
|
||||
}
|
||||
waived
|
||||
}
|
||||
|
||||
/// The `unused-waiver` findings for directives that suppressed nothing,
|
||||
/// grouped by the file they were written in.
|
||||
///
|
||||
/// `enabled` is every rule the run had switched on. A waiver for a rule
|
||||
/// that never ran is silent, exactly as an inline one is — it never had a
|
||||
/// chance to fire — and so is everything here when `unused-waiver` itself
|
||||
/// is off.
|
||||
pub fn unused(&self, used: &WaiverUse, enabled: &[&'static str]) -> Vec<UnusedReport> {
|
||||
if !enabled.contains(&UNUSED_WAIVER) {
|
||||
return Vec::new();
|
||||
}
|
||||
let severity = rule_by_name(UNUSED_WAIVER).map_or(Severity::Style, |rule| rule.severity());
|
||||
let mut reports: Vec<UnusedReport> = self
|
||||
.sources
|
||||
.iter()
|
||||
.map(|source| UnusedReport {
|
||||
path: source.path.clone(),
|
||||
text: source.text.clone(),
|
||||
violations: Vec::new(),
|
||||
})
|
||||
.collect();
|
||||
for (index, directive) in self.directives.iter().enumerate() {
|
||||
if used.fired(index) || !enabled.contains(&directive.rule.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let message = format!("unused waiver for `{}`", directive.rule);
|
||||
let mut violation = Violation::new(UNUSED_WAIVER, message, directive.span);
|
||||
// Built outside `lint`, which is what stamps every other finding.
|
||||
violation.severity = severity;
|
||||
if let Some(report) = reports.get_mut(directive.source) {
|
||||
report.violations.push(violation);
|
||||
}
|
||||
}
|
||||
reports.retain(|report| !report.violations.is_empty());
|
||||
reports
|
||||
}
|
||||
}
|
||||
|
||||
impl Directive {
|
||||
/// True when this directive waives `rule` at `line` of `path`.
|
||||
///
|
||||
/// A buffer with no path (stdin) is covered by a directive with no
|
||||
/// `--location` and by no other: a pattern cannot match a name that does
|
||||
/// not exist.
|
||||
fn covers(&self, path: Option<&Path>, rule: &str, line: u32) -> bool {
|
||||
if self.rule != rule {
|
||||
return false;
|
||||
}
|
||||
if let Some((start, end)) = self.lines {
|
||||
if line < start || end < line {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
match &self.location {
|
||||
None => true,
|
||||
Some(pattern) => path.is_some_and(|path| {
|
||||
lucisv_core::walk::is_excluded(path, std::slice::from_ref(pattern))
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One directive line: its rule, its line range and its location pattern.
|
||||
///
|
||||
/// `span` is that line's own range in the waiver file, carried into the
|
||||
/// directive so an unused one can be reported where it was written. The
|
||||
/// source index is filled in by [`ExternalWaivers::absorb`].
|
||||
fn parse_directive(line: &str, span: TextRange) -> Result<Directive, String> {
|
||||
let mut words = line.split_whitespace();
|
||||
// The line was trimmed and is not empty, so there is a first word.
|
||||
let keyword = words.next().unwrap_or_default();
|
||||
if keyword != "waive" {
|
||||
return Err(format!("expected a `waive` directive, found `{keyword}`"));
|
||||
}
|
||||
let mut rule: Option<String> = None;
|
||||
let mut lines: Option<(u32, u32)> = None;
|
||||
let mut location: Option<String> = None;
|
||||
for word in words {
|
||||
let (flag, value) = split_flag(word)?;
|
||||
match flag {
|
||||
"--rule" => set_once(&mut rule, flag, parse_rule(value)?)?,
|
||||
"--line" => set_once(&mut lines, flag, parse_lines(value)?)?,
|
||||
_ => set_once(&mut location, flag, parse_location(value)?)?,
|
||||
}
|
||||
}
|
||||
let rule = rule.ok_or("`waive` needs a `--rule=<rule-name>`")?;
|
||||
Ok(Directive { source: 0, span, rule, lines, location })
|
||||
}
|
||||
|
||||
/// Fills a slot the directive may only fill once.
|
||||
fn set_once<T>(slot: &mut Option<T>, flag: &str, value: T) -> Result<(), String> {
|
||||
if slot.is_some() {
|
||||
return Err(format!("`{flag}` is given twice"));
|
||||
}
|
||||
*slot = Some(value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The `--flag=value` one word of a directive is.
|
||||
fn split_flag(word: &str) -> Result<(&str, &str), String> {
|
||||
let (flag, value) = word.split_once('=').unwrap_or((word, ""));
|
||||
match flag {
|
||||
"--rule" | "--line" | "--location" => {}
|
||||
// Verible's third matcher waives by the *text* of the line, which
|
||||
// needs the regex engine lucisv deliberately does not have.
|
||||
"--regex" => {
|
||||
return Err("`--regex` is not supported; waive by `--line` or `--location`".to_string())
|
||||
}
|
||||
other => {
|
||||
return Err(format!(
|
||||
"unknown option `{other}` (the options are `--rule`, `--line` and `--location`)"
|
||||
))
|
||||
}
|
||||
}
|
||||
if !word.contains('=') {
|
||||
return Err(format!("`{flag}` takes a value: write `{flag}=<value>`"));
|
||||
}
|
||||
if value.is_empty() {
|
||||
return Err(format!("`{flag}` has an empty value"));
|
||||
}
|
||||
Ok((flag, value))
|
||||
}
|
||||
|
||||
/// A `--rule` value: one rule the registry knows.
|
||||
///
|
||||
/// A severity word is refused rather than expanded. `--select style` turns a
|
||||
/// whole class on for a run the user is watching; a waiver file is checked in,
|
||||
/// and one word there quietly silencing every style rule in the project is not
|
||||
/// a thing anyone should be able to write by accident.
|
||||
fn parse_rule(value: &str) -> Result<String, String> {
|
||||
if rule_by_name(value).is_some() {
|
||||
return Ok(value.to_string());
|
||||
}
|
||||
if Severity::from_name(value).is_some() {
|
||||
return Err(format!(
|
||||
"`--rule={value}` names a severity class; a waiver names one rule at a time"
|
||||
));
|
||||
}
|
||||
Err(format!("unknown rule `{value}`"))
|
||||
}
|
||||
|
||||
/// A `--line` value: `N` or `N-M`, 1-based, both ends included.
|
||||
fn parse_lines(value: &str) -> Result<(u32, u32), String> {
|
||||
let malformed =
|
||||
|| format!("`--line={value}` is not a line or a line range (`--line=5`, `--line=5-9`)");
|
||||
let (start, end) = value.split_once('-').unwrap_or((value, value));
|
||||
let start: u32 = start.parse().map_err(|_| malformed())?;
|
||||
let end: u32 = end.parse().map_err(|_| malformed())?;
|
||||
if start == 0 {
|
||||
return Err(format!("`--line={value}` starts at 0; lines are numbered from 1"));
|
||||
}
|
||||
if end < start {
|
||||
return Err(format!("`--line={value}` counts backwards"));
|
||||
}
|
||||
Ok((start, end))
|
||||
}
|
||||
|
||||
/// A `--location` value: an `--exclude` pattern, never a regex.
|
||||
fn parse_location(value: &str) -> Result<String, String> {
|
||||
match regex_hint(value) {
|
||||
Some(found) => Err(format!(
|
||||
"`--location={value}` looks like a regular expression (`{found}`); lucisv matches a \
|
||||
location the way `--exclude` does — `*` stands for any run of characters within one \
|
||||
path component, a pattern with `/` matches a path suffix and one without matches the \
|
||||
file name, and nothing else is a metacharacter"
|
||||
)),
|
||||
None => Ok(value.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The first regex metacharacter in a pattern, if it has one.
|
||||
///
|
||||
/// A bare `.` is not one: `foo.sv` is a file name. `.*` and `.+` are, and so
|
||||
/// is every character that means nothing in a glob and something in a regex.
|
||||
fn regex_hint(pattern: &str) -> Option<String> {
|
||||
for token in [".*", ".+"] {
|
||||
if pattern.contains(token) {
|
||||
return Some(token.to_string());
|
||||
}
|
||||
}
|
||||
pattern.chars().find(|c| "\\^$[]()|?+{}".contains(*c)).map(|c| c.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn waivers(text: &str) -> (ExternalWaivers, Vec<String>) {
|
||||
ExternalWaivers::parse(Path::new("project.waiver"), text)
|
||||
}
|
||||
|
||||
/// The one problem `text` produces, without the `file:line: ` prefix.
|
||||
fn problem(text: &str) -> String {
|
||||
let (waivers, problems) = waivers(text);
|
||||
assert!(waivers.is_empty(), "a bad line contributes no directive");
|
||||
assert_eq!(problems.len(), 1, "{problems:?}");
|
||||
problems[0].split_once(": ").expect("a `file:line: message`").1.to_string()
|
||||
}
|
||||
|
||||
/// Whether the file's directives waive `rule` at `line` of `path`.
|
||||
fn covered(text: &str, path: Option<&str>, rule: &str, line: u32) -> bool {
|
||||
let (waivers, problems) = waivers(text);
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
let mut used = WaiverUse::default();
|
||||
waivers.covers(path.map(Path::new), rule, line, &mut used)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_directive_shape_parses() {
|
||||
let (waivers, problems) = waivers(
|
||||
"# a comment\n\
|
||||
\n\
|
||||
waive --rule=no-tabs\n\
|
||||
waive --rule=no-tabs --line=12\n\
|
||||
waive --rule=no-tabs --line=12-20\n\
|
||||
waive --rule=no-tabs --location=legacy.sv\n\
|
||||
\x20 waive --rule=no-tabs --line=3 --location=rtl/legacy.sv\n\
|
||||
waive --location=a.sv --rule=no-tabs\n",
|
||||
);
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
assert_eq!(waivers.directives.len(), 6);
|
||||
assert_eq!(waivers.directives[1].lines, Some((12, 12)));
|
||||
assert_eq!(waivers.directives[2].lines, Some((12, 20)));
|
||||
assert_eq!(waivers.directives[3].location.as_deref(), Some("legacy.sv"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_line_endings_do_not_shift_a_directives_span() {
|
||||
let (waivers, problems) = waivers("# note\r\nwaive --rule=no-tabs\r\n");
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
let span = waivers.directives[0].span;
|
||||
assert_eq!(span.start as usize, "# note\r\n".len());
|
||||
assert_eq!(span.end as usize, "# note\r\nwaive --rule=no-tabs".len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_error_names_the_file_the_line_and_the_difference() {
|
||||
let (_, problems) = waivers("waive --rule=no-such-rule\n");
|
||||
assert_eq!(problems[0], "project.waiver:1: unknown rule `no-such-rule`");
|
||||
|
||||
assert_eq!(problem("waive\n"), "`waive` needs a `--rule=<rule-name>`");
|
||||
assert_eq!(problem("waive --line=3\n"), "`waive` needs a `--rule=<rule-name>`");
|
||||
assert!(problem("skip --rule=no-tabs\n").contains("found `skip`"));
|
||||
assert!(problem("waive --rule=style\n").contains("names a severity class"));
|
||||
assert!(problem("waive --rule=no-tabs --line=0\n").contains("numbered from 1"));
|
||||
assert!(problem("waive --rule=no-tabs --line=9-5\n").contains("counts backwards"));
|
||||
assert!(problem("waive --rule=no-tabs --line=x\n").contains("is not a line or a line"));
|
||||
assert!(problem("waive --rule=no-tabs --line=5-\n").contains("is not a line or a line"));
|
||||
assert!(problem("waive --rule=no-tabs --rule=no-tabs\n").contains("given twice"));
|
||||
assert!(problem("waive --rule=no-tabs --lines=3\n").contains("unknown option `--lines`"));
|
||||
assert!(problem("waive --rule=no-tabs --regex=x\n").contains("`--regex` is not supported"));
|
||||
assert!(problem("waive --rule\n").contains("takes a value"));
|
||||
assert!(problem("waive --rule=\n").contains("empty value"));
|
||||
assert!(problem("waive --rule=no-tabs --location=x --location=y\n").contains("twice"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_regex_looking_location_is_refused_and_a_glob_is_not() {
|
||||
for pattern in [".*_pkg.sv", "top\\.sv", "^a.sv$", "(a|b).sv", "a?.sv", "a+.sv", "[ab].sv"]
|
||||
{
|
||||
let text = format!("waive --rule=no-tabs --location={pattern}\n");
|
||||
let message = problem(&text);
|
||||
assert!(message.contains("looks like a regular expression"), "{pattern}: {message}");
|
||||
assert!(message.contains("`--exclude`"), "{pattern}: {message}");
|
||||
}
|
||||
for pattern in ["a.sv", "*_gen.sv", "rtl/*.sv", "legacy/top.sv", "*"] {
|
||||
let text = format!("waive --rule=no-tabs --location={pattern}\n");
|
||||
let (_, problems) = waivers(&text);
|
||||
assert!(problems.is_empty(), "{pattern}: {problems:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directive_with_no_line_and_no_location_covers_everything() {
|
||||
let text = "waive --rule=no-tabs\n";
|
||||
assert!(covered(text, Some("rtl/a.sv"), "no-tabs", 1));
|
||||
assert!(covered(text, Some("elsewhere/b.sv"), "no-tabs", 900));
|
||||
assert!(covered(text, None, "no-tabs", 1), "a stdin buffer too");
|
||||
assert!(!covered(text, Some("rtl/a.sv"), "no-trailing-whitespace", 1), "another rule");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_covers_itself_and_a_range_covers_both_ends() {
|
||||
let one = "waive --rule=no-tabs --line=12\n";
|
||||
assert!(covered(one, Some("a.sv"), "no-tabs", 12));
|
||||
assert!(!covered(one, Some("a.sv"), "no-tabs", 11));
|
||||
assert!(!covered(one, Some("a.sv"), "no-tabs", 13));
|
||||
|
||||
let range = "waive --rule=no-tabs --line=12-14\n";
|
||||
for line in [12, 13, 14] {
|
||||
assert!(covered(range, Some("a.sv"), "no-tabs", line), "line {line}");
|
||||
}
|
||||
assert!(!covered(range, Some("a.sv"), "no-tabs", 11));
|
||||
assert!(!covered(range, Some("a.sv"), "no-tabs", 15));
|
||||
}
|
||||
|
||||
/// The `--exclude` semantics, at the waiver file's end of them: a pattern
|
||||
/// without `/` matches the file name at any depth, one with `/` matches a
|
||||
/// path suffix, and `*` stays inside one component.
|
||||
#[test]
|
||||
fn a_location_matches_the_way_an_exclude_pattern_does() {
|
||||
let by_name = "waive --rule=no-tabs --location=legacy.sv\n";
|
||||
assert!(covered(by_name, Some("a/b/legacy.sv"), "no-tabs", 1));
|
||||
assert!(!covered(by_name, Some("a/b/other.sv"), "no-tabs", 1));
|
||||
|
||||
let by_suffix = "waive --rule=no-tabs --location=vendor/legacy.sv\n";
|
||||
assert!(covered(by_suffix, Some("a/vendor/legacy.sv"), "no-tabs", 1));
|
||||
assert!(!covered(by_suffix, Some("a/rtl/legacy.sv"), "no-tabs", 1));
|
||||
|
||||
let glob = "waive --rule=no-tabs --location=*_gen.sv\n";
|
||||
assert!(covered(glob, Some("rtl/top_gen.sv"), "no-tabs", 1));
|
||||
assert!(!covered(glob, Some("rtl/top.sv"), "no-tabs", 1));
|
||||
// `*` does not cross a `/`, exactly as in a walk's exclude.
|
||||
let anchored = "waive --rule=no-tabs --location=rtl/*.sv\n";
|
||||
assert!(covered(anchored, Some("top/rtl/b.sv"), "no-tabs", 1));
|
||||
assert!(!covered(anchored, Some("rtl/a/b.sv"), "no-tabs", 1));
|
||||
|
||||
// A buffer with no path is covered by nothing that names a location.
|
||||
assert!(!covered(by_name, None, "no-tabs", 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directive_that_fired_is_not_reported_and_one_that_did_not_is() {
|
||||
let (waivers, problems) =
|
||||
waivers("waive --rule=no-tabs\nwaive --rule=no-trailing-whitespace\n");
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
let enabled = ["no-tabs", "no-trailing-whitespace", UNUSED_WAIVER];
|
||||
|
||||
let mut used = WaiverUse::default();
|
||||
assert!(waivers.covers(Some(Path::new("a.sv")), "no-tabs", 1, &mut used));
|
||||
|
||||
let reports = waivers.unused(&used, &enabled);
|
||||
assert_eq!(reports.len(), 1, "one waiver file, one group");
|
||||
assert_eq!(reports[0].path, PathBuf::from("project.waiver"));
|
||||
assert_eq!(reports[0].violations.len(), 1, "only the one that never fired");
|
||||
assert!(reports[0].violations[0].message.contains("no-trailing-whitespace"));
|
||||
assert_eq!(reports[0].violations[0].rule, UNUSED_WAIVER);
|
||||
assert_eq!(reports[0].violations[0].severity, Severity::Style, "stamped here");
|
||||
// The finding points at the dead directive's own line.
|
||||
assert_eq!(reports[0].violations[0].span.start as usize, "waive --rule=no-tabs\n".len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_waiver_for_a_rule_the_run_did_not_enable_is_silent() {
|
||||
let (waivers, _) = waivers("waive --rule=no-tabs\n");
|
||||
let used = WaiverUse::default();
|
||||
assert!(waivers.unused(&used, &["no-trailing-whitespace", UNUSED_WAIVER]).is_empty());
|
||||
// And so is everything when `unused-waiver` itself is off.
|
||||
assert!(waivers.unused(&used, &["no-tabs"]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absorbing_a_second_file_keeps_each_directive_with_its_own_file() {
|
||||
let (mut first, _) =
|
||||
ExternalWaivers::parse(Path::new("a.waiver"), "waive --rule=no-tabs\n");
|
||||
let (second, _) =
|
||||
ExternalWaivers::parse(Path::new("b.waiver"), "waive --rule=no-trailing-whitespace\n");
|
||||
first.absorb(second);
|
||||
assert_eq!(first.directives.len(), 2);
|
||||
|
||||
let mut used = WaiverUse::default();
|
||||
assert!(first.covers(Some(Path::new("a.sv")), "no-tabs", 1, &mut used));
|
||||
let reports = first.unused(&used, &["no-tabs", "no-trailing-whitespace", UNUSED_WAIVER]);
|
||||
assert_eq!(reports.len(), 1, "only the file with a dead directive: {}", reports.len());
|
||||
assert_eq!(reports[0].path, PathBuf::from("b.waiver"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_merges_across_the_files_a_run_linted_in_parallel() {
|
||||
let (waivers, _) = waivers(
|
||||
"waive --rule=no-tabs --location=a.sv\n\
|
||||
waive --rule=no-tabs --location=b.sv\n",
|
||||
);
|
||||
let enabled = ["no-tabs", UNUSED_WAIVER];
|
||||
|
||||
let mut first = WaiverUse::default();
|
||||
waivers.covers(Some(Path::new("a.sv")), "no-tabs", 1, &mut first);
|
||||
assert_eq!(waivers.unused(&first, &enabled)[0].violations.len(), 1, "b.sv's is dead");
|
||||
|
||||
let mut second = WaiverUse::default();
|
||||
waivers.covers(Some(Path::new("b.sv")), "no-tabs", 1, &mut second);
|
||||
first.merge(&second);
|
||||
assert!(waivers.unused(&first, &enabled).is_empty(), "both fired, over two files");
|
||||
}
|
||||
}
|
||||
@@ -235,12 +235,39 @@ pub struct ParamDecl {
|
||||
pub declarators: Vec<Declarator>,
|
||||
}
|
||||
|
||||
/// A net delay and the side of the data type it was written on.
|
||||
///
|
||||
/// IEEE 1800 §6.7 puts `delay3` *after* the type —
|
||||
/// `wire [31:0] #0.1 x = y;`, which is how
|
||||
/// `pulp_riscv_dbg/tb/unused/SimDTM.sv:38` writes it — while the spelling
|
||||
/// the rest of the corpus uses puts it between the net keyword and the type.
|
||||
/// Both are read, never both at once, and printed back where they were
|
||||
/// written: moving a delay across the type reorders tokens, which
|
||||
/// `verify.rs` rightly refuses.
|
||||
#[derive(Debug)]
|
||||
pub struct NetDelay {
|
||||
/// Comments written between whatever precedes the delay and its `#`:
|
||||
/// the `/* c */` of `wire /* c */ #5 w;` and of
|
||||
/// `wire [7:0] /* c */ #1 w;`. Without a slot here the comment would be
|
||||
/// printed one node later and `verify.rs` would refuse the file.
|
||||
pub before_hash: Vec<Comment>,
|
||||
/// Comments written between the `#` and the delay value — the delay's
|
||||
/// other gap, and the one the gap fuzzer asks about the moment the
|
||||
/// first one has an owner.
|
||||
pub after_hash: Vec<Comment>,
|
||||
/// The delay itself: the `5` of `wire #5 w;`.
|
||||
pub expr: Expr,
|
||||
/// True when it stood between the data type and the declarators.
|
||||
pub after_type: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DataDecl {
|
||||
/// Net type (`wire`, `tri`, ...) if any.
|
||||
pub net: Option<String>,
|
||||
/// Net delay: the `5` in `wire #5 w;`
|
||||
pub delay: Option<Expr>,
|
||||
/// Net delay, if any: the `5` in `wire #5 w;` or the `0.1` in
|
||||
/// `wire [31:0] #0.1 x = y;`.
|
||||
pub delay: Option<NetDelay>,
|
||||
/// Qualifiers written before the type, in source order: `var`,
|
||||
/// `automatic`, `static`, `const`, and — inside a class body — `rand`,
|
||||
/// `randc`, `local`, `protected`, and the `virtual [interface]` of a
|
||||
|
||||
@@ -259,9 +259,32 @@ pub enum ExprKind {
|
||||
min: Box<Expr>,
|
||||
typ: Box<Expr>,
|
||||
max: Box<Expr>,
|
||||
/// What was written around the two `:`.
|
||||
comments: Box<MinTypMaxComments>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Comments written around the two `:` of a `min : typ : max` delay
|
||||
/// (IEEE 1800 §28.14):
|
||||
///
|
||||
/// ```text
|
||||
/// min /*before_typ*/ : /*after_typ*/ typ /*before_max*/ : /*after_max*/ max
|
||||
/// ```
|
||||
///
|
||||
/// Boxed by its holder for the reason every expression-level slot is: `Expr`
|
||||
/// is walked recursively and its size is pinned at 96 bytes.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct MinTypMaxComments {
|
||||
/// Between `min` and the first `:`.
|
||||
pub before_typ: Vec<Comment>,
|
||||
/// Just after the first `:`.
|
||||
pub after_typ: Vec<Comment>,
|
||||
/// Between `typ` and the second `:`.
|
||||
pub before_max: Vec<Comment>,
|
||||
/// Just after the second `:`.
|
||||
pub after_max: Vec<Comment>,
|
||||
}
|
||||
|
||||
/// Comments written in the fixed slots of a **postfix segment** or a
|
||||
/// **bracketed range** — the one shape the grammar writes in five places:
|
||||
///
|
||||
|
||||
@@ -387,6 +387,15 @@ pub enum ItemKind {
|
||||
dangling: Vec<Comment>,
|
||||
},
|
||||
GenIf(GenIf),
|
||||
/// A bare `begin … end` written where an item belongs — at module scope
|
||||
/// or straight inside `generate … endgenerate`. Not a legal module item
|
||||
/// (IEEE 1800 §23.2.1); tools that accept it read it as an unnamed
|
||||
/// generate block, which is the node kept here. Only error-tolerant
|
||||
/// parsing produces it, always beside a diagnostic at the `begin`, so the
|
||||
/// formatter — which refuses any file with a diagnostic — never prints
|
||||
/// one. The `module-begin-block` and `v2001-generate-begin` lints are
|
||||
/// what report it. Boxed for the same reason [`ItemKind::GenFor`] is.
|
||||
GenBlock(Box<GenBlock>),
|
||||
/// Boxed: a `for` generate holds a whole `SimpleAssign`, a condition, a
|
||||
/// step and a block, which together are twice the next-largest item.
|
||||
GenFor(Box<GenFor>),
|
||||
|
||||
@@ -162,8 +162,15 @@ pub struct ContAssign {
|
||||
/// Drive strength: the `(weak0, pull1)` in
|
||||
/// `assign (weak0, pull1) x = y;` (IEEE 1800 §10.3.1), in source order.
|
||||
pub strength: Option<DriveStrength>,
|
||||
/// Comments written between the `#` and the delay itself.
|
||||
pub after_hash: Vec<Comment>,
|
||||
/// Delay expression: the `5` in `assign #5 x = y;`
|
||||
pub delay: Option<Expr>,
|
||||
/// Comments written between that delay and the first left-hand side.
|
||||
/// Without a slot here they would join the first pair's `meta.leading`,
|
||||
/// which prints straight after the `assign` — in front of the delay the
|
||||
/// source wrote them behind.
|
||||
pub after_delay: Vec<Comment>,
|
||||
pub assigns: Vec<AssignPair>,
|
||||
}
|
||||
|
||||
@@ -363,12 +370,37 @@ pub struct GateInstantiation {
|
||||
/// The `(weak1)` in `pullup (weak1) p (x);` (IEEE 1800 §28.3), or the
|
||||
/// `(strong0, strong1)` pair every driving gate also accepts.
|
||||
pub strength: Option<DriveStrength>,
|
||||
/// Comments written between the gate (or its drive strength) and the `#`
|
||||
/// of the delay: the `/* c */` of `and /* c */ #(2, 3) g (y, a, b);`.
|
||||
pub before_hash: Vec<Comment>,
|
||||
/// Comments written between that `#` and the delay itself.
|
||||
pub after_hash: Vec<Comment>,
|
||||
/// The delay written after `#`: empty when there is none, one element for
|
||||
/// every spelling a net or a continuous assignment also accepts, and two
|
||||
/// or three for the `(rise, fall[, turn-off])` list that only a gate
|
||||
/// takes (IEEE 1800 §28.14, `top_earlgrey/ip/ast/rtl/aon_osc.sv:41`).
|
||||
pub delay: Vec<Expr>,
|
||||
pub delay: Vec<DelayValue>,
|
||||
pub instances: Vec<GateInstance>,
|
||||
/// Comments written between the last instance and the `;`.
|
||||
pub before_semi: Vec<Comment>,
|
||||
}
|
||||
|
||||
/// One value of a delay list, with the comments written on either side of the
|
||||
/// separator that reaches it.
|
||||
///
|
||||
/// A one-value delay keeps its comments in its own [`ExprKind::Paren`], which
|
||||
/// has had the two slots all along; this shape exists for the multi-value
|
||||
/// `#(rise, fall[, turn-off])` list, whose parentheses and commas the printer
|
||||
/// writes itself and which therefore has nowhere else to put them. The first
|
||||
/// value's `leading` is what stood just inside the `(`, and the last value's
|
||||
/// `trailing` is what stood just before the `)`.
|
||||
#[derive(Debug)]
|
||||
pub struct DelayValue {
|
||||
/// Comments between the `(` or the `,` before this value and the value.
|
||||
pub leading: Vec<Comment>,
|
||||
pub expr: Expr,
|
||||
/// Comments between the value and the `,` or `)` that follows it.
|
||||
pub trailing: Vec<Comment>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -377,6 +409,9 @@ pub struct GateInstance {
|
||||
pub name: Option<String>,
|
||||
/// Byte range of `name`.
|
||||
pub name_span: Option<TextRange>,
|
||||
/// Comments written between the instance name and the `(` of its
|
||||
/// terminal list.
|
||||
pub before_args: Vec<Comment>,
|
||||
pub args: Vec<ExprItem>,
|
||||
/// Code extent of the gate instance.
|
||||
pub span: TextRange,
|
||||
|
||||
@@ -249,12 +249,7 @@ impl<'a> Parser<'a> {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let delay = if net.is_some() && self.cur().is_sym("#") {
|
||||
self.bump();
|
||||
Some(self.parse_delay_value()?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let before = self.parse_net_delay(net.is_some(), false)?;
|
||||
// A declaration reaches here with its `virtual` already in
|
||||
// `qualifiers`, so `parse_opt_data_type`'s own modport branch cannot
|
||||
// fire: `virtual spi_if.tb tb_sif = sif.tb;`
|
||||
@@ -265,11 +260,39 @@ impl<'a> Parser<'a> {
|
||||
} else {
|
||||
self.parse_opt_data_type()?
|
||||
};
|
||||
// IEEE 1800 §6.7 writes the delay *here*, after the data type
|
||||
// (`wire [31:0] #0.1 x = y;`, `pulp_riscv_dbg/tb/unused/SimDTM.sv:38`);
|
||||
// everything else in the corpus writes it before. Either is read and
|
||||
// printed back where it stood, but a declaration with one on each
|
||||
// side is not a shape the LRM has.
|
||||
let after = self.parse_net_delay(net.is_some(), true)?;
|
||||
let delay = match (before, after) {
|
||||
(Some(_), Some(_)) => {
|
||||
return self.error("a net delay is written before or after the type, not both")
|
||||
}
|
||||
(before, after) => before.or(after),
|
||||
};
|
||||
let declarators = self.parse_declarators()?;
|
||||
self.expect_sym(";")?;
|
||||
Ok(DataDecl { net, delay, qualifiers, ty, declarators })
|
||||
}
|
||||
|
||||
/// The net delay at the cursor, if one is written there: `#5`, `#0.1`,
|
||||
/// `#(1:2:3)`. Only a net declaration may carry one, so `is_net` gates
|
||||
/// the whole read — a `#` anywhere else belongs to whoever comes next.
|
||||
fn parse_net_delay(&mut self, is_net: bool, after_type: bool) -> PResult<Option<NetDelay>> {
|
||||
if !is_net || !self.cur().is_sym("#") {
|
||||
return Ok(None);
|
||||
}
|
||||
// The `#` is written, so the gap in front of it is the delay's own:
|
||||
// `wire /* c */ #5 w;`. Taken only here — when the read does not
|
||||
// happen the gap belongs to whatever comes next.
|
||||
let before_hash = self.take_gap();
|
||||
self.bump();
|
||||
let after_hash = self.take_gap();
|
||||
Ok(Some(NetDelay { before_hash, after_hash, expr: self.parse_delay_value()?, after_type }))
|
||||
}
|
||||
|
||||
pub(super) fn parse_port_decl(&mut self) -> PResult<PortDecl> {
|
||||
let dir = self.bump().text;
|
||||
let net = {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! `bind` directives. Drive strengths and delay values live here because
|
||||
//! these are the only items that write them.
|
||||
|
||||
use super::recover::is_sync_stop;
|
||||
use super::*;
|
||||
|
||||
/// The strength keywords a drive strength is written from (IEEE 1800 §28.11).
|
||||
@@ -20,9 +21,17 @@ impl<'a> Parser<'a> {
|
||||
pub(super) fn parse_cont_assign(&mut self) -> PResult<ContAssign> {
|
||||
self.expect_kw("assign")?;
|
||||
let strength = self.parse_opt_drive_strength()?;
|
||||
let mut after_hash = Vec::new();
|
||||
let mut after_delay = Vec::new();
|
||||
let delay = if self.cur().is_sym("#") {
|
||||
self.bump();
|
||||
Some(self.parse_delay_value()?)
|
||||
after_hash = self.take_gap();
|
||||
let delay = self.parse_delay_value()?;
|
||||
// The gap between the delay and the first left-hand side is the
|
||||
// delay's, not the pair's: a pair's leading comments print right
|
||||
// after the `assign`, which is in front of the delay.
|
||||
after_delay = self.take_gap();
|
||||
Some(delay)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -54,7 +63,7 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
self.expect_sym(";")?;
|
||||
Ok(ContAssign { strength, delay, assigns })
|
||||
Ok(ContAssign { strength, after_hash, delay, after_delay, assigns })
|
||||
}
|
||||
|
||||
/// The optional `( strength0 , strength1 )` of a continuous assignment
|
||||
@@ -93,46 +102,75 @@ impl<'a> Parser<'a> {
|
||||
/// spelling has always produced, so `#(5)` and `#(1:2:3)` still print
|
||||
/// exactly as written; only a real comma list yields more than one
|
||||
/// element.
|
||||
fn parse_delay_values(&mut self) -> PResult<Vec<Expr>> {
|
||||
fn parse_delay_values(&mut self) -> PResult<Vec<DelayValue>> {
|
||||
if !self.cur().is_sym("(") {
|
||||
return Ok(vec![self.parse_primary()?]);
|
||||
let expr = self.parse_primary()?;
|
||||
return Ok(vec![DelayValue { leading: Vec::new(), expr, trailing: Vec::new() }]);
|
||||
}
|
||||
let start = self.here();
|
||||
self.bump(); // (
|
||||
let mut out = Vec::new();
|
||||
// What is written just inside the `(` belongs to the first value; the
|
||||
// gap before each `,` and the gap after it belong to the values either
|
||||
// side of it.
|
||||
self.bump();
|
||||
let mut leading = self.take_gap();
|
||||
let mut out: Vec<DelayValue> = Vec::new();
|
||||
loop {
|
||||
let inner_start = self.here();
|
||||
let first = self.parse_expr()?;
|
||||
out.push(if self.eat_sym(":") {
|
||||
let typ = self.parse_expr()?;
|
||||
self.expect_sym(":")?;
|
||||
let max = self.parse_expr()?;
|
||||
self.expr_at(
|
||||
inner_start,
|
||||
ExprKind::MinTypMax {
|
||||
min: Box::new(first),
|
||||
typ: Box::new(typ),
|
||||
max: Box::new(max),
|
||||
},
|
||||
)
|
||||
} else {
|
||||
first
|
||||
});
|
||||
let expr = self.parse_min_typ_max_tail(inner_start, first)?;
|
||||
let trailing = self.gap_before(",");
|
||||
out.push(DelayValue { leading: std::mem::take(&mut leading), expr, trailing });
|
||||
if !self.eat_sym(",") {
|
||||
break;
|
||||
}
|
||||
leading = self.take_gap();
|
||||
}
|
||||
if let Some(last) = out.last_mut() {
|
||||
last.trailing = self.gap_before(")");
|
||||
}
|
||||
self.expect_sym(")")?;
|
||||
if out.len() == 1 {
|
||||
let inner = out.remove(0);
|
||||
return Ok(vec![self.expr_at(
|
||||
// One value keeps the `( )` node the one-value spelling has always
|
||||
// produced, and its two comment slots are where the paren gaps go.
|
||||
let DelayValue { leading, expr, trailing } = out.remove(0);
|
||||
let paren = self.expr_at(
|
||||
start,
|
||||
ExprKind::Paren { inner: Box::new(inner), before: Vec::new(), after: Vec::new() },
|
||||
)]);
|
||||
ExprKind::Paren { inner: Box::new(expr), before: leading, after: trailing },
|
||||
);
|
||||
return Ok(vec![DelayValue { leading: Vec::new(), expr: paren, trailing: Vec::new() }]);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The `: typ : max` tail of a `min : typ : max` expression, or `min`
|
||||
/// unchanged when no `:` follows it.
|
||||
///
|
||||
/// One grammar for the two places that write it — a delay list and a
|
||||
/// parenthesized expression — so the four comment slots around the two
|
||||
/// colons exist in both.
|
||||
pub(super) fn parse_min_typ_max_tail(&mut self, start: u32, min: Expr) -> PResult<Expr> {
|
||||
let before_typ = self.gap_before(":");
|
||||
if !self.eat_sym(":") {
|
||||
return Ok(min);
|
||||
}
|
||||
let mut comments = MinTypMaxComments { before_typ, ..Default::default() };
|
||||
comments.after_typ = self.take_gap();
|
||||
let typ = self.parse_expr()?;
|
||||
comments.before_max = self.gap_before(":");
|
||||
self.expect_sym(":")?;
|
||||
comments.after_max = self.take_gap();
|
||||
let max = self.parse_expr()?;
|
||||
Ok(self.expr_at(
|
||||
start,
|
||||
ExprKind::MinTypMax {
|
||||
min: Box::new(min),
|
||||
typ: Box::new(typ),
|
||||
max: Box::new(max),
|
||||
comments: Box::new(comments),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// The single delay value a net declaration or a continuous assignment
|
||||
/// takes. The multi-value list is a gate-instantiation spelling only —
|
||||
/// see [`Parser::parse_delay_values`].
|
||||
@@ -141,7 +179,9 @@ impl<'a> Parser<'a> {
|
||||
if values.len() > 1 {
|
||||
return self.error("a multi-value delay list is only allowed on a gate instantiation");
|
||||
}
|
||||
Ok(values.remove(0))
|
||||
// A lone value carries no comments of its own: `parse_delay_values`
|
||||
// folded the paren gaps into its `ExprKind::Paren`.
|
||||
Ok(values.remove(0).expr)
|
||||
}
|
||||
|
||||
/// True when the cursor opens a `bind` directive (IEEE 1800 §23.11).
|
||||
@@ -504,6 +544,16 @@ impl<'a> Parser<'a> {
|
||||
let before_open = self.take_before_open("(");
|
||||
let mark = self.pending_trailing.len();
|
||||
let paren_start = self.here();
|
||||
// A half-typed `.NAME(` whose value would read as the next
|
||||
// instance: `sub #(.WIDTH(8), .DEPTH(` ⏎ `u0 (.a(x));`. Nothing
|
||||
// inside the list fails — `u0 (.a(x))` is a legal call with named
|
||||
// arguments — so the greedy parse swallows the instance and the
|
||||
// whole instantiation collapses into one error item. Failing the
|
||||
// element here costs the one connection and keeps everything
|
||||
// else. See `docs/features/small-items-3/README.md`.
|
||||
if self.tolerant && self.cur().is_sym("(") && self.value_runs_into_next_instance() {
|
||||
return self.error("unclosed `(` in a port or parameter connection");
|
||||
}
|
||||
let mut close_comments = Vec::new();
|
||||
let mut after_open = Vec::new();
|
||||
let expr = if self.eat_sym("(") {
|
||||
@@ -562,6 +612,58 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the `(` at the cursor — the one that opens a connection's
|
||||
/// value — is never closed **and** something that reads as the next
|
||||
/// instance sits inside it.
|
||||
///
|
||||
/// Tolerant mode only, asked once per named connection before its value
|
||||
/// is parsed. The walk starts just past the `(` at depth zero and ends at
|
||||
/// the first of: a closer that would take the depth below zero (the
|
||||
/// value's own `)` — it closes, so nothing is wrong and the value is
|
||||
/// parsed as written), a `;` or a construct keyword at depth zero, or end
|
||||
/// of file. On a file that parses it therefore stops at the value's `)`
|
||||
/// after a handful of tokens; only a value whose bracket was never closed
|
||||
/// walks as far as the next `;`.
|
||||
///
|
||||
/// The candidate is an identifier that opens its own line and is followed
|
||||
/// by `(` — how an instance is written, and how nothing written *inside*
|
||||
/// a value normally is. Only depth zero is read: a candidate inside a
|
||||
/// deeper unclosed bracket (`.DEPTH(f(g(` ⏎ `u0 (…)`) is not seen, and
|
||||
/// that shape falls back to the coarser item-level recovery, which keeps
|
||||
/// the `endmodule` but loses the instantiation. Deliberate — reading
|
||||
/// deeper would start guessing which of several unclosed brackets the
|
||||
/// user meant to close.
|
||||
fn value_runs_into_next_instance(&self) -> bool {
|
||||
let mut depth = 0u32;
|
||||
let mut candidate = false;
|
||||
let mut i = self.pos + 1;
|
||||
while let Some(t) = self.tokens.get(i) {
|
||||
if t.kind == TokenKind::Eof {
|
||||
break;
|
||||
}
|
||||
if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") {
|
||||
depth += 1;
|
||||
} else if t.is_sym(")") || t.is_sym("]") || t.is_sym("}") {
|
||||
if depth == 0 {
|
||||
return false;
|
||||
}
|
||||
depth -= 1;
|
||||
} else if depth == 0 {
|
||||
if t.is_sym(";") || is_sync_stop(t) {
|
||||
break;
|
||||
}
|
||||
if t.kind == TokenKind::Ident
|
||||
&& self.tokens[i - 1].line != t.line
|
||||
&& self.tokens.get(i + 1).is_some_and(|n| n.is_sym("("))
|
||||
{
|
||||
candidate = true;
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
candidate
|
||||
}
|
||||
|
||||
/// Consume the tokens up to `end_pos` as one verbatim expression.
|
||||
///
|
||||
/// [`Parser::open_conds`] is deliberately left alone: it counts *item*
|
||||
@@ -584,8 +686,11 @@ impl<'a> Parser<'a> {
|
||||
// instance's argument list would, and only a strength keyword after
|
||||
// the `(` tells the two apart.
|
||||
let strength = self.parse_opt_drive_strength()?;
|
||||
let before_hash = self.take_before_open("#");
|
||||
let mut after_hash = Vec::new();
|
||||
let delay = if self.cur().is_sym("#") {
|
||||
self.bump();
|
||||
after_hash = self.take_gap();
|
||||
self.parse_delay_values()?
|
||||
} else {
|
||||
Vec::new()
|
||||
@@ -597,6 +702,7 @@ impl<'a> Parser<'a> {
|
||||
let name =
|
||||
if self.cur().kind == TokenKind::Ident { Some(self.expect_name()?) } else { None };
|
||||
let (name, name_span) = split_label(name);
|
||||
let before_args = self.take_before_open("(");
|
||||
self.expect_sym("(")?;
|
||||
let mut args = Vec::new();
|
||||
if !self.cur().is_sym(")") {
|
||||
@@ -610,12 +716,21 @@ impl<'a> Parser<'a> {
|
||||
if more {
|
||||
meta.trailing = self.take_trailing();
|
||||
}
|
||||
instances.push(GateInstance { meta, name, name_span, args, span });
|
||||
instances.push(GateInstance { meta, name, name_span, before_args, args, span });
|
||||
if !more {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let before_semi = self.gap_before(";");
|
||||
self.expect_sym(";")?;
|
||||
Ok(GateInstantiation { gate, strength, delay, instances })
|
||||
Ok(GateInstantiation {
|
||||
gate,
|
||||
strength,
|
||||
before_hash,
|
||||
after_hash,
|
||||
delay,
|
||||
instances,
|
||||
before_semi,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -275,6 +275,22 @@ impl<'a> Parser<'a> {
|
||||
self.expect_closer("endgenerate")?;
|
||||
Ok(ItemKind::GenerateRegion { items, dangling })
|
||||
}
|
||||
// A bare `begin … end` where an item belongs — at module scope or
|
||||
// straight inside a generate region. It is not a module item
|
||||
// (IEEE 1800 §23.2.1), so strict mode falls through to the
|
||||
// default arm and refuses it exactly as it always has. Tolerant
|
||||
// mode reads it the way every tool that accepts it does — as an
|
||||
// unnamed generate block — and still records the diagnostic, so
|
||||
// the file is reported as not parsing cleanly and the formatter
|
||||
// goes on emitting it unchanged. What is bought is the rest of
|
||||
// the body: without this the item fails, recovery skips to a sync
|
||||
// point and everything after the block is lost. The
|
||||
// `module-begin-block` and `v2001-generate-begin` lints read the
|
||||
// node.
|
||||
"begin" if self.tolerant => {
|
||||
self.record("`begin`/`end` block is not a module item");
|
||||
self.parse_gen_block().map(|b| ItemKind::GenBlock(Box::new(b)))
|
||||
}
|
||||
"if" => self.parse_gen_if().map(ItemKind::GenIf),
|
||||
"for" => self.parse_gen_for().map(|g| ItemKind::GenFor(Box::new(g))),
|
||||
"case" => self.parse_gen_case().map(ItemKind::GenCase),
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! belong only to them: parameter ports, ports (ANSI and non-ANSI),
|
||||
//! modports and clocking blocks.
|
||||
|
||||
use super::split::UnitHead;
|
||||
use super::*;
|
||||
|
||||
/// The three pieces a `#( parameter ... )` port list yields, so module and
|
||||
@@ -21,6 +22,7 @@ impl<'a> Parser<'a> {
|
||||
/// one header grammar (IEEE 1800 §23.2.1, §25.3) and one body item list —
|
||||
/// only the closing keyword differs, so `end_kw` is the whole difference.
|
||||
pub(super) fn parse_module(&mut self, end_kw: &str) -> PResult<Module> {
|
||||
let conds = self.open_conds;
|
||||
let kw = self.bump().text;
|
||||
let before_name = self.take_gap();
|
||||
let Name { text: name, span: name_span } = self.expect_name()?;
|
||||
@@ -47,8 +49,18 @@ impl<'a> Parser<'a> {
|
||||
// behind it is what the module is for.
|
||||
self.expect_after_recovery(";", self.recovered_since(mark))?;
|
||||
let mut items = Vec::new();
|
||||
let mut head = UnitHead { kw: &kw, name: &name, conds, floor: conds };
|
||||
while !self.at_body_end(end_kw) {
|
||||
// Two rival headers written across the arms of one `ifdef region
|
||||
// are bracket-balanced, so nothing else in the grammar objects
|
||||
// until this unit runs out of file looking for its `end` keyword.
|
||||
// Failing here instead routes the whole unit into the split
|
||||
// recovery; see `docs/features/parser-skips/README.md`.
|
||||
if self.at_rival_header(&head) {
|
||||
return self.error(format!("rival header for `{name}` in a conditional region"));
|
||||
}
|
||||
items.push(self.item_or_recover()?);
|
||||
head.floor = head.floor.min(self.open_conds);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_closer(end_kw)?;
|
||||
|
||||
@@ -97,21 +97,7 @@ impl<'a> Parser<'a> {
|
||||
let mark = self.pending_trailing.len();
|
||||
let inner_start = self.here();
|
||||
let inner = self.parse_expr()?;
|
||||
let inner = if self.eat_sym(":") {
|
||||
let typ = self.parse_expr()?;
|
||||
self.expect_sym(":")?;
|
||||
let max = self.parse_expr()?;
|
||||
self.expr_at(
|
||||
inner_start,
|
||||
ExprKind::MinTypMax {
|
||||
min: Box::new(inner),
|
||||
typ: Box::new(typ),
|
||||
max: Box::new(max),
|
||||
},
|
||||
)
|
||||
} else {
|
||||
inner
|
||||
};
|
||||
let inner = self.parse_min_typ_max_tail(inner_start, inner)?;
|
||||
let after = self.take_around(mark);
|
||||
self.expect_sym(")")?;
|
||||
Ok(self.expr_at(
|
||||
@@ -454,8 +440,18 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
|
||||
/// In parameter connections a value may be a type (`.T(logic [7:0])`).
|
||||
///
|
||||
/// An **anonymous aggregate** is a type too — `.T(struct packed { logic a;
|
||||
/// })`, the override a `parameter type` defaulting to one takes (IEEE 1800
|
||||
/// §6.19, §7.2). `parse_type_ref` has read that body since the first day;
|
||||
/// only this door was closed, because `struct`/`union`/`enum` are not in
|
||||
/// [`TYPE_KEYWORDS`] and so fell through to `parse_expr`, whose keyword arm
|
||||
/// answers "unexpected keyword `struct` in expression".
|
||||
pub(super) fn parse_expr_or_type(&mut self) -> PResult<Expr> {
|
||||
let t = self.cur();
|
||||
if t.is_kw("struct") || t.is_kw("union") || t.is_kw("enum") {
|
||||
return self.parse_type_expr();
|
||||
}
|
||||
if t.kind == TokenKind::Keyword
|
||||
&& TYPE_KEYWORDS.contains(&t.text.as_str())
|
||||
&& !self.nth(1).is_sym("'")
|
||||
|
||||
@@ -67,13 +67,19 @@ pub(crate) fn error_file(source: &str) -> SourceFile {
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `t` closes, or opens, a construct an enclosing parse loop is
|
||||
/// responsible for. [`Parser::at_sync_stop`] asks it about the cursor; the
|
||||
/// lookaheads that walk raw tokens ahead of the cursor ask it about those.
|
||||
pub(super) fn is_sync_stop(t: &Token) -> bool {
|
||||
t.kind == TokenKind::Keyword
|
||||
&& (SYNC_CLOSERS.contains(&t.text.as_str()) || SYNC_OPENERS.contains(&t.text.as_str()))
|
||||
}
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
/// True when the cursor sits on a token recovery must not consume: it
|
||||
/// closes, or opens, a construct an enclosing loop is responsible for.
|
||||
pub(super) fn at_sync_stop(&self) -> bool {
|
||||
let t = self.cur();
|
||||
t.kind == TokenKind::Keyword
|
||||
&& (SYNC_CLOSERS.contains(&t.text.as_str()) || SYNC_OPENERS.contains(&t.text.as_str()))
|
||||
is_sync_stop(self.cur())
|
||||
}
|
||||
|
||||
/// True on any of the `join` keywords that close a `fork`.
|
||||
|
||||
@@ -14,7 +14,10 @@
|
||||
//! * the bracket counter is **seeded from the list's own open bracket** —
|
||||
//! already consumed by the caller — so the `;`s inside a `for (…; …; …)`
|
||||
//! header are invisible and no skip can run past the bracket that closes
|
||||
//! the list it is in;
|
||||
//! the list it is in. An element that gave up standing *on* a bracket
|
||||
//! opened one it never closed, so that bracket is taken before the skip
|
||||
//! starts rather than counted as a level of its own (see
|
||||
//! [`Parser::recover_element`]);
|
||||
//! * a **line change** stops a skip. It is the one line-based rule in the
|
||||
//! parser, and it is what makes `module m (input logic a, inp⏎ output b);`
|
||||
//! cost one port instead of the rest of the list.
|
||||
@@ -245,6 +248,17 @@ impl<'a> Parser<'a> {
|
||||
// neither ends here nor eats a separator, so take one token to
|
||||
// guarantee it advances.
|
||||
self.bump();
|
||||
} else if self.at_open_bracket() {
|
||||
// The element gave up standing *on* a bracket, which is therefore
|
||||
// one it opened and never closed — the `(` of a half-typed
|
||||
// `.DEPTH(` (see `Parser::value_runs_into_next_instance`). That
|
||||
// bracket is part of the broken element, not a level the skip has
|
||||
// to balance: counting it would put the skip one level below the
|
||||
// list, where the line-change rule is not read, and the rest of
|
||||
// the body would be swallowed looking for a `)` that was never
|
||||
// written. Taken here, the skip starts inside it at the list's own
|
||||
// level and stops at the next line as it does everywhere else.
|
||||
self.bump();
|
||||
}
|
||||
self.skip_inside_brackets(false);
|
||||
let _ = self.take_dangling();
|
||||
@@ -253,6 +267,12 @@ impl<'a> Parser<'a> {
|
||||
RawText { text: self.slice(span), col, span }
|
||||
}
|
||||
|
||||
/// True on a token that opens a bracket.
|
||||
fn at_open_bracket(&self) -> bool {
|
||||
let t = self.cur();
|
||||
t.is_sym("(") || t.is_sym("[") || t.is_sym("{")
|
||||
}
|
||||
|
||||
/// The extent a recovery covers: from `start` through the last token it
|
||||
/// took, or the empty range at `start` when it took none (the sync point
|
||||
/// was already under the cursor).
|
||||
|
||||
@@ -10,8 +10,10 @@
|
||||
//! The recovery is deliberately hard to reach. It fires only after a real
|
||||
//! parse failure, and only when that failure is the grammar refusing a
|
||||
//! `else / `elsif / `endif that closes a region which is genuinely open
|
||||
//! and which the failed item did not open, with a bracket the arm left
|
||||
//! open. Everything else — a plain syntax error that merely sits near a
|
||||
//! and which the failed item did not open — with a bracket the arm left
|
||||
//! open, or with the arm behind the directive re-writing the very header
|
||||
//! the failed item began with (`docs/features/parser-skips/README.md`).
|
||||
//! Everything else — a plain syntax error that merely sits near a
|
||||
//! directive, a garbage token run with directives in it, an unterminated
|
||||
//! region, a stray closer with nothing open — still refuses.
|
||||
//! See `docs/features/directive-split/README.md`.
|
||||
@@ -106,7 +108,92 @@ fn construct_end(head: &[Token]) -> ConstructEnd {
|
||||
ConstructEnd::Unknown
|
||||
}
|
||||
|
||||
/// The unit whose body a loop is reading, as [`Parser::at_rival_header`]
|
||||
/// needs it.
|
||||
pub(super) struct UnitHead<'h> {
|
||||
/// The unit's keyword, as written: `module`, `macromodule`, `interface`
|
||||
/// or `program`.
|
||||
pub(super) kw: &'h str,
|
||||
/// The unit's name.
|
||||
pub(super) name: &'h str,
|
||||
/// Item-scope conditional regions open at the unit's own first token.
|
||||
pub(super) conds: u32,
|
||||
/// The lowest item-scope nesting the body has reached since it started.
|
||||
/// Below `conds` means the region that stood open at the header was
|
||||
/// closed inside the body, so a directive at the cursor continues some
|
||||
/// later region rather than that one.
|
||||
pub(super) floor: u32,
|
||||
}
|
||||
|
||||
/// The keyword that closes a unit, given its opening keyword — or `None` for
|
||||
/// a keyword that opens no unit. `interface class` is a class and closes with
|
||||
/// `endclass`; the caller rules it out by requiring a name after the keyword.
|
||||
fn unit_end_kw(t: &Token) -> Option<&'static str> {
|
||||
if t.kind != TokenKind::Keyword {
|
||||
return None;
|
||||
}
|
||||
match t.text.as_str() {
|
||||
"module" | "macromodule" => Some("endmodule"),
|
||||
"interface" => Some("endinterface"),
|
||||
"program" => Some("endprogram"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `t` opens a unit that `close` ends. Its own test, so a unit
|
||||
/// *nested* in a captured body cannot end the extent scan on its closer.
|
||||
fn opens_unit(t: &Token, close: &str) -> bool {
|
||||
unit_end_kw(t) == Some(close)
|
||||
}
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
/// True when the cursor stands on the `` `else `` / `` `elsif `` of a
|
||||
/// region opened *before* `head` was written, and the arm behind it
|
||||
/// re-writes `head`'s own keyword and name.
|
||||
///
|
||||
/// That is one header written twice across the arms of a region — the
|
||||
/// `jtag_if.sv` shape — not a unit nested inside another one. Both
|
||||
/// spellings are bracket-balanced, so nothing fails until the outer unit
|
||||
/// reaches EOF looking for its closer; the body loop asks this before
|
||||
/// each item instead, and fails where the evidence is.
|
||||
/// See `docs/features/parser-skips/README.md`.
|
||||
pub(super) fn at_rival_header(&self, head: &UnitHead) -> bool {
|
||||
if !continues_conditional(self.cur()) {
|
||||
return false;
|
||||
}
|
||||
// A region must have been open at the header, must still be the live
|
||||
// one (nothing opened since is still open) and must never have been
|
||||
// closed inside the body.
|
||||
if head.conds == 0 || self.open_conds != head.conds || head.floor != head.conds {
|
||||
return false;
|
||||
}
|
||||
self.nth(1).is_kw(head.kw)
|
||||
&& self.nth(2).kind == TokenKind::Ident
|
||||
&& self.nth(2).text == head.name
|
||||
}
|
||||
|
||||
/// The closing keyword of the unit a rival header opened, or `None` when
|
||||
/// the item that failed at `mark` is not one.
|
||||
///
|
||||
/// The mirror of [`Parser::at_rival_header`], read from the tokens rather
|
||||
/// than from a flag on the error: [`ParseError`] is public and carries
|
||||
/// only a message and a position, and every other condition of this
|
||||
/// trigger is already read from the mark and the cursor — so all of the
|
||||
/// evidence stays in one place and no error path can set the flag by
|
||||
/// accident.
|
||||
fn rival_end_kw(&self, mark: &ItemMark) -> Option<&'static str> {
|
||||
let head = self.tokens.get(mark.pos)?;
|
||||
let end = unit_end_kw(head)?;
|
||||
let name = self.tokens.get(mark.pos + 1)?;
|
||||
if name.kind != TokenKind::Ident {
|
||||
return None;
|
||||
}
|
||||
let rival = self.nth(1).is_kw(&head.text)
|
||||
&& self.nth(2).kind == TokenKind::Ident
|
||||
&& self.nth(2).text == name.text;
|
||||
rival.then_some(end)
|
||||
}
|
||||
|
||||
/// Count the conditional-compilation directive standing at the cursor,
|
||||
/// which the caller is about to consume as an `ItemKind::Directive`.
|
||||
///
|
||||
@@ -150,7 +237,9 @@ impl<'a> Parser<'a> {
|
||||
err: ParseError,
|
||||
) -> PResult<ItemKind> {
|
||||
if self.at_split_conditional(mark) {
|
||||
if let Some((end_pos, conds_after)) = self.scan_split_extent(mark) {
|
||||
if let Some((end_pos, conds_after)) =
|
||||
self.scan_split_extent(mark, self.rival_end_kw(mark))
|
||||
{
|
||||
// The block swallowed the region's own `else / `endif, which
|
||||
// *are* item-scope nesting even though they now sit inside
|
||||
// opaque bytes. The extent scan already worked out what they
|
||||
@@ -202,9 +291,12 @@ impl<'a> Parser<'a> {
|
||||
/// and ends nothing: it is broken input, and the parse error stands;
|
||||
/// 3. the item's own conditional nesting is back to zero there, so the
|
||||
/// live region is one opened *before* the item rather than by it;
|
||||
/// 4. the arm left a bracket open, i.e. it is structurally a fragment.
|
||||
/// A missing `;` leaves nothing open and is indistinguishable from a
|
||||
/// typo, so it is refused.
|
||||
/// 4. the arm is structurally a fragment. Two spellings qualify: it left
|
||||
/// a bracket open (`(`, `[` or `{` unmatched), or it is a **unit
|
||||
/// header the next arm writes again** ([`Parser::rival_end_kw`]) — a
|
||||
/// header written twice is as much a fragment as an unclosed bracket,
|
||||
/// and it is the only bracket-balanced shape allowed in. A missing `;`
|
||||
/// leaves neither, is indistinguishable from a typo, and is refused.
|
||||
fn at_split_conditional(&self, mark: &ItemMark) -> bool {
|
||||
let at = self.cur();
|
||||
if !continues_conditional(at) && !closes_conditional(at) {
|
||||
@@ -228,7 +320,7 @@ impl<'a> Parser<'a> {
|
||||
brackets -= 1;
|
||||
}
|
||||
}
|
||||
cond == 0 && brackets > 0
|
||||
cond == 0 && (brackets > 0 || self.rival_end_kw(mark).is_some())
|
||||
}
|
||||
|
||||
/// One past the last token of the construct the split region belongs to,
|
||||
@@ -248,13 +340,25 @@ impl<'a> Parser<'a> {
|
||||
/// no region live is a stray closer, not a split, and gives up — the same
|
||||
/// refusal the trigger makes, repeated here because the scan walks past
|
||||
/// the point the trigger looked at.
|
||||
fn scan_split_extent(&self, mark: &ItemMark) -> Option<(usize, u32)> {
|
||||
///
|
||||
/// `unit_end` is `Some(closing keyword)` for a rival unit header, whose
|
||||
/// `;` closes only its *header*: the block is the whole unit, so the scan
|
||||
/// runs to the matching `endmodule` / `endinterface` / `endprogram`
|
||||
/// instead — counting units of the same kind on the way, so one nested in
|
||||
/// the body cannot end it early. (An `interface class` nested in a
|
||||
/// captured `interface` closes with `endclass`, leaves the count above
|
||||
/// zero and makes the scan give up: the parse error stands, which is the
|
||||
/// safe side.)
|
||||
fn scan_split_extent(&self, mark: &ItemMark, unit_end: Option<&str>) -> Option<(usize, u32)> {
|
||||
// Regions this scan opened, and regions that were already open when
|
||||
// it started. A directive at scan level zero belongs to the latter.
|
||||
let mut cond = 0i32;
|
||||
let mut live = mark.conds;
|
||||
let mut closed_outer = false;
|
||||
let mut brackets = 0i32;
|
||||
// Units of the head's kind open at `i`, counted only in `unit_end`
|
||||
// mode. The head at `mark.pos` is itself the first one.
|
||||
let mut units = 0i32;
|
||||
let mut i = mark.pos;
|
||||
while let Some(t) = self.tokens.get(i) {
|
||||
if t.kind == TokenKind::Eof {
|
||||
@@ -283,6 +387,15 @@ impl<'a> Parser<'a> {
|
||||
if brackets < 0 {
|
||||
return None;
|
||||
}
|
||||
} else if let Some(close) = unit_end {
|
||||
if opens_unit(t, close) {
|
||||
units += 1;
|
||||
} else if t.is_kw(close) {
|
||||
units -= 1;
|
||||
if units == 0 && cond == 0 && closed_outer {
|
||||
return Some((self.past_end_label(i + 1), live));
|
||||
}
|
||||
}
|
||||
} else if t.is_sym(";") && brackets == 0 && cond == 0 && closed_outer {
|
||||
return Some((i + 1, live));
|
||||
}
|
||||
|
||||
@@ -290,3 +290,58 @@ fn a_struct_member_may_be_declared_rand() {
|
||||
assert!(s.members[2].qualifiers.is_empty());
|
||||
assert_eq!(s.members[0].declarators[0].name, "cpol");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Net delays on either side of the data type (TODO §38.2,
|
||||
// `docs/features/parser-skips/README.md`)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The net delay of a single-declaration module, with the side of the data
|
||||
/// type it was written on.
|
||||
fn net_delay_of(src: &str) -> (String, bool) {
|
||||
let f = parse_ok(src);
|
||||
let d = match &module_of(&f).items[0].kind {
|
||||
ItemKind::DataDecl(d) => d,
|
||||
_ => panic!("expected a declaration"),
|
||||
};
|
||||
let delay = d.delay.as_ref().expect("a net delay");
|
||||
(src[delay.expr.span.as_range()].to_string(), delay.after_type)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_net_delay_is_read_on_either_side_of_the_data_type() {
|
||||
// Before the type is what the corpus writes; after it is where IEEE
|
||||
// 1800 §6.7 puts `delay3`, and where
|
||||
// `pulp_riscv_dbg/tb/unused/SimDTM.sv:38` writes it.
|
||||
assert_eq!(net_delay_of("module m;\n wire #5 w;\nendmodule\n"), ("5".into(), false));
|
||||
assert_eq!(
|
||||
net_delay_of("module m;\n wire [31:0] #0.1 x = y;\nendmodule\n"),
|
||||
("0.1".into(), true)
|
||||
);
|
||||
// After a plain `logic`-typed net, and after a signed keyword run.
|
||||
assert_eq!(net_delay_of("module m;\n wire logic #3 a;\nendmodule\n"), ("3".into(), true));
|
||||
assert_eq!(
|
||||
net_delay_of("module m;\n wire signed [7:0] #(1:2:3) b;\nendmodule\n"),
|
||||
("(1:2:3)".into(), true)
|
||||
);
|
||||
// The before position is unmoved by any of it.
|
||||
assert_eq!(
|
||||
net_delay_of("module m;\n wire #(1:2:3) signed [7:0] c;\nendmodule\n"),
|
||||
("(1:2:3)".into(), false)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_net_delay_written_on_both_sides_is_an_error() {
|
||||
let msg = parse_err("module m;\n wire #5 [31:0] #6 x;\nendmodule\n");
|
||||
assert!(msg.contains("before or after the type, not both"), "{msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_net_declaration_reads_a_delay() {
|
||||
// A variable has no `delay3`, so the `#` is not swallowed here — it is
|
||||
// an ordinary syntax error, exactly as it was before either position
|
||||
// was accepted.
|
||||
assert!(parse_err("module m;\n logic #5 x;\nendmodule\n").contains("expected"));
|
||||
assert!(parse_err("module m;\n logic [7:0] #5 x;\nendmodule\n").contains("expected"));
|
||||
}
|
||||
@@ -190,7 +190,7 @@ fn a_gate_takes_a_multi_value_delay_list() {
|
||||
// The one-value parenthesized spelling keeps its `Paren` node, which
|
||||
// is what makes `#(5)` print back as `#(5)` and not as `#5`.
|
||||
let ItemKind::GateInstantiation(g) = &m.items[2].kind else { panic!("expected a gate") };
|
||||
assert!(matches!(g.delay[0].kind, ExprKind::Paren { .. }));
|
||||
assert!(matches!(g.delay[0].expr.kind, ExprKind::Paren { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -218,3 +218,41 @@ fn a_bind_instance_may_be_a_hierarchical_path() {
|
||||
let ItemKind::Bind(b) = &f.items[0].kind else { panic!("expected a bind") };
|
||||
assert_eq!(b.instances.iter().map(|i| i.text.as_str()).collect::<Vec<_>>(), ["a.b", "plain"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inline_aggregate_is_a_parameter_override_argument() {
|
||||
// TODO §45.3: a `parameter type` defaulting to an anonymous aggregate is
|
||||
// overridden with one, and `parse_type_ref` has read that body all along —
|
||||
// only `parse_expr_or_type`'s door was shut (`struct`/`union`/`enum` are
|
||||
// not `TYPE_KEYWORDS`), so the value read as an expression and failed.
|
||||
for src in [
|
||||
"module m;\n sub #(.T(struct packed { logic a; })) u ();\nendmodule\n",
|
||||
"module m;\n sub #(.T(union packed { logic [7:0] a; })) u ();\nendmodule\n",
|
||||
"module m;\n sub #(.T(enum logic [1:0] {A, B})) u ();\nendmodule\n",
|
||||
"module m;\n sub #(.T(struct packed { /* why */ logic a; })) u ();\nendmodule\n",
|
||||
] {
|
||||
let f = parse_ok(src);
|
||||
let ItemKind::Instantiation(i) = &module_of(&f).items[0].kind else {
|
||||
panic!("expected an instantiation")
|
||||
};
|
||||
let params = i.params.as_ref().expect("an override list");
|
||||
let value = oks(params)[0].expr.as_ref().expect("a value");
|
||||
assert!(matches!(value.kind, ExprKind::Type(_)), "{src:?} read as {:?}", value.kind);
|
||||
// Strict and tolerant must agree: the tolerant parser reports nothing
|
||||
// where the strict one succeeds.
|
||||
let (_, diags) = crate::parse_source_tolerant(src);
|
||||
assert!(diags.is_empty(), "{src:?} left {diags:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ordered_parameter_override_takes_an_inline_aggregate_too() {
|
||||
// The bare-expression arm of `parse_connection` shares `parse_expr_or_type`
|
||||
// with the named one, so both doors opened at once.
|
||||
let f = parse_ok("module m;\n sub #(struct packed { logic a; }) u ();\nendmodule\n");
|
||||
let ItemKind::Instantiation(i) = &module_of(&f).items[0].kind else {
|
||||
panic!("expected an instantiation")
|
||||
};
|
||||
let params = i.params.as_ref().expect("an override list");
|
||||
assert!(matches!(oks(params)[0].expr.as_ref().expect("a value").kind, ExprKind::Type(_)));
|
||||
}
|
||||
@@ -628,3 +628,158 @@ fn an_opening_split_that_is_the_last_item_does_not_eat_the_closing_keyword() {
|
||||
"a directive starting a statement list is pass-through, not a split"
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Rival unit headers written across the arms of one region
|
||||
// (`docs/features/parser-skips/README.md`)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The `jtag_if.sv` shape, in the four spellings that differ only in the
|
||||
/// header: `interface`/`module`, with and without `#( ... )`, with `()` and
|
||||
/// with a real port list. Every one of them is one verbatim item running
|
||||
/// from the first header to the unit's own closing keyword.
|
||||
#[test]
|
||||
fn rival_unit_headers_across_one_region_become_one_verbatim_item() {
|
||||
for (why, src, ends) in [
|
||||
(
|
||||
"interface, `#( ... ) ()` — hw/dv/sv/jtag_agent/jtag_if.sv:6",
|
||||
"`ifdef GATE_LEVEL\n interface jtag_if #(parameter int unsigned P = 41_664) \
|
||||
();\n`else\n interface jtag_if #(parameter int unsigned P = 20_000) \
|
||||
();\n`endif\n wire tck;\nendinterface\nparameter int AFTER = 1;\n",
|
||||
"endinterface",
|
||||
),
|
||||
(
|
||||
"interface, no parameter list",
|
||||
"`ifdef A\ninterface i ();\n`else\ninterface i ();\n`endif\n wire \
|
||||
tck;\nendinterface\nparameter int AFTER = 1;\n",
|
||||
"endinterface",
|
||||
),
|
||||
(
|
||||
"module, a real port list",
|
||||
"`ifdef A\nmodule m (input a, output b);\n`else\nmodule m (input a, output \
|
||||
b);\n`endif\n wire x;\nendmodule\nparameter int AFTER = 1;\n",
|
||||
"endmodule",
|
||||
),
|
||||
(
|
||||
"module, a closing label",
|
||||
"`ifdef A\nmodule m #(parameter int W = 1) ();\n`else\nmodule m #(parameter int W = \
|
||||
2) ();\n`endif\n wire x;\nendmodule : m\nparameter int AFTER = 1;\n",
|
||||
"endmodule : m",
|
||||
),
|
||||
] {
|
||||
let f = parse_ok(src);
|
||||
let kinds = split_items(&f);
|
||||
assert_eq!(kinds.len(), 3, "{why}: {kinds:?}");
|
||||
assert!(kinds[0].starts_with("directive:`ifdef"), "{why}: {kinds:?}");
|
||||
assert_eq!(kinds[2], "param", "{why}: the item after the unit was not swallowed");
|
||||
let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("{why}: expected verbatim") };
|
||||
assert_eq!(raw.text, src[raw.span.as_range()], "{why}");
|
||||
assert!(raw.text.ends_with(ends), "{why}: {:?}", raw.text);
|
||||
assert!(raw.text.contains("`else") && raw.text.contains("`endif"), "{why}: {:?}", raw.text);
|
||||
// The whole unit is inside the block, its body included.
|
||||
assert!(raw.text.contains("wire"), "{why}: {:?}", raw.text);
|
||||
assert_eq!(open_conds_after(src), 0, "{why}: the region's own `endif was accounted for");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rival_headers_produce_the_same_tree_in_both_modes() {
|
||||
let src = "`ifdef GATE_LEVEL\n interface jtag_if #(parameter int unsigned P = 41_664) \
|
||||
();\n`else\n interface jtag_if #(parameter int unsigned P = 20_000) \
|
||||
();\n`endif\n wire tck;\nendinterface\n";
|
||||
let strict = parse_ok(src);
|
||||
let toks = tokenize(src).expect("lex error");
|
||||
let (tolerant, diags) = parse_tolerant(toks, src);
|
||||
assert!(diags.is_empty(), "{diags:?}");
|
||||
assert_eq!(split_items(&strict), split_items(&tolerant));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_written_around_a_rival_header_are_kept() {
|
||||
// The real file writes a comment inside each arm and one before the
|
||||
// region; none of them may be dropped.
|
||||
let src = "// head\n`ifdef GATE_LEVEL // which\n // 24MHz for GLS\n interface jtag_if \
|
||||
();\n`else\n // 50MHz for DV\n interface jtag_if ();\n`endif\n // pins\n wire \
|
||||
tck;\nendinterface // done\n";
|
||||
let f = parse_ok(src);
|
||||
assert_eq!(texts(&f.items[0].meta.leading), ["// head"]);
|
||||
assert_eq!(f.items[0].meta.trailing.as_ref().expect("the `ifdef's comment").text, "// which");
|
||||
// The capture starts at the item's *first token*, so the comment written
|
||||
// in front of the header is the item's own leading comment — the same
|
||||
// place every other split puts it — and the rest are inside the block.
|
||||
assert_eq!(texts(&f.items[1].meta.leading), ["// 24MHz for GLS"]);
|
||||
let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") };
|
||||
for c in ["// 50MHz for DV", "// pins"] {
|
||||
assert!(raw.text.contains(c), "{c} was dropped from {:?}", raw.text);
|
||||
}
|
||||
assert!(!raw.text.contains("// done"), "the trailing comment was swallowed");
|
||||
assert_eq!(f.items[1].meta.trailing.as_ref().expect("the comment survived").text, "// done");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_unit_nested_in_a_captured_body_does_not_end_the_scan_early() {
|
||||
// The extent scan counts units of the head's kind, so the *inner*
|
||||
// `endmodule` cannot be mistaken for the rival unit's own.
|
||||
let src = "`ifdef A\nmodule m ();\n`else\nmodule m ();\n`endif\n module inner ();\n \
|
||||
endmodule\n wire x;\nendmodule\nparameter int AFTER = 1;\n";
|
||||
let f = parse_ok(src);
|
||||
let kinds = split_items(&f);
|
||||
assert_eq!(kinds.len(), 3, "{kinds:?}");
|
||||
let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") };
|
||||
assert!(raw.text.contains("module inner"), "{:?}", raw.text);
|
||||
assert!(raw.text.ends_with("endmodule"), "{:?}", raw.text);
|
||||
assert_eq!(kinds[2], "param", "{kinds:?}");
|
||||
}
|
||||
|
||||
// -- the three negatives ----------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_second_unit_in_an_arm_of_a_region_opened_inside_the_body_is_still_an_error() {
|
||||
// Two nested units, which is illegal: the region the `else belongs to
|
||||
// was opened *by the body*, not before the header, so the arm is not a
|
||||
// rival spelling of anything.
|
||||
let msg = parse_err(
|
||||
"`ifdef OUTER\nmodule m;\n`ifdef A\n wire a;\n`else\nmodule m;\n`endif\n wire \
|
||||
b;\nendmodule\n",
|
||||
);
|
||||
assert!(msg.contains("endmodule"), "{msg}");
|
||||
// The same shape with no region open at all around the outer unit.
|
||||
let msg = parse_err(
|
||||
"module m;\n`ifdef A\n wire a;\n`else\nmodule m;\n wire \
|
||||
b;\n`endif\nendmodule\n",
|
||||
);
|
||||
assert!(msg.contains("endmodule"), "{msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_different_name_after_the_else_is_not_a_rival_header() {
|
||||
let msg = parse_err(
|
||||
"`ifdef A\ninterface i ();\n`else\ninterface j ();\n`endif\n wire \
|
||||
x;\nendinterface\n",
|
||||
);
|
||||
assert!(msg.contains("endinterface"), "{msg}");
|
||||
// Nor is a different keyword for the same name.
|
||||
let msg = parse_err(
|
||||
"`ifdef A\ninterface i ();\n`else\nmodule i ();\n`endif\n wire x;\nendinterface\n",
|
||||
);
|
||||
assert!(msg.contains("endinterface"), "{msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_region_closed_before_the_header_leaves_the_else_stray() {
|
||||
// The region opened at the top of the file is closed before the
|
||||
// interface begins, so the `else below closes nothing: broken input,
|
||||
// and the parse error stands.
|
||||
let msg = parse_err(
|
||||
"`ifdef A\n wire a;\n`endif\ninterface i ();\n`else\n interface i ();\n`endif\n wire \
|
||||
x;\nendinterface\n",
|
||||
);
|
||||
assert!(msg.contains("endinterface"), "{msg}");
|
||||
// And a region closed *inside* the body before the `else: the header's
|
||||
// region is gone, so the live one is not the one it was written under.
|
||||
let msg = parse_err(
|
||||
"`ifdef OUTER\ninterface i ();\n`endif\n`ifdef B\n wire a;\n`else\n interface i \
|
||||
();\n`endif\nendinterface\n",
|
||||
);
|
||||
assert!(msg.contains("endinterface"), "{msg}");
|
||||
}
|
||||
@@ -67,6 +67,7 @@ fn collect_sva(items: &[vlog_parser::ast::Item], out: &mut Vec<(u32, u32)>) {
|
||||
ItemKind::Package { items, .. } => collect_sva(items, out),
|
||||
ItemKind::Class(c) => collect_sva(&c.items, out),
|
||||
ItemKind::GenerateRegion { items, .. } => collect_sva(items, out),
|
||||
ItemKind::GenBlock(b) => collect_sva(&b.items, out),
|
||||
ItemKind::GenIf(g) => {
|
||||
collect_sva(&g.then.items, out);
|
||||
match g.els.as_deref() {
|
||||
|
||||
@@ -101,6 +101,8 @@ const BROKEN: &[(&str, &str)] = &[
|
||||
("half-typed instantiation", "module m;\n sub u0 (.a(\nendmodule\n"),
|
||||
("garbage between modules", "module a;\nendmodule\n@#!\nmodule b;\n wire w;\nendmodule\n"),
|
||||
("error in generate", "module m;\ngenerate\n if (W) begin\n wire ;\n end\nendgenerate\n wire ok;\nendmodule\n"),
|
||||
("module-scope begin block", "module m;\n begin\n wire a;\n end\n wire b;\nendmodule\n"),
|
||||
("override runs into the next instance", "module m;\n sub #(.W(8), .D(\n u0 (.a(x));\nendmodule\n"),
|
||||
("all garbage", "!!! ???\n"),
|
||||
("stray endmodule", "endmodule\nmodule b;\nendmodule\n"),
|
||||
("unterminated string", "module m;\n initial $display(\"abc);\nendmodule\n"),
|
||||
@@ -190,6 +192,7 @@ fn walk_item(item: &Item, out: &mut Vec<(vlog_parser::TextRange, String)>) {
|
||||
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => {
|
||||
items.iter().for_each(|i| walk_item(i, out))
|
||||
}
|
||||
ItemKind::GenBlock(b) => b.items.iter().for_each(|i| walk_item(i, out)),
|
||||
ItemKind::GenIf(g) => walk_gen_if(g, out),
|
||||
ItemKind::GenFor(g) => g.body.items.iter().for_each(|i| walk_item(i, out)),
|
||||
ItemKind::GenCase(g) => {
|
||||
@@ -516,6 +519,90 @@ fn a_half_typed_instantiation_costs_one_connection() {
|
||||
assert_eq!(error_nodes(&file).len(), 1);
|
||||
}
|
||||
|
||||
/// The QA shape of 2026-09-02 (`docs/features/header-recovery/README.md`):
|
||||
/// a half-typed `#(` override whose value would read as the next instance.
|
||||
/// Nothing inside the list fails on its own — `u0 (.a(x), .b(y))` is a legal
|
||||
/// call with named arguments — so before §36.2 the greedy parse swallowed the
|
||||
/// instance and the whole instantiation collapsed into one error item that ate
|
||||
/// the `endmodule` too. It now costs the one override.
|
||||
#[test]
|
||||
fn a_half_typed_override_does_not_swallow_the_next_instance() {
|
||||
let src = "module m;\n sub #(.WIDTH(8), .DEPTH(\n u0 (.a(x), .b(y));\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
assert_eq!(&src[diags[0].span.as_range()], "(", "the diagnostic points at the unclosed `(`");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 1, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
|
||||
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
|
||||
panic!("{}", kind_name(&m.items[0]))
|
||||
};
|
||||
let params = inst.params.as_ref().expect("an override list");
|
||||
assert_eq!(params.len(), 2);
|
||||
assert_eq!(params[0].ok().map(|c| c.name.as_str()), Some("WIDTH"));
|
||||
assert_eq!(params[1].error().map(|r| r.text.as_str()), Some(".DEPTH("));
|
||||
assert_eq!(inst.instances.len(), 1);
|
||||
assert_eq!(inst.instances[0].name, "u0");
|
||||
let Connections::Named(conns) = &inst.instances[0].conns else { panic!("named connections") };
|
||||
assert_eq!(conns.len(), 2, "both connections of the instance survive");
|
||||
// The `endmodule` was consumed by the module, not by the error: one
|
||||
// diagnostic above already says so, and the module's span ends at it.
|
||||
assert_eq!(&src[m.items[0].span.as_range()], "sub #(.WIDTH(8), .DEPTH(\n u0 (.a(x), .b(y));");
|
||||
}
|
||||
|
||||
/// The same lookahead covers the connection list. `u1` cannot be a second
|
||||
/// instance of `sub` — no comma was written — so it becomes an item of the
|
||||
/// module, which is one error node instead of the whole rest of the body.
|
||||
#[test]
|
||||
fn a_half_typed_connection_does_not_swallow_the_next_instance() {
|
||||
let src = "module m;\n sub u0 (.a(\n u1 (.b(y));\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 2, "{diags:?}");
|
||||
assert_eq!(&src[diags[0].span.as_range()], "(");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 2, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
|
||||
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
|
||||
panic!("{}", kind_name(&m.items[0]))
|
||||
};
|
||||
let Connections::Named(conns) = &inst.instances[0].conns else { panic!("named connections") };
|
||||
assert_eq!(conns.len(), 1);
|
||||
assert_eq!(conns[0].error().map(|r| r.text.as_str()), Some(".a("));
|
||||
assert_eq!(error_nodes(&file).len(), 2, "the connection and the orphaned `u1 (...)`");
|
||||
}
|
||||
|
||||
/// The ambiguous shape stays ambiguous. With the parentheses balancing, the
|
||||
/// value *closes* — the lookahead says nothing is wrong and the greedy parse
|
||||
/// wins, exactly as before §36.2. Pinned so nobody "fixes" it: the parser
|
||||
/// cannot know whether the author meant a call or a forgotten `)`.
|
||||
#[test]
|
||||
fn a_connection_value_whose_parens_balance_is_still_read_greedily() {
|
||||
let src = "module m;\n sub #(.D(\n u0 (.a(x)));\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 2, "{diags:?}");
|
||||
assert!(diags.iter().all(|d| !d.message.contains("unclosed")), "{diags:?}");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 1);
|
||||
let ItemKind::Error(raw) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
|
||||
assert_eq!(raw.text, "sub #(.D(\n u0 (.a(x)));");
|
||||
}
|
||||
|
||||
/// A legal value written over three lines — whose middle line opens with an
|
||||
/// identifier followed by `(`, the very shape the lookahead hunts for — parses
|
||||
/// identically in both modes, because the value closes.
|
||||
#[test]
|
||||
fn a_legal_multi_line_connection_value_is_untouched() {
|
||||
let src = "module m;\n sub #(.DEPTH(\n f(1)\n )) u0 (.a(x));\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert!(diags.is_empty(), "{diags:?}");
|
||||
assert!(parse_source(src).is_ok(), "and strict mode reads it too");
|
||||
let m = module_named(&file, "m");
|
||||
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
|
||||
panic!("{}", kind_name(&m.items[0]))
|
||||
};
|
||||
let params = inst.params.as_ref().expect("an override list");
|
||||
assert_eq!(params.len(), 1);
|
||||
assert_eq!(params[0].ok().map(|c| c.name.as_str()), Some("DEPTH"));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Header recovery (TODO §32): one test per shape, with exact counts
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -713,6 +800,100 @@ fn an_error_in_a_generate_block_does_not_eat_the_endgenerate() {
|
||||
assert!(matches!(&m.items[1].kind, ItemKind::DataDecl(_)));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// A bare `begin … end` where an item belongs (TODO §36.1)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The block a `begin` opens at module scope is kept, with its items and with
|
||||
/// everything written after it. It is still an error — one diagnostic, at the
|
||||
/// keyword — so the formatter goes on refusing the file; what changed is that
|
||||
/// recovery no longer throws the rest of the module away.
|
||||
#[test]
|
||||
fn a_module_scope_begin_block_keeps_its_items_and_the_items_after_it() {
|
||||
let src = "module m;\n begin\n wire a;\n end\n assign b = 1;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
assert_eq!(&src[diags[0].span.as_range()], "begin");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 2, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
|
||||
let ItemKind::GenBlock(b) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
|
||||
assert!(b.is_block);
|
||||
assert_eq!(b.label, None);
|
||||
assert_eq!(b.items.len(), 1);
|
||||
assert!(matches!(&b.items[0].kind, ItemKind::DataDecl(_)), "{}", kind_name(&b.items[0]));
|
||||
assert!(matches!(&m.items[1].kind, ItemKind::ContAssign(_)), "{}", kind_name(&m.items[1]));
|
||||
assert!(error_nodes(&file).is_empty(), "the block is a node, not a leaf");
|
||||
}
|
||||
|
||||
/// The same one scope in: `generate begin … end endgenerate`. The region keeps
|
||||
/// its `endgenerate` and the module keeps the items after it.
|
||||
#[test]
|
||||
fn a_generate_region_begin_block_keeps_its_items_and_the_items_after_it() {
|
||||
let src = "module m;\n generate\n begin : g\n wire a;\n end\n \
|
||||
endgenerate\n wire ok;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
assert_eq!(&src[diags[0].span.as_range()], "begin");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 2, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
|
||||
let ItemKind::GenerateRegion { items, .. } = &m.items[0].kind else {
|
||||
panic!("{}", kind_name(&m.items[0]))
|
||||
};
|
||||
assert_eq!(items.len(), 1);
|
||||
let ItemKind::GenBlock(b) = &items[0].kind else { panic!("{}", kind_name(&items[0])) };
|
||||
assert_eq!(b.label.as_deref(), Some("g"));
|
||||
assert_eq!(b.items.len(), 1);
|
||||
assert!(matches!(&m.items[1].kind, ItemKind::DataDecl(_)), "{}", kind_name(&m.items[1]));
|
||||
}
|
||||
|
||||
/// Strict mode is untouched: both shapes are still a hard parse error, which
|
||||
/// is what keeps every corpus file byte-identical.
|
||||
#[test]
|
||||
fn strict_mode_still_refuses_a_bare_begin_block() {
|
||||
for src in [
|
||||
"module m;\n begin\n wire a;\n end\nendmodule\n",
|
||||
"module m;\n generate\n begin\n wire a;\n end\n endgenerate\nendmodule\n",
|
||||
] {
|
||||
let err = parse_source(src).expect_err("strict mode must refuse a bare `begin`");
|
||||
assert!(err.to_string().contains("begin"), "{err}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `end : label` on the recovered block lands in `end_label`, the way it does
|
||||
/// on any other generate block.
|
||||
#[test]
|
||||
fn a_bare_begin_block_keeps_its_end_label() {
|
||||
let src = "module m;\n begin : b\n wire a;\n end : b\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
let m = module_named(&file, "m");
|
||||
let ItemKind::GenBlock(b) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
|
||||
assert_eq!(b.label.as_deref(), Some("b"));
|
||||
assert_eq!(b.end_label.as_deref(), Some("b"));
|
||||
let label_span = b.end_label_span.expect("an end-label span");
|
||||
assert_eq!(&src[label_span.as_range()], "b");
|
||||
}
|
||||
|
||||
/// A block inside a block recovers the same way, once per keyword, and both
|
||||
/// blocks keep what was written in them.
|
||||
#[test]
|
||||
fn a_begin_block_nested_in_another_recovers_the_same_way() {
|
||||
let src = "module m;\n begin\n begin\n wire a;\n end\n end\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 2, "{diags:?}");
|
||||
for d in &diags {
|
||||
assert_eq!(&src[d.span.as_range()], "begin");
|
||||
}
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 1);
|
||||
let ItemKind::GenBlock(outer) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
|
||||
assert_eq!(outer.items.len(), 1);
|
||||
let ItemKind::GenBlock(inner) = &outer.items[0].kind else {
|
||||
panic!("{}", kind_name(&outer.items[0]))
|
||||
};
|
||||
assert!(matches!(&inner.items[0].kind, ItemKind::DataDecl(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_of_only_garbage_is_one_error_item() {
|
||||
for src in ["!!! ???\n", "@@@\n", "?\n"] {
|
||||
|
||||
@@ -34,6 +34,7 @@ fn walk(items: &[Item], f: &mut dyn FnMut(&Item)) {
|
||||
ItemKind::Package { items, .. } => walk(items, f),
|
||||
ItemKind::Class(c) => walk(&c.items, f),
|
||||
ItemKind::GenerateRegion { items, .. } => walk(items, f),
|
||||
ItemKind::GenBlock(b) => walk(&b.items, f),
|
||||
ItemKind::GenFor(g) => walk(&g.body.items, f),
|
||||
ItemKind::GenIf(g) => {
|
||||
walk(&g.then.items, f);
|
||||
|
||||
@@ -565,6 +565,7 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
|
||||
check_item(src, i, here);
|
||||
}
|
||||
}
|
||||
ItemKind::GenBlock(b) => check_gen_block(src, b, here),
|
||||
ItemKind::Directive(raw) | ItemKind::MacroItem(MacroCall { raw, .. }) => {
|
||||
assert_inside(src, "raw text", raw.span, here);
|
||||
}
|
||||
@@ -613,7 +614,7 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
|
||||
}
|
||||
ItemKind::GateInstantiation(g) => {
|
||||
for d in &g.delay {
|
||||
check_expr(src, d, here);
|
||||
check_expr(src, &d.expr, here);
|
||||
}
|
||||
for i in &g.instances {
|
||||
assert_inside(src, "gate instance", i.span, here);
|
||||
@@ -1226,7 +1227,7 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) {
|
||||
check_expr(src, lo, here);
|
||||
check_expr(src, hi, here);
|
||||
}
|
||||
ExprKind::MinTypMax { min, typ, max } => {
|
||||
ExprKind::MinTypMax { min, typ, max, .. } => {
|
||||
check_expr(src, min, here);
|
||||
check_expr(src, typ, here);
|
||||
check_expr(src, max, here);
|
||||
|
||||
@@ -353,19 +353,24 @@ fn params(module: &Module, text: &str) -> Vec<PlanParam> {
|
||||
|
||||
/// A parameter's default as an override list can write it, or nothing.
|
||||
///
|
||||
/// Two things disqualify one, and the corpus produced both from a single
|
||||
/// header (`common_cells/src/ecc_encode.sv`, a `parameter type` defaulting to
|
||||
/// an anonymous multi-line `struct packed`):
|
||||
/// Two things disqualify one:
|
||||
///
|
||||
/// * it is written across several lines — the source's own indentation means
|
||||
/// nothing inside a `#( ... )` on someone else's line, and re-flowing it
|
||||
/// would risk rewriting a string literal's spaces;
|
||||
/// * writing it back does not parse — lucisv's expression grammar does not
|
||||
/// accept an inline aggregate as a parameter override, and a skeleton that
|
||||
/// does not parse hands the user a red squiggle from our own server.
|
||||
/// * writing it back does not parse, which the probe below asks rather than
|
||||
/// guesses, because a skeleton that does not parse hands the user a red
|
||||
/// squiggle from our own server.
|
||||
///
|
||||
/// A default lucisv cannot write back is simply not offered: the tabstop comes
|
||||
/// up empty and the user types what they meant.
|
||||
///
|
||||
/// The probe is what makes this grow with the grammar. An **inline aggregate**
|
||||
/// default (`parameter type T = struct packed { logic a; }`) used to fail it —
|
||||
/// the override grammar refused a `struct` head — and was dropped; since
|
||||
/// TODO §45.3 the same probe passes and the type text is emitted. Only the
|
||||
/// multi-line spelling, which the corpus's `common_cells/src/ecc_encode.sv`
|
||||
/// writes, is still refused, and by the first rule rather than the second.
|
||||
fn default_text(text: &str, param: &ParamPort) -> String {
|
||||
let Some(expr) = ¶m.default else { return String::new() };
|
||||
let written = slice(text, expr.span).trim();
|
||||
@@ -743,6 +748,38 @@ endmodule
|
||||
assert!(parse_source_tolerant(&probe).1.is_empty(), "the skeleton must parse: {skeleton}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_one_line_inline_aggregate_default_is_emitted() {
|
||||
// TODO §45.3: the override grammar accepts an inline aggregate, so the
|
||||
// probe in `default_text` passes and the type text is offered instead
|
||||
// of an empty tabstop. Only the multi-line spelling is still dropped,
|
||||
// by the "written across several lines" rule above it.
|
||||
let text = "\
|
||||
module agg #(
|
||||
parameter type packed_t = struct packed {logic parity; logic [7:0] word;},
|
||||
parameter type state_e = enum logic [1:0] {IDLE, BUSY}
|
||||
) ();
|
||||
endmodule
|
||||
";
|
||||
let plan = plan(text, "agg");
|
||||
assert_eq!(
|
||||
plan.params,
|
||||
vec![
|
||||
PlanParam {
|
||||
name: "packed_t".into(),
|
||||
default: "struct packed {logic parity; logic [7:0] word;}".into(),
|
||||
},
|
||||
PlanParam {
|
||||
name: "state_e".into(),
|
||||
default: "enum logic [1:0] {IDLE, BUSY}".into(),
|
||||
},
|
||||
]
|
||||
);
|
||||
let skeleton = plan.render(&Layout::default());
|
||||
let probe = format!("module p;\n{skeleton}\nendmodule\n");
|
||||
assert!(parse_source_tolerant(&probe).1.is_empty(), "the skeleton must parse: {skeleton}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_line_type_is_shown_on_one_line() {
|
||||
let text = "\
|
||||
|
||||
@@ -42,7 +42,7 @@ pub use instantiate::{
|
||||
};
|
||||
pub use ports::{
|
||||
add_port, enclosing_module, may_have_port_action, port_action_modules, port_actions,
|
||||
propagate_ports, remove_port, ModuleRef, PortAction,
|
||||
propagate_ports, remove_port, sites_phrase, ModuleRef, PortAction,
|
||||
};
|
||||
pub use rename::{
|
||||
contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, RenameTarget,
|
||||
|
||||
@@ -150,6 +150,7 @@ pub(super) fn collect_instantiations<'t>(items: &'t [Item], out: &mut Vec<&'t In
|
||||
ItemKind::Module(module) => collect_instantiations(&module.items, out),
|
||||
ItemKind::Package { items, .. } => collect_instantiations(items, out),
|
||||
ItemKind::GenerateRegion { items, .. } => collect_instantiations(items, out),
|
||||
ItemKind::GenBlock(b) => collect_instantiations(&b.items, out),
|
||||
ItemKind::GenIf(gen) => {
|
||||
collect_gen_block(&gen.then, out);
|
||||
let mut els = gen.els.as_deref();
|
||||
|
||||
@@ -236,7 +236,12 @@ pub fn enclosing_module(text: &str, offset: u32) -> Option<String> {
|
||||
|
||||
/// "updates 3 instantiations" / "updates 1 instantiation" / "no instantiation
|
||||
/// in scope".
|
||||
fn sites_phrase(sites: usize) -> String {
|
||||
///
|
||||
/// Public because a server may have to write the same sentence with a count of
|
||||
/// its own: an offer that has not read the fan-out takes the number from its
|
||||
/// workspace index instead of from the plan, and the two must not come to be
|
||||
/// worded differently (`docs/features/lazy-code-action/README.md`).
|
||||
pub fn sites_phrase(sites: usize) -> String {
|
||||
match sites {
|
||||
0 => "no instantiation in scope".to_string(),
|
||||
1 => "updates 1 instantiation".to_string(),
|
||||
|
||||
@@ -179,7 +179,7 @@ impl<'a> Binder<'a> {
|
||||
|
||||
pub(super) fn bind_data_decl(&mut self, d: &DataDecl, span: TextRange, scope: ScopeId) {
|
||||
let kind = if d.net.is_some() { SymbolKind::Net } else { SymbolKind::Var };
|
||||
self.bind_opt_expr(d.delay.as_ref(), scope);
|
||||
self.bind_opt_expr(d.delay.as_ref().map(|n| &n.expr), scope);
|
||||
self.bind_declarators(&d.declarators, kind, &d.ty, span, scope);
|
||||
}
|
||||
|
||||
|
||||
@@ -175,7 +175,7 @@ impl<'a> Binder<'a> {
|
||||
// same rule connection port names follow).
|
||||
ExprKind::NamedArg { value, .. } => self.bind_expr(value, scope),
|
||||
ExprKind::Type(ty) => self.bind_data_type(ty, e.span, scope),
|
||||
ExprKind::MinTypMax { min, typ, max } => {
|
||||
ExprKind::MinTypMax { min, typ, max, .. } => {
|
||||
self.bind_expr(min, scope);
|
||||
self.bind_expr(typ, scope);
|
||||
self.bind_expr(max, scope);
|
||||
|
||||
@@ -108,7 +108,7 @@ impl<'a> Binder<'a> {
|
||||
ItemKind::Bind(b) => self.bind_bind(b, scope),
|
||||
ItemKind::GateInstantiation(g) => {
|
||||
for d in &g.delay {
|
||||
self.bind_expr(d, scope);
|
||||
self.bind_expr(&d.expr, scope);
|
||||
}
|
||||
for inst in &g.instances {
|
||||
if let (Some(name), Some(ns)) = (&inst.name, inst.name_span) {
|
||||
@@ -128,6 +128,9 @@ impl<'a> Binder<'a> {
|
||||
let inner = self.new_scope(ScopeKind::Generate, scope, item.span);
|
||||
self.bind_items(items, inner);
|
||||
}
|
||||
// A bare `begin … end` where an item belongs: bound as the
|
||||
// unnamed generate scope an unlabeled `if` arm's block gets.
|
||||
ItemKind::GenBlock(b) => self.bind_gen_block(b, scope),
|
||||
ItemKind::GenIf(g) => self.bind_gen_if(g, scope),
|
||||
ItemKind::GenFor(g) => self.bind_gen_for(g, item.span, scope),
|
||||
ItemKind::GenCase(g) => {
|
||||
|
||||
@@ -77,6 +77,7 @@ fn walk<'a>(items: &'a [Item], owner: Option<Decl<'a>>, out: &mut Vec<Site<'a>>)
|
||||
}
|
||||
ItemKind::Package { items, .. } => walk(items, owner, out),
|
||||
ItemKind::GenerateRegion { items, .. } => walk(items, owner, out),
|
||||
ItemKind::GenBlock(b) => block(b, owner, out),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
block(&gen_if.then, owner, out);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
|
||||
+22
-3
@@ -1,5 +1,24 @@
|
||||
# Verilog/SystemVerilog coverage gaps — ranked (2026-09-01)
|
||||
|
||||
**Reading this report today (2026-09-04).** The survey below is a historical
|
||||
v0.21.0 measurement with later amendments, not a fresh list of current failures.
|
||||
For the current implementation and outstanding contracts, use
|
||||
[repository-analysis.md](repository-analysis.md) and [topo.md](topo.md).
|
||||
Since the original survey, interface/modport and struct-member semantics,
|
||||
statement/class fences, header/list recovery, rule documentation, and three
|
||||
lint expansion waves have landed. The old probes were not re-run as part of
|
||||
the documentation audit; their historical counts are retained.
|
||||
|
||||
Current follow-ups to the latest addendum: v0.40.0 recovers bare item-level
|
||||
`begin` blocks as `ItemKind::GenBlock` **in tolerant mode**, so lint rules see
|
||||
their contents; strict formatting still refuses them. It also improves recovery
|
||||
for unclosed overrides that would consume the following instance. The
|
||||
post-v0.41.0 `parser-skips` commit accepts rival conditional unit headers as
|
||||
verbatim units and preserves net delays before or after the type. Its QA is
|
||||
accepted; release v0.42.0 is pending. Comments immediately before a net-delay
|
||||
`#` still cause a formatter verification refusal. External waiver files remain
|
||||
planned, not implemented.
|
||||
|
||||
What lucisv 0.21.0 does not yet handle, ranked by severity, from two
|
||||
independent sweeps crossed against each other:
|
||||
|
||||
@@ -149,8 +168,7 @@ signal named only inside a property edits it, references list it, and the
|
||||
"at least identifier occurrences" fallback the C1 row asked for was
|
||||
overtaken rather than built (what the grammar cannot read still rewinds to
|
||||
the byte-exact capture, and rename *names* those regions instead of going
|
||||
quiet). What the tables above still leave open, by weight: the second half of
|
||||
M12 (`--rules-doc`, §2.9-5); L3, L6, L9 and L10. M10's error recovery inside
|
||||
quiet). What the tables above still leave open, by weight: L3, L6, L9 and L10. M12's second half (`--rules-doc`, §2.9-5) was delivered by macro-word-census. M10's error recovery inside
|
||||
headers and lists is closed (TODO §32), with the narrowing recorded in its
|
||||
row: a truncated file reports *more* diagnostics than before, because the
|
||||
constructs that now survive say what closer they are missing. M13's small
|
||||
@@ -174,7 +192,8 @@ the generated truth.
|
||||
|
||||
Three coverage notes the wave produced, none of them a language gap:
|
||||
|
||||
- **`begin` where an item belongs is a parser gap, not a rule gap.** The
|
||||
- **Historical parser gap, closed in tolerant mode by v0.40.0:** `begin`
|
||||
where an item belongs. At the time of this addendum, the
|
||||
parser refuses a module-scope `begin … end` and a bare `begin` inside a
|
||||
`generate` region rather than recovering either as a block, so recovery
|
||||
unwinds and the rest of that unit is lost — `module-begin-block` and
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
# atomic write coordination
|
||||
|
||||
## Goal
|
||||
|
||||
Two writers of one file, inside one lucisv process, must not fight over the
|
||||
temp file the atomic write goes through (TODO §41, `docs/repository-analysis.md`
|
||||
finding 1, topo handshake §2.9-26). `atomic::temp_path` named its temp from the
|
||||
canonical target and the process id, so every thread of one process derived the
|
||||
*same* name for one target: the audit's probe — two threads writing 1 MiB each
|
||||
to one file, 100 rounds — produced 100 write errors in 200 calls (no mixed
|
||||
bytes, because `fs::write` truncated and rewrote the whole buffer, but half the
|
||||
writes failed outright and each failure removed the other writer's temp). Two
|
||||
ways in existed: the CLI's `dedup` folded `.` and `..` lexically but left
|
||||
symlinks unresolved, so `b.sv -> a.sv` reached two rayon workers as two files;
|
||||
and any two threads of one process asked to write one path.
|
||||
|
||||
Both are closed here. Every writer now gets a temp name no other writer in the
|
||||
process will be given (a per-process `AtomicU64` beside the pid) and creates it
|
||||
with `create_new`, so the name is owned, never shared. `dedup` keys on the
|
||||
canonical path when the file exists, so two spellings of one file are one job —
|
||||
while the path lucisv *reports* stays the first spelling the user gave. And the
|
||||
target's mode goes on the temp before its bytes do, so a 0600 file's replacement
|
||||
never holds the file's contents at a wider mode.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A rename is atomic within a directory**, on every filesystem lucisv ships
|
||||
to. That was already this module's premise; nothing here weakens it.
|
||||
- **Two *processes* writing one target are not coordinated, deliberately.**
|
||||
Both renames are atomic and the later one wins; the loser's bytes are
|
||||
discarded whole, never merged. Both processes formatted the same input and
|
||||
`format` is idempotent, so whichever rename lands last leaves the file
|
||||
complete and correctly formatted. A lock file would buy nothing and would be
|
||||
one more thing left behind by a `^C`. This is stated in the `atomic.rs`
|
||||
module doc, which is where a reader will look for it.
|
||||
- **A temp-name collision means a leftover, not a race.** A name is handed out
|
||||
once per process, so `AlreadyExists` can only mean a temp from an *earlier*
|
||||
process that died mid-write and whose pid this process now carries. The write
|
||||
retries with the next counter value, at most `TEMP_ATTEMPTS = 32` times; 32
|
||||
stale temps for one file in one directory is a directory to clean by hand,
|
||||
not a race to keep retrying through.
|
||||
- **`fs::canonicalize` is the identity of a file that exists.** Two names that
|
||||
canonicalize alike are one file (hardlinks aside — two hardlinks to one inode
|
||||
have two distinct canonical paths and stay two jobs, which is what a user who
|
||||
made hardlinks asked for). A path with no file behind it has no canonical
|
||||
form, and the old lexical fold answers for it.
|
||||
- **A chmod does not revoke an already-open descriptor.** That is why, when
|
||||
there is a target, the temp is *created* 0600 on unix rather than created at
|
||||
the umask's mode and narrowed afterwards: narrowing later would leave a
|
||||
window in which someone could open the empty temp and then read the bytes
|
||||
through the descriptor they kept. With no target there is no earlier mode to
|
||||
honour and the umask decides, exactly as `fs::write` would.
|
||||
- The dedup key is computed on the main thread, before any worker exists, so
|
||||
the extra `canonicalize` per input is one `realpath` per file at startup and
|
||||
not per write.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **`lucisv_core::atomic::write_atomic` — unchanged signature, unchanged
|
||||
contract**, plus one promise it did not make before: two threads of one
|
||||
process writing one target both succeed, and the target ends up holding one
|
||||
writer's whole buffer. Callers (`lucisv/src/main.rs`, `lucisv/src/lint.rs`,
|
||||
`lucisv_core/src/cache.rs`) need no change.
|
||||
- The two behaviours other tests already pin are kept exactly: a read-only
|
||||
target is refused with `PermissionDenied`, and a symlinked target is
|
||||
resolved so the link is not replaced.
|
||||
- The temp file's *name* changed shape: `.{name}.{pid}.{n}.lucisv-tmp`. Any
|
||||
tool that matched the old `.{name}.{pid}.lucisv-tmp` (nothing in this
|
||||
repository does; the tests match on the `.lucisv-tmp` suffix) must match
|
||||
the suffix instead.
|
||||
- A file created where there was no target still takes the umask's mode. The
|
||||
0600 creation applies only when a target's mode is about to be copied on.
|
||||
- **`lucisv::dedup` — same signature, same output order, same reported paths.**
|
||||
It only folds *more* than it used to: two spellings that reach one file are
|
||||
now one job. `absolute` stays the lexical fold and is now reached only for
|
||||
paths that do not exist; its doc comment says so.
|
||||
- Nothing is requested of another module.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] 41.1 exclusive unique temps (per-process `AtomicU64` + `create_new`,
|
||||
bounded retry), mode before bytes
|
||||
- [x] 41.2 dedup by canonical identity, reported path unchanged
|
||||
- [x] Last-writer semantics for two processes stated in the `atomic.rs` module
|
||||
doc and above; no lock built
|
||||
- [x] Tests: the audit's probe (2 threads × 100 rounds × 1 MiB, 0 write
|
||||
errors, one whole buffer per round); temp-name uniqueness across
|
||||
threads; the 0600 window, twice (a unit test on the mode step, and a
|
||||
live poll of the directory during a real 8 MiB write); `dedup` with a
|
||||
symlink alias in both spelling orders, with a `..` detour, and with
|
||||
missing files; a CLI test where `dir/b.sv -> dir/a.sv` is formatted and
|
||||
reported once
|
||||
- [x] Gates (guarded): fmt, clippy, workspace tests, corpus, write-path
|
||||
byte-identity
|
||||
- [ ] QA (see the brief in TODO §41)
|
||||
|
||||
## Docs to apply at merge (lead)
|
||||
|
||||
- `docs/topo.md` §2.9-26 (same-target atomic writers) is closed by this lane:
|
||||
the temp name carries a per-process counter and is created `O_EXCL`, and the
|
||||
CLI dedups by canonical identity so one file cannot reach two workers.
|
||||
Suggested strike-through note: *"closed by §41 (0.43.0): unique `O_EXCL`
|
||||
temps, dedup on `fs::canonicalize`; two *processes* remain last-writer-wins
|
||||
by design, stated in `atomic.rs`."*
|
||||
- `docs/repository-analysis.md` finding 1: annotate **fixed by §41** — the
|
||||
probe now runs as `atomic::tests::two_threads_writing_one_target_never_collide`
|
||||
and reports 0 write errors in 200 calls; the symlink alias closes as
|
||||
`cli::a_symlink_and_its_target_are_one_file`.
|
||||
- `README.md` needs no change: no user-visible behaviour moved. The only
|
||||
externally observable difference is the temp file's name shape,
|
||||
`.{name}.{pid}.{n}.lucisv-tmp`, which the README does not document.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-09-05 — dev (Opus 5).** TODO §41 implemented in full.
|
||||
|
||||
Files touched, all inside the plan's expected set:
|
||||
|
||||
- `crates/lucisv_core/src/atomic.rs` — the write path.
|
||||
- `crates/lucisv/src/main.rs` — `dedup`/`identity`/`absolute` and their tests.
|
||||
- `crates/lucisv/tests/cli.rs` — the symlink-alias end-to-end test.
|
||||
- `docs/features/atomic-write-coordination/README.md` — this file.
|
||||
- `TODO.md` — §41's own checkboxes (the QA line left alone).
|
||||
|
||||
Nothing outside that set was touched.
|
||||
|
||||
**41.1.** `temp_path` now stamps the name with a per-process `AtomicU64`
|
||||
counter as well as the pid: `.{name}.{pid}.{n}.lucisv-tmp`. `create_temp`
|
||||
opens it with `OpenOptions::new().write(true).create_new(true)`, so a name
|
||||
that somehow exists is `AlreadyExists` and the next counter value is tried,
|
||||
up to `TEMP_ATTEMPTS = 32`, after which the write fails with a message naming
|
||||
the target and the bound (reasoning for 32 in Assumptions). `write_atomic`
|
||||
now stats the target once, at the top, and passes the `Option<Permissions>`
|
||||
down: the read-only refusal, the decision to create the temp 0600, and the
|
||||
mode copy all read that one stat instead of three.
|
||||
|
||||
`fill_temp` puts the mode on before the bytes on unix (`File::set_permissions`
|
||||
through the handle opened before the chmod, so a mode without an owner-write
|
||||
bit does not stop the write); on non-unix it keeps today's order, because
|
||||
`set_permissions` there takes a path and there is nothing to gain from
|
||||
reordering. The write itself is `write_all` on the owned handle rather than
|
||||
`fs::write`, which is what makes both the exclusive create and the early chmod
|
||||
possible.
|
||||
|
||||
**Deviation from the plan, deliberate.** The plan asked only that the mode be
|
||||
copied before the bytes. Writing the window test showed that was not enough:
|
||||
the temp is *created* at the umask's mode, so for one instant an empty
|
||||
world-readable file exists at a name anyone can open — and a chmod does not
|
||||
revoke a descriptor already opened through it, so an observer holding that
|
||||
descriptor would then read the private file's contents as they were written.
|
||||
The temp is therefore created with `mode(0o600)` on unix *when there is a
|
||||
target whose mode it is about to take*; with no target it is created at the
|
||||
umask's mode, so a brand-new file's permissions are exactly what they were
|
||||
before this change. This is strictly narrower than the plan's ask, not wider.
|
||||
The first run of `a_temp_seen_mid_write_is_never_world_readable` caught the
|
||||
gap (observed mode 0644 on a temp for a 0600 target); it passes now.
|
||||
|
||||
**41.2.** `dedup` keys on `identity(cwd, path)`: `fs::canonicalize(path)` when
|
||||
it answers, else the old `absolute(cwd, path)` lexical fold. The reported path
|
||||
is untouched — `dedup` still keeps the *first* spelling of each file and its
|
||||
order. `absolute`'s doc comment now says it is the fold for paths that do not
|
||||
exist rather than a deliberate refusal to resolve symlinks.
|
||||
|
||||
**Tests (6 new, all guarded).**
|
||||
|
||||
- `atomic::tests::two_threads_writing_one_target_never_collide` — the audit's
|
||||
probe: two writers and this thread meet at a pair of barriers each round, so
|
||||
the target is inspected between rounds with nobody mid-write. 100 rounds,
|
||||
1 MiB per writer, distinct buffers: 0 write errors, and every round the file
|
||||
holds exactly one writer's whole buffer with no temp left behind.
|
||||
- `atomic::tests::every_thread_gets_its_own_temp_name` — 4 threads × 200 names
|
||||
for one target, all 800 distinct.
|
||||
- `atomic::tests::the_temp_takes_the_targets_mode_before_any_bytes` — the
|
||||
unit-testable step: the temp is 0600 the moment it exists, `copy_mode` puts
|
||||
the target's mode on while `len() == 0`, and `fill_temp` still writes
|
||||
through the handle afterwards.
|
||||
- `atomic::tests::a_temp_seen_mid_write_is_never_world_readable` — the same
|
||||
window from outside, polling the directory during a real 8 MiB
|
||||
`write_atomic`. It asserts about what it sees and never about *seeing* it,
|
||||
so a scheduler that hides the window cannot make it flaky.
|
||||
- `lucisv::tests::dedup_folds_a_symlink_onto_the_file_it_points_at` — the
|
||||
alias in both spelling orders (the first spelling is the one kept), a `..`
|
||||
detour through an existing directory, and missing files falling back to the
|
||||
lexical key (two different missing files stay two).
|
||||
- `cli::a_symlink_and_its_target_are_one_file` — `dir/b.sv -> dir/a.sv`
|
||||
through the real binary: `--check` prints exactly one `would reformat:` line
|
||||
and it names `a.sv`; the format run says "1 file reformatted"; the link is
|
||||
still a link afterwards.
|
||||
|
||||
**Both new tests were checked for teeth** by temporarily reverting the fix in
|
||||
the working tree and restoring it immediately: without the counter the probe
|
||||
reports *exactly* "100 write errors in 200 calls" — the audit's number, to the
|
||||
call — and with lexical dedup the CLI test sees two `would reformat:` lines,
|
||||
for `a.sv` and `b.sv`.
|
||||
|
||||
**Gates, all through `tools/guard.sh` (no guard kill anywhere).**
|
||||
|
||||
- `cargo fmt -p lucisv_core -p lucisv` clean.
|
||||
- `cargo clippy --all-targets` clean, zero warnings. Two of my own drew
|
||||
warnings on the way (`cloned_ref_to_slice_refs` in the dedup test,
|
||||
`byte_char_slices` in the probe) and were fixed rather than allowed.
|
||||
- `tools/guard.sh -- cargo test --workspace`: **3 771 passed, 0 failed**
|
||||
(baseline 3 765 + the 6 above).
|
||||
- `tools/guard.sh -- tools/corpus_check.sh`: **814/820 (99.3 %)**, the same
|
||||
six failures, `verification-error: none`, `crash: none`.
|
||||
- Write-path byte-identity: 300 corpus files copied to a scratch directory
|
||||
(one of them chmod 0600) and formatted in place — 292 reformatted, 4
|
||||
unchanged, 4 pre-existing parse failures; a second run reports all 296
|
||||
unchanged (idempotent); the 0600 file is still 0600; no `.lucisv-tmp` left
|
||||
behind. Every one of the 296 files' in-place bytes is byte-identical to the
|
||||
same file formatted through stdin, which never touches `write_atomic` —
|
||||
so the new write path delivers exactly the formatter's bytes.
|
||||
- Peak RSS of the probe test, `/usr/bin/time -l` around the single test under
|
||||
the guard: **36 995 072 B (35.3 MiB)** max resident, 0.38 s wall. The two
|
||||
1 MiB buffers and the read-back are the only allocations the test adds.
|
||||
|
||||
Nothing is unfinished. The one judgement call a reviewer may want to weigh is
|
||||
the 0600 creation described under "Deviation" above.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-09-05 — QA (Sonnet 5).** Verified against the §41 QA brief. All
|
||||
experiments ran on copies under the scratchpad or on a standalone scratch
|
||||
crate path-depending on `lucisv_core`; nothing in `corpus/` or
|
||||
`/Users/guoliangchen/repo/opentitan` was written to. Every probe and gate ran
|
||||
through `tools/guard.sh` (no guard kill anywhere). Two temporary `#[test]`
|
||||
functions were added to poke at private functions (`create_temp`/`copy_mode`
|
||||
in `atomic.rs`, `identity`/`dedup` symlink cases in `main.rs`), run, and then
|
||||
removed — `git diff` on both files verified byte-identical to the dev's diff
|
||||
before and after.
|
||||
|
||||
1. **Multithread probe, 4 and 8 threads** (standalone scratch binary linking
|
||||
`lucisv_core`, `/usr/bin/time -l`, guarded). 4 threads × 100 rounds: 0
|
||||
write errors in 400 calls, 0 bad rounds, 0 leftover temps, peak RSS
|
||||
8 749 056 B (8.3 MiB). 8 threads × 100 rounds: 0 write errors in 800
|
||||
calls, 0 bad rounds, 0 leftover temps, peak RSS 13 107 200 B (12.5 MiB).
|
||||
Matches the dev's 2-thread number scaled up; no error rate creeps back in
|
||||
with more contention.
|
||||
2. **The 0600 window.** Black-box directory polling (mirroring the dev's own
|
||||
`a_temp_seen_mid_write_is_never_world_readable`, generalized): a 0600
|
||||
target under continuous 8 MiB rewrites for 3s — 88 053 samples, widest
|
||||
temp mode ever seen `0600`, final mode `0600`. A 0644 target: widest seen
|
||||
`0644` (never wider), final `0644`. A 0755 target: widest seen `0755`,
|
||||
final `0755`. Brand-new target vs. a plain `fs::write` in the same
|
||||
directory: both land at `0644` under umask `022` — match. The "0600 at
|
||||
creation, then widened by the rename" half of the inverse case is not
|
||||
observable black-box (`copy_mode` runs before `write_all` with no yield
|
||||
point, so the 0600 instant is sub-microsecond) — confirmed instead with a
|
||||
temporary source-level test calling `create_temp`/`copy_mode` directly for
|
||||
0644 and 0755 targets: the temp is born 0600 in both cases, then
|
||||
`copy_mode` widens it to the target's real mode before any byte is
|
||||
written. Removed after passing.
|
||||
3. **Retry bound.** Predicted the temp names from the diff
|
||||
(`.{name}.{pid}.{n}.lucisv-tmp`, counter from 0, one static per process)
|
||||
and pre-created all 32 (`n=0..31`) in a fresh process before its first
|
||||
`write_atomic` call: the write fails with `"no free temp file name beside
|
||||
.../a.sv after 32 tries"`, naming the target and the bound, and leaves
|
||||
exactly the 32 pre-created temps (no new one added). Pre-creating 31
|
||||
(`n=0..30`, one slot free) in a fresh process: the write succeeds
|
||||
(consuming `n=31`), the target holds the new bytes, and exactly 31 stale
|
||||
temps remain — no extra temp left by the successful write itself.
|
||||
4. **Symlink and identity.** Temporary unit tests against `identity`/`dedup`
|
||||
covered: `dir2 -> dir1` containing the file (both spelling orders, first
|
||||
spelling kept and reported); an absolute vs. relative spelling through
|
||||
the dir symlink; a `../` detour; a dangling symlink (canonicalize fails,
|
||||
falls back to the lexical key — two lexical spellings of *one* dangling
|
||||
link still fold, two *different* dangling links stay two); a symlink to a
|
||||
file outside the pair being compared (folds onto the real file by
|
||||
canonical identity regardless of "was it walked"). All passed; removed
|
||||
after. Then the mandated real-binary run (`cargo build --release -p
|
||||
lucisv`, `dir/b.sv -> dir/a.sv`): `--check` printed exactly one `would
|
||||
reformat:` line naming `a.sv`, exit 1; `--diff` printed exactly one diff
|
||||
block naming `a.sv`, exit 1; a real format run reported "1 file
|
||||
reformatted", exit 0, both `a.sv` and (through the link) `b.sv` read back
|
||||
the formatted text, and `b.sv` was still a symlink pointing at `a.sv`
|
||||
afterwards (`readlink` unchanged); a second `--check` reported "1 file
|
||||
left unchanged, 1 file from cache", exit 0. Also checked by hand: a
|
||||
dangling symlink inside a walked directory errors
|
||||
`"...dead.sv: No such file or directory"` (the user's own spelling, not a
|
||||
resolved one) without a panic, exit 2; a symlink to a file *outside* the
|
||||
walked directory formats correctly through the link, and passing both the
|
||||
link and the real outside file explicitly on the command line dedups to
|
||||
one job, one report line, one write — verified with `--check` and with a
|
||||
real write (outside file correctly formatted, link left intact).
|
||||
5. **Two processes.** Two `lucisv format` processes launched at the same
|
||||
moment (both under `tools/guard.sh`, backgrounded, `wait`ed) against one
|
||||
shared scratch copy of `corpus/common_cells/src` (100 files): both exited
|
||||
0. The resulting tree is byte-identical (`diff -rq`) to a fresh copy
|
||||
formatted by a single process. No `.lucisv-tmp` anywhere afterward. A
|
||||
follow-up `--check` on the two-process tree reports "100 files left
|
||||
unchanged, 100 files from cache", exit 0 — no truncation, no corruption,
|
||||
consistent with the documented last-writer-wins semantics (both writers
|
||||
were formatting the same input to the same idempotent output, so there
|
||||
was nothing for a "loser" to lose).
|
||||
6. **Refusals and mid-run failures.** A read-only (0444) target: refused with
|
||||
`PermissionDenied` ("... is read-only"), file content and mode (444)
|
||||
untouched, no temp created. A target in a read-only (0555) directory:
|
||||
refused with a plain OS `Permission denied (os error 13)` (temp creation
|
||||
itself fails — expected, since `write_atomic`'s own read-only check is
|
||||
for the *target's* mode, not the directory's), file untouched. Directory
|
||||
deleted mid-write: 200 rounds of racing `fs::remove_dir_all` against a
|
||||
concurrent 8 MiB `write_atomic` in a scratch binary with
|
||||
`catch_unwind` around the writer thread — 139 writes completed before the
|
||||
delete won the race, 61 got a plain `io::Error` (`No such file or
|
||||
directory` / `Invalid argument`), **0 panics**. No corruption claim
|
||||
applies once the directory itself is gone.
|
||||
7. **Behaviour parity.** 300 files copied from `corpus/ibex` (path structure
|
||||
preserved) into a scratch tree. `--stdout` of every file saved first (4
|
||||
pre-existing parse failures unrelated to this feature — a `.tpl.sv`
|
||||
template, a Yosys-primitive `.v`, and two vendor files with unsupported
|
||||
constructs, all already known corpus failures). In-place format of the
|
||||
300: "283 files reformatted, 13 files left unchanged, 4 files failed to
|
||||
format" — same 4 files, same error text, byte-identical to the `--stdout`
|
||||
errors. All 296 successfully-formatted files are byte-identical between
|
||||
the in-place result and `--stdout` of the original (0 mismatches). The 4
|
||||
failed files are byte-unchanged from their originals (hard invariant #1
|
||||
held). A follow-up `--check` on the tree: "296 files left unchanged, 296
|
||||
files from cache, 4 files failed to format" — idempotent.
|
||||
|
||||
**Gates (all guarded, no kill).**
|
||||
- `cargo clippy --all-targets`: clean, 0 warnings.
|
||||
- `tools/guard.sh -- cargo test --workspace`: **3 771 passed, 0 failed, 44
|
||||
ignored** — matches the dev's reported 3 771 exactly.
|
||||
- `tools/guard.sh -- tools/corpus_check.sh`: **814/820 (99.3%)**, the same
|
||||
six failures (5 parse-error + 1 lex-error), `verification-error: none`,
|
||||
`crash: none` — matches the dev's reported number exactly.
|
||||
|
||||
**Findings.** None at any severity. No corruption, no panic, no leftover
|
||||
temp, no mode widening, no dedup miss, no parity break, and no gate
|
||||
regression across any of the seven attacks.
|
||||
|
||||
**Repo hygiene.** `git status --porcelain` on the four `corpus/*` checkouts
|
||||
shows only a pre-existing untracked `.vfmt-corpus-rev` marker (identical
|
||||
41-byte file, mtime 2026-08-19, present in all four — predates this session,
|
||||
not written by anything here); no tracked file in any corpus checkout is
|
||||
modified. In the main tree, `git diff` on `crates/lucisv_core/src/atomic.rs`,
|
||||
`crates/lucisv/src/main.rs` and `crates/lucisv/tests/cli.rs` is byte-identical
|
||||
to the dev's diff at the start of this QA pass (verified before and after
|
||||
every temporary test was added/removed). All scratch experiments and the
|
||||
standalone `probe` crate lived under the scratchpad and have been removed.
|
||||
|
||||
**Verdict: PASS.** No rework needed.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-05 — lead.** Accepted; ships in 0.43.0. The fix is the plan's plus
|
||||
one tightening the plan should have asked for: a temp created at the umask's
|
||||
mode and chmod'ed later would leave an empty world-readable file at a
|
||||
guessable name for an instant, and a descriptor opened through it would
|
||||
survive the chmod — so creating the temp at 0600 when a target exists, then
|
||||
widening through the open handle before the bytes, is the correct order and
|
||||
the dev's deviation is accepted as written. The retry bound of 32 is the
|
||||
right shape (a name is issued once per process, so only a dead earlier
|
||||
process with the same pid can collide, and 32 of those is a directory to
|
||||
clean, not a race). QA's attack was thorough — 4 and 8 threads, the window
|
||||
polled from outside, the bound hit exactly, two real processes over one
|
||||
tree, a directory deleted mid-write with 0 panics — and found nothing. Two
|
||||
processes on one target stay last-writer-wins by design; the formatter's
|
||||
idempotence is what makes that safe, and the module doc says so.
|
||||
@@ -0,0 +1,565 @@
|
||||
# didOpen cost
|
||||
|
||||
## Goal
|
||||
|
||||
Take 3 (`docs/performance_take3.md` §8.4) measured that a `didOpen` of a file
|
||||
the index already covers delays the **next** request by 21–51 ms, scaling with
|
||||
file size, where take 2 measured a flat 2–4 ms. The server is a synchronous
|
||||
loop, so whatever the open does before returning is what the next request waits
|
||||
behind. TODO.md §46 asked for the cost to be measured, broken down, and for the
|
||||
largest item in it — not all of them — to be fixed, with the open returning to
|
||||
the loop fast enough that the request behind it is not left waiting and is
|
||||
still answered from up-to-date state.
|
||||
|
||||
The finding turned out to understate the problem by an order of magnitude. At
|
||||
the whole-workspace scope, opening opentitan's 42 000-line
|
||||
`pinmux_reg_top.sv` delayed the next request by **1.74 seconds**, and the whole
|
||||
of it was one lint rule asking the workspace census a question per declaration
|
||||
in the buffer. Moving that question behind the rule's own local guards — where
|
||||
its twin rule has always asked it — took the same open to **117 ms**, and took
|
||||
the take-3 rows from 51–95 ms to 3–9 ms.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The oracle is a pure predicate.** `MentionOracle::mentioned_elsewhere` reads
|
||||
the index and returns a `bool`; it has no side effects, so where in a
|
||||
conjunction of `continue` guards it is asked cannot change what the rule
|
||||
finds. Pinned empirically as well as argued: the 0.39.0 binary and the fixed
|
||||
one publish byte-identical diagnostics for a workspace built to exercise both
|
||||
answers (below).
|
||||
- **A `didOpen`'s buffer must be analyzed before the open returns.** Every
|
||||
request flushes dirty buffers first (`Server::answer_request`), so deferring
|
||||
the *parse* to the change debounce would move the cost, not remove it, and
|
||||
would break "the first request after the open is answered from up-to-date
|
||||
state". The parse stays synchronous, and so does the publish.
|
||||
- The measurements are wire-level and on one machine (below). Sub-millisecond
|
||||
differences are not claimed; everything reported here is a factor, not a
|
||||
percent.
|
||||
- opentitan is read-only. The index cache went to a scratch
|
||||
`initializationOptions.storagePath`; `git -C ~/repo/opentitan status
|
||||
--porcelain` reported the same three pre-existing modified files before and
|
||||
after every phase.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **`vlog_linter` → the server, unchanged.** `UndrivenNet::check` returns the
|
||||
same violations, in the same order, for the same context. No rule signature,
|
||||
no registry entry, no severity and no `default_on`/`needs_workspace` answer
|
||||
moved. `lucisv check` is unaffected in every way (it has no oracle, so the
|
||||
reordered test is a constant `false` there).
|
||||
- **`WorkspaceIndex::files_mentioning` — no change requested.** Its doc comment
|
||||
records that a merged `word → files` map was measured against the per-file
|
||||
walk and rejected. That ruling stands and is not reopened here: the fix is to
|
||||
ask the question a thousand times fewer, not to make the question faster.
|
||||
What this round adds to the record is the cost of *one* question — a walk
|
||||
over every indexed file — which is what makes asking it per declaration a
|
||||
mistake at any workspace size.
|
||||
- **`Server::publish` / `flush_dirty` — untouched.** §46 allowed the open's
|
||||
diagnostics to be moved onto the change debounce. They were not; see
|
||||
"What was not done".
|
||||
|
||||
## The measurement
|
||||
|
||||
### Method
|
||||
|
||||
`scratchpad/perf46/driver.py`, take 3's method (§9 of that doc): framed
|
||||
JSON-RPC over the server's stdio, `workspace/configuration` answered with
|
||||
`{"index":{"scope":"workspace"}}`, cache warmth through
|
||||
`initializationOptions.storagePath`, positions resolved from the file text at
|
||||
run time. Per file, in one settled session: `didOpen` and a `textDocument/hover`
|
||||
at the first `module <name>` token written in the **same** flush, timed from the
|
||||
`didOpen` frame going out to the hover response coming back; then the identical
|
||||
hover again as the control. Three tries per file per binary, warm store.
|
||||
|
||||
Both binaries `cargo build --release -p lucisv_server`: the tree at f795606
|
||||
(0.43.0) and `v0.39.0` from a scratch `git worktree` (removed afterwards).
|
||||
Every server run, build and sweep went through `tools/guard.sh -m 8 -t 900`;
|
||||
no guard kill occurred.
|
||||
|
||||
Machine: Apple M1 Max, 10 cores, 64 GB, macOS 27.0, quiet (load 1–3), nothing
|
||||
else building.
|
||||
|
||||
**Note on the file set.** §46 named "the largest file in
|
||||
`hw/top_darjeeling/ip/xbar_peri/rtl/autogen/` (tl_peri_pkg.sv-class, ~42k
|
||||
lines)". In this checkout that directory holds only an 8 KB and a 3.6 KB file;
|
||||
the ~42 000-line file the plan meant is
|
||||
`hw/top_darjeeling/ip_autogen/pinmux/rtl/pinmux_reg_top.sv` (42 192 lines,
|
||||
1.3 MB), the largest `.sv` in the tree. That is the file used.
|
||||
|
||||
### Where the time went — the breakdown
|
||||
|
||||
Temporary `eprintln!` timings inside `didOpen`, `Document::new`,
|
||||
`Server::publish`, `diagnostics::all_in` and `lint_with`'s rule loop, on the
|
||||
release build; **all of them removed before finishing** (`git diff` shows only
|
||||
the rule and the tests). Milliseconds, one representative try per file.
|
||||
|
||||
| Stage | `aes.sv` 326 L | `aes_core.sv` 1 145 L | `pinmux_reg_top.sv` 42 192 L |
|
||||
|---|---:|---:|---:|
|
||||
| lex | 0.31 | 1.01 | 41.24 |
|
||||
| tolerant parse | 0.59 | 1.01 | 31.73 |
|
||||
| `collect_defines` | 0.00 | 0.01 | 0.57 |
|
||||
| `analyze` | 0.17 | 0.56 | 11.57 |
|
||||
| `resolve_external` | 0.12 | 0.32 | 4.79 |
|
||||
| line index | 0.01 | 0.03 | 0.62 |
|
||||
| **`Document::new` (the whole parse)** | **1.33** | **3.04** | **90.61** |
|
||||
| `LintRun::for_document` (discovery, waivers, memo) | 0.34 | 0.07 | 0.09 |
|
||||
| `diagnostics::all_in` (the lint pass) | 4.87 | 54.43 | **1 653.76** |
|
||||
| — of which the rule `undriven-net` | 4.38 | 52.23 | **1 608.45** |
|
||||
| — of which `multiply-driven` | — | — | 8.22 |
|
||||
| — every other rule, together | ≈0.5 | ≈2.2 | ≈37 |
|
||||
| **`didOpen` total** | **7.07** | **58.01** | **1 745.06** |
|
||||
|
||||
Two things the table settles:
|
||||
|
||||
1. **The widen is not involved.** At the whole-workspace scope every file is
|
||||
already in scope, so `widen_of` answers `Nothing` and the open costs the
|
||||
parse plus the publish and nothing else. The `didOpen` total is the sum of
|
||||
the two rows above it to within 0.2 ms.
|
||||
2. **The lint pass is 75 / 94 / 95 % of the open, and one rule is 90 / 96 /
|
||||
97 % of the lint pass.** `LintRun::for_document` — §42's discovery, the
|
||||
waiver-file reads and the once-only memo, the thing §46 guessed at — costs
|
||||
70–340 µs and is not a candidate. Neither is the completion word table or
|
||||
the semantic tokens: neither runs on an open at all.
|
||||
|
||||
### Why `undriven-net` cost that
|
||||
|
||||
The rule asked the workspace census about **every** declaration in the buffer,
|
||||
before any of its local guards had a chance to silence it:
|
||||
|
||||
```rust
|
||||
if intentionally_unused(..) || !judgeable(..) || has_init { continue }
|
||||
if ctx.mentioned_elsewhere(&decl.name) { continue } // ← was here
|
||||
let Some(usage) = signals.usage(decl) else { continue };
|
||||
if connected || driven || reads == 0 { continue }
|
||||
found.push(..)
|
||||
```
|
||||
|
||||
One `mentioned_elsewhere` is `WorkspaceIndex::files_mentioning`, a walk over
|
||||
**every indexed file** binary-searching its sorted word list — 3 976 files in
|
||||
opentitan at the workspace scope. `pinmux_reg_top.sv` has roughly four thousand
|
||||
declarations, and essentially all of them are driven, so all four thousand
|
||||
questions were asked and all four thousand answers were thrown away by the very
|
||||
next guard. `unused-signal`, the twin rule with the same oracle, has always
|
||||
asked last, which is why it never showed up in a profile.
|
||||
|
||||
The fix is to ask the question where its twin asks it: last, of the handful of
|
||||
declarations that would otherwise be reported. It is a pure reordering of a
|
||||
conjunction of `continue` guards over a side-effect-free predicate, so the
|
||||
findings and their order are unchanged.
|
||||
|
||||
### Before and after — the three §46 files
|
||||
|
||||
Wire time, `didOpen` → the hover behind it, three tries, warm store, workspace
|
||||
scope, ms.
|
||||
|
||||
| File | lines | KB | 0.39.0 | 0.43.0 **before** | 0.43.0 **after** | factor |
|
||||
|---|---:|---:|---|---|---|---:|
|
||||
| `hw/ip/aes/rtl/aes.sv` | 326 | 14 | 8.6 / 9.5 / 7.8 | 8.1 / 5.9 / 10.1 | **4.3 / 1.8 / 2.3** | ~3× |
|
||||
| `hw/ip/aes/rtl/aes_core.sv` | 1 145 | 49 | 55.8 / 65.7 / 44.4 | 56.2 / 54.0 / 48.0 | **5.9 / 6.9 / 6.3** | ~8× |
|
||||
| `…/pinmux/rtl/pinmux_reg_top.sv` | 42 192 | 1 297 | 1 725.8 / 1 694.1 / 1 751.1 | 1 742.5 / 1 740.2 / 1 756.8 | **116.5 / 116.2 / 117.3** | ~15× |
|
||||
|
||||
The control — the identical hover issued straight after the first — is
|
||||
0.09–0.20 ms for `aes.sv`, 0.12–0.19 for `aes_core.sv` and 0.46–0.60 for
|
||||
`pinmux_reg_top.sv`, before and after alike. It is the open that costs, exactly
|
||||
as take 3 said.
|
||||
|
||||
**0.39.0 measures the same as 0.43.0 before the fix.** This was never a
|
||||
regression: `undriven-net` has asked in that order since it was written. Take
|
||||
3's §8.4 comparison against take 2's 2–4 ms is therefore not a "something got
|
||||
slower" story, and take 2's client — which no longer exists — most likely
|
||||
measured a session whose scope did not switch the workspace rules on at all.
|
||||
|
||||
### Before and after — take 3's own §8.4 rows
|
||||
|
||||
Same method, whole-workspace scope. (Take 3 measured these at the *default*
|
||||
scope after the `aes.sv` widen, where the census covers ~124 files rather than
|
||||
3 976; that is why the "before" column here is worse than §8.4's 21/31/51 ms.
|
||||
The two are the same defect at two census sizes.)
|
||||
|
||||
| File | KB | take 3 §8.4 (default scope) | **before** (workspace scope) | **after** |
|
||||
|---|---:|---:|---|---|
|
||||
| `hw/ip/hmac/rtl/hmac.sv` | 33 | 21.1 | 56.8 / 42.7 / 51.0 | **4.7 / 5.7 / 3.3** |
|
||||
| `hw/ip/kmac/rtl/kmac.sv` | 53 | 31.1 | 69.3 / 72.1 / 70.6 | **7.9 / 5.3 / 8.8** |
|
||||
| `hw/ip/spi_device/rtl/spi_device.sv` | 67 | 51.2 | 94.2 / 103.4 / 88.6 | **6.0 / 8.6 / 8.7** |
|
||||
|
||||
### The ≤ 5 ms contract, honestly
|
||||
|
||||
§46 asked for "`didOpen` returns to the loop in ≤ 5 ms for a 1 000-line file".
|
||||
|
||||
- For a **generated** 1 000-line buffer the release binary is under 2 ms. Met.
|
||||
- For `aes_core.sv` — 1 145 lines but 49 KB of dense opentitan RTL, four times
|
||||
the bytes per line of a generated file — the open is **5.9–6.9 ms**, of which
|
||||
**3.0–4.4 ms is `Document::new`**: the lex, the tolerant parse, the semantic
|
||||
analysis and the external resolution. The lint pass is now 1.3 ms of it.
|
||||
So the contract is met per line and missed per byte on the densest real file
|
||||
measured, and the remainder is the parse — which cannot be deferred without
|
||||
breaking "the first request after the open is answered from up-to-date
|
||||
state". Recorded as the limit rather than met by redefining the file.
|
||||
|
||||
### Behavioural equivalence, checked on the wire
|
||||
|
||||
A two-file scratch workspace built to exercise both oracle answers: `top.sv`
|
||||
declares `lonely` (read, undriven, mentioned nowhere else) and `shared_name`
|
||||
(read, undriven, but `force`d from `other.sv`). Both binaries publish exactly
|
||||
|
||||
```
|
||||
undriven-net @1:7 `lonely` is read but never driven
|
||||
```
|
||||
|
||||
and nothing about `shared_name` — the census still silences it. Byte-identical
|
||||
between 0.39.0 and the fixed build.
|
||||
|
||||
## What was not done, and why
|
||||
|
||||
- **The open's diagnostics were not moved onto the change debounce.** §46 named
|
||||
it as a likely shape and allowed the diagnostics to arrive a debounce later.
|
||||
They still go out inside the `didOpen`, synchronously, because after the fix
|
||||
the whole publish is 0.5–1.5 ms on a real RTL file and 24 ms on a
|
||||
42 000-line one; deferring it would buy a millisecond and cost the guarantee
|
||||
that an opened file is diagnosed before anything queued behind it is
|
||||
answered. **There is no debounce on the open, and there is nothing new to
|
||||
pin about when diagnostics arrive** — pinned anyway, by
|
||||
`an_open_still_publishes_its_diagnostics_with_no_edit_behind_it`.
|
||||
- **The buffer's re-index was not skipped on a content-hash match.** §46's
|
||||
other suggested shape. It is not on the open path at all: a `didOpen` of a
|
||||
file already in scope runs no index update — `widen_of` answers `Nothing` and
|
||||
the index is untouched until a `didSave`. There was nothing to skip.
|
||||
- **`WorkspaceIndex::files_mentioning` was not given an inverted index.** See
|
||||
Handshakes: that ruling is recorded in its own doc comment and is not this
|
||||
round's to reopen. It is now the largest single item left on the open path
|
||||
for a 42 000-line file (`multiply-driven` at 8 ms is the next), but at
|
||||
~117 ms total the file is no longer the round's problem.
|
||||
- **The other 95 ms of `pinmux_reg_top.sv`'s open is the parse** (lex 41 ms,
|
||||
parse 32 ms, analyze 12 ms). Not touched; it is the price of a 1.3 MB buffer
|
||||
and it is 25× under the large-file threshold that would skip it.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Measure first: the driver, three files, three tries, both binaries, warm
|
||||
store, workspace scope.
|
||||
- [x] Profile the open path with temporary timings; the breakdown table above;
|
||||
the timings removed (`git diff` is the rule plus the tests).
|
||||
- [x] Fix the largest item: `undriven-net` asks the census last.
|
||||
- [x] Wire-level timing test on a generated 2 000-line buffer.
|
||||
- [x] Correctness pin: the first hover **and** the first definition after an
|
||||
open see the buffer, not the disk.
|
||||
- [x] Diagnostics-still-arrive pin, with the debounce question answered (there
|
||||
is none).
|
||||
- [x] Exact regression pin: the oracle is asked once per reported candidate.
|
||||
- [x] The take-3 rows re-measured, before and after, in this README.
|
||||
- [x] Gates: `cargo fmt -p lucisv_server -p vlog_linter`, `cargo clippy
|
||||
--all-targets`, `cargo test --workspace`, `tools/corpus_check.sh`,
|
||||
`editors/vscode/smoke.js` — all guarded.
|
||||
- [ ] QA.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-05 — dev (Fable 5.1)
|
||||
|
||||
- Built both binaries release: the tree at f795606, and `v0.39.0` in a scratch
|
||||
worktree under the scratchpad (removed at the end, `git worktree remove`).
|
||||
- Wrote `scratchpad/perf46/driver.py` to take 3's method and measured the three
|
||||
§46 files, three tries each, on both binaries. Both binaries measured the
|
||||
same, which is the first finding: **§8.4 is not a regression**.
|
||||
- Instrumented the open path with temporary `eprintln!` timings at four levels
|
||||
(the `didOpen` arm, `Document::new`'s six steps, `Server::publish` /
|
||||
`diagnostics_of`, and `lint_with`'s per-rule loop), measured, and removed
|
||||
every one of them. The breakdown table is above.
|
||||
- Result: the lint pass is 75–95 % of the open and `undriven-net` is 90–97 % of
|
||||
the lint pass, because it asked the workspace census once per declaration
|
||||
ahead of its own local guards. `unused-signal`, the twin rule, has always
|
||||
asked last.
|
||||
- **The fix**: move `ctx.mentioned_elsewhere` in `UndrivenNet::check` below the
|
||||
`usage` / `connected` / `driven` / `reads == 0` guards. Six lines moved, a
|
||||
comment saying why. A pure reordering of `continue`s over a side-effect-free
|
||||
predicate.
|
||||
- Checked equivalence three ways: the unit suite, the corpus check (unmoved),
|
||||
and a wire comparison of published diagnostics between the 0.39.0 binary and
|
||||
the fixed one over a workspace built so that the census both fires and does
|
||||
not. Identical.
|
||||
- Tests: one exact regression pin in the rule (a counting oracle — the findings
|
||||
alone cannot tell the two orders apart), and three wire-level tests in
|
||||
`crates/lucisv_server/tests/e2e.rs` reusing the `Live` session helper that
|
||||
was already there (`talk` writes a whole session before reading, so it cannot
|
||||
time anything).
|
||||
- **Deviation, stated plainly: the wire test's bound is 200 ms, not §46's
|
||||
25 ms.** Two reasons, both measured. (1) `cargo test` builds unoptimized, and
|
||||
one tolerant parse of a 2 000-line buffer costs ~53 ms there on its own —
|
||||
stable to a millisecond across runs — so 25 ms is unreachable in a debug
|
||||
build whatever the lint pass does; §46's 25 ms is a release figure, and the
|
||||
release binary opens the same buffer in 2–4 ms. (2) The test cannot catch the
|
||||
§46 defect at any bound: the census walk costs milliseconds over a forty-file
|
||||
fixture (measured — 53 ms with the fix, 54 ms without it, and 63 ms with the
|
||||
fixture grown to 400 files and per-file-unique names), and a fixture of
|
||||
opentitan's four thousand files has no business in the suite. So the wire
|
||||
test pins the contract — an open does not start doing something unbounded —
|
||||
and the counting oracle test in `undriven_net.rs` is the exact pin for the
|
||||
defect. Both are documented as such in their own doc comments.
|
||||
- Scratch worktree removed; driver and scratch stores deleted; opentitan
|
||||
`git status --porcelain` reports the three pre-existing files and nothing
|
||||
else.
|
||||
|
||||
**Files touched** (the plan's expected set, plus one):
|
||||
|
||||
- `crates/vlog_linter/src/rules/undriven_net.rs` — the fix and its test.
|
||||
- `crates/lucisv_server/tests/e2e.rs` — three wire tests and two helpers.
|
||||
- `docs/features/didopen-cost/README.md` — this file.
|
||||
- `TODO.md` — §46's four dev checkboxes and §44's `didOpen` line.
|
||||
|
||||
Nothing else. In particular **no server source file was changed**: the fix
|
||||
turned out to be one rule in `vlog_linter`, not anything in the open path
|
||||
itself, which is why `crates/lucisv_server/src/server/{notification,diagnostics,
|
||||
index}.rs` and `state.rs` are untouched despite being where §46 expected the
|
||||
work.
|
||||
|
||||
**Gate numbers**: `cargo fmt -p lucisv_server -p vlog_linter` clean; `cargo
|
||||
clippy --all-targets` clean; `cargo test --workspace` **3 814 passed, 0
|
||||
failed, 44 ignored** (baseline 3 810 — the four new tests);
|
||||
`tools/corpus_check.sh` **814/820**, the same six failures and the same
|
||||
`verification-error: none` / `crash: none`; `node editors/vscode/smoke.js
|
||||
target/release/lucisv-server` OK. Every one guarded at `-m 8`; no guard kill,
|
||||
and nothing came near the limit.
|
||||
|
||||
## Docs to apply at merge (lead)
|
||||
|
||||
### `docs/performance_take3.md` — annotate finding §8.4
|
||||
|
||||
Append to §8.4, after the "Reproduce" paragraph:
|
||||
|
||||
> **Fixed in 0.44.0 (TODO §46), and the finding understated it.** The delay is
|
||||
> not the widen, the diagnostics plumbing or §42's lint-run construction: it is
|
||||
> one rule. `undriven-net` asked the workspace census
|
||||
> (`WorkspaceIndex::files_mentioning`, a walk over every indexed file) once per
|
||||
> declaration in the buffer, *before* its own local guards had a chance to
|
||||
> silence it — so a file with four thousand declarations asked four thousand
|
||||
> questions and threw away four thousand answers. `unused-signal`, the twin
|
||||
> rule with the same oracle, has always asked last; `undriven-net` now does
|
||||
> too. At the whole-workspace scope, where the census covers 3 976 files rather
|
||||
> than this section's ~124, the same three files measured 51 / 70 / 95 ms
|
||||
> before and **4.6 / 7.3 / 7.8 ms** after, and opentitan's largest file,
|
||||
> `hw/top_darjeeling/ip_autogen/pinmux/rtl/pinmux_reg_top.sv` (42 192 lines),
|
||||
> went from **1 742 ms to 117 ms**. The take-2 comparison in this section
|
||||
> should be read as "take 2's session probably did not have the workspace rules
|
||||
> on", not as a regression: 0.39.0 measures the same as 0.43.0 on every cell.
|
||||
> Breakdown and method in `docs/features/didopen-cost/README.md`.
|
||||
|
||||
### `docs/perf/README.md` — a new entry
|
||||
|
||||
> ### 2026-09-05 — the `didOpen` delay (TODO §46, 0.44.0)
|
||||
>
|
||||
> Take 3's §8.4 (a `didOpen` of an already-indexed file delaying the next
|
||||
> request by 21–51 ms) measured and fixed. The breakdown, taken with temporary
|
||||
> timings on a release build and re-taken after: the tolerant parse plus the
|
||||
> semantic analysis is 1.3 / 3.0 / 91 ms for a 326- / 1 145- / 42 192-line
|
||||
> opentitan file, and the lint pass was 4.9 / 54 / 1 654 ms — of which
|
||||
> `undriven-net` alone was 4.4 / 52 / 1 608. The rule asked
|
||||
> `WorkspaceIndex::files_mentioning` (a walk over all 3 976 indexed files) once
|
||||
> per declaration, ahead of the local guards that silence almost all of them.
|
||||
> Moved behind them, where `unused-signal` has always asked.
|
||||
>
|
||||
> Wire time, `didOpen` → the request behind it, workspace scope, warm store,
|
||||
> three tries, M1 Max:
|
||||
>
|
||||
> | file | before | after |
|
||||
> |---|---|---|
|
||||
> | `aes.sv` (326 L) | 8.1 / 5.9 / 10.1 ms | 4.3 / 1.8 / 2.3 ms |
|
||||
> | `aes_core.sv` (1 145 L) | 56.2 / 54.0 / 48.0 ms | 5.9 / 6.9 / 6.3 ms |
|
||||
> | `hmac.sv` | 56.8 / 42.7 / 51.0 ms | 4.7 / 5.7 / 3.3 ms |
|
||||
> | `kmac.sv` | 69.3 / 72.1 / 70.6 ms | 7.9 / 5.3 / 8.8 ms |
|
||||
> | `spi_device.sv` | 94.2 / 103.4 / 88.6 ms | 6.0 / 8.6 / 8.7 ms |
|
||||
> | `pinmux_reg_top.sv` (42 192 L) | 1 742 / 1 740 / 1 757 ms | 116.5 / 116.2 / 117.3 ms |
|
||||
>
|
||||
> The same cost was paid on **every keystroke flush**, not just on opens: the
|
||||
> change debounce ends in the same `set_document` + `publish` pair.
|
||||
> 0.39.0 measures the same as 0.43.0 everywhere in the "before" column, so this
|
||||
> was never a regression — it is a rule that has been ordered that way since it
|
||||
> was written. Published diagnostics are byte-identical before and after.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-05 — QA (Sonnet)
|
||||
|
||||
**Verdict: PASS.** No HIGH or MEDIUM findings. Two LOW/informational notes
|
||||
below; neither blocks the fix.
|
||||
|
||||
**What was verified, and how.**
|
||||
|
||||
1. **Code reading.** `git diff` of the three touched files
|
||||
(`crates/vlog_linter/src/rules/undriven_net.rs`,
|
||||
`crates/lucisv_server/tests/e2e.rs`, `TODO.md`) — a pure reordering of six
|
||||
lines plus a comment in the rule, one new unit test asserting the oracle's
|
||||
call count, and three new wire-level tests reusing the existing `Live`
|
||||
helper. Confirmed `unused-signal` (`crates/vlog_linter/src/rules/
|
||||
unused_signal.rs`) already asks its oracle last, behind
|
||||
`mentioned_outside_declarations`, unchanged by this diff — the dev's "its
|
||||
twin rule has always asked last" claim checks out by inspection.
|
||||
`WorkspaceIndex::files_mentioning`/`files_naming_in_macros`
|
||||
(`crates/vlog_semantic/src/workspace/index.rs:286-331`) confirmed
|
||||
word-exact (binary search over a sorted per-file word list, no substring
|
||||
matching) and `crates/vlog_semantic/src/words.rs` confirmed comments
|
||||
contribute no words (only `Ident`/`SystemIdent` tokens and raw text inside
|
||||
macros/directives/attributes) and macro-argument text is folded into the
|
||||
*same* union census `files_mentioning` reads — so a macro-only mention is
|
||||
expected to silence the rule exactly as a plain mention does.
|
||||
2. **Equivalence, scratch workspace.** Built both binaries release
|
||||
(`tools/guard.sh -m 8 -t 900 -- cargo build --release -p lucisv -p
|
||||
lucisv_server`): the working tree at f795606-plus-uncommitted-diff, and
|
||||
`v0.43.0` in a scratch `git worktree` (removed after). Wrote a five-file
|
||||
scratch workspace (`top.sv`, `tb.sv`, `bound_over.sv`, `iface/bus_if.sv`,
|
||||
`pkg/util_pkg.sv`) exercising every guard interaction the attack list
|
||||
named: undriven+mentioned (silent), undriven+unmentioned (reported), driven
|
||||
locally+mentioned (silent), undriven but hierarchically assigned from a
|
||||
sibling testbench (silent), `force`d through a hierarchical path from a
|
||||
sibling (silent), named only in a sibling's `bind`-ed override connection
|
||||
(silent), a plain cross-file mention (silent), a name that is only a
|
||||
*substring* of a longer identifier in a sibling (still **reported** — no
|
||||
substring match), a name that appears in a sibling only inside a `//`
|
||||
comment (still **reported** — comments aren't tokens), a name that appears
|
||||
in a sibling only as a macro argument (silent — the raw-text fold), each
|
||||
port direction, a net inside a `generate` block, a `logic` variable
|
||||
(not a `wire`), an interface, and a package. `lucisv check --select
|
||||
undriven-net .` and `--select unused-signal,undriven-net .` and a full
|
||||
`check .`, text and `--output-format json`: **byte-identical** between the
|
||||
two binaries in every case (6 violations found; `undriven_hier`,
|
||||
`undriven_forced`, `undriven_bound`, `undriven_macro_arg`,
|
||||
`undriven_mentioned`, `driven_and_mentioned` all correctly silent).
|
||||
3. **Equivalence, opentitan (read-only).** `--select undriven-net,unused-signal
|
||||
--output-format json` over `hw/ip/aes`, `hw/ip/hmac`, `hw/ip/spi_device`,
|
||||
`hw/top_darjeeling/ip_autogen/pinmux`, sets compared (order does not
|
||||
matter here since neither directory produced more than one finding):
|
||||
**identical** in all four (`aes`: 1 finding both binaries, set-equal;
|
||||
the other three: 0 findings, both). `git -C ~/repo/opentitan status
|
||||
--porcelain` before and after: only the three pre-existing files
|
||||
(`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`,
|
||||
`hw/top_earlgrey/ip/ast/rtl/ast.sv`).
|
||||
4. **The counting-oracle unit test, reverted.** Not reverted in this tree.
|
||||
Copied the dev's `undriven_net.rs` (with the fix and its new tests) into a
|
||||
fresh scratch worktree at f795606, hand-reverted only the six-line reorder
|
||||
(oracle back above the `usage`/`driven`/`connected`/`reads==0` guards,
|
||||
dev's new test left as written), and ran
|
||||
`cargo test -p vlog_linter --lib rules::undriven_net::`. Result: 16 of 17
|
||||
pass; `the_project_is_asked_only_about_the_signals_that_would_be_reported`
|
||||
**fails** — `assertion left == right failed: left: 10, right: 1` — exactly
|
||||
what asking the oracle before the local guards predicts (all ten
|
||||
signals in that fixture are `judgeable` with no initializer, so all ten
|
||||
reach the pre-fix guard). Confirms the test is an exact regression pin,
|
||||
not a tautology. Worktree removed after.
|
||||
5. **Wire timing, independently reproduced.** The dev's driver is gone, so a
|
||||
new one was written (`scratchpad/perf46_qa/driver.py`, this session's
|
||||
scratchpad) to the same shape: framed JSON-RPC over stdio,
|
||||
`initializationOptions.storagePath` for cache control, `workspace/
|
||||
didChangeConfiguration` to the workspace scope, a `workspace/symbol`
|
||||
barrier before timing, `didOpen`+`hover` in the same flush timed from send
|
||||
to the hover response, warm store, three tries. M1 Max (10 cores, 64 GB),
|
||||
`v0.43.0` (scratch worktree, removed after) vs the fixed tree's release
|
||||
build:
|
||||
|
||||
| File | 0.43.0 | fixed | factor |
|
||||
|---|---:|---:|---:|
|
||||
| `aes.sv` | 4.83 / 4.81 / 4.88 ms | 1.49 / 1.35 / 1.31 ms | ~3.4× |
|
||||
| `aes_core.sv` | 41.4 / 43.2 / 47.1 ms | 3.90 / 3.66 / 3.57 ms | ~11× |
|
||||
| `pinmux_reg_top.sv` | 1825 / 1805 / 1806 ms | 104 / 108 / 107 ms | ~17× |
|
||||
|
||||
Independently-measured numbers differ from the README's own table (a
|
||||
different driver, different process/JSON overhead, one machine) but the
|
||||
**direction and rough magnitude match closely**, `pinmux_reg_top.sv`
|
||||
especially (~17× here vs ~15× claimed, 104-108 ms here vs 116-117 ms
|
||||
claimed). The control hover (issued right after) was 0.05-0.85 ms in every
|
||||
case, before and after alike, confirming the open itself is what costs.
|
||||
Also timed a `didChange` full-text flush on `aes_core.sv` (not just
|
||||
`didOpen`): **42.6-43.5 ms (0.43.0) → 3.8-4.0 ms (fixed)** — confirms the
|
||||
README's "the same cost was paid on every keystroke flush" claim; the
|
||||
flush and the open cost the same because both end in the same
|
||||
`set_document` + `publish` pair, as documented.
|
||||
6. **`opentitan`'s 1.0 MiB index-scan cap, noted in passing (see finding
|
||||
below).** Confirmed by `window/logMessage` output during warm-up:
|
||||
`pinmux_reg_top.sv` under all three top-level variants is *skipped from
|
||||
the workspace index scan* ("skipped (1.3 MiB > 1.0 MiB cap)"), which is
|
||||
exactly take 3's "3976 indexed, 3 skipped" — not a new discovery, just
|
||||
confirms the population this round's numbers describe. The currently
|
||||
*open* buffer is unaffected by this cap (it goes through `Document::new`
|
||||
on `didOpen` regardless of size), which is why the dev's own breakdown
|
||||
table and this session's timings both see `pinmux_reg_top.sv` fully
|
||||
parsed and linted when opened.
|
||||
7. **e2e tests, 5×.** `tools/guard.sh -m 8 -t 300 -- cargo test -p
|
||||
lucisv_server --test e2e -- --test-threads=1
|
||||
opening_a_two_thousand_line_buffer_does_not_delay_the_request_behind_it
|
||||
the_first_hover_after_an_open_sees_the_buffer_and_not_the_disk
|
||||
an_open_still_publishes_its_diagnostics_with_no_edit_behind_it`: **3
|
||||
passed, 0 failed, every one of 5 runs**, 0.65-0.70 s each. Stable.
|
||||
8. **The 200 ms vs 25 ms question — my view for the lead.** The dev's
|
||||
reasoning holds up under independent measurement, not just their own
|
||||
instrumentation: (a) `target/debug/lucisv check` on a fresh 2000-line
|
||||
generated buffer (no workspace) took ~40 ms wall-clock (steady state,
|
||||
process spawn included) against `target/release/lucisv`'s ~10 ms on the
|
||||
same buffer — a debug/release ratio in the same ballpark as the dev's
|
||||
53 ms/2-4 ms claim for the parse alone; (b) a release-mode wire
|
||||
measurement of a comparable 2000-line generated buffer (matching the
|
||||
e2e test's own `generated_module` shape, 40 package neighbours, through
|
||||
the *actual LSP wire* including Python subprocess/JSON overhead) came
|
||||
back at 11.7-11.8 ms — comfortably under both 25 ms and 200 ms. This
|
||||
triangulates the dev's claim: the 200 ms bound is not hiding a live
|
||||
defect, it is debug-build parse cost that release mode does not pay, so
|
||||
asking the debug-build wire test for 25 ms would be asking it to beat a
|
||||
floor the interpreter/parser layer sets on its own. **200 ms is the
|
||||
right bound for this test**; I would not lower it, and I would not read
|
||||
"200 ms, not 25 ms" as the fix being incomplete.
|
||||
9. **Gates, guarded, re-run independently.** `cargo clippy --all-targets`:
|
||||
clean (0.12 s — fully cached, nothing to re-lint since the dev's own
|
||||
clean run). `tools/guard.sh -m 8 -t 1800 -- cargo test --workspace`:
|
||||
**3814 passed, 0 failed, 44 ignored** (summed across every crate's `test
|
||||
result:` line) — matches the dev's claimed count exactly.
|
||||
`tools/guard.sh -m 8 -t 1800 -- tools/corpus_check.sh`: **814/820
|
||||
(99.3%)**, `verification-error: none`, `crash: none`, the same six parse
|
||||
errors. `node editors/vscode/smoke.js target/release/lucisv-server`: OK
|
||||
(20 messages). No guard kill on any run.
|
||||
|
||||
**Findings.**
|
||||
|
||||
- **LOW (informational, not a defect).** While this QA was running, the
|
||||
shared working tree picked up further edits not part of the dev's
|
||||
original diff: `CHANGELOG.md`, `editors/vscode/CHANGELOG.md`,
|
||||
`editors/vscode/README.md` gained 0.44.0 release-note entries, and
|
||||
`TODO.md` gained the §46 dev-checkbox ticks (matching this README's
|
||||
Status/TODO) plus a new §47 planning section, beyond what this QA read at
|
||||
the start of its session. None of this touches the rule, the tests, or
|
||||
this README's content above this log entry, and none of it changed any
|
||||
number this QA independently re-measured — `crates/vlog_linter/src/
|
||||
rules/undriven_net.rs` and `crates/lucisv_server/tests/e2e.rs` are
|
||||
byte-identical to what was diffed at the start of this session (71 and
|
||||
204 changed lines respectively, matching exactly). Flagged so the lead
|
||||
knows the tree was not exclusively QA's for the whole session; not
|
||||
something this QA touched or reverted.
|
||||
- **LOW (context, not a defect).** `WorkspaceIndex`'s workspace-scan size cap
|
||||
(1.0 MiB) skips all three `pinmux_reg_top.sv` variants from the persistent
|
||||
cross-file census entirely. This is pre-existing and matches take 3's own
|
||||
"3976 indexed, 3 skipped" count — not introduced or affected by this
|
||||
change — but worth restating next to this round's numbers since a reader
|
||||
could otherwise wonder why a 1.3 MB file's own words never reach another
|
||||
file's `mentioned_elsewhere` answer. The *open* buffer's own analysis is
|
||||
unaffected by the cap, which is why the timings above still show the full
|
||||
parse+lint cost when the file itself is opened.
|
||||
|
||||
**Equivalence result:** identical findings, identical order, on the scratch
|
||||
fixture (text and JSON), on `lucisv check .` with no `--select`, and on all
|
||||
four opentitan directories — 0.43.0 and the fixed tree agree everywhere
|
||||
tested.
|
||||
|
||||
**Verdict: PASS.**
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-05 — lead.** Accepted; ships in 0.44.0 with §45. The plan's three
|
||||
guesses were wrong and the dev's first step — measure — is what found the
|
||||
real cause: one rule asking the whole-workspace census once per declaration
|
||||
before its local guards. The fix is six reordered lines over a
|
||||
side-effect-free predicate, with equivalence shown three ways (the suite,
|
||||
the corpus, and QA's crafted workspace covering every guard interaction
|
||||
plus four opentitan IPs byte-identical between 0.43.0 and the fix). 15× on
|
||||
the largest file, 10× on typical IPs, on every keystroke as well as every
|
||||
open. The 200 ms wire-test bound is ruled correct: it pins the contract in
|
||||
a debug build whose parse alone is ~53 ms, the exact regression pin is the
|
||||
counting-oracle unit test (verified to fail on a revert), and QA's release
|
||||
measurement of the same buffer (11.7 ms) shows the plan's 25 ms was a
|
||||
release number. No debounce was added and none is needed at 0.5–1.5 ms per
|
||||
publish. (The README lacked its Review section; added here.)
|
||||
@@ -300,6 +300,15 @@ trigger is not too loose.
|
||||
`Fmt::raw_text`'s `crosses_line_inside_string` path emits a `Doc::Text`
|
||||
with embedded newlines and leaves the printer's column stale. Pre-existing
|
||||
(assertions round), no corruption. See Handshakes → Consumed.
|
||||
- [x] **Two of the "not done, deliberately" items above were delivered by
|
||||
TODO §38.1** (2026-09-04, `docs/features/parser-skips/README.md`): a
|
||||
split whose shared tail ends in a **keyword** rather than a `;`, and the
|
||||
one **bracketless** shape that is not indistinguishable from a missing
|
||||
terminator — a unit header the next arm writes again (`jtag_if.sv`).
|
||||
`at_split_conditional`'s fourth condition now reads "bracket open **or**
|
||||
rival header", and `scan_split_extent` takes the unit's closing keyword.
|
||||
The rest of the bracketless family stays refused, and the inside of a
|
||||
split region is still byte-for-byte.
|
||||
|
||||
## Work log
|
||||
|
||||
|
||||
@@ -326,6 +326,20 @@ linter; master's linter has since grown 36 rules, `Severity` on `Rule` and new
|
||||
files, so those three arms need re-applying to master's versions of the two
|
||||
files at merge. Nothing else in this branch touches `crates/vlog_linter`.
|
||||
|
||||
**2026-09-04 — the MEDIUM QA finding below is fixed (TODO §36.2).** The
|
||||
half-typed `#(` override whose value reads as the next instance
|
||||
(`sub #(.WIDTH(8), .DEPTH(` ⏎ `u0 (.a(x), .b(y));`) now costs the one
|
||||
override element and nothing else: `.WIDTH(8)` survives as `Ok`, `.DEPTH(`
|
||||
is the error element, `u0` keeps both its connections and the module keeps
|
||||
its `endmodule`, on one diagnostic at the unclosed `(`. The fix is one
|
||||
tolerant-mode lookahead in `Parser::parse_connection`
|
||||
(`value_runs_into_next_instance`) plus the bracket the skip in
|
||||
`recover_element` now takes when an element gives up standing on one. See
|
||||
`docs/features/small-items-3/README.md`; the shape is pinned by
|
||||
`a_half_typed_override_does_not_swallow_the_next_instance` in
|
||||
`crates/vlog_parser/tests/error_recovery.rs`, with the balanced-parens
|
||||
control beside it (that one is still read greedily, deliberately).
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-04 — QA agent
|
||||
|
||||
@@ -0,0 +1,573 @@
|
||||
# lazy-code-action
|
||||
|
||||
TODO §37 — the three server residues left over from §10: the lazy
|
||||
`codeAction/resolve` for the port refactorings (§37.1), the `inlayHint` zero at
|
||||
the default scope (§37.2), and `locate::location` onto `DeclPositions`
|
||||
(§37.3). One README, one section each.
|
||||
|
||||
## Goal
|
||||
|
||||
**§37.1.** `textDocument/codeAction` arrives on nearly every cursor move, and
|
||||
the port refactorings answered it by computing the *whole* edit — over the
|
||||
instantiated module's entire fan-out plus every open buffer, each file read as
|
||||
text. `docs/performance_take2.md` §6a measured what that costs on opentitan:
|
||||
~1.4 ms per instantiating file plus a ~13 ms floor, **185–201 ms at a 128-file
|
||||
fan-out, to offer zero actions**, above §3's "reads as a hang" line, on the hot
|
||||
path. The *offer* is now local — the buffer, plus the instantiated module's own
|
||||
declaration when the cursor is on an instantiation — and the edit is computed
|
||||
by `codeAction/resolve` when the user picks the action. A client that cannot
|
||||
resolve is unaffected: it still gets the edit up front.
|
||||
|
||||
**§37.2.** `inlayHint` returns 0 hints at the default (folder) scope where the
|
||||
workspace scope returns 4 (`performance_take2.md` §4b, §8.9), the one §4b row
|
||||
the `didOpen` widen did not fix. Investigated, and it is **not a bug** — the
|
||||
finding is written out below, with two tests that pin it.
|
||||
|
||||
**§37.3.** Every file-scope declaration's client-side range is already in the
|
||||
index (`DeclPositions`, added by the design-hierarchy round), so
|
||||
`textDocument/definition` and `workspace/symbol` need not read a file to
|
||||
convert an indexed span. They no longer do: **27.7 µs → 0.40 µs per
|
||||
definition** on opentitan.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The offer may be optimistic; the resolve is exact.** A refusal the engine
|
||||
can only see over the fan-out — an instantiation elsewhere connecting `sub`'s
|
||||
ports *by position*, which makes `remove_port` refuse whole — is invisible to
|
||||
a one-file offer, so the lightbulb can appear and the resolve then decline
|
||||
with "the action is no longer available". This is the trade LSP's resolve
|
||||
model is for; the alternative is the 185 ms. The refusals cheap enough to
|
||||
keep are kept: a module the index declares twice is checked through
|
||||
`WorkspaceIndex::units` before anything is offered, exactly as the eager path
|
||||
refuses over the two declaring files it reads.
|
||||
- **The count in an offered title comes from the index and may be one behind.**
|
||||
`instantiations_of(name)` records one edge per *written statement* with its
|
||||
instances, and the title counts **instances** (`sub u1(), u2();` is two), to
|
||||
match what the eager title counts — the instances the plan really rewrites.
|
||||
The two disagree exactly where the index cannot know: an unsaved buffer's new
|
||||
instantiation, a file-scope instantiation site (which records no edge at
|
||||
all), an instance connecting with `.*`. So the offered and resolved actions
|
||||
are matched on the title *without* its count phrase (`ports::key`), and the
|
||||
resolved action carries the exact title.
|
||||
- **`Def::lines.positions` is `Some` for every file-scope declaration and
|
||||
`None` for every member**, as `DeclLines` documents. §37.3 relies on that:
|
||||
members keep the file-read path, which is not a fallback nobody takes — it is
|
||||
the only answer a port has.
|
||||
- **`codeAction/resolve` carries no `textDocument`**, so the large-file fast
|
||||
path's gate — which reads a URI out of the params — never sees it. `resolve`
|
||||
refuses a buffer on that fast path itself: the mode's contract is that a
|
||||
large buffer is never parsed, and one stale lightbulb is not a reason to
|
||||
break it.
|
||||
- An **open buffer** keeps the file-read path in §37.3 whatever the index
|
||||
recorded, because the buffer's text may have moved since it was indexed and
|
||||
every other answer about that buffer is computed against the text it holds
|
||||
now.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **`vlog_refactor` → server.** `ports::sites_phrase` is now `pub` (re-exported
|
||||
from the crate root as `vlog_refactor::sites_phrase`). The server writes the
|
||||
same sentence with a count of its own, and one spelling of a user-visible
|
||||
string is the point. Nothing else in `vlog_refactor` changed; `port_actions`,
|
||||
`port_action_modules` and `module_definition` are consumed exactly as before.
|
||||
- **`Workspace` → server.** `Workspace::held_views()` added, `#[cfg(test)]`
|
||||
and `pub(crate)`: the view cache is how a test asserts that an answer read no
|
||||
file. No production caller.
|
||||
- **`main.rs` → `server`.** `ClientAbilities` gains `code_action_resolve`, read
|
||||
at `initialize` from `textDocument.codeAction.resolveSupport.properties`
|
||||
containing `"edit"`. The `initialize` result advertises
|
||||
`codeActionProvider.resolveProvider: true` unconditionally — the server can
|
||||
always answer a resolve, including for an action that already carries its
|
||||
edit, which it hands straight back.
|
||||
- **The wire.** New method answered: `codeAction/resolve`. New field on an
|
||||
offered port action: `data` (`{uri, position, title}`), opaque to the client.
|
||||
The quick fixes in `code_action.rs` are unchanged and still complete when
|
||||
offered.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] §37.1 `ports::offers` — the local offer, titles counted from the index,
|
||||
`data` instead of an edit.
|
||||
- [x] §37.1 `ports::resolve` — today's eager answer at the offer's position,
|
||||
matched on `key(title)`; `RequestFailed` with "the action is no longer
|
||||
available." when nothing matches, and a distinct sentence for an action
|
||||
this server never offered.
|
||||
- [x] §37.1 capability gate: `code_action_resolve_support` in `main.rs`,
|
||||
`ClientAbilities::code_action_resolve`, the dispatch branch.
|
||||
- [x] §37.1 `resolve_provider: Some(true)` advertised; `codeAction/resolve`
|
||||
dispatch arm.
|
||||
- [x] §37.1 tests: the offer's menu equals the eager one over `crowded(40)`;
|
||||
the offer's source set is the buffer (+ the declaring file); the resolved
|
||||
edit is byte-equal to the eager one at both cursor shapes; the unsaved
|
||||
buffer answered by the resolve; a stale and a closed document refused; a
|
||||
foreign action refused; a complete action returned untouched; the
|
||||
duplicate-declaration refusal; a buffer that grew onto the large-file
|
||||
fast path; `key`'s own unit test.
|
||||
- [x] §37.1 e2e over the wire, both client shapes.
|
||||
- [x] §37.1 perf: the "offer" column on `perf.rs`'s
|
||||
`a_code_action_at_an_instantiation_before_and_after`, plus
|
||||
`ports::tests::the_offer_is_flat_where_the_eager_answer_grows`
|
||||
(3/40/128 instantiators, both cursor shapes).
|
||||
- [x] §37.2 investigated; finding written below; two tests at the default
|
||||
scope.
|
||||
- [x] §37.3 `locate::definition_location`, routed through `nav::definition`
|
||||
and `symbols::workspace_symbols`.
|
||||
- [x] §37.3 pins: the encoding shapes, no `file_view` created, members keep
|
||||
the read, the open-buffer case.
|
||||
- [x] §37.3 opentitan timing, read-only
|
||||
(`locate::tests::defining_over_a_real_project`).
|
||||
- [ ] Not done, deliberately: **memoising `module_sources`** per (module, index
|
||||
generation), take 1's other suggestion. The offer makes it unnecessary on
|
||||
the hot path — the fan-out is now read once per *click* — and a cache
|
||||
keyed on a generation is a staleness question this round did not need to
|
||||
open.
|
||||
- [ ] Not done, deliberately: **the quick fixes stay eager.** They are built
|
||||
from the buffer's own violations, which the server has already computed
|
||||
for the diagnostics; there is nothing to defer.
|
||||
|
||||
## §37.1 — how the offer stays local
|
||||
|
||||
`ports::offers` runs the engine's own `port_actions` over a source set built by
|
||||
`ports::offer_sources`:
|
||||
|
||||
1. **the buffer the request names**, from the open document (no read);
|
||||
2. **the declaring file of every module `port_action_modules` named**, via
|
||||
`vlog_refactor::module_definition(index, name)` — the same two steps
|
||||
`inlay.rs`'s `Plans::read` takes, and one file read at most.
|
||||
|
||||
A cursor on a **port declaration** names its own module, whose declaring file
|
||||
*is* the buffer, so that case reads nothing at all. A cursor on an
|
||||
**instantiation** names the instantiated module, and its declaration is what
|
||||
`propagate_ports` needs to know which connections are missing — so the offer
|
||||
is exact for that action, including its "connect N missing ports" count, which
|
||||
is a count of edits in the cursor's own file.
|
||||
|
||||
The edits `port_actions` computes over those one or two files are thrown away.
|
||||
Only the titles and the kind survive, plus `data`.
|
||||
|
||||
`ports::resolve` re-runs `ports::code_actions` — today's eager path, unchanged
|
||||
— at the offer's position and returns the action whose `key(title)` matches.
|
||||
|
||||
### Measured
|
||||
|
||||
This machine, 2026-09-04, release.
|
||||
|
||||
`cargo test --release -p lucisv_server perf::a_code_action -- --ignored
|
||||
--nocapture --test-threads=1` — the original probe (a port of a module
|
||||
instantiated in 3 of 504 files, 200 lines each), now with the offer column
|
||||
TODO §37.1 asked for:
|
||||
|
||||
| whole workspace | fan-out (eager) | **offer** | `sources()` alone |
|
||||
|---:|---:|---:|---:|
|
||||
| 776 ms | 433 µs | **58 µs** | 11.5 ms |
|
||||
|
||||
`cargo test --release -p lucisv_server --bin lucisv-server
|
||||
ports::tests::the_offer_is_flat -- --ignored --nocapture --test-threads=1` —
|
||||
200 noise modules plus `n` files instantiating `sub`, the shape §6a measured
|
||||
on opentitan:
|
||||
|
||||
| fan-out | cursor | eager | **offer** | actions |
|
||||
|---:|---|---:|---:|---:|
|
||||
| 3 | a port declaration | 485 µs | **68 µs** | 1 |
|
||||
| 3 | an instantiation | 172 µs | **72 µs** | 0 |
|
||||
| 40 | a port declaration | 4.84 ms | **53 µs** | 1 |
|
||||
| 40 | an instantiation | 1.45 ms | **55 µs** | 0 |
|
||||
| 128 | a port declaration | 15.0 ms | **53 µs** | 1 |
|
||||
| 128 | an instantiation | 4.60 ms | **55 µs** | 0 |
|
||||
|
||||
The eager column grows with the fan-out and the offer column does not: 53–72 µs
|
||||
at every size, both cursors (the two 3-file rows are the first measurements
|
||||
taken in the process and carry that much warm-up). The two "0 actions" rows are
|
||||
§6a's own complaint — a cursor on a fully-connected instantiation, where the old
|
||||
path spent its whole bill to offer nothing.
|
||||
|
||||
## §37.2 — the `inlayHint` zero at the default scope is correct
|
||||
|
||||
**Finding: not a bug. `performance_take2.md` §4b's last row compares a
|
||||
different question from every row above it.**
|
||||
|
||||
Every other row of that table asks about `aes` — `definition`, `hover`,
|
||||
`signatureHelp`, `references` on the `aes` instantiation in
|
||||
`hw/ip/aes/dv/tb/tb.sv`. `aes` is declared in `hw/ip/aes/rtl/aes.sv`, which the
|
||||
`didOpen` widen reaches: opening `hw/ip/aes/dv/tb/tb.sv` at the shipped
|
||||
`scopeDepth` of 2 raises to `hw/ip/aes`, 124 files. So those rows answer.
|
||||
|
||||
`inlayHint` cannot ask about `aes` at all: that instantiation's connections are
|
||||
**named** (`.clk_i(clk)`), and a named connection gets no hint by design — the
|
||||
reader can already see which port is which. The only positional connections in
|
||||
`tb.sv` are:
|
||||
|
||||
```systemverilog
|
||||
pins_if #($bits(lc_escalate)) lc_escalate_if (lc_escalate);
|
||||
pins_if #(1) idle_if (idle);
|
||||
```
|
||||
|
||||
Two positional parameter overrides and two positional port connections — **the
|
||||
4 hints the workspace scope returns**. `pins_if` is declared in
|
||||
`hw/dv/sv/common_ifs/pins_if.sv`; there is no `pins_if` anywhere under
|
||||
`hw/ip/aes` (checked). So at the default scope the module is genuinely not in
|
||||
the index, `vlog_refactor::module_definition` has nothing to answer with, and
|
||||
`Plans::read` declines — which is the documented contract: an instantiation
|
||||
whose module the index does not hold gets no hints, because guessing port names
|
||||
puts a wrong name on screen with no way for the reader to tell.
|
||||
|
||||
`inlay.rs` uses **the same lookup its neighbours use**. `signature.rs:28` and
|
||||
`completion`'s module-header tier call `vlog_refactor::module_definition` on the
|
||||
same index; hover and definition go through the same overlay. Asked about
|
||||
`pins_if` at the default scope, every one of them answers nothing too. There is
|
||||
no lookup inlay is missing.
|
||||
|
||||
Two tests pin it (`inlay.rs`), on an opentitan-shaped tree — `ip/aes/rtl`,
|
||||
`ip/aes/dv/tb`, and a `dv/common` beside the block:
|
||||
|
||||
- `the_default_scope_hints_a_module_the_didopen_widen_reached` — at the
|
||||
**default** scope (no `index.scope`, `scopeDepth` 2), the instantiation of the
|
||||
block's own module is hinted. The default scope hints; §4b's row is not
|
||||
evidence that it does not.
|
||||
- `an_out_of_scope_module_is_unhinted_exactly_as_it_is_undefined` — the
|
||||
instantiation of the module outside the block gets no hints, **and**
|
||||
`textDocument/definition` and hover give nothing for it either; widening to
|
||||
the workspace scope makes all three answer.
|
||||
|
||||
For the lead: if the wanted behaviour is that a hint pulls its module's
|
||||
declaration in from outside the scope, that is a *scope* change (the widen
|
||||
would have to follow instantiation edges), and it would change what
|
||||
`definition`, `hover` and `completion` answer at the same time. It is not an
|
||||
inlay-hint fix, and it is not what this round did.
|
||||
|
||||
## §37.3 — `locate::definition_location`
|
||||
|
||||
`Def::lines.positions` holds `{name, decl}` as `Utf16Range`s, converted through
|
||||
the declaring file's own `LineIndex::utf16_position` while it was indexed —
|
||||
which is the very converter `convert::Positions` uses on the wire, so the two
|
||||
cannot disagree. `locate::definition_location(ws, path, def)` returns the name's
|
||||
range straight from there when the file has no open buffer, and falls through to
|
||||
`locate::location`'s read otherwise (an open buffer, or a member, which records
|
||||
no positions).
|
||||
|
||||
Routed through: `nav::definition`'s `Definition::External` arm and
|
||||
`symbols::workspace_symbols`. `nav`'s `` `define`` arm keeps the read — a
|
||||
`DefineTable` entry is not a `Def` and has no recorded positions.
|
||||
|
||||
### Pins
|
||||
|
||||
- `locate::tests::the_two_paths_agree_over_multi_byte_astral_crlf_and_a_bom` —
|
||||
one file with a BOM at offset 0, CRLF endings, two- and three-byte
|
||||
characters and an astral character that is two UTF-16 code units; the
|
||||
index-only `Location` equals the file-read one exactly.
|
||||
- `locate::tests::a_file_scope_definition_is_located_without_reading_its_file`
|
||||
and `nav::tests::a_cross_file_definition_reads_no_file` — asserted through
|
||||
`Workspace::held_views()`, the view cache a read would land in. Empty after
|
||||
the definition and after a `workspace/symbol`; one entry after the same
|
||||
question is asked the old way.
|
||||
- `locate::tests::a_member_keeps_the_file_read_path` — a port records no
|
||||
positions and still answers, through the read.
|
||||
- `locate::tests::an_open_buffer_still_answers_from_the_buffer`.
|
||||
|
||||
### Measured, over opentitan, read-only
|
||||
|
||||
`LUCISV_PERF_CORPUS=/Users/guoliangchen/repo/opentitan cargo test --release -p
|
||||
lucisv_server --bin lucisv-server locate::tests::defining -- --ignored
|
||||
--nocapture --test-threads=1`, 3 976 indexed files, 200 targets (modules the
|
||||
corpus instantiates, each in a different file):
|
||||
|
||||
| | total, 200 definitions | per definition |
|
||||
|---|---:|---:|
|
||||
| file-read (before) | 5.54 ms | 27.7 µs |
|
||||
| index-only (after) | 80.5 µs | **0.40 µs** |
|
||||
|
||||
69× on the conversion, and it is the whole of what a cross-file
|
||||
`textDocument/definition` into a closed file was doing besides the lookup.
|
||||
`git -C ~/repo/opentitan status --porcelain` unchanged after the run.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-04 — dev agent (Opus)
|
||||
|
||||
- Read `CLAUDE.md`, TODO §37 and the §10 lines it closes,
|
||||
`docs/performance_take2.md` §4b/§6a/§7/§8, and the code each item names.
|
||||
- **§37.3 first** (smallest, independent). `locate::definition_location` plus
|
||||
`locate::range`; `state.rs` gained `held_views()` (`#[cfg(test)]`,
|
||||
`pub(crate)`) so a test can assert that no file was read. Routed
|
||||
`nav::definition` and `symbols::workspace_symbols` through it. Four tests in
|
||||
`locate.rs` (new test module) and one in `nav.rs`.
|
||||
- Deviation from the plan's expectation, recorded: the plan said "no
|
||||
`file_view` created for a file-scope definition"; the assertion is through
|
||||
`Workspace::held_views()`, a new test-only accessor, rather than a
|
||||
counter — the cache *is* the counter, and it is already what `state.rs`'s
|
||||
own tests assert against.
|
||||
- One thing the plan did not anticipate: an **open buffer** must keep the
|
||||
file-read path. Its `Def` spans are the disk file's until the next
|
||||
re-index, and converting them against the buffer's current text is what
|
||||
every other answer about that buffer does. Pinned by
|
||||
`an_open_buffer_still_answers_from_the_buffer`, which asserts the
|
||||
(pre-existing, unchanged) stale-span behaviour rather than pretending this
|
||||
round fixed it.
|
||||
- **§37.2 second.** Investigated by reading `hw/ip/aes/dv/tb/tb.sv` and
|
||||
locating `pins_if` in the opentitan checkout (read-only, `find`/`ls` only).
|
||||
The zero is correct; the finding is written above, with two tests. No
|
||||
production code changed for this item.
|
||||
- **§37.1 last.** `ports::offers`, `ports::offer_sources`, `ports::resolve`,
|
||||
`ports::key`, `ports::counted`, `ports::instances_of`,
|
||||
`ports::declared_twice`; `ClientAbilities::code_action_resolve`;
|
||||
`code_action_resolve_support` in `main.rs`; `resolve_provider: Some(true)`;
|
||||
the dispatch branch and the `codeAction/resolve` arm.
|
||||
- **Deviation, flagged:** `vlog_refactor::ports::sites_phrase` was made
|
||||
`pub` and re-exported. The plan allowed a change to
|
||||
`crates/vlog_refactor/src/ports/mod.rs` "only if the offer needs a new
|
||||
one-file question", and this is not one — it is the alternative to writing
|
||||
a second spelling of a user-visible sentence in the server and letting the
|
||||
two drift. No behaviour changed in `vlog_refactor`.
|
||||
- **Deviation, flagged:** the plan said resolve returns "the action whose
|
||||
title matches". Exact title matching cannot work, because the offer's
|
||||
count comes from the index and the eager count from the plan, and the
|
||||
plan's own §37.1 requires the unsaved-buffer case (index 3, plan 4) to
|
||||
resolve. Matching is therefore on `key(title)` — the title with its
|
||||
trailing ` (…)` count phrase removed. An escaped identifier cannot contain
|
||||
a space, so `" ("` never occurs inside a port name; `a_title_keys_on_
|
||||
everything_but_its_count` pins it.
|
||||
- **Deviation, flagged:** `resolve` returns an action that already carries an
|
||||
`edit` unchanged instead of refusing it. A client that declares
|
||||
`resolveSupport` may resolve anything it was offered, including the quick
|
||||
fixes, and refusing those would break fix-on-save for exactly the clients
|
||||
this feature is for.
|
||||
- `resolve` refuses a large-file buffer, because the fast path's own gate
|
||||
cannot see a request whose params are a `CodeAction`. Found by reading
|
||||
`server/large_file.rs`'s `document_uri`, not by a test failing; pinned by
|
||||
`a_resolve_against_a_buffer_on_the_large_file_fast_path_is_refused`.
|
||||
- The existing eager pin `an_unsaved_buffer_contributes_the_instantiation_
|
||||
the_index_has_not_seen` was **kept** rather than moved: the eager path is
|
||||
still live code for a client without `resolveSupport`. Its lazy sibling
|
||||
`the_resolved_edit_sees_an_unsaved_buffer_the_offer_could_not_count` is the
|
||||
moved pin.
|
||||
- **The two new perf probes live beside the code they measure**, not in
|
||||
`perf.rs`: `perf.rs` is already the one file over the size rule with a
|
||||
written reason (895 production lines, `docs/features/decomposition-server`),
|
||||
and `perf::mean` is `pub(crate)` precisely so a probe can sit next to its
|
||||
subject — `nav.rs`'s references probes already do. `perf.rs` grew by the
|
||||
five lines of the offer column and nothing else (900 lines).
|
||||
- Files touched outside the plan's expected set: **none**
|
||||
(`crates/vlog_refactor/src/lib.rs` for the re-export is the only file not
|
||||
named in it; `crates/vlog_refactor/src/ports/mod.rs` was named).
|
||||
|
||||
## Gates (dev, guarded, 2026-09-04)
|
||||
|
||||
- `cargo fmt -p lucisv_server`, `cargo fmt -p vlog_refactor` — clean
|
||||
(`--check` verified).
|
||||
- `cargo clippy --all-targets` — clean, no new `#[allow]`.
|
||||
- `tools/guard.sh -- cargo test --workspace` — **3 734 passed, 0 failed,
|
||||
44 ignored** (the ignored are the perf probes).
|
||||
- `tools/guard.sh -- tools/corpus_check.sh` — **814/820 (99.3 %)**, the same
|
||||
six failures, `verification-error: none`, `crash: none`.
|
||||
- `cargo build --release -p lucisv_server` then `tools/guard.sh -- node
|
||||
editors/vscode/smoke.js target/release/lucisv-server` — OK, 20 messages.
|
||||
- No guard kill at any point. `git -C ~/repo/opentitan status --porcelain`
|
||||
after every opentitan read: the same three pre-existing modifications
|
||||
(`hw/ip/aes/dv/tb/tb.sv`, both `ast.sv`), nothing else.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-04 — QA agent (Sonnet)
|
||||
|
||||
Read `CLAUDE.md`, TODO §37, the dev's account above in full (Goal, Assumptions,
|
||||
Handshakes, work log — all five flagged deviations), then the diffs of every
|
||||
touched file. Attacked the three items over the real code, not just the
|
||||
dev's own tests; every scratch test below was added as a temporary `#[test]`,
|
||||
run, and removed before this log was written (`git diff --stat` after cleanup
|
||||
is byte-identical to the dev's own: 15 modified + this README).
|
||||
|
||||
**§37.1 — lazy `codeAction`/`resolve`.**
|
||||
|
||||
- Malformed `data` (scratch test in `ports.rs`): a wrong-typed `uri` (a JSON
|
||||
number) fails to deserialize into `Offer` → `NOT_OURS`; a well-formed `data`
|
||||
naming a document **never opened at all** (distinct from one that was open
|
||||
and closed) → `GONE`; a `position` far past EOF → `Positions::offset` clamps
|
||||
to the text length (confirmed by reading `convert.rs:44-59`) rather than
|
||||
panicking, `code_actions` at the clamped offset finds nothing, → `GONE`. No
|
||||
panic in any case.
|
||||
- A closed document and a document whose port has since been removed: both
|
||||
already pinned by the dev's `a_resolve_of_an_action_the_buffer_no_longer_
|
||||
carries_is_refused`; reproduced by re-running it directly.
|
||||
- The unsaved-buffer "different count" case (index says 3, buffer really has
|
||||
4): the dev's `the_resolved_edit_sees_an_unsaved_buffer_the_offer_could_not_
|
||||
see` is exactly this attack — re-run, still resolves with the corrected
|
||||
title and the wider edit.
|
||||
- A quick-fix action passed to `resolve`: `code_action.rs`'s `quick_fix`
|
||||
(line ~76) always sets `edit: Some(...)`, so it always takes `resolve`'s
|
||||
first branch (`action.edit.is_some()` → returned unchanged) regardless of
|
||||
origin — confirmed by reading the function rather than by a redundant
|
||||
integration test, since the logic path is identical to the dev's own
|
||||
synthetic "complete" case in `a_resolve_of_something_this_server_never_
|
||||
offered_says_so`.
|
||||
- Title-key matching with an escaped identifier containing `(` and no interior
|
||||
space (`\rst(a)`, IEEE 1800-2017 §5.6.1 — an escaped identifier ends at
|
||||
whitespace): built a real module with this port name, instantiated it in
|
||||
three files, and drove the actual engine (not a hand-built title) through
|
||||
`offered`/`code_actions`/`resolve`. The offer's menu matched the eager
|
||||
menu, the title genuinely carried the literal `` `\rst(a)` `` including the
|
||||
paren, and `key()` still isolated the trailing count phrase correctly — the
|
||||
dev's reasoning in the comment on `key` holds under an adversarial name.
|
||||
(One test-authoring pitfall found and fixed on my own scratch test, not a
|
||||
product bug: `ports.rs`'s pre-existing `qa_escaped_module_name_
|
||||
instantiation_parity_with_whole_workspace` also builds a `Tree::new(
|
||||
"qa_escaped")`, and reusing that same name in my own scratch test raced the
|
||||
two tests over the same temp directory under parallel `cargo test`
|
||||
execution, producing spurious failures in both. Renamed my scratch tree and
|
||||
the collision was gone on repeated runs. `Tree::new` keys its temp directory
|
||||
on the string name alone with no per-test-function salt, which is a latent
|
||||
hazard for the *next* test added under the same name — not something this
|
||||
feature's diff introduced or should fix, flagging it here rather than in
|
||||
the diff.)
|
||||
- Capability gate over the wire (scratch test in `tests/e2e.rs`, two shapes in
|
||||
one loop): `resolveSupport` present but its `properties` list `["documentation"]`
|
||||
(no `"edit"`), and `capabilities: {}` with no `codeAction` key at all. Both
|
||||
got the eager shape — `data` null, `edit` inline with the real
|
||||
`WorkspaceEdit` — over an actual `initialize` → `didOpen` →
|
||||
`textDocument/codeAction` session, not just the unit test of
|
||||
`code_action_resolve_support` in isolation.
|
||||
- Large-file mode: confirmed by reading `server/large_file.rs`'s
|
||||
`document_uri` (`params.get("textDocument")?...`) — a `codeAction/resolve`
|
||||
request's params are a bare `CodeAction`, which has no `textDocument` key,
|
||||
so `large_file_answer` returns `None` unconditionally for this method and
|
||||
the request falls through to `dispatch.rs`'s normal arm, where `ports::
|
||||
resolve`'s own `.filter(|doc| !doc.large)` refuses it. Re-ran the dev's
|
||||
`a_resolve_against_a_buffer_on_the_large_file_fast_path_is_refused` — passes,
|
||||
no panic.
|
||||
- Cost/timing, re-derived independently over the wire against the real
|
||||
opentitan checkout (confirmed still 128 files instantiate `prim_flop_2sync`
|
||||
today via `grep`), read-only throughout:
|
||||
- Built `lucisv-server` v0.40.0 in a scratch worktree
|
||||
(`git worktree add /private/tmp/.../scratchpad/base v0.40.0`, `cargo build
|
||||
--release -p lucisv_server`, then `git worktree remove` — the one git
|
||||
command used outside status/diff), and wrote a small throwaway Node driver
|
||||
(`scratchpad/time_code_action.js`, modeled on `editors/vscode/smoke.js`'s
|
||||
framing) to time a real `textDocument/codeAction` at the
|
||||
`prim_flop_2sync` instantiation in `hw/ip/aon_timer/rtl/aon_timer.sv`,
|
||||
workspace-scoped via `initializationOptions.lucisv.index.scope`.
|
||||
- v0.40.0 server, eager (no `resolveSupport`): 76.4 / 76.4 / 77.8 ms repeats.
|
||||
- This branch's server, eager (no `resolveSupport`): 77.3 / 76.2 / 77.7 ms
|
||||
repeats — statistically identical to v0.40.0, confirming no regression for
|
||||
a client that cannot resolve.
|
||||
- This branch's server, **offer** (`resolveSupport: ["edit"]`): 4.76 / 4.38
|
||||
/ 4.25 ms repeats — about **16× faster**, both with 0 actions returned
|
||||
(the same "worst case: full cost, nothing offered" shape §6a complained
|
||||
about).
|
||||
- Also re-ran the dev's own ignored perf probe
|
||||
(`ports::tests::the_offer_is_flat_where_the_eager_answer_grows`) directly:
|
||||
eager 656 µs–15.6 ms across 3/40/128 fan-out, offer 55–78 µs flat — closely
|
||||
matches the table in this README (§37.1 "Measured").
|
||||
- **Note, not a finding against this feature:** my repeat numbers (~76 ms
|
||||
eager) are well under `performance_take2.md` §6a's originally recorded
|
||||
184.9–186.2 ms for this exact shape. Both old and new servers agree with
|
||||
each other on *this* machine, so it reads as a machine/measurement-harness
|
||||
difference from whatever produced §6a's numbers, not a regression — the
|
||||
relative number this feature is judged on (offer vs. eager, same server,
|
||||
same request) is the clean ~16× and it holds.
|
||||
- `offer_sources`'s read set: re-ran the dev's `the_offer_reads_the_buffer_
|
||||
and_at_most_the_declaring_file` — one file at a port declaration, the buffer
|
||||
plus the declaring file (never the instantiating tops or noise files) at an
|
||||
instantiation.
|
||||
|
||||
**§37.2 — the `inlayHint` zero at the default scope.**
|
||||
|
||||
- Verified the finding independently against the **real** opentitan checkout,
|
||||
read-only: `find . -iname pins_if.sv` → exactly one hit,
|
||||
`hw/dv/sv/common_ifs/pins_if.sv`, confirmed outside `hw/ip/aes` entirely (a
|
||||
sibling library folder the default scope's raise-to-`hw/ip/aes` widen does
|
||||
not reach).
|
||||
- Wrote a scratch, `#[ignore]`d test in `inlay.rs` (guarded, read-only) that
|
||||
opens the real `hw/ip/aes/dv/tb/tb.sv` at the shipped default scope and
|
||||
asserts: the widen reached files under `hw/ip/aes` but none under
|
||||
`common_ifs`; `nav::definition`, `hover::hover` and `inlay_hints` all answer
|
||||
nothing about the `pins_if` instantiation. All three held. Agree with the
|
||||
dev's finding: this is a scope-reach question, not an inlay-hint bug, and
|
||||
every neighbour using the same `module_definition` lookup is equally blind
|
||||
to it at this scope.
|
||||
- `git -C ~/repo/opentitan status --porcelain` unchanged after every read
|
||||
(the same three pre-existing modifications).
|
||||
|
||||
**§37.3 — `locate::definition_location` index-only path.**
|
||||
|
||||
- Re-ran every pin in `locate.rs` and `nav.rs`; all pass.
|
||||
- Extra encoding attacks beyond the dev's own (BOM, CRLF, multi-byte, astral):
|
||||
a **tab-indented** declaration, and a declaration **after a lone `\r`**
|
||||
(old-Mac line ending, not `\n`) — both agree between the index-only and
|
||||
file-read paths exactly. (First attempt at the lone-`\r` case put it inside
|
||||
a line comment and found zero declarations at all: `lexer.rs`'s line-comment
|
||||
scanner runs to the next `\n` only, so a bare `\r` inside a comment does not
|
||||
end it and the intended module got swallowed into the comment text — a
|
||||
pre-existing, unrelated lexer property, not a locate.rs bug. Moved the `\r`
|
||||
outside the comment and the equality attack ran as intended.)
|
||||
- An open buffer with an edit above the definition still answers from the
|
||||
buffer's own current text, confirmed via the dev's `an_open_buffer_still_
|
||||
answers_from_the_buffer` (re-run) plus reasoning: `ws.document_for_path`
|
||||
gates the index-only branch off whenever a buffer is open, whatever the
|
||||
index recorded.
|
||||
- `held_views()` is `#[cfg(test)]` — grep and the diff both confirm no
|
||||
production caller; it cannot be reached outside a test build.
|
||||
- Timing re-derived independently, read-only, over the real opentitan
|
||||
checkout (3 976 indexed files, 200 targets): **index-only 390 ns/definition,
|
||||
file-read 27.9 µs/definition** — matches the README's 0.40 µs / 27.7 µs
|
||||
claim within run-to-run noise, same ~69–71× ratio.
|
||||
`git -C ~/repo/opentitan status --porcelain` unchanged.
|
||||
|
||||
**Gates, re-run myself, guarded:**
|
||||
|
||||
- `cargo clippy --all-targets` — clean, no warnings (checked both with and
|
||||
without my scratch tests present).
|
||||
- `tools/guard.sh -- cargo test --workspace` — **3 734 passed, 0 failed, 44
|
||||
ignored**, matching the dev's own gate exactly. No guard kill.
|
||||
- `tools/guard.sh -- tools/corpus_check.sh` — **814/820 (99.3%)**, the same
|
||||
six failures, `verification-error: none`, `crash: none`.
|
||||
- `tools/guard.sh -- node editors/vscode/smoke.js target/release/lucisv-server`
|
||||
— OK, 20 messages.
|
||||
- `git -C ~/repo/opentitan status --porcelain` after every opentitan read,
|
||||
throughout the session: unchanged, the same three pre-existing
|
||||
modifications every time.
|
||||
- Scratch worktree at `/private/tmp/.../scratchpad/base` (v0.40.0) removed
|
||||
with `git worktree remove` after use; `git worktree list` shows only the
|
||||
main tree.
|
||||
|
||||
**Findings.** None at HIGH or MEDIUM severity. Two LOW, informational, neither
|
||||
in this feature's own diff:
|
||||
- LOW — `ports.rs`'s test-scratch `Tree::new` keys its temp directory on the
|
||||
caller-supplied string alone, with no per-test salt; two tests choosing the
|
||||
same name race under parallel execution (reproduced against the pre-existing
|
||||
`qa_escaped_module_name_instantiation_parity_with_whole_workspace`). Not
|
||||
part of this diff and not blocking; worth a name-collision guard (e.g.
|
||||
salt with the test's `#[test]` function name) if it bites again.
|
||||
- LOW — the offer/eager repeat-timing numbers measured this session (~76 ms
|
||||
eager, ~4.5 ms offer, both machines) are well under `performance_take2.md`
|
||||
§6a's recorded 184.9–186.2 ms for the identical 128-file-fan-out shape;
|
||||
old and new servers agree with each other on this machine, so it reads as
|
||||
environment drift from whatever produced §6a's numbers rather than a
|
||||
regression this feature introduced. Recorded for whoever next revisits
|
||||
§6a's absolute numbers.
|
||||
|
||||
**Verdict: PASS.**
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-04 — lead.** Accepted; ships in 0.41.0. 37.1 is the shape §10
|
||||
asked for and the numbers say why: the offer is flat (53–68 µs from a
|
||||
3-file to a 128-file fan-out, on both cursor shapes) where the eager path
|
||||
is linear, and over the wire on opentitan's worst case QA measured the
|
||||
offer at ~4.5 ms against ~77 ms eager — the cursor-move request is off the
|
||||
fan-out. The dev's five deviations are all right: matching on the title's
|
||||
key rather than the exact title is forced by the plan's own unsaved-buffer
|
||||
requirement, and the escaped-identifier attack (`\rst(a)`) shows the key
|
||||
holds; refusing a resolve on a large buffer closes a gate the fast path's
|
||||
URI check cannot see; keeping the eager unsaved-buffer pin beside its
|
||||
lazy sibling is correct because the eager path is still live for clients
|
||||
that cannot resolve. 37.2 is ruled as the dev framed it: the zero is
|
||||
correct — `pins_if` is declared outside what the default scope reaches
|
||||
from `tb.sv`, definition and hover answer nothing there either, and QA
|
||||
confirmed it on the real tree — so this is a *scope* question, not an
|
||||
inlay defect, and the §10 line is closed as investigated. 37.3 is a pure
|
||||
fast path (index-only Location equal to the file-read one over every
|
||||
encoding shape QA and the dev tried, 69× cheaper, no view created), with
|
||||
the honest exclusion of open buffers whose indexed spans may be stale.
|
||||
QA's two LOWs are noted, not actioned: `Tree::new` takes a per-test name
|
||||
and the existing names are distinct, and §6a's absolute numbers were
|
||||
measured on a different day's machine state — both servers agree with
|
||||
each other here, which is what the comparison needed.
|
||||
@@ -0,0 +1,455 @@
|
||||
# lint-config-contract
|
||||
|
||||
TODO §42. Repository-analysis finding 2, topology handshake 28.
|
||||
|
||||
## Goal
|
||||
|
||||
One lint-configuration contract for the two front ends. Before this round the
|
||||
CLI read a project's `[lint] select` / `ignore` out of `lucisv.toml` and the
|
||||
server did not: `enabled_rules` selected rules from `ClientSettings` alone,
|
||||
and `configured` discovered the same config file only to read its rule options
|
||||
and its line length. A team that checked in `select = ["no-tabs"]` therefore
|
||||
got one answer from CI and a different one from every editor in the project,
|
||||
and the docs had to say so. The server also *dropped* a `[lint.<rule>]` entry
|
||||
the registry refused (`let _ = options.set_raw(...)`) with nothing said, while
|
||||
the same mistake made in `lucisv.lint.options` was logged.
|
||||
|
||||
The contract, which is the CLI's today applied to the editor: **the editor's
|
||||
settings play the role the CLI's flags play.** `lucisv/src/lint.rs` picks the
|
||||
flag when one was given and the project file otherwise (`pick`); the server
|
||||
now picks `lucisv.lint.select` when it is non-empty and `[lint] select`
|
||||
otherwise, and the same for `ignore`, key by key. And a project entry that
|
||||
cannot be used is *said* — once per (config file, entry), in the words
|
||||
`lucisv check` fails the run with — rather than silently dropped.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A server cannot fail a run.** Everything the CLI treats as fatal (an
|
||||
unknown rule name, a rejected rule option, a waiver file that is not there
|
||||
or holds an unparsable directive) is here a dropped entry plus one log line.
|
||||
The buffer keeps being linted with everything that *was* understood. This is
|
||||
the standing rule of `lint.rs` and `settings::rule_options`, applied to the
|
||||
project file for the first time.
|
||||
- **Rungs 3 and 4 are the editor's alone.** `lucisv.lint.severity.<class>` and
|
||||
`lucisv.lint.rules.<name>` have no counterpart in `lucisv.toml` and none on
|
||||
the command line, so nothing about them changed. They still apply *over* a
|
||||
selection the project made, which is what "all style off except `no-tabs`"
|
||||
needs.
|
||||
- **One discovery per pass, no new file read.** `configured` already ran
|
||||
`Discovery::new(true).for_file(path)` once per `LintRun::for_document`;
|
||||
the project's selection is read out of the `FileConfig` that discovery
|
||||
already produced, so 42.1 costs zero stats and zero opens. The waiver files
|
||||
are now read in two calls instead of one (the project's paths, then the
|
||||
editor's) so a problem in the project's can be attributed to the
|
||||
`lucisv.toml` that named it — the same files, the same number of reads.
|
||||
- **The memo is keyed by (config path, message), re-armed by content.** The
|
||||
server has no "config generation": nothing invalidates on a `lucisv.toml`
|
||||
write, because the file is re-read on every pass. So `ProblemLog` stamps
|
||||
each config path with a hash of that file's lint-relevant content
|
||||
(`[lint] select`/`ignore`/`waivers` and every `[lint.<rule>]` entry) and
|
||||
clears that path's memo when the stamp moves. A user who edits the file and
|
||||
gets it wrong again is told again; a user who types in a `.sv` buffer is
|
||||
not told a hundred times. A problem in a *waiver file* named by an unchanged
|
||||
`lucisv.toml` is said once per session, which is the one edge the stamp does
|
||||
not see; it is a log line, not a diagnostic, and `lucisv check` is the place
|
||||
that fails over it.
|
||||
- **The memo lives behind a `RefCell`.** A lint pass runs behind `&self` — the
|
||||
pull models compute diagnostics inside a `map` over the open buffers — and
|
||||
the memo is the one thing a pass writes. `try_borrow_mut` with an early
|
||||
return, so no panic is reachable even if a future caller nests.
|
||||
- An unknown rule name in the project's lists is dropped rather than obeyed:
|
||||
see the Work log's "beyond the plan".
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed**
|
||||
|
||||
- `lucisv_core::config::{Discovery, FileConfig, LintOption}` — `lint_select`,
|
||||
`lint_ignore`, `lint_waivers`, `lint_options` (with `LintOption::line`) and
|
||||
`source`. Unchanged by this round; `source` and `line` are what let a server
|
||||
message name the file and line `lucisv check` names.
|
||||
- `vlog_linter::{rules_named, rule_by_name, all_rules, default_rules,
|
||||
workspace_rules, RuleOptions::set_raw, ExternalWaivers::{read, absorb}}` —
|
||||
unchanged. `set_raw`'s error text is reused verbatim, so the server's line
|
||||
and the CLI's are the same sentence.
|
||||
- `crate::settings::ClientSettings` — unchanged.
|
||||
|
||||
**Promised**
|
||||
|
||||
- `lint::enabled_rules` **changed signature**:
|
||||
`enabled_rules(&ClientSettings, &ProjectLint, has_oracle)`. The only caller
|
||||
outside the module's own tests was `LintRun::for_document`. A caller that
|
||||
wants the editor-only ladder passes `&ProjectLint::default()`.
|
||||
- `lint::LintRun::config_problems() -> &ConfigProblems` is new, and
|
||||
`server::diagnostics` is the one place that reports them. A future caller
|
||||
that builds a `LintRun` outside the diagnostics path (today: the code-action
|
||||
entry in `server/dispatch.rs`) says nothing, deliberately — one reporter, so
|
||||
the memo cannot be raced by two.
|
||||
- `lint::waiver_paths` keeps its signature and its behaviour (project paths
|
||||
first, then the editor's, resolved as before); `server::notification` still
|
||||
calls it with a default `FileConfig` to check the editor's alone.
|
||||
|
||||
**Requested of others (not done here)**
|
||||
|
||||
- `README.md`, `docs/site/src/content/docs/start/configuration.md` and
|
||||
`docs/repository-analysis.md` carry the old sentence. The replacement text
|
||||
is below, for the lead to apply at merge.
|
||||
- `docs/features/server-lint/README.md` line 228 still reads "Not done,
|
||||
deliberately: rule selection. No `lucisv.toml` `lint` key…", which was
|
||||
already stale before this round (the key landed in §33) and is now doubly
|
||||
so. Out of this lane's file set; flagged for the lead.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] 42.1 project selection into the ladder, editor-when-set-else-project
|
||||
- [x] 42.2 rejected project options logged with `<file>:<line>: <message>`,
|
||||
once per (config file, entry), the lint still running
|
||||
- [x] unit tests: the four-way table, severity words in the toml lists, the
|
||||
editor-only rungs over a project selection, the once-only log across
|
||||
three passes, the re-arm on an edited config
|
||||
- [x] e2e tests: the project selects / the editor replaces / an emptied
|
||||
setting hands it back; the rejected option logged once over the wire;
|
||||
the CLI and the server asserted equal for three configurations
|
||||
- [x] docs text for README / site / repository-analysis (below)
|
||||
- [ ] topo §2.9-28 struck (lead); finding 2 annotated (lead)
|
||||
- [x] QA
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-09-05 — dev (Opus 5)**
|
||||
|
||||
New module `crates/lucisv_server/src/lint/project.rs` (Rust 2018 lets
|
||||
`lint.rs` own a `lint/` directory), so nothing was added to `lint.rs`'s test
|
||||
block, which already dwarfs its 201 production lines. It holds `ProjectLint`,
|
||||
`ConfigProblems`, `ProblemLog` and their tests.
|
||||
|
||||
The ladder as implemented, in `lint::enabled_rules`:
|
||||
|
||||
1. base = `default_on`, plus the `needs_workspace` rules when `has_oracle`;
|
||||
2. `pick(lucisv.lint.select, [lint] select)` — the editor's list when it is
|
||||
non-empty, else the project's — **replaces** the base when it names
|
||||
anything;
|
||||
3. `lucisv.lint.severity.<class>` off **removes** that class (editor only);
|
||||
4. `lucisv.lint.rules.<name>` sets or clears one rule (editor only);
|
||||
5. `pick(lucisv.lint.ignore, [lint] ignore)` **removes**.
|
||||
|
||||
`pick` is a five-line twin of the CLI's, and rungs 2 and 5 are picked
|
||||
independently — a project that selects and a user who only ignores keep both
|
||||
halves. Every list takes a severity word wherever a rule name fits, the
|
||||
project's as much as the editor's, because both go through
|
||||
`vlog_linter::rules_named`.
|
||||
|
||||
`configured` now returns its problems instead of `let _`-ing them away, in
|
||||
`lucisv check`'s wording (`{file}:{line}: rule `{rule}` {error}` — the format
|
||||
string is `lucisv/src/lint.rs`'s `rule_options`, copied deliberately rather
|
||||
than shared, since the two crates are bins and neither can depend on the
|
||||
other). `for_document` reads the project's waiver files apart from the
|
||||
editor's and keeps the project's problems; the editor's are still said once by
|
||||
`notification::apply_settings`, so nothing is said twice.
|
||||
|
||||
`Server::report_config_problems` (in `server/diagnostics.rs`, on the one path
|
||||
that publishes) filters them through `ProblemLog` and logs the survivors as
|
||||
`lucisv: <file>:<line>: <message>; ignored` at `MessageType::WARNING` —
|
||||
`window/logMessage`, not `showMessage`: a typo in a checked-in config is not
|
||||
worth a popup on every editor in the project.
|
||||
|
||||
**Beyond the plan (one addition, deliberate).** `ProjectLint::read` also drops
|
||||
and reports a name in `[lint] select` / `ignore` that the registry does not
|
||||
know. The plan named only the rejected `[lint.<rule>]` entry and the bad
|
||||
waiver directive. The reason for adding it: `named()` skips an unknown word,
|
||||
so `select = ["no-tab"]` taken at face value resolves to *no rules at all* and
|
||||
blanks the file's squiggles, which reads as "lucisv is happy" rather than
|
||||
"lucisv could not read your config" — the same silent-drop failure §42.2
|
||||
exists to close, one line up. `lucisv check` fails the run over it; the server
|
||||
drops the name, says it once, and applies the rest of the list (a `select`
|
||||
left empty by the dropping falls back to the base set, which is the safe
|
||||
direction: some rules rather than none). The message has no line number,
|
||||
because `lucisv_core::config` records one per `[lint.<rule>]` entry and not
|
||||
per list element: `<toml>: [lint] select: unknown rule: no-tab`.
|
||||
|
||||
**Cost.** No new file read per diagnostics pass: the project selection comes
|
||||
out of the `FileConfig` the pass's single `Discovery` already produced, and
|
||||
the waiver files are the same files read the same number of times, just in two
|
||||
calls instead of one. The only new work per pass is a `DefaultHasher` over the
|
||||
config's `[lint]` entries (a handful of short strings) and a `HashMap` probe,
|
||||
both of which are skipped entirely when the config has no problems —
|
||||
`ConfigProblems::is_empty` returns before the memo is touched, which is every
|
||||
buffer in a project whose config is correct.
|
||||
|
||||
**Files touched** (all within the expected set):
|
||||
|
||||
- `crates/lucisv_server/src/lint/project.rs` (new)
|
||||
- `crates/lucisv_server/src/lint.rs`
|
||||
- `crates/lucisv_server/src/server/mod.rs` (the memo field)
|
||||
- `crates/lucisv_server/src/server/diagnostics.rs` (the one reporter)
|
||||
- `crates/lucisv_server/tests/e2e.rs` (three tests appended)
|
||||
- `TODO.md` (§42's own checkboxes)
|
||||
- this README
|
||||
|
||||
## Docs to apply at merge (lead)
|
||||
|
||||
### `README.md`, the two sentences at the end of the linter section (~line 432)
|
||||
|
||||
Replace:
|
||||
|
||||
> The server currently selects rules from `lucisv.lint.*` editor settings;
|
||||
> project `[lint] select/ignore` lists affect the CLI only. Project per-rule
|
||||
> options are read by both front ends.
|
||||
|
||||
with:
|
||||
|
||||
> Both front ends read the same configuration, and the editor's settings play
|
||||
> the role the CLI's flags play: `lucisv.lint.select` when it is set, else
|
||||
> `[lint] select` from the buffer's `lucisv.toml`, else the default set — and
|
||||
> the same for `ignore`, decided independently. `lucisv.lint.severity.*` and
|
||||
> `lucisv.lint.rules.*` have no project counterpart and apply over whichever
|
||||
> selection stands. Project per-rule options are read by both front ends. A
|
||||
> project entry lucisv cannot use — an unknown rule name in `[lint]
|
||||
> select`/`ignore`, a rejected `[lint.<rule>]` option, an unreadable waiver
|
||||
> file or a directive that does not parse — fails `lucisv check` with
|
||||
> `<file>:<line>: <message>` and exit 2; in an editor it is dropped, written
|
||||
> once to the lucisv log in the same words, and everything lucisv did
|
||||
> understand still lints the buffer.
|
||||
|
||||
Also, five lines above, the waiver sentence "a bad line in a file named by the
|
||||
editor setting is written once to the lucisv log, one named by `lucisv.toml`
|
||||
is not (run `lucisv check` to see it)" becomes:
|
||||
|
||||
> a bad line is written once to the lucisv log whether the file was named by
|
||||
> the editor setting or by `lucisv.toml`.
|
||||
|
||||
### `docs/site/src/content/docs/start/configuration.md`
|
||||
|
||||
The Keys table, rows 33–34 — the "Used by" column becomes "CLI and editor":
|
||||
|
||||
| `[lint].select` | string array | defaults | rule names or severity classes | CLI and editor |
|
||||
| `[lint].ignore` | string array | `[]` | rule names or severity classes | CLI and editor |
|
||||
|
||||
The "Editor settings" paragraph (~line 91) replaces:
|
||||
|
||||
> For lint selection, the server currently reads editor settings only. Project
|
||||
> `[lint] select/ignore` lists affect the CLI and are not inherited by the
|
||||
> server. Selection proceeds through defaults → select → severity switches →
|
||||
> per-rule toggles → ignore. Editor rule options overlay project rule options
|
||||
> key by key. Invalid editor options are logged and dropped. Invalid project
|
||||
> rule-option entries are currently dropped by server linting without a
|
||||
> per-entry log; `lucisv check` reports them as configuration errors.
|
||||
|
||||
with:
|
||||
|
||||
> For lint selection, the editor's settings play the role the CLI's flags
|
||||
> play. Selection proceeds through defaults → select → severity switches →
|
||||
> per-rule toggles → ignore. `select` is `lucisv.lint.select` when that
|
||||
> setting is non-empty and the project's `[lint] select` otherwise; `ignore`
|
||||
> is decided the same way and independently. The severity switches and
|
||||
> per-rule toggles are editor-only — a `lucisv.toml` has no such keys — and
|
||||
> apply over whichever selection stands. Editor rule options overlay project
|
||||
> rule options key by key. An entry that cannot be used is dropped and logged
|
||||
> once per configuration file and entry, in the same `<file>:<line>:
|
||||
> <message>` wording `lucisv check` fails with: an invalid editor option, an
|
||||
> invalid `[lint.<rule>]` entry, an unknown rule name in `[lint]
|
||||
> select`/`ignore`, or an unreadable waiver file. `lucisv check` treats each
|
||||
> of these as a configuration error and exits 2; the server keeps linting with
|
||||
> the entry dropped.
|
||||
|
||||
The Discovery section (~line 57) sentence "A bad configuration is an error for
|
||||
the CLI, preventing partial writes. In an editor, the server reports the
|
||||
problem and falls back to the next available setting." is still true and needs
|
||||
no change.
|
||||
|
||||
### `docs/repository-analysis.md`, finding 2
|
||||
|
||||
Replace the "The docs now describe the implemented behavior…" paragraph with a
|
||||
fix note in the shape finding 1 already uses:
|
||||
|
||||
> **Fixed by TODO §42 (0.43.0, 2026-09-05):** `enabled_rules` now takes the
|
||||
> project's selection beside the editor's and picks the editor's list when it
|
||||
> is non-empty, the project's otherwise, key by key — the CLI's `pick` applied
|
||||
> to the editor. Rejected project entries are logged once per (configuration
|
||||
> file, entry) as `<file>:<line>: <message>`, the wording `lucisv check` fails
|
||||
> with, and the buffer is still linted with the entry dropped. Pinned by
|
||||
> `lint::project`'s four-way table test and by three wire-level tests in
|
||||
> `crates/lucisv_server/tests/e2e.rs`, one of which asserts the CLI's and the
|
||||
> server's rule lists equal for three configurations. See
|
||||
> `docs/features/lint-config-contract/README.md`.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-09-05 — QA (Sonnet)**
|
||||
|
||||
Read the plan (TODO §42), the finding/handshake it answers (repository-
|
||||
analysis finding 2, `docs/topo.md` §2.9-28), and this feature's README in
|
||||
full, including the "beyond the plan" deviation (unknown rule names in
|
||||
`[lint] select`/`ignore` dropped and logged) and the waiver-file edge
|
||||
(memo keyed by the toml's stamp, not the waiver file's). Read the diffs of
|
||||
`lint.rs`, the new `lint/project.rs`, `server/diagnostics.rs`,
|
||||
`server/mod.rs`, and the three tests appended to `tests/e2e.rs`, and the
|
||||
CLI's own `lucisv/src/lint.rs` (`pick`, `rule_options`) and
|
||||
`vlog_linter::registry::select_rules`/`rules_named` for the wording and
|
||||
precedence this feature is required to mirror.
|
||||
|
||||
Built `cargo build --release -p lucisv -p lucisv_server` once. Wrote a
|
||||
throwaway attack suite as extra `#[test]` functions appended to
|
||||
`crates/lucisv_server/tests/e2e.rs` (never committed to the dev's file —
|
||||
removed before this pass ends; verified by `git diff --stat` matching the
|
||||
dev's original 205-line insertion both before and after), driving the real
|
||||
server binary over framed JSON-RPC, plus one wire-level test against a real
|
||||
file copied read-only out of opentitan (`hw/ip/aes/dv/tb/tb.sv`, no write).
|
||||
Two attack tests needed a raw child process with an explicit read/write
|
||||
interleaving (rather than `talk()`'s single write-then-read-to-EOF) to test
|
||||
disk-edit timing without a race, and to drive a `hover` request as a
|
||||
synchronization barrier between passes — documented inline while they
|
||||
existed; removed with the rest.
|
||||
|
||||
**Verified, all as specified:**
|
||||
|
||||
- The four-way matrix {toml select ∅/set, editor select ∅/set} ×
|
||||
{toml ignore ∅/set, editor ignore ∅/set} over the wire, using a buffer
|
||||
with findings in all three severities (`no-tabs`/`no-trailing-whitespace`/
|
||||
`line-length` = style, `unused-signal`/`undriven-net` = warning,
|
||||
`duplicate-declaration` = error) rather than the unit test's two rules —
|
||||
every cell matches the documented ladder, and select/ignore are confirmed
|
||||
decided **independently** (a project select plus a project ignore both
|
||||
apply when the editor names neither).
|
||||
- Severity words in the toml's lists (`select = ["style"]`,
|
||||
`ignore = ["style"]`), including mixed with a rule name in the same list.
|
||||
- Rungs 3/4 (editor-only class switch, per-rule toggle) apply over a project
|
||||
selection, including the per-rule word beating the class word (note: the
|
||||
editor's `rules.<name>` setting takes the **string** `"on"`/`"off"`, not a
|
||||
JSON boolean — confirmed against `settings.rs`'s `rule_toggles` after an
|
||||
initial test mistake).
|
||||
- `didChangeConfiguration` transitions: editor `select` set then cleared
|
||||
restores the project's; same, independently, for `ignore`.
|
||||
- Nested `lucisv.toml`s: an outer and an inner buffer in one workspace each
|
||||
follow their own nearest config file. (First attempt used identical
|
||||
buffer text in both files and got `[]` for the inner buffer — not a
|
||||
product bug: the shared file-scope oracle correctly saw the identically-
|
||||
named `unused-signal` candidate declared in the other indexed file and
|
||||
suppressed it, `docs/features/semantic-lints-on/README.md`'s documented
|
||||
false-negative-safe direction. Fixed by giving each file's declarations
|
||||
distinct names.)
|
||||
- An unknown rule name in `[lint] select`: dropped, logged once
|
||||
(`<toml>: [lint] select: unknown rule: no-tab`), the rest of the list
|
||||
still applies, and the buffer keeps being linted — confirmed against
|
||||
`lucisv check` on the identical config, which exits 2 and prints the same
|
||||
`unknown rule: no-tab` wording before failing the run. The two front
|
||||
ends' *reactions* differ by design (a server cannot fail a run); their
|
||||
*diagnosis* of the same mistake does not.
|
||||
- A rejected `[lint.<rule>]` option (`length = "wide"`): exactly one
|
||||
`window/logMessage` across five `didChange` passes over the same bad
|
||||
config; the message's core (`<toml>:<line>: rule `<rule>` <detail>`) found
|
||||
verbatim inside `lucisv check`'s own stderr on the identical config (the
|
||||
CLI prepends `error: `, which the server's log line has no equivalent
|
||||
of — compared by substring, not equality, for that reason); the buffer
|
||||
still linted with the entry dropped. Edited live to a *different* bad
|
||||
value (`length = "-1"`) mid-session: logged again, once. Then fixed
|
||||
(`length = 100`): silence from there on. (This needed the raw
|
||||
read/write-interleaved harness — a `talk()` one-shot builds the whole
|
||||
session string, `std::fs::write`s included, before the server is even
|
||||
spawned, so every edit would already be on disk before anything runs;
|
||||
used a `hover` request after each edit as a synchronization barrier,
|
||||
since `Server::answer_request` flushes the dirty buffer before answering
|
||||
any request.)
|
||||
- A bad directive in a waiver file named by `[lint] waivers`: logged once,
|
||||
naming the **waiver file's own** path and line, not the toml's.
|
||||
- Extra probe beyond the plan, for the README's stated waiver/toml-stamp
|
||||
edge: fixed the waiver file, then brought back the **exact same** bad
|
||||
line, toml untouched throughout — not logged a second time, confirming
|
||||
the memo really is keyed by exact message text under an unchanged toml
|
||||
stamp, not merely "one waiver problem per session" in some coarser sense.
|
||||
Contrast: two *different* bad lines in the same unedited-toml waiver file
|
||||
during one session are each logged once (not suppressed by the first) —
|
||||
consistent with `ProblemLog`'s `BTreeSet<String>` keyed by message text,
|
||||
not a defect, but worth the lead/dev knowing the precise grain the
|
||||
"once per session" sentence in Assumptions describes.
|
||||
- CLI/server rule-set equality: five configurations (none, an explicit
|
||||
select, `select=["style"]` + one ignored, `ignore=["style"]`, a select
|
||||
containing an unknown name) plus one real file copied read-only out of
|
||||
opentitan (`hw/ip/aes/dv/tb/tb.sv`, no `lucisv.toml` in that repo, so a
|
||||
scratch one governed the copy) — server and CLI rule-code sets equal in
|
||||
every case.
|
||||
- Robustness: `select = []` (explicit empty) falls back to the base set,
|
||||
same as absent; duplicate names in `select` collapse harmlessly; a name
|
||||
in both `select` and `ignore` ends up ignored (ignore is the top rung); a
|
||||
`[lint]` key the parser rejects outright fails `parse()` entirely, which
|
||||
the CLI turns into an exit-2 run failure and the server (via the
|
||||
pre-existing `.ok()` fallback in `configured`, **unchanged by §42**)
|
||||
swallows into defaults across several passes with **zero** log lines —
|
||||
confirmed it does not newly start logging under this feature.
|
||||
- Performance: 20 consecutive diagnostics passes over a 2000-line buffer
|
||||
with a valid config, this server against a 0.42.0 server built in a
|
||||
scratch worktree (`git worktree add .../scratchpad/base v0.42.0`, removed
|
||||
with `git worktree remove` before finishing). Three runs: ratios 0.985,
|
||||
1.001, 0.983 (new server negligibly faster or equal, never slower) — no
|
||||
measurable regression, as the README's cost analysis claims.
|
||||
- Gates, guarded: `cargo clippy --all-targets` clean; `cargo test
|
||||
--workspace` — **3780 passed, 0 failed** (matches the dev's count
|
||||
exactly); `tools/corpus_check.sh` — **814/820 (99.3%)**, the same six
|
||||
pre-existing parse errors; `node editors/vscode/smoke.js
|
||||
target/release/lucisv-server` — OK.
|
||||
- `git -C /Users/guoliangchen/repo/opentitan status --porcelain` after use:
|
||||
unchanged, the same three pre-existing modified files
|
||||
(`hw/ip/aes/dv/tb/tb.sv`, the two `ast.sv`s) as before this session — no
|
||||
`lucisv.toml` was written there.
|
||||
|
||||
**Findings.**
|
||||
|
||||
- **LOW, pre-existing, not introduced by §42** — a `didChange` sent in the
|
||||
same message burst as `shutdown` is never flushed: `lsp_server::
|
||||
Connection::handle_shutdown` (called from
|
||||
`crates/lucisv_server/src/server/mod.rs`'s `process_batch`) answers
|
||||
shutdown directly, bypassing `Server::answer_request`'s `flush_dirty()`.
|
||||
A dirty buffer's last edit is silently dropped — no republish, no
|
||||
config-problem log for that pass — if the client shuts down before the
|
||||
150ms `CHANGE_DEBOUNCE` fires or before another request arrives. This
|
||||
interacts with §42's own "a `lucisv.toml` edited on disk takes effect at
|
||||
the next publish" claim: that claim holds only when *some* republish
|
||||
actually happens before the session ends, which is not the same as
|
||||
saying the edit's diagnostics are guaranteed to reach the client at all
|
||||
in a fast open-edit-shutdown session. Reproduced in the (removed) attack
|
||||
test by sending a `didChange` immediately before `shutdown` in one write
|
||||
and observing zero further publishes; fixed the test by sleeping past
|
||||
the debounce instead of treating it as a §42 bug, since the behavior
|
||||
predates this feature and is a property of the `lsp-server` crate's own
|
||||
shutdown handling, not of anything `lint.rs`/`lint/project.rs` changed.
|
||||
Not a §42 regression; flagging for whoever owns `change-debounce` next.
|
||||
- **LOW, pre-existing, not introduced by §42** — an unknown name in the
|
||||
*editor's* `lucisv.lint.select`/`ignore` is silently dropped at
|
||||
settings-parse time (`crates/lucisv_server/src/settings.rs`'s `rules`,
|
||||
called from `from_payload`), with no log line — unlike `lucisv.lint.
|
||||
options`, whose rejected entries are logged (`lint_option_warnings`).
|
||||
§42 makes the *project* side of the same mistake (`[lint] select`/
|
||||
`ignore` in `lucisv.toml`) both dropped and logged (the "beyond the
|
||||
plan" addition in the Work log), which is more informative than the
|
||||
editor's own settings for the identical typo. Not this feature's
|
||||
handshake to fix (`ClientSettings` is unchanged by §42) and not asked
|
||||
for by the plan, but the asymmetry is now sharper than before this
|
||||
round landed; worth a line in the lead's notes for a future pass over
|
||||
`settings.rs`.
|
||||
- No correctness, idempotency, or comment-preservation issues found; no
|
||||
masked-corruption concern applies (this feature touches lint
|
||||
configuration, not `verify.rs`'s forgiveness).
|
||||
|
||||
**Verdict: PASS.** No blocking findings. The two LOW findings above are
|
||||
pre-existing behavior outside this feature's stated handshakes, not
|
||||
regressions introduced by §42; recorded for whoever picks them up next.
|
||||
Ticked TODO §42's QA checkbox and this feature's own `Status / TODO`
|
||||
"QA" line.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-05 — lead.** Accepted; ships in 0.43.0. The contract is the ruled
|
||||
one and it is now the same sentence on both front ends: the editor's list
|
||||
when set, else the project's, key by key, with the editor-only rungs applied
|
||||
over whichever stands — and the wire-level equality test is what makes that
|
||||
a fact rather than a description. The dev's one step beyond the plan
|
||||
(dropping and logging an unknown rule name in a project list) is accepted:
|
||||
an editor cannot fail the run, and a typo that silently resolves to "no
|
||||
rules" reads as a clean file, which is the wrong kind of quiet. The
|
||||
once-only memo keyed by config content is the right shape for a server with
|
||||
no config generation; its stated edge (a waiver file's bad line under an
|
||||
unchanged toml is said once per session) is acceptable and documented. QA's
|
||||
two LOWs are pre-existing and out of scope; the second — an unknown name in
|
||||
the *editor's* `lucisv.lint.select` still silently dropped — is worth a line
|
||||
in a later round and is filed in topo §2.9 as item 29. Docs applied to
|
||||
README, the linter guide, configuration.md, the analysis and topo.
|
||||
@@ -0,0 +1,415 @@
|
||||
# parser-skips
|
||||
|
||||
## Goal
|
||||
|
||||
Close the two parser skips TODO §11 left open after the opentitan sweep —
|
||||
the last two shapes in that sweep that were grammar work rather than
|
||||
"not SystemVerilog".
|
||||
|
||||
1. **Rival unit headers in a conditional region** (`jtag_if.sv`). One
|
||||
`interface` header written twice across the arms of an
|
||||
`` `ifdef ``/`` `else `` region, both spellings bracket-*balanced*:
|
||||
|
||||
```verilog
|
||||
`ifdef GATE_LEVEL
|
||||
interface jtag_if #(parameter int unsigned P = 41_664) ();
|
||||
`else
|
||||
interface jtag_if #(parameter int unsigned P = 20_000) ();
|
||||
`endif
|
||||
wire tck;
|
||||
…
|
||||
endinterface
|
||||
```
|
||||
|
||||
Before this round the first header parsed in full, the `` `else `` became
|
||||
a directive item of its body, the second `interface jtag_if` became a
|
||||
*nested* interface, and the outer one ran out of file: `163:1: expected
|
||||
`endinterface``. `directive-split`'s trigger never fired, because nothing
|
||||
errored until EOF and neither arm left a bracket open. Now the body loop
|
||||
recognises the rival before it parses the item, fails there, and the
|
||||
existing conditional-split recovery turns the **whole unit** into one
|
||||
`ItemKind::Verbatim` item — the same treatment a bracket-unbalanced split
|
||||
header has had since `directive-split`.
|
||||
|
||||
2. **A net delay written after the type** (`SimDTM.sv`). IEEE 1800 §6.7 puts
|
||||
`delay3` after the data type — `wire [31:0] #0.1 x = y;` — and lucisv
|
||||
parsed it only between the net keyword and the type. `DataDecl::delay`
|
||||
now carries the position it was written in and the formatter prints it
|
||||
there. No normalisation: moving a delay across the type reorders tokens,
|
||||
which `verify.rs` rightly refuses.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A rival header is a fragment, the way an unclosed bracket is.** Two
|
||||
bracket-balanced spellings of one header sharing one body are not a tree
|
||||
any more than two heads sharing one `{` are: there is no AST for "either
|
||||
this header or that one". So the unit joins the verbatim bucket rather
|
||||
than getting a layout. **The standing trade is `directive-split`'s**
|
||||
(README → Goal, and Status → "any canonical *layout* for the inside of a
|
||||
split region — it stays byte-for-byte"): the captured bytes come back
|
||||
exactly as written, so the unit's **body is not formatted**. For
|
||||
`jtag_if.sv` that means the file's one visible change is the block's own
|
||||
re-indent — `Fmt::raw_lines` dedents every line by the head's column, so a
|
||||
unit written two spaces in comes back at column 1 with its *relative*
|
||||
layout intact (`directive-split` README → Assumptions, "a verbatim block's
|
||||
relative layout is what survives"). `--check` therefore says "would
|
||||
reformat", not "unchanged".
|
||||
|
||||
- **The rival trigger is five conditions at once**, and every one of them is
|
||||
read from the tokens — never from a flag someone could set by mistake:
|
||||
|
||||
1. the cursor stands on a `` `else `` / `` `elsif ``;
|
||||
2. a conditional region was open at the unit's own first token
|
||||
(`open_conds > 0` there);
|
||||
3. that region is still the live one — nothing opened inside the body is
|
||||
still open (`open_conds` is back to the header's value) **and** the
|
||||
header's own region was never closed inside the body (the body's
|
||||
lowest nesting never dipped below it). Without the second half, a body
|
||||
that closes the outer region and opens another would present a
|
||||
`` `else `` that continues the *new* region at the same count;
|
||||
4. the token after the directive is the unit's own keyword;
|
||||
5. the token after that is the unit's own name.
|
||||
|
||||
- **The evidence is re-derived at the split, not carried on the error.**
|
||||
`ParseError` is a public struct with three public fields and no room for a
|
||||
flag; adding one would touch every construction site in the crate and give
|
||||
every error path a way to reach the recovery. `Parser::rival_end_kw` reads
|
||||
the same shape back out of `ItemMark::pos` and the cursor instead, which
|
||||
is exactly how the other three conditions of `at_split_conditional` are
|
||||
already checked. Cost: the shape is spelled twice (`at_rival_header` for
|
||||
the body loop, `rival_end_kw` for the split). Benefit: the whole trigger
|
||||
stays in one file and is provable from the token stream alone.
|
||||
|
||||
- **The extent scan ends at the unit's closing keyword.** A unit header's
|
||||
own `;` closes only the header, so the `;` rule `scan_split_extent` has
|
||||
always used would have ended the block at the first body declaration.
|
||||
With `unit_end = Some(kw)` the scan runs to the matching `endmodule` /
|
||||
`endinterface` / `endprogram`, counting units of the same kind so one
|
||||
nested in the body cannot end it early, and swallowing an
|
||||
`endinterface : name` label the way the opening split already does.
|
||||
An `interface class` nested inside a captured `interface` closes with
|
||||
`endclass`, leaves the unit count above zero and makes the scan give up —
|
||||
the parse error stands, which is the safe side of the trade.
|
||||
|
||||
- **Both delay positions, never both at once.** `wire #5 [31:0] #6 x;` is a
|
||||
parse error naming the rule. Only a *net* declaration reads a delay in
|
||||
either position, so `logic #5 x;` and `logic [7:0] #5 x;` are the ordinary
|
||||
syntax errors they always were.
|
||||
|
||||
- **A comment written directly in front of the `#` has no slot.** It is
|
||||
refused by `verify.rs` (token reorder), for the after-type position and
|
||||
for the before-type position alike. That is **pre-existing** — the
|
||||
before-type spelling has behaved this way since the delay was first
|
||||
parsed — and the new position inherits it unchanged. Recorded as a `#SKIP`
|
||||
case in `net_delay_position.cases`, not fixed: giving the delay a comment
|
||||
slot is a `comment-slots` change. **Closed by walk-cycles (TODO §43.2),
|
||||
2026-09-05:** `NetDelay::{before_hash, after_hash}`; the `#SKIP` is live. The other gaps around a delay (an
|
||||
attribute in front of the declaration, a comment after the delay) do
|
||||
round-trip.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### Consumed
|
||||
|
||||
- `Parser::split_conditional_item` / `capture_split` / `verbatim_since` /
|
||||
`Fmt::raw_lines` — the `directive-split` recovery and its verbatim
|
||||
printer, used unchanged. `ItemKind::Verbatim` gains no new producer: the
|
||||
same call in `parse_item_inner` produces it.
|
||||
- `Parser::open_conds` and `ItemMark::conds` — the item-scope conditional
|
||||
nesting `directive-split` maintains in `note_item_conditional`. Read, not
|
||||
written, by the rival path; the one write is the existing
|
||||
`self.open_conds = conds_after` in `split_conditional_item`.
|
||||
- `Parser::parse_delay_value` (`parser/instance.rs`) — reads `#5`, `#0.1`
|
||||
and `#(1:2:3)`. Used unchanged for both positions.
|
||||
|
||||
### Promised / changed for others
|
||||
|
||||
- **`at_split_conditional`'s fourth condition widened**, from "the arm left
|
||||
a bracket open" to "the arm left a bracket open **or** the arm behind the
|
||||
directive re-writes this item's own unit header". Recorded in
|
||||
`docs/features/directive-split/README.md` → Status. Everything that
|
||||
refused before still refuses; the three negatives are pinned as tests.
|
||||
- **`scan_split_extent` gained a second parameter**, `unit_end:
|
||||
Option<&str>`. `None` is byte-identical to the old behaviour and is what
|
||||
every pre-existing caller path passes.
|
||||
- **`DataDecl::delay` changed type**, `Option<Expr>` → `Option<NetDelay>`
|
||||
where `NetDelay { expr: Expr, after_type: bool }`. Two readers existed in
|
||||
the whole workspace and both were one-line changes
|
||||
(`vlog_formatter/src/format/decl.rs`, `vlog_semantic/src/bind/decl.rs`),
|
||||
so the struct was preferred over a second `DataDecl` field: it makes
|
||||
"after_type set with no delay" unrepresentable, at no cost to consumers.
|
||||
- **`verify.rs` is untouched.** No normalization was added and no
|
||||
forgiveness widened. Both halves of this round are the *opposite* of
|
||||
forgiveness — the delay is printed where it was written precisely so the
|
||||
token order the safety net compares is unchanged, and a verbatim block is
|
||||
re-lexed as ordinary tokens on both sides.
|
||||
- **`ast::size_pins` still green, unchanged.** It pins `Expr`, `Stmt` and
|
||||
`StmtKind`; `NetDelay` adds a `bool` to `DataDecl`, which none of the
|
||||
three contains.
|
||||
|
||||
### Requests to other clusters
|
||||
|
||||
- **`comment-slots`**: a net delay has no slot for the comment written
|
||||
immediately in front of its `#`, so such a file is refused by the safety
|
||||
net rather than reformatted. Pre-existing, both positions, recorded as a
|
||||
`#SKIP` case (see Assumptions). **Answered by walk-cycles (TODO §43.2),
|
||||
2026-09-05.**
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] 38.1 rival-header detection in `parse_module`'s body loop
|
||||
(`parser/module.rs`), `at_rival_header` / `rival_end_kw` / `opens_unit`
|
||||
and the widened trigger (`parser/split.rs`), the keyword-ended extent
|
||||
scan.
|
||||
- [x] 38.1 tests: the four header spellings, both modes' trees equal,
|
||||
comments kept, a unit nested in a captured body, the three negatives —
|
||||
`parser/tests/split.rs`; four formatter cases including the real
|
||||
`jtag_if.sv` in full — `tests/cases/rival_headers.cases`.
|
||||
- [x] 38.2 `NetDelay` with its position (`ast/decl.rs`), `parse_net_delay`
|
||||
for either side and the both-sides error (`parser/decl.rs`),
|
||||
`Fmt::net_delay` printing it where it was written
|
||||
(`format/decl.rs`), the one consumer update (`bind/decl.rs`).
|
||||
- [x] 38.2 tests: both positions and their spans, both-at-once refused, only
|
||||
a net reads one — `parser/tests/decl.rs`; five formatter cases
|
||||
including the real `SimDTM.sv:38-41` — `tests/cases/net_delay_position.cases`.
|
||||
- [x] docs: this README; §11's two lines and §38's checkboxes ticked in
|
||||
`TODO.md`; the `directive-split` cross-reference.
|
||||
- [x] Gates (guarded): `cargo fmt -p` on the three touched crates, clippy
|
||||
`--all-targets` clean, `cargo test --workspace` 3 744 passed / 0
|
||||
failed, `tools/corpus_check.sh` 814/820 with the same six failures,
|
||||
both opentitan files through `format --check`.
|
||||
- [ ] **Not done, deliberately:** a rival header whose two arms spell the
|
||||
keyword differently (`module` in one arm, `macromodule` in the other);
|
||||
a rival written across three or more arms where the *name* differs in
|
||||
one of them; any layout for the inside of a captured unit. Each is
|
||||
refused, not mis-parsed.
|
||||
- [x] QA. Verdict: PASS. See QA log (2026-09-04).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-04 — dev
|
||||
|
||||
**38.1, the rival header.** Read `parse_module`, `split.rs` and
|
||||
`directive-split`'s README first. The failure the plan describes is real and
|
||||
reproduced on trunk grammar: with both arms bracket-balanced, nothing errors
|
||||
until the outer unit reaches EOF, so `at_split_conditional` — which is only
|
||||
ever consulted from `parse_item_inner`'s `Err` arm — never sees a cursor on
|
||||
the `` `else ``.
|
||||
|
||||
Detection went into `parse_module`'s body loop, before `item_or_recover`, as
|
||||
the plan asked. `parse_module` now records `open_conds` at its own first
|
||||
token and tracks the lowest nesting the body has reached (`UnitHead::floor`);
|
||||
the check itself, `Parser::at_rival_header`, lives in `split.rs` beside the
|
||||
rest of the trigger, so `module.rs` grew by twelve lines and stayed at 635.
|
||||
|
||||
Routing: **a dedicated check beside the bracket one**, not a flag on the
|
||||
error. `ParseError` is public with three public fields; a fourth would be an
|
||||
API change touching every construction site, and a flag is a thing an
|
||||
unrelated error path can set. `rival_end_kw` re-derives the shape from
|
||||
`ItemMark::pos` and the cursor — which is how the trigger's other three
|
||||
conditions are already checked — and returns the unit's closing keyword,
|
||||
which the extent scan then needs anyway. So the one helper both widens the
|
||||
trigger and steers the scan.
|
||||
|
||||
`scan_split_extent` took an `Option<&str>` closer. With `None` it is the old
|
||||
function byte for byte. With `Some`, it ends at the matching closing keyword
|
||||
(past an `endinterface : name` label) instead of at a `;`, counting units of
|
||||
the same kind so a module nested in the captured body cannot end it early —
|
||||
pinned by `a_unit_nested_in_a_captured_body_does_not_end_the_scan_early`.
|
||||
|
||||
The three negatives the plan named are each a test, and each is refused by a
|
||||
*different* condition: a region opened inside the body fails condition 3 (or
|
||||
2, when nothing was open around the unit at all); a different name after the
|
||||
`` `else `` fails condition 5; a region closed before the header fails
|
||||
condition 2. A fourth shape — a body that closes the header's region and
|
||||
opens another, which leaves the *count* equal — is what `floor` is for, and
|
||||
is the second half of `a_region_closed_before_the_header_leaves_the_else_stray`.
|
||||
|
||||
The real file: `hw/dv/sv/jtag_agent/jtag_if.sv` parses, formats, is
|
||||
idempotent, keeps all 34 of its comments and comes back at the same 162
|
||||
lines. Its one change is the verbatim block's dedent (the unit was written
|
||||
two spaces in). It is in `rival_headers.cases` in full, input and output, so
|
||||
the harness proves the idempotency and the byte-identity of the body on the
|
||||
actual bytes rather than on a paraphrase.
|
||||
|
||||
One deviation worth naming: the comment written between the `` `ifdef `` and
|
||||
the header (`// jtag interface with default 24MHz tck for GLS`) is **not**
|
||||
inside the verbatim block — the capture starts at the item's first token, so
|
||||
it is the item's own leading comment, exactly as in every other split. It is
|
||||
printed, not dropped; the test asserts where it lands.
|
||||
|
||||
**38.2, the net delay.** `NetDelay { expr, after_type }` rather than two
|
||||
`DataDecl` fields: with only two readers in the workspace, both one-line
|
||||
either way, the struct wins because it cannot represent "after_type set with
|
||||
no delay". The parser reads the delay through one helper called twice, once
|
||||
on each side of `parse_opt_data_type`, and `(Some, Some)` is an error naming
|
||||
the rule. The formatter's `Fmt::net_delay` prints the delay only on the side
|
||||
it was written on; nothing is normalised, so both spellings round-trip byte
|
||||
for byte and `verify.rs` sees the token order it was given.
|
||||
|
||||
`SimDTM.sv` now parses; its diff is ordinary layout (the DPI header, the
|
||||
port list, an `else begin`), and the four `#0.1` wire lines come back
|
||||
untouched. `ast::size_pins` is unchanged and green: it pins `Expr`, `Stmt`
|
||||
and `StmtKind`, none of which holds a `DataDecl`.
|
||||
|
||||
**Found, not fixed:** a comment written directly in front of a delay's `#`
|
||||
has no slot, so the file is refused by the safety net. It behaves identically
|
||||
in the *pre-existing* before-the-type position, so this is not a regression
|
||||
of this round; recorded as a `#SKIP` case and as a handshake request to
|
||||
`comment-slots`.
|
||||
|
||||
**Files touched outside the plan's expected set:**
|
||||
`docs/features/directive-split/README.md` (one Status bullet, the
|
||||
cross-reference §38 asked for) and this README. Nothing else.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-04 — QA
|
||||
|
||||
Read `TODO.md` §38 and this README (Goal/Assumptions/Handshakes/Work log) in
|
||||
full, then the diffs of every touched file and both new `.cases` files. Built
|
||||
`target/release/lucisv` (release) from the dev's tree; the 0.41.0 baseline
|
||||
binary was already cached at `~/.cache/lucisv-baselines/`, so no scratch
|
||||
worktree was needed.
|
||||
|
||||
**38.1, rival headers.** Traced `at_rival_header` / `rival_end_kw` /
|
||||
`scan_split_extent` by hand against the token stream: the extent scan's
|
||||
else-if chain disables the `;` terminator whenever `unit_end` is `Some`
|
||||
(confirmed by reading the branch order), `opens_unit` is keyed to the failed
|
||||
unit's own closing keyword so a nested unit of a *different* kind never
|
||||
touches the counter, and a same-kind-but-different-closer nested unit
|
||||
(`interface class … endclass`) leaves the counter stuck above zero and makes
|
||||
the scan give up — the parse error stands, as documented.
|
||||
|
||||
Attacked with `target/release/lucisv format --stdout` (a Rust-level
|
||||
strict/tolerant-parity and comment-preservation pass was already covered by
|
||||
the dev's own `parser/tests/split.rs` additions, which I re-ran rather than
|
||||
duplicating):
|
||||
- Header spellings: `interface`, `module`, `program`; with and without
|
||||
`#(...)`; `()`, a real port list, and no port list; three arms
|
||||
(`ifdef`/`elsif`/`else`, all three rival); a comment directly before the
|
||||
rival header in the `else` arm; the region's own `` `endif `` written after
|
||||
the body's first item; rival arms with *different* `#(...)` lengths; a
|
||||
`module` nested inside a captured `interface` body (does not end the scan
|
||||
early); an `end : label` inside the body; `endinterface : jtag_if`. All
|
||||
parse, format unchanged (0 diff from input), and are idempotent.
|
||||
- The three plan negatives, plus the "region closed and a new one opened at
|
||||
the same count" fourth shape the dev's `floor` field targets — all four
|
||||
stay `expected end<kw> (found "<eof>")` parse errors, never a Verbatim.
|
||||
- Termination: an unterminated rival (no `endinterface` at all) and a rival
|
||||
whose `` `endif `` is the last token in the file both surface the original
|
||||
`rival header for … in a conditional region` parse error (the extent scan
|
||||
finds no closer, so it returns `None` and the original error stands) — no
|
||||
corruption, no panic, no silent accept.
|
||||
- A rival shape nested inside `generate … if (1) begin … end … endgenerate`:
|
||||
parses, is idempotent, and reindents only the verbatim block's own base to
|
||||
the surrounding column (relative layout preserved) — an odd but
|
||||
non-corrupting result; not a shape the plan named, recorded here as a
|
||||
curiosity rather than a finding since nothing breaks.
|
||||
- Three additional attempts at over-widening `at_split_conditional`'s fourth
|
||||
condition, per the QA brief: (1) a real syntax error inside the body,
|
||||
unrelated to any header, immediately followed by an `else`/rival-shaped
|
||||
arm; (2) the header parses fully and the *next* declaration errors right
|
||||
before a rival-shaped `else`; (3) a rival-shaped arm one nesting level
|
||||
*outside* the item that actually failed (nested units). All three stay
|
||||
ordinary parse errors — `rival_end_kw` reads `mark.pos`, the position of
|
||||
the item that actually failed, and returns `None` whenever that token is
|
||||
not the unit's own keyword+name, so none of the three ever reaches the
|
||||
split. The trigger does not over-fire.
|
||||
- "Not done, deliberately" claims verified directly: a keyword mismatch
|
||||
across arms (`macromodule` vs `module`) and a three-arm rival with one
|
||||
wrong name both stay the pre-existing `expected endmodule (found <eof>)`
|
||||
error, not a mis-parse.
|
||||
- The real file (`hw/dv/sv/jtag_agent/jtag_if.sv`, read via `--stdout` only):
|
||||
idempotent; 162 lines in and out; all 34 `//` comments present, 0 `/*`
|
||||
comments in either (matches); the only diff from the source is the
|
||||
verbatim block's dedent, confirmed with `diff` — every other line
|
||||
byte-identical. Matches the dev's account exactly.
|
||||
- `rival_headers.cases`: read start to finish, including the copied
|
||||
`jtag_if.sv` case — its input half diffs clean against the read-only
|
||||
opentitan file.
|
||||
|
||||
**38.2, net delay.** Attacked before/after positions for `wire`, `tri`,
|
||||
`wand`, `supply0`, and a `logic`-typed net (`wire logic #2 x;`); packed
|
||||
dims; `signed`; delay forms `#5`, `#(1:2:3)`, `#0.1`, `#1ns`; both positions
|
||||
at once (`a net delay is written before or after the type, not both` —
|
||||
matches the plan's message); a delay on `reg`/`logic` variable declarations
|
||||
(ordinary `expected identifier (found "#")` syntax errors, exactly the
|
||||
pre-§38.2 behavior — not net declarations, so `parse_net_delay`'s `is_net`
|
||||
gate correctly refuses). `wire vectored [3:0] x;` (no delay) also errors on
|
||||
both the new binary and the 0.41.0 baseline identically — a pre-existing,
|
||||
unrelated gap (`vectored` net-decl qualifier is not parsed at all), not a
|
||||
regression of this round.
|
||||
|
||||
Every working shape is idempotent (checked `format(format(x)) == format(x)`
|
||||
on seven distinct shapes). Confirmed the `#SKIP` case
|
||||
(`wire /* c */ #5 x;`) is genuinely pre-existing by running
|
||||
`~/.cache/lucisv-baselines/lucisv-0.41.0 format --stdout` on the isolated
|
||||
before-type shape: identical `verification failed: token stream diverges …`
|
||||
error, same column, on the baseline that predates this round entirely. Ran
|
||||
the same probe on the new after-type shape and on the exact two lines in the
|
||||
`.cases` `#SKIP` block — same failure mode both times, confirming the
|
||||
struct's `after_type` field inherits the gap rather than introducing it.
|
||||
The other two round-tripping cases in `net_delay_position.cases` (an
|
||||
attribute before the declaration, a comment after the delay) were run
|
||||
directly and match their expected output byte for byte, including the
|
||||
forced line break the comment causes.
|
||||
|
||||
Semantic consumer: added a temporary `#[test]` in
|
||||
`crates/vlog_semantic/tests/semantics.rs` (`qa_scratch_a_delayed_net_still_resolves`,
|
||||
removed after use — final `git diff` on that file is empty) declaring
|
||||
`wire [31:0] #0.1 delayed_net = other;` and asserting `definition_of` on a
|
||||
later use resolves back to the `Net` symbol. Passed. `bind_data_decl`'s
|
||||
one-line change (`d.delay.as_ref().map(|n| &n.expr)`) is correct.
|
||||
|
||||
**Byte-identity.** Corpus (820 files, `find corpus -name '*.sv' -o -name
|
||||
'*.v'`): compared `format --stdout` output and exit code between
|
||||
`target/release/lucisv` and the 0.41.0 baseline over every file — **0
|
||||
differences** (neither skip file is in the corpus, as the dev's README
|
||||
says). Opentitan sweep over `hw/ip`, `hw/top_earlgrey/ip`,
|
||||
`hw/top_darjeeling/ip`, `hw/dv`, `hw/vendor` (2 554 `.sv`/`.v`/`.svh`/`.vh`
|
||||
files) comparing `format --check` exit codes between the two binaries:
|
||||
**exactly** `hw/dv/sv/jtag_agent/jtag_if.sv` and
|
||||
`hw/vendor/pulp_riscv_dbg/tb/unused/SimDTM.sv` changed, both from exit 2
|
||||
(parse error) to exit 1 (would-reformat) — no other file in the sweep
|
||||
differs. `git -C /Users/guoliangchen/repo/opentitan status --porcelain`
|
||||
after every read-only invocation shows only the three files the task's
|
||||
baseline convention already allows (`hw/ip/aes/dv/tb/tb.sv`,
|
||||
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`),
|
||||
none of which this session touched.
|
||||
|
||||
**Gates (guarded).**
|
||||
- `cargo clippy --all-targets`: clean.
|
||||
- `tools/guard.sh -- cargo test --workspace`: **3 744 passed / 0 failed**
|
||||
(36 ignored, all pre-existing `#[ignore]` measurement tests) — matches the
|
||||
dev's claimed count exactly.
|
||||
- `tools/guard.sh -- tools/corpus_check.sh`: **814/820** parsed &
|
||||
formattable, same six pre-existing failures (`parse-error` count 6,
|
||||
`verification-error` 0, `crash` 0).
|
||||
|
||||
No HIGH or MEDIUM findings. One LOW/informational note (the `generate`
|
||||
nesting shape above) recorded for the trail, not requiring rework — the
|
||||
result is correct and non-corrupting, just an untested corner the plan
|
||||
didn't name.
|
||||
|
||||
**Verdict: PASS.**
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-04 — lead.** Accepted; ships in 0.42.0 with §39. 38.1 does what
|
||||
the §11 skip asked and no more: the rival is detected where it can be
|
||||
detected (a continuing directive at the unit's own entry level, followed by
|
||||
the same keyword and the same name), the error is routed into the split
|
||||
that already exists, and the capture runs to the unit's real closer counting
|
||||
nested units of the same kind. The dev's deviation — a dedicated check
|
||||
beside the bracket one rather than a flag on the public `ParseError` — is
|
||||
the right call for the reason given, and QA's three attempts to make the
|
||||
widened trigger over-fire all stayed ordinary errors. The body of a split
|
||||
unit is verbatim, which is the standing directive-split trade. 38.2 is a
|
||||
positional field with no normalisation, so `verify.rs` is untouched and
|
||||
the token order is preserved on both spellings; the comment-before-`#` gap
|
||||
is pre-existing (QA confirmed against 0.41.0) and stays a `#SKIP` with a
|
||||
handshake to comment-slots. Byte-identity: 0 of 820 corpus files differ
|
||||
from 0.41.0, and over 2 554 opentitan files exactly the two named files
|
||||
change outcome, both from parse error to formattable. QA's LOW (a rival
|
||||
nested in a generate `if` arm also recovers) is fine as it is.
|
||||
@@ -188,7 +188,13 @@ code_action_provider: Some(CodeActionProviderCapability::Options(CodeActionOptio
|
||||
|
||||
`Options` rather than `Simple(true)` on purpose: a client that filters by kind
|
||||
(which is how fix-on-save is configured) has to be told which kinds exist.
|
||||
`resolve_provider` is `None` because every action is returned complete.
|
||||
`resolve_provider` was `None` because every action was returned complete;
|
||||
since TODO §37.1 it is `Some(true)` and a third kind
|
||||
(`refactor.rewrite.lucisv.ports`) is listed. The quick fixes above are
|
||||
unaffected — the actions that are now offered without their edits are the port
|
||||
refactorings, and only to a client that declared
|
||||
`textDocument.codeAction.resolveSupport.properties: ["edit"]`. See
|
||||
`docs/features/lazy-code-action/README.md`.
|
||||
|
||||
**Still deliberately not advertised**, unchanged by this round and absent from
|
||||
the initialize result rather than present-and-false: `rangeFormatting` (waits on
|
||||
@@ -219,16 +225,25 @@ TODO §2 `--lines`), `completion`, `rename`, `signatureHelp`, and cross-file
|
||||
capability's kinds on the wire, quick fixes + fixAll, and a filtered
|
||||
fix-on-save request.
|
||||
- [x] `docs/features/lucisv-server/README.md` deferred list annotated.
|
||||
- [ ] **Not done, deliberately:** rule selection. No `lucisv.toml` `lint` key
|
||||
exists (Handshake 2); the server runs `default_rules()`.
|
||||
- [x] ~~**Not done, deliberately:** rule selection. No `lucisv.toml` `lint` key
|
||||
exists (Handshake 2); the server runs `default_rules()`.~~ Delivered by
|
||||
**linter-expansion-1** (editor toggles, 0.36.x) and **lint-config-contract**
|
||||
(project `[lint] select/ignore`, TODO §42, 0.43.0).
|
||||
- [ ] **Not done, deliberately:** offering Unsafe fixes. No rule ships one, and
|
||||
when one does it wants a decision (a separate `source.fixAll` kind? a
|
||||
client setting?), not a silent inclusion.
|
||||
- [x] ~~**Not done:** fence-aware fixes (Handshake 3) — a quick fix can edit
|
||||
inside a `// verilog_format: off` region, where `lucisv check --fix` would
|
||||
not.~~ Delivered by **shared-fence-filter** (round 14).
|
||||
- [ ] **Not done:** `codeAction/resolve`. Every action is cheap to build in
|
||||
full; lazy resolution is a payload optimization for actions that are not.
|
||||
- [x] ~~**Not done:** `codeAction/resolve`. Every action is cheap to build in
|
||||
full; lazy resolution is a payload optimization for actions that are
|
||||
not.~~ Delivered by **lazy-code-action** (TODO §37.1), and the note was
|
||||
right about *these* actions: the quick fixes and `source.fixAll.lucisv`
|
||||
are still returned complete. What is now lazy is the **port
|
||||
refactorings**, whose offer used to compute the whole cross-file edit —
|
||||
185–201 ms at a 128-file fan-out, on every cursor move. `resolve` hands
|
||||
an action that already carries its edit straight back, so a client that
|
||||
resolves everything it was offered still gets these unchanged.
|
||||
- [x] ~~**Not done:** sharing one parse with the linter (Handshake 1).~~
|
||||
Delivered by **one-parse** (round 19).
|
||||
|
||||
|
||||
@@ -0,0 +1,551 @@
|
||||
# small items, round 3
|
||||
|
||||
## Goal
|
||||
|
||||
Three items that do not belong to any larger feature, shipped together
|
||||
(TODO §36, release 0.40.0).
|
||||
|
||||
**36.1 — a bare `begin … end` where an item belongs is recovered, not
|
||||
refused.** `begin` is not a module item (IEEE 1800 §23.2.1), and lucisv's
|
||||
parser failed the item outright; error recovery then skipped to the next sync
|
||||
point, so everything written after the block was lost and the two lints that
|
||||
report the construct (`module-begin-block`, `v2001-generate-begin`) had to
|
||||
read the error leaf's first word. In tolerant mode the block is now parsed as
|
||||
the unnamed generate block every tool that accepts it makes of it, kept as
|
||||
`ItemKind::GenBlock(Box<GenBlock>)`, with a diagnostic recorded at the
|
||||
`begin`. Strict mode is untouched, so nothing about a file that parses
|
||||
changes. topo §2.9-25.
|
||||
|
||||
**36.2 — a half-typed `.NAME(` no longer swallows the next instance.** In
|
||||
`sub #(.WIDTH(8), .DEPTH(` ⏎ `u0 (.a(x), .b(y));` nothing inside the override
|
||||
list fails: `u0 (.a(x), .b(y))` is a legal call with named arguments, so the
|
||||
greedy value parse ate the instance and the whole instantiation collapsed into
|
||||
one item-level error that took the `endmodule` with it. This was the MEDIUM
|
||||
finding in the header-recovery QA log of 2026-09-02. One tolerant-mode
|
||||
lookahead in `Parser::parse_connection` now fails that element instead, so the
|
||||
override costs one element and everything else survives. topo §2.9-24.
|
||||
|
||||
**36.3 — in-place writes are atomic.** `lucisv format` and `lucisv lint --fix`
|
||||
wrote with `fs::write`, which truncates the target and *then* writes: a crash,
|
||||
a full disk or a `^C` in between leaves the user's source truncated, which is
|
||||
the one thing lucisv promises never to do. `lucisv_core::atomic::write_atomic`
|
||||
is the single write path now — temp file beside the target, permissions
|
||||
copied, `rename` on top — and `cache.rs`'s hand-rolled copy of the same dance
|
||||
is gone. A §1 backlog item, QA find of 2026-08-25.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **36.1** — a file holding a recovered `begin` block always carries at least
|
||||
one diagnostic, so the formatter's "zero errors or nothing" contract keeps
|
||||
refusing it and `ItemKind::GenBlock` never reaches printed output. The
|
||||
formatter arm exists for a future range or tolerant printer, not for today.
|
||||
- **36.1** — the block's scope shape is an unlabeled generate block's. A
|
||||
labeled one declares its label, exactly as `bind_gen_block` already does for
|
||||
an `if` arm; nothing invents a new scope kind.
|
||||
- **36.1** — `module-begin-block` reports only a block written *directly* in a
|
||||
module body and `v2001-generate-begin` only one written directly in a
|
||||
generate region, so a `begin` nested inside another recovered block is
|
||||
reported by neither. That was true before this round too (the whole nest was
|
||||
one error leaf whose first word was the outer `begin`); it is now pinned by
|
||||
`only_the_outermost_block_of_a_nest_is_reported_at_module_scope`.
|
||||
- **36.2** — an identifier that opens its own line and is followed by `(`,
|
||||
found at bracket depth zero inside a value that never closes, is the next
|
||||
instance. A value that *does* close is never touched, however it is written,
|
||||
which is what keeps every legal file identical in both modes.
|
||||
- **36.2** — when the parentheses balance the shape is genuinely ambiguous
|
||||
(`sub #(.D(` ⏎ `u0 (.a(x)));`), and the greedy parse still wins. Pinned as a
|
||||
test so it is not "fixed" later.
|
||||
- **36.3** — `rename` within one directory is atomic on every platform lucisv
|
||||
ships to, and the canonical target's directory is on the target's own
|
||||
filesystem. Concurrency between two lucisv processes writing one file is
|
||||
last-writer-wins on whole contents, never a mix of the two.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **`vlog_parser` → everyone**: `ItemKind` gained the variant
|
||||
`GenBlock(Box<GenBlock>)`. Every walker over items must descend into its
|
||||
`items` the way it descends into an unlabeled `GenIf` arm's block. Done in
|
||||
this round for `vlog_formatter` (`format/item.rs`, `fence.rs`),
|
||||
`vlog_semantic` (`bind/item.rs`, `instantiations.rs`), `vlog_refactor`
|
||||
(`ports/find.rs`), `vlog_linter` (`visit.rs` ×2, `signals.rs`,
|
||||
`module_decls.rs`) and `lucisv_server` (`linked.rs`, `selection.rs`,
|
||||
`type_def.rs`), plus the four test walkers in `crates/vlog_parser/tests`.
|
||||
Three of those matches are exhaustive, so the compiler finds them; the rest
|
||||
end in `_ => {}` and were found by grepping for `ItemKind::GenerateRegion`.
|
||||
- **`vlog_linter` ← `vlog_parser`**: `module_begin_block::begin_block` reads
|
||||
`ItemKind::GenBlock` instead of an `ItemKind::Error` leaf. It stays the one
|
||||
reading both rules share.
|
||||
- **`lucisv_core` → `lucisv`**: new `lucisv_core::atomic::write_atomic`. Any
|
||||
future in-place write goes through it rather than `fs::write`. No new
|
||||
dependency: `std::fs` only.
|
||||
- **`vlog_parser` internals**: `recover.rs` exposes `is_sync_stop(&Token)`,
|
||||
which `at_sync_stop` now calls — so a lookahead walking raw tokens asks the
|
||||
same question about a token ahead of the cursor.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] 36.1 `ItemKind::GenBlock`, the `begin` arm, all consumers, the two rules
|
||||
- [x] 36.2 the `value_runs_into_next_instance` lookahead and its four tests
|
||||
- [x] 36.3 `write_atomic`, its three users, its tests
|
||||
- [x] docs: this README, the two rule doc strings, the rule rows in
|
||||
`README.md` and `docs/site/.../rules.md`, the header-recovery work-log
|
||||
line
|
||||
- [x] Gates (guarded): `cargo fmt -p` per touched crate, `cargo clippy
|
||||
--all-targets`, `cargo test --workspace`, corpus check
|
||||
- [ ] QA
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-04 — dev agent
|
||||
|
||||
**36.1.** `ItemKind::GenBlock(Box<GenBlock>)` added first, then
|
||||
`cargo check --workspace --all-targets` to find the three exhaustive matches
|
||||
(`vlog_formatter/src/format/item.rs`, `vlog_semantic/src/bind/item.rs`,
|
||||
`crates/vlog_parser/tests/spans.rs`) and a grep for
|
||||
`ItemKind::GenerateRegion` to find the rest. Every arm is the boring one:
|
||||
walk `items`. Boxed, so `ast::size_pins` does not move — it still passes
|
||||
untouched.
|
||||
|
||||
The parser arm is `"begin" if self.tolerant`, so **strict mode falls through
|
||||
to the same default arm it always did**. One deviation from the plan's
|
||||
wording: that arm's message is ``unsupported construct starting with keyword
|
||||
`begin` ``, not "expected item" — `begin` is a keyword, so it never reached
|
||||
`parse_item_inner`'s `_ => self.error("expected item")`. Nothing about strict
|
||||
mode changed, which is what the byte-identity of the corpus depends on;
|
||||
`strict_mode_still_refuses_a_bare_begin_block` pins it.
|
||||
|
||||
The formatter's `gen_block` was split by a pure extraction: `begin_block`
|
||||
prints from the keyword on, and `gen_block` keeps the separator it puts in
|
||||
front of that keyword for the `if (…)`/`for (…)` header a generate block
|
||||
normally hangs off. The `ItemKind::GenBlock` arm calls `begin_block` directly,
|
||||
because a block standing as an item starts at the item's own column. The arm
|
||||
is unreachable from `format_source` (a diagnostic is always recorded, and a
|
||||
file with a diagnostic is emitted unchanged); it exists so a range or tolerant
|
||||
printer has nothing to invent. `before_kw` comments are printed by the arm, so
|
||||
nothing can be dropped there either.
|
||||
|
||||
The binder reuses `bind_gen_block` — the same call an `if` arm's block gets,
|
||||
labeled or not. No new scope kind.
|
||||
|
||||
**Finding: a new nesting family, and one test outside the plan's file set.**
|
||||
Recovering the block means the tolerant parser now *recurses* through nested
|
||||
`begin`s, 64 levels deep (`MAX_NESTING_DEPTH`), which measures at 3–4 MiB of
|
||||
stack in a debug build (bisected: dies at 3 MiB, survives at 4). That is well
|
||||
inside `PARSE_STACK_SIZE` (32 MiB) and under the ~9.7 MiB worst case
|
||||
`docs/features/recursion-limit/README.md` records, so no constant moves. But
|
||||
`lucisv_server`'s `inline::tests::a_deeply_nested_file_neither_crashes_nor_
|
||||
misses_the_trigger` builds 3 000 nested `begin`s and parses them on libtest's
|
||||
own thread, which is not a `PARSE_STACK_SIZE` thread — it aborted the whole
|
||||
test binary with a stack overflow. Fixed by running that test's body on a
|
||||
thread of its own, the way `vlog_formatter/tests/deep_nesting.rs` and
|
||||
`crates/lucisv/tests/cli.rs` already do; the test's actual subject (the inline
|
||||
path never recurses) is unchanged. **`crates/lucisv_server/src/inline.rs` is
|
||||
outside §36's stated touch set** — it is the only such file, and this is the
|
||||
reason.
|
||||
|
||||
**36.2.** `Parser::value_runs_into_next_instance` walks tokens from just past
|
||||
the value's `(` at depth zero: a closer that would take the depth below zero
|
||||
means the value closes and the answer is `false`; a `;` or a sync keyword
|
||||
(`is_sync_stop`, factored out of `at_sync_stop`) or EOF ends the walk and the
|
||||
answer is whether a candidate was seen. On a file that parses the walk stops
|
||||
at the value's `)` after a handful of tokens.
|
||||
|
||||
**Deviation, and the one thing the plan left to verify.** The plan asked for
|
||||
the diagnostic at the unclosed `(` *and* for the existing skip to leave the
|
||||
cursor on `u0`. Those two are in conflict: `push_diag` takes its span from the
|
||||
cursor, so the diagnostic is only on the `(` if the element fails without
|
||||
consuming it — and then `skip_inside_brackets` counts that `(` as a nesting
|
||||
level, stops reading the line-change rule (which is only consulted at the
|
||||
list's own level), and runs to EOF. As the plan directs, **the skip's start
|
||||
was fixed, not the lookahead**: `recover_element` now takes an open bracket
|
||||
the cursor is sitting on before it starts skipping, since an element that gave
|
||||
up *on* a bracket is an element that opened one and never closed it. That is
|
||||
one `else if` in `recover_element`; no existing test moved.
|
||||
|
||||
The resulting tree for the README shape is exactly the one asked for:
|
||||
`params = [Ok(.WIDTH(8)), Error(".DEPTH(")]`, one instance `u0` with **two**
|
||||
connections, **one** diagnostic whose span is the `(`, and `endmodule`
|
||||
consumed by the module.
|
||||
|
||||
Second deviation, in the connection-list twin (`sub u0 (.a(` ⏎
|
||||
`u1 (.b(y));`): the plan expected `u1` to become a **second instance**. It
|
||||
cannot — no `,` was written after `u0`'s connection list, so the instance loop
|
||||
ends there and `u1 (.b(y));` is read as the next *item* of the module. It is
|
||||
not a legal item on its own, so it becomes one error node with a second
|
||||
diagnostic. That is still the win the item is about: before, `u1` was
|
||||
swallowed into `.a(`'s value and the module lost its `endmodule`. Pinned as
|
||||
written, in `a_half_typed_connection_does_not_swallow_the_next_instance`.
|
||||
|
||||
**36.3.** `write_atomic` resolves symlinks first (`fs::canonicalize` when the
|
||||
path exists — writing *through* a link is what `fs::write` does, and renaming
|
||||
onto the link would replace it with a file and orphan the real one), writes
|
||||
`.{name}.{pid}.lucisv-tmp` in the target's directory, copies the target's
|
||||
permissions onto it when there is a target, renames, and removes the temp on
|
||||
any failure after it exists. `std::fs` only, no dependency. `cache.rs::store`
|
||||
lost its inline copy; `main.rs`'s `process_file` and `lint.rs`'s `--fix` call
|
||||
it. One small fix beside it: `cache.rs`'s `no_temporary_file_is_left_behind`
|
||||
filtered for names ending in `.tmp`, which the new suffix does not match, so
|
||||
the filter now catches `-tmp` too — otherwise the test would have passed
|
||||
without testing anything.
|
||||
|
||||
**Files touched outside §36's stated set** (each named above):
|
||||
`crates/lucisv_server/src/inline.rs` (the stack-size finding),
|
||||
`crates/vlog_parser/tests/{spans.rs,census.rs,null_items.rs}` (walkers the new
|
||||
variant reaches — the plan named `error_recovery.rs` only),
|
||||
`crates/vlog_linter/src/{module_decls.rs,signals.rs}` and
|
||||
`crates/lucisv_server/src/{linked.rs,selection.rs,type_def.rs}` and
|
||||
`crates/vlog_semantic/src/instantiations.rs` and
|
||||
`crates/vlog_refactor/src/ports/find.rs` (all covered by "every exhaustive
|
||||
`ItemKind` match the new variant reaches", but worth listing),
|
||||
`crates/vlog_formatter/src/fence.rs`, and
|
||||
`crates/vlog_parser/src/parser/recover.rs` (the `is_sync_stop` extraction).
|
||||
|
||||
**Gates.** `cargo fmt -p` over the eight touched crates: clean.
|
||||
`cargo clippy --all-targets`: **0 warnings**.
|
||||
`tools/guard.sh -- cargo test --workspace`: **3 621 passed, 0 failed, 40
|
||||
ignored** — 3 603 before this round plus exactly the **18** pins it adds: 9 in
|
||||
`crates/vlog_parser/tests/error_recovery.rs` (5 for 36.1, 4 for 36.2), 3 in
|
||||
the two rule modules, 6 in `atomic.rs`. Two more shapes joined that file's
|
||||
`BROKEN` table, so they also run through
|
||||
`diagnostics_and_error_nodes_stay_inside_the_file` and
|
||||
`a_diagnostics_span_is_the_token_its_line_col_names` without adding a test
|
||||
name. The truncation and single-character-deletion fuzzers — the termination
|
||||
guard for both parser changes — are green.
|
||||
`tools/guard.sh -- tools/corpus_check.sh`: **814/820 (99.3 %)**, the same six
|
||||
failures as before (`end`, `cp_sign_cross`, `1`, `)`, `$_DLATCH_P_`, and the
|
||||
lex error), 0 verification errors, 0 crashes. No guard kill anywhere.
|
||||
|
||||
**On the rule rows in `README.md`.** `README.md`'s table row for each of the
|
||||
two rules is a one-line summary that never mentioned the parser, so it needed
|
||||
no change; the prose that did (the two `Rule::doc` strings and the two
|
||||
sections in `docs/site/src/content/docs/reference/rules.md`) is rewritten.
|
||||
|
||||
### 2026-09-04 — lead, at review
|
||||
|
||||
QA's REWORK items closed in the tree: `mismatched-labels` gained the
|
||||
`ItemKind::GenBlock` arm (`check_gen_block`, the same call an `if` arm's
|
||||
block gets) with a test on a `begin : fetch … end : decode` at module
|
||||
scope; the LOW became a paragraph on `value_runs_into_next_instance`
|
||||
saying why only depth zero is read. One lead finding on 36.3, fixed with a
|
||||
test: `rename` replaces a file whatever its mode, so `write_atomic` would
|
||||
have silently rewritten a read-only file where the old `fs::write` refused
|
||||
it — it now returns `PermissionDenied` before making a temp file, which
|
||||
keeps the CLI's behaviour on a `chmod a-w` file exactly what it was. QA's
|
||||
process flag was the lead's own TODO housekeeping (the §27–§35 QA lines,
|
||||
done in their QA logs, ticked; the §27 P6 line annotated — topo §2.9-18 is
|
||||
already struck as delivered by §29, and the stale checkbox in the
|
||||
sva-bodies README is now ticked with the same note).
|
||||
|
||||
**Release gates (lead, guarded, merged tree):** `cargo clippy --all-targets`
|
||||
0 warnings; `cargo test --workspace` **3 715 passed / 0 failed / 42 ignored
|
||||
over 48 binaries**; corpus **814/820**, the same six failures, no crash;
|
||||
`lucisv format --stdout` byte-identity over all 820 corpus files against
|
||||
`~/.cache/lucisv-baselines/lucisv-0.39.0`: **0 differing**; opentitan
|
||||
read-only `--check` over `hw/ip`, `hw/top_earlgrey/ip`, `hw/top_darjeeling/ip`
|
||||
identical to 0.39.0 (1 867 would reformat / 30 unchanged / 5 failed), lint
|
||||
census over `hw/ip` 446 = 446, working tree status unchanged; vsix smoke
|
||||
OK. Ships as 0.40.0.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-04 — QA agent
|
||||
|
||||
Read the plan (TODO §36), the dev's account above, and the full diff
|
||||
(`git diff --stat`, then every touched file). Attacked all three items by
|
||||
hand against the working tree; nothing here was committed by QA — all edits
|
||||
are the dev's, all attack inputs lived under the QA scratchpad or as
|
||||
temporary `#[test]`s removed before this log was written.
|
||||
|
||||
**36.1 (`ItemKind::GenBlock`).** Confirmed `record()` (which takes its span
|
||||
from the cursor) runs before `parse_gen_block()` bumps past the `begin`
|
||||
keyword, so the diagnostic really does land on the keyword, not on whatever
|
||||
`parse_gen_block` consumes first. Read every consumer the Handshakes section
|
||||
claims (`format/item.rs`, `fence.rs`, `bind/item.rs`, `instantiations.rs`,
|
||||
`ports/find.rs`, `visit.rs` ×2, `module_decls.rs`, `signals.rs`, `linked.rs`,
|
||||
`selection.rs`, `type_def.rs`, and the four parser test walkers) — each is
|
||||
the boring "descend into `.items`" arm the plan asked for, or (for
|
||||
`exprs.rs`, which the Handshakes section does not mention) correctly needs
|
||||
no arm at all because it walks per-item "root expression" sites and reaches
|
||||
a `GenBlock`'s own items through `walk_items`, which already recurses.
|
||||
`type_hierarchy.rs`'s class-hierarchy walk intentionally never descends into
|
||||
any generate construct (a documented, pre-existing gap unrelated to this
|
||||
round) and correctly gained no arm either.
|
||||
|
||||
Typed every shape the plan and the QA brief ask for directly against
|
||||
`parse_source_tolerant`/`parse_source`: labeled block (`begin : g … end : g`,
|
||||
round-trips into `end_label`), nested `begin`s (two diagnostics, both kept,
|
||||
`only_the_outermost_block_of_a_nest_is_reported_at_module_scope` pins that
|
||||
neither rule reports the inner one — correct, matches the pre-round
|
||||
behaviour for a nested leaf), a block containing an instantiation and an
|
||||
`always` block, a block as a module's only item, a block right before
|
||||
`endmodule`, `begin` with a comment before and inside it (`before_kw` is
|
||||
printed by the formatter's dead arm — read, not just trusted, since the arm
|
||||
is unreachable from `format_source`), an unclosed `begin` at module scope
|
||||
(recovers as far as it can and does **not** eat `endmodule` when one
|
||||
follows; `an_unclosed_begin_keeps_the_statements_inside_it` already pinned
|
||||
the general unclosed-block case pre-round and nothing about that changed),
|
||||
and `begin` inside a generate `if` arm (unchanged — that path never reaches
|
||||
the new `"begin"` arm because `parse_gen_if`'s block already calls
|
||||
`parse_gen_block` directly, not through `parse_keyword_item`). `begin`
|
||||
inside interface/program/package: all three share `parse_module`'s item
|
||||
loop with `module`, so the new arm is reached identically in every one —
|
||||
confirmed by reading the dispatch table in `parse_keyword_item`, which does
|
||||
not special-case the container.
|
||||
|
||||
`module-begin-block` and `v2001-generate-begin` each fire exactly once, at
|
||||
the keyword, in every shape above; `forbid_defparam` (a third, unrelated
|
||||
rule) sees the violation written inside the recovered block in both of the
|
||||
dev's own tests, proving the items are live to every rule, not just the two
|
||||
that read the node directly.
|
||||
|
||||
The formatter's dead arm was force-fed through `format_source` on the two
|
||||
`BROKEN`-table pins via `--check`-style parsing: a file carrying the
|
||||
diagnostic is reported as not parsing cleanly and the formatter emits it
|
||||
unchanged, so the arm genuinely never executes in `lucisv format`. The
|
||||
fence collector (`vlog_formatter/src/fence.rs`, tolerant parse) does not
|
||||
panic on any shape above.
|
||||
|
||||
LSP outline/symbols: `selection.rs`'s smart-selection walker and
|
||||
`type_def.rs`'s go-to-type walker both gained the boring arm and were read,
|
||||
not separately exercised through a live server harness (a cheap unit test
|
||||
through `lucisv_server`'s existing harness would have needed a workspace
|
||||
fixture outside this pass's time budget; the arms are structurally identical
|
||||
to the ones already covered for `GenIf`/`GenFor`/`GenCase`, so this is a
|
||||
LOW-confidence gap rather than a real risk).
|
||||
|
||||
**Finding (MEDIUM) — `mismatched-labels` does not check a bare block's own
|
||||
label pair.** `crates/vlog_linter/src/rules/mismatched_labels.rs`'s
|
||||
`item_labels` (around line 125) has arms for `GenIf`/`GenFor`/`GenCase` that
|
||||
call `check_gen_block` on each arm's block — but no arm for the new
|
||||
`ItemKind::GenBlock` itself, so `begin : fetch … end : decode` written
|
||||
directly at module scope (or inside `generate … endgenerate`) is silently
|
||||
**not** flagged, even though the rule's own doc string explicitly lists
|
||||
`begin` as one of the checked constructs and the rule is Severity::Error
|
||||
(a genuine compile error under IEEE 1800 §9.3.4). Confirmed with a temporary
|
||||
test (`module m;\n begin : fetch\n wire a;\n end : decode\nendmodule\n`
|
||||
→ `MismatchedLabels.check` returns 0 violations; removed after confirming,
|
||||
not left in the tree). This was missed by the dev's own method (compiler
|
||||
errors for exhaustive matches, plus `grep ItemKind::GenerateRegion` for the
|
||||
rest) because `mismatched_labels.rs` is neither exhaustive over `ItemKind`
|
||||
nor does it mention `GenerateRegion` — it goes straight to the
|
||||
`GenIf`/`GenFor`/`GenCase` arms. Fix is one arm:
|
||||
`ItemKind::GenBlock(b) => check_gen_block(out, b)`. Not fixed by QA because
|
||||
it is a real behavior change to a shipping rule, not a typo.
|
||||
|
||||
**36.2 (`value_runs_into_next_instance`).** Reproduced the README shape
|
||||
exactly: params `[Ok(.WIDTH(8)), Error(".DEPTH(")]`, `u0` with two
|
||||
connections, one diagnostic on the `(`, `endmodule` consumed — matches
|
||||
`a_half_typed_override_does_not_swallow_the_next_instance`. Attacked:
|
||||
|
||||
- Ambiguous balanced-parens control (`sub #(.D(` / `u0 (.a(x)));`) — still
|
||||
read greedily, exactly pinned, confirmed unchanged.
|
||||
- Legal multi-line value whose middle line is `f(1)` — identical strict and
|
||||
tolerant trees, confirmed by the dev's own test plus a manual read of the
|
||||
parity test.
|
||||
- The named connection-list twin — matches the dev's documented deviation
|
||||
exactly: `u1` cannot become a second instance (no comma after `u0`'s
|
||||
list), so it is a second, malformed module item instead. Still strictly
|
||||
better than the pre-round total loss of `endmodule`.
|
||||
- **Nested/deeper unclosed brackets** (`.DEPTH(f(g(h(` / `u0 (.a(x));`):
|
||||
the lookahead's depth counter never returns to 0 before EOF (three net
|
||||
un-closed opens), so its candidate check — gated on depth == 0 — never
|
||||
fires and `value_runs_into_next_instance` returns `false`. Falls back to
|
||||
the pre-existing (pre-§36.2) recovery: the whole `sub #(...)` collapses
|
||||
into one `ItemKind::Error`, but critically **`endmodule` is still not
|
||||
eaten** (the general item-level sync/skip saves it, independent of this
|
||||
round's fix) — confirmed by direct inspection, no hang (sub-millisecond),
|
||||
no panic, `assert_diagnostics_fit` holds. This is a known scope boundary,
|
||||
not a regression: the plan's heuristic is depth-0 only by design. LOW —
|
||||
worth a one-line doc-comment on `value_runs_into_next_instance` for the
|
||||
next reader, not a blocking fix.
|
||||
- **Positional/ordered connection lists**: `value_runs_into_next_instance`
|
||||
is wired only into `parse_connection`'s named-connection (`.name(`)
|
||||
branch; `parse_ordered_connection` calls `parse_expr_or_type` with no
|
||||
lookahead at all. Attacked `sub u0 (f(` / `u1 (.a(x));` (a positional
|
||||
value that reads as a call spanning into the next instance): the
|
||||
pre-existing generic `element_or_recover`/`recover_element` path handles
|
||||
it safely — the whole `f(...)` argument list including `u1 (.a(x))`
|
||||
becomes one error *connection element* (bytes preserved, nothing lost),
|
||||
the instance list ends cleanly at the following `;`, and `endmodule` is
|
||||
read normally. So there is no corruption and no hang, but `u1` is not
|
||||
separately recognized the way the named-connection case's `u1`-as-item
|
||||
is. This matches the plan's own text, which demonstrates "the connection
|
||||
list" case with a **named** connection (`.a(`), never a bare positional
|
||||
one — so this is not a gap against the stated scope, just worth recording
|
||||
so nobody assumes positional lists get the same treatment. LOW.
|
||||
- Several `.A(1), .B(2), .C(` named overrides in a row, only the last
|
||||
unclosed: exactly one diagnostic (at `.C(`'s paren), `u0` recovered as a
|
||||
proper `Instantiation` with the override list ending cleanly — confirmed.
|
||||
- A `;` written inside the unclosed value before any candidate identifier
|
||||
(`.DEPTH(x;` / `u0 (.a(x));`): the lookahead's walk ends at the `;` with
|
||||
no candidate seen, so it correctly answers `false` (the plan's own
|
||||
design — a `;` at depth 0 always ends the walk) and the shape falls
|
||||
through to ordinary item-level recovery: two error items, `endmodule`
|
||||
still intact. No corruption.
|
||||
- Macro calls inside the value were not separately attacked beyond the
|
||||
above (a macro-call token is lexed as `Directive`/identifier-like and the
|
||||
candidate check only cares about `TokenKind::Ident` followed immediately
|
||||
by `(` on a fresh line, so a macro invocation such as `` `WIDTH(8) ``
|
||||
cannot itself be mistaken for the candidate — reasoned from
|
||||
`value_runs_into_next_instance`'s token-kind check rather than typed by
|
||||
hand; LOW confidence, not exercised).
|
||||
|
||||
**Termination (`recover_list.rs`'s new bracket-seeded branch).** Reasoned
|
||||
through `recover_element`/`skip_inside_brackets`'s `open` counter by hand,
|
||||
then confirmed by execution: the new `else if self.at_open_bracket()` arm
|
||||
only ever fires when the cursor sits exactly on the unclosed value's own
|
||||
`(` (true in the depth-0 lookahead-hit case; the nested-bracket case above
|
||||
never reaches this branch at all, since the lookahead itself declines and
|
||||
the cursor lands on the `;`, not on a bracket). No crafted input — several
|
||||
`.x(` in a row, nested unclosed brackets on one line, a `)` on the next
|
||||
line — produced a spin or a skip that ran past its own list: every attack
|
||||
above either terminated in well under a second or matched the pre-existing
|
||||
"skips to EOF" fallback the plan already accepted as a limit for cases
|
||||
outside the depth-0 heuristic. `list_ends`'s own "unmoved cursor ends the
|
||||
list" guarantee (unchanged this round) remains the structural backstop
|
||||
regardless.
|
||||
|
||||
Ran `tolerant_parse_equals_strict_parse_on_valid_sources` and the
|
||||
truncation/single-character-deletion fuzz tests in `error_recovery.rs`
|
||||
(guarded): green, and they now also cover the two new `BROKEN`-table
|
||||
entries the dev added (`module-scope begin block`,
|
||||
`override runs into the next instance`), so every byte-prefix and every
|
||||
single-byte-deletion of those two shapes is exercised too.
|
||||
|
||||
Timed a tolerant parse of the largest opentitan file
|
||||
(`hw/top_darjeeling/ip_autogen/pinmux/rtl/pinmux_reg_top.sv`, 42k lines) with
|
||||
`--check`, three runs each, current binary vs. the cached 0.39.0 baseline:
|
||||
~0.63–0.65 s both, no measurable difference — the lookahead costs nothing on
|
||||
a file that parses, as the plan predicted.
|
||||
|
||||
**36.3 (`write_atomic`).** Built `target/release/lucisv` and attacked by
|
||||
hand in the QA scratchpad (all removed after):
|
||||
|
||||
- A file formatted through a symlink: the symlink's target got the new
|
||||
bytes, the link itself was untouched and still resolves to it.
|
||||
- A 0600 file and a 0755 file each kept their mode across `lucisv format`.
|
||||
- A read-only directory (rename target unwritable): `write_atomic` fails at
|
||||
the temp-file `fs::write` step itself (can't even create the temp inside
|
||||
a `dr-xr-xr-x` directory), so no `.lucisv-tmp` is ever created; the CLI
|
||||
reports `error: …: Permission denied (os error 13)` and exits 2, the same
|
||||
family of exit code every other per-file failure uses. Original file
|
||||
untouched.
|
||||
- `lucisv check --fix` on a file with a fixable violation
|
||||
(`no-trailing-whitespace`): fixed correctly, mode preserved, no leftover
|
||||
temp.
|
||||
- Two `lucisv format` invocations racing on one inode through two path
|
||||
spellings (`conc.sv` and a symlink alias `sub/alias.sv` both resolving to
|
||||
it): both processes exited 0, the file ended up whole and correctly
|
||||
formatted (last-writer-wins on whole contents, exactly the assumption the
|
||||
README states — no torn/mixed output, no crash).
|
||||
- The temp name is `.{name}.{pid}.lucisv-tmp` — confirmed two concurrent
|
||||
processes on the same file get different temp names (different pids), so
|
||||
they cannot collide on the temp file itself even though they race on the
|
||||
final `rename`.
|
||||
- A leftover temp simulated by hand (`touch .good.sv.99999.lucisv-tmp` next
|
||||
to a real `good.sv`) is **not** picked up by the CLI's directory walk:
|
||||
confirmed `lucisv --check .` over the directory processed exactly the one
|
||||
real file. Traced why in `crates/lucisv_core/src/walk.rs`: discovery
|
||||
matches on `Path::extension()` against `["v","sv","vh","svh"]`, and a name
|
||||
with multiple dots (`.good.sv.99999.lucisv-tmp`) yields `extension() ==
|
||||
Some("lucisv-tmp")`, which is in none of those — so no glob or hidden-file
|
||||
special-casing is even needed for this to hold.
|
||||
- `cache.rs`: read the diff — `store()` now calls `write_atomic` directly
|
||||
and the inline tempfile-and-rename it used to hand-roll is gone. Its own
|
||||
`no_temporary_file_is_left_behind` test was updated to also filter
|
||||
`-tmp`-suffixed names (the old filter only matched `.tmp`, which the new
|
||||
`.lucisv-tmp` suffix does not end with — without this fix the test would
|
||||
have silently stopped testing anything). Ran it directly: passes, along
|
||||
with the rest of `cache.rs`'s suite (15/15) and all 6 of `atomic.rs`'s own
|
||||
tests.
|
||||
|
||||
**Finding (MEDIUM-ish, process, not correctness) — `TODO.md` diff includes
|
||||
8 unrelated historical checkboxes.** `git diff -- TODO.md` flips eight
|
||||
`- [ ]` → `- [x]` QA lines in sections §29 through §35 (already-released
|
||||
0.34.0–0.39.0 work), plus a `**Delivered by §29**` note appended to the P6
|
||||
line under §29. None of this is in §36's stated file-ownership list (which
|
||||
only claims "this section" of `TODO.md`), and none of it is mentioned in
|
||||
the work log above. It may well be correct bookkeeping (those releases did
|
||||
ship, and the checkboxes may simply never have been flipped in an earlier
|
||||
session) — but at least the P6/§2.9-18 line is worth the lead's own look:
|
||||
`docs/topo.md`'s `refactor-rename` row (line 494) still says "Open residue:
|
||||
macro-invocation-argument warnings need §2.9-18", and
|
||||
`docs/features/sva-bodies/README.md:290` still shows that same P6 item as
|
||||
`- [ ]` in its own Status/TODO — so at least one of the two docs disagrees
|
||||
with the TODO.md edit made in this round. Whether the other seven flips are
|
||||
equally solid was not independently re-verified (out of this round's actual
|
||||
scope to re-derive); flagging so the lead can decide whether to keep,
|
||||
revert, or verify them before this lands. Did not revert it myself — the
|
||||
content may be true, and reverting a possibly-correct bookkeeping fix would
|
||||
be its own guess.
|
||||
|
||||
**Gates re-run by QA (guarded, all green).**
|
||||
- `cargo clippy --all-targets` (targeted at every touched crate plus a full
|
||||
workspace check): 0 warnings.
|
||||
- `tools/guard.sh -- cargo test --workspace`: **3 713 passed, 0 failed, 42
|
||||
ignored**, no guard kill. (This total differs from the dev's reported
|
||||
3 621/40 in the work log; re-run twice, both times 3 713/42 — not
|
||||
re-derived line-by-line against the dev's count, but the number that
|
||||
matters, 0 failed, agrees, and every individually re-run suite — parser,
|
||||
linter rules, cache, atomic — is green on its own.)
|
||||
- `tools/guard.sh -- tools/corpus_check.sh`: **814/820 (99.3%)**, same six
|
||||
failures (`end`, `cp_sign_cross`, `1`, `)`, `$_DLATCH_P_`, the lex error),
|
||||
0 verification errors, 0 crashes.
|
||||
- `tools/guard.sh -- target/release/lucisv check --select
|
||||
module-begin-block,v2001-generate-begin` over
|
||||
`hw/ip`, `hw/top_earlgrey/ip`, `hw/top_darjeeling/ip`: **0 findings**,
|
||||
identical (exit 0) on both the current binary and the cached
|
||||
`lucisv-0.39.0` baseline. `hw/vendor` also checked for parity: both
|
||||
binaries hit the same pre-existing lex error in the same vendored file
|
||||
and exit 2 identically. Bare `begin` blocks are evidently rare enough in
|
||||
real RTL that this census cannot exercise the new recovery path itself —
|
||||
it only confirms no regression on files that already parse.
|
||||
`git -C opentitan status --porcelain` after every sweep: unchanged, only
|
||||
the three pre-existing baseline-drift files
|
||||
(`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`,
|
||||
`hw/top_earlgrey/ip/ast/rtl/ast.sv`).
|
||||
|
||||
**Verdict: REWORK (small).**
|
||||
1. MEDIUM — `crates/vlog_linter/src/rules/mismatched_labels.rs`: add
|
||||
`ItemKind::GenBlock(b) => check_gen_block(out, b)` to `item_labels`'s
|
||||
match, plus a test (`begin : fetch … end : decode` at module scope must
|
||||
fire `mismatched-labels`). This is the one real gap: a shipping
|
||||
Severity::Error rule silently misses a real compile error on the new
|
||||
node.
|
||||
2. LOW — a one-line doc-comment addition to
|
||||
`Parser::value_runs_into_next_instance` noting the depth-0-only scope
|
||||
(nested/nonzero-depth unclosed brackets fall back to the pre-existing
|
||||
coarser recovery) would save the next reader the same investigation.
|
||||
Not blocking.
|
||||
3. Process flag (not a code defect) — the eight unrelated `TODO.md`
|
||||
checkbox flips in §29–§35 and the §2.9-18/topo.md discrepancy: lead's
|
||||
call on whether to keep, verify, or revert before merge.
|
||||
|
||||
Everything else — 36.1's node, consumers, and rules; 36.2's lookahead,
|
||||
its termination behavior, and its tests; 36.3's `write_atomic` and its
|
||||
three call sites — held up under attack. Re-run finding 1 and this is a
|
||||
clean ship.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-04 — lead.** Accepted; ships in 0.40.0. The three parts are what
|
||||
§36 asked for and no more. 36.1 is the right shape: strict mode falls
|
||||
through untouched (the corpus byte-identity gate is the proof), the
|
||||
tolerant arm records the diagnostic *and* keeps the block, and the
|
||||
consumers each make the boring choice — the binder reuses the `if`-arm
|
||||
path, the formatter arm is a pure extraction of `gen_block`. The nesting
|
||||
finding (a 3 000-deep `begin` nest now recursing to `MAX_NESTING_DEPTH`
|
||||
and needing `PARSE_STACK_SIZE` in the one server test that parsed on
|
||||
libtest's thread) was handled the way the two existing deep-nesting tests
|
||||
handle it, and the measured 3–4 MiB is well inside the documented worst
|
||||
case. 36.2's lookahead is linear, depth-zero only by design and pinned
|
||||
both ways (the balanced-parens control stays greedy); the dev's deviation
|
||||
— taking the bracket the element stopped *on* before the skip, rather
|
||||
than making the diagnostic point elsewhere — is the right resolution of
|
||||
the plan's two conflicting requirements, and QA's termination attack
|
||||
confirmed it cannot spin. 36.3 gains one refusal at review (read-only
|
||||
targets), which is parity with the old writer rather than new policy.
|
||||
QA's only miss-of-the-dev's-audit (`mismatched-labels`) is a reminder that
|
||||
a grep for a sibling variant is not an exhaustiveness proof; the fix is
|
||||
in. Gates re-run by the lead on the merged tree: see the work log's
|
||||
release line and CHANGELOG 0.40.0.
|
||||
@@ -0,0 +1,565 @@
|
||||
# small items, round 4
|
||||
|
||||
## Goal
|
||||
|
||||
Four items that belong to no larger feature, shipped together (TODO §45,
|
||||
release 0.44.0). Each closes an open handshake in `docs/topo.md` §2.9.
|
||||
|
||||
**45.1 — the editor's unknown rule name is said once (topo 29).** A name in
|
||||
`lucisv.lint.select` / `lucisv.lint.ignore` that the registry does not know was
|
||||
dropped in silence (`settings::rules` filtered it away), while the same typo in
|
||||
a `lucisv.toml`'s `[lint] select` has been logged since §42 and
|
||||
`lucisv.lint.options` has described its own bad entries since §34. The name is
|
||||
still dropped — a typo on a socket must not cost a session its diagnostics —
|
||||
and is now logged through `server/notification.rs` as
|
||||
`lucisv.lint.select: unknown rule: <name>`, **once** per (setting, name),
|
||||
re-armed only when the list changes. A `select` emptied by the dropping falls
|
||||
through §42's ladder exactly as before.
|
||||
|
||||
**45.2 — a warning channel for the walk (topo 30).** `Walk::dir` propagated
|
||||
`read_dir`'s error with `?`, so one permission-denied directory anywhere under
|
||||
the start dropped every file already found and failed the run — walk-cycles'
|
||||
QA found it on a link to `/`. `lucisv_core::walk::collect_files` now takes a
|
||||
`&mut dyn FnMut(Warning)` sink: an unreadable directory, an unreadable
|
||||
`.gitignore` and a source file that is only a broken link are each said once
|
||||
and skipped, and the walk goes on. The CLI writes `warning: <path>: <message>`
|
||||
to stderr before the report and changes no exit code; the server folds them
|
||||
into the scope's own warnings, which are logged once per scan. The dangling
|
||||
source link is **no longer handed on** — that reverses §43's review ruling on
|
||||
purpose, because the warning is now the error's home.
|
||||
|
||||
**45.3 — an inline aggregate as a parameter-override argument (topo 17).**
|
||||
`m #(.T(struct packed { logic a; })) u ();` was rejected: `parse_expr_or_type`
|
||||
routed a value to `parse_type_expr` only for a head in `TYPE_KEYWORDS`, and
|
||||
`struct`/`union`/`enum` are not in that table, so the value read as an
|
||||
expression and hit "unexpected keyword `struct` in expression".
|
||||
`parse_type_ref` had read that body since the first day and the type printer
|
||||
had printed it; only the door was shut. With it open,
|
||||
`vlog_refactor::instantiation_plan` stops dropping a one-line `parameter type`
|
||||
default that is an anonymous aggregate — its probe simply passes now — and
|
||||
emits the type text.
|
||||
|
||||
**45.4 — comment slots inside a delay list (topo 22's leftovers).**
|
||||
`parse_delay_values` serves `#(1:2:3)` on nets and continuous assignments and
|
||||
`#(rise, fall[, turn-off])` on gates. The gaps around the `(`, the two `:` and
|
||||
the `,` had no owner, so a comment written in one moved and `verify.rs` refused
|
||||
the file. They have owners now — `MinTypMaxComments`, `DelayValue`, the gate's
|
||||
`before_hash`/`after_hash`/`before_semi`, the gate instance's `before_args`,
|
||||
and the continuous assignment's `after_hash`/`after_delay` — and the RTL gap
|
||||
fuzzer's fixture set covers the construct at zero failures.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **45.1** — the memo is the *previous settings value's own warning list*, so
|
||||
"once per (setting, name)" and "re-armed when the setting changes" are one
|
||||
mechanism rather than two. A list edited from `[a]` to `[a, b]` says only
|
||||
`b`; cleared and re-typed, it says everything again. Both lists hold a
|
||||
handful of entries at most, so a linear scan beats a set.
|
||||
- **45.1** — the options warnings keep their old behaviour (raised every time
|
||||
the setting arrives). They are a different field for that reason; merging the
|
||||
two vectors would have quietly changed §34's contract.
|
||||
- **45.2** — a dangling link that does **not** name a source file stays silent.
|
||||
It was never going to be read, and warning about every broken link in a tree
|
||||
is noise, not information. The `walk.rs` test pins both halves.
|
||||
- **45.2** — a path the user names on the command line is not walked, so
|
||||
naming a dangling link directly is still `no such file or directory`, exit 2.
|
||||
The channel is about what the *walk* finds.
|
||||
- **45.2** — an unreadable `.gitignore` used to abort the run too; it is now a
|
||||
warning on the same channel. That is one step beyond the plan's wording and
|
||||
is the same judgement: a walk that finds too much is a better failure than a
|
||||
walk that finds nothing.
|
||||
- **45.2** — `Warning`'s `message` is the operating system's own words, except
|
||||
for a broken symbolic link, which is named as one (`symlink_metadata` says
|
||||
so) because `No such file or directory` reads as a lucisv bug there.
|
||||
- **45.3** — an aggregate head in expression position is *always* a type. No
|
||||
legal expression starts with `struct`, `union` or `enum`, so the new arm in
|
||||
`parse_expr_or_type` cannot take a value away from the expression grammar.
|
||||
It opens the same door for `$bits(struct packed {…})`, a stream slice size
|
||||
and an assignment-pattern key, all of which reach `parse_expr_or_type` too.
|
||||
- **45.3** — the aggregate prints through the existing type printer, so a
|
||||
`struct`/`union` body opens across lines exactly as it does in a declaration
|
||||
and an `enum` body stays inline. Nothing was laid out specially for the
|
||||
override list.
|
||||
- **45.4** — a comment inside a bracket pair forces that pair open. That has
|
||||
been true since comment-slots; the one-value `#( /*c*/ 1:2:3 )` case in
|
||||
`delay_comment_slots.cases` is a fixed point at that layout for that reason.
|
||||
- **45.4** — `Expr` stays at 96 bytes: `MinTypMaxComments` is boxed, as every
|
||||
expression-level slot is (`ast/mod.rs`'s size assertion is the check).
|
||||
- **45.4** — the empty case costs nothing. Every new slot is printed through
|
||||
`Fmt::slot_comments` or an `is_empty()` match that emits the space the old
|
||||
code emitted, which is what the corpus and opentitan byte-identity runs below
|
||||
measure.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed, unchanged.** `Parser::{take_gap, gap_before, take_before_open,
|
||||
take_meta, take_before_sep}` — every new slot is built from them, on
|
||||
comment-slots' rule that a gap belongs to a construct only when the token that
|
||||
closes it was written. `Fmt::{slot_comments, inline_comments,
|
||||
inline_comments_spaced, semi, trailing}` likewise. `verify.rs` untouched and
|
||||
no normalization widened; ten new attack pairs ship anyway (CLAUDE.md
|
||||
invariant 4).
|
||||
|
||||
**Promised / changed.** All additive except where marked.
|
||||
|
||||
| node / API | change | note |
|
||||
|---|---|---|
|
||||
| `lucisv_core::walk::Warning` | new | `{ path, message }`, `Display` as `<path>: <message>` |
|
||||
| `lucisv_core::walk::collect_files` | **signature**: fifth parameter `&mut dyn FnMut(Warning)` | two callers, one line each |
|
||||
| `ExprKind::MinTypMax` | `comments: Box<MinTypMaxComments>` | four slots, two `:` |
|
||||
| `ContAssign` | `after_hash`, `after_delay` | `assign # /*a*/ (5) /*b*/ y = x;` |
|
||||
| `GateInstantiation` | `before_hash`, `after_hash`, `before_semi`; `delay: Vec<Expr>` → `Vec<DelayValue>` | **changed field type** |
|
||||
| `GateInstance` | `before_args` | `g1 /*c*/ (y, a)` |
|
||||
| `ast::DelayValue` | new | `{ leading, expr, trailing }` — the `(`, `,` and `)` slots of a multi-value list |
|
||||
| `settings::ClientSettings` | `lint_name_warnings: Vec<String>` | one line per unknown name |
|
||||
| `settings::rules` | **signature**: takes the setting's name and a warning sink | private to the module |
|
||||
| `Server::said_lint_names` | new field | §45.1's memo |
|
||||
| `Workspace::{walked_files, folder_files, default_files, widened_files}` | **signature**: each takes `&mut dyn FnMut(String)` | private to `state.rs` |
|
||||
|
||||
Why a **sink** and not a `Walked { files, warnings }` return: both callers
|
||||
accumulate into a `&mut Vec<PathBuf>` across a loop over their inputs — the
|
||||
CLI over `opts.inputs`, the server over its scope directories — so a struct
|
||||
return would have made each of them merge two vectors per iteration and give
|
||||
up the accumulator idiom. With the sink each call site is one changed line:
|
||||
the CLI adds `&mut |w| eprintln!("warning: {w}")`, the server adds
|
||||
`&mut |w| warn(w.to_string())` onto the scope warnings it already collects.
|
||||
|
||||
**Requests filed.** None. Nothing outside this round's own file set was
|
||||
edited.
|
||||
|
||||
## Docs to apply at merge (lead)
|
||||
|
||||
`docs/topo.md` §2.9 — four rows:
|
||||
|
||||
- **Row 17** (inline aggregate as a parameter-override argument) — strike, and
|
||||
append: *— **delivered 2026-09-05 by small-items-4 (TODO §45.3)**:
|
||||
`parse_expr_or_type` routes a `struct`/`union`/`enum` head to
|
||||
`parse_type_expr`, which `parse_type_ref` has been able to read since the
|
||||
first day; the value is an `ExprKind::Type` printed by the existing type
|
||||
printer (a struct or union body opens, an enum body stays inline). The same
|
||||
door opens for the four other callers of `parse_expr_or_type` — `$bits(…)`,
|
||||
a stream slice size, an assignment-pattern key and an ordered override.
|
||||
`vlog_refactor`'s `default_text` probe now passes such a default and
|
||||
`instantiation_plan` emits the type text; only the **multi-line** spelling
|
||||
(`common_cells/src/ecc_encode.sv`) is still dropped, and by the
|
||||
"written across several lines" rule rather than by the grammar. Corpus (860)
|
||||
and opentitan (3 947) byte-identical.*
|
||||
- **Row 22** (comment slots in shared machinery, already struck) — append to
|
||||
its delivered note: *A fifth fuzzer bar was added 2026-09-05 by
|
||||
small-items-4 (TODO §45.4): the **delay list** — `#(1:2:3)` on nets and
|
||||
continuous assignments, `#(rise, fall)` on gates — gained
|
||||
`MinTypMaxComments` (four slots, one grammar shared with the parenthesized
|
||||
`(a:b:c)` expression), `ast::DelayValue` for the multi-value list's `(`, `,`
|
||||
and `)`, and `ContAssign::{after_hash, after_delay}`,
|
||||
`GateInstantiation::{before_hash, after_hash, before_semi}`,
|
||||
`GateInstance::before_args`. `EXPECTED_RTL_GAPS` 374 → 419, still at zero
|
||||
failures.*
|
||||
- **Row 29** (the editor's unknown rule name) — strike, and append:
|
||||
*— **delivered 2026-09-05 by small-items-4 (TODO §45.1)**:
|
||||
`settings::rules` describes every dropped name into
|
||||
`ClientSettings::lint_name_warnings` as
|
||||
`lucisv.lint.<select|ignore>: unknown rule: <name>`, and `apply_settings`
|
||||
logs what `Server::said_lint_names` — the previous settings value's own
|
||||
warning list — does not already hold. Once per (setting, name); a
|
||||
`didChangeConfiguration` that changes the list re-arms exactly what is new in
|
||||
it; four diagnostics passes add nothing. The dropping itself, and §42's
|
||||
ladder under an emptied `select`, are unchanged.*
|
||||
- **Row 30** (an unreadable directory aborts the whole walk) — strike, and
|
||||
append: *— **delivered 2026-09-05 by small-items-4 (TODO §45.2)**:
|
||||
`walk::collect_files` takes a `&mut dyn FnMut(Warning)` sink (`Warning
|
||||
{ path, message }`), chosen over a `Walked { files, warnings }` return
|
||||
because both callers accumulate into a `&mut Vec<PathBuf>` across a loop and
|
||||
a struct return would have cost each of them a merge per input. An unreadable
|
||||
directory, an unreadable `.gitignore` and a dangling **source-file** link are
|
||||
each said once and skipped; the walk finishes. CLI: `warning: <path>:
|
||||
<message>` on stderr before the report, exit code unchanged. Server: the
|
||||
warnings join the scope's own and are logged once per scan through
|
||||
`report_scope`. §43's review ruling that a dangling source link is handed on
|
||||
to fail in the front end is **reversed** — the warning is the error's home
|
||||
now. A dangling link that names no source file is still skipped silently.*
|
||||
|
||||
Also worth a line in `README.md` where the walk is described, if it says a
|
||||
walk fails on an unreadable directory: it warns and continues now.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] 45.1 editor unknown-name log (`settings.rs`, `server/notification.rs`,
|
||||
`server/mod.rs`, `server/tests/settings.rs`)
|
||||
- [x] 45.2 walk warning channel, both front ends (`lucisv_core/src/walk.rs`,
|
||||
`lucisv/src/main.rs`, `lucisv/tests/cli.rs`,
|
||||
`lucisv_server/src/state.rs`)
|
||||
- [x] 45.3 inline aggregate override argument + plan emission
|
||||
(`parser/primary.rs`, `parser/tests/instance.rs`,
|
||||
`vlog_refactor/src/instantiate.rs`, `tests/cases/instantiation.cases`)
|
||||
- [x] 45.4 delay-list comment slots + fuzzer coverage (`ast/expr.rs`,
|
||||
`ast/module.rs`, `parser/instance.rs`, `format/expr.rs`,
|
||||
`format/instance.rs`, `format/item.rs`,
|
||||
`tests/cases/delay_comment_slots.cases`, `tests/verification.rs`)
|
||||
- [x] Gates (guarded): fmt, clippy, `cargo test --workspace`, corpus,
|
||||
byte-identity, smoke, the hostile-tree CLI run
|
||||
- [ ] docs: topo 29/30/17/22 struck (lead — text above)
|
||||
- [x] QA (2026-09-05 — REWORK, one MEDIUM finding; see QA log)
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-05 — dev (Fable 5.1)
|
||||
|
||||
**45.3 first, because it was one line of grammar.** `parse_expr_or_type`
|
||||
(`parser/primary.rs`) checked `TYPE_KEYWORDS`, which holds the *integral and
|
||||
non-integral* type keywords only. `struct`, `union` and `enum` are keywords
|
||||
too and `parse_type_ref` already dispatches all three to `parse_struct_type` /
|
||||
`parse_enum_type`, so the fix is a second arm in front of the existing one. No
|
||||
legal expression begins with one of those words, so the arm cannot take a
|
||||
value away from the expression grammar; the previous behaviour was
|
||||
"unexpected keyword `struct` in expression".
|
||||
|
||||
Nothing else was needed for the plan's second half. `default_text` in
|
||||
`vlog_refactor/src/instantiate.rs` already *probes* — it writes
|
||||
`m #(.P( <default> )) u ();` and asks the tolerant parser — so a one-line
|
||||
aggregate default started being emitted the moment the grammar accepted it.
|
||||
The doc comment there claimed the grammar was the reason such a default was
|
||||
dropped; it now says the probe is the rule and that the multi-line spelling is
|
||||
what is still refused, by the other rule above it. Test added.
|
||||
|
||||
**45.4 was measured, not guessed.** The candidate fixture went into
|
||||
`RTL_FIXTURES` first and the fuzzer named 23 failing gaps. Fixing them meant
|
||||
one new expression-level slot (`MinTypMaxComments`, boxed) and one new list
|
||||
shape:
|
||||
|
||||
- `parse_delay_values` now returns `Vec<DelayValue>` (`{ leading, expr,
|
||||
trailing }`). The **one-value** spelling still folds into the
|
||||
`ExprKind::Paren` it always produced, and the paren's existing `before` /
|
||||
`after` slots are exactly where the `#( … )` gaps go — so nets and continuous
|
||||
assignments needed no new node at all. Only the gate's multi-value list, whose
|
||||
parentheses and commas the *printer* writes, needed somewhere to put them.
|
||||
- The two `min : typ : max` grammars — the delay list's and the parenthesized
|
||||
expression's in `parser/primary.rs` — were folded into
|
||||
`Parser::parse_min_typ_max_tail`, so the four colon slots exist in both. That
|
||||
is the same "three duplicated grammars folded into one" move comment-slots
|
||||
made.
|
||||
- The gate instantiation had four gaps of its own with no owner once the delay
|
||||
had slots: before the `#`, after the `#`, before an instance's `(`, and
|
||||
before the `;`. `GateInstance::meta` was parsed but never printed, so the
|
||||
gap in front of an instance name is now printed too, along with the
|
||||
element's `before_sep` / `trailing` around the `,` between two instances.
|
||||
- `ContAssign` gained `after_hash` and `after_delay`. The second one matters:
|
||||
a continuous assignment prints its first pair's leading comments straight
|
||||
after the `assign` keyword, which is *in front of* the delay, so a comment
|
||||
written after the delay had to be taken out of that path before `take_meta`
|
||||
saw it.
|
||||
|
||||
`EXPECTED_RTL_GAPS` 374 → 419 with the reason on the constant and on the
|
||||
fixture. Six cases in a new `delay_comment_slots.cases`, plus five attack
|
||||
pairs in `verification.rs`, one per token a new slot sits beside.
|
||||
|
||||
**45.2 — the channel shape.** `&mut dyn FnMut(Warning)`, not `Walked { files,
|
||||
warnings }`. Both callers of `collect_files` accumulate into a `&mut
|
||||
Vec<PathBuf>` across a loop over their own inputs, so a struct return would
|
||||
have replaced one line with three at each of them and given up the accumulator
|
||||
the signature is built around. With the sink each call site is one changed
|
||||
line. Inside the crate, `Walk::dir` lost its `io::Result` entirely and split
|
||||
into `dir` (enter, push the ignore stack, pop it) and `entries` (read and
|
||||
recurse), which keeps both under twenty lines.
|
||||
|
||||
The reversal is deliberate and is the plan's: a dangling **source-file** link
|
||||
is warned about and **not** pushed into `files`. §43's review had kept it in
|
||||
the list so the front end's `no such file` error survived; the warning is that
|
||||
error's home now, and it says something the old path could not — that the file
|
||||
is a broken link rather than absent. The walk.rs test and its comment were
|
||||
rewritten to say so. A dangling link that names no source file is still
|
||||
skipped in silence; it was never going to be read.
|
||||
|
||||
Server plumbing: `walked_files` / `folder_files` / `default_files` /
|
||||
`widened_files` each take the sink, and `source_files` collects into the
|
||||
`Scope::warnings` that already existed for a filelist's problems. That road
|
||||
ends at `report_scope`, which logs each line once per scan and shows the first
|
||||
one — the same treatment a filelist's warnings have always had. **Deviation
|
||||
from the plan's letter:** the plan said "through `notification.rs`"; the scan
|
||||
warnings' channel is `server/client.rs`'s `report_scope`, called from
|
||||
`server/index.rs` and `server/mod.rs` where a scan finishes. Inventing a second
|
||||
road for the same class of message would have been worse than using the one
|
||||
that exists. "Once per scan" holds.
|
||||
|
||||
**45.1 — the memo.** `settings::rules` takes the setting's name and a warning
|
||||
sink and describes each dropped name; the lines land in a new
|
||||
`ClientSettings::lint_name_warnings`, kept separate from
|
||||
`lint_option_warnings` because the two are said differently. `apply_settings`
|
||||
logs the lines `Server::said_lint_names` does not hold and then replaces that
|
||||
memo with the current list — which is the whole of "once per (setting, name),
|
||||
re-armed when the setting changes". The options warnings' behaviour is
|
||||
untouched.
|
||||
|
||||
**Gates, all guarded.** `cargo fmt` per touched crate and `cargo fmt --all --
|
||||
--check` clean; `cargo clippy --all-targets` clean; `cargo test --workspace`
|
||||
**3 810 passed, 0 failed, 44 ignored** (baseline 3 788 — 22 new tests);
|
||||
`tools/corpus_check.sh` **814/820**, the same six errors, no verification error
|
||||
and no crash; byte-identity against the trunk binary (built from `git archive
|
||||
HEAD` into the scratchpad, never a checkout in this tree) **860 corpus files,
|
||||
0 diffs** and **3 947 opentitan files, 0 diffs**, with the same 6 and 9 errors
|
||||
either side; `node editors/vscode/smoke.js target/release/lucisv-server` OK;
|
||||
and `target/release/lucisv format --check` over a scratch tree with a `0o000`
|
||||
subdirectory and a dangling `x.sv` link printed exactly two `warning:` lines on
|
||||
stderr before the report, reported the other files, and exited 1 on the
|
||||
formatting alone. `git -C ~/repo/opentitan status --porcelain` shows only the
|
||||
three pre-existing files.
|
||||
|
||||
**Files touched outside the plan's expected set.** Three, all forced by an AST
|
||||
field the round added and each a mechanical pattern update:
|
||||
`crates/vlog_semantic/src/bind/expr.rs` (a `..` in the `MinTypMax` arm),
|
||||
`crates/vlog_semantic/src/bind/item.rs` (`&d.expr` for the gate delay) and
|
||||
`crates/vlog_parser/tests/spans.rs` (both of the same). Nothing else in
|
||||
`vlog_semantic` was changed.
|
||||
|
||||
### 2026-09-05 — lead, at review
|
||||
|
||||
QA's MEDIUM closed in the tree: a *line* comment trailing a gate instance's
|
||||
`,` now ends the line and the next instance continues one level in
|
||||
(`indent(vec![Doc::HardLine])`, the module-instantiation printer's rule); a
|
||||
block comment there stays inline, as the dev's own case table expects. A
|
||||
case in `net_delay_position.cases` pins the repro. The four topo rows are
|
||||
applied.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-05 — QA (Sonnet)
|
||||
|
||||
Build: `cargo build --release -p lucisv -p lucisv_server` clean, up to date
|
||||
with the uncommitted tree at f302b47+.
|
||||
|
||||
**45.1 — the editor's unknown rule name.** Read `settings.rs`,
|
||||
`server/notification.rs`, `server/mod.rs`, `server/tests/settings.rs` in
|
||||
full; behaviour matches the README exactly (memo = previous settings
|
||||
value's own warning list, `lint_option_warnings` untouched, severity words
|
||||
never warned). Added a temporary wire-level test to `tests/e2e.rs`
|
||||
(`talk`, framed JSON-RPC, real binary) driving: push `lucisv.lint.select:
|
||||
["no-tab"]` → open → three `didChange`s each forced through a `flush_dirty`
|
||||
by an interleaved `codeAction` request (four diagnostics passes total,
|
||||
confirmed by counting `textDocument/publishDiagnostics`) → re-push the
|
||||
identical list → push a second typo `nope` → push with the first typo
|
||||
fixed. Result: exactly one `window/logMessage` `lucisv: lucisv.lint.select:
|
||||
unknown rule: no-tab`, nothing across the four diagnostics passes or the
|
||||
identical re-push, exactly one more line for `nope` when it was added,
|
||||
nothing when the first typo was dropped from the list. Test removed after
|
||||
passing (file `tests/e2e.rs` is unchanged, confirmed by `git diff`). Unit
|
||||
tests already in the diff cover the `ignore` typo, an empty `select`
|
||||
falling through §42's ladder with the rule set unchanged, and a severity
|
||||
word (`style`, `warning`) never being reported — read and agree with all
|
||||
three. No findings.
|
||||
|
||||
**45.2 — the walk's warning channel.** Read `walk.rs`, `main.rs`,
|
||||
`tests/cli.rs`, `state.rs` diffs in full, plus `server/client.rs`'s
|
||||
`report_scope` (unchanged — confirmed the "went through `client.rs` instead
|
||||
of `notification.rs`" deviation is real and `report_scope` already does
|
||||
"logged once per scan, one showMessage summary at most" for every existing
|
||||
caller). Built eight hostile scratch trees under the scratchpad and ran the
|
||||
CLI over each through `tools/guard.sh -t 120`:
|
||||
- 0o000 subdirectory: warning on stderr before the report, `format --check`
|
||||
on an already-clean tree exits **0** with the warning still printed
|
||||
(the exact case TODO §45.2 calls out); `format --check` on a tree needing
|
||||
a reformat exits 1 on the formatting alone; `format` (real reformat, on a
|
||||
scratch copy) and `check` both warn and proceed, exit 0.
|
||||
- dangling `x.sv` link: warned, dropped, not handed to the formatter.
|
||||
- dangling link to a non-source name: silent, as specified.
|
||||
- unreadable `.gitignore` (0o000): warned, directory still walked.
|
||||
- a symlink cycle plus an unreadable directory in the same tree: no hang,
|
||||
no crash, the unreadable directory is warned once and the rest of the
|
||||
tree is reported.
|
||||
- **the start directory itself unreadable (0o000)**: `path.is_dir()`
|
||||
succeeds (stat needs only the parent's search bit), so the walk enters,
|
||||
`read_dir` fails, one warning is printed naming the start directory, and
|
||||
the run then fails with the CLI's ordinary `error: no Verilog files
|
||||
found` at exit 2 — sensible, not a crash, not silent. Not covered by the
|
||||
dev's own tests; recorded here since the plan asked "what happens?".
|
||||
- an unreadable file `y.sv` (chmod 0o000, not a directory): reported once,
|
||||
as the pre-existing per-file read error (`error: ...: Permission
|
||||
denied`), *not* as a walk warning — confirmed not duplicated.
|
||||
- 200 unreadable directories under one start: exactly 200 `warning:` lines,
|
||||
the walk finishes, the one real file is still reported.
|
||||
|
||||
Server: adapted the existing `Session`/`Tree` test harness (as
|
||||
`server/tests/*.rs` already does) into a temporary file
|
||||
(`server/tests/qa_scratch_45.rs`, registered and later removed from
|
||||
`server/tests/mod.rs`) to drive `Session::wide` over a tree with one 0o000
|
||||
subdirectory: the warning is logged exactly once via `logged()`, at most
|
||||
one `shown()` `window/showMessage` summary, and pushing a settings change
|
||||
that forces `reindex` (`lucisv.index.maxFileSize` with `scope: "workspace"`
|
||||
kept, mirroring `capping()` in `server/tests/index.rs`) logs the same
|
||||
warning again exactly once. `server/tests/mod.rs` and the deleted scratch
|
||||
file leave no diff (`git diff --stat` confirms only the intended lane
|
||||
files changed). No findings.
|
||||
|
||||
**45.3 — inline aggregate override argument.** Manually formatted a file
|
||||
covering `struct packed`, `union packed` (with two members), `enum`, a
|
||||
`struct packed` with a comment inside, a nested `struct packed` inside a
|
||||
`struct packed`, and the same aggregate as a **positional** override
|
||||
(`m #(struct packed {logic a;}) u5 ();`) — all format correctly (struct/
|
||||
union bodies open, enum stays inline, comment kept), round-trip is a fixed
|
||||
point (`format(format(x)) == format(x)`, byte-for-byte), and the comment
|
||||
survives. Confirmed the illegal expression-position case is unchanged and
|
||||
safe: `assign x = struct packed { logic a; };` still fails with the
|
||||
original `parse error: ... unexpected keyword \`struct\` in expression`
|
||||
under both `format --check` and `format --stdout`, exit 2, no corruption —
|
||||
`parse_expr` (assign's RHS) does not route through `parse_expr_or_type`, so
|
||||
the new door stays shut there exactly as the Assumptions section claims.
|
||||
Ran `vlog_refactor`'s new and neighboring tests directly
|
||||
(`a_one_line_inline_aggregate_default_is_emitted`,
|
||||
`a_multi_line_type_is_shown_on_one_line`): both green, confirming the
|
||||
one-line default is now emitted and the multi-line one is still dropped, by
|
||||
the "written across several lines" rule rather than the grammar. No
|
||||
findings.
|
||||
|
||||
**45.4 — delay-list comment slots.** Read the fixture
|
||||
(`delay_comment_slots.cases`) end to end against the `Promised / changed`
|
||||
table in the Handshakes section: every new field
|
||||
(`MinTypMaxComments`'s four slots, the one-value `Paren`'s two slots,
|
||||
`ContAssign::{after_hash, after_delay}`,
|
||||
`GateInstantiation::{before_hash, after_hash, before_semi}`,
|
||||
`DelayValue::{leading, trailing}`, `GateInstance::before_args`, and
|
||||
`GateInstance::meta.{before_sep, trailing}`) has at least one case, plus a
|
||||
byte-cost-zero case and one line-comment case (the `min:typ:max` colon
|
||||
only). Confirmed `EXPECTED_RTL_GAPS` 419 with the block-comment-per-gap
|
||||
fuzzer at 0 failures (`cargo test -p vlog_formatter
|
||||
a_comment_in_every_rtl_gap_still_formats`).
|
||||
|
||||
**Because the fuzzer and the fixture both probe with `/*block*/` comments
|
||||
only, I attacked every new slot again by hand with `//line` comments** (the
|
||||
plan explicitly asked for "line comments in each slot"). Seven of eight
|
||||
were fine (`before_hash`, `after_hash`, `before_args`, `before_semi`, the
|
||||
one-value delay's two `Paren` slots, `ContAssign::after_hash`,
|
||||
`ContAssign::after_delay` all correctly force a hard line after a line
|
||||
comment via `inline_comments_spaced`/`slot_comments`). The eighth is a
|
||||
**real bug**:
|
||||
|
||||
> **FINDING (MEDIUM) — a line comment trailing a gate instance's `,`
|
||||
> separator corrupts the rest of the statement into the comment; caught
|
||||
> by `verify.rs`, so no bad file is ever written, but `lucisv format`
|
||||
> hard-fails (exit 2) on legal, comment-bearing SystemVerilog that TODO
|
||||
> §45.4 claims this round closes.**
|
||||
>
|
||||
> `crates/vlog_formatter/src/format/instance.rs:400-405` (the gate
|
||||
> instantiation's multi-instance loop, only reached for `i < last`):
|
||||
> ```rust
|
||||
> docs.push(text(","));
|
||||
> if let Some(tr) = &inst.meta.trailing {
|
||||
> docs.push(text(" "));
|
||||
> docs.push(self.comment(tr));
|
||||
> }
|
||||
> ```
|
||||
> Nothing forces a line break after `tr` before the next iteration prints
|
||||
> the following instance's `meta.leading` (a bare `text(" ")` when that is
|
||||
> empty). When `tr` is a line comment, everything the next iteration emits
|
||||
> lands on the same source line, and a line comment runs to end of line —
|
||||
> so on re-lex the rest of the statement disappears into the comment.
|
||||
> `verify.rs` sees the token-stream divergence and correctly refuses to
|
||||
> write the file (invariant 1 upheld; nothing corrupted on disk); the
|
||||
> failure mode is a hard error on valid input, not corrupted output.
|
||||
>
|
||||
> Repro:
|
||||
> ```systemverilog
|
||||
> module m;
|
||||
> and #(2, 3) g0 (y, a), // p
|
||||
> g1 (z, b);
|
||||
> endmodule
|
||||
> ```
|
||||
> `target/release/lucisv format --stdout repro.sv` →
|
||||
> `error: repro.sv: verification failed: token stream diverges at index 17:
|
||||
> input has comment "// p" at 2:26, output has comment "// p g1 (z, b);" at
|
||||
> 2:26`, exit 2. Reproduces with three instances too (the whole remainder,
|
||||
> including a further `,`-separated instance, is swallowed).
|
||||
>
|
||||
> Contrast with the pre-existing, correct pattern four lines above this one
|
||||
> in the same file (`format/instance.rs:64-74`, the *module*-instantiation
|
||||
> multi-instance list), which already does the right thing:
|
||||
> ```rust
|
||||
> 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); }
|
||||
> ```
|
||||
> The gate-instance printer added by 45.4 does not replicate the
|
||||
> `i < last` hard-line-after-trailing-comment rule (or use
|
||||
> `inline_comments_spaced`/`Fmt::trailing`, which both already know a line
|
||||
> comment forces a break).
|
||||
>
|
||||
> Not caught by the dev's own attack tests or the RTL fuzzer because both
|
||||
> only exercise the `before_sep`/`trailing` slot with **block** comments
|
||||
> (`delay_comment_slots.cases`'s last case:
|
||||
> `g0 (y, a) /* before */ , /* after */ g1 (z, b)`). Not a widened
|
||||
> `verify.rs` forgiveness (invariant 4 does not apply — nothing in
|
||||
> `verify.rs` changed), and not a dropped comment (invariant 3 holds —
|
||||
> the whole file is refused, not partially emitted). Severity kept at
|
||||
> MEDIUM rather than HIGH because of that: no corruption reaches disk,
|
||||
> the blast radius is exactly this one slot/comment-kind combination, and
|
||||
> the corpus and opentitan sweeps (neither of which contains this pattern)
|
||||
> are unaffected — confirmed by the unchanged 814/820 and the byte-identity
|
||||
> runs below.
|
||||
>
|
||||
> Suggested fix (for the dev, not applied here per QA's mandate not to
|
||||
> redesign): either call `self.inline_comments_spaced` for the trailing
|
||||
> comment instead of the raw `text(" ")` + `self.comment(tr)` pair (it
|
||||
> already emits `Doc::HardLine` when the comment is a line comment), or
|
||||
> mirror the module-instantiation loop's explicit `if i < last { push
|
||||
> HardLine }` after the trailing comment.
|
||||
|
||||
**Byte-identity and gates (all guarded).**
|
||||
- `cargo clippy --all-targets`: clean.
|
||||
- `tools/guard.sh -- cargo test --workspace`: **3 810 passed, 0 failed, 44
|
||||
ignored** — matches the dev's number exactly.
|
||||
- `tools/guard.sh -- tools/corpus_check.sh`: **814/820**, same six parse
|
||||
errors, 0 verification errors, 0 crashes.
|
||||
- `node editors/vscode/smoke.js target/release/lucisv-server`: OK.
|
||||
- Corpus byte-identity vs `~/.cache/lucisv-baselines/lucisv-0.43.0`:
|
||||
compared `format --stdout` + exit code file by file over all **860**
|
||||
corpus source files (not just the 820 `corpus_check.sh` reports on) —
|
||||
**0 differing**.
|
||||
- Opentitan `format --check` vs the same 0.43.0 baseline over `hw/ip`,
|
||||
`hw/top_earlgrey/ip`, `hw/top_darjeeling/ip`, `hw/dv`, `hw/vendor`:
|
||||
**2 553** source files (not the dev's 3 947 — a different, smaller
|
||||
file-extension/glob accounting was used here; not investigated further
|
||||
since exit codes and normalized stdout/stderr matched exactly either
|
||||
way); every exit code identical, and every stderr line identical once
|
||||
the baseline's incidental `, N files from cache` cache-hit annotation
|
||||
(a pre-existing `.lucisv_cache/` in the opentitan tree, untracked,
|
||||
gitignored, unaffected by which binary populated it) is stripped from
|
||||
both sides — **0 behavioural differences**.
|
||||
`git -C ~/repo/opentitan status --porcelain` after every run: only the
|
||||
three pre-existing modified files (`hw/ip/aes/dv/tb/tb.sv`,
|
||||
`hw/top_darjeeling/ip/ast/rtl/ast.sv`,
|
||||
`hw/top_earlgrey/ip/ast/rtl/ast.sv`).
|
||||
|
||||
**Cleanup.** All scratch trees removed (permissions restored with
|
||||
`chmod -R u+rwx` first). The two temporary test additions
|
||||
(`tests/e2e.rs`, `server/tests/qa_scratch_45.rs` + its `mod.rs`
|
||||
registration) were removed after use; `git diff --stat` shows no lane file
|
||||
touched by this QA pass except this README and the TODO.md checkbox.
|
||||
|
||||
**Verdict: REWORK.** One finding, filed above:
|
||||
- **MEDIUM** — `format/instance.rs:400-405`, a line comment trailing a
|
||||
gate instance's `,` separator (`GateInstance::meta.trailing`, not the
|
||||
last instance) corrupts the rest of the statement into the comment;
|
||||
`verify.rs` catches it and refuses the file rather than writing bad
|
||||
output, but `lucisv format` hard-fails on legal input the round claims
|
||||
to support. Needs a fix plus a line-comment test in
|
||||
`delay_comment_slots.cases` or `verification.rs` before this closes.
|
||||
|
||||
Everything else in 45.1, 45.2 and 45.3 checked out clean against the plan,
|
||||
including the corners the plan called out by name (the start-directory
|
||||
case, the 200-unreadable-directories case, the illegal-expression-position
|
||||
case, severity words never warned, four diagnostics passes, a rescan
|
||||
re-arming the server's log).
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-05 — lead.** Accepted with the rework above; ships in 0.44.0
|
||||
with §46. Four small items, each the shape the plan asked for. The sink
|
||||
choice for the walk (a closure over a struct return) is right for the
|
||||
reason given — both callers accumulate across a loop — and routing the
|
||||
server's scan warnings through the road filelist warnings already take,
|
||||
rather than `notification.rs`, is the better reading of the plan. The §43
|
||||
reversal (a dangling source link is warned about and not handed on) is now
|
||||
correct because the warning has a home. QA's MEDIUM was a real formatter
|
||||
refusal on legal input — the one class of bug the verifier exists to catch,
|
||||
and it did — fixed at review with the rule the sibling printer already had.
|
||||
Byte-identity: 0 of 860 corpus files and 0 of 3 947 opentitan files differ
|
||||
from 0.43.0.
|
||||
@@ -287,8 +287,10 @@ right, and the two together are why nothing in either tree falls back.
|
||||
in-file and through the index, `FACTS_FORMAT` 16
|
||||
- [x] **P5** — the verbatim-SVA rename warning, with both pins (a fallback
|
||||
region warns; a structured one does not)
|
||||
- [ ] **P6 §2.9-18** — the engine half is delivered and pinned; the server
|
||||
fan-out is filed as Handshake request 1 above
|
||||
- [x] **P6 §2.9-18** — the engine half is delivered and pinned; the server
|
||||
fan-out is filed as Handshake request 1 above. **Closed by TODO §29**
|
||||
(2026-09-02): the macro-word census answers the server half without
|
||||
the fan-out; topo §2.9-18 is struck.
|
||||
- [x] **Measurement** — see the work log
|
||||
|
||||
## Design
|
||||
|
||||
@@ -0,0 +1,561 @@
|
||||
# waiver-files
|
||||
|
||||
## Goal
|
||||
|
||||
Findings can be suppressed from *outside* the RTL, in Verible's waiver file
|
||||
format, so a project that already has a `.waiver` file carries it over
|
||||
unchanged and a team can silence a rule for a legacy directory without
|
||||
editing five hundred files. One directive per line —
|
||||
`waive --rule=<rule> [--line=N|--line=N-M] [--location=<pattern>]`, with `#`
|
||||
comments and blank lines ignored — read from `--waiver-file` on the command
|
||||
line, from `waivers` under `[lint]` in a `lucisv.toml`, and from
|
||||
`lucisv.lint.waivers` in an editor. External waivers and the inline
|
||||
`// lucisv: waive` comments are a **union**: a finding either covers is
|
||||
suppressed, and one both cover marks both used. This closes §4's last two
|
||||
waiver items (TODO §39).
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **`--location` is not a regex.** Verible's is; lucisv has no regex engine
|
||||
in the linter's path and deliberately keeps `--exclude`'s glob semantics
|
||||
everywhere a pattern names files. A pattern that *looks* like a regex is
|
||||
refused with a message saying what the difference is, rather than silently
|
||||
matching nothing. The detector is `waiver_file::regex_hint`: `.*`, `.+`,
|
||||
or any of `\ ^ $ [ ] ( ) | ? + { }`. A bare `.` is not a metacharacter —
|
||||
`foo.sv` is a file name. A pattern that is a valid glob *and* looks like a
|
||||
regex (a file with a `+` in its name) is refused; nothing in the corpus or
|
||||
in opentitan has one, and the message tells the user what to write.
|
||||
- **A directive names one rule.** A severity word (`error`, `warning`,
|
||||
`style`) is refused, though `--select`/`--ignore` accept one: a waiver file
|
||||
is checked in, and one word in it quietly silencing a whole class is not
|
||||
something anyone should be able to write by accident.
|
||||
- **`--regex=` is refused by name**, because Verible has it and a user
|
||||
carrying a file over deserves to be told which directive lucisv cannot
|
||||
honour rather than "unknown option".
|
||||
- **Line ranges are `N-M`, inclusive, 1-based**, matching Verible. `N:M` is
|
||||
not accepted.
|
||||
- **A stdin buffer has no path**, so a directive with a `--location` cannot
|
||||
cover it; one without covers it like any other file.
|
||||
- The CLI de-duplicates waiver files by their **canonicalized** path, so the
|
||||
same file named by `--waiver-file` and by a `lucisv.toml` is read once. If
|
||||
canonicalization fails (a path that does not exist) the path as written is
|
||||
the key — and a non-existent path fails the run a line later anyway.
|
||||
- The server reads its waiver files **on every lint pass**, exactly as it
|
||||
already re-reads the buffer's `lucisv.toml` per pass, so a waiver file
|
||||
edited while the editor is open takes effect at the next publish with no
|
||||
cache to invalidate. The cost is a few `read_to_string`s of small files
|
||||
beside a parse and an analysis, and it is zero when nothing is configured.
|
||||
- `lint::fixable` (the code-action path) still runs `default_rules()` with no
|
||||
waivers at all, inline or external — unchanged from before this round. A
|
||||
waived finding was never published, so no lightbulb is offered for it in
|
||||
practice; the mismatch is pre-existing and out of scope here.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed**
|
||||
|
||||
- `lucisv_core::walk::is_excluded` — the `--exclude` matcher, now also the
|
||||
`--location` matcher. **This adds `lucisv_core` as a dependency of
|
||||
`vlog_linter`** (`crates/vlog_linter/Cargo.toml`, with the reason in a
|
||||
comment). `lucisv_core` has no dependencies of its own, so this adds no
|
||||
external code and closes no loop; copying the matcher instead would have
|
||||
meant the two *look* the same and can drift. **This is a new edge for
|
||||
`docs/topo.md`: `vlog_linter ──▶ lucisv_core`.** That file is owned by
|
||||
another process this round, so the edge is recorded here for the lead to
|
||||
apply.
|
||||
- `lucisv_core::config::FileConfig::lint_waivers` — new `Option<Vec<PathBuf>>`
|
||||
field, `[lint] waivers`, resolved against the config file's own directory
|
||||
by `Discovery` exactly as `filelist` is.
|
||||
- `vlog_linter::rule_by_name` / `Severity::from_name` — a directive's `--rule`
|
||||
is validated against the registry at parse time.
|
||||
|
||||
**Promised**
|
||||
|
||||
- `vlog_linter::lint(ctx, rules)` is **unchanged** in signature and behaviour;
|
||||
it now delegates to `lint_with(ctx, rules, &ExternalWaivers::default())`.
|
||||
- `vlog_linter::lint_with(ctx, rules, &ExternalWaivers) -> (Vec<Violation>,
|
||||
WaiverUse)` is the new entry point. The `WaiverUse` half is the caller's to
|
||||
merge across a run and hand back to `ExternalWaivers::unused`.
|
||||
- `vlog_linter::{ExternalWaivers, UnusedReport, WaiverUse}` are public.
|
||||
`ExternalWaivers::read` returns `(waivers, problems)` — a file that cannot
|
||||
be opened is the `Err`, a file with bad *lines* is an `Ok` carrying both —
|
||||
so the CLI can fail the run and the server can drop the line and log it,
|
||||
from one reader.
|
||||
- `vlog_linter::waiver::Waivers::filter` is gone, replaced by
|
||||
`Waivers::covers(rule, line)`; the union has to ask both waiver kinds about
|
||||
every violation, and a `filter` that dropped violations before the external
|
||||
one saw them would have marked only one of a covering pair used. Internal
|
||||
to the crate (`pub(crate)`), so nothing outside moves.
|
||||
- `lucisv_server::state::Workspace::roots()` is new (`&[PathBuf]`), for
|
||||
resolving a relative `lucisv.lint.waivers` entry against the first root the
|
||||
way `filelist_path` does inline.
|
||||
- `lucisv_server::lint::{waiver_paths, external_waivers}` are public so
|
||||
`server/notification.rs` can validate the setting once when it arrives.
|
||||
- `settings::LintSelection` gained a sixth element (the waiver list), so a
|
||||
changed list republishes every open buffer, as a changed option already did.
|
||||
- `lucisv::lint::{plan, check_stdin}`: `check_stdin` takes one more argument
|
||||
(`&ExternalWaivers`); `external_waivers(opts, configs)` is public for the
|
||||
stdin path in `main.rs`.
|
||||
|
||||
**Requested of the lead** (files owned by the concurrent docs process): the
|
||||
`README.md` / docs-site text under "Docs to apply at merge (lead)" below, and
|
||||
the `docs/topo.md` edge above.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] 39.1 `waiver_file.rs` (parse + match) and the union in `lib.rs`
|
||||
- [x] 39.2 discovery: `[lint] waivers`, `--waiver-file`, `lucisv.lint.waivers`
|
||||
- [x] 39.3 unused reporting on the CLI; errors on both front ends
|
||||
- [x] the VS Code setting — **by hand** in `editors/vscode/package.json`:
|
||||
`vlog_linter::vscode` generates only `lucisv.lint.severity.*` and
|
||||
`lucisv.lint.rules.*`, and the drift test
|
||||
(`settings.rs::the_vscode_lint_toggles_match_the_registry`) filters on
|
||||
exactly those two prefixes, so `lucisv.lint.select`, `ignore`, `options`
|
||||
and now `waivers` are hand-written beside them
|
||||
- [x] tests: every directive shape and every error; matching by name, path
|
||||
suffix, line and range; union with an inline waiver; unused reporting;
|
||||
CLI (`--waiver-file` twice, toml + CLI, exit codes); server unit tests;
|
||||
one e2e case over the wire
|
||||
- [x] docs: this README; TODO §4's two waiver lines and §39's own boxes
|
||||
- [ ] QA
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-09-04 (dev).**
|
||||
|
||||
- `crates/vlog_linter/src/waiver_file.rs` (new, ~330 lines with tests): the
|
||||
directive parser, the matcher, `WaiverUse` and the unused report.
|
||||
`waiver.rs` is untouched except that `filter` became `covers` — it is still
|
||||
only the inline story.
|
||||
- The union lives in `lib.rs::waive`, which asks **both** waiver kinds about
|
||||
every violation and never short-circuits: `inline.covers(..) || external
|
||||
.covers(..)` with `||` would have left the second waiver of a covering pair
|
||||
looking dead. There is a test for exactly that in `cli.rs`.
|
||||
- Grammar accepted, exactly:
|
||||
`waive` then any order of `--rule=<rule>` (required, once),
|
||||
`--line=<N>` or `--line=<N>-<M>` (once), `--location=<pattern>` (once).
|
||||
Leading and trailing whitespace ignored, `#` comments and blank lines
|
||||
ignored, CRLF handled (the span arithmetic uses `split_inclusive('\n')` so a
|
||||
`\r` does not shift a directive's reported line). There is no quoting, so a
|
||||
pattern cannot contain a space — the same limitation `.f` filelists have.
|
||||
- Every error message (each prefixed `<file>:<line>: `):
|
||||
- ``expected a `waive` directive, found `<word>` ``
|
||||
- ``` `waive` needs a `--rule=<rule-name>` ```
|
||||
- ``unknown rule `<name>` ``
|
||||
- ``` `--rule=<word>` names a severity class; a waiver names one rule at a time ```
|
||||
- ``` `--line=<v>` is not a line or a line range (`--line=5`, `--line=5-9`) ```
|
||||
- ``` `--line=<v>` starts at 0; lines are numbered from 1 ```
|
||||
- ``` `--line=<v>` counts backwards ```
|
||||
- ``` `--location=<v>` looks like a regular expression (`<token>`); lucisv
|
||||
matches a location the way `--exclude` does — … ```
|
||||
- ``` `--<flag>` is given twice ```
|
||||
- ``` `--regex` is not supported; waive by `--line` or `--location` ```
|
||||
- ``unknown option `<flag>` (the options are `--rule`, `--line` and
|
||||
`--location`)``
|
||||
- ``` `--<flag>` takes a value: write `--<flag>=<value>` ```
|
||||
- ``` `--<flag>` has an empty value ```
|
||||
- and, for a file that cannot be opened at all, `<path>: <io error>`.
|
||||
- CLI: `--waiver-file` is repeatable and lint-only; the run's set is the flag's
|
||||
files in order, then every `[lint] waivers` entry of a config file governing
|
||||
an input, de-duplicated canonically. The first problem fails the run at exit
|
||||
2 before anything is linted, matching a bad `[lint.<rule>]` entry.
|
||||
- Unused external waivers are computed **after** the whole run
|
||||
(`lint::dead_waivers`), from the `WaiverUse` each file's report carries,
|
||||
merged. They are reported as ordinary `unused-waiver` violations against the
|
||||
waiver file, which means they flow through `--output-format json` and the
|
||||
exit code unchanged. A stdin run is a run of one buffer and reports them
|
||||
too.
|
||||
- `check_one`/`run_rules`/`fix_source` grew a `Pass<'a>` struct rather than a
|
||||
seventh and eighth parameter (clippy's `too_many_arguments` was one argument
|
||||
away). Pure plumbing; no behaviour moved.
|
||||
- Under `--fix`, usage accumulates across the fix rounds: a waiver that
|
||||
covered a finding the fix then removed still did its job.
|
||||
- Server: `LintRun` carries an `ExternalWaivers`; `violations_in` calls
|
||||
`lint_with` and discards the usage half, because the server never sees a
|
||||
whole run and must not claim a waiver is dead. The setting's files are read
|
||||
a second time in `apply_settings` purely to log what is wrong with them —
|
||||
once per settings push instead of once per keystroke.
|
||||
- Deviations from the plan, all noted above: the `lucisv_core` dependency in
|
||||
`vlog_linter` (Handshakes), the VS Code setting added by hand rather than
|
||||
through the generator (which does not cover this family of settings), and
|
||||
`editors/vscode/README.md` gaining the setting's row — a file outside the
|
||||
plan's expected touch set, listed below.
|
||||
|
||||
**Gates (all guarded, 2026-09-04)**
|
||||
|
||||
- `cargo fmt -p` clean for `lucisv`, `lucisv_core`, `lucisv_server`,
|
||||
`vlog_linter`; `cargo clippy --all-targets` clean (zero warnings).
|
||||
- `tools/guard.sh -- cargo test --workspace`: **3 764 passed, 0 failed, 44
|
||||
ignored** (3 744 at 0.41.0, plus this round's 20 new tests).
|
||||
- `tools/guard.sh -- tools/corpus_check.sh`: **814/820**, the same six
|
||||
failures as 0.41.0.
|
||||
- `cargo build --release -p lucisv -p lucisv_server`, then
|
||||
`tools/guard.sh -- node editors/vscode/smoke.js target/release/lucisv-server`
|
||||
— OK, 20 messages.
|
||||
- opentitan demonstration, read-only:
|
||||
`target/release/lucisv check --no-cache --select error,warning,style
|
||||
hw/ip/aes/rtl` reports **307** violations; with
|
||||
`--waiver-file <scratch>/opentitan.waiver` holding
|
||||
|
||||
```text
|
||||
waive --rule=dff-name-style --line=226 --location=aes_key_expand.sv
|
||||
```
|
||||
|
||||
it reports **306**, and the one line that disappears is exactly
|
||||
`aes_key_expand.sv:226:12 … [dff-name-style]`. (The *default* rule set finds
|
||||
nothing at all in `hw/ip/aes/rtl`, which is why the demonstration selects
|
||||
every class.) `git -C ~/repo/opentitan status --porcelain` afterwards shows
|
||||
only the three pre-existing modified files.
|
||||
|
||||
**Files touched outside the plan's expected set**
|
||||
|
||||
- `crates/vlog_linter/Cargo.toml` — the `lucisv_core` path dependency.
|
||||
- `crates/lucisv_server/src/state.rs` — `Workspace::roots()`, an accessor.
|
||||
- `crates/lucisv_server/tests/e2e.rs`, `crates/lucisv/tests/cli.rs` — tests
|
||||
the plan asked for.
|
||||
- `editors/vscode/README.md` — the settings table's row for
|
||||
`lucisv.lint.waivers` (`README.md` at the repo root and everything under
|
||||
`docs/site/` were owned by another process this round and are left alone;
|
||||
their text is below).
|
||||
|
||||
## Docs to apply at merge (lead)
|
||||
|
||||
Ready to paste. The first block is for `README.md` (the linter section, after
|
||||
the inline-waiver paragraph) and for
|
||||
`docs/site/src/content/docs/guides/linter.md`.
|
||||
|
||||
```markdown
|
||||
### Waivers
|
||||
|
||||
A finding is suppressed by a comment in the RTL:
|
||||
|
||||
```systemverilog
|
||||
wire a; // lucisv: waive no-tabs
|
||||
// lucisv: waive-start line-length
|
||||
…
|
||||
// lucisv: waive-stop line-length
|
||||
```
|
||||
|
||||
`verilog_lint:` is accepted in place of `lucisv:`, so a Verible-annotated
|
||||
codebase needs no editing.
|
||||
|
||||
It can also be suppressed from **outside** the RTL, in Verible's waiver file
|
||||
format — one directive per line, `#` comments and blank lines ignored:
|
||||
|
||||
```text
|
||||
# every line of every file
|
||||
waive --rule=no-tabs
|
||||
# one line, or a range with both ends included
|
||||
waive --rule=line-length --line=12
|
||||
waive --rule=line-length --line=12-20
|
||||
# only the files a pattern names
|
||||
waive --rule=no-tabs --location=legacy/top.sv
|
||||
```
|
||||
|
||||
`--rule` is required and names exactly one rule — a severity word is not
|
||||
accepted here. `--line` is 1-based. `--location` is matched the way an
|
||||
`--exclude` pattern is: `*` stands for any run of characters *within* one path
|
||||
component, a pattern containing `/` matches a path suffix, and one without
|
||||
matches the file name at any depth. Unlike Verible's, it is **not** a regular
|
||||
expression, and a pattern that looks like one (`.*`, `\.`, `[…]`) is an error
|
||||
naming the difference rather than a pattern that silently matches nothing.
|
||||
|
||||
lucisv reads waiver files from three places, and they **add up**:
|
||||
|
||||
| Where | Paths relative to | Applies to |
|
||||
| --- | --- | --- |
|
||||
| `lucisv check --waiver-file <path>` (repeatable) | the working directory | that run |
|
||||
| `waivers` under `[lint]` in `lucisv.toml` | that `lucisv.toml` | the CLI and the editor |
|
||||
| `lucisv.lint.waivers` in an editor | the first workspace folder | the editor |
|
||||
|
||||
```toml
|
||||
[lint]
|
||||
waivers = [ "waivers/legacy.waiver" ]
|
||||
```
|
||||
|
||||
External waivers and inline ones are a **union**: a finding either covers is
|
||||
suppressed, and a finding both cover leaves neither reported as dead.
|
||||
|
||||
A waiver file that does not exist, or a directive that does not parse, fails
|
||||
`lucisv check` with `<file>:<line>: <message>` and exit 2 — the same treatment
|
||||
a bad `[lint.<rule>]` entry gets. In an editor the bad line is dropped, the
|
||||
rest of the file still applies, and the problem is written once to the lucisv
|
||||
log.
|
||||
|
||||
A waiver that suppressed nothing is itself reported, under the
|
||||
`unused-waiver` rule: an inline one at the comment, an external one at its
|
||||
line of the waiver file. **Only `lucisv check` reports unused external
|
||||
waivers**, and only after the whole run has been linted — a `--location` may
|
||||
name a file the run has not reached yet, and an editor never sees a whole run
|
||||
at all.
|
||||
```
|
||||
|
||||
For `docs/site/src/content/docs/reference/cli.md`, in the `lucisv check`
|
||||
options table:
|
||||
|
||||
```markdown
|
||||
| `--waiver-file <PATH>` | Read waiver directives from this file; repeatable. Adds to whatever `waivers` under `[lint]` in a `lucisv.toml` already names. Relative to the working directory. A missing file or an unparsable directive is an error (exit 2) |
|
||||
```
|
||||
|
||||
For `docs/site/src/content/docs/start/configuration.md`, in the `lucisv.toml`
|
||||
key table and the editor-settings table respectively:
|
||||
|
||||
```markdown
|
||||
| `[lint] waivers` | `[]` | External waiver files, resolved against the `lucisv.toml`'s own directory. Verible's format; see the linter guide's Waivers section |
|
||||
```
|
||||
|
||||
```markdown
|
||||
| `lucisv.lint.waivers` | `[]` | External waiver files, absolute or relative to the first workspace folder; added to whatever `[lint] waivers` names. A missing file or an unparsable directive is logged and dropped. Unused external waivers are reported by `lucisv check` only |
|
||||
```
|
||||
|
||||
And the edge for `docs/topo.md`: **`vlog_linter ──▶ lucisv_core`** —
|
||||
`waiver_file.rs` matches a `--location` with `walk::is_excluded`, the same
|
||||
matcher `--exclude` uses.
|
||||
|
||||
### 2026-09-05 — lead, at review
|
||||
|
||||
QA's HIGH closed in the tree: `lucisv_server::lint::fixable` now takes the
|
||||
buffer's `LintRun` and lints with `lint_with(ctx, run.rules, run.external)`,
|
||||
so a quick fix is never offered — and `source.fixAll.lucisv` never applied —
|
||||
for a finding a checked-in waiver file waived; the code-action entry point
|
||||
takes the run and the dispatch builds it with `LintRun::for_document`. This
|
||||
also stops the code-action path from fixing under `default_rules()` while
|
||||
the diagnostics pass runs the enabled set, a second pre-existing drift.
|
||||
Pinned by `an_externally_waived_finding_gets_no_quick_fix_and_fix_all_leaves_it`.
|
||||
The BOM LOW: a leading U+FEFF is stripped before the first directive is
|
||||
read. The other LOW (a bad line in a file named by `[lint] waivers` is
|
||||
dropped silently in the editor, the editor-setting path is logged) is
|
||||
documented in the applied docs and folded into §42.2, which surfaces every
|
||||
rejected project entry with file and line. The docs in "Docs to apply at
|
||||
merge" are applied to README.md, the linter guide, cli.md, configuration.md
|
||||
and topo.md.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-09-05 (QA).**
|
||||
|
||||
Read the plan (TODO §39), the feature README in full, and the diffs of
|
||||
`crates/vlog_linter/src/{waiver_file.rs,waiver.rs,lib.rs}`,
|
||||
`crates/lucisv_core/src/config.rs`,
|
||||
`crates/lucisv/src/{args.rs,lint.rs,main.rs}`,
|
||||
`crates/lucisv_server/src/{lint.rs,settings.rs,state.rs,server/notification.rs}`,
|
||||
`editors/vscode/package.json` and `editors/vscode/README.md`, and the two test
|
||||
files. Built `cargo build --release -p lucisv -p lucisv_server`, then attacked
|
||||
the grammar, precedence and both front ends by hand, using scratch files under
|
||||
the session scratchpad and read-only runs over opentitan. Every experiment
|
||||
that needed a real request over the wire (server disk re-read, code-action
|
||||
gap) was a temporary `#[test]` appended to `crates/lucisv_server/tests/e2e.rs`,
|
||||
run under `tools/guard.sh`, then removed — `git diff --stat` on that file
|
||||
after removal matches the dev's own 81-line addition exactly, confirming no
|
||||
residue.
|
||||
|
||||
**CLI grammar — all shapes and errors, verified by direct reproduction.**
|
||||
`--rule` alone, `--line=N`, `--line=N-M`, `--location=name.sv`,
|
||||
`--location=dir/name.sv` (suffix), all three together in every order (3
|
||||
permutations tried) — every shape suppresses exactly the finding(s) it should
|
||||
and nothing else. Every error message in the Work Log fires with the
|
||||
`<file>:<line>: message` shape and exit 2: bad keyword, missing `--rule`,
|
||||
unknown rule, severity-as-rule, `--line=0`, `--line=9-5`, non-numeric
|
||||
`--line`, doubled flag, unknown flag, `--regex=`, flag with no value, empty
|
||||
value, a regex-looking `--location` (with the reason named). With three bad
|
||||
lines in one file (line 1 fine, line 2 and 3 both bad), only line 2 is
|
||||
reported — the **first** bad line, confirmed. With two waiver files
|
||||
(`goodA.waiver` clean, `badB.waiver` bad), the error correctly names
|
||||
`badB.waiver`, not a false-positive stop at the first file.
|
||||
|
||||
Edge cases: `--line=5-5` behaves as a one-line range; `--line=1-4` spanning
|
||||
the whole 4-line file waives every occurrence; `--line=100` past EOF is
|
||||
reported `unused-waiver`, never an error; `--location` naming a file absent
|
||||
from the run is reported unused; `--location=f*.sv` and `--location=**/foo.sv`
|
||||
both match via the `--exclude` glob semantics as documented; CRLF endings
|
||||
parse every directive without shifting reported line numbers (multi-line CRLF
|
||||
file tested, both directives fired); a UTF-8 BOM before `waive` is rejected
|
||||
with a (slightly odd but non-corrupting) "found `\u{feff}waive`" message, exit
|
||||
2 — acceptable, not a hazard; tabs between `--rule=`/`--line=`/`--location=`
|
||||
words parse fine (`split_whitespace` handles them); `Waive` (capitalized) is
|
||||
correctly rejected — the grammar is case-sensitive as specified; an empty
|
||||
waiver file contributes nothing and errors nothing; a directory given as
|
||||
`--waiver-file` surfaces the OS "Is a directory" error at exit 2; a
|
||||
non-UTF-8 waiver file is rejected with "stream did not contain valid UTF-8",
|
||||
exit 2. The same waiver file given twice via `--waiver-file` is read once —
|
||||
confirmed by only one `unused-waiver` finding, not two, for a dead directive
|
||||
in it.
|
||||
|
||||
Discovery combinations: `[lint] waivers` in a `lucisv.toml` (resolved
|
||||
against the toml's directory) plus `--waiver-file` (resolved against the
|
||||
cwd) from a **different cwd** than the toml's directory both applied
|
||||
together correctly, suppressing both their respective lines. A `lucisv.toml`
|
||||
pointing at a missing waiver file fails the run with the resolved absolute
|
||||
path and exit 2.
|
||||
|
||||
**Precedence — union, exactly as specified.** A finding covered by both an
|
||||
inline `// lucisv: waive` and a matching external directive is suppressed
|
||||
once, and **neither** is reported unused. An inline waiver covering nothing
|
||||
plus an external one covering the actual finding: the inline is reported
|
||||
`unused-waiver`, the external (which fired) is not. `--select` excluding the
|
||||
waived rule entirely makes the waiver silent (no `unused-waiver`) — consistent
|
||||
with existing inline-waiver behavior and documented in the Assumptions.
|
||||
`--fix` with a waived fixable violation: reproduced on a scratch copy (never
|
||||
opentitan) — the waived line's tab was left untouched while an unwaived tab
|
||||
on another line was fixed in the same run. Exit code and `--output-format
|
||||
json`: an unused external waiver flows through as an ordinary violation
|
||||
(`"filename":"<waiver-file>"`, correct line/column) and contributes to the
|
||||
non-zero exit code.
|
||||
|
||||
**Server, over the wire (temporary e2e tests, removed after).** `[lint]
|
||||
waivers` in a checked-in `lucisv.toml` suppresses a published diagnostic
|
||||
(confirmed both standalone and combined with `lucisv.lint.waivers`).
|
||||
`workspace/didChangeConfiguration` adding, then removing, then re-adding
|
||||
`lucisv.lint.waivers` mid-session updates published diagnostics each time
|
||||
(`[1,2] → [2] → [1,2] → [2]`, 0-based `no-tabs` lines, across four pushes) —
|
||||
no reload needed. A waiver file **edited on disk while the server runs** is
|
||||
re-read: verified by hand-driving the JSON-RPC stream (rather than the
|
||||
`talk()` helper, which writes the whole session before reading anything, so
|
||||
race-free ordering needed manual interleaving) — read the first publish,
|
||||
*then* rewrote the waiver file on disk, *then* sent a no-op `didChange`, and
|
||||
the second publish reflected the new file content with no restart. This
|
||||
matches the Assumptions section's claim exactly. A bad directive in
|
||||
`lucisv.lint.waivers` is logged once via `window/logMessage` (not
|
||||
`showMessage`) when the setting arrives, not once per keystroke — confirmed
|
||||
both by the dev's own e2e test (exactly 2 log lines for one bad rule + one
|
||||
missing file) and by code inspection: `lint::violations_in`/`LintRun::for_
|
||||
document` discard the read's problem list on every pass, so only
|
||||
`notification.rs`'s one-time read at settings-arrival time can log anything.
|
||||
The server never publishes `unused-waiver` for an external waiver, in any of
|
||||
the above scenarios — confirmed.
|
||||
|
||||
One clarification volunteered here since it affects how a reader should
|
||||
weight the "documented" note in the config.rs precedent: a bad `[lint]
|
||||
waivers` entry from a *toml* (as opposed to the `lucisv.lint.waivers`
|
||||
*setting*) is silently dropped by the server with **no log line at all** —
|
||||
`notification.rs::waiver_problems` only inspects the setting's own paths
|
||||
(`FileConfig::default()` is passed, discarding the buffer's real config).
|
||||
This is consistent with the server's pre-existing treatment of a bad
|
||||
`[lint.<rule>]` entry (`lint.rs::configured`'s comment: "dropped here rather
|
||||
than reported... which is where a config error belongs" — i.e. `lucisv
|
||||
check`'s job), so it is not a new inconsistency, but it means a typo in a
|
||||
checked-in `lucisv.toml`'s `[lint] waivers` is invisible in the editor with no
|
||||
log trace at all (only `lucisv check` will ever catch it). Not filing this as
|
||||
a defect since it matches standing precedent, but noting it because the plan
|
||||
text's single sentence ("the server logs it through notification.rs and
|
||||
drops that line, never the file") reads as if it covers all three discovery
|
||||
paths, and it does not — it covers only the editor setting.
|
||||
|
||||
**Opentitan (read-only).** Reproduced exactly: `--select error,warning,style
|
||||
hw/ip/aes/rtl` → **307**; with the `dff-name-style --line=226
|
||||
--location=aes_key_expand.sv` waiver → **306**, and the missing line is
|
||||
confirmed to be `aes_key_expand.sv:226:12 … [dff-name-style]`. Added: the
|
||||
`--location` **suffix** form `aes/rtl/aes_key_expand.sv` → also **306**
|
||||
(same result as the file-name form). A whole-file waiver
|
||||
(`--rule=port-name-suffix --location=aes_wrap.sv`, no `--line`) → **304**
|
||||
(three `port-name-suffix` findings in that file, all gone, zero remaining).
|
||||
A waiver naming a file outside the run (`--location=nonexistent_file_xyz.sv`)
|
||||
produces exactly one `unused-waiver` line. `git -C
|
||||
~/repo/opentitan status --porcelain` after every run showed only the three
|
||||
pre-existing modified files (`hw/ip/aes/dv/tb/tb.sv`,
|
||||
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`).
|
||||
|
||||
**Gates (all guarded).** `cargo fmt --check`: clean. `cargo clippy
|
||||
--all-targets`: clean, zero warnings. `tools/guard.sh -- cargo test
|
||||
--workspace`: **3 764 passed, 0 failed, 44 ignored** — matches the dev's
|
||||
figure exactly. `tools/guard.sh -- tools/corpus_check.sh`: **814/820
|
||||
(99.3%)**, the same six pre-existing failures (one `end`, one identifier, one
|
||||
expression, one declaration/instantiation, one `;`, one lex "number base").
|
||||
`tools/guard.sh -- node editors/vscode/smoke.js target/release/lucisv-server`:
|
||||
OK, 20 messages.
|
||||
|
||||
### Findings
|
||||
|
||||
**HIGH — the code-action path does not honor external waivers, and the
|
||||
Assumptions section understates it.** `lucisv_server::lint::fixable`
|
||||
(`crates/lucisv_server/src/lint.rs:334`, called from
|
||||
`code_action::code_actions`, `crates/lucisv_server/src/code_action.rs:37`)
|
||||
calls the old `lint(&ctx, &default_rules())` rather than `lint_with`, so it
|
||||
never consults `LintRun::external`. **Inline waivers are still respected
|
||||
here** — `lint()` internally still runs `Waivers::collect(ctx)` regardless of
|
||||
the `external` argument, so an inline-waived finding correctly gets no quick
|
||||
fix. **External waivers are not respected at all**, and this is
|
||||
reproducible, not merely theoretical:
|
||||
|
||||
- Reproduction (temporary e2e test, removed after): a buffer with three
|
||||
tabbed lines — one inline-waived (`// lucisv: waive no-tabs`), one
|
||||
externally waived via a `lucisv.toml`'s `[lint] waivers` pointing at a
|
||||
waiver file with `--rule=no-tabs --line=3`, one waived by neither.
|
||||
Published diagnostics correctly show only the un-waived line. A
|
||||
`textDocument/codeAction` request over the whole buffer returns **two**
|
||||
quickfix actions: the un-waived line (expected) **and the externally
|
||||
waived line** (not expected — no action should exist for it at all). Worse,
|
||||
a `source.fixAll.lucisv` request (what an editor's "format/fix on save"
|
||||
sends) **actually rewrites the externally-waived line**, turning its tab
|
||||
into spaces — silently overriding the waiver a team member wrote into a
|
||||
checked-in `lucisv.toml`.
|
||||
- The Assumptions section's claim — "A waived finding was never published,
|
||||
so no lightbulb is offered for it in practice; the mismatch is pre-existing
|
||||
and out of scope here" — is only half right. It is accurate for a finding
|
||||
an *inline* waiver covers (no lightbulb, confirmed). It is **not** accurate
|
||||
for a finding only an *external* waiver covers: `code_actions` never
|
||||
consults the published diagnostics list or the request's `range` against
|
||||
what the client already sees — it recomputes `fixable()` independently and
|
||||
offers/applies whatever it finds, waiver or not. The QA brief's own
|
||||
framing ("it is pre-existing for inline waivers too") does not hold up
|
||||
against this reproduction — the inline case is fine; only the external one
|
||||
is broken, and it is broken in a way that actively edits code
|
||||
(`fixAll`), not merely in a way that could theoretically surface a
|
||||
quickfix nobody clicks.
|
||||
- This does not violate the CLAUDE.md corruption invariant (the output is a
|
||||
valid, idempotent formatting change, just one the team asked to suppress
|
||||
for that line) but it does defeat the stated purpose of an external
|
||||
waiver for anyone with fix-on-save enabled, which is a common editor
|
||||
default. Recommend `fixable` take the buffer's `ExternalWaivers` (already
|
||||
computed once per `LintRun`) the same way `violations_in` does, or, if a
|
||||
fix for 0.42.0 is out of scope, correcting the Assumptions section to state
|
||||
the real risk plainly (external waivers are not honored by the editor's
|
||||
quick-fix or fix-on-save code path) rather than describing it as
|
||||
no-observable-difference.
|
||||
|
||||
**LOW — BOM message is unusual but not a hazard.** A waiver file with a
|
||||
leading UTF-8 BOM produces `` expected a `waive` directive, found
|
||||
`\u{feff}waive` `` (the BOM character embedded verbatim in the error text)
|
||||
rather than a message about the BOM specifically. Exit 2, no corruption, and
|
||||
BOM'd waiver files are not mentioned as a requirement anywhere in the plan —
|
||||
recording this only because the QA brief asked for a BOM to be tried. Not
|
||||
blocking.
|
||||
|
||||
**LOW — documentation precision.** The plan's discovery-rule bullet describes
|
||||
the server logging behavior for a bad waiver line as if it applied uniformly
|
||||
across all three discovery paths; in the implementation it applies only to
|
||||
the `lucisv.lint.waivers` editor setting, and a bad `[lint] waivers` entry
|
||||
from a `lucisv.toml` is silently dropped with no log at all on the server
|
||||
side. This matches the server's existing, unrelated precedent for
|
||||
`[lint.<rule>]` entries, so it is not a code defect, just worth a line in the
|
||||
feature README's Assumptions (or the merge docs) so a future reader is not
|
||||
surprised that only the editor-setting path logs.
|
||||
|
||||
Everything else asked for in the QA brief — every directive shape and error,
|
||||
every precedence combination, `--select`/`--ignore` interaction, `--fix`
|
||||
interaction, server settings roundtrip, disk re-read, toml-via-server,
|
||||
opentitan counts — checked out exactly as designed and documented.
|
||||
|
||||
**Verdict: REWORK** — one HIGH finding (the code-action/fixAll gap for
|
||||
external waivers, and the inaccurate risk description of it in the
|
||||
Assumptions section). Everything else in the feature — the CLI grammar, the
|
||||
CLI's own `--fix`, precedence, discovery, the diagnostics-publishing half of
|
||||
the server, and the opentitan demonstration — is solid and matches the plan
|
||||
precisely. The lead's call on whether the HIGH finding blocks 0.42.0 or ships
|
||||
with corrected documentation and a follow-up item; either way the
|
||||
Assumptions section as written should not stand unchanged, since it asserts
|
||||
something this QA pass showed to be false in the `fixAll` case specifically.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-05 — lead.** Accepted with the rework above; ships in 0.42.0 with
|
||||
§38. The format, discovery and precedence are the ruled ones, and the dev's
|
||||
deviations hold: the `vlog_linter ──▶ lucisv_core` edge is the right price
|
||||
for one pattern language across `--exclude` and `--location` (copying the
|
||||
matcher would have made two), the `Pass` struct is plain plumbing, and the
|
||||
setting joins the hand-written `select`/`ignore`/`options` rather than the
|
||||
generator's per-rule toggles. QA's HIGH was real and is the kind of gap a
|
||||
union has to be checked for at every consumer — the fix routes the last
|
||||
consumer through the run. Unused-waiver reporting on the CLI only, after the
|
||||
whole run, stays as ruled. The opentitan demonstration (307 → 306 by one
|
||||
directive, 304 with a whole-file rule waiver) is the behaviour asked for.
|
||||
@@ -0,0 +1,447 @@
|
||||
# walk cycles
|
||||
|
||||
## Goal
|
||||
|
||||
Two unrelated residues of the repository analysis (finding 3), landed
|
||||
together as TODO §43 because each is small and neither collides with the
|
||||
other.
|
||||
|
||||
**43.1 — a cycle policy for the shared walk.** `lucisv_core::walk` recursed
|
||||
on `Path::is_dir()` with no memory of where it had been. A symlink that
|
||||
points back into the tree it sits in — `a/loop -> ../a`, `a/sub/up -> ..`,
|
||||
the `rtl -> ../shared/rtl` pair a vendored checkout writes twice — made the
|
||||
walk descend forever, one directory deeper each time, until the operating
|
||||
system refused the path. Both front ends share that walk: `lucisv` (and so
|
||||
`format`, `check`, `--check`, `--diff`) and the language server's index scan,
|
||||
where the symptom is not an error message but an index that never comes up.
|
||||
The policy is now **each directory is entered once, by identity**: a symlink
|
||||
naming a directory the walk has already entered is skipped silently, and a
|
||||
symlink naming one it has not is still followed, once. No traversal budget —
|
||||
identity *is* the policy, and a budget would be a second, weaker rule
|
||||
answering the same question differently.
|
||||
|
||||
**43.2 — the net delay's comment slots.** `wire /* c */ #5 w;` and
|
||||
`wire [7:0] /* c */ #1 w;` were refused outright: `NetDelay` had no field for
|
||||
a comment written in front of its `#`, so the comment was printed one node
|
||||
later and `verify.rs` — correctly — refused the whole file (exit 2, no
|
||||
output). `NetDelay` now owns both of its gaps, `before_hash` and
|
||||
`after_hash`, and the `#SKIP` `parser-skips` left in
|
||||
`net_delay_position.cases` is retired.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Directory identity on unix is `(dev, ino)`.** `fs::metadata` follows
|
||||
symlinks, so the link and its target return the same pair, which is exactly
|
||||
the question being asked. Elsewhere (there is no non-unix CI today, but the
|
||||
crate compiles there) it is `fs::canonicalize`, which resolves the same way
|
||||
at the cost of a path lookup. Both are `Option`: a name whose metadata
|
||||
cannot be read is not a directory the walk can enter.
|
||||
- **A hard link is not a cycle, and is not treated as one.** Two hard-linked
|
||||
*files* have one inode and the visited set never sees them: only
|
||||
directories are recorded. (Hard-linked directories are not creatable on any
|
||||
filesystem lucisv runs on.)
|
||||
- **The visited set lives for one `collect_files` call.** Two inputs named on
|
||||
one command line each get their own walk, so a directory reachable from
|
||||
both is still walked twice — unchanged, and the CLI's own path dedup is
|
||||
what answers that (`§41`). Inside one walk the same file reached under two
|
||||
spellings is reported once, under the first spelling that reaches it: entry
|
||||
order is `read_dir` sorted by path, so `link_a/x.sv` wins over `shared/x.sv`
|
||||
and `shared/x.sv` wins over `zlink/x.sv`. This is the same rule §41 already
|
||||
applies to a symlinked *file*.
|
||||
- **A dangling symlink is not an input.** `metadata` fails on it, so it is
|
||||
neither walked nor collected. Before this round a dangling `x.sv` link was
|
||||
collected and failed later, at read time, with a "no such file" error the
|
||||
user did not write.
|
||||
- **The `.gitignore`/`--exclude` decision still comes first.** A cycle inside
|
||||
an ignored or excluded directory is never entered at all, so the visited
|
||||
set never sees it; the ignore rules were not touched.
|
||||
- **A comment in front of a `#` belongs to the delay** (43.2), the way
|
||||
`Typedef::before_name` owns the gap in front of its name: the gap is taken
|
||||
only on the branch that actually consumes the `#`, so a `#` that is not a
|
||||
net delay leaves the comment for whoever comes next.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **`lucisv_core::walk` → `lucisv` and `lucisv_server`** (topo §2.9-8, struck
|
||||
by this round). `collect_files`'s signature is unchanged. What changed is
|
||||
what it returns for a tree containing symlinked directories: it terminates,
|
||||
and a directory reachable under several names contributes its files once.
|
||||
`lucisv_server::state::Workspace::walked_files` is the server's only caller
|
||||
and needed no change — its `sort`/`dedup` still runs, and now has less to
|
||||
do. `vlog_linter` uses `walk::is_excluded` only, which is untouched.
|
||||
- **`vlog_parser::ast::NetDelay` → `vlog_formatter`** (topo §2.9-27, struck).
|
||||
Two new public fields, `before_hash` and `after_hash`, both
|
||||
`Vec<Comment>`. The only constructor is `Parser::parse_net_delay`; the only
|
||||
reader is `Fmt::net_delay`. `vlog_semantic`, `vlog_linter` and
|
||||
`vlog_refactor` do not name the type.
|
||||
- **Not taken:** the gaps *inside* a delay's `#( … )` — `#( /*c*/ 1:2:3 )`
|
||||
and each side of its two `:` — are still refused. They are
|
||||
`parse_delay_values`, shared with a gate instantiation's delay list, and
|
||||
they fail identically outside a net declaration; they belong with the rest
|
||||
of the shared expression machinery in topo §2.9-22, not here. Recorded
|
||||
below and left for a future round.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] 43.1 `Walk::visited`, `Walk::enter`, `dir_id` per platform; `dir()`
|
||||
checks-and-inserts before `read_dir`
|
||||
- [x] 43.1 a dangling symlink is skipped rather than collected
|
||||
- [x] 43.1 unit tests: self-loop, ancestor link from a nested start, two
|
||||
links to one target, a link to a directory not yet walked, a dangling
|
||||
link, a cycle inside an ignored directory
|
||||
- [x] 43.1 CLI test (`--check` over a cyclic tree names each file once)
|
||||
- [x] 43.1 server test (a cyclic workspace scans once and finishes)
|
||||
- [x] 43.2 `NetDelay::before_hash` + `after_hash`, parser and formatter
|
||||
- [x] 43.2 the `#SKIP` in `net_delay_position.cases` retired, three live
|
||||
cases in its place
|
||||
- [x] 43.2 the RTL gap fuzzer covers a net delay (352 → 374 gaps, still zero
|
||||
failures)
|
||||
- [x] Gates: fmt, clippy, workspace tests, corpus, both binaries over a
|
||||
cyclic tree
|
||||
|
||||
## Docs to apply at merge (lead)
|
||||
|
||||
- `docs/topo.md` §2.9-8 — strike: **delivered 2026-09-05 by walk-cycles
|
||||
(TODO §43.1)**: `lucisv_core::walk::Walk` keeps a `visited` set keyed on
|
||||
`(dev, ino)` on unix and the canonical path elsewhere; each directory is
|
||||
entered once, a symlink to a directory already entered is skipped
|
||||
silently, a symlink to one not yet entered is still followed, a dangling
|
||||
symlink is skipped. Both front ends: CLI `--check` over a cyclic tree names
|
||||
each file once; the server's `walked_files` scan finishes.
|
||||
- `docs/topo.md` §2.9-27 — strike: **delivered 2026-09-05 by walk-cycles
|
||||
(TODO §43.2)**: `NetDelay::before_hash` and `after_hash` own the two gaps
|
||||
around the `#`; the formatter prints them inline; the
|
||||
`net_delay_position.cases` `#SKIP` is retired and the RTL gap fuzzer covers
|
||||
the construct. The gaps *inside* `#( 1:2:3 )` remain refused and belong to
|
||||
§2.9-22 (`parse_delay_values`, shared with gate delays).
|
||||
- `docs/repository-analysis.md` finding 3 — annotate as closed by TODO §43.1
|
||||
with the identity policy above, and note that the "no traversal budget"
|
||||
ruling was the lead's.
|
||||
- `docs/features/parser-skips/README.md` — its Assumptions (line ~103),
|
||||
Handshakes (line ~151) and QA log (lines ~343, ~409) describe the net-delay
|
||||
comment as a live `#SKIP` and as a handshake request to `comment-slots`.
|
||||
That request is now answered; a one-line "closed by walk-cycles (TODO
|
||||
§43.2), 2026-09-05" under each is the honest amendment. Not edited here —
|
||||
it is another feature's README, and this lane owns none of it.
|
||||
- `README.md` — no change needed: the walk's user-visible contract
|
||||
(extensions, `--exclude`, `.gitignore`) is unchanged. If a line is wanted,
|
||||
it is in the CLI section: "a symlinked directory is walked once; a cycle
|
||||
terminates".
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-09-05 — dev (Opus 5).**
|
||||
|
||||
*43.1, `crates/lucisv_core/src/walk.rs`.* `Walk` gained
|
||||
`visited: HashSet<DirId>` and one method, `enter`, which is the whole policy:
|
||||
`dir_id(dir).is_some_and(|id| self.visited.insert(id))`. `dir()` calls it
|
||||
first and returns `Ok(())` when it answers false, so a directory already
|
||||
entered costs one `metadata` call and nothing else — no `read_dir`, no
|
||||
ignore-stack push, no recursion. `DirId` is `(u64, u64)` under `#[cfg(unix)]`
|
||||
from `MetadataExt::dev`/`ino`, and `PathBuf` from `fs::canonicalize`
|
||||
otherwise; `dir_id` returns `Option`, and `None` (a dangling link, a
|
||||
directory that vanished mid-walk) means "not entered".
|
||||
|
||||
The entry loop's `path.is_dir()` became one `fs::metadata(&path)` — the same
|
||||
single stat, and it follows symlinks exactly as `is_dir()` did, so a
|
||||
symlinked directory is still recognized as a directory. Three things fall out
|
||||
of having the metadata rather than a bool: `meta.is_dir()` for the walk arm,
|
||||
`meta.is_file()` for the collect arm, and a dangling link (no metadata at
|
||||
all) skipped by the `let … else { continue }` in front of both. The extension
|
||||
test moved into a small `is_source` helper so the collect arm stays one line.
|
||||
|
||||
The one behaviour change beyond termination that a user could notice: a
|
||||
dangling symlink named `x.sv` used to be *collected* and then failed at read
|
||||
time. It is now skipped. That is in the plan's test list ("a dangling symlink
|
||||
is skipped") and is the same judgment as the directory case.
|
||||
|
||||
Six unit tests in `walk.rs`, all `#[cfg(unix)]` because they need real
|
||||
symlinks, over a `TempTree` helper in the test module (the third such helper
|
||||
in the crate — `config.rs` and `cache.rs` have their own; a fourth copy is
|
||||
cheaper than a shared test-support module for two dozen lines). Each of them
|
||||
would have run until the OS refused a path before this change.
|
||||
|
||||
*43.2, three crates.* `NetDelay` gained `before_hash` and `after_hash`.
|
||||
`parse_net_delay` takes the first with `take_gap()` **after** the
|
||||
`cur().is_sym("#")` check — the `gap_before("#")` contract, spelled out
|
||||
rather than called, because the check is already there for the `is_net` gate
|
||||
— and the second with `take_gap()` after the `bump()`.
|
||||
|
||||
`Fmt::net_delay` now owns the separator in front of the delay as well as the
|
||||
delay: it emits the `before_hash` comments *instead of* the plain space when
|
||||
there are any, and the plain space when there are not, so a declaration with
|
||||
no comment there is laid out byte-identically to before. That moved the
|
||||
trailing space off `net` (`text(format!("{net} "))` → `text(net.clone())`)
|
||||
and off the data type, which is why `data_decl` changed shape slightly; the
|
||||
two call sites are now inside the `if let Some(net)` and
|
||||
`if let Some(t) = self.data_type(…)` arms, which is also correct, since a
|
||||
delay is only ever read after a net keyword, and an after-type delay only
|
||||
after a data type that was actually written.
|
||||
|
||||
*Deviation from the plan: `after_hash`.* The plan asks for `before_hash`
|
||||
only, and also asks that the gap fuzzer cover the new slot. Those two are in
|
||||
tension: `assert_no_failing_gaps` demands **zero** failures across a fixture
|
||||
set, and the smallest fixture that exercises `before_hash` (`wire #5 a;`)
|
||||
also contains the gap between `#` and `5`, which had no owner either. So the
|
||||
fixture could not be added without it. `after_hash` is four lines (one field,
|
||||
one `take_gap`, one `slot_comments`) on the same construct, and closes the
|
||||
delay's own gaps completely; the alternative was to leave the fuzzer without
|
||||
a net-delay fixture, which is the thing the plan explicitly asked for. Flagged
|
||||
here for the lead.
|
||||
|
||||
The gaps inside `#( 1:2:3 )` are *not* closed — eight of them, measured with
|
||||
the fixture `wire [7:0] #(1:2:3) b = c;` before it was narrowed to `#1`. They
|
||||
live in `parser/instance.rs::parse_delay_values`, shared with gate
|
||||
instantiation delay lists, fail identically there, and are §2.9-22 shared
|
||||
machinery. The RTL fuzzer fixture is `wire #5 a;` / `wire [7:0] #1 b = c;`,
|
||||
which covers both sides of the type and both new slots; `EXPECTED_RTL_GAPS`
|
||||
352 → 374, zero failures.
|
||||
|
||||
*Files touched outside the plan's expected set.* None beyond what the plan
|
||||
names, with one addition: `crates/vlog_formatter/tests/verification.rs` (the
|
||||
gap fuzzer's fixture and count — the plan says "find how the fuzzer
|
||||
enumerates slots and add this one", which is this file). Full list:
|
||||
`crates/lucisv_core/src/walk.rs`, `crates/lucisv/tests/cli.rs`,
|
||||
`crates/lucisv_server/src/state.rs` (test only),
|
||||
`crates/vlog_parser/src/ast/decl.rs`,
|
||||
`crates/vlog_parser/src/parser/decl.rs`,
|
||||
`crates/vlog_formatter/src/format/decl.rs`,
|
||||
`crates/vlog_formatter/tests/cases/net_delay_position.cases`,
|
||||
`crates/vlog_formatter/tests/verification.rs`, `TODO.md`, this README.
|
||||
|
||||
*Do the tests have teeth?* Asked directly rather than assumed: the `enter`
|
||||
call was short-circuited (`if false && !self.enter(dir)`) and the walk tests
|
||||
re-run. Three of the six failed — the self-loop, the ancestor link and the two
|
||||
links — with paths 31 levels of `a/up/` deep, which is what the OS refuses at
|
||||
rather than a hang. The other three (the sibling link, the dangling link, the
|
||||
ignored cycle) pass either way by construction: they are about the *other*
|
||||
half of the policy. The short-circuit was reverted immediately and the file
|
||||
compared against a copy taken before it; `walk::` is green again.
|
||||
|
||||
*Gates, all guarded.* `cargo fmt --check` on the five touched crates: clean.
|
||||
`cargo clippy --all-targets`: clean, no new `#[allow]`. `cargo test
|
||||
--workspace`: **3 788 passed, 0 failed** (baseline 3 780 + the 8 tests this
|
||||
round adds: 6 in `walk.rs`, 1 CLI, 1 server). `tools/corpus_check.sh`:
|
||||
**814/820 (99.3%)**, the same six failures (five parse, one lex) and the same
|
||||
10 already-clean files. Byte-identity: no corpus file writes a comment before
|
||||
a net delay's `#` — checked with a direct grep over `corpus/`, 0 hits — and
|
||||
the empty-slot path emits exactly the `text(" ")` it did before, so the
|
||||
formatter's output over the corpus cannot have moved; the corpus counts
|
||||
confirm it. `node editors/vscode/smoke.js target/release/lucisv-server`: OK,
|
||||
20 messages. The cyclic scratch tree (a self-link, a `..` link one level down,
|
||||
a `../../..` link three levels down, a second name for one directory, and a
|
||||
dangling `x.sv` link) through both release binaries under
|
||||
`tools/guard.sh -t 120`: `lucisv --check` finishes in ~1s and names its three
|
||||
files once each; an LSP session (initialize with that `rootUri`, `initialized`,
|
||||
one `didOpen`, `workspace/symbol`) finishes in ~1s with each package indexed
|
||||
exactly once. No guard kill anywhere in the round.
|
||||
|
||||
### 2026-09-05 — lead, at review
|
||||
|
||||
QA's MEDIUM (the dangling-symlink change made a "no such file" error
|
||||
silent) is ruled and fixed: a dangling link that *names a source file* is
|
||||
handed on again, so the front end reports it exactly as 0.42.0 did (exit 2);
|
||||
a dangling link to anything else is skipped as the dev wrote. The test is
|
||||
renamed to say both halves. QA's LOW (a link to `/` is followed and the
|
||||
first permission-denied directory aborts the whole walk, dropping the files
|
||||
already found) is pre-existing `?` propagation and is filed as topo §2.9-30
|
||||
together with the warning channel the walk lacks. The opentitan
|
||||
`tlul_adapter_vh.sv` divergence QA root-caused is §41's canonical dedup
|
||||
reporting a same-directory symlink alias once — the intended change, noted
|
||||
in 0.43.0's release notes.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-09-05 — QA (Sonnet).** Built `target/release/{lucisv,lucisv_server}` once
|
||||
and attacked both halves of the round on scratch trees under
|
||||
`tools/guard.sh -t 120`; nothing was ever killed (no memory or wall-clock hit)
|
||||
in this pass.
|
||||
|
||||
*Diff review.* Read `crates/lucisv_core/src/walk.rs`,
|
||||
`crates/vlog_parser/src/{ast,parser}/decl.rs`,
|
||||
`crates/vlog_formatter/src/format/decl.rs`, the two test files, and
|
||||
`crates/lucisv/tests/cli.rs` / `crates/lucisv_server/src/state.rs` line by
|
||||
line against the plan. Traced the `data_decl` reshuffle by hand for the
|
||||
empty-slot case on both sides of the type: `net_delay`'s separator branch
|
||||
degrades to the same `text(" ")` the old unconditional call emitted, so a
|
||||
declaration with neither a delay nor a comment is unaffected — confirmed
|
||||
this holds for the "after_type but no data_type" case too, which cannot
|
||||
arise (`parse_net_delay(is_net, true)` only ever succeeds after
|
||||
`parse_opt_data_type` actually consumed tokens, since an omitted type
|
||||
leaves the `#` for the `before` call to claim first).
|
||||
|
||||
*43.1 — cycle attacks (all via `tools/guard.sh -t 120`, actual wall times
|
||||
well under that in every case).*
|
||||
- Depth 1/2/3 cycles (`a/loop -> a`, `a/b/up -> ..`, `a/b/c/top -> ../../..`):
|
||||
terminate, each file named once. Two-link cycle (`a/x -> ../b`,
|
||||
`b/y -> ../a`): terminates, `ma.sv` and `mb.sv` each reported once, `mb.sv`
|
||||
under the alias spelling `a/x/mb.sv` (first spelling reached, as documented).
|
||||
Chain of 50 symlinked directories collapsing to one target: resolved
|
||||
correctly and fast (single `metadata` call per hop, no manual recursion) —
|
||||
no `ELOOP`, no slowdown.
|
||||
- **Ancestor-of-start escape.** Built `start/out -> ../..` where the target is
|
||||
*outside* `start` entirely (not just the walk's own root) and ran
|
||||
`--check` with `start` as the CLI argument (not its parent). The link is
|
||||
followed once — per the ruling, identity is the policy, not location — and
|
||||
pulls in a sibling file and a grandparent-level file that are not inside
|
||||
`start` at all. It terminates (~1s) because the walk eventually re-enters
|
||||
`start` itself from the other direction and that's already visited. Not a
|
||||
bug — this is the plan's own explicit choice (no budget, `rtl ->
|
||||
../shared/rtl` must keep working) — but it is a real, user-visible
|
||||
consequence: pointing lucisv at a subdirectory can pull in files from
|
||||
outside it if that subdirectory contains an upward-and-back symlink.
|
||||
Flagged as **LOW / informational** for the lead's record, not a defect.
|
||||
- **Link to `/`.** Followed once, as the ruling implies it must be; spent
|
||||
~14.6s doing real `readdir`/`stat` work under `/System`, `/Library`,
|
||||
`/private` etc. before hitting a permission-denied directory, at which
|
||||
point the *entire* run aborted with `error: <original start path>:
|
||||
Permission denied` — none of the user's own files were reported, not even
|
||||
the ones already found. Reproduced this abort-on-any-`read_dir`-error
|
||||
behaviour with a controlled example (`crates/lucisv_core/src/walk.rs`'s
|
||||
`dir()` uses `?` on `read_dir(dir)?.collect::<Result<_,_>>()?`, unchanged
|
||||
by this diff) — it is pre-existing, not introduced by 43.1: the old,
|
||||
cycle-blind walker would have followed `/` identically and hit the same
|
||||
wall. Filed as **LOW / informational**, since it predates this round, but
|
||||
worth the lead's attention because 43.1 is what makes "follow a link
|
||||
outside the tree" a documented, intentional feature rather than an
|
||||
accident — a link to `/` (or to any tree with a permission-restricted
|
||||
subdirectory anywhere under it) now silently costs the *entire* check, not
|
||||
just the linked file. Link to a real bounded tree (`/usr/share`, 250 MB):
|
||||
walked completely in ~1s, correctly found and lex-errored on a
|
||||
coincidentally `.sv`-named file (`vim/vim91/tutor/tutor1.sv`, Swedish
|
||||
locale code) — confirms outside-of-start links are followed and that nothing
|
||||
hangs on a moderately large real directory.
|
||||
- Hard-linked **files**: reported twice, once per directory, confirming
|
||||
identity is directory-only as documented. Two directories with identical
|
||||
content but different inodes: both walked (not deduped) — confirmed
|
||||
content-blind, inode-based identity.
|
||||
- Gitignore interplay: a cycle inside an ignored directory never runs
|
||||
(confirmed — the `loop` symlink inside `build/` was never touched); an
|
||||
ignored symlinked directory name is skipped by that spelling but the real
|
||||
target directory (different name, not itself ignored) is still walked
|
||||
directly — this is unchanged, pre-existing per-spelling ignore matching,
|
||||
not a 43.1 regression; a `.gitignore` inside a followed link's target
|
||||
applies to the walk (its `sub/` pattern correctly hid the target's own
|
||||
subdirectory when reached through the link).
|
||||
- **The dangling `x.sv` behaviour change**, `lucisv format --check dir`
|
||||
with a dangling `x.sv` link, new binary vs.
|
||||
`~/.cache/lucisv-baselines/lucisv-0.42.0`: confirmed exactly as the
|
||||
work log describes — 0.42.0 collects it, fails at read time
|
||||
(`error: .../x.sv: No such file or directory`, exit 2, "1 file would be
|
||||
reformatted, 1 file failed to format"); the new binary skips it silently
|
||||
(exit 1, "1 file would be reformatted", no mention of `x.sv` anywhere).
|
||||
**Finding, MEDIUM, for the lead's ruling** (this is what the plan and
|
||||
TODO explicitly asked for, so not a defect against the dev — but the
|
||||
silence itself is worth a second look): a dangling symlink named like a
|
||||
source file usually means something real broke (a missing vendor drop, a
|
||||
bad checkout), and the user now gets no signal at all instead of a
|
||||
specific, actionable error. The CLI already has a precedent for this exact
|
||||
tension — a missing file named in a `-f` filelist is a **warning on
|
||||
stderr**, changing no exit code — and the same shape (warn, don't fail,
|
||||
don't stay silent) seems like it would keep 43.1's win (no more hard
|
||||
crash on a broken symlink) without losing the signal. Recommend the lead
|
||||
decide whether `walk.rs` should carry a callback/return channel for this
|
||||
one case, or whether silence is accepted as-is.
|
||||
- **Both front ends.** CLI `--check` over a two-directory cyclic tree
|
||||
(`rtl/self -> ../rtl`, `rtl/sub/up -> ..`): 2 files, once each. The same
|
||||
tree over `lucisv_server` (drove the real binary over stdio, same framing
|
||||
`talk_with` uses: `initialize` with that `rootUri` +
|
||||
`workspace/didChangeConfiguration` for the wide index scope +
|
||||
`workspace/symbol` queries): both declared modules found exactly once,
|
||||
finished in-process with no hang. **File counts agree between CLI and
|
||||
server for the same tree (2 and 2).**
|
||||
Explicit file argument that is a symlink to a directory, and a start
|
||||
directory that is itself a symlink: both work, both find the expected
|
||||
file under the given spelling.
|
||||
|
||||
*43.2 — comment-slot attacks, all via `format --stdout`, then idempotency
|
||||
(format twice) and a before/after comment-count check on every shape:*
|
||||
`wire /* c */ #5 w;`, `wire // c` + `#5 w;` on the next line, `wire [7:0]
|
||||
/* c */ #1 b = c;`, `wire # /* c */ 5 w;` (`after_hash`), both slots at once
|
||||
(`wire /* c1 */ # /* c2 */ 5 w;`), two comments in one slot
|
||||
(`wire /* one */ /* two */ #5 w;`), a comment on the after-type side
|
||||
(`wire [7:0] /* c */ #1 b = c;`), `tri`/`wand` with a delay comment,
|
||||
an attribute ahead of the module. All ten: format cleanly, round-trip
|
||||
idempotent, comment count preserved exactly. The refused shapes stayed
|
||||
refused and did **not** corrupt: all four gaps inside `#(1:2:3)` — before
|
||||
`1`, around each `:`, after `3` — still fail with a `verification failed:
|
||||
token stream diverges` error and no output, matching the "not taken" scope
|
||||
in Handshakes (topo §2.9-22). Ran the gap fuzzer directly
|
||||
(`cargo test -p vlog_formatter a_comment_in_every_rtl_gap_still_formats`
|
||||
under guard): passes; confirmed `EXPECTED_RTL_GAPS` is 374 in the tree and
|
||||
that the added fixture (`wire #5 a;\n wire [7:0] #1 b = c;`) genuinely
|
||||
exercises both new slots (both are comment-free in the fixture itself, but
|
||||
the fuzzer inserts a comment into every inter-token gap in turn, which is
|
||||
what raised the count from 352).
|
||||
|
||||
*Gates, all guarded.* `cargo fmt --check` (five touched crates): clean.
|
||||
`cargo clippy --all-targets`: clean, 0 warnings. `cargo test --workspace`:
|
||||
**3 788 passed, 0 failed** — matches the work log exactly. Re-ran just
|
||||
`lucisv_core`'s `walk::tests` in isolation: 17 passed (11 pre-existing + the
|
||||
6 new ones), including the 6 cycle tests as their own filtered run.
|
||||
`tools/corpus_check.sh`: **814/820 (99.3%)**, same 6 failures
|
||||
(`ibex/dv/formal/check/peek/compare_helper.sv`,
|
||||
`ibex/dv/uvm/core_ibex/riscv_dv_extension/riscv_core_setting.tpl.sv`,
|
||||
`ibex/syn/rtl/latch_map.v`,
|
||||
`ibex/vendor/google_riscv-dv/src/riscv_instr_cover_group.sv`,
|
||||
`picorv32/scripts/romload/testbench.v`,
|
||||
`picorv32/scripts/smtbmc/mulcmp.v`), same 10 already-clean files.
|
||||
`node editors/vscode/smoke.js target/release/lucisv-server`: OK, 20
|
||||
messages.
|
||||
|
||||
*Byte-identity vs 0.42.0.* Over the 820-file corpus, each file individually
|
||||
through `format --stdout` (bypasses directory-walk dedup, isolates the
|
||||
formatter itself): **0 differing**, exit codes included. Opentitan
|
||||
`format --check` (using `--no-cache` on both sides after the first pass
|
||||
showed cache-hit-count noise from a shared `.lucisv_cache`; see below) over
|
||||
`hw/ip`, `hw/top_earlgrey/ip`, `hw/top_darjeeling/ip`, `hw/dv`, `hw/vendor`:
|
||||
`hw/top_earlgrey/ip`, `hw/top_darjeeling/ip`, `hw/dv`, `hw/vendor` are
|
||||
byte-identical between the two binaries (including exit codes: 1, 2, 1, 2
|
||||
respectively). **`hw/ip` differs by exactly one file**:
|
||||
`hw/ip/tlul/rtl/tlul_adapter_vh.sv` is reported "would reformat" by 0.42.0
|
||||
and silently absorbed (not reported at all) by the new binary — 1773 vs.
|
||||
1772 files. Root-caused, not a §43 regression: `hw/ip/tlul/rtl` contains
|
||||
`tlul_adapter_shim.sv -> tlul_adapter_vh.sv`, a **symlinked file next to its
|
||||
own target in the same directory**, and `crates/lucisv/src/main.rs`'s
|
||||
`dedup()` (canonical-path fold, keeps the first spelling — this is §41,
|
||||
already in trunk, *not* touched by this diff, and shipped in a release
|
||||
*after* 0.42.0 per the loop order in `TODO.md`) now folds
|
||||
`tlul_adapter_shim.sv`/`tlul_adapter_vh.sv` onto one entry, keeping
|
||||
`tlul_adapter_shim.sv` (alphabetically first) and dropping the other.
|
||||
Reproduced in isolation on a two-file scratch directory
|
||||
(`real.sv` + `shim.sv -> real.sv`) with both binaries, `--no-cache`: 0.42.0
|
||||
reports both, the new binary reports one — confirms this is `main.rs`'s
|
||||
existing dedup (unmodified by 43.1/43.2) becoming visible only because the
|
||||
0.42.0 baseline predates it, not anything in this round's diff. Filed as
|
||||
**informational**, not a §43 finding: the "byte-identity vs 0.42.0" gate is
|
||||
not a clean isolation of this round alone once §41/§42 sit between the
|
||||
baseline and trunk; recommend future rounds diff against trunk-before-the-
|
||||
lane (or the `wip-43` backup already under
|
||||
`~/.cache/lucisv-baselines/`) for a true delta, and use 0.42.0 only for the
|
||||
"nothing has moved since the last *release*" question. Confirmed
|
||||
`git -C ~/repo/opentitan status --porcelain` still shows only the three
|
||||
expected pre-existing modifications (`hw/ip/aes/dv/tb/tb.sv`,
|
||||
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`)
|
||||
after all opentitan runs; `.lucisv_cache/` is gitignored and untouched by
|
||||
this statement either way.
|
||||
|
||||
*Verdict:* **PASS.** No corruption, no idempotency break, no dropped
|
||||
comment, in any attack. Both hard invariants around cycles (identity,
|
||||
no budget) and the two new comment slots hold up under adversarial input,
|
||||
and the refused inside-`#(...)` gaps stay refused rather than silently
|
||||
accepted. Two behavioural points are flagged above for the lead's ruling
|
||||
(the dangling-symlink silence, MEDIUM; the link-to-`/` full-run abort on a
|
||||
permission wall, LOW/pre-existing) plus one informational note on the
|
||||
baseline choice for byte-identity gates — none of them block this round.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-05 — lead.** Accepted; ships in 0.43.0. 43.1 is the ruled policy
|
||||
in one method — identity is the whole rule, and QA's cycles of every shape,
|
||||
the 50-link chain and the two-link cycle all terminate with each file once.
|
||||
The dev's `after_hash` slot beyond the plan is accepted: the gap fuzzer's
|
||||
zero-failure bar made it necessary, and four lines on the same construct is
|
||||
the right size; the `#(1:2:3)` interior stays §2.9-22's. The one behaviour
|
||||
change QA flagged is corrected above so no user loses an error they had.
|
||||
Both front ends share the walk unchanged in signature, and the byte-identity
|
||||
gate over the corpus is 0 differing.
|
||||
@@ -0,0 +1,29 @@
|
||||
# Manual extension-host acceptance — checklist
|
||||
|
||||
The one test of the VS Code extension that is not `editors/vscode/smoke.js`.
|
||||
Run it on a release build (`code --install-extension lucisv-<v>-darwin-arm64.vsix --force`)
|
||||
with `/Users/guoliangchen/repo/opentitan` open as the workspace. About an
|
||||
hour. Record the release, the date and any failure in the table at the end.
|
||||
|
||||
| # | Step | Expected |
|
||||
|---|---|---|
|
||||
| 1 | Open `hw/ip/aes/rtl/aes.sv`. Status bar. | "lucisv" item appears; no error toast; Output → lucisv shows the server version. |
|
||||
| 2 | Wait for the scan bar to finish. Hover `aes_core` in an instantiation. | Hover card with the module's header and file:line; F12 jumps to `aes_core.sv`. |
|
||||
| 3 | Insert a tab at the start of a line. | A `no-tabs` squiggle within a second; lightbulb offers "Replace tab"; fix-on-save (`editor.codeActionsOnSave` with `source.fixAll.lucisv`) removes it. Undo. |
|
||||
| 4 | Cursor on `.clk_i` in an instantiation; open the lightbulb. | Port refactorings listed instantly (no hitch); picking one applies an edit (undo). |
|
||||
| 5 | Format Document (Shift+Alt+F) on `aes.sv`. | Reformats without an error toast; Format again is a no-op. Undo all. |
|
||||
| 6 | Settings → search "lucisv.lint". | Every rule has a toggle; `severity.style` off removes all style squiggles immediately. Restore. |
|
||||
| 7 | Add `[lint] select = ["no-tabs"]` in a scratch `lucisv.toml` beside the file. | Only `no-tabs` diagnostics remain; removing the file restores the defaults. |
|
||||
| 8 | Theme: switch Dark+ → Light+ → High Contrast. | Semantic highlighting readable in all three; no invisible tokens. |
|
||||
| 9 | Zoom: View → Appearance → Zoom In ×3, then reset. | Hierarchy view and hover cards scale; nothing clipped. |
|
||||
| 10 | Keyboard only: `Ctrl+Shift+O` (symbols), `F12`, `Shift+F12`, `F2` rename, `Esc`. | Every action reachable without the mouse; rename preview shows all files. |
|
||||
| 11 | Screen reader (VoiceOver, ⌘F5): tab through the lucisv hierarchy view. | Each row announced with its name; the toggle buttons announced. Turn VoiceOver off. |
|
||||
| 12 | Old server: point `lucisv.server.path` at `~/.cache/lucisv-baselines/lucisv-0.39.0`'s sibling server if kept, else skip. | Extension warns about the version mismatch and still works. Reset the setting. |
|
||||
| 13 | The other VSIX shape: install the `lucisv-<v>-universal.vsix` (no bundled server) with the CLI on PATH. | Same behaviour as steps 1–5. |
|
||||
| 14 | Restart the server (command palette: "lucisv: Restart Server"). | Diagnostics return within a few seconds; no duplicate status items. |
|
||||
|
||||
## Runs
|
||||
|
||||
| Release | Date | Result | Failures (step, what happened) |
|
||||
|---|---|---|---|
|
||||
| | | | |
|
||||
@@ -709,6 +709,37 @@ subsuming folder is twenty times the old scope, skipping the overlap saves 5 %.
|
||||
What the round bought is in the landing figure, and it grows with the workspace's
|
||||
vocabulary — which is why the opentitan table above is the one that matters.
|
||||
|
||||
## Measurement round — take 3 on opentitan (2026-09-05)
|
||||
|
||||
`docs/performance_take3.md` — 0.43.0 (`73799f3`) against a 0.39.0 server built
|
||||
from the tag for the comparison, plus the first CLI sweeps (`format --check`
|
||||
and `check` over five opentitan trees, 0.39.0 / 0.41.0 / 0.43.0, wall clock and
|
||||
peak RSS). Read-only round: nothing was fixed, findings were filed.
|
||||
|
||||
The three headline numbers:
|
||||
|
||||
- **`codeAction` on the hot path: 37 ms → 5 ms** at the `aes` cursor and
|
||||
**185 ms → 16 ms** at a 128-file fan-out, for a client that advertises
|
||||
`codeAction.resolveSupport` — §37.1's lazy offer, and it is flat in the
|
||||
fan-out where the eager path is linear in it. The whole hot path is now
|
||||
inside the frame budget; `codeAction` leaves the queue-blocking table it
|
||||
headed in both earlier takes.
|
||||
- **The first RTL `didOpen` at the shipped default: 1 411–1 568 ms →
|
||||
365 ms warm.** Take 2 called this "the wave's one real regression"; round 8
|
||||
above plus the index cache took it apart, and 0.39.0 already measures it, so
|
||||
it is closed.
|
||||
- **The CLI is 0.6 s for `format --check` over `hw/ip`'s 1 807 files** and
|
||||
0.40 s to lint them, at ~230 MB peak RSS — essentially flat across the three
|
||||
binaries.
|
||||
|
||||
Three findings filed, none fixed: the **eager** `codeAction` path (a client
|
||||
without `resolveSupport`) is ~1.37× slower than take 2 at every fan-out, and
|
||||
0.39.0 already shows it; a `didOpen` of a file already in scope delays the next
|
||||
request by 21–51 ms where take 2 measured 2–4 ms; and `lucisv check` is 6–10%
|
||||
slower than 0.39.0 (0.367 → 0.400 s on `hw/ip`). Take 3 also has something
|
||||
neither earlier take did — **a server-side column**, from the shipped
|
||||
`--verbose` flag, which confirms the wire numbers to within 0.4 ms.
|
||||
|
||||
## What it would take to go faster
|
||||
|
||||
Ranked by what the measurements above say is there, with what each would
|
||||
@@ -1047,3 +1078,34 @@ for one keystroke in a 10 000-line buffer, roughly 30 ms of it lex and parse.
|
||||
That is the figure any incremental-parsing proposal has to be argued against,
|
||||
and it now exists.
|
||||
|
||||
|
||||
### 2026-09-05 — the `didOpen` delay (TODO §46, 0.44.0)
|
||||
|
||||
Take 3's §8.4 (a `didOpen` of an already-indexed file delaying the next
|
||||
request by 21–51 ms) measured and fixed. The breakdown, taken with temporary
|
||||
timings on a release build and re-taken after: the tolerant parse plus the
|
||||
semantic analysis is 1.3 / 3.0 / 91 ms for a 326- / 1 145- / 42 192-line
|
||||
opentitan file, and the lint pass was 4.9 / 54 / 1 654 ms — of which
|
||||
`undriven-net` alone was 4.4 / 52 / 1 608. The rule asked
|
||||
`WorkspaceIndex::files_mentioning` (a walk over all 3 976 indexed files) once
|
||||
per declaration, ahead of the local guards that silence almost all of them.
|
||||
Moved behind them, where `unused-signal` has always asked.
|
||||
|
||||
Wire time, `didOpen` → the request behind it, workspace scope, warm store,
|
||||
three tries, M1 Max:
|
||||
|
||||
| file | before | after |
|
||||
|---|---|---|
|
||||
| `aes.sv` (326 L) | 8.1 / 5.9 / 10.1 ms | 4.3 / 1.8 / 2.3 ms |
|
||||
| `aes_core.sv` (1 145 L) | 56.2 / 54.0 / 48.0 ms | 5.9 / 6.9 / 6.3 ms |
|
||||
| `hmac.sv` | 56.8 / 42.7 / 51.0 ms | 4.7 / 5.7 / 3.3 ms |
|
||||
| `kmac.sv` | 69.3 / 72.1 / 70.6 ms | 7.9 / 5.3 / 8.8 ms |
|
||||
| `spi_device.sv` | 94.2 / 103.4 / 88.6 ms | 6.0 / 8.6 / 8.7 ms |
|
||||
| `pinmux_reg_top.sv` (42 192 L) | 1 742 / 1 740 / 1 757 ms | 116.5 / 116.2 / 117.3 ms |
|
||||
|
||||
The same cost was paid on **every keystroke flush**, not just on opens: the
|
||||
change debounce ends in the same `set_document` + `publish` pair. 0.39.0
|
||||
measures the same as 0.43.0 everywhere in the "before" column, so this was
|
||||
never a regression — the rule had been ordered that way since it was
|
||||
written. Published diagnostics are byte-identical before and after. Full
|
||||
account: `docs/features/didopen-cost/README.md`.
|
||||
Loaded 100 of 151 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user