Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
97aa2fefd8 | ||
|
|
9604753b6c | ||
|
|
797ef86d47 | ||
|
|
a30dda167a | ||
|
|
0757503fd1 | ||
|
|
6a0af26fdf | ||
|
|
8adb6c8ac1 | ||
|
|
fbee290a0a | ||
|
|
b1b3cad09b |
No files matched your search
@@ -4,6 +4,74 @@ 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.41.0 — 2026-09-04
|
||||
|
||||
### Code actions off the fan-out
|
||||
|
||||
- **Lazy port refactorings.** For a client that supports
|
||||
`codeAction/resolve` (VS Code does), the port actions are offered from
|
||||
the buffer and the instantiated module's declaration alone, and the
|
||||
edit is computed when the action is picked. The request VS Code sends
|
||||
on nearly every cursor move no longer reads the module's fan-out:
|
||||
flat at ~55 µs in-process from a 3-file to a 128-file fan-out, where
|
||||
it was linear (15 ms at 128). A resolve for an action that no longer
|
||||
applies is an error, not an empty edit. Clients without resolve
|
||||
support get the edit up front, as before.
|
||||
- **Definitions from the index.** `textDocument/definition` and
|
||||
workspace symbols for a file-scope declaration in a closed file now
|
||||
build the location from the positions the index already records
|
||||
instead of reading the file: 0.4 µs against 28 µs per answer.
|
||||
- **inlayHint at the default scope**: investigated, not changed. The
|
||||
hints missing at that scope belong to a module declared outside what
|
||||
the scope reaches; definition and hover say the same. A scope
|
||||
question, recorded in the feature README.
|
||||
|
||||
## 0.40.0 — 2026-09-04
|
||||
|
||||
### Two parser residues and atomic writes
|
||||
|
||||
- **A bare `begin … end` at module scope, or straight inside
|
||||
`generate … endgenerate`, is recovered** in error-tolerant mode as an
|
||||
unnamed generate block (`ItemKind::GenBlock`) with a diagnostic at the
|
||||
keyword, instead of being refused and taking the rest of the unit with
|
||||
it. The items inside and after the block are now visible to the
|
||||
editor and to every lint rule; `module-begin-block`,
|
||||
`v2001-generate-begin` and `mismatched-labels` read the node. Strict
|
||||
parsing is unchanged, so the formatter still refuses the file exactly
|
||||
as before.
|
||||
- **A half-typed `#(` override or connection whose value would read as
|
||||
the next instance** (`sub #(.W(8), .DEPTH(` ⏎ `u0 (.a(x));`) now costs
|
||||
one error element: `.W(8)` survives, `u0` is an instance with its
|
||||
connections, one diagnostic on the unclosed `(`. The balanced-parens
|
||||
spelling stays ambiguous and is still parsed greedily, by design.
|
||||
- **In-place writes are atomic.** `lucisv format`, `lucisv check --fix`
|
||||
and the cache write a sibling temp file and rename it over the target,
|
||||
so a crash or a full disk never leaves a source file truncated. The
|
||||
target's permissions are kept, a symlink's *target* is what gets
|
||||
replaced, and a read-only file is refused as it always was.
|
||||
|
||||
## 0.39.0 — 2026-09-04
|
||||
|
||||
### The rest of Verible's rules
|
||||
|
||||
Nineteen more rules bring lucisv to **73** — every rule in Verible's
|
||||
published list except the one that needs a compiler. New: `module-begin-
|
||||
block`, `legacy-generate-region`, `legacy-genvar-declaration`,
|
||||
`v2001-generate-begin`, `explicit-function-lifetime`,
|
||||
`explicit-task-lifetime`, `positive-meaning-parameter-name`,
|
||||
`suggest-parentheses` (safe fix), `unpacked-dimensions-range-ordering`,
|
||||
`uvm-macro-semicolon`, `create-object-name-match`,
|
||||
`numeric-format-string-style`, `macro-string-concatenation`,
|
||||
`disable-statement`, `forbidden-macro` (`macros` option),
|
||||
`endif-comment` (safe fix), `forbid-line-continuations`,
|
||||
`dff-name-style`, `proper-parameter-declaration`.
|
||||
`invalid-system-task-function` gains a `symbols` option (Verible's
|
||||
"forbidden-symbol" is the same rule); `void-cast` gains
|
||||
`forbidden_calls`. The two lifetime rules deliberately exempt an
|
||||
out-of-body method definition (`function cls::f()`), which is where
|
||||
almost every finding on a UVM tree would otherwise land. Each rule's
|
||||
documentation cites the Verible rule and default it follows.
|
||||
|
||||
## 0.38.0 — 2026-09-04
|
||||
|
||||
### Lint rule options, and the Style family
|
||||
|
||||
Generated
+8
-8
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.38.0"
|
||||
version = "0.41.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.38.0"
|
||||
version = "0.41.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.38.0"
|
||||
version = "0.41.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.38.0"
|
||||
version = "0.41.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.38.0"
|
||||
version = "0.41.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -264,11 +264,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.38.0"
|
||||
version = "0.41.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.38.0"
|
||||
version = "0.41.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
@@ -276,7 +276,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.38.0"
|
||||
version = "0.41.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.38.0"
|
||||
version = "0.41.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -242,6 +242,11 @@ makes an editor's red squiggle worth believing.
|
||||
| `instance-shadowing` | warning | — | no declaration hides an enclosing one |
|
||||
| `undriven-net` † | warning | — | everything read is driven by something |
|
||||
| `unused-signal` † | warning | — | no net or variable nothing uses |
|
||||
| `create-object-name-match` | warning | — | `type_id::create("x")` names the handle `x` |
|
||||
| `forbidden-macro` | warning | — | no macro on the project's forbidden list |
|
||||
| `uvm-macro-semicolon` | warning | — | no `;` after a `` `uvm_* `` macro (off by default) |
|
||||
| `macro-string-concatenation` | warning | — | no `` `` `` inside a plain string (off by default) |
|
||||
| `disable-statement` | warning | — | `disable fork`, not a fork label (off by default) |
|
||||
| `no-tabs` | style | safe | spaces, not tabs (a tab inside a string is left alone) |
|
||||
| `no-trailing-whitespace` | style | safe | nothing but code before the newline |
|
||||
| `empty-item` | style | safe | no `;` standing where an item belongs |
|
||||
@@ -270,6 +275,20 @@ makes an editor's red squiggle worth believing.
|
||||
| `banned-declared-name-patterns` | style | — | no declared name matching a project's own list (off) |
|
||||
| `explicit-begin` | style | safe | every body is a `begin ... end` block (off by default) |
|
||||
| `unused-waiver` | style | — | waivers that suppress nothing |
|
||||
| `explicit-function-lifetime` | style | — | `automatic`/`static` on a function outside a class |
|
||||
| `explicit-task-lifetime` | style | — | `automatic`/`static` on a task outside a class |
|
||||
| `positive-meaning-parameter-name` | style | — | no `disable`-prefixed parameter name |
|
||||
| `suggest-parentheses` | style | safe | `a ? (b ? c : d) : e`, parenthesized |
|
||||
| `unpacked-dimensions-range-ordering` | style | — | an unpacked dimension is `[0:N-1]` |
|
||||
| `module-begin-block` | style | — | no `begin`/`end` at module scope |
|
||||
| `v2001-generate-begin` | style | — | no bare `begin` in a generate region |
|
||||
| `forbid-line-continuations` | style | — | no `\` breaking a string literal |
|
||||
| `legacy-generate-region` | style | — | no `generate … endgenerate` wrapper (off) |
|
||||
| `legacy-genvar-declaration` | style | — | a genvar is declared in the `for` header (off) |
|
||||
| `endif-comment` | style | safe | `` `endif `` names what it closes (off by default) |
|
||||
| `numeric-format-string-style` | style | — | a radix prefix matches its specifier (off) |
|
||||
| `proper-parameter-declaration` | style | — | `parameter` in a header, `localparam` in a body (off) |
|
||||
| `dff-name-style` | style | — | a flip-flop is `_q`, its input `_d` (off by default) |
|
||||
|
||||
† On by default when lucisv can see a project (a multi-file CLI run or the
|
||||
language server), and off for a single file or stdin unless `--select` names
|
||||
|
||||
@@ -1233,19 +1233,26 @@ Files: `crates/lucisv_server/src/{candidates.rs,state.rs,server.rs,perf.rs}`,
|
||||
|
||||
### Deferred, filed
|
||||
|
||||
- [ ] `codeAction` costs 185–201 ms at a 128-file fan-out and offers
|
||||
- [x] `codeAction` costs 185–201 ms at a 128-file fan-out and offers
|
||||
**zero** actions there (`performance_take2.md` §6a): ~1.4 ms per
|
||||
instantiating file plus a ~13 ms floor, paid before anything knows
|
||||
there is nothing to offer. Wants either the lazy resolve below or
|
||||
a cheap zero-detector that answers before the fan-out is walked.
|
||||
- [ ] `inlayHint` returns **0 hints at the default scope** where the
|
||||
**Delivered by §37.1**: the offer is flat at 54–59 µs from a 3- to a
|
||||
128-file fan-out, both cursor shapes.
|
||||
- [x] `inlayHint` returns **0 hints at the default scope** where the
|
||||
workspace scope returns 4 (`performance_take2.md` §8): investigate
|
||||
before assuming it is scope-relative-answers working as intended —
|
||||
the hinted instantiation's module may be in scope and still unhinted.
|
||||
- [ ] codeAction lazy resolution (`codeAction/resolve`): make the offer
|
||||
**Investigated by §37.2 and ruled correct**: the four hints are
|
||||
`pins_if`'s, declared in `hw/dv/sv/common_ifs`, which the widen to
|
||||
`hw/ip/aes` does not reach; hover and definition answer nothing for it
|
||||
either. Finding and two default-scope tests in
|
||||
`docs/features/lazy-code-action/README.md`.
|
||||
- [x] codeAction lazy resolution (`codeAction/resolve`): make the offer
|
||||
index-only (~0 ms regardless of fan-out), edits computed on
|
||||
lightbulb click — kills the 83 ms worst case. Owner-approved
|
||||
direction, after the wave.
|
||||
direction, after the wave. **Delivered by §37.1.**
|
||||
- [x] Rename over an index-stale workspace: Lane A must state the
|
||||
staleness premise; if the verifier cannot catch a hidden
|
||||
reference, the honesty gate is the lead's review call. Stated
|
||||
@@ -1290,10 +1297,17 @@ and three owner items. See
|
||||
lowercased index with a character-mask pre-filter and a counting
|
||||
top-K — 3–8 ms per query over a generated 120 000-entry
|
||||
hierarchy, asserted in the node suite.
|
||||
- [ ] Filed, not done: rewire `locate::location` onto `DeclPositions`
|
||||
- [x] Filed, not done: rewire `locate::location` onto `DeclPositions`
|
||||
so `textDocument/definition`, references, the lens and both
|
||||
hierarchies stop reading a file to convert an indexed span. Every
|
||||
unit's range is now in the index for free.
|
||||
unit's range is now in the index for free. **Delivered by §37.3**
|
||||
for the file-scope answers `nav.rs` and `symbols.rs` give
|
||||
(27.9 µs → 0.42 µs per definition on opentitan); references, the
|
||||
lens and the hierarchies answer from `ReferenceSite`/`InstantiationEdge`
|
||||
spans, which are not `Def`s and record no `DeclPositions`, and
|
||||
`references`' one `Def` span (`includeDeclaration`) is converted in the
|
||||
same one-fetch batch as that file's reference sites — filed again
|
||||
there rather than silently dropped.
|
||||
- [ ] Manual extension-host acceptance (themes, keyboard-only, zoom,
|
||||
screen readers, an old server binary, both VSIX shapes).
|
||||
|
||||
@@ -2913,12 +2927,12 @@ collide); no parallel lane.
|
||||
`undriven-net`, exactly as in `covergroup-bodies`.
|
||||
- [x] P5 verbatim-SVA rename warning (pin: a fallback region spelling
|
||||
the old name warns, never silent)
|
||||
- [ ] P6 §2.9-18 wiring (pin: a file whose only relationship to the name
|
||||
- [x] P6 §2.9-18 wiring (pin: a file whose only relationship to the name
|
||||
is a macro argument still warns) — the **engine half is done and
|
||||
pinned**; the server fan-out (`Workspace::rename_sources`,
|
||||
outside the round's file list) is filed as Handshake request 1 in
|
||||
`docs/features/sva-bodies/README.md`, with the unbounded-read-set
|
||||
objection that makes it a lead's call rather than a mechanical wiring
|
||||
objection that makes it a lead's call rather than a mechanical wiring. **Delivered by §29** (macro-word census, `unread_macro_warnings`).
|
||||
- [x] P7 SVA gap fuzzer at zero (705 gaps, 0 failures); the 12 assertion
|
||||
attack pairs kept plus 46 new ones; `verify.rs` untouched
|
||||
- [x] Measurement: opentitan **79/79 declarations and 97/97 assertions**
|
||||
@@ -2928,7 +2942,7 @@ collide); no parallel lane.
|
||||
corpus 13 files moved and opentitan 36, all inside assertion text;
|
||||
both sweeps otherwise byte-identical; the 4 854 `` `ASSERT* ``
|
||||
invocations byte-identical
|
||||
- [ ] QA on opentitan (read-only): structured counts re-derived; every
|
||||
- [x] QA on opentitan (read-only): structured counts re-derived; every
|
||||
moved file's diff read; rename of a signal used in
|
||||
`hw/ip/*/rtl/*_assert*.sv` properties; sweep unchanged
|
||||
|
||||
@@ -3126,7 +3140,7 @@ edge).
|
||||
store measurement +123 402 bytes (+3.11 %) on the corpus and
|
||||
+743 873 (+1.66 %) on opentitan; opentitan `lucisv check` sweep
|
||||
byte-identical, working tree untouched
|
||||
- [ ] QA: rename of `clk` in an opentitan IP with the server, timing
|
||||
- [x] QA: rename of `clk` in an opentitan IP with the server, timing
|
||||
before/after (must not regress; the warning list must name only
|
||||
files outside the source set), the pins re-derived
|
||||
|
||||
@@ -3223,7 +3237,7 @@ parallel with §29.
|
||||
unchanged — 3 223/48 tests, 0 clippy warnings, 814/820 with the
|
||||
same six failures, 0 diffs over 860 corpus and 3 947 opentitan
|
||||
files
|
||||
- [ ] QA: hand-written interface + DPI files in every listed shape,
|
||||
- [x] QA: hand-written interface + DPI files in every listed shape,
|
||||
idempotent, comments kept; the negative pin; sweep unchanged
|
||||
|
||||
## 31. Format fences at statement level and inside class bodies (planned 2026-09-02) — M9, §2.9-3
|
||||
@@ -3329,7 +3343,7 @@ lead may start it in parallel if §30's files are settled).
|
||||
3 234/0/42); corpus 814/820, 860 files byte-identical to the 0.34.0
|
||||
binary; opentitan census 9 fenced files of 3 947 — 4 moved, each
|
||||
keeping its own fenced bytes, `--check` counts unchanged
|
||||
- [ ] QA: fences in every statement scope listed and in the three
|
||||
- [x] QA: fences in every statement scope listed and in the three
|
||||
deferred places (must be inert, never corrupt); an `off` with no
|
||||
`on` in each scope (runs to the scope end only); nested fences;
|
||||
`--lines` over a fenced statement; `--fix` still declines inside
|
||||
@@ -3474,7 +3488,7 @@ formatter collide with §30's tf.rs/module.rs at merge; sequential).
|
||||
- [x] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
|
||||
byte-identical (strict path untouched); opentitan read-only sweep
|
||||
unchanged
|
||||
- [ ] QA: type each of the (a)–(f) shapes into the real server against
|
||||
- [x] QA: type each of the (a)–(f) shapes into the real server against
|
||||
an opentitan file and read the published diagnostics and the
|
||||
outline; the fuzzers re-run; strict-mode parity re-derived
|
||||
|
||||
@@ -3646,7 +3660,7 @@ linter-expansion-1/README.md (new), TODO §33. Worktree `lint-1`.
|
||||
- [x] Gates: fmt/clippy/`cargo test --workspace`; corpus 814/820
|
||||
byte-identical (formatter untouched); opentitan read-only
|
||||
`lucisv check` census + timing
|
||||
- [ ] QA: every new rule attacked with hand-written true positives and
|
||||
- [x] QA: every new rule attacked with hand-written true positives and
|
||||
near-misses; the false-positive census re-read; toggles exercised
|
||||
through the real server (`workspace/didChangeConfiguration`)
|
||||
|
||||
@@ -3774,6 +3788,336 @@ Every suite and sweep under `tools/guard.sh`.
|
||||
- [x] Gates (guarded): fmt/clippy/`cargo test --workspace`; corpus
|
||||
814/820 byte-identical; vsix smoke; opentitan read-only census +
|
||||
timing vs 0.36.0
|
||||
- [ ] QA: options attacked (bad key/kind/range/regex on both front
|
||||
- [x] QA: options attacked (bad key/kind/range/regex on both front
|
||||
ends), every rule with near-misses, the census re-read
|
||||
|
||||
## 35. Linter expansion, wave 3 (planned 2026-09-04) — the remaining Verible rules
|
||||
|
||||
After §34 (54 rules, options end to end). The twenty Verible rules not
|
||||
yet in lucisv, each a small file on the §33/§34 pattern (severity,
|
||||
Verible name and default cited, options through `OptionSpec`, true
|
||||
positives and near-misses, a `.lint` case, corpus + opentitan counts
|
||||
with ten findings classified; every new gap between tokens a rule reads
|
||||
is the parser's, not the rule's). Dev Opus 5, QA Sonnet 5, worktree
|
||||
`lint-3`, every suite and sweep under `tools/guard.sh`. Feature README:
|
||||
`docs/features/linter-expansion-3/README.md`.
|
||||
|
||||
Rules (Verible default → lucisv default; severity; options):
|
||||
- `module-begin-block` (on → on; Style): a `begin`/`end` at module scope.
|
||||
- `legacy-generate-region` (off → off; Style): `generate … endgenerate`.
|
||||
- `legacy-genvar-declaration` (off → off; Style): a `genvar` declared
|
||||
outside the `for` header.
|
||||
- `v2001-generate-begin` (on → on; Style): a bare `begin` in a generate
|
||||
region.
|
||||
- `explicit-function-lifetime` / `explicit-task-lifetime` (on → on;
|
||||
Style): `automatic`/`static` stated outside classes.
|
||||
- `positive-meaning-parameter-name` (on → on; Style): no `disable_`
|
||||
prefixed parameters.
|
||||
- `suggest-parentheses` (on → on; Style): `a ? b : c` inside another
|
||||
ternary or a mixed-precedence expression without parentheses (Verible's
|
||||
shape, cited).
|
||||
- `unpacked-dimensions-range-ordering` (on → on; Style): `[N-1:0]`
|
||||
unpacked.
|
||||
- `uvm-macro-semicolon` (off → off; Warning): `` `uvm_* `` macros ending
|
||||
in `;`.
|
||||
- `create-object-name-match` (on → on; Warning): `type_id::create("x")`
|
||||
whose string differs from the variable.
|
||||
- `numeric-format-string-style` (off → off; Style): `%d`/`%h` prefixes
|
||||
in format strings.
|
||||
- `macro-string-concatenation` (off → off; Warning): `` `"…`" `` misuse.
|
||||
- `disable-statement` (off → off; Warning): `disable` outside a
|
||||
`fork`/sequential block.
|
||||
- `forbidden-macro` (on → on; Warning; option `macros` list, default
|
||||
Verible's `uvm_warning`) and `forbidden-symbol` (on → on; Warning;
|
||||
option `symbols` list, default `$psprintf`, `$random`, `$dist_*` per
|
||||
Verible — folding `invalid-system-task-function`'s list into an
|
||||
option if the two overlap; say which).
|
||||
- `endif-comment` (off → off; Style; safe fix appends `// name`).
|
||||
- `forbid-line-continuations` (on → on; Style): a `\` continuation
|
||||
inside a string literal.
|
||||
- `dff-name-style` (off → off; Style; options `input`, `output`,
|
||||
`waive_ifs_with_conditions`, `waive_lhs_regex` as Verible).
|
||||
- `proper-parameter-declaration` (off → off; Style; options
|
||||
`package_allow_parameter`, `package_allow_localparam`).
|
||||
- `void-cast`'s named-call half (Verible's forbidden-call list) as an
|
||||
option on the existing rule.
|
||||
Plus the LOW from §34's QA: a checked-in `tests/e2e.rs` case for
|
||||
`lucisv.lint.options` over the wire. Docs: the toggles regenerated,
|
||||
README.md rows, docs-site sections, coverage_gaps "linter" addendum.
|
||||
- [x] the twenty rules, each with tests and counts
|
||||
- [x] `void-cast` option; `forbidden-*` lists; `invalid-system-task-
|
||||
function` reconciled
|
||||
- [x] e2e case for `lucisv.lint.options`
|
||||
- [x] docs + regenerated toggles
|
||||
- [x] Gates (guarded): fmt/clippy/`cargo test --workspace`; corpus
|
||||
814/820 byte-identical; vsix smoke; opentitan census + timing
|
||||
- [x] QA: every rule attacked; census re-read; options attacked
|
||||
|
||||
|
||||
## 36. Small items, round 3 (planned 2026-09-04) — topo §2.9-24, §2.9-25, atomic writes
|
||||
|
||||
One lane, in the main tree (owner's call: no worktree, no parallel lane; QA
|
||||
reads the same tree). Dev: Opus 5. QA: Sonnet 5. Feature README:
|
||||
`docs/features/small-items-3/README.md`. Ships as 0.40.0.
|
||||
|
||||
**File ownership** (the whole tree is free, but this is the expected touch
|
||||
set — anything outside it is named in the work log):
|
||||
`crates/vlog_parser/src/parser/{item.rs,instance.rs,recover_list.rs}`,
|
||||
`crates/vlog_parser/src/ast/{mod.rs,module.rs}`,
|
||||
`crates/vlog_parser/tests/error_recovery.rs`,
|
||||
`crates/vlog_formatter/src/format/item.rs` (one arm),
|
||||
`crates/vlog_linter/src/rules/{module_begin_block,v2001_generate_begin}.rs`
|
||||
and every exhaustive `ItemKind` match the new variant reaches
|
||||
(`vlog_semantic`, `vlog_refactor`, `lucisv_server`, `vlog_linter/visit.rs`),
|
||||
`crates/lucisv_core/src/{atomic.rs (new),cache.rs,lib.rs}`,
|
||||
`crates/lucisv/src/{main.rs,lint.rs}`, the two rules' rows in `README.md`
|
||||
and `docs/site/src/content/docs/reference/rules.md`, `docs/topo.md` §2.9
|
||||
(strike 24 and 25 — lead does this at review), this section.
|
||||
|
||||
### 36.1 A bare `begin … end` at module scope or in a generate region is recovered as a block (topo §2.9-25)
|
||||
|
||||
Today `parse_keyword_item` has no `begin` arm, so the item fails with
|
||||
"expected item", `item_or_recover` skips to a sync point and the rest of the
|
||||
unit is lost. Wanted: in **tolerant mode only**, the block is parsed and kept.
|
||||
|
||||
- New `ItemKind::GenBlock(Box<GenBlock>)` — the existing generate-block node
|
||||
(`is_block: true`, label optional). No new node type.
|
||||
- `parse_keyword_item`: a `"begin"` arm. Strict mode: the same "expected
|
||||
item" error as today (byte-identity of every corpus file depends on the
|
||||
strict parser refusing this; nothing about strict mode changes).
|
||||
Tolerant mode: `self.record("`begin`/`end` block is not a module item")`
|
||||
*at the `begin` keyword*, then `parse_gen_block()` and wrap it. The
|
||||
diagnostic is not optional: the file must still be reported as not
|
||||
parsing cleanly, so the formatter's "zero errors or nothing" contract
|
||||
keeps refusing it exactly as before.
|
||||
- Consumers, each the boring choice: the formatter prints it the way
|
||||
`gen_block` prints an `if` arm's block (indent the items, `end`, the end
|
||||
label if any) — it never reaches output today (a diagnostic is always
|
||||
recorded) but the arm exists so a future range/tolerant printer has
|
||||
nothing to invent; the semantic binder walks its items as one unnamed
|
||||
generate block scope, the same scope shape an unlabeled `if` arm's block
|
||||
gets (find how `GenIf` arms are bound and reuse that path — do not invent
|
||||
a scope kind); `visit.rs`/outline/refactor walkers descend into
|
||||
`items` and nothing else.
|
||||
- The two rules stop reading an error leaf: `begin_block(item)` returns the
|
||||
`begin` keyword's range (`span.start .. +5`) of an `ItemKind::GenBlock`
|
||||
and `None` for everything else; delete `first_word_is_begin`. Doc strings
|
||||
of both rules: replace the "parser rejects … rest of the module is lost"
|
||||
paragraph with the truth (the parser recovers the block in tolerant mode
|
||||
and records a diagnostic; the block's items are visible to every other
|
||||
rule). Same paragraph in `README.md`'s rule rows and `rules.md`.
|
||||
- Tests (in `tests/error_recovery.rs` and the two rules' modules):
|
||||
`a_module_scope_begin_block_keeps_its_items_and_the_items_after_it`
|
||||
(block with a `wire` inside, an `assign` after it, `endmodule` consumed,
|
||||
exactly one diagnostic at `begin`); the generate-region twin; strict mode
|
||||
still refuses both (an `Err`, not a node); an `end : label` on the block
|
||||
round-trips into `end_label`; a nested `begin` inside the block recovers
|
||||
the same way (two diagnostics, both blocks kept); the two rules each fire
|
||||
once, at the keyword, and a *different* rule sees a violation written
|
||||
inside the block (proof the items survive); the size pins in
|
||||
`ast::size_pins` unchanged (the variant is boxed).
|
||||
|
||||
### 36.2 A half-typed `#(` override whose value could read as a call (topo §2.9-24)
|
||||
|
||||
Source (the QA finding in the header-recovery README, verbatim):
|
||||
```
|
||||
module m;
|
||||
sub #(.WIDTH(8), .DEPTH(
|
||||
u0 (.a(x), .b(y));
|
||||
endmodule
|
||||
```
|
||||
The value of `.DEPTH(` is parsed greedily; `u0 (.a(x), .b(y))` is a legal
|
||||
call with named arguments, so no error fires inside the list and the whole
|
||||
instantiation collapses to an item-level `Error`. Wanted: the element
|
||||
`.DEPTH(` is an error element, `.WIDTH(8)` survives, `u0` is an instance
|
||||
with two connections, one diagnostic.
|
||||
|
||||
- One lookahead in `parse_connection`, tolerant mode only, before the value
|
||||
is parsed (`parse_expr_or_type`): `fn value_runs_into_next_instance(&self)
|
||||
-> bool`. Walk tokens from the cursor with a bracket depth starting at 0.
|
||||
A closer that would take the depth below 0 is the value's own `)`: return
|
||||
`false` — the value closes and is parsed normally. At depth 0, an
|
||||
identifier that is the first token of its line and whose next token is
|
||||
`(` is *remembered* as the candidate next instance. A `;` at depth 0, a
|
||||
sync keyword (`endmodule`, `endinterface`, … — reuse the predicate
|
||||
`at_sync_stop` is built on) or EOF ends the walk: return whether a
|
||||
candidate was seen. That is: the value's `(` is never closed **and**
|
||||
something that looks like the next instance sits inside it. On a valid
|
||||
file the walk ends at the value's `)` after a handful of tokens, so cost
|
||||
is nothing; only an unclosed value walks to the next `;`.
|
||||
- When it returns `true`, fail the element with an error whose span is the
|
||||
unclosed `(` (`paren_start`), message "unclosed `(` in a port or parameter
|
||||
connection". `element_or_recover` turns it into the error element and the
|
||||
existing skip (bracket-seeded, stops at the first token of a new line)
|
||||
must leave the cursor on `u0`; `list_ends` then ends the override list
|
||||
(recovered, no comma), `close_list` forgives the missing `)`, and the
|
||||
instance loop reads `u0`. Verify that tree exactly; if the skip lands
|
||||
elsewhere, fix the skip's start, not the lookahead.
|
||||
- The same helper covers the connection list: `sub u0 (.a(` ⏎ `u1 (.b(y));`
|
||||
costs one connection and keeps `u1` as a second instance.
|
||||
- The ambiguous shape stays ambiguous: with the parens balancing
|
||||
(`.D(` ⏎ `u0 (.a(x)));`) the value closes, the walk returns `false`, the
|
||||
greedy parse wins — pin that as a test so nobody "fixes" it later.
|
||||
- Tests: the README shape above (params `[Ok, Error]`, one instance, two
|
||||
connections, one diagnostic at the `(`, `endmodule` consumed); the
|
||||
connection-list twin; the balanced-parens control; a legal multi-line
|
||||
value `.DEPTH(` ⏎ `f(1)` ⏎ `)` parses identically in strict and tolerant
|
||||
mode (the parity test `tolerant_parse_equals_strict_parse_on_valid_sources`
|
||||
plus a direct case); the header-recovery README's finding gets a work-log
|
||||
line pointing here.
|
||||
|
||||
### 36.3 Atomic in-place writes (§1 backlog item, QA find of 2026-08-25)
|
||||
|
||||
`process_file` (`lucisv/src/main.rs`) and `--fix` (`lucisv/src/lint.rs`)
|
||||
write with `fs::write`, which truncates then writes; `cache.rs` already does
|
||||
tempfile + rename by hand. One shared helper, three users.
|
||||
|
||||
- `crates/lucisv_core/src/atomic.rs`: `pub fn write_atomic(path: &Path,
|
||||
bytes: &[u8]) -> io::Result<()>`. Resolve symlinks first
|
||||
(`fs::canonicalize` when the path exists — `fs::write` writes *through* a
|
||||
symlink and a rename onto the link would replace it with a file; the
|
||||
canonical target is what gets replaced). Temp file in the target's
|
||||
directory, `.{file_name}.{pid}.lucisv-tmp`; write; copy the target's
|
||||
permissions onto it when the target exists (`set_permissions`, so a
|
||||
0600 or 0755 file stays that way); `rename` onto the target; on any
|
||||
failure after the temp exists, remove it and return the error. No new
|
||||
dependency.
|
||||
- `cache.rs` uses the helper instead of its inline copy (behaviour
|
||||
identical; its `no_temporary_file_is_left_behind` test keeps passing).
|
||||
`main.rs:309` and `lint.rs:315` call it.
|
||||
- Tests in `atomic.rs`: bytes land; no temp file left in the directory
|
||||
after success; after a failed rename (target path is a directory) no
|
||||
temp file is left and `Err` comes back; permissions preserved
|
||||
(`#[cfg(unix)]`); writing through a symlink replaces the *target* and the
|
||||
link still points at it; a new file (no prior target) is created.
|
||||
|
||||
### Gates (dev runs, all guarded)
|
||||
|
||||
`cargo fmt -p` per touched crate; `cargo clippy --all-targets` clean;
|
||||
`tools/guard.sh -- cargo test --workspace`; `tools/guard.sh --
|
||||
tools/corpus_check.sh` still 814/820 with the same six failures; the
|
||||
`tests/error_recovery.rs` truncation and single-character-deletion fuzz
|
||||
tests green (they are the termination guard for 36.1/36.2). Lead at review:
|
||||
byte-identity of every corpus file against the cached 0.39.0 binary,
|
||||
opentitan read-only sweep, vsix smoke, 0.40.0.
|
||||
|
||||
- [x] 36.1 `ItemKind::GenBlock`, the `begin` arm, consumers, the two rules
|
||||
- [x] 36.2 the lookahead, the four tests
|
||||
- [x] 36.3 `write_atomic`, three users, tests
|
||||
- [x] docs: feature README, rule rows, header-recovery work-log line
|
||||
- [x] Gates (guarded)
|
||||
- [x] QA: every shape above typed against the tolerant parser and the two
|
||||
rules; the ambiguous control; strict/tolerant parity re-run; the
|
||||
truncation fuzzers re-run; atomic writes attacked (symlink, mode,
|
||||
directory target, concurrent writers on one inode) — REWORK (small):
|
||||
`mismatched-labels` had no arm for the block; fixed by the lead at
|
||||
review with a test, plus the LOW doc comment and a read-only-target
|
||||
refusal in `write_atomic` (parity with the old `fs::write`)
|
||||
|
||||
## 37. Server residue from §10 (planned 2026-09-04) — lazy codeAction resolve, the inlayHint zero, `locate` onto `DeclPositions`
|
||||
|
||||
One lane in the main tree, dev Opus 5 then QA Sonnet 5, same protocol as
|
||||
§36 (lead snapshots the diff before QA; QA never runs a git command that
|
||||
rewrites the tree). Feature README: `docs/features/lazy-code-action/README.md`
|
||||
(one README for the three, sections per item). Ships as 0.41.0.
|
||||
|
||||
**Expected touch set:** `crates/lucisv_server/src/{ports.rs,code_action.rs,
|
||||
locate.rs,nav.rs,symbols.rs,inlay.rs,main.rs,state.rs,perf.rs}`,
|
||||
`crates/lucisv_server/src/server/{dispatch.rs,mod.rs}`,
|
||||
`crates/lucisv_server/tests/e2e.rs`, `crates/vlog_refactor/src/ports/mod.rs`
|
||||
(only if the offer needs a new one-file question), the §10 lines this closes
|
||||
(1236–1249 and 1293), `docs/features/server-lint/README.md`'s resolve note,
|
||||
this section. Anything else is named in the work log.
|
||||
|
||||
### 37.1 `codeAction/resolve` for the port refactorings (§10, owner-approved)
|
||||
|
||||
`ports::code_actions` costs ~1.4 ms per instantiating file plus a 13 ms
|
||||
floor on every cursor move (`docs/performance_take2.md` §6a: 185 ms at a
|
||||
128-file fan-out, to offer zero actions), because the *offer* already
|
||||
computes the full edit over `Workspace::module_sources` — the module's
|
||||
fan-out **plus every open buffer**, each read as text. The quick fixes in
|
||||
`code_action.rs` are cheap and stay eager; only the port actions change.
|
||||
|
||||
- **The offer is local.** Whether an action exists at the cursor is a
|
||||
one-file question plus, for a cursor on an instantiation, the instantiated
|
||||
module's own declaration (`vlog_refactor::module_definition` through the
|
||||
index — one file, the way `inlay.rs`'s `Plans::read` does it). Run the
|
||||
engine's `port_actions` over exactly those sources to learn which actions
|
||||
exist; throw the edits away. No fan-out is read. The title's count
|
||||
("updates N instantiations") comes from the index
|
||||
(`instantiations_of(name)` — say in the doc whether that is instances or
|
||||
files, and word the title to match); the unsaved-buffer case in
|
||||
`an_unsaved_buffer_contributes_the_instantiation_the_index_has_not_seen`
|
||||
is answered by the *resolved* edit, which is still exact — move that pin
|
||||
to resolve.
|
||||
- **Resolve computes the edit.** Each offered action carries `data`
|
||||
(`{uri, position, title}`) and no `edit`. `codeAction/resolve` re-runs
|
||||
today's eager path at that position and returns the action whose title
|
||||
matches, with its `edit`. No match (the buffer changed under the
|
||||
lightbulb) is an error response, `"the action is no longer available"`,
|
||||
not a silent empty edit. Advertise `resolve_provider: Some(true)`.
|
||||
- **A client that cannot resolve gets today's answer.** Read
|
||||
`textDocument.codeAction.resolveSupport.properties` at `initialize`; only
|
||||
when it lists `"edit"` is the offer lazy. Keep the flag in the server
|
||||
state beside whatever `main.rs` already reads from the client
|
||||
capabilities (the range-formatting registration is the precedent).
|
||||
- Tests: the lazy offer's titles and kinds equal the eager offer's, over
|
||||
the `crowded` tree; the resolved `WorkspaceEdit` is byte-equal to the
|
||||
eager one (both cursor shapes: a port declaration, an instantiation with
|
||||
missing connections); the no-resolveSupport client gets the eager shape;
|
||||
a resolve after the document changed errors; the offer over
|
||||
`crowded(40)` reads none of the noise files and none of the fan-out
|
||||
(pin it the way `the_files_a_code_action_reads_are_the_modules_own_fan_out`
|
||||
pins the eager path — through what the offer asks the workspace for);
|
||||
an e2e case over the wire (`tests/e2e.rs`): initialize with
|
||||
resolveSupport → `codeAction` returns `data` and no `edit` →
|
||||
`codeAction/resolve` returns the edit; initialize without → the edit is
|
||||
inline. `perf.rs`'s `a_code_action_at_an_instantiation_before_and_after`
|
||||
gains an "offer" column; report the three numbers in the work log.
|
||||
|
||||
### 37.2 `inlayHint` returns 0 at the default scope where workspace scope returns 4 (§10 / take-2 §8)
|
||||
|
||||
Investigate before fixing: `Plans::read` asks `module_definition` of the
|
||||
index, and at folder or default scope the instantiated module's file may
|
||||
not be in the index even though §4b says the default scope now answers
|
||||
cross-file questions (the `didOpen` widen). Find which lookup the
|
||||
neighbours (hover, signature help, completion) use that inlay does not,
|
||||
and make inlay use it. Deliverable is one of: a fix with a test at the
|
||||
default scope (a `sub.sv` outside the opened folder, `top.sv` inside it,
|
||||
hints appear after the widen), or — if the zero is correct — a paragraph
|
||||
in the README saying exactly why, for the lead to rule on. Not a gate.
|
||||
|
||||
### 37.3 `locate::location` onto `DeclPositions` (§10, filed)
|
||||
|
||||
`Def::lines.positions` (`DeclPositions { name, decl }`, `Some` for every
|
||||
file-scope declaration) already holds the client-side ranges, so
|
||||
`textDocument/definition`, references, the lens and both hierarchies need
|
||||
not read a file to convert an indexed span. Add the index-only path in
|
||||
`locate.rs` for a `Def` whose positions are recorded (members keep the
|
||||
file-read path — they have none) and route `nav.rs`/`symbols.rs`'s
|
||||
file-scope answers through it. Pins: the index-only `Location` equals the
|
||||
file-read one over files with multi-byte and astral characters (UTF-16
|
||||
surrogates), CRLF and a BOM; a file-scope definition answers without a
|
||||
`file_view` being created (assert through whatever the view cache exposes,
|
||||
or add a test-only counter — say which); a definition request over an
|
||||
opentitan file timed before/after, read-only, in the work log.
|
||||
|
||||
### Gates (dev, guarded)
|
||||
|
||||
`cargo fmt -p` per touched crate; clippy clean; `tools/guard.sh -- cargo
|
||||
test --workspace`; `tools/guard.sh -- tools/corpus_check.sh` unchanged
|
||||
(814/820, same six); the e2e suite green; vsix smoke. Lead at review:
|
||||
byte-identity vs 0.40.0, opentitan read-only sweep, 0.41.0.
|
||||
|
||||
- [x] 37.1 lazy offer + resolve + capability gate + e2e + perf column
|
||||
- [x] 37.2 inlayHint: fix with test, or the written finding — the written
|
||||
finding (the zero is correct), plus two default-scope tests
|
||||
- [x] 37.3 `locate` index-only path + pins + timing
|
||||
- [x] docs: feature README; §10 lines ticked; server-lint note
|
||||
- [x] Gates (guarded)
|
||||
- [x] QA: resolve attacked (stale document, wrong data, missing data,
|
||||
client without resolveSupport, both cursor shapes, unsaved buffer);
|
||||
inlay at the default scope against a real two-folder tree; locate
|
||||
equality over the encoding shapes; opentitan timing re-derived —
|
||||
PASS, no findings above LOW; offer ~4.5 ms vs eager ~77 ms over the
|
||||
wire at the 128-file fan-out
|
||||
@@ -9,6 +9,7 @@ use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
|
||||
use lucisv_core::atomic::write_atomic;
|
||||
use lucisv_core::config::FileConfig;
|
||||
use rayon::prelude::*;
|
||||
use vlog_formatter::fence::{self, Region};
|
||||
@@ -312,7 +313,7 @@ fn check_one(
|
||||
};
|
||||
let index = LineIndex::new(rewritten.as_deref().unwrap_or(&src));
|
||||
if let Some(text) = rewritten {
|
||||
if let Err(e) = std::fs::write(file, &text) {
|
||||
if let Err(e) = write_atomic(file, text.as_bytes()) {
|
||||
return failed(format!("{path}: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ use std::process::ExitCode;
|
||||
use rayon::prelude::*;
|
||||
|
||||
use args::{Command, Options};
|
||||
use lucisv_core::atomic::write_atomic;
|
||||
use lucisv_core::cache::{content_hash, Cache, Entry};
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use lucisv_core::filelist;
|
||||
@@ -306,7 +307,7 @@ fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) ->
|
||||
FileResult::plain(Outcome::Changed(diff::unified(&name.to_string(), &src, &out)))
|
||||
} else if opts.check {
|
||||
FileResult::plain(Outcome::Changed(format!("would reformat: {name}\n")))
|
||||
} else if let Err(e) = std::fs::write(file, &out) {
|
||||
} else if let Err(e) = write_atomic(file, out.as_bytes()) {
|
||||
FileResult::plain(Outcome::Failed(format!("{name}: {e}")))
|
||||
} else {
|
||||
// The bytes now on disk are formatted, so they are what the cache
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
//! Replacing a file's contents without ever leaving it half written.
|
||||
//!
|
||||
//! `fs::write` truncates the target and then writes into it, so a crash, a
|
||||
//! full disk or a `^C` between the two leaves the user's source truncated —
|
||||
//! and lucisv's first invariant is that it never corrupts code. Every
|
||||
//! in-place write goes through [`write_atomic`] instead: a sibling temp file
|
||||
//! gets the bytes, and a `rename` over the target publishes them in one step
|
||||
//! that either happened or did not.
|
||||
//!
|
||||
//! See `docs/features/small-items-3/README.md`.
|
||||
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Writes `bytes` to `path`, replacing whatever was there in one step.
|
||||
///
|
||||
/// A temp file beside the target takes the bytes, inherits the target's
|
||||
/// permissions when there is a target, and is renamed onto it — `rename` is
|
||||
/// atomic within a directory on every platform lucisv ships to, so a reader
|
||||
/// sees either the old file or the new one and never a truncated one. A
|
||||
/// failure anywhere after the temp exists removes it before returning.
|
||||
///
|
||||
/// A symlinked target is resolved first: `fs::write` writes *through* a
|
||||
/// symlink, so replacing the link itself would silently redirect it at a new
|
||||
/// file and leave the real one stale. The canonical path is what gets
|
||||
/// replaced, which is also what makes the temp land on the target's own
|
||||
/// filesystem — `rename` cannot cross one.
|
||||
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
let target = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
|
||||
// A rename replaces a file whatever its mode, so a read-only target would
|
||||
// be silently overwritten where `fs::write` refuses it. Keep the refusal:
|
||||
// a file someone made read-only is asking not to be rewritten in place.
|
||||
if fs::metadata(&target).is_ok_and(|m| m.permissions().readonly()) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
format!("{} is read-only", path.display()),
|
||||
));
|
||||
}
|
||||
let tmp = temp_path(&target)?;
|
||||
if let Err(e) = fs::write(&tmp, bytes) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(e);
|
||||
}
|
||||
// A file someone made read-only, or executable, keeps its mode: the temp
|
||||
// was created with the process umask, not with the target's bits. No
|
||||
// target means a new file, which takes the umask as `fs::write` would.
|
||||
if let Ok(meta) = fs::metadata(&target) {
|
||||
let _ = fs::set_permissions(&tmp, meta.permissions());
|
||||
}
|
||||
if let Err(e) = fs::rename(&tmp, &target) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The temp file's path: hidden, in the target's own directory, and stamped
|
||||
/// with the process id so two lucisv runs over one tree cannot collide.
|
||||
fn temp_path(target: &Path) -> io::Result<PathBuf> {
|
||||
let dir = target.parent().unwrap_or_else(|| Path::new("."));
|
||||
let name = target
|
||||
.file_name()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no file name to write"))?;
|
||||
let mut tmp = std::ffi::OsString::from(".");
|
||||
tmp.push(name);
|
||||
tmp.push(format!(".{}.lucisv-tmp", std::process::id()));
|
||||
Ok(dir.join(tmp))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A directory that removes itself, the way `cache.rs`'s own tests have
|
||||
/// one — no dependency, and no leftovers under `target/`.
|
||||
struct TempDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"lucisv-atomic-{tag}-{}-{:?}",
|
||||
std::process::id(),
|
||||
std::thread::current().id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("create temp dir");
|
||||
TempDir { path }
|
||||
}
|
||||
|
||||
fn file(&self, name: &str) -> PathBuf {
|
||||
self.path.join(name)
|
||||
}
|
||||
|
||||
/// Every name in the directory, so a test can say what is *not* there.
|
||||
fn names(&self) -> Vec<String> {
|
||||
let mut out: Vec<String> = fs::read_dir(&self.path)
|
||||
.expect("read dir")
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bytes_land_and_no_temp_file_is_left_behind() {
|
||||
let dir = TempDir::new("plain");
|
||||
let file = dir.file("a.sv");
|
||||
fs::write(&file, "old\n").expect("seed");
|
||||
write_atomic(&file, b"new\n").expect("write");
|
||||
assert_eq!(fs::read_to_string(&file).expect("read"), "new\n");
|
||||
assert_eq!(dir.names(), vec!["a.sv".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_exist_yet_is_created() {
|
||||
let dir = TempDir::new("create");
|
||||
let file = dir.file("new.sv");
|
||||
write_atomic(&file, b"hello\n").expect("write");
|
||||
assert_eq!(fs::read_to_string(&file).expect("read"), "hello\n");
|
||||
assert_eq!(dir.names(), vec!["new.sv".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_that_cannot_happen_is_an_error_and_leaves_no_temp() {
|
||||
// A directory standing where the file should be: the write succeeds,
|
||||
// the rename cannot.
|
||||
let dir = TempDir::new("dirtarget");
|
||||
let target = dir.file("occupied");
|
||||
fs::create_dir(&target).expect("create dir");
|
||||
let err = write_atomic(&target, b"x\n").expect_err("a directory cannot be replaced");
|
||||
assert!(err.to_string().len() > 1, "{err}");
|
||||
assert_eq!(dir.names(), vec!["occupied".to_string()], "the temp file was cleaned up");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writing_the_same_path_twice_leaves_one_file() {
|
||||
let dir = TempDir::new("twice");
|
||||
let file = dir.file("a.sv");
|
||||
write_atomic(&file, b"one\n").expect("write");
|
||||
write_atomic(&file, b"two\n").expect("write");
|
||||
assert_eq!(fs::read_to_string(&file).expect("read"), "two\n");
|
||||
assert_eq!(dir.names(), vec!["a.sv".to_string()]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_targets_permissions_are_preserved() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = TempDir::new("modes");
|
||||
for mode in [0o600, 0o755] {
|
||||
let file = dir.file(&format!("m{mode:o}.sv"));
|
||||
fs::write(&file, "old\n").expect("seed");
|
||||
fs::set_permissions(&file, fs::Permissions::from_mode(mode)).expect("chmod");
|
||||
write_atomic(&file, b"new\n").expect("write");
|
||||
let got = fs::metadata(&file).expect("stat").permissions().mode() & 0o777;
|
||||
assert_eq!(got, mode, "mode {mode:o} was not preserved");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_read_only_target_is_refused_and_left_alone() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = TempDir::new("readonly");
|
||||
let file = dir.file("ro.sv");
|
||||
fs::write(&file, "old\n").expect("seed");
|
||||
fs::set_permissions(&file, fs::Permissions::from_mode(0o444)).expect("chmod");
|
||||
let err = write_atomic(&file, b"new\n").expect_err("a read-only file is not replaced");
|
||||
assert_eq!(err.kind(), io::ErrorKind::PermissionDenied, "{err}");
|
||||
assert_eq!(fs::read_to_string(&file).expect("read"), "old\n");
|
||||
assert_eq!(dir.names(), vec!["ro.sv".to_string()], "no temp file was made");
|
||||
fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).expect("restore");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn writing_through_a_symlink_replaces_the_target_not_the_link() {
|
||||
let dir = TempDir::new("symlink");
|
||||
let real = dir.file("real.sv");
|
||||
let link = dir.file("link.sv");
|
||||
fs::write(&real, "old\n").expect("seed");
|
||||
std::os::unix::fs::symlink(&real, &link).expect("symlink");
|
||||
write_atomic(&link, b"new\n").expect("write");
|
||||
assert_eq!(fs::read_to_string(&real).expect("read"), "new\n", "the target got the bytes");
|
||||
assert!(
|
||||
fs::symlink_metadata(&link).expect("stat").file_type().is_symlink(),
|
||||
"the link is still a link"
|
||||
);
|
||||
assert_eq!(fs::read_to_string(&link).expect("read"), "new\n", "and still points at it");
|
||||
}
|
||||
}
|
||||
@@ -87,10 +87,7 @@ impl Cache {
|
||||
if !ignore.exists() {
|
||||
let _ = std::fs::write(&ignore, "*\n");
|
||||
}
|
||||
let tmp = dir.join(format!("{FILE}.{}.tmp", std::process::id()));
|
||||
if std::fs::write(&tmp, self.render()).is_ok() && std::fs::rename(&tmp, path).is_err() {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
}
|
||||
let _ = crate::atomic::write_atomic(path, self.render().as_bytes());
|
||||
}
|
||||
|
||||
/// The file's text: one line per entry, sorted by path so that two
|
||||
@@ -397,7 +394,7 @@ mod tests {
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.filter(|n| n.ends_with(".tmp"))
|
||||
.filter(|n| n.ends_with(".tmp") || n.ends_with("-tmp"))
|
||||
.collect();
|
||||
assert!(leftovers.is_empty(), "{leftovers:?}");
|
||||
}
|
||||
|
||||
@@ -6,11 +6,14 @@
|
||||
//! the same `lucisv.toml` and skip the same files as CI's `lucisv --check`.
|
||||
//! `cache` answers the third question of the same family — whether a file
|
||||
//! needs to be processed at all, and `filelist` answers the first one the way
|
||||
//! an EDA project already does, from a `.f` file. See
|
||||
//! an EDA project already does, from a `.f` file. `atomic` is the one write
|
||||
//! path all of them share: nothing here ever truncates a file it is
|
||||
//! replacing. See
|
||||
//! `docs/features/lucisv-core-lift/README.md`, and
|
||||
//! `docs/features/{config-discovery,parallel-files,format-cache,filelist}/README.md`
|
||||
//! for the rules themselves.
|
||||
|
||||
pub mod atomic;
|
||||
pub mod cache;
|
||||
pub mod config;
|
||||
pub mod filelist;
|
||||
|
||||
@@ -755,6 +755,92 @@ endmodule
|
||||
assert_eq!(labels, ["clk_renamed:", "rst_n:", "data:"]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the default scope (TODO §37.2 / `performance_take2.md` §4b, §8)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// An opentitan-shaped tree: an IP block with its RTL and its testbench,
|
||||
/// and a shared library folder outside that block. Opening
|
||||
/// `ip/aes/dv/tb/tb.sv` at the shipped `scopeDepth` of 2 raises to
|
||||
/// `ip/aes`, so `ip/aes/rtl/sub.sv` is indexed and `dv/common/far.sv` is
|
||||
/// not — which is exactly the shape `hw/ip/aes/dv/tb/tb.sv` has against
|
||||
/// `hw/dv/sv/common_ifs/pins_if.sv`.
|
||||
fn default_scoped(name: &str) -> (Tree, Workspace, Uri, &'static str) {
|
||||
const TB: &str =
|
||||
"module tb;\n sub u_sub (clk, rst_n, data);\n far u_far (a);\nendmodule\n";
|
||||
let tree = Tree::new(name);
|
||||
fs::create_dir_all(tree.path.join("ip/aes/rtl")).expect("dirs");
|
||||
fs::create_dir_all(tree.path.join("ip/aes/dv/tb")).expect("dirs");
|
||||
fs::create_dir_all(tree.path.join("dv/common")).expect("dirs");
|
||||
tree.write("ip/aes/rtl/sub.sv", SUB);
|
||||
tree.write("dv/common/far.sv", "module far (\n input logic a\n);\nendmodule\n");
|
||||
let tb = tree.write("ip/aes/dv/tb/tb.sv", TB);
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
// The shipped default: no `index.scope`, `scopeDepth` 2.
|
||||
ws.set_client_settings(crate::settings::ClientSettings::default());
|
||||
ws.adopt_roots(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&tb).expect("uri");
|
||||
ws.set_document(uri.clone(), TB.to_string());
|
||||
ws.rebuild_index();
|
||||
(tree, ws, uri, TB)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_scope_hints_a_module_the_didopen_widen_reached() {
|
||||
// `performance_take2.md` §4b measured 0 hints at the default scope
|
||||
// where the workspace scope gives 4, and §8 filed it as a correctness
|
||||
// gap. It is not one: the hints that scope answers are exactly the
|
||||
// instantiations whose module the widen reached.
|
||||
let (tree, ws, uri, _) = default_scoped("default_scope");
|
||||
assert!(
|
||||
ws.index().files().iter().any(|f| f.ends_with("sub.sv")),
|
||||
"the widen reached the block's own RTL: {:?}",
|
||||
ws.index().files()
|
||||
);
|
||||
assert!(
|
||||
!ws.index().files().iter().any(|f| f.ends_with("far.sv")),
|
||||
"and not the library folder beside it"
|
||||
);
|
||||
|
||||
let hints = inlay_hints(&ws, &uri, everything());
|
||||
let labels: Vec<String> = hints
|
||||
.into_iter()
|
||||
.map(|h| {
|
||||
let InlayHintLabel::String(s) = h.label else { panic!("string") };
|
||||
s
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(labels, ["clk:", "rst_n:", "data:"], "the in-scope instantiation is hinted");
|
||||
drop(tree);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_out_of_scope_module_is_unhinted_exactly_as_it_is_undefined() {
|
||||
// The other half of the same finding: the `far` instantiation gets no
|
||||
// hints — and go-to-definition and hover give nothing for it either.
|
||||
// The zero is the scope's, not this module's; inlay uses the same
|
||||
// `module_definition` lookup its neighbours do.
|
||||
let (tree, ws, uri, tb) = default_scoped("out_of_scope");
|
||||
let hints = inlay_hints(&ws, &uri, everything());
|
||||
assert!(
|
||||
hints.iter().all(|hint| hint.position.line != 2),
|
||||
"nothing on the `far` line: {hints:#?}"
|
||||
);
|
||||
|
||||
let far = tb.find("far u_far").expect("the instantiation") as u32;
|
||||
assert!(crate::nav::definition(&ws, &uri, far).is_empty(), "nor does F12 answer");
|
||||
assert!(crate::hover::hover(&ws, &uri, far).is_none(), "nor does hover");
|
||||
|
||||
// And the moment the scope reaches it, all three answer.
|
||||
let mut wide = Workspace::default();
|
||||
wide.open_whole_workspace(vec![tree.path.clone()]);
|
||||
wide.set_document(uri.clone(), tb.to_string());
|
||||
let hints = inlay_hints(&wide, &uri, everything());
|
||||
assert_eq!(hints.len(), 4, "three ports plus `far`'s one: {hints:#?}");
|
||||
assert_eq!(crate::nav::definition(&wide, &uri, far).len(), 1);
|
||||
}
|
||||
|
||||
/// Order-of-magnitude perf checks, not run as part of the ordinary suite:
|
||||
/// timing assertions in a shared CI runner are flaky by nature. Run with
|
||||
/// `cargo test --release -p lucisv_server --bin lucisv-server qa_perf -- --ignored --nocapture`.
|
||||
|
||||
@@ -575,6 +575,7 @@ mod tests {
|
||||
use crate::uri::path_to_uri;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
use vlog_parser::PARSE_STACK_SIZE;
|
||||
|
||||
/// A one-file workspace with `path` open and the cursor at `needle`'s end.
|
||||
/// No files on disk: nothing here reads the index.
|
||||
@@ -1081,10 +1082,31 @@ endmodule
|
||||
// A trailing newline, so this test isolates depth from the separate
|
||||
// true-end-of-file `Eof`-adjacency case pinned above.
|
||||
text.push_str("initial begin\n");
|
||||
let (ws, uri, position) = asking(&text, "initial begin");
|
||||
assert!(!ws.document(&uri).expect("open").tokens.is_empty(), "the lexer never recurses");
|
||||
let items = inline_completions(&ws, &uri, position);
|
||||
assert!(items.is_some(), "the innermost, truly unclosed `begin` still offers its `end`");
|
||||
// Opening the document *parses* it, and since §36.1 a bare `begin` at
|
||||
// item scope is a generate block the tolerant parser descends into —
|
||||
// so this text nests the parser to `MAX_NESTING_DEPTH` and costs ~4
|
||||
// MiB of stack in a debug build. That is exactly what
|
||||
// `PARSE_STACK_SIZE` is for; every production thread that may reach a
|
||||
// parse is given it (`main.rs`), libtest's own thread is not, so the
|
||||
// body runs on one of its own. Nothing here is about the inline path,
|
||||
// which still never recurses.
|
||||
std::thread::Builder::new()
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(move || {
|
||||
let (ws, uri, position) = asking(&text, "initial begin");
|
||||
assert!(
|
||||
!ws.document(&uri).expect("open").tokens.is_empty(),
|
||||
"the lexer never recurses"
|
||||
);
|
||||
let items = inline_completions(&ws, &uri, position);
|
||||
assert!(
|
||||
items.is_some(),
|
||||
"the innermost, truly unclosed `begin` still offers its `end`"
|
||||
);
|
||||
})
|
||||
.expect("spawn")
|
||||
.join()
|
||||
.expect("the inline path crashed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -144,6 +144,7 @@ fn item_pairs(item: &Item, out: &mut Vec<Pair>) {
|
||||
ItemKind::Task(t) => task_pairs(t, out),
|
||||
ItemKind::Clocking(c) => clocking_pairs(c, out),
|
||||
ItemKind::GenerateRegion { items, .. } => items_pairs(items, out),
|
||||
ItemKind::GenBlock(b) => items_pairs(&b.items, out),
|
||||
ItemKind::GenIf(g) => gen_if_pairs(g, out),
|
||||
ItemKind::GenFor(g) => gen_block_pairs(&g.body, out),
|
||||
ItemKind::GenCase(g) => {
|
||||
|
||||
@@ -7,11 +7,18 @@
|
||||
//! buffer's own line index when there is one, and otherwise through
|
||||
//! `Workspace::file_view`, which reads a closed file at most once per
|
||||
//! generation of it rather than once per question about it.
|
||||
//!
|
||||
//! One span never needs that read at all: a **file-scope declaration**'s own
|
||||
//! name, whose client-side range the index recorded when the file was scanned
|
||||
//! ([`vlog_semantic::DeclPositions`]). [`definition_location`] is that path,
|
||||
//! and it is what `textDocument/definition` and `workspace/symbol` answer
|
||||
//! from — see `docs/features/lazy-code-action/README.md`.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_types::Location;
|
||||
use lsp_types::{Location, Position, Range};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{Def, Utf16Range};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::state::Workspace;
|
||||
@@ -27,6 +34,40 @@ pub fn location(ws: &Workspace, path: &Path, span: TextRange) -> Option<Location
|
||||
Some(Location { uri, range: Positions::new(&view.text, &view.lines).range(span) })
|
||||
}
|
||||
|
||||
/// Where an **indexed** declaration is written — its name's own range.
|
||||
///
|
||||
/// The index converted that range to client positions while it was scanning
|
||||
/// the file ([`vlog_semantic::DeclLines::positions`]), so pointing an editor
|
||||
/// at a module nobody has open is a map lookup rather than a file read: the
|
||||
/// same eight numbers, computed once at index time instead of once per
|
||||
/// question. Only **file-scope** declarations carry them; a member (a port, a
|
||||
/// parameter, a class field) records none and falls through to
|
||||
/// [`location`]'s read, which is the whole reason this is a separate function
|
||||
/// rather than a change inside that one.
|
||||
///
|
||||
/// **An open buffer keeps the read.** Its text may have moved since it was
|
||||
/// indexed, and every other answer about that buffer is computed against the
|
||||
/// text it holds now; answering this one from the index instead would make
|
||||
/// go-to-definition disagree with the document symbols beside it.
|
||||
pub fn definition_location(ws: &Workspace, path: &Path, def: &Def) -> Option<Location> {
|
||||
if ws.document_for_path(path).is_none() {
|
||||
if let Some(recorded) = def.lines.positions {
|
||||
return Some(Location { uri: path_to_uri(path)?, range: range(recorded.name) });
|
||||
}
|
||||
}
|
||||
location(ws, path, def.name_span)
|
||||
}
|
||||
|
||||
/// An index-recorded range as the protocol's own — the same four numbers,
|
||||
/// both already counted in UTF-16 code units by the file's own
|
||||
/// `LineIndex::utf16_position`, which is the converter `Positions` uses too.
|
||||
fn range(recorded: Utf16Range) -> Range {
|
||||
Range {
|
||||
start: Position { line: recorded.start.line, character: recorded.start.character },
|
||||
end: Position { line: recorded.end.line, character: recorded.end.character },
|
||||
}
|
||||
}
|
||||
|
||||
/// The 1-based line a byte offset falls on, for hover text that names a file
|
||||
/// and a line rather than jumping to it.
|
||||
///
|
||||
@@ -49,3 +90,197 @@ pub fn line_number(ws: &Workspace, path: &Path, offset: u32) -> Option<u32> {
|
||||
pub fn display_name(path: &Path) -> String {
|
||||
path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A scratch workspace root. Removed on drop.
|
||||
struct Tree {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl Tree {
|
||||
fn new(name: &str) -> Tree {
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("lucisv_server_locate_{}_{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("temp dir");
|
||||
Tree { path }
|
||||
}
|
||||
|
||||
/// Write a file as **bytes**, so a test can put a BOM or CRLF in one.
|
||||
fn write(&self, rel: &str, text: &str) -> PathBuf {
|
||||
let path = self.path.join(rel);
|
||||
fs::write(&path, text.as_bytes()).expect("write");
|
||||
path
|
||||
}
|
||||
|
||||
/// An indexed workspace over everything written so far.
|
||||
fn indexed(&self) -> Workspace {
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![self.path.clone()]);
|
||||
ws
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
/// The one declaration of `name` in the index, and the file it is in.
|
||||
fn only_def<'w>(ws: &'w Workspace, name: &str) -> (&'w Def, &'w Path) {
|
||||
let index = ws.index();
|
||||
let [def] = index.units(name) else { panic!("exactly one `{name}`") };
|
||||
(def, index.path(def.file).expect("a path"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_scope_definition_is_located_without_reading_its_file() {
|
||||
let tree = Tree::new("no_read");
|
||||
tree.write("sub.sv", "module sub (\n input logic clk\n);\nendmodule\n");
|
||||
let ws = tree.indexed();
|
||||
let (def, path) = only_def(&ws, "sub");
|
||||
|
||||
let indexed = definition_location(&ws, path, def).expect("a location");
|
||||
assert!(ws.held_views().is_empty(), "no file was read: {:?}", ws.held_views());
|
||||
|
||||
// Only now, so the comparison cannot be what filled the cache.
|
||||
let read = location(&ws, path, def.name_span).expect("a location");
|
||||
assert_eq!(indexed, read);
|
||||
assert_eq!(ws.held_views().len(), 1, "the file-read path really does read one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_two_paths_agree_over_multi_byte_astral_crlf_and_a_bom() {
|
||||
// Everything that has ever made a UTF-16 conversion disagree, in one
|
||||
// file: a BOM at offset 0, CRLF line endings, a two-byte character, a
|
||||
// three-byte one, and an astral character that is *two* UTF-16 code
|
||||
// units on its own.
|
||||
let tree = Tree::new("encodings");
|
||||
tree.write(
|
||||
"wide.sv",
|
||||
"\u{feff}// é ✓ 𝛼𝛽 — a comment\r\n\
|
||||
// 𝟘𝟙𝟚 more\r\n\
|
||||
module wide (\r\n input logic clk\r\n);\r\nendmodule\r\n",
|
||||
);
|
||||
let ws = tree.indexed();
|
||||
let (def, path) = only_def(&ws, "wide");
|
||||
|
||||
let indexed = definition_location(&ws, path, def).expect("a location");
|
||||
assert!(ws.held_views().is_empty(), "still no read");
|
||||
let read = location(&ws, path, def.name_span).expect("a location");
|
||||
assert_eq!(indexed, read, "the index-only range must be the file-read one");
|
||||
// And it really is the name, not the line: `module ` is seven UTF-16
|
||||
// units into line 2 (0-based), whatever the lines above it hold.
|
||||
assert_eq!(indexed.range.start.line, 2);
|
||||
assert_eq!(indexed.range.start.character, 7);
|
||||
assert_eq!(indexed.range.end.character, 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_still_answers_from_the_buffer() {
|
||||
// The index saw the file on disk; the buffer has since gained a line
|
||||
// above the declaration, and has not been re-indexed. An indexed span
|
||||
// is stale either way — the byte offset is the disk file's — and what
|
||||
// this pins is that the *conversion* is unchanged by this round: the
|
||||
// buffer's own line index, exactly as before, so go-to-definition and
|
||||
// the document symbols beside it still agree with each other.
|
||||
let tree = Tree::new("open_buffer");
|
||||
let path = tree.write("sub.sv", "module sub;\nendmodule\n");
|
||||
let mut ws = tree.indexed();
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri, "// typed since\nmodule sub;\nendmodule\n".to_string());
|
||||
|
||||
let (def, path) = only_def(&ws, "sub");
|
||||
let located = definition_location(&ws, path, def).expect("a location");
|
||||
assert_eq!(
|
||||
located,
|
||||
location(&ws, path, def.name_span).expect("a location"),
|
||||
"an open buffer takes the file-read path, index positions or not"
|
||||
);
|
||||
assert_eq!(located.range.start.line, 0, "byte 7 of the buffer, not of the index's file");
|
||||
assert!(ws.held_views().is_empty(), "an open buffer is never viewed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_keeps_the_file_read_path() {
|
||||
// Members carry no `DeclPositions` — see `DeclLines` — so the fallback
|
||||
// is not decoration: it is the only answer for a port.
|
||||
let tree = Tree::new("member");
|
||||
tree.write("sub.sv", "module sub (\n input logic clk\n);\nendmodule\n");
|
||||
let ws = tree.indexed();
|
||||
let index = ws.index();
|
||||
let [port] = index.member("sub", "clk") else { panic!("one `clk`") };
|
||||
assert!(port.lines.positions.is_none(), "a member records no client positions");
|
||||
let path = index.path(port.file).expect("a path");
|
||||
assert_eq!(
|
||||
definition_location(&ws, path, port),
|
||||
location(&ws, path, port.name_span),
|
||||
"and the fallback answers exactly what it always did"
|
||||
);
|
||||
assert_eq!(ws.held_views().len(), 1, "which cost the read");
|
||||
}
|
||||
|
||||
/// `LUCISV_PERF_CORPUS=/path/to/project cargo test --release -p lucisv_server --bin lucisv-server locate::tests::defining -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement over a corpus this repository does not ship — see docs/perf/README.md"]
|
||||
fn defining_over_a_real_project() {
|
||||
// TODO §37.3's own number, beside the code it measures rather than in
|
||||
// `perf.rs` — the precedent `perf::mean`'s `pub(crate)` exists for.
|
||||
// Two columns over the same corpus and the same targets: converting an
|
||||
// indexed span by reading its file, and reading it off the index.
|
||||
// **Read-only** — the corpus is opened, never written.
|
||||
let Ok(root) = std::env::var("LUCISV_PERF_CORPUS") else {
|
||||
eprintln!("LUCISV_PERF_CORPUS is unset — nothing to measure");
|
||||
return;
|
||||
};
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(crate::settings::ClientSettings {
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
..Default::default()
|
||||
});
|
||||
let started = std::time::Instant::now();
|
||||
ws.open_whole_workspace(vec![PathBuf::from(&root)]);
|
||||
let scan = started.elapsed();
|
||||
|
||||
// The targets: modules the corpus instantiates somewhere, whose single
|
||||
// declaration the index can name — what an F12 on an instantiation
|
||||
// lands on, and each in a different file.
|
||||
let names: Vec<String> =
|
||||
ws.index().instantiations().map(|(name, _)| name.to_string()).collect();
|
||||
let targets: Vec<(PathBuf, vlog_semantic::Def)> = names
|
||||
.iter()
|
||||
.filter_map(|name| {
|
||||
let path = vlog_refactor::module_definition(ws.index(), name).ok()?;
|
||||
let [def] = ws.index().units(name) else { return None };
|
||||
def.lines.positions.is_some().then(|| (path.to_path_buf(), def.clone()))
|
||||
})
|
||||
.take(200)
|
||||
.collect();
|
||||
|
||||
let indexed = crate::perf::mean(5, || {
|
||||
for (path, def) in &targets {
|
||||
std::hint::black_box(definition_location(&ws, path, def));
|
||||
}
|
||||
});
|
||||
let read = crate::perf::mean(5, || {
|
||||
for (path, def) in &targets {
|
||||
std::hint::black_box(location(&ws, path, def.name_span));
|
||||
}
|
||||
});
|
||||
let each = targets.len().max(1) as u32;
|
||||
eprintln!(
|
||||
"definition over {} indexed files of {root} (scan {scan:?}), {} targets:\n \
|
||||
index-only {indexed:?}, file-read {read:?} — {:?} vs {:?} per definition",
|
||||
ws.index().files().len(),
|
||||
targets.len(),
|
||||
indexed / each,
|
||||
read / each,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -126,6 +126,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
configuration: configuration_support(¶ms),
|
||||
token_server_cancel: token_server_cancel_support(¶ms),
|
||||
hierarchy_view,
|
||||
code_action_resolve: code_action_resolve_support(¶ms),
|
||||
};
|
||||
connection.initialize_finish(id, initialize_value(ranges_formatting)?)?;
|
||||
|
||||
@@ -261,8 +262,13 @@ fn capabilities() -> ServerCapabilities {
|
||||
CodeActionKind::new(ports::REFACTOR_PORTS),
|
||||
]),
|
||||
work_done_progress_options: WorkDoneProgressOptions::default(),
|
||||
// Every action is returned complete; there is nothing to resolve.
|
||||
resolve_provider: None,
|
||||
// The quick fixes are complete when they are offered; the port
|
||||
// refactorings are not, for a client that can ask
|
||||
// (`docs/features/lazy-code-action/README.md`). Advertised
|
||||
// unconditionally because the server can always answer a resolve
|
||||
// — including for an action that already carries its edit, which
|
||||
// it hands straight back.
|
||||
resolve_provider: Some(true),
|
||||
})),
|
||||
// The port refactorings. `lucisv.addPort` needs a declaration typed by
|
||||
// the user, which no code action can carry, and a Vim user has no
|
||||
@@ -499,6 +505,24 @@ fn snippet_support(params: &InitializeParams) -> bool {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the client can fetch a code action's `edit` after the fact —
|
||||
/// `textDocument.codeAction.resolveSupport.properties` listing `"edit"`.
|
||||
///
|
||||
/// The property list is the capability: a client that can resolve `title`
|
||||
/// alone cannot be offered an action without its edit, so nothing short of
|
||||
/// `"edit"` counts. A client that says nothing gets every action complete, as
|
||||
/// every client did before this was read
|
||||
/// (`docs/features/lazy-code-action/README.md`).
|
||||
fn code_action_resolve_support(params: &InitializeParams) -> bool {
|
||||
params
|
||||
.capabilities
|
||||
.text_document
|
||||
.as_ref()
|
||||
.and_then(|text_document| text_document.code_action.as_ref())
|
||||
.and_then(|code_action| code_action.resolve_support.as_ref())
|
||||
.is_some_and(|resolve| resolve.properties.iter().any(|property| property == "edit"))
|
||||
}
|
||||
|
||||
/// Whether the client applies a `workspace/applyEdit` request.
|
||||
///
|
||||
/// A client that did not say so gets a command's edit back as the request
|
||||
@@ -1148,6 +1172,46 @@ mod tests {
|
||||
assert!(kinds.contains(&CodeActionKind::QUICKFIX));
|
||||
assert!(kinds.contains(&CodeActionKind::new(code_action::FIX_ALL)));
|
||||
assert!(kinds.contains(&CodeActionKind::new(ports::REFACTOR_PORTS)));
|
||||
assert_eq!(
|
||||
options.resolve_provider,
|
||||
Some(true),
|
||||
"the port refactorings are offered without their edits to a client that can ask"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_action_resolve_support_is_read_from_the_clients_own_capabilities() {
|
||||
use lsp_types::{
|
||||
ClientCapabilities, CodeActionCapabilityResolveSupport, CodeActionClientCapabilities,
|
||||
TextDocumentClientCapabilities,
|
||||
};
|
||||
assert!(
|
||||
!code_action_resolve_support(&InitializeParams::default()),
|
||||
"silence means the whole edit up front"
|
||||
);
|
||||
|
||||
let saying = |properties: &[&str]| InitializeParams {
|
||||
capabilities: ClientCapabilities {
|
||||
text_document: Some(TextDocumentClientCapabilities {
|
||||
code_action: Some(CodeActionClientCapabilities {
|
||||
resolve_support: Some(CodeActionCapabilityResolveSupport {
|
||||
properties: properties.iter().map(|p| p.to_string()).collect(),
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert!(code_action_resolve_support(&saying(&["edit"])));
|
||||
assert!(code_action_resolve_support(&saying(&["documentation", "edit"])));
|
||||
assert!(
|
||||
!code_action_resolve_support(&saying(&["documentation"])),
|
||||
"resolving anything but the edit is no use to us"
|
||||
);
|
||||
assert!(!code_action_resolve_support(&saying(&[])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -7,7 +7,7 @@ use vlog_semantic::{Def, Definition, ExternalTarget, Semantics, Symbol, SymbolId
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::includes;
|
||||
use crate::locate::location;
|
||||
use crate::locate::{definition_location, location};
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
@@ -60,7 +60,9 @@ pub fn definition(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<Location> {
|
||||
.iter()
|
||||
.filter_map(|def| {
|
||||
let path = ws.index().path(def.file)?;
|
||||
location(ws, path, def.name_span)
|
||||
// A file-scope declaration's range is already in the index, so
|
||||
// the jump costs no read of the file it lands in.
|
||||
definition_location(ws, path, def)
|
||||
})
|
||||
.collect(),
|
||||
None => Vec::new(),
|
||||
@@ -691,6 +693,36 @@ mod tests {
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cross_file_definition_reads_no_file() {
|
||||
// The jump above, asked again for what it *costs*: the target module's
|
||||
// range is in the index (`DeclPositions`), so nothing opens `sub.sv`.
|
||||
// Pinned through the view cache, which is where a read would land.
|
||||
let dir = temp_dir("no_read");
|
||||
let sub = dir.join("sub.sv");
|
||||
fs::write(&sub, "module sub (input clk);\nendmodule\n").expect("write");
|
||||
let top_path = dir.join("top.sv");
|
||||
let top_text = "module top;\n sub u_sub (.clk(1'b0));\nendmodule\n";
|
||||
fs::write(&top_path, top_text).expect("write");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
let uri = path_to_uri(&top_path).expect("uri");
|
||||
ws.set_document(uri.clone(), top_text.to_string());
|
||||
|
||||
let locations = definition(&ws, &uri, at(top_text, "sub u_sub"));
|
||||
assert_eq!(locations.len(), 1);
|
||||
assert_eq!(locations[0].range.start.character, 7, "and it is still the right answer");
|
||||
assert!(ws.held_views().is_empty(), "no file was read: {:?}", ws.held_views());
|
||||
|
||||
// `workspace/symbol` answers the same way, over the same index.
|
||||
let hits = crate::symbols::workspace_symbols(&ws, "sub");
|
||||
assert!(hits.iter().any(|hit| hit.name == "sub"), "{hits:#?}");
|
||||
assert!(ws.held_views().is_empty(), "nor did the symbol search");
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ambiguous_workspace_name_returns_every_location() {
|
||||
let dir = temp_dir("ambig");
|
||||
|
||||
@@ -1022,6 +1022,14 @@ fn a_code_action_at_an_instantiation_before_and_after() {
|
||||
let after = mean(20, || {
|
||||
black_box(crate::ports::code_actions(&ws, &uri, black_box(offset)));
|
||||
});
|
||||
// TODO §37.1's column: the *offer* a client that can resolve receives,
|
||||
// which reads the buffer and — at an instantiation — one more file,
|
||||
// whatever the fan-out is. The edit is computed by `resolve`, which is the
|
||||
// `after` column above, once, when the user clicks.
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
let offer = mean(20, || {
|
||||
black_box(crate::ports::offers(&ws, &uri, black_box(position), black_box(offset)));
|
||||
});
|
||||
let read = mean(3, || {
|
||||
black_box(ws.sources());
|
||||
});
|
||||
@@ -1035,9 +1043,10 @@ fn a_code_action_at_an_instantiation_before_and_after() {
|
||||
});
|
||||
// A measurement of an answer that was not given is worthless.
|
||||
assert_eq!(crate::ports::code_actions(&ws, &uri, offset).len(), 1);
|
||||
assert_eq!(crate::ports::offers(&ws, &uri, position, offset).len(), 1);
|
||||
eprintln!(
|
||||
"codeAction on a port of a module instantiated in 3 of {} files ({lines} lines each): \
|
||||
whole workspace {before:?}, fan-out {after:?} \
|
||||
whole workspace {before:?}, fan-out {after:?}, offer {offer:?} \
|
||||
(`sources()` alone: {read:?}; prepareRename, untouched: {prepare:?})",
|
||||
ws.index().files().len()
|
||||
);
|
||||
|
||||
@@ -12,6 +12,13 @@
|
||||
//! and `lucisv.propagatePorts` take a position and exist for the same reason a
|
||||
//! Vim user has no lightbulb: a command works everywhere a keybinding does.
|
||||
//! See `docs/features/refactor-ports/README.md`.
|
||||
//!
|
||||
//! **Two shapes of code action.** A client that can resolve is *offered*
|
||||
//! actions with no edit ([`offers`]) and asks for the edit when the user picks
|
||||
//! one ([`resolve`]); a client that cannot gets the edit up front
|
||||
//! ([`code_actions`]). The offer reads one or two files whatever the module's
|
||||
//! fan-out is, which is the whole point — see
|
||||
//! `docs/features/lazy-code-action/README.md`.
|
||||
|
||||
// See `rename.rs` for why this is a `WorkspaceEdit`'s problem and not ours.
|
||||
#![allow(clippy::mutable_key_type)]
|
||||
@@ -22,6 +29,7 @@ use std::path::{Path, PathBuf};
|
||||
use lsp_types::{
|
||||
CodeAction, CodeActionKind, CodeActionOrCommand, Position, TextEdit, Uri, WorkspaceEdit,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use vlog_parser::LineIndex;
|
||||
use vlog_refactor::{ModuleRef, RefactorEdit};
|
||||
@@ -48,6 +56,12 @@ pub fn commands() -> Vec<String> {
|
||||
|
||||
/// The port actions available at a position, each carrying its own computed
|
||||
/// edit — nothing to resolve, and nothing offered that would be refused.
|
||||
///
|
||||
/// What a client without `codeAction/resolve` gets, and what [`resolve`]
|
||||
/// re-runs to answer one that has. It reads the module's whole fan-out
|
||||
/// ([`Workspace::module_sources`]), which is ~1.4 ms per instantiating file:
|
||||
/// fine once, when the user has clicked, and not fine on every cursor move,
|
||||
/// which is why [`offers`] exists.
|
||||
pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrCommand> {
|
||||
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
||||
let Some(path) = doc.path.clone() else { return Vec::new() };
|
||||
@@ -76,6 +90,183 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrC
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What a lazily-offered action carries in place of its edit: enough to ask
|
||||
/// the same question again when the user picks it.
|
||||
///
|
||||
/// The position rather than the offset, because that is what the client
|
||||
/// speaks and what the buffer it will be re-read against is indexed by.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Offer {
|
||||
uri: Uri,
|
||||
position: Position,
|
||||
title: String,
|
||||
}
|
||||
|
||||
/// The sentence a resolve that finds nothing answers with. Not a silent empty
|
||||
/// edit: an action that has stopped applying is news, and applying nothing
|
||||
/// while saying nothing is how a user comes to distrust the lightbulb.
|
||||
const GONE: &str = "the action is no longer available.";
|
||||
/// A resolve of something this server never offered.
|
||||
const NOT_OURS: &str = "this code action carries no lucisv port refactoring to resolve.";
|
||||
|
||||
/// The port actions available at a position, **without their edits** — the
|
||||
/// offer a client that can `codeAction/resolve` is sent.
|
||||
///
|
||||
/// The question "is there an action here at all" is answered over the buffer
|
||||
/// itself plus, for a cursor on an instantiation, the instantiated module's
|
||||
/// own declaration ([`offer_sources`]) — one or two files, whatever the
|
||||
/// module's fan-out is. The edits those two files produce are thrown away;
|
||||
/// [`resolve`] computes the real one over the whole fan-out when the user
|
||||
/// clicks.
|
||||
///
|
||||
/// **The count in the title comes from the index**, since the fan-out has not
|
||||
/// been read: [`instances_of`] counts every *instance* the index has seen of
|
||||
/// the module, so `sub u1(), u2();` counts two. The eager title counts the
|
||||
/// instances the plan really rewrites, which is the same number except where
|
||||
/// the index cannot know — an unsaved buffer's new instantiation, a
|
||||
/// file-scope instantiation site (which records no edge), an instance
|
||||
/// connecting with `.*`. The two are therefore matched on the part of the
|
||||
/// title *before* that count; see [`key`].
|
||||
pub fn offers(
|
||||
ws: &Workspace,
|
||||
uri: &Uri,
|
||||
position: Position,
|
||||
offset: u32,
|
||||
) -> Vec<CodeActionOrCommand> {
|
||||
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
||||
let Some(path) = doc.path.clone() else { return Vec::new() };
|
||||
let modules = vlog_refactor::port_action_modules(&doc.text, offset);
|
||||
// A name the workspace declares twice is a refusal the engine makes over
|
||||
// the fan-out, where it can see both declarations. The offer cannot, so it
|
||||
// asks the index the same question rather than offering an action that
|
||||
// resolve would then decline.
|
||||
if modules.is_empty() || modules.iter().any(|name| declared_twice(ws, name)) {
|
||||
return Vec::new();
|
||||
}
|
||||
let sources = offer_sources(ws, &path, &doc.text, &modules);
|
||||
vlog_refactor::port_actions(&sources, &path, offset)
|
||||
.into_iter()
|
||||
.map(|action| {
|
||||
let title = counted(ws, action.title, &modules);
|
||||
let data =
|
||||
serde_json::to_value(Offer { uri: uri.clone(), position, title: title.clone() })
|
||||
.ok();
|
||||
CodeActionOrCommand::CodeAction(CodeAction {
|
||||
title,
|
||||
kind: Some(CodeActionKind::new(REFACTOR_PORTS)),
|
||||
data,
|
||||
..Default::default()
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The files an [`offers`] call reads: the buffer the request names, and the
|
||||
/// declaration of every module an instantiation under the cursor names.
|
||||
///
|
||||
/// The second is the same two steps `inlay.rs`'s `Plans::read` takes — the
|
||||
/// index says which file declares the module, and that one file is read —
|
||||
/// and it is what lets the engine answer "this instantiation is missing
|
||||
/// ports" without any file that *instantiates* the module. A cursor on a port
|
||||
/// declaration names its own module, whose declaring file is the buffer
|
||||
/// itself, so that case reads nothing at all.
|
||||
///
|
||||
/// `pub(crate)` for the test that pins exactly this set.
|
||||
pub(crate) fn offer_sources(
|
||||
ws: &Workspace,
|
||||
path: &Path,
|
||||
text: &str,
|
||||
modules: &[String],
|
||||
) -> Vec<(PathBuf, String)> {
|
||||
let mut sources = vec![(path.to_path_buf(), text.to_string())];
|
||||
for name in modules {
|
||||
let Ok(declared_in) = vlog_refactor::module_definition(ws.index(), name) else { continue };
|
||||
if sources.iter().any(|(held, _)| held == declared_in) {
|
||||
continue;
|
||||
}
|
||||
if let Some(text) = ws.text_of(declared_in) {
|
||||
sources.push((declared_in.to_path_buf(), text));
|
||||
}
|
||||
}
|
||||
sources
|
||||
}
|
||||
|
||||
/// The edit for one offered action, computed now that the user has picked it.
|
||||
///
|
||||
/// Today's eager answer at the offer's own position, narrowed to the action
|
||||
/// whose title the client is holding. An action already carrying its edit is
|
||||
/// returned untouched — a client may resolve anything it likes, and the quick
|
||||
/// fixes in `code_action.rs` are complete when they are offered.
|
||||
pub fn resolve(ws: &Workspace, action: CodeAction) -> Result<CodeAction, String> {
|
||||
if action.edit.is_some() {
|
||||
return Ok(action);
|
||||
}
|
||||
let offer: Offer = action
|
||||
.data
|
||||
.clone()
|
||||
.and_then(|data| serde_json::from_value(data).ok())
|
||||
.ok_or_else(|| NOT_OURS.to_string())?;
|
||||
// A `codeAction/resolve` carries a `CodeAction`, not a `textDocument`, so
|
||||
// the large-file fast path's gate (which reads the URI out of the params)
|
||||
// never sees this request. A buffer that has grown past the threshold
|
||||
// since it was offered an action is refused here instead: the fast path's
|
||||
// whole contract is that a large buffer is never parsed, and one stale
|
||||
// lightbulb is not a reason to break it.
|
||||
let doc = ws.document(&offer.uri).filter(|doc| !doc.large).ok_or_else(|| GONE.to_string())?;
|
||||
let offset = doc.positions().offset(offer.position);
|
||||
code_actions(ws, &offer.uri, offset)
|
||||
.into_iter()
|
||||
.find_map(|offered| match offered {
|
||||
CodeActionOrCommand::CodeAction(found) if key(&found.title) == key(&offer.title) => {
|
||||
Some(found)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.map(|mut resolved| {
|
||||
resolved.data = action.data;
|
||||
resolved
|
||||
})
|
||||
.ok_or_else(|| GONE.to_string())
|
||||
}
|
||||
|
||||
/// An action's identity: its title without the count phrase the offer and the
|
||||
/// eager path can honestly disagree about.
|
||||
///
|
||||
/// `"lucisv: remove port `rst` (updates 3 instantiations)"` keys as
|
||||
/// ``"lucisv: remove port `rst`"``; a title with no such suffix
|
||||
/// (`"lucisv: connect 1 missing port"`, whose count is the cursor's own file's
|
||||
/// and therefore exact) keys as itself. An escaped identifier cannot contain a
|
||||
/// space, so `" ("` never occurs inside a port name.
|
||||
fn key(title: &str) -> &str {
|
||||
title.strip_suffix(')').and_then(|head| head.rsplit_once(" (")).map_or(title, |(head, _)| head)
|
||||
}
|
||||
|
||||
/// An offered title with the workspace's own instantiation count in it,
|
||||
/// replacing the one the offer's one or two files could see.
|
||||
fn counted(ws: &Workspace, title: String, modules: &[String]) -> String {
|
||||
let Some(head) = title.strip_suffix(')').and_then(|head| head.rsplit_once(" (")) else {
|
||||
return title;
|
||||
};
|
||||
let sites = modules.iter().map(|name| instances_of(ws, name)).sum();
|
||||
format!("{} ({})", head.0, vlog_refactor::sites_phrase(sites))
|
||||
}
|
||||
|
||||
/// Every instance of `name` the index has seen. An edge is one written
|
||||
/// statement, so its instances are counted rather than the edges themselves —
|
||||
/// `sub u1 (), u2 ();` is two connection lists to rewrite and the title says
|
||||
/// two.
|
||||
fn instances_of(ws: &Workspace, name: &str) -> usize {
|
||||
ws.index().instantiations_of(name).iter().map(|edge| edge.instances.len()).sum()
|
||||
}
|
||||
|
||||
/// Whether the index holds more than one declaration of `name` a module
|
||||
/// reference could mean — the ambiguity `vlog_refactor::module_definition`
|
||||
/// refuses to guess between, and the one the engine refuses a refactoring
|
||||
/// over.
|
||||
fn declared_twice(ws: &Workspace, name: &str) -> bool {
|
||||
ws.index().units(name).iter().filter(|def| def.kind.is_instantiable()).count() > 1
|
||||
}
|
||||
|
||||
/// Run one of the three commands, or say why it cannot run.
|
||||
///
|
||||
/// The answer is the `WorkspaceEdit` to apply plus the engine's warnings. How
|
||||
@@ -809,6 +1000,322 @@ mod tests {
|
||||
assert_eq!(edits_for(action.edit.as_ref().expect("edit"), &new_uri).len(), 2);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the lazy offer and its resolve (TODO §37.1)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The offer a client that can resolve receives at `offset`.
|
||||
fn offered(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrCommand> {
|
||||
let position = ws.document(uri).expect("an open document").positions().position(offset);
|
||||
offers(ws, uri, position, offset)
|
||||
}
|
||||
|
||||
/// One action's title and kind — what a lightbulb draws, and all an offer
|
||||
/// promises.
|
||||
fn menu(actions: &[CodeActionOrCommand]) -> Vec<(String, Option<String>)> {
|
||||
actions
|
||||
.iter()
|
||||
.map(|action| {
|
||||
let CodeActionOrCommand::CodeAction(action) = action else {
|
||||
return ("a command".to_string(), None);
|
||||
};
|
||||
(action.title.clone(), action.kind.as_ref().map(|k| k.as_str().to_string()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The one action an offer holds.
|
||||
fn only(actions: &[CodeActionOrCommand]) -> &CodeAction {
|
||||
let [CodeActionOrCommand::CodeAction(action)] = actions else {
|
||||
panic!("exactly one action, got {actions:#?}")
|
||||
};
|
||||
action
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lazy_offer_names_exactly_what_the_eager_one_names() {
|
||||
let tree = Tree::new("lazy_menu");
|
||||
let mut ws = crowded(&tree, 40);
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
let lazy = offered(&ws, &sub_uri, offset);
|
||||
assert_eq!(menu(&lazy), menu(&code_actions(&ws, &sub_uri, offset)));
|
||||
assert_eq!(
|
||||
menu(&lazy)[0].0,
|
||||
"lucisv: remove port `rst` (updates 3 instantiations)",
|
||||
"counted from the index, and it agrees with the plan's own count"
|
||||
);
|
||||
let action = only(&lazy);
|
||||
assert!(action.edit.is_none(), "an offer carries no edit");
|
||||
assert!(action.data.is_some(), "it carries what resolve needs instead");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offer_reads_the_buffer_and_at_most_the_declaring_file() {
|
||||
// The pin `the_files_a_code_action_reads_are_the_modules_own_fan_out`
|
||||
// is to the eager path; this is the same question asked of the offer,
|
||||
// through the set it hands the engine. Neither the 40 noise files nor
|
||||
// — and this is the point — any of the three instantiating tops.
|
||||
let tree = Tree::new("lazy_reads");
|
||||
let mut ws = crowded(&tree, 40);
|
||||
let sub = tree.path.join("sub.sv");
|
||||
let sub_uri = path_to_uri(&sub).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
assert_eq!(ws.sources().len(), 44, "the whole workspace");
|
||||
assert_eq!(ws.module_sources(&sub, &["sub".to_string()]).len(), 4, "the eager fan-out");
|
||||
|
||||
// A cursor on a port declaration: the module is the buffer's own.
|
||||
let read = offer_sources(&ws, &sub, SUB, &["sub".to_string()]);
|
||||
let names: Vec<String> = read
|
||||
.iter()
|
||||
.map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string())
|
||||
.collect();
|
||||
assert_eq!(names, ["sub.sv"], "one file, and it is the buffer itself");
|
||||
|
||||
// A cursor on an instantiation: the buffer, plus the one file the
|
||||
// index says declares the module.
|
||||
let top = tree.path.join("top0.sv");
|
||||
let top_text = std::fs::read_to_string(&top).expect("read");
|
||||
let read = offer_sources(&ws, &top, &top_text, &["sub".to_string()]);
|
||||
let mut names: Vec<String> = read
|
||||
.iter()
|
||||
.map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string())
|
||||
.collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["sub.sv", "top0.sv"], "and never top1, top2 or a noise file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resolved_action_carries_the_eager_edit_at_a_port_declaration() {
|
||||
let tree = Tree::new("resolve_port");
|
||||
let mut ws = crowded(&tree, 40);
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
let resolved = resolve(&ws, only(&offered(&ws, &sub_uri, offset)).clone()).expect("edit");
|
||||
let eager = only(&code_actions(&ws, &sub_uri, offset)).clone();
|
||||
assert_eq!(resolved.title, eager.title);
|
||||
assert_eq!(resolved.kind, eager.kind);
|
||||
assert_eq!(resolved.edit, eager.edit, "the same WorkspaceEdit, to the byte");
|
||||
assert!(resolved.data.is_some(), "the offer's own data survives the round trip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resolved_action_carries_the_eager_edit_at_an_instantiation() {
|
||||
// The other cursor shape: an instantiation missing a connection, where
|
||||
// the offer has to read the *instantiated* module's declaration to
|
||||
// know there is anything to offer at all.
|
||||
let tree = Tree::new("resolve_inst");
|
||||
let text = "module top;\n logic clk, rst;\n sub u_sub (.clk(clk));\nendmodule\n";
|
||||
tree.write("sub.sv", SUB);
|
||||
let top = tree.write("top.sv", text);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&top).expect("uri");
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
let offset = text.find("sub u_sub").expect("the instantiation") as u32;
|
||||
|
||||
let lazy = offered(&ws, &uri, offset);
|
||||
assert_eq!(menu(&lazy), menu(&code_actions(&ws, &uri, offset)));
|
||||
assert_eq!(menu(&lazy)[0].0, "lucisv: connect 1 missing port");
|
||||
assert!(only(&lazy).edit.is_none());
|
||||
|
||||
let resolved = resolve(&ws, only(&lazy).clone()).expect("edit");
|
||||
assert_eq!(resolved.edit, only(&code_actions(&ws, &uri, offset)).edit);
|
||||
assert_eq!(
|
||||
edits_for(resolved.edit.as_ref().expect("edit"), &uri)[0].new_text,
|
||||
", .rst(rst)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_resolved_edit_sees_an_unsaved_buffer_the_offer_could_not_count() {
|
||||
// The pin `an_unsaved_buffer_contributes_the_instantiation_the_index
|
||||
// _has_not_seen` moved to the lazy path. The offer counts instances
|
||||
// from the index, which has not seen the unsaved one, so the title
|
||||
// says three; the *edit* is computed over the fan-out plus every open
|
||||
// buffer, so it disconnects all four. Exactness lives in the edit,
|
||||
// which is what the user actually applies.
|
||||
let tree = Tree::new("lazy_unsaved");
|
||||
let mut ws = crowded(&tree, 20);
|
||||
let extra = tree.path.join("noise0.sv");
|
||||
let extra_uri = path_to_uri(&extra).expect("uri");
|
||||
let typed = "module noise0;\n logic c, r;\n sub u_new (.clk(c), .rst(r));\nendmodule\n";
|
||||
ws.set_document(extra_uri.clone(), typed.to_string());
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
let lazy = offered(&ws, &sub_uri, offset);
|
||||
assert_eq!(
|
||||
menu(&lazy)[0].0,
|
||||
"lucisv: remove port `rst` (updates 3 instantiations)",
|
||||
"the index has not seen the fourth"
|
||||
);
|
||||
let resolved = resolve(&ws, only(&lazy).clone()).expect("edit");
|
||||
assert_eq!(
|
||||
resolved.title, "lucisv: remove port `rst` (updates 4 instantiations)",
|
||||
"and the resolve says so"
|
||||
);
|
||||
let edit = resolved.edit.as_ref().expect("an edit");
|
||||
assert_eq!(edits_for(edit, &extra_uri).len(), 2, "the unsaved buffer is disconnected too");
|
||||
assert_eq!(resolved.edit, only(&code_actions(&ws, &sub_uri, offset)).edit);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resolve_of_an_action_the_buffer_no_longer_carries_is_refused() {
|
||||
let tree = Tree::new("lazy_stale");
|
||||
let mut ws = crowded(&tree, 10);
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
let offered = only(&offered(&ws, &sub_uri, offset)).clone();
|
||||
|
||||
// The user kept typing: the port the lightbulb was about is gone.
|
||||
ws.set_document(sub_uri.clone(), "module sub (\n input logic clk\n);\nendmodule\n".into());
|
||||
let message = resolve(&ws, offered.clone()).expect_err("nothing to resolve");
|
||||
assert_eq!(message, GONE);
|
||||
|
||||
// And a document that has been closed altogether says the same.
|
||||
ws.close_document(&sub_uri);
|
||||
assert_eq!(resolve(&ws, offered).expect_err("no buffer"), GONE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resolve_against_a_buffer_on_the_large_file_fast_path_is_refused() {
|
||||
// `codeAction/resolve`'s params are a `CodeAction`, so the fast path's
|
||||
// own gate — which reads a `textDocument` out of the params — never
|
||||
// sees this request. A buffer that grew past the threshold since it
|
||||
// was offered an action must still not be parsed.
|
||||
let tree = Tree::new("lazy_large");
|
||||
let mut ws = crowded(&tree, 5);
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
let offered = only(&offered(&ws, &sub_uri, offset)).clone();
|
||||
|
||||
let _ = ws.set_client_settings(crate::settings::ClientSettings {
|
||||
large_file_threshold: 8,
|
||||
..Default::default()
|
||||
});
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
assert!(ws.document(&sub_uri).expect("open").large, "the buffer is on the fast path");
|
||||
assert_eq!(resolve(&ws, offered).expect_err("not parsed"), GONE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resolve_of_something_this_server_never_offered_says_so() {
|
||||
let tree = Tree::new("lazy_foreign");
|
||||
let (ws, uri, _) = opened(&tree);
|
||||
let bare = CodeAction { title: "someone else's action".to_string(), ..Default::default() };
|
||||
assert_eq!(resolve(&ws, bare.clone()).expect_err("no data"), NOT_OURS);
|
||||
|
||||
// Data that is not ours either — a shape `serde` cannot read as an
|
||||
// offer. Refused, not guessed at.
|
||||
let junk = CodeAction { data: Some(serde_json::json!({"nope": 1})), ..bare.clone() };
|
||||
assert_eq!(resolve(&ws, junk).expect_err("junk data"), NOT_OURS);
|
||||
|
||||
// An action that already carries its edit — every quick fix in
|
||||
// `code_action.rs`, and the port actions a non-resolving client is
|
||||
// sent — comes straight back, because there is nothing to add to it.
|
||||
let complete =
|
||||
CodeAction { edit: Some(WorkspaceEdit::new(HashMap::from([(uri, vec![])]))), ..bare };
|
||||
assert_eq!(resolve(&ws, complete.clone()).expect("nothing to do"), complete);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_the_workspace_declares_twice_is_not_offered_either() {
|
||||
// The eager path refuses because both declaring files are in the set
|
||||
// it reads (`a_module_declared_twice_is_refused_through_the_subset_as
|
||||
// _well`). The offer reads neither, so it asks the index the same
|
||||
// question — otherwise it would offer an action resolve then refuses.
|
||||
let tree = Tree::new("lazy_ambiguous");
|
||||
let mut ws = crowded(&tree, 10);
|
||||
tree.write("clone.sv", SUB);
|
||||
ws.rebuild_index();
|
||||
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
|
||||
ws.set_document(sub_uri.clone(), SUB.to_string());
|
||||
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
|
||||
|
||||
assert!(offered(&ws, &sub_uri, offset).is_empty());
|
||||
assert!(code_actions(&ws, &sub_uri, offset).is_empty(), "as the eager path does");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_title_keys_on_everything_but_its_count() {
|
||||
assert_eq!(
|
||||
key("lucisv: remove port `rst` (updates 3 instantiations)"),
|
||||
key("lucisv: remove port `rst` (no instantiation in scope)")
|
||||
);
|
||||
assert_eq!(key("lucisv: connect 1 missing port"), "lucisv: connect 1 missing port");
|
||||
assert_ne!(
|
||||
key("lucisv: remove port `rst` (updates 1 instantiation)"),
|
||||
key("lucisv: remove port `clk` (updates 1 instantiation)")
|
||||
);
|
||||
}
|
||||
|
||||
/// `cargo test --release -p lucisv_server --bin lucisv-server ports::tests::the_offer_is_flat -- --ignored --nocapture --test-threads=1`
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/perf/README.md"]
|
||||
fn the_offer_is_flat_where_the_eager_answer_grows() {
|
||||
// `performance_take2.md` §6a measured the eager answer growing with
|
||||
// the module's fan-out — ~1.4 ms per instantiating file plus a ~13 ms
|
||||
// floor, 185 ms at 128 files, to offer *zero* actions. The offer reads
|
||||
// one file (a cursor on a port declaration) or two (a cursor on an
|
||||
// instantiation), so its column should be flat. Beside the code it
|
||||
// measures rather than in `perf.rs`, which is what `perf::mean` is
|
||||
// `pub(crate)` for.
|
||||
for instantiators in [3usize, 40, 128] {
|
||||
let tree = Tree::new(&format!("perf_offer_{instantiators}"));
|
||||
tree.write("sub.sv", SUB);
|
||||
for n in 0..instantiators {
|
||||
tree.write(
|
||||
&format!("top{n:03}.sv"),
|
||||
&format!(
|
||||
"module top{n:03};\n logic c, r;\n \
|
||||
sub u_sub (.clk(c), .rst(r));\nendmodule\n"
|
||||
),
|
||||
);
|
||||
}
|
||||
for n in 0..200 {
|
||||
tree.write(
|
||||
&format!("noise{n:03}.sv"),
|
||||
&format!(
|
||||
"module noise{n:03};\n logic a;\n wire b;\n \
|
||||
assign b = a;\nendmodule\n"
|
||||
),
|
||||
);
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
|
||||
for (what, file, needle, skip) in [
|
||||
("a port declaration", "sub.sv", "input logic rst", 12u32),
|
||||
("an instantiation ", "top000.sv", "sub u_sub", 0),
|
||||
] {
|
||||
let path = tree.path.join(file);
|
||||
let text = std::fs::read_to_string(&path).expect("read");
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), text.clone());
|
||||
let offset = text.find(needle).expect("the cursor") as u32 + skip;
|
||||
let eager = crate::perf::mean(5, || {
|
||||
std::hint::black_box(code_actions(&ws, &uri, offset));
|
||||
});
|
||||
let offer = crate::perf::mean(20, || {
|
||||
std::hint::black_box(offered(&ws, &uri, offset));
|
||||
});
|
||||
eprintln!(
|
||||
" fan-out {instantiators:>3}, cursor on {what}: eager {eager:?}, \
|
||||
offer {offer:?} ({} actions)",
|
||||
offered(&ws, &uri, offset).len()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_command_is_declined() {
|
||||
let tree = Tree::new("unknown");
|
||||
|
||||
@@ -117,6 +117,7 @@ fn items(list: &[Item], offset: u32, out: &mut Vec<TextRange>) {
|
||||
ItemKind::Class(class) => items(&class.items, offset, out),
|
||||
ItemKind::Package { items: inner, .. } => items(inner, offset, out),
|
||||
ItemKind::GenerateRegion { items: inner, .. } => items(inner, offset, out),
|
||||
ItemKind::GenBlock(b) => items(&b.items, offset, out),
|
||||
ItemKind::GenIf(gen_if) => gen_if_blocks(gen_if, offset, out),
|
||||
ItemKind::GenFor(gen_for) => gen_block(&gen_for.body, offset, out),
|
||||
ItemKind::GenCase(gen_case) => {
|
||||
|
||||
@@ -14,22 +14,22 @@
|
||||
use lsp_server::{Request, RequestId, Response};
|
||||
use lsp_types::request::{
|
||||
CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls, CallHierarchyPrepare,
|
||||
CodeActionRequest, CodeLensRequest, Completion, DocumentDiagnosticRequest,
|
||||
DocumentHighlightRequest, DocumentLinkRequest, DocumentSymbolRequest, ExecuteCommand,
|
||||
FoldingRangeRequest, Formatting, GotoDefinition, GotoTypeDefinition, GotoTypeDefinitionParams,
|
||||
GotoTypeDefinitionResponse, HoverRequest, InlayHintRequest, InlineCompletionRequest,
|
||||
LinkedEditingRange, OnTypeFormatting, PrepareRenameRequest, RangeFormatting, References,
|
||||
Rename, Request as _, SelectionRangeRequest, SemanticTokensFullDeltaRequest,
|
||||
SemanticTokensFullRequest, SemanticTokensRangeRequest, SignatureHelpRequest,
|
||||
TypeHierarchyPrepare, TypeHierarchySubtypes, TypeHierarchySupertypes, WillRenameFiles,
|
||||
WillSaveWaitUntil, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
|
||||
CodeActionRequest, CodeActionResolveRequest, CodeLensRequest, Completion,
|
||||
DocumentDiagnosticRequest, DocumentHighlightRequest, DocumentLinkRequest,
|
||||
DocumentSymbolRequest, ExecuteCommand, FoldingRangeRequest, Formatting, GotoDefinition,
|
||||
GotoTypeDefinition, GotoTypeDefinitionParams, GotoTypeDefinitionResponse, HoverRequest,
|
||||
InlayHintRequest, InlineCompletionRequest, LinkedEditingRange, OnTypeFormatting,
|
||||
PrepareRenameRequest, RangeFormatting, References, Rename, Request as _, SelectionRangeRequest,
|
||||
SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, SemanticTokensRangeRequest,
|
||||
SignatureHelpRequest, TypeHierarchyPrepare, TypeHierarchySubtypes, TypeHierarchySupertypes,
|
||||
WillRenameFiles, WillSaveWaitUntil, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
|
||||
};
|
||||
use lsp_types::{
|
||||
CallHierarchyIncomingCallsParams, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams,
|
||||
CodeActionKind, CodeActionParams, CodeLensParams, CompletionParams, DocumentDiagnosticParams,
|
||||
DocumentDiagnosticReportResult, DocumentHighlightParams, DocumentLinkParams,
|
||||
DocumentSymbolParams, DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams,
|
||||
GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams,
|
||||
CodeAction, CodeActionKind, CodeActionParams, CodeLensParams, CompletionParams,
|
||||
DocumentDiagnosticParams, DocumentDiagnosticReportResult, DocumentHighlightParams,
|
||||
DocumentLinkParams, DocumentSymbolParams, DocumentSymbolResponse, ExecuteCommandParams,
|
||||
FoldingRangeParams, GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams,
|
||||
InlineCompletionParams, LinkedEditingRangeParams, Position, ReferenceParams, RenameFilesParams,
|
||||
RenameParams, SelectionRangeParams, SemanticTokens, SemanticTokensDeltaParams,
|
||||
SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeResult,
|
||||
@@ -258,10 +258,26 @@ impl Server {
|
||||
if code_action::wanted(only.as_deref(), &CodeActionKind::new(ports::REFACTOR_PORTS))
|
||||
{
|
||||
let offset = doc.positions().offset(p.range.start);
|
||||
actions.extend(ports::code_actions(&self.workspace, &uri, offset));
|
||||
// A client that can resolve is offered the actions without
|
||||
// their edits, which is what keeps a cursor resting on an
|
||||
// instantiation off the module's fan-out; one that cannot
|
||||
// gets the whole edit, exactly as before.
|
||||
actions.extend(match self.abilities.code_action_resolve {
|
||||
true => ports::offers(&self.workspace, &uri, p.range.start, offset),
|
||||
false => ports::code_actions(&self.workspace, &uri, offset),
|
||||
});
|
||||
}
|
||||
to_value(actions)
|
||||
}),
|
||||
// The edit for an action offered without one. An action that
|
||||
// already carries its edit comes straight back, so a client that
|
||||
// resolves everything it is offered is answered too.
|
||||
CodeActionResolveRequest::METHOD => decode(request).and_then(|action: CodeAction| {
|
||||
match ports::resolve(&self.workspace, action) {
|
||||
Ok(resolved) => to_value(resolved),
|
||||
Err(message) => Err(Failure::Request(message)),
|
||||
}
|
||||
}),
|
||||
// Custom method, so it is matched by name rather than through a
|
||||
// `lsp_types::request` type. Nothing advertises it: a client that
|
||||
// does not know it never asks.
|
||||
|
||||
@@ -104,6 +104,13 @@ pub struct ClientAbilities {
|
||||
/// Whether the client hosts the custom lucisv hierarchy sidebar and wants
|
||||
/// a notification whenever the installed workspace index changes.
|
||||
pub hierarchy_view: bool,
|
||||
/// Whether the client can fetch a code action's `edit` through
|
||||
/// `codeAction/resolve` — `textDocument.codeAction.resolveSupport`
|
||||
/// listing `"edit"`. Only then are the port refactorings *offered* without
|
||||
/// their edits; a client that said nothing gets the whole edit up front,
|
||||
/// which is what every client got before this was read
|
||||
/// (`docs/features/lazy-code-action/README.md`).
|
||||
pub code_action_resolve: bool,
|
||||
}
|
||||
|
||||
/// Everything the server owns.
|
||||
|
||||
@@ -1797,6 +1797,17 @@ impl Workspace {
|
||||
Some(view)
|
||||
}
|
||||
|
||||
/// The files the view cache is holding, newest first.
|
||||
///
|
||||
/// Test-only, and it exists for one question: whether an answer read a
|
||||
/// file at all. A `Location` computed from the index alone must leave this
|
||||
/// empty, which is the whole point of `locate::definition_location` — see
|
||||
/// `docs/features/lazy-code-action/README.md`.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn held_views(&self) -> Vec<PathBuf> {
|
||||
self.views.borrow().iter().map(|view| view.path.clone()).collect()
|
||||
}
|
||||
|
||||
/// The held view for `path`, moved to the front so the bounds below drop
|
||||
/// whatever has gone longest unused.
|
||||
fn cached_view(&self, path: &Path) -> Option<Rc<FileView>> {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use lsp_types::{Location, SymbolInformation, SymbolKind as LspKind};
|
||||
use vlog_semantic::{Symbol, SymbolKind};
|
||||
|
||||
use crate::locate::location;
|
||||
use crate::locate::definition_location;
|
||||
use crate::state::{Document, Workspace, WORKSPACE_SYMBOL_LIMIT};
|
||||
|
||||
/// How a declaration reads in hover text.
|
||||
@@ -129,7 +129,11 @@ pub fn workspace_symbols(ws: &Workspace, query: &str) -> Vec<SymbolInformation>
|
||||
.take(WORKSPACE_SYMBOL_LIMIT)
|
||||
.filter_map(|hit| {
|
||||
let path = index.path(hit.def.file)?;
|
||||
let location: Location = location(ws, path, hit.def.name_span)?;
|
||||
// A unit's range is in the index; a member's is not, and falls
|
||||
// back to the file read. `workspace/symbol` answers up to
|
||||
// `WORKSPACE_SYMBOL_LIMIT` hits at once, so this is the request
|
||||
// the index-carried positions matter most to.
|
||||
let location: Location = definition_location(ws, path, hit.def)?;
|
||||
// `deprecated` is a deprecated protocol field that is still a
|
||||
// named field of the struct.
|
||||
#[allow(deprecated)]
|
||||
|
||||
@@ -180,6 +180,7 @@ fn item_site(item: &Item, offset: u32) -> Option<Site<'_>> {
|
||||
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => {
|
||||
site_at(items, offset)
|
||||
}
|
||||
ItemKind::GenBlock(b) => gen_block_site(b, offset),
|
||||
ItemKind::GenIf(g) => gen_if_site(g, offset),
|
||||
ItemKind::GenFor(g) => gen_block_site(&g.body, offset),
|
||||
ItemKind::GenCase(g) => g.items.iter().find_map(|arm| gen_block_site(&arm.body, offset)),
|
||||
|
||||
@@ -1484,6 +1484,106 @@ fn a_port_code_action_and_the_port_commands_round_trip_over_the_wire() {
|
||||
);
|
||||
assert!(conditional["result"].is_null(), "a refusal carries no edits: {conditional:#?}");
|
||||
|
||||
// 7. The client above sent `"capabilities":{}`, so every action came back
|
||||
// complete — which is the whole of the no-resolveSupport contract.
|
||||
assert!(port_action["data"].is_null(), "nothing to resolve for this client: {port_action:#?}");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_resolves_is_offered_the_port_action_without_its_edit() {
|
||||
// The lazy half of the same feature (TODO §37.1): a client that declares
|
||||
// `codeAction.resolveSupport.properties: ["edit"]` is offered the action
|
||||
// with `data` and no `edit`, and gets the edit from `codeAction/resolve`.
|
||||
// Only an e2e test can check that the `data` really survives the round
|
||||
// trip through the client — it is opaque JSON the server never sees again
|
||||
// until the client hands it back.
|
||||
let dir = temp_dir("resolve");
|
||||
let sub = dir.join("sub.sv");
|
||||
std::fs::write(&sub, PORTS_SUB).expect("write");
|
||||
let top = dir.join("top.sv");
|
||||
std::fs::write(&top, PORTS_TOP).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let top_uri = format!("file://{}", top.display());
|
||||
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"codeAction":{{"resolveSupport":{{"properties":["edit"]}}}}}}}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(PORTS_TOP).expect("json")
|
||||
)),
|
||||
// The cursor on `u_sub`, whose instantiation is missing `.rst`.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{top_uri}"}},"range":{{"start":{{"line":2,"character":6}},"end":{{"line":2,"character":6}}}},"context":{{"diagnostics":[]}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
let messages = talk(&session);
|
||||
|
||||
// 1. The capability says a resolve is answered.
|
||||
let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
|
||||
let provider = &initialize["result"]["capabilities"]["codeActionProvider"];
|
||||
assert_eq!(provider["resolveProvider"], true, "{provider:#?}");
|
||||
|
||||
// 2. The offer carries `data` and no `edit`.
|
||||
let actions = messages.iter().find(|m| m["id"] == 2).expect("codeAction response");
|
||||
let offered = actions["result"].as_array().expect("an array of actions");
|
||||
let action = offered
|
||||
.iter()
|
||||
.find(|a| a["kind"] == "refactor.rewrite.lucisv.ports")
|
||||
.unwrap_or_else(|| panic!("no port action in {offered:#?}"));
|
||||
assert_eq!(action["title"], "lucisv: connect 1 missing port");
|
||||
assert!(action["edit"].is_null(), "an offer carries no edit: {action:#?}");
|
||||
assert_eq!(action["data"]["uri"], top_uri.as_str());
|
||||
assert_eq!(action["data"]["title"], action["title"]);
|
||||
|
||||
// 3. Handing that same action back gets the edit. A second session,
|
||||
// because the action has to be echoed verbatim and it is only known now.
|
||||
let resolve = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"codeAction":{{"resolveSupport":{{"properties":["edit"]}}}}}}}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(PORTS_TOP).expect("json")
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":3,"method":"codeAction/resolve","params":{}}}"#,
|
||||
serde_json::to_string(action).expect("json")
|
||||
)),
|
||||
// ...and an action this server never offered is refused with a
|
||||
// sentence rather than an empty edit.
|
||||
frame(
|
||||
r#"{"jsonrpc":"2.0","id":4,"method":"codeAction/resolve","params":{"title":"someone else's action"}}"#,
|
||||
),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
let messages = talk(&resolve);
|
||||
let resolved = messages.iter().find(|m| m["id"] == 3).expect("resolve response");
|
||||
let edits = resolved["result"]["edit"]["changes"][&top_uri]
|
||||
.as_array()
|
||||
.unwrap_or_else(|| panic!("no edit in {resolved:#?}"));
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert_eq!(edits[0]["newText"], ", .rst(rst)");
|
||||
assert_eq!(edits[0]["range"]["start"]["line"], 2);
|
||||
assert_eq!(resolved["result"]["title"], "lucisv: connect 1 missing port");
|
||||
|
||||
let foreign = messages.iter().find(|m| m["id"] == 4).expect("refusal response");
|
||||
assert_eq!(foreign["error"]["code"], -32803, "LSP's RequestFailed");
|
||||
assert!(
|
||||
foreign["error"]["message"].as_str().is_some_and(|m| m.contains("no lucisv port")),
|
||||
"{foreign:#?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -7367,6 +7467,81 @@ fn the_project_wide_lint_rules_publish_and_a_setting_turns_them_off() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `lucisv.lint.options` over the wire — the pin §34's QA found missing and
|
||||
/// drove by hand twice (`docs/features/linter-expansion-2/README.md`, QA log).
|
||||
///
|
||||
/// Three claims a unit test cannot make: the object survives
|
||||
/// `didChangeConfiguration` and changes what is published; the editor's value
|
||||
/// beats a checked-in `lucisv.toml`'s, key by key; and a refused entry is
|
||||
/// *dropped and logged* rather than fatal — the rule keeps running, here on
|
||||
/// the `lucisv.toml` value the bad entry failed to override.
|
||||
#[test]
|
||||
fn the_lint_options_setting_changes_what_is_published_and_a_bad_entry_is_logged() {
|
||||
let dir = temp_dir("lintoptions");
|
||||
std::fs::write(dir.join("lucisv.toml"), "[lint.line-length]\nlength = 40\n").expect("write");
|
||||
let file = dir.join("wide.sv");
|
||||
let text = "module wide;\n wire this_line_is_a_good_deal_wider_than_forty;\nendmodule\n";
|
||||
std::fs::write(&file, text).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(text).expect("json")
|
||||
)),
|
||||
// The editor's value beats the checked-in one, key by key.
|
||||
frame(
|
||||
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"lint":{"options":{"line-length":{"length":200}}}}}}}"#,
|
||||
),
|
||||
// ... and a typo'd key is refused, dropped and logged, leaving the
|
||||
// `lucisv.toml` value standing rather than turning the linter off.
|
||||
frame(
|
||||
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"lint":{"options":{"line-length":{"lenght":200}}}}}}}"#,
|
||||
),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&session);
|
||||
let wide: Vec<usize> = messages
|
||||
.iter()
|
||||
.filter(|m| m["method"] == "textDocument/publishDiagnostics")
|
||||
.filter(|m| m["params"]["uri"] == uri.as_str())
|
||||
.map(|m| {
|
||||
m["params"]["diagnostics"]
|
||||
.as_array()
|
||||
.map(|list| list.iter().filter(|d| d["code"] == "line-length").count())
|
||||
.unwrap_or(0)
|
||||
})
|
||||
.collect();
|
||||
assert!(wide.len() >= 3, "one publish per state: {wide:?}");
|
||||
assert_eq!(wide[0], 1, "the `lucisv.toml`'s 40 flags the 47-column line: {wide:?}");
|
||||
assert_eq!(wide[1], 0, "the editor's 200 beat it: {wide:?}");
|
||||
assert_eq!(
|
||||
wide[wide.len() - 1],
|
||||
1,
|
||||
"the refused entry is dropped, so the `lucisv.toml` value stands again: {wide:?}"
|
||||
);
|
||||
|
||||
let logged: Vec<&str> = messages
|
||||
.iter()
|
||||
.filter(|m| m["method"] == "window/logMessage")
|
||||
.filter_map(|m| m["params"]["message"].as_str())
|
||||
.filter(|text| text.contains("lucisv.lint.options"))
|
||||
.collect();
|
||||
assert_eq!(logged.len(), 1, "exactly the one refused entry: {logged:?}");
|
||||
assert!(logged[0].contains("lenght"), "{}", logged[0]);
|
||||
assert!(logged[0].contains("ignored"), "{}", logged[0]);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `lucisv.instantiate` — `docs/topo.md` §2.9-19. What only an e2e test can
|
||||
/// check: that the command is advertised in `initialize`, that its three
|
||||
/// arguments survive the wire, and that the skeleton arrives as a
|
||||
|
||||
@@ -245,6 +245,7 @@ fn scan_nested(src: &str, item: &Item, out: &mut Vec<Region>) {
|
||||
ItemKind::Module(m) => scan_scope(src, &m.items, &m.dangling, out),
|
||||
ItemKind::Package { items, dangling, .. } => scan_scope(src, items, dangling, out),
|
||||
ItemKind::GenerateRegion { items, dangling } => scan_scope(src, items, dangling, out),
|
||||
ItemKind::GenBlock(b) => scan_gen_block(src, b, out),
|
||||
ItemKind::GenIf(g) => scan_gen_if(src, g, out),
|
||||
ItemKind::GenFor(g) => scan_gen_block(src, &g.body, out),
|
||||
ItemKind::GenCase(g) => {
|
||||
|
||||
@@ -274,6 +274,21 @@ impl<'a> Fmt<'a> {
|
||||
body.extend(self.dangling(dangling));
|
||||
concat(vec![text("generate"), indent(body), Doc::HardLine, text("endgenerate")])
|
||||
}
|
||||
// A bare `begin … end` standing where an item belongs. Never
|
||||
// reached from `format_source`: the parser records a diagnostic
|
||||
// beside it and a file with a diagnostic is emitted unchanged.
|
||||
// The arm exists so a range or tolerant printer has nothing to
|
||||
// invent — the block prints the way a generate block's does,
|
||||
// without the separator `gen_block` puts in front of the keyword
|
||||
// for the header it usually hangs off.
|
||||
ItemKind::GenBlock(b) => {
|
||||
let mut docs = Vec::new();
|
||||
if self.inline_comments(&b.before_kw, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
self.begin_block(&mut docs, b, depth);
|
||||
concat(docs)
|
||||
}
|
||||
ItemKind::GenIf(g) => self.gen_if(g, depth),
|
||||
ItemKind::GenFor(g) => self.gen_for(g, depth),
|
||||
ItemKind::GenCase(g) => self.gen_case(g, depth),
|
||||
@@ -464,26 +479,7 @@ impl<'a> Fmt<'a> {
|
||||
} else {
|
||||
self.inline_comments_spaced(&b.before_kw, docs);
|
||||
}
|
||||
docs.push(text("begin"));
|
||||
if let Some(l) = &b.label {
|
||||
self.slot_comments(&b.before_colon, docs);
|
||||
docs.push(text(if b.before_colon.is_empty() { " :" } else { ":" }));
|
||||
if b.after_colon.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&b.after_colon, docs);
|
||||
}
|
||||
docs.push(text(named(l)));
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
if !b.items.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.item_seq(&b.items, depth + 1));
|
||||
}
|
||||
body.extend(self.dangling(&b.dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(self.closing_labeled("end", &b.end_label, &b.end_label_comments));
|
||||
self.begin_block(docs, b, depth);
|
||||
true
|
||||
} else {
|
||||
let item = &b.items[0];
|
||||
@@ -492,6 +488,33 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A generate block's `begin … end` and everything between, from the
|
||||
/// keyword on — the separator in front of it is the caller's, because a
|
||||
/// block hanging off an `if (…)` header needs one and a block standing on
|
||||
/// its own as an item ([`ItemKind::GenBlock`]) does not.
|
||||
fn begin_block(&self, docs: &mut Vec<Doc>, b: &GenBlock, depth: usize) {
|
||||
docs.push(text("begin"));
|
||||
if let Some(l) = &b.label {
|
||||
self.slot_comments(&b.before_colon, docs);
|
||||
docs.push(text(if b.before_colon.is_empty() { " :" } else { ":" }));
|
||||
if b.after_colon.is_empty() {
|
||||
docs.push(text(" "));
|
||||
} else {
|
||||
self.inline_comments_spaced(&b.after_colon, docs);
|
||||
}
|
||||
docs.push(text(named(l)));
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
if !b.items.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.item_seq(&b.items, depth + 1));
|
||||
}
|
||||
body.extend(self.dangling(&b.dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(self.closing_labeled("end", &b.end_label, &b.end_label_comments));
|
||||
}
|
||||
|
||||
fn gen_for(&self, g: &GenFor, depth: usize) -> Doc {
|
||||
let mut header = Vec::new();
|
||||
self.for_open(&g.comments, &mut header);
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
//! Every expression written in a file.
|
||||
//!
|
||||
//! `visit` walks the item and statement spines and `decls` the types and
|
||||
//! dimensions; neither reaches *into* an expression, and a rule that judges
|
||||
//! the shape of one (`suggest-parentheses`) needs every node of every tree,
|
||||
//! wherever it was written. Collecting them lives here so each of the three
|
||||
//! files stays one sentence long.
|
||||
|
||||
use vlog_parser::ast::{
|
||||
Connections, Expr, ExprKind, ForStep, Instantiation, ItemKind, ListElem, SourceFile, StmtKind,
|
||||
TimingControl,
|
||||
};
|
||||
|
||||
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
|
||||
|
||||
/// Calls `f` on every expression of the file, sub-expressions included.
|
||||
///
|
||||
/// The **roots** are the places an expression is written: a continuous or
|
||||
/// procedural assignment, a declaration's initialiser, a condition, a call
|
||||
/// argument, an instantiation's connections, a generate header, an expression
|
||||
/// statement. Sub-expressions are then reached through every composite
|
||||
/// [`ExprKind`], so a node buried in a concatenation inside a call argument is
|
||||
/// visited like any other.
|
||||
pub(crate) fn walk_exprs(file: &SourceFile, f: &mut dyn FnMut(&Expr)) {
|
||||
let mut root = |expr: &Expr| descend(expr, f);
|
||||
walk_param_ports(file, &mut |port| {
|
||||
if let Some(default) = &port.default {
|
||||
root(default);
|
||||
}
|
||||
});
|
||||
walk_items(file, &mut |item| match &item.kind {
|
||||
ItemKind::ContAssign(assign) => {
|
||||
if let Some(delay) = &assign.delay {
|
||||
root(delay);
|
||||
}
|
||||
for pair in &assign.assigns {
|
||||
root(&pair.lhs);
|
||||
root(&pair.rhs);
|
||||
}
|
||||
}
|
||||
ItemKind::ParamDecl(decl) => initialisers(&decl.declarators, &mut root),
|
||||
ItemKind::DataDecl(decl) => initialisers(&decl.declarators, &mut root),
|
||||
ItemKind::PortDecl(decl) => initialisers(&decl.declarators, &mut root),
|
||||
ItemKind::ElabTask(expr) => root(expr),
|
||||
ItemKind::Instantiation(inst) => connections(inst, &mut root),
|
||||
ItemKind::Bind(bind) => connections(&bind.inst, &mut root),
|
||||
ItemKind::GenIf(gen_if) => root(&gen_if.cond),
|
||||
ItemKind::GenFor(gen_for) => {
|
||||
root(&gen_for.init.lhs);
|
||||
root(&gen_for.init.rhs);
|
||||
root(&gen_for.cond);
|
||||
match &gen_for.step {
|
||||
ForStep::Assign(assign) => {
|
||||
root(&assign.lhs);
|
||||
root(&assign.rhs);
|
||||
}
|
||||
ForStep::Expr(expr) => root(expr),
|
||||
}
|
||||
}
|
||||
ItemKind::GenCase(gen_case) => {
|
||||
root(&gen_case.expr);
|
||||
for case_item in &gen_case.items {
|
||||
for label in &case_item.labels {
|
||||
root(&label.expr);
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::Defparam(pairs) => {
|
||||
for (target, value) in pairs {
|
||||
root(target);
|
||||
root(value);
|
||||
}
|
||||
}
|
||||
ItemKind::Alias(terms) => {
|
||||
for term in terms {
|
||||
root(term);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
|
||||
StmtKind::Assign { lhs, rhs, timing, .. } => {
|
||||
root(lhs);
|
||||
root(rhs);
|
||||
if let Some(TimingControl::Delay { expr, .. }) = timing {
|
||||
root(expr);
|
||||
}
|
||||
}
|
||||
StmtKind::ExprStmt(expr) | StmtKind::EventTrigger(expr) => root(expr),
|
||||
StmtKind::If { cond, .. } => root(cond),
|
||||
StmtKind::Case { expr, items, .. } => {
|
||||
root(expr);
|
||||
for case_item in items {
|
||||
for label in &case_item.labels {
|
||||
root(&label.expr);
|
||||
}
|
||||
}
|
||||
}
|
||||
StmtKind::RandCase { items, .. } => {
|
||||
for case_item in items {
|
||||
for label in &case_item.labels {
|
||||
root(&label.expr);
|
||||
}
|
||||
}
|
||||
}
|
||||
StmtKind::For { init, cond, step, .. } => {
|
||||
for one in init {
|
||||
root(&one.assign.lhs);
|
||||
root(&one.assign.rhs);
|
||||
}
|
||||
if let Some(cond) = cond {
|
||||
root(cond);
|
||||
}
|
||||
for one in step {
|
||||
match one {
|
||||
ForStep::Assign(assign) => {
|
||||
root(&assign.lhs);
|
||||
root(&assign.rhs);
|
||||
}
|
||||
ForStep::Expr(expr) => root(expr),
|
||||
}
|
||||
}
|
||||
}
|
||||
StmtKind::While { cond, .. } | StmtKind::DoWhile { cond, .. } => root(cond),
|
||||
StmtKind::Repeat { count, .. } => root(count),
|
||||
StmtKind::Foreach { target, .. } => root(target),
|
||||
StmtKind::Wait { cond, .. } => root(cond),
|
||||
// A sensitivity list holds edge terms, not values; only the `#delay`
|
||||
// spelling carries an expression a rule would judge.
|
||||
StmtKind::Timing { control: TimingControl::Delay { expr, .. }, .. } => root(expr),
|
||||
StmtKind::ForceRelease { lhs, rhs, .. } => {
|
||||
root(lhs);
|
||||
if let Some(rhs) = rhs {
|
||||
root(rhs);
|
||||
}
|
||||
}
|
||||
StmtKind::Return { expr: Some(expr), .. } => root(expr),
|
||||
StmtKind::VarDecl(decl) => initialisers(&decl.declarators, &mut root),
|
||||
StmtKind::ParamDecl(decl) => initialisers(&decl.declarators, &mut root),
|
||||
StmtKind::PortDecl(decl) => initialisers(&decl.declarators, &mut root),
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
|
||||
fn initialisers(declarators: &[vlog_parser::ast::Declarator], root: &mut dyn FnMut(&Expr)) {
|
||||
for declarator in declarators {
|
||||
if let Some(init) = &declarator.init {
|
||||
root(init);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn connections(inst: &Instantiation, root: &mut dyn FnMut(&Expr)) {
|
||||
if let Some(params) = &inst.params {
|
||||
for conn in params.iter().filter_map(ListElem::ok) {
|
||||
if let Some(expr) = &conn.expr {
|
||||
root(expr);
|
||||
}
|
||||
}
|
||||
}
|
||||
for instance in &inst.instances {
|
||||
match &instance.conns {
|
||||
Connections::Named(conns) => {
|
||||
for conn in conns.iter().filter_map(ListElem::ok) {
|
||||
if let Some(expr) = &conn.expr {
|
||||
root(expr);
|
||||
}
|
||||
}
|
||||
}
|
||||
Connections::Ordered(conns) => {
|
||||
for conn in conns.iter().filter_map(ListElem::ok) {
|
||||
if let Some(expr) = &conn.expr {
|
||||
root(expr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One expression and everything inside it.
|
||||
fn descend(expr: &Expr, f: &mut dyn FnMut(&Expr)) {
|
||||
f(expr);
|
||||
match &expr.kind {
|
||||
ExprKind::Unary { expr: inner, .. }
|
||||
| ExprKind::Postfix { expr: inner, .. }
|
||||
| ExprKind::New(inner)
|
||||
| ExprKind::Paren { inner, .. } => descend(inner, f),
|
||||
ExprKind::Binary { lhs, rhs, .. } => {
|
||||
descend(lhs, f);
|
||||
descend(rhs, f);
|
||||
}
|
||||
ExprKind::Ternary { cond, then, els, .. } => {
|
||||
descend(cond, f);
|
||||
descend(then, f);
|
||||
descend(els, f);
|
||||
}
|
||||
ExprKind::Call { callee, args, .. } => {
|
||||
descend(callee, f);
|
||||
for arg in args {
|
||||
descend(&arg.expr, f);
|
||||
}
|
||||
}
|
||||
ExprKind::Index { base, index, .. } => {
|
||||
descend(base, f);
|
||||
descend(index, f);
|
||||
}
|
||||
ExprKind::Range { base, msb, lsb, .. } => {
|
||||
descend(base, f);
|
||||
descend(msb, f);
|
||||
descend(lsb, f);
|
||||
}
|
||||
ExprKind::Member { base, .. }
|
||||
| ExprKind::Scope { base, .. }
|
||||
| ExprKind::Parameterized { base, .. } => descend(base, f),
|
||||
ExprKind::Concat(items) => {
|
||||
for item in items {
|
||||
descend(&item.expr, f);
|
||||
}
|
||||
}
|
||||
ExprKind::Repl { count, inner } | ExprKind::AssignPatternRepl { count, inner } => {
|
||||
descend(count, f);
|
||||
for item in inner {
|
||||
descend(&item.expr, f);
|
||||
}
|
||||
}
|
||||
ExprKind::Stream { slice, inner, .. } => {
|
||||
if let Some(slice) = slice {
|
||||
descend(slice, f);
|
||||
}
|
||||
for item in inner {
|
||||
descend(&item.expr, f);
|
||||
}
|
||||
}
|
||||
ExprKind::Cast { ty, expr: inner, .. } => {
|
||||
descend(ty, f);
|
||||
descend(inner, f);
|
||||
}
|
||||
ExprKind::Inside { lhs, ranges, .. } => {
|
||||
descend(lhs, f);
|
||||
for item in ranges {
|
||||
descend(&item.expr, f);
|
||||
}
|
||||
}
|
||||
ExprKind::InsideMacro { lhs, .. } => descend(lhs, f),
|
||||
ExprKind::With { base, .. } | ExprKind::WithConstraint { base, .. } => descend(base, f),
|
||||
ExprKind::Dist { expr: inner, .. } => descend(inner, f),
|
||||
ExprKind::NamedArg { value, .. } => descend(value, f),
|
||||
ExprKind::AssignPattern(items) => {
|
||||
for item in items {
|
||||
if let Some(key) = &item.key {
|
||||
descend(key, f);
|
||||
}
|
||||
descend(&item.value, f);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
|
||||
fn ternaries(src: &str) -> usize {
|
||||
let (file, _) = parse_source_tolerant(src);
|
||||
let mut n = 0;
|
||||
walk_exprs(&file, &mut |expr| {
|
||||
if matches!(expr.kind, ExprKind::Ternary { .. }) {
|
||||
n += 1;
|
||||
}
|
||||
});
|
||||
n
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reaches_an_expression_written_anywhere() {
|
||||
let src = "module m #(parameter int P = a ? 1 : 2) (\n\
|
||||
input logic i\n\
|
||||
);\n\
|
||||
logic v = b ? 1 : 2;\n\
|
||||
assign w = c ? 1 : 2;\n\
|
||||
sub u (.p(d ? 1 : 2));\n\
|
||||
if (e ? 1 : 2) begin : g\n wire x;\n end\n\
|
||||
initial begin\n\
|
||||
if (f ? 1 : 2) y = g_ ? 1 : 2;\n\
|
||||
z = {h ? 1 : 2, call(i ? 1 : 2)};\n\
|
||||
end\n\
|
||||
endmodule\n";
|
||||
assert_eq!(ternaries(src), 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nested_expression_is_reached_through_every_composite() {
|
||||
assert_eq!(ternaries("module m;\n assign x = ~(a ? 1 : 2);\nendmodule\n"), 1);
|
||||
assert_eq!(ternaries("module m;\n assign x = y[a ? 1 : 2];\nendmodule\n"), 1);
|
||||
assert_eq!(ternaries("module m;\n assign x = int'(a ? 1 : 2);\nendmodule\n"), 1);
|
||||
assert_eq!(ternaries("module m;\n assign x = {2{a ? 1 : 2}};\nendmodule\n"), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_with_no_expressions_visits_nothing() {
|
||||
assert_eq!(ternaries("module m;\nendmodule\n"), 0);
|
||||
}
|
||||
}
|
||||
@@ -22,11 +22,13 @@
|
||||
|
||||
mod context;
|
||||
mod decls;
|
||||
mod exprs;
|
||||
mod interfaces;
|
||||
mod literal;
|
||||
mod module_decls;
|
||||
mod naming;
|
||||
mod options;
|
||||
mod preproc;
|
||||
mod regex;
|
||||
mod registry;
|
||||
mod rule_docs;
|
||||
@@ -201,12 +203,12 @@ mod tests {
|
||||
// Real corpus RTL is annotated for Verible. Waivers naming rules lucisv
|
||||
// has not implemented are that codebase's, not typos, so they are
|
||||
// neither honored nor reported.
|
||||
let src = "module m;\n // verilog_lint: waive explicit-function-lifetime\n wire a;\nendmodule\n";
|
||||
let src = "module m;\n // verilog_lint: waive forbid-implicit-declarations\n wire a;\nendmodule\n";
|
||||
assert!(lint_all(src).is_empty());
|
||||
|
||||
// lucisv's own spelling gets no such benefit of the doubt.
|
||||
let src =
|
||||
"module m;\n // lucisv: waive explicit-function-lifetime\n wire a;\nendmodule\n";
|
||||
"module m;\n // lucisv: waive forbid-implicit-declarations\n wire a;\nendmodule\n";
|
||||
assert_eq!(names(&lint_all(src)), vec![UNUSED_WAIVER]);
|
||||
}
|
||||
|
||||
|
||||
@@ -90,6 +90,7 @@ fn collect_body(item: &Item, out: &mut Vec<SignalDecl>) {
|
||||
collect_body(inner, out);
|
||||
}
|
||||
}
|
||||
ItemKind::GenBlock(b) => block(b, out),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
block(&gen_if.then, out);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! What a preprocessor token says: the name a macro invocation calls, and the
|
||||
//! word and operand a compiler directive carries.
|
||||
//!
|
||||
//! The lexer keeps both shapes as single tokens — a macro invocation
|
||||
//! (`` `uvm_info("A", "B", UVM_LOW) ``) is one `Ident` whose text starts with
|
||||
//! a backtick and swallows its balanced arguments, and a directive
|
||||
//! (`` `ifdef FOO ``) is one `Directive` running to the end of its (possibly
|
||||
//! continued) line. Four rules read those texts; reading them in one place is
|
||||
//! what stops the four from disagreeing about where a name starts and ends.
|
||||
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
|
||||
/// The macro this token invokes, without its backtick or arguments, or `None`
|
||||
/// for a token that is not a macro invocation.
|
||||
pub(crate) fn macro_name(token: &Token) -> Option<&str> {
|
||||
if token.kind != TokenKind::Ident {
|
||||
return None;
|
||||
}
|
||||
let rest = token.text.strip_prefix('`')?;
|
||||
let end = rest.find(|c: char| !is_name_char(c)).unwrap_or(rest.len());
|
||||
match end {
|
||||
0 => None,
|
||||
_ => Some(&rest[..end]),
|
||||
}
|
||||
}
|
||||
|
||||
/// The keyword of a compiler directive (`ifdef`, `endif`, `define`), or `None`
|
||||
/// for a token that is not one.
|
||||
pub(crate) fn directive_word(token: &Token) -> Option<&str> {
|
||||
if token.kind != TokenKind::Directive {
|
||||
return None;
|
||||
}
|
||||
let rest = token.text.strip_prefix('`')?;
|
||||
let end = rest.find(|c: char| !is_name_char(c)).unwrap_or(rest.len());
|
||||
match end {
|
||||
0 => None,
|
||||
_ => Some(&rest[..end]),
|
||||
}
|
||||
}
|
||||
|
||||
/// The name a directive names — the `FOO` of `` `ifdef FOO `` — or `None` when
|
||||
/// it names nothing.
|
||||
pub(crate) fn directive_operand(token: &Token) -> Option<&str> {
|
||||
let word = directive_word(token)?;
|
||||
let rest = token.text.get(1 + word.len()..)?.trim_start();
|
||||
let end = rest.find(|c: char| !is_name_char(c)).unwrap_or(rest.len());
|
||||
match end {
|
||||
0 => None,
|
||||
_ => Some(&rest[..end]),
|
||||
}
|
||||
}
|
||||
|
||||
/// The characters an identifier is made of, matching the lexer's own rule.
|
||||
fn is_name_char(c: char) -> bool {
|
||||
c == '_' || c == '$' || c.is_ascii_alphanumeric()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_parser::tokenize;
|
||||
|
||||
fn tokens(src: &str) -> Vec<Token> {
|
||||
tokenize(src).expect("lexes")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_invocation_gives_its_name() {
|
||||
let toks = tokens("module m;\n initial `uvm_info(\"A\", \"B\", UVM_LOW);\nendmodule\n");
|
||||
let names: Vec<&str> = toks.iter().filter_map(macro_name).collect();
|
||||
assert_eq!(names, vec!["uvm_info"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_without_arguments_gives_its_name_too() {
|
||||
let toks = tokens("module m;\n `ASSERT_INIT\nendmodule\n");
|
||||
assert_eq!(toks.iter().filter_map(macro_name).collect::<Vec<_>>(), vec!["ASSERT_INIT"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ordinary_identifier_is_not_a_macro() {
|
||||
let toks = tokens("module m;\n wire uvm_info;\nendmodule\n");
|
||||
assert!(toks.iter().filter_map(macro_name).next().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directive_gives_its_word_and_operand() {
|
||||
let toks = tokens("`ifdef FOO\n`endif\n`define BAR 1\nmodule m;\nendmodule\n");
|
||||
let words: Vec<&str> = toks.iter().filter_map(directive_word).collect();
|
||||
assert_eq!(words, vec!["ifdef", "endif", "define"]);
|
||||
let operands: Vec<Option<&str>> =
|
||||
toks.iter().filter(|t| t.kind == TokenKind::Directive).map(directive_operand).collect();
|
||||
assert_eq!(operands, vec![Some("FOO"), None, Some("BAR")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directive_is_not_a_macro_invocation_and_the_other_way_round() {
|
||||
let toks = tokens("`ifdef FOO\nmodule m;\n `ASSERT\nendmodule\n`endif\n");
|
||||
assert_eq!(toks.iter().filter_map(macro_name).collect::<Vec<_>>(), vec!["ASSERT"]);
|
||||
assert!(toks
|
||||
.iter()
|
||||
.filter(|t| t.kind == TokenKind::Ident)
|
||||
.all(|t| directive_word(t).is_none()));
|
||||
}
|
||||
}
|
||||
@@ -85,24 +85,36 @@ pub fn all_rules() -> Vec<&'static dyn Rule> {
|
||||
&rules::banned_declared_name_patterns::BannedDeclaredNamePatterns,
|
||||
&rules::case_missing_default::CaseMissingDefault,
|
||||
&rules::constraint_name_style::ConstraintNameStyle,
|
||||
&rules::create_object_name_match::CreateObjectNameMatch,
|
||||
&rules::dff_name_style::DffNameStyle,
|
||||
&rules::disable_statement::DisableStatement,
|
||||
&rules::duplicate_declaration::DuplicateDeclaration,
|
||||
&rules::empty_item::EmptyItem,
|
||||
&rules::endif_comment::EndifComment,
|
||||
&rules::enum_name_style::EnumNameStyle,
|
||||
&rules::explicit_begin::ExplicitBegin,
|
||||
&rules::explicit_function_lifetime::ExplicitFunctionLifetime,
|
||||
&rules::explicit_function_task_parameter_type::ExplicitFunctionTaskParameterType,
|
||||
&rules::explicit_parameter_storage_type::ExplicitParameterStorageType,
|
||||
&rules::explicit_task_lifetime::ExplicitTaskLifetime,
|
||||
&rules::forbid_consecutive_null_statements::ForbidConsecutiveNullStatements,
|
||||
&rules::forbid_defparam::ForbidDefparam,
|
||||
&rules::forbid_line_continuations::ForbidLineContinuations,
|
||||
&rules::forbid_negative_array_dim::ForbidNegativeArrayDim,
|
||||
&rules::forbidden_macro::ForbiddenMacro,
|
||||
&rules::generate_label::GenerateLabel,
|
||||
&rules::generate_label_prefix::GenerateLabelPrefix,
|
||||
&rules::incomplete_assignment::IncompleteAssignment,
|
||||
&rules::instance_shadowing::InstanceShadowing,
|
||||
&rules::interface_name_style::InterfaceNameStyle,
|
||||
&rules::invalid_system_task_function::InvalidSystemTaskFunction,
|
||||
&rules::legacy_generate_region::LegacyGenerateRegion,
|
||||
&rules::legacy_genvar_declaration::LegacyGenvarDeclaration,
|
||||
&rules::line_length::LineLength,
|
||||
&rules::macro_name_style::MacroNameStyle,
|
||||
&rules::macro_string_concatenation::MacroStringConcatenation,
|
||||
&rules::mismatched_labels::MismatchedLabels,
|
||||
&rules::module_begin_block::ModuleBeginBlock,
|
||||
&rules::module_filename::ModuleFilename,
|
||||
&rules::module_name_style::ModuleNameStyle,
|
||||
&rules::module_parameter::ModuleParameter,
|
||||
@@ -110,6 +122,7 @@ pub fn all_rules() -> Vec<&'static dyn Rule> {
|
||||
&rules::multiply_driven::MultiplyDriven,
|
||||
&rules::no_tabs::NoTabs,
|
||||
&rules::no_trailing_whitespace::NoTrailingWhitespace,
|
||||
&rules::numeric_format_string_style::NumericFormatStringStyle,
|
||||
&rules::one_module_per_file::OneModulePerFile,
|
||||
&rules::package_filename::PackageFilename,
|
||||
&rules::packed_dimensions_range_ordering::PackedDimensionsRangeOrdering,
|
||||
@@ -117,9 +130,12 @@ pub fn all_rules() -> Vec<&'static dyn Rule> {
|
||||
&rules::parameter_type_name_style::ParameterTypeNameStyle,
|
||||
&rules::plusarg_assignment::PlusargAssignment,
|
||||
&rules::port_name_suffix::PortNameSuffix,
|
||||
&rules::positive_meaning_parameter_name::PositiveMeaningParameterName,
|
||||
&rules::posix_eof::PosixEof,
|
||||
&rules::proper_parameter_declaration::ProperParameterDeclaration,
|
||||
&rules::signal_name_style::SignalNameStyle,
|
||||
&rules::struct_union_name_style::StructUnionNameStyle,
|
||||
&rules::suggest_parentheses::SuggestParentheses,
|
||||
&rules::suspicious_semicolon::SuspiciousSemicolon,
|
||||
&rules::truncated_numeric_literal::TruncatedNumericLiteral,
|
||||
&rules::typedef_enums::TypedefEnums,
|
||||
@@ -129,8 +145,11 @@ pub fn all_rules() -> Vec<&'static dyn Rule> {
|
||||
&rules::undriven_net::UndrivenNet,
|
||||
&rules::unknown_parameter::UnknownParameter,
|
||||
&rules::unknown_port::UnknownPort,
|
||||
&rules::unpacked_dimensions_range_ordering::UnpackedDimensionsRangeOrdering,
|
||||
&rules::unused_signal::UnusedSignal,
|
||||
&rules::unused_waiver::UnusedWaiver,
|
||||
&rules::uvm_macro_semicolon::UvmMacroSemicolon,
|
||||
&rules::v2001_generate_begin::V2001GenerateBegin,
|
||||
&rules::void_cast::VoidCast,
|
||||
&rules::wire_reg_mixup::WireRegMixup,
|
||||
]
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
//! `create-object-name-match` — `type_id::create("x")` names the variable `x`.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::{walk_all_stmts, walk_items};
|
||||
use vlog_parser::ast::{Expr, ExprKind, ItemKind, StmtKind};
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct CreateObjectNameMatch;
|
||||
|
||||
const NAME: &str = "create-object-name-match";
|
||||
|
||||
impl Rule for CreateObjectNameMatch {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"give `type_id::create` the name of the variable it is assigned to"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"The string handed to `type_id::create()` becomes the object's UVM \
|
||||
instance name, and that name is what `uvm_config_db` paths, factory \
|
||||
overrides, `+uvm_set_config` plusargs and every report line are \
|
||||
written against. When it does not match the handle it was assigned \
|
||||
to, a config setting aimed at `env.agent.driver` silently misses the \
|
||||
object the reader believes it is aimed at — and nothing fails, it \
|
||||
just does not take. Verible's `create-object-name-match` (\"Checks \
|
||||
that the 'name' argument of `type_id::create()` matches the assigned \
|
||||
variable name.\", enabled by default) is the same rule and the same \
|
||||
default.\n\n\
|
||||
Judged where Verible judges it: a right-hand side of the shape \
|
||||
`<type>::type_id::create(\"name\", …)`, however the type is \
|
||||
qualified (`pkg::cls::type_id::create`), assigned to a **plain \
|
||||
variable** — a `this.h` or an array element is not one, and neither \
|
||||
is a `create` whose first argument is not a string literal. No \
|
||||
automatic fix: rewriting the string changes the object's UVM path, \
|
||||
and rewriting the variable renames it everywhere; which is meant is \
|
||||
the author's to say."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
let mut judge = |lhs: &str, rhs: &Expr| {
|
||||
let Some(arg) = create_name(rhs) else { return };
|
||||
let Some(written) = string_value(arg) else { return };
|
||||
if written == lhs {
|
||||
return;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!(
|
||||
"`type_id::create` is named `{written}` but assigned to `{lhs}`; \
|
||||
the two must match"
|
||||
),
|
||||
arg.span,
|
||||
));
|
||||
};
|
||||
walk_all_stmts(ctx.file(), &mut |stmt| match &stmt.kind {
|
||||
StmtKind::Assign { lhs, rhs, .. } => {
|
||||
if let ExprKind::Ident(name) = &lhs.kind {
|
||||
judge(name, rhs);
|
||||
}
|
||||
}
|
||||
StmtKind::VarDecl(decl) => {
|
||||
for declarator in &decl.declarators {
|
||||
if let Some(init) = &declarator.init {
|
||||
judge(&declarator.name, init);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
walk_items(ctx.file(), &mut |item| {
|
||||
let ItemKind::DataDecl(decl) = &item.kind else { return };
|
||||
for declarator in &decl.declarators {
|
||||
if let Some(init) = &declarator.init {
|
||||
judge(&declarator.name, init);
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The first argument of a `…::type_id::create(…)` call, or `None` for
|
||||
/// anything else.
|
||||
fn create_name(expr: &Expr) -> Option<&Expr> {
|
||||
let ExprKind::Call { callee, args, .. } = &expr.kind else { return None };
|
||||
let ExprKind::Scope { base, name, .. } = &callee.kind else { return None };
|
||||
if name != "create" {
|
||||
return None;
|
||||
}
|
||||
let ExprKind::Scope { name: middle, .. } = &base.kind else { return None };
|
||||
if middle != "type_id" {
|
||||
return None;
|
||||
}
|
||||
args.first().map(|arg| &arg.expr)
|
||||
}
|
||||
|
||||
/// The text of a string literal, without its quotes.
|
||||
fn string_value(expr: &Expr) -> Option<&str> {
|
||||
let ExprKind::Str(text) = &expr.kind else { return None };
|
||||
text.strip_prefix('"')?.strip_suffix('"')
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
CreateObjectNameMatch.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn body(text: &str) -> String {
|
||||
format!(
|
||||
"class c;\n function automatic void build();\n {text}\n endfunction\nendclass\n"
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_mismatched_name_and_underlines_the_string() {
|
||||
let src = body("driver_h = my_driver::type_id::create(\"drv\", this);");
|
||||
let found = violations(&src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "\"drv\"");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_matching_name_is_what_the_rule_wants() {
|
||||
for text in [
|
||||
"driver_h = my_driver::type_id::create(\"driver_h\", this);",
|
||||
"driver_h = pkg::my_driver::type_id::create(\"driver_h\");",
|
||||
] {
|
||||
let src = body(text);
|
||||
assert!(violations(&src).is_empty(), "{text}: {:?}", violations(&src));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declaration_with_an_initialiser_is_judged_too() {
|
||||
let src = body("my_driver driver_h = my_driver::type_id::create(\"drv\");");
|
||||
assert_eq!(violations(&src).len(), 1, "{:?}", violations(&src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn something_that_is_not_a_type_id_create_is_left_alone() {
|
||||
for text in [
|
||||
"driver_h = my_driver::create(\"drv\");",
|
||||
"driver_h = my_driver::type_id::get();",
|
||||
"driver_h = new(\"drv\");",
|
||||
"driver_h = f(\"drv\");",
|
||||
] {
|
||||
let src = body(text);
|
||||
assert!(violations(&src).is_empty(), "{text}: {:?}", violations(&src));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_literal_name_or_a_non_plain_target_says_nothing() {
|
||||
for text in [
|
||||
"driver_h = my_driver::type_id::create(name_s, this);",
|
||||
"this.driver_h = my_driver::type_id::create(\"drv\");",
|
||||
"agents[0] = my_agent::type_id::create(\"drv\");",
|
||||
] {
|
||||
let src = body(text);
|
||||
assert!(violations(&src).is_empty(), "{text}: {:?}", violations(&src));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,459 @@
|
||||
//! `dff-name-style` — a flip-flop's output and its next-state input are named
|
||||
//! for each other.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::options::{OptionDefault, OptionKind, OptionSpec};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::{walk_all_stmts, walk_items};
|
||||
use vlog_parser::ast::{Expr, ExprKind, ItemKind, Stmt, StmtKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct DffNameStyle;
|
||||
|
||||
const NAME: &str = "dff-name-style";
|
||||
|
||||
/// Verible's four options. Its `input` / `output` / `waive_ifs_with_conditions`
|
||||
/// are comma-separated strings there and lists here, which is how every other
|
||||
/// lucisv list option is spelled; `waive_lhs_regex`'s default is Verible's
|
||||
/// `(?i)mem.*` written without the inline flag this engine does not implement.
|
||||
const OPTIONS: &[OptionSpec] = &[
|
||||
OptionSpec {
|
||||
name: "input",
|
||||
kind: OptionKind::List,
|
||||
default: OptionDefault::List(&["next", "n", "d"]),
|
||||
doc: "suffixes that mark the next-state input of a flip-flop",
|
||||
},
|
||||
OptionSpec {
|
||||
name: "output",
|
||||
kind: OptionKind::List,
|
||||
default: OptionDefault::List(&["reg", "r", "ff", "q"]),
|
||||
doc: "suffixes that mark the registered output of a flip-flop",
|
||||
},
|
||||
OptionSpec {
|
||||
name: "waive_ifs_with_conditions",
|
||||
kind: OptionKind::List,
|
||||
default: OptionDefault::List(&[
|
||||
"!rst_ni",
|
||||
"flush_i",
|
||||
"!rst_ni || flush_i",
|
||||
"flush_i || !rst_ni",
|
||||
]),
|
||||
doc: "conditions whose branches are reset or flush paths and are not judged",
|
||||
},
|
||||
OptionSpec {
|
||||
name: "waive_lhs_regex",
|
||||
kind: OptionKind::Regex,
|
||||
default: OptionDefault::Str("[mM][eE][mM].*"),
|
||||
doc: "names that are not flip-flops at all and are left alone",
|
||||
},
|
||||
];
|
||||
|
||||
impl Rule for DffNameStyle {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"name a flip-flop's output and its next-state input for each other"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn default_on(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn options(&self) -> &'static [OptionSpec] {
|
||||
OPTIONS
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"The `_q`/`_d` convention makes a design's state visible at a glance: \
|
||||
`count_q <= count_d` says \"this is the register, that is the \
|
||||
combinational next value\", so a waveform, a schematic and the source \
|
||||
all name the same two nets, and a signal called `count_q` driven by \
|
||||
a `always_comb` is a mistake the reader can see without following it. \
|
||||
Verible's `dff-name-style` (\"Checks that D Flip-Flops use \
|
||||
appropriate naming conventions in input/output ports.\", **disabled** \
|
||||
by default) is the same rule and the same default, with the same four \
|
||||
options.\n\n\
|
||||
Two things are checked. **In an `always_ff`**, a nonblocking \
|
||||
assignment's left-hand side must end with one of the `output` \
|
||||
suffixes (`_q`, `_r`, `_ff`, `_reg`, optionally with a pipeline \
|
||||
number: `data_q2`); and when its right-hand side is a plain name \
|
||||
ending with one of the `input` suffixes (`_d`, `_n`, `_next`), the \
|
||||
two must share a base — `data_q <= data_d` is right, `data_q <= \
|
||||
other_d` is not. **Outside one**, a blocking or continuous \
|
||||
assignment to a name ending in an `output` suffix is reported: that \
|
||||
name promises a register and is not one.\n\n\
|
||||
Only a **plain identifier** is judged on either side; an indexed, \
|
||||
member-selected or concatenated target is not something a naming \
|
||||
convention can speak about. A branch whose `if` condition is one of \
|
||||
`waive_ifs_with_conditions` is skipped, which is what keeps reset \
|
||||
and flush paths quiet, and a name matching `waive_lhs_regex` is \
|
||||
skipped entirely (memories are not flip-flops). Conditions are \
|
||||
compared ignoring whitespace, so `!rst_ni` and `! rst_ni` are the \
|
||||
same waiver. No automatic fix: renaming a signal is a rename."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let settings = Settings::read(ctx);
|
||||
let mut out = Vec::new();
|
||||
registered(ctx, &settings, &mut out);
|
||||
unregistered(ctx, &settings, &mut out);
|
||||
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The four options, read once for the whole file.
|
||||
struct Settings {
|
||||
input: Vec<String>,
|
||||
output: Vec<String>,
|
||||
waived_conditions: Vec<String>,
|
||||
waived_lhs: Option<crate::regex::Regex>,
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
fn read(ctx: &LintContext) -> Settings {
|
||||
Settings {
|
||||
input: ctx.option_list(NAME, "input"),
|
||||
output: ctx.option_list(NAME, "output"),
|
||||
waived_conditions: ctx
|
||||
.option_list(NAME, "waive_ifs_with_conditions")
|
||||
.iter()
|
||||
.map(|text| squeeze(text))
|
||||
.collect(),
|
||||
waived_lhs: ctx.option_pattern(NAME, "waive_lhs_regex"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this left-hand side is one the project asked not to judge.
|
||||
fn waives(&self, name: &str) -> bool {
|
||||
self.waived_lhs.as_ref().is_some_and(|pattern| pattern.is_match(name))
|
||||
}
|
||||
}
|
||||
|
||||
/// The `always_ff` half: every nonblocking assignment inside one.
|
||||
fn registered(ctx: &LintContext, settings: &Settings, out: &mut Vec<Violation>) {
|
||||
walk_items(ctx.file(), &mut |item| {
|
||||
let ItemKind::Always { kw, stmt } = &item.kind else { return };
|
||||
if kw != "always_ff" {
|
||||
return;
|
||||
}
|
||||
let mut conditions: Vec<String> = Vec::new();
|
||||
clocked(ctx, settings, stmt, &mut conditions, out);
|
||||
});
|
||||
}
|
||||
|
||||
/// Walks one `always_ff` body, remembering which `if` conditions hold.
|
||||
fn clocked(
|
||||
ctx: &LintContext,
|
||||
settings: &Settings,
|
||||
stmt: &Stmt,
|
||||
conditions: &mut Vec<String>,
|
||||
out: &mut Vec<Violation>,
|
||||
) {
|
||||
match &stmt.kind {
|
||||
StmtKind::Assign { lhs, rhs, op, .. } if op == "<=" => {
|
||||
if conditions.iter().any(|cond| settings.waived_conditions.contains(cond)) {
|
||||
return;
|
||||
}
|
||||
judge_flop(settings, lhs, rhs, out);
|
||||
}
|
||||
StmtKind::If { cond, then, els, .. } => {
|
||||
conditions.push(squeeze(text_of(ctx, cond.span)));
|
||||
clocked(ctx, settings, then, conditions, out);
|
||||
conditions.pop();
|
||||
if let Some(els) = els {
|
||||
clocked(ctx, settings, els, conditions, out);
|
||||
}
|
||||
}
|
||||
StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => {
|
||||
for inner in stmts {
|
||||
clocked(ctx, settings, inner, conditions, out);
|
||||
}
|
||||
}
|
||||
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
|
||||
for case_item in items {
|
||||
clocked(ctx, settings, &case_item.stmt, conditions, out);
|
||||
}
|
||||
}
|
||||
StmtKind::Labeled { stmt: inner, .. }
|
||||
| StmtKind::For { body: inner, .. }
|
||||
| StmtKind::While { body: inner, .. }
|
||||
| StmtKind::DoWhile { body: inner, .. }
|
||||
| StmtKind::Repeat { body: inner, .. }
|
||||
| StmtKind::Forever { body: inner }
|
||||
| StmtKind::Foreach { body: inner, .. } => clocked(ctx, settings, inner, conditions, out),
|
||||
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
|
||||
clocked(ctx, settings, inner, conditions, out)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// One `q <= d` inside an `always_ff`.
|
||||
fn judge_flop(settings: &Settings, lhs: &Expr, rhs: &Expr, out: &mut Vec<Violation>) {
|
||||
let Some(target) = plain_name(lhs) else { return };
|
||||
if settings.waives(target) {
|
||||
return;
|
||||
}
|
||||
let Some(base) = base_of(target, &settings.output) else {
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!(
|
||||
"`{target}` is assigned in an `always_ff` but does not end with {}",
|
||||
one_of(&settings.output)
|
||||
),
|
||||
lhs.span,
|
||||
));
|
||||
return;
|
||||
};
|
||||
if base.is_empty() {
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!("`{target}` is nothing but a flip-flop suffix; name the signal too"),
|
||||
lhs.span,
|
||||
));
|
||||
return;
|
||||
}
|
||||
let Some(source) = plain_name(rhs) else { return };
|
||||
let Some(source_base) = base_of(source, &settings.input) else { return };
|
||||
if source_base != base {
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!(
|
||||
"`{target}` is driven by `{source}`; the parts before the suffixes must \
|
||||
match, but `{base}` is not `{source_base}`"
|
||||
),
|
||||
rhs.span,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// The other half: a name that promises a register, driven by something that
|
||||
/// is not one.
|
||||
fn unregistered(ctx: &LintContext, settings: &Settings, out: &mut Vec<Violation>) {
|
||||
let mut judge = |lhs: &Expr| {
|
||||
let Some(target) = plain_name(lhs) else { return };
|
||||
if settings.waives(target) {
|
||||
return;
|
||||
}
|
||||
if base_of(target, &settings.output).is_some_and(|base| !base.is_empty()) {
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!(
|
||||
"`{target}` is named like a flip-flop output but is not driven by a \
|
||||
nonblocking assignment in an `always_ff`"
|
||||
),
|
||||
lhs.span,
|
||||
));
|
||||
}
|
||||
};
|
||||
walk_items(ctx.file(), &mut |item| {
|
||||
let ItemKind::ContAssign(assign) = &item.kind else { return };
|
||||
for pair in &assign.assigns {
|
||||
judge(&pair.lhs);
|
||||
}
|
||||
});
|
||||
// A blocking assignment anywhere — in an `always_comb`, an `initial`, or
|
||||
// inside the `always_ff` itself, which is the shape the rule most wants.
|
||||
walk_all_stmts(ctx.file(), &mut |stmt| {
|
||||
let StmtKind::Assign { lhs, op, .. } = &stmt.kind else { return };
|
||||
if op == "<=" {
|
||||
return;
|
||||
}
|
||||
judge(lhs);
|
||||
});
|
||||
}
|
||||
|
||||
/// The name of a plain identifier, or `None` for any other target.
|
||||
fn plain_name(expr: &Expr) -> Option<&str> {
|
||||
match &expr.kind {
|
||||
ExprKind::Ident(name) => Some(name),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The part of `name` before its `_<suffix>[digits]` tail, or `None` when it
|
||||
/// carries none of `suffixes`.
|
||||
fn base_of<'a>(name: &'a str, suffixes: &[String]) -> Option<&'a str> {
|
||||
let trimmed = name.trim_end_matches(|c: char| c.is_ascii_digit());
|
||||
for suffix in suffixes {
|
||||
if let Some(base) = trimmed.strip_suffix(suffix.as_str()) {
|
||||
if let Some(base) = base.strip_suffix('_') {
|
||||
return Some(base);
|
||||
}
|
||||
// `_q` on its own: a suffix with nothing in front of it.
|
||||
if base.is_empty() && trimmed.len() == suffix.len() {
|
||||
return Some("");
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// `` `_q`, `_r` or `_ff` `` — the suffix list, as a message says it.
|
||||
fn one_of(suffixes: &[String]) -> String {
|
||||
let quoted: Vec<String> = suffixes.iter().map(|s| format!("`_{s}`")).collect();
|
||||
match quoted.split_last() {
|
||||
Some((last, [])) => last.clone(),
|
||||
Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
|
||||
None => "a registered-output suffix".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The source text of a span.
|
||||
fn text_of<'a>(ctx: &'a LintContext, span: TextRange) -> &'a str {
|
||||
ctx.source().get(span.as_range()).unwrap_or("")
|
||||
}
|
||||
|
||||
/// The same text with every space taken out, so `!rst_ni` and `! rst_ni` are
|
||||
/// one waiver rather than two.
|
||||
fn squeeze(text: &str) -> String {
|
||||
text.chars().filter(|c| !c.is_whitespace()).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::options::RuleOptions;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
DffNameStyle.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn with(src: &str, key: &str, raw: &str) -> Vec<Violation> {
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw(NAME, key, raw).expect("accepted");
|
||||
DffNameStyle.check(&LintContext::new(src, None).with_options(&options))
|
||||
}
|
||||
|
||||
fn flop(body: &str) -> String {
|
||||
format!("module m;\n always_ff @(posedge clk) begin\n {body}\n end\nendmodule\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_convention_is_clean() {
|
||||
for body in [
|
||||
"data_q <= data_d;",
|
||||
"data_r <= data_n;",
|
||||
"data_ff <= data_next;",
|
||||
"data_reg <= data_d;",
|
||||
"data_q2 <= data_d2;",
|
||||
"data_q <= other_signal;",
|
||||
"data_q <= a + b;",
|
||||
] {
|
||||
let src = flop(body);
|
||||
assert!(violations(&src).is_empty(), "{body}: {:?}", violations(&src));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_registered_name_without_a_suffix() {
|
||||
let src = flop("data <= data_d;");
|
||||
let found = violations(&src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "data");
|
||||
assert!(found[0].message.contains("`_q`"), "{}", found[0].message);
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_mismatched_pair_and_points_at_the_source() {
|
||||
let src = flop("a_q <= b_n;");
|
||||
let found = violations(&src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "b_n");
|
||||
assert!(found[0].message.contains("`a` is not `b`"), "{}", found[0].message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_suffix_names_nothing() {
|
||||
let src = flop("_q <= data_d;");
|
||||
let found = violations(&src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(
|
||||
found[0].message.contains("nothing but a flip-flop suffix"),
|
||||
"{}",
|
||||
found[0].message
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reset_branch_is_waived_whatever_its_spacing() {
|
||||
for cond in ["!rst_ni", "! rst_ni", "flush_i", "!rst_ni || flush_i"] {
|
||||
let src = flop(&format!("if ({cond}) data <= '0; else data_q <= data_d;"));
|
||||
assert!(violations(&src).is_empty(), "{cond}: {:?}", violations(&src));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_condition_that_is_not_waived_is_still_judged() {
|
||||
let src = flop("if (enable_i) data <= data_d;");
|
||||
assert_eq!(violations(&src).len(), 1, "{:?}", violations(&src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_memory_name_is_waived_by_the_default_pattern() {
|
||||
for name in ["mem_array", "MEM_ARRAY", "Memory"] {
|
||||
let src = flop(&format!("{name} <= data_d;"));
|
||||
assert!(violations(&src).is_empty(), "{name}: {:?}", violations(&src));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flip_flop_name_driven_by_anything_else_is_reported() {
|
||||
let combinational = "module m;\n always_comb data_q = data_d;\nendmodule\n";
|
||||
assert_eq!(violations(combinational).len(), 1, "{:?}", violations(combinational));
|
||||
let continuous = "module m;\n assign data_q = data_d;\nendmodule\n";
|
||||
assert_eq!(violations(continuous).len(), 1, "{:?}", violations(continuous));
|
||||
let blocking_in_ff = flop("data_q = data_d;");
|
||||
assert_eq!(violations(&blocking_in_ff).len(), 1, "{:?}", violations(&blocking_in_ff));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_signal_driven_combinationally_is_nobodys_business() {
|
||||
let src = "module m;\n assign data_d = a + b;\n always_comb next = 1;\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_plain_target_is_not_judged() {
|
||||
for body in ["data[0] <= data_d;", "s.f <= data_d;", "{a, b} <= data_d;"] {
|
||||
let src = flop(body);
|
||||
assert!(violations(&src).is_empty(), "{body}: {:?}", violations(&src));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_suffix_lists_are_configurable() {
|
||||
let src = flop("data_ptr <= data_nxt;");
|
||||
assert_eq!(violations(&src).len(), 1);
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw(NAME, "output", "[\"ptr\"]").expect("accepted");
|
||||
options.set_raw(NAME, "input", "[\"nxt\"]").expect("accepted");
|
||||
let found = DffNameStyle.check(&LintContext::new(&src, None).with_options(&options));
|
||||
assert!(found.is_empty(), "{found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lhs_waiver_pattern_is_configurable() {
|
||||
let src = flop("scratch <= data_d;");
|
||||
assert_eq!(violations(&src).len(), 1);
|
||||
assert!(with(&src, "waive_lhs_regex", "\"scratch.*\"").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_waived_conditions_are_configurable() {
|
||||
let src = flop("if (my_reset) data <= '0;");
|
||||
assert_eq!(violations(&src).len(), 1);
|
||||
assert!(with(&src, "waive_ifs_with_conditions", "[\"my_reset\"]").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
//! `disable-statement` — `disable` only a sequential block, or `disable fork`.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::{walk_all_stmts, walk_items};
|
||||
use vlog_parser::ast::{ItemKind, SourceFile, StmtKind};
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct DisableStatement;
|
||||
|
||||
const NAME: &str = "disable-statement";
|
||||
|
||||
impl Rule for DisableStatement {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"`disable` a sequential block or a task, and write `disable fork` for processes"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn default_on(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"`disable label` terminates the named sequential block, and \
|
||||
`disable fork` terminates the calling process's children (IEEE 1800 \
|
||||
§9.6.2, §9.6.3). Naming a `fork` block instead of writing \
|
||||
`disable fork` is the mistake this rule exists for: it reads as \
|
||||
though it kills the forked processes and does something else \
|
||||
entirely, and in the common `fork … join_none` idiom it kills \
|
||||
nothing at all. Verible's `disable-statement` (\"Checks that there \
|
||||
are no occurrences of `disable some_label` if label refers to \
|
||||
non-sequential blocks.\", **disabled** by default) is the same rule \
|
||||
and the same default.\n\n\
|
||||
What counts as a valid target here is the label of a \
|
||||
`begin : name` block, a statement label (`name : begin`) — and, \
|
||||
**wider than Verible**, the name of a task or function declared in \
|
||||
the same file, because `disable task_name` is a legal and ordinary \
|
||||
thing to write (§9.6.2) and reporting it would be a false positive. \
|
||||
A name lucisv cannot see at all — a block in another file, a label a \
|
||||
macro produces — is therefore reported; that is the rule's one \
|
||||
false-positive mode and the reason it ships off. No automatic fix: \
|
||||
whether the author meant `disable fork` or a different label is not \
|
||||
something the source says."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let targets = disableable(ctx.file());
|
||||
let mut out = Vec::new();
|
||||
walk_all_stmts(ctx.file(), &mut |stmt| {
|
||||
let StmtKind::Disable(name) = &stmt.kind else { return };
|
||||
// `disable fork` is the keyword form, not a label.
|
||||
if name == "fork" || targets.contains(name.as_str()) {
|
||||
return;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!(
|
||||
"`disable {name}` names no sequential block or task; write `disable fork` \
|
||||
to stop forked processes"
|
||||
),
|
||||
stmt.span,
|
||||
));
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Every name a `disable` may legitimately mention in this file: the labels of
|
||||
/// sequential blocks and statement labels, plus the tasks and functions the
|
||||
/// file declares.
|
||||
fn disableable(file: &SourceFile) -> BTreeSet<String> {
|
||||
let mut out = BTreeSet::new();
|
||||
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
|
||||
StmtKind::Block { label: Some(label), .. } => {
|
||||
out.insert(label.clone());
|
||||
}
|
||||
StmtKind::Labeled { name, stmt: inner, .. } => {
|
||||
if matches!(inner.kind, StmtKind::Block { .. }) {
|
||||
out.insert(name.clone());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
walk_items(file, &mut |item| match &item.kind {
|
||||
ItemKind::Task(decl) => {
|
||||
out.insert(decl.name.clone());
|
||||
}
|
||||
ItemKind::Function(decl) => {
|
||||
out.insert(decl.name.clone());
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
DisableStatement.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_disable_of_a_fork_label() {
|
||||
let src = "module m;\n initial begin\n fork : threads\n join_none\n \
|
||||
disable threads;\n end\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "disable threads;");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disable_fork_is_the_spelling_the_rule_asks_for() {
|
||||
let src = "module m;\n initial begin\n fork\n join_none\n disable fork;\n \
|
||||
end\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sequential_block_label_is_a_valid_target() {
|
||||
let src = "module m;\n initial begin : seq\n disable seq;\n end\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_statement_label_on_a_block_counts_too() {
|
||||
let src = "module m;\n initial begin\n outer : begin\n disable outer;\n \
|
||||
end\n end\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_task_of_the_same_file_is_a_legal_target() {
|
||||
let src = "module m;\n task automatic t();\n endtask\n initial begin\n \
|
||||
disable t;\n end\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_this_file_does_not_declare_is_reported() {
|
||||
let src = "module m;\n initial begin\n disable somewhere_else;\n end\nendmodule\n";
|
||||
assert_eq!(violations(src).len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
//! `endif-comment` — say which `` `ifdef `` an `` `endif `` closes.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::preproc::{directive_operand, directive_word};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::{Applicability, Fix, Violation};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::Token;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct EndifComment;
|
||||
|
||||
const NAME: &str = "endif-comment";
|
||||
|
||||
impl Rule for EndifComment {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"name the condition an `` `endif `` closes in a comment beside it"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn default_on(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn fix(&self) -> Option<Applicability> {
|
||||
Some(Applicability::Safe)
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A bare `` `endif `` two hundred lines below its `` `ifdef `` tells \
|
||||
the reader nothing: which condition just ended, and whether the \
|
||||
nesting is what they think it is, both take a scroll to answer. \
|
||||
`` `endif // SYNTHESIS `` answers them in place, which is the same \
|
||||
argument `mismatched-labels` makes for `end : name`. Verible's \
|
||||
`endif-comment` (\"Checks that a Verilog `` `endif `` directive is \
|
||||
followed by a matching comment.\", **disabled** by default) is the \
|
||||
same rule and the same default.\n\n\
|
||||
The comment must **name the condition** — any comment on the \
|
||||
`` `endif ``'s own line that writes the macro name as a word will \
|
||||
do, so `// SYNTHESIS`, `` // `ifdef SYNTHESIS `` and `/* SYNTHESIS \
|
||||
*/` all pass. An `` `endif `` whose `` `ifdef `` lucisv cannot see \
|
||||
(an unbalanced file, a condition opened in an included header) is \
|
||||
left alone: there is no name to ask for.\n\n\
|
||||
The fix is **safe** and only offered where there is no comment at \
|
||||
all: it appends `` // <name> `` after the directive, adding text and \
|
||||
removing none. A comment that is there but names something else is \
|
||||
reported without a fix — rewriting somebody's words is not a repair."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut open: Vec<Option<String>> = Vec::new();
|
||||
let mut out = Vec::new();
|
||||
for token in ctx.tokens() {
|
||||
match directive_word(token) {
|
||||
Some("ifdef") | Some("ifndef") => {
|
||||
open.push(directive_operand(token).map(str::to_string))
|
||||
}
|
||||
Some("endif") => {
|
||||
// An `endif` with nothing open is an unbalanced file, or a
|
||||
// condition opened in an included header: no name to ask
|
||||
// for, so nothing to say.
|
||||
let Some(Some(name)) = open.pop() else { continue };
|
||||
if let Some(violation) = judge(ctx, token, &name) {
|
||||
out.push(violation);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The finding this `` `endif `` earns, or `None` when its comment names the
|
||||
/// condition.
|
||||
fn judge(ctx: &LintContext, token: &Token, name: &str) -> Option<Violation> {
|
||||
let beside: Vec<&str> = ctx
|
||||
.comments()
|
||||
.into_iter()
|
||||
.filter(|comment| comment.line == token.line && comment.span.start >= token.span.end)
|
||||
.map(|comment| comment.text.as_str())
|
||||
.collect();
|
||||
if beside.iter().any(|text| names(text, name)) {
|
||||
return None;
|
||||
}
|
||||
let violation = Violation::new(
|
||||
NAME,
|
||||
format!("`endif` does not say what it closes; write `// {name}`"),
|
||||
token.span,
|
||||
);
|
||||
match beside.is_empty() {
|
||||
true => Some(violation.with_fix(Fix::safe(vec![(
|
||||
TextRange::new(token.span.end, token.span.end),
|
||||
format!(" // {name}"),
|
||||
)]))),
|
||||
// There is a comment; it just names something else. Replacing it would
|
||||
// throw away what somebody wrote.
|
||||
false => Some(violation),
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `text` writes `name` as a whole word.
|
||||
fn names(text: &str, name: &str) -> bool {
|
||||
let is_part = |c: char| c == '_' || c == '$' || c.is_ascii_alphanumeric();
|
||||
let mut rest = text;
|
||||
while let Some(at) = rest.find(name) {
|
||||
let before = rest[..at].chars().next_back();
|
||||
let after = rest[at + name.len()..].chars().next();
|
||||
if !before.is_some_and(is_part) && !after.is_some_and(is_part) {
|
||||
return true;
|
||||
}
|
||||
rest = &rest[at + name.len()..];
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::violation::apply_fixes;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
EndifComment.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_bare_endif_and_offers_the_comment() {
|
||||
let src = "`ifdef SYNTHESIS\nmodule m;\nendmodule\n`endif\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "`endif");
|
||||
let fixed = apply_fixes(src, &found, false);
|
||||
assert_eq!(fixed.output, "`ifdef SYNTHESIS\nmodule m;\nendmodule\n`endif // SYNTHESIS\n");
|
||||
assert!(violations(&fixed.output).is_empty(), "the fix settles");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_naming_comment_of_any_shape_passes() {
|
||||
for comment in ["// SYNTHESIS", "// `ifdef SYNTHESIS", "/* SYNTHESIS */", "//SYNTHESIS"] {
|
||||
let src = format!("`ifdef SYNTHESIS\nmodule m;\nendmodule\n`endif {comment}\n");
|
||||
assert!(violations(&src).is_empty(), "{comment}: {:?}", violations(&src));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_naming_something_else_is_reported_without_a_fix() {
|
||||
let src = "`ifdef SYNTHESIS\nmodule m;\nendmodule\n`endif // done\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].fix.is_none(), "somebody's comment is not ours to rewrite");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_that_only_contains_the_condition_is_not_a_match() {
|
||||
let src = "`ifdef SYN\nmodule m;\nendmodule\n`endif // SYNTHESIS\n";
|
||||
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nesting_pairs_each_endif_with_its_own_condition() {
|
||||
let src = "`ifdef A\n`ifdef B\nmodule m;\nendmodule\n`endif\n`endif\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 2, "{found:?}");
|
||||
assert!(found[0].message.contains("// B"), "{}", found[0].message);
|
||||
assert!(found[1].message.contains("// A"), "{}", found[1].message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ifndef_and_an_else_are_handled_like_the_ifdef() {
|
||||
let src = "`ifndef A\nmodule m;\nendmodule\n`else\nmodule n;\nendmodule\n`endif\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("// A"), "{}", found[0].message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unbalanced_endif_has_no_name_to_ask_for() {
|
||||
assert!(violations("`endif\nmodule m;\nendmodule\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_on_the_next_line_is_not_beside_the_endif() {
|
||||
let src = "`ifdef A\nmodule m;\nendmodule\n`endif\n// A\n";
|
||||
assert_eq!(violations(src).len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
//! `explicit-function-lifetime` — say `automatic` or `static` outside a class.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::{walk_items_scoped, ItemScope};
|
||||
use vlog_parser::ast::ItemKind;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct ExplicitFunctionLifetime;
|
||||
|
||||
const NAME: &str = "explicit-function-lifetime";
|
||||
|
||||
/// The two words that state a lifetime, wherever a subroutine writes them.
|
||||
pub(crate) const LIFETIMES: [&str; 2] = ["automatic", "static"];
|
||||
|
||||
impl Rule for ExplicitFunctionLifetime {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"state `automatic` or `static` on a function declared outside a class"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A function with no stated lifetime is `static` in a module and \
|
||||
`automatic` in a class (IEEE 1800 §13.4.2), and a static function's \
|
||||
locals are shared by every call — so one written without the keyword \
|
||||
is a re-entrancy bug waiting for the second caller, and a reader \
|
||||
cannot tell whether the author knew. Writing the word costs nine \
|
||||
characters and removes the question. Verible's \
|
||||
`explicit-function-lifetime` (\"Checks that every function declared \
|
||||
outside of a class is declared with an explicit lifetime.\", enabled \
|
||||
by default) is the same rule and the same default; a class method is \
|
||||
exempt in both, because there the default is already the safe one.\n\n\
|
||||
A body-less **prototype** — `extern function f;`, a `pure virtual`, a \
|
||||
DPI import — is not judged: it declares no locals, and the definition \
|
||||
that follows is where the lifetime belongs. Nor is an **out-of-body \
|
||||
definition** (`function cls::f(...); … endfunction`), which is \
|
||||
**wider than Verible**: lexically it sits outside the class, and \
|
||||
Verible reports it, but it *is* a class method and its lifetime is \
|
||||
already automatic — 948 of the 960 opentitan findings this rule and \
|
||||
its task twin produced before the exemption were exactly that shape. \
|
||||
No automatic fix: \
|
||||
`automatic` is the answer a reader expects and `static` is what the \
|
||||
language would have picked, so choosing between them changes what \
|
||||
the code does."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_items_scoped(ctx.file(), &mut |scope, item| {
|
||||
let ItemKind::Function(decl) = &item.kind else { return };
|
||||
// An out-of-body definition (`function cls::f(...)`) is a class
|
||||
// method written outside the class body; `scope` is non-empty for
|
||||
// exactly those.
|
||||
if scope == ItemScope::Class
|
||||
|| !decl.scope.is_empty()
|
||||
|| decl.is_prototype
|
||||
|| decl.dpi.is_some()
|
||||
{
|
||||
return;
|
||||
}
|
||||
if decl.qualifiers.iter().any(|q| LIFETIMES.contains(&q.text.as_str())) {
|
||||
return;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!(
|
||||
"function `{}` has no explicit lifetime; write `automatic` or `static`",
|
||||
decl.name
|
||||
),
|
||||
decl.name_span,
|
||||
));
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
ExplicitFunctionLifetime.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_module_function_and_points_at_its_name() {
|
||||
let src = "module m;\n function int f(int x);\n return x;\n endfunction\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "f");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn either_keyword_satisfies_the_rule() {
|
||||
for kw in ["automatic", "static"] {
|
||||
let src = format!(
|
||||
"module m;\n function {kw} int f(int x);\n return x;\n endfunction\nendmodule\n"
|
||||
);
|
||||
assert!(violations(&src).is_empty(), "{kw}: {:?}", violations(&src));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_class_method_is_exempt() {
|
||||
let src = "class c;\n function int f(int x);\n return x;\n endfunction\nendclass\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_or_file_scope_function_is_judged() {
|
||||
let pkg = "package p;\n function int f();\n return 0;\n endfunction\nendpackage\n";
|
||||
assert_eq!(violations(pkg).len(), 1);
|
||||
let top = "function int f();\n return 0;\nendfunction\n";
|
||||
assert_eq!(violations(top).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prototype_declares_no_locals() {
|
||||
let src = "class c;\n extern function int f();\nendclass\n\
|
||||
import \"DPI-C\" function int c_f(input int x);\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
/// An `extern` method defined outside its class body is still a class
|
||||
/// method; Verible reports it, lucisv does not (see the rule's doc).
|
||||
#[test]
|
||||
fn an_out_of_body_definition_is_a_class_method() {
|
||||
let src = "class c;\n extern function int f();\nendclass\n\
|
||||
function c::f();\n return 0;\nendfunction\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_class_nested_in_a_package_is_still_a_class() {
|
||||
let src = "package p;\n class c;\n function int f();\n return 0;\n \
|
||||
endfunction\n endclass\nendpackage\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
//! `explicit-task-lifetime` — say `automatic` or `static` outside a class.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::rules::explicit_function_lifetime::LIFETIMES;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::{walk_items_scoped, ItemScope};
|
||||
use vlog_parser::ast::ItemKind;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct ExplicitTaskLifetime;
|
||||
|
||||
const NAME: &str = "explicit-task-lifetime";
|
||||
|
||||
impl Rule for ExplicitTaskLifetime {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"state `automatic` or `static` on a task declared outside a class"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"The same argument `explicit-function-lifetime` makes, and worse: a \
|
||||
task can block, so a `static` one is routinely called from two \
|
||||
processes at once and its locals are one set of variables shared \
|
||||
between them (IEEE 1800 §13.4.2). A task with no stated lifetime is \
|
||||
`static` in a module and `automatic` in a class, and nothing in the \
|
||||
source says which the author meant. Verible's \
|
||||
`explicit-task-lifetime` (\"Checks that every task declared outside \
|
||||
of a class is declared with an explicit lifetime.\", enabled by \
|
||||
default) is the same rule and the same default.\n\n\
|
||||
A body-less prototype, a DPI import and an out-of-body definition \
|
||||
(`task cls::t(); … endtask`) are not judged, and no automatic fix is \
|
||||
offered — all for the reasons `explicit-function-lifetime` gives."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_items_scoped(ctx.file(), &mut |scope, item| {
|
||||
let ItemKind::Task(decl) = &item.kind else { return };
|
||||
// An out-of-body definition (`function cls::f(...)`) is a class
|
||||
// method written outside the class body; `scope` is non-empty for
|
||||
// exactly those.
|
||||
if scope == ItemScope::Class
|
||||
|| !decl.scope.is_empty()
|
||||
|| decl.is_prototype
|
||||
|| decl.dpi.is_some()
|
||||
{
|
||||
return;
|
||||
}
|
||||
if decl.qualifiers.iter().any(|q| LIFETIMES.contains(&q.text.as_str())) {
|
||||
return;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!(
|
||||
"task `{}` has no explicit lifetime; write `automatic` or `static`",
|
||||
decl.name
|
||||
),
|
||||
decl.name_span,
|
||||
));
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
ExplicitTaskLifetime.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_module_task_and_points_at_its_name() {
|
||||
let src = "module m;\n task t();\n endtask\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "t");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn either_keyword_satisfies_the_rule() {
|
||||
for kw in ["automatic", "static"] {
|
||||
let src = format!("module m;\n task {kw} t();\n endtask\nendmodule\n");
|
||||
assert!(violations(&src).is_empty(), "{kw}: {:?}", violations(&src));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_class_method_is_exempt() {
|
||||
assert!(violations("class c;\n task t();\n endtask\nendclass\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_function_is_the_other_rules_business() {
|
||||
let src = "module m;\n function int f();\n return 0;\n endfunction\nendmodule\n";
|
||||
assert!(violations(src).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prototype_declares_no_locals() {
|
||||
assert!(violations("class c;\n extern task t();\nendclass\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_out_of_body_definition_is_a_class_method() {
|
||||
let src = "class c;\n extern task t();\nendclass\ntask c::t();\nendtask\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! `forbid-line-continuations` — no `\` breaking a string literal.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::TokenKind;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct ForbidLineContinuations;
|
||||
|
||||
const NAME: &str = "forbid-line-continuations";
|
||||
|
||||
impl Rule for ForbidLineContinuations {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"do not break a string literal across lines with a backslash continuation"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A string broken with a backslash at end of line keeps every character \
|
||||
of the next line, its leading indentation included — so re-indenting \
|
||||
the file changes the string's *value*, and a formatter, a rebase or \
|
||||
a careless editor silently alters what the design prints. It is also \
|
||||
invisible: the second line looks like code. The portable spelling is \
|
||||
string concatenation, `{\"first \", \"second\"}`, which the compiler \
|
||||
folds and nothing can re-indent. Verible's \
|
||||
`forbid-line-continuations` (\"Checks that there are no occurrences \
|
||||
of `\\` when breaking string literal lines.\", enabled by default) is \
|
||||
the same rule and the same default.\n\n\
|
||||
Only a continuation *inside a string literal* is judged: a `` `define \
|
||||
`` body written across lines with a `\\` is the only way the language \
|
||||
gives to write a multi-line macro, and this rule says nothing about \
|
||||
it. No automatic fix — replacing the continuation with a \
|
||||
concatenation has to decide where the whitespace of the second line \
|
||||
belongs, and only the author knows."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
for token in ctx.tokens().iter().filter(|t| t.kind == TokenKind::String) {
|
||||
for offset in continuations(&token.text) {
|
||||
let start = token.span.start + offset as u32;
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
"string literal is broken with a `\\` line continuation; write \
|
||||
`{\"...\", \"...\"}` instead",
|
||||
TextRange::new(start, start + 1),
|
||||
));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Byte offsets of every backslash that continues `text` onto the next line.
|
||||
///
|
||||
/// A `\\` is an escaped backslash and continues nothing, so the scan steps
|
||||
/// over both characters — otherwise `"a\\\\\n"` would be read as a
|
||||
/// continuation of its own escape.
|
||||
fn continuations(text: &str) -> Vec<usize> {
|
||||
let bytes = text.as_bytes();
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0usize;
|
||||
while i + 1 < bytes.len() {
|
||||
if bytes[i] != b'\\' {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
match bytes[i + 1] {
|
||||
b'\n' => out.push(i),
|
||||
// `\r\n` counts too: the file's line endings are not the point.
|
||||
b'\r' if bytes.get(i + 2) == Some(&b'\n') => out.push(i),
|
||||
_ => {}
|
||||
}
|
||||
i += 2;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
ForbidLineContinuations.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_the_backslash_that_breaks_a_string() {
|
||||
let src = "module m;\n initial $display(\"a long \\\n string\");\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "\\");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_one_line_string_is_clean() {
|
||||
let src = "module m;\n initial $display(\"a long string\");\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ordinary_escape_is_not_a_continuation() {
|
||||
let src = "module m;\n initial $display(\"tab\\t quote\\\" slash\\\\ end\");\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_line_define_is_not_a_string() {
|
||||
let src = "`define TWO_LINES \\\n wire a; \\\n wire b;\nmodule m;\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_break_of_one_string_is_reported() {
|
||||
let src = "module m;\n initial $display(\"a \\\n b \\\n c\");\nendmodule\n";
|
||||
assert_eq!(violations(src).len(), 2, "{:?}", violations(src));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//! `forbidden-macro` — macros a project has decided nothing should call.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::options::{OptionDefault, OptionKind, OptionSpec};
|
||||
use crate::preproc::macro_name;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct ForbiddenMacro;
|
||||
|
||||
const NAME: &str = "forbidden-macro";
|
||||
|
||||
/// The one option, spelled as this rule's own since Verible's list is a
|
||||
/// compile-time constant with no parameter to change it.
|
||||
const OPTIONS: &[OptionSpec] = &[OptionSpec {
|
||||
name: "macros",
|
||||
kind: OptionKind::List,
|
||||
// Verible's own list, name for name: `uvm_warning` and nothing else.
|
||||
default: OptionDefault::List(&["uvm_warning"]),
|
||||
doc: "macro names nothing may invoke, with or without the leading backtick",
|
||||
}];
|
||||
|
||||
impl Rule for ForbiddenMacro {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"do not invoke a forbidden macro"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn options(&self) -> &'static [OptionSpec] {
|
||||
OPTIONS
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"Verible's `forbidden-macro` (\"Checks that no forbidden macro calls \
|
||||
are used.\", enabled by default) ships one name: `` `uvm_warning ``. \
|
||||
A UVM warning is a message nothing acts on — the test keeps running, \
|
||||
the regression stays green, and the condition that produced it is \
|
||||
rediscovered later by somebody reading a log. The UVM style guides \
|
||||
that ban it want the choice made at the point of failure: \
|
||||
`` `uvm_error `` if the test should fail, `` `uvm_info `` if it \
|
||||
really is only information.\n\n\
|
||||
Verible hard-codes its list; lucisv makes it the `macros` option, so \
|
||||
a project that has banned `` `uvm_fatal `` or a macro of its own \
|
||||
writes them down instead of asking for a new rule. An entry may be \
|
||||
written with or without its backtick — `\"uvm_warning\"` and \
|
||||
`` \"`uvm_warning\"`` name the same macro. An empty list turns the \
|
||||
rule off as surely as `--ignore` does. No automatic fix: which \
|
||||
replacement is right is exactly the judgment the rule is asking for."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let forbidden: Vec<String> = ctx
|
||||
.option_list(NAME, "macros")
|
||||
.iter()
|
||||
.map(|entry| entry.trim_start_matches('`').to_string())
|
||||
.collect();
|
||||
if forbidden.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
ctx.tokens()
|
||||
.iter()
|
||||
.filter_map(|token| {
|
||||
let name = macro_name(token)?;
|
||||
if !forbidden.iter().any(|entry| entry == name) {
|
||||
return None;
|
||||
}
|
||||
// The backtick and the name, not the arguments after them.
|
||||
let end = token.span.start + 1 + name.len() as u32;
|
||||
Some(Violation::new(
|
||||
NAME,
|
||||
format!("`` `{name} `` is a forbidden macro"),
|
||||
TextRange::new(token.span.start, end),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::options::RuleOptions;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
ForbiddenMacro.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn with(src: &str, raw: &str) -> Vec<Violation> {
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw(NAME, "macros", raw).expect("accepted");
|
||||
ForbiddenMacro.check(&LintContext::new(src, None).with_options(&options))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_the_default_name_and_underlines_the_invocation() {
|
||||
let src = "module m;\n initial `uvm_warning(\"A\", \"B\");\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "`uvm_warning");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_neighbouring_uvm_macros_are_left_alone() {
|
||||
let src = "module m;\n\
|
||||
\x20 initial begin\n\
|
||||
\x20 `uvm_info(\"A\", \"B\", UVM_LOW)\n\
|
||||
\x20 `uvm_error(\"A\", \"B\")\n\
|
||||
\x20 `uvm_fatal(\"A\", \"B\")\n\
|
||||
\x20 end\n\
|
||||
endmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_that_only_starts_the_same_is_not_a_hit() {
|
||||
let src = "module m;\n initial `uvm_warning_once(\"A\");\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_identifier_or_a_string_with_the_name_in_it_is_not_an_invocation() {
|
||||
let src = "module m;\n wire uvm_warning;\n initial $display(\"`uvm_warning\");\n\
|
||||
endmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_option_replaces_the_list_and_accepts_either_spelling() {
|
||||
let src = "module m;\n initial begin\n `uvm_warning(\"A\", \"B\")\n \
|
||||
`my_macro(1)\n end\nendmodule\n";
|
||||
assert_eq!(with(src, "[\"my_macro\"]").len(), 1);
|
||||
assert_eq!(with(src, "[\"`my_macro\"]").len(), 1);
|
||||
assert_eq!(with(src, "[\"uvm_warning\", \"my_macro\"]").len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_list_reports_nothing() {
|
||||
let src = "module m;\n initial `uvm_warning(\"A\", \"B\");\nendmodule\n";
|
||||
assert!(with(src, "[]").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! `invalid-system-task-function` — system tasks nothing should still call.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::options::{OptionDefault, OptionKind, OptionSpec};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
@@ -11,6 +12,26 @@ pub struct InvalidSystemTaskFunction;
|
||||
|
||||
const NAME: &str = "invalid-system-task-function";
|
||||
|
||||
/// The list, as an option — Verible hard-codes it in the source file it calls
|
||||
/// `forbidden-symbol`, which is this rule under its implementation's name.
|
||||
const OPTIONS: &[OptionSpec] = &[OptionSpec {
|
||||
name: "symbols",
|
||||
kind: OptionKind::List,
|
||||
default: OptionDefault::List(&[
|
||||
"$psprintf",
|
||||
"$random",
|
||||
"$srandom",
|
||||
"$dist_chi_square",
|
||||
"$dist_erlang",
|
||||
"$dist_exponential",
|
||||
"$dist_normal",
|
||||
"$dist_poisson",
|
||||
"$dist_t",
|
||||
"$dist_uniform",
|
||||
]),
|
||||
doc: "system task and function names nothing may call, `$` included",
|
||||
}];
|
||||
|
||||
/// The forbidden names and what to write instead — Verible's list
|
||||
/// (`invalid-system-task-function`), name for name.
|
||||
///
|
||||
@@ -46,6 +67,10 @@ impl Rule for InvalidSystemTaskFunction {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn options(&self) -> &'static [OptionSpec] {
|
||||
OPTIONS
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"`$random`, `$srandom` and the `$dist_*` family all draw from one \
|
||||
global generator, so adding a call anywhere in a testbench reshuffles \
|
||||
@@ -55,23 +80,32 @@ impl Rule for InvalidSystemTaskFunction {
|
||||
vendor spelling of the standard `$sformatf` and is not portable. \
|
||||
Verible's `invalid-system-task-function` (\"Checks that no forbidden \
|
||||
system tasks or functions are used.\", enabled by default) forbids \
|
||||
exactly this list, and lucisv names the replacement in the message. \
|
||||
exactly this list, and lucisv names the replacement in the message.\n\n\
|
||||
**There is no separate `forbidden-symbol` rule**, here or in Verible: \
|
||||
`forbidden-symbol` is the name of the *source file* Verible \
|
||||
implements this rule in, and the rule it registers is this one. The \
|
||||
list Verible hard-codes there is lucisv's `symbols` option, so a \
|
||||
project that wants `$stop` or a vendor task on it writes it down \
|
||||
instead of getting a second rule that would fire twice on \
|
||||
`$psprintf`. A name the default list knows is reported with its \
|
||||
replacement; one a project adds is reported without, because only \
|
||||
the project knows what to use instead.\n\n\
|
||||
No automatic fix: `$random` and `$urandom` return different value \
|
||||
streams, so swapping them changes what the test does."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let forbidden = ctx.option_list(NAME, "symbols");
|
||||
ctx.tokens()
|
||||
.iter()
|
||||
.filter(|token| token.kind == TokenKind::SystemIdent)
|
||||
.filter_map(|token| {
|
||||
let (name, instead) =
|
||||
FORBIDDEN.iter().find(|(name, _)| *name == token.text.as_str())?;
|
||||
Some(Violation::new(
|
||||
NAME,
|
||||
format!("`{name}` is forbidden; use `{instead}`"),
|
||||
token.span,
|
||||
))
|
||||
let name = forbidden.iter().find(|name| *name == &token.text)?;
|
||||
let message = match FORBIDDEN.iter().find(|(known, _)| known == name) {
|
||||
Some((_, instead)) => format!("`{name}` is forbidden; use `{instead}`"),
|
||||
None => format!("`{name}` is forbidden by this project's settings"),
|
||||
};
|
||||
Some(Violation::new(NAME, message, token.span))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -129,4 +163,36 @@ mod tests {
|
||||
let src = "module m;\n initial $display(\"call $random here\");\nendmodule\n";
|
||||
assert!(violations(src).is_empty());
|
||||
}
|
||||
|
||||
/// The `symbols` option is `forbidden-symbol`'s list, folded into the one
|
||||
/// rule Verible actually registers.
|
||||
#[test]
|
||||
fn the_option_replaces_the_list() {
|
||||
use crate::options::RuleOptions;
|
||||
let src = "module m;\n initial begin\n a = $random();\n $stop;\n end\nendmodule\n";
|
||||
assert_eq!(violations(src).len(), 1, "the default list has `$random` and not `$stop`");
|
||||
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw(NAME, "symbols", "[\"$stop\"]").expect("accepted");
|
||||
let found =
|
||||
InvalidSystemTaskFunction.check(&LintContext::new(src, None).with_options(&options));
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("$stop"), "{}", found[0].message);
|
||||
assert!(
|
||||
found[0].message.contains("this project's settings"),
|
||||
"a name with no known replacement says so: {}",
|
||||
found[0].message
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_list_reports_nothing() {
|
||||
use crate::options::RuleOptions;
|
||||
let src = "module m;\n initial a = $random();\nendmodule\n";
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw(NAME, "symbols", "[]").expect("accepted");
|
||||
assert!(InvalidSystemTaskFunction
|
||||
.check(&LintContext::new(src, None).with_options(&options))
|
||||
.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//! `legacy-generate-region` — the `generate … endgenerate` wrapper.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_items;
|
||||
use vlog_parser::ast::ItemKind;
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct LegacyGenerateRegion;
|
||||
|
||||
const NAME: &str = "legacy-generate-region";
|
||||
|
||||
impl Rule for LegacyGenerateRegion {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"write generate constructs without a `generate … endgenerate` region"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn default_on(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"Verilog-2001 required generate constructs to sit inside a \
|
||||
`generate … endgenerate` region. SystemVerilog does not (IEEE 1800 \
|
||||
§27.3): an `if`, `for` or `case` generate is a module item like any \
|
||||
other, and the wrapper adds a level of indentation, a keyword pair to \
|
||||
match and nothing else. Verible's `legacy-generate-region` (\"Checks \
|
||||
that there are no generate regions.\", **disabled** by default) is \
|
||||
the same rule and lucisv ships it off for the same reason: a codebase \
|
||||
that must still compile as Verilog-2001 needs the region, and only \
|
||||
the project knows which one it is.\n\n\
|
||||
No automatic fix. Deleting the two keywords is a whole-region edit \
|
||||
that re-indents everything between them, which is the formatter's \
|
||||
job and not a lint fix's."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_items(ctx.file(), &mut |item| {
|
||||
if !matches!(item.kind, ItemKind::GenerateRegion { .. }) {
|
||||
return;
|
||||
}
|
||||
// Point at the `generate` keyword, which is where the region opens.
|
||||
let kw = TextRange::new(item.span.start, item.span.start + 8);
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
"`generate … endgenerate` region is not needed in SystemVerilog",
|
||||
kw,
|
||||
));
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
LegacyGenerateRegion.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_region_and_points_at_its_keyword() {
|
||||
let src = "module m;\n generate\n if (A) begin : g\n wire a;\n end\n \
|
||||
endgenerate\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "generate");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generate_construct_without_the_wrapper_is_what_the_rule_wants() {
|
||||
let src = "module m;\n if (A) begin : g\n wire a;\n end\n\
|
||||
\x20 for (genvar i = 0; i < 2; i++) begin : l\n wire b;\n end\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_region_of_a_file_is_reported() {
|
||||
let src = "module a;\n generate\n endgenerate\nendmodule\n\
|
||||
module b;\n generate\n endgenerate\nendmodule\n";
|
||||
assert_eq!(violations(src).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nested_region_is_reported_too() {
|
||||
let src = "module m;\n generate\n if (A) begin : g\n generate\n \
|
||||
endgenerate\n end\n endgenerate\nendmodule\n";
|
||||
assert_eq!(violations(src).len(), 2, "{:?}", violations(src));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
//! `legacy-genvar-declaration` — declare the loop variable in the `for` header.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_items;
|
||||
use vlog_parser::ast::ItemKind;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct LegacyGenvarDeclaration;
|
||||
|
||||
const NAME: &str = "legacy-genvar-declaration";
|
||||
|
||||
impl Rule for LegacyGenvarDeclaration {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"declare a genvar in the `for` header, not in a separate statement"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn default_on(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"Verilog-2001 made a `genvar` a module-scope declaration, so a loop \
|
||||
variable outlived the loop that used it and two loops sharing one \
|
||||
`genvar i;` read as if they shared a variable. SystemVerilog lets the \
|
||||
header declare it — `for (genvar i = 0; i < N; i++)` — which scopes \
|
||||
the name to the loop and makes each loop's variable its own (IEEE \
|
||||
1800 §27.4). Verible's `legacy-genvar-declaration` (\"Checks that \
|
||||
there are no separate `genvar` declarations.\", **disabled** by \
|
||||
default) is the same rule, and lucisv ships it off for the same \
|
||||
reason: a Verilog-2001 codebase has no other spelling available.\n\n\
|
||||
No automatic fix: moving the declaration means editing every `for` \
|
||||
header that used it, and only the author knows which ones those are."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_items(ctx.file(), &mut |item| {
|
||||
let ItemKind::Genvar(names) = &item.kind else { return };
|
||||
for name in names {
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!(
|
||||
"genvar `{}` is declared outside a `for` header; write \
|
||||
`for (genvar {} = …)`",
|
||||
name.text, name.text
|
||||
),
|
||||
name.span,
|
||||
));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
LegacyGenvarDeclaration.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_separate_declaration_and_points_at_the_name() {
|
||||
let src = "module m;\n genvar i;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "i");
|
||||
assert!(found[0].message.contains("`i`"), "{}", found[0].message);
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_name_of_one_declaration_is_reported() {
|
||||
assert_eq!(violations("module m;\n genvar i, j, k;\nendmodule\n").len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_declaration_is_what_the_rule_wants() {
|
||||
let src = "module m;\n for (genvar i = 0; i < 2; i++) begin : g\n wire a;\n end\n\
|
||||
endmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ordinary_variable_is_not_a_genvar() {
|
||||
assert!(violations("module m;\n integer i;\n int j;\nendmodule\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declaration_inside_a_generate_region_is_reached() {
|
||||
let src = "module m;\n generate\n genvar i;\n endgenerate\nendmodule\n";
|
||||
assert_eq!(violations(src).len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
//! `macro-string-concatenation` — `` `` `` inside a plain string does nothing.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::preproc::directive_word;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct MacroStringConcatenation;
|
||||
|
||||
const NAME: &str = "macro-string-concatenation";
|
||||
|
||||
impl Rule for MacroStringConcatenation {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"do not write the `` `` `` concatenation operator inside a plain string"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn default_on(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"Inside a `` `define `` body, `` `` `` glues two tokens together and \
|
||||
`` `\" `` opens a string the preprocessor still looks inside \
|
||||
(IEEE 1800 §22.5.1). Written inside an *ordinary* `\"…\"` string the \
|
||||
operator is not an operator at all — the preprocessor does not \
|
||||
expand anything in a plain string literal, so the two backticks end \
|
||||
up in the output text and the macro silently produces `` a``b `` \
|
||||
where the author expected `ab`. Verible's \
|
||||
`macro-string-concatenation` (\"Concatenation will not be evaluated \
|
||||
here. Use `\\\"...`\\\" instead.\", **disabled** by default) reports \
|
||||
the same shape, and lucisv ships it off for the same reason: it is a \
|
||||
narrow mistake, and a project with no macro-built strings never meets \
|
||||
it.\n\n\
|
||||
Only a `` `define `` body is scanned, and only its plain string \
|
||||
literals — a `` `\"…`\" `` region is exactly the correct spelling and \
|
||||
is skipped. No automatic fix: turning `\"…\"` into `` `\"…`\" `` \
|
||||
changes what the macro expands to, which is the repair but not one a \
|
||||
linter should make unasked."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
for token in ctx.tokens() {
|
||||
if directive_word(token) != Some("define") {
|
||||
continue;
|
||||
}
|
||||
for offset in concatenations_in_plain_strings(&token.text) {
|
||||
let start = token.span.start + offset as u32;
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
"token concatenation inside a plain string literal is not evaluated; \
|
||||
write the string as `\"...`\"",
|
||||
TextRange::new(start, start + 2),
|
||||
));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Byte offsets of every `` `` `` written inside a plain `"…"` literal of
|
||||
/// `text`, in source order.
|
||||
///
|
||||
/// A `` `"…`" `` region — the spelling that *does* work — is skipped whole,
|
||||
/// which is what keeps the correct form from being reported as the mistake.
|
||||
fn concatenations_in_plain_strings(text: &str) -> Vec<usize> {
|
||||
let bytes = text.as_bytes();
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0usize;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'`' && bytes.get(i + 1) == Some(&b'"') {
|
||||
i = match find(bytes, i + 2, b"`\"") {
|
||||
Some(end) => end + 2,
|
||||
None => break,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
if bytes[i] != b'"' {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let mut j = i + 1;
|
||||
while j < bytes.len() && bytes[j] != b'"' {
|
||||
if bytes[j] == b'\\' {
|
||||
j += 1;
|
||||
}
|
||||
if bytes.get(j) == Some(&b'`') && bytes.get(j + 1) == Some(&b'`') {
|
||||
out.push(j);
|
||||
j += 1;
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
i = j + 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The offset of the next `needle` at or after `from`.
|
||||
fn find(bytes: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
|
||||
(from..bytes.len().saturating_sub(needle.len() - 1))
|
||||
.find(|&i| &bytes[i..i + needle.len()] == needle)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
MacroStringConcatenation.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_the_operator_and_underlines_it() {
|
||||
let src = "`define GLUE(a, b) $display(\"a``b\")\nmodule m;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "``");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_macro_quoted_spelling_is_the_correct_one() {
|
||||
let src = "`define GLUE(a, b) $display(`\"a``b`\")\nmodule m;\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_define_with_no_string_is_silent() {
|
||||
let src = "`define GLUE(a, b) a``b\nmodule m;\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_string_outside_a_define_is_not_this_rules_business() {
|
||||
let src = "module m;\n initial $display(\"a``b\");\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_occurrence_of_one_define_is_reported() {
|
||||
let src = "`define G(a, b, c) $display(\"a``b\", \"b``c\")\nmodule m;\nendmodule\n";
|
||||
assert_eq!(violations(src).len(), 2, "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escaped_quote_does_not_end_the_string_early() {
|
||||
let src = "`define G(a) $display(\"x\\\"y``z\")\nmodule m;\nendmodule\n";
|
||||
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
|
||||
}
|
||||
}
|
||||
@@ -141,6 +141,9 @@ fn item_labels(out: &mut Vec<Violation>, item: &Item) {
|
||||
}
|
||||
}
|
||||
ItemKind::GenFor(gen_for) => check_gen_block(out, &gen_for.body),
|
||||
// A bare `begin … end` standing as an item (§36.1) is the same node
|
||||
// without a header: its label pair is checked exactly like an arm's.
|
||||
ItemKind::GenBlock(block) => check_gen_block(out, block),
|
||||
ItemKind::GenCase(gen_case) => {
|
||||
for case_item in &gen_case.items {
|
||||
check_gen_block(out, &case_item.body);
|
||||
@@ -285,6 +288,23 @@ mod tests {
|
||||
assert_eq!(violations(generate).len(), 1, "{:?}", violations(generate));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_block_at_module_scope_is_checked_like_a_generate_arm() {
|
||||
// §36.1: the block is a node now, so its own footer is checked. Not
|
||||
// legal at module scope at all (`module-begin-block` says so), but a
|
||||
// mismatched footer is the compile error this rule exists for.
|
||||
let src = "module m;\n\
|
||||
begin : fetch\n\
|
||||
wire a;\n\
|
||||
end : decode\n\
|
||||
endmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "decode");
|
||||
let ok = "module m;\n begin : fetch\n wire a;\n end : fetch\nendmodule\n";
|
||||
assert!(violations(ok).is_empty(), "{:?}", violations(ok));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nested_block_is_matched_against_its_own_header() {
|
||||
let src = "module m;\n\
|
||||
|
||||
@@ -13,24 +13,36 @@ pub mod always_ff_non_blocking;
|
||||
pub mod banned_declared_name_patterns;
|
||||
pub mod case_missing_default;
|
||||
pub mod constraint_name_style;
|
||||
pub mod create_object_name_match;
|
||||
pub mod dff_name_style;
|
||||
pub mod disable_statement;
|
||||
pub mod duplicate_declaration;
|
||||
pub mod empty_item;
|
||||
pub mod endif_comment;
|
||||
pub mod enum_name_style;
|
||||
pub mod explicit_begin;
|
||||
pub mod explicit_function_lifetime;
|
||||
pub mod explicit_function_task_parameter_type;
|
||||
pub mod explicit_parameter_storage_type;
|
||||
pub mod explicit_task_lifetime;
|
||||
pub mod forbid_consecutive_null_statements;
|
||||
pub mod forbid_defparam;
|
||||
pub mod forbid_line_continuations;
|
||||
pub mod forbid_negative_array_dim;
|
||||
pub mod forbidden_macro;
|
||||
pub mod generate_label;
|
||||
pub mod generate_label_prefix;
|
||||
pub mod incomplete_assignment;
|
||||
pub mod instance_shadowing;
|
||||
pub mod interface_name_style;
|
||||
pub mod invalid_system_task_function;
|
||||
pub mod legacy_generate_region;
|
||||
pub mod legacy_genvar_declaration;
|
||||
pub mod line_length;
|
||||
pub mod macro_name_style;
|
||||
pub mod macro_string_concatenation;
|
||||
pub mod mismatched_labels;
|
||||
pub mod module_begin_block;
|
||||
pub mod module_filename;
|
||||
pub mod module_name_style;
|
||||
pub mod module_parameter;
|
||||
@@ -38,6 +50,7 @@ pub mod module_port;
|
||||
pub mod multiply_driven;
|
||||
pub mod no_tabs;
|
||||
pub mod no_trailing_whitespace;
|
||||
pub mod numeric_format_string_style;
|
||||
pub mod one_module_per_file;
|
||||
pub mod package_filename;
|
||||
pub mod packed_dimensions_range_ordering;
|
||||
@@ -45,9 +58,12 @@ pub mod parameter_name_style;
|
||||
pub mod parameter_type_name_style;
|
||||
pub mod plusarg_assignment;
|
||||
pub mod port_name_suffix;
|
||||
pub mod positive_meaning_parameter_name;
|
||||
pub mod posix_eof;
|
||||
pub mod proper_parameter_declaration;
|
||||
pub mod signal_name_style;
|
||||
pub mod struct_union_name_style;
|
||||
pub mod suggest_parentheses;
|
||||
pub mod suspicious_semicolon;
|
||||
pub mod truncated_numeric_literal;
|
||||
pub mod typedef_enums;
|
||||
@@ -57,7 +73,10 @@ pub mod undersized_binary_literal;
|
||||
pub mod undriven_net;
|
||||
pub mod unknown_parameter;
|
||||
pub mod unknown_port;
|
||||
pub mod unpacked_dimensions_range_ordering;
|
||||
pub mod unused_signal;
|
||||
pub mod unused_waiver;
|
||||
pub mod uvm_macro_semicolon;
|
||||
pub mod v2001_generate_begin;
|
||||
pub mod void_cast;
|
||||
pub mod wire_reg_mixup;
|
||||
@@ -0,0 +1,182 @@
|
||||
//! `module-begin-block` — no `begin`/`end` block at module scope.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::ast::{Item, ItemKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct ModuleBeginBlock;
|
||||
|
||||
const NAME: &str = "module-begin-block";
|
||||
|
||||
impl Rule for ModuleBeginBlock {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"do not write a `begin`/`end` block at module scope"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A `begin … end` written straight into a module body is not a module \
|
||||
item: IEEE 1800 §23.2.1 lists what may stand there, and a sequential \
|
||||
block is not on the list. Tools that accept it treat it as an \
|
||||
unnamed generate block, so the declarations inside it land in an \
|
||||
invented scope (`genblk1.x`) and every hierarchical path written \
|
||||
against them is wrong. Verible's `module-begin-block` (\"Checks that \
|
||||
there are no begin-end blocks declared at the module level.\", \
|
||||
enabled by default) is the same rule and the same default.\n\n\
|
||||
lucisv's parser **recovers** the construct: in error-tolerant mode \
|
||||
the block is read as the unnamed generate block every tool that \
|
||||
accepts it makes of it, and a diagnostic is recorded at the `begin` \
|
||||
— so the file is still reported as not parsing cleanly and the \
|
||||
formatter still refuses to format it, but the items written inside \
|
||||
the block are visible to this rule and to every other one. What this \
|
||||
rule reads is that block standing where a module item belongs. No \
|
||||
automatic fix: whether the block should become a generate block, an \
|
||||
`always` or nothing at all is the author's to decide."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
for item in &ctx.file().items {
|
||||
module_items(item, &mut |inner| {
|
||||
if let Some(span) = begin_block(inner) {
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
"`begin`/`end` block at module scope; a module item belongs here",
|
||||
span,
|
||||
));
|
||||
}
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The `begin` keyword of an item that is a bare `begin … end` block, or
|
||||
/// `None` for any other item.
|
||||
///
|
||||
/// Shared with `v2001-generate-begin`, which asks the same question one scope
|
||||
/// further in: the two rules must agree about what a stray `begin` looks like,
|
||||
/// and one reading is how that is guaranteed.
|
||||
pub(crate) fn begin_block(item: &Item) -> Option<TextRange> {
|
||||
let ItemKind::GenBlock(block) = &item.kind else { return None };
|
||||
// The node's span opens at the keyword, whatever the item's own span does
|
||||
// with the attributes written in front of it.
|
||||
Some(TextRange::new(block.span.start, block.span.start + 5))
|
||||
}
|
||||
|
||||
/// Calls `f` on every item written directly in a module, interface or program
|
||||
/// body — nested units included, generate constructs deliberately not, since
|
||||
/// a `begin` inside one of those is `v2001-generate-begin`'s business.
|
||||
fn module_items(item: &Item, f: &mut dyn FnMut(&Item)) {
|
||||
match &item.kind {
|
||||
ItemKind::Module(module) => {
|
||||
for inner in &module.items {
|
||||
f(inner);
|
||||
module_items(inner, f);
|
||||
}
|
||||
}
|
||||
ItemKind::Package { items, .. } => {
|
||||
for inner in items {
|
||||
module_items(inner, f);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `file` holds a module at all — used by the tests below only.
|
||||
#[cfg(test)]
|
||||
fn has_module(file: &vlog_parser::ast::SourceFile) -> bool {
|
||||
file.items.iter().any(|item| matches!(item.kind, ItemKind::Module(_)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
ModuleBeginBlock.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_module_scope_block_and_points_at_its_begin() {
|
||||
let src = "module m;\n begin\n wire a;\n end\nendmodule\n";
|
||||
let ctx = LintContext::new(src, None);
|
||||
assert!(has_module(ctx.file()), "the probe needs the module to survive recovery");
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "begin");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ordinary_module_body_is_silent() {
|
||||
let src = "module m;\n\
|
||||
\x20 wire a;\n\
|
||||
\x20 initial begin\n a = 1;\n end\n\
|
||||
\x20 always_comb begin\n b = a;\n end\n\
|
||||
\x20 if (A) begin : g\n wire c;\n end\n\
|
||||
endmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_inside_a_generate_region_belongs_to_the_other_rule() {
|
||||
let src = "module m;\n generate\n begin : b\n wire a;\n end\n \
|
||||
endgenerate\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_identifier_that_starts_with_begin_is_not_the_keyword() {
|
||||
// The error leaf of an unparsable item starting with `beginning` must
|
||||
// not be read as a block.
|
||||
let src = "module m;\n beginning @@@;\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_block_keeps_its_items_and_the_module_keeps_the_items_after_it() {
|
||||
// §36.1: the block is a node now, not an error leaf, so what is
|
||||
// written inside it and after it is still there for every rule.
|
||||
// Before, recovery skipped to `endmodule` and the `defparam` was
|
||||
// inside one opaque leaf.
|
||||
let src = "module m;\n begin\n defparam u.P = 1;\n end\n wire a;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "begin");
|
||||
let ctx = LintContext::new(src, None);
|
||||
let inside = crate::rules::forbid_defparam::ForbidDefparam.check(&ctx);
|
||||
assert_eq!(inside.len(), 1, "a rule reading the block's items: {inside:?}");
|
||||
assert_eq!(ctx.file().items.len(), 1, "one module");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_outermost_block_of_a_nest_is_reported_at_module_scope() {
|
||||
// The inner block is written inside a block, not at module scope, so
|
||||
// it is not this rule's finding — exactly as before §36.1, when the
|
||||
// whole nest was one leaf whose first token was the outer `begin`.
|
||||
let src = "module m;\n begin\n begin\n wire a;\n end\n end\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(found[0].span.start, 12, "the outer `begin`");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_parses_cleanly_has_nothing_to_report() {
|
||||
let src = "module m;\n wire a;\nendmodule\n";
|
||||
assert!(LintContext::new(src, None).parsed_cleanly());
|
||||
assert!(violations(src).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
//! `numeric-format-string-style` — a radix prefix must match its specifier.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::TokenKind;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct NumericFormatStringStyle;
|
||||
|
||||
const NAME: &str = "numeric-format-string-style";
|
||||
|
||||
/// The base a prefix or a format specifier names.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Radix {
|
||||
Binary,
|
||||
Hex,
|
||||
Decimal,
|
||||
}
|
||||
|
||||
impl Radix {
|
||||
/// The base this letter names, or `None` for a letter that names none.
|
||||
fn of(letter: char) -> Option<Radix> {
|
||||
match letter {
|
||||
'b' | 'B' => Some(Radix::Binary),
|
||||
'h' | 'H' | 'x' | 'X' => Some(Radix::Hex),
|
||||
'd' | 'D' => Some(Radix::Decimal),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The word a message calls this base.
|
||||
fn word(self) -> &'static str {
|
||||
match self {
|
||||
Radix::Binary => "binary",
|
||||
Radix::Hex => "hexadecimal",
|
||||
Radix::Decimal => "decimal",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Rule for NumericFormatStringStyle {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"give a numeric format specifier the radix prefix that matches it"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn default_on(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A log line that prints `addr = 0x1010` when the value was formatted \
|
||||
with `%b` has told the reader a lie that costs an hour: they read the \
|
||||
number in the base the prefix claims. The convention is to write the \
|
||||
prefix that matches — `0x%0h`, `'b%0b` — or to write no prefix at \
|
||||
all, and to give a decimal number none, because `0d` is not a prefix \
|
||||
anyone reads. Verible's `numeric-format-string-style` (\"Checks that \
|
||||
string literals with numeric format specifiers have proper \
|
||||
prefixes.\", **disabled** by default) reports exactly the mismatch, \
|
||||
and lucisv ships it off for the same reason: it is a house \
|
||||
convention, not a defect.\n\n\
|
||||
A specifier with **no prefix is always accepted** — `\"%0h\"` and \
|
||||
`\"%d\"` are clean. What is reported is a `0`- or `'`-introduced \
|
||||
radix prefix immediately before the `%` that names a different base \
|
||||
(`\"0x%0b\"`, `\"'b%0d\"`), and any prefix at all before a decimal \
|
||||
specifier (`\"0d%0d\"`). Only real string literals are scanned: a \
|
||||
string written inside a macro invocation is part of that \
|
||||
invocation's one token and is not seen here. No automatic fix — \
|
||||
which half is wrong, the prefix or the specifier, is the author's to \
|
||||
say."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
for token in ctx.tokens().iter().filter(|t| t.kind == TokenKind::String) {
|
||||
for bad in mismatches(&token.text) {
|
||||
let start = token.span.start + bad.start as u32;
|
||||
let end = token.span.start + bad.end as u32;
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!(
|
||||
"`{}` prints a {} value after a {} prefix",
|
||||
bad.text,
|
||||
bad.specifier.word(),
|
||||
match bad.prefix {
|
||||
Some(prefix) => prefix.word(),
|
||||
None => "radix",
|
||||
}
|
||||
),
|
||||
TextRange::new(start, end),
|
||||
));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// One badly prefixed specifier: where it is, what it says, and what the
|
||||
/// prefix in front of it claimed.
|
||||
struct Mismatch {
|
||||
start: usize,
|
||||
end: usize,
|
||||
text: String,
|
||||
prefix: Option<Radix>,
|
||||
specifier: Radix,
|
||||
}
|
||||
|
||||
/// Every prefix/specifier mismatch of one string literal, in source order.
|
||||
fn mismatches(text: &str) -> Vec<Mismatch> {
|
||||
let bytes = text.as_bytes();
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0usize;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] != b'%' {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
// `%%` is a literal per cent, not a specifier.
|
||||
if bytes.get(i + 1) == Some(&b'%') {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
let mut j = i + 1;
|
||||
while bytes.get(j).is_some_and(u8::is_ascii_digit) {
|
||||
j += 1;
|
||||
}
|
||||
let Some(specifier) = bytes.get(j).map(|&b| b as char).and_then(Radix::of) else {
|
||||
i = j.max(i + 1);
|
||||
continue;
|
||||
};
|
||||
let prefix = prefix_before(bytes, i);
|
||||
let wrong = match (prefix, specifier) {
|
||||
(Some(_), Radix::Decimal) => true,
|
||||
(Some(prefix), specifier) => prefix != specifier,
|
||||
(None, _) => false,
|
||||
};
|
||||
if wrong {
|
||||
let start = if prefix.is_some() { i - 2 } else { i };
|
||||
out.push(Mismatch {
|
||||
start,
|
||||
end: j + 1,
|
||||
text: text[start..j + 1].to_string(),
|
||||
prefix,
|
||||
specifier,
|
||||
});
|
||||
}
|
||||
i = j + 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The radix a `0x` / `'b`-shaped prefix immediately before `at` claims.
|
||||
fn prefix_before(bytes: &[u8], at: usize) -> Option<Radix> {
|
||||
if at < 2 {
|
||||
return None;
|
||||
}
|
||||
if !matches!(bytes[at - 2], b'0' | b'\'') {
|
||||
return None;
|
||||
}
|
||||
Radix::of(bytes[at - 1] as char)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
NumericFormatStringStyle.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn display(literal: &str) -> String {
|
||||
format!("module m;\n initial $display({literal}, v);\nendmodule\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_mismatched_prefix_and_underlines_prefix_and_specifier() {
|
||||
let src = display("\"0x%0b\"");
|
||||
let found = violations(&src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "0x%0b");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
/// Verible's own accepted list, literal for literal.
|
||||
#[test]
|
||||
fn a_matching_or_absent_prefix_is_accepted() {
|
||||
for literal in [
|
||||
"\"0x%0x\"",
|
||||
"\"'h%0h\"",
|
||||
"\"'h%h\"",
|
||||
"\"0h%h\"",
|
||||
"\"%0x\"",
|
||||
"\"%h\"",
|
||||
"\"%x\"",
|
||||
"\"0b%0b\"",
|
||||
"\"'b%0b\"",
|
||||
"\"%0b\"",
|
||||
"\"%0d\"",
|
||||
"\"0x%0x, %d\"",
|
||||
"\"0x%0x (bin: 'b%b, dec: %d)\"",
|
||||
] {
|
||||
let src = display(literal);
|
||||
assert!(violations(&src).is_empty(), "{literal}: {:?}", violations(&src));
|
||||
}
|
||||
}
|
||||
|
||||
/// Verible's own rejected list, literal for literal.
|
||||
#[test]
|
||||
fn every_mismatch_verible_names_is_reported() {
|
||||
for literal in [
|
||||
"\"0b%0x\"",
|
||||
"\"'b%0x\"",
|
||||
"\"0x%0b\"",
|
||||
"\"'h%0b\"",
|
||||
"\"0x%0d\"",
|
||||
"\"'h%0d\"",
|
||||
"\"0b%0d\"",
|
||||
"\"'b%0d\"",
|
||||
"\"0d%0d\"",
|
||||
"\"'d%0d\"",
|
||||
] {
|
||||
let src = display(literal);
|
||||
assert_eq!(violations(&src).len(), 1, "{literal}: {:?}", violations(&src));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_numeric_specifier_and_a_literal_percent_are_ignored() {
|
||||
for literal in ["\"%s\"", "\"%0t\"", "\"%m\"", "\"100%% done\"", "\"0x%s\""] {
|
||||
let src = display(literal);
|
||||
assert!(violations(&src).is_empty(), "{literal}: {:?}", violations(&src));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_specifier_of_one_string_is_judged_on_its_own() {
|
||||
let src = display("\"0x%0b and 0b%0h and %d\"");
|
||||
assert_eq!(violations(&src).len(), 2, "{:?}", violations(&src));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
//! `positive-meaning-parameter-name` — no `disable`-prefixed parameter.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
|
||||
use vlog_parser::ast::{ItemKind, StmtKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct PositiveMeaningParameterName;
|
||||
|
||||
const NAME: &str = "positive-meaning-parameter-name";
|
||||
|
||||
/// The prefix a parameter must not start with, compared case-insensitively.
|
||||
const FORBIDDEN_PREFIX: &str = "disable";
|
||||
|
||||
impl Rule for PositiveMeaningParameterName {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"name a parameter for what it enables, not for what it disables"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A negatively named parameter forces every use of it to be read \
|
||||
twice: `if (!DisableEcc)` is a double negative, and a default of \
|
||||
`DisableEcc = 0` means \"ECC is on\", which nobody reads correctly at \
|
||||
speed. Naming the positive meaning — `EnableEcc`, `EccEnabled` — \
|
||||
makes each use say what it does. Verible's \
|
||||
`positive-meaning-parameter-name` (\"Checks that no parameter name \
|
||||
starts with 'disable', using positive naming is recommended.\", \
|
||||
enabled by default) is the same rule and the same default; the \
|
||||
comparison is case-insensitive there and here, so `DISABLE_X` and \
|
||||
`disable_x` are both reported.\n\n\
|
||||
Every parameter is judged, in a formal parameter list and in a body \
|
||||
declaration alike, `localparam` included. No automatic fix: \
|
||||
inverting a parameter means inverting every use of it and its \
|
||||
default, which is a refactor, not a repair."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
let mut judge = |name: &str, span: TextRange| {
|
||||
if !starts_with_disable(name) {
|
||||
return;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!(
|
||||
"parameter `{name}` is named for what it disables; name the positive meaning"
|
||||
),
|
||||
span,
|
||||
));
|
||||
};
|
||||
walk_param_ports(ctx.file(), &mut |port| judge(&port.name, port.name_span));
|
||||
walk_items(ctx.file(), &mut |item| {
|
||||
let ItemKind::ParamDecl(decl) = &item.kind else { return };
|
||||
for declarator in &decl.declarators {
|
||||
judge(&declarator.name, declarator.name_span);
|
||||
}
|
||||
});
|
||||
walk_all_stmts(ctx.file(), &mut |stmt| {
|
||||
let StmtKind::ParamDecl(decl) = &stmt.kind else { return };
|
||||
for declarator in &decl.declarators {
|
||||
judge(&declarator.name, declarator.name_span);
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `name` begins with `disable`, in any case.
|
||||
fn starts_with_disable(name: &str) -> bool {
|
||||
name.len() >= FORBIDDEN_PREFIX.len()
|
||||
&& name[..FORBIDDEN_PREFIX.len()].eq_ignore_ascii_case(FORBIDDEN_PREFIX)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
PositiveMeaningParameterName.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_formal_parameter_and_points_at_its_name() {
|
||||
let src = "module m #(parameter int DisableEcc = 0) ();\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "DisableEcc");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_prefix_is_matched_in_any_case() {
|
||||
for name in ["disable_ecc", "DISABLE_ECC", "DisableEcc", "dIsAbLe"] {
|
||||
let src = format!("module m;\n localparam int {name} = 0;\nendmodule\n");
|
||||
assert_eq!(violations(&src).len(), 1, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_positive_name_is_what_the_rule_wants() {
|
||||
for name in ["EnableEcc", "EccEnabled", "Width", "Dis", "NotDisabled", "UnDisable"] {
|
||||
let src = format!("module m;\n localparam int {name} = 0;\nendmodule\n");
|
||||
assert!(violations(&src).is_empty(), "{name}: {:?}", violations(&src));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_place_a_parameter_is_written_is_reached() {
|
||||
let src = "module m #(parameter int DisableA = 0) ();\n\
|
||||
\x20 localparam int DisableB = 0;\n\
|
||||
\x20 function automatic int f();\n parameter int DisableC = 0;\n \
|
||||
return DisableC;\n endfunction\n\
|
||||
endmodule\n\
|
||||
class c #(parameter int DisableD = 0);\nendclass\n";
|
||||
assert_eq!(violations(src).len(), 4, "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ordinary_signal_is_not_a_parameter() {
|
||||
assert!(violations("module m;\n wire disable_ecc;\nendmodule\n").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
//! `proper-parameter-declaration` — `parameter` in a header, `localparam` in a body.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::options::{OptionDefault, OptionKind, OptionSpec};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::{walk_items_scoped, ItemScope};
|
||||
use vlog_parser::ast::ItemKind;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct ProperParameterDeclaration;
|
||||
|
||||
const NAME: &str = "proper-parameter-declaration";
|
||||
|
||||
/// Verible's two options, spelled and defaulted as Verible spells them.
|
||||
const OPTIONS: &[OptionSpec] = &[
|
||||
OptionSpec {
|
||||
name: "package_allow_parameter",
|
||||
kind: OptionKind::Bool,
|
||||
default: OptionDefault::Bool(false),
|
||||
doc: "accept `parameter` in a package body",
|
||||
},
|
||||
OptionSpec {
|
||||
name: "package_allow_localparam",
|
||||
kind: OptionKind::Bool,
|
||||
default: OptionDefault::Bool(true),
|
||||
doc: "accept `localparam` in a package body",
|
||||
},
|
||||
];
|
||||
|
||||
impl Rule for ProperParameterDeclaration {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"declare `parameter` only in a formal parameter list and `localparam` only in a body"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn default_on(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn options(&self) -> &'static [OptionSpec] {
|
||||
OPTIONS
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A `parameter` is what an instantiation may override, so it belongs \
|
||||
in the `#( … )` a caller can see. Written in a module *body* it is \
|
||||
still overridable — by `defparam`, or by a hierarchical override — \
|
||||
which means a value the reader believes is fixed can change from \
|
||||
outside with nothing at the declaration to say so. `localparam` is \
|
||||
the spelling for a constant that is nobody's business but the \
|
||||
module's. Verible's `proper-parameter-declaration` (\"Checks that \
|
||||
`parameter` declarations are in formal parameter lists and \
|
||||
`localparam` in modules/classes/packages.\", **disabled** by \
|
||||
default) is the same rule and the same default, with the same two \
|
||||
options: `package_allow_parameter` (false) and \
|
||||
`package_allow_localparam` (true).\n\n\
|
||||
A **formal parameter list is never judged** — `#(parameter int W = \
|
||||
8)` and `#(localparam int X = 2*W)` are both fine there. What is \
|
||||
judged is a body declaration: `parameter` anywhere is wrong (in a \
|
||||
package, unless `package_allow_parameter`), and `localparam` is \
|
||||
right in a module, interface, program or class body, wrong at file \
|
||||
scope, and in a package answers to `package_allow_localparam`. Only \
|
||||
item-scope declarations are read; a `parameter` written among a \
|
||||
subroutine's statements is left to the language. No automatic fix: \
|
||||
`parameter` → `localparam` removes an override an instantiation may \
|
||||
be relying on."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let allow_parameter = ctx.option_bool(NAME, "package_allow_parameter");
|
||||
let allow_localparam = ctx.option_bool(NAME, "package_allow_localparam");
|
||||
let mut out = Vec::new();
|
||||
walk_items_scoped(ctx.file(), &mut |scope, item| {
|
||||
let ItemKind::ParamDecl(decl) = &item.kind else { return };
|
||||
let Some(first) = decl.declarators.first() else { return };
|
||||
let Some(message) = complaint(&decl.kw, scope, allow_parameter, allow_localparam)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
out.push(Violation::new(NAME, message, first.name_span));
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// What is wrong with this keyword in this scope, or `None` when nothing is.
|
||||
fn complaint(
|
||||
kw: &str,
|
||||
scope: ItemScope,
|
||||
allow_parameter: bool,
|
||||
allow_localparam: bool,
|
||||
) -> Option<String> {
|
||||
match (kw, scope) {
|
||||
("parameter", ItemScope::Package) if allow_parameter => None,
|
||||
("parameter", _) => Some(
|
||||
"`parameter` belongs in a formal parameter list; write `localparam` for a \
|
||||
body constant"
|
||||
.to_string(),
|
||||
),
|
||||
("localparam", ItemScope::Package) if allow_localparam => None,
|
||||
("localparam", ItemScope::Package) => Some(
|
||||
"`localparam` is not accepted in a package body by this project's settings".to_string(),
|
||||
),
|
||||
("localparam", ItemScope::File) => {
|
||||
Some("`localparam` belongs in a module, interface, program or class body".to_string())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::options::RuleOptions;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
ProperParameterDeclaration.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn with(src: &str, key: &str, raw: &str) -> Vec<Violation> {
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw(NAME, key, raw).expect("accepted");
|
||||
ProperParameterDeclaration.check(&LintContext::new(src, None).with_options(&options))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_parameter_in_a_module_body_and_points_at_its_name() {
|
||||
let src = "module m;\n parameter int Bar = 1;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "Bar");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
/// Verible's own accepted list, snippet for snippet.
|
||||
#[test]
|
||||
fn the_shapes_verible_accepts_are_accepted() {
|
||||
for src in [
|
||||
"module foo; localparam int Bar = 1; endmodule\n",
|
||||
"class foo; localparam int Bar = 1; endclass\n",
|
||||
"package foo; localparam int Bar = 1; endpackage\n",
|
||||
"module foo #(localparam int Bar = 1); endmodule\n",
|
||||
"module foo #(parameter int Bar = 1); endmodule\n",
|
||||
] {
|
||||
assert!(violations(src).is_empty(), "{src}: {:?}", violations(src));
|
||||
}
|
||||
}
|
||||
|
||||
/// Verible's own rejected list, snippet for snippet.
|
||||
#[test]
|
||||
fn the_shapes_verible_rejects_are_reported() {
|
||||
for src in [
|
||||
"parameter int Foo = 1;\n",
|
||||
"package foo; parameter int Bar = 1; endpackage\n",
|
||||
"module foo; parameter int Bar = 1; endmodule\n",
|
||||
"class foo; parameter int Bar = 1; endclass\n",
|
||||
"package foo; class bar; parameter int HelloWorld = 1; endclass endpackage\n",
|
||||
] {
|
||||
assert_eq!(violations(src).len(), 1, "{src}: {:?}", violations(src));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_allow_parameter_moves_the_line() {
|
||||
let src = "package foo; parameter int Bar = 1; endpackage\n";
|
||||
assert_eq!(violations(src).len(), 1);
|
||||
assert!(with(src, "package_allow_parameter", "true").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_allow_localparam_moves_it_the_other_way() {
|
||||
let src = "package foo; localparam int Bar = 1; endpackage\n";
|
||||
assert!(violations(src).is_empty());
|
||||
assert_eq!(with(src, "package_allow_localparam", "false").len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_localparam_at_file_scope_has_no_body_to_belong_to() {
|
||||
assert_eq!(violations("localparam int Foo = 1;\n").len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declaration_inside_a_generate_block_keeps_its_modules_scope() {
|
||||
let src = "module m;\n if (A) begin : g\n localparam int X = 1;\n end\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
//! `suggest-parentheses` — parenthesize a ternary nested in a ternary.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::exprs::walk_exprs;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::{Fix, Violation};
|
||||
use vlog_parser::ast::{Expr, ExprKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct SuggestParentheses;
|
||||
|
||||
const NAME: &str = "suggest-parentheses";
|
||||
|
||||
impl Rule for SuggestParentheses {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"parenthesize a conditional written in the true-clause of another"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn fix(&self) -> Option<crate::violation::Applicability> {
|
||||
Some(crate::violation::Applicability::Safe)
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"`a ? b ? c : d : e` is legal and means `a ? (b ? c : d) : e` — the \
|
||||
conditional operator is right-associative — but the reader has to \
|
||||
know that and then count colons to find which `:` closes which `?`. \
|
||||
Two characters remove the question. Verible's `suggest-parentheses` \
|
||||
(\"Recommend extra parentheses around subexpressions where it helps \
|
||||
readability.\", enabled by default) reports exactly this shape: a \
|
||||
condition expression standing, unparenthesized, in the true-clause of \
|
||||
another condition expression. lucisv reports the same shape and \
|
||||
nothing more — a ternary in the *false*-clause is where the language \
|
||||
already puts it, and every other mixed-precedence expression is left \
|
||||
alone, because a rule that guessed at operator combinations would \
|
||||
report far more than it explained.\n\n\
|
||||
The fix is **safe**: it writes a `(` and a `)` around the inner \
|
||||
conditional and changes no token, which is the meaning the language \
|
||||
already gives the expression."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_exprs(ctx.file(), &mut |expr| {
|
||||
let ExprKind::Ternary { then, .. } = &expr.kind else { return };
|
||||
if !matches!(then.kind, ExprKind::Ternary { .. }) {
|
||||
return;
|
||||
}
|
||||
out.push(
|
||||
Violation::new(
|
||||
NAME,
|
||||
"conditional in the true-clause of another conditional; parenthesize it",
|
||||
then.span,
|
||||
)
|
||||
.with_fix(Fix::safe(parenthesize(then))),
|
||||
);
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The two insertions that wrap `expr` in parentheses, touching nothing else.
|
||||
fn parenthesize(expr: &Expr) -> Vec<(TextRange, String)> {
|
||||
vec![
|
||||
(TextRange::new(expr.span.start, expr.span.start), "(".to_string()),
|
||||
(TextRange::new(expr.span.end, expr.span.end), ")".to_string()),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::violation::apply_fixes;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
SuggestParentheses.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn assign(rhs: &str) -> String {
|
||||
format!("module m;\n assign x = {rhs};\nendmodule\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_the_nested_true_clause_and_underlines_it() {
|
||||
let src = assign("a ? b ? c : d : e");
|
||||
let found = violations(&src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "b ? c : d");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fix_only_adds_parentheses() {
|
||||
let src = assign("a ? b ? c : d : e");
|
||||
let fixed = apply_fixes(&src, &violations(&src), false);
|
||||
assert_eq!(fixed.applied, 1);
|
||||
assert_eq!(fixed.output, assign("a ? (b ? c : d) : e"));
|
||||
// ... and the fixed text has nothing left to report.
|
||||
assert!(violations(&fixed.output).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_already_parenthesized_clause_is_clean() {
|
||||
assert!(violations(&assign("a ? (b ? c : d) : e")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_conditional_in_the_false_clause_is_where_the_language_puts_it() {
|
||||
assert!(violations(&assign("a ? b : c ? d : e")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_conditional_is_clean() {
|
||||
assert!(violations(&assign("a ? b : c")).is_empty());
|
||||
assert!(violations(&assign("a + b * c")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_conditional_condition_is_not_this_rules_business() {
|
||||
// Verible reports the true-clause only; a `?:` used as the condition
|
||||
// of another already needs its own parentheses to parse.
|
||||
assert!(violations(&assign("(a ? b : c) ? d : e")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_deep_reports_each_nesting() {
|
||||
let src = assign("a ? b ? c ? d : e : f : g");
|
||||
assert_eq!(violations(&src).len(), 2, "{:?}", violations(&src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_conditional_written_anywhere_is_reached() {
|
||||
let src = "module m #(parameter int P = a ? b ? 1 : 2 : 3) ();\n\
|
||||
\x20 initial begin\n y = c ? d ? 1 : 2 : 3;\n end\nendmodule\n";
|
||||
assert_eq!(violations(src).len(), 2, "{:?}", violations(src));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
//! `unpacked-dimensions-range-ordering` — write an array's extent `[0:N-1]`.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::decls::{walk_dims, Packing};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::ast::{DimKind, Expr, ExprKind};
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct UnpackedDimensionsRangeOrdering;
|
||||
|
||||
const NAME: &str = "unpacked-dimensions-range-ordering";
|
||||
|
||||
impl Rule for UnpackedDimensionsRangeOrdering {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"declare an unpacked dimension in increasing order, `[0:N-1]`"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"An unpacked dimension is an *array*, and an array counts up: element \
|
||||
0 first. `logic q [7:0]` declares the same eight elements as \
|
||||
`logic q [0:7]` but numbers them backwards, so `foreach (q[i])` \
|
||||
visits them in the opposite order to the one the declaration suggests \
|
||||
and every `for (i = 0; i < 8; i++)` written beside it reads the array \
|
||||
the other way round. Verible's \
|
||||
`unpacked-dimensions-range-ordering` (\"Checks that unpacked \
|
||||
dimension ranges are declared in big-endian order `[0:N-1]`.\", \
|
||||
enabled by default) is the same rule and the same default — and it \
|
||||
is the mirror image of `packed-dimensions-range-ordering`, which \
|
||||
wants a *vector*'s width the other way, `[N-1:0]`.\n\n\
|
||||
Only a range is judged. A sized extent (`logic q [8]`), a dynamic \
|
||||
(`[]`), an associative (`[*]`, `[key_t]`) and a queue are not \
|
||||
ranges and are left alone. A range is flagged when both bounds are \
|
||||
integer literals and the left one is larger, and when the right one \
|
||||
is a literal `0` and the left is anything else (`[N-1:0]`) — every \
|
||||
other shape is two symbolic bounds lucisv does not evaluate. No \
|
||||
automatic fix: reversing a range reverses every use of it."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_dims(ctx.file(), &mut |packing, dim| {
|
||||
if packing != Packing::Unpacked {
|
||||
return;
|
||||
}
|
||||
let DimKind::Range { a, b: Some(b) } = &dim.kind else { return };
|
||||
if !descending(a, b) {
|
||||
return;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
"unpacked dimension counts downwards; write it as `[0:N-1]`",
|
||||
dim.span,
|
||||
));
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `[a:b]` demonstrably counts downwards.
|
||||
///
|
||||
/// Two literals decide it outright. A right bound of literal `0` decides it
|
||||
/// too whatever the left bound is — `[WIDTH-1:0]` is the shape this rule
|
||||
/// mostly meets — unless the left bound is `0` as well, which is the
|
||||
/// one-element `[0:0]` and counts in no direction at all. Anything else is
|
||||
/// two symbolic bounds lucisv cannot compare, and it says nothing.
|
||||
fn descending(a: &Expr, b: &Expr) -> bool {
|
||||
match (literal(a), literal(b)) {
|
||||
(Some(left), Some(right)) => left > right,
|
||||
(None, Some(0)) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of a plain unsigned integer literal, or `None` for anything else.
|
||||
fn literal(expr: &Expr) -> Option<u128> {
|
||||
let ExprKind::Number(text) = &expr.kind else { return None };
|
||||
if text.contains(['\'', '.']) {
|
||||
return None;
|
||||
}
|
||||
text.chars().filter(|c| *c != '_').collect::<String>().parse().ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
UnpackedDimensionsRangeOrdering.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn decl(text: &str) -> String {
|
||||
format!("module m;\n {text}\nendmodule\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_descending_unpacked_range() {
|
||||
let src = decl("logic q [7:0];");
|
||||
let found = violations(&src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "[7:0]");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_the_common_symbolic_to_zero_shape() {
|
||||
assert_eq!(violations(&decl("logic q [DEPTH-1:0];")).len(), 1);
|
||||
assert_eq!(violations(&decl("logic q [2:1];")).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_increasing_range_is_what_the_rule_wants() {
|
||||
for text in [
|
||||
"logic q [0:7];",
|
||||
"logic q [0:DEPTH-1];",
|
||||
"logic q [0:0];",
|
||||
"logic q [8];",
|
||||
"logic q [];",
|
||||
"logic q [string];",
|
||||
"logic q;",
|
||||
] {
|
||||
let src = decl(text);
|
||||
assert!(violations(&src).is_empty(), "{text}: {:?}", violations(&src));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_symbolic_bounds_are_left_alone() {
|
||||
assert!(violations(&decl("logic q [LO:HI];")).is_empty());
|
||||
assert!(violations(&decl("logic q [A-1:B];")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_packed_dimension_is_the_other_rules_business() {
|
||||
assert!(violations(&decl("logic [7:0] v;")).is_empty());
|
||||
// ... and both dimensions of one declaration are told apart.
|
||||
assert_eq!(violations(&decl("logic [7:0] q [3:0];")).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_declaration_shape_is_reached() {
|
||||
let src = "module m #(parameter int P [1:0] = '{0, 0}) (\n\
|
||||
input logic a [1:0]\n\
|
||||
);\n\
|
||||
logic b [1:0];\n\
|
||||
typedef logic w_t [1:0];\n\
|
||||
function automatic void f(input logic x [1:0]);\n\
|
||||
endfunction\n\
|
||||
endmodule\n";
|
||||
assert_eq!(violations(src).len(), 5, "{:?}", violations(src));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
//! `uvm-macro-semicolon` — no `;` after a `` `uvm_* `` macro invocation.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::preproc::macro_name;
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::token::TokenKind;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct UvmMacroSemicolon;
|
||||
|
||||
const NAME: &str = "uvm-macro-semicolon";
|
||||
|
||||
/// The prefix that marks a macro as UVM's.
|
||||
const UVM: &str = "uvm_";
|
||||
|
||||
impl Rule for UvmMacroSemicolon {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"do not write a `;` after a `` `uvm_* `` macro invocation"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn default_on(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"The UVM reporting macros expand to a `begin … end` block, so the `;` \
|
||||
so many people write after one is a *null statement* that follows it. \
|
||||
Usually harmless; not always — `if (x) `uvm_info(…); else …` puts the \
|
||||
null statement where the `if`'s body should be and the `else` then \
|
||||
belongs to nothing, which is a compile error or, worse, a silently \
|
||||
different branch structure. Verible's `uvm-macro-semicolon` (\"Checks \
|
||||
that no `uvm_*` macro calls end with ';'.\", **disabled** by default) \
|
||||
is the same rule and lucisv ships it off for the same reason: the \
|
||||
semicolon is written everywhere in existing UVM code and is almost \
|
||||
always inert, so turning it on is a project's decision.\n\n\
|
||||
A macro whose name begins `uvm_` is judged, whatever follows the \
|
||||
invocation's arguments; the finding points at the `;`. **No \
|
||||
automatic fix**: deleting the `;` is exactly the edit that is unsafe \
|
||||
in the one shape the rule exists for — after `if (x) `uvm_info(…);` \
|
||||
with no `else`, removing it is fine, and with one it changes which \
|
||||
statement the `else` binds to."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let tokens = ctx.tokens();
|
||||
let mut out = Vec::new();
|
||||
for (i, token) in tokens.iter().enumerate() {
|
||||
let Some(name) = macro_name(token) else { continue };
|
||||
if !name.starts_with(UVM) {
|
||||
continue;
|
||||
}
|
||||
let Some(next) = tokens.get(i + 1) else { continue };
|
||||
if next.kind != TokenKind::Symbol || next.text != ";" {
|
||||
continue;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!("`` `{name} `` already ends its statement; the `;` is a null statement"),
|
||||
next.span,
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
UvmMacroSemicolon.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_the_semicolon_not_the_macro() {
|
||||
let src = "module m;\n initial `uvm_info(\"A\", \"B\", UVM_LOW);\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], ";");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bare_invocation_is_what_the_rule_wants() {
|
||||
let src = "module m;\n initial begin\n `uvm_info(\"A\", \"B\", UVM_LOW)\n end\n\
|
||||
endmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_uvm_macro_is_not_judged() {
|
||||
let src = "module m;\n initial `my_macro(1);\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_uvm_macro_of_a_file_is_reported() {
|
||||
let src = "module m;\n initial begin\n `uvm_info(\"A\", \"B\", UVM_LOW);\n \
|
||||
`uvm_error(\"A\", \"B\");\n `uvm_fatal(\"A\", \"B\")\n end\nendmodule\n";
|
||||
assert_eq!(violations(src).len(), 2, "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_semicolon_on_the_next_line_still_follows_the_macro() {
|
||||
let src = "module m;\n initial `uvm_info(\"A\", \"B\", UVM_LOW)\n ;\nendmodule\n";
|
||||
assert_eq!(violations(src).len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
//! `v2001-generate-begin` — no bare `begin` inside a generate region.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::rules::module_begin_block::begin_block;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::walk_items;
|
||||
use vlog_parser::ast::ItemKind;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct V2001GenerateBegin;
|
||||
|
||||
const NAME: &str = "v2001-generate-begin";
|
||||
|
||||
impl Rule for V2001GenerateBegin {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"do not write a bare `begin` block inside a generate region"
|
||||
}
|
||||
|
||||
fn severity(&self) -> Severity {
|
||||
Severity::Style
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A `begin … end` written directly inside `generate … endgenerate`, \
|
||||
with no `if`, `for` or `case` around it, was a Verilog-2001 spelling \
|
||||
for \"one more scope\". It opens an unnamed generate block, so every \
|
||||
declaration inside it acquires an invented path segment (`genblk1.x`) \
|
||||
that renumbers the moment a block is added above it — and it buys \
|
||||
nothing, because the region is already a scope. Verible's \
|
||||
`v2001-generate-begin` (\"Checks that there are no generate-begin \
|
||||
blocks inside a generate region.\", enabled by default) is the same \
|
||||
rule and the same default.\n\n\
|
||||
Like `module-begin-block`, this reads the block lucisv's parser \
|
||||
recovers where it refuses the construct: an unnamed generate block \
|
||||
written directly inside a `generate … endgenerate`, kept in the tree \
|
||||
beside a diagnostic at its `begin`, so everything declared inside it \
|
||||
is still visible to the other rules. No automatic fix — deleting the \
|
||||
two keywords re-indents the whole block, and giving it a label \
|
||||
instead is a different repair."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_items(ctx.file(), &mut |item| {
|
||||
let ItemKind::GenerateRegion { items, .. } = &item.kind else { return };
|
||||
for inner in items {
|
||||
if let Some(span) = begin_block(inner) {
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
"bare `begin` block inside a generate region; the region is \
|
||||
already a scope",
|
||||
span,
|
||||
));
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
V2001GenerateBegin.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_bare_begin_and_points_at_the_keyword() {
|
||||
let src = "module m;\n generate\n begin : b\n wire a;\n end\n \
|
||||
endgenerate\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "begin");
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generate_construct_inside_the_region_is_what_belongs_there() {
|
||||
let src = "module m;\n generate\n\
|
||||
\x20 if (A) begin : g\n wire a;\n end\n\
|
||||
\x20 for (genvar i = 0; i < 2; i++) begin : l\n wire b;\n end\n\
|
||||
\x20 endgenerate\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_scope_block_belongs_to_the_other_rule() {
|
||||
let src = "module m;\n begin\n wire a;\n end\nendmodule\n";
|
||||
assert!(violations(src).is_empty(), "{:?}", violations(src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_blocks_items_stay_visible_to_the_other_rules() {
|
||||
let src = "module m;\n generate\n begin : b\n defparam u.P = 1;\n end\n \
|
||||
endgenerate\n wire ok;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert_eq!(&src[found[0].span.as_range()], "begin");
|
||||
let inside =
|
||||
crate::rules::forbid_defparam::ForbidDefparam.check(&LintContext::new(src, None));
|
||||
assert_eq!(inside.len(), 1, "a rule reading the block's items: {inside:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_with_no_generate_region_is_silent() {
|
||||
assert!(violations("module m;\n wire a;\nendmodule\n").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! `void-cast` — `void'(…)` around something that is not a call.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::options::{OptionDefault, OptionKind, OptionSpec};
|
||||
use crate::registry::Rule;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
@@ -12,6 +13,15 @@ pub struct VoidCast;
|
||||
|
||||
const NAME: &str = "void-cast";
|
||||
|
||||
/// Verible's own forbidden-call list, which it hard-codes: `uvm_hdl_read` and
|
||||
/// `randomize` (the bare call and the `obj.randomize()` method alike).
|
||||
const OPTIONS: &[OptionSpec] = &[OptionSpec {
|
||||
name: "forbidden_calls",
|
||||
kind: OptionKind::List,
|
||||
default: OptionDefault::List(&["uvm_hdl_read", "randomize"]),
|
||||
doc: "calls whose result must be checked, so a `void'` cast of one is a bug",
|
||||
}];
|
||||
|
||||
impl Rule for VoidCast {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
@@ -25,6 +35,10 @@ impl Rule for VoidCast {
|
||||
Severity::Warning
|
||||
}
|
||||
|
||||
fn options(&self) -> &'static [OptionSpec] {
|
||||
OPTIONS
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"`void'(expr)` exists for exactly one purpose: calling a function for \
|
||||
its side effect and saying out loud that the return value is being \
|
||||
@@ -35,12 +49,19 @@ impl Rule for VoidCast {
|
||||
edit. Verible ships a `void-cast` rule (\"Checks that void casts do \
|
||||
not contain certain function/method calls.\", enabled by default) \
|
||||
with a different subject: **it forbids a named list of calls** whose \
|
||||
result must be checked (`randomize`, `uvm_hdl_read`). lucisv's is the \
|
||||
complementary check TODO §33 asked for — the operand must be a call \
|
||||
at all — and takes no list, so the two do not overlap and neither \
|
||||
replaces the other; the named-call form belongs with the per-rule \
|
||||
options of wave 2. No automatic fix: whether the repair is to delete \
|
||||
the cast or to add the missing call is the author's to decide.\n\n\
|
||||
result must be checked (`randomize`, `uvm_hdl_read`). lucisv checks \
|
||||
both halves in the one rule. The first is the check TODO §33 asked \
|
||||
for — the operand must be a call at all — and the second is \
|
||||
Verible's, spelled as the `forbidden_calls` option so a project can \
|
||||
name its own. A discarded `randomize()` is the classic version: it \
|
||||
returns 0 when the constraints could not be solved, and \
|
||||
`void'(randomize())` throws that away, so the test runs on with \
|
||||
whatever the object happened to hold. The two halves cannot both \
|
||||
fire on one statement — the first wants a call and the second wants \
|
||||
a particular one — so a `void'(randomize())` is reported once. No \
|
||||
automatic fix for either: whether the repair is to delete the cast, \
|
||||
to add the missing call or to check the result is the author's to \
|
||||
decide.\n\n\
|
||||
Only a `void'(...)` standing **as a statement** is judged, which is \
|
||||
the one place the construct belongs: a `void` value gives an \
|
||||
enclosing expression nothing to do with it, so a `void'` buried in an \
|
||||
@@ -48,16 +69,31 @@ impl Rule for VoidCast {
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let forbidden = ctx.option_list(NAME, "forbidden_calls");
|
||||
let mut out = Vec::new();
|
||||
walk_all_stmts(ctx.file(), &mut |stmt| {
|
||||
let StmtKind::ExprStmt(expr) = &stmt.kind else { return };
|
||||
let ExprKind::Cast { ty, expr: inner, pattern, .. } = &expr.kind else { return };
|
||||
if *pattern || !is_void(ty) || is_call(inner) {
|
||||
if *pattern || !is_void(ty) {
|
||||
return;
|
||||
}
|
||||
if !is_call(inner) {
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
"`void'(...)` around something that is not a call; nothing is being discarded",
|
||||
expr.span,
|
||||
));
|
||||
return;
|
||||
}
|
||||
let Some(called) = called_name(inner) else { return };
|
||||
if !forbidden.iter().any(|name| name == called) {
|
||||
return;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
"`void'(...)` around something that is not a call; nothing is being discarded",
|
||||
format!(
|
||||
"`{called}` returns a result that must be checked; do not cast it to `void`"
|
||||
),
|
||||
expr.span,
|
||||
));
|
||||
});
|
||||
@@ -65,6 +101,23 @@ impl Rule for VoidCast {
|
||||
}
|
||||
}
|
||||
|
||||
/// The name the cast operand calls — the last segment of the callee, so
|
||||
/// `obj.randomize()`, `pkg::uvm_hdl_read()` and a bare `randomize()` all
|
||||
/// answer the same word.
|
||||
fn called_name(expr: &Expr) -> Option<&str> {
|
||||
match &expr.kind {
|
||||
ExprKind::Call { callee, .. } => match &callee.kind {
|
||||
ExprKind::Ident(name) => Some(name),
|
||||
ExprKind::Member { name, .. } | ExprKind::Scope { name, .. } => Some(name),
|
||||
_ => None,
|
||||
},
|
||||
ExprKind::Paren { inner, .. } => called_name(inner),
|
||||
ExprKind::With { base, .. } | ExprKind::WithConstraint { base, .. } => called_name(base),
|
||||
ExprKind::Cast { expr: inner, .. } => called_name(inner),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// True for the casting type `void`, however it is spelled in the tree.
|
||||
fn is_void(ty: &Expr) -> bool {
|
||||
matches!(&ty.kind, ExprKind::Ident(name) if name == "void")
|
||||
@@ -116,18 +169,57 @@ mod tests {
|
||||
fn a_call_is_what_a_void_cast_is_for() {
|
||||
for text in [
|
||||
"void'(f());",
|
||||
"void'(obj.randomize());",
|
||||
"void'(pkg::f(1, 2));",
|
||||
"void'(q.pop_front());",
|
||||
"void'((f()));",
|
||||
"void'($cast(a, b));",
|
||||
"void'(randomize(x) with { x inside {[0:7]}; });",
|
||||
"void'(q.sum() with (item.w));",
|
||||
] {
|
||||
assert!(violations(&stmt(text)).is_empty(), "{text}: {:?}", violations(&stmt(text)));
|
||||
}
|
||||
}
|
||||
|
||||
/// Verible's half of the rule: a call whose result must be checked.
|
||||
#[test]
|
||||
fn a_forbidden_call_is_reported_however_it_is_written() {
|
||||
for text in [
|
||||
"void'(randomize());",
|
||||
"void'(obj.randomize());",
|
||||
"void'(randomize(x) with { x inside {[0:7]}; });",
|
||||
"void'(uvm_hdl_read(path, value));",
|
||||
"void'(pkg::uvm_hdl_read(path, value));",
|
||||
] {
|
||||
let found = violations(&stmt(text));
|
||||
assert_eq!(found.len(), 1, "{text}: {found:?}");
|
||||
assert!(found[0].message.contains("must be checked"), "{}", found[0].message);
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_two_halves_never_both_fire_on_one_statement() {
|
||||
// The operand is a call, so the "not a call" half is silent; it is a
|
||||
// forbidden call, so the other half speaks — once.
|
||||
assert_eq!(violations(&stmt("void'(randomize());")).len(), 1);
|
||||
assert_eq!(violations(&stmt("void'(x);")).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_forbidden_list_is_configurable() {
|
||||
use crate::options::RuleOptions;
|
||||
let src = stmt("void'(my_check());");
|
||||
assert!(violations(&src).is_empty());
|
||||
let mut options = RuleOptions::new();
|
||||
options.set_raw(NAME, "forbidden_calls", "[\"my_check\"]").expect("accepted");
|
||||
let found = VoidCast.check(&LintContext::new(&src, None).with_options(&options));
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
// ... and the default names are no longer forbidden once replaced.
|
||||
let randomized = stmt("void'(randomize());");
|
||||
assert!(VoidCast
|
||||
.check(&LintContext::new(&randomized, None).with_options(&options))
|
||||
.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cast_to_something_else_is_not_this_rules_business() {
|
||||
for text in ["a = int'(x);", "a = logic'(x);", "a = my_t'(x);", "a = 4'(x);"] {
|
||||
|
||||
@@ -369,6 +369,7 @@ impl Scanner {
|
||||
}
|
||||
}
|
||||
ItemKind::GenerateRegion { items, .. } => self.items(items, module, true),
|
||||
ItemKind::GenBlock(b) => self.items(&b.items, module, true),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
self.items(&gen_if.then.items, module, true);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
|
||||
@@ -24,6 +24,7 @@ fn items(list: &[Item], f: &mut dyn FnMut(&Item)) {
|
||||
ItemKind::Class(class) => items(&class.items, f),
|
||||
ItemKind::Package { items: inner, .. } => items(inner, f),
|
||||
ItemKind::GenerateRegion { items: inner, .. } => items(inner, f),
|
||||
ItemKind::GenBlock(b) => items(&b.items, f),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
gen_block(&gen_if.then, f);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
@@ -70,6 +71,67 @@ fn gen_block(block: &GenBlock, f: &mut dyn FnMut(&Item)) {
|
||||
items(&block.items, f);
|
||||
}
|
||||
|
||||
/// The declaration an item was written inside — what a rule needs when the
|
||||
/// same construct is right in one scope and wrong in another.
|
||||
///
|
||||
/// A generate construct is not a scope here: `localparam` inside a
|
||||
/// `generate` block is still written in the module that holds it, and both
|
||||
/// rules that ask this question (`proper-parameter-declaration`, the two
|
||||
/// `explicit-*-lifetime`) mean the enclosing *declaration*, not the block.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum ItemScope {
|
||||
/// Written at file scope, outside every declaration.
|
||||
File,
|
||||
/// Inside a `module`, `interface` or `program` body.
|
||||
Module,
|
||||
/// Inside a `package` body.
|
||||
Package,
|
||||
/// Inside a `class` body.
|
||||
Class,
|
||||
}
|
||||
|
||||
/// Calls `f` on every item of the file, saying which declaration holds it.
|
||||
pub(crate) fn walk_items_scoped(file: &SourceFile, f: &mut dyn FnMut(ItemScope, &Item)) {
|
||||
scoped_items(&file.items, ItemScope::File, f);
|
||||
}
|
||||
|
||||
fn scoped_items(list: &[Item], scope: ItemScope, f: &mut dyn FnMut(ItemScope, &Item)) {
|
||||
for item in list {
|
||||
f(scope, item);
|
||||
match &item.kind {
|
||||
ItemKind::Module(m) => scoped_items(&m.items, ItemScope::Module, f),
|
||||
ItemKind::Class(class) => scoped_items(&class.items, ItemScope::Class, f),
|
||||
ItemKind::Package { items: inner, .. } => scoped_items(inner, ItemScope::Package, f),
|
||||
// A generate construct keeps the scope it was written in.
|
||||
ItemKind::GenerateRegion { items: inner, .. } => scoped_items(inner, scope, f),
|
||||
ItemKind::GenBlock(b) => scoped_items(&b.items, scope, f),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
scoped_items(&gen_if.then.items, scope, f);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
while let Some(branch) = els {
|
||||
match branch {
|
||||
GenElse::If(_, nested) => {
|
||||
scoped_items(&nested.then.items, scope, f);
|
||||
els = nested.els.as_deref();
|
||||
}
|
||||
GenElse::Block(block) => {
|
||||
scoped_items(&block.items, scope, f);
|
||||
els = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::GenFor(gen_for) => scoped_items(&gen_for.body.items, scope, f),
|
||||
ItemKind::GenCase(gen_case) => {
|
||||
for case_item in &gen_case.items {
|
||||
scoped_items(&case_item.body.items, scope, f);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls `f` on every statement of the file, nested statements included.
|
||||
pub(crate) fn walk_all_stmts(file: &SourceFile, f: &mut dyn FnMut(&Stmt)) {
|
||||
// A statement fragment is a whole file of statements with no item around
|
||||
@@ -314,6 +376,41 @@ mod tests {
|
||||
assert_eq!(names, vec!["A".to_string(), "T".to_string()]);
|
||||
}
|
||||
|
||||
/// The scope a rule asks about is the enclosing *declaration*, and a
|
||||
/// generate construct passes the one it was written in through.
|
||||
#[test]
|
||||
fn every_item_is_told_which_declaration_holds_it() {
|
||||
let src = "localparam int AtFile = 0;\n\
|
||||
package p;\n\
|
||||
localparam int InPackage = 0;\n\
|
||||
class c;\n localparam int InClass = 0;\n endclass\n\
|
||||
endpackage\n\
|
||||
module m;\n\
|
||||
localparam int InModule = 0;\n\
|
||||
if (A) begin : g\n localparam int InGenerate = 0;\n end\n\
|
||||
endmodule\n";
|
||||
let (file, diagnostics) = parse_source_tolerant(src);
|
||||
assert!(diagnostics.is_empty(), "{diagnostics:?}");
|
||||
let mut seen: Vec<(String, ItemScope)> = Vec::new();
|
||||
walk_items_scoped(&file, &mut |scope, item| {
|
||||
if let ItemKind::ParamDecl(decl) = &item.kind {
|
||||
for declarator in &decl.declarators {
|
||||
seen.push((declarator.name.clone(), scope));
|
||||
}
|
||||
}
|
||||
});
|
||||
assert_eq!(
|
||||
seen,
|
||||
vec![
|
||||
("AtFile".to_string(), ItemScope::File),
|
||||
("InPackage".to_string(), ItemScope::Package),
|
||||
("InClass".to_string(), ItemScope::Class),
|
||||
("InModule".to_string(), ItemScope::Module),
|
||||
("InGenerate".to_string(), ItemScope::Module),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unparsable_region_is_visited_but_holds_nothing() {
|
||||
let (file, diagnostics) = parse_source_tolerant("module m;\n @@@;\nendmodule\n");
|
||||
|
||||
@@ -74,9 +74,9 @@ endmodule
|
||||
====
|
||||
# `endfunction;` / `endtask;` are recorded on the declaration, not as null items
|
||||
module m;
|
||||
function int f();
|
||||
function automatic int f();
|
||||
endfunction;
|
||||
task t();
|
||||
task automatic t();
|
||||
endtask;
|
||||
endmodule
|
||||
====
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
#select suggest-parentheses
|
||||
# a conditional in the true-clause of another, and the safe fix that parenthesizes it
|
||||
module m;
|
||||
assign x = a ? b ? c : d : e;
|
||||
//^ 18 suggest-parentheses
|
||||
assign y = a ? b : c ? d : e;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign x = a ? (b ? c : d) : e;
|
||||
//^ 18 suggest-parentheses
|
||||
assign y = a ? b : c ? d : e;
|
||||
endmodule
|
||||
====
|
||||
#select unpacked-dimensions-range-ordering
|
||||
# an array counts up; a vector's width is the other rule's business
|
||||
module m;
|
||||
logic [7:0] v;
|
||||
logic q [0:3];
|
||||
logic r [3:0];
|
||||
//^ 11 unpacked-dimensions-range-ordering
|
||||
logic s [DEPTH-1:0];
|
||||
//^ 11 unpacked-dimensions-range-ordering
|
||||
logic t [4];
|
||||
logic [LO:HI] u [LO:HI];
|
||||
endmodule
|
||||
@@ -0,0 +1,56 @@
|
||||
#select legacy-generate-region,legacy-genvar-declaration
|
||||
# the Verilog-2001 spellings, both off by default and both selected here
|
||||
module m;
|
||||
genvar i;
|
||||
//^ 10 legacy-genvar-declaration
|
||||
generate
|
||||
//^ 3 legacy-generate-region
|
||||
for (i = 0; i < 2; i++) begin : g_lanes
|
||||
wire a;
|
||||
end
|
||||
endgenerate
|
||||
endmodule
|
||||
====
|
||||
#select legacy-generate-region,legacy-genvar-declaration
|
||||
# the SystemVerilog spelling has neither
|
||||
module m;
|
||||
for (genvar i = 0; i < 2; i++) begin : g_lanes
|
||||
wire a;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
#select module-begin-block
|
||||
# a sequential block written where a module item belongs
|
||||
module m;
|
||||
begin
|
||||
//^ 3 module-begin-block
|
||||
wire a;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
#select module-begin-block,v2001-generate-begin
|
||||
# a bare begin inside a generate region belongs to the other rule
|
||||
module m;
|
||||
generate
|
||||
begin : b
|
||||
//^ 5 v2001-generate-begin
|
||||
wire a;
|
||||
end
|
||||
endgenerate
|
||||
endmodule
|
||||
====
|
||||
#select module-begin-block,v2001-generate-begin
|
||||
# every legal block shape is silent
|
||||
module m;
|
||||
initial begin
|
||||
a = 1;
|
||||
end
|
||||
always_comb begin
|
||||
b = a;
|
||||
end
|
||||
generate
|
||||
if (A) begin : g_a
|
||||
wire c;
|
||||
end
|
||||
endgenerate
|
||||
endmodule
|
||||
@@ -0,0 +1,43 @@
|
||||
#select explicit-function-lifetime,explicit-task-lifetime
|
||||
# a subroutine outside a class must say which lifetime it has
|
||||
module m;
|
||||
function int f(int x);
|
||||
//^ 16 explicit-function-lifetime
|
||||
return x;
|
||||
endfunction
|
||||
task t();
|
||||
//^ 8 explicit-task-lifetime
|
||||
endtask
|
||||
endmodule
|
||||
====
|
||||
#select explicit-function-lifetime,explicit-task-lifetime
|
||||
# either keyword satisfies both rules
|
||||
module m;
|
||||
function automatic int f(int x);
|
||||
return x;
|
||||
endfunction
|
||||
task static t();
|
||||
endtask
|
||||
endmodule
|
||||
====
|
||||
#select explicit-function-lifetime,explicit-task-lifetime
|
||||
# a class method is exempt, and a prototype declares no locals
|
||||
package p;
|
||||
class c;
|
||||
function int f();
|
||||
return 0;
|
||||
endfunction
|
||||
task t();
|
||||
endtask
|
||||
extern function int g();
|
||||
endclass
|
||||
endpackage
|
||||
====
|
||||
#select explicit-function-lifetime
|
||||
# a package-scope function is judged like a module's
|
||||
package p;
|
||||
function int f();
|
||||
//^ 16 explicit-function-lifetime
|
||||
return 0;
|
||||
endfunction
|
||||
endpackage
|
||||
@@ -0,0 +1,39 @@
|
||||
#select positive-meaning-parameter-name
|
||||
# a parameter named for what it turns off
|
||||
module m #(
|
||||
parameter int DisableEcc = 0
|
||||
//^ 17 positive-meaning-parameter-name
|
||||
) ();
|
||||
localparam int disable_crc = 1;
|
||||
//^ 18 positive-meaning-parameter-name
|
||||
localparam int EnableEcc = 1;
|
||||
endmodule
|
||||
====
|
||||
#select proper-parameter-declaration
|
||||
# `parameter` in a body, `localparam` in a formal list
|
||||
module m #(
|
||||
parameter int Width = 8,
|
||||
localparam int Half = Width / 2
|
||||
) ();
|
||||
parameter int Depth = 4;
|
||||
//^ 17 proper-parameter-declaration
|
||||
localparam int Mask = 3;
|
||||
endmodule
|
||||
====
|
||||
#select proper-parameter-declaration
|
||||
# a package takes `localparam` by default and `parameter` only when told to
|
||||
package p;
|
||||
localparam int A = 1;
|
||||
parameter int B = 2;
|
||||
//^ 17 proper-parameter-declaration
|
||||
endpackage
|
||||
====
|
||||
#select proper-parameter-declaration
|
||||
#options proper-parameter-declaration.package_allow_parameter = true
|
||||
#options proper-parameter-declaration.package_allow_localparam = false
|
||||
# the two options move the line in opposite directions
|
||||
package p;
|
||||
localparam int A = 1;
|
||||
//^ 18 proper-parameter-declaration
|
||||
parameter int B = 2;
|
||||
endpackage
|
||||
@@ -0,0 +1,78 @@
|
||||
#select forbidden-macro,uvm-macro-semicolon
|
||||
# the default forbidden macro, and the `;` the UVM macros do not want
|
||||
module m;
|
||||
initial begin
|
||||
`uvm_warning("A", "B")
|
||||
//^ 5 forbidden-macro
|
||||
`uvm_info("A", "B", UVM_LOW);
|
||||
//^ 33 uvm-macro-semicolon
|
||||
`uvm_error("A", "B")
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
#select forbidden-macro
|
||||
#options forbidden-macro.macros = ["my_macro"]
|
||||
# the option replaces Verible's one-name list
|
||||
module m;
|
||||
initial begin
|
||||
`uvm_warning("A", "B")
|
||||
`my_macro(1)
|
||||
//^ 5 forbidden-macro
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
#select macro-string-concatenation
|
||||
# `` inside a plain string is not evaluated; inside `"..."` it is
|
||||
`define GLUE(a, b) $display("a``b")
|
||||
//^ 31 macro-string-concatenation
|
||||
`define OK(a, b) $display(`"a``b`")
|
||||
module m;
|
||||
endmodule
|
||||
====
|
||||
#select endif-comment
|
||||
# a bare `endif is named by the safe fix
|
||||
`ifdef SYNTHESIS
|
||||
module m;
|
||||
endmodule
|
||||
`endif
|
||||
//^ 1 endif-comment
|
||||
----
|
||||
`ifdef SYNTHESIS
|
||||
module m;
|
||||
endmodule
|
||||
`endif // SYNTHESIS
|
||||
//^ 1 endif-comment
|
||||
====
|
||||
#select endif-comment
|
||||
# nesting pairs each `endif with its own condition, and a naming comment passes
|
||||
`ifdef A
|
||||
`ifdef B
|
||||
module m;
|
||||
endmodule
|
||||
`endif // B
|
||||
`endif
|
||||
//^ 1 endif-comment
|
||||
====
|
||||
#select forbid-line-continuations
|
||||
# a `define may be broken across lines and a string may not. The positive
|
||||
# case has no marker home here: the finding lands on the *first* line of a
|
||||
# multi-line string, and a marker attaches to the line above it — which is
|
||||
# inside the string. Pinned in the rule's unit tests instead, as `posix-eof`
|
||||
# is; what this case pins is that a multi-line macro is never reported.
|
||||
`define TWO_LINES \
|
||||
wire a; \
|
||||
wire b;
|
||||
module m;
|
||||
endmodule
|
||||
====
|
||||
#select numeric-format-string-style
|
||||
# the prefix must name the base the specifier prints
|
||||
module m;
|
||||
initial begin
|
||||
$display("0x%0h and 'b%0b and %d", a, b, c);
|
||||
$display("0x%0b", a);
|
||||
//^ 15 numeric-format-string-style
|
||||
$display("0d%0d", a);
|
||||
//^ 15 numeric-format-string-style
|
||||
end
|
||||
endmodule
|
||||
@@ -26,7 +26,7 @@ module m;
|
||||
void'(x);
|
||||
//^ 5 void-cast
|
||||
void'(f());
|
||||
void'(obj.randomize() with { a inside {[0:3]}; });
|
||||
void'(obj.pop() with { a inside {[0:3]}; });
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
#select create-object-name-match
|
||||
# the create name is the handle's name
|
||||
class c;
|
||||
function automatic void build();
|
||||
driver_h = my_driver::type_id::create("drv", this);
|
||||
//^ 43 create-object-name-match
|
||||
monitor_h = my_monitor::type_id::create("monitor_h", this);
|
||||
endfunction
|
||||
endclass
|
||||
====
|
||||
#select void-cast
|
||||
# the two halves of the rule: a non-call operand, and a call whose result must be checked
|
||||
class c;
|
||||
function automatic void run();
|
||||
void'(x);
|
||||
//^ 5 void-cast
|
||||
void'(f());
|
||||
void'(obj.randomize());
|
||||
//^ 5 void-cast
|
||||
endfunction
|
||||
endclass
|
||||
====
|
||||
#select void-cast
|
||||
#options void-cast.forbidden_calls = ["my_check"]
|
||||
# the forbidden-call list is the project's
|
||||
class c;
|
||||
function automatic void run();
|
||||
void'(obj.randomize());
|
||||
void'(my_check());
|
||||
//^ 5 void-cast
|
||||
endfunction
|
||||
endclass
|
||||
====
|
||||
#select invalid-system-task-function
|
||||
#options invalid-system-task-function.symbols = ["$stop"]
|
||||
# `symbols` is Verible's `forbidden-symbol` list, folded into this one rule
|
||||
module m;
|
||||
initial begin
|
||||
a = $random();
|
||||
$stop;
|
||||
//^ 5 invalid-system-task-function
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
#select disable-statement
|
||||
# a fork label is not something `disable` may name
|
||||
module m;
|
||||
initial begin : seq
|
||||
fork : threads
|
||||
join_none
|
||||
disable seq;
|
||||
disable fork;
|
||||
disable threads;
|
||||
//^ 5 disable-statement
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
#select dff-name-style
|
||||
# the `_q`/`_d` convention, its reset waiver and its mismatch
|
||||
module m;
|
||||
always_ff @(posedge clk) begin
|
||||
if (!rst_ni) count <= '0;
|
||||
else count_q <= count_d;
|
||||
other_q <= wrong_d;
|
||||
//^ 16 dff-name-style
|
||||
plain <= count_d;
|
||||
//^ 5 dff-name-style
|
||||
end
|
||||
assign result_q = count_d;
|
||||
//^ 10 dff-name-style
|
||||
endmodule
|
||||
====
|
||||
#select dff-name-style
|
||||
#options dff-name-style.output = ["ptr"]
|
||||
#options dff-name-style.input = ["nxt"]
|
||||
# the suffix lists are the project's
|
||||
module m;
|
||||
always_ff @(posedge clk) begin
|
||||
data_ptr <= data_nxt;
|
||||
data_q <= data_d;
|
||||
//^ 5 dff-name-style
|
||||
end
|
||||
endmodule
|
||||
@@ -29,7 +29,7 @@ endmodule
|
||||
====
|
||||
# a verible waiver for a rule lucisv does not have is ignored
|
||||
module m;
|
||||
// verilog_lint: waive explicit-function-lifetime
|
||||
// verilog_lint: waive forbid-implicit-declarations
|
||||
wire a;
|
||||
endmodule
|
||||
====
|
||||
|
||||
@@ -387,6 +387,15 @@ pub enum ItemKind {
|
||||
dangling: Vec<Comment>,
|
||||
},
|
||||
GenIf(GenIf),
|
||||
/// A bare `begin … end` written where an item belongs — at module scope
|
||||
/// or straight inside `generate … endgenerate`. Not a legal module item
|
||||
/// (IEEE 1800 §23.2.1); tools that accept it read it as an unnamed
|
||||
/// generate block, which is the node kept here. Only error-tolerant
|
||||
/// parsing produces it, always beside a diagnostic at the `begin`, so the
|
||||
/// formatter — which refuses any file with a diagnostic — never prints
|
||||
/// one. The `module-begin-block` and `v2001-generate-begin` lints are
|
||||
/// what report it. Boxed for the same reason [`ItemKind::GenFor`] is.
|
||||
GenBlock(Box<GenBlock>),
|
||||
/// Boxed: a `for` generate holds a whole `SimpleAssign`, a condition, a
|
||||
/// step and a block, which together are twice the next-largest item.
|
||||
GenFor(Box<GenFor>),
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! `bind` directives. Drive strengths and delay values live here because
|
||||
//! these are the only items that write them.
|
||||
|
||||
use super::recover::is_sync_stop;
|
||||
use super::*;
|
||||
|
||||
/// The strength keywords a drive strength is written from (IEEE 1800 §28.11).
|
||||
@@ -504,6 +505,16 @@ impl<'a> Parser<'a> {
|
||||
let before_open = self.take_before_open("(");
|
||||
let mark = self.pending_trailing.len();
|
||||
let paren_start = self.here();
|
||||
// A half-typed `.NAME(` whose value would read as the next
|
||||
// instance: `sub #(.WIDTH(8), .DEPTH(` ⏎ `u0 (.a(x));`. Nothing
|
||||
// inside the list fails — `u0 (.a(x))` is a legal call with named
|
||||
// arguments — so the greedy parse swallows the instance and the
|
||||
// whole instantiation collapses into one error item. Failing the
|
||||
// element here costs the one connection and keeps everything
|
||||
// else. See `docs/features/small-items-3/README.md`.
|
||||
if self.tolerant && self.cur().is_sym("(") && self.value_runs_into_next_instance() {
|
||||
return self.error("unclosed `(` in a port or parameter connection");
|
||||
}
|
||||
let mut close_comments = Vec::new();
|
||||
let mut after_open = Vec::new();
|
||||
let expr = if self.eat_sym("(") {
|
||||
@@ -562,6 +573,58 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the `(` at the cursor — the one that opens a connection's
|
||||
/// value — is never closed **and** something that reads as the next
|
||||
/// instance sits inside it.
|
||||
///
|
||||
/// Tolerant mode only, asked once per named connection before its value
|
||||
/// is parsed. The walk starts just past the `(` at depth zero and ends at
|
||||
/// the first of: a closer that would take the depth below zero (the
|
||||
/// value's own `)` — it closes, so nothing is wrong and the value is
|
||||
/// parsed as written), a `;` or a construct keyword at depth zero, or end
|
||||
/// of file. On a file that parses it therefore stops at the value's `)`
|
||||
/// after a handful of tokens; only a value whose bracket was never closed
|
||||
/// walks as far as the next `;`.
|
||||
///
|
||||
/// The candidate is an identifier that opens its own line and is followed
|
||||
/// by `(` — how an instance is written, and how nothing written *inside*
|
||||
/// a value normally is. Only depth zero is read: a candidate inside a
|
||||
/// deeper unclosed bracket (`.DEPTH(f(g(` ⏎ `u0 (…)`) is not seen, and
|
||||
/// that shape falls back to the coarser item-level recovery, which keeps
|
||||
/// the `endmodule` but loses the instantiation. Deliberate — reading
|
||||
/// deeper would start guessing which of several unclosed brackets the
|
||||
/// user meant to close.
|
||||
fn value_runs_into_next_instance(&self) -> bool {
|
||||
let mut depth = 0u32;
|
||||
let mut candidate = false;
|
||||
let mut i = self.pos + 1;
|
||||
while let Some(t) = self.tokens.get(i) {
|
||||
if t.kind == TokenKind::Eof {
|
||||
break;
|
||||
}
|
||||
if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") {
|
||||
depth += 1;
|
||||
} else if t.is_sym(")") || t.is_sym("]") || t.is_sym("}") {
|
||||
if depth == 0 {
|
||||
return false;
|
||||
}
|
||||
depth -= 1;
|
||||
} else if depth == 0 {
|
||||
if t.is_sym(";") || is_sync_stop(t) {
|
||||
break;
|
||||
}
|
||||
if t.kind == TokenKind::Ident
|
||||
&& self.tokens[i - 1].line != t.line
|
||||
&& self.tokens.get(i + 1).is_some_and(|n| n.is_sym("("))
|
||||
{
|
||||
candidate = true;
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
candidate
|
||||
}
|
||||
|
||||
/// Consume the tokens up to `end_pos` as one verbatim expression.
|
||||
///
|
||||
/// [`Parser::open_conds`] is deliberately left alone: it counts *item*
|
||||
|
||||
@@ -275,6 +275,22 @@ impl<'a> Parser<'a> {
|
||||
self.expect_closer("endgenerate")?;
|
||||
Ok(ItemKind::GenerateRegion { items, dangling })
|
||||
}
|
||||
// A bare `begin … end` where an item belongs — at module scope or
|
||||
// straight inside a generate region. It is not a module item
|
||||
// (IEEE 1800 §23.2.1), so strict mode falls through to the
|
||||
// default arm and refuses it exactly as it always has. Tolerant
|
||||
// mode reads it the way every tool that accepts it does — as an
|
||||
// unnamed generate block — and still records the diagnostic, so
|
||||
// the file is reported as not parsing cleanly and the formatter
|
||||
// goes on emitting it unchanged. What is bought is the rest of
|
||||
// the body: without this the item fails, recovery skips to a sync
|
||||
// point and everything after the block is lost. The
|
||||
// `module-begin-block` and `v2001-generate-begin` lints read the
|
||||
// node.
|
||||
"begin" if self.tolerant => {
|
||||
self.record("`begin`/`end` block is not a module item");
|
||||
self.parse_gen_block().map(|b| ItemKind::GenBlock(Box::new(b)))
|
||||
}
|
||||
"if" => self.parse_gen_if().map(ItemKind::GenIf),
|
||||
"for" => self.parse_gen_for().map(|g| ItemKind::GenFor(Box::new(g))),
|
||||
"case" => self.parse_gen_case().map(ItemKind::GenCase),
|
||||
|
||||
@@ -67,13 +67,19 @@ pub(crate) fn error_file(source: &str) -> SourceFile {
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `t` closes, or opens, a construct an enclosing parse loop is
|
||||
/// responsible for. [`Parser::at_sync_stop`] asks it about the cursor; the
|
||||
/// lookaheads that walk raw tokens ahead of the cursor ask it about those.
|
||||
pub(super) fn is_sync_stop(t: &Token) -> bool {
|
||||
t.kind == TokenKind::Keyword
|
||||
&& (SYNC_CLOSERS.contains(&t.text.as_str()) || SYNC_OPENERS.contains(&t.text.as_str()))
|
||||
}
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
/// True when the cursor sits on a token recovery must not consume: it
|
||||
/// closes, or opens, a construct an enclosing loop is responsible for.
|
||||
pub(super) fn at_sync_stop(&self) -> bool {
|
||||
let t = self.cur();
|
||||
t.kind == TokenKind::Keyword
|
||||
&& (SYNC_CLOSERS.contains(&t.text.as_str()) || SYNC_OPENERS.contains(&t.text.as_str()))
|
||||
is_sync_stop(self.cur())
|
||||
}
|
||||
|
||||
/// True on any of the `join` keywords that close a `fork`.
|
||||
|
||||
@@ -14,7 +14,10 @@
|
||||
//! * 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;
|
||||
//! the list it is in. An element that gave up standing *on* a bracket
|
||||
//! opened one it never closed, so that bracket is taken before the skip
|
||||
//! starts rather than counted as a level of its own (see
|
||||
//! [`Parser::recover_element`]);
|
||||
//! * 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.
|
||||
@@ -245,6 +248,17 @@ impl<'a> Parser<'a> {
|
||||
// neither ends here nor eats a separator, so take one token to
|
||||
// guarantee it advances.
|
||||
self.bump();
|
||||
} else if self.at_open_bracket() {
|
||||
// The element gave up standing *on* a bracket, which is therefore
|
||||
// one it opened and never closed — the `(` of a half-typed
|
||||
// `.DEPTH(` (see `Parser::value_runs_into_next_instance`). That
|
||||
// bracket is part of the broken element, not a level the skip has
|
||||
// to balance: counting it would put the skip one level below the
|
||||
// list, where the line-change rule is not read, and the rest of
|
||||
// the body would be swallowed looking for a `)` that was never
|
||||
// written. Taken here, the skip starts inside it at the list's own
|
||||
// level and stops at the next line as it does everywhere else.
|
||||
self.bump();
|
||||
}
|
||||
self.skip_inside_brackets(false);
|
||||
let _ = self.take_dangling();
|
||||
@@ -253,6 +267,12 @@ impl<'a> Parser<'a> {
|
||||
RawText { text: self.slice(span), col, span }
|
||||
}
|
||||
|
||||
/// True on a token that opens a bracket.
|
||||
fn at_open_bracket(&self) -> bool {
|
||||
let t = self.cur();
|
||||
t.is_sym("(") || t.is_sym("[") || t.is_sym("{")
|
||||
}
|
||||
|
||||
/// 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).
|
||||
|
||||
@@ -67,6 +67,7 @@ fn collect_sva(items: &[vlog_parser::ast::Item], out: &mut Vec<(u32, u32)>) {
|
||||
ItemKind::Package { items, .. } => collect_sva(items, out),
|
||||
ItemKind::Class(c) => collect_sva(&c.items, out),
|
||||
ItemKind::GenerateRegion { items, .. } => collect_sva(items, out),
|
||||
ItemKind::GenBlock(b) => collect_sva(&b.items, out),
|
||||
ItemKind::GenIf(g) => {
|
||||
collect_sva(&g.then.items, out);
|
||||
match g.els.as_deref() {
|
||||
|
||||
@@ -101,6 +101,8 @@ const BROKEN: &[(&str, &str)] = &[
|
||||
("half-typed instantiation", "module m;\n sub u0 (.a(\nendmodule\n"),
|
||||
("garbage between modules", "module a;\nendmodule\n@#!\nmodule b;\n wire w;\nendmodule\n"),
|
||||
("error in generate", "module m;\ngenerate\n if (W) begin\n wire ;\n end\nendgenerate\n wire ok;\nendmodule\n"),
|
||||
("module-scope begin block", "module m;\n begin\n wire a;\n end\n wire b;\nendmodule\n"),
|
||||
("override runs into the next instance", "module m;\n sub #(.W(8), .D(\n u0 (.a(x));\nendmodule\n"),
|
||||
("all garbage", "!!! ???\n"),
|
||||
("stray endmodule", "endmodule\nmodule b;\nendmodule\n"),
|
||||
("unterminated string", "module m;\n initial $display(\"abc);\nendmodule\n"),
|
||||
@@ -190,6 +192,7 @@ fn walk_item(item: &Item, out: &mut Vec<(vlog_parser::TextRange, String)>) {
|
||||
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => {
|
||||
items.iter().for_each(|i| walk_item(i, out))
|
||||
}
|
||||
ItemKind::GenBlock(b) => b.items.iter().for_each(|i| walk_item(i, out)),
|
||||
ItemKind::GenIf(g) => walk_gen_if(g, out),
|
||||
ItemKind::GenFor(g) => g.body.items.iter().for_each(|i| walk_item(i, out)),
|
||||
ItemKind::GenCase(g) => {
|
||||
@@ -516,6 +519,90 @@ fn a_half_typed_instantiation_costs_one_connection() {
|
||||
assert_eq!(error_nodes(&file).len(), 1);
|
||||
}
|
||||
|
||||
/// The QA shape of 2026-09-02 (`docs/features/header-recovery/README.md`):
|
||||
/// a half-typed `#(` override whose value would read as the next instance.
|
||||
/// Nothing inside the list fails on its own — `u0 (.a(x), .b(y))` is a legal
|
||||
/// call with named arguments — so before §36.2 the greedy parse swallowed the
|
||||
/// instance and the whole instantiation collapsed into one error item that ate
|
||||
/// the `endmodule` too. It now costs the one override.
|
||||
#[test]
|
||||
fn a_half_typed_override_does_not_swallow_the_next_instance() {
|
||||
let src = "module m;\n sub #(.WIDTH(8), .DEPTH(\n u0 (.a(x), .b(y));\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
assert_eq!(&src[diags[0].span.as_range()], "(", "the diagnostic points at the unclosed `(`");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 1, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
|
||||
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
|
||||
panic!("{}", kind_name(&m.items[0]))
|
||||
};
|
||||
let params = inst.params.as_ref().expect("an override list");
|
||||
assert_eq!(params.len(), 2);
|
||||
assert_eq!(params[0].ok().map(|c| c.name.as_str()), Some("WIDTH"));
|
||||
assert_eq!(params[1].error().map(|r| r.text.as_str()), Some(".DEPTH("));
|
||||
assert_eq!(inst.instances.len(), 1);
|
||||
assert_eq!(inst.instances[0].name, "u0");
|
||||
let Connections::Named(conns) = &inst.instances[0].conns else { panic!("named connections") };
|
||||
assert_eq!(conns.len(), 2, "both connections of the instance survive");
|
||||
// The `endmodule` was consumed by the module, not by the error: one
|
||||
// diagnostic above already says so, and the module's span ends at it.
|
||||
assert_eq!(&src[m.items[0].span.as_range()], "sub #(.WIDTH(8), .DEPTH(\n u0 (.a(x), .b(y));");
|
||||
}
|
||||
|
||||
/// The same lookahead covers the connection list. `u1` cannot be a second
|
||||
/// instance of `sub` — no comma was written — so it becomes an item of the
|
||||
/// module, which is one error node instead of the whole rest of the body.
|
||||
#[test]
|
||||
fn a_half_typed_connection_does_not_swallow_the_next_instance() {
|
||||
let src = "module m;\n sub u0 (.a(\n u1 (.b(y));\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 2, "{diags:?}");
|
||||
assert_eq!(&src[diags[0].span.as_range()], "(");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 2, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
|
||||
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
|
||||
panic!("{}", kind_name(&m.items[0]))
|
||||
};
|
||||
let Connections::Named(conns) = &inst.instances[0].conns else { panic!("named connections") };
|
||||
assert_eq!(conns.len(), 1);
|
||||
assert_eq!(conns[0].error().map(|r| r.text.as_str()), Some(".a("));
|
||||
assert_eq!(error_nodes(&file).len(), 2, "the connection and the orphaned `u1 (...)`");
|
||||
}
|
||||
|
||||
/// The ambiguous shape stays ambiguous. With the parentheses balancing, the
|
||||
/// value *closes* — the lookahead says nothing is wrong and the greedy parse
|
||||
/// wins, exactly as before §36.2. Pinned so nobody "fixes" it: the parser
|
||||
/// cannot know whether the author meant a call or a forgotten `)`.
|
||||
#[test]
|
||||
fn a_connection_value_whose_parens_balance_is_still_read_greedily() {
|
||||
let src = "module m;\n sub #(.D(\n u0 (.a(x)));\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 2, "{diags:?}");
|
||||
assert!(diags.iter().all(|d| !d.message.contains("unclosed")), "{diags:?}");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 1);
|
||||
let ItemKind::Error(raw) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
|
||||
assert_eq!(raw.text, "sub #(.D(\n u0 (.a(x)));");
|
||||
}
|
||||
|
||||
/// A legal value written over three lines — whose middle line opens with an
|
||||
/// identifier followed by `(`, the very shape the lookahead hunts for — parses
|
||||
/// identically in both modes, because the value closes.
|
||||
#[test]
|
||||
fn a_legal_multi_line_connection_value_is_untouched() {
|
||||
let src = "module m;\n sub #(.DEPTH(\n f(1)\n )) u0 (.a(x));\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert!(diags.is_empty(), "{diags:?}");
|
||||
assert!(parse_source(src).is_ok(), "and strict mode reads it too");
|
||||
let m = module_named(&file, "m");
|
||||
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
|
||||
panic!("{}", kind_name(&m.items[0]))
|
||||
};
|
||||
let params = inst.params.as_ref().expect("an override list");
|
||||
assert_eq!(params.len(), 1);
|
||||
assert_eq!(params[0].ok().map(|c| c.name.as_str()), Some("DEPTH"));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Header recovery (TODO §32): one test per shape, with exact counts
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -713,6 +800,100 @@ fn an_error_in_a_generate_block_does_not_eat_the_endgenerate() {
|
||||
assert!(matches!(&m.items[1].kind, ItemKind::DataDecl(_)));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// A bare `begin … end` where an item belongs (TODO §36.1)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The block a `begin` opens at module scope is kept, with its items and with
|
||||
/// everything written after it. It is still an error — one diagnostic, at the
|
||||
/// keyword — so the formatter goes on refusing the file; what changed is that
|
||||
/// recovery no longer throws the rest of the module away.
|
||||
#[test]
|
||||
fn a_module_scope_begin_block_keeps_its_items_and_the_items_after_it() {
|
||||
let src = "module m;\n begin\n wire a;\n end\n assign b = 1;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
assert_eq!(&src[diags[0].span.as_range()], "begin");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 2, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
|
||||
let ItemKind::GenBlock(b) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
|
||||
assert!(b.is_block);
|
||||
assert_eq!(b.label, None);
|
||||
assert_eq!(b.items.len(), 1);
|
||||
assert!(matches!(&b.items[0].kind, ItemKind::DataDecl(_)), "{}", kind_name(&b.items[0]));
|
||||
assert!(matches!(&m.items[1].kind, ItemKind::ContAssign(_)), "{}", kind_name(&m.items[1]));
|
||||
assert!(error_nodes(&file).is_empty(), "the block is a node, not a leaf");
|
||||
}
|
||||
|
||||
/// The same one scope in: `generate begin … end endgenerate`. The region keeps
|
||||
/// its `endgenerate` and the module keeps the items after it.
|
||||
#[test]
|
||||
fn a_generate_region_begin_block_keeps_its_items_and_the_items_after_it() {
|
||||
let src = "module m;\n generate\n begin : g\n wire a;\n end\n \
|
||||
endgenerate\n wire ok;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
assert_eq!(&src[diags[0].span.as_range()], "begin");
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 2, "{:?}", m.items.iter().map(kind_name).collect::<Vec<_>>());
|
||||
let ItemKind::GenerateRegion { items, .. } = &m.items[0].kind else {
|
||||
panic!("{}", kind_name(&m.items[0]))
|
||||
};
|
||||
assert_eq!(items.len(), 1);
|
||||
let ItemKind::GenBlock(b) = &items[0].kind else { panic!("{}", kind_name(&items[0])) };
|
||||
assert_eq!(b.label.as_deref(), Some("g"));
|
||||
assert_eq!(b.items.len(), 1);
|
||||
assert!(matches!(&m.items[1].kind, ItemKind::DataDecl(_)), "{}", kind_name(&m.items[1]));
|
||||
}
|
||||
|
||||
/// Strict mode is untouched: both shapes are still a hard parse error, which
|
||||
/// is what keeps every corpus file byte-identical.
|
||||
#[test]
|
||||
fn strict_mode_still_refuses_a_bare_begin_block() {
|
||||
for src in [
|
||||
"module m;\n begin\n wire a;\n end\nendmodule\n",
|
||||
"module m;\n generate\n begin\n wire a;\n end\n endgenerate\nendmodule\n",
|
||||
] {
|
||||
let err = parse_source(src).expect_err("strict mode must refuse a bare `begin`");
|
||||
assert!(err.to_string().contains("begin"), "{err}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `end : label` on the recovered block lands in `end_label`, the way it does
|
||||
/// on any other generate block.
|
||||
#[test]
|
||||
fn a_bare_begin_block_keeps_its_end_label() {
|
||||
let src = "module m;\n begin : b\n wire a;\n end : b\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 1, "{diags:?}");
|
||||
let m = module_named(&file, "m");
|
||||
let ItemKind::GenBlock(b) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
|
||||
assert_eq!(b.label.as_deref(), Some("b"));
|
||||
assert_eq!(b.end_label.as_deref(), Some("b"));
|
||||
let label_span = b.end_label_span.expect("an end-label span");
|
||||
assert_eq!(&src[label_span.as_range()], "b");
|
||||
}
|
||||
|
||||
/// A block inside a block recovers the same way, once per keyword, and both
|
||||
/// blocks keep what was written in them.
|
||||
#[test]
|
||||
fn a_begin_block_nested_in_another_recovers_the_same_way() {
|
||||
let src = "module m;\n begin\n begin\n wire a;\n end\n end\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert_eq!(diags.len(), 2, "{diags:?}");
|
||||
for d in &diags {
|
||||
assert_eq!(&src[d.span.as_range()], "begin");
|
||||
}
|
||||
let m = module_named(&file, "m");
|
||||
assert_eq!(m.items.len(), 1);
|
||||
let ItemKind::GenBlock(outer) = &m.items[0].kind else { panic!("{}", kind_name(&m.items[0])) };
|
||||
assert_eq!(outer.items.len(), 1);
|
||||
let ItemKind::GenBlock(inner) = &outer.items[0].kind else {
|
||||
panic!("{}", kind_name(&outer.items[0]))
|
||||
};
|
||||
assert!(matches!(&inner.items[0].kind, ItemKind::DataDecl(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_of_only_garbage_is_one_error_item() {
|
||||
for src in ["!!! ???\n", "@@@\n", "?\n"] {
|
||||
|
||||
@@ -34,6 +34,7 @@ fn walk(items: &[Item], f: &mut dyn FnMut(&Item)) {
|
||||
ItemKind::Package { items, .. } => walk(items, f),
|
||||
ItemKind::Class(c) => walk(&c.items, f),
|
||||
ItemKind::GenerateRegion { items, .. } => walk(items, f),
|
||||
ItemKind::GenBlock(b) => walk(&b.items, f),
|
||||
ItemKind::GenFor(g) => walk(&g.body.items, f),
|
||||
ItemKind::GenIf(g) => {
|
||||
walk(&g.then.items, f);
|
||||
|
||||
@@ -565,6 +565,7 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
|
||||
check_item(src, i, here);
|
||||
}
|
||||
}
|
||||
ItemKind::GenBlock(b) => check_gen_block(src, b, here),
|
||||
ItemKind::Directive(raw) | ItemKind::MacroItem(MacroCall { raw, .. }) => {
|
||||
assert_inside(src, "raw text", raw.span, here);
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ pub use instantiate::{
|
||||
};
|
||||
pub use ports::{
|
||||
add_port, enclosing_module, may_have_port_action, port_action_modules, port_actions,
|
||||
propagate_ports, remove_port, ModuleRef, PortAction,
|
||||
propagate_ports, remove_port, sites_phrase, ModuleRef, PortAction,
|
||||
};
|
||||
pub use rename::{
|
||||
contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, RenameTarget,
|
||||
|
||||
@@ -150,6 +150,7 @@ pub(super) fn collect_instantiations<'t>(items: &'t [Item], out: &mut Vec<&'t In
|
||||
ItemKind::Module(module) => collect_instantiations(&module.items, out),
|
||||
ItemKind::Package { items, .. } => collect_instantiations(items, out),
|
||||
ItemKind::GenerateRegion { items, .. } => collect_instantiations(items, out),
|
||||
ItemKind::GenBlock(b) => collect_instantiations(&b.items, out),
|
||||
ItemKind::GenIf(gen) => {
|
||||
collect_gen_block(&gen.then, out);
|
||||
let mut els = gen.els.as_deref();
|
||||
|
||||
@@ -236,7 +236,12 @@ pub fn enclosing_module(text: &str, offset: u32) -> Option<String> {
|
||||
|
||||
/// "updates 3 instantiations" / "updates 1 instantiation" / "no instantiation
|
||||
/// in scope".
|
||||
fn sites_phrase(sites: usize) -> String {
|
||||
///
|
||||
/// Public because a server may have to write the same sentence with a count of
|
||||
/// its own: an offer that has not read the fan-out takes the number from its
|
||||
/// workspace index instead of from the plan, and the two must not come to be
|
||||
/// worded differently (`docs/features/lazy-code-action/README.md`).
|
||||
pub fn sites_phrase(sites: usize) -> String {
|
||||
match sites {
|
||||
0 => "no instantiation in scope".to_string(),
|
||||
1 => "updates 1 instantiation".to_string(),
|
||||
|
||||
@@ -128,6 +128,9 @@ impl<'a> Binder<'a> {
|
||||
let inner = self.new_scope(ScopeKind::Generate, scope, item.span);
|
||||
self.bind_items(items, inner);
|
||||
}
|
||||
// A bare `begin … end` where an item belongs: bound as the
|
||||
// unnamed generate scope an unlabeled `if` arm's block gets.
|
||||
ItemKind::GenBlock(b) => self.bind_gen_block(b, scope),
|
||||
ItemKind::GenIf(g) => self.bind_gen_if(g, scope),
|
||||
ItemKind::GenFor(g) => self.bind_gen_for(g, item.span, scope),
|
||||
ItemKind::GenCase(g) => {
|
||||
|
||||
@@ -77,6 +77,7 @@ fn walk<'a>(items: &'a [Item], owner: Option<Decl<'a>>, out: &mut Vec<Site<'a>>)
|
||||
}
|
||||
ItemKind::Package { items, .. } => walk(items, owner, out),
|
||||
ItemKind::GenerateRegion { items, .. } => walk(items, owner, out),
|
||||
ItemKind::GenBlock(b) => block(b, owner, out),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
block(&gen_if.then, owner, out);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
|
||||
@@ -162,3 +162,35 @@ mid-line list positions (port/parameter lists, `case` label lists) stay
|
||||
inert, because a column-0 verbatim slice has no place inside a `Group`. The
|
||||
three stale READMEs named under the order were reconciled in the 0.33.0
|
||||
documentation pass.
|
||||
|
||||
## Linter addendum (2026-09-04, TODO §35)
|
||||
|
||||
Three waves of linter expansion (§33, §34, §35) took the registry from 17
|
||||
rules to **73**, and with §35 lucisv implements **every rule in Verible's
|
||||
published list except one**: `forbid-implicit-declarations`, which needs the
|
||||
elaboration-order model lucisv does not have. Each rule cites its Verible
|
||||
name, description and default in its own `doc`; `lucisv check --rules-doc` is
|
||||
the generated truth.
|
||||
|
||||
Three coverage notes the wave produced, none of them a language gap:
|
||||
|
||||
- **`begin` where an item belongs is a parser gap, not a rule gap.** The
|
||||
parser refuses a module-scope `begin … end` and a bare `begin` inside a
|
||||
`generate` region rather than recovering either as a block, so recovery
|
||||
unwinds and the rest of that unit is lost — `module-begin-block` and
|
||||
`v2001-generate-begin` read the error leaf instead of a tree. Both
|
||||
constructs are illegal (the first) or legacy (the second), so the finding
|
||||
itself is exact; what is lost is every *other* rule's view of that file.
|
||||
Filed here as the linter's one remaining "the rule reads a gap between
|
||||
tokens" case, for a future parser round to recover as a labelled generate
|
||||
block.
|
||||
- **An `.svh` fragment included into a class body is judged as file scope.**
|
||||
`explicit-function-lifetime` / `explicit-task-lifetime` report methods in a
|
||||
fragment that only becomes a class body after `` `include``. Verible, which
|
||||
also lints one file at a time, reports the same; 39 of the two rules' 101
|
||||
opentitan findings are that shape. Not fixable without following includes,
|
||||
which is the same boundary `docs/features/fragment-mode/README.md` records.
|
||||
- **Verible's `forbidden-symbol` is not a rule.** It is the name of the
|
||||
source file Verible implements `invalid-system-task-function` in. lucisv
|
||||
ships one rule with the list as its `symbols` option rather than two rules
|
||||
that would both fire on `$psprintf`.
|
||||
@@ -326,6 +326,20 @@ linter; master's linter has since grown 36 rules, `Severity` on `Rule` and new
|
||||
files, so those three arms need re-applying to master's versions of the two
|
||||
files at merge. Nothing else in this branch touches `crates/vlog_linter`.
|
||||
|
||||
**2026-09-04 — the MEDIUM QA finding below is fixed (TODO §36.2).** The
|
||||
half-typed `#(` override whose value reads as the next instance
|
||||
(`sub #(.WIDTH(8), .DEPTH(` ⏎ `u0 (.a(x), .b(y));`) now costs the one
|
||||
override element and nothing else: `.WIDTH(8)` survives as `Ok`, `.DEPTH(`
|
||||
is the error element, `u0` keeps both its connections and the module keeps
|
||||
its `endmodule`, on one diagnostic at the unclosed `(`. The fix is one
|
||||
tolerant-mode lookahead in `Parser::parse_connection`
|
||||
(`value_runs_into_next_instance`) plus the bracket the skip in
|
||||
`recover_element` now takes when an element gives up standing on one. See
|
||||
`docs/features/small-items-3/README.md`; the shape is pinned by
|
||||
`a_half_typed_override_does_not_swallow_the_next_instance` in
|
||||
`crates/vlog_parser/tests/error_recovery.rs`, with the balanced-parens
|
||||
control beside it (that one is still read greedily, deliberately).
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-04 — QA agent
|
||||
|
||||
@@ -0,0 +1,573 @@
|
||||
# lazy-code-action
|
||||
|
||||
TODO §37 — the three server residues left over from §10: the lazy
|
||||
`codeAction/resolve` for the port refactorings (§37.1), the `inlayHint` zero at
|
||||
the default scope (§37.2), and `locate::location` onto `DeclPositions`
|
||||
(§37.3). One README, one section each.
|
||||
|
||||
## Goal
|
||||
|
||||
**§37.1.** `textDocument/codeAction` arrives on nearly every cursor move, and
|
||||
the port refactorings answered it by computing the *whole* edit — over the
|
||||
instantiated module's entire fan-out plus every open buffer, each file read as
|
||||
text. `docs/performance_take2.md` §6a measured what that costs on opentitan:
|
||||
~1.4 ms per instantiating file plus a ~13 ms floor, **185–201 ms at a 128-file
|
||||
fan-out, to offer zero actions**, above §3's "reads as a hang" line, on the hot
|
||||
path. The *offer* is now local — the buffer, plus the instantiated module's own
|
||||
declaration when the cursor is on an instantiation — and the edit is computed
|
||||
by `codeAction/resolve` when the user picks the action. A client that cannot
|
||||
resolve is unaffected: it still gets the edit up front.
|
||||
|
||||
**§37.2.** `inlayHint` returns 0 hints at the default (folder) scope where the
|
||||
workspace scope returns 4 (`performance_take2.md` §4b, §8.9), the one §4b row
|
||||
the `didOpen` widen did not fix. Investigated, and it is **not a bug** — the
|
||||
finding is written out below, with two tests that pin it.
|
||||
|
||||
**§37.3.** Every file-scope declaration's client-side range is already in the
|
||||
index (`DeclPositions`, added by the design-hierarchy round), so
|
||||
`textDocument/definition` and `workspace/symbol` need not read a file to
|
||||
convert an indexed span. They no longer do: **27.7 µs → 0.40 µs per
|
||||
definition** on opentitan.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The offer may be optimistic; the resolve is exact.** A refusal the engine
|
||||
can only see over the fan-out — an instantiation elsewhere connecting `sub`'s
|
||||
ports *by position*, which makes `remove_port` refuse whole — is invisible to
|
||||
a one-file offer, so the lightbulb can appear and the resolve then decline
|
||||
with "the action is no longer available". This is the trade LSP's resolve
|
||||
model is for; the alternative is the 185 ms. The refusals cheap enough to
|
||||
keep are kept: a module the index declares twice is checked through
|
||||
`WorkspaceIndex::units` before anything is offered, exactly as the eager path
|
||||
refuses over the two declaring files it reads.
|
||||
- **The count in an offered title comes from the index and may be one behind.**
|
||||
`instantiations_of(name)` records one edge per *written statement* with its
|
||||
instances, and the title counts **instances** (`sub u1(), u2();` is two), to
|
||||
match what the eager title counts — the instances the plan really rewrites.
|
||||
The two disagree exactly where the index cannot know: an unsaved buffer's new
|
||||
instantiation, a file-scope instantiation site (which records no edge at
|
||||
all), an instance connecting with `.*`. So the offered and resolved actions
|
||||
are matched on the title *without* its count phrase (`ports::key`), and the
|
||||
resolved action carries the exact title.
|
||||
- **`Def::lines.positions` is `Some` for every file-scope declaration and
|
||||
`None` for every member**, as `DeclLines` documents. §37.3 relies on that:
|
||||
members keep the file-read path, which is not a fallback nobody takes — it is
|
||||
the only answer a port has.
|
||||
- **`codeAction/resolve` carries no `textDocument`**, so the large-file fast
|
||||
path's gate — which reads a URI out of the params — never sees it. `resolve`
|
||||
refuses a buffer on that fast path itself: the mode's contract is that a
|
||||
large buffer is never parsed, and one stale lightbulb is not a reason to
|
||||
break it.
|
||||
- An **open buffer** keeps the file-read path in §37.3 whatever the index
|
||||
recorded, because the buffer's text may have moved since it was indexed and
|
||||
every other answer about that buffer is computed against the text it holds
|
||||
now.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **`vlog_refactor` → server.** `ports::sites_phrase` is now `pub` (re-exported
|
||||
from the crate root as `vlog_refactor::sites_phrase`). The server writes the
|
||||
same sentence with a count of its own, and one spelling of a user-visible
|
||||
string is the point. Nothing else in `vlog_refactor` changed; `port_actions`,
|
||||
`port_action_modules` and `module_definition` are consumed exactly as before.
|
||||
- **`Workspace` → server.** `Workspace::held_views()` added, `#[cfg(test)]`
|
||||
and `pub(crate)`: the view cache is how a test asserts that an answer read no
|
||||
file. No production caller.
|
||||
- **`main.rs` → `server`.** `ClientAbilities` gains `code_action_resolve`, read
|
||||
at `initialize` from `textDocument.codeAction.resolveSupport.properties`
|
||||
containing `"edit"`. The `initialize` result advertises
|
||||
`codeActionProvider.resolveProvider: true` unconditionally — the server can
|
||||
always answer a resolve, including for an action that already carries its
|
||||
edit, which it hands straight back.
|
||||
- **The wire.** New method answered: `codeAction/resolve`. New field on an
|
||||
offered port action: `data` (`{uri, position, title}`), opaque to the client.
|
||||
The quick fixes in `code_action.rs` are unchanged and still complete when
|
||||
offered.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] §37.1 `ports::offers` — the local offer, titles counted from the index,
|
||||
`data` instead of an edit.
|
||||
- [x] §37.1 `ports::resolve` — today's eager answer at the offer's position,
|
||||
matched on `key(title)`; `RequestFailed` with "the action is no longer
|
||||
available." when nothing matches, and a distinct sentence for an action
|
||||
this server never offered.
|
||||
- [x] §37.1 capability gate: `code_action_resolve_support` in `main.rs`,
|
||||
`ClientAbilities::code_action_resolve`, the dispatch branch.
|
||||
- [x] §37.1 `resolve_provider: Some(true)` advertised; `codeAction/resolve`
|
||||
dispatch arm.
|
||||
- [x] §37.1 tests: the offer's menu equals the eager one over `crowded(40)`;
|
||||
the offer's source set is the buffer (+ the declaring file); the resolved
|
||||
edit is byte-equal to the eager one at both cursor shapes; the unsaved
|
||||
buffer answered by the resolve; a stale and a closed document refused; a
|
||||
foreign action refused; a complete action returned untouched; the
|
||||
duplicate-declaration refusal; a buffer that grew onto the large-file
|
||||
fast path; `key`'s own unit test.
|
||||
- [x] §37.1 e2e over the wire, both client shapes.
|
||||
- [x] §37.1 perf: the "offer" column on `perf.rs`'s
|
||||
`a_code_action_at_an_instantiation_before_and_after`, plus
|
||||
`ports::tests::the_offer_is_flat_where_the_eager_answer_grows`
|
||||
(3/40/128 instantiators, both cursor shapes).
|
||||
- [x] §37.2 investigated; finding written below; two tests at the default
|
||||
scope.
|
||||
- [x] §37.3 `locate::definition_location`, routed through `nav::definition`
|
||||
and `symbols::workspace_symbols`.
|
||||
- [x] §37.3 pins: the encoding shapes, no `file_view` created, members keep
|
||||
the read, the open-buffer case.
|
||||
- [x] §37.3 opentitan timing, read-only
|
||||
(`locate::tests::defining_over_a_real_project`).
|
||||
- [ ] Not done, deliberately: **memoising `module_sources`** per (module, index
|
||||
generation), take 1's other suggestion. The offer makes it unnecessary on
|
||||
the hot path — the fan-out is now read once per *click* — and a cache
|
||||
keyed on a generation is a staleness question this round did not need to
|
||||
open.
|
||||
- [ ] Not done, deliberately: **the quick fixes stay eager.** They are built
|
||||
from the buffer's own violations, which the server has already computed
|
||||
for the diagnostics; there is nothing to defer.
|
||||
|
||||
## §37.1 — how the offer stays local
|
||||
|
||||
`ports::offers` runs the engine's own `port_actions` over a source set built by
|
||||
`ports::offer_sources`:
|
||||
|
||||
1. **the buffer the request names**, from the open document (no read);
|
||||
2. **the declaring file of every module `port_action_modules` named**, via
|
||||
`vlog_refactor::module_definition(index, name)` — the same two steps
|
||||
`inlay.rs`'s `Plans::read` takes, and one file read at most.
|
||||
|
||||
A cursor on a **port declaration** names its own module, whose declaring file
|
||||
*is* the buffer, so that case reads nothing at all. A cursor on an
|
||||
**instantiation** names the instantiated module, and its declaration is what
|
||||
`propagate_ports` needs to know which connections are missing — so the offer
|
||||
is exact for that action, including its "connect N missing ports" count, which
|
||||
is a count of edits in the cursor's own file.
|
||||
|
||||
The edits `port_actions` computes over those one or two files are thrown away.
|
||||
Only the titles and the kind survive, plus `data`.
|
||||
|
||||
`ports::resolve` re-runs `ports::code_actions` — today's eager path, unchanged
|
||||
— at the offer's position and returns the action whose `key(title)` matches.
|
||||
|
||||
### Measured
|
||||
|
||||
This machine, 2026-09-04, release.
|
||||
|
||||
`cargo test --release -p lucisv_server perf::a_code_action -- --ignored
|
||||
--nocapture --test-threads=1` — the original probe (a port of a module
|
||||
instantiated in 3 of 504 files, 200 lines each), now with the offer column
|
||||
TODO §37.1 asked for:
|
||||
|
||||
| whole workspace | fan-out (eager) | **offer** | `sources()` alone |
|
||||
|---:|---:|---:|---:|
|
||||
| 776 ms | 433 µs | **58 µs** | 11.5 ms |
|
||||
|
||||
`cargo test --release -p lucisv_server --bin lucisv-server
|
||||
ports::tests::the_offer_is_flat -- --ignored --nocapture --test-threads=1` —
|
||||
200 noise modules plus `n` files instantiating `sub`, the shape §6a measured
|
||||
on opentitan:
|
||||
|
||||
| fan-out | cursor | eager | **offer** | actions |
|
||||
|---:|---|---:|---:|---:|
|
||||
| 3 | a port declaration | 485 µs | **68 µs** | 1 |
|
||||
| 3 | an instantiation | 172 µs | **72 µs** | 0 |
|
||||
| 40 | a port declaration | 4.84 ms | **53 µs** | 1 |
|
||||
| 40 | an instantiation | 1.45 ms | **55 µs** | 0 |
|
||||
| 128 | a port declaration | 15.0 ms | **53 µs** | 1 |
|
||||
| 128 | an instantiation | 4.60 ms | **55 µs** | 0 |
|
||||
|
||||
The eager column grows with the fan-out and the offer column does not: 53–72 µs
|
||||
at every size, both cursors (the two 3-file rows are the first measurements
|
||||
taken in the process and carry that much warm-up). The two "0 actions" rows are
|
||||
§6a's own complaint — a cursor on a fully-connected instantiation, where the old
|
||||
path spent its whole bill to offer nothing.
|
||||
|
||||
## §37.2 — the `inlayHint` zero at the default scope is correct
|
||||
|
||||
**Finding: not a bug. `performance_take2.md` §4b's last row compares a
|
||||
different question from every row above it.**
|
||||
|
||||
Every other row of that table asks about `aes` — `definition`, `hover`,
|
||||
`signatureHelp`, `references` on the `aes` instantiation in
|
||||
`hw/ip/aes/dv/tb/tb.sv`. `aes` is declared in `hw/ip/aes/rtl/aes.sv`, which the
|
||||
`didOpen` widen reaches: opening `hw/ip/aes/dv/tb/tb.sv` at the shipped
|
||||
`scopeDepth` of 2 raises to `hw/ip/aes`, 124 files. So those rows answer.
|
||||
|
||||
`inlayHint` cannot ask about `aes` at all: that instantiation's connections are
|
||||
**named** (`.clk_i(clk)`), and a named connection gets no hint by design — the
|
||||
reader can already see which port is which. The only positional connections in
|
||||
`tb.sv` are:
|
||||
|
||||
```systemverilog
|
||||
pins_if #($bits(lc_escalate)) lc_escalate_if (lc_escalate);
|
||||
pins_if #(1) idle_if (idle);
|
||||
```
|
||||
|
||||
Two positional parameter overrides and two positional port connections — **the
|
||||
4 hints the workspace scope returns**. `pins_if` is declared in
|
||||
`hw/dv/sv/common_ifs/pins_if.sv`; there is no `pins_if` anywhere under
|
||||
`hw/ip/aes` (checked). So at the default scope the module is genuinely not in
|
||||
the index, `vlog_refactor::module_definition` has nothing to answer with, and
|
||||
`Plans::read` declines — which is the documented contract: an instantiation
|
||||
whose module the index does not hold gets no hints, because guessing port names
|
||||
puts a wrong name on screen with no way for the reader to tell.
|
||||
|
||||
`inlay.rs` uses **the same lookup its neighbours use**. `signature.rs:28` and
|
||||
`completion`'s module-header tier call `vlog_refactor::module_definition` on the
|
||||
same index; hover and definition go through the same overlay. Asked about
|
||||
`pins_if` at the default scope, every one of them answers nothing too. There is
|
||||
no lookup inlay is missing.
|
||||
|
||||
Two tests pin it (`inlay.rs`), on an opentitan-shaped tree — `ip/aes/rtl`,
|
||||
`ip/aes/dv/tb`, and a `dv/common` beside the block:
|
||||
|
||||
- `the_default_scope_hints_a_module_the_didopen_widen_reached` — at the
|
||||
**default** scope (no `index.scope`, `scopeDepth` 2), the instantiation of the
|
||||
block's own module is hinted. The default scope hints; §4b's row is not
|
||||
evidence that it does not.
|
||||
- `an_out_of_scope_module_is_unhinted_exactly_as_it_is_undefined` — the
|
||||
instantiation of the module outside the block gets no hints, **and**
|
||||
`textDocument/definition` and hover give nothing for it either; widening to
|
||||
the workspace scope makes all three answer.
|
||||
|
||||
For the lead: if the wanted behaviour is that a hint pulls its module's
|
||||
declaration in from outside the scope, that is a *scope* change (the widen
|
||||
would have to follow instantiation edges), and it would change what
|
||||
`definition`, `hover` and `completion` answer at the same time. It is not an
|
||||
inlay-hint fix, and it is not what this round did.
|
||||
|
||||
## §37.3 — `locate::definition_location`
|
||||
|
||||
`Def::lines.positions` holds `{name, decl}` as `Utf16Range`s, converted through
|
||||
the declaring file's own `LineIndex::utf16_position` while it was indexed —
|
||||
which is the very converter `convert::Positions` uses on the wire, so the two
|
||||
cannot disagree. `locate::definition_location(ws, path, def)` returns the name's
|
||||
range straight from there when the file has no open buffer, and falls through to
|
||||
`locate::location`'s read otherwise (an open buffer, or a member, which records
|
||||
no positions).
|
||||
|
||||
Routed through: `nav::definition`'s `Definition::External` arm and
|
||||
`symbols::workspace_symbols`. `nav`'s `` `define`` arm keeps the read — a
|
||||
`DefineTable` entry is not a `Def` and has no recorded positions.
|
||||
|
||||
### Pins
|
||||
|
||||
- `locate::tests::the_two_paths_agree_over_multi_byte_astral_crlf_and_a_bom` —
|
||||
one file with a BOM at offset 0, CRLF endings, two- and three-byte
|
||||
characters and an astral character that is two UTF-16 code units; the
|
||||
index-only `Location` equals the file-read one exactly.
|
||||
- `locate::tests::a_file_scope_definition_is_located_without_reading_its_file`
|
||||
and `nav::tests::a_cross_file_definition_reads_no_file` — asserted through
|
||||
`Workspace::held_views()`, the view cache a read would land in. Empty after
|
||||
the definition and after a `workspace/symbol`; one entry after the same
|
||||
question is asked the old way.
|
||||
- `locate::tests::a_member_keeps_the_file_read_path` — a port records no
|
||||
positions and still answers, through the read.
|
||||
- `locate::tests::an_open_buffer_still_answers_from_the_buffer`.
|
||||
|
||||
### Measured, over opentitan, read-only
|
||||
|
||||
`LUCISV_PERF_CORPUS=/Users/guoliangchen/repo/opentitan cargo test --release -p
|
||||
lucisv_server --bin lucisv-server locate::tests::defining -- --ignored
|
||||
--nocapture --test-threads=1`, 3 976 indexed files, 200 targets (modules the
|
||||
corpus instantiates, each in a different file):
|
||||
|
||||
| | total, 200 definitions | per definition |
|
||||
|---|---:|---:|
|
||||
| file-read (before) | 5.54 ms | 27.7 µs |
|
||||
| index-only (after) | 80.5 µs | **0.40 µs** |
|
||||
|
||||
69× on the conversion, and it is the whole of what a cross-file
|
||||
`textDocument/definition` into a closed file was doing besides the lookup.
|
||||
`git -C ~/repo/opentitan status --porcelain` unchanged after the run.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-04 — dev agent (Opus)
|
||||
|
||||
- Read `CLAUDE.md`, TODO §37 and the §10 lines it closes,
|
||||
`docs/performance_take2.md` §4b/§6a/§7/§8, and the code each item names.
|
||||
- **§37.3 first** (smallest, independent). `locate::definition_location` plus
|
||||
`locate::range`; `state.rs` gained `held_views()` (`#[cfg(test)]`,
|
||||
`pub(crate)`) so a test can assert that no file was read. Routed
|
||||
`nav::definition` and `symbols::workspace_symbols` through it. Four tests in
|
||||
`locate.rs` (new test module) and one in `nav.rs`.
|
||||
- Deviation from the plan's expectation, recorded: the plan said "no
|
||||
`file_view` created for a file-scope definition"; the assertion is through
|
||||
`Workspace::held_views()`, a new test-only accessor, rather than a
|
||||
counter — the cache *is* the counter, and it is already what `state.rs`'s
|
||||
own tests assert against.
|
||||
- One thing the plan did not anticipate: an **open buffer** must keep the
|
||||
file-read path. Its `Def` spans are the disk file's until the next
|
||||
re-index, and converting them against the buffer's current text is what
|
||||
every other answer about that buffer does. Pinned by
|
||||
`an_open_buffer_still_answers_from_the_buffer`, which asserts the
|
||||
(pre-existing, unchanged) stale-span behaviour rather than pretending this
|
||||
round fixed it.
|
||||
- **§37.2 second.** Investigated by reading `hw/ip/aes/dv/tb/tb.sv` and
|
||||
locating `pins_if` in the opentitan checkout (read-only, `find`/`ls` only).
|
||||
The zero is correct; the finding is written above, with two tests. No
|
||||
production code changed for this item.
|
||||
- **§37.1 last.** `ports::offers`, `ports::offer_sources`, `ports::resolve`,
|
||||
`ports::key`, `ports::counted`, `ports::instances_of`,
|
||||
`ports::declared_twice`; `ClientAbilities::code_action_resolve`;
|
||||
`code_action_resolve_support` in `main.rs`; `resolve_provider: Some(true)`;
|
||||
the dispatch branch and the `codeAction/resolve` arm.
|
||||
- **Deviation, flagged:** `vlog_refactor::ports::sites_phrase` was made
|
||||
`pub` and re-exported. The plan allowed a change to
|
||||
`crates/vlog_refactor/src/ports/mod.rs` "only if the offer needs a new
|
||||
one-file question", and this is not one — it is the alternative to writing
|
||||
a second spelling of a user-visible sentence in the server and letting the
|
||||
two drift. No behaviour changed in `vlog_refactor`.
|
||||
- **Deviation, flagged:** the plan said resolve returns "the action whose
|
||||
title matches". Exact title matching cannot work, because the offer's
|
||||
count comes from the index and the eager count from the plan, and the
|
||||
plan's own §37.1 requires the unsaved-buffer case (index 3, plan 4) to
|
||||
resolve. Matching is therefore on `key(title)` — the title with its
|
||||
trailing ` (…)` count phrase removed. An escaped identifier cannot contain
|
||||
a space, so `" ("` never occurs inside a port name; `a_title_keys_on_
|
||||
everything_but_its_count` pins it.
|
||||
- **Deviation, flagged:** `resolve` returns an action that already carries an
|
||||
`edit` unchanged instead of refusing it. A client that declares
|
||||
`resolveSupport` may resolve anything it was offered, including the quick
|
||||
fixes, and refusing those would break fix-on-save for exactly the clients
|
||||
this feature is for.
|
||||
- `resolve` refuses a large-file buffer, because the fast path's own gate
|
||||
cannot see a request whose params are a `CodeAction`. Found by reading
|
||||
`server/large_file.rs`'s `document_uri`, not by a test failing; pinned by
|
||||
`a_resolve_against_a_buffer_on_the_large_file_fast_path_is_refused`.
|
||||
- The existing eager pin `an_unsaved_buffer_contributes_the_instantiation_
|
||||
the_index_has_not_seen` was **kept** rather than moved: the eager path is
|
||||
still live code for a client without `resolveSupport`. Its lazy sibling
|
||||
`the_resolved_edit_sees_an_unsaved_buffer_the_offer_could_not_count` is the
|
||||
moved pin.
|
||||
- **The two new perf probes live beside the code they measure**, not in
|
||||
`perf.rs`: `perf.rs` is already the one file over the size rule with a
|
||||
written reason (895 production lines, `docs/features/decomposition-server`),
|
||||
and `perf::mean` is `pub(crate)` precisely so a probe can sit next to its
|
||||
subject — `nav.rs`'s references probes already do. `perf.rs` grew by the
|
||||
five lines of the offer column and nothing else (900 lines).
|
||||
- Files touched outside the plan's expected set: **none**
|
||||
(`crates/vlog_refactor/src/lib.rs` for the re-export is the only file not
|
||||
named in it; `crates/vlog_refactor/src/ports/mod.rs` was named).
|
||||
|
||||
## Gates (dev, guarded, 2026-09-04)
|
||||
|
||||
- `cargo fmt -p lucisv_server`, `cargo fmt -p vlog_refactor` — clean
|
||||
(`--check` verified).
|
||||
- `cargo clippy --all-targets` — clean, no new `#[allow]`.
|
||||
- `tools/guard.sh -- cargo test --workspace` — **3 734 passed, 0 failed,
|
||||
44 ignored** (the ignored are the perf probes).
|
||||
- `tools/guard.sh -- tools/corpus_check.sh` — **814/820 (99.3 %)**, the same
|
||||
six failures, `verification-error: none`, `crash: none`.
|
||||
- `cargo build --release -p lucisv_server` then `tools/guard.sh -- node
|
||||
editors/vscode/smoke.js target/release/lucisv-server` — OK, 20 messages.
|
||||
- No guard kill at any point. `git -C ~/repo/opentitan status --porcelain`
|
||||
after every opentitan read: the same three pre-existing modifications
|
||||
(`hw/ip/aes/dv/tb/tb.sv`, both `ast.sv`), nothing else.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-04 — QA agent (Sonnet)
|
||||
|
||||
Read `CLAUDE.md`, TODO §37, the dev's account above in full (Goal, Assumptions,
|
||||
Handshakes, work log — all five flagged deviations), then the diffs of every
|
||||
touched file. Attacked the three items over the real code, not just the
|
||||
dev's own tests; every scratch test below was added as a temporary `#[test]`,
|
||||
run, and removed before this log was written (`git diff --stat` after cleanup
|
||||
is byte-identical to the dev's own: 15 modified + this README).
|
||||
|
||||
**§37.1 — lazy `codeAction`/`resolve`.**
|
||||
|
||||
- Malformed `data` (scratch test in `ports.rs`): a wrong-typed `uri` (a JSON
|
||||
number) fails to deserialize into `Offer` → `NOT_OURS`; a well-formed `data`
|
||||
naming a document **never opened at all** (distinct from one that was open
|
||||
and closed) → `GONE`; a `position` far past EOF → `Positions::offset` clamps
|
||||
to the text length (confirmed by reading `convert.rs:44-59`) rather than
|
||||
panicking, `code_actions` at the clamped offset finds nothing, → `GONE`. No
|
||||
panic in any case.
|
||||
- A closed document and a document whose port has since been removed: both
|
||||
already pinned by the dev's `a_resolve_of_an_action_the_buffer_no_longer_
|
||||
carries_is_refused`; reproduced by re-running it directly.
|
||||
- The unsaved-buffer "different count" case (index says 3, buffer really has
|
||||
4): the dev's `the_resolved_edit_sees_an_unsaved_buffer_the_offer_could_not_
|
||||
see` is exactly this attack — re-run, still resolves with the corrected
|
||||
title and the wider edit.
|
||||
- A quick-fix action passed to `resolve`: `code_action.rs`'s `quick_fix`
|
||||
(line ~76) always sets `edit: Some(...)`, so it always takes `resolve`'s
|
||||
first branch (`action.edit.is_some()` → returned unchanged) regardless of
|
||||
origin — confirmed by reading the function rather than by a redundant
|
||||
integration test, since the logic path is identical to the dev's own
|
||||
synthetic "complete" case in `a_resolve_of_something_this_server_never_
|
||||
offered_says_so`.
|
||||
- Title-key matching with an escaped identifier containing `(` and no interior
|
||||
space (`\rst(a)`, IEEE 1800-2017 §5.6.1 — an escaped identifier ends at
|
||||
whitespace): built a real module with this port name, instantiated it in
|
||||
three files, and drove the actual engine (not a hand-built title) through
|
||||
`offered`/`code_actions`/`resolve`. The offer's menu matched the eager
|
||||
menu, the title genuinely carried the literal `` `\rst(a)` `` including the
|
||||
paren, and `key()` still isolated the trailing count phrase correctly — the
|
||||
dev's reasoning in the comment on `key` holds under an adversarial name.
|
||||
(One test-authoring pitfall found and fixed on my own scratch test, not a
|
||||
product bug: `ports.rs`'s pre-existing `qa_escaped_module_name_
|
||||
instantiation_parity_with_whole_workspace` also builds a `Tree::new(
|
||||
"qa_escaped")`, and reusing that same name in my own scratch test raced the
|
||||
two tests over the same temp directory under parallel `cargo test`
|
||||
execution, producing spurious failures in both. Renamed my scratch tree and
|
||||
the collision was gone on repeated runs. `Tree::new` keys its temp directory
|
||||
on the string name alone with no per-test-function salt, which is a latent
|
||||
hazard for the *next* test added under the same name — not something this
|
||||
feature's diff introduced or should fix, flagging it here rather than in
|
||||
the diff.)
|
||||
- Capability gate over the wire (scratch test in `tests/e2e.rs`, two shapes in
|
||||
one loop): `resolveSupport` present but its `properties` list `["documentation"]`
|
||||
(no `"edit"`), and `capabilities: {}` with no `codeAction` key at all. Both
|
||||
got the eager shape — `data` null, `edit` inline with the real
|
||||
`WorkspaceEdit` — over an actual `initialize` → `didOpen` →
|
||||
`textDocument/codeAction` session, not just the unit test of
|
||||
`code_action_resolve_support` in isolation.
|
||||
- Large-file mode: confirmed by reading `server/large_file.rs`'s
|
||||
`document_uri` (`params.get("textDocument")?...`) — a `codeAction/resolve`
|
||||
request's params are a bare `CodeAction`, which has no `textDocument` key,
|
||||
so `large_file_answer` returns `None` unconditionally for this method and
|
||||
the request falls through to `dispatch.rs`'s normal arm, where `ports::
|
||||
resolve`'s own `.filter(|doc| !doc.large)` refuses it. Re-ran the dev's
|
||||
`a_resolve_against_a_buffer_on_the_large_file_fast_path_is_refused` — passes,
|
||||
no panic.
|
||||
- Cost/timing, re-derived independently over the wire against the real
|
||||
opentitan checkout (confirmed still 128 files instantiate `prim_flop_2sync`
|
||||
today via `grep`), read-only throughout:
|
||||
- Built `lucisv-server` v0.40.0 in a scratch worktree
|
||||
(`git worktree add /private/tmp/.../scratchpad/base v0.40.0`, `cargo build
|
||||
--release -p lucisv_server`, then `git worktree remove` — the one git
|
||||
command used outside status/diff), and wrote a small throwaway Node driver
|
||||
(`scratchpad/time_code_action.js`, modeled on `editors/vscode/smoke.js`'s
|
||||
framing) to time a real `textDocument/codeAction` at the
|
||||
`prim_flop_2sync` instantiation in `hw/ip/aon_timer/rtl/aon_timer.sv`,
|
||||
workspace-scoped via `initializationOptions.lucisv.index.scope`.
|
||||
- v0.40.0 server, eager (no `resolveSupport`): 76.4 / 76.4 / 77.8 ms repeats.
|
||||
- This branch's server, eager (no `resolveSupport`): 77.3 / 76.2 / 77.7 ms
|
||||
repeats — statistically identical to v0.40.0, confirming no regression for
|
||||
a client that cannot resolve.
|
||||
- This branch's server, **offer** (`resolveSupport: ["edit"]`): 4.76 / 4.38
|
||||
/ 4.25 ms repeats — about **16× faster**, both with 0 actions returned
|
||||
(the same "worst case: full cost, nothing offered" shape §6a complained
|
||||
about).
|
||||
- Also re-ran the dev's own ignored perf probe
|
||||
(`ports::tests::the_offer_is_flat_where_the_eager_answer_grows`) directly:
|
||||
eager 656 µs–15.6 ms across 3/40/128 fan-out, offer 55–78 µs flat — closely
|
||||
matches the table in this README (§37.1 "Measured").
|
||||
- **Note, not a finding against this feature:** my repeat numbers (~76 ms
|
||||
eager) are well under `performance_take2.md` §6a's originally recorded
|
||||
184.9–186.2 ms for this exact shape. Both old and new servers agree with
|
||||
each other on *this* machine, so it reads as a machine/measurement-harness
|
||||
difference from whatever produced §6a's numbers, not a regression — the
|
||||
relative number this feature is judged on (offer vs. eager, same server,
|
||||
same request) is the clean ~16× and it holds.
|
||||
- `offer_sources`'s read set: re-ran the dev's `the_offer_reads_the_buffer_
|
||||
and_at_most_the_declaring_file` — one file at a port declaration, the buffer
|
||||
plus the declaring file (never the instantiating tops or noise files) at an
|
||||
instantiation.
|
||||
|
||||
**§37.2 — the `inlayHint` zero at the default scope.**
|
||||
|
||||
- Verified the finding independently against the **real** opentitan checkout,
|
||||
read-only: `find . -iname pins_if.sv` → exactly one hit,
|
||||
`hw/dv/sv/common_ifs/pins_if.sv`, confirmed outside `hw/ip/aes` entirely (a
|
||||
sibling library folder the default scope's raise-to-`hw/ip/aes` widen does
|
||||
not reach).
|
||||
- Wrote a scratch, `#[ignore]`d test in `inlay.rs` (guarded, read-only) that
|
||||
opens the real `hw/ip/aes/dv/tb/tb.sv` at the shipped default scope and
|
||||
asserts: the widen reached files under `hw/ip/aes` but none under
|
||||
`common_ifs`; `nav::definition`, `hover::hover` and `inlay_hints` all answer
|
||||
nothing about the `pins_if` instantiation. All three held. Agree with the
|
||||
dev's finding: this is a scope-reach question, not an inlay-hint bug, and
|
||||
every neighbour using the same `module_definition` lookup is equally blind
|
||||
to it at this scope.
|
||||
- `git -C ~/repo/opentitan status --porcelain` unchanged after every read
|
||||
(the same three pre-existing modifications).
|
||||
|
||||
**§37.3 — `locate::definition_location` index-only path.**
|
||||
|
||||
- Re-ran every pin in `locate.rs` and `nav.rs`; all pass.
|
||||
- Extra encoding attacks beyond the dev's own (BOM, CRLF, multi-byte, astral):
|
||||
a **tab-indented** declaration, and a declaration **after a lone `\r`**
|
||||
(old-Mac line ending, not `\n`) — both agree between the index-only and
|
||||
file-read paths exactly. (First attempt at the lone-`\r` case put it inside
|
||||
a line comment and found zero declarations at all: `lexer.rs`'s line-comment
|
||||
scanner runs to the next `\n` only, so a bare `\r` inside a comment does not
|
||||
end it and the intended module got swallowed into the comment text — a
|
||||
pre-existing, unrelated lexer property, not a locate.rs bug. Moved the `\r`
|
||||
outside the comment and the equality attack ran as intended.)
|
||||
- An open buffer with an edit above the definition still answers from the
|
||||
buffer's own current text, confirmed via the dev's `an_open_buffer_still_
|
||||
answers_from_the_buffer` (re-run) plus reasoning: `ws.document_for_path`
|
||||
gates the index-only branch off whenever a buffer is open, whatever the
|
||||
index recorded.
|
||||
- `held_views()` is `#[cfg(test)]` — grep and the diff both confirm no
|
||||
production caller; it cannot be reached outside a test build.
|
||||
- Timing re-derived independently, read-only, over the real opentitan
|
||||
checkout (3 976 indexed files, 200 targets): **index-only 390 ns/definition,
|
||||
file-read 27.9 µs/definition** — matches the README's 0.40 µs / 27.7 µs
|
||||
claim within run-to-run noise, same ~69–71× ratio.
|
||||
`git -C ~/repo/opentitan status --porcelain` unchanged.
|
||||
|
||||
**Gates, re-run myself, guarded:**
|
||||
|
||||
- `cargo clippy --all-targets` — clean, no warnings (checked both with and
|
||||
without my scratch tests present).
|
||||
- `tools/guard.sh -- cargo test --workspace` — **3 734 passed, 0 failed, 44
|
||||
ignored**, matching the dev's own gate exactly. No guard kill.
|
||||
- `tools/guard.sh -- tools/corpus_check.sh` — **814/820 (99.3%)**, the same
|
||||
six failures, `verification-error: none`, `crash: none`.
|
||||
- `tools/guard.sh -- node editors/vscode/smoke.js target/release/lucisv-server`
|
||||
— OK, 20 messages.
|
||||
- `git -C ~/repo/opentitan status --porcelain` after every opentitan read,
|
||||
throughout the session: unchanged, the same three pre-existing
|
||||
modifications every time.
|
||||
- Scratch worktree at `/private/tmp/.../scratchpad/base` (v0.40.0) removed
|
||||
with `git worktree remove` after use; `git worktree list` shows only the
|
||||
main tree.
|
||||
|
||||
**Findings.** None at HIGH or MEDIUM severity. Two LOW, informational, neither
|
||||
in this feature's own diff:
|
||||
- LOW — `ports.rs`'s test-scratch `Tree::new` keys its temp directory on the
|
||||
caller-supplied string alone, with no per-test salt; two tests choosing the
|
||||
same name race under parallel execution (reproduced against the pre-existing
|
||||
`qa_escaped_module_name_instantiation_parity_with_whole_workspace`). Not
|
||||
part of this diff and not blocking; worth a name-collision guard (e.g.
|
||||
salt with the test's `#[test]` function name) if it bites again.
|
||||
- LOW — the offer/eager repeat-timing numbers measured this session (~76 ms
|
||||
eager, ~4.5 ms offer, both machines) are well under `performance_take2.md`
|
||||
§6a's recorded 184.9–186.2 ms for the identical 128-file-fan-out shape;
|
||||
old and new servers agree with each other on this machine, so it reads as
|
||||
environment drift from whatever produced §6a's numbers rather than a
|
||||
regression this feature introduced. Recorded for whoever next revisits
|
||||
§6a's absolute numbers.
|
||||
|
||||
**Verdict: PASS.**
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-04 — lead.** Accepted; ships in 0.41.0. 37.1 is the shape §10
|
||||
asked for and the numbers say why: the offer is flat (53–68 µs from a
|
||||
3-file to a 128-file fan-out, on both cursor shapes) where the eager path
|
||||
is linear, and over the wire on opentitan's worst case QA measured the
|
||||
offer at ~4.5 ms against ~77 ms eager — the cursor-move request is off the
|
||||
fan-out. The dev's five deviations are all right: matching on the title's
|
||||
key rather than the exact title is forced by the plan's own unsaved-buffer
|
||||
requirement, and the escaped-identifier attack (`\rst(a)`) shows the key
|
||||
holds; refusing a resolve on a large buffer closes a gate the fast path's
|
||||
URI check cannot see; keeping the eager unsaved-buffer pin beside its
|
||||
lazy sibling is correct because the eager path is still live for clients
|
||||
that cannot resolve. 37.2 is ruled as the dev framed it: the zero is
|
||||
correct — `pins_if` is declared outside what the default scope reaches
|
||||
from `tb.sv`, definition and hover answer nothing there either, and QA
|
||||
confirmed it on the real tree — so this is a *scope* question, not an
|
||||
inlay defect, and the §10 line is closed as investigated. 37.3 is a pure
|
||||
fast path (index-only Location equal to the file-read one over every
|
||||
encoding shape QA and the dev tried, 69× cheaper, no view created), with
|
||||
the honest exclusion of open buffers whose indexed spans may be stale.
|
||||
QA's two LOWs are noted, not actioned: `Tree::new` takes a per-test name
|
||||
and the existing names are distinct, and §6a's absolute numbers were
|
||||
measured on a different day's machine state — both servers agree with
|
||||
each other here, which is what the comparison needed.
|
||||
@@ -0,0 +1,575 @@
|
||||
# linter expansion, wave 3 — the remaining Verible rules
|
||||
|
||||
## Goal
|
||||
|
||||
TODO §35. The rules Verible publishes that lucisv did not have: nineteen new
|
||||
files on the §33/§34 pattern (severity, Verible name/description/default
|
||||
cited in the rule's own `doc`, options through `OptionSpec`, true positives
|
||||
and near-misses in unit tests, a `.lint` case, corpus + opentitan counts with
|
||||
ten findings classified), plus the two reconciliations §35 asked for —
|
||||
Verible's *forbidden-symbol* list folded into `invalid-system-task-function`
|
||||
as a `symbols` option rather than shipped as a second rule that would fire
|
||||
twice on `$psprintf`, and Verible's forbidden-call half of `void-cast` added
|
||||
to lucisv's existing rule as a `forbidden_calls` option. The registry goes
|
||||
from 54 rules to **73**, which is every rule in Verible's published list
|
||||
except `forbid-implicit-declarations`. Plus §34's open LOW: a checked-in
|
||||
`tests/e2e.rs` case for `lucisv.lint.options` over the wire.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Verible is the reference, read during the round.** Every rule's `doc`
|
||||
quotes its Verible equivalent's one-line description and states its
|
||||
enabled-by-default flag, both read from
|
||||
<https://chipsalliance.github.io/verible/lint.html> and — where the
|
||||
published page is too thin to implement from — from the rule's own source
|
||||
and test files under
|
||||
`verible/verilog/analysis/checkers/` on 2026-09-04. Each deviation is
|
||||
listed in the work log and named in the rule's own `doc`.
|
||||
- **`forbidden-symbol` is not a Verible rule.** It is the name of the *source
|
||||
file* (`forbidden-symbol-rule.cc`) in which Verible implements
|
||||
`invalid-system-task-function`; that file's descriptor registers the name
|
||||
`"invalid-system-task-function"` and its map is the ten `$psprintf` /
|
||||
`$random` / `$srandom` / `$dist_*` entries lucisv already shipped. Shipping
|
||||
a second rule would have meant two findings on every `$psprintf`, which is
|
||||
what §35 forbade; the list is the `symbols` option instead. Verified by
|
||||
reading the file, not from memory.
|
||||
- **A parser that refuses a construct still lets a rule report it.** lucisv's
|
||||
parser rejects a module-scope `begin … end` and a bare `begin` inside a
|
||||
`generate` region (both are illegal or legacy), leaving an `ItemKind::Error`
|
||||
leaf whose first token is `begin`. `module-begin-block` and
|
||||
`v2001-generate-begin` read that leaf. The finding is exact — no legal item
|
||||
in either scope starts with that keyword — but error recovery unwinds out of
|
||||
the enclosing unit, so a file with one of these reports little else. Filed
|
||||
as a parser gap in `docs/coverage_gaps.md`; see Handshakes.
|
||||
- **A `.svh` fragment is judged as the file it is, not as the class it is
|
||||
included into.** The two lifetime rules report methods in a fragment that
|
||||
only becomes a class body after `` `include``. Verible, which also lints one
|
||||
file at a time, reports the same. 39 of the two rules' 101 opentitan
|
||||
findings are that shape.
|
||||
- **Where an option list replaces a Verible constant, the default is
|
||||
Verible's constant.** `forbidden-macro.macros` = `["uvm_warning"]`,
|
||||
`void-cast.forbidden_calls` = `["uvm_hdl_read", "randomize"]`,
|
||||
`invalid-system-task-function.symbols` = the ten names — so a run that
|
||||
configures nothing behaves exactly as Verible does. `dff-name-style`'s four
|
||||
options are Verible's, with its comma-separated strings written as lists
|
||||
(which is how every other lucisv list option is spelled) and its
|
||||
`waive_lhs_regex` default `(?i)mem.*` rewritten `[mM][eE][mM].*`, because
|
||||
`crates/vlog_linter/src/regex.rs` implements no inline flags and refuses
|
||||
`(?…)` by name.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumed** — `vlog_parser::ast` (unchanged: `FunctionDecl::scope`,
|
||||
`RawText`, `Genvar`, `GenerateRegion`, `StmtKind::Disable`,
|
||||
`ExprKind::Ternary`/`Scope`/`Call` are all read as they stand),
|
||||
`vlog_parser::token` (a macro invocation is one `Ident` starting with a
|
||||
backtick; a directive is one `Directive` to end of line — both facts are now
|
||||
read in one place, `crate::preproc`), `vlog_linter::options` and
|
||||
`LintContext::option_*` from §34, unchanged.
|
||||
- **Promised (new inside `vlog_linter`, all `pub(crate)`)** —
|
||||
`visit::ItemScope` + `visit::walk_items_scoped` (the enclosing *declaration*
|
||||
of an item), `exprs::walk_exprs` (every expression of a file),
|
||||
`preproc::{macro_name, directive_word, directive_operand}`. No public API of
|
||||
the crate changed; `Rule` and `OptionSpec` are exactly §34's.
|
||||
- **Promised (user-visible)** — nineteen new rule names, and two new option
|
||||
keys on rules that already existed: `invalid-system-task-function.symbols`
|
||||
and `void-cast.forbidden_calls`. Both default to the behaviour 0.38.0
|
||||
shipped, and `invalid-system-task-function`'s finding list is **byte-identical**
|
||||
to 0.38.0's on both trees (measured below).
|
||||
- **Files touched outside `vlog_linter`, each minimal and named by §35:**
|
||||
- `editors/vscode/package.json` — regenerated by
|
||||
`cargo run -p vlog_linter --example vscode_lint_settings`; nothing
|
||||
hand-edited. The drift test in `lucisv_server` proves it.
|
||||
- `crates/lucisv_server/tests/e2e.rs` — one new test, §35's own item.
|
||||
- `README.md`, `docs/site/src/content/docs/reference/rules.md`,
|
||||
`docs/coverage_gaps.md`, `TODO.md` — documentation, §35's own items.
|
||||
- **Handshake request to the parser (not made as an edit):** recover a
|
||||
module-scope `begin … end` and a bare `begin` inside a `generate` region as
|
||||
an unnamed generate block instead of an error leaf, so the *rest* of the
|
||||
unit survives. Both rules would then read a tree, and every other rule would
|
||||
keep working on such a file. Recorded in `docs/coverage_gaps.md`'s linter
|
||||
addendum; no `vlog_parser` file was touched by this lane.
|
||||
- **Not changed, deliberately** — `vlog_formatter`, `verify.rs`,
|
||||
`vlog_parser` (`git diff` over all three is empty); the formatter's corpus
|
||||
output is byte-identical to 0.38.0.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] 35.1 the nineteen rules, each with unit tests, a `.lint` case and
|
||||
corpus + opentitan counts
|
||||
- [x] 35.2 `void-cast`'s `forbidden_calls`; `forbidden-macro`'s `macros`;
|
||||
`invalid-system-task-function` reconciled with Verible's
|
||||
`forbidden-symbol` (one rule, one `symbols` option — the decision and
|
||||
its evidence are in Assumptions)
|
||||
- [x] 35.3 a checked-in `tests/e2e.rs` case for `lucisv.lint.options`
|
||||
- [x] 35.4 docs: README "Linting" rows, the docs-site rules page, the
|
||||
`coverage_gaps.md` linter addendum, `package.json` regenerated
|
||||
- [x] Gates (guarded): fmt, clippy 0, `cargo test --workspace` 3 695/48,
|
||||
corpus 814/820, `--stdout` byte-identity 0 differing, vsix smoke,
|
||||
opentitan census + timing
|
||||
- [ ] QA
|
||||
|
||||
## The rules, measured
|
||||
|
||||
Counts are `lucisv check --select <rule> --no-config` over the 860-file corpus
|
||||
and over `~/repo/opentitan/hw` (10 k files, read-only), with the release
|
||||
binary of this branch. "V" is Verible's default for the same rule; lucisv
|
||||
matches it for all nineteen. Ten findings per rule were read where there are
|
||||
ten; where there are fewer, all of them were.
|
||||
|
||||
| Rule | Sev | Default (V→here) | Verible equivalent | Options (default) | Corpus | opentitan | Findings read |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| `module-begin-block` | style | on→on | same | — | 0 | 0 | **0 on either tree** — no real file writes a sequential block at module scope, which is what makes it illegal. Pinned by unit tests and a `.lint` case, and confirmed firing through the release binary on a crafted file |
|
||||
| `legacy-generate-region` | style | off→off | same | — | 6 | 3 | 9 true (all there are): `picorv32.v` ×3, `picorv32/scripts/{quartus,vivado}/system.v`, `common_cells/src/deprecated/generic_LFSR_8bit.sv`, `aes/pre_dv/…/tlul_delayer.sv`, `ascon/pre_dv/…/ascon_sim.sv`, `pulp_riscv_dbg/sva/dm_top_sva.sv`. Every one is Verilog-2001-era or vendored code — which is exactly why the rule ships off |
|
||||
| `legacy-genvar-declaration` | style | off→off | same | — | 0 | 1 | 1 true (all there is): `pulp_riscv_dbg/sva/dm_top_sva.sv:55` writes `genvar i;` above the `for` that uses it — the same file `legacy-generate-region` flags one line earlier |
|
||||
| `v2001-generate-begin` | style | on→on | same | — | 0 | 0 | **0 on either tree.** Pinned by unit tests and a `.lint` case, and confirmed firing through the release binary on a crafted file |
|
||||
| `explicit-function-lifetime` | style | on→on | same | — | 29 | 32 | 10 read, all true: `.svh` fragments included into *modules* (`prim_util_memload.svh`, `prim_util_get_scramble_params.svh` — there a function really is static by default) and `pre_dv` program bodies. **The out-of-body exemption is what made this number honest**: before it, 948 of 960 findings across this rule and its twin were `function cls::f(…)` definitions, which are class methods |
|
||||
| `explicit-task-lifetime` | style | on→on | same | — | 47 | 69 | 10 read: 2 true (`prim_util_memload.svh`'s `simutil_memload`, a `pre_dv` program task), 8 **needs judgment** — `cip_base_vseq__*.svh`, fragments `` `include``d *inside* a class body, where lucisv (and Verible, which also lints per file) cannot see the class. All in `dv/`, outside opentitan's lint filesets |
|
||||
| `positive-meaning-parameter-name` | style | on→on | same | — | 0 | 0 | **0 on either tree** — neither codebase names a parameter `disable*`. Pinned by unit tests (four spellings, four near-misses) and a `.lint` case; confirmed firing through the release binary |
|
||||
| `suggest-parentheses` | style | on→on | same | — | 0 | 0 | **0 on either tree** — `a ? b ? c : d : e` is written by nobody; people parenthesize. Pinned by unit tests (including three-deep) and a `.lint` case with its safe fix; confirmed firing through the release binary |
|
||||
| `unpacked-dimensions-range-ordering` | style | on→on | same | — | 11 | 7 | 10 read, all true: `logic […] FIFO_REGISTERS[DATA_DEPTH-1:0]`, `payload_t data_fifo [DutNumInp-1:0][DutNumOut-1:0][$]`, `uint length[NUM_PATTGEN_CHANNELS-1:0]` — real descending arrays. The mirror image of `packed-dimensions-range-ordering`, and the two never both fire on one dimension |
|
||||
| `uvm-macro-semicolon` | warning | off→off | same | — | 22 | 214 | 10 read, all true: `` `uvm_fatal(…); `` in the ibex cosim monitors, `` `uvm_create_obj(…); `` throughout `hw/dv/sv`. All in `dv/`+`vendor/`. Off, as Verible ships it — the `;` is inert in almost every one of them |
|
||||
| `create-object-name-match` | warning | on→on | same | — | 1 | 4 | 5 true (all there are): `irq_single_seq_h` created as `irq_raise_single_seq_h`, `m_csrng_agent_cfg` created as `m_csrng_genbits_agent_cfg`, `item` as `sba_req`, `xbar_vseq` as `xbar_stress_all_vseq`. Every one is a config-db path that will not match what the reader expects |
|
||||
| `numeric-format-string-style` | style | off→off | same | — | 4 | 6 | 6 true (all there are): `"host_delay = 0x%0d "` ×4 in `push_pull_item.sv` (a decimal printed behind a hex prefix) and `"'d%3d"` in `spid_upload_tb.sv`. Off, as Verible ships it |
|
||||
| `macro-string-concatenation` | warning | off→off | same | — | 2 | 10 | 10 true: `` `define _ACCESS_CHECKS `` in `mem_bkdr_util.sv` writes `` "addr 0x%0h not ``_DW``-bit aligned" `` — a plain string, so the two backticks reach the output — and the alert-handler `vseq`s do the same. Off, as Verible ships it |
|
||||
| `disable-statement` | warning | off→off | same | — | 0 | 4 | 4 true (all there are): `disable sar_simple_thread` / `sar_burst_thread` in `hmac_base_vseq.sv` and two in `lc_ctrl_smoke_vseq.sv`, every one naming a `fork : label`, which is the exact construct the rule exists for. Off, as Verible ships it |
|
||||
| `forbidden-macro` | warning | on→on | `forbidden-macro` | `macros` (`["uvm_warning"]`) | 1 | 1 | 1 true on each tree (all there are): `riscv_instr_cov.svh:434` in `google_riscv-dv`, vendored into both. Verible hard-codes the list; here it is an option |
|
||||
| `endif-comment` | style | off→off | same | safe fix | 398 | 706 | 10 read, all true: `common_cells/include/common_cells/assertions.svh` (`// UVM`, `// XSIM`, `// SYNTHESIS`), `bus_params_pkg.sv` (`// BUS_AW`, `// BUS_DW`, …). Off, as Verible ships it; the fix names the condition the `` `ifdef `` opened |
|
||||
| `forbid-line-continuations` | style | on→on | same | — | 0 | 0 | **0 on either tree** — no file in either breaks a string with `\`. Pinned by unit tests and confirmed firing through the release binary; the `.lint` case pins the negative direction (a multi-line `` `define `` is never reported), because a marker cannot be written inside a multi-line string |
|
||||
| `dff-name-style` | style | off→off | same | `input` (`["next","n","d"]`), `output` (`["reg","r","ff","q"]`), `waive_ifs_with_conditions` (Verible's four), `waive_lhs_regex` (`"[mM][eE][mM].*"`) | 385 | 2 233 | 10 read, all true *as the rule reads it*: `init`/`stalls` in `common_cells/formal/*`, `gpio_p2d`, `spi_device_sck_o` in `hw/dv/dpi/*` — registers not named `_q`. Neither codebase follows the `_q`/`_d` convention, which is why the rule ships off; a project that does gets a real check |
|
||||
| `proper-parameter-declaration` | style | off→off | same | `package_allow_parameter` (false), `package_allow_localparam` (true) | 716 | 13 992 | 10 read, all true: `parameter` in package bodies (`bus_params_pkg.sv`, `alert_esc_agent_pkg.sv`) and in module bodies (`cdc_2phase_clearable_tb.sv`). opentitan writes `parameter` in packages everywhere, which the Verible default `package_allow_parameter = false` reports; one option accepts it. Off, as Verible ships it |
|
||||
|
||||
Two options on rules that already existed:
|
||||
|
||||
| Rule | Option (default) | Corpus | opentitan | Findings read |
|
||||
|---|---|---|---|---|
|
||||
| `void-cast` | `forbidden_calls` (`["uvm_hdl_read", "randomize"]`) | 0 → **3** | 0 → **3** | 6 true (all there are): `void'(randomize())` in `id_queue_tb.sv` ×2, `stream_register_tb.sv`, `entropy_src_env_cfg.sv`, `entropy_src_tb.sv`, and `void'(uvm_hdl_read(…))` in `hmac_directed_vseq.sv`. Every one discards a result that says whether the operation worked |
|
||||
| `invalid-system-task-function` | `symbols` (the ten names) | 8 → 8 | 23 → 23 | **byte-identical to 0.38.0** on both trees, stdout and stderr — the option's default reproduces the hard-coded list exactly |
|
||||
|
||||
**Why a Verible-default rule fires inside opentitan at all.** opentitan lints
|
||||
its `hw/ip/*/rtl` filesets with
|
||||
`hw/lint/tools/veriblelint/lowrisc-styleguide.rules.verible_lint`, which was
|
||||
read for this round: it sets `line-length=length:100`,
|
||||
`explicit-parameter-storage-type=exempt_type:string`,
|
||||
`parameter-name-style=localparam_style:CamelCase|ALL_CAPS` and disables
|
||||
`typedef-structs-unions` — and says **nothing** about any of §35's rules. So
|
||||
Verible on opentitan's own filesets would report the same findings the five
|
||||
default-on rules with non-zero counts produce here. It does not, in practice,
|
||||
because those filesets are `rtl/` only: of the 116 new default-on findings on
|
||||
`hw/`, **8 are under an `rtl/` path** — five of them in `hw/ip/prim/rtl/`
|
||||
`.svh` fragments (`prim_util_memload.svh`, `prim_util_get_scramble_params.svh`,
|
||||
which are simulation-only helpers `` `include``d into a module and are
|
||||
genuinely static there), three in `pre_dv`/`pre_sca` testbench `rtl/`
|
||||
directories — and the other 108 are in `dv/`, `pre_dv/`, `sva/`, `dpi/` and
|
||||
`vendor/`, which opentitan's dvsim lint does not cover. That is the whole
|
||||
explanation — no reading of a rule differs from Verible's.
|
||||
|
||||
**The census.** The default set now reports **1 169** findings on opentitan
|
||||
`hw/` against 0.38.0's 1 053, and **8 524** on the corpus against 8 432. Both
|
||||
deltas are exactly the new default-on work:
|
||||
|
||||
```
|
||||
opentitan 32 + 69 + 7 + 4 + 1 + 3 = 116 (= 1169 − 1053)
|
||||
corpus 29 + 47 + 11 + 1 + 1 + 3 = 92 (= 8524 − 8432)
|
||||
```
|
||||
|
||||
— `explicit-task-lifetime`, `explicit-function-lifetime`,
|
||||
`unpacked-dimensions-range-ordering`, `create-object-name-match`,
|
||||
`forbidden-macro`, and `void-cast`'s new named-call half. The other four
|
||||
default-on rules (`module-begin-block`, `v2001-generate-begin`,
|
||||
`positive-meaning-parameter-name`, `suggest-parentheses` and
|
||||
`forbid-line-continuations` — five of them) contribute nothing on either
|
||||
tree.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-04 — dev (Opus 5)
|
||||
|
||||
**35.1, the nineteen rules.** Written in §35's order: the two `forbidden-*`
|
||||
list rules first (which is where the `forbidden-symbol` reconciliation had to
|
||||
be settled), then the Style rules, then the Warning rules.
|
||||
|
||||
Three shared readers were added inside the crate rather than duplicated
|
||||
across rules, each one sentence long:
|
||||
|
||||
- `visit::walk_items_scoped` + `visit::ItemScope` — the enclosing
|
||||
*declaration* of an item (file, module, package, class), with generate
|
||||
constructs passing the scope through. Read by both lifetime rules and by
|
||||
`proper-parameter-declaration`.
|
||||
- `exprs.rs` — `walk_exprs`, every expression of a file: the roots (a
|
||||
continuous or procedural assignment, a declaration initialiser, a
|
||||
condition, a call argument, an instantiation's connections, a generate
|
||||
header, an expression statement, a parameter port's default) and a descent
|
||||
through every composite `ExprKind`. Only `suggest-parentheses` needs it
|
||||
today, and it needs *all* of it — a rule that judged expression shape from
|
||||
a partial walk would be silently blind.
|
||||
- `preproc.rs` — `macro_name`, `directive_word`, `directive_operand`. Four
|
||||
rules read the lexer's two preprocessor token shapes; reading them in one
|
||||
place is what stops the four disagreeing about where a name ends.
|
||||
|
||||
**Decisions and deviations, for the lead:**
|
||||
|
||||
- **`forbidden-symbol` ships as an option, not a rule.** Verible's
|
||||
`forbidden-symbol-rule.cc` registers the descriptor name
|
||||
`"invalid-system-task-function"` — the two names §35 listed separately are
|
||||
one rule under its file name. lucisv keeps the one rule and gives it
|
||||
`symbols`; the rule's `doc` says so in as many words, so nobody
|
||||
re-derives it. Finding list byte-identical to 0.38.0's.
|
||||
- **`void-cast` now checks both halves in one rule.** lucisv's original
|
||||
question (the operand must be a call) and Verible's (a named list of calls
|
||||
must not be discarded). They cannot both fire on one statement — the first
|
||||
wants any call, the second a particular one — so a `void'(randomize())` is
|
||||
reported once. Option name `forbidden_calls` is lucisv's; Verible has none.
|
||||
- **`module-begin-block` and `v2001-generate-begin` read an error leaf.** The
|
||||
parser refuses both constructs; the rules read the `ItemKind::Error` whose
|
||||
first token is `begin`, one at module scope and one inside a
|
||||
`GenerateRegion`. `begin_block()` is written once (in
|
||||
`module_begin_block.rs`) and shared, so the two cannot disagree about what
|
||||
a stray `begin` looks like. The parser gap is a Handshake request, not an
|
||||
edit.
|
||||
- **Both lifetime rules exempt an out-of-body definition**, which is wider
|
||||
than Verible. `function cls::f(…); … endfunction` is lexically outside the
|
||||
class and Verible reports it; it *is* a class method, and its lifetime is
|
||||
already automatic. The first opentitan census, before the exemption, was
|
||||
948 findings of exactly that shape out of 960 — a census-driven fix of the
|
||||
kind §34's `generate-label` produced. `FunctionDecl::scope` /
|
||||
`TaskDecl::scope` is non-empty for exactly those declarations.
|
||||
- **`disable-statement` also accepts a task or function name.** `disable
|
||||
task_name` is legal (IEEE 1800 §9.6.2) and Verible reports it; reporting it
|
||||
would be a false positive on a rule whose point is "write `disable fork`".
|
||||
Named in the rule's `doc`.
|
||||
- **`suggest-parentheses` implements Verible's shape and no more.** §35
|
||||
mentioned "or a mixed-precedence expression"; Verible's rule is only the
|
||||
nested-true-clause one (`suggest-parentheses-rule.cc`: the true-case child,
|
||||
unwrapped, is itself a condition expression), and a rule that guessed at
|
||||
operator combinations would report far more than it explained. Its safe fix
|
||||
inserts two characters and changes no token.
|
||||
- **`dff-name-style`'s `waive_lhs_regex` default is `[mM][eE][mM].*`**, not
|
||||
Verible's `(?i)mem.*`: lucisv's pattern engine refuses `(?…)` by name
|
||||
(§34's rework), and the rewritten pattern accepts the same names. Its three
|
||||
list options are Verible's comma-separated strings written as lists.
|
||||
Conditions are compared with whitespace squeezed out, so `!rst_ni` and
|
||||
`! rst_ni` are one waiver.
|
||||
- **`endif-comment`'s fix is offered only where there is no comment at all.**
|
||||
A comment that names something else is reported without one: rewriting
|
||||
somebody's words is not a repair.
|
||||
- **`numeric-format-string-style` was implemented from Verible's own test
|
||||
file**, whose accepted and rejected literal lists are reproduced verbatim
|
||||
as two unit tests (13 accepted, 10 rejected). A specifier with no prefix is
|
||||
always accepted; only a mismatched prefix, and any prefix before a decimal
|
||||
specifier, are reported.
|
||||
- **`forbid-line-continuations` has no positive `.lint` case.** The finding
|
||||
lands on the *first* line of a multi-line string and the harness attaches a
|
||||
marker to the line above it, which is inside the string. Pinned by unit
|
||||
tests instead — the same situation `posix-eof` is in, and the case file says
|
||||
so while pinning the negative direction (a multi-line `` `define `` is never
|
||||
reported).
|
||||
- **Three existing test fixtures named `explicit-function-lifetime` as a rule
|
||||
lucisv does not have** (`lib.rs`'s waiver test, `waivers.lint`) or wrote a
|
||||
lifetime-less subroutine (`empty_item.lint`), and one `.lint` case wrote
|
||||
`void'(obj.randomize() with …)` as a clean void cast. All four now name
|
||||
`forbid-implicit-declarations` — Verible's one remaining unimplemented rule
|
||||
— or say `automatic`, or call something else. Noted because they are §34
|
||||
files.
|
||||
|
||||
**35.2** — the two option additions, above.
|
||||
|
||||
**35.3** — `tests/e2e.rs` gained
|
||||
`the_lint_options_setting_changes_what_is_published_and_a_bad_entry_is_logged`:
|
||||
a `lucisv.toml` with `[lint.line-length] length = 40` flags a 47-column line;
|
||||
`lucisv.lint.options` with `length: 200` clears it mid-session (the editor
|
||||
beats the toml, key by key); a typo'd `lenght` is refused, logged as exactly
|
||||
one `window/logMessage` naming the setting and ending "ignored", and dropped —
|
||||
so the `lucisv.toml` value stands again and the finding comes back. That is
|
||||
§34's open LOW closed with the behaviour its QA verified by hand twice.
|
||||
|
||||
**35.4** — `README.md` (19 rows, verified against `--rules-doc`'s 73 names by
|
||||
diff), the docs-site rules page (badge 54 → 73, 19 table rows and 19 sections,
|
||||
headers diffed against `--rules-doc` — identical sets),
|
||||
`docs/coverage_gaps.md`'s linter addendum (the Verible-coverage claim, the
|
||||
parser gap, the fragment boundary, the `forbidden-symbol` note), and
|
||||
`editors/vscode/package.json` regenerated by the generator. No setting was
|
||||
added, so `editors/vscode/README.md` is unchanged — its "54 rules in all"
|
||||
line is inside the *0.38.0 highlights* section and is historical.
|
||||
|
||||
## Measurements
|
||||
|
||||
All runs under `tools/guard.sh`; **no guard kill at any point**.
|
||||
|
||||
- **`cargo test --workspace`**: **3 695 passed, 0 failed, 42 ignored** over
|
||||
**48** test binaries (baseline 3 564 / 48 / 42) — +131 tests, no binary
|
||||
added or removed. The `.lint` table went from 246 to **275** cases.
|
||||
- **fmt**: `cargo fmt -p vlog_linter`, `cargo fmt -p lucisv_server`.
|
||||
**clippy**: `cargo clippy --all-targets --workspace`, **0 warnings**, and no
|
||||
new `#[allow]` anywhere in the diff.
|
||||
- **Corpus gate**: `{"passing":814,"total":820,"pct":99.3}` — the same six
|
||||
known failures, unchanged.
|
||||
- **Formatter byte-identity**: `lucisv format --stdout` over all 860 corpus
|
||||
files, this build vs `~/.cache/lucisv-baselines/lucisv-0.38.0`:
|
||||
**0 differ**. `git diff` over `vlog_formatter`, `vlog_parser` and
|
||||
`verify.rs` is empty.
|
||||
- **`invalid-system-task-function` identity**: `check --select
|
||||
invalid-system-task-function --no-config`, this build vs 0.38.0 — corpus
|
||||
**8 findings**, opentitan **23 findings**, stdout and stderr byte-identical
|
||||
on both trees.
|
||||
- **opentitan `check` census**: default set **1 169** findings against
|
||||
0.38.0's **1 053**; corpus **8 524** against **8 432**. The arithmetic is
|
||||
above and balances exactly.
|
||||
- **opentitan `check` timing** (three interleaved runs each, timed inside the
|
||||
guard): 0.38.0 **0.86 / 0.84 / 0.84 s**, this build **0.86 / 0.86 / 0.85 s**
|
||||
— no measurable difference, though the new build runs ten more default-on
|
||||
rules.
|
||||
- **vsix smoke**: `node editors/vscode/smoke.js target/debug/lucisv-server` —
|
||||
OK, 20 messages.
|
||||
- **opentitan tree after the round**: `git -C ~/repo/opentitan status
|
||||
--porcelain` shows only the three pre-existing modifications
|
||||
(`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`,
|
||||
`hw/top_earlgrey/ip/ast/rtl/ast.sv`). Every opentitan run was
|
||||
`lucisv check` and read-only.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-04 — QA (Sonnet 5)
|
||||
|
||||
Verified in the `lint-3` worktree only, everything guarded, opentitan
|
||||
read-only. Scratch under `.../scratchpad/qa-35/`.
|
||||
|
||||
**1. Gates, all reproduced independently.** `cargo fmt --all -- --check`
|
||||
clean. `cargo clippy --all-targets --workspace`: 0 warnings; `git diff
|
||||
b1b3cad` shows no new `#[allow]` anywhere (grepped the whole diff, not just
|
||||
the new files). `cargo test --workspace --no-fail-fast` (full log, not
|
||||
tail-truncated, so every binary's `test result:` line was summed): **3 695
|
||||
passed / 0 failed / 42 ignored / 48 binaries** — exact match, no guard kill.
|
||||
`git diff --stat b1b3cad -- crates/vlog_formatter crates/vlog_parser`: empty.
|
||||
Corpus gate (own build of `scripts/score.sh target/release/lucisv`, main
|
||||
tree's `corpus/`, read-only): `{"passing":814,"total":820,"pct":99.3}`, same
|
||||
five failure categories (2 invalid-or-fragment, 1 directive-split, 1
|
||||
macro-items, 1 not-verilog, 1 other). `--stdout` byte-identity over all 860
|
||||
corpus files, this build vs `~/.cache/lucisv-baselines/lucisv-0.38.0`: **0
|
||||
differ**. vsix smoke: `node editors/vscode/smoke.js target/release/lucisv-server`
|
||||
— OK, 20 messages. Changed-file set: `git diff --stat b1b3cad` (15 tracked
|
||||
files) plus the 20 untracked additions (19 rule files + the feature README)
|
||||
match §35's ownership list exactly — nothing touched outside `vlog_linter`,
|
||||
the two disclosed doc/toggle files, and the checked-in e2e test; the new
|
||||
`the_lint_options_setting_changes_what_is_published_and_a_bad_entry_is_logged`
|
||||
test in `crates/lucisv_server/tests/e2e.rs` was confirmed present in the run
|
||||
(`ok`, line 1797 of the full log).
|
||||
|
||||
**2. `forbidden-symbol` reconciliation.** Read Verible's actual
|
||||
`forbidden-symbol-rule.cc` (`verible/verilog/analysis/checkers/`, GitHub
|
||||
API-fetched, not from memory): its C++ class is `ForbiddenSystemTaskFunctionRule`
|
||||
but the descriptor name it registers is `"invalid-system-task-function"`
|
||||
under topic `"forbidden-system-functions"`, and its hard-coded map is exactly
|
||||
the ten names lucisv ships (`$psprintf`→`$sformatf`, `$random`→`$urandom`,
|
||||
`$srandom`→`process::self().srandom()`, the six `$dist_*`→`$urandom`) —
|
||||
confirms the dev's claim word for word. CLI: `$psprintf` fires exactly once
|
||||
with defaults; `[lint.invalid-system-task-function] symbols = ["$foo"]`
|
||||
makes `$foo` fire and `$psprintf` stop firing (verified both directions).
|
||||
Finding-list byte-identity, this build vs 0.38.0, `--select
|
||||
invalid-system-task-function --no-config`: corpus **8** findings, opentitan
|
||||
**23** findings, `diff` empty on both trees both ways. `git -C
|
||||
~/repo/opentitan status --porcelain` before/after: only the three
|
||||
pre-existing files — read-only held.
|
||||
|
||||
**3. The nineteen rules, adversarially.** Read all 19 rule source files in
|
||||
full (not just the diff) plus `exprs.rs` and `preproc.rs`; every rule's own
|
||||
unit-test block already exercises true positive / near-miss / edge shapes
|
||||
(macro text, fragments, class bodies, generate scopes) matching what its
|
||||
`doc` claims — no gap between doc and code found in any of the 19. Targeted,
|
||||
independent CLI/CLI-toml/LSP probes on top of reading:
|
||||
|
||||
- `module-begin-block` / `v2001-generate-begin`: crafted a module-scope
|
||||
`begin…end` and a bare `begin` in a `generate` region. Each fires exactly
|
||||
once, span is exactly the 5-character `begin` keyword (confirmed via
|
||||
`--output-format json` `range`), and no other rule misfires on the file
|
||||
(only the incidental `module-filename` mismatch from my own test
|
||||
filename). Confirmed via Verible's actual source
|
||||
(`module-begin-block-rule.cc`, `v2001-generate-begin-rule.cc`) that both
|
||||
are real Verible rule names with exactly the cited descriptions, both
|
||||
enabled by default, and that `v2001-generate-begin`'s matcher
|
||||
(`NodekGenerateRegion(HasGenerateBlock())`) does not distinguish a labelled
|
||||
from an unlabelled block — so the rule's own test using `begin : b` is
|
||||
correct, not a bug.
|
||||
- **Lifetime exemption**: `class c; extern function int f(); endclass
|
||||
function c::f(); return 0; endfunction` (out-of-body definition) is
|
||||
**silent**; a bare `function int f(); return 0; endfunction` at module
|
||||
scope **fires**. Both confirmed live via the CLI, matching the doc and the
|
||||
948/960 census claim.
|
||||
- `disable-statement`: a fork label, a task name and an undeclared name in
|
||||
one file — CLI confirms `disable threads` (fork label) and `disable
|
||||
somewhere_else` (undeclared) fire, `disable t` (task) is silent. Read
|
||||
Verible's real `disable-statement-rule.cc`: it matches only `kSeqBlock`
|
||||
labels and does **not** special-case a task/function name, so lucisv's
|
||||
"wider than Verible" claim (avoiding a false positive on the
|
||||
IEEE-1800-legal `disable task_name`) is a genuine, correctly-cited
|
||||
deviation, not an invented one.
|
||||
- `suggest-parentheses`: confirmed the rule's scope is deliberately narrow by
|
||||
reading Verible's actual `suggest-parentheses-rule.cc` — it contains a
|
||||
literal `// TODO: evaluate other types of expressions` and only matches a
|
||||
`kConditionExpression` nested in another's true-clause, nothing about
|
||||
mixed-precedence operators. So `a + b << c`, `a & b | c`, `!a == b` and a
|
||||
five-operator chain (`a | b & c ^ d << e >> f`) correctly produce **no**
|
||||
finding (exit 0, confirmed) — this is lucisv matching Verible's real
|
||||
scope, not an incomplete implementation. On the true-positive shape `a ? b
|
||||
? c : d : e`: `--fix` on a hand-written file parses (`lucisv --check`
|
||||
exit 0 after the fix), is idempotent through the formatter (a `lucisv
|
||||
format` pass afterward makes zero changes), and re-linting the fixed file
|
||||
is clean. Truth-tabled `a ? (b ? c : d) : e` against the unparenthesized
|
||||
original for all 32 combinations of 5 boolean inputs in Python: **0
|
||||
mismatches** — the fix is semantically inert by construction (parens make
|
||||
explicit what right-associativity already meant).
|
||||
- `endif-comment`: `--fix` on a hand-written file with a bare and a
|
||||
`` `ifndef``/`` `else`` pair both parses and is idempotent (a `lucisv
|
||||
format` pass afterward is a no-op on a second run), and the fixed
|
||||
diagnostics clear. **One LOW finding**: the fix's insertion
|
||||
(`crates/vlog_linter/src/rules/endif_comment.rs:102`,
|
||||
`format!(" // {name}")`) writes **two** spaces before the comment, but
|
||||
lucisv's formatter's canonical trailing-comment spacing is **one** space
|
||||
(confirmed against `crates/vlog_formatter/src/fence.rs`'s own test
|
||||
fixtures, e.g. `"wire a; // note"`) — so `lucisv --check` on a
|
||||
freshly-`--fix`ed file reports "would reformat" immediately, and only
|
||||
settles after one `lucisv format` pass. Not a correctness bug: the file
|
||||
still parses, the eventual output is semantically identical and
|
||||
idempotent, and `Applicability::Safe` is documented as "preserves meaning
|
||||
and intent" only, not "already formatter-clean" — but it is a real,
|
||||
fixable inconsistency (one character) worth a follow-up so a `--fix` run
|
||||
does not leave a file that immediately fails `--check`.
|
||||
- Option-bearing rules, **CLI toml** (all five): `invalid-system-task-
|
||||
function.symbols` (above); `dff-name-style`'s four options set together
|
||||
(`input`, `output`, `waive_ifs_with_conditions`, `waive_lhs_regex`) turn a
|
||||
file with three otherwise-reportable shapes fully clean; `forbidden-
|
||||
macro.macros = ["my_macro"]` fires only `my_macro`, not the default
|
||||
`uvm_warning`; `void-cast.forbidden_calls = ["my_risky_call"]` fires only
|
||||
that name, not `randomize`; `proper-parameter-declaration`'s two booleans
|
||||
confirmed via its own unit tests (`package_allow_parameter`,
|
||||
`package_allow_localparam`, both directions) plus a live check below.
|
||||
**LSP editor object**, a standalone Python script speaking framed
|
||||
JSON-RPC at the real `lucisv-server` binary (same technique
|
||||
linter-expansion-2's QA used, since no other checked-in e2e case touches
|
||||
these three): `forbidden-macro.macros` replaced live — the pre-push
|
||||
publish flags `` `uvm_warning ``, the post-push publish (`macros:
|
||||
["my_macro"]`) flags `` `my_macro `` instead, on the same file; `void-
|
||||
cast.forbidden_calls` emptied live — pre-push 1 finding, post-push 0;
|
||||
`proper-parameter-declaration.package_allow_parameter` — pre-push 0 (rule
|
||||
is off by default, confirmed correct, not a bug), post-select-push 1,
|
||||
post-option-push 0. All three behaved exactly as configured, no crash, no
|
||||
stray diagnostic.
|
||||
- `void-cast`'s two halves never double-fire: confirmed via its own unit
|
||||
test (`the_two_halves_never_both_fire_on_one_statement`) and via the CLI
|
||||
toml probe above (`my_risky_call` reported once).
|
||||
|
||||
**4. Opentitan census, re-derived independently.** Own build's default-set
|
||||
`check --no-config` over `hw/`: **1 169** findings; 0.38.0's: **1 053**
|
||||
(re-run myself, not taken from the README). Corpus: **8 524** vs 0.38.0's
|
||||
**8 432** (also re-run). Delta arithmetic reproduced exactly: opentitan
|
||||
32+69+7+4+1+3=116=1169−1053, corpus 29+47+11+1+1+3=92=8524−8432, checked
|
||||
per-rule with a `--select <rule>` sweep over all nineteen rules on both
|
||||
trees — **every one of the 19 rows in the README's table matches my own
|
||||
count exactly** (module-begin-block 0/0, legacy-generate-region 6/3,
|
||||
legacy-genvar-declaration 0/1, v2001-generate-begin 0/0,
|
||||
explicit-function-lifetime 29/32, explicit-task-lifetime 47/69,
|
||||
positive-meaning-parameter-name 0/0, suggest-parentheses 0/0,
|
||||
unpacked-dimensions-range-ordering 11/7, uvm-macro-semicolon 22/214,
|
||||
create-object-name-match 1/4, numeric-format-string-style 4/6,
|
||||
macro-string-concatenation 2/10, disable-statement 0/4, forbidden-macro
|
||||
1/1, endif-comment 398/706, forbid-line-continuations 0/0, dff-name-style
|
||||
385/2233, proper-parameter-declaration 716/13992), plus `void-cast` 0→3 on
|
||||
both trees. `git -C ~/repo/opentitan status --porcelain` checked before and
|
||||
after every sweep: only the three pre-existing files, every run read-only.
|
||||
|
||||
Five findings classified for each of the five named rules:
|
||||
- `explicit-task-lifetime`: read 5 of opentitan's 69 —
|
||||
`cip_base_vseq__sec_cm_fi.svh` tasks (`run_sec_cm_fi_vseq`,
|
||||
`pre_run_sec_cm_fi_vseq`, `post_run_sec_cm_fi_vseq`,
|
||||
`check_sec_cm_fi_resp`, `test_sec_cm_fi`), all `.svh` fragments
|
||||
`` `include``d into a class body — matches the README's "needs judgment"
|
||||
bucket exactly (lucisv, like Verible, cannot see the class from the
|
||||
fragment's own scope).
|
||||
- `suggest-parentheses`: 0 on opentitan — matches the README, nothing to
|
||||
classify.
|
||||
- `unpacked-dimensions-range-ordering`: read 5 of 7 —
|
||||
`pattgen_agent_cfg.sv:15`, `kmac_reduced_tb.sv:338` and `:354`,
|
||||
`ram_1p.v:24`, `pattgen_scoreboard.sv:22`, all genuine descending unpacked
|
||||
ranges — true positives, matches the README's characterization.
|
||||
- `create-object-name-match`: read all 4 (all there are) —
|
||||
`edn_env_cfg.sv` (`m_csrng_genbits_agent_cfg`/`m_csrng_agent_cfg`),
|
||||
`rv_dm_buffered_enable_vseq.sv` (`sba_req`/`item`),
|
||||
`xbar_stress_all_with_rand_reset_vseq.sv`
|
||||
(`xbar_stress_all_vseq`/`xbar_vseq`), `core_ibex_vseq.sv`
|
||||
(`irq_single_seq_h`/`irq_raise_single_seq_h`) — exactly the four the
|
||||
README names, all true positives.
|
||||
- `forbid-line-continuations`: 0 on opentitan — matches the README, nothing
|
||||
to classify.
|
||||
|
||||
No misclassification found in any finding read. Timing, three interleaved
|
||||
runs each (`/usr/bin/time -p` inside the guard, default-set `check
|
||||
--no-config` over `hw/`): 0.38.0 **0.85 / 0.86 / 0.83 s**, this build
|
||||
**0.87 / 0.91 / 0.84 s** — within noise of the README's own numbers, no
|
||||
regression over 10%.
|
||||
|
||||
**5. Docs.** `lucisv check --rules-doc`: **73** `## ` sections. README.md's
|
||||
"Linting" table: 73 rule rows (excluded the three-row severity legend after
|
||||
first miscounting it, same trap linter-expansion-2's QA hit) — diffed
|
||||
against `--rules-doc`'s name set: **identical**. `docs/site/src/content/
|
||||
docs/reference/rules.md`: 73 `## ` headers, diffed against `--rules-doc`:
|
||||
**identical**. `editors/vscode/package.json`: 73
|
||||
`lucisv.lint.rules.<name>` toggles, diffed against `--rules-doc`:
|
||||
**identical** — and the drift test is not vacuous: in a throwaway worktree
|
||||
(`git worktree add --detach` from `b1b3cad`, the dev's diff applied with
|
||||
`git apply`, untracked files copied over, removed after with `git worktree
|
||||
remove --force`), added a `FakeDriftRule` to `registry::all_rules()` with no
|
||||
matching `package.json` entry — `cargo test -p lucisv_server
|
||||
the_vscode_lint_toggles_match_the_registry` **FAILED** as expected, naming
|
||||
`fake-drift-rule` in the registry side only. `git worktree list` afterward:
|
||||
back to the original two worktrees. `docs/coverage_gaps.md`'s "Linter
|
||||
addendum (2026-09-04, TODO §35)" section reads true against the shipped
|
||||
code: the 73/74-rule count, the parser-gap note for the two `begin`-reading
|
||||
rules, the `.svh`-fragment boundary, and the `forbidden-symbol` note all
|
||||
match what I verified above. TODO §35's checkboxes match this README's
|
||||
Status/TODO (35.1–35.4 and Gates ticked, QA still open pending this entry).
|
||||
The four renamed §34 fixtures (`crates/vlog_linter/src/lib.rs`'s two waiver
|
||||
tests, `tests/cases/waivers.lint`, `tests/cases/empty_item.lint`,
|
||||
`tests/cases/statements.lint`) now name `forbid-implicit-declarations` (the
|
||||
one Verible rule lucisv still lacks) or write `automatic`/a different call,
|
||||
and all ran green in the full workspace test log
|
||||
(`a_verible_waiver_for_a_rule_lucisv_does_not_have_is_ignored ... ok`).
|
||||
|
||||
**Verdict: PASS.** One LOW finding: `endif-comment`'s safe fix inserts two
|
||||
spaces before its trailing comment where lucisv's formatter's canonical
|
||||
style is one, so a freshly-`--fix`ed file needs one `lucisv format` pass to
|
||||
be `--check`-clean (`crates/vlog_linter/src/rules/endif_comment.rs:102`).
|
||||
Harmless — parses, idempotent, semantically identical, and
|
||||
`Applicability::Safe` never promised formatter-clean output — but worth the
|
||||
one-character fix in a follow-up. Everything else verified clean: all
|
||||
gates reproduced independently and matching exactly; the `forbidden-symbol`
|
||||
reconciliation confirmed against Verible's actual source, not the dev's
|
||||
citation of it; all nineteen rules read in full and adversarially probed,
|
||||
including two rules' scope-narrowing decisions (`suggest-parentheses`,
|
||||
`disable-statement`) independently confirmed against Verible's own source
|
||||
rather than taken on the dev's word; the lifetime exemption and the two
|
||||
error-leaf rules' isolation confirmed live; every option-bearing rule
|
||||
exercised through the CLI toml, and three of them through a live LSP
|
||||
session with the editor's value observed to win; the opentitan and corpus
|
||||
censuses re-derived independently and matching the README's table and
|
||||
arithmetic exactly, five findings apiece classified for the five named
|
||||
rules with no misclassification; the docs, the drift test's teeth, and the
|
||||
renamed §34 fixtures all confirmed.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-04 — lead.** Accepted. With this wave every rule in Verible's
|
||||
published list is in lucisv except the one that needs a compiler, and
|
||||
the round's best decision was reading Verible's source rather than its
|
||||
table: `forbidden-symbol` is the file name of `invalid-system-task-
|
||||
function`, so it is an option, not a second rule that would have fired
|
||||
twice on `$psprintf`. The census-driven narrowing of the lifetime rules
|
||||
(948 of 960 findings were out-of-body definitions) is the right kind of
|
||||
divergence, written down; the two rules that fire on an error leaf are
|
||||
honest about the parser's limit and file it (`docs/topo.md` §2.9-25).
|
||||
QA read the nineteen files, verified two scope decisions against
|
||||
Verible's own source, truth-tabled the parenthesizing fix, and drove
|
||||
the options through both doors. The one LOW — the `endif-comment` fix
|
||||
wrote two spaces where the formatter writes one — fixed at review with
|
||||
its two expectations. Ships in 0.39.0. The linter now stands at 73
|
||||
rules with severities, toggles and options; what remains for it is
|
||||
measurement in use, not more rules.
|
||||
@@ -188,7 +188,13 @@ code_action_provider: Some(CodeActionProviderCapability::Options(CodeActionOptio
|
||||
|
||||
`Options` rather than `Simple(true)` on purpose: a client that filters by kind
|
||||
(which is how fix-on-save is configured) has to be told which kinds exist.
|
||||
`resolve_provider` is `None` because every action is returned complete.
|
||||
`resolve_provider` was `None` because every action was returned complete;
|
||||
since TODO §37.1 it is `Some(true)` and a third kind
|
||||
(`refactor.rewrite.lucisv.ports`) is listed. The quick fixes above are
|
||||
unaffected — the actions that are now offered without their edits are the port
|
||||
refactorings, and only to a client that declared
|
||||
`textDocument.codeAction.resolveSupport.properties: ["edit"]`. See
|
||||
`docs/features/lazy-code-action/README.md`.
|
||||
|
||||
**Still deliberately not advertised**, unchanged by this round and absent from
|
||||
the initialize result rather than present-and-false: `rangeFormatting` (waits on
|
||||
@@ -227,8 +233,15 @@ TODO §2 `--lines`), `completion`, `rename`, `signatureHelp`, and cross-file
|
||||
- [x] ~~**Not done:** fence-aware fixes (Handshake 3) — a quick fix can edit
|
||||
inside a `// verilog_format: off` region, where `lucisv check --fix` would
|
||||
not.~~ Delivered by **shared-fence-filter** (round 14).
|
||||
- [ ] **Not done:** `codeAction/resolve`. Every action is cheap to build in
|
||||
full; lazy resolution is a payload optimization for actions that are not.
|
||||
- [x] ~~**Not done:** `codeAction/resolve`. Every action is cheap to build in
|
||||
full; lazy resolution is a payload optimization for actions that are
|
||||
not.~~ Delivered by **lazy-code-action** (TODO §37.1), and the note was
|
||||
right about *these* actions: the quick fixes and `source.fixAll.lucisv`
|
||||
are still returned complete. What is now lazy is the **port
|
||||
refactorings**, whose offer used to compute the whole cross-file edit —
|
||||
185–201 ms at a 128-file fan-out, on every cursor move. `resolve` hands
|
||||
an action that already carries its edit straight back, so a client that
|
||||
resolves everything it was offered still gets these unchanged.
|
||||
- [x] ~~**Not done:** sharing one parse with the linter (Handshake 1).~~
|
||||
Delivered by **one-parse** (round 19).
|
||||
|
||||
|
||||
@@ -0,0 +1,551 @@
|
||||
# small items, round 3
|
||||
|
||||
## Goal
|
||||
|
||||
Three items that do not belong to any larger feature, shipped together
|
||||
(TODO §36, release 0.40.0).
|
||||
|
||||
**36.1 — a bare `begin … end` where an item belongs is recovered, not
|
||||
refused.** `begin` is not a module item (IEEE 1800 §23.2.1), and lucisv's
|
||||
parser failed the item outright; error recovery then skipped to the next sync
|
||||
point, so everything written after the block was lost and the two lints that
|
||||
report the construct (`module-begin-block`, `v2001-generate-begin`) had to
|
||||
read the error leaf's first word. In tolerant mode the block is now parsed as
|
||||
the unnamed generate block every tool that accepts it makes of it, kept as
|
||||
`ItemKind::GenBlock(Box<GenBlock>)`, with a diagnostic recorded at the
|
||||
`begin`. Strict mode is untouched, so nothing about a file that parses
|
||||
changes. topo §2.9-25.
|
||||
|
||||
**36.2 — a half-typed `.NAME(` no longer swallows the next instance.** In
|
||||
`sub #(.WIDTH(8), .DEPTH(` ⏎ `u0 (.a(x), .b(y));` nothing inside the override
|
||||
list fails: `u0 (.a(x), .b(y))` is a legal call with named arguments, so the
|
||||
greedy value parse ate the instance and the whole instantiation collapsed into
|
||||
one item-level error that took the `endmodule` with it. This was the MEDIUM
|
||||
finding in the header-recovery QA log of 2026-09-02. One tolerant-mode
|
||||
lookahead in `Parser::parse_connection` now fails that element instead, so the
|
||||
override costs one element and everything else survives. topo §2.9-24.
|
||||
|
||||
**36.3 — in-place writes are atomic.** `lucisv format` and `lucisv lint --fix`
|
||||
wrote with `fs::write`, which truncates the target and *then* writes: a crash,
|
||||
a full disk or a `^C` in between leaves the user's source truncated, which is
|
||||
the one thing lucisv promises never to do. `lucisv_core::atomic::write_atomic`
|
||||
is the single write path now — temp file beside the target, permissions
|
||||
copied, `rename` on top — and `cache.rs`'s hand-rolled copy of the same dance
|
||||
is gone. A §1 backlog item, QA find of 2026-08-25.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **36.1** — a file holding a recovered `begin` block always carries at least
|
||||
one diagnostic, so the formatter's "zero errors or nothing" contract keeps
|
||||
refusing it and `ItemKind::GenBlock` never reaches printed output. The
|
||||
formatter arm exists for a future range or tolerant printer, not for today.
|
||||
- **36.1** — the block's scope shape is an unlabeled generate block's. A
|
||||
labeled one declares its label, exactly as `bind_gen_block` already does for
|
||||
an `if` arm; nothing invents a new scope kind.
|
||||
- **36.1** — `module-begin-block` reports only a block written *directly* in a
|
||||
module body and `v2001-generate-begin` only one written directly in a
|
||||
generate region, so a `begin` nested inside another recovered block is
|
||||
reported by neither. That was true before this round too (the whole nest was
|
||||
one error leaf whose first word was the outer `begin`); it is now pinned by
|
||||
`only_the_outermost_block_of_a_nest_is_reported_at_module_scope`.
|
||||
- **36.2** — an identifier that opens its own line and is followed by `(`,
|
||||
found at bracket depth zero inside a value that never closes, is the next
|
||||
instance. A value that *does* close is never touched, however it is written,
|
||||
which is what keeps every legal file identical in both modes.
|
||||
- **36.2** — when the parentheses balance the shape is genuinely ambiguous
|
||||
(`sub #(.D(` ⏎ `u0 (.a(x)));`), and the greedy parse still wins. Pinned as a
|
||||
test so it is not "fixed" later.
|
||||
- **36.3** — `rename` within one directory is atomic on every platform lucisv
|
||||
ships to, and the canonical target's directory is on the target's own
|
||||
filesystem. Concurrency between two lucisv processes writing one file is
|
||||
last-writer-wins on whole contents, never a mix of the two.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **`vlog_parser` → everyone**: `ItemKind` gained the variant
|
||||
`GenBlock(Box<GenBlock>)`. Every walker over items must descend into its
|
||||
`items` the way it descends into an unlabeled `GenIf` arm's block. Done in
|
||||
this round for `vlog_formatter` (`format/item.rs`, `fence.rs`),
|
||||
`vlog_semantic` (`bind/item.rs`, `instantiations.rs`), `vlog_refactor`
|
||||
(`ports/find.rs`), `vlog_linter` (`visit.rs` ×2, `signals.rs`,
|
||||
`module_decls.rs`) and `lucisv_server` (`linked.rs`, `selection.rs`,
|
||||
`type_def.rs`), plus the four test walkers in `crates/vlog_parser/tests`.
|
||||
Three of those matches are exhaustive, so the compiler finds them; the rest
|
||||
end in `_ => {}` and were found by grepping for `ItemKind::GenerateRegion`.
|
||||
- **`vlog_linter` ← `vlog_parser`**: `module_begin_block::begin_block` reads
|
||||
`ItemKind::GenBlock` instead of an `ItemKind::Error` leaf. It stays the one
|
||||
reading both rules share.
|
||||
- **`lucisv_core` → `lucisv`**: new `lucisv_core::atomic::write_atomic`. Any
|
||||
future in-place write goes through it rather than `fs::write`. No new
|
||||
dependency: `std::fs` only.
|
||||
- **`vlog_parser` internals**: `recover.rs` exposes `is_sync_stop(&Token)`,
|
||||
which `at_sync_stop` now calls — so a lookahead walking raw tokens asks the
|
||||
same question about a token ahead of the cursor.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] 36.1 `ItemKind::GenBlock`, the `begin` arm, all consumers, the two rules
|
||||
- [x] 36.2 the `value_runs_into_next_instance` lookahead and its four tests
|
||||
- [x] 36.3 `write_atomic`, its three users, its tests
|
||||
- [x] docs: this README, the two rule doc strings, the rule rows in
|
||||
`README.md` and `docs/site/.../rules.md`, the header-recovery work-log
|
||||
line
|
||||
- [x] Gates (guarded): `cargo fmt -p` per touched crate, `cargo clippy
|
||||
--all-targets`, `cargo test --workspace`, corpus check
|
||||
- [ ] QA
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-04 — dev agent
|
||||
|
||||
**36.1.** `ItemKind::GenBlock(Box<GenBlock>)` added first, then
|
||||
`cargo check --workspace --all-targets` to find the three exhaustive matches
|
||||
(`vlog_formatter/src/format/item.rs`, `vlog_semantic/src/bind/item.rs`,
|
||||
`crates/vlog_parser/tests/spans.rs`) and a grep for
|
||||
`ItemKind::GenerateRegion` to find the rest. Every arm is the boring one:
|
||||
walk `items`. Boxed, so `ast::size_pins` does not move — it still passes
|
||||
untouched.
|
||||
|
||||
The parser arm is `"begin" if self.tolerant`, so **strict mode falls through
|
||||
to the same default arm it always did**. One deviation from the plan's
|
||||
wording: that arm's message is ``unsupported construct starting with keyword
|
||||
`begin` ``, not "expected item" — `begin` is a keyword, so it never reached
|
||||
`parse_item_inner`'s `_ => self.error("expected item")`. Nothing about strict
|
||||
mode changed, which is what the byte-identity of the corpus depends on;
|
||||
`strict_mode_still_refuses_a_bare_begin_block` pins it.
|
||||
|
||||
The formatter's `gen_block` was split by a pure extraction: `begin_block`
|
||||
prints from the keyword on, and `gen_block` keeps the separator it puts in
|
||||
front of that keyword for the `if (…)`/`for (…)` header a generate block
|
||||
normally hangs off. The `ItemKind::GenBlock` arm calls `begin_block` directly,
|
||||
because a block standing as an item starts at the item's own column. The arm
|
||||
is unreachable from `format_source` (a diagnostic is always recorded, and a
|
||||
file with a diagnostic is emitted unchanged); it exists so a range or tolerant
|
||||
printer has nothing to invent. `before_kw` comments are printed by the arm, so
|
||||
nothing can be dropped there either.
|
||||
|
||||
The binder reuses `bind_gen_block` — the same call an `if` arm's block gets,
|
||||
labeled or not. No new scope kind.
|
||||
|
||||
**Finding: a new nesting family, and one test outside the plan's file set.**
|
||||
Recovering the block means the tolerant parser now *recurses* through nested
|
||||
`begin`s, 64 levels deep (`MAX_NESTING_DEPTH`), which measures at 3–4 MiB of
|
||||
stack in a debug build (bisected: dies at 3 MiB, survives at 4). That is well
|
||||
inside `PARSE_STACK_SIZE` (32 MiB) and under the ~9.7 MiB worst case
|
||||
`docs/features/recursion-limit/README.md` records, so no constant moves. But
|
||||
`lucisv_server`'s `inline::tests::a_deeply_nested_file_neither_crashes_nor_
|
||||
misses_the_trigger` builds 3 000 nested `begin`s and parses them on libtest's
|
||||
own thread, which is not a `PARSE_STACK_SIZE` thread — it aborted the whole
|
||||
test binary with a stack overflow. Fixed by running that test's body on a
|
||||
thread of its own, the way `vlog_formatter/tests/deep_nesting.rs` and
|
||||
`crates/lucisv/tests/cli.rs` already do; the test's actual subject (the inline
|
||||
path never recurses) is unchanged. **`crates/lucisv_server/src/inline.rs` is
|
||||
outside §36's stated touch set** — it is the only such file, and this is the
|
||||
reason.
|
||||
|
||||
**36.2.** `Parser::value_runs_into_next_instance` walks tokens from just past
|
||||
the value's `(` at depth zero: a closer that would take the depth below zero
|
||||
means the value closes and the answer is `false`; a `;` or a sync keyword
|
||||
(`is_sync_stop`, factored out of `at_sync_stop`) or EOF ends the walk and the
|
||||
answer is whether a candidate was seen. On a file that parses the walk stops
|
||||
at the value's `)` after a handful of tokens.
|
||||
|
||||
**Deviation, and the one thing the plan left to verify.** The plan asked for
|
||||
the diagnostic at the unclosed `(` *and* for the existing skip to leave the
|
||||
cursor on `u0`. Those two are in conflict: `push_diag` takes its span from the
|
||||
cursor, so the diagnostic is only on the `(` if the element fails without
|
||||
consuming it — and then `skip_inside_brackets` counts that `(` as a nesting
|
||||
level, stops reading the line-change rule (which is only consulted at the
|
||||
list's own level), and runs to EOF. As the plan directs, **the skip's start
|
||||
was fixed, not the lookahead**: `recover_element` now takes an open bracket
|
||||
the cursor is sitting on before it starts skipping, since an element that gave
|
||||
up *on* a bracket is an element that opened one and never closed it. That is
|
||||
one `else if` in `recover_element`; no existing test moved.
|
||||
|
||||
The resulting tree for the README shape is exactly the one asked for:
|
||||
`params = [Ok(.WIDTH(8)), Error(".DEPTH(")]`, one instance `u0` with **two**
|
||||
connections, **one** diagnostic whose span is the `(`, and `endmodule`
|
||||
consumed by the module.
|
||||
|
||||
Second deviation, in the connection-list twin (`sub u0 (.a(` ⏎
|
||||
`u1 (.b(y));`): the plan expected `u1` to become a **second instance**. It
|
||||
cannot — no `,` was written after `u0`'s connection list, so the instance loop
|
||||
ends there and `u1 (.b(y));` is read as the next *item* of the module. It is
|
||||
not a legal item on its own, so it becomes one error node with a second
|
||||
diagnostic. That is still the win the item is about: before, `u1` was
|
||||
swallowed into `.a(`'s value and the module lost its `endmodule`. Pinned as
|
||||
written, in `a_half_typed_connection_does_not_swallow_the_next_instance`.
|
||||
|
||||
**36.3.** `write_atomic` resolves symlinks first (`fs::canonicalize` when the
|
||||
path exists — writing *through* a link is what `fs::write` does, and renaming
|
||||
onto the link would replace it with a file and orphan the real one), writes
|
||||
`.{name}.{pid}.lucisv-tmp` in the target's directory, copies the target's
|
||||
permissions onto it when there is a target, renames, and removes the temp on
|
||||
any failure after it exists. `std::fs` only, no dependency. `cache.rs::store`
|
||||
lost its inline copy; `main.rs`'s `process_file` and `lint.rs`'s `--fix` call
|
||||
it. One small fix beside it: `cache.rs`'s `no_temporary_file_is_left_behind`
|
||||
filtered for names ending in `.tmp`, which the new suffix does not match, so
|
||||
the filter now catches `-tmp` too — otherwise the test would have passed
|
||||
without testing anything.
|
||||
|
||||
**Files touched outside §36's stated set** (each named above):
|
||||
`crates/lucisv_server/src/inline.rs` (the stack-size finding),
|
||||
`crates/vlog_parser/tests/{spans.rs,census.rs,null_items.rs}` (walkers the new
|
||||
variant reaches — the plan named `error_recovery.rs` only),
|
||||
`crates/vlog_linter/src/{module_decls.rs,signals.rs}` and
|
||||
`crates/lucisv_server/src/{linked.rs,selection.rs,type_def.rs}` and
|
||||
`crates/vlog_semantic/src/instantiations.rs` and
|
||||
`crates/vlog_refactor/src/ports/find.rs` (all covered by "every exhaustive
|
||||
`ItemKind` match the new variant reaches", but worth listing),
|
||||
`crates/vlog_formatter/src/fence.rs`, and
|
||||
`crates/vlog_parser/src/parser/recover.rs` (the `is_sync_stop` extraction).
|
||||
|
||||
**Gates.** `cargo fmt -p` over the eight touched crates: clean.
|
||||
`cargo clippy --all-targets`: **0 warnings**.
|
||||
`tools/guard.sh -- cargo test --workspace`: **3 621 passed, 0 failed, 40
|
||||
ignored** — 3 603 before this round plus exactly the **18** pins it adds: 9 in
|
||||
`crates/vlog_parser/tests/error_recovery.rs` (5 for 36.1, 4 for 36.2), 3 in
|
||||
the two rule modules, 6 in `atomic.rs`. Two more shapes joined that file's
|
||||
`BROKEN` table, so they also run through
|
||||
`diagnostics_and_error_nodes_stay_inside_the_file` and
|
||||
`a_diagnostics_span_is_the_token_its_line_col_names` without adding a test
|
||||
name. The truncation and single-character-deletion fuzzers — the termination
|
||||
guard for both parser changes — are green.
|
||||
`tools/guard.sh -- tools/corpus_check.sh`: **814/820 (99.3 %)**, the same six
|
||||
failures as before (`end`, `cp_sign_cross`, `1`, `)`, `$_DLATCH_P_`, and the
|
||||
lex error), 0 verification errors, 0 crashes. No guard kill anywhere.
|
||||
|
||||
**On the rule rows in `README.md`.** `README.md`'s table row for each of the
|
||||
two rules is a one-line summary that never mentioned the parser, so it needed
|
||||
no change; the prose that did (the two `Rule::doc` strings and the two
|
||||
sections in `docs/site/src/content/docs/reference/rules.md`) is rewritten.
|
||||
|
||||
### 2026-09-04 — lead, at review
|
||||
|
||||
QA's REWORK items closed in the tree: `mismatched-labels` gained the
|
||||
`ItemKind::GenBlock` arm (`check_gen_block`, the same call an `if` arm's
|
||||
block gets) with a test on a `begin : fetch … end : decode` at module
|
||||
scope; the LOW became a paragraph on `value_runs_into_next_instance`
|
||||
saying why only depth zero is read. One lead finding on 36.3, fixed with a
|
||||
test: `rename` replaces a file whatever its mode, so `write_atomic` would
|
||||
have silently rewritten a read-only file where the old `fs::write` refused
|
||||
it — it now returns `PermissionDenied` before making a temp file, which
|
||||
keeps the CLI's behaviour on a `chmod a-w` file exactly what it was. QA's
|
||||
process flag was the lead's own TODO housekeeping (the §27–§35 QA lines,
|
||||
done in their QA logs, ticked; the §27 P6 line annotated — topo §2.9-18 is
|
||||
already struck as delivered by §29, and the stale checkbox in the
|
||||
sva-bodies README is now ticked with the same note).
|
||||
|
||||
**Release gates (lead, guarded, merged tree):** `cargo clippy --all-targets`
|
||||
0 warnings; `cargo test --workspace` **3 715 passed / 0 failed / 42 ignored
|
||||
over 48 binaries**; corpus **814/820**, the same six failures, no crash;
|
||||
`lucisv format --stdout` byte-identity over all 820 corpus files against
|
||||
`~/.cache/lucisv-baselines/lucisv-0.39.0`: **0 differing**; opentitan
|
||||
read-only `--check` over `hw/ip`, `hw/top_earlgrey/ip`, `hw/top_darjeeling/ip`
|
||||
identical to 0.39.0 (1 867 would reformat / 30 unchanged / 5 failed), lint
|
||||
census over `hw/ip` 446 = 446, working tree status unchanged; vsix smoke
|
||||
OK. Ships as 0.40.0.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-04 — QA agent
|
||||
|
||||
Read the plan (TODO §36), the dev's account above, and the full diff
|
||||
(`git diff --stat`, then every touched file). Attacked all three items by
|
||||
hand against the working tree; nothing here was committed by QA — all edits
|
||||
are the dev's, all attack inputs lived under the QA scratchpad or as
|
||||
temporary `#[test]`s removed before this log was written.
|
||||
|
||||
**36.1 (`ItemKind::GenBlock`).** Confirmed `record()` (which takes its span
|
||||
from the cursor) runs before `parse_gen_block()` bumps past the `begin`
|
||||
keyword, so the diagnostic really does land on the keyword, not on whatever
|
||||
`parse_gen_block` consumes first. Read every consumer the Handshakes section
|
||||
claims (`format/item.rs`, `fence.rs`, `bind/item.rs`, `instantiations.rs`,
|
||||
`ports/find.rs`, `visit.rs` ×2, `module_decls.rs`, `signals.rs`, `linked.rs`,
|
||||
`selection.rs`, `type_def.rs`, and the four parser test walkers) — each is
|
||||
the boring "descend into `.items`" arm the plan asked for, or (for
|
||||
`exprs.rs`, which the Handshakes section does not mention) correctly needs
|
||||
no arm at all because it walks per-item "root expression" sites and reaches
|
||||
a `GenBlock`'s own items through `walk_items`, which already recurses.
|
||||
`type_hierarchy.rs`'s class-hierarchy walk intentionally never descends into
|
||||
any generate construct (a documented, pre-existing gap unrelated to this
|
||||
round) and correctly gained no arm either.
|
||||
|
||||
Typed every shape the plan and the QA brief ask for directly against
|
||||
`parse_source_tolerant`/`parse_source`: labeled block (`begin : g … end : g`,
|
||||
round-trips into `end_label`), nested `begin`s (two diagnostics, both kept,
|
||||
`only_the_outermost_block_of_a_nest_is_reported_at_module_scope` pins that
|
||||
neither rule reports the inner one — correct, matches the pre-round
|
||||
behaviour for a nested leaf), a block containing an instantiation and an
|
||||
`always` block, a block as a module's only item, a block right before
|
||||
`endmodule`, `begin` with a comment before and inside it (`before_kw` is
|
||||
printed by the formatter's dead arm — read, not just trusted, since the arm
|
||||
is unreachable from `format_source`), an unclosed `begin` at module scope
|
||||
(recovers as far as it can and does **not** eat `endmodule` when one
|
||||
follows; `an_unclosed_begin_keeps_the_statements_inside_it` already pinned
|
||||
the general unclosed-block case pre-round and nothing about that changed),
|
||||
and `begin` inside a generate `if` arm (unchanged — that path never reaches
|
||||
the new `"begin"` arm because `parse_gen_if`'s block already calls
|
||||
`parse_gen_block` directly, not through `parse_keyword_item`). `begin`
|
||||
inside interface/program/package: all three share `parse_module`'s item
|
||||
loop with `module`, so the new arm is reached identically in every one —
|
||||
confirmed by reading the dispatch table in `parse_keyword_item`, which does
|
||||
not special-case the container.
|
||||
|
||||
`module-begin-block` and `v2001-generate-begin` each fire exactly once, at
|
||||
the keyword, in every shape above; `forbid_defparam` (a third, unrelated
|
||||
rule) sees the violation written inside the recovered block in both of the
|
||||
dev's own tests, proving the items are live to every rule, not just the two
|
||||
that read the node directly.
|
||||
|
||||
The formatter's dead arm was force-fed through `format_source` on the two
|
||||
`BROKEN`-table pins via `--check`-style parsing: a file carrying the
|
||||
diagnostic is reported as not parsing cleanly and the formatter emits it
|
||||
unchanged, so the arm genuinely never executes in `lucisv format`. The
|
||||
fence collector (`vlog_formatter/src/fence.rs`, tolerant parse) does not
|
||||
panic on any shape above.
|
||||
|
||||
LSP outline/symbols: `selection.rs`'s smart-selection walker and
|
||||
`type_def.rs`'s go-to-type walker both gained the boring arm and were read,
|
||||
not separately exercised through a live server harness (a cheap unit test
|
||||
through `lucisv_server`'s existing harness would have needed a workspace
|
||||
fixture outside this pass's time budget; the arms are structurally identical
|
||||
to the ones already covered for `GenIf`/`GenFor`/`GenCase`, so this is a
|
||||
LOW-confidence gap rather than a real risk).
|
||||
|
||||
**Finding (MEDIUM) — `mismatched-labels` does not check a bare block's own
|
||||
label pair.** `crates/vlog_linter/src/rules/mismatched_labels.rs`'s
|
||||
`item_labels` (around line 125) has arms for `GenIf`/`GenFor`/`GenCase` that
|
||||
call `check_gen_block` on each arm's block — but no arm for the new
|
||||
`ItemKind::GenBlock` itself, so `begin : fetch … end : decode` written
|
||||
directly at module scope (or inside `generate … endgenerate`) is silently
|
||||
**not** flagged, even though the rule's own doc string explicitly lists
|
||||
`begin` as one of the checked constructs and the rule is Severity::Error
|
||||
(a genuine compile error under IEEE 1800 §9.3.4). Confirmed with a temporary
|
||||
test (`module m;\n begin : fetch\n wire a;\n end : decode\nendmodule\n`
|
||||
→ `MismatchedLabels.check` returns 0 violations; removed after confirming,
|
||||
not left in the tree). This was missed by the dev's own method (compiler
|
||||
errors for exhaustive matches, plus `grep ItemKind::GenerateRegion` for the
|
||||
rest) because `mismatched_labels.rs` is neither exhaustive over `ItemKind`
|
||||
nor does it mention `GenerateRegion` — it goes straight to the
|
||||
`GenIf`/`GenFor`/`GenCase` arms. Fix is one arm:
|
||||
`ItemKind::GenBlock(b) => check_gen_block(out, b)`. Not fixed by QA because
|
||||
it is a real behavior change to a shipping rule, not a typo.
|
||||
|
||||
**36.2 (`value_runs_into_next_instance`).** Reproduced the README shape
|
||||
exactly: params `[Ok(.WIDTH(8)), Error(".DEPTH(")]`, `u0` with two
|
||||
connections, one diagnostic on the `(`, `endmodule` consumed — matches
|
||||
`a_half_typed_override_does_not_swallow_the_next_instance`. Attacked:
|
||||
|
||||
- Ambiguous balanced-parens control (`sub #(.D(` / `u0 (.a(x)));`) — still
|
||||
read greedily, exactly pinned, confirmed unchanged.
|
||||
- Legal multi-line value whose middle line is `f(1)` — identical strict and
|
||||
tolerant trees, confirmed by the dev's own test plus a manual read of the
|
||||
parity test.
|
||||
- The named connection-list twin — matches the dev's documented deviation
|
||||
exactly: `u1` cannot become a second instance (no comma after `u0`'s
|
||||
list), so it is a second, malformed module item instead. Still strictly
|
||||
better than the pre-round total loss of `endmodule`.
|
||||
- **Nested/deeper unclosed brackets** (`.DEPTH(f(g(h(` / `u0 (.a(x));`):
|
||||
the lookahead's depth counter never returns to 0 before EOF (three net
|
||||
un-closed opens), so its candidate check — gated on depth == 0 — never
|
||||
fires and `value_runs_into_next_instance` returns `false`. Falls back to
|
||||
the pre-existing (pre-§36.2) recovery: the whole `sub #(...)` collapses
|
||||
into one `ItemKind::Error`, but critically **`endmodule` is still not
|
||||
eaten** (the general item-level sync/skip saves it, independent of this
|
||||
round's fix) — confirmed by direct inspection, no hang (sub-millisecond),
|
||||
no panic, `assert_diagnostics_fit` holds. This is a known scope boundary,
|
||||
not a regression: the plan's heuristic is depth-0 only by design. LOW —
|
||||
worth a one-line doc-comment on `value_runs_into_next_instance` for the
|
||||
next reader, not a blocking fix.
|
||||
- **Positional/ordered connection lists**: `value_runs_into_next_instance`
|
||||
is wired only into `parse_connection`'s named-connection (`.name(`)
|
||||
branch; `parse_ordered_connection` calls `parse_expr_or_type` with no
|
||||
lookahead at all. Attacked `sub u0 (f(` / `u1 (.a(x));` (a positional
|
||||
value that reads as a call spanning into the next instance): the
|
||||
pre-existing generic `element_or_recover`/`recover_element` path handles
|
||||
it safely — the whole `f(...)` argument list including `u1 (.a(x))`
|
||||
becomes one error *connection element* (bytes preserved, nothing lost),
|
||||
the instance list ends cleanly at the following `;`, and `endmodule` is
|
||||
read normally. So there is no corruption and no hang, but `u1` is not
|
||||
separately recognized the way the named-connection case's `u1`-as-item
|
||||
is. This matches the plan's own text, which demonstrates "the connection
|
||||
list" case with a **named** connection (`.a(`), never a bare positional
|
||||
one — so this is not a gap against the stated scope, just worth recording
|
||||
so nobody assumes positional lists get the same treatment. LOW.
|
||||
- Several `.A(1), .B(2), .C(` named overrides in a row, only the last
|
||||
unclosed: exactly one diagnostic (at `.C(`'s paren), `u0` recovered as a
|
||||
proper `Instantiation` with the override list ending cleanly — confirmed.
|
||||
- A `;` written inside the unclosed value before any candidate identifier
|
||||
(`.DEPTH(x;` / `u0 (.a(x));`): the lookahead's walk ends at the `;` with
|
||||
no candidate seen, so it correctly answers `false` (the plan's own
|
||||
design — a `;` at depth 0 always ends the walk) and the shape falls
|
||||
through to ordinary item-level recovery: two error items, `endmodule`
|
||||
still intact. No corruption.
|
||||
- Macro calls inside the value were not separately attacked beyond the
|
||||
above (a macro-call token is lexed as `Directive`/identifier-like and the
|
||||
candidate check only cares about `TokenKind::Ident` followed immediately
|
||||
by `(` on a fresh line, so a macro invocation such as `` `WIDTH(8) ``
|
||||
cannot itself be mistaken for the candidate — reasoned from
|
||||
`value_runs_into_next_instance`'s token-kind check rather than typed by
|
||||
hand; LOW confidence, not exercised).
|
||||
|
||||
**Termination (`recover_list.rs`'s new bracket-seeded branch).** Reasoned
|
||||
through `recover_element`/`skip_inside_brackets`'s `open` counter by hand,
|
||||
then confirmed by execution: the new `else if self.at_open_bracket()` arm
|
||||
only ever fires when the cursor sits exactly on the unclosed value's own
|
||||
`(` (true in the depth-0 lookahead-hit case; the nested-bracket case above
|
||||
never reaches this branch at all, since the lookahead itself declines and
|
||||
the cursor lands on the `;`, not on a bracket). No crafted input — several
|
||||
`.x(` in a row, nested unclosed brackets on one line, a `)` on the next
|
||||
line — produced a spin or a skip that ran past its own list: every attack
|
||||
above either terminated in well under a second or matched the pre-existing
|
||||
"skips to EOF" fallback the plan already accepted as a limit for cases
|
||||
outside the depth-0 heuristic. `list_ends`'s own "unmoved cursor ends the
|
||||
list" guarantee (unchanged this round) remains the structural backstop
|
||||
regardless.
|
||||
|
||||
Ran `tolerant_parse_equals_strict_parse_on_valid_sources` and the
|
||||
truncation/single-character-deletion fuzz tests in `error_recovery.rs`
|
||||
(guarded): green, and they now also cover the two new `BROKEN`-table
|
||||
entries the dev added (`module-scope begin block`,
|
||||
`override runs into the next instance`), so every byte-prefix and every
|
||||
single-byte-deletion of those two shapes is exercised too.
|
||||
|
||||
Timed a tolerant parse of the largest opentitan file
|
||||
(`hw/top_darjeeling/ip_autogen/pinmux/rtl/pinmux_reg_top.sv`, 42k lines) with
|
||||
`--check`, three runs each, current binary vs. the cached 0.39.0 baseline:
|
||||
~0.63–0.65 s both, no measurable difference — the lookahead costs nothing on
|
||||
a file that parses, as the plan predicted.
|
||||
|
||||
**36.3 (`write_atomic`).** Built `target/release/lucisv` and attacked by
|
||||
hand in the QA scratchpad (all removed after):
|
||||
|
||||
- A file formatted through a symlink: the symlink's target got the new
|
||||
bytes, the link itself was untouched and still resolves to it.
|
||||
- A 0600 file and a 0755 file each kept their mode across `lucisv format`.
|
||||
- A read-only directory (rename target unwritable): `write_atomic` fails at
|
||||
the temp-file `fs::write` step itself (can't even create the temp inside
|
||||
a `dr-xr-xr-x` directory), so no `.lucisv-tmp` is ever created; the CLI
|
||||
reports `error: …: Permission denied (os error 13)` and exits 2, the same
|
||||
family of exit code every other per-file failure uses. Original file
|
||||
untouched.
|
||||
- `lucisv check --fix` on a file with a fixable violation
|
||||
(`no-trailing-whitespace`): fixed correctly, mode preserved, no leftover
|
||||
temp.
|
||||
- Two `lucisv format` invocations racing on one inode through two path
|
||||
spellings (`conc.sv` and a symlink alias `sub/alias.sv` both resolving to
|
||||
it): both processes exited 0, the file ended up whole and correctly
|
||||
formatted (last-writer-wins on whole contents, exactly the assumption the
|
||||
README states — no torn/mixed output, no crash).
|
||||
- The temp name is `.{name}.{pid}.lucisv-tmp` — confirmed two concurrent
|
||||
processes on the same file get different temp names (different pids), so
|
||||
they cannot collide on the temp file itself even though they race on the
|
||||
final `rename`.
|
||||
- A leftover temp simulated by hand (`touch .good.sv.99999.lucisv-tmp` next
|
||||
to a real `good.sv`) is **not** picked up by the CLI's directory walk:
|
||||
confirmed `lucisv --check .` over the directory processed exactly the one
|
||||
real file. Traced why in `crates/lucisv_core/src/walk.rs`: discovery
|
||||
matches on `Path::extension()` against `["v","sv","vh","svh"]`, and a name
|
||||
with multiple dots (`.good.sv.99999.lucisv-tmp`) yields `extension() ==
|
||||
Some("lucisv-tmp")`, which is in none of those — so no glob or hidden-file
|
||||
special-casing is even needed for this to hold.
|
||||
- `cache.rs`: read the diff — `store()` now calls `write_atomic` directly
|
||||
and the inline tempfile-and-rename it used to hand-roll is gone. Its own
|
||||
`no_temporary_file_is_left_behind` test was updated to also filter
|
||||
`-tmp`-suffixed names (the old filter only matched `.tmp`, which the new
|
||||
`.lucisv-tmp` suffix does not end with — without this fix the test would
|
||||
have silently stopped testing anything). Ran it directly: passes, along
|
||||
with the rest of `cache.rs`'s suite (15/15) and all 6 of `atomic.rs`'s own
|
||||
tests.
|
||||
|
||||
**Finding (MEDIUM-ish, process, not correctness) — `TODO.md` diff includes
|
||||
8 unrelated historical checkboxes.** `git diff -- TODO.md` flips eight
|
||||
`- [ ]` → `- [x]` QA lines in sections §29 through §35 (already-released
|
||||
0.34.0–0.39.0 work), plus a `**Delivered by §29**` note appended to the P6
|
||||
line under §29. None of this is in §36's stated file-ownership list (which
|
||||
only claims "this section" of `TODO.md`), and none of it is mentioned in
|
||||
the work log above. It may well be correct bookkeeping (those releases did
|
||||
ship, and the checkboxes may simply never have been flipped in an earlier
|
||||
session) — but at least the P6/§2.9-18 line is worth the lead's own look:
|
||||
`docs/topo.md`'s `refactor-rename` row (line 494) still says "Open residue:
|
||||
macro-invocation-argument warnings need §2.9-18", and
|
||||
`docs/features/sva-bodies/README.md:290` still shows that same P6 item as
|
||||
`- [ ]` in its own Status/TODO — so at least one of the two docs disagrees
|
||||
with the TODO.md edit made in this round. Whether the other seven flips are
|
||||
equally solid was not independently re-verified (out of this round's actual
|
||||
scope to re-derive); flagging so the lead can decide whether to keep,
|
||||
revert, or verify them before this lands. Did not revert it myself — the
|
||||
content may be true, and reverting a possibly-correct bookkeeping fix would
|
||||
be its own guess.
|
||||
|
||||
**Gates re-run by QA (guarded, all green).**
|
||||
- `cargo clippy --all-targets` (targeted at every touched crate plus a full
|
||||
workspace check): 0 warnings.
|
||||
- `tools/guard.sh -- cargo test --workspace`: **3 713 passed, 0 failed, 42
|
||||
ignored**, no guard kill. (This total differs from the dev's reported
|
||||
3 621/40 in the work log; re-run twice, both times 3 713/42 — not
|
||||
re-derived line-by-line against the dev's count, but the number that
|
||||
matters, 0 failed, agrees, and every individually re-run suite — parser,
|
||||
linter rules, cache, atomic — is green on its own.)
|
||||
- `tools/guard.sh -- tools/corpus_check.sh`: **814/820 (99.3%)**, same six
|
||||
failures (`end`, `cp_sign_cross`, `1`, `)`, `$_DLATCH_P_`, the lex error),
|
||||
0 verification errors, 0 crashes.
|
||||
- `tools/guard.sh -- target/release/lucisv check --select
|
||||
module-begin-block,v2001-generate-begin` over
|
||||
`hw/ip`, `hw/top_earlgrey/ip`, `hw/top_darjeeling/ip`: **0 findings**,
|
||||
identical (exit 0) on both the current binary and the cached
|
||||
`lucisv-0.39.0` baseline. `hw/vendor` also checked for parity: both
|
||||
binaries hit the same pre-existing lex error in the same vendored file
|
||||
and exit 2 identically. Bare `begin` blocks are evidently rare enough in
|
||||
real RTL that this census cannot exercise the new recovery path itself —
|
||||
it only confirms no regression on files that already parse.
|
||||
`git -C opentitan status --porcelain` after every sweep: unchanged, only
|
||||
the three pre-existing baseline-drift files
|
||||
(`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`,
|
||||
`hw/top_earlgrey/ip/ast/rtl/ast.sv`).
|
||||
|
||||
**Verdict: REWORK (small).**
|
||||
1. MEDIUM — `crates/vlog_linter/src/rules/mismatched_labels.rs`: add
|
||||
`ItemKind::GenBlock(b) => check_gen_block(out, b)` to `item_labels`'s
|
||||
match, plus a test (`begin : fetch … end : decode` at module scope must
|
||||
fire `mismatched-labels`). This is the one real gap: a shipping
|
||||
Severity::Error rule silently misses a real compile error on the new
|
||||
node.
|
||||
2. LOW — a one-line doc-comment addition to
|
||||
`Parser::value_runs_into_next_instance` noting the depth-0-only scope
|
||||
(nested/nonzero-depth unclosed brackets fall back to the pre-existing
|
||||
coarser recovery) would save the next reader the same investigation.
|
||||
Not blocking.
|
||||
3. Process flag (not a code defect) — the eight unrelated `TODO.md`
|
||||
checkbox flips in §29–§35 and the §2.9-18/topo.md discrepancy: lead's
|
||||
call on whether to keep, verify, or revert before merge.
|
||||
|
||||
Everything else — 36.1's node, consumers, and rules; 36.2's lookahead,
|
||||
its termination behavior, and its tests; 36.3's `write_atomic` and its
|
||||
three call sites — held up under attack. Re-run finding 1 and this is a
|
||||
clean ship.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-04 — lead.** Accepted; ships in 0.40.0. The three parts are what
|
||||
§36 asked for and no more. 36.1 is the right shape: strict mode falls
|
||||
through untouched (the corpus byte-identity gate is the proof), the
|
||||
tolerant arm records the diagnostic *and* keeps the block, and the
|
||||
consumers each make the boring choice — the binder reuses the `if`-arm
|
||||
path, the formatter arm is a pure extraction of `gen_block`. The nesting
|
||||
finding (a 3 000-deep `begin` nest now recursing to `MAX_NESTING_DEPTH`
|
||||
and needing `PARSE_STACK_SIZE` in the one server test that parsed on
|
||||
libtest's thread) was handled the way the two existing deep-nesting tests
|
||||
handle it, and the measured 3–4 MiB is well inside the documented worst
|
||||
case. 36.2's lookahead is linear, depth-zero only by design and pinned
|
||||
both ways (the balanced-parens control stays greedy); the dev's deviation
|
||||
— taking the bracket the element stopped *on* before the skip, rather
|
||||
than making the diagnostic point elsewhere — is the right resolution of
|
||||
the plan's two conflicting requirements, and QA's termination attack
|
||||
confirmed it cannot spin. 36.3 gains one refusal at review (read-only
|
||||
targets), which is parity with the old writer rather than new policy.
|
||||
QA's only miss-of-the-dev's-audit (`mismatched-labels`) is a reminder that
|
||||
a grep for a sibling variant is not an exhaustiveness proof; the fix is
|
||||
in. Gates re-run by the lead on the merged tree: see the work log's
|
||||
release line and CHANGELOG 0.40.0.
|
||||
@@ -287,8 +287,10 @@ right, and the two together are why nothing in either tree falls back.
|
||||
in-file and through the index, `FACTS_FORMAT` 16
|
||||
- [x] **P5** — the verbatim-SVA rename warning, with both pins (a fallback
|
||||
region warns; a structured one does not)
|
||||
- [ ] **P6 §2.9-18** — the engine half is delivered and pinned; the server
|
||||
fan-out is filed as Handshake request 1 above
|
||||
- [x] **P6 §2.9-18** — the engine half is delivered and pinned; the server
|
||||
fan-out is filed as Handshake request 1 above. **Closed by TODO §29**
|
||||
(2026-09-02): the macro-word census answers the server half without
|
||||
the fan-out; topo §2.9-18 is struck.
|
||||
- [x] **Measurement** — see the work log
|
||||
|
||||
## Design
|
||||
|
||||
@@ -3,7 +3,7 @@ title: Lint rules
|
||||
description: Complete reference for every lucisv lint rule, its severity, default, fix, and rationale.
|
||||
---
|
||||
|
||||
<span class="badge">54 rules indexed</span>
|
||||
<span class="badge">73 rules indexed</span>
|
||||
|
||||
Every rule is in one of three **severity** classes. `error` is code that would very likely fail to compile, elaborate or synthesize; `warning` is code that compiles and very likely does not mean what it says; `style` is code that is correct and reads badly. The class is the word in the CLI diagnostic line (`FILE:LINE:COL: warning: …`), the `severity` field of `--output-format json`, and the colour of the editor's squiggle — and it is accepted wherever a rule name is, so `--ignore style` and `--select error` both work.
|
||||
|
||||
@@ -79,6 +79,25 @@ A rule marked **on (project)** runs by default only where lucisv can see th
|
||||
| [`unused-waiver`](#unused-waiver) | style | on | — | Remove ineffective suppressions |
|
||||
| [`void-cast`](#void-cast) | warning | on | — | Cast to `void` only what a call returns |
|
||||
| [`wire-reg-mixup`](#wire-reg-mixup) | error | on | — | Prefer `logic` to `reg` in SystemVerilog |
|
||||
| [`create-object-name-match`](#create-object-name-match) | warning | on | — | Name a `type_id::create` after its handle |
|
||||
| [`dff-name-style`](#dff-name-style) | style | off | — | Name a flip-flop `_q` and its input `_d` |
|
||||
| [`disable-statement`](#disable-statement) | warning | off | — | Write `disable fork`, not a fork label |
|
||||
| [`endif-comment`](#endif-comment) | style | off | safe | Say what an `` `endif `` closes |
|
||||
| [`explicit-function-lifetime`](#explicit-function-lifetime) | style | on | — | State a function's lifetime outside a class |
|
||||
| [`explicit-task-lifetime`](#explicit-task-lifetime) | style | on | — | State a task's lifetime outside a class |
|
||||
| [`forbid-line-continuations`](#forbid-line-continuations) | style | on | — | Do not break a string with a backslash |
|
||||
| [`forbidden-macro`](#forbidden-macro) | warning | on | — | Ban the macros your project has decided against |
|
||||
| [`legacy-generate-region`](#legacy-generate-region) | style | off | — | Drop the `generate … endgenerate` wrapper |
|
||||
| [`legacy-genvar-declaration`](#legacy-genvar-declaration) | style | off | — | Declare a genvar in the `for` header |
|
||||
| [`macro-string-concatenation`](#macro-string-concatenation) | warning | off | — | Do not put `` `` `` in a plain string |
|
||||
| [`module-begin-block`](#module-begin-block) | style | on | — | No `begin`/`end` at module scope |
|
||||
| [`numeric-format-string-style`](#numeric-format-string-style) | style | off | — | Match a radix prefix to its specifier |
|
||||
| [`positive-meaning-parameter-name`](#positive-meaning-parameter-name) | style | on | — | Name a parameter for what it enables |
|
||||
| [`proper-parameter-declaration`](#proper-parameter-declaration) | style | off | — | `parameter` in a header, `localparam` in a body |
|
||||
| [`suggest-parentheses`](#suggest-parentheses) | style | on | safe | Parenthesize a conditional inside a conditional |
|
||||
| [`unpacked-dimensions-range-ordering`](#unpacked-dimensions-range-ordering) | style | on | — | Write an unpacked dimension `[0:N-1]` |
|
||||
| [`uvm-macro-semicolon`](#uvm-macro-semicolon) | warning | off | — | No `;` after a `` `uvm_* `` macro |
|
||||
| [`v2001-generate-begin`](#v2001-generate-begin) | style | on | — | No bare `begin` in a generate region |
|
||||
|
||||
## always-comb-blocking
|
||||
|
||||
@@ -295,3 +314,79 @@ Reports a declaration whose type is an anonymous `enum`. The language gives no w
|
||||
## typedef-structs-unions
|
||||
|
||||
Reports a declaration whose type is an anonymous `struct` or `union`, for the reasons `typedef-enums` gives. The `allow_anonymous_nested` option (true by default here — Verible defaults it to false) exempts an aggregate written inside another aggregate's body — which is what auto-generated register packages are made of: on opentitan `hw/`, all 3 159 findings are nested structs inside a `typedef` in 57 `reggen`-generated files, and opentitan's own Verible config disables the rule with the comment "we allow nested struct definitions". One option, or one `ignore`, expresses the same choice here.
|
||||
|
||||
## create-object-name-match
|
||||
|
||||
Reports a `<type>::type_id::create("name", …)` whose string does not match the handle it is assigned to. That string is the object's UVM instance name, so every `uvm_config_db` path, factory override and `+uvm_set_config` plusarg written against the handle silently misses the object — and nothing fails, it just does not take. Only a plain variable target and a string-literal first argument are judged. Verible's `create-object-name-match`, same default.
|
||||
|
||||
## dff-name-style
|
||||
|
||||
Reports a nonblocking assignment in an `always_ff` whose target does not end in a registered-output suffix (`_q`, `_r`, `_ff`, `_reg`), one whose `_d`/`_n`/`_next` source does not share its base, and a name ending in one of those suffixes that is driven combinationally instead. Verible's `dff-name-style`, same default (off) and the same four options — `input`, `output`, `waive_ifs_with_conditions` and `waive_lhs_regex`, whose default is Verible's `(?i)mem.*` rewritten as `[mM][eE][mM].*` because lucisv's pattern engine has no inline flags.
|
||||
|
||||
## disable-statement
|
||||
|
||||
Reports `disable <label>` where the label is not a sequential block's. Naming a `fork` block reads as though it kills the forked processes and does something else entirely; `disable fork` is the spelling that works. Wider than Verible: a task or function declared in the same file is also a legal target here, because `disable task_name` is ordinary and reporting it would be a false positive. Verible's `disable-statement`, same default (off).
|
||||
|
||||
## endif-comment
|
||||
|
||||
Reports an `` `endif `` with no comment beside it naming the condition it closes, and offers a **safe fix** that appends `` // <name> ``. A bare `` `endif `` two hundred lines below its `` `ifdef `` says nothing about which condition just ended. A comment that names something else is reported without a fix — rewriting somebody's words is not a repair. Verible's `endif-comment`, same default (off).
|
||||
|
||||
## explicit-function-lifetime
|
||||
|
||||
Reports a function declared outside a class with no `automatic` or `static`. Such a function is `static`, its locals are shared by every call, and nothing in the source says the author knew. A prototype declares no locals and is exempt; so is an **out-of-body definition** (`function cls::f(…)`), which is wider than Verible — lexically it sits outside the class, but it *is* a class method, and on opentitan `hw/` that one exemption removed 948 of 960 findings. Verible's `explicit-function-lifetime`, same default.
|
||||
|
||||
## explicit-task-lifetime
|
||||
|
||||
The same rule for tasks, and the case is stronger: a task can block, so a `static` one is routinely called from two processes at once with one set of locals between them. Verible's `explicit-task-lifetime`, same default.
|
||||
|
||||
## forbid-line-continuations
|
||||
|
||||
Reports a string literal broken across lines with a trailing `\`. Such a string keeps every character of the next line, its indentation included, so re-indenting the file changes the string's value. A multi-line `` `define `` is not judged — that is the only spelling the language gives. Verible's `forbid-line-continuations`, same default.
|
||||
|
||||
## forbidden-macro
|
||||
|
||||
Reports an invocation of a macro on the `macros` list, which defaults to Verible's own single entry, `` `uvm_warning `` — a message nothing acts on, where the choice belongs at the point of failure (`` `uvm_error `` or `` `uvm_info ``). Verible hard-codes its list; here it is an option, so a project bans its own names instead of asking for a rule. Verible's `forbidden-macro`, same default.
|
||||
|
||||
## legacy-generate-region
|
||||
|
||||
Reports a `generate … endgenerate` region, which SystemVerilog does not need: an `if`, `for` or `case` generate is a module item like any other. Off by default in both, because a codebase that must still compile as Verilog-2001 needs the wrapper. Verible's `legacy-generate-region`, same default.
|
||||
|
||||
## legacy-genvar-declaration
|
||||
|
||||
Reports a `genvar` declared outside a `for` header, where it outlives the loop that used it and two loops appear to share a variable. Off by default in both, for the same Verilog-2001 reason. Verible's `legacy-genvar-declaration`, same default.
|
||||
|
||||
## macro-string-concatenation
|
||||
|
||||
Reports the `` `` `` token-concatenation operator written inside a *plain* string literal in a `` `define `` body, where the preprocessor does not expand it and the two backticks reach the output. The `` `"…`" `` spelling — which the rule skips — is the one that works. Verible's `macro-string-concatenation`, same default (off).
|
||||
|
||||
## module-begin-block
|
||||
|
||||
Reports a `begin … end` written straight into a module body, where a module item belongs. Tools that accept it treat it as an unnamed generate block, so the declarations inside land in an invented scope and every hierarchical path written against them is wrong. lucisv's parser *recovers* the construct in error-tolerant mode — it reads the block as that unnamed generate block and records a diagnostic at the `begin`, so the file is still reported as not parsing cleanly and is still never formatted, while the items inside the block and after it stay visible to every rule. Verible's `module-begin-block`, same default.
|
||||
|
||||
## numeric-format-string-style
|
||||
|
||||
Reports a `0x`/`'b`-style radix prefix immediately before a `%` specifier that prints a different base (`"0x%0b"`), and any such prefix before a decimal one (`"0d%0d"`). A specifier with no prefix is always accepted. A log line that prints `addr = 0x1010` for a binary value costs the reader an hour. Verible's `numeric-format-string-style`, same default (off).
|
||||
|
||||
## positive-meaning-parameter-name
|
||||
|
||||
Reports a parameter whose name starts with `disable`, in any case. `if (!DisableEcc)` is a double negative and `DisableEcc = 0` means "ECC is on", which nobody reads correctly at speed. Verible's `positive-meaning-parameter-name`, same default.
|
||||
|
||||
## proper-parameter-declaration
|
||||
|
||||
Reports a `parameter` written in a module, class or package *body* rather than in a formal parameter list, and a `localparam` written where the project's options do not allow it. A body `parameter` is still overridable from outside with nothing at the declaration to say so. A formal parameter list is never judged. Verible's `proper-parameter-declaration`, same default (off) and the same two options, `package_allow_parameter` (false) and `package_allow_localparam` (true).
|
||||
|
||||
## suggest-parentheses
|
||||
|
||||
Reports a conditional expression standing unparenthesized in the true-clause of another (`a ? b ? c : d : e`) and offers a **safe fix** that adds the two characters. The language already reads it that way; the reader has to count colons to find out. A conditional in the false-clause is where the language puts it and is not reported. Verible's `suggest-parentheses`, same shape and same default.
|
||||
|
||||
## unpacked-dimensions-range-ordering
|
||||
|
||||
Reports an unpacked dimension that counts downwards (`[7:0]`, `[DEPTH-1:0]`), where element 0 is the last one and every `for (i = 0; …)` beside it reads the array backwards. The mirror image of `packed-dimensions-range-ordering`, which wants a vector's width the other way. A sized, dynamic or associative extent is not a range and is left alone; two symbolic bounds lucisv cannot compare are too. Verible's `unpacked-dimensions-range-ordering`, same default.
|
||||
|
||||
## uvm-macro-semicolon
|
||||
|
||||
Reports a `;` written after a `` `uvm_* `` macro invocation. The macros expand to a `begin … end`, so the `;` is a null statement — usually inert, and not after `if (x) `uvm_info(…); else …`, where the `else` then belongs to nothing. Off by default in both, because the semicolon is written everywhere in existing UVM code. No fix: deleting it is exactly the edit that is unsafe in the shape the rule exists for. Verible's `uvm-macro-semicolon`, same default.
|
||||
|
||||
## v2001-generate-begin
|
||||
|
||||
Reports a bare `begin … end` written directly inside a `generate … endgenerate` with no `if`, `for` or `case` around it. It opens an unnamed generate block — an invented path segment that renumbers when a block is added above it — and buys nothing, because the region is already a scope. Read from the same recovered block `module-begin-block` reads, one scope in. Verible's `v2001-generate-begin`, same default.
|
||||
+5
-1
@@ -385,6 +385,9 @@ recursion-limit, whose edges sit in §2.1). Code edges:
|
||||
| `interface-dpi-arms ──▶ interfaces / dpi-export / comment-slots` | depends | (2026-09-02, TODO §30, M13) Modport method prototypes (`import task drive(int x)`) through `Parser::parse_tf_header`/`Fmt::tf_header`, the single header parse and print the function/task declarations now share; bound `Target::InScope` with the formals in a scope of their own; one prototype per `import`/`export` group (the comma list stays an error, recorded). Unnamed DPI formals behind `parse_tf_ports(allow_unnamed)`, the empty-name convention on `TfArg::name`. `const /*c*/ ref` gap owned (`TfArg::after_const`). Zero corpus population; 4 807 files byte-identical. |
|
||||
| `statement-fences ──▶ format-fences / classes / shared-fence-filter / range-formatting` | depends | (2026-09-02, TODO §31, M9) Fences at statement level and inside class bodies; `protected_regions`/`is_protected` signatures untouched so `lucisv/src/lint.rs` and `lucisv_server/src/lint.rs` are byte-identical; `verify.rs` untouched. One narrowing: a fence written after code on the same line is an ordinary comment everywhere now (it already was at statement level and in the documented rule). |
|
||||
| `header-recovery ──▶ error-recovery / parser / lucisv_server` | depends | (2026-09-04, TODO §32, M10) An `Error(RawText)` element in the four list element types (`ListElem<T>`) and `ExprKind::Error`; `element_or_recover` with a list-local, bracket-seeded sync set; `list_ends` ends any list whose iteration left the cursor unmoved — the structural guarantee that closes the non-advancing loop which exhausted memory on the first cut (the reason `tools/guard.sh` exists); headers keep their node so bodies bind in the right scope; recovery declines on a conditional-compilation directive so `split.rs`'s verbatim rescue keeps strict parity. Every consumer of a port/param/connection/tf-arg list reads it through `ListElem::ok`. Opened §2.9-24. |
|
||||
| `linter-expansion-1 ──▶ linter-core / semantic-lints-on / editor-settings / vlog_semantic` | depends | (2026-09-03, TODO §33) `Severity` on every rule (Error / Warning / Style) carried through CLI text and JSON, editor `ERROR/WARNING/INFORMATION`, `--rules-doc`, and select/ignore by class word; VS Code `lucisv.lint.severity.*` switches and tri-state `lucisv.lint.rules.<rule>` toggles generated by `vlog_linter::vscode` with a drift test; `lint::enabled_rules` is the one ladder (defaults → select → class switches → per-rule → ignore). Nineteen Error/Warning rules; `Semantics::duplicates()` added additively (no store change). |
|
||||
| `linter-expansion-2 ──▶ linter-expansion-1 / config-discovery / editor-settings` | depends | (2026-09-04, TODO §34) Per-rule options: `OptionSpec`/`RuleOptions` with one validator behind `[lint.<rule>]` tables (accepted now; `lucisv_core::config` stores them raw) and the editor's `lucisv.lint.options` (bad entries logged and dropped); precedence editor > toml > default key by key; an in-house anchored regex engine run as a Thompson-NFA simulation (linear by construction; unknown escapes refused by name). Eighteen Style rules; the four naming rules take Verible's option spellings with byte-identical defaults; `typedef-structs-unions` allows nested anonymous aggregates by default (lead ruling, opentitan measurement). |
|
||||
| `linter-expansion-3 ──▶ linter-expansion-2` | depends | (2026-09-04, TODO §35) The remaining nineteen Verible rules (73 in all — every published Verible rule but `forbid-implicit-declarations`); Verible's `forbidden-symbol` is the source-file name of `invalid-system-task-function`, so it is that rule's `symbols` option; `void-cast` gains `forbidden_calls`; the lifetime rules exempt out-of-body definitions (census: 948 of 960 findings). Opened §2.9-25. |
|
||||
| `constraint-bodies ──▶ classes / out-of-class-constraints / dv-statements / safety-net` | depends | (2026-09-02, round 1 of coverage_gaps C1) `ItemKind::Constraint(ConstraintDecl)` with a structured `ConstraintSet` (`Expr{soft}`, `Implication`, `If`, `Foreach`, `SolveBefore`, `Unique`, `DisableSoft`, `Directive`, `Empty`), `ExprKind::Dist`, and `WithConstraint.block` as `ConstraintBody::{Items, Verbatim}`. The parser takes a `Rewind` snapshot (cursor, **both pending-comment buckets**, depth, links, `open_conds`, diagnostics length), attempts the structured body, and on any error restores it and re-runs v0.26.0's verbatim capture character for character — so an unknown shape *is* the old behavior, not an approximation (pinned on text, slice and `col`). **No keywords reserved**: `soft`/`dist`/`solve`/`before` are matched by text like `restrict`, so `token.rs`, `pairs.rs`, the editor grammar and `tests/grammar.rs` are untouched and `logic before;` keeps working; `:=`/`:/` stay two tokens with a span-adjacency check (a `:/` token would swallow `:/* c */`). Canonical layout: one item per line, `}` at the header column, dist weights as a braced list; a `with` block keeps the source's one-line-or-not shape. `verify.rs` untouched; the constraint attack pairs re-derived plus new ones. Exhaustive arms paid in `format.rs`, `bind.rs`, `tests/spans.rs`; `visit.rs` gets an explicit no-op arm (no items/statements inside). **QA rework**: comments after the round's own text-matched words were dropped; the dev answered with an exhaustive gap fuzzer (a `/*C*/` in every inter-token gap of 15 fixtures, 358 gaps, format + idempotency demanded) and 14 named comment fields plus `ConstraintItemKind::takes_semi()` (one owner of the `;`) and `Parser::gap_before` (the closer-side twin of `take_before_open`); 96 regressions vs v0.26.0 became 40, all in shared machinery outside this lane — §2.9-22. Opentitan: 1 993 of 2 009 bodies structured (fallbacks: 10 macro-item bodies, 6 non-LRM shapes), failure set unchanged, per-file tolerant diagnostics identical, 48 DV files idempotent with comment streams byte-identical. |
|
||||
| `covergroup-bodies ──▶ constraint-bodies / classes / safety-net` | depends | (2026-09-02, round 2 of coverage_gaps C1) `ItemKind::Covergroup(Box<CovergroupDecl>)` with `CoverItemKind::{Coverpoint, Cross, Option, Directive, Empty}`, `BinDecl { wildcard, kind, name, array, spec: BinSpec::{Values, Transitions, Default, DefaultSequence, Select}, with_expr, iff }`, `SelectExpr` for `binsof … intersect … && !binsof`, one `CoverageEvent` enum. Same `Rewind` fallback as constraints — v0.27.0's flat scan re-run character for character on any failure — and no keywords reserved (`coverpoint`, `bins`, `cross`, `binsof`, `intersect`, `wildcard`, `ignore_bins`, `illegal_bins`, `option`, `type_option` by text). **Two guards in shared expression machinery, the round's one risk**: `at_postfix_segment` refuses `[` followed by `*`/`->`/`=` (no index can start with those — it is what lets `1'b1[*5]` be a transition repeat), and a `no_with` flag while a bin spec operand is read (so the bin's own `with (…)` filter is not eaten as an array-method iterator argument); `(`-disambiguation is by position, the LRM's own rule. `plain_expr_list` → `plain_list` and `constraint_parens` → `guard_parens`, shared with `iff`/`with`. `verify.rs` untouched, twelve attack pairs. The gap fuzzer was built in from day one (329 gaps, 52 fail, all §2.9-22 shared machinery — *asserted* by running each shape outside a covergroup). Opentitan: 544 of 544 covergroups structured, 87/87 DV covergroup files idempotent, failure set and per-file diagnostics identical. `on_type.rs` keeps `covergroup` OPAQUE by argument. |
|
||||
| `fragment-mode ──▶ error-recovery / define-table / lexer-cleanup / covergroup-bodies` | depends | (2026-09-02, coverage_gaps H4 corrected) Class-body and module-item `.svh` fragments already parsed — the file-scope item loop *is* the class-item loop; the three shapes that did not (statement lists, enum-member lists, cover-item lists) become `SourceFile::fragment: Option<Fragment>` (`items` empty iff `fragment` is `Some`). Detection is a whole-file rule, not an error-message match: the FIRST STRUCTURAL item failed (directives, macro items and null items are legal in every body and do not count; a tolerant `Ok` that recorded a diagnostic counts as failed — the `if … else` generate-vs-statement parity bug), the file does not open with a design-unit keyword, and a shape consumes the file to EOF, tried narrowest-first (cover items → enum members → statements: the wider grammars mis-read the narrower). Each shape re-lexes a fresh token stream — `Rewind` deliberately does not restore the tokens' comment buckets, right for verbatim captures and fatal here. Shared loops lifted (`parse_enum_members`, `parse_cover_items`); formatter prints a fragment at indent 0 through existing printers; binder gives statements a file `Block` scope and enum variants file scope; **no census change** (a fragment's variants are not exported — `pkg::CUSTOM_1` must not resolve to a name that does not exist), FACTS stays 12. Separately, the lexer continues a `` `define `` whose formal-argument `(` touches the name and is still open at end of line, no backslash needed until the list closes — `cip_base_vseq__tl_errors.svh`'s real blocker. Corpus 813 → 814/820; opentitan 12 → 10, exactly the two predicted files. |
|
||||
@@ -583,7 +586,8 @@ update the filing README(s) and this file.
|
||||
| ~~21~~ | ~~`Parser::parse_scoped_name` joins a `pkg::name` chain into one `String`, erasing the segment boundary, so an escaped segment (`\my-pkg ::\state-t` as a type, an instantiated module or a `bind` target) is reprinted without its terminating space and **refused by the safety net** — an error, never a corruption. Wanted: the AST keeps the segments (as `parse_method_name` already does for `FunctionDecl::scope`). Pinned by `escaped_identifiers.cases`'s one `#SKIP` and `verification::an_escaped_name_in_a_scoped_type_is_rejected_rather_than_corrupted`, both of which must keep failing-to-format until delivered~~ — **delivered 2026-09-02 by comment-slots**: `Parser::push_scope_segment` is the one join for every `::` chain and writes the escaped segment's terminator; `parse_method_name` keeps real segments (`ScopeSeg`, one comment slot per `::`). The `#SKIP` is a live case and the verification pin is inverted, with a new pair asserting the tightened spelling is still refused | escaped-identifiers | ~~vlog_parser~~ done |
|
||||
| ~~22~~ | ~~**Comment slots in shared expression/name machinery** drop the comment and the safety net refuses the file: `q[/*c*/ i]` (index expressions), `x inside {[/*c*/ 0:3]}` and `n /*c*/ inside {` (`inside` / `parse_value_range`), `pkg/*c*/ ::cls::name` (`parse_method_name` chains), `foreach (q[/*c*/ i])` (`parse_foreach_target`), `static /*c*/ constraint` / `pure /*c*/ static function` (`take_member_prefix`). Found by constraint-bodies' exhaustive gap fuzzer (358 gaps; these 40 fail identically on v0.26.0 in the same constructs outside a constraint). Inside a constraint they are regressions relative to the verbatim era — but no opentitan file hits one (sweep unchanged). Wanted: a parser-wide round giving each slot a `Meta`/comments field, then re-running the fuzzer to zero.~~ — **delivered 2026-09-02 by comment-slots**: ~70 named comment fields across `ExprKind`/`Stmt`/declarations/headers/labels (`SegmentComments`, `BinaryComments`, `CastComments`, `LabelComments`, `Stmt::before_semi` + `StmtKind::takes_semi()`), three duplicated grammars folded into `parse_postfix_segment` / `parse_value_range`, and four gap fuzzers at zero — covergroup 329, fragment 153, constraint 395 (committed at last), RTL 352 (new). Corpus (860 files) and opentitan (3 975 files) byte-identical to v0.30.0. Deliberately left: `if`/`case` in-paren comments still recovered print-side by `header_parens` (only `after_kw` got a slot) — a real slot there would change existing layout | constraint-bodies (dev + QA) | ~~vlog_parser~~ done |
|
||||
| 23 | A **cross-file instance-member tail does not resolve for rename**: with `module sub` in `sub.sv` and `assign w = u_x.sig;` in `top.sv`, renaming `sub`'s `wire sig` edits `sub.sv` only — the same shape in one file resolves and is edited (`a_hierarchical_tail_that_resolves_is_renamed_with_its_declaration`). Since comment-slots the rename *says so* (item 20's warning); the edit itself is the gap. Modules export ports and parameters only (the class-member-access round 2 ruling), so an internal net is exactly what the cross-file hop refuses — the fix is either an export rule for nets named through an instance or a rename-time in-file fallback resolution of the tail. | comment-slots (dev, surfaced by the §2.9-20 control test) | vlog_semantic / vlog_refactor |
|
||||
| 24 | A **half-typed `#(` parameter override whose value can read as a call** (`sub #(.W(` ⏎ `u0 (.a(x))`) — the greedy expression grammar swallows the next instance's name before any error fires, so the whole instantiation still degrades to an item-level `Error` node instead of getting header recovery's benefit. Found by §32's QA; the fix is a lookahead in the override grammar (an identifier followed by `(` on a later line is the next instance, not a call). | header-recovery (QA) | vlog_parser |
|
||||
| ~~24~~ | ~~A **half-typed `#(` parameter override whose value can read as a call** (`sub #(.W(` ⏎ `u0 (.a(x))`) — the greedy expression grammar swallows the next instance's name before any error fires, so the whole instantiation still degrades to an item-level `Error` node instead of getting header recovery's benefit. Found by §32's QA; the fix is a lookahead in the override grammar (an identifier followed by `(` on a later line is the next instance, not a call).~~ — **delivered 2026-09-04 by small-items-3 (TODO §36)** | header-recovery (QA) | vlog_parser |
|
||||
| ~~25~~ | ~~The parser **refuses** a module-scope `begin … end` and a bare `begin` inside a `generate` region (an `ItemKind::Error`) rather than recovering them as an unnamed generate block, so `module-begin-block` and `v2001-generate-begin` (TODO §35) fire on an error leaf and the rest of the unit is lost to recovery. Wanted: tolerant-mode recovery that keeps the block's items.~~ — **delivered 2026-09-04 by small-items-3 (TODO §36)** | linter-expansion-3 (dev) | vlog_parser |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -5,6 +5,31 @@ for you. The extension and its bundled language server share one version
|
||||
number; the full engineering notes live in the
|
||||
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
|
||||
|
||||
## 0.41.0 — 2026-09-04
|
||||
|
||||
- **A quieter cursor.** Resting the cursor on an instantiation of a
|
||||
widely used module no longer stalls the editor: port refactorings are
|
||||
offered instantly and their edit is computed only when you pick one.
|
||||
- **Faster go-to-definition** for declarations in files you have not
|
||||
opened.
|
||||
|
||||
## 0.40.0 — 2026-09-04
|
||||
|
||||
- **Better recovery while you type.** A stray `begin … end` at module
|
||||
scope, and a half-typed `#(` override above another instance, no
|
||||
longer take the rest of the module out of the outline, hover and
|
||||
diagnostics — you get one squiggle where the problem is.
|
||||
- **Safer saves.** Format-on-save and `--fix` now replace a file in one
|
||||
step; an interrupted write can no longer leave it truncated.
|
||||
|
||||
## 0.39.0 — 2026-09-04
|
||||
|
||||
- **Nineteen more lint rules** (73 in all): generate-style rules,
|
||||
explicit lifetimes, `suggest-parentheses` and `endif-comment` with
|
||||
safe fixes, UVM idiom checks, forbidden macros and calls, DFF naming
|
||||
and parameter placement — every rule of Verible's list, each with its
|
||||
own toggle and options.
|
||||
|
||||
## 0.38.0 — 2026-09-04
|
||||
|
||||
- **Rule options.** Configure a rule from `lucisv.lint.options` (or
|
||||
|
||||
@@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view,
|
||||
then open a Verilog or SystemVerilog file. There is no separate server or CLI
|
||||
setup.
|
||||
|
||||
The current release is **0.38.0**. Its platform packages include both
|
||||
The current release is **0.41.0**. Its platform packages include both
|
||||
`lucisv-server` and the `lucisv` command-line tool:
|
||||
|
||||
| Package target | Machines |
|
||||
@@ -364,6 +364,22 @@ Every nesting color is a proper VS Code theme color:
|
||||
}
|
||||
```
|
||||
|
||||
## Release 0.41.0 highlights
|
||||
|
||||
Version 0.41.0 takes the code-action request off the module fan-out and
|
||||
answers go-to-definition from the index.
|
||||
|
||||
## Release 0.40.0 highlights
|
||||
|
||||
Version 0.40.0 recovers a stray `begin` block and a half-typed `#(`
|
||||
override without losing the rest of the module, and makes every
|
||||
in-place write atomic.
|
||||
|
||||
## Release 0.39.0 highlights
|
||||
|
||||
Version 0.39.0 completes the Verible rule set: 73 lint rules, each with
|
||||
a severity, a toggle and, where it applies, options.
|
||||
|
||||
## Release 0.38.0 highlights
|
||||
|
||||
Version 0.38.0 adds per-rule lint options (naming patterns, line
|
||||
|
||||
+275
-47
@@ -2,7 +2,7 @@
|
||||
"name": "lucisv",
|
||||
"displayName": "lucisv — Verilog/SystemVerilog",
|
||||
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
|
||||
"version": "0.38.0",
|
||||
"version": "0.41.0",
|
||||
"publisher": "guoliangchen",
|
||||
"author": "Guoliang Chen",
|
||||
"license": "MIT",
|
||||
@@ -494,7 +494,7 @@
|
||||
"order": 29,
|
||||
"markdownDescription": "**warning** — give every case statement a default branch. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.explicit-function-task-parameter-type": {
|
||||
"lucisv.lint.rules.create-object-name-match": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
"enumDescriptions": [
|
||||
@@ -504,6 +504,30 @@
|
||||
],
|
||||
"default": "default",
|
||||
"order": 30,
|
||||
"markdownDescription": "**warning** — give `type_id::create` the name of the variable it is assigned to. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.disable-statement": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
"enumDescriptions": [
|
||||
"Leave it as it ships: Off by default.",
|
||||
"Always run this rule.",
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 31,
|
||||
"markdownDescription": "**warning** — `disable` a sequential block or a task, and write `disable fork` for processes. Off by default."
|
||||
},
|
||||
"lucisv.lint.rules.explicit-function-task-parameter-type": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
"enumDescriptions": [
|
||||
"Leave it as it ships: On by default.",
|
||||
"Always run this rule.",
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 32,
|
||||
"markdownDescription": "**warning** — declare a storage type on every function and task argument. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.forbid-defparam": {
|
||||
@@ -515,7 +539,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 31,
|
||||
"order": 33,
|
||||
"markdownDescription": "**warning** — override a parameter at the instantiation, not with `defparam`. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.forbid-negative-array-dim": {
|
||||
@@ -527,9 +551,21 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 32,
|
||||
"order": 34,
|
||||
"markdownDescription": "**warning** — do not write a negative constant in a dimension. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.forbidden-macro": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
"enumDescriptions": [
|
||||
"Leave it as it ships: On by default.",
|
||||
"Always run this rule.",
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 35,
|
||||
"markdownDescription": "**warning** — do not invoke a forbidden macro. On by default. Options (set them in `#lucisv.lint.options#`): `macros`."
|
||||
},
|
||||
"lucisv.lint.rules.incomplete-assignment": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
@@ -539,7 +575,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 33,
|
||||
"order": 36,
|
||||
"markdownDescription": "**warning** — assign every variable on every path of an always_comb. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.instance-shadowing": {
|
||||
@@ -551,7 +587,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 34,
|
||||
"order": 37,
|
||||
"markdownDescription": "**warning** — do not hide an enclosing declaration with a new one of the same name. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.invalid-system-task-function": {
|
||||
@@ -563,8 +599,20 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 35,
|
||||
"markdownDescription": "**warning** — do not call a deprecated or non-reproducible system task. On by default."
|
||||
"order": 38,
|
||||
"markdownDescription": "**warning** — do not call a deprecated or non-reproducible system task. On by default. Options (set them in `#lucisv.lint.options#`): `symbols`."
|
||||
},
|
||||
"lucisv.lint.rules.macro-string-concatenation": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
"enumDescriptions": [
|
||||
"Leave it as it ships: Off by default.",
|
||||
"Always run this rule.",
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 39,
|
||||
"markdownDescription": "**warning** — do not write the `` `` `` concatenation operator inside a plain string. Off by default."
|
||||
},
|
||||
"lucisv.lint.rules.module-parameter": {
|
||||
"type": "string",
|
||||
@@ -575,7 +623,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 36,
|
||||
"order": 40,
|
||||
"markdownDescription": "**warning** — override more than one parameter by name. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.module-port": {
|
||||
@@ -587,7 +635,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 37,
|
||||
"order": 41,
|
||||
"markdownDescription": "**warning** — connect an instance with more than one port by name. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.packed-dimensions-range-ordering": {
|
||||
@@ -599,7 +647,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 38,
|
||||
"order": 42,
|
||||
"markdownDescription": "**warning** — declare a packed dimension in decreasing order, `[N-1:0]`. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.plusarg-assignment": {
|
||||
@@ -611,7 +659,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 39,
|
||||
"order": 43,
|
||||
"markdownDescription": "**warning** — read a plusarg with `$value$plusargs`, not `$test$plusargs`. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.suspicious-semicolon": {
|
||||
@@ -623,7 +671,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 40,
|
||||
"order": 44,
|
||||
"markdownDescription": "**warning** — do not end a control statement's header with a `;`. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.truncated-numeric-literal": {
|
||||
@@ -635,7 +683,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 41,
|
||||
"order": 45,
|
||||
"markdownDescription": "**warning** — keep a sized literal inside the width it declares. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.undersized-binary-literal": {
|
||||
@@ -647,7 +695,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 42,
|
||||
"order": 46,
|
||||
"markdownDescription": "**warning** — write every bit of a sized binary literal. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.undriven-net": {
|
||||
@@ -659,7 +707,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 43,
|
||||
"order": 47,
|
||||
"markdownDescription": "**warning** — drive a signal that something reads. On where lucisv can see the project."
|
||||
},
|
||||
"lucisv.lint.rules.unused-signal": {
|
||||
@@ -671,9 +719,21 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 44,
|
||||
"order": 48,
|
||||
"markdownDescription": "**warning** — delete a signal nothing uses. On where lucisv can see the project."
|
||||
},
|
||||
"lucisv.lint.rules.uvm-macro-semicolon": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
"enumDescriptions": [
|
||||
"Leave it as it ships: Off by default.",
|
||||
"Always run this rule.",
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 49,
|
||||
"markdownDescription": "**warning** — do not write a `;` after a `` `uvm_* `` macro invocation. Off by default."
|
||||
},
|
||||
"lucisv.lint.rules.void-cast": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
@@ -683,8 +743,8 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 45,
|
||||
"markdownDescription": "**warning** — cast to `void` only what a call returns. On by default."
|
||||
"order": 50,
|
||||
"markdownDescription": "**warning** — cast to `void` only what a call returns. On by default. Options (set them in `#lucisv.lint.options#`): `forbidden_calls`."
|
||||
},
|
||||
"lucisv.lint.rules.always-comb": {
|
||||
"type": "string",
|
||||
@@ -695,7 +755,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 46,
|
||||
"order": 51,
|
||||
"markdownDescription": "**style** — write `always_comb` instead of `always @*`. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.banned-declared-name-patterns": {
|
||||
@@ -707,7 +767,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 47,
|
||||
"order": 52,
|
||||
"markdownDescription": "**style** — do not declare a name the project has banned. Off by default. Options (set them in `#lucisv.lint.options#`): `patterns`."
|
||||
},
|
||||
"lucisv.lint.rules.constraint-name-style": {
|
||||
@@ -719,9 +779,21 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 48,
|
||||
"order": 53,
|
||||
"markdownDescription": "**style** — name constraints in lower_snake_case ending in _c. On by default. Options (set them in `#lucisv.lint.options#`): `pattern`."
|
||||
},
|
||||
"lucisv.lint.rules.dff-name-style": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
"enumDescriptions": [
|
||||
"Leave it as it ships: Off by default.",
|
||||
"Always run this rule.",
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 54,
|
||||
"markdownDescription": "**style** — name a flip-flop's output and its next-state input for each other. Off by default. Options (set them in `#lucisv.lint.options#`): `input`, `output`, `waive_ifs_with_conditions`, `waive_lhs_regex`."
|
||||
},
|
||||
"lucisv.lint.rules.empty-item": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
@@ -731,9 +803,21 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 49,
|
||||
"order": 55,
|
||||
"markdownDescription": "**style** — drop a `;` that stands where an item belongs. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.endif-comment": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
"enumDescriptions": [
|
||||
"Leave it as it ships: Off by default.",
|
||||
"Always run this rule.",
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 56,
|
||||
"markdownDescription": "**style** — name the condition an `` `endif `` closes in a comment beside it. Off by default."
|
||||
},
|
||||
"lucisv.lint.rules.enum-name-style": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
@@ -743,7 +827,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 50,
|
||||
"order": 57,
|
||||
"markdownDescription": "**style** — name enum typedefs in lower_snake_case ending in _e or _t. On by default. Options (set them in `#lucisv.lint.options#`): `style_regex`."
|
||||
},
|
||||
"lucisv.lint.rules.explicit-begin": {
|
||||
@@ -755,9 +839,21 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 51,
|
||||
"order": 58,
|
||||
"markdownDescription": "**style** — wrap every body in `begin` and `end`. Off by default. Options (set them in `#lucisv.lint.options#`): `always_comb_enable`, `always_enable`, `always_ff_enable`, `always_latch_enable`, `else_enable`, `final_enable`, `for_enable`, `forever_enable`, `if_enable`, `initial_enable`, `while_enable`."
|
||||
},
|
||||
"lucisv.lint.rules.explicit-function-lifetime": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
"enumDescriptions": [
|
||||
"Leave it as it ships: On by default.",
|
||||
"Always run this rule.",
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 59,
|
||||
"markdownDescription": "**style** — state `automatic` or `static` on a function declared outside a class. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.explicit-parameter-storage-type": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
@@ -767,9 +863,21 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 52,
|
||||
"order": 60,
|
||||
"markdownDescription": "**style** — declare a storage type on every parameter. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.explicit-task-lifetime": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
"enumDescriptions": [
|
||||
"Leave it as it ships: On by default.",
|
||||
"Always run this rule.",
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 61,
|
||||
"markdownDescription": "**style** — state `automatic` or `static` on a task declared outside a class. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.forbid-consecutive-null-statements": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
@@ -779,9 +887,21 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 53,
|
||||
"order": 62,
|
||||
"markdownDescription": "**style** — remove the extra `;`. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.forbid-line-continuations": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
"enumDescriptions": [
|
||||
"Leave it as it ships: On by default.",
|
||||
"Always run this rule.",
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 63,
|
||||
"markdownDescription": "**style** — do not break a string literal across lines with a backslash continuation. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.generate-label": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
@@ -791,7 +911,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 54,
|
||||
"order": 64,
|
||||
"markdownDescription": "**style** — label every generate block. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.generate-label-prefix": {
|
||||
@@ -803,7 +923,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 55,
|
||||
"order": 65,
|
||||
"markdownDescription": "**style** — prefix a generate block's label with `g_` or `gen_`. On by default. Options (set them in `#lucisv.lint.options#`): `prefix`."
|
||||
},
|
||||
"lucisv.lint.rules.interface-name-style": {
|
||||
@@ -815,9 +935,33 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 56,
|
||||
"order": 66,
|
||||
"markdownDescription": "**style** — name interfaces in lower_snake_case ending in _if. On by default. Options (set them in `#lucisv.lint.options#`): `style_regex`."
|
||||
},
|
||||
"lucisv.lint.rules.legacy-generate-region": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
"enumDescriptions": [
|
||||
"Leave it as it ships: Off by default.",
|
||||
"Always run this rule.",
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 67,
|
||||
"markdownDescription": "**style** — write generate constructs without a `generate … endgenerate` region. Off by default."
|
||||
},
|
||||
"lucisv.lint.rules.legacy-genvar-declaration": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
"enumDescriptions": [
|
||||
"Leave it as it ships: Off by default.",
|
||||
"Always run this rule.",
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 68,
|
||||
"markdownDescription": "**style** — declare a genvar in the `for` header, not in a separate statement. Off by default."
|
||||
},
|
||||
"lucisv.lint.rules.line-length": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
@@ -827,7 +971,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 57,
|
||||
"order": 69,
|
||||
"markdownDescription": "**style** — keep lines within the configured width. On by default. Options (set them in `#lucisv.lint.options#`): `length`."
|
||||
},
|
||||
"lucisv.lint.rules.macro-name-style": {
|
||||
@@ -839,9 +983,21 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 58,
|
||||
"order": 70,
|
||||
"markdownDescription": "**style** — name macros in ALL_CAPS. On by default. Options (set them in `#lucisv.lint.options#`): `style_regex`."
|
||||
},
|
||||
"lucisv.lint.rules.module-begin-block": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
"enumDescriptions": [
|
||||
"Leave it as it ships: On by default.",
|
||||
"Always run this rule.",
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 71,
|
||||
"markdownDescription": "**style** — do not write a `begin`/`end` block at module scope. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.module-filename": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
@@ -851,7 +1007,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 59,
|
||||
"order": 72,
|
||||
"markdownDescription": "**style** — name a one-module file after its module. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.module-name-style": {
|
||||
@@ -863,7 +1019,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 60,
|
||||
"order": 73,
|
||||
"markdownDescription": "**style** — name modules in lower_snake_case. Off by default. Options (set them in `#lucisv.lint.options#`): `style_regex`."
|
||||
},
|
||||
"lucisv.lint.rules.no-tabs": {
|
||||
@@ -875,7 +1031,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 61,
|
||||
"order": 74,
|
||||
"markdownDescription": "**style** — use spaces, not tabs. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.no-trailing-whitespace": {
|
||||
@@ -887,9 +1043,21 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 62,
|
||||
"order": 75,
|
||||
"markdownDescription": "**style** — no whitespace at the end of a line. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.numeric-format-string-style": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
"enumDescriptions": [
|
||||
"Leave it as it ships: Off by default.",
|
||||
"Always run this rule.",
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 76,
|
||||
"markdownDescription": "**style** — give a numeric format specifier the radix prefix that matches it. Off by default."
|
||||
},
|
||||
"lucisv.lint.rules.one-module-per-file": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
@@ -899,7 +1067,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 63,
|
||||
"order": 77,
|
||||
"markdownDescription": "**style** — declare one module per file. Off by default."
|
||||
},
|
||||
"lucisv.lint.rules.package-filename": {
|
||||
@@ -911,7 +1079,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 64,
|
||||
"order": 78,
|
||||
"markdownDescription": "**style** — name a one-package file after its package. On by default. Options (set them in `#lucisv.lint.options#`): `allow-dash-for-underscore`."
|
||||
},
|
||||
"lucisv.lint.rules.parameter-name-style": {
|
||||
@@ -923,7 +1091,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 65,
|
||||
"order": 79,
|
||||
"markdownDescription": "**style** — name parameters in CamelCase or ALL_CAPS. On by default. Options (set them in `#lucisv.lint.options#`): `localparam_style`, `localparam_style_regex`, `parameter_style`, `parameter_style_regex`."
|
||||
},
|
||||
"lucisv.lint.rules.parameter-type-name-style": {
|
||||
@@ -935,7 +1103,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 66,
|
||||
"order": 80,
|
||||
"markdownDescription": "**style** — name type parameters in lower_snake_case ending in _t. Off by default. Options (set them in `#lucisv.lint.options#`): `style_regex`."
|
||||
},
|
||||
"lucisv.lint.rules.port-name-suffix": {
|
||||
@@ -947,9 +1115,21 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 67,
|
||||
"order": 81,
|
||||
"markdownDescription": "**style** — end a port's name with the suffix for its direction. Off by default. Options (set them in `#lucisv.lint.options#`): `suffixes`."
|
||||
},
|
||||
"lucisv.lint.rules.positive-meaning-parameter-name": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
"enumDescriptions": [
|
||||
"Leave it as it ships: On by default.",
|
||||
"Always run this rule.",
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 82,
|
||||
"markdownDescription": "**style** — name a parameter for what it enables, not for what it disables. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.posix-eof": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
@@ -959,9 +1139,21 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 68,
|
||||
"order": 83,
|
||||
"markdownDescription": "**style** — end the file with a newline. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.proper-parameter-declaration": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
"enumDescriptions": [
|
||||
"Leave it as it ships: Off by default.",
|
||||
"Always run this rule.",
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 84,
|
||||
"markdownDescription": "**style** — declare `parameter` only in a formal parameter list and `localparam` only in a body. Off by default. Options (set them in `#lucisv.lint.options#`): `package_allow_parameter`, `package_allow_localparam`."
|
||||
},
|
||||
"lucisv.lint.rules.signal-name-style": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
@@ -971,7 +1163,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 69,
|
||||
"order": 85,
|
||||
"markdownDescription": "**style** — name signals in lower_snake_case. Off by default. Options (set them in `#lucisv.lint.options#`): `style_regex`."
|
||||
},
|
||||
"lucisv.lint.rules.struct-union-name-style": {
|
||||
@@ -983,9 +1175,21 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 70,
|
||||
"order": 86,
|
||||
"markdownDescription": "**style** — name struct and union typedefs in lower_snake_case ending in _t. On by default. Options (set them in `#lucisv.lint.options#`): `style_regex`."
|
||||
},
|
||||
"lucisv.lint.rules.suggest-parentheses": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
"enumDescriptions": [
|
||||
"Leave it as it ships: On by default.",
|
||||
"Always run this rule.",
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 87,
|
||||
"markdownDescription": "**style** — parenthesize a conditional written in the true-clause of another. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.typedef-enums": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
@@ -995,7 +1199,7 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 71,
|
||||
"order": 88,
|
||||
"markdownDescription": "**style** — give an enum type a name with `typedef`. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.typedef-structs-unions": {
|
||||
@@ -1007,9 +1211,21 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 72,
|
||||
"order": 89,
|
||||
"markdownDescription": "**style** — give a struct or union type a name with `typedef`. On by default. Options (set them in `#lucisv.lint.options#`): `allow_anonymous_nested`."
|
||||
},
|
||||
"lucisv.lint.rules.unpacked-dimensions-range-ordering": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
"enumDescriptions": [
|
||||
"Leave it as it ships: On by default.",
|
||||
"Always run this rule.",
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 90,
|
||||
"markdownDescription": "**style** — declare an unpacked dimension in increasing order, `[0:N-1]`. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.unused-waiver": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
@@ -1019,8 +1235,20 @@
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 73,
|
||||
"order": 91,
|
||||
"markdownDescription": "**style** — remove waivers that no longer suppress anything. On by default."
|
||||
},
|
||||
"lucisv.lint.rules.v2001-generate-begin": {
|
||||
"type": "string",
|
||||
"enum": ["default", "on", "off"],
|
||||
"enumDescriptions": [
|
||||
"Leave it as it ships: On by default.",
|
||||
"Always run this rule.",
|
||||
"Never run this rule."
|
||||
],
|
||||
"default": "default",
|
||||
"order": 92,
|
||||
"markdownDescription": "**style** — do not write a bare `begin` block inside a generate region. On by default."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user