Compare commits

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

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

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

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

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

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 17:49:03 -07:00
lucioandClaude Fable 5 6a15594ae8 WIP §32 header recovery — DO NOT MERGE: half-finished; a fuzz test loops without advancing and exhausts memory (crashed the machine 2026-09-03)
Checkpoint of the interrupted dev work (rate limit) so master stays
clean. Known state: a_half_typed_instantiation_is_one_error_node
(expected to invert) and tolerant_parse_equals_strict_parse_on_valid_
sources FAIL; the error_recovery test binary exceeds 6 GB under
tools/guard.sh (a non-advancing recovery loop under the delete-any-
character / truncate fuzzers). Resume in a worktree of this branch,
under tools/guard.sh, fixing the advance guarantee first.

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

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

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

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

No files matched your search

+168
View File
@@ -4,6 +4,174 @@ 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
While you type a port list, a parameter list, a function's argument
list, an instantiation's connections, or the header of a `for`/`if`/
`while`/`case`, the editor used to lose the whole surrounding module or
function: its body re-parsed at file scope, its symbols vanished from
the outline and from completion, and the orphaned `endmodule` produced a
second error. Recovery now happens inside the list: the element that
failed becomes an error element, the ones you already typed stay, the
header keeps its node, and the body binds in the right scope. One
diagnostic per typo. The strict parse (what the formatter uses) is
untouched, so every corpus file formats byte for byte as before.
Measured over the corpus with every file cut in half: error nodes fall
by 11 %; diagnostics rise by 7 % because a module whose header was cut
now survives to report its missing `endmodule` instead of vanishing
into one error node. Known gap: a half-typed `#(` override whose value
can read as a call still collapses its instantiation (filed).
## 0.36.1 — 2026-09-04
The 0.36.0 tag never published: its release commit shipped without a
CHANGELOG section (the release chain's draft lived in a session
scratchpad that a crash had wiped), and the release workflow refuses a
version without notes, as designed. 0.36.1 is 0.36.0 plus these notes.
## 0.36.0 — 2026-09-03
### The linter grows up: severities, per-rule toggles, and 19 new rules
Every lint rule now has a **severity** — `error` (would likely fail to
compile or elaborate, or silently mis-synthesize), `warning` (a probable
bug) or `style` — printed in `lucisv check` output
(`FILE:LINE:COL: warning: message [rule]`), carried in the JSON output,
mapped to red / yellow / blue in the editor, and shown in
`--rules-doc`, which now groups rules by class. `--select`, `--ignore`
and `[lint]` in `lucisv.toml` accept a severity word (`--ignore style`).
**Editor toggles.** VS Code settings gain three master switches
(`lucisv.lint.severity.error`, `.warning`, `.style`) and one setting per
rule (`lucisv.lint.rules.<rule>`: `default` / `on` / `off`), generated
from the rule registry so the list can never drift. Precedence, top to
bottom: defaults → `select` → severity switches → per-rule settings →
`ignore`. Changing any of them re-checks every open file.
**New rules — Error**: `mismatched-labels`, `duplicate-declaration`,
`undeclared-identifier` (with a project; silent for names that come
from macros, `` `include``d fragments or hierarchical paths),
`unknown-port`, `unknown-parameter`.
**New rules — Warning**: `forbid-defparam`, `invalid-system-task-function`,
`truncated-numeric-literal`, `undersized-binary-literal` (safe fix pads),
`suspicious-semicolon`, `packed-dimensions-range-ordering`, `module-port`,
`module-parameter`, `explicit-function-task-parameter-type`,
`plusarg-assignment`, `instance-shadowing`, `forbid-negative-array-dim`,
`void-cast`, `incomplete-assignment` (latch inference in `always_comb`).
Verible equivalents are named in each rule's documentation; defaults
follow Verible's except where the doc says why not. Existing rules
re-classified: `multiply-driven` and `wire-reg-mixup` are errors.
Measured on opentitan: every false-positive class found was closed with
a test; `lucisv check` over its `hw/` tree runs in the same time as
0.35.0.
## 0.35.0 — 2026-09-02
### Format fences reach statements and class bodies
`// verilog_format: off` / `// lucisv: off` (and the `lucisv:` spelling)
now protect statements inside `begin … end`, `fork … join`, function
and task bodies and `always`/`initial`/`final` blocks, and items inside
a class body — not only items at module scope. A fenced region is
copied byte for byte, keeps its own indentation, and is a fixed point
under a second pass; an unmatched `off` runs to the end of its own
list. `--lines` range formatting honours a fenced statement inside the
selected range. Four opentitan files that already carried fences inside
functions and class bodies now keep those bytes.
One rule is applied uniformly: a fence must start its line (whitespace
or a finished block comment may precede it). A fence written after code
on the same line — `module m; // lucisv: off` — is an ordinary comment,
as the fence documentation has said since the feature shipped; it used
to open a region at module scope by accident.
Not yet fenceable, with reasons in the feature README: port lists,
case-item label lists, same-line fences, and a property's local
declarations.
## 0.34.0 — 2026-09-02
### Rename tells you what it could not reach
+14
View File
@@ -128,6 +128,20 @@ Rules:
- Update `TODO.md`: check items your feature completes (leave the item
text intact).
## Runaway guard (never run a suite or sweep bare)
On 2026-09-03 a background test run consumed 100 GB and crashed the
machine. macOS enforces no memory cap, so the cap is ours:
`tools/guard.sh [-m GB] [-t SECONDS] -- <command>` kills a command's
process tree when its resident set or wall clock exceeds the limits
(defaults 8 GB / 30 min).
- **Every `cargo test`, every fuzzer, every corpus or opentitan sweep,
and every `lucisv`/`lucisv-server` run over a tree goes through
`tools/guard.sh`** — dev, QA and lead alike, foreground or background.
- A guard kill is a finding: report the command and the limit it hit;
do not raise the limit to make it pass.
## Parallel lanes (the 2-agent loop)
Up to **two dev/QA lanes may run concurrently** when — and only when —
Generated
+8 -8
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.34.0"
version = "0.40.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.34.0"
version = "0.40.0"
[[package]]
name = "lucisv_server"
version = "0.34.0"
version = "0.40.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.34.0"
version = "0.40.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.34.0"
version = "0.40.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -264,11 +264,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.34.0"
version = "0.40.0"
[[package]]
name = "vlog_refactor"
version = "0.34.0"
version = "0.40.0"
dependencies = [
"vlog_parser",
"vlog_semantic",
@@ -276,7 +276,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.34.0"
version = "0.40.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.34.0"
version = "0.40.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+208 -29
View File
@@ -172,11 +172,13 @@ would format — same walk, same `--exclude`, same `.gitignore` handling, same
`lucisv.toml` discovery.
```bash
lucisv check rtl/ # FILE:LINE:COL: message [rule-name]
lucisv check rtl/ # FILE:LINE:COL: severity: message [rule]
lucisv check --output-format json rtl/ # one JSON array, for editors and CI
lucisv check --select no-tabs rtl/ # only these rules (comma-separated)
lucisv check --ignore module-filename rtl/ # everything but these
lucisv check --select error rtl/ # a whole severity class, by name
lucisv check --fix rtl/ # apply the safe fixes, write files back
lucisv check --rules-doc # the generated reference for every rule
```
Exit codes are the frozen contract above: 0 clean (or everything fixed), 1
@@ -184,35 +186,194 @@ violations remain, 2 error. Unlike the formatter, `check` uses the
error-tolerant parser, so a file lucisv cannot fully parse is still linted for
what it can see.
| Rule | Fix | What it wants |
### Severities
Every rule is in one of three classes, and the class is the word that stands
in the diagnostic line, in the JSON `severity` field, and in the editor's
squiggle colour:
| Class | Means | Editor |
|---|---|---|
| `no-tabs` | safe | spaces, not tabs (a tab inside a string is left alone) |
| `no-trailing-whitespace` | safe | nothing but code before the newline |
| `case-missing-default` | — | every `case`/`casex`/`casez` has a `default` |
| `always-ff-non-blocking` | — | `<=` inside `always_ff` |
| `always-comb-blocking` | — | `=` inside `always_comb` |
| `explicit-parameter-storage-type` | — | `parameter int W = 8`, not `parameter W = 8` |
| `module-filename` | — | a one-module file is named after its module |
| `unused-waiver` | — | waivers that suppress nothing |
| `unused-signal` † | — | no net or variable nothing uses |
| `undriven-net` † | — | everything read is driven by something |
| `multiply-driven` † | — | one driver per variable |
| `error` | would very likely fail to compile, elaborate or synthesize | red (LSP Error) |
| `warning` | compiles, and very likely does not mean what it says | yellow (LSP Warning) |
| `style` | correct, and reads badly | blue (LSP Information) |
A class name is accepted **wherever a rule name is** — on `--select`, on
`--ignore`, and in `select`/`ignore` under `[lint]` in `lucisv.toml`:
```bash
lucisv check --select error rtl/ # only the compile-breakers
lucisv check --ignore style rtl/ # everything but the naming rules
```
Every `error`-class rule follows one discipline: **silence beats a wrong
accusation**. Each of them goes quiet whenever the run cannot answer — a file
that did not fully parse, a module the project does not hold or holds twice, a
name a macro produces, a fragment written to be `` `include``d. That is what
makes an editor's red squiggle worth believing.
### The rules
| Rule | Severity | Fix | What it wants |
|---|---|---|---|
| `multiply-driven` † | error | — | one driver per variable |
| `wire-reg-mixup` | error | — | `logic`, not `reg`, in a `.sv` file |
| `mismatched-labels` | error | — | `end : name` names the block it closes |
| `duplicate-declaration` | error | — | each name declared once per scope |
| `undeclared-identifier` † | error | — | every name is declared somewhere in the project |
| `unknown-port` † | error | — | `.name(…)` is a port the module declares |
| `unknown-parameter` † | error | — | `#(.NAME(…))` is a parameter it declares |
| `always-ff-non-blocking` | warning | — | `<=` inside `always_ff` |
| `always-comb-blocking` | warning | — | `=` inside `always_comb` |
| `case-missing-default` | warning | — | every `case`/`casex`/`casez` has a `default` |
| `incomplete-assignment` | warning | — | an `always_comb` assigns on every path |
| `suspicious-semicolon` | warning | — | no `if (x);` / `for (…);` / `while (…);` |
| `forbid-defparam` | warning | — | override at the instantiation, not with `defparam` |
| `invalid-system-task-function` | warning | — | no `$random`, `$psprintf`, `$dist_*`, `$srandom` |
| `plusarg-assignment` | warning | — | `$value$plusargs`, not `$test$plusargs` |
| `truncated-numeric-literal` | warning | — | a sized literal fits its width |
| `undersized-binary-literal` | warning | safe | every bit of a sized binary literal is written |
| `packed-dimensions-range-ordering` | warning | — | a packed dimension is `[N-1:0]` |
| `forbid-negative-array-dim` | warning | — | no negative literal in a dimension |
| `module-port` | warning | — | more than one port is connected by name |
| `module-parameter` | warning | — | more than one parameter is overridden by name |
| `explicit-function-task-parameter-type` | warning | — | every tf argument has a storage type |
| `void-cast` | warning | — | `void'(…)` wraps a call |
| `instance-shadowing` | warning | — | no declaration hides an enclosing one |
| `undriven-net` † | warning | — | everything read is driven by something |
| `unused-signal` † | warning | — | no net or variable nothing uses |
| `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 |
| `explicit-parameter-storage-type` | style | — | `parameter int W = 8`, not `parameter W = 8` |
| `module-filename` | style | — | a one-module file is named after its module |
| `enum-name-style` | style | — | `lower_snake_case` ending `_e`/`_t` |
| `struct-union-name-style` | style | — | `lower_snake_case` ending `_t` |
| `parameter-name-style` | style | — | `CamelCase` or `ALL_CAPS` |
| `module-name-style` | style | — | `lower_snake_case` (off by default) |
| `line-length` | style | — | no line wider than the width the formatter uses |
| `posix-eof` | style | safe | the file ends with a newline |
| `forbid-consecutive-null-statements` | style | safe | no `;;` where a statement belongs |
| `generate-label` | style | — | every generate block carries a `: label` |
| `generate-label-prefix` | style | — | that label starts with `g_` or `gen_` |
| `package-filename` | style | — | a one-package file is named after its package |
| `interface-name-style` | style | — | `lower_snake_case` ending `_if` |
| `macro-name-style` | style | — | a `` `define`` name is `ALL_CAPS` |
| `constraint-name-style` | style | — | `lower_snake_case` ending `_c` |
| `typedef-enums` | style | — | an `enum` type is named with a `typedef` |
| `typedef-structs-unions` | style | — | a `struct`/`union` type is named with a `typedef` |
| `always-comb` | style | unsafe | `always_comb`, not `always @*` |
| `signal-name-style` | style | — | `lower_snake_case` signals (off by default) |
| `parameter-type-name-style` | style | — | `lower_snake_case` ending `_t` type parameters (off) |
| `port-name-suffix` | style | — | `_i` / `_o` / `_io` say which way a port points (off) |
| `one-module-per-file` | style | — | one `module` per file (off by default) |
| `banned-declared-name-patterns` | style | — | no declared name matching a project's own list (off) |
| `explicit-begin` | style | safe | every body is a `begin ... end` block (off by default) |
| `unused-waiver` | style | — | waivers that suppress nothing |
| `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
them. These three read the file's *symbol table*, not just its syntax; the
project-wide identifier census keeps a hierarchical use in another file from
becoming a false positive. See `docs/features/semantic-lints-on/README.md`.
The table above is not the whole set — naming-style rules ship too, and
`cargo run -p vlog_linter --example rules_markdown` prints the generated
reference for every rule with its default.
them. These rules read the file's *symbol table* and ask the project about
names, not just the file's syntax; the project-wide identifier census keeps a
hierarchical use in another file from becoming a false positive. See
`docs/features/semantic-lints-on/README.md` and
`docs/features/linter-expansion-1/README.md`.
`lucisv check --rules-doc` prints the whole reference — every rule, its class,
its default, its fix and the paragraph saying why it exists — generated from
the registry, so it can never be out of date.
Fixes follow ruff's applicability model: `--fix` applies *safe* fixes (those
that cannot change what the code means), `--unsafe-fixes` widens that — no
rule ships an unsafe fix yet. Violations inside a `// verilog_format: off`
that cannot change what the code means), `--unsafe-fixes` widens that to the
rest. One rule ships an unsafe fix: `always-comb` rewrites `always @*` to
`always_comb`, which is a different block at time zero and makes a second
driver of its outputs an error — right nearly always, and not lucisv's call to
make without being asked. Violations inside a `// verilog_format: off`
region are reported but never fixed: `off` means hands-off for the linter too,
so `--fix` leaves every byte of a fenced region exactly as written.
### Rule options
A rule can be configured in a `[lint.<rule-name>]` table:
```toml
[lint]
ignore = ["typedef-structs-unions"]
[lint.line-length]
length = 120 # the linter's limit, if not the formatter's
[lint.generate-label-prefix]
prefix = ["g_", "gen_"] # the label prefixes this project writes
[lint.parameter-name-style]
localparam_style = "CamelCase" # Verible's own default, stricter than ours
[lint.signal-name-style]
style_regex = "[a-z][a-z_0-9]*" # a pattern, matched against the whole name
```
The keys are Verible's wherever it has the same option, so a `.rules.verible`
file translates word for word. An option nobody sets reads the default
`lucisv check --rules-doc` prints beside it. An unknown rule or option name, a
value of the wrong kind, an integer out of range or a pattern that does not
compile **fails the run**, naming the config file and the line — a typo in a
lint setting is not something to guess at.
Patterns are not full RE2. What is supported: literals, `.`, `[...]` classes
with ranges and negation, the escapes `\d \D \w \W \s \S` (character
classes), `\n \t \r` (control characters) and `\<punctuation>` (that
character, literally), groups, `|`, and the postfix `*` `+` `?` — matched
against the **whole** name, so `^`/`$` are accepted and redundant.
Everything else is **refused when the option is read, by name**: counted
repetition (`{2,3}`), lookaround and flag groups (`(?=…)`, `(?:…)`), and every
escape not listed above — a backreference (`\1`), a word boundary (`\b`),
`\A`, `\z`, `\p{…}`, `\x41`. An unsupported escape read as a literal would
quietly judge the wrong names (`\bword\b` would match `bwordb`), which is
worse than an error you can read.
Matching is a Thompson-NFA simulation, so it is linear in pattern × name
length whatever shape the pattern has: no pattern can make `lucisv check` — or
an editor session — hang.
From an editor the same options are one object, `lucisv.lint.options`:
```json
"lucisv.lint.options": {
"line-length": { "length": 120 },
"typedef-structs-unions": { "allow_anonymous_nested": false }
}
```
There the precedence is **the editor's value, then the `lucisv.toml`, then the
rule's default — key by key**: a project can set two options and one user
override the third without losing the others. (This is the opposite order to
the formatting settings, where a checked-in `lucisv.toml` outranks the editor:
formatting has a byte-exact contract with CI, and which findings you are shown
in your own editor is yours to choose.) A bad entry there is *ignored* and
reported in the lucisv log rather than fatal, so one typo cannot leave a
session with no diagnostics.
### Waivers
```systemverilog
@@ -302,8 +463,8 @@ both layouts are fixed points of re-formatting:
### Turning the formatter off
Items between a `// verilog_format: off` and a `// verilog_format: on`
comment are emitted as the exact source bytes they were written with,
Everything between a `// verilog_format: off` and a `// verilog_format: on`
comment is emitted as the exact source bytes it was written with,
indentation included — the escape hatch for hand-aligned tables and the
like. `// lucisv: off` / `// lucisv: on` is an accepted alias.
@@ -317,12 +478,30 @@ module m;
endmodule
```
The fence must be a line comment on its own line, and its text must match
exactly — `// lucisv: off for now` is an ordinary comment, not a fence. An
`off` with no matching `on` runs to the end of the enclosing item list
(module body, package body, generate block, or the file). Fences select
whole items; one written between two *statements* has no effect yet. Full
rules: `docs/features/format-fences/README.md`.
A fence works between **items** — module, package and class members, and
top-level items — and between **statements**: inside `begin`…`end`,
`fork`…`join*`, and function, task, `initial`, `always` and `final` bodies.
```systemverilog
class scoreboard;
function void build_phase();
// verilog_format: off
uvm_config_db#(cfg_t)::set(this, "env.agent", "cfg",
cfg.agent_cfg); // hand-wrapped, left alone
// verilog_format: on
endfunction
endclass
```
The fence must be a line comment that begins its own line, and its text must
match exactly — `// lucisv: off for now` is an ordinary comment, not a fence,
and so is one written after code on the same line (`wire a; // lucisv: off`,
`begin // lucisv: off`). An `off` with no matching `on` runs to the end of the
enclosing list and no further: the module body, the class body, the
`begin`…`end`, the function body, or the file. A fence inside a port list, a
parameter list or a `case` **label** list is still an ordinary comment. Full
rules: `docs/features/format-fences/README.md` and
`docs/features/statement-fences/README.md`.
### Range formatting (`--lines`)
+556 -25
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
@@ -3314,15 +3314,22 @@ READMEs, README.md "Turning the formatter off", docs/topo.md §2.9-3
struck (lead), TODO §31. Runs after §29/§30 merge (format/ collides
with §30's routine.rs only at merge; disjoint files otherwise — the
lead may start it in parallel if §30's files are settled).
- [ ] 31.1 class bodies (+ any other item-list carrier), cases, §2.9-3
- [ ] 31.2 statement lists: scan, merge, `stmt_seq`/`stmt` rules,
line-start gate, trailing-comment end, range planner re-check
- [ ] 31.3 docs rewritten (format-fences README, README.md, the
- [x] 31.1 class bodies (+ any other item-list carrier), cases, §2.9-3 —
`Interface`/`Program` are `ItemKind::Module` and were already scanned,
there is no `Checker` node, and `PropSeqDecl.locals` is deferred (it is
the one `Vec<Item>` not printed through `item_seq`)
- [x] 31.2 statement lists: scan, merge, `stmt_seq`/`stmt` rules,
line-start gate, trailing-comment end, range planner re-check — the
planner now merges `collect`'s fences into `Plan.regions`, without
which `--lines` would have reformatted a fenced statement
- [x] 31.3 docs rewritten (format-fences README, README.md, the
inverted case), deferrals listed with reasons
- [ ] Attack pairs + the fences.rs triple per scope; verify.rs untouched
- [ ] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
byte-identical; opentitan fence census + sweep
- [ ] QA: fences in every statement scope listed and in the three
- [x] Attack pairs + the fences.rs triple per scope; verify.rs untouched
- [x] Gates: fmt/clippy/`cargo test --workspace` 3 244/0/42 (was
3 234/0/42); corpus 814/820, 860 files byte-identical to the 0.34.0
binary; opentitan census 9 fenced files of 3 947 — 4 moved, each
keeping its own fenced bytes, `--check` counts unchanged
- [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
@@ -3447,24 +3454,548 @@ only), crates/lucisv_server/src/perf.rs (measurement only), docs/
features/header-recovery/README.md (new), amendments in error-recovery
README, docs/coverage_gaps.md M10, TODO §32. Runs after §31 (parser +
formatter collide with §30's tf.rs/module.rs at merge; sequential).
- [ ] 32.1 error elements in the four list types + `ExprKind::Error`;
cross-crate arms pre-agreed
- [ ] 32.2 `element_or_recover` with the list-local, bracket-seeded
- [x] 32.1 error elements in the four list types + `ExprKind::Error`;
cross-crate arms pre-agreed — one generic `ListElem<T>` over five
lists (a class's parameter ports are the fifth)
- [x] 32.2 `element_or_recover` with the list-local, bracket-seeded
sync set (`,` `)` `;` line change)
- [ ] 32.3 headers keep their node (port, param, tf-port, connection
- [x] 32.3 headers keep their node (port, param, tf-port, connection
lists infallible in tolerant mode; closers via `expect_closer`)
- [ ] 32.4 `for`/`if`/`while`/`case` conditions recover inside the
parentheses
- [ ] 32.5 parser pins per shape with exact counts; walkers extended;
- [x] 32.4 `for`/`if`/`while`/`case` conditions recover inside the
parentheses (`repeat` and `do…while` too, same helper)
- [x] 32.5 parser pins per shape with exact counts; walkers extended;
550-source equality and the fuzzers green
- [ ] 32.6 server pins: symbols survive, completion scope survives, one
- [x] 32.6 server pins: symbols survive, completion scope survives, one
diagnostic, validity probes unchanged
- [ ] 32.7 docs + measurements (parse_tolerant timing, truncated-corpus
diagnostic census)
- [ ] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
- [x] 32.7 docs + measurements (parse_tolerant timing, truncated-corpus
diagnostic census — error nodes 622 → 555, diagnostics 1 702 →
1 826: the constructs that now survive report their own missing
closers)
- [x] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
byte-identical (strict path untouched); opentitan read-only sweep
unchanged
- [ ] QA: type each of the (a)–(f) shapes into the real server against
- [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
## 33. Linter expansion, wave 1 (planned 2026-09-02) — severities, per-rule editor toggles, and the Error/Warning-class rules
Owner's ask: expand the linter toward what Verible's linter covers (62
rules, https://chipsalliance.github.io/verible/lint.html), expose every
rule in VS Code as a toggle grouped by severity so a user can enable or
disable rules one at a time or a whole severity at once, and put the
style rules and the "would likely fail to compile or synthesize" rules
first. Today: 17 rules, no severity notion (`Rule` has `name`,
`summary`, `doc`, `default_on`, `needs_workspace`, `fix`, `check`), every
editor diagnostic is `WARNING`, the editor surface is
`lucisv.lint.select`/`ignore` lists. Dev Opus 5, QA Sonnet 5. Feature
README: `docs/features/linter-expansion-1/README.md`. Runs in a
worktree in parallel with §31 (fences: `vlog_formatter`, README.md's
"Turning the formatter off" section only); this lane owns
`vlog_linter`, `lucisv/src/lint.rs` + args, `lucisv_server/src/
{settings,lint}.rs`, `editors/vscode/{package.json,README.md}`, README.md's
"Linting" section, `docs/site/.../reference/rules.md`.
**33.0 Severity, end to end.**
(a) `vlog_linter`: `pub enum Severity { Error, Warning, Style }` with
`as_str` (`error`/`warning`/`style`) and `Rule::severity(&self) ->
Severity` (no default — every rule states it; the reason goes in the
rule's `doc`). Assignments for the 17: **Error** — `multiply-driven`
(two procedural drivers of one variable is an elaboration error in
SystemVerilog), `wire-reg-mixup` (a procedural assignment to a net is a
compile error); **Warning** — `always-comb-blocking`,
`always-ff-non-blocking`, `case-missing-default`, `undriven-net`,
`unused-signal`; **Style** — `empty-item`, `enum-name-style`,
`explicit-parameter-storage-type`, `module-filename`,
`module-name-style`, `no-tabs`, `no-trailing-whitespace`,
`parameter-name-style`, `struct-union-name-style`, `unused-waiver`.
`Violation` carries the severity (set by the runner from the rule, not
by each rule). (b) `select_rules(select, ignore, …)` accepts a severity
name wherever a rule name is accepted — `--select style`, `--ignore
warning`, `[lint] ignore = ["style"]` — expanding to every rule of that
severity; an unknown name still fails naming the file. (c) CLI text
output becomes `FILE:LINE:COL: error|warning|style: message [rule]`
(the severity word is new; pin the old tests to the new shape); JSON
gains `"severity"`. Exit codes unchanged. (d) Editor:
`DiagnosticSeverity::ERROR` / `WARNING` / `INFORMATION` respectively;
`source` unchanged. (e) `--rules-doc` and `rules_markdown()`: a
Severity column, sections grouped by severity, the intro explaining the
three words.
**33.1 Editor toggles, generated from the registry.** In
`editors/vscode/package.json`: three master switches
`lucisv.lint.severity.error`, `.warning`, `.style` (boolean, default
true, `order` 10/11/12, description naming what each class means), and
one boolean per rule `lucisv.lint.rules.<rule-name>` (default = the
rule's default; `markdownDescription` = `**severity** — summary`; the
project-only rules say "on where lucisv can see the project"; `order`
sorted by severity then name so the Settings UI groups them; the
existing `lucisv.lint.select`/`ignore` stay, documented as the
power-user spelling). Generated, not hand-written: a
`crates/vlog_linter/examples/vscode_lint_settings.rs` (or a `tools/`
script driving `cargo run --example`) that prints the JSON fragment,
and a `crates/lucisv_server` test that parses package.json and asserts
the `lucisv.lint.rules.*` set, defaults and descriptions equal the
registry — the drift guard, so a new rule cannot ship without its
toggle. The server (`settings.rs`) reads all of them; the enabled set
is computed in one documented function `enabled_rules(settings,
has_oracle)` with this precedence, top to bottom: (1) the base set is
the defaults (`default_on`, and `needs_workspace` rules only with an
oracle); (2) a non-empty `select` replaces the base set; (3) a severity
switch that is off removes every rule of that severity; (4) an
explicitly set per-rule toggle sets or clears that rule; (5) `ignore`
removes — the off switch of last resort. Pinned by a table test.
Changing any of them republishes every open file, as select/ignore do.
The CLI has parity through select/ignore with severity names; no
per-rule flags (`--ignore rule` is that).
**33.2 New rules, Error class** (each a file under `rules/`, its own
tests, its doc with the Verible name where one exists, and a measured
false-positive count on opentitan — see QA):
- `mismatched-labels` (Verible, off there; **on** here, Error): an end
label that does not match its block's name (`end : wrong`, `endmodule
: other`) — a compile error. Reuse what linked-editing already pairs.
- `duplicate-declaration` (Error): the same name declared twice in one
scope (port and signal, two signals, two params). Ask the binder:
`Binder::declare` sees the second declaration — record it (a
`Semantics` query `duplicates()` or a per-scope check), skip generate
scopes and macro-expanded text; no false positive on `input clk`
+ `logic clk` non-ANSI redeclaration (legal) — pin it.
- `undeclared-identifier` (Error, `needs_workspace`): a use the file
did not resolve and the workspace overlay left `StillUnresolved`/
`NotFound`, excluding: names inside macro invocations, system names,
names a `` `define`` in scope produces, names the file's macro-word
census contains, hierarchical tails, names in a package this file
wildcard-imports when that package is not indexed. Measured on
opentitan; ships default-on only if the count of unexplained
findings on that tree is 0 — otherwise default-off with the
measurement and the reason in the doc.
- `unknown-port` and `unknown-parameter` (Error, `needs_workspace`): a
named connection `.x(…)` / override `.P(…)` naming a port or
parameter the instantiated module does not declare (the index
exports both). Silent when the module is not indexed or is declared
twice with different shapes.
**33.3 New rules, Warning class** (Verible name, default there → here):
- `forbid-defparam` (on → on): `defparam` is deprecated and rejected by
some tools.
- `invalid-system-task-function` (on → on): `$psprintf`, `$random`
(use `$urandom`), `$dist_*`, `$srandom` … Verible's list, cited.
- `truncated-numeric-literal` (on → on): a sized literal whose value
does not fit its width (`4'hFFF`).
- `undersized-binary-literal` (on → on, safe fix pads): `8'b1`; binary
only by default, as Verible.
- `suspicious-semicolon` (off → **on**): `if (x);`, `for (…);`,
`while (…);` — a body that is a null statement.
- `packed-dimensions-range-ordering` (on → on): a packed dimension
written `[0:N-1]`.
- `module-port` and `module-parameter` (on → on): positional
connections/overrides when more than one port/parameter.
- `explicit-function-task-parameter-type` (on → on): an untyped tf
argument is a 1-bit `logic` — a silent truncation.
- `plusarg-assignment` (on → on): `$value$plusargs` result unused /
`$test$plusargs` misuse, as Verible defines it.
- `instance-shadowing` (off → **on**): a declaration shadowing one in
an enclosing scope of the same unit (the binder knows).
- `forbid-negative-array-dim` (off → on): a negative literal in a
dimension.
- `void-cast` (on → on): `void'(…)` around anything but a function
call that has a return value (Verible's rule).
- `incomplete-assignment` (no Verible equivalent; Warning): in an
`always_comb`, a variable assigned in the `then` branch of an `if`
with no `else` (or in some `case` items, not `default`) and not
assigned unconditionally earlier in the block — latch inference.
Conservative by construction: only flag when the block has no
unconditional assignment to that variable before the `if`/`case`;
measured on opentitan.
**33.4 Docs and measurement.** README.md "Linting" (severities, the
toggles, select/ignore with severity names), `editors/vscode/README.md`
settings table, the docs-site rules page (hand-written prose today —
add the new rules with their severity and a note that `--rules-doc` is
the generated truth), CHANGELOG untouched (the lead writes it). For
every new rule: findings on the corpus and on opentitan `hw/`
(read-only `lucisv check`), with ten findings read and classified per
rule (true / false positive / needs judgment); opentitan is lint-clean
under Verible, so a Verible-equivalent rule that fires there needs an
explanation (their config disables it, or our reading differs — say
which). Timing: `lucisv check` over opentitan before/after (the
semantic rules already dominate; the new ones must not add more than a
few percent).
Files: crates/vlog_linter/src/{registry.rs, rule_docs.rs, violation.rs,
lib.rs, rules/mod.rs, rules/<new>.rs, context.rs (if a semantics query
is needed), visit.rs (new walkers)} + tests/cases/*.lint,
crates/vlog_linter/examples/vscode_lint_settings.rs (new),
crates/vlog_semantic (only if `duplicates()`/shadowing needs a query —
additive, say so in Handshakes), crates/lucisv/src/{lint.rs, args.rs}
+ tests, crates/lucisv_server/src/{settings.rs, lint.rs} + tests,
editors/vscode/{package.json, README.md}, README.md "Linting",
docs/site/src/content/docs/reference/rules.md, docs/features/
linter-expansion-1/README.md (new), TODO §33. Worktree `lint-1`.
- [x] 33.0 `Severity` on every rule; select/ignore by severity; CLI
text/JSON; editor severities; `--rules-doc` grouped
- [x] 33.1 package.json toggles generated + drift test; `enabled_rules`
precedence pinned; republish on change
- [x] 33.2 Error rules: mismatched-labels, duplicate-declaration,
undeclared-identifier (measured; default decided by the count),
unknown-port, unknown-parameter
- [x] 33.3 Warning rules: the thirteen listed, each with tests and an
opentitan count
- [x] 33.4 docs; measurements table in the README
- [x] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
byte-identical (formatter untouched); opentitan read-only
`lucisv check` census + timing
- [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`)
## 34. Linter expansion, wave 2 (planned 2026-09-03) — per-rule options, and the first eighteen Style rules
After §33 (36 rules, severities, toggles). Two things this wave adds:
the **option plumbing** every configurable rule needs, and the Style
rules from Verible's list that carry the most weight in a style guide
(naming, file layout, generate labels, typedefs, line length). Dev
Opus 5, QA Sonnet 5. Feature README: `docs/features/linter-expansion-2/
README.md`. Mapped: `lucisv_core::config` parses one table, `[lint]`,
with `select`/`ignore`, and rejects `[lint.<rule>]` by name
(`config.rs::parse_entry`: "per-rule lint settings … are not supported
yet"); the editor has `lucisv.lint.select/ignore/severity.*/rules.*`;
`Rule` has no notion of options; `LintContext` carries source, tokens,
tree, semantics slot and the oracle; `line-length` already lives in
`FileConfig` for the formatter.
**34.0 Options, end to end.**
(a) `vlog_linter`: `pub struct OptionSpec { name: &'static str, kind:
OptionKind (Bool | Int { min, max } | Str | Regex | List), default:
OptionValue, doc: &'static str }` and `Rule::options(&self) ->
&'static [OptionSpec]` (default empty); `RuleOptions` — a validated
map `rule → key → OptionValue` built by `RuleOptions::parse(rule, key,
raw)` that rejects an unknown key ("rule `x` has no option `y`; it has:
…"), a wrong kind, an out-of-range int or an invalid regex, each with
the message the two front ends print with file and line. `LintContext`
carries `&RuleOptions`; a rule reads `ctx.option_str(NAME, "pattern")`
etc. with the spec's default as the fallback, so a rule never sees
"unset". (b) `lucisv_core::config`: `[lint.<rule>]` tables accepted —
`key = value` for bool/int/string, `key = ["a", "b"]` for lists —
stored raw in `FileConfig::lint_options: Vec<(rule, key, raw, line)>`
(the core crate does not know the rules); the CLI resolves them
against the registry per file the way `[lint] select` names are
checked, failing the run with file:line on the first bad entry. (c)
Editor: `lucisv.lint.options` (object; `{"<rule>": {"<key>": value}}`,
`additionalProperties`), parsed in `settings.rs`, validated the same
way — a bad entry is a `window/logMessage` warning and is ignored, so
one typo cannot switch the linter off; republish on change. (d)
Precedence: editor options over `lucisv.toml` options over the spec
default, key by key (the same ladder `lucisv.lineLength` uses — cite
`format::settings_for`). (e) `--rules-doc` lists each rule's options
with kind, default and doc; the VS Code generator emits nothing per
option (the object setting covers them) but its description names the
options each rule takes. (f) Pins: parse/validate table tests; a
`lucisv.toml` with `[lint.line-length] length = 120` changes the
verdict; the editor object does the same over the wire; a bad key
fails the CLI naming file:line and only logs in the editor.
**34.1 Options on the existing naming rules** (so the family is
consistent before the new members arrive): `enum-name-style`,
`struct-union-name-style`, `module-name-style`, `parameter-name-style`
gain the option Verible gives them (`style_regex`; `parameter-name-
style` gets `localparam_style`/`parameter_style` with Verible's
`CamelCase|ALL_CAPS` vocabulary plus the `_regex` overrides); defaults
reproduce today's behaviour exactly (pin: the corpus and opentitan
finding lists are byte-identical with no options set).
**34.2 New Style rules** (Verible name; default there → here; options):
- `line-length` (on; `length`, default = the formatter's configured
`line-length`, else 100) — a token-aware check that ignores a line
that is one unbreakable token (a long string or macro invocation),
as Verible does.
- `posix-eof` (on; safe fix appends the newline).
- `forbid-consecutive-null-statements` (on; safe fix) — `;;` at
statement level, the statement twin of `empty-item`.
- `generate-label` (on) and `generate-label-prefix` (on; `prefix`
list, default `g_`/`gen_`).
- `package-filename` (on; `allow-dash-for-underscore`, same as
`module-filename`).
- `one-module-per-file` (off).
- `signal-name-style` (off; `style_regex`, default `[a-z_0-9]+`).
- `interface-name-style` (on; `style_regex`, default `[a-z_0-9]+(_if)`).
- `macro-name-style` (on; `style_regex`, default `[A-Z_0-9]+`; the
macro's own name from the `` `define`` table).
- `constraint-name-style` (on; `pattern`, default `([a-z0-9]+_)+c`).
- `parameter-type-name-style` (off; lower_snake + `_t`).
- `port-name-suffix` (off; `_i`/`_o`/`_io`/`_ni`/`_no`/`_nio` per
Verible; option `suffixes` list).
- `banned-declared-name-patterns` (off; `patterns` list of regexes).
- `typedef-enums` (on) and `typedef-structs-unions` (on;
`allow_anonymous_nested`).
- `always-comb` (on; **unsafe** fix rewriting `always @*`/`@(*)` to
`always_comb` — the two are not identical at time zero, so the fix is
offered but not applied by default).
- `explicit-begin` (off; the eleven `*_enable` bool options Verible
has; safe fix wraps the body in `begin`/`end`).
Each: its own file, true positives and near-misses, a `.lint` case,
corpus + opentitan counts with ten findings read and classified;
opentitan is Verible-clean for its `dvsim` filesets, so a
Verible-default rule that fires inside them needs an explanation.
**34.3 Docs and toggles.** The VS Code generator regenerates the 18 new
`lucisv.lint.rules.*` entries (the drift test enforces it); README.md
"Linting" gains the options section and the rows; `editors/vscode/
README.md` documents `lucisv.lint.options`; the docs-site rules page
gains the sections; CHANGELOG untouched (the lead writes it).
Remaining Verible rules — `module-begin-block`, `legacy-generate-
region`, `legacy-genvar-declaration`, `v2001-generate-begin`,
`explicit-function-lifetime`/`explicit-task-lifetime`,
`positive-meaning-parameter-name`, `suggest-parentheses`,
`unpacked-dimensions-range-ordering`, `uvm-macro-semicolon`,
`create-object-name-match`, `numeric-format-string-style`,
`macro-string-concatenation`, `disable-statement`, `forbidden-macro`/
`forbidden-symbol`, `endif-comment`, `forbid-line-continuations`,
`dff-name-style`, `proper-parameter-declaration` — are §35, wave 3.
Files: crates/vlog_linter/src/{registry.rs (OptionSpec, options()),
options.rs (new: OptionKind/OptionValue/RuleOptions), context.rs,
rule_docs.rs, vscode.rs, lib.rs, rules/<new>.rs, rules/<naming>.rs}
+ tests/cases/*.lint, crates/lucisv_core/src/config.rs (+ tests),
crates/lucisv/src/{lint.rs, args.rs?} + tests, crates/lucisv_server/
src/{settings.rs, lint.rs} + tests, editors/vscode/{package.json,
README.md}, README.md "Linting", docs/site/.../reference/rules.md,
docs/features/linter-expansion-2/README.md (new), TODO §34. Worktree
`lint-2`; disjoint from §32 (parser) so the two may run in parallel.
Every suite and sweep under `tools/guard.sh`.
- [x] 34.0 options end to end (spec, validation, toml table, editor
object, precedence, --rules-doc); pins
- [x] 34.1 options on the four existing naming rules; defaults
byte-identical
- [x] 34.2 the eighteen Style rules, each with tests, counts and ten
classified findings
- [x] 34.3 docs + regenerated toggles
- [x] Gates (guarded): fmt/clippy/`cargo test --workspace`; corpus
814/820 byte-identical; vsix smoke; opentitan read-only census +
timing vs 0.36.0
- [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`)
+136 -23
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
@@ -50,6 +56,11 @@ pub struct Plan {
/// a rule asks about one name at a time and never about a file.
pub struct Census {
files: HashMap<String, u32>,
/// Module or interface name → what it declares, `None` for a unit the run
/// cannot answer for: a header carrying a compiler directive, or two
/// declarations that disagree. Empty when no enabled rule asked for it —
/// building it costs a parse of every file in the run.
interfaces: HashMap<String, Option<vlog_linter::ModuleInterface>>,
}
impl Census {
@@ -58,27 +69,61 @@ impl Census {
/// A file that cannot be read or does not lex contributes nothing, which
/// is the same all-or-nothing rule the rest of the run gives it: the
/// file's own check reports the error.
fn of(jobs: &[Job]) -> Census {
let per_file: Vec<Vec<String>> = jobs
///
/// `interfaces` says whether the run also needs each unit's ports and
/// parameters (`unknown-port`, `unknown-parameter`). It costs a **parse**
/// of every file on top of the lex the word census already pays for, so
/// it is built only when some enabled rule asks — measured on opentitan
/// `hw/` in `docs/features/linter-expansion-1/README.md`.
fn of(jobs: &[Job], interfaces: bool) -> Census {
type PerFile = (Vec<String>, Vec<(String, Option<vlog_linter::ModuleInterface>)>);
let per_file: Vec<PerFile> = jobs
.par_iter()
.map(|job| match std::fs::read_to_string(&job.path) {
Ok(src) => words::harvest_text(&src),
Err(_) => Vec::new(),
.map(|job| {
let Ok(src) = std::fs::read_to_string(&job.path) else {
return (Vec::new(), Vec::new());
};
if !interfaces {
return (words::harvest_text(&src), Vec::new());
}
// One lex for both halves: the parse is what the interface
// table needs, and its tokens are the word census's.
let parsed = ParsedSource::parse(&src);
(words::harvest(parsed.tokens()), vlog_linter::module_interfaces(parsed.file()))
})
.collect();
let mut files: HashMap<String, u32> = HashMap::new();
for words in per_file {
let mut units: HashMap<String, Option<vlog_linter::ModuleInterface>> = HashMap::new();
for (words, declared) in per_file {
for word in words {
*files.entry(word).or_default() += 1;
}
for (name, interface) in declared {
// Two declarations of one name answer only when they agree;
// anything else is a question the run cannot settle.
units
.entry(name)
.and_modify(|held| {
if *held != interface {
*held = None;
}
})
.or_insert(interface);
}
}
Census { files }
Census { files, interfaces: units }
}
/// How many files in the run write `name` down.
fn count(&self, name: &str) -> u32 {
self.files.get(name).copied().unwrap_or(0)
}
/// What the run says `name` declares, or `None` when it cannot say.
fn interface(&self, name: &str) -> Option<vlog_linter::ModuleInterface> {
self.interfaces.get(name)?.clone()
}
}
/// One file's view of the census: everything the project says, minus what
@@ -96,6 +141,13 @@ impl MentionOracle for Elsewhere<'_> {
let mine = u32::from(self.own.binary_search_by(|w| w.as_str().cmp(name)).is_ok());
self.census.count(name) > mine
}
/// The run's interface table, which covers **every** file including this
/// one: a module is instantiated as often in the file that declares it as
/// anywhere else, and there is nothing to subtract here.
fn module_interface(&self, name: &str) -> Option<vlog_linter::ModuleInterface> {
self.census.interface(name)
}
}
/// Resolve the run: the rules for each file, and whether a census is owed.
@@ -117,13 +169,53 @@ pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Res
let ignore = pick(&opts.ignore, file_config.lint_ignore.as_deref());
let rules = vlog_linter::select_rules(select, ignore, workspace)
.map_err(|e| format!("{}: {e}", path.display()))?;
jobs.push(Job { path, config, rules });
let options = rule_options(&file_config)?;
jobs.push(Job { path, config, rules, options });
}
let wanted = jobs.iter().any(|job| job.rules.iter().any(|rule| rule.needs_workspace()));
let census = (workspace && wanted).then(|| Census::of(&jobs));
let interfaces = jobs.iter().any(|job| job.rules.iter().any(|rule| reads_interfaces(*rule)));
let census = (workspace && wanted).then(|| Census::of(&jobs, workspace && interfaces));
Ok(Plan { jobs, census })
}
/// The `[lint.<rule>]` entries of one file's config, resolved against the
/// registry.
///
/// The names and the values are checked **here**, where the registry is, and
/// the first bad entry fails the run naming the config file and the line it
/// was written on — the same treatment a bad `[lint] select` name gets, and
/// for the same reason: a user typed it and is watching.
pub fn rule_options(file_config: &FileConfig) -> Result<RuleOptions, String> {
let mut options = RuleOptions::new();
for entry in &file_config.lint_options {
options.set_raw(&entry.rule, &entry.key, &entry.raw).map_err(|e| {
let file = file_config
.source
.as_ref()
.map_or_else(|| "lucisv.toml".to_string(), |path| path.display().to_string());
// The rule is named as well as the option: the table header two
// lines up says which rule it is, and an error a user reads out
// of a CI log has no table header beside it.
format!("{file}:{}: rule `{}` {e}", entry.line, entry.rule)
})?;
}
Ok(options)
}
/// Whether this rule reads the census's **interface** half, which costs a
/// parse of every file in the run rather than a lex.
///
/// By name, because the alternative is a fourth boolean on the `Rule` trait
/// for two rules: `Rule::needs_workspace` already says "this rule asks the
/// project something", and which *question* it asks is between the rule and
/// the oracle. A name that is not in the registry cannot reach here — the
/// rules are `&'static dyn Rule` values from that registry — and a rule added
/// to the pair without being added here answers `None` and goes quiet, which
/// is the safe direction.
fn reads_interfaces(rule: &'static dyn Rule) -> bool {
matches!(rule.name(), "unknown-port" | "unknown-parameter")
}
/// The command line's list when it said anything, else the config file's.
fn pick<'a>(cli: &'a [String], config: Option<&'a [String]>) -> &'a [String] {
if cli.is_empty() {
@@ -154,7 +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
@@ -170,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}"));
@@ -187,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();
@@ -204,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)
}
});
@@ -217,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}"));
}
}
@@ -238,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
@@ -252,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,
@@ -300,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);
@@ -314,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)
@@ -348,15 +452,23 @@ fn finish(opts: &Options, reports: Vec<Report>) -> ExitCode {
}
}
/// Verible's diagnostic line: `FILE:LINE:COL: message [rule-name]`.
/// Verible's diagnostic line with the severity word in front of the message:
/// `FILE:LINE:COL: error|warning|style: message [rule-name]`.
///
/// The word sits where a compiler puts it, so the line greps and reads the way
/// every other tool's does, and `grep ': error:'` is the whole of "show me
/// what would not compile".
fn print_text(reports: &[Report]) {
let mut out = String::new();
for report in reports {
for violation in &report.violations {
let (line, col) = position(report, violation);
out.push_str(&format!(
"{}:{line}:{col}: {} [{}]\n",
report.path, violation.message, violation.rule
"{}:{line}:{col}: {}: {} [{}]\n",
report.path,
violation.severity.as_str(),
violation.message,
violation.rule
));
}
}
@@ -372,12 +484,13 @@ fn print_json(reports: &[Report]) {
let (line, col) = position(report, violation);
let (end_line, end_col) = end_position(report, violation);
items.push(format!(
"{{\"filename\":{},\"rule\":{},\"message\":{},\
"{{\"filename\":{},\"rule\":{},\"severity\":{},\"message\":{},\
\"location\":{{\"line\":{line},\"column\":{col}}},\
\"end_location\":{{\"line\":{end_line},\"column\":{end_col}}},\
\"range\":{{\"start\":{},\"end\":{}}},\"fix\":{}}}",
quote(&report.path),
quote(violation.rule),
quote(violation.severity.as_str()),
quote(&violation.message),
violation.span.start,
violation.span.end,
+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) {
+100 -8
View File
@@ -753,7 +753,9 @@ fn check_reports_violations_and_exits_1() {
let out = run(&["check", &path]);
assert_eq!(code(&out), 1, "violations must exit 1: {}", stderr(&out));
let text = stdout(&out);
assert!(text.contains(&format!("{path}:2:1: tab character")), "{text}");
// `FILE:LINE:COL: severity: message [rule]` — the severity word is part
// of the line since §33.0, and both of these are style findings.
assert!(text.contains(&format!("{path}:2:1: style: tab character")), "{text}");
assert!(text.contains("[no-tabs]"), "{text}");
assert!(text.contains("[module-filename]"), "{text}");
assert!(stderr(&out).contains("found 2 violations"), "{}", stderr(&out));
@@ -797,6 +799,7 @@ fn check_json_is_one_array_with_positions_and_fixes() {
assert!(text.starts_with('['), "{text}");
assert!(text.trim_end().ends_with(']'), "{text}");
assert_eq!(text.matches("\"rule\":\"no-tabs\"").count(), 1, "{text}");
assert!(text.contains("\"severity\":\"style\""), "{text}");
assert!(text.contains("\"location\":{\"line\":2,\"column\":1}"), "{text}");
assert!(text.contains("\"applicability\":\"safe\""), "{text}");
assert!(text.contains("\"content\":\" \""), "{text}");
@@ -895,6 +898,30 @@ fn check_select_and_ignore_pick_the_rule_set() {
assert!(stderr(&out).contains("unknown rule"), "{}", stderr(&out));
}
/// A severity word stands for its whole class wherever a rule name fits —
/// §33.0's headline for the command line.
#[test]
fn check_select_and_ignore_accept_a_severity_word() {
let dir = TempDir::new("check-severity");
// `reg` is an error-class finding, the tab and the name are style ones.
let path = dir.write("bar.sv", "module foo;\n\treg a;\nendmodule\n");
let out = run(&["check", "--select", "error", &path]);
assert_eq!(code(&out), 1, "{}", stdout(&out));
let text = stdout(&out);
assert_eq!(text.lines().count(), 1, "{text}");
assert!(text.contains(": error: "), "{text}");
assert!(text.contains("[wire-reg-mixup]"), "{text}");
let out = run(&["check", "--ignore", "style", &path]);
assert_eq!(stdout(&out).lines().count(), 1, "{}", stdout(&out));
assert!(stdout(&out).contains("[wire-reg-mixup]"), "{}", stdout(&out));
// Ignoring every class leaves nothing to report.
let out = run(&["check", "--ignore", "error,warning,style", &path]);
assert_eq!(code(&out), 0, "{}", stdout(&out));
}
#[test]
fn check_honors_inline_waivers_and_reports_dead_ones() {
let dir = TempDir::new("check-waive");
@@ -1836,16 +1863,81 @@ fn an_unknown_rule_in_the_lint_table_is_an_error() {
assert_eq!(code(&out), 2);
}
/// Per-rule tables are named rather than silently ignored, so a user who
/// writes one finds out it does nothing yet.
/// A `[lint.<rule>]` table configures that rule, and the verdict changes
/// with it — §34.0's headline claim, end to end through the real binary.
#[test]
fn a_per_rule_lint_table_is_refused_by_name() {
fn a_per_rule_lint_table_changes_the_verdict() {
let dir = TempDir::new("lint-per-rule");
dir.write("dut.sv", DUT);
dir.write("lucisv.toml", "[lint.unused-signal]\nignore = \"tmp_*\"\n");
let wide = format!("module m;\n wire {};\nendmodule\n", "a".repeat(110));
dir.write("m.sv", &wide);
let out = run(&["check", &dir.root()]);
assert!(stderr(&out).contains("per-rule lint settings"), "{}", stderr(&out));
assert_eq!(code(&out), 2);
assert!(stdout(&out).contains("line-length"), "over the default 100: {}", stdout(&out));
dir.write("lucisv.toml", "[lint.line-length]\nlength = 130\n");
let out = run(&["check", &dir.root()]);
assert_eq!(stdout(&out), "", "the option raised the limit");
assert_eq!(code(&out), 0);
}
/// A bad entry fails the run naming the config file and the line, which is
/// what tells a user *where* to fix it.
#[test]
fn a_bad_rule_option_fails_the_run_naming_file_and_line() {
let dir = TempDir::new("lint-bad-option");
dir.write("m.sv", "module m;\nendmodule\n");
for (config, wanted) in [
("[lint.line-length]\nlength = 10\n", "must be between"),
("[lint.line-length]\nlen = 120\n", "has no option `len`"),
("[lint.no-such-rule]\nx = 1\n", "unknown rule `no-such-rule`"),
("[lint.no-tabs]\nwidth = 4\n", "takes no options"),
("[lint.signal-name-style]\nstyle_regex = \"[a-\"\n", "not a valid pattern"),
// An escape from another dialect must be refused rather than read
// as a literal, which would silently judge the wrong names (QA,
// 2026-09-04).
("[lint.signal-name-style]\nstyle_regex = \"\\bword\\b\"\n", "unsupported escape `\\b`"),
("[lint.macro-name-style]\nstyle_regex = \"(A)\\1\"\n", "unsupported escape `\\1`"),
] {
dir.write("lucisv.toml", config);
let out = run(&["check", &dir.root()]);
let text = stderr(&out);
assert!(text.contains(wanted), "{config:?}: {text}");
assert!(text.contains("lucisv.toml:2:"), "file and line: {text}");
assert_eq!(code(&out), 2, "{config:?}");
}
// Every one of them names the rule as well as the option, so an error
// read out of a CI log stands on its own.
dir.write("lucisv.toml", "[lint.line-length]\nlength = 10\n");
let text = stderr(&run(&["check", &dir.root()]));
assert!(text.contains("rule `line-length`"), "{text}");
assert!(text.contains("`length` must be between"), "{text}");
}
/// The width `line-length` holds a file to is the width the formatter is
/// configured with, so the two halves of lucisv cannot disagree.
#[test]
fn line_length_follows_the_formatters_width() {
let dir = TempDir::new("lint-width");
let wide = format!("module m;\n wire {};\nendmodule\n", "a".repeat(90));
dir.write("m.sv", &wide);
assert_eq!(stdout(&run(&["check", &dir.root()])), "", "under the default 100");
let narrow = run(&["check", &dir.root(), "--line-length", "80"]);
assert!(stdout(&narrow).contains("line-length"), "{}", stdout(&narrow));
dir.write("lucisv.toml", "line-length = 80\n");
let from_config = run(&["check", &dir.root()]);
assert!(stdout(&from_config).contains("line-length"), "{}", stdout(&from_config));
}
/// A stdin buffer reads the same `[lint.<rule>]` tables a file does.
#[test]
fn a_stdin_buffer_reads_the_rule_options_too() {
let dir = TempDir::new("lint-stdin-options");
dir.write("lucisv.toml", "[lint.macro-name-style]\nstyle_regex = \"[a-z_0-9]+\"\n");
let name = format!("{}/m.sv", dir.root());
let out = run_with_stdin(&["check", "-", "--stdin-filename", &name], "`define lower_ok 1\n");
assert_eq!(stdout(&out), "", "the config's pattern accepts it: {}", stdout(&out));
let plain = run_with_stdin(&["check", "-"], "`define lower_ok 1\n");
assert!(stdout(&plain).contains("macro-name-style"), "{}", stdout(&plain));
}
/// The QA finding of 2026-09-02, pinned end to end: a testbench that reads an
+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;
+41 -31
View File
@@ -528,39 +528,49 @@ mod tests {
}
}
/// QA finding (performance wave Lane B, 2026-08-28), not a regression this
/// QA finding (performance wave Lane B, 2026-08-28), not a regression that
/// round introduced: a module with an attribute instance (`(* ... *)`)
/// anywhere near its header — right after its name, or on one of its
/// ports — is not indexed as a `Module` unit **at all**.
/// `WorkspaceIndex::units` comes back empty, so [`module_header`] declines
/// at the very first line (no `[def]` to anchor on) before the whitelist
/// walk ever runs, and completion's module tier — which sources its
/// candidate names from the same table — never offers the module in the
/// first place. This is a `vlog_semantic`/`vlog_parser` parsing gap, not a
/// completion-core one: it is filed in `docs/features/completion-core/
/// README.md`'s QA log rather than fixed here, because `vlog_semantic` is
/// outside this round's touched files. The two "attribute" shapes this QA
/// round added to [`SHAPES`] (`attributed`, `port_attributed`) still pass
/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] — but only
/// because both sides of that comparison fall back to the same whole-file
/// parse, which this test makes explicit rather than leaving it as an
/// unremarked side effect of the pin.
/// **between its name and its `#(`** is not indexed as a `Module` unit at
/// all. `WorkspaceIndex::units` comes back empty, so [`module_header`]
/// declines at the very first line (no `[def]` to anchor on) before the
/// whitelist walk ever runs, and completion's module tier — which sources
/// its candidate names from the same table — never offers the module in
/// the first place. That attribute sits inside no list, so no recovery
/// reaches it; it is still filed in `docs/features/completion-core/
/// README.md`'s QA log.
///
/// **The `port_attributed` half of the finding was fixed by header
/// recovery** (TODO §32, `docs/features/header-recovery/README.md`): an
/// attribute on a *port* now costs that one port and nothing else — the
/// list keeps a `ListElem::Error` where `(* keep *) output logic q` was
/// written, and the module keeps its name, its other ports and its body,
/// so it is indexed and its header slices for real rather than by
/// whole-file fallback. That is the re-audit the old message asked for,
/// and it is the second half of this test;
/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] covers the
/// same shape from the other side.
#[test]
fn a_module_with_an_attribute_near_its_header_is_not_indexed_at_all() {
for module in ["attributed", "port_attributed"] {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
index.units(module).is_empty(),
"{module}: if this starts finding a unit, module_header should be re-audited \
for whether it now slices attributes correctly rather than by lucky fallback"
);
assert!(
module_header(&index, module, text).is_none(),
"{module}: no unit to anchor on"
);
}
fn an_attribute_before_the_parameter_list_still_costs_the_whole_module() {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == "attributed").expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
index.units("attributed").is_empty(),
"if this starts finding a unit, module_header should be re-audited \
for whether it now slices attributes correctly rather than by lucky fallback"
);
assert!(module_header(&index, "attributed", text).is_none(), "no unit to anchor on");
}
#[test]
fn an_attribute_on_a_port_costs_that_port_only() {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == "port_attributed").expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert_eq!(index.units("port_attributed").len(), 1, "the module survives its broken port");
let header = module_header(&index, "port_attributed", text).expect("a sliced header");
assert!(header.starts_with("module port_attributed ("), "{header:?}");
assert!(header.contains("(* keep *) output logic q"), "the port list is kept whole");
}
/// The guard is not decoration: a non-ANSI module really does plan
@@ -513,6 +513,20 @@ endmodule
);
}
/// The premise the probe above rests on, stated as a test: the probe is
/// *discriminating*. Header recovery (TODO §32) widened what a tolerant
/// parse can read, so the question "did this insertion parse?" is only
/// worth asking while text that does **not** parse still says so.
#[test]
fn the_insertion_probe_still_reports_text_that_does_not_parse() {
let broken = "if (cond begin\n\n end";
let probe = format!("module p;\n always_comb begin\n {broken}\n end\nendmodule\n");
assert!(
!vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
"recovery must not make a broken insertion look clean: {probe}"
);
}
#[test]
fn a_templates_documentation_shows_what_it_expands_to() {
let top = "module top;\n alw\nendmodule\n";
@@ -896,6 +910,30 @@ endmodule
drop(tree);
}
/// Header recovery (TODO §32) pinned where completion meets it: with a
/// half-typed parameter *above* the cursor, the module still has a scope,
/// so [`visible_symbols`] still answers from it — the parameters and ports
/// already typed are offered inside the very header being edited.
///
/// Before this round the broken header took the whole `Module` node with
/// it, the body re-parsed at file scope, and the scope chain covering this
/// offset held nothing at all.
#[test]
fn a_broken_header_still_completes_from_the_modules_scope() {
let top = "\
module top #(parameter W = , parameter DEPTH = 4) (
input logic clk_i,
output logic DE
);
logic w_local;
endmodule
";
let (_tree, ws, uri, position) = asking("brokenheader", top, "output logic DE");
let found = items(completions(&ws, &uri, position, true));
let item = find(&found, "DEPTH").expect("the parameter typed after the broken one");
assert_eq!(tier(item), TIER_SCOPE, "answered from the module's own scope");
}
/// The scope tier goes fuzzy too, with no mask table behind it — it is
/// the one tier computed per request.
#[test]
+35 -3
View File
@@ -135,11 +135,12 @@ mod tests {
#[test]
fn one_list_carries_both_sources() {
// A file that parses cleanly and violates a lint rule: the publish is
// one list, and the lint finding is in it as a warning.
// one list, and the lint finding is in it at its rule's own severity
// — `no-tabs` is a style rule, so INFORMATION (§33.0).
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
let published = all(ws.document(&uri).expect("open"));
assert_eq!(published.len(), 1);
assert_eq!(published[0].severity, Some(DiagnosticSeverity::WARNING));
assert_eq!(published[0].severity, Some(DiagnosticSeverity::INFORMATION));
assert_eq!(published[0].code, Some(lsp_types::NumberOrString::String("no-tabs".into())));
}
@@ -149,12 +150,43 @@ mod tests {
let published = all(ws.document(&uri).expect("open"));
let severities: Vec<_> = published.iter().map(|d| d.severity).collect();
assert!(severities.contains(&Some(DiagnosticSeverity::ERROR)), "{published:#?}");
assert!(severities.contains(&Some(DiagnosticSeverity::WARNING)), "{published:#?}");
assert!(severities.contains(&Some(DiagnosticSeverity::INFORMATION)), "{published:#?}");
assert!(published.iter().all(|d| d.source.as_deref() == Some("lucisv")));
// Errors first: a parse error is what the user must fix.
assert_eq!(published[0].severity, Some(DiagnosticSeverity::ERROR));
}
/// The user-visible contract of header recovery (TODO §32), pinned where
/// the user meets it: a typo in a port list costs **one** diagnostic, and
/// the module around it survives whole — its name, the ports typed before
/// and after the typo, and its body all still in the outline.
///
/// Before this round the same buffer published two errors (the header, and
/// the orphaned `endmodule`), the body re-parsed as file-scope items, and
/// the outline had no module in it at all.
#[test]
fn a_broken_port_list_publishes_one_error_and_keeps_its_module() {
let (ws, uri) = doc_of("module m (input a, , input b);\n wire ok;\nendmodule\n");
let doc = ws.document(&uri).expect("open");
let diags = diagnostics(doc);
assert_eq!(diags.len(), 1, "{diags:#?}");
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::ERROR));
assert_eq!(diags[0].range.start.line, 0, "the header's own line");
// The missing-closer pass explains a *parse* failure; there is no
// unclosed block here, so it must add nothing.
assert!(crate::pairs::missing_end_diagnostics(doc).is_empty());
let symbols = crate::symbols::document_symbols(doc);
assert_eq!(symbols.len(), 1, "the module is still in the outline");
assert_eq!(symbols[0].name, "m");
let children = symbols[0].children.as_ref().expect("module contents");
let names: Vec<&str> = children.iter().map(|c| c.name.as_str()).collect();
assert!(names.contains(&"a"), "the port before the typo: {names:?}");
assert!(names.contains(&"b"), "the port after it: {names:?}");
assert!(names.contains(&"ok"), "the body: {names:?}");
}
#[test]
fn a_lex_error_gets_a_visible_range() {
// The lexer gives up at end of file, which a trailing newline makes
+34 -4
View File
@@ -22,7 +22,7 @@
use std::collections::HashMap;
use lsp_types::{InlayHint, InlayHintKind, InlayHintLabel, Range, Uri};
use vlog_parser::ast::{Connections, Expr, Instance, Instantiation};
use vlog_parser::ast::{Connection, Connections, Expr, Instance, Instantiation, ListElem};
use vlog_parser::TextRange;
use vlog_refactor::InstantiationPlan;
use vlog_semantic::instantiations;
@@ -84,6 +84,13 @@ enum Kind {
/// name is written somewhere in the same list.
fn param_sites(inst: &Instantiation) -> Vec<Site> {
let Some(params) = &inst.params else { return Vec::new() };
// A list a tolerant parse recovered inside gets no hints either: which
// parameter a position names is exactly what the skipped text decides, so
// any hint here would be a guess, and a wrong hint is worse than none.
if params.iter().any(ListElem::is_error) {
return Vec::new();
}
let params: Vec<&Connection> = params.iter().filter_map(ListElem::ok).collect();
if params.iter().any(|param| !param.name.is_empty()) {
return Vec::new();
}
@@ -99,7 +106,16 @@ fn param_sites(inst: &Instantiation) -> Vec<Site> {
/// instance: the connections are the module's ports either way.
fn port_sites(instance: &Instance) -> Vec<Site> {
let Connections::Ordered(conns) = &instance.conns else { return Vec::new() };
conns.iter().enumerate().filter_map(|(index, conn)| site(index, conn.expr.as_ref())).collect()
// As in `param_sites`: a recovered list's positions are a guess.
if conns.iter().any(ListElem::is_error) {
return Vec::new();
}
conns
.iter()
.filter_map(ListElem::ok)
.enumerate()
.filter_map(|(index, conn)| site(index, conn.expr.as_ref()))
.collect()
}
/// A site at the start of `expr`, or nothing for an omitted position
@@ -542,10 +558,23 @@ endmodule
assert_eq!(hints[1], (2, 10, "clk:".to_string()), "the line before it had é and 🎉");
}
/// A buffer mid-edit still hints where the *positions* are known, and
/// stops where they are not.
///
/// Header recovery (TODO §32) changed the first half: `sub u1 (clk, rst_n`
/// used to fail to parse at all, so there was nothing to hint from. Now
/// the instantiation survives with both positional connections, and both
/// are at the index they were written at, so both are hinted. The second
/// half is the rule that replaces "does not parse": a list the parser
/// *recovered* inside holds text nobody can index, so `port_sites` and
/// `param_sites` decline the whole list rather than mislabel what follows
/// the hole.
#[test]
fn a_buffer_that_does_not_parse_hints_nothing_rather_than_guessing() {
fn a_truncated_list_hints_and_a_recovered_one_does_not() {
let top = "module top;\n sub u1 (clk, rst_n\n";
assert!(hints_of("broken", top).is_empty());
assert_eq!(labels(&hints_of("truncated", top)), ["clk:", "rst_n:"]);
let holed = "module top;\n sub u1 (clk, .\n wire w;\nendmodule\n";
assert!(hints_of("recovered", holed).is_empty());
}
#[test]
@@ -563,6 +592,7 @@ endmodule
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let insts = instantiations::sites(&tree.items);
let params = insts[0].inst.params.as_ref().expect("a `#( ... )`");
let params: Vec<_> = params.iter().filter_map(ListElem::ok).collect();
assert_eq!(params[0].name, "", "`8` names nothing");
assert_eq!(params[1].name, "DEPTH", "`.DEPTH(16)` does");
}
+40 -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]
@@ -1894,6 +1916,20 @@ sub #(
}
}
/// The premise the "the accepted text must parse" probe above rests on:
/// the probe can still fail. Header recovery (TODO §32) widened what a
/// tolerant parse reads — a half-typed connection list is now a recovered
/// instantiation rather than a dead item — so the probe is only worth
/// asking while text that does not parse still says so.
#[test]
fn the_accepted_text_probe_still_reports_text_that_does_not_parse() {
let probe = "module lucisv_probe;\n logic clk;\n sub u_sub (.clk(\nendmodule\n";
assert!(
!vlog_parser::parse_source_tolerant(probe).1.is_empty(),
"recovery must not make a broken instantiation look clean"
);
}
#[test]
fn a_module_with_no_ports_ghosts_a_sane_instantiation() {
let top = "module top;\n bare \nendmodule\n";
+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) => {
+307 -17
View File
@@ -11,15 +11,19 @@
//! `docs/features/semantic-lints-on/README.md` and
//! `docs/features/server-lint/README.md`.
use std::collections::BTreeSet;
use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString};
use vlog_formatter::fence::{self, Region};
use vlog_linter::{
default_rules, lint, workspace_rules, LintContext, MentionOracle, Rule, Violation,
default_rules, lint, workspace_rules, LintContext, MentionOracle, ModuleInterface, Rule,
RuleOptions, Severity, Violation,
};
use vlog_semantic::{FileId, WorkspaceIndex};
use vlog_semantic::{FileId, SymbolKind, WorkspaceIndex};
use crate::convert::Positions;
use crate::diagnostics::SOURCE;
use crate::settings::ClientSettings;
use crate::state::{Document, Workspace};
/// What one lint pass runs: which rules, and what it may ask about the files
@@ -31,14 +35,29 @@ use crate::state::{Document, Workspace};
pub struct LintRun<'a> {
rules: Vec<&'static dyn Rule>,
oracle: Option<IndexMentions<'a>>,
/// What the buffer's `lucisv.toml` and the editor's settings configured
/// about each rule, merged. Empty means every rule reads its own default.
options: RuleOptions,
/// The width `line-length` holds this buffer to — the width the formatter
/// would wrap it to, so the two halves of lucisv cannot disagree.
line_length: usize,
}
impl Default for LintRun<'_> {
fn default() -> LintRun<'static> {
LintRun { rules: default_rules(), oracle: None }
LintRun {
rules: default_rules(),
oracle: None,
options: RuleOptions::new(),
line_length: DEFAULT_LINE_LENGTH,
}
}
}
/// The width a buffer is held to when neither its `lucisv.toml` nor the
/// editor says otherwise — `vlog_formatter::Config`'s own default.
const DEFAULT_LINE_LENGTH: usize = 100;
impl<'a> LintRun<'a> {
/// The pass this workspace's settings and index describe for one buffer.
///
@@ -52,19 +71,15 @@ impl<'a> LintRun<'a> {
let index = ws.index();
let own = doc.path.as_deref().and_then(|path| index.file_id(path));
let workspace = index.files().len() > usize::from(own.is_some());
let client = ws.client_settings();
// Every name in the settings was checked against the registry when the
// settings were parsed, so this cannot fail; if it somehow does, the
// defaults are the answer a dropped setting always gets here.
let rules = vlog_linter::select_rules(&client.lint_select, &client.lint_ignore, workspace)
.unwrap_or_else(|_| if workspace { workspace_rules() } else { default_rules() });
let rules = enabled_rules(ws.client_settings(), workspace);
let oracle = workspace.then_some(IndexMentions { index, own });
LintRun { rules, oracle }
let (options, line_length) = configured(ws.client_settings(), doc);
LintRun { rules, oracle, options, line_length }
}
/// This run's context over a buffer's own parse products.
fn context<'d>(&'d self, doc: &'d Document) -> LintContext<'d> {
let ctx = context(doc);
let ctx = context(doc).with_options(&self.options).with_line_length(self.line_length);
match &self.oracle {
Some(oracle) => ctx.with_oracle(oracle),
None => ctx,
@@ -72,6 +87,104 @@ impl<'a> LintRun<'a> {
}
}
/// The per-rule options and the line width governing one buffer.
///
/// **Precedence for an option, highest first: the editor, then the buffer's
/// `lucisv.toml`, then the rule's own default — key by key**, so a project
/// that sets two options and a user who overrides one keep the other. This is
/// deliberately the *opposite* order to `format::settings_for`, where a
/// checked-in `lucisv.toml` outranks the editor: formatting has a byte-exact
/// contract with CI that a user's editor must not break, while a lint option
/// changes which findings that user is shown in their own editor and is
/// theirs to set. §34.0(d).
///
/// The **width** follows the formatting ladder instead, because it is not a
/// lint setting at all: it is the width the formatter would wrap this buffer
/// to, read the same way `format::settings_for` reads it, so a line lucisv
/// wrote is never a line lucisv calls too long. `line-length`'s own `length`
/// option still beats it — that is the rule's own business, and the rule
/// applies it.
///
/// The config file is read here, per pass, exactly as `format::discover`
/// reads it per formatting request: a `lucisv.toml` edited while the server
/// runs takes effect at the next publish, and the read is a few stats beside
/// a parse and an analysis the same pass already paid for.
fn configured(client: &ClientSettings, doc: &Document) -> (RuleOptions, usize) {
let file = doc
.path
.as_deref()
.and_then(|path| lucisv_core::config::Discovery::new(true).for_file(path).ok())
.unwrap_or_default();
let mut options = RuleOptions::new();
for entry in &file.lint_options {
// A broken entry in the file is dropped here rather than reported:
// `format::settings_for` already surfaces a `lucisv.toml` problem to
// the user, and `lucisv check` fails the run over it with file and
// line, which is where a config error belongs.
let _ = options.set_raw(&entry.rule, &entry.key, &entry.raw);
}
options.overlay(&client.lint_options);
let width = file.line_length.or(client.line_length).unwrap_or(DEFAULT_LINE_LENGTH);
(options, width)
}
/// Which rules a buffer is linted with, given what the editor's settings say.
///
/// **The one ladder**, top rung last — every rung may undo the one above it:
///
/// 1. the base set is what the rules themselves declare: `default_on`, plus
/// the `needs_workspace` rules when `has_oracle`;
/// 2. a non-empty `lucisv.lint.select` **replaces** that base set, exactly as
/// `--select` replaces it on the command line;
/// 3. a `lucisv.lint.severity.<class>` switched off **removes** every rule of
/// that class;
/// 4. a `lucisv.lint.rules.<name>` set to `on` or `off` sets or clears that
/// one rule — the per-rule word beats the class word, which is what makes
/// "all style off except `no-tabs`" expressible;
/// 5. `lucisv.lint.ignore` **removes** — the off switch of last resort, the
/// one a user reaches for when nothing else worked.
///
/// Rungs 2 and 5 accept a severity word wherever a rule name fits.
pub fn enabled_rules(settings: &ClientSettings, has_oracle: bool) -> Vec<&'static dyn Rule> {
let base = if settings.lint_select.is_empty() {
if has_oracle {
workspace_rules()
} else {
default_rules()
}
} else {
named(&settings.lint_select)
};
let mut on: BTreeSet<&'static str> = base.iter().map(|rule| rule.name()).collect();
for (severity, class_on) in &settings.lint_severity {
if !class_on {
on.retain(|name| {
vlog_linter::rule_by_name(name).is_some_and(|rule| rule.severity() != *severity)
});
}
}
for (name, wanted) in &settings.lint_rules {
let Some(rule) = vlog_linter::rule_by_name(name) else { continue };
if *wanted {
on.insert(rule.name());
} else {
on.remove(rule.name());
}
}
for rule in named(&settings.lint_ignore) {
on.remove(rule.name());
}
vlog_linter::all_rules().into_iter().filter(|rule| on.contains(rule.name())).collect()
}
/// Every rule a list of `--select`-style words names, unknown words skipped —
/// they were already dropped when the settings were parsed, and a name that
/// survived that filter always resolves.
fn named(words: &[String]) -> Vec<&'static dyn Rule> {
words.iter().filter_map(|word| vlog_linter::rules_named(word)).flatten().collect()
}
/// The workspace index, asked the one question a lint rule may ask about other
/// files.
///
@@ -97,6 +210,32 @@ impl MentionOracle for IndexMentions<'_> {
fn mentioned_elsewhere(&self, name: &str) -> bool {
self.index.mentioned_outside(name, self.own)
}
/// The ports and overridable parameters of an indexed module or interface,
/// read off the index's member table — the very table a `.port` completion
/// list is offered from, so a connection lucisv would have completed is
/// never one it then calls unknown.
///
/// `None` for a unit the index does not hold, and for one it holds **more
/// than once**: two modules of a name are two different headers, and
/// answering with either would make an Error-class rule guess. A
/// `localparam` is left out, because it is not overridable.
fn module_interface(&self, name: &str) -> Option<ModuleInterface> {
let units = self.index.units(name);
let [unit] = units else { return None };
if !unit.kind.is_instantiable() {
return None;
}
let mut interface = ModuleInterface::default();
for (member, defs) in self.index.members_of(name) {
match defs.first().map(|def| def.kind) {
Some(SymbolKind::Port) => interface.ports.push(member.to_string()),
Some(SymbolKind::Param) => interface.parameters.push(member.to_string()),
_ => {}
}
}
Some(interface)
}
}
/// The document's own parse products, lent to the linter — "one parse, two
@@ -175,14 +314,13 @@ pub fn diagnostics_in(doc: &Document, run: &LintRun) -> Vec<Diagnostic> {
/// The diagnostic a violation becomes.
///
/// **Warning**, never Error: a lint finding is an opinion about style, and a
/// parse error is the compiler refusing. The `code` is the rule's stable name,
/// which is what a user needs to write a waiver or an `--ignore`, and what a
/// code action matches on.
/// The editor's severity is the rule's own class ([`severity_of`]). The `code`
/// is the rule's stable name, which is what a user needs to write a waiver or
/// an `--ignore`, and what a code action matches on.
pub fn diagnostic(positions: &Positions<'_>, violation: &Violation) -> Diagnostic {
Diagnostic {
range: positions.diagnostic_range(violation.span),
severity: Some(DiagnosticSeverity::WARNING),
severity: Some(severity_of(violation.severity)),
code: Some(NumberOrString::String(violation.rule.to_string())),
source: Some(SOURCE.to_string()),
message: violation.message.clone(),
@@ -190,6 +328,21 @@ pub fn diagnostic(positions: &Positions<'_>, violation: &Violation) -> Diagnosti
}
}
/// How an editor is asked to paint one class.
///
/// `error` is the red squiggle a compiler error gets — a rule only claims it
/// when the code would very likely not build, which is why the Error class is
/// held to the silence-when-unsure rule. `style` deliberately stops short of
/// `HINT`: a hint is invisible in most themes and would make the style rules
/// look broken rather than quiet.
fn severity_of(severity: Severity) -> DiagnosticSeverity {
match severity {
Severity::Error => DiagnosticSeverity::ERROR,
Severity::Warning => DiagnosticSeverity::WARNING,
Severity::Style => DiagnosticSeverity::INFORMATION,
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -211,13 +364,35 @@ mod tests {
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
let diags = diagnostics(ws.document(&uri).expect("open"));
assert_eq!(diags.len(), 1);
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::WARNING));
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::INFORMATION), "no-tabs is style");
assert_eq!(diags[0].code, Some(NumberOrString::String("no-tabs".into())));
assert_eq!(diags[0].source.as_deref(), Some("lucisv"));
assert_eq!(diags[0].range.start.line, 1);
assert!(diags[0].range.start < diags[0].range.end, "never zero-width");
}
/// Each class paints its own squiggle: a compile-error rule reads as an
/// error, a latch-shaped one as a warning, a naming one as information.
#[test]
fn a_diagnostics_severity_is_its_rules_class() {
assert_eq!(severity_of(Severity::Error), DiagnosticSeverity::ERROR);
assert_eq!(severity_of(Severity::Warning), DiagnosticSeverity::WARNING);
assert_eq!(severity_of(Severity::Style), DiagnosticSeverity::INFORMATION);
// `reg` is error-class, the tab is style-class, and the two arrive in
// one publish wearing different colours.
let (ws, uri) = doc_of("module m;\n\treg a;\nendmodule\n");
let diags = diagnostics(ws.document(&uri).expect("open"));
let by_code = |name: &str| {
diags
.iter()
.find(|d| d.code == Some(NumberOrString::String(name.into())))
.and_then(|d| d.severity)
};
assert_eq!(by_code("wire-reg-mixup"), Some(DiagnosticSeverity::ERROR), "{diags:#?}");
assert_eq!(by_code("no-tabs"), Some(DiagnosticSeverity::INFORMATION), "{diags:#?}");
}
#[test]
fn a_waived_violation_is_never_published() {
let (ws, uri) = doc_of("module m;\n\twire a; // lucisv: waive no-tabs\nendmodule\n");
@@ -368,6 +543,121 @@ mod tests {
let _ = std::fs::remove_dir_all(dir);
}
/// The ladder of §33.1, one row per rung, asserted against the rule set
/// `enabled_rules` produces. Each row is (what the settings say, what must
/// be true of the result).
#[test]
fn the_enabled_rules_ladder_is_the_documented_one() {
let names = |settings: &ClientSettings, oracle: bool| -> Vec<&'static str> {
enabled_rules(settings, oracle).into_iter().map(|rule| rule.name()).collect()
};
let with = |f: &dyn Fn(&mut ClientSettings)| {
let mut settings = ClientSettings::default();
f(&mut settings);
settings
};
// 1. the base set is the rules' own defaults, and a workspace adds
// exactly the rules that asked for one.
let base = ClientSettings::default();
assert_eq!(
names(&base, false),
default_rules().iter().map(|r| r.name()).collect::<Vec<_>>()
);
assert_eq!(
names(&base, true),
workspace_rules().iter().map(|r| r.name()).collect::<Vec<_>>()
);
// 2. a non-empty `select` replaces the base set — including rules that
// ship off, exactly as `--select` does.
let selected = with(&|s| s.lint_select = vec!["module-name-style".to_string()]);
assert_eq!(names(&selected, false), vec!["module-name-style"]);
// ... and a severity word may stand there.
let styled = with(&|s| s.lint_select = vec!["style".to_string()]);
assert!(names(&styled, true)
.iter()
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
== Severity::Style));
// 3. a class switched off removes every rule of that class.
let no_style = with(&|s| {
s.lint_severity.insert(Severity::Style, false);
});
assert!(!names(&no_style, true).contains(&"no-tabs"));
assert!(names(&no_style, true).contains(&"unused-signal"), "other classes stay");
// 4. a per-rule toggle beats the class switch, in both directions.
let style_off_but_tabs = with(&|s| {
s.lint_severity.insert(Severity::Style, false);
s.lint_rules.insert("no-tabs".to_string(), true);
});
assert!(names(&style_off_but_tabs, true).contains(&"no-tabs"));
let one_off = with(&|s| {
s.lint_rules.insert("no-tabs".to_string(), false);
});
assert!(!names(&one_off, true).contains(&"no-tabs"));
// A toggle also adds a rule `select` did not name, and one that ships
// off entirely.
let added = with(&|s| {
s.lint_select = vec!["no-tabs".to_string()];
s.lint_rules.insert("module-name-style".to_string(), true);
});
assert_eq!(names(&added, false), vec!["module-name-style", "no-tabs"]);
// 5. `ignore` is the last word, over a toggle that says `on`.
let ignored = with(&|s| {
s.lint_rules.insert("no-tabs".to_string(), true);
s.lint_ignore = vec!["no-tabs".to_string()];
});
assert!(!names(&ignored, true).contains(&"no-tabs"));
// ... and it takes a severity word too.
let quiet = with(&|s| s.lint_ignore = vec!["style".to_string()]);
assert!(names(&quiet, true)
.iter()
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
!= Severity::Style));
// The result is always in registry order, whatever order the settings
// named things in — two runs must print findings the same way.
let jumbled = with(&|s| {
s.lint_select = vec!["no-trailing-whitespace".to_string(), "no-tabs".to_string()];
});
assert_eq!(names(&jumbled, false), vec!["no-tabs", "no-trailing-whitespace"]);
}
/// The toggles reach the real published diagnostics, not just the rule
/// list: a class switched off silences its squiggles.
#[test]
fn a_class_switch_changes_what_the_server_publishes() {
let (mut ws, dir, uri) = two_file_project("classes");
ws.set_document(uri.clone(), "module dut;\n\tlogic dead;\nendmodule\n".to_string());
let doc = ws.document(&uri).expect("open");
let mut both = codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc)));
both.sort();
assert_eq!(both, vec!["no-tabs", "unused-signal"], "premise");
let mut off = ClientSettings::default();
off.lint_severity.insert(Severity::Style, false);
ws.set_client_settings(off);
let doc = ws.document(&uri).expect("open");
assert_eq!(
codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc))),
vec!["unused-signal"],
"the style class went quiet"
);
let mut back = ClientSettings::default();
back.lint_severity.insert(Severity::Style, false);
back.lint_rules.insert("no-tabs".to_string(), true);
ws.set_client_settings(back);
let doc = ws.document(&uri).expect("open");
let mut with_tabs = codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc)));
with_tabs.sort();
assert_eq!(with_tabs, vec!["no-tabs", "unused-signal"], "the per-rule word wins");
let _ = std::fs::remove_dir_all(dir);
}
/// The off switch, over the settings door: `lucisv.lint.ignore` takes a
/// rule out of the published set.
#[test]
+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;
@@ -268,9 +285,13 @@ impl Server {
/// The rule selection in force, as a value two settings pushes can be
/// compared by.
fn lint_selection(&self) -> (Vec<String>, Vec<String>) {
let client = self.workspace.client_settings();
(client.lint_select.clone(), client.lint_ignore.clone())
///
/// All four lint settings, not just the two lists: since §33.1 a class
/// switch (`lucisv.lint.severity.*`) and a per-rule toggle
/// (`lucisv.lint.rules.*`) change which rules run too, and a change to one
/// of them must republish exactly as a change to `select`/`ignore` does.
fn lint_selection(&self) -> settings::LintSelection {
settings::lint_selection(self.workspace.client_settings())
}
}
+349 -3
View File
@@ -13,9 +13,11 @@
//! Not to be confused with `format::Settings`, which is what one formatting
//! request resolved to after every rung of that ladder was applied.
use std::collections::BTreeMap;
use std::ops::RangeInclusive;
use serde_json::Value;
use vlog_linter::{OptionValue, RuleOptions, Severity};
/// Accepted `line-length`, and accepted `indent`.
///
@@ -174,6 +176,32 @@ pub struct ClientSettings {
/// `lucisv.lint.ignore`: rules dropped from whatever `select` left. Same
/// validation, same reason.
pub lint_ignore: Vec<String>,
/// `lucisv.lint.severity.error` / `.warning` / `.style`: the master switch
/// of each class. Every class is present and `true` unless a client turned
/// one off — see `lint::enabled_rules` for where it sits in the ladder.
pub lint_severity: BTreeMap<Severity, bool>,
/// `lucisv.lint.rules.<rule-name>`: the rules a client said something
/// **explicit** about — `true` for `on`, `false` for `off`.
///
/// A rule left at `default` is *absent from this map*, and that is the
/// whole reason the setting is a three-word enum rather than a boolean: a
/// client sends the whole section, every key at its default, so "unset"
/// and "set to the shipped value" would arrive identically and a per-rule
/// toggle nobody touched would silently override `select` and the class
/// switches.
pub lint_rules: BTreeMap<String, bool>,
/// `lucisv.lint.options`: `{"<rule>": {"<key>": value}}`, validated
/// against the rule registry.
///
/// Refused entries are **dropped**, not fatal — this module's standing
/// rule, and the reason it matters here more than anywhere else: one
/// typo in an options object must not be able to switch the linter off
/// for a whole session. What was refused is kept in
/// [`ClientSettings::lint_option_warnings`] so the user is told.
pub lint_options: RuleOptions,
/// One line per refused `lucisv.lint.options` entry, ready for a
/// `window/logMessage`. Empty for a settings push that was all valid.
pub lint_option_warnings: Vec<String>,
}
/// The settings a client that said nothing is treated as having asked for.
@@ -200,10 +228,43 @@ impl Default for ClientSettings {
large_file_threshold: DEFAULT_LARGE_FILE_THRESHOLD,
lint_select: Vec::new(),
lint_ignore: Vec::new(),
lint_severity: every_class_on(),
lint_rules: BTreeMap::new(),
lint_options: RuleOptions::new(),
lint_option_warnings: Vec::new(),
}
}
}
/// Every severity class switched on — what a client that said nothing means.
fn every_class_on() -> BTreeMap<Severity, bool> {
Severity::ALL.into_iter().map(|severity| (severity, true)).collect()
}
/// Everything about a settings value that decides **which rules run**: the two
/// name lists, the class switches and the per-rule toggles.
///
/// Its only use is equality — the server compares it across a settings change
/// to decide whether every open file must be published again.
pub type LintSelection =
(Vec<String>, Vec<String>, BTreeMap<Severity, bool>, BTreeMap<String, bool>, RuleOptions);
/// The lint settings of `settings`, as one comparable value.
///
/// The options are in here with the four that choose rules, because a changed
/// option changes what a rule *reports* — a `line-length` of 120 unpublishes
/// every finding drawn at 100 — and every open file must be published again
/// for exactly the same reason a changed selection does.
pub fn lint_selection(settings: &ClientSettings) -> LintSelection {
(
settings.lint_select.clone(),
settings.lint_ignore.clone(),
settings.lint_severity.clone(),
settings.lint_rules.clone(),
settings.lint_options.clone(),
)
}
/// Read the `lucisv` section out of a `workspace/didChangeConfiguration` payload.
///
/// **Nothing here trusts the client.** `package.json`'s JSON schema constrains
@@ -231,6 +292,7 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
let large_file = lucisv.get("largeFile");
// And `lucisv.lint.select` / `lucisv.lint.ignore` the same way again.
let lint = lucisv.get("lint");
let (options, warnings) = rule_options(lint.and_then(|l| l.get("options")));
ClientSettings {
line_length: bounded(lucisv.get("lineLength"), LINE_LENGTH_RANGE),
indent: bounded(lucisv.get("indent"), INDENT_RANGE),
@@ -274,17 +336,112 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
.unwrap_or(DEFAULT_LARGE_FILE_THRESHOLD),
lint_select: rules(lint.and_then(|l| l.get("select"))),
lint_ignore: rules(lint.and_then(|l| l.get("ignore"))),
// `lucisv.lint.severity.<class>` and `lucisv.lint.rules.<name>` nest
// one level deeper again, for the same reason `index.*` does.
lint_severity: severity_switches(lint.and_then(|l| l.get("severity"))),
lint_rules: rule_toggles(lint.and_then(|l| l.get("rules"))),
lint_options: options,
lint_option_warnings: warnings,
}
}
/// The rule names in a settings array, dropping every one the registry does
/// not know.
/// The rule names in a settings array, dropping every one that names neither a
/// rule nor a severity class.
///
/// Silence rather than an error, on this module's standing rule: a push is
/// JSON on a socket, and a typo in one name must not cost the user every
/// diagnostic in the file. A dropped name leaves the rule where it was.
fn rules(value: Option<&Value>) -> Vec<String> {
strings(value).into_iter().filter(|name| vlog_linter::rule_by_name(name).is_some()).collect()
strings(value).into_iter().filter(|name| vlog_linter::rules_named(name).is_some()).collect()
}
/// The three class master switches, each `true` unless a client turned it off.
///
/// A missing or wrong-typed switch leaves its class on: the safe direction for
/// a switch that silences a whole family of diagnostics is the one that shows
/// them, exactly as an unreadable size cap leaves the cap on.
fn severity_switches(value: Option<&Value>) -> BTreeMap<Severity, bool> {
Severity::ALL
.into_iter()
.map(|severity| {
let on = flag(value.and_then(|v| v.get(severity.as_str()))).unwrap_or(true);
(severity, on)
})
.collect()
}
/// The rules a client said something explicit about: `on` and `off` only.
///
/// `default` — and any word that is neither, and any key that is not a rule —
/// contributes nothing, which is what leaves the rule wherever the rest of the
/// ladder put it. See [`ClientSettings::lint_rules`].
fn rule_toggles(value: Option<&Value>) -> BTreeMap<String, bool> {
let Some(Value::Object(map)) = value else { return BTreeMap::new() };
map.iter()
.filter(|(name, _)| vlog_linter::rule_by_name(name).is_some())
.filter_map(|(name, choice)| match choice.as_str() {
Some("on") => Some((name.clone(), true)),
Some("off") => Some((name.clone(), false)),
_ => None,
})
.collect()
}
/// The `lucisv.lint.options` object, validated against the rule registry.
///
/// The shape is `{"<rule>": {"<key>": value}}` — the nesting VS Code's
/// settings model produces for an object setting, and the one a hand-written
/// Neovim config writes. Every entry goes through the **same** validator a
/// `[lint.<rule>]` table in a `lucisv.toml` goes through
/// (`RuleOptions::set`), so an option means one thing in both front ends.
///
/// A refused entry is dropped and described, rather than failing the push:
/// the CLI can fail a run over a typo because a user typed it and is watching,
/// while a settings push arrives on a socket and failing it would leave an
/// editor with no diagnostics and no way to see why. The descriptions are
/// returned for the caller to log.
fn rule_options(value: Option<&Value>) -> (RuleOptions, Vec<String>) {
let mut options = RuleOptions::new();
let mut warnings = Vec::new();
let Some(Value::Object(rules)) = value else { return (options, warnings) };
for (rule, keys) in rules {
let Some(Value::Object(keys)) = Some(keys) else {
warnings.push(format!("lucisv.lint.options.{rule} is not an object; ignored"));
continue;
};
for (key, raw) in keys {
let Some(value) = option_value(raw) else {
warnings.push(format!(
"lucisv.lint.options.{rule}.{key}: {raw} is not a boolean, number, \
string or list of strings; ignored"
));
continue;
};
if let Err(problem) = options.set(rule, key, value) {
warnings.push(format!("lucisv.lint.options.{rule}.{key}: {problem}; ignored"));
}
}
}
(options, warnings)
}
/// One JSON value as an option value, or nothing for a shape no option takes.
///
/// Structural only — whether the *kind* is the one the option declares is
/// `RuleOptions::set`'s answer, so the error a user reads names the option
/// and its kind rather than JSON's.
fn option_value(raw: &Value) -> Option<OptionValue> {
match raw {
Value::Bool(b) => Some(OptionValue::Bool(*b)),
Value::Number(n) => n.as_i64().map(OptionValue::Int),
Value::String(s) => Some(OptionValue::Str(s.clone())),
Value::Array(items) => items
.iter()
.map(|item| item.as_str().map(str::to_string))
.collect::<Option<Vec<String>>>()
.map(OptionValue::List),
_ => None,
}
}
/// One of the two `lucisv.index.scope` words, or nothing. Matched exactly —
@@ -623,6 +780,195 @@ mod tests {
}
}
/// **The drift guard.** `editors/vscode/package.json` declares one switch
/// per severity class and one per rule, generated by
/// `vlog_linter::vscode_lint_settings`. This compares the two as JSON
/// *values*, so formatting is free but a rule added without its toggle —
/// or a summary, default or severity edited on one side only — fails here.
///
/// Regenerate with
/// `cargo run -p vlog_linter --example vscode_lint_settings`.
#[test]
fn the_vscode_lint_toggles_match_the_registry() {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../editors/vscode/package.json");
let text = std::fs::read_to_string(&path).expect("the extension manifest");
let manifest: Value = serde_json::from_str(&text).expect("valid json");
let properties = manifest["contributes"]["configuration"]["properties"]
.as_object()
.expect("a properties object");
let declared: serde_json::Map<String, Value> = properties
.iter()
.filter(|(key, _)| {
key.starts_with("lucisv.lint.severity.") || key.starts_with("lucisv.lint.rules.")
})
.map(|(key, value)| (key.clone(), value.clone()))
.collect();
let generated: Value = serde_json::from_str(&vlog_linter::vscode_lint_settings())
.expect("the generator emits valid json");
let generated = generated.as_object().expect("an object");
let names = |map: &serde_json::Map<String, Value>| {
let mut keys: Vec<String> = map.keys().cloned().collect();
keys.sort();
keys
};
assert_eq!(
names(&declared),
names(generated),
"package.json and the rule registry disagree about which lint settings exist; \
regenerate with `cargo run -p vlog_linter --example vscode_lint_settings`"
);
for (key, value) in generated {
assert_eq!(declared.get(key), Some(value), "{key} drifted");
}
// And every rule really does have one, which is the promise the whole
// generator exists to keep.
for rule in vlog_linter::all_rules() {
assert!(declared.contains_key(&vlog_linter::rule_setting(rule)), "{}", rule.name());
}
}
/// A default-everything payload — which is what a client sends for a user
/// who has touched nothing — must say nothing about any rule.
#[test]
fn the_shipped_lint_toggles_are_no_opinion() {
let mut rules = serde_json::Map::new();
for rule in vlog_linter::all_rules() {
rules.insert(rule.name().to_string(), json!("default"));
}
let found = settings(json!({"lucisv": {"lint": {
"severity": {"error": true, "warning": true, "style": true},
"rules": Value::Object(rules),
}}}));
assert_eq!(found, ClientSettings::default(), "every shipped value is silence");
}
#[test]
fn the_severity_switches_and_rule_toggles_are_read() {
let found = settings(json!({"lucisv": {"lint": {
"severity": {"style": false, "warning": "yes"},
"rules": {"no-tabs": "on", "unused-signal": "off", "empty-item": "default",
"no-such-rule": "on", "case-missing-default": 3},
}}}));
assert!(!found.lint_severity[&Severity::Style]);
assert!(found.lint_severity[&Severity::Warning], "a wrong type leaves it on");
assert!(found.lint_severity[&Severity::Error], "and so does absence");
assert_eq!(
found.lint_rules,
[("no-tabs".to_string(), true), ("unused-signal".to_string(), false)]
.into_iter()
.collect::<BTreeMap<_, _>>(),
"`default`, an unknown rule and a wrong-typed choice all say nothing"
);
// A `lint` that is not an object leaves every class on and nothing said.
let junk = settings(json!({"lucisv": {"lint": 7}}));
assert_eq!(junk.lint_severity, every_class_on());
assert!(junk.lint_rules.is_empty());
}
/// A severity word is a legal `select`/`ignore` entry since §33.0, so the
/// validating filter must keep it.
#[test]
fn a_severity_word_survives_the_select_and_ignore_filter() {
let found = settings(json!({"lucisv": {"lint": {
"select": ["style", "no-tabs", "nope"],
"ignore": ["warning"],
}}}));
assert_eq!(found.lint_select, vec!["style", "no-tabs"]);
assert_eq!(found.lint_ignore, vec!["warning"]);
}
/// What the server compares two settings pushes by, to decide whether the
/// squiggles it already drew are still right.
#[test]
fn the_lint_selection_notices_every_setting_that_changes_the_rule_set() {
let base = ClientSettings::default();
let mut severity = base.clone();
severity.lint_severity.insert(Severity::Style, false);
let mut toggled = base.clone();
toggled.lint_rules.insert("no-tabs".to_string(), false);
let mut selected = base.clone();
selected.lint_select = vec!["error".to_string()];
let mut ignored = base.clone();
ignored.lint_ignore = vec!["no-tabs".to_string()];
let mut configured = base.clone();
configured.lint_options.set_raw("line-length", "length", "120").expect("accepted");
for changed in [severity, toggled, selected, ignored, configured] {
assert_ne!(lint_selection(&base), lint_selection(&changed));
}
// A setting that does not change which rules run does not republish.
let mut unrelated = base.clone();
unrelated.indent = Some(4);
assert_eq!(lint_selection(&base), lint_selection(&unrelated));
}
/// §34.0(c): the object is read, validated against the registry, and a
/// bad entry is dropped **with a warning** rather than failing the push.
#[test]
fn the_lint_options_object_is_read_and_validated() {
let found = settings(json!({"lucisv": {"lint": {"options": {
"line-length": {"length": 120},
"generate-label-prefix": {"prefix": ["blk_"]},
"typedef-structs-unions": {"allow_anonymous_nested": true},
"signal-name-style": {"style_regex": "[a-z_0-9]+"},
}}}}));
assert_eq!(found.lint_options.int("line-length", "length"), 120);
assert_eq!(
found.lint_options.list("generate-label-prefix", "prefix"),
vec!["blk_".to_string()]
);
assert!(found.lint_options.bool("typedef-structs-unions", "allow_anonymous_nested"));
assert_eq!(found.lint_options.str("signal-name-style", "style_regex"), "[a-z_0-9]+");
assert!(found.lint_option_warnings.is_empty(), "{:?}", found.lint_option_warnings);
}
#[test]
fn a_refused_option_is_dropped_and_described_rather_than_fatal() {
let found = settings(json!({"lucisv": {"lint": {"options": {
"line-length": {"length": 10, "len": 120},
"no-such-rule": {"x": 1},
"no-tabs": {"width": 4},
"signal-name-style": {"style_regex": "[a-"},
"interface-name-style": {"style_regex": "\\bword\\b"},
"macro-name-style": {"style_regex": 4},
"package-filename": "not-an-object",
"port-name-suffix": {"suffixes": [1, 2]},
}}}}));
// Nothing was accepted, and every refusal says which entry and why.
assert!(found.lint_options.is_empty(), "{:?}", found.lint_options);
let warnings = found.lint_option_warnings.join("\n");
for wanted in [
"line-length.length",
"must be between",
"has no option `len`",
"unknown rule `no-such-rule`",
"takes no options",
"not a valid pattern",
"unsupported escape `\\b`",
"expects a pattern, found an integer",
"package-filename is not an object",
"port-name-suffix.suffixes",
] {
assert!(warnings.contains(wanted), "{wanted} missing from:\n{warnings}");
}
// ... and the rest of the settings survived the bad object.
assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE);
}
/// A settings payload with no options object is exactly today's
/// behaviour: every rule reads its own default.
#[test]
fn no_options_object_means_every_default() {
for payload in [json!({"lucisv": {}}), json!({"lucisv": {"lint": {}}})] {
let found = settings(payload);
assert!(found.lint_options.is_empty());
assert!(found.lint_option_warnings.is_empty());
assert_eq!(found.lint_options.int("line-length", "length"), 100, "the spec default");
}
}
#[test]
fn the_default_vscode_payload_is_no_opinion_about_anything() {
// Every setting at its `package.json` default: nulls and an empty
+11
View File
@@ -456,6 +456,17 @@ mod tests {
}
}
/// The premise [`every_untouched_expansion_parses`] rests on: the probe
/// can still fail. Header recovery (TODO §32) widened what a tolerant
/// parse reads, and a probe that answered "clean" for everything would
/// pass that test while proving nothing.
#[test]
fn the_expansion_probe_still_reports_text_that_does_not_parse() {
let probe = "module p;\n always_comb begin\n case (sel\n end\nendmodule\n";
let (_, diagnostics) = vlog_parser::parse_source_tolerant(probe);
assert!(!diagnostics.is_empty(), "recovery must not make a broken expansion look clean");
}
#[test]
fn every_hole_is_a_tabstop_the_snippet_grammar_reads() {
// The editor-snippets lesson, restated for generated text: VS Code
+10 -7
View File
@@ -41,7 +41,7 @@
use lsp_types::{Location, Uri};
use vlog_parser::ast::{
AnsiPort, DataType, Declarator, GenBlock, GenElse, GenIf, Instantiation, Item, ItemKind,
Module, ParamPort, PortList, Stmt, StmtKind, StructType, TfArg, TypeExtra, Typedef,
ListElem, Module, ParamPort, PortList, Stmt, StmtKind, StructType, TfArg, TypeExtra, Typedef,
TypedefKind,
};
use vlog_parser::TextRange;
@@ -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)),
@@ -250,18 +251,20 @@ fn module_site(m: &Module, offset: u32) -> Option<Site<'_>> {
.or_else(|| site_at(&m.items, offset))
}
fn ansi_port_site(ports: &[AnsiPort], offset: u32) -> Option<Site<'_>> {
let port = ports.iter().find(|p| p.span.contains(offset))?;
// The three header lists below skip their error elements: text a tolerant
// parse could not read names no type, so there is no definition to go to.
fn ansi_port_site(ports: &[ListElem<AnsiPort>], offset: u32) -> Option<Site<'_>> {
let port = ports.iter().filter_map(ListElem::ok).find(|p| p.span.contains(offset))?;
site(&port.ty.name, TextRange::new(port.span.start, port.name_span.start))
}
fn param_port_site(ports: &[ParamPort], offset: u32) -> Option<Site<'_>> {
let port = ports.iter().find(|p| p.span.contains(offset))?;
fn param_port_site(ports: &[ListElem<ParamPort>], offset: u32) -> Option<Site<'_>> {
let port = ports.iter().filter_map(ListElem::ok).find(|p| p.span.contains(offset))?;
site(&port.ty.name, TextRange::new(port.span.start, port.name_span.start))
}
fn tf_arg_site(args: &[TfArg], offset: u32) -> Option<Site<'_>> {
let arg = args.iter().find(|a| a.span.contains(offset))?;
fn tf_arg_site(args: &[ListElem<TfArg>], offset: u32) -> Option<Site<'_>> {
let arg = args.iter().filter_map(ListElem::ok).find(|a| a.span.contains(offset))?;
site(&arg.ty.name, TextRange::new(arg.span.start, arg.name_span.start))
}
+78 -1
View File
@@ -455,7 +455,9 @@ fn lint_diagnostics_and_a_code_action_round_trip_over_the_wire() {
assert!(codes.contains(&"no-tabs"), "{codes:?}");
assert!(codes.contains(&"no-trailing-whitespace"), "{codes:?}");
for diagnostic in diagnostics {
assert_eq!(diagnostic["severity"], 2, "a lint finding is a warning");
// Both rules here are style-class, which is LSP severity 3
// (INFORMATION) since §33.0.
assert_eq!(diagnostic["severity"], 3, "a style finding is information");
assert_eq!(diagnostic["source"], "lucisv");
}
@@ -7365,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
+154 -20
View File
@@ -3,7 +3,9 @@
//! A fenced region is emitted as the exact source bytes it was written with,
//! so nothing inside it is ever laid out. This module answers the two
//! questions that makes possible: which comments are fences, and which byte
//! ranges they select. Full spec: `docs/features/format-fences/README.md`.
//! ranges they select. Full spec: `docs/features/format-fences/README.md`,
//! plus `docs/features/statement-fences/README.md` for the class-body and
//! statement-list scopes.
//!
//! [`protected_regions`] and [`is_protected`] are the same answer for the
//! tools that only *edit* fenced bytes rather than lay them out — the CLI's
@@ -11,7 +13,10 @@
//! there is one definition of "what is fenced": see
//! `docs/features/shared-fence-filter/README.md`.
use vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind, SourceFile};
use vlog_parser::ast::{
Fragment, GenBlock, GenElse, GenIf, Item, ItemKind, SourceFile, Stmt, StmtKind,
};
use vlog_parser::span::TextRange;
use vlog_parser::token::Comment;
use vlog_parser::LineIndex;
@@ -54,7 +59,15 @@ pub struct Region {
/// Every fenced region in `file`, sorted and non-overlapping.
pub fn collect(src: &str, file: &SourceFile) -> Vec<Region> {
let mut found = Vec::new();
scan_scope(src, &file.items, &file.dangling, &mut found);
match &file.fragment {
// A statement fragment is one statement list standing at file scope,
// its dangling comments ending it exactly as a file's items' do. The
// other fragment shapes are element lists, which are not fenceable.
Some(Fragment::Statements(stmts)) => {
scan_stmt_scope(src, stmts, &file.dangling, &mut found)
}
_ => scan_scope(src, &file.items, &file.dangling, &mut found),
}
found.sort_by_key(|r| r.fence);
// A region inside an already-fenced range never runs: the items holding
// it are emitted as source bytes, so they are never formatted. Dropping
@@ -146,50 +159,73 @@ fn scanned_regions(src: &str) -> Vec<Region> {
regions
}
/// Scan one item-list scope, then its nested scopes.
/// Scan one flat stream of units — each unit's leading comments, then its own
/// code extent — followed by the scope's dangling comments.
///
/// The scope is a flat stream of units — each item's leading comments, then
/// the item's own code — followed by the dangling comments. A region opens at
/// the first `off` in that stream and closes at the first `on` after it;
/// anything else, including a second `off`, is just text.
fn scan_scope(src: &str, items: &[Item], dangling: &[Comment], out: &mut Vec<Region>) {
/// A region opens at the first `off` in that stream and closes at the first
/// `on` after it; anything else, including a second `off`, is just text. An
/// item list and a statement list have exactly this shape, and it is the only
/// shape a fence pairs inside, which is why both scan through here.
fn scan_units<'u>(
src: &str,
units: impl Iterator<Item = (&'u [Comment], TextRange)>,
dangling: &[Comment],
out: &mut Vec<Region>,
) {
let mut open: Option<Region> = None;
let mut scope_end = 0usize;
for item in items {
for c in &item.meta.leading {
for (leading, span) in units {
for c in leading {
// An attribute followed by a comment puts a "leading" comment
// *after* the item's span starts. Opening a region there would
// *after* the unit's span starts. Opening a region there would
// emit the attribute twice, so such comments are not fences.
if c.span.start < item.span.start {
if c.span.start < span.start {
step(src, c, &mut open, out);
}
}
// A leading comment always ends before its item's code does, so the
// item's own end is the scope's high-water mark.
scope_end = item.span.end as usize;
// A leading comment always ends before its unit's code does, so the
// unit's own end is the scope's high-water mark.
scope_end = span.end as usize;
}
for c in dangling {
step(src, c, &mut open, out);
scope_end = c.span.end as usize;
}
if let Some(mut r) = open {
// An unmatched `off` runs to the end of the scope. The last item's
// An unmatched `off` runs to the end of the scope. The last unit's
// span stops before the comment trailing it on the same line, and
// `Meta.trailing` has no span to consult, so that comment has to be
// picked up from the source or it would be dropped.
r.end = with_trailing_comments(src, scope_end);
out.push(r);
}
}
/// Scan one item-list scope, then its nested scopes.
fn scan_scope(src: &str, items: &[Item], dangling: &[Comment], out: &mut Vec<Region>) {
scan_units(src, items.iter().map(|i| (i.meta.leading.as_slice(), i.span)), dangling, out);
for item in items {
scan_nested(src, item, out);
}
}
/// Scan one statement-list scope, then its nested scopes.
///
/// The statement twin of [`scan_scope`], unit for unit — which is what keeps a
/// region aligned with statement boundaries and stops an unmatched `off` at the
/// list's end rather than at the `end`, `join` or `endfunction` past it.
fn scan_stmt_scope(src: &str, stmts: &[Stmt], dangling: &[Comment], out: &mut Vec<Region>) {
scan_units(src, stmts.iter().map(|s| (s.meta.leading.as_slice(), s.span)), dangling, out);
for stmt in stmts {
scan_nested_stmt(src, stmt, out);
}
}
/// Advance the open/closed state by one comment unit.
fn step(src: &str, c: &Comment, open: &mut Option<Region>, out: &mut Vec<Region>) {
let start = c.span.start as usize;
match (fence_of(&c.text), open.is_some()) {
(Some(Fence::Off), false) => {
(Some(Fence::Off), false) if opens_line(src, start) => {
*open = Some(Region { fence: start, start: line_start(src, start), end: 0 })
}
(Some(Fence::On), true) => {
@@ -202,13 +238,14 @@ fn step(src: &str, c: &Comment, open: &mut Option<Region>, out: &mut Vec<Region>
}
}
/// Item scopes nested inside one item. Statement bodies are not scanned:
/// statement-level fences are out of scope (see the feature README).
/// Scopes nested inside one item: the item lists, and the statement lists an
/// item's body reaches.
fn scan_nested(src: &str, item: &Item, out: &mut Vec<Region>) {
match &item.kind {
ItemKind::Module(m) => scan_scope(src, &m.items, &m.dangling, out),
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) => {
@@ -216,6 +253,57 @@ fn scan_nested(src: &str, item: &Item, out: &mut Vec<Region>) {
scan_gen_block(src, &i.body, out);
}
}
ItemKind::Class(c) => scan_scope(src, &c.items, &c.dangling, out),
ItemKind::Function(f) => scan_stmt_scope(src, &f.stmts, &f.dangling, out),
ItemKind::Task(t) => scan_stmt_scope(src, &t.stmts, &t.dangling, out),
ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => {
scan_nested_stmt(src, stmt, out)
}
_ => {}
}
}
/// Statement scopes nested inside one statement.
///
/// A statement *list* is a scope — `begin`…`end`, `fork`…`join*`. A
/// single-statement body is not, for the reason [`scan_gen_block`] refuses a
/// block-less generate item: there is no list for a fence to end in, and the
/// formatter lays that statement out inside a `Group`. So the bodies below are
/// walked into rather than scanned, and only the block one of them holds opens
/// a scope.
fn scan_nested_stmt(src: &str, stmt: &Stmt, out: &mut Vec<Region>) {
match &stmt.kind {
StmtKind::Block { stmts, dangling, .. } | StmtKind::ForkJoin { stmts, dangling, .. } => {
scan_stmt_scope(src, stmts, dangling, out)
}
StmtKind::If { then, els, .. } => {
scan_nested_stmt(src, then, out);
if let Some(e) = els {
scan_nested_stmt(src, e, out);
}
}
StmtKind::Assert { then, els, .. } => {
for s in then.iter().chain(els.iter()) {
scan_nested_stmt(src, s, out);
}
}
// A case item's *labels* are not a fenceable stream (see the feature
// README); the block one of them may hold is.
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
for i in items {
scan_nested_stmt(src, &i.stmt, out);
}
}
StmtKind::For { body, .. }
| StmtKind::While { body, .. }
| StmtKind::DoWhile { body, .. }
| StmtKind::Repeat { body, .. }
| StmtKind::Forever { body }
| StmtKind::Foreach { body, .. }
| StmtKind::Labeled { stmt: body, .. } => scan_nested_stmt(src, body, out),
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
scan_nested_stmt(src, inner, out)
}
_ => {}
}
}
@@ -242,6 +330,30 @@ fn scan_gen_block(src: &str, b: &GenBlock, out: &mut Vec<Region>) {
}
}
/// Whether a fence written at `at` begins the *content* of its line: nothing
/// but whitespace and finished block comments precedes it there.
///
/// This is what makes `begin // lucisv: off` an ordinary comment. The parser
/// hands a comment written after `begin` to the next *statement* as a leading
/// one, so without this test a region would open in the middle of a line and
/// take its first line's bytes from the wrong column. A fence preceded only by
/// another comment (`/* a */ // lucisv: off`) still opens one: that comment is
/// a unit of the same stream and prints on the line above.
fn opens_line(src: &str, at: usize) -> bool {
let bol = src.get(..at).and_then(|s| s.rfind('\n')).map_or(0, |i| i + 1);
let Some(mut before) = src.get(bol..at) else { return false };
loop {
before = before.trim_start();
if before.is_empty() {
return true;
}
match before.strip_prefix("/*").and_then(|b| b.split_once("*/")) {
Some((_, rest)) => before = rest,
None => return false,
}
}
}
/// The start of the line `at` sits on, when nothing but whitespace precedes it
/// there — otherwise `at` itself, so a fence sharing its line with another
/// comment does not swallow it.
@@ -323,6 +435,28 @@ mod tests {
assert_eq!(fence_of("// off"), None);
}
#[test]
fn a_fence_only_opens_a_region_at_the_start_of_its_line() {
// Whitespace before it, at any depth, and at the very first byte.
assert!(opens_line("// lucisv: off\n", 0));
assert!(opens_line("module m;\n // lucisv: off\n", 12));
assert!(opens_line("module m;\n\t\t// lucisv: off\n", 12));
// Another comment before it is still the start of the line's content.
let src = "module m;\n /* a */ // lucisv: off\n";
assert!(opens_line(src, src.find("//").expect("fence")));
let src = "module m;\n /* a */ /* b */ // lucisv: off\n";
assert!(opens_line(src, src.find("//").expect("fence")));
// Code before it is not — the two shapes the parser hands to the next
// node as a *leading* comment even though they trail code.
let src = "module m;\n always @(*) begin // lucisv: off\n x = 1;\n";
assert!(!opens_line(src, src.find("//").expect("fence")));
let src = "module m; // lucisv: off\n wire a;\n";
assert!(!opens_line(src, src.find("//").expect("fence")));
// An unterminated block comment before it is not a finished comment.
let src = "module m;\n /* a // lucisv: off\n";
assert!(!opens_line(src, src.find("// lucisv").expect("fence")));
}
#[test]
fn a_fence_line_starts_at_its_indentation() {
let src = "module m;\n // lucisv: off\n";
+10 -2
View File
@@ -38,7 +38,11 @@ impl<'a> Fmt<'a> {
if let Some(params) = &c.param_ports {
let items: Vec<ListItem> = params
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma))
.map(|p| {
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma)
})
})
.collect();
let items = self.list_entries(items, &c.param_directives);
let broken = !c.param_directives.is_empty();
@@ -52,7 +56,11 @@ impl<'a> Fmt<'a> {
if let Some(params) = &ext.params {
let items: Vec<ListItem> = params
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.connection(p)).with_comma(p.comma))
.map(|p| {
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.connection(p)).with_comma(p.comma)
})
})
.collect();
let items = self.list_entries(items, &ext.param_directives);
let broken = !ext.param_directives.is_empty();
+5
View File
@@ -305,6 +305,11 @@ impl<'a> Fmt<'a> {
// region never begins its own line, so a dedent-by-column would
// drift instead of reaching a fixed point.
ExprKind::Verbatim(raw) => self.raw_inline(raw),
// Unreachable from `format_source`, as `ItemKind::Error` is: only
// a tolerant parse builds this leaf, and the formatter parses
// strictly. Printed verbatim so nothing is lost if that ever
// changes — see `ListItem::from_raw`.
ExprKind::Error(raw) => self.raw_inline(raw),
ExprKind::MinTypMax { min, typ, max } => {
concat(vec![self.expr(min), text(":"), self.expr(typ), text(":"), self.expr(max)])
}
+22 -12
View File
@@ -28,7 +28,11 @@ impl<'a> Fmt<'a> {
if let Some(params) = &inst.params {
let items: Vec<ListItem> = params
.iter()
.map(|c| ListItem::from_meta(&c.meta, self.connection(c)).with_comma(c.comma))
.map(|c| {
self.list_elem(c, |c| {
ListItem::from_meta(&c.meta, self.connection(c)).with_comma(c.comma)
})
})
.collect();
let items = self.list_entries(items, &inst.param_directives);
let broken = !inst.param_directives.is_empty() || holds_verbatim_value(params);
@@ -109,19 +113,23 @@ impl<'a> Fmt<'a> {
list.iter()
.zip(&aligns)
.map(|(c, a)| {
ListItem::from_meta(&c.meta, self.connection_aligned(c, a.as_ref()))
.with_comma(c.comma)
self.list_elem(c, |c| {
ListItem::from_meta(&c.meta, self.connection_aligned(c, a.as_ref()))
.with_comma(c.comma)
})
})
.collect()
}
Connections::Ordered(list) => list
.iter()
.map(|c| {
let d = match &c.expr {
Some(e) => self.expr(e),
None => text(""),
};
ListItem::from_meta(&c.meta, d).with_comma(c.comma)
self.list_elem(c, |c| {
let d = match &c.expr {
Some(e) => self.expr(e),
None => text(""),
};
ListItem::from_meta(&c.meta, d).with_comma(c.comma)
})
})
.collect(),
};
@@ -132,18 +140,20 @@ impl<'a> Fmt<'a> {
/// The alignment plan for an instance's named connection list.
fn connection_aligns(
&self,
conns: &[Connection],
conns: &[ListElem<Connection>],
directives: &[ListDirective],
depth: usize,
) -> Vec<Option<Align>> {
let rows: Vec<Option<Row>> = conns
.iter()
.map(|c| {
// An error element has no cells to align, so it has no row.
let c = c.ok()?;
let paren = self.open_paren_offset(c.name_span.end)?;
Self::row_of(&self.connection_cells(c), vec![paren], usize::from(c.comma))
})
.collect();
let breaks = Self::list_breaks(conns.iter().map(|c| &c.meta), directives);
let breaks = Self::list_breaks(conns.iter().map(|c| c.ok().map(|c| &c.meta)), directives);
self.align_groups(&rows, &breaks, CONNECTION_COLS, depth)
}
@@ -369,8 +379,8 @@ impl<'a> Fmt<'a> {
/// be measured as one short line and flattened around a value that is
/// twenty lines tall. It is exactly the reason a list holding a
/// [`ListDirective`] is broken, for exactly the same construct.
fn holds_verbatim_value(list: &[Connection]) -> bool {
list.iter().any(|c| match &c.expr {
fn holds_verbatim_value(list: &[ListElem<Connection>]) -> bool {
list.iter().filter_map(ListElem::ok).any(|c| match &c.expr {
Some(Expr { kind: ExprKind::Verbatim(raw), .. }) => raw.text.contains('\n'),
_ => false,
})
+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);
+40 -2
View File
@@ -38,6 +38,27 @@ pub(super) struct ListItem {
}
impl ListItem {
/// The entry an error element of a header list prints as: the text a
/// tolerant parse skipped, verbatim, carrying no comments of its own —
/// they are bytes of that text.
///
/// **Unreachable from `format_source`**, exactly as `ItemKind::Error` is:
/// the formatter parses strictly, and only [`vlog_parser::parse_tolerant`]
/// builds a [`ListElem::Error`]. Printing the bytes rather than nothing
/// means that if some future entry point ever did hand one over,
/// `verify.rs`'s token-equivalence check would see the tokens instead of
/// silently losing them.
pub(super) fn from_raw(doc: Doc) -> Self {
ListItem {
leading: Vec::new(),
doc,
before_sep: Vec::new(),
trailing: None,
comma: None,
directive: false,
}
}
pub(super) fn from_meta(meta: &Meta, doc: Doc) -> Self {
ListItem {
leading: meta.leading.clone(),
@@ -58,6 +79,20 @@ impl ListItem {
}
impl<'a> Fmt<'a> {
/// One entry of a **header** list: the element as `entry` prints it, or —
/// for an error element — its bytes; see [`ListItem::from_raw`] for why
/// the second case cannot be reached from `format_source`.
pub(super) fn list_elem<T>(
&self,
elem: &ListElem<T>,
entry: impl FnOnce(&T) -> ListItem,
) -> ListItem {
match elem {
ListElem::Ok(v) => entry(v),
ListElem::Error(raw) => ListItem::from_raw(self.raw_text(raw)),
}
}
/// A bracketed expression list (concatenation, call arguments, `inside`
/// set). Comments on an element ride along and break the list open.
pub(super) fn expr_list(&self, open: &str, items: &[ExprItem], close: &str) -> Doc {
@@ -316,15 +351,18 @@ impl<'a> Fmt<'a> {
/// with a comment or an attribute of their own — both print on their own
/// line — and those a compiler directive was written in front of.
///
/// A `None` meta is an error element, which has none; it always starts a
/// group, being raw bytes of a width no other row shares.
///
/// A blank line is deliberately *not* a boundary here: `delimited` drops
/// blank lines between list elements, so a boundary drawn at one would
/// vanish from the output and the next pass would group differently.
pub(super) fn list_breaks<'m>(
metas: impl Iterator<Item = &'m Meta>,
metas: impl Iterator<Item = Option<&'m Meta>>,
directives: &[ListDirective],
) -> Vec<bool> {
let mut breaks: Vec<bool> =
metas.map(|m| !m.leading.is_empty() || !m.attrs.is_empty()).collect();
metas.map(|m| m.is_none_or(|m| !m.leading.is_empty() || !m.attrs.is_empty())).collect();
for d in directives {
if let Some(b) = breaks.get_mut(d.before) {
*b = true;
+16 -6
View File
@@ -67,7 +67,11 @@ impl<'a> Fmt<'a> {
if let Some(params) = &m.param_ports {
let items: Vec<ListItem> = params
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma))
.map(|p| {
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma)
})
})
.collect();
let items = self.list_entries(items, &m.param_directives);
let broken = !m.param_directives.is_empty();
@@ -94,15 +98,19 @@ impl<'a> Fmt<'a> {
.iter()
.zip(&aligns)
.map(|(p, a)| {
ListItem::from_meta(&p.meta, self.ansi_port(p, a.as_ref()))
.with_comma(p.comma)
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.ansi_port(p, a.as_ref()))
.with_comma(p.comma)
})
})
.collect()
}
PortList::NonAnsi(ports) => ports
.iter()
.map(|p| {
ListItem::from_meta(&p.meta, name_doc(&p.name)).with_comma(p.comma)
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, name_doc(&p.name)).with_comma(p.comma)
})
})
.collect(),
_ => Vec::new(),
@@ -223,13 +231,15 @@ impl<'a> Fmt<'a> {
/// The alignment plan for a module header's ANSI port list.
fn ansi_port_aligns(
&self,
ports: &[AnsiPort],
ports: &[ListElem<AnsiPort>],
directives: &[ListDirective],
depth: usize,
) -> Vec<Option<Align>> {
let rows: Vec<Option<Row>> = ports
.iter()
.map(|p| {
// An error element has no cells to align, so it has no row.
let p = p.ok()?;
Self::row_of(
&self.ansi_port_cells(p),
vec![p.name_span.start],
@@ -237,7 +247,7 @@ impl<'a> Fmt<'a> {
)
})
.collect();
let breaks = Self::list_breaks(ports.iter().map(|p| &p.meta), directives);
let breaks = Self::list_breaks(ports.iter().map(|p| p.ok().map(|p| &p.meta)), directives);
self.align_groups(&rows, &breaks, ANSI_PORT_COLS, depth)
}
+6 -4
View File
@@ -27,7 +27,7 @@ pub(super) struct TfHeader<'h> {
name: &'h str,
has_parens: bool,
before_args: &'h [Comment],
args: &'h [TfArg],
args: &'h [ListElem<TfArg>],
args_dangling: &'h [Comment],
}
@@ -119,9 +119,11 @@ impl<'a> Fmt<'a> {
}
}
pub(super) fn tf_args(&self, args: &[TfArg], dangling: &[Comment]) -> Doc {
let items: Vec<ListItem> =
args.iter().map(|a| ListItem::from_meta(&a.meta, self.tf_arg(a))).collect();
pub(super) fn tf_args(&self, args: &[ListElem<TfArg>], dangling: &[Comment]) -> Doc {
let items: Vec<ListItem> = args
.iter()
.map(|a| self.list_elem(a, |a| ListItem::from_meta(&a.meta, self.tf_arg(a))))
.collect();
self.delimited_dangling("(", items, dangling, ")", false)
}
+36 -4
View File
@@ -30,16 +30,48 @@ struct BlockDoc<'a> {
impl<'a> Fmt<'a> {
fn stmt(&self, s: &Stmt) -> Doc {
self.with_meta(&s.meta, self.stmt_kind(&s.kind, &s.before_semi))
concat(self.stmt_docs(s))
}
/// One statement: its leading comments, then — unless a verbatim region is
/// already emitting its bytes — its code and trailing comment. The
/// statement twin of `Fmt::item_docs`, with the same two rules: comments
/// written before the `off` fence are still emitted, because comments are
/// never dropped, and a statement the region swallowed emits nothing.
fn stmt_docs(&self, s: &Stmt) -> Vec<Doc> {
// A verbatim run whose first statement carries no leading comment opens
// at the statement's own code; there is no comment to emit it from.
if let Some(region) = self.opens_at(s.span.start as usize) {
return vec![self.verbatim(region)];
}
if self.is_verbatim(s.span) {
// The statement's own bytes, its attributes included, are emitted
// verbatim by the fence; only its leading comments are ours.
let mut docs = self.leading_comments(&s.meta);
// The last comment asked for a line break before code that is not
// coming. Whoever emits the next unit separates it itself.
if matches!(docs.last(), Some(Doc::HardLine)) {
docs.pop();
}
return docs;
}
vec![self.with_meta(&s.meta, self.stmt_kind(&s.kind, &s.before_semi))]
}
/// Sequence of statements at one indent level, preserving single blank
/// lines between them. A statement a fenced region swallowed emits
/// nothing, and contributes no separator either.
pub(super) fn stmt_seq(&self, stmts: &[Stmt]) -> Vec<Doc> {
let mut docs = Vec::new();
for (i, s) in stmts.iter().enumerate() {
if i > 0 {
for s in stmts {
let stmt_docs = self.stmt_docs(s);
if stmt_docs.is_empty() {
continue;
}
if !docs.is_empty() {
docs.push(if s.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
}
docs.push(self.stmt(s));
docs.extend(stmt_docs);
}
docs
}
+8 -1
View File
@@ -158,7 +158,14 @@ pub fn select(src: &str, file: &SourceFile, lines: &LineRanges) -> Selection {
pub fn plan(src: &str, file: &SourceFile, selection: &Selection) -> Plan {
let mut planner = Planner::new(src, file, Mode::Picks(&selection.picks));
planner.scope(&file.items, &file.dangling);
Plan { regions: normalize(planner.regions), splits: planner.splits }
// The fenced regions go in alongside the runs the picks made. An *item* a
// fence covers is already `Pick::Verbatim`, so its bytes are in a run
// either way; a fenced **statement** inside a laid-out item has no such
// run behind it, and without this the caller's `--lines` would reformat
// bytes the author fenced off. `normalize` folds the two into their union.
let mut regions = planner.regions;
regions.extend(planner.fences.iter().copied());
Plan { regions: normalize(regions), splits: planner.splits }
}
/// Sort the collected regions and fold everything that overlaps into one.
+246 -2
View File
@@ -372,7 +372,7 @@ wire a;
endgenerate
endmodule
====
# a statement-level fence has no effect this round
# a statement-level fence fences the statements between it and the on
module m;
always @(*) begin
// lucisv: off
@@ -382,15 +382,259 @@ y = 2;
end
endmodule
----
module m;
always @(*) begin
// lucisv: off
x = 1;
// lucisv: on
y = 2;
end
endmodule
====
# a statement region keeps its own indentation, first line included
module m;
initial begin
// lucisv: off
x <= 8'h0a;
yy <= 8'h0b;
// lucisv: on
z <= 1;
end
endmodule
----
module m;
initial begin
// lucisv: off
x <= 8'h0a;
yy <= 8'h0b;
// lucisv: on
z <= 1;
end
endmodule
====
# an unmatched off runs to the end of the block, not past its end
module m;
initial begin
// lucisv: off
x = 1;
y = 2; // note
end
initial begin
z = 3;
end
endmodule
----
module m;
initial begin
// lucisv: off
x = 1;
y = 2; // note
end
initial begin
z = 3;
end
endmodule
====
# an unmatched off in a fork body stops at the join
module m;
initial fork
// lucisv: off
p1 ();
p2 ();
join_none
endmodule
----
module m;
initial
fork
// lucisv: off
p1 ();
p2 ();
join_none
endmodule
====
# fences work in a function body and stop at endfunction
module m;
function int f();
// lucisv: off
int a =1;
// lucisv: on
return a;
endfunction
endmodule
----
module m;
function int f();
// lucisv: off
int a =1;
// lucisv: on
return a;
endfunction
endmodule
====
# a fence inside a case item's block body fences that block only
module m;
always @(*) begin
case (s)
2'b00: begin
// lucisv: off
a = 1;
// lucisv: on
b = 2;
end
default: c = 3;
endcase
end
endmodule
----
module m;
always @(*) begin
case (s)
2'b00: begin
// lucisv: off
a = 1;
// lucisv: on
b = 2;
end
default: c = 3;
endcase
end
endmodule
====
# a fence written after begin on the same line is an ordinary comment
module m;
always @(*) begin // lucisv: off
x = 1;
y = 2;
end
endmodule
----
module m;
always @(*) begin
// lucisv: off
x = 1;
// lucisv: on
y = 2;
end
endmodule
====
# a fence written after a module header on the same line is an ordinary comment
module m; // lucisv: off
wire a;
wire b;
endmodule
----
module m;
// lucisv: off
wire a;
wire b;
endmodule
====
# a fence inside a bodyless if is an ordinary comment
module m;
always @(*)
// lucisv: off
if (c) x = 1;
endmodule
----
module m;
always @(*)
// lucisv: off
if (c) x = 1;
endmodule
====
# fences work inside a class body
class c;
int a;
// lucisv: off
int b =2;
int cc =3;
// lucisv: on
int d;
endclass
----
class c;
int a;
// lucisv: off
int b =2;
int cc =3;
// lucisv: on
int d;
endclass
====
# an unmatched off in a class body stops at endclass
class c;
// lucisv: off
int a;
endclass
class d;
int b;
endclass
----
class c;
// lucisv: off
int a;
endclass
class d;
int b;
endclass
====
# a fence around a nested class fences the whole nested class
class outer;
// lucisv: off
class inner;
int x;
endclass
// lucisv: on
int y;
endclass
----
class outer;
// lucisv: off
class inner;
int x;
endclass
// lucisv: on
int y;
endclass
====
# a port-list fence is an ordinary comment, and the port list still formats
module m (
// lucisv: off
input logic a,
output logic b
);
endmodule
----
module m (
// lucisv: off
input logic a,
output logic b
);
endmodule
====
# a case-item label fence is an ordinary comment
module m;
always @(*) begin
case (s)
// lucisv: off
2'b00: a = 1;
2'b01: a = 2;
endcase
end
endmodule
----
module m;
always @(*) begin
case (s)
// lucisv: off
2'b00: a = 1;
2'b01: a = 2;
endcase
end
endmodule
====
# a blank line before the off fence survives, collapsed to one
module m;
wire z;
+136
View File
@@ -93,6 +93,142 @@ fn a_corrupted_fenced_region_is_still_rejected_by_the_safety_net() {
}
}
#[test]
fn a_statement_region_is_emitted_byte_for_byte() {
// A fence between two statements of an `always` block: the hand-aligned
// interior, the blank line and the trailing comment all survive, and the
// statement after the `on` is formatted normally.
let src = "module m;\n always_ff @(posedge clk) begin\n // lucisv: off\n q0 <= d0; // lo\n\n q1 <= d1;\n // lucisv: on\n q2 <= d2;\n end\nendmodule\n";
let region =
" // lucisv: off\n q0 <= d0; // lo\n\n q1 <= d1;\n // lucisv: on";
let out = fenced(src, region);
assert!(out.contains("\n q2 <= d2;\n"), "formatting did not resume in the block:\n{out}");
}
#[test]
fn an_unmatched_off_in_a_statement_list_stops_at_the_end_of_that_list() {
// It must stop at the block's last statement — its trailing comment
// included — and never swallow the `end`, the `endfunction` or anything
// after them.
let src = "module m;\n initial begin\n // lucisv: off\n x = 1;\n y = 2; // note\n end\n\n function int f();\n return 1;\n endfunction\nendmodule\n";
let out = fenced(src, " // lucisv: off\n x = 1;\n y = 2; // note");
assert!(out.contains("\n end\n"), "the block's `end` was swallowed:\n{out}");
assert!(out.contains("function int f();"), "the next item was not formatted:\n{out}");
assert!(out.contains(" return 1;"), "the next body was not formatted:\n{out}");
}
#[test]
fn a_fork_body_and_a_task_body_are_each_their_own_scope() {
let src = "module m;\n task automatic t();\n fork\n // lucisv: off\n p1 ();\n p2 ();\n // lucisv: on\n p3 ();\n join\n z = 1;\n endtask\nendmodule\n";
let out =
fenced(src, " // lucisv: off\n p1 ();\n p2 ();\n // lucisv: on");
assert!(out.contains(" p3();"), "the statement after the `on` was not formatted:\n{out}");
assert!(out.contains(" z = 1;"), "the task body after the fork was not formatted:\n{out}");
}
#[test]
fn a_class_body_is_a_fenceable_scope() {
let src = "class c;\n int a;\n // lucisv: off\n int b = 2;\n int cc =3;\n // lucisv: on\n int d;\nendclass\n";
let out = fenced(src, " // lucisv: off\n int b = 2;\n int cc =3;\n // lucisv: on");
assert!(out.contains(" int a;\n"), "{out}");
assert!(out.contains(" int d;\n"), "{out}");
}
#[test]
fn an_unmatched_off_in_a_class_body_stops_at_endclass() {
let src = "class c;\n // lucisv: off\n int a; // note\nendclass\n\nclass d;\n int b;\nendclass\n";
let out = fenced(src, " // lucisv: off\n int a; // note");
assert!(out.contains("class d;\n int b;\n"), "the next class was not formatted:\n{out}");
}
#[test]
fn a_fence_sharing_its_line_with_code_is_an_ordinary_comment() {
// `begin // lucisv: off` reaches the scan as the *leading* comment of the
// first statement, mid-line. Honouring it would open a region whose first
// line came from the wrong column; it is an ordinary comment instead.
let src = "module m;\n always @(*) begin // lucisv: off\n x = 1;\n y = 2;\n end\nendmodule\n";
let out = fmt(src);
verify_equivalence(src, &out).expect("equivalent");
assert_eq!(fmt(&out), out, "second pass changed the output");
assert!(out.contains(" x = 1;"), "the fence fired mid-line:\n{out}");
// The same rule at item level: a header's own line is not a fence line.
let src = "module m; // lucisv: off\n wire a;\nendmodule\n";
let out = fmt(src);
verify_equivalence(src, &out).expect("equivalent");
assert_eq!(fmt(&out), out, "second pass changed the output");
assert!(out.contains(" wire a;"), "the fence fired mid-line:\n{out}");
}
#[test]
fn the_three_deferred_places_are_inert_and_never_corrupt() {
// A port list, a case-item label list, and the single-statement body of a
// bodyless `if`: a fence in each is an ordinary comment, and the code
// around it is laid out exactly as it would be without one.
let cases = [
"module m (\n // lucisv: off\n input logic a,\n output logic b\n);\nendmodule\n",
"module m;\n always @(*) case (s)\n // lucisv: off\n 2'b00: a = 1;\n 2'b01: a = 2;\n endcase\nendmodule\n",
"module m;\n always @(*)\n // lucisv: off\n if (c) x = 1;\nendmodule\n",
];
for src in cases {
let out = fmt(src);
verify_equivalence(src, &out).expect("output is token-equivalent to the input");
assert_eq!(fmt(&out), out, "second pass changed the output:\n{out}");
assert!(out.contains("lucisv: off"), "the fence comment was dropped:\n{out}");
assert!(!out.contains(" a = 1"), "the fence fenced:\n{out}");
assert!(!out.contains("input logic"), "the fence fenced:\n{out}");
}
}
#[test]
fn a_corrupted_statement_or_class_region_is_still_rejected_by_the_safety_net() {
// The same attack as at item level, aimed at the two new scopes: a fence
// is not a licence to change bytes, and a hand-built "output" that
// reformats, drops or adds anything inside one must fail equivalence.
// Every pair changes the *token stream*, which is the question
// `verify_equivalence` answers; that a region's bytes are also reproduced
// exactly — spacing included, which no token check can see — is what the
// `fenced` helper asserts in the tests above.
let stmt = "module m;\n initial begin\n // lucisv: off\n x = 1;\n y = 2; // note\n // lucisv: on\n end\nendmodule\n";
let stmt_corrupted = [
// a literal rewritten inside the region
"module m;\n initial begin\n // lucisv: off\n x = 7;\n y = 2; // note\n // lucisv: on\n end\nendmodule\n",
// the region's trailing comment dropped
"module m;\n initial begin\n // lucisv: off\n x = 1;\n y = 2;\n // lucisv: on\n end\nendmodule\n",
// the `off` fence itself dropped
"module m;\n initial begin\n x = 1;\n y = 2; // note\n // lucisv: on\n end\nendmodule\n",
// a statement added inside the region
"module m;\n initial begin\n // lucisv: off\n x = 1;\n z = 0;\n y = 2; // note\n // lucisv: on\n end\nendmodule\n",
// a statement dropped from inside the region
"module m;\n initial begin\n // lucisv: off\n x = 1;\n // lucisv: on\n end\nendmodule\n",
// the `on` fence turned into an ordinary comment
"module m;\n initial begin\n // lucisv: off\n x = 1;\n y = 2; // note\n // lucisv: onward\n end\nendmodule\n",
// the block's `end` swallowed into the region's last line
"module m;\n initial begin\n // lucisv: off\n x = 1;\n y = 2; // note\n // lucisv: on\nendmodule\n",
];
let class = "class c;\n // lucisv: off\n int b = 2;\n int cc =3;\n // lucisv: on\n int d;\nendclass\n";
let class_corrupted = [
// a type rewritten inside the region
"class c;\n // lucisv: off\n bit b = 2;\n int cc =3;\n // lucisv: on\n int d;\nendclass\n",
// a member dropped from inside the region
"class c;\n // lucisv: off\n int b = 2;\n // lucisv: on\n int d;\nendclass\n",
// a member added inside the region
"class c;\n // lucisv: off\n int b = 2;\n int cc =3;\n int e;\n // lucisv: on\n int d;\nendclass\n",
// `endclass` swallowed
"class c;\n // lucisv: off\n int b = 2;\n int cc =3;\n // lucisv: on\n int d;\n",
// a fence comment dropped
"class c;\n int b = 2;\n int cc =3;\n // lucisv: on\n int d;\nendclass\n",
];
for (src, corrupted) in [(stmt, &stmt_corrupted[..]), (class, &class_corrupted[..])] {
verify_equivalence(src, &fmt(src)).expect("the real output is equivalent");
for bad in corrupted {
assert!(
verify_equivalence(src, bad).is_err(),
"a corrupted fenced region was accepted:\n{bad}"
);
}
}
}
#[test]
fn the_matcher_agrees_with_what_the_formatter_honours() {
// The unit tests in `fence.rs` pin the matcher; this pins that the
+34
View File
@@ -218,6 +218,40 @@ fn a_fence_outranks_a_range() {
assert!(out.contains(" wire b;\n wire c;\n"), "the region is untouched: {out}");
}
const WITH_STMT_FENCE: &str = "\
module m;
initial begin
a = 1;
// lucisv: off
b = 2;
cc = 3;
// lucisv: on
d = 4;
end
endmodule
";
#[test]
fn a_statement_fence_outranks_a_range_too() {
// A fenced *statement* sits inside an item the caller's lines select, so
// there is no verbatim run behind it: the plan has to carry the fence
// itself or the region would be laid out. Selecting any line of it, or
// the whole block, must leave those bytes exactly as written.
for spec in ["4", "5", "6", "7", "2-10"] {
let out = fixed_point(WITH_STMT_FENCE, spec);
assert!(
out.contains(" // lucisv: off\n b = 2;\n cc = 3;\n // lucisv: on\n"),
"spec {spec} reformatted the region:\n{out}"
);
}
// Laying out the whole block still formats what is outside the region.
let out = fixed_point(WITH_STMT_FENCE, "2-10");
assert!(out.contains(" a = 1;"), "{out}");
assert!(out.contains(" d = 4;"), "{out}");
// And a range that misses the block entirely changes nothing at all.
assert_eq!(fixed_point(WITH_STMT_FENCE, "1"), WITH_STMT_FENCE);
}
const ALIGNED: &str = "\
module m;
localparam int A = 1;
@@ -0,0 +1,16 @@
//! Prints the `lucisv.lint.severity.*` and `lucisv.lint.rules.*` settings for
//! `editors/vscode/package.json`, generated from the rule registry.
//!
//! ```text
//! cargo run -p vlog_linter --example vscode_lint_settings
//! ```
//!
//! Paste the body of the printed object into that file's
//! `contributes.configuration.properties`, replacing the block that is there.
//! The drift test in `lucisv_server` (`settings::tests::
//! the_vscode_lint_toggles_match_the_registry`) fails whenever the two
//! disagree, so a rule cannot ship without its toggle.
fn main() {
print!("{}", vlog_linter::vscode_lint_settings());
}
+165
View File
@@ -9,12 +9,20 @@ use vlog_parser::token::{Comment, Token, TokenKind};
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LexError, LineIndex};
use vlog_semantic::{analyze, Semantics};
use crate::options::RuleOptions;
use crate::signals::Signals;
/// The default tab stop used when a fix expands a tab, matching lucisv's
/// default indent. `LintContext::with_tab_width` follows `--indent`.
const DEFAULT_TAB_WIDTH: usize = 2;
/// The width `line-length` holds a file to when nothing says otherwise —
/// `vlog_formatter::Config`'s own default, because the two are the same
/// number: a formatted file that the linter then calls too wide would be
/// lucisv disagreeing with itself. `LintContext::with_line_length` follows
/// `--line-length` and `lucisv.toml`.
const DEFAULT_LINE_LENGTH: usize = 100;
/// One text, parsed once: the products a lint run reads.
///
/// This is the owned half of "one parse, two tools" (TODO §4): a caller with
@@ -84,6 +92,16 @@ impl ParsedSource {
&self.tokens
}
/// The tolerant parse itself — public for the same reason [`tokens`] is:
/// a caller that has already paid for the parse can read the tree for
/// something else (`lucisv check` harvests its interface census off it)
/// instead of parsing the same text twice.
///
/// [`tokens`]: ParsedSource::tokens
pub fn file(&self) -> &SourceFile {
&self.file
}
/// A lint context borrowing this parse. `path` is the file the text came
/// from, or `None` for a buffer (stdin) — rules that need a filename skip.
pub fn context(&self, path: Option<PathBuf>) -> LintContext<'_> {
@@ -125,6 +143,42 @@ enum Backing<'a> {
pub trait MentionOracle: Sync {
/// Whether any file **other than** the one being linted mentions `name`.
fn mentioned_elsewhere(&self, name: &str) -> bool;
/// What the project says the module or interface `name` declares, or
/// `None` when it cannot say — the unit is not in the project, or it is
/// declared more than once and the declarations disagree.
///
/// The second question a rule may ask about other files, added by TODO
/// §33.2 for `unknown-port` and `unknown-parameter`. It is deliberately
/// still a *closed* question — the names a connection list may use, and
/// nothing about them — and `None` is a first-class answer that every
/// caller must treat as silence rather than as an empty list. A front end
/// with no such table at all answers `None` to everything, which leaves
/// those two rules quiet and every other rule exactly where it was.
fn module_interface(&self, _name: &str) -> Option<ModuleInterface> {
None
}
}
/// The names a module or interface declares that an instantiation may write.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ModuleInterface {
/// Port names, as written.
pub ports: Vec<String>,
/// Overridable parameter names, as written — a `localparam` is not one.
pub parameters: Vec<String>,
}
impl ModuleInterface {
/// Whether the unit declares a port called `name`.
pub fn has_port(&self, name: &str) -> bool {
self.ports.iter().any(|port| port == name)
}
/// Whether the unit declares an overridable parameter called `name`.
pub fn has_parameter(&self, name: &str) -> bool {
self.parameters.iter().any(|parameter| parameter == name)
}
}
/// Where a context's symbol table comes from: lent by a caller that already
@@ -134,6 +188,12 @@ pub trait MentionOracle: Sync {
/// Lazy rather than eager because most rules are syntactic: a run with no
/// semantic rule enabled — which is every default `lucisv check`, since all
/// three semantic rules ship off — must not pay for an analysis nobody reads.
// The `Lazy` variant is the table itself, held inline on purpose: it is one
// per lint run, it is written exactly once, and boxing it would add an
// allocation to the path that already avoided one by not analyzing at all.
// `Semantics` grew past clippy's variant-size threshold when it gained its
// `duplicates` table (§33.2); nothing about the trade changed with it.
#[allow(clippy::large_enum_variant)]
enum SemanticsSlot<'a> {
Lent(&'a Semantics),
Lazy(OnceCell<Semantics>),
@@ -149,6 +209,10 @@ pub struct LintContext<'a> {
backing: Backing<'a>,
path: Option<PathBuf>,
tab_width: usize,
line_length: usize,
/// What the run configured about each rule, or `None` for a run that
/// configured nothing — which reads exactly as the specs' own defaults.
options: Option<&'a RuleOptions>,
/// Byte ranges of string literals, ascending — the one place text rules
/// must not rewrite, because there whitespace is data.
strings: Vec<TextRange>,
@@ -156,6 +220,9 @@ pub struct LintContext<'a> {
/// The signal table the semantic rules read, built once for all of them
/// the first time one asks — and never for a run with none enabled.
signals: OnceCell<Signals>,
/// Whether the tolerant parse produced no `Error` leaf, answered once for
/// the rules that read structure. See [`LintContext::parsed_cleanly`].
clean: OnceCell<bool>,
/// What the workspace says about a name, when the caller has a workspace.
/// `None` is a run that cannot see other files — a single-file
/// `lucisv check`, stdin, a unit test — and every rule that would consult
@@ -199,9 +266,12 @@ impl<'a> LintContext<'a> {
backing,
path,
tab_width: DEFAULT_TAB_WIDTH,
line_length: DEFAULT_LINE_LENGTH,
options: None,
strings: Vec::new(),
semantics: SemanticsSlot::Lazy(OnceCell::new()),
signals: OnceCell::new(),
clean: OnceCell::new(),
oracle: None,
};
ctx.strings =
@@ -215,6 +285,68 @@ impl<'a> LintContext<'a> {
self
}
/// Sets the width the run's formatter would wrap to, which is what
/// `line-length` holds the file to unless that rule's own `length` option
/// says otherwise.
pub fn with_line_length(mut self, line_length: usize) -> LintContext<'a> {
self.line_length = line_length.max(1);
self
}
/// Lends the per-rule options the run resolved. A context without them
/// reads every option at its declared default, which is the shipped
/// behaviour.
pub fn with_options(mut self, options: &'a RuleOptions) -> LintContext<'a> {
self.options = Some(options);
self
}
/// The width the run's formatter wraps to. See
/// [`with_line_length`](LintContext::with_line_length).
pub fn line_length(&self) -> usize {
self.line_length
}
/// What the run configured, or the empty set.
pub fn options(&self) -> &RuleOptions {
match self.options {
Some(options) => options,
None => RuleOptions::none(),
}
}
/// One boolean option of `rule`, or its declared default.
pub fn option_bool(&self, rule: &str, key: &str) -> bool {
self.options().bool(rule, key)
}
/// One integer option of `rule`, or its declared default.
pub fn option_int(&self, rule: &str, key: &str) -> i64 {
self.options().int(rule, key)
}
/// One string (or pattern) option of `rule`, or its declared default.
pub fn option_str(&self, rule: &str, key: &str) -> &str {
self.options().str(rule, key)
}
/// One list option of `rule`, or its declared default.
pub fn option_list(&self, rule: &str, key: &str) -> Vec<String> {
self.options().list(rule, key)
}
/// Whether the run said anything about this option at all — the question
/// a rule asks when its fallback is not its spec's default.
pub fn option_is_set(&self, rule: &str, key: &str) -> bool {
self.options().is_set(rule, key)
}
/// One pattern option of `rule`, compiled, or `None` if it does not
/// compile — which cannot happen for a value this run accepted.
pub(crate) fn option_pattern(&self, rule: &str, key: &str) -> Option<crate::regex::Regex> {
crate::options::pattern(self.options(), rule, key)
}
/// Lends the symbol table the caller already built for this exact text —
/// "one parse, two tools" extended to the analysis (the language server
/// analyzes every buffer anyway, so its lint pass must not analyze twice).
@@ -245,6 +377,13 @@ impl<'a> LintContext<'a> {
self.oracle.is_some_and(|oracle| oracle.mentioned_elsewhere(name))
}
/// What the project says the unit `name` declares. `None` — no oracle, no
/// such unit, or two that disagree — means the run cannot answer, and a
/// rule that asked must then say nothing.
pub fn module_interface(&self, name: &str) -> Option<ModuleInterface> {
self.oracle?.module_interface(name)
}
/// Whether this run can see other files at all.
pub fn has_oracle(&self) -> bool {
self.oracle.is_some()
@@ -266,6 +405,32 @@ impl<'a> LintContext<'a> {
self.signals.get_or_init(|| Signals::scan(self))
}
/// Whether the whole file fit the grammar — no `Error` leaf anywhere in
/// the tolerant parse.
///
/// The tolerant parse is what makes a text rule work in a half-written
/// buffer, and most rules are right to ignore the difference. A rule that
/// reads **structure** is not: error recovery unwinds out of the construct
/// it failed in, so the declarations that followed are bound in whatever
/// scope recovery landed in — a class method's locals end up at file
/// scope, and every one of them looks like a redeclaration of the last
/// method's. Measured on opentitan: `spi_device_scoreboard.sv` (454 parse
/// errors, a macro-heavy UVM file) produced sixteen such phantoms, which
/// is sixteen wrong accusations from one file. A rule that would rather be
/// silent than wrong asks this first.
pub fn parsed_cleanly(&self) -> bool {
*self.clean.get_or_init(|| {
let mut clean = true;
crate::visit::walk_items(self.file(), &mut |item| {
clean &= !matches!(item.kind, vlog_parser::ast::ItemKind::Error(_));
});
crate::visit::walk_all_stmts(self.file(), &mut |stmt| {
clean &= !matches!(stmt.kind, vlog_parser::ast::StmtKind::Error(_));
});
clean
})
}
/// The source text being linted.
pub fn source(&self) -> &str {
match &self.backing {
+331
View File
@@ -0,0 +1,331 @@
//! Every declared type and every dimension in a file.
//!
//! A `DataType` is written in a dozen places — a port, a parameter, a
//! declarator, a typedef's base, a struct member, a subroutine's return type
//! and its arguments — and the rules that judge a *type* (the packed-dimension
//! ordering, a negative array bound) care about all of them equally. Collecting
//! them lives here rather than in `visit`, which is about the item and
//! statement spines; keeping the two apart is what stops either file from
//! becoming "everything a rule might want to walk".
use vlog_parser::ast::{
DataType, Dim, EnumType, FunctionDecl, ItemKind, ListElem, SourceFile, StmtKind, StructType,
TaskDecl, TfArg, TypeExtra, TypedefKind,
};
use vlog_parser::span::TextRange;
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
/// Where a dimension was written. The two are different constructs with
/// different conventions — `[N-1:0]` for a packed vector, `[N]` for an array —
/// so a rule that judges one must not judge the other by accident.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Packing {
/// Written before the declared name: a vector's width.
Packed,
/// Written after it: an array's extent.
Unpacked,
}
/// Calls `f` on every data type written in the file, an anonymous aggregate's
/// members and base included.
pub(crate) fn walk_data_types(file: &SourceFile, f: &mut dyn FnMut(&DataType)) {
let mut visit = |ty: &DataType| descend(ty, f);
walk_param_ports(file, &mut |port| visit(&port.ty));
walk_items(file, &mut |item| match &item.kind {
ItemKind::Module(module) => {
if let vlog_parser::ast::PortList::Ansi(ports) = &module.ports {
for port in ports.iter().filter_map(ListElem::ok) {
visit(&port.ty);
}
}
}
ItemKind::Typedef(typedef) => typedef_types(&typedef.kind, &mut visit),
ItemKind::ParamDecl(decl) => visit(&decl.ty),
ItemKind::DataDecl(decl) => visit(&decl.ty),
ItemKind::PortDecl(decl) => visit(&decl.ty),
ItemKind::Function(decl) => function_types(decl, &mut visit),
ItemKind::Task(decl) => task_types(decl, &mut visit),
_ => {}
});
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
StmtKind::VarDecl(decl) => visit(&decl.ty),
StmtKind::ParamDecl(decl) => visit(&decl.ty),
StmtKind::PortDecl(decl) => visit(&decl.ty),
StmtKind::Typedef(typedef) => typedef_types(&typedef.kind, &mut visit),
_ => {}
});
}
/// Calls `f` on every dimension in the file, saying which kind it is.
pub(crate) fn walk_dims(file: &SourceFile, f: &mut dyn FnMut(Packing, &Dim)) {
walk_data_types(file, &mut |ty| {
for dim in &ty.packed {
f(Packing::Packed, dim);
}
});
walk_unpacked(file, f);
}
/// The unpacked half: the `[…]` written *after* a declared name.
fn walk_unpacked(file: &SourceFile, f: &mut dyn FnMut(Packing, &Dim)) {
let mut unpacked = |dims: &[Dim]| {
for dim in dims {
f(Packing::Unpacked, dim);
}
};
walk_param_ports(file, &mut |port| unpacked(&port.unpacked));
walk_items(file, &mut |item| match &item.kind {
ItemKind::Module(module) => {
if let vlog_parser::ast::PortList::Ansi(ports) = &module.ports {
for port in ports.iter().filter_map(ListElem::ok) {
unpacked(&port.unpacked);
}
}
}
ItemKind::Typedef(typedef) => unpacked(&typedef.unpacked),
ItemKind::ParamDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
ItemKind::DataDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
ItemKind::PortDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
ItemKind::Function(decl) => arg_dims(&decl.args, &mut unpacked),
ItemKind::Task(decl) => arg_dims(&decl.args, &mut unpacked),
_ => {}
});
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
StmtKind::VarDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
StmtKind::ParamDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
StmtKind::PortDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
StmtKind::Typedef(typedef) => unpacked(&typedef.unpacked),
_ => {}
});
}
fn declarator_dims(declarators: &[vlog_parser::ast::Declarator], unpacked: &mut dyn FnMut(&[Dim])) {
for declarator in declarators {
unpacked(&declarator.unpacked);
}
}
fn arg_dims(args: &[ListElem<TfArg>], unpacked: &mut dyn FnMut(&[Dim])) {
for arg in args.iter().filter_map(ListElem::ok) {
unpacked(&arg.unpacked);
}
}
fn typedef_types(kind: &TypedefKind, visit: &mut dyn FnMut(&DataType)) {
match kind {
TypedefKind::Alias(ty) => visit(ty),
TypedefKind::Enum(enum_ty) => enum_types(enum_ty, visit),
TypedefKind::Struct(struct_ty) => struct_types(struct_ty, visit),
TypedefKind::ForwardClass => {}
}
}
fn function_types(decl: &FunctionDecl, visit: &mut dyn FnMut(&DataType)) {
if let Some(ret) = &decl.ret {
visit(ret);
}
for arg in decl.args.iter().filter_map(ListElem::ok) {
visit(&arg.ty);
}
}
fn task_types(decl: &TaskDecl, visit: &mut dyn FnMut(&DataType)) {
for arg in decl.args.iter().filter_map(ListElem::ok) {
visit(&arg.ty);
}
}
fn enum_types(enum_ty: &EnumType, visit: &mut dyn FnMut(&DataType)) {
if let Some(base) = &enum_ty.base {
visit(base);
}
}
fn struct_types(struct_ty: &StructType, visit: &mut dyn FnMut(&DataType)) {
for member in &struct_ty.members {
visit(&member.ty);
}
}
/// A type written in a declaration, with the name that declaration gives.
///
/// What the two `typedef-*` rules need and `walk_data_types` cannot say: a
/// `DataType` carries no span of its own, so a rule that judges the *type* of
/// a declaration reports at the name — and needs to know whether that
/// declaration is nested inside another aggregate's body.
pub(crate) struct DeclaredType<'a> {
/// The type as written.
pub(crate) ty: &'a DataType,
/// The name declared with it.
pub(crate) name: &'a str,
/// Byte range of that name — where a finding points.
pub(crate) span: TextRange,
/// True when this declaration is a member of another `struct`/`union`.
pub(crate) nested: bool,
}
/// Calls `f` on every type written in a **declaration** — a data or port
/// declaration, an ANSI port, a variable declaration in a statement — and on
/// every member of an aggregate written inside one.
///
/// A `typedef`'s own base type is deliberately not visited: a named type is
/// exactly what the `typedef-*` rules ask for, so passing it to them would be
/// asking them to flag the shape they exist to encourage. Its members are
/// visited, as nested declarations.
pub(crate) fn walk_declared_types(file: &SourceFile, f: &mut dyn FnMut(&DeclaredType)) {
walk_items(file, &mut |item| match &item.kind {
ItemKind::Module(module) => {
if let vlog_parser::ast::PortList::Ansi(ports) = &module.ports {
for port in ports.iter().filter_map(ListElem::ok) {
declared(&port.ty, &port.name, port.name_span, false, f);
}
}
}
ItemKind::DataDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
ItemKind::PortDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
// Only the members: the typedef itself is the named type these rules
// want, and the naming rules judge its name.
ItemKind::Typedef(typedef) => typedef_members(&typedef.kind, f),
_ => {}
});
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
StmtKind::VarDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
StmtKind::PortDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
StmtKind::Typedef(typedef) => typedef_members(&typedef.kind, f),
_ => {}
});
}
/// One declaration, and whatever aggregate its type carries.
fn declared(
ty: &DataType,
name: &str,
span: TextRange,
nested: bool,
f: &mut dyn FnMut(&DeclaredType),
) {
f(&DeclaredType { ty, name, span, nested });
members_of(ty, f);
}
/// One declaration's type, once per name it declares.
fn declarator_types(
ty: &DataType,
declarators: &[vlog_parser::ast::Declarator],
f: &mut dyn FnMut(&DeclaredType),
) {
for declarator in declarators {
declared(ty, &declarator.name, declarator.name_span, false, f);
}
}
/// The members of an anonymous aggregate, and of the aggregates inside it.
fn members_of(ty: &DataType, f: &mut dyn FnMut(&DeclaredType)) {
if let Some(TypeExtra::Struct(structure)) = ty.inline() {
struct_members(structure, f);
}
}
/// The members of a `struct`/`union` body, each as a nested declaration.
fn struct_members(structure: &StructType, f: &mut dyn FnMut(&DeclaredType)) {
for member in &structure.members {
for declarator in &member.declarators {
f(&DeclaredType {
ty: &member.ty,
name: &declarator.name,
span: declarator.name_span,
nested: true,
});
}
members_of(&member.ty, f);
}
}
/// A typedef's members — everything inside its body, but not the body itself.
fn typedef_members(kind: &TypedefKind, f: &mut dyn FnMut(&DeclaredType)) {
if let TypedefKind::Struct(structure) = kind {
struct_members(structure, f);
}
}
/// One type and whatever aggregate it *is*: an anonymous `enum`'s base and an
/// anonymous `struct`'s members are types written inside this one.
fn descend(ty: &DataType, f: &mut dyn FnMut(&DataType)) {
f(ty);
match ty.inline() {
Some(TypeExtra::Enum(enum_ty)) => enum_types(enum_ty, &mut |inner| descend(inner, f)),
Some(TypeExtra::Struct(struct_ty)) => {
struct_types(struct_ty, &mut |inner| descend(inner, f))
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::parse_source_tolerant;
fn packed_widths(src: &str) -> Vec<String> {
let (file, _) = parse_source_tolerant(src);
let mut out = Vec::new();
walk_dims(&file, &mut |packing, dim| {
if packing == Packing::Packed {
out.push(src[dim.span.as_range()].to_string());
}
});
out
}
fn unpacked_extents(src: &str) -> Vec<String> {
let (file, _) = parse_source_tolerant(src);
let mut out = Vec::new();
walk_dims(&file, &mut |packing, dim| {
if packing == Packing::Unpacked {
out.push(src[dim.span.as_range()].to_string());
}
});
out
}
#[test]
fn reaches_the_packed_dimensions_of_every_declaration_shape() {
let src = "module m #(parameter logic [1:0] P = 0) (\n\
input logic [2:0] a\n\
);\n\
logic [3:0] b;\n\
typedef logic [4:0] w_t;\n\
function logic [5:0] f(input logic [6:0] x);\n\
logic [7:0] local_v;\n\
return 0;\n\
endfunction\n\
endmodule\n";
assert_eq!(
packed_widths(src),
vec!["[1:0]", "[2:0]", "[3:0]", "[4:0]", "[5:0]", "[6:0]", "[7:0]"]
);
}
#[test]
fn reaches_an_anonymous_aggregates_members_and_base() {
let src = "module m;\n\
struct packed { logic [1:0] a; logic [2:0] b; } s;\n\
enum logic [3:0] { A } e;\n\
endmodule\n";
assert_eq!(packed_widths(src), vec!["[1:0]", "[2:0]", "[3:0]"]);
}
#[test]
fn packed_and_unpacked_are_told_apart() {
let src = "module m;\n logic [1:0] q [4];\nendmodule\n";
assert_eq!(packed_widths(src), vec!["[1:0]"]);
assert_eq!(unpacked_extents(src), vec!["[4]"]);
}
#[test]
fn a_struct_member_is_reached_through_a_typedef() {
let src = "typedef struct packed {\n logic [9:0] wide;\n} w_t;\n";
assert_eq!(packed_widths(src), vec!["[9:0]"]);
}
}
+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);
}
}
+182
View File
@@ -0,0 +1,182 @@
//! What each module in one file declares that an instantiation may name.
//!
//! The language server answers [`MentionOracle::module_interface`] from its
//! workspace index, which already records every module's ports and parameters.
//! `lucisv check` has no index, so it reads the same facts off the parse it
//! makes anyway — this file is that reading, and it lives here so the CLI and
//! the linter cannot come to disagree about what "a port of this module" is.
//!
//! Erring is one-directional on purpose: a unit whose header lucisv cannot see
//! whole is reported as **unknowable** rather than as a short list, because a
//! short list is what turns a legal connection into an accusation.
use vlog_parser::ast::{ItemKind, ListElem, Module, ParamPort, PortList, SourceFile};
use crate::context::ModuleInterface;
use crate::visit::walk_items;
/// Every module, interface and program the file declares, with what it
/// exposes. `None` for a unit whose header cannot be read whole.
///
/// A file may declare a name twice (two `` `ifdef`` arms, a copy-paste); the
/// caller merges across files and must treat any disagreement as unknowable,
/// so both entries are returned rather than one.
pub fn module_interfaces(file: &SourceFile) -> Vec<(String, Option<ModuleInterface>)> {
let mut out = Vec::new();
walk_items(file, &mut |item| {
if let ItemKind::Module(module) = &item.kind {
out.push((module.name.clone(), interface_of(module)));
}
});
out
}
/// One unit's surface, or `None` when its header is not fully visible.
fn interface_of(module: &Module) -> Option<ModuleInterface> {
// A directive written *between* ports or parameters may be a conditional
// — whose arms are all in the list, so the list stays a superset — or a
// macro invocation standing where a port belongs, whose expansion lucisv
// never sees. Telling the two apart would be a second preprocessor; a
// header with any directive in it is simply not answered for.
if !module.port_directives.is_empty() || !module.param_directives.is_empty() {
return None;
}
Some(ModuleInterface { ports: ports_of(module), parameters: parameters_of(module) })
}
/// The port names of either header style. A header with no port list at all
/// declares none, which is a fact rather than a gap: nothing may be connected
/// to it by name.
fn ports_of(module: &Module) -> Vec<String> {
match &module.ports {
PortList::Ansi(ports) => {
ports.iter().filter_map(ListElem::ok).map(|port| port.name.clone()).collect()
}
PortList::NonAnsi(ports) => {
ports.iter().filter_map(ListElem::ok).map(|port| port.name.clone()).collect()
}
PortList::None | PortList::Empty => Vec::new(),
}
}
/// The names an `#(.NAME(value))` override may write: every `parameter` in the
/// header and in the body.
///
/// A `localparam` is **not** one — it is the module's own constant and is not
/// overridable (IEEE 1800 §6.20.4), which is exactly the distinction
/// `SymbolKind::LocalParam` was parted out for. A header parameter written
/// without a keyword continues the previous declaration and inherits its
/// keyword, which is how `#(parameter int A = 1, B = 2)` declares two
/// overridable parameters.
fn parameters_of(module: &Module) -> Vec<String> {
let mut out = Vec::new();
let mut overridable = true;
for port in module.param_ports.iter().flatten().filter_map(ListElem::ok) {
overridable = is_parameter(port, overridable);
if overridable {
out.push(port.name.clone());
}
}
for item in &module.items {
if let ItemKind::ParamDecl(decl) = &item.kind {
if decl.kw == "parameter" {
out.extend(decl.declarators.iter().map(|d| d.name.clone()));
}
}
}
out
}
/// Whether this header parameter is overridable, given whether the one before
/// it was: a written keyword decides, and no keyword continues.
fn is_parameter(port: &ParamPort, previous: bool) -> bool {
match port.kw.as_deref() {
Some("localparam") => false,
Some(_) => true,
None => previous,
}
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::parse_source_tolerant;
fn interfaces(src: &str) -> Vec<(String, Option<ModuleInterface>)> {
let (file, _) = parse_source_tolerant(src);
module_interfaces(&file)
}
fn only(src: &str) -> ModuleInterface {
let found = interfaces(src);
assert_eq!(found.len(), 1, "{found:?}");
found.into_iter().next().and_then(|(_, i)| i).expect("a readable header")
}
#[test]
fn reads_an_ansi_header() {
let read = only(
"module m #(parameter int Width = 8, localparam int Derived = Width + 1) (\n\
input logic clk_i,\n\
output logic [7:0] data_o\n\
);\n\
endmodule\n",
);
assert_eq!(read.ports, vec!["clk_i", "data_o"]);
assert_eq!(read.parameters, vec!["Width"], "a localparam is not overridable");
}
#[test]
fn reads_a_non_ansi_header() {
let read = only("module m (clk, rst_n);\n input clk;\n input rst_n;\nendmodule\n");
assert_eq!(read.ports, vec!["clk", "rst_n"]);
}
#[test]
fn a_continuation_parameter_inherits_its_keyword() {
let read = only("module m #(parameter int A = 1, B = 2) ();\nendmodule\n");
assert_eq!(read.parameters, vec!["A", "B"]);
let local = only("module m #(localparam int A = 1, B = 2) ();\nendmodule\n");
assert!(local.parameters.is_empty(), "both continue the localparam");
}
#[test]
fn a_body_parameter_is_overridable_and_a_body_localparam_is_not() {
let read =
only("module m ();\n parameter int Depth = 4;\n localparam int W = 2;\nendmodule\n");
assert_eq!(read.parameters, vec!["Depth"]);
}
#[test]
fn a_header_with_a_directive_in_it_is_unknowable() {
let src = "module m (\n\
`ifdef X\n\
input logic a,\n\
`endif\n\
input logic b\n\
);\n\
endmodule\n";
assert_eq!(interfaces(src), vec![("m".to_string(), None)]);
}
#[test]
fn a_port_less_module_declares_no_ports() {
let read = only("module m;\nendmodule\n");
assert!(read.ports.is_empty());
assert!(read.parameters.is_empty());
let empty = only("module m ();\nendmodule\n");
assert!(empty.ports.is_empty());
}
#[test]
fn an_interface_is_read_the_same_way() {
let read = only("interface bus_if (input logic clk);\nendinterface\n");
assert_eq!(read.ports, vec!["clk"]);
}
#[test]
fn every_unit_of_a_file_is_returned() {
let found = interfaces("module a ();\nendmodule\nmodule b ();\nendmodule\n");
assert_eq!(found.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(), vec!["a", "b"]);
}
}
+57 -4
View File
@@ -21,26 +21,42 @@
//! `docs/features/linter-core/README.md`.
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;
mod severity;
mod signals;
mod violation;
mod visit;
mod vscode;
mod waiver;
use std::path::PathBuf;
pub use context::{LintContext, MentionOracle, ParsedSource};
pub use registry::{all_rules, default_rules, rule_by_name, select_rules, workspace_rules, Rule};
pub use context::{LintContext, MentionOracle, ModuleInterface, ParsedSource};
pub use interfaces::module_interfaces;
pub use options::{OptionDefault, OptionKind, OptionSpec, OptionValue, RuleOptions};
pub use registry::{
all_rules, default_rules, rule_by_name, rules_named, select_rules, workspace_rules, Rule,
};
pub use rule_docs::rules_markdown;
pub use severity::Severity;
pub use violation::{apply_fixes, Applicability, Fix, Fixed, Violation};
/// The identifier census a [`MentionOracle`] is answered from, re-exported
/// from `vlog_semantic` so a front end that implements the oracle needs this
/// crate alone. One harvest for the whole workspace — see
/// `docs/features/semantic-lints-on/README.md`.
pub use vlog_semantic::words;
pub use vscode::{rule_setting, severity_setting, vscode_lint_settings, RULE_CHOICES};
pub use waiver::UNUSED_WAIVER;
use waiver::Waivers;
@@ -87,9 +103,24 @@ pub fn lint(ctx: &LintContext, enabled: &[&'static dyn Rule]) -> Vec<Violation>
kept.sort_by(|a, b| {
(a.span.start, a.span.end, a.rule).cmp(&(b.span.start, b.span.end, b.rule))
});
stamp_severities(&mut kept);
kept
}
/// Gives every finding the class its rule declares.
///
/// One place rather than one per rule: a rule's `check` builds violations
/// without knowing what it is called, the `unused-waiver` findings are built by
/// the waiver scanner and not by a rule at all, and a severity written twice
/// would eventually be written differently. See [`Violation::severity`].
fn stamp_severities(violations: &mut [Violation]) {
for violation in violations {
if let Some(rule) = rule_by_name(violation.rule) {
violation.severity = rule.severity();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -172,11 +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]);
}
@@ -211,6 +243,27 @@ mod tests {
assert!(run(src, None, &enabled).is_empty());
}
/// Every finding the runner returns carries its rule's class — including
/// the `unused-waiver` ones, which no rule's `check` produced.
#[test]
fn the_runner_stamps_every_finding_with_its_rules_severity() {
let src = "module m;\n\
\treg a; // lucisv: waive no-such-rule\n\
\talways_comb a <= 1'b0;\n\
endmodule\n";
let found = run(src, Some(PathBuf::from("rtl/m.sv")), &default_rules());
assert!(found.len() >= 3, "{found:#?}");
for violation in &found {
let rule = rule_by_name(violation.rule).expect("a registered rule");
assert_eq!(violation.severity, rule.severity(), "{}", violation.rule);
}
let by_rule =
|name: &str| found.iter().find(|v| v.rule == name).map(|v| v.severity).expect(name);
assert_eq!(by_rule("wire-reg-mixup"), Severity::Error);
assert_eq!(by_rule("always-comb-blocking"), Severity::Warning);
assert_eq!(by_rule(UNUSED_WAIVER), Severity::Style);
}
#[test]
fn a_file_that_does_not_parse_still_gets_its_text_rules() {
let src = "module m;\n\t@@@ this is not verilog\nendmodule\n";
+156
View File
@@ -0,0 +1,156 @@
//! Sized based literals, read the way the two width rules need them.
//!
//! `truncated-numeric-literal` asks "how many bits does what is written
//! actually need?" and `undersized-binary-literal` asks "how many digits were
//! written?". Both questions are about the same `<size>'<base><digits>` shape,
//! so it is parsed once here rather than twice, slightly differently.
/// One `<size>'[s]<base><digits>` literal, as written.
///
/// Only the *sized* spelling is modelled: an unsized `'h1f` takes its width
/// from context, so neither rule has anything to compare against and
/// [`parse`] returns `None` for it.
pub(crate) struct SizedLiteral<'a> {
/// The declared width, in bits.
pub width: u32,
/// The base letter, lower-cased: `b`, `o`, `d` or `h`.
pub base: char,
/// The digits as written, `_` separators included.
pub digits: &'a str,
}
impl SizedLiteral<'_> {
/// The digits with the `_` separators taken out.
pub fn packed_digits(&self) -> String {
self.digits.chars().filter(|c| *c != '_').collect()
}
/// How many bits the written value really needs, or `None` when that
/// cannot be said: an empty or malformed digit run, or a decimal value
/// carrying `x`/`z`.
///
/// A digit that is `x`, `z` or `?` counts as full-width — `4'hxF` needs
/// eight bits, because the unknown nibble is still a nibble.
pub fn significant_bits(&self) -> Option<u32> {
let digits = self.packed_digits();
let digits = digits.trim_start_matches('0');
if digits.is_empty() {
return Some(0);
}
let Some(per_digit) = bits_per_digit(self.base) else {
// Decimal: the whole run is one number, so an `x` in it makes the
// value unknown rather than one unknown digit.
let value: u128 = digits.parse().ok()?;
return Some(128 - value.leading_zeros());
};
let mut chars = digits.chars();
let first = chars.next()?;
let rest = chars.count() as u32;
let head = match first.to_ascii_lowercase() {
'x' | 'z' | '?' => per_digit,
c => bits_of(c, self.base)?,
};
Some(rest * per_digit + head)
}
}
/// Reads a sized based literal, or `None` for anything else — an unsized
/// literal, a plain decimal, a real, a time literal.
pub(crate) fn parse(text: &str) -> Option<SizedLiteral<'_>> {
let (size, rest) = text.split_once('\'')?;
let width: u32 = size.chars().filter(|c| *c != '_').collect::<String>().parse().ok()?;
// `8'sh1f` — the signedness marker sits between the tick and the base.
let rest = rest.strip_prefix(['s', 'S']).unwrap_or(rest);
let mut chars = rest.chars();
let base = chars.next()?.to_ascii_lowercase();
if !matches!(base, 'b' | 'o' | 'd' | 'h') {
return None;
}
let digits = rest.get(1..)?;
if digits.is_empty() || !digits.chars().all(|c| is_digit_of(c, base) || c == '_') {
return None;
}
Some(SizedLiteral { width, base, digits })
}
/// How many bits one digit of `base` carries; `None` for decimal, which is not
/// a per-digit base at all.
fn bits_per_digit(base: char) -> Option<u32> {
match base {
'b' => Some(1),
'o' => Some(3),
'h' => Some(4),
_ => None,
}
}
/// How many bits one known digit's value needs (`7` needs three, `1` needs
/// one), or `None` when the character is not a digit of this base.
fn bits_of(c: char, base: char) -> Option<u32> {
let value = c.to_digit(16)?;
let per_digit = bits_per_digit(base)?;
if value >= 1 << per_digit {
return None;
}
Some(32 - value.leading_zeros())
}
/// True when `c` may stand among `base`'s digits, unknowns included.
fn is_digit_of(c: char, base: char) -> bool {
let c = c.to_ascii_lowercase();
if matches!(c, 'x' | 'z' | '?') {
return true;
}
match base {
'b' => matches!(c, '0' | '1'),
'o' => c.is_digit(8),
'd' => c.is_ascii_digit(),
_ => c.is_ascii_hexdigit(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn bits(text: &str) -> Option<u32> {
parse(text)?.significant_bits()
}
#[test]
fn a_sized_literal_is_read_in_every_base() {
for (text, width, base, digits) in [
("8'hFF", 8, 'h', "FF"),
("4'b1010", 4, 'b', "1010"),
("3'o7", 3, 'o', "7"),
("16'd1000", 16, 'd', "1000"),
("8'sh1f", 8, 'h', "1f"),
("32'hdead_beef", 32, 'h', "dead_beef"),
] {
let found = parse(text).unwrap_or_else(|| panic!("{text}"));
assert_eq!((found.width, found.base, found.digits), (width, base, digits), "{text}");
}
}
#[test]
fn anything_that_is_not_a_sized_based_literal_is_declined() {
for text in ["'h1f", "42", "1.5", "10ns", "8'", "8'q1", "8'h", "8'hG", "'0"] {
assert!(parse(text).is_none(), "{text}");
}
}
#[test]
fn significant_bits_counts_what_is_written() {
assert_eq!(bits("4'h0"), Some(0));
assert_eq!(bits("4'h1"), Some(1));
assert_eq!(bits("4'h8"), Some(4));
assert_eq!(bits("4'hFFF"), Some(12), "three full nibbles");
assert_eq!(bits("8'b0000_0001"), Some(1), "leading zeros do not count");
assert_eq!(bits("4'o7"), Some(3));
assert_eq!(bits("8'd255"), Some(8));
assert_eq!(bits("8'd256"), Some(9));
assert_eq!(bits("4'hx"), Some(4), "an unknown nibble is still a nibble");
assert_eq!(bits("4'h0x"), Some(4), "and leading zeros still do not count");
assert_eq!(bits("8'dx"), None, "a decimal unknown says nothing about width");
}
}
+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());
}
}
+266 -11
View File
@@ -1,7 +1,9 @@
//! The rule trait and the table of rules that exist.
use crate::context::LintContext;
use crate::options::OptionSpec;
use crate::rules;
use crate::severity::Severity;
use crate::violation::{Applicability, Violation};
/// One lint rule.
@@ -17,6 +19,14 @@ pub trait Rule: Sync {
/// One line, imperative, no trailing period.
fn summary(&self) -> &'static str;
/// How bad this rule's findings are.
///
/// Deliberately without a default: a class is a claim about what a finding
/// means to the user, and a rule that inherited one silently would be
/// making that claim by accident. The reason for the class chosen belongs
/// in [`Rule::doc`].
fn severity(&self) -> Severity;
/// Why the rule exists — the style-guide rationale, in prose.
fn doc(&self) -> &'static str;
@@ -50,6 +60,18 @@ pub trait Rule: Sync {
None
}
/// What a user may configure about this rule, or nothing.
///
/// The keys are Verible's wherever it has the same option, so a project
/// migrating a `.rules.verible` file types the same words. A rule reads
/// one through [`LintContext`], never from a run's settings directly, and
/// always gets a value: the spec's default is the fallback, so there is no
/// "unset" case in any rule. See
/// `docs/features/linter-expansion-2/README.md`.
fn options(&self) -> &'static [OptionSpec] {
&[]
}
/// Everything this rule finds in one file.
fn check(&self, ctx: &LintContext) -> Vec<Violation>;
}
@@ -57,22 +79,78 @@ 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,
&rules::module_port::ModulePort,
&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,
]
}
@@ -112,10 +190,25 @@ pub fn rule_by_name(name: &str) -> Option<&'static dyn Rule> {
all_rules().into_iter().find(|rule| rule.name() == name)
}
/// The rules one `--select` / `--ignore` name stands for.
///
/// A rule name stands for itself; a **severity name** (`error`, `warning`,
/// `style`) stands for every rule of that class, so `--ignore style` is one
/// word for the whole family. `None` for a name that is neither, which is what
/// makes a typo a failed run rather than a silently empty selection.
pub fn rules_named(name: &str) -> Option<Vec<&'static dyn Rule>> {
if let Some(rule) = rule_by_name(name) {
return Some(vec![rule]);
}
let severity = Severity::from_name(name)?;
Some(all_rules().into_iter().filter(|rule| rule.severity() == severity).collect())
}
/// The rules a run should use: `select` replaces the default set (empty means
/// keep it), then `ignore` removes from whatever is left. An unknown name on
/// either list is an error rather than a silent no-op — a typo'd `--select`
/// that quietly ran everything would be worse than a failed run.
/// keep it), then `ignore` removes from whatever is left. Either list may name
/// a rule or a whole severity ([`rules_named`]). An unknown name on either
/// list is an error rather than a silent no-op — a typo'd `--select` that
/// quietly ran everything would be worse than a failed run.
///
/// `workspace` only reaches [`default_rules`]: an explicit `select` names the
/// rules it wants and gets them, oracle or no oracle, exactly as an explicit
@@ -128,25 +221,27 @@ pub fn select_rules(
let mut chosen = if select.is_empty() {
enabled_rules(workspace)
} else {
let mut chosen = Vec::new();
let mut chosen: Vec<&'static dyn Rule> = Vec::new();
for name in select {
let rule = rule_by_name(name).ok_or_else(|| unknown(name))?;
if !chosen.iter().any(|r: &&'static dyn Rule| r.name() == rule.name()) {
chosen.push(rule);
for rule in rules_named(name).ok_or_else(|| unknown(name))? {
if !chosen.iter().any(|r| r.name() == rule.name()) {
chosen.push(rule);
}
}
}
chosen
};
for name in ignore {
rule_by_name(name).ok_or_else(|| unknown(name))?;
chosen.retain(|rule| rule.name() != name);
let dropped = rules_named(name).ok_or_else(|| unknown(name))?;
chosen.retain(|rule| !dropped.iter().any(|d| d.name() == rule.name()));
}
Ok(chosen)
}
fn unknown(name: &str) -> String {
let known = all_rules().iter().map(|r| r.name()).collect::<Vec<_>>().join(", ");
format!("unknown rule: {name} (known rules: {known})")
let severities = Severity::ALL.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
format!("unknown rule: {name} (severities: {severities}; known rules: {known})")
}
#[cfg(test)]
@@ -211,7 +306,17 @@ mod tests {
let project: Vec<&str> = workspace_rules().iter().map(|r| r.name()).collect();
let added: Vec<&str> =
project.iter().copied().filter(|name| !alone.contains(name)).collect();
assert_eq!(added, vec!["multiply-driven", "undriven-net", "unused-signal"]);
assert_eq!(
added,
vec![
"multiply-driven",
"undeclared-identifier",
"undriven-net",
"unknown-parameter",
"unknown-port",
"unused-signal",
]
);
assert!(alone.iter().all(|name| project.contains(name)), "a workspace never removes one");
for rule in all_rules() {
assert_eq!(rule.needs_workspace(), added.contains(&rule.name()), "{}", rule.name());
@@ -283,6 +388,156 @@ mod tests {
assert!(message.contains("no-tabs"), "the error must list what is known: {message}");
}
/// Every rule states a class, and no rule name collides with a class
/// name — otherwise `--select error` would mean two things.
#[test]
fn every_rule_has_a_severity_and_no_name_shadows_a_class() {
for rule in all_rules() {
assert!(Severity::ALL.contains(&rule.severity()), "{}", rule.name());
assert!(
Severity::from_name(rule.name()).is_none(),
"{} shadows a severity word",
rule.name()
);
}
}
/// The assignments §33.0 wrote down for the seventeen rules that predate
/// severities. A rule moving class is a user-visible change, so it moves
/// here first.
#[test]
fn the_original_seventeen_keep_the_classes_they_were_given() {
let expected: &[(&str, Severity)] = &[
("multiply-driven", Severity::Error),
("wire-reg-mixup", Severity::Error),
("always-comb-blocking", Severity::Warning),
("always-ff-non-blocking", Severity::Warning),
("case-missing-default", Severity::Warning),
("undriven-net", Severity::Warning),
("unused-signal", Severity::Warning),
("empty-item", Severity::Style),
("enum-name-style", Severity::Style),
("explicit-parameter-storage-type", Severity::Style),
("module-filename", Severity::Style),
("module-name-style", Severity::Style),
("no-tabs", Severity::Style),
("no-trailing-whitespace", Severity::Style),
("parameter-name-style", Severity::Style),
("struct-union-name-style", Severity::Style),
("unused-waiver", Severity::Style),
];
for (name, severity) in expected {
let rule = rule_by_name(name).unwrap_or_else(|| panic!("{name} exists"));
assert_eq!(rule.severity(), *severity, "{name}");
}
}
#[test]
fn a_severity_name_stands_for_every_rule_of_that_class() {
for severity in Severity::ALL {
let named = rules_named(severity.as_str()).unwrap_or_default();
let expected: Vec<&str> = all_rules()
.into_iter()
.filter(|rule| rule.severity() == severity)
.map(|rule| rule.name())
.collect();
assert_eq!(named.iter().map(|r| r.name()).collect::<Vec<_>>(), expected);
assert!(!expected.is_empty(), "{severity:?} has no rules");
}
assert!(rules_named("no-tabs").is_some_and(|rules| rules.len() == 1));
assert!(rules_named("no-such-thing").is_none());
}
/// `--select style`, `--ignore warning`: the whole point of the words.
#[test]
fn select_and_ignore_accept_a_severity_wherever_a_rule_fits() {
let styled = select_rules(&["style".to_string()], &[], true).unwrap();
assert!(styled.iter().all(|rule| rule.severity() == Severity::Style));
assert!(styled.iter().any(|rule| rule.name() == "no-tabs"));
let quiet = select_rules(&[], &["style".to_string()], true).unwrap();
assert!(quiet.iter().all(|rule| rule.severity() != Severity::Style));
assert!(quiet.iter().any(|rule| rule.name() == "unused-signal"), "warnings survive");
// A severity and a rule name mix on one list, and the same rule named
// twice is still selected once.
let mixed =
select_rules(&["style".to_string(), "no-tabs".to_string()], &[], false).unwrap();
assert_eq!(mixed.iter().filter(|rule| rule.name() == "no-tabs").count(), 1);
// Ignoring a class removes it from an explicit selection too.
let none = select_rules(&["no-tabs".to_string()], &["style".to_string()], false).unwrap();
assert!(none.is_empty());
}
#[test]
fn the_unknown_name_error_names_the_severity_words_too() {
let message = select_rules(&["styles".to_string()], &[], false).err().unwrap_or_default();
assert!(message.contains("style"), "{message}");
assert!(message.contains("no-tabs"), "{message}");
}
/// Every option a rule declares is one a user could actually write down,
/// and one whose own default is acceptable to itself — a default outside
/// its range, or a pattern that does not compile, would be a rule nobody
/// could satisfy.
#[test]
fn every_declared_option_is_well_formed() {
use crate::options::{OptionKind, RuleOptions};
for rule in all_rules() {
let mut names: Vec<&str> = rule.options().iter().map(|spec| spec.name).collect();
let count = names.len();
names.sort_unstable();
names.dedup();
assert_eq!(names.len(), count, "{}: duplicate option names", rule.name());
for spec in rule.options() {
let where_ = format!("{}.{}", rule.name(), spec.name);
assert!(
spec.name.chars().all(|c| c.is_ascii_lowercase()
|| c.is_ascii_digit()
|| c == '_'
|| c == '-'),
"{where_}: option names are lower-case words",
);
assert!(spec.doc.len() > 10, "{where_}: doc too thin");
assert!(!spec.doc.ends_with('.'), "{where_}: doc ends in a period");
let mut options = RuleOptions::new();
options
.set(rule.name(), spec.name, spec.default.value())
.unwrap_or_else(|e| panic!("{where_}: its own default is refused: {e}"));
if let OptionKind::Int { min, max } = spec.kind {
assert!(min <= max, "{where_}: empty range");
}
}
}
}
/// The options §34 gave the four naming rules that predate them, spelled
/// as Verible spells the same options.
#[test]
fn the_naming_rules_take_the_options_verible_gives_them() {
let names = |rule: &str| {
rule_by_name(rule)
.unwrap_or_else(|| panic!("{rule} exists"))
.options()
.iter()
.map(|spec| spec.name)
.collect::<Vec<_>>()
};
assert_eq!(names("enum-name-style"), vec!["style_regex"]);
assert_eq!(names("struct-union-name-style"), vec!["style_regex"]);
assert_eq!(names("module-name-style"), vec!["style_regex"]);
assert_eq!(
names("parameter-name-style"),
vec![
"localparam_style",
"localparam_style_regex",
"parameter_style",
"parameter_style_regex"
]
);
}
#[test]
fn lookup_by_name_finds_every_rule_and_nothing_else() {
for rule in all_rules() {
+161 -19
View File
@@ -6,7 +6,10 @@
//! per rule. If a rule exists, it is in here; if its `doc` changes, so does
//! this.
use crate::options::OptionKind;
use crate::registry::all_rules;
use crate::severity::Severity;
use crate::Rule;
/// The whole rule reference as one markdown document.
pub fn rules_markdown() -> String {
@@ -15,6 +18,12 @@ pub fn rules_markdown() -> String {
out.push_str(
"Generated from the rule registry by `vlog_linter::rules_markdown` — \
do not edit by hand.\n\n\
Every rule is in one of three **severity** classes, and the class is \
a word `--select` and `--ignore` accept wherever a rule name fits \
(`--ignore style`, `--select error`). **error** is code that would \
very likely fail to compile, elaborate or synthesize; **warning** is \
code that compiles but very likely does not mean what it says; \
**style** is code that is correct and reads badly.\n\n\
A rule marked **on** runs for a plain `lucisv check`; the others need \
`--select <name>`. A rule marked **on (project)** runs by default \
only where lucisv can see the other files of the project — \
@@ -23,30 +32,78 @@ pub fn rules_markdown() -> String {
a stdin buffer it is off and must be selected. Any rule can be turned \
off with `--ignore <name>`, with `ignore` under `[lint]` in \
`lucisv.toml`, or waived in the source with `// lucisv: waive \
<name>`.\n\n",
<name>`.\n\n\
A rule with **options** is configured in a `[lint.<rule-name>]` \
table of a `lucisv.toml`, or from an editor with \
`lucisv.lint.options`; an option nobody sets reads the default \
listed with it. An unknown option name, a value of the wrong kind, \
an integer out of range and a pattern that does not compile are all \
refused, naming the file and the line.\n\n",
);
out.push_str("| Rule | Default | Fix |\n|---|---|---|\n");
out.push_str("| Rule | Severity | Default | Fix |\n|---|---|---|---|\n");
for rule in all_rules() {
out.push_str(&format!(
"| [`{name}`](#{name}) | {default} | {fix} |\n",
"| [`{name}`](#{name}) | {severity} | {default} | {fix} |\n",
name = rule.name(),
severity = rule.severity().as_str(),
default = default_word(rule),
fix = fix_word(rule),
));
}
out.push('\n');
for rule in all_rules() {
out.push_str(&format!("## {}\n\n", rule.name()));
out.push_str(&format!("{}.\n\n", capitalize(rule.summary())));
out.push_str(&format!("- Default: {}\n- Fix: {}\n\n", default_word(rule), fix_word(rule)));
out.push_str(rule.doc());
out.push_str("\n\n");
for severity in Severity::ALL {
out.push_str(&format!("# {} — {}\n\n", severity.as_str(), severity.describes()));
for rule in all_rules().into_iter().filter(|rule| rule.severity() == severity) {
out.push_str(&format!("## {}\n\n", rule.name()));
out.push_str(&format!("{}.\n\n", capitalize(rule.summary())));
out.push_str(&format!(
"- Severity: {}\n- Default: {}\n- Fix: {}\n\n",
severity.as_str(),
default_word(rule),
fix_word(rule),
));
out.push_str(rule.doc());
out.push_str("\n\n");
out.push_str(&options_table(rule));
}
}
out
}
/// A rule's options, as a small table under its prose — empty for a rule
/// that takes none, which is most of them.
fn options_table(rule: &dyn Rule) -> String {
if rule.options().is_empty() {
return String::new();
}
let mut out = String::from("| Option | Kind | Default | Meaning |\n|---|---|---|---|\n");
for spec in rule.options() {
out.push_str(&format!(
"| `{name}` | {kind} | `{default}` | {doc} |\n",
name = spec.name,
kind = kind_word(spec.kind),
default = spec.default.as_written(),
doc = spec.doc,
));
}
out.push('\n');
out
}
/// How the reference spells an option's kind, a `Words` option's vocabulary
/// included — a user cannot guess `CamelCase|ALL_CAPS` from "word list".
fn kind_word(kind: OptionKind) -> String {
match kind {
OptionKind::Int { min, max } => format!("integer {min}–{max}"),
OptionKind::Words(vocabulary) => {
format!("one or more of {} joined with `\\|`", vocabulary.join(", "))
}
other => other.as_str().to_string(),
}
}
/// How the table spells a rule's default: on, off, or on wherever there is a
/// project to ask about ([`crate::Rule::needs_workspace`]).
fn default_word(rule: &dyn crate::Rule) -> &'static str {
@@ -98,7 +155,7 @@ mod tests {
fn the_index_lists_every_rule_once() {
let markdown = rules_markdown();
for rule in all_rules() {
let row = format!("| [`{0}`](#{0}) |", rule.name());
let row = format!("| [`{0}`](#{0}) | ", rule.name());
assert_eq!(markdown.matches(&row).count(), 1, "{}", rule.name());
}
}
@@ -106,27 +163,96 @@ mod tests {
#[test]
fn defaults_and_fixes_are_rendered_from_the_registry() {
let markdown = rules_markdown();
assert!(markdown.contains("| [`no-tabs`](#no-tabs) | **on** | safe |"));
assert!(markdown.contains("| [`module-name-style`](#module-name-style) | off | none |"));
assert!(markdown.contains("| [`no-tabs`](#no-tabs) | style | **on** | safe |"));
assert!(
markdown.contains("| [`module-name-style`](#module-name-style) | style | off | none |")
);
// The three semantic rules are fixless, and default on exactly where
// there is a project to ask about a name — see
// docs/features/semantic-lints-on/README.md.
for name in ["multiply-driven", "undriven-net", "unused-signal"] {
for (name, severity) in [
("multiply-driven", "error"),
("undriven-net", "warning"),
("unused-signal", "warning"),
] {
assert!(
markdown.contains(&format!("| [`{name}`](#{name}) | **on (project)** | none |")),
markdown.contains(&format!(
"| [`{name}`](#{name}) | {severity} | **on (project)** | none |"
)),
"{name}"
);
}
assert_eq!(fix_word(&crate::rules::no_tabs::NoTabs), Applicability::Safe.as_str());
}
/// Every rule sits under the heading of its own class, and the three
/// headings are written worst-first.
#[test]
fn the_sections_are_grouped_by_severity() {
let markdown = rules_markdown();
let heading = |severity: Severity| {
markdown
.find(&format!("\n# {} — ", severity.as_str()))
.unwrap_or_else(|| panic!("{severity:?} heading"))
};
let (error, warning, style) =
(heading(Severity::Error), heading(Severity::Warning), heading(Severity::Style));
assert!(error < warning && warning < style, "worst first");
for rule in all_rules() {
let at = markdown
.find(&format!("\n## {}\n", rule.name()))
.unwrap_or_else(|| panic!("{}", rule.name()));
let own = heading(rule.severity());
let next = [error, warning, style]
.into_iter()
.filter(|start| *start > own)
.min()
.unwrap_or(markdown.len());
assert!(own < at && at < next, "{} is under the wrong heading", rule.name());
}
}
/// Every option a rule declares is in the reference, with the default a
/// run that configures nothing actually reads.
#[test]
fn every_option_is_listed_with_its_kind_and_default() {
let markdown = rules_markdown();
for rule in all_rules() {
for spec in rule.options() {
assert!(
markdown.contains(&format!("| `{}` |", spec.name)),
"{}.{}",
rule.name(),
spec.name
);
assert!(markdown.contains(spec.doc), "{}.{}: doc", rule.name(), spec.name);
}
}
assert!(markdown.contains("| `length` | integer 40–400 | `100` |"), "line-length");
assert!(
markdown.contains("| `prefix` | list of strings | `[\"g_\", \"gen_\"]` |"),
"generate-label-prefix"
);
assert!(
markdown.contains("one or more of CamelCase, ALL_CAPS joined with"),
"parameter-name-style's vocabulary"
);
// A rule with no options gets no table.
let no_tabs = markdown
.split("## no-tabs\n")
.nth(1)
.and_then(|rest| rest.split("\n## ").next())
.unwrap_or_default();
assert!(!no_tabs.contains("| Option |"), "{no_tabs}");
}
#[test]
fn the_document_shape_is_pinned() {
// A golden test on the *shape*, not on the prose: the heading, the
// generated-by note, the index table header, and the first per-rule
// section, which together are what a reader (and any renderer) sees.
let markdown = rules_markdown();
let head: Vec<&str> = markdown.lines().take(8).collect();
let head: Vec<&str> = markdown.lines().take(12).collect();
assert_eq!(
head,
vec![
@@ -135,6 +261,12 @@ mod tests {
"Generated from the rule registry by `vlog_linter::rules_markdown` — do not edit \
by hand.",
"",
"Every rule is in one of three **severity** classes, and the class is a word \
`--select` and `--ignore` accept wherever a rule name fits (`--ignore style`, \
`--select error`). **error** is code that would very likely fail to compile, \
elaborate or synthesize; **warning** is code that compiles but very likely does \
not mean what it says; **style** is code that is correct and reads badly.",
"",
"A rule marked **on** runs for a plain `lucisv check`; the others need \
`--select <name>`. A rule marked **on (project)** runs by default only where \
lucisv can see the other files of the project — `lucisv check <dir>`, or the \
@@ -143,18 +275,28 @@ mod tests {
rule can be turned off with `--ignore <name>`, with `ignore` under `[lint]` in \
`lucisv.toml`, or waived in the source with `// lucisv: waive <name>`.",
"",
"| Rule | Default | Fix |",
"|---|---|---|",
"A rule with **options** is configured in a `[lint.<rule-name>]` table of a \
`lucisv.toml`, or from an editor with `lucisv.lint.options`; an option nobody \
sets reads the default listed with it. An unknown option name, a value of the \
wrong kind, an integer out of range and a pattern that does not compile are \
all refused, naming the file and the line.",
"",
"| Rule | Severity | Default | Fix |",
"|---|---|---|---|",
]
);
let first_rule = all_rules()[0];
let first_rule = all_rules()
.into_iter()
.find(|rule| rule.severity() == Severity::Error)
.expect("some rule is an error");
let section = format!(
"## {}\n\n{}.\n\n- Default: {}\n- Fix: {}\n\n{}\n\n",
"## {}\n\n{}.\n\n- Severity: error\n- Default: {}\n- Fix: {}\n\n{}\n\n{}",
first_rule.name(),
capitalize(first_rule.summary()),
default_word(first_rule),
fix_word(first_rule),
first_rule.doc(),
options_table(first_rule),
);
assert!(markdown.contains(&section), "per-rule section shape changed:\n{section}");
assert!(markdown.ends_with("\n\n"));
+164
View File
@@ -0,0 +1,164 @@
//! `always-comb` — write combinational logic as `always_comb`.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use crate::visit::walk_items;
use vlog_parser::ast::{ItemKind, SensList, StmtKind, TimingControl};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct AlwaysComb;
const NAME: &str = "always-comb";
impl Rule for AlwaysComb {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"write `always_comb` instead of `always @*`"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"`always_comb` says what the block is *for*, and the language checks \
the claim: the tool errors if anything else drives one of its \
left-hand sides, and it infers the sensitivity list including the \
functions the block calls — which `always @*` does not. Verible's \
`always-comb` (enabled by default) asks for the SystemVerilog \
spelling wherever `always @*` or `always @(*)` is written, and lucisv \
checks the same thing.\n\n\
The fix is offered but **unsafe**, and the reason is real: an \
`always_comb` block runs once at time zero and an `always @*` block \
does not run until something in its sensitivity list changes, so a \
testbench that samples before the first change can see a different \
value. It also becomes an error for the block's outputs to be driven \
anywhere else, which is usually the bug being found but is still a \
change in what compiles. `--unsafe-fixes` applies it; the edit is the \
keyword and its `@(*)`, nothing else."
}
fn fix(&self) -> Option<Applicability> {
Some(Applicability::Unsafe)
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::Always { kw, stmt } = &item.kind else { return };
if kw != "always" {
return;
}
let StmtKind::Timing { control: TimingControl::Event(sens), stmt: Some(body) } =
&stmt.kind
else {
return;
};
if !matches!(sens, SensList::Star { .. }) {
return;
}
let Some(header) = header_span(ctx, item.span.start, body.span.start) else { return };
out.push(
Violation::new(NAME, "use `always_comb` instead of `always @*`", header)
.with_fix(Fix::unsafe_fix(vec![(header, "always_comb".to_string())])),
);
});
out
}
}
/// The `always @(*)` in front of the body: from the keyword to the end of the
/// last token before the body starts.
///
/// Read off the tokens rather than assumed, because the sensitivity control
/// may be written `@*`, `@ (*)` or `@( /* why */ * )`, and the fix must
/// replace exactly what was written and not a byte more.
fn header_span(ctx: &LintContext, start: u32, body: u32) -> Option<TextRange> {
let end = ctx
.tokens()
.iter()
.filter(|token| token.span.start >= start && token.span.end <= body)
.map(|token| token.span.end)
.max()?;
(end > start).then(|| TextRange::new(start, end))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::violation::apply_fixes;
fn violations(src: &str) -> Vec<Violation> {
AlwaysComb.check(&LintContext::new(src, None))
}
#[test]
fn flags_both_spellings_and_rewrites_only_the_header() {
for src in [
"module m;\n always @(*) x = 1;\nendmodule\n",
"module m;\n always @* x = 1;\nendmodule\n",
] {
let found = violations(src);
assert_eq!(found.len(), 1, "{src}");
let fixed = apply_fixes(src, &found, true);
assert_eq!(fixed.output, "module m;\n always_comb x = 1;\nendmodule\n", "{src}");
}
}
#[test]
fn the_fix_is_unsafe() {
let src = "module m;\n always @(*) x = 1;\nendmodule\n";
let found = violations(src);
assert_eq!(found[0].fix.as_ref().map(|f| f.applicability), Some(Applicability::Unsafe));
assert_eq!(apply_fixes(src, &found, false).applied, 0, "not without --unsafe-fixes");
}
#[test]
fn a_multi_line_block_keeps_its_layout() {
let src = "module m;\n always @(*) begin\n x = 1;\n end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1);
assert_eq!(
apply_fixes(src, &found, true).output,
"module m;\n always_comb begin\n x = 1;\n end\nendmodule\n"
);
}
#[test]
fn a_comment_inside_the_control_is_replaced_with_it() {
// The whole header is one edit, so a comment written inside `@( * )`
// goes with it — which is why the fix is offered, not applied.
let src = "module m;\n always @( /* all */ * ) x = 1;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1);
assert_eq!(
apply_fixes(src, &found, true).output,
"module m;\n always_comb x = 1;\nendmodule\n"
);
}
#[test]
fn an_explicit_sensitivity_list_is_none_of_its_business() {
for src in [
"module m;\n always @(a or b) x = 1;\nendmodule\n",
"module m;\n always @(posedge clk) q <= d;\nendmodule\n",
"module m;\n always_comb x = 1;\nendmodule\n",
"module m;\n always_ff @(posedge clk) q <= d;\nendmodule\n",
"module m;\n always @(*);\nendmodule\n",
] {
assert!(violations(src).is_empty(), "{src}");
}
}
#[test]
fn an_always_star_inside_a_generate_block_is_covered() {
let src = "module m;\n if (A) begin : g\n always @(*) x = 1;\n end\nendmodule\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
}
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_items, walk_stmts};
use vlog_parser::ast::{ItemKind, StmtKind};
@@ -20,6 +21,10 @@ impl Rule for AlwaysCombBlocking {
"assign with `=` inside always_comb"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A non-blocking assignment in a combinational block schedules its \
update for the end of the time step, so a value read later in the same \
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_items, walk_stmts};
use vlog_parser::ast::{ItemKind, StmtKind};
@@ -20,6 +21,10 @@ impl Rule for AlwaysFfNonBlocking {
"assign with `<=` inside always_ff"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A blocking assignment in a clocked block updates immediately, so two \
flops written in one `always_ff` can see each other's new value in \
@@ -0,0 +1,139 @@
//! `banned-declared-name-patterns` — names a project has forbidden.
use crate::context::LintContext;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::regex::Regex;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
/// See [`Rule::doc`].
pub struct BannedDeclaredNamePatterns;
const NAME: &str = "banned-declared-name-patterns";
impl Rule for BannedDeclaredNamePatterns {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not declare a name the project has banned"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"Every codebase has words it has decided against — a deprecated \
prefix, a vendor's reserved namespace, the `tmp`/`foo` a review keeps \
catching — and none of them are anybody else's business. Verible's \
`banned-declared-name-patterns` is the rule a project points at its \
own list, and it ships **off** with an empty list, which is exactly \
what lucisv does: with no `patterns` set the rule reports nothing and \
costs nothing.\n\n\
It judges **declared** names, not uses: every name the file's symbol \
table holds — modules, packages, types, parameters, signals, ports, \
instances, block labels, class members. A pattern must match the whole \
name, so `tmp.*` bans `tmp_addr` and `.*_tmp` bans `addr_tmp`. There \
is no fix: only the author knows what the name should have been."
}
fn default_on(&self) -> bool {
false
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "patterns",
kind: OptionKind::RegexList,
default: OptionDefault::List(&[]),
doc: "the patterns a declared name may not match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let patterns: Vec<(String, Regex)> = ctx
.option_list(NAME, "patterns")
.into_iter()
// A pattern that does not compile cannot be configured — the
// option is validated when it is read — so filtering here only
// ever drops what could not have arrived.
.filter_map(|text| Regex::compile(&text).ok().map(|regex| (text, regex)))
.collect();
if patterns.is_empty() {
return Vec::new();
}
let mut out = Vec::new();
for symbol in ctx.semantics().symbols() {
let Some((pattern, _)) =
patterns.iter().find(|(_, regex)| regex.is_match(&symbol.name))
else {
continue;
};
out.push(Violation::new(
NAME,
format!("`{}` matches the banned pattern `{pattern}`", symbol.name),
symbol.name_span,
));
}
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn banning(patterns: &str, src: &str) -> Vec<Violation> {
let mut options = RuleOptions::new();
options.set_raw(NAME, "patterns", patterns).expect("accepted");
BannedDeclaredNamePatterns.check(&LintContext::new(src, None).with_options(&options))
}
#[test]
fn nothing_is_banned_by_default() {
let src = "module m;\n logic tmp_addr;\nendmodule\n";
assert!(BannedDeclaredNamePatterns.check(&LintContext::new(src, None)).is_empty());
assert!(!BannedDeclaredNamePatterns.default_on());
}
#[test]
fn a_banned_name_is_reported_where_it_is_declared() {
let src = "module m;\n logic tmp_addr;\n logic keep_me;\nendmodule\n";
let found = banning("[\"tmp.*\"]", src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("banned pattern `tmp.*`"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "tmp_addr");
assert!(found[0].fix.is_none());
}
#[test]
fn the_match_is_the_whole_name() {
let src = "module m;\n logic addr_tmp;\nendmodule\n";
assert!(banning("[\"tmp\"]", src).is_empty(), "a substring is not a match");
assert_eq!(banning("[\".*_tmp\"]", src).len(), 1);
}
#[test]
fn every_kind_of_declared_name_is_covered() {
let src = "package foo_pkg;\n typedef logic foo_t;\nendpackage\n\
module foo_mod (input logic foo_port);\n logic foo_sig;\nendmodule\n";
let found = banning("[\"foo.*\"]", src);
let names: Vec<&str> = found.iter().map(|v| &src[v.span.as_range()]).collect();
for wanted in ["foo_pkg", "foo_t", "foo_mod", "foo_port", "foo_sig"] {
assert!(names.contains(&wanted), "{wanted} missing from {names:?}");
}
}
#[test]
fn several_patterns_are_all_applied_and_findings_come_back_in_order() {
let src = "module m;\n logic tmp_a;\n logic bad_b;\nendmodule\n";
let found = banning("[\"tmp.*\", \"bad.*\"]", src);
assert_eq!(found.len(), 2);
assert!(found[0].span.start < found[1].span.start);
}
}
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_all_stmts, walk_items};
use vlog_parser::ast::{CaseItem, GenCaseItem, ItemKind, StmtKind};
@@ -21,6 +22,10 @@ impl Rule for CaseMissingDefault {
"give every case statement a default branch"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A case statement with no `default` infers a latch in combinational \
logic and leaves the unlisted patterns unspecified in simulation — the \
@@ -0,0 +1,127 @@
//! `constraint-name-style` — constraint names end in `_c`.
use crate::context::LintContext;
use crate::naming::{fits_pattern, is_escaped, style_message};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::ItemKind;
/// See [`Rule::doc`].
pub struct ConstraintNameStyle;
const NAME: &str = "constraint-name-style";
impl Rule for ConstraintNameStyle {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name constraints in lower_snake_case ending in _c"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A constraint block's name is what a test turns off — \
`obj.addr_range_c.constraint_mode(0)` — so it is read far from its \
declaration and needs to say what it is at the use site. Verible's \
`constraint-name-style` (enabled by default) spells the convention as \
`([a-z0-9]+_)+c`: lower-case words, then a `_c` suffix. lucisv checks \
the same pattern, on the constraints a class declares and on the \
out-of-block `constraint cls::name { … }` form.\n\n\
A prototype (`constraint c;`) is judged like a definition — it \
declares the same name. Escaped identifiers are exempt, and there is \
no fix: a rename reaches every `constraint_mode` call."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "pattern",
kind: OptionKind::Regex,
default: OptionDefault::Str("([a-z0-9]+_)+c"),
doc: "the pattern a constraint's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::Constraint(decl) = &item.kind else { return };
let name = &decl.name.text;
if is_escaped(name) || fits_pattern(ctx, NAME, "pattern", name) {
return;
}
out.push(Violation::new(
NAME,
style_message(
ctx,
NAME,
"pattern",
&format!("constraint `{name}`"),
"is not lower_snake_case ending in `_c`",
),
decl.name.span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
ConstraintNameStyle.check(&LintContext::new(src, None))
}
fn constraint(name: &str) -> String {
format!("class c;\n rand int addr;\n constraint {name} {{ addr > 0; }}\nendclass\n")
}
#[test]
fn flags_a_missing_suffix_and_points_at_the_name() {
let src = constraint("addr_range");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "addr_range");
assert!(found[0].fix.is_none());
}
#[test]
fn the_convention_is_clean() {
for name in ["addr_range_c", "a_c", "addr2_range_c"] {
assert!(violations(&constraint(name)).is_empty(), "{name}");
}
for name in ["c", "AddrRangeC", "addr_range", "_addr_c"] {
assert_eq!(violations(&constraint(name)).len(), 1, "{name}");
}
}
#[test]
fn a_prototype_and_an_out_of_block_definition_are_judged_too() {
let src = "class c;\n extern constraint addr_range;\nendclass\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
let src = "constraint c::addr_range { x > 0; }\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn a_configured_pattern_replaces_the_default() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "pattern", "\"c_[a-z_0-9]+\"").expect("accepted");
let src = constraint("c_addr_range");
let ctx = LintContext::new(&src, None).with_options(&options);
assert!(ConstraintNameStyle.check(&ctx).is_empty());
let src = constraint("addr_range_c");
let ctx = LintContext::new(&src, None).with_options(&options);
assert_eq!(ConstraintNameStyle.check(&ctx).len(), 1);
}
}
@@ -0,0 +1,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,197 @@
//! `duplicate-declaration` — one name declared twice in one scope.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_semantic::{ScopeKind, SymbolKind};
/// See [`Rule::doc`].
pub struct DuplicateDeclaration;
const NAME: &str = "duplicate-declaration";
impl Rule for DuplicateDeclaration {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"declare each name once per scope"
}
fn severity(&self) -> Severity {
Severity::Error
}
fn doc(&self) -> &'static str {
"Two declarations of one name in one scope is an elaboration error in \
every tool (IEEE 1800 §3.13 — an identifier is unique within its \
namespace and scope). It happens when a signal is copied and the \
paste is not renamed, when two parameters are merged from different \
branches, or when a `logic` is declared beside the `input` of the \
same name. Verible has no equivalent rule; this is TODO §33's own, \
and it is an **Error** because the file will not compile.\n\n\
**Silent whenever the second declaration might be legal**, which is \
the rule every Error-class check here follows. It says nothing when \
either declaration is a **port** — a non-ANSI port is *completed* by \
a body `input clk;` and then by a `logic clk;`, all three of which \
are the same port and all three legal — nor about a function, task, \
class, constraint, covergroup, property, sequence, modport or \
clocking name, each of which has a legal prototype-plus-definition \
or forward-declaration shape. It says nothing inside a `generate` \
scope, where only one arm is ever elaborated, and nothing when a \
conditional-compilation directive stands between the two \
declarations, which is that same exclusivity written for the \
preprocessor. What is left is two ordinary declarations of one name, \
side by side, in one scope. No automatic fix: which of the two the \
author meant to keep is not something a linter can know."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
// Error recovery rebinds whatever followed a construct it could not
// parse into whatever scope it unwound to, which turns every later
// local into a phantom redeclaration. An Error-class rule says nothing
// about a file it cannot trust the shape of.
if !ctx.parsed_cleanly() {
return Vec::new();
}
let semantics = ctx.semantics();
let mut out = Vec::new();
for duplicate in semantics.duplicates() {
let Some(first) = semantics.symbol(duplicate.first) else { continue };
if !plain(duplicate.kind) || !plain(first.kind) {
continue;
}
let scope = semantics.scope(duplicate.scope).map(|scope| scope.kind);
// A generate scope elaborates one arm at a time; the file scope is
// where a `` `include``d fragment and a recovered construct both
// land, and two file-scope units of one name are the workspace's
// business rather than this file's.
if matches!(scope, Some(ScopeKind::Generate) | Some(ScopeKind::File)) {
continue;
}
let spans = [first.name_span.start, duplicate.name_span.start];
if ctx.signals().conditional_between(&spans) {
continue;
}
out.push(Violation::new(
NAME,
format!("`{}` is already declared in this scope", duplicate.name),
duplicate.name_span,
));
}
out
}
}
/// True for the declaration kinds that may be written **once** and once only.
///
/// Everything left out has a legal shape in which the same name is written
/// twice: a port is completed by its body declaration, a function or task by
/// its out-of-body definition, a class by its `typedef class` forward
/// declaration, and a constraint, covergroup, property or sequence by its own
/// prototype. An **enum member** is left out for a different reason: IEEE 1800
/// §6.19's name *range* (`RvCoreCsrGprT[0:2]`) declares a run of members under
/// one written identifier, and the binder records the identifier — so two
/// disjoint ranges of one base name look like one name declared twice when the
/// members they declare do not collide at all (measured on opentitan:
/// `jtag_rv_debugger_pkg.sv`). Listed positively rather than as an exclusion
/// list, so a kind added to `vlog_semantic` later is silent until somebody
/// decides it belongs.
fn plain(kind: SymbolKind) -> bool {
matches!(
kind,
SymbolKind::Net
| SymbolKind::Var
| SymbolKind::Param
| SymbolKind::LocalParam
| SymbolKind::Genvar
| SymbolKind::Typedef
| SymbolKind::Instance
| SymbolKind::TfArg
| SymbolKind::StructMember
)
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
DuplicateDeclaration.check(&LintContext::new(src, None))
}
#[test]
fn flags_two_signals_of_one_name() {
let src = "module m;\n logic a;\n logic a;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`a`"), "{}", found[0].message);
assert_eq!(found[0].span.start as usize, src.rfind('a').map(|i| i - 1).unwrap_or(0) + 1);
assert!(found[0].fix.is_none());
}
#[test]
fn flags_two_parameters_two_typedefs_and_two_instances() {
for src in [
"module m;\n parameter int W = 1;\n parameter int W = 2;\nendmodule\n",
"module m;\n typedef logic t;\n typedef bit t;\nendmodule\n",
"module m;\n sub u ();\n sub u ();\nendmodule\n",
] {
assert_eq!(violations(src).len(), 1, "{src}");
}
}
/// The non-ANSI shape: the header names the port, the body declares its
/// direction and then its type. Three declarations, one port, all legal.
#[test]
fn a_non_ansi_port_completed_in_the_body_is_never_flagged() {
let src = "module m (clk);\n input clk;\n logic clk;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
assert!(violations("module m (clk);\n input wire clk;\nendmodule\n").is_empty());
// An ANSI port redeclared in the body is left alone too, for the same
// reason: a rule that cannot tell the two apart must not accuse.
assert!(violations("module m (input logic clk);\n logic clk;\nendmodule\n").is_empty());
}
#[test]
fn a_prototype_and_its_definition_are_one_declaration() {
let src = "class c;\n extern function void f();\nendclass\n\
function void c::f();\nendfunction\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
let forward = "package p;\n typedef class c;\n class c;\n endclass\nendpackage\n";
assert!(violations(forward).is_empty(), "{:?}", violations(forward));
}
#[test]
fn conditional_arms_are_exclusive_so_they_are_not_flagged() {
let src = "module m;\n`ifdef X\n logic b;\n`else\n logic b;\n`endif\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_generate_scope_elaborates_one_arm_at_a_time() {
let src = "module m;\n\
generate\n\
if (A) begin : g\n\
logic x;\n\
end else begin : g\n\
logic x;\n\
end\n\
endgenerate\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_name_reused_in_a_nested_scope_is_not_a_duplicate() {
// That is shadowing, which is `instance-shadowing`'s subject.
let src =
"module m;\n logic a;\n always_comb begin : blk\n logic a;\n end\nendmodule\n";
assert!(violations(src).is_empty());
// And two modules may each declare `a`.
let two = "module m;\n logic a;\nendmodule\nmodule n;\n logic a;\nendmodule\n";
assert!(violations(two).is_empty());
}
}
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use crate::visit::walk_items;
use vlog_parser::ast::ItemKind;
@@ -21,6 +22,10 @@ impl Rule for EmptyItem {
"drop a `;` that stands where an item belongs"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A lone `;` in a module, generate, package, interface, program or class \
body is a *null item* (IEEE 1800-2017 A.1.4). It is legal and it means \
@@ -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,8 +2,10 @@
//! or `_t`.
use crate::context::LintContext;
use crate::naming::{is_escaped, is_lower_snake_case};
use crate::naming::{fits_pattern, is_escaped};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::{ItemKind, TypedefKind};
@@ -22,6 +24,10 @@ impl Rule for EnumNameStyle {
"name enum typedefs in lower_snake_case ending in _e or _t"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A type name that looks like a type name is what makes a declaration \
readable at a glance: `state_e cur_state` says which identifier is the \
@@ -31,7 +37,20 @@ impl Rule for EnumNameStyle {
same shape. Only a `typedef enum` is judged: an anonymous enum has no \
name to check, and giving it one is Verible's separate \
`typedef-enums` idea. Escaped identifiers are exempt, and there is no \
fix: a type rename reaches every use."
fix: a type rename reaches every use.\n\n\
The shape is the `style_regex` option, and its default is \
`[a-z][a-z_0-9]*(_t|_e)` — Verible's pattern with the first character \
pinned to a letter, which is what lucisv's preset checked before the \
option existed and what keeps a leading `_` reported."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str(DEFAULT_STYLE),
doc: "the pattern an enum typedef's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
@@ -42,13 +61,18 @@ impl Rule for EnumNameStyle {
return;
}
let name = &typedef.name;
let suffixed = name.ends_with("_e") || name.ends_with("_t");
if is_lower_snake_case(name) && suffixed {
if fits_pattern(ctx, NAME, "style_regex", name) {
return;
}
out.push(Violation::new(
NAME,
format!("enum `{name}` is not lower_snake_case ending in `_e` or `_t`"),
crate::naming::style_message(
ctx,
NAME,
"style_regex",
&format!("enum `{name}`"),
"is not lower_snake_case ending in `_e` or `_t`",
),
typedef.name_span,
));
});
@@ -56,6 +80,10 @@ impl Rule for EnumNameStyle {
}
}
/// Today's preset, written as a pattern: `lower_snake_case` (a letter first)
/// ending in `_e` or `_t`.
const DEFAULT_STYLE: &str = "[a-z][a-z_0-9]*(_t|_e)";
#[cfg(test)]
mod tests {
use super::*;
@@ -104,4 +132,31 @@ mod tests {
let src = typedef("state");
assert_eq!(&src[violations(&src)[0].span.as_range()], "state");
}
/// The default pattern is today's preset, character for character: a
/// leading `_` or digit is still rejected, which Verible's own
/// `[a-z_0-9]+(_t|_e)` would accept.
#[test]
fn the_default_pattern_is_the_preset_it_replaced() {
for bad in ["_state_t", "State_t", "state"] {
assert_eq!(violations(&typedef(bad)).len(), 1, "{bad}");
}
for good in ["state_t", "state_e", "s_t", "fifo2_state_e"] {
assert!(violations(&typedef(good)).is_empty(), "{good}");
}
}
#[test]
fn a_configured_pattern_replaces_it_and_is_named_in_the_message() {
let mut options = crate::options::RuleOptions::new();
options.set_raw(NAME, "style_regex", "\"[a-z_0-9]+_e\"").expect("accepted");
let src = typedef("state_t");
let ctx = LintContext::new(&src, None).with_options(&options);
let found = EnumNameStyle.check(&ctx);
assert_eq!(found.len(), 1, "`_t` is no longer accepted");
assert!(found[0].message.contains("[a-z_0-9]+_e"), "{}", found[0].message);
let src = typedef("_state_e");
let ctx = LintContext::new(&src, None).with_options(&options);
assert!(EnumNameStyle.check(&ctx).is_empty(), "and a leading `_` now passes");
}
}
@@ -0,0 +1,330 @@
//! `explicit-begin` — a body is a `begin ... end` block, always.
use crate::context::LintContext;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use crate::visit::{walk_all_stmts, walk_items};
use vlog_parser::ast::{ItemKind, Stmt, StmtKind};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct ExplicitBegin;
const NAME: &str = "explicit-begin";
/// The eleven constructs Verible lets a project switch on one at a time, each
/// with the keyword a diagnostic names it by.
const ENABLES: [(&str, &str); 11] = [
("always_comb_enable", "always_comb"),
("always_enable", "always"),
("always_ff_enable", "always_ff"),
("always_latch_enable", "always_latch"),
("else_enable", "else"),
("final_enable", "final"),
("for_enable", "for"),
("forever_enable", "forever"),
("if_enable", "if"),
("initial_enable", "initial"),
("while_enable", "while"),
];
impl Rule for ExplicitBegin {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"wrap every body in `begin` and `end`"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"The classic C bug transplanted: `if (a) x = 1;` grows a second \
statement in a later edit, the author indents it, and the compiler \
reads it as unconditional. Writing `begin ... end` from the start \
makes that edit impossible to get wrong, which is why several house \
styles require it. Verible's `explicit-begin` ships **off** — the \
style is far from universal, and a codebase that does not follow it \
would light up on the first run — and lucisv keeps it off for the same \
reason.\n\n\
Eleven `*_enable` options, exactly Verible's, switch the constructs on \
and off one at a time; all are on when the rule is. An `else if` is \
never reported: the `else`'s body is another `if`, which is the \
chained form every style guide writes. A null body (`if (a) ;`) is \
left to `suspicious-semicolon`, which has more to say about it. The \
fix wraps the body in `begin`/`end` and is **safe** — a block around \
one statement changes nothing — and running the formatter afterwards \
lays it out."
}
fn default_on(&self) -> bool {
false
}
fn fix(&self) -> Option<Applicability> {
Some(Applicability::Safe)
}
fn options(&self) -> &'static [OptionSpec] {
// Written out rather than generated, because a spec table is a
// `static` and every entry needs its own `&'static str` doc.
&[
OptionSpec {
name: "always_comb_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `always_comb`",
},
OptionSpec {
name: "always_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `always`",
},
OptionSpec {
name: "always_ff_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `always_ff`",
},
OptionSpec {
name: "always_latch_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `always_latch`",
},
OptionSpec {
name: "else_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `else`",
},
OptionSpec {
name: "final_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of a `final`",
},
OptionSpec {
name: "for_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of a `for` loop",
},
OptionSpec {
name: "forever_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of a `forever` loop",
},
OptionSpec {
name: "if_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `if`",
},
OptionSpec {
name: "initial_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `initial`",
},
OptionSpec {
name: "while_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of a `while` loop",
},
]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
let mut report = |keyword: &'static str, body: &Stmt| {
if !enabled(ctx, keyword) || is_block(body) || matches!(body.kind, StmtKind::Null) {
return;
}
out.push(
Violation::new(
NAME,
format!("`{keyword}` body is not a `begin ... end` block"),
body.span,
)
.with_fix(Fix::safe(vec![
(TextRange::new(body.span.start, body.span.start), "begin ".to_string()),
(TextRange::new(body.span.end, body.span.end), " end".to_string()),
])),
);
};
walk_items(ctx.file(), &mut |item| match &item.kind {
ItemKind::Always { kw, stmt } => {
let keyword = ENABLES
.iter()
.find_map(|(_, word)| (*word == kw).then_some(*word))
.unwrap_or("always");
if let Some(body) = procedural_body(stmt) {
report(keyword, body);
}
}
ItemKind::Initial(stmt) => {
if let Some(body) = procedural_body(stmt) {
report("initial", body);
}
}
ItemKind::Final(stmt) => {
if let Some(body) = procedural_body(stmt) {
report("final", body);
}
}
_ => {}
});
walk_all_stmts(ctx.file(), &mut |stmt| match &stmt.kind {
StmtKind::If { then, els, .. } => {
report("if", then);
// `else if` is the chained form, not a missing block.
if let Some(els) = els {
if !matches!(els.kind, StmtKind::If { .. }) {
report("else", els);
}
}
}
StmtKind::For { body, .. } => report("for", body),
StmtKind::While { body, .. } => report("while", body),
StmtKind::Forever { body } => report("forever", body),
_ => {}
});
out
}
}
/// Whether the run wants this construct checked.
fn enabled(ctx: &LintContext, keyword: &str) -> bool {
ENABLES
.iter()
.find(|(_, word)| *word == keyword)
.is_none_or(|(option, _)| ctx.option_bool(NAME, option))
}
/// The statement a procedural block really runs: the one under its timing
/// control, when it has one (`always_ff @(posedge clk) q <= d;`).
///
/// `None` for a timing control with no body at all (`always @(posedge clk);`),
/// which has nothing to wrap.
fn procedural_body(stmt: &Stmt) -> Option<&Stmt> {
match &stmt.kind {
StmtKind::Timing { stmt, .. } => stmt.as_deref(),
_ => Some(stmt),
}
}
/// Whether this statement is already a block.
fn is_block(stmt: &Stmt) -> bool {
matches!(stmt.kind, StmtKind::Block { .. } | StmtKind::ForkJoin { .. })
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
use crate::violation::apply_fixes;
fn violations(src: &str) -> Vec<Violation> {
ExplicitBegin.check(&LintContext::new(src, None))
}
#[test]
fn it_is_off_by_default_and_takes_veribles_eleven_options() {
assert!(!ExplicitBegin.default_on());
let names: Vec<&str> = ExplicitBegin.options().iter().map(|spec| spec.name).collect();
assert_eq!(names.len(), 11);
assert!(names.contains(&"if_enable") && names.contains(&"always_ff_enable"));
}
#[test]
fn flags_an_unblocked_if_body_and_wraps_it() {
let src = "module m;\n initial begin\n if (a) x = 1;\n end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "x = 1;");
let fixed = apply_fixes(src, &found, false);
assert_eq!(
fixed.output,
"module m;\n initial begin\n if (a) begin x = 1; end\n end\nendmodule\n"
);
assert!(violations(&fixed.output).is_empty(), "the fix satisfies the rule");
}
#[test]
fn a_blocked_body_is_clean() {
let src = "module m;\n initial begin\n if (a) begin\n x = 1;\n end\n end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn every_construct_is_covered() {
let src = "module m;\n\
\x20 always_comb x = 1;\n\
\x20 always_ff @(posedge clk) q <= d;\n\
\x20 always @(a) y = 2;\n\
\x20 always_latch if (en) z = 3;\n\
\x20 initial x = 0;\n\
\x20 final $display(\"bye\");\n\
endmodule\n";
let found = violations(src);
// Six bodies, plus the `if` inside the always_latch.
assert_eq!(found.len(), 7, "{:#?}", found.iter().map(|v| &v.message).collect::<Vec<_>>());
let src = "module m;\n initial begin\n\
\x20 for (int i = 0; i < 2; i++) x = i;\n\
\x20 while (a) y = 1;\n\
\x20 forever z = 2;\n\
\x20 end\nendmodule\n";
assert_eq!(violations(src).len(), 3, "{:?}", violations(src));
}
#[test]
fn an_else_if_chain_is_not_a_missing_block() {
let src = "module m;\n initial begin\n if (a) begin\n x = 1;\n end\n\
\x20 else if (b) begin\n x = 2;\n end\n end\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_bare_else_body_is_reported() {
let src =
"module m;\n initial begin\n if (a) begin\n x = 1;\n end else x = 2;\n\
\x20 end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`else`"), "{}", found[0].message);
}
#[test]
fn a_null_body_is_left_to_suspicious_semicolon() {
let src = "module m;\n initial begin\n if (a) ;\n end\nendmodule\n";
assert!(violations(src).is_empty());
}
#[test]
fn each_option_switches_its_own_construct_off() {
let src = "module m;\n initial begin\n if (a) x = 1;\n while (b) y = 2;\n end\n\
endmodule\n";
assert_eq!(violations(src).len(), 2);
let mut options = RuleOptions::new();
options.set_raw(NAME, "if_enable", "false").expect("accepted");
let found = ExplicitBegin.check(&LintContext::new(src, None).with_options(&options));
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`while`"), "{}", found[0].message);
}
#[test]
fn a_fork_join_body_is_already_a_block() {
let src = "module m;\n initial fork\n x = 1;\n join\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
}
@@ -0,0 +1,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,152 @@
//! `explicit-function-task-parameter-type` — every formal gets a storage type.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::{ItemKind, ListElem, TfArg};
/// See [`Rule::doc`].
pub struct ExplicitFunctionTaskParameterType;
const NAME: &str = "explicit-function-task-parameter-type";
impl Rule for ExplicitFunctionTaskParameterType {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"declare a storage type on every function and task argument"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A task or function formal written without a type is a **one-bit \
`logic`** (IEEE 1800 §13.3), so `function f(input a);` truncates \
every caller's argument to its low bit and nothing complains — the \
function simply returns the wrong answer for anything wider than a \
flag. Verible's `explicit-function-task-parameter-type` (\"Checks \
that every function and task parameter is declared with an explicit \
storage type.\", enabled by default) is the same rule and the same \
default. **A continuation formal inherits**: in `f(input int a, b)` \
the `b` is an `int`, so only the argument that *opens* a declaration \
— the first one, or the first after a direction keyword — is judged, \
which is exactly the language's own rule. A DPI import's unnamed \
formal (`import \"DPI-C\" function int f(int);`) names a type and no \
identifier and is not this rule's subject. No automatic fix: only the \
author knows how wide the argument was meant to be."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let (kw, args) = match &item.kind {
ItemKind::Function(decl) => ("function", &decl.args),
ItemKind::Task(decl) => ("task", &decl.args),
_ => return,
};
out.extend(untyped(kw, args));
});
out
}
}
/// The formals of one argument list that end up implicitly typed.
///
/// Walked in order with the declaration's type carried along, which is how the
/// language reads them: a formal that writes a type sets it, a formal that
/// writes a direction keyword opens a new declaration (and so a new type,
/// implicit until written), and a formal that writes neither inherits whatever
/// is in force.
fn untyped(kw: &'static str, args: &[ListElem<TfArg>]) -> Vec<Violation> {
let mut out = Vec::new();
let mut opened = false;
for arg in args.iter().filter_map(ListElem::ok) {
let opens = !opened || arg.dir.is_some() || !arg.ty.is_implicit();
opened = true;
if !opens || !arg.ty.is_implicit() || arg.name.is_empty() {
continue;
}
out.push(Violation::new(
NAME,
format!("{kw} argument `{}` has no storage type; it is a 1-bit `logic`", arg.name),
arg.span,
));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ExplicitFunctionTaskParameterType.check(&LintContext::new(src, None))
}
fn wrap(header: &str) -> String {
format!("module m;\n {header}\n endfunction\nendmodule\n")
}
#[test]
fn flags_an_untyped_formal() {
let src = wrap("function void f(input a);");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`a`"), "{}", found[0].message);
assert!(found[0].message.contains("1-bit"), "{}", found[0].message);
assert!(found[0].fix.is_none());
}
#[test]
fn a_typed_formal_is_what_the_rule_wants() {
for header in [
"function void f(input logic a);",
"function void f(input int a);",
"function void f(input logic [7:0] a);",
"function void f(my_t a);",
"function void f();",
] {
assert!(
violations(&wrap(header)).is_empty(),
"{header}: {:?}",
violations(&wrap(header))
);
}
}
#[test]
fn a_continuation_formal_inherits_the_type_before_it() {
// `b` is an `int`, so only a genuinely untyped run may be reported.
assert!(violations(&wrap("function void f(input int a, b);")).is_empty());
// ... and a new direction keyword opens a new, untyped declaration.
let found = violations(&wrap("function void f(input int a, output b);"));
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`b`"), "{}", found[0].message);
}
#[test]
fn a_task_is_judged_the_same_way() {
let src = "module m;\n task t(input a);\n endtask\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("task"), "{}", found[0].message);
}
#[test]
fn an_unnamed_dpi_formal_is_not_this_rules_subject() {
let src = "import \"DPI-C\" function int f(int, chandle);\n";
assert!(violations(src).is_empty());
}
#[test]
fn a_class_method_is_reached() {
let src = "class c;\n function void f(input a);\n endfunction\nendclass\n";
assert_eq!(violations(src).len(), 1);
}
}
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
use vlog_parser::ast::{ItemKind, ParamDecl, StmtKind};
@@ -20,6 +21,10 @@ impl Rule for ExplicitParameterStorageType {
"declare a storage type on every parameter"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A parameter with no declared type takes its type from whatever it is \
assigned — and an override at instantiation can change that type, not \
@@ -0,0 +1,120 @@
//! `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,93 @@
//! `forbid-defparam` — `defparam` is deprecated; override at instantiation.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::ItemKind;
/// See [`Rule::doc`].
pub struct ForbidDefparam;
const NAME: &str = "forbid-defparam";
impl Rule for ForbidDefparam {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"override a parameter at the instantiation, not with `defparam`"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"`defparam` reaches into another scope and changes a parameter there, \
so the value a module elaborates with is written somewhere the module \
does not name and a reader has no way to find without grepping the \
whole design. It was deprecated in IEEE 1800-2009 (§A.11, and the LRM \
says it may be removed from a future revision), several synthesis \
tools reject it outright, and the `#(.NAME(value))` override at the \
instantiation says the same thing where the instance is. Verible's \
`forbid-defparam` (\"Do not use defparam.\", enabled by default) is \
the same rule. No automatic fix: moving the value to the right \
instantiation needs the instantiation, which may be in another file."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
if matches!(item.kind, ItemKind::Defparam(_)) {
out.push(Violation::new(
NAME,
"`defparam` is deprecated; override the parameter at its instantiation",
item.span,
));
}
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ForbidDefparam.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_defparam_wherever_it_stands() {
let src = "module m;\n sub u ();\n defparam u.WIDTH = 8;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "defparam u.WIDTH = 8;");
assert!(found[0].fix.is_none());
}
#[test]
fn a_named_override_is_what_the_rule_wants() {
assert!(violations("module m;\n sub #(.WIDTH(8)) u ();\nendmodule\n").is_empty());
// Nor is a parameter declaration one.
assert!(violations("module m;\n parameter int WIDTH = 8;\nendmodule\n").is_empty());
// And a signal that merely spells the word is not one either.
assert!(violations("module m;\n logic defparam_n;\nendmodule\n").is_empty());
}
#[test]
fn a_defparam_inside_generate_is_reached() {
let src = "module m;\n\
generate\n\
if (A) begin : g\n\
defparam u.W = 1;\n\
end\n\
endgenerate\n\
endmodule\n";
assert_eq!(violations(src).len(), 1);
}
}
@@ -0,0 +1,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,144 @@
//! `forbid-negative-array-dim` — a negative literal inside a dimension.
use crate::context::LintContext;
use crate::decls::walk_dims;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::ast::{DimKind, Expr, ExprKind};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct ForbidNegativeArrayDim;
const NAME: &str = "forbid-negative-array-dim";
impl Rule for ForbidNegativeArrayDim {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not write a negative constant in a dimension"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"`logic q [-1]` and `logic [-1:0] v` are what a parameter that came \
out zero or one too small looks like after the subtraction: \
`[WIDTH-1:0]` with `WIDTH = 0` is `[-1:0]`, which tools variously \
reject, treat as empty, or size as two bits. Written as a literal it \
is never intentional. Verible's `forbid-negative-array-dim` (\"Check \
for negative constant literals inside array dimensions.\") is the \
same rule; **lucisv turns it on by default where Verible ships it \
off**, because a negative literal spelled out in a dimension has no \
legitimate reading. Only a written `-<literal>` is flagged — an \
expression that would *evaluate* negative needs the parameter values, \
which lucisv does not have. No automatic fix."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_dims(ctx.file(), &mut |_, dim| {
let DimKind::Range { a, b } = &dim.kind else { return };
for expr in [Some(a), b.as_ref()].into_iter().flatten() {
for span in negative_literals(expr) {
out.push(Violation::new(NAME, "negative constant in a dimension", span));
}
}
});
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
out
}
}
/// The spans of every written `-<literal>` inside `expr`.
///
/// A whole expression tree rather than the top node alone, because the shape
/// that turns up in real code is `[-1:0]` on one side and `[WIDTH-1:-1]` on
/// the other, and the offending term can sit anywhere in an arithmetic
/// expression.
fn negative_literals(expr: &Expr) -> Vec<TextRange> {
let mut out = Vec::new();
collect(expr, &mut out);
out
}
fn collect(expr: &Expr, out: &mut Vec<TextRange>) {
match &expr.kind {
ExprKind::Unary { op, expr: inner, .. } => {
if op == "-" && matches!(inner.kind, ExprKind::Number(_)) {
out.push(expr.span);
return;
}
collect(inner, out);
}
ExprKind::Binary { lhs, rhs, .. } => {
collect(lhs, out);
collect(rhs, out);
}
ExprKind::Paren { inner, .. } => collect(inner, out),
ExprKind::Ternary { cond, then, els, .. } => {
collect(cond, out);
collect(then, out);
collect(els, out);
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ForbidNegativeArrayDim.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_negative_packed_bound() {
let src = "module m;\n logic [-1:0] v;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "-1");
assert!(found[0].fix.is_none());
}
#[test]
fn flags_a_negative_unpacked_extent_and_one_buried_in_arithmetic() {
assert_eq!(violations("module m;\n logic q [-1];\nendmodule\n").len(), 1);
assert_eq!(violations("module m;\n logic [W + -2:0] v;\nendmodule\n").len(), 1);
// Both ends count.
assert_eq!(violations("module m;\n logic [-1:-2] v;\nendmodule\n").len(), 2);
}
#[test]
fn ordinary_dimensions_are_silent() {
for decl in [
"logic [7:0] v;",
"logic [WIDTH-1:0] v;",
"logic q [4];",
"logic q [0:3];",
"logic v;",
"logic q [];",
] {
let src = format!("module m;\n {decl}\nendmodule\n");
assert!(violations(&src).is_empty(), "{decl}: {:?}", violations(&src));
}
}
#[test]
fn a_negative_outside_a_dimension_is_not_this_rules_business() {
assert!(violations("module m;\n assign x = -1;\nendmodule\n").is_empty());
assert!(violations("module m;\n parameter int P = -1;\nendmodule\n").is_empty());
}
#[test]
fn a_subtraction_is_not_a_negative_literal() {
// `WIDTH-1` is the ordinary way to write a width and must never fire.
assert!(violations("module m;\n logic [WIDTH-1:0] v;\nendmodule\n").is_empty());
}
}
@@ -0,0 +1,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,349 @@
//! `incomplete-assignment` — a latch inferred in an `always_comb`.
use std::collections::BTreeSet;
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_items, walk_stmts};
use vlog_parser::ast::{Expr, ExprKind, ItemKind, Stmt, StmtKind};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct IncompleteAssignment;
const NAME: &str = "incomplete-assignment";
impl Rule for IncompleteAssignment {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"assign every variable on every path of an always_comb"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A variable an `always_comb` writes on some paths and not on others \
has to *hold its value* on the others, and holding a value is a \
latch: the synthesized circuit grows storage nobody asked for, the \
timing closes differently, and in simulation the block reads back \
whatever it left there last time. `always_comb` was added to the \
language precisely so tools could catch this, and most of them do — \
but only at elaboration, long after the edit. There is no Verible \
equivalent; this is TODO §33's own rule.\n\n\
**Conservative by construction.** It speaks only about the \
*top level* of an `always_comb` body, and only in the two shapes that \
are unambiguous: an `if` with no `else`, and a `case` with no \
`default`. A variable is reported only when the block writes it \
inside such a statement and nothing **earlier in the block** already \
covered it — where covering it means a plain assignment (a partial \
one, through a bit select or a field, counts), or an `if`/`else` or a \
`case` with a `default` that writes it in *every* arm. That last one \
is the usual style, and the usual repair is the other: a default \
assignment at the top of the block.\n\n\
Everything else stays silent, deliberately: a name the block \
**declares for itself** (a local temporary is not a latched output), \
a left-hand side that is not a plain name or a concatenation of them, \
a conditional nested inside another, and every `always` that is not \
an `always_comb`. Measured on opentitan: three findings before those \
exemptions, all three false, none after. No automatic fix: what the \
missing branch should assign is a design decision."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::Always { kw, stmt } = &item.kind else { return };
if kw != "always_comb" {
return;
}
out.extend(latches(ctx.source(), stmt));
});
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
out
}
}
/// The findings of one `always_comb` body.
fn latches(source: &str, body: &Stmt) -> Vec<Violation> {
// Names the block declares for itself are never reported: a temporary
// written inside the branch it was declared in is a local, not a latched
// output, and deciding which of the two it is needs elaboration.
let local = declared_names(body);
let mut covered: BTreeSet<String> = BTreeSet::new();
let mut out = Vec::new();
for stmt in top_level(body) {
match &stmt.kind {
// Any write at all counts as coverage, a partial one included: a
// block that sets `cfg.mode` at the top and the whole `cfg` under
// an `if` has written the variable before the branch.
StmtKind::Assign { lhs, .. } => covered.extend(written_names(lhs)),
StmtKind::If { cond, then, els: None, .. } => {
let at = header(source, stmt.span, cond.span);
report(&mut out, &covered, &local, at, branch_names(then));
}
// An `if` with an `else`, and a `case` with a `default`, cover
// every name their branches agree on — which is how the usual
// "assign it in every arm" style is written.
StmtKind::If { then, els: Some(els), .. } => {
covered.extend(intersect(&[branch_names(then), branch_names(els)]));
}
StmtKind::Case { expr, items, .. } => {
let per_branch: Vec<BTreeSet<String>> =
items.iter().map(|item| branch_names(&item.stmt)).collect();
if items.iter().any(|item| item.labels.is_empty()) {
covered.extend(intersect(&per_branch));
} else {
let mut names = BTreeSet::new();
for branch in &per_branch {
names.extend(branch.iter().cloned());
}
let at = header(source, stmt.span, expr.span);
report(&mut out, &covered, &local, at, names);
}
}
_ => {}
}
}
out
}
/// The names every one of these branches writes.
fn intersect(branches: &[BTreeSet<String>]) -> BTreeSet<String> {
let Some((first, rest)) = branches.split_first() else { return BTreeSet::new() };
first.iter().filter(|name| rest.iter().all(|set| set.contains(*name))).cloned().collect()
}
/// Every name the block declares anywhere inside itself.
fn declared_names(body: &Stmt) -> BTreeSet<String> {
let mut names = BTreeSet::new();
walk_stmts(body, &mut |stmt| {
if let StmtKind::VarDecl(decl) = &stmt.kind {
names.extend(decl.declarators.iter().map(|d| d.name.clone()));
}
});
names
}
/// The statements written directly in the body — the body itself when it is
/// one statement, and a `begin ... end`'s own list when it is a block.
fn top_level(body: &Stmt) -> Vec<&Stmt> {
match &body.kind {
StmtKind::Block { stmts, .. } => stmts.iter().collect(),
// The body of an `always_comb` carries no timing control of its own,
// so anything else is a single statement standing as the whole block.
_ => vec![body],
}
}
/// Every plain name a branch assigns, however deep inside it.
fn branch_names(stmt: &Stmt) -> BTreeSet<String> {
let mut names = BTreeSet::new();
walk_stmts(stmt, &mut |inner| {
if let StmtKind::Assign { lhs, .. } = &inner.kind {
names.extend(assigned_name(lhs));
}
});
names
}
/// Adds one finding per name the branch writes that nothing covered before it
/// and that the block does not declare for itself.
fn report(
out: &mut Vec<Violation>,
covered: &BTreeSet<String>,
local: &BTreeSet<String>,
span: TextRange,
names: BTreeSet<String>,
) {
for name in names {
if covered.contains(&name) || local.contains(&name) {
continue;
}
out.push(Violation::new(
NAME,
format!("`{name}` is not assigned on every path; this infers a latch"),
span,
));
}
}
/// The `if (cond)` / `case (subject)` header alone, so a whole branch is not
/// painted red for a problem that lives on one line. The subject's own span
/// stops inside the parentheses, so the underline runs on to the `)` that
/// closes it — the same shape `case-missing-default` underlines.
fn header(source: &str, stmt: TextRange, subject: TextRange) -> TextRange {
let close = source
.get(subject.end as usize..)
.and_then(|rest| rest.find(')'))
.map(|i| subject.end + i as u32 + 1)
.unwrap_or(subject.end);
TextRange::new(stmt.start, close.max(stmt.start))
}
/// The plain name a left-hand side writes, or nothing when the target is not
/// one identifier.
///
/// A bit or field select (`x[3] = …`, `s.f = …`) writes *part* of a variable,
/// and deciding whether the rest is covered needs ranges resolved — so those
/// are not names this rule will accuse. A concatenation lvalue is every name
/// in it, each of which is written whole.
fn assigned_name(lhs: &Expr) -> Vec<String> {
match &lhs.kind {
ExprKind::Ident(name) => vec![name.clone()],
ExprKind::Concat(items) => {
items.iter().flat_map(|item| assigned_name(&item.expr)).collect()
}
_ => Vec::new(),
}
}
/// Every name a left-hand side touches, a *part* of one included.
///
/// The wider question — "was this variable written here at all?" — which is
/// what the coverage set wants: a block that writes `cfg.mode` before an `if`
/// that writes the whole `cfg` has already spoken for `cfg`, and reporting it
/// would be a latch that is not there.
fn written_names(lhs: &Expr) -> Vec<String> {
match &lhs.kind {
ExprKind::Ident(name) => vec![name.clone()],
ExprKind::Concat(items) => {
items.iter().flat_map(|item| written_names(&item.expr)).collect()
}
ExprKind::Index { base, .. }
| ExprKind::Range { base, .. }
| ExprKind::Member { base, .. } => written_names(base),
_ => Vec::new(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
IncompleteAssignment.check(&LintContext::new(src, None))
}
fn wrap(body: &str) -> String {
format!("module m;\n always_comb begin\n{body} end\nendmodule\n")
}
#[test]
fn flags_a_variable_written_only_under_an_if() {
let src = wrap(" if (en) y = a;\n");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`y`"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "if (en)", "the header, not the branch");
assert!(found[0].fix.is_none());
}
#[test]
fn a_default_assignment_before_the_if_is_the_repair() {
assert!(violations(&wrap(" y = 1'b0;\n if (en) y = a;\n")).is_empty());
// ... and it must come *before*: assigning after the `if` does not
// stop the branch from inferring one.
assert_eq!(violations(&wrap(" if (en) y = a;\n y = 1'b0;\n")).len(), 1);
}
#[test]
fn an_if_with_an_else_covers_every_path() {
assert!(violations(&wrap(" if (en) y = a; else y = b;\n")).is_empty());
}
#[test]
fn a_case_without_default_is_flagged_and_one_with_it_is_not() {
let with_default = " case (s)\n 0: y = a;\n default: y = b;\n endcase\n";
assert!(violations(&wrap(with_default)).is_empty());
let without = " case (s)\n 0: y = a;\n 1: y = b;\n endcase\n";
let found = violations(&wrap(without));
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`y`"), "{}", found[0].message);
}
#[test]
fn every_variable_of_a_branch_is_named_once() {
let found = violations(&wrap(" if (en) begin\n y = a;\n z = b;\n end\n"));
assert_eq!(found.len(), 2, "{found:?}");
assert!(found[0].message.contains("`y`") || found[0].message.contains("`z`"));
// And a variable written twice in the branch is still one finding.
let twice = violations(&wrap(" if (en) begin\n y = a;\n y = b;\n end\n"));
assert_eq!(twice.len(), 1, "{twice:?}");
}
#[test]
fn only_always_comb_is_judged() {
for kw in ["always", "always_ff", "always_latch"] {
let src = format!("module m;\n {kw} @(posedge clk) if (en) y <= a;\nendmodule\n");
assert!(violations(&src).is_empty(), "{kw}");
}
assert!(violations("module m;\n always @* if (en) y = a;\nendmodule\n").is_empty());
}
#[test]
fn a_partial_write_is_not_accused() {
// Deciding whether the other bits are covered needs ranges resolved,
// which this rule does not do.
assert!(violations(&wrap(" if (en) y[3] = a;\n")).is_empty());
assert!(violations(&wrap(" if (en) s.f = a;\n")).is_empty());
}
#[test]
fn a_concatenation_lvalue_names_every_target() {
let found = violations(&wrap(" if (en) {y, z} = a;\n"));
assert_eq!(found.len(), 2, "{found:?}");
}
#[test]
fn a_nested_conditional_is_left_to_the_top_level_one() {
// The outer `if` has an `else`, so the block covers every path as far
// as this rule is willing to claim.
let src = wrap(" if (en) begin\n if (x) y = a;\n end else y = b;\n");
assert!(violations(&src).is_empty());
}
/// The three shapes the opentitan census turned up as false positives, each
/// pinned so it stays quiet.
#[test]
fn the_shapes_that_are_not_latches_stay_quiet() {
// 1. A variable the block declares for itself, written in the branch
// it was declared in (`entropy_src_core.sv`).
let local = wrap(" if (en) begin\n logic [3:0] tmp;\n tmp = a;\n end\n");
assert!(violations(&local).is_empty(), "{:?}", violations(&local));
// 2. A partial write before the branch covers the variable
// (`kmac_app.sv`).
let partial = wrap(" cfg.mode = a;\n if (en) cfg = b;\n");
assert!(violations(&partial).is_empty(), "{:?}", violations(&partial));
// 3. A `case` with a `default` that writes it in every arm, followed
// by an `if` that writes it again (`ibex_alu.sv`).
let after_case = wrap(
" case (s)\n 0: y = a;\n default: y = b;\n endcase\n\
\x20 if (en) y = 1'b1;\n",
);
assert!(violations(&after_case).is_empty(), "{:?}", violations(&after_case));
}
#[test]
fn an_if_else_before_the_branch_also_covers_it() {
let src = wrap(" if (a) y = 1; else y = 0;\n if (en) y = 2;\n");
assert!(violations(&src).is_empty(), "{:?}", violations(&src));
// ... but only for the names *both* arms write.
let partial = wrap(" if (a) y = 1; else z = 0;\n if (en) y = 2;\n");
assert_eq!(violations(&partial).len(), 1, "{:?}", violations(&partial));
}
#[test]
fn a_body_that_is_one_statement_is_still_a_body() {
let src = "module m;\n always_comb if (en) y = a;\nendmodule\n";
assert_eq!(violations(src).len(), 1);
}
}
@@ -0,0 +1,204 @@
//! `instance-shadowing` — a declaration hiding one from an enclosing scope.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_semantic::{Scope, ScopeKind, Semantics, SymbolKind};
/// See [`Rule::doc`].
pub struct InstanceShadowing;
const NAME: &str = "instance-shadowing";
impl Rule for InstanceShadowing {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not hide an enclosing declaration with a new one of the same name"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A `logic count;` inside a `begin : blk` where the module already has \
a `count` compiles, and from then on every mention of `count` inside \
the block means the inner one — including the ones written before the \
inner declaration was added, which is how this arrives in a review \
diff that looks like it changed nothing. Verible's `instance-\
shadowing` (\"Warns if there are multiple declarations in the same \
scope that shadow each other with the same name.\") is the same rule; \
**lucisv turns it on by default where Verible ships it off**, because \
the finding is always worth a second look and the repair is a rename \
in one block.\n\n\
Only the scopes **inside one design unit** are compared: a module, a \
package or a class opens a fresh namespace, and a signal called `data` \
in two different modules shadows nothing. A generate scope is \
compared like any other block — the shadowing is real there too. No \
automatic fix: renaming reaches every use inside the block."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
// Shadowing is a claim about *which scope* a name was declared in,
// and error recovery moves declarations between scopes — so a file
// that did not fully parse gets no opinion, exactly as
// `duplicate-declaration` gives it none.
if !ctx.parsed_cleanly() {
return Vec::new();
}
let semantics = ctx.semantics();
let mut out = Vec::new();
for scope in semantics.scopes() {
if opens_a_unit(scope.kind) {
continue;
}
for &id in &scope.symbols {
let Some(symbol) = semantics.symbol(id) else { continue };
let Some(hidden) = shadowed(semantics, scope, &symbol.name) else { continue };
if !judged(symbol.kind) {
continue;
}
// The two are exclusive when a conditional-compilation
// directive stands between them, exactly as they are for
// `duplicate-declaration`.
if ctx.signals().conditional_between(&[hidden, symbol.name_span.start]) {
continue;
}
out.push(Violation::new(
NAME,
format!(
"`{}` shadows a declaration of the same name outside this scope",
symbol.name
),
symbol.name_span,
));
}
}
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
out
}
}
/// The name span of the enclosing declaration `name` hides, if there is one
/// **within the same design unit**.
///
/// The walk stops at the scope that opens a unit — a module, package or class
/// body — because a name declared in a different unit is reached by a
/// qualified path, never by shadowing.
fn shadowed(semantics: &Semantics, scope: &Scope, name: &str) -> Option<u32> {
let mut parent = scope.parent;
while let Some(id) = parent {
let outer = semantics.scope(id)?;
if let Some(hidden) = outer.lookup_local(name) {
return semantics.symbol(hidden).map(|symbol| symbol.name_span.start);
}
if opens_a_unit(outer.kind) {
return None;
}
parent = outer.parent;
}
None
}
/// True for the scopes that open a design unit's own namespace.
fn opens_a_unit(kind: ScopeKind) -> bool {
matches!(kind, ScopeKind::File | ScopeKind::Module | ScopeKind::Package | ScopeKind::Class)
}
/// True for the declarations worth reporting.
///
/// A subroutine argument named after an enclosing signal is idiomatic
/// (`function automatic f(input logic clk)`), a block label is not a value,
/// and a `genvar` is scoped to its own loop by construction — so those stay
/// out. What is left is data and instances, which is where the surprise is.
fn judged(kind: SymbolKind) -> bool {
matches!(
kind,
SymbolKind::Net | SymbolKind::Var | SymbolKind::Instance | SymbolKind::LocalParam
)
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
InstanceShadowing.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_block_local_that_hides_a_module_signal() {
let src = "module m;\n\
logic count;\n\
always_comb begin : blk\n\
logic count;\n\
count = 1'b0;\n\
end\n\
endmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`count`"), "{}", found[0].message);
assert!(found[0].span.start as usize > src.find("blk").unwrap_or(0), "the inner one");
assert!(found[0].fix.is_none());
}
#[test]
fn a_name_declared_once_is_never_flagged() {
let src = "module m;\n\
logic count;\n\
always_comb begin : blk\n\
logic other;\n\
end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_different_unit_shadows_nothing() {
let src = "module a;\n logic data;\nendmodule\nmodule b;\n logic data;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
// Nor does a package-level name reached from a module.
let pkg = "package p;\n logic data;\nendpackage\nmodule m;\n logic data;\nendmodule\n";
assert!(violations(pkg).is_empty(), "{:?}", violations(pkg));
}
#[test]
fn a_generate_block_is_compared_like_any_other() {
let src = "module m;\n\
logic x;\n\
generate\n\
if (A) begin : g\n\
logic x;\n\
end\n\
endgenerate\n\
endmodule\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn a_subroutine_argument_named_after_a_signal_is_idiomatic() {
let src = "module m;\n\
logic clk;\n\
function automatic void f(input logic clk);\n\
endfunction\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn conditional_arms_are_exclusive() {
let src = "module m;\n\
logic x;\n\
always_comb begin : blk\n\
`ifdef A\n\
logic x;\n\
`endif\n\
end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
}
@@ -0,0 +1,138 @@
//! `interface-name-style` — interface names are `lower_snake_case` ending
//! `_if`.
use crate::context::LintContext;
use crate::naming::{fits_pattern, is_escaped, style_message};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::ItemKind;
/// See [`Rule::doc`].
pub struct InterfaceNameStyle;
const NAME: &str = "interface-name-style";
impl Rule for InterfaceNameStyle {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name interfaces in lower_snake_case ending in _if"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"An interface is written where a type is written — `virtual bus_if h`, \
`bus_if.master port` — and nothing in the syntax says that the \
identifier is an interface rather than a module or a class. The `_if` \
suffix is what says it, and Verible's `interface-name-style` (enabled \
by default, pattern `[a-z_0-9]+(_if)`) requires it. lucisv checks the \
same shape, on every `interface` declaration in the file.\n\n\
Only an `interface` is judged: a `module` and a `program` have their \
own conventions, and `module-name-style` is where a project that wants \
one says so. Escaped identifiers are exempt, and there is no fix — an \
interface rename reaches every port, every virtual handle and every \
file that imports it."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str("[a-z_0-9]+(_if)"),
doc: "the pattern an interface's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::Module(module) = &item.kind else { return };
if module.kw != "interface" || is_escaped(&module.name) {
return;
}
if fits_pattern(ctx, NAME, "style_regex", &module.name) {
return;
}
out.push(Violation::new(
NAME,
style_message(
ctx,
NAME,
"style_regex",
&format!("interface `{}`", module.name),
"is not lower_snake_case ending in `_if`",
),
module.name_span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
InterfaceNameStyle.check(&LintContext::new(src, None))
}
fn interface(name: &str) -> String {
format!("interface {name};\nendinterface\n")
}
#[test]
fn flags_a_missing_suffix_and_points_at_the_name() {
let src = interface("bus");
let found = violations(&src);
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("`bus`"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "bus");
assert!(found[0].fix.is_none());
}
#[test]
fn the_convention_is_clean() {
for name in ["bus_if", "clk_rst_if", "tl_if", "a_if"] {
assert!(violations(&interface(name)).is_empty(), "{name}");
}
for name in ["BusIf", "bus_IF", "bus_intf"] {
assert_eq!(violations(&interface(name)).len(), 1, "{name}");
}
}
#[test]
fn a_module_or_a_program_is_none_of_its_business() {
assert!(violations("module bus;\nendmodule\n").is_empty());
assert!(violations("program test;\nendprogram\n").is_empty());
}
#[test]
fn an_interface_inside_a_package_is_covered() {
let src = "package p;\n interface bus;\n endinterface\nendpackage\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn a_configured_pattern_replaces_the_default() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "style_regex", "\"[a-z_0-9]+_intf\"").expect("accepted");
let src = interface("bus_intf");
let ctx = LintContext::new(&src, None).with_options(&options);
assert!(InterfaceNameStyle.check(&ctx).is_empty());
let src = interface("bus_if");
let ctx = LintContext::new(&src, None).with_options(&options);
let found = InterfaceNameStyle.check(&ctx);
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("_intf"), "{}", found[0].message);
}
}
@@ -0,0 +1,198 @@
//! `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;
use vlog_parser::token::TokenKind;
/// See [`Rule::doc`].
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.
///
/// The `$dist_*` family and `$random` all draw from the *global* seed that
/// `$random` shares, so one extra call anywhere in a testbench reshuffles
/// every other stream; `$urandom` and `$urandom_range` are per-thread and
/// reproducible. `$psprintf` is a vendor extension for the standard
/// `$sformatf`, and `$srandom` seeds that same global generator rather than
/// the calling process.
const FORBIDDEN: &[(&str, &str)] = &[
("$psprintf", "$sformatf"),
("$random", "$urandom"),
("$srandom", "process::self().srandom()"),
("$dist_chi_square", "$urandom"),
("$dist_erlang", "$urandom"),
("$dist_exponential", "$urandom"),
("$dist_normal", "$urandom"),
("$dist_poisson", "$urandom"),
("$dist_t", "$urandom"),
("$dist_uniform", "$urandom"),
];
impl Rule for InvalidSystemTaskFunction {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not call a deprecated or non-reproducible system task"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn 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 \
every other random stream in it and a failing seed stops reproducing \
— the reason IEEE 1800 added the per-process `$urandom` / \
`$urandom_range` and `process::self().srandom()`. `$psprintf` is a \
vendor spelling of the standard `$sformatf` and is not portable. \
Verible's `invalid-system-task-function` (\"Checks that no forbidden \
system tasks or functions are used.\", enabled by default) forbids \
exactly this list, and lucisv names the replacement in the message.\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 = 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()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
InvalidSystemTaskFunction.check(&LintContext::new(src, None))
}
#[test]
fn flags_every_forbidden_name_and_says_what_to_use() {
for (name, instead) in FORBIDDEN {
let src = format!("module m;\n initial x = {name}();\nendmodule\n");
let found = violations(&src);
assert_eq!(found.len(), 1, "{name}: {found:?}");
assert!(found[0].message.contains(name), "{}", found[0].message);
assert!(found[0].message.contains(instead), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], *name, "the call, underlined");
}
}
#[test]
fn the_replacements_and_their_neighbours_are_left_alone() {
let src = "module m;\n\
initial begin\n\
a = $urandom();\n\
b = $urandom_range(0, 7);\n\
c = $sformatf(\"%0d\", a);\n\
$display(\"%0d\", b);\n\
end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_near_miss_name_is_not_a_hit() {
// Matched whole, not by prefix: `$random_stable` and a signal called
// `random` are neither of them `$random`.
let src = "module m;\n\
logic random;\n\
initial begin\n\
a = $randomize_helper();\n\
b = random;\n\
end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_forbidden_name_inside_a_string_is_data() {
let src = "module m;\n initial $display(\"call $random here\");\nendmodule\n";
assert!(violations(src).is_empty());
}
/// 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));
}
}
@@ -0,0 +1,319 @@
//! `mismatched-labels` — an end label that does not name its own block.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_all_stmts, walk_items};
use vlog_parser::ast::{GenBlock, GenElse, Item, ItemKind, Name, StmtKind};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct MismatchedLabels;
const NAME: &str = "mismatched-labels";
impl Rule for MismatchedLabels {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"make an end label name the block it closes"
}
fn severity(&self) -> Severity {
Severity::Error
}
fn doc(&self) -> &'static str {
"`begin : fetch … end : decode` is a compile error (IEEE 1800 §9.3.4: \
if both labels are given they must be identical), and so is an \
`end : name` on a block that was never labelled. It is the classic \
result of copying a block and renaming only one half — which is also \
why it survives review: the two halves are pages apart. Verible's \
`mismatched-labels` (\"Check for matching begin/end labels.\") is the \
same rule; **lucisv turns it on by default where Verible ships it \
off**, and files it as an **Error** rather than a style finding, \
because the file does not compile.\n\n\
Every construct that may carry a footer label is checked with one \
answer: `module`/`interface`/`program`, `package`, `class`, \
`function`, `task`, `begin`, `fork`/`join`, a generate block, a \
`clocking` block, a `covergroup`, and a `property`/`sequence`. It is \
a comparison of two spellings and nothing more, so an escaped \
identifier is compared as written. No automatic fix: which of the two \
names is the right one is exactly what a linter cannot know."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| item_labels(&mut out, item));
walk_all_stmts(ctx.file(), &mut |stmt| match &stmt.kind {
StmtKind::Block { label, end_label, end_label_span, .. } => {
check_pair(&mut out, label.as_deref(), end_label.as_deref(), *end_label_span, "end")
}
StmtKind::ForkJoin { label, end_label, end_label_span, .. } => check_pair(
&mut out,
label.as_deref(),
end_label.as_deref(),
*end_label_span,
"join",
),
_ => {}
});
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
out
}
}
/// The label pair one item carries, checked. One arm per construct that may
/// write a footer label, so a construct that gains one later has an obvious
/// place to go.
fn item_labels(out: &mut Vec<Violation>, item: &Item) {
match &item.kind {
ItemKind::Module(module) => check_pair(
out,
Some(&module.name),
module.end_label.as_deref(),
module.end_label_span,
match module.kw.as_str() {
"interface" => "endinterface",
"program" => "endprogram",
_ => "endmodule",
},
),
ItemKind::Package { name, end_label, end_label_span, .. } => {
check_pair(out, Some(name), end_label.as_deref(), *end_label_span, "endpackage")
}
ItemKind::Class(class) => check_pair(
out,
Some(&class.name),
class.end_label.as_deref(),
class.end_label_span,
"endclass",
),
ItemKind::Function(decl) => check_pair(
out,
Some(&decl.name),
decl.end_label.as_deref(),
decl.end_label_span,
"endfunction",
),
ItemKind::Task(decl) => check_pair(
out,
Some(&decl.name),
decl.end_label.as_deref(),
decl.end_label_span,
"endtask",
),
ItemKind::Clocking(decl) => check_pair(
out,
decl.name.as_ref().map(|name| name.text.as_str()),
decl.end_label.as_deref(),
decl.end_label_span,
"endclocking",
),
ItemKind::Covergroup(decl) => {
check_name_pair(out, Some(&decl.name.text), decl.end_label.as_ref(), "endgroup")
}
ItemKind::PropSeqDecl(decl) => check_name_pair(
out,
Some(&decl.name.text),
decl.end_label.as_ref(),
if decl.kw == "sequence" { "endsequence" } else { "endproperty" },
),
// The item walk descends into a generate block's *items* but never
// visits the block itself, so its own label pair is collected here.
ItemKind::GenIf(gen_if) => {
check_gen_block(out, &gen_if.then);
let mut els = gen_if.els.as_deref();
while let Some(branch) = els {
match branch {
GenElse::If(_, nested) => {
check_gen_block(out, &nested.then);
els = nested.els.as_deref();
}
GenElse::Block(block) => {
check_gen_block(out, block);
els = None;
}
}
}
}
ItemKind::GenFor(gen_for) => check_gen_block(out, &gen_for.body),
// 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);
}
}
_ => {}
}
}
fn check_gen_block(out: &mut Vec<Violation>, block: &GenBlock) {
check_pair(
out,
block.label.as_deref(),
block.end_label.as_deref(),
block.end_label_span,
"end",
);
}
/// Compares one header/footer pair, when a footer label was written at all.
fn check_pair(
out: &mut Vec<Violation>,
opened: Option<&str>,
closed: Option<&str>,
at: Option<TextRange>,
kw: &'static str,
) {
let (Some(closed), Some(at)) = (closed, at) else { return };
if at.is_empty() {
return;
}
let message = match opened {
Some(opened) if opened == closed => return,
Some(opened) => format!("`{kw} : {closed}` closes `{opened}`"),
None => format!("`{kw} : {closed}` closes a block with no label"),
};
out.push(Violation::new(NAME, message, at));
}
/// The same, for the constructs whose footer label is a [`Name`].
fn check_name_pair(
out: &mut Vec<Violation>,
opened: Option<&str>,
closed: Option<&Name>,
kw: &'static str,
) {
check_pair(
out,
opened,
closed.map(|name| name.text.as_str()),
closed.map(|name| name.span),
kw,
);
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
MismatchedLabels.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_footer_that_names_another_block() {
let src = "module m;\n\
always_comb begin : fetch\n\
x = 1;\n\
end : decode\n\
endmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "decode");
assert!(found[0].message.contains("fetch"), "{}", found[0].message);
assert!(found[0].fix.is_none());
}
#[test]
fn flags_a_footer_label_on_an_unlabelled_block() {
let src = "module m;\n always_comb begin\n x = 1;\n end : blk\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("no label"), "{}", found[0].message);
}
#[test]
fn a_matching_pair_and_a_missing_footer_are_both_fine() {
for src in [
"module m;\n always_comb begin : blk\n x = 1;\n end : blk\nendmodule\n",
"module m;\n always_comb begin : blk\n x = 1;\n end\nendmodule\n",
"module m;\n always_comb begin\n x = 1;\n end\nendmodule\n",
"module m;\nendmodule : m\n",
] {
assert!(violations(src).is_empty(), "{src}: {:?}", violations(src));
}
}
#[test]
fn every_construct_with_a_footer_label_is_checked() {
for (src, wrong) in [
("module m;\nendmodule : other\n", "other"),
("interface i;\nendinterface : other\n", "other"),
("package p;\nendpackage : other\n", "other"),
("class c;\nendclass : other\n", "other"),
("module m;\n function void f();\n endfunction : other\nendmodule\n", "other"),
("module m;\n task t();\n endtask : other\nendmodule\n", "other"),
(
"interface i;\n clocking cb @(posedge clk);\n endclocking : other\nendinterface\n",
"other",
),
(
"module m;\n covergroup cg;\n endgroup : other\nendmodule\n",
"other",
),
(
"module m;\n property p;\n a |-> b;\n endproperty : other\nendmodule\n",
"other",
),
] {
let found = violations(src);
assert_eq!(found.len(), 1, "{src}: {found:?}");
assert_eq!(&src[found[0].span.as_range()], wrong, "{src}");
}
}
#[test]
fn a_fork_join_and_a_generate_block_are_checked() {
let fork = "module m;\n\
initial fork : spawn\n\
x = 1;\n\
join : other\n\
endmodule\n";
assert_eq!(violations(fork).len(), 1, "{:?}", violations(fork));
let generate = "module m;\n\
generate\n\
if (A) begin : g\n\
wire a;\n\
end : other\n\
endgenerate\n\
endmodule\n";
assert_eq!(violations(generate).len(), 1, "{:?}", violations(generate));
}
#[test]
fn a_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\
always_comb begin : outer\n\
begin : inner\n\
x = 1;\n\
end : inner\n\
end : outer\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
}
+62 -4
View File
@@ -1,24 +1,82 @@
//! The rules themselves, one module each.
//!
//! Most rules are **syntactic** — text, tokens or tree shape. The three that
//! are not (`unused-signal`, `undriven-net`, `multiply-driven`) read the
//! symbol table through `crate::signals`; see
//! `docs/features/semantic-lints/README.md`.
//! Most rules are **syntactic** — text, tokens or tree shape. The ones that
//! are not read the symbol table: `unused-signal`, `undriven-net` and
//! `multiply-driven` through `crate::signals` (see
//! `docs/features/semantic-lints/README.md`), and `duplicate-declaration` and
//! `instance-shadowing` through `vlog_semantic::Semantics` directly (see
//! `docs/features/linter-expansion-1/README.md`).
pub mod always_comb;
pub mod always_comb_blocking;
pub mod always_ff_non_blocking;
pub mod banned_declared_name_patterns;
pub mod case_missing_default;
pub mod constraint_name_style;
pub mod 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;
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());
}
}
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_parser::ast::ItemKind;
@@ -19,6 +20,10 @@ impl Rule for ModuleFilename {
"name a one-module file after its module"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"Every Verilog tool that finds a module by searching a library \
directory — simulators, synthesis `-y` paths, most build systems — \
@@ -1,8 +1,10 @@
//! `module-name-style` — module names are `lower_snake_case`.
use crate::context::LintContext;
use crate::naming::{is_escaped, is_lower_snake_case};
use crate::naming::{fits_pattern, is_escaped, style_message};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::ItemKind;
@@ -21,6 +23,10 @@ impl Rule for ModuleNameStyle {
"name modules in lower_snake_case"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A module name ends up as a file name, a directory name, an instance \
path in a waveform viewer and a grep target, and every one of those is \
@@ -31,23 +37,44 @@ impl Rule for ModuleNameStyle {
here, Verible ships no `module-name-style` rule to inherit a default \
from, so enabling it is the user's call — `--select \
module-name-style`. Escaped identifiers (`\\my$mod`) are exempt, and \
there is no fix: renaming a module is a cross-file edit."
there is no fix: renaming a module is a cross-file edit.\n\n\
The shape is the `style_regex` option, default `[a-z][a-z_0-9]*` — \
the preset this rule checked before the option existed. The rule \
judges every `module`, `interface` and `program` name; a project that \
wants the `_if` convention for its interfaces has \
`interface-name-style` for that, and turning both on holds an \
interface to both."
}
fn default_on(&self) -> bool {
false
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str("[a-z][a-z_0-9]*"),
doc: "the pattern a module's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::Module(module) = &item.kind else { return };
if is_escaped(&module.name) || is_lower_snake_case(&module.name) {
if is_escaped(&module.name) || fits_pattern(ctx, NAME, "style_regex", &module.name) {
return;
}
out.push(Violation::new(
NAME,
format!("module `{}` is not lower_snake_case", module.name),
style_message(
ctx,
NAME,
"style_regex",
&format!("module `{}`", module.name),
"is not lower_snake_case",
),
module.name_span,
));
});
@@ -94,4 +121,26 @@ mod tests {
fn it_is_off_by_default() {
assert!(!ModuleNameStyle.default_on());
}
#[test]
fn the_default_pattern_is_the_preset_it_replaced() {
for bad in ["_foo", "FooBar", "fooBar"] {
assert_eq!(violations(&format!("module {bad};\nendmodule\n")).len(), 1, "{bad}");
}
for good in ["foo", "foo_bar", "fifo2_ctrl"] {
assert!(violations(&format!("module {good};\nendmodule\n")).is_empty(), "{good}");
}
}
#[test]
fn a_configured_pattern_replaces_it() {
let mut options = crate::options::RuleOptions::new();
options.set_raw(NAME, "style_regex", "\"[A-Z][A-Za-z0-9]*\"").expect("accepted");
let ctx = LintContext::new("module FooBar;\nendmodule\n", None).with_options(&options);
assert!(ModuleNameStyle.check(&ctx).is_empty());
let ctx = LintContext::new("module foo_bar;\nendmodule\n", None).with_options(&options);
let found = ModuleNameStyle.check(&ctx);
assert_eq!(found.len(), 1);
assert!(found[0].message.contains("[A-Z][A-Za-z0-9]*"), "{}", found[0].message);
}
}
@@ -0,0 +1,103 @@
//! `module-parameter` — override a multi-parameter instance by name.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_instantiations;
use vlog_parser::ast::ListElem;
/// See [`Rule::doc`].
pub struct ModuleParameter;
const NAME: &str = "module-parameter";
impl Rule for ModuleParameter {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"override more than one parameter by name"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"`sub #(8, 4) u ()` binds by *order*, so a parameter added to the \
instantiated module — or two of them reordered — silently changes \
what every instance elaborates to, and two integers in a row give a \
reader nothing to check against. `#(.Width(8), .Depth(4))` names each \
one where it is written. Verible's `module-parameter` (\"Checks that \
module instantiations with more than one parameter are passed in as \
named parameters.\", enabled by default) is the same rule and the \
same default; a single positional override is left alone by both. No \
automatic fix: the names live in the instantiated module, usually in \
another file."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_instantiations(ctx.file(), &mut |inst| {
let Some(params) = &inst.params else { return };
let positional =
params.iter().filter_map(ListElem::ok).filter(|conn| conn.name.is_empty()).count();
if positional < 2 {
return;
}
out.push(Violation::new(
NAME,
format!("`{}` takes {positional} parameters by position; name them", inst.module),
inst.module_span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ModuleParameter.check(&LintContext::new(src, None))
}
#[test]
fn flags_more_than_one_positional_override() {
let src = "module m;\n sub #(8, 4) u_sub ();\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`sub`"), "{}", found[0].message);
assert!(found[0].message.contains("2 parameters"), "{}", found[0].message);
assert!(found[0].fix.is_none());
}
#[test]
fn a_named_override_is_what_the_rule_wants() {
let src = "module m;\n sub #(.Width(8), .Depth(4)) u_sub ();\nendmodule\n";
assert!(violations(src).is_empty());
}
#[test]
fn one_override_or_none_has_no_order_to_get_wrong() {
assert!(violations("module m;\n sub #(8) u ();\nendmodule\n").is_empty());
assert!(violations("module m;\n sub #() u ();\nendmodule\n").is_empty());
assert!(violations("module m;\n sub u ();\nendmodule\n").is_empty());
}
#[test]
fn a_bind_and_a_generate_body_are_both_reached() {
assert_eq!(violations("bind top sub #(8, 4) u ();\n").len(), 1);
let generate = "module m;\n\
generate\n\
if (A) begin : g\n\
sub #(8, 4) u ();\n\
end\n\
endgenerate\n\
endmodule\n";
assert_eq!(violations(generate).len(), 1);
}
}
+119
View File
@@ -0,0 +1,119 @@
//! `module-port` — connect a multi-port instance by name.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_instantiations;
use vlog_parser::ast::Connections;
/// See [`Rule::doc`].
pub struct ModulePort;
const NAME: &str = "module-port";
impl Rule for ModulePort {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"connect an instance with more than one port by name"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A positional connection list binds by *order*, so inserting a port in \
the instantiated module silently rewires every instance of it — and \
two ports of the same width swapped by hand compile perfectly and \
fail in simulation. A named list (`.clk_i(clk)`) says what is \
connected to what at the site, breaks loudly when a port is renamed, \
and is what every reviewer can check without opening the other file. \
Verible's `module-port` (\"Checks that module instantiations with \
more than one port are passed in as named ports.\", enabled by \
default) is the same rule and the same default; a single-port \
instance is left alone by both, because there is no order to get \
wrong. No automatic fix: naming the ports needs the instantiated \
module's port list, which is usually in another file."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_instantiations(ctx.file(), &mut |inst| {
for instance in &inst.instances {
let Connections::Ordered(conns) = &instance.conns else { continue };
if conns.len() < 2 {
continue;
}
out.push(Violation::new(
NAME,
format!(
"`{}` is connected by position; name its {} ports",
inst.module,
conns.len()
),
instance.span,
));
}
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ModulePort.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_positional_list_of_more_than_one() {
let src = "module m;\n sub u_sub (a, b, c);\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`sub`"), "{}", found[0].message);
assert!(found[0].message.contains("3 ports"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "u_sub (a, b, c)");
assert!(found[0].fix.is_none());
}
#[test]
fn a_named_list_is_what_the_rule_wants() {
let src = "module m;\n sub u_sub (.a(x), .b(y), .c(z));\nendmodule\n";
assert!(violations(src).is_empty());
// `.*` is a named list too.
assert!(violations("module m;\n sub u_sub (.*);\nendmodule\n").is_empty());
}
#[test]
fn one_port_or_none_has_no_order_to_get_wrong() {
assert!(violations("module m;\n sub u_sub (a);\nendmodule\n").is_empty());
assert!(violations("module m;\n sub u_sub ();\nendmodule\n").is_empty());
}
#[test]
fn every_instance_of_one_statement_is_judged() {
let src = "module m;\n sub u1 (a, b), u2 (.a(x), .b(y)), u3 (c, d);\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 2, "{found:?}");
assert!(found[0].span.start < found[1].span.start, "in source order");
}
#[test]
fn an_instantiation_inside_generate_and_a_bind_are_both_reached() {
let generate = "module m;\n\
generate\n\
if (A) begin : g\n\
sub u (a, b);\n\
end\n\
endgenerate\n\
endmodule\n";
assert_eq!(violations(generate).len(), 1);
assert_eq!(violations("bind top sub u (a, b);\n").len(), 1);
}
}
@@ -4,6 +4,7 @@ use std::collections::BTreeSet;
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::signals::{Driver, DriverKind};
use crate::violation::Violation;
@@ -21,6 +22,10 @@ impl Rule for MultiplyDriven {
"give a variable exactly one driver"
}
fn severity(&self) -> Severity {
Severity::Error
}
fn doc(&self) -> &'static str {
"A SystemVerilog *variable* — `logic`, `reg`, `int` — may be written \
from one source only (IEEE 1800 §6.5). Two `always` blocks assigning \
+5
View File
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use vlog_parser::span::TextRange;
@@ -19,6 +20,10 @@ impl Rule for NoTabs {
"use spaces, not tabs"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A tab renders at a width nobody agrees on, so a file mixing tabs and \
spaces looks aligned in the editor that wrote it and ragged everywhere \
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use vlog_parser::span::TextRange;
@@ -19,6 +20,10 @@ impl Rule for NoTrailingWhitespace {
"no whitespace at the end of a line"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"Trailing whitespace is invisible, so it survives review and then shows \
up as diff noise the day somebody's editor strips it — a one-character \
@@ -0,0 +1,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());
}
}
Loaded 100 of 219 files, more files were not shown because too many files have changed in this diff. Show more