Compare commits

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

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

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

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

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

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 03:40:12 -07:00
lucioandClaude Fable 5 965c4ee25a TODO §33/§34 planned: linter expansion — severities, per-rule VS Code toggles, Error/Warning-class rules (wave 1); the Style class and per-rule options (wave 2)
ci / checks (push) Successful in 1m4s
ci / corpus (push) Successful in 29s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 02:57:31 -07:00
88 changed files with 8574 additions and 222 deletions

No files matched your search

+24
View File
@@ -4,6 +4,30 @@ All notable changes to lucisv are recorded here. Versions follow
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
(see `README.md`) are the only frozen contract.
## 0.35.0 — 2026-09-02
### Format fences reach statements and class bodies
`// verilog_format: off` / `// lucisv: off` (and the `lucisv:` spelling)
now protect statements inside `begin … end`, `fork … join`, function
and task bodies and `always`/`initial`/`final` blocks, and items inside
a class body — not only items at module scope. A fenced region is
copied byte for byte, keeps its own indentation, and is a fixed point
under a second pass; an unmatched `off` runs to the end of its own
list. `--lines` range formatting honours a fenced statement inside the
selected range. Four opentitan files that already carried fences inside
functions and class bodies now keep those bytes.
One rule is applied uniformly: a fence must start its line (whitespace
or a finished block comment may precede it). A fence written after code
on the same line — `module m; // lucisv: off` — is an ordinary comment,
as the fence documentation has said since the feature shipped; it used
to open a region at module scope by accident.
Not yet fenceable, with reasons in the feature README: port lists,
case-item label lists, same-line fences, and a property's local
declarations.
## 0.34.0 — 2026-09-02
### Rename tells you what it could not reach
+14
View File
@@ -128,6 +128,20 @@ Rules:
- Update `TODO.md`: check items your feature completes (leave the item
text intact).
## Runaway guard (never run a suite or sweep bare)
On 2026-09-03 a background test run consumed 100 GB and crashed the
machine. macOS enforces no memory cap, so the cap is ours:
`tools/guard.sh [-m GB] [-t SECONDS] -- <command>` kills a command's
process tree when its resident set or wall clock exceeds the limits
(defaults 8 GB / 30 min).
- **Every `cargo test`, every fuzzer, every corpus or opentitan sweep,
and every `lucisv`/`lucisv-server` run over a tree goes through
`tools/guard.sh`** — dev, QA and lead alike, foreground or background.
- A guard kill is a finding: report the command and the limit it hit;
do not raise the limit to make it pass.
## Parallel lanes (the 2-agent loop)
Up to **two dev/QA lanes may run concurrently** when — and only when —
Generated
+8 -8
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.34.0"
version = "0.36.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.34.0"
version = "0.36.0"
[[package]]
name = "lucisv_server"
version = "0.34.0"
version = "0.36.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.34.0"
version = "0.36.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.34.0"
version = "0.36.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -264,11 +264,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.34.0"
version = "0.36.0"
[[package]]
name = "vlog_refactor"
version = "0.34.0"
version = "0.36.0"
dependencies = [
"vlog_parser",
"vlog_semantic",
@@ -276,7 +276,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.34.0"
version = "0.36.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.34.0"
version = "0.36.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+103 -27
View File
@@ -172,11 +172,13 @@ would format — same walk, same `--exclude`, same `.gitignore` handling, same
`lucisv.toml` discovery.
```bash
lucisv check rtl/ # FILE:LINE:COL: message [rule-name]
lucisv check rtl/ # FILE:LINE:COL: severity: message [rule]
lucisv check --output-format json rtl/ # one JSON array, for editors and CI
lucisv check --select no-tabs rtl/ # only these rules (comma-separated)
lucisv check --ignore module-filename rtl/ # everything but these
lucisv check --select error rtl/ # a whole severity class, by name
lucisv check --fix rtl/ # apply the safe fixes, write files back
lucisv check --rules-doc # the generated reference for every rule
```
Exit codes are the frozen contract above: 0 clean (or everything fixed), 1
@@ -184,28 +186,84 @@ violations remain, 2 error. Unlike the formatter, `check` uses the
error-tolerant parser, so a file lucisv cannot fully parse is still linted for
what it can see.
| Rule | Fix | What it wants |
### Severities
Every rule is in one of three classes, and the class is the word that stands
in the diagnostic line, in the JSON `severity` field, and in the editor's
squiggle colour:
| Class | Means | Editor |
|---|---|---|
| `no-tabs` | safe | spaces, not tabs (a tab inside a string is left alone) |
| `no-trailing-whitespace` | safe | nothing but code before the newline |
| `case-missing-default` | — | every `case`/`casex`/`casez` has a `default` |
| `always-ff-non-blocking` | — | `<=` inside `always_ff` |
| `always-comb-blocking` | — | `=` inside `always_comb` |
| `explicit-parameter-storage-type` | — | `parameter int W = 8`, not `parameter W = 8` |
| `module-filename` | — | a one-module file is named after its module |
| `unused-waiver` | — | waivers that suppress nothing |
| `unused-signal` † | — | no net or variable nothing uses |
| `undriven-net` † | — | everything read is driven by something |
| `multiply-driven` † | — | one driver per variable |
| `error` | would very likely fail to compile, elaborate or synthesize | red (LSP Error) |
| `warning` | compiles, and very likely does not mean what it says | yellow (LSP Warning) |
| `style` | correct, and reads badly | blue (LSP Information) |
A class name is accepted **wherever a rule name is** — on `--select`, on
`--ignore`, and in `select`/`ignore` under `[lint]` in `lucisv.toml`:
```bash
lucisv check --select error rtl/ # only the compile-breakers
lucisv check --ignore style rtl/ # everything but the naming rules
```
Every `error`-class rule follows one discipline: **silence beats a wrong
accusation**. Each of them goes quiet whenever the run cannot answer — a file
that did not fully parse, a module the project does not hold or holds twice, a
name a macro produces, a fragment written to be `` `include``d. That is what
makes an editor's red squiggle worth believing.
### The rules
| Rule | Severity | Fix | What it wants |
|---|---|---|---|
| `multiply-driven` † | error | — | one driver per variable |
| `wire-reg-mixup` | error | — | `logic`, not `reg`, in a `.sv` file |
| `mismatched-labels` | error | — | `end : name` names the block it closes |
| `duplicate-declaration` | error | — | each name declared once per scope |
| `undeclared-identifier` † | error | — | every name is declared somewhere in the project |
| `unknown-port` † | error | — | `.name(…)` is a port the module declares |
| `unknown-parameter` † | error | — | `#(.NAME(…))` is a parameter it declares |
| `always-ff-non-blocking` | warning | — | `<=` inside `always_ff` |
| `always-comb-blocking` | warning | — | `=` inside `always_comb` |
| `case-missing-default` | warning | — | every `case`/`casex`/`casez` has a `default` |
| `incomplete-assignment` | warning | — | an `always_comb` assigns on every path |
| `suspicious-semicolon` | warning | — | no `if (x);` / `for (…);` / `while (…);` |
| `forbid-defparam` | warning | — | override at the instantiation, not with `defparam` |
| `invalid-system-task-function` | warning | — | no `$random`, `$psprintf`, `$dist_*`, `$srandom` |
| `plusarg-assignment` | warning | — | `$value$plusargs`, not `$test$plusargs` |
| `truncated-numeric-literal` | warning | — | a sized literal fits its width |
| `undersized-binary-literal` | warning | safe | every bit of a sized binary literal is written |
| `packed-dimensions-range-ordering` | warning | — | a packed dimension is `[N-1:0]` |
| `forbid-negative-array-dim` | warning | — | no negative literal in a dimension |
| `module-port` | warning | — | more than one port is connected by name |
| `module-parameter` | warning | — | more than one parameter is overridden by name |
| `explicit-function-task-parameter-type` | warning | — | every tf argument has a storage type |
| `void-cast` | warning | — | `void'(…)` wraps a call |
| `instance-shadowing` | warning | — | no declaration hides an enclosing one |
| `undriven-net` † | warning | — | everything read is driven by something |
| `unused-signal` † | warning | — | no net or variable nothing uses |
| `no-tabs` | style | safe | spaces, not tabs (a tab inside a string is left alone) |
| `no-trailing-whitespace` | style | safe | nothing but code before the newline |
| `empty-item` | style | safe | no `;` standing where an item belongs |
| `explicit-parameter-storage-type` | style | — | `parameter int W = 8`, not `parameter W = 8` |
| `module-filename` | style | — | a one-module file is named after its module |
| `enum-name-style` | style | — | `lower_snake_case` ending `_e`/`_t` |
| `struct-union-name-style` | style | — | `lower_snake_case` ending `_t` |
| `parameter-name-style` | style | — | `CamelCase` or `ALL_CAPS` |
| `module-name-style` | style | — | `lower_snake_case` (off by default) |
| `unused-waiver` | style | — | waivers that suppress nothing |
† On by default when lucisv can see a project (a multi-file CLI run or the
language server), and off for a single file or stdin unless `--select` names
them. These three read the file's *symbol table*, not just its syntax; the
project-wide identifier census keeps a hierarchical use in another file from
becoming a false positive. See `docs/features/semantic-lints-on/README.md`.
The table above is not the whole set — naming-style rules ship too, and
`cargo run -p vlog_linter --example rules_markdown` prints the generated
reference for every rule with its default.
them. These rules read the file's *symbol table* and ask the project about
names, not just the file's syntax; the project-wide identifier census keeps a
hierarchical use in another file from becoming a false positive. See
`docs/features/semantic-lints-on/README.md` and
`docs/features/linter-expansion-1/README.md`.
`lucisv check --rules-doc` prints the whole reference — every rule, its class,
its default, its fix and the paragraph saying why it exists — generated from
the registry, so it can never be out of date.
Fixes follow ruff's applicability model: `--fix` applies *safe* fixes (those
that cannot change what the code means), `--unsafe-fixes` widens that — no
@@ -302,8 +360,8 @@ both layouts are fixed points of re-formatting:
### Turning the formatter off
Items between a `// verilog_format: off` and a `// verilog_format: on`
comment are emitted as the exact source bytes they were written with,
Everything between a `// verilog_format: off` and a `// verilog_format: on`
comment is emitted as the exact source bytes it was written with,
indentation included — the escape hatch for hand-aligned tables and the
like. `// lucisv: off` / `// lucisv: on` is an accepted alias.
@@ -317,12 +375,30 @@ module m;
endmodule
```
The fence must be a line comment on its own line, and its text must match
exactly — `// lucisv: off for now` is an ordinary comment, not a fence. An
`off` with no matching `on` runs to the end of the enclosing item list
(module body, package body, generate block, or the file). Fences select
whole items; one written between two *statements* has no effect yet. Full
rules: `docs/features/format-fences/README.md`.
A fence works between **items** — module, package and class members, and
top-level items — and between **statements**: inside `begin`…`end`,
`fork`…`join*`, and function, task, `initial`, `always` and `final` bodies.
```systemverilog
class scoreboard;
function void build_phase();
// verilog_format: off
uvm_config_db#(cfg_t)::set(this, "env.agent", "cfg",
cfg.agent_cfg); // hand-wrapped, left alone
// verilog_format: on
endfunction
endclass
```
The fence must be a line comment that begins its own line, and its text must
match exactly — `// lucisv: off for now` is an ordinary comment, not a fence,
and so is one written after code on the same line (`wire a; // lucisv: off`,
`begin // lucisv: off`). An `off` with no matching `on` runs to the end of the
enclosing list and no further: the module body, the class body, the
`begin`…`end`, the function body, or the file. A fence inside a port list, a
parameter list or a `case` **label** list is still an ordinary comment. Full
rules: `docs/features/format-fences/README.md` and
`docs/features/statement-fences/README.md`.
### Range formatting (`--lines`)
+211 -7
View File
@@ -3314,14 +3314,21 @@ READMEs, README.md "Turning the formatter off", docs/topo.md §2.9-3
struck (lead), TODO §31. Runs after §29/§30 merge (format/ collides
with §30's routine.rs only at merge; disjoint files otherwise — the
lead may start it in parallel if §30's files are settled).
- [ ] 31.1 class bodies (+ any other item-list carrier), cases, §2.9-3
- [ ] 31.2 statement lists: scan, merge, `stmt_seq`/`stmt` rules,
line-start gate, trailing-comment end, range planner re-check
- [ ] 31.3 docs rewritten (format-fences README, README.md, the
- [x] 31.1 class bodies (+ any other item-list carrier), cases, §2.9-3 —
`Interface`/`Program` are `ItemKind::Module` and were already scanned,
there is no `Checker` node, and `PropSeqDecl.locals` is deferred (it is
the one `Vec<Item>` not printed through `item_seq`)
- [x] 31.2 statement lists: scan, merge, `stmt_seq`/`stmt` rules,
line-start gate, trailing-comment end, range planner re-check — the
planner now merges `collect`'s fences into `Plan.regions`, without
which `--lines` would have reformatted a fenced statement
- [x] 31.3 docs rewritten (format-fences README, README.md, the
inverted case), deferrals listed with reasons
- [ ] Attack pairs + the fences.rs triple per scope; verify.rs untouched
- [ ] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
byte-identical; opentitan fence census + sweep
- [x] Attack pairs + the fences.rs triple per scope; verify.rs untouched
- [x] Gates: fmt/clippy/`cargo test --workspace` 3 244/0/42 (was
3 234/0/42); corpus 814/820, 860 files byte-identical to the 0.34.0
binary; opentitan census 9 fenced files of 3 947 — 4 moved, each
keeping its own fenced bytes, `--check` counts unchanged
- [ ] QA: fences in every statement scope listed and in the three
deferred places (must be inert, never corrupt); an `off` with no
`on` in each scope (runs to the scope end only); nested fences;
@@ -3468,3 +3475,200 @@ formatter collide with §30's tf.rs/module.rs at merge; sequential).
an opentitan file and read the published diagnostics and the
outline; the fuzzers re-run; strict-mode parity re-derived
## 33. Linter expansion, wave 1 (planned 2026-09-02) — severities, per-rule editor toggles, and the Error/Warning-class rules
Owner's ask: expand the linter toward what Verible's linter covers (62
rules, https://chipsalliance.github.io/verible/lint.html), expose every
rule in VS Code as a toggle grouped by severity so a user can enable or
disable rules one at a time or a whole severity at once, and put the
style rules and the "would likely fail to compile or synthesize" rules
first. Today: 17 rules, no severity notion (`Rule` has `name`,
`summary`, `doc`, `default_on`, `needs_workspace`, `fix`, `check`), every
editor diagnostic is `WARNING`, the editor surface is
`lucisv.lint.select`/`ignore` lists. Dev Opus 5, QA Sonnet 5. Feature
README: `docs/features/linter-expansion-1/README.md`. Runs in a
worktree in parallel with §31 (fences: `vlog_formatter`, README.md's
"Turning the formatter off" section only); this lane owns
`vlog_linter`, `lucisv/src/lint.rs` + args, `lucisv_server/src/
{settings,lint}.rs`, `editors/vscode/{package.json,README.md}`, README.md's
"Linting" section, `docs/site/.../reference/rules.md`.
**33.0 Severity, end to end.**
(a) `vlog_linter`: `pub enum Severity { Error, Warning, Style }` with
`as_str` (`error`/`warning`/`style`) and `Rule::severity(&self) ->
Severity` (no default — every rule states it; the reason goes in the
rule's `doc`). Assignments for the 17: **Error** — `multiply-driven`
(two procedural drivers of one variable is an elaboration error in
SystemVerilog), `wire-reg-mixup` (a procedural assignment to a net is a
compile error); **Warning** — `always-comb-blocking`,
`always-ff-non-blocking`, `case-missing-default`, `undriven-net`,
`unused-signal`; **Style** — `empty-item`, `enum-name-style`,
`explicit-parameter-storage-type`, `module-filename`,
`module-name-style`, `no-tabs`, `no-trailing-whitespace`,
`parameter-name-style`, `struct-union-name-style`, `unused-waiver`.
`Violation` carries the severity (set by the runner from the rule, not
by each rule). (b) `select_rules(select, ignore, …)` accepts a severity
name wherever a rule name is accepted — `--select style`, `--ignore
warning`, `[lint] ignore = ["style"]` — expanding to every rule of that
severity; an unknown name still fails naming the file. (c) CLI text
output becomes `FILE:LINE:COL: error|warning|style: message [rule]`
(the severity word is new; pin the old tests to the new shape); JSON
gains `"severity"`. Exit codes unchanged. (d) Editor:
`DiagnosticSeverity::ERROR` / `WARNING` / `INFORMATION` respectively;
`source` unchanged. (e) `--rules-doc` and `rules_markdown()`: a
Severity column, sections grouped by severity, the intro explaining the
three words.
**33.1 Editor toggles, generated from the registry.** In
`editors/vscode/package.json`: three master switches
`lucisv.lint.severity.error`, `.warning`, `.style` (boolean, default
true, `order` 10/11/12, description naming what each class means), and
one boolean per rule `lucisv.lint.rules.<rule-name>` (default = the
rule's default; `markdownDescription` = `**severity** — summary`; the
project-only rules say "on where lucisv can see the project"; `order`
sorted by severity then name so the Settings UI groups them; the
existing `lucisv.lint.select`/`ignore` stay, documented as the
power-user spelling). Generated, not hand-written: a
`crates/vlog_linter/examples/vscode_lint_settings.rs` (or a `tools/`
script driving `cargo run --example`) that prints the JSON fragment,
and a `crates/lucisv_server` test that parses package.json and asserts
the `lucisv.lint.rules.*` set, defaults and descriptions equal the
registry — the drift guard, so a new rule cannot ship without its
toggle. The server (`settings.rs`) reads all of them; the enabled set
is computed in one documented function `enabled_rules(settings,
has_oracle)` with this precedence, top to bottom: (1) the base set is
the defaults (`default_on`, and `needs_workspace` rules only with an
oracle); (2) a non-empty `select` replaces the base set; (3) a severity
switch that is off removes every rule of that severity; (4) an
explicitly set per-rule toggle sets or clears that rule; (5) `ignore`
removes — the off switch of last resort. Pinned by a table test.
Changing any of them republishes every open file, as select/ignore do.
The CLI has parity through select/ignore with severity names; no
per-rule flags (`--ignore rule` is that).
**33.2 New rules, Error class** (each a file under `rules/`, its own
tests, its doc with the Verible name where one exists, and a measured
false-positive count on opentitan — see QA):
- `mismatched-labels` (Verible, off there; **on** here, Error): an end
label that does not match its block's name (`end : wrong`, `endmodule
: other`) — a compile error. Reuse what linked-editing already pairs.
- `duplicate-declaration` (Error): the same name declared twice in one
scope (port and signal, two signals, two params). Ask the binder:
`Binder::declare` sees the second declaration — record it (a
`Semantics` query `duplicates()` or a per-scope check), skip generate
scopes and macro-expanded text; no false positive on `input clk`
+ `logic clk` non-ANSI redeclaration (legal) — pin it.
- `undeclared-identifier` (Error, `needs_workspace`): a use the file
did not resolve and the workspace overlay left `StillUnresolved`/
`NotFound`, excluding: names inside macro invocations, system names,
names a `` `define`` in scope produces, names the file's macro-word
census contains, hierarchical tails, names in a package this file
wildcard-imports when that package is not indexed. Measured on
opentitan; ships default-on only if the count of unexplained
findings on that tree is 0 — otherwise default-off with the
measurement and the reason in the doc.
- `unknown-port` and `unknown-parameter` (Error, `needs_workspace`): a
named connection `.x(…)` / override `.P(…)` naming a port or
parameter the instantiated module does not declare (the index
exports both). Silent when the module is not indexed or is declared
twice with different shapes.
**33.3 New rules, Warning class** (Verible name, default there → here):
- `forbid-defparam` (on → on): `defparam` is deprecated and rejected by
some tools.
- `invalid-system-task-function` (on → on): `$psprintf`, `$random`
(use `$urandom`), `$dist_*`, `$srandom` … Verible's list, cited.
- `truncated-numeric-literal` (on → on): a sized literal whose value
does not fit its width (`4'hFFF`).
- `undersized-binary-literal` (on → on, safe fix pads): `8'b1`; binary
only by default, as Verible.
- `suspicious-semicolon` (off → **on**): `if (x);`, `for (…);`,
`while (…);` — a body that is a null statement.
- `packed-dimensions-range-ordering` (on → on): a packed dimension
written `[0:N-1]`.
- `module-port` and `module-parameter` (on → on): positional
connections/overrides when more than one port/parameter.
- `explicit-function-task-parameter-type` (on → on): an untyped tf
argument is a 1-bit `logic` — a silent truncation.
- `plusarg-assignment` (on → on): `$value$plusargs` result unused /
`$test$plusargs` misuse, as Verible defines it.
- `instance-shadowing` (off → **on**): a declaration shadowing one in
an enclosing scope of the same unit (the binder knows).
- `forbid-negative-array-dim` (off → on): a negative literal in a
dimension.
- `void-cast` (on → on): `void'(…)` around anything but a function
call that has a return value (Verible's rule).
- `incomplete-assignment` (no Verible equivalent; Warning): in an
`always_comb`, a variable assigned in the `then` branch of an `if`
with no `else` (or in some `case` items, not `default`) and not
assigned unconditionally earlier in the block — latch inference.
Conservative by construction: only flag when the block has no
unconditional assignment to that variable before the `if`/`case`;
measured on opentitan.
**33.4 Docs and measurement.** README.md "Linting" (severities, the
toggles, select/ignore with severity names), `editors/vscode/README.md`
settings table, the docs-site rules page (hand-written prose today —
add the new rules with their severity and a note that `--rules-doc` is
the generated truth), CHANGELOG untouched (the lead writes it). For
every new rule: findings on the corpus and on opentitan `hw/`
(read-only `lucisv check`), with ten findings read and classified per
rule (true / false positive / needs judgment); opentitan is lint-clean
under Verible, so a Verible-equivalent rule that fires there needs an
explanation (their config disables it, or our reading differs — say
which). Timing: `lucisv check` over opentitan before/after (the
semantic rules already dominate; the new ones must not add more than a
few percent).
Files: crates/vlog_linter/src/{registry.rs, rule_docs.rs, violation.rs,
lib.rs, rules/mod.rs, rules/<new>.rs, context.rs (if a semantics query
is needed), visit.rs (new walkers)} + tests/cases/*.lint,
crates/vlog_linter/examples/vscode_lint_settings.rs (new),
crates/vlog_semantic (only if `duplicates()`/shadowing needs a query —
additive, say so in Handshakes), crates/lucisv/src/{lint.rs, args.rs}
+ tests, crates/lucisv_server/src/{settings.rs, lint.rs} + tests,
editors/vscode/{package.json, README.md}, README.md "Linting",
docs/site/src/content/docs/reference/rules.md, docs/features/
linter-expansion-1/README.md (new), TODO §33. Worktree `lint-1`.
- [x] 33.0 `Severity` on every rule; select/ignore by severity; CLI
text/JSON; editor severities; `--rules-doc` grouped
- [x] 33.1 package.json toggles generated + drift test; `enabled_rules`
precedence pinned; republish on change
- [x] 33.2 Error rules: mismatched-labels, duplicate-declaration,
undeclared-identifier (measured; default decided by the count),
unknown-port, unknown-parameter
- [x] 33.3 Warning rules: the thirteen listed, each with tests and an
opentitan count
- [x] 33.4 docs; measurements table in the README
- [x] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
byte-identical (formatter untouched); opentitan read-only
`lucisv check` census + timing
- [ ] QA: every new rule attacked with hand-written true positives and
near-misses; the false-positive census re-read; toggles exercised
through the real server (`workspace/didChangeConfiguration`)
## 34. Linter expansion, wave 2 (planned 2026-09-02, after §33) — the Style class and per-rule options
The style family from Verible, with the per-rule configuration the
naming rules need: `signal-name-style`, `interface-name-style`,
`macro-name-style`, `constraint-name-style`, `parameter-type-name-style`,
`dff-name-style`, `port-name-suffix`, `banned-declared-name-patterns`
(each with a `pattern`/style option), `line-length` (reads the
formatter's `line-length`), `posix-eof` (safe fix), `endif-comment`,
`forbid-line-continuations`, `one-module-per-file`, `package-filename`,
`typedef-enums`, `typedef-structs-unions`, `module-begin-block`,
`generate-label` + `generate-label-prefix`, `always-comb` (`@*` →
`always_comb`, safe fix), `legacy-generate-region`,
`legacy-genvar-declaration`, `v2001-generate-begin`,
`explicit-function-lifetime`/`explicit-task-lifetime`,
`positive-meaning-parameter-name`, `suggest-parentheses`,
`forbid-consecutive-null-statements`, `unpacked-dimensions-range-
ordering`, `uvm-macro-semicolon`, `create-object-name-match`,
`numeric-format-string-style`, `macro-string-concatenation`,
`disable-statement`, `forbidden-macro`/`forbidden-symbol` (list
options). Options: `[lint.<rule>]` tables in `lucisv.toml` (today
rejected by name — the parser exists) and `lucisv.lint.options.<rule>`
in the editor, validated against a per-rule option schema declared by
the rule (`Rule::options() -> &[OptionSpec]`), shown in `--rules-doc`.
Detailed plan to be written when §33 lands.
+82 -12
View File
@@ -50,6 +50,11 @@ pub struct Plan {
/// a rule asks about one name at a time and never about a file.
pub struct Census {
files: HashMap<String, u32>,
/// Module or interface name → what it declares, `None` for a unit the run
/// cannot answer for: a header carrying a compiler directive, or two
/// declarations that disagree. Empty when no enabled rule asked for it —
/// building it costs a parse of every file in the run.
interfaces: HashMap<String, Option<vlog_linter::ModuleInterface>>,
}
impl Census {
@@ -58,27 +63,61 @@ impl Census {
/// A file that cannot be read or does not lex contributes nothing, which
/// is the same all-or-nothing rule the rest of the run gives it: the
/// file's own check reports the error.
fn of(jobs: &[Job]) -> Census {
let per_file: Vec<Vec<String>> = jobs
///
/// `interfaces` says whether the run also needs each unit's ports and
/// parameters (`unknown-port`, `unknown-parameter`). It costs a **parse**
/// of every file on top of the lex the word census already pays for, so
/// it is built only when some enabled rule asks — measured on opentitan
/// `hw/` in `docs/features/linter-expansion-1/README.md`.
fn of(jobs: &[Job], interfaces: bool) -> Census {
type PerFile = (Vec<String>, Vec<(String, Option<vlog_linter::ModuleInterface>)>);
let per_file: Vec<PerFile> = jobs
.par_iter()
.map(|job| match std::fs::read_to_string(&job.path) {
Ok(src) => words::harvest_text(&src),
Err(_) => Vec::new(),
.map(|job| {
let Ok(src) = std::fs::read_to_string(&job.path) else {
return (Vec::new(), Vec::new());
};
if !interfaces {
return (words::harvest_text(&src), Vec::new());
}
// One lex for both halves: the parse is what the interface
// table needs, and its tokens are the word census's.
let parsed = ParsedSource::parse(&src);
(words::harvest(parsed.tokens()), vlog_linter::module_interfaces(parsed.file()))
})
.collect();
let mut files: HashMap<String, u32> = HashMap::new();
for words in per_file {
let mut units: HashMap<String, Option<vlog_linter::ModuleInterface>> = HashMap::new();
for (words, declared) in per_file {
for word in words {
*files.entry(word).or_default() += 1;
}
for (name, interface) in declared {
// Two declarations of one name answer only when they agree;
// anything else is a question the run cannot settle.
units
.entry(name)
.and_modify(|held| {
if *held != interface {
*held = None;
}
})
.or_insert(interface);
}
}
Census { files }
Census { files, interfaces: units }
}
/// How many files in the run write `name` down.
fn count(&self, name: &str) -> u32 {
self.files.get(name).copied().unwrap_or(0)
}
/// What the run says `name` declares, or `None` when it cannot say.
fn interface(&self, name: &str) -> Option<vlog_linter::ModuleInterface> {
self.interfaces.get(name)?.clone()
}
}
/// One file's view of the census: everything the project says, minus what
@@ -96,6 +135,13 @@ impl MentionOracle for Elsewhere<'_> {
let mine = u32::from(self.own.binary_search_by(|w| w.as_str().cmp(name)).is_ok());
self.census.count(name) > mine
}
/// The run's interface table, which covers **every** file including this
/// one: a module is instantiated as often in the file that declares it as
/// anywhere else, and there is nothing to subtract here.
fn module_interface(&self, name: &str) -> Option<vlog_linter::ModuleInterface> {
self.census.interface(name)
}
}
/// Resolve the run: the rules for each file, and whether a census is owed.
@@ -120,10 +166,25 @@ pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Res
jobs.push(Job { path, config, rules });
}
let wanted = jobs.iter().any(|job| job.rules.iter().any(|rule| rule.needs_workspace()));
let census = (workspace && wanted).then(|| Census::of(&jobs));
let interfaces = jobs.iter().any(|job| job.rules.iter().any(|rule| reads_interfaces(*rule)));
let census = (workspace && wanted).then(|| Census::of(&jobs, workspace && interfaces));
Ok(Plan { jobs, census })
}
/// Whether this rule reads the census's **interface** half, which costs a
/// parse of every file in the run rather than a lex.
///
/// By name, because the alternative is a fourth boolean on the `Rule` trait
/// for two rules: `Rule::needs_workspace` already says "this rule asks the
/// project something", and which *question* it asks is between the rule and
/// the oracle. A name that is not in the registry cannot reach here — the
/// rules are `&'static dyn Rule` values from that registry — and a rule added
/// to the pair without being added here answers `None` and goes quiet, which
/// is the safe direction.
fn reads_interfaces(rule: &'static dyn Rule) -> bool {
matches!(rule.name(), "unknown-port" | "unknown-parameter")
}
/// The command line's list when it said anything, else the config file's.
fn pick<'a>(cli: &'a [String], config: Option<&'a [String]>) -> &'a [String] {
if cli.is_empty() {
@@ -348,15 +409,23 @@ fn finish(opts: &Options, reports: Vec<Report>) -> ExitCode {
}
}
/// Verible's diagnostic line: `FILE:LINE:COL: message [rule-name]`.
/// Verible's diagnostic line with the severity word in front of the message:
/// `FILE:LINE:COL: error|warning|style: message [rule-name]`.
///
/// The word sits where a compiler puts it, so the line greps and reads the way
/// every other tool's does, and `grep ': error:'` is the whole of "show me
/// what would not compile".
fn print_text(reports: &[Report]) {
let mut out = String::new();
for report in reports {
for violation in &report.violations {
let (line, col) = position(report, violation);
out.push_str(&format!(
"{}:{line}:{col}: {} [{}]\n",
report.path, violation.message, violation.rule
"{}:{line}:{col}: {}: {} [{}]\n",
report.path,
violation.severity.as_str(),
violation.message,
violation.rule
));
}
}
@@ -372,12 +441,13 @@ fn print_json(reports: &[Report]) {
let (line, col) = position(report, violation);
let (end_line, end_col) = end_position(report, violation);
items.push(format!(
"{{\"filename\":{},\"rule\":{},\"message\":{},\
"{{\"filename\":{},\"rule\":{},\"severity\":{},\"message\":{},\
\"location\":{{\"line\":{line},\"column\":{col}}},\
\"end_location\":{{\"line\":{end_line},\"column\":{end_col}}},\
\"range\":{{\"start\":{},\"end\":{}}},\"fix\":{}}}",
quote(&report.path),
quote(violation.rule),
quote(violation.severity.as_str()),
quote(&violation.message),
violation.span.start,
violation.span.end,
+28 -1
View File
@@ -753,7 +753,9 @@ fn check_reports_violations_and_exits_1() {
let out = run(&["check", &path]);
assert_eq!(code(&out), 1, "violations must exit 1: {}", stderr(&out));
let text = stdout(&out);
assert!(text.contains(&format!("{path}:2:1: tab character")), "{text}");
// `FILE:LINE:COL: severity: message [rule]` — the severity word is part
// of the line since §33.0, and both of these are style findings.
assert!(text.contains(&format!("{path}:2:1: style: tab character")), "{text}");
assert!(text.contains("[no-tabs]"), "{text}");
assert!(text.contains("[module-filename]"), "{text}");
assert!(stderr(&out).contains("found 2 violations"), "{}", stderr(&out));
@@ -797,6 +799,7 @@ fn check_json_is_one_array_with_positions_and_fixes() {
assert!(text.starts_with('['), "{text}");
assert!(text.trim_end().ends_with(']'), "{text}");
assert_eq!(text.matches("\"rule\":\"no-tabs\"").count(), 1, "{text}");
assert!(text.contains("\"severity\":\"style\""), "{text}");
assert!(text.contains("\"location\":{\"line\":2,\"column\":1}"), "{text}");
assert!(text.contains("\"applicability\":\"safe\""), "{text}");
assert!(text.contains("\"content\":\" \""), "{text}");
@@ -895,6 +898,30 @@ fn check_select_and_ignore_pick_the_rule_set() {
assert!(stderr(&out).contains("unknown rule"), "{}", stderr(&out));
}
/// A severity word stands for its whole class wherever a rule name fits —
/// §33.0's headline for the command line.
#[test]
fn check_select_and_ignore_accept_a_severity_word() {
let dir = TempDir::new("check-severity");
// `reg` is an error-class finding, the tab and the name are style ones.
let path = dir.write("bar.sv", "module foo;\n\treg a;\nendmodule\n");
let out = run(&["check", "--select", "error", &path]);
assert_eq!(code(&out), 1, "{}", stdout(&out));
let text = stdout(&out);
assert_eq!(text.lines().count(), 1, "{text}");
assert!(text.contains(": error: "), "{text}");
assert!(text.contains("[wire-reg-mixup]"), "{text}");
let out = run(&["check", "--ignore", "style", &path]);
assert_eq!(stdout(&out).lines().count(), 1, "{}", stdout(&out));
assert!(stdout(&out).contains("[wire-reg-mixup]"), "{}", stdout(&out));
// Ignoring every class leaves nothing to report.
let out = run(&["check", "--ignore", "error,warning,style", &path]);
assert_eq!(code(&out), 0, "{}", stdout(&out));
}
#[test]
fn check_honors_inline_waivers_and_reports_dead_ones() {
let dir = TempDir::new("check-waive");
+4 -3
View File
@@ -135,11 +135,12 @@ mod tests {
#[test]
fn one_list_carries_both_sources() {
// A file that parses cleanly and violates a lint rule: the publish is
// one list, and the lint finding is in it as a warning.
// one list, and the lint finding is in it at its rule's own severity
// — `no-tabs` is a style rule, so INFORMATION (§33.0).
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
let published = all(ws.document(&uri).expect("open"));
assert_eq!(published.len(), 1);
assert_eq!(published[0].severity, Some(DiagnosticSeverity::WARNING));
assert_eq!(published[0].severity, Some(DiagnosticSeverity::INFORMATION));
assert_eq!(published[0].code, Some(lsp_types::NumberOrString::String("no-tabs".into())));
}
@@ -149,7 +150,7 @@ mod tests {
let published = all(ws.document(&uri).expect("open"));
let severities: Vec<_> = published.iter().map(|d| d.severity).collect();
assert!(severities.contains(&Some(DiagnosticSeverity::ERROR)), "{published:#?}");
assert!(severities.contains(&Some(DiagnosticSeverity::WARNING)), "{published:#?}");
assert!(severities.contains(&Some(DiagnosticSeverity::INFORMATION)), "{published:#?}");
assert!(published.iter().all(|d| d.source.as_deref() == Some("lucisv")));
// Errors first: a parse error is what the user must fix.
assert_eq!(published[0].severity, Some(DiagnosticSeverity::ERROR));
+247 -14
View File
@@ -11,15 +11,19 @@
//! `docs/features/semantic-lints-on/README.md` and
//! `docs/features/server-lint/README.md`.
use std::collections::BTreeSet;
use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString};
use vlog_formatter::fence::{self, Region};
use vlog_linter::{
default_rules, lint, workspace_rules, LintContext, MentionOracle, Rule, Violation,
default_rules, lint, workspace_rules, LintContext, MentionOracle, ModuleInterface, Rule,
Severity, Violation,
};
use vlog_semantic::{FileId, WorkspaceIndex};
use vlog_semantic::{FileId, SymbolKind, WorkspaceIndex};
use crate::convert::Positions;
use crate::diagnostics::SOURCE;
use crate::settings::ClientSettings;
use crate::state::{Document, Workspace};
/// What one lint pass runs: which rules, and what it may ask about the files
@@ -52,12 +56,7 @@ impl<'a> LintRun<'a> {
let index = ws.index();
let own = doc.path.as_deref().and_then(|path| index.file_id(path));
let workspace = index.files().len() > usize::from(own.is_some());
let client = ws.client_settings();
// Every name in the settings was checked against the registry when the
// settings were parsed, so this cannot fail; if it somehow does, the
// defaults are the answer a dropped setting always gets here.
let rules = vlog_linter::select_rules(&client.lint_select, &client.lint_ignore, workspace)
.unwrap_or_else(|_| if workspace { workspace_rules() } else { default_rules() });
let rules = enabled_rules(ws.client_settings(), workspace);
let oracle = workspace.then_some(IndexMentions { index, own });
LintRun { rules, oracle }
}
@@ -72,6 +71,63 @@ impl<'a> LintRun<'a> {
}
}
/// Which rules a buffer is linted with, given what the editor's settings say.
///
/// **The one ladder**, top rung last — every rung may undo the one above it:
///
/// 1. the base set is what the rules themselves declare: `default_on`, plus
/// the `needs_workspace` rules when `has_oracle`;
/// 2. a non-empty `lucisv.lint.select` **replaces** that base set, exactly as
/// `--select` replaces it on the command line;
/// 3. a `lucisv.lint.severity.<class>` switched off **removes** every rule of
/// that class;
/// 4. a `lucisv.lint.rules.<name>` set to `on` or `off` sets or clears that
/// one rule — the per-rule word beats the class word, which is what makes
/// "all style off except `no-tabs`" expressible;
/// 5. `lucisv.lint.ignore` **removes** — the off switch of last resort, the
/// one a user reaches for when nothing else worked.
///
/// Rungs 2 and 5 accept a severity word wherever a rule name fits.
pub fn enabled_rules(settings: &ClientSettings, has_oracle: bool) -> Vec<&'static dyn Rule> {
let base = if settings.lint_select.is_empty() {
if has_oracle {
workspace_rules()
} else {
default_rules()
}
} else {
named(&settings.lint_select)
};
let mut on: BTreeSet<&'static str> = base.iter().map(|rule| rule.name()).collect();
for (severity, class_on) in &settings.lint_severity {
if !class_on {
on.retain(|name| {
vlog_linter::rule_by_name(name).is_some_and(|rule| rule.severity() != *severity)
});
}
}
for (name, wanted) in &settings.lint_rules {
let Some(rule) = vlog_linter::rule_by_name(name) else { continue };
if *wanted {
on.insert(rule.name());
} else {
on.remove(rule.name());
}
}
for rule in named(&settings.lint_ignore) {
on.remove(rule.name());
}
vlog_linter::all_rules().into_iter().filter(|rule| on.contains(rule.name())).collect()
}
/// Every rule a list of `--select`-style words names, unknown words skipped —
/// they were already dropped when the settings were parsed, and a name that
/// survived that filter always resolves.
fn named(words: &[String]) -> Vec<&'static dyn Rule> {
words.iter().filter_map(|word| vlog_linter::rules_named(word)).flatten().collect()
}
/// The workspace index, asked the one question a lint rule may ask about other
/// files.
///
@@ -97,6 +153,32 @@ impl MentionOracle for IndexMentions<'_> {
fn mentioned_elsewhere(&self, name: &str) -> bool {
self.index.mentioned_outside(name, self.own)
}
/// The ports and overridable parameters of an indexed module or interface,
/// read off the index's member table — the very table a `.port` completion
/// list is offered from, so a connection lucisv would have completed is
/// never one it then calls unknown.
///
/// `None` for a unit the index does not hold, and for one it holds **more
/// than once**: two modules of a name are two different headers, and
/// answering with either would make an Error-class rule guess. A
/// `localparam` is left out, because it is not overridable.
fn module_interface(&self, name: &str) -> Option<ModuleInterface> {
let units = self.index.units(name);
let [unit] = units else { return None };
if !unit.kind.is_instantiable() {
return None;
}
let mut interface = ModuleInterface::default();
for (member, defs) in self.index.members_of(name) {
match defs.first().map(|def| def.kind) {
Some(SymbolKind::Port) => interface.ports.push(member.to_string()),
Some(SymbolKind::Param) => interface.parameters.push(member.to_string()),
_ => {}
}
}
Some(interface)
}
}
/// The document's own parse products, lent to the linter — "one parse, two
@@ -175,14 +257,13 @@ pub fn diagnostics_in(doc: &Document, run: &LintRun) -> Vec<Diagnostic> {
/// The diagnostic a violation becomes.
///
/// **Warning**, never Error: a lint finding is an opinion about style, and a
/// parse error is the compiler refusing. The `code` is the rule's stable name,
/// which is what a user needs to write a waiver or an `--ignore`, and what a
/// code action matches on.
/// The editor's severity is the rule's own class ([`severity_of`]). The `code`
/// is the rule's stable name, which is what a user needs to write a waiver or
/// an `--ignore`, and what a code action matches on.
pub fn diagnostic(positions: &Positions<'_>, violation: &Violation) -> Diagnostic {
Diagnostic {
range: positions.diagnostic_range(violation.span),
severity: Some(DiagnosticSeverity::WARNING),
severity: Some(severity_of(violation.severity)),
code: Some(NumberOrString::String(violation.rule.to_string())),
source: Some(SOURCE.to_string()),
message: violation.message.clone(),
@@ -190,6 +271,21 @@ pub fn diagnostic(positions: &Positions<'_>, violation: &Violation) -> Diagnosti
}
}
/// How an editor is asked to paint one class.
///
/// `error` is the red squiggle a compiler error gets — a rule only claims it
/// when the code would very likely not build, which is why the Error class is
/// held to the silence-when-unsure rule. `style` deliberately stops short of
/// `HINT`: a hint is invisible in most themes and would make the style rules
/// look broken rather than quiet.
fn severity_of(severity: Severity) -> DiagnosticSeverity {
match severity {
Severity::Error => DiagnosticSeverity::ERROR,
Severity::Warning => DiagnosticSeverity::WARNING,
Severity::Style => DiagnosticSeverity::INFORMATION,
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -211,13 +307,35 @@ mod tests {
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
let diags = diagnostics(ws.document(&uri).expect("open"));
assert_eq!(diags.len(), 1);
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::WARNING));
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::INFORMATION), "no-tabs is style");
assert_eq!(diags[0].code, Some(NumberOrString::String("no-tabs".into())));
assert_eq!(diags[0].source.as_deref(), Some("lucisv"));
assert_eq!(diags[0].range.start.line, 1);
assert!(diags[0].range.start < diags[0].range.end, "never zero-width");
}
/// Each class paints its own squiggle: a compile-error rule reads as an
/// error, a latch-shaped one as a warning, a naming one as information.
#[test]
fn a_diagnostics_severity_is_its_rules_class() {
assert_eq!(severity_of(Severity::Error), DiagnosticSeverity::ERROR);
assert_eq!(severity_of(Severity::Warning), DiagnosticSeverity::WARNING);
assert_eq!(severity_of(Severity::Style), DiagnosticSeverity::INFORMATION);
// `reg` is error-class, the tab is style-class, and the two arrive in
// one publish wearing different colours.
let (ws, uri) = doc_of("module m;\n\treg a;\nendmodule\n");
let diags = diagnostics(ws.document(&uri).expect("open"));
let by_code = |name: &str| {
diags
.iter()
.find(|d| d.code == Some(NumberOrString::String(name.into())))
.and_then(|d| d.severity)
};
assert_eq!(by_code("wire-reg-mixup"), Some(DiagnosticSeverity::ERROR), "{diags:#?}");
assert_eq!(by_code("no-tabs"), Some(DiagnosticSeverity::INFORMATION), "{diags:#?}");
}
#[test]
fn a_waived_violation_is_never_published() {
let (ws, uri) = doc_of("module m;\n\twire a; // lucisv: waive no-tabs\nendmodule\n");
@@ -368,6 +486,121 @@ mod tests {
let _ = std::fs::remove_dir_all(dir);
}
/// The ladder of §33.1, one row per rung, asserted against the rule set
/// `enabled_rules` produces. Each row is (what the settings say, what must
/// be true of the result).
#[test]
fn the_enabled_rules_ladder_is_the_documented_one() {
let names = |settings: &ClientSettings, oracle: bool| -> Vec<&'static str> {
enabled_rules(settings, oracle).into_iter().map(|rule| rule.name()).collect()
};
let with = |f: &dyn Fn(&mut ClientSettings)| {
let mut settings = ClientSettings::default();
f(&mut settings);
settings
};
// 1. the base set is the rules' own defaults, and a workspace adds
// exactly the rules that asked for one.
let base = ClientSettings::default();
assert_eq!(
names(&base, false),
default_rules().iter().map(|r| r.name()).collect::<Vec<_>>()
);
assert_eq!(
names(&base, true),
workspace_rules().iter().map(|r| r.name()).collect::<Vec<_>>()
);
// 2. a non-empty `select` replaces the base set — including rules that
// ship off, exactly as `--select` does.
let selected = with(&|s| s.lint_select = vec!["module-name-style".to_string()]);
assert_eq!(names(&selected, false), vec!["module-name-style"]);
// ... and a severity word may stand there.
let styled = with(&|s| s.lint_select = vec!["style".to_string()]);
assert!(names(&styled, true)
.iter()
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
== Severity::Style));
// 3. a class switched off removes every rule of that class.
let no_style = with(&|s| {
s.lint_severity.insert(Severity::Style, false);
});
assert!(!names(&no_style, true).contains(&"no-tabs"));
assert!(names(&no_style, true).contains(&"unused-signal"), "other classes stay");
// 4. a per-rule toggle beats the class switch, in both directions.
let style_off_but_tabs = with(&|s| {
s.lint_severity.insert(Severity::Style, false);
s.lint_rules.insert("no-tabs".to_string(), true);
});
assert!(names(&style_off_but_tabs, true).contains(&"no-tabs"));
let one_off = with(&|s| {
s.lint_rules.insert("no-tabs".to_string(), false);
});
assert!(!names(&one_off, true).contains(&"no-tabs"));
// A toggle also adds a rule `select` did not name, and one that ships
// off entirely.
let added = with(&|s| {
s.lint_select = vec!["no-tabs".to_string()];
s.lint_rules.insert("module-name-style".to_string(), true);
});
assert_eq!(names(&added, false), vec!["module-name-style", "no-tabs"]);
// 5. `ignore` is the last word, over a toggle that says `on`.
let ignored = with(&|s| {
s.lint_rules.insert("no-tabs".to_string(), true);
s.lint_ignore = vec!["no-tabs".to_string()];
});
assert!(!names(&ignored, true).contains(&"no-tabs"));
// ... and it takes a severity word too.
let quiet = with(&|s| s.lint_ignore = vec!["style".to_string()]);
assert!(names(&quiet, true)
.iter()
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
!= Severity::Style));
// The result is always in registry order, whatever order the settings
// named things in — two runs must print findings the same way.
let jumbled = with(&|s| {
s.lint_select = vec!["no-trailing-whitespace".to_string(), "no-tabs".to_string()];
});
assert_eq!(names(&jumbled, false), vec!["no-tabs", "no-trailing-whitespace"]);
}
/// The toggles reach the real published diagnostics, not just the rule
/// list: a class switched off silences its squiggles.
#[test]
fn a_class_switch_changes_what_the_server_publishes() {
let (mut ws, dir, uri) = two_file_project("classes");
ws.set_document(uri.clone(), "module dut;\n\tlogic dead;\nendmodule\n".to_string());
let doc = ws.document(&uri).expect("open");
let mut both = codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc)));
both.sort();
assert_eq!(both, vec!["no-tabs", "unused-signal"], "premise");
let mut off = ClientSettings::default();
off.lint_severity.insert(Severity::Style, false);
ws.set_client_settings(off);
let doc = ws.document(&uri).expect("open");
assert_eq!(
codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc))),
vec!["unused-signal"],
"the style class went quiet"
);
let mut back = ClientSettings::default();
back.lint_severity.insert(Severity::Style, false);
back.lint_rules.insert("no-tabs".to_string(), true);
ws.set_client_settings(back);
let doc = ws.document(&uri).expect("open");
let mut with_tabs = codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc)));
with_tabs.sort();
assert_eq!(with_tabs, vec!["no-tabs", "unused-signal"], "the per-rule word wins");
let _ = std::fs::remove_dir_all(dir);
}
/// The off switch, over the settings door: `lucisv.lint.ignore` takes a
/// rule out of the published set.
#[test]
@@ -268,9 +268,13 @@ impl Server {
/// The rule selection in force, as a value two settings pushes can be
/// compared by.
fn lint_selection(&self) -> (Vec<String>, Vec<String>) {
let client = self.workspace.client_settings();
(client.lint_select.clone(), client.lint_ignore.clone())
///
/// All four lint settings, not just the two lists: since §33.1 a class
/// switch (`lucisv.lint.severity.*`) and a per-rule toggle
/// (`lucisv.lint.rules.*`) change which rules run too, and a change to one
/// of them must republish exactly as a change to `select`/`ignore` does.
fn lint_selection(&self) -> settings::LintSelection {
settings::lint_selection(self.workspace.client_settings())
}
}
+202 -3
View File
@@ -13,9 +13,11 @@
//! Not to be confused with `format::Settings`, which is what one formatting
//! request resolved to after every rung of that ladder was applied.
use std::collections::BTreeMap;
use std::ops::RangeInclusive;
use serde_json::Value;
use vlog_linter::Severity;
/// Accepted `line-length`, and accepted `indent`.
///
@@ -174,6 +176,20 @@ pub struct ClientSettings {
/// `lucisv.lint.ignore`: rules dropped from whatever `select` left. Same
/// validation, same reason.
pub lint_ignore: Vec<String>,
/// `lucisv.lint.severity.error` / `.warning` / `.style`: the master switch
/// of each class. Every class is present and `true` unless a client turned
/// one off — see `lint::enabled_rules` for where it sits in the ladder.
pub lint_severity: BTreeMap<Severity, bool>,
/// `lucisv.lint.rules.<rule-name>`: the rules a client said something
/// **explicit** about — `true` for `on`, `false` for `off`.
///
/// A rule left at `default` is *absent from this map*, and that is the
/// whole reason the setting is a three-word enum rather than a boolean: a
/// client sends the whole section, every key at its default, so "unset"
/// and "set to the shipped value" would arrive identically and a per-rule
/// toggle nobody touched would silently override `select` and the class
/// switches.
pub lint_rules: BTreeMap<String, bool>,
}
/// The settings a client that said nothing is treated as having asked for.
@@ -200,10 +216,35 @@ impl Default for ClientSettings {
large_file_threshold: DEFAULT_LARGE_FILE_THRESHOLD,
lint_select: Vec::new(),
lint_ignore: Vec::new(),
lint_severity: every_class_on(),
lint_rules: BTreeMap::new(),
}
}
}
/// Every severity class switched on — what a client that said nothing means.
fn every_class_on() -> BTreeMap<Severity, bool> {
Severity::ALL.into_iter().map(|severity| (severity, true)).collect()
}
/// Everything about a settings value that decides **which rules run**: the two
/// name lists, the class switches and the per-rule toggles.
///
/// Its only use is equality — the server compares it across a settings change
/// to decide whether every open file must be published again.
pub type LintSelection =
(Vec<String>, Vec<String>, BTreeMap<Severity, bool>, BTreeMap<String, bool>);
/// The four lint settings of `settings`, as one comparable value.
pub fn lint_selection(settings: &ClientSettings) -> LintSelection {
(
settings.lint_select.clone(),
settings.lint_ignore.clone(),
settings.lint_severity.clone(),
settings.lint_rules.clone(),
)
}
/// Read the `lucisv` section out of a `workspace/didChangeConfiguration` payload.
///
/// **Nothing here trusts the client.** `package.json`'s JSON schema constrains
@@ -274,17 +315,53 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
.unwrap_or(DEFAULT_LARGE_FILE_THRESHOLD),
lint_select: rules(lint.and_then(|l| l.get("select"))),
lint_ignore: rules(lint.and_then(|l| l.get("ignore"))),
// `lucisv.lint.severity.<class>` and `lucisv.lint.rules.<name>` nest
// one level deeper again, for the same reason `index.*` does.
lint_severity: severity_switches(lint.and_then(|l| l.get("severity"))),
lint_rules: rule_toggles(lint.and_then(|l| l.get("rules"))),
}
}
/// The rule names in a settings array, dropping every one the registry does
/// not know.
/// The rule names in a settings array, dropping every one that names neither a
/// rule nor a severity class.
///
/// Silence rather than an error, on this module's standing rule: a push is
/// JSON on a socket, and a typo in one name must not cost the user every
/// diagnostic in the file. A dropped name leaves the rule where it was.
fn rules(value: Option<&Value>) -> Vec<String> {
strings(value).into_iter().filter(|name| vlog_linter::rule_by_name(name).is_some()).collect()
strings(value).into_iter().filter(|name| vlog_linter::rules_named(name).is_some()).collect()
}
/// The three class master switches, each `true` unless a client turned it off.
///
/// A missing or wrong-typed switch leaves its class on: the safe direction for
/// a switch that silences a whole family of diagnostics is the one that shows
/// them, exactly as an unreadable size cap leaves the cap on.
fn severity_switches(value: Option<&Value>) -> BTreeMap<Severity, bool> {
Severity::ALL
.into_iter()
.map(|severity| {
let on = flag(value.and_then(|v| v.get(severity.as_str()))).unwrap_or(true);
(severity, on)
})
.collect()
}
/// The rules a client said something explicit about: `on` and `off` only.
///
/// `default` — and any word that is neither, and any key that is not a rule —
/// contributes nothing, which is what leaves the rule wherever the rest of the
/// ladder put it. See [`ClientSettings::lint_rules`].
fn rule_toggles(value: Option<&Value>) -> BTreeMap<String, bool> {
let Some(Value::Object(map)) = value else { return BTreeMap::new() };
map.iter()
.filter(|(name, _)| vlog_linter::rule_by_name(name).is_some())
.filter_map(|(name, choice)| match choice.as_str() {
Some("on") => Some((name.clone(), true)),
Some("off") => Some((name.clone(), false)),
_ => None,
})
.collect()
}
/// One of the two `lucisv.index.scope` words, or nothing. Matched exactly —
@@ -623,6 +700,128 @@ mod tests {
}
}
/// **The drift guard.** `editors/vscode/package.json` declares one switch
/// per severity class and one per rule, generated by
/// `vlog_linter::vscode_lint_settings`. This compares the two as JSON
/// *values*, so formatting is free but a rule added without its toggle —
/// or a summary, default or severity edited on one side only — fails here.
///
/// Regenerate with
/// `cargo run -p vlog_linter --example vscode_lint_settings`.
#[test]
fn the_vscode_lint_toggles_match_the_registry() {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../editors/vscode/package.json");
let text = std::fs::read_to_string(&path).expect("the extension manifest");
let manifest: Value = serde_json::from_str(&text).expect("valid json");
let properties = manifest["contributes"]["configuration"]["properties"]
.as_object()
.expect("a properties object");
let declared: serde_json::Map<String, Value> = properties
.iter()
.filter(|(key, _)| {
key.starts_with("lucisv.lint.severity.") || key.starts_with("lucisv.lint.rules.")
})
.map(|(key, value)| (key.clone(), value.clone()))
.collect();
let generated: Value = serde_json::from_str(&vlog_linter::vscode_lint_settings())
.expect("the generator emits valid json");
let generated = generated.as_object().expect("an object");
let names = |map: &serde_json::Map<String, Value>| {
let mut keys: Vec<String> = map.keys().cloned().collect();
keys.sort();
keys
};
assert_eq!(
names(&declared),
names(generated),
"package.json and the rule registry disagree about which lint settings exist; \
regenerate with `cargo run -p vlog_linter --example vscode_lint_settings`"
);
for (key, value) in generated {
assert_eq!(declared.get(key), Some(value), "{key} drifted");
}
// And every rule really does have one, which is the promise the whole
// generator exists to keep.
for rule in vlog_linter::all_rules() {
assert!(declared.contains_key(&vlog_linter::rule_setting(rule)), "{}", rule.name());
}
}
/// A default-everything payload — which is what a client sends for a user
/// who has touched nothing — must say nothing about any rule.
#[test]
fn the_shipped_lint_toggles_are_no_opinion() {
let mut rules = serde_json::Map::new();
for rule in vlog_linter::all_rules() {
rules.insert(rule.name().to_string(), json!("default"));
}
let found = settings(json!({"lucisv": {"lint": {
"severity": {"error": true, "warning": true, "style": true},
"rules": Value::Object(rules),
}}}));
assert_eq!(found, ClientSettings::default(), "every shipped value is silence");
}
#[test]
fn the_severity_switches_and_rule_toggles_are_read() {
let found = settings(json!({"lucisv": {"lint": {
"severity": {"style": false, "warning": "yes"},
"rules": {"no-tabs": "on", "unused-signal": "off", "empty-item": "default",
"no-such-rule": "on", "case-missing-default": 3},
}}}));
assert!(!found.lint_severity[&Severity::Style]);
assert!(found.lint_severity[&Severity::Warning], "a wrong type leaves it on");
assert!(found.lint_severity[&Severity::Error], "and so does absence");
assert_eq!(
found.lint_rules,
[("no-tabs".to_string(), true), ("unused-signal".to_string(), false)]
.into_iter()
.collect::<BTreeMap<_, _>>(),
"`default`, an unknown rule and a wrong-typed choice all say nothing"
);
// A `lint` that is not an object leaves every class on and nothing said.
let junk = settings(json!({"lucisv": {"lint": 7}}));
assert_eq!(junk.lint_severity, every_class_on());
assert!(junk.lint_rules.is_empty());
}
/// A severity word is a legal `select`/`ignore` entry since §33.0, so the
/// validating filter must keep it.
#[test]
fn a_severity_word_survives_the_select_and_ignore_filter() {
let found = settings(json!({"lucisv": {"lint": {
"select": ["style", "no-tabs", "nope"],
"ignore": ["warning"],
}}}));
assert_eq!(found.lint_select, vec!["style", "no-tabs"]);
assert_eq!(found.lint_ignore, vec!["warning"]);
}
/// What the server compares two settings pushes by, to decide whether the
/// squiggles it already drew are still right.
#[test]
fn the_lint_selection_notices_every_setting_that_changes_the_rule_set() {
let base = ClientSettings::default();
let mut severity = base.clone();
severity.lint_severity.insert(Severity::Style, false);
let mut toggled = base.clone();
toggled.lint_rules.insert("no-tabs".to_string(), false);
let mut selected = base.clone();
selected.lint_select = vec!["error".to_string()];
let mut ignored = base.clone();
ignored.lint_ignore = vec!["no-tabs".to_string()];
for changed in [severity, toggled, selected, ignored] {
assert_ne!(lint_selection(&base), lint_selection(&changed));
}
// A setting that does not change which rules run does not republish.
let mut unrelated = base.clone();
unrelated.indent = Some(4);
assert_eq!(lint_selection(&base), lint_selection(&unrelated));
}
#[test]
fn the_default_vscode_payload_is_no_opinion_about_anything() {
// Every setting at its `package.json` default: nulls and an empty
+3 -1
View File
@@ -455,7 +455,9 @@ fn lint_diagnostics_and_a_code_action_round_trip_over_the_wire() {
assert!(codes.contains(&"no-tabs"), "{codes:?}");
assert!(codes.contains(&"no-trailing-whitespace"), "{codes:?}");
for diagnostic in diagnostics {
assert_eq!(diagnostic["severity"], 2, "a lint finding is a warning");
// Both rules here are style-class, which is LSP severity 3
// (INFORMATION) since §33.0.
assert_eq!(diagnostic["severity"], 3, "a style finding is information");
assert_eq!(diagnostic["source"], "lucisv");
}
+153 -20
View File
@@ -3,7 +3,9 @@
//! A fenced region is emitted as the exact source bytes it was written with,
//! so nothing inside it is ever laid out. This module answers the two
//! questions that makes possible: which comments are fences, and which byte
//! ranges they select. Full spec: `docs/features/format-fences/README.md`.
//! ranges they select. Full spec: `docs/features/format-fences/README.md`,
//! plus `docs/features/statement-fences/README.md` for the class-body and
//! statement-list scopes.
//!
//! [`protected_regions`] and [`is_protected`] are the same answer for the
//! tools that only *edit* fenced bytes rather than lay them out — the CLI's
@@ -11,7 +13,10 @@
//! there is one definition of "what is fenced": see
//! `docs/features/shared-fence-filter/README.md`.
use vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind, SourceFile};
use vlog_parser::ast::{
Fragment, GenBlock, GenElse, GenIf, Item, ItemKind, SourceFile, Stmt, StmtKind,
};
use vlog_parser::span::TextRange;
use vlog_parser::token::Comment;
use vlog_parser::LineIndex;
@@ -54,7 +59,15 @@ pub struct Region {
/// Every fenced region in `file`, sorted and non-overlapping.
pub fn collect(src: &str, file: &SourceFile) -> Vec<Region> {
let mut found = Vec::new();
scan_scope(src, &file.items, &file.dangling, &mut found);
match &file.fragment {
// A statement fragment is one statement list standing at file scope,
// its dangling comments ending it exactly as a file's items' do. The
// other fragment shapes are element lists, which are not fenceable.
Some(Fragment::Statements(stmts)) => {
scan_stmt_scope(src, stmts, &file.dangling, &mut found)
}
_ => scan_scope(src, &file.items, &file.dangling, &mut found),
}
found.sort_by_key(|r| r.fence);
// A region inside an already-fenced range never runs: the items holding
// it are emitted as source bytes, so they are never formatted. Dropping
@@ -146,50 +159,73 @@ fn scanned_regions(src: &str) -> Vec<Region> {
regions
}
/// Scan one item-list scope, then its nested scopes.
/// Scan one flat stream of units — each unit's leading comments, then its own
/// code extent — followed by the scope's dangling comments.
///
/// The scope is a flat stream of units — each item's leading comments, then
/// the item's own code — followed by the dangling comments. A region opens at
/// the first `off` in that stream and closes at the first `on` after it;
/// anything else, including a second `off`, is just text.
fn scan_scope(src: &str, items: &[Item], dangling: &[Comment], out: &mut Vec<Region>) {
/// A region opens at the first `off` in that stream and closes at the first
/// `on` after it; anything else, including a second `off`, is just text. An
/// item list and a statement list have exactly this shape, and it is the only
/// shape a fence pairs inside, which is why both scan through here.
fn scan_units<'u>(
src: &str,
units: impl Iterator<Item = (&'u [Comment], TextRange)>,
dangling: &[Comment],
out: &mut Vec<Region>,
) {
let mut open: Option<Region> = None;
let mut scope_end = 0usize;
for item in items {
for c in &item.meta.leading {
for (leading, span) in units {
for c in leading {
// An attribute followed by a comment puts a "leading" comment
// *after* the item's span starts. Opening a region there would
// *after* the unit's span starts. Opening a region there would
// emit the attribute twice, so such comments are not fences.
if c.span.start < item.span.start {
if c.span.start < span.start {
step(src, c, &mut open, out);
}
}
// A leading comment always ends before its item's code does, so the
// item's own end is the scope's high-water mark.
scope_end = item.span.end as usize;
// A leading comment always ends before its unit's code does, so the
// unit's own end is the scope's high-water mark.
scope_end = span.end as usize;
}
for c in dangling {
step(src, c, &mut open, out);
scope_end = c.span.end as usize;
}
if let Some(mut r) = open {
// An unmatched `off` runs to the end of the scope. The last item's
// An unmatched `off` runs to the end of the scope. The last unit's
// span stops before the comment trailing it on the same line, and
// `Meta.trailing` has no span to consult, so that comment has to be
// picked up from the source or it would be dropped.
r.end = with_trailing_comments(src, scope_end);
out.push(r);
}
}
/// Scan one item-list scope, then its nested scopes.
fn scan_scope(src: &str, items: &[Item], dangling: &[Comment], out: &mut Vec<Region>) {
scan_units(src, items.iter().map(|i| (i.meta.leading.as_slice(), i.span)), dangling, out);
for item in items {
scan_nested(src, item, out);
}
}
/// Scan one statement-list scope, then its nested scopes.
///
/// The statement twin of [`scan_scope`], unit for unit — which is what keeps a
/// region aligned with statement boundaries and stops an unmatched `off` at the
/// list's end rather than at the `end`, `join` or `endfunction` past it.
fn scan_stmt_scope(src: &str, stmts: &[Stmt], dangling: &[Comment], out: &mut Vec<Region>) {
scan_units(src, stmts.iter().map(|s| (s.meta.leading.as_slice(), s.span)), dangling, out);
for stmt in stmts {
scan_nested_stmt(src, stmt, out);
}
}
/// Advance the open/closed state by one comment unit.
fn step(src: &str, c: &Comment, open: &mut Option<Region>, out: &mut Vec<Region>) {
let start = c.span.start as usize;
match (fence_of(&c.text), open.is_some()) {
(Some(Fence::Off), false) => {
(Some(Fence::Off), false) if opens_line(src, start) => {
*open = Some(Region { fence: start, start: line_start(src, start), end: 0 })
}
(Some(Fence::On), true) => {
@@ -202,8 +238,8 @@ fn step(src: &str, c: &Comment, open: &mut Option<Region>, out: &mut Vec<Region>
}
}
/// Item scopes nested inside one item. Statement bodies are not scanned:
/// statement-level fences are out of scope (see the feature README).
/// Scopes nested inside one item: the item lists, and the statement lists an
/// item's body reaches.
fn scan_nested(src: &str, item: &Item, out: &mut Vec<Region>) {
match &item.kind {
ItemKind::Module(m) => scan_scope(src, &m.items, &m.dangling, out),
@@ -216,6 +252,57 @@ fn scan_nested(src: &str, item: &Item, out: &mut Vec<Region>) {
scan_gen_block(src, &i.body, out);
}
}
ItemKind::Class(c) => scan_scope(src, &c.items, &c.dangling, out),
ItemKind::Function(f) => scan_stmt_scope(src, &f.stmts, &f.dangling, out),
ItemKind::Task(t) => scan_stmt_scope(src, &t.stmts, &t.dangling, out),
ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => {
scan_nested_stmt(src, stmt, out)
}
_ => {}
}
}
/// Statement scopes nested inside one statement.
///
/// A statement *list* is a scope — `begin`…`end`, `fork`…`join*`. A
/// single-statement body is not, for the reason [`scan_gen_block`] refuses a
/// block-less generate item: there is no list for a fence to end in, and the
/// formatter lays that statement out inside a `Group`. So the bodies below are
/// walked into rather than scanned, and only the block one of them holds opens
/// a scope.
fn scan_nested_stmt(src: &str, stmt: &Stmt, out: &mut Vec<Region>) {
match &stmt.kind {
StmtKind::Block { stmts, dangling, .. } | StmtKind::ForkJoin { stmts, dangling, .. } => {
scan_stmt_scope(src, stmts, dangling, out)
}
StmtKind::If { then, els, .. } => {
scan_nested_stmt(src, then, out);
if let Some(e) = els {
scan_nested_stmt(src, e, out);
}
}
StmtKind::Assert { then, els, .. } => {
for s in then.iter().chain(els.iter()) {
scan_nested_stmt(src, s, out);
}
}
// A case item's *labels* are not a fenceable stream (see the feature
// README); the block one of them may hold is.
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
for i in items {
scan_nested_stmt(src, &i.stmt, out);
}
}
StmtKind::For { body, .. }
| StmtKind::While { body, .. }
| StmtKind::DoWhile { body, .. }
| StmtKind::Repeat { body, .. }
| StmtKind::Forever { body }
| StmtKind::Foreach { body, .. }
| StmtKind::Labeled { stmt: body, .. } => scan_nested_stmt(src, body, out),
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
scan_nested_stmt(src, inner, out)
}
_ => {}
}
}
@@ -242,6 +329,30 @@ fn scan_gen_block(src: &str, b: &GenBlock, out: &mut Vec<Region>) {
}
}
/// Whether a fence written at `at` begins the *content* of its line: nothing
/// but whitespace and finished block comments precedes it there.
///
/// This is what makes `begin // lucisv: off` an ordinary comment. The parser
/// hands a comment written after `begin` to the next *statement* as a leading
/// one, so without this test a region would open in the middle of a line and
/// take its first line's bytes from the wrong column. A fence preceded only by
/// another comment (`/* a */ // lucisv: off`) still opens one: that comment is
/// a unit of the same stream and prints on the line above.
fn opens_line(src: &str, at: usize) -> bool {
let bol = src.get(..at).and_then(|s| s.rfind('\n')).map_or(0, |i| i + 1);
let Some(mut before) = src.get(bol..at) else { return false };
loop {
before = before.trim_start();
if before.is_empty() {
return true;
}
match before.strip_prefix("/*").and_then(|b| b.split_once("*/")) {
Some((_, rest)) => before = rest,
None => return false,
}
}
}
/// The start of the line `at` sits on, when nothing but whitespace precedes it
/// there — otherwise `at` itself, so a fence sharing its line with another
/// comment does not swallow it.
@@ -323,6 +434,28 @@ mod tests {
assert_eq!(fence_of("// off"), None);
}
#[test]
fn a_fence_only_opens_a_region_at_the_start_of_its_line() {
// Whitespace before it, at any depth, and at the very first byte.
assert!(opens_line("// lucisv: off\n", 0));
assert!(opens_line("module m;\n // lucisv: off\n", 12));
assert!(opens_line("module m;\n\t\t// lucisv: off\n", 12));
// Another comment before it is still the start of the line's content.
let src = "module m;\n /* a */ // lucisv: off\n";
assert!(opens_line(src, src.find("//").expect("fence")));
let src = "module m;\n /* a */ /* b */ // lucisv: off\n";
assert!(opens_line(src, src.find("//").expect("fence")));
// Code before it is not — the two shapes the parser hands to the next
// node as a *leading* comment even though they trail code.
let src = "module m;\n always @(*) begin // lucisv: off\n x = 1;\n";
assert!(!opens_line(src, src.find("//").expect("fence")));
let src = "module m; // lucisv: off\n wire a;\n";
assert!(!opens_line(src, src.find("//").expect("fence")));
// An unterminated block comment before it is not a finished comment.
let src = "module m;\n /* a // lucisv: off\n";
assert!(!opens_line(src, src.find("// lucisv").expect("fence")));
}
#[test]
fn a_fence_line_starts_at_its_indentation() {
let src = "module m;\n // lucisv: off\n";
+36 -4
View File
@@ -30,16 +30,48 @@ struct BlockDoc<'a> {
impl<'a> Fmt<'a> {
fn stmt(&self, s: &Stmt) -> Doc {
self.with_meta(&s.meta, self.stmt_kind(&s.kind, &s.before_semi))
concat(self.stmt_docs(s))
}
/// One statement: its leading comments, then — unless a verbatim region is
/// already emitting its bytes — its code and trailing comment. The
/// statement twin of `Fmt::item_docs`, with the same two rules: comments
/// written before the `off` fence are still emitted, because comments are
/// never dropped, and a statement the region swallowed emits nothing.
fn stmt_docs(&self, s: &Stmt) -> Vec<Doc> {
// A verbatim run whose first statement carries no leading comment opens
// at the statement's own code; there is no comment to emit it from.
if let Some(region) = self.opens_at(s.span.start as usize) {
return vec![self.verbatim(region)];
}
if self.is_verbatim(s.span) {
// The statement's own bytes, its attributes included, are emitted
// verbatim by the fence; only its leading comments are ours.
let mut docs = self.leading_comments(&s.meta);
// The last comment asked for a line break before code that is not
// coming. Whoever emits the next unit separates it itself.
if matches!(docs.last(), Some(Doc::HardLine)) {
docs.pop();
}
return docs;
}
vec![self.with_meta(&s.meta, self.stmt_kind(&s.kind, &s.before_semi))]
}
/// Sequence of statements at one indent level, preserving single blank
/// lines between them. A statement a fenced region swallowed emits
/// nothing, and contributes no separator either.
pub(super) fn stmt_seq(&self, stmts: &[Stmt]) -> Vec<Doc> {
let mut docs = Vec::new();
for (i, s) in stmts.iter().enumerate() {
if i > 0 {
for s in stmts {
let stmt_docs = self.stmt_docs(s);
if stmt_docs.is_empty() {
continue;
}
if !docs.is_empty() {
docs.push(if s.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
}
docs.push(self.stmt(s));
docs.extend(stmt_docs);
}
docs
}
+8 -1
View File
@@ -158,7 +158,14 @@ pub fn select(src: &str, file: &SourceFile, lines: &LineRanges) -> Selection {
pub fn plan(src: &str, file: &SourceFile, selection: &Selection) -> Plan {
let mut planner = Planner::new(src, file, Mode::Picks(&selection.picks));
planner.scope(&file.items, &file.dangling);
Plan { regions: normalize(planner.regions), splits: planner.splits }
// The fenced regions go in alongside the runs the picks made. An *item* a
// fence covers is already `Pick::Verbatim`, so its bytes are in a run
// either way; a fenced **statement** inside a laid-out item has no such
// run behind it, and without this the caller's `--lines` would reformat
// bytes the author fenced off. `normalize` folds the two into their union.
let mut regions = planner.regions;
regions.extend(planner.fences.iter().copied());
Plan { regions: normalize(regions), splits: planner.splits }
}
/// Sort the collected regions and fold everything that overlaps into one.
+246 -2
View File
@@ -372,7 +372,7 @@ wire a;
endgenerate
endmodule
====
# a statement-level fence has no effect this round
# a statement-level fence fences the statements between it and the on
module m;
always @(*) begin
// lucisv: off
@@ -382,15 +382,259 @@ y = 2;
end
endmodule
----
module m;
always @(*) begin
// lucisv: off
x = 1;
// lucisv: on
y = 2;
end
endmodule
====
# a statement region keeps its own indentation, first line included
module m;
initial begin
// lucisv: off
x <= 8'h0a;
yy <= 8'h0b;
// lucisv: on
z <= 1;
end
endmodule
----
module m;
initial begin
// lucisv: off
x <= 8'h0a;
yy <= 8'h0b;
// lucisv: on
z <= 1;
end
endmodule
====
# an unmatched off runs to the end of the block, not past its end
module m;
initial begin
// lucisv: off
x = 1;
y = 2; // note
end
initial begin
z = 3;
end
endmodule
----
module m;
initial begin
// lucisv: off
x = 1;
y = 2; // note
end
initial begin
z = 3;
end
endmodule
====
# an unmatched off in a fork body stops at the join
module m;
initial fork
// lucisv: off
p1 ();
p2 ();
join_none
endmodule
----
module m;
initial
fork
// lucisv: off
p1 ();
p2 ();
join_none
endmodule
====
# fences work in a function body and stop at endfunction
module m;
function int f();
// lucisv: off
int a =1;
// lucisv: on
return a;
endfunction
endmodule
----
module m;
function int f();
// lucisv: off
int a =1;
// lucisv: on
return a;
endfunction
endmodule
====
# a fence inside a case item's block body fences that block only
module m;
always @(*) begin
case (s)
2'b00: begin
// lucisv: off
a = 1;
// lucisv: on
b = 2;
end
default: c = 3;
endcase
end
endmodule
----
module m;
always @(*) begin
case (s)
2'b00: begin
// lucisv: off
a = 1;
// lucisv: on
b = 2;
end
default: c = 3;
endcase
end
endmodule
====
# a fence written after begin on the same line is an ordinary comment
module m;
always @(*) begin // lucisv: off
x = 1;
y = 2;
end
endmodule
----
module m;
always @(*) begin
// lucisv: off
x = 1;
// lucisv: on
y = 2;
end
endmodule
====
# a fence written after a module header on the same line is an ordinary comment
module m; // lucisv: off
wire a;
wire b;
endmodule
----
module m;
// lucisv: off
wire a;
wire b;
endmodule
====
# a fence inside a bodyless if is an ordinary comment
module m;
always @(*)
// lucisv: off
if (c) x = 1;
endmodule
----
module m;
always @(*)
// lucisv: off
if (c) x = 1;
endmodule
====
# fences work inside a class body
class c;
int a;
// lucisv: off
int b =2;
int cc =3;
// lucisv: on
int d;
endclass
----
class c;
int a;
// lucisv: off
int b =2;
int cc =3;
// lucisv: on
int d;
endclass
====
# an unmatched off in a class body stops at endclass
class c;
// lucisv: off
int a;
endclass
class d;
int b;
endclass
----
class c;
// lucisv: off
int a;
endclass
class d;
int b;
endclass
====
# a fence around a nested class fences the whole nested class
class outer;
// lucisv: off
class inner;
int x;
endclass
// lucisv: on
int y;
endclass
----
class outer;
// lucisv: off
class inner;
int x;
endclass
// lucisv: on
int y;
endclass
====
# a port-list fence is an ordinary comment, and the port list still formats
module m (
// lucisv: off
input logic a,
output logic b
);
endmodule
----
module m (
// lucisv: off
input logic a,
output logic b
);
endmodule
====
# a case-item label fence is an ordinary comment
module m;
always @(*) begin
case (s)
// lucisv: off
2'b00: a = 1;
2'b01: a = 2;
endcase
end
endmodule
----
module m;
always @(*) begin
case (s)
// lucisv: off
2'b00: a = 1;
2'b01: a = 2;
endcase
end
endmodule
====
# a blank line before the off fence survives, collapsed to one
module m;
wire z;
+136
View File
@@ -93,6 +93,142 @@ fn a_corrupted_fenced_region_is_still_rejected_by_the_safety_net() {
}
}
#[test]
fn a_statement_region_is_emitted_byte_for_byte() {
// A fence between two statements of an `always` block: the hand-aligned
// interior, the blank line and the trailing comment all survive, and the
// statement after the `on` is formatted normally.
let src = "module m;\n always_ff @(posedge clk) begin\n // lucisv: off\n q0 <= d0; // lo\n\n q1 <= d1;\n // lucisv: on\n q2 <= d2;\n end\nendmodule\n";
let region =
" // lucisv: off\n q0 <= d0; // lo\n\n q1 <= d1;\n // lucisv: on";
let out = fenced(src, region);
assert!(out.contains("\n q2 <= d2;\n"), "formatting did not resume in the block:\n{out}");
}
#[test]
fn an_unmatched_off_in_a_statement_list_stops_at_the_end_of_that_list() {
// It must stop at the block's last statement — its trailing comment
// included — and never swallow the `end`, the `endfunction` or anything
// after them.
let src = "module m;\n initial begin\n // lucisv: off\n x = 1;\n y = 2; // note\n end\n\n function int f();\n return 1;\n endfunction\nendmodule\n";
let out = fenced(src, " // lucisv: off\n x = 1;\n y = 2; // note");
assert!(out.contains("\n end\n"), "the block's `end` was swallowed:\n{out}");
assert!(out.contains("function int f();"), "the next item was not formatted:\n{out}");
assert!(out.contains(" return 1;"), "the next body was not formatted:\n{out}");
}
#[test]
fn a_fork_body_and_a_task_body_are_each_their_own_scope() {
let src = "module m;\n task automatic t();\n fork\n // lucisv: off\n p1 ();\n p2 ();\n // lucisv: on\n p3 ();\n join\n z = 1;\n endtask\nendmodule\n";
let out =
fenced(src, " // lucisv: off\n p1 ();\n p2 ();\n // lucisv: on");
assert!(out.contains(" p3();"), "the statement after the `on` was not formatted:\n{out}");
assert!(out.contains(" z = 1;"), "the task body after the fork was not formatted:\n{out}");
}
#[test]
fn a_class_body_is_a_fenceable_scope() {
let src = "class c;\n int a;\n // lucisv: off\n int b = 2;\n int cc =3;\n // lucisv: on\n int d;\nendclass\n";
let out = fenced(src, " // lucisv: off\n int b = 2;\n int cc =3;\n // lucisv: on");
assert!(out.contains(" int a;\n"), "{out}");
assert!(out.contains(" int d;\n"), "{out}");
}
#[test]
fn an_unmatched_off_in_a_class_body_stops_at_endclass() {
let src = "class c;\n // lucisv: off\n int a; // note\nendclass\n\nclass d;\n int b;\nendclass\n";
let out = fenced(src, " // lucisv: off\n int a; // note");
assert!(out.contains("class d;\n int b;\n"), "the next class was not formatted:\n{out}");
}
#[test]
fn a_fence_sharing_its_line_with_code_is_an_ordinary_comment() {
// `begin // lucisv: off` reaches the scan as the *leading* comment of the
// first statement, mid-line. Honouring it would open a region whose first
// line came from the wrong column; it is an ordinary comment instead.
let src = "module m;\n always @(*) begin // lucisv: off\n x = 1;\n y = 2;\n end\nendmodule\n";
let out = fmt(src);
verify_equivalence(src, &out).expect("equivalent");
assert_eq!(fmt(&out), out, "second pass changed the output");
assert!(out.contains(" x = 1;"), "the fence fired mid-line:\n{out}");
// The same rule at item level: a header's own line is not a fence line.
let src = "module m; // lucisv: off\n wire a;\nendmodule\n";
let out = fmt(src);
verify_equivalence(src, &out).expect("equivalent");
assert_eq!(fmt(&out), out, "second pass changed the output");
assert!(out.contains(" wire a;"), "the fence fired mid-line:\n{out}");
}
#[test]
fn the_three_deferred_places_are_inert_and_never_corrupt() {
// A port list, a case-item label list, and the single-statement body of a
// bodyless `if`: a fence in each is an ordinary comment, and the code
// around it is laid out exactly as it would be without one.
let cases = [
"module m (\n // lucisv: off\n input logic a,\n output logic b\n);\nendmodule\n",
"module m;\n always @(*) case (s)\n // lucisv: off\n 2'b00: a = 1;\n 2'b01: a = 2;\n endcase\nendmodule\n",
"module m;\n always @(*)\n // lucisv: off\n if (c) x = 1;\nendmodule\n",
];
for src in cases {
let out = fmt(src);
verify_equivalence(src, &out).expect("output is token-equivalent to the input");
assert_eq!(fmt(&out), out, "second pass changed the output:\n{out}");
assert!(out.contains("lucisv: off"), "the fence comment was dropped:\n{out}");
assert!(!out.contains(" a = 1"), "the fence fenced:\n{out}");
assert!(!out.contains("input logic"), "the fence fenced:\n{out}");
}
}
#[test]
fn a_corrupted_statement_or_class_region_is_still_rejected_by_the_safety_net() {
// The same attack as at item level, aimed at the two new scopes: a fence
// is not a licence to change bytes, and a hand-built "output" that
// reformats, drops or adds anything inside one must fail equivalence.
// Every pair changes the *token stream*, which is the question
// `verify_equivalence` answers; that a region's bytes are also reproduced
// exactly — spacing included, which no token check can see — is what the
// `fenced` helper asserts in the tests above.
let stmt = "module m;\n initial begin\n // lucisv: off\n x = 1;\n y = 2; // note\n // lucisv: on\n end\nendmodule\n";
let stmt_corrupted = [
// a literal rewritten inside the region
"module m;\n initial begin\n // lucisv: off\n x = 7;\n y = 2; // note\n // lucisv: on\n end\nendmodule\n",
// the region's trailing comment dropped
"module m;\n initial begin\n // lucisv: off\n x = 1;\n y = 2;\n // lucisv: on\n end\nendmodule\n",
// the `off` fence itself dropped
"module m;\n initial begin\n x = 1;\n y = 2; // note\n // lucisv: on\n end\nendmodule\n",
// a statement added inside the region
"module m;\n initial begin\n // lucisv: off\n x = 1;\n z = 0;\n y = 2; // note\n // lucisv: on\n end\nendmodule\n",
// a statement dropped from inside the region
"module m;\n initial begin\n // lucisv: off\n x = 1;\n // lucisv: on\n end\nendmodule\n",
// the `on` fence turned into an ordinary comment
"module m;\n initial begin\n // lucisv: off\n x = 1;\n y = 2; // note\n // lucisv: onward\n end\nendmodule\n",
// the block's `end` swallowed into the region's last line
"module m;\n initial begin\n // lucisv: off\n x = 1;\n y = 2; // note\n // lucisv: on\nendmodule\n",
];
let class = "class c;\n // lucisv: off\n int b = 2;\n int cc =3;\n // lucisv: on\n int d;\nendclass\n";
let class_corrupted = [
// a type rewritten inside the region
"class c;\n // lucisv: off\n bit b = 2;\n int cc =3;\n // lucisv: on\n int d;\nendclass\n",
// a member dropped from inside the region
"class c;\n // lucisv: off\n int b = 2;\n // lucisv: on\n int d;\nendclass\n",
// a member added inside the region
"class c;\n // lucisv: off\n int b = 2;\n int cc =3;\n int e;\n // lucisv: on\n int d;\nendclass\n",
// `endclass` swallowed
"class c;\n // lucisv: off\n int b = 2;\n int cc =3;\n // lucisv: on\n int d;\n",
// a fence comment dropped
"class c;\n int b = 2;\n int cc =3;\n // lucisv: on\n int d;\nendclass\n",
];
for (src, corrupted) in [(stmt, &stmt_corrupted[..]), (class, &class_corrupted[..])] {
verify_equivalence(src, &fmt(src)).expect("the real output is equivalent");
for bad in corrupted {
assert!(
verify_equivalence(src, bad).is_err(),
"a corrupted fenced region was accepted:\n{bad}"
);
}
}
}
#[test]
fn the_matcher_agrees_with_what_the_formatter_honours() {
// The unit tests in `fence.rs` pin the matcher; this pins that the
+34
View File
@@ -218,6 +218,40 @@ fn a_fence_outranks_a_range() {
assert!(out.contains(" wire b;\n wire c;\n"), "the region is untouched: {out}");
}
const WITH_STMT_FENCE: &str = "\
module m;
initial begin
a = 1;
// lucisv: off
b = 2;
cc = 3;
// lucisv: on
d = 4;
end
endmodule
";
#[test]
fn a_statement_fence_outranks_a_range_too() {
// A fenced *statement* sits inside an item the caller's lines select, so
// there is no verbatim run behind it: the plan has to carry the fence
// itself or the region would be laid out. Selecting any line of it, or
// the whole block, must leave those bytes exactly as written.
for spec in ["4", "5", "6", "7", "2-10"] {
let out = fixed_point(WITH_STMT_FENCE, spec);
assert!(
out.contains(" // lucisv: off\n b = 2;\n cc = 3;\n // lucisv: on\n"),
"spec {spec} reformatted the region:\n{out}"
);
}
// Laying out the whole block still formats what is outside the region.
let out = fixed_point(WITH_STMT_FENCE, "2-10");
assert!(out.contains(" a = 1;"), "{out}");
assert!(out.contains(" d = 4;"), "{out}");
// And a range that misses the block entirely changes nothing at all.
assert_eq!(fixed_point(WITH_STMT_FENCE, "1"), WITH_STMT_FENCE);
}
const ALIGNED: &str = "\
module m;
localparam int A = 1;
@@ -0,0 +1,16 @@
//! Prints the `lucisv.lint.severity.*` and `lucisv.lint.rules.*` settings for
//! `editors/vscode/package.json`, generated from the rule registry.
//!
//! ```text
//! cargo run -p vlog_linter --example vscode_lint_settings
//! ```
//!
//! Paste the body of the printed object into that file's
//! `contributes.configuration.properties`, replacing the block that is there.
//! The drift test in `lucisv_server` (`settings::tests::
//! the_vscode_lint_toggles_match_the_registry`) fails whenever the two
//! disagree, so a rule cannot ship without its toggle.
fn main() {
print!("{}", vlog_linter::vscode_lint_settings());
}
+89
View File
@@ -84,6 +84,16 @@ impl ParsedSource {
&self.tokens
}
/// The tolerant parse itself — public for the same reason [`tokens`] is:
/// a caller that has already paid for the parse can read the tree for
/// something else (`lucisv check` harvests its interface census off it)
/// instead of parsing the same text twice.
///
/// [`tokens`]: ParsedSource::tokens
pub fn file(&self) -> &SourceFile {
&self.file
}
/// A lint context borrowing this parse. `path` is the file the text came
/// from, or `None` for a buffer (stdin) — rules that need a filename skip.
pub fn context(&self, path: Option<PathBuf>) -> LintContext<'_> {
@@ -125,6 +135,42 @@ enum Backing<'a> {
pub trait MentionOracle: Sync {
/// Whether any file **other than** the one being linted mentions `name`.
fn mentioned_elsewhere(&self, name: &str) -> bool;
/// What the project says the module or interface `name` declares, or
/// `None` when it cannot say — the unit is not in the project, or it is
/// declared more than once and the declarations disagree.
///
/// The second question a rule may ask about other files, added by TODO
/// §33.2 for `unknown-port` and `unknown-parameter`. It is deliberately
/// still a *closed* question — the names a connection list may use, and
/// nothing about them — and `None` is a first-class answer that every
/// caller must treat as silence rather than as an empty list. A front end
/// with no such table at all answers `None` to everything, which leaves
/// those two rules quiet and every other rule exactly where it was.
fn module_interface(&self, _name: &str) -> Option<ModuleInterface> {
None
}
}
/// The names a module or interface declares that an instantiation may write.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ModuleInterface {
/// Port names, as written.
pub ports: Vec<String>,
/// Overridable parameter names, as written — a `localparam` is not one.
pub parameters: Vec<String>,
}
impl ModuleInterface {
/// Whether the unit declares a port called `name`.
pub fn has_port(&self, name: &str) -> bool {
self.ports.iter().any(|port| port == name)
}
/// Whether the unit declares an overridable parameter called `name`.
pub fn has_parameter(&self, name: &str) -> bool {
self.parameters.iter().any(|parameter| parameter == name)
}
}
/// Where a context's symbol table comes from: lent by a caller that already
@@ -134,6 +180,12 @@ pub trait MentionOracle: Sync {
/// Lazy rather than eager because most rules are syntactic: a run with no
/// semantic rule enabled — which is every default `lucisv check`, since all
/// three semantic rules ship off — must not pay for an analysis nobody reads.
// The `Lazy` variant is the table itself, held inline on purpose: it is one
// per lint run, it is written exactly once, and boxing it would add an
// allocation to the path that already avoided one by not analyzing at all.
// `Semantics` grew past clippy's variant-size threshold when it gained its
// `duplicates` table (§33.2); nothing about the trade changed with it.
#[allow(clippy::large_enum_variant)]
enum SemanticsSlot<'a> {
Lent(&'a Semantics),
Lazy(OnceCell<Semantics>),
@@ -156,6 +208,9 @@ pub struct LintContext<'a> {
/// The signal table the semantic rules read, built once for all of them
/// the first time one asks — and never for a run with none enabled.
signals: OnceCell<Signals>,
/// Whether the tolerant parse produced no `Error` leaf, answered once for
/// the rules that read structure. See [`LintContext::parsed_cleanly`].
clean: OnceCell<bool>,
/// What the workspace says about a name, when the caller has a workspace.
/// `None` is a run that cannot see other files — a single-file
/// `lucisv check`, stdin, a unit test — and every rule that would consult
@@ -202,6 +257,7 @@ impl<'a> LintContext<'a> {
strings: Vec::new(),
semantics: SemanticsSlot::Lazy(OnceCell::new()),
signals: OnceCell::new(),
clean: OnceCell::new(),
oracle: None,
};
ctx.strings =
@@ -245,6 +301,13 @@ impl<'a> LintContext<'a> {
self.oracle.is_some_and(|oracle| oracle.mentioned_elsewhere(name))
}
/// What the project says the unit `name` declares. `None` — no oracle, no
/// such unit, or two that disagree — means the run cannot answer, and a
/// rule that asked must then say nothing.
pub fn module_interface(&self, name: &str) -> Option<ModuleInterface> {
self.oracle?.module_interface(name)
}
/// Whether this run can see other files at all.
pub fn has_oracle(&self) -> bool {
self.oracle.is_some()
@@ -266,6 +329,32 @@ impl<'a> LintContext<'a> {
self.signals.get_or_init(|| Signals::scan(self))
}
/// Whether the whole file fit the grammar — no `Error` leaf anywhere in
/// the tolerant parse.
///
/// The tolerant parse is what makes a text rule work in a half-written
/// buffer, and most rules are right to ignore the difference. A rule that
/// reads **structure** is not: error recovery unwinds out of the construct
/// it failed in, so the declarations that followed are bound in whatever
/// scope recovery landed in — a class method's locals end up at file
/// scope, and every one of them looks like a redeclaration of the last
/// method's. Measured on opentitan: `spi_device_scoreboard.sv` (454 parse
/// errors, a macro-heavy UVM file) produced sixteen such phantoms, which
/// is sixteen wrong accusations from one file. A rule that would rather be
/// silent than wrong asks this first.
pub fn parsed_cleanly(&self) -> bool {
*self.clean.get_or_init(|| {
let mut clean = true;
crate::visit::walk_items(self.file(), &mut |item| {
clean &= !matches!(item.kind, vlog_parser::ast::ItemKind::Error(_));
});
crate::visit::walk_all_stmts(self.file(), &mut |stmt| {
clean &= !matches!(stmt.kind, vlog_parser::ast::StmtKind::Error(_));
});
clean
})
}
/// The source text being linted.
pub fn source(&self) -> &str {
match &self.backing {
+229
View File
@@ -0,0 +1,229 @@
//! Every declared type and every dimension in a file.
//!
//! A `DataType` is written in a dozen places — a port, a parameter, a
//! declarator, a typedef's base, a struct member, a subroutine's return type
//! and its arguments — and the rules that judge a *type* (the packed-dimension
//! ordering, a negative array bound) care about all of them equally. Collecting
//! them lives here rather than in `visit`, which is about the item and
//! statement spines; keeping the two apart is what stops either file from
//! becoming "everything a rule might want to walk".
use vlog_parser::ast::{
DataType, Dim, EnumType, FunctionDecl, ItemKind, SourceFile, StmtKind, StructType, TaskDecl,
TfArg, TypeExtra, TypedefKind,
};
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
/// Where a dimension was written. The two are different constructs with
/// different conventions — `[N-1:0]` for a packed vector, `[N]` for an array —
/// so a rule that judges one must not judge the other by accident.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Packing {
/// Written before the declared name: a vector's width.
Packed,
/// Written after it: an array's extent.
Unpacked,
}
/// Calls `f` on every data type written in the file, an anonymous aggregate's
/// members and base included.
pub(crate) fn walk_data_types(file: &SourceFile, f: &mut dyn FnMut(&DataType)) {
let mut visit = |ty: &DataType| descend(ty, f);
walk_param_ports(file, &mut |port| visit(&port.ty));
walk_items(file, &mut |item| match &item.kind {
ItemKind::Module(module) => {
if let vlog_parser::ast::PortList::Ansi(ports) = &module.ports {
for port in ports {
visit(&port.ty);
}
}
}
ItemKind::Typedef(typedef) => typedef_types(&typedef.kind, &mut visit),
ItemKind::ParamDecl(decl) => visit(&decl.ty),
ItemKind::DataDecl(decl) => visit(&decl.ty),
ItemKind::PortDecl(decl) => visit(&decl.ty),
ItemKind::Function(decl) => function_types(decl, &mut visit),
ItemKind::Task(decl) => task_types(decl, &mut visit),
_ => {}
});
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
StmtKind::VarDecl(decl) => visit(&decl.ty),
StmtKind::ParamDecl(decl) => visit(&decl.ty),
StmtKind::PortDecl(decl) => visit(&decl.ty),
StmtKind::Typedef(typedef) => typedef_types(&typedef.kind, &mut visit),
_ => {}
});
}
/// Calls `f` on every dimension in the file, saying which kind it is.
pub(crate) fn walk_dims(file: &SourceFile, f: &mut dyn FnMut(Packing, &Dim)) {
walk_data_types(file, &mut |ty| {
for dim in &ty.packed {
f(Packing::Packed, dim);
}
});
walk_unpacked(file, f);
}
/// The unpacked half: the `[…]` written *after* a declared name.
fn walk_unpacked(file: &SourceFile, f: &mut dyn FnMut(Packing, &Dim)) {
let mut unpacked = |dims: &[Dim]| {
for dim in dims {
f(Packing::Unpacked, dim);
}
};
walk_param_ports(file, &mut |port| unpacked(&port.unpacked));
walk_items(file, &mut |item| match &item.kind {
ItemKind::Module(module) => {
if let vlog_parser::ast::PortList::Ansi(ports) = &module.ports {
for port in ports {
unpacked(&port.unpacked);
}
}
}
ItemKind::Typedef(typedef) => unpacked(&typedef.unpacked),
ItemKind::ParamDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
ItemKind::DataDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
ItemKind::PortDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
ItemKind::Function(decl) => arg_dims(&decl.args, &mut unpacked),
ItemKind::Task(decl) => arg_dims(&decl.args, &mut unpacked),
_ => {}
});
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
StmtKind::VarDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
StmtKind::ParamDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
StmtKind::PortDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
StmtKind::Typedef(typedef) => unpacked(&typedef.unpacked),
_ => {}
});
}
fn declarator_dims(declarators: &[vlog_parser::ast::Declarator], unpacked: &mut dyn FnMut(&[Dim])) {
for declarator in declarators {
unpacked(&declarator.unpacked);
}
}
fn arg_dims(args: &[TfArg], unpacked: &mut dyn FnMut(&[Dim])) {
for arg in args {
unpacked(&arg.unpacked);
}
}
fn typedef_types(kind: &TypedefKind, visit: &mut dyn FnMut(&DataType)) {
match kind {
TypedefKind::Alias(ty) => visit(ty),
TypedefKind::Enum(enum_ty) => enum_types(enum_ty, visit),
TypedefKind::Struct(struct_ty) => struct_types(struct_ty, visit),
TypedefKind::ForwardClass => {}
}
}
fn function_types(decl: &FunctionDecl, visit: &mut dyn FnMut(&DataType)) {
if let Some(ret) = &decl.ret {
visit(ret);
}
for arg in &decl.args {
visit(&arg.ty);
}
}
fn task_types(decl: &TaskDecl, visit: &mut dyn FnMut(&DataType)) {
for arg in &decl.args {
visit(&arg.ty);
}
}
fn enum_types(enum_ty: &EnumType, visit: &mut dyn FnMut(&DataType)) {
if let Some(base) = &enum_ty.base {
visit(base);
}
}
fn struct_types(struct_ty: &StructType, visit: &mut dyn FnMut(&DataType)) {
for member in &struct_ty.members {
visit(&member.ty);
}
}
/// One type and whatever aggregate it *is*: an anonymous `enum`'s base and an
/// anonymous `struct`'s members are types written inside this one.
fn descend(ty: &DataType, f: &mut dyn FnMut(&DataType)) {
f(ty);
match ty.inline() {
Some(TypeExtra::Enum(enum_ty)) => enum_types(enum_ty, &mut |inner| descend(inner, f)),
Some(TypeExtra::Struct(struct_ty)) => {
struct_types(struct_ty, &mut |inner| descend(inner, f))
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::parse_source_tolerant;
fn packed_widths(src: &str) -> Vec<String> {
let (file, _) = parse_source_tolerant(src);
let mut out = Vec::new();
walk_dims(&file, &mut |packing, dim| {
if packing == Packing::Packed {
out.push(src[dim.span.as_range()].to_string());
}
});
out
}
fn unpacked_extents(src: &str) -> Vec<String> {
let (file, _) = parse_source_tolerant(src);
let mut out = Vec::new();
walk_dims(&file, &mut |packing, dim| {
if packing == Packing::Unpacked {
out.push(src[dim.span.as_range()].to_string());
}
});
out
}
#[test]
fn reaches_the_packed_dimensions_of_every_declaration_shape() {
let src = "module m #(parameter logic [1:0] P = 0) (\n\
input logic [2:0] a\n\
);\n\
logic [3:0] b;\n\
typedef logic [4:0] w_t;\n\
function logic [5:0] f(input logic [6:0] x);\n\
logic [7:0] local_v;\n\
return 0;\n\
endfunction\n\
endmodule\n";
assert_eq!(
packed_widths(src),
vec!["[1:0]", "[2:0]", "[3:0]", "[4:0]", "[5:0]", "[6:0]", "[7:0]"]
);
}
#[test]
fn reaches_an_anonymous_aggregates_members_and_base() {
let src = "module m;\n\
struct packed { logic [1:0] a; logic [2:0] b; } s;\n\
enum logic [3:0] { A } e;\n\
endmodule\n";
assert_eq!(packed_widths(src), vec!["[1:0]", "[2:0]", "[3:0]"]);
}
#[test]
fn packed_and_unpacked_are_told_apart() {
let src = "module m;\n logic [1:0] q [4];\nendmodule\n";
assert_eq!(packed_widths(src), vec!["[1:0]"]);
assert_eq!(unpacked_extents(src), vec!["[4]"]);
}
#[test]
fn a_struct_member_is_reached_through_a_typedef() {
let src = "typedef struct packed {\n logic [9:0] wide;\n} w_t;\n";
assert_eq!(packed_widths(src), vec!["[9:0]"]);
}
}
+178
View File
@@ -0,0 +1,178 @@
//! What each module in one file declares that an instantiation may name.
//!
//! The language server answers [`MentionOracle::module_interface`] from its
//! workspace index, which already records every module's ports and parameters.
//! `lucisv check` has no index, so it reads the same facts off the parse it
//! makes anyway — this file is that reading, and it lives here so the CLI and
//! the linter cannot come to disagree about what "a port of this module" is.
//!
//! Erring is one-directional on purpose: a unit whose header lucisv cannot see
//! whole is reported as **unknowable** rather than as a short list, because a
//! short list is what turns a legal connection into an accusation.
use vlog_parser::ast::{ItemKind, Module, ParamPort, PortList, SourceFile};
use crate::context::ModuleInterface;
use crate::visit::walk_items;
/// Every module, interface and program the file declares, with what it
/// exposes. `None` for a unit whose header cannot be read whole.
///
/// A file may declare a name twice (two `` `ifdef`` arms, a copy-paste); the
/// caller merges across files and must treat any disagreement as unknowable,
/// so both entries are returned rather than one.
pub fn module_interfaces(file: &SourceFile) -> Vec<(String, Option<ModuleInterface>)> {
let mut out = Vec::new();
walk_items(file, &mut |item| {
if let ItemKind::Module(module) = &item.kind {
out.push((module.name.clone(), interface_of(module)));
}
});
out
}
/// One unit's surface, or `None` when its header is not fully visible.
fn interface_of(module: &Module) -> Option<ModuleInterface> {
// A directive written *between* ports or parameters may be a conditional
// — whose arms are all in the list, so the list stays a superset — or a
// macro invocation standing where a port belongs, whose expansion lucisv
// never sees. Telling the two apart would be a second preprocessor; a
// header with any directive in it is simply not answered for.
if !module.port_directives.is_empty() || !module.param_directives.is_empty() {
return None;
}
Some(ModuleInterface { ports: ports_of(module), parameters: parameters_of(module) })
}
/// The port names of either header style. A header with no port list at all
/// declares none, which is a fact rather than a gap: nothing may be connected
/// to it by name.
fn ports_of(module: &Module) -> Vec<String> {
match &module.ports {
PortList::Ansi(ports) => ports.iter().map(|port| port.name.clone()).collect(),
PortList::NonAnsi(ports) => ports.iter().map(|port| port.name.clone()).collect(),
PortList::None | PortList::Empty => Vec::new(),
}
}
/// The names an `#(.NAME(value))` override may write: every `parameter` in the
/// header and in the body.
///
/// A `localparam` is **not** one — it is the module's own constant and is not
/// overridable (IEEE 1800 §6.20.4), which is exactly the distinction
/// `SymbolKind::LocalParam` was parted out for. A header parameter written
/// without a keyword continues the previous declaration and inherits its
/// keyword, which is how `#(parameter int A = 1, B = 2)` declares two
/// overridable parameters.
fn parameters_of(module: &Module) -> Vec<String> {
let mut out = Vec::new();
let mut overridable = true;
for port in module.param_ports.iter().flatten() {
overridable = is_parameter(port, overridable);
if overridable {
out.push(port.name.clone());
}
}
for item in &module.items {
if let ItemKind::ParamDecl(decl) = &item.kind {
if decl.kw == "parameter" {
out.extend(decl.declarators.iter().map(|d| d.name.clone()));
}
}
}
out
}
/// Whether this header parameter is overridable, given whether the one before
/// it was: a written keyword decides, and no keyword continues.
fn is_parameter(port: &ParamPort, previous: bool) -> bool {
match port.kw.as_deref() {
Some("localparam") => false,
Some(_) => true,
None => previous,
}
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::parse_source_tolerant;
fn interfaces(src: &str) -> Vec<(String, Option<ModuleInterface>)> {
let (file, _) = parse_source_tolerant(src);
module_interfaces(&file)
}
fn only(src: &str) -> ModuleInterface {
let found = interfaces(src);
assert_eq!(found.len(), 1, "{found:?}");
found.into_iter().next().and_then(|(_, i)| i).expect("a readable header")
}
#[test]
fn reads_an_ansi_header() {
let read = only(
"module m #(parameter int Width = 8, localparam int Derived = Width + 1) (\n\
input logic clk_i,\n\
output logic [7:0] data_o\n\
);\n\
endmodule\n",
);
assert_eq!(read.ports, vec!["clk_i", "data_o"]);
assert_eq!(read.parameters, vec!["Width"], "a localparam is not overridable");
}
#[test]
fn reads_a_non_ansi_header() {
let read = only("module m (clk, rst_n);\n input clk;\n input rst_n;\nendmodule\n");
assert_eq!(read.ports, vec!["clk", "rst_n"]);
}
#[test]
fn a_continuation_parameter_inherits_its_keyword() {
let read = only("module m #(parameter int A = 1, B = 2) ();\nendmodule\n");
assert_eq!(read.parameters, vec!["A", "B"]);
let local = only("module m #(localparam int A = 1, B = 2) ();\nendmodule\n");
assert!(local.parameters.is_empty(), "both continue the localparam");
}
#[test]
fn a_body_parameter_is_overridable_and_a_body_localparam_is_not() {
let read =
only("module m ();\n parameter int Depth = 4;\n localparam int W = 2;\nendmodule\n");
assert_eq!(read.parameters, vec!["Depth"]);
}
#[test]
fn a_header_with_a_directive_in_it_is_unknowable() {
let src = "module m (\n\
`ifdef X\n\
input logic a,\n\
`endif\n\
input logic b\n\
);\n\
endmodule\n";
assert_eq!(interfaces(src), vec![("m".to_string(), None)]);
}
#[test]
fn a_port_less_module_declares_no_ports() {
let read = only("module m;\nendmodule\n");
assert!(read.ports.is_empty());
assert!(read.parameters.is_empty());
let empty = only("module m ();\nendmodule\n");
assert!(empty.ports.is_empty());
}
#[test]
fn an_interface_is_read_the_same_way() {
let read = only("interface bus_if (input logic clk);\nendinterface\n");
assert_eq!(read.ports, vec!["clk"]);
}
#[test]
fn every_unit_of_a_file_is_returned() {
let found = interfaces("module a ();\nendmodule\nmodule b ();\nendmodule\n");
assert_eq!(found.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(), vec!["a", "b"]);
}
}
+48 -2
View File
@@ -21,26 +21,36 @@
//! `docs/features/linter-core/README.md`.
mod context;
mod decls;
mod interfaces;
mod literal;
mod naming;
mod registry;
mod rule_docs;
mod rules;
mod severity;
mod signals;
mod violation;
mod visit;
mod vscode;
mod waiver;
use std::path::PathBuf;
pub use context::{LintContext, MentionOracle, ParsedSource};
pub use registry::{all_rules, default_rules, rule_by_name, select_rules, workspace_rules, Rule};
pub use context::{LintContext, MentionOracle, ModuleInterface, ParsedSource};
pub use interfaces::module_interfaces;
pub use registry::{
all_rules, default_rules, rule_by_name, rules_named, select_rules, workspace_rules, Rule,
};
pub use rule_docs::rules_markdown;
pub use severity::Severity;
pub use violation::{apply_fixes, Applicability, Fix, Fixed, Violation};
/// The identifier census a [`MentionOracle`] is answered from, re-exported
/// from `vlog_semantic` so a front end that implements the oracle needs this
/// crate alone. One harvest for the whole workspace — see
/// `docs/features/semantic-lints-on/README.md`.
pub use vlog_semantic::words;
pub use vscode::{rule_setting, severity_setting, vscode_lint_settings, RULE_CHOICES};
pub use waiver::UNUSED_WAIVER;
use waiver::Waivers;
@@ -87,9 +97,24 @@ pub fn lint(ctx: &LintContext, enabled: &[&'static dyn Rule]) -> Vec<Violation>
kept.sort_by(|a, b| {
(a.span.start, a.span.end, a.rule).cmp(&(b.span.start, b.span.end, b.rule))
});
stamp_severities(&mut kept);
kept
}
/// Gives every finding the class its rule declares.
///
/// One place rather than one per rule: a rule's `check` builds violations
/// without knowing what it is called, the `unused-waiver` findings are built by
/// the waiver scanner and not by a rule at all, and a severity written twice
/// would eventually be written differently. See [`Violation::severity`].
fn stamp_severities(violations: &mut [Violation]) {
for violation in violations {
if let Some(rule) = rule_by_name(violation.rule) {
violation.severity = rule.severity();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -211,6 +236,27 @@ mod tests {
assert!(run(src, None, &enabled).is_empty());
}
/// Every finding the runner returns carries its rule's class — including
/// the `unused-waiver` ones, which no rule's `check` produced.
#[test]
fn the_runner_stamps_every_finding_with_its_rules_severity() {
let src = "module m;\n\
\treg a; // lucisv: waive no-such-rule\n\
\talways_comb a <= 1'b0;\n\
endmodule\n";
let found = run(src, Some(PathBuf::from("rtl/m.sv")), &default_rules());
assert!(found.len() >= 3, "{found:#?}");
for violation in &found {
let rule = rule_by_name(violation.rule).expect("a registered rule");
assert_eq!(violation.severity, rule.severity(), "{}", violation.rule);
}
let by_rule =
|name: &str| found.iter().find(|v| v.rule == name).map(|v| v.severity).expect(name);
assert_eq!(by_rule("wire-reg-mixup"), Severity::Error);
assert_eq!(by_rule("always-comb-blocking"), Severity::Warning);
assert_eq!(by_rule(UNUSED_WAIVER), Severity::Style);
}
#[test]
fn a_file_that_does_not_parse_still_gets_its_text_rules() {
let src = "module m;\n\t@@@ this is not verilog\nendmodule\n";
+156
View File
@@ -0,0 +1,156 @@
//! Sized based literals, read the way the two width rules need them.
//!
//! `truncated-numeric-literal` asks "how many bits does what is written
//! actually need?" and `undersized-binary-literal` asks "how many digits were
//! written?". Both questions are about the same `<size>'<base><digits>` shape,
//! so it is parsed once here rather than twice, slightly differently.
/// One `<size>'[s]<base><digits>` literal, as written.
///
/// Only the *sized* spelling is modelled: an unsized `'h1f` takes its width
/// from context, so neither rule has anything to compare against and
/// [`parse`] returns `None` for it.
pub(crate) struct SizedLiteral<'a> {
/// The declared width, in bits.
pub width: u32,
/// The base letter, lower-cased: `b`, `o`, `d` or `h`.
pub base: char,
/// The digits as written, `_` separators included.
pub digits: &'a str,
}
impl SizedLiteral<'_> {
/// The digits with the `_` separators taken out.
pub fn packed_digits(&self) -> String {
self.digits.chars().filter(|c| *c != '_').collect()
}
/// How many bits the written value really needs, or `None` when that
/// cannot be said: an empty or malformed digit run, or a decimal value
/// carrying `x`/`z`.
///
/// A digit that is `x`, `z` or `?` counts as full-width — `4'hxF` needs
/// eight bits, because the unknown nibble is still a nibble.
pub fn significant_bits(&self) -> Option<u32> {
let digits = self.packed_digits();
let digits = digits.trim_start_matches('0');
if digits.is_empty() {
return Some(0);
}
let Some(per_digit) = bits_per_digit(self.base) else {
// Decimal: the whole run is one number, so an `x` in it makes the
// value unknown rather than one unknown digit.
let value: u128 = digits.parse().ok()?;
return Some(128 - value.leading_zeros());
};
let mut chars = digits.chars();
let first = chars.next()?;
let rest = chars.count() as u32;
let head = match first.to_ascii_lowercase() {
'x' | 'z' | '?' => per_digit,
c => bits_of(c, self.base)?,
};
Some(rest * per_digit + head)
}
}
/// Reads a sized based literal, or `None` for anything else — an unsized
/// literal, a plain decimal, a real, a time literal.
pub(crate) fn parse(text: &str) -> Option<SizedLiteral<'_>> {
let (size, rest) = text.split_once('\'')?;
let width: u32 = size.chars().filter(|c| *c != '_').collect::<String>().parse().ok()?;
// `8'sh1f` — the signedness marker sits between the tick and the base.
let rest = rest.strip_prefix(['s', 'S']).unwrap_or(rest);
let mut chars = rest.chars();
let base = chars.next()?.to_ascii_lowercase();
if !matches!(base, 'b' | 'o' | 'd' | 'h') {
return None;
}
let digits = rest.get(1..)?;
if digits.is_empty() || !digits.chars().all(|c| is_digit_of(c, base) || c == '_') {
return None;
}
Some(SizedLiteral { width, base, digits })
}
/// How many bits one digit of `base` carries; `None` for decimal, which is not
/// a per-digit base at all.
fn bits_per_digit(base: char) -> Option<u32> {
match base {
'b' => Some(1),
'o' => Some(3),
'h' => Some(4),
_ => None,
}
}
/// How many bits one known digit's value needs (`7` needs three, `1` needs
/// one), or `None` when the character is not a digit of this base.
fn bits_of(c: char, base: char) -> Option<u32> {
let value = c.to_digit(16)?;
let per_digit = bits_per_digit(base)?;
if value >= 1 << per_digit {
return None;
}
Some(32 - value.leading_zeros())
}
/// True when `c` may stand among `base`'s digits, unknowns included.
fn is_digit_of(c: char, base: char) -> bool {
let c = c.to_ascii_lowercase();
if matches!(c, 'x' | 'z' | '?') {
return true;
}
match base {
'b' => matches!(c, '0' | '1'),
'o' => c.is_digit(8),
'd' => c.is_ascii_digit(),
_ => c.is_ascii_hexdigit(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn bits(text: &str) -> Option<u32> {
parse(text)?.significant_bits()
}
#[test]
fn a_sized_literal_is_read_in_every_base() {
for (text, width, base, digits) in [
("8'hFF", 8, 'h', "FF"),
("4'b1010", 4, 'b', "1010"),
("3'o7", 3, 'o', "7"),
("16'd1000", 16, 'd', "1000"),
("8'sh1f", 8, 'h', "1f"),
("32'hdead_beef", 32, 'h', "dead_beef"),
] {
let found = parse(text).unwrap_or_else(|| panic!("{text}"));
assert_eq!((found.width, found.base, found.digits), (width, base, digits), "{text}");
}
}
#[test]
fn anything_that_is_not_a_sized_based_literal_is_declined() {
for text in ["'h1f", "42", "1.5", "10ns", "8'", "8'q1", "8'h", "8'hG", "'0"] {
assert!(parse(text).is_none(), "{text}");
}
}
#[test]
fn significant_bits_counts_what_is_written() {
assert_eq!(bits("4'h0"), Some(0));
assert_eq!(bits("4'h1"), Some(1));
assert_eq!(bits("4'h8"), Some(4));
assert_eq!(bits("4'hFFF"), Some(12), "three full nibbles");
assert_eq!(bits("8'b0000_0001"), Some(1), "leading zeros do not count");
assert_eq!(bits("4'o7"), Some(3));
assert_eq!(bits("8'd255"), Some(8));
assert_eq!(bits("8'd256"), Some(9));
assert_eq!(bits("4'hx"), Some(4), "an unknown nibble is still a nibble");
assert_eq!(bits("4'h0x"), Some(4), "and leading zeros still do not count");
assert_eq!(bits("8'dx"), None, "a decimal unknown says nothing about width");
}
}
+155 -11
View File
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::rules;
use crate::severity::Severity;
use crate::violation::{Applicability, Violation};
/// One lint rule.
@@ -17,6 +18,14 @@ pub trait Rule: Sync {
/// One line, imperative, no trailing period.
fn summary(&self) -> &'static str;
/// How bad this rule's findings are.
///
/// Deliberately without a default: a class is a claim about what a finding
/// means to the user, and a rule that inherited one silently would be
/// making that claim by accident. The reason for the class chosen belongs
/// in [`Rule::doc`].
fn severity(&self) -> Severity;
/// Why the rule exists — the style-guide rationale, in prose.
fn doc(&self) -> &'static str;
@@ -60,19 +69,38 @@ pub fn all_rules() -> Vec<&'static dyn Rule> {
&rules::always_comb_blocking::AlwaysCombBlocking,
&rules::always_ff_non_blocking::AlwaysFfNonBlocking,
&rules::case_missing_default::CaseMissingDefault,
&rules::duplicate_declaration::DuplicateDeclaration,
&rules::empty_item::EmptyItem,
&rules::enum_name_style::EnumNameStyle,
&rules::explicit_function_task_parameter_type::ExplicitFunctionTaskParameterType,
&rules::explicit_parameter_storage_type::ExplicitParameterStorageType,
&rules::forbid_defparam::ForbidDefparam,
&rules::forbid_negative_array_dim::ForbidNegativeArrayDim,
&rules::incomplete_assignment::IncompleteAssignment,
&rules::instance_shadowing::InstanceShadowing,
&rules::invalid_system_task_function::InvalidSystemTaskFunction,
&rules::mismatched_labels::MismatchedLabels,
&rules::module_filename::ModuleFilename,
&rules::module_name_style::ModuleNameStyle,
&rules::module_parameter::ModuleParameter,
&rules::module_port::ModulePort,
&rules::multiply_driven::MultiplyDriven,
&rules::no_tabs::NoTabs,
&rules::no_trailing_whitespace::NoTrailingWhitespace,
&rules::packed_dimensions_range_ordering::PackedDimensionsRangeOrdering,
&rules::parameter_name_style::ParameterNameStyle,
&rules::plusarg_assignment::PlusargAssignment,
&rules::struct_union_name_style::StructUnionNameStyle,
&rules::suspicious_semicolon::SuspiciousSemicolon,
&rules::truncated_numeric_literal::TruncatedNumericLiteral,
&rules::undeclared_identifier::UndeclaredIdentifier,
&rules::undersized_binary_literal::UndersizedBinaryLiteral,
&rules::undriven_net::UndrivenNet,
&rules::unknown_parameter::UnknownParameter,
&rules::unknown_port::UnknownPort,
&rules::unused_signal::UnusedSignal,
&rules::unused_waiver::UnusedWaiver,
&rules::void_cast::VoidCast,
&rules::wire_reg_mixup::WireRegMixup,
]
}
@@ -112,10 +140,25 @@ pub fn rule_by_name(name: &str) -> Option<&'static dyn Rule> {
all_rules().into_iter().find(|rule| rule.name() == name)
}
/// The rules one `--select` / `--ignore` name stands for.
///
/// A rule name stands for itself; a **severity name** (`error`, `warning`,
/// `style`) stands for every rule of that class, so `--ignore style` is one
/// word for the whole family. `None` for a name that is neither, which is what
/// makes a typo a failed run rather than a silently empty selection.
pub fn rules_named(name: &str) -> Option<Vec<&'static dyn Rule>> {
if let Some(rule) = rule_by_name(name) {
return Some(vec![rule]);
}
let severity = Severity::from_name(name)?;
Some(all_rules().into_iter().filter(|rule| rule.severity() == severity).collect())
}
/// The rules a run should use: `select` replaces the default set (empty means
/// keep it), then `ignore` removes from whatever is left. An unknown name on
/// either list is an error rather than a silent no-op — a typo'd `--select`
/// that quietly ran everything would be worse than a failed run.
/// keep it), then `ignore` removes from whatever is left. Either list may name
/// a rule or a whole severity ([`rules_named`]). An unknown name on either
/// list is an error rather than a silent no-op — a typo'd `--select` that
/// quietly ran everything would be worse than a failed run.
///
/// `workspace` only reaches [`default_rules`]: an explicit `select` names the
/// rules it wants and gets them, oracle or no oracle, exactly as an explicit
@@ -128,25 +171,27 @@ pub fn select_rules(
let mut chosen = if select.is_empty() {
enabled_rules(workspace)
} else {
let mut chosen = Vec::new();
let mut chosen: Vec<&'static dyn Rule> = Vec::new();
for name in select {
let rule = rule_by_name(name).ok_or_else(|| unknown(name))?;
if !chosen.iter().any(|r: &&'static dyn Rule| r.name() == rule.name()) {
chosen.push(rule);
for rule in rules_named(name).ok_or_else(|| unknown(name))? {
if !chosen.iter().any(|r| r.name() == rule.name()) {
chosen.push(rule);
}
}
}
chosen
};
for name in ignore {
rule_by_name(name).ok_or_else(|| unknown(name))?;
chosen.retain(|rule| rule.name() != name);
let dropped = rules_named(name).ok_or_else(|| unknown(name))?;
chosen.retain(|rule| !dropped.iter().any(|d| d.name() == rule.name()));
}
Ok(chosen)
}
fn unknown(name: &str) -> String {
let known = all_rules().iter().map(|r| r.name()).collect::<Vec<_>>().join(", ");
format!("unknown rule: {name} (known rules: {known})")
let severities = Severity::ALL.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
format!("unknown rule: {name} (severities: {severities}; known rules: {known})")
}
#[cfg(test)]
@@ -211,7 +256,17 @@ mod tests {
let project: Vec<&str> = workspace_rules().iter().map(|r| r.name()).collect();
let added: Vec<&str> =
project.iter().copied().filter(|name| !alone.contains(name)).collect();
assert_eq!(added, vec!["multiply-driven", "undriven-net", "unused-signal"]);
assert_eq!(
added,
vec![
"multiply-driven",
"undeclared-identifier",
"undriven-net",
"unknown-parameter",
"unknown-port",
"unused-signal",
]
);
assert!(alone.iter().all(|name| project.contains(name)), "a workspace never removes one");
for rule in all_rules() {
assert_eq!(rule.needs_workspace(), added.contains(&rule.name()), "{}", rule.name());
@@ -283,6 +338,95 @@ mod tests {
assert!(message.contains("no-tabs"), "the error must list what is known: {message}");
}
/// Every rule states a class, and no rule name collides with a class
/// name — otherwise `--select error` would mean two things.
#[test]
fn every_rule_has_a_severity_and_no_name_shadows_a_class() {
for rule in all_rules() {
assert!(Severity::ALL.contains(&rule.severity()), "{}", rule.name());
assert!(
Severity::from_name(rule.name()).is_none(),
"{} shadows a severity word",
rule.name()
);
}
}
/// The assignments §33.0 wrote down for the seventeen rules that predate
/// severities. A rule moving class is a user-visible change, so it moves
/// here first.
#[test]
fn the_original_seventeen_keep_the_classes_they_were_given() {
let expected: &[(&str, Severity)] = &[
("multiply-driven", Severity::Error),
("wire-reg-mixup", Severity::Error),
("always-comb-blocking", Severity::Warning),
("always-ff-non-blocking", Severity::Warning),
("case-missing-default", Severity::Warning),
("undriven-net", Severity::Warning),
("unused-signal", Severity::Warning),
("empty-item", Severity::Style),
("enum-name-style", Severity::Style),
("explicit-parameter-storage-type", Severity::Style),
("module-filename", Severity::Style),
("module-name-style", Severity::Style),
("no-tabs", Severity::Style),
("no-trailing-whitespace", Severity::Style),
("parameter-name-style", Severity::Style),
("struct-union-name-style", Severity::Style),
("unused-waiver", Severity::Style),
];
for (name, severity) in expected {
let rule = rule_by_name(name).unwrap_or_else(|| panic!("{name} exists"));
assert_eq!(rule.severity(), *severity, "{name}");
}
}
#[test]
fn a_severity_name_stands_for_every_rule_of_that_class() {
for severity in Severity::ALL {
let named = rules_named(severity.as_str()).unwrap_or_default();
let expected: Vec<&str> = all_rules()
.into_iter()
.filter(|rule| rule.severity() == severity)
.map(|rule| rule.name())
.collect();
assert_eq!(named.iter().map(|r| r.name()).collect::<Vec<_>>(), expected);
assert!(!expected.is_empty(), "{severity:?} has no rules");
}
assert!(rules_named("no-tabs").is_some_and(|rules| rules.len() == 1));
assert!(rules_named("no-such-thing").is_none());
}
/// `--select style`, `--ignore warning`: the whole point of the words.
#[test]
fn select_and_ignore_accept_a_severity_wherever_a_rule_fits() {
let styled = select_rules(&["style".to_string()], &[], true).unwrap();
assert!(styled.iter().all(|rule| rule.severity() == Severity::Style));
assert!(styled.iter().any(|rule| rule.name() == "no-tabs"));
let quiet = select_rules(&[], &["style".to_string()], true).unwrap();
assert!(quiet.iter().all(|rule| rule.severity() != Severity::Style));
assert!(quiet.iter().any(|rule| rule.name() == "unused-signal"), "warnings survive");
// A severity and a rule name mix on one list, and the same rule named
// twice is still selected once.
let mixed =
select_rules(&["style".to_string(), "no-tabs".to_string()], &[], false).unwrap();
assert_eq!(mixed.iter().filter(|rule| rule.name() == "no-tabs").count(), 1);
// Ignoring a class removes it from an explicit selection too.
let none = select_rules(&["no-tabs".to_string()], &["style".to_string()], false).unwrap();
assert!(none.is_empty());
}
#[test]
fn the_unknown_name_error_names_the_severity_words_too() {
let message = select_rules(&["styles".to_string()], &[], false).err().unwrap_or_default();
assert!(message.contains("style"), "{message}");
assert!(message.contains("no-tabs"), "{message}");
}
#[test]
fn lookup_by_name_finds_every_rule_and_nothing_else() {
for rule in all_rules() {
+78 -18
View File
@@ -7,6 +7,7 @@
//! this.
use crate::registry::all_rules;
use crate::severity::Severity;
/// The whole rule reference as one markdown document.
pub fn rules_markdown() -> String {
@@ -15,6 +16,12 @@ pub fn rules_markdown() -> String {
out.push_str(
"Generated from the rule registry by `vlog_linter::rules_markdown` — \
do not edit by hand.\n\n\
Every rule is in one of three **severity** classes, and the class is \
a word `--select` and `--ignore` accept wherever a rule name fits \
(`--ignore style`, `--select error`). **error** is code that would \
very likely fail to compile, elaborate or synthesize; **warning** is \
code that compiles but very likely does not mean what it says; \
**style** is code that is correct and reads badly.\n\n\
A rule marked **on** runs for a plain `lucisv check`; the others need \
`--select <name>`. A rule marked **on (project)** runs by default \
only where lucisv can see the other files of the project — \
@@ -26,23 +33,32 @@ pub fn rules_markdown() -> String {
<name>`.\n\n",
);
out.push_str("| Rule | Default | Fix |\n|---|---|---|\n");
out.push_str("| Rule | Severity | Default | Fix |\n|---|---|---|---|\n");
for rule in all_rules() {
out.push_str(&format!(
"| [`{name}`](#{name}) | {default} | {fix} |\n",
"| [`{name}`](#{name}) | {severity} | {default} | {fix} |\n",
name = rule.name(),
severity = rule.severity().as_str(),
default = default_word(rule),
fix = fix_word(rule),
));
}
out.push('\n');
for rule in all_rules() {
out.push_str(&format!("## {}\n\n", rule.name()));
out.push_str(&format!("{}.\n\n", capitalize(rule.summary())));
out.push_str(&format!("- Default: {}\n- Fix: {}\n\n", default_word(rule), fix_word(rule)));
out.push_str(rule.doc());
out.push_str("\n\n");
for severity in Severity::ALL {
out.push_str(&format!("# {} — {}\n\n", severity.as_str(), severity.describes()));
for rule in all_rules().into_iter().filter(|rule| rule.severity() == severity) {
out.push_str(&format!("## {}\n\n", rule.name()));
out.push_str(&format!("{}.\n\n", capitalize(rule.summary())));
out.push_str(&format!(
"- Severity: {}\n- Default: {}\n- Fix: {}\n\n",
severity.as_str(),
default_word(rule),
fix_word(rule),
));
out.push_str(rule.doc());
out.push_str("\n\n");
}
}
out
}
@@ -98,7 +114,7 @@ mod tests {
fn the_index_lists_every_rule_once() {
let markdown = rules_markdown();
for rule in all_rules() {
let row = format!("| [`{0}`](#{0}) |", rule.name());
let row = format!("| [`{0}`](#{0}) | ", rule.name());
assert_eq!(markdown.matches(&row).count(), 1, "{}", rule.name());
}
}
@@ -106,27 +122,62 @@ mod tests {
#[test]
fn defaults_and_fixes_are_rendered_from_the_registry() {
let markdown = rules_markdown();
assert!(markdown.contains("| [`no-tabs`](#no-tabs) | **on** | safe |"));
assert!(markdown.contains("| [`module-name-style`](#module-name-style) | off | none |"));
assert!(markdown.contains("| [`no-tabs`](#no-tabs) | style | **on** | safe |"));
assert!(
markdown.contains("| [`module-name-style`](#module-name-style) | style | off | none |")
);
// The three semantic rules are fixless, and default on exactly where
// there is a project to ask about a name — see
// docs/features/semantic-lints-on/README.md.
for name in ["multiply-driven", "undriven-net", "unused-signal"] {
for (name, severity) in [
("multiply-driven", "error"),
("undriven-net", "warning"),
("unused-signal", "warning"),
] {
assert!(
markdown.contains(&format!("| [`{name}`](#{name}) | **on (project)** | none |")),
markdown.contains(&format!(
"| [`{name}`](#{name}) | {severity} | **on (project)** | none |"
)),
"{name}"
);
}
assert_eq!(fix_word(&crate::rules::no_tabs::NoTabs), Applicability::Safe.as_str());
}
/// Every rule sits under the heading of its own class, and the three
/// headings are written worst-first.
#[test]
fn the_sections_are_grouped_by_severity() {
let markdown = rules_markdown();
let heading = |severity: Severity| {
markdown
.find(&format!("\n# {} — ", severity.as_str()))
.unwrap_or_else(|| panic!("{severity:?} heading"))
};
let (error, warning, style) =
(heading(Severity::Error), heading(Severity::Warning), heading(Severity::Style));
assert!(error < warning && warning < style, "worst first");
for rule in all_rules() {
let at = markdown
.find(&format!("\n## {}\n", rule.name()))
.unwrap_or_else(|| panic!("{}", rule.name()));
let own = heading(rule.severity());
let next = [error, warning, style]
.into_iter()
.filter(|start| *start > own)
.min()
.unwrap_or(markdown.len());
assert!(own < at && at < next, "{} is under the wrong heading", rule.name());
}
}
#[test]
fn the_document_shape_is_pinned() {
// A golden test on the *shape*, not on the prose: the heading, the
// generated-by note, the index table header, and the first per-rule
// section, which together are what a reader (and any renderer) sees.
let markdown = rules_markdown();
let head: Vec<&str> = markdown.lines().take(8).collect();
let head: Vec<&str> = markdown.lines().take(10).collect();
assert_eq!(
head,
vec![
@@ -135,6 +186,12 @@ mod tests {
"Generated from the rule registry by `vlog_linter::rules_markdown` — do not edit \
by hand.",
"",
"Every rule is in one of three **severity** classes, and the class is a word \
`--select` and `--ignore` accept wherever a rule name fits (`--ignore style`, \
`--select error`). **error** is code that would very likely fail to compile, \
elaborate or synthesize; **warning** is code that compiles but very likely does \
not mean what it says; **style** is code that is correct and reads badly.",
"",
"A rule marked **on** runs for a plain `lucisv check`; the others need \
`--select <name>`. A rule marked **on (project)** runs by default only where \
lucisv can see the other files of the project — `lucisv check <dir>`, or the \
@@ -143,13 +200,16 @@ mod tests {
rule can be turned off with `--ignore <name>`, with `ignore` under `[lint]` in \
`lucisv.toml`, or waived in the source with `// lucisv: waive <name>`.",
"",
"| Rule | Default | Fix |",
"|---|---|---|",
"| Rule | Severity | Default | Fix |",
"|---|---|---|---|",
]
);
let first_rule = all_rules()[0];
let first_rule = all_rules()
.into_iter()
.find(|rule| rule.severity() == Severity::Error)
.expect("some rule is an error");
let section = format!(
"## {}\n\n{}.\n\n- Default: {}\n- Fix: {}\n\n{}\n\n",
"## {}\n\n{}.\n\n- Severity: error\n- Default: {}\n- Fix: {}\n\n{}\n\n",
first_rule.name(),
capitalize(first_rule.summary()),
default_word(first_rule),
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_items, walk_stmts};
use vlog_parser::ast::{ItemKind, StmtKind};
@@ -20,6 +21,10 @@ impl Rule for AlwaysCombBlocking {
"assign with `=` inside always_comb"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A non-blocking assignment in a combinational block schedules its \
update for the end of the time step, so a value read later in the same \
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_items, walk_stmts};
use vlog_parser::ast::{ItemKind, StmtKind};
@@ -20,6 +21,10 @@ impl Rule for AlwaysFfNonBlocking {
"assign with `<=` inside always_ff"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A blocking assignment in a clocked block updates immediately, so two \
flops written in one `always_ff` can see each other's new value in \
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_all_stmts, walk_items};
use vlog_parser::ast::{CaseItem, GenCaseItem, ItemKind, StmtKind};
@@ -21,6 +22,10 @@ impl Rule for CaseMissingDefault {
"give every case statement a default branch"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A case statement with no `default` infers a latch in combinational \
logic and leaves the unlisted patterns unspecified in simulation — the \
@@ -0,0 +1,197 @@
//! `duplicate-declaration` — one name declared twice in one scope.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_semantic::{ScopeKind, SymbolKind};
/// See [`Rule::doc`].
pub struct DuplicateDeclaration;
const NAME: &str = "duplicate-declaration";
impl Rule for DuplicateDeclaration {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"declare each name once per scope"
}
fn severity(&self) -> Severity {
Severity::Error
}
fn doc(&self) -> &'static str {
"Two declarations of one name in one scope is an elaboration error in \
every tool (IEEE 1800 §3.13 — an identifier is unique within its \
namespace and scope). It happens when a signal is copied and the \
paste is not renamed, when two parameters are merged from different \
branches, or when a `logic` is declared beside the `input` of the \
same name. Verible has no equivalent rule; this is TODO §33's own, \
and it is an **Error** because the file will not compile.\n\n\
**Silent whenever the second declaration might be legal**, which is \
the rule every Error-class check here follows. It says nothing when \
either declaration is a **port** — a non-ANSI port is *completed* by \
a body `input clk;` and then by a `logic clk;`, all three of which \
are the same port and all three legal — nor about a function, task, \
class, constraint, covergroup, property, sequence, modport or \
clocking name, each of which has a legal prototype-plus-definition \
or forward-declaration shape. It says nothing inside a `generate` \
scope, where only one arm is ever elaborated, and nothing when a \
conditional-compilation directive stands between the two \
declarations, which is that same exclusivity written for the \
preprocessor. What is left is two ordinary declarations of one name, \
side by side, in one scope. No automatic fix: which of the two the \
author meant to keep is not something a linter can know."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
// Error recovery rebinds whatever followed a construct it could not
// parse into whatever scope it unwound to, which turns every later
// local into a phantom redeclaration. An Error-class rule says nothing
// about a file it cannot trust the shape of.
if !ctx.parsed_cleanly() {
return Vec::new();
}
let semantics = ctx.semantics();
let mut out = Vec::new();
for duplicate in semantics.duplicates() {
let Some(first) = semantics.symbol(duplicate.first) else { continue };
if !plain(duplicate.kind) || !plain(first.kind) {
continue;
}
let scope = semantics.scope(duplicate.scope).map(|scope| scope.kind);
// A generate scope elaborates one arm at a time; the file scope is
// where a `` `include``d fragment and a recovered construct both
// land, and two file-scope units of one name are the workspace's
// business rather than this file's.
if matches!(scope, Some(ScopeKind::Generate) | Some(ScopeKind::File)) {
continue;
}
let spans = [first.name_span.start, duplicate.name_span.start];
if ctx.signals().conditional_between(&spans) {
continue;
}
out.push(Violation::new(
NAME,
format!("`{}` is already declared in this scope", duplicate.name),
duplicate.name_span,
));
}
out
}
}
/// True for the declaration kinds that may be written **once** and once only.
///
/// Everything left out has a legal shape in which the same name is written
/// twice: a port is completed by its body declaration, a function or task by
/// its out-of-body definition, a class by its `typedef class` forward
/// declaration, and a constraint, covergroup, property or sequence by its own
/// prototype. An **enum member** is left out for a different reason: IEEE 1800
/// §6.19's name *range* (`RvCoreCsrGprT[0:2]`) declares a run of members under
/// one written identifier, and the binder records the identifier — so two
/// disjoint ranges of one base name look like one name declared twice when the
/// members they declare do not collide at all (measured on opentitan:
/// `jtag_rv_debugger_pkg.sv`). Listed positively rather than as an exclusion
/// list, so a kind added to `vlog_semantic` later is silent until somebody
/// decides it belongs.
fn plain(kind: SymbolKind) -> bool {
matches!(
kind,
SymbolKind::Net
| SymbolKind::Var
| SymbolKind::Param
| SymbolKind::LocalParam
| SymbolKind::Genvar
| SymbolKind::Typedef
| SymbolKind::Instance
| SymbolKind::TfArg
| SymbolKind::StructMember
)
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
DuplicateDeclaration.check(&LintContext::new(src, None))
}
#[test]
fn flags_two_signals_of_one_name() {
let src = "module m;\n logic a;\n logic a;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`a`"), "{}", found[0].message);
assert_eq!(found[0].span.start as usize, src.rfind('a').map(|i| i - 1).unwrap_or(0) + 1);
assert!(found[0].fix.is_none());
}
#[test]
fn flags_two_parameters_two_typedefs_and_two_instances() {
for src in [
"module m;\n parameter int W = 1;\n parameter int W = 2;\nendmodule\n",
"module m;\n typedef logic t;\n typedef bit t;\nendmodule\n",
"module m;\n sub u ();\n sub u ();\nendmodule\n",
] {
assert_eq!(violations(src).len(), 1, "{src}");
}
}
/// The non-ANSI shape: the header names the port, the body declares its
/// direction and then its type. Three declarations, one port, all legal.
#[test]
fn a_non_ansi_port_completed_in_the_body_is_never_flagged() {
let src = "module m (clk);\n input clk;\n logic clk;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
assert!(violations("module m (clk);\n input wire clk;\nendmodule\n").is_empty());
// An ANSI port redeclared in the body is left alone too, for the same
// reason: a rule that cannot tell the two apart must not accuse.
assert!(violations("module m (input logic clk);\n logic clk;\nendmodule\n").is_empty());
}
#[test]
fn a_prototype_and_its_definition_are_one_declaration() {
let src = "class c;\n extern function void f();\nendclass\n\
function void c::f();\nendfunction\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
let forward = "package p;\n typedef class c;\n class c;\n endclass\nendpackage\n";
assert!(violations(forward).is_empty(), "{:?}", violations(forward));
}
#[test]
fn conditional_arms_are_exclusive_so_they_are_not_flagged() {
let src = "module m;\n`ifdef X\n logic b;\n`else\n logic b;\n`endif\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_generate_scope_elaborates_one_arm_at_a_time() {
let src = "module m;\n\
generate\n\
if (A) begin : g\n\
logic x;\n\
end else begin : g\n\
logic x;\n\
end\n\
endgenerate\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_name_reused_in_a_nested_scope_is_not_a_duplicate() {
// That is shadowing, which is `instance-shadowing`'s subject.
let src =
"module m;\n logic a;\n always_comb begin : blk\n logic a;\n end\nendmodule\n";
assert!(violations(src).is_empty());
// And two modules may each declare `a`.
let two = "module m;\n logic a;\nendmodule\nmodule n;\n logic a;\nendmodule\n";
assert!(violations(two).is_empty());
}
}
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use crate::visit::walk_items;
use vlog_parser::ast::ItemKind;
@@ -21,6 +22,10 @@ impl Rule for EmptyItem {
"drop a `;` that stands where an item belongs"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A lone `;` in a module, generate, package, interface, program or class \
body is a *null item* (IEEE 1800-2017 A.1.4). It is legal and it means \
@@ -4,6 +4,7 @@
use crate::context::LintContext;
use crate::naming::{is_escaped, is_lower_snake_case};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::{ItemKind, TypedefKind};
@@ -22,6 +23,10 @@ impl Rule for EnumNameStyle {
"name enum typedefs in lower_snake_case ending in _e or _t"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A type name that looks like a type name is what makes a declaration \
readable at a glance: `state_e cur_state` says which identifier is the \
@@ -0,0 +1,152 @@
//! `explicit-function-task-parameter-type` — every formal gets a storage type.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::{ItemKind, TfArg};
/// See [`Rule::doc`].
pub struct ExplicitFunctionTaskParameterType;
const NAME: &str = "explicit-function-task-parameter-type";
impl Rule for ExplicitFunctionTaskParameterType {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"declare a storage type on every function and task argument"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A task or function formal written without a type is a **one-bit \
`logic`** (IEEE 1800 §13.3), so `function f(input a);` truncates \
every caller's argument to its low bit and nothing complains — the \
function simply returns the wrong answer for anything wider than a \
flag. Verible's `explicit-function-task-parameter-type` (\"Checks \
that every function and task parameter is declared with an explicit \
storage type.\", enabled by default) is the same rule and the same \
default. **A continuation formal inherits**: in `f(input int a, b)` \
the `b` is an `int`, so only the argument that *opens* a declaration \
— the first one, or the first after a direction keyword — is judged, \
which is exactly the language's own rule. A DPI import's unnamed \
formal (`import \"DPI-C\" function int f(int);`) names a type and no \
identifier and is not this rule's subject. No automatic fix: only the \
author knows how wide the argument was meant to be."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let (kw, args) = match &item.kind {
ItemKind::Function(decl) => ("function", &decl.args),
ItemKind::Task(decl) => ("task", &decl.args),
_ => return,
};
out.extend(untyped(kw, args));
});
out
}
}
/// The formals of one argument list that end up implicitly typed.
///
/// Walked in order with the declaration's type carried along, which is how the
/// language reads them: a formal that writes a type sets it, a formal that
/// writes a direction keyword opens a new declaration (and so a new type,
/// implicit until written), and a formal that writes neither inherits whatever
/// is in force.
fn untyped(kw: &'static str, args: &[TfArg]) -> Vec<Violation> {
let mut out = Vec::new();
let mut opened = false;
for arg in args {
let opens = !opened || arg.dir.is_some() || !arg.ty.is_implicit();
opened = true;
if !opens || !arg.ty.is_implicit() || arg.name.is_empty() {
continue;
}
out.push(Violation::new(
NAME,
format!("{kw} argument `{}` has no storage type; it is a 1-bit `logic`", arg.name),
arg.span,
));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ExplicitFunctionTaskParameterType.check(&LintContext::new(src, None))
}
fn wrap(header: &str) -> String {
format!("module m;\n {header}\n endfunction\nendmodule\n")
}
#[test]
fn flags_an_untyped_formal() {
let src = wrap("function void f(input a);");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`a`"), "{}", found[0].message);
assert!(found[0].message.contains("1-bit"), "{}", found[0].message);
assert!(found[0].fix.is_none());
}
#[test]
fn a_typed_formal_is_what_the_rule_wants() {
for header in [
"function void f(input logic a);",
"function void f(input int a);",
"function void f(input logic [7:0] a);",
"function void f(my_t a);",
"function void f();",
] {
assert!(
violations(&wrap(header)).is_empty(),
"{header}: {:?}",
violations(&wrap(header))
);
}
}
#[test]
fn a_continuation_formal_inherits_the_type_before_it() {
// `b` is an `int`, so only a genuinely untyped run may be reported.
assert!(violations(&wrap("function void f(input int a, b);")).is_empty());
// ... and a new direction keyword opens a new, untyped declaration.
let found = violations(&wrap("function void f(input int a, output b);"));
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`b`"), "{}", found[0].message);
}
#[test]
fn a_task_is_judged_the_same_way() {
let src = "module m;\n task t(input a);\n endtask\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("task"), "{}", found[0].message);
}
#[test]
fn an_unnamed_dpi_formal_is_not_this_rules_subject() {
let src = "import \"DPI-C\" function int f(int, chandle);\n";
assert!(violations(src).is_empty());
}
#[test]
fn a_class_method_is_reached() {
let src = "class c;\n function void f(input a);\n endfunction\nendclass\n";
assert_eq!(violations(src).len(), 1);
}
}
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
use vlog_parser::ast::{ItemKind, ParamDecl, StmtKind};
@@ -20,6 +21,10 @@ impl Rule for ExplicitParameterStorageType {
"declare a storage type on every parameter"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A parameter with no declared type takes its type from whatever it is \
assigned — and an override at instantiation can change that type, not \
@@ -0,0 +1,93 @@
//! `forbid-defparam` — `defparam` is deprecated; override at instantiation.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::ItemKind;
/// See [`Rule::doc`].
pub struct ForbidDefparam;
const NAME: &str = "forbid-defparam";
impl Rule for ForbidDefparam {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"override a parameter at the instantiation, not with `defparam`"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"`defparam` reaches into another scope and changes a parameter there, \
so the value a module elaborates with is written somewhere the module \
does not name and a reader has no way to find without grepping the \
whole design. It was deprecated in IEEE 1800-2009 (§A.11, and the LRM \
says it may be removed from a future revision), several synthesis \
tools reject it outright, and the `#(.NAME(value))` override at the \
instantiation says the same thing where the instance is. Verible's \
`forbid-defparam` (\"Do not use defparam.\", enabled by default) is \
the same rule. No automatic fix: moving the value to the right \
instantiation needs the instantiation, which may be in another file."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
if matches!(item.kind, ItemKind::Defparam(_)) {
out.push(Violation::new(
NAME,
"`defparam` is deprecated; override the parameter at its instantiation",
item.span,
));
}
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ForbidDefparam.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_defparam_wherever_it_stands() {
let src = "module m;\n sub u ();\n defparam u.WIDTH = 8;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "defparam u.WIDTH = 8;");
assert!(found[0].fix.is_none());
}
#[test]
fn a_named_override_is_what_the_rule_wants() {
assert!(violations("module m;\n sub #(.WIDTH(8)) u ();\nendmodule\n").is_empty());
// Nor is a parameter declaration one.
assert!(violations("module m;\n parameter int WIDTH = 8;\nendmodule\n").is_empty());
// And a signal that merely spells the word is not one either.
assert!(violations("module m;\n logic defparam_n;\nendmodule\n").is_empty());
}
#[test]
fn a_defparam_inside_generate_is_reached() {
let src = "module m;\n\
generate\n\
if (A) begin : g\n\
defparam u.W = 1;\n\
end\n\
endgenerate\n\
endmodule\n";
assert_eq!(violations(src).len(), 1);
}
}
@@ -0,0 +1,144 @@
//! `forbid-negative-array-dim` — a negative literal inside a dimension.
use crate::context::LintContext;
use crate::decls::walk_dims;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::ast::{DimKind, Expr, ExprKind};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct ForbidNegativeArrayDim;
const NAME: &str = "forbid-negative-array-dim";
impl Rule for ForbidNegativeArrayDim {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not write a negative constant in a dimension"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"`logic q [-1]` and `logic [-1:0] v` are what a parameter that came \
out zero or one too small looks like after the subtraction: \
`[WIDTH-1:0]` with `WIDTH = 0` is `[-1:0]`, which tools variously \
reject, treat as empty, or size as two bits. Written as a literal it \
is never intentional. Verible's `forbid-negative-array-dim` (\"Check \
for negative constant literals inside array dimensions.\") is the \
same rule; **lucisv turns it on by default where Verible ships it \
off**, because a negative literal spelled out in a dimension has no \
legitimate reading. Only a written `-<literal>` is flagged — an \
expression that would *evaluate* negative needs the parameter values, \
which lucisv does not have. No automatic fix."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_dims(ctx.file(), &mut |_, dim| {
let DimKind::Range { a, b } = &dim.kind else { return };
for expr in [Some(a), b.as_ref()].into_iter().flatten() {
for span in negative_literals(expr) {
out.push(Violation::new(NAME, "negative constant in a dimension", span));
}
}
});
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
out
}
}
/// The spans of every written `-<literal>` inside `expr`.
///
/// A whole expression tree rather than the top node alone, because the shape
/// that turns up in real code is `[-1:0]` on one side and `[WIDTH-1:-1]` on
/// the other, and the offending term can sit anywhere in an arithmetic
/// expression.
fn negative_literals(expr: &Expr) -> Vec<TextRange> {
let mut out = Vec::new();
collect(expr, &mut out);
out
}
fn collect(expr: &Expr, out: &mut Vec<TextRange>) {
match &expr.kind {
ExprKind::Unary { op, expr: inner, .. } => {
if op == "-" && matches!(inner.kind, ExprKind::Number(_)) {
out.push(expr.span);
return;
}
collect(inner, out);
}
ExprKind::Binary { lhs, rhs, .. } => {
collect(lhs, out);
collect(rhs, out);
}
ExprKind::Paren { inner, .. } => collect(inner, out),
ExprKind::Ternary { cond, then, els, .. } => {
collect(cond, out);
collect(then, out);
collect(els, out);
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ForbidNegativeArrayDim.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_negative_packed_bound() {
let src = "module m;\n logic [-1:0] v;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "-1");
assert!(found[0].fix.is_none());
}
#[test]
fn flags_a_negative_unpacked_extent_and_one_buried_in_arithmetic() {
assert_eq!(violations("module m;\n logic q [-1];\nendmodule\n").len(), 1);
assert_eq!(violations("module m;\n logic [W + -2:0] v;\nendmodule\n").len(), 1);
// Both ends count.
assert_eq!(violations("module m;\n logic [-1:-2] v;\nendmodule\n").len(), 2);
}
#[test]
fn ordinary_dimensions_are_silent() {
for decl in [
"logic [7:0] v;",
"logic [WIDTH-1:0] v;",
"logic q [4];",
"logic q [0:3];",
"logic v;",
"logic q [];",
] {
let src = format!("module m;\n {decl}\nendmodule\n");
assert!(violations(&src).is_empty(), "{decl}: {:?}", violations(&src));
}
}
#[test]
fn a_negative_outside_a_dimension_is_not_this_rules_business() {
assert!(violations("module m;\n assign x = -1;\nendmodule\n").is_empty());
assert!(violations("module m;\n parameter int P = -1;\nendmodule\n").is_empty());
}
#[test]
fn a_subtraction_is_not_a_negative_literal() {
// `WIDTH-1` is the ordinary way to write a width and must never fire.
assert!(violations("module m;\n logic [WIDTH-1:0] v;\nendmodule\n").is_empty());
}
}
@@ -0,0 +1,349 @@
//! `incomplete-assignment` — a latch inferred in an `always_comb`.
use std::collections::BTreeSet;
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_items, walk_stmts};
use vlog_parser::ast::{Expr, ExprKind, ItemKind, Stmt, StmtKind};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct IncompleteAssignment;
const NAME: &str = "incomplete-assignment";
impl Rule for IncompleteAssignment {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"assign every variable on every path of an always_comb"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A variable an `always_comb` writes on some paths and not on others \
has to *hold its value* on the others, and holding a value is a \
latch: the synthesized circuit grows storage nobody asked for, the \
timing closes differently, and in simulation the block reads back \
whatever it left there last time. `always_comb` was added to the \
language precisely so tools could catch this, and most of them do — \
but only at elaboration, long after the edit. There is no Verible \
equivalent; this is TODO §33's own rule.\n\n\
**Conservative by construction.** It speaks only about the \
*top level* of an `always_comb` body, and only in the two shapes that \
are unambiguous: an `if` with no `else`, and a `case` with no \
`default`. A variable is reported only when the block writes it \
inside such a statement and nothing **earlier in the block** already \
covered it — where covering it means a plain assignment (a partial \
one, through a bit select or a field, counts), or an `if`/`else` or a \
`case` with a `default` that writes it in *every* arm. That last one \
is the usual style, and the usual repair is the other: a default \
assignment at the top of the block.\n\n\
Everything else stays silent, deliberately: a name the block \
**declares for itself** (a local temporary is not a latched output), \
a left-hand side that is not a plain name or a concatenation of them, \
a conditional nested inside another, and every `always` that is not \
an `always_comb`. Measured on opentitan: three findings before those \
exemptions, all three false, none after. No automatic fix: what the \
missing branch should assign is a design decision."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::Always { kw, stmt } = &item.kind else { return };
if kw != "always_comb" {
return;
}
out.extend(latches(ctx.source(), stmt));
});
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
out
}
}
/// The findings of one `always_comb` body.
fn latches(source: &str, body: &Stmt) -> Vec<Violation> {
// Names the block declares for itself are never reported: a temporary
// written inside the branch it was declared in is a local, not a latched
// output, and deciding which of the two it is needs elaboration.
let local = declared_names(body);
let mut covered: BTreeSet<String> = BTreeSet::new();
let mut out = Vec::new();
for stmt in top_level(body) {
match &stmt.kind {
// Any write at all counts as coverage, a partial one included: a
// block that sets `cfg.mode` at the top and the whole `cfg` under
// an `if` has written the variable before the branch.
StmtKind::Assign { lhs, .. } => covered.extend(written_names(lhs)),
StmtKind::If { cond, then, els: None, .. } => {
let at = header(source, stmt.span, cond.span);
report(&mut out, &covered, &local, at, branch_names(then));
}
// An `if` with an `else`, and a `case` with a `default`, cover
// every name their branches agree on — which is how the usual
// "assign it in every arm" style is written.
StmtKind::If { then, els: Some(els), .. } => {
covered.extend(intersect(&[branch_names(then), branch_names(els)]));
}
StmtKind::Case { expr, items, .. } => {
let per_branch: Vec<BTreeSet<String>> =
items.iter().map(|item| branch_names(&item.stmt)).collect();
if items.iter().any(|item| item.labels.is_empty()) {
covered.extend(intersect(&per_branch));
} else {
let mut names = BTreeSet::new();
for branch in &per_branch {
names.extend(branch.iter().cloned());
}
let at = header(source, stmt.span, expr.span);
report(&mut out, &covered, &local, at, names);
}
}
_ => {}
}
}
out
}
/// The names every one of these branches writes.
fn intersect(branches: &[BTreeSet<String>]) -> BTreeSet<String> {
let Some((first, rest)) = branches.split_first() else { return BTreeSet::new() };
first.iter().filter(|name| rest.iter().all(|set| set.contains(*name))).cloned().collect()
}
/// Every name the block declares anywhere inside itself.
fn declared_names(body: &Stmt) -> BTreeSet<String> {
let mut names = BTreeSet::new();
walk_stmts(body, &mut |stmt| {
if let StmtKind::VarDecl(decl) = &stmt.kind {
names.extend(decl.declarators.iter().map(|d| d.name.clone()));
}
});
names
}
/// The statements written directly in the body — the body itself when it is
/// one statement, and a `begin ... end`'s own list when it is a block.
fn top_level(body: &Stmt) -> Vec<&Stmt> {
match &body.kind {
StmtKind::Block { stmts, .. } => stmts.iter().collect(),
// The body of an `always_comb` carries no timing control of its own,
// so anything else is a single statement standing as the whole block.
_ => vec![body],
}
}
/// Every plain name a branch assigns, however deep inside it.
fn branch_names(stmt: &Stmt) -> BTreeSet<String> {
let mut names = BTreeSet::new();
walk_stmts(stmt, &mut |inner| {
if let StmtKind::Assign { lhs, .. } = &inner.kind {
names.extend(assigned_name(lhs));
}
});
names
}
/// Adds one finding per name the branch writes that nothing covered before it
/// and that the block does not declare for itself.
fn report(
out: &mut Vec<Violation>,
covered: &BTreeSet<String>,
local: &BTreeSet<String>,
span: TextRange,
names: BTreeSet<String>,
) {
for name in names {
if covered.contains(&name) || local.contains(&name) {
continue;
}
out.push(Violation::new(
NAME,
format!("`{name}` is not assigned on every path; this infers a latch"),
span,
));
}
}
/// The `if (cond)` / `case (subject)` header alone, so a whole branch is not
/// painted red for a problem that lives on one line. The subject's own span
/// stops inside the parentheses, so the underline runs on to the `)` that
/// closes it — the same shape `case-missing-default` underlines.
fn header(source: &str, stmt: TextRange, subject: TextRange) -> TextRange {
let close = source
.get(subject.end as usize..)
.and_then(|rest| rest.find(')'))
.map(|i| subject.end + i as u32 + 1)
.unwrap_or(subject.end);
TextRange::new(stmt.start, close.max(stmt.start))
}
/// The plain name a left-hand side writes, or nothing when the target is not
/// one identifier.
///
/// A bit or field select (`x[3] = …`, `s.f = …`) writes *part* of a variable,
/// and deciding whether the rest is covered needs ranges resolved — so those
/// are not names this rule will accuse. A concatenation lvalue is every name
/// in it, each of which is written whole.
fn assigned_name(lhs: &Expr) -> Vec<String> {
match &lhs.kind {
ExprKind::Ident(name) => vec![name.clone()],
ExprKind::Concat(items) => {
items.iter().flat_map(|item| assigned_name(&item.expr)).collect()
}
_ => Vec::new(),
}
}
/// Every name a left-hand side touches, a *part* of one included.
///
/// The wider question — "was this variable written here at all?" — which is
/// what the coverage set wants: a block that writes `cfg.mode` before an `if`
/// that writes the whole `cfg` has already spoken for `cfg`, and reporting it
/// would be a latch that is not there.
fn written_names(lhs: &Expr) -> Vec<String> {
match &lhs.kind {
ExprKind::Ident(name) => vec![name.clone()],
ExprKind::Concat(items) => {
items.iter().flat_map(|item| written_names(&item.expr)).collect()
}
ExprKind::Index { base, .. }
| ExprKind::Range { base, .. }
| ExprKind::Member { base, .. } => written_names(base),
_ => Vec::new(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
IncompleteAssignment.check(&LintContext::new(src, None))
}
fn wrap(body: &str) -> String {
format!("module m;\n always_comb begin\n{body} end\nendmodule\n")
}
#[test]
fn flags_a_variable_written_only_under_an_if() {
let src = wrap(" if (en) y = a;\n");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`y`"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "if (en)", "the header, not the branch");
assert!(found[0].fix.is_none());
}
#[test]
fn a_default_assignment_before_the_if_is_the_repair() {
assert!(violations(&wrap(" y = 1'b0;\n if (en) y = a;\n")).is_empty());
// ... and it must come *before*: assigning after the `if` does not
// stop the branch from inferring one.
assert_eq!(violations(&wrap(" if (en) y = a;\n y = 1'b0;\n")).len(), 1);
}
#[test]
fn an_if_with_an_else_covers_every_path() {
assert!(violations(&wrap(" if (en) y = a; else y = b;\n")).is_empty());
}
#[test]
fn a_case_without_default_is_flagged_and_one_with_it_is_not() {
let with_default = " case (s)\n 0: y = a;\n default: y = b;\n endcase\n";
assert!(violations(&wrap(with_default)).is_empty());
let without = " case (s)\n 0: y = a;\n 1: y = b;\n endcase\n";
let found = violations(&wrap(without));
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`y`"), "{}", found[0].message);
}
#[test]
fn every_variable_of_a_branch_is_named_once() {
let found = violations(&wrap(" if (en) begin\n y = a;\n z = b;\n end\n"));
assert_eq!(found.len(), 2, "{found:?}");
assert!(found[0].message.contains("`y`") || found[0].message.contains("`z`"));
// And a variable written twice in the branch is still one finding.
let twice = violations(&wrap(" if (en) begin\n y = a;\n y = b;\n end\n"));
assert_eq!(twice.len(), 1, "{twice:?}");
}
#[test]
fn only_always_comb_is_judged() {
for kw in ["always", "always_ff", "always_latch"] {
let src = format!("module m;\n {kw} @(posedge clk) if (en) y <= a;\nendmodule\n");
assert!(violations(&src).is_empty(), "{kw}");
}
assert!(violations("module m;\n always @* if (en) y = a;\nendmodule\n").is_empty());
}
#[test]
fn a_partial_write_is_not_accused() {
// Deciding whether the other bits are covered needs ranges resolved,
// which this rule does not do.
assert!(violations(&wrap(" if (en) y[3] = a;\n")).is_empty());
assert!(violations(&wrap(" if (en) s.f = a;\n")).is_empty());
}
#[test]
fn a_concatenation_lvalue_names_every_target() {
let found = violations(&wrap(" if (en) {y, z} = a;\n"));
assert_eq!(found.len(), 2, "{found:?}");
}
#[test]
fn a_nested_conditional_is_left_to_the_top_level_one() {
// The outer `if` has an `else`, so the block covers every path as far
// as this rule is willing to claim.
let src = wrap(" if (en) begin\n if (x) y = a;\n end else y = b;\n");
assert!(violations(&src).is_empty());
}
/// The three shapes the opentitan census turned up as false positives, each
/// pinned so it stays quiet.
#[test]
fn the_shapes_that_are_not_latches_stay_quiet() {
// 1. A variable the block declares for itself, written in the branch
// it was declared in (`entropy_src_core.sv`).
let local = wrap(" if (en) begin\n logic [3:0] tmp;\n tmp = a;\n end\n");
assert!(violations(&local).is_empty(), "{:?}", violations(&local));
// 2. A partial write before the branch covers the variable
// (`kmac_app.sv`).
let partial = wrap(" cfg.mode = a;\n if (en) cfg = b;\n");
assert!(violations(&partial).is_empty(), "{:?}", violations(&partial));
// 3. A `case` with a `default` that writes it in every arm, followed
// by an `if` that writes it again (`ibex_alu.sv`).
let after_case = wrap(
" case (s)\n 0: y = a;\n default: y = b;\n endcase\n\
\x20 if (en) y = 1'b1;\n",
);
assert!(violations(&after_case).is_empty(), "{:?}", violations(&after_case));
}
#[test]
fn an_if_else_before_the_branch_also_covers_it() {
let src = wrap(" if (a) y = 1; else y = 0;\n if (en) y = 2;\n");
assert!(violations(&src).is_empty(), "{:?}", violations(&src));
// ... but only for the names *both* arms write.
let partial = wrap(" if (a) y = 1; else z = 0;\n if (en) y = 2;\n");
assert_eq!(violations(&partial).len(), 1, "{:?}", violations(&partial));
}
#[test]
fn a_body_that_is_one_statement_is_still_a_body() {
let src = "module m;\n always_comb if (en) y = a;\nendmodule\n";
assert_eq!(violations(src).len(), 1);
}
}
@@ -0,0 +1,204 @@
//! `instance-shadowing` — a declaration hiding one from an enclosing scope.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_semantic::{Scope, ScopeKind, Semantics, SymbolKind};
/// See [`Rule::doc`].
pub struct InstanceShadowing;
const NAME: &str = "instance-shadowing";
impl Rule for InstanceShadowing {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not hide an enclosing declaration with a new one of the same name"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A `logic count;` inside a `begin : blk` where the module already has \
a `count` compiles, and from then on every mention of `count` inside \
the block means the inner one — including the ones written before the \
inner declaration was added, which is how this arrives in a review \
diff that looks like it changed nothing. Verible's `instance-\
shadowing` (\"Warns if there are multiple declarations in the same \
scope that shadow each other with the same name.\") is the same rule; \
**lucisv turns it on by default where Verible ships it off**, because \
the finding is always worth a second look and the repair is a rename \
in one block.\n\n\
Only the scopes **inside one design unit** are compared: a module, a \
package or a class opens a fresh namespace, and a signal called `data` \
in two different modules shadows nothing. A generate scope is \
compared like any other block — the shadowing is real there too. No \
automatic fix: renaming reaches every use inside the block."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
// Shadowing is a claim about *which scope* a name was declared in,
// and error recovery moves declarations between scopes — so a file
// that did not fully parse gets no opinion, exactly as
// `duplicate-declaration` gives it none.
if !ctx.parsed_cleanly() {
return Vec::new();
}
let semantics = ctx.semantics();
let mut out = Vec::new();
for scope in semantics.scopes() {
if opens_a_unit(scope.kind) {
continue;
}
for &id in &scope.symbols {
let Some(symbol) = semantics.symbol(id) else { continue };
let Some(hidden) = shadowed(semantics, scope, &symbol.name) else { continue };
if !judged(symbol.kind) {
continue;
}
// The two are exclusive when a conditional-compilation
// directive stands between them, exactly as they are for
// `duplicate-declaration`.
if ctx.signals().conditional_between(&[hidden, symbol.name_span.start]) {
continue;
}
out.push(Violation::new(
NAME,
format!(
"`{}` shadows a declaration of the same name outside this scope",
symbol.name
),
symbol.name_span,
));
}
}
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
out
}
}
/// The name span of the enclosing declaration `name` hides, if there is one
/// **within the same design unit**.
///
/// The walk stops at the scope that opens a unit — a module, package or class
/// body — because a name declared in a different unit is reached by a
/// qualified path, never by shadowing.
fn shadowed(semantics: &Semantics, scope: &Scope, name: &str) -> Option<u32> {
let mut parent = scope.parent;
while let Some(id) = parent {
let outer = semantics.scope(id)?;
if let Some(hidden) = outer.lookup_local(name) {
return semantics.symbol(hidden).map(|symbol| symbol.name_span.start);
}
if opens_a_unit(outer.kind) {
return None;
}
parent = outer.parent;
}
None
}
/// True for the scopes that open a design unit's own namespace.
fn opens_a_unit(kind: ScopeKind) -> bool {
matches!(kind, ScopeKind::File | ScopeKind::Module | ScopeKind::Package | ScopeKind::Class)
}
/// True for the declarations worth reporting.
///
/// A subroutine argument named after an enclosing signal is idiomatic
/// (`function automatic f(input logic clk)`), a block label is not a value,
/// and a `genvar` is scoped to its own loop by construction — so those stay
/// out. What is left is data and instances, which is where the surprise is.
fn judged(kind: SymbolKind) -> bool {
matches!(
kind,
SymbolKind::Net | SymbolKind::Var | SymbolKind::Instance | SymbolKind::LocalParam
)
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
InstanceShadowing.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_block_local_that_hides_a_module_signal() {
let src = "module m;\n\
logic count;\n\
always_comb begin : blk\n\
logic count;\n\
count = 1'b0;\n\
end\n\
endmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`count`"), "{}", found[0].message);
assert!(found[0].span.start as usize > src.find("blk").unwrap_or(0), "the inner one");
assert!(found[0].fix.is_none());
}
#[test]
fn a_name_declared_once_is_never_flagged() {
let src = "module m;\n\
logic count;\n\
always_comb begin : blk\n\
logic other;\n\
end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_different_unit_shadows_nothing() {
let src = "module a;\n logic data;\nendmodule\nmodule b;\n logic data;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
// Nor does a package-level name reached from a module.
let pkg = "package p;\n logic data;\nendpackage\nmodule m;\n logic data;\nendmodule\n";
assert!(violations(pkg).is_empty(), "{:?}", violations(pkg));
}
#[test]
fn a_generate_block_is_compared_like_any_other() {
let src = "module m;\n\
logic x;\n\
generate\n\
if (A) begin : g\n\
logic x;\n\
end\n\
endgenerate\n\
endmodule\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn a_subroutine_argument_named_after_a_signal_is_idiomatic() {
let src = "module m;\n\
logic clk;\n\
function automatic void f(input logic clk);\n\
endfunction\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn conditional_arms_are_exclusive() {
let src = "module m;\n\
logic x;\n\
always_comb begin : blk\n\
`ifdef A\n\
logic x;\n\
`endif\n\
end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
}
@@ -0,0 +1,132 @@
//! `invalid-system-task-function` — system tasks nothing should still call.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::token::TokenKind;
/// See [`Rule::doc`].
pub struct InvalidSystemTaskFunction;
const NAME: &str = "invalid-system-task-function";
/// The forbidden names and what to write instead — Verible's list
/// (`invalid-system-task-function`), name for name.
///
/// The `$dist_*` family and `$random` all draw from the *global* seed that
/// `$random` shares, so one extra call anywhere in a testbench reshuffles
/// every other stream; `$urandom` and `$urandom_range` are per-thread and
/// reproducible. `$psprintf` is a vendor extension for the standard
/// `$sformatf`, and `$srandom` seeds that same global generator rather than
/// the calling process.
const FORBIDDEN: &[(&str, &str)] = &[
("$psprintf", "$sformatf"),
("$random", "$urandom"),
("$srandom", "process::self().srandom()"),
("$dist_chi_square", "$urandom"),
("$dist_erlang", "$urandom"),
("$dist_exponential", "$urandom"),
("$dist_normal", "$urandom"),
("$dist_poisson", "$urandom"),
("$dist_t", "$urandom"),
("$dist_uniform", "$urandom"),
];
impl Rule for InvalidSystemTaskFunction {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not call a deprecated or non-reproducible system task"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"`$random`, `$srandom` and the `$dist_*` family all draw from one \
global generator, so adding a call anywhere in a testbench reshuffles \
every other random stream in it and a failing seed stops reproducing \
— the reason IEEE 1800 added the per-process `$urandom` / \
`$urandom_range` and `process::self().srandom()`. `$psprintf` is a \
vendor spelling of the standard `$sformatf` and is not portable. \
Verible's `invalid-system-task-function` (\"Checks that no forbidden \
system tasks or functions are used.\", enabled by default) forbids \
exactly this list, and lucisv names the replacement in the message. \
No automatic fix: `$random` and `$urandom` return different value \
streams, so swapping them changes what the test does."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
ctx.tokens()
.iter()
.filter(|token| token.kind == TokenKind::SystemIdent)
.filter_map(|token| {
let (name, instead) =
FORBIDDEN.iter().find(|(name, _)| *name == token.text.as_str())?;
Some(Violation::new(
NAME,
format!("`{name}` is forbidden; use `{instead}`"),
token.span,
))
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
InvalidSystemTaskFunction.check(&LintContext::new(src, None))
}
#[test]
fn flags_every_forbidden_name_and_says_what_to_use() {
for (name, instead) in FORBIDDEN {
let src = format!("module m;\n initial x = {name}();\nendmodule\n");
let found = violations(&src);
assert_eq!(found.len(), 1, "{name}: {found:?}");
assert!(found[0].message.contains(name), "{}", found[0].message);
assert!(found[0].message.contains(instead), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], *name, "the call, underlined");
}
}
#[test]
fn the_replacements_and_their_neighbours_are_left_alone() {
let src = "module m;\n\
initial begin\n\
a = $urandom();\n\
b = $urandom_range(0, 7);\n\
c = $sformatf(\"%0d\", a);\n\
$display(\"%0d\", b);\n\
end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_near_miss_name_is_not_a_hit() {
// Matched whole, not by prefix: `$random_stable` and a signal called
// `random` are neither of them `$random`.
let src = "module m;\n\
logic random;\n\
initial begin\n\
a = $randomize_helper();\n\
b = random;\n\
end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_forbidden_name_inside_a_string_is_data() {
let src = "module m;\n initial $display(\"call $random here\");\nendmodule\n";
assert!(violations(src).is_empty());
}
}
@@ -0,0 +1,299 @@
//! `mismatched-labels` — an end label that does not name its own block.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_all_stmts, walk_items};
use vlog_parser::ast::{GenBlock, GenElse, Item, ItemKind, Name, StmtKind};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct MismatchedLabels;
const NAME: &str = "mismatched-labels";
impl Rule for MismatchedLabels {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"make an end label name the block it closes"
}
fn severity(&self) -> Severity {
Severity::Error
}
fn doc(&self) -> &'static str {
"`begin : fetch … end : decode` is a compile error (IEEE 1800 §9.3.4: \
if both labels are given they must be identical), and so is an \
`end : name` on a block that was never labelled. It is the classic \
result of copying a block and renaming only one half — which is also \
why it survives review: the two halves are pages apart. Verible's \
`mismatched-labels` (\"Check for matching begin/end labels.\") is the \
same rule; **lucisv turns it on by default where Verible ships it \
off**, and files it as an **Error** rather than a style finding, \
because the file does not compile.\n\n\
Every construct that may carry a footer label is checked with one \
answer: `module`/`interface`/`program`, `package`, `class`, \
`function`, `task`, `begin`, `fork`/`join`, a generate block, a \
`clocking` block, a `covergroup`, and a `property`/`sequence`. It is \
a comparison of two spellings and nothing more, so an escaped \
identifier is compared as written. No automatic fix: which of the two \
names is the right one is exactly what a linter cannot know."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| item_labels(&mut out, item));
walk_all_stmts(ctx.file(), &mut |stmt| match &stmt.kind {
StmtKind::Block { label, end_label, end_label_span, .. } => {
check_pair(&mut out, label.as_deref(), end_label.as_deref(), *end_label_span, "end")
}
StmtKind::ForkJoin { label, end_label, end_label_span, .. } => check_pair(
&mut out,
label.as_deref(),
end_label.as_deref(),
*end_label_span,
"join",
),
_ => {}
});
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
out
}
}
/// The label pair one item carries, checked. One arm per construct that may
/// write a footer label, so a construct that gains one later has an obvious
/// place to go.
fn item_labels(out: &mut Vec<Violation>, item: &Item) {
match &item.kind {
ItemKind::Module(module) => check_pair(
out,
Some(&module.name),
module.end_label.as_deref(),
module.end_label_span,
match module.kw.as_str() {
"interface" => "endinterface",
"program" => "endprogram",
_ => "endmodule",
},
),
ItemKind::Package { name, end_label, end_label_span, .. } => {
check_pair(out, Some(name), end_label.as_deref(), *end_label_span, "endpackage")
}
ItemKind::Class(class) => check_pair(
out,
Some(&class.name),
class.end_label.as_deref(),
class.end_label_span,
"endclass",
),
ItemKind::Function(decl) => check_pair(
out,
Some(&decl.name),
decl.end_label.as_deref(),
decl.end_label_span,
"endfunction",
),
ItemKind::Task(decl) => check_pair(
out,
Some(&decl.name),
decl.end_label.as_deref(),
decl.end_label_span,
"endtask",
),
ItemKind::Clocking(decl) => check_pair(
out,
decl.name.as_ref().map(|name| name.text.as_str()),
decl.end_label.as_deref(),
decl.end_label_span,
"endclocking",
),
ItemKind::Covergroup(decl) => {
check_name_pair(out, Some(&decl.name.text), decl.end_label.as_ref(), "endgroup")
}
ItemKind::PropSeqDecl(decl) => check_name_pair(
out,
Some(&decl.name.text),
decl.end_label.as_ref(),
if decl.kw == "sequence" { "endsequence" } else { "endproperty" },
),
// The item walk descends into a generate block's *items* but never
// visits the block itself, so its own label pair is collected here.
ItemKind::GenIf(gen_if) => {
check_gen_block(out, &gen_if.then);
let mut els = gen_if.els.as_deref();
while let Some(branch) = els {
match branch {
GenElse::If(_, nested) => {
check_gen_block(out, &nested.then);
els = nested.els.as_deref();
}
GenElse::Block(block) => {
check_gen_block(out, block);
els = None;
}
}
}
}
ItemKind::GenFor(gen_for) => check_gen_block(out, &gen_for.body),
ItemKind::GenCase(gen_case) => {
for case_item in &gen_case.items {
check_gen_block(out, &case_item.body);
}
}
_ => {}
}
}
fn check_gen_block(out: &mut Vec<Violation>, block: &GenBlock) {
check_pair(
out,
block.label.as_deref(),
block.end_label.as_deref(),
block.end_label_span,
"end",
);
}
/// Compares one header/footer pair, when a footer label was written at all.
fn check_pair(
out: &mut Vec<Violation>,
opened: Option<&str>,
closed: Option<&str>,
at: Option<TextRange>,
kw: &'static str,
) {
let (Some(closed), Some(at)) = (closed, at) else { return };
if at.is_empty() {
return;
}
let message = match opened {
Some(opened) if opened == closed => return,
Some(opened) => format!("`{kw} : {closed}` closes `{opened}`"),
None => format!("`{kw} : {closed}` closes a block with no label"),
};
out.push(Violation::new(NAME, message, at));
}
/// The same, for the constructs whose footer label is a [`Name`].
fn check_name_pair(
out: &mut Vec<Violation>,
opened: Option<&str>,
closed: Option<&Name>,
kw: &'static str,
) {
check_pair(
out,
opened,
closed.map(|name| name.text.as_str()),
closed.map(|name| name.span),
kw,
);
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
MismatchedLabels.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_footer_that_names_another_block() {
let src = "module m;\n\
always_comb begin : fetch\n\
x = 1;\n\
end : decode\n\
endmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "decode");
assert!(found[0].message.contains("fetch"), "{}", found[0].message);
assert!(found[0].fix.is_none());
}
#[test]
fn flags_a_footer_label_on_an_unlabelled_block() {
let src = "module m;\n always_comb begin\n x = 1;\n end : blk\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("no label"), "{}", found[0].message);
}
#[test]
fn a_matching_pair_and_a_missing_footer_are_both_fine() {
for src in [
"module m;\n always_comb begin : blk\n x = 1;\n end : blk\nendmodule\n",
"module m;\n always_comb begin : blk\n x = 1;\n end\nendmodule\n",
"module m;\n always_comb begin\n x = 1;\n end\nendmodule\n",
"module m;\nendmodule : m\n",
] {
assert!(violations(src).is_empty(), "{src}: {:?}", violations(src));
}
}
#[test]
fn every_construct_with_a_footer_label_is_checked() {
for (src, wrong) in [
("module m;\nendmodule : other\n", "other"),
("interface i;\nendinterface : other\n", "other"),
("package p;\nendpackage : other\n", "other"),
("class c;\nendclass : other\n", "other"),
("module m;\n function void f();\n endfunction : other\nendmodule\n", "other"),
("module m;\n task t();\n endtask : other\nendmodule\n", "other"),
(
"interface i;\n clocking cb @(posedge clk);\n endclocking : other\nendinterface\n",
"other",
),
(
"module m;\n covergroup cg;\n endgroup : other\nendmodule\n",
"other",
),
(
"module m;\n property p;\n a |-> b;\n endproperty : other\nendmodule\n",
"other",
),
] {
let found = violations(src);
assert_eq!(found.len(), 1, "{src}: {found:?}");
assert_eq!(&src[found[0].span.as_range()], wrong, "{src}");
}
}
#[test]
fn a_fork_join_and_a_generate_block_are_checked() {
let fork = "module m;\n\
initial fork : spawn\n\
x = 1;\n\
join : other\n\
endmodule\n";
assert_eq!(violations(fork).len(), 1, "{:?}", violations(fork));
let generate = "module m;\n\
generate\n\
if (A) begin : g\n\
wire a;\n\
end : other\n\
endgenerate\n\
endmodule\n";
assert_eq!(violations(generate).len(), 1, "{:?}", violations(generate));
}
#[test]
fn a_nested_block_is_matched_against_its_own_header() {
let src = "module m;\n\
always_comb begin : outer\n\
begin : inner\n\
x = 1;\n\
end : inner\n\
end : outer\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
}
+25 -4
View File
@@ -1,24 +1,45 @@
//! The rules themselves, one module each.
//!
//! Most rules are **syntactic** — text, tokens or tree shape. The three that
//! are not (`unused-signal`, `undriven-net`, `multiply-driven`) read the
//! symbol table through `crate::signals`; see
//! `docs/features/semantic-lints/README.md`.
//! Most rules are **syntactic** — text, tokens or tree shape. The ones that
//! are not read the symbol table: `unused-signal`, `undriven-net` and
//! `multiply-driven` through `crate::signals` (see
//! `docs/features/semantic-lints/README.md`), and `duplicate-declaration` and
//! `instance-shadowing` through `vlog_semantic::Semantics` directly (see
//! `docs/features/linter-expansion-1/README.md`).
pub mod always_comb_blocking;
pub mod always_ff_non_blocking;
pub mod case_missing_default;
pub mod duplicate_declaration;
pub mod empty_item;
pub mod enum_name_style;
pub mod explicit_function_task_parameter_type;
pub mod explicit_parameter_storage_type;
pub mod forbid_defparam;
pub mod forbid_negative_array_dim;
pub mod incomplete_assignment;
pub mod instance_shadowing;
pub mod invalid_system_task_function;
pub mod mismatched_labels;
pub mod module_filename;
pub mod module_name_style;
pub mod module_parameter;
pub mod module_port;
pub mod multiply_driven;
pub mod no_tabs;
pub mod no_trailing_whitespace;
pub mod packed_dimensions_range_ordering;
pub mod parameter_name_style;
pub mod plusarg_assignment;
pub mod struct_union_name_style;
pub mod suspicious_semicolon;
pub mod truncated_numeric_literal;
pub mod undeclared_identifier;
pub mod undersized_binary_literal;
pub mod undriven_net;
pub mod unknown_parameter;
pub mod unknown_port;
pub mod unused_signal;
pub mod unused_waiver;
pub mod void_cast;
pub mod wire_reg_mixup;
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::ast::ItemKind;
@@ -19,6 +20,10 @@ impl Rule for ModuleFilename {
"name a one-module file after its module"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"Every Verilog tool that finds a module by searching a library \
directory — simulators, synthesis `-y` paths, most build systems — \
@@ -3,6 +3,7 @@
use crate::context::LintContext;
use crate::naming::{is_escaped, is_lower_snake_case};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::ItemKind;
@@ -21,6 +22,10 @@ impl Rule for ModuleNameStyle {
"name modules in lower_snake_case"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A module name ends up as a file name, a directory name, an instance \
path in a waveform viewer and a grep target, and every one of those is \
@@ -0,0 +1,101 @@
//! `module-parameter` — override a multi-parameter instance by name.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_instantiations;
/// See [`Rule::doc`].
pub struct ModuleParameter;
const NAME: &str = "module-parameter";
impl Rule for ModuleParameter {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"override more than one parameter by name"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"`sub #(8, 4) u ()` binds by *order*, so a parameter added to the \
instantiated module — or two of them reordered — silently changes \
what every instance elaborates to, and two integers in a row give a \
reader nothing to check against. `#(.Width(8), .Depth(4))` names each \
one where it is written. Verible's `module-parameter` (\"Checks that \
module instantiations with more than one parameter are passed in as \
named parameters.\", enabled by default) is the same rule and the \
same default; a single positional override is left alone by both. No \
automatic fix: the names live in the instantiated module, usually in \
another file."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_instantiations(ctx.file(), &mut |inst| {
let Some(params) = &inst.params else { return };
let positional = params.iter().filter(|conn| conn.name.is_empty()).count();
if positional < 2 {
return;
}
out.push(Violation::new(
NAME,
format!("`{}` takes {positional} parameters by position; name them", inst.module),
inst.module_span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ModuleParameter.check(&LintContext::new(src, None))
}
#[test]
fn flags_more_than_one_positional_override() {
let src = "module m;\n sub #(8, 4) u_sub ();\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`sub`"), "{}", found[0].message);
assert!(found[0].message.contains("2 parameters"), "{}", found[0].message);
assert!(found[0].fix.is_none());
}
#[test]
fn a_named_override_is_what_the_rule_wants() {
let src = "module m;\n sub #(.Width(8), .Depth(4)) u_sub ();\nendmodule\n";
assert!(violations(src).is_empty());
}
#[test]
fn one_override_or_none_has_no_order_to_get_wrong() {
assert!(violations("module m;\n sub #(8) u ();\nendmodule\n").is_empty());
assert!(violations("module m;\n sub #() u ();\nendmodule\n").is_empty());
assert!(violations("module m;\n sub u ();\nendmodule\n").is_empty());
}
#[test]
fn a_bind_and_a_generate_body_are_both_reached() {
assert_eq!(violations("bind top sub #(8, 4) u ();\n").len(), 1);
let generate = "module m;\n\
generate\n\
if (A) begin : g\n\
sub #(8, 4) u ();\n\
end\n\
endgenerate\n\
endmodule\n";
assert_eq!(violations(generate).len(), 1);
}
}
+119
View File
@@ -0,0 +1,119 @@
//! `module-port` — connect a multi-port instance by name.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_instantiations;
use vlog_parser::ast::Connections;
/// See [`Rule::doc`].
pub struct ModulePort;
const NAME: &str = "module-port";
impl Rule for ModulePort {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"connect an instance with more than one port by name"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A positional connection list binds by *order*, so inserting a port in \
the instantiated module silently rewires every instance of it — and \
two ports of the same width swapped by hand compile perfectly and \
fail in simulation. A named list (`.clk_i(clk)`) says what is \
connected to what at the site, breaks loudly when a port is renamed, \
and is what every reviewer can check without opening the other file. \
Verible's `module-port` (\"Checks that module instantiations with \
more than one port are passed in as named ports.\", enabled by \
default) is the same rule and the same default; a single-port \
instance is left alone by both, because there is no order to get \
wrong. No automatic fix: naming the ports needs the instantiated \
module's port list, which is usually in another file."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_instantiations(ctx.file(), &mut |inst| {
for instance in &inst.instances {
let Connections::Ordered(conns) = &instance.conns else { continue };
if conns.len() < 2 {
continue;
}
out.push(Violation::new(
NAME,
format!(
"`{}` is connected by position; name its {} ports",
inst.module,
conns.len()
),
instance.span,
));
}
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ModulePort.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_positional_list_of_more_than_one() {
let src = "module m;\n sub u_sub (a, b, c);\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`sub`"), "{}", found[0].message);
assert!(found[0].message.contains("3 ports"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "u_sub (a, b, c)");
assert!(found[0].fix.is_none());
}
#[test]
fn a_named_list_is_what_the_rule_wants() {
let src = "module m;\n sub u_sub (.a(x), .b(y), .c(z));\nendmodule\n";
assert!(violations(src).is_empty());
// `.*` is a named list too.
assert!(violations("module m;\n sub u_sub (.*);\nendmodule\n").is_empty());
}
#[test]
fn one_port_or_none_has_no_order_to_get_wrong() {
assert!(violations("module m;\n sub u_sub (a);\nendmodule\n").is_empty());
assert!(violations("module m;\n sub u_sub ();\nendmodule\n").is_empty());
}
#[test]
fn every_instance_of_one_statement_is_judged() {
let src = "module m;\n sub u1 (a, b), u2 (.a(x), .b(y)), u3 (c, d);\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 2, "{found:?}");
assert!(found[0].span.start < found[1].span.start, "in source order");
}
#[test]
fn an_instantiation_inside_generate_and_a_bind_are_both_reached() {
let generate = "module m;\n\
generate\n\
if (A) begin : g\n\
sub u (a, b);\n\
end\n\
endgenerate\n\
endmodule\n";
assert_eq!(violations(generate).len(), 1);
assert_eq!(violations("bind top sub u (a, b);\n").len(), 1);
}
}
@@ -4,6 +4,7 @@ use std::collections::BTreeSet;
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::signals::{Driver, DriverKind};
use crate::violation::Violation;
@@ -21,6 +22,10 @@ impl Rule for MultiplyDriven {
"give a variable exactly one driver"
}
fn severity(&self) -> Severity {
Severity::Error
}
fn doc(&self) -> &'static str {
"A SystemVerilog *variable* — `logic`, `reg`, `int` — may be written \
from one source only (IEEE 1800 §6.5). Two `always` blocks assigning \
+5
View File
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use vlog_parser::span::TextRange;
@@ -19,6 +20,10 @@ impl Rule for NoTabs {
"use spaces, not tabs"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A tab renders at a width nobody agrees on, so a file mixing tabs and \
spaces looks aligned in the editor that wrote it and ragged everywhere \
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use vlog_parser::span::TextRange;
@@ -19,6 +20,10 @@ impl Rule for NoTrailingWhitespace {
"no whitespace at the end of a line"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"Trailing whitespace is invisible, so it survives review and then shows \
up as diff noise the day somebody's editor strips it — a one-character \
@@ -0,0 +1,149 @@
//! `packed-dimensions-range-ordering` — write a vector's width `[N-1:0]`.
use crate::context::LintContext;
use crate::decls::{walk_dims, Packing};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::ast::{DimKind, Expr, ExprKind};
/// See [`Rule::doc`].
pub struct PackedDimensionsRangeOrdering;
const NAME: &str = "packed-dimensions-range-ordering";
impl Rule for PackedDimensionsRangeOrdering {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"declare a packed dimension in decreasing order, `[N-1:0]`"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"`logic [0:7] data` is legal and means bit 0 is the *most* significant \
one, so `data[0]` is the top bit, a part select counts the other way \
and every concatenation with an ordinary `[7:0]` vector silently \
reverses. Nothing in the language stops it and no tool warns; the \
cost lands on whoever reads the two declarations side by side. \
Verible's `packed-dimensions-range-ordering` (\"Checks that packed \
dimension ranges are declare in little-endian (decreasing) order, \
e.g. `[N-1:0]`.\", enabled by default) is the same rule and the same \
default. **Only packed dimensions are judged**: an unpacked `[0:3]` \
array is an ordinary ascending array and is a perfectly normal thing \
to write. A range is flagged when both bounds are integer literals \
and the left one is smaller, and when the left one is a literal `0` \
and the right is anything else — every other shape is left alone, \
because lucisv does not evaluate parameters. No automatic fix: \
reversing a range reverses every use of it."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_dims(ctx.file(), &mut |packing, dim| {
if packing != Packing::Packed {
return;
}
let DimKind::Range { a, b: Some(b) } = &dim.kind else { return };
if !ascending(a, b) {
return;
}
out.push(Violation::new(
NAME,
"packed dimension counts upwards; write it as `[N-1:0]`",
dim.span,
));
});
out
}
}
/// True when `[a:b]` demonstrably counts upwards.
///
/// Two literals decide it outright. A left bound of literal `0` decides it too
/// whatever the right bound is — `[0:WIDTH-1]` is the shape this rule mostly
/// meets — unless the right bound is `0` as well, which is the one-bit
/// `[0:0]` and counts in no direction at all. Anything else is two symbolic
/// bounds lucisv cannot compare, and it says nothing.
fn ascending(a: &Expr, b: &Expr) -> bool {
match (literal(a), literal(b)) {
(Some(left), Some(right)) => left < right,
(Some(0), None) => true,
_ => false,
}
}
/// The value of a plain unsigned integer literal, or `None` for anything else.
fn literal(expr: &Expr) -> Option<u128> {
let ExprKind::Number(text) = &expr.kind else { return None };
if text.contains(['\'', '.']) {
return None;
}
text.chars().filter(|c| *c != '_').collect::<String>().parse().ok()
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
PackedDimensionsRangeOrdering.check(&LintContext::new(src, None))
}
fn decl(ty: &str) -> String {
format!("module m;\n {ty} sig;\nendmodule\n")
}
#[test]
fn flags_an_ascending_packed_range() {
let src = decl("logic [0:7]");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "[0:7]");
assert!(found[0].fix.is_none());
}
#[test]
fn flags_the_common_zero_to_symbolic_shape() {
assert_eq!(violations(&decl("logic [0:WIDTH-1]")).len(), 1);
assert_eq!(violations(&decl("logic [1:2]")).len(), 1);
}
#[test]
fn a_decreasing_range_is_what_the_rule_wants() {
for ty in ["logic [7:0]", "logic [WIDTH-1:0]", "logic [0:0]", "logic", "logic [3]"] {
assert!(violations(&decl(ty)).is_empty(), "{ty}: {:?}", violations(&decl(ty)));
}
}
#[test]
fn two_symbolic_bounds_are_left_alone() {
// lucisv does not evaluate parameters, so it says nothing here rather
// than guessing which way `LO:HI` counts.
assert!(violations(&decl("logic [LO:HI]")).is_empty());
assert!(violations(&decl("logic [A-1:B]")).is_empty());
}
#[test]
fn an_unpacked_array_is_not_a_packed_dimension() {
assert!(violations("module m;\n logic q [0:3];\nendmodule\n").is_empty());
assert!(violations("module m;\n logic [7:0] q [0:3];\nendmodule\n").is_empty());
}
#[test]
fn every_declaration_shape_is_reached() {
let src = "module m #(parameter logic [0:1] P = 0) (\n\
input logic [0:2] a\n\
);\n\
typedef logic [0:3] w_t;\n\
function void f(input logic [0:4] x);\n\
endfunction\n\
endmodule\n";
assert_eq!(violations(src).len(), 4, "{:?}", violations(src));
}
}
@@ -3,6 +3,7 @@
use crate::context::LintContext;
use crate::naming::{is_camel_case, is_escaped, is_upper_snake_case};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
use vlog_parser::ast::{ItemKind, ParamDecl, StmtKind};
@@ -22,6 +23,10 @@ impl Rule for ParameterNameStyle {
"name parameters in CamelCase or ALL_CAPS"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A parameter is a compile-time constant, and reading one at a use site \
should not require scrolling back to the declaration to learn that. \
@@ -0,0 +1,88 @@
//! `plusarg-assignment` — read a plusarg's value, do not test for its name.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::token::TokenKind;
/// See [`Rule::doc`].
pub struct PlusargAssignment;
const NAME: &str = "plusarg-assignment";
/// The system task this rule is about.
const TEST_PLUSARGS: &str = "$test$plusargs";
impl Rule for PlusargAssignment {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"read a plusarg with `$value$plusargs`, not `$test$plusargs`"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"`$test$plusargs(\"foo\")` answers only whether `+foo` was on the \
command line, and it matches by *prefix*: `+foobar` makes it true \
too, so two switches that share a prefix silently turn each other on. \
`$value$plusargs(\"foo=%d\", v)` matches the whole name, says whether \
it was there, and hands back the value — everything the other one \
does, without the trap, which is why a plusarg should always be \
given and read as a value. Verible's `plusarg-assignment` (\"Checks \
that plusargs are always assigned a value, by ensuring that plusargs \
are never accessed using the `$test$plusargs` system task.\", enabled \
by default) is the same rule and the same default. No automatic fix: \
the replacement needs a format string and a variable to read into, \
neither of which the call being replaced has."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
ctx.tokens()
.iter()
.filter(|token| token.kind == TokenKind::SystemIdent && token.text == TEST_PLUSARGS)
.map(|token| {
Violation::new(
NAME,
"`$test$plusargs` matches by prefix; use `$value$plusargs` and read the value",
token.span,
)
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
PlusargAssignment.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_test_plusargs_call() {
let src = "module m;\n initial if ($test$plusargs(\"fast\")) go = 1;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "$test$plusargs");
assert!(found[0].fix.is_none());
}
#[test]
fn the_value_form_is_what_the_rule_wants() {
let src = "module m;\n\
initial if ($value$plusargs(\"speed=%0d\", speed)) go = 1;\n\
endmodule\n";
assert!(violations(src).is_empty());
// And a name that merely contains the words is not the call.
assert!(violations("module m;\n logic test_plusargs;\nendmodule\n").is_empty());
assert!(violations("module m;\n initial $display(\"$test$plusargs\");\nendmodule\n")
.is_empty());
}
}
@@ -4,6 +4,7 @@
use crate::context::LintContext;
use crate::naming::{is_escaped, is_lower_snake_case};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::{ItemKind, TypedefKind};
@@ -22,6 +23,10 @@ impl Rule for StructUnionNameStyle {
"name struct and union typedefs in lower_snake_case ending in _t"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"The `_t` suffix is the one piece of Verilog naming convention that is \
nearly universal: it marks an identifier as a type, which the language \
@@ -0,0 +1,168 @@
//! `suspicious-semicolon` — a `;` where a body was meant.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_all_stmts;
use vlog_parser::ast::{Stmt, StmtKind};
/// See [`Rule::doc`].
pub struct SuspiciousSemicolon;
const NAME: &str = "suspicious-semicolon";
impl Rule for SuspiciousSemicolon {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not end a control statement's header with a `;`"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"`if (ready);` is legal and does nothing: the `;` is the whole body, \
and whatever is indented under it runs unconditionally. The same \
typo turns `for (…);` and `while (…);` into a loop that spins on an \
empty body — an infinite one, if the body was where the loop variable \
moved. It survives review because it looks right; the character that \
breaks it is one column wide. Verible's `suspicious-semicolon` \
(\"Checks that there are no suspicious semicolons that might affect \
code behaviour but escape quick visual inspection.\") is the same \
rule; **lucisv turns it on by default where Verible ships it off**, \
because the finding is a typo rather than a matter of taste. A \
deliberately empty body is written `begin end`, which is not \
reported. No automatic fix: deleting the `;` would change what the \
code does, and that is the author's call."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_all_stmts(ctx.file(), &mut |stmt| {
for (what, body) in empty_bodies(stmt) {
out.push(Violation::new(
NAME,
format!("`{what}` has an empty body; the `;` is the whole of it"),
body.span,
));
}
});
out
}
}
/// The null bodies of one statement: what it is, and the `;` standing where
/// its body belongs. A statement with a real body contributes nothing.
fn empty_bodies(stmt: &Stmt) -> Vec<(&'static str, &Stmt)> {
let null = |body: &Stmt| matches!(body.kind, StmtKind::Null);
let mut out = Vec::new();
match &stmt.kind {
StmtKind::If { then, els, .. } => {
if null(then) {
out.push(("if", then.as_ref()));
}
// An `else if` is an `if` and is judged as one when the walk
// reaches it; only a bare `else ;` is this statement's fault.
if let Some(els) = els {
if null(els) {
out.push(("else", els.as_ref()));
}
}
}
StmtKind::For { body, .. } => push_if(&mut out, "for", body, null),
StmtKind::While { body, .. } => push_if(&mut out, "while", body, null),
StmtKind::Repeat { body, .. } => push_if(&mut out, "repeat", body, null),
StmtKind::Forever { body } => push_if(&mut out, "forever", body, null),
StmtKind::Foreach { body, .. } => push_if(&mut out, "foreach", body, null),
_ => {}
}
out
}
fn push_if<'a>(
out: &mut Vec<(&'static str, &'a Stmt)>,
what: &'static str,
body: &'a Stmt,
null: impl Fn(&Stmt) -> bool,
) {
if null(body) {
out.push((what, body));
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
SuspiciousSemicolon.check(&LintContext::new(src, None))
}
fn wrap(body: &str) -> String {
format!("module m;\n always_comb begin\n{body} end\nendmodule\n")
}
#[test]
fn flags_an_if_whose_body_is_a_semicolon() {
let src = wrap(" if (ready);\n x = 1;\n");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`if`"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], ";", "the `;`, underlined");
assert!(found[0].fix.is_none());
}
#[test]
fn flags_every_loop_header_and_a_bare_else() {
for (body, what) in [
(" for (int i = 0; i < 4; i++);\n", "for"),
(" while (busy);\n", "while"),
(" repeat (4);\n", "repeat"),
(" forever;\n", "forever"),
(" foreach (q[i]);\n", "foreach"),
(" if (a) x = 1; else;\n", "else"),
] {
let found = violations(&wrap(body));
assert_eq!(found.len(), 1, "{body}: {found:?}");
assert!(found[0].message.contains(what), "{}", found[0].message);
}
}
#[test]
fn a_real_body_is_never_flagged() {
for body in [
" if (ready) x = 1;\n",
" if (ready) begin\n x = 1;\n end\n",
" if (a) x = 1; else x = 0;\n",
" while (busy) x = 1;\n",
" for (int i = 0; i < 4; i++) x = i;\n",
] {
assert!(violations(&wrap(body)).is_empty(), "{body}");
}
}
#[test]
fn a_deliberately_empty_block_is_the_way_to_write_one() {
assert!(violations(&wrap(" if (ready) begin end\n")).is_empty());
assert!(violations(&wrap(" forever begin end\n")).is_empty());
}
#[test]
fn a_lone_null_statement_is_not_a_body() {
// A stray `;` among statements is harmless — it is nobody's body.
assert!(violations(&wrap(" ;\n x = 1;\n")).is_empty());
}
#[test]
fn an_else_if_chain_is_judged_on_the_inner_if() {
let src = wrap(" if (a) x = 1; else if (b);\n");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`if`"), "{}", found[0].message);
}
}
@@ -0,0 +1,156 @@
//! `truncated-numeric-literal` — a literal wider than the width it declares.
use crate::context::LintContext;
use crate::literal;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::token::TokenKind;
/// See [`Rule::doc`].
pub struct TruncatedNumericLiteral;
const NAME: &str = "truncated-numeric-literal";
impl Rule for TruncatedNumericLiteral {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"keep a sized literal inside the width it declares"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"`4'hFFF` is not an error and not a warning in most simulators: the \
value is silently truncated to `4'hF` and the extra digits are gone. \
Whichever half of it was wrong — the width or the value — the code \
does not do what it reads as, and the reader has to count nibbles to \
see it. Verible's `truncated-numeric-literal` (\"Checks that numeric \
literals are not longer than their stated bit-width to avoid \
undesired accidental truncation.\", enabled by default) is the same \
rule. Leading zeros do not count (`8'h0FF` is eight bits), an `x` or \
`z` digit counts as a full digit, and a decimal literal carrying `x` \
is not judged at all. A literal whose digits are **all** unknown \
(`3'hz`, `7'hzz`) is left alone: those are how the language spells a \
three-bit and a seven-bit `z`, and their digit count only exceeds the \
width because a hex digit is four bits. No automatic fix: only the \
author knows which of the two numbers was meant."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
ctx.tokens()
.iter()
.filter(|token| token.kind == TokenKind::Number)
.filter_map(|token| {
let parsed = literal::parse(&token.text)?;
let bits = parsed.significant_bits()?;
if bits <= parsed.width || all_unknown(&parsed.packed_digits()) {
return None;
}
Some(Violation::new(
NAME,
format!(
"literal needs {bits} bits but declares {}; the value is truncated",
parsed.width
),
token.span,
))
})
.collect()
}
}
/// True when every digit is `x`, `z` or `?`.
///
/// `3'hz` and `7'hzz` are how the language spells a three-bit and a seven-bit
/// `z`: the digit count exceeds the width by construction, because one hex
/// digit is four bits, and nothing is being truncated — the value is unknown
/// either way. Measured on opentitan, this shape was every one of the rule's
/// findings in `top_earlgrey/dv/tb/tb.sv`.
fn all_unknown(digits: &str) -> bool {
!digits.is_empty() && digits.chars().all(|c| matches!(c.to_ascii_lowercase(), 'x' | 'z' | '?'))
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
TruncatedNumericLiteral.check(&LintContext::new(src, None))
}
fn assign(value: &str) -> String {
format!("module m;\n assign x = {value};\nendmodule\n")
}
#[test]
fn flags_a_literal_that_does_not_fit() {
let found = violations(&assign("4'hFFF"));
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("12 bits"), "{}", found[0].message);
assert!(found[0].message.contains("declares 4"), "{}", found[0].message);
assert!(found[0].fix.is_none());
}
#[test]
fn flags_every_base() {
for value in ["1'b11", "2'o77", "4'hFF", "4'd16", "8'd300"] {
assert_eq!(violations(&assign(value)).len(), 1, "{value}");
}
}
#[test]
fn a_literal_that_fits_is_silent() {
for value in [
"4'hF",
"4'h0F",
"8'h0FF",
"8'b0000_0001",
"32'hdead_beef",
"8'd255",
"4'h0",
"1'b0",
"8'sh7f",
] {
assert!(
violations(&assign(value)).is_empty(),
"{value}: {:?}",
violations(&assign(value))
);
}
}
#[test]
fn an_unknown_digit_counts_but_a_decimal_unknown_is_not_judged() {
assert_eq!(violations(&assign("4'hxF")).len(), 1, "two nibbles in a one-nibble literal");
assert!(violations(&assign("4'hx")).is_empty(), "one nibble fits");
assert!(violations(&assign("8'dx")).is_empty(), "a decimal x says nothing about width");
}
/// `3'hz` is a three-bit `z`, not a truncated four-bit one — the shape
/// that was every opentitan finding in `top_earlgrey/dv/tb/tb.sv`.
#[test]
fn an_all_unknown_literal_is_not_truncated() {
for value in ["3'hz", "7'hzz", "1'bx", "5'h??", "3'hZ"] {
assert!(
violations(&assign(value)).is_empty(),
"{value}: {:?}",
violations(&assign(value))
);
}
// A mixed literal still counts its digits.
assert_eq!(violations(&assign("4'hxF")).len(), 1);
}
#[test]
fn an_unsized_literal_and_a_plain_number_are_not_judged() {
for value in ["'h1f", "42", "1.5", "'0", "'1"] {
assert!(violations(&assign(value)).is_empty(), "{value}");
}
}
}
@@ -0,0 +1,238 @@
//! `undeclared-identifier` — a name nothing in the project declares.
use std::collections::BTreeSet;
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::ast::ItemKind;
use vlog_semantic::{words, Resolution};
/// See [`Rule::doc`].
pub struct UndeclaredIdentifier;
const NAME: &str = "undeclared-identifier";
impl Rule for UndeclaredIdentifier {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"use a name something declares"
}
fn severity(&self) -> Severity {
Severity::Error
}
fn doc(&self) -> &'static str {
"A misspelled signal name is the one mistake in Verilog that costs \
nothing to make and hours to find: an undeclared identifier in a \
value position is an elaboration error in a strict tool and an \
implicit one-bit net in a permissive one, and the second is worse — \
the design builds, the bit stays `z`, and the bug surfaces in \
simulation as a value nobody can trace. This rule reports a name that \
**this file** does not declare, that no external unit it names could \
supply, and that **no other file in the project writes down at all**.\n\n\
Every one of those clauses is an exclusion, and they are what make an \
Error-class rule about names safe to run. It says nothing at all \
unless the run can see the project (`lucisv check <dir>`, or the \
language server), because the whole case for a finding is that the \
name appears nowhere else. It says nothing about a name any macro \
invocation, compiler directive or attribute in this file writes down \
— text lucisv never expands, and where half the identifiers in a \
testbench live. It says nothing about a file that did not fully \
parse, where error recovery moves declarations between scopes. And it \
says nothing where the single-file analysis already knew it could not \
answer: a package member, an inherited name, a hierarchical tail and \
a `.port` connection all resolve elsewhere and never reach here. \
Verible has no equivalent rule — its linter is syntax-only.\n\n\
**Measured before it was switched on.** Over opentitan's `hw/` \
(3 975 files) and over lucisv's own 860-file corpus it reports the \
same five findings, in one file: `ibex/dv/formal/spec/spec_api.sv` \
connects `.mhartid_out(mhart_id_o)` and four siblings to names its \
module header never declares, which is exactly the implicit net this \
rule exists to find. No false positive survived the exclusions, so it \
ships on wherever there is a project — the same terms `unused-signal` \
and `undriven-net` run on. No automatic fix: a misspelling has no one \
repair."
}
fn default_on(&self) -> bool {
false
}
fn needs_workspace(&self) -> bool {
true
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
// The whole case for a finding is "nothing else in the project writes
// this name down", which a run that cannot see the project cannot
// make. Without an oracle this rule has nothing to say — and saying
// it anyway would accuse every name in every buffer.
if !ctx.has_oracle() || !ctx.parsed_cleanly() || !declares_a_unit(ctx) {
return Vec::new();
}
let raw: BTreeSet<String> = words::harvest_raw(ctx.tokens()).into_iter().collect();
let semantics = ctx.semantics();
semantics
.references()
.iter()
.filter(|reference| reference.resolution == Resolution::NotFound)
.filter(|reference| !reference.name_span.is_empty())
// A use written at **file scope** belongs to no unit; the
// fragment guard above has already dropped the files where that
// is the whole file, and what is left is a stray.
.filter(|reference| reference.scope != semantics.file_scope())
// A name the file declares *somewhere* — a generate block's
// label reached through a hierarchical path, a member of a scope
// this use is not written in — is a name that exists; whether the
// path to it is right is more than this rule claims to know.
.filter(|reference| semantics.symbols_named(&reference.name).next().is_none())
.filter(|reference| !raw.contains(&reference.name))
.filter(|reference| !ctx.mentioned_elsewhere(&reference.name))
.map(|reference| {
Violation::new(
NAME,
format!("`{}` is declared nowhere in the project", reference.name),
reference.name_span,
)
})
.collect()
}
}
/// True when the file declares a design unit of its own — a module, an
/// interface, a program, a package or a class.
///
/// A file that declares none but still holds declarations and assignments is
/// a **fragment**: the middle of a module body, written to be `` `include``d
/// at that point (`docs/features/fragment-mode/README.md`), where every name
/// it reads is declared by the file that includes it and no census of *this*
/// file can see them. Measured on opentitan: every one of the rule's 94
/// findings was in four such fragments in ibex's formal harness plus one
/// generate label, and this guard plus the declared-here guard removes all
/// of them.
fn declares_a_unit(ctx: &LintContext) -> bool {
let mut found = false;
crate::visit::walk_items(ctx.file(), &mut |item| {
found |= matches!(
item.kind,
ItemKind::Module(_) | ItemKind::Package { .. } | ItemKind::Class(_)
);
});
found
}
#[cfg(test)]
mod tests {
use super::*;
use crate::MentionOracle;
/// A project in which these names are written down somewhere else.
struct Elsewhere(&'static [&'static str]);
impl MentionOracle for Elsewhere {
fn mentioned_elsewhere(&self, name: &str) -> bool {
self.0.contains(&name)
}
}
fn violations(src: &str, elsewhere: &'static [&'static str]) -> Vec<Violation> {
let ctx = LintContext::new(src, None);
let oracle = Elsewhere(elsewhere);
UndeclaredIdentifier.check(&ctx.with_oracle(&oracle))
}
#[test]
fn flags_a_name_nothing_declares_and_nothing_else_mentions() {
let src = "module m;\n logic data;\n assign x = dara;\nendmodule\n";
let found = violations(src, &[]);
assert!(found.iter().any(|v| v.message.contains("`dara`")), "{found:?}");
assert!(found[0].fix.is_none());
}
#[test]
fn a_declared_name_is_never_flagged() {
let src = "module m;\n logic data;\n assign data = 1'b0;\nendmodule\n";
assert!(violations(src, &[]).is_empty(), "{:?}", violations(src, &[]));
}
/// The rule's whole safety net: a name some other file writes down —
/// however it writes it — is not an accusation this rule will make.
#[test]
fn a_name_another_file_mentions_is_left_alone() {
let src = "module m;\n assign x = elsewhere_sig;\nendmodule\n";
assert!(violations(src, &["elsewhere_sig", "x"]).is_empty());
}
#[test]
fn a_name_this_files_macro_text_writes_down_is_left_alone() {
// `MY_SIG` is produced by a macro lucisv never expands; the census of
// raw text is what tells the rule to keep quiet.
let src = "module m;\n\
logic x;\n\
`define MY_SIG some_sig\n\
assign x = some_sig;\n\
endmodule\n";
assert!(violations(src, &[]).is_empty(), "{:?}", violations(src, &[]));
}
/// An `` `include``d fragment — a module body with no module around it —
/// reads names the including file declares, and no census of this file
/// can see them. It was 85 of the 94 opentitan findings.
#[test]
fn an_include_fragment_gets_no_opinion() {
let src = "assign pre_pc = other_sig;\nlogic [3:0] pre_regs;\n";
assert!(violations(src, &[]).is_empty(), "{:?}", violations(src, &[]));
}
/// A generate label reached through a hierarchical path is declared in
/// this file, just not in the scope the use is written in.
#[test]
fn a_name_this_file_declares_somewhere_is_left_alone() {
let src = "module m;\n\
if (1) begin : gen_lfsr\n\
logic state_q;\n\
end\n\
assign x = gen_lfsr;\n\
endmodule\n";
let found = violations(src, &[]);
assert!(!found.iter().any(|v| v.message.contains("gen_lfsr")), "{found:?}");
}
#[test]
fn a_run_with_no_project_behind_it_says_nothing() {
let src = "module m;\n assign x = dara;\nendmodule\n";
let ctx = LintContext::new(src, None);
assert!(UndeclaredIdentifier.check(&ctx).is_empty(), "no oracle, no opinion");
}
#[test]
fn a_file_that_did_not_parse_gets_no_opinion() {
let src = "module m;\n @@@ junk\n assign x = dara;\nendmodule\n";
assert!(violations(src, &[]).is_empty(), "{:?}", violations(src, &[]));
}
#[test]
fn a_package_member_and_a_hierarchical_tail_never_reach_this_rule() {
// Both resolve somewhere else — an external candidate or a member —
// so neither is a `NotFound`, which is what this rule reports.
for src in [
"module m;\n assign x = pkg::thing;\nendmodule\n",
"module m;\n assign x = tb.dut.sig;\nendmodule\n",
"module m;\n import p::*;\n assign x = from_pkg;\nendmodule\n",
] {
let found = violations(src, &[]);
assert!(
!found.iter().any(|v| v.message.contains("thing")
|| v.message.contains("sig")
|| v.message.contains("from_pkg")),
"{src}: {found:?}"
);
}
}
}
@@ -0,0 +1,187 @@
//! `undersized-binary-literal` — write every bit of a sized binary literal.
use crate::context::LintContext;
use crate::literal;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use vlog_parser::span::TextRange;
use vlog_parser::token::TokenKind;
/// See [`Rule::doc`].
pub struct UndersizedBinaryLiteral;
const NAME: &str = "undersized-binary-literal";
impl Rule for UndersizedBinaryLiteral {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"write every bit of a sized binary literal"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"`8'b1` is one bit written where eight were declared, and a reader has \
to remember the zero-extension rule to know it is `8'b0000_0001` — \
while the very similar `8'bx` is *not* `8'b0000_000x` but eight `x`s, \
because a leading `x` or `z` extends instead of zero-filling. Spelling \
every bit takes the rule out of the reader's head. Verible's \
`undersized-binary-literal` (\"Checks that the digits of binary \
literals for the configured bases match their declared width.\", \
enabled by default, binary only by default) is the same rule and the \
same default; lucisv checks binary alone for the same reason, and — \
also following that rule's defaults, whose `lint_zero` option is \
off — leaves a literal whose value is **zero** alone: `2'b0` is not \
a truncation waiting to happen, it is how the language spells zero. \
The fix \
is **safe**: it writes the extension the language would have applied, \
which is `0` for a literal starting with `0` or `1` and the unknown \
itself for one starting with `x` or `z`. Underscore separators are \
preserved as written, and a literal *wider* than its declaration is \
`truncated-numeric-literal`'s business, not this one's."
}
fn fix(&self) -> Option<Applicability> {
Some(Applicability::Safe)
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
ctx.tokens()
.iter()
.filter(|token| token.kind == TokenKind::Number)
.filter_map(|token| {
let parsed = literal::parse(&token.text)?;
if parsed.base != 'b' {
return None;
}
let digits = parsed.packed_digits();
let written = digits.chars().count() as u32;
if written >= parsed.width || is_zero(&digits) {
return None;
}
let padding = pad_char(&digits)?;
let missing = (parsed.width - written) as usize;
// The pad goes in front of the first digit as written, so an
// `_` the author put in the middle stays where it was.
let first = token.span.end - parsed.digits.len() as u32;
Some(
Violation::new(
NAME,
format!("binary literal writes {written} of its {} bits", parsed.width),
token.span,
)
.with_fix(Fix::safe(vec![(
TextRange::new(first, first),
padding.to_string().repeat(missing),
)])),
)
})
.collect()
}
}
/// True for a literal whose written value is zero — `1'b0`, `8'b0`, `4'b00`.
///
/// Exempt because Verible's `lint_zero` option defaults to **false**, and
/// matching its default is what keeps a Verible-clean codebase lucisv-clean:
/// measured on opentitan, `'b0` accounts for the great majority of every
/// undersized binary literal in the tree, and every one of them reads exactly
/// as it means.
fn is_zero(digits: &str) -> bool {
digits.chars().all(|c| c == '0')
}
/// The digit the language would extend this literal with: an unknown extends
/// itself, everything else extends with `0` (IEEE 1800 §5.7.1). `None` for an
/// empty digit run, which [`literal::parse`] never produces.
fn pad_char(digits: &str) -> Option<char> {
match digits.chars().next()?.to_ascii_lowercase() {
c @ ('x' | 'z' | '?') => Some(c),
_ => Some('0'),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::violation::apply_fixes;
fn violations(src: &str) -> Vec<Violation> {
UndersizedBinaryLiteral.check(&LintContext::new(src, None))
}
fn assign(value: &str) -> String {
format!("module m;\n assign x = {value};\nendmodule\n")
}
fn fixed(value: &str) -> String {
let src = assign(value);
apply_fixes(&src, &violations(&src), false).output
}
#[test]
fn flags_a_short_binary_literal_and_pads_it() {
let src = assign("8'b1");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("1 of its 8"), "{}", found[0].message);
assert_eq!(fixed("8'b1"), assign("8'b00000001"));
}
#[test]
fn an_unknown_extends_itself_not_with_zeros() {
assert_eq!(fixed("4'bx"), assign("4'bxxxx"));
assert_eq!(fixed("4'bz"), assign("4'bzzzz"));
// ... and a literal that only *contains* an unknown still zero-fills,
// because the language looks at the leftmost digit.
assert_eq!(fixed("4'b1x"), assign("4'b001x"));
}
#[test]
fn separators_stay_where_the_author_put_them() {
assert_eq!(fixed("8'b1_1"), assign("8'b0000001_1"));
}
/// Verible's `lint_zero` defaults to off, and so does lucisv: `2'b0` was
/// the great majority of this rule's opentitan findings before the exempt.
#[test]
fn a_zero_literal_is_exempt() {
for value in ["2'b0", "8'b0", "4'b00", "1'b0", "32'b0_0"] {
assert!(violations(&assign(value)).is_empty(), "{value}");
}
// A non-zero literal of the same width is still reported.
assert_eq!(violations(&assign("2'b1")).len(), 1);
}
#[test]
fn a_full_width_literal_is_silent() {
for value in ["8'b0000_0001", "1'b0", "4'b1010", "4'bxxxx"] {
assert!(violations(&assign(value)).is_empty(), "{value}");
}
}
#[test]
fn only_binary_is_judged_and_only_when_sized() {
for value in ["8'h1", "8'd1", "8'o1", "'b1", "42"] {
assert!(violations(&assign(value)).is_empty(), "{value}");
}
}
#[test]
fn an_oversized_literal_belongs_to_the_other_rule() {
assert!(violations(&assign("1'b11")).is_empty());
}
#[test]
fn the_fix_leaves_the_file_clean() {
let src = assign("8'b1");
let once = apply_fixes(&src, &violations(&src), false).output;
assert!(violations(&once).is_empty(), "idempotent: {once}");
}
}
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::signals::intentionally_unused;
use crate::violation::Violation;
@@ -19,6 +20,10 @@ impl Rule for UndrivenNet {
"drive a signal that something reads"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A net read by the design but assigned by nothing is `z` forever, and \
a variable in the same position is `x` forever. In simulation this \
@@ -0,0 +1,145 @@
//! `unknown-parameter` — a `#(.NAME(…))` the module does not declare.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_instantiations;
/// See [`Rule::doc`].
pub struct UnknownParameter;
const NAME: &str = "unknown-parameter";
impl Rule for UnknownParameter {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"override only parameters the instantiated module declares"
}
fn severity(&self) -> Severity {
Severity::Error
}
fn doc(&self) -> &'static str {
"`#(.Width(8))` on a module whose parameter is called `DataWidth` is \
an elaboration error, and — worse than the port version — the \
*silent* failure mode is real: a tool that accepts the override \
anyway elaborates the module at its declared default, so the design \
builds and is the wrong width. A `localparam` is not overridable at \
all (IEEE 1800 §6.20.4), so naming one here is the same error wearing \
a different hat, and lucisv reports it: the parameter list this rule \
checks against holds every `parameter` of the header and the body and \
no `localparam` of either. Verible has no equivalent; this is TODO \
§33.2's own rule.\n\n\
It keeps `unknown-port`'s silences exactly: no project, an unindexed \
module, one declared twice with different headers, one whose header \
carries a compiler directive, and a scope-qualified instantiation are \
all cases where the run cannot answer and the rule says nothing. A \
positional override names nothing to check — that is `module-\
parameter`'s subject. No automatic fix."
}
fn default_on(&self) -> bool {
// Off without a project: with no interface table to ask, every named
// override would be unanswerable and the rule would be a no-op that
// still cost a walk.
false
}
fn needs_workspace(&self) -> bool {
true
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_instantiations(ctx.file(), &mut |inst| {
if inst.module.contains(':') {
return;
}
let Some(params) = &inst.params else { return };
let Some(interface) = ctx.module_interface(&inst.module) else { return };
for param in params {
if param.name == "*" || param.name_span.is_empty() {
continue;
}
if interface.has_parameter(&param.name) {
continue;
}
out.push(Violation::new(
NAME,
format!("`{}` declares no overridable parameter `{}`", inst.module, param.name),
param.name_span,
));
}
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::context::{MentionOracle, ModuleInterface};
/// A project holding one module with these overridable parameters.
struct Project(&'static str, &'static [&'static str]);
impl MentionOracle for Project {
fn mentioned_elsewhere(&self, _name: &str) -> bool {
false
}
fn module_interface(&self, name: &str) -> Option<ModuleInterface> {
(name == self.0).then(|| ModuleInterface {
ports: Vec::new(),
parameters: self.1.iter().map(|p| p.to_string()).collect(),
})
}
}
fn violations(src: &str, project: &'static Project) -> Vec<Violation> {
let ctx = LintContext::new(src, None);
UnknownParameter.check(&ctx.with_oracle(project))
}
static SUB: Project = Project("sub", &["Width", "Depth"]);
#[test]
fn flags_an_override_the_module_does_not_declare() {
let src = "module m;\n sub #(.Width(8), .Deth(4)) u ();\nendmodule\n";
let found = violations(src, &SUB);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`Deth`"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "Deth");
assert!(found[0].fix.is_none());
}
#[test]
fn a_declared_parameter_is_never_flagged() {
let src = "module m;\n sub #(.Width(8), .Depth(4)) u ();\nendmodule\n";
assert!(violations(src, &SUB).is_empty(), "{:?}", violations(src, &SUB));
}
#[test]
fn a_positional_override_names_nothing_to_check() {
assert!(violations("module m;\n sub #(8, 4) u ();\nendmodule\n", &SUB).is_empty());
assert!(violations("module m;\n sub u ();\nendmodule\n", &SUB).is_empty());
}
#[test]
fn an_unindexed_module_and_a_run_with_no_project_are_both_silent() {
assert!(violations("module m;\n other #(.Nope(1)) u ();\nendmodule\n", &SUB).is_empty());
let src = "module m;\n sub #(.Nope(1)) u ();\nendmodule\n";
assert!(UnknownParameter.check(&LintContext::new(src, None)).is_empty());
}
#[test]
fn a_scope_qualified_instantiation_is_left_to_the_workspace() {
let src = "module m;\n pkg::sub #(.Nope(1)) u ();\nendmodule\n";
assert!(violations(src, &SUB).is_empty());
}
}
@@ -0,0 +1,169 @@
//! `unknown-port` — a `.name(…)` the instantiated module does not declare.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_instantiations;
use vlog_parser::ast::Connections;
/// See [`Rule::doc`].
pub struct UnknownPort;
const NAME: &str = "unknown-port";
impl Rule for UnknownPort {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"connect only ports the instantiated module declares"
}
fn severity(&self) -> Severity {
Severity::Error
}
fn doc(&self) -> &'static str {
"`.data_i(x)` on a module that declares `data_in` is an elaboration \
error in every tool, and the commonest way to reach it is a port \
rename that reached the declaration and three of its four \
instantiations. The fourth is in another file, so nothing about the \
file being edited says anything is wrong. Verible has no equivalent \
— its linter reads one file at a time — and this is TODO §33.2's own \
rule.\n\n\
**Silent whenever the project cannot answer**, which is what an \
Error-class rule owes: with no project behind the run at all, for a \
module the project does not declare, for one declared more than once \
with different headers, and for one whose header lucisv cannot read \
whole — a port list carrying a compiler directive is the case that \
matters, because a macro standing where a port belongs expands to \
names lucisv never sees. A `.*` connection names nothing and is not \
judged, and a scope-qualified instantiation (`pkg::mod`) is left to \
the workspace. No automatic fix: the right port name is a guess, and \
a wrong guess here rewires a design."
}
fn default_on(&self) -> bool {
// Off without a project: with no interface table to ask, every named
// connection would be unanswerable and the rule would be a no-op that
// still cost a walk.
false
}
fn needs_workspace(&self) -> bool {
true
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_instantiations(ctx.file(), &mut |inst| {
if inst.module.contains(':') {
return;
}
let Some(interface) = ctx.module_interface(&inst.module) else { return };
for instance in &inst.instances {
let Connections::Named(conns) = &instance.conns else { continue };
for conn in conns {
if conn.name == "*" || conn.name_span.is_empty() {
continue;
}
if interface.has_port(&conn.name) {
continue;
}
out.push(Violation::new(
NAME,
format!("`{}` declares no port `{}`", inst.module, conn.name),
conn.name_span,
));
}
}
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::context::{MentionOracle, ModuleInterface};
/// A project holding one module with these ports.
struct Project(&'static str, &'static [&'static str]);
impl MentionOracle for Project {
fn mentioned_elsewhere(&self, _name: &str) -> bool {
false
}
fn module_interface(&self, name: &str) -> Option<ModuleInterface> {
(name == self.0).then(|| ModuleInterface {
ports: self.1.iter().map(|p| p.to_string()).collect(),
parameters: Vec::new(),
})
}
}
fn violations(src: &str, project: &'static Project) -> Vec<Violation> {
let ctx = LintContext::new(src, None);
UnknownPort.check(&ctx.with_oracle(project))
}
static SUB: Project = Project("sub", &["clk_i", "data_i"]);
#[test]
fn flags_a_connection_the_module_does_not_declare() {
let src = "module m;\n sub u (.clk_i(clk), .dara_i(d));\nendmodule\n";
let found = violations(src, &SUB);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`dara_i`"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "dara_i");
assert!(found[0].fix.is_none());
}
#[test]
fn a_declared_port_is_never_flagged() {
let src = "module m;\n sub u (.clk_i(clk), .data_i(d));\nendmodule\n";
assert!(violations(src, &SUB).is_empty(), "{:?}", violations(src, &SUB));
}
#[test]
fn a_module_the_project_does_not_declare_is_left_alone() {
let src = "module m;\n other u (.whatever(x));\nendmodule\n";
assert!(violations(src, &SUB).is_empty());
}
#[test]
fn a_wildcard_and_a_positional_list_name_nothing_to_check() {
assert!(violations("module m;\n sub u (.*);\nendmodule\n", &SUB).is_empty());
assert!(violations("module m;\n sub u (a, b);\nendmodule\n", &SUB).is_empty());
}
#[test]
fn a_run_with_no_project_says_nothing() {
let src = "module m;\n sub u (.dara_i(d));\nendmodule\n";
assert!(UnknownPort.check(&LintContext::new(src, None)).is_empty());
}
#[test]
fn a_scope_qualified_instantiation_is_left_to_the_workspace() {
let src = "module m;\n pkg::sub u (.dara_i(d));\nendmodule\n";
assert!(violations(src, &SUB).is_empty());
}
#[test]
fn an_implicit_named_connection_is_judged_too() {
// `.clk_i` with no parentheses is a named connection like any other.
let src = "module m;\n sub u (.clk_i, .dara_i);\nendmodule\n";
let found = violations(src, &SUB);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`dara_i`"), "{}", found[0].message);
}
#[test]
fn every_instance_of_one_statement_is_judged() {
let src = "module m;\n sub u1 (.dara_i(a)), u2 (.data_i(b));\nendmodule\n";
assert_eq!(violations(src, &SUB).len(), 1);
}
}
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::signals::intentionally_unused;
use crate::violation::Violation;
@@ -19,6 +20,10 @@ impl Rule for UnusedSignal {
"delete a signal nothing uses"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A `wire` or `logic` that nothing reads and nothing drives is dead \
weight: it costs a reader the effort of working out what it is for, \
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::waiver::UNUSED_WAIVER;
@@ -17,6 +18,10 @@ impl Rule for UnusedWaiver {
"remove waivers that no longer suppress anything"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A `// lucisv: waive` comment outlives the problem it was written for: \
the code is fixed, the waiver stays, and the next reader believes the \
+151
View File
@@ -0,0 +1,151 @@
//! `void-cast` — `void'(…)` around something that is not a call.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_all_stmts;
use vlog_parser::ast::{Expr, ExprKind, StmtKind};
/// See [`Rule::doc`].
pub struct VoidCast;
const NAME: &str = "void-cast";
impl Rule for VoidCast {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"cast to `void` only what a call returns"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"`void'(expr)` exists for exactly one purpose: calling a function for \
its side effect and saying out loud that the return value is being \
thrown away (IEEE 1800 §13.4.1). Around anything that is not a call — \
a variable, a literal, an arithmetic expression — it discards a value \
nobody computed for a side effect, which means either the call that \
was meant to be there is missing or the cast is left over from an \
edit. Verible ships a `void-cast` rule (\"Checks that void casts do \
not contain certain function/method calls.\", enabled by default) \
with a different subject: **it forbids a named list of calls** whose \
result must be checked (`randomize`, `uvm_hdl_read`). lucisv's is the \
complementary check TODO §33 asked for — the operand must be a call \
at all — and takes no list, so the two do not overlap and neither \
replaces the other; the named-call form belongs with the per-rule \
options of wave 2. No automatic fix: whether the repair is to delete \
the cast or to add the missing call is the author's to decide.\n\n\
Only a `void'(...)` standing **as a statement** is judged, which is \
the one place the construct belongs: a `void` value gives an \
enclosing expression nothing to do with it, so a `void'` buried in an \
rvalue is a different mistake and one this rule stays out of."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_all_stmts(ctx.file(), &mut |stmt| {
let StmtKind::ExprStmt(expr) = &stmt.kind else { return };
let ExprKind::Cast { ty, expr: inner, pattern, .. } = &expr.kind else { return };
if *pattern || !is_void(ty) || is_call(inner) {
return;
}
out.push(Violation::new(
NAME,
"`void'(...)` around something that is not a call; nothing is being discarded",
expr.span,
));
});
out
}
}
/// True for the casting type `void`, however it is spelled in the tree.
fn is_void(ty: &Expr) -> bool {
matches!(&ty.kind, ExprKind::Ident(name) if name == "void")
|| matches!(&ty.kind, ExprKind::Type(data) if data.name == "void")
}
/// True when the cast's operand is a call — the only thing `void'` is for.
///
/// A method call reaches here as a `Call` whose callee is a `Member`
/// (`obj.randomize()`), and a `new` expression is a constructor call; both
/// count, and so does a call carrying a `with` clause — `void'(randomize(x)
/// with { … })` is the commonest void cast there is. A parenthesized operand
/// is looked through, because `void'((f()))` is the same statement written
/// twice.
fn is_call(expr: &Expr) -> bool {
match &expr.kind {
ExprKind::Call { .. } | ExprKind::New(_) => true,
ExprKind::Paren { inner, .. } => is_call(inner),
ExprKind::With { base, .. } | ExprKind::WithConstraint { base, .. } => is_call(base),
// A cast around a cast is somebody being explicit about a return
// type; look through it rather than accuse the outer one.
ExprKind::Cast { expr: inner, .. } => is_call(inner),
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
VoidCast.check(&LintContext::new(src, None))
}
fn stmt(text: &str) -> String {
format!("module m;\n initial begin\n {text}\n end\nendmodule\n")
}
#[test]
fn flags_a_void_cast_of_a_plain_value() {
let src = stmt("void'(x);");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "void'(x)");
assert!(found[0].fix.is_none());
}
#[test]
fn a_call_is_what_a_void_cast_is_for() {
for text in [
"void'(f());",
"void'(obj.randomize());",
"void'(pkg::f(1, 2));",
"void'(q.pop_front());",
"void'((f()));",
"void'($cast(a, b));",
"void'(randomize(x) with { x inside {[0:7]}; });",
"void'(q.sum() with (item.w));",
] {
assert!(violations(&stmt(text)).is_empty(), "{text}: {:?}", violations(&stmt(text)));
}
}
#[test]
fn a_cast_to_something_else_is_not_this_rules_business() {
for text in ["a = int'(x);", "a = logic'(x);", "a = my_t'(x);", "a = 4'(x);"] {
assert!(violations(&stmt(text)).is_empty(), "{text}");
}
}
#[test]
fn only_a_statement_position_cast_is_judged() {
// A `void'` in an rvalue is a different mistake; this rule is about
// the statement idiom and says nothing there.
assert!(violations(&stmt("a = void'(x);")).is_empty());
}
#[test]
fn a_non_call_operand_of_any_shape_is_flagged() {
for text in ["void'(1);", "void'(a + b);", "void'(s.field);", "void'(q[0]);"] {
assert_eq!(violations(&stmt(text)).len(), 1, "{text}");
}
}
}
@@ -4,6 +4,7 @@ use std::path::Path;
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::token::TokenKind;
@@ -21,6 +22,10 @@ impl Rule for WireRegMixup {
"use `logic` instead of `reg` in SystemVerilog files"
}
fn severity(&self) -> Severity {
Severity::Error
}
fn doc(&self) -> &'static str {
"`reg` is Verilog-1995's name for a variable, and its worst property is \
that it reads like hardware: generations of engineers have written \
+82
View File
@@ -0,0 +1,82 @@
//! How bad a finding is: the three classes every rule states.
//!
//! Verible has no such notion — every one of its rules produces the same
//! diagnostic — and ruff spells it as a rule *prefix* (`E`, `W`, `F`). lucisv
//! takes ruff's idea and Verible's vocabulary: three words a user can select,
//! ignore and toggle by, chosen so the question they answer is "would a tool
//! refuse this file?" rather than "how annoyed am I".
/// How bad one rule's findings are.
///
/// The order is worst-first, and it is the order a generated document and a
/// settings UI list the classes in — so [`Ord`] is derived rather than
/// hand-written, and sorting by it sorts by seriousness.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Severity {
/// The code would very likely fail to compile, elaborate or synthesize.
/// A rule may only claim this when it is certain: an `Error` finding is an
/// accusation, so every rule in this class stays silent whenever it cannot
/// answer — see `docs/features/linter-expansion-1/README.md`.
Error,
/// The code compiles, and means something the author probably did not
/// intend: a latch where none was wanted, a deprecated construct, a
/// literal that does not fit its width.
Warning,
/// The code is correct and reads badly: naming, tabs, a redundant `;`.
Style,
}
impl Severity {
/// Every class, worst first — the order rules and settings are grouped in.
pub const ALL: [Severity; 3] = [Severity::Error, Severity::Warning, Severity::Style];
/// The word this class is spelled with everywhere a user meets it:
/// `--select`, `--ignore`, the CLI diagnostic line, the JSON output and
/// the generated rule reference.
pub fn as_str(self) -> &'static str {
match self {
Severity::Error => "error",
Severity::Warning => "warning",
Severity::Style => "style",
}
}
/// The class that word names, or `None` when it names no class.
pub fn from_name(name: &str) -> Option<Severity> {
Severity::ALL.into_iter().find(|severity| severity.as_str() == name)
}
/// One line saying what the class means, for the generated reference and
/// for the settings UI — one wording, so the two cannot drift.
pub fn describes(self) -> &'static str {
match self {
Severity::Error => {
"code that would very likely fail to compile, elaborate or synthesize"
}
Severity::Warning => "code that compiles but very likely does not mean what it says",
Severity::Style => "code that is correct and reads badly",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_class_round_trips_through_its_word() {
for severity in Severity::ALL {
assert_eq!(Severity::from_name(severity.as_str()), Some(severity));
assert!(!severity.describes().is_empty());
}
assert_eq!(Severity::from_name("errors"), None);
assert_eq!(Severity::from_name("Error"), None, "matched exactly, like every other name");
}
#[test]
fn the_classes_are_ordered_worst_first() {
let mut shuffled = [Severity::Style, Severity::Error, Severity::Warning];
shuffled.sort_unstable();
assert_eq!(shuffled, Severity::ALL);
}
}
+10 -1
View File
@@ -2,12 +2,21 @@
use vlog_parser::span::TextRange;
use crate::severity::Severity;
/// One rule finding: which rule, what is wrong, where, and — sometimes —
/// how to repair it.
#[derive(Debug, Clone)]
pub struct Violation {
/// The reporting rule's stable kebab-case name.
pub rule: &'static str,
/// How bad it is. **Set by the runner from the reporting rule**, not by
/// the rule's own `check` — [`crate::lint`] stamps every finding with
/// [`crate::Rule::severity`] before it is returned, so a rule cannot
/// contradict its own declared class. A violation built by hand (a rule's
/// unit test calling `check` directly) carries the placeholder below until
/// it goes through the runner.
pub severity: Severity,
/// One sentence, lower case, no trailing period — the diagnostic line.
pub message: String,
/// Byte range the diagnostic points at.
@@ -19,7 +28,7 @@ pub struct Violation {
impl Violation {
/// A finding with no automatic repair.
pub fn new(rule: &'static str, message: impl Into<String>, span: TextRange) -> Violation {
Violation { rule, message: message.into(), span, fix: None }
Violation { rule, severity: Severity::Warning, message: message.into(), span, fix: None }
}
/// The same finding, carrying a repair.
+13 -1
View File
@@ -5,7 +5,8 @@
//! text and no children, so they are visited and matched by nothing.
use vlog_parser::ast::{
Fragment, GenBlock, GenElse, Item, ItemKind, ParamPort, SourceFile, Stmt, StmtKind,
Fragment, GenBlock, GenElse, Instantiation, Item, ItemKind, ParamPort, SourceFile, Stmt,
StmtKind,
};
/// Calls `f` on every item in the file, nested items included.
@@ -156,6 +157,17 @@ pub(crate) fn walk_param_ports(file: &SourceFile, f: &mut dyn FnMut(&ParamPort))
});
}
/// Calls `f` on every module instantiation of the file — a plain one, and the
/// one a `bind` directive carries, which is an ordinary instantiation written
/// somewhere else.
pub(crate) fn walk_instantiations(file: &SourceFile, f: &mut dyn FnMut(&Instantiation)) {
walk_items(file, &mut |item| match &item.kind {
ItemKind::Instantiation(inst) => f(inst),
ItemKind::Bind(bind) => f(&bind.inst),
_ => {}
});
}
#[cfg(test)]
mod tests {
use super::*;
+188
View File
@@ -0,0 +1,188 @@
//! The VS Code lint settings, generated from the rule registry.
//!
//! `editors/vscode/package.json` declares one switch per severity class and
//! one per rule. Hand-written, that list would go stale the first time a rule
//! was added — the rule would ship with no way to turn it off from the
//! editor — so it is generated here instead, by the same crate that owns the
//! registry, exactly as [`crate::rules_markdown`] generates the rule
//! reference.
//!
//! Two consumers, one text: `cargo run -p vlog_linter --example
//! vscode_lint_settings` prints it for a human to paste in, and a test in
//! `lucisv_server` parses both this and `package.json` and fails when they
//! disagree. See `docs/features/linter-expansion-1/README.md`.
use crate::registry::all_rules;
use crate::severity::Severity;
use crate::Rule;
/// The setting a severity class's master switch is called.
pub fn severity_setting(severity: Severity) -> String {
format!("lucisv.lint.severity.{}", severity.as_str())
}
/// The setting one rule's toggle is called.
pub fn rule_setting(rule: &dyn Rule) -> String {
format!("lucisv.lint.rules.{}", rule.name())
}
/// The three words a per-rule toggle takes.
///
/// A tri-state rather than a boolean, and deliberately: the ladder in
/// `lucisv_server::settings::enabled_rules` distinguishes a rule the user
/// *said something about* from one they left alone, and a plain boolean cannot
/// carry that — a client sends every setting in the section, its default
/// included, so "unset" and "set to the default" would arrive identically and
/// a per-rule toggle would silently override `select` and the class switches.
pub const RULE_CHOICES: [&str; 3] = ["default", "on", "off"];
/// The whole `lucisv.lint.severity.*` + `lucisv.lint.rules.*` block, as the
/// JSON object `package.json`'s `configuration.properties` holds them in.
///
/// Two-space indentation with an eight-space margin, which is where those
/// properties sit in that file, so the text pastes in as it stands.
pub fn vscode_lint_settings() -> String {
let mut entries: Vec<String> = Vec::new();
for (i, severity) in Severity::ALL.into_iter().enumerate() {
entries.push(severity_entry(severity, 10 + i as u32));
}
let mut order = 20;
for severity in Severity::ALL {
for rule in all_rules().into_iter().filter(|rule| rule.severity() == severity) {
entries.push(rule_entry(rule, order));
order += 1;
}
}
format!("{{\n{}\n}}\n", entries.join(",\n"))
}
/// One class's master switch.
fn severity_entry(severity: Severity, order: u32) -> String {
let description = format!(
"Run the **{word}** lint rules — {what}. Turning this off silences the whole class; \
a per-rule toggle below still has the last word, and \
`#lucisv.lint.ignore#` still removes a rule whatever else says. \
Takes effect immediately — every open file is re-checked.",
word = severity.as_str(),
what = severity.describes(),
);
format!(
" \"{id}\": {{\n\
\x20 \"type\": \"boolean\",\n\
\x20 \"default\": true,\n\
\x20 \"order\": {order},\n\
\x20 \"markdownDescription\": {description}\n\
\x20 }}",
id = severity_setting(severity),
description = json_string(&description),
)
}
/// One rule's toggle.
fn rule_entry(rule: &'static dyn Rule, order: u32) -> String {
let description = format!(
"**{severity}** — {summary}. {default}",
severity = rule.severity().as_str(),
summary = rule.summary(),
default = default_sentence(rule),
);
format!(
" \"{id}\": {{\n\
\x20 \"type\": \"string\",\n\
\x20 \"enum\": [{choices}],\n\
\x20 \"enumDescriptions\": [\n\
\x20 {leave},\n\
\x20 \"Always run this rule.\",\n\
\x20 \"Never run this rule.\"\n\
\x20 ],\n\
\x20 \"default\": \"default\",\n\
\x20 \"order\": {order},\n\
\x20 \"markdownDescription\": {description}\n\
\x20 }}",
id = rule_setting(rule),
choices = RULE_CHOICES.iter().map(|c| json_string(c)).collect::<Vec<_>>().join(", "),
leave = json_string(&format!("Leave it as it ships: {}", default_sentence(rule))),
description = json_string(&description),
)
}
/// How a rule's own default is said in one sentence — the same three cases
/// [`crate::rules_markdown`]'s Default column spells.
fn default_sentence(rule: &dyn Rule) -> String {
match (rule.default_on(), rule.needs_workspace()) {
(true, _) => "On by default.".to_string(),
(false, true) => "On where lucisv can see the project.".to_string(),
(false, false) => "Off by default.".to_string(),
}
}
/// A JSON string literal. Hand-rolled, as the CLI's JSON output is: this crate
/// depends on `vlog_parser` and `std` alone, and a serialization framework for
/// one string shape is not a trade worth making.
fn json_string(text: &str) -> String {
let mut out = String::with_capacity(text.len() + 2);
out.push('"');
for c in text.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_rule_and_every_class_gets_an_entry() {
let json = vscode_lint_settings();
for severity in Severity::ALL {
assert!(json.contains(&format!("\"{}\"", severity_setting(severity))), "{severity:?}");
}
for rule in all_rules() {
let id = rule_setting(rule);
assert_eq!(json.matches(&format!("\"{id}\"")).count(), 1, "{id}");
assert!(
json.contains(&format!("**{}** — {}.", rule.severity().as_str(), rule.summary())),
"{id}: description",
);
}
}
/// The toggles are ordered worst class first, then by name — which is how
/// the Settings UI groups them.
#[test]
fn the_order_numbers_group_by_severity_then_name() {
let json = vscode_lint_settings();
let mut expected: Vec<String> = Vec::new();
for severity in Severity::ALL {
let mut names: Vec<&str> = all_rules()
.into_iter()
.filter(|rule| rule.severity() == severity)
.map(|rule| rule.name())
.collect();
names.sort_unstable();
expected.extend(names.into_iter().map(str::to_string));
}
let found: Vec<String> = json
.lines()
.filter_map(|line| line.trim().strip_prefix("\"lucisv.lint.rules."))
.filter_map(|rest| rest.split('"').next().map(str::to_string))
.collect();
assert_eq!(found, expected);
}
#[test]
fn json_strings_are_escaped() {
assert_eq!(json_string("a\"b\\c"), "\"a\\\"b\\\\c\"");
assert_eq!(json_string("em — dash"), "\"em — dash\"", "UTF-8 passes through");
}
}
@@ -3,6 +3,7 @@ module m;
always_comb begin
case (s)
//^ 5 case-missing-default
//^ 5 incomplete-assignment
0: x = 1;
endcase
end
@@ -33,6 +34,7 @@ module m;
always_comb begin
// lucisv: waive case-missing-default
case (s)
//^ 5 incomplete-assignment
0: x = 1;
endcase
end
@@ -0,0 +1,83 @@
# a packed dimension that counts upwards
#select packed-dimensions-range-ordering
module m;
logic [0:7] up;
//^ 9 packed-dimensions-range-ordering
logic [0:WIDTH-1] also_up;
//^ 9 packed-dimensions-range-ordering
endmodule
====
# the decreasing form, a one-bit range, and an unpacked array
#select packed-dimensions-range-ordering
module m;
logic [7:0] down;
logic [WIDTH-1:0] symbolic;
logic [0:0] one_bit;
logic [LO:HI] unknowable;
logic ascending_array [0:3];
endmodule
====
# a negative constant written into a dimension
#select forbid-negative-array-dim
module m;
logic [-1:0] v;
//^ 10 forbid-negative-array-dim
logic q [-1];
//^ 12 forbid-negative-array-dim
endmodule
====
# a subtraction is not a negative literal
#select forbid-negative-array-dim
module m;
logic [WIDTH-1:0] v;
logic q [DEPTH];
parameter int P = -1;
endmodule
====
# an untyped formal is a one-bit logic
#select explicit-function-task-parameter-type
module m;
function void f(input a);
//^ 19 explicit-function-task-parameter-type
endfunction
endmodule
====
# a continuation formal inherits the type in force
#select explicit-function-task-parameter-type
module m;
function void f(input int a, b);
endfunction
task t(input logic [7:0] c);
endtask
endmodule
====
# a positional connection list of more than one port
#select module-port
module m;
sub u_sub (a, b, c);
//^ 7 module-port
endmodule
====
# named connections, a wildcard, and a single positional one
#select module-port
module m;
sub u1 (.a(x), .b(y));
sub u2 (.*);
sub u3 (a);
sub u4 ();
endmodule
====
# more than one positional parameter override
#select module-parameter
module m;
sub #(8, 4) u_sub ();
//^ 3 module-parameter
endmodule
====
# named overrides, and a single positional one
#select module-parameter
module m;
sub #(.Width(8), .Depth(4)) u1 ();
sub #(8) u2 ();
sub u3 ();
endmodule
@@ -0,0 +1,82 @@
# an end label that names another block is a compile error
#select mismatched-labels
module m;
always_comb begin : fetch
x = 1;
end : decode
//^ 9 mismatched-labels
endmodule
====
# a footer label on a block that has none is one too
#select mismatched-labels
module m;
always_comb begin
x = 1;
end : blk
//^ 9 mismatched-labels
endmodule
====
# a matching pair, and a footer that was simply not written
#select mismatched-labels
module m;
always_comb begin : blk
x = 1;
end : blk
always_comb begin : other
y = 1;
end
endmodule : m
====
# every construct with a footer label is checked
#select mismatched-labels
package p;
function void f();
endfunction : g
//^ 17 mismatched-labels
endpackage : q
//^ 14 mismatched-labels
====
# two declarations of one name in one scope
#select duplicate-declaration
module m;
logic a;
logic a;
//^ 9 duplicate-declaration
endmodule
====
# a non-ANSI port is completed by its body declarations, three times legally
#select duplicate-declaration
module m (clk);
input clk;
logic clk;
endmodule
====
# conditional arms never coexist, so they are not duplicates
#select duplicate-declaration
module m;
`ifdef X
logic b;
`else
logic b;
`endif
endmodule
====
# a block-local hiding a module signal is shadowing, not duplication
#select instance-shadowing
module m;
logic count;
always_comb begin : blk
logic count;
//^ 11 instance-shadowing
count = 1'b0;
end
endmodule
====
# two modules may each declare the same name
#select instance-shadowing
module a;
logic data;
endmodule
module b;
logic data;
endmodule
@@ -0,0 +1,61 @@
# a literal wider than its declared width is truncated
#select truncated-numeric-literal
module m;
assign x = 4'hFFF;
//^ 14 truncated-numeric-literal
endmodule
====
# leading zeros, an exact fit and an all-unknown literal are all fine
#select truncated-numeric-literal
module m;
assign a = 8'h0FF;
assign b = 32'hdead_beef;
assign c = 3'hz;
assign d = 7'hzz;
endmodule
====
# an unsized literal has no width to overflow
#select truncated-numeric-literal
module m;
assign x = 'hffff_ffff;
endmodule
====
# a short binary literal is padded to its declared width
#select undersized-binary-literal
module m;
assign x = 8'b1;
//^ 14 undersized-binary-literal
endmodule
----
module m;
assign x = 8'b00000001;
//^ 14 undersized-binary-literal
endmodule
====
# an unknown extends itself rather than zero-filling
#select undersized-binary-literal
module m;
assign x = 4'bz;
//^ 14 undersized-binary-literal
endmodule
----
module m;
assign x = 4'bzzzz;
//^ 14 undersized-binary-literal
endmodule
====
# zero is exempt, as it is in verible: `lint_zero` defaults off
#select undersized-binary-literal
module m;
assign a = 2'b0;
assign b = 32'b0;
assign c = 4'b1010;
endmodule
====
# only binary is judged, and only when the literal says its width
#select undersized-binary-literal
module m;
assign a = 8'h1;
assign b = 8'd1;
assign c = 'b1;
endmodule
@@ -0,0 +1,98 @@
# a control statement whose whole body is a `;`
#select suspicious-semicolon
module m;
always_comb begin
if (ready);
//^ 15 suspicious-semicolon
while (busy);
//^ 17 suspicious-semicolon
end
endmodule
====
# a real body, and the way to write a deliberately empty one
#select suspicious-semicolon
module m;
always_comb begin
if (ready) x = 1;
forever begin end
;
end
endmodule
====
# a void cast around something that is not a call discards nothing
#select void-cast
module m;
initial begin
void'(x);
//^ 5 void-cast
void'(f());
void'(obj.randomize() with { a inside {[0:3]}; });
end
endmodule
====
# defparam reaches into another scope
#select forbid-defparam
module m;
sub u ();
defparam u.WIDTH = 8;
//^ 3 forbid-defparam
endmodule
====
# the named override is what the rule wants instead
#select forbid-defparam
module m;
sub #(.WIDTH(8)) u ();
endmodule
====
# the forbidden system tasks, and the replacements beside them
#select invalid-system-task-function
module m;
initial begin
a = $random();
//^ 9 invalid-system-task-function
b = $psprintf("%0d", a);
//^ 9 invalid-system-task-function
c = $urandom();
d = $sformatf("%0d", c);
end
endmodule
====
# a plusarg should be read as a value, not tested for by prefix
#select plusarg-assignment
module m;
initial begin
if ($test$plusargs("fast")) go = 1;
//^ 9 plusarg-assignment
if ($value$plusargs("speed=%0d", speed)) go = 1;
end
endmodule
====
# a variable written only under an if infers a latch
#select incomplete-assignment
module m;
always_comb begin
if (en) y = a;
//^ 5 incomplete-assignment
end
endmodule
====
# a default assignment before the branch is the repair
#select incomplete-assignment
module m;
always_comb begin
y = 1'b0;
if (en) y = a;
end
endmodule
====
# a case with a default writes every arm, so the if after it is covered
#select incomplete-assignment
module m;
always_comb begin
case (s)
0: y = a;
default: y = b;
endcase
if (en) y = 1'b1;
end
endmodule
+14 -2
View File
@@ -24,7 +24,7 @@ use vlog_parser::ast::*;
use vlog_parser::span::TextRange;
use vlog_parser::token::is_keyword;
use crate::model::{Scope, ScopeId, ScopeKind, Symbol, SymbolId, SymbolKind};
use crate::model::{Duplicate, Scope, ScopeId, ScopeKind, Symbol, SymbolId, SymbolKind};
/// A recorded use, waiting for pass two to say what it names.
pub(crate) struct Pending {
@@ -129,6 +129,9 @@ pub(crate) struct Binder<'a> {
pub(crate) scopes: Vec<Scope>,
pub(crate) symbols: Vec<Symbol>,
pub(crate) pending: Vec<Pending>,
/// Every name a scope bound a second time, in the order they were
/// written. Purely a record — see [`Duplicate`].
pub(crate) duplicates: Vec<Duplicate>,
deferred: Vec<Deferred<'a>>,
/// While a `randomize() with { ... }` block is being bound: the head of
/// the object being randomized, so a bare name inside the block is
@@ -159,6 +162,7 @@ impl<'a> Binder<'a> {
scopes: vec![file],
symbols: Vec::new(),
pending: Vec::new(),
duplicates: Vec::new(),
deferred: Vec::new(),
with_head: None,
bind_target: None,
@@ -201,7 +205,15 @@ impl<'a> Binder<'a> {
if name.is_empty() {
return None;
}
if self.scopes[scope.0 as usize].names.contains_key(name) {
if let Some(&first) = self.scopes[scope.0 as usize].names.get(name) {
self.duplicates.push(Duplicate {
name: name.to_string(),
name_span,
decl_span,
kind,
first,
scope,
});
self.use_name(scope, name, name_span, Target::Lexical);
return None;
}
+26 -4
View File
@@ -28,8 +28,8 @@ mod workspace;
pub use facts::{record_path, FACTS_FORMAT};
pub use model::{
DocumentSymbol, Import, MemberSite, Reference, ReferenceId, Resolution, Scope, ScopeId,
ScopeKind, Symbol, SymbolId, SymbolKind,
DocumentSymbol, Duplicate, Import, MemberSite, Reference, ReferenceId, Resolution, Scope,
ScopeId, ScopeKind, Symbol, SymbolId, SymbolKind,
};
pub use workspace::{
index_order, resolve_external, DeclLines, DeclPositions, DeclSite, Def, Definition,
@@ -54,6 +54,9 @@ pub struct Semantics {
symbol_positions: Vec<(TextRange, SymbolId)>,
/// Non-empty reference-name spans, sorted by start for cursor lookup.
reference_positions: Vec<(TextRange, ReferenceId)>,
/// Every name a scope bound twice, in source order. Recorded by the
/// binder and judged by nobody here — see [`Duplicate`].
duplicates: Vec<Duplicate>,
/// Every symbol id, sorted by the name it declares, ties in declaration
/// order — so looking a name up is a binary search rather than a walk of
/// every symbol. A side table rather than a `HashMap<String, _>` because
@@ -75,7 +78,7 @@ pub fn analyze(file: &SourceFile, src: &str) -> Semantics {
// only guaranteed to exist once the whole file is bound.
binder.bind_deferred();
let bind::Binder { mut scopes, symbols, pending, .. } = binder;
let bind::Binder { mut scopes, symbols, pending, duplicates, .. } = binder;
link_imports(&mut scopes, &symbols);
let mut references = Vec::with_capacity(pending.len());
@@ -120,7 +123,16 @@ pub fn analyze(file: &SourceFile, src: &str) -> Semantics {
// would have seen, which is what makes swapping the two an identity.
let mut by_name: Vec<SymbolId> = (0..symbols.len() as u32).map(SymbolId).collect();
by_name.sort_by(|a, b| symbols[a.0 as usize].name.cmp(&symbols[b.0 as usize].name));
Semantics { scopes, symbols, references, uses, symbol_positions, reference_positions, by_name }
Semantics {
scopes,
symbols,
references,
uses,
duplicates,
symbol_positions,
reference_positions,
by_name,
}
}
/// Point every import at the package it names, when this file declares it.
@@ -153,6 +165,16 @@ impl Semantics {
&self.references
}
/// Every name a scope bound a second time, in source order.
///
/// Additive, and read by one caller: the `duplicate-declaration` lint.
/// Nothing else in the crate consults it, and no existing answer changed
/// when it was added — a redeclaration is still a reference to the first
/// declaration everywhere it was one before.
pub fn duplicates(&self) -> &[Duplicate] {
&self.duplicates
}
/// The file scope.
pub fn file_scope(&self) -> ScopeId {
ScopeId(0)
+31
View File
@@ -155,6 +155,37 @@ pub struct Symbol {
pub child_scope: Option<ScopeId>,
}
/// A name a scope bound **twice**: the second declaration, and the first one
/// that already held the name.
///
/// The binder's rule is that a redeclaration becomes a *reference* to the
/// first declaration rather than a second symbol — which is exactly what makes
/// a non-ANSI port's body declaration attach to its header port, and an
/// out-of-body method definition attach to its prototype. That is the right
/// answer for hover, rename and go-to-definition, and it means the fact that a
/// second declaration was written is not otherwise recoverable from the
/// tables. This records it, so a caller who cares (the `duplicate-declaration`
/// lint) can ask; every existing caller is unaffected.
///
/// **Recorded, not judged.** Several of these are perfectly legal, and telling
/// which is the caller's business: see
/// `docs/features/linter-expansion-1/README.md`.
#[derive(Debug, Clone)]
pub struct Duplicate {
/// The name declared twice.
pub name: String,
/// Byte range of the **second** declaration's name, as written.
pub name_span: TextRange,
/// Byte range of the whole second declaration.
pub decl_span: TextRange,
/// What kind of declaration the second one is.
pub kind: SymbolKind,
/// The declaration that already held the name.
pub first: SymbolId,
/// The scope both were written in.
pub scope: ScopeId,
}
/// What a [`Reference`] turned out to name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Resolution {
+9 -6
View File
@@ -60,7 +60,7 @@ request.
| M6 | ~~Indexed hierarchical `bind` target (`bind top.gen[0].u_core …`).~~ | bind README non-goals. | Delivered by TODO §26: `BindDirective::target` is a `Vec<PathSegment { name, span, index }>` and `at_bind_directive` steps over one `[…]` per segment. Shipped with the §2.9-15 semantics in the same round — a lone target resolves as a module or interface, a connection's port half against the bound-in module and its expression half in the target's scope. Real but unmeasured: still zero corpus and opentitan hits. |
| M7 | Semantic lints (`unused-signal`, `undriven-net`, `multiply-driven`) ship **off by default**. | linter-core / semantic-lints READMEs; blocked on topo §2.9-6 (workspace-wide "does any file mention this name"). | These are the lints RTL engineers want most; the index now has reference postings and `files_spelling`, so §2.9-6 is closer than when filed. |
| M8 | ~~Lint rules do not descend into verbatim regions~~ — **closed at 0.33.0 for what parses**, by construction: the rules read the reference table, and a structured assertion contributes ordinary references to it. A `signals.rs` `opaque_span` remains only for a region that fell back. | assertions / clocking-wave / sva-bodies READMEs. | Same root as C1; resolved with it. |
| M9 | Statement-level format fences (inside `always`, case items, port lists) and fences inside class bodies (topo §2.9-3). | format-fences / classes READMEs. | Users protect hand-aligned tables inside procedural blocks; DV users protect them in classes. |
| ~~M9~~ | ~~Statement-level format fences (inside `always`, case items, port lists) and fences inside class bodies (topo §2.9-3).~~ — **closed at 0.34.0+ by TODO §31.** Class bodies and every statement *list* (`begin`…`end`, `fork`…`join*`, function/task bodies, `initial`/`always`/`final` bodies, a `case` item's block body, a statement fragment) are fenceable scopes; `--lines` still loses to a fence. Two of the three named places stay out, with reasons: port/parameter lists and `case` **label** lists print mid-line inside a `Group`, where `Doc::Verbatim` (column-0, break-forcing) cannot stand — that wants a new printer primitive, not a scan arm. Measured on OpenTitan, which has 9 fenced files: four now keep their fenced bytes, including a 110-line class-body region. | statement-fences README; format-fences / classes / shared-fence-filter READMEs amended. | Users protect hand-aligned tables inside procedural blocks; DV users protect them in classes. |
| M10 | Error recovery does not reach headers and lists (port lists, parameter lists, for-headers) — a half-typed port list yields a garbage tree. | error-recovery README (QA-confirmed). | Editing experience: diagnostics cascade while typing a header. |
| M11 | Anonymous aggregate members (`enum {A,B} x;`) not symbols (topo §2.9-13); cast type `state_t'(0)` records no reference. | overlay-promotion README; probe: enum *typedef'd* members do work. | Partial: named enums navigate, anonymous ones do not. |
| M12 | No `lint` key in `lucisv.toml` (topo §2.9-4); no `--rules-doc`. | four READMEs. | Config surface, not language — but it gates per-project rule selection. |
@@ -149,11 +149,14 @@ 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: M9 statement-level
and class-body format fences
(§2.9-3); M10 error recovery inside headers and lists; the second half of
quiet). What the tables above still leave open, by weight: M10 error recovery
inside headers and lists; the second half of
M12 (`--rules-doc`, §2.9-5); L3, L6, L9 and L10. M13's small
interface/DPI grammar arms are closed (TODO §30) — with one narrowing
recorded there: a single `import` may carry one prototype, not a
comma-separated list of them. The three stale READMEs named under the
order were reconciled in the 0.33.0 documentation pass.
comma-separated list of them. M9's format fences are closed too (TODO §31,
§2.9-3), with the same kind of narrowing recorded in its row: the two
mid-line list positions (port/parameter lists, `case` label lists) stay
inert, because a column-0 verbatim slice has no place inside a `Group`. The
three stale READMEs named under the order were reconciled in the 0.33.0
documentation pass.
+13 -4
View File
@@ -184,7 +184,14 @@ indexed, hovered or navigable.** That is a real LSP gap, not an oversight, and
it is the natural next round for that crate. **Delivered 2026-08-19 by
`class-semantics`** — see `docs/features/class-semantics/README.md`.
**Requested of `vlog_formatter::fence` (out of this feature's scope):**
**Requested of `vlog_formatter::fence` (out of this feature's scope) —
DELIVERED 2026-09-03 by TODO §31 / `docs/features/statement-fences`.**
`scan_nested` now carries the arm this section asked for verbatim
(`ItemKind::Class(c) => scan_scope(src, &c.items, &c.dangling, out)`), plus
the statement scopes a class's methods hold, so the probe below is now
formatted exactly as its module twin is and the asymmetry the lead note
describes is closed. The original request, kept for the record:
`scan_nested` enumerates the item scopes a fence can live in — module,
package, generate region, generate `if`/`for`/`case` — and ends in a `_ => {}`
catch-all, so a class body is not scanned. Probed and confirmed:
@@ -332,9 +339,11 @@ non-zero verification-error count.
- [ ] **Not done, deliberately:** canonical layout for constraint and
covergroup bodies. Two grammars, no layout convention worth inventing,
and the verbatim path is corruption-proof by construction.
- [ ] **Not done, out of scope:** fences inside class bodies (`fence.rs`, one
arm) and lint-rule coverage of class members (`visit.rs`, one arm).
Both filed under Handshakes.
- [x] **Fences inside class bodies** (`fence.rs`, one arm) — filed under
Handshakes, delivered 2026-09-03 by TODO §31
(`docs/features/statement-fences/README.md`).
- [ ] **Not done, out of scope:** lint-rule coverage of class members
(`visit.rs`, one arm). Filed under Handshakes.
- [ ] **Not done:** `` `uvm_field_int (x, y)`` — a macro invocation with a
space before its `(`. Ten of the 70 still-blocked ex-`extends` files die
on this, and it is the documented `macro-items` gap (their Assumptions,
+64 -36
View File
@@ -36,20 +36,27 @@ Consequences, all deliberate and all tested:
- **Block comments are not fences.** `/* verilog_format: off */` is an
ordinary comment. Restricting fences to `//` keeps a fence a whole-line
thing and keeps the region boundaries at line granularity.
- **A fence must be a leading comment**, i.e. it must start a line (nothing
but whitespace, or another comment, before it on that line). A comment on
the same line as preceding *code* is attached to that code as *trailing*
trivia, and `Meta.trailing` is an `Option<String>` with no span — there is
nothing to splice from. So `wire a; // lucisv: off` is an ordinary comment.
See Handshakes for the parser change that would lift this.
- **A fence must be a leading comment that begins the content of its line**
(nothing but whitespace, or finished block comments, before it there). Two
shapes fall outside that. A comment on the same line as preceding *code* is
usually attached to that code as *trailing* trivia, so `wire a; //
lucisv: off` is an ordinary comment — see Handshakes for the parser change
that would lift this. But not always: after a `begin`, or after a module
header's `;`, the parser hands such a comment to the **next** node as a
*leading* one, mid-line. `fence::opens_line` refuses those too, which is
what makes the rule above true rather than aspirational. (It was not, until
`statement-fences` — until then `module m; // lucisv: off` opened a region
whose first line was sliced from mid-line. Fixed there, with the case
pinned; the block-comment exception below is deliberate and unchanged.)
- The alias and the long form are interchangeable: an `off` in either
spelling is closed by an `on` in either spelling.
## Semantics
Fences select whole **items** (module items, package items, top-level items),
Verible-style. Think of an item list as a flat stream of *units*: each item's
leading comments, then the item's own code (its `(* … *)` attributes and
Fences select whole **items** (module items, package items, class members,
top-level items) and, since `statement-fences`, whole **statements**,
Verible-style. Think of a list as a flat stream of *units*: each element's
leading comments, then the element's own code (its `(* … *)` attributes and
trailing comment included), and finally the scope's dangling comments.
- A region **opens** at the first `off` fence in that stream and **closes**
@@ -68,44 +75,56 @@ trailing comment included), and finally the scope's dangling comments.
open `off`; both are just bytes inside the region, or an ordinary comment.
Fences do not nest and do not count.
- **An unmatched `off` runs to the end of its scope** — the last byte of the
containing item list, which is the end of the last item (its same-line
containing list, which is the end of the last element (its same-line
trailing comment included) or of the last dangling comment, whichever comes
last. At file scope that is the last byte of content in the file. It does
**not** leak into the enclosing scope: an `off` inside a module body is
closed by the module's `endmodule` at the latest, and an `on` written after
`endmodule` belongs to the file scope and cannot close it.
closed by the module's `endmodule` at the latest, an `off` inside a
`begin`…`end` by that block's `end`, and an `on` written after the closing
keyword belongs to the enclosing scope and cannot close it.
- **Fences never cross a scope boundary**, which is what keeps a region
aligned with item boundaries: a region can never end in the middle of an
item, so the formatter never has to print half of one.
aligned with element boundaries: a region can never end in the middle of an
item or a statement, so the formatter never has to print half of one.
### Out of scope this round: statement-level fences
A fence inside an item body — between two statements in an `always` block,
between two case items, inside a port list — **has no effect**. It is
formatted as an ordinary comment. Only `Item` lists are fenceable:
### The fenceable scopes
| fenceable scope | |
|---|---|
| file | `SourceFile.items` + `dangling` |
| package body | `ItemKind::Package` |
| module body | `Module.items` + `dangling` |
| module / interface / program body | `Module.items` + `dangling` |
| class body | `ClassDecl.items` + `dangling` |
| `generate` region | `ItemKind::GenerateRegion` |
| generate `begin`…`end` | `GenBlock` with `is_block` |
| `begin`…`end` | `StmtKind::Block` |
| `fork`…`join`/`join_any`/`join_none` | `StmtKind::ForkJoin` |
| function / task body | `FunctionDecl.stmts`, `TaskDecl.stmts` + `dangling` |
| statement fragment | `Fragment::Statements` |
Not fenceable: statement lists (`begin`/`end`, `fork`, function/task bodies),
case-item lists, port/parameter/connection lists, and the single-item body of
a bodyless `if (X) item;` in a generate (there is no list for a fence to end
in, and the formatter lays that item out inside a `Group`).
The statement scopes are reached from `ItemKind::{Always, Initial, Final,
Function, Task}` and from every compound statement that can hold a block —
`if`/`else`, `case`/`randcase` item bodies, the loops, a timing control, a
`wait`, an immediate `assert`, a labelled statement. Details, and the
statement half of the scan, in `docs/features/statement-fences/README.md`.
**Still not fenceable**, each for a reason recorded in that README:
port/parameter/connection lists and case-item *label* lists (their elements
print mid-line inside a `Group`, where a column-0 `Doc::Verbatim` cannot go);
the single-element body of a bodyless `if (X) …`, in a generate or in a
statement (there is no list for a fence to end in); same-line trailing fences;
and `PropSeqDecl.locals`, the one `Vec<Item>` not printed through `item_seq`.
The interaction worth knowing: an `off` at item level whose matching `on` was
written inside a *statement* is an unmatched `off`, so it runs to the end of
the item list rather than stopping at the `on`. That errs toward *more*
verbatim text, never toward reformatting something the author fenced off.
the item list rather than stopping at the `on` — and that `on`, in the
statement scope, is a stray `on`, i.e. an ordinary comment. That errs toward
*more* verbatim text, never toward reformatting something the author fenced
off.
## Splice mechanics
`fence::collect(src, &file)` walks the item scopes once, before any
formatting, and returns a sorted, non-overlapping `Vec<Region>`:
`fence::collect(src, &file)` walks the scopes once, before any formatting,
and returns a sorted, non-overlapping `Vec<Region>`:
```rust
struct Region { fence: usize, start: usize, end: usize }
@@ -192,11 +211,14 @@ either, so no stray blank lines appear where the region swallowed items.
- `Comment.span` / `Comment.text` / `Comment.blank_before` — the fence
matcher and the region boundaries.
- `Item.span` (code extent, attributes in, comments out) — region membership
for an item's code.
- `Item.span` / `Stmt.span` (code extent, attributes in, comments out) —
region membership for an element's code.
- The item-scope shapes: `SourceFile{items,dangling}`, `Module`,
`ItemKind::Package`, `ItemKind::GenerateRegion`, `GenBlock`, `GenIf`,
`GenFor`, `GenCase`.
`GenFor`, `GenCase`, `ClassDecl`.
- The statement-scope shapes, added by `statement-fences`:
`StmtKind::Block`, `StmtKind::ForkJoin`, `FunctionDecl`/`TaskDecl`
`stmts` + `dangling`, and `Fragment::Statements`.
Nothing in `crates/vlog_parser` was changed, and nothing new is required of
it for this feature to work as documented.
@@ -233,8 +255,11 @@ column 0, newlines included. It is treated as containing a hard line
(`contains_hard_line`, `Printer::fits`), so it can never be measured for a
flat layout. The one contract it relies on: it is only ever emitted right
after a line break or at the very start of the output, which is where the
"strip the indentation just written" step is correct. Both current emitters
(`Fmt::leading_comments`, `Fmt::dangling`) satisfy that.
"strip the indentation just written" step is correct. Every emitter satisfies
that: `Fmt::leading_comments`, `Fmt::dangling`, `Fmt::file`, `item_docs`
(through `item_seq`, whose callers all break first) and — since
`statement-fences` — `stmt_docs` (through `stmt_seq`, likewise, the statement
fragment at the start of the output being the one "or".)
## Status / TODO
@@ -255,9 +280,12 @@ after a line break or at the very start of the output, which is where the
must reject.
- [x] README.md Style section mentions fences.
- [x] TODO.md §2 fences item checked.
- [ ] **Not done, deliberately:** statement-level fences (documented above).
- [ ] **Not done:** same-line (`trailing`-trivia) fences — blocked on a
parser change, see Handshakes.
- [x] **Statement-level fences and class-body fences** — delivered
2026-09-03 by `docs/features/statement-fences/README.md` (TODO §31,
coverage_gaps M9, topo §2.9-3). The scope table above is the current
answer; this feature's own code was extended, not replaced.
- [ ] **Not done:** same-line (`trailing`-trivia) fences — the parser change
landed (see Handshakes), the rule it would need has not been decided.
## Work log
+618
View File
@@ -0,0 +1,618 @@
# linter expansion, wave 1 (TODO §33)
## Goal
Grow the linter from 17 rules toward what Verible's 62 cover, and give a user
a way to say which of them they want. Three things, in one lane because they
touch the same registry: a **severity** on every rule (`error` / `warning` /
`style`) carried end to end — into `--select`/`--ignore`, the CLI diagnostic
line, the JSON output, the editor's squiggle colour and the generated rule
reference; **per-rule toggles in VS Code**, generated from the registry so a
rule cannot ship without its switch, with one documented precedence for the
five ways a rule can be turned on or off; and the **rules that matter first** —
the ones that say the code would not compile (Error) and the ones that say it
does not mean what it says (Warning). The Style family and per-rule options are
wave 2 (§34). 17 rules → **36**.
## Assumptions
- **Severity is a property of the rule, not of the finding.** Every violation a
rule reports is in the same class, so the runner stamps it
(`vlog_linter::lint`) rather than each `check` remembering to. A rule whose
findings would want two classes is two rules.
- **`Error` means "a tool would refuse this file", and a rule may only claim
it when it is certain.** Every Error-class rule added here is silent whenever
the workspace cannot answer: a file that did not fully parse, a module that
is not indexed or is indexed twice, a name a macro produces, a fragment
written to be `` `include``d. A wrong accusation in this class is worse than
a hundred missed ones, and the opentitan census below is what turned that
sentence into code — every Error rule's first measurement found false
positives, and each one became an exclusion with a test.
- **A severity word is not a rule name.** `error`, `warning` and `style` are
accepted wherever a rule name is, and
`registry::every_rule_has_a_severity_and_no_name_shadows_a_class` pins that
no rule may be named after a class.
- **The editor's classes map to LSP severities 1/2/3.** Style is
`INFORMATION`, not `HINT`: a hint is invisible in most themes, which would
make the style rules look broken rather than quiet.
- **The VS Code settings are generated, never hand-written.** The generator is
the registry; the drift test in `lucisv_server` is what makes that true after
the next rule is added.
- **A file that does not parse gets no structural opinion.** `LintContext::
parsed_cleanly` is the shared guard: error recovery unwinds out of the
construct it failed in, so declarations that followed are bound in whatever
scope recovery landed in. Three rules ask it before saying anything.
- **Verible's defaults are matched unless §33 says otherwise**, options
included: `undersized-binary-literal` exempts a zero literal because
Verible's `lint_zero` defaults off, and checks binary only because its `oct`
and `hex` default off. Four rules Verible ships **off** are on here by §33's
instruction: `mismatched-labels`, `suspicious-semicolon`,
`instance-shadowing`, `forbid-negative-array-dim`.
## Handshakes
**Consumed**
- `vlog_parser::ast` — unchanged. The new syntactic rules read the same nodes
the existing ones do, through `crate::visit` and the new `crate::decls`.
- `vlog_semantic::words::harvest_raw` — already public; `undeclared-identifier`
reads it for the "a macro writes this name down" exclusion.
- `vlog_semantic::WorkspaceIndex::{units, members_of}` — already public; the
server answers `module_interface` from them.
**Requested and taken — `vlog_semantic`, additive (flag for the lead)**
`duplicate-declaration` could not be answered from the existing tables: the
binder turns a redeclaration into a *reference* to the first declaration
(which is what makes a non-ANSI port's body declaration attach to its header
port), so the fact that a second declaration was written is not recoverable.
As §33.2 anticipated, one additive query was added:
- `vlog_semantic::Duplicate` — name, both spans, kind, the first symbol, the
scope.
- `Binder::duplicates` records one on the path that already existed
(`declare`'s "already bound" arm); nothing else in that function changed.
- `Semantics::duplicates() -> &[Duplicate]`.
**No `FACTS_FORMAT` change**: nothing was added to `FileFacts`, nothing is
persisted, and no existing answer moved — a redeclaration is still a reference
to the first declaration everywhere it was one before. `vlog_semantic`'s own
tests are unchanged and green.
**Requested and taken — `lucisv_server/src/server/notification.rs` (flag for
the lead)**
Two lines. `apply_settings` republishes every open file when the lint
*selection* changes, and compares it through a private `lint_selection()` that
cloned `lint_select` and `lint_ignore`. §33.1 requires the same republish when
a class switch or a per-rule toggle changes, so that function now calls the new
`settings::lint_selection(&ClientSettings)`, which returns all four. The file
is not on this lane's ownership list; the change is mechanically required by
§33.1's "changing any of them republishes every open file", cannot collide with
the §31 lane (different crate), and is called out here and in the lane report
so the lead can rule on it at merge.
**Promised (new public surface of `vlog_linter`)**
- `Severity` (`Error` / `Warning` / `Style`) with `as_str`, `from_name`,
`describes` and `ALL`.
- `Rule::severity(&self) -> Severity` — **no default**; every rule states one.
*A consumer implementing `Rule` outside this crate must add it.* No such
consumer exists.
- `Violation::severity` — set by `lint`, not by the reporting rule.
- `rules_named(&str) -> Option<Vec<&'static dyn Rule>>`; `select_rules` now
accepts severity words on either list.
- `LintContext::parsed_cleanly()`, `LintContext::module_interface()`.
- `MentionOracle::module_interface(&str) -> Option<ModuleInterface>` — a
**defaulted** method returning `None`, so every existing implementor keeps
compiling and answers "I cannot say", which leaves the two rules that ask it
silent.
- `ModuleInterface { ports, parameters }` with `has_port` / `has_parameter`.
- `module_interfaces(&SourceFile)` — the CLI's reading of a parse.
- `ParsedSource::file()`.
- `vscode_lint_settings()`, `rule_setting`, `severity_setting`,
`RULE_CHOICES`.
- `rules_markdown()` gains a Severity column and groups its sections by class.
**Promised (CLI)** — text output is
`FILE:LINE:COL: error|warning|style: message [rule]`; JSON gains `"severity"`.
Exit codes unchanged.
**Promised (server)** — a lint diagnostic's `severity` is its rule's class;
`lint::enabled_rules(settings, has_oracle)` is the one ladder.
## Status / TODO
- [x] 33.0 `Severity` on every rule; select/ignore by severity; CLI text/JSON;
editor severities; `--rules-doc` grouped
- [x] 33.1 package.json toggles generated + drift test; `enabled_rules`
precedence pinned; republish on change
- [x] 33.2 Error rules: mismatched-labels, duplicate-declaration,
undeclared-identifier (measured; default decided by the count),
unknown-port, unknown-parameter
- [x] 33.3 Warning rules: the thirteen listed, each with tests and an
opentitan count
- [x] 33.4 docs; measurements table below
- [x] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
byte-identical; opentitan read-only census + timing
- [ ] QA
## Measurements
**Corpus** = lucisv's 860-file corpus (`corpus/`). **opentitan** = a read-only
`lucisv check hw` over 3 975 files at `/Users/guoliangchen/repo/opentitan`
(`git status --porcelain` after every run showed only the three files that were
already modified before this lane started). "Sample" is findings read and
classified, out of ten where there were ten.
| Rule | Sev | Default | Verible equivalent (its default) | Corpus | opentitan | Sample: true / false / judgment |
|---|---|---|---|---:|---:|---|
| `mismatched-labels` | error | on | `mismatched-labels` (off) → **on** | 0 | 1 | 1 / 0 / 0 |
| `duplicate-declaration` | error | on | none | 0 | 0 | — (18 before the exclusions, all false) |
| `undeclared-identifier` | error | on (project) | none | 5 | 5 | 5 / 0 / 0 |
| `unknown-port` | error | on (project) | none | 0 | 40 | 6 / 0 / 0 |
| `unknown-parameter` | error | on (project) | none | 1 | 4 | 4 / 0 / 0 |
| `forbid-defparam` | warning | on | `forbid-defparam` (on) | 0 | 0 | — |
| `invalid-system-task-function` | warning | on | same (on) | 8 | 23 | 10 / 0 / 0 |
| `truncated-numeric-literal` | warning | on | same (on) | 0 | 0 | — (50 before the all-unknown exempt, all false) |
| `undersized-binary-literal` | warning | on, safe fix | same (on, `lint_zero` off) | 11 | 6 | 6 / 0 / 0 |
| `suspicious-semicolon` | warning | on | same (off) → **on** | 3 | 5 | 5 / 0 / 0 |
| `packed-dimensions-range-ordering` | warning | on | same (on) | 0 | 4 | 4 / 0 / 0 |
| `module-port` | warning | on | same (on) | 44 | 161 | 7 / 0 / 3 |
| `module-parameter` | warning | on | same (on) | 2 | 0 | 2 / 0 / 0 |
| `explicit-function-task-parameter-type` | warning | on | same (on) | 1 | 5 | 5 / 0 / 0 |
| `plusarg-assignment` | warning | on | same (on) | 19 | 13 | 10 / 0 / 0 |
| `instance-shadowing` | warning | on | same (off) → **on** | 28 | 129 | 3 / 0 / 0 |
| `forbid-negative-array-dim` | warning | on | same (off) → **on** | 0 | 0 | — |
| `void-cast` | warning | on | same (on), different subject | 0 | 0 | — (1 before the `with` fix, false) |
| `incomplete-assignment` | warning | on | none | 3 | 0 | 3 / 0 / 0 (corpus) |
### Why a Verible-default-on rule fires on a "Verible-clean" tree
opentitan is lint-clean under Verible **for the filesets its `dvsim` lint
configurations name** — `hw/top_*/lint/*_lint_cfgs.hjson`, which cover RTL and
a chosen slice of DV. `lucisv check hw` covers all 3 975 files, including
`hw/vendor/` (third-party: ibex, pulp, riscv-dv), `hw/ip/*/pre_dv`,
`hw/ip/*/pre_sca` and `hw/ip/*/fpv`, none of which that flow lints. Every
finding of a Verible-equivalent rule sits in one of those:
- `module-port` (161): every one in `hw/top_*/dv/`, mostly autogenerated
`tb__xbar_connect.sv` interface instantiations (`tl_if tl_if(clk, rst_n)`).
The three "judgment" samples are exactly that idiom — a two-port clocking
interface connected positionally, which Verible would flag too.
- `undersized-binary-literal` (6): all in `hw/vendor/`.
- `invalid-system-task-function` (23), `plusarg-assignment` (13),
`explicit-function-task-parameter-type` (5),
`packed-dimensions-range-ordering` (4): DV, vendored and pre-silicon
directories.
- opentitan's own Verible config
(`hw/lint/tools/veriblelint/lowrisc-styleguide.rules.verible_lint`) sets only
four options and disables one rule; none of them is a rule this wave added.
### False positives found by the census and closed
Every one of these was found by reading opentitan findings, and every one is
now a named exclusion with a test beside it:
| Rule | Before | Cause | After |
|---|---:|---|---:|
| `duplicate-declaration` | 18 | error recovery in a 454-error UVM file rebinds every method local at file scope; enum **name ranges** (`Gpr[0:2]`); non-ANSI port completion | 0 |
| `undersized-binary-literal` | 456 | `2'b0` — Verible's `lint_zero` defaults **off** | 6 |
| `truncated-numeric-literal` | 50 | `3'hz`, `7'hzz`: one hex digit is four bits, so an all-unknown literal always "overflows" | 0 |
| `incomplete-assignment` | 3 | a temporary the block declares; a partial write before the branch; a `case` with a `default` covering every arm | 0 |
| `void-cast` | 1 | `void'(randomize(x) with { … })` — a call wearing a postfix clause | 0 |
| `undeclared-identifier` | 94 | `` `include``d **fragments** (a module body with no module around it: 85 of the 94); a generate label reached hierarchically | 5 |
### `undeclared-identifier`: the default decision
§33.2 made the default conditional on the count of *unexplained* findings on
opentitan being zero. After the exclusions above it reports **five** findings,
in one file, on both trees: `ibex/dv/formal/spec/spec_api.sv` connects
`.mhartid_out(mhart_id_o)`, `.mimpid_out(mimp_id_o)`, `.minstret_in(minstret_i)`,
`.minstret_out(minstret_o)` and `.mvendorid_out(mvendor_id_o)` to names its
module header never declares — implicit one-bit nets, which is exactly what the
rule exists to find. Unexplained: **0**. It therefore ships on wherever there
is a project, the same terms `unused-signal` and `undriven-net` run on.
*The residual risk, for the lead:* the rule's safety rests on the census
covering the whole project. A deliberately partial run (`lucisv check
hw/ip/uart` alone) has a smaller census and could accuse a name declared in a
directory the run did not include. The same is structurally true of
`unused-signal`, but there the failure mode is a false *negative* and here it
is a false positive. `--ignore undeclared-identifier`, `[lint] ignore` and the
per-rule VS Code toggle are all off switches for it.
### Timing — `lucisv check hw` over opentitan (3 975 files)
| Build | Wall (best of 3) |
|---|---:|
| 0.34.0 baseline (`/tmp/lucisv-0.34.0-baseline`) | 0.91 s |
| this lane, default rules | 0.83 s |
| this lane, `--ignore unknown-port --ignore unknown-parameter` | 0.66 s |
The interface half of the CLI census costs a **parse** of every file on top of
the lex the word census already paid for (~0.17 s here), and is built only when
`unknown-port` or `unknown-parameter` is enabled. Even with it the run is
*faster* than 0.34.0, because the same pass now harvests the word census from
the parse's own tokens instead of lexing the text a second time. The nineteen
new rules' own checking cost is inside the noise.
### Corpus and formatter gates
- `scripts/corpus_gate.sh corpus` → `{"passing":814,"total":820,"pct":99.3}`,
the same six failures, exit 0.
- `--stdout` over all 860 corpus files, byte-compared against the 0.34.0
baseline binary: **860 checked, 0 differing**. The formatter is untouched.
- `node editors/vscode/smoke.js target/debug/lucisv-server` → OK, 20 messages.
## Work log
### 2026-09-03 — 33.0, severity end to end
- New `vlog_linter::severity` (`Severity`, `as_str`/`from_name`/`describes`/
`ALL`), `Rule::severity` with no default, `Violation::severity`.
- **The runner stamps.** `lint()` ends with `stamp_severities`, which looks
each finding's rule up in the registry. One place rather than one per rule,
and it also covers the `unused-waiver` findings, which the waiver scanner
builds without a rule's `check` ever running. Pinned by
`the_runner_stamps_every_finding_with_its_rules_severity`.
- The seventeen assignments §33.0 listed are pinned as a table test, so a rule
changing class is a deliberate edit.
- `select_rules` goes through the new `rules_named`. `--ignore style` and
`[lint] ignore = ["style"]` therefore work with no change in
`lucisv_core::config` (it never validated names).
- CLI text gained the severity word; JSON gained `"severity"`. The server maps
Error/Warning/Style to ERROR/WARNING/INFORMATION. Four existing tests
asserted `WARNING` for style rules and were updated in place with the reason
in a comment.
- `rules_markdown` grew a Severity column, a per-rule `- Severity:` line and
three class headings.
### 2026-09-03 — 33.1, the toggles
- New `vlog_linter::vscode` generates the whole `lucisv.lint.severity.*` +
`lucisv.lint.rules.*` block; `examples/vscode_lint_settings.rs` prints it.
- **Deviation from §33.1, deliberate.** The brief asked for "one boolean per
rule, default = the rule's default", and for a precedence rung that fires
only on an *explicitly set* toggle. Those two cannot both hold: a client
sends the whole section with every key at its default, so a boolean cannot
distinguish "unset" from "set to the shipped value", and rung 4 would then
silently override `select` and the class switches for every user. The
toggles are therefore a three-word enum — `default` / `on` / `off`, default
`default` — which is tri-state, renders as a dropdown in the Settings UI
(a `["boolean","null"]` schema renders as raw JSON), and states the rule's
own default in its description and in its `enumDescriptions`.
- `settings.rs` reads them into `lint_severity: BTreeMap<Severity, bool>` and
`lint_rules: BTreeMap<String, bool>` (present only for `on`/`off`), on this
module's standing rule that an unreadable value leaves the shipped default.
The `select`/`ignore` validator now keeps severity words.
- `lint::enabled_rules(settings, has_oracle)` is the one ladder, documented
rung by rung and pinned by `the_enabled_rules_ladder_is_the_documented_one`,
plus `a_class_switch_changes_what_the_server_publishes` through the real
diagnostics path.
- The drift guard `the_vscode_lint_toggles_match_the_registry` parses both
`package.json` and the generator's output and compares them as JSON values.
It caught the stale manifest three times during this lane, which is what it
is for.
### 2026-09-03 — 33.2 and 33.3, the rules
- Nineteen rules, one file each, each with unit tests holding true positives
**and** near-misses, and a `.lint` case in one of the four new case files
(`literals`, `labels_and_scopes`, `statements`, `declarations`).
- Two new shared walkers rather than growing `visit.rs` past its one sentence:
`visit::walk_instantiations` (a plain instantiation and a `bind`'s), and a
new `decls.rs` for every `DataType` and every `Dim` in a file, packed and
unpacked told apart. A new `literal.rs` reads a sized based literal once for
the two width rules.
- `interfaces.rs` reads a parse's module headers into a `ModuleInterface`, for
the CLI census. A header carrying **any** directive between its ports or
parameters is reported unknowable rather than short: telling an `` `ifdef``
arm from a macro standing where a port belongs would be a second
preprocessor, and a short list is what turns a legal connection into an
accusation.
- `MentionOracle` gained one defaulted method. The CLI implements it from a
new interface half of `Census`, built only when a rule asks; the server
implements it from the workspace index, refusing a module the index holds
more than once.
- `LintContext::parsed_cleanly()` is the shared "this file's structure cannot
be trusted" guard, asked by `duplicate-declaration`, `instance-shadowing`
and `undeclared-identifier`.
- One `#[allow(clippy::large_enum_variant)]` was added, on
`context::SemanticsSlot`: `Semantics` grew past clippy's threshold when it
gained its `duplicates` table, and boxing the lazy slot would add an
allocation to the path that exists to avoid one. The reason is in a comment
above it.
- Every rule was measured on opentitan before it was called done; six false
positive classes were found that way and closed, each with a test naming the
file it came from. The counts are in Measurements above.
### 2026-09-03 — 33.4, docs
- README.md "Linting": the severity section, the class table, the ladder for
`--select error` / `--ignore style`, and a 36-row rule table.
- `editors/vscode/README.md`: two Diagnostics rows, six Settings rows and the
five-rung precedence.
- `docs/site/.../reference/rules.md`: the badge, the intro paragraphs on
severity and on the Error-class discipline, a Severity column, and one
hand-written section per new rule — with a note that `--rules-doc` is the
generated truth. A test-free page, so it is checked by hand against
`--rules-doc`'s section list (they match exactly).
## QA log
### 2026-09-03 — verification of 33.0–33.4, verdict PASS
Scope: everything on the Status/TODO list except the last box. Worked
entirely in `.claude/worktrees/lint-1` (branch `lint-1`, based on 965c4ee,
uncommitted); every experiment that needed a modified registry or a rebuilt
baseline binary ran in a throwaway `git worktree` created from 965c4ee or
999edd0 and removed when done (`baseline-965c4ee`, `throwaway-lint1`,
`baseline-rebuild` — none left behind). Opentitan was touched read-only;
`git -C opentitan status --porcelain` showed 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`) before and after every run in this pass.
**1. Gates.**
- `cargo fmt --all -- --check`: clean.
- `cargo clippy --all-targets --workspace`: clean. The first run was a cache
hit (0.11 s, nothing recompiled) so I re-ran it against a throwaway
`--target-dir` to force a full rebuild of all nine workspace crates — still
0 warnings, 14.5 s. The one new `#[allow(clippy::large_enum_variant)]` (on
`vlog_linter::context::SemanticsSlot`) carries an explanatory comment.
- `cargo test --workspace --no-fail-fast`: 48 binaries, **3383 passed, 0
failed, 42 ignored** — matches the dev's reported numbers exactly.
- `git diff --stat 965c4ee -- crates/vlog_formatter`: empty. `git diff
--name-only 965c4ee`: confined to the §33 ownership list plus the two
disclosed handshake files (`crates/vlog_semantic/src/{bind/mod.rs,lib.rs,
model.rs}`, `crates/lucisv_server/src/server/notification.rs`) — nothing
else.
- `cargo build --release -p lucisv`: clean. `--stdout` over all 860 corpus
files vs a freshly rebuilt 0.34.0 baseline (999edd0; `965c4ee` has no
crate diff from it, confirmed with `git diff --stat 999edd0 965c4ee --
crates/`): **860 checked, 0 differing**. (The originally-referenced
`/tmp/lucisv-0.34.0-baseline` was removed by the environment between
session restarts; rebuilding it from 999edd0 in a throwaway worktree
produced a byte-identical binary — same size, 2 342 144 bytes — and the
check was redone against the rebuild with the same 860/0 result.)
- `scripts/corpus_gate.sh corpus`: `{"passing":814,"total":820,"pct":99.3}` —
matches.
- vsix smoke (`node editors/vscode/smoke.js target/debug/lucisv-server`): OK,
20 messages.
**2. Severity plumbing.** Built a file with one violation of each class
(`no-tabs`/style, `wire-reg-mixup`/error, `always-comb-blocking`/warning).
Text output: `FILE:LINE:COL: error|warning|style: message [rule]`, exactly.
JSON: every finding carries `"severity"`; the baseline's JSON for the same
file has no such key. Exit code (1) matches the baseline binary's on the same
file. `--select style` → only the style finding; `--ignore warning` → warning
dropped, other two kept; `--select error --ignore mismatched-labels` → only
`wire-reg-mixup` (the only error-class rule this file trips); `--select
bogus` → `error: unknown rule: bogus (severities: error, warning, style;
known rules: ...)`, exit 2. `[lint] ignore = ["style"]` in `lucisv.toml` →
style dropped, same as `--ignore style`. `--rules-doc`: 36 rules, each with a
severity; the seventeen original assignments in the table match
`the_original_seventeen_keep_the_classes_they_were_given` exactly
(`multiply-driven`/error, `wire-reg-mixup`/error, five warnings, nine
styles).
**3. Editor toggles, through the real server.** No existing e2e test in
`tests/e2e.rs` exercises `lucisv.lint.severity.*` or `lucisv.lint.rules.*`
over the wire (only the pre-existing `lucisv.lint.ignore` case is there); the
new settings are otherwise covered by `settings.rs` and `lint.rs` unit tests
only. I drove the real `target/debug/lucisv-server` binary myself, framing
JSON-RPC by hand (same Content-Length model as `tests/e2e.rs`'s `talk()`),
one whole session per scenario so ordering could not be ambiguous:
- (a) `severity.style=false` on a file with all three classes → style
vanishes, error/warning stay. Correct.
- (b) `rules.always-comb-blocking=off` (a warning rule) → that rule vanishes,
others stay. Correct.
- (c) `rules.module-name-style=on` (a default-off style rule, on a
badly-named module) → it appears where it was silent before. Correct.
- (d) `select=["style"]` + `severity.style=false` → **empty**, i.e. rung 3
(class switch) applied after rung 2 (select) leaves nothing. Correct —
matches `enabled_rules`'s documented ladder.
- (e) `rules.module-name-style=on` + `ignore=["module-name-style"]` in the
same push → absent. Rung 5 beats rung 4. Correct.
- (f) every key sent explicitly at its default value → identical to the
no-configuration baseline (one publish, same set). Correct.
- A sequential single-session run (default → style off → reset to `{}` →
a rule off) reproduced the same transitions, confirming each
`didChangeConfiguration` payload fully replaces the settings rather than
merging (an empty `{"lint":{}}` genuinely resets every key).
- Diagnostic severities: `wire-reg-mixup` (error) → LSP 1, `always-comb-
blocking` (warning) → LSP 2, `no-tabs` (style) → LSP 3 (INFORMATION).
Confirmed.
- **False start, resolved.** An earlier *interactive* driver (writing one
frame, reading, writing the next) mis-reported scenario (d) as returning
the unchanged baseline set. Cross-checked two ways: a throwaway unit test
in a copy of `settings.rs` calling `from_payload` + `lint::enabled_rules`
directly on the same JSON returned the correct empty set, and the
whole-session driver above (matching `tests/e2e.rs`'s own proven model)
also returned the correct empty set on the real wire. The interactive
script's read/write interleaving was the bug, not the product; recorded
here for the trail, not as a finding.
- Drift test: read `the_vscode_lint_toggles_match_the_registry`
(`crates/lucisv_server/src/settings.rs`). Added a fake rule
(`qa-fake-rule`) to the registry in a throwaway worktree copy (not
`lint-1`) without touching `package.json` — the test **failed**, naming
the mismatch and pointing at the regenerate command. Not a test that
cannot fail. Throwaway worktree removed afterward.
**4. The 19 new rules, adversarially.** For each rule: a true positive, a
near-miss that must not fire, and a plan-named edge case, via `lucisv check
--select <rule>` on hand-written files.
*Error class* (false positive here would be HIGH):
- `mismatched-labels`: `end : wrong` fires; matching label, unlabeled `end`,
matching `generate` block label, matching `endclass : name` all silent;
mismatched generate label and mismatched `endclass` label both fire. All
correct, no false positives.
- `duplicate-declaration`: two `logic a;` fires; non-ANSI `input clk;` +
`logic clk;` silent; two `generate` arms each declaring `x` silent; a
macro-expanded double declaration (`` `DECLARE_X`` twice) silent. All
correct.
- `undeclared-identifier` (project only): a genuinely undeclared name in a
project with no wildcard import fires; the same name is silent as a single
file (rule is off without a workspace, confirmed via `--select` on one
file vs. on its directory); a hierarchical tail (`u_sub.internal_sig`), a
`$unit`-scope name declared outside any module and used from another file,
and a name that appears only inside a macro invocation argument are all
silent — none of these produced a false positive. **One thing worth
recording, not a bug**: a file with *any* wildcard package import
(`import p::*;`) gets every otherwise-unresolved value-position name
reclassified from `Resolution::NotFound` to `Resolution::ExternalCandidate`
at the single-file bind stage (`vlog_semantic::resolve::miss`), and the
rule's own doc says it never looks past that — "a package member ...
resolve[s] elsewhere and never reach[es] here." I verified this is
unconditional: a name that is genuinely **not** a member of the
wildcard-imported package still does not fire. This is squarely the
documented, deliberate trade-off ("Error... a rule may only claim it when
it is certain") — most UVM testbenches carry `import uvm_pkg::*;`, so the
rule's real-world reach is narrower than the opentitan "5 findings, all
true" headline number suggests on its own. Not a forcing finding since it
matches the rule's own stated contract exactly; worth a line in the
README's own doc if the lead wants it more visible.
- `unknown-port` / `unknown-parameter`: `.nonexistent_port(clk)` on an
indexed module fires; a correct connection is silent; `.*` is silent; an
interface-typed port (`bus_if.m b`) connected by name is silent; a
parameter override of a `localparam` (`.DOUBLE(16)`) fires as
`unknown-parameter`, matching the dev's stated "counts it as true"; a
module not indexed anywhere (single file, unknown submodule) is silent; a
module indexed **twice** (two files each declaring `module leaf`) is
silent. All eight scenarios matched the plan exactly.
*Warning class* (false positive here is MEDIUM): `forbid-defparam`,
`invalid-system-task-function`, `truncated-numeric-literal` (fire on
overflow, silent at-width, silent on an all-`z`/`x` literal),
`undersized-binary-literal` (fire on a short literal, silent when full-width,
silent on `4'b0`), `suspicious-semicolon`, `packed-dimensions-range-
ordering`, `module-port` (fires on ≥2 **positional** connections, silent
named, silent single-positional — checked the actual semantics against the
doc after an initial wrong guess), `module-parameter` (same shape),
`explicit-function-task-parameter-type` (fires on an untyped arg, silent
when typed, silent when a later arg shares an earlier one's declared type —
`int a, b` is both `int`), `plusarg-assignment`, `instance-shadowing`,
`forbid-negative-array-dim`, `void-cast` (fires on `void'(x)` around a plain
variable — not around a discarded call result, which is the opposite of my
first guess; silent around a real call; silent around
`randomize(x) with {...}`, the documented false-positive fix), and
`incomplete-assignment` (fires on an `if` with no `else`, silent with an
`else`, silent on a `case` with `default`). All fourteen behaved exactly as
documented; zero false positives, zero missed true positives on the stated
shapes. (Note: TODO §33.3 says "the thirteen listed" but the Measurements
table lists fourteen warning-class rules delivered — a small, harmless
wording/count mismatch, LOW.)
**5. Opentitan census (read-only).** `lucisv check --output-format json hw`
(3 947 `.sv`/`.v`/`.svh`/`.vh` files by my own glob — close enough to the
dev's 3 975 that the difference is almost certainly extension-set or a file
added/removed since; not investigated further) produced 619 violations. One
file failed to lex (`riscv_core_setting.tpl.sv`, a Jinja template, not real
Verilog — pre-existing, unrelated to this lane) — same as the baseline would
report. Per-rule counts for every §33 rule matched the README's table
**exactly**: `mismatched-labels` 1, `undeclared-identifier` 5, `unknown-port`
40, `unknown-parameter` 4, `invalid-system-task-function` 23,
`undersized-binary-literal` 6, `suspicious-semicolon` 5,
`packed-dimensions-range-ordering` 4, `module-port` 161,
`explicit-function-task-parameter-type` 5, `plusarg-assignment` 13,
`instance-shadowing` 129, and zero for `duplicate-declaration`,
`forbid-defparam`, `truncated-numeric-literal`, `module-parameter`,
`forbid-negative-array-dim`, `void-cast`, `incomplete-assignment`. Read five
each of `undeclared-identifier` (the five `ibex/dv/formal/spec/spec_api.sv`
implicit-net findings, exactly as documented — true), `unknown-port` (five
`pre_dv`/`fpv` testbench-vs-RTL port mismatches — read as true, consistent
with those directories sitting outside `dvsim`'s lint scope) and
`instance-shadowing` (five nested-scope name reuses, e.g. loop variable `i`
and a common `ral`/`id` — plausible warning-class findings, not false
positives, though a few are the kind of "judgment" case the dev's own sample
already flagged). `duplicate-declaration` and `incomplete-assignment`: 0,
matching. `git status --porcelain` in opentitan stayed at the same three
pre-existing files after this run.
**Timing — MEDIUM finding.** Rebuilt the 0.34.0 baseline (999edd0, byte-
identical to the one the dev used) since the original was gone from `/tmp`.
`lucisv check hw`, interleaved NEW/BASE, best of 3 (plus a separate 5-run
pass for the new binary alone): **new lane ≈ 1.05 s, 0.34.0 baseline ≈
0.83 s — roughly 25% slower**, on this machine, right now — the opposite of
the dev's reported 0.83 s → 0.91 s... (dev: new *faster* than baseline; here:
new *slower*). `--ignore unknown-port --ignore unknown-parameter` did not
recover much (~0.92 s best of 3), unlike the dev's reported drop to 0.66 s.
This session ran many concurrent cargo builds/tests across several worktrees
throughout the QA pass, which is a real possible confound (shared cache
contention, thermal throttling) — I do not have a quiet machine to rule that
out — but the regression was consistent and reproducible across 11
interleaved measurements, not a one-off. Flagging as MEDIUM per the timing
threshold; recommend the dev or lead re-measure on an otherwise-idle machine
before treating the absolute numbers as settled. This does not affect
correctness and is not a PASS blocker on its own.
**6. `Semantics::duplicates()`.** `git diff 965c4ee -- crates/vlog_semantic/
src/facts.rs`: empty — no `FACTS_FORMAT` change. Reviewed the `bind/mod.rs`,
`model.rs` and `lib.rs` diffs directly: the "already bound" arm in
`declare()` now also pushes a `Duplicate` record before doing exactly what it
did before (`use_name` + return `None`); nothing else in that function
changed. `cargo test -p vlog_semantic` in a throwaway worktree at 965c4ee vs.
in `lint-1`: **test-for-test identical** (17 binaries, same pass count in
each, e.g. 31/12/27/13/1/12/3/8/26+1ignored/40+1ignored/31/32/18/9/5/86+2ignored/0).
Corpus, 17-original-rules-only: ran both the new binary and the rebuilt
baseline with the **same explicit** `--select <the 17 original rule names>`
over all 860 corpus files and diffed the JSON (severity field stripped for
the comparison) — **0 differing**. (First attempt at this compared the new
binary's explicit `--select` output against the *baseline's own default*
run and found 13 spurious diffs, all `undriven-net`/`unused-signal` —
these are `needs_workspace`-gated, default-off-without-a-project rules, and
an explicit `--select` bypasses that gate in both versions identically per
`select_rules`'s documented contract; comparing against the baseline's
unselected default was an apples-to-oranges mistake on my part, not a
product issue — resolved by selecting the same list on both sides.)
**7. Docs.** `--rules-doc`'s 36 rule names/severities match README.md's
36-row table exactly, and match the docs-site
`reference/rules.md`'s 36 section headers exactly (diffed all three sets
programmatically). `editors/vscode/README.md` documents the tri-state
dropdown (`default`/`on`/`off`) and spells out the five-rung precedence
ladder in prose (does not use the literal words "tri-state"/"rung", but the
content is there and correct). TODO.md §33 checkboxes match the work done;
only the QA line is (correctly) still unchecked. **LOW**: the dev's work log
does not record the "`docs/site/dist` was not rebuilt" note the plan
expected — independently confirmed true (`git diff --name-only 965c4ee --
docs/site/dist` is empty) but not written down anywhere in the feature
README. **LOW**: §33.3's TODO text says "the thirteen listed" against
fourteen warning rules actually delivered (see §4 above) — cosmetic.
**Verdict: PASS.**
No HIGH or CRITICAL findings. Every Error-class rule was attacked with the
plan's own named shapes and produced zero false positives; the drift test
provably fails when it should; the precedence ladder is correct on the real
wire; the 17 original rules are byte-identical to baseline; opentitan is
untouched. Two LOW documentation nits and one MEDIUM timing measurement
(reproducible on this machine, opposite sign from the dev's own numbers,
confounded by heavy concurrent build load during this QA pass) are recorded
above for the lead's attention; none of them are correctness or safety-net
issues and none block merge on their own.
## Review
**2026-09-03 — lead.** Accepted. The round is larger than any linter
change before it — 17 → 36 rules, a severity on every one, the editor
surface generated from the registry — and its discipline held: each
rule is its own file with true positives and near-misses, the
false-positive classes found on opentitan were closed one test at a
time (456 → 6 on `undersized-binary-literal` by matching Verible's
`lint_zero` default; 94 → 5 on `undeclared-identifier` by giving an
`` `include``d fragment no opinion), and the drift test was proved able
to fail. Two decisions the plan did not make are the right ones: the
per-rule setting is tri-state because a VS Code client sends every key
at its default and a boolean cannot say "unset" — the plan's boolean
would have silently overridden `select` and the class switches for
every user; and `undeclared-identifier` ships on-with-a-project because
its unexplained count is zero and its silence rule (any other file
mentioning the name) is the false-negative-safe direction the semantic
lints already use. The two handshakes taken (`Semantics::duplicates()`,
additive, no store change; two lines in `notification.rs` so a toggle
republishes) are accepted. QA's MEDIUM timing note was measured under
another lane's compiles; re-measured at merge on a quiet machine and
recorded below. Ships in 0.36.0. Wave 2 (§34) takes the Style family
and per-rule options.
+16 -1
View File
@@ -32,7 +32,22 @@ behavior is unchanged byte for byte; the server gains the CLI's
example of that width — the formatter's `collect` does not yet fire inside
class bodies, the classes round's filed gap, but the scan backstop does, so
a fence inside a class body protects `--fix` and server quick fixes even
though `lucisv format` ignores it there.)
though `lucisv format` ignores it there.) **That example is stale as of
2026-09-03: TODO §31 (`docs/features/statement-fences/README.md`) taught
`collect` the class bodies and the statement lists, so the formatter and the
backstop now agree there. The union is still wider than `collect` alone —
the scan has no notion of scope, would be fooled by a fence spelled inside a
block comment, and pairs an `off` with the next `on` anywhere in the file —
but the specific asymmetry named above is closed. Neither
`protected_regions` nor `is_protected` changed: same signatures, same
contracts, and `crates/lucisv/src/lint.rs` and
`crates/lucisv_server/src/lint.rs` are byte-identical. One shape got
*narrower*, not wider, and it is the only one: `module m;
// verilog_format: off` used to be a region `collect` reported (the line
scan never saw it — the trimmed line is not a fence text), so `--fix`
declined inside it. That comment is no longer a fence at all, so nothing
there is protected any more. Right answer, but a narrowing; recorded here
because this file is where "what is protected" is supposed to be legible.**
- **`protected_regions` takes `&str` and parses internally, on purpose.** The
alternative — accepting a caller's `SourceFile` — would let the two front
ends feed different trees and get different answers, which is the drift this
+638
View File
@@ -0,0 +1,638 @@
# statement-fences
## Goal
`// verilog_format: off` … `// verilog_format: on` selected whole **items**
only. A fence written between two statements of an `always` block, inside a
function or task body, inside a `fork`, or between two members of a `class`
was formatted as an ordinary comment — the hand-aligned tables RTL authors
protect at module scope had no escape hatch one level down, and DV code, which
lives almost entirely inside class bodies and methods, had none at all. This
round adds those scopes: a class body scans as the item list it already is,
and statement lists (`begin`…`end`, `fork`…`join*`, function/task bodies, the
body of an `initial`/`always`/`final`) scan through a statement twin of the
item scan. Closes coverage_gaps M9 and topo §2.9-3, and closes the asymmetry
`shared-fence-filter` documented: `protected_regions`' line scan already
declined to *edit* inside these fences, while the formatter happily laid them
out. Nothing here widens what a fence is or what it emits — a region is still
a slice of source bytes.
## Assumptions
- **A statement list is a fence scope; a single-statement body is not.** The
bodies of `if`, `for`, `while`, `repeat`, `forever`, `foreach`, `do while`,
a timing control and an immediate `assert` are walked *into* but are not
scopes themselves, for the reason `scan_gen_block` refuses a block-less
generate item: there is no list for a region to end in, and the formatter
lays that statement out inside a `Group`, where a column-0
break-forcing `Doc::Verbatim` has no correct place. Only the `begin`…`end`
or `fork`…`join*` such a body may hold opens a scope.
- **A fence must begin the content of its line.** Nothing but whitespace and
finished block comments may precede it there. This is `fence::opens_line`,
and statement scanning is what forced it: the parser hands a comment written
after `begin` on the same line to the *next statement* as a leading comment,
so without the test `always @(*) begin // lucisv: off` would open a region
whose first line was sliced from the middle of a line. It is also what the
format-fences README already claimed the rule was — see the deviation in the
work log.
- **`Stmt.span` is the statement's code extent, its attributes included and
its comments excluded, and it reaches its own `;`.** Both halves are
load-bearing, exactly as `Item.span`'s are: the attribute half is why
splicing a statement reproduces its `(* … *)`, the comment half is why a
statement's leading comments can be emitted while its code is skipped, and
the `;` half is why a region ending at a statement never cuts a token in
half. Verified by probe (`x = 1;` spans the `;`).
- **A statement scope's end is the last statement's `span.end`, extended over
the comment trailing it on the same line.** `Meta.trailing` carries a span
now, but the scan reads the source rather than the node, so that one
function (`with_trailing_comments`) answers the question for items and
statements alike. Without it an unmatched `off` would drop that comment —
hard invariant #3.
- **A region never straddles two scopes**, so regions are pairwise nested or
disjoint, and `collect`'s existing "sort by `fence`, then drop any region
whose `fence` precedes the previous region's `end`" filter still leaves a
list sorted by both ends — `region_at`'s `partition_point` precondition.
The argument is unchanged from item scopes and is spelled out under
Handshakes.
- **Every `stmt_seq` caller emits a line break before it.** `Doc::Verbatim`'s
one contract is that it is only ever emitted right after a line break or at
the very start of the output; `block_doc`, the `fork` arm, `function`,
`task` all push a `HardLine` before the sequence, and the statement-fragment
path is the start of the output. Audited by grep, listed in the work log.
## Handshakes
**Consumed from `vlog_parser` (nothing new is required of it):**
- `Stmt.meta.leading` / `Stmt.span` — the units of a statement scope, the
same pair `Item` supplies.
- The statement-scope shapes: `StmtKind::Block`, `StmtKind::ForkJoin`,
`FunctionDecl.stmts` + `.dangling`, `TaskDecl.stmts` + `.dangling`, and the
bodies reached from `ItemKind::{Always, Initial, Final}`.
- The item-scope shape `ClassDecl { items, dangling }`.
- `Fragment::Statements` — a statement fragment is one statement list at file
scope, so `collect` scans it as one.
**Promised to `vlog_formatter` callers: no public signature changed.**
`fence::collect`, `fence::region_at`, `fence::protected_regions` and
`fence::is_protected` keep their signatures and their contracts.
`crates/lucisv/src/lint.rs` and `crates/lucisv_server/src/lint.rs` are
byte-identical. What *did* change is `collect`'s answer: it now reports
regions the line scan already reported, which narrows the union
`protected_regions` returns toward the truth and can only ever decline the
same edits or fewer.
**`region_at`'s precondition still holds.** Two regions are nested or
disjoint: a region lives in one scope's unit stream, running from its `off`
fence to an `on` in the same stream or to that scope's own end, and scopes
nest. A statement region therefore lies wholly inside the item whose body
holds it, and an item-level region either contains that item entirely or ends
before it starts. Sorting by `fence` and dropping every region whose `fence`
falls before the previous region's `end` leaves a disjoint list, which is
sorted by both ends.
**`verify.rs` is untouched.** No normalization was added, broadened or
weakened, so CLAUDE.md hard invariant #4's obligation does not arise — and
none was needed: a region is source bytes, so it re-lexes to exactly the
tokens it came from, and the units it replaces are exactly the ones whose
bytes it contains. Equivalence holds by construction and the check runs
unchanged as the backstop. New corrupted-region attack pairs for a statement
region and a class-body region are in `tests/fences.rs`, modelled on the five
that already guard item regions. Note what a *token* check cannot see: a
whitespace-only rewrite inside a region is token-equivalent, so the attack
pairs are all token-stream corruptions and the byte-exactness of a region is
asserted separately, by the `fenced` helper.
**`range.rs`: the plan now carries the fences.** `range::plan` extends its
manufactured verbatim runs with `fence::collect`'s regions before
`normalize` folds the two into their union. At item level this changes no
answer — a fenced item is already `Pick::Verbatim`, so its bytes were in a run
either way — but a fenced **statement** inside a laid-out item has no run
behind it, and without the merge `--lines` over such an item would have
reformatted bytes the author fenced off. A fence outranks a range, as before.
**Recursion budget (`docs/features/recursion-limit/README.md`): unaffected.**
`scan_nested_stmt` recurses only through statement nesting the parser already
bounds (`parse_stmt` is gated at the same 320 layers), builds no tree, and
`Doc::Verbatim` is a leaf.
**Requested of nobody.** No handshake request was filed; every file this round
needed was in its own ownership list.
## Deferred, with reasons
- **Port and parameter lists, and case-item label lists.** Their elements are
printed inside a `Group`, mid-line. `Doc::Verbatim` is column-0 and forces a
break — it cannot stand inside a group — and `Doc::Inline`, the only
mid-line verbatim primitive, carries no region indentation, so a region
spliced there would drift on every pass. This wants a different printer
primitive, not another scan arm. A fence in either place stays an ordinary
comment; pinned by `the_three_deferred_places_are_inert_and_never_corrupt`
and by two `.cases` entries.
- **Same-line (trailing-trivia) fences.** `wire a; // lucisv: off` is an
ordinary comment. Unblocked since `Meta.trailing` gained a span
(comments-round, 2026-08-19) but still deliberately inert: accepting it
means deciding whether the region starts on the *next* line, which is a
different rule from "the region starts at the fence's line start", and
nothing has asked for it.
- **The single-statement body of a bodyless `if (x) y = 1;`**, and the
single-item body of a bodyless generate `if` before it — same `Group`
reason as the lists above.
- **`PropSeqDecl.locals`** — a `Vec<Item>` that is *not* printed through
`item_seq`: `sva.rs` prints each local with `with_meta` and then the
property spec, which is not an item. The list has no end a region could
stop at without inventing one. Left alone; `Interface` and `Program` need
no arm because both are `ItemKind::Module`, which has been scanned since the
first round, and there is no `Checker` node in the AST at all.
- **The cross-level pairing rule is unchanged.** An item-level `off` closed by
a statement-level `on` is still an unmatched `off` — it runs to the end of
its own item list — and the `on` is a stray `on` in the statement scope,
i.e. an ordinary comment. That errs toward *more* verbatim text, never
toward reformatting something the author fenced off.
## Status / TODO
- [x] 31.1 class bodies: `ItemKind::Class` arm in `scan_nested`; the other
item-list carriers checked and named (`Interface`/`Program` are
`ItemKind::Module`, already scanned; no `Checker` node exists;
`PropSeqDecl.locals` deferred with a reason). Cases: a fence around one
member, around a nested class, an unmatched `off` stopping at
`endclass`, comments before the `off`.
- [x] 31.2 statement lists: `scan_units` (the shared unit stream),
`scan_stmt_scope`, `scan_nested_stmt`, the `Always`/`Initial`/`Final`/
`Function`/`Task` arms, the merge into `collect`'s sorted list, the
`stmt_seq`/`stmt_docs` rules, the `opens_line` gate, the
trailing-comment scope end, and the `range.rs` planner merge.
- [x] 31.3 docs rewritten: format-fences README ("Out of scope" replaced by
the real scope table), classes README handshake ticked,
shared-fence-filter README's asymmetry note corrected, `README.md`
"Turning the formatter off", `docs/coverage_gaps.md` M9 struck.
- [x] Attack pairs (a statement region, a class-body region) plus the
`fenced` triple for every new scope; `verify.rs` untouched.
- [x] Gates: `cargo fmt -p vlog_formatter`, `cargo clippy --all-targets
--workspace`, `cargo test --workspace`, corpus 814/820 byte-identical to
0.34.0, opentitan fence census + read-only sweep.
- [x] QA: PASS (2026-09-03). No CRITICAL/HIGH findings; two MEDIUM items
for the lead's ruling (`docs/topo.md` edited outside the dev's file
list; the `opens_line` narrowing, recommended as a drift fix) and one
LOW informational note. Full log below.
## Work log
### 2026-09-03 — dev agent (Opus 5)
Baseline measured first, in a throwaway `git worktree` at `HEAD`:
`cargo test --workspace` **3 234 passed, 0 failed, 42 ignored**.
**31.1 — class bodies (one arm, as planned).** `ItemKind::Class(c) =>
scan_scope(src, &c.items, &c.dangling, out)` in `scan_nested`. The other
item-list carriers were checked, since the plan asked for them by name:
`Interface` and `Program` are not separate nodes — both are `ItemKind::Module`
(`Module::end_kw` picks the closing keyword), so they have been fenceable
since the first round; there is **no** `Checker` node in the AST (grep over
`crates/vlog_parser/src/ast`); `GenBlock`, `GenerateRegion` and `Package` were
already scanned. The only `Vec<Item>` left unscanned is `PropSeqDecl.locals`,
deferred above with its reason. `format/class.rs` needed **no change** — the
class body has always printed through the fence-aware `item_seq`/`dangling`,
which is why one scan arm was the whole feature.
**31.2 — statement lists.**
- `scan_scope`'s body became `scan_units`, a scan over an iterator of
`(leading comments, code extent)` pairs plus the scope's dangling comments.
`scan_scope` and the new `scan_stmt_scope` are each three lines on top of
it. This is a pure refactor of the item path — the attribute guard
(`c.span.start < span.start`), the high-water mark and the
unmatched-`off` trailing-comment scan all live in one place now instead of
two, and the item-level output is unchanged.
- `scan_nested_stmt` walks the statement tree and opens a scope only at
`Block` and `ForkJoin`. `If`/`Assert` (both arms), `Case`/`RandCase` (each
item's body), `For`/`While`/`DoWhile`/`Repeat`/`Forever`/`Foreach`/
`Labeled` and the `Timing`/`Wait` bodies are walked through.
**Deviation from the plan, deliberate:** `Assert` and `Labeled` are not in
§31.2's list. They are structurally identical to `If`'s arms and to a bare
body — a `foo : begin … end` labelled block is a common DV shape — and
including them adds no scope kind, only reach.
- `scan_nested` gained the four item-side entries: `Function`/`Task` scan
their `stmts` + `dangling` as a scope; `Always`/`Initial`/`Final` hand their
body statement to `scan_nested_stmt`, which finds the `begin`…`end` inside
it.
- `collect` now dispatches on `SourceFile::fragment`: a `Fragment::Statements`
file is one statement list at file scope and scans as one.
**Deviation, deliberate:** §31.2 did not mention fragment mode. It is three
lines, `items` is empty for every fragment (verified in
`parser/directive.rs::read_fragment`), and leaving it out would have made
"statement lists are fenceable" false on the LSP's fragment path alone.
- `format/stmt.rs`: `Fmt::stmt_docs` is the statement twin of `item_docs` —
the region an offset *opens*, else the leading comments alone when the code
is swallowed (with the dangling `HardLine` dropped), else the statement.
`stmt` is now `concat(stmt_docs(s))` and `stmt_seq` separates on "did this
unit emit anything" instead of on the index, which is byte-identical to the
old formulation when no fence is present — the untouched snapshot suite is
the proof.
- `range.rs`: `plan` extends its runs with `planner.fences` before
`normalize`. See Handshakes for why; `normalize`'s doc comment already
described folding a fence and a run into their union, and this is the caller
that makes that sentence true.
**The line-start gate, and the one behaviour change outside the new scopes.**
`step` now opens a region only when `opens_line(src, start)`: whitespace and
finished block comments may precede a fence on its line, code may not. It was
forced by `always @(*) begin // lucisv: off`, which the parser hands to the
first inner statement as a *leading* comment — mid-line — where a region would
have started at the wrong column. Applying the test only to statement scopes
would have left the rule two rules, so it is applied everywhere, and that
changes one item-level shape: `module m; // lucisv: off` used to open a region
and now does not. Three reasons this is the right call rather than a
regression: the format-fences README has documented the rule as "*it must
start a line (nothing but whitespace, or another comment, before it on that
line)*" since the first round, so the code was the thing that drifted; the
existing `.cases` entry "a fence written after code on the same line is not a
fence" states the same rule for the case where the comment lands as *trailing*
trivia; and it narrows what fires, which cannot corrupt. The documented
`/* a */ // lucisv: off` exception is preserved deliberately — a block comment
before the fence is a unit of the same stream. Pinned by
`a_fence_sharing_its_line_with_code_is_an_ordinary_comment` and two `.cases`
entries. Corpus impact: none, it holds zero fences. **One consequence worth
stating plainly**, because it is the only place this round *narrows*
anything: `protected_regions` used to protect a `module m; // lucisv: off`
region (via `collect`; the line scan never saw it, since the trimmed line is
not a fence text), so `lucisv check --fix` and the server's quick fixes
declined to edit there. They no longer do — which is right, since that
comment is no longer a fence by any definition, but it is a narrowing and not
just a widening. Probed directly (`is_protected` false for that shape, true
for a statement fence, a class-body fence and an unmatched `off` in a task
body).
**File sizes, measured** (production lines: non-blank, non-comment, outside
`#[cfg(test)]`): `fence.rs` 226 → **246**, `format/stmt.rs` 573 → **590**,
`range.rs` 320 → **325**. All three stay inside CLAUDE.md's 300–600 band, and
nothing was pushed over a threshold. `format/stmt.rs` is the one to watch: at
590 it is close enough that the *next* addition to it should go in a new
module. Splitting it was not done here on purpose — a split is a pure move
and belongs in its own change, not tangled with a behaviour change.
**Not changed, on purpose:** `verify.rs`, `protected_regions`/`is_protected`,
`crates/lucisv/**`, `crates/lucisv_server/**`, `format/class.rs`,
`format/item.rs` (the two rules a swallowed unit obeys were already there and
`stmt_docs` mirrors them rather than sharing a helper — the two take different
node types and factoring them would cost a trait for one caller each).
**Results.** `cargo test --workspace` **3 244 passed, 0 failed, 42 ignored**
(baseline, measured in a worktree at `HEAD`: 3 234 / 0 / 42) — +10 tests:
8 in `tests/fences.rs`, 1 in `tests/ranges.rs`
(`a_statement_fence_outranks_a_range_too`, confirmed to fail without the
`range.rs` merge), 1 unit test in `fence.rs` for `opens_line`. `fences.cases`
goes 25 → 38 entries (+13; the entry "a statement-level fence has no effect
this round" was *inverted* rather than added, as §31.3 said it would be).
`cargo test -p vlog_formatter` 285 (was 275).
`cargo clippy --all-targets --workspace` **0 warnings**.
`cargo fmt -p vlog_formatter` clean — note it reformats the crate's tests
too, which is where the one unrelated-looking hunk in `tests/fences.rs` comes
from. `verify.rs` and `tests/verification.rs` untouched (`git diff --quiet`
on both).
Corpus: `scripts/corpus_gate.sh corpus` → `{"passing":814,"total":820,
"pct":99.3}`, the same six failures by the same categories, **0 verification
errors, 0 crashes**. Byte-identity against the 0.34.0 release binary
(`/tmp/lucisv-0.34.0-baseline`), `--stdout` per file over all **860** corpus
sources: **0 differences** — as expected, the corpus contains **zero** fence
comments (0 files match `verilog_format: (off|on)|lucisv: (off|on)`).
**OpenTitan (read-only; `--check` and `--stdout` only).** Census first: **9**
of 3 947 sources carry fence comments, 33 comment lines in all, and many sit
inside class bodies, task bodies and `fork` blocks — so files *could* move,
and four did. Old-vs-new `--stdout` over the whole tree: **4 differences of
3 947**, every one of them the fenced bytes now being preserved:
| file | what changed |
|---|---|
| `hw/ip/lc_ctrl/dv/env/lc_ctrl_env.sv` | a fenced `uvm_config_db#(…)::set(…)` call inside a `function` body keeps its hand-wrapped argument layout instead of being re-broken one-per-line |
| `hw/ip/lc_ctrl/dv/env/seq_lib/lc_ctrl_errors_vseq.sv` | a fenced **class-body** region (two `virtual task`s, ~110 lines) keeps its hand-written ternaries, comment placement and blank lines |
| `hw/ip/lc_ctrl/dv/env/seq_lib/lc_ctrl_jtag_access_vseq.sv` | the closing `on` fence keeps its own (odd, 5-space) indentation, because the fence comment is part of the region |
| `hw/ip/lc_ctrl/dv/env/seq_lib/lc_ctrl_jtag_priority_vseq.sv` | the blank line written between the `on` fence and the next statement is dropped — the documented "after the region" rule, now reaching statement level |
**Injection stress, the way the first fence round did it** (harness in the
scratchpad, not checked in; seed `0x2026_0903_dead_beef`, replayable). Four
random `off`/`on` line pairs injected into every corpus file that parses, each
compared against a **paired control** where the same two lines are ordinary
comments of identical width — the control matters, because injecting any
comment into a port list or an expression is a known pre-existing refusal
class (corpus-bugs README) and an unpaired comparison blames it on the fence.
Result over **3 348 trials** across 854 files:
```
trials=3348 fence_refusals=39 plain_refusals=39 new=0
honoured=3309 byte_exact=1976 same_level=1202 same_level_byte_exact=850
```
**Zero** verification failures attributable to fencing, and no panic. The
byte-exact figure (1 976 of 3 309 runs reproduce the whole `off`-line-through-
`on`-line slice contiguously) is a *floor*, not a defect rate: a randomly
placed pair lands as often as not in a position where the fence is inert by
design — a port list, a case label, a header line, an expression — or at two
different nesting levels, where the `off` is unmatched and correctly stops at
its own scope's end instead of reaching the `on`. Restricting to pairs whose
two lines share an indentation (a crude same-scope proxy, and only a proxy —
two sibling blocks share an indent too) lifts it to 850 of 1 202. What the
run rules out is the thing that matters: no injected fence ever made the
formatter produce output the safety net had to refuse when the same comment
in the same place would not have.
Each diff is assertion-free in the sense that matters: the `+` side is the
file's own source bytes. All four are fixed points under a second pass
(checked explicitly), and `--stdout` succeeding at all means
`verify_equivalence` and `verify_convergence` both passed inside
`format_source`. The read-only `--check` sweep reports **identical** counts
before and after (3 896 would reformat, 72 unchanged, 11 failed to format),
and `git -C ../opentitan status --porcelain` shows 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`).
Files touched: `crates/vlog_formatter/src/fence.rs`,
`crates/vlog_formatter/src/format/stmt.rs`,
`crates/vlog_formatter/src/range.rs`,
`crates/vlog_formatter/tests/fences.rs`,
`crates/vlog_formatter/tests/cases/fences.cases`, this README,
`docs/features/format-fences/README.md`, `docs/features/classes/README.md`,
`docs/features/shared-fence-filter/README.md`, `docs/coverage_gaps.md`,
`README.md`, `TODO.md` (§31 only). No `git commit`/`push`.
## QA log
### 2026-09-03 — QA agent (Sonnet 5)
All checks run read-only against the uncommitted main tree, plus one
throwaway `git worktree` (`.claude/worktrees/qa-play-31`, removed when done)
for the two experiments that needed source edits (the narrowing probe and
the `range.rs` load-bearing check). Never ran `git checkout`/`stash`/
`reset`/`clean` in the main tree. `git status --porcelain` before and after
this pass is identical to what the dev left: no file outside the dev's own
edits was touched.
**1. Gates — all confirmed independently, not just re-reading the dev's
numbers.**
- `cargo fmt --all -- --check`: clean (exit 0).
- `cargo clippy --all-targets --workspace`: 0 warnings; `git diff` of the
three touched files has no `#[allow]`.
- `cargo test --workspace --no-fail-fast`: summed the 48 `test result:`
lines myself — **3 244 passed, 0 failed, 42 ignored**, matching the
claimed baseline delta (3 234 → 3 244).
- `cargo test -p vlog_formatter`: summed to **285** (32+1+5+14+2+23+208+0),
matching the claimed 275 → 285.
- `git diff --stat -- crates/vlog_formatter/src/verify.rs crates/lucisv/src/lint.rs crates/lucisv_server/src/lint.rs`:
empty, all three.
- Changed-file set: `git status --porcelain` lists exactly the files named
in Handshakes/Work log, **plus `docs/topo.md`**, which is *not* in the
ownership list given to me (TODO §31's own "Files:" line marks
`docs/topo.md §2.9-3 struck (lead)` as the lead's job, not the dev's).
The content of that edit is accurate and consistent with everything
else (checked below), so this is a process note, not a defect: the
edit is already made, uncommitted, in the working tree ahead of lead
review. **MEDIUM** (process, not correctness) — flagging for the lead's
ruling, not blocking.
**2. Byte-identity — reproduced independently, not by trusting the dev's
numbers.**
- Built `cargo build --release -p lucisv` myself.
- Corpus: copied `corpus/` to two scratch trees, formatted one with
`/tmp/lucisv-0.34.0-baseline` and the other with the new binary
in-place, `diff -rq` the two trees: **0 differences** across all 860
files. `scripts/corpus_gate.sh corpus` → `814/820, 99.3%`, same failure
categories, 0 verification errors, 0 crashes.
- OpenTitan (read-only throughout — only `--stdout`/`--check`, and I
verified `git -C .../opentitan status --porcelain` was clean of
anything but the three pre-existing files both before and after):
- Census: `grep -rlE 'verilog_format: (off|on)|lucisv: (off|on)'` over
`hw/` → **9 files**, matching the dev's count.
- Copied the whole `hw/` tree (3 947 sources) to two scratch trees,
formatted one with each binary, `diff -rq`: **exactly 4 differing
files**, and they are the same 4 the dev named
(`lc_ctrl_env.sv`, `lc_ctrl_errors_vseq.sv`,
`lc_ctrl_jtag_access_vseq.sv`, `lc_ctrl_jtag_priority_vseq.sv`). Both
binaries exit 2 (pre-existing parse failures elsewhere in the vendor
tree, unrelated).
- Read all four diffs. `lc_ctrl_env.sv`: the new output's fenced lines
are byte-for-byte the same text as `git show HEAD:...` at that
location (checked directly). `lc_ctrl_jtag_access_vseq.sv`: confirmed
the source really does have 5 leading spaces before that `on` fence
(`awk` line dump), so the "odd indentation preserved" claim is real,
not a typo. `lc_ctrl_jtag_priority_vseq.sv`: the blank line after the
`on` fence is dropped, matching the documented after-region rule.
`lc_ctrl_errors_vseq.sv`: found the single real fence pair by grep
(lines 918/1030 — the other six `verilog_format: off/on` comments in
that file all carry trailing text, e.g. "- avoid bad formatting", so
per the fence grammar they are correctly **not** fences and correctly
untouched); a Python regex extraction confirmed the new output's
~110-line fenced slice is identical to the same slice in
`git show HEAD:...` of the file.
- Second-pass fixed point: ran the new binary again on all four new
outputs — byte-identical (`diff -q` clean) for all four.
- Comment census (counting `//`-bearing lines) on all four files:
original source, old-binary output, new-binary output all match
exactly (8, 196, 41, 21 respectively) — no comment dropped.
- `--check` over `hw/` with both binaries: identical counts, **3 896
would reformat, 72 unchanged, 11 failed**, both before and after.
**3. Break it — 15 hand-written files** (scratchpad `qa-31/breakit/`),
one per scope/edge named in the task: `begin…end`, `fork…join`, a function
body, a bodyless `always_comb` (no `begin`), a whole `if`/`else`, a `case`
item body, a class item and a nested class, an item-level `off` closed by a
statement-level `on` (two variants), an unmatched `off` in a statement list
stopping before `endfunction`, `begin // lucisv: off` (same-line, ordinary
comment), a block comment sharing the fence's line (the documented
exception), a fence with trailing text (ordinary comment), deep nesting
(fork inside if inside if), a fenced statement under `--lines` (five range
specs against the CLI directly, not just the dev's `ranges.rs` test), and
`check --fix` on two shapes.
Every file that parsed produced output — `format_source` calls
`verify_equivalence`+`verify_convergence` internally, so every successful
`--stdout` already proves equivalence; I additionally re-ran the output
through the binary a second time and diffed byte-for-byte for all 15 —
**all fixed points**. Comment line counts (`//`/`/*` occurrences) match
input to output on all 13 of the scope/edge files. Specific findings:
- The bodyless `always_comb` case: confirmed the fence comment survives
(never dropped) while `x = 1;` is laid out normally (collapsed
spacing) — correctly inert, not a scope, as documented.
- The nested-fence pairing rule (item `off` / statement `on`): built a
case with `wire a;` after the `initial begin...end` inside the same
module, both with distinctive multi-space padding. Confirmed the
**entire module body up to and including that `wire` declaration** came
out byte-for-byte raw (padding preserved), while a `wire b;` written
*after* it was laid out normally — i.e. the unmatched item-level `off`
swallows everything to the end of its own item list, the inner
statement-level `on` is correctly inert, and the fence does not leak
into the next item. Matches the documented rule exactly.
- `--lines`: ran the CLI directly (not the dev's own test) with
`--lines 4` and `--lines 1-9` over a file with a mid-block fence: both
left the fenced statements untouched while reformatting the
surrounding, already-clean statements — a fence outranks a range,
confirmed against the real binary.
- `check --fix`: crafted two files, one with the narrowing shape
(`module m; // lucisv: off` followed by a stray `;` null item) and one
with a genuine statement fence around a stray tab character. Ran
`check --fix` with **both** `/tmp/lucisv-0.34.0-baseline` and the new
binary on copies of each:
- Narrowing shape: old binary reports the `empty-item` violation but
does **not** fix it (declined, protected); new binary fixes it
(deletes the `;`) and the violation disappears from the report
entirely. This is the real, user-visible consequence of the
narrowing, confirmed live rather than by reading the dev's prose.
- Genuine statement fence: **both** binaries report the `no-tabs`
violation but decline to fix it — the tab stays untouched by both.
Statement-level protection for `--fix` holds.
No dropped comment, no non-fixed-point, no moved byte inside a region in
any of the 15 files.
**4. The narrowing — reproduced at both the formatter and the
`is_protected`/`protected_regions` layer**, and the CLI `--fix` layer
above.
- Quoted the format-fences README exactly as of round 1
(`git show 02f6865:docs/features/format-fences/README.md`): *"A fence
must be a leading comment, i.e. it must start a line (nothing but
whitespace, or another comment, before it on that line)."* The dev's
claim that this rule predates the code is correct — verified by reading
round 1's own text, not by trusting the work log's paraphrase.
- Built two throwaway worktrees (`qa-play-31` at the dev's patch,
`qa-baseline-31` at plain `HEAD`) and added a temporary probe test to
each (`tests/fences.rs`, never touching the main tree). Confirmed
directly: `protected_regions`/`is_protected` on `module m; //
lucisv: off\n wire a;\nendmodule` returns **not protected** on the
dev's patch and **protected** on plain `HEAD` — the narrowing is real
at the API level the CLI's `--fix` and the server's quick fixes both
call, not just in the formatter's own byte-for-byte splice.
- A genuine statement fence and a genuine class-body fence both remain
protected in the same probe, and `collect`'s own (scope-aware) answer
for an unmatched `off` in a task body stops exactly at `endtask`
(verified the region's `end <= task_end`), never past it — the crude
line-scan half of `protected_regions`'s union has no notion of scope
and may still over-protect further (documented, and I confirmed it: it
ran the same unmatched-`off` region to end of file), which only ever
*declines* an edit and is unrelated to this feature.
- Both worktrees removed after use (`git worktree remove --force`);
`git status --porcelain` on the main tree confirmed unaffected
throughout.
**Recommendation on the narrowing: drift fix, not a regression.** The
documented rule predates this round by two releases (round 1, commit
`02f6865`); the code was the thing out of step with its own spec, not the
other way around; the change only removes protection, it adds none (an
already-verified-safe direction per invariant #1); and the shape it stops
matching (`module m; // lucisv: off`, comment trailing the header on the
same line) was never advertised as supported in any README, changelog, or
`.cases` file before this round touched it. I found no place where a user
was told this specific shape worked. Concur with the dev: ship it as a
drift fix, MEDIUM severity recorded for the lead's ruling only because it
is a live user-visible behavior change (a real `--fix` decision flips),
not because anything is wrong with it.
**5. Attack pairs.** Read the dev's new corrupted-region pairs in
`tests/fences.rs` (7 statement-region + 5 class-region corruptions) — all
plausible, all target genuine token-stream changes (literal rewrites,
dropped/added statements or members, fence-comment tampering, swallowed
closer). Added two of my own in the `qa-play-31` worktree:
- A single literal changed inside an otherwise-intact statement region —
rejected by `verify_equivalence`, as expected.
- The `on` fence's *effective* position moved one statement earlier: first
tried a whitespace-only variant (`y = 2;` → `y = 2;`, fence text left
in place) and it was **accepted** by `verify_equivalence` — not a bug,
the documented boundary ("a whitespace-only rewrite inside a region is
token-equivalent") applies identically to item-level regions since round
1 and `verify.rs` is untouched this round, so there is no new widening
to attack-test under invariant #4. Replaced it with two variants that
are genuine token corruptions (a literal changed inside the region; the
`on` fence's own text moved a line, laundering a statement from
verbatim to laid-out) — both correctly rejected.
- **LOW note, not a defect**: worth restating in the feature README
(already is, in Handshakes) that the safety net's defense against a
whitespace-only corruption inside *any* fenced region — item or
statement — is the formatter's own verbatim-copy code path, unit- and
snapshot-tested directly, not `verify_equivalence` after the fact. This
is pre-existing and out of scope for this round.
**6. `range.rs` load-bearing claim — reproduced.** In `qa-play-31`,
commented out the one line `regions.extend(planner.fences.iter().copied());`
in `range::plan`: `cargo test -p vlog_formatter --test ranges
a_statement_fence_outranks_a_range_too` **failed** exactly as predicted
(spec `4` reformatted the fenced statement, collapsing `b`/`cc`'s
spacing). Restored the line: the test **passed**. The claim is not
decorative — the merge is genuinely load-bearing.
**7. Docs.** Read all four amended READMEs in full
(`format-fences`, `classes`, `shared-fence-filter`, plus the new
`statement-fences`) and `README.md`'s "Turning the formatter off" and
`docs/coverage_gaps.md`'s M9 row.
- `format-fences/README.md`: "Out of scope" is now a real "The fenceable
scopes" table plus a "Still not fenceable" list; matches the code
(checked the `scan_nested`/`scan_nested_stmt` match arms directly
against the table's rows).
- `classes/README.md`: the filed handshake is marked delivered with the
exact arm quoted; matches `fence.rs`'s actual diff.
- `shared-fence-filter/README.md`: the stale-asymmetry note is correctly
marked stale with a dated correction; the "one shape got narrower"
paragraph matches finding 4 above word for word.
- `README.md`: the new class-method example is realistic UVM shape and
formats correctly when I ran it (spot-checked). The "must begin its own
line" and "no further" wording matches the code.
- `docs/coverage_gaps.md`: M9 struck with an accurate closing note (the
two deferred mid-line positions named correctly); the "what's still
open" paragraph at the bottom updated consistently.
- `TODO.md` §31: all four sub-checklists ticked match delivered work;
only the QA line is unchecked, correctly, since QA had not run.
Deferrals (port/parameter lists, case-item *label* lists, same-line
fences, `PropSeqDecl.locals`) are each named with a real, checkable
reason in the statement-fences README's own "Deferred, with reasons"
section, and I independently exercised the three deferred shapes
(break-it §3, `t4`/port-list/case-label cases already covered by the
dev's own `the_three_deferred_places_are_inert_and_never_corrupt` test,
which I read and agree models them correctly).
**Findings summary.**
- MEDIUM: `docs/topo.md` was already edited in the uncommitted tree,
outside the file-ownership list this task gave me and outside what
TODO §31's own "Files:" line assigns to the dev (marked "(lead)"). The
content is accurate; flagging only the process order for the lead.
Not blocking.
- MEDIUM (ruling requested, not a defect): the `opens_line` narrowing —
see finding 4. Recommend: accept as a drift fix.
- LOW (informational, not a defect): the safety net's blind spot for a
whitespace-only corruption *inside* a region is unrelated to this
round's changes to `verify.rs` (there are none) and predates it at item
level; noted for the record only.
- No CRITICAL or HIGH findings. No corruption, no dropped comment, no
non-fixed-point output, no moved byte inside any region, no reach past
a scope's own end, no range reformatting a fenced byte, and `verify.rs`
confirmed untouched (`git diff --stat` empty) with its existing token
check independently re-exercised and holding for every genuine
corruption I constructed.
**Verdict: PASS.**
## Review
**2026-09-02 — lead.** Accepted. The round did what the plan asked and
found the two things the plan could not see: that `range.rs` must merge
fence regions into its plan because a fenced *statement* has no verbatim
run behind it (proved by breaking it), and that the line-start rule has
to be one rule — `opens_line` everywhere — because the parser hands a
same-line fence after `begin` to the first inner statement as a leading
comment. The narrowing that follows (`module m; // lucisv: off` no
longer opens a region, and the backstop stops protecting that shape) is
ruled a drift fix: the format-fences README has said "it must start a
line" since round 1 (QA quoted the commit), the statement-level case
already behaved that way, and a fence hiding after code is exactly the
ambiguity the rule exists to remove. `scan_units` as the one scan under
both scope kinds is the right shape; the three extra walker arms add
reach, not scope kinds. Deferred with reasons and recorded: port lists,
case-item labels, same-line fences, a property's locals. Proof:
corpus byte-identical (zero fences there), opentitan's four fenced
files now keep their bytes and are fixed points, 3 348 injection trials
with no new refusals. QA's note that a whitespace-only change inside a
region is invisible to `verify_equivalence` is a documented, pre-
existing property of item-level fences too (a region is source bytes;
the formatter never rewrites them) and is not this round's obligation.
`format/stmt.rs` at 590 production lines is the next lane's first
split. Ships in 0.35.0.
+122 -21
View File
@@ -1,31 +1,56 @@
---
title: Lint rules
description: Complete reference for all seventeen lucisv lint rules, their defaults, fixes, and rationale.
description: Complete reference for every lucisv lint rule, its severity, default, fix, and rationale.
---
<span class="badge">17 rules indexed</span>
<span class="badge">36 rules indexed</span>
Every rule is in one of three **severity** classes. `error` is code that would very likely fail to compile, elaborate or synthesize; `warning` is code that compiles and very likely does not mean what it says; `style` is code that is correct and reads badly. The class is the word in the CLI diagnostic line (`FILE:LINE:COL: warning: …`), the `severity` field of `--output-format json`, and the colour of the editor's squiggle — and it is accepted wherever a rule name is, so `--ignore style` and `--select error` both work.
Every `error`-class rule is held to one discipline: it goes **silent whenever the run cannot answer** — a file that did not fully parse, a module the project does not hold or holds twice, a name a macro produces, a fragment written to be `` `include``d. A wrong accusation in that class is worse than a hundred missed ones.
This page is hand-written prose. The generated truth is `lucisv check --rules-doc`, which prints every rule with its class, default, fix and rationale straight from the registry.
A rule marked **on&nbsp;(project)** runs by default only where lucisv can see the other files of your project — `lucisv check <dir>`, or the language server. Over a single file or a stdin buffer it is off and must be `--select`ed, because its one false-positive mode is a use in another file. Turn any rule off with `--ignore`, with `ignore` under `[lint]` in `lucisv.toml`, or with `lucisv.lint.ignore` in your editor.
| Rule | Default | Fix | Purpose |
|---|:---:|:---:|---|
| [`always-comb-blocking`](#always-comb-blocking) | on | — | Use `=` inside `always_comb` |
| [`always-ff-non-blocking`](#always-ff-non-blocking) | on | — | Use `<=` inside `always_ff` |
| [`case-missing-default`](#case-missing-default) | on | — | Give every case a default branch |
| [`empty-item`](#empty-item) | on | safe | Drop a `;` that stands where an item belongs |
| [`enum-name-style`](#enum-name-style) | on | — | Name enum typedefs with `_e` or `_t` |
| [`explicit-parameter-storage-type`](#explicit-parameter-storage-type) | on | — | Declare parameter storage types |
| [`module-filename`](#module-filename) | on | — | Match one-module files to module names |
| [`module-name-style`](#module-name-style) | off | — | Use lower_snake_case module names |
| [`multiply-driven`](#multiply-driven) | on&nbsp;(project) | — | Give variables one driver |
| [`no-tabs`](#no-tabs) | on | safe | Use spaces outside string literals |
| [`no-trailing-whitespace`](#no-trailing-whitespace) | on | safe | Remove end-of-line whitespace |
| [`parameter-name-style`](#parameter-name-style) | on | — | Use CamelCase or ALL_CAPS parameters |
| [`struct-union-name-style`](#struct-union-name-style) | on | — | Name aggregate typedefs with `_t` |
| [`undriven-net`](#undriven-net) | on&nbsp;(project) | — | Drive signals that are read |
| [`unused-signal`](#unused-signal) | on&nbsp;(project) | — | Detect unreferenced internal signals |
| [`unused-waiver`](#unused-waiver) | on | — | Remove ineffective suppressions |
| [`wire-reg-mixup`](#wire-reg-mixup) | on | — | Prefer `logic` to `reg` in SystemVerilog |
| Rule | Severity | Default | Fix | Purpose |
|---|:---:|:---:|:---:|---|
| [`always-comb-blocking`](#always-comb-blocking) | warning | on | — | Use `=` inside `always_comb` |
| [`always-ff-non-blocking`](#always-ff-non-blocking) | warning | on | — | Use `<=` inside `always_ff` |
| [`case-missing-default`](#case-missing-default) | warning | on | — | Give every case a default branch |
| [`duplicate-declaration`](#duplicate-declaration) | error | on | — | Declare each name once per scope |
| [`empty-item`](#empty-item) | style | on | safe | Drop a `;` that stands where an item belongs |
| [`enum-name-style`](#enum-name-style) | style | on | — | Name enum typedefs with `_e` or `_t` |
| [`explicit-function-task-parameter-type`](#explicit-function-task-parameter-type) | warning | on | — | Type every function and task argument |
| [`explicit-parameter-storage-type`](#explicit-parameter-storage-type) | style | on | — | Declare parameter storage types |
| [`forbid-defparam`](#forbid-defparam) | warning | on | — | Override at the instantiation, not with `defparam` |
| [`forbid-negative-array-dim`](#forbid-negative-array-dim) | warning | on | — | Keep negative literals out of dimensions |
| [`incomplete-assignment`](#incomplete-assignment) | warning | on | — | Assign on every path of an `always_comb` |
| [`instance-shadowing`](#instance-shadowing) | warning | on | — | Do not hide an enclosing declaration |
| [`invalid-system-task-function`](#invalid-system-task-function) | warning | on | — | Avoid deprecated and non-reproducible system tasks |
| [`mismatched-labels`](#mismatched-labels) | error | on | — | Make an end label name its own block |
| [`module-filename`](#module-filename) | style | on | — | Match one-module files to module names |
| [`module-name-style`](#module-name-style) | style | off | — | Use lower_snake_case module names |
| [`module-parameter`](#module-parameter) | warning | on | — | Override more than one parameter by name |
| [`module-port`](#module-port) | warning | on | — | Connect more than one port by name |
| [`multiply-driven`](#multiply-driven) | error | on&nbsp;(project) | — | Give variables one driver |
| [`no-tabs`](#no-tabs) | style | on | safe | Use spaces outside string literals |
| [`no-trailing-whitespace`](#no-trailing-whitespace) | style | on | safe | Remove end-of-line whitespace |
| [`packed-dimensions-range-ordering`](#packed-dimensions-range-ordering) | warning | on | — | Write a packed dimension `[N-1:0]` |
| [`parameter-name-style`](#parameter-name-style) | style | on | — | Use CamelCase or ALL_CAPS parameters |
| [`plusarg-assignment`](#plusarg-assignment) | warning | on | — | Read a plusarg with `$value$plusargs` |
| [`struct-union-name-style`](#struct-union-name-style) | style | on | — | Name aggregate typedefs with `_t` |
| [`suspicious-semicolon`](#suspicious-semicolon) | warning | on | — | No `if (x);` or `while (x);` |
| [`truncated-numeric-literal`](#truncated-numeric-literal) | warning | on | — | Keep a sized literal inside its width |
| [`undeclared-identifier`](#undeclared-identifier) | error | on&nbsp;(project) | — | Use a name something declares |
| [`undersized-binary-literal`](#undersized-binary-literal) | warning | on | safe | Write every bit of a sized binary literal |
| [`undriven-net`](#undriven-net) | warning | on&nbsp;(project) | — | Drive signals that are read |
| [`unknown-parameter`](#unknown-parameter) | error | on&nbsp;(project) | — | Override only parameters the module declares |
| [`unknown-port`](#unknown-port) | error | on&nbsp;(project) | — | Connect only ports the module declares |
| [`unused-signal`](#unused-signal) | warning | on&nbsp;(project) | — | Detect unreferenced internal signals |
| [`unused-waiver`](#unused-waiver) | style | on | — | Remove ineffective suppressions |
| [`void-cast`](#void-cast) | warning | on | — | Cast to `void` only what a call returns |
| [`wire-reg-mixup`](#wire-reg-mixup) | error | on | — | Prefer `logic` to `reg` in SystemVerilog |
## always-comb-blocking
@@ -94,3 +119,79 @@ Reports malformed, unknown, or ineffective waiver comments when their target rul
## wire-reg-mixup
Reports `reg` in `.sv` and `.svh` files and recommends `logic`. Verilog `.v`/`.vh` files and unnamed stdin are exempt; `wire` remains valid and is never flagged.
## duplicate-declaration
Reports a name a scope binds twice — two signals, two parameters, two typedefs, two instances. It is silent whenever the second declaration might be legal: a **port** on either side (a non-ANSI port is completed by its body declarations, all legally), a function, task, class, constraint, covergroup, property, sequence, modport or clocking name (each has a prototype-plus-definition or forward-declaration form), an enum **name range** (`Gpr[0:2]` declares a run of members under one written identifier), a `generate` scope, a pair separated by a conditional-compilation directive, the file scope, and any file that did not fully parse. Measured on opentitan: 18 findings before those exclusions, all of them phantoms from one 454-error UVM file, and 0 after.
## explicit-function-task-parameter-type
Reports a task or function formal with no storage type, which the language makes a one-bit `logic` (IEEE 1800 §13.3). Only the argument that *opens* a declaration is judged — a continuation (`f(input int a, b)`) inherits — and a DPI import's unnamed formal is not this rule's subject. Verible's `explicit-function-task-parameter-type`, same default.
## forbid-defparam
Reports `defparam`, deprecated since IEEE 1800-2009 and rejected outright by several synthesis tools. The `#(.NAME(value))` override at the instantiation says the same thing where the instance is. Verible's `forbid-defparam`, same default.
## forbid-negative-array-dim
Reports a written negative literal inside a dimension, packed or unpacked — the shape `[WIDTH-1:0]` collapses to when `WIDTH` comes out zero. Only a literal is judged; an expression that would evaluate negative needs parameter values lucisv does not have. Verible ships this off; lucisv turns it on, because a negative literal spelled out in a dimension has no legitimate reading.
## incomplete-assignment
Reports a variable an `always_comb` writes under an `if` with no `else`, or in some arms of a `default`-less `case`, and nowhere unconditionally before — a latch inferred where none was wanted. Conservative by construction: it reads only the top level of the block, treats a partial write and an every-arm `if`/`else` or `case` as coverage, and never reports a name the block declares for itself. No Verible equivalent. Measured on opentitan: 3 findings before those exclusions, all false, 0 after; 3 on lucisv's corpus, all real latches in `common_cells/src/deprecated`.
## instance-shadowing
Reports a declaration that hides one from an enclosing scope of the same design unit — the block-local `count` that quietly changes what every `count` in the block means. Only data and instances are judged (a subroutine argument named after a signal is idiomatic), and only within one unit. Verible ships this off; lucisv turns it on.
## invalid-system-task-function
Reports `$random`, `$srandom`, the `$dist_*` family and `$psprintf`, and names the replacement. The random family all draw from one global generator, so a call added anywhere reshuffles every other stream and a failing seed stops reproducing; `$psprintf` is a vendor spelling of `$sformatf`. Verible's `invalid-system-task-function`, same list, same default.
## mismatched-labels
Reports an end label that does not name the block it closes, and an `end : name` on a block that has none — both compile errors (IEEE 1800 §9.3.4). Every construct that may carry a footer label is checked with one answer: module, interface, program, package, class, function, task, `begin`, `fork`/`join`, generate block, clocking block, covergroup, property and sequence. Verible ships this off; lucisv turns it on and files it as an error.
## module-parameter
Reports more than one positional parameter override, which binds by order and silently changes what every instance elaborates to when a parameter is added or two are swapped. Verible's `module-parameter`, same default.
## module-port
Reports more than one positional port connection, for the same reason. A single-port instance has no order to get wrong and is left alone. Verible's `module-port`, same default.
## packed-dimensions-range-ordering
Reports a packed dimension that counts upwards (`[0:7]`, `[0:WIDTH-1]`), where bit 0 is the most significant one and every concatenation with an ordinary `[7:0]` vector silently reverses. Unpacked arrays are not judged — an ascending array is normal — and two symbolic bounds lucisv cannot compare are left alone. Verible's `packed-dimensions-range-ordering`, same default.
## plusarg-assignment
Reports `$test$plusargs`, which matches by *prefix* — `+foobar` makes `$test$plusargs("foo")` true — and asks for `$value$plusargs`, which matches the whole name and hands back the value. Verible's `plusarg-assignment`, same default.
## suspicious-semicolon
Reports `if (x);`, `for (…);`, `while (…);` and their relatives, where the `;` is the whole body and whatever is indented under it runs unconditionally. A deliberately empty body is `begin end` and is not reported. Verible ships this off; lucisv turns it on, because the finding is a typo rather than a matter of taste.
## truncated-numeric-literal
Reports a sized literal whose digits need more bits than it declares (`4'hFFF`), which most simulators truncate silently. Leading zeros do not count, and a literal whose digits are all `x`/`z` (`3'hz`) is left alone — those spell an unknown of that width. Verible's `truncated-numeric-literal`, same default.
## undeclared-identifier
Reports a name this file does not declare, that no external unit it names could supply, and that **no other file in the project writes down at all**. Every clause is an exclusion, and they are what make an error-class rule about names safe: no project behind the run means no opinion, and so do a name any macro, directive or attribute in the file writes down, a file that did not fully parse, and an `` `include``d fragment with no unit of its own. Measured on opentitan `hw/` and on lucisv's corpus: the same five findings, all real implicit nets in one ibex formal file. No Verible equivalent.
## undersized-binary-literal
Reports a sized binary literal that writes fewer digits than its width (`8'b1`), and its safe fix writes the extension the language would have applied — `0` for a literal starting with `0` or `1`, the unknown itself for one starting with `x` or `z`. A literal whose value is zero is exempt, matching Verible's `lint_zero` default. Verible's `undersized-binary-literal`, same bases, same defaults.
## unknown-parameter
Reports a `#(.NAME(…))` override naming a parameter the instantiated module does not declare — including a `localparam`, which is not overridable at all. It is silent whenever the project cannot answer: no project, an unindexed module, one declared twice with different headers, one whose header carries a compiler directive, a scope-qualified instantiation. Measured on opentitan: 4 findings, spot-checked true. No Verible equivalent.
## unknown-port
Reports a `.name(…)` connection naming a port the instantiated module does not declare — the port rename that reached three of four instantiations. Same silences as `unknown-parameter`; `.*` names nothing and is not judged. Measured on opentitan: 40 findings, spot-checked true, all in pre-silicon testbenches out of step with their RTL. No Verible equivalent.
## void-cast
Reports `void'(…)` around something that is not a call, where there is no return value to discard — the missing call, or the cast left over from an edit. Verible's `void-cast` forbids a *named list* of calls instead, so the two do not overlap; the named-call form is wave 2's business. Only a cast standing as a statement is judged.
+2 -1
View File
@@ -383,6 +383,7 @@ recursion-limit, whose edges sit in §2.1). Code edges:
| `sva-bodies ──▶ assertions / constraint-bodies / covergroup-bodies / comment-slots / refactor-rename / semantic-lints` | depends | (2026-09-02) The SVA half of coverage_gaps C1/M8. `property`/`sequence` declarations, concurrent `assert`/`assume`/`cover`/`restrict property`, `expect`, `cover sequence` and `default disable iff` are real nodes: `sequence_expr`/`property_expr` as one precedence-climbing extension of `parse_expr` (the README's table is IEEE 1800-2017 **Table 16-3** row by row — QA caught two rows transcribed from Table 11-2 instead: `nexttime`/`s_nexttime` sit on `not`'s row, and the whole loosest row — `always`/`eventually`/`accept_on`/`reject_on`/`sync_*`/`if`/`case` — is read position-independently with a `property_expr` operand at precedence 0; a right-associative operator at or below `iff` likewise reads its right operand at 0), typed formals, assertion variables, action blocks as the statements they are — behind a `Rewind` snapshot with a byte-exact per-construct verbatim fallback that fires on 0 of 4 792 files. Nothing reserved: operator words are text-matched in SVA position only. One layout rule: top-level `\|->`/`\|=>`/`##`/`and`/`or` break one per line at the parent's indent when the spec does not fit. SVA gap fuzzer 705/0; 46 attack pairs plus the accepted transformation; `verify.rs` untouched; `tests/census.rs::sva_lines` proves every changed line of the 49 moved files lies inside an SVA construct. Semantics: `SymbolKind::{Property, Sequence}`, `ScopeKind::PropSeq`, instances resolve in-file and cross-file (`FACTS_FORMAT` 15 → 16); rename/references/lints see inside; `Scope::sva_fallback_warnings` for what would fall back. Output moved in 13 corpus + 36 opentitan files, all inside assertion text. |
| `macro-word-census ──▶ semantic-lints-on / refactor-rename / index-persistence / lint-rules-2` | depends | (2026-09-02, TODO §29) `FileFacts::macro_words` (`words::harvest_raw`, tag `MW`, `FACTS_FORMAT` 16 → 17) and `WorkspaceIndex::files_naming_in_macros`; `lucisv_server::rename` warns about every file naming the old name inside a macro invocation that lies outside the set `rename_sources` built — the §2.9-18 ruling made real, nothing read. `vlog_refactor::Scope` promoted to the crate root (pure move). `lucisv check --rules-doc` prints `rules_markdown()` (§2.9-5). |
| `interface-dpi-arms ──▶ interfaces / dpi-export / comment-slots` | depends | (2026-09-02, TODO §30, M13) Modport method prototypes (`import task drive(int x)`) through `Parser::parse_tf_header`/`Fmt::tf_header`, the single header parse and print the function/task declarations now share; bound `Target::InScope` with the formals in a scope of their own; one prototype per `import`/`export` group (the comma list stays an error, recorded). Unnamed DPI formals behind `parse_tf_ports(allow_unnamed)`, the empty-name convention on `TfArg::name`. `const /*c*/ ref` gap owned (`TfArg::after_const`). Zero corpus population; 4 807 files byte-identical. |
| `statement-fences ──▶ format-fences / classes / shared-fence-filter / range-formatting` | depends | (2026-09-02, TODO §31, M9) Fences at statement level and inside class bodies; `protected_regions`/`is_protected` signatures untouched so `lucisv/src/lint.rs` and `lucisv_server/src/lint.rs` are byte-identical; `verify.rs` untouched. One narrowing: a fence written after code on the same line is an ordinary comment everywhere now (it already was at statement level and in the documented rule). |
| `constraint-bodies ──▶ classes / out-of-class-constraints / dv-statements / safety-net` | depends | (2026-09-02, round 1 of coverage_gaps C1) `ItemKind::Constraint(ConstraintDecl)` with a structured `ConstraintSet` (`Expr{soft}`, `Implication`, `If`, `Foreach`, `SolveBefore`, `Unique`, `DisableSoft`, `Directive`, `Empty`), `ExprKind::Dist`, and `WithConstraint.block` as `ConstraintBody::{Items, Verbatim}`. The parser takes a `Rewind` snapshot (cursor, **both pending-comment buckets**, depth, links, `open_conds`, diagnostics length), attempts the structured body, and on any error restores it and re-runs v0.26.0's verbatim capture character for character — so an unknown shape *is* the old behavior, not an approximation (pinned on text, slice and `col`). **No keywords reserved**: `soft`/`dist`/`solve`/`before` are matched by text like `restrict`, so `token.rs`, `pairs.rs`, the editor grammar and `tests/grammar.rs` are untouched and `logic before;` keeps working; `:=`/`:/` stay two tokens with a span-adjacency check (a `:/` token would swallow `:/* c */`). Canonical layout: one item per line, `}` at the header column, dist weights as a braced list; a `with` block keeps the source's one-line-or-not shape. `verify.rs` untouched; the constraint attack pairs re-derived plus new ones. Exhaustive arms paid in `format.rs`, `bind.rs`, `tests/spans.rs`; `visit.rs` gets an explicit no-op arm (no items/statements inside). **QA rework**: comments after the round's own text-matched words were dropped; the dev answered with an exhaustive gap fuzzer (a `/*C*/` in every inter-token gap of 15 fixtures, 358 gaps, format + idempotency demanded) and 14 named comment fields plus `ConstraintItemKind::takes_semi()` (one owner of the `;`) and `Parser::gap_before` (the closer-side twin of `take_before_open`); 96 regressions vs v0.26.0 became 40, all in shared machinery outside this lane — §2.9-22. Opentitan: 1 993 of 2 009 bodies structured (fallbacks: 10 macro-item bodies, 6 non-LRM shapes), failure set unchanged, per-file tolerant diagnostics identical, 48 DV files idempotent with comment streams byte-identical. |
| `covergroup-bodies ──▶ constraint-bodies / classes / safety-net` | depends | (2026-09-02, round 2 of coverage_gaps C1) `ItemKind::Covergroup(Box<CovergroupDecl>)` with `CoverItemKind::{Coverpoint, Cross, Option, Directive, Empty}`, `BinDecl { wildcard, kind, name, array, spec: BinSpec::{Values, Transitions, Default, DefaultSequence, Select}, with_expr, iff }`, `SelectExpr` for `binsof … intersect … && !binsof`, one `CoverageEvent` enum. Same `Rewind` fallback as constraints — v0.27.0's flat scan re-run character for character on any failure — and no keywords reserved (`coverpoint`, `bins`, `cross`, `binsof`, `intersect`, `wildcard`, `ignore_bins`, `illegal_bins`, `option`, `type_option` by text). **Two guards in shared expression machinery, the round's one risk**: `at_postfix_segment` refuses `[` followed by `*`/`->`/`=` (no index can start with those — it is what lets `1'b1[*5]` be a transition repeat), and a `no_with` flag while a bin spec operand is read (so the bin's own `with (…)` filter is not eaten as an array-method iterator argument); `(`-disambiguation is by position, the LRM's own rule. `plain_expr_list` → `plain_list` and `constraint_parens` → `guard_parens`, shared with `iff`/`with`. `verify.rs` untouched, twelve attack pairs. The gap fuzzer was built in from day one (329 gaps, 52 fail, all §2.9-22 shared machinery — *asserted* by running each shape outside a covergroup). Opentitan: 544 of 544 covergroups structured, 87/87 DV covergroup files idempotent, failure set and per-file diagnostics identical. `on_type.rs` keeps `covergroup` OPAQUE by argument. |
| `fragment-mode ──▶ error-recovery / define-table / lexer-cleanup / covergroup-bodies` | depends | (2026-09-02, coverage_gaps H4 corrected) Class-body and module-item `.svh` fragments already parsed — the file-scope item loop *is* the class-item loop; the three shapes that did not (statement lists, enum-member lists, cover-item lists) become `SourceFile::fragment: Option<Fragment>` (`items` empty iff `fragment` is `Some`). Detection is a whole-file rule, not an error-message match: the FIRST STRUCTURAL item failed (directives, macro items and null items are legal in every body and do not count; a tolerant `Ok` that recorded a diagnostic counts as failed — the `if … else` generate-vs-statement parity bug), the file does not open with a design-unit keyword, and a shape consumes the file to EOF, tried narrowest-first (cover items → enum members → statements: the wider grammars mis-read the narrower). Each shape re-lexes a fresh token stream — `Rewind` deliberately does not restore the tokens' comment buckets, right for verbatim captures and fatal here. Shared loops lifted (`parse_enum_members`, `parse_cover_items`); formatter prints a fragment at indent 0 through existing printers; binder gives statements a file `Block` scope and enum variants file scope; **no census change** (a fragment's variants are not exported — `pkg::CUSTOM_1` must not resolve to a name that does not exist), FACTS stays 12. Separately, the lexer continues a `` `define `` whose formal-argument `(` touches the name and is still open at end of line, no backslash needed until the list closes — `cip_base_vseq__tl_errors.svh`'s real blocker. Corpus 813 → 814/820; opentitan 12 → 10, exactly the two predicted files. |
@@ -560,7 +561,7 @@ update the filing README(s) and this file.
|---|---|---|---|
| 1 | `lucisv_core::path::normalize` — one `.`/`..` folding instead of three private copies (`filelist::Reader::normalize`, `config::Discovery::absolute`, `includes::normalize`, the last now `pub`) | include-nav; restated by file-operations | lucisv_core |
| 2 | A span for `DataType` (and `ExprKind::Cast::ty` tails) — the last thing keeping `vlog_semantic/src/scan.rs` alive | vlog-semantic (item 2); restated by class-semantics | vlog_parser |
| 3 | `fence::scan_nested` has no `ItemKind::Class` arm — formatter fences are inert inside class bodies (the `--fix` backstop still holds; asymmetry errs hands-off) | classes | vlog_formatter (fence.rs) |
| ~~3~~ | ~~`fence::scan_nested` has no `ItemKind::Class` arm — formatter fences are inert inside class bodies (the `--fix` backstop still holds; asymmetry errs hands-off)~~ — **delivered 2026-09-02 by statement-fences (TODO §31)**: `scan_nested` enters class bodies, functions, tasks, `always`/`initial`/`final`; statement lists (`begin…end`, `fork…join`, every compound body) are fenceable through `scan_stmt_scope`/`scan_nested_stmt` on the shared `scan_units`; `stmt_docs`/`stmt_seq` obey the two swallowed-unit rules; fence regions merge into `range.rs`'s plan (load-bearing — a fenced statement has no verbatim run behind it). A region opens only at a line start (`opens_line`), so `module m; // lucisv: off` no longer opens one — the rule the format-fences README has stated since round 1. Deferred with reasons: port lists, case-item label lists, same-line fences, `PropSeqDecl.locals`. Opentitan: 4 of its 9 fenced files now keep their fenced bytes. | classes | ~~vlog_formatter (fence.rs)~~ done |
| ~~4~~ | ~~A `lint` key in `lucisv.toml` (`[lint.<rule>]` config; selected-rules list) with CLI>config precedence~~ — **delivered 2026-09-02 by semantic-lints-on**: `[lint] select = […] / ignore = […]` in `lucisv.toml` (CLI over config, key by key; unknown rule names fail the run naming the file; `[lint.<rule>]` tables rejected by name — per-rule config stays filed) and `lucisv.lint.select/ignore` settings (registry-validated, republish on change). | linter-core; restated by lint-rules-2, semantic-lints, server-lint | ~~config-discovery / lucisv_core~~ done |
| ~~5~~ | ~~`lucisv check --rules-doc` printing `rules_markdown()`~~ — **delivered 2026-09-02 by macro-word-census (TODO §29.3)**: `lucisv check --rules-doc` prints `rules_markdown()` and exits 0, takes no files, is lint-only; the example binary is gone | lint-rules-2 | ~~crates/lucisv~~ done |
| ~~6~~ | ~~Workspace-wide "does any file mention this name" query — the precondition for the semantic lints defaulting on~~ — **delivered 2026-09-02 by semantic-lints-on**: `FileFacts::words` (one identifier harvest, `vlog_semantic::words`, lifted from the server's candidates) and `WorkspaceIndex::files_mentioning` / `mentioned_outside(name, own_file)`; `FACTS_FORMAT` 12 → 13. The three rules consult a `MentionOracle` and are on by default whenever one exists. | semantic-lints | ~~vlog_semantic (index)~~ done |
+9
View File
@@ -5,6 +5,15 @@ for you. The extension and its bundled language server share one version
number; the full engineering notes live in the
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
## 0.35.0 — 2026-09-02
- **Format fences work inside procedural blocks and classes.**
`// lucisv: off` … `// lucisv: on` now protects statements inside
`begin … end`, `fork … join`, function and task bodies and
`always`/`initial`/`final`, and items inside a class body — byte for
byte, including with range formatting. A fence must start its line;
one written after code on the same line is a plain comment.
## 0.34.0 — 2026-09-02
- **Rename warns about macro arguments it could not edit**, naming every
+25 -2
View File
@@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view,
then open a Verilog or SystemVerilog file. There is no separate server or CLI
setup.
The current release is **0.34.0**. Its platform packages include both
The current release is **0.35.0**. Its platform packages include both
`lucisv-server` and the `lucisv` command-line tool:
| Package target | Machines |
@@ -113,6 +113,8 @@ enabling both paths formats twice.
|---|---|
| Live parse diagnostics | Error-tolerant parsing keeps useful feedback flowing while code is half typed |
| Live lint diagnostics | The same lint registry as `lucisv check`, delivered through push or modern pull diagnostics |
| Severity per rule | Every rule is `error`, `warning` or `style`, and the squiggle is painted red, yellow or blue to match |
| Per-rule toggles | One setting per rule and one per severity class, all under `lucisv.lint.*`; changing any of them re-checks every open file immediately |
| Safe quick fixes | One lightbulb action per safe lint fix, plus **Fix all lucisv auto-fixable problems** |
| Waivers | `lucisv:` and Verible-compatible `verilog_lint:` line/range waivers are understood |
| Scope feedback | An unmatched `begin`/`end` or `fork`/`join` is colored as an error until its pair exists |
@@ -279,13 +281,29 @@ Server-side templates add `if`, `if/else`, `else if`, `case`, `for`, `while`,
| `lucisv.index.persist` | `true` | Remember what indexing each file found, so a reopen resumes instead of rescanning |
| `lucisv.index.cachePath` | `""` | Where that store lives; empty means the extension's own per-workspace storage folder |
| `lucisv.largeFile.threshold` | `4 MiB` | Size in bytes above which an opened file gets viewport-only highlighting and nothing else — no parsing, diagnostics, formatting, or indexing; `0` analyzes everything |
| `lucisv.lint.severity.error` | `true` | Run the rules for code that would very likely not compile; off silences the whole class |
| `lucisv.lint.severity.warning` | `true` | Run the rules for code that compiles and very likely does not mean what it says |
| `lucisv.lint.severity.style` | `true` | Run the rules for code that is correct and reads badly |
| `lucisv.lint.rules.<rule>` | `default` | One dropdown per rule — `default`, `on` or `off`. `default` is what the rule ships as, which the setting's own description names |
| `lucisv.lint.select` | `[]` | Power-user spelling of `lucisv check --select`: run exactly these rules, replacing the default set. A severity word (`error`, `warning`, `style`) stands for its whole class |
| `lucisv.lint.ignore` | `[]` | Power-user spelling of `--ignore`, and the off switch of last resort; takes a severity word too |
| `lucisv.formatOnSave` | `false` | Protocol save hook for editors without native format-on-save; keep off in VS Code. Its indent comes from `lucisv.toml` or `lucisv.indent`, never from the editor tab size, which the protocol does not send on this path |
| `lucisv.serverPath` | bundled | Explicit server override for advanced use; an unchanged setting uses the bundled server |
| `lucisv.verbose` | `false` | Print how long every operation took in the lucisv output channel — one `timing:` line per request, notification, scan, widen, buffer flush, and per request that had to wait behind a rescan. **Restarts the language server when changed**, because it is an argument the server is started with |
The six `lucisv.index.*` settings and `lucisv.largeFile.threshold` arrive with
the [large workspaces](#large-workspaces) work; everything else ships in
0.10.2.
0.10.2. The `lucisv.lint.*` settings are **generated from the rule registry**,
so a rule cannot ship without its toggle.
When several of them disagree, this is the order — each step may undo the one
above it:
1. what the rules themselves ship as (a project-wide rule needs a workspace);
2. a non-empty `lucisv.lint.select` replaces that set;
3. a severity switch that is off removes its whole class;
4. a per-rule dropdown set to `on` or `off` decides that one rule;
5. `lucisv.lint.ignore` removes, whatever anything else said.
A nearby `lucisv.toml` is the project source of truth and wins over editor
style settings. Each file discovers configuration upward, so one workspace may
@@ -326,6 +344,11 @@ Every nesting color is a proper VS Code theme color:
}
```
## Release 0.35.0 highlights
Version 0.35.0 lets format fences protect statements inside procedural
blocks, function and task bodies, and items inside class bodies.
## Release 0.34.0 highlights
Version 0.34.0 makes rename name the macro arguments it cannot edit,
+451 -1
View File
@@ -2,7 +2,7 @@
"name": "lucisv",
"displayName": "lucisv — Verilog/SystemVerilog",
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
"version": "0.34.0",
"version": "0.36.0",
"publisher": "guoliangchen",
"author": "Guoliang Chen",
"license": "MIT",
@@ -348,6 +348,456 @@
},
"default": [],
"markdownDescription": "Lint rules to drop from whatever `#lucisv.lint.select#` left — the editor's spelling of `lucisv check --ignore`. This is the off switch for the three rules that read the whole project rather than one file (`unused-signal`, `undriven-net`, `multiply-driven`): they are on by default wherever lucisv can see the other files of your workspace, because it can then tell that another file reads a signal through a hierarchical path. A name lucisv does not know is ignored. Takes effect immediately — every open file is re-checked."
},
"lucisv.lint.severity.error": {
"type": "boolean",
"default": true,
"order": 10,
"markdownDescription": "Run the **error** lint rules — code that would very likely fail to compile, elaborate or synthesize. Turning this off silences the whole class; a per-rule toggle below still has the last word, and `#lucisv.lint.ignore#` still removes a rule whatever else says. Takes effect immediately — every open file is re-checked."
},
"lucisv.lint.severity.warning": {
"type": "boolean",
"default": true,
"order": 11,
"markdownDescription": "Run the **warning** lint rules — code that compiles but very likely does not mean what it says. Turning this off silences the whole class; a per-rule toggle below still has the last word, and `#lucisv.lint.ignore#` still removes a rule whatever else says. Takes effect immediately — every open file is re-checked."
},
"lucisv.lint.severity.style": {
"type": "boolean",
"default": true,
"order": 12,
"markdownDescription": "Run the **style** lint rules — code that is correct and reads badly. Turning this off silences the whole class; a per-rule toggle below still has the last word, and `#lucisv.lint.ignore#` still removes a rule whatever else says. Takes effect immediately — every open file is re-checked."
},
"lucisv.lint.rules.duplicate-declaration": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 20,
"markdownDescription": "**error** — declare each name once per scope. On by default."
},
"lucisv.lint.rules.mismatched-labels": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 21,
"markdownDescription": "**error** — make an end label name the block it closes. On by default."
},
"lucisv.lint.rules.multiply-driven": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On where lucisv can see the project.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 22,
"markdownDescription": "**error** — give a variable exactly one driver. On where lucisv can see the project."
},
"lucisv.lint.rules.undeclared-identifier": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On where lucisv can see the project.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 23,
"markdownDescription": "**error** — use a name something declares. On where lucisv can see the project."
},
"lucisv.lint.rules.unknown-parameter": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On where lucisv can see the project.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 24,
"markdownDescription": "**error** — override only parameters the instantiated module declares. On where lucisv can see the project."
},
"lucisv.lint.rules.unknown-port": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On where lucisv can see the project.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 25,
"markdownDescription": "**error** — connect only ports the instantiated module declares. On where lucisv can see the project."
},
"lucisv.lint.rules.wire-reg-mixup": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 26,
"markdownDescription": "**error** — use `logic` instead of `reg` in SystemVerilog files. On by default."
},
"lucisv.lint.rules.always-comb-blocking": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 27,
"markdownDescription": "**warning** — assign with `=` inside always_comb. On by default."
},
"lucisv.lint.rules.always-ff-non-blocking": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 28,
"markdownDescription": "**warning** — assign with `<=` inside always_ff. On by default."
},
"lucisv.lint.rules.case-missing-default": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 29,
"markdownDescription": "**warning** — give every case statement a default branch. On by default."
},
"lucisv.lint.rules.explicit-function-task-parameter-type": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 30,
"markdownDescription": "**warning** — declare a storage type on every function and task argument. On by default."
},
"lucisv.lint.rules.forbid-defparam": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 31,
"markdownDescription": "**warning** — override a parameter at the instantiation, not with `defparam`. On by default."
},
"lucisv.lint.rules.forbid-negative-array-dim": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 32,
"markdownDescription": "**warning** — do not write a negative constant in a dimension. On by default."
},
"lucisv.lint.rules.incomplete-assignment": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 33,
"markdownDescription": "**warning** — assign every variable on every path of an always_comb. On by default."
},
"lucisv.lint.rules.instance-shadowing": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 34,
"markdownDescription": "**warning** — do not hide an enclosing declaration with a new one of the same name. On by default."
},
"lucisv.lint.rules.invalid-system-task-function": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 35,
"markdownDescription": "**warning** — do not call a deprecated or non-reproducible system task. On by default."
},
"lucisv.lint.rules.module-parameter": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 36,
"markdownDescription": "**warning** — override more than one parameter by name. On by default."
},
"lucisv.lint.rules.module-port": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 37,
"markdownDescription": "**warning** — connect an instance with more than one port by name. On by default."
},
"lucisv.lint.rules.packed-dimensions-range-ordering": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 38,
"markdownDescription": "**warning** — declare a packed dimension in decreasing order, `[N-1:0]`. On by default."
},
"lucisv.lint.rules.plusarg-assignment": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 39,
"markdownDescription": "**warning** — read a plusarg with `$value$plusargs`, not `$test$plusargs`. On by default."
},
"lucisv.lint.rules.suspicious-semicolon": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 40,
"markdownDescription": "**warning** — do not end a control statement's header with a `;`. On by default."
},
"lucisv.lint.rules.truncated-numeric-literal": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 41,
"markdownDescription": "**warning** — keep a sized literal inside the width it declares. On by default."
},
"lucisv.lint.rules.undersized-binary-literal": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 42,
"markdownDescription": "**warning** — write every bit of a sized binary literal. On by default."
},
"lucisv.lint.rules.undriven-net": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On where lucisv can see the project.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 43,
"markdownDescription": "**warning** — drive a signal that something reads. On where lucisv can see the project."
},
"lucisv.lint.rules.unused-signal": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On where lucisv can see the project.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 44,
"markdownDescription": "**warning** — delete a signal nothing uses. On where lucisv can see the project."
},
"lucisv.lint.rules.void-cast": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 45,
"markdownDescription": "**warning** — cast to `void` only what a call returns. On by default."
},
"lucisv.lint.rules.empty-item": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 46,
"markdownDescription": "**style** — drop a `;` that stands where an item belongs. On by default."
},
"lucisv.lint.rules.enum-name-style": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 47,
"markdownDescription": "**style** — name enum typedefs in lower_snake_case ending in _e or _t. On by default."
},
"lucisv.lint.rules.explicit-parameter-storage-type": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 48,
"markdownDescription": "**style** — declare a storage type on every parameter. On by default."
},
"lucisv.lint.rules.module-filename": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 49,
"markdownDescription": "**style** — name a one-module file after its module. On by default."
},
"lucisv.lint.rules.module-name-style": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: Off by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 50,
"markdownDescription": "**style** — name modules in lower_snake_case. Off by default."
},
"lucisv.lint.rules.no-tabs": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 51,
"markdownDescription": "**style** — use spaces, not tabs. On by default."
},
"lucisv.lint.rules.no-trailing-whitespace": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 52,
"markdownDescription": "**style** — no whitespace at the end of a line. On by default."
},
"lucisv.lint.rules.parameter-name-style": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 53,
"markdownDescription": "**style** — name parameters in CamelCase or ALL_CAPS. On by default."
},
"lucisv.lint.rules.struct-union-name-style": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 54,
"markdownDescription": "**style** — name struct and union typedefs in lower_snake_case ending in _t. On by default."
},
"lucisv.lint.rules.unused-waiver": {
"type": "string",
"enum": ["default", "on", "off"],
"enumDescriptions": [
"Leave it as it ships: On by default.",
"Always run this rule.",
"Never run this rule."
],
"default": "default",
"order": 55,
"markdownDescription": "**style** — remove waivers that no longer suppress anything. On by default."
}
}
}
Executable
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env bash
# Run a command under a memory and wall-clock guard.
#
# Usage: tools/guard.sh [-m MAX_GB] [-t MAX_SECONDS] -- <command...>
# tools/guard.sh -m 8 -t 900 -- cargo test --workspace
#
# Every second the resident set of the command's whole process tree is
# summed; if it exceeds MAX_GB (default 8) or the clock exceeds MAX_SECONDS
# (default 1800) the tree is killed (TERM, then KILL) and the script exits
# 137 with a line saying why. Exists because a runaway test or sweep once
# consumed 100 GB and took the machine down (2026-09-03): agents run every
# test suite, fuzzer and corpus/opentitan sweep through this.
#
# macOS has no enforced `ulimit -v`, so the guard is a poller, not a cap:
# a process that allocates faster than one second's worth of headroom can
# still overshoot briefly. Standard tooling only (ps, awk, kill).
set -u
max_gb=8
max_s=1800
while [ $# -gt 0 ]; do
case $1 in
-m) max_gb=$2; shift 2 ;;
-t) max_s=$2; shift 2 ;;
--) shift; break ;;
*) echo "usage: $0 [-m MAX_GB] [-t MAX_SECONDS] -- <command...>" >&2; exit 2 ;;
esac
done
[ $# -gt 0 ] || { echo "guard.sh: no command" >&2; exit 2; }
"$@" &
root=$!
start=$(date +%s)
# The command's process tree: descendants by parent pid, transitively.
tree() {
local all="$1" next
while :; do
next=$(ps -axo pid=,ppid= | awk -v set=" $all " '
{ if (index(set, " " $2 " ") > 0 && index(set, " " $1 " ") == 0) printf "%s ", $1 }')
[ -z "$next" ] && break
all="$all $next"
done
echo "$all"
}
kill_tree() {
local pids; pids=$(tree "$root")
kill -TERM $pids 2>/dev/null
sleep 2
kill -KILL $pids 2>/dev/null
}
max_kb=$((max_gb * 1024 * 1024))
while kill -0 "$root" 2>/dev/null; do
pids=$(tree "$root")
rss=$(ps -o rss= -p $(echo "$pids" | tr ' ' ',') 2>/dev/null | awk '{s+=$1} END {print s+0}')
now=$(date +%s)
if [ "$rss" -gt "$max_kb" ]; then
echo "guard.sh: memory ${rss} kB exceeded ${max_gb} GB — killing: $*" >&2
kill_tree; exit 137
fi
if [ $((now - start)) -gt "$max_s" ]; then
echo "guard.sh: ${max_s} s exceeded — killing: $*" >&2
kill_tree; exit 137
fi
sleep 1
done
wait "$root"