Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a896e0dff0 | ||
|
|
0cb398bcd9 | ||
|
|
17697b9d77 | ||
|
|
5e5813a2a9 | ||
|
|
bafc1b425b | ||
|
|
8c61570a04 | ||
|
|
7c4bdbcfea | ||
|
|
e902af37c5 | ||
|
|
4ba6eafa2d | ||
|
|
747ae02b0e | ||
|
|
ffbb29ddbb | ||
|
|
f1d44a2a0c | ||
|
|
10b63e665d | ||
|
|
a648561f63 | ||
|
|
6a15594ae8 |
No files matched your search
@@ -4,6 +4,104 @@ All notable changes to lucisv are recorded here. Versions follow
|
||||
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
|
||||
(see `README.md`) are the only frozen contract.
|
||||
|
||||
## 0.38.0 — 2026-09-04
|
||||
|
||||
### Lint rule options, and the Style family
|
||||
|
||||
**Per-rule options.** A rule that takes options can be configured in
|
||||
`lucisv.toml` (`[lint.line-length] length = 120`,
|
||||
`[lint.signal-name-style] style_regex = "[a-z_0-9]+"`) and from the
|
||||
editor (`lucisv.lint.options`, one object keyed by rule). Both doors run
|
||||
one validator: a bad key, kind, range or pattern fails `lucisv check`
|
||||
naming the file and line, and is logged and dropped in the editor so a
|
||||
typo cannot switch a rule off. Editor options win over `lucisv.toml`,
|
||||
key by key. `--rules-doc` lists every option with its kind and default.
|
||||
Patterns use a small built-in regex dialect (literals, `.`, classes,
|
||||
groups, alternation, `* + ?`, `\d \w \s`), whole-name anchored, run as
|
||||
a linear-time automaton so no pattern can slow a lint run; anything
|
||||
outside the dialect is refused by name.
|
||||
|
||||
**Eighteen new Style rules** (54 in all): `line-length` (the
|
||||
formatter's width), `posix-eof` (safe fix), `forbid-consecutive-null-
|
||||
statements` (safe fix), `generate-label`, `generate-label-prefix`,
|
||||
`package-filename`, `one-module-per-file` (off), `signal-name-style`
|
||||
(off), `interface-name-style`, `macro-name-style`,
|
||||
`constraint-name-style`, `parameter-type-name-style` (off),
|
||||
`port-name-suffix` (off), `banned-declared-name-patterns` (off),
|
||||
`typedef-enums`, `typedef-structs-unions`, `always-comb` (unsafe fix),
|
||||
`explicit-begin` (off). The four existing naming rules take Verible's
|
||||
option spellings. `typedef-structs-unions` allows a nested anonymous
|
||||
aggregate by default — a deliberate divergence from Verible, because
|
||||
every one of its 3 159 findings on opentitan was a generated register
|
||||
package; `allow_anonymous_nested = false` restores the stricter reading.
|
||||
|
||||
Every rule's toggle in VS Code is regenerated from the registry.
|
||||
|
||||
## 0.37.0 — 2026-09-04
|
||||
|
||||
### Typing a header no longer loses the module
|
||||
|
||||
While you type a port list, a parameter list, a function's argument
|
||||
list, an instantiation's connections, or the header of a `for`/`if`/
|
||||
`while`/`case`, the editor used to lose the whole surrounding module or
|
||||
function: its body re-parsed at file scope, its symbols vanished from
|
||||
the outline and from completion, and the orphaned `endmodule` produced a
|
||||
second error. Recovery now happens inside the list: the element that
|
||||
failed becomes an error element, the ones you already typed stay, the
|
||||
header keeps its node, and the body binds in the right scope. One
|
||||
diagnostic per typo. The strict parse (what the formatter uses) is
|
||||
untouched, so every corpus file formats byte for byte as before.
|
||||
|
||||
Measured over the corpus with every file cut in half: error nodes fall
|
||||
by 11 %; diagnostics rise by 7 % because a module whose header was cut
|
||||
now survives to report its missing `endmodule` instead of vanishing
|
||||
into one error node. Known gap: a half-typed `#(` override whose value
|
||||
can read as a call still collapses its instantiation (filed).
|
||||
|
||||
## 0.36.1 — 2026-09-04
|
||||
|
||||
The 0.36.0 tag never published: its release commit shipped without a
|
||||
CHANGELOG section (the release chain's draft lived in a session
|
||||
scratchpad that a crash had wiped), and the release workflow refuses a
|
||||
version without notes, as designed. 0.36.1 is 0.36.0 plus these notes.
|
||||
|
||||
## 0.36.0 — 2026-09-03
|
||||
|
||||
### The linter grows up: severities, per-rule toggles, and 19 new rules
|
||||
|
||||
Every lint rule now has a **severity** — `error` (would likely fail to
|
||||
compile or elaborate, or silently mis-synthesize), `warning` (a probable
|
||||
bug) or `style` — printed in `lucisv check` output
|
||||
(`FILE:LINE:COL: warning: message [rule]`), carried in the JSON output,
|
||||
mapped to red / yellow / blue in the editor, and shown in
|
||||
`--rules-doc`, which now groups rules by class. `--select`, `--ignore`
|
||||
and `[lint]` in `lucisv.toml` accept a severity word (`--ignore style`).
|
||||
|
||||
**Editor toggles.** VS Code settings gain three master switches
|
||||
(`lucisv.lint.severity.error`, `.warning`, `.style`) and one setting per
|
||||
rule (`lucisv.lint.rules.<rule>`: `default` / `on` / `off`), generated
|
||||
from the rule registry so the list can never drift. Precedence, top to
|
||||
bottom: defaults → `select` → severity switches → per-rule settings →
|
||||
`ignore`. Changing any of them re-checks every open file.
|
||||
|
||||
**New rules — Error**: `mismatched-labels`, `duplicate-declaration`,
|
||||
`undeclared-identifier` (with a project; silent for names that come
|
||||
from macros, `` `include``d fragments or hierarchical paths),
|
||||
`unknown-port`, `unknown-parameter`.
|
||||
**New rules — Warning**: `forbid-defparam`, `invalid-system-task-function`,
|
||||
`truncated-numeric-literal`, `undersized-binary-literal` (safe fix pads),
|
||||
`suspicious-semicolon`, `packed-dimensions-range-ordering`, `module-port`,
|
||||
`module-parameter`, `explicit-function-task-parameter-type`,
|
||||
`plusarg-assignment`, `instance-shadowing`, `forbid-negative-array-dim`,
|
||||
`void-cast`, `incomplete-assignment` (latch inference in `always_comb`).
|
||||
Verible equivalents are named in each rule's documentation; defaults
|
||||
follow Verible's except where the doc says why not. Existing rules
|
||||
re-classified: `multiply-driven` and `wire-reg-mixup` are errors.
|
||||
|
||||
Measured on opentitan: every false-positive class found was closed with
|
||||
a test; `lucisv check` over its `hw/` tree runs in the same time as
|
||||
0.35.0.
|
||||
|
||||
## 0.35.0 — 2026-09-02
|
||||
|
||||
### Format fences reach statements and class bodies
|
||||
|
||||
Generated
+8
-8
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.36.0"
|
||||
version = "0.38.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.36.0"
|
||||
version = "0.38.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.36.0"
|
||||
version = "0.38.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.36.0"
|
||||
version = "0.38.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.36.0"
|
||||
version = "0.38.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -264,11 +264,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.36.0"
|
||||
version = "0.38.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.36.0"
|
||||
version = "0.38.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
@@ -276,7 +276,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.36.0"
|
||||
version = "0.38.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.36.0"
|
||||
version = "0.38.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -251,6 +251,24 @@ makes an editor's red squiggle worth believing.
|
||||
| `struct-union-name-style` | style | — | `lower_snake_case` ending `_t` |
|
||||
| `parameter-name-style` | style | — | `CamelCase` or `ALL_CAPS` |
|
||||
| `module-name-style` | style | — | `lower_snake_case` (off by default) |
|
||||
| `line-length` | style | — | no line wider than the width the formatter uses |
|
||||
| `posix-eof` | style | safe | the file ends with a newline |
|
||||
| `forbid-consecutive-null-statements` | style | safe | no `;;` where a statement belongs |
|
||||
| `generate-label` | style | — | every generate block carries a `: label` |
|
||||
| `generate-label-prefix` | style | — | that label starts with `g_` or `gen_` |
|
||||
| `package-filename` | style | — | a one-package file is named after its package |
|
||||
| `interface-name-style` | style | — | `lower_snake_case` ending `_if` |
|
||||
| `macro-name-style` | style | — | a `` `define`` name is `ALL_CAPS` |
|
||||
| `constraint-name-style` | style | — | `lower_snake_case` ending `_c` |
|
||||
| `typedef-enums` | style | — | an `enum` type is named with a `typedef` |
|
||||
| `typedef-structs-unions` | style | — | a `struct`/`union` type is named with a `typedef` |
|
||||
| `always-comb` | style | unsafe | `always_comb`, not `always @*` |
|
||||
| `signal-name-style` | style | — | `lower_snake_case` signals (off by default) |
|
||||
| `parameter-type-name-style` | style | — | `lower_snake_case` ending `_t` type parameters (off) |
|
||||
| `port-name-suffix` | style | — | `_i` / `_o` / `_io` say which way a port points (off) |
|
||||
| `one-module-per-file` | style | — | one `module` per file (off by default) |
|
||||
| `banned-declared-name-patterns` | style | — | no declared name matching a project's own list (off) |
|
||||
| `explicit-begin` | style | safe | every body is a `begin ... end` block (off by default) |
|
||||
| `unused-waiver` | style | — | waivers that suppress nothing |
|
||||
|
||||
† On by default when lucisv can see a project (a multi-file CLI run or the
|
||||
@@ -266,11 +284,77 @@ its default, its fix and the paragraph saying why it exists — generated from
|
||||
the registry, so it can never be out of date.
|
||||
|
||||
Fixes follow ruff's applicability model: `--fix` applies *safe* fixes (those
|
||||
that cannot change what the code means), `--unsafe-fixes` widens that — no
|
||||
rule ships an unsafe fix yet. Violations inside a `// verilog_format: off`
|
||||
that cannot change what the code means), `--unsafe-fixes` widens that to the
|
||||
rest. One rule ships an unsafe fix: `always-comb` rewrites `always @*` to
|
||||
`always_comb`, which is a different block at time zero and makes a second
|
||||
driver of its outputs an error — right nearly always, and not lucisv's call to
|
||||
make without being asked. Violations inside a `// verilog_format: off`
|
||||
region are reported but never fixed: `off` means hands-off for the linter too,
|
||||
so `--fix` leaves every byte of a fenced region exactly as written.
|
||||
|
||||
### Rule options
|
||||
|
||||
A rule can be configured in a `[lint.<rule-name>]` table:
|
||||
|
||||
```toml
|
||||
[lint]
|
||||
ignore = ["typedef-structs-unions"]
|
||||
|
||||
[lint.line-length]
|
||||
length = 120 # the linter's limit, if not the formatter's
|
||||
|
||||
[lint.generate-label-prefix]
|
||||
prefix = ["g_", "gen_"] # the label prefixes this project writes
|
||||
|
||||
[lint.parameter-name-style]
|
||||
localparam_style = "CamelCase" # Verible's own default, stricter than ours
|
||||
|
||||
[lint.signal-name-style]
|
||||
style_regex = "[a-z][a-z_0-9]*" # a pattern, matched against the whole name
|
||||
```
|
||||
|
||||
The keys are Verible's wherever it has the same option, so a `.rules.verible`
|
||||
file translates word for word. An option nobody sets reads the default
|
||||
`lucisv check --rules-doc` prints beside it. An unknown rule or option name, a
|
||||
value of the wrong kind, an integer out of range or a pattern that does not
|
||||
compile **fails the run**, naming the config file and the line — a typo in a
|
||||
lint setting is not something to guess at.
|
||||
|
||||
Patterns are not full RE2. What is supported: literals, `.`, `[...]` classes
|
||||
with ranges and negation, the escapes `\d \D \w \W \s \S` (character
|
||||
classes), `\n \t \r` (control characters) and `\<punctuation>` (that
|
||||
character, literally), groups, `|`, and the postfix `*` `+` `?` — matched
|
||||
against the **whole** name, so `^`/`$` are accepted and redundant.
|
||||
|
||||
Everything else is **refused when the option is read, by name**: counted
|
||||
repetition (`{2,3}`), lookaround and flag groups (`(?=…)`, `(?:…)`), and every
|
||||
escape not listed above — a backreference (`\1`), a word boundary (`\b`),
|
||||
`\A`, `\z`, `\p{…}`, `\x41`. An unsupported escape read as a literal would
|
||||
quietly judge the wrong names (`\bword\b` would match `bwordb`), which is
|
||||
worse than an error you can read.
|
||||
|
||||
Matching is a Thompson-NFA simulation, so it is linear in pattern × name
|
||||
length whatever shape the pattern has: no pattern can make `lucisv check` — or
|
||||
an editor session — hang.
|
||||
|
||||
From an editor the same options are one object, `lucisv.lint.options`:
|
||||
|
||||
```json
|
||||
"lucisv.lint.options": {
|
||||
"line-length": { "length": 120 },
|
||||
"typedef-structs-unions": { "allow_anonymous_nested": false }
|
||||
}
|
||||
```
|
||||
|
||||
There the precedence is **the editor's value, then the `lucisv.toml`, then the
|
||||
rule's default — key by key**: a project can set two options and one user
|
||||
override the third without losing the others. (This is the opposite order to
|
||||
the formatting settings, where a checked-in `lucisv.toml` outranks the editor:
|
||||
formatting has a byte-exact contract with CI, and which findings you are shown
|
||||
in your own editor is yours to choose.) A bad entry there is *ignored* and
|
||||
reported in the lucisv log rather than fatal, so one typo cannot leave a
|
||||
session with no diagnostics.
|
||||
|
||||
### Waivers
|
||||
|
||||
```systemverilog
|
||||
|
||||
@@ -3454,21 +3454,24 @@ only), crates/lucisv_server/src/perf.rs (measurement only), docs/
|
||||
features/header-recovery/README.md (new), amendments in error-recovery
|
||||
README, docs/coverage_gaps.md M10, TODO §32. Runs after §31 (parser +
|
||||
formatter collide with §30's tf.rs/module.rs at merge; sequential).
|
||||
- [ ] 32.1 error elements in the four list types + `ExprKind::Error`;
|
||||
cross-crate arms pre-agreed
|
||||
- [ ] 32.2 `element_or_recover` with the list-local, bracket-seeded
|
||||
- [x] 32.1 error elements in the four list types + `ExprKind::Error`;
|
||||
cross-crate arms pre-agreed — one generic `ListElem<T>` over five
|
||||
lists (a class's parameter ports are the fifth)
|
||||
- [x] 32.2 `element_or_recover` with the list-local, bracket-seeded
|
||||
sync set (`,` `)` `;` line change)
|
||||
- [ ] 32.3 headers keep their node (port, param, tf-port, connection
|
||||
- [x] 32.3 headers keep their node (port, param, tf-port, connection
|
||||
lists infallible in tolerant mode; closers via `expect_closer`)
|
||||
- [ ] 32.4 `for`/`if`/`while`/`case` conditions recover inside the
|
||||
parentheses
|
||||
- [ ] 32.5 parser pins per shape with exact counts; walkers extended;
|
||||
- [x] 32.4 `for`/`if`/`while`/`case` conditions recover inside the
|
||||
parentheses (`repeat` and `do…while` too, same helper)
|
||||
- [x] 32.5 parser pins per shape with exact counts; walkers extended;
|
||||
550-source equality and the fuzzers green
|
||||
- [ ] 32.6 server pins: symbols survive, completion scope survives, one
|
||||
- [x] 32.6 server pins: symbols survive, completion scope survives, one
|
||||
diagnostic, validity probes unchanged
|
||||
- [ ] 32.7 docs + measurements (parse_tolerant timing, truncated-corpus
|
||||
diagnostic census)
|
||||
- [ ] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
|
||||
- [x] 32.7 docs + measurements (parse_tolerant timing, truncated-corpus
|
||||
diagnostic census — error nodes 622 → 555, diagnostics 1 702 →
|
||||
1 826: the constructs that now survive report their own missing
|
||||
closers)
|
||||
- [x] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
|
||||
byte-identical (strict path untouched); opentitan read-only sweep
|
||||
unchanged
|
||||
- [ ] QA: type each of the (a)–(f) shapes into the real server against
|
||||
@@ -3647,28 +3650,130 @@ linter-expansion-1/README.md (new), TODO §33. Worktree `lint-1`.
|
||||
near-misses; the false-positive census re-read; toggles exercised
|
||||
through the real server (`workspace/didChangeConfiguration`)
|
||||
|
||||
## 34. Linter expansion, wave 2 (planned 2026-09-02, after §33) — the Style class and per-rule options
|
||||
## 34. Linter expansion, wave 2 (planned 2026-09-03) — per-rule options, and the first eighteen Style rules
|
||||
|
||||
The style family from Verible, with the per-rule configuration the
|
||||
naming rules need: `signal-name-style`, `interface-name-style`,
|
||||
`macro-name-style`, `constraint-name-style`, `parameter-type-name-style`,
|
||||
`dff-name-style`, `port-name-suffix`, `banned-declared-name-patterns`
|
||||
(each with a `pattern`/style option), `line-length` (reads the
|
||||
formatter's `line-length`), `posix-eof` (safe fix), `endif-comment`,
|
||||
`forbid-line-continuations`, `one-module-per-file`, `package-filename`,
|
||||
`typedef-enums`, `typedef-structs-unions`, `module-begin-block`,
|
||||
`generate-label` + `generate-label-prefix`, `always-comb` (`@*` →
|
||||
`always_comb`, safe fix), `legacy-generate-region`,
|
||||
`legacy-genvar-declaration`, `v2001-generate-begin`,
|
||||
After §33 (36 rules, severities, toggles). Two things this wave adds:
|
||||
the **option plumbing** every configurable rule needs, and the Style
|
||||
rules from Verible's list that carry the most weight in a style guide
|
||||
(naming, file layout, generate labels, typedefs, line length). Dev
|
||||
Opus 5, QA Sonnet 5. Feature README: `docs/features/linter-expansion-2/
|
||||
README.md`. Mapped: `lucisv_core::config` parses one table, `[lint]`,
|
||||
with `select`/`ignore`, and rejects `[lint.<rule>]` by name
|
||||
(`config.rs::parse_entry`: "per-rule lint settings … are not supported
|
||||
yet"); the editor has `lucisv.lint.select/ignore/severity.*/rules.*`;
|
||||
`Rule` has no notion of options; `LintContext` carries source, tokens,
|
||||
tree, semantics slot and the oracle; `line-length` already lives in
|
||||
`FileConfig` for the formatter.
|
||||
|
||||
**34.0 Options, end to end.**
|
||||
(a) `vlog_linter`: `pub struct OptionSpec { name: &'static str, kind:
|
||||
OptionKind (Bool | Int { min, max } | Str | Regex | List), default:
|
||||
OptionValue, doc: &'static str }` and `Rule::options(&self) ->
|
||||
&'static [OptionSpec]` (default empty); `RuleOptions` — a validated
|
||||
map `rule → key → OptionValue` built by `RuleOptions::parse(rule, key,
|
||||
raw)` that rejects an unknown key ("rule `x` has no option `y`; it has:
|
||||
…"), a wrong kind, an out-of-range int or an invalid regex, each with
|
||||
the message the two front ends print with file and line. `LintContext`
|
||||
carries `&RuleOptions`; a rule reads `ctx.option_str(NAME, "pattern")`
|
||||
etc. with the spec's default as the fallback, so a rule never sees
|
||||
"unset". (b) `lucisv_core::config`: `[lint.<rule>]` tables accepted —
|
||||
`key = value` for bool/int/string, `key = ["a", "b"]` for lists —
|
||||
stored raw in `FileConfig::lint_options: Vec<(rule, key, raw, line)>`
|
||||
(the core crate does not know the rules); the CLI resolves them
|
||||
against the registry per file the way `[lint] select` names are
|
||||
checked, failing the run with file:line on the first bad entry. (c)
|
||||
Editor: `lucisv.lint.options` (object; `{"<rule>": {"<key>": value}}`,
|
||||
`additionalProperties`), parsed in `settings.rs`, validated the same
|
||||
way — a bad entry is a `window/logMessage` warning and is ignored, so
|
||||
one typo cannot switch the linter off; republish on change. (d)
|
||||
Precedence: editor options over `lucisv.toml` options over the spec
|
||||
default, key by key (the same ladder `lucisv.lineLength` uses — cite
|
||||
`format::settings_for`). (e) `--rules-doc` lists each rule's options
|
||||
with kind, default and doc; the VS Code generator emits nothing per
|
||||
option (the object setting covers them) but its description names the
|
||||
options each rule takes. (f) Pins: parse/validate table tests; a
|
||||
`lucisv.toml` with `[lint.line-length] length = 120` changes the
|
||||
verdict; the editor object does the same over the wire; a bad key
|
||||
fails the CLI naming file:line and only logs in the editor.
|
||||
|
||||
**34.1 Options on the existing naming rules** (so the family is
|
||||
consistent before the new members arrive): `enum-name-style`,
|
||||
`struct-union-name-style`, `module-name-style`, `parameter-name-style`
|
||||
gain the option Verible gives them (`style_regex`; `parameter-name-
|
||||
style` gets `localparam_style`/`parameter_style` with Verible's
|
||||
`CamelCase|ALL_CAPS` vocabulary plus the `_regex` overrides); defaults
|
||||
reproduce today's behaviour exactly (pin: the corpus and opentitan
|
||||
finding lists are byte-identical with no options set).
|
||||
|
||||
**34.2 New Style rules** (Verible name; default there → here; options):
|
||||
- `line-length` (on; `length`, default = the formatter's configured
|
||||
`line-length`, else 100) — a token-aware check that ignores a line
|
||||
that is one unbreakable token (a long string or macro invocation),
|
||||
as Verible does.
|
||||
- `posix-eof` (on; safe fix appends the newline).
|
||||
- `forbid-consecutive-null-statements` (on; safe fix) — `;;` at
|
||||
statement level, the statement twin of `empty-item`.
|
||||
- `generate-label` (on) and `generate-label-prefix` (on; `prefix`
|
||||
list, default `g_`/`gen_`).
|
||||
- `package-filename` (on; `allow-dash-for-underscore`, same as
|
||||
`module-filename`).
|
||||
- `one-module-per-file` (off).
|
||||
- `signal-name-style` (off; `style_regex`, default `[a-z_0-9]+`).
|
||||
- `interface-name-style` (on; `style_regex`, default `[a-z_0-9]+(_if)`).
|
||||
- `macro-name-style` (on; `style_regex`, default `[A-Z_0-9]+`; the
|
||||
macro's own name from the `` `define`` table).
|
||||
- `constraint-name-style` (on; `pattern`, default `([a-z0-9]+_)+c`).
|
||||
- `parameter-type-name-style` (off; lower_snake + `_t`).
|
||||
- `port-name-suffix` (off; `_i`/`_o`/`_io`/`_ni`/`_no`/`_nio` per
|
||||
Verible; option `suffixes` list).
|
||||
- `banned-declared-name-patterns` (off; `patterns` list of regexes).
|
||||
- `typedef-enums` (on) and `typedef-structs-unions` (on;
|
||||
`allow_anonymous_nested`).
|
||||
- `always-comb` (on; **unsafe** fix rewriting `always @*`/`@(*)` to
|
||||
`always_comb` — the two are not identical at time zero, so the fix is
|
||||
offered but not applied by default).
|
||||
- `explicit-begin` (off; the eleven `*_enable` bool options Verible
|
||||
has; safe fix wraps the body in `begin`/`end`).
|
||||
Each: its own file, true positives and near-misses, a `.lint` case,
|
||||
corpus + opentitan counts with ten findings read and classified;
|
||||
opentitan is Verible-clean for its `dvsim` filesets, so a
|
||||
Verible-default rule that fires inside them needs an explanation.
|
||||
|
||||
**34.3 Docs and toggles.** The VS Code generator regenerates the 18 new
|
||||
`lucisv.lint.rules.*` entries (the drift test enforces it); README.md
|
||||
"Linting" gains the options section and the rows; `editors/vscode/
|
||||
README.md` documents `lucisv.lint.options`; the docs-site rules page
|
||||
gains the sections; CHANGELOG untouched (the lead writes it).
|
||||
Remaining Verible rules — `module-begin-block`, `legacy-generate-
|
||||
region`, `legacy-genvar-declaration`, `v2001-generate-begin`,
|
||||
`explicit-function-lifetime`/`explicit-task-lifetime`,
|
||||
`positive-meaning-parameter-name`, `suggest-parentheses`,
|
||||
`forbid-consecutive-null-statements`, `unpacked-dimensions-range-
|
||||
ordering`, `uvm-macro-semicolon`, `create-object-name-match`,
|
||||
`numeric-format-string-style`, `macro-string-concatenation`,
|
||||
`disable-statement`, `forbidden-macro`/`forbidden-symbol` (list
|
||||
options). Options: `[lint.<rule>]` tables in `lucisv.toml` (today
|
||||
rejected by name — the parser exists) and `lucisv.lint.options.<rule>`
|
||||
in the editor, validated against a per-rule option schema declared by
|
||||
the rule (`Rule::options() -> &[OptionSpec]`), shown in `--rules-doc`.
|
||||
Detailed plan to be written when §33 lands.
|
||||
`unpacked-dimensions-range-ordering`, `uvm-macro-semicolon`,
|
||||
`create-object-name-match`, `numeric-format-string-style`,
|
||||
`macro-string-concatenation`, `disable-statement`, `forbidden-macro`/
|
||||
`forbidden-symbol`, `endif-comment`, `forbid-line-continuations`,
|
||||
`dff-name-style`, `proper-parameter-declaration` — are §35, wave 3.
|
||||
|
||||
Files: crates/vlog_linter/src/{registry.rs (OptionSpec, options()),
|
||||
options.rs (new: OptionKind/OptionValue/RuleOptions), context.rs,
|
||||
rule_docs.rs, vscode.rs, lib.rs, rules/<new>.rs, rules/<naming>.rs}
|
||||
+ tests/cases/*.lint, crates/lucisv_core/src/config.rs (+ tests),
|
||||
crates/lucisv/src/{lint.rs, args.rs?} + tests, crates/lucisv_server/
|
||||
src/{settings.rs, lint.rs} + tests, editors/vscode/{package.json,
|
||||
README.md}, README.md "Linting", docs/site/.../reference/rules.md,
|
||||
docs/features/linter-expansion-2/README.md (new), TODO §34. Worktree
|
||||
`lint-2`; disjoint from §32 (parser) so the two may run in parallel.
|
||||
Every suite and sweep under `tools/guard.sh`.
|
||||
- [x] 34.0 options end to end (spec, validation, toml table, editor
|
||||
object, precedence, --rules-doc); pins
|
||||
- [x] 34.1 options on the four existing naming rules; defaults
|
||||
byte-identical
|
||||
- [x] 34.2 the eighteen Style rules, each with tests, counts and ten
|
||||
classified findings
|
||||
- [x] 34.3 docs + regenerated toggles
|
||||
- [x] Gates (guarded): fmt/clippy/`cargo test --workspace`; corpus
|
||||
814/820 byte-identical; vsix smoke; opentitan read-only census +
|
||||
timing vs 0.36.0
|
||||
- [ ] QA: options attacked (bad key/kind/range/regex on both front
|
||||
ends), every rule with near-misses, the census re-read
|
||||
|
||||
+52
-10
@@ -14,7 +14,9 @@ use rayon::prelude::*;
|
||||
use vlog_formatter::fence::{self, Region};
|
||||
use vlog_formatter::Config;
|
||||
use vlog_linter::words;
|
||||
use vlog_linter::{apply_fixes, lint, Fix, MentionOracle, ParsedSource, Rule, Violation};
|
||||
use vlog_linter::{
|
||||
apply_fixes, lint, Fix, MentionOracle, ParsedSource, Rule, RuleOptions, Violation,
|
||||
};
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
use crate::args::{Options, OutputFormat};
|
||||
@@ -31,6 +33,9 @@ pub struct Job {
|
||||
path: PathBuf,
|
||||
config: Config,
|
||||
rules: Vec<&'static dyn Rule>,
|
||||
/// What this file's `lucisv.toml` configured about each rule, validated
|
||||
/// against the registry when the run was planned.
|
||||
options: RuleOptions,
|
||||
}
|
||||
|
||||
/// A whole `lucisv check` run: what to lint, and what the project says about
|
||||
@@ -163,7 +168,8 @@ pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Res
|
||||
let ignore = pick(&opts.ignore, file_config.lint_ignore.as_deref());
|
||||
let rules = vlog_linter::select_rules(select, ignore, workspace)
|
||||
.map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
jobs.push(Job { path, config, rules });
|
||||
let options = rule_options(&file_config)?;
|
||||
jobs.push(Job { path, config, rules, options });
|
||||
}
|
||||
let wanted = jobs.iter().any(|job| job.rules.iter().any(|rule| rule.needs_workspace()));
|
||||
let interfaces = jobs.iter().any(|job| job.rules.iter().any(|rule| reads_interfaces(*rule)));
|
||||
@@ -171,6 +177,30 @@ pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Res
|
||||
Ok(Plan { jobs, census })
|
||||
}
|
||||
|
||||
/// The `[lint.<rule>]` entries of one file's config, resolved against the
|
||||
/// registry.
|
||||
///
|
||||
/// The names and the values are checked **here**, where the registry is, and
|
||||
/// the first bad entry fails the run naming the config file and the line it
|
||||
/// was written on — the same treatment a bad `[lint] select` name gets, and
|
||||
/// for the same reason: a user typed it and is watching.
|
||||
pub fn rule_options(file_config: &FileConfig) -> Result<RuleOptions, String> {
|
||||
let mut options = RuleOptions::new();
|
||||
for entry in &file_config.lint_options {
|
||||
options.set_raw(&entry.rule, &entry.key, &entry.raw).map_err(|e| {
|
||||
let file = file_config
|
||||
.source
|
||||
.as_ref()
|
||||
.map_or_else(|| "lucisv.toml".to_string(), |path| path.display().to_string());
|
||||
// The rule is named as well as the option: the table header two
|
||||
// lines up says which rule it is, and an error a user reads out
|
||||
// of a CI log has no table header beside it.
|
||||
format!("{file}:{}: rule `{}` {e}", entry.line, entry.rule)
|
||||
})?;
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
/// Whether this rule reads the census's **interface** half, which costs a
|
||||
/// parse of every file in the run rather than a lex.
|
||||
///
|
||||
@@ -215,7 +245,9 @@ pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
|
||||
let mut reports: Vec<Report> = plan
|
||||
.jobs
|
||||
.par_iter()
|
||||
.map(|job| check_one(&job.path, &job.config, opts, &job.rules, plan.census.as_ref()))
|
||||
.map(|job| {
|
||||
check_one(&job.path, &job.config, opts, &job.rules, &job.options, plan.census.as_ref())
|
||||
})
|
||||
.collect();
|
||||
// Diagnostics are printed sorted by path, then by position within the
|
||||
// file (`lint` already sorts those), so a run over a directory reads
|
||||
@@ -231,10 +263,11 @@ pub fn check_stdin(
|
||||
src: &str,
|
||||
config: &Config,
|
||||
rules: &[&'static dyn Rule],
|
||||
options: &RuleOptions,
|
||||
) -> ExitCode {
|
||||
let name = opts.stdin_filename.clone().unwrap_or_else(|| "<stdin>".to_string());
|
||||
let path = opts.stdin_filename.as_ref().map(PathBuf::from);
|
||||
let (violations, lex_error) = run_rules(src, path, config, rules, None);
|
||||
let (violations, lex_error) = run_rules(src, path, config, rules, options, None);
|
||||
// Nothing is ever written back for stdin, so `--fix` has nothing to do
|
||||
// here; the violations are reported as they are.
|
||||
let error = lex_error.map(|e| format!("{name}: {e}"));
|
||||
@@ -248,6 +281,7 @@ fn check_one(
|
||||
config: &Config,
|
||||
opts: &Options,
|
||||
rules: &[&'static dyn Rule],
|
||||
options: &RuleOptions,
|
||||
census: Option<&Census>,
|
||||
) -> Report {
|
||||
let path = file.display().to_string();
|
||||
@@ -265,10 +299,10 @@ fn check_one(
|
||||
};
|
||||
let outcome = crate::catch_panic(|| {
|
||||
if opts.fix {
|
||||
fix_source(&src, file, config, opts, rules, census)
|
||||
fix_source(&src, file, config, opts, rules, options, census)
|
||||
} else {
|
||||
let (violations, lex_error) =
|
||||
run_rules(&src, Some(file.to_path_buf()), config, rules, census);
|
||||
run_rules(&src, Some(file.to_path_buf()), config, rules, options, census);
|
||||
(violations, None, 0, lex_error)
|
||||
}
|
||||
});
|
||||
@@ -299,6 +333,7 @@ fn run_rules(
|
||||
path: Option<PathBuf>,
|
||||
config: &Config,
|
||||
rules: &[&'static dyn Rule],
|
||||
options: &RuleOptions,
|
||||
census: Option<&Census>,
|
||||
) -> (Vec<Violation>, Option<String>) {
|
||||
// One parse per file (TODO §4): the products are built here, once, and
|
||||
@@ -313,8 +348,13 @@ fn run_rules(
|
||||
// census so a signal never counts as mentioned by its own declaration.
|
||||
let elsewhere = census.map(|census| Elsewhere { census, own: words::harvest(parsed.tokens()) });
|
||||
// The indent width the formatter would use is also the width a tab
|
||||
// expands to, so `--indent 4` fixes tabs into four spaces.
|
||||
let ctx = parsed.context(path).with_tab_width(config.indent_width);
|
||||
// expands to, so `--indent 4` fixes tabs into four spaces — and the width
|
||||
// it would wrap to is the width `line-length` holds the file to.
|
||||
let ctx = parsed
|
||||
.context(path)
|
||||
.with_tab_width(config.indent_width)
|
||||
.with_line_length(config.max_width)
|
||||
.with_options(options);
|
||||
let ctx = match &elsewhere {
|
||||
Some(elsewhere) => ctx.with_oracle(elsewhere),
|
||||
None => ctx,
|
||||
@@ -361,12 +401,13 @@ fn fix_source(
|
||||
config: &Config,
|
||||
opts: &Options,
|
||||
rules: &[&'static dyn Rule],
|
||||
options: &RuleOptions,
|
||||
census: Option<&Census>,
|
||||
) -> (Vec<Violation>, Option<String>, usize, Option<String>) {
|
||||
let mut text = src.to_string();
|
||||
let mut fixed = 0;
|
||||
let (mut violations, mut lex_error) =
|
||||
run_rules(&text, Some(file.to_path_buf()), config, rules, census);
|
||||
run_rules(&text, Some(file.to_path_buf()), config, rules, options, census);
|
||||
for _ in 0..MAX_FIX_ROUNDS {
|
||||
let round =
|
||||
apply_fixes(&text, &fixable_outside_fences(&text, &violations), opts.unsafe_fixes);
|
||||
@@ -375,7 +416,8 @@ fn fix_source(
|
||||
}
|
||||
fixed += round.applied;
|
||||
text = round.output;
|
||||
(violations, lex_error) = run_rules(&text, Some(file.to_path_buf()), config, rules, census);
|
||||
(violations, lex_error) =
|
||||
run_rules(&text, Some(file.to_path_buf()), config, rules, options, census);
|
||||
}
|
||||
let rewritten = (text != src).then_some(text);
|
||||
(violations, rewritten, fixed, lex_error)
|
||||
|
||||
@@ -98,7 +98,7 @@ fn run_check(opts: &Options) -> ExitCode {
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
if opts.is_stdin() {
|
||||
let config = match stdin_config(opts) {
|
||||
let (config, file_config) = match stdin_config(opts) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
@@ -120,7 +120,14 @@ fn run_check(opts: &Options) -> ExitCode {
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
return lint::check_stdin(opts, &src, &config, &rules);
|
||||
let options = match lint::rule_options(&file_config) {
|
||||
Ok(options) => options,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
return lint::check_stdin(opts, &src, &config, &rules, &options);
|
||||
}
|
||||
let jobs = match gather(opts).and_then(|jobs| build_pool(opts).map(|()| jobs)) {
|
||||
Ok(jobs) => jobs,
|
||||
@@ -140,7 +147,7 @@ fn run_check(opts: &Options) -> ExitCode {
|
||||
|
||||
fn run_stdin(opts: &Options) -> ExitCode {
|
||||
let name = opts.stdin_filename.as_deref().unwrap_or("<stdin>");
|
||||
let config = match stdin_config(opts) {
|
||||
let (config, _file_config) = match stdin_config(opts) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
@@ -421,13 +428,16 @@ fn absolute(cwd: &Path, path: &Path) -> PathBuf {
|
||||
|
||||
/// The settings for a buffer piped in on stdin: discovery anchors on
|
||||
/// `--stdin-filename`'s directory when given, else on the current one.
|
||||
fn stdin_config(opts: &Options) -> Result<Config, String> {
|
||||
/// The formatter config a stdin buffer is served with, and the `lucisv.toml`
|
||||
/// it came from — the linter needs the file's own `[lint.<rule>]` entries,
|
||||
/// which the resolved `Config` does not carry.
|
||||
fn stdin_config(opts: &Options) -> Result<(Config, FileConfig), String> {
|
||||
let mut discovery = Discovery::new(!opts.no_config);
|
||||
let file = match opts.stdin_filename.as_deref() {
|
||||
Some(name) => discovery.for_file(Path::new(name))?,
|
||||
None => discovery.for_dir(Path::new("."))?,
|
||||
};
|
||||
Ok(opts.config_with(&file))
|
||||
Ok((opts.config_with(&file), file))
|
||||
}
|
||||
|
||||
fn report(opts: &Options, changed: usize, unchanged: usize, cached: usize, errors: usize) {
|
||||
|
||||
@@ -1863,16 +1863,81 @@ fn an_unknown_rule_in_the_lint_table_is_an_error() {
|
||||
assert_eq!(code(&out), 2);
|
||||
}
|
||||
|
||||
/// Per-rule tables are named rather than silently ignored, so a user who
|
||||
/// writes one finds out it does nothing yet.
|
||||
/// A `[lint.<rule>]` table configures that rule, and the verdict changes
|
||||
/// with it — §34.0's headline claim, end to end through the real binary.
|
||||
#[test]
|
||||
fn a_per_rule_lint_table_is_refused_by_name() {
|
||||
fn a_per_rule_lint_table_changes_the_verdict() {
|
||||
let dir = TempDir::new("lint-per-rule");
|
||||
dir.write("dut.sv", DUT);
|
||||
dir.write("lucisv.toml", "[lint.unused-signal]\nignore = \"tmp_*\"\n");
|
||||
let wide = format!("module m;\n wire {};\nendmodule\n", "a".repeat(110));
|
||||
dir.write("m.sv", &wide);
|
||||
let out = run(&["check", &dir.root()]);
|
||||
assert!(stderr(&out).contains("per-rule lint settings"), "{}", stderr(&out));
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(stdout(&out).contains("line-length"), "over the default 100: {}", stdout(&out));
|
||||
|
||||
dir.write("lucisv.toml", "[lint.line-length]\nlength = 130\n");
|
||||
let out = run(&["check", &dir.root()]);
|
||||
assert_eq!(stdout(&out), "", "the option raised the limit");
|
||||
assert_eq!(code(&out), 0);
|
||||
}
|
||||
|
||||
/// A bad entry fails the run naming the config file and the line, which is
|
||||
/// what tells a user *where* to fix it.
|
||||
#[test]
|
||||
fn a_bad_rule_option_fails_the_run_naming_file_and_line() {
|
||||
let dir = TempDir::new("lint-bad-option");
|
||||
dir.write("m.sv", "module m;\nendmodule\n");
|
||||
for (config, wanted) in [
|
||||
("[lint.line-length]\nlength = 10\n", "must be between"),
|
||||
("[lint.line-length]\nlen = 120\n", "has no option `len`"),
|
||||
("[lint.no-such-rule]\nx = 1\n", "unknown rule `no-such-rule`"),
|
||||
("[lint.no-tabs]\nwidth = 4\n", "takes no options"),
|
||||
("[lint.signal-name-style]\nstyle_regex = \"[a-\"\n", "not a valid pattern"),
|
||||
// An escape from another dialect must be refused rather than read
|
||||
// as a literal, which would silently judge the wrong names (QA,
|
||||
// 2026-09-04).
|
||||
("[lint.signal-name-style]\nstyle_regex = \"\\bword\\b\"\n", "unsupported escape `\\b`"),
|
||||
("[lint.macro-name-style]\nstyle_regex = \"(A)\\1\"\n", "unsupported escape `\\1`"),
|
||||
] {
|
||||
dir.write("lucisv.toml", config);
|
||||
let out = run(&["check", &dir.root()]);
|
||||
let text = stderr(&out);
|
||||
assert!(text.contains(wanted), "{config:?}: {text}");
|
||||
assert!(text.contains("lucisv.toml:2:"), "file and line: {text}");
|
||||
assert_eq!(code(&out), 2, "{config:?}");
|
||||
}
|
||||
// Every one of them names the rule as well as the option, so an error
|
||||
// read out of a CI log stands on its own.
|
||||
dir.write("lucisv.toml", "[lint.line-length]\nlength = 10\n");
|
||||
let text = stderr(&run(&["check", &dir.root()]));
|
||||
assert!(text.contains("rule `line-length`"), "{text}");
|
||||
assert!(text.contains("`length` must be between"), "{text}");
|
||||
}
|
||||
|
||||
/// The width `line-length` holds a file to is the width the formatter is
|
||||
/// configured with, so the two halves of lucisv cannot disagree.
|
||||
#[test]
|
||||
fn line_length_follows_the_formatters_width() {
|
||||
let dir = TempDir::new("lint-width");
|
||||
let wide = format!("module m;\n wire {};\nendmodule\n", "a".repeat(90));
|
||||
dir.write("m.sv", &wide);
|
||||
assert_eq!(stdout(&run(&["check", &dir.root()])), "", "under the default 100");
|
||||
let narrow = run(&["check", &dir.root(), "--line-length", "80"]);
|
||||
assert!(stdout(&narrow).contains("line-length"), "{}", stdout(&narrow));
|
||||
|
||||
dir.write("lucisv.toml", "line-length = 80\n");
|
||||
let from_config = run(&["check", &dir.root()]);
|
||||
assert!(stdout(&from_config).contains("line-length"), "{}", stdout(&from_config));
|
||||
}
|
||||
|
||||
/// A stdin buffer reads the same `[lint.<rule>]` tables a file does.
|
||||
#[test]
|
||||
fn a_stdin_buffer_reads_the_rule_options_too() {
|
||||
let dir = TempDir::new("lint-stdin-options");
|
||||
dir.write("lucisv.toml", "[lint.macro-name-style]\nstyle_regex = \"[a-z_0-9]+\"\n");
|
||||
let name = format!("{}/m.sv", dir.root());
|
||||
let out = run_with_stdin(&["check", "-", "--stdin-filename", &name], "`define lower_ok 1\n");
|
||||
assert_eq!(stdout(&out), "", "the config's pattern accepts it: {}", stdout(&out));
|
||||
let plain = run_with_stdin(&["check", "-"], "`define lower_ok 1\n");
|
||||
assert!(stdout(&plain).contains("macro-name-style"), "{}", stdout(&plain));
|
||||
}
|
||||
|
||||
/// The QA finding of 2026-09-02, pinned end to end: a testbench that reads an
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -156,6 +156,37 @@ mod tests {
|
||||
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
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -1894,6 +1894,20 @@ sub #(
|
||||
}
|
||||
}
|
||||
|
||||
/// The premise the "the accepted text must parse" probe above rests on:
|
||||
/// the probe can still fail. Header recovery (TODO §32) widened what a
|
||||
/// tolerant parse reads — a half-typed connection list is now a recovered
|
||||
/// instantiation rather than a dead item — so the probe is only worth
|
||||
/// asking while text that does not parse still says so.
|
||||
#[test]
|
||||
fn the_accepted_text_probe_still_reports_text_that_does_not_parse() {
|
||||
let probe = "module lucisv_probe;\n logic clk;\n sub u_sub (.clk(\nendmodule\n";
|
||||
assert!(
|
||||
!vlog_parser::parse_source_tolerant(probe).1.is_empty(),
|
||||
"recovery must not make a broken instantiation look clean"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_with_no_ports_ghosts_a_sane_instantiation() {
|
||||
let top = "module top;\n bare \nendmodule\n";
|
||||
|
||||
@@ -17,7 +17,7 @@ use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString};
|
||||
use vlog_formatter::fence::{self, Region};
|
||||
use vlog_linter::{
|
||||
default_rules, lint, workspace_rules, LintContext, MentionOracle, ModuleInterface, Rule,
|
||||
Severity, Violation,
|
||||
RuleOptions, Severity, Violation,
|
||||
};
|
||||
use vlog_semantic::{FileId, SymbolKind, WorkspaceIndex};
|
||||
|
||||
@@ -35,14 +35,29 @@ use crate::state::{Document, Workspace};
|
||||
pub struct LintRun<'a> {
|
||||
rules: Vec<&'static dyn Rule>,
|
||||
oracle: Option<IndexMentions<'a>>,
|
||||
/// What the buffer's `lucisv.toml` and the editor's settings configured
|
||||
/// about each rule, merged. Empty means every rule reads its own default.
|
||||
options: RuleOptions,
|
||||
/// The width `line-length` holds this buffer to — the width the formatter
|
||||
/// would wrap it to, so the two halves of lucisv cannot disagree.
|
||||
line_length: usize,
|
||||
}
|
||||
|
||||
impl Default for LintRun<'_> {
|
||||
fn default() -> LintRun<'static> {
|
||||
LintRun { rules: default_rules(), oracle: None }
|
||||
LintRun {
|
||||
rules: default_rules(),
|
||||
oracle: None,
|
||||
options: RuleOptions::new(),
|
||||
line_length: DEFAULT_LINE_LENGTH,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The width a buffer is held to when neither its `lucisv.toml` nor the
|
||||
/// editor says otherwise — `vlog_formatter::Config`'s own default.
|
||||
const DEFAULT_LINE_LENGTH: usize = 100;
|
||||
|
||||
impl<'a> LintRun<'a> {
|
||||
/// The pass this workspace's settings and index describe for one buffer.
|
||||
///
|
||||
@@ -58,12 +73,13 @@ impl<'a> LintRun<'a> {
|
||||
let workspace = index.files().len() > usize::from(own.is_some());
|
||||
let rules = enabled_rules(ws.client_settings(), workspace);
|
||||
let oracle = workspace.then_some(IndexMentions { index, own });
|
||||
LintRun { rules, oracle }
|
||||
let (options, line_length) = configured(ws.client_settings(), doc);
|
||||
LintRun { rules, oracle, options, line_length }
|
||||
}
|
||||
|
||||
/// This run's context over a buffer's own parse products.
|
||||
fn context<'d>(&'d self, doc: &'d Document) -> LintContext<'d> {
|
||||
let ctx = context(doc);
|
||||
let ctx = context(doc).with_options(&self.options).with_line_length(self.line_length);
|
||||
match &self.oracle {
|
||||
Some(oracle) => ctx.with_oracle(oracle),
|
||||
None => ctx,
|
||||
@@ -71,6 +87,47 @@ impl<'a> LintRun<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The per-rule options and the line width governing one buffer.
|
||||
///
|
||||
/// **Precedence for an option, highest first: the editor, then the buffer's
|
||||
/// `lucisv.toml`, then the rule's own default — key by key**, so a project
|
||||
/// that sets two options and a user who overrides one keep the other. This is
|
||||
/// deliberately the *opposite* order to `format::settings_for`, where a
|
||||
/// checked-in `lucisv.toml` outranks the editor: formatting has a byte-exact
|
||||
/// contract with CI that a user's editor must not break, while a lint option
|
||||
/// changes which findings that user is shown in their own editor and is
|
||||
/// theirs to set. §34.0(d).
|
||||
///
|
||||
/// The **width** follows the formatting ladder instead, because it is not a
|
||||
/// lint setting at all: it is the width the formatter would wrap this buffer
|
||||
/// to, read the same way `format::settings_for` reads it, so a line lucisv
|
||||
/// wrote is never a line lucisv calls too long. `line-length`'s own `length`
|
||||
/// option still beats it — that is the rule's own business, and the rule
|
||||
/// applies it.
|
||||
///
|
||||
/// The config file is read here, per pass, exactly as `format::discover`
|
||||
/// reads it per formatting request: a `lucisv.toml` edited while the server
|
||||
/// runs takes effect at the next publish, and the read is a few stats beside
|
||||
/// a parse and an analysis the same pass already paid for.
|
||||
fn configured(client: &ClientSettings, doc: &Document) -> (RuleOptions, usize) {
|
||||
let file = doc
|
||||
.path
|
||||
.as_deref()
|
||||
.and_then(|path| lucisv_core::config::Discovery::new(true).for_file(path).ok())
|
||||
.unwrap_or_default();
|
||||
let mut options = RuleOptions::new();
|
||||
for entry in &file.lint_options {
|
||||
// A broken entry in the file is dropped here rather than reported:
|
||||
// `format::settings_for` already surfaces a `lucisv.toml` problem to
|
||||
// the user, and `lucisv check` fails the run over it with file and
|
||||
// line, which is where a config error belongs.
|
||||
let _ = options.set_raw(&entry.rule, &entry.key, &entry.raw);
|
||||
}
|
||||
options.overlay(&client.lint_options);
|
||||
let width = file.line_length.or(client.line_length).unwrap_or(DEFAULT_LINE_LENGTH);
|
||||
(options, width)
|
||||
}
|
||||
|
||||
/// Which rules a buffer is linted with, given what the editor's settings say.
|
||||
///
|
||||
/// **The one ladder**, top rung last — every rung may undo the one above it:
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -17,7 +17,7 @@ use std::collections::BTreeMap;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use serde_json::Value;
|
||||
use vlog_linter::Severity;
|
||||
use vlog_linter::{OptionValue, RuleOptions, Severity};
|
||||
|
||||
/// Accepted `line-length`, and accepted `indent`.
|
||||
///
|
||||
@@ -190,6 +190,18 @@ pub struct ClientSettings {
|
||||
/// toggle nobody touched would silently override `select` and the class
|
||||
/// switches.
|
||||
pub lint_rules: BTreeMap<String, bool>,
|
||||
/// `lucisv.lint.options`: `{"<rule>": {"<key>": value}}`, validated
|
||||
/// against the rule registry.
|
||||
///
|
||||
/// Refused entries are **dropped**, not fatal — this module's standing
|
||||
/// rule, and the reason it matters here more than anywhere else: one
|
||||
/// typo in an options object must not be able to switch the linter off
|
||||
/// for a whole session. What was refused is kept in
|
||||
/// [`ClientSettings::lint_option_warnings`] so the user is told.
|
||||
pub lint_options: RuleOptions,
|
||||
/// One line per refused `lucisv.lint.options` entry, ready for a
|
||||
/// `window/logMessage`. Empty for a settings push that was all valid.
|
||||
pub lint_option_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// The settings a client that said nothing is treated as having asked for.
|
||||
@@ -218,6 +230,8 @@ impl Default for ClientSettings {
|
||||
lint_ignore: Vec::new(),
|
||||
lint_severity: every_class_on(),
|
||||
lint_rules: BTreeMap::new(),
|
||||
lint_options: RuleOptions::new(),
|
||||
lint_option_warnings: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -233,15 +247,21 @@ fn every_class_on() -> BTreeMap<Severity, bool> {
|
||||
/// Its only use is equality — the server compares it across a settings change
|
||||
/// to decide whether every open file must be published again.
|
||||
pub type LintSelection =
|
||||
(Vec<String>, Vec<String>, BTreeMap<Severity, bool>, BTreeMap<String, bool>);
|
||||
(Vec<String>, Vec<String>, BTreeMap<Severity, bool>, BTreeMap<String, bool>, RuleOptions);
|
||||
|
||||
/// The four lint settings of `settings`, as one comparable value.
|
||||
/// The lint settings of `settings`, as one comparable value.
|
||||
///
|
||||
/// The options are in here with the four that choose rules, because a changed
|
||||
/// option changes what a rule *reports* — a `line-length` of 120 unpublishes
|
||||
/// every finding drawn at 100 — and every open file must be published again
|
||||
/// for exactly the same reason a changed selection does.
|
||||
pub fn lint_selection(settings: &ClientSettings) -> LintSelection {
|
||||
(
|
||||
settings.lint_select.clone(),
|
||||
settings.lint_ignore.clone(),
|
||||
settings.lint_severity.clone(),
|
||||
settings.lint_rules.clone(),
|
||||
settings.lint_options.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -272,6 +292,7 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
||||
let large_file = lucisv.get("largeFile");
|
||||
// And `lucisv.lint.select` / `lucisv.lint.ignore` the same way again.
|
||||
let lint = lucisv.get("lint");
|
||||
let (options, warnings) = rule_options(lint.and_then(|l| l.get("options")));
|
||||
ClientSettings {
|
||||
line_length: bounded(lucisv.get("lineLength"), LINE_LENGTH_RANGE),
|
||||
indent: bounded(lucisv.get("indent"), INDENT_RANGE),
|
||||
@@ -319,6 +340,8 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
||||
// one level deeper again, for the same reason `index.*` does.
|
||||
lint_severity: severity_switches(lint.and_then(|l| l.get("severity"))),
|
||||
lint_rules: rule_toggles(lint.and_then(|l| l.get("rules"))),
|
||||
lint_options: options,
|
||||
lint_option_warnings: warnings,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -364,6 +387,63 @@ fn rule_toggles(value: Option<&Value>) -> BTreeMap<String, bool> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The `lucisv.lint.options` object, validated against the rule registry.
|
||||
///
|
||||
/// The shape is `{"<rule>": {"<key>": value}}` — the nesting VS Code's
|
||||
/// settings model produces for an object setting, and the one a hand-written
|
||||
/// Neovim config writes. Every entry goes through the **same** validator a
|
||||
/// `[lint.<rule>]` table in a `lucisv.toml` goes through
|
||||
/// (`RuleOptions::set`), so an option means one thing in both front ends.
|
||||
///
|
||||
/// A refused entry is dropped and described, rather than failing the push:
|
||||
/// the CLI can fail a run over a typo because a user typed it and is watching,
|
||||
/// while a settings push arrives on a socket and failing it would leave an
|
||||
/// editor with no diagnostics and no way to see why. The descriptions are
|
||||
/// returned for the caller to log.
|
||||
fn rule_options(value: Option<&Value>) -> (RuleOptions, Vec<String>) {
|
||||
let mut options = RuleOptions::new();
|
||||
let mut warnings = Vec::new();
|
||||
let Some(Value::Object(rules)) = value else { return (options, warnings) };
|
||||
for (rule, keys) in rules {
|
||||
let Some(Value::Object(keys)) = Some(keys) else {
|
||||
warnings.push(format!("lucisv.lint.options.{rule} is not an object; ignored"));
|
||||
continue;
|
||||
};
|
||||
for (key, raw) in keys {
|
||||
let Some(value) = option_value(raw) else {
|
||||
warnings.push(format!(
|
||||
"lucisv.lint.options.{rule}.{key}: {raw} is not a boolean, number, \
|
||||
string or list of strings; ignored"
|
||||
));
|
||||
continue;
|
||||
};
|
||||
if let Err(problem) = options.set(rule, key, value) {
|
||||
warnings.push(format!("lucisv.lint.options.{rule}.{key}: {problem}; ignored"));
|
||||
}
|
||||
}
|
||||
}
|
||||
(options, warnings)
|
||||
}
|
||||
|
||||
/// One JSON value as an option value, or nothing for a shape no option takes.
|
||||
///
|
||||
/// Structural only — whether the *kind* is the one the option declares is
|
||||
/// `RuleOptions::set`'s answer, so the error a user reads names the option
|
||||
/// and its kind rather than JSON's.
|
||||
fn option_value(raw: &Value) -> Option<OptionValue> {
|
||||
match raw {
|
||||
Value::Bool(b) => Some(OptionValue::Bool(*b)),
|
||||
Value::Number(n) => n.as_i64().map(OptionValue::Int),
|
||||
Value::String(s) => Some(OptionValue::Str(s.clone())),
|
||||
Value::Array(items) => items
|
||||
.iter()
|
||||
.map(|item| item.as_str().map(str::to_string))
|
||||
.collect::<Option<Vec<String>>>()
|
||||
.map(OptionValue::List),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// One of the two `lucisv.index.scope` words, or nothing. Matched exactly —
|
||||
/// case and all — because the enum in `package.json` is what a settings UI
|
||||
/// offers, and forgiving `"Workspace"` here would make a typo mean something
|
||||
@@ -813,7 +893,9 @@ mod tests {
|
||||
selected.lint_select = vec!["error".to_string()];
|
||||
let mut ignored = base.clone();
|
||||
ignored.lint_ignore = vec!["no-tabs".to_string()];
|
||||
for changed in [severity, toggled, selected, ignored] {
|
||||
let mut configured = base.clone();
|
||||
configured.lint_options.set_raw("line-length", "length", "120").expect("accepted");
|
||||
for changed in [severity, toggled, selected, ignored, configured] {
|
||||
assert_ne!(lint_selection(&base), lint_selection(&changed));
|
||||
}
|
||||
// A setting that does not change which rules run does not republish.
|
||||
@@ -822,6 +904,71 @@ mod tests {
|
||||
assert_eq!(lint_selection(&base), lint_selection(&unrelated));
|
||||
}
|
||||
|
||||
/// §34.0(c): the object is read, validated against the registry, and a
|
||||
/// bad entry is dropped **with a warning** rather than failing the push.
|
||||
#[test]
|
||||
fn the_lint_options_object_is_read_and_validated() {
|
||||
let found = settings(json!({"lucisv": {"lint": {"options": {
|
||||
"line-length": {"length": 120},
|
||||
"generate-label-prefix": {"prefix": ["blk_"]},
|
||||
"typedef-structs-unions": {"allow_anonymous_nested": true},
|
||||
"signal-name-style": {"style_regex": "[a-z_0-9]+"},
|
||||
}}}}));
|
||||
assert_eq!(found.lint_options.int("line-length", "length"), 120);
|
||||
assert_eq!(
|
||||
found.lint_options.list("generate-label-prefix", "prefix"),
|
||||
vec!["blk_".to_string()]
|
||||
);
|
||||
assert!(found.lint_options.bool("typedef-structs-unions", "allow_anonymous_nested"));
|
||||
assert_eq!(found.lint_options.str("signal-name-style", "style_regex"), "[a-z_0-9]+");
|
||||
assert!(found.lint_option_warnings.is_empty(), "{:?}", found.lint_option_warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_option_is_dropped_and_described_rather_than_fatal() {
|
||||
let found = settings(json!({"lucisv": {"lint": {"options": {
|
||||
"line-length": {"length": 10, "len": 120},
|
||||
"no-such-rule": {"x": 1},
|
||||
"no-tabs": {"width": 4},
|
||||
"signal-name-style": {"style_regex": "[a-"},
|
||||
"interface-name-style": {"style_regex": "\\bword\\b"},
|
||||
"macro-name-style": {"style_regex": 4},
|
||||
"package-filename": "not-an-object",
|
||||
"port-name-suffix": {"suffixes": [1, 2]},
|
||||
}}}}));
|
||||
// Nothing was accepted, and every refusal says which entry and why.
|
||||
assert!(found.lint_options.is_empty(), "{:?}", found.lint_options);
|
||||
let warnings = found.lint_option_warnings.join("\n");
|
||||
for wanted in [
|
||||
"line-length.length",
|
||||
"must be between",
|
||||
"has no option `len`",
|
||||
"unknown rule `no-such-rule`",
|
||||
"takes no options",
|
||||
"not a valid pattern",
|
||||
"unsupported escape `\\b`",
|
||||
"expects a pattern, found an integer",
|
||||
"package-filename is not an object",
|
||||
"port-name-suffix.suffixes",
|
||||
] {
|
||||
assert!(warnings.contains(wanted), "{wanted} missing from:\n{warnings}");
|
||||
}
|
||||
// ... and the rest of the settings survived the bad object.
|
||||
assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE);
|
||||
}
|
||||
|
||||
/// A settings payload with no options object is exactly today's
|
||||
/// behaviour: every rule reads its own default.
|
||||
#[test]
|
||||
fn no_options_object_means_every_default() {
|
||||
for payload in [json!({"lucisv": {}}), json!({"lucisv": {"lint": {}}})] {
|
||||
let found = settings(payload);
|
||||
assert!(found.lint_options.is_empty());
|
||||
assert!(found.lint_option_warnings.is_empty());
|
||||
assert_eq!(found.lint_options.int("line-length", "length"), 100, "the spec default");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_vscode_payload_is_no_opinion_about_anything() {
|
||||
// Every setting at its `package.json` default: nulls and an empty
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -41,7 +41,7 @@
|
||||
use lsp_types::{Location, Uri};
|
||||
use vlog_parser::ast::{
|
||||
AnsiPort, DataType, Declarator, GenBlock, GenElse, GenIf, Instantiation, Item, ItemKind,
|
||||
Module, ParamPort, PortList, Stmt, StmtKind, StructType, TfArg, TypeExtra, Typedef,
|
||||
ListElem, Module, ParamPort, PortList, Stmt, StmtKind, StructType, TfArg, TypeExtra, Typedef,
|
||||
TypedefKind,
|
||||
};
|
||||
use vlog_parser::TextRange;
|
||||
@@ -250,18 +250,20 @@ fn module_site(m: &Module, offset: u32) -> Option<Site<'_>> {
|
||||
.or_else(|| site_at(&m.items, offset))
|
||||
}
|
||||
|
||||
fn ansi_port_site(ports: &[AnsiPort], offset: u32) -> Option<Site<'_>> {
|
||||
let port = ports.iter().find(|p| p.span.contains(offset))?;
|
||||
// The three header lists below skip their error elements: text a tolerant
|
||||
// parse could not read names no type, so there is no definition to go to.
|
||||
fn ansi_port_site(ports: &[ListElem<AnsiPort>], offset: u32) -> Option<Site<'_>> {
|
||||
let port = ports.iter().filter_map(ListElem::ok).find(|p| p.span.contains(offset))?;
|
||||
site(&port.ty.name, TextRange::new(port.span.start, port.name_span.start))
|
||||
}
|
||||
|
||||
fn param_port_site(ports: &[ParamPort], offset: u32) -> Option<Site<'_>> {
|
||||
let port = ports.iter().find(|p| p.span.contains(offset))?;
|
||||
fn param_port_site(ports: &[ListElem<ParamPort>], offset: u32) -> Option<Site<'_>> {
|
||||
let port = ports.iter().filter_map(ListElem::ok).find(|p| p.span.contains(offset))?;
|
||||
site(&port.ty.name, TextRange::new(port.span.start, port.name_span.start))
|
||||
}
|
||||
|
||||
fn tf_arg_site(args: &[TfArg], offset: u32) -> Option<Site<'_>> {
|
||||
let arg = args.iter().find(|a| a.span.contains(offset))?;
|
||||
fn tf_arg_site(args: &[ListElem<TfArg>], offset: u32) -> Option<Site<'_>> {
|
||||
let arg = args.iter().filter_map(ListElem::ok).find(|a| a.span.contains(offset))?;
|
||||
site(&arg.ty.name, TextRange::new(arg.span.start, arg.name_span.start))
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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)])
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -9,12 +9,20 @@ use vlog_parser::token::{Comment, Token, TokenKind};
|
||||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LexError, LineIndex};
|
||||
use vlog_semantic::{analyze, Semantics};
|
||||
|
||||
use crate::options::RuleOptions;
|
||||
use crate::signals::Signals;
|
||||
|
||||
/// The default tab stop used when a fix expands a tab, matching lucisv's
|
||||
/// default indent. `LintContext::with_tab_width` follows `--indent`.
|
||||
const DEFAULT_TAB_WIDTH: usize = 2;
|
||||
|
||||
/// The width `line-length` holds a file to when nothing says otherwise —
|
||||
/// `vlog_formatter::Config`'s own default, because the two are the same
|
||||
/// number: a formatted file that the linter then calls too wide would be
|
||||
/// lucisv disagreeing with itself. `LintContext::with_line_length` follows
|
||||
/// `--line-length` and `lucisv.toml`.
|
||||
const DEFAULT_LINE_LENGTH: usize = 100;
|
||||
|
||||
/// One text, parsed once: the products a lint run reads.
|
||||
///
|
||||
/// This is the owned half of "one parse, two tools" (TODO §4): a caller with
|
||||
@@ -201,6 +209,10 @@ pub struct LintContext<'a> {
|
||||
backing: Backing<'a>,
|
||||
path: Option<PathBuf>,
|
||||
tab_width: usize,
|
||||
line_length: usize,
|
||||
/// What the run configured about each rule, or `None` for a run that
|
||||
/// configured nothing — which reads exactly as the specs' own defaults.
|
||||
options: Option<&'a RuleOptions>,
|
||||
/// Byte ranges of string literals, ascending — the one place text rules
|
||||
/// must not rewrite, because there whitespace is data.
|
||||
strings: Vec<TextRange>,
|
||||
@@ -254,6 +266,8 @@ impl<'a> LintContext<'a> {
|
||||
backing,
|
||||
path,
|
||||
tab_width: DEFAULT_TAB_WIDTH,
|
||||
line_length: DEFAULT_LINE_LENGTH,
|
||||
options: None,
|
||||
strings: Vec::new(),
|
||||
semantics: SemanticsSlot::Lazy(OnceCell::new()),
|
||||
signals: OnceCell::new(),
|
||||
@@ -271,6 +285,68 @@ impl<'a> LintContext<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the width the run's formatter would wrap to, which is what
|
||||
/// `line-length` holds the file to unless that rule's own `length` option
|
||||
/// says otherwise.
|
||||
pub fn with_line_length(mut self, line_length: usize) -> LintContext<'a> {
|
||||
self.line_length = line_length.max(1);
|
||||
self
|
||||
}
|
||||
|
||||
/// Lends the per-rule options the run resolved. A context without them
|
||||
/// reads every option at its declared default, which is the shipped
|
||||
/// behaviour.
|
||||
pub fn with_options(mut self, options: &'a RuleOptions) -> LintContext<'a> {
|
||||
self.options = Some(options);
|
||||
self
|
||||
}
|
||||
|
||||
/// The width the run's formatter wraps to. See
|
||||
/// [`with_line_length`](LintContext::with_line_length).
|
||||
pub fn line_length(&self) -> usize {
|
||||
self.line_length
|
||||
}
|
||||
|
||||
/// What the run configured, or the empty set.
|
||||
pub fn options(&self) -> &RuleOptions {
|
||||
match self.options {
|
||||
Some(options) => options,
|
||||
None => RuleOptions::none(),
|
||||
}
|
||||
}
|
||||
|
||||
/// One boolean option of `rule`, or its declared default.
|
||||
pub fn option_bool(&self, rule: &str, key: &str) -> bool {
|
||||
self.options().bool(rule, key)
|
||||
}
|
||||
|
||||
/// One integer option of `rule`, or its declared default.
|
||||
pub fn option_int(&self, rule: &str, key: &str) -> i64 {
|
||||
self.options().int(rule, key)
|
||||
}
|
||||
|
||||
/// One string (or pattern) option of `rule`, or its declared default.
|
||||
pub fn option_str(&self, rule: &str, key: &str) -> &str {
|
||||
self.options().str(rule, key)
|
||||
}
|
||||
|
||||
/// One list option of `rule`, or its declared default.
|
||||
pub fn option_list(&self, rule: &str, key: &str) -> Vec<String> {
|
||||
self.options().list(rule, key)
|
||||
}
|
||||
|
||||
/// Whether the run said anything about this option at all — the question
|
||||
/// a rule asks when its fallback is not its spec's default.
|
||||
pub fn option_is_set(&self, rule: &str, key: &str) -> bool {
|
||||
self.options().is_set(rule, key)
|
||||
}
|
||||
|
||||
/// One pattern option of `rule`, compiled, or `None` if it does not
|
||||
/// compile — which cannot happen for a value this run accepted.
|
||||
pub(crate) fn option_pattern(&self, rule: &str, key: &str) -> Option<crate::regex::Regex> {
|
||||
crate::options::pattern(self.options(), rule, key)
|
||||
}
|
||||
|
||||
/// Lends the symbol table the caller already built for this exact text —
|
||||
/// "one parse, two tools" extended to the analysis (the language server
|
||||
/// analyzes every buffer anyway, so its lint pass must not analyze twice).
|
||||
|
||||
@@ -9,9 +9,10 @@
|
||||
//! becoming "everything a rule might want to walk".
|
||||
|
||||
use vlog_parser::ast::{
|
||||
DataType, Dim, EnumType, FunctionDecl, ItemKind, SourceFile, StmtKind, StructType, TaskDecl,
|
||||
TfArg, TypeExtra, TypedefKind,
|
||||
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};
|
||||
|
||||
@@ -34,7 +35,7 @@ pub(crate) fn walk_data_types(file: &SourceFile, f: &mut dyn FnMut(&DataType)) {
|
||||
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 {
|
||||
for port in ports.iter().filter_map(ListElem::ok) {
|
||||
visit(&port.ty);
|
||||
}
|
||||
}
|
||||
@@ -77,7 +78,7 @@ fn walk_unpacked(file: &SourceFile, f: &mut dyn FnMut(Packing, &Dim)) {
|
||||
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 {
|
||||
for port in ports.iter().filter_map(ListElem::ok) {
|
||||
unpacked(&port.unpacked);
|
||||
}
|
||||
}
|
||||
@@ -105,8 +106,8 @@ fn declarator_dims(declarators: &[vlog_parser::ast::Declarator], unpacked: &mut
|
||||
}
|
||||
}
|
||||
|
||||
fn arg_dims(args: &[TfArg], unpacked: &mut dyn FnMut(&[Dim])) {
|
||||
for arg in args {
|
||||
fn arg_dims(args: &[ListElem<TfArg>], unpacked: &mut dyn FnMut(&[Dim])) {
|
||||
for arg in args.iter().filter_map(ListElem::ok) {
|
||||
unpacked(&arg.unpacked);
|
||||
}
|
||||
}
|
||||
@@ -124,13 +125,13 @@ fn function_types(decl: &FunctionDecl, visit: &mut dyn FnMut(&DataType)) {
|
||||
if let Some(ret) = &decl.ret {
|
||||
visit(ret);
|
||||
}
|
||||
for arg in &decl.args {
|
||||
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 {
|
||||
for arg in decl.args.iter().filter_map(ListElem::ok) {
|
||||
visit(&arg.ty);
|
||||
}
|
||||
}
|
||||
@@ -147,6 +148,107 @@ fn struct_types(struct_ty: &StructType, visit: &mut dyn FnMut(&DataType)) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A type written in a declaration, with the name that declaration gives.
|
||||
///
|
||||
/// What the two `typedef-*` rules need and `walk_data_types` cannot say: a
|
||||
/// `DataType` carries no span of its own, so a rule that judges the *type* of
|
||||
/// a declaration reports at the name — and needs to know whether that
|
||||
/// declaration is nested inside another aggregate's body.
|
||||
pub(crate) struct DeclaredType<'a> {
|
||||
/// The type as written.
|
||||
pub(crate) ty: &'a DataType,
|
||||
/// The name declared with it.
|
||||
pub(crate) name: &'a str,
|
||||
/// Byte range of that name — where a finding points.
|
||||
pub(crate) span: TextRange,
|
||||
/// True when this declaration is a member of another `struct`/`union`.
|
||||
pub(crate) nested: bool,
|
||||
}
|
||||
|
||||
/// Calls `f` on every type written in a **declaration** — a data or port
|
||||
/// declaration, an ANSI port, a variable declaration in a statement — and on
|
||||
/// every member of an aggregate written inside one.
|
||||
///
|
||||
/// A `typedef`'s own base type is deliberately not visited: a named type is
|
||||
/// exactly what the `typedef-*` rules ask for, so passing it to them would be
|
||||
/// asking them to flag the shape they exist to encourage. Its members are
|
||||
/// visited, as nested declarations.
|
||||
pub(crate) fn walk_declared_types(file: &SourceFile, f: &mut dyn FnMut(&DeclaredType)) {
|
||||
walk_items(file, &mut |item| match &item.kind {
|
||||
ItemKind::Module(module) => {
|
||||
if let vlog_parser::ast::PortList::Ansi(ports) = &module.ports {
|
||||
for port in ports.iter().filter_map(ListElem::ok) {
|
||||
declared(&port.ty, &port.name, port.name_span, false, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::DataDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
|
||||
ItemKind::PortDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
|
||||
// Only the members: the typedef itself is the named type these rules
|
||||
// want, and the naming rules judge its name.
|
||||
ItemKind::Typedef(typedef) => typedef_members(&typedef.kind, f),
|
||||
_ => {}
|
||||
});
|
||||
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
|
||||
StmtKind::VarDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
|
||||
StmtKind::PortDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
|
||||
StmtKind::Typedef(typedef) => typedef_members(&typedef.kind, f),
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
|
||||
/// One declaration, and whatever aggregate its type carries.
|
||||
fn declared(
|
||||
ty: &DataType,
|
||||
name: &str,
|
||||
span: TextRange,
|
||||
nested: bool,
|
||||
f: &mut dyn FnMut(&DeclaredType),
|
||||
) {
|
||||
f(&DeclaredType { ty, name, span, nested });
|
||||
members_of(ty, f);
|
||||
}
|
||||
|
||||
/// One declaration's type, once per name it declares.
|
||||
fn declarator_types(
|
||||
ty: &DataType,
|
||||
declarators: &[vlog_parser::ast::Declarator],
|
||||
f: &mut dyn FnMut(&DeclaredType),
|
||||
) {
|
||||
for declarator in declarators {
|
||||
declared(ty, &declarator.name, declarator.name_span, false, f);
|
||||
}
|
||||
}
|
||||
|
||||
/// The members of an anonymous aggregate, and of the aggregates inside it.
|
||||
fn members_of(ty: &DataType, f: &mut dyn FnMut(&DeclaredType)) {
|
||||
if let Some(TypeExtra::Struct(structure)) = ty.inline() {
|
||||
struct_members(structure, f);
|
||||
}
|
||||
}
|
||||
|
||||
/// The members of a `struct`/`union` body, each as a nested declaration.
|
||||
fn struct_members(structure: &StructType, f: &mut dyn FnMut(&DeclaredType)) {
|
||||
for member in &structure.members {
|
||||
for declarator in &member.declarators {
|
||||
f(&DeclaredType {
|
||||
ty: &member.ty,
|
||||
name: &declarator.name,
|
||||
span: declarator.name_span,
|
||||
nested: true,
|
||||
});
|
||||
}
|
||||
members_of(&member.ty, f);
|
||||
}
|
||||
}
|
||||
|
||||
/// A typedef's members — everything inside its body, but not the body itself.
|
||||
fn typedef_members(kind: &TypedefKind, f: &mut dyn FnMut(&DeclaredType)) {
|
||||
if let TypedefKind::Struct(structure) = kind {
|
||||
struct_members(structure, f);
|
||||
}
|
||||
}
|
||||
|
||||
/// One type and whatever aggregate it *is*: an anonymous `enum`'s base and an
|
||||
/// anonymous `struct`'s members are types written inside this one.
|
||||
fn descend(ty: &DataType, f: &mut dyn FnMut(&DataType)) {
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! whole is reported as **unknowable** rather than as a short list, because a
|
||||
//! short list is what turns a legal connection into an accusation.
|
||||
|
||||
use vlog_parser::ast::{ItemKind, Module, ParamPort, PortList, SourceFile};
|
||||
use vlog_parser::ast::{ItemKind, ListElem, Module, ParamPort, PortList, SourceFile};
|
||||
|
||||
use crate::context::ModuleInterface;
|
||||
use crate::visit::walk_items;
|
||||
@@ -49,8 +49,12 @@ fn interface_of(module: &Module) -> Option<ModuleInterface> {
|
||||
/// to it by name.
|
||||
fn ports_of(module: &Module) -> Vec<String> {
|
||||
match &module.ports {
|
||||
PortList::Ansi(ports) => ports.iter().map(|port| port.name.clone()).collect(),
|
||||
PortList::NonAnsi(ports) => ports.iter().map(|port| port.name.clone()).collect(),
|
||||
PortList::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(),
|
||||
}
|
||||
}
|
||||
@@ -67,7 +71,7 @@ fn ports_of(module: &Module) -> Vec<String> {
|
||||
fn parameters_of(module: &Module) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut overridable = true;
|
||||
for port in module.param_ports.iter().flatten() {
|
||||
for port in module.param_ports.iter().flatten().filter_map(ListElem::ok) {
|
||||
overridable = is_parameter(port, overridable);
|
||||
if overridable {
|
||||
out.push(port.name.clone());
|
||||
|
||||
@@ -24,7 +24,10 @@ mod context;
|
||||
mod decls;
|
||||
mod interfaces;
|
||||
mod literal;
|
||||
mod module_decls;
|
||||
mod naming;
|
||||
mod options;
|
||||
mod regex;
|
||||
mod registry;
|
||||
mod rule_docs;
|
||||
mod rules;
|
||||
@@ -39,6 +42,7 @@ use std::path::PathBuf;
|
||||
|
||||
pub use context::{LintContext, MentionOracle, ModuleInterface, ParsedSource};
|
||||
pub use interfaces::module_interfaces;
|
||||
pub use options::{OptionDefault, OptionKind, OptionSpec, OptionValue, RuleOptions};
|
||||
pub use registry::{
|
||||
all_rules, default_rules, rule_by_name, rules_named, select_rules, workspace_rules, Rule,
|
||||
};
|
||||
@@ -197,11 +201,12 @@ mod tests {
|
||||
// Real corpus RTL is annotated for Verible. Waivers naming rules lucisv
|
||||
// has not implemented are that codebase's, not typos, so they are
|
||||
// neither honored nor reported.
|
||||
let src = "module m;\n // verilog_lint: waive macro-name-style\n wire a;\nendmodule\n";
|
||||
let src = "module m;\n // verilog_lint: waive explicit-function-lifetime\n wire a;\nendmodule\n";
|
||||
assert!(lint_all(src).is_empty());
|
||||
|
||||
// lucisv's own spelling gets no such benefit of the doubt.
|
||||
let src = "module m;\n // lucisv: waive macro-name-style\n wire a;\nendmodule\n";
|
||||
let src =
|
||||
"module m;\n // lucisv: waive explicit-function-lifetime\n wire a;\nendmodule\n";
|
||||
assert_eq!(names(&lint_all(src)), vec![UNUSED_WAIVER]);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
//! The nets, variables and ports a module declares — what the two signal
|
||||
//! naming rules judge.
|
||||
//!
|
||||
//! A module's own declarations are a different population from "every
|
||||
//! declared name in the file": a class property, a loop variable and a
|
||||
//! function local are not signals, and a rule that judged them would be
|
||||
//! reporting on things the style guide says nothing about. Collecting them
|
||||
//! lives here rather than in `visit` (the item and statement spines) or
|
||||
//! `decls` (types and dimensions), so each of the three files stays one
|
||||
//! sentence long.
|
||||
|
||||
use vlog_parser::ast::{
|
||||
AnsiPort, GenBlock, GenElse, Item, ItemKind, ListElem, PortList, SourceFile,
|
||||
};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// One net, variable or port a module declares.
|
||||
pub(crate) struct SignalDecl {
|
||||
/// The declared name, as written.
|
||||
pub(crate) name: String,
|
||||
/// Byte range of that name.
|
||||
pub(crate) span: TextRange,
|
||||
/// The word a diagnostic calls it: `port` or `signal`.
|
||||
pub(crate) what: &'static str,
|
||||
/// The direction of a port, as written (`input`, `output`, `inout`), or
|
||||
/// `None` for a signal.
|
||||
pub(crate) dir: Option<String>,
|
||||
}
|
||||
|
||||
/// Every net, variable and port declared inside a module, interface or
|
||||
/// program of `file`, header and body alike, generate blocks included.
|
||||
///
|
||||
/// A `class` body is deliberately not descended into: its properties are not
|
||||
/// signals. A function or task body is not either — a local is scoped to the
|
||||
/// subroutine and named for it.
|
||||
pub(crate) fn module_signals(file: &SourceFile) -> Vec<SignalDecl> {
|
||||
let mut out = Vec::new();
|
||||
for item in &file.items {
|
||||
collect_item(item, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn collect_item(item: &Item, out: &mut Vec<SignalDecl>) {
|
||||
match &item.kind {
|
||||
ItemKind::Module(module) => {
|
||||
header_ports(&module.ports, out);
|
||||
for inner in &module.items {
|
||||
collect_body(inner, out);
|
||||
}
|
||||
}
|
||||
// A module may be written inside a package; nothing else at file
|
||||
// level holds one.
|
||||
ItemKind::Package { items, .. } => {
|
||||
for inner in items {
|
||||
collect_item(inner, out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// One item of a module body.
|
||||
fn collect_body(item: &Item, out: &mut Vec<SignalDecl>) {
|
||||
match &item.kind {
|
||||
ItemKind::DataDecl(decl) => {
|
||||
for declarator in &decl.declarators {
|
||||
out.push(SignalDecl {
|
||||
name: declarator.name.clone(),
|
||||
span: declarator.name_span,
|
||||
what: "signal",
|
||||
dir: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
ItemKind::PortDecl(decl) => {
|
||||
for declarator in &decl.declarators {
|
||||
out.push(SignalDecl {
|
||||
name: declarator.name.clone(),
|
||||
span: declarator.name_span,
|
||||
what: "port",
|
||||
dir: Some(decl.dir.clone()),
|
||||
});
|
||||
}
|
||||
}
|
||||
// A nested module is a module of its own.
|
||||
ItemKind::Module(_) => collect_item(item, out),
|
||||
ItemKind::GenerateRegion { items, .. } => {
|
||||
for inner in items {
|
||||
collect_body(inner, out);
|
||||
}
|
||||
}
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
block(&gen_if.then, out);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
while let Some(branch) = els {
|
||||
match branch {
|
||||
GenElse::If(_, nested) => {
|
||||
block(&nested.then, out);
|
||||
els = nested.els.as_deref();
|
||||
}
|
||||
GenElse::Block(inner) => {
|
||||
block(inner, out);
|
||||
els = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::GenFor(gen_for) => block(&gen_for.body, out),
|
||||
ItemKind::GenCase(gen_case) => {
|
||||
for case_item in &gen_case.items {
|
||||
block(&case_item.body, out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn block(block: &GenBlock, out: &mut Vec<SignalDecl>) {
|
||||
for item in &block.items {
|
||||
collect_body(item, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// The ports of a module header, in either style.
|
||||
fn header_ports(ports: &PortList, out: &mut Vec<SignalDecl>) {
|
||||
match ports {
|
||||
PortList::Ansi(ports) => {
|
||||
// A port with no direction keyword continues the previous one, as
|
||||
// the language says; a first port with none is `inout` by default.
|
||||
let mut carried: Option<String> = None;
|
||||
for port in ports.iter().filter_map(ListElem::ok) {
|
||||
carried = direction(port).or(carried);
|
||||
out.push(SignalDecl {
|
||||
name: port.name.clone(),
|
||||
span: port.name_span,
|
||||
what: "port",
|
||||
dir: carried.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
// A non-ANSI header *names* its ports; the body declares them
|
||||
// (`input clk;`), and that declaration is the one collected — so a
|
||||
// rule reports each port once, where its direction is written.
|
||||
PortList::NonAnsi(_) | PortList::None | PortList::Empty => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn direction(port: &AnsiPort) -> Option<String> {
|
||||
port.dir.clone()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
|
||||
fn signals(src: &str) -> Vec<(String, &'static str, Option<String>)> {
|
||||
let (file, _) = parse_source_tolerant(src);
|
||||
module_signals(&file).into_iter().map(|decl| (decl.name, decl.what, decl.dir)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collects_header_ports_body_ports_and_signals() {
|
||||
let src = "module m (input logic clk, output data);\n\
|
||||
\x20 wire a;\n\
|
||||
\x20 logic [7:0] b, c;\n\
|
||||
endmodule\n";
|
||||
assert_eq!(
|
||||
signals(src),
|
||||
vec![
|
||||
("clk".to_string(), "port", Some("input".to_string())),
|
||||
("data".to_string(), "port", Some("output".to_string())),
|
||||
("a".to_string(), "signal", None),
|
||||
("b".to_string(), "signal", None),
|
||||
("c".to_string(), "signal", None),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_with_no_direction_continues_the_previous_one() {
|
||||
let src = "module m (input logic a, b, output c);\nendmodule\n";
|
||||
let dirs: Vec<Option<String>> = signals(src).into_iter().map(|s| s.2).collect();
|
||||
assert_eq!(
|
||||
dirs,
|
||||
vec![Some("input".to_string()), Some("input".to_string()), Some("output".to_string())]
|
||||
);
|
||||
}
|
||||
|
||||
/// A non-ANSI port is declared once, in the body: the header only lists
|
||||
/// the names, and collecting those too would report every such port
|
||||
/// twice.
|
||||
#[test]
|
||||
fn a_non_ansi_port_is_collected_where_the_body_declares_it() {
|
||||
let src = "module m (a, b);\n input a;\n output b;\nendmodule\n";
|
||||
assert_eq!(
|
||||
signals(src),
|
||||
vec![
|
||||
("a".to_string(), "port", Some("input".to_string())),
|
||||
("b".to_string(), "port", Some("output".to_string())),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generate_blocks_are_descended_into_and_class_bodies_are_not() {
|
||||
let src = "module m;\n\
|
||||
\x20 generate\n\
|
||||
\x20 if (A) begin : g\n wire in_gen;\n end\n\
|
||||
\x20 endgenerate\n\
|
||||
\x20 for (genvar i = 0; i < 2; i++) begin : l\n wire looped;\n end\n\
|
||||
endmodule\n\
|
||||
class c;\n logic property_of_a_class;\nendclass\n";
|
||||
let names: Vec<String> = signals(src).into_iter().map(|s| s.0).collect();
|
||||
assert_eq!(names, vec!["in_gen".to_string(), "looped".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_and_a_module_in_a_package_are_covered() {
|
||||
let src = "interface i (input clk);\n wire w;\nendinterface\n\
|
||||
package p;\n module inner;\n wire deep;\n endmodule\nendpackage\n";
|
||||
let names: Vec<String> = signals(src).into_iter().map(|s| s.0).collect();
|
||||
assert_eq!(names, vec!["clk".to_string(), "w".to_string(), "deep".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_function_local_is_not_a_signal() {
|
||||
let src = "module m;\n function void f();\n logic local_var;\n endfunction\n\
|
||||
endmodule\n";
|
||||
assert!(signals(src).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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(), "[]");
|
||||
}
|
||||
}
|
||||
@@ -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 ¤t {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The rule trait and the table of rules that exist.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::options::OptionSpec;
|
||||
use crate::rules;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::{Applicability, Violation};
|
||||
@@ -59,6 +60,18 @@ pub trait Rule: Sync {
|
||||
None
|
||||
}
|
||||
|
||||
/// What a user may configure about this rule, or nothing.
|
||||
///
|
||||
/// The keys are Verible's wherever it has the same option, so a project
|
||||
/// migrating a `.rules.verible` file types the same words. A rule reads
|
||||
/// one through [`LintContext`], never from a run's settings directly, and
|
||||
/// always gets a value: the spec's default is the fallback, so there is no
|
||||
/// "unset" case in any rule. See
|
||||
/// `docs/features/linter-expansion-2/README.md`.
|
||||
fn options(&self) -> &'static [OptionSpec] {
|
||||
&[]
|
||||
}
|
||||
|
||||
/// Everything this rule finds in one file.
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation>;
|
||||
}
|
||||
@@ -66,19 +79,29 @@ pub trait Rule: Sync {
|
||||
/// Every rule that exists, in a stable order.
|
||||
pub fn all_rules() -> Vec<&'static dyn Rule> {
|
||||
vec![
|
||||
&rules::always_comb::AlwaysComb,
|
||||
&rules::always_comb_blocking::AlwaysCombBlocking,
|
||||
&rules::always_ff_non_blocking::AlwaysFfNonBlocking,
|
||||
&rules::banned_declared_name_patterns::BannedDeclaredNamePatterns,
|
||||
&rules::case_missing_default::CaseMissingDefault,
|
||||
&rules::constraint_name_style::ConstraintNameStyle,
|
||||
&rules::duplicate_declaration::DuplicateDeclaration,
|
||||
&rules::empty_item::EmptyItem,
|
||||
&rules::enum_name_style::EnumNameStyle,
|
||||
&rules::explicit_begin::ExplicitBegin,
|
||||
&rules::explicit_function_task_parameter_type::ExplicitFunctionTaskParameterType,
|
||||
&rules::explicit_parameter_storage_type::ExplicitParameterStorageType,
|
||||
&rules::forbid_consecutive_null_statements::ForbidConsecutiveNullStatements,
|
||||
&rules::forbid_defparam::ForbidDefparam,
|
||||
&rules::forbid_negative_array_dim::ForbidNegativeArrayDim,
|
||||
&rules::generate_label::GenerateLabel,
|
||||
&rules::generate_label_prefix::GenerateLabelPrefix,
|
||||
&rules::incomplete_assignment::IncompleteAssignment,
|
||||
&rules::instance_shadowing::InstanceShadowing,
|
||||
&rules::interface_name_style::InterfaceNameStyle,
|
||||
&rules::invalid_system_task_function::InvalidSystemTaskFunction,
|
||||
&rules::line_length::LineLength,
|
||||
&rules::macro_name_style::MacroNameStyle,
|
||||
&rules::mismatched_labels::MismatchedLabels,
|
||||
&rules::module_filename::ModuleFilename,
|
||||
&rules::module_name_style::ModuleNameStyle,
|
||||
@@ -87,12 +110,20 @@ pub fn all_rules() -> Vec<&'static dyn Rule> {
|
||||
&rules::multiply_driven::MultiplyDriven,
|
||||
&rules::no_tabs::NoTabs,
|
||||
&rules::no_trailing_whitespace::NoTrailingWhitespace,
|
||||
&rules::one_module_per_file::OneModulePerFile,
|
||||
&rules::package_filename::PackageFilename,
|
||||
&rules::packed_dimensions_range_ordering::PackedDimensionsRangeOrdering,
|
||||
&rules::parameter_name_style::ParameterNameStyle,
|
||||
&rules::parameter_type_name_style::ParameterTypeNameStyle,
|
||||
&rules::plusarg_assignment::PlusargAssignment,
|
||||
&rules::port_name_suffix::PortNameSuffix,
|
||||
&rules::posix_eof::PosixEof,
|
||||
&rules::signal_name_style::SignalNameStyle,
|
||||
&rules::struct_union_name_style::StructUnionNameStyle,
|
||||
&rules::suspicious_semicolon::SuspiciousSemicolon,
|
||||
&rules::truncated_numeric_literal::TruncatedNumericLiteral,
|
||||
&rules::typedef_enums::TypedefEnums,
|
||||
&rules::typedef_structs_unions::TypedefStructsUnions,
|
||||
&rules::undeclared_identifier::UndeclaredIdentifier,
|
||||
&rules::undersized_binary_literal::UndersizedBinaryLiteral,
|
||||
&rules::undriven_net::UndrivenNet,
|
||||
@@ -427,6 +458,67 @@ mod tests {
|
||||
assert!(message.contains("no-tabs"), "{message}");
|
||||
}
|
||||
|
||||
/// Every option a rule declares is one a user could actually write down,
|
||||
/// and one whose own default is acceptable to itself — a default outside
|
||||
/// its range, or a pattern that does not compile, would be a rule nobody
|
||||
/// could satisfy.
|
||||
#[test]
|
||||
fn every_declared_option_is_well_formed() {
|
||||
use crate::options::{OptionKind, RuleOptions};
|
||||
for rule in all_rules() {
|
||||
let mut names: Vec<&str> = rule.options().iter().map(|spec| spec.name).collect();
|
||||
let count = names.len();
|
||||
names.sort_unstable();
|
||||
names.dedup();
|
||||
assert_eq!(names.len(), count, "{}: duplicate option names", rule.name());
|
||||
for spec in rule.options() {
|
||||
let where_ = format!("{}.{}", rule.name(), spec.name);
|
||||
assert!(
|
||||
spec.name.chars().all(|c| c.is_ascii_lowercase()
|
||||
|| c.is_ascii_digit()
|
||||
|| c == '_'
|
||||
|| c == '-'),
|
||||
"{where_}: option names are lower-case words",
|
||||
);
|
||||
assert!(spec.doc.len() > 10, "{where_}: doc too thin");
|
||||
assert!(!spec.doc.ends_with('.'), "{where_}: doc ends in a period");
|
||||
let mut options = RuleOptions::new();
|
||||
options
|
||||
.set(rule.name(), spec.name, spec.default.value())
|
||||
.unwrap_or_else(|e| panic!("{where_}: its own default is refused: {e}"));
|
||||
if let OptionKind::Int { min, max } = spec.kind {
|
||||
assert!(min <= max, "{where_}: empty range");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The options §34 gave the four naming rules that predate them, spelled
|
||||
/// as Verible spells the same options.
|
||||
#[test]
|
||||
fn the_naming_rules_take_the_options_verible_gives_them() {
|
||||
let names = |rule: &str| {
|
||||
rule_by_name(rule)
|
||||
.unwrap_or_else(|| panic!("{rule} exists"))
|
||||
.options()
|
||||
.iter()
|
||||
.map(|spec| spec.name)
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(names("enum-name-style"), vec!["style_regex"]);
|
||||
assert_eq!(names("struct-union-name-style"), vec!["style_regex"]);
|
||||
assert_eq!(names("module-name-style"), vec!["style_regex"]);
|
||||
assert_eq!(
|
||||
names("parameter-name-style"),
|
||||
vec![
|
||||
"localparam_style",
|
||||
"localparam_style_regex",
|
||||
"parameter_style",
|
||||
"parameter_style_regex"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_by_name_finds_every_rule_and_nothing_else() {
|
||||
for rule in all_rules() {
|
||||
|
||||
@@ -6,8 +6,10 @@
|
||||
//! per rule. If a rule exists, it is in here; if its `doc` changes, so does
|
||||
//! this.
|
||||
|
||||
use crate::options::OptionKind;
|
||||
use crate::registry::all_rules;
|
||||
use crate::severity::Severity;
|
||||
use crate::Rule;
|
||||
|
||||
/// The whole rule reference as one markdown document.
|
||||
pub fn rules_markdown() -> String {
|
||||
@@ -30,7 +32,13 @@ pub fn rules_markdown() -> String {
|
||||
a stdin buffer it is off and must be selected. Any rule can be turned \
|
||||
off with `--ignore <name>`, with `ignore` under `[lint]` in \
|
||||
`lucisv.toml`, or waived in the source with `// lucisv: waive \
|
||||
<name>`.\n\n",
|
||||
<name>`.\n\n\
|
||||
A rule with **options** is configured in a `[lint.<rule-name>]` \
|
||||
table of a `lucisv.toml`, or from an editor with \
|
||||
`lucisv.lint.options`; an option nobody sets reads the default \
|
||||
listed with it. An unknown option name, a value of the wrong kind, \
|
||||
an integer out of range and a pattern that does not compile are all \
|
||||
refused, naming the file and the line.\n\n",
|
||||
);
|
||||
|
||||
out.push_str("| Rule | Severity | Default | Fix |\n|---|---|---|---|\n");
|
||||
@@ -58,11 +66,44 @@ pub fn rules_markdown() -> String {
|
||||
));
|
||||
out.push_str(rule.doc());
|
||||
out.push_str("\n\n");
|
||||
out.push_str(&options_table(rule));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A rule's options, as a small table under its prose — empty for a rule
|
||||
/// that takes none, which is most of them.
|
||||
fn options_table(rule: &dyn Rule) -> String {
|
||||
if rule.options().is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let mut out = String::from("| Option | Kind | Default | Meaning |\n|---|---|---|---|\n");
|
||||
for spec in rule.options() {
|
||||
out.push_str(&format!(
|
||||
"| `{name}` | {kind} | `{default}` | {doc} |\n",
|
||||
name = spec.name,
|
||||
kind = kind_word(spec.kind),
|
||||
default = spec.default.as_written(),
|
||||
doc = spec.doc,
|
||||
));
|
||||
}
|
||||
out.push('\n');
|
||||
out
|
||||
}
|
||||
|
||||
/// How the reference spells an option's kind, a `Words` option's vocabulary
|
||||
/// included — a user cannot guess `CamelCase|ALL_CAPS` from "word list".
|
||||
fn kind_word(kind: OptionKind) -> String {
|
||||
match kind {
|
||||
OptionKind::Int { min, max } => format!("integer {min}–{max}"),
|
||||
OptionKind::Words(vocabulary) => {
|
||||
format!("one or more of {} joined with `\\|`", vocabulary.join(", "))
|
||||
}
|
||||
other => other.as_str().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// How the table spells a rule's default: on, off, or on wherever there is a
|
||||
/// project to ask about ([`crate::Rule::needs_workspace`]).
|
||||
fn default_word(rule: &dyn crate::Rule) -> &'static str {
|
||||
@@ -171,13 +212,47 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every option a rule declares is in the reference, with the default a
|
||||
/// run that configures nothing actually reads.
|
||||
#[test]
|
||||
fn every_option_is_listed_with_its_kind_and_default() {
|
||||
let markdown = rules_markdown();
|
||||
for rule in all_rules() {
|
||||
for spec in rule.options() {
|
||||
assert!(
|
||||
markdown.contains(&format!("| `{}` |", spec.name)),
|
||||
"{}.{}",
|
||||
rule.name(),
|
||||
spec.name
|
||||
);
|
||||
assert!(markdown.contains(spec.doc), "{}.{}: doc", rule.name(), spec.name);
|
||||
}
|
||||
}
|
||||
assert!(markdown.contains("| `length` | integer 40–400 | `100` |"), "line-length");
|
||||
assert!(
|
||||
markdown.contains("| `prefix` | list of strings | `[\"g_\", \"gen_\"]` |"),
|
||||
"generate-label-prefix"
|
||||
);
|
||||
assert!(
|
||||
markdown.contains("one or more of CamelCase, ALL_CAPS joined with"),
|
||||
"parameter-name-style's vocabulary"
|
||||
);
|
||||
// A rule with no options gets no table.
|
||||
let no_tabs = markdown
|
||||
.split("## no-tabs\n")
|
||||
.nth(1)
|
||||
.and_then(|rest| rest.split("\n## ").next())
|
||||
.unwrap_or_default();
|
||||
assert!(!no_tabs.contains("| Option |"), "{no_tabs}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_document_shape_is_pinned() {
|
||||
// A golden test on the *shape*, not on the prose: the heading, the
|
||||
// generated-by note, the index table header, and the first per-rule
|
||||
// section, which together are what a reader (and any renderer) sees.
|
||||
let markdown = rules_markdown();
|
||||
let head: Vec<&str> = markdown.lines().take(10).collect();
|
||||
let head: Vec<&str> = markdown.lines().take(12).collect();
|
||||
assert_eq!(
|
||||
head,
|
||||
vec![
|
||||
@@ -200,6 +275,12 @@ mod tests {
|
||||
rule can be turned off with `--ignore <name>`, with `ignore` under `[lint]` in \
|
||||
`lucisv.toml`, or waived in the source with `// lucisv: waive <name>`.",
|
||||
"",
|
||||
"A rule with **options** is configured in a `[lint.<rule-name>]` table of a \
|
||||
`lucisv.toml`, or from an editor with `lucisv.lint.options`; an option nobody \
|
||||
sets reads the default listed with it. An unknown option name, a value of the \
|
||||
wrong kind, an integer out of range and a pattern that does not compile are \
|
||||
all refused, naming the file and the line.",
|
||||
"",
|
||||
"| Rule | Severity | Default | Fix |",
|
||||
"|---|---|---|---|",
|
||||
]
|
||||
@@ -209,12 +290,13 @@ mod tests {
|
||||
.find(|rule| rule.severity() == Severity::Error)
|
||||
.expect("some rule is an error");
|
||||
let section = format!(
|
||||
"## {}\n\n{}.\n\n- Severity: error\n- Default: {}\n- Fix: {}\n\n{}\n\n",
|
||||
"## {}\n\n{}.\n\n- Severity: error\n- Default: {}\n- Fix: {}\n\n{}\n\n{}",
|
||||
first_rule.name(),
|
||||
capitalize(first_rule.summary()),
|
||||
default_word(first_rule),
|
||||
fix_word(first_rule),
|
||||
first_rule.doc(),
|
||||
options_table(first_rule),
|
||||
);
|
||||
assert!(markdown.contains(§ion), "per-rule section shape changed:\n{section}");
|
||||
assert!(markdown.ends_with("\n\n"));
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
//! `always-comb` — write combinational logic as `always_comb`.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::{Applicability, Fix, Violation};
|
||||
use crate::visit::walk_items;
|
||||
use vlog_parser::ast::{ItemKind, SensList, StmtKind, TimingControl};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct AlwaysComb;
|
||||
|
||||
const NAME: &str = "always-comb";
|
||||
|
||||
impl Rule for AlwaysComb {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"write `always_comb` instead of `always @*`"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"`always_comb` says what the block is *for*, and the language checks \
|
||||
the claim: the tool errors if anything else drives one of its \
|
||||
left-hand sides, and it infers the sensitivity list including the \
|
||||
functions the block calls — which `always @*` does not. Verible's \
|
||||
`always-comb` (enabled by default) asks for the SystemVerilog \
|
||||
spelling wherever `always @*` or `always @(*)` is written, and lucisv \
|
||||
checks the same thing.\n\n\
|
||||
The fix is offered but **unsafe**, and the reason is real: an \
|
||||
`always_comb` block runs once at time zero and an `always @*` block \
|
||||
does not run until something in its sensitivity list changes, so a \
|
||||
testbench that samples before the first change can see a different \
|
||||
value. It also becomes an error for the block's outputs to be driven \
|
||||
anywhere else, which is usually the bug being found but is still a \
|
||||
change in what compiles. `--unsafe-fixes` applies it; the edit is the \
|
||||
keyword and its `@(*)`, nothing else."
|
||||
}
|
||||
|
||||
fn fix(&self) -> Option<Applicability> {
|
||||
Some(Applicability::Unsafe)
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_items(ctx.file(), &mut |item| {
|
||||
let ItemKind::Always { kw, stmt } = &item.kind else { return };
|
||||
if kw != "always" {
|
||||
return;
|
||||
}
|
||||
let StmtKind::Timing { control: TimingControl::Event(sens), stmt: Some(body) } =
|
||||
&stmt.kind
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if !matches!(sens, SensList::Star { .. }) {
|
||||
return;
|
||||
}
|
||||
let Some(header) = header_span(ctx, item.span.start, body.span.start) else { return };
|
||||
out.push(
|
||||
Violation::new(NAME, "use `always_comb` instead of `always @*`", header)
|
||||
.with_fix(Fix::unsafe_fix(vec![(header, "always_comb".to_string())])),
|
||||
);
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The `always @(*)` in front of the body: from the keyword to the end of the
|
||||
/// last token before the body starts.
|
||||
///
|
||||
/// Read off the tokens rather than assumed, because the sensitivity control
|
||||
/// may be written `@*`, `@ (*)` or `@( /* why */ * )`, and the fix must
|
||||
/// replace exactly what was written and not a byte more.
|
||||
fn header_span(ctx: &LintContext, start: u32, body: u32) -> Option<TextRange> {
|
||||
let end = ctx
|
||||
.tokens()
|
||||
.iter()
|
||||
.filter(|token| token.span.start >= start && token.span.end <= body)
|
||||
.map(|token| token.span.end)
|
||||
.max()?;
|
||||
(end > start).then(|| TextRange::new(start, end))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::violation::apply_fixes;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
AlwaysComb.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_both_spellings_and_rewrites_only_the_header() {
|
||||
for src in [
|
||||
"module m;\n always @(*) x = 1;\nendmodule\n",
|
||||
"module m;\n always @* x = 1;\nendmodule\n",
|
||||
] {
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{src}");
|
||||
let fixed = apply_fixes(src, &found, true);
|
||||
assert_eq!(fixed.output, "module m;\n always_comb x = 1;\nendmodule\n", "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fix_is_unsafe() {
|
||||
let src = "module m;\n always @(*) x = 1;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found[0].fix.as_ref().map(|f| f.applicability), Some(Applicability::Unsafe));
|
||||
assert_eq!(apply_fixes(src, &found, false).applied, 0, "not without --unsafe-fixes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_line_block_keeps_its_layout() {
|
||||
let src = "module m;\n always @(*) begin\n x = 1;\n end\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1);
|
||||
assert_eq!(
|
||||
apply_fixes(src, &found, true).output,
|
||||
"module m;\n always_comb begin\n x = 1;\n end\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_inside_the_control_is_replaced_with_it() {
|
||||
// The whole header is one edit, so a comment written inside `@( * )`
|
||||
// goes with it — which is why the fix is offered, not applied.
|
||||
let src = "module m;\n always @( /* all */ * ) x = 1;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1);
|
||||
assert_eq!(
|
||||
apply_fixes(src, &found, true).output,
|
||||
"module m;\n always_comb x = 1;\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicit_sensitivity_list_is_none_of_its_business() {
|
||||
for src in [
|
||||
"module m;\n always @(a or b) x = 1;\nendmodule\n",
|
||||
"module m;\n always @(posedge clk) q <= d;\nendmodule\n",
|
||||
"module m;\n always_comb x = 1;\nendmodule\n",
|
||||
"module m;\n always_ff @(posedge clk) q <= d;\nendmodule\n",
|
||||
"module m;\n always @(*);\nendmodule\n",
|
||||
] {
|
||||
assert!(violations(src).is_empty(), "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_always_star_inside_a_generate_block_is_covered() {
|
||||
let src = "module m;\n if (A) begin : g\n always @(*) x = 1;\n end\nendmodule\n";
|
||||
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
//! `banned-declared-name-patterns` — names a project has forbidden.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::options::{OptionDefault, OptionKind, OptionSpec};
|
||||
use crate::regex::Regex;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct BannedDeclaredNamePatterns;
|
||||
|
||||
const NAME: &str = "banned-declared-name-patterns";
|
||||
|
||||
impl Rule for BannedDeclaredNamePatterns {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"do not declare a name the project has banned"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"Every codebase has words it has decided against — a deprecated \
|
||||
prefix, a vendor's reserved namespace, the `tmp`/`foo` a review keeps \
|
||||
catching — and none of them are anybody else's business. Verible's \
|
||||
`banned-declared-name-patterns` is the rule a project points at its \
|
||||
own list, and it ships **off** with an empty list, which is exactly \
|
||||
what lucisv does: with no `patterns` set the rule reports nothing and \
|
||||
costs nothing.\n\n\
|
||||
It judges **declared** names, not uses: every name the file's symbol \
|
||||
table holds — modules, packages, types, parameters, signals, ports, \
|
||||
instances, block labels, class members. A pattern must match the whole \
|
||||
name, so `tmp.*` bans `tmp_addr` and `.*_tmp` bans `addr_tmp`. There \
|
||||
is no fix: only the author knows what the name should have been."
|
||||
}
|
||||
|
||||
fn default_on(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn options(&self) -> &'static [OptionSpec] {
|
||||
&[OptionSpec {
|
||||
name: "patterns",
|
||||
kind: OptionKind::RegexList,
|
||||
default: OptionDefault::List(&[]),
|
||||
doc: "the patterns a declared name may not match",
|
||||
}]
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let patterns: Vec<(String, Regex)> = ctx
|
||||
.option_list(NAME, "patterns")
|
||||
.into_iter()
|
||||
// A pattern that does not compile cannot be configured — the
|
||||
// option is validated when it is read — so filtering here only
|
||||
// ever drops what could not have arrived.
|
||||
.filter_map(|text| Regex::compile(&text).ok().map(|regex| (text, regex)))
|
||||
.collect();
|
||||
if patterns.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for symbol in ctx.semantics().symbols() {
|
||||
let Some((pattern, _)) =
|
||||
patterns.iter().find(|(_, regex)| regex.is_match(&symbol.name))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!("`{}` matches the banned pattern `{pattern}`", symbol.name),
|
||||
symbol.name_span,
|
||||
));
|
||||
}
|
||||
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::options::RuleOptions;
|
||||
|
||||
fn banning(patterns: &str, src: &str) -> Vec<Violation> {
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw(NAME, "patterns", patterns).expect("accepted");
|
||||
BannedDeclaredNamePatterns.check(&LintContext::new(src, None).with_options(&options))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_is_banned_by_default() {
|
||||
let src = "module m;\n logic tmp_addr;\nendmodule\n";
|
||||
assert!(BannedDeclaredNamePatterns.check(&LintContext::new(src, None)).is_empty());
|
||||
assert!(!BannedDeclaredNamePatterns.default_on());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_banned_name_is_reported_where_it_is_declared() {
|
||||
let src = "module m;\n logic tmp_addr;\n logic keep_me;\nendmodule\n";
|
||||
let found = banning("[\"tmp.*\"]", src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("banned pattern `tmp.*`"), "{}", found[0].message);
|
||||
assert_eq!(&src[found[0].span.as_range()], "tmp_addr");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_match_is_the_whole_name() {
|
||||
let src = "module m;\n logic addr_tmp;\nendmodule\n";
|
||||
assert!(banning("[\"tmp\"]", src).is_empty(), "a substring is not a match");
|
||||
assert_eq!(banning("[\".*_tmp\"]", src).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_kind_of_declared_name_is_covered() {
|
||||
let src = "package foo_pkg;\n typedef logic foo_t;\nendpackage\n\
|
||||
module foo_mod (input logic foo_port);\n logic foo_sig;\nendmodule\n";
|
||||
let found = banning("[\"foo.*\"]", src);
|
||||
let names: Vec<&str> = found.iter().map(|v| &src[v.span.as_range()]).collect();
|
||||
for wanted in ["foo_pkg", "foo_t", "foo_mod", "foo_port", "foo_sig"] {
|
||||
assert!(names.contains(&wanted), "{wanted} missing from {names:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_patterns_are_all_applied_and_findings_come_back_in_order() {
|
||||
let src = "module m;\n logic tmp_a;\n logic bad_b;\nendmodule\n";
|
||||
let found = banning("[\"tmp.*\", \"bad.*\"]", src);
|
||||
assert_eq!(found.len(), 2);
|
||||
assert!(found[0].span.start < found[1].span.start);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//! `constraint-name-style` — constraint names end in `_c`.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::naming::{fits_pattern, is_escaped, style_message};
|
||||
use crate::options::{OptionDefault, OptionKind, OptionSpec};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_items;
|
||||
use vlog_parser::ast::ItemKind;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct ConstraintNameStyle;
|
||||
|
||||
const NAME: &str = "constraint-name-style";
|
||||
|
||||
impl Rule for ConstraintNameStyle {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"name constraints in lower_snake_case ending in _c"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A constraint block's name is what a test turns off — \
|
||||
`obj.addr_range_c.constraint_mode(0)` — so it is read far from its \
|
||||
declaration and needs to say what it is at the use site. Verible's \
|
||||
`constraint-name-style` (enabled by default) spells the convention as \
|
||||
`([a-z0-9]+_)+c`: lower-case words, then a `_c` suffix. lucisv checks \
|
||||
the same pattern, on the constraints a class declares and on the \
|
||||
out-of-block `constraint cls::name { … }` form.\n\n\
|
||||
A prototype (`constraint c;`) is judged like a definition — it \
|
||||
declares the same name. Escaped identifiers are exempt, and there is \
|
||||
no fix: a rename reaches every `constraint_mode` call."
|
||||
}
|
||||
|
||||
fn options(&self) -> &'static [OptionSpec] {
|
||||
&[OptionSpec {
|
||||
name: "pattern",
|
||||
kind: OptionKind::Regex,
|
||||
default: OptionDefault::Str("([a-z0-9]+_)+c"),
|
||||
doc: "the pattern a constraint's whole name must match",
|
||||
}]
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_items(ctx.file(), &mut |item| {
|
||||
let ItemKind::Constraint(decl) = &item.kind else { return };
|
||||
let name = &decl.name.text;
|
||||
if is_escaped(name) || fits_pattern(ctx, NAME, "pattern", name) {
|
||||
return;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
style_message(
|
||||
ctx,
|
||||
NAME,
|
||||
"pattern",
|
||||
&format!("constraint `{name}`"),
|
||||
"is not lower_snake_case ending in `_c`",
|
||||
),
|
||||
decl.name.span,
|
||||
));
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::options::RuleOptions;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
ConstraintNameStyle.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn constraint(name: &str) -> String {
|
||||
format!("class c;\n rand int addr;\n constraint {name} {{ addr > 0; }}\nendclass\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_missing_suffix_and_points_at_the_name() {
|
||||
let src = constraint("addr_range");
|
||||
let found = violations(&src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "addr_range");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_convention_is_clean() {
|
||||
for name in ["addr_range_c", "a_c", "addr2_range_c"] {
|
||||
assert!(violations(&constraint(name)).is_empty(), "{name}");
|
||||
}
|
||||
for name in ["c", "AddrRangeC", "addr_range", "_addr_c"] {
|
||||
assert_eq!(violations(&constraint(name)).len(), 1, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prototype_and_an_out_of_block_definition_are_judged_too() {
|
||||
let src = "class c;\n extern constraint addr_range;\nendclass\n";
|
||||
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
|
||||
let src = "constraint c::addr_range { x > 0; }\n";
|
||||
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_configured_pattern_replaces_the_default() {
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw(NAME, "pattern", "\"c_[a-z_0-9]+\"").expect("accepted");
|
||||
let src = constraint("c_addr_range");
|
||||
let ctx = LintContext::new(&src, None).with_options(&options);
|
||||
assert!(ConstraintNameStyle.check(&ctx).is_empty());
|
||||
let src = constraint("addr_range_c");
|
||||
let ctx = LintContext::new(&src, None).with_options(&options);
|
||||
assert_eq!(ConstraintNameStyle.check(&ctx).len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
//! or `_t`.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::naming::{is_escaped, is_lower_snake_case};
|
||||
use crate::naming::{fits_pattern, is_escaped};
|
||||
use crate::options::{OptionDefault, OptionKind, OptionSpec};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
@@ -36,7 +37,20 @@ impl Rule for EnumNameStyle {
|
||||
same shape. Only a `typedef enum` is judged: an anonymous enum has no \
|
||||
name to check, and giving it one is Verible's separate \
|
||||
`typedef-enums` idea. Escaped identifiers are exempt, and there is no \
|
||||
fix: a type rename reaches every use."
|
||||
fix: a type rename reaches every use.\n\n\
|
||||
The shape is the `style_regex` option, and its default is \
|
||||
`[a-z][a-z_0-9]*(_t|_e)` — Verible's pattern with the first character \
|
||||
pinned to a letter, which is what lucisv's preset checked before the \
|
||||
option existed and what keeps a leading `_` reported."
|
||||
}
|
||||
|
||||
fn options(&self) -> &'static [OptionSpec] {
|
||||
&[OptionSpec {
|
||||
name: "style_regex",
|
||||
kind: OptionKind::Regex,
|
||||
default: OptionDefault::Str(DEFAULT_STYLE),
|
||||
doc: "the pattern an enum typedef's whole name must match",
|
||||
}]
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
@@ -47,13 +61,18 @@ impl Rule for EnumNameStyle {
|
||||
return;
|
||||
}
|
||||
let name = &typedef.name;
|
||||
let suffixed = name.ends_with("_e") || name.ends_with("_t");
|
||||
if is_lower_snake_case(name) && suffixed {
|
||||
if fits_pattern(ctx, NAME, "style_regex", name) {
|
||||
return;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!("enum `{name}` is not lower_snake_case ending in `_e` or `_t`"),
|
||||
crate::naming::style_message(
|
||||
ctx,
|
||||
NAME,
|
||||
"style_regex",
|
||||
&format!("enum `{name}`"),
|
||||
"is not lower_snake_case ending in `_e` or `_t`",
|
||||
),
|
||||
typedef.name_span,
|
||||
));
|
||||
});
|
||||
@@ -61,6 +80,10 @@ impl Rule for EnumNameStyle {
|
||||
}
|
||||
}
|
||||
|
||||
/// Today's preset, written as a pattern: `lower_snake_case` (a letter first)
|
||||
/// ending in `_e` or `_t`.
|
||||
const DEFAULT_STYLE: &str = "[a-z][a-z_0-9]*(_t|_e)";
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -109,4 +132,31 @@ mod tests {
|
||||
let src = typedef("state");
|
||||
assert_eq!(&src[violations(&src)[0].span.as_range()], "state");
|
||||
}
|
||||
|
||||
/// The default pattern is today's preset, character for character: a
|
||||
/// leading `_` or digit is still rejected, which Verible's own
|
||||
/// `[a-z_0-9]+(_t|_e)` would accept.
|
||||
#[test]
|
||||
fn the_default_pattern_is_the_preset_it_replaced() {
|
||||
for bad in ["_state_t", "State_t", "state"] {
|
||||
assert_eq!(violations(&typedef(bad)).len(), 1, "{bad}");
|
||||
}
|
||||
for good in ["state_t", "state_e", "s_t", "fifo2_state_e"] {
|
||||
assert!(violations(&typedef(good)).is_empty(), "{good}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_configured_pattern_replaces_it_and_is_named_in_the_message() {
|
||||
let mut options = crate::options::RuleOptions::new();
|
||||
options.set_raw(NAME, "style_regex", "\"[a-z_0-9]+_e\"").expect("accepted");
|
||||
let src = typedef("state_t");
|
||||
let ctx = LintContext::new(&src, None).with_options(&options);
|
||||
let found = EnumNameStyle.check(&ctx);
|
||||
assert_eq!(found.len(), 1, "`_t` is no longer accepted");
|
||||
assert!(found[0].message.contains("[a-z_0-9]+_e"), "{}", found[0].message);
|
||||
let src = typedef("_state_e");
|
||||
let ctx = LintContext::new(&src, None).with_options(&options);
|
||||
assert!(EnumNameStyle.check(&ctx).is_empty(), "and a leading `_` now passes");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
//! `explicit-begin` — a body is a `begin ... end` block, always.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::options::{OptionDefault, OptionKind, OptionSpec};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::{Applicability, Fix, Violation};
|
||||
use crate::visit::{walk_all_stmts, walk_items};
|
||||
use vlog_parser::ast::{ItemKind, Stmt, StmtKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct ExplicitBegin;
|
||||
|
||||
const NAME: &str = "explicit-begin";
|
||||
|
||||
/// The eleven constructs Verible lets a project switch on one at a time, each
|
||||
/// with the keyword a diagnostic names it by.
|
||||
const ENABLES: [(&str, &str); 11] = [
|
||||
("always_comb_enable", "always_comb"),
|
||||
("always_enable", "always"),
|
||||
("always_ff_enable", "always_ff"),
|
||||
("always_latch_enable", "always_latch"),
|
||||
("else_enable", "else"),
|
||||
("final_enable", "final"),
|
||||
("for_enable", "for"),
|
||||
("forever_enable", "forever"),
|
||||
("if_enable", "if"),
|
||||
("initial_enable", "initial"),
|
||||
("while_enable", "while"),
|
||||
];
|
||||
|
||||
impl Rule for ExplicitBegin {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"wrap every body in `begin` and `end`"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"The classic C bug transplanted: `if (a) x = 1;` grows a second \
|
||||
statement in a later edit, the author indents it, and the compiler \
|
||||
reads it as unconditional. Writing `begin ... end` from the start \
|
||||
makes that edit impossible to get wrong, which is why several house \
|
||||
styles require it. Verible's `explicit-begin` ships **off** — the \
|
||||
style is far from universal, and a codebase that does not follow it \
|
||||
would light up on the first run — and lucisv keeps it off for the same \
|
||||
reason.\n\n\
|
||||
Eleven `*_enable` options, exactly Verible's, switch the constructs on \
|
||||
and off one at a time; all are on when the rule is. An `else if` is \
|
||||
never reported: the `else`'s body is another `if`, which is the \
|
||||
chained form every style guide writes. A null body (`if (a) ;`) is \
|
||||
left to `suspicious-semicolon`, which has more to say about it. The \
|
||||
fix wraps the body in `begin`/`end` and is **safe** — a block around \
|
||||
one statement changes nothing — and running the formatter afterwards \
|
||||
lays it out."
|
||||
}
|
||||
|
||||
fn default_on(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn fix(&self) -> Option<Applicability> {
|
||||
Some(Applicability::Safe)
|
||||
}
|
||||
|
||||
fn options(&self) -> &'static [OptionSpec] {
|
||||
// Written out rather than generated, because a spec table is a
|
||||
// `static` and every entry needs its own `&'static str` doc.
|
||||
&[
|
||||
OptionSpec {
|
||||
name: "always_comb_enable",
|
||||
kind: OptionKind::Bool,
|
||||
default: OptionDefault::Bool(true),
|
||||
doc: "check the body of an `always_comb`",
|
||||
},
|
||||
OptionSpec {
|
||||
name: "always_enable",
|
||||
kind: OptionKind::Bool,
|
||||
default: OptionDefault::Bool(true),
|
||||
doc: "check the body of an `always`",
|
||||
},
|
||||
OptionSpec {
|
||||
name: "always_ff_enable",
|
||||
kind: OptionKind::Bool,
|
||||
default: OptionDefault::Bool(true),
|
||||
doc: "check the body of an `always_ff`",
|
||||
},
|
||||
OptionSpec {
|
||||
name: "always_latch_enable",
|
||||
kind: OptionKind::Bool,
|
||||
default: OptionDefault::Bool(true),
|
||||
doc: "check the body of an `always_latch`",
|
||||
},
|
||||
OptionSpec {
|
||||
name: "else_enable",
|
||||
kind: OptionKind::Bool,
|
||||
default: OptionDefault::Bool(true),
|
||||
doc: "check the body of an `else`",
|
||||
},
|
||||
OptionSpec {
|
||||
name: "final_enable",
|
||||
kind: OptionKind::Bool,
|
||||
default: OptionDefault::Bool(true),
|
||||
doc: "check the body of a `final`",
|
||||
},
|
||||
OptionSpec {
|
||||
name: "for_enable",
|
||||
kind: OptionKind::Bool,
|
||||
default: OptionDefault::Bool(true),
|
||||
doc: "check the body of a `for` loop",
|
||||
},
|
||||
OptionSpec {
|
||||
name: "forever_enable",
|
||||
kind: OptionKind::Bool,
|
||||
default: OptionDefault::Bool(true),
|
||||
doc: "check the body of a `forever` loop",
|
||||
},
|
||||
OptionSpec {
|
||||
name: "if_enable",
|
||||
kind: OptionKind::Bool,
|
||||
default: OptionDefault::Bool(true),
|
||||
doc: "check the body of an `if`",
|
||||
},
|
||||
OptionSpec {
|
||||
name: "initial_enable",
|
||||
kind: OptionKind::Bool,
|
||||
default: OptionDefault::Bool(true),
|
||||
doc: "check the body of an `initial`",
|
||||
},
|
||||
OptionSpec {
|
||||
name: "while_enable",
|
||||
kind: OptionKind::Bool,
|
||||
default: OptionDefault::Bool(true),
|
||||
doc: "check the body of a `while` loop",
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
let mut report = |keyword: &'static str, body: &Stmt| {
|
||||
if !enabled(ctx, keyword) || is_block(body) || matches!(body.kind, StmtKind::Null) {
|
||||
return;
|
||||
}
|
||||
out.push(
|
||||
Violation::new(
|
||||
NAME,
|
||||
format!("`{keyword}` body is not a `begin ... end` block"),
|
||||
body.span,
|
||||
)
|
||||
.with_fix(Fix::safe(vec![
|
||||
(TextRange::new(body.span.start, body.span.start), "begin ".to_string()),
|
||||
(TextRange::new(body.span.end, body.span.end), " end".to_string()),
|
||||
])),
|
||||
);
|
||||
};
|
||||
walk_items(ctx.file(), &mut |item| match &item.kind {
|
||||
ItemKind::Always { kw, stmt } => {
|
||||
let keyword = ENABLES
|
||||
.iter()
|
||||
.find_map(|(_, word)| (*word == kw).then_some(*word))
|
||||
.unwrap_or("always");
|
||||
if let Some(body) = procedural_body(stmt) {
|
||||
report(keyword, body);
|
||||
}
|
||||
}
|
||||
ItemKind::Initial(stmt) => {
|
||||
if let Some(body) = procedural_body(stmt) {
|
||||
report("initial", body);
|
||||
}
|
||||
}
|
||||
ItemKind::Final(stmt) => {
|
||||
if let Some(body) = procedural_body(stmt) {
|
||||
report("final", body);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
walk_all_stmts(ctx.file(), &mut |stmt| match &stmt.kind {
|
||||
StmtKind::If { then, els, .. } => {
|
||||
report("if", then);
|
||||
// `else if` is the chained form, not a missing block.
|
||||
if let Some(els) = els {
|
||||
if !matches!(els.kind, StmtKind::If { .. }) {
|
||||
report("else", els);
|
||||
}
|
||||
}
|
||||
}
|
||||
StmtKind::For { body, .. } => report("for", body),
|
||||
StmtKind::While { body, .. } => report("while", body),
|
||||
StmtKind::Forever { body } => report("forever", body),
|
||||
_ => {}
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the run wants this construct checked.
|
||||
fn enabled(ctx: &LintContext, keyword: &str) -> bool {
|
||||
ENABLES
|
||||
.iter()
|
||||
.find(|(_, word)| *word == keyword)
|
||||
.is_none_or(|(option, _)| ctx.option_bool(NAME, option))
|
||||
}
|
||||
|
||||
/// The statement a procedural block really runs: the one under its timing
|
||||
/// control, when it has one (`always_ff @(posedge clk) q <= d;`).
|
||||
///
|
||||
/// `None` for a timing control with no body at all (`always @(posedge clk);`),
|
||||
/// which has nothing to wrap.
|
||||
fn procedural_body(stmt: &Stmt) -> Option<&Stmt> {
|
||||
match &stmt.kind {
|
||||
StmtKind::Timing { stmt, .. } => stmt.as_deref(),
|
||||
_ => Some(stmt),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this statement is already a block.
|
||||
fn is_block(stmt: &Stmt) -> bool {
|
||||
matches!(stmt.kind, StmtKind::Block { .. } | StmtKind::ForkJoin { .. })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::options::RuleOptions;
|
||||
use crate::violation::apply_fixes;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
ExplicitBegin.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_is_off_by_default_and_takes_veribles_eleven_options() {
|
||||
assert!(!ExplicitBegin.default_on());
|
||||
let names: Vec<&str> = ExplicitBegin.options().iter().map(|spec| spec.name).collect();
|
||||
assert_eq!(names.len(), 11);
|
||||
assert!(names.contains(&"if_enable") && names.contains(&"always_ff_enable"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_an_unblocked_if_body_and_wraps_it() {
|
||||
let src = "module m;\n initial begin\n if (a) x = 1;\n end\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "x = 1;");
|
||||
let fixed = apply_fixes(src, &found, false);
|
||||
assert_eq!(
|
||||
fixed.output,
|
||||
"module m;\n initial begin\n if (a) begin x = 1; end\n end\nendmodule\n"
|
||||
);
|
||||
assert!(violations(&fixed.output).is_empty(), "the fix satisfies the rule");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blocked_body_is_clean() {
|
||||
let src = "module m;\n initial begin\n if (a) begin\n x = 1;\n end\n end\n\
|
||||
endmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_construct_is_covered() {
|
||||
let src = "module m;\n\
|
||||
\x20 always_comb x = 1;\n\
|
||||
\x20 always_ff @(posedge clk) q <= d;\n\
|
||||
\x20 always @(a) y = 2;\n\
|
||||
\x20 always_latch if (en) z = 3;\n\
|
||||
\x20 initial x = 0;\n\
|
||||
\x20 final $display(\"bye\");\n\
|
||||
endmodule\n";
|
||||
let found = violations(src);
|
||||
// Six bodies, plus the `if` inside the always_latch.
|
||||
assert_eq!(found.len(), 7, "{:#?}", found.iter().map(|v| &v.message).collect::<Vec<_>>());
|
||||
let src = "module m;\n initial begin\n\
|
||||
\x20 for (int i = 0; i < 2; i++) x = i;\n\
|
||||
\x20 while (a) y = 1;\n\
|
||||
\x20 forever z = 2;\n\
|
||||
\x20 end\nendmodule\n";
|
||||
assert_eq!(violations(src).len(), 3, "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_else_if_chain_is_not_a_missing_block() {
|
||||
let src = "module m;\n initial begin\n if (a) begin\n x = 1;\n end\n\
|
||||
\x20 else if (b) begin\n x = 2;\n end\n end\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_else_body_is_reported() {
|
||||
let src =
|
||||
"module m;\n initial begin\n if (a) begin\n x = 1;\n end else x = 2;\n\
|
||||
\x20 end\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("`else`"), "{}", found[0].message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_null_body_is_left_to_suspicious_semicolon() {
|
||||
let src = "module m;\n initial begin\n if (a) ;\n end\nendmodule\n";
|
||||
assert!(violations(src).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_option_switches_its_own_construct_off() {
|
||||
let src = "module m;\n initial begin\n if (a) x = 1;\n while (b) y = 2;\n end\n\
|
||||
endmodule\n";
|
||||
assert_eq!(violations(src).len(), 2);
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw(NAME, "if_enable", "false").expect("accepted");
|
||||
let found = ExplicitBegin.check(&LintContext::new(src, None).with_options(&options));
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("`while`"), "{}", found[0].message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fork_join_body_is_already_a_block() {
|
||||
let src = "module m;\n initial fork\n x = 1;\n join\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_items;
|
||||
use vlog_parser::ast::{ItemKind, TfArg};
|
||||
use vlog_parser::ast::{ItemKind, ListElem, TfArg};
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct ExplicitFunctionTaskParameterType;
|
||||
@@ -63,10 +63,10 @@ impl Rule for ExplicitFunctionTaskParameterType {
|
||||
/// writes a direction keyword opens a new declaration (and so a new type,
|
||||
/// implicit until written), and a formal that writes neither inherits whatever
|
||||
/// is in force.
|
||||
fn untyped(kw: &'static str, args: &[TfArg]) -> Vec<Violation> {
|
||||
fn untyped(kw: &'static str, args: &[ListElem<TfArg>]) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
let mut opened = false;
|
||||
for arg in args {
|
||||
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() {
|
||||
|
||||
@@ -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,118 @@
|
||||
//! `generate-label` — every generate block carries a label.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_generate_blocks;
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct GenerateLabel;
|
||||
|
||||
const NAME: &str = "generate-label";
|
||||
|
||||
impl Rule for GenerateLabel {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"label every generate block"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"An unlabelled generate block still has a name: the tool invents one \
|
||||
(`genblk3`), and that name is what appears in the hierarchy path, in \
|
||||
every waveform, in every constraint file and in every error message \
|
||||
the simulator prints. Renumbering happens the moment somebody adds a \
|
||||
block above it, so paths written against the invented names rot \
|
||||
silently. Verible's `generate-label` (enabled by default) requires the \
|
||||
`begin : name`, and lucisv checks the same thing on every `if`, `for` \
|
||||
and `case` generate block.\n\n\
|
||||
Only a block is judged. A generate `if` whose branch is a single item \
|
||||
with no `begin` opens no scope and needs no name — making it a block \
|
||||
is Verible's separate `generate-begin` family, which lucisv does not \
|
||||
have yet. There is no fix: only the author knows what the block should \
|
||||
be called."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
if !ctx.parsed_cleanly() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk_generate_blocks(ctx.file(), &mut |block| {
|
||||
if !block.is_block || block.label.is_some() {
|
||||
return;
|
||||
}
|
||||
// Point at the `begin`, which is where the label would be written.
|
||||
let begin = TextRange::new(block.span.start, block.span.start + 5);
|
||||
out.push(Violation::new(NAME, "generate block has no `: label`", begin));
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
GenerateLabel.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_an_unlabelled_block_and_points_at_its_begin() {
|
||||
let src = "module m;\n if (A) begin\n wire a;\n end\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "begin");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_labelled_block_is_clean() {
|
||||
let src = "module m;\n if (A) begin : g_a\n wire a;\n end\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_generate_shape_is_covered() {
|
||||
let src = "module m;\n\
|
||||
\x20 generate\n\
|
||||
\x20 for (genvar i = 0; i < 2; i++) begin\n wire a;\n end\n\
|
||||
\x20 if (A) begin\n wire b;\n end else begin\n wire c;\n end\n\
|
||||
\x20 case (A)\n 0: begin\n wire d;\n end\n endcase\n\
|
||||
\x20 endgenerate\n\
|
||||
endmodule\n";
|
||||
assert_eq!(violations(src).len(), 4, "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blockless_branch_opens_no_scope() {
|
||||
let src = "module m;\n if (A) wire a;\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_procedural_begin_is_not_a_generate_block() {
|
||||
let src = "module m;\n initial begin\n x = 1;\n end\nendmodule\n";
|
||||
assert!(violations(src).is_empty());
|
||||
}
|
||||
|
||||
/// The opentitan false-positive class: in a file error recovery could not
|
||||
/// put back together, a procedural `begin` can be rebound as a generate
|
||||
/// block. The rule says nothing about such a file.
|
||||
#[test]
|
||||
fn a_file_that_does_not_parse_is_left_alone() {
|
||||
let src = "module m;\n @@@ junk\n if (A) begin\n wire a;\n end\nendmodule\n";
|
||||
let ctx = LintContext::new(src, None);
|
||||
assert!(!ctx.parsed_cleanly(), "the probe needs a file that does not parse");
|
||||
assert!(GenerateLabel.check(&ctx).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
//! `generate-label-prefix` — a generate block's label says it is one.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::options::{OptionDefault, OptionKind, OptionSpec};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_generate_blocks;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct GenerateLabelPrefix;
|
||||
|
||||
const NAME: &str = "generate-label-prefix";
|
||||
|
||||
impl Rule for GenerateLabelPrefix {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"prefix a generate block's label with `g_` or `gen_`"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A generate label becomes a level of the instance hierarchy, so \
|
||||
`top.core.fifo.data` may or may not have a generate block in the \
|
||||
middle of it — and whether it does decides whether a path written in a \
|
||||
testbench, an SDC file or an assertion still resolves after the code \
|
||||
is re-parameterized. A prefix makes the generate levels visible in \
|
||||
every such path. Verible's `generate-label-prefix` (enabled by \
|
||||
default) requires one, and lucisv accepts `g_` or `gen_`, the two \
|
||||
spellings real RTL uses.\n\n\
|
||||
The `prefix` option is the list of accepted beginnings; an empty list \
|
||||
accepts every label, which is how a project turns the shape off while \
|
||||
keeping `generate-label`'s requirement that there *be* a label. There \
|
||||
is no fix: renaming a block changes every hierarchical path that names \
|
||||
it.\n\n\
|
||||
Silent in a file that does not fully parse, for the reason \
|
||||
`generate-label` gives: error recovery can rebind a procedural block \
|
||||
as a generate one, and a label judged there would be judged by the \
|
||||
wrong convention."
|
||||
}
|
||||
|
||||
fn options(&self) -> &'static [OptionSpec] {
|
||||
&[OptionSpec {
|
||||
name: "prefix",
|
||||
kind: OptionKind::List,
|
||||
default: OptionDefault::List(&["g_", "gen_"]),
|
||||
doc: "the beginnings a generate block's label may have",
|
||||
}]
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let prefixes = ctx.option_list(NAME, "prefix");
|
||||
if prefixes.is_empty() || !ctx.parsed_cleanly() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk_generate_blocks(ctx.file(), &mut |block| {
|
||||
let (Some(label), Some(span)) = (&block.label, block.label_span) else { return };
|
||||
if prefixes.iter().any(|prefix| label.starts_with(prefix.as_str())) {
|
||||
return;
|
||||
}
|
||||
let wanted: Vec<String> = prefixes.iter().map(|p| format!("`{p}`")).collect();
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!("generate label `{label}` does not start with {}", wanted.join(" or ")),
|
||||
span,
|
||||
));
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::options::RuleOptions;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
GenerateLabelPrefix.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn labelled(label: &str) -> String {
|
||||
format!("module m;\n if (A) begin : {label}\n wire a;\n end\nendmodule\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_label_with_no_prefix_and_points_at_it() {
|
||||
let src = labelled("core");
|
||||
let found = violations(&src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("`g_` or `gen_`"), "{}", found[0].message);
|
||||
assert_eq!(&src[found[0].span.as_range()], "core");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_conventional_prefixes_are_accepted() {
|
||||
assert!(violations(&labelled("g_core")).is_empty());
|
||||
assert!(violations(&labelled("gen_core")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unlabelled_block_is_generate_labels_business() {
|
||||
let src = "module m;\n if (A) begin\n wire a;\n end\nendmodule\n";
|
||||
assert!(violations(src).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_parse_is_left_alone() {
|
||||
let src = "module m;\n @@@ junk\n if (A) begin : core\n wire a;\n end\nendmodule\n";
|
||||
let ctx = LintContext::new(src, None);
|
||||
assert!(!ctx.parsed_cleanly());
|
||||
assert!(GenerateLabelPrefix.check(&ctx).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_for_generate_label_is_covered() {
|
||||
let src = "module m;\n for (genvar i = 0; i < 2; i++) begin : lanes\n wire a;\n end\n\
|
||||
endmodule\n";
|
||||
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_configured_list_replaces_the_default_and_an_empty_one_accepts_everything() {
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw(NAME, "prefix", "[\"blk_\"]").expect("accepted");
|
||||
let src = labelled("blk_core");
|
||||
assert!(GenerateLabelPrefix
|
||||
.check(&LintContext::new(&src, None).with_options(&options))
|
||||
.is_empty());
|
||||
let src = labelled("g_core");
|
||||
assert_eq!(
|
||||
GenerateLabelPrefix.check(&LintContext::new(&src, None).with_options(&options)).len(),
|
||||
1
|
||||
);
|
||||
|
||||
let mut empty = RuleOptions::new();
|
||||
empty.set_raw(NAME, "prefix", "[]").expect("accepted");
|
||||
let src = labelled("core");
|
||||
assert!(GenerateLabelPrefix
|
||||
.check(&LintContext::new(&src, None).with_options(&empty))
|
||||
.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
//! `interface-name-style` — interface names are `lower_snake_case` ending
|
||||
//! `_if`.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::naming::{fits_pattern, is_escaped, style_message};
|
||||
use crate::options::{OptionDefault, OptionKind, OptionSpec};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_items;
|
||||
use vlog_parser::ast::ItemKind;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct InterfaceNameStyle;
|
||||
|
||||
const NAME: &str = "interface-name-style";
|
||||
|
||||
impl Rule for InterfaceNameStyle {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"name interfaces in lower_snake_case ending in _if"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"An interface is written where a type is written — `virtual bus_if h`, \
|
||||
`bus_if.master port` — and nothing in the syntax says that the \
|
||||
identifier is an interface rather than a module or a class. The `_if` \
|
||||
suffix is what says it, and Verible's `interface-name-style` (enabled \
|
||||
by default, pattern `[a-z_0-9]+(_if)`) requires it. lucisv checks the \
|
||||
same shape, on every `interface` declaration in the file.\n\n\
|
||||
Only an `interface` is judged: a `module` and a `program` have their \
|
||||
own conventions, and `module-name-style` is where a project that wants \
|
||||
one says so. Escaped identifiers are exempt, and there is no fix — an \
|
||||
interface rename reaches every port, every virtual handle and every \
|
||||
file that imports it."
|
||||
}
|
||||
|
||||
fn options(&self) -> &'static [OptionSpec] {
|
||||
&[OptionSpec {
|
||||
name: "style_regex",
|
||||
kind: OptionKind::Regex,
|
||||
default: OptionDefault::Str("[a-z_0-9]+(_if)"),
|
||||
doc: "the pattern an interface's whole name must match",
|
||||
}]
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_items(ctx.file(), &mut |item| {
|
||||
let ItemKind::Module(module) = &item.kind else { return };
|
||||
if module.kw != "interface" || is_escaped(&module.name) {
|
||||
return;
|
||||
}
|
||||
if fits_pattern(ctx, NAME, "style_regex", &module.name) {
|
||||
return;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
style_message(
|
||||
ctx,
|
||||
NAME,
|
||||
"style_regex",
|
||||
&format!("interface `{}`", module.name),
|
||||
"is not lower_snake_case ending in `_if`",
|
||||
),
|
||||
module.name_span,
|
||||
));
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::options::RuleOptions;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
InterfaceNameStyle.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn interface(name: &str) -> String {
|
||||
format!("interface {name};\nendinterface\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_missing_suffix_and_points_at_the_name() {
|
||||
let src = interface("bus");
|
||||
let found = violations(&src);
|
||||
assert_eq!(found.len(), 1);
|
||||
assert!(found[0].message.contains("`bus`"), "{}", found[0].message);
|
||||
assert_eq!(&src[found[0].span.as_range()], "bus");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_convention_is_clean() {
|
||||
for name in ["bus_if", "clk_rst_if", "tl_if", "a_if"] {
|
||||
assert!(violations(&interface(name)).is_empty(), "{name}");
|
||||
}
|
||||
for name in ["BusIf", "bus_IF", "bus_intf"] {
|
||||
assert_eq!(violations(&interface(name)).len(), 1, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_or_a_program_is_none_of_its_business() {
|
||||
assert!(violations("module bus;\nendmodule\n").is_empty());
|
||||
assert!(violations("program test;\nendprogram\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_inside_a_package_is_covered() {
|
||||
let src = "package p;\n interface bus;\n endinterface\nendpackage\n";
|
||||
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_configured_pattern_replaces_the_default() {
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw(NAME, "style_regex", "\"[a-z_0-9]+_intf\"").expect("accepted");
|
||||
let src = interface("bus_intf");
|
||||
let ctx = LintContext::new(&src, None).with_options(&options);
|
||||
assert!(InterfaceNameStyle.check(&ctx).is_empty());
|
||||
let src = interface("bus_if");
|
||||
let ctx = LintContext::new(&src, None).with_options(&options);
|
||||
let found = InterfaceNameStyle.check(&ctx);
|
||||
assert_eq!(found.len(), 1);
|
||||
assert!(found[0].message.contains("_intf"), "{}", found[0].message);
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -7,19 +7,29 @@
|
||||
//! `instance-shadowing` through `vlog_semantic::Semantics` directly (see
|
||||
//! `docs/features/linter-expansion-1/README.md`).
|
||||
|
||||
pub mod always_comb;
|
||||
pub mod always_comb_blocking;
|
||||
pub mod always_ff_non_blocking;
|
||||
pub mod banned_declared_name_patterns;
|
||||
pub mod case_missing_default;
|
||||
pub mod constraint_name_style;
|
||||
pub mod duplicate_declaration;
|
||||
pub mod empty_item;
|
||||
pub mod enum_name_style;
|
||||
pub mod explicit_begin;
|
||||
pub mod explicit_function_task_parameter_type;
|
||||
pub mod explicit_parameter_storage_type;
|
||||
pub mod forbid_consecutive_null_statements;
|
||||
pub mod forbid_defparam;
|
||||
pub mod forbid_negative_array_dim;
|
||||
pub mod generate_label;
|
||||
pub mod generate_label_prefix;
|
||||
pub mod incomplete_assignment;
|
||||
pub mod instance_shadowing;
|
||||
pub mod interface_name_style;
|
||||
pub mod invalid_system_task_function;
|
||||
pub mod line_length;
|
||||
pub mod macro_name_style;
|
||||
pub mod mismatched_labels;
|
||||
pub mod module_filename;
|
||||
pub mod module_name_style;
|
||||
@@ -28,12 +38,20 @@ pub mod module_port;
|
||||
pub mod multiply_driven;
|
||||
pub mod no_tabs;
|
||||
pub mod no_trailing_whitespace;
|
||||
pub mod one_module_per_file;
|
||||
pub mod package_filename;
|
||||
pub mod packed_dimensions_range_ordering;
|
||||
pub mod parameter_name_style;
|
||||
pub mod parameter_type_name_style;
|
||||
pub mod plusarg_assignment;
|
||||
pub mod port_name_suffix;
|
||||
pub mod posix_eof;
|
||||
pub mod signal_name_style;
|
||||
pub mod struct_union_name_style;
|
||||
pub mod suspicious_semicolon;
|
||||
pub mod truncated_numeric_literal;
|
||||
pub mod typedef_enums;
|
||||
pub mod typedef_structs_unions;
|
||||
pub mod undeclared_identifier;
|
||||
pub mod undersized_binary_literal;
|
||||
pub mod undriven_net;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! `module-name-style` — module names are `lower_snake_case`.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::naming::{is_escaped, is_lower_snake_case};
|
||||
use crate::naming::{fits_pattern, is_escaped, style_message};
|
||||
use crate::options::{OptionDefault, OptionKind, OptionSpec};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
@@ -36,23 +37,44 @@ impl Rule for ModuleNameStyle {
|
||||
here, Verible ships no `module-name-style` rule to inherit a default \
|
||||
from, so enabling it is the user's call — `--select \
|
||||
module-name-style`. Escaped identifiers (`\\my$mod`) are exempt, and \
|
||||
there is no fix: renaming a module is a cross-file edit."
|
||||
there is no fix: renaming a module is a cross-file edit.\n\n\
|
||||
The shape is the `style_regex` option, default `[a-z][a-z_0-9]*` — \
|
||||
the preset this rule checked before the option existed. The rule \
|
||||
judges every `module`, `interface` and `program` name; a project that \
|
||||
wants the `_if` convention for its interfaces has \
|
||||
`interface-name-style` for that, and turning both on holds an \
|
||||
interface to both."
|
||||
}
|
||||
|
||||
fn default_on(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn options(&self) -> &'static [OptionSpec] {
|
||||
&[OptionSpec {
|
||||
name: "style_regex",
|
||||
kind: OptionKind::Regex,
|
||||
default: OptionDefault::Str("[a-z][a-z_0-9]*"),
|
||||
doc: "the pattern a module's whole name must match",
|
||||
}]
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_items(ctx.file(), &mut |item| {
|
||||
let ItemKind::Module(module) = &item.kind else { return };
|
||||
if is_escaped(&module.name) || is_lower_snake_case(&module.name) {
|
||||
if is_escaped(&module.name) || fits_pattern(ctx, NAME, "style_regex", &module.name) {
|
||||
return;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!("module `{}` is not lower_snake_case", module.name),
|
||||
style_message(
|
||||
ctx,
|
||||
NAME,
|
||||
"style_regex",
|
||||
&format!("module `{}`", module.name),
|
||||
"is not lower_snake_case",
|
||||
),
|
||||
module.name_span,
|
||||
));
|
||||
});
|
||||
@@ -99,4 +121,26 @@ mod tests {
|
||||
fn it_is_off_by_default() {
|
||||
assert!(!ModuleNameStyle.default_on());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_pattern_is_the_preset_it_replaced() {
|
||||
for bad in ["_foo", "FooBar", "fooBar"] {
|
||||
assert_eq!(violations(&format!("module {bad};\nendmodule\n")).len(), 1, "{bad}");
|
||||
}
|
||||
for good in ["foo", "foo_bar", "fifo2_ctrl"] {
|
||||
assert!(violations(&format!("module {good};\nendmodule\n")).is_empty(), "{good}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_configured_pattern_replaces_it() {
|
||||
let mut options = crate::options::RuleOptions::new();
|
||||
options.set_raw(NAME, "style_regex", "\"[A-Z][A-Za-z0-9]*\"").expect("accepted");
|
||||
let ctx = LintContext::new("module FooBar;\nendmodule\n", None).with_options(&options);
|
||||
assert!(ModuleNameStyle.check(&ctx).is_empty());
|
||||
let ctx = LintContext::new("module foo_bar;\nendmodule\n", None).with_options(&options);
|
||||
let found = ModuleNameStyle.check(&ctx);
|
||||
assert_eq!(found.len(), 1);
|
||||
assert!(found[0].message.contains("[A-Z][A-Za-z0-9]*"), "{}", found[0].message);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ 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;
|
||||
@@ -41,7 +42,8 @@ impl Rule for ModuleParameter {
|
||||
let mut out = Vec::new();
|
||||
walk_instantiations(ctx.file(), &mut |inst| {
|
||||
let Some(params) = &inst.params else { return };
|
||||
let positional = params.iter().filter(|conn| conn.name.is_empty()).count();
|
||||
let positional =
|
||||
params.iter().filter_map(ListElem::ok).filter(|conn| conn.name.is_empty()).count();
|
||||
if positional < 2 {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
//! `one-module-per-file` — one module declaration per file.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::ast::ItemKind;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct OneModulePerFile;
|
||||
|
||||
const NAME: &str = "one-module-per-file";
|
||||
|
||||
impl Rule for OneModulePerFile {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"declare one module per file"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"Every tool that finds a module by searching a library directory looks \
|
||||
for one named `<module>.sv`, and `module-filename` ties the file to the \
|
||||
module it declares — a claim that only means something when there is \
|
||||
exactly one. Verible's `one-module-per-file` is **off** by default and \
|
||||
so is this one: plenty of real RTL keeps a handful of small helper \
|
||||
modules beside the one the file is named for, and that is a project's \
|
||||
choice rather than a mistake.\n\n\
|
||||
Only the file's own `module` declarations count. An `interface`, a \
|
||||
`program` and a `package` are not modules — a package of types beside \
|
||||
the module that uses them is the common shape this rule must not \
|
||||
punish.\n\n\
|
||||
Silent in a file that does not fully parse: error recovery unwinds to \
|
||||
file scope, so a `module` written inside something the parser could \
|
||||
not finish reappears as a second top-level declaration — an accusation \
|
||||
about text the author never wrote that way."
|
||||
}
|
||||
|
||||
fn default_on(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
if !ctx.parsed_cleanly() {
|
||||
return Vec::new();
|
||||
}
|
||||
let modules: Vec<_> = ctx
|
||||
.file()
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|item| match &item.kind {
|
||||
ItemKind::Module(module) if module.kw == "module" => Some(module),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let Some(first) = modules.first() else { return Vec::new() };
|
||||
modules
|
||||
.iter()
|
||||
.skip(1)
|
||||
.map(|module| {
|
||||
Violation::new(
|
||||
NAME,
|
||||
format!(
|
||||
"module `{}` is the file's second declaration; `{}` is the first",
|
||||
module.name, first.name
|
||||
),
|
||||
module.name_span,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
OneModulePerFile.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_every_module_after_the_first() {
|
||||
let src = "module a;\nendmodule\nmodule b;\nendmodule\nmodule c;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 2);
|
||||
assert!(found[0].message.contains("`b`"), "{}", found[0].message);
|
||||
assert!(found[0].message.contains("`a` is the first"), "{}", found[0].message);
|
||||
assert_eq!(&src[found[1].span.as_range()], "c");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_module_is_clean() {
|
||||
assert!(violations("module a;\nendmodule\n").is_empty());
|
||||
assert!(violations("package p;\nendpackage\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_or_an_interface_beside_a_module_is_not_a_second_module() {
|
||||
let src = "package p;\nendpackage\nmodule a;\nendmodule\ninterface i;\nendinterface\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
/// The everyday shape this rule must not punish: one module, and the
|
||||
/// package of types it uses, in the same file.
|
||||
#[test]
|
||||
fn a_package_and_a_program_beside_one_module_are_clean() {
|
||||
let src = "package p;\n typedef logic w_t;\nendpackage\n\
|
||||
module a;\nendmodule\n\
|
||||
program t;\nendprogram\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_parse_is_left_alone() {
|
||||
// Recovery can promote a module the author nested inside something
|
||||
// else to file scope; this rule must not accuse them of it.
|
||||
let src = "module a;\n module inner;\n endmodule\nendmodule\n";
|
||||
let ctx = LintContext::new(src, None);
|
||||
assert!(!ctx.parsed_cleanly(), "a nested module does not parse");
|
||||
assert!(OneModulePerFile.check(&ctx).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_is_off_by_default() {
|
||||
assert!(!OneModulePerFile.default_on());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
//! `package-filename` — a one-package file is named after its package.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::options::{OptionDefault, OptionKind, OptionSpec};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::ast::ItemKind;
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct PackageFilename;
|
||||
|
||||
const NAME: &str = "package-filename";
|
||||
|
||||
impl Rule for PackageFilename {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"name a one-package file after its package"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A package is imported by name and found by file name, so the two \
|
||||
disagreeing costs the same grep every time. Verible's \
|
||||
`package-filename` (enabled by default) requires the file to be named \
|
||||
after the package it declares, and accepts a `_pkg` suffix on the file \
|
||||
that the package name does not carry — `foo` in `foo_pkg.sv` is the \
|
||||
convention half of the industry writes. lucisv accepts both spellings \
|
||||
for the same reason.\n\n\
|
||||
Like `module-filename`, it speaks only when the file declares exactly \
|
||||
one package, is silent for input with no file name (stdin), and offers \
|
||||
no fix: renaming a file is not the linter's business. The \
|
||||
`allow-dash-for-underscore` option lets a file named `foo-pkg.sv` \
|
||||
satisfy a package called `foo_pkg`, which is Verible's option of the \
|
||||
same name on `module-filename`. It is also silent in a file that does \
|
||||
not fully parse: `exactly one package` is a claim about structure, and \
|
||||
error recovery can invent a second one."
|
||||
}
|
||||
|
||||
fn options(&self) -> &'static [OptionSpec] {
|
||||
&[OptionSpec {
|
||||
name: "allow-dash-for-underscore",
|
||||
kind: OptionKind::Bool,
|
||||
default: OptionDefault::Bool(false),
|
||||
doc: "treat a `-` in the file name as the `_` of the package name",
|
||||
}]
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
if !ctx.parsed_cleanly() {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(path) = ctx.path() else { return Vec::new() };
|
||||
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { return Vec::new() };
|
||||
let mut packages = ctx.file().items.iter().filter_map(|item| match &item.kind {
|
||||
ItemKind::Package { name, name_span, .. } => Some((name, *name_span)),
|
||||
_ => None,
|
||||
});
|
||||
let (Some((name, span)), None) = (packages.next(), packages.next()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let stem = if ctx.option_bool(NAME, "allow-dash-for-underscore") {
|
||||
stem.replace('-', "_")
|
||||
} else {
|
||||
stem.to_string()
|
||||
};
|
||||
if stem == *name || stem == format!("{name}_pkg") {
|
||||
return Vec::new();
|
||||
}
|
||||
let file_name = path.file_name().and_then(|s| s.to_str()).unwrap_or(&stem);
|
||||
vec![report(name, span, file_name)]
|
||||
}
|
||||
}
|
||||
|
||||
fn report(name: &str, span: TextRange, file_name: &str) -> Violation {
|
||||
Violation::new(NAME, format!("package `{name}` does not match file name `{file_name}`"), span)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::options::RuleOptions;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn violations(src: &str, path: Option<&str>) -> Vec<Violation> {
|
||||
PackageFilename.check(&LintContext::new(src, path.map(PathBuf::from)))
|
||||
}
|
||||
|
||||
fn package(name: &str) -> String {
|
||||
format!("package {name};\nendpackage\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_mismatch_and_points_at_the_name() {
|
||||
let src = package("foo_pkg");
|
||||
let found = violations(&src, Some("rtl/bar.sv"));
|
||||
assert_eq!(found.len(), 1);
|
||||
assert!(found[0].message.contains("bar.sv"), "{}", found[0].message);
|
||||
assert_eq!(&src[found[0].span.as_range()], "foo_pkg");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_conventional_spellings_are_accepted() {
|
||||
assert!(violations(&package("foo_pkg"), Some("rtl/foo_pkg.sv")).is_empty());
|
||||
assert!(violations(&package("foo"), Some("rtl/foo.sv")).is_empty());
|
||||
assert!(violations(&package("foo"), Some("rtl/foo_pkg.sv")).is_empty(), "the `_pkg` file");
|
||||
assert!(violations(&package("foo"), Some("rtl/foo.svh")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silent_without_a_file_name_or_with_more_than_one_package() {
|
||||
assert!(violations(&package("foo"), None).is_empty());
|
||||
let two = "package a;\nendpackage\npackage b;\nendpackage\n";
|
||||
assert!(violations(two, Some("rtl/c.sv")).is_empty());
|
||||
assert!(violations("module m;\nendmodule\n", Some("rtl/c.sv")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_parse_is_left_alone() {
|
||||
let src = "package foo_pkg;\n @@@ junk\nendpackage\n";
|
||||
let ctx = LintContext::new(src, Some(PathBuf::from("rtl/bar.sv")));
|
||||
assert!(!ctx.parsed_cleanly());
|
||||
assert!(PackageFilename.check(&ctx).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dash_stands_for_an_underscore_only_when_asked() {
|
||||
let src = package("foo_pkg");
|
||||
assert_eq!(violations(&src, Some("rtl/foo-pkg.sv")).len(), 1);
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw(NAME, "allow-dash-for-underscore", "true").expect("accepted");
|
||||
let ctx =
|
||||
LintContext::new(&src, Some(PathBuf::from("rtl/foo-pkg.sv"))).with_options(&options);
|
||||
assert!(PackageFilename.check(&ctx).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
//! `parameter-name-style` — parameter names are `CamelCase` or `ALL_CAPS`.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::naming::{is_camel_case, is_escaped, is_upper_snake_case};
|
||||
use crate::naming::{fits_style, is_escaped, STYLE_WORDS};
|
||||
use crate::options::{OptionDefault, OptionKind, OptionSpec};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
@@ -34,23 +35,57 @@ impl Rule for ParameterNameStyle {
|
||||
this, with `CamelCase` and `ALL_CAPS` as its presets. lucisv accepts \
|
||||
either preset for both `parameter` and `localparam` — Verible's \
|
||||
default is stricter for `localparam` (`CamelCase` only), which would \
|
||||
flag most `localparam int FOO_BAR` in existing RTL; until per-rule \
|
||||
style configuration exists, the union is the honest default. The rule \
|
||||
covers item- and statement-level declarations and the `#( ... )` \
|
||||
parameter ports of module and class headers. Escaped identifiers are \
|
||||
exempt, and there is no fix: a rename reaches every override site."
|
||||
flag most `localparam int FOO_BAR` in existing RTL, so the union is \
|
||||
the default here and the option is where a project says otherwise. \
|
||||
The rule covers item- and statement-level declarations and the \
|
||||
`#( ... )` parameter ports of module and class headers. Escaped \
|
||||
identifiers are exempt, and there is no fix: a rename reaches every \
|
||||
override site.\n\n\
|
||||
Four options, spelled as Verible spells them: `parameter_style` and \
|
||||
`localparam_style` take `CamelCase`, `ALL_CAPS`, or both joined with \
|
||||
`|`; `parameter_style_regex` and `localparam_style_regex` replace the \
|
||||
words with a pattern for a project whose convention is neither."
|
||||
}
|
||||
|
||||
fn options(&self) -> &'static [OptionSpec] {
|
||||
&[
|
||||
OptionSpec {
|
||||
name: "localparam_style",
|
||||
kind: OptionKind::Words(&STYLE_WORDS),
|
||||
default: OptionDefault::Str(BOTH_PRESETS),
|
||||
doc: "the presets a `localparam` name may take, joined with `|`",
|
||||
},
|
||||
OptionSpec {
|
||||
name: "localparam_style_regex",
|
||||
kind: OptionKind::Regex,
|
||||
default: OptionDefault::Str(""),
|
||||
doc: "a pattern a `localparam` name must match instead of the presets",
|
||||
},
|
||||
OptionSpec {
|
||||
name: "parameter_style",
|
||||
kind: OptionKind::Words(&STYLE_WORDS),
|
||||
default: OptionDefault::Str(BOTH_PRESETS),
|
||||
doc: "the presets a `parameter` name may take, joined with `|`",
|
||||
},
|
||||
OptionSpec {
|
||||
name: "parameter_style_regex",
|
||||
kind: OptionKind::Regex,
|
||||
default: OptionDefault::Str(""),
|
||||
doc: "a pattern a `parameter` name must match instead of the presets",
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_items(ctx.file(), &mut |item| {
|
||||
if let ItemKind::ParamDecl(decl) = &item.kind {
|
||||
check_decl(decl, &mut out);
|
||||
check_decl(ctx, decl, &mut out);
|
||||
}
|
||||
});
|
||||
walk_all_stmts(ctx.file(), &mut |stmt| {
|
||||
if let StmtKind::ParamDecl(decl) = &stmt.kind {
|
||||
check_decl(decl, &mut out);
|
||||
check_decl(ctx, decl, &mut out);
|
||||
}
|
||||
});
|
||||
walk_param_ports(ctx.file(), &mut |port| {
|
||||
@@ -62,29 +97,41 @@ impl Rule for ParameterNameStyle {
|
||||
return;
|
||||
}
|
||||
let kw = port.kw.as_deref().unwrap_or("parameter");
|
||||
report(&port.name, port.name_span, kw, &mut out);
|
||||
report(ctx, &port.name, port.name_span, kw, &mut out);
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The presets both keywords accept unless a project says otherwise.
|
||||
const BOTH_PRESETS: &str = "CamelCase|ALL_CAPS";
|
||||
|
||||
/// Reports every declarator of one `parameter`/`localparam` declaration.
|
||||
fn check_decl(decl: &ParamDecl, out: &mut Vec<Violation>) {
|
||||
fn check_decl(ctx: &LintContext, decl: &ParamDecl, out: &mut Vec<Violation>) {
|
||||
for declarator in &decl.declarators {
|
||||
report(&declarator.name, declarator.name_span, &decl.kw, out);
|
||||
report(ctx, &declarator.name, declarator.name_span, &decl.kw, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reports `name` unless it matches one of the two accepted presets.
|
||||
fn report(name: &str, span: TextRange, kw: &str, out: &mut Vec<Violation>) {
|
||||
if is_escaped(name) || is_camel_case(name) || is_upper_snake_case(name) {
|
||||
/// Reports `name` unless it fits the style the run asks of its keyword.
|
||||
fn report(ctx: &LintContext, name: &str, span: TextRange, kw: &str, out: &mut Vec<Violation>) {
|
||||
let (style, regex) = if kw == "localparam" {
|
||||
("localparam_style", "localparam_style_regex")
|
||||
} else {
|
||||
("parameter_style", "parameter_style_regex")
|
||||
};
|
||||
if is_escaped(name) || fits_style(ctx, NAME, style, regex, name) {
|
||||
return;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!("`{kw}` `{name}` is neither CamelCase nor ALL_CAPS"),
|
||||
span,
|
||||
));
|
||||
let subject = format!("`{kw}` `{name}`");
|
||||
let message = if ctx.option_is_set(NAME, regex) {
|
||||
format!("{subject} does not match `{}`", ctx.option_str(NAME, regex))
|
||||
} else if ctx.option_is_set(NAME, style) {
|
||||
format!("{subject} is not {}", ctx.option_str(NAME, style).replace('|', " or "))
|
||||
} else {
|
||||
format!("{subject} is neither CamelCase nor ALL_CAPS")
|
||||
};
|
||||
out.push(Violation::new(NAME, message, span));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -141,4 +188,36 @@ mod tests {
|
||||
fn it_is_on_by_default() {
|
||||
assert!(ParameterNameStyle.default_on());
|
||||
}
|
||||
|
||||
fn with(options: &crate::options::RuleOptions, src: &str) -> Vec<Violation> {
|
||||
ParameterNameStyle.check(&LintContext::new(src, None).with_options(options))
|
||||
}
|
||||
|
||||
/// Verible's own default — `localparam_style: CamelCase` — is one option
|
||||
/// away, and it separates the two keywords as Verible does.
|
||||
#[test]
|
||||
fn the_two_keywords_take_their_own_styles() {
|
||||
let src = "module m;\n parameter int ADDR_W = 8;\n localparam int MAX_DEPTH = 4;\n\
|
||||
endmodule\n";
|
||||
assert!(violations(src).is_empty(), "both presets by default");
|
||||
let mut options = crate::options::RuleOptions::new();
|
||||
options.set_raw(NAME, "localparam_style", "\"CamelCase\"").expect("accepted");
|
||||
let found = with(&options, src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("MAX_DEPTH"), "{}", found[0].message);
|
||||
assert!(found[0].message.contains("is not CamelCase"), "{}", found[0].message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pattern_replaces_the_presets_for_that_keyword_only() {
|
||||
let mut options = crate::options::RuleOptions::new();
|
||||
options.set_raw(NAME, "parameter_style_regex", "\"p_[a-z_0-9]+\"").expect("accepted");
|
||||
let src = "module m;\n parameter int p_width = 8;\n localparam int MAX_DEPTH = 4;\n\
|
||||
endmodule\n";
|
||||
assert!(with(&options, src).is_empty(), "the localparam keeps its presets");
|
||||
let src = "module m;\n parameter int Width = 8;\nendmodule\n";
|
||||
let found = with(&options, src);
|
||||
assert_eq!(found.len(), 1);
|
||||
assert!(found[0].message.contains("p_[a-z_0-9]+"), "{}", found[0].message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//! `parameter-type-name-style` — `type` parameters are named like types.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::naming::{fits_pattern, is_escaped, style_message};
|
||||
use crate::options::{OptionDefault, OptionKind, OptionSpec};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_param_ports;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct ParameterTypeNameStyle;
|
||||
|
||||
const NAME: &str = "parameter-type-name-style";
|
||||
|
||||
impl Rule for ParameterTypeNameStyle {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"name type parameters in lower_snake_case ending in _t"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A `type` parameter is a type, not a constant: it is written where \
|
||||
`logic` or `addr_t` is written, and naming it `T` or `WIDTH_T` makes \
|
||||
a declaration read like an expression. Verible's \
|
||||
`parameter-type-name-style` asks for the same `lower_snake_case` with \
|
||||
a `_t` suffix every other type name here carries, and ships it **off**; \
|
||||
lucisv keeps it off, because the single-letter `#(type T = int)` is \
|
||||
near-universal in UVM code and switching this on for such a codebase \
|
||||
would report every class in it.\n\n\
|
||||
Only a `type` parameter is judged — an ordinary one is \
|
||||
`parameter-name-style`'s. Escaped identifiers are exempt, and there is \
|
||||
no fix: a rename reaches every override site."
|
||||
}
|
||||
|
||||
fn default_on(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn options(&self) -> &'static [OptionSpec] {
|
||||
&[OptionSpec {
|
||||
name: "style_regex",
|
||||
kind: OptionKind::Regex,
|
||||
default: OptionDefault::Str("[a-z][a-z_0-9]*_t"),
|
||||
doc: "the pattern a type parameter's whole name must match",
|
||||
}]
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_param_ports(ctx.file(), &mut |port| {
|
||||
if !port.is_type || is_escaped(&port.name) {
|
||||
return;
|
||||
}
|
||||
if fits_pattern(ctx, NAME, "style_regex", &port.name) {
|
||||
return;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
style_message(
|
||||
ctx,
|
||||
NAME,
|
||||
"style_regex",
|
||||
&format!("type parameter `{}`", port.name),
|
||||
"is not lower_snake_case ending in `_t`",
|
||||
),
|
||||
port.name_span,
|
||||
));
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::options::RuleOptions;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
ParameterTypeNameStyle.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_single_letter_type_parameter() {
|
||||
let src = "class c #(type T = int);\nendclass\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "T");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_convention_is_clean() {
|
||||
assert!(violations("class c #(type item_t = int);\nendclass\n").is_empty());
|
||||
assert!(violations("module m #(type addr_t = logic) ();\nendmodule\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ordinary_parameter_is_none_of_its_business() {
|
||||
assert!(violations("module m #(parameter int Width = 8) ();\nendmodule\n").is_empty());
|
||||
assert!(violations("module m;\n parameter int width = 8;\nendmodule\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_is_off_by_default() {
|
||||
assert!(!ParameterTypeNameStyle.default_on());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_configured_pattern_replaces_the_default() {
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw(NAME, "style_regex", "\"[A-Z]\"").expect("accepted");
|
||||
let ctx =
|
||||
LintContext::new("class c #(type T = int);\nendclass\n", None).with_options(&options);
|
||||
assert!(ParameterTypeNameStyle.check(&ctx).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
//! `port-name-suffix` — a port's name says which way it points.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::module_decls::module_signals;
|
||||
use crate::naming::is_escaped;
|
||||
use crate::options::{OptionDefault, OptionKind, OptionSpec};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct PortNameSuffix;
|
||||
|
||||
const NAME: &str = "port-name-suffix";
|
||||
|
||||
/// The six suffixes Verible knows, and the direction each one claims.
|
||||
const KNOWN: [(&str, &str); 6] = [
|
||||
("_i", "input"),
|
||||
("_ni", "input"),
|
||||
("_o", "output"),
|
||||
("_no", "output"),
|
||||
("_io", "inout"),
|
||||
("_nio", "inout"),
|
||||
];
|
||||
|
||||
impl Rule for PortNameSuffix {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"end a port's name with the suffix for its direction"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"At an instantiation, `.data(data)` says nothing about which way the \
|
||||
signal flows; `.data_i(data_o)` says it at a glance, and a mistake in \
|
||||
a connection list becomes visible without opening the module. The \
|
||||
lowRISC style guide asks for it and Verible's `port-name-suffix` \
|
||||
checks it: `_i` / `_ni` for an input, `_o` / `_no` for an output, \
|
||||
`_io` / `_nio` for an `inout`, where the `n` marks an active-low \
|
||||
signal. Both ship it **off** — a codebase that did not start with the \
|
||||
convention cannot adopt it one port at a time — and lucisv does too.\n\n\
|
||||
The `suffixes` option is the list of accepted endings. A suffix in it \
|
||||
that is one of the six known ones is accepted **only for its own \
|
||||
direction**, so shortening the list to `[\"_i\", \"_o\"]` bans the \
|
||||
active-low spellings without letting an input end in `_o`; any other \
|
||||
suffix a project adds is accepted for every direction, since only the \
|
||||
project knows what it means. A port whose direction the header does \
|
||||
not state — a non-ANSI name, declared in the body — is judged where \
|
||||
the body declares it. Escaped identifiers are exempt, and there is no \
|
||||
fix: renaming a port reaches every instantiation."
|
||||
}
|
||||
|
||||
fn default_on(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn options(&self) -> &'static [OptionSpec] {
|
||||
&[OptionSpec {
|
||||
name: "suffixes",
|
||||
kind: OptionKind::List,
|
||||
default: OptionDefault::List(&["_i", "_ni", "_o", "_no", "_io", "_nio"]),
|
||||
doc: "the endings a port name may have",
|
||||
}]
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let configured = ctx.option_list(NAME, "suffixes");
|
||||
let mut out = Vec::new();
|
||||
for port in module_signals(ctx.file()) {
|
||||
let (Some(dir), "port") = (port.dir.as_deref(), port.what) else { continue };
|
||||
if is_escaped(&port.name) {
|
||||
continue;
|
||||
}
|
||||
let allowed = allowed_for(&configured, dir);
|
||||
if allowed.is_empty() || allowed.iter().any(|s| port.name.ends_with(s.as_str())) {
|
||||
continue;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!("{dir} port `{}` does not end in {}", port.name, or_list(&allowed)),
|
||||
port.span,
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The configured suffixes this direction may use: a known suffix only where
|
||||
/// it belongs, and anything the project added everywhere.
|
||||
fn allowed_for(configured: &[String], dir: &str) -> Vec<String> {
|
||||
configured
|
||||
.iter()
|
||||
.filter(|suffix| {
|
||||
KNOWN.iter().find(|(known, _)| known == suffix).is_none_or(|(_, wants)| *wants == dir)
|
||||
})
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// "`_i` or `_ni`" — the list as a sentence.
|
||||
fn or_list(suffixes: &[String]) -> String {
|
||||
let quoted: Vec<String> = suffixes.iter().map(|s| format!("`{s}`")).collect();
|
||||
match quoted.split_last() {
|
||||
Some((last, [])) => last.clone(),
|
||||
Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
|
||||
None => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::options::RuleOptions;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
PortNameSuffix.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_port_with_no_suffix_and_names_what_it_wanted() {
|
||||
let src = "module m (input logic clk, output logic data);\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 2, "{found:?}");
|
||||
assert!(found[0].message.contains("input port `clk`"), "{}", found[0].message);
|
||||
assert!(found[0].message.contains("`_i` or `_ni`"), "{}", found[0].message);
|
||||
assert_eq!(&src[found[0].span.as_range()], "clk");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_convention_is_clean() {
|
||||
let src = "module m (input logic clk_i, input logic rst_ni, output logic data_o,\n\
|
||||
\x20 output logic ack_no, inout wire sda_io, inout wire scl_nio);\n\
|
||||
endmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_suffix_for_the_wrong_direction_is_still_wrong() {
|
||||
let src = "module m (input logic data_o);\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1);
|
||||
assert!(found[0].message.contains("input port `data_o`"), "{}", found[0].message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_body_declared_port_is_judged_where_its_direction_is() {
|
||||
// The non-ANSI header only lists the name; the body declaration is
|
||||
// the one that carries the direction, and the one reported.
|
||||
let src = "module m (clk);\n input clk;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(found[0].span.start as usize, src.rfind("clk").unwrap_or(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_signal_is_not_a_port() {
|
||||
assert!(violations("module m;\n logic internal;\nendmodule\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shortening_the_list_bans_the_active_low_spellings() {
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw(NAME, "suffixes", "[\"_i\", \"_o\"]").expect("accepted");
|
||||
let src = "module m (input logic rst_ni, input logic clk_i, output logic data_o);\n\
|
||||
endmodule\n";
|
||||
let ctx = LintContext::new(src, None).with_options(&options);
|
||||
let found = PortNameSuffix.check(&ctx);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("rst_ni"), "{}", found[0].message);
|
||||
assert!(found[0].message.contains("does not end in `_i`"), "{}", found[0].message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_specific_suffix_is_accepted_in_every_direction() {
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw(NAME, "suffixes", "[\"_pin\"]").expect("accepted");
|
||||
let src = "module m (input logic clk_pin, output logic data_pin);\nendmodule\n";
|
||||
let ctx = LintContext::new(src, None).with_options(&options);
|
||||
assert!(PortNameSuffix.check(&ctx).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_is_off_by_default() {
|
||||
assert!(!PortNameSuffix.default_on());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
//! `posix-eof` — a file ends with a newline.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::{Applicability, Fix, Violation};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct PosixEof;
|
||||
|
||||
const NAME: &str = "posix-eof";
|
||||
|
||||
impl Rule for PosixEof {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"end the file with a newline"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"POSIX defines a line as ending in a newline, so a file whose last line \
|
||||
has none has, formally, no last line: `cat` runs the next file into it, \
|
||||
`wc -l` counts one line short, and every diff of a later edit shows the \
|
||||
final line twice — once removed, once added with the newline. Verible's \
|
||||
`posix-eof` (enabled by default) asks for the newline and so does \
|
||||
lucisv's formatter, which always writes one. The fix appends it, which \
|
||||
cannot change what the code means. An empty file has no last line to \
|
||||
terminate and is left alone."
|
||||
}
|
||||
|
||||
fn fix(&self) -> Option<Applicability> {
|
||||
Some(Applicability::Safe)
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let source = ctx.source();
|
||||
if source.is_empty() || source.ends_with('\n') {
|
||||
return Vec::new();
|
||||
}
|
||||
let end = source.len() as u32;
|
||||
// The diagnostic points at the last character, which is where an
|
||||
// editor's cursor lands; the fix appends past it.
|
||||
let last = source.chars().next_back().map_or(end, |c| end - c.len_utf8() as u32);
|
||||
vec![Violation::new(NAME, "file does not end with a newline", TextRange::new(last, end))
|
||||
.with_fix(Fix::safe(vec![(TextRange::new(end, end), "\n".to_string())]))]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::violation::apply_fixes;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
PosixEof.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_missing_newline_and_appends_one() {
|
||||
let src = "module m;\nendmodule";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1);
|
||||
let fixed = apply_fixes(src, &found, false);
|
||||
assert_eq!(fixed.output, "module m;\nendmodule\n");
|
||||
assert!(violations(&fixed.output).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_terminated_file_is_clean() {
|
||||
assert!(violations("module m;\nendmodule\n").is_empty());
|
||||
assert!(violations("\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_file_has_no_last_line() {
|
||||
assert!(violations("").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_points_at_the_last_character() {
|
||||
let src = "module m;\nendmodule";
|
||||
let found = violations(src);
|
||||
assert_eq!(&src[found[0].span.as_range()], "e");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multibyte_last_character_is_not_split() {
|
||||
let src = "// naïve";
|
||||
let found = violations(src);
|
||||
assert_eq!(&src[found[0].span.as_range()], "e");
|
||||
assert_eq!(apply_fixes(src, &found, false).output, "// naïve\n");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
//! `signal-name-style` — nets, variables and ports are `lower_snake_case`.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::module_decls::module_signals;
|
||||
use crate::naming::{fits_pattern, is_escaped, style_message};
|
||||
use crate::options::{OptionDefault, OptionKind, OptionSpec};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct SignalNameStyle;
|
||||
|
||||
const NAME: &str = "signal-name-style";
|
||||
|
||||
impl Rule for SignalNameStyle {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"name signals in lower_snake_case"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A signal name is read in a waveform viewer next to a hundred others, \
|
||||
and a codebase that mixes `dataValid`, `DATA_VALID` and `data_valid` \
|
||||
makes every one of those a separate grep. Verible's \
|
||||
`signal-name-style` spells the convention as `[a-z_0-9]+` and ships it \
|
||||
**off**; lucisv keeps it off for the same reason \
|
||||
`parameter-name-style` keeps its union of presets — a naming rule \
|
||||
switched on for an existing codebase reports thousands of findings on \
|
||||
its first run, and that is a project's decision to make.\n\n\
|
||||
It judges the nets, variables and ports declared **inside a module, \
|
||||
interface or program**: the ANSI ports of the header, the non-ANSI \
|
||||
`input`/`output` declarations of the body, and the `wire`/`logic`/`reg` \
|
||||
declarations beside them. A class property is not a signal and is left \
|
||||
alone; a `parameter` is `parameter-name-style`'s, and a `genvar` names \
|
||||
a loop, not a wire. Escaped identifiers are exempt, and there is no \
|
||||
fix: renaming a signal reaches every use, including uses in other \
|
||||
files."
|
||||
}
|
||||
|
||||
fn default_on(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn options(&self) -> &'static [OptionSpec] {
|
||||
&[OptionSpec {
|
||||
name: "style_regex",
|
||||
kind: OptionKind::Regex,
|
||||
default: OptionDefault::Str("[a-z_0-9]+"),
|
||||
doc: "the pattern a signal's whole name must match",
|
||||
}]
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
for signal in module_signals(ctx.file()) {
|
||||
if is_escaped(&signal.name) || fits_pattern(ctx, NAME, "style_regex", &signal.name) {
|
||||
continue;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
style_message(
|
||||
ctx,
|
||||
NAME,
|
||||
"style_regex",
|
||||
&format!("{} `{}`", signal.what, signal.name),
|
||||
"is not lower_snake_case",
|
||||
),
|
||||
signal.span,
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::options::RuleOptions;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
SignalNameStyle.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_camel_case_signal_and_names_what_it_is() {
|
||||
let src = "module m;\n logic dataValid;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.starts_with("signal `dataValid`"), "{}", found[0].message);
|
||||
assert_eq!(&src[found[0].span.as_range()], "dataValid");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ports_of_both_header_styles_are_covered() {
|
||||
let ansi = "module m (input logic clkIn, output wire dataOut);\nendmodule\n";
|
||||
assert_eq!(violations(ansi).len(), 2, "{:?}", violations(ansi));
|
||||
assert!(violations(ansi)[0].message.starts_with("port `clkIn`"));
|
||||
let non_ansi = "module m (clkIn, dataOut);\n input clkIn;\n output dataOut;\nendmodule\n";
|
||||
// Once each: the header lists the names, the body declares them, and
|
||||
// the declaration is what is reported.
|
||||
assert_eq!(violations(non_ansi).len(), 2, "{:?}", violations(non_ansi));
|
||||
assert!(violations(non_ansi)[0].span.start as usize > non_ansi.find(");").unwrap_or(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conventional_names_are_clean() {
|
||||
let src = "module m (input logic clk_i, output wire data_o);\n logic [7:0] wr_ptr2;\n\
|
||||
endmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_signal_inside_a_generate_block_is_covered() {
|
||||
let src = "module m;\n generate\n if (A) begin : g\n logic dataValid;\n\
|
||||
\x20 end\n endgenerate\nendmodule\n";
|
||||
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_class_property_and_a_parameter_are_not_signals() {
|
||||
assert!(violations("class c;\n logic dataValid;\nendclass\n").is_empty());
|
||||
assert!(violations("module m;\n parameter int AddrWidth = 1;\nendmodule\n").is_empty());
|
||||
assert!(violations("module m;\n genvar iGen;\nendmodule\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_configured_pattern_replaces_the_default() {
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw(NAME, "style_regex", "\"[a-z][a-zA-Z0-9]*\"").expect("accepted");
|
||||
let ctx = LintContext::new("module m;\n logic dataValid;\nendmodule\n", None)
|
||||
.with_options(&options);
|
||||
assert!(SignalNameStyle.check(&ctx).is_empty());
|
||||
let ctx = LintContext::new("module m;\n logic data_valid;\nendmodule\n", None)
|
||||
.with_options(&options);
|
||||
assert_eq!(SignalNameStyle.check(&ctx).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_is_off_by_default() {
|
||||
assert!(!SignalNameStyle.default_on());
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
//! `lower_snake_case` ending `_t`.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::naming::{is_escaped, is_lower_snake_case};
|
||||
use crate::naming::{fits_pattern, is_escaped, style_message};
|
||||
use crate::options::{OptionDefault, OptionKind, OptionSpec};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
@@ -36,7 +37,20 @@ impl Rule for StructUnionNameStyle {
|
||||
a `typedef struct` / `typedef union` is judged — an anonymous struct \
|
||||
has no name, and requiring it to have one is Verible's separate \
|
||||
`typedef-structs-unions` idea. Escaped identifiers are exempt, and \
|
||||
there is no fix: a type rename reaches every use."
|
||||
there is no fix: a type rename reaches every use.\n\n\
|
||||
The shape is the `style_regex` option, whose default \
|
||||
`[a-z][a-z_0-9]*_t` is Verible's pattern with the first character \
|
||||
pinned to a letter — the preset lucisv checked before the option \
|
||||
existed."
|
||||
}
|
||||
|
||||
fn options(&self) -> &'static [OptionSpec] {
|
||||
&[OptionSpec {
|
||||
name: "style_regex",
|
||||
kind: OptionKind::Regex,
|
||||
default: OptionDefault::Str("[a-z][a-z_0-9]*_t"),
|
||||
doc: "the pattern a struct or union typedef's whole name must match",
|
||||
}]
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
@@ -45,12 +59,18 @@ impl Rule for StructUnionNameStyle {
|
||||
let ItemKind::Typedef(typedef) = &item.kind else { return };
|
||||
let TypedefKind::Struct(structure) = &typedef.kind else { return };
|
||||
let name = &typedef.name;
|
||||
if is_escaped(name) || (is_lower_snake_case(name) && name.ends_with("_t")) {
|
||||
if is_escaped(name) || fits_pattern(ctx, NAME, "style_regex", name) {
|
||||
return;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!("{} `{name}` is not lower_snake_case ending in `_t`", structure.kw),
|
||||
style_message(
|
||||
ctx,
|
||||
NAME,
|
||||
"style_regex",
|
||||
&format!("{} `{name}`", structure.kw),
|
||||
"is not lower_snake_case ending in `_t`",
|
||||
),
|
||||
typedef.name_span,
|
||||
));
|
||||
});
|
||||
@@ -101,6 +121,30 @@ mod tests {
|
||||
assert!(violations(src).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_pattern_is_the_preset_it_replaced() {
|
||||
for bad in ["_addr_t", "AddrT", "addr"] {
|
||||
assert_eq!(violations(&typedef("struct", bad)).len(), 1, "{bad}");
|
||||
}
|
||||
for good in ["addr_t", "a_t", "word2_t"] {
|
||||
assert!(violations(&typedef("struct", good)).is_empty(), "{good}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_configured_pattern_replaces_it() {
|
||||
let mut options = crate::options::RuleOptions::new();
|
||||
options.set_raw(NAME, "style_regex", "\"[a-z_0-9]+_s\"").expect("accepted");
|
||||
let src = typedef("struct", "addr_s");
|
||||
let ctx = LintContext::new(&src, None).with_options(&options);
|
||||
assert!(StructUnionNameStyle.check(&ctx).is_empty());
|
||||
let src = typedef("struct", "addr_t");
|
||||
let ctx = LintContext::new(&src, None).with_options(&options);
|
||||
let found = StructUnionNameStyle.check(&ctx);
|
||||
assert_eq!(found.len(), 1);
|
||||
assert!(found[0].message.contains("[a-z_0-9]+_s"), "{}", found[0].message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_struct_typedef_inside_a_class_body_is_covered() {
|
||||
let src = "class c;\n typedef struct packed { logic a; } addr;\nendclass\n";
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
//! `typedef-enums` — an `enum` type is declared with a `typedef`.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::decls::walk_declared_types;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::ast::TypeExtra;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct TypedefEnums;
|
||||
|
||||
const NAME: &str = "typedef-enums";
|
||||
|
||||
impl Rule for TypedefEnums {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"give an enum type a name with `typedef`"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"An anonymous `enum logic [1:0] {IDLE, BUSY} state;` gives the enum no \
|
||||
name, and the language gives no way to write one afterwards: a \
|
||||
function cannot take the type, a port cannot carry it, a cast cannot \
|
||||
name it, and a second variable of the same states has to repeat the \
|
||||
whole list — where the two copies are *different* types to the \
|
||||
compiler. Verible's `typedef-enums` (enabled by default) asks for the \
|
||||
`typedef`, and lucisv checks the same shape.\n\n\
|
||||
Every declaration is judged: a variable, a port, a struct member. \
|
||||
There is no fix — where the `typedef` should go (this file, the \
|
||||
package next to it) is a design decision, not a rewrite."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_declared_types(ctx.file(), &mut |declared| {
|
||||
if !matches!(declared.ty.inline(), Some(TypeExtra::Enum(_))) {
|
||||
return;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!(
|
||||
"`{}` is declared with an anonymous enum; name it with `typedef`",
|
||||
declared.name
|
||||
),
|
||||
declared.span,
|
||||
));
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
TypedefEnums.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_an_anonymous_enum_variable_and_points_at_the_name() {
|
||||
let src = "module m;\n enum logic [1:0] { IDLE, BUSY } state;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "state");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typedef_enum_is_the_shape_it_asks_for() {
|
||||
let src = "package p;\n typedef enum logic [1:0] { IDLE, BUSY } state_e;\nendpackage\n\
|
||||
module m;\n state_e state;\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_and_a_struct_member_are_covered() {
|
||||
let src = "module m (input enum logic { A, B } mode);\nendmodule\n";
|
||||
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
|
||||
let src = "package p;\n typedef struct packed {\n\
|
||||
\x20 enum logic { A, B } inner;\n } outer_t;\nendpackage\n";
|
||||
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_variable_declared_in_a_procedure_is_covered() {
|
||||
let src = "module m;\n initial begin\n enum logic { A, B } local_state;\n end\n\
|
||||
endmodule\n";
|
||||
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ordinary_declaration_is_none_of_its_business() {
|
||||
assert!(violations("module m;\n logic [1:0] state;\nendmodule\n").is_empty());
|
||||
let src = "module m;\n struct packed { logic a; } s;\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "structs are the other rule's");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
//! `typedef-structs-unions` — a `struct`/`union` type is declared with a
|
||||
//! `typedef`.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::decls::walk_declared_types;
|
||||
use crate::options::{OptionDefault, OptionKind, OptionSpec};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::ast::TypeExtra;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct TypedefStructsUnions;
|
||||
|
||||
const NAME: &str = "typedef-structs-unions";
|
||||
|
||||
impl Rule for TypedefStructsUnions {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"give a struct or union type a name with `typedef`"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"An anonymous `struct packed { … } s;` cannot be passed to a function, \
|
||||
returned from one, carried on a port or written in a cast, and a \
|
||||
second variable declared with the same member list is a *different* \
|
||||
type to the compiler — so the layout ends up copied, and the copies \
|
||||
drift. Verible's `typedef-structs-unions` (enabled by default) asks \
|
||||
for the `typedef`, and lucisv checks the same shape on every \
|
||||
declaration: a variable, a port, a member.\n\n\
|
||||
The `allow_anonymous_nested` option exempts an anonymous aggregate \
|
||||
written **inside** another aggregate's body, where it has a name — its \
|
||||
member's — and cannot be referred to from outside anyway. Verible \
|
||||
defaults its equivalent (`allow_anonymous_nested_type`) to false; \
|
||||
lucisv defaults it to **true**, a deliberate divergence: on opentitan \
|
||||
every one of the rule's 3 159 findings was a nested struct inside a \
|
||||
`typedef` in a generated register package, and opentitan's own \
|
||||
Verible config disables the whole rule for that reason. Set the \
|
||||
option to false for Verible's stricter reading. There is no fix: \
|
||||
where the `typedef` belongs is a design decision."
|
||||
}
|
||||
|
||||
fn options(&self) -> &'static [OptionSpec] {
|
||||
&[OptionSpec {
|
||||
name: "allow_anonymous_nested",
|
||||
kind: OptionKind::Bool,
|
||||
default: OptionDefault::Bool(true),
|
||||
doc: "accept an anonymous struct or union written inside another one (lucisv's default; Verible's is false)",
|
||||
}]
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let allow_nested = ctx.option_bool(NAME, "allow_anonymous_nested");
|
||||
let mut out = Vec::new();
|
||||
walk_declared_types(ctx.file(), &mut |declared| {
|
||||
let Some(TypeExtra::Struct(structure)) = declared.ty.inline() else { return };
|
||||
if declared.nested && allow_nested {
|
||||
return;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!(
|
||||
"`{}` is declared with an anonymous {}; name it with `typedef`",
|
||||
declared.name, structure.kw
|
||||
),
|
||||
declared.span,
|
||||
));
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::options::RuleOptions;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
TypedefStructsUnions.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_an_anonymous_struct_and_points_at_the_name() {
|
||||
let src = "module m;\n struct packed { logic a; } s;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("anonymous struct"), "{}", found[0].message);
|
||||
assert_eq!(&src[found[0].span.as_range()], "s");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_union_is_named_in_the_message() {
|
||||
let src = "module m;\n union packed { logic a; logic b; } u;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1);
|
||||
assert!(found[0].message.contains("anonymous union"), "{}", found[0].message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typedef_struct_is_the_shape_it_asks_for() {
|
||||
let src = "package p;\n typedef struct packed { logic a; } word_t;\nendpackage\n\
|
||||
module m;\n word_t w;\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nested_anonymous_struct_is_allowed_by_default_and_reported_when_asked() {
|
||||
// lucisv's default is `allow_anonymous_nested = true` (the doc says
|
||||
// why); Verible's stricter reading is one option away.
|
||||
let src = "package p;\n typedef struct packed {\n\
|
||||
\x20 struct packed { logic x; } inner;\n } outer_t;\nendpackage\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw(NAME, "allow_anonymous_nested", "false").expect("accepted");
|
||||
let ctx = LintContext::new(src, None).with_options(&options);
|
||||
let found = TypedefStructsUnions.check(&ctx);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "inner");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allowing_nested_ones_does_not_allow_a_top_level_one() {
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw(NAME, "allow_anonymous_nested", "true").expect("accepted");
|
||||
let src = "module m;\n struct packed { logic a; } s;\nendmodule\n";
|
||||
let ctx = LintContext::new(src, None).with_options(&options);
|
||||
assert_eq!(TypedefStructsUnions.check(&ctx).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_anonymous_enum_is_the_other_rules_business() {
|
||||
let src = "module m;\n enum logic { A, B } e;\nendmodule\n";
|
||||
assert!(violations(src).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_instantiations;
|
||||
use vlog_parser::ast::ListElem;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct UnknownParameter;
|
||||
@@ -62,7 +63,7 @@ impl Rule for UnknownParameter {
|
||||
}
|
||||
let Some(params) = &inst.params else { return };
|
||||
let Some(interface) = ctx.module_interface(&inst.module) else { return };
|
||||
for param in params {
|
||||
for param in params.iter().filter_map(ListElem::ok) {
|
||||
if param.name == "*" || param.name_span.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_instantiations;
|
||||
use vlog_parser::ast::Connections;
|
||||
use vlog_parser::ast::ListElem;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct UnknownPort;
|
||||
@@ -65,7 +66,7 @@ impl Rule for UnknownPort {
|
||||
let Some(interface) = ctx.module_interface(&inst.module) else { return };
|
||||
for instance in &inst.instances {
|
||||
let Connections::Named(conns) = &instance.conns else { continue };
|
||||
for conn in conns {
|
||||
for conn in conns.iter().filter_map(ListElem::ok) {
|
||||
if conn.name == "*" || conn.name_span.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ use std::collections::{HashMap, HashSet};
|
||||
|
||||
use vlog_parser::ast::{
|
||||
ClockingItemKind, Connections, Expr, ExprKind, ForStep, GenElse, Instantiation, Item, ItemKind,
|
||||
SourceFile, Stmt, StmtKind,
|
||||
ListElem, SourceFile, Stmt, StmtKind,
|
||||
};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::TokenKind;
|
||||
@@ -483,11 +483,25 @@ impl Scanner {
|
||||
match &instance.conns {
|
||||
Connections::Ordered(conns) => {
|
||||
for conn in conns {
|
||||
self.unknown.push(conn.span);
|
||||
// An error element is text a tolerant parse could not
|
||||
// read; whatever signals it mentions are unknown, so
|
||||
// its span joins the same opaque bucket.
|
||||
match conn {
|
||||
ListElem::Ok(conn) => self.unknown.push(conn.span),
|
||||
ListElem::Error(raw) => self.unknown.push(raw.span),
|
||||
}
|
||||
}
|
||||
}
|
||||
Connections::Named(conns) => {
|
||||
for conn in conns {
|
||||
let conn = match conn {
|
||||
ListElem::Ok(conn) => conn,
|
||||
// Opaque, as above.
|
||||
ListElem::Error(raw) => {
|
||||
self.unknown.push(raw.span);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match (conn.name.as_str(), &conn.expr) {
|
||||
// `.*` connects every same-named signal without
|
||||
// writing any of their names down.
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
//! text and no children, so they are visited and matched by nothing.
|
||||
|
||||
use vlog_parser::ast::{
|
||||
Fragment, GenBlock, GenElse, Instantiation, Item, ItemKind, ParamPort, SourceFile, Stmt,
|
||||
StmtKind,
|
||||
Fragment, GenBlock, GenElse, Instantiation, Item, ItemKind, ListElem, ParamPort, SourceFile,
|
||||
Stmt, StmtKind,
|
||||
};
|
||||
|
||||
/// Calls `f` on every item in the file, nested items included.
|
||||
@@ -142,6 +142,37 @@ fn stmts(list: &[Stmt], f: &mut dyn FnMut(&Stmt)) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls `f` on every generate block of the file — the `begin … end` (or the
|
||||
/// single item standing for one) of an `if`, `for` or `case` generate,
|
||||
/// nested blocks included.
|
||||
pub(crate) fn walk_generate_blocks(file: &SourceFile, f: &mut dyn FnMut(&GenBlock)) {
|
||||
walk_items(file, &mut |item| match &item.kind {
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
f(&gen_if.then);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
while let Some(branch) = els {
|
||||
match branch {
|
||||
GenElse::If(_, nested) => {
|
||||
f(&nested.then);
|
||||
els = nested.els.as_deref();
|
||||
}
|
||||
GenElse::Block(block) => {
|
||||
f(block);
|
||||
els = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::GenFor(gen_for) => f(&gen_for.body),
|
||||
ItemKind::GenCase(gen_case) => {
|
||||
for case_item in &gen_case.items {
|
||||
f(&case_item.body);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
|
||||
/// Calls `f` on every `#( ... )` parameter port of the file — a module header's
|
||||
/// and a class header's alike, since both spell them with the same node.
|
||||
pub(crate) fn walk_param_ports(file: &SourceFile, f: &mut dyn FnMut(&ParamPort)) {
|
||||
@@ -151,7 +182,9 @@ pub(crate) fn walk_param_ports(file: &SourceFile, f: &mut dyn FnMut(&ParamPort))
|
||||
ItemKind::Class(class) => &class.param_ports,
|
||||
_ => return,
|
||||
};
|
||||
for port in ports.iter().flatten() {
|
||||
// An error element is a parameter a tolerant parse could not read: it
|
||||
// has no name and no type, so there is nothing for a rule to judge.
|
||||
for port in ports.iter().flatten().filter_map(ListElem::ok) {
|
||||
f(port);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -81,10 +81,11 @@ fn severity_entry(severity: Severity, order: u32) -> String {
|
||||
/// One rule's toggle.
|
||||
fn rule_entry(rule: &'static dyn Rule, order: u32) -> String {
|
||||
let description = format!(
|
||||
"**{severity}** — {summary}. {default}",
|
||||
"**{severity}** — {summary}. {default}{options}",
|
||||
severity = rule.severity().as_str(),
|
||||
summary = rule.summary(),
|
||||
default = default_sentence(rule),
|
||||
options = options_sentence(rule),
|
||||
);
|
||||
format!(
|
||||
" \"{id}\": {{\n\
|
||||
@@ -106,6 +107,20 @@ fn rule_entry(rule: &'static dyn Rule, order: u32) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// The options a rule takes, named in its description.
|
||||
///
|
||||
/// No setting is generated *per option* — `lucisv.lint.options` is one object
|
||||
/// that carries them all, and 60 more entries in the Settings UI would bury
|
||||
/// the toggles this file exists to produce. What the description owes the
|
||||
/// reader is the words to type into that object, which is this.
|
||||
fn options_sentence(rule: &dyn Rule) -> String {
|
||||
let names: Vec<String> = rule.options().iter().map(|spec| format!("`{}`", spec.name)).collect();
|
||||
match names.len() {
|
||||
0 => String::new(),
|
||||
_ => format!(" Options (set them in `#lucisv.lint.options#`): {}.", names.join(", ")),
|
||||
}
|
||||
}
|
||||
|
||||
/// How a rule's own default is said in one sentence — the same three cases
|
||||
/// [`crate::rules_markdown`]'s Default column spells.
|
||||
fn default_sentence(rule: &dyn Rule) -> String {
|
||||
@@ -180,6 +195,33 @@ mod tests {
|
||||
assert_eq!(found, expected);
|
||||
}
|
||||
|
||||
/// A rule with options says so, and names them; a rule without says
|
||||
/// nothing extra.
|
||||
#[test]
|
||||
fn a_rules_description_names_the_options_it_takes() {
|
||||
let json = vscode_lint_settings();
|
||||
assert!(
|
||||
json.contains("Options (set them in `#lucisv.lint.options#`): `length`."),
|
||||
"line-length's option"
|
||||
);
|
||||
assert!(
|
||||
json.contains(
|
||||
"`localparam_style`, `localparam_style_regex`, `parameter_style`, \
|
||||
`parameter_style_regex`."
|
||||
),
|
||||
"parameter-name-style's four"
|
||||
);
|
||||
for rule in all_rules() {
|
||||
let has = !rule.options().is_empty();
|
||||
let entry = json
|
||||
.split(&format!("\"{}\"", rule_setting(rule)))
|
||||
.nth(1)
|
||||
.and_then(|rest| rest.split("},").next())
|
||||
.unwrap_or_default();
|
||||
assert_eq!(entry.contains("Options (set them in"), has, "{}", rule.name());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_strings_are_escaped() {
|
||||
assert_eq!(json_string("a\"b\\c"), "\"a\\\"b\\\\c\"");
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
#select always-comb
|
||||
# both spellings of the implicit sensitivity list
|
||||
module m;
|
||||
always @(*) x = 1;
|
||||
//^ 3 always-comb
|
||||
always @* y = 2;
|
||||
//^ 3 always-comb
|
||||
always @(a or b) z = 3;
|
||||
always_comb w = 4;
|
||||
endmodule
|
||||
@@ -25,7 +25,7 @@ package p;
|
||||
endpackage
|
||||
====
|
||||
# every non-procedural scope is reached: interface
|
||||
interface ifc;
|
||||
interface ifc_if;
|
||||
logic a;
|
||||
;
|
||||
//^ 3 empty-item
|
||||
@@ -48,7 +48,7 @@ endmodule
|
||||
====
|
||||
# every non-procedural scope is reached: inside a generate-for body
|
||||
module m;
|
||||
for (genvar i = 0; i < 2; i++) begin : g
|
||||
for (genvar i = 0; i < 2; i++) begin : g_loop
|
||||
;
|
||||
//^ 5 empty-item
|
||||
end
|
||||
@@ -56,7 +56,7 @@ endmodule
|
||||
====
|
||||
# `end;` after a generate block, and a run of null items after it
|
||||
module m;
|
||||
if (N > 1) begin : g1
|
||||
if (N > 1) begin : g_one
|
||||
wire x;
|
||||
end;
|
||||
//^ 6 empty-item
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
#select explicit-begin
|
||||
# an unblocked body is wrapped, and an `else if` chain is not touched
|
||||
module m;
|
||||
initial begin
|
||||
if (a) x = 1;
|
||||
//^ 12 explicit-begin
|
||||
else if (b) begin
|
||||
x = 2;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
if (a) begin x = 1; end
|
||||
//^ 12 explicit-begin
|
||||
else if (b) begin
|
||||
x = 2;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
#select explicit-begin
|
||||
#options explicit-begin.if_enable = false
|
||||
# each construct has its own switch
|
||||
module m;
|
||||
initial begin
|
||||
if (a) x = 1;
|
||||
while (b) y = 2;
|
||||
//^ 15 explicit-begin
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
if (a) x = 1;
|
||||
while (b) begin y = 2; end
|
||||
//^ 15 explicit-begin
|
||||
end
|
||||
endmodule
|
||||
@@ -0,0 +1,42 @@
|
||||
#select package-filename
|
||||
#path rtl/other.sv
|
||||
# a package that does not match its file name
|
||||
package foo_pkg;
|
||||
//^ 9 package-filename
|
||||
endpackage
|
||||
====
|
||||
#select package-filename
|
||||
#path rtl/foo_pkg.sv
|
||||
# both conventional spellings are accepted
|
||||
package foo_pkg;
|
||||
endpackage
|
||||
====
|
||||
#select package-filename
|
||||
#path rtl/foo_pkg.sv
|
||||
# a package named without the suffix, in a `_pkg` file
|
||||
package foo;
|
||||
endpackage
|
||||
====
|
||||
#select package-filename
|
||||
#path rtl/foo-pkg.sv
|
||||
#options package-filename.allow-dash-for-underscore = true
|
||||
# a dash stands for an underscore when the project says so
|
||||
package foo_pkg;
|
||||
endpackage
|
||||
====
|
||||
#select one-module-per-file
|
||||
# every module after the first is reported
|
||||
module a;
|
||||
endmodule
|
||||
module b;
|
||||
//^ 8 one-module-per-file
|
||||
endmodule
|
||||
====
|
||||
#select one-module-per-file
|
||||
# a package and an interface beside one module are not modules
|
||||
package p;
|
||||
endpackage
|
||||
module a;
|
||||
endmodule
|
||||
interface i;
|
||||
endinterface
|
||||
@@ -0,0 +1,35 @@
|
||||
#select generate-label,generate-label-prefix
|
||||
# an unlabelled generate block, and a labelled one with no prefix
|
||||
module m;
|
||||
if (A) begin
|
||||
//^ 10 generate-label
|
||||
wire a;
|
||||
end
|
||||
for (genvar i = 0; i < 2; i++) begin : lanes
|
||||
//^ 42 generate-label-prefix
|
||||
wire b;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
#select generate-label,generate-label-prefix
|
||||
# the convention is clean
|
||||
module m;
|
||||
if (A) begin : g_a
|
||||
wire a;
|
||||
end else begin : gen_b
|
||||
wire b;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
#select generate-label-prefix
|
||||
#options generate-label-prefix.prefix = ["blk_"]
|
||||
# the option replaces the accepted prefixes
|
||||
module m;
|
||||
if (A) begin : blk_a
|
||||
wire a;
|
||||
end
|
||||
if (B) begin : g_b
|
||||
//^ 18 generate-label-prefix
|
||||
wire b;
|
||||
end
|
||||
endmodule
|
||||
@@ -0,0 +1,41 @@
|
||||
#select line-length
|
||||
# a line past the default width is reported at the first column over it
|
||||
module m;
|
||||
wire aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;
|
||||
//^ 101 line-length
|
||||
endmodule
|
||||
====
|
||||
#select line-length
|
||||
# a line at the limit is not over it
|
||||
module m;
|
||||
wire aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;
|
||||
endmodule
|
||||
====
|
||||
#select line-length
|
||||
#options line-length.length = 60
|
||||
# the option narrows the limit
|
||||
module m;
|
||||
wire aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;
|
||||
//^ 61 line-length
|
||||
endmodule
|
||||
====
|
||||
#select line-length
|
||||
#options line-length.length = 200
|
||||
# and widens it
|
||||
module m;
|
||||
wire aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;
|
||||
endmodule
|
||||
====
|
||||
#select line-length
|
||||
# a line that is one unbreakable token is left alone, `;` or not
|
||||
`include "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.svh"
|
||||
module m;
|
||||
`AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA;
|
||||
endmodule
|
||||
====
|
||||
#select line-length
|
||||
# a long comment can be wrapped, so it is reported
|
||||
module m;
|
||||
endmodule
|
||||
// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
|
||||
//^ 101 line-length
|
||||
@@ -0,0 +1,83 @@
|
||||
#select signal-name-style
|
||||
# ports and signals are judged where they are declared
|
||||
module m (input logic clkIn, output logic data_o);
|
||||
//^ 23 signal-name-style
|
||||
logic dataValid;
|
||||
//^ 9 signal-name-style
|
||||
logic wr_ptr2;
|
||||
endmodule
|
||||
====
|
||||
#select signal-name-style
|
||||
#options signal-name-style.style_regex = "[a-z][a-zA-Z0-9]*"
|
||||
# the option replaces the convention
|
||||
module m;
|
||||
logic dataValid;
|
||||
logic data_valid;
|
||||
//^ 9 signal-name-style
|
||||
endmodule
|
||||
====
|
||||
#select interface-name-style
|
||||
# an interface without the `_if` suffix
|
||||
interface bus;
|
||||
//^ 11 interface-name-style
|
||||
endinterface
|
||||
====
|
||||
#select interface-name-style
|
||||
# the convention, and a module the rule says nothing about
|
||||
interface bus_if;
|
||||
endinterface
|
||||
module bus;
|
||||
endmodule
|
||||
====
|
||||
#select macro-name-style
|
||||
# the defined name is judged, not the uses
|
||||
`define my_macro 1
|
||||
//^ 9 macro-name-style
|
||||
`define MY_OTHER(a) (a)
|
||||
module m;
|
||||
wire x = `my_macro;
|
||||
endmodule
|
||||
====
|
||||
#select constraint-name-style
|
||||
# a constraint that does not end in `_c`
|
||||
class c;
|
||||
rand int addr;
|
||||
constraint addr_range { addr > 0; }
|
||||
//^ 14 constraint-name-style
|
||||
constraint addr_max_c { addr < 9; }
|
||||
endclass
|
||||
====
|
||||
#select parameter-type-name-style
|
||||
# a type parameter named like a type, and one not
|
||||
class c #(type T = int, type item_t = int);
|
||||
//^ 16 parameter-type-name-style
|
||||
endclass
|
||||
====
|
||||
#select port-name-suffix
|
||||
# each direction has its own suffixes
|
||||
module m (input logic clk, input logic rst_ni, output logic data_o, inout wire sda);
|
||||
//^ 23 port-name-suffix
|
||||
//^ 80 port-name-suffix
|
||||
endmodule
|
||||
====
|
||||
#select port-name-suffix
|
||||
#options port-name-suffix.suffixes = ["_i", "_o"]
|
||||
# shortening the list bans the active-low spellings
|
||||
module m (input logic clk_i, input logic rst_ni, output logic data_o);
|
||||
//^ 42 port-name-suffix
|
||||
endmodule
|
||||
====
|
||||
#select banned-declared-name-patterns
|
||||
# nothing is banned until the project says so
|
||||
module m;
|
||||
logic tmp_addr;
|
||||
endmodule
|
||||
====
|
||||
#select banned-declared-name-patterns
|
||||
#options banned-declared-name-patterns.patterns = ["tmp.*"]
|
||||
# a banned name is reported where it is declared
|
||||
module m;
|
||||
logic tmp_addr;
|
||||
//^ 9 banned-declared-name-patterns
|
||||
logic keep_me;
|
||||
endmodule
|
||||
@@ -0,0 +1,29 @@
|
||||
#select forbid-consecutive-null-statements
|
||||
# a doubled `;` is reported and the extra one deleted
|
||||
module m;
|
||||
initial begin
|
||||
x = 1;;
|
||||
//^ 11 forbid-consecutive-null-statements
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
x = 1;
|
||||
//^ 11 forbid-consecutive-null-statements
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
#select forbid-consecutive-null-statements
|
||||
# an empty `for` header holds no statements
|
||||
module m;
|
||||
initial for (;;) x = 1;
|
||||
endmodule
|
||||
====
|
||||
#select forbid-consecutive-null-statements
|
||||
# a lone null statement is another rule's business
|
||||
module m;
|
||||
initial begin
|
||||
;
|
||||
end
|
||||
endmodule
|
||||
@@ -0,0 +1,13 @@
|
||||
#select posix-eof
|
||||
# a terminated file is clean
|
||||
#
|
||||
# The other half of this rule — a file whose last line has no newline — cannot
|
||||
# be written here: the harness rejoins every case body with a trailing newline,
|
||||
# so no case input can lack one. It is pinned in the rule's own unit tests
|
||||
# (`rules::posix_eof::tests`), fix included.
|
||||
module m;
|
||||
endmodule
|
||||
====
|
||||
#select posix-eof
|
||||
# a file that is only a comment is terminated too
|
||||
// nothing but a note
|
||||
@@ -0,0 +1,32 @@
|
||||
#select typedef-enums,typedef-structs-unions
|
||||
# anonymous aggregates in declarations
|
||||
module m;
|
||||
enum logic [1:0] { IDLE, BUSY } state;
|
||||
//^ 35 typedef-enums
|
||||
struct packed { logic a; } s;
|
||||
//^ 30 typedef-structs-unions
|
||||
endmodule
|
||||
====
|
||||
#select typedef-enums,typedef-structs-unions
|
||||
# a named type is the shape they ask for
|
||||
package p;
|
||||
typedef enum logic [1:0] { IDLE, BUSY } state_e;
|
||||
typedef struct packed { logic a; } word_t;
|
||||
endpackage
|
||||
module m;
|
||||
state_e state;
|
||||
word_t w;
|
||||
endmodule
|
||||
====
|
||||
#select typedef-structs-unions
|
||||
#options typedef-structs-unions.allow_anonymous_nested = true
|
||||
# a nested anonymous struct may be allowed; a top-level one is still not
|
||||
package p;
|
||||
typedef struct packed {
|
||||
struct packed { logic x; } inner;
|
||||
} outer_t;
|
||||
endpackage
|
||||
module m;
|
||||
union packed { logic a; logic b; } u;
|
||||
//^ 38 typedef-structs-unions
|
||||
endmodule
|
||||
@@ -29,13 +29,13 @@ endmodule
|
||||
====
|
||||
# a verible waiver for a rule lucisv does not have is ignored
|
||||
module m;
|
||||
// verilog_lint: waive macro-name-style
|
||||
// verilog_lint: waive explicit-function-lifetime
|
||||
wire a;
|
||||
endmodule
|
||||
====
|
||||
# lucisv's own spelling for an unknown rule is reported
|
||||
module m;
|
||||
// lucisv: waive macro-name-style
|
||||
// lucisv: waive explicit-function-lifetime
|
||||
//^ 3 unused-waiver
|
||||
wire a;
|
||||
endmodule
|
||||
|
||||
@@ -20,6 +20,10 @@
|
||||
//! - `#path <p>` — lint the source as if it were read from this file path.
|
||||
//! - `#select ...` — comma-separated rule names, `lucisv check --select`
|
||||
//! semantics (replaces the default rule set).
|
||||
//! - `#options <rule>.<key> = <value>` — set one per-rule option for this
|
||||
//! case, in the `lucisv.toml` spelling (`120`, `true`, `"[a-z]+"`,
|
||||
//! `["a", "b"]`). Repeatable. A refused entry fails the case, so the
|
||||
//! option's own validation is pinned here too.
|
||||
//! - `#workspace [name,...]` — run the case as part of a *project*: the rules
|
||||
//! that need a workspace default on, and a `MentionOracle` answers "yes,
|
||||
//! some other file mentions this" for each listed name (an empty list is a
|
||||
@@ -42,7 +46,7 @@ use std::path::PathBuf;
|
||||
use vlog_formatter::{format_source, Config};
|
||||
use vlog_linter::{
|
||||
apply_fixes, lint, rule_by_name, select_rules, Applicability, LintContext, MentionOracle,
|
||||
ParsedSource, Rule,
|
||||
ParsedSource, Rule, RuleOptions,
|
||||
};
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
@@ -54,6 +58,8 @@ struct Case {
|
||||
tolerant: bool,
|
||||
path: Option<String>,
|
||||
select: Vec<String>,
|
||||
/// `#options`: what this case configured about its rules.
|
||||
options: RuleOptions,
|
||||
/// `#workspace`: `None` is a run with no oracle; `Some(names)` is a run
|
||||
/// with one that says those names are mentioned in some other file.
|
||||
workspace: Option<Vec<String>>,
|
||||
@@ -111,6 +117,7 @@ fn split_case(file: &str, start: usize, block: &[&str]) -> Result<Case, String>
|
||||
let mut tolerant = false;
|
||||
let mut path = None;
|
||||
let mut select = Vec::new();
|
||||
let mut options = RuleOptions::new();
|
||||
let mut workspace = None;
|
||||
let mut body = block;
|
||||
while let Some(first) = body.first() {
|
||||
@@ -129,6 +136,9 @@ fn split_case(file: &str, start: usize, block: &[&str]) -> Result<Case, String>
|
||||
path = Some(p.trim().to_string());
|
||||
} else if let Some(s) = rest.strip_prefix("select ") {
|
||||
select = s.split(',').map(|r| r.trim().to_string()).collect();
|
||||
} else if let Some(entry) = rest.strip_prefix("options ") {
|
||||
set_option(&mut options, entry)
|
||||
.map_err(|e| format!("{file}:{start}: bad #options: {e}"))?;
|
||||
} else if rest == "workspace" {
|
||||
workspace = Some(Vec::new());
|
||||
} else if let Some(s) = rest.strip_prefix("workspace ") {
|
||||
@@ -146,7 +156,7 @@ fn split_case(file: &str, start: usize, block: &[&str]) -> Result<Case, String>
|
||||
} else if directive_like {
|
||||
return Err(format!(
|
||||
"{file}:{start}: unknown directive `#{}` \
|
||||
(known: #path, #select, #workspace, #tolerant, #SKIP; \
|
||||
(known: #path, #select, #options, #workspace, #tolerant, #SKIP; \
|
||||
a case name needs a space after `#`)",
|
||||
rest.split_whitespace().next().unwrap_or(rest)
|
||||
));
|
||||
@@ -169,7 +179,20 @@ fn split_case(file: &str, start: usize, block: &[&str]) -> Result<Case, String>
|
||||
if input.trim().is_empty() {
|
||||
return Err(format!("{file}:{start}: case has no source"));
|
||||
}
|
||||
Ok(Case { name, line: start, skip, tolerant, path, select, workspace, input, fixed })
|
||||
Ok(Case { name, line: start, skip, tolerant, path, select, options, workspace, input, fixed })
|
||||
}
|
||||
|
||||
/// One `#options <rule>.<key> = <value>` entry, through the linter's own
|
||||
/// validator — the same door a `lucisv.toml` comes in by.
|
||||
fn set_option(options: &mut RuleOptions, entry: &str) -> Result<(), String> {
|
||||
let (name, value) = entry
|
||||
.split_once('=')
|
||||
.ok_or_else(|| format!("expected `<rule>.<key> = <value>`, found `{entry}`"))?;
|
||||
let (rule, key) = name
|
||||
.trim()
|
||||
.split_once('.')
|
||||
.ok_or_else(|| format!("expected `<rule>.<key>`, found `{}`", name.trim()))?;
|
||||
options.set_raw(rule.trim(), key.trim(), value.trim())
|
||||
}
|
||||
|
||||
/// Attaches the case's oracle, if it declared one.
|
||||
@@ -238,14 +261,17 @@ fn check_case(file: &str, case: &Case) -> Result<(), String> {
|
||||
|
||||
let path = case.path.clone().map(PathBuf::from);
|
||||
let oracle = case.workspace.clone().map(Elsewhere);
|
||||
let own = LintContext::new(&case.input, path.clone());
|
||||
let own = LintContext::new(&case.input, path.clone()).with_options(&case.options);
|
||||
let violations = lint(&with_oracle(own, oracle.as_ref()), &rules);
|
||||
|
||||
// "One parse, two tools", held over every case: a context built from
|
||||
// pre-parsed products must find exactly what one built from the source
|
||||
// does — rule, message, span and fix alike (the Debug form carries all).
|
||||
let parsed = ParsedSource::parse(&case.input);
|
||||
let via_products = lint(&with_oracle(parsed.context(path.clone()), oracle.as_ref()), &rules);
|
||||
let via_products = lint(
|
||||
&with_oracle(parsed.context(path.clone()).with_options(&case.options), oracle.as_ref()),
|
||||
&rules,
|
||||
);
|
||||
if format!("{violations:?}") != format!("{via_products:?}") {
|
||||
return Err(format!(
|
||||
"{at}: linting from pre-parsed products found something different from \
|
||||
@@ -334,12 +360,16 @@ fn check_fix(
|
||||
oracle: Option<&Elsewhere>,
|
||||
expected_fixed: &str,
|
||||
) -> Result<(), String> {
|
||||
let options = &case.options;
|
||||
let mut fixed = case.input.clone();
|
||||
for round in 0.. {
|
||||
if round >= 10 {
|
||||
return Err(format!("{at}: fixing did not settle within 10 rounds"));
|
||||
}
|
||||
let found = lint(&with_oracle(LintContext::new(&fixed, path.clone()), oracle), rules);
|
||||
let found = lint(
|
||||
&with_oracle(LintContext::new(&fixed, path.clone()).with_options(options), oracle),
|
||||
rules,
|
||||
);
|
||||
let out = apply_fixes(&fixed, &found, false);
|
||||
if out.applied == 0 {
|
||||
break;
|
||||
@@ -357,15 +387,17 @@ fn check_fix(
|
||||
// offer a Safe fix — a violation without a fix (or with an Unsafe one)
|
||||
// may legitimately survive.
|
||||
let index = LineIndex::new(&fixed);
|
||||
let still_fixable: Vec<String> =
|
||||
lint(&with_oracle(LintContext::new(&fixed, path.clone()), oracle), rules)
|
||||
.iter()
|
||||
.filter(|v| v.fix.as_ref().is_some_and(|f| f.applicability == Applicability::Safe))
|
||||
.map(|v| {
|
||||
let (line, col) = index.line_col(v.span.start);
|
||||
format!(" {line}:{col} {} — {}", v.rule, v.message)
|
||||
})
|
||||
.collect();
|
||||
let still_fixable: Vec<String> = lint(
|
||||
&with_oracle(LintContext::new(&fixed, path.clone()).with_options(options), oracle),
|
||||
rules,
|
||||
)
|
||||
.iter()
|
||||
.filter(|v| v.fix.as_ref().is_some_and(|f| f.applicability == Applicability::Safe))
|
||||
.map(|v| {
|
||||
let (line, col) = index.line_col(v.span.start);
|
||||
format!(" {line}:{col} {} — {}", v.rule, v.message)
|
||||
})
|
||||
.collect();
|
||||
if !still_fixable.is_empty() {
|
||||
return Err(format!(
|
||||
"{at}: the fixed output still has Safe-fixable findings:\n{}",
|
||||
|
||||
@@ -28,7 +28,7 @@ pub struct ClassDecl {
|
||||
pub param_after_hash: Vec<Comment>,
|
||||
/// `None` when the header wrote no `#( ... )`; an empty `Some` is a
|
||||
/// written-but-empty `#()`.
|
||||
pub param_ports: Option<Vec<ParamPort>>,
|
||||
pub param_ports: Option<Vec<ListElem<ParamPort>>>,
|
||||
/// Directives written between the parameter ports, in source order.
|
||||
pub param_directives: Vec<ListDirective>,
|
||||
/// Comments written after the last parameter port and before its `)`.
|
||||
@@ -75,7 +75,7 @@ pub struct ClassExtends {
|
||||
/// Comments written between the base-class name and the `#`.
|
||||
pub param_comments: Vec<Comment>,
|
||||
/// `None` when no `#( ... )` was written.
|
||||
pub params: Option<Vec<Connection>>,
|
||||
pub params: Option<Vec<ListElem<Connection>>>,
|
||||
/// Directives written between the overrides, in source order.
|
||||
pub param_directives: Vec<ListDirective>,
|
||||
/// Code extent of the clause, from `extends` through its last token.
|
||||
|
||||
@@ -19,7 +19,7 @@ pub struct CovergroupDecl {
|
||||
/// The `(bit [3:0] a)` formal argument list. `None` when the source wrote
|
||||
/// no parens at all — printing an empty `()` back would be a token-stream
|
||||
/// change the safety net refuses.
|
||||
pub args: Option<Vec<TfArg>>,
|
||||
pub args: Option<Vec<ListElem<TfArg>>>,
|
||||
/// The `coverage_event` of the header. IEEE 1800 §19.3 makes the two
|
||||
/// spellings alternatives, so one field holds whichever was written.
|
||||
pub event: Option<CoverageEvent>,
|
||||
@@ -73,7 +73,7 @@ pub struct SampleFn {
|
||||
pub before_args: Vec<Comment>,
|
||||
/// True when the source wrote `( ... )` at all.
|
||||
pub has_parens: bool,
|
||||
pub args: Vec<TfArg>,
|
||||
pub args: Vec<ListElem<TfArg>>,
|
||||
}
|
||||
|
||||
/// One `coverage_spec_or_option` of a covergroup body.
|
||||
|
||||
@@ -306,7 +306,7 @@ pub struct FunctionDecl {
|
||||
pub has_parens: bool,
|
||||
/// Comments written between the name and the `(` of the port list.
|
||||
pub before_args: Vec<Comment>,
|
||||
pub args: Vec<TfArg>,
|
||||
pub args: Vec<ListElem<TfArg>>,
|
||||
/// Comments written inside an argument list with no argument to carry
|
||||
/// them (`function void f( /*c*/ );`).
|
||||
pub args_dangling: Vec<Comment>,
|
||||
@@ -349,7 +349,7 @@ pub struct TaskDecl {
|
||||
pub has_parens: bool,
|
||||
/// Comments written between the name and the `(` of the port list.
|
||||
pub before_args: Vec<Comment>,
|
||||
pub args: Vec<TfArg>,
|
||||
pub args: Vec<ListElem<TfArg>>,
|
||||
/// Comments written inside an empty argument list; see
|
||||
/// [`FunctionDecl::args_dangling`].
|
||||
pub args_dangling: Vec<Comment>,
|
||||
@@ -381,7 +381,7 @@ pub struct LetDecl {
|
||||
/// False for the port-less spelling `let x = expr;` — an empty `()` was
|
||||
/// written when this is true and [`LetDecl::ports`] is empty.
|
||||
pub has_parens: bool,
|
||||
pub ports: Vec<TfArg>,
|
||||
pub ports: Vec<ListElem<TfArg>>,
|
||||
pub value: Expr,
|
||||
}
|
||||
|
||||
@@ -423,7 +423,7 @@ pub struct TfArg {
|
||||
/// a pair of parentheses that hold no argument to carry them (`f( /*c*/ )`).
|
||||
#[derive(Debug, Default)]
|
||||
pub struct TfPorts {
|
||||
pub args: Vec<TfArg>,
|
||||
pub args: Vec<ListElem<TfArg>>,
|
||||
pub dangling: Vec<Comment>,
|
||||
}
|
||||
|
||||
@@ -477,7 +477,7 @@ pub struct TfPrototype {
|
||||
pub has_parens: bool,
|
||||
/// Comments written between the name and the `(` of the port list.
|
||||
pub before_args: Vec<Comment>,
|
||||
pub args: Vec<TfArg>,
|
||||
pub args: Vec<ListElem<TfArg>>,
|
||||
/// Comments written inside an argument list with no argument to carry
|
||||
/// them (`task drive( /*c*/ )`).
|
||||
pub args_dangling: Vec<Comment>,
|
||||
|
||||
@@ -15,6 +15,14 @@ pub struct Expr {
|
||||
pub span: TextRange,
|
||||
}
|
||||
|
||||
impl Expr {
|
||||
/// True for the leaf a tolerant parse leaves where a statement header's
|
||||
/// condition did not parse; see [`ExprKind::Error`].
|
||||
pub fn is_error(&self) -> bool {
|
||||
matches!(self.kind, ExprKind::Error(_))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ExprKind {
|
||||
Ident(String),
|
||||
@@ -235,6 +243,15 @@ pub enum ExprKind {
|
||||
/// the whole *item* became [`ItemKind::Verbatim`]. The region itself
|
||||
/// records nothing and is re-emitted exactly as written.
|
||||
Verbatim(RawText),
|
||||
/// Text a **tolerant** parse could not read as an expression, kept
|
||||
/// verbatim: the `i <` of a half-typed `for (int i = 0; i <` header.
|
||||
///
|
||||
/// Built only inside a statement header's brackets, and only by
|
||||
/// [`crate::parse_tolerant`] — the strict parser fails on the typo
|
||||
/// instead, exactly as it does for [`ItemKind::Error`] — so the statement
|
||||
/// keeps its shape and its body while the broken condition is one leaf.
|
||||
/// See `docs/features/header-recovery/README.md`.
|
||||
Error(RawText),
|
||||
/// A type used in expression position (`parameter type T = logic [7:0]`).
|
||||
Type(DataType),
|
||||
/// `(min : typ : max)` delay expression.
|
||||
|
||||
@@ -169,6 +169,60 @@ pub struct RawText {
|
||||
pub span: TextRange,
|
||||
}
|
||||
|
||||
/// One element of a header list: the element as written, or — in a tolerant
|
||||
/// parse only — the text of one that did not parse.
|
||||
///
|
||||
/// The five header lists (a module's ports and parameter ports, a
|
||||
/// subroutine's formals, an instance's named and ordered connections) share
|
||||
/// this one wrapper rather than each growing a two-variant enum of its own:
|
||||
/// the shape is the same in all of them, and one type means one place says
|
||||
/// what an error element is. [`crate::parse`] never builds an
|
||||
/// [`ListElem::Error`] — the strict parser fails on the typo instead — so a
|
||||
/// consumer of a strictly parsed tree sees only [`ListElem::Ok`]. A consumer
|
||||
/// of [`crate::parse_tolerant`]'s tree must decide what to do with the other
|
||||
/// variant, which is the point of making it a variant; see
|
||||
/// `docs/features/header-recovery/README.md`.
|
||||
#[derive(Debug)]
|
||||
pub enum ListElem<T> {
|
||||
/// An element that parsed.
|
||||
Ok(T),
|
||||
/// Text a tolerant parse could not read as an element, kept verbatim.
|
||||
Error(RawText),
|
||||
}
|
||||
|
||||
impl<T> ListElem<T> {
|
||||
/// The element, or `None` for an error element — the filter a consumer
|
||||
/// that only wants the well-formed elements reads the list through.
|
||||
pub fn ok(&self) -> Option<&T> {
|
||||
match self {
|
||||
ListElem::Ok(v) => Some(v),
|
||||
ListElem::Error(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The element as a mutable reference, or `None` for an error element:
|
||||
/// what the parser's list loops hang a separator's comments on.
|
||||
pub fn ok_mut(&mut self) -> Option<&mut T> {
|
||||
match self {
|
||||
ListElem::Ok(v) => Some(v),
|
||||
ListElem::Error(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The skipped text of an error element, or `None` for one that parsed.
|
||||
pub fn error(&self) -> Option<&RawText> {
|
||||
match self {
|
||||
ListElem::Ok(_) => None,
|
||||
ListElem::Error(raw) => Some(raw),
|
||||
}
|
||||
}
|
||||
|
||||
/// True for an element a tolerant parse recovered from.
|
||||
pub fn is_error(&self) -> bool {
|
||||
matches!(self, ListElem::Error(_))
|
||||
}
|
||||
}
|
||||
|
||||
/// A compiler directive written *between* the elements of a port,
|
||||
/// parameter-port, enum-member, parameter-override or instance-connection
|
||||
/// list (`` `ifdef``/`` `else``/`` `elsif``/`` `endif``, `` `define``,
|
||||
|
||||
@@ -31,7 +31,7 @@ pub struct Module {
|
||||
pub param_after_hash: Vec<Comment>,
|
||||
/// `None` when the header wrote no `#( ... )` at all; an empty `Some` is a
|
||||
/// written-but-empty `#()`, which must be printed back.
|
||||
pub param_ports: Option<Vec<ParamPort>>,
|
||||
pub param_ports: Option<Vec<ListElem<ParamPort>>>,
|
||||
/// Directives written between the parameter ports, in source order.
|
||||
pub param_directives: Vec<ListDirective>,
|
||||
/// Comments written after the last parameter port and before the `)`.
|
||||
@@ -86,9 +86,9 @@ pub enum PortList {
|
||||
/// Empty parens: `module m();`
|
||||
Empty,
|
||||
/// ANSI-style declarations in the header.
|
||||
Ansi(Vec<AnsiPort>),
|
||||
Ansi(Vec<ListElem<AnsiPort>>),
|
||||
/// Non-ANSI: just names in the header, declared in the body.
|
||||
NonAnsi(Vec<NonAnsiPort>),
|
||||
NonAnsi(Vec<ListElem<NonAnsiPort>>),
|
||||
}
|
||||
|
||||
/// A name-only port in a non-ANSI header (`module m (a, b);`). It has no
|
||||
@@ -208,7 +208,7 @@ pub struct Instantiation {
|
||||
/// The parameter override list, `None` when the source wrote no `#(...)`
|
||||
/// at all. An empty `Some` is a written-but-empty `#()`, which must be
|
||||
/// printed back: dropping it would lose two tokens.
|
||||
pub params: Option<Vec<Connection>>,
|
||||
pub params: Option<Vec<ListElem<Connection>>>,
|
||||
/// Directives written between the parameter overrides, in source order.
|
||||
/// They live here rather than inside `params` because a `#( ... )` whose
|
||||
/// whole body is one `` `include`` has no override to hang them on.
|
||||
@@ -240,8 +240,8 @@ pub struct Instance {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Connections {
|
||||
Ordered(Vec<OrderedConn>),
|
||||
Named(Vec<Connection>),
|
||||
Ordered(Vec<ListElem<OrderedConn>>),
|
||||
Named(Vec<ListElem<Connection>>),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
||||
@@ -97,34 +97,37 @@ impl<'a> Parser<'a> {
|
||||
self.bump();
|
||||
after_hash = self.take_gap();
|
||||
self.expect_sym("(")?;
|
||||
let mark = self.diags_mark();
|
||||
let mut list = Vec::new();
|
||||
self.take_list_directives(&mut param_directives, 0);
|
||||
if !self.cur().is_sym(")") {
|
||||
loop {
|
||||
list.push(self.parse_connection()?);
|
||||
if let Some(last) = list.last_mut() {
|
||||
let at = self.pos;
|
||||
list.push(self.element_or_recover(|p| p.parse_connection())?);
|
||||
let recovered = list.last().is_some_and(ListElem::is_error);
|
||||
if let Some(ListElem::Ok(last)) = list.last_mut() {
|
||||
self.take_before_sep(&mut last.meta, ",");
|
||||
}
|
||||
let comma = self.eat_sym(",");
|
||||
if let Some(last) = list.last_mut() {
|
||||
if let Some(ListElem::Ok(last)) = list.last_mut() {
|
||||
last.comma = comma;
|
||||
if comma && last.meta.trailing.is_none() {
|
||||
last.meta.trailing = self.take_trailing();
|
||||
}
|
||||
}
|
||||
let dirs = self.take_list_directives(&mut param_directives, list.len());
|
||||
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
|
||||
if self.list_ends(at, comma, dirs.any, recovered) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let n = list.len();
|
||||
self.take_last_entry_before_close(
|
||||
list.last_mut().map(|c| &mut c.meta),
|
||||
list.last_mut().and_then(|c| c.ok_mut()).map(|c| &mut c.meta),
|
||||
&mut param_directives,
|
||||
n,
|
||||
);
|
||||
self.expect_sym(")")?;
|
||||
self.close_list(mark)?;
|
||||
params = Some(list);
|
||||
}
|
||||
Ok(ClassExtends {
|
||||
|
||||
@@ -256,6 +256,7 @@ impl<'a> Parser<'a> {
|
||||
Self::push_scope_segment(&mut module, &segment);
|
||||
}
|
||||
let module_span = self.span_from(module_start);
|
||||
let mark = self.diags_mark();
|
||||
let param_comments = self.take_before_open("#");
|
||||
let mut params = None;
|
||||
let mut after_hash = Vec::new();
|
||||
@@ -268,12 +269,14 @@ impl<'a> Parser<'a> {
|
||||
self.take_list_directives(&mut param_directives, 0);
|
||||
if !self.cur().is_sym(")") {
|
||||
loop {
|
||||
list.push(self.parse_connection()?);
|
||||
if let Some(last) = list.last_mut() {
|
||||
let at = self.pos;
|
||||
list.push(self.element_or_recover(|p| p.parse_connection())?);
|
||||
let recovered = list.last().is_some_and(ListElem::is_error);
|
||||
if let Some(ListElem::Ok(last)) = list.last_mut() {
|
||||
self.take_before_sep(&mut last.meta, ",");
|
||||
}
|
||||
let comma = self.eat_sym(",");
|
||||
if let Some(last) = list.last_mut() {
|
||||
if let Some(ListElem::Ok(last)) = list.last_mut() {
|
||||
last.comma = comma;
|
||||
if comma && last.meta.trailing.is_none() {
|
||||
last.meta.trailing = self.take_trailing();
|
||||
@@ -285,7 +288,7 @@ impl<'a> Parser<'a> {
|
||||
// the list, and after a directive only the closing bracket
|
||||
// does — an `` `ifdef`` arm may end without a comma and
|
||||
// still be followed by an `` `else`` arm.
|
||||
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
|
||||
if self.list_ends(at, comma, dirs.any, recovered) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -293,11 +296,11 @@ impl<'a> Parser<'a> {
|
||||
// Comments before the `)` of the override list belong inside it.
|
||||
let n = list.len();
|
||||
self.take_last_entry_before_close(
|
||||
list.last_mut().map(|c| &mut c.meta),
|
||||
list.last_mut().and_then(|c| c.ok_mut()).map(|c| &mut c.meta),
|
||||
&mut param_directives,
|
||||
n,
|
||||
);
|
||||
self.expect_sym(")")?;
|
||||
self.close_list(mark)?;
|
||||
params = Some(list);
|
||||
}
|
||||
let mut instances = Vec::new();
|
||||
@@ -308,9 +311,10 @@ impl<'a> Parser<'a> {
|
||||
let dims = self.parse_dims()?;
|
||||
let conn_comments = self.take_before_open("(");
|
||||
self.expect_sym("(")?;
|
||||
let conn_mark = self.diags_mark();
|
||||
let mut conn_directives = Vec::new();
|
||||
let conns = self.parse_connections(&mut conn_directives)?;
|
||||
self.expect_sym(")")?;
|
||||
self.close_list(conn_mark)?;
|
||||
let span = self.span_from(start);
|
||||
self.take_before_sep(&mut meta, ",");
|
||||
let more = self.eat_sym(",");
|
||||
@@ -332,7 +336,12 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
let before_semi = self.gap_before(";");
|
||||
self.expect_sym(";")?;
|
||||
// As in a module header (`Parser::parse_module`): once something in
|
||||
// this instantiation has been reported, a missing `;` is part of the
|
||||
// same typo, and the item is worth more than a second message. It is
|
||||
// what leaves the `wire w;` under a half-typed `sub u (.a(` an item of
|
||||
// the module.
|
||||
self.expect_after_recovery(";", self.recovered_since(mark))?;
|
||||
Ok(Instantiation {
|
||||
module,
|
||||
module_span,
|
||||
@@ -377,58 +386,77 @@ impl<'a> Parser<'a> {
|
||||
if self.at_named_connection() {
|
||||
let mut conns = Vec::new();
|
||||
loop {
|
||||
conns.push(self.parse_connection()?);
|
||||
if let Some(last) = conns.last_mut() {
|
||||
let at = self.pos;
|
||||
conns.push(self.element_or_recover(|p| p.parse_connection())?);
|
||||
let recovered = conns.last().is_some_and(ListElem::is_error);
|
||||
if let Some(ListElem::Ok(last)) = conns.last_mut() {
|
||||
self.take_before_sep(&mut last.meta, ",");
|
||||
}
|
||||
let comma = self.eat_sym(",");
|
||||
if let Some(last) = conns.last_mut() {
|
||||
if let Some(ListElem::Ok(last)) = conns.last_mut() {
|
||||
last.comma = comma;
|
||||
if comma && last.meta.trailing.is_none() {
|
||||
last.meta.trailing = self.take_trailing();
|
||||
}
|
||||
}
|
||||
let dirs = self.take_list_directives(directives, conns.len());
|
||||
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
|
||||
if self.list_ends(at, comma, dirs.any, recovered) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Comments before the closing `)` belong to the last entry: after
|
||||
// it they would sit outside the connection list entirely.
|
||||
let n = conns.len();
|
||||
self.take_last_entry_before_close(conns.last_mut().map(|c| &mut c.meta), directives, n);
|
||||
let last = conns.last_mut().and_then(|c| c.ok_mut()).map(|c| &mut c.meta);
|
||||
self.take_last_entry_before_close(last, directives, n);
|
||||
Ok(Connections::Named(conns))
|
||||
} else {
|
||||
let mut conns = Vec::new();
|
||||
loop {
|
||||
let start = self.here();
|
||||
let meta = self.take_meta();
|
||||
let expr = if self.cur().is_sym(",") || self.cur().is_sym(")") {
|
||||
None
|
||||
} else {
|
||||
Some(self.parse_expr()?)
|
||||
let at = self.pos;
|
||||
conns.push(self.element_or_recover(|p| p.parse_ordered_connection())?);
|
||||
let recovered = conns.last().is_some_and(ListElem::is_error);
|
||||
let comma = match conns.last() {
|
||||
Some(ListElem::Ok(last)) => last.comma,
|
||||
// A positional connection reads its own separator; an
|
||||
// error element leaves the `,` for the list, as in a
|
||||
// non-ANSI port list.
|
||||
_ => self.eat_sym(","),
|
||||
};
|
||||
// An omitted connection (`u (a, , c)`) consumed no token, so
|
||||
// this is the empty span where it would have started.
|
||||
let span = self.span_from(start);
|
||||
let mut meta = meta;
|
||||
self.take_before_sep(&mut meta, ",");
|
||||
let comma = self.eat_sym(",");
|
||||
if comma {
|
||||
meta.trailing = self.take_trailing();
|
||||
}
|
||||
conns.push(OrderedConn { meta, expr, comma, span });
|
||||
let dirs = self.take_list_directives(directives, conns.len());
|
||||
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
|
||||
if self.list_ends(at, comma, dirs.any, recovered) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let n = conns.len();
|
||||
self.take_last_entry_before_close(conns.last_mut().map(|c| &mut c.meta), directives, n);
|
||||
let last = conns.last_mut().and_then(|c| c.ok_mut()).map(|c| &mut c.meta);
|
||||
self.take_last_entry_before_close(last, directives, n);
|
||||
Ok(Connections::Ordered(conns))
|
||||
}
|
||||
}
|
||||
|
||||
/// One positional connection (`u (a, , c)`), its separator included: an
|
||||
/// omitted one writes no token at all, so the `,` is the only thing that
|
||||
/// says it was there.
|
||||
fn parse_ordered_connection(&mut self) -> PResult<OrderedConn> {
|
||||
let start = self.here();
|
||||
let mut meta = self.take_meta();
|
||||
let expr = if self.cur().is_sym(",") || self.cur().is_sym(")") {
|
||||
None
|
||||
} else {
|
||||
Some(self.parse_expr()?)
|
||||
};
|
||||
// An omitted connection consumed no token, so this is the empty span
|
||||
// where it would have started.
|
||||
let span = self.span_from(start);
|
||||
self.take_before_sep(&mut meta, ",");
|
||||
let comma = self.eat_sym(",");
|
||||
if comma {
|
||||
meta.trailing = self.take_trailing();
|
||||
}
|
||||
Ok(OrderedConn { meta, expr, comma, span })
|
||||
}
|
||||
|
||||
/// True when the connection list starts with a named connection. The
|
||||
/// leading `(* ... *)` attributes of the first entry are looked past:
|
||||
/// they belong to the connection, not to the list.
|
||||
|
||||
@@ -86,78 +86,14 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
"if" => self.parse_if_stmt(None),
|
||||
"case" | "casex" | "casez" => self.parse_case_stmt(None),
|
||||
"for" => {
|
||||
self.bump();
|
||||
let mut comments = ForComments { after_kw: self.take_gap(), ..Default::default() };
|
||||
self.expect_sym("(")?;
|
||||
comments.after_open = self.take_gap();
|
||||
let mut init = Vec::new();
|
||||
if !self.cur().is_sym(";") {
|
||||
loop {
|
||||
// Each init may introduce its own variable, and its
|
||||
// type may be a keyword or a typedef'd name:
|
||||
// `for (int i = 0, StateEnumT t = t.first(); ...)`
|
||||
// (prim_sparse_fsm_flop.sv:48). An identifier only
|
||||
// counts as a type when another identifier follows it
|
||||
// — `for (i = 0; ...)` assigns to an existing `i`.
|
||||
let ty = {
|
||||
let t = self.cur();
|
||||
let kw_type = t.kind == TokenKind::Keyword
|
||||
&& TYPE_KEYWORDS.contains(&t.text.as_str());
|
||||
if kw_type || (t.kind == TokenKind::Ident && self.at_typed_declarator())
|
||||
{
|
||||
Some(self.parse_opt_data_type()?)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let before_name = self.take_gap();
|
||||
let lhs = self.parse_unary()?;
|
||||
let mut op_comments =
|
||||
BinaryComments { before: self.gap_before("="), after: Vec::new() };
|
||||
self.expect_sym("=")?;
|
||||
op_comments.after = self.take_gap();
|
||||
let rhs = self.parse_expr()?;
|
||||
init.push(ForInit {
|
||||
ty,
|
||||
before_name,
|
||||
assign: SimpleAssign {
|
||||
lhs,
|
||||
op: "=".to_string(),
|
||||
op_comments: Box::new(op_comments),
|
||||
rhs,
|
||||
},
|
||||
});
|
||||
if !self.eat_sym(",") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
comments.before_first_semi = self.gap_before(";");
|
||||
self.expect_sym(";")?;
|
||||
comments.after_first_semi = self.take_gap();
|
||||
let cond = if self.cur().is_sym(";") { None } else { Some(self.parse_expr()?) };
|
||||
comments.before_second_semi = self.gap_before(";");
|
||||
self.expect_sym(";")?;
|
||||
comments.after_second_semi = self.take_gap();
|
||||
let mut step = Vec::new();
|
||||
if !self.cur().is_sym(")") {
|
||||
step.push(self.parse_for_step()?);
|
||||
while self.eat_sym(",") {
|
||||
step.push(self.parse_for_step()?);
|
||||
}
|
||||
}
|
||||
comments.before_close = self.gap_before(")");
|
||||
self.expect_sym(")")?;
|
||||
let body = Box::new(self.parse_stmt()?);
|
||||
Ok(StmtKind::For { init, cond, step, comments: Box::new(comments), body })
|
||||
}
|
||||
"for" => self.parse_for_stmt(),
|
||||
"while" => {
|
||||
self.bump();
|
||||
self.expect_sym("(")?;
|
||||
let cond = self.parse_expr()?;
|
||||
self.expect_sym(")")?;
|
||||
Ok(StmtKind::While { cond, body: Box::new(self.parse_stmt()?) })
|
||||
let cond = self.cond_or_recover()?;
|
||||
let recovered = cond.is_error();
|
||||
self.expect_after_recovery(")", recovered)?;
|
||||
Ok(StmtKind::While { cond, body: Box::new(self.body_after_recovery(recovered)?) })
|
||||
}
|
||||
"do" => {
|
||||
self.bump();
|
||||
@@ -167,18 +103,19 @@ impl<'a> Parser<'a> {
|
||||
HeaderComments { after_kw: self.take_before_open("("), ..Default::default() };
|
||||
self.expect_sym("(")?;
|
||||
comments.after_open = self.take_gap();
|
||||
let cond = self.parse_expr()?;
|
||||
let cond = self.cond_or_recover()?;
|
||||
comments.before_close = self.gap_before(")");
|
||||
self.expect_sym(")")?;
|
||||
self.expect_after_recovery(")", cond.is_error())?;
|
||||
self.expect_stmt_semi()?;
|
||||
Ok(StmtKind::DoWhile { body, cond, comments: Box::new(comments) })
|
||||
}
|
||||
"repeat" => {
|
||||
self.bump();
|
||||
self.expect_sym("(")?;
|
||||
let count = self.parse_expr()?;
|
||||
self.expect_sym(")")?;
|
||||
Ok(StmtKind::Repeat { count, body: Box::new(self.parse_stmt()?) })
|
||||
let count = self.cond_or_recover()?;
|
||||
let recovered = count.is_error();
|
||||
self.expect_after_recovery(")", recovered)?;
|
||||
Ok(StmtKind::Repeat { count, body: Box::new(self.body_after_recovery(recovered)?) })
|
||||
}
|
||||
"forever" => {
|
||||
self.bump();
|
||||
@@ -334,4 +271,98 @@ impl<'a> Parser<'a> {
|
||||
_ => self.error(format!("unsupported statement starting with keyword `{kw}`")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `for ( init ; cond ; step ) statement` (IEEE 1800 §12.7.1).
|
||||
///
|
||||
/// The three sections live inside one bracket, so in tolerant mode they
|
||||
/// recover as one: whatever failed is reported once, the rest of the
|
||||
/// header becomes the loop's [`ExprKind::Error`] condition, and the body
|
||||
/// is parsed as usual. The init entries read before the failure are kept
|
||||
/// — they are what declares the loop variable the body uses.
|
||||
fn parse_for_stmt(&mut self) -> PResult<StmtKind> {
|
||||
self.bump();
|
||||
let mut comments = ForComments { after_kw: self.take_gap(), ..Default::default() };
|
||||
self.expect_sym("(")?;
|
||||
comments.after_open = self.take_gap();
|
||||
let mut init = Vec::new();
|
||||
let mut step = Vec::new();
|
||||
let start_pos = self.pos;
|
||||
let start = self.here();
|
||||
let cond = match self.parse_for_header(&mut comments, &mut init, &mut step) {
|
||||
Ok(cond) => cond,
|
||||
Err(e) if self.tolerant => Some(self.error_expr(start_pos, start, e)),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let recovered = cond.as_ref().is_some_and(Expr::is_error);
|
||||
if !recovered {
|
||||
comments.before_close = self.gap_before(")");
|
||||
}
|
||||
self.expect_after_recovery(")", recovered)?;
|
||||
let body = Box::new(self.body_after_recovery(recovered)?);
|
||||
Ok(StmtKind::For { init, cond, step, comments: Box::new(comments), body })
|
||||
}
|
||||
|
||||
/// The three sections between a `for` header's brackets, filling `init`
|
||||
/// and `step` as it goes so a failure keeps what was read before it.
|
||||
fn parse_for_header(
|
||||
&mut self,
|
||||
comments: &mut ForComments,
|
||||
init: &mut Vec<ForInit>,
|
||||
step: &mut Vec<ForStep>,
|
||||
) -> PResult<Option<Expr>> {
|
||||
if !self.cur().is_sym(";") {
|
||||
loop {
|
||||
// Each init may introduce its own variable, and its type may
|
||||
// be a keyword or a typedef'd name:
|
||||
// `for (int i = 0, StateEnumT t = t.first(); ...)`
|
||||
// (prim_sparse_fsm_flop.sv:48). An identifier only counts as a
|
||||
// type when another identifier follows it — `for (i = 0; ...)`
|
||||
// assigns to an existing `i`.
|
||||
let ty = {
|
||||
let t = self.cur();
|
||||
let kw_type =
|
||||
t.kind == TokenKind::Keyword && TYPE_KEYWORDS.contains(&t.text.as_str());
|
||||
if kw_type || (t.kind == TokenKind::Ident && self.at_typed_declarator()) {
|
||||
Some(self.parse_opt_data_type()?)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let before_name = self.take_gap();
|
||||
let lhs = self.parse_unary()?;
|
||||
let mut op_comments =
|
||||
BinaryComments { before: self.gap_before("="), after: Vec::new() };
|
||||
self.expect_sym("=")?;
|
||||
op_comments.after = self.take_gap();
|
||||
let rhs = self.parse_expr()?;
|
||||
init.push(ForInit {
|
||||
ty,
|
||||
before_name,
|
||||
assign: SimpleAssign {
|
||||
lhs,
|
||||
op: "=".to_string(),
|
||||
op_comments: Box::new(op_comments),
|
||||
rhs,
|
||||
},
|
||||
});
|
||||
if !self.eat_sym(",") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
comments.before_first_semi = self.gap_before(";");
|
||||
self.expect_sym(";")?;
|
||||
comments.after_first_semi = self.take_gap();
|
||||
let cond = if self.cur().is_sym(";") { None } else { Some(self.parse_expr()?) };
|
||||
comments.before_second_semi = self.gap_before(";");
|
||||
self.expect_sym(";")?;
|
||||
comments.after_second_semi = self.take_gap();
|
||||
if !self.cur().is_sym(")") {
|
||||
step.push(self.parse_for_step()?);
|
||||
while self.eat_sym(",") {
|
||||
step.push(self.parse_for_step()?);
|
||||
}
|
||||
}
|
||||
Ok(cond)
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,8 @@
|
||||
//! | file | holds |
|
||||
//! |---|---|
|
||||
//! | `cursor` | the token cursor, spans, `expect`/`eat`, the comment plumbing |
|
||||
//! | `recover` | tolerant-mode error recovery |
|
||||
//! | `recover` | tolerant-mode error recovery in item and statement lists |
|
||||
//! | `recover_list` | tolerant-mode error recovery inside a header's lists and brackets |
|
||||
//! | `item` | the file and item loops, the keyword → item dispatch, packages, imports, DPI, generate |
|
||||
//! | `module` | module/interface/program headers, ports, modports, clocking blocks |
|
||||
//! | `decl` | data types, declarators, parameters, `typedef`/`enum`/`struct` |
|
||||
@@ -59,6 +60,7 @@ mod keyword_stmt;
|
||||
mod module;
|
||||
mod primary;
|
||||
mod recover;
|
||||
mod recover_list;
|
||||
mod split;
|
||||
mod stmt;
|
||||
mod sva;
|
||||
|
||||
@@ -9,7 +9,7 @@ use super::*;
|
||||
#[derive(Default)]
|
||||
pub(super) struct ParamPortList {
|
||||
/// `None` when no `#( ... )` was written at all.
|
||||
pub(super) ports: Option<Vec<ParamPort>>,
|
||||
pub(super) ports: Option<Vec<ListElem<ParamPort>>>,
|
||||
pub(super) directives: Vec<ListDirective>,
|
||||
pub(super) dangling: Vec<Comment>,
|
||||
/// Comments written between the `#` and the `(`.
|
||||
@@ -32,6 +32,7 @@ impl<'a> Parser<'a> {
|
||||
imports.push(HeaderImport { meta, paths });
|
||||
}
|
||||
let param_comments = self.take_before_open("#");
|
||||
let mark = self.diags_mark();
|
||||
let ParamPortList {
|
||||
ports: param_ports,
|
||||
directives: param_directives,
|
||||
@@ -41,7 +42,10 @@ impl<'a> Parser<'a> {
|
||||
let port_comments = self.take_before_open("(");
|
||||
let (ports, port_dangling, port_directives) = self.parse_port_list()?;
|
||||
let before_semi = self.gap_before(";");
|
||||
self.expect_sym(";")?;
|
||||
// A header that already reported something keeps its `;` optional: the
|
||||
// missing one is part of the typo already reported, and the body
|
||||
// behind it is what the module is for.
|
||||
self.expect_after_recovery(";", self.recovered_since(mark))?;
|
||||
let mut items = Vec::new();
|
||||
while !self.at_body_end(end_kw) {
|
||||
items.push(self.item_or_recover()?);
|
||||
@@ -321,16 +325,19 @@ impl<'a> Parser<'a> {
|
||||
self.bump();
|
||||
out.after_hash = self.take_gap();
|
||||
self.expect_sym("(")?;
|
||||
let mark = self.diags_mark();
|
||||
let mut list = Vec::new();
|
||||
self.take_list_directives(&mut out.directives, 0);
|
||||
if !self.cur().is_sym(")") {
|
||||
loop {
|
||||
list.push(self.parse_param_port()?);
|
||||
if let Some(last) = list.last_mut() {
|
||||
let at = self.pos;
|
||||
list.push(self.element_or_recover(|p| p.parse_param_port())?);
|
||||
let recovered = list.last().is_some_and(ListElem::is_error);
|
||||
if let Some(ListElem::Ok(last)) = list.last_mut() {
|
||||
self.take_before_sep(&mut last.meta, ",");
|
||||
}
|
||||
let comma = self.eat_sym(",");
|
||||
if let Some(last) = list.last_mut() {
|
||||
if let Some(ListElem::Ok(last)) = list.last_mut() {
|
||||
last.comma = comma;
|
||||
if comma && last.meta.trailing.is_none() {
|
||||
last.meta.trailing = self.take_trailing();
|
||||
@@ -341,13 +348,15 @@ impl<'a> Parser<'a> {
|
||||
// With one, only the closing bracket says so: an `` `ifdef``
|
||||
// arm may end without a comma and another arm may still follow
|
||||
// (`` `else``), or the arm may have been the tail of the list.
|
||||
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
|
||||
// In tolerant mode the closing bracket decides on its own; see
|
||||
// [`Parser::list_ends`].
|
||||
if self.list_ends(at, comma, dirs.any, recovered) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.dangling = self.take_dangling();
|
||||
self.expect_sym(")")?;
|
||||
self.close_list(mark)?;
|
||||
out.ports = Some(list);
|
||||
Ok(out)
|
||||
}
|
||||
@@ -434,6 +443,7 @@ impl<'a> Parser<'a> {
|
||||
return Ok((PortList::None, Vec::new(), Vec::new()));
|
||||
}
|
||||
self.bump();
|
||||
let mark = self.diags_mark();
|
||||
// Directives before the first port. Harvested here rather than in the
|
||||
// loop below because both the ANSI/non-ANSI decision and the
|
||||
// written-but-empty check read the token after them.
|
||||
@@ -467,32 +477,34 @@ impl<'a> Parser<'a> {
|
||||
if ansi {
|
||||
let mut ports = Vec::new();
|
||||
loop {
|
||||
ports.push(self.parse_ansi_port()?);
|
||||
if let Some(last) = ports.last_mut() {
|
||||
let at = self.pos;
|
||||
ports.push(self.element_or_recover(|p| p.parse_ansi_port())?);
|
||||
let recovered = ports.last().is_some_and(ListElem::is_error);
|
||||
if let Some(ListElem::Ok(last)) = ports.last_mut() {
|
||||
self.take_before_sep(&mut last.meta, ",");
|
||||
}
|
||||
let comma = self.eat_sym(",");
|
||||
if let Some(last) = ports.last_mut() {
|
||||
if let Some(ListElem::Ok(last)) = ports.last_mut() {
|
||||
last.comma = comma;
|
||||
if comma && last.meta.trailing.is_none() {
|
||||
last.meta.trailing = self.take_trailing();
|
||||
}
|
||||
}
|
||||
let dirs = self.take_list_directives(&mut directives, ports.len());
|
||||
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
|
||||
if self.list_ends(at, comma, dirs.any, recovered) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Comments on their own lines before the `)` belong inside it.
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_sym(")")?;
|
||||
self.close_list(mark)?;
|
||||
// A trailing comment on the closing line belongs to the last
|
||||
// port — but only when the header did not write a `;` right
|
||||
// after the `)`. `module m (input a) /*c*/ ;` writes its comment
|
||||
// in the *header's* gap, and printing it back inside the parens
|
||||
// moves it across the `)`.
|
||||
if !self.cur().is_sym(";") {
|
||||
if let Some(last) = ports.last_mut() {
|
||||
if let Some(ListElem::Ok(last)) = ports.last_mut() {
|
||||
if last.meta.trailing.is_none() {
|
||||
last.meta.trailing = self.take_trailing();
|
||||
}
|
||||
@@ -502,25 +514,42 @@ impl<'a> Parser<'a> {
|
||||
} else {
|
||||
let mut ports = Vec::new();
|
||||
loop {
|
||||
let start = self.here();
|
||||
let mut meta = self.take_meta();
|
||||
let name = self.expect_ident()?;
|
||||
let span = self.span_from(start);
|
||||
self.take_before_sep(&mut meta, ",");
|
||||
let comma = self.eat_sym(",");
|
||||
meta.trailing = self.take_trailing();
|
||||
ports.push(NonAnsiPort { meta, name, comma, span });
|
||||
let at = self.pos;
|
||||
ports.push(self.element_or_recover(|p| p.parse_non_ansi_port())?);
|
||||
let recovered = ports.last().is_some_and(ListElem::is_error);
|
||||
let comma = match ports.last() {
|
||||
Some(ListElem::Ok(last)) => last.comma,
|
||||
// A non-ANSI port reads its own separator, so an error
|
||||
// element — which never got that far — leaves the `,` for
|
||||
// the list to take. Leaving it under the cursor was the
|
||||
// 2026-09-03 runaway: see the work log.
|
||||
_ => self.eat_sym(","),
|
||||
};
|
||||
let dirs = self.take_list_directives(&mut directives, ports.len());
|
||||
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym(")")) {
|
||||
if self.list_ends(at, comma, dirs.any, recovered) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_sym(")")?;
|
||||
self.close_list(mark)?;
|
||||
Ok((PortList::NonAnsi(ports), dangling, directives))
|
||||
}
|
||||
}
|
||||
|
||||
/// One name of a non-ANSI header's port list (`module m (a, b);`),
|
||||
/// its separator included: the port *is* its name, so there is nothing
|
||||
/// else to read and the `,` is what says whether another follows.
|
||||
fn parse_non_ansi_port(&mut self) -> PResult<NonAnsiPort> {
|
||||
let start = self.here();
|
||||
let mut meta = self.take_meta();
|
||||
let name = self.expect_ident()?;
|
||||
let span = self.span_from(start);
|
||||
self.take_before_sep(&mut meta, ",");
|
||||
let comma = self.eat_sym(",");
|
||||
meta.trailing = self.take_trailing();
|
||||
Ok(NonAnsiPort { meta, name, comma, span })
|
||||
}
|
||||
|
||||
fn parse_ansi_port(&mut self) -> PResult<AnsiPort> {
|
||||
let start = self.here();
|
||||
let mut meta = self.take_meta();
|
||||
|
||||
@@ -114,7 +114,7 @@ impl<'a> Parser<'a> {
|
||||
|
||||
/// File `err` as a diagnostic. Called while the cursor still sits on the
|
||||
/// token the error was raised at, which is where its span comes from.
|
||||
fn push_diag(&mut self, err: ParseError) {
|
||||
pub(super) fn push_diag(&mut self, err: ParseError) {
|
||||
let span = self.cur().span;
|
||||
self.diagnostics.push(ParseDiagnostic {
|
||||
message: err.message,
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
//! Error recovery *inside* a header — its bracketed lists and the parentheses
|
||||
//! of a statement header — reached only in tolerant mode.
|
||||
//!
|
||||
//! `recover.rs` recovers in item and statement **lists**, which means a typo
|
||||
//! anywhere inside a header escapes to the nearest enclosing one and takes the
|
||||
//! whole module, function or statement with it. This file is the second, much
|
||||
//! smaller answer: a list element that does not parse becomes an
|
||||
//! [`ListElem::Error`], a statement header's condition that does not parse
|
||||
//! becomes an [`ExprKind::Error`], and the construct around it keeps its name,
|
||||
//! the elements that were typed and its body.
|
||||
//!
|
||||
//! Two rules make the skipping predictable, and both are list-local:
|
||||
//!
|
||||
//! * the bracket counter is **seeded from the list's own open bracket** —
|
||||
//! already consumed by the caller — so the `;`s inside a `for (…; …; …)`
|
||||
//! header are invisible and no skip can run past the bracket that closes
|
||||
//! the list it is in;
|
||||
//! * a **line change** stops a skip. It is the one line-based rule in the
|
||||
//! parser, and it is what makes `module m (input logic a, inp⏎ output b);`
|
||||
//! cost one port instead of the rest of the list.
|
||||
//!
|
||||
//! See `docs/features/header-recovery/README.md`.
|
||||
|
||||
use super::directive::{closes_conditional, continues_conditional, opens_conditional};
|
||||
use super::*;
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
/// True where a bracketed header list may end: on its own closing
|
||||
/// bracket, on a `;` (the header was abandoned), at end of file, or on a
|
||||
/// keyword an enclosing construct owns.
|
||||
///
|
||||
/// Read only in tolerant mode, and only with the list's brackets balanced,
|
||||
/// so a `)` here is the list's own.
|
||||
pub(super) fn at_list_end(&self) -> bool {
|
||||
let t = self.cur();
|
||||
self.at_eof() || t.is_sym(")") || t.is_sym(";") || self.at_sync_stop()
|
||||
}
|
||||
|
||||
/// Whether a header list's loop is over. `start` is the cursor the
|
||||
/// iteration began at, `comma` whether a `,` followed the element just
|
||||
/// read, `dirs_any` whether a compiler directive did, and `recovered`
|
||||
/// whether that element was an error the list recovered from.
|
||||
///
|
||||
/// Strict mode asks exactly what the loops asked before this file existed,
|
||||
/// and looks at neither `start` nor `recovered`. Tolerant mode asks four
|
||||
/// things:
|
||||
///
|
||||
/// * **progress**: an iteration that consumed no token ends the list, full
|
||||
/// stop. This is the termination guarantee, and it is structural rather
|
||||
/// than argued — no reasoning about what an element parser or a skip did
|
||||
/// can make one of these loops spin, because the loop itself refuses to
|
||||
/// go round again on an unmoved cursor. (It *was* argued before, and the
|
||||
/// argument had a hole: see the work log for 2026-09-03.)
|
||||
/// * the **closing bracket**, not the comma — a missing `,` in the middle
|
||||
/// of a port list would otherwise throw away every port after it. On a
|
||||
/// list that parses, the two agree: every one of these loops ends with
|
||||
/// the cursor on its own `)`, which is what keeps a tolerant parse of a
|
||||
/// good file identical to a strict one. Reading on past a missing comma
|
||||
/// is not silent — it is one diagnostic, recorded here.
|
||||
/// * after a **recovered** element, the comma decides again: the skip ends
|
||||
/// at the separator when there is one, so no comma means the list is not
|
||||
/// there any more and what follows belongs to the enclosing construct.
|
||||
/// That is what leaves the `wire w;` under a half-typed `sub u (.a(` as
|
||||
/// an item of the module instead of swallowing it into the list.
|
||||
pub(super) fn list_ends(
|
||||
&mut self,
|
||||
start: usize,
|
||||
comma: bool,
|
||||
dirs_any: bool,
|
||||
recovered: bool,
|
||||
) -> bool {
|
||||
if !self.tolerant {
|
||||
return (!comma && !dirs_any) || (dirs_any && self.cur().is_sym(")"));
|
||||
}
|
||||
if self.pos == start || self.at_list_end() || (recovered && !comma) {
|
||||
return true;
|
||||
}
|
||||
if !comma && !dirs_any {
|
||||
self.record("expected `,`");
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Parse one element of a bracketed header list; in tolerant mode turn a
|
||||
/// failure into an error element holding the text skipped to the next
|
||||
/// element boundary. Strict mode propagates the error unchanged.
|
||||
pub(super) fn element_or_recover<T>(
|
||||
&mut self,
|
||||
parse: impl FnOnce(&mut Self) -> PResult<T>,
|
||||
) -> PResult<ListElem<T>> {
|
||||
let start_pos = self.pos;
|
||||
let start = self.here();
|
||||
match parse(self) {
|
||||
Ok(value) => Ok(ListElem::Ok(value)),
|
||||
Err(e) if self.tolerant && !self.at_conditional_directive() => {
|
||||
Ok(ListElem::Error(self.recover_element(start_pos, start, e)))
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// True on a `` `ifdef `` / `` `ifndef `` / `` `else `` / `` `elsif `` /
|
||||
/// `` `endif ``: a directive that opens, continues or closes a
|
||||
/// conditional-compilation region.
|
||||
///
|
||||
/// A list element that failed *there* is one arm of a construct written
|
||||
/// across the arms of a region — a header split by `` `ifdef `` — and the
|
||||
/// enclosing item or statement captures the whole of it verbatim
|
||||
/// (`split.rs`). Balanced directives never reach here at all;
|
||||
/// `take_list_directives` harvests those between elements. So this error
|
||||
/// is passed out untouched: recovering it would take that rescue away and
|
||||
/// give a file the strict parser reads *correctly* a different tree, which
|
||||
/// is the one thing tolerant mode may never do. Found by
|
||||
/// `tolerant_parse_equals_strict_parse_on_valid_sources` over
|
||||
/// `directive_in_statements.cases`; see the work log for 2026-09-03.
|
||||
fn at_conditional_directive(&self) -> bool {
|
||||
let t = self.cur();
|
||||
opens_conditional(t) || continues_conditional(t) || closes_conditional(t)
|
||||
}
|
||||
|
||||
/// How many diagnostics stand recorded — a mark to ask
|
||||
/// [`Parser::recovered_since`] about later. Always 0 in strict mode, which
|
||||
/// is what makes every question asked of it answer "no" there.
|
||||
pub(super) fn diags_mark(&self) -> usize {
|
||||
self.diagnostics.len()
|
||||
}
|
||||
|
||||
/// Whether anything was reported since `mark`: whether the header being
|
||||
/// parsed has already told the user what is wrong with it.
|
||||
pub(super) fn recovered_since(&self, mark: usize) -> bool {
|
||||
self.diagnostics.len() > mark
|
||||
}
|
||||
|
||||
/// Consume the `)` that closes a header list, `mark` being the diagnostic
|
||||
/// count when the list began.
|
||||
///
|
||||
/// In tolerant mode a missing one is not a failure: where the list already
|
||||
/// reported something, that message is the one about this typo and a
|
||||
/// second would be noise; where it did not, the missing bracket is itself
|
||||
/// the news and gets one diagnostic. Strict mode fails with exactly the
|
||||
/// message [`Parser::expect_sym`] would have used.
|
||||
pub(super) fn close_list(&mut self, mark: usize) -> PResult<()> {
|
||||
if self.eat_sym(")") {
|
||||
return Ok(());
|
||||
}
|
||||
if self.tolerant {
|
||||
if !self.recovered_since(mark) {
|
||||
self.record("expected `)`");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
self.error("expected `)`")
|
||||
}
|
||||
|
||||
/// Consume `sym` after a header that already recovered from an error: its
|
||||
/// diagnostic is the one about this header, so a `;` or bracket missing
|
||||
/// behind it is taken silently rather than reported twice or — worse —
|
||||
/// failing the whole header and losing the body.
|
||||
///
|
||||
/// Without a recovery, and in strict mode, this *is*
|
||||
/// [`Parser::expect_sym`].
|
||||
pub(super) fn expect_after_recovery(&mut self, sym: &str, recovered: bool) -> PResult<()> {
|
||||
if recovered && self.tolerant {
|
||||
let _ = self.eat_sym(sym);
|
||||
return Ok(());
|
||||
}
|
||||
self.expect_sym(sym).map(|_| ())
|
||||
}
|
||||
|
||||
/// The body of a statement whose header was recovered.
|
||||
///
|
||||
/// Where the enclosing block or file has already ended — `for (i = 0; i <`
|
||||
/// with an `end` under it — there is no statement to read, and reading one
|
||||
/// would consume the `end` the block is waiting for. The body is then an
|
||||
/// empty error leaf: a loop with nothing typed in it yet is still a loop,
|
||||
/// and inventing a `;` would put a token in the tree the source never
|
||||
/// wrote. Reached only in tolerant mode, and only after a recovery.
|
||||
pub(super) fn body_after_recovery(&mut self, recovered: bool) -> PResult<Stmt> {
|
||||
if !(recovered && self.tolerant && (self.at_eof() || self.at_sync_stop())) {
|
||||
return self.parse_stmt();
|
||||
}
|
||||
let span = TextRange::empty(self.here());
|
||||
let raw = RawText { text: String::new(), col: self.cur().col, span };
|
||||
Ok(Stmt {
|
||||
meta: Meta::default(),
|
||||
kind: StmtKind::Error(raw),
|
||||
before_semi: Vec::new(),
|
||||
span,
|
||||
})
|
||||
}
|
||||
|
||||
/// The condition between the brackets of an `if`, `while`, `repeat`,
|
||||
/// `case` or `do … while` header, whose `(` the caller has consumed.
|
||||
///
|
||||
/// In tolerant mode a failure — or a condition the `)` does not follow —
|
||||
/// becomes one [`ExprKind::Error`] covering the text skipped up to the
|
||||
/// header's own `)`, so the statement keeps its body and the file keeps
|
||||
/// one diagnostic. In strict mode this is [`Parser::parse_expr`], and the
|
||||
/// caller's `expect_sym(")")` reports the missing bracket as before.
|
||||
pub(super) fn cond_or_recover(&mut self) -> PResult<Expr> {
|
||||
if !self.tolerant {
|
||||
return self.parse_expr();
|
||||
}
|
||||
let start_pos = self.pos;
|
||||
let start = self.here();
|
||||
match self.parse_expr() {
|
||||
Ok(e) if self.cur().is_sym(")") => Ok(e),
|
||||
Ok(_) => {
|
||||
let err = self.make_error("expected `)`");
|
||||
Ok(self.error_expr(start_pos, start, err))
|
||||
}
|
||||
Err(e) => Ok(self.error_expr(start_pos, start, e)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Record `err` and skip the rest of a statement header's brackets,
|
||||
/// handing back the skipped source as one [`ExprKind::Error`] node.
|
||||
///
|
||||
/// Called by [`Parser::cond_or_recover`] and by the `for` header, which
|
||||
/// recovers as a whole: its three sections are one bracket, so the error
|
||||
/// node stands where its condition would.
|
||||
pub(super) fn error_expr(&mut self, start_pos: usize, start: u32, err: ParseError) -> Expr {
|
||||
self.push_diag(err);
|
||||
if self.pos == start_pos && !self.cur().is_sym(")") {
|
||||
// The header consumed nothing and the skip below may not either;
|
||||
// take one token so the statement cannot be re-read forever.
|
||||
self.bump();
|
||||
}
|
||||
self.skip_inside_brackets(true);
|
||||
// As in `recover`: comments inside the skipped range are bytes of the
|
||||
// raw text now, and the trivia copies would otherwise reattach
|
||||
// themselves to whatever node comes next.
|
||||
let _ = self.take_dangling();
|
||||
let span = self.recovered_span(start_pos, start);
|
||||
let col = self.tokens.get(start_pos).map(|t| t.col).unwrap_or(1);
|
||||
Expr { kind: ExprKind::Error(RawText { text: self.slice(span), col, span }), span }
|
||||
}
|
||||
|
||||
/// Record `err` and skip the remains of a broken list element, handing
|
||||
/// back the skipped source as a verbatim leaf spanning from `start`.
|
||||
fn recover_element(&mut self, start_pos: usize, start: u32, err: ParseError) -> RawText {
|
||||
self.push_diag(err);
|
||||
if self.pos == start_pos && !self.at_list_end() && !self.cur().is_sym(",") {
|
||||
// Nothing was consumed and nothing below will be: the list loop
|
||||
// neither ends here nor eats a separator, so take one token to
|
||||
// guarantee it advances.
|
||||
self.bump();
|
||||
}
|
||||
self.skip_inside_brackets(false);
|
||||
let _ = self.take_dangling();
|
||||
let span = self.recovered_span(start_pos, start);
|
||||
let col = self.tokens.get(start_pos).map(|t| t.col).unwrap_or(1);
|
||||
RawText { text: self.slice(span), col, span }
|
||||
}
|
||||
|
||||
/// The extent a recovery covers: from `start` through the last token it
|
||||
/// took, or the empty range at `start` when it took none (the sync point
|
||||
/// was already under the cursor).
|
||||
fn recovered_span(&self, start_pos: usize, start: u32) -> TextRange {
|
||||
if self.pos == start_pos {
|
||||
TextRange::empty(start)
|
||||
} else {
|
||||
self.span_from(start)
|
||||
}
|
||||
}
|
||||
|
||||
/// Skip forward inside a bracket the caller already consumed, stopping
|
||||
/// *before* the token that ends the skip.
|
||||
///
|
||||
/// The counter starts at one — the list's own open bracket — so a closing
|
||||
/// bracket at that level is the list's own and ends the skip, and nothing
|
||||
/// nested inside can be mistaken for it. At that level the skip also stops
|
||||
/// at a `,` (the next element's separator), at a keyword an enclosing
|
||||
/// construct owns, and at the first token of a new line. A `;` ends it too
|
||||
/// unless `through_semis` is set, which is what lets a `for` header — the
|
||||
/// one bracket with `;`s of its own inside it — recover as a whole.
|
||||
fn skip_inside_brackets(&mut self, through_semis: bool) {
|
||||
let mut open = 1u32;
|
||||
let mut line = self.prev_line();
|
||||
while !self.at_eof() {
|
||||
if open == 1 && self.at_element_sync(line, through_semis) {
|
||||
return;
|
||||
}
|
||||
let t = self.cur();
|
||||
let opens = t.is_sym("(") || t.is_sym("[") || t.is_sym("{");
|
||||
let closes = t.is_sym(")") || t.is_sym("]") || t.is_sym("}");
|
||||
line = t.line;
|
||||
if opens {
|
||||
open += 1;
|
||||
} else if closes {
|
||||
open -= 1;
|
||||
}
|
||||
self.bump();
|
||||
}
|
||||
}
|
||||
|
||||
/// True on a token that ends a skip at the list's own bracket level:
|
||||
/// `line` is the line the last token belonging to the broken element was
|
||||
/// written on, so a token on any other line starts something new.
|
||||
fn at_element_sync(&self, line: u32, through_semis: bool) -> bool {
|
||||
let t = self.cur();
|
||||
if t.is_sym(";") {
|
||||
return !through_semis;
|
||||
}
|
||||
t.line != line
|
||||
|| t.is_sym(",")
|
||||
|| t.is_sym(")")
|
||||
|| t.is_sym("]")
|
||||
|| t.is_sym("}")
|
||||
|| self.at_sync_stop()
|
||||
}
|
||||
|
||||
/// The line the last consumed token was written on — the line a skip
|
||||
/// measures "a new line" against. At the very first token there is none,
|
||||
/// so the cursor's own line stands in.
|
||||
fn prev_line(&self) -> u32 {
|
||||
match self.pos.checked_sub(1) {
|
||||
Some(i) => self.tokens[i].line,
|
||||
None => self.cur().line,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -161,9 +161,10 @@ impl<'a> Parser<'a> {
|
||||
self.expect_kw("if")?;
|
||||
let after_kw = self.take_before_open("(");
|
||||
self.expect_sym("(")?;
|
||||
let cond = self.parse_expr()?;
|
||||
self.expect_sym(")")?;
|
||||
let then = Box::new(self.parse_stmt()?);
|
||||
let cond = self.cond_or_recover()?;
|
||||
let recovered = cond.is_error();
|
||||
self.expect_after_recovery(")", recovered)?;
|
||||
let then = Box::new(self.body_after_recovery(recovered)?);
|
||||
let mut else_comments = Vec::new();
|
||||
let els = if self.cur().is_kw("else") {
|
||||
// Whatever was written in the gap before `else` stays on the
|
||||
@@ -182,8 +183,8 @@ impl<'a> Parser<'a> {
|
||||
let kw = self.bump().text;
|
||||
let after_kw = self.take_before_open("(");
|
||||
self.expect_sym("(")?;
|
||||
let expr = self.parse_expr()?;
|
||||
self.expect_sym(")")?;
|
||||
let expr = self.cond_or_recover()?;
|
||||
self.expect_after_recovery(")", expr.is_error())?;
|
||||
// `case (x) inside` — the same statement with one extra token, whose
|
||||
// labels may be `[lo:hi]` ranges (handled by `parse_expr_item`).
|
||||
let inside = self.eat_kw("inside");
|
||||
|
||||
@@ -14,7 +14,7 @@ fn class_header_parts_are_kept_apart() {
|
||||
assert_eq!(c.param_ports.as_ref().expect("a parameter port list").len(), 1);
|
||||
let ext = c.extends.as_ref().expect("an extends clause");
|
||||
assert_eq!(ext.name, "pkg::base");
|
||||
let params = ext.params.as_ref().expect("base parameter overrides");
|
||||
let params = oks(ext.params.as_ref().expect("base parameter overrides"));
|
||||
assert_eq!(params.len(), 2);
|
||||
assert_eq!(params[0].name, "A");
|
||||
// An ordered override has no name, only an expression.
|
||||
|
||||
@@ -45,6 +45,7 @@ fn a_comment_before_a_list_comma_lands_in_before_sep() {
|
||||
let file = parse_ok("module m (input a /* pre */, /* post */ input b);\nendmodule");
|
||||
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
|
||||
let PortList::Ansi(ports) = &m.ports else { panic!("expected an ANSI port list") };
|
||||
let ports = oks(ports);
|
||||
assert_eq!(ports[0].meta.before_sep.len(), 1, "written before the comma");
|
||||
assert_eq!(ports[0].meta.before_sep[0].text, "/* pre */");
|
||||
let trailing = ports[0].meta.trailing.as_ref().expect("written after the comma");
|
||||
@@ -59,6 +60,7 @@ fn a_comment_after_the_last_element_is_not_a_before_sep_comment() {
|
||||
let file = parse_ok("module m (input a /* tail */);\nendmodule");
|
||||
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
|
||||
let PortList::Ansi(ports) = &m.ports else { panic!("expected an ANSI port list") };
|
||||
let ports = oks(ports);
|
||||
assert!(ports[0].meta.before_sep.is_empty(), "nothing separates it from the `)`");
|
||||
assert_eq!(ports[0].meta.trailing.as_ref().expect("a trailing comment").text, "/* tail */");
|
||||
}
|
||||
@@ -99,7 +101,7 @@ fn comments_before_a_headers_brackets_land_on_the_module() {
|
||||
assert_eq!(m.param_comments[0].text, "// params");
|
||||
assert_eq!(m.port_comments.len(), 1);
|
||||
assert_eq!(m.port_comments[0].text, "// ports");
|
||||
let params = m.param_ports.as_ref().expect("a parameter port list");
|
||||
let params = oks(m.param_ports.as_ref().expect("a parameter port list"));
|
||||
assert!(params[0].meta.leading.is_empty(), "not the first parameter's leading comment");
|
||||
}
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ fn a_covergroup_header_keeps_its_name_its_args_and_its_end_label() {
|
||||
let g = covergroup_of(&f);
|
||||
assert_eq!(g.name.text, "g");
|
||||
assert_eq!(&f.span.as_range().start, &0);
|
||||
let args = g.args.as_ref().expect("the formal list was parsed");
|
||||
let args = oks(g.args.as_ref().expect("the formal list was parsed"));
|
||||
assert_eq!(args.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), ["a", "n"]);
|
||||
assert_eq!(g.end_label.as_ref().expect("the label was kept").text, "g");
|
||||
assert!(!g.end_semi);
|
||||
@@ -98,7 +98,7 @@ fn a_sample_function_header_keeps_the_word_and_its_arguments() {
|
||||
};
|
||||
assert_eq!(s.name.text, "sample");
|
||||
assert!(s.has_parens);
|
||||
assert_eq!(s.args.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), ["addr", "rw"]);
|
||||
assert_eq!(oks(&s.args).iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), ["addr", "rw"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -131,8 +131,8 @@ fn a_virtual_interface_type_stands_in_every_type_position() {
|
||||
assert_eq!(ty.virt, Some(VirtualKw::Bare));
|
||||
assert_eq!(ty.name, "push_pull_if");
|
||||
let ItemKind::Function(fun) = &items[1].kind else { panic!("expected a function") };
|
||||
assert_eq!(fun.args[0].ty.virt, Some(VirtualKw::Interface));
|
||||
assert_eq!(fun.args[0].ty.name, "bus_if");
|
||||
assert_eq!(oks(&fun.args)[0].ty.virt, Some(VirtualKw::Interface));
|
||||
assert_eq!(oks(&fun.args)[0].ty.name, "bus_if");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -229,7 +229,7 @@ fn a_let_declaration_keeps_its_ports_and_its_value() {
|
||||
assert_eq!(l.name, "max");
|
||||
assert!(l.has_parens);
|
||||
assert_eq!(l.ports.len(), 2);
|
||||
assert_eq!(l.ports[1].name, "b");
|
||||
assert_eq!(oks(&l.ports)[1].name, "b");
|
||||
assert!(matches!(l.value.kind, ExprKind::Ternary { .. }));
|
||||
}
|
||||
|
||||
@@ -266,8 +266,8 @@ fn a_virtual_interface_type_may_name_a_modport() {
|
||||
let f = parse_ok("module m;\n task t(virtual spi_if.tb sif);\n endtask\nendmodule\n");
|
||||
let m = module_of(&f);
|
||||
let ItemKind::Task(t) = &m.items[0].kind else { panic!("expected a task") };
|
||||
assert_eq!(t.args[0].ty.name, "spi_if.tb");
|
||||
assert!(t.args[0].ty.virt.is_some(), "still a virtual interface type");
|
||||
assert_eq!(oks(&t.args)[0].ty.name, "spi_if.tb");
|
||||
assert!(oks(&t.args)[0].ty.virt.is_some(), "still a virtual interface type");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -183,6 +183,7 @@ fn a_directive_between_ports_records_its_place_and_the_commas_around_it() {
|
||||
let file = parse_ok(src);
|
||||
let m = module_of(&file);
|
||||
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") };
|
||||
let ports = oks(ports);
|
||||
assert_eq!(ports.len(), 3);
|
||||
assert_eq!(
|
||||
ports.iter().map(|p| p.comma).collect::<Vec<_>>(),
|
||||
@@ -206,7 +207,7 @@ fn a_comma_written_after_a_directive_belongs_to_the_directive() {
|
||||
let src = "module m #(\n parameter int A = 1\n`ifdef S\n ,\n parameter int B = 2\n`endif\n) ();\nendmodule\n";
|
||||
let file = parse_ok(src);
|
||||
let m = module_of(&file);
|
||||
let params = m.param_ports.as_ref().expect("a parameter port list");
|
||||
let params = oks(m.param_ports.as_ref().expect("a parameter port list"));
|
||||
assert_eq!(params.len(), 2);
|
||||
assert!(!params[0].comma, "the first parameter wrote no comma of its own");
|
||||
assert!(!params[1].comma);
|
||||
@@ -225,6 +226,7 @@ fn a_list_with_no_directive_keeps_an_empty_directive_vector() {
|
||||
assert!(m.param_directives.is_empty());
|
||||
assert!(m.port_directives.is_empty());
|
||||
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") };
|
||||
let ports = oks(ports);
|
||||
assert_eq!(ports.iter().map(|p| p.comma).collect::<Vec<_>>(), vec![true, false]);
|
||||
}
|
||||
|
||||
@@ -236,6 +238,7 @@ fn both_arms_of_an_else_are_ordinary_elements_of_one_list() {
|
||||
let file = parse_ok(src);
|
||||
let m = module_of(&file);
|
||||
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports") };
|
||||
let ports = oks(ports);
|
||||
assert_eq!(ports.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), vec!["a", "b"]);
|
||||
assert!(ports.iter().all(|p| !p.comma), "neither arm's port wrote a comma");
|
||||
assert_eq!(m.port_directives.len(), 3);
|
||||
@@ -288,6 +291,7 @@ fn a_directive_between_connections_records_its_place_and_the_commas() {
|
||||
let Connections::Named(conns) = &inst.instances[0].conns else {
|
||||
panic!("expected named connections")
|
||||
};
|
||||
let conns = oks(conns);
|
||||
assert_eq!(conns.len(), 3);
|
||||
assert_eq!(
|
||||
conns.iter().map(|c| c.comma).collect::<Vec<_>>(),
|
||||
@@ -311,7 +315,7 @@ fn a_directive_between_parameter_overrides_lands_on_the_instantiation() {
|
||||
let src = "module m;\n sub #(\n`ifndef S\n`ifdef T\n .P(0),\n`endif\n .Q(1)\n`endif\n ) u (.a(x));\nendmodule\n";
|
||||
let file = parse_ok(src);
|
||||
let inst = instantiation_of(&file);
|
||||
let params = inst.params.as_ref().expect("an override list");
|
||||
let params = oks(inst.params.as_ref().expect("an override list"));
|
||||
assert_eq!(params.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), vec!["P", "Q"]);
|
||||
assert_eq!(params.iter().map(|c| c.comma).collect::<Vec<_>>(), vec![true, false]);
|
||||
let d = &inst.param_directives;
|
||||
@@ -355,6 +359,7 @@ fn a_directive_before_the_first_connection_does_not_hide_the_dot() {
|
||||
let Connections::Named(conns) = &inst.instances[0].conns else {
|
||||
panic!("expected named connections")
|
||||
};
|
||||
let conns = oks(conns);
|
||||
assert_eq!(conns.len(), 2);
|
||||
assert_eq!(inst.instances[0].conn_directives[0].before, 0);
|
||||
}
|
||||
@@ -367,6 +372,7 @@ fn a_directive_between_positional_connections_is_harvested_too() {
|
||||
let Connections::Ordered(conns) = &inst.instances[0].conns else {
|
||||
panic!("expected ordered connections")
|
||||
};
|
||||
let conns = oks(conns);
|
||||
assert_eq!(conns.iter().map(|c| c.comma).collect::<Vec<_>>(), vec![true, true, false]);
|
||||
assert_eq!(inst.instances[0].conn_directives.len(), 2);
|
||||
}
|
||||
@@ -383,6 +389,7 @@ fn an_instantiation_with_no_directive_keeps_empty_directive_vectors() {
|
||||
let Connections::Named(conns) = &inst.instances[0].conns else {
|
||||
panic!("expected named connections")
|
||||
};
|
||||
let conns = oks(conns);
|
||||
assert_eq!(conns.iter().map(|c| c.comma).collect::<Vec<_>>(), vec![true, false]);
|
||||
}
|
||||
|
||||
@@ -405,6 +412,7 @@ fn a_directive_inside_a_connection_is_captured_or_refused_by_kind() {
|
||||
let Connections::Named(conns) = &inst.instances[0].conns else {
|
||||
panic!("expected named connections")
|
||||
};
|
||||
let conns = oks(conns);
|
||||
assert_eq!(conns[0].name, "a");
|
||||
let Some(Expr { kind: ExprKind::Verbatim(raw), .. }) = &conns[0].expr else {
|
||||
panic!("expected a verbatim value")
|
||||
|
||||
@@ -163,6 +163,7 @@ fn an_attribute_may_precede_a_named_port_connection() {
|
||||
let Connections::Named(conns) = &inst.instances[0].conns else {
|
||||
panic!("expected named connections")
|
||||
};
|
||||
let conns = oks(conns);
|
||||
assert_eq!(conns[0].meta.attrs.len(), 1);
|
||||
assert_eq!(conns[0].meta.attrs[0].text, "(* async *)");
|
||||
assert_eq!(conns[0].name, "a");
|
||||
|
||||
@@ -73,7 +73,7 @@ fn a_dpi_import_is_a_function_prototype_with_a_linkage_prefix() {
|
||||
assert_eq!(b.dpi.as_ref().and_then(|d| d.property.clone()), Some("context".to_string()));
|
||||
assert_eq!(b.ret.as_ref().map(|t| t.name.clone()), Some("chandle".to_string()));
|
||||
assert_eq!(b.args.len(), 1);
|
||||
assert!(b.args[0].dir.is_none());
|
||||
assert!(oks(&b.args)[0].dir.is_none());
|
||||
|
||||
let ItemKind::Task(c) = &items[2].kind else { panic!("expected a task") };
|
||||
let dpi = c.dpi.as_ref().expect("DPI prefix");
|
||||
@@ -101,11 +101,12 @@ fn a_dpi_import_formal_may_be_written_without_a_name() {
|
||||
let f = parse_ok(src);
|
||||
let ItemKind::Package { items, .. } = &f.items[0].kind else { panic!("expected package") };
|
||||
let ItemKind::Function(g) = &items[0].kind else { panic!("expected a function") };
|
||||
let names: Vec<&str> = g.args.iter().map(|a| a.name.as_str()).collect();
|
||||
let args = oks(&g.args);
|
||||
let names: Vec<&str> = args.iter().map(|a| a.name.as_str()).collect();
|
||||
assert_eq!(names, ["", "", "named"]);
|
||||
assert_eq!(g.args[1].dir.as_deref(), Some("input"));
|
||||
assert_eq!(g.args[1].ty.name, "logic");
|
||||
for a in &g.args[..2] {
|
||||
assert_eq!(args[1].dir.as_deref(), Some("input"));
|
||||
assert_eq!(args[1].ty.name, "logic");
|
||||
for a in &args[..2] {
|
||||
assert!(a.name_span.is_empty(), "an absent name spans nothing");
|
||||
assert!(a.span.start <= a.name_span.start && a.name_span.end <= a.span.end);
|
||||
}
|
||||
|
||||
@@ -28,6 +28,13 @@ fn parse_ok(src: &str) -> SourceFile {
|
||||
}
|
||||
}
|
||||
|
||||
/// The well-formed elements of a header list. Every source here is parsed by
|
||||
/// the **strict** parser, which never builds a [`ListElem::Error`], so this is
|
||||
/// the whole list — it is the shape, not the content, that the wrapper costs.
|
||||
fn oks<T>(list: &[ListElem<T>]) -> Vec<&T> {
|
||||
list.iter().filter_map(ListElem::ok).collect()
|
||||
}
|
||||
|
||||
/// The keywords of a qualifier run, without the comments each one carries.
|
||||
fn words(run: &[Qualifier]) -> Vec<&str> {
|
||||
run.iter().map(|q| q.text.as_str()).collect()
|
||||
|
||||
@@ -57,7 +57,7 @@ fn ansi_ports(src: &str) -> Vec<(String, String, String)> {
|
||||
let file = parse_ok(src);
|
||||
let m = module_of(&file);
|
||||
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports in {src:?}") };
|
||||
ports
|
||||
oks(ports)
|
||||
.iter()
|
||||
.map(|p| (p.dir.clone().unwrap_or_default(), p.ty.name.clone(), p.name.clone()))
|
||||
.collect()
|
||||
@@ -147,6 +147,7 @@ fn a_name_only_port_list_is_still_non_ansi() {
|
||||
let file = parse_ok("module m (a, b, c);\ninput a;\ninput b;\noutput c;\nendmodule\n");
|
||||
let m = module_of(&file);
|
||||
let PortList::NonAnsi(ports) = &m.ports else { panic!("expected a non-ANSI port list") };
|
||||
let ports = oks(ports);
|
||||
assert_eq!(ports.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), vec!["a", "b", "c"]);
|
||||
assert_eq!(ports.iter().map(|p| p.comma).collect::<Vec<_>>(), vec![true, true, false]);
|
||||
|
||||
@@ -283,9 +284,10 @@ fn a_modport_may_import_a_method_prototype() {
|
||||
assert_eq!(drive.kind, TfKind::Task);
|
||||
assert_eq!(drive.name, "drive");
|
||||
assert!(drive.ret.is_none(), "a task has no return type");
|
||||
assert_eq!(drive.args.len(), 1);
|
||||
assert_eq!(drive.args[0].name, "x");
|
||||
assert_eq!(drive.args[0].dir.as_deref(), Some("input"));
|
||||
let drive_args = oks(&drive.args);
|
||||
assert_eq!(drive_args.len(), 1);
|
||||
assert_eq!(drive_args[0].name, "x");
|
||||
assert_eq!(drive_args[0].dir.as_deref(), Some("input"));
|
||||
assert!(ports[1].names.is_empty(), "a prototype group names nothing else");
|
||||
let peek = ports[2].prototype.as_ref().expect("an exported prototype");
|
||||
assert_eq!(ports[2].kw, "export");
|
||||
@@ -320,7 +322,7 @@ fn every_gap_of_a_modport_prototype_has_an_owner() {
|
||||
let p = port.prototype.as_ref().expect("a prototype");
|
||||
assert_eq!(p.after_kw.len(), 1, "between `task` and the name");
|
||||
assert_eq!(p.before_args.len(), 1, "between the name and the `(`");
|
||||
assert_eq!(p.args[0].meta.leading.len(), 1, "inside the `(`");
|
||||
assert_eq!(oks(&p.args)[0].meta.leading.len(), 1, "inside the `(`");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user