Compare commits

...
19 Commits
Author SHA1 Message Date
lucioandClaude Fable 5 a896e0dff0 Release 0.38.0 — lint rule options and the Style family
ci / checks (push) Successful in 1m5s
ci / corpus (push) Successful in 33s
release / build-and-publish (push) Successful in 11m24s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:46:03 -05:00
lucioandClaude Fable 5 0cb398bcd9 merge follow-up: §34's port walkers read ANSI port lists through ListElem::ok (§32's error elements)
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:39:00 -05:00
lucio 17697b9d77 Merge branch 'lint-2' 2026-09-04 03:36:59 -05:00
lucioandClaude Fable 5 5e5813a2a9 Linter expansion, wave 2: per-rule options end to end, options on the naming rules, and eighteen Style rules
TODO section 34 (36 -> 54 rules).
Options: OptionSpec/OptionKind/OptionValue/RuleOptions in vlog_linter
with one validator behind both front ends - [lint.<rule>] tables in
lucisv.toml (accepted now; stored raw by lucisv_core::config, resolved
per file by the CLI with <config>:<line> on the first bad entry) and
the editor's lucisv.lint.options object (bad entries logged and
dropped) - precedence editor > toml > default key by key, --rules-doc
listing every option. A small anchored regex engine of our own: a
Thompson-NFA simulation, linear in pattern x name by construction
(QA's first cut found the backtracking matcher exponential on (a*)*b),
unknown escapes refused by name through both doors, a 71-row table
verified against CPython. The four naming rules take Verible's option
spellings with defaults that keep today's verdicts byte-identical.
Eighteen Style rules, one file each with true positives and near-
misses: line-length (the formatter's width), posix-eof (safe fix),
forbid-consecutive-null-statements (safe fix), generate-label and
generate-label-prefix, package-filename, one-module-per-file (off),
signal/interface/macro/constraint/parameter-type-name-style,
port-name-suffix (off), banned-declared-name-patterns (off),
typedef-enums, typedef-structs-unions (allow_anonymous_nested defaults
true here - opentitan's 3 159 findings were all generated register
packages, and its own config disables the rule), always-comb (unsafe
fix), explicit-begin (off, Verible's eleven enables). Four rules ask
parsed_cleanly() first after a census showed error-recovered UVM files
rebound as generate blocks. package.json regenerated (drift test).
3 549 tests / 48 binaries; corpus 814/820 byte-identical; naming-rule
finding lists identical to 0.36.0; opentitan check timing unchanged.

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

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:36:59 -05:00
lucioandClaude Fable 5 bafc1b425b docs: header-recovery QA follow-up — the fuzz sweep's time-based guard kill isolated; no hang (max single parse 38 ms over the whole file)
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 29s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:25:52 -05:00
lucioandClaude Fable 5 8c61570a04 tools/guard.sh: keep the command's stdin (a backgrounded job got /dev/null, silently emptying stdin-fed lucisv runs)
ci / checks (push) Successful in 1m7s
ci / corpus (push) Successful in 31s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:09:29 -05:00
lucioandClaude Fable 5 7c4bdbcfea Release 0.37.0 — error recovery inside headers and lists
ci / checks (push) Successful in 1m8s
ci / corpus (push) Successful in 33s
release / build-and-publish (push) Successful in 9m43s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:08:47 -05:00
lucioandClaude Fable 5 e902af37c5 docs: topo — header-recovery row, §2.9-24 filed (half-typed #( override that reads as a call)
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:08:47 -05:00
lucio 4ba6eafa2d Merge branch 'wip-header-recovery'
# Conflicts:
#	crates/vlog_linter/src/visit.rs
2026-09-04 03:01:49 -05:00
lucioandClaude Fable 5 747ae02b0e Error recovery inside headers and lists: error elements, a list-local bracket-seeded sync that cannot stall, headers keep their node
TODO section 32 (coverage_gaps M10).
A typo inside a port list, parameter list, tf-port list, connection
list or a for/if/while/case header no longer destroys the enclosing
module or function. The four list element types and ExprKind gain an
Error(RawText) element; element_or_recover records the diagnostic and
skips to a list-local sync set (',' ')' ';' or a line change) with the
bracket counter seeded from the list's own opener, and list_ends ends
any list whose iteration left the cursor unmoved - the structural
guarantee that closes the non-advancing loop which exhausted memory on
the first cut. Headers are infallible in tolerant mode: the node keeps
its name, the typed elements and its body, so the body binds in the
right scope and there is no orphaned closer; recovery declines on a
conditional-compilation directive so split.rs's verbatim rescue still
runs and strict parity holds (550 fixtures and all 814 strict-parsing
corpus files, Debug-equal). Pins per shape with exact counts; server
pins: document symbols and scoped completion survive a broken header,
one diagnostic, the three validity probes keep their verdicts.
Census over the corpus truncated at each midpoint: error nodes 622 ->
555, diagnostics 1 702 -> 1 826 (surviving modules now report their
missing endmodule). parse_tolerant timing within noise. 3 259 tests on
this branch (0.35.0 + 15 pins); corpus 814/820 byte-identical.

docs/features/header-recovery/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 02:58:24 -05:00
lucioandClaude Fable 5 ffbb29ddbb Release 0.36.1 — 0.36.0 with its release notes (that tag never published: no CHANGELOG section)
ci / checks (push) Successful in 1m8s
ci / corpus (push) Successful in 31s
release / build-and-publish (push) Successful in 11m34s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 02:42:32 -05:00
lucioandClaude Fable 5 f1d44a2a0c WIP checkpoint, §32 paused 2026-09-03 — runaway root cause fixed (list_ends on an unmoved cursor), strict parity restored; 32.1–32.5 done, 32.6 half, 32.7 + gates not run
Root cause of the 100 GB crash: a non-ANSI port loop took its trailing
comma from the element, an error element never got that far, the next
iteration failed on the same comma, consumed nothing and pushed another
empty error element - an allocating spin. Fix is structural: list_ends
ends the list whenever the cursor has not moved since the iteration
began; the two loops that read their own separator also eat it after an
error element. Truncate-anywhere + delete-any-character pass under
tools/guard.sh -m 4. Strict parity: element_or_recover declines on a
conditional-compilation directive so split.rs's verbatim rescue still
runs. cargo test -p vlog_parser 365 + 26 + 31 / 0 failed; workspace
suite NOT re-run since the last fixes. Not done: completion pin + the
three validity probes (32.6), measurements (32.7), README amendments,
coverage_gaps M10, TODO ticks, every gate. Handshake: three
vlog_linter arms (visit.rs walk_param_ports, signals.rs connection
loops) live in the earlier commit 6a15594.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 18:28:33 -07:00
lucioandClaude Fable 5 10b63e665d docs: linter-expansion-1 review — opentitan lint timing re-measured at merge (no difference vs 0.35.0)
ci / checks (push) Successful in 1m5s
ci / corpus (push) Successful in 27s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 18:01:24 -07:00
lucioandClaude Fable 5 a648561f63 TODO §34 planned in detail: per-rule lint options end to end, options on the naming rules, the first eighteen Style rules; the rest deferred to §35
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 18:00:45 -07:00
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 6a15594ae8 WIP §32 header recovery — DO NOT MERGE: half-finished; a fuzz test loops without advancing and exhausts memory (crashed the machine 2026-09-03)
Checkpoint of the interrupted dev work (rate limit) so master stays
clean. Known state: a_half_typed_instantiation_is_one_error_node
(expected to invert) and tolerant_parse_equals_strict_parse_on_valid_
sources FAIL; the error_recovery test binary exceeds 6 GB under
tools/guard.sh (a non-advancing recovery loop under the delete-any-
character / truncate fuzzers). Resume in a worktree of this branch,
under tools/guard.sh, fixing the advance guarantee first.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 17:48:28 -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
169 changed files with 16778 additions and 751 deletions

No files matched your search

+98
View File
@@ -4,6 +4,104 @@ 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.38.0 — 2026-09-04
### Lint rule options, and the Style family
**Per-rule options.** A rule that takes options can be configured in
`lucisv.toml` (`[lint.line-length] length = 120`,
`[lint.signal-name-style] style_regex = "[a-z_0-9]+"`) and from the
editor (`lucisv.lint.options`, one object keyed by rule). Both doors run
one validator: a bad key, kind, range or pattern fails `lucisv check`
naming the file and line, and is logged and dropped in the editor so a
typo cannot switch a rule off. Editor options win over `lucisv.toml`,
key by key. `--rules-doc` lists every option with its kind and default.
Patterns use a small built-in regex dialect (literals, `.`, classes,
groups, alternation, `* + ?`, `\d \w \s`), whole-name anchored, run as
a linear-time automaton so no pattern can slow a lint run; anything
outside the dialect is refused by name.
**Eighteen new Style rules** (54 in all): `line-length` (the
formatter's width), `posix-eof` (safe fix), `forbid-consecutive-null-
statements` (safe fix), `generate-label`, `generate-label-prefix`,
`package-filename`, `one-module-per-file` (off), `signal-name-style`
(off), `interface-name-style`, `macro-name-style`,
`constraint-name-style`, `parameter-type-name-style` (off),
`port-name-suffix` (off), `banned-declared-name-patterns` (off),
`typedef-enums`, `typedef-structs-unions`, `always-comb` (unsafe fix),
`explicit-begin` (off). The four existing naming rules take Verible's
option spellings. `typedef-structs-unions` allows a nested anonymous
aggregate by default — a deliberate divergence from Verible, because
every one of its 3 159 findings on opentitan was a generated register
package; `allow_anonymous_nested = false` restores the stricter reading.
Every rule's toggle in VS Code is regenerated from the registry.
## 0.37.0 — 2026-09-04
### Typing a header no longer loses the module
While you type a port list, a parameter list, a function's argument
list, an instantiation's connections, or the header of a `for`/`if`/
`while`/`case`, the editor used to lose the whole surrounding module or
function: its body re-parsed at file scope, its symbols vanished from
the outline and from completion, and the orphaned `endmodule` produced a
second error. Recovery now happens inside the list: the element that
failed becomes an error element, the ones you already typed stay, the
header keeps its node, and the body binds in the right scope. One
diagnostic per typo. The strict parse (what the formatter uses) is
untouched, so every corpus file formats byte for byte as before.
Measured over the corpus with every file cut in half: error nodes fall
by 11 %; diagnostics rise by 7 % because a module whose header was cut
now survives to report its missing `endmodule` instead of vanishing
into one error node. Known gap: a half-typed `#(` override whose value
can read as a call still collapses its instantiation (filed).
## 0.36.1 — 2026-09-04
The 0.36.0 tag never published: its release commit shipped without a
CHANGELOG section (the release chain's draft lived in a session
scratchpad that a crash had wiped), and the release workflow refuses a
version without notes, as designed. 0.36.1 is 0.36.0 plus these notes.
## 0.36.0 — 2026-09-03
### The linter grows up: severities, per-rule toggles, and 19 new rules
Every lint rule now has a **severity** — `error` (would likely fail to
compile or elaborate, or silently mis-synthesize), `warning` (a probable
bug) or `style` — printed in `lucisv check` output
(`FILE:LINE:COL: warning: message [rule]`), carried in the JSON output,
mapped to red / yellow / blue in the editor, and shown in
`--rules-doc`, which now groups rules by class. `--select`, `--ignore`
and `[lint]` in `lucisv.toml` accept a severity word (`--ignore style`).
**Editor toggles.** VS Code settings gain three master switches
(`lucisv.lint.severity.error`, `.warning`, `.style`) and one setting per
rule (`lucisv.lint.rules.<rule>`: `default` / `on` / `off`), generated
from the rule registry so the list can never drift. Precedence, top to
bottom: defaults → `select` → severity switches → per-rule settings →
`ignore`. Changing any of them re-checks every open file.
**New rules — Error**: `mismatched-labels`, `duplicate-declaration`,
`undeclared-identifier` (with a project; silent for names that come
from macros, `` `include``d fragments or hierarchical paths),
`unknown-port`, `unknown-parameter`.
**New rules — Warning**: `forbid-defparam`, `invalid-system-task-function`,
`truncated-numeric-literal`, `undersized-binary-literal` (safe fix pads),
`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` (latch inference in `always_comb`).
Verible equivalents are named in each rule's documentation; defaults
follow Verible's except where the doc says why not. Existing rules
re-classified: `multiply-driven` and `wire-reg-mixup` are errors.
Measured on opentitan: every false-positive class found was closed with
a test; `lucisv check` over its `hw/` tree runs in the same time as
0.35.0.
## 0.35.0 — 2026-09-02
### Format fences reach statements and class bodies
+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.35.0"
version = "0.38.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.35.0"
version = "0.38.0"
[[package]]
name = "lucisv_server"
version = "0.35.0"
version = "0.38.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.35.0"
version = "0.38.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.35.0"
version = "0.38.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -264,11 +264,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.35.0"
version = "0.38.0"
[[package]]
name = "vlog_refactor"
version = "0.35.0"
version = "0.38.0"
dependencies = [
"vlog_parser",
"vlog_semantic",
@@ -276,7 +276,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.35.0"
version = "0.38.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.35.0"
version = "0.38.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+163 -21
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,35 +186,175 @@ 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) |
| `line-length` | style | — | no line wider than the width the formatter uses |
| `posix-eof` | style | safe | the file ends with a newline |
| `forbid-consecutive-null-statements` | style | safe | no `;;` where a statement belongs |
| `generate-label` | style | — | every generate block carries a `: label` |
| `generate-label-prefix` | style | — | that label starts with `g_` or `gen_` |
| `package-filename` | style | — | a one-package file is named after its package |
| `interface-name-style` | style | — | `lower_snake_case` ending `_if` |
| `macro-name-style` | style | — | a `` `define`` name is `ALL_CAPS` |
| `constraint-name-style` | style | — | `lower_snake_case` ending `_c` |
| `typedef-enums` | style | — | an `enum` type is named with a `typedef` |
| `typedef-structs-unions` | style | — | a `struct`/`union` type is named with a `typedef` |
| `always-comb` | style | unsafe | `always_comb`, not `always @*` |
| `signal-name-style` | style | — | `lower_snake_case` signals (off by default) |
| `parameter-type-name-style` | style | — | `lower_snake_case` ending `_t` type parameters (off) |
| `port-name-suffix` | style | — | `_i` / `_o` / `_io` say which way a port points (off) |
| `one-module-per-file` | style | — | one `module` per file (off by default) |
| `banned-declared-name-patterns` | style | — | no declared name matching a project's own list (off) |
| `explicit-begin` | style | safe | every body is a `begin ... end` block (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
rule ships an unsafe fix yet. Violations inside a `// verilog_format: off`
that cannot change what the code means), `--unsafe-fixes` widens that to the
rest. One rule ships an unsafe fix: `always-comb` rewrites `always @*` to
`always_comb`, which is a different block at time zero and makes a second
driver of its outputs an error — right nearly always, and not lucisv's call to
make without being asked. Violations inside a `// verilog_format: off`
region are reported but never fixed: `off` means hands-off for the linter too,
so `--fix` leaves every byte of a fenced region exactly as written.
### Rule options
A rule can be configured in a `[lint.<rule-name>]` table:
```toml
[lint]
ignore = ["typedef-structs-unions"]
[lint.line-length]
length = 120 # the linter's limit, if not the formatter's
[lint.generate-label-prefix]
prefix = ["g_", "gen_"] # the label prefixes this project writes
[lint.parameter-name-style]
localparam_style = "CamelCase" # Verible's own default, stricter than ours
[lint.signal-name-style]
style_regex = "[a-z][a-z_0-9]*" # a pattern, matched against the whole name
```
The keys are Verible's wherever it has the same option, so a `.rules.verible`
file translates word for word. An option nobody sets reads the default
`lucisv check --rules-doc` prints beside it. An unknown rule or option name, a
value of the wrong kind, an integer out of range or a pattern that does not
compile **fails the run**, naming the config file and the line — a typo in a
lint setting is not something to guess at.
Patterns are not full RE2. What is supported: literals, `.`, `[...]` classes
with ranges and negation, the escapes `\d \D \w \W \s \S` (character
classes), `\n \t \r` (control characters) and `\<punctuation>` (that
character, literally), groups, `|`, and the postfix `*` `+` `?` — matched
against the **whole** name, so `^`/`$` are accepted and redundant.
Everything else is **refused when the option is read, by name**: counted
repetition (`{2,3}`), lookaround and flag groups (`(?=…)`, `(?:…)`), and every
escape not listed above — a backreference (`\1`), a word boundary (`\b`),
`\A`, `\z`, `\p{…}`, `\x41`. An unsupported escape read as a literal would
quietly judge the wrong names (`\bword\b` would match `bwordb`), which is
worse than an error you can read.
Matching is a Thompson-NFA simulation, so it is linear in pattern × name
length whatever shape the pattern has: no pattern can make `lucisv check` — or
an editor session — hang.
From an editor the same options are one object, `lucisv.lint.options`:
```json
"lucisv.lint.options": {
"line-length": { "length": 120 },
"typedef-structs-unions": { "allow_anonymous_nested": false }
}
```
There the precedence is **the editor's value, then the `lucisv.toml`, then the
rule's default — key by key**: a project can set two options and one user
override the third without losing the others. (This is the opposite order to
the formatting settings, where a checked-in `lucisv.toml` outranks the editor:
formatting has a byte-exact contract with CI, and which findings you are shown
in your own editor is yours to choose.) A bad entry there is *ignored* and
reported in the lucisv log rather than fatal, so one typo cannot leave a
session with no diagnostics.
### Waivers
```systemverilog
+143 -38
View File
@@ -3454,21 +3454,24 @@ only), crates/lucisv_server/src/perf.rs (measurement only), docs/
features/header-recovery/README.md (new), amendments in error-recovery
README, docs/coverage_gaps.md M10, TODO §32. Runs after §31 (parser +
formatter collide with §30's tf.rs/module.rs at merge; sequential).
- [ ] 32.1 error elements in the four list types + `ExprKind::Error`;
cross-crate arms pre-agreed
- [ ] 32.2 `element_or_recover` with the list-local, bracket-seeded
- [x] 32.1 error elements in the four list types + `ExprKind::Error`;
cross-crate arms pre-agreed — one generic `ListElem<T>` over five
lists (a class's parameter ports are the fifth)
- [x] 32.2 `element_or_recover` with the list-local, bracket-seeded
sync set (`,` `)` `;` line change)
- [ ] 32.3 headers keep their node (port, param, tf-port, connection
- [x] 32.3 headers keep their node (port, param, tf-port, connection
lists infallible in tolerant mode; closers via `expect_closer`)
- [ ] 32.4 `for`/`if`/`while`/`case` conditions recover inside the
parentheses
- [ ] 32.5 parser pins per shape with exact counts; walkers extended;
- [x] 32.4 `for`/`if`/`while`/`case` conditions recover inside the
parentheses (`repeat` and `do…while` too, same helper)
- [x] 32.5 parser pins per shape with exact counts; walkers extended;
550-source equality and the fuzzers green
- [ ] 32.6 server pins: symbols survive, completion scope survives, one
- [x] 32.6 server pins: symbols survive, completion scope survives, one
diagnostic, validity probes unchanged
- [ ] 32.7 docs + measurements (parse_tolerant timing, truncated-corpus
diagnostic census)
- [ ] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
- [x] 32.7 docs + measurements (parse_tolerant timing, truncated-corpus
diagnostic census — error nodes 622 → 555, diagnostics 1 702 →
1 826: the constructs that now survive report their own missing
closers)
- [x] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
byte-identical (strict path untouched); opentitan read-only sweep
unchanged
- [ ] QA: type each of the (a)–(f) shapes into the real server against
@@ -3630,45 +3633,147 @@ additive, say so in Handshakes), crates/lucisv/src/{lint.rs, args.rs}
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`.
- [ ] 33.0 `Severity` on every rule; select/ignore by severity; CLI
- [x] 33.0 `Severity` on every rule; select/ignore by severity; CLI
text/JSON; editor severities; `--rules-doc` grouped
- [ ] 33.1 package.json toggles generated + drift test; `enabled_rules`
- [x] 33.1 package.json toggles generated + drift test; `enabled_rules`
precedence pinned; republish on change
- [ ] 33.2 Error rules: mismatched-labels, duplicate-declaration,
- [x] 33.2 Error rules: mismatched-labels, duplicate-declaration,
undeclared-identifier (measured; default decided by the count),
unknown-port, unknown-parameter
- [ ] 33.3 Warning rules: the thirteen listed, each with tests and an
- [x] 33.3 Warning rules: the thirteen listed, each with tests and an
opentitan count
- [ ] 33.4 docs; measurements table in the README
- [ ] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
- [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
## 34. Linter expansion, wave 2 (planned 2026-09-03) — per-rule options, and the first eighteen Style rules
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`,
After §33 (36 rules, severities, toggles). Two things this wave adds:
the **option plumbing** every configurable rule needs, and the Style
rules from Verible's list that carry the most weight in a style guide
(naming, file layout, generate labels, typedefs, line length). Dev
Opus 5, QA Sonnet 5. Feature README: `docs/features/linter-expansion-2/
README.md`. Mapped: `lucisv_core::config` parses one table, `[lint]`,
with `select`/`ignore`, and rejects `[lint.<rule>]` by name
(`config.rs::parse_entry`: "per-rule lint settings … are not supported
yet"); the editor has `lucisv.lint.select/ignore/severity.*/rules.*`;
`Rule` has no notion of options; `LintContext` carries source, tokens,
tree, semantics slot and the oracle; `line-length` already lives in
`FileConfig` for the formatter.
**34.0 Options, end to end.**
(a) `vlog_linter`: `pub struct OptionSpec { name: &'static str, kind:
OptionKind (Bool | Int { min, max } | Str | Regex | List), default:
OptionValue, doc: &'static str }` and `Rule::options(&self) ->
&'static [OptionSpec]` (default empty); `RuleOptions` — a validated
map `rule → key → OptionValue` built by `RuleOptions::parse(rule, key,
raw)` that rejects an unknown key ("rule `x` has no option `y`; it has:
…"), a wrong kind, an out-of-range int or an invalid regex, each with
the message the two front ends print with file and line. `LintContext`
carries `&RuleOptions`; a rule reads `ctx.option_str(NAME, "pattern")`
etc. with the spec's default as the fallback, so a rule never sees
"unset". (b) `lucisv_core::config`: `[lint.<rule>]` tables accepted —
`key = value` for bool/int/string, `key = ["a", "b"]` for lists —
stored raw in `FileConfig::lint_options: Vec<(rule, key, raw, line)>`
(the core crate does not know the rules); the CLI resolves them
against the registry per file the way `[lint] select` names are
checked, failing the run with file:line on the first bad entry. (c)
Editor: `lucisv.lint.options` (object; `{"<rule>": {"<key>": value}}`,
`additionalProperties`), parsed in `settings.rs`, validated the same
way — a bad entry is a `window/logMessage` warning and is ignored, so
one typo cannot switch the linter off; republish on change. (d)
Precedence: editor options over `lucisv.toml` options over the spec
default, key by key (the same ladder `lucisv.lineLength` uses — cite
`format::settings_for`). (e) `--rules-doc` lists each rule's options
with kind, default and doc; the VS Code generator emits nothing per
option (the object setting covers them) but its description names the
options each rule takes. (f) Pins: parse/validate table tests; a
`lucisv.toml` with `[lint.line-length] length = 120` changes the
verdict; the editor object does the same over the wire; a bad key
fails the CLI naming file:line and only logs in the editor.
**34.1 Options on the existing naming rules** (so the family is
consistent before the new members arrive): `enum-name-style`,
`struct-union-name-style`, `module-name-style`, `parameter-name-style`
gain the option Verible gives them (`style_regex`; `parameter-name-
style` gets `localparam_style`/`parameter_style` with Verible's
`CamelCase|ALL_CAPS` vocabulary plus the `_regex` overrides); defaults
reproduce today's behaviour exactly (pin: the corpus and opentitan
finding lists are byte-identical with no options set).
**34.2 New Style rules** (Verible name; default there → here; options):
- `line-length` (on; `length`, default = the formatter's configured
`line-length`, else 100) — a token-aware check that ignores a line
that is one unbreakable token (a long string or macro invocation),
as Verible does.
- `posix-eof` (on; safe fix appends the newline).
- `forbid-consecutive-null-statements` (on; safe fix) — `;;` at
statement level, the statement twin of `empty-item`.
- `generate-label` (on) and `generate-label-prefix` (on; `prefix`
list, default `g_`/`gen_`).
- `package-filename` (on; `allow-dash-for-underscore`, same as
`module-filename`).
- `one-module-per-file` (off).
- `signal-name-style` (off; `style_regex`, default `[a-z_0-9]+`).
- `interface-name-style` (on; `style_regex`, default `[a-z_0-9]+(_if)`).
- `macro-name-style` (on; `style_regex`, default `[A-Z_0-9]+`; the
macro's own name from the `` `define`` table).
- `constraint-name-style` (on; `pattern`, default `([a-z0-9]+_)+c`).
- `parameter-type-name-style` (off; lower_snake + `_t`).
- `port-name-suffix` (off; `_i`/`_o`/`_io`/`_ni`/`_no`/`_nio` per
Verible; option `suffixes` list).
- `banned-declared-name-patterns` (off; `patterns` list of regexes).
- `typedef-enums` (on) and `typedef-structs-unions` (on;
`allow_anonymous_nested`).
- `always-comb` (on; **unsafe** fix rewriting `always @*`/`@(*)` to
`always_comb` — the two are not identical at time zero, so the fix is
offered but not applied by default).
- `explicit-begin` (off; the eleven `*_enable` bool options Verible
has; safe fix wraps the body in `begin`/`end`).
Each: its own file, true positives and near-misses, a `.lint` case,
corpus + opentitan counts with ten findings read and classified;
opentitan is Verible-clean for its `dvsim` filesets, so a
Verible-default rule that fires inside them needs an explanation.
**34.3 Docs and toggles.** The VS Code generator regenerates the 18 new
`lucisv.lint.rules.*` entries (the drift test enforces it); README.md
"Linting" gains the options section and the rows; `editors/vscode/
README.md` documents `lucisv.lint.options`; the docs-site rules page
gains the sections; CHANGELOG untouched (the lead writes it).
Remaining Verible rules — `module-begin-block`, `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.
`unpacked-dimensions-range-ordering`, `uvm-macro-semicolon`,
`create-object-name-match`, `numeric-format-string-style`,
`macro-string-concatenation`, `disable-statement`, `forbidden-macro`/
`forbidden-symbol`, `endif-comment`, `forbid-line-continuations`,
`dff-name-style`, `proper-parameter-declaration` — are §35, wave 3.
Files: crates/vlog_linter/src/{registry.rs (OptionSpec, options()),
options.rs (new: OptionKind/OptionValue/RuleOptions), context.rs,
rule_docs.rs, vscode.rs, lib.rs, rules/<new>.rs, rules/<naming>.rs}
+ tests/cases/*.lint, crates/lucisv_core/src/config.rs (+ tests),
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/.../reference/rules.md,
docs/features/linter-expansion-2/README.md (new), TODO §34. Worktree
`lint-2`; disjoint from §32 (parser) so the two may run in parallel.
Every suite and sweep under `tools/guard.sh`.
- [x] 34.0 options end to end (spec, validation, toml table, editor
object, precedence, --rules-doc); pins
- [x] 34.1 options on the four existing naming rules; defaults
byte-identical
- [x] 34.2 the eighteen Style rules, each with tests, counts and ten
classified findings
- [x] 34.3 docs + regenerated toggles
- [x] Gates (guarded): fmt/clippy/`cargo test --workspace`; corpus
814/820 byte-identical; vsix smoke; opentitan read-only census +
timing vs 0.36.0
- [ ] QA: options attacked (bad key/kind/range/regex on both front
ends), every rule with near-misses, the census re-read
+134 -22
View File
@@ -14,7 +14,9 @@ use rayon::prelude::*;
use vlog_formatter::fence::{self, Region};
use vlog_formatter::Config;
use vlog_linter::words;
use vlog_linter::{apply_fixes, lint, Fix, MentionOracle, ParsedSource, Rule, Violation};
use vlog_linter::{
apply_fixes, lint, Fix, MentionOracle, ParsedSource, Rule, RuleOptions, Violation,
};
use vlog_parser::LineIndex;
use crate::args::{Options, OutputFormat};
@@ -31,6 +33,9 @@ pub struct Job {
path: PathBuf,
config: Config,
rules: Vec<&'static dyn Rule>,
/// What this file's `lucisv.toml` configured about each rule, validated
/// against the registry when the run was planned.
options: RuleOptions,
}
/// A whole `lucisv check` run: what to lint, and what the project says about
@@ -50,6 +55,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 +68,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 +140,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.
@@ -117,13 +168,53 @@ pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Res
let ignore = pick(&opts.ignore, file_config.lint_ignore.as_deref());
let rules = vlog_linter::select_rules(select, ignore, workspace)
.map_err(|e| format!("{}: {e}", path.display()))?;
jobs.push(Job { path, config, rules });
let options = rule_options(&file_config)?;
jobs.push(Job { path, config, rules, options });
}
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 })
}
/// The `[lint.<rule>]` entries of one file's config, resolved against the
/// registry.
///
/// The names and the values are checked **here**, where the registry is, and
/// the first bad entry fails the run naming the config file and the line it
/// was written on — the same treatment a bad `[lint] select` name gets, and
/// for the same reason: a user typed it and is watching.
pub fn rule_options(file_config: &FileConfig) -> Result<RuleOptions, String> {
let mut options = RuleOptions::new();
for entry in &file_config.lint_options {
options.set_raw(&entry.rule, &entry.key, &entry.raw).map_err(|e| {
let file = file_config
.source
.as_ref()
.map_or_else(|| "lucisv.toml".to_string(), |path| path.display().to_string());
// The rule is named as well as the option: the table header two
// lines up says which rule it is, and an error a user reads out
// of a CI log has no table header beside it.
format!("{file}:{}: rule `{}` {e}", entry.line, entry.rule)
})?;
}
Ok(options)
}
/// 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() {
@@ -154,7 +245,9 @@ pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
let mut reports: Vec<Report> = plan
.jobs
.par_iter()
.map(|job| check_one(&job.path, &job.config, opts, &job.rules, plan.census.as_ref()))
.map(|job| {
check_one(&job.path, &job.config, opts, &job.rules, &job.options, plan.census.as_ref())
})
.collect();
// Diagnostics are printed sorted by path, then by position within the
// file (`lint` already sorts those), so a run over a directory reads
@@ -170,10 +263,11 @@ pub fn check_stdin(
src: &str,
config: &Config,
rules: &[&'static dyn Rule],
options: &RuleOptions,
) -> ExitCode {
let name = opts.stdin_filename.clone().unwrap_or_else(|| "<stdin>".to_string());
let path = opts.stdin_filename.as_ref().map(PathBuf::from);
let (violations, lex_error) = run_rules(src, path, config, rules, None);
let (violations, lex_error) = run_rules(src, path, config, rules, options, None);
// Nothing is ever written back for stdin, so `--fix` has nothing to do
// here; the violations are reported as they are.
let error = lex_error.map(|e| format!("{name}: {e}"));
@@ -187,6 +281,7 @@ fn check_one(
config: &Config,
opts: &Options,
rules: &[&'static dyn Rule],
options: &RuleOptions,
census: Option<&Census>,
) -> Report {
let path = file.display().to_string();
@@ -204,10 +299,10 @@ fn check_one(
};
let outcome = crate::catch_panic(|| {
if opts.fix {
fix_source(&src, file, config, opts, rules, census)
fix_source(&src, file, config, opts, rules, options, census)
} else {
let (violations, lex_error) =
run_rules(&src, Some(file.to_path_buf()), config, rules, census);
run_rules(&src, Some(file.to_path_buf()), config, rules, options, census);
(violations, None, 0, lex_error)
}
});
@@ -238,6 +333,7 @@ fn run_rules(
path: Option<PathBuf>,
config: &Config,
rules: &[&'static dyn Rule],
options: &RuleOptions,
census: Option<&Census>,
) -> (Vec<Violation>, Option<String>) {
// One parse per file (TODO §4): the products are built here, once, and
@@ -252,8 +348,13 @@ fn run_rules(
// census so a signal never counts as mentioned by its own declaration.
let elsewhere = census.map(|census| Elsewhere { census, own: words::harvest(parsed.tokens()) });
// The indent width the formatter would use is also the width a tab
// expands to, so `--indent 4` fixes tabs into four spaces.
let ctx = parsed.context(path).with_tab_width(config.indent_width);
// expands to, so `--indent 4` fixes tabs into four spaces — and the width
// it would wrap to is the width `line-length` holds the file to.
let ctx = parsed
.context(path)
.with_tab_width(config.indent_width)
.with_line_length(config.max_width)
.with_options(options);
let ctx = match &elsewhere {
Some(elsewhere) => ctx.with_oracle(elsewhere),
None => ctx,
@@ -300,12 +401,13 @@ fn fix_source(
config: &Config,
opts: &Options,
rules: &[&'static dyn Rule],
options: &RuleOptions,
census: Option<&Census>,
) -> (Vec<Violation>, Option<String>, usize, Option<String>) {
let mut text = src.to_string();
let mut fixed = 0;
let (mut violations, mut lex_error) =
run_rules(&text, Some(file.to_path_buf()), config, rules, census);
run_rules(&text, Some(file.to_path_buf()), config, rules, options, census);
for _ in 0..MAX_FIX_ROUNDS {
let round =
apply_fixes(&text, &fixable_outside_fences(&text, &violations), opts.unsafe_fixes);
@@ -314,7 +416,8 @@ fn fix_source(
}
fixed += round.applied;
text = round.output;
(violations, lex_error) = run_rules(&text, Some(file.to_path_buf()), config, rules, census);
(violations, lex_error) =
run_rules(&text, Some(file.to_path_buf()), config, rules, options, census);
}
let rewritten = (text != src).then_some(text);
(violations, rewritten, fixed, lex_error)
@@ -348,15 +451,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 +483,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,
+15 -5
View File
@@ -98,7 +98,7 @@ fn run_check(opts: &Options) -> ExitCode {
return ExitCode::from(2);
}
if opts.is_stdin() {
let config = match stdin_config(opts) {
let (config, file_config) = match stdin_config(opts) {
Ok(c) => c,
Err(e) => {
eprintln!("error: {e}");
@@ -120,7 +120,14 @@ fn run_check(opts: &Options) -> ExitCode {
return ExitCode::from(2);
}
};
return lint::check_stdin(opts, &src, &config, &rules);
let options = match lint::rule_options(&file_config) {
Ok(options) => options,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
return lint::check_stdin(opts, &src, &config, &rules, &options);
}
let jobs = match gather(opts).and_then(|jobs| build_pool(opts).map(|()| jobs)) {
Ok(jobs) => jobs,
@@ -140,7 +147,7 @@ fn run_check(opts: &Options) -> ExitCode {
fn run_stdin(opts: &Options) -> ExitCode {
let name = opts.stdin_filename.as_deref().unwrap_or("<stdin>");
let config = match stdin_config(opts) {
let (config, _file_config) = match stdin_config(opts) {
Ok(c) => c,
Err(e) => {
eprintln!("error: {e}");
@@ -421,13 +428,16 @@ fn absolute(cwd: &Path, path: &Path) -> PathBuf {
/// The settings for a buffer piped in on stdin: discovery anchors on
/// `--stdin-filename`'s directory when given, else on the current one.
fn stdin_config(opts: &Options) -> Result<Config, String> {
/// The formatter config a stdin buffer is served with, and the `lucisv.toml`
/// it came from — the linter needs the file's own `[lint.<rule>]` entries,
/// which the resolved `Config` does not carry.
fn stdin_config(opts: &Options) -> Result<(Config, FileConfig), String> {
let mut discovery = Discovery::new(!opts.no_config);
let file = match opts.stdin_filename.as_deref() {
Some(name) => discovery.for_file(Path::new(name))?,
None => discovery.for_dir(Path::new("."))?,
};
Ok(opts.config_with(&file))
Ok((opts.config_with(&file), file))
}
fn report(opts: &Options, changed: usize, unchanged: usize, cached: usize, errors: usize) {
+100 -8
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");
@@ -1836,16 +1863,81 @@ fn an_unknown_rule_in_the_lint_table_is_an_error() {
assert_eq!(code(&out), 2);
}
/// Per-rule tables are named rather than silently ignored, so a user who
/// writes one finds out it does nothing yet.
/// A `[lint.<rule>]` table configures that rule, and the verdict changes
/// with it — §34.0's headline claim, end to end through the real binary.
#[test]
fn a_per_rule_lint_table_is_refused_by_name() {
fn a_per_rule_lint_table_changes_the_verdict() {
let dir = TempDir::new("lint-per-rule");
dir.write("dut.sv", DUT);
dir.write("lucisv.toml", "[lint.unused-signal]\nignore = \"tmp_*\"\n");
let wide = format!("module m;\n wire {};\nendmodule\n", "a".repeat(110));
dir.write("m.sv", &wide);
let out = run(&["check", &dir.root()]);
assert!(stderr(&out).contains("per-rule lint settings"), "{}", stderr(&out));
assert_eq!(code(&out), 2);
assert!(stdout(&out).contains("line-length"), "over the default 100: {}", stdout(&out));
dir.write("lucisv.toml", "[lint.line-length]\nlength = 130\n");
let out = run(&["check", &dir.root()]);
assert_eq!(stdout(&out), "", "the option raised the limit");
assert_eq!(code(&out), 0);
}
/// A bad entry fails the run naming the config file and the line, which is
/// what tells a user *where* to fix it.
#[test]
fn a_bad_rule_option_fails_the_run_naming_file_and_line() {
let dir = TempDir::new("lint-bad-option");
dir.write("m.sv", "module m;\nendmodule\n");
for (config, wanted) in [
("[lint.line-length]\nlength = 10\n", "must be between"),
("[lint.line-length]\nlen = 120\n", "has no option `len`"),
("[lint.no-such-rule]\nx = 1\n", "unknown rule `no-such-rule`"),
("[lint.no-tabs]\nwidth = 4\n", "takes no options"),
("[lint.signal-name-style]\nstyle_regex = \"[a-\"\n", "not a valid pattern"),
// An escape from another dialect must be refused rather than read
// as a literal, which would silently judge the wrong names (QA,
// 2026-09-04).
("[lint.signal-name-style]\nstyle_regex = \"\\bword\\b\"\n", "unsupported escape `\\b`"),
("[lint.macro-name-style]\nstyle_regex = \"(A)\\1\"\n", "unsupported escape `\\1`"),
] {
dir.write("lucisv.toml", config);
let out = run(&["check", &dir.root()]);
let text = stderr(&out);
assert!(text.contains(wanted), "{config:?}: {text}");
assert!(text.contains("lucisv.toml:2:"), "file and line: {text}");
assert_eq!(code(&out), 2, "{config:?}");
}
// Every one of them names the rule as well as the option, so an error
// read out of a CI log stands on its own.
dir.write("lucisv.toml", "[lint.line-length]\nlength = 10\n");
let text = stderr(&run(&["check", &dir.root()]));
assert!(text.contains("rule `line-length`"), "{text}");
assert!(text.contains("`length` must be between"), "{text}");
}
/// The width `line-length` holds a file to is the width the formatter is
/// configured with, so the two halves of lucisv cannot disagree.
#[test]
fn line_length_follows_the_formatters_width() {
let dir = TempDir::new("lint-width");
let wide = format!("module m;\n wire {};\nendmodule\n", "a".repeat(90));
dir.write("m.sv", &wide);
assert_eq!(stdout(&run(&["check", &dir.root()])), "", "under the default 100");
let narrow = run(&["check", &dir.root(), "--line-length", "80"]);
assert!(stdout(&narrow).contains("line-length"), "{}", stdout(&narrow));
dir.write("lucisv.toml", "line-length = 80\n");
let from_config = run(&["check", &dir.root()]);
assert!(stdout(&from_config).contains("line-length"), "{}", stdout(&from_config));
}
/// A stdin buffer reads the same `[lint.<rule>]` tables a file does.
#[test]
fn a_stdin_buffer_reads_the_rule_options_too() {
let dir = TempDir::new("lint-stdin-options");
dir.write("lucisv.toml", "[lint.macro-name-style]\nstyle_regex = \"[a-z_0-9]+\"\n");
let name = format!("{}/m.sv", dir.root());
let out = run_with_stdin(&["check", "-", "--stdin-filename", &name], "`define lower_ok 1\n");
assert_eq!(stdout(&out), "", "the config's pattern accepts it: {}", stdout(&out));
let plain = run_with_stdin(&["check", "-"], "`define lower_ok 1\n");
assert!(stdout(&plain).contains("macro-name-style"), "{}", stdout(&plain));
}
/// The QA finding of 2026-09-02, pinned end to end: a testbench that reads an
+169 -22
View File
@@ -1,8 +1,9 @@
//! `lucisv.toml` / `.lucisv.toml` discovery and its TOML-subset parser.
//!
//! Only what a small config file needs is supported (comments, `key = int`,
//! `key = "string"`, `key = ["a", "b"]`, and the single table `[lint]`);
//! everything else is rejected by name rather than ignored. See
//! `key = "string"`, `key = ["a", "b"]`, the table `[lint]` and the per-rule
//! `[lint.<rule>]` tables); everything else is rejected by name rather than
//! ignored. See
//! `docs/features/config-discovery/README.md` for the grammar and the
//! reasoning behind not taking a TOML dependency.
@@ -36,6 +37,34 @@ pub struct FileConfig {
pub lint_select: Option<Vec<String>>,
/// `[lint] ignore`: rules dropped from whatever `select` left.
pub lint_ignore: Option<Vec<String>>,
/// `[lint.<rule>]` tables, **as written**: one entry per key, in file
/// order.
///
/// Neither the rule names nor the option names or their values are
/// checked here — this crate does not know the rule registry, exactly as
/// it does not know which rule names `select` may hold. `lucisv check`
/// resolves them against `vlog_linter`'s specs and fails the run naming
/// this file and the line, which is what [`LintOption::line`] is for.
pub lint_options: Vec<LintOption>,
/// The config file these settings were read from, when they were read
/// from one. `parse` leaves it unset — it is handed text, not a path —
/// and [`Discovery`] fills it in, so an error about an entry can name the
/// file the user has to edit.
pub source: Option<PathBuf>,
}
/// One `key = value` written under a `[lint.<rule>]` table, as written.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LintOption {
/// The rule named by the table header.
pub rule: String,
/// The option key.
pub key: String,
/// The value's text, comment stripped, quotes and all — the linter's own
/// parser reads it, because only it knows what kind the key takes.
pub raw: String,
/// 1-based line the entry was written on.
pub line: usize,
}
/// Parses the supported TOML subset. Errors are prefixed `<line>: ` so the
@@ -45,36 +74,55 @@ pub fn parse(text: &str) -> Result<FileConfig, String> {
// Editors on some platforms prepend a BOM; it would otherwise garble
// key matching on line 1 into an `unknown key` with invisible cause.
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
// Which table the keys below belong to. There is exactly one table, so
// this is a flag rather than a path: `[lint]` opens it and nothing closes
// it, which is TOML's own rule.
let mut in_lint = false;
// Which table the keys below belong to: the top level until a header
// opens one, and then that one until the next header. Nothing closes a
// table, which is TOML's own rule.
let mut table = Table::Top;
for (index, raw) in text.lines().enumerate() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
parse_entry(line, &mut config, &mut in_lint).map_err(|e| format!("{}: {e}", index + 1))?;
parse_entry(line, &mut config, &mut table, index + 1)
.map_err(|e| format!("{}: {e}", index + 1))?;
}
Ok(config)
}
fn parse_entry(line: &str, config: &mut FileConfig, in_lint: &mut bool) -> Result<(), String> {
/// The table whose keys are being read.
enum Table {
/// Before any header: the formatter's own keys.
Top,
/// `[lint]`: `select` and `ignore`.
Lint,
/// `[lint.<rule>]`: that rule's options.
Rule(String),
}
fn parse_entry(
line: &str,
config: &mut FileConfig,
table: &mut Table,
number: usize,
) -> Result<(), String> {
if line.starts_with('[') {
// `[lint]` is the one table lucisv reads. `[lint.<rule>]` — per-rule
// settings — is named in the error rather than ignored, so a user who
// writes one finds out it is not supported yet instead of wondering
// why it did nothing (topo §2.9-4 keeps the per-rule half open).
// `[lint]` carries `select`/`ignore`; `[lint.<rule>]` carries that
// rule's options, which are stored raw and checked by whoever knows
// the registry.
if line == "[lint]" {
*in_lint = true;
*table = Table::Lint;
return Ok(());
}
if line.starts_with("[lint.") {
return Err(format!(
"per-rule lint settings (`{line}`) are not supported yet; `[lint]` takes `select` and `ignore`"
));
if let Some(rule) = line.strip_prefix("[lint.").and_then(|r| r.strip_suffix(']')) {
if rule.is_empty() || rule.contains('.') || rule.contains(' ') {
return Err(format!("`{line}` is not a rule table; write `[lint.<rule-name>]`"));
}
*table = Table::Rule(rule.to_string());
return Ok(());
}
return Err(format!("unknown table `{line}` (the only table is `[lint]`)"));
return Err(format!(
"unknown table `{line}` (the tables are `[lint]` and `[lint.<rule-name>]`)"
));
}
let (key, value) =
line.split_once('=').ok_or_else(|| format!("expected `key = value`, found `{line}`"))?;
@@ -83,8 +131,10 @@ fn parse_entry(line: &str, config: &mut FileConfig, in_lint: &mut bool) -> Resul
if value.is_empty() {
return Err(format!("`{key}` has no value"));
}
if *in_lint {
return parse_lint_entry(key, value, config);
match table {
Table::Lint => return parse_lint_entry(key, value, config),
Table::Rule(rule) => return parse_rule_entry(rule, key, value, config, number),
Table::Top => {}
}
match key {
"line-length" => set_int(&mut config.line_length, key, value, 40, 400),
@@ -105,7 +155,8 @@ fn parse_entry(line: &str, config: &mut FileConfig, in_lint: &mut bool) -> Resul
}
_ => Err(format!(
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
and select, ignore under `[lint]`)"
select, ignore under `[lint]`; and a rule's own options under \
`[lint.<rule-name>]`)"
)),
}
}
@@ -126,6 +177,26 @@ fn parse_lint_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(
Ok(())
}
/// One `key = value` of a `[lint.<rule>]` table, kept as written.
fn parse_rule_entry(
rule: &str,
key: &str,
value: &str,
config: &mut FileConfig,
line: usize,
) -> Result<(), String> {
if config.lint_options.iter().any(|held| held.rule == rule && held.key == key) {
return Err(format!("duplicate key `{key}` under `[lint.{rule}]`"));
}
config.lint_options.push(LintOption {
rule: rule.to_string(),
key: key.to_string(),
raw: value.to_string(),
line,
});
Ok(())
}
fn set_int(
slot: &mut Option<usize>,
key: &str,
@@ -292,6 +363,8 @@ fn load(path: &Path) -> Result<FileConfig, String> {
let dir = path.parent().unwrap_or(Path::new("."));
config.filelist = Some(dir.join(filelist));
}
// So an error about a `[lint.<rule>]` entry can name the file to edit.
config.source = Some(path.to_path_buf());
Ok(config)
}
@@ -451,7 +524,8 @@ exclude = [ \"build\", \"*_gen.sv\", ]
fn the_lint_table_rejects_what_it_does_not_support() {
assert!(err("[lint]\nbogus = [\"a\"]").contains("unknown key `bogus` under `[lint]`"));
assert!(err("[lint]\nselect = \"no-tabs\"").contains("multi-line arrays are unsupported"));
assert!(err("[lint.no-tabs]\nseverity = \"error\"").contains("per-rule lint settings"));
assert!(err("[lint.]\nx = 1").contains("not a rule table"));
assert!(err("[lint.a.b]\nx = 1").contains("not a rule table"));
assert!(err("[lint]\nindent = 4").contains("unknown key `indent` under `[lint]`"));
// A key before any table still belongs to the top level.
assert!(err("select = [\"no-tabs\"]").contains("unknown key `select`"));
@@ -462,6 +536,79 @@ exclude = [ \"build\", \"*_gen.sv\", ]
);
}
/// The per-rule tables: stored exactly as written, because this crate
/// has no idea what a rule is or what its options take.
#[test]
fn a_rule_table_keeps_its_entries_as_written() {
let config = parse(
"[lint]\nignore = [\"no-tabs\"]\n\n\
[lint.line-length]\nlength = 120\n\n\
[lint.signal-name-style]\nstyle_regex = \"[a-z_0-9]+\" # ours\n",
)
.expect("parses");
assert_eq!(config.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
let entries: Vec<(&str, &str, &str, usize)> = config
.lint_options
.iter()
.map(|o| (o.rule.as_str(), o.key.as_str(), o.raw.as_str(), o.line))
.collect();
assert_eq!(
entries,
vec![
("line-length", "length", "120", 5),
("signal-name-style", "style_regex", "\"[a-z_0-9]+\"", 8),
]
);
}
/// A backslash is legal in an option value and refused in a top-level
/// string: the linter's own parser reads the former, and a pattern is the
/// one value that needs them.
#[test]
fn a_rule_option_value_is_not_string_checked_here() {
let config =
parse("[lint.signal-name-style]\nstyle_regex = \"[a-z]\\d+\"\n").expect("parses");
assert_eq!(config.lint_options[0].raw, "\"[a-z]\\d+\"");
assert!(err("exclude = [\"a\\d\"]").contains("escapes"), "still refused up here");
}
#[test]
fn a_rule_table_rejects_a_repeated_key_and_a_bad_header() {
assert!(err("[lint.line-length]\nlength = 1\nlength = 2")
.contains("duplicate key `length` under `[lint.line-length]`"));
// The same key under two different rules is two different options.
let config = parse(
"[lint.enum-name-style]\nstyle_regex = \"a\"\n\
[lint.module-name-style]\nstyle_regex = \"b\"\n",
)
.expect("parses");
assert_eq!(config.lint_options.len(), 2);
assert!(err("[lint.a b]\nx = 1").contains("not a rule table"));
}
/// Nothing closes a table: the keys after a rule header belong to it
/// until the next header, and a formatter key written there is that
/// rule's option as far as this parser is concerned.
#[test]
fn a_rule_table_runs_until_the_next_header() {
let config =
parse("indent = 4\n[lint.line-length]\nlength = 120\nindent = 8\n").expect("parses");
assert_eq!(config.indent, Some(4));
assert_eq!(config.lint_options.len(), 2);
assert_eq!(config.lint_options[1].key, "indent");
}
#[test]
fn a_config_file_records_where_it_came_from() {
let tree = TempTree::new();
let written = tree.write("lucisv.toml", "[lint.line-length]\nlength = 120\n");
let file = tree.write("x.sv", "");
let found = Discovery::new(true).for_file(&file).expect("reads");
assert_eq!(found.source.as_deref(), Some(written.as_path()));
// `parse` alone has no path to record.
assert_eq!(parse("indent = 4").expect("parses").source, None);
}
/// A throwaway directory tree under the system temp dir.
struct TempTree {
path: PathBuf,
+41 -31
View File
@@ -528,39 +528,49 @@ mod tests {
}
}
/// QA finding (performance wave Lane B, 2026-08-28), not a regression this
/// QA finding (performance wave Lane B, 2026-08-28), not a regression that
/// round introduced: a module with an attribute instance (`(* ... *)`)
/// anywhere near its header — right after its name, or on one of its
/// ports — is not indexed as a `Module` unit **at all**.
/// `WorkspaceIndex::units` comes back empty, so [`module_header`] declines
/// at the very first line (no `[def]` to anchor on) before the whitelist
/// walk ever runs, and completion's module tier — which sources its
/// candidate names from the same table — never offers the module in the
/// first place. This is a `vlog_semantic`/`vlog_parser` parsing gap, not a
/// completion-core one: it is filed in `docs/features/completion-core/
/// README.md`'s QA log rather than fixed here, because `vlog_semantic` is
/// outside this round's touched files. The two "attribute" shapes this QA
/// round added to [`SHAPES`] (`attributed`, `port_attributed`) still pass
/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] — but only
/// because both sides of that comparison fall back to the same whole-file
/// parse, which this test makes explicit rather than leaving it as an
/// unremarked side effect of the pin.
/// **between its name and its `#(`** is not indexed as a `Module` unit at
/// all. `WorkspaceIndex::units` comes back empty, so [`module_header`]
/// declines at the very first line (no `[def]` to anchor on) before the
/// whitelist walk ever runs, and completion's module tier — which sources
/// its candidate names from the same table — never offers the module in
/// the first place. That attribute sits inside no list, so no recovery
/// reaches it; it is still filed in `docs/features/completion-core/
/// README.md`'s QA log.
///
/// **The `port_attributed` half of the finding was fixed by header
/// recovery** (TODO §32, `docs/features/header-recovery/README.md`): an
/// attribute on a *port* now costs that one port and nothing else — the
/// list keeps a `ListElem::Error` where `(* keep *) output logic q` was
/// written, and the module keeps its name, its other ports and its body,
/// so it is indexed and its header slices for real rather than by
/// whole-file fallback. That is the re-audit the old message asked for,
/// and it is the second half of this test;
/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] covers the
/// same shape from the other side.
#[test]
fn a_module_with_an_attribute_near_its_header_is_not_indexed_at_all() {
for module in ["attributed", "port_attributed"] {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
index.units(module).is_empty(),
"{module}: if this starts finding a unit, module_header should be re-audited \
for whether it now slices attributes correctly rather than by lucky fallback"
);
assert!(
module_header(&index, module, text).is_none(),
"{module}: no unit to anchor on"
);
}
fn an_attribute_before_the_parameter_list_still_costs_the_whole_module() {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == "attributed").expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
index.units("attributed").is_empty(),
"if this starts finding a unit, module_header should be re-audited \
for whether it now slices attributes correctly rather than by lucky fallback"
);
assert!(module_header(&index, "attributed", text).is_none(), "no unit to anchor on");
}
#[test]
fn an_attribute_on_a_port_costs_that_port_only() {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == "port_attributed").expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert_eq!(index.units("port_attributed").len(), 1, "the module survives its broken port");
let header = module_header(&index, "port_attributed", text).expect("a sliced header");
assert!(header.starts_with("module port_attributed ("), "{header:?}");
assert!(header.contains("(* keep *) output logic q"), "the port list is kept whole");
}
/// The guard is not decoration: a non-ANSI module really does plan
@@ -513,6 +513,20 @@ endmodule
);
}
/// The premise the probe above rests on, stated as a test: the probe is
/// *discriminating*. Header recovery (TODO §32) widened what a tolerant
/// parse can read, so the question "did this insertion parse?" is only
/// worth asking while text that does **not** parse still says so.
#[test]
fn the_insertion_probe_still_reports_text_that_does_not_parse() {
let broken = "if (cond begin\n\n end";
let probe = format!("module p;\n always_comb begin\n {broken}\n end\nendmodule\n");
assert!(
!vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
"recovery must not make a broken insertion look clean: {probe}"
);
}
#[test]
fn a_templates_documentation_shows_what_it_expands_to() {
let top = "module top;\n alw\nendmodule\n";
@@ -896,6 +910,30 @@ endmodule
drop(tree);
}
/// Header recovery (TODO §32) pinned where completion meets it: with a
/// half-typed parameter *above* the cursor, the module still has a scope,
/// so [`visible_symbols`] still answers from it — the parameters and ports
/// already typed are offered inside the very header being edited.
///
/// Before this round the broken header took the whole `Module` node with
/// it, the body re-parsed at file scope, and the scope chain covering this
/// offset held nothing at all.
#[test]
fn a_broken_header_still_completes_from_the_modules_scope() {
let top = "\
module top #(parameter W = , parameter DEPTH = 4) (
input logic clk_i,
output logic DE
);
logic w_local;
endmodule
";
let (_tree, ws, uri, position) = asking("brokenheader", top, "output logic DE");
let found = items(completions(&ws, &uri, position, true));
let item = find(&found, "DEPTH").expect("the parameter typed after the broken one");
assert_eq!(tier(item), TIER_SCOPE, "answered from the module's own scope");
}
/// The scope tier goes fuzzy too, with no mask table behind it — it is
/// the one tier computed per request.
#[test]
+35 -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,12 +150,43 @@ 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));
}
/// The user-visible contract of header recovery (TODO §32), pinned where
/// the user meets it: a typo in a port list costs **one** diagnostic, and
/// the module around it survives whole — its name, the ports typed before
/// and after the typo, and its body all still in the outline.
///
/// Before this round the same buffer published two errors (the header, and
/// the orphaned `endmodule`), the body re-parsed as file-scope items, and
/// the outline had no module in it at all.
#[test]
fn a_broken_port_list_publishes_one_error_and_keeps_its_module() {
let (ws, uri) = doc_of("module m (input a, , input b);\n wire ok;\nendmodule\n");
let doc = ws.document(&uri).expect("open");
let diags = diagnostics(doc);
assert_eq!(diags.len(), 1, "{diags:#?}");
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::ERROR));
assert_eq!(diags[0].range.start.line, 0, "the header's own line");
// The missing-closer pass explains a *parse* failure; there is no
// unclosed block here, so it must add nothing.
assert!(crate::pairs::missing_end_diagnostics(doc).is_empty());
let symbols = crate::symbols::document_symbols(doc);
assert_eq!(symbols.len(), 1, "the module is still in the outline");
assert_eq!(symbols[0].name, "m");
let children = symbols[0].children.as_ref().expect("module contents");
let names: Vec<&str> = children.iter().map(|c| c.name.as_str()).collect();
assert!(names.contains(&"a"), "the port before the typo: {names:?}");
assert!(names.contains(&"b"), "the port after it: {names:?}");
assert!(names.contains(&"ok"), "the body: {names:?}");
}
#[test]
fn a_lex_error_gets_a_visible_range() {
// The lexer gives up at end of file, which a trailing newline makes
+34 -4
View File
@@ -22,7 +22,7 @@
use std::collections::HashMap;
use lsp_types::{InlayHint, InlayHintKind, InlayHintLabel, Range, Uri};
use vlog_parser::ast::{Connections, Expr, Instance, Instantiation};
use vlog_parser::ast::{Connection, Connections, Expr, Instance, Instantiation, ListElem};
use vlog_parser::TextRange;
use vlog_refactor::InstantiationPlan;
use vlog_semantic::instantiations;
@@ -84,6 +84,13 @@ enum Kind {
/// name is written somewhere in the same list.
fn param_sites(inst: &Instantiation) -> Vec<Site> {
let Some(params) = &inst.params else { return Vec::new() };
// A list a tolerant parse recovered inside gets no hints either: which
// parameter a position names is exactly what the skipped text decides, so
// any hint here would be a guess, and a wrong hint is worse than none.
if params.iter().any(ListElem::is_error) {
return Vec::new();
}
let params: Vec<&Connection> = params.iter().filter_map(ListElem::ok).collect();
if params.iter().any(|param| !param.name.is_empty()) {
return Vec::new();
}
@@ -99,7 +106,16 @@ fn param_sites(inst: &Instantiation) -> Vec<Site> {
/// instance: the connections are the module's ports either way.
fn port_sites(instance: &Instance) -> Vec<Site> {
let Connections::Ordered(conns) = &instance.conns else { return Vec::new() };
conns.iter().enumerate().filter_map(|(index, conn)| site(index, conn.expr.as_ref())).collect()
// As in `param_sites`: a recovered list's positions are a guess.
if conns.iter().any(ListElem::is_error) {
return Vec::new();
}
conns
.iter()
.filter_map(ListElem::ok)
.enumerate()
.filter_map(|(index, conn)| site(index, conn.expr.as_ref()))
.collect()
}
/// A site at the start of `expr`, or nothing for an omitted position
@@ -542,10 +558,23 @@ endmodule
assert_eq!(hints[1], (2, 10, "clk:".to_string()), "the line before it had é and 🎉");
}
/// A buffer mid-edit still hints where the *positions* are known, and
/// stops where they are not.
///
/// Header recovery (TODO §32) changed the first half: `sub u1 (clk, rst_n`
/// used to fail to parse at all, so there was nothing to hint from. Now
/// the instantiation survives with both positional connections, and both
/// are at the index they were written at, so both are hinted. The second
/// half is the rule that replaces "does not parse": a list the parser
/// *recovered* inside holds text nobody can index, so `port_sites` and
/// `param_sites` decline the whole list rather than mislabel what follows
/// the hole.
#[test]
fn a_buffer_that_does_not_parse_hints_nothing_rather_than_guessing() {
fn a_truncated_list_hints_and_a_recovered_one_does_not() {
let top = "module top;\n sub u1 (clk, rst_n\n";
assert!(hints_of("broken", top).is_empty());
assert_eq!(labels(&hints_of("truncated", top)), ["clk:", "rst_n:"]);
let holed = "module top;\n sub u1 (clk, .\n wire w;\nendmodule\n";
assert!(hints_of("recovered", holed).is_empty());
}
#[test]
@@ -563,6 +592,7 @@ endmodule
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let insts = instantiations::sites(&tree.items);
let params = insts[0].inst.params.as_ref().expect("a `#( ... )`");
let params: Vec<_> = params.iter().filter_map(ListElem::ok).collect();
assert_eq!(params[0].name, "", "`8` names nothing");
assert_eq!(params[1].name, "DEPTH", "`.DEPTH(16)` does");
}
+14
View File
@@ -1894,6 +1894,20 @@ sub #(
}
}
/// The premise the "the accepted text must parse" probe above rests on:
/// the probe can still fail. Header recovery (TODO §32) widened what a
/// tolerant parse reads — a half-typed connection list is now a recovered
/// instantiation rather than a dead item — so the probe is only worth
/// asking while text that does not parse still says so.
#[test]
fn the_accepted_text_probe_still_reports_text_that_does_not_parse() {
let probe = "module lucisv_probe;\n logic clk;\n sub u_sub (.clk(\nendmodule\n";
assert!(
!vlog_parser::parse_source_tolerant(probe).1.is_empty(),
"recovery must not make a broken instantiation look clean"
);
}
#[test]
fn a_module_with_no_ports_ghosts_a_sane_instantiation() {
let top = "module top;\n bare \nendmodule\n";
+307 -17
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,
RuleOptions, 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
@@ -31,14 +35,29 @@ use crate::state::{Document, Workspace};
pub struct LintRun<'a> {
rules: Vec<&'static dyn Rule>,
oracle: Option<IndexMentions<'a>>,
/// What the buffer's `lucisv.toml` and the editor's settings configured
/// about each rule, merged. Empty means every rule reads its own default.
options: RuleOptions,
/// The width `line-length` holds this buffer to — the width the formatter
/// would wrap it to, so the two halves of lucisv cannot disagree.
line_length: usize,
}
impl Default for LintRun<'_> {
fn default() -> LintRun<'static> {
LintRun { rules: default_rules(), oracle: None }
LintRun {
rules: default_rules(),
oracle: None,
options: RuleOptions::new(),
line_length: DEFAULT_LINE_LENGTH,
}
}
}
/// The width a buffer is held to when neither its `lucisv.toml` nor the
/// editor says otherwise — `vlog_formatter::Config`'s own default.
const DEFAULT_LINE_LENGTH: usize = 100;
impl<'a> LintRun<'a> {
/// The pass this workspace's settings and index describe for one buffer.
///
@@ -52,19 +71,15 @@ 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 }
let (options, line_length) = configured(ws.client_settings(), doc);
LintRun { rules, oracle, options, line_length }
}
/// This run's context over a buffer's own parse products.
fn context<'d>(&'d self, doc: &'d Document) -> LintContext<'d> {
let ctx = context(doc);
let ctx = context(doc).with_options(&self.options).with_line_length(self.line_length);
match &self.oracle {
Some(oracle) => ctx.with_oracle(oracle),
None => ctx,
@@ -72,6 +87,104 @@ impl<'a> LintRun<'a> {
}
}
/// The per-rule options and the line width governing one buffer.
///
/// **Precedence for an option, highest first: the editor, then the buffer's
/// `lucisv.toml`, then the rule's own default — key by key**, so a project
/// that sets two options and a user who overrides one keep the other. This is
/// deliberately the *opposite* order to `format::settings_for`, where a
/// checked-in `lucisv.toml` outranks the editor: formatting has a byte-exact
/// contract with CI that a user's editor must not break, while a lint option
/// changes which findings that user is shown in their own editor and is
/// theirs to set. §34.0(d).
///
/// The **width** follows the formatting ladder instead, because it is not a
/// lint setting at all: it is the width the formatter would wrap this buffer
/// to, read the same way `format::settings_for` reads it, so a line lucisv
/// wrote is never a line lucisv calls too long. `line-length`'s own `length`
/// option still beats it — that is the rule's own business, and the rule
/// applies it.
///
/// The config file is read here, per pass, exactly as `format::discover`
/// reads it per formatting request: a `lucisv.toml` edited while the server
/// runs takes effect at the next publish, and the read is a few stats beside
/// a parse and an analysis the same pass already paid for.
fn configured(client: &ClientSettings, doc: &Document) -> (RuleOptions, usize) {
let file = doc
.path
.as_deref()
.and_then(|path| lucisv_core::config::Discovery::new(true).for_file(path).ok())
.unwrap_or_default();
let mut options = RuleOptions::new();
for entry in &file.lint_options {
// A broken entry in the file is dropped here rather than reported:
// `format::settings_for` already surfaces a `lucisv.toml` problem to
// the user, and `lucisv check` fails the run over it with file and
// line, which is where a config error belongs.
let _ = options.set_raw(&entry.rule, &entry.key, &entry.raw);
}
options.overlay(&client.lint_options);
let width = file.line_length.or(client.line_length).unwrap_or(DEFAULT_LINE_LENGTH);
(options, width)
}
/// 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 +210,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 +314,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 +328,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 +364,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 +543,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]
@@ -12,12 +12,13 @@ use lsp_server::{ExtractError, Notification};
use lsp_types::notification::{
DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles,
DidChangeWorkspaceFolders, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument,
DidRenameFiles, DidSaveTextDocument, Notification as _,
DidRenameFiles, DidSaveTextDocument, LogMessage, Notification as _,
};
use lsp_types::{
DeleteFilesParams, DidChangeConfigurationParams, DidChangeTextDocumentParams,
DidChangeWatchedFilesParams, DidChangeWorkspaceFoldersParams, DidCloseTextDocumentParams,
DidOpenTextDocumentParams, DidSaveTextDocumentParams, RenameFilesParams, Uri, WorkspaceFolder,
DidOpenTextDocumentParams, DidSaveTextDocumentParams, LogMessageParams, MessageType,
RenameFilesParams, Uri, WorkspaceFolder,
};
use serde::de::DeserializeOwned;
@@ -244,14 +245,30 @@ impl Server {
pub(super) fn apply_settings(&mut self, settings: settings::ClientSettings) {
let watched = self.workspace.filelist_path();
let linted = self.lint_selection();
// A `lucisv.lint.options` entry the registry refused is dropped, not
// fatal (`settings::rule_options`) — so the log line is the only way
// the user learns their option is doing nothing. Logged, not shown: a
// typo in a settings file is not worth a popup, and a client that
// resends its whole section would raise the same one repeatedly.
for warning in &settings.lint_option_warnings {
self.notify(
LogMessage::METHOD,
LogMessageParams {
typ: MessageType::WARNING,
message: format!("lucisv: {warning}"),
},
);
}
// Only `exclude` and `filelist` change which files exist as far as
// this server is concerned; the other settings are read afresh by the
// next request that wants them and need no invalidation.
if self.workspace.set_client_settings(settings) {
self.reindex();
} else if self.lint_selection() != linted {
// `lucisv.lint.select`/`ignore` change which rules run and nothing
// else: no file's contents moved, so there is nothing to rescan —
// `lucisv.lint.select`/`ignore`, the class switches, the per-rule
// toggles and the per-rule *options* change which rules run and
// what they report, and nothing else: no file's contents moved,
// so there is nothing to rescan —
// but every published squiggle was drawn under the old selection,
// and a client that pulls has cached answers under it too.
self.generation += 1;
@@ -268,9 +285,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())
}
}
+349 -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::{OptionValue, RuleOptions, Severity};
/// Accepted `line-length`, and accepted `indent`.
///
@@ -174,6 +176,32 @@ 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>,
/// `lucisv.lint.options`: `{"<rule>": {"<key>": value}}`, validated
/// against the rule registry.
///
/// Refused entries are **dropped**, not fatal — this module's standing
/// rule, and the reason it matters here more than anywhere else: one
/// typo in an options object must not be able to switch the linter off
/// for a whole session. What was refused is kept in
/// [`ClientSettings::lint_option_warnings`] so the user is told.
pub lint_options: RuleOptions,
/// One line per refused `lucisv.lint.options` entry, ready for a
/// `window/logMessage`. Empty for a settings push that was all valid.
pub lint_option_warnings: Vec<String>,
}
/// The settings a client that said nothing is treated as having asked for.
@@ -200,10 +228,43 @@ 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(),
lint_options: RuleOptions::new(),
lint_option_warnings: Vec::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>, RuleOptions);
/// The lint settings of `settings`, as one comparable value.
///
/// The options are in here with the four that choose rules, because a changed
/// option changes what a rule *reports* — a `line-length` of 120 unpublishes
/// every finding drawn at 100 — and every open file must be published again
/// for exactly the same reason a changed selection does.
pub fn lint_selection(settings: &ClientSettings) -> LintSelection {
(
settings.lint_select.clone(),
settings.lint_ignore.clone(),
settings.lint_severity.clone(),
settings.lint_rules.clone(),
settings.lint_options.clone(),
)
}
/// Read the `lucisv` section out of a `workspace/didChangeConfiguration` payload.
///
/// **Nothing here trusts the client.** `package.json`'s JSON schema constrains
@@ -231,6 +292,7 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
let large_file = lucisv.get("largeFile");
// And `lucisv.lint.select` / `lucisv.lint.ignore` the same way again.
let lint = lucisv.get("lint");
let (options, warnings) = rule_options(lint.and_then(|l| l.get("options")));
ClientSettings {
line_length: bounded(lucisv.get("lineLength"), LINE_LENGTH_RANGE),
indent: bounded(lucisv.get("indent"), INDENT_RANGE),
@@ -274,17 +336,112 @@ 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"))),
lint_options: options,
lint_option_warnings: warnings,
}
}
/// 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()
}
/// The `lucisv.lint.options` object, validated against the rule registry.
///
/// The shape is `{"<rule>": {"<key>": value}}` — the nesting VS Code's
/// settings model produces for an object setting, and the one a hand-written
/// Neovim config writes. Every entry goes through the **same** validator a
/// `[lint.<rule>]` table in a `lucisv.toml` goes through
/// (`RuleOptions::set`), so an option means one thing in both front ends.
///
/// A refused entry is dropped and described, rather than failing the push:
/// the CLI can fail a run over a typo because a user typed it and is watching,
/// while a settings push arrives on a socket and failing it would leave an
/// editor with no diagnostics and no way to see why. The descriptions are
/// returned for the caller to log.
fn rule_options(value: Option<&Value>) -> (RuleOptions, Vec<String>) {
let mut options = RuleOptions::new();
let mut warnings = Vec::new();
let Some(Value::Object(rules)) = value else { return (options, warnings) };
for (rule, keys) in rules {
let Some(Value::Object(keys)) = Some(keys) else {
warnings.push(format!("lucisv.lint.options.{rule} is not an object; ignored"));
continue;
};
for (key, raw) in keys {
let Some(value) = option_value(raw) else {
warnings.push(format!(
"lucisv.lint.options.{rule}.{key}: {raw} is not a boolean, number, \
string or list of strings; ignored"
));
continue;
};
if let Err(problem) = options.set(rule, key, value) {
warnings.push(format!("lucisv.lint.options.{rule}.{key}: {problem}; ignored"));
}
}
}
(options, warnings)
}
/// One JSON value as an option value, or nothing for a shape no option takes.
///
/// Structural only — whether the *kind* is the one the option declares is
/// `RuleOptions::set`'s answer, so the error a user reads names the option
/// and its kind rather than JSON's.
fn option_value(raw: &Value) -> Option<OptionValue> {
match raw {
Value::Bool(b) => Some(OptionValue::Bool(*b)),
Value::Number(n) => n.as_i64().map(OptionValue::Int),
Value::String(s) => Some(OptionValue::Str(s.clone())),
Value::Array(items) => items
.iter()
.map(|item| item.as_str().map(str::to_string))
.collect::<Option<Vec<String>>>()
.map(OptionValue::List),
_ => None,
}
}
/// One of the two `lucisv.index.scope` words, or nothing. Matched exactly —
@@ -623,6 +780,195 @@ 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()];
let mut configured = base.clone();
configured.lint_options.set_raw("line-length", "length", "120").expect("accepted");
for changed in [severity, toggled, selected, ignored, configured] {
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));
}
/// §34.0(c): the object is read, validated against the registry, and a
/// bad entry is dropped **with a warning** rather than failing the push.
#[test]
fn the_lint_options_object_is_read_and_validated() {
let found = settings(json!({"lucisv": {"lint": {"options": {
"line-length": {"length": 120},
"generate-label-prefix": {"prefix": ["blk_"]},
"typedef-structs-unions": {"allow_anonymous_nested": true},
"signal-name-style": {"style_regex": "[a-z_0-9]+"},
}}}}));
assert_eq!(found.lint_options.int("line-length", "length"), 120);
assert_eq!(
found.lint_options.list("generate-label-prefix", "prefix"),
vec!["blk_".to_string()]
);
assert!(found.lint_options.bool("typedef-structs-unions", "allow_anonymous_nested"));
assert_eq!(found.lint_options.str("signal-name-style", "style_regex"), "[a-z_0-9]+");
assert!(found.lint_option_warnings.is_empty(), "{:?}", found.lint_option_warnings);
}
#[test]
fn a_refused_option_is_dropped_and_described_rather_than_fatal() {
let found = settings(json!({"lucisv": {"lint": {"options": {
"line-length": {"length": 10, "len": 120},
"no-such-rule": {"x": 1},
"no-tabs": {"width": 4},
"signal-name-style": {"style_regex": "[a-"},
"interface-name-style": {"style_regex": "\\bword\\b"},
"macro-name-style": {"style_regex": 4},
"package-filename": "not-an-object",
"port-name-suffix": {"suffixes": [1, 2]},
}}}}));
// Nothing was accepted, and every refusal says which entry and why.
assert!(found.lint_options.is_empty(), "{:?}", found.lint_options);
let warnings = found.lint_option_warnings.join("\n");
for wanted in [
"line-length.length",
"must be between",
"has no option `len`",
"unknown rule `no-such-rule`",
"takes no options",
"not a valid pattern",
"unsupported escape `\\b`",
"expects a pattern, found an integer",
"package-filename is not an object",
"port-name-suffix.suffixes",
] {
assert!(warnings.contains(wanted), "{wanted} missing from:\n{warnings}");
}
// ... and the rest of the settings survived the bad object.
assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE);
}
/// A settings payload with no options object is exactly today's
/// behaviour: every rule reads its own default.
#[test]
fn no_options_object_means_every_default() {
for payload in [json!({"lucisv": {}}), json!({"lucisv": {"lint": {}}})] {
let found = settings(payload);
assert!(found.lint_options.is_empty());
assert!(found.lint_option_warnings.is_empty());
assert_eq!(found.lint_options.int("line-length", "length"), 100, "the spec default");
}
}
#[test]
fn the_default_vscode_payload_is_no_opinion_about_anything() {
// Every setting at its `package.json` default: nulls and an empty
+11
View File
@@ -456,6 +456,17 @@ mod tests {
}
}
/// The premise [`every_untouched_expansion_parses`] rests on: the probe
/// can still fail. Header recovery (TODO §32) widened what a tolerant
/// parse reads, and a probe that answered "clean" for everything would
/// pass that test while proving nothing.
#[test]
fn the_expansion_probe_still_reports_text_that_does_not_parse() {
let probe = "module p;\n always_comb begin\n case (sel\n end\nendmodule\n";
let (_, diagnostics) = vlog_parser::parse_source_tolerant(probe);
assert!(!diagnostics.is_empty(), "recovery must not make a broken expansion look clean");
}
#[test]
fn every_hole_is_a_tabstop_the_snippet_grammar_reads() {
// The editor-snippets lesson, restated for generated text: VS Code
+9 -7
View File
@@ -41,7 +41,7 @@
use lsp_types::{Location, Uri};
use vlog_parser::ast::{
AnsiPort, DataType, Declarator, GenBlock, GenElse, GenIf, Instantiation, Item, ItemKind,
Module, ParamPort, PortList, Stmt, StmtKind, StructType, TfArg, TypeExtra, Typedef,
ListElem, Module, ParamPort, PortList, Stmt, StmtKind, StructType, TfArg, TypeExtra, Typedef,
TypedefKind,
};
use vlog_parser::TextRange;
@@ -250,18 +250,20 @@ fn module_site(m: &Module, offset: u32) -> Option<Site<'_>> {
.or_else(|| site_at(&m.items, offset))
}
fn ansi_port_site(ports: &[AnsiPort], offset: u32) -> Option<Site<'_>> {
let port = ports.iter().find(|p| p.span.contains(offset))?;
// The three header lists below skip their error elements: text a tolerant
// parse could not read names no type, so there is no definition to go to.
fn ansi_port_site(ports: &[ListElem<AnsiPort>], offset: u32) -> Option<Site<'_>> {
let port = ports.iter().filter_map(ListElem::ok).find(|p| p.span.contains(offset))?;
site(&port.ty.name, TextRange::new(port.span.start, port.name_span.start))
}
fn param_port_site(ports: &[ParamPort], offset: u32) -> Option<Site<'_>> {
let port = ports.iter().find(|p| p.span.contains(offset))?;
fn param_port_site(ports: &[ListElem<ParamPort>], offset: u32) -> Option<Site<'_>> {
let port = ports.iter().filter_map(ListElem::ok).find(|p| p.span.contains(offset))?;
site(&port.ty.name, TextRange::new(port.span.start, port.name_span.start))
}
fn tf_arg_site(args: &[TfArg], offset: u32) -> Option<Site<'_>> {
let arg = args.iter().find(|a| a.span.contains(offset))?;
fn tf_arg_site(args: &[ListElem<TfArg>], offset: u32) -> Option<Site<'_>> {
let arg = args.iter().filter_map(ListElem::ok).find(|a| a.span.contains(offset))?;
site(&arg.ty.name, TextRange::new(arg.span.start, arg.name_span.start))
}
+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");
}
+10 -2
View File
@@ -38,7 +38,11 @@ impl<'a> Fmt<'a> {
if let Some(params) = &c.param_ports {
let items: Vec<ListItem> = params
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma))
.map(|p| {
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma)
})
})
.collect();
let items = self.list_entries(items, &c.param_directives);
let broken = !c.param_directives.is_empty();
@@ -52,7 +56,11 @@ impl<'a> Fmt<'a> {
if let Some(params) = &ext.params {
let items: Vec<ListItem> = params
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.connection(p)).with_comma(p.comma))
.map(|p| {
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.connection(p)).with_comma(p.comma)
})
})
.collect();
let items = self.list_entries(items, &ext.param_directives);
let broken = !ext.param_directives.is_empty();
+5
View File
@@ -305,6 +305,11 @@ impl<'a> Fmt<'a> {
// region never begins its own line, so a dedent-by-column would
// drift instead of reaching a fixed point.
ExprKind::Verbatim(raw) => self.raw_inline(raw),
// Unreachable from `format_source`, as `ItemKind::Error` is: only
// a tolerant parse builds this leaf, and the formatter parses
// strictly. Printed verbatim so nothing is lost if that ever
// changes — see `ListItem::from_raw`.
ExprKind::Error(raw) => self.raw_inline(raw),
ExprKind::MinTypMax { min, typ, max } => {
concat(vec![self.expr(min), text(":"), self.expr(typ), text(":"), self.expr(max)])
}
+22 -12
View File
@@ -28,7 +28,11 @@ impl<'a> Fmt<'a> {
if let Some(params) = &inst.params {
let items: Vec<ListItem> = params
.iter()
.map(|c| ListItem::from_meta(&c.meta, self.connection(c)).with_comma(c.comma))
.map(|c| {
self.list_elem(c, |c| {
ListItem::from_meta(&c.meta, self.connection(c)).with_comma(c.comma)
})
})
.collect();
let items = self.list_entries(items, &inst.param_directives);
let broken = !inst.param_directives.is_empty() || holds_verbatim_value(params);
@@ -109,19 +113,23 @@ impl<'a> Fmt<'a> {
list.iter()
.zip(&aligns)
.map(|(c, a)| {
ListItem::from_meta(&c.meta, self.connection_aligned(c, a.as_ref()))
.with_comma(c.comma)
self.list_elem(c, |c| {
ListItem::from_meta(&c.meta, self.connection_aligned(c, a.as_ref()))
.with_comma(c.comma)
})
})
.collect()
}
Connections::Ordered(list) => list
.iter()
.map(|c| {
let d = match &c.expr {
Some(e) => self.expr(e),
None => text(""),
};
ListItem::from_meta(&c.meta, d).with_comma(c.comma)
self.list_elem(c, |c| {
let d = match &c.expr {
Some(e) => self.expr(e),
None => text(""),
};
ListItem::from_meta(&c.meta, d).with_comma(c.comma)
})
})
.collect(),
};
@@ -132,18 +140,20 @@ impl<'a> Fmt<'a> {
/// The alignment plan for an instance's named connection list.
fn connection_aligns(
&self,
conns: &[Connection],
conns: &[ListElem<Connection>],
directives: &[ListDirective],
depth: usize,
) -> Vec<Option<Align>> {
let rows: Vec<Option<Row>> = conns
.iter()
.map(|c| {
// An error element has no cells to align, so it has no row.
let c = c.ok()?;
let paren = self.open_paren_offset(c.name_span.end)?;
Self::row_of(&self.connection_cells(c), vec![paren], usize::from(c.comma))
})
.collect();
let breaks = Self::list_breaks(conns.iter().map(|c| &c.meta), directives);
let breaks = Self::list_breaks(conns.iter().map(|c| c.ok().map(|c| &c.meta)), directives);
self.align_groups(&rows, &breaks, CONNECTION_COLS, depth)
}
@@ -369,8 +379,8 @@ impl<'a> Fmt<'a> {
/// be measured as one short line and flattened around a value that is
/// twenty lines tall. It is exactly the reason a list holding a
/// [`ListDirective`] is broken, for exactly the same construct.
fn holds_verbatim_value(list: &[Connection]) -> bool {
list.iter().any(|c| match &c.expr {
fn holds_verbatim_value(list: &[ListElem<Connection>]) -> bool {
list.iter().filter_map(ListElem::ok).any(|c| match &c.expr {
Some(Expr { kind: ExprKind::Verbatim(raw), .. }) => raw.text.contains('\n'),
_ => false,
})
+40 -2
View File
@@ -38,6 +38,27 @@ pub(super) struct ListItem {
}
impl ListItem {
/// The entry an error element of a header list prints as: the text a
/// tolerant parse skipped, verbatim, carrying no comments of its own —
/// they are bytes of that text.
///
/// **Unreachable from `format_source`**, exactly as `ItemKind::Error` is:
/// the formatter parses strictly, and only [`vlog_parser::parse_tolerant`]
/// builds a [`ListElem::Error`]. Printing the bytes rather than nothing
/// means that if some future entry point ever did hand one over,
/// `verify.rs`'s token-equivalence check would see the tokens instead of
/// silently losing them.
pub(super) fn from_raw(doc: Doc) -> Self {
ListItem {
leading: Vec::new(),
doc,
before_sep: Vec::new(),
trailing: None,
comma: None,
directive: false,
}
}
pub(super) fn from_meta(meta: &Meta, doc: Doc) -> Self {
ListItem {
leading: meta.leading.clone(),
@@ -58,6 +79,20 @@ impl ListItem {
}
impl<'a> Fmt<'a> {
/// One entry of a **header** list: the element as `entry` prints it, or —
/// for an error element — its bytes; see [`ListItem::from_raw`] for why
/// the second case cannot be reached from `format_source`.
pub(super) fn list_elem<T>(
&self,
elem: &ListElem<T>,
entry: impl FnOnce(&T) -> ListItem,
) -> ListItem {
match elem {
ListElem::Ok(v) => entry(v),
ListElem::Error(raw) => ListItem::from_raw(self.raw_text(raw)),
}
}
/// A bracketed expression list (concatenation, call arguments, `inside`
/// set). Comments on an element ride along and break the list open.
pub(super) fn expr_list(&self, open: &str, items: &[ExprItem], close: &str) -> Doc {
@@ -316,15 +351,18 @@ impl<'a> Fmt<'a> {
/// with a comment or an attribute of their own — both print on their own
/// line — and those a compiler directive was written in front of.
///
/// A `None` meta is an error element, which has none; it always starts a
/// group, being raw bytes of a width no other row shares.
///
/// A blank line is deliberately *not* a boundary here: `delimited` drops
/// blank lines between list elements, so a boundary drawn at one would
/// vanish from the output and the next pass would group differently.
pub(super) fn list_breaks<'m>(
metas: impl Iterator<Item = &'m Meta>,
metas: impl Iterator<Item = Option<&'m Meta>>,
directives: &[ListDirective],
) -> Vec<bool> {
let mut breaks: Vec<bool> =
metas.map(|m| !m.leading.is_empty() || !m.attrs.is_empty()).collect();
metas.map(|m| m.is_none_or(|m| !m.leading.is_empty() || !m.attrs.is_empty())).collect();
for d in directives {
if let Some(b) = breaks.get_mut(d.before) {
*b = true;
+16 -6
View File
@@ -67,7 +67,11 @@ impl<'a> Fmt<'a> {
if let Some(params) = &m.param_ports {
let items: Vec<ListItem> = params
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma))
.map(|p| {
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma)
})
})
.collect();
let items = self.list_entries(items, &m.param_directives);
let broken = !m.param_directives.is_empty();
@@ -94,15 +98,19 @@ impl<'a> Fmt<'a> {
.iter()
.zip(&aligns)
.map(|(p, a)| {
ListItem::from_meta(&p.meta, self.ansi_port(p, a.as_ref()))
.with_comma(p.comma)
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.ansi_port(p, a.as_ref()))
.with_comma(p.comma)
})
})
.collect()
}
PortList::NonAnsi(ports) => ports
.iter()
.map(|p| {
ListItem::from_meta(&p.meta, name_doc(&p.name)).with_comma(p.comma)
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, name_doc(&p.name)).with_comma(p.comma)
})
})
.collect(),
_ => Vec::new(),
@@ -223,13 +231,15 @@ impl<'a> Fmt<'a> {
/// The alignment plan for a module header's ANSI port list.
fn ansi_port_aligns(
&self,
ports: &[AnsiPort],
ports: &[ListElem<AnsiPort>],
directives: &[ListDirective],
depth: usize,
) -> Vec<Option<Align>> {
let rows: Vec<Option<Row>> = ports
.iter()
.map(|p| {
// An error element has no cells to align, so it has no row.
let p = p.ok()?;
Self::row_of(
&self.ansi_port_cells(p),
vec![p.name_span.start],
@@ -237,7 +247,7 @@ impl<'a> Fmt<'a> {
)
})
.collect();
let breaks = Self::list_breaks(ports.iter().map(|p| &p.meta), directives);
let breaks = Self::list_breaks(ports.iter().map(|p| p.ok().map(|p| &p.meta)), directives);
self.align_groups(&rows, &breaks, ANSI_PORT_COLS, depth)
}
+6 -4
View File
@@ -27,7 +27,7 @@ pub(super) struct TfHeader<'h> {
name: &'h str,
has_parens: bool,
before_args: &'h [Comment],
args: &'h [TfArg],
args: &'h [ListElem<TfArg>],
args_dangling: &'h [Comment],
}
@@ -119,9 +119,11 @@ impl<'a> Fmt<'a> {
}
}
pub(super) fn tf_args(&self, args: &[TfArg], dangling: &[Comment]) -> Doc {
let items: Vec<ListItem> =
args.iter().map(|a| ListItem::from_meta(&a.meta, self.tf_arg(a))).collect();
pub(super) fn tf_args(&self, args: &[ListElem<TfArg>], dangling: &[Comment]) -> Doc {
let items: Vec<ListItem> = args
.iter()
.map(|a| self.list_elem(a, |a| ListItem::from_meta(&a.meta, self.tf_arg(a))))
.collect();
self.delimited_dangling("(", items, dangling, ")", false)
}
@@ -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());
}
+165
View File
@@ -9,12 +9,20 @@ use vlog_parser::token::{Comment, Token, TokenKind};
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LexError, LineIndex};
use vlog_semantic::{analyze, Semantics};
use crate::options::RuleOptions;
use crate::signals::Signals;
/// The default tab stop used when a fix expands a tab, matching lucisv's
/// default indent. `LintContext::with_tab_width` follows `--indent`.
const DEFAULT_TAB_WIDTH: usize = 2;
/// The width `line-length` holds a file to when nothing says otherwise —
/// `vlog_formatter::Config`'s own default, because the two are the same
/// number: a formatted file that the linter then calls too wide would be
/// lucisv disagreeing with itself. `LintContext::with_line_length` follows
/// `--line-length` and `lucisv.toml`.
const DEFAULT_LINE_LENGTH: usize = 100;
/// One text, parsed once: the products a lint run reads.
///
/// This is the owned half of "one parse, two tools" (TODO §4): a caller with
@@ -84,6 +92,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 +143,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 +188,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>),
@@ -149,6 +209,10 @@ pub struct LintContext<'a> {
backing: Backing<'a>,
path: Option<PathBuf>,
tab_width: usize,
line_length: usize,
/// What the run configured about each rule, or `None` for a run that
/// configured nothing — which reads exactly as the specs' own defaults.
options: Option<&'a RuleOptions>,
/// Byte ranges of string literals, ascending — the one place text rules
/// must not rewrite, because there whitespace is data.
strings: Vec<TextRange>,
@@ -156,6 +220,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
@@ -199,9 +266,12 @@ impl<'a> LintContext<'a> {
backing,
path,
tab_width: DEFAULT_TAB_WIDTH,
line_length: DEFAULT_LINE_LENGTH,
options: None,
strings: Vec::new(),
semantics: SemanticsSlot::Lazy(OnceCell::new()),
signals: OnceCell::new(),
clean: OnceCell::new(),
oracle: None,
};
ctx.strings =
@@ -215,6 +285,68 @@ impl<'a> LintContext<'a> {
self
}
/// Sets the width the run's formatter would wrap to, which is what
/// `line-length` holds the file to unless that rule's own `length` option
/// says otherwise.
pub fn with_line_length(mut self, line_length: usize) -> LintContext<'a> {
self.line_length = line_length.max(1);
self
}
/// Lends the per-rule options the run resolved. A context without them
/// reads every option at its declared default, which is the shipped
/// behaviour.
pub fn with_options(mut self, options: &'a RuleOptions) -> LintContext<'a> {
self.options = Some(options);
self
}
/// The width the run's formatter wraps to. See
/// [`with_line_length`](LintContext::with_line_length).
pub fn line_length(&self) -> usize {
self.line_length
}
/// What the run configured, or the empty set.
pub fn options(&self) -> &RuleOptions {
match self.options {
Some(options) => options,
None => RuleOptions::none(),
}
}
/// One boolean option of `rule`, or its declared default.
pub fn option_bool(&self, rule: &str, key: &str) -> bool {
self.options().bool(rule, key)
}
/// One integer option of `rule`, or its declared default.
pub fn option_int(&self, rule: &str, key: &str) -> i64 {
self.options().int(rule, key)
}
/// One string (or pattern) option of `rule`, or its declared default.
pub fn option_str(&self, rule: &str, key: &str) -> &str {
self.options().str(rule, key)
}
/// One list option of `rule`, or its declared default.
pub fn option_list(&self, rule: &str, key: &str) -> Vec<String> {
self.options().list(rule, key)
}
/// Whether the run said anything about this option at all — the question
/// a rule asks when its fallback is not its spec's default.
pub fn option_is_set(&self, rule: &str, key: &str) -> bool {
self.options().is_set(rule, key)
}
/// One pattern option of `rule`, compiled, or `None` if it does not
/// compile — which cannot happen for a value this run accepted.
pub(crate) fn option_pattern(&self, rule: &str, key: &str) -> Option<crate::regex::Regex> {
crate::options::pattern(self.options(), rule, key)
}
/// Lends the symbol table the caller already built for this exact text —
/// "one parse, two tools" extended to the analysis (the language server
/// analyzes every buffer anyway, so its lint pass must not analyze twice).
@@ -245,6 +377,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 +405,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 {
+331
View File
@@ -0,0 +1,331 @@
//! 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, ListElem, SourceFile, StmtKind, StructType,
TaskDecl, TfArg, TypeExtra, TypedefKind,
};
use vlog_parser::span::TextRange;
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.iter().filter_map(ListElem::ok) {
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.iter().filter_map(ListElem::ok) {
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: &[ListElem<TfArg>], unpacked: &mut dyn FnMut(&[Dim])) {
for arg in args.iter().filter_map(ListElem::ok) {
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.iter().filter_map(ListElem::ok) {
visit(&arg.ty);
}
}
fn task_types(decl: &TaskDecl, visit: &mut dyn FnMut(&DataType)) {
for arg in decl.args.iter().filter_map(ListElem::ok) {
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);
}
}
/// A type written in a declaration, with the name that declaration gives.
///
/// What the two `typedef-*` rules need and `walk_data_types` cannot say: a
/// `DataType` carries no span of its own, so a rule that judges the *type* of
/// a declaration reports at the name — and needs to know whether that
/// declaration is nested inside another aggregate's body.
pub(crate) struct DeclaredType<'a> {
/// The type as written.
pub(crate) ty: &'a DataType,
/// The name declared with it.
pub(crate) name: &'a str,
/// Byte range of that name — where a finding points.
pub(crate) span: TextRange,
/// True when this declaration is a member of another `struct`/`union`.
pub(crate) nested: bool,
}
/// Calls `f` on every type written in a **declaration** — a data or port
/// declaration, an ANSI port, a variable declaration in a statement — and on
/// every member of an aggregate written inside one.
///
/// A `typedef`'s own base type is deliberately not visited: a named type is
/// exactly what the `typedef-*` rules ask for, so passing it to them would be
/// asking them to flag the shape they exist to encourage. Its members are
/// visited, as nested declarations.
pub(crate) fn walk_declared_types(file: &SourceFile, f: &mut dyn FnMut(&DeclaredType)) {
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.iter().filter_map(ListElem::ok) {
declared(&port.ty, &port.name, port.name_span, false, f);
}
}
}
ItemKind::DataDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
ItemKind::PortDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
// Only the members: the typedef itself is the named type these rules
// want, and the naming rules judge its name.
ItemKind::Typedef(typedef) => typedef_members(&typedef.kind, f),
_ => {}
});
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
StmtKind::VarDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
StmtKind::PortDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
StmtKind::Typedef(typedef) => typedef_members(&typedef.kind, f),
_ => {}
});
}
/// One declaration, and whatever aggregate its type carries.
fn declared(
ty: &DataType,
name: &str,
span: TextRange,
nested: bool,
f: &mut dyn FnMut(&DeclaredType),
) {
f(&DeclaredType { ty, name, span, nested });
members_of(ty, f);
}
/// One declaration's type, once per name it declares.
fn declarator_types(
ty: &DataType,
declarators: &[vlog_parser::ast::Declarator],
f: &mut dyn FnMut(&DeclaredType),
) {
for declarator in declarators {
declared(ty, &declarator.name, declarator.name_span, false, f);
}
}
/// The members of an anonymous aggregate, and of the aggregates inside it.
fn members_of(ty: &DataType, f: &mut dyn FnMut(&DeclaredType)) {
if let Some(TypeExtra::Struct(structure)) = ty.inline() {
struct_members(structure, f);
}
}
/// The members of a `struct`/`union` body, each as a nested declaration.
fn struct_members(structure: &StructType, f: &mut dyn FnMut(&DeclaredType)) {
for member in &structure.members {
for declarator in &member.declarators {
f(&DeclaredType {
ty: &member.ty,
name: &declarator.name,
span: declarator.name_span,
nested: true,
});
}
members_of(&member.ty, f);
}
}
/// A typedef's members — everything inside its body, but not the body itself.
fn typedef_members(kind: &TypedefKind, f: &mut dyn FnMut(&DeclaredType)) {
if let TypedefKind::Struct(structure) = kind {
struct_members(structure, f);
}
}
/// 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]"]);
}
}
+182
View File
@@ -0,0 +1,182 @@
//! 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, ListElem, 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().filter_map(ListElem::ok).map(|port| port.name.clone()).collect()
}
PortList::NonAnsi(ports) => {
ports.iter().filter_map(ListElem::ok).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().filter_map(ListElem::ok) {
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"]);
}
}
+55 -4
View File
@@ -21,26 +21,40 @@
//! `docs/features/linter-core/README.md`.
mod context;
mod decls;
mod interfaces;
mod literal;
mod module_decls;
mod naming;
mod options;
mod regex;
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 options::{OptionDefault, OptionKind, OptionSpec, OptionValue, RuleOptions};
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 +101,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::*;
@@ -172,11 +201,12 @@ mod tests {
// Real corpus RTL is annotated for Verible. Waivers naming rules lucisv
// has not implemented are that codebase's, not typos, so they are
// neither honored nor reported.
let src = "module m;\n // verilog_lint: waive macro-name-style\n wire a;\nendmodule\n";
let src = "module m;\n // verilog_lint: waive explicit-function-lifetime\n wire a;\nendmodule\n";
assert!(lint_all(src).is_empty());
// lucisv's own spelling gets no such benefit of the doubt.
let src = "module m;\n // lucisv: waive macro-name-style\n wire a;\nendmodule\n";
let src =
"module m;\n // lucisv: waive explicit-function-lifetime\n wire a;\nendmodule\n";
assert_eq!(names(&lint_all(src)), vec![UNUSED_WAIVER]);
}
@@ -211,6 +241,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");
}
}
+233
View File
@@ -0,0 +1,233 @@
//! The nets, variables and ports a module declares — what the two signal
//! naming rules judge.
//!
//! A module's own declarations are a different population from "every
//! declared name in the file": a class property, a loop variable and a
//! function local are not signals, and a rule that judged them would be
//! reporting on things the style guide says nothing about. Collecting them
//! lives here rather than in `visit` (the item and statement spines) or
//! `decls` (types and dimensions), so each of the three files stays one
//! sentence long.
use vlog_parser::ast::{
AnsiPort, GenBlock, GenElse, Item, ItemKind, ListElem, PortList, SourceFile,
};
use vlog_parser::span::TextRange;
/// One net, variable or port a module declares.
pub(crate) struct SignalDecl {
/// The declared name, as written.
pub(crate) name: String,
/// Byte range of that name.
pub(crate) span: TextRange,
/// The word a diagnostic calls it: `port` or `signal`.
pub(crate) what: &'static str,
/// The direction of a port, as written (`input`, `output`, `inout`), or
/// `None` for a signal.
pub(crate) dir: Option<String>,
}
/// Every net, variable and port declared inside a module, interface or
/// program of `file`, header and body alike, generate blocks included.
///
/// A `class` body is deliberately not descended into: its properties are not
/// signals. A function or task body is not either — a local is scoped to the
/// subroutine and named for it.
pub(crate) fn module_signals(file: &SourceFile) -> Vec<SignalDecl> {
let mut out = Vec::new();
for item in &file.items {
collect_item(item, &mut out);
}
out
}
fn collect_item(item: &Item, out: &mut Vec<SignalDecl>) {
match &item.kind {
ItemKind::Module(module) => {
header_ports(&module.ports, out);
for inner in &module.items {
collect_body(inner, out);
}
}
// A module may be written inside a package; nothing else at file
// level holds one.
ItemKind::Package { items, .. } => {
for inner in items {
collect_item(inner, out);
}
}
_ => {}
}
}
/// One item of a module body.
fn collect_body(item: &Item, out: &mut Vec<SignalDecl>) {
match &item.kind {
ItemKind::DataDecl(decl) => {
for declarator in &decl.declarators {
out.push(SignalDecl {
name: declarator.name.clone(),
span: declarator.name_span,
what: "signal",
dir: None,
});
}
}
ItemKind::PortDecl(decl) => {
for declarator in &decl.declarators {
out.push(SignalDecl {
name: declarator.name.clone(),
span: declarator.name_span,
what: "port",
dir: Some(decl.dir.clone()),
});
}
}
// A nested module is a module of its own.
ItemKind::Module(_) => collect_item(item, out),
ItemKind::GenerateRegion { items, .. } => {
for inner in items {
collect_body(inner, out);
}
}
ItemKind::GenIf(gen_if) => {
block(&gen_if.then, out);
let mut els = gen_if.els.as_deref();
while let Some(branch) = els {
match branch {
GenElse::If(_, nested) => {
block(&nested.then, out);
els = nested.els.as_deref();
}
GenElse::Block(inner) => {
block(inner, out);
els = None;
}
}
}
}
ItemKind::GenFor(gen_for) => block(&gen_for.body, out),
ItemKind::GenCase(gen_case) => {
for case_item in &gen_case.items {
block(&case_item.body, out);
}
}
_ => {}
}
}
fn block(block: &GenBlock, out: &mut Vec<SignalDecl>) {
for item in &block.items {
collect_body(item, out);
}
}
/// The ports of a module header, in either style.
fn header_ports(ports: &PortList, out: &mut Vec<SignalDecl>) {
match ports {
PortList::Ansi(ports) => {
// A port with no direction keyword continues the previous one, as
// the language says; a first port with none is `inout` by default.
let mut carried: Option<String> = None;
for port in ports.iter().filter_map(ListElem::ok) {
carried = direction(port).or(carried);
out.push(SignalDecl {
name: port.name.clone(),
span: port.name_span,
what: "port",
dir: carried.clone(),
});
}
}
// A non-ANSI header *names* its ports; the body declares them
// (`input clk;`), and that declaration is the one collected — so a
// rule reports each port once, where its direction is written.
PortList::NonAnsi(_) | PortList::None | PortList::Empty => {}
}
}
fn direction(port: &AnsiPort) -> Option<String> {
port.dir.clone()
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::parse_source_tolerant;
fn signals(src: &str) -> Vec<(String, &'static str, Option<String>)> {
let (file, _) = parse_source_tolerant(src);
module_signals(&file).into_iter().map(|decl| (decl.name, decl.what, decl.dir)).collect()
}
#[test]
fn collects_header_ports_body_ports_and_signals() {
let src = "module m (input logic clk, output data);\n\
\x20 wire a;\n\
\x20 logic [7:0] b, c;\n\
endmodule\n";
assert_eq!(
signals(src),
vec![
("clk".to_string(), "port", Some("input".to_string())),
("data".to_string(), "port", Some("output".to_string())),
("a".to_string(), "signal", None),
("b".to_string(), "signal", None),
("c".to_string(), "signal", None),
]
);
}
#[test]
fn a_port_with_no_direction_continues_the_previous_one() {
let src = "module m (input logic a, b, output c);\nendmodule\n";
let dirs: Vec<Option<String>> = signals(src).into_iter().map(|s| s.2).collect();
assert_eq!(
dirs,
vec![Some("input".to_string()), Some("input".to_string()), Some("output".to_string())]
);
}
/// A non-ANSI port is declared once, in the body: the header only lists
/// the names, and collecting those too would report every such port
/// twice.
#[test]
fn a_non_ansi_port_is_collected_where_the_body_declares_it() {
let src = "module m (a, b);\n input a;\n output b;\nendmodule\n";
assert_eq!(
signals(src),
vec![
("a".to_string(), "port", Some("input".to_string())),
("b".to_string(), "port", Some("output".to_string())),
]
);
}
#[test]
fn generate_blocks_are_descended_into_and_class_bodies_are_not() {
let src = "module m;\n\
\x20 generate\n\
\x20 if (A) begin : g\n wire in_gen;\n end\n\
\x20 endgenerate\n\
\x20 for (genvar i = 0; i < 2; i++) begin : l\n wire looped;\n end\n\
endmodule\n\
class c;\n logic property_of_a_class;\nendclass\n";
let names: Vec<String> = signals(src).into_iter().map(|s| s.0).collect();
assert_eq!(names, vec!["in_gen".to_string(), "looped".to_string()]);
}
#[test]
fn an_interface_and_a_module_in_a_package_are_covered() {
let src = "interface i (input clk);\n wire w;\nendinterface\n\
package p;\n module inner;\n wire deep;\n endmodule\nendpackage\n";
let names: Vec<String> = signals(src).into_iter().map(|s| s.0).collect();
assert_eq!(names, vec!["clk".to_string(), "w".to_string(), "deep".to_string()]);
}
#[test]
fn a_function_local_is_not_a_signal() {
let src = "module m;\n function void f();\n logic local_var;\n endfunction\n\
endmodule\n";
assert!(signals(src).is_empty());
}
}
+106 -21
View File
@@ -1,13 +1,12 @@
//! The naming-style presets the naming rules check against.
//!
//! Verible spells its naming conventions as RE2 regular expressions. lucisv
//! spells the same conventions as character-class predicates instead, on
//! purpose: every preset anyone actually uses is "these character classes, in
//! this order", which is four small functions — and a regex engine is a
//! dependency this crate (today: `vlog_parser` + std) does not otherwise need.
//! The cost is that user-supplied patterns are not expressible; that waits on
//! the `lint` key in `lucisv.toml` and is recorded as such in
//! `docs/features/lint-rules-2/README.md`.
//! Verible spells its naming conventions as RE2 regular expressions, and
//! since §34 so does lucisv: `crate::regex` reads the subset a style guide is
//! written in, and each naming rule takes the pattern as an option whose
//! default is the preset it shipped with. What survives here are the two
//! `CamelCase`/`ALL_CAPS` predicates — Verible spells those as *words* in
//! `parameter_style`, not as patterns — and the three small helpers every
//! naming rule shares.
//!
//! An **escaped identifier** (`\my$name `) is exempt from every style: its
//! whole point is to carry characters no convention allows.
@@ -17,13 +16,6 @@ pub(crate) fn is_escaped(name: &str) -> bool {
name.starts_with('\\')
}
/// `lower_snake_case`: starts with a lowercase letter, then lowercase
/// letters, digits and underscores.
pub(crate) fn is_lower_snake_case(name: &str) -> bool {
starts_with(name, char::is_ascii_lowercase)
&& name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}
/// `UPPER_SNAKE_CASE`: starts with an uppercase letter, then uppercase
/// letters, digits and underscores. Verible calls this preset `ALL_CAPS`.
pub(crate) fn is_upper_snake_case(name: &str) -> bool {
@@ -37,6 +29,80 @@ pub(crate) fn is_camel_case(name: &str) -> bool {
starts_with(name, char::is_ascii_uppercase) && name.chars().all(|c| c.is_ascii_alphanumeric())
}
/// The vocabulary Verible's `*_style` options are written in, and the one
/// [`matches_style_words`] reads.
pub(crate) const STYLE_WORDS: [&str; 2] = ["CamelCase", "ALL_CAPS"];
/// Whether `name` fits any of the `|`-separated preset words of a `*_style`
/// option (`CamelCase|ALL_CAPS`). A word outside the vocabulary cannot reach
/// here — the option refuses it — so an unknown one simply matches nothing.
pub(crate) fn matches_style_words(name: &str, spelling: &str) -> bool {
spelling.split('|').map(str::trim).any(|word| match word {
"CamelCase" => is_camel_case(name),
"ALL_CAPS" => is_upper_snake_case(name),
_ => false,
})
}
/// Whether `name` is one this rule accepts, given a `*_style_regex` override
/// the run may have set and the `*_style` words otherwise.
///
/// The two-key shape is Verible's: the words are what a style guide says, and
/// the pattern is the escape hatch for a project whose convention is neither.
/// An override that does not compile cannot be set (the option is validated
/// when it is read), so a `None` pattern here means "nobody set one".
pub(crate) fn fits_style(
ctx: &crate::context::LintContext,
rule: &str,
style_key: &str,
regex_key: &str,
name: &str,
) -> bool {
if ctx.option_is_set(rule, regex_key) {
return match ctx.option_pattern(rule, regex_key) {
Some(pattern) => pattern.is_match(name),
None => true,
};
}
matches_style_words(name, ctx.option_str(rule, style_key))
}
/// Whether `name` matches this rule's single pattern option — the shape the
/// three type-and-module naming rules take.
pub(crate) fn fits_pattern(
ctx: &crate::context::LintContext,
rule: &str,
regex_key: &str,
name: &str,
) -> bool {
match ctx.option_pattern(rule, regex_key) {
Some(pattern) => pattern.is_match(name),
// Unreachable for a validated option; being quiet is the safe
// direction for a rule that cannot tell what it was asked.
None => true,
}
}
/// What a naming rule says about a name it rejected.
///
/// A run that configured nothing reads the preset's own words — the sentence
/// the rule has always printed, so a default run's diagnostics are the ones
/// CI already has — and a run that set a pattern is told **which** pattern it
/// failed, because "is not lower_snake_case" would be a lie there.
pub(crate) fn style_message(
ctx: &crate::context::LintContext,
rule: &str,
regex_key: &str,
subject: &str,
preset: &str,
) -> String {
if ctx.option_is_set(rule, regex_key) {
format!("{subject} does not match `{}`", ctx.option_str(rule, regex_key))
} else {
format!("{subject} {preset}")
}
}
/// True when `name` is non-empty and its first character passes `first`.
fn starts_with(name: &str, first: impl Fn(&char) -> bool) -> bool {
name.chars().next().is_some_and(|c| first(&c))
@@ -46,13 +112,32 @@ fn starts_with(name: &str, first: impl Fn(&char) -> bool) -> bool {
mod tests {
use super::*;
/// The `lower_snake_case` preset the three type-and-module naming rules
/// used before §34 gave them `style_regex` is now spelled as the pattern
/// `[a-z][a-z_0-9]*`, and the two accept exactly the same names — which
/// is what keeps those rules' findings byte-identical.
#[test]
fn lower_snake_case_accepts_what_rtl_writes() {
for name in ["a", "clk", "data_i", "fifo2_wr_en", "a1_b2"] {
assert!(is_lower_snake_case(name), "{name}");
}
for name in ["", "Clk", "_clk", "clkA", "clk-en", "CLK", "1clk"] {
assert!(!is_lower_snake_case(name), "{name}");
fn the_lower_snake_case_pattern_is_the_preset_it_replaced() {
let pattern = crate::regex::Regex::compile("[a-z][a-z_0-9]*").expect("compiles");
let preset = |name: &str| {
name.chars().next().is_some_and(|c| c.is_ascii_lowercase())
&& name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
};
for name in [
"a",
"clk",
"data_i",
"fifo2_wr_en",
"a1_b2",
"",
"Clk",
"_clk",
"clkA",
"clk-en",
"CLK",
"1clk",
] {
assert_eq!(pattern.is_match(name), preset(name), "{name}");
}
}
+602
View File
@@ -0,0 +1,602 @@
//! Per-rule options: what a rule may be configured with, and the validated
//! map one run carries.
//!
//! Verible gives most of its rules a handful of options (`style_regex`,
//! `length`, the `*_enable` switches) and spells them
//! `--rules=rule-name=option:value`. lucisv spells them where its other
//! settings already live — a `[lint.<rule>]` table in `lucisv.toml`, a
//! `lucisv.lint.options` object in the editor — and both doors come through
//! this module, so the two front ends cannot disagree about what a value
//! means or which values are refused.
//!
//! A rule never sees "unset": every read falls back to the spec's own
//! default, which is also the default the generated rule reference prints.
//! See `docs/features/linter-expansion-2/README.md`.
use std::collections::BTreeMap;
use crate::regex::Regex;
use crate::registry::rule_by_name;
/// What kind of value one option takes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OptionKind {
/// `true` / `false`.
Bool,
/// An integer within the inclusive bounds.
Int {
/// Smallest accepted value.
min: i64,
/// Largest accepted value.
max: i64,
},
/// Any string.
Str,
/// A string that must compile as a pattern (see [`crate::regex`]).
Regex,
/// A list of strings.
List,
/// A list of strings, each of which must compile as a pattern.
RegexList,
/// One or more words from a fixed vocabulary, joined with `|` — how
/// Verible writes `parameter_style:CamelCase|ALL_CAPS`.
Words(&'static [&'static str]),
}
impl OptionKind {
/// The word `--rules-doc` and the settings UI name this kind with.
pub fn as_str(self) -> &'static str {
match self {
OptionKind::Bool => "boolean",
OptionKind::Int { .. } => "integer",
OptionKind::Str => "string",
OptionKind::Regex => "pattern",
OptionKind::List => "list of strings",
OptionKind::RegexList => "list of patterns",
OptionKind::Words(_) => "`|`-separated word list",
}
}
/// The vocabulary a [`OptionKind::Words`] option accepts, for the
/// generated reference; empty for every other kind.
pub fn vocabulary(self) -> &'static [&'static str] {
match self {
OptionKind::Words(words) => words,
_ => &[],
}
}
}
/// One option's value, as a run holds it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OptionValue {
/// A boolean.
Bool(bool),
/// An integer.
Int(i64),
/// A string — a pattern included, which is a string that compiled.
Str(String),
/// A list of strings.
List(Vec<String>),
}
impl OptionValue {
/// The word an error message calls this value's kind, so "expects an
/// integer, found a list" reads as a sentence.
fn kind_word(&self) -> &'static str {
match self {
OptionValue::Bool(_) => "a boolean",
OptionValue::Int(_) => "an integer",
OptionValue::Str(_) => "a string",
OptionValue::List(_) => "a list",
}
}
}
/// One option's default, as a rule declares it.
///
/// A second type rather than an [`OptionValue`], because a spec lives in a
/// `static` table: `&'static str` and `&'static [&'static str]` are
/// constructible there and `String`/`Vec<String>` are not. [`Self::value`]
/// is the bridge for a caller that wants the owned form.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OptionDefault {
/// A boolean default.
Bool(bool),
/// An integer default.
Int(i64),
/// A string (or pattern) default.
Str(&'static str),
/// A list default.
List(&'static [&'static str]),
}
impl OptionDefault {
/// The owned value this default stands for.
pub fn value(self) -> OptionValue {
match self {
OptionDefault::Bool(b) => OptionValue::Bool(b),
OptionDefault::Int(n) => OptionValue::Int(n),
OptionDefault::Str(s) => OptionValue::Str(s.to_string()),
OptionDefault::List(items) => {
OptionValue::List(items.iter().map(|s| s.to_string()).collect())
}
}
}
/// How the rule reference and the settings UI print this default.
pub fn as_written(self) -> String {
match self {
OptionDefault::Bool(b) => b.to_string(),
OptionDefault::Int(n) => n.to_string(),
OptionDefault::Str(s) => format!("\"{s}\""),
OptionDefault::List(items) => {
let inner: Vec<String> = items.iter().map(|s| format!("\"{s}\"")).collect();
format!("[{}]", inner.join(", "))
}
}
}
}
/// One option a rule declares: its name, its kind, what it is when nobody
/// says otherwise, and what it is for.
#[derive(Debug, Clone, Copy)]
pub struct OptionSpec {
/// The key a user writes, as Verible spells it where there is an
/// equivalent.
pub name: &'static str,
/// What kind of value it takes.
pub kind: OptionKind,
/// The value a rule reads when nobody configured it.
pub default: OptionDefault,
/// One line saying what it does — the text `--rules-doc` prints.
pub doc: &'static str,
}
/// The options a run resolved to: `rule → key → value`, validated.
///
/// Only what somebody actually set is in here. A rule asks for an option it
/// declares and gets the spec's default when this map is silent, which is why
/// no rule has an "unset" case to handle and why an empty map is exactly the
/// shipped behaviour.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RuleOptions {
values: BTreeMap<(String, String), OptionValue>,
}
/// The options a run with nothing configured has — what a context that was
/// lent none reads from.
static NONE: RuleOptions = RuleOptions::new();
impl RuleOptions {
/// An empty set of options.
pub const fn new() -> RuleOptions {
RuleOptions { values: BTreeMap::new() }
}
/// The shared empty set, for a caller with nothing to configure.
pub(crate) fn none() -> &'static RuleOptions {
&NONE
}
/// Whether anything at all was configured.
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
/// Sets one option from the text a `lucisv.toml` wrote after the `=`.
///
/// The value's shape is read **against the spec's kind** — `true`, `42`,
/// `"text"`, `["a", "b"]` — so the message a user gets names the kind the
/// option actually takes rather than TOML's idea of what they typed.
/// Unlike `lucisv_core::config`'s strings, a backslash is an ordinary
/// character here: a pattern is the one value that needs them.
pub fn set_raw(&mut self, rule: &str, key: &str, raw: &str) -> Result<(), String> {
let spec = spec_of(rule, key)?;
let value = parse_raw(&spec, raw)?;
self.insert(rule, key, value)
}
/// Sets one option from a value a front end already decoded (the editor's
/// JSON). Validated exactly as [`Self::set_raw`]'s is.
pub fn set(&mut self, rule: &str, key: &str, value: OptionValue) -> Result<(), String> {
let spec = spec_of(rule, key)?;
let value = check(&spec, value)?;
self.insert(rule, key, value)
}
fn insert(&mut self, rule: &str, key: &str, value: OptionValue) -> Result<(), String> {
self.values.insert((rule.to_string(), key.to_string()), value);
Ok(())
}
/// Lays `other`'s entries over this set's, key by key.
///
/// The merge the two front ends need: a `lucisv.toml`'s options are the
/// base and the editor's are laid over them one key at a time, so a
/// project that sets two options and a user who overrides one keep the
/// other. Both sides were validated when they were read, so nothing can
/// be refused here.
pub fn overlay(&mut self, other: &RuleOptions) {
for (key, value) in &other.values {
self.values.insert(key.clone(), value.clone());
}
}
/// Whether this run set `key` on `rule` at all — the one question a rule
/// asks when its default is not a constant (`line-length`'s `length`
/// falls back to the formatter's width).
pub fn is_set(&self, rule: &str, key: &str) -> bool {
self.lookup(rule, key).is_some()
}
/// A boolean option's value, or its default.
pub fn bool(&self, rule: &str, key: &str) -> bool {
match (self.lookup(rule, key), default_of(rule, key)) {
(Some(OptionValue::Bool(b)), _) => *b,
(_, Some(OptionDefault::Bool(b))) => b,
_ => false,
}
}
/// An integer option's value, or its default.
pub fn int(&self, rule: &str, key: &str) -> i64 {
match (self.lookup(rule, key), default_of(rule, key)) {
(Some(OptionValue::Int(n)), _) => *n,
(_, Some(OptionDefault::Int(n))) => n,
_ => 0,
}
}
/// A string (or pattern) option's value, or its default.
pub fn str(&self, rule: &str, key: &str) -> &str {
match (self.lookup(rule, key), default_of(rule, key)) {
(Some(OptionValue::Str(s)), _) => s,
(_, Some(OptionDefault::Str(s))) => s,
_ => "",
}
}
/// A list option's value, or its default.
pub fn list(&self, rule: &str, key: &str) -> Vec<String> {
match (self.lookup(rule, key), default_of(rule, key)) {
(Some(OptionValue::List(items)), _) => items.clone(),
(_, Some(OptionDefault::List(items))) => {
items.iter().map(|item| item.to_string()).collect()
}
_ => Vec::new(),
}
}
fn lookup(&self, rule: &str, key: &str) -> Option<&OptionValue> {
// A borrowed lookup without allocating the pair: the map is tiny (a
// handful of entries at most), so a scan is cheaper than the two
// `String`s a keyed lookup would build on every rule's every read.
self.values.iter().find(|((r, k), _)| r == rule && k == key).map(|(_, value)| value)
}
}
/// The spec for `rule`'s `key`, or the message a user should read instead.
fn spec_of(rule: &str, key: &str) -> Result<OptionSpec, String> {
let found = rule_by_name(rule).ok_or_else(|| format!("unknown rule `{rule}`"))?;
let options = found.options();
if options.is_empty() {
return Err(format!("rule `{rule}` takes no options"));
}
options.iter().find(|spec| spec.name == key).copied().ok_or_else(|| {
let known = options.iter().map(|spec| spec.name).collect::<Vec<_>>().join(", ");
format!("rule `{rule}` has no option `{key}`; it has: {known}")
})
}
/// One option's declared default, or `None` for a key no rule declares —
/// which the accessors treat as the type's own zero, since nothing can have
/// been stored under it either.
fn default_of(rule: &str, key: &str) -> Option<OptionDefault> {
let found = rule_by_name(rule)?;
found.options().iter().find(|spec| spec.name == key).map(|spec| spec.default)
}
/// Reads `raw` — the text after the `=` in a `lucisv.toml` — as the kind
/// `spec` declares.
fn parse_raw(spec: &OptionSpec, raw: &str) -> Result<OptionValue, String> {
let raw = raw.trim();
let value = match spec.kind {
OptionKind::Bool => match raw {
"true" => OptionValue::Bool(true),
"false" => OptionValue::Bool(false),
_ => return Err(expected(spec, "`true` or `false`", raw)),
},
OptionKind::Int { .. } => {
let digits = raw.strip_prefix('-').unwrap_or(raw);
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
return Err(expected(spec, "an integer", raw));
}
let n: i64 = raw.parse().map_err(|_| expected(spec, "an integer", raw))?;
OptionValue::Int(n)
}
OptionKind::Str | OptionKind::Regex | OptionKind::Words(_) => {
OptionValue::Str(unquote(spec, raw)?)
}
OptionKind::List | OptionKind::RegexList => {
let inner = raw
.strip_prefix('[')
.and_then(|rest| rest.strip_suffix(']'))
.ok_or_else(|| expected(spec, "a list like `[\"a\", \"b\"]`", raw))?;
let mut items: Vec<&str> = inner.split(',').map(str::trim).collect();
if items.last() == Some(&"") {
// Either an empty list or a permitted trailing comma.
items.pop();
}
OptionValue::List(
items.iter().map(|item| unquote(spec, item)).collect::<Result<_, _>>()?,
)
}
};
check(spec, value)
}
/// A `"quoted"` string, kept as written — backslashes and all.
fn unquote(spec: &OptionSpec, raw: &str) -> Result<String, String> {
let inner = raw
.strip_prefix('"')
.and_then(|rest| rest.strip_suffix('"'))
.ok_or_else(|| expected(spec, "a quoted string", raw))?;
if inner.contains('"') {
return Err(expected(spec, "a quoted string", raw));
}
Ok(inner.to_string())
}
/// Whether `value` is one this option accepts: the right kind, in range, and
/// — for a pattern — one that compiles.
fn check(spec: &OptionSpec, value: OptionValue) -> Result<OptionValue, String> {
match (spec.kind, &value) {
(OptionKind::Bool, OptionValue::Bool(_)) => Ok(value),
(OptionKind::Int { min, max }, OptionValue::Int(n)) => {
if *n < min || *n > max {
return Err(format!("`{}` must be between {min} and {max}, found {n}", spec.name));
}
Ok(value)
}
(OptionKind::Str, OptionValue::Str(_)) => Ok(value),
(OptionKind::Regex, OptionValue::Str(pattern)) => {
compile(spec, pattern)?;
Ok(value)
}
(OptionKind::List, OptionValue::List(_)) => Ok(value),
(OptionKind::RegexList, OptionValue::List(patterns)) => {
for pattern in patterns {
compile(spec, pattern)?;
}
Ok(value)
}
(OptionKind::Words(vocabulary), OptionValue::Str(spelling)) => {
let words: Vec<&str> = spelling.split('|').map(str::trim).collect();
if words.iter().any(|word| word.is_empty()) {
return Err(format!("`{}`: empty word in `{spelling}`", spec.name));
}
if let Some(bad) = words.iter().find(|word| !vocabulary.contains(word)) {
return Err(format!(
"`{}`: `{bad}` is not one of {}",
spec.name,
vocabulary.join(", ")
));
}
Ok(value)
}
_ => Err(format!(
"`{}` expects {}, found {}",
spec.name,
article(spec.kind),
value.kind_word()
)),
}
}
/// Compiles one pattern, naming the option in the message.
fn compile(spec: &OptionSpec, pattern: &str) -> Result<(), String> {
Regex::compile(pattern)
.map(|_| ())
.map_err(|e| format!("`{}`: `{pattern}` is not a valid pattern: {e}", spec.name))
}
/// The kind, with the article an error message wants in front of it.
fn article(kind: OptionKind) -> String {
match kind {
OptionKind::Int { .. } => "an integer".to_string(),
other => format!("a {}", other.as_str()),
}
}
fn expected(spec: &OptionSpec, wanted: &str, raw: &str) -> String {
format!("`{}` expects {wanted}, found `{raw}`", spec.name)
}
/// A compiled pattern option, or `None` when it does not compile.
///
/// Every pattern a run holds was compiled once when it was accepted, so
/// `None` here can only be a spec whose own default is wrong — which the
/// registry's tests forbid.
pub(crate) fn pattern(options: &RuleOptions, rule: &str, key: &str) -> Option<Regex> {
Regex::compile(options.str(rule, key)).ok()
}
#[cfg(test)]
mod tests {
use super::*;
fn options() -> RuleOptions {
RuleOptions::new()
}
#[test]
fn an_unset_option_reads_its_specs_default() {
let opts = options();
assert_eq!(opts.str("signal-name-style", "style_regex"), "[a-z_0-9]+");
assert_eq!(opts.int("line-length", "length"), 100);
assert!(!opts.is_set("line-length", "length"));
assert!(opts.is_empty());
}
#[test]
fn a_set_option_wins_and_is_remembered_as_set() {
let mut opts = options();
opts.set_raw("line-length", "length", "120").expect("accepted");
assert_eq!(opts.int("line-length", "length"), 120);
assert!(opts.is_set("line-length", "length"));
assert!(!opts.is_empty());
}
#[test]
fn every_kind_parses_from_the_text_a_toml_writes() {
let mut opts = options();
opts.set_raw("typedef-structs-unions", "allow_anonymous_nested", "true").expect("bool");
assert!(opts.bool("typedef-structs-unions", "allow_anonymous_nested"));
opts.set_raw("signal-name-style", "style_regex", "\"[a-z]+\"").expect("regex");
assert_eq!(opts.str("signal-name-style", "style_regex"), "[a-z]+");
opts.set_raw("generate-label-prefix", "prefix", "[ \"g_\", \"gen_\", ]").expect("list");
assert_eq!(
opts.list("generate-label-prefix", "prefix"),
vec!["g_".to_string(), "gen_".to_string()]
);
opts.set_raw("port-name-suffix", "suffixes", "[]").expect("empty list");
assert!(opts.list("port-name-suffix", "suffixes").is_empty());
}
#[test]
fn a_backslash_survives_into_a_pattern() {
// `lucisv_core::config` refuses escapes in its own strings; an option
// value is stored raw and read here, which is what lets `\d` through.
let mut opts = options();
opts.set_raw("signal-name-style", "style_regex", "\"[a-z]\\d+\"").expect("accepted");
assert_eq!(opts.str("signal-name-style", "style_regex"), "[a-z]\\d+");
}
#[test]
fn an_unknown_rule_or_key_says_what_exists() {
let mut opts = options();
let error = opts.set_raw("no-such-rule", "x", "1").err().unwrap_or_default();
assert!(error.contains("unknown rule `no-such-rule`"), "{error}");
let error = opts.set_raw("no-tabs", "width", "4").err().unwrap_or_default();
assert!(error.contains("takes no options"), "{error}");
let error = opts.set_raw("line-length", "len", "120").err().unwrap_or_default();
assert!(error.contains("has no option `len`"), "{error}");
assert!(error.contains("it has: length"), "{error}");
}
#[test]
fn a_wrong_kind_is_refused_through_both_doors() {
let mut opts = options();
assert!(opts.set_raw("line-length", "length", "\"120\"").is_err());
assert!(opts.set_raw("signal-name-style", "style_regex", "120").is_err());
assert!(opts.set_raw("port-name-suffix", "suffixes", "\"_i\"").is_err());
assert!(opts.set_raw("typedef-structs-unions", "allow_anonymous_nested", "yes").is_err());
let error = opts
.set("line-length", "length", OptionValue::Str("120".to_string()))
.err()
.unwrap_or_default();
assert!(error.contains("expects an integer, found a string"), "{error}");
}
#[test]
fn an_out_of_range_integer_is_refused() {
let mut opts = options();
let error = opts.set_raw("line-length", "length", "10").err().unwrap_or_default();
assert!(error.contains("must be between"), "{error}");
assert!(opts.set_raw("line-length", "length", "40").is_ok());
}
/// An escape this engine does not implement is refused when the option
/// is read, not read as a literal — the difference between an error a
/// user can see and a naming rule that quietly judges the wrong names
/// (QA, 2026-09-04).
#[test]
fn an_unsupported_escape_never_becomes_a_literal() {
let mut opts = options();
for pattern in ["\"\\bword\\b\"", "\"(a)\\1\"", "\"\\p{L}+\""] {
let error = opts
.set_raw("signal-name-style", "style_regex", pattern)
.err()
.unwrap_or_else(|| panic!("{pattern} was accepted"));
assert!(error.contains("unsupported escape"), "{pattern}: {error}");
assert!(error.contains("style_regex"), "{pattern}: {error}");
}
// ... and the option keeps its default, so the rule still works.
assert_eq!(opts.str("signal-name-style", "style_regex"), "[a-z_0-9]+");
}
#[test]
fn an_invalid_pattern_is_refused_by_name() {
let mut opts = options();
let error =
opts.set_raw("signal-name-style", "style_regex", "\"[a-\"").err().unwrap_or_default();
assert!(error.contains("not a valid pattern"), "{error}");
let error = opts
.set(
"banned-declared-name-patterns",
"patterns",
OptionValue::List(vec!["(ok".to_string()]),
)
.err()
.unwrap_or_default();
assert!(error.contains("not a valid pattern"), "{error}");
}
#[test]
fn a_style_word_outside_the_vocabulary_is_refused() {
let mut opts = options();
assert!(opts
.set_raw("parameter-name-style", "parameter_style", "\"CamelCase|ALL_CAPS\"")
.is_ok());
assert!(opts.set_raw("parameter-name-style", "localparam_style", "\"CamelCase\"").is_ok());
let error = opts
.set_raw("parameter-name-style", "parameter_style", "\"snake_case\"")
.err()
.unwrap_or_default();
assert!(error.contains("is not one of"), "{error}");
let error = opts
.set_raw("parameter-name-style", "parameter_style", "\"CamelCase|\"")
.err()
.unwrap_or_default();
assert!(error.contains("empty word"), "{error}");
}
#[test]
fn a_refused_value_leaves_the_previous_one_standing() {
let mut opts = options();
opts.set_raw("line-length", "length", "120").expect("accepted");
assert!(opts.set_raw("line-length", "length", "2").is_err());
assert_eq!(opts.int("line-length", "length"), 120);
}
/// Key by key: an overlay replaces the keys it names and leaves the
/// rest of the base standing.
#[test]
fn an_overlay_replaces_one_key_at_a_time() {
let mut base = options();
base.set_raw("line-length", "length", "120").expect("accepted");
base.set_raw("generate-label-prefix", "prefix", "[\"blk_\"]").expect("accepted");
let mut top = options();
top.set_raw("line-length", "length", "140").expect("accepted");
base.overlay(&top);
assert_eq!(base.int("line-length", "length"), 140, "the overlay wins");
assert_eq!(
base.list("generate-label-prefix", "prefix"),
vec!["blk_".to_string()],
"and the key it did not name survives"
);
// An empty overlay changes nothing.
base.overlay(&options());
assert_eq!(base.int("line-length", "length"), 140);
}
#[test]
fn defaults_are_written_the_way_a_user_would_type_them() {
assert_eq!(OptionDefault::Bool(true).as_written(), "true");
assert_eq!(OptionDefault::Int(100).as_written(), "100");
assert_eq!(OptionDefault::Str("[a-z]+").as_written(), "\"[a-z]+\"");
assert_eq!(OptionDefault::List(&["g_", "gen_"]).as_written(), "[\"g_\", \"gen_\"]");
assert_eq!(OptionDefault::List(&[]).as_written(), "[]");
}
}
+716
View File
@@ -0,0 +1,716 @@
//! The small regular-expression engine the naming options are spelled with.
//!
//! Verible spells every naming convention as an RE2 pattern, and §34's
//! `style_regex` options are the same patterns typed by the same users, so
//! lucisv has to read them. What it does **not** need is RE2: the patterns
//! that appear in a style guide are character classes, alternation and the
//! three postfix repeats, which is one small engine — and this crate's
//! dependency list (`vlog_parser` + std) is worth more than the syntax nobody
//! writes here.
//!
//! # The supported subset
//!
//! - literals, and `.` for any character except a newline;
//! - `[...]` classes, with `^` negation, `a-z` ranges, a leading `]` or a
//! trailing `-` as a literal, and the `\d`/`\w`/`\s` shorthands inside;
//! - the escapes `\d \D \w \W \s \S` (classes), `\n \t \r` (control
//! characters) and `\<punctuation>` (that character, literally);
//! - groups `( ... )`, alternation `|`, and the postfix `*`, `+`, `?`;
//! - a `^` at the very start and a `$` at the very end, accepted and ignored
//! because the match is **anchored at both ends** anyway: a name matches
//! its style when the whole name matches the pattern, which is how Verible
//! reads its own.
//!
//! **Everything else is refused when the option is read, by name**: counted
//! repetition (`{2,3}`), lookaround (`(?=...)`), and every escape not in the
//! list above — a backreference (`\1`), a word boundary (`\b`), `\A`, `\z`,
//! `\p{...}`, `\x41`. Refusing is the whole point: an unsupported escape
//! treated as a literal would quietly accuse or excuse the wrong names, which
//! is worse than an error the user can read (QA, 2026-09-04).
//!
//! # Why it cannot hang
//!
//! The matcher is a **Thompson NFA simulation** (a Pike VM without capture
//! groups): the pattern is compiled to a small instruction program, and the
//! set of live program counters is advanced one character at a time, each
//! state entered at most once per character. Matching is therefore
//! `O(pattern × name)` **by construction**, whatever shape the pattern has.
//! The backtracking matcher this replaced was exponential on an ambiguous
//! repeat — QA measured `(a*)*b` against a 30-character name at 20.6 s and a
//! guard kill on the shipped binary (2026-09-04), which a user could
//! configure into every future lint run and into every keystroke of an editor
//! session.
/// One compiled pattern, matched whole against a name.
pub(crate) struct Regex {
prog: Vec<Inst>,
}
/// One instruction of the compiled program.
///
/// `Split` and `Jump` are the only control flow, and the only instructions
/// that consume no input; everything else advances one character.
#[derive(Debug, Clone)]
enum Inst {
/// Match this character exactly.
Char(char),
/// Match any character except a newline (`.`).
Any,
/// Match any character of this set.
Class(Class),
/// Continue at **both** targets — the alternation and repeat primitive.
Split(usize, usize),
/// Continue at this target.
Jump(usize),
/// The whole pattern matched, if the input is also finished.
Match,
}
/// A set of characters: ranges, plus an optional negation.
#[derive(Debug, Clone)]
struct Class {
ranges: Vec<(char, char)>,
negated: bool,
}
impl Class {
fn contains(&self, c: char) -> bool {
let hit = self.ranges.iter().any(|(lo, hi)| *lo <= c && c <= *hi);
hit != self.negated
}
}
/// The syntax tree the parser builds and the compiler walks.
enum Node {
/// Matches the empty string.
Empty,
/// One literal character.
Char(char),
/// `.` — any character except a newline.
Any,
/// One `[...]` class, or one of the `\d`-style shorthands.
Class(Class),
/// A sequence, matched left to right.
Concat(Vec<Node>),
/// Alternatives.
Alt(Vec<Node>),
/// A repeated node: `*`, `+` or `?`.
Repeat { node: Box<Node>, kind: RepeatKind },
}
/// Which postfix repeat was written.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RepeatKind {
/// `*` — zero or more.
Star,
/// `+` — one or more.
Plus,
/// `?` — zero or one.
Question,
}
impl Regex {
/// Compiles `pattern`, or says what is wrong with it.
pub(crate) fn compile(pattern: &str) -> Result<Regex, String> {
let chars: Vec<char> = pattern.chars().collect();
let mut parser = Parser { chars, at: 0 };
// `^ ... $` is how the same convention is often written down; the
// match is anchored either way, so the anchors are accepted and
// dropped rather than rejected as unsupported.
if parser.chars.first() == Some(&'^') {
parser.at = 1;
}
if parser.chars.last() == Some(&'$') && parser.chars.len() > parser.at && !escaped(&parser)
{
parser.chars.pop();
}
let root = parser.alternation()?;
if let Some(left) = parser.chars.get(parser.at) {
return Err(match left {
')' => "unmatched `)`".to_string(),
c => format!("unexpected `{c}`"),
});
}
let mut prog = Vec::new();
emit(&root, &mut prog);
prog.push(Inst::Match);
Ok(Regex { prog })
}
/// Whether the **whole** of `text` matches the pattern.
///
/// One pass over the characters, carrying the set of live program
/// counters: every state is entered at most once per character, so the
/// cost is `O(prog × text)` however ambiguous the pattern is.
pub(crate) fn is_match(&self, text: &str) -> bool {
let mut current: Vec<usize> = Vec::with_capacity(self.prog.len());
let mut next: Vec<usize> = Vec::with_capacity(self.prog.len());
let mut on_current = vec![false; self.prog.len()];
let mut on_next = vec![false; self.prog.len()];
self.add(0, &mut current, &mut on_current);
for c in text.chars() {
next.clear();
on_next.iter_mut().for_each(|seen| *seen = false);
for &pc in &current {
let takes = match &self.prog[pc] {
Inst::Char(want) => *want == c,
Inst::Any => c != '\n',
Inst::Class(class) => class.contains(c),
// `Match` mid-input is a pattern that ended before the
// name did, which a whole-name match refuses.
Inst::Match | Inst::Split(..) | Inst::Jump(_) => false,
};
if takes {
self.add(pc + 1, &mut next, &mut on_next);
}
}
std::mem::swap(&mut current, &mut next);
std::mem::swap(&mut on_current, &mut on_next);
if current.is_empty() {
return false;
}
}
current.iter().any(|pc| matches!(self.prog[*pc], Inst::Match))
}
/// Adds a thread at `pc`, following the instructions that consume no
/// input. `seen` keeps each state to one visit per character, which is
/// what bounds the work — and what makes a loop of empty matches
/// terminate instead of spinning.
fn add(&self, pc: usize, list: &mut Vec<usize>, seen: &mut [bool]) {
if seen.get(pc).copied().unwrap_or(true) {
return;
}
seen[pc] = true;
match self.prog[pc] {
Inst::Jump(to) => self.add(to, list, seen),
Inst::Split(a, b) => {
self.add(a, list, seen);
self.add(b, list, seen);
}
_ => list.push(pc),
}
}
}
/// Compiles one node onto the end of `prog`.
fn emit(node: &Node, prog: &mut Vec<Inst>) {
match node {
Node::Empty => {}
Node::Char(c) => prog.push(Inst::Char(*c)),
Node::Any => prog.push(Inst::Any),
Node::Class(class) => prog.push(Inst::Class(class.clone())),
Node::Concat(parts) => parts.iter().for_each(|part| emit(part, prog)),
Node::Alt(branches) => emit_alt(branches, prog),
Node::Repeat { node, kind } => emit_repeat(node, *kind, prog),
}
}
/// `split L1, L2; L1: first; jmp end; L2: rest…; end:`
fn emit_alt(branches: &[Node], prog: &mut Vec<Inst>) {
let Some((first, rest)) = branches.split_first() else { return };
if rest.is_empty() {
emit(first, prog);
return;
}
let split = prog.len();
prog.push(Inst::Split(0, 0)); // patched below
emit(first, prog);
let jump = prog.len();
prog.push(Inst::Jump(0)); // patched below
let second = prog.len();
emit_alt(rest, prog);
let end = prog.len();
prog[split] = Inst::Split(split + 1, second);
prog[jump] = Inst::Jump(end);
}
/// The three postfix repeats, each as a split around the body.
fn emit_repeat(node: &Node, kind: RepeatKind, prog: &mut Vec<Inst>) {
match kind {
// L: split body, end; body: … ; jmp L; end:
RepeatKind::Star => {
let split = prog.len();
prog.push(Inst::Split(0, 0));
emit(node, prog);
prog.push(Inst::Jump(split));
let end = prog.len();
prog[split] = Inst::Split(split + 1, end);
}
// body: … ; split body, end; end:
RepeatKind::Plus => {
let body = prog.len();
emit(node, prog);
let split = prog.len();
prog.push(Inst::Split(body, split + 1));
}
// split body, end; body: … ; end:
RepeatKind::Question => {
let split = prog.len();
prog.push(Inst::Split(0, 0));
emit(node, prog);
let end = prog.len();
prog[split] = Inst::Split(split + 1, end);
}
}
}
/// Whether the pattern's last character is escaped — so a trailing `\$` is
/// the literal dollar it was written as and not the anchor.
fn escaped(parser: &Parser) -> bool {
let before = parser.chars.len().saturating_sub(1);
parser.chars[..before].iter().rev().take_while(|c| **c == '\\').count() % 2 == 1
}
/// The escapes this engine understands, for the message a refusal prints.
const SUPPORTED_ESCAPES: &str =
"\\d \\D \\w \\W \\s \\S \\n \\t \\r, and \\<punctuation> for that character";
/// The recursive-descent parser for the subset.
struct Parser {
chars: Vec<char>,
at: usize,
}
impl Parser {
fn peek(&self) -> Option<char> {
self.chars.get(self.at).copied()
}
fn bump(&mut self) -> Option<char> {
let c = self.peek();
self.at += c.is_some() as usize;
c
}
/// `branch ( '|' branch )*`
fn alternation(&mut self) -> Result<Node, String> {
let mut branches = vec![self.concatenation()?];
while self.peek() == Some('|') {
self.at += 1;
branches.push(self.concatenation()?);
}
Ok(if branches.len() == 1 {
branches.pop().unwrap_or(Node::Empty)
} else {
Node::Alt(branches)
})
}
/// `repeated*`, stopping at `|` or the group's `)`.
fn concatenation(&mut self) -> Result<Node, String> {
let mut parts = Vec::new();
while !matches!(self.peek(), None | Some('|') | Some(')')) {
parts.push(self.repeated()?);
}
Ok(match parts.len() {
0 => Node::Empty,
1 => parts.pop().unwrap_or(Node::Empty),
_ => Node::Concat(parts),
})
}
/// One atom with its postfix `*`, `+` or `?`.
fn repeated(&mut self) -> Result<Node, String> {
let atom = self.atom()?;
let kind = match self.peek() {
Some('*') => RepeatKind::Star,
Some('+') => RepeatKind::Plus,
Some('?') => RepeatKind::Question,
_ => return Ok(atom),
};
self.at += 1;
if matches!(self.peek(), Some('*' | '+' | '?')) {
return Err(format!("`{}` cannot follow a repeat", self.peek().unwrap_or('?')));
}
Ok(Node::Repeat { node: Box::new(atom), kind })
}
fn atom(&mut self) -> Result<Node, String> {
match self.bump() {
Some('(') => {
// `(?...)` is lookaround or a flag group — RE2 syntax this
// engine does not implement, and refusing it by name is what
// stops it being read as a literal `?`.
if self.peek() == Some('?') {
return Err(
"`(?...)` groups (lookaround, flags, non-capturing) are unsupported in \
lucisv patterns"
.to_string(),
);
}
let inner = self.alternation()?;
if self.bump() != Some(')') {
return Err("unmatched `(`".to_string());
}
Ok(inner)
}
Some('[') => self.class(),
Some('.') => Ok(Node::Any),
Some('\\') => self.escape(),
Some(c @ ('*' | '+' | '?')) => Err(format!("`{c}` has nothing to repeat")),
Some(c @ ('{' | '}')) => {
Err(format!("`{c}` (counted repetition) is unsupported in lucisv patterns"))
}
Some(c @ ('^' | '$')) => {
Err(format!("`{c}` is only accepted at the start or end of a pattern"))
}
Some(')') => Err("unmatched `)`".to_string()),
Some(c) => Ok(Node::Char(c)),
None => Err("pattern ends where a character was expected".to_string()),
}
}
/// `\d`, `\w`, `\s`, their negations, the three control characters, or a
/// punctuation character escaped to itself.
///
/// **Anything else is an error.** A letter or digit escape this engine
/// does not implement — `\b`, `\A`, `\1`, `\p` — is a pattern from
/// another dialect that would mean something quite different if it were
/// read as a literal, so it is named and refused.
fn escape(&mut self) -> Result<Node, String> {
let c = self.bump().ok_or("a `\\` at the end of the pattern escapes nothing")?;
Ok(match c {
'd' => Node::Class(digits(false)),
'D' => Node::Class(digits(true)),
'w' => Node::Class(word(false)),
'W' => Node::Class(word(true)),
's' => Node::Class(space(false)),
'S' => Node::Class(space(true)),
'n' => Node::Char('\n'),
't' => Node::Char('\t'),
'r' => Node::Char('\r'),
other if other.is_alphanumeric() => return Err(unsupported_escape(other)),
other => Node::Char(other),
})
}
/// A `[...]` class, the `[` already consumed.
fn class(&mut self) -> Result<Node, String> {
let negated = self.peek() == Some('^');
self.at += negated as usize;
let mut ranges: Vec<(char, char)> = Vec::new();
// A `]` written first is a literal `]`, as in every regex dialect.
let mut first = true;
loop {
let c = match self.bump() {
Some(']') if !first => break,
Some(c) => c,
None => return Err("unmatched `[`".to_string()),
};
first = false;
let lo = if c == '\\' { self.class_escape(&mut ranges)? } else { Some(c) };
let Some(lo) = lo else { continue };
// `a-z`, but a `-` before the closing `]` is a literal `-`.
if self.peek() == Some('-') && self.chars.get(self.at + 1) != Some(&']') {
self.at += 1;
let hi = match self.bump() {
Some('\\') => self.class_literal_escape()?,
Some(c) => c,
None => return Err("unmatched `[`".to_string()),
};
if hi < lo {
return Err(format!("class range `{lo}-{hi}` runs backwards"));
}
ranges.push((lo, hi));
} else {
ranges.push((lo, lo));
}
}
if ranges.is_empty() {
return Err("empty character class".to_string());
}
Ok(Node::Class(Class { ranges, negated }))
}
/// An escape inside a class: a shorthand adds its ranges and yields
/// nothing, an escaped punctuation or control character yields itself,
/// and anything else is refused by name.
///
/// The **negated** shorthands (`\D`, `\W`, `\S`) are refused inside a
/// class rather than accepted: a class is one set of ranges with one
/// negation flag, and mixing a complemented set into it would need set
/// arithmetic this engine does not do. Refusing says so; accepting would
/// have to guess.
fn class_escape(&mut self, ranges: &mut Vec<(char, char)>) -> Result<Option<char>, String> {
let c = self.bump().ok_or("a `\\` at the end of a class escapes nothing")?;
let shorthand = match c {
'd' => Some(digits(false)),
'w' => Some(word(false)),
's' => Some(space(false)),
_ => None,
};
if let Some(class) = shorthand {
ranges.extend(class.ranges);
return Ok(None);
}
Ok(Some(match c {
'n' => '\n',
't' => '\t',
'r' => '\r',
'D' | 'W' | 'S' => {
return Err(format!(
"`\\{c}` is unsupported inside a `[...]` class; write it outside one"
))
}
other if other.is_alphanumeric() => return Err(unsupported_escape(other)),
other => other,
}))
}
/// The far end of a class range, which must be one character — a
/// shorthand there (`[a-\d]`) is meaningless.
fn class_literal_escape(&mut self) -> Result<char, String> {
let c = self.bump().ok_or("a `\\` at the end of a class escapes nothing")?;
Ok(match c {
'n' => '\n',
't' => '\t',
'r' => '\r',
other if other.is_alphanumeric() => return Err(unsupported_escape(other)),
other => other,
})
}
}
/// The one message an unimplemented escape gets, wherever it was written.
fn unsupported_escape(c: char) -> String {
format!("unsupported escape `\\{c}` (supported: {SUPPORTED_ESCAPES})")
}
fn digits(negated: bool) -> Class {
Class { ranges: vec![('0', '9')], negated }
}
fn word(negated: bool) -> Class {
Class { ranges: vec![('a', 'z'), ('A', 'Z'), ('0', '9'), ('_', '_')], negated }
}
fn space(negated: bool) -> Class {
Class { ranges: vec![(' ', ' '), ('\t', '\t'), ('\n', '\n'), ('\r', '\r')], negated }
}
#[cfg(test)]
mod tests {
use super::*;
fn hit(pattern: &str, text: &str) -> bool {
Regex::compile(pattern).unwrap_or_else(|e| panic!("{pattern}: {e}")).is_match(text)
}
#[test]
fn the_patterns_the_naming_options_ship_with_work() {
// Every default this round introduces, against real names.
assert!(hit("[a-z_0-9]+", "wr_en"));
assert!(!hit("[a-z_0-9]+", "wrEn"));
assert!(hit("[a-z_0-9]+(_if)", "bus_if"));
assert!(!hit("[a-z_0-9]+(_if)", "bus"));
assert!(hit("[A-Z_0-9]+", "MY_MACRO"));
assert!(!hit("[A-Z_0-9]+", "my_macro"));
assert!(hit("([a-z0-9]+_)+c", "addr_range_c"));
assert!(!hit("([a-z0-9]+_)+c", "addr_range"));
assert!(hit("[a-z_0-9]+(_t|_e)", "state_e"));
assert!(hit("[a-z_0-9]+(_t|_e)", "word_t"));
assert!(!hit("[a-z_0-9]+(_t|_e)", "word"));
}
/// The probe table, every verdict checked against Python's
/// `re.fullmatch` (QA's 46 probes of 2026-09-04 plus this round's own).
/// It is written down rather than described so a change to the engine
/// has to disagree with CPython in public.
#[test]
fn every_probe_agrees_with_python_re_fullmatch() {
// (pattern, text, re.fullmatch(pattern, text) is not None)
let probes: &[(&str, &str, bool)] = &[
// literals and anchoring
("abc", "abc", true),
("abc", "abcd", false),
("abc", "xabcx", false),
("abc", "ab", false),
("", "", true),
("", "a", false),
// `.`
("a.c", "abc", true),
("a.c", "a_c", true),
("a.c", "ac", false),
(".*", "anything", true),
("a.b", "a\nb", false),
// classes
("[a-z]+", "abc", true),
("[a-z]+", "abC", false),
("[a-z_0-9]+", "a_1", true),
("[^0-9]+", "abc", true),
("[^0-9]+", "ab1", false),
("[a-]+", "a-a", true),
("[]a]+", "]a", true),
("[\\]]", "]", true),
("[a-c-e]+", "a-e", true),
("[A-Za-z][A-Za-z0-9]*", "Ab9", true),
("[A-Za-z][A-Za-z0-9]*", "9Ab", false),
// shorthands
("\\d+", "42", true),
("\\d+", "4a", false),
("\\D+", "abc", true),
("\\D+", "ab1", false),
("\\w+", "a_1", true),
("\\w+", "a-1", false),
("\\W+", "-", true),
("\\W+", "a", false),
("\\s+", " \t", true),
("\\s+", " a", false),
("\\S+", "abc", true),
("[\\d_]+", "4_2", true),
("[\\w]+", "a_1", true),
("a\\.b", "a.b", true),
("a\\.b", "axb", false),
// groups, alternation, nesting
("(a|b)(c|d)", "ad", true),
("(a|b)(c|d)", "ac", true),
("(a|b)(c|d)", "bb", false),
("(ab|a)+b", "aab", true),
("((a|b)+_)?x", "abab_x", true),
("((a|b)+_)?x", "x", true),
("(a|)b", "b", true),
("(|a)b", "ab", true),
("(ab)+", "ababab", true),
("(ab)+", "ababa", false),
// repeats, including the ambiguous shapes that used to blow up
("a*ab", "aaab", true),
("a+b", "b", false),
("a?b", "b", true),
("(a?)*b", "b", true),
("(a*)*b", "aaab", true),
("(a*)*b", "aaaa", false),
("(a|aa)*b", "aaaab", true),
("(a|aa)*b", "aaaa", false),
("(.*)*x", "abcx", true),
("(.*)*x", "abc", false),
("((a*)*)*b", "aab", true),
("(a+)+b", "aaab", true),
("(a+)+b", "aaa", false),
// the shipped defaults, both ways
("[a-z][a-z_0-9]*(_t|_e)", "state_e", true),
("[a-z][a-z_0-9]*(_t|_e)", "_state_e", false),
("[a-z][a-z_0-9]*_t", "word_t", true),
("[a-z][a-z_0-9]*_t", "wordt", false),
("[a-z_0-9]+(_if)", "clk_rst_if", true),
("[a-z_0-9]+(_if)", "bus_intf", false),
("([a-z0-9]+_)+c", "addr_range_c", true),
("([a-z0-9]+_)+c", "c", false),
("[A-Z_0-9]+", "W2", true),
("[a-z][a-z_0-9]*", "fifo2_ctrl", true),
("[a-z][a-z_0-9]*", "Fifo2Ctrl", false),
];
for (pattern, text, expected) in probes {
assert_eq!(hit(pattern, text), *expected, "{pattern:?} vs {text:?}");
}
assert!(probes.len() >= 60, "the table is the pin; keep it wide");
}
#[test]
fn the_match_is_anchored_at_both_ends() {
assert!(!hit("[a-z]+", "abc1"));
assert!(!hit("bc", "abc"));
assert!(hit("^[a-z]+$", "abc"), "explicit anchors are accepted and ignored");
assert!(hit("a\\$", "a$"), "an escaped `$` at the end is a literal");
}
/// The HIGH finding of 2026-09-04: an ambiguous repeat was exponential
/// under the old backtracking matcher (30 characters took 20.6 s and hit
/// the runaway guard). The NFA simulation is linear by construction, so
/// the same shapes finish on a 200-character name in microseconds.
#[test]
fn an_ambiguous_repeat_is_linear_not_exponential() {
let long = "a".repeat(200);
let start = std::time::Instant::now();
for pattern in ["(a*)*b", "(a|aa)*b", "(.*)*x", "((a*)*)*b", "(a+)+b", "(a?)*b"] {
assert!(!hit(pattern, &long), "{pattern} must not match a name of only `a`s");
}
let elapsed = start.elapsed();
assert!(
elapsed < std::time::Duration::from_millis(500),
"six ambiguous patterns over 200 characters took {elapsed:?}; \
the matcher is backtracking again"
);
}
/// An unsupported escape is refused **by name**, never read as a
/// literal — the second HIGH finding of 2026-09-04. QA's two cases are
/// the first two rows.
#[test]
fn an_unsupported_escape_is_refused_by_name() {
for pattern in [
"(a)\\1", // a backreference: must not match `a1`
"\\bword\\b", // a word boundary: must not match `bwordb`
"\\B",
"\\A",
"\\z",
"\\Z",
"\\p{L}",
"\\x41",
"\\u0041",
"\\Q",
"\\9",
"\\0",
"\\f",
"\\v",
"[\\b]",
"[a\\1]",
"[a-\\d]",
"[\\D]",
"[\\S]",
"[\\W]",
] {
let error = Regex::compile(pattern).err().unwrap_or_else(|| {
panic!("{pattern} compiled; an unimplemented escape must be refused")
});
assert!(
error.contains("unsupported") || error.contains("unsupported inside"),
"{pattern}: {error}"
);
}
// The message names the escape and what is available instead.
let error = Regex::compile("\\bword\\b").err().unwrap_or_default();
assert!(error.contains("`\\b`"), "{error}");
assert!(error.contains("\\d"), "{error}");
// And the supported ones still compile.
for pattern in [
"\\d", "\\D", "\\w", "\\W", "\\s", "\\S", "\\n", "\\t", "\\r", "\\.", "\\\\", "\\[",
"\\]", "\\(", "\\)", "\\|", "\\+", "\\*", "\\?", "\\-", "\\{", "\\}", "\\^", "\\$",
"[\\d]", "[\\w]", "[\\s]", "[\\-]",
] {
assert!(Regex::compile(pattern).is_ok(), "{pattern} must compile");
}
}
#[test]
fn a_bad_pattern_says_what_is_wrong() {
for (pattern, wanted) in [
("(a", "unmatched `("),
("a)", "unmatched `)`"),
("[a", "unmatched `["),
("[]", "unmatched `["),
("[^]", "unmatched `["),
("*a", "nothing to repeat"),
("a**", "cannot follow a repeat"),
("a{2}", "counted repetition"),
("a{2,3}", "counted repetition"),
("(?=a)b", "(?...)"),
("(?:a)b", "(?...)"),
("a$b", "start or end"),
("[z-a]", "runs backwards"),
("a\\", "escapes nothing"),
] {
let error = Regex::compile(pattern).err().unwrap_or_default();
assert!(error.contains(wanted), "{pattern}: {error}");
}
}
#[test]
fn unicode_passes_through_as_literals() {
assert!(hit("naïve", "naïve"));
assert!(!hit("[a-z]+", "naïve"));
// A non-ASCII letter escape is still an escape nobody implements.
assert!(Regex::compile("\\é").is_err());
}
}
+247 -11
View File
@@ -1,7 +1,9 @@
//! The rule trait and the table of rules that exist.
use crate::context::LintContext;
use crate::options::OptionSpec;
use crate::rules;
use crate::severity::Severity;
use crate::violation::{Applicability, Violation};
/// One lint rule.
@@ -17,6 +19,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;
@@ -50,6 +60,18 @@ pub trait Rule: Sync {
None
}
/// What a user may configure about this rule, or nothing.
///
/// The keys are Verible's wherever it has the same option, so a project
/// migrating a `.rules.verible` file types the same words. A rule reads
/// one through [`LintContext`], never from a run's settings directly, and
/// always gets a value: the spec's default is the fallback, so there is no
/// "unset" case in any rule. See
/// `docs/features/linter-expansion-2/README.md`.
fn options(&self) -> &'static [OptionSpec] {
&[]
}
/// Everything this rule finds in one file.
fn check(&self, ctx: &LintContext) -> Vec<Violation>;
}
@@ -57,22 +79,59 @@ pub trait Rule: Sync {
/// Every rule that exists, in a stable order.
pub fn all_rules() -> Vec<&'static dyn Rule> {
vec![
&rules::always_comb::AlwaysComb,
&rules::always_comb_blocking::AlwaysCombBlocking,
&rules::always_ff_non_blocking::AlwaysFfNonBlocking,
&rules::banned_declared_name_patterns::BannedDeclaredNamePatterns,
&rules::case_missing_default::CaseMissingDefault,
&rules::constraint_name_style::ConstraintNameStyle,
&rules::duplicate_declaration::DuplicateDeclaration,
&rules::empty_item::EmptyItem,
&rules::enum_name_style::EnumNameStyle,
&rules::explicit_begin::ExplicitBegin,
&rules::explicit_function_task_parameter_type::ExplicitFunctionTaskParameterType,
&rules::explicit_parameter_storage_type::ExplicitParameterStorageType,
&rules::forbid_consecutive_null_statements::ForbidConsecutiveNullStatements,
&rules::forbid_defparam::ForbidDefparam,
&rules::forbid_negative_array_dim::ForbidNegativeArrayDim,
&rules::generate_label::GenerateLabel,
&rules::generate_label_prefix::GenerateLabelPrefix,
&rules::incomplete_assignment::IncompleteAssignment,
&rules::instance_shadowing::InstanceShadowing,
&rules::interface_name_style::InterfaceNameStyle,
&rules::invalid_system_task_function::InvalidSystemTaskFunction,
&rules::line_length::LineLength,
&rules::macro_name_style::MacroNameStyle,
&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::one_module_per_file::OneModulePerFile,
&rules::package_filename::PackageFilename,
&rules::packed_dimensions_range_ordering::PackedDimensionsRangeOrdering,
&rules::parameter_name_style::ParameterNameStyle,
&rules::parameter_type_name_style::ParameterTypeNameStyle,
&rules::plusarg_assignment::PlusargAssignment,
&rules::port_name_suffix::PortNameSuffix,
&rules::posix_eof::PosixEof,
&rules::signal_name_style::SignalNameStyle,
&rules::struct_union_name_style::StructUnionNameStyle,
&rules::suspicious_semicolon::SuspiciousSemicolon,
&rules::truncated_numeric_literal::TruncatedNumericLiteral,
&rules::typedef_enums::TypedefEnums,
&rules::typedef_structs_unions::TypedefStructsUnions,
&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 +171,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 +202,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 +287,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 +369,156 @@ 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}");
}
/// Every option a rule declares is one a user could actually write down,
/// and one whose own default is acceptable to itself — a default outside
/// its range, or a pattern that does not compile, would be a rule nobody
/// could satisfy.
#[test]
fn every_declared_option_is_well_formed() {
use crate::options::{OptionKind, RuleOptions};
for rule in all_rules() {
let mut names: Vec<&str> = rule.options().iter().map(|spec| spec.name).collect();
let count = names.len();
names.sort_unstable();
names.dedup();
assert_eq!(names.len(), count, "{}: duplicate option names", rule.name());
for spec in rule.options() {
let where_ = format!("{}.{}", rule.name(), spec.name);
assert!(
spec.name.chars().all(|c| c.is_ascii_lowercase()
|| c.is_ascii_digit()
|| c == '_'
|| c == '-'),
"{where_}: option names are lower-case words",
);
assert!(spec.doc.len() > 10, "{where_}: doc too thin");
assert!(!spec.doc.ends_with('.'), "{where_}: doc ends in a period");
let mut options = RuleOptions::new();
options
.set(rule.name(), spec.name, spec.default.value())
.unwrap_or_else(|e| panic!("{where_}: its own default is refused: {e}"));
if let OptionKind::Int { min, max } = spec.kind {
assert!(min <= max, "{where_}: empty range");
}
}
}
}
/// The options §34 gave the four naming rules that predate them, spelled
/// as Verible spells the same options.
#[test]
fn the_naming_rules_take_the_options_verible_gives_them() {
let names = |rule: &str| {
rule_by_name(rule)
.unwrap_or_else(|| panic!("{rule} exists"))
.options()
.iter()
.map(|spec| spec.name)
.collect::<Vec<_>>()
};
assert_eq!(names("enum-name-style"), vec!["style_regex"]);
assert_eq!(names("struct-union-name-style"), vec!["style_regex"]);
assert_eq!(names("module-name-style"), vec!["style_regex"]);
assert_eq!(
names("parameter-name-style"),
vec![
"localparam_style",
"localparam_style_regex",
"parameter_style",
"parameter_style_regex"
]
);
}
#[test]
fn lookup_by_name_finds_every_rule_and_nothing_else() {
for rule in all_rules() {
+161 -19
View File
@@ -6,7 +6,10 @@
//! per rule. If a rule exists, it is in here; if its `doc` changes, so does
//! this.
use crate::options::OptionKind;
use crate::registry::all_rules;
use crate::severity::Severity;
use crate::Rule;
/// The whole rule reference as one markdown document.
pub fn rules_markdown() -> String {
@@ -15,6 +18,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 — \
@@ -23,30 +32,78 @@ pub fn rules_markdown() -> String {
a stdin buffer it is off and must be selected. Any rule can be turned \
off with `--ignore <name>`, with `ignore` under `[lint]` in \
`lucisv.toml`, or waived in the source with `// lucisv: waive \
<name>`.\n\n",
<name>`.\n\n\
A rule with **options** is configured in a `[lint.<rule-name>]` \
table of a `lucisv.toml`, or from an editor with \
`lucisv.lint.options`; an option nobody sets reads the default \
listed with it. An unknown option name, a value of the wrong kind, \
an integer out of range and a pattern that does not compile are all \
refused, naming the file and the line.\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.push_str(&options_table(rule));
}
}
out
}
/// A rule's options, as a small table under its prose — empty for a rule
/// that takes none, which is most of them.
fn options_table(rule: &dyn Rule) -> String {
if rule.options().is_empty() {
return String::new();
}
let mut out = String::from("| Option | Kind | Default | Meaning |\n|---|---|---|---|\n");
for spec in rule.options() {
out.push_str(&format!(
"| `{name}` | {kind} | `{default}` | {doc} |\n",
name = spec.name,
kind = kind_word(spec.kind),
default = spec.default.as_written(),
doc = spec.doc,
));
}
out.push('\n');
out
}
/// How the reference spells an option's kind, a `Words` option's vocabulary
/// included — a user cannot guess `CamelCase|ALL_CAPS` from "word list".
fn kind_word(kind: OptionKind) -> String {
match kind {
OptionKind::Int { min, max } => format!("integer {min}–{max}"),
OptionKind::Words(vocabulary) => {
format!("one or more of {} joined with `\\|`", vocabulary.join(", "))
}
other => other.as_str().to_string(),
}
}
/// How the table spells a rule's default: on, off, or on wherever there is a
/// project to ask about ([`crate::Rule::needs_workspace`]).
fn default_word(rule: &dyn crate::Rule) -> &'static str {
@@ -98,7 +155,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 +163,96 @@ 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());
}
}
/// Every option a rule declares is in the reference, with the default a
/// run that configures nothing actually reads.
#[test]
fn every_option_is_listed_with_its_kind_and_default() {
let markdown = rules_markdown();
for rule in all_rules() {
for spec in rule.options() {
assert!(
markdown.contains(&format!("| `{}` |", spec.name)),
"{}.{}",
rule.name(),
spec.name
);
assert!(markdown.contains(spec.doc), "{}.{}: doc", rule.name(), spec.name);
}
}
assert!(markdown.contains("| `length` | integer 40–400 | `100` |"), "line-length");
assert!(
markdown.contains("| `prefix` | list of strings | `[\"g_\", \"gen_\"]` |"),
"generate-label-prefix"
);
assert!(
markdown.contains("one or more of CamelCase, ALL_CAPS joined with"),
"parameter-name-style's vocabulary"
);
// A rule with no options gets no table.
let no_tabs = markdown
.split("## no-tabs\n")
.nth(1)
.and_then(|rest| rest.split("\n## ").next())
.unwrap_or_default();
assert!(!no_tabs.contains("| Option |"), "{no_tabs}");
}
#[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(12).collect();
assert_eq!(
head,
vec![
@@ -135,6 +261,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,18 +275,28 @@ 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 |",
"|---|---|---|",
"A rule with **options** is configured in a `[lint.<rule-name>]` table of a \
`lucisv.toml`, or from an editor with `lucisv.lint.options`; an option nobody \
sets reads the default listed with it. An unknown option name, a value of the \
wrong kind, an integer out of range and a pattern that does not compile are \
all refused, naming the file and the line.",
"",
"| 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),
fix_word(first_rule),
first_rule.doc(),
options_table(first_rule),
);
assert!(markdown.contains(&section), "per-rule section shape changed:\n{section}");
assert!(markdown.ends_with("\n\n"));
+164
View File
@@ -0,0 +1,164 @@
//! `always-comb` — write combinational logic as `always_comb`.
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, SensList, StmtKind, TimingControl};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct AlwaysComb;
const NAME: &str = "always-comb";
impl Rule for AlwaysComb {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"write `always_comb` instead of `always @*`"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"`always_comb` says what the block is *for*, and the language checks \
the claim: the tool errors if anything else drives one of its \
left-hand sides, and it infers the sensitivity list including the \
functions the block calls — which `always @*` does not. Verible's \
`always-comb` (enabled by default) asks for the SystemVerilog \
spelling wherever `always @*` or `always @(*)` is written, and lucisv \
checks the same thing.\n\n\
The fix is offered but **unsafe**, and the reason is real: an \
`always_comb` block runs once at time zero and an `always @*` block \
does not run until something in its sensitivity list changes, so a \
testbench that samples before the first change can see a different \
value. It also becomes an error for the block's outputs to be driven \
anywhere else, which is usually the bug being found but is still a \
change in what compiles. `--unsafe-fixes` applies it; the edit is the \
keyword and its `@(*)`, nothing else."
}
fn fix(&self) -> Option<Applicability> {
Some(Applicability::Unsafe)
}
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" {
return;
}
let StmtKind::Timing { control: TimingControl::Event(sens), stmt: Some(body) } =
&stmt.kind
else {
return;
};
if !matches!(sens, SensList::Star { .. }) {
return;
}
let Some(header) = header_span(ctx, item.span.start, body.span.start) else { return };
out.push(
Violation::new(NAME, "use `always_comb` instead of `always @*`", header)
.with_fix(Fix::unsafe_fix(vec![(header, "always_comb".to_string())])),
);
});
out
}
}
/// The `always @(*)` in front of the body: from the keyword to the end of the
/// last token before the body starts.
///
/// Read off the tokens rather than assumed, because the sensitivity control
/// may be written `@*`, `@ (*)` or `@( /* why */ * )`, and the fix must
/// replace exactly what was written and not a byte more.
fn header_span(ctx: &LintContext, start: u32, body: u32) -> Option<TextRange> {
let end = ctx
.tokens()
.iter()
.filter(|token| token.span.start >= start && token.span.end <= body)
.map(|token| token.span.end)
.max()?;
(end > start).then(|| TextRange::new(start, end))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::violation::apply_fixes;
fn violations(src: &str) -> Vec<Violation> {
AlwaysComb.check(&LintContext::new(src, None))
}
#[test]
fn flags_both_spellings_and_rewrites_only_the_header() {
for src in [
"module m;\n always @(*) x = 1;\nendmodule\n",
"module m;\n always @* x = 1;\nendmodule\n",
] {
let found = violations(src);
assert_eq!(found.len(), 1, "{src}");
let fixed = apply_fixes(src, &found, true);
assert_eq!(fixed.output, "module m;\n always_comb x = 1;\nendmodule\n", "{src}");
}
}
#[test]
fn the_fix_is_unsafe() {
let src = "module m;\n always @(*) x = 1;\nendmodule\n";
let found = violations(src);
assert_eq!(found[0].fix.as_ref().map(|f| f.applicability), Some(Applicability::Unsafe));
assert_eq!(apply_fixes(src, &found, false).applied, 0, "not without --unsafe-fixes");
}
#[test]
fn a_multi_line_block_keeps_its_layout() {
let src = "module m;\n always @(*) begin\n x = 1;\n end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1);
assert_eq!(
apply_fixes(src, &found, true).output,
"module m;\n always_comb begin\n x = 1;\n end\nendmodule\n"
);
}
#[test]
fn a_comment_inside_the_control_is_replaced_with_it() {
// The whole header is one edit, so a comment written inside `@( * )`
// goes with it — which is why the fix is offered, not applied.
let src = "module m;\n always @( /* all */ * ) x = 1;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1);
assert_eq!(
apply_fixes(src, &found, true).output,
"module m;\n always_comb x = 1;\nendmodule\n"
);
}
#[test]
fn an_explicit_sensitivity_list_is_none_of_its_business() {
for src in [
"module m;\n always @(a or b) x = 1;\nendmodule\n",
"module m;\n always @(posedge clk) q <= d;\nendmodule\n",
"module m;\n always_comb x = 1;\nendmodule\n",
"module m;\n always_ff @(posedge clk) q <= d;\nendmodule\n",
"module m;\n always @(*);\nendmodule\n",
] {
assert!(violations(src).is_empty(), "{src}");
}
}
#[test]
fn an_always_star_inside_a_generate_block_is_covered() {
let src = "module m;\n if (A) begin : g\n always @(*) x = 1;\n end\nendmodule\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
}
@@ -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 \
@@ -0,0 +1,139 @@
//! `banned-declared-name-patterns` — names a project has forbidden.
use crate::context::LintContext;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::regex::Regex;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
/// See [`Rule::doc`].
pub struct BannedDeclaredNamePatterns;
const NAME: &str = "banned-declared-name-patterns";
impl Rule for BannedDeclaredNamePatterns {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not declare a name the project has banned"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"Every codebase has words it has decided against — a deprecated \
prefix, a vendor's reserved namespace, the `tmp`/`foo` a review keeps \
catching — and none of them are anybody else's business. Verible's \
`banned-declared-name-patterns` is the rule a project points at its \
own list, and it ships **off** with an empty list, which is exactly \
what lucisv does: with no `patterns` set the rule reports nothing and \
costs nothing.\n\n\
It judges **declared** names, not uses: every name the file's symbol \
table holds — modules, packages, types, parameters, signals, ports, \
instances, block labels, class members. A pattern must match the whole \
name, so `tmp.*` bans `tmp_addr` and `.*_tmp` bans `addr_tmp`. There \
is no fix: only the author knows what the name should have been."
}
fn default_on(&self) -> bool {
false
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "patterns",
kind: OptionKind::RegexList,
default: OptionDefault::List(&[]),
doc: "the patterns a declared name may not match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let patterns: Vec<(String, Regex)> = ctx
.option_list(NAME, "patterns")
.into_iter()
// A pattern that does not compile cannot be configured — the
// option is validated when it is read — so filtering here only
// ever drops what could not have arrived.
.filter_map(|text| Regex::compile(&text).ok().map(|regex| (text, regex)))
.collect();
if patterns.is_empty() {
return Vec::new();
}
let mut out = Vec::new();
for symbol in ctx.semantics().symbols() {
let Some((pattern, _)) =
patterns.iter().find(|(_, regex)| regex.is_match(&symbol.name))
else {
continue;
};
out.push(Violation::new(
NAME,
format!("`{}` matches the banned pattern `{pattern}`", symbol.name),
symbol.name_span,
));
}
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn banning(patterns: &str, src: &str) -> Vec<Violation> {
let mut options = RuleOptions::new();
options.set_raw(NAME, "patterns", patterns).expect("accepted");
BannedDeclaredNamePatterns.check(&LintContext::new(src, None).with_options(&options))
}
#[test]
fn nothing_is_banned_by_default() {
let src = "module m;\n logic tmp_addr;\nendmodule\n";
assert!(BannedDeclaredNamePatterns.check(&LintContext::new(src, None)).is_empty());
assert!(!BannedDeclaredNamePatterns.default_on());
}
#[test]
fn a_banned_name_is_reported_where_it_is_declared() {
let src = "module m;\n logic tmp_addr;\n logic keep_me;\nendmodule\n";
let found = banning("[\"tmp.*\"]", src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("banned pattern `tmp.*`"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "tmp_addr");
assert!(found[0].fix.is_none());
}
#[test]
fn the_match_is_the_whole_name() {
let src = "module m;\n logic addr_tmp;\nendmodule\n";
assert!(banning("[\"tmp\"]", src).is_empty(), "a substring is not a match");
assert_eq!(banning("[\".*_tmp\"]", src).len(), 1);
}
#[test]
fn every_kind_of_declared_name_is_covered() {
let src = "package foo_pkg;\n typedef logic foo_t;\nendpackage\n\
module foo_mod (input logic foo_port);\n logic foo_sig;\nendmodule\n";
let found = banning("[\"foo.*\"]", src);
let names: Vec<&str> = found.iter().map(|v| &src[v.span.as_range()]).collect();
for wanted in ["foo_pkg", "foo_t", "foo_mod", "foo_port", "foo_sig"] {
assert!(names.contains(&wanted), "{wanted} missing from {names:?}");
}
}
#[test]
fn several_patterns_are_all_applied_and_findings_come_back_in_order() {
let src = "module m;\n logic tmp_a;\n logic bad_b;\nendmodule\n";
let found = banning("[\"tmp.*\", \"bad.*\"]", src);
assert_eq!(found.len(), 2);
assert!(found[0].span.start < found[1].span.start);
}
}
@@ -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,127 @@
//! `constraint-name-style` — constraint names end in `_c`.
use crate::context::LintContext;
use crate::naming::{fits_pattern, is_escaped, style_message};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
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 ConstraintNameStyle;
const NAME: &str = "constraint-name-style";
impl Rule for ConstraintNameStyle {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name constraints in lower_snake_case ending in _c"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A constraint block's name is what a test turns off — \
`obj.addr_range_c.constraint_mode(0)` — so it is read far from its \
declaration and needs to say what it is at the use site. Verible's \
`constraint-name-style` (enabled by default) spells the convention as \
`([a-z0-9]+_)+c`: lower-case words, then a `_c` suffix. lucisv checks \
the same pattern, on the constraints a class declares and on the \
out-of-block `constraint cls::name { … }` form.\n\n\
A prototype (`constraint c;`) is judged like a definition — it \
declares the same name. Escaped identifiers are exempt, and there is \
no fix: a rename reaches every `constraint_mode` call."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "pattern",
kind: OptionKind::Regex,
default: OptionDefault::Str("([a-z0-9]+_)+c"),
doc: "the pattern a constraint's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::Constraint(decl) = &item.kind else { return };
let name = &decl.name.text;
if is_escaped(name) || fits_pattern(ctx, NAME, "pattern", name) {
return;
}
out.push(Violation::new(
NAME,
style_message(
ctx,
NAME,
"pattern",
&format!("constraint `{name}`"),
"is not lower_snake_case ending in `_c`",
),
decl.name.span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
ConstraintNameStyle.check(&LintContext::new(src, None))
}
fn constraint(name: &str) -> String {
format!("class c;\n rand int addr;\n constraint {name} {{ addr > 0; }}\nendclass\n")
}
#[test]
fn flags_a_missing_suffix_and_points_at_the_name() {
let src = constraint("addr_range");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "addr_range");
assert!(found[0].fix.is_none());
}
#[test]
fn the_convention_is_clean() {
for name in ["addr_range_c", "a_c", "addr2_range_c"] {
assert!(violations(&constraint(name)).is_empty(), "{name}");
}
for name in ["c", "AddrRangeC", "addr_range", "_addr_c"] {
assert_eq!(violations(&constraint(name)).len(), 1, "{name}");
}
}
#[test]
fn a_prototype_and_an_out_of_block_definition_are_judged_too() {
let src = "class c;\n extern constraint addr_range;\nendclass\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
let src = "constraint c::addr_range { x > 0; }\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn a_configured_pattern_replaces_the_default() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "pattern", "\"c_[a-z_0-9]+\"").expect("accepted");
let src = constraint("c_addr_range");
let ctx = LintContext::new(&src, None).with_options(&options);
assert!(ConstraintNameStyle.check(&ctx).is_empty());
let src = constraint("addr_range_c");
let ctx = LintContext::new(&src, None).with_options(&options);
assert_eq!(ConstraintNameStyle.check(&ctx).len(), 1);
}
}
@@ -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 \
@@ -2,8 +2,10 @@
//! or `_t`.
use crate::context::LintContext;
use crate::naming::{is_escaped, is_lower_snake_case};
use crate::naming::{fits_pattern, is_escaped};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
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 +24,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 \
@@ -31,7 +37,20 @@ impl Rule for EnumNameStyle {
same shape. Only a `typedef enum` is judged: an anonymous enum has no \
name to check, and giving it one is Verible's separate \
`typedef-enums` idea. Escaped identifiers are exempt, and there is no \
fix: a type rename reaches every use."
fix: a type rename reaches every use.\n\n\
The shape is the `style_regex` option, and its default is \
`[a-z][a-z_0-9]*(_t|_e)` — Verible's pattern with the first character \
pinned to a letter, which is what lucisv's preset checked before the \
option existed and what keeps a leading `_` reported."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str(DEFAULT_STYLE),
doc: "the pattern an enum typedef's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
@@ -42,13 +61,18 @@ impl Rule for EnumNameStyle {
return;
}
let name = &typedef.name;
let suffixed = name.ends_with("_e") || name.ends_with("_t");
if is_lower_snake_case(name) && suffixed {
if fits_pattern(ctx, NAME, "style_regex", name) {
return;
}
out.push(Violation::new(
NAME,
format!("enum `{name}` is not lower_snake_case ending in `_e` or `_t`"),
crate::naming::style_message(
ctx,
NAME,
"style_regex",
&format!("enum `{name}`"),
"is not lower_snake_case ending in `_e` or `_t`",
),
typedef.name_span,
));
});
@@ -56,6 +80,10 @@ impl Rule for EnumNameStyle {
}
}
/// Today's preset, written as a pattern: `lower_snake_case` (a letter first)
/// ending in `_e` or `_t`.
const DEFAULT_STYLE: &str = "[a-z][a-z_0-9]*(_t|_e)";
#[cfg(test)]
mod tests {
use super::*;
@@ -104,4 +132,31 @@ mod tests {
let src = typedef("state");
assert_eq!(&src[violations(&src)[0].span.as_range()], "state");
}
/// The default pattern is today's preset, character for character: a
/// leading `_` or digit is still rejected, which Verible's own
/// `[a-z_0-9]+(_t|_e)` would accept.
#[test]
fn the_default_pattern_is_the_preset_it_replaced() {
for bad in ["_state_t", "State_t", "state"] {
assert_eq!(violations(&typedef(bad)).len(), 1, "{bad}");
}
for good in ["state_t", "state_e", "s_t", "fifo2_state_e"] {
assert!(violations(&typedef(good)).is_empty(), "{good}");
}
}
#[test]
fn a_configured_pattern_replaces_it_and_is_named_in_the_message() {
let mut options = crate::options::RuleOptions::new();
options.set_raw(NAME, "style_regex", "\"[a-z_0-9]+_e\"").expect("accepted");
let src = typedef("state_t");
let ctx = LintContext::new(&src, None).with_options(&options);
let found = EnumNameStyle.check(&ctx);
assert_eq!(found.len(), 1, "`_t` is no longer accepted");
assert!(found[0].message.contains("[a-z_0-9]+_e"), "{}", found[0].message);
let src = typedef("_state_e");
let ctx = LintContext::new(&src, None).with_options(&options);
assert!(EnumNameStyle.check(&ctx).is_empty(), "and a leading `_` now passes");
}
}
@@ -0,0 +1,330 @@
//! `explicit-begin` — a body is a `begin ... end` block, always.
use crate::context::LintContext;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use crate::visit::{walk_all_stmts, walk_items};
use vlog_parser::ast::{ItemKind, Stmt, StmtKind};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct ExplicitBegin;
const NAME: &str = "explicit-begin";
/// The eleven constructs Verible lets a project switch on one at a time, each
/// with the keyword a diagnostic names it by.
const ENABLES: [(&str, &str); 11] = [
("always_comb_enable", "always_comb"),
("always_enable", "always"),
("always_ff_enable", "always_ff"),
("always_latch_enable", "always_latch"),
("else_enable", "else"),
("final_enable", "final"),
("for_enable", "for"),
("forever_enable", "forever"),
("if_enable", "if"),
("initial_enable", "initial"),
("while_enable", "while"),
];
impl Rule for ExplicitBegin {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"wrap every body in `begin` and `end`"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"The classic C bug transplanted: `if (a) x = 1;` grows a second \
statement in a later edit, the author indents it, and the compiler \
reads it as unconditional. Writing `begin ... end` from the start \
makes that edit impossible to get wrong, which is why several house \
styles require it. Verible's `explicit-begin` ships **off** — the \
style is far from universal, and a codebase that does not follow it \
would light up on the first run — and lucisv keeps it off for the same \
reason.\n\n\
Eleven `*_enable` options, exactly Verible's, switch the constructs on \
and off one at a time; all are on when the rule is. An `else if` is \
never reported: the `else`'s body is another `if`, which is the \
chained form every style guide writes. A null body (`if (a) ;`) is \
left to `suspicious-semicolon`, which has more to say about it. The \
fix wraps the body in `begin`/`end` and is **safe** — a block around \
one statement changes nothing — and running the formatter afterwards \
lays it out."
}
fn default_on(&self) -> bool {
false
}
fn fix(&self) -> Option<Applicability> {
Some(Applicability::Safe)
}
fn options(&self) -> &'static [OptionSpec] {
// Written out rather than generated, because a spec table is a
// `static` and every entry needs its own `&'static str` doc.
&[
OptionSpec {
name: "always_comb_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `always_comb`",
},
OptionSpec {
name: "always_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `always`",
},
OptionSpec {
name: "always_ff_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `always_ff`",
},
OptionSpec {
name: "always_latch_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `always_latch`",
},
OptionSpec {
name: "else_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `else`",
},
OptionSpec {
name: "final_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of a `final`",
},
OptionSpec {
name: "for_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of a `for` loop",
},
OptionSpec {
name: "forever_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of a `forever` loop",
},
OptionSpec {
name: "if_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `if`",
},
OptionSpec {
name: "initial_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `initial`",
},
OptionSpec {
name: "while_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of a `while` loop",
},
]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
let mut report = |keyword: &'static str, body: &Stmt| {
if !enabled(ctx, keyword) || is_block(body) || matches!(body.kind, StmtKind::Null) {
return;
}
out.push(
Violation::new(
NAME,
format!("`{keyword}` body is not a `begin ... end` block"),
body.span,
)
.with_fix(Fix::safe(vec![
(TextRange::new(body.span.start, body.span.start), "begin ".to_string()),
(TextRange::new(body.span.end, body.span.end), " end".to_string()),
])),
);
};
walk_items(ctx.file(), &mut |item| match &item.kind {
ItemKind::Always { kw, stmt } => {
let keyword = ENABLES
.iter()
.find_map(|(_, word)| (*word == kw).then_some(*word))
.unwrap_or("always");
if let Some(body) = procedural_body(stmt) {
report(keyword, body);
}
}
ItemKind::Initial(stmt) => {
if let Some(body) = procedural_body(stmt) {
report("initial", body);
}
}
ItemKind::Final(stmt) => {
if let Some(body) = procedural_body(stmt) {
report("final", body);
}
}
_ => {}
});
walk_all_stmts(ctx.file(), &mut |stmt| match &stmt.kind {
StmtKind::If { then, els, .. } => {
report("if", then);
// `else if` is the chained form, not a missing block.
if let Some(els) = els {
if !matches!(els.kind, StmtKind::If { .. }) {
report("else", els);
}
}
}
StmtKind::For { body, .. } => report("for", body),
StmtKind::While { body, .. } => report("while", body),
StmtKind::Forever { body } => report("forever", body),
_ => {}
});
out
}
}
/// Whether the run wants this construct checked.
fn enabled(ctx: &LintContext, keyword: &str) -> bool {
ENABLES
.iter()
.find(|(_, word)| *word == keyword)
.is_none_or(|(option, _)| ctx.option_bool(NAME, option))
}
/// The statement a procedural block really runs: the one under its timing
/// control, when it has one (`always_ff @(posedge clk) q <= d;`).
///
/// `None` for a timing control with no body at all (`always @(posedge clk);`),
/// which has nothing to wrap.
fn procedural_body(stmt: &Stmt) -> Option<&Stmt> {
match &stmt.kind {
StmtKind::Timing { stmt, .. } => stmt.as_deref(),
_ => Some(stmt),
}
}
/// Whether this statement is already a block.
fn is_block(stmt: &Stmt) -> bool {
matches!(stmt.kind, StmtKind::Block { .. } | StmtKind::ForkJoin { .. })
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
use crate::violation::apply_fixes;
fn violations(src: &str) -> Vec<Violation> {
ExplicitBegin.check(&LintContext::new(src, None))
}
#[test]
fn it_is_off_by_default_and_takes_veribles_eleven_options() {
assert!(!ExplicitBegin.default_on());
let names: Vec<&str> = ExplicitBegin.options().iter().map(|spec| spec.name).collect();
assert_eq!(names.len(), 11);
assert!(names.contains(&"if_enable") && names.contains(&"always_ff_enable"));
}
#[test]
fn flags_an_unblocked_if_body_and_wraps_it() {
let src = "module m;\n initial begin\n if (a) x = 1;\n end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "x = 1;");
let fixed = apply_fixes(src, &found, false);
assert_eq!(
fixed.output,
"module m;\n initial begin\n if (a) begin x = 1; end\n end\nendmodule\n"
);
assert!(violations(&fixed.output).is_empty(), "the fix satisfies the rule");
}
#[test]
fn a_blocked_body_is_clean() {
let src = "module m;\n initial begin\n if (a) begin\n x = 1;\n end\n end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn every_construct_is_covered() {
let src = "module m;\n\
\x20 always_comb x = 1;\n\
\x20 always_ff @(posedge clk) q <= d;\n\
\x20 always @(a) y = 2;\n\
\x20 always_latch if (en) z = 3;\n\
\x20 initial x = 0;\n\
\x20 final $display(\"bye\");\n\
endmodule\n";
let found = violations(src);
// Six bodies, plus the `if` inside the always_latch.
assert_eq!(found.len(), 7, "{:#?}", found.iter().map(|v| &v.message).collect::<Vec<_>>());
let src = "module m;\n initial begin\n\
\x20 for (int i = 0; i < 2; i++) x = i;\n\
\x20 while (a) y = 1;\n\
\x20 forever z = 2;\n\
\x20 end\nendmodule\n";
assert_eq!(violations(src).len(), 3, "{:?}", violations(src));
}
#[test]
fn an_else_if_chain_is_not_a_missing_block() {
let src = "module m;\n initial begin\n if (a) begin\n x = 1;\n end\n\
\x20 else if (b) begin\n x = 2;\n end\n end\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_bare_else_body_is_reported() {
let src =
"module m;\n initial begin\n if (a) begin\n x = 1;\n end else x = 2;\n\
\x20 end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`else`"), "{}", found[0].message);
}
#[test]
fn a_null_body_is_left_to_suspicious_semicolon() {
let src = "module m;\n initial begin\n if (a) ;\n end\nendmodule\n";
assert!(violations(src).is_empty());
}
#[test]
fn each_option_switches_its_own_construct_off() {
let src = "module m;\n initial begin\n if (a) x = 1;\n while (b) y = 2;\n end\n\
endmodule\n";
assert_eq!(violations(src).len(), 2);
let mut options = RuleOptions::new();
options.set_raw(NAME, "if_enable", "false").expect("accepted");
let found = ExplicitBegin.check(&LintContext::new(src, None).with_options(&options));
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`while`"), "{}", found[0].message);
}
#[test]
fn a_fork_join_body_is_already_a_block() {
let src = "module m;\n initial fork\n x = 1;\n join\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
}
@@ -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, ListElem, 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: &[ListElem<TfArg>]) -> Vec<Violation> {
let mut out = Vec::new();
let mut opened = false;
for arg in args.iter().filter_map(ListElem::ok) {
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,120 @@
//! `forbid-consecutive-null-statements` — no `;;` where a statement belongs.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use crate::visit::walk_all_stmts;
use vlog_parser::ast::StmtKind;
/// See [`Rule::doc`].
pub struct ForbidConsecutiveNullStatements;
const NAME: &str = "forbid-consecutive-null-statements";
impl Rule for ForbidConsecutiveNullStatements {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"remove the extra `;`"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A `;` immediately after another `;` is a **null statement**: legal, \
meaningless, and almost always a typo left behind by an edit — the \
statement twin of `empty-item`. It is also a trap next to a loop or an \
`if`, where a stray `;` silently becomes the body. Verible's \
`forbid-consecutive-null-statements` (enabled by default) reports \
exactly this, and the fix deletes the extra `;`, which cannot change \
what the code means.\n\n\
The test is Verible's: a null statement whose preceding token is a \
`;`. The empty header of a `for (;;)` is not a statement and is never \
reported, and neither is the single `;` after an `end` — that one is \
the block's own terminator."
}
fn fix(&self) -> Option<Applicability> {
Some(Applicability::Safe)
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_all_stmts(ctx.file(), &mut |stmt| {
if !matches!(stmt.kind, StmtKind::Null) || !follows_a_semicolon(ctx, stmt.span.start) {
return;
}
out.push(
Violation::new(NAME, "consecutive null statement; remove the `;`", stmt.span)
.with_fix(Fix::safe(vec![(stmt.span, String::new())])),
);
});
out
}
}
/// Whether the token before `at` is a `;`.
fn follows_a_semicolon(ctx: &LintContext, at: u32) -> bool {
ctx.tokens()
.iter()
.rev()
.find(|token| token.span.end <= at)
.is_some_and(|token| token.text == ";")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::violation::apply_fixes;
fn violations(src: &str) -> Vec<Violation> {
ForbidConsecutiveNullStatements.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_doubled_semicolon_and_deletes_the_extra_one() {
let src = "module m;\n initial begin\n x = 1;;\n end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
let fixed = apply_fixes(src, &found, false);
assert_eq!(fixed.output, "module m;\n initial begin\n x = 1;\n end\nendmodule\n");
assert!(violations(&fixed.output).is_empty());
}
#[test]
fn three_in_a_row_lose_two() {
let src = "module m;\n initial begin\n x = 1;;;\n end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 2);
assert_eq!(
apply_fixes(src, &found, false).output,
"module m;\n initial begin\n x = 1;\n end\nendmodule\n"
);
}
#[test]
fn an_empty_for_header_is_not_a_statement() {
let src = "module m;\n initial for (;;) x = 1;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_lone_null_statement_is_left_to_its_own_devices() {
// `if (x) ;` is `suspicious-semicolon`'s business, not this rule's.
let src = "module m;\n initial if (x) ;\nendmodule\n";
assert!(violations(src).is_empty());
let src = "module m;\n initial begin\n ;\n end\nendmodule\n";
assert!(violations(src).is_empty());
}
#[test]
fn a_semicolon_after_an_end_is_not_one() {
let src = "module m;\n initial begin\n begin\n end;\n end\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
}
@@ -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,118 @@
//! `generate-label` — every generate block carries a label.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_generate_blocks;
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct GenerateLabel;
const NAME: &str = "generate-label";
impl Rule for GenerateLabel {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"label every generate block"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"An unlabelled generate block still has a name: the tool invents one \
(`genblk3`), and that name is what appears in the hierarchy path, in \
every waveform, in every constraint file and in every error message \
the simulator prints. Renumbering happens the moment somebody adds a \
block above it, so paths written against the invented names rot \
silently. Verible's `generate-label` (enabled by default) requires the \
`begin : name`, and lucisv checks the same thing on every `if`, `for` \
and `case` generate block.\n\n\
Only a block is judged. A generate `if` whose branch is a single item \
with no `begin` opens no scope and needs no name — making it a block \
is Verible's separate `generate-begin` family, which lucisv does not \
have yet. There is no fix: only the author knows what the block should \
be called."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
if !ctx.parsed_cleanly() {
return Vec::new();
}
let mut out = Vec::new();
walk_generate_blocks(ctx.file(), &mut |block| {
if !block.is_block || block.label.is_some() {
return;
}
// Point at the `begin`, which is where the label would be written.
let begin = TextRange::new(block.span.start, block.span.start + 5);
out.push(Violation::new(NAME, "generate block has no `: label`", begin));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
GenerateLabel.check(&LintContext::new(src, None))
}
#[test]
fn flags_an_unlabelled_block_and_points_at_its_begin() {
let src = "module m;\n if (A) begin\n wire a;\n end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "begin");
assert!(found[0].fix.is_none());
}
#[test]
fn a_labelled_block_is_clean() {
let src = "module m;\n if (A) begin : g_a\n wire a;\n end\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn every_generate_shape_is_covered() {
let src = "module m;\n\
\x20 generate\n\
\x20 for (genvar i = 0; i < 2; i++) begin\n wire a;\n end\n\
\x20 if (A) begin\n wire b;\n end else begin\n wire c;\n end\n\
\x20 case (A)\n 0: begin\n wire d;\n end\n endcase\n\
\x20 endgenerate\n\
endmodule\n";
assert_eq!(violations(src).len(), 4, "{:?}", violations(src));
}
#[test]
fn a_blockless_branch_opens_no_scope() {
let src = "module m;\n if (A) wire a;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_procedural_begin_is_not_a_generate_block() {
let src = "module m;\n initial begin\n x = 1;\n end\nendmodule\n";
assert!(violations(src).is_empty());
}
/// The opentitan false-positive class: in a file error recovery could not
/// put back together, a procedural `begin` can be rebound as a generate
/// block. The rule says nothing about such a file.
#[test]
fn a_file_that_does_not_parse_is_left_alone() {
let src = "module m;\n @@@ junk\n if (A) begin\n wire a;\n end\nendmodule\n";
let ctx = LintContext::new(src, None);
assert!(!ctx.parsed_cleanly(), "the probe needs a file that does not parse");
assert!(GenerateLabel.check(&ctx).is_empty());
}
}
@@ -0,0 +1,150 @@
//! `generate-label-prefix` — a generate block's label says it is one.
use crate::context::LintContext;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_generate_blocks;
/// See [`Rule::doc`].
pub struct GenerateLabelPrefix;
const NAME: &str = "generate-label-prefix";
impl Rule for GenerateLabelPrefix {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"prefix a generate block's label with `g_` or `gen_`"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A generate label becomes a level of the instance hierarchy, so \
`top.core.fifo.data` may or may not have a generate block in the \
middle of it — and whether it does decides whether a path written in a \
testbench, an SDC file or an assertion still resolves after the code \
is re-parameterized. A prefix makes the generate levels visible in \
every such path. Verible's `generate-label-prefix` (enabled by \
default) requires one, and lucisv accepts `g_` or `gen_`, the two \
spellings real RTL uses.\n\n\
The `prefix` option is the list of accepted beginnings; an empty list \
accepts every label, which is how a project turns the shape off while \
keeping `generate-label`'s requirement that there *be* a label. There \
is no fix: renaming a block changes every hierarchical path that names \
it.\n\n\
Silent in a file that does not fully parse, for the reason \
`generate-label` gives: error recovery can rebind a procedural block \
as a generate one, and a label judged there would be judged by the \
wrong convention."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "prefix",
kind: OptionKind::List,
default: OptionDefault::List(&["g_", "gen_"]),
doc: "the beginnings a generate block's label may have",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let prefixes = ctx.option_list(NAME, "prefix");
if prefixes.is_empty() || !ctx.parsed_cleanly() {
return Vec::new();
}
let mut out = Vec::new();
walk_generate_blocks(ctx.file(), &mut |block| {
let (Some(label), Some(span)) = (&block.label, block.label_span) else { return };
if prefixes.iter().any(|prefix| label.starts_with(prefix.as_str())) {
return;
}
let wanted: Vec<String> = prefixes.iter().map(|p| format!("`{p}`")).collect();
out.push(Violation::new(
NAME,
format!("generate label `{label}` does not start with {}", wanted.join(" or ")),
span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
GenerateLabelPrefix.check(&LintContext::new(src, None))
}
fn labelled(label: &str) -> String {
format!("module m;\n if (A) begin : {label}\n wire a;\n end\nendmodule\n")
}
#[test]
fn flags_a_label_with_no_prefix_and_points_at_it() {
let src = labelled("core");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`g_` or `gen_`"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "core");
assert!(found[0].fix.is_none());
}
#[test]
fn both_conventional_prefixes_are_accepted() {
assert!(violations(&labelled("g_core")).is_empty());
assert!(violations(&labelled("gen_core")).is_empty());
}
#[test]
fn an_unlabelled_block_is_generate_labels_business() {
let src = "module m;\n if (A) begin\n wire a;\n end\nendmodule\n";
assert!(violations(src).is_empty());
}
#[test]
fn a_file_that_does_not_parse_is_left_alone() {
let src = "module m;\n @@@ junk\n if (A) begin : core\n wire a;\n end\nendmodule\n";
let ctx = LintContext::new(src, None);
assert!(!ctx.parsed_cleanly());
assert!(GenerateLabelPrefix.check(&ctx).is_empty());
}
#[test]
fn a_for_generate_label_is_covered() {
let src = "module m;\n for (genvar i = 0; i < 2; i++) begin : lanes\n wire a;\n end\n\
endmodule\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn a_configured_list_replaces_the_default_and_an_empty_one_accepts_everything() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "prefix", "[\"blk_\"]").expect("accepted");
let src = labelled("blk_core");
assert!(GenerateLabelPrefix
.check(&LintContext::new(&src, None).with_options(&options))
.is_empty());
let src = labelled("g_core");
assert_eq!(
GenerateLabelPrefix.check(&LintContext::new(&src, None).with_options(&options)).len(),
1
);
let mut empty = RuleOptions::new();
empty.set_raw(NAME, "prefix", "[]").expect("accepted");
let src = labelled("core");
assert!(GenerateLabelPrefix
.check(&LintContext::new(&src, None).with_options(&empty))
.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,138 @@
//! `interface-name-style` — interface names are `lower_snake_case` ending
//! `_if`.
use crate::context::LintContext;
use crate::naming::{fits_pattern, is_escaped, style_message};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
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 InterfaceNameStyle;
const NAME: &str = "interface-name-style";
impl Rule for InterfaceNameStyle {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name interfaces in lower_snake_case ending in _if"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"An interface is written where a type is written — `virtual bus_if h`, \
`bus_if.master port` — and nothing in the syntax says that the \
identifier is an interface rather than a module or a class. The `_if` \
suffix is what says it, and Verible's `interface-name-style` (enabled \
by default, pattern `[a-z_0-9]+(_if)`) requires it. lucisv checks the \
same shape, on every `interface` declaration in the file.\n\n\
Only an `interface` is judged: a `module` and a `program` have their \
own conventions, and `module-name-style` is where a project that wants \
one says so. Escaped identifiers are exempt, and there is no fix — an \
interface rename reaches every port, every virtual handle and every \
file that imports it."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str("[a-z_0-9]+(_if)"),
doc: "the pattern an interface's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::Module(module) = &item.kind else { return };
if module.kw != "interface" || is_escaped(&module.name) {
return;
}
if fits_pattern(ctx, NAME, "style_regex", &module.name) {
return;
}
out.push(Violation::new(
NAME,
style_message(
ctx,
NAME,
"style_regex",
&format!("interface `{}`", module.name),
"is not lower_snake_case ending in `_if`",
),
module.name_span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
InterfaceNameStyle.check(&LintContext::new(src, None))
}
fn interface(name: &str) -> String {
format!("interface {name};\nendinterface\n")
}
#[test]
fn flags_a_missing_suffix_and_points_at_the_name() {
let src = interface("bus");
let found = violations(&src);
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("`bus`"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "bus");
assert!(found[0].fix.is_none());
}
#[test]
fn the_convention_is_clean() {
for name in ["bus_if", "clk_rst_if", "tl_if", "a_if"] {
assert!(violations(&interface(name)).is_empty(), "{name}");
}
for name in ["BusIf", "bus_IF", "bus_intf"] {
assert_eq!(violations(&interface(name)).len(), 1, "{name}");
}
}
#[test]
fn a_module_or_a_program_is_none_of_its_business() {
assert!(violations("module bus;\nendmodule\n").is_empty());
assert!(violations("program test;\nendprogram\n").is_empty());
}
#[test]
fn an_interface_inside_a_package_is_covered() {
let src = "package p;\n interface bus;\n endinterface\nendpackage\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn a_configured_pattern_replaces_the_default() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "style_regex", "\"[a-z_0-9]+_intf\"").expect("accepted");
let src = interface("bus_intf");
let ctx = LintContext::new(&src, None).with_options(&options);
assert!(InterfaceNameStyle.check(&ctx).is_empty());
let src = interface("bus_if");
let ctx = LintContext::new(&src, None).with_options(&options);
let found = InterfaceNameStyle.check(&ctx);
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("_intf"), "{}", found[0].message);
}
}
@@ -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());
}
}
+180
View File
@@ -0,0 +1,180 @@
//! `line-length` — no line wider than the run's width.
use crate::context::LintContext;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct LineLength;
const NAME: &str = "line-length";
impl Rule for LineLength {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"keep lines within the configured width"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A line nobody can see the end of is a line nobody reviews: side-by-side \
diffs, terminal windows and printed listings all cut at a fixed width. \
Verible's `line-length` (enabled by default, 100 columns) is this rule, \
and lucisv's default is the width **the formatter is configured with** \
for this file — `--line-length`, `lucisv.toml`, or 100 — so the two \
halves of lucisv cannot disagree about what fits. The `length` option \
overrides that for a project that lints wider than it formats.\n\n\
The check is token-aware, as Verible's is: a line that holds one \
unbreakable token — a long string literal, an `` `include`` path, a \
macro invocation — is left alone, because there is no way to wrap it \
and reporting it would only teach the user to waive the rule. A `;` or \
`,` after that token does not count as a second piece. There is no \
fix: where to break a line is what the formatter is for, and running \
it is the repair."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "length",
kind: OptionKind::Int { min: 40, max: 400 },
default: OptionDefault::Int(100),
doc: "the widest line accepted; unset means the width the formatter uses",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
// The spec's default is what `--rules-doc` prints; the *run's* default
// is the formatter's width, which is why the question here is whether
// anybody set the option rather than what it reads.
let limit = if ctx.option_is_set(NAME, "length") {
ctx.option_int(NAME, "length").max(1) as usize
} else {
ctx.line_length()
};
let mut out = Vec::new();
for line in 1..=ctx.line_index().line_count() {
let Some(range) = ctx.line_index().line_range(line) else { continue };
let text = ctx.line_text(line);
let width = text.chars().count();
if width <= limit || is_unbreakable(ctx, range) {
continue;
}
// Point at the first column past the limit, as a compiler does.
let over = text.char_indices().nth(limit).map_or(text.len(), |(at, _)| at) as u32;
out.push(Violation::new(
NAME,
format!("line is {width} characters; the limit is {limit}"),
TextRange::new(range.start + over, range.end),
));
}
out
}
}
/// Whether this line is one piece of text that no wrapping could shorten.
///
/// The pieces are the tokens and the comments that touch the line, less a
/// trailing `;` or `,` — punctuation that has to sit somewhere and never
/// makes a line wrappable. One piece and it is a token: unbreakable. A
/// comment is *not* unbreakable, since prose wraps.
fn is_unbreakable(ctx: &LintContext, line: TextRange) -> bool {
let touches = |span: TextRange| span.start < line.end && line.start < span.end;
let comments = ctx.comments().into_iter().filter(|c| touches(c.span)).count();
if comments > 0 {
return false;
}
let tokens: Vec<&vlog_parser::token::Token> = ctx
.tokens()
.iter()
.filter(|token| token.kind != vlog_parser::token::TokenKind::Eof && touches(token.span))
.filter(|token| !matches!(token.text.as_str(), ";" | ","))
.collect();
tokens.len() == 1
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
LineLength.check(&LintContext::new(src, None))
}
fn line_of(width: usize) -> String {
format!("module m;\n wire {};\nendmodule\n", "a".repeat(width))
}
#[test]
fn flags_a_line_past_the_width_and_leaves_the_rest_alone() {
let src = line_of(120);
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("the limit is 100"), "{}", found[0].message);
assert!(found[0].fix.is_none(), "wrapping a line is the formatter's job");
assert!(violations(&line_of(50)).is_empty());
}
#[test]
fn it_points_at_the_first_column_past_the_limit() {
let src = line_of(120);
let found = violations(&src);
let (line, col) = LintContext::new(&src, None).line_index().line_col(found[0].span.start);
assert_eq!((line, col), (2, 101));
}
#[test]
fn the_width_is_the_one_the_formatter_was_given() {
let src = line_of(90);
assert!(violations(&src).is_empty(), "under the default 100");
let ctx = LintContext::new(&src, None).with_line_length(80);
assert_eq!(LineLength.check(&ctx).len(), 1, "and over a narrower one");
}
#[test]
fn the_option_overrides_the_formatters_width() {
let src = line_of(110);
let mut options = RuleOptions::new();
options.set_raw(NAME, "length", "120").expect("accepted");
let ctx = LintContext::new(&src, None).with_options(&options).with_line_length(80);
assert!(LineLength.check(&ctx).is_empty(), "the option beats the formatter's width");
}
#[test]
fn a_line_that_is_one_unbreakable_token_is_left_alone() {
// A long include path, a long macro invocation and a long string on a
// line of its own: none of them can be wrapped.
let long = "x".repeat(140);
for src in [
format!("`include \"{long}.svh\"\n"),
format!("module m;\n `{long}\nendmodule\n"),
format!("module m;\n initial x = 1;\nendmodule\n// {long}\n"),
] {
let found = violations(&src);
let unbreakable = !src.contains("// ");
assert_eq!(found.is_empty(), unbreakable, "{}", &src[..40.min(src.len())]);
}
}
#[test]
fn a_long_string_inside_a_statement_is_still_reported() {
// The line has other tokens, so the formatter could break it.
let src = format!("module m;\n initial $display(\"{}\");\nendmodule\n", "y".repeat(120));
assert_eq!(violations(&src).len(), 1);
}
#[test]
fn a_trailing_semicolon_does_not_make_a_line_breakable() {
let src = format!("module m;\n `{};\nendmodule\n", "z".repeat(140));
assert!(violations(&src).is_empty());
}
}
@@ -0,0 +1,173 @@
//! `macro-name-style` — `` `define`` names are `ALL_CAPS`.
use crate::context::LintContext;
use crate::naming::{fits_pattern, style_message};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::span::TextRange;
use vlog_parser::token::TokenKind;
/// See [`Rule::doc`].
pub struct MacroNameStyle;
const NAME: &str = "macro-name-style";
impl Rule for MacroNameStyle {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name macros in ALL_CAPS"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A macro is text substitution: it obeys no scope, it is invisible in a \
waveform, and it can rewrite the code around its use into something \
the reader did not write. Every language that has macros marks them by \
case for that reason, and Verible's `macro-name-style` (enabled by \
default, pattern `[A-Z_0-9]+`) is the Verilog spelling of it. lucisv \
checks the name a `` `define`` declares — not its uses, which are \
whatever the definition called itself.\n\n\
The check reads the directive text rather than a preprocessor table: \
lucisv does not expand macros, so what a file defines is exactly what \
its `` `define`` lines say. There is no fix — renaming a macro reaches \
every use, including uses in other files."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str("[A-Z_0-9]+"),
doc: "the pattern a macro's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
for token in ctx.tokens() {
if token.kind != TokenKind::Directive {
continue;
}
let Some((name, span)) = defined_name(&token.text, token.span.start) else { continue };
if fits_pattern(ctx, NAME, "style_regex", &name) {
continue;
}
out.push(Violation::new(
NAME,
style_message(
ctx,
NAME,
"style_regex",
&format!("macro `{name}`"),
"is not ALL_CAPS",
),
span,
));
}
out
}
}
/// The name a `` `define`` directive declares, with its byte range.
///
/// `text` is the directive as the lexer kept it — from the backtick to the end
/// of the (possibly continued) line — and `at` is where it starts in the file.
fn defined_name(text: &str, at: u32) -> Option<(String, TextRange)> {
let rest = text.strip_prefix('`')?;
let rest = rest.strip_prefix("define")?;
if !rest.starts_with([' ', '\t']) {
return None;
}
let after_keyword = text.len() - rest.len();
let start = after_keyword + (rest.len() - rest.trim_start().len());
let name: String = text[start..]
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '$')
.collect();
if name.is_empty() {
return None;
}
let start = at + start as u32;
Some((name.clone(), TextRange::new(start, start + name.len() as u32)))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
MacroNameStyle.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_lower_case_macro_and_points_at_the_name() {
let src = "`define my_macro 1\n";
let found = violations(src);
assert_eq!(found.len(), 1);
assert_eq!(&src[found[0].span.as_range()], "my_macro");
assert!(found[0].fix.is_none(), "a rename reaches every use");
}
#[test]
fn all_caps_names_are_clean() {
assert!(violations("`define MY_MACRO 1\n").is_empty());
assert!(violations("`define W2 8\n").is_empty());
assert!(violations("`define MY_FN(a, b) ((a) + (b))\n").is_empty());
}
#[test]
fn a_function_like_macro_is_read_up_to_its_paren() {
let src = "`define my_fn(a) (a)\n";
let found = violations(src);
assert_eq!(found.len(), 1);
assert_eq!(&src[found[0].span.as_range()], "my_fn");
}
#[test]
fn other_directives_and_uses_are_none_of_its_business() {
for src in [
"`include \"lower_case.svh\"\n",
"`ifdef lower_case\n`endif\n",
"`timescale 1ns / 1ps\n",
"module m;\n `my_macro\nendmodule\n",
"`undef my_macro\n",
] {
assert!(violations(src).is_empty(), "{src}");
}
}
#[test]
fn a_definition_inside_a_module_is_found_too() {
let src = "module m;\n`define inner 1\nendmodule\n";
assert_eq!(violations(src).len(), 1);
}
#[test]
fn a_configured_pattern_replaces_the_default() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "style_regex", "\"[a-z_0-9]+\"").expect("accepted");
let ctx = LintContext::new("`define my_macro 1\n", None).with_options(&options);
assert!(MacroNameStyle.check(&ctx).is_empty());
let ctx = LintContext::new("`define MY_MACRO 1\n", None).with_options(&options);
let found = MacroNameStyle.check(&ctx);
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("[a-z_0-9]+"), "{}", found[0].message);
}
#[test]
fn a_multi_line_definition_is_read_from_its_first_line() {
let src = "`define my_macro(a) \\\n do_something(a)\n";
let found = violations(src);
assert_eq!(found.len(), 1);
assert_eq!(&src[found[0].span.as_range()], "my_macro");
}
}
@@ -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));
}
}
+43 -4
View File
@@ -1,24 +1,63 @@
//! 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;
pub mod always_comb_blocking;
pub mod always_ff_non_blocking;
pub mod banned_declared_name_patterns;
pub mod case_missing_default;
pub mod constraint_name_style;
pub mod duplicate_declaration;
pub mod empty_item;
pub mod enum_name_style;
pub mod explicit_begin;
pub mod explicit_function_task_parameter_type;
pub mod explicit_parameter_storage_type;
pub mod forbid_consecutive_null_statements;
pub mod forbid_defparam;
pub mod forbid_negative_array_dim;
pub mod generate_label;
pub mod generate_label_prefix;
pub mod incomplete_assignment;
pub mod instance_shadowing;
pub mod interface_name_style;
pub mod invalid_system_task_function;
pub mod line_length;
pub mod macro_name_style;
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 one_module_per_file;
pub mod package_filename;
pub mod packed_dimensions_range_ordering;
pub mod parameter_name_style;
pub mod parameter_type_name_style;
pub mod plusarg_assignment;
pub mod port_name_suffix;
pub mod posix_eof;
pub mod signal_name_style;
pub mod struct_union_name_style;
pub mod suspicious_semicolon;
pub mod truncated_numeric_literal;
pub mod typedef_enums;
pub mod typedef_structs_unions;
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 — \
@@ -1,8 +1,10 @@
//! `module-name-style` — module names are `lower_snake_case`.
use crate::context::LintContext;
use crate::naming::{is_escaped, is_lower_snake_case};
use crate::naming::{fits_pattern, is_escaped, style_message};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::ItemKind;
@@ -21,6 +23,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 \
@@ -31,23 +37,44 @@ impl Rule for ModuleNameStyle {
here, Verible ships no `module-name-style` rule to inherit a default \
from, so enabling it is the user's call — `--select \
module-name-style`. Escaped identifiers (`\\my$mod`) are exempt, and \
there is no fix: renaming a module is a cross-file edit."
there is no fix: renaming a module is a cross-file edit.\n\n\
The shape is the `style_regex` option, default `[a-z][a-z_0-9]*` — \
the preset this rule checked before the option existed. The rule \
judges every `module`, `interface` and `program` name; a project that \
wants the `_if` convention for its interfaces has \
`interface-name-style` for that, and turning both on holds an \
interface to both."
}
fn default_on(&self) -> bool {
false
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str("[a-z][a-z_0-9]*"),
doc: "the pattern a module's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::Module(module) = &item.kind else { return };
if is_escaped(&module.name) || is_lower_snake_case(&module.name) {
if is_escaped(&module.name) || fits_pattern(ctx, NAME, "style_regex", &module.name) {
return;
}
out.push(Violation::new(
NAME,
format!("module `{}` is not lower_snake_case", module.name),
style_message(
ctx,
NAME,
"style_regex",
&format!("module `{}`", module.name),
"is not lower_snake_case",
),
module.name_span,
));
});
@@ -94,4 +121,26 @@ mod tests {
fn it_is_off_by_default() {
assert!(!ModuleNameStyle.default_on());
}
#[test]
fn the_default_pattern_is_the_preset_it_replaced() {
for bad in ["_foo", "FooBar", "fooBar"] {
assert_eq!(violations(&format!("module {bad};\nendmodule\n")).len(), 1, "{bad}");
}
for good in ["foo", "foo_bar", "fifo2_ctrl"] {
assert!(violations(&format!("module {good};\nendmodule\n")).is_empty(), "{good}");
}
}
#[test]
fn a_configured_pattern_replaces_it() {
let mut options = crate::options::RuleOptions::new();
options.set_raw(NAME, "style_regex", "\"[A-Z][A-Za-z0-9]*\"").expect("accepted");
let ctx = LintContext::new("module FooBar;\nendmodule\n", None).with_options(&options);
assert!(ModuleNameStyle.check(&ctx).is_empty());
let ctx = LintContext::new("module foo_bar;\nendmodule\n", None).with_options(&options);
let found = ModuleNameStyle.check(&ctx);
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("[A-Z][A-Za-z0-9]*"), "{}", found[0].message);
}
}
@@ -0,0 +1,103 @@
//! `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;
use vlog_parser::ast::ListElem;
/// 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_map(ListElem::ok).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,134 @@
//! `one-module-per-file` — one module declaration per file.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::ast::ItemKind;
/// See [`Rule::doc`].
pub struct OneModulePerFile;
const NAME: &str = "one-module-per-file";
impl Rule for OneModulePerFile {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"declare one module per file"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"Every tool that finds a module by searching a library directory looks \
for one named `<module>.sv`, and `module-filename` ties the file to the \
module it declares — a claim that only means something when there is \
exactly one. Verible's `one-module-per-file` is **off** by default and \
so is this one: plenty of real RTL keeps a handful of small helper \
modules beside the one the file is named for, and that is a project's \
choice rather than a mistake.\n\n\
Only the file's own `module` declarations count. An `interface`, a \
`program` and a `package` are not modules — a package of types beside \
the module that uses them is the common shape this rule must not \
punish.\n\n\
Silent in a file that does not fully parse: error recovery unwinds to \
file scope, so a `module` written inside something the parser could \
not finish reappears as a second top-level declaration — an accusation \
about text the author never wrote that way."
}
fn default_on(&self) -> bool {
false
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
if !ctx.parsed_cleanly() {
return Vec::new();
}
let modules: Vec<_> = ctx
.file()
.items
.iter()
.filter_map(|item| match &item.kind {
ItemKind::Module(module) if module.kw == "module" => Some(module),
_ => None,
})
.collect();
let Some(first) = modules.first() else { return Vec::new() };
modules
.iter()
.skip(1)
.map(|module| {
Violation::new(
NAME,
format!(
"module `{}` is the file's second declaration; `{}` is the first",
module.name, first.name
),
module.name_span,
)
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
OneModulePerFile.check(&LintContext::new(src, None))
}
#[test]
fn flags_every_module_after_the_first() {
let src = "module a;\nendmodule\nmodule b;\nendmodule\nmodule c;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 2);
assert!(found[0].message.contains("`b`"), "{}", found[0].message);
assert!(found[0].message.contains("`a` is the first"), "{}", found[0].message);
assert_eq!(&src[found[1].span.as_range()], "c");
}
#[test]
fn one_module_is_clean() {
assert!(violations("module a;\nendmodule\n").is_empty());
assert!(violations("package p;\nendpackage\n").is_empty());
}
#[test]
fn a_package_or_an_interface_beside_a_module_is_not_a_second_module() {
let src = "package p;\nendpackage\nmodule a;\nendmodule\ninterface i;\nendinterface\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
/// The everyday shape this rule must not punish: one module, and the
/// package of types it uses, in the same file.
#[test]
fn a_package_and_a_program_beside_one_module_are_clean() {
let src = "package p;\n typedef logic w_t;\nendpackage\n\
module a;\nendmodule\n\
program t;\nendprogram\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_file_that_does_not_parse_is_left_alone() {
// Recovery can promote a module the author nested inside something
// else to file scope; this rule must not accuse them of it.
let src = "module a;\n module inner;\n endmodule\nendmodule\n";
let ctx = LintContext::new(src, None);
assert!(!ctx.parsed_cleanly(), "a nested module does not parse");
assert!(OneModulePerFile.check(&ctx).is_empty());
}
#[test]
fn it_is_off_by_default() {
assert!(!OneModulePerFile.default_on());
}
}
@@ -0,0 +1,144 @@
//! `package-filename` — a one-package file is named after its package.
use crate::context::LintContext;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::ast::ItemKind;
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct PackageFilename;
const NAME: &str = "package-filename";
impl Rule for PackageFilename {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name a one-package file after its package"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A package is imported by name and found by file name, so the two \
disagreeing costs the same grep every time. Verible's \
`package-filename` (enabled by default) requires the file to be named \
after the package it declares, and accepts a `_pkg` suffix on the file \
that the package name does not carry — `foo` in `foo_pkg.sv` is the \
convention half of the industry writes. lucisv accepts both spellings \
for the same reason.\n\n\
Like `module-filename`, it speaks only when the file declares exactly \
one package, is silent for input with no file name (stdin), and offers \
no fix: renaming a file is not the linter's business. The \
`allow-dash-for-underscore` option lets a file named `foo-pkg.sv` \
satisfy a package called `foo_pkg`, which is Verible's option of the \
same name on `module-filename`. It is also silent in a file that does \
not fully parse: `exactly one package` is a claim about structure, and \
error recovery can invent a second one."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "allow-dash-for-underscore",
kind: OptionKind::Bool,
default: OptionDefault::Bool(false),
doc: "treat a `-` in the file name as the `_` of the package name",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
if !ctx.parsed_cleanly() {
return Vec::new();
}
let Some(path) = ctx.path() else { return Vec::new() };
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { return Vec::new() };
let mut packages = ctx.file().items.iter().filter_map(|item| match &item.kind {
ItemKind::Package { name, name_span, .. } => Some((name, *name_span)),
_ => None,
});
let (Some((name, span)), None) = (packages.next(), packages.next()) else {
return Vec::new();
};
let stem = if ctx.option_bool(NAME, "allow-dash-for-underscore") {
stem.replace('-', "_")
} else {
stem.to_string()
};
if stem == *name || stem == format!("{name}_pkg") {
return Vec::new();
}
let file_name = path.file_name().and_then(|s| s.to_str()).unwrap_or(&stem);
vec![report(name, span, file_name)]
}
}
fn report(name: &str, span: TextRange, file_name: &str) -> Violation {
Violation::new(NAME, format!("package `{name}` does not match file name `{file_name}`"), span)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
use std::path::PathBuf;
fn violations(src: &str, path: Option<&str>) -> Vec<Violation> {
PackageFilename.check(&LintContext::new(src, path.map(PathBuf::from)))
}
fn package(name: &str) -> String {
format!("package {name};\nendpackage\n")
}
#[test]
fn flags_a_mismatch_and_points_at_the_name() {
let src = package("foo_pkg");
let found = violations(&src, Some("rtl/bar.sv"));
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("bar.sv"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "foo_pkg");
assert!(found[0].fix.is_none());
}
#[test]
fn both_conventional_spellings_are_accepted() {
assert!(violations(&package("foo_pkg"), Some("rtl/foo_pkg.sv")).is_empty());
assert!(violations(&package("foo"), Some("rtl/foo.sv")).is_empty());
assert!(violations(&package("foo"), Some("rtl/foo_pkg.sv")).is_empty(), "the `_pkg` file");
assert!(violations(&package("foo"), Some("rtl/foo.svh")).is_empty());
}
#[test]
fn silent_without_a_file_name_or_with_more_than_one_package() {
assert!(violations(&package("foo"), None).is_empty());
let two = "package a;\nendpackage\npackage b;\nendpackage\n";
assert!(violations(two, Some("rtl/c.sv")).is_empty());
assert!(violations("module m;\nendmodule\n", Some("rtl/c.sv")).is_empty());
}
#[test]
fn a_file_that_does_not_parse_is_left_alone() {
let src = "package foo_pkg;\n @@@ junk\nendpackage\n";
let ctx = LintContext::new(src, Some(PathBuf::from("rtl/bar.sv")));
assert!(!ctx.parsed_cleanly());
assert!(PackageFilename.check(&ctx).is_empty());
}
#[test]
fn a_dash_stands_for_an_underscore_only_when_asked() {
let src = package("foo_pkg");
assert_eq!(violations(&src, Some("rtl/foo-pkg.sv")).len(), 1);
let mut options = RuleOptions::new();
options.set_raw(NAME, "allow-dash-for-underscore", "true").expect("accepted");
let ctx =
LintContext::new(&src, Some(PathBuf::from("rtl/foo-pkg.sv"))).with_options(&options);
assert!(PackageFilename.check(&ctx).is_empty());
}
}
@@ -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));
}
}
@@ -1,8 +1,10 @@
//! `parameter-name-style` — parameter names are `CamelCase` or `ALL_CAPS`.
use crate::context::LintContext;
use crate::naming::{is_camel_case, is_escaped, is_upper_snake_case};
use crate::naming::{fits_style, is_escaped, STYLE_WORDS};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
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 +24,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. \
@@ -29,23 +35,57 @@ impl Rule for ParameterNameStyle {
this, with `CamelCase` and `ALL_CAPS` as its presets. lucisv accepts \
either preset for both `parameter` and `localparam` — Verible's \
default is stricter for `localparam` (`CamelCase` only), which would \
flag most `localparam int FOO_BAR` in existing RTL; until per-rule \
style configuration exists, the union is the honest default. The rule \
covers item- and statement-level declarations and the `#( ... )` \
parameter ports of module and class headers. Escaped identifiers are \
exempt, and there is no fix: a rename reaches every override site."
flag most `localparam int FOO_BAR` in existing RTL, so the union is \
the default here and the option is where a project says otherwise. \
The rule covers item- and statement-level declarations and the \
`#( ... )` parameter ports of module and class headers. Escaped \
identifiers are exempt, and there is no fix: a rename reaches every \
override site.\n\n\
Four options, spelled as Verible spells them: `parameter_style` and \
`localparam_style` take `CamelCase`, `ALL_CAPS`, or both joined with \
`|`; `parameter_style_regex` and `localparam_style_regex` replace the \
words with a pattern for a project whose convention is neither."
}
fn options(&self) -> &'static [OptionSpec] {
&[
OptionSpec {
name: "localparam_style",
kind: OptionKind::Words(&STYLE_WORDS),
default: OptionDefault::Str(BOTH_PRESETS),
doc: "the presets a `localparam` name may take, joined with `|`",
},
OptionSpec {
name: "localparam_style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str(""),
doc: "a pattern a `localparam` name must match instead of the presets",
},
OptionSpec {
name: "parameter_style",
kind: OptionKind::Words(&STYLE_WORDS),
default: OptionDefault::Str(BOTH_PRESETS),
doc: "the presets a `parameter` name may take, joined with `|`",
},
OptionSpec {
name: "parameter_style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str(""),
doc: "a pattern a `parameter` name must match instead of the presets",
},
]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
if let ItemKind::ParamDecl(decl) = &item.kind {
check_decl(decl, &mut out);
check_decl(ctx, decl, &mut out);
}
});
walk_all_stmts(ctx.file(), &mut |stmt| {
if let StmtKind::ParamDecl(decl) = &stmt.kind {
check_decl(decl, &mut out);
check_decl(ctx, decl, &mut out);
}
});
walk_param_ports(ctx.file(), &mut |port| {
@@ -57,29 +97,41 @@ impl Rule for ParameterNameStyle {
return;
}
let kw = port.kw.as_deref().unwrap_or("parameter");
report(&port.name, port.name_span, kw, &mut out);
report(ctx, &port.name, port.name_span, kw, &mut out);
});
out
}
}
/// The presets both keywords accept unless a project says otherwise.
const BOTH_PRESETS: &str = "CamelCase|ALL_CAPS";
/// Reports every declarator of one `parameter`/`localparam` declaration.
fn check_decl(decl: &ParamDecl, out: &mut Vec<Violation>) {
fn check_decl(ctx: &LintContext, decl: &ParamDecl, out: &mut Vec<Violation>) {
for declarator in &decl.declarators {
report(&declarator.name, declarator.name_span, &decl.kw, out);
report(ctx, &declarator.name, declarator.name_span, &decl.kw, out);
}
}
/// Reports `name` unless it matches one of the two accepted presets.
fn report(name: &str, span: TextRange, kw: &str, out: &mut Vec<Violation>) {
if is_escaped(name) || is_camel_case(name) || is_upper_snake_case(name) {
/// Reports `name` unless it fits the style the run asks of its keyword.
fn report(ctx: &LintContext, name: &str, span: TextRange, kw: &str, out: &mut Vec<Violation>) {
let (style, regex) = if kw == "localparam" {
("localparam_style", "localparam_style_regex")
} else {
("parameter_style", "parameter_style_regex")
};
if is_escaped(name) || fits_style(ctx, NAME, style, regex, name) {
return;
}
out.push(Violation::new(
NAME,
format!("`{kw}` `{name}` is neither CamelCase nor ALL_CAPS"),
span,
));
let subject = format!("`{kw}` `{name}`");
let message = if ctx.option_is_set(NAME, regex) {
format!("{subject} does not match `{}`", ctx.option_str(NAME, regex))
} else if ctx.option_is_set(NAME, style) {
format!("{subject} is not {}", ctx.option_str(NAME, style).replace('|', " or "))
} else {
format!("{subject} is neither CamelCase nor ALL_CAPS")
};
out.push(Violation::new(NAME, message, span));
}
#[cfg(test)]
@@ -136,4 +188,36 @@ mod tests {
fn it_is_on_by_default() {
assert!(ParameterNameStyle.default_on());
}
fn with(options: &crate::options::RuleOptions, src: &str) -> Vec<Violation> {
ParameterNameStyle.check(&LintContext::new(src, None).with_options(options))
}
/// Verible's own default — `localparam_style: CamelCase` — is one option
/// away, and it separates the two keywords as Verible does.
#[test]
fn the_two_keywords_take_their_own_styles() {
let src = "module m;\n parameter int ADDR_W = 8;\n localparam int MAX_DEPTH = 4;\n\
endmodule\n";
assert!(violations(src).is_empty(), "both presets by default");
let mut options = crate::options::RuleOptions::new();
options.set_raw(NAME, "localparam_style", "\"CamelCase\"").expect("accepted");
let found = with(&options, src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("MAX_DEPTH"), "{}", found[0].message);
assert!(found[0].message.contains("is not CamelCase"), "{}", found[0].message);
}
#[test]
fn a_pattern_replaces_the_presets_for_that_keyword_only() {
let mut options = crate::options::RuleOptions::new();
options.set_raw(NAME, "parameter_style_regex", "\"p_[a-z_0-9]+\"").expect("accepted");
let src = "module m;\n parameter int p_width = 8;\n localparam int MAX_DEPTH = 4;\n\
endmodule\n";
assert!(with(&options, src).is_empty(), "the localparam keeps its presets");
let src = "module m;\n parameter int Width = 8;\nendmodule\n";
let found = with(&options, src);
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("p_[a-z_0-9]+"), "{}", found[0].message);
}
}
@@ -0,0 +1,124 @@
//! `parameter-type-name-style` — `type` parameters are named like types.
use crate::context::LintContext;
use crate::naming::{fits_pattern, is_escaped, style_message};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_param_ports;
/// See [`Rule::doc`].
pub struct ParameterTypeNameStyle;
const NAME: &str = "parameter-type-name-style";
impl Rule for ParameterTypeNameStyle {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name type parameters in lower_snake_case ending in _t"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A `type` parameter is a type, not a constant: it is written where \
`logic` or `addr_t` is written, and naming it `T` or `WIDTH_T` makes \
a declaration read like an expression. Verible's \
`parameter-type-name-style` asks for the same `lower_snake_case` with \
a `_t` suffix every other type name here carries, and ships it **off**; \
lucisv keeps it off, because the single-letter `#(type T = int)` is \
near-universal in UVM code and switching this on for such a codebase \
would report every class in it.\n\n\
Only a `type` parameter is judged — an ordinary one is \
`parameter-name-style`'s. Escaped identifiers are exempt, and there is \
no fix: a rename reaches every override site."
}
fn default_on(&self) -> bool {
false
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str("[a-z][a-z_0-9]*_t"),
doc: "the pattern a type parameter's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_param_ports(ctx.file(), &mut |port| {
if !port.is_type || is_escaped(&port.name) {
return;
}
if fits_pattern(ctx, NAME, "style_regex", &port.name) {
return;
}
out.push(Violation::new(
NAME,
style_message(
ctx,
NAME,
"style_regex",
&format!("type parameter `{}`", port.name),
"is not lower_snake_case ending in `_t`",
),
port.name_span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
ParameterTypeNameStyle.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_single_letter_type_parameter() {
let src = "class c #(type T = int);\nendclass\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "T");
assert!(found[0].fix.is_none());
}
#[test]
fn the_convention_is_clean() {
assert!(violations("class c #(type item_t = int);\nendclass\n").is_empty());
assert!(violations("module m #(type addr_t = logic) ();\nendmodule\n").is_empty());
}
#[test]
fn an_ordinary_parameter_is_none_of_its_business() {
assert!(violations("module m #(parameter int Width = 8) ();\nendmodule\n").is_empty());
assert!(violations("module m;\n parameter int width = 8;\nendmodule\n").is_empty());
}
#[test]
fn it_is_off_by_default() {
assert!(!ParameterTypeNameStyle.default_on());
}
#[test]
fn a_configured_pattern_replaces_the_default() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "style_regex", "\"[A-Z]\"").expect("accepted");
let ctx =
LintContext::new("class c #(type T = int);\nendclass\n", None).with_options(&options);
assert!(ParameterTypeNameStyle.check(&ctx).is_empty());
}
}
@@ -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());
}
}
@@ -0,0 +1,193 @@
//! `port-name-suffix` — a port's name says which way it points.
use crate::context::LintContext;
use crate::module_decls::module_signals;
use crate::naming::is_escaped;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
/// See [`Rule::doc`].
pub struct PortNameSuffix;
const NAME: &str = "port-name-suffix";
/// The six suffixes Verible knows, and the direction each one claims.
const KNOWN: [(&str, &str); 6] = [
("_i", "input"),
("_ni", "input"),
("_o", "output"),
("_no", "output"),
("_io", "inout"),
("_nio", "inout"),
];
impl Rule for PortNameSuffix {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"end a port's name with the suffix for its direction"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"At an instantiation, `.data(data)` says nothing about which way the \
signal flows; `.data_i(data_o)` says it at a glance, and a mistake in \
a connection list becomes visible without opening the module. The \
lowRISC style guide asks for it and Verible's `port-name-suffix` \
checks it: `_i` / `_ni` for an input, `_o` / `_no` for an output, \
`_io` / `_nio` for an `inout`, where the `n` marks an active-low \
signal. Both ship it **off** — a codebase that did not start with the \
convention cannot adopt it one port at a time — and lucisv does too.\n\n\
The `suffixes` option is the list of accepted endings. A suffix in it \
that is one of the six known ones is accepted **only for its own \
direction**, so shortening the list to `[\"_i\", \"_o\"]` bans the \
active-low spellings without letting an input end in `_o`; any other \
suffix a project adds is accepted for every direction, since only the \
project knows what it means. A port whose direction the header does \
not state — a non-ANSI name, declared in the body — is judged where \
the body declares it. Escaped identifiers are exempt, and there is no \
fix: renaming a port reaches every instantiation."
}
fn default_on(&self) -> bool {
false
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "suffixes",
kind: OptionKind::List,
default: OptionDefault::List(&["_i", "_ni", "_o", "_no", "_io", "_nio"]),
doc: "the endings a port name may have",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let configured = ctx.option_list(NAME, "suffixes");
let mut out = Vec::new();
for port in module_signals(ctx.file()) {
let (Some(dir), "port") = (port.dir.as_deref(), port.what) else { continue };
if is_escaped(&port.name) {
continue;
}
let allowed = allowed_for(&configured, dir);
if allowed.is_empty() || allowed.iter().any(|s| port.name.ends_with(s.as_str())) {
continue;
}
out.push(Violation::new(
NAME,
format!("{dir} port `{}` does not end in {}", port.name, or_list(&allowed)),
port.span,
));
}
out
}
}
/// The configured suffixes this direction may use: a known suffix only where
/// it belongs, and anything the project added everywhere.
fn allowed_for(configured: &[String], dir: &str) -> Vec<String> {
configured
.iter()
.filter(|suffix| {
KNOWN.iter().find(|(known, _)| known == suffix).is_none_or(|(_, wants)| *wants == dir)
})
.cloned()
.collect()
}
/// "`_i` or `_ni`" — the list as a sentence.
fn or_list(suffixes: &[String]) -> String {
let quoted: Vec<String> = suffixes.iter().map(|s| format!("`{s}`")).collect();
match quoted.split_last() {
Some((last, [])) => last.clone(),
Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
None => String::new(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
PortNameSuffix.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_port_with_no_suffix_and_names_what_it_wanted() {
let src = "module m (input logic clk, output logic data);\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 2, "{found:?}");
assert!(found[0].message.contains("input port `clk`"), "{}", found[0].message);
assert!(found[0].message.contains("`_i` or `_ni`"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "clk");
assert!(found[0].fix.is_none());
}
#[test]
fn the_convention_is_clean() {
let src = "module m (input logic clk_i, input logic rst_ni, output logic data_o,\n\
\x20 output logic ack_no, inout wire sda_io, inout wire scl_nio);\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_suffix_for_the_wrong_direction_is_still_wrong() {
let src = "module m (input logic data_o);\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("input port `data_o`"), "{}", found[0].message);
}
#[test]
fn a_body_declared_port_is_judged_where_its_direction_is() {
// The non-ANSI header only lists the name; the body declaration is
// the one that carries the direction, and the one reported.
let src = "module m (clk);\n input clk;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(found[0].span.start as usize, src.rfind("clk").unwrap_or(0));
}
#[test]
fn a_signal_is_not_a_port() {
assert!(violations("module m;\n logic internal;\nendmodule\n").is_empty());
}
#[test]
fn shortening_the_list_bans_the_active_low_spellings() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "suffixes", "[\"_i\", \"_o\"]").expect("accepted");
let src = "module m (input logic rst_ni, input logic clk_i, output logic data_o);\n\
endmodule\n";
let ctx = LintContext::new(src, None).with_options(&options);
let found = PortNameSuffix.check(&ctx);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("rst_ni"), "{}", found[0].message);
assert!(found[0].message.contains("does not end in `_i`"), "{}", found[0].message);
}
#[test]
fn a_project_specific_suffix_is_accepted_in_every_direction() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "suffixes", "[\"_pin\"]").expect("accepted");
let src = "module m (input logic clk_pin, output logic data_pin);\nendmodule\n";
let ctx = LintContext::new(src, None).with_options(&options);
assert!(PortNameSuffix.check(&ctx).is_empty());
}
#[test]
fn it_is_off_by_default() {
assert!(!PortNameSuffix.default_on());
}
}
+100
View File
@@ -0,0 +1,100 @@
//! `posix-eof` — a file ends with a newline.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct PosixEof;
const NAME: &str = "posix-eof";
impl Rule for PosixEof {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"end the file with a newline"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"POSIX defines a line as ending in a newline, so a file whose last line \
has none has, formally, no last line: `cat` runs the next file into it, \
`wc -l` counts one line short, and every diff of a later edit shows the \
final line twice — once removed, once added with the newline. Verible's \
`posix-eof` (enabled by default) asks for the newline and so does \
lucisv's formatter, which always writes one. The fix appends it, which \
cannot change what the code means. An empty file has no last line to \
terminate and is left alone."
}
fn fix(&self) -> Option<Applicability> {
Some(Applicability::Safe)
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let source = ctx.source();
if source.is_empty() || source.ends_with('\n') {
return Vec::new();
}
let end = source.len() as u32;
// The diagnostic points at the last character, which is where an
// editor's cursor lands; the fix appends past it.
let last = source.chars().next_back().map_or(end, |c| end - c.len_utf8() as u32);
vec![Violation::new(NAME, "file does not end with a newline", TextRange::new(last, end))
.with_fix(Fix::safe(vec![(TextRange::new(end, end), "\n".to_string())]))]
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::violation::apply_fixes;
fn violations(src: &str) -> Vec<Violation> {
PosixEof.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_missing_newline_and_appends_one() {
let src = "module m;\nendmodule";
let found = violations(src);
assert_eq!(found.len(), 1);
let fixed = apply_fixes(src, &found, false);
assert_eq!(fixed.output, "module m;\nendmodule\n");
assert!(violations(&fixed.output).is_empty());
}
#[test]
fn a_terminated_file_is_clean() {
assert!(violations("module m;\nendmodule\n").is_empty());
assert!(violations("\n").is_empty());
}
#[test]
fn an_empty_file_has_no_last_line() {
assert!(violations("").is_empty());
}
#[test]
fn it_points_at_the_last_character() {
let src = "module m;\nendmodule";
let found = violations(src);
assert_eq!(&src[found[0].span.as_range()], "e");
}
#[test]
fn a_multibyte_last_character_is_not_split() {
let src = "// naïve";
let found = violations(src);
assert_eq!(&src[found[0].span.as_range()], "e");
assert_eq!(apply_fixes(src, &found, false).output, "// naïve\n");
}
}
@@ -0,0 +1,151 @@
//! `signal-name-style` — nets, variables and ports are `lower_snake_case`.
use crate::context::LintContext;
use crate::module_decls::module_signals;
use crate::naming::{fits_pattern, is_escaped, style_message};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
/// See [`Rule::doc`].
pub struct SignalNameStyle;
const NAME: &str = "signal-name-style";
impl Rule for SignalNameStyle {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name signals in lower_snake_case"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A signal name is read in a waveform viewer next to a hundred others, \
and a codebase that mixes `dataValid`, `DATA_VALID` and `data_valid` \
makes every one of those a separate grep. Verible's \
`signal-name-style` spells the convention as `[a-z_0-9]+` and ships it \
**off**; lucisv keeps it off for the same reason \
`parameter-name-style` keeps its union of presets — a naming rule \
switched on for an existing codebase reports thousands of findings on \
its first run, and that is a project's decision to make.\n\n\
It judges the nets, variables and ports declared **inside a module, \
interface or program**: the ANSI ports of the header, the non-ANSI \
`input`/`output` declarations of the body, and the `wire`/`logic`/`reg` \
declarations beside them. A class property is not a signal and is left \
alone; a `parameter` is `parameter-name-style`'s, and a `genvar` names \
a loop, not a wire. Escaped identifiers are exempt, and there is no \
fix: renaming a signal reaches every use, including uses in other \
files."
}
fn default_on(&self) -> bool {
false
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str("[a-z_0-9]+"),
doc: "the pattern a signal's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
for signal in module_signals(ctx.file()) {
if is_escaped(&signal.name) || fits_pattern(ctx, NAME, "style_regex", &signal.name) {
continue;
}
out.push(Violation::new(
NAME,
style_message(
ctx,
NAME,
"style_regex",
&format!("{} `{}`", signal.what, signal.name),
"is not lower_snake_case",
),
signal.span,
));
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
SignalNameStyle.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_camel_case_signal_and_names_what_it_is() {
let src = "module m;\n logic dataValid;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.starts_with("signal `dataValid`"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "dataValid");
assert!(found[0].fix.is_none());
}
#[test]
fn ports_of_both_header_styles_are_covered() {
let ansi = "module m (input logic clkIn, output wire dataOut);\nendmodule\n";
assert_eq!(violations(ansi).len(), 2, "{:?}", violations(ansi));
assert!(violations(ansi)[0].message.starts_with("port `clkIn`"));
let non_ansi = "module m (clkIn, dataOut);\n input clkIn;\n output dataOut;\nendmodule\n";
// Once each: the header lists the names, the body declares them, and
// the declaration is what is reported.
assert_eq!(violations(non_ansi).len(), 2, "{:?}", violations(non_ansi));
assert!(violations(non_ansi)[0].span.start as usize > non_ansi.find(");").unwrap_or(0));
}
#[test]
fn conventional_names_are_clean() {
let src = "module m (input logic clk_i, output wire data_o);\n logic [7:0] wr_ptr2;\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_signal_inside_a_generate_block_is_covered() {
let src = "module m;\n generate\n if (A) begin : g\n logic dataValid;\n\
\x20 end\n endgenerate\nendmodule\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn a_class_property_and_a_parameter_are_not_signals() {
assert!(violations("class c;\n logic dataValid;\nendclass\n").is_empty());
assert!(violations("module m;\n parameter int AddrWidth = 1;\nendmodule\n").is_empty());
assert!(violations("module m;\n genvar iGen;\nendmodule\n").is_empty());
}
#[test]
fn a_configured_pattern_replaces_the_default() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "style_regex", "\"[a-z][a-zA-Z0-9]*\"").expect("accepted");
let ctx = LintContext::new("module m;\n logic dataValid;\nendmodule\n", None)
.with_options(&options);
assert!(SignalNameStyle.check(&ctx).is_empty());
let ctx = LintContext::new("module m;\n logic data_valid;\nendmodule\n", None)
.with_options(&options);
assert_eq!(SignalNameStyle.check(&ctx).len(), 1);
}
#[test]
fn it_is_off_by_default() {
assert!(!SignalNameStyle.default_on());
}
}
@@ -2,8 +2,10 @@
//! `lower_snake_case` ending `_t`.
use crate::context::LintContext;
use crate::naming::{is_escaped, is_lower_snake_case};
use crate::naming::{fits_pattern, is_escaped, style_message};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
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 +24,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 \
@@ -31,7 +37,20 @@ impl Rule for StructUnionNameStyle {
a `typedef struct` / `typedef union` is judged — an anonymous struct \
has no name, and requiring it to have one is Verible's separate \
`typedef-structs-unions` idea. Escaped identifiers are exempt, and \
there is no fix: a type rename reaches every use."
there is no fix: a type rename reaches every use.\n\n\
The shape is the `style_regex` option, whose default \
`[a-z][a-z_0-9]*_t` is Verible's pattern with the first character \
pinned to a letter — the preset lucisv checked before the option \
existed."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str("[a-z][a-z_0-9]*_t"),
doc: "the pattern a struct or union typedef's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
@@ -40,12 +59,18 @@ impl Rule for StructUnionNameStyle {
let ItemKind::Typedef(typedef) = &item.kind else { return };
let TypedefKind::Struct(structure) = &typedef.kind else { return };
let name = &typedef.name;
if is_escaped(name) || (is_lower_snake_case(name) && name.ends_with("_t")) {
if is_escaped(name) || fits_pattern(ctx, NAME, "style_regex", name) {
return;
}
out.push(Violation::new(
NAME,
format!("{} `{name}` is not lower_snake_case ending in `_t`", structure.kw),
style_message(
ctx,
NAME,
"style_regex",
&format!("{} `{name}`", structure.kw),
"is not lower_snake_case ending in `_t`",
),
typedef.name_span,
));
});
@@ -96,6 +121,30 @@ mod tests {
assert!(violations(src).is_empty());
}
#[test]
fn the_default_pattern_is_the_preset_it_replaced() {
for bad in ["_addr_t", "AddrT", "addr"] {
assert_eq!(violations(&typedef("struct", bad)).len(), 1, "{bad}");
}
for good in ["addr_t", "a_t", "word2_t"] {
assert!(violations(&typedef("struct", good)).is_empty(), "{good}");
}
}
#[test]
fn a_configured_pattern_replaces_it() {
let mut options = crate::options::RuleOptions::new();
options.set_raw(NAME, "style_regex", "\"[a-z_0-9]+_s\"").expect("accepted");
let src = typedef("struct", "addr_s");
let ctx = LintContext::new(&src, None).with_options(&options);
assert!(StructUnionNameStyle.check(&ctx).is_empty());
let src = typedef("struct", "addr_t");
let ctx = LintContext::new(&src, None).with_options(&options);
let found = StructUnionNameStyle.check(&ctx);
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("[a-z_0-9]+_s"), "{}", found[0].message);
}
#[test]
fn a_struct_typedef_inside_a_class_body_is_covered() {
let src = "class c;\n typedef struct packed { logic a; } addr;\nendclass\n";
@@ -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,106 @@
//! `typedef-enums` — an `enum` type is declared with a `typedef`.
use crate::context::LintContext;
use crate::decls::walk_declared_types;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::ast::TypeExtra;
/// See [`Rule::doc`].
pub struct TypedefEnums;
const NAME: &str = "typedef-enums";
impl Rule for TypedefEnums {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"give an enum type a name with `typedef`"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"An anonymous `enum logic [1:0] {IDLE, BUSY} state;` gives the enum no \
name, and the language gives no way to write one afterwards: a \
function cannot take the type, a port cannot carry it, a cast cannot \
name it, and a second variable of the same states has to repeat the \
whole list — where the two copies are *different* types to the \
compiler. Verible's `typedef-enums` (enabled by default) asks for the \
`typedef`, and lucisv checks the same shape.\n\n\
Every declaration is judged: a variable, a port, a struct member. \
There is no fix — where the `typedef` should go (this file, the \
package next to it) is a design decision, not a rewrite."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_declared_types(ctx.file(), &mut |declared| {
if !matches!(declared.ty.inline(), Some(TypeExtra::Enum(_))) {
return;
}
out.push(Violation::new(
NAME,
format!(
"`{}` is declared with an anonymous enum; name it with `typedef`",
declared.name
),
declared.span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
TypedefEnums.check(&LintContext::new(src, None))
}
#[test]
fn flags_an_anonymous_enum_variable_and_points_at_the_name() {
let src = "module m;\n enum logic [1:0] { IDLE, BUSY } state;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "state");
assert!(found[0].fix.is_none());
}
#[test]
fn a_typedef_enum_is_the_shape_it_asks_for() {
let src = "package p;\n typedef enum logic [1:0] { IDLE, BUSY } state_e;\nendpackage\n\
module m;\n state_e state;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_port_and_a_struct_member_are_covered() {
let src = "module m (input enum logic { A, B } mode);\nendmodule\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
let src = "package p;\n typedef struct packed {\n\
\x20 enum logic { A, B } inner;\n } outer_t;\nendpackage\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn a_variable_declared_in_a_procedure_is_covered() {
let src = "module m;\n initial begin\n enum logic { A, B } local_state;\n end\n\
endmodule\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn an_ordinary_declaration_is_none_of_its_business() {
assert!(violations("module m;\n logic [1:0] state;\nendmodule\n").is_empty());
let src = "module m;\n struct packed { logic a; } s;\nendmodule\n";
assert!(violations(src).is_empty(), "structs are the other rule's");
}
}
@@ -0,0 +1,144 @@
//! `typedef-structs-unions` — a `struct`/`union` type is declared with a
//! `typedef`.
use crate::context::LintContext;
use crate::decls::walk_declared_types;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::ast::TypeExtra;
/// See [`Rule::doc`].
pub struct TypedefStructsUnions;
const NAME: &str = "typedef-structs-unions";
impl Rule for TypedefStructsUnions {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"give a struct or union type a name with `typedef`"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"An anonymous `struct packed { … } s;` cannot be passed to a function, \
returned from one, carried on a port or written in a cast, and a \
second variable declared with the same member list is a *different* \
type to the compiler — so the layout ends up copied, and the copies \
drift. Verible's `typedef-structs-unions` (enabled by default) asks \
for the `typedef`, and lucisv checks the same shape on every \
declaration: a variable, a port, a member.\n\n\
The `allow_anonymous_nested` option exempts an anonymous aggregate \
written **inside** another aggregate's body, where it has a name — its \
member's — and cannot be referred to from outside anyway. Verible \
defaults its equivalent (`allow_anonymous_nested_type`) to false; \
lucisv defaults it to **true**, a deliberate divergence: on opentitan \
every one of the rule's 3 159 findings was a nested struct inside a \
`typedef` in a generated register package, and opentitan's own \
Verible config disables the whole rule for that reason. Set the \
option to false for Verible's stricter reading. There is no fix: \
where the `typedef` belongs is a design decision."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "allow_anonymous_nested",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "accept an anonymous struct or union written inside another one (lucisv's default; Verible's is false)",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let allow_nested = ctx.option_bool(NAME, "allow_anonymous_nested");
let mut out = Vec::new();
walk_declared_types(ctx.file(), &mut |declared| {
let Some(TypeExtra::Struct(structure)) = declared.ty.inline() else { return };
if declared.nested && allow_nested {
return;
}
out.push(Violation::new(
NAME,
format!(
"`{}` is declared with an anonymous {}; name it with `typedef`",
declared.name, structure.kw
),
declared.span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
TypedefStructsUnions.check(&LintContext::new(src, None))
}
#[test]
fn flags_an_anonymous_struct_and_points_at_the_name() {
let src = "module m;\n struct packed { logic a; } s;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("anonymous struct"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "s");
assert!(found[0].fix.is_none());
}
#[test]
fn a_union_is_named_in_the_message() {
let src = "module m;\n union packed { logic a; logic b; } u;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("anonymous union"), "{}", found[0].message);
}
#[test]
fn a_typedef_struct_is_the_shape_it_asks_for() {
let src = "package p;\n typedef struct packed { logic a; } word_t;\nendpackage\n\
module m;\n word_t w;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_nested_anonymous_struct_is_allowed_by_default_and_reported_when_asked() {
// lucisv's default is `allow_anonymous_nested = true` (the doc says
// why); Verible's stricter reading is one option away.
let src = "package p;\n typedef struct packed {\n\
\x20 struct packed { logic x; } inner;\n } outer_t;\nendpackage\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
let mut options = RuleOptions::new();
options.set_raw(NAME, "allow_anonymous_nested", "false").expect("accepted");
let ctx = LintContext::new(src, None).with_options(&options);
let found = TypedefStructsUnions.check(&ctx);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "inner");
}
#[test]
fn allowing_nested_ones_does_not_allow_a_top_level_one() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "allow_anonymous_nested", "true").expect("accepted");
let src = "module m;\n struct packed { logic a; } s;\nendmodule\n";
let ctx = LintContext::new(src, None).with_options(&options);
assert_eq!(TypedefStructsUnions.check(&ctx).len(), 1);
}
#[test]
fn an_anonymous_enum_is_the_other_rules_business() {
let src = "module m;\n enum logic { A, B } e;\nendmodule\n";
assert!(violations(src).is_empty());
}
}
@@ -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,146 @@
//! `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;
use vlog_parser::ast::ListElem;
/// 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.iter().filter_map(ListElem::ok) {
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,170 @@
//! `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;
use vlog_parser::ast::ListElem;
/// 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.iter().filter_map(ListElem::ok) {
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);
}
}
+16 -2
View File
@@ -18,7 +18,7 @@ use std::collections::{HashMap, HashSet};
use vlog_parser::ast::{
ClockingItemKind, Connections, Expr, ExprKind, ForStep, GenElse, Instantiation, Item, ItemKind,
SourceFile, Stmt, StmtKind,
ListElem, SourceFile, Stmt, StmtKind,
};
use vlog_parser::span::TextRange;
use vlog_parser::token::TokenKind;
@@ -483,11 +483,25 @@ impl Scanner {
match &instance.conns {
Connections::Ordered(conns) => {
for conn in conns {
self.unknown.push(conn.span);
// An error element is text a tolerant parse could not
// read; whatever signals it mentions are unknown, so
// its span joins the same opaque bucket.
match conn {
ListElem::Ok(conn) => self.unknown.push(conn.span),
ListElem::Error(raw) => self.unknown.push(raw.span),
}
}
}
Connections::Named(conns) => {
for conn in conns {
let conn = match conn {
ListElem::Ok(conn) => conn,
// Opaque, as above.
ListElem::Error(raw) => {
self.unknown.push(raw.span);
continue;
}
};
match (conn.name.as_str(), &conn.expr) {
// `.*` connects every same-named signal without
// writing any of their names down.
+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.
+47 -2
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, ListElem, ParamPort, SourceFile,
Stmt, StmtKind,
};
/// Calls `f` on every item in the file, nested items included.
@@ -141,6 +142,37 @@ fn stmts(list: &[Stmt], f: &mut dyn FnMut(&Stmt)) {
}
}
/// Calls `f` on every generate block of the file — the `begin … end` (or the
/// single item standing for one) of an `if`, `for` or `case` generate,
/// nested blocks included.
pub(crate) fn walk_generate_blocks(file: &SourceFile, f: &mut dyn FnMut(&GenBlock)) {
walk_items(file, &mut |item| match &item.kind {
ItemKind::GenIf(gen_if) => {
f(&gen_if.then);
let mut els = gen_if.els.as_deref();
while let Some(branch) = els {
match branch {
GenElse::If(_, nested) => {
f(&nested.then);
els = nested.els.as_deref();
}
GenElse::Block(block) => {
f(block);
els = None;
}
}
}
}
ItemKind::GenFor(gen_for) => f(&gen_for.body),
ItemKind::GenCase(gen_case) => {
for case_item in &gen_case.items {
f(&case_item.body);
}
}
_ => {}
});
}
/// Calls `f` on every `#( ... )` parameter port of the file — a module header's
/// and a class header's alike, since both spell them with the same node.
pub(crate) fn walk_param_ports(file: &SourceFile, f: &mut dyn FnMut(&ParamPort)) {
@@ -150,12 +182,25 @@ pub(crate) fn walk_param_ports(file: &SourceFile, f: &mut dyn FnMut(&ParamPort))
ItemKind::Class(class) => &class.param_ports,
_ => return,
};
for port in ports.iter().flatten() {
// An error element is a parameter a tolerant parse could not read: it
// has no name and no type, so there is nothing for a rule to judge.
for port in ports.iter().flatten().filter_map(ListElem::ok) {
f(port);
}
});
}
/// 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::*;
+230
View File
@@ -0,0 +1,230 @@
//! 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}{options}",
severity = rule.severity().as_str(),
summary = rule.summary(),
default = default_sentence(rule),
options = options_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),
)
}
/// The options a rule takes, named in its description.
///
/// No setting is generated *per option* — `lucisv.lint.options` is one object
/// that carries them all, and 60 more entries in the Settings UI would bury
/// the toggles this file exists to produce. What the description owes the
/// reader is the words to type into that object, which is this.
fn options_sentence(rule: &dyn Rule) -> String {
let names: Vec<String> = rule.options().iter().map(|spec| format!("`{}`", spec.name)).collect();
match names.len() {
0 => String::new(),
_ => format!(" Options (set them in `#lucisv.lint.options#`): {}.", names.join(", ")),
}
}
/// 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);
}
/// A rule with options says so, and names them; a rule without says
/// nothing extra.
#[test]
fn a_rules_description_names_the_options_it_takes() {
let json = vscode_lint_settings();
assert!(
json.contains("Options (set them in `#lucisv.lint.options#`): `length`."),
"line-length's option"
);
assert!(
json.contains(
"`localparam_style`, `localparam_style_regex`, `parameter_style`, \
`parameter_style_regex`."
),
"parameter-name-style's four"
);
for rule in all_rules() {
let has = !rule.options().is_empty();
let entry = json
.split(&format!("\"{}\"", rule_setting(rule)))
.nth(1)
.and_then(|rest| rest.split("},").next())
.unwrap_or_default();
assert_eq!(entry.contains("Options (set them in"), has, "{}", rule.name());
}
}
#[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");
}
}
@@ -0,0 +1,10 @@
#select always-comb
# both spellings of the implicit sensitivity list
module m;
always @(*) x = 1;
//^ 3 always-comb
always @* y = 2;
//^ 3 always-comb
always @(a or b) z = 3;
always_comb w = 4;
endmodule
Loaded 100 of 169 files, more files were not shown because too many files have changed in this diff. Show more