Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c4bdbcfea | ||
|
|
e902af37c5 | ||
|
|
4ba6eafa2d | ||
|
|
747ae02b0e | ||
|
|
ffbb29ddbb | ||
|
|
f1d44a2a0c | ||
|
|
10b63e665d | ||
|
|
a648561f63 | ||
|
|
1c20549cfa | ||
|
|
97f7296b8f | ||
|
|
cebeff45b4 | ||
|
|
6a15594ae8 | ||
|
|
4d70de1976 |
No files matched your search
@@ -4,6 +4,71 @@ 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.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
|
||||
|
||||
@@ -128,6 +128,20 @@ Rules:
|
||||
- Update `TODO.md`: check items your feature completes (leave the item
|
||||
text intact).
|
||||
|
||||
## Runaway guard (never run a suite or sweep bare)
|
||||
|
||||
On 2026-09-03 a background test run consumed 100 GB and crashed the
|
||||
machine. macOS enforces no memory cap, so the cap is ours:
|
||||
`tools/guard.sh [-m GB] [-t SECONDS] -- <command>` kills a command's
|
||||
process tree when its resident set or wall clock exceeds the limits
|
||||
(defaults 8 GB / 30 min).
|
||||
|
||||
- **Every `cargo test`, every fuzzer, every corpus or opentitan sweep,
|
||||
and every `lucisv`/`lucisv-server` run over a tree goes through
|
||||
`tools/guard.sh`** — dev, QA and lead alike, foreground or background.
|
||||
- A guard kill is a finding: report the command and the limit it hit;
|
||||
do not raise the limit to make it pass.
|
||||
|
||||
## Parallel lanes (the 2-agent loop)
|
||||
|
||||
Up to **two dev/QA lanes may run concurrently** when — and only when —
|
||||
|
||||
Generated
+8
-8
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.35.0"
|
||||
version = "0.37.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.35.0"
|
||||
version = "0.37.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.35.0"
|
||||
version = "0.37.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.35.0"
|
||||
version = "0.37.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.35.0"
|
||||
version = "0.37.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -264,11 +264,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.35.0"
|
||||
version = "0.37.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.35.0"
|
||||
version = "0.37.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
@@ -276,7 +276,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.35.0"
|
||||
version = "0.37.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.35.0"
|
||||
version = "0.37.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -172,11 +172,13 @@ would format — same walk, same `--exclude`, same `.gitignore` handling, same
|
||||
`lucisv.toml` discovery.
|
||||
|
||||
```bash
|
||||
lucisv check rtl/ # FILE:LINE:COL: message [rule-name]
|
||||
lucisv check rtl/ # FILE:LINE:COL: severity: message [rule]
|
||||
lucisv check --output-format json rtl/ # one JSON array, for editors and CI
|
||||
lucisv check --select no-tabs rtl/ # only these rules (comma-separated)
|
||||
lucisv check --ignore module-filename rtl/ # everything but these
|
||||
lucisv check --select error rtl/ # a whole severity class, by name
|
||||
lucisv check --fix rtl/ # apply the safe fixes, write files back
|
||||
lucisv check --rules-doc # the generated reference for every rule
|
||||
```
|
||||
|
||||
Exit codes are the frozen contract above: 0 clean (or everything fixed), 1
|
||||
@@ -184,28 +186,84 @@ violations remain, 2 error. Unlike the formatter, `check` uses the
|
||||
error-tolerant parser, so a file lucisv cannot fully parse is still linted for
|
||||
what it can see.
|
||||
|
||||
| Rule | Fix | What it wants |
|
||||
### Severities
|
||||
|
||||
Every rule is in one of three classes, and the class is the word that stands
|
||||
in the diagnostic line, in the JSON `severity` field, and in the editor's
|
||||
squiggle colour:
|
||||
|
||||
| Class | Means | Editor |
|
||||
|---|---|---|
|
||||
| `no-tabs` | safe | spaces, not tabs (a tab inside a string is left alone) |
|
||||
| `no-trailing-whitespace` | safe | nothing but code before the newline |
|
||||
| `case-missing-default` | — | every `case`/`casex`/`casez` has a `default` |
|
||||
| `always-ff-non-blocking` | — | `<=` inside `always_ff` |
|
||||
| `always-comb-blocking` | — | `=` inside `always_comb` |
|
||||
| `explicit-parameter-storage-type` | — | `parameter int W = 8`, not `parameter W = 8` |
|
||||
| `module-filename` | — | a one-module file is named after its module |
|
||||
| `unused-waiver` | — | waivers that suppress nothing |
|
||||
| `unused-signal` † | — | no net or variable nothing uses |
|
||||
| `undriven-net` † | — | everything read is driven by something |
|
||||
| `multiply-driven` † | — | one driver per variable |
|
||||
| `error` | would very likely fail to compile, elaborate or synthesize | red (LSP Error) |
|
||||
| `warning` | compiles, and very likely does not mean what it says | yellow (LSP Warning) |
|
||||
| `style` | correct, and reads badly | blue (LSP Information) |
|
||||
|
||||
A class name is accepted **wherever a rule name is** — on `--select`, on
|
||||
`--ignore`, and in `select`/`ignore` under `[lint]` in `lucisv.toml`:
|
||||
|
||||
```bash
|
||||
lucisv check --select error rtl/ # only the compile-breakers
|
||||
lucisv check --ignore style rtl/ # everything but the naming rules
|
||||
```
|
||||
|
||||
Every `error`-class rule follows one discipline: **silence beats a wrong
|
||||
accusation**. Each of them goes quiet whenever the run cannot answer — a file
|
||||
that did not fully parse, a module the project does not hold or holds twice, a
|
||||
name a macro produces, a fragment written to be `` `include``d. That is what
|
||||
makes an editor's red squiggle worth believing.
|
||||
|
||||
### The rules
|
||||
|
||||
| Rule | Severity | Fix | What it wants |
|
||||
|---|---|---|---|
|
||||
| `multiply-driven` † | error | — | one driver per variable |
|
||||
| `wire-reg-mixup` | error | — | `logic`, not `reg`, in a `.sv` file |
|
||||
| `mismatched-labels` | error | — | `end : name` names the block it closes |
|
||||
| `duplicate-declaration` | error | — | each name declared once per scope |
|
||||
| `undeclared-identifier` † | error | — | every name is declared somewhere in the project |
|
||||
| `unknown-port` † | error | — | `.name(…)` is a port the module declares |
|
||||
| `unknown-parameter` † | error | — | `#(.NAME(…))` is a parameter it declares |
|
||||
| `always-ff-non-blocking` | warning | — | `<=` inside `always_ff` |
|
||||
| `always-comb-blocking` | warning | — | `=` inside `always_comb` |
|
||||
| `case-missing-default` | warning | — | every `case`/`casex`/`casez` has a `default` |
|
||||
| `incomplete-assignment` | warning | — | an `always_comb` assigns on every path |
|
||||
| `suspicious-semicolon` | warning | — | no `if (x);` / `for (…);` / `while (…);` |
|
||||
| `forbid-defparam` | warning | — | override at the instantiation, not with `defparam` |
|
||||
| `invalid-system-task-function` | warning | — | no `$random`, `$psprintf`, `$dist_*`, `$srandom` |
|
||||
| `plusarg-assignment` | warning | — | `$value$plusargs`, not `$test$plusargs` |
|
||||
| `truncated-numeric-literal` | warning | — | a sized literal fits its width |
|
||||
| `undersized-binary-literal` | warning | safe | every bit of a sized binary literal is written |
|
||||
| `packed-dimensions-range-ordering` | warning | — | a packed dimension is `[N-1:0]` |
|
||||
| `forbid-negative-array-dim` | warning | — | no negative literal in a dimension |
|
||||
| `module-port` | warning | — | more than one port is connected by name |
|
||||
| `module-parameter` | warning | — | more than one parameter is overridden by name |
|
||||
| `explicit-function-task-parameter-type` | warning | — | every tf argument has a storage type |
|
||||
| `void-cast` | warning | — | `void'(…)` wraps a call |
|
||||
| `instance-shadowing` | warning | — | no declaration hides an enclosing one |
|
||||
| `undriven-net` † | warning | — | everything read is driven by something |
|
||||
| `unused-signal` † | warning | — | no net or variable nothing uses |
|
||||
| `no-tabs` | style | safe | spaces, not tabs (a tab inside a string is left alone) |
|
||||
| `no-trailing-whitespace` | style | safe | nothing but code before the newline |
|
||||
| `empty-item` | style | safe | no `;` standing where an item belongs |
|
||||
| `explicit-parameter-storage-type` | style | — | `parameter int W = 8`, not `parameter W = 8` |
|
||||
| `module-filename` | style | — | a one-module file is named after its module |
|
||||
| `enum-name-style` | style | — | `lower_snake_case` ending `_e`/`_t` |
|
||||
| `struct-union-name-style` | style | — | `lower_snake_case` ending `_t` |
|
||||
| `parameter-name-style` | style | — | `CamelCase` or `ALL_CAPS` |
|
||||
| `module-name-style` | style | — | `lower_snake_case` (off by default) |
|
||||
| `unused-waiver` | style | — | waivers that suppress nothing |
|
||||
|
||||
† On by default when lucisv can see a project (a multi-file CLI run or the
|
||||
language server), and off for a single file or stdin unless `--select` names
|
||||
them. These three read the file's *symbol table*, not just its syntax; the
|
||||
project-wide identifier census keeps a hierarchical use in another file from
|
||||
becoming a false positive. See `docs/features/semantic-lints-on/README.md`.
|
||||
The table above is not the whole set — naming-style rules ship too, and
|
||||
`cargo run -p vlog_linter --example rules_markdown` prints the generated
|
||||
reference for every rule with its default.
|
||||
them. These rules read the file's *symbol table* and ask the project about
|
||||
names, not just the file's syntax; the project-wide identifier census keeps a
|
||||
hierarchical use in another file from becoming a false positive. See
|
||||
`docs/features/semantic-lints-on/README.md` and
|
||||
`docs/features/linter-expansion-1/README.md`.
|
||||
|
||||
`lucisv check --rules-doc` prints the whole reference — every rule, its class,
|
||||
its default, its fix and the paragraph saying why it exists — generated from
|
||||
the registry, so it can never be out of date.
|
||||
|
||||
Fixes follow ruff's applicability model: `--fix` applies *safe* fixes (those
|
||||
that cannot change what the code means), `--unsafe-fixes` widens that — no
|
||||
|
||||
@@ -3454,21 +3454,24 @@ only), crates/lucisv_server/src/perf.rs (measurement only), docs/
|
||||
features/header-recovery/README.md (new), amendments in error-recovery
|
||||
README, docs/coverage_gaps.md M10, TODO §32. Runs after §31 (parser +
|
||||
formatter collide with §30's tf.rs/module.rs at merge; sequential).
|
||||
- [ ] 32.1 error elements in the four list types + `ExprKind::Error`;
|
||||
cross-crate arms pre-agreed
|
||||
- [ ] 32.2 `element_or_recover` with the list-local, bracket-seeded
|
||||
- [x] 32.1 error elements in the four list types + `ExprKind::Error`;
|
||||
cross-crate arms pre-agreed — one generic `ListElem<T>` over five
|
||||
lists (a class's parameter ports are the fifth)
|
||||
- [x] 32.2 `element_or_recover` with the list-local, bracket-seeded
|
||||
sync set (`,` `)` `;` line change)
|
||||
- [ ] 32.3 headers keep their node (port, param, tf-port, connection
|
||||
- [x] 32.3 headers keep their node (port, param, tf-port, connection
|
||||
lists infallible in tolerant mode; closers via `expect_closer`)
|
||||
- [ ] 32.4 `for`/`if`/`while`/`case` conditions recover inside the
|
||||
parentheses
|
||||
- [ ] 32.5 parser pins per shape with exact counts; walkers extended;
|
||||
- [x] 32.4 `for`/`if`/`while`/`case` conditions recover inside the
|
||||
parentheses (`repeat` and `do…while` too, same helper)
|
||||
- [x] 32.5 parser pins per shape with exact counts; walkers extended;
|
||||
550-source equality and the fuzzers green
|
||||
- [ ] 32.6 server pins: symbols survive, completion scope survives, one
|
||||
- [x] 32.6 server pins: symbols survive, completion scope survives, one
|
||||
diagnostic, validity probes unchanged
|
||||
- [ ] 32.7 docs + measurements (parse_tolerant timing, truncated-corpus
|
||||
diagnostic census)
|
||||
- [ ] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
|
||||
- [x] 32.7 docs + measurements (parse_tolerant timing, truncated-corpus
|
||||
diagnostic census — error nodes 622 → 555, diagnostics 1 702 →
|
||||
1 826: the constructs that now survive report their own missing
|
||||
closers)
|
||||
- [x] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
|
||||
byte-identical (strict path untouched); opentitan read-only sweep
|
||||
unchanged
|
||||
- [ ] QA: type each of the (a)–(f) shapes into the real server against
|
||||
@@ -3630,45 +3633,147 @@ additive, say so in Handshakes), crates/lucisv/src/{lint.rs, args.rs}
|
||||
editors/vscode/{package.json, README.md}, README.md "Linting",
|
||||
docs/site/src/content/docs/reference/rules.md, docs/features/
|
||||
linter-expansion-1/README.md (new), TODO §33. Worktree `lint-1`.
|
||||
- [ ] 33.0 `Severity` on every rule; select/ignore by severity; CLI
|
||||
- [x] 33.0 `Severity` on every rule; select/ignore by severity; CLI
|
||||
text/JSON; editor severities; `--rules-doc` grouped
|
||||
- [ ] 33.1 package.json toggles generated + drift test; `enabled_rules`
|
||||
- [x] 33.1 package.json toggles generated + drift test; `enabled_rules`
|
||||
precedence pinned; republish on change
|
||||
- [ ] 33.2 Error rules: mismatched-labels, duplicate-declaration,
|
||||
- [x] 33.2 Error rules: mismatched-labels, duplicate-declaration,
|
||||
undeclared-identifier (measured; default decided by the count),
|
||||
unknown-port, unknown-parameter
|
||||
- [ ] 33.3 Warning rules: the thirteen listed, each with tests and an
|
||||
- [x] 33.3 Warning rules: the thirteen listed, each with tests and an
|
||||
opentitan count
|
||||
- [ ] 33.4 docs; measurements table in the README
|
||||
- [ ] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
|
||||
- [x] 33.4 docs; measurements table in the README
|
||||
- [x] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
|
||||
byte-identical (formatter untouched); opentitan read-only
|
||||
`lucisv check` census + timing
|
||||
- [ ] QA: every new rule attacked with hand-written true positives and
|
||||
near-misses; the false-positive census re-read; toggles exercised
|
||||
through the real server (`workspace/didChangeConfiguration`)
|
||||
|
||||
## 34. Linter expansion, wave 2 (planned 2026-09-02, after §33) — the Style class and per-rule options
|
||||
## 34. Linter expansion, wave 2 (planned 2026-09-03) — per-rule options, and the first eighteen Style rules
|
||||
|
||||
The style family from Verible, with the per-rule configuration the
|
||||
naming rules need: `signal-name-style`, `interface-name-style`,
|
||||
`macro-name-style`, `constraint-name-style`, `parameter-type-name-style`,
|
||||
`dff-name-style`, `port-name-suffix`, `banned-declared-name-patterns`
|
||||
(each with a `pattern`/style option), `line-length` (reads the
|
||||
formatter's `line-length`), `posix-eof` (safe fix), `endif-comment`,
|
||||
`forbid-line-continuations`, `one-module-per-file`, `package-filename`,
|
||||
`typedef-enums`, `typedef-structs-unions`, `module-begin-block`,
|
||||
`generate-label` + `generate-label-prefix`, `always-comb` (`@*` →
|
||||
`always_comb`, safe fix), `legacy-generate-region`,
|
||||
`legacy-genvar-declaration`, `v2001-generate-begin`,
|
||||
After §33 (36 rules, severities, toggles). Two things this wave adds:
|
||||
the **option plumbing** every configurable rule needs, and the Style
|
||||
rules from Verible's list that carry the most weight in a style guide
|
||||
(naming, file layout, generate labels, typedefs, line length). Dev
|
||||
Opus 5, QA Sonnet 5. Feature README: `docs/features/linter-expansion-2/
|
||||
README.md`. Mapped: `lucisv_core::config` parses one table, `[lint]`,
|
||||
with `select`/`ignore`, and rejects `[lint.<rule>]` by name
|
||||
(`config.rs::parse_entry`: "per-rule lint settings … are not supported
|
||||
yet"); the editor has `lucisv.lint.select/ignore/severity.*/rules.*`;
|
||||
`Rule` has no notion of options; `LintContext` carries source, tokens,
|
||||
tree, semantics slot and the oracle; `line-length` already lives in
|
||||
`FileConfig` for the formatter.
|
||||
|
||||
**34.0 Options, end to end.**
|
||||
(a) `vlog_linter`: `pub struct OptionSpec { name: &'static str, kind:
|
||||
OptionKind (Bool | Int { min, max } | Str | Regex | List), default:
|
||||
OptionValue, doc: &'static str }` and `Rule::options(&self) ->
|
||||
&'static [OptionSpec]` (default empty); `RuleOptions` — a validated
|
||||
map `rule → key → OptionValue` built by `RuleOptions::parse(rule, key,
|
||||
raw)` that rejects an unknown key ("rule `x` has no option `y`; it has:
|
||||
…"), a wrong kind, an out-of-range int or an invalid regex, each with
|
||||
the message the two front ends print with file and line. `LintContext`
|
||||
carries `&RuleOptions`; a rule reads `ctx.option_str(NAME, "pattern")`
|
||||
etc. with the spec's default as the fallback, so a rule never sees
|
||||
"unset". (b) `lucisv_core::config`: `[lint.<rule>]` tables accepted —
|
||||
`key = value` for bool/int/string, `key = ["a", "b"]` for lists —
|
||||
stored raw in `FileConfig::lint_options: Vec<(rule, key, raw, line)>`
|
||||
(the core crate does not know the rules); the CLI resolves them
|
||||
against the registry per file the way `[lint] select` names are
|
||||
checked, failing the run with file:line on the first bad entry. (c)
|
||||
Editor: `lucisv.lint.options` (object; `{"<rule>": {"<key>": value}}`,
|
||||
`additionalProperties`), parsed in `settings.rs`, validated the same
|
||||
way — a bad entry is a `window/logMessage` warning and is ignored, so
|
||||
one typo cannot switch the linter off; republish on change. (d)
|
||||
Precedence: editor options over `lucisv.toml` options over the spec
|
||||
default, key by key (the same ladder `lucisv.lineLength` uses — cite
|
||||
`format::settings_for`). (e) `--rules-doc` lists each rule's options
|
||||
with kind, default and doc; the VS Code generator emits nothing per
|
||||
option (the object setting covers them) but its description names the
|
||||
options each rule takes. (f) Pins: parse/validate table tests; a
|
||||
`lucisv.toml` with `[lint.line-length] length = 120` changes the
|
||||
verdict; the editor object does the same over the wire; a bad key
|
||||
fails the CLI naming file:line and only logs in the editor.
|
||||
|
||||
**34.1 Options on the existing naming rules** (so the family is
|
||||
consistent before the new members arrive): `enum-name-style`,
|
||||
`struct-union-name-style`, `module-name-style`, `parameter-name-style`
|
||||
gain the option Verible gives them (`style_regex`; `parameter-name-
|
||||
style` gets `localparam_style`/`parameter_style` with Verible's
|
||||
`CamelCase|ALL_CAPS` vocabulary plus the `_regex` overrides); defaults
|
||||
reproduce today's behaviour exactly (pin: the corpus and opentitan
|
||||
finding lists are byte-identical with no options set).
|
||||
|
||||
**34.2 New Style rules** (Verible name; default there → here; options):
|
||||
- `line-length` (on; `length`, default = the formatter's configured
|
||||
`line-length`, else 100) — a token-aware check that ignores a line
|
||||
that is one unbreakable token (a long string or macro invocation),
|
||||
as Verible does.
|
||||
- `posix-eof` (on; safe fix appends the newline).
|
||||
- `forbid-consecutive-null-statements` (on; safe fix) — `;;` at
|
||||
statement level, the statement twin of `empty-item`.
|
||||
- `generate-label` (on) and `generate-label-prefix` (on; `prefix`
|
||||
list, default `g_`/`gen_`).
|
||||
- `package-filename` (on; `allow-dash-for-underscore`, same as
|
||||
`module-filename`).
|
||||
- `one-module-per-file` (off).
|
||||
- `signal-name-style` (off; `style_regex`, default `[a-z_0-9]+`).
|
||||
- `interface-name-style` (on; `style_regex`, default `[a-z_0-9]+(_if)`).
|
||||
- `macro-name-style` (on; `style_regex`, default `[A-Z_0-9]+`; the
|
||||
macro's own name from the `` `define`` table).
|
||||
- `constraint-name-style` (on; `pattern`, default `([a-z0-9]+_)+c`).
|
||||
- `parameter-type-name-style` (off; lower_snake + `_t`).
|
||||
- `port-name-suffix` (off; `_i`/`_o`/`_io`/`_ni`/`_no`/`_nio` per
|
||||
Verible; option `suffixes` list).
|
||||
- `banned-declared-name-patterns` (off; `patterns` list of regexes).
|
||||
- `typedef-enums` (on) and `typedef-structs-unions` (on;
|
||||
`allow_anonymous_nested`).
|
||||
- `always-comb` (on; **unsafe** fix rewriting `always @*`/`@(*)` to
|
||||
`always_comb` — the two are not identical at time zero, so the fix is
|
||||
offered but not applied by default).
|
||||
- `explicit-begin` (off; the eleven `*_enable` bool options Verible
|
||||
has; safe fix wraps the body in `begin`/`end`).
|
||||
Each: its own file, true positives and near-misses, a `.lint` case,
|
||||
corpus + opentitan counts with ten findings read and classified;
|
||||
opentitan is Verible-clean for its `dvsim` filesets, so a
|
||||
Verible-default rule that fires inside them needs an explanation.
|
||||
|
||||
**34.3 Docs and toggles.** The VS Code generator regenerates the 18 new
|
||||
`lucisv.lint.rules.*` entries (the drift test enforces it); README.md
|
||||
"Linting" gains the options section and the rows; `editors/vscode/
|
||||
README.md` documents `lucisv.lint.options`; the docs-site rules page
|
||||
gains the sections; CHANGELOG untouched (the lead writes it).
|
||||
Remaining Verible rules — `module-begin-block`, `legacy-generate-
|
||||
region`, `legacy-genvar-declaration`, `v2001-generate-begin`,
|
||||
`explicit-function-lifetime`/`explicit-task-lifetime`,
|
||||
`positive-meaning-parameter-name`, `suggest-parentheses`,
|
||||
`forbid-consecutive-null-statements`, `unpacked-dimensions-range-
|
||||
ordering`, `uvm-macro-semicolon`, `create-object-name-match`,
|
||||
`numeric-format-string-style`, `macro-string-concatenation`,
|
||||
`disable-statement`, `forbidden-macro`/`forbidden-symbol` (list
|
||||
options). Options: `[lint.<rule>]` tables in `lucisv.toml` (today
|
||||
rejected by name — the parser exists) and `lucisv.lint.options.<rule>`
|
||||
in the editor, validated against a per-rule option schema declared by
|
||||
the rule (`Rule::options() -> &[OptionSpec]`), shown in `--rules-doc`.
|
||||
Detailed plan to be written when §33 lands.
|
||||
`unpacked-dimensions-range-ordering`, `uvm-macro-semicolon`,
|
||||
`create-object-name-match`, `numeric-format-string-style`,
|
||||
`macro-string-concatenation`, `disable-statement`, `forbidden-macro`/
|
||||
`forbidden-symbol`, `endif-comment`, `forbid-line-continuations`,
|
||||
`dff-name-style`, `proper-parameter-declaration` — are §35, wave 3.
|
||||
|
||||
Files: crates/vlog_linter/src/{registry.rs (OptionSpec, options()),
|
||||
options.rs (new: OptionKind/OptionValue/RuleOptions), context.rs,
|
||||
rule_docs.rs, vscode.rs, lib.rs, rules/<new>.rs, rules/<naming>.rs}
|
||||
+ tests/cases/*.lint, crates/lucisv_core/src/config.rs (+ tests),
|
||||
crates/lucisv/src/{lint.rs, args.rs?} + tests, crates/lucisv_server/
|
||||
src/{settings.rs, lint.rs} + tests, editors/vscode/{package.json,
|
||||
README.md}, README.md "Linting", docs/site/.../reference/rules.md,
|
||||
docs/features/linter-expansion-2/README.md (new), TODO §34. Worktree
|
||||
`lint-2`; disjoint from §32 (parser) so the two may run in parallel.
|
||||
Every suite and sweep under `tools/guard.sh`.
|
||||
- [ ] 34.0 options end to end (spec, validation, toml table, editor
|
||||
object, precedence, --rules-doc); pins
|
||||
- [ ] 34.1 options on the four existing naming rules; defaults
|
||||
byte-identical
|
||||
- [ ] 34.2 the eighteen Style rules, each with tests, counts and ten
|
||||
classified findings
|
||||
- [ ] 34.3 docs + regenerated toggles
|
||||
- [ ] Gates (guarded): fmt/clippy/`cargo test --workspace`; corpus
|
||||
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
|
||||
|
||||
+82
-12
@@ -50,6 +50,11 @@ pub struct Plan {
|
||||
/// a rule asks about one name at a time and never about a file.
|
||||
pub struct Census {
|
||||
files: HashMap<String, u32>,
|
||||
/// Module or interface name → what it declares, `None` for a unit the run
|
||||
/// cannot answer for: a header carrying a compiler directive, or two
|
||||
/// declarations that disagree. Empty when no enabled rule asked for it —
|
||||
/// building it costs a parse of every file in the run.
|
||||
interfaces: HashMap<String, Option<vlog_linter::ModuleInterface>>,
|
||||
}
|
||||
|
||||
impl Census {
|
||||
@@ -58,27 +63,61 @@ impl Census {
|
||||
/// A file that cannot be read or does not lex contributes nothing, which
|
||||
/// is the same all-or-nothing rule the rest of the run gives it: the
|
||||
/// file's own check reports the error.
|
||||
fn of(jobs: &[Job]) -> Census {
|
||||
let per_file: Vec<Vec<String>> = jobs
|
||||
///
|
||||
/// `interfaces` says whether the run also needs each unit's ports and
|
||||
/// parameters (`unknown-port`, `unknown-parameter`). It costs a **parse**
|
||||
/// of every file on top of the lex the word census already pays for, so
|
||||
/// it is built only when some enabled rule asks — measured on opentitan
|
||||
/// `hw/` in `docs/features/linter-expansion-1/README.md`.
|
||||
fn of(jobs: &[Job], interfaces: bool) -> Census {
|
||||
type PerFile = (Vec<String>, Vec<(String, Option<vlog_linter::ModuleInterface>)>);
|
||||
let per_file: Vec<PerFile> = jobs
|
||||
.par_iter()
|
||||
.map(|job| match std::fs::read_to_string(&job.path) {
|
||||
Ok(src) => words::harvest_text(&src),
|
||||
Err(_) => Vec::new(),
|
||||
.map(|job| {
|
||||
let Ok(src) = std::fs::read_to_string(&job.path) else {
|
||||
return (Vec::new(), Vec::new());
|
||||
};
|
||||
if !interfaces {
|
||||
return (words::harvest_text(&src), Vec::new());
|
||||
}
|
||||
// One lex for both halves: the parse is what the interface
|
||||
// table needs, and its tokens are the word census's.
|
||||
let parsed = ParsedSource::parse(&src);
|
||||
(words::harvest(parsed.tokens()), vlog_linter::module_interfaces(parsed.file()))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut files: HashMap<String, u32> = HashMap::new();
|
||||
for words in per_file {
|
||||
let mut units: HashMap<String, Option<vlog_linter::ModuleInterface>> = HashMap::new();
|
||||
for (words, declared) in per_file {
|
||||
for word in words {
|
||||
*files.entry(word).or_default() += 1;
|
||||
}
|
||||
for (name, interface) in declared {
|
||||
// Two declarations of one name answer only when they agree;
|
||||
// anything else is a question the run cannot settle.
|
||||
units
|
||||
.entry(name)
|
||||
.and_modify(|held| {
|
||||
if *held != interface {
|
||||
*held = None;
|
||||
}
|
||||
})
|
||||
.or_insert(interface);
|
||||
}
|
||||
}
|
||||
Census { files }
|
||||
Census { files, interfaces: units }
|
||||
}
|
||||
|
||||
/// How many files in the run write `name` down.
|
||||
fn count(&self, name: &str) -> u32 {
|
||||
self.files.get(name).copied().unwrap_or(0)
|
||||
}
|
||||
|
||||
/// What the run says `name` declares, or `None` when it cannot say.
|
||||
fn interface(&self, name: &str) -> Option<vlog_linter::ModuleInterface> {
|
||||
self.interfaces.get(name)?.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// One file's view of the census: everything the project says, minus what
|
||||
@@ -96,6 +135,13 @@ impl MentionOracle for Elsewhere<'_> {
|
||||
let mine = u32::from(self.own.binary_search_by(|w| w.as_str().cmp(name)).is_ok());
|
||||
self.census.count(name) > mine
|
||||
}
|
||||
|
||||
/// The run's interface table, which covers **every** file including this
|
||||
/// one: a module is instantiated as often in the file that declares it as
|
||||
/// anywhere else, and there is nothing to subtract here.
|
||||
fn module_interface(&self, name: &str) -> Option<vlog_linter::ModuleInterface> {
|
||||
self.census.interface(name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the run: the rules for each file, and whether a census is owed.
|
||||
@@ -120,10 +166,25 @@ pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Res
|
||||
jobs.push(Job { path, config, rules });
|
||||
}
|
||||
let wanted = jobs.iter().any(|job| job.rules.iter().any(|rule| rule.needs_workspace()));
|
||||
let census = (workspace && wanted).then(|| Census::of(&jobs));
|
||||
let interfaces = jobs.iter().any(|job| job.rules.iter().any(|rule| reads_interfaces(*rule)));
|
||||
let census = (workspace && wanted).then(|| Census::of(&jobs, workspace && interfaces));
|
||||
Ok(Plan { jobs, census })
|
||||
}
|
||||
|
||||
/// Whether this rule reads the census's **interface** half, which costs a
|
||||
/// parse of every file in the run rather than a lex.
|
||||
///
|
||||
/// By name, because the alternative is a fourth boolean on the `Rule` trait
|
||||
/// for two rules: `Rule::needs_workspace` already says "this rule asks the
|
||||
/// project something", and which *question* it asks is between the rule and
|
||||
/// the oracle. A name that is not in the registry cannot reach here — the
|
||||
/// rules are `&'static dyn Rule` values from that registry — and a rule added
|
||||
/// to the pair without being added here answers `None` and goes quiet, which
|
||||
/// is the safe direction.
|
||||
fn reads_interfaces(rule: &'static dyn Rule) -> bool {
|
||||
matches!(rule.name(), "unknown-port" | "unknown-parameter")
|
||||
}
|
||||
|
||||
/// The command line's list when it said anything, else the config file's.
|
||||
fn pick<'a>(cli: &'a [String], config: Option<&'a [String]>) -> &'a [String] {
|
||||
if cli.is_empty() {
|
||||
@@ -348,15 +409,23 @@ fn finish(opts: &Options, reports: Vec<Report>) -> ExitCode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Verible's diagnostic line: `FILE:LINE:COL: message [rule-name]`.
|
||||
/// Verible's diagnostic line with the severity word in front of the message:
|
||||
/// `FILE:LINE:COL: error|warning|style: message [rule-name]`.
|
||||
///
|
||||
/// The word sits where a compiler puts it, so the line greps and reads the way
|
||||
/// every other tool's does, and `grep ': error:'` is the whole of "show me
|
||||
/// what would not compile".
|
||||
fn print_text(reports: &[Report]) {
|
||||
let mut out = String::new();
|
||||
for report in reports {
|
||||
for violation in &report.violations {
|
||||
let (line, col) = position(report, violation);
|
||||
out.push_str(&format!(
|
||||
"{}:{line}:{col}: {} [{}]\n",
|
||||
report.path, violation.message, violation.rule
|
||||
"{}:{line}:{col}: {}: {} [{}]\n",
|
||||
report.path,
|
||||
violation.severity.as_str(),
|
||||
violation.message,
|
||||
violation.rule
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -372,12 +441,13 @@ fn print_json(reports: &[Report]) {
|
||||
let (line, col) = position(report, violation);
|
||||
let (end_line, end_col) = end_position(report, violation);
|
||||
items.push(format!(
|
||||
"{{\"filename\":{},\"rule\":{},\"message\":{},\
|
||||
"{{\"filename\":{},\"rule\":{},\"severity\":{},\"message\":{},\
|
||||
\"location\":{{\"line\":{line},\"column\":{col}}},\
|
||||
\"end_location\":{{\"line\":{end_line},\"column\":{end_col}}},\
|
||||
\"range\":{{\"start\":{},\"end\":{}}},\"fix\":{}}}",
|
||||
quote(&report.path),
|
||||
quote(violation.rule),
|
||||
quote(violation.severity.as_str()),
|
||||
quote(&violation.message),
|
||||
violation.span.start,
|
||||
violation.span.end,
|
||||
|
||||
@@ -753,7 +753,9 @@ fn check_reports_violations_and_exits_1() {
|
||||
let out = run(&["check", &path]);
|
||||
assert_eq!(code(&out), 1, "violations must exit 1: {}", stderr(&out));
|
||||
let text = stdout(&out);
|
||||
assert!(text.contains(&format!("{path}:2:1: tab character")), "{text}");
|
||||
// `FILE:LINE:COL: severity: message [rule]` — the severity word is part
|
||||
// of the line since §33.0, and both of these are style findings.
|
||||
assert!(text.contains(&format!("{path}:2:1: style: tab character")), "{text}");
|
||||
assert!(text.contains("[no-tabs]"), "{text}");
|
||||
assert!(text.contains("[module-filename]"), "{text}");
|
||||
assert!(stderr(&out).contains("found 2 violations"), "{}", stderr(&out));
|
||||
@@ -797,6 +799,7 @@ fn check_json_is_one_array_with_positions_and_fixes() {
|
||||
assert!(text.starts_with('['), "{text}");
|
||||
assert!(text.trim_end().ends_with(']'), "{text}");
|
||||
assert_eq!(text.matches("\"rule\":\"no-tabs\"").count(), 1, "{text}");
|
||||
assert!(text.contains("\"severity\":\"style\""), "{text}");
|
||||
assert!(text.contains("\"location\":{\"line\":2,\"column\":1}"), "{text}");
|
||||
assert!(text.contains("\"applicability\":\"safe\""), "{text}");
|
||||
assert!(text.contains("\"content\":\" \""), "{text}");
|
||||
@@ -895,6 +898,30 @@ fn check_select_and_ignore_pick_the_rule_set() {
|
||||
assert!(stderr(&out).contains("unknown rule"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
/// A severity word stands for its whole class wherever a rule name fits —
|
||||
/// §33.0's headline for the command line.
|
||||
#[test]
|
||||
fn check_select_and_ignore_accept_a_severity_word() {
|
||||
let dir = TempDir::new("check-severity");
|
||||
// `reg` is an error-class finding, the tab and the name are style ones.
|
||||
let path = dir.write("bar.sv", "module foo;\n\treg a;\nendmodule\n");
|
||||
|
||||
let out = run(&["check", "--select", "error", &path]);
|
||||
assert_eq!(code(&out), 1, "{}", stdout(&out));
|
||||
let text = stdout(&out);
|
||||
assert_eq!(text.lines().count(), 1, "{text}");
|
||||
assert!(text.contains(": error: "), "{text}");
|
||||
assert!(text.contains("[wire-reg-mixup]"), "{text}");
|
||||
|
||||
let out = run(&["check", "--ignore", "style", &path]);
|
||||
assert_eq!(stdout(&out).lines().count(), 1, "{}", stdout(&out));
|
||||
assert!(stdout(&out).contains("[wire-reg-mixup]"), "{}", stdout(&out));
|
||||
|
||||
// Ignoring every class leaves nothing to report.
|
||||
let out = run(&["check", "--ignore", "error,warning,style", &path]);
|
||||
assert_eq!(code(&out), 0, "{}", stdout(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_honors_inline_waivers_and_reports_dead_ones() {
|
||||
let dir = TempDir::new("check-waive");
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -135,11 +135,12 @@ mod tests {
|
||||
#[test]
|
||||
fn one_list_carries_both_sources() {
|
||||
// A file that parses cleanly and violates a lint rule: the publish is
|
||||
// one list, and the lint finding is in it as a warning.
|
||||
// one list, and the lint finding is in it at its rule's own severity
|
||||
// — `no-tabs` is a style rule, so INFORMATION (§33.0).
|
||||
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
|
||||
let published = all(ws.document(&uri).expect("open"));
|
||||
assert_eq!(published.len(), 1);
|
||||
assert_eq!(published[0].severity, Some(DiagnosticSeverity::WARNING));
|
||||
assert_eq!(published[0].severity, Some(DiagnosticSeverity::INFORMATION));
|
||||
assert_eq!(published[0].code, Some(lsp_types::NumberOrString::String("no-tabs".into())));
|
||||
}
|
||||
|
||||
@@ -149,12 +150,43 @@ mod tests {
|
||||
let published = all(ws.document(&uri).expect("open"));
|
||||
let severities: Vec<_> = published.iter().map(|d| d.severity).collect();
|
||||
assert!(severities.contains(&Some(DiagnosticSeverity::ERROR)), "{published:#?}");
|
||||
assert!(severities.contains(&Some(DiagnosticSeverity::WARNING)), "{published:#?}");
|
||||
assert!(severities.contains(&Some(DiagnosticSeverity::INFORMATION)), "{published:#?}");
|
||||
assert!(published.iter().all(|d| d.source.as_deref() == Some("lucisv")));
|
||||
// Errors first: a parse error is what the user must fix.
|
||||
assert_eq!(published[0].severity, Some(DiagnosticSeverity::ERROR));
|
||||
}
|
||||
|
||||
/// The user-visible contract of header recovery (TODO §32), pinned where
|
||||
/// the user meets it: a typo in a port list costs **one** diagnostic, and
|
||||
/// the module around it survives whole — its name, the ports typed before
|
||||
/// and after the typo, and its body all still in the outline.
|
||||
///
|
||||
/// Before this round the same buffer published two errors (the header, and
|
||||
/// the orphaned `endmodule`), the body re-parsed as file-scope items, and
|
||||
/// the outline had no module in it at all.
|
||||
#[test]
|
||||
fn a_broken_port_list_publishes_one_error_and_keeps_its_module() {
|
||||
let (ws, uri) = doc_of("module m (input a, , input b);\n wire ok;\nendmodule\n");
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let diags = diagnostics(doc);
|
||||
assert_eq!(diags.len(), 1, "{diags:#?}");
|
||||
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::ERROR));
|
||||
assert_eq!(diags[0].range.start.line, 0, "the header's own line");
|
||||
|
||||
// The missing-closer pass explains a *parse* failure; there is no
|
||||
// unclosed block here, so it must add nothing.
|
||||
assert!(crate::pairs::missing_end_diagnostics(doc).is_empty());
|
||||
|
||||
let symbols = crate::symbols::document_symbols(doc);
|
||||
assert_eq!(symbols.len(), 1, "the module is still in the outline");
|
||||
assert_eq!(symbols[0].name, "m");
|
||||
let children = symbols[0].children.as_ref().expect("module contents");
|
||||
let names: Vec<&str> = children.iter().map(|c| c.name.as_str()).collect();
|
||||
assert!(names.contains(&"a"), "the port before the typo: {names:?}");
|
||||
assert!(names.contains(&"b"), "the port after it: {names:?}");
|
||||
assert!(names.contains(&"ok"), "the body: {names:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lex_error_gets_a_visible_range() {
|
||||
// The lexer gives up at end of file, which a trailing newline makes
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -11,15 +11,19 @@
|
||||
//! `docs/features/semantic-lints-on/README.md` and
|
||||
//! `docs/features/server-lint/README.md`.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString};
|
||||
use vlog_formatter::fence::{self, Region};
|
||||
use vlog_linter::{
|
||||
default_rules, lint, workspace_rules, LintContext, MentionOracle, Rule, Violation,
|
||||
default_rules, lint, workspace_rules, LintContext, MentionOracle, ModuleInterface, Rule,
|
||||
Severity, Violation,
|
||||
};
|
||||
use vlog_semantic::{FileId, WorkspaceIndex};
|
||||
use vlog_semantic::{FileId, SymbolKind, WorkspaceIndex};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::diagnostics::SOURCE;
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::state::{Document, Workspace};
|
||||
|
||||
/// What one lint pass runs: which rules, and what it may ask about the files
|
||||
@@ -52,12 +56,7 @@ impl<'a> LintRun<'a> {
|
||||
let index = ws.index();
|
||||
let own = doc.path.as_deref().and_then(|path| index.file_id(path));
|
||||
let workspace = index.files().len() > usize::from(own.is_some());
|
||||
let client = ws.client_settings();
|
||||
// Every name in the settings was checked against the registry when the
|
||||
// settings were parsed, so this cannot fail; if it somehow does, the
|
||||
// defaults are the answer a dropped setting always gets here.
|
||||
let rules = vlog_linter::select_rules(&client.lint_select, &client.lint_ignore, workspace)
|
||||
.unwrap_or_else(|_| if workspace { workspace_rules() } else { default_rules() });
|
||||
let rules = enabled_rules(ws.client_settings(), workspace);
|
||||
let oracle = workspace.then_some(IndexMentions { index, own });
|
||||
LintRun { rules, oracle }
|
||||
}
|
||||
@@ -72,6 +71,63 @@ impl<'a> LintRun<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which rules a buffer is linted with, given what the editor's settings say.
|
||||
///
|
||||
/// **The one ladder**, top rung last — every rung may undo the one above it:
|
||||
///
|
||||
/// 1. the base set is what the rules themselves declare: `default_on`, plus
|
||||
/// the `needs_workspace` rules when `has_oracle`;
|
||||
/// 2. a non-empty `lucisv.lint.select` **replaces** that base set, exactly as
|
||||
/// `--select` replaces it on the command line;
|
||||
/// 3. a `lucisv.lint.severity.<class>` switched off **removes** every rule of
|
||||
/// that class;
|
||||
/// 4. a `lucisv.lint.rules.<name>` set to `on` or `off` sets or clears that
|
||||
/// one rule — the per-rule word beats the class word, which is what makes
|
||||
/// "all style off except `no-tabs`" expressible;
|
||||
/// 5. `lucisv.lint.ignore` **removes** — the off switch of last resort, the
|
||||
/// one a user reaches for when nothing else worked.
|
||||
///
|
||||
/// Rungs 2 and 5 accept a severity word wherever a rule name fits.
|
||||
pub fn enabled_rules(settings: &ClientSettings, has_oracle: bool) -> Vec<&'static dyn Rule> {
|
||||
let base = if settings.lint_select.is_empty() {
|
||||
if has_oracle {
|
||||
workspace_rules()
|
||||
} else {
|
||||
default_rules()
|
||||
}
|
||||
} else {
|
||||
named(&settings.lint_select)
|
||||
};
|
||||
let mut on: BTreeSet<&'static str> = base.iter().map(|rule| rule.name()).collect();
|
||||
|
||||
for (severity, class_on) in &settings.lint_severity {
|
||||
if !class_on {
|
||||
on.retain(|name| {
|
||||
vlog_linter::rule_by_name(name).is_some_and(|rule| rule.severity() != *severity)
|
||||
});
|
||||
}
|
||||
}
|
||||
for (name, wanted) in &settings.lint_rules {
|
||||
let Some(rule) = vlog_linter::rule_by_name(name) else { continue };
|
||||
if *wanted {
|
||||
on.insert(rule.name());
|
||||
} else {
|
||||
on.remove(rule.name());
|
||||
}
|
||||
}
|
||||
for rule in named(&settings.lint_ignore) {
|
||||
on.remove(rule.name());
|
||||
}
|
||||
vlog_linter::all_rules().into_iter().filter(|rule| on.contains(rule.name())).collect()
|
||||
}
|
||||
|
||||
/// Every rule a list of `--select`-style words names, unknown words skipped —
|
||||
/// they were already dropped when the settings were parsed, and a name that
|
||||
/// survived that filter always resolves.
|
||||
fn named(words: &[String]) -> Vec<&'static dyn Rule> {
|
||||
words.iter().filter_map(|word| vlog_linter::rules_named(word)).flatten().collect()
|
||||
}
|
||||
|
||||
/// The workspace index, asked the one question a lint rule may ask about other
|
||||
/// files.
|
||||
///
|
||||
@@ -97,6 +153,32 @@ impl MentionOracle for IndexMentions<'_> {
|
||||
fn mentioned_elsewhere(&self, name: &str) -> bool {
|
||||
self.index.mentioned_outside(name, self.own)
|
||||
}
|
||||
|
||||
/// The ports and overridable parameters of an indexed module or interface,
|
||||
/// read off the index's member table — the very table a `.port` completion
|
||||
/// list is offered from, so a connection lucisv would have completed is
|
||||
/// never one it then calls unknown.
|
||||
///
|
||||
/// `None` for a unit the index does not hold, and for one it holds **more
|
||||
/// than once**: two modules of a name are two different headers, and
|
||||
/// answering with either would make an Error-class rule guess. A
|
||||
/// `localparam` is left out, because it is not overridable.
|
||||
fn module_interface(&self, name: &str) -> Option<ModuleInterface> {
|
||||
let units = self.index.units(name);
|
||||
let [unit] = units else { return None };
|
||||
if !unit.kind.is_instantiable() {
|
||||
return None;
|
||||
}
|
||||
let mut interface = ModuleInterface::default();
|
||||
for (member, defs) in self.index.members_of(name) {
|
||||
match defs.first().map(|def| def.kind) {
|
||||
Some(SymbolKind::Port) => interface.ports.push(member.to_string()),
|
||||
Some(SymbolKind::Param) => interface.parameters.push(member.to_string()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Some(interface)
|
||||
}
|
||||
}
|
||||
|
||||
/// The document's own parse products, lent to the linter — "one parse, two
|
||||
@@ -175,14 +257,13 @@ pub fn diagnostics_in(doc: &Document, run: &LintRun) -> Vec<Diagnostic> {
|
||||
|
||||
/// The diagnostic a violation becomes.
|
||||
///
|
||||
/// **Warning**, never Error: a lint finding is an opinion about style, and a
|
||||
/// parse error is the compiler refusing. The `code` is the rule's stable name,
|
||||
/// which is what a user needs to write a waiver or an `--ignore`, and what a
|
||||
/// code action matches on.
|
||||
/// The editor's severity is the rule's own class ([`severity_of`]). The `code`
|
||||
/// is the rule's stable name, which is what a user needs to write a waiver or
|
||||
/// an `--ignore`, and what a code action matches on.
|
||||
pub fn diagnostic(positions: &Positions<'_>, violation: &Violation) -> Diagnostic {
|
||||
Diagnostic {
|
||||
range: positions.diagnostic_range(violation.span),
|
||||
severity: Some(DiagnosticSeverity::WARNING),
|
||||
severity: Some(severity_of(violation.severity)),
|
||||
code: Some(NumberOrString::String(violation.rule.to_string())),
|
||||
source: Some(SOURCE.to_string()),
|
||||
message: violation.message.clone(),
|
||||
@@ -190,6 +271,21 @@ pub fn diagnostic(positions: &Positions<'_>, violation: &Violation) -> Diagnosti
|
||||
}
|
||||
}
|
||||
|
||||
/// How an editor is asked to paint one class.
|
||||
///
|
||||
/// `error` is the red squiggle a compiler error gets — a rule only claims it
|
||||
/// when the code would very likely not build, which is why the Error class is
|
||||
/// held to the silence-when-unsure rule. `style` deliberately stops short of
|
||||
/// `HINT`: a hint is invisible in most themes and would make the style rules
|
||||
/// look broken rather than quiet.
|
||||
fn severity_of(severity: Severity) -> DiagnosticSeverity {
|
||||
match severity {
|
||||
Severity::Error => DiagnosticSeverity::ERROR,
|
||||
Severity::Warning => DiagnosticSeverity::WARNING,
|
||||
Severity::Style => DiagnosticSeverity::INFORMATION,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -211,13 +307,35 @@ mod tests {
|
||||
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
|
||||
let diags = diagnostics(ws.document(&uri).expect("open"));
|
||||
assert_eq!(diags.len(), 1);
|
||||
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::WARNING));
|
||||
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::INFORMATION), "no-tabs is style");
|
||||
assert_eq!(diags[0].code, Some(NumberOrString::String("no-tabs".into())));
|
||||
assert_eq!(diags[0].source.as_deref(), Some("lucisv"));
|
||||
assert_eq!(diags[0].range.start.line, 1);
|
||||
assert!(diags[0].range.start < diags[0].range.end, "never zero-width");
|
||||
}
|
||||
|
||||
/// Each class paints its own squiggle: a compile-error rule reads as an
|
||||
/// error, a latch-shaped one as a warning, a naming one as information.
|
||||
#[test]
|
||||
fn a_diagnostics_severity_is_its_rules_class() {
|
||||
assert_eq!(severity_of(Severity::Error), DiagnosticSeverity::ERROR);
|
||||
assert_eq!(severity_of(Severity::Warning), DiagnosticSeverity::WARNING);
|
||||
assert_eq!(severity_of(Severity::Style), DiagnosticSeverity::INFORMATION);
|
||||
|
||||
// `reg` is error-class, the tab is style-class, and the two arrive in
|
||||
// one publish wearing different colours.
|
||||
let (ws, uri) = doc_of("module m;\n\treg a;\nendmodule\n");
|
||||
let diags = diagnostics(ws.document(&uri).expect("open"));
|
||||
let by_code = |name: &str| {
|
||||
diags
|
||||
.iter()
|
||||
.find(|d| d.code == Some(NumberOrString::String(name.into())))
|
||||
.and_then(|d| d.severity)
|
||||
};
|
||||
assert_eq!(by_code("wire-reg-mixup"), Some(DiagnosticSeverity::ERROR), "{diags:#?}");
|
||||
assert_eq!(by_code("no-tabs"), Some(DiagnosticSeverity::INFORMATION), "{diags:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_waived_violation_is_never_published() {
|
||||
let (ws, uri) = doc_of("module m;\n\twire a; // lucisv: waive no-tabs\nendmodule\n");
|
||||
@@ -368,6 +486,121 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// The ladder of §33.1, one row per rung, asserted against the rule set
|
||||
/// `enabled_rules` produces. Each row is (what the settings say, what must
|
||||
/// be true of the result).
|
||||
#[test]
|
||||
fn the_enabled_rules_ladder_is_the_documented_one() {
|
||||
let names = |settings: &ClientSettings, oracle: bool| -> Vec<&'static str> {
|
||||
enabled_rules(settings, oracle).into_iter().map(|rule| rule.name()).collect()
|
||||
};
|
||||
let with = |f: &dyn Fn(&mut ClientSettings)| {
|
||||
let mut settings = ClientSettings::default();
|
||||
f(&mut settings);
|
||||
settings
|
||||
};
|
||||
|
||||
// 1. the base set is the rules' own defaults, and a workspace adds
|
||||
// exactly the rules that asked for one.
|
||||
let base = ClientSettings::default();
|
||||
assert_eq!(
|
||||
names(&base, false),
|
||||
default_rules().iter().map(|r| r.name()).collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(
|
||||
names(&base, true),
|
||||
workspace_rules().iter().map(|r| r.name()).collect::<Vec<_>>()
|
||||
);
|
||||
|
||||
// 2. a non-empty `select` replaces the base set — including rules that
|
||||
// ship off, exactly as `--select` does.
|
||||
let selected = with(&|s| s.lint_select = vec!["module-name-style".to_string()]);
|
||||
assert_eq!(names(&selected, false), vec!["module-name-style"]);
|
||||
// ... and a severity word may stand there.
|
||||
let styled = with(&|s| s.lint_select = vec!["style".to_string()]);
|
||||
assert!(names(&styled, true)
|
||||
.iter()
|
||||
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
|
||||
== Severity::Style));
|
||||
|
||||
// 3. a class switched off removes every rule of that class.
|
||||
let no_style = with(&|s| {
|
||||
s.lint_severity.insert(Severity::Style, false);
|
||||
});
|
||||
assert!(!names(&no_style, true).contains(&"no-tabs"));
|
||||
assert!(names(&no_style, true).contains(&"unused-signal"), "other classes stay");
|
||||
|
||||
// 4. a per-rule toggle beats the class switch, in both directions.
|
||||
let style_off_but_tabs = with(&|s| {
|
||||
s.lint_severity.insert(Severity::Style, false);
|
||||
s.lint_rules.insert("no-tabs".to_string(), true);
|
||||
});
|
||||
assert!(names(&style_off_but_tabs, true).contains(&"no-tabs"));
|
||||
let one_off = with(&|s| {
|
||||
s.lint_rules.insert("no-tabs".to_string(), false);
|
||||
});
|
||||
assert!(!names(&one_off, true).contains(&"no-tabs"));
|
||||
// A toggle also adds a rule `select` did not name, and one that ships
|
||||
// off entirely.
|
||||
let added = with(&|s| {
|
||||
s.lint_select = vec!["no-tabs".to_string()];
|
||||
s.lint_rules.insert("module-name-style".to_string(), true);
|
||||
});
|
||||
assert_eq!(names(&added, false), vec!["module-name-style", "no-tabs"]);
|
||||
|
||||
// 5. `ignore` is the last word, over a toggle that says `on`.
|
||||
let ignored = with(&|s| {
|
||||
s.lint_rules.insert("no-tabs".to_string(), true);
|
||||
s.lint_ignore = vec!["no-tabs".to_string()];
|
||||
});
|
||||
assert!(!names(&ignored, true).contains(&"no-tabs"));
|
||||
// ... and it takes a severity word too.
|
||||
let quiet = with(&|s| s.lint_ignore = vec!["style".to_string()]);
|
||||
assert!(names(&quiet, true)
|
||||
.iter()
|
||||
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
|
||||
!= Severity::Style));
|
||||
|
||||
// The result is always in registry order, whatever order the settings
|
||||
// named things in — two runs must print findings the same way.
|
||||
let jumbled = with(&|s| {
|
||||
s.lint_select = vec!["no-trailing-whitespace".to_string(), "no-tabs".to_string()];
|
||||
});
|
||||
assert_eq!(names(&jumbled, false), vec!["no-tabs", "no-trailing-whitespace"]);
|
||||
}
|
||||
|
||||
/// The toggles reach the real published diagnostics, not just the rule
|
||||
/// list: a class switched off silences its squiggles.
|
||||
#[test]
|
||||
fn a_class_switch_changes_what_the_server_publishes() {
|
||||
let (mut ws, dir, uri) = two_file_project("classes");
|
||||
ws.set_document(uri.clone(), "module dut;\n\tlogic dead;\nendmodule\n".to_string());
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let mut both = codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc)));
|
||||
both.sort();
|
||||
assert_eq!(both, vec!["no-tabs", "unused-signal"], "premise");
|
||||
|
||||
let mut off = ClientSettings::default();
|
||||
off.lint_severity.insert(Severity::Style, false);
|
||||
ws.set_client_settings(off);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
assert_eq!(
|
||||
codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc))),
|
||||
vec!["unused-signal"],
|
||||
"the style class went quiet"
|
||||
);
|
||||
|
||||
let mut back = ClientSettings::default();
|
||||
back.lint_severity.insert(Severity::Style, false);
|
||||
back.lint_rules.insert("no-tabs".to_string(), true);
|
||||
ws.set_client_settings(back);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let mut with_tabs = codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc)));
|
||||
with_tabs.sort();
|
||||
assert_eq!(with_tabs, vec!["no-tabs", "unused-signal"], "the per-rule word wins");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// The off switch, over the settings door: `lucisv.lint.ignore` takes a
|
||||
/// rule out of the published set.
|
||||
#[test]
|
||||
|
||||
@@ -268,9 +268,13 @@ impl Server {
|
||||
|
||||
/// The rule selection in force, as a value two settings pushes can be
|
||||
/// compared by.
|
||||
fn lint_selection(&self) -> (Vec<String>, Vec<String>) {
|
||||
let client = self.workspace.client_settings();
|
||||
(client.lint_select.clone(), client.lint_ignore.clone())
|
||||
///
|
||||
/// All four lint settings, not just the two lists: since §33.1 a class
|
||||
/// switch (`lucisv.lint.severity.*`) and a per-rule toggle
|
||||
/// (`lucisv.lint.rules.*`) change which rules run too, and a change to one
|
||||
/// of them must republish exactly as a change to `select`/`ignore` does.
|
||||
fn lint_selection(&self) -> settings::LintSelection {
|
||||
settings::lint_selection(self.workspace.client_settings())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,9 +13,11 @@
|
||||
//! Not to be confused with `format::Settings`, which is what one formatting
|
||||
//! request resolved to after every rung of that ladder was applied.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use serde_json::Value;
|
||||
use vlog_linter::Severity;
|
||||
|
||||
/// Accepted `line-length`, and accepted `indent`.
|
||||
///
|
||||
@@ -174,6 +176,20 @@ pub struct ClientSettings {
|
||||
/// `lucisv.lint.ignore`: rules dropped from whatever `select` left. Same
|
||||
/// validation, same reason.
|
||||
pub lint_ignore: Vec<String>,
|
||||
/// `lucisv.lint.severity.error` / `.warning` / `.style`: the master switch
|
||||
/// of each class. Every class is present and `true` unless a client turned
|
||||
/// one off — see `lint::enabled_rules` for where it sits in the ladder.
|
||||
pub lint_severity: BTreeMap<Severity, bool>,
|
||||
/// `lucisv.lint.rules.<rule-name>`: the rules a client said something
|
||||
/// **explicit** about — `true` for `on`, `false` for `off`.
|
||||
///
|
||||
/// A rule left at `default` is *absent from this map*, and that is the
|
||||
/// whole reason the setting is a three-word enum rather than a boolean: a
|
||||
/// client sends the whole section, every key at its default, so "unset"
|
||||
/// and "set to the shipped value" would arrive identically and a per-rule
|
||||
/// toggle nobody touched would silently override `select` and the class
|
||||
/// switches.
|
||||
pub lint_rules: BTreeMap<String, bool>,
|
||||
}
|
||||
|
||||
/// The settings a client that said nothing is treated as having asked for.
|
||||
@@ -200,10 +216,35 @@ impl Default for ClientSettings {
|
||||
large_file_threshold: DEFAULT_LARGE_FILE_THRESHOLD,
|
||||
lint_select: Vec::new(),
|
||||
lint_ignore: Vec::new(),
|
||||
lint_severity: every_class_on(),
|
||||
lint_rules: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every severity class switched on — what a client that said nothing means.
|
||||
fn every_class_on() -> BTreeMap<Severity, bool> {
|
||||
Severity::ALL.into_iter().map(|severity| (severity, true)).collect()
|
||||
}
|
||||
|
||||
/// Everything about a settings value that decides **which rules run**: the two
|
||||
/// name lists, the class switches and the per-rule toggles.
|
||||
///
|
||||
/// Its only use is equality — the server compares it across a settings change
|
||||
/// to decide whether every open file must be published again.
|
||||
pub type LintSelection =
|
||||
(Vec<String>, Vec<String>, BTreeMap<Severity, bool>, BTreeMap<String, bool>);
|
||||
|
||||
/// The four lint settings of `settings`, as one comparable value.
|
||||
pub fn lint_selection(settings: &ClientSettings) -> LintSelection {
|
||||
(
|
||||
settings.lint_select.clone(),
|
||||
settings.lint_ignore.clone(),
|
||||
settings.lint_severity.clone(),
|
||||
settings.lint_rules.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Read the `lucisv` section out of a `workspace/didChangeConfiguration` payload.
|
||||
///
|
||||
/// **Nothing here trusts the client.** `package.json`'s JSON schema constrains
|
||||
@@ -274,17 +315,53 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
||||
.unwrap_or(DEFAULT_LARGE_FILE_THRESHOLD),
|
||||
lint_select: rules(lint.and_then(|l| l.get("select"))),
|
||||
lint_ignore: rules(lint.and_then(|l| l.get("ignore"))),
|
||||
// `lucisv.lint.severity.<class>` and `lucisv.lint.rules.<name>` nest
|
||||
// one level deeper again, for the same reason `index.*` does.
|
||||
lint_severity: severity_switches(lint.and_then(|l| l.get("severity"))),
|
||||
lint_rules: rule_toggles(lint.and_then(|l| l.get("rules"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The rule names in a settings array, dropping every one the registry does
|
||||
/// not know.
|
||||
/// The rule names in a settings array, dropping every one that names neither a
|
||||
/// rule nor a severity class.
|
||||
///
|
||||
/// Silence rather than an error, on this module's standing rule: a push is
|
||||
/// JSON on a socket, and a typo in one name must not cost the user every
|
||||
/// diagnostic in the file. A dropped name leaves the rule where it was.
|
||||
fn rules(value: Option<&Value>) -> Vec<String> {
|
||||
strings(value).into_iter().filter(|name| vlog_linter::rule_by_name(name).is_some()).collect()
|
||||
strings(value).into_iter().filter(|name| vlog_linter::rules_named(name).is_some()).collect()
|
||||
}
|
||||
|
||||
/// The three class master switches, each `true` unless a client turned it off.
|
||||
///
|
||||
/// A missing or wrong-typed switch leaves its class on: the safe direction for
|
||||
/// a switch that silences a whole family of diagnostics is the one that shows
|
||||
/// them, exactly as an unreadable size cap leaves the cap on.
|
||||
fn severity_switches(value: Option<&Value>) -> BTreeMap<Severity, bool> {
|
||||
Severity::ALL
|
||||
.into_iter()
|
||||
.map(|severity| {
|
||||
let on = flag(value.and_then(|v| v.get(severity.as_str()))).unwrap_or(true);
|
||||
(severity, on)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The rules a client said something explicit about: `on` and `off` only.
|
||||
///
|
||||
/// `default` — and any word that is neither, and any key that is not a rule —
|
||||
/// contributes nothing, which is what leaves the rule wherever the rest of the
|
||||
/// ladder put it. See [`ClientSettings::lint_rules`].
|
||||
fn rule_toggles(value: Option<&Value>) -> BTreeMap<String, bool> {
|
||||
let Some(Value::Object(map)) = value else { return BTreeMap::new() };
|
||||
map.iter()
|
||||
.filter(|(name, _)| vlog_linter::rule_by_name(name).is_some())
|
||||
.filter_map(|(name, choice)| match choice.as_str() {
|
||||
Some("on") => Some((name.clone(), true)),
|
||||
Some("off") => Some((name.clone(), false)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One of the two `lucisv.index.scope` words, or nothing. Matched exactly —
|
||||
@@ -623,6 +700,128 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// **The drift guard.** `editors/vscode/package.json` declares one switch
|
||||
/// per severity class and one per rule, generated by
|
||||
/// `vlog_linter::vscode_lint_settings`. This compares the two as JSON
|
||||
/// *values*, so formatting is free but a rule added without its toggle —
|
||||
/// or a summary, default or severity edited on one side only — fails here.
|
||||
///
|
||||
/// Regenerate with
|
||||
/// `cargo run -p vlog_linter --example vscode_lint_settings`.
|
||||
#[test]
|
||||
fn the_vscode_lint_toggles_match_the_registry() {
|
||||
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../editors/vscode/package.json");
|
||||
let text = std::fs::read_to_string(&path).expect("the extension manifest");
|
||||
let manifest: Value = serde_json::from_str(&text).expect("valid json");
|
||||
let properties = manifest["contributes"]["configuration"]["properties"]
|
||||
.as_object()
|
||||
.expect("a properties object");
|
||||
let declared: serde_json::Map<String, Value> = properties
|
||||
.iter()
|
||||
.filter(|(key, _)| {
|
||||
key.starts_with("lucisv.lint.severity.") || key.starts_with("lucisv.lint.rules.")
|
||||
})
|
||||
.map(|(key, value)| (key.clone(), value.clone()))
|
||||
.collect();
|
||||
|
||||
let generated: Value = serde_json::from_str(&vlog_linter::vscode_lint_settings())
|
||||
.expect("the generator emits valid json");
|
||||
let generated = generated.as_object().expect("an object");
|
||||
|
||||
let names = |map: &serde_json::Map<String, Value>| {
|
||||
let mut keys: Vec<String> = map.keys().cloned().collect();
|
||||
keys.sort();
|
||||
keys
|
||||
};
|
||||
assert_eq!(
|
||||
names(&declared),
|
||||
names(generated),
|
||||
"package.json and the rule registry disagree about which lint settings exist; \
|
||||
regenerate with `cargo run -p vlog_linter --example vscode_lint_settings`"
|
||||
);
|
||||
for (key, value) in generated {
|
||||
assert_eq!(declared.get(key), Some(value), "{key} drifted");
|
||||
}
|
||||
// And every rule really does have one, which is the promise the whole
|
||||
// generator exists to keep.
|
||||
for rule in vlog_linter::all_rules() {
|
||||
assert!(declared.contains_key(&vlog_linter::rule_setting(rule)), "{}", rule.name());
|
||||
}
|
||||
}
|
||||
|
||||
/// A default-everything payload — which is what a client sends for a user
|
||||
/// who has touched nothing — must say nothing about any rule.
|
||||
#[test]
|
||||
fn the_shipped_lint_toggles_are_no_opinion() {
|
||||
let mut rules = serde_json::Map::new();
|
||||
for rule in vlog_linter::all_rules() {
|
||||
rules.insert(rule.name().to_string(), json!("default"));
|
||||
}
|
||||
let found = settings(json!({"lucisv": {"lint": {
|
||||
"severity": {"error": true, "warning": true, "style": true},
|
||||
"rules": Value::Object(rules),
|
||||
}}}));
|
||||
assert_eq!(found, ClientSettings::default(), "every shipped value is silence");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_severity_switches_and_rule_toggles_are_read() {
|
||||
let found = settings(json!({"lucisv": {"lint": {
|
||||
"severity": {"style": false, "warning": "yes"},
|
||||
"rules": {"no-tabs": "on", "unused-signal": "off", "empty-item": "default",
|
||||
"no-such-rule": "on", "case-missing-default": 3},
|
||||
}}}));
|
||||
assert!(!found.lint_severity[&Severity::Style]);
|
||||
assert!(found.lint_severity[&Severity::Warning], "a wrong type leaves it on");
|
||||
assert!(found.lint_severity[&Severity::Error], "and so does absence");
|
||||
assert_eq!(
|
||||
found.lint_rules,
|
||||
[("no-tabs".to_string(), true), ("unused-signal".to_string(), false)]
|
||||
.into_iter()
|
||||
.collect::<BTreeMap<_, _>>(),
|
||||
"`default`, an unknown rule and a wrong-typed choice all say nothing"
|
||||
);
|
||||
// A `lint` that is not an object leaves every class on and nothing said.
|
||||
let junk = settings(json!({"lucisv": {"lint": 7}}));
|
||||
assert_eq!(junk.lint_severity, every_class_on());
|
||||
assert!(junk.lint_rules.is_empty());
|
||||
}
|
||||
|
||||
/// A severity word is a legal `select`/`ignore` entry since §33.0, so the
|
||||
/// validating filter must keep it.
|
||||
#[test]
|
||||
fn a_severity_word_survives_the_select_and_ignore_filter() {
|
||||
let found = settings(json!({"lucisv": {"lint": {
|
||||
"select": ["style", "no-tabs", "nope"],
|
||||
"ignore": ["warning"],
|
||||
}}}));
|
||||
assert_eq!(found.lint_select, vec!["style", "no-tabs"]);
|
||||
assert_eq!(found.lint_ignore, vec!["warning"]);
|
||||
}
|
||||
|
||||
/// What the server compares two settings pushes by, to decide whether the
|
||||
/// squiggles it already drew are still right.
|
||||
#[test]
|
||||
fn the_lint_selection_notices_every_setting_that_changes_the_rule_set() {
|
||||
let base = ClientSettings::default();
|
||||
let mut severity = base.clone();
|
||||
severity.lint_severity.insert(Severity::Style, false);
|
||||
let mut toggled = base.clone();
|
||||
toggled.lint_rules.insert("no-tabs".to_string(), false);
|
||||
let mut selected = base.clone();
|
||||
selected.lint_select = vec!["error".to_string()];
|
||||
let mut ignored = base.clone();
|
||||
ignored.lint_ignore = vec!["no-tabs".to_string()];
|
||||
for changed in [severity, toggled, selected, ignored] {
|
||||
assert_ne!(lint_selection(&base), lint_selection(&changed));
|
||||
}
|
||||
// A setting that does not change which rules run does not republish.
|
||||
let mut unrelated = base.clone();
|
||||
unrelated.indent = Some(4);
|
||||
assert_eq!(lint_selection(&base), lint_selection(&unrelated));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_vscode_payload_is_no_opinion_about_anything() {
|
||||
// Every setting at its `package.json` default: nulls and an empty
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
|
||||
@@ -455,7 +455,9 @@ fn lint_diagnostics_and_a_code_action_round_trip_over_the_wire() {
|
||||
assert!(codes.contains(&"no-tabs"), "{codes:?}");
|
||||
assert!(codes.contains(&"no-trailing-whitespace"), "{codes:?}");
|
||||
for diagnostic in diagnostics {
|
||||
assert_eq!(diagnostic["severity"], 2, "a lint finding is a warning");
|
||||
// Both rules here are style-class, which is LSP severity 3
|
||||
// (INFORMATION) since §33.0.
|
||||
assert_eq!(diagnostic["severity"], 3, "a style finding is information");
|
||||
assert_eq!(diagnostic["source"], "lucisv");
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
//! Prints the `lucisv.lint.severity.*` and `lucisv.lint.rules.*` settings for
|
||||
//! `editors/vscode/package.json`, generated from the rule registry.
|
||||
//!
|
||||
//! ```text
|
||||
//! cargo run -p vlog_linter --example vscode_lint_settings
|
||||
//! ```
|
||||
//!
|
||||
//! Paste the body of the printed object into that file's
|
||||
//! `contributes.configuration.properties`, replacing the block that is there.
|
||||
//! The drift test in `lucisv_server` (`settings::tests::
|
||||
//! the_vscode_lint_toggles_match_the_registry`) fails whenever the two
|
||||
//! disagree, so a rule cannot ship without its toggle.
|
||||
|
||||
fn main() {
|
||||
print!("{}", vlog_linter::vscode_lint_settings());
|
||||
}
|
||||
@@ -84,6 +84,16 @@ impl ParsedSource {
|
||||
&self.tokens
|
||||
}
|
||||
|
||||
/// The tolerant parse itself — public for the same reason [`tokens`] is:
|
||||
/// a caller that has already paid for the parse can read the tree for
|
||||
/// something else (`lucisv check` harvests its interface census off it)
|
||||
/// instead of parsing the same text twice.
|
||||
///
|
||||
/// [`tokens`]: ParsedSource::tokens
|
||||
pub fn file(&self) -> &SourceFile {
|
||||
&self.file
|
||||
}
|
||||
|
||||
/// A lint context borrowing this parse. `path` is the file the text came
|
||||
/// from, or `None` for a buffer (stdin) — rules that need a filename skip.
|
||||
pub fn context(&self, path: Option<PathBuf>) -> LintContext<'_> {
|
||||
@@ -125,6 +135,42 @@ enum Backing<'a> {
|
||||
pub trait MentionOracle: Sync {
|
||||
/// Whether any file **other than** the one being linted mentions `name`.
|
||||
fn mentioned_elsewhere(&self, name: &str) -> bool;
|
||||
|
||||
/// What the project says the module or interface `name` declares, or
|
||||
/// `None` when it cannot say — the unit is not in the project, or it is
|
||||
/// declared more than once and the declarations disagree.
|
||||
///
|
||||
/// The second question a rule may ask about other files, added by TODO
|
||||
/// §33.2 for `unknown-port` and `unknown-parameter`. It is deliberately
|
||||
/// still a *closed* question — the names a connection list may use, and
|
||||
/// nothing about them — and `None` is a first-class answer that every
|
||||
/// caller must treat as silence rather than as an empty list. A front end
|
||||
/// with no such table at all answers `None` to everything, which leaves
|
||||
/// those two rules quiet and every other rule exactly where it was.
|
||||
fn module_interface(&self, _name: &str) -> Option<ModuleInterface> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The names a module or interface declares that an instantiation may write.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct ModuleInterface {
|
||||
/// Port names, as written.
|
||||
pub ports: Vec<String>,
|
||||
/// Overridable parameter names, as written — a `localparam` is not one.
|
||||
pub parameters: Vec<String>,
|
||||
}
|
||||
|
||||
impl ModuleInterface {
|
||||
/// Whether the unit declares a port called `name`.
|
||||
pub fn has_port(&self, name: &str) -> bool {
|
||||
self.ports.iter().any(|port| port == name)
|
||||
}
|
||||
|
||||
/// Whether the unit declares an overridable parameter called `name`.
|
||||
pub fn has_parameter(&self, name: &str) -> bool {
|
||||
self.parameters.iter().any(|parameter| parameter == name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a context's symbol table comes from: lent by a caller that already
|
||||
@@ -134,6 +180,12 @@ pub trait MentionOracle: Sync {
|
||||
/// Lazy rather than eager because most rules are syntactic: a run with no
|
||||
/// semantic rule enabled — which is every default `lucisv check`, since all
|
||||
/// three semantic rules ship off — must not pay for an analysis nobody reads.
|
||||
// The `Lazy` variant is the table itself, held inline on purpose: it is one
|
||||
// per lint run, it is written exactly once, and boxing it would add an
|
||||
// allocation to the path that already avoided one by not analyzing at all.
|
||||
// `Semantics` grew past clippy's variant-size threshold when it gained its
|
||||
// `duplicates` table (§33.2); nothing about the trade changed with it.
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
enum SemanticsSlot<'a> {
|
||||
Lent(&'a Semantics),
|
||||
Lazy(OnceCell<Semantics>),
|
||||
@@ -156,6 +208,9 @@ pub struct LintContext<'a> {
|
||||
/// The signal table the semantic rules read, built once for all of them
|
||||
/// the first time one asks — and never for a run with none enabled.
|
||||
signals: OnceCell<Signals>,
|
||||
/// Whether the tolerant parse produced no `Error` leaf, answered once for
|
||||
/// the rules that read structure. See [`LintContext::parsed_cleanly`].
|
||||
clean: OnceCell<bool>,
|
||||
/// What the workspace says about a name, when the caller has a workspace.
|
||||
/// `None` is a run that cannot see other files — a single-file
|
||||
/// `lucisv check`, stdin, a unit test — and every rule that would consult
|
||||
@@ -202,6 +257,7 @@ impl<'a> LintContext<'a> {
|
||||
strings: Vec::new(),
|
||||
semantics: SemanticsSlot::Lazy(OnceCell::new()),
|
||||
signals: OnceCell::new(),
|
||||
clean: OnceCell::new(),
|
||||
oracle: None,
|
||||
};
|
||||
ctx.strings =
|
||||
@@ -245,6 +301,13 @@ impl<'a> LintContext<'a> {
|
||||
self.oracle.is_some_and(|oracle| oracle.mentioned_elsewhere(name))
|
||||
}
|
||||
|
||||
/// What the project says the unit `name` declares. `None` — no oracle, no
|
||||
/// such unit, or two that disagree — means the run cannot answer, and a
|
||||
/// rule that asked must then say nothing.
|
||||
pub fn module_interface(&self, name: &str) -> Option<ModuleInterface> {
|
||||
self.oracle?.module_interface(name)
|
||||
}
|
||||
|
||||
/// Whether this run can see other files at all.
|
||||
pub fn has_oracle(&self) -> bool {
|
||||
self.oracle.is_some()
|
||||
@@ -266,6 +329,32 @@ impl<'a> LintContext<'a> {
|
||||
self.signals.get_or_init(|| Signals::scan(self))
|
||||
}
|
||||
|
||||
/// Whether the whole file fit the grammar — no `Error` leaf anywhere in
|
||||
/// the tolerant parse.
|
||||
///
|
||||
/// The tolerant parse is what makes a text rule work in a half-written
|
||||
/// buffer, and most rules are right to ignore the difference. A rule that
|
||||
/// reads **structure** is not: error recovery unwinds out of the construct
|
||||
/// it failed in, so the declarations that followed are bound in whatever
|
||||
/// scope recovery landed in — a class method's locals end up at file
|
||||
/// scope, and every one of them looks like a redeclaration of the last
|
||||
/// method's. Measured on opentitan: `spi_device_scoreboard.sv` (454 parse
|
||||
/// errors, a macro-heavy UVM file) produced sixteen such phantoms, which
|
||||
/// is sixteen wrong accusations from one file. A rule that would rather be
|
||||
/// silent than wrong asks this first.
|
||||
pub fn parsed_cleanly(&self) -> bool {
|
||||
*self.clean.get_or_init(|| {
|
||||
let mut clean = true;
|
||||
crate::visit::walk_items(self.file(), &mut |item| {
|
||||
clean &= !matches!(item.kind, vlog_parser::ast::ItemKind::Error(_));
|
||||
});
|
||||
crate::visit::walk_all_stmts(self.file(), &mut |stmt| {
|
||||
clean &= !matches!(stmt.kind, vlog_parser::ast::StmtKind::Error(_));
|
||||
});
|
||||
clean
|
||||
})
|
||||
}
|
||||
|
||||
/// The source text being linted.
|
||||
pub fn source(&self) -> &str {
|
||||
match &self.backing {
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
//! Every declared type and every dimension in a file.
|
||||
//!
|
||||
//! A `DataType` is written in a dozen places — a port, a parameter, a
|
||||
//! declarator, a typedef's base, a struct member, a subroutine's return type
|
||||
//! and its arguments — and the rules that judge a *type* (the packed-dimension
|
||||
//! ordering, a negative array bound) care about all of them equally. Collecting
|
||||
//! them lives here rather than in `visit`, which is about the item and
|
||||
//! statement spines; keeping the two apart is what stops either file from
|
||||
//! becoming "everything a rule might want to walk".
|
||||
|
||||
use vlog_parser::ast::{
|
||||
DataType, Dim, EnumType, FunctionDecl, ItemKind, ListElem, SourceFile, StmtKind, StructType,
|
||||
TaskDecl, TfArg, TypeExtra, TypedefKind,
|
||||
};
|
||||
|
||||
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
|
||||
|
||||
/// Where a dimension was written. The two are different constructs with
|
||||
/// different conventions — `[N-1:0]` for a packed vector, `[N]` for an array —
|
||||
/// so a rule that judges one must not judge the other by accident.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Packing {
|
||||
/// Written before the declared name: a vector's width.
|
||||
Packed,
|
||||
/// Written after it: an array's extent.
|
||||
Unpacked,
|
||||
}
|
||||
|
||||
/// Calls `f` on every data type written in the file, an anonymous aggregate's
|
||||
/// members and base included.
|
||||
pub(crate) fn walk_data_types(file: &SourceFile, f: &mut dyn FnMut(&DataType)) {
|
||||
let mut visit = |ty: &DataType| descend(ty, f);
|
||||
walk_param_ports(file, &mut |port| visit(&port.ty));
|
||||
walk_items(file, &mut |item| match &item.kind {
|
||||
ItemKind::Module(module) => {
|
||||
if let vlog_parser::ast::PortList::Ansi(ports) = &module.ports {
|
||||
for port in ports.iter().filter_map(ListElem::ok) {
|
||||
visit(&port.ty);
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::Typedef(typedef) => typedef_types(&typedef.kind, &mut visit),
|
||||
ItemKind::ParamDecl(decl) => visit(&decl.ty),
|
||||
ItemKind::DataDecl(decl) => visit(&decl.ty),
|
||||
ItemKind::PortDecl(decl) => visit(&decl.ty),
|
||||
ItemKind::Function(decl) => function_types(decl, &mut visit),
|
||||
ItemKind::Task(decl) => task_types(decl, &mut visit),
|
||||
_ => {}
|
||||
});
|
||||
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
|
||||
StmtKind::VarDecl(decl) => visit(&decl.ty),
|
||||
StmtKind::ParamDecl(decl) => visit(&decl.ty),
|
||||
StmtKind::PortDecl(decl) => visit(&decl.ty),
|
||||
StmtKind::Typedef(typedef) => typedef_types(&typedef.kind, &mut visit),
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
|
||||
/// Calls `f` on every dimension in the file, saying which kind it is.
|
||||
pub(crate) fn walk_dims(file: &SourceFile, f: &mut dyn FnMut(Packing, &Dim)) {
|
||||
walk_data_types(file, &mut |ty| {
|
||||
for dim in &ty.packed {
|
||||
f(Packing::Packed, dim);
|
||||
}
|
||||
});
|
||||
walk_unpacked(file, f);
|
||||
}
|
||||
|
||||
/// The unpacked half: the `[…]` written *after* a declared name.
|
||||
fn walk_unpacked(file: &SourceFile, f: &mut dyn FnMut(Packing, &Dim)) {
|
||||
let mut unpacked = |dims: &[Dim]| {
|
||||
for dim in dims {
|
||||
f(Packing::Unpacked, dim);
|
||||
}
|
||||
};
|
||||
walk_param_ports(file, &mut |port| unpacked(&port.unpacked));
|
||||
walk_items(file, &mut |item| match &item.kind {
|
||||
ItemKind::Module(module) => {
|
||||
if let vlog_parser::ast::PortList::Ansi(ports) = &module.ports {
|
||||
for port in ports.iter().filter_map(ListElem::ok) {
|
||||
unpacked(&port.unpacked);
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::Typedef(typedef) => unpacked(&typedef.unpacked),
|
||||
ItemKind::ParamDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
|
||||
ItemKind::DataDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
|
||||
ItemKind::PortDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
|
||||
ItemKind::Function(decl) => arg_dims(&decl.args, &mut unpacked),
|
||||
ItemKind::Task(decl) => arg_dims(&decl.args, &mut unpacked),
|
||||
_ => {}
|
||||
});
|
||||
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
|
||||
StmtKind::VarDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
|
||||
StmtKind::ParamDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
|
||||
StmtKind::PortDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
|
||||
StmtKind::Typedef(typedef) => unpacked(&typedef.unpacked),
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
|
||||
fn declarator_dims(declarators: &[vlog_parser::ast::Declarator], unpacked: &mut dyn FnMut(&[Dim])) {
|
||||
for declarator in declarators {
|
||||
unpacked(&declarator.unpacked);
|
||||
}
|
||||
}
|
||||
|
||||
fn arg_dims(args: &[ListElem<TfArg>], unpacked: &mut dyn FnMut(&[Dim])) {
|
||||
for arg in args.iter().filter_map(ListElem::ok) {
|
||||
unpacked(&arg.unpacked);
|
||||
}
|
||||
}
|
||||
|
||||
fn typedef_types(kind: &TypedefKind, visit: &mut dyn FnMut(&DataType)) {
|
||||
match kind {
|
||||
TypedefKind::Alias(ty) => visit(ty),
|
||||
TypedefKind::Enum(enum_ty) => enum_types(enum_ty, visit),
|
||||
TypedefKind::Struct(struct_ty) => struct_types(struct_ty, visit),
|
||||
TypedefKind::ForwardClass => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn function_types(decl: &FunctionDecl, visit: &mut dyn FnMut(&DataType)) {
|
||||
if let Some(ret) = &decl.ret {
|
||||
visit(ret);
|
||||
}
|
||||
for arg in decl.args.iter().filter_map(ListElem::ok) {
|
||||
visit(&arg.ty);
|
||||
}
|
||||
}
|
||||
|
||||
fn task_types(decl: &TaskDecl, visit: &mut dyn FnMut(&DataType)) {
|
||||
for arg in decl.args.iter().filter_map(ListElem::ok) {
|
||||
visit(&arg.ty);
|
||||
}
|
||||
}
|
||||
|
||||
fn enum_types(enum_ty: &EnumType, visit: &mut dyn FnMut(&DataType)) {
|
||||
if let Some(base) = &enum_ty.base {
|
||||
visit(base);
|
||||
}
|
||||
}
|
||||
|
||||
fn struct_types(struct_ty: &StructType, visit: &mut dyn FnMut(&DataType)) {
|
||||
for member in &struct_ty.members {
|
||||
visit(&member.ty);
|
||||
}
|
||||
}
|
||||
|
||||
/// One type and whatever aggregate it *is*: an anonymous `enum`'s base and an
|
||||
/// anonymous `struct`'s members are types written inside this one.
|
||||
fn descend(ty: &DataType, f: &mut dyn FnMut(&DataType)) {
|
||||
f(ty);
|
||||
match ty.inline() {
|
||||
Some(TypeExtra::Enum(enum_ty)) => enum_types(enum_ty, &mut |inner| descend(inner, f)),
|
||||
Some(TypeExtra::Struct(struct_ty)) => {
|
||||
struct_types(struct_ty, &mut |inner| descend(inner, f))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
|
||||
fn packed_widths(src: &str) -> Vec<String> {
|
||||
let (file, _) = parse_source_tolerant(src);
|
||||
let mut out = Vec::new();
|
||||
walk_dims(&file, &mut |packing, dim| {
|
||||
if packing == Packing::Packed {
|
||||
out.push(src[dim.span.as_range()].to_string());
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn unpacked_extents(src: &str) -> Vec<String> {
|
||||
let (file, _) = parse_source_tolerant(src);
|
||||
let mut out = Vec::new();
|
||||
walk_dims(&file, &mut |packing, dim| {
|
||||
if packing == Packing::Unpacked {
|
||||
out.push(src[dim.span.as_range()].to_string());
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reaches_the_packed_dimensions_of_every_declaration_shape() {
|
||||
let src = "module m #(parameter logic [1:0] P = 0) (\n\
|
||||
input logic [2:0] a\n\
|
||||
);\n\
|
||||
logic [3:0] b;\n\
|
||||
typedef logic [4:0] w_t;\n\
|
||||
function logic [5:0] f(input logic [6:0] x);\n\
|
||||
logic [7:0] local_v;\n\
|
||||
return 0;\n\
|
||||
endfunction\n\
|
||||
endmodule\n";
|
||||
assert_eq!(
|
||||
packed_widths(src),
|
||||
vec!["[1:0]", "[2:0]", "[3:0]", "[4:0]", "[5:0]", "[6:0]", "[7:0]"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reaches_an_anonymous_aggregates_members_and_base() {
|
||||
let src = "module m;\n\
|
||||
struct packed { logic [1:0] a; logic [2:0] b; } s;\n\
|
||||
enum logic [3:0] { A } e;\n\
|
||||
endmodule\n";
|
||||
assert_eq!(packed_widths(src), vec!["[1:0]", "[2:0]", "[3:0]"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packed_and_unpacked_are_told_apart() {
|
||||
let src = "module m;\n logic [1:0] q [4];\nendmodule\n";
|
||||
assert_eq!(packed_widths(src), vec!["[1:0]"]);
|
||||
assert_eq!(unpacked_extents(src), vec!["[4]"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_struct_member_is_reached_through_a_typedef() {
|
||||
let src = "typedef struct packed {\n logic [9:0] wide;\n} w_t;\n";
|
||||
assert_eq!(packed_widths(src), vec!["[9:0]"]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
//! What each module in one file declares that an instantiation may name.
|
||||
//!
|
||||
//! The language server answers [`MentionOracle::module_interface`] from its
|
||||
//! workspace index, which already records every module's ports and parameters.
|
||||
//! `lucisv check` has no index, so it reads the same facts off the parse it
|
||||
//! makes anyway — this file is that reading, and it lives here so the CLI and
|
||||
//! the linter cannot come to disagree about what "a port of this module" is.
|
||||
//!
|
||||
//! Erring is one-directional on purpose: a unit whose header lucisv cannot see
|
||||
//! whole is reported as **unknowable** rather than as a short list, because a
|
||||
//! short list is what turns a legal connection into an accusation.
|
||||
|
||||
use vlog_parser::ast::{ItemKind, ListElem, Module, ParamPort, PortList, SourceFile};
|
||||
|
||||
use crate::context::ModuleInterface;
|
||||
use crate::visit::walk_items;
|
||||
|
||||
/// Every module, interface and program the file declares, with what it
|
||||
/// exposes. `None` for a unit whose header cannot be read whole.
|
||||
///
|
||||
/// A file may declare a name twice (two `` `ifdef`` arms, a copy-paste); the
|
||||
/// caller merges across files and must treat any disagreement as unknowable,
|
||||
/// so both entries are returned rather than one.
|
||||
pub fn module_interfaces(file: &SourceFile) -> Vec<(String, Option<ModuleInterface>)> {
|
||||
let mut out = Vec::new();
|
||||
walk_items(file, &mut |item| {
|
||||
if let ItemKind::Module(module) = &item.kind {
|
||||
out.push((module.name.clone(), interface_of(module)));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// One unit's surface, or `None` when its header is not fully visible.
|
||||
fn interface_of(module: &Module) -> Option<ModuleInterface> {
|
||||
// A directive written *between* ports or parameters may be a conditional
|
||||
// — whose arms are all in the list, so the list stays a superset — or a
|
||||
// macro invocation standing where a port belongs, whose expansion lucisv
|
||||
// never sees. Telling the two apart would be a second preprocessor; a
|
||||
// header with any directive in it is simply not answered for.
|
||||
if !module.port_directives.is_empty() || !module.param_directives.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(ModuleInterface { ports: ports_of(module), parameters: parameters_of(module) })
|
||||
}
|
||||
|
||||
/// The port names of either header style. A header with no port list at all
|
||||
/// declares none, which is a fact rather than a gap: nothing may be connected
|
||||
/// to it by name.
|
||||
fn ports_of(module: &Module) -> Vec<String> {
|
||||
match &module.ports {
|
||||
PortList::Ansi(ports) => {
|
||||
ports.iter().filter_map(ListElem::ok).map(|port| port.name.clone()).collect()
|
||||
}
|
||||
PortList::NonAnsi(ports) => {
|
||||
ports.iter().filter_map(ListElem::ok).map(|port| port.name.clone()).collect()
|
||||
}
|
||||
PortList::None | PortList::Empty => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The names an `#(.NAME(value))` override may write: every `parameter` in the
|
||||
/// header and in the body.
|
||||
///
|
||||
/// A `localparam` is **not** one — it is the module's own constant and is not
|
||||
/// overridable (IEEE 1800 §6.20.4), which is exactly the distinction
|
||||
/// `SymbolKind::LocalParam` was parted out for. A header parameter written
|
||||
/// without a keyword continues the previous declaration and inherits its
|
||||
/// keyword, which is how `#(parameter int A = 1, B = 2)` declares two
|
||||
/// overridable parameters.
|
||||
fn parameters_of(module: &Module) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut overridable = true;
|
||||
for port in module.param_ports.iter().flatten().filter_map(ListElem::ok) {
|
||||
overridable = is_parameter(port, overridable);
|
||||
if overridable {
|
||||
out.push(port.name.clone());
|
||||
}
|
||||
}
|
||||
for item in &module.items {
|
||||
if let ItemKind::ParamDecl(decl) = &item.kind {
|
||||
if decl.kw == "parameter" {
|
||||
out.extend(decl.declarators.iter().map(|d| d.name.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether this header parameter is overridable, given whether the one before
|
||||
/// it was: a written keyword decides, and no keyword continues.
|
||||
fn is_parameter(port: &ParamPort, previous: bool) -> bool {
|
||||
match port.kw.as_deref() {
|
||||
Some("localparam") => false,
|
||||
Some(_) => true,
|
||||
None => previous,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
|
||||
fn interfaces(src: &str) -> Vec<(String, Option<ModuleInterface>)> {
|
||||
let (file, _) = parse_source_tolerant(src);
|
||||
module_interfaces(&file)
|
||||
}
|
||||
|
||||
fn only(src: &str) -> ModuleInterface {
|
||||
let found = interfaces(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
found.into_iter().next().and_then(|(_, i)| i).expect("a readable header")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_an_ansi_header() {
|
||||
let read = only(
|
||||
"module m #(parameter int Width = 8, localparam int Derived = Width + 1) (\n\
|
||||
input logic clk_i,\n\
|
||||
output logic [7:0] data_o\n\
|
||||
);\n\
|
||||
endmodule\n",
|
||||
);
|
||||
assert_eq!(read.ports, vec!["clk_i", "data_o"]);
|
||||
assert_eq!(read.parameters, vec!["Width"], "a localparam is not overridable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_a_non_ansi_header() {
|
||||
let read = only("module m (clk, rst_n);\n input clk;\n input rst_n;\nendmodule\n");
|
||||
assert_eq!(read.ports, vec!["clk", "rst_n"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_continuation_parameter_inherits_its_keyword() {
|
||||
let read = only("module m #(parameter int A = 1, B = 2) ();\nendmodule\n");
|
||||
assert_eq!(read.parameters, vec!["A", "B"]);
|
||||
let local = only("module m #(localparam int A = 1, B = 2) ();\nendmodule\n");
|
||||
assert!(local.parameters.is_empty(), "both continue the localparam");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_body_parameter_is_overridable_and_a_body_localparam_is_not() {
|
||||
let read =
|
||||
only("module m ();\n parameter int Depth = 4;\n localparam int W = 2;\nendmodule\n");
|
||||
assert_eq!(read.parameters, vec!["Depth"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_with_a_directive_in_it_is_unknowable() {
|
||||
let src = "module m (\n\
|
||||
`ifdef X\n\
|
||||
input logic a,\n\
|
||||
`endif\n\
|
||||
input logic b\n\
|
||||
);\n\
|
||||
endmodule\n";
|
||||
assert_eq!(interfaces(src), vec![("m".to_string(), None)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_less_module_declares_no_ports() {
|
||||
let read = only("module m;\nendmodule\n");
|
||||
assert!(read.ports.is_empty());
|
||||
assert!(read.parameters.is_empty());
|
||||
let empty = only("module m ();\nendmodule\n");
|
||||
assert!(empty.ports.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_is_read_the_same_way() {
|
||||
let read = only("interface bus_if (input logic clk);\nendinterface\n");
|
||||
assert_eq!(read.ports, vec!["clk"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_unit_of_a_file_is_returned() {
|
||||
let found = interfaces("module a ();\nendmodule\nmodule b ();\nendmodule\n");
|
||||
assert_eq!(found.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(), vec!["a", "b"]);
|
||||
}
|
||||
}
|
||||
@@ -21,26 +21,36 @@
|
||||
//! `docs/features/linter-core/README.md`.
|
||||
|
||||
mod context;
|
||||
mod decls;
|
||||
mod interfaces;
|
||||
mod literal;
|
||||
mod naming;
|
||||
mod registry;
|
||||
mod rule_docs;
|
||||
mod rules;
|
||||
mod severity;
|
||||
mod signals;
|
||||
mod violation;
|
||||
mod visit;
|
||||
mod vscode;
|
||||
mod waiver;
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub use context::{LintContext, MentionOracle, ParsedSource};
|
||||
pub use registry::{all_rules, default_rules, rule_by_name, select_rules, workspace_rules, Rule};
|
||||
pub use context::{LintContext, MentionOracle, ModuleInterface, ParsedSource};
|
||||
pub use interfaces::module_interfaces;
|
||||
pub use registry::{
|
||||
all_rules, default_rules, rule_by_name, rules_named, select_rules, workspace_rules, Rule,
|
||||
};
|
||||
pub use rule_docs::rules_markdown;
|
||||
pub use severity::Severity;
|
||||
pub use violation::{apply_fixes, Applicability, Fix, Fixed, Violation};
|
||||
/// The identifier census a [`MentionOracle`] is answered from, re-exported
|
||||
/// from `vlog_semantic` so a front end that implements the oracle needs this
|
||||
/// crate alone. One harvest for the whole workspace — see
|
||||
/// `docs/features/semantic-lints-on/README.md`.
|
||||
pub use vlog_semantic::words;
|
||||
pub use vscode::{rule_setting, severity_setting, vscode_lint_settings, RULE_CHOICES};
|
||||
pub use waiver::UNUSED_WAIVER;
|
||||
|
||||
use waiver::Waivers;
|
||||
@@ -87,9 +97,24 @@ pub fn lint(ctx: &LintContext, enabled: &[&'static dyn Rule]) -> Vec<Violation>
|
||||
kept.sort_by(|a, b| {
|
||||
(a.span.start, a.span.end, a.rule).cmp(&(b.span.start, b.span.end, b.rule))
|
||||
});
|
||||
stamp_severities(&mut kept);
|
||||
kept
|
||||
}
|
||||
|
||||
/// Gives every finding the class its rule declares.
|
||||
///
|
||||
/// One place rather than one per rule: a rule's `check` builds violations
|
||||
/// without knowing what it is called, the `unused-waiver` findings are built by
|
||||
/// the waiver scanner and not by a rule at all, and a severity written twice
|
||||
/// would eventually be written differently. See [`Violation::severity`].
|
||||
fn stamp_severities(violations: &mut [Violation]) {
|
||||
for violation in violations {
|
||||
if let Some(rule) = rule_by_name(violation.rule) {
|
||||
violation.severity = rule.severity();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -211,6 +236,27 @@ mod tests {
|
||||
assert!(run(src, None, &enabled).is_empty());
|
||||
}
|
||||
|
||||
/// Every finding the runner returns carries its rule's class — including
|
||||
/// the `unused-waiver` ones, which no rule's `check` produced.
|
||||
#[test]
|
||||
fn the_runner_stamps_every_finding_with_its_rules_severity() {
|
||||
let src = "module m;\n\
|
||||
\treg a; // lucisv: waive no-such-rule\n\
|
||||
\talways_comb a <= 1'b0;\n\
|
||||
endmodule\n";
|
||||
let found = run(src, Some(PathBuf::from("rtl/m.sv")), &default_rules());
|
||||
assert!(found.len() >= 3, "{found:#?}");
|
||||
for violation in &found {
|
||||
let rule = rule_by_name(violation.rule).expect("a registered rule");
|
||||
assert_eq!(violation.severity, rule.severity(), "{}", violation.rule);
|
||||
}
|
||||
let by_rule =
|
||||
|name: &str| found.iter().find(|v| v.rule == name).map(|v| v.severity).expect(name);
|
||||
assert_eq!(by_rule("wire-reg-mixup"), Severity::Error);
|
||||
assert_eq!(by_rule("always-comb-blocking"), Severity::Warning);
|
||||
assert_eq!(by_rule(UNUSED_WAIVER), Severity::Style);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_parse_still_gets_its_text_rules() {
|
||||
let src = "module m;\n\t@@@ this is not verilog\nendmodule\n";
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
//! Sized based literals, read the way the two width rules need them.
|
||||
//!
|
||||
//! `truncated-numeric-literal` asks "how many bits does what is written
|
||||
//! actually need?" and `undersized-binary-literal` asks "how many digits were
|
||||
//! written?". Both questions are about the same `<size>'<base><digits>` shape,
|
||||
//! so it is parsed once here rather than twice, slightly differently.
|
||||
|
||||
/// One `<size>'[s]<base><digits>` literal, as written.
|
||||
///
|
||||
/// Only the *sized* spelling is modelled: an unsized `'h1f` takes its width
|
||||
/// from context, so neither rule has anything to compare against and
|
||||
/// [`parse`] returns `None` for it.
|
||||
pub(crate) struct SizedLiteral<'a> {
|
||||
/// The declared width, in bits.
|
||||
pub width: u32,
|
||||
/// The base letter, lower-cased: `b`, `o`, `d` or `h`.
|
||||
pub base: char,
|
||||
/// The digits as written, `_` separators included.
|
||||
pub digits: &'a str,
|
||||
}
|
||||
|
||||
impl SizedLiteral<'_> {
|
||||
/// The digits with the `_` separators taken out.
|
||||
pub fn packed_digits(&self) -> String {
|
||||
self.digits.chars().filter(|c| *c != '_').collect()
|
||||
}
|
||||
|
||||
/// How many bits the written value really needs, or `None` when that
|
||||
/// cannot be said: an empty or malformed digit run, or a decimal value
|
||||
/// carrying `x`/`z`.
|
||||
///
|
||||
/// A digit that is `x`, `z` or `?` counts as full-width — `4'hxF` needs
|
||||
/// eight bits, because the unknown nibble is still a nibble.
|
||||
pub fn significant_bits(&self) -> Option<u32> {
|
||||
let digits = self.packed_digits();
|
||||
let digits = digits.trim_start_matches('0');
|
||||
if digits.is_empty() {
|
||||
return Some(0);
|
||||
}
|
||||
let Some(per_digit) = bits_per_digit(self.base) else {
|
||||
// Decimal: the whole run is one number, so an `x` in it makes the
|
||||
// value unknown rather than one unknown digit.
|
||||
let value: u128 = digits.parse().ok()?;
|
||||
return Some(128 - value.leading_zeros());
|
||||
};
|
||||
let mut chars = digits.chars();
|
||||
let first = chars.next()?;
|
||||
let rest = chars.count() as u32;
|
||||
let head = match first.to_ascii_lowercase() {
|
||||
'x' | 'z' | '?' => per_digit,
|
||||
c => bits_of(c, self.base)?,
|
||||
};
|
||||
Some(rest * per_digit + head)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a sized based literal, or `None` for anything else — an unsized
|
||||
/// literal, a plain decimal, a real, a time literal.
|
||||
pub(crate) fn parse(text: &str) -> Option<SizedLiteral<'_>> {
|
||||
let (size, rest) = text.split_once('\'')?;
|
||||
let width: u32 = size.chars().filter(|c| *c != '_').collect::<String>().parse().ok()?;
|
||||
// `8'sh1f` — the signedness marker sits between the tick and the base.
|
||||
let rest = rest.strip_prefix(['s', 'S']).unwrap_or(rest);
|
||||
let mut chars = rest.chars();
|
||||
let base = chars.next()?.to_ascii_lowercase();
|
||||
if !matches!(base, 'b' | 'o' | 'd' | 'h') {
|
||||
return None;
|
||||
}
|
||||
let digits = rest.get(1..)?;
|
||||
if digits.is_empty() || !digits.chars().all(|c| is_digit_of(c, base) || c == '_') {
|
||||
return None;
|
||||
}
|
||||
Some(SizedLiteral { width, base, digits })
|
||||
}
|
||||
|
||||
/// How many bits one digit of `base` carries; `None` for decimal, which is not
|
||||
/// a per-digit base at all.
|
||||
fn bits_per_digit(base: char) -> Option<u32> {
|
||||
match base {
|
||||
'b' => Some(1),
|
||||
'o' => Some(3),
|
||||
'h' => Some(4),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// How many bits one known digit's value needs (`7` needs three, `1` needs
|
||||
/// one), or `None` when the character is not a digit of this base.
|
||||
fn bits_of(c: char, base: char) -> Option<u32> {
|
||||
let value = c.to_digit(16)?;
|
||||
let per_digit = bits_per_digit(base)?;
|
||||
if value >= 1 << per_digit {
|
||||
return None;
|
||||
}
|
||||
Some(32 - value.leading_zeros())
|
||||
}
|
||||
|
||||
/// True when `c` may stand among `base`'s digits, unknowns included.
|
||||
fn is_digit_of(c: char, base: char) -> bool {
|
||||
let c = c.to_ascii_lowercase();
|
||||
if matches!(c, 'x' | 'z' | '?') {
|
||||
return true;
|
||||
}
|
||||
match base {
|
||||
'b' => matches!(c, '0' | '1'),
|
||||
'o' => c.is_digit(8),
|
||||
'd' => c.is_ascii_digit(),
|
||||
_ => c.is_ascii_hexdigit(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn bits(text: &str) -> Option<u32> {
|
||||
parse(text)?.significant_bits()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sized_literal_is_read_in_every_base() {
|
||||
for (text, width, base, digits) in [
|
||||
("8'hFF", 8, 'h', "FF"),
|
||||
("4'b1010", 4, 'b', "1010"),
|
||||
("3'o7", 3, 'o', "7"),
|
||||
("16'd1000", 16, 'd', "1000"),
|
||||
("8'sh1f", 8, 'h', "1f"),
|
||||
("32'hdead_beef", 32, 'h', "dead_beef"),
|
||||
] {
|
||||
let found = parse(text).unwrap_or_else(|| panic!("{text}"));
|
||||
assert_eq!((found.width, found.base, found.digits), (width, base, digits), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anything_that_is_not_a_sized_based_literal_is_declined() {
|
||||
for text in ["'h1f", "42", "1.5", "10ns", "8'", "8'q1", "8'h", "8'hG", "'0"] {
|
||||
assert!(parse(text).is_none(), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn significant_bits_counts_what_is_written() {
|
||||
assert_eq!(bits("4'h0"), Some(0));
|
||||
assert_eq!(bits("4'h1"), Some(1));
|
||||
assert_eq!(bits("4'h8"), Some(4));
|
||||
assert_eq!(bits("4'hFFF"), Some(12), "three full nibbles");
|
||||
assert_eq!(bits("8'b0000_0001"), Some(1), "leading zeros do not count");
|
||||
assert_eq!(bits("4'o7"), Some(3));
|
||||
assert_eq!(bits("8'd255"), Some(8));
|
||||
assert_eq!(bits("8'd256"), Some(9));
|
||||
assert_eq!(bits("4'hx"), Some(4), "an unknown nibble is still a nibble");
|
||||
assert_eq!(bits("4'h0x"), Some(4), "and leading zeros still do not count");
|
||||
assert_eq!(bits("8'dx"), None, "a decimal unknown says nothing about width");
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::rules;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::{Applicability, Violation};
|
||||
|
||||
/// One lint rule.
|
||||
@@ -17,6 +18,14 @@ pub trait Rule: Sync {
|
||||
/// One line, imperative, no trailing period.
|
||||
fn summary(&self) -> &'static str;
|
||||
|
||||
/// How bad this rule's findings are.
|
||||
///
|
||||
/// Deliberately without a default: a class is a claim about what a finding
|
||||
/// means to the user, and a rule that inherited one silently would be
|
||||
/// making that claim by accident. The reason for the class chosen belongs
|
||||
/// in [`Rule::doc`].
|
||||
fn severity(&self) -> Severity;
|
||||
|
||||
/// Why the rule exists — the style-guide rationale, in prose.
|
||||
fn doc(&self) -> &'static str;
|
||||
|
||||
@@ -60,19 +69,38 @@ pub fn all_rules() -> Vec<&'static dyn Rule> {
|
||||
&rules::always_comb_blocking::AlwaysCombBlocking,
|
||||
&rules::always_ff_non_blocking::AlwaysFfNonBlocking,
|
||||
&rules::case_missing_default::CaseMissingDefault,
|
||||
&rules::duplicate_declaration::DuplicateDeclaration,
|
||||
&rules::empty_item::EmptyItem,
|
||||
&rules::enum_name_style::EnumNameStyle,
|
||||
&rules::explicit_function_task_parameter_type::ExplicitFunctionTaskParameterType,
|
||||
&rules::explicit_parameter_storage_type::ExplicitParameterStorageType,
|
||||
&rules::forbid_defparam::ForbidDefparam,
|
||||
&rules::forbid_negative_array_dim::ForbidNegativeArrayDim,
|
||||
&rules::incomplete_assignment::IncompleteAssignment,
|
||||
&rules::instance_shadowing::InstanceShadowing,
|
||||
&rules::invalid_system_task_function::InvalidSystemTaskFunction,
|
||||
&rules::mismatched_labels::MismatchedLabels,
|
||||
&rules::module_filename::ModuleFilename,
|
||||
&rules::module_name_style::ModuleNameStyle,
|
||||
&rules::module_parameter::ModuleParameter,
|
||||
&rules::module_port::ModulePort,
|
||||
&rules::multiply_driven::MultiplyDriven,
|
||||
&rules::no_tabs::NoTabs,
|
||||
&rules::no_trailing_whitespace::NoTrailingWhitespace,
|
||||
&rules::packed_dimensions_range_ordering::PackedDimensionsRangeOrdering,
|
||||
&rules::parameter_name_style::ParameterNameStyle,
|
||||
&rules::plusarg_assignment::PlusargAssignment,
|
||||
&rules::struct_union_name_style::StructUnionNameStyle,
|
||||
&rules::suspicious_semicolon::SuspiciousSemicolon,
|
||||
&rules::truncated_numeric_literal::TruncatedNumericLiteral,
|
||||
&rules::undeclared_identifier::UndeclaredIdentifier,
|
||||
&rules::undersized_binary_literal::UndersizedBinaryLiteral,
|
||||
&rules::undriven_net::UndrivenNet,
|
||||
&rules::unknown_parameter::UnknownParameter,
|
||||
&rules::unknown_port::UnknownPort,
|
||||
&rules::unused_signal::UnusedSignal,
|
||||
&rules::unused_waiver::UnusedWaiver,
|
||||
&rules::void_cast::VoidCast,
|
||||
&rules::wire_reg_mixup::WireRegMixup,
|
||||
]
|
||||
}
|
||||
@@ -112,10 +140,25 @@ pub fn rule_by_name(name: &str) -> Option<&'static dyn Rule> {
|
||||
all_rules().into_iter().find(|rule| rule.name() == name)
|
||||
}
|
||||
|
||||
/// The rules one `--select` / `--ignore` name stands for.
|
||||
///
|
||||
/// A rule name stands for itself; a **severity name** (`error`, `warning`,
|
||||
/// `style`) stands for every rule of that class, so `--ignore style` is one
|
||||
/// word for the whole family. `None` for a name that is neither, which is what
|
||||
/// makes a typo a failed run rather than a silently empty selection.
|
||||
pub fn rules_named(name: &str) -> Option<Vec<&'static dyn Rule>> {
|
||||
if let Some(rule) = rule_by_name(name) {
|
||||
return Some(vec![rule]);
|
||||
}
|
||||
let severity = Severity::from_name(name)?;
|
||||
Some(all_rules().into_iter().filter(|rule| rule.severity() == severity).collect())
|
||||
}
|
||||
|
||||
/// The rules a run should use: `select` replaces the default set (empty means
|
||||
/// keep it), then `ignore` removes from whatever is left. An unknown name on
|
||||
/// either list is an error rather than a silent no-op — a typo'd `--select`
|
||||
/// that quietly ran everything would be worse than a failed run.
|
||||
/// keep it), then `ignore` removes from whatever is left. Either list may name
|
||||
/// a rule or a whole severity ([`rules_named`]). An unknown name on either
|
||||
/// list is an error rather than a silent no-op — a typo'd `--select` that
|
||||
/// quietly ran everything would be worse than a failed run.
|
||||
///
|
||||
/// `workspace` only reaches [`default_rules`]: an explicit `select` names the
|
||||
/// rules it wants and gets them, oracle or no oracle, exactly as an explicit
|
||||
@@ -128,25 +171,27 @@ pub fn select_rules(
|
||||
let mut chosen = if select.is_empty() {
|
||||
enabled_rules(workspace)
|
||||
} else {
|
||||
let mut chosen = Vec::new();
|
||||
let mut chosen: Vec<&'static dyn Rule> = Vec::new();
|
||||
for name in select {
|
||||
let rule = rule_by_name(name).ok_or_else(|| unknown(name))?;
|
||||
if !chosen.iter().any(|r: &&'static dyn Rule| r.name() == rule.name()) {
|
||||
chosen.push(rule);
|
||||
for rule in rules_named(name).ok_or_else(|| unknown(name))? {
|
||||
if !chosen.iter().any(|r| r.name() == rule.name()) {
|
||||
chosen.push(rule);
|
||||
}
|
||||
}
|
||||
}
|
||||
chosen
|
||||
};
|
||||
for name in ignore {
|
||||
rule_by_name(name).ok_or_else(|| unknown(name))?;
|
||||
chosen.retain(|rule| rule.name() != name);
|
||||
let dropped = rules_named(name).ok_or_else(|| unknown(name))?;
|
||||
chosen.retain(|rule| !dropped.iter().any(|d| d.name() == rule.name()));
|
||||
}
|
||||
Ok(chosen)
|
||||
}
|
||||
|
||||
fn unknown(name: &str) -> String {
|
||||
let known = all_rules().iter().map(|r| r.name()).collect::<Vec<_>>().join(", ");
|
||||
format!("unknown rule: {name} (known rules: {known})")
|
||||
let severities = Severity::ALL.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
|
||||
format!("unknown rule: {name} (severities: {severities}; known rules: {known})")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -211,7 +256,17 @@ mod tests {
|
||||
let project: Vec<&str> = workspace_rules().iter().map(|r| r.name()).collect();
|
||||
let added: Vec<&str> =
|
||||
project.iter().copied().filter(|name| !alone.contains(name)).collect();
|
||||
assert_eq!(added, vec!["multiply-driven", "undriven-net", "unused-signal"]);
|
||||
assert_eq!(
|
||||
added,
|
||||
vec![
|
||||
"multiply-driven",
|
||||
"undeclared-identifier",
|
||||
"undriven-net",
|
||||
"unknown-parameter",
|
||||
"unknown-port",
|
||||
"unused-signal",
|
||||
]
|
||||
);
|
||||
assert!(alone.iter().all(|name| project.contains(name)), "a workspace never removes one");
|
||||
for rule in all_rules() {
|
||||
assert_eq!(rule.needs_workspace(), added.contains(&rule.name()), "{}", rule.name());
|
||||
@@ -283,6 +338,95 @@ mod tests {
|
||||
assert!(message.contains("no-tabs"), "the error must list what is known: {message}");
|
||||
}
|
||||
|
||||
/// Every rule states a class, and no rule name collides with a class
|
||||
/// name — otherwise `--select error` would mean two things.
|
||||
#[test]
|
||||
fn every_rule_has_a_severity_and_no_name_shadows_a_class() {
|
||||
for rule in all_rules() {
|
||||
assert!(Severity::ALL.contains(&rule.severity()), "{}", rule.name());
|
||||
assert!(
|
||||
Severity::from_name(rule.name()).is_none(),
|
||||
"{} shadows a severity word",
|
||||
rule.name()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The assignments §33.0 wrote down for the seventeen rules that predate
|
||||
/// severities. A rule moving class is a user-visible change, so it moves
|
||||
/// here first.
|
||||
#[test]
|
||||
fn the_original_seventeen_keep_the_classes_they_were_given() {
|
||||
let expected: &[(&str, Severity)] = &[
|
||||
("multiply-driven", Severity::Error),
|
||||
("wire-reg-mixup", Severity::Error),
|
||||
("always-comb-blocking", Severity::Warning),
|
||||
("always-ff-non-blocking", Severity::Warning),
|
||||
("case-missing-default", Severity::Warning),
|
||||
("undriven-net", Severity::Warning),
|
||||
("unused-signal", Severity::Warning),
|
||||
("empty-item", Severity::Style),
|
||||
("enum-name-style", Severity::Style),
|
||||
("explicit-parameter-storage-type", Severity::Style),
|
||||
("module-filename", Severity::Style),
|
||||
("module-name-style", Severity::Style),
|
||||
("no-tabs", Severity::Style),
|
||||
("no-trailing-whitespace", Severity::Style),
|
||||
("parameter-name-style", Severity::Style),
|
||||
("struct-union-name-style", Severity::Style),
|
||||
("unused-waiver", Severity::Style),
|
||||
];
|
||||
for (name, severity) in expected {
|
||||
let rule = rule_by_name(name).unwrap_or_else(|| panic!("{name} exists"));
|
||||
assert_eq!(rule.severity(), *severity, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_severity_name_stands_for_every_rule_of_that_class() {
|
||||
for severity in Severity::ALL {
|
||||
let named = rules_named(severity.as_str()).unwrap_or_default();
|
||||
let expected: Vec<&str> = all_rules()
|
||||
.into_iter()
|
||||
.filter(|rule| rule.severity() == severity)
|
||||
.map(|rule| rule.name())
|
||||
.collect();
|
||||
assert_eq!(named.iter().map(|r| r.name()).collect::<Vec<_>>(), expected);
|
||||
assert!(!expected.is_empty(), "{severity:?} has no rules");
|
||||
}
|
||||
assert!(rules_named("no-tabs").is_some_and(|rules| rules.len() == 1));
|
||||
assert!(rules_named("no-such-thing").is_none());
|
||||
}
|
||||
|
||||
/// `--select style`, `--ignore warning`: the whole point of the words.
|
||||
#[test]
|
||||
fn select_and_ignore_accept_a_severity_wherever_a_rule_fits() {
|
||||
let styled = select_rules(&["style".to_string()], &[], true).unwrap();
|
||||
assert!(styled.iter().all(|rule| rule.severity() == Severity::Style));
|
||||
assert!(styled.iter().any(|rule| rule.name() == "no-tabs"));
|
||||
|
||||
let quiet = select_rules(&[], &["style".to_string()], true).unwrap();
|
||||
assert!(quiet.iter().all(|rule| rule.severity() != Severity::Style));
|
||||
assert!(quiet.iter().any(|rule| rule.name() == "unused-signal"), "warnings survive");
|
||||
|
||||
// A severity and a rule name mix on one list, and the same rule named
|
||||
// twice is still selected once.
|
||||
let mixed =
|
||||
select_rules(&["style".to_string(), "no-tabs".to_string()], &[], false).unwrap();
|
||||
assert_eq!(mixed.iter().filter(|rule| rule.name() == "no-tabs").count(), 1);
|
||||
|
||||
// Ignoring a class removes it from an explicit selection too.
|
||||
let none = select_rules(&["no-tabs".to_string()], &["style".to_string()], false).unwrap();
|
||||
assert!(none.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_unknown_name_error_names_the_severity_words_too() {
|
||||
let message = select_rules(&["styles".to_string()], &[], false).err().unwrap_or_default();
|
||||
assert!(message.contains("style"), "{message}");
|
||||
assert!(message.contains("no-tabs"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_by_name_finds_every_rule_and_nothing_else() {
|
||||
for rule in all_rules() {
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
//! this.
|
||||
|
||||
use crate::registry::all_rules;
|
||||
use crate::severity::Severity;
|
||||
|
||||
/// The whole rule reference as one markdown document.
|
||||
pub fn rules_markdown() -> String {
|
||||
@@ -15,6 +16,12 @@ pub fn rules_markdown() -> String {
|
||||
out.push_str(
|
||||
"Generated from the rule registry by `vlog_linter::rules_markdown` — \
|
||||
do not edit by hand.\n\n\
|
||||
Every rule is in one of three **severity** classes, and the class is \
|
||||
a word `--select` and `--ignore` accept wherever a rule name fits \
|
||||
(`--ignore style`, `--select error`). **error** is code that would \
|
||||
very likely fail to compile, elaborate or synthesize; **warning** is \
|
||||
code that compiles but very likely does not mean what it says; \
|
||||
**style** is code that is correct and reads badly.\n\n\
|
||||
A rule marked **on** runs for a plain `lucisv check`; the others need \
|
||||
`--select <name>`. A rule marked **on (project)** runs by default \
|
||||
only where lucisv can see the other files of the project — \
|
||||
@@ -26,23 +33,32 @@ pub fn rules_markdown() -> String {
|
||||
<name>`.\n\n",
|
||||
);
|
||||
|
||||
out.push_str("| Rule | Default | Fix |\n|---|---|---|\n");
|
||||
out.push_str("| Rule | Severity | Default | Fix |\n|---|---|---|---|\n");
|
||||
for rule in all_rules() {
|
||||
out.push_str(&format!(
|
||||
"| [`{name}`](#{name}) | {default} | {fix} |\n",
|
||||
"| [`{name}`](#{name}) | {severity} | {default} | {fix} |\n",
|
||||
name = rule.name(),
|
||||
severity = rule.severity().as_str(),
|
||||
default = default_word(rule),
|
||||
fix = fix_word(rule),
|
||||
));
|
||||
}
|
||||
out.push('\n');
|
||||
|
||||
for rule in all_rules() {
|
||||
out.push_str(&format!("## {}\n\n", rule.name()));
|
||||
out.push_str(&format!("{}.\n\n", capitalize(rule.summary())));
|
||||
out.push_str(&format!("- Default: {}\n- Fix: {}\n\n", default_word(rule), fix_word(rule)));
|
||||
out.push_str(rule.doc());
|
||||
out.push_str("\n\n");
|
||||
for severity in Severity::ALL {
|
||||
out.push_str(&format!("# {} — {}\n\n", severity.as_str(), severity.describes()));
|
||||
for rule in all_rules().into_iter().filter(|rule| rule.severity() == severity) {
|
||||
out.push_str(&format!("## {}\n\n", rule.name()));
|
||||
out.push_str(&format!("{}.\n\n", capitalize(rule.summary())));
|
||||
out.push_str(&format!(
|
||||
"- Severity: {}\n- Default: {}\n- Fix: {}\n\n",
|
||||
severity.as_str(),
|
||||
default_word(rule),
|
||||
fix_word(rule),
|
||||
));
|
||||
out.push_str(rule.doc());
|
||||
out.push_str("\n\n");
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -98,7 +114,7 @@ mod tests {
|
||||
fn the_index_lists_every_rule_once() {
|
||||
let markdown = rules_markdown();
|
||||
for rule in all_rules() {
|
||||
let row = format!("| [`{0}`](#{0}) |", rule.name());
|
||||
let row = format!("| [`{0}`](#{0}) | ", rule.name());
|
||||
assert_eq!(markdown.matches(&row).count(), 1, "{}", rule.name());
|
||||
}
|
||||
}
|
||||
@@ -106,27 +122,62 @@ mod tests {
|
||||
#[test]
|
||||
fn defaults_and_fixes_are_rendered_from_the_registry() {
|
||||
let markdown = rules_markdown();
|
||||
assert!(markdown.contains("| [`no-tabs`](#no-tabs) | **on** | safe |"));
|
||||
assert!(markdown.contains("| [`module-name-style`](#module-name-style) | off | none |"));
|
||||
assert!(markdown.contains("| [`no-tabs`](#no-tabs) | style | **on** | safe |"));
|
||||
assert!(
|
||||
markdown.contains("| [`module-name-style`](#module-name-style) | style | off | none |")
|
||||
);
|
||||
// The three semantic rules are fixless, and default on exactly where
|
||||
// there is a project to ask about a name — see
|
||||
// docs/features/semantic-lints-on/README.md.
|
||||
for name in ["multiply-driven", "undriven-net", "unused-signal"] {
|
||||
for (name, severity) in [
|
||||
("multiply-driven", "error"),
|
||||
("undriven-net", "warning"),
|
||||
("unused-signal", "warning"),
|
||||
] {
|
||||
assert!(
|
||||
markdown.contains(&format!("| [`{name}`](#{name}) | **on (project)** | none |")),
|
||||
markdown.contains(&format!(
|
||||
"| [`{name}`](#{name}) | {severity} | **on (project)** | none |"
|
||||
)),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
assert_eq!(fix_word(&crate::rules::no_tabs::NoTabs), Applicability::Safe.as_str());
|
||||
}
|
||||
|
||||
/// Every rule sits under the heading of its own class, and the three
|
||||
/// headings are written worst-first.
|
||||
#[test]
|
||||
fn the_sections_are_grouped_by_severity() {
|
||||
let markdown = rules_markdown();
|
||||
let heading = |severity: Severity| {
|
||||
markdown
|
||||
.find(&format!("\n# {} — ", severity.as_str()))
|
||||
.unwrap_or_else(|| panic!("{severity:?} heading"))
|
||||
};
|
||||
let (error, warning, style) =
|
||||
(heading(Severity::Error), heading(Severity::Warning), heading(Severity::Style));
|
||||
assert!(error < warning && warning < style, "worst first");
|
||||
for rule in all_rules() {
|
||||
let at = markdown
|
||||
.find(&format!("\n## {}\n", rule.name()))
|
||||
.unwrap_or_else(|| panic!("{}", rule.name()));
|
||||
let own = heading(rule.severity());
|
||||
let next = [error, warning, style]
|
||||
.into_iter()
|
||||
.filter(|start| *start > own)
|
||||
.min()
|
||||
.unwrap_or(markdown.len());
|
||||
assert!(own < at && at < next, "{} is under the wrong heading", rule.name());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_document_shape_is_pinned() {
|
||||
// A golden test on the *shape*, not on the prose: the heading, the
|
||||
// generated-by note, the index table header, and the first per-rule
|
||||
// section, which together are what a reader (and any renderer) sees.
|
||||
let markdown = rules_markdown();
|
||||
let head: Vec<&str> = markdown.lines().take(8).collect();
|
||||
let head: Vec<&str> = markdown.lines().take(10).collect();
|
||||
assert_eq!(
|
||||
head,
|
||||
vec![
|
||||
@@ -135,6 +186,12 @@ mod tests {
|
||||
"Generated from the rule registry by `vlog_linter::rules_markdown` — do not edit \
|
||||
by hand.",
|
||||
"",
|
||||
"Every rule is in one of three **severity** classes, and the class is a word \
|
||||
`--select` and `--ignore` accept wherever a rule name fits (`--ignore style`, \
|
||||
`--select error`). **error** is code that would very likely fail to compile, \
|
||||
elaborate or synthesize; **warning** is code that compiles but very likely does \
|
||||
not mean what it says; **style** is code that is correct and reads badly.",
|
||||
"",
|
||||
"A rule marked **on** runs for a plain `lucisv check`; the others need \
|
||||
`--select <name>`. A rule marked **on (project)** runs by default only where \
|
||||
lucisv can see the other files of the project — `lucisv check <dir>`, or the \
|
||||
@@ -143,13 +200,16 @@ mod tests {
|
||||
rule can be turned off with `--ignore <name>`, with `ignore` under `[lint]` in \
|
||||
`lucisv.toml`, or waived in the source with `// lucisv: waive <name>`.",
|
||||
"",
|
||||
"| Rule | Default | Fix |",
|
||||
"|---|---|---|",
|
||||
"| Rule | Severity | Default | Fix |",
|
||||
"|---|---|---|---|",
|
||||
]
|
||||
);
|
||||
let first_rule = all_rules()[0];
|
||||
let first_rule = all_rules()
|
||||
.into_iter()
|
||||
.find(|rule| rule.severity() == Severity::Error)
|
||||
.expect("some rule is an error");
|
||||
let section = format!(
|
||||
"## {}\n\n{}.\n\n- Default: {}\n- Fix: {}\n\n{}\n\n",
|
||||
"## {}\n\n{}.\n\n- Severity: error\n- Default: {}\n- Fix: {}\n\n{}\n\n",
|
||||
first_rule.name(),
|
||||
capitalize(first_rule.summary()),
|
||||
default_word(first_rule),
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::{walk_items, walk_stmts};
|
||||
use vlog_parser::ast::{ItemKind, StmtKind};
|
||||
@@ -20,6 +21,10 @@ impl Rule for AlwaysCombBlocking {
|
||||
"assign with `=` inside always_comb"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A non-blocking assignment in a combinational block schedules its \
|
||||
update for the end of the time step, so a value read later in the same \
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::{walk_items, walk_stmts};
|
||||
use vlog_parser::ast::{ItemKind, StmtKind};
|
||||
@@ -20,6 +21,10 @@ impl Rule for AlwaysFfNonBlocking {
|
||||
"assign with `<=` inside always_ff"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A blocking assignment in a clocked block updates immediately, so two \
|
||||
flops written in one `always_ff` can see each other's new value in \
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::{walk_all_stmts, walk_items};
|
||||
use vlog_parser::ast::{CaseItem, GenCaseItem, ItemKind, StmtKind};
|
||||
@@ -21,6 +22,10 @@ impl Rule for CaseMissingDefault {
|
||||
"give every case statement a default branch"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A case statement with no `default` infers a latch in combinational \
|
||||
logic and leaves the unlisted patterns unspecified in simulation — the \
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
//! `duplicate-declaration` — one name declared twice in one scope.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_semantic::{ScopeKind, SymbolKind};
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct DuplicateDeclaration;
|
||||
|
||||
const NAME: &str = "duplicate-declaration";
|
||||
|
||||
impl Rule for DuplicateDeclaration {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"declare each name once per scope"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Error
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"Two declarations of one name in one scope is an elaboration error in \
|
||||
every tool (IEEE 1800 §3.13 — an identifier is unique within its \
|
||||
namespace and scope). It happens when a signal is copied and the \
|
||||
paste is not renamed, when two parameters are merged from different \
|
||||
branches, or when a `logic` is declared beside the `input` of the \
|
||||
same name. Verible has no equivalent rule; this is TODO §33's own, \
|
||||
and it is an **Error** because the file will not compile.\n\n\
|
||||
**Silent whenever the second declaration might be legal**, which is \
|
||||
the rule every Error-class check here follows. It says nothing when \
|
||||
either declaration is a **port** — a non-ANSI port is *completed* by \
|
||||
a body `input clk;` and then by a `logic clk;`, all three of which \
|
||||
are the same port and all three legal — nor about a function, task, \
|
||||
class, constraint, covergroup, property, sequence, modport or \
|
||||
clocking name, each of which has a legal prototype-plus-definition \
|
||||
or forward-declaration shape. It says nothing inside a `generate` \
|
||||
scope, where only one arm is ever elaborated, and nothing when a \
|
||||
conditional-compilation directive stands between the two \
|
||||
declarations, which is that same exclusivity written for the \
|
||||
preprocessor. What is left is two ordinary declarations of one name, \
|
||||
side by side, in one scope. No automatic fix: which of the two the \
|
||||
author meant to keep is not something a linter can know."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
// Error recovery rebinds whatever followed a construct it could not
|
||||
// parse into whatever scope it unwound to, which turns every later
|
||||
// local into a phantom redeclaration. An Error-class rule says nothing
|
||||
// about a file it cannot trust the shape of.
|
||||
if !ctx.parsed_cleanly() {
|
||||
return Vec::new();
|
||||
}
|
||||
let semantics = ctx.semantics();
|
||||
let mut out = Vec::new();
|
||||
for duplicate in semantics.duplicates() {
|
||||
let Some(first) = semantics.symbol(duplicate.first) else { continue };
|
||||
if !plain(duplicate.kind) || !plain(first.kind) {
|
||||
continue;
|
||||
}
|
||||
let scope = semantics.scope(duplicate.scope).map(|scope| scope.kind);
|
||||
// A generate scope elaborates one arm at a time; the file scope is
|
||||
// where a `` `include``d fragment and a recovered construct both
|
||||
// land, and two file-scope units of one name are the workspace's
|
||||
// business rather than this file's.
|
||||
if matches!(scope, Some(ScopeKind::Generate) | Some(ScopeKind::File)) {
|
||||
continue;
|
||||
}
|
||||
let spans = [first.name_span.start, duplicate.name_span.start];
|
||||
if ctx.signals().conditional_between(&spans) {
|
||||
continue;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!("`{}` is already declared in this scope", duplicate.name),
|
||||
duplicate.name_span,
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// True for the declaration kinds that may be written **once** and once only.
|
||||
///
|
||||
/// Everything left out has a legal shape in which the same name is written
|
||||
/// twice: a port is completed by its body declaration, a function or task by
|
||||
/// its out-of-body definition, a class by its `typedef class` forward
|
||||
/// declaration, and a constraint, covergroup, property or sequence by its own
|
||||
/// prototype. An **enum member** is left out for a different reason: IEEE 1800
|
||||
/// §6.19's name *range* (`RvCoreCsrGprT[0:2]`) declares a run of members under
|
||||
/// one written identifier, and the binder records the identifier — so two
|
||||
/// disjoint ranges of one base name look like one name declared twice when the
|
||||
/// members they declare do not collide at all (measured on opentitan:
|
||||
/// `jtag_rv_debugger_pkg.sv`). Listed positively rather than as an exclusion
|
||||
/// list, so a kind added to `vlog_semantic` later is silent until somebody
|
||||
/// decides it belongs.
|
||||
fn plain(kind: SymbolKind) -> bool {
|
||||
matches!(
|
||||
kind,
|
||||
SymbolKind::Net
|
||||
| SymbolKind::Var
|
||||
| SymbolKind::Param
|
||||
| SymbolKind::LocalParam
|
||||
| SymbolKind::Genvar
|
||||
| SymbolKind::Typedef
|
||||
| SymbolKind::Instance
|
||||
| SymbolKind::TfArg
|
||||
| SymbolKind::StructMember
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
DuplicateDeclaration.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_two_signals_of_one_name() {
|
||||
let src = "module m;\n logic a;\n logic a;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("`a`"), "{}", found[0].message);
|
||||
assert_eq!(found[0].span.start as usize, src.rfind('a').map(|i| i - 1).unwrap_or(0) + 1);
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_two_parameters_two_typedefs_and_two_instances() {
|
||||
for src in [
|
||||
"module m;\n parameter int W = 1;\n parameter int W = 2;\nendmodule\n",
|
||||
"module m;\n typedef logic t;\n typedef bit t;\nendmodule\n",
|
||||
"module m;\n sub u ();\n sub u ();\nendmodule\n",
|
||||
] {
|
||||
assert_eq!(violations(src).len(), 1, "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The non-ANSI shape: the header names the port, the body declares its
|
||||
/// direction and then its type. Three declarations, one port, all legal.
|
||||
#[test]
|
||||
fn a_non_ansi_port_completed_in_the_body_is_never_flagged() {
|
||||
let src = "module m (clk);\n input clk;\n logic clk;\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
assert!(violations("module m (clk);\n input wire clk;\nendmodule\n").is_empty());
|
||||
// An ANSI port redeclared in the body is left alone too, for the same
|
||||
// reason: a rule that cannot tell the two apart must not accuse.
|
||||
assert!(violations("module m (input logic clk);\n logic clk;\nendmodule\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prototype_and_its_definition_are_one_declaration() {
|
||||
let src = "class c;\n extern function void f();\nendclass\n\
|
||||
function void c::f();\nendfunction\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
let forward = "package p;\n typedef class c;\n class c;\n endclass\nendpackage\n";
|
||||
assert!(violations(forward).is_empty(), "{:?}", violations(forward));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conditional_arms_are_exclusive_so_they_are_not_flagged() {
|
||||
let src = "module m;\n`ifdef X\n logic b;\n`else\n logic b;\n`endif\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generate_scope_elaborates_one_arm_at_a_time() {
|
||||
let src = "module m;\n\
|
||||
generate\n\
|
||||
if (A) begin : g\n\
|
||||
logic x;\n\
|
||||
end else begin : g\n\
|
||||
logic x;\n\
|
||||
end\n\
|
||||
endgenerate\n\
|
||||
endmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_reused_in_a_nested_scope_is_not_a_duplicate() {
|
||||
// That is shadowing, which is `instance-shadowing`'s subject.
|
||||
let src =
|
||||
"module m;\n logic a;\n always_comb begin : blk\n logic a;\n end\nendmodule\n";
|
||||
assert!(violations(src).is_empty());
|
||||
// And two modules may each declare `a`.
|
||||
let two = "module m;\n logic a;\nendmodule\nmodule n;\n logic a;\nendmodule\n";
|
||||
assert!(violations(two).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::{Applicability, Fix, Violation};
|
||||
use crate::visit::walk_items;
|
||||
use vlog_parser::ast::ItemKind;
|
||||
@@ -21,6 +22,10 @@ impl Rule for EmptyItem {
|
||||
"drop a `;` that stands where an item belongs"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A lone `;` in a module, generate, package, interface, program or class \
|
||||
body is a *null item* (IEEE 1800-2017 A.1.4). It is legal and it means \
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
use crate::context::LintContext;
|
||||
use crate::naming::{is_escaped, is_lower_snake_case};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_items;
|
||||
use vlog_parser::ast::{ItemKind, TypedefKind};
|
||||
@@ -22,6 +23,10 @@ impl Rule for EnumNameStyle {
|
||||
"name enum typedefs in lower_snake_case ending in _e or _t"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A type name that looks like a type name is what makes a declaration \
|
||||
readable at a glance: `state_e cur_state` says which identifier is the \
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
//! `explicit-function-task-parameter-type` — every formal gets a storage type.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_items;
|
||||
use vlog_parser::ast::{ItemKind, ListElem, TfArg};
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct ExplicitFunctionTaskParameterType;
|
||||
|
||||
const NAME: &str = "explicit-function-task-parameter-type";
|
||||
|
||||
impl Rule for ExplicitFunctionTaskParameterType {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"declare a storage type on every function and task argument"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A task or function formal written without a type is a **one-bit \
|
||||
`logic`** (IEEE 1800 §13.3), so `function f(input a);` truncates \
|
||||
every caller's argument to its low bit and nothing complains — the \
|
||||
function simply returns the wrong answer for anything wider than a \
|
||||
flag. Verible's `explicit-function-task-parameter-type` (\"Checks \
|
||||
that every function and task parameter is declared with an explicit \
|
||||
storage type.\", enabled by default) is the same rule and the same \
|
||||
default. **A continuation formal inherits**: in `f(input int a, b)` \
|
||||
the `b` is an `int`, so only the argument that *opens* a declaration \
|
||||
— the first one, or the first after a direction keyword — is judged, \
|
||||
which is exactly the language's own rule. A DPI import's unnamed \
|
||||
formal (`import \"DPI-C\" function int f(int);`) names a type and no \
|
||||
identifier and is not this rule's subject. No automatic fix: only the \
|
||||
author knows how wide the argument was meant to be."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_items(ctx.file(), &mut |item| {
|
||||
let (kw, args) = match &item.kind {
|
||||
ItemKind::Function(decl) => ("function", &decl.args),
|
||||
ItemKind::Task(decl) => ("task", &decl.args),
|
||||
_ => return,
|
||||
};
|
||||
out.extend(untyped(kw, args));
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The formals of one argument list that end up implicitly typed.
|
||||
///
|
||||
/// Walked in order with the declaration's type carried along, which is how the
|
||||
/// language reads them: a formal that writes a type sets it, a formal that
|
||||
/// writes a direction keyword opens a new declaration (and so a new type,
|
||||
/// implicit until written), and a formal that writes neither inherits whatever
|
||||
/// is in force.
|
||||
fn untyped(kw: &'static str, args: &[ListElem<TfArg>]) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
let mut opened = false;
|
||||
for arg in args.iter().filter_map(ListElem::ok) {
|
||||
let opens = !opened || arg.dir.is_some() || !arg.ty.is_implicit();
|
||||
opened = true;
|
||||
if !opens || !arg.ty.is_implicit() || arg.name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!("{kw} argument `{}` has no storage type; it is a 1-bit `logic`", arg.name),
|
||||
arg.span,
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
ExplicitFunctionTaskParameterType.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn wrap(header: &str) -> String {
|
||||
format!("module m;\n {header}\n endfunction\nendmodule\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_an_untyped_formal() {
|
||||
let src = wrap("function void f(input a);");
|
||||
let found = violations(&src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("`a`"), "{}", found[0].message);
|
||||
assert!(found[0].message.contains("1-bit"), "{}", found[0].message);
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typed_formal_is_what_the_rule_wants() {
|
||||
for header in [
|
||||
"function void f(input logic a);",
|
||||
"function void f(input int a);",
|
||||
"function void f(input logic [7:0] a);",
|
||||
"function void f(my_t a);",
|
||||
"function void f();",
|
||||
] {
|
||||
assert!(
|
||||
violations(&wrap(header)).is_empty(),
|
||||
"{header}: {:?}",
|
||||
violations(&wrap(header))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_continuation_formal_inherits_the_type_before_it() {
|
||||
// `b` is an `int`, so only a genuinely untyped run may be reported.
|
||||
assert!(violations(&wrap("function void f(input int a, b);")).is_empty());
|
||||
// ... and a new direction keyword opens a new, untyped declaration.
|
||||
let found = violations(&wrap("function void f(input int a, output b);"));
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("`b`"), "{}", found[0].message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_task_is_judged_the_same_way() {
|
||||
let src = "module m;\n task t(input a);\n endtask\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("task"), "{}", found[0].message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unnamed_dpi_formal_is_not_this_rules_subject() {
|
||||
let src = "import \"DPI-C\" function int f(int, chandle);\n";
|
||||
assert!(violations(src).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_class_method_is_reached() {
|
||||
let src = "class c;\n function void f(input a);\n endfunction\nendclass\n";
|
||||
assert_eq!(violations(src).len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
|
||||
use vlog_parser::ast::{ItemKind, ParamDecl, StmtKind};
|
||||
@@ -20,6 +21,10 @@ impl Rule for ExplicitParameterStorageType {
|
||||
"declare a storage type on every parameter"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A parameter with no declared type takes its type from whatever it is \
|
||||
assigned — and an override at instantiation can change that type, not \
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
//! `forbid-defparam` — `defparam` is deprecated; override at instantiation.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_items;
|
||||
use vlog_parser::ast::ItemKind;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct ForbidDefparam;
|
||||
|
||||
const NAME: &str = "forbid-defparam";
|
||||
|
||||
impl Rule for ForbidDefparam {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"override a parameter at the instantiation, not with `defparam`"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"`defparam` reaches into another scope and changes a parameter there, \
|
||||
so the value a module elaborates with is written somewhere the module \
|
||||
does not name and a reader has no way to find without grepping the \
|
||||
whole design. It was deprecated in IEEE 1800-2009 (§A.11, and the LRM \
|
||||
says it may be removed from a future revision), several synthesis \
|
||||
tools reject it outright, and the `#(.NAME(value))` override at the \
|
||||
instantiation says the same thing where the instance is. Verible's \
|
||||
`forbid-defparam` (\"Do not use defparam.\", enabled by default) is \
|
||||
the same rule. No automatic fix: moving the value to the right \
|
||||
instantiation needs the instantiation, which may be in another file."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_items(ctx.file(), &mut |item| {
|
||||
if matches!(item.kind, ItemKind::Defparam(_)) {
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
"`defparam` is deprecated; override the parameter at its instantiation",
|
||||
item.span,
|
||||
));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
ForbidDefparam.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_defparam_wherever_it_stands() {
|
||||
let src = "module m;\n sub u ();\n defparam u.WIDTH = 8;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "defparam u.WIDTH = 8;");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_override_is_what_the_rule_wants() {
|
||||
assert!(violations("module m;\n sub #(.WIDTH(8)) u ();\nendmodule\n").is_empty());
|
||||
// Nor is a parameter declaration one.
|
||||
assert!(violations("module m;\n parameter int WIDTH = 8;\nendmodule\n").is_empty());
|
||||
// And a signal that merely spells the word is not one either.
|
||||
assert!(violations("module m;\n logic defparam_n;\nendmodule\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_defparam_inside_generate_is_reached() {
|
||||
let src = "module m;\n\
|
||||
generate\n\
|
||||
if (A) begin : g\n\
|
||||
defparam u.W = 1;\n\
|
||||
end\n\
|
||||
endgenerate\n\
|
||||
endmodule\n";
|
||||
assert_eq!(violations(src).len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
//! `forbid-negative-array-dim` — a negative literal inside a dimension.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::decls::walk_dims;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::ast::{DimKind, Expr, ExprKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct ForbidNegativeArrayDim;
|
||||
|
||||
const NAME: &str = "forbid-negative-array-dim";
|
||||
|
||||
impl Rule for ForbidNegativeArrayDim {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"do not write a negative constant in a dimension"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"`logic q [-1]` and `logic [-1:0] v` are what a parameter that came \
|
||||
out zero or one too small looks like after the subtraction: \
|
||||
`[WIDTH-1:0]` with `WIDTH = 0` is `[-1:0]`, which tools variously \
|
||||
reject, treat as empty, or size as two bits. Written as a literal it \
|
||||
is never intentional. Verible's `forbid-negative-array-dim` (\"Check \
|
||||
for negative constant literals inside array dimensions.\") is the \
|
||||
same rule; **lucisv turns it on by default where Verible ships it \
|
||||
off**, because a negative literal spelled out in a dimension has no \
|
||||
legitimate reading. Only a written `-<literal>` is flagged — an \
|
||||
expression that would *evaluate* negative needs the parameter values, \
|
||||
which lucisv does not have. No automatic fix."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_dims(ctx.file(), &mut |_, dim| {
|
||||
let DimKind::Range { a, b } = &dim.kind else { return };
|
||||
for expr in [Some(a), b.as_ref()].into_iter().flatten() {
|
||||
for span in negative_literals(expr) {
|
||||
out.push(Violation::new(NAME, "negative constant in a dimension", span));
|
||||
}
|
||||
}
|
||||
});
|
||||
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The spans of every written `-<literal>` inside `expr`.
|
||||
///
|
||||
/// A whole expression tree rather than the top node alone, because the shape
|
||||
/// that turns up in real code is `[-1:0]` on one side and `[WIDTH-1:-1]` on
|
||||
/// the other, and the offending term can sit anywhere in an arithmetic
|
||||
/// expression.
|
||||
fn negative_literals(expr: &Expr) -> Vec<TextRange> {
|
||||
let mut out = Vec::new();
|
||||
collect(expr, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
fn collect(expr: &Expr, out: &mut Vec<TextRange>) {
|
||||
match &expr.kind {
|
||||
ExprKind::Unary { op, expr: inner, .. } => {
|
||||
if op == "-" && matches!(inner.kind, ExprKind::Number(_)) {
|
||||
out.push(expr.span);
|
||||
return;
|
||||
}
|
||||
collect(inner, out);
|
||||
}
|
||||
ExprKind::Binary { lhs, rhs, .. } => {
|
||||
collect(lhs, out);
|
||||
collect(rhs, out);
|
||||
}
|
||||
ExprKind::Paren { inner, .. } => collect(inner, out),
|
||||
ExprKind::Ternary { cond, then, els, .. } => {
|
||||
collect(cond, out);
|
||||
collect(then, out);
|
||||
collect(els, out);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
ForbidNegativeArrayDim.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_negative_packed_bound() {
|
||||
let src = "module m;\n logic [-1:0] v;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "-1");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_negative_unpacked_extent_and_one_buried_in_arithmetic() {
|
||||
assert_eq!(violations("module m;\n logic q [-1];\nendmodule\n").len(), 1);
|
||||
assert_eq!(violations("module m;\n logic [W + -2:0] v;\nendmodule\n").len(), 1);
|
||||
// Both ends count.
|
||||
assert_eq!(violations("module m;\n logic [-1:-2] v;\nendmodule\n").len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_dimensions_are_silent() {
|
||||
for decl in [
|
||||
"logic [7:0] v;",
|
||||
"logic [WIDTH-1:0] v;",
|
||||
"logic q [4];",
|
||||
"logic q [0:3];",
|
||||
"logic v;",
|
||||
"logic q [];",
|
||||
] {
|
||||
let src = format!("module m;\n {decl}\nendmodule\n");
|
||||
assert!(violations(&src).is_empty(), "{decl}: {:?}", violations(&src));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_negative_outside_a_dimension_is_not_this_rules_business() {
|
||||
assert!(violations("module m;\n assign x = -1;\nendmodule\n").is_empty());
|
||||
assert!(violations("module m;\n parameter int P = -1;\nendmodule\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_subtraction_is_not_a_negative_literal() {
|
||||
// `WIDTH-1` is the ordinary way to write a width and must never fire.
|
||||
assert!(violations("module m;\n logic [WIDTH-1:0] v;\nendmodule\n").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
//! `incomplete-assignment` — a latch inferred in an `always_comb`.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::{walk_items, walk_stmts};
|
||||
use vlog_parser::ast::{Expr, ExprKind, ItemKind, Stmt, StmtKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct IncompleteAssignment;
|
||||
|
||||
const NAME: &str = "incomplete-assignment";
|
||||
|
||||
impl Rule for IncompleteAssignment {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"assign every variable on every path of an always_comb"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A variable an `always_comb` writes on some paths and not on others \
|
||||
has to *hold its value* on the others, and holding a value is a \
|
||||
latch: the synthesized circuit grows storage nobody asked for, the \
|
||||
timing closes differently, and in simulation the block reads back \
|
||||
whatever it left there last time. `always_comb` was added to the \
|
||||
language precisely so tools could catch this, and most of them do — \
|
||||
but only at elaboration, long after the edit. There is no Verible \
|
||||
equivalent; this is TODO §33's own rule.\n\n\
|
||||
**Conservative by construction.** It speaks only about the \
|
||||
*top level* of an `always_comb` body, and only in the two shapes that \
|
||||
are unambiguous: an `if` with no `else`, and a `case` with no \
|
||||
`default`. A variable is reported only when the block writes it \
|
||||
inside such a statement and nothing **earlier in the block** already \
|
||||
covered it — where covering it means a plain assignment (a partial \
|
||||
one, through a bit select or a field, counts), or an `if`/`else` or a \
|
||||
`case` with a `default` that writes it in *every* arm. That last one \
|
||||
is the usual style, and the usual repair is the other: a default \
|
||||
assignment at the top of the block.\n\n\
|
||||
Everything else stays silent, deliberately: a name the block \
|
||||
**declares for itself** (a local temporary is not a latched output), \
|
||||
a left-hand side that is not a plain name or a concatenation of them, \
|
||||
a conditional nested inside another, and every `always` that is not \
|
||||
an `always_comb`. Measured on opentitan: three findings before those \
|
||||
exemptions, all three false, none after. No automatic fix: what the \
|
||||
missing branch should assign is a design decision."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_items(ctx.file(), &mut |item| {
|
||||
let ItemKind::Always { kw, stmt } = &item.kind else { return };
|
||||
if kw != "always_comb" {
|
||||
return;
|
||||
}
|
||||
out.extend(latches(ctx.source(), stmt));
|
||||
});
|
||||
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The findings of one `always_comb` body.
|
||||
fn latches(source: &str, body: &Stmt) -> Vec<Violation> {
|
||||
// Names the block declares for itself are never reported: a temporary
|
||||
// written inside the branch it was declared in is a local, not a latched
|
||||
// output, and deciding which of the two it is needs elaboration.
|
||||
let local = declared_names(body);
|
||||
let mut covered: BTreeSet<String> = BTreeSet::new();
|
||||
let mut out = Vec::new();
|
||||
for stmt in top_level(body) {
|
||||
match &stmt.kind {
|
||||
// Any write at all counts as coverage, a partial one included: a
|
||||
// block that sets `cfg.mode` at the top and the whole `cfg` under
|
||||
// an `if` has written the variable before the branch.
|
||||
StmtKind::Assign { lhs, .. } => covered.extend(written_names(lhs)),
|
||||
StmtKind::If { cond, then, els: None, .. } => {
|
||||
let at = header(source, stmt.span, cond.span);
|
||||
report(&mut out, &covered, &local, at, branch_names(then));
|
||||
}
|
||||
// An `if` with an `else`, and a `case` with a `default`, cover
|
||||
// every name their branches agree on — which is how the usual
|
||||
// "assign it in every arm" style is written.
|
||||
StmtKind::If { then, els: Some(els), .. } => {
|
||||
covered.extend(intersect(&[branch_names(then), branch_names(els)]));
|
||||
}
|
||||
StmtKind::Case { expr, items, .. } => {
|
||||
let per_branch: Vec<BTreeSet<String>> =
|
||||
items.iter().map(|item| branch_names(&item.stmt)).collect();
|
||||
if items.iter().any(|item| item.labels.is_empty()) {
|
||||
covered.extend(intersect(&per_branch));
|
||||
} else {
|
||||
let mut names = BTreeSet::new();
|
||||
for branch in &per_branch {
|
||||
names.extend(branch.iter().cloned());
|
||||
}
|
||||
let at = header(source, stmt.span, expr.span);
|
||||
report(&mut out, &covered, &local, at, names);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The names every one of these branches writes.
|
||||
fn intersect(branches: &[BTreeSet<String>]) -> BTreeSet<String> {
|
||||
let Some((first, rest)) = branches.split_first() else { return BTreeSet::new() };
|
||||
first.iter().filter(|name| rest.iter().all(|set| set.contains(*name))).cloned().collect()
|
||||
}
|
||||
|
||||
/// Every name the block declares anywhere inside itself.
|
||||
fn declared_names(body: &Stmt) -> BTreeSet<String> {
|
||||
let mut names = BTreeSet::new();
|
||||
walk_stmts(body, &mut |stmt| {
|
||||
if let StmtKind::VarDecl(decl) = &stmt.kind {
|
||||
names.extend(decl.declarators.iter().map(|d| d.name.clone()));
|
||||
}
|
||||
});
|
||||
names
|
||||
}
|
||||
|
||||
/// The statements written directly in the body — the body itself when it is
|
||||
/// one statement, and a `begin ... end`'s own list when it is a block.
|
||||
fn top_level(body: &Stmt) -> Vec<&Stmt> {
|
||||
match &body.kind {
|
||||
StmtKind::Block { stmts, .. } => stmts.iter().collect(),
|
||||
// The body of an `always_comb` carries no timing control of its own,
|
||||
// so anything else is a single statement standing as the whole block.
|
||||
_ => vec![body],
|
||||
}
|
||||
}
|
||||
|
||||
/// Every plain name a branch assigns, however deep inside it.
|
||||
fn branch_names(stmt: &Stmt) -> BTreeSet<String> {
|
||||
let mut names = BTreeSet::new();
|
||||
walk_stmts(stmt, &mut |inner| {
|
||||
if let StmtKind::Assign { lhs, .. } = &inner.kind {
|
||||
names.extend(assigned_name(lhs));
|
||||
}
|
||||
});
|
||||
names
|
||||
}
|
||||
|
||||
/// Adds one finding per name the branch writes that nothing covered before it
|
||||
/// and that the block does not declare for itself.
|
||||
fn report(
|
||||
out: &mut Vec<Violation>,
|
||||
covered: &BTreeSet<String>,
|
||||
local: &BTreeSet<String>,
|
||||
span: TextRange,
|
||||
names: BTreeSet<String>,
|
||||
) {
|
||||
for name in names {
|
||||
if covered.contains(&name) || local.contains(&name) {
|
||||
continue;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!("`{name}` is not assigned on every path; this infers a latch"),
|
||||
span,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// The `if (cond)` / `case (subject)` header alone, so a whole branch is not
|
||||
/// painted red for a problem that lives on one line. The subject's own span
|
||||
/// stops inside the parentheses, so the underline runs on to the `)` that
|
||||
/// closes it — the same shape `case-missing-default` underlines.
|
||||
fn header(source: &str, stmt: TextRange, subject: TextRange) -> TextRange {
|
||||
let close = source
|
||||
.get(subject.end as usize..)
|
||||
.and_then(|rest| rest.find(')'))
|
||||
.map(|i| subject.end + i as u32 + 1)
|
||||
.unwrap_or(subject.end);
|
||||
TextRange::new(stmt.start, close.max(stmt.start))
|
||||
}
|
||||
|
||||
/// The plain name a left-hand side writes, or nothing when the target is not
|
||||
/// one identifier.
|
||||
///
|
||||
/// A bit or field select (`x[3] = …`, `s.f = …`) writes *part* of a variable,
|
||||
/// and deciding whether the rest is covered needs ranges resolved — so those
|
||||
/// are not names this rule will accuse. A concatenation lvalue is every name
|
||||
/// in it, each of which is written whole.
|
||||
fn assigned_name(lhs: &Expr) -> Vec<String> {
|
||||
match &lhs.kind {
|
||||
ExprKind::Ident(name) => vec![name.clone()],
|
||||
ExprKind::Concat(items) => {
|
||||
items.iter().flat_map(|item| assigned_name(&item.expr)).collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every name a left-hand side touches, a *part* of one included.
|
||||
///
|
||||
/// The wider question — "was this variable written here at all?" — which is
|
||||
/// what the coverage set wants: a block that writes `cfg.mode` before an `if`
|
||||
/// that writes the whole `cfg` has already spoken for `cfg`, and reporting it
|
||||
/// would be a latch that is not there.
|
||||
fn written_names(lhs: &Expr) -> Vec<String> {
|
||||
match &lhs.kind {
|
||||
ExprKind::Ident(name) => vec![name.clone()],
|
||||
ExprKind::Concat(items) => {
|
||||
items.iter().flat_map(|item| written_names(&item.expr)).collect()
|
||||
}
|
||||
ExprKind::Index { base, .. }
|
||||
| ExprKind::Range { base, .. }
|
||||
| ExprKind::Member { base, .. } => written_names(base),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
IncompleteAssignment.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn wrap(body: &str) -> String {
|
||||
format!("module m;\n always_comb begin\n{body} end\nendmodule\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_variable_written_only_under_an_if() {
|
||||
let src = wrap(" if (en) y = a;\n");
|
||||
let found = violations(&src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("`y`"), "{}", found[0].message);
|
||||
assert_eq!(&src[found[0].span.as_range()], "if (en)", "the header, not the branch");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_default_assignment_before_the_if_is_the_repair() {
|
||||
assert!(violations(&wrap(" y = 1'b0;\n if (en) y = a;\n")).is_empty());
|
||||
// ... and it must come *before*: assigning after the `if` does not
|
||||
// stop the branch from inferring one.
|
||||
assert_eq!(violations(&wrap(" if (en) y = a;\n y = 1'b0;\n")).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_if_with_an_else_covers_every_path() {
|
||||
assert!(violations(&wrap(" if (en) y = a; else y = b;\n")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_case_without_default_is_flagged_and_one_with_it_is_not() {
|
||||
let with_default = " case (s)\n 0: y = a;\n default: y = b;\n endcase\n";
|
||||
assert!(violations(&wrap(with_default)).is_empty());
|
||||
let without = " case (s)\n 0: y = a;\n 1: y = b;\n endcase\n";
|
||||
let found = violations(&wrap(without));
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("`y`"), "{}", found[0].message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_variable_of_a_branch_is_named_once() {
|
||||
let found = violations(&wrap(" if (en) begin\n y = a;\n z = b;\n end\n"));
|
||||
assert_eq!(found.len(), 2, "{found:?}");
|
||||
assert!(found[0].message.contains("`y`") || found[0].message.contains("`z`"));
|
||||
// And a variable written twice in the branch is still one finding.
|
||||
let twice = violations(&wrap(" if (en) begin\n y = a;\n y = b;\n end\n"));
|
||||
assert_eq!(twice.len(), 1, "{twice:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_always_comb_is_judged() {
|
||||
for kw in ["always", "always_ff", "always_latch"] {
|
||||
let src = format!("module m;\n {kw} @(posedge clk) if (en) y <= a;\nendmodule\n");
|
||||
assert!(violations(&src).is_empty(), "{kw}");
|
||||
}
|
||||
assert!(violations("module m;\n always @* if (en) y = a;\nendmodule\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_partial_write_is_not_accused() {
|
||||
// Deciding whether the other bits are covered needs ranges resolved,
|
||||
// which this rule does not do.
|
||||
assert!(violations(&wrap(" if (en) y[3] = a;\n")).is_empty());
|
||||
assert!(violations(&wrap(" if (en) s.f = a;\n")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_concatenation_lvalue_names_every_target() {
|
||||
let found = violations(&wrap(" if (en) {y, z} = a;\n"));
|
||||
assert_eq!(found.len(), 2, "{found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nested_conditional_is_left_to_the_top_level_one() {
|
||||
// The outer `if` has an `else`, so the block covers every path as far
|
||||
// as this rule is willing to claim.
|
||||
let src = wrap(" if (en) begin\n if (x) y = a;\n end else y = b;\n");
|
||||
assert!(violations(&src).is_empty());
|
||||
}
|
||||
|
||||
/// The three shapes the opentitan census turned up as false positives, each
|
||||
/// pinned so it stays quiet.
|
||||
#[test]
|
||||
fn the_shapes_that_are_not_latches_stay_quiet() {
|
||||
// 1. A variable the block declares for itself, written in the branch
|
||||
// it was declared in (`entropy_src_core.sv`).
|
||||
let local = wrap(" if (en) begin\n logic [3:0] tmp;\n tmp = a;\n end\n");
|
||||
assert!(violations(&local).is_empty(), "{:?}", violations(&local));
|
||||
|
||||
// 2. A partial write before the branch covers the variable
|
||||
// (`kmac_app.sv`).
|
||||
let partial = wrap(" cfg.mode = a;\n if (en) cfg = b;\n");
|
||||
assert!(violations(&partial).is_empty(), "{:?}", violations(&partial));
|
||||
|
||||
// 3. A `case` with a `default` that writes it in every arm, followed
|
||||
// by an `if` that writes it again (`ibex_alu.sv`).
|
||||
let after_case = wrap(
|
||||
" case (s)\n 0: y = a;\n default: y = b;\n endcase\n\
|
||||
\x20 if (en) y = 1'b1;\n",
|
||||
);
|
||||
assert!(violations(&after_case).is_empty(), "{:?}", violations(&after_case));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_if_else_before_the_branch_also_covers_it() {
|
||||
let src = wrap(" if (a) y = 1; else y = 0;\n if (en) y = 2;\n");
|
||||
assert!(violations(&src).is_empty(), "{:?}", violations(&src));
|
||||
// ... but only for the names *both* arms write.
|
||||
let partial = wrap(" if (a) y = 1; else z = 0;\n if (en) y = 2;\n");
|
||||
assert_eq!(violations(&partial).len(), 1, "{:?}", violations(&partial));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_body_that_is_one_statement_is_still_a_body() {
|
||||
let src = "module m;\n always_comb if (en) y = a;\nendmodule\n";
|
||||
assert_eq!(violations(src).len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
//! `instance-shadowing` — a declaration hiding one from an enclosing scope.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_semantic::{Scope, ScopeKind, Semantics, SymbolKind};
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct InstanceShadowing;
|
||||
|
||||
const NAME: &str = "instance-shadowing";
|
||||
|
||||
impl Rule for InstanceShadowing {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"do not hide an enclosing declaration with a new one of the same name"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A `logic count;` inside a `begin : blk` where the module already has \
|
||||
a `count` compiles, and from then on every mention of `count` inside \
|
||||
the block means the inner one — including the ones written before the \
|
||||
inner declaration was added, which is how this arrives in a review \
|
||||
diff that looks like it changed nothing. Verible's `instance-\
|
||||
shadowing` (\"Warns if there are multiple declarations in the same \
|
||||
scope that shadow each other with the same name.\") is the same rule; \
|
||||
**lucisv turns it on by default where Verible ships it off**, because \
|
||||
the finding is always worth a second look and the repair is a rename \
|
||||
in one block.\n\n\
|
||||
Only the scopes **inside one design unit** are compared: a module, a \
|
||||
package or a class opens a fresh namespace, and a signal called `data` \
|
||||
in two different modules shadows nothing. A generate scope is \
|
||||
compared like any other block — the shadowing is real there too. No \
|
||||
automatic fix: renaming reaches every use inside the block."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
// Shadowing is a claim about *which scope* a name was declared in,
|
||||
// and error recovery moves declarations between scopes — so a file
|
||||
// that did not fully parse gets no opinion, exactly as
|
||||
// `duplicate-declaration` gives it none.
|
||||
if !ctx.parsed_cleanly() {
|
||||
return Vec::new();
|
||||
}
|
||||
let semantics = ctx.semantics();
|
||||
let mut out = Vec::new();
|
||||
for scope in semantics.scopes() {
|
||||
if opens_a_unit(scope.kind) {
|
||||
continue;
|
||||
}
|
||||
for &id in &scope.symbols {
|
||||
let Some(symbol) = semantics.symbol(id) else { continue };
|
||||
let Some(hidden) = shadowed(semantics, scope, &symbol.name) else { continue };
|
||||
if !judged(symbol.kind) {
|
||||
continue;
|
||||
}
|
||||
// The two are exclusive when a conditional-compilation
|
||||
// directive stands between them, exactly as they are for
|
||||
// `duplicate-declaration`.
|
||||
if ctx.signals().conditional_between(&[hidden, symbol.name_span.start]) {
|
||||
continue;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!(
|
||||
"`{}` shadows a declaration of the same name outside this scope",
|
||||
symbol.name
|
||||
),
|
||||
symbol.name_span,
|
||||
));
|
||||
}
|
||||
}
|
||||
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The name span of the enclosing declaration `name` hides, if there is one
|
||||
/// **within the same design unit**.
|
||||
///
|
||||
/// The walk stops at the scope that opens a unit — a module, package or class
|
||||
/// body — because a name declared in a different unit is reached by a
|
||||
/// qualified path, never by shadowing.
|
||||
fn shadowed(semantics: &Semantics, scope: &Scope, name: &str) -> Option<u32> {
|
||||
let mut parent = scope.parent;
|
||||
while let Some(id) = parent {
|
||||
let outer = semantics.scope(id)?;
|
||||
if let Some(hidden) = outer.lookup_local(name) {
|
||||
return semantics.symbol(hidden).map(|symbol| symbol.name_span.start);
|
||||
}
|
||||
if opens_a_unit(outer.kind) {
|
||||
return None;
|
||||
}
|
||||
parent = outer.parent;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// True for the scopes that open a design unit's own namespace.
|
||||
fn opens_a_unit(kind: ScopeKind) -> bool {
|
||||
matches!(kind, ScopeKind::File | ScopeKind::Module | ScopeKind::Package | ScopeKind::Class)
|
||||
}
|
||||
|
||||
/// True for the declarations worth reporting.
|
||||
///
|
||||
/// A subroutine argument named after an enclosing signal is idiomatic
|
||||
/// (`function automatic f(input logic clk)`), a block label is not a value,
|
||||
/// and a `genvar` is scoped to its own loop by construction — so those stay
|
||||
/// out. What is left is data and instances, which is where the surprise is.
|
||||
fn judged(kind: SymbolKind) -> bool {
|
||||
matches!(
|
||||
kind,
|
||||
SymbolKind::Net | SymbolKind::Var | SymbolKind::Instance | SymbolKind::LocalParam
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
InstanceShadowing.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_block_local_that_hides_a_module_signal() {
|
||||
let src = "module m;\n\
|
||||
logic count;\n\
|
||||
always_comb begin : blk\n\
|
||||
logic count;\n\
|
||||
count = 1'b0;\n\
|
||||
end\n\
|
||||
endmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("`count`"), "{}", found[0].message);
|
||||
assert!(found[0].span.start as usize > src.find("blk").unwrap_or(0), "the inner one");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_declared_once_is_never_flagged() {
|
||||
let src = "module m;\n\
|
||||
logic count;\n\
|
||||
always_comb begin : blk\n\
|
||||
logic other;\n\
|
||||
end\n\
|
||||
endmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_different_unit_shadows_nothing() {
|
||||
let src = "module a;\n logic data;\nendmodule\nmodule b;\n logic data;\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
// Nor does a package-level name reached from a module.
|
||||
let pkg = "package p;\n logic data;\nendpackage\nmodule m;\n logic data;\nendmodule\n";
|
||||
assert!(violations(pkg).is_empty(), "{:?}", violations(pkg));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generate_block_is_compared_like_any_other() {
|
||||
let src = "module m;\n\
|
||||
logic x;\n\
|
||||
generate\n\
|
||||
if (A) begin : g\n\
|
||||
logic x;\n\
|
||||
end\n\
|
||||
endgenerate\n\
|
||||
endmodule\n";
|
||||
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_subroutine_argument_named_after_a_signal_is_idiomatic() {
|
||||
let src = "module m;\n\
|
||||
logic clk;\n\
|
||||
function automatic void f(input logic clk);\n\
|
||||
endfunction\n\
|
||||
endmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conditional_arms_are_exclusive() {
|
||||
let src = "module m;\n\
|
||||
logic x;\n\
|
||||
always_comb begin : blk\n\
|
||||
`ifdef A\n\
|
||||
logic x;\n\
|
||||
`endif\n\
|
||||
end\n\
|
||||
endmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//! `invalid-system-task-function` — system tasks nothing should still call.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::token::TokenKind;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct InvalidSystemTaskFunction;
|
||||
|
||||
const NAME: &str = "invalid-system-task-function";
|
||||
|
||||
/// The forbidden names and what to write instead — Verible's list
|
||||
/// (`invalid-system-task-function`), name for name.
|
||||
///
|
||||
/// The `$dist_*` family and `$random` all draw from the *global* seed that
|
||||
/// `$random` shares, so one extra call anywhere in a testbench reshuffles
|
||||
/// every other stream; `$urandom` and `$urandom_range` are per-thread and
|
||||
/// reproducible. `$psprintf` is a vendor extension for the standard
|
||||
/// `$sformatf`, and `$srandom` seeds that same global generator rather than
|
||||
/// the calling process.
|
||||
const FORBIDDEN: &[(&str, &str)] = &[
|
||||
("$psprintf", "$sformatf"),
|
||||
("$random", "$urandom"),
|
||||
("$srandom", "process::self().srandom()"),
|
||||
("$dist_chi_square", "$urandom"),
|
||||
("$dist_erlang", "$urandom"),
|
||||
("$dist_exponential", "$urandom"),
|
||||
("$dist_normal", "$urandom"),
|
||||
("$dist_poisson", "$urandom"),
|
||||
("$dist_t", "$urandom"),
|
||||
("$dist_uniform", "$urandom"),
|
||||
];
|
||||
|
||||
impl Rule for InvalidSystemTaskFunction {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"do not call a deprecated or non-reproducible system task"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"`$random`, `$srandom` and the `$dist_*` family all draw from one \
|
||||
global generator, so adding a call anywhere in a testbench reshuffles \
|
||||
every other random stream in it and a failing seed stops reproducing \
|
||||
— the reason IEEE 1800 added the per-process `$urandom` / \
|
||||
`$urandom_range` and `process::self().srandom()`. `$psprintf` is a \
|
||||
vendor spelling of the standard `$sformatf` and is not portable. \
|
||||
Verible's `invalid-system-task-function` (\"Checks that no forbidden \
|
||||
system tasks or functions are used.\", enabled by default) forbids \
|
||||
exactly this list, and lucisv names the replacement in the message. \
|
||||
No automatic fix: `$random` and `$urandom` return different value \
|
||||
streams, so swapping them changes what the test does."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
ctx.tokens()
|
||||
.iter()
|
||||
.filter(|token| token.kind == TokenKind::SystemIdent)
|
||||
.filter_map(|token| {
|
||||
let (name, instead) =
|
||||
FORBIDDEN.iter().find(|(name, _)| *name == token.text.as_str())?;
|
||||
Some(Violation::new(
|
||||
NAME,
|
||||
format!("`{name}` is forbidden; use `{instead}`"),
|
||||
token.span,
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
InvalidSystemTaskFunction.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_every_forbidden_name_and_says_what_to_use() {
|
||||
for (name, instead) in FORBIDDEN {
|
||||
let src = format!("module m;\n initial x = {name}();\nendmodule\n");
|
||||
let found = violations(&src);
|
||||
assert_eq!(found.len(), 1, "{name}: {found:?}");
|
||||
assert!(found[0].message.contains(name), "{}", found[0].message);
|
||||
assert!(found[0].message.contains(instead), "{}", found[0].message);
|
||||
assert_eq!(&src[found[0].span.as_range()], *name, "the call, underlined");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_replacements_and_their_neighbours_are_left_alone() {
|
||||
let src = "module m;\n\
|
||||
initial begin\n\
|
||||
a = $urandom();\n\
|
||||
b = $urandom_range(0, 7);\n\
|
||||
c = $sformatf(\"%0d\", a);\n\
|
||||
$display(\"%0d\", b);\n\
|
||||
end\n\
|
||||
endmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_near_miss_name_is_not_a_hit() {
|
||||
// Matched whole, not by prefix: `$random_stable` and a signal called
|
||||
// `random` are neither of them `$random`.
|
||||
let src = "module m;\n\
|
||||
logic random;\n\
|
||||
initial begin\n\
|
||||
a = $randomize_helper();\n\
|
||||
b = random;\n\
|
||||
end\n\
|
||||
endmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_forbidden_name_inside_a_string_is_data() {
|
||||
let src = "module m;\n initial $display(\"call $random here\");\nendmodule\n";
|
||||
assert!(violations(src).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
//! `mismatched-labels` — an end label that does not name its own block.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::{walk_all_stmts, walk_items};
|
||||
use vlog_parser::ast::{GenBlock, GenElse, Item, ItemKind, Name, StmtKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct MismatchedLabels;
|
||||
|
||||
const NAME: &str = "mismatched-labels";
|
||||
|
||||
impl Rule for MismatchedLabels {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"make an end label name the block it closes"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Error
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"`begin : fetch … end : decode` is a compile error (IEEE 1800 §9.3.4: \
|
||||
if both labels are given they must be identical), and so is an \
|
||||
`end : name` on a block that was never labelled. It is the classic \
|
||||
result of copying a block and renaming only one half — which is also \
|
||||
why it survives review: the two halves are pages apart. Verible's \
|
||||
`mismatched-labels` (\"Check for matching begin/end labels.\") is the \
|
||||
same rule; **lucisv turns it on by default where Verible ships it \
|
||||
off**, and files it as an **Error** rather than a style finding, \
|
||||
because the file does not compile.\n\n\
|
||||
Every construct that may carry a footer label is checked with one \
|
||||
answer: `module`/`interface`/`program`, `package`, `class`, \
|
||||
`function`, `task`, `begin`, `fork`/`join`, a generate block, a \
|
||||
`clocking` block, a `covergroup`, and a `property`/`sequence`. It is \
|
||||
a comparison of two spellings and nothing more, so an escaped \
|
||||
identifier is compared as written. No automatic fix: which of the two \
|
||||
names is the right one is exactly what a linter cannot know."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_items(ctx.file(), &mut |item| item_labels(&mut out, item));
|
||||
walk_all_stmts(ctx.file(), &mut |stmt| match &stmt.kind {
|
||||
StmtKind::Block { label, end_label, end_label_span, .. } => {
|
||||
check_pair(&mut out, label.as_deref(), end_label.as_deref(), *end_label_span, "end")
|
||||
}
|
||||
StmtKind::ForkJoin { label, end_label, end_label_span, .. } => check_pair(
|
||||
&mut out,
|
||||
label.as_deref(),
|
||||
end_label.as_deref(),
|
||||
*end_label_span,
|
||||
"join",
|
||||
),
|
||||
_ => {}
|
||||
});
|
||||
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The label pair one item carries, checked. One arm per construct that may
|
||||
/// write a footer label, so a construct that gains one later has an obvious
|
||||
/// place to go.
|
||||
fn item_labels(out: &mut Vec<Violation>, item: &Item) {
|
||||
match &item.kind {
|
||||
ItemKind::Module(module) => check_pair(
|
||||
out,
|
||||
Some(&module.name),
|
||||
module.end_label.as_deref(),
|
||||
module.end_label_span,
|
||||
match module.kw.as_str() {
|
||||
"interface" => "endinterface",
|
||||
"program" => "endprogram",
|
||||
_ => "endmodule",
|
||||
},
|
||||
),
|
||||
ItemKind::Package { name, end_label, end_label_span, .. } => {
|
||||
check_pair(out, Some(name), end_label.as_deref(), *end_label_span, "endpackage")
|
||||
}
|
||||
ItemKind::Class(class) => check_pair(
|
||||
out,
|
||||
Some(&class.name),
|
||||
class.end_label.as_deref(),
|
||||
class.end_label_span,
|
||||
"endclass",
|
||||
),
|
||||
ItemKind::Function(decl) => check_pair(
|
||||
out,
|
||||
Some(&decl.name),
|
||||
decl.end_label.as_deref(),
|
||||
decl.end_label_span,
|
||||
"endfunction",
|
||||
),
|
||||
ItemKind::Task(decl) => check_pair(
|
||||
out,
|
||||
Some(&decl.name),
|
||||
decl.end_label.as_deref(),
|
||||
decl.end_label_span,
|
||||
"endtask",
|
||||
),
|
||||
ItemKind::Clocking(decl) => check_pair(
|
||||
out,
|
||||
decl.name.as_ref().map(|name| name.text.as_str()),
|
||||
decl.end_label.as_deref(),
|
||||
decl.end_label_span,
|
||||
"endclocking",
|
||||
),
|
||||
ItemKind::Covergroup(decl) => {
|
||||
check_name_pair(out, Some(&decl.name.text), decl.end_label.as_ref(), "endgroup")
|
||||
}
|
||||
ItemKind::PropSeqDecl(decl) => check_name_pair(
|
||||
out,
|
||||
Some(&decl.name.text),
|
||||
decl.end_label.as_ref(),
|
||||
if decl.kw == "sequence" { "endsequence" } else { "endproperty" },
|
||||
),
|
||||
// The item walk descends into a generate block's *items* but never
|
||||
// visits the block itself, so its own label pair is collected here.
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
check_gen_block(out, &gen_if.then);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
while let Some(branch) = els {
|
||||
match branch {
|
||||
GenElse::If(_, nested) => {
|
||||
check_gen_block(out, &nested.then);
|
||||
els = nested.els.as_deref();
|
||||
}
|
||||
GenElse::Block(block) => {
|
||||
check_gen_block(out, block);
|
||||
els = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::GenFor(gen_for) => check_gen_block(out, &gen_for.body),
|
||||
ItemKind::GenCase(gen_case) => {
|
||||
for case_item in &gen_case.items {
|
||||
check_gen_block(out, &case_item.body);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn check_gen_block(out: &mut Vec<Violation>, block: &GenBlock) {
|
||||
check_pair(
|
||||
out,
|
||||
block.label.as_deref(),
|
||||
block.end_label.as_deref(),
|
||||
block.end_label_span,
|
||||
"end",
|
||||
);
|
||||
}
|
||||
|
||||
/// Compares one header/footer pair, when a footer label was written at all.
|
||||
fn check_pair(
|
||||
out: &mut Vec<Violation>,
|
||||
opened: Option<&str>,
|
||||
closed: Option<&str>,
|
||||
at: Option<TextRange>,
|
||||
kw: &'static str,
|
||||
) {
|
||||
let (Some(closed), Some(at)) = (closed, at) else { return };
|
||||
if at.is_empty() {
|
||||
return;
|
||||
}
|
||||
let message = match opened {
|
||||
Some(opened) if opened == closed => return,
|
||||
Some(opened) => format!("`{kw} : {closed}` closes `{opened}`"),
|
||||
None => format!("`{kw} : {closed}` closes a block with no label"),
|
||||
};
|
||||
out.push(Violation::new(NAME, message, at));
|
||||
}
|
||||
|
||||
/// The same, for the constructs whose footer label is a [`Name`].
|
||||
fn check_name_pair(
|
||||
out: &mut Vec<Violation>,
|
||||
opened: Option<&str>,
|
||||
closed: Option<&Name>,
|
||||
kw: &'static str,
|
||||
) {
|
||||
check_pair(
|
||||
out,
|
||||
opened,
|
||||
closed.map(|name| name.text.as_str()),
|
||||
closed.map(|name| name.span),
|
||||
kw,
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
MismatchedLabels.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_footer_that_names_another_block() {
|
||||
let src = "module m;\n\
|
||||
always_comb begin : fetch\n\
|
||||
x = 1;\n\
|
||||
end : decode\n\
|
||||
endmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "decode");
|
||||
assert!(found[0].message.contains("fetch"), "{}", found[0].message);
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_footer_label_on_an_unlabelled_block() {
|
||||
let src = "module m;\n always_comb begin\n x = 1;\n end : blk\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("no label"), "{}", found[0].message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_matching_pair_and_a_missing_footer_are_both_fine() {
|
||||
for src in [
|
||||
"module m;\n always_comb begin : blk\n x = 1;\n end : blk\nendmodule\n",
|
||||
"module m;\n always_comb begin : blk\n x = 1;\n end\nendmodule\n",
|
||||
"module m;\n always_comb begin\n x = 1;\n end\nendmodule\n",
|
||||
"module m;\nendmodule : m\n",
|
||||
] {
|
||||
assert!(violations(src).is_empty(), "{src}: {:?}", violations(src));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_construct_with_a_footer_label_is_checked() {
|
||||
for (src, wrong) in [
|
||||
("module m;\nendmodule : other\n", "other"),
|
||||
("interface i;\nendinterface : other\n", "other"),
|
||||
("package p;\nendpackage : other\n", "other"),
|
||||
("class c;\nendclass : other\n", "other"),
|
||||
("module m;\n function void f();\n endfunction : other\nendmodule\n", "other"),
|
||||
("module m;\n task t();\n endtask : other\nendmodule\n", "other"),
|
||||
(
|
||||
"interface i;\n clocking cb @(posedge clk);\n endclocking : other\nendinterface\n",
|
||||
"other",
|
||||
),
|
||||
(
|
||||
"module m;\n covergroup cg;\n endgroup : other\nendmodule\n",
|
||||
"other",
|
||||
),
|
||||
(
|
||||
"module m;\n property p;\n a |-> b;\n endproperty : other\nendmodule\n",
|
||||
"other",
|
||||
),
|
||||
] {
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{src}: {found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], wrong, "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fork_join_and_a_generate_block_are_checked() {
|
||||
let fork = "module m;\n\
|
||||
initial fork : spawn\n\
|
||||
x = 1;\n\
|
||||
join : other\n\
|
||||
endmodule\n";
|
||||
assert_eq!(violations(fork).len(), 1, "{:?}", violations(fork));
|
||||
|
||||
let generate = "module m;\n\
|
||||
generate\n\
|
||||
if (A) begin : g\n\
|
||||
wire a;\n\
|
||||
end : other\n\
|
||||
endgenerate\n\
|
||||
endmodule\n";
|
||||
assert_eq!(violations(generate).len(), 1, "{:?}", violations(generate));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nested_block_is_matched_against_its_own_header() {
|
||||
let src = "module m;\n\
|
||||
always_comb begin : outer\n\
|
||||
begin : inner\n\
|
||||
x = 1;\n\
|
||||
end : inner\n\
|
||||
end : outer\n\
|
||||
endmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,45 @@
|
||||
//! The rules themselves, one module each.
|
||||
//!
|
||||
//! Most rules are **syntactic** — text, tokens or tree shape. The three that
|
||||
//! are not (`unused-signal`, `undriven-net`, `multiply-driven`) read the
|
||||
//! symbol table through `crate::signals`; see
|
||||
//! `docs/features/semantic-lints/README.md`.
|
||||
//! Most rules are **syntactic** — text, tokens or tree shape. The ones that
|
||||
//! are not read the symbol table: `unused-signal`, `undriven-net` and
|
||||
//! `multiply-driven` through `crate::signals` (see
|
||||
//! `docs/features/semantic-lints/README.md`), and `duplicate-declaration` and
|
||||
//! `instance-shadowing` through `vlog_semantic::Semantics` directly (see
|
||||
//! `docs/features/linter-expansion-1/README.md`).
|
||||
|
||||
pub mod always_comb_blocking;
|
||||
pub mod always_ff_non_blocking;
|
||||
pub mod case_missing_default;
|
||||
pub mod duplicate_declaration;
|
||||
pub mod empty_item;
|
||||
pub mod enum_name_style;
|
||||
pub mod explicit_function_task_parameter_type;
|
||||
pub mod explicit_parameter_storage_type;
|
||||
pub mod forbid_defparam;
|
||||
pub mod forbid_negative_array_dim;
|
||||
pub mod incomplete_assignment;
|
||||
pub mod instance_shadowing;
|
||||
pub mod invalid_system_task_function;
|
||||
pub mod mismatched_labels;
|
||||
pub mod module_filename;
|
||||
pub mod module_name_style;
|
||||
pub mod module_parameter;
|
||||
pub mod module_port;
|
||||
pub mod multiply_driven;
|
||||
pub mod no_tabs;
|
||||
pub mod no_trailing_whitespace;
|
||||
pub mod packed_dimensions_range_ordering;
|
||||
pub mod parameter_name_style;
|
||||
pub mod plusarg_assignment;
|
||||
pub mod struct_union_name_style;
|
||||
pub mod suspicious_semicolon;
|
||||
pub mod truncated_numeric_literal;
|
||||
pub mod undeclared_identifier;
|
||||
pub mod undersized_binary_literal;
|
||||
pub mod undriven_net;
|
||||
pub mod unknown_parameter;
|
||||
pub mod unknown_port;
|
||||
pub mod unused_signal;
|
||||
pub mod unused_waiver;
|
||||
pub mod void_cast;
|
||||
pub mod wire_reg_mixup;
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::ast::ItemKind;
|
||||
|
||||
@@ -19,6 +20,10 @@ impl Rule for ModuleFilename {
|
||||
"name a one-module file after its module"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"Every Verilog tool that finds a module by searching a library \
|
||||
directory — simulators, synthesis `-y` paths, most build systems — \
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use crate::context::LintContext;
|
||||
use crate::naming::{is_escaped, is_lower_snake_case};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_items;
|
||||
use vlog_parser::ast::ItemKind;
|
||||
@@ -21,6 +22,10 @@ impl Rule for ModuleNameStyle {
|
||||
"name modules in lower_snake_case"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A module name ends up as a file name, a directory name, an instance \
|
||||
path in a waveform viewer and a grep target, and every one of those is \
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
//! `module-parameter` — override a multi-parameter instance by name.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_instantiations;
|
||||
use vlog_parser::ast::ListElem;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct ModuleParameter;
|
||||
|
||||
const NAME: &str = "module-parameter";
|
||||
|
||||
impl Rule for ModuleParameter {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"override more than one parameter by name"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"`sub #(8, 4) u ()` binds by *order*, so a parameter added to the \
|
||||
instantiated module — or two of them reordered — silently changes \
|
||||
what every instance elaborates to, and two integers in a row give a \
|
||||
reader nothing to check against. `#(.Width(8), .Depth(4))` names each \
|
||||
one where it is written. Verible's `module-parameter` (\"Checks that \
|
||||
module instantiations with more than one parameter are passed in as \
|
||||
named parameters.\", enabled by default) is the same rule and the \
|
||||
same default; a single positional override is left alone by both. No \
|
||||
automatic fix: the names live in the instantiated module, usually in \
|
||||
another file."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_instantiations(ctx.file(), &mut |inst| {
|
||||
let Some(params) = &inst.params else { return };
|
||||
let positional =
|
||||
params.iter().filter_map(ListElem::ok).filter(|conn| conn.name.is_empty()).count();
|
||||
if positional < 2 {
|
||||
return;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!("`{}` takes {positional} parameters by position; name them", inst.module),
|
||||
inst.module_span,
|
||||
));
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
ModuleParameter.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_more_than_one_positional_override() {
|
||||
let src = "module m;\n sub #(8, 4) u_sub ();\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("`sub`"), "{}", found[0].message);
|
||||
assert!(found[0].message.contains("2 parameters"), "{}", found[0].message);
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_override_is_what_the_rule_wants() {
|
||||
let src = "module m;\n sub #(.Width(8), .Depth(4)) u_sub ();\nendmodule\n";
|
||||
assert!(violations(src).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_override_or_none_has_no_order_to_get_wrong() {
|
||||
assert!(violations("module m;\n sub #(8) u ();\nendmodule\n").is_empty());
|
||||
assert!(violations("module m;\n sub #() u ();\nendmodule\n").is_empty());
|
||||
assert!(violations("module m;\n sub u ();\nendmodule\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bind_and_a_generate_body_are_both_reached() {
|
||||
assert_eq!(violations("bind top sub #(8, 4) u ();\n").len(), 1);
|
||||
let generate = "module m;\n\
|
||||
generate\n\
|
||||
if (A) begin : g\n\
|
||||
sub #(8, 4) u ();\n\
|
||||
end\n\
|
||||
endgenerate\n\
|
||||
endmodule\n";
|
||||
assert_eq!(violations(generate).len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
//! `module-port` — connect a multi-port instance by name.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_instantiations;
|
||||
use vlog_parser::ast::Connections;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct ModulePort;
|
||||
|
||||
const NAME: &str = "module-port";
|
||||
|
||||
impl Rule for ModulePort {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"connect an instance with more than one port by name"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A positional connection list binds by *order*, so inserting a port in \
|
||||
the instantiated module silently rewires every instance of it — and \
|
||||
two ports of the same width swapped by hand compile perfectly and \
|
||||
fail in simulation. A named list (`.clk_i(clk)`) says what is \
|
||||
connected to what at the site, breaks loudly when a port is renamed, \
|
||||
and is what every reviewer can check without opening the other file. \
|
||||
Verible's `module-port` (\"Checks that module instantiations with \
|
||||
more than one port are passed in as named ports.\", enabled by \
|
||||
default) is the same rule and the same default; a single-port \
|
||||
instance is left alone by both, because there is no order to get \
|
||||
wrong. No automatic fix: naming the ports needs the instantiated \
|
||||
module's port list, which is usually in another file."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_instantiations(ctx.file(), &mut |inst| {
|
||||
for instance in &inst.instances {
|
||||
let Connections::Ordered(conns) = &instance.conns else { continue };
|
||||
if conns.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!(
|
||||
"`{}` is connected by position; name its {} ports",
|
||||
inst.module,
|
||||
conns.len()
|
||||
),
|
||||
instance.span,
|
||||
));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
ModulePort.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_positional_list_of_more_than_one() {
|
||||
let src = "module m;\n sub u_sub (a, b, c);\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("`sub`"), "{}", found[0].message);
|
||||
assert!(found[0].message.contains("3 ports"), "{}", found[0].message);
|
||||
assert_eq!(&src[found[0].span.as_range()], "u_sub (a, b, c)");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_list_is_what_the_rule_wants() {
|
||||
let src = "module m;\n sub u_sub (.a(x), .b(y), .c(z));\nendmodule\n";
|
||||
assert!(violations(src).is_empty());
|
||||
// `.*` is a named list too.
|
||||
assert!(violations("module m;\n sub u_sub (.*);\nendmodule\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_port_or_none_has_no_order_to_get_wrong() {
|
||||
assert!(violations("module m;\n sub u_sub (a);\nendmodule\n").is_empty());
|
||||
assert!(violations("module m;\n sub u_sub ();\nendmodule\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_instance_of_one_statement_is_judged() {
|
||||
let src = "module m;\n sub u1 (a, b), u2 (.a(x), .b(y)), u3 (c, d);\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 2, "{found:?}");
|
||||
assert!(found[0].span.start < found[1].span.start, "in source order");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instantiation_inside_generate_and_a_bind_are_both_reached() {
|
||||
let generate = "module m;\n\
|
||||
generate\n\
|
||||
if (A) begin : g\n\
|
||||
sub u (a, b);\n\
|
||||
end\n\
|
||||
endgenerate\n\
|
||||
endmodule\n";
|
||||
assert_eq!(violations(generate).len(), 1);
|
||||
assert_eq!(violations("bind top sub u (a, b);\n").len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ use std::collections::BTreeSet;
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::signals::{Driver, DriverKind};
|
||||
use crate::violation::Violation;
|
||||
|
||||
@@ -21,6 +22,10 @@ impl Rule for MultiplyDriven {
|
||||
"give a variable exactly one driver"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Error
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A SystemVerilog *variable* — `logic`, `reg`, `int` — may be written \
|
||||
from one source only (IEEE 1800 §6.5). Two `always` blocks assigning \
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::{Applicability, Fix, Violation};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
@@ -19,6 +20,10 @@ impl Rule for NoTabs {
|
||||
"use spaces, not tabs"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A tab renders at a width nobody agrees on, so a file mixing tabs and \
|
||||
spaces looks aligned in the editor that wrote it and ragged everywhere \
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::{Applicability, Fix, Violation};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
@@ -19,6 +20,10 @@ impl Rule for NoTrailingWhitespace {
|
||||
"no whitespace at the end of a line"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"Trailing whitespace is invisible, so it survives review and then shows \
|
||||
up as diff noise the day somebody's editor strips it — a one-character \
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
//! `packed-dimensions-range-ordering` — write a vector's width `[N-1:0]`.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::decls::{walk_dims, Packing};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::ast::{DimKind, Expr, ExprKind};
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct PackedDimensionsRangeOrdering;
|
||||
|
||||
const NAME: &str = "packed-dimensions-range-ordering";
|
||||
|
||||
impl Rule for PackedDimensionsRangeOrdering {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"declare a packed dimension in decreasing order, `[N-1:0]`"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"`logic [0:7] data` is legal and means bit 0 is the *most* significant \
|
||||
one, so `data[0]` is the top bit, a part select counts the other way \
|
||||
and every concatenation with an ordinary `[7:0]` vector silently \
|
||||
reverses. Nothing in the language stops it and no tool warns; the \
|
||||
cost lands on whoever reads the two declarations side by side. \
|
||||
Verible's `packed-dimensions-range-ordering` (\"Checks that packed \
|
||||
dimension ranges are declare in little-endian (decreasing) order, \
|
||||
e.g. `[N-1:0]`.\", enabled by default) is the same rule and the same \
|
||||
default. **Only packed dimensions are judged**: an unpacked `[0:3]` \
|
||||
array is an ordinary ascending array and is a perfectly normal thing \
|
||||
to write. A range is flagged when both bounds are integer literals \
|
||||
and the left one is smaller, and when the left one is a literal `0` \
|
||||
and the right is anything else — every other shape is left alone, \
|
||||
because lucisv does not evaluate parameters. No automatic fix: \
|
||||
reversing a range reverses every use of it."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_dims(ctx.file(), &mut |packing, dim| {
|
||||
if packing != Packing::Packed {
|
||||
return;
|
||||
}
|
||||
let DimKind::Range { a, b: Some(b) } = &dim.kind else { return };
|
||||
if !ascending(a, b) {
|
||||
return;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
"packed dimension counts upwards; write it as `[N-1:0]`",
|
||||
dim.span,
|
||||
));
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `[a:b]` demonstrably counts upwards.
|
||||
///
|
||||
/// Two literals decide it outright. A left bound of literal `0` decides it too
|
||||
/// whatever the right bound is — `[0:WIDTH-1]` is the shape this rule mostly
|
||||
/// meets — unless the right bound is `0` as well, which is the one-bit
|
||||
/// `[0:0]` and counts in no direction at all. Anything else is two symbolic
|
||||
/// bounds lucisv cannot compare, and it says nothing.
|
||||
fn ascending(a: &Expr, b: &Expr) -> bool {
|
||||
match (literal(a), literal(b)) {
|
||||
(Some(left), Some(right)) => left < right,
|
||||
(Some(0), None) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of a plain unsigned integer literal, or `None` for anything else.
|
||||
fn literal(expr: &Expr) -> Option<u128> {
|
||||
let ExprKind::Number(text) = &expr.kind else { return None };
|
||||
if text.contains(['\'', '.']) {
|
||||
return None;
|
||||
}
|
||||
text.chars().filter(|c| *c != '_').collect::<String>().parse().ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
PackedDimensionsRangeOrdering.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn decl(ty: &str) -> String {
|
||||
format!("module m;\n {ty} sig;\nendmodule\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_an_ascending_packed_range() {
|
||||
let src = decl("logic [0:7]");
|
||||
let found = violations(&src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "[0:7]");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_the_common_zero_to_symbolic_shape() {
|
||||
assert_eq!(violations(&decl("logic [0:WIDTH-1]")).len(), 1);
|
||||
assert_eq!(violations(&decl("logic [1:2]")).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_decreasing_range_is_what_the_rule_wants() {
|
||||
for ty in ["logic [7:0]", "logic [WIDTH-1:0]", "logic [0:0]", "logic", "logic [3]"] {
|
||||
assert!(violations(&decl(ty)).is_empty(), "{ty}: {:?}", violations(&decl(ty)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_symbolic_bounds_are_left_alone() {
|
||||
// lucisv does not evaluate parameters, so it says nothing here rather
|
||||
// than guessing which way `LO:HI` counts.
|
||||
assert!(violations(&decl("logic [LO:HI]")).is_empty());
|
||||
assert!(violations(&decl("logic [A-1:B]")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unpacked_array_is_not_a_packed_dimension() {
|
||||
assert!(violations("module m;\n logic q [0:3];\nendmodule\n").is_empty());
|
||||
assert!(violations("module m;\n logic [7:0] q [0:3];\nendmodule\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_declaration_shape_is_reached() {
|
||||
let src = "module m #(parameter logic [0:1] P = 0) (\n\
|
||||
input logic [0:2] a\n\
|
||||
);\n\
|
||||
typedef logic [0:3] w_t;\n\
|
||||
function void f(input logic [0:4] x);\n\
|
||||
endfunction\n\
|
||||
endmodule\n";
|
||||
assert_eq!(violations(src).len(), 4, "{:?}", violations(src));
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
use crate::context::LintContext;
|
||||
use crate::naming::{is_camel_case, is_escaped, is_upper_snake_case};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
|
||||
use vlog_parser::ast::{ItemKind, ParamDecl, StmtKind};
|
||||
@@ -22,6 +23,10 @@ impl Rule for ParameterNameStyle {
|
||||
"name parameters in CamelCase or ALL_CAPS"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A parameter is a compile-time constant, and reading one at a use site \
|
||||
should not require scrolling back to the declaration to learn that. \
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
//! `plusarg-assignment` — read a plusarg's value, do not test for its name.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::token::TokenKind;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct PlusargAssignment;
|
||||
|
||||
const NAME: &str = "plusarg-assignment";
|
||||
|
||||
/// The system task this rule is about.
|
||||
const TEST_PLUSARGS: &str = "$test$plusargs";
|
||||
|
||||
impl Rule for PlusargAssignment {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"read a plusarg with `$value$plusargs`, not `$test$plusargs`"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"`$test$plusargs(\"foo\")` answers only whether `+foo` was on the \
|
||||
command line, and it matches by *prefix*: `+foobar` makes it true \
|
||||
too, so two switches that share a prefix silently turn each other on. \
|
||||
`$value$plusargs(\"foo=%d\", v)` matches the whole name, says whether \
|
||||
it was there, and hands back the value — everything the other one \
|
||||
does, without the trap, which is why a plusarg should always be \
|
||||
given and read as a value. Verible's `plusarg-assignment` (\"Checks \
|
||||
that plusargs are always assigned a value, by ensuring that plusargs \
|
||||
are never accessed using the `$test$plusargs` system task.\", enabled \
|
||||
by default) is the same rule and the same default. No automatic fix: \
|
||||
the replacement needs a format string and a variable to read into, \
|
||||
neither of which the call being replaced has."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
ctx.tokens()
|
||||
.iter()
|
||||
.filter(|token| token.kind == TokenKind::SystemIdent && token.text == TEST_PLUSARGS)
|
||||
.map(|token| {
|
||||
Violation::new(
|
||||
NAME,
|
||||
"`$test$plusargs` matches by prefix; use `$value$plusargs` and read the value",
|
||||
token.span,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
PlusargAssignment.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_test_plusargs_call() {
|
||||
let src = "module m;\n initial if ($test$plusargs(\"fast\")) go = 1;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "$test$plusargs");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_value_form_is_what_the_rule_wants() {
|
||||
let src = "module m;\n\
|
||||
initial if ($value$plusargs(\"speed=%0d\", speed)) go = 1;\n\
|
||||
endmodule\n";
|
||||
assert!(violations(src).is_empty());
|
||||
// And a name that merely contains the words is not the call.
|
||||
assert!(violations("module m;\n logic test_plusargs;\nendmodule\n").is_empty());
|
||||
assert!(violations("module m;\n initial $display(\"$test$plusargs\");\nendmodule\n")
|
||||
.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
use crate::context::LintContext;
|
||||
use crate::naming::{is_escaped, is_lower_snake_case};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_items;
|
||||
use vlog_parser::ast::{ItemKind, TypedefKind};
|
||||
@@ -22,6 +23,10 @@ impl Rule for StructUnionNameStyle {
|
||||
"name struct and union typedefs in lower_snake_case ending in _t"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"The `_t` suffix is the one piece of Verilog naming convention that is \
|
||||
nearly universal: it marks an identifier as a type, which the language \
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
//! `suspicious-semicolon` — a `;` where a body was meant.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_all_stmts;
|
||||
use vlog_parser::ast::{Stmt, StmtKind};
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct SuspiciousSemicolon;
|
||||
|
||||
const NAME: &str = "suspicious-semicolon";
|
||||
|
||||
impl Rule for SuspiciousSemicolon {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"do not end a control statement's header with a `;`"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"`if (ready);` is legal and does nothing: the `;` is the whole body, \
|
||||
and whatever is indented under it runs unconditionally. The same \
|
||||
typo turns `for (…);` and `while (…);` into a loop that spins on an \
|
||||
empty body — an infinite one, if the body was where the loop variable \
|
||||
moved. It survives review because it looks right; the character that \
|
||||
breaks it is one column wide. Verible's `suspicious-semicolon` \
|
||||
(\"Checks that there are no suspicious semicolons that might affect \
|
||||
code behaviour but escape quick visual inspection.\") is the same \
|
||||
rule; **lucisv turns it on by default where Verible ships it off**, \
|
||||
because the finding is a typo rather than a matter of taste. A \
|
||||
deliberately empty body is written `begin end`, which is not \
|
||||
reported. No automatic fix: deleting the `;` would change what the \
|
||||
code does, and that is the author's call."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_all_stmts(ctx.file(), &mut |stmt| {
|
||||
for (what, body) in empty_bodies(stmt) {
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!("`{what}` has an empty body; the `;` is the whole of it"),
|
||||
body.span,
|
||||
));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The null bodies of one statement: what it is, and the `;` standing where
|
||||
/// its body belongs. A statement with a real body contributes nothing.
|
||||
fn empty_bodies(stmt: &Stmt) -> Vec<(&'static str, &Stmt)> {
|
||||
let null = |body: &Stmt| matches!(body.kind, StmtKind::Null);
|
||||
let mut out = Vec::new();
|
||||
match &stmt.kind {
|
||||
StmtKind::If { then, els, .. } => {
|
||||
if null(then) {
|
||||
out.push(("if", then.as_ref()));
|
||||
}
|
||||
// An `else if` is an `if` and is judged as one when the walk
|
||||
// reaches it; only a bare `else ;` is this statement's fault.
|
||||
if let Some(els) = els {
|
||||
if null(els) {
|
||||
out.push(("else", els.as_ref()));
|
||||
}
|
||||
}
|
||||
}
|
||||
StmtKind::For { body, .. } => push_if(&mut out, "for", body, null),
|
||||
StmtKind::While { body, .. } => push_if(&mut out, "while", body, null),
|
||||
StmtKind::Repeat { body, .. } => push_if(&mut out, "repeat", body, null),
|
||||
StmtKind::Forever { body } => push_if(&mut out, "forever", body, null),
|
||||
StmtKind::Foreach { body, .. } => push_if(&mut out, "foreach", body, null),
|
||||
_ => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn push_if<'a>(
|
||||
out: &mut Vec<(&'static str, &'a Stmt)>,
|
||||
what: &'static str,
|
||||
body: &'a Stmt,
|
||||
null: impl Fn(&Stmt) -> bool,
|
||||
) {
|
||||
if null(body) {
|
||||
out.push((what, body));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
SuspiciousSemicolon.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn wrap(body: &str) -> String {
|
||||
format!("module m;\n always_comb begin\n{body} end\nendmodule\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_an_if_whose_body_is_a_semicolon() {
|
||||
let src = wrap(" if (ready);\n x = 1;\n");
|
||||
let found = violations(&src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("`if`"), "{}", found[0].message);
|
||||
assert_eq!(&src[found[0].span.as_range()], ";", "the `;`, underlined");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_every_loop_header_and_a_bare_else() {
|
||||
for (body, what) in [
|
||||
(" for (int i = 0; i < 4; i++);\n", "for"),
|
||||
(" while (busy);\n", "while"),
|
||||
(" repeat (4);\n", "repeat"),
|
||||
(" forever;\n", "forever"),
|
||||
(" foreach (q[i]);\n", "foreach"),
|
||||
(" if (a) x = 1; else;\n", "else"),
|
||||
] {
|
||||
let found = violations(&wrap(body));
|
||||
assert_eq!(found.len(), 1, "{body}: {found:?}");
|
||||
assert!(found[0].message.contains(what), "{}", found[0].message);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_real_body_is_never_flagged() {
|
||||
for body in [
|
||||
" if (ready) x = 1;\n",
|
||||
" if (ready) begin\n x = 1;\n end\n",
|
||||
" if (a) x = 1; else x = 0;\n",
|
||||
" while (busy) x = 1;\n",
|
||||
" for (int i = 0; i < 4; i++) x = i;\n",
|
||||
] {
|
||||
assert!(violations(&wrap(body)).is_empty(), "{body}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deliberately_empty_block_is_the_way_to_write_one() {
|
||||
assert!(violations(&wrap(" if (ready) begin end\n")).is_empty());
|
||||
assert!(violations(&wrap(" forever begin end\n")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lone_null_statement_is_not_a_body() {
|
||||
// A stray `;` among statements is harmless — it is nobody's body.
|
||||
assert!(violations(&wrap(" ;\n x = 1;\n")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_else_if_chain_is_judged_on_the_inner_if() {
|
||||
let src = wrap(" if (a) x = 1; else if (b);\n");
|
||||
let found = violations(&src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("`if`"), "{}", found[0].message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
//! `truncated-numeric-literal` — a literal wider than the width it declares.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::literal;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::token::TokenKind;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct TruncatedNumericLiteral;
|
||||
|
||||
const NAME: &str = "truncated-numeric-literal";
|
||||
|
||||
impl Rule for TruncatedNumericLiteral {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"keep a sized literal inside the width it declares"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"`4'hFFF` is not an error and not a warning in most simulators: the \
|
||||
value is silently truncated to `4'hF` and the extra digits are gone. \
|
||||
Whichever half of it was wrong — the width or the value — the code \
|
||||
does not do what it reads as, and the reader has to count nibbles to \
|
||||
see it. Verible's `truncated-numeric-literal` (\"Checks that numeric \
|
||||
literals are not longer than their stated bit-width to avoid \
|
||||
undesired accidental truncation.\", enabled by default) is the same \
|
||||
rule. Leading zeros do not count (`8'h0FF` is eight bits), an `x` or \
|
||||
`z` digit counts as a full digit, and a decimal literal carrying `x` \
|
||||
is not judged at all. A literal whose digits are **all** unknown \
|
||||
(`3'hz`, `7'hzz`) is left alone: those are how the language spells a \
|
||||
three-bit and a seven-bit `z`, and their digit count only exceeds the \
|
||||
width because a hex digit is four bits. No automatic fix: only the \
|
||||
author knows which of the two numbers was meant."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
ctx.tokens()
|
||||
.iter()
|
||||
.filter(|token| token.kind == TokenKind::Number)
|
||||
.filter_map(|token| {
|
||||
let parsed = literal::parse(&token.text)?;
|
||||
let bits = parsed.significant_bits()?;
|
||||
if bits <= parsed.width || all_unknown(&parsed.packed_digits()) {
|
||||
return None;
|
||||
}
|
||||
Some(Violation::new(
|
||||
NAME,
|
||||
format!(
|
||||
"literal needs {bits} bits but declares {}; the value is truncated",
|
||||
parsed.width
|
||||
),
|
||||
token.span,
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// True when every digit is `x`, `z` or `?`.
|
||||
///
|
||||
/// `3'hz` and `7'hzz` are how the language spells a three-bit and a seven-bit
|
||||
/// `z`: the digit count exceeds the width by construction, because one hex
|
||||
/// digit is four bits, and nothing is being truncated — the value is unknown
|
||||
/// either way. Measured on opentitan, this shape was every one of the rule's
|
||||
/// findings in `top_earlgrey/dv/tb/tb.sv`.
|
||||
fn all_unknown(digits: &str) -> bool {
|
||||
!digits.is_empty() && digits.chars().all(|c| matches!(c.to_ascii_lowercase(), 'x' | 'z' | '?'))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
TruncatedNumericLiteral.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn assign(value: &str) -> String {
|
||||
format!("module m;\n assign x = {value};\nendmodule\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_literal_that_does_not_fit() {
|
||||
let found = violations(&assign("4'hFFF"));
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("12 bits"), "{}", found[0].message);
|
||||
assert!(found[0].message.contains("declares 4"), "{}", found[0].message);
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_every_base() {
|
||||
for value in ["1'b11", "2'o77", "4'hFF", "4'd16", "8'd300"] {
|
||||
assert_eq!(violations(&assign(value)).len(), 1, "{value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_literal_that_fits_is_silent() {
|
||||
for value in [
|
||||
"4'hF",
|
||||
"4'h0F",
|
||||
"8'h0FF",
|
||||
"8'b0000_0001",
|
||||
"32'hdead_beef",
|
||||
"8'd255",
|
||||
"4'h0",
|
||||
"1'b0",
|
||||
"8'sh7f",
|
||||
] {
|
||||
assert!(
|
||||
violations(&assign(value)).is_empty(),
|
||||
"{value}: {:?}",
|
||||
violations(&assign(value))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_digit_counts_but_a_decimal_unknown_is_not_judged() {
|
||||
assert_eq!(violations(&assign("4'hxF")).len(), 1, "two nibbles in a one-nibble literal");
|
||||
assert!(violations(&assign("4'hx")).is_empty(), "one nibble fits");
|
||||
assert!(violations(&assign("8'dx")).is_empty(), "a decimal x says nothing about width");
|
||||
}
|
||||
|
||||
/// `3'hz` is a three-bit `z`, not a truncated four-bit one — the shape
|
||||
/// that was every opentitan finding in `top_earlgrey/dv/tb/tb.sv`.
|
||||
#[test]
|
||||
fn an_all_unknown_literal_is_not_truncated() {
|
||||
for value in ["3'hz", "7'hzz", "1'bx", "5'h??", "3'hZ"] {
|
||||
assert!(
|
||||
violations(&assign(value)).is_empty(),
|
||||
"{value}: {:?}",
|
||||
violations(&assign(value))
|
||||
);
|
||||
}
|
||||
// A mixed literal still counts its digits.
|
||||
assert_eq!(violations(&assign("4'hxF")).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unsized_literal_and_a_plain_number_are_not_judged() {
|
||||
for value in ["'h1f", "42", "1.5", "'0", "'1"] {
|
||||
assert!(violations(&assign(value)).is_empty(), "{value}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
//! `undeclared-identifier` — a name nothing in the project declares.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::ast::ItemKind;
|
||||
use vlog_semantic::{words, Resolution};
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct UndeclaredIdentifier;
|
||||
|
||||
const NAME: &str = "undeclared-identifier";
|
||||
|
||||
impl Rule for UndeclaredIdentifier {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"use a name something declares"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Error
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A misspelled signal name is the one mistake in Verilog that costs \
|
||||
nothing to make and hours to find: an undeclared identifier in a \
|
||||
value position is an elaboration error in a strict tool and an \
|
||||
implicit one-bit net in a permissive one, and the second is worse — \
|
||||
the design builds, the bit stays `z`, and the bug surfaces in \
|
||||
simulation as a value nobody can trace. This rule reports a name that \
|
||||
**this file** does not declare, that no external unit it names could \
|
||||
supply, and that **no other file in the project writes down at all**.\n\n\
|
||||
Every one of those clauses is an exclusion, and they are what make an \
|
||||
Error-class rule about names safe to run. It says nothing at all \
|
||||
unless the run can see the project (`lucisv check <dir>`, or the \
|
||||
language server), because the whole case for a finding is that the \
|
||||
name appears nowhere else. It says nothing about a name any macro \
|
||||
invocation, compiler directive or attribute in this file writes down \
|
||||
— text lucisv never expands, and where half the identifiers in a \
|
||||
testbench live. It says nothing about a file that did not fully \
|
||||
parse, where error recovery moves declarations between scopes. And it \
|
||||
says nothing where the single-file analysis already knew it could not \
|
||||
answer: a package member, an inherited name, a hierarchical tail and \
|
||||
a `.port` connection all resolve elsewhere and never reach here. \
|
||||
Verible has no equivalent rule — its linter is syntax-only.\n\n\
|
||||
**Measured before it was switched on.** Over opentitan's `hw/` \
|
||||
(3 975 files) and over lucisv's own 860-file corpus it reports the \
|
||||
same five findings, in one file: `ibex/dv/formal/spec/spec_api.sv` \
|
||||
connects `.mhartid_out(mhart_id_o)` and four siblings to names its \
|
||||
module header never declares, which is exactly the implicit net this \
|
||||
rule exists to find. No false positive survived the exclusions, so it \
|
||||
ships on wherever there is a project — the same terms `unused-signal` \
|
||||
and `undriven-net` run on. No automatic fix: a misspelling has no one \
|
||||
repair."
|
||||
}
|
||||
|
||||
fn default_on(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn needs_workspace(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
// The whole case for a finding is "nothing else in the project writes
|
||||
// this name down", which a run that cannot see the project cannot
|
||||
// make. Without an oracle this rule has nothing to say — and saying
|
||||
// it anyway would accuse every name in every buffer.
|
||||
if !ctx.has_oracle() || !ctx.parsed_cleanly() || !declares_a_unit(ctx) {
|
||||
return Vec::new();
|
||||
}
|
||||
let raw: BTreeSet<String> = words::harvest_raw(ctx.tokens()).into_iter().collect();
|
||||
let semantics = ctx.semantics();
|
||||
semantics
|
||||
.references()
|
||||
.iter()
|
||||
.filter(|reference| reference.resolution == Resolution::NotFound)
|
||||
.filter(|reference| !reference.name_span.is_empty())
|
||||
// A use written at **file scope** belongs to no unit; the
|
||||
// fragment guard above has already dropped the files where that
|
||||
// is the whole file, and what is left is a stray.
|
||||
.filter(|reference| reference.scope != semantics.file_scope())
|
||||
// A name the file declares *somewhere* — a generate block's
|
||||
// label reached through a hierarchical path, a member of a scope
|
||||
// this use is not written in — is a name that exists; whether the
|
||||
// path to it is right is more than this rule claims to know.
|
||||
.filter(|reference| semantics.symbols_named(&reference.name).next().is_none())
|
||||
.filter(|reference| !raw.contains(&reference.name))
|
||||
.filter(|reference| !ctx.mentioned_elsewhere(&reference.name))
|
||||
.map(|reference| {
|
||||
Violation::new(
|
||||
NAME,
|
||||
format!("`{}` is declared nowhere in the project", reference.name),
|
||||
reference.name_span,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the file declares a design unit of its own — a module, an
|
||||
/// interface, a program, a package or a class.
|
||||
///
|
||||
/// A file that declares none but still holds declarations and assignments is
|
||||
/// a **fragment**: the middle of a module body, written to be `` `include``d
|
||||
/// at that point (`docs/features/fragment-mode/README.md`), where every name
|
||||
/// it reads is declared by the file that includes it and no census of *this*
|
||||
/// file can see them. Measured on opentitan: every one of the rule's 94
|
||||
/// findings was in four such fragments in ibex's formal harness plus one
|
||||
/// generate label, and this guard plus the declared-here guard removes all
|
||||
/// of them.
|
||||
fn declares_a_unit(ctx: &LintContext) -> bool {
|
||||
let mut found = false;
|
||||
crate::visit::walk_items(ctx.file(), &mut |item| {
|
||||
found |= matches!(
|
||||
item.kind,
|
||||
ItemKind::Module(_) | ItemKind::Package { .. } | ItemKind::Class(_)
|
||||
);
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::MentionOracle;
|
||||
|
||||
/// A project in which these names are written down somewhere else.
|
||||
struct Elsewhere(&'static [&'static str]);
|
||||
|
||||
impl MentionOracle for Elsewhere {
|
||||
fn mentioned_elsewhere(&self, name: &str) -> bool {
|
||||
self.0.contains(&name)
|
||||
}
|
||||
}
|
||||
|
||||
fn violations(src: &str, elsewhere: &'static [&'static str]) -> Vec<Violation> {
|
||||
let ctx = LintContext::new(src, None);
|
||||
let oracle = Elsewhere(elsewhere);
|
||||
UndeclaredIdentifier.check(&ctx.with_oracle(&oracle))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_name_nothing_declares_and_nothing_else_mentions() {
|
||||
let src = "module m;\n logic data;\n assign x = dara;\nendmodule\n";
|
||||
let found = violations(src, &[]);
|
||||
assert!(found.iter().any(|v| v.message.contains("`dara`")), "{found:?}");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declared_name_is_never_flagged() {
|
||||
let src = "module m;\n logic data;\n assign data = 1'b0;\nendmodule\n";
|
||||
assert!(violations(src, &[]).is_empty(), "{:?}", violations(src, &[]));
|
||||
}
|
||||
|
||||
/// The rule's whole safety net: a name some other file writes down —
|
||||
/// however it writes it — is not an accusation this rule will make.
|
||||
#[test]
|
||||
fn a_name_another_file_mentions_is_left_alone() {
|
||||
let src = "module m;\n assign x = elsewhere_sig;\nendmodule\n";
|
||||
assert!(violations(src, &["elsewhere_sig", "x"]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_this_files_macro_text_writes_down_is_left_alone() {
|
||||
// `MY_SIG` is produced by a macro lucisv never expands; the census of
|
||||
// raw text is what tells the rule to keep quiet.
|
||||
let src = "module m;\n\
|
||||
logic x;\n\
|
||||
`define MY_SIG some_sig\n\
|
||||
assign x = some_sig;\n\
|
||||
endmodule\n";
|
||||
assert!(violations(src, &[]).is_empty(), "{:?}", violations(src, &[]));
|
||||
}
|
||||
|
||||
/// An `` `include``d fragment — a module body with no module around it —
|
||||
/// reads names the including file declares, and no census of this file
|
||||
/// can see them. It was 85 of the 94 opentitan findings.
|
||||
#[test]
|
||||
fn an_include_fragment_gets_no_opinion() {
|
||||
let src = "assign pre_pc = other_sig;\nlogic [3:0] pre_regs;\n";
|
||||
assert!(violations(src, &[]).is_empty(), "{:?}", violations(src, &[]));
|
||||
}
|
||||
|
||||
/// A generate label reached through a hierarchical path is declared in
|
||||
/// this file, just not in the scope the use is written in.
|
||||
#[test]
|
||||
fn a_name_this_file_declares_somewhere_is_left_alone() {
|
||||
let src = "module m;\n\
|
||||
if (1) begin : gen_lfsr\n\
|
||||
logic state_q;\n\
|
||||
end\n\
|
||||
assign x = gen_lfsr;\n\
|
||||
endmodule\n";
|
||||
let found = violations(src, &[]);
|
||||
assert!(!found.iter().any(|v| v.message.contains("gen_lfsr")), "{found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_with_no_project_behind_it_says_nothing() {
|
||||
let src = "module m;\n assign x = dara;\nendmodule\n";
|
||||
let ctx = LintContext::new(src, None);
|
||||
assert!(UndeclaredIdentifier.check(&ctx).is_empty(), "no oracle, no opinion");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_did_not_parse_gets_no_opinion() {
|
||||
let src = "module m;\n @@@ junk\n assign x = dara;\nendmodule\n";
|
||||
assert!(violations(src, &[]).is_empty(), "{:?}", violations(src, &[]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_member_and_a_hierarchical_tail_never_reach_this_rule() {
|
||||
// Both resolve somewhere else — an external candidate or a member —
|
||||
// so neither is a `NotFound`, which is what this rule reports.
|
||||
for src in [
|
||||
"module m;\n assign x = pkg::thing;\nendmodule\n",
|
||||
"module m;\n assign x = tb.dut.sig;\nendmodule\n",
|
||||
"module m;\n import p::*;\n assign x = from_pkg;\nendmodule\n",
|
||||
] {
|
||||
let found = violations(src, &[]);
|
||||
assert!(
|
||||
!found.iter().any(|v| v.message.contains("thing")
|
||||
|| v.message.contains("sig")
|
||||
|| v.message.contains("from_pkg")),
|
||||
"{src}: {found:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
//! `undersized-binary-literal` — write every bit of a sized binary literal.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::literal;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::{Applicability, Fix, Violation};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::TokenKind;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct UndersizedBinaryLiteral;
|
||||
|
||||
const NAME: &str = "undersized-binary-literal";
|
||||
|
||||
impl Rule for UndersizedBinaryLiteral {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"write every bit of a sized binary literal"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"`8'b1` is one bit written where eight were declared, and a reader has \
|
||||
to remember the zero-extension rule to know it is `8'b0000_0001` — \
|
||||
while the very similar `8'bx` is *not* `8'b0000_000x` but eight `x`s, \
|
||||
because a leading `x` or `z` extends instead of zero-filling. Spelling \
|
||||
every bit takes the rule out of the reader's head. Verible's \
|
||||
`undersized-binary-literal` (\"Checks that the digits of binary \
|
||||
literals for the configured bases match their declared width.\", \
|
||||
enabled by default, binary only by default) is the same rule and the \
|
||||
same default; lucisv checks binary alone for the same reason, and — \
|
||||
also following that rule's defaults, whose `lint_zero` option is \
|
||||
off — leaves a literal whose value is **zero** alone: `2'b0` is not \
|
||||
a truncation waiting to happen, it is how the language spells zero. \
|
||||
The fix \
|
||||
is **safe**: it writes the extension the language would have applied, \
|
||||
which is `0` for a literal starting with `0` or `1` and the unknown \
|
||||
itself for one starting with `x` or `z`. Underscore separators are \
|
||||
preserved as written, and a literal *wider* than its declaration is \
|
||||
`truncated-numeric-literal`'s business, not this one's."
|
||||
}
|
||||
|
||||
fn fix(&self) -> Option<Applicability> {
|
||||
Some(Applicability::Safe)
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
ctx.tokens()
|
||||
.iter()
|
||||
.filter(|token| token.kind == TokenKind::Number)
|
||||
.filter_map(|token| {
|
||||
let parsed = literal::parse(&token.text)?;
|
||||
if parsed.base != 'b' {
|
||||
return None;
|
||||
}
|
||||
let digits = parsed.packed_digits();
|
||||
let written = digits.chars().count() as u32;
|
||||
if written >= parsed.width || is_zero(&digits) {
|
||||
return None;
|
||||
}
|
||||
let padding = pad_char(&digits)?;
|
||||
let missing = (parsed.width - written) as usize;
|
||||
// The pad goes in front of the first digit as written, so an
|
||||
// `_` the author put in the middle stays where it was.
|
||||
let first = token.span.end - parsed.digits.len() as u32;
|
||||
Some(
|
||||
Violation::new(
|
||||
NAME,
|
||||
format!("binary literal writes {written} of its {} bits", parsed.width),
|
||||
token.span,
|
||||
)
|
||||
.with_fix(Fix::safe(vec![(
|
||||
TextRange::new(first, first),
|
||||
padding.to_string().repeat(missing),
|
||||
)])),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// True for a literal whose written value is zero — `1'b0`, `8'b0`, `4'b00`.
|
||||
///
|
||||
/// Exempt because Verible's `lint_zero` option defaults to **false**, and
|
||||
/// matching its default is what keeps a Verible-clean codebase lucisv-clean:
|
||||
/// measured on opentitan, `'b0` accounts for the great majority of every
|
||||
/// undersized binary literal in the tree, and every one of them reads exactly
|
||||
/// as it means.
|
||||
fn is_zero(digits: &str) -> bool {
|
||||
digits.chars().all(|c| c == '0')
|
||||
}
|
||||
|
||||
/// The digit the language would extend this literal with: an unknown extends
|
||||
/// itself, everything else extends with `0` (IEEE 1800 §5.7.1). `None` for an
|
||||
/// empty digit run, which [`literal::parse`] never produces.
|
||||
fn pad_char(digits: &str) -> Option<char> {
|
||||
match digits.chars().next()?.to_ascii_lowercase() {
|
||||
c @ ('x' | 'z' | '?') => Some(c),
|
||||
_ => Some('0'),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::violation::apply_fixes;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
UndersizedBinaryLiteral.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn assign(value: &str) -> String {
|
||||
format!("module m;\n assign x = {value};\nendmodule\n")
|
||||
}
|
||||
|
||||
fn fixed(value: &str) -> String {
|
||||
let src = assign(value);
|
||||
apply_fixes(&src, &violations(&src), false).output
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_short_binary_literal_and_pads_it() {
|
||||
let src = assign("8'b1");
|
||||
let found = violations(&src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("1 of its 8"), "{}", found[0].message);
|
||||
assert_eq!(fixed("8'b1"), assign("8'b00000001"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_extends_itself_not_with_zeros() {
|
||||
assert_eq!(fixed("4'bx"), assign("4'bxxxx"));
|
||||
assert_eq!(fixed("4'bz"), assign("4'bzzzz"));
|
||||
// ... and a literal that only *contains* an unknown still zero-fills,
|
||||
// because the language looks at the leftmost digit.
|
||||
assert_eq!(fixed("4'b1x"), assign("4'b001x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separators_stay_where_the_author_put_them() {
|
||||
assert_eq!(fixed("8'b1_1"), assign("8'b0000001_1"));
|
||||
}
|
||||
|
||||
/// Verible's `lint_zero` defaults to off, and so does lucisv: `2'b0` was
|
||||
/// the great majority of this rule's opentitan findings before the exempt.
|
||||
#[test]
|
||||
fn a_zero_literal_is_exempt() {
|
||||
for value in ["2'b0", "8'b0", "4'b00", "1'b0", "32'b0_0"] {
|
||||
assert!(violations(&assign(value)).is_empty(), "{value}");
|
||||
}
|
||||
// A non-zero literal of the same width is still reported.
|
||||
assert_eq!(violations(&assign("2'b1")).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_width_literal_is_silent() {
|
||||
for value in ["8'b0000_0001", "1'b0", "4'b1010", "4'bxxxx"] {
|
||||
assert!(violations(&assign(value)).is_empty(), "{value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_binary_is_judged_and_only_when_sized() {
|
||||
for value in ["8'h1", "8'd1", "8'o1", "'b1", "42"] {
|
||||
assert!(violations(&assign(value)).is_empty(), "{value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_oversized_literal_belongs_to_the_other_rule() {
|
||||
assert!(violations(&assign("1'b11")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fix_leaves_the_file_clean() {
|
||||
let src = assign("8'b1");
|
||||
let once = apply_fixes(&src, &violations(&src), false).output;
|
||||
assert!(violations(&once).is_empty(), "idempotent: {once}");
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::signals::intentionally_unused;
|
||||
use crate::violation::Violation;
|
||||
|
||||
@@ -19,6 +20,10 @@ impl Rule for UndrivenNet {
|
||||
"drive a signal that something reads"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A net read by the design but assigned by nothing is `z` forever, and \
|
||||
a variable in the same position is `x` forever. In simulation this \
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
//! `unknown-parameter` — a `#(.NAME(…))` the module does not declare.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_instantiations;
|
||||
use vlog_parser::ast::ListElem;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct UnknownParameter;
|
||||
|
||||
const NAME: &str = "unknown-parameter";
|
||||
|
||||
impl Rule for UnknownParameter {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"override only parameters the instantiated module declares"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Error
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"`#(.Width(8))` on a module whose parameter is called `DataWidth` is \
|
||||
an elaboration error, and — worse than the port version — the \
|
||||
*silent* failure mode is real: a tool that accepts the override \
|
||||
anyway elaborates the module at its declared default, so the design \
|
||||
builds and is the wrong width. A `localparam` is not overridable at \
|
||||
all (IEEE 1800 §6.20.4), so naming one here is the same error wearing \
|
||||
a different hat, and lucisv reports it: the parameter list this rule \
|
||||
checks against holds every `parameter` of the header and the body and \
|
||||
no `localparam` of either. Verible has no equivalent; this is TODO \
|
||||
§33.2's own rule.\n\n\
|
||||
It keeps `unknown-port`'s silences exactly: no project, an unindexed \
|
||||
module, one declared twice with different headers, one whose header \
|
||||
carries a compiler directive, and a scope-qualified instantiation are \
|
||||
all cases where the run cannot answer and the rule says nothing. A \
|
||||
positional override names nothing to check — that is `module-\
|
||||
parameter`'s subject. No automatic fix."
|
||||
}
|
||||
|
||||
fn default_on(&self) -> bool {
|
||||
// Off without a project: with no interface table to ask, every named
|
||||
// override would be unanswerable and the rule would be a no-op that
|
||||
// still cost a walk.
|
||||
false
|
||||
}
|
||||
|
||||
fn needs_workspace(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_instantiations(ctx.file(), &mut |inst| {
|
||||
if inst.module.contains(':') {
|
||||
return;
|
||||
}
|
||||
let Some(params) = &inst.params else { return };
|
||||
let Some(interface) = ctx.module_interface(&inst.module) else { return };
|
||||
for param in params.iter().filter_map(ListElem::ok) {
|
||||
if param.name == "*" || param.name_span.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if interface.has_parameter(¶m.name) {
|
||||
continue;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!("`{}` declares no overridable parameter `{}`", inst.module, param.name),
|
||||
param.name_span,
|
||||
));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::context::{MentionOracle, ModuleInterface};
|
||||
|
||||
/// A project holding one module with these overridable parameters.
|
||||
struct Project(&'static str, &'static [&'static str]);
|
||||
|
||||
impl MentionOracle for Project {
|
||||
fn mentioned_elsewhere(&self, _name: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn module_interface(&self, name: &str) -> Option<ModuleInterface> {
|
||||
(name == self.0).then(|| ModuleInterface {
|
||||
ports: Vec::new(),
|
||||
parameters: self.1.iter().map(|p| p.to_string()).collect(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn violations(src: &str, project: &'static Project) -> Vec<Violation> {
|
||||
let ctx = LintContext::new(src, None);
|
||||
UnknownParameter.check(&ctx.with_oracle(project))
|
||||
}
|
||||
|
||||
static SUB: Project = Project("sub", &["Width", "Depth"]);
|
||||
|
||||
#[test]
|
||||
fn flags_an_override_the_module_does_not_declare() {
|
||||
let src = "module m;\n sub #(.Width(8), .Deth(4)) u ();\nendmodule\n";
|
||||
let found = violations(src, &SUB);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("`Deth`"), "{}", found[0].message);
|
||||
assert_eq!(&src[found[0].span.as_range()], "Deth");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declared_parameter_is_never_flagged() {
|
||||
let src = "module m;\n sub #(.Width(8), .Depth(4)) u ();\nendmodule\n";
|
||||
assert!(violations(src, &SUB).is_empty(), "{:?}", violations(src, &SUB));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_positional_override_names_nothing_to_check() {
|
||||
assert!(violations("module m;\n sub #(8, 4) u ();\nendmodule\n", &SUB).is_empty());
|
||||
assert!(violations("module m;\n sub u ();\nendmodule\n", &SUB).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unindexed_module_and_a_run_with_no_project_are_both_silent() {
|
||||
assert!(violations("module m;\n other #(.Nope(1)) u ();\nendmodule\n", &SUB).is_empty());
|
||||
let src = "module m;\n sub #(.Nope(1)) u ();\nendmodule\n";
|
||||
assert!(UnknownParameter.check(&LintContext::new(src, None)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scope_qualified_instantiation_is_left_to_the_workspace() {
|
||||
let src = "module m;\n pkg::sub #(.Nope(1)) u ();\nendmodule\n";
|
||||
assert!(violations(src, &SUB).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
//! `unknown-port` — a `.name(…)` the instantiated module does not declare.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_instantiations;
|
||||
use vlog_parser::ast::Connections;
|
||||
use vlog_parser::ast::ListElem;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct UnknownPort;
|
||||
|
||||
const NAME: &str = "unknown-port";
|
||||
|
||||
impl Rule for UnknownPort {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"connect only ports the instantiated module declares"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Error
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"`.data_i(x)` on a module that declares `data_in` is an elaboration \
|
||||
error in every tool, and the commonest way to reach it is a port \
|
||||
rename that reached the declaration and three of its four \
|
||||
instantiations. The fourth is in another file, so nothing about the \
|
||||
file being edited says anything is wrong. Verible has no equivalent \
|
||||
— its linter reads one file at a time — and this is TODO §33.2's own \
|
||||
rule.\n\n\
|
||||
**Silent whenever the project cannot answer**, which is what an \
|
||||
Error-class rule owes: with no project behind the run at all, for a \
|
||||
module the project does not declare, for one declared more than once \
|
||||
with different headers, and for one whose header lucisv cannot read \
|
||||
whole — a port list carrying a compiler directive is the case that \
|
||||
matters, because a macro standing where a port belongs expands to \
|
||||
names lucisv never sees. A `.*` connection names nothing and is not \
|
||||
judged, and a scope-qualified instantiation (`pkg::mod`) is left to \
|
||||
the workspace. No automatic fix: the right port name is a guess, and \
|
||||
a wrong guess here rewires a design."
|
||||
}
|
||||
|
||||
fn default_on(&self) -> bool {
|
||||
// Off without a project: with no interface table to ask, every named
|
||||
// connection would be unanswerable and the rule would be a no-op that
|
||||
// still cost a walk.
|
||||
false
|
||||
}
|
||||
|
||||
fn needs_workspace(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_instantiations(ctx.file(), &mut |inst| {
|
||||
if inst.module.contains(':') {
|
||||
return;
|
||||
}
|
||||
let Some(interface) = ctx.module_interface(&inst.module) else { return };
|
||||
for instance in &inst.instances {
|
||||
let Connections::Named(conns) = &instance.conns else { continue };
|
||||
for conn in conns.iter().filter_map(ListElem::ok) {
|
||||
if conn.name == "*" || conn.name_span.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if interface.has_port(&conn.name) {
|
||||
continue;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!("`{}` declares no port `{}`", inst.module, conn.name),
|
||||
conn.name_span,
|
||||
));
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::context::{MentionOracle, ModuleInterface};
|
||||
|
||||
/// A project holding one module with these ports.
|
||||
struct Project(&'static str, &'static [&'static str]);
|
||||
|
||||
impl MentionOracle for Project {
|
||||
fn mentioned_elsewhere(&self, _name: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn module_interface(&self, name: &str) -> Option<ModuleInterface> {
|
||||
(name == self.0).then(|| ModuleInterface {
|
||||
ports: self.1.iter().map(|p| p.to_string()).collect(),
|
||||
parameters: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn violations(src: &str, project: &'static Project) -> Vec<Violation> {
|
||||
let ctx = LintContext::new(src, None);
|
||||
UnknownPort.check(&ctx.with_oracle(project))
|
||||
}
|
||||
|
||||
static SUB: Project = Project("sub", &["clk_i", "data_i"]);
|
||||
|
||||
#[test]
|
||||
fn flags_a_connection_the_module_does_not_declare() {
|
||||
let src = "module m;\n sub u (.clk_i(clk), .dara_i(d));\nendmodule\n";
|
||||
let found = violations(src, &SUB);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("`dara_i`"), "{}", found[0].message);
|
||||
assert_eq!(&src[found[0].span.as_range()], "dara_i");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declared_port_is_never_flagged() {
|
||||
let src = "module m;\n sub u (.clk_i(clk), .data_i(d));\nendmodule\n";
|
||||
assert!(violations(src, &SUB).is_empty(), "{:?}", violations(src, &SUB));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_the_project_does_not_declare_is_left_alone() {
|
||||
let src = "module m;\n other u (.whatever(x));\nendmodule\n";
|
||||
assert!(violations(src, &SUB).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_and_a_positional_list_name_nothing_to_check() {
|
||||
assert!(violations("module m;\n sub u (.*);\nendmodule\n", &SUB).is_empty());
|
||||
assert!(violations("module m;\n sub u (a, b);\nendmodule\n", &SUB).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_with_no_project_says_nothing() {
|
||||
let src = "module m;\n sub u (.dara_i(d));\nendmodule\n";
|
||||
assert!(UnknownPort.check(&LintContext::new(src, None)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scope_qualified_instantiation_is_left_to_the_workspace() {
|
||||
let src = "module m;\n pkg::sub u (.dara_i(d));\nendmodule\n";
|
||||
assert!(violations(src, &SUB).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_implicit_named_connection_is_judged_too() {
|
||||
// `.clk_i` with no parentheses is a named connection like any other.
|
||||
let src = "module m;\n sub u (.clk_i, .dara_i);\nendmodule\n";
|
||||
let found = violations(src, &SUB);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("`dara_i`"), "{}", found[0].message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_instance_of_one_statement_is_judged() {
|
||||
let src = "module m;\n sub u1 (.dara_i(a)), u2 (.data_i(b));\nendmodule\n";
|
||||
assert_eq!(violations(src, &SUB).len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::signals::intentionally_unused;
|
||||
use crate::violation::Violation;
|
||||
|
||||
@@ -19,6 +20,10 @@ impl Rule for UnusedSignal {
|
||||
"delete a signal nothing uses"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A `wire` or `logic` that nothing reads and nothing drives is dead \
|
||||
weight: it costs a reader the effort of working out what it is for, \
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::waiver::UNUSED_WAIVER;
|
||||
|
||||
@@ -17,6 +18,10 @@ impl Rule for UnusedWaiver {
|
||||
"remove waivers that no longer suppress anything"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A `// lucisv: waive` comment outlives the problem it was written for: \
|
||||
the code is fixed, the waiver stays, and the next reader believes the \
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
//! `void-cast` — `void'(…)` around something that is not a call.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_all_stmts;
|
||||
use vlog_parser::ast::{Expr, ExprKind, StmtKind};
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct VoidCast;
|
||||
|
||||
const NAME: &str = "void-cast";
|
||||
|
||||
impl Rule for VoidCast {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"cast to `void` only what a call returns"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"`void'(expr)` exists for exactly one purpose: calling a function for \
|
||||
its side effect and saying out loud that the return value is being \
|
||||
thrown away (IEEE 1800 §13.4.1). Around anything that is not a call — \
|
||||
a variable, a literal, an arithmetic expression — it discards a value \
|
||||
nobody computed for a side effect, which means either the call that \
|
||||
was meant to be there is missing or the cast is left over from an \
|
||||
edit. Verible ships a `void-cast` rule (\"Checks that void casts do \
|
||||
not contain certain function/method calls.\", enabled by default) \
|
||||
with a different subject: **it forbids a named list of calls** whose \
|
||||
result must be checked (`randomize`, `uvm_hdl_read`). lucisv's is the \
|
||||
complementary check TODO §33 asked for — the operand must be a call \
|
||||
at all — and takes no list, so the two do not overlap and neither \
|
||||
replaces the other; the named-call form belongs with the per-rule \
|
||||
options of wave 2. No automatic fix: whether the repair is to delete \
|
||||
the cast or to add the missing call is the author's to decide.\n\n\
|
||||
Only a `void'(...)` standing **as a statement** is judged, which is \
|
||||
the one place the construct belongs: a `void` value gives an \
|
||||
enclosing expression nothing to do with it, so a `void'` buried in an \
|
||||
rvalue is a different mistake and one this rule stays out of."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_all_stmts(ctx.file(), &mut |stmt| {
|
||||
let StmtKind::ExprStmt(expr) = &stmt.kind else { return };
|
||||
let ExprKind::Cast { ty, expr: inner, pattern, .. } = &expr.kind else { return };
|
||||
if *pattern || !is_void(ty) || is_call(inner) {
|
||||
return;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
"`void'(...)` around something that is not a call; nothing is being discarded",
|
||||
expr.span,
|
||||
));
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// True for the casting type `void`, however it is spelled in the tree.
|
||||
fn is_void(ty: &Expr) -> bool {
|
||||
matches!(&ty.kind, ExprKind::Ident(name) if name == "void")
|
||||
|| matches!(&ty.kind, ExprKind::Type(data) if data.name == "void")
|
||||
}
|
||||
|
||||
/// True when the cast's operand is a call — the only thing `void'` is for.
|
||||
///
|
||||
/// A method call reaches here as a `Call` whose callee is a `Member`
|
||||
/// (`obj.randomize()`), and a `new` expression is a constructor call; both
|
||||
/// count, and so does a call carrying a `with` clause — `void'(randomize(x)
|
||||
/// with { … })` is the commonest void cast there is. A parenthesized operand
|
||||
/// is looked through, because `void'((f()))` is the same statement written
|
||||
/// twice.
|
||||
fn is_call(expr: &Expr) -> bool {
|
||||
match &expr.kind {
|
||||
ExprKind::Call { .. } | ExprKind::New(_) => true,
|
||||
ExprKind::Paren { inner, .. } => is_call(inner),
|
||||
ExprKind::With { base, .. } | ExprKind::WithConstraint { base, .. } => is_call(base),
|
||||
// A cast around a cast is somebody being explicit about a return
|
||||
// type; look through it rather than accuse the outer one.
|
||||
ExprKind::Cast { expr: inner, .. } => is_call(inner),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
VoidCast.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn stmt(text: &str) -> String {
|
||||
format!("module m;\n initial begin\n {text}\n end\nendmodule\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_void_cast_of_a_plain_value() {
|
||||
let src = stmt("void'(x);");
|
||||
let found = violations(&src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "void'(x)");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_call_is_what_a_void_cast_is_for() {
|
||||
for text in [
|
||||
"void'(f());",
|
||||
"void'(obj.randomize());",
|
||||
"void'(pkg::f(1, 2));",
|
||||
"void'(q.pop_front());",
|
||||
"void'((f()));",
|
||||
"void'($cast(a, b));",
|
||||
"void'(randomize(x) with { x inside {[0:7]}; });",
|
||||
"void'(q.sum() with (item.w));",
|
||||
] {
|
||||
assert!(violations(&stmt(text)).is_empty(), "{text}: {:?}", violations(&stmt(text)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cast_to_something_else_is_not_this_rules_business() {
|
||||
for text in ["a = int'(x);", "a = logic'(x);", "a = my_t'(x);", "a = 4'(x);"] {
|
||||
assert!(violations(&stmt(text)).is_empty(), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_statement_position_cast_is_judged() {
|
||||
// A `void'` in an rvalue is a different mistake; this rule is about
|
||||
// the statement idiom and says nothing there.
|
||||
assert!(violations(&stmt("a = void'(x);")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_call_operand_of_any_shape_is_flagged() {
|
||||
for text in ["void'(1);", "void'(a + b);", "void'(s.field);", "void'(q[0]);"] {
|
||||
assert_eq!(violations(&stmt(text)).len(), 1, "{text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ use std::path::Path;
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::token::TokenKind;
|
||||
|
||||
@@ -21,6 +22,10 @@ impl Rule for WireRegMixup {
|
||||
"use `logic` instead of `reg` in SystemVerilog files"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Error
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"`reg` is Verilog-1995's name for a variable, and its worst property is \
|
||||
that it reads like hardware: generations of engineers have written \
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
//! How bad a finding is: the three classes every rule states.
|
||||
//!
|
||||
//! Verible has no such notion — every one of its rules produces the same
|
||||
//! diagnostic — and ruff spells it as a rule *prefix* (`E`, `W`, `F`). lucisv
|
||||
//! takes ruff's idea and Verible's vocabulary: three words a user can select,
|
||||
//! ignore and toggle by, chosen so the question they answer is "would a tool
|
||||
//! refuse this file?" rather than "how annoyed am I".
|
||||
|
||||
/// How bad one rule's findings are.
|
||||
///
|
||||
/// The order is worst-first, and it is the order a generated document and a
|
||||
/// settings UI list the classes in — so [`Ord`] is derived rather than
|
||||
/// hand-written, and sorting by it sorts by seriousness.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum Severity {
|
||||
/// The code would very likely fail to compile, elaborate or synthesize.
|
||||
/// A rule may only claim this when it is certain: an `Error` finding is an
|
||||
/// accusation, so every rule in this class stays silent whenever it cannot
|
||||
/// answer — see `docs/features/linter-expansion-1/README.md`.
|
||||
Error,
|
||||
/// The code compiles, and means something the author probably did not
|
||||
/// intend: a latch where none was wanted, a deprecated construct, a
|
||||
/// literal that does not fit its width.
|
||||
Warning,
|
||||
/// The code is correct and reads badly: naming, tabs, a redundant `;`.
|
||||
Style,
|
||||
}
|
||||
|
||||
impl Severity {
|
||||
/// Every class, worst first — the order rules and settings are grouped in.
|
||||
pub const ALL: [Severity; 3] = [Severity::Error, Severity::Warning, Severity::Style];
|
||||
|
||||
/// The word this class is spelled with everywhere a user meets it:
|
||||
/// `--select`, `--ignore`, the CLI diagnostic line, the JSON output and
|
||||
/// the generated rule reference.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Severity::Error => "error",
|
||||
Severity::Warning => "warning",
|
||||
Severity::Style => "style",
|
||||
}
|
||||
}
|
||||
|
||||
/// The class that word names, or `None` when it names no class.
|
||||
pub fn from_name(name: &str) -> Option<Severity> {
|
||||
Severity::ALL.into_iter().find(|severity| severity.as_str() == name)
|
||||
}
|
||||
|
||||
/// One line saying what the class means, for the generated reference and
|
||||
/// for the settings UI — one wording, so the two cannot drift.
|
||||
pub fn describes(self) -> &'static str {
|
||||
match self {
|
||||
Severity::Error => {
|
||||
"code that would very likely fail to compile, elaborate or synthesize"
|
||||
}
|
||||
Severity::Warning => "code that compiles but very likely does not mean what it says",
|
||||
Severity::Style => "code that is correct and reads badly",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_class_round_trips_through_its_word() {
|
||||
for severity in Severity::ALL {
|
||||
assert_eq!(Severity::from_name(severity.as_str()), Some(severity));
|
||||
assert!(!severity.describes().is_empty());
|
||||
}
|
||||
assert_eq!(Severity::from_name("errors"), None);
|
||||
assert_eq!(Severity::from_name("Error"), None, "matched exactly, like every other name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_classes_are_ordered_worst_first() {
|
||||
let mut shuffled = [Severity::Style, Severity::Error, Severity::Warning];
|
||||
shuffled.sort_unstable();
|
||||
assert_eq!(shuffled, Severity::ALL);
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -2,12 +2,21 @@
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
use crate::severity::Severity;
|
||||
|
||||
/// One rule finding: which rule, what is wrong, where, and — sometimes —
|
||||
/// how to repair it.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Violation {
|
||||
/// The reporting rule's stable kebab-case name.
|
||||
pub rule: &'static str,
|
||||
/// How bad it is. **Set by the runner from the reporting rule**, not by
|
||||
/// the rule's own `check` — [`crate::lint`] stamps every finding with
|
||||
/// [`crate::Rule::severity`] before it is returned, so a rule cannot
|
||||
/// contradict its own declared class. A violation built by hand (a rule's
|
||||
/// unit test calling `check` directly) carries the placeholder below until
|
||||
/// it goes through the runner.
|
||||
pub severity: Severity,
|
||||
/// One sentence, lower case, no trailing period — the diagnostic line.
|
||||
pub message: String,
|
||||
/// Byte range the diagnostic points at.
|
||||
@@ -19,7 +28,7 @@ pub struct Violation {
|
||||
impl Violation {
|
||||
/// A finding with no automatic repair.
|
||||
pub fn new(rule: &'static str, message: impl Into<String>, span: TextRange) -> Violation {
|
||||
Violation { rule, message: message.into(), span, fix: None }
|
||||
Violation { rule, severity: Severity::Warning, message: message.into(), span, fix: None }
|
||||
}
|
||||
|
||||
/// The same finding, carrying a repair.
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
//! text and no children, so they are visited and matched by nothing.
|
||||
|
||||
use vlog_parser::ast::{
|
||||
Fragment, GenBlock, GenElse, Item, ItemKind, ParamPort, SourceFile, Stmt, StmtKind,
|
||||
Fragment, GenBlock, GenElse, Instantiation, Item, ItemKind, ListElem, ParamPort, SourceFile,
|
||||
Stmt, StmtKind,
|
||||
};
|
||||
|
||||
/// Calls `f` on every item in the file, nested items included.
|
||||
@@ -150,12 +151,25 @@ pub(crate) fn walk_param_ports(file: &SourceFile, f: &mut dyn FnMut(&ParamPort))
|
||||
ItemKind::Class(class) => &class.param_ports,
|
||||
_ => return,
|
||||
};
|
||||
for port in ports.iter().flatten() {
|
||||
// An error element is a parameter a tolerant parse could not read: it
|
||||
// has no name and no type, so there is nothing for a rule to judge.
|
||||
for port in ports.iter().flatten().filter_map(ListElem::ok) {
|
||||
f(port);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Calls `f` on every module instantiation of the file — a plain one, and the
|
||||
/// one a `bind` directive carries, which is an ordinary instantiation written
|
||||
/// somewhere else.
|
||||
pub(crate) fn walk_instantiations(file: &SourceFile, f: &mut dyn FnMut(&Instantiation)) {
|
||||
walk_items(file, &mut |item| match &item.kind {
|
||||
ItemKind::Instantiation(inst) => f(inst),
|
||||
ItemKind::Bind(bind) => f(&bind.inst),
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
//! The VS Code lint settings, generated from the rule registry.
|
||||
//!
|
||||
//! `editors/vscode/package.json` declares one switch per severity class and
|
||||
//! one per rule. Hand-written, that list would go stale the first time a rule
|
||||
//! was added — the rule would ship with no way to turn it off from the
|
||||
//! editor — so it is generated here instead, by the same crate that owns the
|
||||
//! registry, exactly as [`crate::rules_markdown`] generates the rule
|
||||
//! reference.
|
||||
//!
|
||||
//! Two consumers, one text: `cargo run -p vlog_linter --example
|
||||
//! vscode_lint_settings` prints it for a human to paste in, and a test in
|
||||
//! `lucisv_server` parses both this and `package.json` and fails when they
|
||||
//! disagree. See `docs/features/linter-expansion-1/README.md`.
|
||||
|
||||
use crate::registry::all_rules;
|
||||
use crate::severity::Severity;
|
||||
use crate::Rule;
|
||||
|
||||
/// The setting a severity class's master switch is called.
|
||||
pub fn severity_setting(severity: Severity) -> String {
|
||||
format!("lucisv.lint.severity.{}", severity.as_str())
|
||||
}
|
||||
|
||||
/// The setting one rule's toggle is called.
|
||||
pub fn rule_setting(rule: &dyn Rule) -> String {
|
||||
format!("lucisv.lint.rules.{}", rule.name())
|
||||
}
|
||||
|
||||
/// The three words a per-rule toggle takes.
|
||||
///
|
||||
/// A tri-state rather than a boolean, and deliberately: the ladder in
|
||||
/// `lucisv_server::settings::enabled_rules` distinguishes a rule the user
|
||||
/// *said something about* from one they left alone, and a plain boolean cannot
|
||||
/// carry that — a client sends every setting in the section, its default
|
||||
/// included, so "unset" and "set to the default" would arrive identically and
|
||||
/// a per-rule toggle would silently override `select` and the class switches.
|
||||
pub const RULE_CHOICES: [&str; 3] = ["default", "on", "off"];
|
||||
|
||||
/// The whole `lucisv.lint.severity.*` + `lucisv.lint.rules.*` block, as the
|
||||
/// JSON object `package.json`'s `configuration.properties` holds them in.
|
||||
///
|
||||
/// Two-space indentation with an eight-space margin, which is where those
|
||||
/// properties sit in that file, so the text pastes in as it stands.
|
||||
pub fn vscode_lint_settings() -> String {
|
||||
let mut entries: Vec<String> = Vec::new();
|
||||
for (i, severity) in Severity::ALL.into_iter().enumerate() {
|
||||
entries.push(severity_entry(severity, 10 + i as u32));
|
||||
}
|
||||
let mut order = 20;
|
||||
for severity in Severity::ALL {
|
||||
for rule in all_rules().into_iter().filter(|rule| rule.severity() == severity) {
|
||||
entries.push(rule_entry(rule, order));
|
||||
order += 1;
|
||||
}
|
||||
}
|
||||
format!("{{\n{}\n}}\n", entries.join(",\n"))
|
||||
}
|
||||
|
||||
/// One class's master switch.
|
||||
fn severity_entry(severity: Severity, order: u32) -> String {
|
||||
let description = format!(
|
||||
"Run the **{word}** lint rules — {what}. Turning this off silences the whole class; \
|
||||
a per-rule toggle below still has the last word, and \
|
||||
`#lucisv.lint.ignore#` still removes a rule whatever else says. \
|
||||
Takes effect immediately — every open file is re-checked.",
|
||||
word = severity.as_str(),
|
||||
what = severity.describes(),
|
||||
);
|
||||
format!(
|
||||
" \"{id}\": {{\n\
|
||||
\x20 \"type\": \"boolean\",\n\
|
||||
\x20 \"default\": true,\n\
|
||||
\x20 \"order\": {order},\n\
|
||||
\x20 \"markdownDescription\": {description}\n\
|
||||
\x20 }}",
|
||||
id = severity_setting(severity),
|
||||
description = json_string(&description),
|
||||
)
|
||||
}
|
||||
|
||||
/// One rule's toggle.
|
||||
fn rule_entry(rule: &'static dyn Rule, order: u32) -> String {
|
||||
let description = format!(
|
||||
"**{severity}** — {summary}. {default}",
|
||||
severity = rule.severity().as_str(),
|
||||
summary = rule.summary(),
|
||||
default = default_sentence(rule),
|
||||
);
|
||||
format!(
|
||||
" \"{id}\": {{\n\
|
||||
\x20 \"type\": \"string\",\n\
|
||||
\x20 \"enum\": [{choices}],\n\
|
||||
\x20 \"enumDescriptions\": [\n\
|
||||
\x20 {leave},\n\
|
||||
\x20 \"Always run this rule.\",\n\
|
||||
\x20 \"Never run this rule.\"\n\
|
||||
\x20 ],\n\
|
||||
\x20 \"default\": \"default\",\n\
|
||||
\x20 \"order\": {order},\n\
|
||||
\x20 \"markdownDescription\": {description}\n\
|
||||
\x20 }}",
|
||||
id = rule_setting(rule),
|
||||
choices = RULE_CHOICES.iter().map(|c| json_string(c)).collect::<Vec<_>>().join(", "),
|
||||
leave = json_string(&format!("Leave it as it ships: {}", default_sentence(rule))),
|
||||
description = json_string(&description),
|
||||
)
|
||||
}
|
||||
|
||||
/// How a rule's own default is said in one sentence — the same three cases
|
||||
/// [`crate::rules_markdown`]'s Default column spells.
|
||||
fn default_sentence(rule: &dyn Rule) -> String {
|
||||
match (rule.default_on(), rule.needs_workspace()) {
|
||||
(true, _) => "On by default.".to_string(),
|
||||
(false, true) => "On where lucisv can see the project.".to_string(),
|
||||
(false, false) => "Off by default.".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A JSON string literal. Hand-rolled, as the CLI's JSON output is: this crate
|
||||
/// depends on `vlog_parser` and `std` alone, and a serialization framework for
|
||||
/// one string shape is not a trade worth making.
|
||||
fn json_string(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len() + 2);
|
||||
out.push('"');
|
||||
for c in text.chars() {
|
||||
match c {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_rule_and_every_class_gets_an_entry() {
|
||||
let json = vscode_lint_settings();
|
||||
for severity in Severity::ALL {
|
||||
assert!(json.contains(&format!("\"{}\"", severity_setting(severity))), "{severity:?}");
|
||||
}
|
||||
for rule in all_rules() {
|
||||
let id = rule_setting(rule);
|
||||
assert_eq!(json.matches(&format!("\"{id}\"")).count(), 1, "{id}");
|
||||
assert!(
|
||||
json.contains(&format!("**{}** — {}.", rule.severity().as_str(), rule.summary())),
|
||||
"{id}: description",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The toggles are ordered worst class first, then by name — which is how
|
||||
/// the Settings UI groups them.
|
||||
#[test]
|
||||
fn the_order_numbers_group_by_severity_then_name() {
|
||||
let json = vscode_lint_settings();
|
||||
let mut expected: Vec<String> = Vec::new();
|
||||
for severity in Severity::ALL {
|
||||
let mut names: Vec<&str> = all_rules()
|
||||
.into_iter()
|
||||
.filter(|rule| rule.severity() == severity)
|
||||
.map(|rule| rule.name())
|
||||
.collect();
|
||||
names.sort_unstable();
|
||||
expected.extend(names.into_iter().map(str::to_string));
|
||||
}
|
||||
let found: Vec<String> = json
|
||||
.lines()
|
||||
.filter_map(|line| line.trim().strip_prefix("\"lucisv.lint.rules."))
|
||||
.filter_map(|rest| rest.split('"').next().map(str::to_string))
|
||||
.collect();
|
||||
assert_eq!(found, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_strings_are_escaped() {
|
||||
assert_eq!(json_string("a\"b\\c"), "\"a\\\"b\\\\c\"");
|
||||
assert_eq!(json_string("em — dash"), "\"em — dash\"", "UTF-8 passes through");
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ module m;
|
||||
always_comb begin
|
||||
case (s)
|
||||
//^ 5 case-missing-default
|
||||
//^ 5 incomplete-assignment
|
||||
0: x = 1;
|
||||
endcase
|
||||
end
|
||||
@@ -33,6 +34,7 @@ module m;
|
||||
always_comb begin
|
||||
// lucisv: waive case-missing-default
|
||||
case (s)
|
||||
//^ 5 incomplete-assignment
|
||||
0: x = 1;
|
||||
endcase
|
||||
end
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
# a packed dimension that counts upwards
|
||||
#select packed-dimensions-range-ordering
|
||||
module m;
|
||||
logic [0:7] up;
|
||||
//^ 9 packed-dimensions-range-ordering
|
||||
logic [0:WIDTH-1] also_up;
|
||||
//^ 9 packed-dimensions-range-ordering
|
||||
endmodule
|
||||
====
|
||||
# the decreasing form, a one-bit range, and an unpacked array
|
||||
#select packed-dimensions-range-ordering
|
||||
module m;
|
||||
logic [7:0] down;
|
||||
logic [WIDTH-1:0] symbolic;
|
||||
logic [0:0] one_bit;
|
||||
logic [LO:HI] unknowable;
|
||||
logic ascending_array [0:3];
|
||||
endmodule
|
||||
====
|
||||
# a negative constant written into a dimension
|
||||
#select forbid-negative-array-dim
|
||||
module m;
|
||||
logic [-1:0] v;
|
||||
//^ 10 forbid-negative-array-dim
|
||||
logic q [-1];
|
||||
//^ 12 forbid-negative-array-dim
|
||||
endmodule
|
||||
====
|
||||
# a subtraction is not a negative literal
|
||||
#select forbid-negative-array-dim
|
||||
module m;
|
||||
logic [WIDTH-1:0] v;
|
||||
logic q [DEPTH];
|
||||
parameter int P = -1;
|
||||
endmodule
|
||||
====
|
||||
# an untyped formal is a one-bit logic
|
||||
#select explicit-function-task-parameter-type
|
||||
module m;
|
||||
function void f(input a);
|
||||
//^ 19 explicit-function-task-parameter-type
|
||||
endfunction
|
||||
endmodule
|
||||
====
|
||||
# a continuation formal inherits the type in force
|
||||
#select explicit-function-task-parameter-type
|
||||
module m;
|
||||
function void f(input int a, b);
|
||||
endfunction
|
||||
task t(input logic [7:0] c);
|
||||
endtask
|
||||
endmodule
|
||||
====
|
||||
# a positional connection list of more than one port
|
||||
#select module-port
|
||||
module m;
|
||||
sub u_sub (a, b, c);
|
||||
//^ 7 module-port
|
||||
endmodule
|
||||
====
|
||||
# named connections, a wildcard, and a single positional one
|
||||
#select module-port
|
||||
module m;
|
||||
sub u1 (.a(x), .b(y));
|
||||
sub u2 (.*);
|
||||
sub u3 (a);
|
||||
sub u4 ();
|
||||
endmodule
|
||||
====
|
||||
# more than one positional parameter override
|
||||
#select module-parameter
|
||||
module m;
|
||||
sub #(8, 4) u_sub ();
|
||||
//^ 3 module-parameter
|
||||
endmodule
|
||||
====
|
||||
# named overrides, and a single positional one
|
||||
#select module-parameter
|
||||
module m;
|
||||
sub #(.Width(8), .Depth(4)) u1 ();
|
||||
sub #(8) u2 ();
|
||||
sub u3 ();
|
||||
endmodule
|
||||
@@ -0,0 +1,82 @@
|
||||
# an end label that names another block is a compile error
|
||||
#select mismatched-labels
|
||||
module m;
|
||||
always_comb begin : fetch
|
||||
x = 1;
|
||||
end : decode
|
||||
//^ 9 mismatched-labels
|
||||
endmodule
|
||||
====
|
||||
# a footer label on a block that has none is one too
|
||||
#select mismatched-labels
|
||||
module m;
|
||||
always_comb begin
|
||||
x = 1;
|
||||
end : blk
|
||||
//^ 9 mismatched-labels
|
||||
endmodule
|
||||
====
|
||||
# a matching pair, and a footer that was simply not written
|
||||
#select mismatched-labels
|
||||
module m;
|
||||
always_comb begin : blk
|
||||
x = 1;
|
||||
end : blk
|
||||
always_comb begin : other
|
||||
y = 1;
|
||||
end
|
||||
endmodule : m
|
||||
====
|
||||
# every construct with a footer label is checked
|
||||
#select mismatched-labels
|
||||
package p;
|
||||
function void f();
|
||||
endfunction : g
|
||||
//^ 17 mismatched-labels
|
||||
endpackage : q
|
||||
//^ 14 mismatched-labels
|
||||
====
|
||||
# two declarations of one name in one scope
|
||||
#select duplicate-declaration
|
||||
module m;
|
||||
logic a;
|
||||
logic a;
|
||||
//^ 9 duplicate-declaration
|
||||
endmodule
|
||||
====
|
||||
# a non-ANSI port is completed by its body declarations, three times legally
|
||||
#select duplicate-declaration
|
||||
module m (clk);
|
||||
input clk;
|
||||
logic clk;
|
||||
endmodule
|
||||
====
|
||||
# conditional arms never coexist, so they are not duplicates
|
||||
#select duplicate-declaration
|
||||
module m;
|
||||
`ifdef X
|
||||
logic b;
|
||||
`else
|
||||
logic b;
|
||||
`endif
|
||||
endmodule
|
||||
====
|
||||
# a block-local hiding a module signal is shadowing, not duplication
|
||||
#select instance-shadowing
|
||||
module m;
|
||||
logic count;
|
||||
always_comb begin : blk
|
||||
logic count;
|
||||
//^ 11 instance-shadowing
|
||||
count = 1'b0;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# two modules may each declare the same name
|
||||
#select instance-shadowing
|
||||
module a;
|
||||
logic data;
|
||||
endmodule
|
||||
module b;
|
||||
logic data;
|
||||
endmodule
|
||||
@@ -0,0 +1,61 @@
|
||||
# a literal wider than its declared width is truncated
|
||||
#select truncated-numeric-literal
|
||||
module m;
|
||||
assign x = 4'hFFF;
|
||||
//^ 14 truncated-numeric-literal
|
||||
endmodule
|
||||
====
|
||||
# leading zeros, an exact fit and an all-unknown literal are all fine
|
||||
#select truncated-numeric-literal
|
||||
module m;
|
||||
assign a = 8'h0FF;
|
||||
assign b = 32'hdead_beef;
|
||||
assign c = 3'hz;
|
||||
assign d = 7'hzz;
|
||||
endmodule
|
||||
====
|
||||
# an unsized literal has no width to overflow
|
||||
#select truncated-numeric-literal
|
||||
module m;
|
||||
assign x = 'hffff_ffff;
|
||||
endmodule
|
||||
====
|
||||
# a short binary literal is padded to its declared width
|
||||
#select undersized-binary-literal
|
||||
module m;
|
||||
assign x = 8'b1;
|
||||
//^ 14 undersized-binary-literal
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign x = 8'b00000001;
|
||||
//^ 14 undersized-binary-literal
|
||||
endmodule
|
||||
====
|
||||
# an unknown extends itself rather than zero-filling
|
||||
#select undersized-binary-literal
|
||||
module m;
|
||||
assign x = 4'bz;
|
||||
//^ 14 undersized-binary-literal
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign x = 4'bzzzz;
|
||||
//^ 14 undersized-binary-literal
|
||||
endmodule
|
||||
====
|
||||
# zero is exempt, as it is in verible: `lint_zero` defaults off
|
||||
#select undersized-binary-literal
|
||||
module m;
|
||||
assign a = 2'b0;
|
||||
assign b = 32'b0;
|
||||
assign c = 4'b1010;
|
||||
endmodule
|
||||
====
|
||||
# only binary is judged, and only when the literal says its width
|
||||
#select undersized-binary-literal
|
||||
module m;
|
||||
assign a = 8'h1;
|
||||
assign b = 8'd1;
|
||||
assign c = 'b1;
|
||||
endmodule
|
||||
@@ -0,0 +1,98 @@
|
||||
# a control statement whose whole body is a `;`
|
||||
#select suspicious-semicolon
|
||||
module m;
|
||||
always_comb begin
|
||||
if (ready);
|
||||
//^ 15 suspicious-semicolon
|
||||
while (busy);
|
||||
//^ 17 suspicious-semicolon
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a real body, and the way to write a deliberately empty one
|
||||
#select suspicious-semicolon
|
||||
module m;
|
||||
always_comb begin
|
||||
if (ready) x = 1;
|
||||
forever begin end
|
||||
;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a void cast around something that is not a call discards nothing
|
||||
#select void-cast
|
||||
module m;
|
||||
initial begin
|
||||
void'(x);
|
||||
//^ 5 void-cast
|
||||
void'(f());
|
||||
void'(obj.randomize() with { a inside {[0:3]}; });
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# defparam reaches into another scope
|
||||
#select forbid-defparam
|
||||
module m;
|
||||
sub u ();
|
||||
defparam u.WIDTH = 8;
|
||||
//^ 3 forbid-defparam
|
||||
endmodule
|
||||
====
|
||||
# the named override is what the rule wants instead
|
||||
#select forbid-defparam
|
||||
module m;
|
||||
sub #(.WIDTH(8)) u ();
|
||||
endmodule
|
||||
====
|
||||
# the forbidden system tasks, and the replacements beside them
|
||||
#select invalid-system-task-function
|
||||
module m;
|
||||
initial begin
|
||||
a = $random();
|
||||
//^ 9 invalid-system-task-function
|
||||
b = $psprintf("%0d", a);
|
||||
//^ 9 invalid-system-task-function
|
||||
c = $urandom();
|
||||
d = $sformatf("%0d", c);
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a plusarg should be read as a value, not tested for by prefix
|
||||
#select plusarg-assignment
|
||||
module m;
|
||||
initial begin
|
||||
if ($test$plusargs("fast")) go = 1;
|
||||
//^ 9 plusarg-assignment
|
||||
if ($value$plusargs("speed=%0d", speed)) go = 1;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a variable written only under an if infers a latch
|
||||
#select incomplete-assignment
|
||||
module m;
|
||||
always_comb begin
|
||||
if (en) y = a;
|
||||
//^ 5 incomplete-assignment
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a default assignment before the branch is the repair
|
||||
#select incomplete-assignment
|
||||
module m;
|
||||
always_comb begin
|
||||
y = 1'b0;
|
||||
if (en) y = a;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a case with a default writes every arm, so the if after it is covered
|
||||
#select incomplete-assignment
|
||||
module m;
|
||||
always_comb begin
|
||||
case (s)
|
||||
0: y = a;
|
||||
default: y = b;
|
||||
endcase
|
||||
if (en) y = 1'b1;
|
||||
end
|
||||
endmodule
|
||||
@@ -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");
|
||||
|
||||
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user