Compare commits

...
13 Commits
Author SHA1 Message Date
lucioandClaude Fable 5.1 797ef86d47 Release 0.40.0 — two parser residues and atomic writes
release / build-and-publish (push) Successful in 6m11s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-04 17:08:53 -05:00
lucioandClaude Fable 5.1 a30dda167a Small items, round 3: a bare begin block recovered as a generate block, the half-typed #( override lookahead, atomic in-place writes
TODO §36 (docs/features/small-items-3). Closes topo §2.9-24 and §2.9-25
and the §1 atomic-writes item.

36.1 `ItemKind::GenBlock(Box<GenBlock>)`: in tolerant mode a `begin … end`
at module scope or straight inside a generate region is parsed as an
unnamed generate block with a diagnostic at the keyword, so the items
inside and after it survive; strict mode is untouched. Consumers walk
its items; `module-begin-block`, `v2001-generate-begin` and
`mismatched-labels` read the node. The formatter's `gen_block` is split
by a pure extraction into `begin_block`. One server test that parsed a
3 000-deep begin nest on libtest's thread now runs on PARSE_STACK_SIZE.

36.2 `Parser::value_runs_into_next_instance`, a tolerant-mode lookahead
in `parse_connection`: an unclosed `.NAME(` whose value would swallow
the next instance as a call fails the element instead; `recover_element`
takes the bracket the element stopped on before skipping so the skip
stays at the list's level. The balanced-parens spelling stays greedy.

36.3 `lucisv_core::atomic::write_atomic`: sibling temp file + rename,
permissions preserved, symlink target replaced, read-only target
refused as `fs::write` refused it; used by format, `check --fix` and
the cache.

Also: TODO housekeeping (QA lines of §27–§35 ticked as recorded in
their QA logs; the §27 P6 line and the sva-bodies README checkbox
annotated as delivered by §29), topo §2.9-24/25 struck.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-04 17:08:53 -05:00
lucioandClaude Fable 5 0757503fd1 Release 0.39.0 — the rest of Verible's rules (73 in all)
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 30s
release / build-and-publish (push) Successful in 6m18s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 05:03:37 -05:00
lucio 6a0af26fdf Merge branch 'lint-3' 2026-09-04 04:56:52 -05:00
lucioandClaude Fable 5 8adb6c8ac1 Linter expansion, wave 3: the remaining nineteen Verible rules, forbidden-macro, void-cast's forbidden calls, and the e2e options case
TODO section 35 (54 -> 73 rules: every rule in Verible's published
list but forbid-implicit-declarations).
module-begin-block, legacy-generate-region, legacy-genvar-declaration,
v2001-generate-begin, explicit-function-lifetime,
explicit-task-lifetime (both exempt out-of-body definitions after a
census showed 948 of 960 findings were exactly that shape),
positive-meaning-parameter-name, suggest-parentheses (safe fix,
truth-tabled), unpacked-dimensions-range-ordering, uvm-macro-semicolon,
create-object-name-match, numeric-format-string-style,
macro-string-concatenation, disable-statement, forbidden-macro,
endif-comment (safe fix), forbid-line-continuations, dff-name-style,
proper-parameter-declaration. Verible's forbidden-symbol is the
source-file name of invalid-system-task-function (read in its
rule .cc), so it is that rule's symbols option, nothing fires twice;
void-cast gains forbidden_calls. Shared readers: walk_items_scoped,
exprs.rs, preproc.rs. A checked-in e2e case drives lucisv.lint.options
over the wire. Two rules fire on an error leaf because the parser
refuses a module-scope begin/end and a bare generate begin - filed as
docs/topo.md 2.9-25.
3 695 tests / 48 binaries; corpus 814/820 byte-identical to 0.38.0;
opentitan default-set census 1 053 -> 1 169, the arithmetic balancing
to the six default-on additions; timing unchanged.

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

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 04:55:10 -05:00
lucioandClaude Fable 5 fbee290a0a docs: topo — linter-expansion-1/2/3 rows; §2.9-25 filed (module-scope begin/end and bare generate begin refused rather than recovered)
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 32s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 04:31:36 -05:00
lucioandClaude Fable 5 b1b3cad09b TODO §35 planned: linter expansion wave 3 — the remaining twenty Verible rules, forbidden-* lists, the e2e options case
ci / checks (push) Successful in 56s
ci / corpus (push) Successful in 29s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:46:55 -05:00
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
124 changed files with 14183 additions and 257 deletions

No files matched your search

+79
View File
@@ -4,6 +4,85 @@ 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.40.0 — 2026-09-04
### Two parser residues and atomic writes
- **A bare `begin … end` at module scope, or straight inside
`generate … endgenerate`, is recovered** in error-tolerant mode as an
unnamed generate block (`ItemKind::GenBlock`) with a diagnostic at the
keyword, instead of being refused and taking the rest of the unit with
it. The items inside and after the block are now visible to the
editor and to every lint rule; `module-begin-block`,
`v2001-generate-begin` and `mismatched-labels` read the node. Strict
parsing is unchanged, so the formatter still refuses the file exactly
as before.
- **A half-typed `#(` override or connection whose value would read as
the next instance** (`sub #(.W(8), .DEPTH(` ⏎ `u0 (.a(x));`) now costs
one error element: `.W(8)` survives, `u0` is an instance with its
connections, one diagnostic on the unclosed `(`. The balanced-parens
spelling stays ambiguous and is still parsed greedily, by design.
- **In-place writes are atomic.** `lucisv format`, `lucisv check --fix`
and the cache write a sibling temp file and rename it over the target,
so a crash or a full disk never leaves a source file truncated. The
target's permissions are kept, a symlink's *target* is what gets
replaced, and a read-only file is refused as it always was.
## 0.39.0 — 2026-09-04
### The rest of Verible's rules
Nineteen more rules bring lucisv to **73** — every rule in Verible's
published list except the one that needs a compiler. New: `module-begin-
block`, `legacy-generate-region`, `legacy-genvar-declaration`,
`v2001-generate-begin`, `explicit-function-lifetime`,
`explicit-task-lifetime`, `positive-meaning-parameter-name`,
`suggest-parentheses` (safe fix), `unpacked-dimensions-range-ordering`,
`uvm-macro-semicolon`, `create-object-name-match`,
`numeric-format-string-style`, `macro-string-concatenation`,
`disable-statement`, `forbidden-macro` (`macros` option),
`endif-comment` (safe fix), `forbid-line-continuations`,
`dff-name-style`, `proper-parameter-declaration`.
`invalid-system-task-function` gains a `symbols` option (Verible's
"forbidden-symbol" is the same rule); `void-cast` gains
`forbidden_calls`. The two lifetime rules deliberately exempt an
out-of-body method definition (`function cls::f()`), which is where
almost every finding on a UVM tree would otherwise land. Each rule's
documentation cites the Verible rule and default it follows.
## 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
Generated
+8 -8
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.37.0"
version = "0.40.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.37.0"
version = "0.40.0"
[[package]]
name = "lucisv_server"
version = "0.37.0"
version = "0.40.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.37.0"
version = "0.40.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.37.0"
version = "0.40.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -264,11 +264,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.37.0"
version = "0.40.0"
[[package]]
name = "vlog_refactor"
version = "0.37.0"
version = "0.40.0"
dependencies = [
"vlog_parser",
"vlog_semantic",
@@ -276,7 +276,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.37.0"
version = "0.40.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.37.0"
version = "0.40.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+105 -2
View File
@@ -242,6 +242,11 @@ makes an editor's red squiggle worth believing.
| `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 |
| `create-object-name-match` | warning | — | `type_id::create("x")` names the handle `x` |
| `forbidden-macro` | warning | — | no macro on the project's forbidden list |
| `uvm-macro-semicolon` | warning | — | no `;` after a `` `uvm_* `` macro (off by default) |
| `macro-string-concatenation` | warning | — | no `` `` `` inside a plain string (off by default) |
| `disable-statement` | warning | — | `disable fork`, not a fork label (off by default) |
| `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 |
@@ -251,7 +256,39 @@ makes an editor's red squiggle worth believing.
| `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 |
| `explicit-function-lifetime` | style | — | `automatic`/`static` on a function outside a class |
| `explicit-task-lifetime` | style | — | `automatic`/`static` on a task outside a class |
| `positive-meaning-parameter-name` | style | — | no `disable`-prefixed parameter name |
| `suggest-parentheses` | style | safe | `a ? (b ? c : d) : e`, parenthesized |
| `unpacked-dimensions-range-ordering` | style | — | an unpacked dimension is `[0:N-1]` |
| `module-begin-block` | style | — | no `begin`/`end` at module scope |
| `v2001-generate-begin` | style | — | no bare `begin` in a generate region |
| `forbid-line-continuations` | style | — | no `\` breaking a string literal |
| `legacy-generate-region` | style | — | no `generate … endgenerate` wrapper (off) |
| `legacy-genvar-declaration` | style | — | a genvar is declared in the `for` header (off) |
| `endif-comment` | style | safe | `` `endif `` names what it closes (off by default) |
| `numeric-format-string-style` | style | — | a radix prefix matches its specifier (off) |
| `proper-parameter-declaration` | style | — | `parameter` in a header, `localparam` in a body (off) |
| `dff-name-style` | style | — | a flip-flop is `_q`, its input `_d` (off by default) |
† 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
@@ -266,11 +303,77 @@ 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
+236 -14
View File
@@ -2913,12 +2913,12 @@ collide); no parallel lane.
`undriven-net`, exactly as in `covergroup-bodies`.
- [x] P5 verbatim-SVA rename warning (pin: a fallback region spelling
the old name warns, never silent)
- [ ] P6 §2.9-18 wiring (pin: a file whose only relationship to the name
- [x] P6 §2.9-18 wiring (pin: a file whose only relationship to the name
is a macro argument still warns) — the **engine half is done and
pinned**; the server fan-out (`Workspace::rename_sources`,
outside the round's file list) is filed as Handshake request 1 in
`docs/features/sva-bodies/README.md`, with the unbounded-read-set
objection that makes it a lead's call rather than a mechanical wiring
objection that makes it a lead's call rather than a mechanical wiring. **Delivered by §29** (macro-word census, `unread_macro_warnings`).
- [x] P7 SVA gap fuzzer at zero (705 gaps, 0 failures); the 12 assertion
attack pairs kept plus 46 new ones; `verify.rs` untouched
- [x] Measurement: opentitan **79/79 declarations and 97/97 assertions**
@@ -2928,7 +2928,7 @@ collide); no parallel lane.
corpus 13 files moved and opentitan 36, all inside assertion text;
both sweeps otherwise byte-identical; the 4 854 `` `ASSERT* ``
invocations byte-identical
- [ ] QA on opentitan (read-only): structured counts re-derived; every
- [x] QA on opentitan (read-only): structured counts re-derived; every
moved file's diff read; rename of a signal used in
`hw/ip/*/rtl/*_assert*.sv` properties; sweep unchanged
@@ -3126,7 +3126,7 @@ edge).
store measurement +123 402 bytes (+3.11 %) on the corpus and
+743 873 (+1.66 %) on opentitan; opentitan `lucisv check` sweep
byte-identical, working tree untouched
- [ ] QA: rename of `clk` in an opentitan IP with the server, timing
- [x] QA: rename of `clk` in an opentitan IP with the server, timing
before/after (must not regress; the warning list must name only
files outside the source set), the pins re-derived
@@ -3223,7 +3223,7 @@ parallel with §29.
unchanged — 3 223/48 tests, 0 clippy warnings, 814/820 with the
same six failures, 0 diffs over 860 corpus and 3 947 opentitan
files
- [ ] QA: hand-written interface + DPI files in every listed shape,
- [x] QA: hand-written interface + DPI files in every listed shape,
idempotent, comments kept; the negative pin; sweep unchanged
## 31. Format fences at statement level and inside class bodies (planned 2026-09-02) — M9, §2.9-3
@@ -3329,7 +3329,7 @@ lead may start it in parallel if §30's files are settled).
3 234/0/42); corpus 814/820, 860 files byte-identical to the 0.34.0
binary; opentitan census 9 fenced files of 3 947 — 4 moved, each
keeping its own fenced bytes, `--check` counts unchanged
- [ ] QA: fences in every statement scope listed and in the three
- [x] QA: fences in every statement scope listed and in the three
deferred places (must be inert, never corrupt); an `off` with no
`on` in each scope (runs to the scope end only); nested fences;
`--lines` over a fenced statement; `--fix` still declines inside
@@ -3474,7 +3474,7 @@ formatter collide with §30's tf.rs/module.rs at merge; sequential).
- [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
- [x] QA: type each of the (a)–(f) shapes into the real server against
an opentitan file and read the published diagnostics and the
outline; the fuzzers re-run; strict-mode parity re-derived
@@ -3646,7 +3646,7 @@ linter-expansion-1/README.md (new), TODO §33. Worktree `lint-1`.
- [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
- [x] 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`)
@@ -3764,16 +3764,238 @@ 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`.
- [ ] 34.0 options end to end (spec, validation, toml table, editor
- [x] 34.0 options end to end (spec, validation, toml table, editor
object, precedence, --rules-doc); pins
- [ ] 34.1 options on the four existing naming rules; defaults
- [x] 34.1 options on the four existing naming rules; defaults
byte-identical
- [ ] 34.2 the eighteen Style rules, each with tests, counts and ten
- [x] 34.2 the eighteen Style rules, each with tests, counts and ten
classified findings
- [ ] 34.3 docs + regenerated toggles
- [ ] Gates (guarded): fmt/clippy/`cargo test --workspace`; corpus
- [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
- [x] QA: options attacked (bad key/kind/range/regex on both front
ends), every rule with near-misses, the census re-read
## 35. Linter expansion, wave 3 (planned 2026-09-04) — the remaining Verible rules
After §34 (54 rules, options end to end). The twenty Verible rules not
yet in lucisv, each a small file on the §33/§34 pattern (severity,
Verible name and default cited, options through `OptionSpec`, true
positives and near-misses, a `.lint` case, corpus + opentitan counts
with ten findings classified; every new gap between tokens a rule reads
is the parser's, not the rule's). Dev Opus 5, QA Sonnet 5, worktree
`lint-3`, every suite and sweep under `tools/guard.sh`. Feature README:
`docs/features/linter-expansion-3/README.md`.
Rules (Verible default → lucisv default; severity; options):
- `module-begin-block` (on → on; Style): a `begin`/`end` at module scope.
- `legacy-generate-region` (off → off; Style): `generate … endgenerate`.
- `legacy-genvar-declaration` (off → off; Style): a `genvar` declared
outside the `for` header.
- `v2001-generate-begin` (on → on; Style): a bare `begin` in a generate
region.
- `explicit-function-lifetime` / `explicit-task-lifetime` (on → on;
Style): `automatic`/`static` stated outside classes.
- `positive-meaning-parameter-name` (on → on; Style): no `disable_`
prefixed parameters.
- `suggest-parentheses` (on → on; Style): `a ? b : c` inside another
ternary or a mixed-precedence expression without parentheses (Verible's
shape, cited).
- `unpacked-dimensions-range-ordering` (on → on; Style): `[N-1:0]`
unpacked.
- `uvm-macro-semicolon` (off → off; Warning): `` `uvm_* `` macros ending
in `;`.
- `create-object-name-match` (on → on; Warning): `type_id::create("x")`
whose string differs from the variable.
- `numeric-format-string-style` (off → off; Style): `%d`/`%h` prefixes
in format strings.
- `macro-string-concatenation` (off → off; Warning): `` `"…`" `` misuse.
- `disable-statement` (off → off; Warning): `disable` outside a
`fork`/sequential block.
- `forbidden-macro` (on → on; Warning; option `macros` list, default
Verible's `uvm_warning`) and `forbidden-symbol` (on → on; Warning;
option `symbols` list, default `$psprintf`, `$random`, `$dist_*` per
Verible — folding `invalid-system-task-function`'s list into an
option if the two overlap; say which).
- `endif-comment` (off → off; Style; safe fix appends `// name`).
- `forbid-line-continuations` (on → on; Style): a `\` continuation
inside a string literal.
- `dff-name-style` (off → off; Style; options `input`, `output`,
`waive_ifs_with_conditions`, `waive_lhs_regex` as Verible).
- `proper-parameter-declaration` (off → off; Style; options
`package_allow_parameter`, `package_allow_localparam`).
- `void-cast`'s named-call half (Verible's forbidden-call list) as an
option on the existing rule.
Plus the LOW from §34's QA: a checked-in `tests/e2e.rs` case for
`lucisv.lint.options` over the wire. Docs: the toggles regenerated,
README.md rows, docs-site sections, coverage_gaps "linter" addendum.
- [x] the twenty rules, each with tests and counts
- [x] `void-cast` option; `forbidden-*` lists; `invalid-system-task-
function` reconciled
- [x] e2e case for `lucisv.lint.options`
- [x] docs + regenerated toggles
- [x] Gates (guarded): fmt/clippy/`cargo test --workspace`; corpus
814/820 byte-identical; vsix smoke; opentitan census + timing
- [x] QA: every rule attacked; census re-read; options attacked
## 36. Small items, round 3 (planned 2026-09-04) — topo §2.9-24, §2.9-25, atomic writes
One lane, in the main tree (owner's call: no worktree, no parallel lane; QA
reads the same tree). Dev: Opus 5. QA: Sonnet 5. Feature README:
`docs/features/small-items-3/README.md`. Ships as 0.40.0.
**File ownership** (the whole tree is free, but this is the expected touch
set — anything outside it is named in the work log):
`crates/vlog_parser/src/parser/{item.rs,instance.rs,recover_list.rs}`,
`crates/vlog_parser/src/ast/{mod.rs,module.rs}`,
`crates/vlog_parser/tests/error_recovery.rs`,
`crates/vlog_formatter/src/format/item.rs` (one arm),
`crates/vlog_linter/src/rules/{module_begin_block,v2001_generate_begin}.rs`
and every exhaustive `ItemKind` match the new variant reaches
(`vlog_semantic`, `vlog_refactor`, `lucisv_server`, `vlog_linter/visit.rs`),
`crates/lucisv_core/src/{atomic.rs (new),cache.rs,lib.rs}`,
`crates/lucisv/src/{main.rs,lint.rs}`, the two rules' rows in `README.md`
and `docs/site/src/content/docs/reference/rules.md`, `docs/topo.md` §2.9
(strike 24 and 25 — lead does this at review), this section.
### 36.1 A bare `begin … end` at module scope or in a generate region is recovered as a block (topo §2.9-25)
Today `parse_keyword_item` has no `begin` arm, so the item fails with
"expected item", `item_or_recover` skips to a sync point and the rest of the
unit is lost. Wanted: in **tolerant mode only**, the block is parsed and kept.
- New `ItemKind::GenBlock(Box<GenBlock>)` — the existing generate-block node
(`is_block: true`, label optional). No new node type.
- `parse_keyword_item`: a `"begin"` arm. Strict mode: the same "expected
item" error as today (byte-identity of every corpus file depends on the
strict parser refusing this; nothing about strict mode changes).
Tolerant mode: `self.record("`begin`/`end` block is not a module item")`
*at the `begin` keyword*, then `parse_gen_block()` and wrap it. The
diagnostic is not optional: the file must still be reported as not
parsing cleanly, so the formatter's "zero errors or nothing" contract
keeps refusing it exactly as before.
- Consumers, each the boring choice: the formatter prints it the way
`gen_block` prints an `if` arm's block (indent the items, `end`, the end
label if any) — it never reaches output today (a diagnostic is always
recorded) but the arm exists so a future range/tolerant printer has
nothing to invent; the semantic binder walks its items as one unnamed
generate block scope, the same scope shape an unlabeled `if` arm's block
gets (find how `GenIf` arms are bound and reuse that path — do not invent
a scope kind); `visit.rs`/outline/refactor walkers descend into
`items` and nothing else.
- The two rules stop reading an error leaf: `begin_block(item)` returns the
`begin` keyword's range (`span.start .. +5`) of an `ItemKind::GenBlock`
and `None` for everything else; delete `first_word_is_begin`. Doc strings
of both rules: replace the "parser rejects … rest of the module is lost"
paragraph with the truth (the parser recovers the block in tolerant mode
and records a diagnostic; the block's items are visible to every other
rule). Same paragraph in `README.md`'s rule rows and `rules.md`.
- Tests (in `tests/error_recovery.rs` and the two rules' modules):
`a_module_scope_begin_block_keeps_its_items_and_the_items_after_it`
(block with a `wire` inside, an `assign` after it, `endmodule` consumed,
exactly one diagnostic at `begin`); the generate-region twin; strict mode
still refuses both (an `Err`, not a node); an `end : label` on the block
round-trips into `end_label`; a nested `begin` inside the block recovers
the same way (two diagnostics, both blocks kept); the two rules each fire
once, at the keyword, and a *different* rule sees a violation written
inside the block (proof the items survive); the size pins in
`ast::size_pins` unchanged (the variant is boxed).
### 36.2 A half-typed `#(` override whose value could read as a call (topo §2.9-24)
Source (the QA finding in the header-recovery README, verbatim):
```
module m;
sub #(.WIDTH(8), .DEPTH(
u0 (.a(x), .b(y));
endmodule
```
The value of `.DEPTH(` is parsed greedily; `u0 (.a(x), .b(y))` is a legal
call with named arguments, so no error fires inside the list and the whole
instantiation collapses to an item-level `Error`. Wanted: the element
`.DEPTH(` is an error element, `.WIDTH(8)` survives, `u0` is an instance
with two connections, one diagnostic.
- One lookahead in `parse_connection`, tolerant mode only, before the value
is parsed (`parse_expr_or_type`): `fn value_runs_into_next_instance(&self)
-> bool`. Walk tokens from the cursor with a bracket depth starting at 0.
A closer that would take the depth below 0 is the value's own `)`: return
`false` — the value closes and is parsed normally. At depth 0, an
identifier that is the first token of its line and whose next token is
`(` is *remembered* as the candidate next instance. A `;` at depth 0, a
sync keyword (`endmodule`, `endinterface`, … — reuse the predicate
`at_sync_stop` is built on) or EOF ends the walk: return whether a
candidate was seen. That is: the value's `(` is never closed **and**
something that looks like the next instance sits inside it. On a valid
file the walk ends at the value's `)` after a handful of tokens, so cost
is nothing; only an unclosed value walks to the next `;`.
- When it returns `true`, fail the element with an error whose span is the
unclosed `(` (`paren_start`), message "unclosed `(` in a port or parameter
connection". `element_or_recover` turns it into the error element and the
existing skip (bracket-seeded, stops at the first token of a new line)
must leave the cursor on `u0`; `list_ends` then ends the override list
(recovered, no comma), `close_list` forgives the missing `)`, and the
instance loop reads `u0`. Verify that tree exactly; if the skip lands
elsewhere, fix the skip's start, not the lookahead.
- The same helper covers the connection list: `sub u0 (.a(` ⏎ `u1 (.b(y));`
costs one connection and keeps `u1` as a second instance.
- The ambiguous shape stays ambiguous: with the parens balancing
(`.D(` ⏎ `u0 (.a(x)));`) the value closes, the walk returns `false`, the
greedy parse wins — pin that as a test so nobody "fixes" it later.
- Tests: the README shape above (params `[Ok, Error]`, one instance, two
connections, one diagnostic at the `(`, `endmodule` consumed); the
connection-list twin; the balanced-parens control; a legal multi-line
value `.DEPTH(` ⏎ `f(1)` ⏎ `)` parses identically in strict and tolerant
mode (the parity test `tolerant_parse_equals_strict_parse_on_valid_sources`
plus a direct case); the header-recovery README's finding gets a work-log
line pointing here.
### 36.3 Atomic in-place writes (§1 backlog item, QA find of 2026-08-25)
`process_file` (`lucisv/src/main.rs`) and `--fix` (`lucisv/src/lint.rs`)
write with `fs::write`, which truncates then writes; `cache.rs` already does
tempfile + rename by hand. One shared helper, three users.
- `crates/lucisv_core/src/atomic.rs`: `pub fn write_atomic(path: &Path,
bytes: &[u8]) -> io::Result<()>`. Resolve symlinks first
(`fs::canonicalize` when the path exists — `fs::write` writes *through* a
symlink and a rename onto the link would replace it with a file; the
canonical target is what gets replaced). Temp file in the target's
directory, `.{file_name}.{pid}.lucisv-tmp`; write; copy the target's
permissions onto it when the target exists (`set_permissions`, so a
0600 or 0755 file stays that way); `rename` onto the target; on any
failure after the temp exists, remove it and return the error. No new
dependency.
- `cache.rs` uses the helper instead of its inline copy (behaviour
identical; its `no_temporary_file_is_left_behind` test keeps passing).
`main.rs:309` and `lint.rs:315` call it.
- Tests in `atomic.rs`: bytes land; no temp file left in the directory
after success; after a failed rename (target path is a directory) no
temp file is left and `Err` comes back; permissions preserved
(`#[cfg(unix)]`); writing through a symlink replaces the *target* and the
link still points at it; a new file (no prior target) is created.
### Gates (dev runs, all guarded)
`cargo fmt -p` per touched crate; `cargo clippy --all-targets` clean;
`tools/guard.sh -- cargo test --workspace`; `tools/guard.sh --
tools/corpus_check.sh` still 814/820 with the same six failures; the
`tests/error_recovery.rs` truncation and single-character-deletion fuzz
tests green (they are the termination guard for 36.1/36.2). Lead at review:
byte-identity of every corpus file against the cached 0.39.0 binary,
opentitan read-only sweep, vsix smoke, 0.40.0.
- [x] 36.1 `ItemKind::GenBlock`, the `begin` arm, consumers, the two rules
- [x] 36.2 the lookahead, the four tests
- [x] 36.3 `write_atomic`, three users, tests
- [x] docs: feature README, rule rows, header-recovery work-log line
- [x] Gates (guarded)
- [x] QA: every shape above typed against the tolerant parser and the two
rules; the ambiguous control; strict/tolerant parity re-run; the
truncation fuzzers re-run; atomic writes attacked (symlink, mode,
directory target, concurrent writers on one inode) — REWORK (small):
`mismatched-labels` had no arm for the block; fixed by the lead at
review with a test, plus the LOW doc comment and a read-only-target
refusal in `write_atomic` (parity with the old `fs::write`)
+54 -11
View File
@@ -9,12 +9,15 @@ use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use lucisv_core::atomic::write_atomic;
use lucisv_core::config::FileConfig;
use rayon::prelude::*;
use vlog_formatter::fence::{self, Region};
use vlog_formatter::Config;
use vlog_linter::words;
use vlog_linter::{apply_fixes, lint, Fix, MentionOracle, ParsedSource, Rule, Violation};
use vlog_linter::{
apply_fixes, lint, Fix, MentionOracle, ParsedSource, Rule, RuleOptions, Violation,
};
use vlog_parser::LineIndex;
use crate::args::{Options, OutputFormat};
@@ -31,6 +34,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
@@ -163,7 +169,8 @@ 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 interfaces = jobs.iter().any(|job| job.rules.iter().any(|rule| reads_interfaces(*rule)));
@@ -171,6 +178,30 @@ pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Res
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.
///
@@ -215,7 +246,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
@@ -231,10 +264,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}"));
@@ -248,6 +282,7 @@ fn check_one(
config: &Config,
opts: &Options,
rules: &[&'static dyn Rule],
options: &RuleOptions,
census: Option<&Census>,
) -> Report {
let path = file.display().to_string();
@@ -265,10 +300,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)
}
});
@@ -278,7 +313,7 @@ fn check_one(
};
let index = LineIndex::new(rewritten.as_deref().unwrap_or(&src));
if let Some(text) = rewritten {
if let Err(e) = std::fs::write(file, &text) {
if let Err(e) = write_atomic(file, text.as_bytes()) {
return failed(format!("{path}: {e}"));
}
}
@@ -299,6 +334,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
@@ -313,8 +349,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,
@@ -361,12 +402,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);
@@ -375,7 +417,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)
+17 -6
View File
@@ -27,6 +27,7 @@ use std::process::ExitCode;
use rayon::prelude::*;
use args::{Command, Options};
use lucisv_core::atomic::write_atomic;
use lucisv_core::cache::{content_hash, Cache, Entry};
use lucisv_core::config::{Discovery, FileConfig};
use lucisv_core::filelist;
@@ -98,7 +99,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 +121,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 +148,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}");
@@ -299,7 +307,7 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
FileResult::plain(Outcome::Changed(diff::unified(&name.to_string(), &src, &out)))
} else if opts.check {
FileResult::plain(Outcome::Changed(format!("would reformat: {name}\n")))
} else if let Err(e) = std::fs::write(file, &out) {
} else if let Err(e) = write_atomic(file, out.as_bytes()) {
FileResult::plain(Outcome::Failed(format!("{name}: {e}")))
} else {
// The bytes now on disk are formatted, so they are what the cache
@@ -421,13 +429,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) {
+72 -7
View File
@@ -1863,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
+202
View File
@@ -0,0 +1,202 @@
//! Replacing a file's contents without ever leaving it half written.
//!
//! `fs::write` truncates the target and then writes into it, so a crash, a
//! full disk or a `^C` between the two leaves the user's source truncated —
//! and lucisv's first invariant is that it never corrupts code. Every
//! in-place write goes through [`write_atomic`] instead: a sibling temp file
//! gets the bytes, and a `rename` over the target publishes them in one step
//! that either happened or did not.
//!
//! See `docs/features/small-items-3/README.md`.
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
/// Writes `bytes` to `path`, replacing whatever was there in one step.
///
/// A temp file beside the target takes the bytes, inherits the target's
/// permissions when there is a target, and is renamed onto it — `rename` is
/// atomic within a directory on every platform lucisv ships to, so a reader
/// sees either the old file or the new one and never a truncated one. A
/// failure anywhere after the temp exists removes it before returning.
///
/// A symlinked target is resolved first: `fs::write` writes *through* a
/// symlink, so replacing the link itself would silently redirect it at a new
/// file and leave the real one stale. The canonical path is what gets
/// replaced, which is also what makes the temp land on the target's own
/// filesystem — `rename` cannot cross one.
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
let target = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
// A rename replaces a file whatever its mode, so a read-only target would
// be silently overwritten where `fs::write` refuses it. Keep the refusal:
// a file someone made read-only is asking not to be rewritten in place.
if fs::metadata(&target).is_ok_and(|m| m.permissions().readonly()) {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("{} is read-only", path.display()),
));
}
let tmp = temp_path(&target)?;
if let Err(e) = fs::write(&tmp, bytes) {
let _ = fs::remove_file(&tmp);
return Err(e);
}
// A file someone made read-only, or executable, keeps its mode: the temp
// was created with the process umask, not with the target's bits. No
// target means a new file, which takes the umask as `fs::write` would.
if let Ok(meta) = fs::metadata(&target) {
let _ = fs::set_permissions(&tmp, meta.permissions());
}
if let Err(e) = fs::rename(&tmp, &target) {
let _ = fs::remove_file(&tmp);
return Err(e);
}
Ok(())
}
/// The temp file's path: hidden, in the target's own directory, and stamped
/// with the process id so two lucisv runs over one tree cannot collide.
fn temp_path(target: &Path) -> io::Result<PathBuf> {
let dir = target.parent().unwrap_or_else(|| Path::new("."));
let name = target
.file_name()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no file name to write"))?;
let mut tmp = std::ffi::OsString::from(".");
tmp.push(name);
tmp.push(format!(".{}.lucisv-tmp", std::process::id()));
Ok(dir.join(tmp))
}
#[cfg(test)]
mod tests {
use super::*;
/// A directory that removes itself, the way `cache.rs`'s own tests have
/// one — no dependency, and no leftovers under `target/`.
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(tag: &str) -> Self {
let path = std::env::temp_dir().join(format!(
"lucisv-atomic-{tag}-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("create temp dir");
TempDir { path }
}
fn file(&self, name: &str) -> PathBuf {
self.path.join(name)
}
/// Every name in the directory, so a test can say what is *not* there.
fn names(&self) -> Vec<String> {
let mut out: Vec<String> = fs::read_dir(&self.path)
.expect("read dir")
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect();
out.sort();
out
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
#[test]
fn the_bytes_land_and_no_temp_file_is_left_behind() {
let dir = TempDir::new("plain");
let file = dir.file("a.sv");
fs::write(&file, "old\n").expect("seed");
write_atomic(&file, b"new\n").expect("write");
assert_eq!(fs::read_to_string(&file).expect("read"), "new\n");
assert_eq!(dir.names(), vec!["a.sv".to_string()]);
}
#[test]
fn a_file_that_does_not_exist_yet_is_created() {
let dir = TempDir::new("create");
let file = dir.file("new.sv");
write_atomic(&file, b"hello\n").expect("write");
assert_eq!(fs::read_to_string(&file).expect("read"), "hello\n");
assert_eq!(dir.names(), vec!["new.sv".to_string()]);
}
#[test]
fn a_rename_that_cannot_happen_is_an_error_and_leaves_no_temp() {
// A directory standing where the file should be: the write succeeds,
// the rename cannot.
let dir = TempDir::new("dirtarget");
let target = dir.file("occupied");
fs::create_dir(&target).expect("create dir");
let err = write_atomic(&target, b"x\n").expect_err("a directory cannot be replaced");
assert!(err.to_string().len() > 1, "{err}");
assert_eq!(dir.names(), vec!["occupied".to_string()], "the temp file was cleaned up");
}
#[test]
fn writing_the_same_path_twice_leaves_one_file() {
let dir = TempDir::new("twice");
let file = dir.file("a.sv");
write_atomic(&file, b"one\n").expect("write");
write_atomic(&file, b"two\n").expect("write");
assert_eq!(fs::read_to_string(&file).expect("read"), "two\n");
assert_eq!(dir.names(), vec!["a.sv".to_string()]);
}
#[cfg(unix)]
#[test]
fn the_targets_permissions_are_preserved() {
use std::os::unix::fs::PermissionsExt;
let dir = TempDir::new("modes");
for mode in [0o600, 0o755] {
let file = dir.file(&format!("m{mode:o}.sv"));
fs::write(&file, "old\n").expect("seed");
fs::set_permissions(&file, fs::Permissions::from_mode(mode)).expect("chmod");
write_atomic(&file, b"new\n").expect("write");
let got = fs::metadata(&file).expect("stat").permissions().mode() & 0o777;
assert_eq!(got, mode, "mode {mode:o} was not preserved");
}
}
#[cfg(unix)]
#[test]
fn a_read_only_target_is_refused_and_left_alone() {
use std::os::unix::fs::PermissionsExt;
let dir = TempDir::new("readonly");
let file = dir.file("ro.sv");
fs::write(&file, "old\n").expect("seed");
fs::set_permissions(&file, fs::Permissions::from_mode(0o444)).expect("chmod");
let err = write_atomic(&file, b"new\n").expect_err("a read-only file is not replaced");
assert_eq!(err.kind(), io::ErrorKind::PermissionDenied, "{err}");
assert_eq!(fs::read_to_string(&file).expect("read"), "old\n");
assert_eq!(dir.names(), vec!["ro.sv".to_string()], "no temp file was made");
fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).expect("restore");
}
#[cfg(unix)]
#[test]
fn writing_through_a_symlink_replaces_the_target_not_the_link() {
let dir = TempDir::new("symlink");
let real = dir.file("real.sv");
let link = dir.file("link.sv");
fs::write(&real, "old\n").expect("seed");
std::os::unix::fs::symlink(&real, &link).expect("symlink");
write_atomic(&link, b"new\n").expect("write");
assert_eq!(fs::read_to_string(&real).expect("read"), "new\n", "the target got the bytes");
assert!(
fs::symlink_metadata(&link).expect("stat").file_type().is_symlink(),
"the link is still a link"
);
assert_eq!(fs::read_to_string(&link).expect("read"), "new\n", "and still points at it");
}
}
+2 -5
View File
@@ -87,10 +87,7 @@ impl Cache {
if !ignore.exists() {
let _ = std::fs::write(&ignore, "*\n");
}
let tmp = dir.join(format!("{FILE}.{}.tmp", std::process::id()));
if std::fs::write(&tmp, self.render()).is_ok() && std::fs::rename(&tmp, path).is_err() {
let _ = std::fs::remove_file(&tmp);
}
let _ = crate::atomic::write_atomic(path, self.render().as_bytes());
}
/// The file's text: one line per entry, sorted by path so that two
@@ -397,7 +394,7 @@ mod tests {
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.ends_with(".tmp"))
.filter(|n| n.ends_with(".tmp") || n.ends_with("-tmp"))
.collect();
assert!(leftovers.is_empty(), "{leftovers:?}");
}
+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,
+4 -1
View File
@@ -6,11 +6,14 @@
//! the same `lucisv.toml` and skip the same files as CI's `lucisv --check`.
//! `cache` answers the third question of the same family — whether a file
//! needs to be processed at all, and `filelist` answers the first one the way
//! an EDA project already does, from a `.f` file. See
//! an EDA project already does, from a `.f` file. `atomic` is the one write
//! path all of them share: nothing here ever truncates a file it is
//! replacing. See
//! `docs/features/lucisv-core-lift/README.md`, and
//! `docs/features/{config-discovery,parallel-files,format-cache,filelist}/README.md`
//! for the rules themselves.
pub mod atomic;
pub mod cache;
pub mod config;
pub mod filelist;
+26 -4
View File
@@ -575,6 +575,7 @@ mod tests {
use crate::uri::path_to_uri;
use std::path::PathBuf;
use std::str::FromStr;
use vlog_parser::PARSE_STACK_SIZE;
/// A one-file workspace with `path` open and the cursor at `needle`'s end.
/// No files on disk: nothing here reads the index.
@@ -1081,10 +1082,31 @@ endmodule
// A trailing newline, so this test isolates depth from the separate
// true-end-of-file `Eof`-adjacency case pinned above.
text.push_str("initial begin\n");
let (ws, uri, position) = asking(&text, "initial begin");
assert!(!ws.document(&uri).expect("open").tokens.is_empty(), "the lexer never recurses");
let items = inline_completions(&ws, &uri, position);
assert!(items.is_some(), "the innermost, truly unclosed `begin` still offers its `end`");
// Opening the document *parses* it, and since §36.1 a bare `begin` at
// item scope is a generate block the tolerant parser descends into —
// so this text nests the parser to `MAX_NESTING_DEPTH` and costs ~4
// MiB of stack in a debug build. That is exactly what
// `PARSE_STACK_SIZE` is for; every production thread that may reach a
// parse is given it (`main.rs`), libtest's own thread is not, so the
// body runs on one of its own. Nothing here is about the inline path,
// which still never recurses.
std::thread::Builder::new()
.stack_size(PARSE_STACK_SIZE)
.spawn(move || {
let (ws, uri, position) = asking(&text, "initial begin");
assert!(
!ws.document(&uri).expect("open").tokens.is_empty(),
"the lexer never recurses"
);
let items = inline_completions(&ws, &uri, position);
assert!(
items.is_some(),
"the innermost, truly unclosed `begin` still offers its `end`"
);
})
.expect("spawn")
.join()
.expect("the inline path crashed");
}
#[test]
+1
View File
@@ -144,6 +144,7 @@ fn item_pairs(item: &Item, out: &mut Vec<Pair>) {
ItemKind::Task(t) => task_pairs(t, out),
ItemKind::Clocking(c) => clocking_pairs(c, out),
ItemKind::GenerateRegion { items, .. } => items_pairs(items, out),
ItemKind::GenBlock(b) => items_pairs(&b.items, out),
ItemKind::GenIf(g) => gen_if_pairs(g, out),
ItemKind::GenFor(g) => gen_block_pairs(&g.body, out),
ItemKind::GenCase(g) => {
+61 -4
View File
@@ -17,7 +17,7 @@ use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString};
use vlog_formatter::fence::{self, Region};
use vlog_linter::{
default_rules, lint, workspace_rules, LintContext, MentionOracle, ModuleInterface, Rule,
Severity, Violation,
RuleOptions, Severity, Violation,
};
use vlog_semantic::{FileId, SymbolKind, WorkspaceIndex};
@@ -35,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.
///
@@ -58,12 +73,13 @@ impl<'a> LintRun<'a> {
let workspace = index.files().len() > usize::from(own.is_some());
let rules = enabled_rules(ws.client_settings(), workspace);
let oracle = workspace.then_some(IndexMentions { index, own });
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,
@@ -71,6 +87,47 @@ 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
View File
@@ -117,6 +117,7 @@ fn items(list: &[Item], offset: u32, out: &mut Vec<TextRange>) {
ItemKind::Class(class) => items(&class.items, offset, out),
ItemKind::Package { items: inner, .. } => items(inner, offset, out),
ItemKind::GenerateRegion { items: inner, .. } => items(inner, offset, out),
ItemKind::GenBlock(b) => items(&b.items, offset, out),
ItemKind::GenIf(gen_if) => gen_if_blocks(gen_if, offset, out),
ItemKind::GenFor(gen_for) => gen_block(&gen_for.body, offset, out),
ItemKind::GenCase(gen_case) => {
@@ -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;
+151 -4
View File
@@ -17,7 +17,7 @@ use std::collections::BTreeMap;
use std::ops::RangeInclusive;
use serde_json::Value;
use vlog_linter::Severity;
use vlog_linter::{OptionValue, RuleOptions, Severity};
/// Accepted `line-length`, and accepted `indent`.
///
@@ -190,6 +190,18 @@ pub struct ClientSettings {
/// 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.
@@ -218,6 +230,8 @@ impl Default for ClientSettings {
lint_ignore: Vec::new(),
lint_severity: every_class_on(),
lint_rules: BTreeMap::new(),
lint_options: RuleOptions::new(),
lint_option_warnings: Vec::new(),
}
}
}
@@ -233,15 +247,21 @@ fn every_class_on() -> BTreeMap<Severity, bool> {
/// Its only use is equality — the server compares it across a settings change
/// to decide whether every open file must be published again.
pub type LintSelection =
(Vec<String>, Vec<String>, BTreeMap<Severity, bool>, BTreeMap<String, bool>);
(Vec<String>, Vec<String>, BTreeMap<Severity, bool>, BTreeMap<String, bool>, RuleOptions);
/// The four lint settings of `settings`, as one comparable value.
/// 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(),
)
}
@@ -272,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),
@@ -319,6 +340,8 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
// 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,
}
}
@@ -364,6 +387,63 @@ fn rule_toggles(value: Option<&Value>) -> BTreeMap<String, bool> {
.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 —
/// case and all — because the enum in `package.json` is what a settings UI
/// offers, and forgiving `"Workspace"` here would make a typo mean something
@@ -813,7 +893,9 @@ mod tests {
selected.lint_select = vec!["error".to_string()];
let mut ignored = base.clone();
ignored.lint_ignore = vec!["no-tabs".to_string()];
for changed in [severity, toggled, selected, ignored] {
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.
@@ -822,6 +904,71 @@ mod tests {
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
+1
View File
@@ -180,6 +180,7 @@ fn item_site(item: &Item, offset: u32) -> Option<Site<'_>> {
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => {
site_at(items, offset)
}
ItemKind::GenBlock(b) => gen_block_site(b, offset),
ItemKind::GenIf(g) => gen_if_site(g, offset),
ItemKind::GenFor(g) => gen_block_site(&g.body, offset),
ItemKind::GenCase(g) => g.items.iter().find_map(|arm| gen_block_site(&arm.body, offset)),
+75
View File
@@ -7367,6 +7367,81 @@ fn the_project_wide_lint_rules_publish_and_a_setting_turns_them_off() {
let _ = std::fs::remove_dir_all(&dir);
}
/// `lucisv.lint.options` over the wire — the pin §34's QA found missing and
/// drove by hand twice (`docs/features/linter-expansion-2/README.md`, QA log).
///
/// Three claims a unit test cannot make: the object survives
/// `didChangeConfiguration` and changes what is published; the editor's value
/// beats a checked-in `lucisv.toml`'s, key by key; and a refused entry is
/// *dropped and logged* rather than fatal — the rule keeps running, here on
/// the `lucisv.toml` value the bad entry failed to override.
#[test]
fn the_lint_options_setting_changes_what_is_published_and_a_bad_entry_is_logged() {
let dir = temp_dir("lintoptions");
std::fs::write(dir.join("lucisv.toml"), "[lint.line-length]\nlength = 40\n").expect("write");
let file = dir.join("wide.sv");
let text = "module wide;\n wire this_line_is_a_good_deal_wider_than_forty;\nendmodule\n";
std::fs::write(&file, text).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(text).expect("json")
)),
// The editor's value beats the checked-in one, key by key.
frame(
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"lint":{"options":{"line-length":{"length":200}}}}}}}"#,
),
// ... and a typo'd key is refused, dropped and logged, leaving the
// `lucisv.toml` value standing rather than turning the linter off.
frame(
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"lint":{"options":{"line-length":{"lenght":200}}}}}}}"#,
),
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
]
.concat();
let messages = talk(&session);
let wide: Vec<usize> = messages
.iter()
.filter(|m| m["method"] == "textDocument/publishDiagnostics")
.filter(|m| m["params"]["uri"] == uri.as_str())
.map(|m| {
m["params"]["diagnostics"]
.as_array()
.map(|list| list.iter().filter(|d| d["code"] == "line-length").count())
.unwrap_or(0)
})
.collect();
assert!(wide.len() >= 3, "one publish per state: {wide:?}");
assert_eq!(wide[0], 1, "the `lucisv.toml`'s 40 flags the 47-column line: {wide:?}");
assert_eq!(wide[1], 0, "the editor's 200 beat it: {wide:?}");
assert_eq!(
wide[wide.len() - 1],
1,
"the refused entry is dropped, so the `lucisv.toml` value stands again: {wide:?}"
);
let logged: Vec<&str> = messages
.iter()
.filter(|m| m["method"] == "window/logMessage")
.filter_map(|m| m["params"]["message"].as_str())
.filter(|text| text.contains("lucisv.lint.options"))
.collect();
assert_eq!(logged.len(), 1, "exactly the one refused entry: {logged:?}");
assert!(logged[0].contains("lenght"), "{}", logged[0]);
assert!(logged[0].contains("ignored"), "{}", logged[0]);
let _ = std::fs::remove_dir_all(&dir);
}
/// `lucisv.instantiate` — `docs/topo.md` §2.9-19. What only an e2e test can
/// check: that the command is advertised in `initialize`, that its three
/// arguments survive the wire, and that the skeleton arrives as a
+1
View File
@@ -245,6 +245,7 @@ fn scan_nested(src: &str, item: &Item, out: &mut Vec<Region>) {
ItemKind::Module(m) => scan_scope(src, &m.items, &m.dangling, out),
ItemKind::Package { items, dangling, .. } => scan_scope(src, items, dangling, out),
ItemKind::GenerateRegion { items, dangling } => scan_scope(src, items, dangling, out),
ItemKind::GenBlock(b) => scan_gen_block(src, b, out),
ItemKind::GenIf(g) => scan_gen_if(src, g, out),
ItemKind::GenFor(g) => scan_gen_block(src, &g.body, out),
ItemKind::GenCase(g) => {
+43 -20
View File
@@ -274,6 +274,21 @@ impl<'a> Fmt<'a> {
body.extend(self.dangling(dangling));
concat(vec![text("generate"), indent(body), Doc::HardLine, text("endgenerate")])
}
// A bare `begin … end` standing where an item belongs. Never
// reached from `format_source`: the parser records a diagnostic
// beside it and a file with a diagnostic is emitted unchanged.
// The arm exists so a range or tolerant printer has nothing to
// invent — the block prints the way a generate block's does,
// without the separator `gen_block` puts in front of the keyword
// for the header it usually hangs off.
ItemKind::GenBlock(b) => {
let mut docs = Vec::new();
if self.inline_comments(&b.before_kw, &mut docs) {
docs.push(Doc::HardLine);
}
self.begin_block(&mut docs, b, depth);
concat(docs)
}
ItemKind::GenIf(g) => self.gen_if(g, depth),
ItemKind::GenFor(g) => self.gen_for(g, depth),
ItemKind::GenCase(g) => self.gen_case(g, depth),
@@ -464,26 +479,7 @@ impl<'a> Fmt<'a> {
} else {
self.inline_comments_spaced(&b.before_kw, docs);
}
docs.push(text("begin"));
if let Some(l) = &b.label {
self.slot_comments(&b.before_colon, docs);
docs.push(text(if b.before_colon.is_empty() { " :" } else { ":" }));
if b.after_colon.is_empty() {
docs.push(text(" "));
} else {
self.inline_comments_spaced(&b.after_colon, docs);
}
docs.push(text(named(l)));
}
let mut body = Vec::new();
if !b.items.is_empty() {
body.push(Doc::HardLine);
body.extend(self.item_seq(&b.items, depth + 1));
}
body.extend(self.dangling(&b.dangling));
docs.push(indent(body));
docs.push(Doc::HardLine);
docs.push(self.closing_labeled("end", &b.end_label, &b.end_label_comments));
self.begin_block(docs, b, depth);
true
} else {
let item = &b.items[0];
@@ -492,6 +488,33 @@ impl<'a> Fmt<'a> {
}
}
/// A generate block's `begin … end` and everything between, from the
/// keyword on — the separator in front of it is the caller's, because a
/// block hanging off an `if (…)` header needs one and a block standing on
/// its own as an item ([`ItemKind::GenBlock`]) does not.
fn begin_block(&self, docs: &mut Vec<Doc>, b: &GenBlock, depth: usize) {
docs.push(text("begin"));
if let Some(l) = &b.label {
self.slot_comments(&b.before_colon, docs);
docs.push(text(if b.before_colon.is_empty() { " :" } else { ":" }));
if b.after_colon.is_empty() {
docs.push(text(" "));
} else {
self.inline_comments_spaced(&b.after_colon, docs);
}
docs.push(text(named(l)));
}
let mut body = Vec::new();
if !b.items.is_empty() {
body.push(Doc::HardLine);
body.extend(self.item_seq(&b.items, depth + 1));
}
body.extend(self.dangling(&b.dangling));
docs.push(indent(body));
docs.push(Doc::HardLine);
docs.push(self.closing_labeled("end", &b.end_label, &b.end_label_comments));
}
fn gen_for(&self, g: &GenFor, depth: usize) -> Doc {
let mut header = Vec::new();
self.for_open(&g.comments, &mut header);
+76
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
@@ -201,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>,
@@ -254,6 +266,8 @@ 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(),
@@ -271,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).
+102
View File
@@ -12,6 +12,7 @@ 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};
@@ -147,6 +148,107 @@ fn struct_types(struct_ty: &StructType, visit: &mut dyn FnMut(&DataType)) {
}
}
/// 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)) {
+306
View File
@@ -0,0 +1,306 @@
//! Every expression written in a file.
//!
//! `visit` walks the item and statement spines and `decls` the types and
//! dimensions; neither reaches *into* an expression, and a rule that judges
//! the shape of one (`suggest-parentheses`) needs every node of every tree,
//! wherever it was written. Collecting them lives here so each of the three
//! files stays one sentence long.
use vlog_parser::ast::{
Connections, Expr, ExprKind, ForStep, Instantiation, ItemKind, ListElem, SourceFile, StmtKind,
TimingControl,
};
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
/// Calls `f` on every expression of the file, sub-expressions included.
///
/// The **roots** are the places an expression is written: a continuous or
/// procedural assignment, a declaration's initialiser, a condition, a call
/// argument, an instantiation's connections, a generate header, an expression
/// statement. Sub-expressions are then reached through every composite
/// [`ExprKind`], so a node buried in a concatenation inside a call argument is
/// visited like any other.
pub(crate) fn walk_exprs(file: &SourceFile, f: &mut dyn FnMut(&Expr)) {
let mut root = |expr: &Expr| descend(expr, f);
walk_param_ports(file, &mut |port| {
if let Some(default) = &port.default {
root(default);
}
});
walk_items(file, &mut |item| match &item.kind {
ItemKind::ContAssign(assign) => {
if let Some(delay) = &assign.delay {
root(delay);
}
for pair in &assign.assigns {
root(&pair.lhs);
root(&pair.rhs);
}
}
ItemKind::ParamDecl(decl) => initialisers(&decl.declarators, &mut root),
ItemKind::DataDecl(decl) => initialisers(&decl.declarators, &mut root),
ItemKind::PortDecl(decl) => initialisers(&decl.declarators, &mut root),
ItemKind::ElabTask(expr) => root(expr),
ItemKind::Instantiation(inst) => connections(inst, &mut root),
ItemKind::Bind(bind) => connections(&bind.inst, &mut root),
ItemKind::GenIf(gen_if) => root(&gen_if.cond),
ItemKind::GenFor(gen_for) => {
root(&gen_for.init.lhs);
root(&gen_for.init.rhs);
root(&gen_for.cond);
match &gen_for.step {
ForStep::Assign(assign) => {
root(&assign.lhs);
root(&assign.rhs);
}
ForStep::Expr(expr) => root(expr),
}
}
ItemKind::GenCase(gen_case) => {
root(&gen_case.expr);
for case_item in &gen_case.items {
for label in &case_item.labels {
root(&label.expr);
}
}
}
ItemKind::Defparam(pairs) => {
for (target, value) in pairs {
root(target);
root(value);
}
}
ItemKind::Alias(terms) => {
for term in terms {
root(term);
}
}
_ => {}
});
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
StmtKind::Assign { lhs, rhs, timing, .. } => {
root(lhs);
root(rhs);
if let Some(TimingControl::Delay { expr, .. }) = timing {
root(expr);
}
}
StmtKind::ExprStmt(expr) | StmtKind::EventTrigger(expr) => root(expr),
StmtKind::If { cond, .. } => root(cond),
StmtKind::Case { expr, items, .. } => {
root(expr);
for case_item in items {
for label in &case_item.labels {
root(&label.expr);
}
}
}
StmtKind::RandCase { items, .. } => {
for case_item in items {
for label in &case_item.labels {
root(&label.expr);
}
}
}
StmtKind::For { init, cond, step, .. } => {
for one in init {
root(&one.assign.lhs);
root(&one.assign.rhs);
}
if let Some(cond) = cond {
root(cond);
}
for one in step {
match one {
ForStep::Assign(assign) => {
root(&assign.lhs);
root(&assign.rhs);
}
ForStep::Expr(expr) => root(expr),
}
}
}
StmtKind::While { cond, .. } | StmtKind::DoWhile { cond, .. } => root(cond),
StmtKind::Repeat { count, .. } => root(count),
StmtKind::Foreach { target, .. } => root(target),
StmtKind::Wait { cond, .. } => root(cond),
// A sensitivity list holds edge terms, not values; only the `#delay`
// spelling carries an expression a rule would judge.
StmtKind::Timing { control: TimingControl::Delay { expr, .. }, .. } => root(expr),
StmtKind::ForceRelease { lhs, rhs, .. } => {
root(lhs);
if let Some(rhs) = rhs {
root(rhs);
}
}
StmtKind::Return { expr: Some(expr), .. } => root(expr),
StmtKind::VarDecl(decl) => initialisers(&decl.declarators, &mut root),
StmtKind::ParamDecl(decl) => initialisers(&decl.declarators, &mut root),
StmtKind::PortDecl(decl) => initialisers(&decl.declarators, &mut root),
_ => {}
});
}
fn initialisers(declarators: &[vlog_parser::ast::Declarator], root: &mut dyn FnMut(&Expr)) {
for declarator in declarators {
if let Some(init) = &declarator.init {
root(init);
}
}
}
fn connections(inst: &Instantiation, root: &mut dyn FnMut(&Expr)) {
if let Some(params) = &inst.params {
for conn in params.iter().filter_map(ListElem::ok) {
if let Some(expr) = &conn.expr {
root(expr);
}
}
}
for instance in &inst.instances {
match &instance.conns {
Connections::Named(conns) => {
for conn in conns.iter().filter_map(ListElem::ok) {
if let Some(expr) = &conn.expr {
root(expr);
}
}
}
Connections::Ordered(conns) => {
for conn in conns.iter().filter_map(ListElem::ok) {
if let Some(expr) = &conn.expr {
root(expr);
}
}
}
}
}
}
/// One expression and everything inside it.
fn descend(expr: &Expr, f: &mut dyn FnMut(&Expr)) {
f(expr);
match &expr.kind {
ExprKind::Unary { expr: inner, .. }
| ExprKind::Postfix { expr: inner, .. }
| ExprKind::New(inner)
| ExprKind::Paren { inner, .. } => descend(inner, f),
ExprKind::Binary { lhs, rhs, .. } => {
descend(lhs, f);
descend(rhs, f);
}
ExprKind::Ternary { cond, then, els, .. } => {
descend(cond, f);
descend(then, f);
descend(els, f);
}
ExprKind::Call { callee, args, .. } => {
descend(callee, f);
for arg in args {
descend(&arg.expr, f);
}
}
ExprKind::Index { base, index, .. } => {
descend(base, f);
descend(index, f);
}
ExprKind::Range { base, msb, lsb, .. } => {
descend(base, f);
descend(msb, f);
descend(lsb, f);
}
ExprKind::Member { base, .. }
| ExprKind::Scope { base, .. }
| ExprKind::Parameterized { base, .. } => descend(base, f),
ExprKind::Concat(items) => {
for item in items {
descend(&item.expr, f);
}
}
ExprKind::Repl { count, inner } | ExprKind::AssignPatternRepl { count, inner } => {
descend(count, f);
for item in inner {
descend(&item.expr, f);
}
}
ExprKind::Stream { slice, inner, .. } => {
if let Some(slice) = slice {
descend(slice, f);
}
for item in inner {
descend(&item.expr, f);
}
}
ExprKind::Cast { ty, expr: inner, .. } => {
descend(ty, f);
descend(inner, f);
}
ExprKind::Inside { lhs, ranges, .. } => {
descend(lhs, f);
for item in ranges {
descend(&item.expr, f);
}
}
ExprKind::InsideMacro { lhs, .. } => descend(lhs, f),
ExprKind::With { base, .. } | ExprKind::WithConstraint { base, .. } => descend(base, f),
ExprKind::Dist { expr: inner, .. } => descend(inner, f),
ExprKind::NamedArg { value, .. } => descend(value, f),
ExprKind::AssignPattern(items) => {
for item in items {
if let Some(key) = &item.key {
descend(key, f);
}
descend(&item.value, f);
}
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::parse_source_tolerant;
fn ternaries(src: &str) -> usize {
let (file, _) = parse_source_tolerant(src);
let mut n = 0;
walk_exprs(&file, &mut |expr| {
if matches!(expr.kind, ExprKind::Ternary { .. }) {
n += 1;
}
});
n
}
#[test]
fn reaches_an_expression_written_anywhere() {
let src = "module m #(parameter int P = a ? 1 : 2) (\n\
input logic i\n\
);\n\
logic v = b ? 1 : 2;\n\
assign w = c ? 1 : 2;\n\
sub u (.p(d ? 1 : 2));\n\
if (e ? 1 : 2) begin : g\n wire x;\n end\n\
initial begin\n\
if (f ? 1 : 2) y = g_ ? 1 : 2;\n\
z = {h ? 1 : 2, call(i ? 1 : 2)};\n\
end\n\
endmodule\n";
assert_eq!(ternaries(src), 9);
}
#[test]
fn a_nested_expression_is_reached_through_every_composite() {
assert_eq!(ternaries("module m;\n assign x = ~(a ? 1 : 2);\nendmodule\n"), 1);
assert_eq!(ternaries("module m;\n assign x = y[a ? 1 : 2];\nendmodule\n"), 1);
assert_eq!(ternaries("module m;\n assign x = int'(a ? 1 : 2);\nendmodule\n"), 1);
assert_eq!(ternaries("module m;\n assign x = {2{a ? 1 : 2}};\nendmodule\n"), 1);
}
#[test]
fn a_file_with_no_expressions_visits_nothing() {
assert_eq!(ternaries("module m;\nendmodule\n"), 0);
}
}
+9 -2
View File
@@ -22,9 +22,14 @@
mod context;
mod decls;
mod exprs;
mod interfaces;
mod literal;
mod module_decls;
mod naming;
mod options;
mod preproc;
mod regex;
mod registry;
mod rule_docs;
mod rules;
@@ -39,6 +44,7 @@ use std::path::PathBuf;
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,
};
@@ -197,11 +203,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 forbid-implicit-declarations\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 forbid-implicit-declarations\n wire a;\nendmodule\n";
assert_eq!(names(&lint_all(src)), vec![UNUSED_WAIVER]);
}
+234
View File
@@ -0,0 +1,234 @@
//! 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::GenBlock(b) => block(b, 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(), "[]");
}
}
+105
View File
@@ -0,0 +1,105 @@
//! What a preprocessor token says: the name a macro invocation calls, and the
//! word and operand a compiler directive carries.
//!
//! The lexer keeps both shapes as single tokens — a macro invocation
//! (`` `uvm_info("A", "B", UVM_LOW) ``) is one `Ident` whose text starts with
//! a backtick and swallows its balanced arguments, and a directive
//! (`` `ifdef FOO ``) is one `Directive` running to the end of its (possibly
//! continued) line. Four rules read those texts; reading them in one place is
//! what stops the four from disagreeing about where a name starts and ends.
use vlog_parser::token::{Token, TokenKind};
/// The macro this token invokes, without its backtick or arguments, or `None`
/// for a token that is not a macro invocation.
pub(crate) fn macro_name(token: &Token) -> Option<&str> {
if token.kind != TokenKind::Ident {
return None;
}
let rest = token.text.strip_prefix('`')?;
let end = rest.find(|c: char| !is_name_char(c)).unwrap_or(rest.len());
match end {
0 => None,
_ => Some(&rest[..end]),
}
}
/// The keyword of a compiler directive (`ifdef`, `endif`, `define`), or `None`
/// for a token that is not one.
pub(crate) fn directive_word(token: &Token) -> Option<&str> {
if token.kind != TokenKind::Directive {
return None;
}
let rest = token.text.strip_prefix('`')?;
let end = rest.find(|c: char| !is_name_char(c)).unwrap_or(rest.len());
match end {
0 => None,
_ => Some(&rest[..end]),
}
}
/// The name a directive names — the `FOO` of `` `ifdef FOO `` — or `None` when
/// it names nothing.
pub(crate) fn directive_operand(token: &Token) -> Option<&str> {
let word = directive_word(token)?;
let rest = token.text.get(1 + word.len()..)?.trim_start();
let end = rest.find(|c: char| !is_name_char(c)).unwrap_or(rest.len());
match end {
0 => None,
_ => Some(&rest[..end]),
}
}
/// The characters an identifier is made of, matching the lexer's own rule.
fn is_name_char(c: char) -> bool {
c == '_' || c == '$' || c.is_ascii_alphanumeric()
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::tokenize;
fn tokens(src: &str) -> Vec<Token> {
tokenize(src).expect("lexes")
}
#[test]
fn a_macro_invocation_gives_its_name() {
let toks = tokens("module m;\n initial `uvm_info(\"A\", \"B\", UVM_LOW);\nendmodule\n");
let names: Vec<&str> = toks.iter().filter_map(macro_name).collect();
assert_eq!(names, vec!["uvm_info"]);
}
#[test]
fn a_macro_without_arguments_gives_its_name_too() {
let toks = tokens("module m;\n `ASSERT_INIT\nendmodule\n");
assert_eq!(toks.iter().filter_map(macro_name).collect::<Vec<_>>(), vec!["ASSERT_INIT"]);
}
#[test]
fn an_ordinary_identifier_is_not_a_macro() {
let toks = tokens("module m;\n wire uvm_info;\nendmodule\n");
assert!(toks.iter().filter_map(macro_name).next().is_none());
}
#[test]
fn a_directive_gives_its_word_and_operand() {
let toks = tokens("`ifdef FOO\n`endif\n`define BAR 1\nmodule m;\nendmodule\n");
let words: Vec<&str> = toks.iter().filter_map(directive_word).collect();
assert_eq!(words, vec!["ifdef", "endif", "define"]);
let operands: Vec<Option<&str>> =
toks.iter().filter(|t| t.kind == TokenKind::Directive).map(directive_operand).collect();
assert_eq!(operands, vec![Some("FOO"), None, Some("BAR")]);
}
#[test]
fn a_directive_is_not_a_macro_invocation_and_the_other_way_round() {
let toks = tokens("`ifdef FOO\nmodule m;\n `ASSERT\nendmodule\n`endif\n");
assert_eq!(toks.iter().filter_map(macro_name).collect::<Vec<_>>(), vec!["ASSERT"]);
assert!(toks
.iter()
.filter(|t| t.kind == TokenKind::Ident)
.all(|t| directive_word(t).is_none()));
}
}
+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());
}
}
+111
View File
@@ -1,6 +1,7 @@
//! 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};
@@ -59,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>;
}
@@ -66,20 +79,42 @@ 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::create_object_name_match::CreateObjectNameMatch,
&rules::dff_name_style::DffNameStyle,
&rules::disable_statement::DisableStatement,
&rules::duplicate_declaration::DuplicateDeclaration,
&rules::empty_item::EmptyItem,
&rules::endif_comment::EndifComment,
&rules::enum_name_style::EnumNameStyle,
&rules::explicit_begin::ExplicitBegin,
&rules::explicit_function_lifetime::ExplicitFunctionLifetime,
&rules::explicit_function_task_parameter_type::ExplicitFunctionTaskParameterType,
&rules::explicit_parameter_storage_type::ExplicitParameterStorageType,
&rules::explicit_task_lifetime::ExplicitTaskLifetime,
&rules::forbid_consecutive_null_statements::ForbidConsecutiveNullStatements,
&rules::forbid_defparam::ForbidDefparam,
&rules::forbid_line_continuations::ForbidLineContinuations,
&rules::forbid_negative_array_dim::ForbidNegativeArrayDim,
&rules::forbidden_macro::ForbiddenMacro,
&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::legacy_generate_region::LegacyGenerateRegion,
&rules::legacy_genvar_declaration::LegacyGenvarDeclaration,
&rules::line_length::LineLength,
&rules::macro_name_style::MacroNameStyle,
&rules::macro_string_concatenation::MacroStringConcatenation,
&rules::mismatched_labels::MismatchedLabels,
&rules::module_begin_block::ModuleBeginBlock,
&rules::module_filename::ModuleFilename,
&rules::module_name_style::ModuleNameStyle,
&rules::module_parameter::ModuleParameter,
@@ -87,19 +122,34 @@ pub fn all_rules() -> Vec<&'static dyn Rule> {
&rules::multiply_driven::MultiplyDriven,
&rules::no_tabs::NoTabs,
&rules::no_trailing_whitespace::NoTrailingWhitespace,
&rules::numeric_format_string_style::NumericFormatStringStyle,
&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::positive_meaning_parameter_name::PositiveMeaningParameterName,
&rules::posix_eof::PosixEof,
&rules::proper_parameter_declaration::ProperParameterDeclaration,
&rules::signal_name_style::SignalNameStyle,
&rules::struct_union_name_style::StructUnionNameStyle,
&rules::suggest_parentheses::SuggestParentheses,
&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::unpacked_dimensions_range_ordering::UnpackedDimensionsRangeOrdering,
&rules::unused_signal::UnusedSignal,
&rules::unused_waiver::UnusedWaiver,
&rules::uvm_macro_semicolon::UvmMacroSemicolon,
&rules::v2001_generate_begin::V2001GenerateBegin,
&rules::void_cast::VoidCast,
&rules::wire_reg_mixup::WireRegMixup,
]
@@ -427,6 +477,67 @@ mod tests {
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() {
+85 -3
View File
@@ -6,8 +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 {
@@ -30,7 +32,13 @@ 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 | Severity | Default | Fix |\n|---|---|---|---|\n");
@@ -58,11 +66,44 @@ pub fn rules_markdown() -> String {
));
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 {
@@ -171,13 +212,47 @@ mod tests {
}
}
/// 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(10).collect();
let head: Vec<&str> = markdown.lines().take(12).collect();
assert_eq!(
head,
vec![
@@ -200,6 +275,12 @@ 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>`.",
"",
"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 |",
"|---|---|---|---|",
]
@@ -209,12 +290,13 @@ mod tests {
.find(|rule| rule.severity() == Severity::Error)
.expect("some rule is an error");
let section = format!(
"## {}\n\n{}.\n\n- Severity: error\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));
}
}
@@ -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);
}
}
@@ -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,178 @@
//! `create-object-name-match` — `type_id::create("x")` names the variable `x`.
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::{Expr, ExprKind, ItemKind, StmtKind};
/// See [`Rule::doc`].
pub struct CreateObjectNameMatch;
const NAME: &str = "create-object-name-match";
impl Rule for CreateObjectNameMatch {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"give `type_id::create` the name of the variable it is assigned to"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"The string handed to `type_id::create()` becomes the object's UVM \
instance name, and that name is what `uvm_config_db` paths, factory \
overrides, `+uvm_set_config` plusargs and every report line are \
written against. When it does not match the handle it was assigned \
to, a config setting aimed at `env.agent.driver` silently misses the \
object the reader believes it is aimed at — and nothing fails, it \
just does not take. Verible's `create-object-name-match` (\"Checks \
that the 'name' argument of `type_id::create()` matches the assigned \
variable name.\", enabled by default) is the same rule and the same \
default.\n\n\
Judged where Verible judges it: a right-hand side of the shape \
`<type>::type_id::create(\"name\", …)`, however the type is \
qualified (`pkg::cls::type_id::create`), assigned to a **plain \
variable** — a `this.h` or an array element is not one, and neither \
is a `create` whose first argument is not a string literal. No \
automatic fix: rewriting the string changes the object's UVM path, \
and rewriting the variable renames it everywhere; which is meant is \
the author's to say."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
let mut judge = |lhs: &str, rhs: &Expr| {
let Some(arg) = create_name(rhs) else { return };
let Some(written) = string_value(arg) else { return };
if written == lhs {
return;
}
out.push(Violation::new(
NAME,
format!(
"`type_id::create` is named `{written}` but assigned to `{lhs}`; \
the two must match"
),
arg.span,
));
};
walk_all_stmts(ctx.file(), &mut |stmt| match &stmt.kind {
StmtKind::Assign { lhs, rhs, .. } => {
if let ExprKind::Ident(name) = &lhs.kind {
judge(name, rhs);
}
}
StmtKind::VarDecl(decl) => {
for declarator in &decl.declarators {
if let Some(init) = &declarator.init {
judge(&declarator.name, init);
}
}
}
_ => {}
});
walk_items(ctx.file(), &mut |item| {
let ItemKind::DataDecl(decl) = &item.kind else { return };
for declarator in &decl.declarators {
if let Some(init) = &declarator.init {
judge(&declarator.name, init);
}
}
});
out
}
}
/// The first argument of a `…::type_id::create(…)` call, or `None` for
/// anything else.
fn create_name(expr: &Expr) -> Option<&Expr> {
let ExprKind::Call { callee, args, .. } = &expr.kind else { return None };
let ExprKind::Scope { base, name, .. } = &callee.kind else { return None };
if name != "create" {
return None;
}
let ExprKind::Scope { name: middle, .. } = &base.kind else { return None };
if middle != "type_id" {
return None;
}
args.first().map(|arg| &arg.expr)
}
/// The text of a string literal, without its quotes.
fn string_value(expr: &Expr) -> Option<&str> {
let ExprKind::Str(text) = &expr.kind else { return None };
text.strip_prefix('"')?.strip_suffix('"')
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
CreateObjectNameMatch.check(&LintContext::new(src, None))
}
fn body(text: &str) -> String {
format!(
"class c;\n function automatic void build();\n {text}\n endfunction\nendclass\n"
)
}
#[test]
fn flags_a_mismatched_name_and_underlines_the_string() {
let src = body("driver_h = my_driver::type_id::create(\"drv\", this);");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "\"drv\"");
assert!(found[0].fix.is_none());
}
#[test]
fn a_matching_name_is_what_the_rule_wants() {
for text in [
"driver_h = my_driver::type_id::create(\"driver_h\", this);",
"driver_h = pkg::my_driver::type_id::create(\"driver_h\");",
] {
let src = body(text);
assert!(violations(&src).is_empty(), "{text}: {:?}", violations(&src));
}
}
#[test]
fn a_declaration_with_an_initialiser_is_judged_too() {
let src = body("my_driver driver_h = my_driver::type_id::create(\"drv\");");
assert_eq!(violations(&src).len(), 1, "{:?}", violations(&src));
}
#[test]
fn something_that_is_not_a_type_id_create_is_left_alone() {
for text in [
"driver_h = my_driver::create(\"drv\");",
"driver_h = my_driver::type_id::get();",
"driver_h = new(\"drv\");",
"driver_h = f(\"drv\");",
] {
let src = body(text);
assert!(violations(&src).is_empty(), "{text}: {:?}", violations(&src));
}
}
#[test]
fn a_non_literal_name_or_a_non_plain_target_says_nothing() {
for text in [
"driver_h = my_driver::type_id::create(name_s, this);",
"this.driver_h = my_driver::type_id::create(\"drv\");",
"agents[0] = my_agent::type_id::create(\"drv\");",
] {
let src = body(text);
assert!(violations(&src).is_empty(), "{text}: {:?}", violations(&src));
}
}
}
@@ -0,0 +1,459 @@
//! `dff-name-style` — a flip-flop's output and its next-state input are named
//! for each other.
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_all_stmts, walk_items};
use vlog_parser::ast::{Expr, ExprKind, ItemKind, Stmt, StmtKind};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct DffNameStyle;
const NAME: &str = "dff-name-style";
/// Verible's four options. Its `input` / `output` / `waive_ifs_with_conditions`
/// are comma-separated strings there and lists here, which is how every other
/// lucisv list option is spelled; `waive_lhs_regex`'s default is Verible's
/// `(?i)mem.*` written without the inline flag this engine does not implement.
const OPTIONS: &[OptionSpec] = &[
OptionSpec {
name: "input",
kind: OptionKind::List,
default: OptionDefault::List(&["next", "n", "d"]),
doc: "suffixes that mark the next-state input of a flip-flop",
},
OptionSpec {
name: "output",
kind: OptionKind::List,
default: OptionDefault::List(&["reg", "r", "ff", "q"]),
doc: "suffixes that mark the registered output of a flip-flop",
},
OptionSpec {
name: "waive_ifs_with_conditions",
kind: OptionKind::List,
default: OptionDefault::List(&[
"!rst_ni",
"flush_i",
"!rst_ni || flush_i",
"flush_i || !rst_ni",
]),
doc: "conditions whose branches are reset or flush paths and are not judged",
},
OptionSpec {
name: "waive_lhs_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str("[mM][eE][mM].*"),
doc: "names that are not flip-flops at all and are left alone",
},
];
impl Rule for DffNameStyle {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name a flip-flop's output and its next-state input for each other"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn default_on(&self) -> bool {
false
}
fn options(&self) -> &'static [OptionSpec] {
OPTIONS
}
fn doc(&self) -> &'static str {
"The `_q`/`_d` convention makes a design's state visible at a glance: \
`count_q <= count_d` says \"this is the register, that is the \
combinational next value\", so a waveform, a schematic and the source \
all name the same two nets, and a signal called `count_q` driven by \
a `always_comb` is a mistake the reader can see without following it. \
Verible's `dff-name-style` (\"Checks that D Flip-Flops use \
appropriate naming conventions in input/output ports.\", **disabled** \
by default) is the same rule and the same default, with the same four \
options.\n\n\
Two things are checked. **In an `always_ff`**, a nonblocking \
assignment's left-hand side must end with one of the `output` \
suffixes (`_q`, `_r`, `_ff`, `_reg`, optionally with a pipeline \
number: `data_q2`); and when its right-hand side is a plain name \
ending with one of the `input` suffixes (`_d`, `_n`, `_next`), the \
two must share a base — `data_q <= data_d` is right, `data_q <= \
other_d` is not. **Outside one**, a blocking or continuous \
assignment to a name ending in an `output` suffix is reported: that \
name promises a register and is not one.\n\n\
Only a **plain identifier** is judged on either side; an indexed, \
member-selected or concatenated target is not something a naming \
convention can speak about. A branch whose `if` condition is one of \
`waive_ifs_with_conditions` is skipped, which is what keeps reset \
and flush paths quiet, and a name matching `waive_lhs_regex` is \
skipped entirely (memories are not flip-flops). Conditions are \
compared ignoring whitespace, so `!rst_ni` and `! rst_ni` are the \
same waiver. No automatic fix: renaming a signal is a rename."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let settings = Settings::read(ctx);
let mut out = Vec::new();
registered(ctx, &settings, &mut out);
unregistered(ctx, &settings, &mut out);
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
out
}
}
/// The four options, read once for the whole file.
struct Settings {
input: Vec<String>,
output: Vec<String>,
waived_conditions: Vec<String>,
waived_lhs: Option<crate::regex::Regex>,
}
impl Settings {
fn read(ctx: &LintContext) -> Settings {
Settings {
input: ctx.option_list(NAME, "input"),
output: ctx.option_list(NAME, "output"),
waived_conditions: ctx
.option_list(NAME, "waive_ifs_with_conditions")
.iter()
.map(|text| squeeze(text))
.collect(),
waived_lhs: ctx.option_pattern(NAME, "waive_lhs_regex"),
}
}
/// Whether this left-hand side is one the project asked not to judge.
fn waives(&self, name: &str) -> bool {
self.waived_lhs.as_ref().is_some_and(|pattern| pattern.is_match(name))
}
}
/// The `always_ff` half: every nonblocking assignment inside one.
fn registered(ctx: &LintContext, settings: &Settings, out: &mut Vec<Violation>) {
walk_items(ctx.file(), &mut |item| {
let ItemKind::Always { kw, stmt } = &item.kind else { return };
if kw != "always_ff" {
return;
}
let mut conditions: Vec<String> = Vec::new();
clocked(ctx, settings, stmt, &mut conditions, out);
});
}
/// Walks one `always_ff` body, remembering which `if` conditions hold.
fn clocked(
ctx: &LintContext,
settings: &Settings,
stmt: &Stmt,
conditions: &mut Vec<String>,
out: &mut Vec<Violation>,
) {
match &stmt.kind {
StmtKind::Assign { lhs, rhs, op, .. } if op == "<=" => {
if conditions.iter().any(|cond| settings.waived_conditions.contains(cond)) {
return;
}
judge_flop(settings, lhs, rhs, out);
}
StmtKind::If { cond, then, els, .. } => {
conditions.push(squeeze(text_of(ctx, cond.span)));
clocked(ctx, settings, then, conditions, out);
conditions.pop();
if let Some(els) = els {
clocked(ctx, settings, els, conditions, out);
}
}
StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => {
for inner in stmts {
clocked(ctx, settings, inner, conditions, out);
}
}
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
for case_item in items {
clocked(ctx, settings, &case_item.stmt, conditions, out);
}
}
StmtKind::Labeled { stmt: inner, .. }
| StmtKind::For { body: inner, .. }
| StmtKind::While { body: inner, .. }
| StmtKind::DoWhile { body: inner, .. }
| StmtKind::Repeat { body: inner, .. }
| StmtKind::Forever { body: inner }
| StmtKind::Foreach { body: inner, .. } => clocked(ctx, settings, inner, conditions, out),
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
clocked(ctx, settings, inner, conditions, out)
}
_ => {}
}
}
/// One `q <= d` inside an `always_ff`.
fn judge_flop(settings: &Settings, lhs: &Expr, rhs: &Expr, out: &mut Vec<Violation>) {
let Some(target) = plain_name(lhs) else { return };
if settings.waives(target) {
return;
}
let Some(base) = base_of(target, &settings.output) else {
out.push(Violation::new(
NAME,
format!(
"`{target}` is assigned in an `always_ff` but does not end with {}",
one_of(&settings.output)
),
lhs.span,
));
return;
};
if base.is_empty() {
out.push(Violation::new(
NAME,
format!("`{target}` is nothing but a flip-flop suffix; name the signal too"),
lhs.span,
));
return;
}
let Some(source) = plain_name(rhs) else { return };
let Some(source_base) = base_of(source, &settings.input) else { return };
if source_base != base {
out.push(Violation::new(
NAME,
format!(
"`{target}` is driven by `{source}`; the parts before the suffixes must \
match, but `{base}` is not `{source_base}`"
),
rhs.span,
));
}
}
/// The other half: a name that promises a register, driven by something that
/// is not one.
fn unregistered(ctx: &LintContext, settings: &Settings, out: &mut Vec<Violation>) {
let mut judge = |lhs: &Expr| {
let Some(target) = plain_name(lhs) else { return };
if settings.waives(target) {
return;
}
if base_of(target, &settings.output).is_some_and(|base| !base.is_empty()) {
out.push(Violation::new(
NAME,
format!(
"`{target}` is named like a flip-flop output but is not driven by a \
nonblocking assignment in an `always_ff`"
),
lhs.span,
));
}
};
walk_items(ctx.file(), &mut |item| {
let ItemKind::ContAssign(assign) = &item.kind else { return };
for pair in &assign.assigns {
judge(&pair.lhs);
}
});
// A blocking assignment anywhere — in an `always_comb`, an `initial`, or
// inside the `always_ff` itself, which is the shape the rule most wants.
walk_all_stmts(ctx.file(), &mut |stmt| {
let StmtKind::Assign { lhs, op, .. } = &stmt.kind else { return };
if op == "<=" {
return;
}
judge(lhs);
});
}
/// The name of a plain identifier, or `None` for any other target.
fn plain_name(expr: &Expr) -> Option<&str> {
match &expr.kind {
ExprKind::Ident(name) => Some(name),
_ => None,
}
}
/// The part of `name` before its `_<suffix>[digits]` tail, or `None` when it
/// carries none of `suffixes`.
fn base_of<'a>(name: &'a str, suffixes: &[String]) -> Option<&'a str> {
let trimmed = name.trim_end_matches(|c: char| c.is_ascii_digit());
for suffix in suffixes {
if let Some(base) = trimmed.strip_suffix(suffix.as_str()) {
if let Some(base) = base.strip_suffix('_') {
return Some(base);
}
// `_q` on its own: a suffix with nothing in front of it.
if base.is_empty() && trimmed.len() == suffix.len() {
return Some("");
}
}
}
None
}
/// `` `_q`, `_r` or `_ff` `` — the suffix list, as a message says it.
fn one_of(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 => "a registered-output suffix".to_string(),
}
}
/// The source text of a span.
fn text_of<'a>(ctx: &'a LintContext, span: TextRange) -> &'a str {
ctx.source().get(span.as_range()).unwrap_or("")
}
/// The same text with every space taken out, so `!rst_ni` and `! rst_ni` are
/// one waiver rather than two.
fn squeeze(text: &str) -> String {
text.chars().filter(|c| !c.is_whitespace()).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
DffNameStyle.check(&LintContext::new(src, None))
}
fn with(src: &str, key: &str, raw: &str) -> Vec<Violation> {
let mut options = RuleOptions::new();
options.set_raw(NAME, key, raw).expect("accepted");
DffNameStyle.check(&LintContext::new(src, None).with_options(&options))
}
fn flop(body: &str) -> String {
format!("module m;\n always_ff @(posedge clk) begin\n {body}\n end\nendmodule\n")
}
#[test]
fn the_convention_is_clean() {
for body in [
"data_q <= data_d;",
"data_r <= data_n;",
"data_ff <= data_next;",
"data_reg <= data_d;",
"data_q2 <= data_d2;",
"data_q <= other_signal;",
"data_q <= a + b;",
] {
let src = flop(body);
assert!(violations(&src).is_empty(), "{body}: {:?}", violations(&src));
}
}
#[test]
fn flags_a_registered_name_without_a_suffix() {
let src = flop("data <= data_d;");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "data");
assert!(found[0].message.contains("`_q`"), "{}", found[0].message);
assert!(found[0].fix.is_none());
}
#[test]
fn flags_a_mismatched_pair_and_points_at_the_source() {
let src = flop("a_q <= b_n;");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "b_n");
assert!(found[0].message.contains("`a` is not `b`"), "{}", found[0].message);
}
#[test]
fn a_bare_suffix_names_nothing() {
let src = flop("_q <= data_d;");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(
found[0].message.contains("nothing but a flip-flop suffix"),
"{}",
found[0].message
);
}
#[test]
fn a_reset_branch_is_waived_whatever_its_spacing() {
for cond in ["!rst_ni", "! rst_ni", "flush_i", "!rst_ni || flush_i"] {
let src = flop(&format!("if ({cond}) data <= '0; else data_q <= data_d;"));
assert!(violations(&src).is_empty(), "{cond}: {:?}", violations(&src));
}
}
#[test]
fn a_condition_that_is_not_waived_is_still_judged() {
let src = flop("if (enable_i) data <= data_d;");
assert_eq!(violations(&src).len(), 1, "{:?}", violations(&src));
}
#[test]
fn a_memory_name_is_waived_by_the_default_pattern() {
for name in ["mem_array", "MEM_ARRAY", "Memory"] {
let src = flop(&format!("{name} <= data_d;"));
assert!(violations(&src).is_empty(), "{name}: {:?}", violations(&src));
}
}
#[test]
fn a_flip_flop_name_driven_by_anything_else_is_reported() {
let combinational = "module m;\n always_comb data_q = data_d;\nendmodule\n";
assert_eq!(violations(combinational).len(), 1, "{:?}", violations(combinational));
let continuous = "module m;\n assign data_q = data_d;\nendmodule\n";
assert_eq!(violations(continuous).len(), 1, "{:?}", violations(continuous));
let blocking_in_ff = flop("data_q = data_d;");
assert_eq!(violations(&blocking_in_ff).len(), 1, "{:?}", violations(&blocking_in_ff));
}
#[test]
fn a_plain_signal_driven_combinationally_is_nobodys_business() {
let src = "module m;\n assign data_d = a + b;\n always_comb next = 1;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_non_plain_target_is_not_judged() {
for body in ["data[0] <= data_d;", "s.f <= data_d;", "{a, b} <= data_d;"] {
let src = flop(body);
assert!(violations(&src).is_empty(), "{body}: {:?}", violations(&src));
}
}
#[test]
fn the_suffix_lists_are_configurable() {
let src = flop("data_ptr <= data_nxt;");
assert_eq!(violations(&src).len(), 1);
let mut options = RuleOptions::new();
options.set_raw(NAME, "output", "[\"ptr\"]").expect("accepted");
options.set_raw(NAME, "input", "[\"nxt\"]").expect("accepted");
let found = DffNameStyle.check(&LintContext::new(&src, None).with_options(&options));
assert!(found.is_empty(), "{found:?}");
}
#[test]
fn the_lhs_waiver_pattern_is_configurable() {
let src = flop("scratch <= data_d;");
assert_eq!(violations(&src).len(), 1);
assert!(with(&src, "waive_lhs_regex", "\"scratch.*\"").is_empty());
}
#[test]
fn the_waived_conditions_are_configurable() {
let src = flop("if (my_reset) data <= '0;");
assert_eq!(violations(&src).len(), 1);
assert!(with(&src, "waive_ifs_with_conditions", "[\"my_reset\"]").is_empty());
}
}
@@ -0,0 +1,157 @@
//! `disable-statement` — `disable` only a sequential block, or `disable fork`.
use std::collections::BTreeSet;
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::{ItemKind, SourceFile, StmtKind};
/// See [`Rule::doc`].
pub struct DisableStatement;
const NAME: &str = "disable-statement";
impl Rule for DisableStatement {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"`disable` a sequential block or a task, and write `disable fork` for processes"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn default_on(&self) -> bool {
false
}
fn doc(&self) -> &'static str {
"`disable label` terminates the named sequential block, and \
`disable fork` terminates the calling process's children (IEEE 1800 \
§9.6.2, §9.6.3). Naming a `fork` block instead of writing \
`disable fork` is the mistake this rule exists for: it reads as \
though it kills the forked processes and does something else \
entirely, and in the common `fork … join_none` idiom it kills \
nothing at all. Verible's `disable-statement` (\"Checks that there \
are no occurrences of `disable some_label` if label refers to \
non-sequential blocks.\", **disabled** by default) is the same rule \
and the same default.\n\n\
What counts as a valid target here is the label of a \
`begin : name` block, a statement label (`name : begin`) — and, \
**wider than Verible**, the name of a task or function declared in \
the same file, because `disable task_name` is a legal and ordinary \
thing to write (§9.6.2) and reporting it would be a false positive. \
A name lucisv cannot see at all — a block in another file, a label a \
macro produces — is therefore reported; that is the rule's one \
false-positive mode and the reason it ships off. No automatic fix: \
whether the author meant `disable fork` or a different label is not \
something the source says."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let targets = disableable(ctx.file());
let mut out = Vec::new();
walk_all_stmts(ctx.file(), &mut |stmt| {
let StmtKind::Disable(name) = &stmt.kind else { return };
// `disable fork` is the keyword form, not a label.
if name == "fork" || targets.contains(name.as_str()) {
return;
}
out.push(Violation::new(
NAME,
format!(
"`disable {name}` names no sequential block or task; write `disable fork` \
to stop forked processes"
),
stmt.span,
));
});
out
}
}
/// Every name a `disable` may legitimately mention in this file: the labels of
/// sequential blocks and statement labels, plus the tasks and functions the
/// file declares.
fn disableable(file: &SourceFile) -> BTreeSet<String> {
let mut out = BTreeSet::new();
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
StmtKind::Block { label: Some(label), .. } => {
out.insert(label.clone());
}
StmtKind::Labeled { name, stmt: inner, .. } => {
if matches!(inner.kind, StmtKind::Block { .. }) {
out.insert(name.clone());
}
}
_ => {}
});
walk_items(file, &mut |item| match &item.kind {
ItemKind::Task(decl) => {
out.insert(decl.name.clone());
}
ItemKind::Function(decl) => {
out.insert(decl.name.clone());
}
_ => {}
});
out
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
DisableStatement.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_disable_of_a_fork_label() {
let src = "module m;\n initial begin\n fork : threads\n join_none\n \
disable threads;\n end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "disable threads;");
assert!(found[0].fix.is_none());
}
#[test]
fn disable_fork_is_the_spelling_the_rule_asks_for() {
let src = "module m;\n initial begin\n fork\n join_none\n disable fork;\n \
end\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_sequential_block_label_is_a_valid_target() {
let src = "module m;\n initial begin : seq\n disable seq;\n end\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_statement_label_on_a_block_counts_too() {
let src = "module m;\n initial begin\n outer : begin\n disable outer;\n \
end\n end\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_task_of_the_same_file_is_a_legal_target() {
let src = "module m;\n task automatic t();\n endtask\n initial begin\n \
disable t;\n end\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_name_this_file_does_not_declare_is_reported() {
let src = "module m;\n initial begin\n disable somewhere_else;\n end\nendmodule\n";
assert_eq!(violations(src).len(), 1);
}
}
@@ -0,0 +1,194 @@
//! `endif-comment` — say which `` `ifdef `` an `` `endif `` closes.
use crate::context::LintContext;
use crate::preproc::{directive_operand, directive_word};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use vlog_parser::span::TextRange;
use vlog_parser::token::Token;
/// See [`Rule::doc`].
pub struct EndifComment;
const NAME: &str = "endif-comment";
impl Rule for EndifComment {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name the condition an `` `endif `` closes in a comment beside it"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn default_on(&self) -> bool {
false
}
fn fix(&self) -> Option<Applicability> {
Some(Applicability::Safe)
}
fn doc(&self) -> &'static str {
"A bare `` `endif `` two hundred lines below its `` `ifdef `` tells \
the reader nothing: which condition just ended, and whether the \
nesting is what they think it is, both take a scroll to answer. \
`` `endif // SYNTHESIS `` answers them in place, which is the same \
argument `mismatched-labels` makes for `end : name`. Verible's \
`endif-comment` (\"Checks that a Verilog `` `endif `` directive is \
followed by a matching comment.\", **disabled** by default) is the \
same rule and the same default.\n\n\
The comment must **name the condition** — any comment on the \
`` `endif ``'s own line that writes the macro name as a word will \
do, so `// SYNTHESIS`, `` // `ifdef SYNTHESIS `` and `/* SYNTHESIS \
*/` all pass. An `` `endif `` whose `` `ifdef `` lucisv cannot see \
(an unbalanced file, a condition opened in an included header) is \
left alone: there is no name to ask for.\n\n\
The fix is **safe** and only offered where there is no comment at \
all: it appends `` // <name> `` after the directive, adding text and \
removing none. A comment that is there but names something else is \
reported without a fix — rewriting somebody's words is not a repair."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut open: Vec<Option<String>> = Vec::new();
let mut out = Vec::new();
for token in ctx.tokens() {
match directive_word(token) {
Some("ifdef") | Some("ifndef") => {
open.push(directive_operand(token).map(str::to_string))
}
Some("endif") => {
// An `endif` with nothing open is an unbalanced file, or a
// condition opened in an included header: no name to ask
// for, so nothing to say.
let Some(Some(name)) = open.pop() else { continue };
if let Some(violation) = judge(ctx, token, &name) {
out.push(violation);
}
}
_ => {}
}
}
out
}
}
/// The finding this `` `endif `` earns, or `None` when its comment names the
/// condition.
fn judge(ctx: &LintContext, token: &Token, name: &str) -> Option<Violation> {
let beside: Vec<&str> = ctx
.comments()
.into_iter()
.filter(|comment| comment.line == token.line && comment.span.start >= token.span.end)
.map(|comment| comment.text.as_str())
.collect();
if beside.iter().any(|text| names(text, name)) {
return None;
}
let violation = Violation::new(
NAME,
format!("`endif` does not say what it closes; write `// {name}`"),
token.span,
);
match beside.is_empty() {
true => Some(violation.with_fix(Fix::safe(vec![(
TextRange::new(token.span.end, token.span.end),
format!(" // {name}"),
)]))),
// There is a comment; it just names something else. Replacing it would
// throw away what somebody wrote.
false => Some(violation),
}
}
/// True when `text` writes `name` as a whole word.
fn names(text: &str, name: &str) -> bool {
let is_part = |c: char| c == '_' || c == '$' || c.is_ascii_alphanumeric();
let mut rest = text;
while let Some(at) = rest.find(name) {
let before = rest[..at].chars().next_back();
let after = rest[at + name.len()..].chars().next();
if !before.is_some_and(is_part) && !after.is_some_and(is_part) {
return true;
}
rest = &rest[at + name.len()..];
}
false
}
#[cfg(test)]
mod tests {
use super::*;
use crate::violation::apply_fixes;
fn violations(src: &str) -> Vec<Violation> {
EndifComment.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_bare_endif_and_offers_the_comment() {
let src = "`ifdef SYNTHESIS\nmodule m;\nendmodule\n`endif\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "`endif");
let fixed = apply_fixes(src, &found, false);
assert_eq!(fixed.output, "`ifdef SYNTHESIS\nmodule m;\nendmodule\n`endif // SYNTHESIS\n");
assert!(violations(&fixed.output).is_empty(), "the fix settles");
}
#[test]
fn a_naming_comment_of_any_shape_passes() {
for comment in ["// SYNTHESIS", "// `ifdef SYNTHESIS", "/* SYNTHESIS */", "//SYNTHESIS"] {
let src = format!("`ifdef SYNTHESIS\nmodule m;\nendmodule\n`endif {comment}\n");
assert!(violations(&src).is_empty(), "{comment}: {:?}", violations(&src));
}
}
#[test]
fn a_comment_naming_something_else_is_reported_without_a_fix() {
let src = "`ifdef SYNTHESIS\nmodule m;\nendmodule\n`endif // done\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].fix.is_none(), "somebody's comment is not ours to rewrite");
}
#[test]
fn a_name_that_only_contains_the_condition_is_not_a_match() {
let src = "`ifdef SYN\nmodule m;\nendmodule\n`endif // SYNTHESIS\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn nesting_pairs_each_endif_with_its_own_condition() {
let src = "`ifdef A\n`ifdef B\nmodule m;\nendmodule\n`endif\n`endif\n";
let found = violations(src);
assert_eq!(found.len(), 2, "{found:?}");
assert!(found[0].message.contains("// B"), "{}", found[0].message);
assert!(found[1].message.contains("// A"), "{}", found[1].message);
}
#[test]
fn an_ifndef_and_an_else_are_handled_like_the_ifdef() {
let src = "`ifndef A\nmodule m;\nendmodule\n`else\nmodule n;\nendmodule\n`endif\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("// A"), "{}", found[0].message);
}
#[test]
fn an_unbalanced_endif_has_no_name_to_ask_for() {
assert!(violations("`endif\nmodule m;\nendmodule\n").is_empty());
}
#[test]
fn a_comment_on_the_next_line_is_not_beside_the_endif() {
let src = "`ifdef A\nmodule m;\nendmodule\n`endif\n// A\n";
assert_eq!(violations(src).len(), 1);
}
}
@@ -2,7 +2,8 @@
//! 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;
@@ -36,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> {
@@ -47,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,
));
});
@@ -61,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::*;
@@ -109,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,149 @@
//! `explicit-function-lifetime` — say `automatic` or `static` outside a class.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_items_scoped, ItemScope};
use vlog_parser::ast::ItemKind;
/// See [`Rule::doc`].
pub struct ExplicitFunctionLifetime;
const NAME: &str = "explicit-function-lifetime";
/// The two words that state a lifetime, wherever a subroutine writes them.
pub(crate) const LIFETIMES: [&str; 2] = ["automatic", "static"];
impl Rule for ExplicitFunctionLifetime {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"state `automatic` or `static` on a function declared outside a class"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A function with no stated lifetime is `static` in a module and \
`automatic` in a class (IEEE 1800 §13.4.2), and a static function's \
locals are shared by every call — so one written without the keyword \
is a re-entrancy bug waiting for the second caller, and a reader \
cannot tell whether the author knew. Writing the word costs nine \
characters and removes the question. Verible's \
`explicit-function-lifetime` (\"Checks that every function declared \
outside of a class is declared with an explicit lifetime.\", enabled \
by default) is the same rule and the same default; a class method is \
exempt in both, because there the default is already the safe one.\n\n\
A body-less **prototype** — `extern function f;`, a `pure virtual`, a \
DPI import — is not judged: it declares no locals, and the definition \
that follows is where the lifetime belongs. Nor is an **out-of-body \
definition** (`function cls::f(...); … endfunction`), which is \
**wider than Verible**: lexically it sits outside the class, and \
Verible reports it, but it *is* a class method and its lifetime is \
already automatic — 948 of the 960 opentitan findings this rule and \
its task twin produced before the exemption were exactly that shape. \
No automatic fix: \
`automatic` is the answer a reader expects and `static` is what the \
language would have picked, so choosing between them changes what \
the code does."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items_scoped(ctx.file(), &mut |scope, item| {
let ItemKind::Function(decl) = &item.kind else { return };
// An out-of-body definition (`function cls::f(...)`) is a class
// method written outside the class body; `scope` is non-empty for
// exactly those.
if scope == ItemScope::Class
|| !decl.scope.is_empty()
|| decl.is_prototype
|| decl.dpi.is_some()
{
return;
}
if decl.qualifiers.iter().any(|q| LIFETIMES.contains(&q.text.as_str())) {
return;
}
out.push(Violation::new(
NAME,
format!(
"function `{}` has no explicit lifetime; write `automatic` or `static`",
decl.name
),
decl.name_span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ExplicitFunctionLifetime.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_module_function_and_points_at_its_name() {
let src = "module m;\n function int f(int x);\n return x;\n endfunction\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "f");
assert!(found[0].fix.is_none());
}
#[test]
fn either_keyword_satisfies_the_rule() {
for kw in ["automatic", "static"] {
let src = format!(
"module m;\n function {kw} int f(int x);\n return x;\n endfunction\nendmodule\n"
);
assert!(violations(&src).is_empty(), "{kw}: {:?}", violations(&src));
}
}
#[test]
fn a_class_method_is_exempt() {
let src = "class c;\n function int f(int x);\n return x;\n endfunction\nendclass\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_package_or_file_scope_function_is_judged() {
let pkg = "package p;\n function int f();\n return 0;\n endfunction\nendpackage\n";
assert_eq!(violations(pkg).len(), 1);
let top = "function int f();\n return 0;\nendfunction\n";
assert_eq!(violations(top).len(), 1);
}
#[test]
fn a_prototype_declares_no_locals() {
let src = "class c;\n extern function int f();\nendclass\n\
import \"DPI-C\" function int c_f(input int x);\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
/// An `extern` method defined outside its class body is still a class
/// method; Verible reports it, lucisv does not (see the rule's doc).
#[test]
fn an_out_of_body_definition_is_a_class_method() {
let src = "class c;\n extern function int f();\nendclass\n\
function c::f();\n return 0;\nendfunction\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_class_nested_in_a_package_is_still_a_class() {
let src = "package p;\n class c;\n function int f();\n return 0;\n \
endfunction\n endclass\nendpackage\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
}
@@ -0,0 +1,120 @@
//! `explicit-task-lifetime` — say `automatic` or `static` outside a class.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::rules::explicit_function_lifetime::LIFETIMES;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_items_scoped, ItemScope};
use vlog_parser::ast::ItemKind;
/// See [`Rule::doc`].
pub struct ExplicitTaskLifetime;
const NAME: &str = "explicit-task-lifetime";
impl Rule for ExplicitTaskLifetime {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"state `automatic` or `static` on a task declared outside a class"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"The same argument `explicit-function-lifetime` makes, and worse: a \
task can block, so a `static` one is routinely called from two \
processes at once and its locals are one set of variables shared \
between them (IEEE 1800 §13.4.2). A task with no stated lifetime is \
`static` in a module and `automatic` in a class, and nothing in the \
source says which the author meant. Verible's \
`explicit-task-lifetime` (\"Checks that every task declared outside \
of a class is declared with an explicit lifetime.\", enabled by \
default) is the same rule and the same default.\n\n\
A body-less prototype, a DPI import and an out-of-body definition \
(`task cls::t(); … endtask`) are not judged, and no automatic fix is \
offered — all for the reasons `explicit-function-lifetime` gives."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items_scoped(ctx.file(), &mut |scope, item| {
let ItemKind::Task(decl) = &item.kind else { return };
// An out-of-body definition (`function cls::f(...)`) is a class
// method written outside the class body; `scope` is non-empty for
// exactly those.
if scope == ItemScope::Class
|| !decl.scope.is_empty()
|| decl.is_prototype
|| decl.dpi.is_some()
{
return;
}
if decl.qualifiers.iter().any(|q| LIFETIMES.contains(&q.text.as_str())) {
return;
}
out.push(Violation::new(
NAME,
format!(
"task `{}` has no explicit lifetime; write `automatic` or `static`",
decl.name
),
decl.name_span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ExplicitTaskLifetime.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_module_task_and_points_at_its_name() {
let src = "module m;\n task t();\n endtask\nendmodule\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 either_keyword_satisfies_the_rule() {
for kw in ["automatic", "static"] {
let src = format!("module m;\n task {kw} t();\n endtask\nendmodule\n");
assert!(violations(&src).is_empty(), "{kw}: {:?}", violations(&src));
}
}
#[test]
fn a_class_method_is_exempt() {
assert!(violations("class c;\n task t();\n endtask\nendclass\n").is_empty());
}
#[test]
fn a_function_is_the_other_rules_business() {
let src = "module m;\n function int f();\n return 0;\n endfunction\nendmodule\n";
assert!(violations(src).is_empty());
}
#[test]
fn a_prototype_declares_no_locals() {
assert!(violations("class c;\n extern task t();\nendclass\n").is_empty());
}
#[test]
fn an_out_of_body_definition_is_a_class_method() {
let src = "class c;\n extern task t();\nendclass\ntask c::t();\nendtask\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
}
@@ -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,129 @@
//! `forbid-line-continuations` — no `\` breaking a string literal.
use crate::context::LintContext;
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 ForbidLineContinuations;
const NAME: &str = "forbid-line-continuations";
impl Rule for ForbidLineContinuations {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not break a string literal across lines with a backslash continuation"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A string broken with a backslash at end of line keeps every character \
of the next line, its leading indentation included — so re-indenting \
the file changes the string's *value*, and a formatter, a rebase or \
a careless editor silently alters what the design prints. It is also \
invisible: the second line looks like code. The portable spelling is \
string concatenation, `{\"first \", \"second\"}`, which the compiler \
folds and nothing can re-indent. Verible's \
`forbid-line-continuations` (\"Checks that there are no occurrences \
of `\\` when breaking string literal lines.\", enabled by default) is \
the same rule and the same default.\n\n\
Only a continuation *inside a string literal* is judged: a `` `define \
`` body written across lines with a `\\` is the only way the language \
gives to write a multi-line macro, and this rule says nothing about \
it. No automatic fix — replacing the continuation with a \
concatenation has to decide where the whitespace of the second line \
belongs, and only the author knows."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
for token in ctx.tokens().iter().filter(|t| t.kind == TokenKind::String) {
for offset in continuations(&token.text) {
let start = token.span.start + offset as u32;
out.push(Violation::new(
NAME,
"string literal is broken with a `\\` line continuation; write \
`{\"...\", \"...\"}` instead",
TextRange::new(start, start + 1),
));
}
}
out
}
}
/// Byte offsets of every backslash that continues `text` onto the next line.
///
/// A `\\` is an escaped backslash and continues nothing, so the scan steps
/// over both characters — otherwise `"a\\\\\n"` would be read as a
/// continuation of its own escape.
fn continuations(text: &str) -> Vec<usize> {
let bytes = text.as_bytes();
let mut out = Vec::new();
let mut i = 0usize;
while i + 1 < bytes.len() {
if bytes[i] != b'\\' {
i += 1;
continue;
}
match bytes[i + 1] {
b'\n' => out.push(i),
// `\r\n` counts too: the file's line endings are not the point.
b'\r' if bytes.get(i + 2) == Some(&b'\n') => out.push(i),
_ => {}
}
i += 2;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ForbidLineContinuations.check(&LintContext::new(src, None))
}
#[test]
fn flags_the_backslash_that_breaks_a_string() {
let src = "module m;\n initial $display(\"a long \\\n string\");\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "\\");
assert!(found[0].fix.is_none());
}
#[test]
fn a_one_line_string_is_clean() {
let src = "module m;\n initial $display(\"a long string\");\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn an_ordinary_escape_is_not_a_continuation() {
let src = "module m;\n initial $display(\"tab\\t quote\\\" slash\\\\ end\");\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_multi_line_define_is_not_a_string() {
let src = "`define TWO_LINES \\\n wire a; \\\n wire b;\nmodule m;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn every_break_of_one_string_is_reported() {
let src = "module m;\n initial $display(\"a \\\n b \\\n c\");\nendmodule\n";
assert_eq!(violations(src).len(), 2, "{:?}", violations(src));
}
}
@@ -0,0 +1,152 @@
//! `forbidden-macro` — macros a project has decided nothing should call.
use crate::context::LintContext;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::preproc::macro_name;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct ForbiddenMacro;
const NAME: &str = "forbidden-macro";
/// The one option, spelled as this rule's own since Verible's list is a
/// compile-time constant with no parameter to change it.
const OPTIONS: &[OptionSpec] = &[OptionSpec {
name: "macros",
kind: OptionKind::List,
// Verible's own list, name for name: `uvm_warning` and nothing else.
default: OptionDefault::List(&["uvm_warning"]),
doc: "macro names nothing may invoke, with or without the leading backtick",
}];
impl Rule for ForbiddenMacro {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not invoke a forbidden macro"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn options(&self) -> &'static [OptionSpec] {
OPTIONS
}
fn doc(&self) -> &'static str {
"Verible's `forbidden-macro` (\"Checks that no forbidden macro calls \
are used.\", enabled by default) ships one name: `` `uvm_warning ``. \
A UVM warning is a message nothing acts on — the test keeps running, \
the regression stays green, and the condition that produced it is \
rediscovered later by somebody reading a log. The UVM style guides \
that ban it want the choice made at the point of failure: \
`` `uvm_error `` if the test should fail, `` `uvm_info `` if it \
really is only information.\n\n\
Verible hard-codes its list; lucisv makes it the `macros` option, so \
a project that has banned `` `uvm_fatal `` or a macro of its own \
writes them down instead of asking for a new rule. An entry may be \
written with or without its backtick — `\"uvm_warning\"` and \
`` \"`uvm_warning\"`` name the same macro. An empty list turns the \
rule off as surely as `--ignore` does. No automatic fix: which \
replacement is right is exactly the judgment the rule is asking for."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let forbidden: Vec<String> = ctx
.option_list(NAME, "macros")
.iter()
.map(|entry| entry.trim_start_matches('`').to_string())
.collect();
if forbidden.is_empty() {
return Vec::new();
}
ctx.tokens()
.iter()
.filter_map(|token| {
let name = macro_name(token)?;
if !forbidden.iter().any(|entry| entry == name) {
return None;
}
// The backtick and the name, not the arguments after them.
let end = token.span.start + 1 + name.len() as u32;
Some(Violation::new(
NAME,
format!("`` `{name} `` is a forbidden macro"),
TextRange::new(token.span.start, end),
))
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
ForbiddenMacro.check(&LintContext::new(src, None))
}
fn with(src: &str, raw: &str) -> Vec<Violation> {
let mut options = RuleOptions::new();
options.set_raw(NAME, "macros", raw).expect("accepted");
ForbiddenMacro.check(&LintContext::new(src, None).with_options(&options))
}
#[test]
fn flags_the_default_name_and_underlines_the_invocation() {
let src = "module m;\n initial `uvm_warning(\"A\", \"B\");\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "`uvm_warning");
assert!(found[0].fix.is_none());
}
#[test]
fn the_neighbouring_uvm_macros_are_left_alone() {
let src = "module m;\n\
\x20 initial begin\n\
\x20 `uvm_info(\"A\", \"B\", UVM_LOW)\n\
\x20 `uvm_error(\"A\", \"B\")\n\
\x20 `uvm_fatal(\"A\", \"B\")\n\
\x20 end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_name_that_only_starts_the_same_is_not_a_hit() {
let src = "module m;\n initial `uvm_warning_once(\"A\");\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn an_identifier_or_a_string_with_the_name_in_it_is_not_an_invocation() {
let src = "module m;\n wire uvm_warning;\n initial $display(\"`uvm_warning\");\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn the_option_replaces_the_list_and_accepts_either_spelling() {
let src = "module m;\n initial begin\n `uvm_warning(\"A\", \"B\")\n \
`my_macro(1)\n end\nendmodule\n";
assert_eq!(with(src, "[\"my_macro\"]").len(), 1);
assert_eq!(with(src, "[\"`my_macro\"]").len(), 1);
assert_eq!(with(src, "[\"uvm_warning\", \"my_macro\"]").len(), 2);
}
#[test]
fn an_empty_list_reports_nothing() {
let src = "module m;\n initial `uvm_warning(\"A\", \"B\");\nendmodule\n";
assert!(with(src, "[]").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,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);
}
}
@@ -1,6 +1,7 @@
//! `invalid-system-task-function` — system tasks nothing should still call.
use crate::context::LintContext;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
@@ -11,6 +12,26 @@ pub struct InvalidSystemTaskFunction;
const NAME: &str = "invalid-system-task-function";
/// The list, as an option — Verible hard-codes it in the source file it calls
/// `forbidden-symbol`, which is this rule under its implementation's name.
const OPTIONS: &[OptionSpec] = &[OptionSpec {
name: "symbols",
kind: OptionKind::List,
default: OptionDefault::List(&[
"$psprintf",
"$random",
"$srandom",
"$dist_chi_square",
"$dist_erlang",
"$dist_exponential",
"$dist_normal",
"$dist_poisson",
"$dist_t",
"$dist_uniform",
]),
doc: "system task and function names nothing may call, `$` included",
}];
/// The forbidden names and what to write instead — Verible's list
/// (`invalid-system-task-function`), name for name.
///
@@ -46,6 +67,10 @@ impl Rule for InvalidSystemTaskFunction {
Severity::Warning
}
fn options(&self) -> &'static [OptionSpec] {
OPTIONS
}
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 \
@@ -55,23 +80,32 @@ impl Rule for InvalidSystemTaskFunction {
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. \
exactly this list, and lucisv names the replacement in the message.\n\n\
**There is no separate `forbidden-symbol` rule**, here or in Verible: \
`forbidden-symbol` is the name of the *source file* Verible \
implements this rule in, and the rule it registers is this one. The \
list Verible hard-codes there is lucisv's `symbols` option, so a \
project that wants `$stop` or a vendor task on it writes it down \
instead of getting a second rule that would fire twice on \
`$psprintf`. A name the default list knows is reported with its \
replacement; one a project adds is reported without, because only \
the project knows what to use instead.\n\n\
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> {
let forbidden = ctx.option_list(NAME, "symbols");
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,
))
let name = forbidden.iter().find(|name| *name == &token.text)?;
let message = match FORBIDDEN.iter().find(|(known, _)| known == name) {
Some((_, instead)) => format!("`{name}` is forbidden; use `{instead}`"),
None => format!("`{name}` is forbidden by this project's settings"),
};
Some(Violation::new(NAME, message, token.span))
})
.collect()
}
@@ -129,4 +163,36 @@ mod tests {
let src = "module m;\n initial $display(\"call $random here\");\nendmodule\n";
assert!(violations(src).is_empty());
}
/// The `symbols` option is `forbidden-symbol`'s list, folded into the one
/// rule Verible actually registers.
#[test]
fn the_option_replaces_the_list() {
use crate::options::RuleOptions;
let src = "module m;\n initial begin\n a = $random();\n $stop;\n end\nendmodule\n";
assert_eq!(violations(src).len(), 1, "the default list has `$random` and not `$stop`");
let mut options = RuleOptions::new();
options.set_raw(NAME, "symbols", "[\"$stop\"]").expect("accepted");
let found =
InvalidSystemTaskFunction.check(&LintContext::new(src, None).with_options(&options));
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("$stop"), "{}", found[0].message);
assert!(
found[0].message.contains("this project's settings"),
"a name with no known replacement says so: {}",
found[0].message
);
}
#[test]
fn an_empty_list_reports_nothing() {
use crate::options::RuleOptions;
let src = "module m;\n initial a = $random();\nendmodule\n";
let mut options = RuleOptions::new();
options.set_raw(NAME, "symbols", "[]").expect("accepted");
assert!(InvalidSystemTaskFunction
.check(&LintContext::new(src, None).with_options(&options))
.is_empty());
}
}
@@ -0,0 +1,104 @@
//! `legacy-generate-region` — the `generate … endgenerate` wrapper.
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;
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct LegacyGenerateRegion;
const NAME: &str = "legacy-generate-region";
impl Rule for LegacyGenerateRegion {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"write generate constructs without a `generate … endgenerate` region"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn default_on(&self) -> bool {
false
}
fn doc(&self) -> &'static str {
"Verilog-2001 required generate constructs to sit inside a \
`generate … endgenerate` region. SystemVerilog does not (IEEE 1800 \
§27.3): an `if`, `for` or `case` generate is a module item like any \
other, and the wrapper adds a level of indentation, a keyword pair to \
match and nothing else. Verible's `legacy-generate-region` (\"Checks \
that there are no generate regions.\", **disabled** by default) is \
the same rule and lucisv ships it off for the same reason: a codebase \
that must still compile as Verilog-2001 needs the region, and only \
the project knows which one it is.\n\n\
No automatic fix. Deleting the two keywords is a whole-region edit \
that re-indents everything between them, which is the formatter's \
job and not a lint fix's."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
if !matches!(item.kind, ItemKind::GenerateRegion { .. }) {
return;
}
// Point at the `generate` keyword, which is where the region opens.
let kw = TextRange::new(item.span.start, item.span.start + 8);
out.push(Violation::new(
NAME,
"`generate … endgenerate` region is not needed in SystemVerilog",
kw,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
LegacyGenerateRegion.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_region_and_points_at_its_keyword() {
let src = "module m;\n generate\n if (A) begin : g\n wire a;\n end\n \
endgenerate\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "generate");
assert!(found[0].fix.is_none());
}
#[test]
fn a_generate_construct_without_the_wrapper_is_what_the_rule_wants() {
let src = "module m;\n if (A) begin : g\n wire a;\n end\n\
\x20 for (genvar i = 0; i < 2; i++) begin : l\n wire b;\n end\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn every_region_of_a_file_is_reported() {
let src = "module a;\n generate\n endgenerate\nendmodule\n\
module b;\n generate\n endgenerate\nendmodule\n";
assert_eq!(violations(src).len(), 2);
}
#[test]
fn a_nested_region_is_reported_too() {
let src = "module m;\n generate\n if (A) begin : g\n generate\n \
endgenerate\n end\n endgenerate\nendmodule\n";
assert_eq!(violations(src).len(), 2, "{:?}", violations(src));
}
}
@@ -0,0 +1,106 @@
//! `legacy-genvar-declaration` — declare the loop variable in the `for` header.
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 LegacyGenvarDeclaration;
const NAME: &str = "legacy-genvar-declaration";
impl Rule for LegacyGenvarDeclaration {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"declare a genvar in the `for` header, not in a separate statement"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn default_on(&self) -> bool {
false
}
fn doc(&self) -> &'static str {
"Verilog-2001 made a `genvar` a module-scope declaration, so a loop \
variable outlived the loop that used it and two loops sharing one \
`genvar i;` read as if they shared a variable. SystemVerilog lets the \
header declare it — `for (genvar i = 0; i < N; i++)` — which scopes \
the name to the loop and makes each loop's variable its own (IEEE \
1800 §27.4). Verible's `legacy-genvar-declaration` (\"Checks that \
there are no separate `genvar` declarations.\", **disabled** by \
default) is the same rule, and lucisv ships it off for the same \
reason: a Verilog-2001 codebase has no other spelling available.\n\n\
No automatic fix: moving the declaration means editing every `for` \
header that used it, and only the author knows which ones those are."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::Genvar(names) = &item.kind else { return };
for name in names {
out.push(Violation::new(
NAME,
format!(
"genvar `{}` is declared outside a `for` header; write \
`for (genvar {} = …)`",
name.text, name.text
),
name.span,
));
}
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
LegacyGenvarDeclaration.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_separate_declaration_and_points_at_the_name() {
let src = "module m;\n genvar i;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "i");
assert!(found[0].message.contains("`i`"), "{}", found[0].message);
assert!(found[0].fix.is_none());
}
#[test]
fn every_name_of_one_declaration_is_reported() {
assert_eq!(violations("module m;\n genvar i, j, k;\nendmodule\n").len(), 3);
}
#[test]
fn a_header_declaration_is_what_the_rule_wants() {
let src = "module m;\n for (genvar i = 0; i < 2; i++) begin : g\n wire a;\n end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn an_ordinary_variable_is_not_a_genvar() {
assert!(violations("module m;\n integer i;\n int j;\nendmodule\n").is_empty());
}
#[test]
fn a_declaration_inside_a_generate_region_is_reached() {
let src = "module m;\n generate\n genvar i;\n endgenerate\nendmodule\n";
assert_eq!(violations(src).len(), 1);
}
}
+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,161 @@
//! `macro-string-concatenation` — `` `` `` inside a plain string does nothing.
use crate::context::LintContext;
use crate::preproc::directive_word;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct MacroStringConcatenation;
const NAME: &str = "macro-string-concatenation";
impl Rule for MacroStringConcatenation {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not write the `` `` `` concatenation operator inside a plain string"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn default_on(&self) -> bool {
false
}
fn doc(&self) -> &'static str {
"Inside a `` `define `` body, `` `` `` glues two tokens together and \
`` `\" `` opens a string the preprocessor still looks inside \
(IEEE 1800 §22.5.1). Written inside an *ordinary* `\"…\"` string the \
operator is not an operator at all — the preprocessor does not \
expand anything in a plain string literal, so the two backticks end \
up in the output text and the macro silently produces `` a``b `` \
where the author expected `ab`. Verible's \
`macro-string-concatenation` (\"Concatenation will not be evaluated \
here. Use `\\\"...`\\\" instead.\", **disabled** by default) reports \
the same shape, and lucisv ships it off for the same reason: it is a \
narrow mistake, and a project with no macro-built strings never meets \
it.\n\n\
Only a `` `define `` body is scanned, and only its plain string \
literals — a `` `\"…`\" `` region is exactly the correct spelling and \
is skipped. No automatic fix: turning `\"…\"` into `` `\"…`\" `` \
changes what the macro expands to, which is the repair but not one a \
linter should make unasked."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
for token in ctx.tokens() {
if directive_word(token) != Some("define") {
continue;
}
for offset in concatenations_in_plain_strings(&token.text) {
let start = token.span.start + offset as u32;
out.push(Violation::new(
NAME,
"token concatenation inside a plain string literal is not evaluated; \
write the string as `\"...`\"",
TextRange::new(start, start + 2),
));
}
}
out
}
}
/// Byte offsets of every `` `` `` written inside a plain `"…"` literal of
/// `text`, in source order.
///
/// A `` `"…`" `` region — the spelling that *does* work — is skipped whole,
/// which is what keeps the correct form from being reported as the mistake.
fn concatenations_in_plain_strings(text: &str) -> Vec<usize> {
let bytes = text.as_bytes();
let mut out = Vec::new();
let mut i = 0usize;
while i < bytes.len() {
if bytes[i] == b'`' && bytes.get(i + 1) == Some(&b'"') {
i = match find(bytes, i + 2, b"`\"") {
Some(end) => end + 2,
None => break,
};
continue;
}
if bytes[i] != b'"' {
i += 1;
continue;
}
let mut j = i + 1;
while j < bytes.len() && bytes[j] != b'"' {
if bytes[j] == b'\\' {
j += 1;
}
if bytes.get(j) == Some(&b'`') && bytes.get(j + 1) == Some(&b'`') {
out.push(j);
j += 1;
}
j += 1;
}
i = j + 1;
}
out
}
/// The offset of the next `needle` at or after `from`.
fn find(bytes: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
(from..bytes.len().saturating_sub(needle.len() - 1))
.find(|&i| &bytes[i..i + needle.len()] == needle)
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
MacroStringConcatenation.check(&LintContext::new(src, None))
}
#[test]
fn flags_the_operator_and_underlines_it() {
let src = "`define GLUE(a, b) $display(\"a``b\")\nmodule m;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "``");
assert!(found[0].fix.is_none());
}
#[test]
fn the_macro_quoted_spelling_is_the_correct_one() {
let src = "`define GLUE(a, b) $display(`\"a``b`\")\nmodule m;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_define_with_no_string_is_silent() {
let src = "`define GLUE(a, b) a``b\nmodule m;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_plain_string_outside_a_define_is_not_this_rules_business() {
let src = "module m;\n initial $display(\"a``b\");\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn every_occurrence_of_one_define_is_reported() {
let src = "`define G(a, b, c) $display(\"a``b\", \"b``c\")\nmodule m;\nendmodule\n";
assert_eq!(violations(src).len(), 2, "{:?}", violations(src));
}
#[test]
fn an_escaped_quote_does_not_end_the_string_early() {
let src = "`define G(a) $display(\"x\\\"y``z\")\nmodule m;\nendmodule\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
}
@@ -141,6 +141,9 @@ fn item_labels(out: &mut Vec<Violation>, item: &Item) {
}
}
ItemKind::GenFor(gen_for) => check_gen_block(out, &gen_for.body),
// A bare `begin … end` standing as an item (§36.1) is the same node
// without a header: its label pair is checked exactly like an arm's.
ItemKind::GenBlock(block) => check_gen_block(out, block),
ItemKind::GenCase(gen_case) => {
for case_item in &gen_case.items {
check_gen_block(out, &case_item.body);
@@ -285,6 +288,23 @@ mod tests {
assert_eq!(violations(generate).len(), 1, "{:?}", violations(generate));
}
#[test]
fn a_bare_block_at_module_scope_is_checked_like_a_generate_arm() {
// §36.1: the block is a node now, so its own footer is checked. Not
// legal at module scope at all (`module-begin-block` says so), but a
// mismatched footer is the compile error this rule exists for.
let src = "module m;\n\
begin : fetch\n\
wire a;\n\
end : decode\n\
endmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "decode");
let ok = "module m;\n begin : fetch\n wire a;\n end : fetch\nendmodule\n";
assert!(violations(ok).is_empty(), "{:?}", violations(ok));
}
#[test]
fn a_nested_block_is_matched_against_its_own_header() {
let src = "module m;\n\
+37
View File
@@ -7,20 +7,42 @@
//! `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 create_object_name_match;
pub mod dff_name_style;
pub mod disable_statement;
pub mod duplicate_declaration;
pub mod empty_item;
pub mod endif_comment;
pub mod enum_name_style;
pub mod explicit_begin;
pub mod explicit_function_lifetime;
pub mod explicit_function_task_parameter_type;
pub mod explicit_parameter_storage_type;
pub mod explicit_task_lifetime;
pub mod forbid_consecutive_null_statements;
pub mod forbid_defparam;
pub mod forbid_line_continuations;
pub mod forbid_negative_array_dim;
pub mod forbidden_macro;
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 legacy_generate_region;
pub mod legacy_genvar_declaration;
pub mod line_length;
pub mod macro_name_style;
pub mod macro_string_concatenation;
pub mod mismatched_labels;
pub mod module_begin_block;
pub mod module_filename;
pub mod module_name_style;
pub mod module_parameter;
@@ -28,18 +50,33 @@ pub mod module_port;
pub mod multiply_driven;
pub mod no_tabs;
pub mod no_trailing_whitespace;
pub mod numeric_format_string_style;
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 positive_meaning_parameter_name;
pub mod posix_eof;
pub mod proper_parameter_declaration;
pub mod signal_name_style;
pub mod struct_union_name_style;
pub mod suggest_parentheses;
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 unpacked_dimensions_range_ordering;
pub mod unused_signal;
pub mod unused_waiver;
pub mod uvm_macro_semicolon;
pub mod v2001_generate_begin;
pub mod void_cast;
pub mod wire_reg_mixup;
@@ -0,0 +1,182 @@
//! `module-begin-block` — no `begin`/`end` block at module scope.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::ast::{Item, ItemKind};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct ModuleBeginBlock;
const NAME: &str = "module-begin-block";
impl Rule for ModuleBeginBlock {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not write a `begin`/`end` block at module scope"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A `begin … end` written straight into a module body is not a module \
item: IEEE 1800 §23.2.1 lists what may stand there, and a sequential \
block is not on the list. Tools that accept it treat it as an \
unnamed generate block, so the declarations inside it land in an \
invented scope (`genblk1.x`) and every hierarchical path written \
against them is wrong. Verible's `module-begin-block` (\"Checks that \
there are no begin-end blocks declared at the module level.\", \
enabled by default) is the same rule and the same default.\n\n\
lucisv's parser **recovers** the construct: in error-tolerant mode \
the block is read as the unnamed generate block every tool that \
accepts it makes of it, and a diagnostic is recorded at the `begin` \
— so the file is still reported as not parsing cleanly and the \
formatter still refuses to format it, but the items written inside \
the block are visible to this rule and to every other one. What this \
rule reads is that block standing where a module item belongs. No \
automatic fix: whether the block should become a generate block, an \
`always` or nothing at all is the author's to decide."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
for item in &ctx.file().items {
module_items(item, &mut |inner| {
if let Some(span) = begin_block(inner) {
out.push(Violation::new(
NAME,
"`begin`/`end` block at module scope; a module item belongs here",
span,
));
}
});
}
out
}
}
/// The `begin` keyword of an item that is a bare `begin … end` block, or
/// `None` for any other item.
///
/// Shared with `v2001-generate-begin`, which asks the same question one scope
/// further in: the two rules must agree about what a stray `begin` looks like,
/// and one reading is how that is guaranteed.
pub(crate) fn begin_block(item: &Item) -> Option<TextRange> {
let ItemKind::GenBlock(block) = &item.kind else { return None };
// The node's span opens at the keyword, whatever the item's own span does
// with the attributes written in front of it.
Some(TextRange::new(block.span.start, block.span.start + 5))
}
/// Calls `f` on every item written directly in a module, interface or program
/// body — nested units included, generate constructs deliberately not, since
/// a `begin` inside one of those is `v2001-generate-begin`'s business.
fn module_items(item: &Item, f: &mut dyn FnMut(&Item)) {
match &item.kind {
ItemKind::Module(module) => {
for inner in &module.items {
f(inner);
module_items(inner, f);
}
}
ItemKind::Package { items, .. } => {
for inner in items {
module_items(inner, f);
}
}
_ => {}
}
}
/// Whether `file` holds a module at all — used by the tests below only.
#[cfg(test)]
fn has_module(file: &vlog_parser::ast::SourceFile) -> bool {
file.items.iter().any(|item| matches!(item.kind, ItemKind::Module(_)))
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ModuleBeginBlock.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_module_scope_block_and_points_at_its_begin() {
let src = "module m;\n begin\n wire a;\n end\nendmodule\n";
let ctx = LintContext::new(src, None);
assert!(has_module(ctx.file()), "the probe needs the module to survive recovery");
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 an_ordinary_module_body_is_silent() {
let src = "module m;\n\
\x20 wire a;\n\
\x20 initial begin\n a = 1;\n end\n\
\x20 always_comb begin\n b = a;\n end\n\
\x20 if (A) begin : g\n wire c;\n end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_block_inside_a_generate_region_belongs_to_the_other_rule() {
let src = "module m;\n generate\n begin : b\n wire a;\n end\n \
endgenerate\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn an_identifier_that_starts_with_begin_is_not_the_keyword() {
// The error leaf of an unparsable item starting with `beginning` must
// not be read as a block.
let src = "module m;\n beginning @@@;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn the_block_keeps_its_items_and_the_module_keeps_the_items_after_it() {
// §36.1: the block is a node now, not an error leaf, so what is
// written inside it and after it is still there for every rule.
// Before, recovery skipped to `endmodule` and the `defparam` was
// inside one opaque leaf.
let src = "module m;\n begin\n defparam u.P = 1;\n end\n wire a;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "begin");
let ctx = LintContext::new(src, None);
let inside = crate::rules::forbid_defparam::ForbidDefparam.check(&ctx);
assert_eq!(inside.len(), 1, "a rule reading the block's items: {inside:?}");
assert_eq!(ctx.file().items.len(), 1, "one module");
}
#[test]
fn only_the_outermost_block_of_a_nest_is_reported_at_module_scope() {
// The inner block is written inside a block, not at module scope, so
// it is not this rule's finding — exactly as before §36.1, when the
// whole nest was one leaf whose first token was the outer `begin`.
let src = "module m;\n begin\n begin\n wire a;\n end\n end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(found[0].span.start, 12, "the outer `begin`");
}
#[test]
fn a_file_that_parses_cleanly_has_nothing_to_report() {
let src = "module m;\n wire a;\nendmodule\n";
assert!(LintContext::new(src, None).parsed_cleanly());
assert!(violations(src).is_empty());
}
}
@@ -1,7 +1,8 @@
//! `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;
@@ -36,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,
));
});
@@ -99,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,250 @@
//! `numeric-format-string-style` — a radix prefix must match its specifier.
use crate::context::LintContext;
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 NumericFormatStringStyle;
const NAME: &str = "numeric-format-string-style";
/// The base a prefix or a format specifier names.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Radix {
Binary,
Hex,
Decimal,
}
impl Radix {
/// The base this letter names, or `None` for a letter that names none.
fn of(letter: char) -> Option<Radix> {
match letter {
'b' | 'B' => Some(Radix::Binary),
'h' | 'H' | 'x' | 'X' => Some(Radix::Hex),
'd' | 'D' => Some(Radix::Decimal),
_ => None,
}
}
/// The word a message calls this base.
fn word(self) -> &'static str {
match self {
Radix::Binary => "binary",
Radix::Hex => "hexadecimal",
Radix::Decimal => "decimal",
}
}
}
impl Rule for NumericFormatStringStyle {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"give a numeric format specifier the radix prefix that matches it"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn default_on(&self) -> bool {
false
}
fn doc(&self) -> &'static str {
"A log line that prints `addr = 0x1010` when the value was formatted \
with `%b` has told the reader a lie that costs an hour: they read the \
number in the base the prefix claims. The convention is to write the \
prefix that matches — `0x%0h`, `'b%0b` — or to write no prefix at \
all, and to give a decimal number none, because `0d` is not a prefix \
anyone reads. Verible's `numeric-format-string-style` (\"Checks that \
string literals with numeric format specifiers have proper \
prefixes.\", **disabled** by default) reports exactly the mismatch, \
and lucisv ships it off for the same reason: it is a house \
convention, not a defect.\n\n\
A specifier with **no prefix is always accepted** — `\"%0h\"` and \
`\"%d\"` are clean. What is reported is a `0`- or `'`-introduced \
radix prefix immediately before the `%` that names a different base \
(`\"0x%0b\"`, `\"'b%0d\"`), and any prefix at all before a decimal \
specifier (`\"0d%0d\"`). Only real string literals are scanned: a \
string written inside a macro invocation is part of that \
invocation's one token and is not seen here. No automatic fix — \
which half is wrong, the prefix or the specifier, is the author's to \
say."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
for token in ctx.tokens().iter().filter(|t| t.kind == TokenKind::String) {
for bad in mismatches(&token.text) {
let start = token.span.start + bad.start as u32;
let end = token.span.start + bad.end as u32;
out.push(Violation::new(
NAME,
format!(
"`{}` prints a {} value after a {} prefix",
bad.text,
bad.specifier.word(),
match bad.prefix {
Some(prefix) => prefix.word(),
None => "radix",
}
),
TextRange::new(start, end),
));
}
}
out
}
}
/// One badly prefixed specifier: where it is, what it says, and what the
/// prefix in front of it claimed.
struct Mismatch {
start: usize,
end: usize,
text: String,
prefix: Option<Radix>,
specifier: Radix,
}
/// Every prefix/specifier mismatch of one string literal, in source order.
fn mismatches(text: &str) -> Vec<Mismatch> {
let bytes = text.as_bytes();
let mut out = Vec::new();
let mut i = 0usize;
while i < bytes.len() {
if bytes[i] != b'%' {
i += 1;
continue;
}
// `%%` is a literal per cent, not a specifier.
if bytes.get(i + 1) == Some(&b'%') {
i += 2;
continue;
}
let mut j = i + 1;
while bytes.get(j).is_some_and(u8::is_ascii_digit) {
j += 1;
}
let Some(specifier) = bytes.get(j).map(|&b| b as char).and_then(Radix::of) else {
i = j.max(i + 1);
continue;
};
let prefix = prefix_before(bytes, i);
let wrong = match (prefix, specifier) {
(Some(_), Radix::Decimal) => true,
(Some(prefix), specifier) => prefix != specifier,
(None, _) => false,
};
if wrong {
let start = if prefix.is_some() { i - 2 } else { i };
out.push(Mismatch {
start,
end: j + 1,
text: text[start..j + 1].to_string(),
prefix,
specifier,
});
}
i = j + 1;
}
out
}
/// The radix a `0x` / `'b`-shaped prefix immediately before `at` claims.
fn prefix_before(bytes: &[u8], at: usize) -> Option<Radix> {
if at < 2 {
return None;
}
if !matches!(bytes[at - 2], b'0' | b'\'') {
return None;
}
Radix::of(bytes[at - 1] as char)
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
NumericFormatStringStyle.check(&LintContext::new(src, None))
}
fn display(literal: &str) -> String {
format!("module m;\n initial $display({literal}, v);\nendmodule\n")
}
#[test]
fn flags_a_mismatched_prefix_and_underlines_prefix_and_specifier() {
let src = display("\"0x%0b\"");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "0x%0b");
assert!(found[0].fix.is_none());
}
/// Verible's own accepted list, literal for literal.
#[test]
fn a_matching_or_absent_prefix_is_accepted() {
for literal in [
"\"0x%0x\"",
"\"'h%0h\"",
"\"'h%h\"",
"\"0h%h\"",
"\"%0x\"",
"\"%h\"",
"\"%x\"",
"\"0b%0b\"",
"\"'b%0b\"",
"\"%0b\"",
"\"%0d\"",
"\"0x%0x, %d\"",
"\"0x%0x (bin: 'b%b, dec: %d)\"",
] {
let src = display(literal);
assert!(violations(&src).is_empty(), "{literal}: {:?}", violations(&src));
}
}
/// Verible's own rejected list, literal for literal.
#[test]
fn every_mismatch_verible_names_is_reported() {
for literal in [
"\"0b%0x\"",
"\"'b%0x\"",
"\"0x%0b\"",
"\"'h%0b\"",
"\"0x%0d\"",
"\"'h%0d\"",
"\"0b%0d\"",
"\"'b%0d\"",
"\"0d%0d\"",
"\"'d%0d\"",
] {
let src = display(literal);
assert_eq!(violations(&src).len(), 1, "{literal}: {:?}", violations(&src));
}
}
#[test]
fn a_non_numeric_specifier_and_a_literal_percent_are_ignored() {
for literal in ["\"%s\"", "\"%0t\"", "\"%m\"", "\"100%% done\"", "\"0x%s\""] {
let src = display(literal);
assert!(violations(&src).is_empty(), "{literal}: {:?}", violations(&src));
}
}
#[test]
fn each_specifier_of_one_string_is_judged_on_its_own() {
let src = display("\"0x%0b and 0b%0h and %d\"");
assert_eq!(violations(&src).len(), 2, "{:?}", violations(&src));
}
}
@@ -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());
}
}
@@ -1,7 +1,8 @@
//! `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;
@@ -34,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| {
@@ -62,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)]
@@ -141,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,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());
}
}
@@ -0,0 +1,134 @@
//! `positive-meaning-parameter-name` — no `disable`-prefixed parameter.
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, StmtKind};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct PositiveMeaningParameterName;
const NAME: &str = "positive-meaning-parameter-name";
/// The prefix a parameter must not start with, compared case-insensitively.
const FORBIDDEN_PREFIX: &str = "disable";
impl Rule for PositiveMeaningParameterName {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name a parameter for what it enables, not for what it disables"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A negatively named parameter forces every use of it to be read \
twice: `if (!DisableEcc)` is a double negative, and a default of \
`DisableEcc = 0` means \"ECC is on\", which nobody reads correctly at \
speed. Naming the positive meaning — `EnableEcc`, `EccEnabled` — \
makes each use say what it does. Verible's \
`positive-meaning-parameter-name` (\"Checks that no parameter name \
starts with 'disable', using positive naming is recommended.\", \
enabled by default) is the same rule and the same default; the \
comparison is case-insensitive there and here, so `DISABLE_X` and \
`disable_x` are both reported.\n\n\
Every parameter is judged, in a formal parameter list and in a body \
declaration alike, `localparam` included. No automatic fix: \
inverting a parameter means inverting every use of it and its \
default, which is a refactor, not a repair."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
let mut judge = |name: &str, span: TextRange| {
if !starts_with_disable(name) {
return;
}
out.push(Violation::new(
NAME,
format!(
"parameter `{name}` is named for what it disables; name the positive meaning"
),
span,
));
};
walk_param_ports(ctx.file(), &mut |port| judge(&port.name, port.name_span));
walk_items(ctx.file(), &mut |item| {
let ItemKind::ParamDecl(decl) = &item.kind else { return };
for declarator in &decl.declarators {
judge(&declarator.name, declarator.name_span);
}
});
walk_all_stmts(ctx.file(), &mut |stmt| {
let StmtKind::ParamDecl(decl) = &stmt.kind else { return };
for declarator in &decl.declarators {
judge(&declarator.name, declarator.name_span);
}
});
out
}
}
/// True when `name` begins with `disable`, in any case.
fn starts_with_disable(name: &str) -> bool {
name.len() >= FORBIDDEN_PREFIX.len()
&& name[..FORBIDDEN_PREFIX.len()].eq_ignore_ascii_case(FORBIDDEN_PREFIX)
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
PositiveMeaningParameterName.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_formal_parameter_and_points_at_its_name() {
let src = "module m #(parameter int DisableEcc = 0) ();\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "DisableEcc");
assert!(found[0].fix.is_none());
}
#[test]
fn the_prefix_is_matched_in_any_case() {
for name in ["disable_ecc", "DISABLE_ECC", "DisableEcc", "dIsAbLe"] {
let src = format!("module m;\n localparam int {name} = 0;\nendmodule\n");
assert_eq!(violations(&src).len(), 1, "{name}");
}
}
#[test]
fn a_positive_name_is_what_the_rule_wants() {
for name in ["EnableEcc", "EccEnabled", "Width", "Dis", "NotDisabled", "UnDisable"] {
let src = format!("module m;\n localparam int {name} = 0;\nendmodule\n");
assert!(violations(&src).is_empty(), "{name}: {:?}", violations(&src));
}
}
#[test]
fn every_place_a_parameter_is_written_is_reached() {
let src = "module m #(parameter int DisableA = 0) ();\n\
\x20 localparam int DisableB = 0;\n\
\x20 function automatic int f();\n parameter int DisableC = 0;\n \
return DisableC;\n endfunction\n\
endmodule\n\
class c #(parameter int DisableD = 0);\nendclass\n";
assert_eq!(violations(src).len(), 4, "{:?}", violations(src));
}
#[test]
fn an_ordinary_signal_is_not_a_parameter() {
assert!(violations("module m;\n wire disable_ecc;\nendmodule\n").is_empty());
}
}
+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,196 @@
//! `proper-parameter-declaration` — `parameter` in a header, `localparam` in a body.
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_items_scoped, ItemScope};
use vlog_parser::ast::ItemKind;
/// See [`Rule::doc`].
pub struct ProperParameterDeclaration;
const NAME: &str = "proper-parameter-declaration";
/// Verible's two options, spelled and defaulted as Verible spells them.
const OPTIONS: &[OptionSpec] = &[
OptionSpec {
name: "package_allow_parameter",
kind: OptionKind::Bool,
default: OptionDefault::Bool(false),
doc: "accept `parameter` in a package body",
},
OptionSpec {
name: "package_allow_localparam",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "accept `localparam` in a package body",
},
];
impl Rule for ProperParameterDeclaration {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"declare `parameter` only in a formal parameter list and `localparam` only in a body"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn default_on(&self) -> bool {
false
}
fn options(&self) -> &'static [OptionSpec] {
OPTIONS
}
fn doc(&self) -> &'static str {
"A `parameter` is what an instantiation may override, so it belongs \
in the `#( … )` a caller can see. Written in a module *body* it is \
still overridable — by `defparam`, or by a hierarchical override — \
which means a value the reader believes is fixed can change from \
outside with nothing at the declaration to say so. `localparam` is \
the spelling for a constant that is nobody's business but the \
module's. Verible's `proper-parameter-declaration` (\"Checks that \
`parameter` declarations are in formal parameter lists and \
`localparam` in modules/classes/packages.\", **disabled** by \
default) is the same rule and the same default, with the same two \
options: `package_allow_parameter` (false) and \
`package_allow_localparam` (true).\n\n\
A **formal parameter list is never judged** — `#(parameter int W = \
8)` and `#(localparam int X = 2*W)` are both fine there. What is \
judged is a body declaration: `parameter` anywhere is wrong (in a \
package, unless `package_allow_parameter`), and `localparam` is \
right in a module, interface, program or class body, wrong at file \
scope, and in a package answers to `package_allow_localparam`. Only \
item-scope declarations are read; a `parameter` written among a \
subroutine's statements is left to the language. No automatic fix: \
`parameter` → `localparam` removes an override an instantiation may \
be relying on."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let allow_parameter = ctx.option_bool(NAME, "package_allow_parameter");
let allow_localparam = ctx.option_bool(NAME, "package_allow_localparam");
let mut out = Vec::new();
walk_items_scoped(ctx.file(), &mut |scope, item| {
let ItemKind::ParamDecl(decl) = &item.kind else { return };
let Some(first) = decl.declarators.first() else { return };
let Some(message) = complaint(&decl.kw, scope, allow_parameter, allow_localparam)
else {
return;
};
out.push(Violation::new(NAME, message, first.name_span));
});
out
}
}
/// What is wrong with this keyword in this scope, or `None` when nothing is.
fn complaint(
kw: &str,
scope: ItemScope,
allow_parameter: bool,
allow_localparam: bool,
) -> Option<String> {
match (kw, scope) {
("parameter", ItemScope::Package) if allow_parameter => None,
("parameter", _) => Some(
"`parameter` belongs in a formal parameter list; write `localparam` for a \
body constant"
.to_string(),
),
("localparam", ItemScope::Package) if allow_localparam => None,
("localparam", ItemScope::Package) => Some(
"`localparam` is not accepted in a package body by this project's settings".to_string(),
),
("localparam", ItemScope::File) => {
Some("`localparam` belongs in a module, interface, program or class body".to_string())
}
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
ProperParameterDeclaration.check(&LintContext::new(src, None))
}
fn with(src: &str, key: &str, raw: &str) -> Vec<Violation> {
let mut options = RuleOptions::new();
options.set_raw(NAME, key, raw).expect("accepted");
ProperParameterDeclaration.check(&LintContext::new(src, None).with_options(&options))
}
#[test]
fn flags_a_parameter_in_a_module_body_and_points_at_its_name() {
let src = "module m;\n parameter int Bar = 1;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "Bar");
assert!(found[0].fix.is_none());
}
/// Verible's own accepted list, snippet for snippet.
#[test]
fn the_shapes_verible_accepts_are_accepted() {
for src in [
"module foo; localparam int Bar = 1; endmodule\n",
"class foo; localparam int Bar = 1; endclass\n",
"package foo; localparam int Bar = 1; endpackage\n",
"module foo #(localparam int Bar = 1); endmodule\n",
"module foo #(parameter int Bar = 1); endmodule\n",
] {
assert!(violations(src).is_empty(), "{src}: {:?}", violations(src));
}
}
/// Verible's own rejected list, snippet for snippet.
#[test]
fn the_shapes_verible_rejects_are_reported() {
for src in [
"parameter int Foo = 1;\n",
"package foo; parameter int Bar = 1; endpackage\n",
"module foo; parameter int Bar = 1; endmodule\n",
"class foo; parameter int Bar = 1; endclass\n",
"package foo; class bar; parameter int HelloWorld = 1; endclass endpackage\n",
] {
assert_eq!(violations(src).len(), 1, "{src}: {:?}", violations(src));
}
}
#[test]
fn package_allow_parameter_moves_the_line() {
let src = "package foo; parameter int Bar = 1; endpackage\n";
assert_eq!(violations(src).len(), 1);
assert!(with(src, "package_allow_parameter", "true").is_empty());
}
#[test]
fn package_allow_localparam_moves_it_the_other_way() {
let src = "package foo; localparam int Bar = 1; endpackage\n";
assert!(violations(src).is_empty());
assert_eq!(with(src, "package_allow_localparam", "false").len(), 1);
}
#[test]
fn a_localparam_at_file_scope_has_no_body_to_belong_to() {
assert_eq!(violations("localparam int Foo = 1;\n").len(), 1);
}
#[test]
fn a_declaration_inside_a_generate_block_keeps_its_modules_scope() {
let src = "module m;\n if (A) begin : g\n localparam int X = 1;\n end\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
}
@@ -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,7 +2,8 @@
//! `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;
@@ -36,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> {
@@ -45,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,
));
});
@@ -101,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,145 @@
//! `suggest-parentheses` — parenthesize a ternary nested in a ternary.
use crate::context::LintContext;
use crate::exprs::walk_exprs;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Fix, Violation};
use vlog_parser::ast::{Expr, ExprKind};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct SuggestParentheses;
const NAME: &str = "suggest-parentheses";
impl Rule for SuggestParentheses {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"parenthesize a conditional written in the true-clause of another"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn fix(&self) -> Option<crate::violation::Applicability> {
Some(crate::violation::Applicability::Safe)
}
fn doc(&self) -> &'static str {
"`a ? b ? c : d : e` is legal and means `a ? (b ? c : d) : e` — the \
conditional operator is right-associative — but the reader has to \
know that and then count colons to find which `:` closes which `?`. \
Two characters remove the question. Verible's `suggest-parentheses` \
(\"Recommend extra parentheses around subexpressions where it helps \
readability.\", enabled by default) reports exactly this shape: a \
condition expression standing, unparenthesized, in the true-clause of \
another condition expression. lucisv reports the same shape and \
nothing more — a ternary in the *false*-clause is where the language \
already puts it, and every other mixed-precedence expression is left \
alone, because a rule that guessed at operator combinations would \
report far more than it explained.\n\n\
The fix is **safe**: it writes a `(` and a `)` around the inner \
conditional and changes no token, which is the meaning the language \
already gives the expression."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_exprs(ctx.file(), &mut |expr| {
let ExprKind::Ternary { then, .. } = &expr.kind else { return };
if !matches!(then.kind, ExprKind::Ternary { .. }) {
return;
}
out.push(
Violation::new(
NAME,
"conditional in the true-clause of another conditional; parenthesize it",
then.span,
)
.with_fix(Fix::safe(parenthesize(then))),
);
});
out
}
}
/// The two insertions that wrap `expr` in parentheses, touching nothing else.
fn parenthesize(expr: &Expr) -> Vec<(TextRange, String)> {
vec![
(TextRange::new(expr.span.start, expr.span.start), "(".to_string()),
(TextRange::new(expr.span.end, expr.span.end), ")".to_string()),
]
}
#[cfg(test)]
mod tests {
use super::*;
use crate::violation::apply_fixes;
fn violations(src: &str) -> Vec<Violation> {
SuggestParentheses.check(&LintContext::new(src, None))
}
fn assign(rhs: &str) -> String {
format!("module m;\n assign x = {rhs};\nendmodule\n")
}
#[test]
fn flags_the_nested_true_clause_and_underlines_it() {
let src = assign("a ? b ? c : d : e");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "b ? c : d");
}
#[test]
fn the_fix_only_adds_parentheses() {
let src = assign("a ? b ? c : d : e");
let fixed = apply_fixes(&src, &violations(&src), false);
assert_eq!(fixed.applied, 1);
assert_eq!(fixed.output, assign("a ? (b ? c : d) : e"));
// ... and the fixed text has nothing left to report.
assert!(violations(&fixed.output).is_empty());
}
#[test]
fn an_already_parenthesized_clause_is_clean() {
assert!(violations(&assign("a ? (b ? c : d) : e")).is_empty());
}
#[test]
fn a_conditional_in_the_false_clause_is_where_the_language_puts_it() {
assert!(violations(&assign("a ? b : c ? d : e")).is_empty());
}
#[test]
fn a_plain_conditional_is_clean() {
assert!(violations(&assign("a ? b : c")).is_empty());
assert!(violations(&assign("a + b * c")).is_empty());
}
#[test]
fn a_conditional_condition_is_not_this_rules_business() {
// Verible reports the true-clause only; a `?:` used as the condition
// of another already needs its own parentheses to parse.
assert!(violations(&assign("(a ? b : c) ? d : e")).is_empty());
}
#[test]
fn three_deep_reports_each_nesting() {
let src = assign("a ? b ? c ? d : e : f : g");
assert_eq!(violations(&src).len(), 2, "{:?}", violations(&src));
}
#[test]
fn a_conditional_written_anywhere_is_reached() {
let src = "module m #(parameter int P = a ? b ? 1 : 2 : 3) ();\n\
\x20 initial begin\n y = c ? d ? 1 : 2 : 3;\n end\nendmodule\n";
assert_eq!(violations(src).len(), 2, "{:?}", violations(src));
}
}
@@ -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,161 @@
//! `unpacked-dimensions-range-ordering` — write an array's extent `[0:N-1]`.
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 UnpackedDimensionsRangeOrdering;
const NAME: &str = "unpacked-dimensions-range-ordering";
impl Rule for UnpackedDimensionsRangeOrdering {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"declare an unpacked dimension in increasing order, `[0:N-1]`"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"An unpacked dimension is an *array*, and an array counts up: element \
0 first. `logic q [7:0]` declares the same eight elements as \
`logic q [0:7]` but numbers them backwards, so `foreach (q[i])` \
visits them in the opposite order to the one the declaration suggests \
and every `for (i = 0; i < 8; i++)` written beside it reads the array \
the other way round. Verible's \
`unpacked-dimensions-range-ordering` (\"Checks that unpacked \
dimension ranges are declared in big-endian order `[0:N-1]`.\", \
enabled by default) is the same rule and the same default — and it \
is the mirror image of `packed-dimensions-range-ordering`, which \
wants a *vector*'s width the other way, `[N-1:0]`.\n\n\
Only a range is judged. A sized extent (`logic q [8]`), a dynamic \
(`[]`), an associative (`[*]`, `[key_t]`) and a queue are not \
ranges and are left alone. A range is flagged when both bounds are \
integer literals and the left one is larger, and when the right one \
is a literal `0` and the left is anything else (`[N-1:0]`) — every \
other shape is two symbolic bounds lucisv does not evaluate. 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::Unpacked {
return;
}
let DimKind::Range { a, b: Some(b) } = &dim.kind else { return };
if !descending(a, b) {
return;
}
out.push(Violation::new(
NAME,
"unpacked dimension counts downwards; write it as `[0:N-1]`",
dim.span,
));
});
out
}
}
/// True when `[a:b]` demonstrably counts downwards.
///
/// Two literals decide it outright. A right bound of literal `0` decides it
/// too whatever the left bound is — `[WIDTH-1:0]` is the shape this rule
/// mostly meets — unless the left bound is `0` as well, which is the
/// one-element `[0:0]` and counts in no direction at all. Anything else is
/// two symbolic bounds lucisv cannot compare, and it says nothing.
fn descending(a: &Expr, b: &Expr) -> bool {
match (literal(a), literal(b)) {
(Some(left), Some(right)) => left > right,
(None, Some(0)) => 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> {
UnpackedDimensionsRangeOrdering.check(&LintContext::new(src, None))
}
fn decl(text: &str) -> String {
format!("module m;\n {text}\nendmodule\n")
}
#[test]
fn flags_a_descending_unpacked_range() {
let src = decl("logic q [7:0];");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "[7:0]");
assert!(found[0].fix.is_none());
}
#[test]
fn flags_the_common_symbolic_to_zero_shape() {
assert_eq!(violations(&decl("logic q [DEPTH-1:0];")).len(), 1);
assert_eq!(violations(&decl("logic q [2:1];")).len(), 1);
}
#[test]
fn an_increasing_range_is_what_the_rule_wants() {
for text in [
"logic q [0:7];",
"logic q [0:DEPTH-1];",
"logic q [0:0];",
"logic q [8];",
"logic q [];",
"logic q [string];",
"logic q;",
] {
let src = decl(text);
assert!(violations(&src).is_empty(), "{text}: {:?}", violations(&src));
}
}
#[test]
fn two_symbolic_bounds_are_left_alone() {
assert!(violations(&decl("logic q [LO:HI];")).is_empty());
assert!(violations(&decl("logic q [A-1:B];")).is_empty());
}
#[test]
fn a_packed_dimension_is_the_other_rules_business() {
assert!(violations(&decl("logic [7:0] v;")).is_empty());
// ... and both dimensions of one declaration are told apart.
assert_eq!(violations(&decl("logic [7:0] q [3:0];")).len(), 1);
}
#[test]
fn every_declaration_shape_is_reached() {
let src = "module m #(parameter int P [1:0] = '{0, 0}) (\n\
input logic a [1:0]\n\
);\n\
logic b [1:0];\n\
typedef logic w_t [1:0];\n\
function automatic void f(input logic x [1:0]);\n\
endfunction\n\
endmodule\n";
assert_eq!(violations(src).len(), 5, "{:?}", violations(src));
}
}
@@ -0,0 +1,118 @@
//! `uvm-macro-semicolon` — no `;` after a `` `uvm_* `` macro invocation.
use crate::context::LintContext;
use crate::preproc::macro_name;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::token::TokenKind;
/// See [`Rule::doc`].
pub struct UvmMacroSemicolon;
const NAME: &str = "uvm-macro-semicolon";
/// The prefix that marks a macro as UVM's.
const UVM: &str = "uvm_";
impl Rule for UvmMacroSemicolon {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not write a `;` after a `` `uvm_* `` macro invocation"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn default_on(&self) -> bool {
false
}
fn doc(&self) -> &'static str {
"The UVM reporting macros expand to a `begin … end` block, so the `;` \
so many people write after one is a *null statement* that follows it. \
Usually harmless; not always — `if (x) `uvm_info(…); else …` puts the \
null statement where the `if`'s body should be and the `else` then \
belongs to nothing, which is a compile error or, worse, a silently \
different branch structure. Verible's `uvm-macro-semicolon` (\"Checks \
that no `uvm_*` macro calls end with ';'.\", **disabled** by default) \
is the same rule and lucisv ships it off for the same reason: the \
semicolon is written everywhere in existing UVM code and is almost \
always inert, so turning it on is a project's decision.\n\n\
A macro whose name begins `uvm_` is judged, whatever follows the \
invocation's arguments; the finding points at the `;`. **No \
automatic fix**: deleting the `;` is exactly the edit that is unsafe \
in the one shape the rule exists for — after `if (x) `uvm_info(…);` \
with no `else`, removing it is fine, and with one it changes which \
statement the `else` binds to."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let tokens = ctx.tokens();
let mut out = Vec::new();
for (i, token) in tokens.iter().enumerate() {
let Some(name) = macro_name(token) else { continue };
if !name.starts_with(UVM) {
continue;
}
let Some(next) = tokens.get(i + 1) else { continue };
if next.kind != TokenKind::Symbol || next.text != ";" {
continue;
}
out.push(Violation::new(
NAME,
format!("`` `{name} `` already ends its statement; the `;` is a null statement"),
next.span,
));
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
UvmMacroSemicolon.check(&LintContext::new(src, None))
}
#[test]
fn flags_the_semicolon_not_the_macro() {
let src = "module m;\n initial `uvm_info(\"A\", \"B\", UVM_LOW);\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], ";");
assert!(found[0].fix.is_none());
}
#[test]
fn the_bare_invocation_is_what_the_rule_wants() {
let src = "module m;\n initial begin\n `uvm_info(\"A\", \"B\", UVM_LOW)\n end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_non_uvm_macro_is_not_judged() {
let src = "module m;\n initial `my_macro(1);\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn every_uvm_macro_of_a_file_is_reported() {
let src = "module m;\n initial begin\n `uvm_info(\"A\", \"B\", UVM_LOW);\n \
`uvm_error(\"A\", \"B\");\n `uvm_fatal(\"A\", \"B\")\n end\nendmodule\n";
assert_eq!(violations(src).len(), 2, "{:?}", violations(src));
}
#[test]
fn a_semicolon_on_the_next_line_still_follows_the_macro() {
let src = "module m;\n initial `uvm_info(\"A\", \"B\", UVM_LOW)\n ;\nendmodule\n";
assert_eq!(violations(src).len(), 1);
}
}
@@ -0,0 +1,116 @@
//! `v2001-generate-begin` — no bare `begin` inside a generate region.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::rules::module_begin_block::begin_block;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::ItemKind;
/// See [`Rule::doc`].
pub struct V2001GenerateBegin;
const NAME: &str = "v2001-generate-begin";
impl Rule for V2001GenerateBegin {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not write a bare `begin` block inside a generate region"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A `begin … end` written directly inside `generate … endgenerate`, \
with no `if`, `for` or `case` around it, was a Verilog-2001 spelling \
for \"one more scope\". It opens an unnamed generate block, so every \
declaration inside it acquires an invented path segment (`genblk1.x`) \
that renumbers the moment a block is added above it — and it buys \
nothing, because the region is already a scope. Verible's \
`v2001-generate-begin` (\"Checks that there are no generate-begin \
blocks inside a generate region.\", enabled by default) is the same \
rule and the same default.\n\n\
Like `module-begin-block`, this reads the block lucisv's parser \
recovers where it refuses the construct: an unnamed generate block \
written directly inside a `generate … endgenerate`, kept in the tree \
beside a diagnostic at its `begin`, so everything declared inside it \
is still visible to the other rules. No automatic fix — deleting the \
two keywords re-indents the whole block, and giving it a label \
instead is a different repair."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::GenerateRegion { items, .. } = &item.kind else { return };
for inner in items {
if let Some(span) = begin_block(inner) {
out.push(Violation::new(
NAME,
"bare `begin` block inside a generate region; the region is \
already a scope",
span,
));
}
}
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
V2001GenerateBegin.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_bare_begin_and_points_at_the_keyword() {
let src = "module m;\n generate\n begin : b\n wire a;\n end\n \
endgenerate\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_generate_construct_inside_the_region_is_what_belongs_there() {
let src = "module m;\n generate\n\
\x20 if (A) begin : g\n wire a;\n end\n\
\x20 for (genvar i = 0; i < 2; i++) begin : l\n wire b;\n end\n\
\x20 endgenerate\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_module_scope_block_belongs_to_the_other_rule() {
let src = "module m;\n begin\n wire a;\n end\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn the_blocks_items_stay_visible_to_the_other_rules() {
let src = "module m;\n generate\n begin : b\n defparam u.P = 1;\n end\n \
endgenerate\n wire ok;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "begin");
let inside =
crate::rules::forbid_defparam::ForbidDefparam.check(&LintContext::new(src, None));
assert_eq!(inside.len(), 1, "a rule reading the block's items: {inside:?}");
}
#[test]
fn a_file_with_no_generate_region_is_silent() {
assert!(violations("module m;\n wire a;\nendmodule\n").is_empty());
}
}
+102 -10
View File
@@ -1,6 +1,7 @@
//! `void-cast` — `void'(…)` around something that is not a call.
use crate::context::LintContext;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
@@ -12,6 +13,15 @@ pub struct VoidCast;
const NAME: &str = "void-cast";
/// Verible's own forbidden-call list, which it hard-codes: `uvm_hdl_read` and
/// `randomize` (the bare call and the `obj.randomize()` method alike).
const OPTIONS: &[OptionSpec] = &[OptionSpec {
name: "forbidden_calls",
kind: OptionKind::List,
default: OptionDefault::List(&["uvm_hdl_read", "randomize"]),
doc: "calls whose result must be checked, so a `void'` cast of one is a bug",
}];
impl Rule for VoidCast {
fn name(&self) -> &'static str {
NAME
@@ -25,6 +35,10 @@ impl Rule for VoidCast {
Severity::Warning
}
fn options(&self) -> &'static [OptionSpec] {
OPTIONS
}
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 \
@@ -35,12 +49,19 @@ impl Rule for VoidCast {
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\
result must be checked (`randomize`, `uvm_hdl_read`). lucisv checks \
both halves in the one rule. The first is the check TODO §33 asked \
for — the operand must be a call at all — and the second is \
Verible's, spelled as the `forbidden_calls` option so a project can \
name its own. A discarded `randomize()` is the classic version: it \
returns 0 when the constraints could not be solved, and \
`void'(randomize())` throws that away, so the test runs on with \
whatever the object happened to hold. The two halves cannot both \
fire on one statement — the first wants a call and the second wants \
a particular one — so a `void'(randomize())` is reported once. No \
automatic fix for either: whether the repair is to delete the cast, \
to add the missing call or to check the result 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 \
@@ -48,16 +69,31 @@ impl Rule for VoidCast {
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let forbidden = ctx.option_list(NAME, "forbidden_calls");
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) {
if *pattern || !is_void(ty) {
return;
}
if !is_call(inner) {
out.push(Violation::new(
NAME,
"`void'(...)` around something that is not a call; nothing is being discarded",
expr.span,
));
return;
}
let Some(called) = called_name(inner) else { return };
if !forbidden.iter().any(|name| name == called) {
return;
}
out.push(Violation::new(
NAME,
"`void'(...)` around something that is not a call; nothing is being discarded",
format!(
"`{called}` returns a result that must be checked; do not cast it to `void`"
),
expr.span,
));
});
@@ -65,6 +101,23 @@ impl Rule for VoidCast {
}
}
/// The name the cast operand calls — the last segment of the callee, so
/// `obj.randomize()`, `pkg::uvm_hdl_read()` and a bare `randomize()` all
/// answer the same word.
fn called_name(expr: &Expr) -> Option<&str> {
match &expr.kind {
ExprKind::Call { callee, .. } => match &callee.kind {
ExprKind::Ident(name) => Some(name),
ExprKind::Member { name, .. } | ExprKind::Scope { name, .. } => Some(name),
_ => None,
},
ExprKind::Paren { inner, .. } => called_name(inner),
ExprKind::With { base, .. } | ExprKind::WithConstraint { base, .. } => called_name(base),
ExprKind::Cast { expr: inner, .. } => called_name(inner),
_ => None,
}
}
/// 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")
@@ -116,18 +169,57 @@ mod tests {
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)));
}
}
/// Verible's half of the rule: a call whose result must be checked.
#[test]
fn a_forbidden_call_is_reported_however_it_is_written() {
for text in [
"void'(randomize());",
"void'(obj.randomize());",
"void'(randomize(x) with { x inside {[0:7]}; });",
"void'(uvm_hdl_read(path, value));",
"void'(pkg::uvm_hdl_read(path, value));",
] {
let found = violations(&stmt(text));
assert_eq!(found.len(), 1, "{text}: {found:?}");
assert!(found[0].message.contains("must be checked"), "{}", found[0].message);
assert!(found[0].fix.is_none());
}
}
#[test]
fn the_two_halves_never_both_fire_on_one_statement() {
// The operand is a call, so the "not a call" half is silent; it is a
// forbidden call, so the other half speaks — once.
assert_eq!(violations(&stmt("void'(randomize());")).len(), 1);
assert_eq!(violations(&stmt("void'(x);")).len(), 1);
}
#[test]
fn the_forbidden_list_is_configurable() {
use crate::options::RuleOptions;
let src = stmt("void'(my_check());");
assert!(violations(&src).is_empty());
let mut options = RuleOptions::new();
options.set_raw(NAME, "forbidden_calls", "[\"my_check\"]").expect("accepted");
let found = VoidCast.check(&LintContext::new(&src, None).with_options(&options));
assert_eq!(found.len(), 1, "{found:?}");
// ... and the default names are no longer forbidden once replaced.
let randomized = stmt("void'(randomize());");
assert!(VoidCast
.check(&LintContext::new(&randomized, None).with_options(&options))
.is_empty());
}
#[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);"] {
+1
View File
@@ -369,6 +369,7 @@ impl Scanner {
}
}
ItemKind::GenerateRegion { items, .. } => self.items(items, module, true),
ItemKind::GenBlock(b) => self.items(&b.items, module, true),
ItemKind::GenIf(gen_if) => {
self.items(&gen_if.then.items, module, true);
let mut els = gen_if.els.as_deref();
+128
View File
@@ -24,6 +24,7 @@ fn items(list: &[Item], f: &mut dyn FnMut(&Item)) {
ItemKind::Class(class) => items(&class.items, f),
ItemKind::Package { items: inner, .. } => items(inner, f),
ItemKind::GenerateRegion { items: inner, .. } => items(inner, f),
ItemKind::GenBlock(b) => items(&b.items, f),
ItemKind::GenIf(gen_if) => {
gen_block(&gen_if.then, f);
let mut els = gen_if.els.as_deref();
@@ -70,6 +71,67 @@ fn gen_block(block: &GenBlock, f: &mut dyn FnMut(&Item)) {
items(&block.items, f);
}
/// The declaration an item was written inside — what a rule needs when the
/// same construct is right in one scope and wrong in another.
///
/// A generate construct is not a scope here: `localparam` inside a
/// `generate` block is still written in the module that holds it, and both
/// rules that ask this question (`proper-parameter-declaration`, the two
/// `explicit-*-lifetime`) mean the enclosing *declaration*, not the block.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ItemScope {
/// Written at file scope, outside every declaration.
File,
/// Inside a `module`, `interface` or `program` body.
Module,
/// Inside a `package` body.
Package,
/// Inside a `class` body.
Class,
}
/// Calls `f` on every item of the file, saying which declaration holds it.
pub(crate) fn walk_items_scoped(file: &SourceFile, f: &mut dyn FnMut(ItemScope, &Item)) {
scoped_items(&file.items, ItemScope::File, f);
}
fn scoped_items(list: &[Item], scope: ItemScope, f: &mut dyn FnMut(ItemScope, &Item)) {
for item in list {
f(scope, item);
match &item.kind {
ItemKind::Module(m) => scoped_items(&m.items, ItemScope::Module, f),
ItemKind::Class(class) => scoped_items(&class.items, ItemScope::Class, f),
ItemKind::Package { items: inner, .. } => scoped_items(inner, ItemScope::Package, f),
// A generate construct keeps the scope it was written in.
ItemKind::GenerateRegion { items: inner, .. } => scoped_items(inner, scope, f),
ItemKind::GenBlock(b) => scoped_items(&b.items, scope, f),
ItemKind::GenIf(gen_if) => {
scoped_items(&gen_if.then.items, scope, f);
let mut els = gen_if.els.as_deref();
while let Some(branch) = els {
match branch {
GenElse::If(_, nested) => {
scoped_items(&nested.then.items, scope, f);
els = nested.els.as_deref();
}
GenElse::Block(block) => {
scoped_items(&block.items, scope, f);
els = None;
}
}
}
}
ItemKind::GenFor(gen_for) => scoped_items(&gen_for.body.items, scope, f),
ItemKind::GenCase(gen_case) => {
for case_item in &gen_case.items {
scoped_items(&case_item.body.items, scope, f);
}
}
_ => {}
}
}
}
/// Calls `f` on every statement of the file, nested statements included.
pub(crate) fn walk_all_stmts(file: &SourceFile, f: &mut dyn FnMut(&Stmt)) {
// A statement fragment is a whole file of statements with no item around
@@ -142,6 +204,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)) {
@@ -283,6 +376,41 @@ mod tests {
assert_eq!(names, vec!["A".to_string(), "T".to_string()]);
}
/// The scope a rule asks about is the enclosing *declaration*, and a
/// generate construct passes the one it was written in through.
#[test]
fn every_item_is_told_which_declaration_holds_it() {
let src = "localparam int AtFile = 0;\n\
package p;\n\
localparam int InPackage = 0;\n\
class c;\n localparam int InClass = 0;\n endclass\n\
endpackage\n\
module m;\n\
localparam int InModule = 0;\n\
if (A) begin : g\n localparam int InGenerate = 0;\n end\n\
endmodule\n";
let (file, diagnostics) = parse_source_tolerant(src);
assert!(diagnostics.is_empty(), "{diagnostics:?}");
let mut seen: Vec<(String, ItemScope)> = Vec::new();
walk_items_scoped(&file, &mut |scope, item| {
if let ItemKind::ParamDecl(decl) = &item.kind {
for declarator in &decl.declarators {
seen.push((declarator.name.clone(), scope));
}
}
});
assert_eq!(
seen,
vec![
("AtFile".to_string(), ItemScope::File),
("InPackage".to_string(), ItemScope::Package),
("InClass".to_string(), ItemScope::Class),
("InModule".to_string(), ItemScope::Module),
("InGenerate".to_string(), ItemScope::Module),
]
);
}
#[test]
fn an_unparsable_region_is_visited_but_holds_nothing() {
let (file, diagnostics) = parse_source_tolerant("module m;\n @@@;\nendmodule\n");
+43 -1
View File
@@ -81,10 +81,11 @@ fn severity_entry(severity: Severity, order: u32) -> String {
/// One rule's toggle.
fn rule_entry(rule: &'static dyn Rule, order: u32) -> String {
let description = format!(
"**{severity}** — {summary}. {default}",
"**{severity}** — {summary}. {default}{options}",
severity = rule.severity().as_str(),
summary = rule.summary(),
default = default_sentence(rule),
options = options_sentence(rule),
);
format!(
" \"{id}\": {{\n\
@@ -106,6 +107,20 @@ fn rule_entry(rule: &'static dyn Rule, order: u32) -> String {
)
}
/// 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 {
@@ -180,6 +195,33 @@ mod tests {
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\"");
@@ -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
@@ -25,7 +25,7 @@ package p;
endpackage
====
# every non-procedural scope is reached: interface
interface ifc;
interface ifc_if;
logic a;
;
//^ 3 empty-item
@@ -48,7 +48,7 @@ endmodule
====
# every non-procedural scope is reached: inside a generate-for body
module m;
for (genvar i = 0; i < 2; i++) begin : g
for (genvar i = 0; i < 2; i++) begin : g_loop
;
//^ 5 empty-item
end
@@ -56,7 +56,7 @@ endmodule
====
# `end;` after a generate block, and a run of null items after it
module m;
if (N > 1) begin : g1
if (N > 1) begin : g_one
wire x;
end;
//^ 6 empty-item
@@ -74,9 +74,9 @@ endmodule
====
# `endfunction;` / `endtask;` are recorded on the declaration, not as null items
module m;
function int f();
function automatic int f();
endfunction;
task t();
task automatic t();
endtask;
endmodule
====
@@ -0,0 +1,40 @@
#select explicit-begin
# an unblocked body is wrapped, and an `else if` chain is not touched
module m;
initial begin
if (a) x = 1;
//^ 12 explicit-begin
else if (b) begin
x = 2;
end
end
endmodule
----
module m;
initial begin
if (a) begin x = 1; end
//^ 12 explicit-begin
else if (b) begin
x = 2;
end
end
endmodule
====
#select explicit-begin
#options explicit-begin.if_enable = false
# each construct has its own switch
module m;
initial begin
if (a) x = 1;
while (b) y = 2;
//^ 15 explicit-begin
end
endmodule
----
module m;
initial begin
if (a) x = 1;
while (b) begin y = 2; end
//^ 15 explicit-begin
end
endmodule
@@ -0,0 +1,26 @@
#select suggest-parentheses
# a conditional in the true-clause of another, and the safe fix that parenthesizes it
module m;
assign x = a ? b ? c : d : e;
//^ 18 suggest-parentheses
assign y = a ? b : c ? d : e;
endmodule
----
module m;
assign x = a ? (b ? c : d) : e;
//^ 18 suggest-parentheses
assign y = a ? b : c ? d : e;
endmodule
====
#select unpacked-dimensions-range-ordering
# an array counts up; a vector's width is the other rule's business
module m;
logic [7:0] v;
logic q [0:3];
logic r [3:0];
//^ 11 unpacked-dimensions-range-ordering
logic s [DEPTH-1:0];
//^ 11 unpacked-dimensions-range-ordering
logic t [4];
logic [LO:HI] u [LO:HI];
endmodule
@@ -0,0 +1,42 @@
#select package-filename
#path rtl/other.sv
# a package that does not match its file name
package foo_pkg;
//^ 9 package-filename
endpackage
====
#select package-filename
#path rtl/foo_pkg.sv
# both conventional spellings are accepted
package foo_pkg;
endpackage
====
#select package-filename
#path rtl/foo_pkg.sv
# a package named without the suffix, in a `_pkg` file
package foo;
endpackage
====
#select package-filename
#path rtl/foo-pkg.sv
#options package-filename.allow-dash-for-underscore = true
# a dash stands for an underscore when the project says so
package foo_pkg;
endpackage
====
#select one-module-per-file
# every module after the first is reported
module a;
endmodule
module b;
//^ 8 one-module-per-file
endmodule
====
#select one-module-per-file
# a package and an interface beside one module are not modules
package p;
endpackage
module a;
endmodule
interface i;
endinterface
@@ -0,0 +1,35 @@
#select generate-label,generate-label-prefix
# an unlabelled generate block, and a labelled one with no prefix
module m;
if (A) begin
//^ 10 generate-label
wire a;
end
for (genvar i = 0; i < 2; i++) begin : lanes
//^ 42 generate-label-prefix
wire b;
end
endmodule
====
#select generate-label,generate-label-prefix
# the convention is clean
module m;
if (A) begin : g_a
wire a;
end else begin : gen_b
wire b;
end
endmodule
====
#select generate-label-prefix
#options generate-label-prefix.prefix = ["blk_"]
# the option replaces the accepted prefixes
module m;
if (A) begin : blk_a
wire a;
end
if (B) begin : g_b
//^ 18 generate-label-prefix
wire b;
end
endmodule
@@ -0,0 +1,56 @@
#select legacy-generate-region,legacy-genvar-declaration
# the Verilog-2001 spellings, both off by default and both selected here
module m;
genvar i;
//^ 10 legacy-genvar-declaration
generate
//^ 3 legacy-generate-region
for (i = 0; i < 2; i++) begin : g_lanes
wire a;
end
endgenerate
endmodule
====
#select legacy-generate-region,legacy-genvar-declaration
# the SystemVerilog spelling has neither
module m;
for (genvar i = 0; i < 2; i++) begin : g_lanes
wire a;
end
endmodule
====
#select module-begin-block
# a sequential block written where a module item belongs
module m;
begin
//^ 3 module-begin-block
wire a;
end
endmodule
====
#select module-begin-block,v2001-generate-begin
# a bare begin inside a generate region belongs to the other rule
module m;
generate
begin : b
//^ 5 v2001-generate-begin
wire a;
end
endgenerate
endmodule
====
#select module-begin-block,v2001-generate-begin
# every legal block shape is silent
module m;
initial begin
a = 1;
end
always_comb begin
b = a;
end
generate
if (A) begin : g_a
wire c;
end
endgenerate
endmodule
@@ -0,0 +1,43 @@
#select explicit-function-lifetime,explicit-task-lifetime
# a subroutine outside a class must say which lifetime it has
module m;
function int f(int x);
//^ 16 explicit-function-lifetime
return x;
endfunction
task t();
//^ 8 explicit-task-lifetime
endtask
endmodule
====
#select explicit-function-lifetime,explicit-task-lifetime
# either keyword satisfies both rules
module m;
function automatic int f(int x);
return x;
endfunction
task static t();
endtask
endmodule
====
#select explicit-function-lifetime,explicit-task-lifetime
# a class method is exempt, and a prototype declares no locals
package p;
class c;
function int f();
return 0;
endfunction
task t();
endtask
extern function int g();
endclass
endpackage
====
#select explicit-function-lifetime
# a package-scope function is judged like a module's
package p;
function int f();
//^ 16 explicit-function-lifetime
return 0;
endfunction
endpackage
@@ -0,0 +1,41 @@
#select line-length
# a line past the default width is reported at the first column over it
module m;
wire aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;
//^ 101 line-length
endmodule
====
#select line-length
# a line at the limit is not over it
module m;
wire aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;
endmodule
====
#select line-length
#options line-length.length = 60
# the option narrows the limit
module m;
wire aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;
//^ 61 line-length
endmodule
====
#select line-length
#options line-length.length = 200
# and widens it
module m;
wire aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;
endmodule
====
#select line-length
# a line that is one unbreakable token is left alone, `;` or not
`include "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.svh"
module m;
`AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA;
endmodule
====
#select line-length
# a long comment can be wrapped, so it is reported
module m;
endmodule
// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
//^ 101 line-length
@@ -0,0 +1,83 @@
#select signal-name-style
# ports and signals are judged where they are declared
module m (input logic clkIn, output logic data_o);
//^ 23 signal-name-style
logic dataValid;
//^ 9 signal-name-style
logic wr_ptr2;
endmodule
====
#select signal-name-style
#options signal-name-style.style_regex = "[a-z][a-zA-Z0-9]*"
# the option replaces the convention
module m;
logic dataValid;
logic data_valid;
//^ 9 signal-name-style
endmodule
====
#select interface-name-style
# an interface without the `_if` suffix
interface bus;
//^ 11 interface-name-style
endinterface
====
#select interface-name-style
# the convention, and a module the rule says nothing about
interface bus_if;
endinterface
module bus;
endmodule
====
#select macro-name-style
# the defined name is judged, not the uses
`define my_macro 1
//^ 9 macro-name-style
`define MY_OTHER(a) (a)
module m;
wire x = `my_macro;
endmodule
====
#select constraint-name-style
# a constraint that does not end in `_c`
class c;
rand int addr;
constraint addr_range { addr > 0; }
//^ 14 constraint-name-style
constraint addr_max_c { addr < 9; }
endclass
====
#select parameter-type-name-style
# a type parameter named like a type, and one not
class c #(type T = int, type item_t = int);
//^ 16 parameter-type-name-style
endclass
====
#select port-name-suffix
# each direction has its own suffixes
module m (input logic clk, input logic rst_ni, output logic data_o, inout wire sda);
//^ 23 port-name-suffix
//^ 80 port-name-suffix
endmodule
====
#select port-name-suffix
#options port-name-suffix.suffixes = ["_i", "_o"]
# shortening the list bans the active-low spellings
module m (input logic clk_i, input logic rst_ni, output logic data_o);
//^ 42 port-name-suffix
endmodule
====
#select banned-declared-name-patterns
# nothing is banned until the project says so
module m;
logic tmp_addr;
endmodule
====
#select banned-declared-name-patterns
#options banned-declared-name-patterns.patterns = ["tmp.*"]
# a banned name is reported where it is declared
module m;
logic tmp_addr;
//^ 9 banned-declared-name-patterns
logic keep_me;
endmodule
@@ -0,0 +1,29 @@
#select forbid-consecutive-null-statements
# a doubled `;` is reported and the extra one deleted
module m;
initial begin
x = 1;;
//^ 11 forbid-consecutive-null-statements
end
endmodule
----
module m;
initial begin
x = 1;
//^ 11 forbid-consecutive-null-statements
end
endmodule
====
#select forbid-consecutive-null-statements
# an empty `for` header holds no statements
module m;
initial for (;;) x = 1;
endmodule
====
#select forbid-consecutive-null-statements
# a lone null statement is another rule's business
module m;
initial begin
;
end
endmodule
@@ -0,0 +1,39 @@
#select positive-meaning-parameter-name
# a parameter named for what it turns off
module m #(
parameter int DisableEcc = 0
//^ 17 positive-meaning-parameter-name
) ();
localparam int disable_crc = 1;
//^ 18 positive-meaning-parameter-name
localparam int EnableEcc = 1;
endmodule
====
#select proper-parameter-declaration
# `parameter` in a body, `localparam` in a formal list
module m #(
parameter int Width = 8,
localparam int Half = Width / 2
) ();
parameter int Depth = 4;
//^ 17 proper-parameter-declaration
localparam int Mask = 3;
endmodule
====
#select proper-parameter-declaration
# a package takes `localparam` by default and `parameter` only when told to
package p;
localparam int A = 1;
parameter int B = 2;
//^ 17 proper-parameter-declaration
endpackage
====
#select proper-parameter-declaration
#options proper-parameter-declaration.package_allow_parameter = true
#options proper-parameter-declaration.package_allow_localparam = false
# the two options move the line in opposite directions
package p;
localparam int A = 1;
//^ 18 proper-parameter-declaration
parameter int B = 2;
endpackage
@@ -0,0 +1,13 @@
#select posix-eof
# a terminated file is clean
#
# The other half of this rule — a file whose last line has no newline — cannot
# be written here: the harness rejoins every case body with a trailing newline,
# so no case input can lack one. It is pinned in the rule's own unit tests
# (`rules::posix_eof::tests`), fix included.
module m;
endmodule
====
#select posix-eof
# a file that is only a comment is terminated too
// nothing but a note
@@ -0,0 +1,78 @@
#select forbidden-macro,uvm-macro-semicolon
# the default forbidden macro, and the `;` the UVM macros do not want
module m;
initial begin
`uvm_warning("A", "B")
//^ 5 forbidden-macro
`uvm_info("A", "B", UVM_LOW);
//^ 33 uvm-macro-semicolon
`uvm_error("A", "B")
end
endmodule
====
#select forbidden-macro
#options forbidden-macro.macros = ["my_macro"]
# the option replaces Verible's one-name list
module m;
initial begin
`uvm_warning("A", "B")
`my_macro(1)
//^ 5 forbidden-macro
end
endmodule
====
#select macro-string-concatenation
# `` inside a plain string is not evaluated; inside `"..."` it is
`define GLUE(a, b) $display("a``b")
//^ 31 macro-string-concatenation
`define OK(a, b) $display(`"a``b`")
module m;
endmodule
====
#select endif-comment
# a bare `endif is named by the safe fix
`ifdef SYNTHESIS
module m;
endmodule
`endif
//^ 1 endif-comment
----
`ifdef SYNTHESIS
module m;
endmodule
`endif // SYNTHESIS
//^ 1 endif-comment
====
#select endif-comment
# nesting pairs each `endif with its own condition, and a naming comment passes
`ifdef A
`ifdef B
module m;
endmodule
`endif // B
`endif
//^ 1 endif-comment
====
#select forbid-line-continuations
# a `define may be broken across lines and a string may not. The positive
# case has no marker home here: the finding lands on the *first* line of a
# multi-line string, and a marker attaches to the line above it — which is
# inside the string. Pinned in the rule's unit tests instead, as `posix-eof`
# is; what this case pins is that a multi-line macro is never reported.
`define TWO_LINES \
wire a; \
wire b;
module m;
endmodule
====
#select numeric-format-string-style
# the prefix must name the base the specifier prints
module m;
initial begin
$display("0x%0h and 'b%0b and %d", a, b, c);
$display("0x%0b", a);
//^ 15 numeric-format-string-style
$display("0d%0d", a);
//^ 15 numeric-format-string-style
end
endmodule
@@ -26,7 +26,7 @@ module m;
void'(x);
//^ 5 void-cast
void'(f());
void'(obj.randomize() with { a inside {[0:3]}; });
void'(obj.pop() with { a inside {[0:3]}; });
end
endmodule
====
@@ -0,0 +1,32 @@
#select typedef-enums,typedef-structs-unions
# anonymous aggregates in declarations
module m;
enum logic [1:0] { IDLE, BUSY } state;
//^ 35 typedef-enums
struct packed { logic a; } s;
//^ 30 typedef-structs-unions
endmodule
====
#select typedef-enums,typedef-structs-unions
# a named type is the shape they ask for
package p;
typedef enum logic [1:0] { IDLE, BUSY } state_e;
typedef struct packed { logic a; } word_t;
endpackage
module m;
state_e state;
word_t w;
endmodule
====
#select typedef-structs-unions
#options typedef-structs-unions.allow_anonymous_nested = true
# a nested anonymous struct may be allowed; a top-level one is still not
package p;
typedef struct packed {
struct packed { logic x; } inner;
} outer_t;
endpackage
module m;
union packed { logic a; logic b; } u;
//^ 38 typedef-structs-unions
endmodule
@@ -0,0 +1,83 @@
#select create-object-name-match
# the create name is the handle's name
class c;
function automatic void build();
driver_h = my_driver::type_id::create("drv", this);
//^ 43 create-object-name-match
monitor_h = my_monitor::type_id::create("monitor_h", this);
endfunction
endclass
====
#select void-cast
# the two halves of the rule: a non-call operand, and a call whose result must be checked
class c;
function automatic void run();
void'(x);
//^ 5 void-cast
void'(f());
void'(obj.randomize());
//^ 5 void-cast
endfunction
endclass
====
#select void-cast
#options void-cast.forbidden_calls = ["my_check"]
# the forbidden-call list is the project's
class c;
function automatic void run();
void'(obj.randomize());
void'(my_check());
//^ 5 void-cast
endfunction
endclass
====
#select invalid-system-task-function
#options invalid-system-task-function.symbols = ["$stop"]
# `symbols` is Verible's `forbidden-symbol` list, folded into this one rule
module m;
initial begin
a = $random();
$stop;
//^ 5 invalid-system-task-function
end
endmodule
====
#select disable-statement
# a fork label is not something `disable` may name
module m;
initial begin : seq
fork : threads
join_none
disable seq;
disable fork;
disable threads;
//^ 5 disable-statement
end
endmodule
====
#select dff-name-style
# the `_q`/`_d` convention, its reset waiver and its mismatch
module m;
always_ff @(posedge clk) begin
if (!rst_ni) count <= '0;
else count_q <= count_d;
other_q <= wrong_d;
//^ 16 dff-name-style
plain <= count_d;
//^ 5 dff-name-style
end
assign result_q = count_d;
//^ 10 dff-name-style
endmodule
====
#select dff-name-style
#options dff-name-style.output = ["ptr"]
#options dff-name-style.input = ["nxt"]
# the suffix lists are the project's
module m;
always_ff @(posedge clk) begin
data_ptr <= data_nxt;
data_q <= data_d;
//^ 5 dff-name-style
end
endmodule
+2 -2
View File
@@ -29,13 +29,13 @@ endmodule
====
# a verible waiver for a rule lucisv does not have is ignored
module m;
// verilog_lint: waive macro-name-style
// verilog_lint: waive forbid-implicit-declarations
wire a;
endmodule
====
# lucisv's own spelling for an unknown rule is reported
module m;
// lucisv: waive macro-name-style
// lucisv: waive explicit-function-lifetime
//^ 3 unused-waiver
wire a;
endmodule
+47 -15
View File
@@ -20,6 +20,10 @@
//! - `#path <p>` — lint the source as if it were read from this file path.
//! - `#select ...` — comma-separated rule names, `lucisv check --select`
//! semantics (replaces the default rule set).
//! - `#options <rule>.<key> = <value>` — set one per-rule option for this
//! case, in the `lucisv.toml` spelling (`120`, `true`, `"[a-z]+"`,
//! `["a", "b"]`). Repeatable. A refused entry fails the case, so the
//! option's own validation is pinned here too.
//! - `#workspace [name,...]` — run the case as part of a *project*: the rules
//! that need a workspace default on, and a `MentionOracle` answers "yes,
//! some other file mentions this" for each listed name (an empty list is a
@@ -42,7 +46,7 @@ use std::path::PathBuf;
use vlog_formatter::{format_source, Config};
use vlog_linter::{
apply_fixes, lint, rule_by_name, select_rules, Applicability, LintContext, MentionOracle,
ParsedSource, Rule,
ParsedSource, Rule, RuleOptions,
};
use vlog_parser::LineIndex;
@@ -54,6 +58,8 @@ struct Case {
tolerant: bool,
path: Option<String>,
select: Vec<String>,
/// `#options`: what this case configured about its rules.
options: RuleOptions,
/// `#workspace`: `None` is a run with no oracle; `Some(names)` is a run
/// with one that says those names are mentioned in some other file.
workspace: Option<Vec<String>>,
@@ -111,6 +117,7 @@ fn split_case(file: &str, start: usize, block: &[&str]) -> Result<Case, String>
let mut tolerant = false;
let mut path = None;
let mut select = Vec::new();
let mut options = RuleOptions::new();
let mut workspace = None;
let mut body = block;
while let Some(first) = body.first() {
@@ -129,6 +136,9 @@ fn split_case(file: &str, start: usize, block: &[&str]) -> Result<Case, String>
path = Some(p.trim().to_string());
} else if let Some(s) = rest.strip_prefix("select ") {
select = s.split(',').map(|r| r.trim().to_string()).collect();
} else if let Some(entry) = rest.strip_prefix("options ") {
set_option(&mut options, entry)
.map_err(|e| format!("{file}:{start}: bad #options: {e}"))?;
} else if rest == "workspace" {
workspace = Some(Vec::new());
} else if let Some(s) = rest.strip_prefix("workspace ") {
@@ -146,7 +156,7 @@ fn split_case(file: &str, start: usize, block: &[&str]) -> Result<Case, String>
} else if directive_like {
return Err(format!(
"{file}:{start}: unknown directive `#{}` \
(known: #path, #select, #workspace, #tolerant, #SKIP; \
(known: #path, #select, #options, #workspace, #tolerant, #SKIP; \
a case name needs a space after `#`)",
rest.split_whitespace().next().unwrap_or(rest)
));
@@ -169,7 +179,20 @@ fn split_case(file: &str, start: usize, block: &[&str]) -> Result<Case, String>
if input.trim().is_empty() {
return Err(format!("{file}:{start}: case has no source"));
}
Ok(Case { name, line: start, skip, tolerant, path, select, workspace, input, fixed })
Ok(Case { name, line: start, skip, tolerant, path, select, options, workspace, input, fixed })
}
/// One `#options <rule>.<key> = <value>` entry, through the linter's own
/// validator — the same door a `lucisv.toml` comes in by.
fn set_option(options: &mut RuleOptions, entry: &str) -> Result<(), String> {
let (name, value) = entry
.split_once('=')
.ok_or_else(|| format!("expected `<rule>.<key> = <value>`, found `{entry}`"))?;
let (rule, key) = name
.trim()
.split_once('.')
.ok_or_else(|| format!("expected `<rule>.<key>`, found `{}`", name.trim()))?;
options.set_raw(rule.trim(), key.trim(), value.trim())
}
/// Attaches the case's oracle, if it declared one.
@@ -238,14 +261,17 @@ fn check_case(file: &str, case: &Case) -> Result<(), String> {
let path = case.path.clone().map(PathBuf::from);
let oracle = case.workspace.clone().map(Elsewhere);
let own = LintContext::new(&case.input, path.clone());
let own = LintContext::new(&case.input, path.clone()).with_options(&case.options);
let violations = lint(&with_oracle(own, oracle.as_ref()), &rules);
// "One parse, two tools", held over every case: a context built from
// pre-parsed products must find exactly what one built from the source
// does — rule, message, span and fix alike (the Debug form carries all).
let parsed = ParsedSource::parse(&case.input);
let via_products = lint(&with_oracle(parsed.context(path.clone()), oracle.as_ref()), &rules);
let via_products = lint(
&with_oracle(parsed.context(path.clone()).with_options(&case.options), oracle.as_ref()),
&rules,
);
if format!("{violations:?}") != format!("{via_products:?}") {
return Err(format!(
"{at}: linting from pre-parsed products found something different from \
@@ -334,12 +360,16 @@ fn check_fix(
oracle: Option<&Elsewhere>,
expected_fixed: &str,
) -> Result<(), String> {
let options = &case.options;
let mut fixed = case.input.clone();
for round in 0.. {
if round >= 10 {
return Err(format!("{at}: fixing did not settle within 10 rounds"));
}
let found = lint(&with_oracle(LintContext::new(&fixed, path.clone()), oracle), rules);
let found = lint(
&with_oracle(LintContext::new(&fixed, path.clone()).with_options(options), oracle),
rules,
);
let out = apply_fixes(&fixed, &found, false);
if out.applied == 0 {
break;
@@ -357,15 +387,17 @@ fn check_fix(
// offer a Safe fix — a violation without a fix (or with an Unsafe one)
// may legitimately survive.
let index = LineIndex::new(&fixed);
let still_fixable: Vec<String> =
lint(&with_oracle(LintContext::new(&fixed, path.clone()), oracle), rules)
.iter()
.filter(|v| v.fix.as_ref().is_some_and(|f| f.applicability == Applicability::Safe))
.map(|v| {
let (line, col) = index.line_col(v.span.start);
format!(" {line}:{col} {} — {}", v.rule, v.message)
})
.collect();
let still_fixable: Vec<String> = lint(
&with_oracle(LintContext::new(&fixed, path.clone()).with_options(options), oracle),
rules,
)
.iter()
.filter(|v| v.fix.as_ref().is_some_and(|f| f.applicability == Applicability::Safe))
.map(|v| {
let (line, col) = index.line_col(v.span.start);
format!(" {line}:{col} {} — {}", v.rule, v.message)
})
.collect();
if !still_fixable.is_empty() {
return Err(format!(
"{at}: the fixed output still has Safe-fixable findings:\n{}",
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff. Show more