Compare commits

...
58 Commits
Author SHA1 Message Date
lucioandClaude Fable 5.1 4c2dae323e Release 0.49.0 — inline module, the last coverage gaps
ci / checks (push) Successful in 1m6s
ci / corpus (push) Successful in 35s
release / build-and-publish (push) Successful in 6m20s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-07 01:13:53 -05:00
lucioandClaude Fable 5.1 a69a1cb528 Coverage gaps L3, L6, L10: six language shapes, randsequence as real nodes, an opt-in uvm_field_* indent
TODO §54 (docs/features/coverage-gaps-l); closes docs/coverage_gaps.md
L3, L6 and L10. The first dev stalled under machine load; a second
finished from the tree.

54.1 `->>` with optional delay or event control (`StmtKind::EventTrigger`),
stream `with [range]` (`ExprKind::StreamWith`), the LRM's other
`casting_type`s, drive strength on a net declaration (`DataDecl::strength`,
whose comment slots also fix a pre-existing refusal on an `assign` with
a comment before its strength), `let` at statement position
(`StmtKind::Let`), and `#(min:typ:max)` clocking skews — `ClockingSkew`
as the LRM's two alternatives, `edge [delay]` | `delay` (review rework of
QA's HIGH). Comment slots added to `let`, stream concatenations and the
clocking grammar; the RTL gap fuzzer at 505 gaps, zero failing.
54.2 `randsequence` (it was a parse error; the keyword is new):
`RandSequence` → `Production` → `Alternative` → `ProdItem` (ref, block,
if, repeat, case, rand join), code blocks by the statement grammar; one
production per line, alternatives aligned; the LRM's examples as cases.
54.3 `[format] uvm-utils-indent` / `lucisv.format.uvmUtilsIndent`, default
off, tracking nested `_begin`/`_end` pairs; 21 corpus files change with
it on, all idempotent. A short comment-free enum body already one-lines,
so no key was built — the behaviour is pinned. `[format]` table tests
added (review rework). `->>`'s event control is bound through the shared
`bind_timing` (review rework of QA's second HIGH).

0 of 820 corpus files differ from 0.48.x with the key off; the opentitan
sweep is identical; no corpus or opentitan file writes any of the new
shapes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-07 01:12:49 -05:00
lucioandClaude Fable 5.1 e1679bebc5 Inline module: a module's body copied into its instantiator with ports and parameters substituted, and a verifier that knows a copy
ci / checks (push) Successful in 1m29s
ci / corpus (push) Successful in 37s
TODO §53.2 (docs/features/extract-inline-module), the fifth §8
refactoring; extract → inline round-trips byte-equal after formatting.

`vlog_refactor::inline_module` (inline/{mod,site,source,render}.rs):
every symbol bound in `S`'s module scope is classified once — a port
becomes the name or literal connected to it, anything else `S` declares
at module scope is prefixed `u_S_` only when `M`'s file already spells
one of them; parameters become `localparam`s with the override or
default; the body is copied verbatim except name spans, with `.name`
shorthand connections expanded when their signal is renamed. Refusals:
`.*`, positional lists, expression connections, an unconnected port, an
output into a literal, any hierarchical reference to `u_S` in the handed
files, `S` unknown/twice/in `M`'s own file, interface/`inout`/unpacked/
non-ANSI ports, `initial`/`final`, macros, directives, any `generate`, a
differing `timescale`, collisions prefixing cannot resolve. Server:
`refactor.inline` lazy action, `lucisv.inlineModule`.

Verifier: `Moving` gains `Origin::{Moved, Copied}` — a copied region's
pieces join the transit under rule 0, "a copied file appears in no
edit"; eight attack pairs through the production entry; QA's neutering
map shows every rule load-bearing. QA's MEDIUMs filed: topo §2.9-32
(same blind spot) and §2.9-33 (`module_sources` lacks a transitive-
instantiators rung).

Trials: corpus 5 inlined / 9 refused, opentitan 5 / 56, the lint census
0 → 0 on every pair. 0 of 854 corpus files differ from 0.48.x.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-06 21:04:05 -05:00
lucioandClaude Fable 5.1 94b0711efb Release 0.48.2 — the 0.48.0 packages rebuilt from the commit that has the hierarchy view
ci / checks (push) Successful in 1m3s
ci / corpus (push) Successful in 34s
release / build-and-publish (push) Successful in 6m51s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-06 00:14:15 -05:00
lucioandClaude Fable 5.1 449b874798 DUT-centred hierarchy view: star a module as DUT, its children and its parents in their own sections, everything else re-rooted
ci / checks (push) Successful in 1m7s
ci / corpus (push) Successful in 31s
release / build-and-publish (push) Successful in 6m20s
TODO §56 (docs/features/dut-hierarchy), the owner's request of 2026-09-06.

Client-only, over the flat `lucisv/moduleHierarchy` snapshot the server
already sends. `hierarchySections.js`: per starred DUT, in starred
order, the DUT's forward subtree (the DUT at the top) and an upward tree
from the DUT through every module that instantiates it (labelled `via
<instance>`, cycles cut with one `recursive` row), then one section for
every module in no DUT's subtree or ancestor closure, re-rooted where
its only parents are DUT ancestors (the review ruling — a monitor beside
the DUT under the same bench stays on screen); a module both below one
DUT and above another appears in both DUT sections; a starred name the
index lacks keeps its sections with a "not in the index" row. Star and
unstar from the webview row menu (the pane is a WebviewView, so the
menu is the renderer's, driven by a `menuTable()` per render), the
`lucisv.hierarchy.{starDut,unstarDut,clearDuts}` commands and title
actions, persistence in `workspaceState` in starred order, and the
`lucisv.hierarchy.duts` setting whose entries show locked. With nothing
starred the pane is byte-identical to before (pinned).

opentitan `hw/ip` (847 modules): `aes` → 3 sections with `tb` in its
parents and 5 modules under `aes_tb` re-rooted into others; `aes` +
`hmac` → 5 sections; every module reachable in both configurations; QA's
200-trial fuzz found no overlap and no gap. `extract_test.js` added to
`.vscodeignore`.

(Committed after the 0.48.0 version commit: the release chain broke at a
test-output grep and cut the tag one commit early; the tag is moved here.)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-06 00:04:05 -05:00
lucioandClaude Fable 5.1 4d342367b9 Release 0.48.0 — a DUT-centred hierarchy view
ci / checks (push) Successful in 1m5s
ci / corpus (push) Successful in 37s
release / build-and-publish (push) Successful in 6m54s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-06 00:03:33 -05:00
lucioandClaude Fable 5.1 a5ca0c9b10 Release 0.47.0 — organize imports, extract module
ci / checks (push) Successful in 59s
ci / corpus (push) Successful in 32s
release / build-and-publish (push) Successful in 6m9s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 23:04:14 -05:00
lucioandClaude Fable 5.1 acf20f7e62 Extract module: dataflow-inferred ports, a new file where the client can create one, and a verifier ledger that follows the move
TODO §53.1 (docs/features/extract-inline-module), the fourth §8
refactoring; §53.2 inline module is unstarted and runs as its own lane.

`vlog_refactor::extract` (region, flow, boundary, render): a selection
of whole module items becomes a new module — a name declared outside
and read inside is an `input`, written inside an `output` (assign and
procedural LHS, for init/step, ++/--, force/release/deassign, `-> ev`,
an initialiser, an output/inout connection through the index), written
on both sides refused; parameters passed through `#(.P(P))`, used
imports copied, the port's type taken from the declaration's own text;
the selection replaced by an instantiation rendered from the new
module's text. Forty-three refusal sentences. `RefactorEdit::created`;
the server emits `CreateFile` document changes when the client reads
both halves of the capability, else writes the module below its source;
`refactor.extract` action carrying `lucisv.extractModule [uri, range,
name]`, and a name prompt in the VS Code extension through the language
client's middleware.

The verifier's never-dropped ledger follows the move (review rework of
QA's two HIGHs): `verify_move(moving: &[(file, region)])` — a piece
deleted inside the moved region must land exactly once in the file the
move names, a deletion outside the region stays an ordinary deletion,
four equations, twelve attack pairs through the production entry;
`check.rs` split (pure move) into `check/{mod,ledger}.rs`. `interface`
and `program` bodies are refused (one AST node, gated on `kw`). QA's
re-attack: PASS; its MEDIUM (a same-file relocation as two edits) is
filed as topo §2.9-32.

Trials: corpus 5 extracted / 6 refused, opentitan `hw/ip/{aes,uart,
spi_host,hmac}` 5 / 5, the unresolved-name census held for every
accepted extraction. 0 of 820 corpus files differ from 0.46.0.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 23:04:14 -05:00
lucioandClaude Fable 5.1 e6eaf53c35 Organize imports: unused imports removed, duplicates merged, the run sorted; the unused-import rule; source.organizeImports
ci / checks (push) Successful in 1m2s
ci / corpus (push) Successful in 47s
TODO §52 (docs/features/organize-imports), the third §8 refactoring.

The judgement lives in `vlog_semantic::imports` (one implementation for
the refactoring and the rule): an import is used when a reference in its
scope, or one nested in it, resolves to a member of the package through
it — `resolve::lexical`'s walk stopped at the scope, every import whose
path admits the name and whose package exports it (binder tables
same-file, `members_of_chain` with re-exports otherwise) marked used, a
deliberate superset; a qualified `p::y` and an import's own package name
never count; an `export p::x` / `export p::*` / `export *::*` in the
scope marks the import it re-exports through as used (IEEE 1800 §26.6 —
the review rework of QA's HIGH, pinned four ways). Refuse to judge: an
unknown or twice-declared package, a macro call or conditional directive
anywhere in the scope, a class with an out-of-file base, a parse
diagnostic, two imports on one line. `vlog_refactor::organize_imports`
deletes the unused lines, merges exact duplicates, sorts the run at the
scope's top (package, item, `*` first), keeps every comment; the
verifier's resolution check refuses a removal a reference needs (attack
pair). `unused-import` (Style, off; safe fix) through
`MentionOracle::package_exports`, silent without a project. Server:
`lucisv: organize imports (removes N, sorts M)` under
`source.organizeImports`, `lucisv.organizeImports`.

Corpus: 40 scopes with ≥ 2 imports, 1 organized, 32 refused for macros;
the rule finds 2, both substantiated. opentitan: 33 of 33 UVM env
packages refused (`` `include "uvm_macros.svh" ``). 0 of 860 corpus
files differ from 0.46.0.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 20:00:31 -05:00
lucioandClaude Fable 5.1 ce2f7190ed Release 0.46.0 — expand .* and convert ports to ANSI
release / build-and-publish (push) Successful in 6m17s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 18:03:54 -05:00
lucioandClaude Fable 5.1 aa479cf701 Convert ports to ANSI: a Verilog-2001 header merged with its body declarations, and a verifier that never drops a comment or an attribute
TODO §51 (docs/features/ansi-conversion), the second §8 refactoring.

`vlog_refactor::convert_to_ansi` (ports/ansi.rs, ports/merge.rs): for a
`PortList::NonAnsi` module, each header name gains its direction, net or
variable type, signing and packed dims from the body declarations that
describe it, merged per IEEE 1800 §23.2.2.2 (`output b; reg [7:0] b;`
→ `output reg [7:0] b`), as insertions around the untouched name so no
reference anchor moves; the absorbed declarations are deleted with their
comments carried onto the ports. Twenty-three refusals, each a sentence
(port expressions, disagreeing ranges, initialisers, directives, a
comment that would have to move into a one-line list, an attributed
declaration). Code action `lucisv: convert ports to ANSI (N ports)` and
command `lucisv.convertToAnsi`.

Review rework (QA's two HIGHs, invariant 4): the verifier's comment rule
is now `never_dropped` over comments and attribute instances alike —
`has ≥ had`, `wrote ≤ gone` unless the text is the one generated
placeholder, `has == had − gone + wrote` — with masked-corruption attack
tests, re-attacked by QA (30-plus pairs, a neutering pass).

Neither the corpus nor opentitan holds a non-ANSI module; acceptance is
by round trip (ANSI → 2001 → ANSI, same ports/types in order) over five
corpus modules and 290 of 291 opentitan candidates (the one failure is
kmac_reduced_tb.sv's pre-existing trailing-comma parse error). 0 of 854
corpus files differ from 0.45.0.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 18:03:54 -05:00
lucioandClaude Fable 5.1 d9ed2c447a Expand .*: a wildcard connection written out as the named connections it stands for
TODO §50 (docs/features/expand-wildcard), the first §8 refactoring.

`vlog_refactor::expand_wildcard` (ports/expand.rs): at the cursor's
instantiation, every port not explicitly connected becomes `.p(p)` when a
same-named net, variable or port is declared in the instance's scope
(generate block → parents → module; IEEE 1800 §23.3.2.4 read strictly —
a parameter, genvar, type, instance or tf argument does not bind) and
`.p()` plus a warning otherwise, in declaration order, replacing the
`.*` element through the ports engine's splice and verifier. Refusals:
no `.*`, two, a positional list, a `bind` directive, a multi-instance
statement, a parse diagnostic in either file, compiler directives in
either list, an unknown or twice-declared module, and a `.*` that binds
nothing. Server: the lazy code action `lucisv: expand .* (N connections)`
and the command `lucisv.expandWildcard`; a title-rewrite bug in the lazy
offer path (`counted`) fixed on the way. Corpus: 11 of 21 sites expand
(the rest refused honestly); opentitan `hw/`: 9 of 66 (50 are `bind`),
each verified, two surfacing real FPV-wrapper drift. 0 of 854 corpus
files differ. Dev-dependency vlog_refactor → vlog_formatter (tests).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 15:03:11 -05:00
lucioandClaude Fable 5.1 1da0a303cc Release 0.45.0 — type spans, package re-exports, hierarchical tails
ci / checks (push) Successful in 1m14s
ci / corpus (push) Successful in 33s
release / build-and-publish (push) Successful in 6m25s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 13:35:57 -05:00
lucioandClaude Fable 5.1 f476c31483 Cross-file instance-member tail: a module's hierarchical surface, read only behind an instance head; rename edits the tail
TODO §49 (docs/features/hierarchical-tail). Closes topo §2.9-23 and
comment-slots finding 2. The first dev was cut off by an outage with the
library half complete; a second finished the tests, README and gates.

`Surface { Connection, Hierarchical }` on `Resolution::ExternalCandidate`
and `MemberSite::Unit`, set by `resolve.rs::head_surface` for an instance
head. `workspace/hierarchy.rs`: `surface_of` (the export rule, re-ruled)
and the two surface-taking reads; the index keeps two disjoint tables —
`members` (connection: ports, parameters; byte-identical to before for
every existing reader) and `hier_members` (nets, variables, instances) —
and a hierarchical read consults the connection table first, so a port
has one record. `FACTS_FORMAT` 18 → 19. `assign w = u_x.sig;` in another
file now resolves to `sub`'s `wire sig`; rename edits both files (nested
`u_a.u_b.sig` included); the §2.9-20 warning is retired for a resolved
tail; a generate-scoped net is still refused honestly. Completion after
`u_x.` in an expression lists the hierarchical surface; a connection
list's does not.

Census: single-file numbers unmoved; 12 939 connection + 5 239
hierarchical-only members; 335 corpus references newly resolve, 514 over
opentitan `hw/` (20 sampled by QA, all genuine). 0 of 860 corpus files
differ. Also: §50/§51 planned, §55 (state.rs size) filed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 13:35:57 -05:00
lucioandClaude Fable 5.1 9ef1058059 Package re-exports as real references: bound halves, RX facts, the member walk through re-exports
ci / checks (push) Successful in 1m17s
ci / corpus (push) Successful in 1m52s
TODO §48 (docs/features/package-reexports). Closes topo §2.9-16 and
dpi-export's request (a).

`bind_export_path` records `export pkg::item` as a `Target::Package` use
and a `Target::UnitMember` use, with no scope import (a re-export brings
nothing into the exporting scope, IEEE 1800 §26.6). `FileFacts` gains the
`RX` group (`FACTS_FORMAT` 17 → 18): per package its re-export edges
(package, source, item|*), with `export *::*` expanded into the package's
own imports at record time. `workspace/reexport.rs`: the member lookup
and listing follow re-exports transitively with a visited set, layered
over `own_chain`/`own_members` so the walk cannot recurse into itself;
`Affected::exporters` keeps one-file updates exact and `fingerprint()`
shows the edges. Definition, hover, completion after `pkg::`, references
and rename all read the one edge. Census 103 870 → 103 875 references
(the corpus's two package export lines), 0 unplaced; 0 of 860 corpus
files differ. opentitan: `spi_device_pkg::SramDepth`, reached only
through a re-export, resolves.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 10:41:54 -05:00
lucioandClaude Fable 5.1 4d59e80568 Type-name spans on the AST; vlog_semantic/src/scan.rs retired
ci / checks (push) Successful in 1m3s
ci / corpus (push) Successful in 33s
TODO §47 (docs/features/type-name-spans). Closes topo §2.9-2.

`DataType` carries `name_start` (a `u32` in its existing padding, so
`Expr` stays at its 96-byte pin) and derives `name_span()` and
`segments()` — the `::`/`.` split from the span's own text, with a
leading escaped identifier read to its terminator first. Five parser
construction sites set it; an implicit type gets the empty range at the
position its name would have had. `StmtKind::Disable { name, name_span }`.
The binder walks `ty.segments()` and verifies every segment's range
against the source before recording it (`exact_or_empty`); a segment that
does not read back is recorded with the empty range, never dropped, so
the census's `unplaced` counter is the alarm a join regression would
move (review rework of QA's MEDIUM). `scan.rs` deleted; `bind_data_type`
lost its `window` and ten call sites their window arithmetic.

Census unchanged in every field (860 files, 27 486 symbols, 103 870
references, 1 197 unresolved, 0 unplaced); 0 of 860 corpus files differ;
200/200 opentitan definition/hover/typeDefinition answers identical.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 09:24:19 -05:00
lucioandClaude Fable 5.1 859742ac84 TODO: §48 package re-exports and §49 cross-file instance-member tail planned
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 08:58:30 -05:00
lucioandClaude Fable 5.1 66f38987ac Release 0.44.0 — opening a file no longer stalls the editor
ci / checks (push) Successful in 1m1s
ci / corpus (push) Successful in 32s
release / build-and-publish (push) Successful in 6m22s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 08:15:37 -05:00
lucioandClaude Fable 5.1 8145a67be6 The didOpen delay: undriven-net asks the workspace census last, not once per declaration
TODO §46 (docs/features/didopen-cost). Closes take-3 finding §8.4 (§44b).

Measured first: on opentitan the open of a 42 192-line file cost
1 745 ms, of which the lint pass was 1 654 ms and `undriven-net` alone
1 608 ms — the rule asked `WorkspaceIndex::files_mentioning` (a walk over
all 3 976 indexed files) once per declaration, ahead of the local guards
that silence almost all of them. Six lines reordered so the oracle is
asked last, as `unused-signal` always did: same findings, same order
(pinned by a counting-oracle unit test that fails on a revert, and shown
byte-identical against 0.43.0 over a crafted workspace and four opentitan
IPs). didOpen → next request: 1 742 → 117 ms on the largest file,
51–95 → 5–8 ms on typical IPs, the same on every keystroke flush. No
debounce added; three wire-level pins with a debug-build bound.

Docs: take-3 §8.4 annotated, docs/perf/README.md entry.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 08:15:37 -05:00
lucioandClaude Fable 5.1 f7956060b3 Small items, round 4: the editor's unknown rule name said once, a warning channel for the walk, inline aggregate override arguments, comment slots inside delay lists
ci / checks (push) Successful in 1m1s
ci / corpus (push) Successful in 32s
TODO §45 (docs/features/small-items-4). Closes topo §2.9-17, 29, 30 and
adds the delay-list bar to §2.9-22.

45.1 `settings::rules` records every dropped `lucisv.lint.select`/`ignore`
name as `lucisv.lint.<setting>: unknown rule: <name>`; `apply_settings`
logs what the previous settings value did not already say — once per
(setting, name), re-armed by a changed list.
45.2 `walk::collect_files` takes a `&mut dyn FnMut(Warning)` sink: an
unreadable directory, an unreadable `.gitignore` and a dangling source
link are warned about and the walk continues; the CLI prints
`warning: <path>: <message>` on stderr before the report with the exit
code unchanged, the server logs once per scan through `report_scope`.
45.3 `parse_expr_or_type` accepts a `struct`/`union`/`enum` head as a
type argument, so `m #(.T(struct packed { logic a; })) u ();` parses and
`instantiation_plan` emits a one-line `parameter type` aggregate default.
45.4 Comment slots for `#(1:2:3)` and gate delay lists
(`MinTypMaxComments`, `DelayValue`, `ContAssign`/`GateInstantiation`/
`GateInstance` slots); `EXPECTED_RTL_GAPS` 374 → 419 at zero failures.
Review rework (QA's MEDIUM): a line comment after a gate instance's `,`
now ends the line, the next instance one level in.

Byte-identity vs 0.43.0: 0 of 820 corpus files and 0 opentitan outcomes
differ.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 07:12:54 -05:00
lucioandClaude Fable 5.1 f302b471a7 TODO: loop 2 order from the owner's twelve rulings; §45 and §46 planned; manual acceptance checklist
ci / checks (push) Successful in 56s
ci / corpus (push) Successful in 30s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 05:50:45 -05:00
lucioandClaude Fable 5.1 7aedfe2554 docs: performance take 3 on opentitan — 0.43.0 vs take 2 vs 0.39.0
ci / checks (push) Successful in 51s
ci / corpus (push) Successful in 28s
TODO §40 (owner request). Every take-2 row re-measured over the wire and
by CLI sweep, three tries each, no instrumentation added. Headlines: the
lazy codeAction is 11.8× on the cursor-move path (200.7 → 24.0 ms at the
128-file fan-out, 39.2 → 5.2 ms on `aes`), the default-scope didOpen is
1 731 → 1 082 ms cold, completion at 0–1 chars 14.8–19.4 → 2.3–3.2 ms;
nothing else moved since 0.39.0. Per-file outcome diff 0.39.0 → 0.43.0
is exactly the three predicted files. Two findings filed as §44
candidates: the eager codeAction path 1.35–1.40× slower than take 2, and
an in-scope didOpen delaying the next request by 21–51 ms.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 03:24:24 -05:00
lucioandClaude Fable 5.1 73799f3d53 Release 0.43.0 — the repository analysis's three findings
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 31s
release / build-and-publish (push) Successful in 6m27s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 02:43:10 -05:00
lucioandClaude Fable 5.1 ec9ec42276 Walker cycle policy by directory identity, and comment slots around a net delay's #
TODO §43 (docs/features/walk-cycles). Closes topo §2.9-8 and §2.9-27 and
repository-analysis finding 3; §2.9-30 filed.

43.1 `lucisv_core::walk::Walk` keeps a `visited` set keyed on `(dev, ino)`
(the canonical path off unix): each directory is entered once, a symlink
to one already entered is skipped, one not yet entered is followed once,
a dangling directory link is skipped. A dangling link that names a source
file is still handed on, so the front end's "no such file" error survives
(review ruling on QA's finding). Both front ends share the walk unchanged
in signature; a cyclic workspace indexes and a cyclic tree formats, each
file once.

43.2 `NetDelay::{before_hash, after_hash}`: the gaps around `#` have
slots, printed inline; the `#SKIP` in net_delay_position.cases is live
and the RTL gap fuzzer covers the construct (374 gaps, 0 failures).

Byte-identity vs 0.42.0: 0 of 820 corpus files differ. On opentitan the
only per-file change is §41's dedup reporting a same-directory symlink
alias once.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 02:43:10 -05:00
lucioandClaude Fable 5.1 4b2dad87fe One lint-configuration contract for project and editor: the server picks the editor's selection when set, else the project's, and logs rejected project entries once
TODO §42 (docs/features/lint-config-contract). Closes topo §2.9-28 and
repository-analysis finding 2.

`enabled_rules(settings, project, has_oracle)`: rung 2 is
`lucisv.lint.select` when non-empty else `[lint] select`, rung 5 the same
for `ignore` — the CLI's `pick` applied to the editor — so one buffer
linted two ways is linted the same way (asserted equal over the wire for
three configurations). `lint::project`: `ProjectLint` read from the
`Discovery` result `configured` already computes (no extra read per
pass); an unknown rule name in a project list is dropped and said rather
than silently emptying the selection. `ConfigProblems`/`ProblemLog`:
rejected `[lint.<rule>]` options, unknown names and bad `[lint] waivers`
lines are logged once per (config file, entry) in `lucisv check`'s
wording, re-armed when the config's lint content changes; the buffer
keeps linting with the entry dropped.

Docs applied: README, the linter guide, configuration.md, the analysis,
topo (28 struck; 29 filed for the editor-side unknown-name silence), site
rebuilt.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 01:45:48 -05:00
lucioandClaude Fable 5.1 3b08c0753c Same-target atomic writers: exclusive per-operation temps, mode before bytes, CLI dedup by canonical identity
TODO §41 (docs/features/atomic-write-coordination). Closes topo §2.9-26
and repository-analysis finding 1.

`atomic::write_atomic` names its temp `.{name}.{pid}.{n}.lucisv-tmp` with
a per-process counter and opens it create-new (O_EXCL), retrying a used
name up to 32 times; on unix the temp is created 0600 when a target
exists and takes the target's mode through the open handle before the
bytes are written, so a 0600 file never has a readable moment. The CLI's
`dedup` keys on the canonical path when the file exists, so a symlink
alias reaches one worker; the reported path is the first spelling. Two
processes on one target remain last-writer-wins (rename is atomic, the
formatter idempotent), stated in the module doc. The audit's probe is a
test: 0 write errors in 200 calls.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 00:40:48 -05:00
lucioandClaude Fable 5.1 972bd1cff1 Release 0.42.0 — external waiver files and the two vendor shapes
ci / checks (push) Successful in 1m5s
ci / corpus (push) Successful in 33s
release / build-and-publish (push) Successful in 6m28s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 00:03:07 -05:00
lucioandClaude Fable 5.1 8a92e79fc0 External waiver files: Verible's format from lucisv.toml, --waiver-file and the editor, union with inline waivers, honoured by quick fixes
TODO §39 (docs/features/waiver-files). Closes §4's last waiver item.

`vlog_linter::waiver_file`: `waive --rule=<rule> [--line=N|N-M]
[--location=<pattern>]`, `#` comments, BOM tolerated; `--location` is
the `--exclude` matcher (`lucisv_core::walk::is_excluded`, a new
vlog_linter → lucisv_core edge), a regex-looking pattern refused by
name. `lint_with(ctx, rules, external)` applies inline and external
waivers as a union and reports which external directives fired;
`lucisv check` reports the dead ones under `unused-waiver` at the
waiver file's line after the whole run. Discovery: `[lint] waivers`
(relative to the toml), `--waiver-file` (repeatable), `lucisv.lint.waivers`
(first workspace root); bad lines fail the CLI run with file:line and
are dropped and logged once by the server.

Review rework (QA's HIGH): the server's code-action path now lints with
the buffer's `LintRun` — its enabled rules and external waivers — so a
quick fix is never offered, nor applied by fix-on-save, for a waived
finding.

Docs: Waivers sections in README and the linter guide, cli and
configuration rows, topo edge, site rebuilt.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-05 00:03:07 -05:00
lucioandClaude Fable 5.1 f6f18de10d docs: repository analysis audit at v0.41.0 — README architecture, topo facts (codec 17, handshakes 26–28), site guides and rebuilt dist
Written by the owner's audit process on 2026-09-04; committed by the lead
unchanged. Findings 1–3 are planned as TODO §41–§43.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-04 23:37:55 -05:00
lucioandClaude Fable 5.1 d5abf81563 The two §11 parser skips: rival unit headers across an ifdef/else split as one verbatim unit, a net delay accepted after the type
TODO §38 (docs/features/parser-skips). Closes the jtag_if.sv and
SimDTM.sv skips from the §11 sweep.

38.1 `Parser::at_rival_header`: in a module/interface/program body, a
continuing directive at the unit's own entry level followed by the same
keyword and name is a header written twice across the arms, not a
nested unit. The error routes into the existing conditional split
(`at_split_conditional` now fires on a rival as well as an open
bracket; `scan_split_extent` runs to the unit's real closer, counting
nested units of the same kind), so the whole unit is one Verbatim item
in both modes. jtag_if.sv now formats (body verbatim, the standing
directive-split trade).

38.2 `DataDecl::delay: Option<NetDelay { expr, after_type }>`: a net
delay is accepted before or after the type (IEEE 1800 §6.7 puts it
after), never both, and printed where it was written. SimDTM.sv now
formats; its four `#0.1` lines come back byte-identical.

Byte-identity vs 0.41.0: 0 of 820 corpus files differ; over 2 554
opentitan files exactly the two named files change outcome.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-04 23:06:37 -05:00
lucioandClaude Fable 5.1 97aa2fefd8 Release 0.41.0 — code actions off the fan-out
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 32s
release / build-and-publish (push) Successful in 6m13s
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-04 18:15:40 -05:00
lucioandClaude Fable 5.1 9604753b6c Lazy codeAction/resolve for the port refactorings, definitions from the index, the inlayHint zero ruled correct
TODO §37 (docs/features/lazy-code-action). Closes the four §10 lines.

37.1 For a client whose resolveSupport lists "edit", the port actions are
offered over the buffer plus the instantiated module's declaration alone
(`ports::offers`, `offer_sources`), carrying `data {uri, position,
title}` and no edit; `codeAction/resolve` (`ports::resolve`) re-runs the
eager path and returns the matching action, matched on the title minus
its count phrase, erroring when the action is gone or the buffer is on
the large-file path. Clients without resolve support get today's eager
answer. Offer flat at ~55 µs from a 3- to a 128-file fan-out where the
eager path was linear; ~4.5 ms vs ~77 ms over the wire on opentitan's
128-file case.

37.2 The inlayHint zero at the default scope is correct: the hinted
module (`pins_if`) is declared outside what the scope reaches, and
definition/hover answer nothing there either. Pinned, not changed.

37.3 `locate::definition_location`: an index-only Location for a closed
file's file-scope declaration from its recorded `DeclPositions`; nav and
workspace symbols routed through it (0.4 µs vs 28 µs). Open buffers keep
the file-read path.

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

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

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

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

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

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

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

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 04:55:10 -05:00
lucioandClaude Fable 5 fbee290a0a docs: topo — linter-expansion-1/2/3 rows; §2.9-25 filed (module-scope begin/end and bare generate begin refused rather than recovered)
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 32s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 04:31:36 -05:00
lucioandClaude Fable 5 b1b3cad09b TODO §35 planned: linter expansion wave 3 — the remaining twenty Verible rules, forbidden-* lists, the e2e options case
ci / checks (push) Successful in 56s
ci / corpus (push) Successful in 29s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:46:55 -05:00
lucioandClaude Fable 5 a896e0dff0 Release 0.38.0 — lint rule options and the Style family
ci / checks (push) Successful in 1m5s
ci / corpus (push) Successful in 33s
release / build-and-publish (push) Successful in 11m24s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:46:03 -05:00
lucioandClaude Fable 5 0cb398bcd9 merge follow-up: §34's port walkers read ANSI port lists through ListElem::ok (§32's error elements)
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-04 03:39:00 -05:00
lucio 17697b9d77 Merge branch 'lint-2' 2026-09-04 03:36:59 -05:00
lucioandClaude Fable 5 5e5813a2a9 Linter expansion, wave 2: per-rule options end to end, options on the naming rules, and eighteen Style rules
TODO section 34 (36 -> 54 rules).
Options: OptionSpec/OptionKind/OptionValue/RuleOptions in vlog_linter
with one validator behind both front ends - [lint.<rule>] tables in
lucisv.toml (accepted now; stored raw by lucisv_core::config, resolved
per file by the CLI with <config>:<line> on the first bad entry) and
the editor's lucisv.lint.options object (bad entries logged and
dropped) - precedence editor > toml > default key by key, --rules-doc
listing every option. A small anchored regex engine of our own: a
Thompson-NFA simulation, linear in pattern x name by construction
(QA's first cut found the backtracking matcher exponential on (a*)*b),
unknown escapes refused by name through both doors, a 71-row table
verified against CPython. The four naming rules take Verible's option
spellings with defaults that keep today's verdicts byte-identical.
Eighteen Style rules, one file each with true positives and near-
misses: line-length (the formatter's width), posix-eof (safe fix),
forbid-consecutive-null-statements (safe fix), generate-label and
generate-label-prefix, package-filename, one-module-per-file (off),
signal/interface/macro/constraint/parameter-type-name-style,
port-name-suffix (off), banned-declared-name-patterns (off),
typedef-enums, typedef-structs-unions (allow_anonymous_nested defaults
true here - opentitan's 3 159 findings were all generated register
packages, and its own config disables the rule), always-comb (unsafe
fix), explicit-begin (off, Verible's eleven enables). Four rules ask
parsed_cleanly() first after a census showed error-recovered UVM files
rebound as generate blocks. package.json regenerated (drift test).
3 549 tests / 48 binaries; corpus 814/820 byte-identical; naming-rule
finding lists identical to 0.36.0; opentitan check timing unchanged.

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 17:47:41 -07:00
392 changed files with 66084 additions and 2924 deletions

No files matched your search

+403
View File
@@ -4,6 +4,409 @@ 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.49.0 — 2026-09-06
### Inline module; the last coverage gaps
- **Inline module.** With the cursor on `S u_S (...)`, `S`'s body is
copied into the instantiating module: ports replaced by the connected
names or literals, parameters as `localparam`s with the override or
default, internal names prefixed `u_S_` only where the file already
spells one of them, comments and attributes carried verbatim, `.name`
shorthand connections inside the body expanded when their signal is
renamed. Refuses — with a sentence — a `.*` or positional list, an
expression connection, an unconnected port, an output into a literal,
any hierarchical reference to the instance, a `generate`, `initial`/
`final`, macros, directives, interface/`inout`/unpacked ports, and a
module declared in the same file. `refactor.inline` action,
`lucisv.inlineModule`. Extract → inline round-trips byte-equal after
formatting.
- **The verifier learns a copy.** A copied region's comments and
attributes may be written once per copy in the destination while the
copied file must appear in no edit at all; attack tests through the
production entry, re-attacked by QA.
- **The last coverage gaps.** Six language shapes now parse and format:
`->>` non-blocking event triggers (with delay or event control), stream
`with [range]` slices, the LRM's other cast bases (`(W+1)'(x)`,
`logic [3:0]'(x)`), drive strength on a net declaration (`wire (strong0,
weak1) w = a;` — its comment slots also fix a pre-existing refusal on
`assign /*c*/ (weak0, pull1) x = y;`), `let` at statement position, and
`#(min:typ:max)` clocking skews. `randsequence … endsequence` is a real
node — productions, weighted alternatives, `rand join`, `repeat`,
`if`/`case`, code blocks — printed one production per line; it was a
parse error before and `randsequence` is now a keyword. Comment slots
added to `let`, stream concatenations and the clocking grammar: the
formatter's gap fuzzer covers 499 gaps at zero failures.
- **`[format] uvm-utils-indent`** (editor `lucisv.format.uvmUtilsIndent`),
default off: indents the `uvm_field_*` lines between
`uvm_object_utils_begin`/`uvm_component_utils_begin` and their `_end`.
On over the corpus it changes 21 files, all idempotent, no comment
lost. A short comment-free enum body already prints on one line, so no
key was added for it; the behaviour is pinned.
## 0.48.2 — 2026-09-06
### The 0.48.0 packages, rebuilt from the right commit
- **0.48.0's packages were built one commit early** — a release-chain
slip tagged the version commit before the feature commit landed, and
the tag was moved after the build had started — so its extension lacks
the DUT-centred hierarchy view its notes describe. **0.48.1 never
built**: its tag caught a concurrent lane's half-written verifier
edits. 0.48.2 is the 0.48.0 tree, packaged from the commit that has
the view. Nothing else changed.
## 0.48.0 — 2026-09-06
### A DUT-centred hierarchy view
- **Star a module as DUT** from the hierarchy pane's row menu (or the
`lucisv.hierarchy.starDut` command, or a checked-in
`lucisv.hierarchy.duts` setting, whose entries show locked). Each DUT
gets two collapsible sections: the DUT with its instance subtree, the
DUT at the very top, and the DUT's parents — an upward tree from the
DUT through every module that instantiates it, transitively, which is
where the DV bench lands. One section holds every other module: those
in no DUT's subtree or ancestor chain, re-rooted where their only
parents are DUT ancestors, so a monitor beside the DUT under the same
bench stays visible. One DUT → three sections; two → five. A module
both below one DUT and above another appears in both DUT sections.
With nothing starred the pane is exactly as before. Client-only, over
the hierarchy snapshot the server already sends.
## 0.47.0 — 2026-09-06
### Organize imports, extract module
- **Organize imports.** Removes the `import pkg::*;` lines nothing in the
scope reaches through, merges exact duplicates and sorts the run at the
top of a module, package or class; `source.organizeImports`, so an
editor's organize-on-save runs it, and `lucisv.organizeImports`. "Used"
is the binder's own lookup, read as a superset — over-keeping is the
safe direction — and an `export pkg::…` in the same package counts as a
use of its import (IEEE 1800 §26.6). It refuses rather than guesses
wherever a macro call, a conditional directive, an unknown or
twice-declared package, or a base class in another file could hide a
use, which is why every opentitan UVM package (all carrying
`` `include "uvm_macros.svh" ``) is refused. The same judgement is the
new `unused-import` rule (Style, off by default, safe fix).
- **Extract module.** Select whole module items and give a name: the
items become a new module with ports inferred from dataflow across the
selection (read only → `input`, written → `output`, written on both
sides → refused), parameters passed through, used imports copied, and
the selection replaced by an instantiation rendered from the new
module's own text. Written to a new file when the client can create
one, below the source module otherwise. Forty-three refusal sentences
for what lucisv cannot judge (a routine argument, a hierarchical path
crossing the boundary, an interface-typed name, a `typedef` of the
source module, …). `refactor.extract` code action, `lucisv.extractModule`,
and a name prompt in the VS Code extension. Inline module follows in a
later release.
- **The verifier's never-dropped ledger follows a move.** For the bytes
an extraction moves, a comment or attribute deleted inside the moved
region must land exactly once in the file the move names; a deletion
outside the region stays an ordinary deletion that must be written
back in its own file. Opt-in per edit, four equations, twelve attack
pairs through the production entry, re-attacked by QA.
## 0.46.0 — 2026-09-05
### Two refactorings: expand `.*`, convert ports to ANSI
- **Expand `.*`.** A wildcard connection is written out as the named
connections it stands for, in the module's declaration order, through
the port engine's splice and verifier. The wildcard rule is read
strictly (IEEE 1800 §23.3.2.4): a same-named net, variable or port
binds; a parameter, genvar, type or instance does not, and that port
becomes `.p()` with a warning naming it. Refused inside a `bind`
directive, on a positional list, on two `.*`, or when a file does not
parse. Code action `lucisv: expand .* (N connections)` and command
`lucisv.expandWildcard`.
- **Convert ports to ANSI.** A Verilog-2001 header with body
declarations becomes an ANSI header (`output b; reg [7:0] b;` →
`output reg [7:0] b`, every merge of §23.2.2.2), the absorbed
declarations deleted and their comments carried onto the ports. The
edit inserts around each header name so nothing that referenced the
port moves; twenty-three shapes are refused with a sentence rather
than guessed (port expressions, disagreeing ranges, initialisers,
directives, a comment that would have to move into a one-line list).
Code action `lucisv: convert ports to ANSI (N ports)` and command
`lucisv.convertToAnsi`.
- **The refactoring verifier's comment rule is stricter, and covers
attributes.** Every comment and every `(* … *)` attribute a file had it
still has, by exact text and count; a piece a deletion covers is
written back exactly as many times as it was deleted, and an edit may
not duplicate one nothing touched — which also catches a comment
rewritten, truncated or duplicated. Ships with masked-corruption
attack tests, re-attacked by QA.
## 0.45.0 — 2026-09-05
### Cross-file semantics: type spans, re-exports, hierarchical tails
- **Type names carry spans.** Every `DataType` and `disable` target knows
its range on the AST; the semantic crate's text scanner (`scan.rs`) is
deleted. Definition and hover on a type name land exactly, `pkg::t`
selecting `t`; a segment the source spells differently from the
parser's join is recorded with an empty range rather than guessed.
- **Package re-exports are real references.** `export pkg::item;` and
`export pkg::*;` bind both halves, the index records each package's
re-exports, and definition, hover, completion after `pkg::`, references
and rename follow them transitively. On opentitan a name reached only
through `export spi_device_reg_pkg::SramDepth;` now resolves.
- **Renaming an internal net edits its hierarchical uses in other files.**
A module now has a hierarchical surface (nets, variables, instances)
read only behind an instance head — `assign w = u_x.sig;` in another
file renames with `sig`'s declaration, nested `u_a.u_b.sig` included —
while connection lists still see ports and parameters only. Completion
after `u_x.` in an expression lists the hierarchical members. Over
opentitan's `hw/`, 514 hierarchical references resolve that did not
before; a rename that now reaches one more file costs one more file's
read.
- The index facts format is 19; stores written by earlier releases are
rebuilt on first use.
## 0.44.0 — 2026-09-05
### Opening a file no longer stalls the editor
- **`undriven-net` asked the workspace census once per declaration**,
ahead of the local guards that silence almost every one, so a
`didOpen` — and every keystroke flush — of a large file paid a walk
over every indexed file thousands of times. Asked last now, the way
its twin `unused-signal` always did. Opening opentitan's 42 192-line
`pinmux_reg_top.sv` at workspace scope: 1 742 ms → 117 ms; typical
IP files 51–95 ms → 5–8 ms. Same findings in the same order.
- **Walk warnings.** An unreadable directory, an unreadable `.gitignore`
or a dangling source-file symlink no longer fails a run: the CLI
prints `warning: <path>: <message>` on stderr before the report with
the exit code unchanged, and the server logs once per scan.
- **A typo in `lucisv.lint.select` or `ignore`** is logged once
(`lucisv.lint.select: unknown rule: <name>`) instead of silently
emptying the selection.
- **Inline aggregate types as parameter-override arguments**
(`m #(.T(struct packed { logic a; })) u ();`) parse, format and are
emitted by the instantiation skeleton.
- **Comment slots inside delay lists** (`#( /*a*/ 1 : 2 : 3 )`, gate
`#(rise, fall)`), and a line comment after a gate instance's comma
now ends the line.
## 0.43.0 — 2026-09-05
### The repository analysis's three findings
- **Atomic writers cannot collide.** In-place writes use an exclusive,
per-operation temp file (`.{name}.{pid}.{n}.lucisv-tmp`, created
0600 when a target exists and given the target's mode before the bytes
land); the CLI deduplicates its inputs by canonical identity, so a
symlink alias of a file reaches one worker and is reported once. Two
processes on one target remain last-writer-wins, which the formatter's
idempotence makes safe.
- **One lint-configuration contract.** The editor now honours a project's
`[lint] select` and `[lint] ignore` the way the CLI honours its flags:
`lucisv.lint.select` when set, else the project's, key by key, with the
editor-only severity switches and per-rule toggles applied over whichever
stands. A project entry the server cannot use — a rejected `[lint.<rule>]`
option, an unknown rule name, a bad waiver directive — is logged once with
file and line in `lucisv check`'s wording and dropped; the buffer keeps
linting. The CLI's and the server's rule lists are asserted equal over
the wire.
- **Directory walks terminate on symlink cycles.** Each directory is
entered once by identity; a link to a directory already entered is
skipped, one not yet entered is followed once, a dangling directory link
is skipped and a dangling source-file link is still reported. Both the
CLI and the server's index scan.
- A comment before a net delay's `#` (`wire /* c */ #5 w;`) now formats.
## 0.42.0 — 2026-09-05
### External waiver files, and the two vendor shapes the sweep skipped
- **External waiver files** in Verible's format: `waive --rule=<rule>
[--line=N|N-M] [--location=<pattern>]`, `#` comments. Read from
`[lint] waivers` in `lucisv.toml`, `lucisv check --waiver-file` (repeatable)
and the editor setting `lucisv.lint.waivers`; the three add up.
`--location` is an `--exclude`-style pattern, not a regex, and a
regex-looking one is refused by name. Union with inline waivers; unused
external waivers are reported under `unused-waiver` at their line of the
waiver file by `lucisv check`, after the whole run. The editor's quick
fixes and fix-on-save honour external waivers too.
- **Rival module/interface headers across an `ifdef`/`else`** (opentitan's
`jtag_if.sv`) now parse: the unit is kept verbatim as a whole, the
standing directive-split trade, instead of nesting and losing its
closer.
- **A net delay after the type** (`wire [31:0] #0.1 x = y;`, where the LRM
puts it) is accepted and printed where it was written.
- Documentation: the repository analysis audit's README and site rewrite
(architecture across all eight crates, topo facts at codec 17) is
committed; its three findings are planned as TODO §41–§43.
## 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
**Per-rule options.** A rule that takes options can be configured in
`lucisv.toml` (`[lint.line-length] length = 120`,
`[lint.signal-name-style] style_regex = "[a-z_0-9]+"`) and from the
editor (`lucisv.lint.options`, one object keyed by rule). Both doors run
one validator: a bad key, kind, range or pattern fails `lucisv check`
naming the file and line, and is logged and dropped in the editor so a
typo cannot switch a rule off. Editor options win over `lucisv.toml`,
key by key. `--rules-doc` lists every option with its kind and default.
Patterns use a small built-in regex dialect (literals, `.`, classes,
groups, alternation, `* + ?`, `\d \w \s`), whole-name anchored, run as
a linear-time automaton so no pattern can slow a lint run; anything
outside the dialect is refused by name.
**Eighteen new Style rules** (54 in all): `line-length` (the
formatter's width), `posix-eof` (safe fix), `forbid-consecutive-null-
statements` (safe fix), `generate-label`, `generate-label-prefix`,
`package-filename`, `one-module-per-file` (off), `signal-name-style`
(off), `interface-name-style`, `macro-name-style`,
`constraint-name-style`, `parameter-type-name-style` (off),
`port-name-suffix` (off), `banned-declared-name-patterns` (off),
`typedef-enums`, `typedef-structs-unions`, `always-comb` (unsafe fix),
`explicit-begin` (off). The four existing naming rules take Verible's
option spellings. `typedef-structs-unions` allows a nested anonymous
aggregate by default — a deliberate divergence from Verible, because
every one of its 3 159 findings on opentitan was a generated register
package; `allow_anonymous_nested = false` restores the stricter reading.
Every rule's toggle in VS Code is regenerated from the registry.
## 0.37.0 — 2026-09-04
### Typing a header no longer loses the module
While you type a port list, a parameter list, a function's argument
list, an instantiation's connections, or the header of a `for`/`if`/
`while`/`case`, the editor used to lose the whole surrounding module or
function: its body re-parsed at file scope, its symbols vanished from
the outline and from completion, and the orphaned `endmodule` produced a
second error. Recovery now happens inside the list: the element that
failed becomes an error element, the ones you already typed stay, the
header keeps its node, and the body binds in the right scope. One
diagnostic per typo. The strict parse (what the formatter uses) is
untouched, so every corpus file formats byte for byte as before.
Measured over the corpus with every file cut in half: error nodes fall
by 11 %; diagnostics rise by 7 % because a module whose header was cut
now survives to report its missing `endmodule` instead of vanishing
into one error node. Known gap: a half-typed `#(` override whose value
can read as a call still collapses its instantiation (filed).
## 0.36.1 — 2026-09-04
The 0.36.0 tag never published: its release commit shipped without a
CHANGELOG section (the release chain's draft lived in a session
scratchpad that a crash had wiped), and the release workflow refuses a
version without notes, as designed. 0.36.1 is 0.36.0 plus these notes.
## 0.36.0 — 2026-09-03
### The linter grows up: severities, per-rule toggles, and 19 new rules
Every lint rule now has a **severity** — `error` (would likely fail to
compile or elaborate, or silently mis-synthesize), `warning` (a probable
bug) or `style` — printed in `lucisv check` output
(`FILE:LINE:COL: warning: message [rule]`), carried in the JSON output,
mapped to red / yellow / blue in the editor, and shown in
`--rules-doc`, which now groups rules by class. `--select`, `--ignore`
and `[lint]` in `lucisv.toml` accept a severity word (`--ignore style`).
**Editor toggles.** VS Code settings gain three master switches
(`lucisv.lint.severity.error`, `.warning`, `.style`) and one setting per
rule (`lucisv.lint.rules.<rule>`: `default` / `on` / `off`), generated
from the rule registry so the list can never drift. Precedence, top to
bottom: defaults → `select` → severity switches → per-rule settings →
`ignore`. Changing any of them re-checks every open file.
**New rules — Error**: `mismatched-labels`, `duplicate-declaration`,
`undeclared-identifier` (with a project; silent for names that come
from macros, `` `include``d fragments or hierarchical paths),
`unknown-port`, `unknown-parameter`.
**New rules — Warning**: `forbid-defparam`, `invalid-system-task-function`,
`truncated-numeric-literal`, `undersized-binary-literal` (safe fix pads),
`suspicious-semicolon`, `packed-dimensions-range-ordering`, `module-port`,
`module-parameter`, `explicit-function-task-parameter-type`,
`plusarg-assignment`, `instance-shadowing`, `forbid-negative-array-dim`,
`void-cast`, `incomplete-assignment` (latch inference in `always_comb`).
Verible equivalents are named in each rule's documentation; defaults
follow Verible's except where the doc says why not. Existing rules
re-classified: `multiply-driven` and `wire-reg-mixup` are errors.
Measured on opentitan: every false-positive class found was closed with
a test; `lucisv check` over its `hw/` tree runs in the same time as
0.35.0.
## 0.35.0 — 2026-09-02
### Format fences reach statements and class bodies
+14
View File
@@ -128,6 +128,20 @@ Rules:
- Update `TODO.md`: check items your feature completes (leave the item
text intact).
## Runaway guard (never run a suite or sweep bare)
On 2026-09-03 a background test run consumed 100 GB and crashed the
machine. macOS enforces no memory cap, so the cap is ours:
`tools/guard.sh [-m GB] [-t SECONDS] -- <command>` kills a command's
process tree when its resident set or wall clock exceeds the limits
(defaults 8 GB / 30 min).
- **Every `cargo test`, every fuzzer, every corpus or opentitan sweep,
and every `lucisv`/`lucisv-server` run over a tree goes through
`tools/guard.sh`** — dev, QA and lead alike, foreground or background.
- A guard kill is a finding: report the command and the limit it hit;
do not raise the limit to make it pass.
## Parallel lanes (the 2-agent loop)
Up to **two dev/QA lanes may run concurrently** when — and only when —
Generated
+10 -8
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.35.0"
version = "0.49.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.35.0"
version = "0.49.0"
[[package]]
name = "lucisv_server"
version = "0.35.0"
version = "0.49.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,15 +248,16 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.35.0"
version = "0.49.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.35.0"
version = "0.49.0"
dependencies = [
"lucisv_core",
"vlog_formatter",
"vlog_parser",
"vlog_semantic",
@@ -264,19 +265,20 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.35.0"
version = "0.49.0"
[[package]]
name = "vlog_refactor"
version = "0.35.0"
version = "0.49.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
"vlog_semantic",
]
[[package]]
name = "vlog_semantic"
version = "0.35.0"
version = "0.49.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.35.0"
version = "0.49.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+293 -34
View File
@@ -2,6 +2,12 @@
A Verilog and SystemVerilog formatter, linter, and language server written in Rust.
Start with the [repository analysis](docs/repository-analysis.md) for a code-based
assessment and [dependency topology](docs/topo.md) for interfaces and change
impact. The [documentation site source](docs/site/README.md) contains usage
guides and references; [CHANGELOG.md](CHANGELOG.md) records releases, and
[TODO.md](TODO.md) tracks work in progress.
An opinionated, fast formatter and linter for Verilog-2001 and SystemVerilog
RTL, built in the image of [ruff](https://github.com/astral-sh/ruff), with
layout conventions and lint ergonomics borrowed from
@@ -106,6 +112,12 @@ trailing `/` (matches directories only), and `!` negation. **Not** supported:
git's "already-tracked files are never ignored" rule. See
`docs/features/parallel-files/README.md` for the exact subset.
Directory walks enter each directory once by identity, so symlink cycles
terminate. Inputs resolving to one canonical file path are processed once.
Unreadable directories or `.gitignore` files and dangling source links found
during a walk warn on stderr and are skipped without changing the exit code;
a missing explicitly named input is still an error.
## Configuration
Settings live in a `lucisv.toml` (or `.lucisv.toml`) file, ruff-style. For each
@@ -158,11 +170,16 @@ error (exit 2) and nothing is processed. Details:
**Precedence: CLI flag > config file > default**, per setting (`--indent 4`
with a file that sets only `line-length` uses both). `exclude` is the
exception: config patterns are *added* to `--exclude`, not replaced by it.
`[format] uvm-utils-indent = true` (editor: `lucisv.format.uvmUtilsIndent`),
off by default, indents the `` `uvm_field_* `` macros written between
`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; it is the one
formatting choice lucisv leaves to the project, because it changes bytes
in existing UVM code (21 of the 860 corpus files).
An unknown key, a bad value, an out-of-range number, or any TOML beyond the
supported subset (tables other than `[lint]`, multi-line arrays, string
escapes) is a hard error naming the file and line — exit 2, with nothing
written. This is deliberate:
supported subset (tables other than `[lint]` and `[lint.<rule>]`, multi-line
arrays, unsupported string escapes) is a hard error naming the file and
line — exit 2, with nothing written. This is deliberate:
a silently ignored `line_length` typo costs more than a strict parser does.
## Linting
@@ -172,11 +189,13 @@ would format — same walk, same `--exclude`, same `.gitignore` handling, same
`lucisv.toml` discovery.
```bash
lucisv check rtl/ # FILE:LINE:COL: message [rule-name]
lucisv check rtl/ # FILE:LINE:COL: severity: message [rule]
lucisv check --output-format json rtl/ # one JSON array, for editors and CI
lucisv check --select no-tabs rtl/ # only these rules (comma-separated)
lucisv check --ignore module-filename rtl/ # everything but these
lucisv check --select error rtl/ # a whole severity class, by name
lucisv check --fix rtl/ # apply the safe fixes, write files back
lucisv check --rules-doc # the generated reference for every rule
```
Exit codes are the frozen contract above: 0 clean (or everything fixed), 1
@@ -184,35 +203,195 @@ violations remain, 2 error. Unlike the formatter, `check` uses the
error-tolerant parser, so a file lucisv cannot fully parse is still linted for
what it can see.
| Rule | Fix | What it wants |
### Severities
Every rule is in one of three classes, and the class is the word that stands
in the diagnostic line, in the JSON `severity` field, and in the editor's
squiggle colour:
| Class | Means | Editor |
|---|---|---|
| `no-tabs` | safe | spaces, not tabs (a tab inside a string is left alone) |
| `no-trailing-whitespace` | safe | nothing but code before the newline |
| `case-missing-default` | — | every `case`/`casex`/`casez` has a `default` |
| `always-ff-non-blocking` | — | `<=` inside `always_ff` |
| `always-comb-blocking` | — | `=` inside `always_comb` |
| `explicit-parameter-storage-type` | — | `parameter int W = 8`, not `parameter W = 8` |
| `module-filename` | — | a one-module file is named after its module |
| `unused-waiver` | — | waivers that suppress nothing |
| `unused-signal` † | — | no net or variable nothing uses |
| `undriven-net` † | — | everything read is driven by something |
| `multiply-driven` † | — | one driver per variable |
| `error` | would very likely fail to compile, elaborate or synthesize | red (LSP Error) |
| `warning` | compiles, and very likely does not mean what it says | yellow (LSP Warning) |
| `style` | correct, and reads badly | blue (LSP Information) |
A class name is accepted **wherever a rule name is** — on `--select`, on
`--ignore`, and in `select`/`ignore` under `[lint]` in `lucisv.toml`:
```bash
lucisv check --select error rtl/ # only the compile-breakers
lucisv check --ignore style rtl/ # everything but the naming rules
```
Every `error`-class rule follows one discipline: **silence beats a wrong
accusation**. Each of them goes quiet whenever the run cannot answer — a file
that did not fully parse, a module the project does not hold or holds twice, a
name a macro produces, a fragment written to be `` `include``d. That is what
makes an editor's red squiggle worth believing.
### The rules
| Rule | Severity | Fix | What it wants |
|---|---|---|---|
| `multiply-driven` † | error | — | one driver per variable |
| `wire-reg-mixup` | error | — | `logic`, not `reg`, in a `.sv` file |
| `mismatched-labels` | error | — | `end : name` names the block it closes |
| `duplicate-declaration` | error | — | each name declared once per scope |
| `undeclared-identifier` † | error | — | every name is declared somewhere in the project |
| `unknown-port` † | error | — | `.name(…)` is a port the module declares |
| `unknown-parameter` † | error | — | `#(.NAME(…))` is a parameter it declares |
| `always-ff-non-blocking` | warning | — | `<=` inside `always_ff` |
| `always-comb-blocking` | warning | — | `=` inside `always_comb` |
| `case-missing-default` | warning | — | every `case`/`casex`/`casez` has a `default` |
| `incomplete-assignment` | warning | — | an `always_comb` assigns on every path |
| `suspicious-semicolon` | warning | — | no `if (x);` / `for (…);` / `while (…);` |
| `forbid-defparam` | warning | — | override at the instantiation, not with `defparam` |
| `invalid-system-task-function` | warning | — | no `$random`, `$psprintf`, `$dist_*`, `$srandom` |
| `plusarg-assignment` | warning | — | `$value$plusargs`, not `$test$plusargs` |
| `truncated-numeric-literal` | warning | — | a sized literal fits its width |
| `undersized-binary-literal` | warning | safe | every bit of a sized binary literal is written |
| `packed-dimensions-range-ordering` | warning | — | a packed dimension is `[N-1:0]` |
| `forbid-negative-array-dim` | warning | — | no negative literal in a dimension |
| `module-port` | warning | — | more than one port is connected by name |
| `module-parameter` | warning | — | more than one parameter is overridden by name |
| `explicit-function-task-parameter-type` | warning | — | every tf argument has a storage type |
| `void-cast` | warning | — | `void'(…)` wraps a call |
| `instance-shadowing` | warning | — | no declaration hides an enclosing one |
| `undriven-net` † | warning | — | everything read is driven by something |
| `unused-signal` † | warning | — | no net or variable nothing uses |
| `create-object-name-match` | warning | — | `type_id::create("x")` names the handle `x` |
| `forbidden-macro` | warning | — | no macro on the project's forbidden list |
| `uvm-macro-semicolon` | warning | — | no `;` after a `` `uvm_* `` macro (off by default) |
| `macro-string-concatenation` | warning | — | no `` `` `` inside a plain string (off by default) |
| `disable-statement` | warning | — | `disable fork`, not a fork label (off by default) |
| `no-tabs` | style | safe | spaces, not tabs (a tab inside a string is left alone) |
| `no-trailing-whitespace` | style | safe | nothing but code before the newline |
| `empty-item` | style | safe | no `;` standing where an item belongs |
| `explicit-parameter-storage-type` | style | — | `parameter int W = 8`, not `parameter W = 8` |
| `module-filename` | style | — | a one-module file is named after its module |
| `enum-name-style` | style | — | `lower_snake_case` ending `_e`/`_t` |
| `struct-union-name-style` | style | — | `lower_snake_case` ending `_t` |
| `parameter-name-style` | style | — | `CamelCase` or `ALL_CAPS` |
| `module-name-style` | style | — | `lower_snake_case` (off by default) |
| `line-length` | style | — | no line wider than the width the formatter uses |
| `posix-eof` | style | safe | the file ends with a newline |
| `forbid-consecutive-null-statements` | style | safe | no `;;` where a statement belongs |
| `generate-label` | style | — | every generate block carries a `: label` |
| `generate-label-prefix` | style | — | that label starts with `g_` or `gen_` |
| `package-filename` | style | — | a one-package file is named after its package |
| `interface-name-style` | style | — | `lower_snake_case` ending `_if` |
| `macro-name-style` | style | — | a `` `define`` name is `ALL_CAPS` |
| `constraint-name-style` | style | — | `lower_snake_case` ending `_c` |
| `typedef-enums` | style | — | an `enum` type is named with a `typedef` |
| `typedef-structs-unions` | style | — | a `struct`/`union` type is named with a `typedef` |
| `always-comb` | style | unsafe | `always_comb`, not `always @*` |
| `signal-name-style` | style | — | `lower_snake_case` signals (off by default) |
| `parameter-type-name-style` | style | — | `lower_snake_case` ending `_t` type parameters (off) |
| `port-name-suffix` | style | — | `_i` / `_o` / `_io` say which way a port points (off) |
| `one-module-per-file` | style | — | one `module` per file (off by default) |
| `banned-declared-name-patterns` | style | — | no declared name matching a project's own list (off) |
| `explicit-begin` | style | safe | every body is a `begin ... end` block (off by default) |
| `unused-waiver` | style | — | waivers that suppress nothing |
| `unused-import` † | style | safe | no `import` nothing in the scope reaches through (off by default; stays off without a project) |
| `explicit-function-lifetime` | style | — | `automatic`/`static` on a function outside a class |
| `explicit-task-lifetime` | style | — | `automatic`/`static` on a task outside a class |
| `positive-meaning-parameter-name` | style | — | no `disable`-prefixed parameter name |
| `suggest-parentheses` | style | safe | `a ? (b ? c : d) : e`, parenthesized |
| `unpacked-dimensions-range-ordering` | style | — | an unpacked dimension is `[0:N-1]` |
| `module-begin-block` | style | — | no `begin`/`end` at module scope |
| `v2001-generate-begin` | style | — | no bare `begin` in a generate region |
| `forbid-line-continuations` | style | — | no `\` breaking a string literal |
| `legacy-generate-region` | style | — | no `generate … endgenerate` wrapper (off) |
| `legacy-genvar-declaration` | style | — | a genvar is declared in the `for` header (off) |
| `endif-comment` | style | safe | `` `endif `` names what it closes (off by default) |
| `numeric-format-string-style` | style | — | a radix prefix matches its specifier (off) |
| `proper-parameter-declaration` | style | — | `parameter` in a header, `localparam` in a body (off) |
| `dff-name-style` | style | — | a flip-flop is `_q`, its input `_d` (off by default) |
† On by default when lucisv can see a project (a multi-file CLI run or the
language server), and off for a single file or stdin unless `--select` names
them. These three read the file's *symbol table*, not just its syntax; the
project-wide identifier census keeps a hierarchical use in another file from
becoming a false positive. See `docs/features/semantic-lints-on/README.md`.
The table above is not the whole set — naming-style rules ship too, and
`cargo run -p vlog_linter --example rules_markdown` prints the generated
reference for every rule with its default.
them. These rules read the file's *symbol table* and ask the project about
names, not just the file's syntax; the project-wide identifier census keeps a
hierarchical use in another file from becoming a false positive. See
`docs/features/semantic-lints-on/README.md` and
`docs/features/linter-expansion-1/README.md`.
`lucisv check --rules-doc` prints the whole reference — every rule, its class,
its default, its fix and the paragraph saying why it exists — generated from
the registry, so it can never be out of date.
Fixes follow ruff's applicability model: `--fix` applies *safe* fixes (those
that cannot change what the code means), `--unsafe-fixes` widens that — no
rule ships an unsafe fix yet. Violations inside a `// verilog_format: off`
that cannot change what the code means), `--unsafe-fixes` widens that to the
rest. One rule ships an unsafe fix: `always-comb` rewrites `always @*` to
`always_comb`, which is a different block at time zero and makes a second
driver of its outputs an error — right nearly always, and not lucisv's call to
make without being asked. Violations inside a `// verilog_format: off`
region are reported but never fixed: `off` means hands-off for the linter too,
so `--fix` leaves every byte of a fenced region exactly as written.
### Rule options
A rule can be configured in a `[lint.<rule-name>]` table:
```toml
[lint]
ignore = ["typedef-structs-unions"]
[lint.line-length]
length = 120 # the linter's limit, if not the formatter's
[lint.generate-label-prefix]
prefix = ["g_", "gen_"] # the label prefixes this project writes
[lint.parameter-name-style]
localparam_style = "CamelCase" # Verible's own default, stricter than ours
[lint.signal-name-style]
style_regex = "[a-z][a-z_0-9]*" # a pattern, matched against the whole name
```
The keys are Verible's wherever it has the same option, so a `.rules.verible`
file translates word for word. An option nobody sets reads the default
`lucisv check --rules-doc` prints beside it. An unknown rule or option name, a
value of the wrong kind, an integer out of range or a pattern that does not
compile **fails the run**, naming the config file and the line — a typo in a
lint setting is not something to guess at.
Patterns are not full RE2. What is supported: literals, `.`, `[...]` classes
with ranges and negation, the escapes `\d \D \w \W \s \S` (character
classes), `\n \t \r` (control characters) and `\<punctuation>` (that
character, literally), groups, `|`, and the postfix `*` `+` `?` — matched
against the **whole** name, so `^`/`$` are accepted and redundant.
Everything else is **refused when the option is read, by name**: counted
repetition (`{2,3}`), lookaround and flag groups (`(?=…)`, `(?:…)`), and every
escape not listed above — a backreference (`\1`), a word boundary (`\b`),
`\A`, `\z`, `\p{…}`, `\x41`. An unsupported escape read as a literal would
quietly judge the wrong names (`\bword\b` would match `bwordb`), which is
worse than an error you can read.
Matching is a Thompson-NFA simulation, so it is linear in pattern × name
length whatever shape the pattern has: no pattern can make `lucisv check` — or
an editor session — hang.
From an editor the same options are one object, `lucisv.lint.options`:
```json
"lucisv.lint.options": {
"line-length": { "length": 120 },
"typedef-structs-unions": { "allow_anonymous_nested": false }
}
```
There the precedence is **the editor's value, then the `lucisv.toml`, then the
rule's default — key by key**: a project can set two options and one user
override the third without losing the others. (This is the opposite order to
the formatting settings, where a checked-in `lucisv.toml` outranks the editor:
formatting has a byte-exact contract with CI, and which findings you are shown
in your own editor is yours to choose.) A bad entry there is *ignored* and
reported in the lucisv log rather than fatal, so one typo cannot leave a
session with no diagnostics.
### Waivers
```systemverilog
@@ -226,13 +405,61 @@ wire a; // lucisv: waive no-tabs suppresses that rule on this line
works unedited — including waivers naming Verible rules lucisv has not
implemented, which are ignored rather than reported. A waiver of lucisv's own
that suppresses nothing, names an unknown rule or is malformed is reported
under `unused-waiver`. External waiver files are not supported. Full rules:
under `unused-waiver`.
Findings can also be suppressed from **outside** the RTL, in Verible's
waiver-file format — one directive per line, `#` comments and blank lines
ignored:
```text
# every line of every file
waive --rule=no-tabs
# one line, or a range with both ends included
waive --rule=line-length --line=12
waive --rule=line-length --line=12-20
# only the files a pattern names
waive --rule=no-tabs --location=legacy/top.sv
```
`--rule` is required and names exactly one rule (a severity word is not
accepted). `--line` is 1-based. `--location` is matched the way an
`--exclude` pattern is — `*` within one path component, a pattern with `/`
matching a path suffix, one without matching the file name at any depth — and
**not** as a regular expression; a pattern that looks like one (`.*`, `\.`,
`[…]`) is an error naming the difference.
Waiver files come from three places, and they add up: `lucisv check
--waiver-file <path>` (repeatable, relative to the working directory),
`waivers` under `[lint]` in `lucisv.toml` (relative to that file; read by the
CLI and the editor), and the editor setting `lucisv.lint.waivers` (relative to
the first workspace folder). External and inline waivers are a union: a
finding either covers is suppressed, and one both cover leaves neither
reported as dead. A missing file or an unparsable directive fails `lucisv
check` with `<file>:<line>: <message>` and exit 2; in an editor the bad line
is dropped and the rest of the file applies, and the bad line is written once
to the lucisv log whether the file was named by the editor setting or by
`lucisv.toml`. Unused external waivers
are reported under `unused-waiver` at their line of the waiver file, by
`lucisv check` only and only after the whole run.
Both front ends read the same configuration, and the editor's settings play
the role the CLI's flags play: `lucisv.lint.select` when it is set, else
`[lint] select` from the buffer's `lucisv.toml`, else the default set — and
the same for `ignore`, decided independently. `lucisv.lint.severity.*` and
`lucisv.lint.rules.*` have no project counterpart and apply over whichever
selection stands. Project per-rule options are read by both front ends. A
project entry lucisv cannot use — an unknown rule name in `[lint]
select`/`ignore`, a rejected `[lint.<rule>]` option, an unreadable waiver
file or a directive that does not parse — fails `lucisv check` with
`<file>:<line>: <message>` and exit 2; in an editor it is dropped, written
once to the lucisv log in the same words, and everything lucisv did
understand still lints the buffer. Full rules:
`docs/features/linter-core/README.md`.
## Architecture (the ruff mapping)
The workspace mirrors ruff's crate layout — a comment-preserving parser, a
generic pretty-printing IR, language formatting rules, and a thin CLI:
The eight-crate workspace separates source syntax, reusable engines, project
inputs, and the CLI/LSP front ends. The formatter follows ruff's separation
of document layout from language rules:
| This repo | ruff equivalent | Role |
|---|---|---|
@@ -240,7 +467,20 @@ generic pretty-printing IR, language formatting rules, and a thin CLI:
| `crates/vlog_formatter/src/{doc,printer}.rs` | `ruff_formatter` | Wadler/prettier-style document IR (`Text`/`Line`/`Group`/`Indent`) + width-aware printer |
| `crates/vlog_formatter/src/format/` | `ruff_python_formatter` | Per-node formatting rules, one module per grammar domain (`item`, `module`, `instance`, `decl`, `stmt`, `expr`, `class`, `cover`, `sva`, …) |
| `crates/vlog_linter` | `ruff_linter` | Rule registry, violations, fix applicability, waivers |
| `crates/lucisv` | the `ruff` CLI | File discovery, in-place rewriting, `--check`, `check`, stdin mode |
| `crates/vlog_semantic` | — | File scopes and references, workspace index, conservative cross-file resolution |
| `crates/vlog_refactor` | — | Verified rename, references, port refactors, instantiation plans |
| `crates/lucisv_core` | — | Shared config, filelists, walks, format cache, atomic replacement |
| `crates/lucisv` | the `ruff` CLI | Parallel per-file formatting/linting, reports, stdin, in-place writes |
| `crates/lucisv_server` | — | Synchronous LSP loop, open-buffer overlays, indexing, editor capabilities |
`vlog_parser` and `lucisv_core` have no dependencies. The formatter depends
only on the parser; semantic analysis also depends only on the parser.
Linting consumes the parser, semantics and `lucisv_core` (for the one
`--exclude`-style matcher a waiver file's `--location` shares with the CLI);
refactoring consumes the parser and semantics. The CLI reaches
semantics through the linter and has no refactoring dependency. The server
composes all six libraries. See [topo.md](docs/topo.md) for the full graph,
including the linter's formatter dependency used only by tests.
Key ideas carried over from ruff/prettier:
@@ -253,8 +493,15 @@ Key ideas carried over from ruff/prettier:
lists, expressions, concatenations) is a `Group`: it renders on one line if
it fits within the line limit, otherwise it breaks one-element-per-line.
A comment inside a group forces it to break.
- **Idempotency as a hard invariant.** The test suite formats every fixture
twice and asserts a fixed point.
- **Verification on every formatting call.** The engine re-lexes input and
output and compares normalized tokens, including comments. It then parses
and formats the output again and requires a fixed point. Either check can
reject the result; the caller retains the original file. This is a lexical
safety net, not compiler elaboration or a proof of hardware equivalence.
- **Two parsing modes.** Formatting uses strict parsing. Linting and the
editor use tolerant parsing: failed elements become error leaves while
valid siblings remain available for analysis. A lexer failure is still
all-or-nothing. Neither mode performs cross-file macro expansion.
## Style
@@ -710,8 +957,11 @@ vim.lsp.enable('lucisv')
**Which files the server indexes.** A filelist if the project has one — the
`filelist` key of its `lucisv.toml`, or the editor setting `lucisv.filelist`
(a path, absolute or relative to the workspace folder) — and then exactly the
files it names. Otherwise the workspace folder, walked as the CLI walks it;
and with no folder open at all, the current file's own directory. Open buffers
files it names. Otherwise the default `lucisv.index.scope = "folder"` starts
from open-file folders, widens by `lucisv.index.scopeDepth` (default 2), and stays bounded by
the workspace roots; `"workspace"` walks the full roots. With no folder open,
the server stays in the current file's directory: depth 0 scans it flat; a
positive depth walks its descendants but never climbs to a parent. Open buffers
are always indexed on top. A filelist that cannot be read warns and falls back
to the folder walk, so the index is never silently empty.
@@ -742,11 +992,20 @@ expected; no PRs or review required.
```bash
cargo build --release # binaries at target/release/{lucisv,lucisv-server}
cargo test # unit + snapshot + idempotency tests
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
tools/guard.sh -- cargo test --workspace # unit, integration, snapshots, doc tests
```
Snapshot tests live in `crates/vlog_formatter/tests/fixtures/`; regenerate
expected outputs with `UPDATE_SNAPSHOTS=1 cargo test -p vlog_formatter`.
expected outputs only for intentional formatting changes with
`UPDATE_SNAPSHOTS=1 tools/guard.sh -- cargo test -p vlog_formatter`.
Table-driven cases live in `crates/vlog_formatter/tests/cases/`; lint cases
live in `crates/vlog_linter/tests/cases/`. All tests, fuzzers, and corpus/tree
sweeps must run through `tools/guard.sh` (8 GiB RSS / 30 minutes by default),
as required by [CLAUDE.md](CLAUDE.md). A guard kill is a finding, not a reason
to increase the limit. Documentation build instructions are in
[docs/site/README.md](docs/site/README.md).
## Install and releases
+1891 -75
View File
File diff suppressed because it is too large. Load diff
+61 -2
View File
@@ -71,6 +71,12 @@ pub struct Options {
pub select: Vec<String>,
/// `check` only: rules to drop from whatever `--select` left.
pub ignore: Vec<String>,
/// `check` only: external waiver files, relative to the current
/// directory. They *add* to whatever `[lint] waivers` in a `lucisv.toml`
/// names — a waiver file suppresses findings and can only ever suppress
/// fewer of them by being left out, so there is nothing here for a
/// command line flag to override.
pub waiver_files: Vec<String>,
/// `check` only: print the generated rule reference and exit, reading no
/// file at all.
pub rules_doc: bool,
@@ -100,6 +106,12 @@ impl Options {
if let Some(n) = self.indent.or(file.indent) {
config.indent_width = n;
}
// `[format]` has no CLI flag: these keys change how already-clean
// files look, so the project's own config is the only place that
// turns one on.
if let Some(on) = file.format_uvm_utils_indent {
config.uvm_utils_indent = on;
}
config
}
@@ -203,6 +215,9 @@ CHECK OPTIONS (`lucisv check` only):
--fix apply safe fixes and write the files back
--unsafe-fixes let --fix apply unsafe fixes too (no rule ships
one yet, so today this changes nothing)
--waiver-file <PATH> read waiver directives from this file; may be
repeated, and adds to whatever `[lint] waivers`
in a lucisv.toml already names
--rules-doc print the rule reference — every rule, what it
reports and whether it has a fix — as Markdown on
stdout and exit 0. Generated from the registry, so
@@ -215,6 +230,31 @@ CHECK OPTIONS (`lucisv check` only):
accepted in place of `lucisv:`. A waiver that suppresses nothing is
reported under the `unused-waiver` rule.
WAIVER FILES:
Findings can also be suppressed from outside the RTL, in Verible's waiver
file format — one directive per line, `#` comments and blank lines ignored:
waive --rule=<rule> every line of every file
waive --rule=<rule> --line=12 one line
waive --rule=<rule> --line=12-20 a range, both ends included
waive --rule=<rule> --location=legacy.sv the files that pattern names
`--rule` is required and names one rule (a severity word is not accepted);
`--line` is 1-based and a range includes both ends; `--location` is matched
the way an `--exclude` pattern is — `*` within one path component, a
pattern with `/` against a path suffix and one without against the file
name. Unlike Verible's, it is **not** a regular expression, and a pattern
that looks like one is an error rather than a silent mismatch.
lucisv reads `--waiver-file <PATH>` (relative to the current directory) and
every path in `waivers` under `[lint]` in a `lucisv.toml` (relative to that
file). An external waiver and an inline one are a union: a finding either
covers is suppressed, and neither is then reported as dead. A file that
does not exist, or a directive that does not parse, fails the run with
`<file>:<line>: message` and exit 2. An external waiver that suppressed
nothing anywhere in the run is reported under `unused-waiver`, at the line
of the waiver file it was written on.
IGNORE FILES:
While walking a directory, lucisv reads a `.gitignore` in every directory it
enters and skips what it names; a deeper file overrides a shallower one and
@@ -250,8 +290,11 @@ CONFIGURATION:
read by lucisv-server only — the CLI reads a filelist only when `-f` names
one, so `lucisv rtl/` always means the directory it was given). One table
is recognized, `[lint]`, with `select` and `ignore` (arrays of rule names,
`--select`/`--ignore` semantics). A command line flag overrides the file's
corresponding key; the other keys still apply.
`--select`/`--ignore` semantics) and `waivers` (an array of waiver file
paths, resolved against the config file's own directory). A command line
flag overrides the file's corresponding key; the other keys still apply —
`--waiver-file` is the exception, and adds to `waivers` rather than
replacing it.
RANGE FORMATTING:
`--lines` formats one construct at a time: an item whose lines meet a range
@@ -298,6 +341,7 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
unsafe_fixes: false,
select: Vec::new(),
ignore: Vec::new(),
waiver_files: Vec::new(),
rules_doc: false,
inputs: Vec::new(),
filelists: Vec::new(),
@@ -378,6 +422,10 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
let v = args.next().ok_or("--ignore requires a value")?;
opts.ignore.extend(split_rules(&v));
}
"--waiver-file" => {
let v = args.next().ok_or("--waiver-file requires a value")?;
opts.waiver_files.push(v);
}
"--rules-doc" => opts.rules_doc = true,
"-h" | "--help" => {
print_help();
@@ -444,6 +492,7 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
(opts.output_format != OutputFormat::Text, "--output-format"),
(!opts.select.is_empty(), "--select"),
(!opts.ignore.is_empty(), "--ignore"),
(!opts.waiver_files.is_empty(), "--waiver-file"),
(opts.rules_doc, "--rules-doc"),
];
let format_only = [
@@ -614,6 +663,16 @@ mod tests {
assert!(parse(&["--no-gitignore", "rtl"]).unwrap().no_gitignore);
}
#[test]
fn waiver_files_are_collected_in_order_and_are_lint_only() {
let opts = parse(&["check", "--waiver-file", "a.waiver", "--waiver-file", "b", "rtl"])
.expect("parsed");
assert_eq!(opts.waiver_files, vec!["a.waiver", "b"]);
assert!(parse(&["check", "rtl"]).unwrap().waiver_files.is_empty());
assert!(parse(&["check", "--waiver-file"]).is_err(), "a value is required");
assert!(parse(&["--waiver-file", "a.waiver", "rtl"]).is_err(), "not a formatter flag");
}
#[test]
fn rules_doc_is_the_one_check_that_needs_no_input() {
assert!(parse(&["check", "--rules-doc"]).unwrap().rules_doc);
+340 -53
View File
@@ -9,12 +9,16 @@ use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use lucisv_core::atomic::write_atomic;
use lucisv_core::config::FileConfig;
use rayon::prelude::*;
use vlog_formatter::fence::{self, Region};
use vlog_formatter::Config;
use vlog_linter::words;
use vlog_linter::{apply_fixes, lint, Fix, MentionOracle, ParsedSource, Rule, Violation};
use vlog_linter::{
apply_fixes, lint_with, ExternalWaivers, Fix, MentionOracle, ParsedSource, Rule, RuleOptions,
Violation, WaiverUse,
};
use vlog_parser::LineIndex;
use crate::args::{Options, OutputFormat};
@@ -31,6 +35,9 @@ pub struct Job {
path: PathBuf,
config: Config,
rules: Vec<&'static dyn Rule>,
/// What this file's `lucisv.toml` configured about each rule, validated
/// against the registry when the run was planned.
options: RuleOptions,
}
/// A whole `lucisv check` run: what to lint, and what the project says about
@@ -40,6 +47,15 @@ pub struct Plan {
/// The project's identifier census, built when at least one selected rule
/// asks for a workspace and there is more than one file to ask about.
census: Option<Census>,
/// Every external waiver file the run reads, applied to every job.
///
/// One set for the whole run rather than one per file, because a
/// `--location` pattern names files and a waiver is only *unused* when no
/// file in the run matched it — a question only the whole run can answer.
external: ExternalWaivers,
/// Every rule name any job in the run has switched on, for deciding which
/// external waivers never had a chance to fire.
enabled: Vec<&'static str>,
}
/// How many of the run's files write each identifier down.
@@ -50,6 +66,16 @@ pub struct Plan {
/// a rule asks about one name at a time and never about a file.
pub struct Census {
files: HashMap<String, u32>,
/// Module or interface name → what it declares, `None` for a unit the run
/// cannot answer for: a header carrying a compiler directive, or two
/// declarations that disagree. Empty when no enabled rule asked for it —
/// building it costs a parse of every file in the run.
interfaces: HashMap<String, Option<vlog_linter::ModuleInterface>>,
/// Package name → the names it exports, `None` for a package the run
/// cannot answer for: one declared twice, or one re-exporting from
/// another package (only a whole-project index settles that). Empty
/// unless `unused-import` is enabled.
packages: HashMap<String, Option<Vec<String>>>,
}
impl Census {
@@ -58,27 +84,89 @@ impl Census {
/// A file that cannot be read or does not lex contributes nothing, which
/// is the same all-or-nothing rule the rest of the run gives it: the
/// file's own check reports the error.
fn of(jobs: &[Job]) -> Census {
let per_file: Vec<Vec<String>> = jobs
///
/// `interfaces` says whether the run also needs each unit's ports and
/// parameters (`unknown-port`, `unknown-parameter`). It costs a **parse**
/// of every file on top of the lex the word census already pays for, so
/// it is built only when some enabled rule asks — measured on opentitan
/// `hw/` in `docs/features/linter-expansion-1/README.md`.
fn of(jobs: &[Job], interfaces: bool, packages: bool) -> Census {
type PerFile = (
Vec<String>,
Vec<(String, Option<vlog_linter::ModuleInterface>)>,
Vec<(String, Option<Vec<String>>)>,
);
let per_file: Vec<PerFile> = jobs
.par_iter()
.map(|job| match std::fs::read_to_string(&job.path) {
Ok(src) => words::harvest_text(&src),
Err(_) => Vec::new(),
.map(|job| {
let Ok(src) = std::fs::read_to_string(&job.path) else {
return (Vec::new(), Vec::new(), Vec::new());
};
let exports = match packages {
true => vlog_linter::package_exports(&job.path, &src),
false => Vec::new(),
};
if !interfaces {
return (words::harvest_text(&src), Vec::new(), exports);
}
// One lex for both halves: the parse is what the interface
// table needs, and its tokens are the word census's.
let parsed = ParsedSource::parse(&src);
(
words::harvest(parsed.tokens()),
vlog_linter::module_interfaces(parsed.file()),
exports,
)
})
.collect();
let mut files: HashMap<String, u32> = HashMap::new();
for words in per_file {
let mut units: HashMap<String, Option<vlog_linter::ModuleInterface>> = HashMap::new();
let mut exported: HashMap<String, Option<Vec<String>>> = HashMap::new();
for (words, declared, exports) in per_file {
for word in words {
*files.entry(word).or_default() += 1;
}
// A package name the run declares twice is a package the run
// cannot answer for, whatever the two say — the same rule the
// workspace index applies, where two `units` is `Ambiguous`.
for (name, names) in exports {
exported.entry(name).and_modify(|held| *held = None).or_insert(names);
}
for (name, interface) in declared {
// Two declarations of one name answer only when they agree;
// anything else is a question the run cannot settle.
units
.entry(name)
.and_modify(|held| {
if *held != interface {
*held = None;
}
})
.or_insert(interface);
}
}
Census { files }
Census { files, interfaces: units, packages: exported }
}
/// How many files in the run write `name` down.
fn count(&self, name: &str) -> u32 {
self.files.get(name).copied().unwrap_or(0)
}
/// What the run says `name` declares, or `None` when it cannot say.
fn interface(&self, name: &str) -> Option<vlog_linter::ModuleInterface> {
self.interfaces.get(name)?.clone()
}
/// What the run says the package `name` exports.
fn package(&self, name: &str) -> vlog_linter::Exports {
match self.packages.get(name) {
Some(Some(names)) => vlog_linter::Exports::Known(names.clone()),
Some(None) => vlog_linter::Exports::Ambiguous,
None => vlog_linter::Exports::Unknown,
}
}
}
/// One file's view of the census: everything the project says, minus what
@@ -96,6 +184,20 @@ impl MentionOracle for Elsewhere<'_> {
let mine = u32::from(self.own.binary_search_by(|w| w.as_str().cmp(name)).is_ok());
self.census.count(name) > mine
}
/// The run's interface table, which covers **every** file including this
/// one: a module is instantiated as often in the file that declares it as
/// anywhere else, and there is nothing to subtract here.
fn module_interface(&self, name: &str) -> Option<vlog_linter::ModuleInterface> {
self.census.interface(name)
}
/// The run's package table, whole-run for the same reason the interface
/// table is: a package is imported as often by the file that declares it
/// as by any other, and there is nothing here to subtract.
fn package_exports(&self, name: &str) -> vlog_linter::Exports {
self.census.package(name)
}
}
/// Resolve the run: the rules for each file, and whether a census is owed.
@@ -111,17 +213,118 @@ impl MentionOracle for Elsewhere<'_> {
/// already says about itself.
pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Result<Plan, String> {
let workspace = gathered.len() > 1;
let external = external_waivers(opts, gathered.iter().map(|(_, _, file)| file))?;
let mut jobs = Vec::with_capacity(gathered.len());
for (path, config, file_config) in gathered {
let select = pick(&opts.select, file_config.lint_select.as_deref());
let ignore = pick(&opts.ignore, file_config.lint_ignore.as_deref());
let rules = vlog_linter::select_rules(select, ignore, workspace)
.map_err(|e| format!("{}: {e}", path.display()))?;
jobs.push(Job { path, config, rules });
let options = rule_options(&file_config)?;
jobs.push(Job { path, config, rules, options });
}
let wanted = jobs.iter().any(|job| job.rules.iter().any(|rule| rule.needs_workspace()));
let census = (workspace && wanted).then(|| Census::of(&jobs));
Ok(Plan { jobs, census })
let asks = |wants: fn(&'static dyn Rule) -> bool| {
jobs.iter().any(|job| job.rules.iter().any(|rule| wants(*rule)))
};
let wanted = asks(|rule| rule.needs_workspace()) || asks(reads_packages);
let interfaces = asks(reads_interfaces);
let packages = asks(reads_packages);
let census = (workspace && wanted)
.then(|| Census::of(&jobs, workspace && interfaces, workspace && packages));
let mut enabled: Vec<&'static str> =
jobs.iter().flat_map(|job| job.rules.iter().map(|rule| rule.name())).collect();
enabled.sort_unstable();
enabled.dedup();
Ok(Plan { jobs, census, external, enabled })
}
/// The run's external waiver files, read once each: `--waiver-file` in flag
/// order, then every `[lint] waivers` entry of a config file governing an
/// input.
///
/// The two **add up** rather than override: a waiver file only ever suppresses
/// findings, so there is nothing for a command line to take back. A file named
/// twice over — the flag and a `lucisv.toml`, or one `lucisv.toml` governing
/// five hundred files — is read once, or its directives would each be reported
/// unused as many times as the file was read.
///
/// A file that cannot be read, or a directive that does not parse, fails the
/// run naming the file and the line, exactly as a bad `[lint.<rule>]` entry
/// does and for the same reason: a user wrote it and is watching.
pub fn external_waivers<'a>(
opts: &Options,
configs: impl Iterator<Item = &'a FileConfig>,
) -> Result<ExternalWaivers, String> {
let mut paths: Vec<PathBuf> = opts.waiver_files.iter().map(PathBuf::from).collect();
for config in configs {
for path in config.lint_waivers.iter().flatten() {
paths.push(path.clone());
}
}
let mut read: Vec<PathBuf> = Vec::new();
let mut waivers = ExternalWaivers::default();
for path in paths {
// Compared canonically, because the flag's path is relative to the
// working directory and a `lucisv.toml`'s is absolute: the same file
// named both ways is still one file, and reading it twice would report
// each of its dead directives twice. Only the *comparison* is
// canonical — the path a diagnostic names stays the one written.
let key = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
if read.contains(&key) {
continue;
}
let (file, problems) = ExternalWaivers::read(&path)?;
if let Some(problem) = problems.first() {
return Err(problem.clone());
}
waivers.absorb(file);
read.push(key);
}
Ok(waivers)
}
/// The `[lint.<rule>]` entries of one file's config, resolved against the
/// registry.
///
/// The names and the values are checked **here**, where the registry is, and
/// the first bad entry fails the run naming the config file and the line it
/// was written on — the same treatment a bad `[lint] select` name gets, and
/// for the same reason: a user typed it and is watching.
pub fn rule_options(file_config: &FileConfig) -> Result<RuleOptions, String> {
let mut options = RuleOptions::new();
for entry in &file_config.lint_options {
options.set_raw(&entry.rule, &entry.key, &entry.raw).map_err(|e| {
let file = file_config
.source
.as_ref()
.map_or_else(|| "lucisv.toml".to_string(), |path| path.display().to_string());
// The rule is named as well as the option: the table header two
// lines up says which rule it is, and an error a user reads out
// of a CI log has no table header beside it.
format!("{file}:{}: rule `{}` {e}", entry.line, entry.rule)
})?;
}
Ok(options)
}
/// Whether this rule reads the census's **interface** half, which costs a
/// parse of every file in the run rather than a lex.
///
/// By name, because the alternative is a fourth boolean on the `Rule` trait
/// for two rules: `Rule::needs_workspace` already says "this rule asks the
/// project something", and which *question* it asks is between the rule and
/// the oracle. A name that is not in the registry cannot reach here — the
/// rules are `&'static dyn Rule` values from that registry — and a rule added
/// to the pair without being added here answers `None` and goes quiet, which
/// is the safe direction.
fn reads_interfaces(rule: &'static dyn Rule) -> bool {
matches!(rule.name(), "unknown-port" | "unknown-parameter")
}
/// The rule that reads the package table, which costs an index of every file
/// in the run on top of the word census.
fn reads_packages(rule: &'static dyn Rule) -> bool {
rule.name() == "unused-import"
}
/// The command line's list when it said anything, else the config file's.
@@ -142,20 +345,51 @@ struct Report {
violations: Vec<Violation>,
/// Violations whose fix was applied and written back.
fixed: usize,
/// Which of the run's external waivers suppressed something in this file.
/// Merged across every file before the dead ones are reported.
used: WaiverUse,
/// Set when the file could not be fully checked: unreadable, unwritable,
/// or — because the lexer is all-or-nothing — unlexable, in which case
/// only the text-level rules saw it.
error: Option<String>,
}
/// Everything one file's lint pass reads besides the file itself.
///
/// One value rather than six parameters: every function below the driver
/// needs the same set, and the `--fix` loop passes it down another level
/// again.
struct Pass<'a> {
config: &'a Config,
rules: &'a [&'static dyn Rule],
options: &'a RuleOptions,
census: Option<&'a Census>,
/// The run's external waiver files. Empty unless `--waiver-file` or a
/// `[lint] waivers` named one, and then costing nothing.
external: &'a ExternalWaivers,
}
/// Lints every gathered file and reports. Exit 1 if anything is left over,
/// 2 if a file could not be read, written, or lexed.
pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
let mut reports: Vec<Report> = plan
.jobs
.par_iter()
.map(|job| check_one(&job.path, &job.config, opts, &job.rules, plan.census.as_ref()))
.map(|job| {
let pass = Pass {
config: &job.config,
rules: &job.rules,
options: &job.options,
census: plan.census.as_ref(),
external: &plan.external,
};
check_one(&job.path, opts, &pass)
})
.collect();
// The dead external waivers are found once every file has been linted,
// and reported against the waiver file, which then sorts in among the
// sources like any other path.
reports.extend(dead_waivers(&plan.external, &reports, &plan.enabled));
// Diagnostics are printed sorted by path, then by position within the
// file (`lint` already sorts those), so a run over a directory reads
// top to bottom whatever order the walk or the worker pool produced.
@@ -163,6 +397,37 @@ pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
finish(opts, reports)
}
/// The `unused-waiver` reports for external waivers no file in the run used.
///
/// **After the whole run**, which is the whole reason this is the CLI's job
/// and not the linter's: a `--location` pattern may match a file the run has
/// not reached yet, so a waiver is only dead once every file has been asked.
fn dead_waivers(
external: &ExternalWaivers,
reports: &[Report],
enabled: &[&'static str],
) -> Vec<Report> {
if external.is_empty() {
return Vec::new();
}
let mut used = WaiverUse::default();
for report in reports {
used.merge(&report.used);
}
external
.unused(&used, enabled)
.into_iter()
.map(|dead| Report {
path: dead.path.display().to_string(),
index: LineIndex::new(&dead.text),
violations: dead.violations,
fixed: 0,
used: WaiverUse::default(),
error: None,
})
.collect()
}
/// Lints a buffer piped in on stdin. `--stdin-filename` names it, and is
/// what the rules that need a file name see.
pub fn check_stdin(
@@ -170,31 +435,35 @@ pub fn check_stdin(
src: &str,
config: &Config,
rules: &[&'static dyn Rule],
options: &RuleOptions,
external: &ExternalWaivers,
) -> ExitCode {
let name = opts.stdin_filename.clone().unwrap_or_else(|| "<stdin>".to_string());
let path = opts.stdin_filename.as_ref().map(PathBuf::from);
let (violations, lex_error) = run_rules(src, path, config, rules, None);
let pass = Pass { config, rules, options, census: None, external };
let (violations, used, lex_error) = run_rules(src, path, &pass);
// Nothing is ever written back for stdin, so `--fix` has nothing to do
// here; the violations are reported as they are.
let error = lex_error.map(|e| format!("{name}: {e}"));
let report = Report { path: name, index: LineIndex::new(src), violations, fixed: 0, error };
finish(opts, vec![report])
let report =
Report { path: name, index: LineIndex::new(src), violations, fixed: 0, used, error };
// One buffer is a whole run too, so a waiver that covered nothing in it is
// as dead as one that covered nothing in a directory.
let names: Vec<&'static str> = rules.iter().map(|rule| rule.name()).collect();
let mut reports = vec![report];
reports.extend(dead_waivers(external, &reports, &names));
finish(opts, reports)
}
/// Lints one file, optionally fixing it, and never panics out of its worker.
fn check_one(
file: &Path,
config: &Config,
opts: &Options,
rules: &[&'static dyn Rule],
census: Option<&Census>,
) -> Report {
fn check_one(file: &Path, opts: &Options, pass: &Pass) -> Report {
let path = file.display().to_string();
let failed = |error: String| Report {
path: path.clone(),
index: LineIndex::new(""),
violations: Vec::new(),
fixed: 0,
used: WaiverUse::default(),
error: Some(error),
};
@@ -204,20 +473,19 @@ fn check_one(
};
let outcome = crate::catch_panic(|| {
if opts.fix {
fix_source(&src, file, config, opts, rules, census)
fix_source(&src, file, opts, pass)
} else {
let (violations, lex_error) =
run_rules(&src, Some(file.to_path_buf()), config, rules, census);
(violations, None, 0, lex_error)
let (violations, used, lex_error) = run_rules(&src, Some(file.to_path_buf()), pass);
(violations, used, None, 0, lex_error)
}
});
let (violations, rewritten, fixed, lex_error) = match outcome {
let (violations, used, rewritten, fixed, lex_error) = match outcome {
Ok(outcome) => outcome,
Err(msg) => return failed(format!("{path}: panicked while linting: {msg}")),
};
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}"));
}
}
@@ -226,20 +494,20 @@ fn check_one(
// so the file must not pass as checked. It is an error (exit 2), exactly
// as `lucisv format` treats the same file.
let error = lex_error.map(|e| format!("{path}: {e}"));
Report { path, index, violations, fixed, error }
Report { path, index, violations, fixed, used, error }
}
/// Runs the rules over one text. The second half of the answer is the lex
/// error when the text does not lex — rendered `line:col: message`, ready
/// for a path prefix — because a file with no tokens was only text-linted
/// and must be reported as an error, not passed off as clean.
/// Runs the rules over one text, reporting which external waivers fired. The
/// last part of the answer is the lex error when the text does not lex —
/// rendered `line:col: message`, ready for a path prefix — because a file with
/// no tokens was only text-linted and must be reported as an error, not passed
/// off as clean.
fn run_rules(
src: &str,
path: Option<PathBuf>,
config: &Config,
rules: &[&'static dyn Rule],
census: Option<&Census>,
) -> (Vec<Violation>, Option<String>) {
pass: &Pass,
) -> (Vec<Violation>, WaiverUse, Option<String>) {
let Pass { config, rules, options, census, external } = *pass;
// One parse per file (TODO §4): the products are built here, once, and
// lent to the context. Under `--fix` each *round* re-enters through this
// function with rewritten text — that re-parse is inherent (the old
@@ -252,13 +520,19 @@ fn run_rules(
// census so a signal never counts as mentioned by its own declaration.
let elsewhere = census.map(|census| Elsewhere { census, own: words::harvest(parsed.tokens()) });
// The indent width the formatter would use is also the width a tab
// expands to, so `--indent 4` fixes tabs into four spaces.
let ctx = parsed.context(path).with_tab_width(config.indent_width);
// expands to, so `--indent 4` fixes tabs into four spaces — and the width
// it would wrap to is the width `line-length` holds the file to.
let ctx = parsed
.context(path)
.with_tab_width(config.indent_width)
.with_line_length(config.max_width)
.with_options(options);
let ctx = match &elsewhere {
Some(elsewhere) => ctx.with_oracle(elsewhere),
None => ctx,
};
(lint(&ctx, rules), lex_error)
let (violations, used) = lint_with(&ctx, rules, external);
(violations, used, lex_error)
}
/// The violations whose fix may be applied: everything except a fix that
@@ -297,15 +571,15 @@ fn touches_fence(fix: &Fix, regions: &[Region]) -> bool {
fn fix_source(
src: &str,
file: &Path,
config: &Config,
opts: &Options,
rules: &[&'static dyn Rule],
census: Option<&Census>,
) -> (Vec<Violation>, Option<String>, usize, Option<String>) {
pass: &Pass,
) -> (Vec<Violation>, WaiverUse, Option<String>, usize, Option<String>) {
let mut text = src.to_string();
let mut fixed = 0;
let (mut violations, mut lex_error) =
run_rules(&text, Some(file.to_path_buf()), config, rules, census);
let mut used = WaiverUse::default();
let (mut violations, mut round_used, mut lex_error) =
run_rules(&text, Some(file.to_path_buf()), pass);
used.merge(&round_used);
for _ in 0..MAX_FIX_ROUNDS {
let round =
apply_fixes(&text, &fixable_outside_fences(&text, &violations), opts.unsafe_fixes);
@@ -314,10 +588,14 @@ fn fix_source(
}
fixed += round.applied;
text = round.output;
(violations, lex_error) = run_rules(&text, Some(file.to_path_buf()), config, rules, census);
(violations, round_used, lex_error) = run_rules(&text, Some(file.to_path_buf()), pass);
// A waiver that covered a finding in an earlier round did its job even
// though the fix then removed the finding, so usage accumulates over
// the rounds rather than being the last round's.
used.merge(&round_used);
}
let rewritten = (text != src).then_some(text);
(violations, rewritten, fixed, lex_error)
(violations, used, rewritten, fixed, lex_error)
}
/// Prints the run and turns it into an exit code.
@@ -348,15 +626,23 @@ fn finish(opts: &Options, reports: Vec<Report>) -> ExitCode {
}
}
/// Verible's diagnostic line: `FILE:LINE:COL: message [rule-name]`.
/// Verible's diagnostic line with the severity word in front of the message:
/// `FILE:LINE:COL: error|warning|style: message [rule-name]`.
///
/// The word sits where a compiler puts it, so the line greps and reads the way
/// every other tool's does, and `grep ': error:'` is the whole of "show me
/// what would not compile".
fn print_text(reports: &[Report]) {
let mut out = String::new();
for report in reports {
for violation in &report.violations {
let (line, col) = position(report, violation);
out.push_str(&format!(
"{}:{line}:{col}: {} [{}]\n",
report.path, violation.message, violation.rule
"{}:{line}:{col}: {}: {} [{}]\n",
report.path,
violation.severity.as_str(),
violation.message,
violation.rule
));
}
}
@@ -372,12 +658,13 @@ fn print_json(reports: &[Report]) {
let (line, col) = position(report, violation);
let (end_line, end_col) = end_position(report, violation);
items.push(format!(
"{{\"filename\":{},\"rule\":{},\"message\":{},\
"{{\"filename\":{},\"rule\":{},\"severity\":{},\"message\":{},\
\"location\":{{\"line\":{line},\"column\":{col}}},\
\"end_location\":{{\"line\":{end_line},\"column\":{end_col}}},\
\"range\":{{\"start\":{},\"end\":{}}},\"fix\":{}}}",
quote(&report.path),
quote(violation.rule),
quote(violation.severity.as_str()),
quote(&violation.message),
violation.span.start,
violation.span.end,
+80 -11
View File
@@ -27,6 +27,7 @@ use std::process::ExitCode;
use rayon::prelude::*;
use args::{Command, Options};
use lucisv_core::atomic::write_atomic;
use lucisv_core::cache::{content_hash, Cache, Entry};
use lucisv_core::config::{Discovery, FileConfig};
use lucisv_core::filelist;
@@ -98,7 +99,7 @@ fn run_check(opts: &Options) -> ExitCode {
return ExitCode::from(2);
}
if opts.is_stdin() {
let config = match stdin_config(opts) {
let (config, file_config) = match stdin_config(opts) {
Ok(c) => c,
Err(e) => {
eprintln!("error: {e}");
@@ -120,7 +121,24 @@ fn run_check(opts: &Options) -> ExitCode {
return ExitCode::from(2);
}
};
return lint::check_stdin(opts, &src, &config, &rules);
let options = match lint::rule_options(&file_config) {
Ok(options) => options,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
// A stdin buffer has one config file too — the one governing
// `--stdin-filename`, or the working directory's — so `[lint] waivers`
// reaches it exactly as `[lint] select` does.
let external = match lint::external_waivers(opts, std::iter::once(&file_config)) {
Ok(external) => external,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
return lint::check_stdin(opts, &src, &config, &rules, &options, &external);
}
let jobs = match gather(opts).and_then(|jobs| build_pool(opts).map(|()| jobs)) {
Ok(jobs) => jobs,
@@ -140,7 +158,7 @@ fn run_check(opts: &Options) -> ExitCode {
fn run_stdin(opts: &Options) -> ExitCode {
let name = opts.stdin_filename.as_deref().unwrap_or("<stdin>");
let config = match stdin_config(opts) {
let (config, _file_config) = match stdin_config(opts) {
Ok(c) => c,
Err(e) => {
eprintln!("error: {e}");
@@ -299,7 +317,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
@@ -348,7 +366,12 @@ fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config, FileConfig)>, String>
return Err(format!("--lines needs a file, not a directory: {input}"));
}
let exclude = opts.exclude_with(&discovery.for_input(Path::new(input))?);
collect_files(input, &exclude, !opts.no_gitignore, &mut files)?;
// The walk's own warnings — an unreadable directory, a source file
// that is only a broken link — go to stderr as they are found, before
// the report and exactly as a filelist's do. A warning is not a
// failure: the exit code is the formatting's alone.
let mut warn = |w| eprintln!("warning: {w}");
collect_files(input, &exclude, !opts.no_gitignore, &mut files, &mut warn)?;
}
// Filelists come after the command line's own inputs, in flag order: they
// add files, they never replace or reorder what was named directly.
@@ -397,13 +420,25 @@ fn filelist_files(opts: &Options) -> Result<Vec<PathBuf>, String> {
fn dedup(files: Vec<PathBuf>) -> Vec<PathBuf> {
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
let mut seen = HashSet::new();
files.into_iter().filter(|file| seen.insert(absolute(&cwd, file))).collect()
files.into_iter().filter(|file| seen.insert(identity(&cwd, file))).collect()
}
/// The key two spellings of one file share: the file's canonical path when it
/// is there, and the lexical fold when it is not.
///
/// Canonical means symlinks resolved, which is the only way to see that
/// `b.sv -> a.sv` is the file `a.sv` already named — two rayon workers on one
/// target otherwise, each rewriting what the other just wrote. A path with no
/// file behind it has no canonical form, and the lexical fold is then the
/// best two names for it can be compared by. Neither is ever the path lucisv
/// reports: that stays the first spelling seen.
fn identity(cwd: &Path, path: &Path) -> PathBuf {
std::fs::canonicalize(path).unwrap_or_else(|_| absolute(cwd, path))
}
/// `path` folded to the absolute, `.`/`..`-free spelling two names for one
/// file share. Lexical, like `lucisv_core`'s own normalization: symlinks are
/// deliberately left unresolved, so this is only ever a dedup key and never
/// the path lucisv reports.
/// file share. Purely lexical, like `lucisv_core`'s own normalization — it
/// answers for paths that do not exist, where there is nothing to resolve.
fn absolute(cwd: &Path, path: &Path) -> PathBuf {
let joined = if path.is_absolute() { path.to_path_buf() } else { cwd.join(path) };
let mut out = PathBuf::new();
@@ -421,13 +456,16 @@ fn absolute(cwd: &Path, path: &Path) -> PathBuf {
/// The settings for a buffer piped in on stdin: discovery anchors on
/// `--stdin-filename`'s directory when given, else on the current one.
fn stdin_config(opts: &Options) -> Result<Config, String> {
/// The formatter config a stdin buffer is served with, and the `lucisv.toml`
/// it came from — the linter needs the file's own `[lint.<rule>]` entries,
/// which the resolved `Config` does not carry.
fn stdin_config(opts: &Options) -> Result<(Config, FileConfig), String> {
let mut discovery = Discovery::new(!opts.no_config);
let file = match opts.stdin_filename.as_deref() {
Some(name) => discovery.for_file(Path::new(name))?,
None => discovery.for_dir(Path::new("."))?,
};
Ok(opts.config_with(&file))
Ok((opts.config_with(&file), file))
}
fn report(opts: &Options, changed: usize, unchanged: usize, cached: usize, errors: usize) {
@@ -581,6 +619,37 @@ mod tests {
assert_eq!(dedup(files), [cwd.join("rtl/a.sv")]);
}
#[cfg(unix)]
#[test]
fn dedup_folds_a_symlink_onto_the_file_it_points_at() {
// A directory walk lists `b.sv` as a file of its own; lexically the
// two names share nothing, and two workers would rewrite one file.
let dir = std::env::temp_dir().join(format!("lucisv-dedup-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
let real = dir.join("a.sv");
let link = dir.join("b.sv");
std::fs::write(&real, "module m;\nendmodule\n").expect("seed");
std::os::unix::fs::symlink(&real, &link).expect("symlink");
assert_eq!(dedup(vec![real.clone(), link.clone()]), std::slice::from_ref(&real));
// Whichever spelling comes first is the one kept and reported.
assert_eq!(dedup(vec![link.clone(), real.clone()]), std::slice::from_ref(&link));
// And a `..` detour through the same link is still the same file.
std::fs::create_dir(dir.join("sub")).expect("sub dir");
let detour = dir.join("sub/../b.sv");
assert_eq!(dedup(vec![real.clone(), detour]), std::slice::from_ref(&real));
// A file that is not there has no canonical path: the key is lexical,
// which still folds `.` and `..`, and two missing files stay two.
let gone = dir.join("gone.sv");
let same = dir.join("./sub/../gone.sv");
let other = dir.join("other.sv");
assert_eq!(dedup(vec![gone.clone(), same, other.clone()]), [gone, other]);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn format_contained_reports_parse_errors() {
let err = format_contained("module", &Config::default(), None).unwrap_err();
+319 -8
View File
@@ -136,6 +136,57 @@ fn formats_files_in_place() {
assert!(stderr(&out).contains("2 files left unchanged"), "{}", stderr(&out));
}
/// A directory walk lists a symlink as a file of its own, so `b.sv -> a.sv`
/// used to put two workers on one file: two report lines for one file, and
/// two writers racing to replace it. It is one file now, named once.
#[cfg(unix)]
#[test]
fn a_symlink_and_its_target_are_one_file() {
let dir = TempDir::new("alias");
dir.write("a.sv", UNFORMATTED);
std::os::unix::fs::symlink(dir.path.join("a.sv"), dir.path.join("b.sv")).expect("symlink");
let out = run(&["--check", &dir.root()]);
assert_eq!(code(&out), 1, "{}", stderr(&out));
let reported = stdout(&out);
let named: Vec<&str> = reported.lines().filter(|l| l.contains("would reformat")).collect();
assert_eq!(named.len(), 1, "one file, one line: {named:?}");
assert!(named[0].ends_with("a.sv"), "the first spelling walked is the one reported: {named:?}");
assert!(stderr(&out).contains("1 file would be reformatted"), "{}", stderr(&out));
let out = run(&[&dir.root()]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(stderr(&out).contains("1 file reformatted"), "{}", stderr(&out));
assert_eq!(dir.read("a.sv"), FORMATTED);
assert_eq!(dir.read("b.sv"), FORMATTED, "and the link still reaches it");
assert!(
std::fs::symlink_metadata(dir.path.join("b.sv")).expect("stat").file_type().is_symlink(),
"the link was not replaced by a copy"
);
}
/// A directory that links back into itself. Before the walk kept a visited
/// set (`docs/features/walk-cycles/README.md`) this run recursed until the
/// OS refused the path; now each directory is entered once, so each file is
/// named once — under the first spelling that reaches it.
#[cfg(unix)]
#[test]
fn a_symlink_cycle_terminates_and_names_each_file_once() {
let dir = TempDir::new("cycle");
dir.write("rtl/a.sv", UNFORMATTED);
dir.write("rtl/sub/b.sv", UNFORMATTED);
// `rtl/self` is `rtl` itself; `rtl/sub/up` is `rtl` from one level down.
std::os::unix::fs::symlink("../rtl", dir.path.join("rtl/self")).expect("symlink");
std::os::unix::fs::symlink("..", dir.path.join("rtl/sub/up")).expect("symlink");
let out = run(&["--check", &dir.root()]);
assert_eq!(code(&out), 1, "{}", stderr(&out));
let reported = stdout(&out);
let named: Vec<&str> = reported.lines().filter(|l| l.contains("would reformat")).collect();
assert_eq!(named.len(), 2, "two files, two lines: {named:?}");
assert!(stderr(&out).contains("2 files would be reformatted"), "{}", stderr(&out));
}
#[test]
fn check_reports_without_writing() {
let dir = TempDir::new("check");
@@ -753,7 +804,9 @@ fn check_reports_violations_and_exits_1() {
let out = run(&["check", &path]);
assert_eq!(code(&out), 1, "violations must exit 1: {}", stderr(&out));
let text = stdout(&out);
assert!(text.contains(&format!("{path}:2:1: tab character")), "{text}");
// `FILE:LINE:COL: severity: message [rule]` — the severity word is part
// of the line since §33.0, and both of these are style findings.
assert!(text.contains(&format!("{path}:2:1: style: tab character")), "{text}");
assert!(text.contains("[no-tabs]"), "{text}");
assert!(text.contains("[module-filename]"), "{text}");
assert!(stderr(&out).contains("found 2 violations"), "{}", stderr(&out));
@@ -797,6 +850,7 @@ fn check_json_is_one_array_with_positions_and_fixes() {
assert!(text.starts_with('['), "{text}");
assert!(text.trim_end().ends_with(']'), "{text}");
assert_eq!(text.matches("\"rule\":\"no-tabs\"").count(), 1, "{text}");
assert!(text.contains("\"severity\":\"style\""), "{text}");
assert!(text.contains("\"location\":{\"line\":2,\"column\":1}"), "{text}");
assert!(text.contains("\"applicability\":\"safe\""), "{text}");
assert!(text.contains("\"content\":\" \""), "{text}");
@@ -895,6 +949,30 @@ fn check_select_and_ignore_pick_the_rule_set() {
assert!(stderr(&out).contains("unknown rule"), "{}", stderr(&out));
}
/// A severity word stands for its whole class wherever a rule name fits —
/// §33.0's headline for the command line.
#[test]
fn check_select_and_ignore_accept_a_severity_word() {
let dir = TempDir::new("check-severity");
// `reg` is an error-class finding, the tab and the name are style ones.
let path = dir.write("bar.sv", "module foo;\n\treg a;\nendmodule\n");
let out = run(&["check", "--select", "error", &path]);
assert_eq!(code(&out), 1, "{}", stdout(&out));
let text = stdout(&out);
assert_eq!(text.lines().count(), 1, "{text}");
assert!(text.contains(": error: "), "{text}");
assert!(text.contains("[wire-reg-mixup]"), "{text}");
let out = run(&["check", "--ignore", "style", &path]);
assert_eq!(stdout(&out).lines().count(), 1, "{}", stdout(&out));
assert!(stdout(&out).contains("[wire-reg-mixup]"), "{}", stdout(&out));
// Ignoring every class leaves nothing to report.
let out = run(&["check", "--ignore", "error,warning,style", &path]);
assert_eq!(code(&out), 0, "{}", stdout(&out));
}
#[test]
fn check_honors_inline_waivers_and_reports_dead_ones() {
let dir = TempDir::new("check-waive");
@@ -908,6 +986,89 @@ fn check_honors_inline_waivers_and_reports_dead_ones() {
assert!(stdout(&out).contains("[unused-waiver]"), "{}", stdout(&out));
}
/// Two tabbed lines, one of which a waiver file's `--line` covers.
const TABBED: &str = "module foo;\n\twire a;\n\twire b;\nendmodule\n";
/// `--waiver-file`: the suppression, the flag repeated, and the dead directive
/// reported at the waiver file's own line. TODO §39.
#[test]
fn check_reads_external_waiver_files() {
let dir = TempDir::new("check-waiver-file");
let path = dir.write("foo.sv", TABBED);
let one = dir.write("one.waiver", "# just line 2\nwaive --rule=no-tabs --line=2\n");
let out = run(&["check", "--waiver-file", &one, &path]);
assert_eq!(code(&out), 1, "{}", stdout(&out));
assert_eq!(stdout(&out).lines().count(), 1, "one tab left: {}", stdout(&out));
assert!(stdout(&out).contains("foo.sv:3:1"), "{}", stdout(&out));
// A second file adds to the first rather than replacing it, and both are
// then used, so neither is reported.
let two = dir.write("two.waiver", "waive --rule=no-tabs --line=3 --location=foo.sv\n");
let out = run(&["check", "--waiver-file", &one, "--waiver-file", &two, &path]);
assert_eq!(code(&out), 0, "{}", stdout(&out));
// A directive that covered nothing is reported against the waiver file.
let dead = dir.write("dead.waiver", "waive --rule=no-tabs --location=elsewhere.sv\n");
let out = run(&["check", "--waiver-file", &dead, &path]);
assert_eq!(code(&out), 1);
let text = stdout(&out);
assert!(text.contains("dead.waiver:1:1: style: unused waiver for `no-tabs`"), "{text}");
assert!(text.contains("[unused-waiver]"), "{text}");
}
/// The `[lint] waivers` key, and that `--waiver-file` adds to it. TODO §39.
#[test]
fn check_reads_the_waiver_files_a_config_file_names() {
let dir = TempDir::new("check-waiver-toml");
let path = dir.write("rtl/foo.sv", TABBED);
dir.write("lucisv.toml", "[lint]\nwaivers = [ \"project.waiver\" ]\n");
dir.write("project.waiver", "waive --rule=no-tabs --line=2\n");
// Relative to the config file, not to the working directory.
let out = run_raw(&["check", "--no-cache", &path]);
assert_eq!(code(&out), 1, "{}", stdout(&out));
assert!(stdout(&out).contains("foo.sv:3:1"), "only line 3 survives: {}", stdout(&out));
let extra = dir.write("extra.waiver", "waive --rule=no-tabs --line=3\n");
let out = run_raw(&["check", "--no-cache", "--waiver-file", &extra, &path]);
assert_eq!(code(&out), 0, "the two lists add up: {}", stdout(&out));
// `--no-config` drops the config file's list with everything else in it.
let out = run_raw(&["check", "--no-cache", "--no-config", &path]);
assert_eq!(code(&out), 1);
assert_eq!(stdout(&out).lines().count(), 2, "both tabs are back: {}", stdout(&out));
}
/// A waiver file that cannot be read, or that has a line that does not parse,
/// fails the run with `<file>:<line>: message` and exit 2. TODO §39.
#[test]
fn a_broken_waiver_file_fails_the_run() {
let dir = TempDir::new("check-waiver-bad");
let path = dir.write("foo.sv", TABBED);
let out = run(&["check", "--waiver-file", &dir.write("x.waiver", "hush\n"), &path]);
assert_eq!(code(&out), 2, "{}", stderr(&out));
assert!(stderr(&out).contains("x.waiver:1: expected a `waive` directive"), "{}", stderr(&out));
let bad = dir.write("y.waiver", "# fine\nwaive --rule=no-such-rule\n");
let out = run(&["check", "--waiver-file", &bad, &path]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("y.waiver:2: unknown rule"), "{}", stderr(&out));
let regexy = dir.write("z.waiver", "waive --rule=no-tabs --location=.*foo.sv\n");
let out = run(&["check", "--waiver-file", &regexy, &path]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("looks like a regular expression"), "{}", stderr(&out));
let out = run(&[
"check",
"--waiver-file",
&dir.path.join("gone.waiver").display().to_string(),
&path,
]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("gone.waiver:"), "{}", stderr(&out));
}
#[test]
fn check_reads_stdin_and_names_it() {
let out = run_with_stdin(&["check", "--stdin-filename", "rtl/z.sv", "-"], LINTY);
@@ -1836,16 +1997,81 @@ fn an_unknown_rule_in_the_lint_table_is_an_error() {
assert_eq!(code(&out), 2);
}
/// Per-rule tables are named rather than silently ignored, so a user who
/// writes one finds out it does nothing yet.
/// A `[lint.<rule>]` table configures that rule, and the verdict changes
/// with it — §34.0's headline claim, end to end through the real binary.
#[test]
fn a_per_rule_lint_table_is_refused_by_name() {
fn a_per_rule_lint_table_changes_the_verdict() {
let dir = TempDir::new("lint-per-rule");
dir.write("dut.sv", DUT);
dir.write("lucisv.toml", "[lint.unused-signal]\nignore = \"tmp_*\"\n");
let wide = format!("module m;\n wire {};\nendmodule\n", "a".repeat(110));
dir.write("m.sv", &wide);
let out = run(&["check", &dir.root()]);
assert!(stderr(&out).contains("per-rule lint settings"), "{}", stderr(&out));
assert_eq!(code(&out), 2);
assert!(stdout(&out).contains("line-length"), "over the default 100: {}", stdout(&out));
dir.write("lucisv.toml", "[lint.line-length]\nlength = 130\n");
let out = run(&["check", &dir.root()]);
assert_eq!(stdout(&out), "", "the option raised the limit");
assert_eq!(code(&out), 0);
}
/// A bad entry fails the run naming the config file and the line, which is
/// what tells a user *where* to fix it.
#[test]
fn a_bad_rule_option_fails_the_run_naming_file_and_line() {
let dir = TempDir::new("lint-bad-option");
dir.write("m.sv", "module m;\nendmodule\n");
for (config, wanted) in [
("[lint.line-length]\nlength = 10\n", "must be between"),
("[lint.line-length]\nlen = 120\n", "has no option `len`"),
("[lint.no-such-rule]\nx = 1\n", "unknown rule `no-such-rule`"),
("[lint.no-tabs]\nwidth = 4\n", "takes no options"),
("[lint.signal-name-style]\nstyle_regex = \"[a-\"\n", "not a valid pattern"),
// An escape from another dialect must be refused rather than read
// as a literal, which would silently judge the wrong names (QA,
// 2026-09-04).
("[lint.signal-name-style]\nstyle_regex = \"\\bword\\b\"\n", "unsupported escape `\\b`"),
("[lint.macro-name-style]\nstyle_regex = \"(A)\\1\"\n", "unsupported escape `\\1`"),
] {
dir.write("lucisv.toml", config);
let out = run(&["check", &dir.root()]);
let text = stderr(&out);
assert!(text.contains(wanted), "{config:?}: {text}");
assert!(text.contains("lucisv.toml:2:"), "file and line: {text}");
assert_eq!(code(&out), 2, "{config:?}");
}
// Every one of them names the rule as well as the option, so an error
// read out of a CI log stands on its own.
dir.write("lucisv.toml", "[lint.line-length]\nlength = 10\n");
let text = stderr(&run(&["check", &dir.root()]));
assert!(text.contains("rule `line-length`"), "{text}");
assert!(text.contains("`length` must be between"), "{text}");
}
/// The width `line-length` holds a file to is the width the formatter is
/// configured with, so the two halves of lucisv cannot disagree.
#[test]
fn line_length_follows_the_formatters_width() {
let dir = TempDir::new("lint-width");
let wide = format!("module m;\n wire {};\nendmodule\n", "a".repeat(90));
dir.write("m.sv", &wide);
assert_eq!(stdout(&run(&["check", &dir.root()])), "", "under the default 100");
let narrow = run(&["check", &dir.root(), "--line-length", "80"]);
assert!(stdout(&narrow).contains("line-length"), "{}", stdout(&narrow));
dir.write("lucisv.toml", "line-length = 80\n");
let from_config = run(&["check", &dir.root()]);
assert!(stdout(&from_config).contains("line-length"), "{}", stdout(&from_config));
}
/// A stdin buffer reads the same `[lint.<rule>]` tables a file does.
#[test]
fn a_stdin_buffer_reads_the_rule_options_too() {
let dir = TempDir::new("lint-stdin-options");
dir.write("lucisv.toml", "[lint.macro-name-style]\nstyle_regex = \"[a-z_0-9]+\"\n");
let name = format!("{}/m.sv", dir.root());
let out = run_with_stdin(&["check", "-", "--stdin-filename", &name], "`define lower_ok 1\n");
assert_eq!(stdout(&out), "", "the config's pattern accepts it: {}", stdout(&out));
let plain = run_with_stdin(&["check", "-"], "`define lower_ok 1\n");
assert!(stdout(&plain).contains("macro-name-style"), "{}", stdout(&plain));
}
/// The QA finding of 2026-09-02, pinned end to end: a testbench that reads an
@@ -1920,3 +2146,88 @@ fn rules_doc_refuses_files_and_belongs_to_check() {
stderr(&out)
);
}
// --- the walk's own warnings (docs/features/small-items-4/README.md) -------
/// A tree with the two things the walk can only warn about: a directory it
/// cannot read, and a source file that is only a broken link.
#[cfg(unix)]
fn unwalkable_tree(tag: &str) -> TempDir {
use std::os::unix::fs::{symlink, PermissionsExt};
let dir = TempDir::new(tag);
dir.write("a.sv", UNFORMATTED);
dir.write("z/late.sv", UNFORMATTED);
dir.write("locked/hidden.sv", UNFORMATTED);
symlink("nowhere.sv", dir.path.join("gone.sv")).expect("symlink");
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o000))
.expect("chmod");
dir
}
#[cfg(unix)]
fn lock(dir: &TempDir) {
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o000))
.expect("chmod");
}
#[cfg(unix)]
fn unlock(dir: &TempDir) {
use std::os::unix::fs::PermissionsExt;
let _ =
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o755));
}
#[test]
#[cfg(unix)]
fn an_unreadable_directory_is_a_warning_and_the_rest_of_the_tree_is_formatted() {
// The finding TODO §45.2 closes: one permission-denied directory used to
// propagate `read_dir`'s error and fail the whole run.
let dir = unwalkable_tree("walk-warn");
let out = run(&[&dir.root()]);
unlock(&dir);
assert_eq!(code(&out), 0, "a warning is not a failure: {}", stderr(&out));
let said = stderr(&out);
assert_eq!(said.matches("warning: ").count(), 2, "{said}");
assert!(said.contains("locked"), "{said}");
assert!(said.contains("gone.sv: broken symbolic link"), "{said}");
assert_eq!(dir.read("a.sv"), FORMATTED, "the other files were formatted");
assert_eq!(dir.read("z/late.sv"), FORMATTED, "including the ones sorted after it");
}
#[test]
#[cfg(unix)]
fn the_walks_warnings_leave_check_modes_exit_code_alone() {
let dir = unwalkable_tree("walk-warn-check");
let out = run(&["--check", &dir.root()]);
unlock(&dir);
// `--check` answers on formatting alone: two files would be reformatted.
assert_eq!(code(&out), 1, "{}", stderr(&out));
assert_eq!(stderr(&out).matches("warning: ").count(), 2, "{}", stderr(&out));
assert!(!stdout(&out).contains("warning"), "warnings stay off stdout: {}", stdout(&out));
// And with nothing left to reformat the run is clean, warnings and all.
dir.write("a.sv", FORMATTED);
dir.write("z/late.sv", FORMATTED);
lock(&dir);
let out = run(&["--check", &dir.root()]);
unlock(&dir);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(stderr(&out).matches("warning: ").count(), 2, "{}", stderr(&out));
}
#[test]
#[cfg(unix)]
fn a_dangling_source_link_named_on_the_command_line_is_still_an_error() {
// The walk drops the link; a path the user typed is not walked at all, so
// "no such file or directory" is still what naming one gets.
let dir = TempDir::new("walk-warn-named");
std::os::unix::fs::symlink("nowhere.sv", dir.path.join("gone.sv")).expect("symlink");
let named = dir.path.join("gone.sv").to_string_lossy().into_owned();
let out = run(&[&named]);
assert_eq!(code(&out), 2, "{}", stderr(&out));
assert!(stderr(&out).contains("no such file or directory"), "{}", stderr(&out));
}
+451
View File
@@ -0,0 +1,451 @@
//! 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.
//!
//! Two threads of one process may write one target: the temp names carry a
//! per-process counter as well as the pid and are created with `O_EXCL`, so
//! each writer owns its own file and neither can see the other's bytes.
//!
//! Two *processes* writing one target are not coordinated, and deliberately
//! so. Both renames are atomic, the later one wins, and the loser's bytes are
//! discarded whole — never merged. Both processes formatted the same input
//! and `format` is idempotent, so whichever rename lands last leaves the
//! file complete and correctly formatted. A lock would buy nothing and would
//! be one more thing to leave behind after a `^C`.
//!
//! See `docs/features/small-items-3/README.md` and
//! `docs/features/atomic-write-coordination/README.md`.
use std::fs::{self, File, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
/// 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.
///
/// The temp is the caller's alone: [`temp_path`] hands out a name no other
/// writer in this process will be given, and the file is created with
/// `create_new`, so a name that somehow exists is an error and not a shared
/// file. Two threads writing one target therefore both succeed, and the
/// target ends up holding one thread's whole buffer.
///
/// 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());
let perms = target_permissions(&target);
// 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 perms.as_ref().is_some_and(fs::Permissions::readonly) {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("{} is read-only", path.display()),
));
}
let (tmp, mut file) = create_temp(&target, perms.is_some())?;
if let Err(e) = fill_temp(&mut file, &tmp, perms, bytes) {
let _ = fs::remove_file(&tmp);
return Err(e);
}
drop(file);
if let Err(e) = fs::rename(&tmp, &target) {
let _ = fs::remove_file(&tmp);
return Err(e);
}
Ok(())
}
/// How many temp names one write tries before giving up.
///
/// A name is only ever handed out once per process, so a collision means a
/// leftover from a *previous* process that crashed mid-write and whose pid
/// this process now has. A handful of those may sit in one directory; a
/// hundred is a directory to clean up by hand, not a race to retry through.
const TEMP_ATTEMPTS: u32 = 32;
/// Creates the temp file, exclusively, and returns it with its path.
///
/// `replacing` says there is a target whose mode the temp is about to take.
/// Then it is born 0600 on unix rather than at the umask's mode: a chmod does
/// not revoke a descriptor someone already opened, so the only way a private
/// file's replacement can never be read by anyone else is for the temp to be
/// private from the moment it exists. With no target there is no earlier mode
/// to honour and the umask decides, as `fs::write` would.
fn create_temp(target: &Path, replacing: bool) -> io::Result<(PathBuf, File)> {
let mut opts = OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
if replacing {
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
#[cfg(not(unix))]
let _ = replacing;
for _ in 0..TEMP_ATTEMPTS {
let tmp = temp_path(target)?;
match opts.open(&tmp) {
Ok(file) => return Ok((tmp, file)),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
Err(e) => return Err(e),
}
}
Err(io::Error::new(
io::ErrorKind::AlreadyExists,
format!("no free temp file name beside {} after {TEMP_ATTEMPTS} tries", target.display()),
))
}
/// Puts the target's mode on the temp, then the bytes in it.
///
/// The order is the point on unix: a 0600 target's replacement must not spend
/// even an instant holding the file's contents under the umask's broader
/// bits. Chmod does not close the handle opened before it, so a mode without
/// an owner-write bit still takes the write. Elsewhere `set_permissions`
/// takes a path rather than a handle and the mode goes on after the bytes,
/// which is the order this always had.
fn fill_temp(
file: &mut File,
tmp: &Path,
perms: Option<fs::Permissions>,
bytes: &[u8],
) -> io::Result<()> {
if cfg!(unix) {
copy_mode(file, perms);
file.write_all(bytes)
} else {
file.write_all(bytes)?;
if let Some(perms) = perms {
let _ = fs::set_permissions(tmp, perms);
}
Ok(())
}
}
/// Puts the target's mode on the temp through its open handle, which is what
/// lets it happen while the temp is still empty. No target means no earlier
/// mode to honour, and the umask's stands.
fn copy_mode(file: &File, perms: Option<fs::Permissions>) {
if let Some(perms) = perms {
let _ = file.set_permissions(perms);
}
}
/// The mode the temp must end up with: a file someone made executable, or
/// private, keeps its bits, because the temp was created with the process
/// umask (or 0600) and not with the target's. `None` means there is no target
/// — a new file, which takes the umask as `fs::write` would.
fn target_permissions(target: &Path) -> Option<fs::Permissions> {
fs::metadata(target).ok().map(|m| m.permissions())
}
/// Names handed out by [`temp_path`], one per call for the life of the
/// process. Wrapping after 2^64 names is not a scenario.
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
/// The temp file's path: hidden, in the target's own directory, and stamped
/// with the process id and a per-process counter — the pid keeps two lucisv
/// runs apart, the counter keeps two threads of one run apart, and together
/// they mean no two writers anywhere are ever given the same name.
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 n = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
let mut tmp = std::ffi::OsString::from(".");
tmp.push(name);
tmp.push(format!(".{}.{n}.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");
}
/// The audit's probe (`docs/repository-analysis.md` finding 1), which
/// used to produce 100 write errors in 200 calls: both threads derived
/// the same temp name from the target and the pid, so one deleted the
/// other's file under it. Now every writer owns its own temp, so every
/// call succeeds and the target holds one writer's whole buffer.
#[test]
fn two_threads_writing_one_target_never_collide() {
const MIB: usize = 1024 * 1024;
const ROUNDS: usize = 100;
let dir = TempDir::new("race");
let file = dir.file("a.sv");
fs::write(&file, "seed\n").expect("seed");
// Three parties: the two writers and this thread, which inspects the
// target between rounds. Nobody starts a round until everyone has
// finished the last one.
let start = std::sync::Arc::new(std::sync::Barrier::new(3));
let done = std::sync::Arc::new(std::sync::Barrier::new(3));
let writers: Vec<_> = (*b"ab")
.into_iter()
.map(|tag| {
let (path, start, done) = (file.clone(), start.clone(), done.clone());
std::thread::spawn(move || {
let bytes = vec![tag; MIB];
let mut errors = Vec::new();
for _ in 0..ROUNDS {
start.wait();
if let Err(e) = write_atomic(&path, &bytes) {
errors.push(e.to_string());
}
done.wait();
}
errors
})
})
.collect();
for round in 0..ROUNDS {
start.wait();
done.wait();
let got = fs::read(&file).expect("read");
assert_eq!(got.len(), MIB, "round {round}: a partial buffer landed");
let tag = got[0];
assert!(tag == b'a' || tag == b'b', "round {round}: neither writer's byte");
assert!(got.iter().all(|&b| b == tag), "round {round}: two buffers were mixed");
assert_eq!(dir.names(), vec!["a.sv".to_string()], "round {round}: a temp was left");
}
let errors: Vec<String> =
writers.into_iter().flat_map(|w| w.join().expect("writer thread")).collect();
assert!(
errors.is_empty(),
"{} write errors in {} calls: {errors:?}",
errors.len(),
2 * ROUNDS
);
}
#[test]
fn every_thread_gets_its_own_temp_name() {
const PER_THREAD: usize = 200;
let dir = TempDir::new("names");
let target = dir.file("a.sv");
let threads: Vec<_> = (0..4)
.map(|_| {
let target = target.clone();
std::thread::spawn(move || {
(0..PER_THREAD)
.map(|_| temp_path(&target).expect("temp name"))
.collect::<Vec<_>>()
})
})
.collect();
let names: Vec<PathBuf> =
threads.into_iter().flat_map(|t| t.join().expect("name thread")).collect();
let unique: std::collections::HashSet<&PathBuf> = names.iter().collect();
assert_eq!(unique.len(), names.len(), "a temp name was handed out twice");
}
/// The mode goes on while the temp is still empty, so a 0600 file's
/// replacement never holds its contents under the umask's wider bits.
#[cfg(unix)]
#[test]
fn the_temp_takes_the_targets_mode_before_any_bytes() {
use std::os::unix::fs::PermissionsExt;
let dir = TempDir::new("modewindow");
let target = dir.file("secret.sv");
fs::write(&target, "old\n").expect("seed");
fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).expect("chmod");
let perms = target_permissions(&target);
let (tmp, mut file) = create_temp(&target, perms.is_some()).expect("temp");
// Born private, before any mode is copied onto it: an fd opened by
// someone else in this instant would not see the bytes to come.
assert_eq!(
fs::metadata(&tmp).expect("stat").permissions().mode() & 0o777,
0o600,
"the temp was created readable by others"
);
copy_mode(&file, perms.clone());
let meta = fs::metadata(&tmp).expect("stat");
assert_eq!(meta.len(), 0, "the mode is set before a single byte is written");
assert_eq!(meta.permissions().mode() & 0o777, 0o600, "the temp is not world-readable");
// And the chmod does not close the door on the handle opened before it.
fill_temp(&mut file, &tmp, perms, b"new\n").expect("fill");
assert_eq!(fs::read_to_string(&tmp).expect("read"), "new\n");
let _ = fs::remove_file(&tmp);
}
/// The same window seen from outside, through a real `write_atomic`: a
/// big enough buffer that the temp is usually observable while it is
/// being filled. It asserts about what it sees and never about seeing it,
/// so a scheduler that hides the window cannot fail the test.
#[cfg(unix)]
#[test]
fn a_temp_seen_mid_write_is_never_world_readable() {
use std::os::unix::fs::PermissionsExt;
let dir = TempDir::new("window");
let target = dir.file("secret.sv");
fs::write(&target, "old\n").expect("seed");
fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).expect("chmod");
let path = target.clone();
let writer = std::thread::spawn(move || {
let bytes = vec![b'x'; 8 * 1024 * 1024];
write_atomic(&path, &bytes)
});
while !writer.is_finished() {
for entry in fs::read_dir(&dir.path).expect("read dir").flatten() {
if !entry.file_name().to_string_lossy().ends_with(".lucisv-tmp") {
continue;
}
let Ok(meta) = entry.metadata() else { continue };
assert_eq!(
meta.permissions().mode() & 0o777,
0o600,
"a temp for a 0600 target was readable by others"
);
}
}
writer.join().expect("writer thread").expect("write");
assert_eq!(fs::metadata(&target).expect("stat").permissions().mode() & 0o777, 0o600);
}
}
+2 -5
View File
@@ -87,10 +87,7 @@ impl Cache {
if !ignore.exists() {
let _ = std::fs::write(&ignore, "*\n");
}
let tmp = dir.join(format!("{FILE}.{}.tmp", std::process::id()));
if std::fs::write(&tmp, self.render()).is_ok() && std::fs::rename(&tmp, path).is_err() {
let _ = std::fs::remove_file(&tmp);
}
let _ = crate::atomic::write_atomic(path, self.render().as_bytes());
}
/// The file's text: one line per entry, sorted by path so that two
@@ -397,7 +394,7 @@ mod tests {
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.ends_with(".tmp"))
.filter(|n| n.ends_with(".tmp") || n.ends_with("-tmp"))
.collect();
assert!(leftovers.is_empty(), "{leftovers:?}");
}
+325 -24
View File
@@ -1,8 +1,9 @@
//! `lucisv.toml` / `.lucisv.toml` discovery and its TOML-subset parser.
//!
//! Only what a small config file needs is supported (comments, `key = int`,
//! `key = "string"`, `key = ["a", "b"]`, and the single table `[lint]`);
//! everything else is rejected by name rather than ignored. See
//! `key = "string"`, `key = ["a", "b"]`, the table `[lint]` and the per-rule
//! `[lint.<rule>]` tables); everything else is rejected by name rather than
//! ignored. See
//! `docs/features/config-discovery/README.md` for the grammar and the
//! reasoning behind not taking a TOML dependency.
@@ -29,6 +30,10 @@ pub struct FileConfig {
/// directory, so every `FileConfig` a `Discovery` hands out carries a
/// usable path. See `docs/features/filelist/README.md`.
pub filelist: Option<PathBuf>,
/// `[format] uvm-utils-indent`: indent the `` `uvm_field_* `` macro
/// statements written between `` `uvm_*_utils_begin `` and
/// `` `uvm_*_utils_end ``. Off for the same reason.
pub format_uvm_utils_indent: Option<bool>,
/// `[lint] select`: run exactly these rules, replacing the default set.
/// The names are **not** validated here — this crate does not know the
/// rule registry; `lucisv check` validates them the moment it resolves the
@@ -36,6 +41,43 @@ pub struct FileConfig {
pub lint_select: Option<Vec<String>>,
/// `[lint] ignore`: rules dropped from whatever `select` left.
pub lint_ignore: Option<Vec<String>>,
/// `[lint] waivers`: external waiver files, in the order written.
///
/// Like [`FileConfig::filelist`], these name *other files*: [`parse`]
/// records them exactly as written and [`Discovery`] resolves each one
/// against the config file's own directory, so every `FileConfig` a
/// `Discovery` hands out carries usable paths. Nothing here reads them —
/// their contents name lint rules, and this crate does not know the rule
/// registry any more than it does for `select`.
pub lint_waivers: Option<Vec<PathBuf>>,
/// `[lint.<rule>]` tables, **as written**: one entry per key, in file
/// order.
///
/// Neither the rule names nor the option names or their values are
/// checked here — this crate does not know the rule registry, exactly as
/// it does not know which rule names `select` may hold. `lucisv check`
/// resolves them against `vlog_linter`'s specs and fails the run naming
/// this file and the line, which is what [`LintOption::line`] is for.
pub lint_options: Vec<LintOption>,
/// The config file these settings were read from, when they were read
/// from one. `parse` leaves it unset — it is handed text, not a path —
/// and [`Discovery`] fills it in, so an error about an entry can name the
/// file the user has to edit.
pub source: Option<PathBuf>,
}
/// One `key = value` written under a `[lint.<rule>]` table, as written.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LintOption {
/// The rule named by the table header.
pub rule: String,
/// The option key.
pub key: String,
/// The value's text, comment stripped, quotes and all — the linter's own
/// parser reads it, because only it knows what kind the key takes.
pub raw: String,
/// 1-based line the entry was written on.
pub line: usize,
}
/// Parses the supported TOML subset. Errors are prefixed `<line>: ` so the
@@ -45,36 +87,62 @@ pub fn parse(text: &str) -> Result<FileConfig, String> {
// Editors on some platforms prepend a BOM; it would otherwise garble
// key matching on line 1 into an `unknown key` with invisible cause.
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
// Which table the keys below belong to. There is exactly one table, so
// this is a flag rather than a path: `[lint]` opens it and nothing closes
// it, which is TOML's own rule.
let mut in_lint = false;
// Which table the keys below belong to: the top level until a header
// opens one, and then that one until the next header. Nothing closes a
// table, which is TOML's own rule.
let mut table = Table::Top;
for (index, raw) in text.lines().enumerate() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
parse_entry(line, &mut config, &mut in_lint).map_err(|e| format!("{}: {e}", index + 1))?;
parse_entry(line, &mut config, &mut table, index + 1)
.map_err(|e| format!("{}: {e}", index + 1))?;
}
Ok(config)
}
fn parse_entry(line: &str, config: &mut FileConfig, in_lint: &mut bool) -> Result<(), String> {
/// The table whose keys are being read.
enum Table {
/// Before any header: the formatter's own keys.
Top,
/// `[lint]`: `select`, `ignore` and `waivers`.
Lint,
/// `[format]`: the layout keys that are off by default.
Format,
/// `[lint.<rule>]`: that rule's options.
Rule(String),
}
fn parse_entry(
line: &str,
config: &mut FileConfig,
table: &mut Table,
number: usize,
) -> Result<(), String> {
if line.starts_with('[') {
// `[lint]` is the one table lucisv reads. `[lint.<rule>]` — per-rule
// settings — is named in the error rather than ignored, so a user who
// writes one finds out it is not supported yet instead of wondering
// why it did nothing (topo §2.9-4 keeps the per-rule half open).
// `[lint]` carries `select`/`ignore`/`waivers`; `[lint.<rule>]` carries that
// rule's options, which are stored raw and checked by whoever knows
// the registry.
if line == "[lint]" {
*in_lint = true;
*table = Table::Lint;
return Ok(());
}
if line.starts_with("[lint.") {
return Err(format!(
"per-rule lint settings (`{line}`) are not supported yet; `[lint]` takes `select` and `ignore`"
));
if line == "[format]" {
*table = Table::Format;
return Ok(());
}
return Err(format!("unknown table `{line}` (the only table is `[lint]`)"));
if let Some(rule) = line.strip_prefix("[lint.").and_then(|r| r.strip_suffix(']')) {
if rule.is_empty() || rule.contains('.') || rule.contains(' ') {
return Err(format!("`{line}` is not a rule table; write `[lint.<rule-name>]`"));
}
*table = Table::Rule(rule.to_string());
return Ok(());
}
return Err(format!(
"unknown table `{line}` \
(the tables are `[format]`, `[lint]` and `[lint.<rule-name>]`)"
));
}
let (key, value) =
line.split_once('=').ok_or_else(|| format!("expected `key = value`, found `{line}`"))?;
@@ -83,8 +151,11 @@ fn parse_entry(line: &str, config: &mut FileConfig, in_lint: &mut bool) -> Resul
if value.is_empty() {
return Err(format!("`{key}` has no value"));
}
if *in_lint {
return parse_lint_entry(key, value, config);
match table {
Table::Format => return parse_format_entry(key, value, config),
Table::Lint => return parse_lint_entry(key, value, config),
Table::Rule(rule) => return parse_rule_entry(rule, key, value, config, number),
Table::Top => {}
}
match key {
"line-length" => set_int(&mut config.line_length, key, value, 40, 400),
@@ -105,18 +176,59 @@ fn parse_entry(line: &str, config: &mut FileConfig, in_lint: &mut bool) -> Resul
}
_ => Err(format!(
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
and select, ignore under `[lint]`)"
uvm-utils-indent under `[format]`; \
select, ignore, waivers under `[lint]`; and a rule's own options \
under `[lint.<rule-name>]`)"
)),
}
}
/// One key of the `[format]` table: a boolean that defaults to off, because
/// it changes how already-clean files are laid out and a project has to opt
/// in before anything of its moves.
fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
let slot = match key {
"uvm-utils-indent" => &mut config.format_uvm_utils_indent,
_ => {
return Err(format!(
"unknown key `{key}` under `[format]` \
(the only key is uvm-utils-indent)"
))
}
};
if slot.is_some() {
return Err(format!("duplicate key `{key}`"));
}
*slot = Some(parse_bool(key, value)?);
Ok(())
}
/// `true` or `false`, and nothing else — a misspelling is a typo the user
/// wants to hear about, not a silent `false`.
fn parse_bool(key: &str, value: &str) -> Result<bool, String> {
match value {
"true" => Ok(true),
"false" => Ok(false),
_ => Err(format!("`{key}` expects `true` or `false`, found `{value}`")),
}
}
/// One key of the `[lint]` table.
fn parse_lint_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
if key == "waivers" {
if config.lint_waivers.is_some() {
return Err(format!("duplicate key `{key}`"));
}
config.lint_waivers = Some(parse_array(value)?.into_iter().map(PathBuf::from).collect());
return Ok(());
}
let slot = match key {
"select" => &mut config.lint_select,
"ignore" => &mut config.lint_ignore,
_ => {
return Err(format!("unknown key `{key}` under `[lint]` (known keys: select, ignore)"))
return Err(format!(
"unknown key `{key}` under `[lint]` (known keys: select, ignore, waivers)"
))
}
};
if slot.is_some() {
@@ -126,6 +238,26 @@ fn parse_lint_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(
Ok(())
}
/// One `key = value` of a `[lint.<rule>]` table, kept as written.
fn parse_rule_entry(
rule: &str,
key: &str,
value: &str,
config: &mut FileConfig,
line: usize,
) -> Result<(), String> {
if config.lint_options.iter().any(|held| held.rule == rule && held.key == key) {
return Err(format!("duplicate key `{key}` under `[lint.{rule}]`"));
}
config.lint_options.push(LintOption {
rule: rule.to_string(),
key: key.to_string(),
raw: value.to_string(),
line,
});
Ok(())
}
fn set_int(
slot: &mut Option<usize>,
key: &str,
@@ -288,10 +420,18 @@ fn load(path: &Path) -> Result<FileConfig, String> {
// `filelist` is the one value that names another file, so it is resolved
// here — against the config file's own directory, which `parse` cannot
// know. An absolute path is left alone (`join` already does that).
let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();
if let Some(filelist) = config.filelist.take() {
let dir = path.parent().unwrap_or(Path::new("."));
config.filelist = Some(dir.join(filelist));
}
// `[lint] waivers` names other files the same way, and is resolved the
// same way: against the config file's directory, an absolute path left
// alone by `join`.
if let Some(waivers) = config.lint_waivers.take() {
config.lint_waivers = Some(waivers.into_iter().map(|file| dir.join(file)).collect());
}
// So an error about a `[lint.<rule>]` entry can name the file to edit.
config.source = Some(path.to_path_buf());
Ok(config)
}
@@ -355,6 +495,34 @@ exclude = [ \"build\", \"*_gen.sv\", ]
);
}
/// `[lint] waivers` names other files, so it resolves the way `filelist`
/// does: against the config file's own directory, absolute paths left
/// alone. See `docs/features/waiver-files/README.md`.
#[test]
fn lint_waivers_are_a_list_resolved_against_the_config_files_directory() {
assert_eq!(
ok("[lint]\nwaivers = [ \"a.waiver\", \"deep/b.waiver\" ]").lint_waivers,
Some(vec![PathBuf::from("a.waiver"), PathBuf::from("deep/b.waiver")])
);
assert_eq!(
ok("[lint]\nselect = [\"no-tabs\"]").lint_waivers,
None,
"absent unless written"
);
assert!(err("[lint]\nwaivers = \"a.waiver\"").contains("multi-line arrays"));
assert!(err("[lint]\nwaivers = []\nwaivers = []").contains("duplicate key `waivers`"));
assert!(err("[lint]\nwaiver = []").contains("unknown key `waiver` under `[lint]`"));
let tree = TempTree::new();
tree.write("lucisv.toml", "[lint]\nwaivers = [ \"rtl/a.waiver\", \"/opt/b.waiver\" ]\n");
let deep = tree.write("a/b/x.sv", "");
let found = Discovery::new(true).for_file(&deep).unwrap();
assert_eq!(
found.lint_waivers,
Some(vec![tree.path.join("rtl/a.waiver"), PathBuf::from("/opt/b.waiver")])
);
}
#[test]
fn an_empty_file_sets_nothing() {
assert_eq!(ok(""), FileConfig::default());
@@ -425,6 +593,65 @@ exclude = [ \"build\", \"*_gen.sv\", ]
);
}
/// The `[format]` table: the layout keys that change how an already-clean
/// file is laid out, and so are off unless a checked-in `lucisv.toml`
/// turns them on (TODO §54.3).
#[test]
fn the_format_table_carries_uvm_utils_indent() {
assert_eq!(ok("[format]\nuvm-utils-indent = true").format_uvm_utils_indent, Some(true));
assert_eq!(ok("[format]\nuvm-utils-indent = false").format_uvm_utils_indent, Some(false));
// Absent unless written — which is what makes the default off.
assert_eq!(ok("indent = 4").format_uvm_utils_indent, None);
assert_eq!(ok("[format]").format_uvm_utils_indent, None);
// The formatter keys still work above the table, and nothing closes
// the table but the next header.
let mixed = parse(
"indent = 4\n\n[format]\nuvm-utils-indent = true\n\n[lint]\nignore = [\"no-tabs\"]",
)
.expect("parses");
assert_eq!(mixed.indent, Some(4));
assert_eq!(mixed.format_uvm_utils_indent, Some(true));
assert_eq!(mixed.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
}
/// Everything about the table's shape, the way the `[lint]` table's is
/// pinned: an unknown key is named, a non-boolean value is refused, and a
/// repeated key is an error rather than a last-one-wins.
#[test]
fn the_format_table_rejects_what_it_does_not_support() {
assert!(err("[format]\nbogus = true").contains("unknown key `bogus` under `[format]`"));
assert!(err("[format]\nuvm-utils-indent = \"yes\"")
.contains("`uvm-utils-indent` expects `true` or `false`, found `\"yes\"`"));
assert!(err("[format]\nuvm-utils-indent = 1").contains("expects `true` or `false`"));
assert!(err("[format]\nuvm-utils-indent =").contains("has no value"));
assert!(err("[format]\nuvm-utils-indent = true\nuvm-utils-indent = false")
.contains("duplicate key `uvm-utils-indent`"));
// A key before any table still belongs to the top level, and the
// top-level unknown-key message names the table it does belong to.
assert!(err("uvm-utils-indent = true").contains("unknown key `uvm-utils-indent`"));
assert!(err("uvm-utils-indent = true").contains("`[format]`"));
// `[format.<anything>]` is not a table this parser knows.
assert!(err("[format.uvm]\nx = 1").contains("unknown table"));
}
/// The same key in a real config file, so the message a user sees names
/// the file and the line to edit — the ladder `[format]` sits at the top
/// of (`lucisv.toml` outranks the editor setting).
#[test]
fn a_bad_format_key_names_the_file_and_line() {
let tree = TempTree::new();
let config = tree.write("lucisv.toml", "indent = 2\n\n[format]\nuvm-utils-indnet = true\n");
let file = tree.write("x.sv", "");
let message = Discovery::new(true).for_file(&file).expect_err("expected an error");
assert!(message.starts_with(&format!("{}:4: ", config.display())), "{message}");
assert!(message.contains("unknown key `uvm-utils-indnet` under `[format]`"), "{message}");
// And the key spelled right loads through the same walk.
let good = TempTree::new();
good.write("lucisv.toml", "[format]\nuvm-utils-indent = true\n");
let sv = good.write("a/b/x.sv", "");
assert_eq!(Discovery::new(true).for_file(&sv).unwrap().format_uvm_utils_indent, Some(true));
}
/// The `[lint]` table: the off switch a round that turns rules on by
/// default owes its users (topo §2.9-4).
#[test]
@@ -451,7 +678,8 @@ exclude = [ \"build\", \"*_gen.sv\", ]
fn the_lint_table_rejects_what_it_does_not_support() {
assert!(err("[lint]\nbogus = [\"a\"]").contains("unknown key `bogus` under `[lint]`"));
assert!(err("[lint]\nselect = \"no-tabs\"").contains("multi-line arrays are unsupported"));
assert!(err("[lint.no-tabs]\nseverity = \"error\"").contains("per-rule lint settings"));
assert!(err("[lint.]\nx = 1").contains("not a rule table"));
assert!(err("[lint.a.b]\nx = 1").contains("not a rule table"));
assert!(err("[lint]\nindent = 4").contains("unknown key `indent` under `[lint]`"));
// A key before any table still belongs to the top level.
assert!(err("select = [\"no-tabs\"]").contains("unknown key `select`"));
@@ -462,6 +690,79 @@ exclude = [ \"build\", \"*_gen.sv\", ]
);
}
/// The per-rule tables: stored exactly as written, because this crate
/// has no idea what a rule is or what its options take.
#[test]
fn a_rule_table_keeps_its_entries_as_written() {
let config = parse(
"[lint]\nignore = [\"no-tabs\"]\n\n\
[lint.line-length]\nlength = 120\n\n\
[lint.signal-name-style]\nstyle_regex = \"[a-z_0-9]+\" # ours\n",
)
.expect("parses");
assert_eq!(config.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
let entries: Vec<(&str, &str, &str, usize)> = config
.lint_options
.iter()
.map(|o| (o.rule.as_str(), o.key.as_str(), o.raw.as_str(), o.line))
.collect();
assert_eq!(
entries,
vec![
("line-length", "length", "120", 5),
("signal-name-style", "style_regex", "\"[a-z_0-9]+\"", 8),
]
);
}
/// A backslash is legal in an option value and refused in a top-level
/// string: the linter's own parser reads the former, and a pattern is the
/// one value that needs them.
#[test]
fn a_rule_option_value_is_not_string_checked_here() {
let config =
parse("[lint.signal-name-style]\nstyle_regex = \"[a-z]\\d+\"\n").expect("parses");
assert_eq!(config.lint_options[0].raw, "\"[a-z]\\d+\"");
assert!(err("exclude = [\"a\\d\"]").contains("escapes"), "still refused up here");
}
#[test]
fn a_rule_table_rejects_a_repeated_key_and_a_bad_header() {
assert!(err("[lint.line-length]\nlength = 1\nlength = 2")
.contains("duplicate key `length` under `[lint.line-length]`"));
// The same key under two different rules is two different options.
let config = parse(
"[lint.enum-name-style]\nstyle_regex = \"a\"\n\
[lint.module-name-style]\nstyle_regex = \"b\"\n",
)
.expect("parses");
assert_eq!(config.lint_options.len(), 2);
assert!(err("[lint.a b]\nx = 1").contains("not a rule table"));
}
/// Nothing closes a table: the keys after a rule header belong to it
/// until the next header, and a formatter key written there is that
/// rule's option as far as this parser is concerned.
#[test]
fn a_rule_table_runs_until_the_next_header() {
let config =
parse("indent = 4\n[lint.line-length]\nlength = 120\nindent = 8\n").expect("parses");
assert_eq!(config.indent, Some(4));
assert_eq!(config.lint_options.len(), 2);
assert_eq!(config.lint_options[1].key, "indent");
}
#[test]
fn a_config_file_records_where_it_came_from() {
let tree = TempTree::new();
let written = tree.write("lucisv.toml", "[lint.line-length]\nlength = 120\n");
let file = tree.write("x.sv", "");
let found = Discovery::new(true).for_file(&file).expect("reads");
assert_eq!(found.source.as_deref(), Some(written.as_path()));
// `parse` alone has no path to record.
assert_eq!(parse("indent = 4").expect("parses").source, None);
}
/// A throwaway directory tree under the system temp dir.
struct TempTree {
path: PathBuf,
+4 -1
View File
@@ -6,11 +6,14 @@
//! the same `lucisv.toml` and skip the same files as CI's `lucisv --check`.
//! `cache` answers the third question of the same family — whether a file
//! needs to be processed at all, and `filelist` answers the first one the way
//! an EDA project already does, from a `.f` file. See
//! an EDA project already does, from a `.f` file. `atomic` is the one write
//! path all of them share: nothing here ever truncates a file it is
//! replacing. See
//! `docs/features/lucisv-core-lift/README.md`, and
//! `docs/features/{config-discovery,parallel-files,format-cache,filelist}/README.md`
//! for the rules themselves.
pub mod atomic;
pub mod cache;
pub mod config;
pub mod filelist;
+383 -23
View File
@@ -2,6 +2,7 @@
//! `.gitignore` subset documented in
//! `docs/features/parallel-files/README.md`.
use std::collections::HashSet;
use std::path::{Path, PathBuf};
/// File extensions lucisv formats when walking a directory.
@@ -10,20 +11,56 @@ pub const EXTENSIONS: &[&str] = &["v", "sv", "vh", "svh"];
/// The name of the per-directory ignore file that is honoured by default.
const GITIGNORE: &str = ".gitignore";
/// Something the walk could not do and went on regardless: a directory it
/// could not read, an ignore file it could not open, a source file that is
/// only a broken link.
///
/// The walk's warning channel exists because none of these is worth failing a
/// run over — one unreadable directory used to drop every file already found
/// — and because a silent skip loses the user the fact entirely. Rendering is
/// the front end's job: the CLI writes `warning: <path>: <message>` to stderr,
/// the server logs the same text once per scan.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Warning {
/// What could not be used.
pub path: PathBuf,
/// Why, in the operating system's own words where there are any.
pub message: String,
}
impl std::fmt::Display for Warning {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.path.display(), self.message)
}
}
/// Adds `input` to `files`: the file itself, or every Verilog file under
/// it if it is a directory. Exclude patterns and `.gitignore` rules apply
/// to directory walks only — a path named on the command line is always
/// formatted.
///
/// `warn` is called once for everything the walk skipped and wants said; see
/// [`Warning`]. Only `input` itself naming nothing is an error — that is the
/// user's own typo, and the run has nothing to do.
pub fn collect_files(
input: &str,
exclude: &[String],
gitignore: bool,
files: &mut Vec<PathBuf>,
warn: &mut dyn FnMut(Warning),
) -> Result<(), String> {
let path = Path::new(input);
if path.is_dir() {
let mut walk = Walk { exclude, gitignore, ignores: Vec::new(), rel: Vec::new(), files };
walk.dir(path).map_err(|e| format!("{input}: {e}"))?;
let mut walk = Walk {
exclude,
gitignore,
ignores: Vec::new(),
rel: Vec::new(),
visited: HashSet::new(),
files,
warn,
};
walk.dir(path);
} else if path.is_file() {
files.push(path.to_path_buf());
} else {
@@ -32,57 +69,166 @@ pub fn collect_files(
Ok(())
}
/// How a directory is recognised as one the walk has already entered. Two
/// names for the same directory — a symlink and its target, or two symlinks
/// pointing at one place — must map to the same identity, or a cycle has no
/// end. On unix that is `(dev, ino)`, the pair the filesystem itself uses;
/// elsewhere it is the canonical path, which resolves symlinks the same way
/// at the cost of a real path lookup.
#[cfg(unix)]
type DirId = (u64, u64);
#[cfg(not(unix))]
type DirId = PathBuf;
/// The identity of the directory at `path`, or `None` when it cannot be
/// read — a dangling symlink, or a directory that vanished mid-walk.
#[cfg(unix)]
fn dir_id(path: &Path) -> Option<DirId> {
use std::os::unix::fs::MetadataExt;
let meta = std::fs::metadata(path).ok()?;
Some((meta.dev(), meta.ino()))
}
#[cfg(not(unix))]
fn dir_id(path: &Path) -> Option<DirId> {
std::fs::canonicalize(path).ok()
}
/// True when `path` names one of the source files lucisv formats.
fn is_source(path: &Path) -> bool {
path.extension().and_then(|e| e.to_str()).is_some_and(|ext| EXTENSIONS.contains(&ext))
}
/// One directory walk. `rel` is the path of the directory currently being
/// read, in components relative to the walk root, which is what
/// `.gitignore` rules are matched against; `ignores` is the stack of
/// ignore files seen from the root down to it.
/// ignore files seen from the root down to it; `visited` is every directory
/// already entered, by identity rather than by spelling.
struct Walk<'a> {
exclude: &'a [String],
gitignore: bool,
ignores: Vec<Ignore>,
rel: Vec<String>,
visited: HashSet<DirId>,
files: &'a mut Vec<PathBuf>,
warn: &'a mut dyn FnMut(Warning),
}
impl Walk<'_> {
fn dir(&mut self, dir: &Path) -> std::io::Result<()> {
let pushed = self.push_ignore(dir)?;
let mut entries: Vec<_> = std::fs::read_dir(dir)?.collect::<Result<_, _>>()?;
fn dir(&mut self, dir: &Path) {
if !self.enter(dir) {
return;
}
let pushed = self.push_ignore(dir);
self.entries(dir);
if pushed {
self.ignores.pop();
}
}
/// One directory's entries, in name order. A directory that cannot be read
/// — the permission-denied one somewhere under the start — is said and
/// skipped: everything already found stays found and the walk goes on,
/// which is the whole reason this channel exists.
fn entries(&mut self, dir: &Path) {
let read = match std::fs::read_dir(dir) {
Ok(read) => read,
Err(e) => return self.say(dir, e.to_string()),
};
let mut entries = Vec::new();
for entry in read {
match entry {
Ok(entry) => entries.push(entry),
Err(e) => self.say(dir, e.to_string()),
}
}
entries.sort_by_key(|e| e.path());
for entry in entries {
let path = entry.path();
if is_excluded(&path, self.exclude) {
continue;
}
let is_dir = path.is_dir();
// One `metadata` call per entry, exactly as before — it follows
// symlinks, so it answers "directory?" for a symlinked directory
// the way `is_dir()` did. A dangling symlink has no metadata at
// all. One that *names a source file* is warned about and dropped:
// §43's QA was right that a silent skip loses the user the fact,
// and §45.2 gives that fact a home of its own rather than handing
// the path on to fail as "no such file" in the front end. One that
// names anything else was never going to be read, and is skipped
// as quietly as it always was.
let Ok(meta) = std::fs::metadata(&path) else {
if is_source(&path) {
let why = broken_link_reason(&path);
self.say(&path, why);
}
continue;
};
self.rel.push(entry.file_name().to_string_lossy().into_owned());
if !is_ignored(&self.ignores, &self.rel, is_dir) {
if is_dir {
self.dir(&path)?;
} else if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
if EXTENSIONS.contains(&ext) {
self.files.push(path);
}
if !is_ignored(&self.ignores, &self.rel, meta.is_dir()) {
if meta.is_dir() {
self.dir(&path);
} else if meta.is_file() && is_source(&path) {
self.files.push(path);
}
}
self.rel.pop();
}
if pushed {
self.ignores.pop();
}
Ok(())
}
/// Hand one warning to the front end.
fn say(&mut self, path: &Path, message: String) {
(self.warn)(Warning { path: path.to_path_buf(), message });
}
/// Records `dir` as entered, and answers whether it had not been entered
/// already. Identity, not spelling: `a/loop -> a` and `a/b/up -> ..` name
/// a directory the walk is already inside, and following either is the
/// cycle that only ends when the OS refuses a path. A symlink to a
/// directory the walk has *not* seen is followed once, so
/// `rtl -> ../shared/rtl` still contributes its files; the second link to
/// one target contributes nothing further, and the files are reported
/// under the first spelling that reached them.
///
/// A directory whose identity cannot be read is not entered.
fn enter(&mut self, dir: &Path) -> bool {
dir_id(dir).is_some_and(|id| self.visited.insert(id))
}
/// Reads `dir`'s `.gitignore`, if there is one, onto the rule stack.
/// Returns whether anything was pushed, so `dir` can pop it again.
fn push_ignore(&mut self, dir: &Path) -> std::io::Result<bool> {
///
/// An ignore file that cannot be read is said and ignored, for the same
/// reason an unreadable directory is: the walk that finds too much is a
/// better failure than the walk that finds nothing.
fn push_ignore(&mut self, dir: &Path) -> bool {
let path = dir.join(GITIGNORE);
if !self.gitignore || !path.is_file() {
return Ok(false);
return false;
}
let rules = parse_gitignore(&std::fs::read_to_string(&path)?);
self.ignores.push(Ignore { base: self.rel.len(), rules });
Ok(true)
match std::fs::read_to_string(&path) {
Ok(text) => {
self.ignores.push(Ignore { base: self.rel.len(), rules: parse_gitignore(&text) });
true
}
Err(e) => {
self.say(&path, e.to_string());
false
}
}
}
}
/// Why a directory entry has no metadata, said the way a person would.
///
/// A broken symbolic link is what this is nearly always about, and naming it
/// as one is worth more than the bare `No such file or directory` the follow
/// produced; anything else keeps the operating system's own words.
fn broken_link_reason(path: &Path) -> String {
match std::fs::symlink_metadata(path) {
Ok(meta) if meta.file_type().is_symlink() => "broken symbolic link".to_string(),
Ok(_) => "cannot be read".to_string(),
Err(e) => e.to_string(),
}
}
@@ -214,6 +360,8 @@ fn glob_component(pattern: &str, name: &str) -> bool {
#[cfg(test)]
mod tests {
use super::*;
#[cfg(unix)]
use std::sync::atomic::{AtomicUsize, Ordering};
fn excluded(path: &str, pattern: &str) -> bool {
is_excluded(Path::new(path), &[pattern.to_string()])
@@ -320,6 +468,218 @@ mod tests {
assert!(!ignored_at(&[(0, "/x.sv")], "sub/x.sv"));
}
// ------------------------------------------------------------------
// Symlink cycles — `docs/features/walk-cycles/README.md`
//
// Every test below builds a real tree with real symlinks, because the
// question is what the filesystem answers, not what a mock does. Each
// one would run until the OS refused a path before the visited set.
// ------------------------------------------------------------------
/// A throwaway directory tree under the system temp dir, removed on
/// drop. `remove_dir_all` unlinks a symlink instead of following it, so
/// a tree with a cycle in it is cleaned up like any other.
#[cfg(unix)]
struct TempTree {
path: PathBuf,
}
#[cfg(unix)]
impl TempTree {
fn new(tag: &str) -> TempTree {
static COUNTER: AtomicUsize = AtomicUsize::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let path =
std::env::temp_dir().join(format!("lucisv-walk-{}-{tag}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("create temp dir");
TempTree { path }
}
fn write(&self, rel: &str, text: &str) {
let path = self.path.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("create parent");
}
std::fs::write(&path, text).expect("write");
}
/// A source file with enough in it to be worth finding.
fn source(&self, rel: &str) {
self.write(rel, "module m;\nendmodule\n");
}
/// Set `rel`'s permission bits. `0o000` is how a test builds the
/// directory the walk cannot read; the test puts them back so the
/// temp tree can be removed.
fn chmod(&self, rel: &str, mode: u32) {
use std::os::unix::fs::PermissionsExt;
let path = self.path.join(rel);
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode))
.expect("set permissions");
}
/// `rel` as a symlink to `target`, which is relative to `rel`'s own
/// directory — the spelling a checked-in symlink actually uses.
fn link(&self, rel: &str, target: &str) {
let path = self.path.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("create parent");
}
std::os::unix::fs::symlink(target, &path).expect("symlink");
}
/// The walk from `rel` (empty for the root), as sorted paths
/// relative to the tree root. Warnings are dropped; the tests that
/// care about them call [`TempTree::warned`].
fn walk(&self, rel: &str) -> Vec<String> {
self.walked(rel).0
}
/// The same, plus what the walk said, each warning's path made
/// relative to the tree root so the assertions read.
fn warned(&self, rel: &str) -> (Vec<String>, Vec<String>) {
self.walked(rel)
}
fn walked(&self, rel: &str) -> (Vec<String>, Vec<String>) {
let start = if rel.is_empty() { self.path.clone() } else { self.path.join(rel) };
let mut files = Vec::new();
let mut warnings = Vec::new();
collect_files(
start.to_str().expect("utf-8 temp path"),
&[],
true,
&mut files,
&mut |w| warnings.push(format!("{}: {}", self.rel_of(&w.path), w.message)),
)
.expect("the walk finishes");
let mut out: Vec<String> = files.iter().map(|p| self.rel_of(p)).collect();
out.sort();
warnings.sort();
(out, warnings)
}
fn rel_of(&self, path: &Path) -> String {
path.strip_prefix(&self.path).unwrap_or(path).to_string_lossy().into_owned()
}
}
#[test]
#[cfg(unix)]
fn a_directory_linking_to_itself_is_entered_once() {
let tree = TempTree::new("selfloop");
tree.source("a/x.sv");
tree.link("a/loop", "../a");
assert_eq!(tree.walk(""), ["a/x.sv"]);
}
#[test]
#[cfg(unix)]
fn a_link_to_an_ancestor_terminates_from_a_nested_start() {
let tree = TempTree::new("uplink");
tree.source("root.sv");
tree.source("a/x.sv");
tree.link("a/up", "..");
// Starting *inside* the cycle: `a` is entered, then `a/up` is the
// root, which the walk has not seen yet and so does enter — once.
// Its own `a` is the directory already being walked, and stops.
assert_eq!(tree.walk("a"), ["a/up/root.sv", "a/x.sv"]);
}
#[test]
#[cfg(unix)]
fn two_links_to_one_directory_yield_its_files_once() {
let tree = TempTree::new("twolinks");
tree.source("shared/x.sv");
// Sorted after `shared`, so the real directory is the spelling that
// reaches the file first; whichever name wins, the file is reported
// exactly once.
tree.link("z1", "shared");
tree.link("z2", "shared");
assert_eq!(tree.walk(""), ["shared/x.sv"]);
}
#[test]
#[cfg(unix)]
fn a_link_to_a_directory_not_yet_walked_is_still_followed() {
let tree = TempTree::new("sibling");
tree.source("shared/rtl/x.sv");
tree.link("proj/rtl", "../shared/rtl");
// The `rtl -> ../shared/rtl` of a real checkout: the target is
// outside the walk, so the link is the only way to it.
assert_eq!(tree.walk("proj"), ["proj/rtl/x.sv"]);
}
#[test]
#[cfg(unix)]
fn a_dangling_source_link_is_warned_about_and_not_handed_on() {
// §43's review kept the dangling source link in the file list so the
// front end's "no such file" error survived. TODO §45.2 reverses that
// on purpose: the warning is now the error's home, so the link is said
// once here and never reaches the formatter. A dangling link that
// names no source file was never going to be read and stays silent.
let tree = TempTree::new("dangling");
tree.source("a/x.sv");
tree.link("a/gone.sv", "nowhere.sv");
tree.link("a/gonedir", "nowhere");
let (files, warnings) = tree.warned("");
assert_eq!(files, ["a/x.sv"]);
assert_eq!(warnings, ["a/gone.sv: broken symbolic link"]);
}
#[test]
#[cfg(unix)]
fn an_unreadable_directory_is_skipped_and_the_walk_goes_on() {
// The finding this channel exists for: one permission-denied directory
// used to propagate `read_dir`'s error out of the whole walk, dropping
// every file already found and failing the run.
let tree = TempTree::new("unreadable");
tree.source("a.sv");
tree.source("locked/hidden.sv");
tree.source("z/late.sv");
tree.chmod("locked", 0o000);
let (files, warnings) = tree.warned("");
tree.chmod("locked", 0o755);
assert_eq!(files, ["a.sv", "z/late.sv"], "the walk finished");
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert!(warnings[0].starts_with("locked: "), "the warning names it: {warnings:?}");
}
#[test]
#[cfg(unix)]
fn an_unreadable_ignore_file_is_said_and_the_directory_is_still_walked() {
let tree = TempTree::new("lockedignore");
tree.write(".gitignore", "build\n");
tree.source("keep.sv");
tree.chmod(".gitignore", 0o000);
let (files, warnings) = tree.warned("");
tree.chmod(".gitignore", 0o644);
assert_eq!(files, ["keep.sv"]);
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert!(warnings[0].starts_with(".gitignore: "), "{warnings:?}");
}
#[test]
#[cfg(unix)]
fn a_clean_walk_says_nothing() {
let tree = TempTree::new("quiet");
tree.source("a/x.sv");
tree.source("b/y.sv");
assert_eq!(tree.warned(""), (vec!["a/x.sv".to_string(), "b/y.sv".to_string()], Vec::new()));
}
#[test]
#[cfg(unix)]
fn a_cycle_inside_an_ignored_directory_is_never_entered() {
let tree = TempTree::new("ignoredcycle");
tree.write(".gitignore", "build\n");
tree.source("keep.sv");
tree.source("build/y.sv");
tree.link("build/loop", "../build");
assert_eq!(tree.walk(""), ["keep.sv"]);
}
#[test]
fn unsupported_syntax_degrades_to_plain_globbing() {
// `**` is just two stars inside one component; documented.
+72 -9
View File
@@ -14,6 +14,7 @@ use lsp_types::{
use vlog_linter::{apply_fixes, rule_by_name, Applicability, Violation};
use crate::convert::Positions;
use crate::lint::LintRun;
use crate::state::Document;
/// The kind of the fix-everything action, namespaced under `source.fixAll` so
@@ -27,6 +28,7 @@ pub const FIX_ALL: &str = "source.fixAll.lucisv";
/// client, because a fix-on-save request asks for `source.fixAll.lucisv` alone
/// and computing every quick fix for it would be work nobody reads.
pub fn code_actions(
run: &LintRun,
uri: &Uri,
doc: &Document,
range: Range,
@@ -34,7 +36,7 @@ pub fn code_actions(
tab_width: usize,
) -> Vec<CodeActionOrCommand> {
let positions = doc.positions();
let violations = crate::lint::fixable(doc, tab_width);
let violations = crate::lint::fixable(run, doc, tab_width);
let mut actions = Vec::new();
if wanted(only, &CodeActionKind::QUICKFIX) {
let quick = violations.iter().filter_map(|v| quick_fix(uri, &positions, v, range));
@@ -170,7 +172,7 @@ mod tests {
fn actions_of(ws: &Workspace) -> Vec<CodeAction> {
let doc = ws.document(&uri()).expect("open");
let whole = doc.positions().whole_document();
code_actions(&uri(), doc, whole, None, 2)
code_actions(&LintRun::default(), &uri(), doc, whole, None, 2)
.into_iter()
.map(|a| match a {
CodeActionOrCommand::CodeAction(action) => action,
@@ -248,7 +250,14 @@ mod tests {
start: Position { line: 1, character: 0 },
end: Position { line: 1, character: 0 },
};
let actions = code_actions(&uri(), doc, line1, Some(&[CodeActionKind::QUICKFIX]), 2);
let actions = code_actions(
&LintRun::default(),
&uri(),
doc,
line1,
Some(&[CodeActionKind::QUICKFIX]),
2,
);
assert_eq!(actions.len(), 1, "the cursor's line only: {actions:#?}");
}
@@ -320,14 +329,32 @@ mod tests {
start: Position { line: fenced_line, character: 0 },
end: Position { line: fenced_line, character: 0 },
};
let actions = code_actions(&uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]), 2);
let actions = code_actions(
&LintRun::default(),
&uri(),
doc,
at,
Some(&[CodeActionKind::QUICKFIX]),
2,
);
assert!(actions.is_empty(), "no quick fix inside a fence: {actions:#?}");
// The unfenced tab one line further down still has one.
let at = Range {
start: Position { line: 4, character: 0 },
end: Position { line: 4, character: 0 },
};
assert_eq!(code_actions(&uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]), 2).len(), 1);
assert_eq!(
code_actions(
&LintRun::default(),
&uri(),
doc,
at,
Some(&[CodeActionKind::QUICKFIX]),
2
)
.len(),
1
);
}
#[test]
@@ -370,14 +397,19 @@ mod tests {
let doc = ws.document(&uri()).expect("open");
let whole = doc.positions().whole_document();
let fix_all_only = [CodeActionKind::new(FIX_ALL)];
let actions = code_actions(&uri(), doc, whole, Some(&fix_all_only), 2);
let actions = code_actions(&LintRun::default(), &uri(), doc, whole, Some(&fix_all_only), 2);
assert_eq!(actions.len(), 1, "no quick fixes when only fixAll was asked for");
// `source` is a prefix filter for `source.fixAll.lucisv`.
let source = [CodeActionKind::SOURCE];
assert_eq!(code_actions(&uri(), doc, whole, Some(&source), 2).len(), 1);
assert_eq!(
code_actions(&LintRun::default(), &uri(), doc, whole, Some(&source), 2).len(),
1
);
// And an unrelated filter selects nothing.
let refactor = [CodeActionKind::REFACTOR];
assert!(code_actions(&uri(), doc, whole, Some(&refactor), 2).is_empty());
assert!(
code_actions(&LintRun::default(), &uri(), doc, whole, Some(&refactor), 2).is_empty()
);
}
#[test]
@@ -386,7 +418,14 @@ mod tests {
let ws = workspace(text);
let doc = ws.document(&uri()).expect("open");
let whole = doc.positions().whole_document();
let actions = code_actions(&uri(), doc, whole, Some(&[CodeActionKind::QUICKFIX]), 4);
let actions = code_actions(
&LintRun::default(),
&uri(),
doc,
whole,
Some(&[CodeActionKind::QUICKFIX]),
4,
);
let CodeActionOrCommand::CodeAction(fix) = &actions[0] else { panic!("an action") };
assert_eq!(applied(text, fix), "module m;\n wire a;\nendmodule\n");
}
@@ -407,4 +446,28 @@ mod tests {
assert!(out.contains("é 🎉"), "comments are never dropped: {out:?}");
assert_eq!(out, "module m;\n // é 🎉 wire a;\nendmodule\n");
}
#[test]
fn an_externally_waived_finding_gets_no_quick_fix_and_fix_all_leaves_it() {
// §39 QA's HIGH: `fixable` used `default_rules()` and no waivers, so
// fix-on-save rewrote a line a checked-in waiver file had waived.
let src = "module m;\n\twire a;\nendmodule\n";
let ws = workspace(src);
let doc = ws.document(&uri()).expect("open");
let whole = doc.positions().whole_document();
let (external, problems) = vlog_linter::ExternalWaivers::parse(
std::path::Path::new("team.waiver"),
"waive --rule=no-tabs\n",
);
assert!(problems.is_empty(), "{problems:?}");
let waived = LintRun::default().with_external(external);
assert!(
code_actions(&waived, &uri(), doc, whole, None, 2).is_empty(),
"no quick fix and no fix-all for a waived finding"
);
assert!(
!code_actions(&LintRun::default(), &uri(), doc, whole, None, 2).is_empty(),
"the same buffer without the waiver is fixable"
);
}
}
+61 -3
View File
@@ -14,7 +14,7 @@ use std::collections::HashSet;
use lsp_types::CompletionResponse;
use vlog_parser::token::{Token, TokenKind};
use vlog_semantic::{MemberSite, Semantics, SymbolKind, WorkspaceIndex};
use vlog_semantic::{MemberSite, Semantics, Surface, SymbolKind, WorkspaceIndex};
use super::site::balanced;
use super::tiers::innermost_scope;
@@ -168,6 +168,14 @@ fn members_at(
site: &MemberSite,
) -> Vec<Member> {
let mut members = Members::new();
// A cross-file site says which surface its own tail resolution reads, and
// the list follows it: behind `u_x.` in an *expression* that is the
// module's hierarchical surface — its nets, variables and instances as
// well as its ports and parameters — which is exactly what the in-file
// `MemberSite::Scope` half above offers for an instance this file
// declares. A connection list's `.` never arrives here; it is
// `connection_members` below, and it is the connection surface.
let mut surface = Surface::Connection;
let base = match site {
MemberSite::Scope(scope) => {
let (scopes, base) = semantics.member_scopes(*scope);
@@ -181,10 +189,13 @@ fn members_at(
// overlay's own inheritance chase does.
base.map(|path| last_segment(&path).to_string())
}
MemberSite::Unit(unit) => Some(unit.clone()),
MemberSite::Unit { path, surface: reads } => {
surface = *reads;
Some(path.clone())
}
};
if let Some(unit) = base {
for (name, def) in index.members_of_chain(&unit) {
for (name, def) in index.members_of_chain_in(&unit, surface) {
members.push(name, def.kind, indexed_detail(def.kind, def.type_name.as_deref()));
}
}
@@ -983,6 +994,53 @@ endmodule
assert_eq!(clk.detail.as_deref(), Some("port"), "table-only across files");
}
/// **§49's completion decision, and its limit.** Behind `u_sub.` in an
/// *expression* the list is the module's **hierarchical** surface — its
/// nets, its variables and its instances as well as its ports and its
/// parameters — because that is what a hierarchical path may name and
/// exactly what the tail resolution will find, so every item offered is
/// an item hover and go-to-definition answer. Behind the `.` of a
/// **connection list** it is the connection surface and nothing more:
/// `.internal(w)` is not a legal connection, and an item the resolution
/// could not find is a wrong answer rather than a generous one.
#[test]
fn an_instance_head_lists_the_hierarchical_surface_and_a_connection_list_does_not() {
const SUB: &str = "module sub (input logic clk);\n wire internal;\n int counter;\n leaf u_leaf ();\nendmodule\n";
let hierarchical = {
let tree = Tree::new("hiersurface_expr");
tree.write("sub.sv", SUB);
tree.write("leaf.sv", "module leaf;\nendmodule\n");
let top = "module top;\n sub u_sub ();\n initial y = u_sub.;\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= u_sub.");
let mut found = labels(&items(completions(&ws, &uri, position, true)))
.iter()
.map(|l| l.to_string())
.collect::<Vec<_>>();
found.sort();
found
};
assert_eq!(
hierarchical,
vec!["clk", "counter", "internal", "u_leaf"],
"the port and the three hierarchical-only members"
);
let connection = {
let tree = Tree::new("hiersurface_conn");
tree.write("sub.sv", SUB);
tree.write("leaf.sv", "module leaf;\nendmodule\n");
let top = "module top;\n sub u_sub (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " .");
let mut found = labels(&items(completions(&ws, &uri, position, true)))
.iter()
.map(|l| l.to_string())
.collect::<Vec<_>>();
found.sort();
found
};
assert_eq!(connection, vec!["clk"], "the connection list is the port list, unchanged");
}
#[test]
fn an_interface_instance_lists_its_ports_too() {
let tree = Tree::new("ifaceconn");
+41 -31
View File
@@ -528,39 +528,49 @@ mod tests {
}
}
/// QA finding (performance wave Lane B, 2026-08-28), not a regression this
/// QA finding (performance wave Lane B, 2026-08-28), not a regression that
/// round introduced: a module with an attribute instance (`(* ... *)`)
/// anywhere near its header — right after its name, or on one of its
/// ports — is not indexed as a `Module` unit **at all**.
/// `WorkspaceIndex::units` comes back empty, so [`module_header`] declines
/// at the very first line (no `[def]` to anchor on) before the whitelist
/// walk ever runs, and completion's module tier — which sources its
/// candidate names from the same table — never offers the module in the
/// first place. This is a `vlog_semantic`/`vlog_parser` parsing gap, not a
/// completion-core one: it is filed in `docs/features/completion-core/
/// README.md`'s QA log rather than fixed here, because `vlog_semantic` is
/// outside this round's touched files. The two "attribute" shapes this QA
/// round added to [`SHAPES`] (`attributed`, `port_attributed`) still pass
/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] — but only
/// because both sides of that comparison fall back to the same whole-file
/// parse, which this test makes explicit rather than leaving it as an
/// unremarked side effect of the pin.
/// **between its name and its `#(`** is not indexed as a `Module` unit at
/// all. `WorkspaceIndex::units` comes back empty, so [`module_header`]
/// declines at the very first line (no `[def]` to anchor on) before the
/// whitelist walk ever runs, and completion's module tier — which sources
/// its candidate names from the same table — never offers the module in
/// the first place. That attribute sits inside no list, so no recovery
/// reaches it; it is still filed in `docs/features/completion-core/
/// README.md`'s QA log.
///
/// **The `port_attributed` half of the finding was fixed by header
/// recovery** (TODO §32, `docs/features/header-recovery/README.md`): an
/// attribute on a *port* now costs that one port and nothing else — the
/// list keeps a `ListElem::Error` where `(* keep *) output logic q` was
/// written, and the module keeps its name, its other ports and its body,
/// so it is indexed and its header slices for real rather than by
/// whole-file fallback. That is the re-audit the old message asked for,
/// and it is the second half of this test;
/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] covers the
/// same shape from the other side.
#[test]
fn a_module_with_an_attribute_near_its_header_is_not_indexed_at_all() {
for module in ["attributed", "port_attributed"] {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
index.units(module).is_empty(),
"{module}: if this starts finding a unit, module_header should be re-audited \
for whether it now slices attributes correctly rather than by lucky fallback"
);
assert!(
module_header(&index, module, text).is_none(),
"{module}: no unit to anchor on"
);
}
fn an_attribute_before_the_parameter_list_still_costs_the_whole_module() {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == "attributed").expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
index.units("attributed").is_empty(),
"if this starts finding a unit, module_header should be re-audited \
for whether it now slices attributes correctly rather than by lucky fallback"
);
assert!(module_header(&index, "attributed", text).is_none(), "no unit to anchor on");
}
#[test]
fn an_attribute_on_a_port_costs_that_port_only() {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == "port_attributed").expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert_eq!(index.units("port_attributed").len(), 1, "the module survives its broken port");
let header = module_header(&index, "port_attributed", text).expect("a sliced header");
assert!(header.starts_with("module port_attributed ("), "{header:?}");
assert!(header.contains("(* keep *) output logic q"), "the port list is kept whole");
}
/// The guard is not decoration: a non-ANSI module really does plan
@@ -513,6 +513,20 @@ endmodule
);
}
/// The premise the probe above rests on, stated as a test: the probe is
/// *discriminating*. Header recovery (TODO §32) widened what a tolerant
/// parse can read, so the question "did this insertion parse?" is only
/// worth asking while text that does **not** parse still says so.
#[test]
fn the_insertion_probe_still_reports_text_that_does_not_parse() {
let broken = "if (cond begin\n\n end";
let probe = format!("module p;\n always_comb begin\n {broken}\n end\nendmodule\n");
assert!(
!vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
"recovery must not make a broken insertion look clean: {probe}"
);
}
#[test]
fn a_templates_documentation_shows_what_it_expands_to() {
let top = "module top;\n alw\nendmodule\n";
@@ -896,6 +910,30 @@ endmodule
drop(tree);
}
/// Header recovery (TODO §32) pinned where completion meets it: with a
/// half-typed parameter *above* the cursor, the module still has a scope,
/// so [`visible_symbols`] still answers from it — the parameters and ports
/// already typed are offered inside the very header being edited.
///
/// Before this round the broken header took the whole `Module` node with
/// it, the body re-parsed at file scope, and the scope chain covering this
/// offset held nothing at all.
#[test]
fn a_broken_header_still_completes_from_the_modules_scope() {
let top = "\
module top #(parameter W = , parameter DEPTH = 4) (
input logic clk_i,
output logic DE
);
logic w_local;
endmodule
";
let (_tree, ws, uri, position) = asking("brokenheader", top, "output logic DE");
let found = items(completions(&ws, &uri, position, true));
let item = find(&found, "DEPTH").expect("the parameter typed after the broken one");
assert_eq!(tier(item), TIER_SCOPE, "answered from the module's own scope");
}
/// The scope tier goes fuzzy too, with no mask table behind it — it is
/// the one tier computed per request.
#[test]
+35 -3
View File
@@ -135,11 +135,12 @@ mod tests {
#[test]
fn one_list_carries_both_sources() {
// A file that parses cleanly and violates a lint rule: the publish is
// one list, and the lint finding is in it as a warning.
// one list, and the lint finding is in it at its rule's own severity
// — `no-tabs` is a style rule, so INFORMATION (§33.0).
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
let published = all(ws.document(&uri).expect("open"));
assert_eq!(published.len(), 1);
assert_eq!(published[0].severity, Some(DiagnosticSeverity::WARNING));
assert_eq!(published[0].severity, Some(DiagnosticSeverity::INFORMATION));
assert_eq!(published[0].code, Some(lsp_types::NumberOrString::String("no-tabs".into())));
}
@@ -149,12 +150,43 @@ mod tests {
let published = all(ws.document(&uri).expect("open"));
let severities: Vec<_> = published.iter().map(|d| d.severity).collect();
assert!(severities.contains(&Some(DiagnosticSeverity::ERROR)), "{published:#?}");
assert!(severities.contains(&Some(DiagnosticSeverity::WARNING)), "{published:#?}");
assert!(severities.contains(&Some(DiagnosticSeverity::INFORMATION)), "{published:#?}");
assert!(published.iter().all(|d| d.source.as_deref() == Some("lucisv")));
// Errors first: a parse error is what the user must fix.
assert_eq!(published[0].severity, Some(DiagnosticSeverity::ERROR));
}
/// The user-visible contract of header recovery (TODO §32), pinned where
/// the user meets it: a typo in a port list costs **one** diagnostic, and
/// the module around it survives whole — its name, the ports typed before
/// and after the typo, and its body all still in the outline.
///
/// Before this round the same buffer published two errors (the header, and
/// the orphaned `endmodule`), the body re-parsed as file-scope items, and
/// the outline had no module in it at all.
#[test]
fn a_broken_port_list_publishes_one_error_and_keeps_its_module() {
let (ws, uri) = doc_of("module m (input a, , input b);\n wire ok;\nendmodule\n");
let doc = ws.document(&uri).expect("open");
let diags = diagnostics(doc);
assert_eq!(diags.len(), 1, "{diags:#?}");
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::ERROR));
assert_eq!(diags[0].range.start.line, 0, "the header's own line");
// The missing-closer pass explains a *parse* failure; there is no
// unclosed block here, so it must add nothing.
assert!(crate::pairs::missing_end_diagnostics(doc).is_empty());
let symbols = crate::symbols::document_symbols(doc);
assert_eq!(symbols.len(), 1, "the module is still in the outline");
assert_eq!(symbols[0].name, "m");
let children = symbols[0].children.as_ref().expect("module contents");
let names: Vec<&str> = children.iter().map(|c| c.name.as_str()).collect();
assert!(names.contains(&"a"), "the port before the typo: {names:?}");
assert!(names.contains(&"b"), "the port after it: {names:?}");
assert!(names.contains(&"ok"), "the body: {names:?}");
}
#[test]
fn a_lex_error_gets_a_visible_range() {
// The lexer gives up at end of file, which a trailing newline makes
+371
View File
@@ -0,0 +1,371 @@
//! Extract a selection into a module of its own, on the wire:
//! `textDocument/codeAction` under LSP's own `refactor.extract`, and
//! `workspace/executeCommand` for the editors that have no lightbulb.
//!
//! Protocol only. The edit is `vlog_refactor::extract_module`; this module
//! decides which files that engine is handed, turns its answer into a
//! `WorkspaceEdit`, and turns its refusal into a request error.
//!
//! **The action carries a command, not an edit** — which is what makes it the
//! laziest of the lot rather than merely a lazy one. Extracting needs a *name*
//! for the new module, and LSP has no prompt: a code action can carry an
//! `edit`, a `command`, or both, and only a command can be intercepted by a
//! client that wants to ask the user something first. So the offer is one
//! parse of one buffer (`vlog_refactor::extract_site`) plus a `Command` naming
//! [`EXTRACT_MODULE`] and the default name `M_extracted`; the VS Code
//! extension registers a client-side command of the same name that shows an
//! input box and calls the server's with what the user typed, and every other
//! client runs the command as sent and gets the default. See
//! `docs/features/extract-inline-module/README.md`.
//!
//! **The new file.** A module extracted into a file of its own is a
//! `CreateFile` resource operation, which only a client that advertises
//! `workspace.workspaceEdit.documentChanges` *and* `resourceOperations`
//! containing `create` can apply. That capability is read at `initialize`
//! ([`crate::server::ClientAbilities::create_files`]) and is the whole of the
//! choice between the two homes: a client that can create files gets `N.sv`
//! beside `M`'s file, and every other client gets `N` written below `M` in the
//! file it came from. The engine says which happened in its warnings.
// See `rename.rs` for why this is a `WorkspaceEdit`'s problem and not ours.
#![allow(clippy::mutable_key_type)]
use lsp_types::{
CodeAction, CodeActionKind, CodeActionOrCommand, Command, CreateFile, DocumentChangeOperation,
DocumentChanges, OneOf, OptionalVersionedTextDocumentIdentifier, Range, ResourceOp,
TextDocumentEdit, TextEdit, Uri, WorkspaceEdit,
};
use serde_json::Value;
use vlog_parser::LineIndex;
use vlog_refactor::{Home, RefactorEdit};
use crate::convert::Positions;
use crate::state::Workspace;
use crate::uri::path_to_uri;
/// Extract a selection into a module: `[uri, range, name]`.
pub const EXTRACT_MODULE: &str = "lucisv.extractModule";
/// Every command this module executes.
pub fn commands() -> Vec<String> {
vec![EXTRACT_MODULE.to_string()]
}
/// The kind LSP reserves for an extraction, which is what an editor's
/// "Refactor…" menu asks for by name.
pub fn kind() -> CodeActionKind {
CodeActionKind::REFACTOR_EXTRACT
}
/// The action for a selection, carrying the command that will ask for a name.
///
/// One parse of the buffer and nothing else: the engine's cheap gate answers
/// "there is nothing here" for almost every selection, and where it does find
/// something the offer is a `Command`, so no workspace is read until the user
/// has picked the action *and* named the module.
pub fn code_actions(ws: &Workspace, uri: &Uri, range: Range) -> Vec<CodeActionOrCommand> {
let Some(doc) = ws.document(uri) else { return Vec::new() };
if doc.path.is_none() {
// An `untitled:` buffer has no directory to put `N.sv` beside and no
// path for the engine's file set; nothing is offered rather than
// offered and refused.
return Vec::new();
}
let positions = doc.positions();
let (start, end) = (positions.offset(range.start), positions.offset(range.end));
let Some(site) = vlog_refactor::extract_site(&doc.text, start, end) else { return Vec::new() };
let arguments = vec![
serde_json::to_value(uri).unwrap_or(Value::Null),
serde_json::to_value(range).unwrap_or(Value::Null),
Value::String(site.default_name.clone()),
];
let title = vlog_refactor::extract_title();
vec![CodeActionOrCommand::CodeAction(CodeAction {
title: title.clone(),
kind: Some(kind()),
command: Some(Command {
title,
command: EXTRACT_MODULE.to_string(),
arguments: Some(arguments),
}),
..Default::default()
})]
}
/// Run `lucisv.extractModule`, or say why it cannot run.
pub fn execute(
ws: &Workspace,
arguments: &[Value],
create_files: bool,
) -> Result<(WorkspaceEdit, Vec<String>), String> {
let uri: Uri = argument(arguments, 0, "a document URI")?;
let range: Range = argument(arguments, 1, "a range")?;
let name: String = argument(arguments, 2, "a name for the new module")?;
let doc = ws
.document(&uri)
.ok_or_else(|| "lucisv can only extract from an open file.".to_string())?;
let path = doc
.path
.clone()
.ok_or_else(|| "lucisv can only extract from a file that has been saved.".to_string())?;
let positions = doc.positions();
let (start, end) = (positions.offset(range.start), positions.offset(range.end));
let Some(site) = vlog_refactor::extract_site(&doc.text, start, end) else {
return Err(NOTHING.to_string());
};
// The engine looks up every module the selection instantiates and every
// package it imports, so the file set is those units' own fan-out — plus
// the new name's, so a workspace that already declares it is a workspace
// the engine can refuse over.
let mut units = site.units;
units.push(name.clone());
let files = ws.module_sources(&path, &units);
let home = match create_files {
true => Home::NewFile,
false => Home::SameFile,
};
let refactoring = vlog_refactor::extract_module(&files, &path, start, end, &name, home)?;
Ok((workspace_edit(ws, &refactoring)?, refactoring.warnings))
}
/// A whole extraction as a `WorkspaceEdit`.
///
/// `documentChanges` rather than `changes` whenever a file is created: a
/// creation is a resource operation, and the two shapes cannot be mixed in one
/// edit. An extraction that creates nothing goes through the ordinary
/// `changes` map, which every client understands.
pub fn workspace_edit(ws: &Workspace, refactoring: &RefactorEdit) -> Result<WorkspaceEdit, String> {
if refactoring.created.is_empty() {
return crate::ports::workspace_edit(ws, refactoring);
}
let mut operations: Vec<DocumentChangeOperation> = Vec::new();
for path in &refactoring.created {
let uri = path_to_uri(path).ok_or_else(|| unaddressable(path))?;
operations.push(DocumentChangeOperation::Op(ResourceOp::Create(CreateFile {
uri,
options: None,
annotation_id: None,
})));
}
for (path, edits) in &refactoring.edits {
let uri = path_to_uri(path).ok_or_else(|| unaddressable(path))?;
// A file the edit creates has no text yet, and the one insertion into
// it is at 0:0 — which is what `Positions` over an empty text says.
let created = refactoring.created.iter().any(|created| created == path);
let text = match created {
true => String::new(),
false => ws.text_of(path).ok_or_else(|| unaddressable(path))?,
};
let index = LineIndex::new(&text);
let positions = Positions::new(&text, &index);
operations.push(DocumentChangeOperation::Edit(TextDocumentEdit {
text_document: OptionalVersionedTextDocumentIdentifier { uri, version: None },
edits: edits
.iter()
.map(|edit| {
OneOf::Left(TextEdit {
range: positions.range(edit.range),
new_text: edit.new_text.clone(),
})
})
.collect(),
}));
}
Ok(WorkspaceEdit {
document_changes: Some(DocumentChanges::Operations(operations)),
..Default::default()
})
}
fn argument<T: serde::de::DeserializeOwned>(
arguments: &[Value],
n: usize,
what: &str,
) -> Result<T, String> {
arguments
.get(n)
.and_then(|value| serde_json::from_value(value.clone()).ok())
.ok_or_else(|| format!("{EXTRACT_MODULE} wants {what} as argument {}.", n + 1))
}
fn unaddressable(path: &std::path::Path) -> String {
format!("lucisv could not address {} as a document; no edits were made.", path.display())
}
const NOTHING: &str = "there is nothing to extract at this selection.";
#[cfg(test)]
mod tests {
use super::*;
use crate::uri::path_to_uri;
use lsp_types::Position;
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_extract_{}_{name}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("temp dir");
Tree { path }
}
fn write(&self, rel: &str, text: &str) -> PathBuf {
let path = self.path.join(rel);
fs::write(&path, text).expect("write");
path
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
const TOP: &str = "\
module top (
input logic [7:0] a,
input logic [7:0] b,
output logic [7:0] q
);
logic [7:0] s;
assign s = a + b;
assign q = s;
endmodule
";
fn opened(tree: &Tree) -> (Workspace, Uri) {
let top = tree.write("top.sv", TOP);
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(), TOP.to_string());
(ws, uri)
}
/// The range of `assign s = a + b;`, as the client speaks it.
fn selection() -> Range {
Range {
start: Position { line: 6, character: 2 },
end: Position { line: 6, character: 19 },
}
}
fn only(actions: Vec<CodeActionOrCommand>) -> Vec<CodeAction> {
actions
.into_iter()
.filter_map(|a| match a {
CodeActionOrCommand::CodeAction(action) => Some(action),
CodeActionOrCommand::Command(_) => None,
})
.collect()
}
#[test]
fn a_selection_of_whole_items_is_offered_the_action_with_a_command_and_a_default_name() {
let tree = Tree::new("offer");
let (ws, uri) = opened(&tree);
let actions = only(code_actions(&ws, &uri, selection()));
let [action] = actions.as_slice() else { panic!("one action, got {actions:?}") };
assert_eq!(action.title, "lucisv: extract selection into module…");
assert_eq!(action.kind, Some(CodeActionKind::REFACTOR_EXTRACT));
assert!(action.edit.is_none(), "the offer reads no workspace");
let command = action.command.as_ref().expect("a command");
assert_eq!(command.command, EXTRACT_MODULE);
let arguments = command.arguments.as_ref().expect("arguments");
assert_eq!(arguments.len(), 3);
assert_eq!(arguments[2], Value::String("top_extracted".to_string()));
}
#[test]
fn a_selection_that_covers_no_whole_item_is_offered_nothing() {
let tree = Tree::new("nothing");
let (ws, uri) = opened(&tree);
let half = Range {
start: Position { line: 6, character: 2 },
end: Position { line: 6, character: 8 },
};
assert!(code_actions(&ws, &uri, half).is_empty());
}
#[test]
fn the_command_creates_the_new_file_for_a_client_that_can() {
let tree = Tree::new("create");
let (ws, uri) = opened(&tree);
let arguments = vec![
serde_json::to_value(&uri).expect("uri"),
serde_json::to_value(selection()).expect("range"),
Value::String("sum".to_string()),
];
let (edit, warnings) = execute(&ws, &arguments, true).expect("extracts");
assert!(warnings.iter().any(|w| w.contains("sum.sv")), "{warnings:?}");
let Some(DocumentChanges::Operations(ops)) = edit.document_changes else {
panic!("a creating edit speaks documentChanges: {edit:?}")
};
let creates = ops
.iter()
.filter(|op| matches!(op, DocumentChangeOperation::Op(ResourceOp::Create(_))))
.count();
assert_eq!(creates, 1, "one file is created: {ops:?}");
assert_eq!(ops.len(), 3, "the creation plus one edit per file: {ops:?}");
}
#[test]
fn the_command_writes_the_module_into_the_same_file_for_a_client_that_cannot() {
let tree = Tree::new("same");
let (ws, uri) = opened(&tree);
let arguments = vec![
serde_json::to_value(&uri).expect("uri"),
serde_json::to_value(selection()).expect("range"),
Value::String("sum".to_string()),
];
let (edit, warnings) = execute(&ws, &arguments, false).expect("extracts");
assert!(
warnings.iter().any(|w| w.contains("did not say it can create files")),
"{warnings:?}"
);
assert!(edit.document_changes.is_none(), "no resource operation is needed");
let changes = edit.changes.as_ref().expect("changes");
assert_eq!(changes.len(), 1, "one file is touched");
assert_eq!(changes.get(&uri).expect("this file").len(), 2);
}
#[test]
fn the_command_says_why_when_there_is_nothing_to_extract() {
let tree = Tree::new("refuse");
let (ws, uri) = opened(&tree);
let arguments = vec![
serde_json::to_value(&uri).expect("uri"),
serde_json::to_value(Range {
start: Position { line: 0, character: 0 },
end: Position { line: 0, character: 3 },
})
.expect("range"),
Value::String("sum".to_string()),
];
assert_eq!(execute(&ws, &arguments, true), Err(NOTHING.to_string()));
}
#[test]
fn the_command_wants_all_three_of_its_arguments() {
let tree = Tree::new("arguments");
let (ws, uri) = opened(&tree);
let short = vec![serde_json::to_value(&uri).expect("uri")];
let message = execute(&ws, &short, true).expect_err("a refusal");
assert!(message.contains("argument 2"), "{message}");
}
#[test]
fn a_client_asking_only_for_refactor_extract_is_answered() {
let filter = [CodeActionKind::REFACTOR_EXTRACT];
assert!(crate::code_action::wanted(Some(&filter), &kind()));
assert!(!crate::code_action::wanted(Some(&filter), &CodeActionKind::QUICKFIX));
}
}
+41
View File
@@ -224,6 +224,14 @@ fn config_from(file: &FileConfig, client: &ClientSettings, options: &FormattingO
if let Some(line_length) = file.line_length {
config.max_width = line_length;
}
// The `[format]` keys follow the same ladder: the editor's own setting
// first, then `lucisv.toml`, which outranks it.
if let Some(on) = client.uvm_utils_indent {
config.uvm_utils_indent = on;
}
if let Some(on) = file.format_uvm_utils_indent {
config.uvm_utils_indent = on;
}
config
}
@@ -508,6 +516,39 @@ mod tests {
assert_eq!(settings.config.max_width, Config::default().max_width);
}
/// The `[format]` keys climb the same ladder — with no rung 3, since the
/// protocol has no option for them: `lucisv.toml` > `lucisv.format.*` >
/// the built-in default, which is off (TODO §54.3).
#[test]
fn a_format_key_climbs_the_ladder_from_off() {
let uvm = |on: Option<bool>| ClientSettings { uvm_utils_indent: on, ..Default::default() };
// Rung 4: nobody asked, so the key never fires.
let (ws, uri) = document("module m;\nendmodule\n");
assert!(!settings_with(&ws, &uri, &none(), &options(2, true)).config.uvm_utils_indent);
// Rung 2: the editor setting is the only thing that spoke.
assert!(
settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true)).config.uvm_utils_indent
);
// Rung 1: `lucisv.toml` outranks the editor, in both directions.
let on = Tree::new("[format]\nuvm-utils-indent = true\n");
let (ws, uri) = on.document("module m;\nendmodule\n");
let settings = settings_with(&ws, &uri, &uvm(Some(false)), &options(2, true));
assert_eq!(settings.problem, None);
assert!(settings.config.uvm_utils_indent, "lucisv.toml wins");
let off = Tree::new("[format]\nuvm-utils-indent = false\n");
let (ws, uri) = off.document("module m;\nendmodule\n");
assert!(
!settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true)).config.uvm_utils_indent
);
// A config that names other keys is silent about this one, so the
// editor setting still answers for it.
let other = Tree::new("indent = 4\n");
let (ws, uri) = other.document("module m;\nendmodule\n");
let settings = settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true));
assert_eq!(settings.config.indent_width, 4);
assert!(settings.config.uvm_utils_indent);
}
#[test]
fn each_key_climbs_the_ladder_independently() {
// A `lucisv.toml` naming only `indent` must not also claim the width:
+381
View File
@@ -0,0 +1,381 @@
//! Organize imports on the wire: `textDocument/codeAction` under LSP's own
//! `source.organizeImports` kind, and `workspace/executeCommand` for the
//! editors that have no lightbulb.
//!
//! Protocol only. The edit is `vlog_refactor::organize_imports`; this module
//! decides which files that engine is handed, turns its answer into a
//! `WorkspaceEdit`, and turns its refusal into a request error.
//!
//! **The kind is `source.organizeImports` and nothing else.** That is the
//! kind an editor's organize-on-save asks for by name, and filing the action
//! under a second `refactor.rewrite.*` kind as well would mean a client
//! asking for both got the same action twice.
//!
//! **The file set.** An `import` binds names in the scope that wrote it, so
//! the edit never leaves the cursor's own file — but *judging* it needs every
//! file that could supply a name through one of those imports: the file
//! declaring each imported package, every file declaring a package of that
//! name (so an ambiguity the index can see is one the engine sees too), and
//! the same again for every package those re-export from (§48). That closure
//! is a handful of files on any workspace, which is what lets this run on a
//! cursor rather than on a whole-workspace read. See
//! `docs/features/organize-imports/README.md`.
// See `rename.rs` for why this is a `WorkspaceEdit`'s problem and not ours.
#![allow(clippy::mutable_key_type)]
use std::path::{Path, PathBuf};
use lsp_types::{CodeAction, CodeActionKind, CodeActionOrCommand, Position, Uri, WorkspaceEdit};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::state::Workspace;
/// Organize the imports at a position: `[uri, position]`.
pub const ORGANIZE_IMPORTS: &str = "lucisv.organizeImports";
/// Every command this module executes.
pub fn commands() -> Vec<String> {
vec![ORGANIZE_IMPORTS.to_string()]
}
/// The kind LSP reserves for this action, which is what an editor's
/// organize-on-save asks for.
pub fn kind() -> CodeActionKind {
CodeActionKind::SOURCE_ORGANIZE_IMPORTS
}
/// The action at a position, carrying its computed edit — what a client
/// without `codeAction/resolve` gets, and what [`resolve`] re-runs.
pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrCommand> {
let Some((path, files)) = at(ws, uri, offset) else { return Vec::new() };
let Ok((edit, removed, sorted)) = vlog_refactor::organize_counts(&files, &path, offset) else {
return Vec::new();
};
let Ok(edit) = crate::ports::workspace_edit(ws, &edit) else { return Vec::new() };
vec![CodeActionOrCommand::CodeAction(CodeAction {
title: vlog_refactor::organize_title(removed, sorted),
kind: Some(kind()),
edit: Some(edit),
..Default::default()
})]
}
/// The same action **without** its edit — the offer a client that can
/// `codeAction/resolve` is sent.
///
/// The counts in the title are the engine's own, computed over the same file
/// set [`resolve`] will use, so the offer and the resolution cannot disagree
/// about what the action promises.
pub fn offers(
ws: &Workspace,
uri: &Uri,
position: Position,
offset: u32,
) -> Vec<CodeActionOrCommand> {
let Some((path, files)) = at(ws, uri, offset) else { return Vec::new() };
let Ok((_, removed, sorted)) = vlog_refactor::organize_counts(&files, &path, offset) else {
return Vec::new();
};
let title = vlog_refactor::organize_title(removed, sorted);
let data = serde_json::to_value(Offer { uri: uri.clone(), position }).ok();
vec![CodeActionOrCommand::CodeAction(CodeAction {
title,
kind: Some(kind()),
data,
..Default::default()
})]
}
/// The edit for an offered action, computed now that the user has picked it.
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 buffer that has grown past the large-file threshold since it was
// offered an action is refused here rather than parsed — `ports::resolve`
// draws the same line, and for the same reason.
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) => Some(found),
CodeActionOrCommand::Command(_) => None,
})
.map(|mut resolved| {
resolved.data = action.data;
resolved
})
.ok_or_else(|| GONE.to_string())
}
/// Run `lucisv.organizeImports`, or say why it cannot run.
pub fn execute(
ws: &Workspace,
arguments: &[Value],
) -> Result<(WorkspaceEdit, Vec<String>), String> {
let uri: Uri =
arguments.first().and_then(|value| serde_json::from_value(value.clone()).ok()).ok_or_else(
|| format!("{ORGANIZE_IMPORTS} wants a document URI as its first argument."),
)?;
let position: Position = arguments
.get(1)
.and_then(|value| serde_json::from_value(value.clone()).ok())
.ok_or_else(|| format!("{ORGANIZE_IMPORTS} wants a position as its second argument."))?;
let doc = ws
.document(&uri)
.ok_or_else(|| "lucisv can only organize the imports of an open file.".to_string())?;
let offset = doc.positions().offset(position);
let (path, files) = at(ws, &uri, offset).ok_or_else(|| NOTHING.to_string())?;
let refactoring = vlog_refactor::organize_imports(&files, &path, offset)?;
Ok((crate::ports::workspace_edit(ws, &refactoring)?, refactoring.warnings))
}
/// The cursor's file and the files the engine needs to judge its imports, or
/// nothing when there is no import run at this position at all.
///
/// The cheap gate first: `imported_packages` is one parse of one buffer and
/// answers "nothing here" for almost every cursor, which is what keeps a
/// `textDocument/codeAction` on every keystroke off the index.
fn at(ws: &Workspace, uri: &Uri, offset: u32) -> Option<(PathBuf, Vec<(PathBuf, String)>)> {
let doc = ws.document(uri)?;
let path = doc.path.clone()?;
let packages = vlog_refactor::imported_packages(&doc.text, offset);
if packages.is_empty() {
return None;
}
let files = sources(ws, &path, &doc.text, &packages);
Some((path, files))
}
/// The buffer, plus every file that declares one of the named packages or one
/// of the packages those re-export from.
///
/// **Every** declaration of a name, not the first: two packages called
/// `foo_pkg` is exactly the ambiguity the engine refuses over, and handing it
/// one of them would hide the refusal instead of making it.
///
/// `pub(crate)` for the test that pins exactly this set.
pub(crate) fn sources(
ws: &Workspace,
path: &Path,
text: &str,
packages: &[String],
) -> Vec<(PathBuf, String)> {
let mut sources = vec![(path.to_path_buf(), text.to_string())];
let mut queue: Vec<String> = packages.to_vec();
let mut seen: Vec<String> = Vec::new();
while let Some(name) = queue.pop() {
if seen.contains(&name) {
continue;
}
for def in ws.index().units(&name) {
let Some(declared_in) = ws.index().path(def.file) 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));
}
}
let onward: Vec<String> =
ws.index().reexported_packages(&name).iter().map(|p| (*p).to_string()).collect();
queue.extend(onward);
seen.push(name);
}
sources
}
/// What a lazily-offered action carries in place of its edit.
#[derive(Serialize, Deserialize)]
struct Offer {
uri: Uri,
position: Position,
}
const GONE: &str = "the action is no longer available.";
const NOT_OURS: &str = "this code action carries no lucisv import organization to resolve.";
const NOTHING: &str = "there is no import run to organize at this position.";
#[cfg(test)]
mod tests {
use super::*;
use crate::uri::path_to_uri;
use lsp_types::{Range, TextEdit};
use std::fs;
/// 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_imports_{}_{name}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("temp dir");
Tree { path }
}
fn write(&self, rel: &str, text: &str) -> PathBuf {
let path = self.path.join(rel);
fs::write(&path, text).expect("write");
path
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
const A_PKG: &str = "package a_pkg;\n typedef int a_t;\nendpackage\n";
const B_PKG: &str = "package b_pkg;\n typedef int b_t;\nendpackage\n";
const TOP: &str = "module top;\n import a_pkg::*;\n import b_pkg::*;\n b_t q;\nendmodule\n";
/// A three-file workspace with `top.sv` open.
fn opened(tree: &Tree) -> (Workspace, Uri) {
tree.write("a_pkg.sv", A_PKG);
tree.write("b_pkg.sv", B_PKG);
let top = tree.write("top.sv", TOP);
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(), TOP.to_string());
(ws, uri)
}
/// The byte offset of a needle in `TOP`.
fn at(needle: &str) -> u32 {
TOP.find(needle).expect("needle") as u32
}
fn edits_of(action: &CodeAction, uri: &Uri) -> Vec<TextEdit> {
action
.edit
.as_ref()
.expect("an edit")
.changes
.as_ref()
.expect("changes")
.get(uri)
.cloned()
.unwrap_or_default()
}
fn only(actions: Vec<CodeActionOrCommand>) -> Vec<CodeAction> {
actions
.into_iter()
.filter_map(|a| match a {
CodeActionOrCommand::CodeAction(action) => Some(action),
CodeActionOrCommand::Command(_) => None,
})
.collect()
}
#[test]
fn a_cursor_on_the_import_run_is_offered_the_action_with_its_counts() {
let tree = Tree::new("offer");
let (ws, uri) = opened(&tree);
let actions = only(code_actions(&ws, &uri, at("import a_pkg")));
let [action] = actions.as_slice() else { panic!("one action, got {actions:?}") };
assert_eq!(action.title, "lucisv: organize imports (removes 1, sorts 1)");
assert_eq!(action.kind, Some(CodeActionKind::SOURCE_ORGANIZE_IMPORTS));
let edits = edits_of(action, &uri);
assert_eq!(edits.len(), 1, "{edits:?}");
assert_eq!(edits[0].new_text, " import b_pkg::*;");
}
#[test]
fn a_cursor_in_the_body_is_offered_nothing() {
let tree = Tree::new("body");
let (ws, uri) = opened(&tree);
assert!(code_actions(&ws, &uri, at("b_t q")).is_empty());
}
#[test]
fn the_lazy_offer_carries_no_edit_and_resolve_supplies_one() {
let tree = Tree::new("resolve");
let (ws, uri) = opened(&tree);
let position = Position { line: 1, character: 2 };
let offered = only(offers(&ws, &uri, position, at("import a_pkg")));
let [offer] = offered.as_slice() else { panic!("one offer, got {offered:?}") };
assert!(offer.edit.is_none(), "the offer reads no fan-out");
assert!(offer.data.is_some(), "and carries what resolve needs");
let resolved = resolve(&ws, offer.clone()).expect("resolves");
assert_eq!(resolved.title, offer.title, "the title never changes under the user");
assert_eq!(edits_of(&resolved, &uri).len(), 1);
}
#[test]
fn an_action_from_somewhere_else_is_not_ours_to_resolve() {
let tree = Tree::new("not_ours");
let (ws, _) = opened(&tree);
let stranger = CodeAction { title: "someone else's".into(), ..Default::default() };
assert_eq!(resolve(&ws, stranger), Err(NOT_OURS.to_string()));
}
#[test]
fn the_command_organizes_at_a_position() {
let tree = Tree::new("command");
let (ws, uri) = opened(&tree);
let arguments = vec![
serde_json::to_value(&uri).expect("uri"),
serde_json::to_value(Position { line: 1, character: 2 }).expect("position"),
];
let (edit, warnings) = execute(&ws, &arguments).expect("organizes");
assert!(warnings.is_empty(), "{warnings:?}");
let edits = edit.changes.as_ref().expect("changes").get(&uri).expect("this file").clone();
assert_eq!(edits.len(), 1);
assert_eq!(edits[0].new_text, " import b_pkg::*;");
}
#[test]
fn the_command_says_why_when_there_is_nothing_to_organize() {
let tree = Tree::new("nothing");
let (ws, uri) = opened(&tree);
let arguments = vec![
serde_json::to_value(&uri).expect("uri"),
serde_json::to_value(Position { line: 3, character: 2 }).expect("position"),
];
assert_eq!(execute(&ws, &arguments), Err(NOTHING.to_string()));
}
#[test]
fn the_file_set_is_the_buffer_and_the_packages_it_imports() {
let tree = Tree::new("sources");
let (ws, uri) = opened(&tree);
let path = ws.document(&uri).expect("open").path.clone().expect("path");
let files = sources(&ws, &path, TOP, &["a_pkg".to_string(), "b_pkg".to_string()]);
let mut names: Vec<String> = files
.iter()
.map(|(p, _)| p.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string())
.collect();
names.sort();
assert_eq!(names, vec!["a_pkg.sv", "b_pkg.sv", "top.sv"]);
}
#[test]
fn a_client_asking_only_for_organize_imports_is_answered() {
// The way organize-on-save asks: `only: ["source.organizeImports"]`.
let filter = [CodeActionKind::SOURCE_ORGANIZE_IMPORTS];
assert!(crate::code_action::wanted(Some(&filter), &kind()));
assert!(!crate::code_action::wanted(
Some(&filter),
&CodeActionKind::new(crate::ports::REFACTOR_PORTS)
));
// And a request for the quick fixes alone does not reach us.
let quick = [CodeActionKind::QUICKFIX];
assert!(!crate::code_action::wanted(Some(&quick), &kind()));
let _ = Range::default();
}
}
+120 -4
View File
@@ -22,7 +22,7 @@
use std::collections::HashMap;
use lsp_types::{InlayHint, InlayHintKind, InlayHintLabel, Range, Uri};
use vlog_parser::ast::{Connections, Expr, Instance, Instantiation};
use vlog_parser::ast::{Connection, Connections, Expr, Instance, Instantiation, ListElem};
use vlog_parser::TextRange;
use vlog_refactor::InstantiationPlan;
use vlog_semantic::instantiations;
@@ -84,6 +84,13 @@ enum Kind {
/// name is written somewhere in the same list.
fn param_sites(inst: &Instantiation) -> Vec<Site> {
let Some(params) = &inst.params else { return Vec::new() };
// A list a tolerant parse recovered inside gets no hints either: which
// parameter a position names is exactly what the skipped text decides, so
// any hint here would be a guess, and a wrong hint is worse than none.
if params.iter().any(ListElem::is_error) {
return Vec::new();
}
let params: Vec<&Connection> = params.iter().filter_map(ListElem::ok).collect();
if params.iter().any(|param| !param.name.is_empty()) {
return Vec::new();
}
@@ -99,7 +106,16 @@ fn param_sites(inst: &Instantiation) -> Vec<Site> {
/// instance: the connections are the module's ports either way.
fn port_sites(instance: &Instance) -> Vec<Site> {
let Connections::Ordered(conns) = &instance.conns else { return Vec::new() };
conns.iter().enumerate().filter_map(|(index, conn)| site(index, conn.expr.as_ref())).collect()
// As in `param_sites`: a recovered list's positions are a guess.
if conns.iter().any(ListElem::is_error) {
return Vec::new();
}
conns
.iter()
.filter_map(ListElem::ok)
.enumerate()
.filter_map(|(index, conn)| site(index, conn.expr.as_ref()))
.collect()
}
/// A site at the start of `expr`, or nothing for an omitted position
@@ -542,10 +558,23 @@ endmodule
assert_eq!(hints[1], (2, 10, "clk:".to_string()), "the line before it had é and 🎉");
}
/// A buffer mid-edit still hints where the *positions* are known, and
/// stops where they are not.
///
/// Header recovery (TODO §32) changed the first half: `sub u1 (clk, rst_n`
/// used to fail to parse at all, so there was nothing to hint from. Now
/// the instantiation survives with both positional connections, and both
/// are at the index they were written at, so both are hinted. The second
/// half is the rule that replaces "does not parse": a list the parser
/// *recovered* inside holds text nobody can index, so `port_sites` and
/// `param_sites` decline the whole list rather than mislabel what follows
/// the hole.
#[test]
fn a_buffer_that_does_not_parse_hints_nothing_rather_than_guessing() {
fn a_truncated_list_hints_and_a_recovered_one_does_not() {
let top = "module top;\n sub u1 (clk, rst_n\n";
assert!(hints_of("broken", top).is_empty());
assert_eq!(labels(&hints_of("truncated", top)), ["clk:", "rst_n:"]);
let holed = "module top;\n sub u1 (clk, .\n wire w;\nendmodule\n";
assert!(hints_of("recovered", holed).is_empty());
}
#[test]
@@ -563,6 +592,7 @@ endmodule
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let insts = instantiations::sites(&tree.items);
let params = insts[0].inst.params.as_ref().expect("a `#( ... )`");
let params: Vec<_> = params.iter().filter_map(ListElem::ok).collect();
assert_eq!(params[0].name, "", "`8` names nothing");
assert_eq!(params[1].name, "DEPTH", "`.DEPTH(16)` does");
}
@@ -725,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`.
+40 -4
View File
@@ -575,6 +575,7 @@ mod tests {
use crate::uri::path_to_uri;
use std::path::PathBuf;
use std::str::FromStr;
use vlog_parser::PARSE_STACK_SIZE;
/// A one-file workspace with `path` open and the cursor at `needle`'s end.
/// No files on disk: nothing here reads the index.
@@ -1081,10 +1082,31 @@ endmodule
// A trailing newline, so this test isolates depth from the separate
// true-end-of-file `Eof`-adjacency case pinned above.
text.push_str("initial begin\n");
let (ws, uri, position) = asking(&text, "initial begin");
assert!(!ws.document(&uri).expect("open").tokens.is_empty(), "the lexer never recurses");
let items = inline_completions(&ws, &uri, position);
assert!(items.is_some(), "the innermost, truly unclosed `begin` still offers its `end`");
// Opening the document *parses* it, and since §36.1 a bare `begin` at
// item scope is a generate block the tolerant parser descends into —
// so this text nests the parser to `MAX_NESTING_DEPTH` and costs ~4
// MiB of stack in a debug build. That is exactly what
// `PARSE_STACK_SIZE` is for; every production thread that may reach a
// parse is given it (`main.rs`), libtest's own thread is not, so the
// body runs on one of its own. Nothing here is about the inline path,
// which still never recurses.
std::thread::Builder::new()
.stack_size(PARSE_STACK_SIZE)
.spawn(move || {
let (ws, uri, position) = asking(&text, "initial begin");
assert!(
!ws.document(&uri).expect("open").tokens.is_empty(),
"the lexer never recurses"
);
let items = inline_completions(&ws, &uri, position);
assert!(
items.is_some(),
"the innermost, truly unclosed `begin` still offers its `end`"
);
})
.expect("spawn")
.join()
.expect("the inline path crashed");
}
#[test]
@@ -1894,6 +1916,20 @@ sub #(
}
}
/// The premise the "the accepted text must parse" probe above rests on:
/// the probe can still fail. Header recovery (TODO §32) widened what a
/// tolerant parse reads — a half-typed connection list is now a recovered
/// instantiation rather than a dead item — so the probe is only worth
/// asking while text that does not parse still says so.
#[test]
fn the_accepted_text_probe_still_reports_text_that_does_not_parse() {
let probe = "module lucisv_probe;\n logic clk;\n sub u_sub (.clk(\nendmodule\n";
assert!(
!vlog_parser::parse_source_tolerant(probe).1.is_empty(),
"recovery must not make a broken instantiation look clean"
);
}
#[test]
fn a_module_with_no_ports_ghosts_a_sane_instantiation() {
let top = "module top;\n bare \nendmodule\n";
+249
View File
@@ -0,0 +1,249 @@
//! Inline a module at the cursor, on the wire: `textDocument/codeAction` under
//! LSP's own `refactor.inline`, and `workspace/executeCommand` for the editors
//! that have no lightbulb.
//!
//! Protocol only. The edit is `vlog_refactor::inline_module`; this module
//! decides which files that engine is handed, turns its answer into a
//! `WorkspaceEdit` and its refusal into a request error.
//!
//! **The action carries a command, not an edit**, for the same reason the
//! extraction's does — laziness rather than a prompt. Answering "what would
//! inlining `S` here look like" means reading `S`'s file, every file that
//! spells it, and analyzing all of them; a `textDocument/codeAction` arrives
//! on every cursor move. So the offer is one parse of one buffer
//! (`vlog_refactor::inline_site`) plus a `Command` naming [`INLINE_MODULE`],
//! and the workspace is not touched until the user picks the action. See
//! `docs/features/extract-inline-module/README.md`.
// See `rename.rs` for why this is a `WorkspaceEdit`'s problem and not ours.
#![allow(clippy::mutable_key_type)]
use lsp_types::{
CodeAction, CodeActionKind, CodeActionOrCommand, Command, Position, Range, Uri, WorkspaceEdit,
};
use serde_json::Value;
use crate::state::Workspace;
/// Inline the module instantiated at a position: `[uri, position]`.
pub const INLINE_MODULE: &str = "lucisv.inlineModule";
/// Every command this module executes.
pub fn commands() -> Vec<String> {
vec![INLINE_MODULE.to_string()]
}
/// The kind LSP reserves for an inline, which is what an editor's "Refactor…"
/// menu asks for by name.
pub fn kind() -> CodeActionKind {
CodeActionKind::REFACTOR_INLINE
}
/// The action for the cursor, carrying the command that does the work.
pub fn code_actions(ws: &Workspace, uri: &Uri, range: Range) -> Vec<CodeActionOrCommand> {
let Some(doc) = ws.document(uri) else { return Vec::new() };
if doc.path.is_none() {
// An `untitled:` buffer has no path for the engine's file set; nothing
// is offered rather than offered and refused.
return Vec::new();
}
let offset = doc.positions().offset(range.start);
let Some(site) = vlog_refactor::inline_site(&doc.text, offset) else { return Vec::new() };
let arguments = vec![
serde_json::to_value(uri).unwrap_or(Value::Null),
serde_json::to_value(range.start).unwrap_or(Value::Null),
];
let title = vlog_refactor::inline_title(&site.module);
vec![CodeActionOrCommand::CodeAction(CodeAction {
title: title.clone(),
kind: Some(kind()),
command: Some(Command {
title,
command: INLINE_MODULE.to_string(),
arguments: Some(arguments),
}),
..Default::default()
})]
}
/// Run `lucisv.inlineModule`, or say why it cannot run.
pub fn execute(
ws: &Workspace,
arguments: &[Value],
) -> Result<(WorkspaceEdit, Vec<String>), String> {
let uri: Uri = argument(arguments, 0, "a document URI")?;
let position: Position = argument(arguments, 1, "a position")?;
let doc =
ws.document(&uri).ok_or_else(|| "lucisv can only inline in an open file.".to_string())?;
let path = doc
.path
.clone()
.ok_or_else(|| "lucisv can only inline in a file that has been saved.".to_string())?;
let offset = doc.positions().offset(position);
let Some(site) = vlog_refactor::inline_site(&doc.text, offset) else {
return Err(NOTHING.to_string());
};
// The engine reads the instantiated module's declaration and refuses over
// any hierarchical path into the instance, so the file set is the two
// units' own fan-out: the declaring file, and every file the index says
// mentions either name.
let files = ws.module_sources(&path, &site.units);
let refactoring = vlog_refactor::inline_module(&files, &path, offset)?;
Ok((crate::ports::workspace_edit(ws, &refactoring)?, refactoring.warnings))
}
fn argument<T: serde::de::DeserializeOwned>(
arguments: &[Value],
n: usize,
what: &str,
) -> Result<T, String> {
arguments
.get(n)
.and_then(|value| serde_json::from_value(value.clone()).ok())
.ok_or_else(|| format!("{INLINE_MODULE} wants {what} as argument {}.", n + 1))
}
const NOTHING: &str = "there is no module instantiation at this position to inline.";
#[cfg(test)]
mod tests {
use super::*;
use crate::uri::path_to_uri;
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_inline_{}_{name}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("temp dir");
Tree { path }
}
fn write(&self, rel: &str, text: &str) {
fs::write(self.path.join(rel), text).expect("write");
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
const SUB: &str = "\
module sub (
input logic a,
output logic q
);
logic s; // the and
assign s = a;
assign q = s;
endmodule
";
const TOP: &str = "\
module top (
input logic x,
output logic z
);
sub u_sub (
.a(x),
.q(z)
);
endmodule
";
fn opened(tree: &Tree) -> (Workspace, Uri) {
tree.write("sub.sv", SUB);
tree.write("top.sv", TOP);
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&tree.path.join("top.sv")).expect("uri");
ws.set_document(uri.clone(), TOP.to_string());
(ws, uri)
}
/// The cursor on the `sub` of `sub u_sub (`.
fn cursor() -> Range {
let at = Position { line: 4, character: 4 };
Range { start: at, end: at }
}
#[test]
fn the_cursor_on_an_instantiation_is_offered_the_action_with_its_command() {
let tree = Tree::new("offer");
let (ws, uri) = opened(&tree);
let actions = code_actions(&ws, &uri, cursor());
let [CodeActionOrCommand::CodeAction(action)] = actions.as_slice() else {
panic!("one action, got {actions:?}")
};
assert_eq!(action.title, "lucisv: inline `sub` here");
assert_eq!(action.kind, Some(CodeActionKind::REFACTOR_INLINE));
assert!(action.edit.is_none(), "the offer reads no workspace");
let command = action.command.as_ref().expect("a command");
assert_eq!(command.command, INLINE_MODULE);
assert_eq!(command.arguments.as_ref().expect("arguments").len(), 2);
}
#[test]
fn a_cursor_on_anything_else_is_offered_nothing() {
let tree = Tree::new("nothing");
let (ws, uri) = opened(&tree);
let elsewhere = Range {
start: Position { line: 1, character: 4 },
end: Position { line: 1, character: 4 },
};
assert!(code_actions(&ws, &uri, elsewhere).is_empty());
}
#[test]
fn the_command_replaces_the_instantiation_with_the_body() {
let tree = Tree::new("run");
let (ws, uri) = opened(&tree);
let arguments = vec![
serde_json::to_value(&uri).expect("uri"),
serde_json::to_value(cursor().start).expect("position"),
];
let (edit, warnings) = execute(&ws, &arguments).expect("inlines");
let changes = edit.changes.as_ref().expect("changes");
assert_eq!(changes.len(), 1, "only the file the cursor is in is edited");
let written = &changes.get(&uri).expect("this file")[0].new_text;
assert!(written.contains("assign s = x;"), "{written}");
assert!(written.contains("// the and"), "{written}");
assert!(warnings.iter().any(|w| w.contains("still declared where it was")), "{warnings:?}");
}
#[test]
fn the_command_says_why_when_there_is_nothing_to_inline() {
let tree = Tree::new("refuse");
let (ws, uri) = opened(&tree);
let arguments = vec![
serde_json::to_value(&uri).expect("uri"),
serde_json::to_value(Position { line: 1, character: 4 }).expect("position"),
];
assert_eq!(execute(&ws, &arguments), Err(NOTHING.to_string()));
}
#[test]
fn the_command_wants_both_of_its_arguments() {
let tree = Tree::new("arguments");
let (ws, uri) = opened(&tree);
let short = vec![serde_json::to_value(&uri).expect("uri")];
let message = execute(&ws, &short).expect_err("a refusal");
assert!(message.contains("argument 2"), "{message}");
}
#[test]
fn a_client_asking_only_for_refactor_inline_is_answered() {
let filter = [CodeActionKind::REFACTOR_INLINE];
assert!(crate::code_action::wanted(Some(&filter), &kind()));
assert!(!crate::code_action::wanted(Some(&filter), &CodeActionKind::QUICKFIX));
}
}
+1
View File
@@ -144,6 +144,7 @@ fn item_pairs(item: &Item, out: &mut Vec<Pair>) {
ItemKind::Task(t) => task_pairs(t, out),
ItemKind::Clocking(c) => clocking_pairs(c, out),
ItemKind::GenerateRegion { items, .. } => items_pairs(items, out),
ItemKind::GenBlock(b) => items_pairs(&b.items, out),
ItemKind::GenIf(g) => gen_if_pairs(g, out),
ItemKind::GenFor(g) => gen_block_pairs(&g.body, out),
ItemKind::GenCase(g) => {
+557 -24
View File
@@ -10,16 +10,32 @@
//! table `lucisv.toml` now carries. See
//! `docs/features/semantic-lints-on/README.md` and
//! `docs/features/server-lint/README.md`.
//!
//! Since §42 the two halves of that selection are one contract: the editor's
//! settings play the role the CLI's flags play, and the project's `[lint]`
//! table is what stands when the editor says nothing —
//! `docs/features/lint-config-contract/README.md`, and [`project`] for the
//! project's half.
mod project;
pub use project::{ConfigProblems, ProblemLog, ProjectLint};
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString};
use lucisv_core::config::FileConfig;
use vlog_formatter::fence::{self, Region};
use vlog_linter::{
default_rules, lint, workspace_rules, LintContext, MentionOracle, Rule, Violation,
default_rules, lint_with, workspace_rules, Exports, ExternalWaivers, LintContext,
MentionOracle, ModuleInterface, Rule, RuleOptions, Severity, Violation,
};
use vlog_semantic::{FileId, WorkspaceIndex};
use vlog_semantic::{FileId, SymbolKind, WorkspaceIndex};
use crate::convert::Positions;
use crate::diagnostics::SOURCE;
use crate::settings::ClientSettings;
use crate::state::{Document, Workspace};
/// What one lint pass runs: which rules, and what it may ask about the files
@@ -31,14 +47,39 @@ use crate::state::{Document, Workspace};
pub struct LintRun<'a> {
rules: Vec<&'static dyn Rule>,
oracle: Option<IndexMentions<'a>>,
/// What the buffer's `lucisv.toml` and the editor's settings configured
/// about each rule, merged. Empty means every rule reads its own default.
options: RuleOptions,
/// The width `line-length` holds this buffer to — the width the formatter
/// would wrap it to, so the two halves of lucisv cannot disagree.
line_length: usize,
/// The external waiver files in force for this buffer, from its
/// `lucisv.toml` and from `lucisv.lint.waivers`. Empty unless one is
/// configured, and then costing the pass nothing.
external: ExternalWaivers,
/// What the buffer's `lucisv.toml` asked for and did not get. Reported by
/// whoever can talk to the client — [`ProblemLog`] keeps it to once per
/// (config file, message) — and never fatal here: §42.2.
problems: ConfigProblems,
}
impl Default for LintRun<'_> {
fn default() -> LintRun<'static> {
LintRun { rules: default_rules(), oracle: None }
LintRun {
rules: default_rules(),
oracle: None,
options: RuleOptions::new(),
line_length: DEFAULT_LINE_LENGTH,
external: ExternalWaivers::default(),
problems: ConfigProblems::default(),
}
}
}
/// The width a buffer is held to when neither its `lucisv.toml` nor the
/// editor says otherwise — `vlog_formatter::Config`'s own default.
const DEFAULT_LINE_LENGTH: usize = 100;
impl<'a> LintRun<'a> {
/// The pass this workspace's settings and index describe for one buffer.
///
@@ -52,19 +93,41 @@ impl<'a> LintRun<'a> {
let index = ws.index();
let own = doc.path.as_deref().and_then(|path| index.file_id(path));
let workspace = index.files().len() > usize::from(own.is_some());
let client = ws.client_settings();
// Every name in the settings was checked against the registry when the
// settings were parsed, so this cannot fail; if it somehow does, the
// defaults are the answer a dropped setting always gets here.
let rules = vlog_linter::select_rules(&client.lint_select, &client.lint_ignore, workspace)
.unwrap_or_else(|_| if workspace { workspace_rules() } else { default_rules() });
let oracle = workspace.then_some(IndexMentions { index, own });
LintRun { rules, oracle }
// One discovery for the whole pass: the selection, the options, the
// width and the waiver paths all read the same `FileConfig`, so
// reading the project's rules costs no extra stat and no extra open.
let (options, line_length, file, mut messages) = configured(ws.client_settings(), doc);
let (from_file, bad_names) = ProjectLint::read(&file);
messages.extend(bad_names);
let rules = enabled_rules(ws.client_settings(), &from_file, workspace);
let (mut external, bad_waivers) = external_waivers(&project_waivers(&file));
messages.extend(bad_waivers);
// The editor's own waiver files are read separately and their
// problems dropped: `notification::apply_settings` already said them
// once, where the setting arrived.
external.absorb(external_waivers(&editor_waivers(ws.client_settings(), ws.roots())).0);
let problems = ConfigProblems::new(&file, messages);
LintRun { rules, oracle, options, line_length, external, problems }
}
/// What this buffer's `lucisv.toml` asked for and did not get, for a
/// caller that can tell the user about it.
pub fn config_problems(&self) -> &ConfigProblems {
&self.problems
}
/// A run carrying these external waivers — for the tests that pin what a
/// waiver keeps out of the code actions.
#[cfg(test)]
pub(crate) fn with_external(mut self, external: ExternalWaivers) -> Self {
self.external = external;
self
}
/// This run's context over a buffer's own parse products.
fn context<'d>(&'d self, doc: &'d Document) -> LintContext<'d> {
let ctx = context(doc);
let ctx = context(doc).with_options(&self.options).with_line_length(self.line_length);
match &self.oracle {
Some(oracle) => ctx.with_oracle(oracle),
None => ctx,
@@ -72,6 +135,202 @@ impl<'a> LintRun<'a> {
}
}
/// The per-rule options and the line width governing one buffer.
///
/// **Precedence for an option, highest first: the editor, then the buffer's
/// `lucisv.toml`, then the rule's own default — key by key**, so a project
/// that sets two options and a user who overrides one keep the other. This is
/// deliberately the *opposite* order to `format::settings_for`, where a
/// checked-in `lucisv.toml` outranks the editor: formatting has a byte-exact
/// contract with CI that a user's editor must not break, while a lint option
/// changes which findings that user is shown in their own editor and is
/// theirs to set. §34.0(d).
///
/// The **width** follows the formatting ladder instead, because it is not a
/// lint setting at all: it is the width the formatter would wrap this buffer
/// to, read the same way `format::settings_for` reads it, so a line lucisv
/// wrote is never a line lucisv calls too long. `line-length`'s own `length`
/// option still beats it — that is the rule's own business, and the rule
/// applies it.
///
/// The config file is read here, per pass, exactly as `format::discover`
/// reads it per formatting request: a `lucisv.toml` edited while the server
/// runs takes effect at the next publish, and the read is a few stats beside
/// a parse and an analysis the same pass already paid for.
fn configured(
client: &ClientSettings,
doc: &Document,
) -> (RuleOptions, usize, FileConfig, Vec<String>) {
let file = doc
.path
.as_deref()
.and_then(|path| lucisv_core::config::Discovery::new(true).for_file(path).ok())
.unwrap_or_default();
let mut options = RuleOptions::new();
let mut problems = Vec::new();
for entry in &file.lint_options {
// A broken entry in the file is dropped rather than fatal — an editor
// cannot fail a run — but it is *said*, in the words `lucisv check`
// fails with, once per (config file, entry): §42.2. Silently dropping
// it left a user's option doing nothing with nothing to read about it.
if let Err(problem) = options.set_raw(&entry.rule, &entry.key, &entry.raw) {
let source = file
.source
.as_ref()
.map_or_else(|| "lucisv.toml".to_string(), |path| path.display().to_string());
problems.push(format!("{source}:{}: rule `{}` {problem}", entry.line, entry.rule));
}
}
options.overlay(&client.lint_options);
let width = file.line_length.or(client.line_length).unwrap_or(DEFAULT_LINE_LENGTH);
(options, width, file, problems)
}
/// The waiver files governing one buffer: its `lucisv.toml`'s `[lint] waivers`
/// first, then `lucisv.lint.waivers` from the editor.
///
/// The two **add up**, the way they do on the command line — a waiver file
/// only ever suppresses findings, so there is nothing here for one list to
/// take back from the other. A relative setting path is resolved against the
/// first workspace root, exactly as `lucisv.filelist` is; a `lucisv.toml`'s
/// paths were already resolved against that file's own directory.
pub fn waiver_paths(client: &ClientSettings, roots: &[PathBuf], file: &FileConfig) -> Vec<PathBuf> {
let mut paths = project_waivers(file);
paths.extend(editor_waivers(client, roots));
paths
}
/// The `[lint] waivers` of one config file, already resolved by `Discovery`
/// against that file's own directory.
///
/// Read apart from the editor's since §42.2, because a problem in one of
/// *these* is the project's and belongs in the output channel with the
/// `lucisv.toml` that named it, while a problem in the editor's was already
/// said where the setting arrived.
fn project_waivers(file: &FileConfig) -> Vec<PathBuf> {
file.lint_waivers.iter().flatten().cloned().collect()
}
/// The waiver files `lucisv.lint.waivers` names, a relative one anchored at
/// the first workspace root exactly as `lucisv.filelist` is.
fn editor_waivers(client: &ClientSettings, roots: &[PathBuf]) -> Vec<PathBuf> {
client
.lint_waivers
.iter()
.map(|setting| {
let path = Path::new(setting);
match roots.first() {
Some(root) if path.is_relative() => root.join(path),
_ => path.to_path_buf(),
}
})
.collect()
}
/// Those files, read: the waivers and one message per file or line that could
/// not be used.
///
/// **Nothing here is fatal.** A push arrives on a socket and a bad path in it
/// must never cost a user every diagnostic in their file — this module's
/// standing rule, and `settings::rule_options`'. The messages are logged once,
/// when the settings arrive (`server::notification::apply_settings`); the lint
/// pass, which runs on every keystroke, drops them silently rather than
/// logging the same line a hundred times.
pub fn external_waivers(paths: &[PathBuf]) -> (ExternalWaivers, Vec<String>) {
let mut waivers = ExternalWaivers::default();
let mut problems = Vec::new();
for path in paths {
match ExternalWaivers::read(path) {
Ok((file, bad)) => {
problems.extend(bad);
waivers.absorb(file);
}
Err(problem) => problems.push(problem),
}
}
(waivers, problems)
}
/// Which rules a buffer is linted with, given what the editor's settings and
/// the buffer's own `lucisv.toml` say.
///
/// **The one ladder**, top rung last — every rung may undo the one above it:
///
/// 1. the base set is what the rules themselves declare: `default_on`, plus
/// the `needs_workspace` rules when `has_oracle`;
/// 2. a non-empty `lucisv.lint.select` **replaces** that base set, exactly as
/// `--select` replaces it on the command line; when the editor names
/// nothing, the project's `[lint] select` replaces it instead — the flag
/// when there is one, else the file, which is `lucisv check`'s own `pick`;
/// 3. a `lucisv.lint.severity.<class>` switched off **removes** every rule of
/// that class;
/// 4. a `lucisv.lint.rules.<name>` set to `on` or `off` sets or clears that
/// one rule — the per-rule word beats the class word, which is what makes
/// "all style off except `no-tabs`" expressible;
/// 5. `lucisv.lint.ignore` **removes** — the off switch of last resort, the
/// one a user reaches for when nothing else worked; when the editor names
/// nothing there either, the project's `[lint] ignore` removes instead.
///
/// Rungs 3 and 4 are the **editor's alone**: a `lucisv.toml` has no such
/// keys, and the command line has no such flags. Rungs 2 and 5 are decided
/// independently — a project that selects and a user who only ignores keep
/// both halves. Every list accepts a severity word wherever a rule name fits,
/// the project's as much as the editor's.
pub fn enabled_rules(
settings: &ClientSettings,
project: &ProjectLint,
has_oracle: bool,
) -> Vec<&'static dyn Rule> {
let select = pick(&settings.lint_select, &project.select);
let base = if select.is_empty() {
if has_oracle {
workspace_rules()
} else {
default_rules()
}
} else {
named(select)
};
let mut on: BTreeSet<&'static str> = base.iter().map(|rule| rule.name()).collect();
for (severity, class_on) in &settings.lint_severity {
if !class_on {
on.retain(|name| {
vlog_linter::rule_by_name(name).is_some_and(|rule| rule.severity() != *severity)
});
}
}
for (name, wanted) in &settings.lint_rules {
let Some(rule) = vlog_linter::rule_by_name(name) else { continue };
if *wanted {
on.insert(rule.name());
} else {
on.remove(rule.name());
}
}
for rule in named(pick(&settings.lint_ignore, &project.ignore)) {
on.remove(rule.name());
}
vlog_linter::all_rules().into_iter().filter(|rule| on.contains(rule.name())).collect()
}
/// The editor's list when it said anything, else the project's — the twin of
/// `lucisv/src/lint.rs`'s `pick`, which is the whole of §42's contract.
fn pick<'a>(editor: &'a [String], project: &'a [String]) -> &'a [String] {
if editor.is_empty() {
project
} else {
editor
}
}
/// Every rule a list of `--select`-style words names, unknown words skipped —
/// they were already dropped when the settings were parsed, and a name that
/// survived that filter always resolves.
fn named(words: &[String]) -> Vec<&'static dyn Rule> {
words.iter().filter_map(|word| vlog_linter::rules_named(word)).flatten().collect()
}
/// The workspace index, asked the one question a lint rule may ask about other
/// files.
///
@@ -97,6 +356,44 @@ impl MentionOracle for IndexMentions<'_> {
fn mentioned_elsewhere(&self, name: &str) -> bool {
self.index.mentioned_outside(name, self.own)
}
/// The ports and overridable parameters of an indexed module or interface,
/// read off the index's member table — the very table a `.port` completion
/// list is offered from, so a connection lucisv would have completed is
/// never one it then calls unknown.
///
/// `None` for a unit the index does not hold, and for one it holds **more
/// than once**: two modules of a name are two different headers, and
/// answering with either would make an Error-class rule guess. A
/// `localparam` is left out, because it is not overridable.
fn module_interface(&self, name: &str) -> Option<ModuleInterface> {
let units = self.index.units(name);
let [unit] = units else { return None };
if !unit.kind.is_instantiable() {
return None;
}
let mut interface = ModuleInterface::default();
for (member, defs) in self.index.members_of(name) {
match defs.first().map(|def| def.kind) {
Some(SymbolKind::Port) => interface.ports.push(member.to_string()),
Some(SymbolKind::Param) => interface.parameters.push(member.to_string()),
_ => {}
}
}
Some(interface)
}
/// Every name a package exports, read off the index's member table — the
/// same `WorkspaceIndex` answer `vlog_refactor`'s organize-imports engine
/// gets, so the squiggle and the lightbulb cannot disagree about which
/// import is dead.
///
/// `Unknown` for a package the index does not hold and `Ambiguous` for one
/// it holds twice; `vlog_semantic::import_usage` refuses to judge in either
/// case rather than guess.
fn package_exports(&self, package: &str) -> Exports {
vlog_semantic::PackageExports::exports(self.index, package)
}
}
/// The document's own parse products, lent to the linter — "one parse, two
@@ -117,8 +414,13 @@ fn context(doc: &Document) -> LintContext<'_> {
///
/// This is the diagnostics path, which never looks at a fix, so the width a
/// `no-tabs` fix would expand a tab to is left at the linter's own default.
/// The external waivers apply here exactly as the inline ones do, as a union.
/// Which of them *fired* is discarded: only a whole run can tell whether a
/// waiver was dead, and a server never has one — it lints the buffers a user
/// happens to have open. `lucisv check` is what reports an unused external
/// waiver; see `docs/features/waiver-files/README.md`.
pub fn violations_in(doc: &Document, run: &LintRun) -> Vec<Violation> {
lint(&run.context(doc), &run.rules)
lint_with(&run.context(doc), &run.rules, &run.external).0
}
/// The findings a code action may offer a fix for, with their fixes built for
@@ -135,8 +437,14 @@ pub fn violations_in(doc: &Document, run: &LintRun) -> Vec<Violation> {
/// just has no lightbulb. Which bytes count as fenced is
/// [`fence::protected_regions`]' answer, the one the CLI asks too; see
/// `docs/features/shared-fence-filter/README.md`.
pub fn fixable(doc: &Document, tab_width: usize) -> Vec<Violation> {
let found = lint(&context(doc).with_tab_width(tab_width), &default_rules());
pub fn fixable(run: &LintRun, doc: &Document, tab_width: usize) -> Vec<Violation> {
// The buffer's own run: its enabled rules and its external waiver files,
// so a fix is never offered — nor applied by fix-on-save — for a finding
// the diagnostics pass would not have shown. Found by §39's QA: with
// `default_rules()` and no waivers here, `source.fixAll.lucisv` rewrote a
// line a checked-in waiver file had waived.
let ctx = run.context(doc).with_tab_width(tab_width);
let found = lint_with(&ctx, &run.rules, &run.external).0;
// One tolerant parse per code-action request: `protected_regions` takes
// text and parses internally, on purpose — one fence answer for every
// front end, none of which can feed it a stale tree (see
@@ -175,14 +483,13 @@ pub fn diagnostics_in(doc: &Document, run: &LintRun) -> Vec<Diagnostic> {
/// The diagnostic a violation becomes.
///
/// **Warning**, never Error: a lint finding is an opinion about style, and a
/// parse error is the compiler refusing. The `code` is the rule's stable name,
/// which is what a user needs to write a waiver or an `--ignore`, and what a
/// code action matches on.
/// The editor's severity is the rule's own class ([`severity_of`]). The `code`
/// is the rule's stable name, which is what a user needs to write a waiver or
/// an `--ignore`, and what a code action matches on.
pub fn diagnostic(positions: &Positions<'_>, violation: &Violation) -> Diagnostic {
Diagnostic {
range: positions.diagnostic_range(violation.span),
severity: Some(DiagnosticSeverity::WARNING),
severity: Some(severity_of(violation.severity)),
code: Some(NumberOrString::String(violation.rule.to_string())),
source: Some(SOURCE.to_string()),
message: violation.message.clone(),
@@ -190,6 +497,21 @@ pub fn diagnostic(positions: &Positions<'_>, violation: &Violation) -> Diagnosti
}
}
/// How an editor is asked to paint one class.
///
/// `error` is the red squiggle a compiler error gets — a rule only claims it
/// when the code would very likely not build, which is why the Error class is
/// held to the silence-when-unsure rule. `style` deliberately stops short of
/// `HINT`: a hint is invisible in most themes and would make the style rules
/// look broken rather than quiet.
fn severity_of(severity: Severity) -> DiagnosticSeverity {
match severity {
Severity::Error => DiagnosticSeverity::ERROR,
Severity::Warning => DiagnosticSeverity::WARNING,
Severity::Style => DiagnosticSeverity::INFORMATION,
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -206,18 +528,57 @@ mod tests {
(ws, uri)
}
#[test]
fn the_index_answers_what_a_package_exports() {
// The handshake `unused-import` reads: the server's oracle hands the
// rule the very member table `vlog_refactor`'s engine reads, so a
// squiggle and a lightbulb cannot disagree about a dead import.
let index = WorkspaceIndex::build([(
PathBuf::from("/rtl/a_pkg.sv"),
"package a_pkg;\n typedef int a_t;\nendpackage\n",
)]);
let oracle = IndexMentions { index: &index, own: None };
match oracle.package_exports("a_pkg") {
Exports::Known(names) => assert!(names.iter().any(|n| n == "a_t"), "{names:?}"),
other => panic!("an indexed package is known: {other:?}"),
}
assert_eq!(oracle.package_exports("nowhere_pkg"), Exports::Unknown);
}
#[test]
fn a_tab_becomes_one_warning_carrying_its_rule_name() {
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
let diags = diagnostics(ws.document(&uri).expect("open"));
assert_eq!(diags.len(), 1);
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::WARNING));
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::INFORMATION), "no-tabs is style");
assert_eq!(diags[0].code, Some(NumberOrString::String("no-tabs".into())));
assert_eq!(diags[0].source.as_deref(), Some("lucisv"));
assert_eq!(diags[0].range.start.line, 1);
assert!(diags[0].range.start < diags[0].range.end, "never zero-width");
}
/// Each class paints its own squiggle: a compile-error rule reads as an
/// error, a latch-shaped one as a warning, a naming one as information.
#[test]
fn a_diagnostics_severity_is_its_rules_class() {
assert_eq!(severity_of(Severity::Error), DiagnosticSeverity::ERROR);
assert_eq!(severity_of(Severity::Warning), DiagnosticSeverity::WARNING);
assert_eq!(severity_of(Severity::Style), DiagnosticSeverity::INFORMATION);
// `reg` is error-class, the tab is style-class, and the two arrive in
// one publish wearing different colours.
let (ws, uri) = doc_of("module m;\n\treg a;\nendmodule\n");
let diags = diagnostics(ws.document(&uri).expect("open"));
let by_code = |name: &str| {
diags
.iter()
.find(|d| d.code == Some(NumberOrString::String(name.into())))
.and_then(|d| d.severity)
};
assert_eq!(by_code("wire-reg-mixup"), Some(DiagnosticSeverity::ERROR), "{diags:#?}");
assert_eq!(by_code("no-tabs"), Some(DiagnosticSeverity::INFORMATION), "{diags:#?}");
}
#[test]
fn a_waived_violation_is_never_published() {
let (ws, uri) = doc_of("module m;\n\twire a; // lucisv: waive no-tabs\nendmodule\n");
@@ -274,7 +635,7 @@ mod tests {
let doc = ws.document(&uri).expect("open");
let diags = diagnostics(doc);
assert_eq!(diags.len(), 2, "both tabs are reported: {diags:#?}");
let offered = fixable(doc, 2);
let offered = fixable(&LintRun::default(), doc, 2);
assert_eq!(offered.len(), 1, "only the unfenced one may be fixed: {offered:#?}");
let free = text.find("\twire b").expect("the unfenced tab") as u32;
assert_eq!(offered[0].span.start, free);
@@ -294,7 +655,7 @@ mod tests {
.any(|d| d.code == Some(NumberOrString::String("no-tabs".into()))),
"still reported"
);
assert!(fixable(doc, 2).is_empty(), "and still not fixable");
assert!(fixable(&LintRun::default(), doc, 2).is_empty(), "and still not fixable");
}
#[test]
@@ -368,6 +729,127 @@ mod tests {
let _ = std::fs::remove_dir_all(dir);
}
/// The ladder of §33.1, one row per rung, asserted against the rule set
/// `enabled_rules` produces. Each row is (what the settings say, what must
/// be true of the result).
#[test]
fn the_enabled_rules_ladder_is_the_documented_one() {
// The project's half of the ladder is `lint::project`'s own table
// test; this one holds it empty, which is the editor-only ladder
// §33.1 wrote.
let names = |settings: &ClientSettings, oracle: bool| -> Vec<&'static str> {
enabled_rules(settings, &ProjectLint::default(), oracle)
.into_iter()
.map(|rule| rule.name())
.collect()
};
let with = |f: &dyn Fn(&mut ClientSettings)| {
let mut settings = ClientSettings::default();
f(&mut settings);
settings
};
// 1. the base set is the rules' own defaults, and a workspace adds
// exactly the rules that asked for one.
let base = ClientSettings::default();
assert_eq!(
names(&base, false),
default_rules().iter().map(|r| r.name()).collect::<Vec<_>>()
);
assert_eq!(
names(&base, true),
workspace_rules().iter().map(|r| r.name()).collect::<Vec<_>>()
);
// 2. a non-empty `select` replaces the base set — including rules that
// ship off, exactly as `--select` does.
let selected = with(&|s| s.lint_select = vec!["module-name-style".to_string()]);
assert_eq!(names(&selected, false), vec!["module-name-style"]);
// ... and a severity word may stand there.
let styled = with(&|s| s.lint_select = vec!["style".to_string()]);
assert!(names(&styled, true)
.iter()
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
== Severity::Style));
// 3. a class switched off removes every rule of that class.
let no_style = with(&|s| {
s.lint_severity.insert(Severity::Style, false);
});
assert!(!names(&no_style, true).contains(&"no-tabs"));
assert!(names(&no_style, true).contains(&"unused-signal"), "other classes stay");
// 4. a per-rule toggle beats the class switch, in both directions.
let style_off_but_tabs = with(&|s| {
s.lint_severity.insert(Severity::Style, false);
s.lint_rules.insert("no-tabs".to_string(), true);
});
assert!(names(&style_off_but_tabs, true).contains(&"no-tabs"));
let one_off = with(&|s| {
s.lint_rules.insert("no-tabs".to_string(), false);
});
assert!(!names(&one_off, true).contains(&"no-tabs"));
// A toggle also adds a rule `select` did not name, and one that ships
// off entirely.
let added = with(&|s| {
s.lint_select = vec!["no-tabs".to_string()];
s.lint_rules.insert("module-name-style".to_string(), true);
});
assert_eq!(names(&added, false), vec!["module-name-style", "no-tabs"]);
// 5. `ignore` is the last word, over a toggle that says `on`.
let ignored = with(&|s| {
s.lint_rules.insert("no-tabs".to_string(), true);
s.lint_ignore = vec!["no-tabs".to_string()];
});
assert!(!names(&ignored, true).contains(&"no-tabs"));
// ... and it takes a severity word too.
let quiet = with(&|s| s.lint_ignore = vec!["style".to_string()]);
assert!(names(&quiet, true)
.iter()
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
!= Severity::Style));
// The result is always in registry order, whatever order the settings
// named things in — two runs must print findings the same way.
let jumbled = with(&|s| {
s.lint_select = vec!["no-trailing-whitespace".to_string(), "no-tabs".to_string()];
});
assert_eq!(names(&jumbled, false), vec!["no-tabs", "no-trailing-whitespace"]);
}
/// The toggles reach the real published diagnostics, not just the rule
/// list: a class switched off silences its squiggles.
#[test]
fn a_class_switch_changes_what_the_server_publishes() {
let (mut ws, dir, uri) = two_file_project("classes");
ws.set_document(uri.clone(), "module dut;\n\tlogic dead;\nendmodule\n".to_string());
let doc = ws.document(&uri).expect("open");
let mut both = codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc)));
both.sort();
assert_eq!(both, vec!["no-tabs", "unused-signal"], "premise");
let mut off = ClientSettings::default();
off.lint_severity.insert(Severity::Style, false);
ws.set_client_settings(off);
let doc = ws.document(&uri).expect("open");
assert_eq!(
codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc))),
vec!["unused-signal"],
"the style class went quiet"
);
let mut back = ClientSettings::default();
back.lint_severity.insert(Severity::Style, false);
back.lint_rules.insert("no-tabs".to_string(), true);
ws.set_client_settings(back);
let doc = ws.document(&uri).expect("open");
let mut with_tabs = codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc)));
with_tabs.sort();
assert_eq!(with_tabs, vec!["no-tabs", "unused-signal"], "the per-rule word wins");
let _ = std::fs::remove_dir_all(dir);
}
/// The off switch, over the settings door: `lucisv.lint.ignore` takes a
/// rule out of the published set.
#[test]
@@ -421,7 +903,7 @@ mod tests {
#[test]
fn an_unfenced_file_offers_every_fix() {
let (ws, uri) = doc_of("module m;\n// just a note\n\twire a;\nendmodule\n");
assert_eq!(fixable(ws.document(&uri).expect("open"), 2).len(), 1);
assert_eq!(fixable(&LintRun::default(), ws.document(&uri).expect("open"), 2).len(), 1);
}
#[test]
@@ -429,9 +911,60 @@ mod tests {
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
let doc = ws.document(&uri).expect("open");
for width in [2usize, 4] {
let found = fixable(doc, width);
let found = fixable(&LintRun::default(), doc, width);
let fix = found[0].fix.as_ref().expect("no-tabs offers a fix");
assert_eq!(fix.edits[0].1, " ".repeat(width));
}
}
/// The two waiver lists add up, and only the setting's relative paths are
/// anchored at the first root — a `lucisv.toml`'s were resolved against
/// that file's own directory before they got here. TODO §39.
#[test]
fn the_config_files_waivers_come_first_and_the_settings_are_rooted() {
let file = FileConfig {
lint_waivers: Some(vec![PathBuf::from("/proj/rtl/project.waiver")]),
..Default::default()
};
let client = ClientSettings {
lint_waivers: vec!["team.waiver".to_string(), "/etc/global.waiver".to_string()],
..Default::default()
};
let roots = vec![PathBuf::from("/work/top")];
assert_eq!(
waiver_paths(&client, &roots, &file),
vec![
PathBuf::from("/proj/rtl/project.waiver"),
PathBuf::from("/work/top/team.waiver"),
PathBuf::from("/etc/global.waiver"),
]
);
// With no root at all a relative path is left as written rather than
// guessed at, exactly as `filelist_path` leaves it.
assert_eq!(
waiver_paths(&client, &[], &FileConfig::default()),
vec![PathBuf::from("team.waiver"), PathBuf::from("/etc/global.waiver")]
);
assert!(waiver_paths(&ClientSettings::default(), &roots, &FileConfig::default()).is_empty());
}
/// A waiver file that is missing, and one with a bad line, are both
/// described rather than fatal — and the good directives of the second
/// still apply. TODO §39.
#[test]
fn a_bad_waiver_file_is_described_and_its_good_directives_still_apply() {
let dir = std::env::temp_dir().join(format!("lucisv_waiver_paths_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
let good = dir.join("good.waiver");
std::fs::write(&good, "waive --rule=no-tabs\nwaive --rule=nope\n").expect("write");
let (waivers, problems) = external_waivers(&[good.clone(), dir.join("missing.waiver")]);
assert!(!waivers.is_empty(), "the good directive survived its neighbour");
assert_eq!(problems.len(), 2, "{problems:?}");
assert!(problems[0].contains("good.waiver:2: unknown rule `nope`"), "{problems:?}");
assert!(problems[1].contains("missing.waiver"), "{problems:?}");
let _ = std::fs::remove_dir_all(&dir);
}
}
+398
View File
@@ -0,0 +1,398 @@
//! What a buffer's `lucisv.toml` says about linting, and what could not be
//! used from it.
//!
//! The contract (§42): **the editor's settings play the role the CLI's flags
//! play**. `lucisv check` picks the flag when one was given and the project
//! file otherwise (`lucisv/src/lint.rs`'s `pick`); the server picks
//! `lucisv.lint.select` when it is non-empty and `[lint] select` otherwise,
//! key by key, so one buffer linted two ways is linted the same way. See
//! `docs/features/lint-config-contract/README.md`.
use std::collections::hash_map::DefaultHasher;
use std::collections::{BTreeSet, HashMap};
use std::hash::{Hash, Hasher};
use std::path::PathBuf;
use lucisv_core::config::FileConfig;
/// The selection a buffer's `lucisv.toml` carries: `[lint] select` and
/// `[lint] ignore`, exactly as `--select` and `--ignore` carry them.
///
/// [`ProjectLint::default`] — both lists empty — is a buffer with no config
/// file, or one whose `[lint]` table says nothing about rules: the editor's
/// settings and the base set then decide everything, which is what this
/// server did before §42.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ProjectLint {
/// `[lint] select`: run exactly these rules, replacing the base set —
/// unless the editor named some, which outranks it.
pub select: Vec<String>,
/// `[lint] ignore`: rules dropped from whatever `select` left — unless
/// the editor named some.
pub ignore: Vec<String>,
}
impl ProjectLint {
/// One config file's selection, with every name the registry does not
/// know dropped and reported.
///
/// `lucisv check` *fails the run* over an unknown name, which an editor
/// cannot do — but it must not silently obey a typo either: a
/// `select = ["no-tab"]` taken at face value would resolve to no rules at
/// all and blank the file's squiggles, which reads as "lucisv is happy"
/// rather than "lucisv could not understand your config". So the name is
/// dropped, said once, and the rest of the list still applies; a `select`
/// left empty by the dropping falls back to the base set.
pub fn read(file: &FileConfig) -> (ProjectLint, Vec<String>) {
let mut problems = Vec::new();
let select = known(file, "select", file.lint_select.as_deref(), &mut problems);
let ignore = known(file, "ignore", file.lint_ignore.as_deref(), &mut problems);
(ProjectLint { select, ignore }, problems)
}
}
/// The names of one `[lint]` list that name something, the others reported.
fn known(
file: &FileConfig,
key: &str,
list: Option<&[String]>,
problems: &mut Vec<String>,
) -> Vec<String> {
let mut kept = Vec::new();
for name in list.unwrap_or(&[]) {
if vlog_linter::rules_named(name).is_some() {
kept.push(name.clone());
} else {
// No line number: `lucisv_core::config` records one per
// `[lint.<rule>]` entry, because those are checked one by one,
// and the list keys are one value each.
problems.push(format!("{}: [lint] {key}: unknown rule: {name}", source_of(file)));
}
}
kept
}
/// The config file's path as an error should name it.
fn source_of(file: &FileConfig) -> String {
file.source.as_ref().map_or_else(|| "lucisv.toml".to_string(), |p| p.display().to_string())
}
/// What one buffer's `lucisv.toml` asked for and did not get: a
/// `[lint.<rule>]` entry the registry refused, a name in `[lint] select` that
/// is not a rule, a `[lint] waivers` file that is not there or holds a
/// directive that does not parse.
///
/// Every message is written the way `lucisv check` writes it —
/// `<file>:<line>: <message>` — so the same mistake reads the same in CI and
/// in an editor's output channel. **Nothing here is fatal**: the entry is
/// dropped and the buffer is still linted with everything that was
/// understood, because a server cannot fail a run the way a command can.
#[derive(Debug, Default, Clone)]
pub struct ConfigProblems {
/// The config file they came from. `None` — no config file was found —
/// means there is nothing to complain about and `messages` is empty.
source: Option<PathBuf>,
/// A stamp of that file's lint content, so an edited config gets a fresh
/// hearing: see [`ProblemLog`].
stamp: u64,
/// The messages, in file order.
messages: Vec<String>,
}
impl ConfigProblems {
/// The problems found in this config file.
pub fn new(file: &FileConfig, messages: Vec<String>) -> ConfigProblems {
ConfigProblems { source: file.source.clone(), stamp: stamp_of(file), messages }
}
/// Whether anything at all could not be used.
pub fn is_empty(&self) -> bool {
self.messages.is_empty()
}
}
/// A stamp over everything in a config file that [`ConfigProblems`] can be
/// about, so that editing the file re-arms the report and editing a source
/// beside it does not.
///
/// A hash rather than a modification time: the file is re-read on every lint
/// pass anyway (`configured`), and a hash of what was parsed cannot be fooled
/// by a filesystem whose timestamps are coarse.
fn stamp_of(file: &FileConfig) -> u64 {
let mut hasher = DefaultHasher::new();
file.lint_select.hash(&mut hasher);
file.lint_ignore.hash(&mut hasher);
file.lint_waivers.hash(&mut hasher);
for entry in &file.lint_options {
entry.rule.hash(&mut hasher);
entry.key.hash(&mut hasher);
entry.raw.hash(&mut hasher);
entry.line.hash(&mut hasher);
}
hasher.finish()
}
/// Which config problems have already been said, so each is said **once**.
///
/// Once per (config file, message), not once per lint pass: the pass runs on
/// every keystroke and every index rebuild, and a hundred copies of one line
/// in the output channel is not a report, it is noise. The editor-settings
/// path has said its own problems once since §34 — this is the same promise
/// for the file a project checks in.
///
/// A config file whose lint content changed clears its own memo, so a user
/// who edits `lucisv.toml` and gets it wrong again is told again. The memo is
/// keyed by path, so it holds one small entry per config file a session ever
/// linted through.
#[derive(Debug, Default)]
pub struct ProblemLog {
said: HashMap<PathBuf, Said>,
}
/// One config file's memo: the content it was taken under, and what was said.
#[derive(Debug, Default)]
struct Said {
stamp: u64,
messages: BTreeSet<String>,
}
impl ProblemLog {
/// The messages that have not been said yet for this config file, marked
/// as said. An empty answer means the user has already been told.
pub fn unsaid(&mut self, problems: &ConfigProblems) -> Vec<String> {
let Some(source) = problems.source.clone() else { return Vec::new() };
if problems.is_empty() {
return Vec::new();
}
let said = self.said.entry(source).or_default();
if said.stamp != problems.stamp {
said.stamp = problems.stamp;
said.messages.clear();
}
problems
.messages
.iter()
.filter(|message| said.messages.insert((*message).clone()))
.cloned()
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::settings::ClientSettings;
use crate::state::{Document, Workspace};
use lsp_types::Uri;
use std::str::FromStr;
use vlog_linter::Severity;
fn config(text: &str) -> FileConfig {
let mut file = lucisv_core::config::parse(text).expect("the config parses");
file.source = Some(PathBuf::from("/rtl/lucisv.toml"));
file
}
fn names(settings: &ClientSettings, project: &ProjectLint, oracle: bool) -> Vec<&'static str> {
super::super::enabled_rules(settings, project, oracle)
.into_iter()
.map(|rule| rule.name())
.collect()
}
fn editor(select: &[&str], ignore: &[&str]) -> ClientSettings {
ClientSettings {
lint_select: select.iter().map(|s| (*s).to_string()).collect(),
lint_ignore: ignore.iter().map(|s| (*s).to_string()).collect(),
..ClientSettings::default()
}
}
fn project(select: &[&str], ignore: &[&str]) -> ProjectLint {
ProjectLint {
select: select.iter().map(|s| (*s).to_string()).collect(),
ignore: ignore.iter().map(|s| (*s).to_string()).collect(),
}
}
/// §42.1's table: every combination of {toml select, editor select} ×
/// {toml ignore, editor ignore}, against the ladder. The editor's list
/// wins when it says anything, the project's is used when it does not,
/// and the two keys are decided **independently** — the CLI's `pick`,
/// applied twice.
#[test]
fn the_editor_outranks_the_project_key_by_key() {
// Four rules stand in for the whole registry: two the project may
// name and two the editor may, so a row's answer says which list was
// consulted rather than which happened to be shorter.
// (toml select, editor select, toml ignore, editor ignore, expected).
type Row = (
&'static [&'static str],
&'static [&'static str],
&'static [&'static str],
&'static [&'static str],
&'static [&'static str],
);
let rows: [Row; 8] = [
// (toml select, editor select, toml ignore, editor ignore) => rules
(&[], &[], &[], &[], &[]),
(&["no-tabs"], &[], &[], &[], &["no-tabs"]),
(&[], &["no-tabs"], &[], &[], &["no-tabs"]),
(&["module-name-style"], &["no-tabs"], &[], &[], &["no-tabs"]),
(&["no-tabs", "module-name-style"], &[], &["no-tabs"], &[], &["module-name-style"]),
(&["no-tabs", "module-name-style"], &[], &[], &["no-tabs"], &["module-name-style"]),
(
&["no-tabs", "module-name-style"],
&[],
&["module-name-style"],
&["no-tabs"],
&["module-name-style"],
),
(
&["module-name-style"],
&["no-tabs", "module-name-style"],
&["no-tabs"],
&["module-name-style"],
&["no-tabs"],
),
];
for (toml_select, ed_select, toml_ignore, ed_ignore, want) in rows {
let settings = editor(ed_select, ed_ignore);
let from_file = project(toml_select, toml_ignore);
let got = names(&settings, &from_file, false);
if want.is_empty() {
// The empty row is the base set, which is too long to spell.
assert_eq!(
got,
super::super::default_rules().iter().map(|r| r.name()).collect::<Vec<_>>(),
"neither list said anything, so the base set stands"
);
} else {
assert_eq!(
got, want,
"{toml_select:?} {ed_select:?} {toml_ignore:?} {ed_ignore:?}"
);
}
}
}
/// A severity word stands for its whole class in the toml's lists exactly
/// as it does in the editor's, and as `--select style` does.
#[test]
fn a_severity_word_works_in_the_projects_lists_too() {
let styled = names(&ClientSettings::default(), &project(&["style"], &[]), true);
assert!(!styled.is_empty());
assert!(styled
.iter()
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
== Severity::Style));
let quiet = names(&ClientSettings::default(), &project(&[], &["style"]), true);
assert!(!quiet.is_empty());
assert!(quiet
.iter()
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
!= Severity::Style));
}
/// A rung 3 or 4 switch is the editor's alone, and still applies over a
/// selection the project made.
#[test]
fn the_editor_only_rungs_still_apply_over_a_project_selection() {
let mut settings = ClientSettings::default();
settings.lint_severity.insert(Severity::Style, false);
let from_file = project(&["no-tabs", "wire-reg-mixup"], &[]);
assert_eq!(
names(&settings, &from_file, false),
vec!["wire-reg-mixup"],
"the class switch removes the project's style rule"
);
settings.lint_rules.insert("no-tabs".to_string(), true);
assert_eq!(
names(&settings, &from_file, false),
vec!["no-tabs", "wire-reg-mixup"],
"and the per-rule word puts it back"
);
}
/// A name the registry does not know is dropped and reported — the run
/// `lucisv check` would have failed keeps going here with what was
/// understood.
#[test]
fn an_unknown_name_in_the_projects_list_is_dropped_and_said() {
let (from_file, problems) =
ProjectLint::read(&config("[lint]\nselect = [\"no-tab\", \"no-tabs\"]\n"));
assert_eq!(from_file.select, vec!["no-tabs"]);
assert_eq!(problems, vec!["/rtl/lucisv.toml: [lint] select: unknown rule: no-tab"]);
assert_eq!(names(&ClientSettings::default(), &from_file, false), vec!["no-tabs"]);
// Every name unknown leaves the list empty, which is the base set —
// the safe direction: some rules rather than none.
let (none, problems) = ProjectLint::read(&config("[lint]\nselect = [\"nope\"]\n"));
assert!(none.select.is_empty());
assert_eq!(problems.len(), 1);
assert_eq!(
names(&ClientSettings::default(), &none, false),
super::super::default_rules().iter().map(|r| r.name()).collect::<Vec<_>>()
);
}
/// §42.2: a `[lint.<rule>]` entry the registry refuses is reported once,
/// however many lint passes run, and the buffer keeps being linted.
#[test]
fn a_rejected_option_is_said_once_and_the_lint_still_runs() {
let dir = std::env::temp_dir()
.join(format!("lucisv_lint_project_{}_rejected", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
std::fs::write(dir.join("lucisv.toml"), "[lint.line-length]\nlength = \"wide\"\n")
.expect("write config");
let path = dir.join("m.sv");
let text = "module m;\n\twire a;\nendmodule\n";
std::fs::write(&path, text).expect("write source");
let uri = Uri::from_str(&format!("file://{}", path.display())).expect("uri");
let mut ws = Workspace::default();
ws.set_document(uri.clone(), text.to_string());
let mut log = ProblemLog::default();
let mut said = Vec::new();
for _ in 0..3 {
let doc: &Document = ws.document(&uri).expect("open");
let run = super::super::LintRun::for_document(&ws, doc);
// The lint still runs: the tab is still a finding.
assert!(
super::super::violations_in(doc, &run).iter().any(|v| v.rule == "no-tabs"),
"the buffer is still linted with the entry dropped"
);
said.extend(log.unsaid(run.config_problems()));
}
assert_eq!(said.len(), 1, "said once across three passes: {said:#?}");
let expected = format!("{}:2: rule `line-length` ", dir.join("lucisv.toml").display());
assert!(said[0].starts_with(&expected), "the wording `lucisv check` prints: {}", said[0]);
let _ = std::fs::remove_dir_all(&dir);
}
/// An edited config gets a fresh hearing: the memo is keyed by the file's
/// lint content, so the same mistake made again after a change is said
/// again.
#[test]
fn an_edited_config_re_arms_the_report() {
let first = config("[lint.line-length]\nlength = \"wide\"\n");
let problems = ConfigProblems::new(&first, vec!["/rtl/lucisv.toml:2: bad".to_string()]);
let mut log = ProblemLog::default();
assert_eq!(log.unsaid(&problems).len(), 1);
assert!(log.unsaid(&problems).is_empty(), "and not twice");
// Same message, different file content: the user has been editing.
let edited = config("# a comment\n[lint.line-length]\nlength = \"wide\"\n");
let again = ConfigProblems::new(&edited, vec!["/rtl/lucisv.toml:3: bad".to_string()]);
assert_eq!(log.unsaid(&again).len(), 1, "a changed config is heard again");
// A buffer with no config file has nothing to report.
let nowhere = ConfigProblems::new(&FileConfig::default(), vec!["never".to_string()]);
assert!(log.unsaid(&nowhere).is_empty());
}
}
+236 -1
View File
@@ -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,
);
}
}
+155 -9
View File
@@ -13,15 +13,18 @@ mod convert;
mod design_hierarchy;
mod diagnostics;
mod expand;
mod extract;
mod file_ops;
mod folding;
mod format;
mod hierarchy;
mod hover;
mod imports;
mod includes;
mod index_cache;
mod inlay;
mod inline;
mod inline_module;
mod instantiate;
mod large;
mod lens;
@@ -59,11 +62,12 @@ use lsp_types::{
DocumentLinkOptions, DocumentOnTypeFormattingOptions, ExecuteCommandOptions,
FoldingRangeProviderCapability, InitializeParams, InlayHintOptions,
InlayHintServerCapabilities, LinkedEditingRangeServerCapabilities, OneOf, PositionEncodingKind,
RenameOptions, SaveOptions, SelectionRangeProviderCapability, SemanticTokensFullOptions,
SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities,
ServerCapabilities, SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind,
TextDocumentSyncOptions, TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability,
WorkDoneProgressOptions, WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities,
RenameOptions, ResourceOperationKind, SaveOptions, SelectionRangeProviderCapability,
SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions,
SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions,
TextDocumentSyncCapability, TextDocumentSyncKind, TextDocumentSyncOptions,
TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability, WorkDoneProgressOptions,
WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities,
};
use vlog_parser::PARSE_STACK_SIZE;
@@ -126,6 +130,8 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
configuration: configuration_support(&params),
token_server_cancel: token_server_cancel_support(&params),
hierarchy_view,
code_action_resolve: code_action_resolve_support(&params),
create_files: create_files_support(&params),
};
connection.initialize_finish(id, initialize_value(ranges_formatting)?)?;
@@ -259,10 +265,18 @@ fn capabilities() -> ServerCapabilities {
CodeActionKind::QUICKFIX,
CodeActionKind::new(code_action::FIX_ALL),
CodeActionKind::new(ports::REFACTOR_PORTS),
imports::kind(),
extract::kind(),
inline_module::kind(),
]),
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
@@ -391,10 +405,13 @@ fn capabilities() -> ServerCapabilities {
}
}
/// Every command this server executes: the three port refactorings, the
/// instantiation skeleton, and the jump the code lens hangs off.
/// Every command this server executes: the port refactorings, organize
/// imports, the instantiation skeleton, and the jump the code lens hangs off.
fn commands() -> Vec<String> {
let mut commands = ports::commands();
commands.extend(imports::commands());
commands.extend(extract::commands());
commands.extend(inline_module::commands());
commands.extend(instantiate::commands());
commands.extend(lens::commands());
commands
@@ -499,6 +516,50 @@ 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 can apply a `WorkspaceEdit` that **creates a file** —
/// `workspace.workspaceEdit.documentChanges` *and* a `resourceOperations`
/// list containing `create`.
///
/// Both halves, because a creation is a resource operation and a resource
/// operation can only be sent inside `documentChanges`: a client with one and
/// not the other cannot apply the edit at all. A client that says nothing gets
/// the extracted module written below the one it came from, in the file it
/// came from, which needs no capability of any kind
/// (`docs/features/extract-inline-module/README.md`).
fn create_files_support(params: &InitializeParams) -> bool {
let Some(edits) = params
.capabilities
.workspace
.as_ref()
.and_then(|workspace| workspace.workspace_edit.as_ref())
else {
return false;
};
let creates = edits
.resource_operations
.as_ref()
.is_some_and(|kinds| kinds.contains(&ResourceOperationKind::Create));
edits.document_changes.unwrap_or(false) && creates
}
/// 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 +1209,91 @@ 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 create_files_support_needs_both_halves_of_the_capability() {
use lsp_types::{
ClientCapabilities, ResourceOperationKind, WorkspaceClientCapabilities,
WorkspaceEditClientCapabilities,
};
assert!(
!create_files_support(&InitializeParams::default()),
"silence means the module goes below the one it came from"
);
let saying = |document_changes: Option<bool>, ops: Option<&[ResourceOperationKind]>| {
InitializeParams {
capabilities: ClientCapabilities {
workspace: Some(WorkspaceClientCapabilities {
workspace_edit: Some(WorkspaceEditClientCapabilities {
document_changes,
resource_operations: ops.map(<[_]>::to_vec),
..Default::default()
}),
..Default::default()
}),
..Default::default()
},
..Default::default()
}
};
let create = [ResourceOperationKind::Create];
let rename = [ResourceOperationKind::Rename];
assert!(create_files_support(&saying(Some(true), Some(&create))), "what VS Code sends");
assert!(
!create_files_support(&saying(Some(true), Some(&rename))),
"a client that can rename but not create cannot apply the creation"
);
assert!(
!create_files_support(&saying(Some(true), None)),
"no resource operations at all is no creation"
);
assert!(
!create_files_support(&saying(None, Some(&create))),
"a resource operation can only be sent inside `documentChanges`"
);
assert!(!create_files_support(&saying(Some(false), Some(&create))));
}
#[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]
+79 -2
View File
@@ -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(),
@@ -550,6 +552,51 @@ mod tests {
assert_eq!(locations[0].range.start.line, 1);
}
/// A qualified type name is two references, each addressable on its own
/// half: the parser spans `pkg::t` and `DataType::segments` splits it, so
/// F12 on the *item* lands on the typedef rather than on the package.
#[test]
fn a_scoped_type_name_jumps_from_its_item_half() {
let text = "\
package pkg;
typedef logic [1:0] t;
endpackage
module m;
pkg::t x;
endmodule
";
let (ws, uri) = document(text);
let item = definition(&ws, &uri, at(text, "pkg::t x") + 5);
assert_eq!(item.len(), 1, "the typedef");
assert_eq!(item[0].range.start.line, 1, "the `typedef ... t;` line");
assert_eq!(item[0].range.start.character, 22, "the name `t`, not the keyword");
let unit = definition(&ws, &uri, at(text, "pkg::t x"));
assert_eq!(unit.len(), 1, "the package");
assert_eq!(unit[0].range.start.line, 0);
}
/// `bus_if.mp bus` — the interface is the type, so the head range is what
/// F12 answers from; the modport tail is a member of it.
#[test]
fn an_interface_port_type_jumps_from_its_head() {
let text = "\
interface bus_if;
logic clk;
modport mp (input clk);
endinterface
module m (bus_if.mp bus);
endmodule
";
let (ws, uri) = document(text);
let head = definition(&ws, &uri, at(text, "bus_if.mp bus") + 2);
assert_eq!(head.len(), 1, "the interface");
assert_eq!(head[0].range.start.line, 0);
assert_eq!(head[0].range.start.character, 10, "the interface name");
let tail = definition(&ws, &uri, at(text, "bus_if.mp bus") + 7);
assert_eq!(tail.len(), 1, "the modport");
assert_eq!(tail[0].range.start.line, 2);
}
#[test]
fn a_macro_use_jumps_to_its_define_in_the_same_file() {
let text = "`define WIDTH 8\nmodule m;\n logic [`WIDTH-1:0] a;\nendmodule\n";
@@ -691,6 +738,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");
+10 -1
View File
@@ -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()
);
+684 -8
View File
@@ -1,5 +1,5 @@
//! The port refactorings on the wire: `textDocument/codeAction` for the two
//! that need no typing, and `workspace/executeCommand` for all three.
//! The port refactorings on the wire: `textDocument/codeAction` for the four
//! that need no typing, and `workspace/executeCommand` for all five.
//!
//! Protocol only. Every edit is computed by `vlog_refactor` over the same file
//! set the workspace index was built from; this module turns the result into a
@@ -8,10 +8,18 @@
//!
//! **Why commands as well as code actions.** Adding a port needs a
//! declaration typed by the user, and a code action carries no input — so
//! `lucisv.addPort` is the API a UI calls once it has asked. `lucisv.removePort`
//! 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.
//! `lucisv.addPort` is the API a UI calls once it has asked. `lucisv.removePort`,
//! `lucisv.propagatePorts`, `lucisv.expandWildcard` and `lucisv.convertToAnsi`
//! 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 +30,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};
@@ -40,14 +49,30 @@ pub const ADD_PORT: &str = "lucisv.addPort";
pub const REMOVE_PORT: &str = "lucisv.removePort";
/// Connect an instantiation's missing ports: `[uri, position]`.
pub const PROPAGATE_PORTS: &str = "lucisv.propagatePorts";
/// Write out the `.*` at a position: `[uri, position]`.
pub const EXPAND_WILDCARD: &str = "lucisv.expandWildcard";
/// Rewrite the non-ANSI header at a position ANSI-style: `[uri, position]`.
pub const CONVERT_TO_ANSI: &str = "lucisv.convertToAnsi";
/// Every command this server executes.
pub fn commands() -> Vec<String> {
vec![ADD_PORT.to_string(), REMOVE_PORT.to_string(), PROPAGATE_PORTS.to_string()]
vec![
ADD_PORT.to_string(),
REMOVE_PORT.to_string(),
PROPAGATE_PORTS.to_string(),
EXPAND_WILDCARD.to_string(),
CONVERT_TO_ANSI.to_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,7 +101,193 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrC
.collect()
}
/// Run one of the three commands, or say why it cannot run.
/// 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.
///
/// Only a title whose count *is* an instantiation census is recounted:
/// `lucisv: expand .* (3 connections)` counts the connections one wildcard
/// becomes, which the offer's own two files already know exactly and no index
/// lookup could improve (`vlog_refactor::is_sites_phrase`).
fn counted(ws: &Workspace, title: String, modules: &[String]) -> String {
let Some((head, phrase)) = title.strip_suffix(')').and_then(|head| head.rsplit_once(" ("))
else {
return title;
};
if !vlog_refactor::is_sites_phrase(phrase) {
return title;
}
let sites = modules.iter().map(|name| instances_of(ws, name)).sum();
format!("{head} ({})", 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 five commands, or say why it cannot run.
///
/// The answer is the `WorkspaceEdit` to apply plus the engine's warnings. How
/// it reaches the editor is `server.rs`'s business: it is pushed as a
@@ -122,10 +333,23 @@ pub fn execute(
let sources = sources_at(ws, &path, offset);
vlog_refactor::propagate_ports(&sources, &path, offset)?
}
EXPAND_WILDCARD => {
let (_, path) = target(ws, arguments.first())?;
let offset = position_argument(ws, arguments, EXPAND_WILDCARD)?;
let sources = sources_at(ws, &path, offset);
vlog_refactor::expand_wildcard(&sources, &path, offset)?
}
CONVERT_TO_ANSI => {
let (_, path) = target(ws, arguments.first())?;
let offset = position_argument(ws, arguments, CONVERT_TO_ANSI)?;
let sources = sources_at(ws, &path, offset);
vlog_refactor::convert_to_ansi(&sources, &path, offset)?
}
// The instantiation skeleton is not a port refactoring and computes
// its own `WorkspaceEdit`, but `server.rs` routes every non-lens
// `workspace/executeCommand` through here — this is the one place an
// edit-producing command is handed to `Server::deliver`.
crate::imports::ORGANIZE_IMPORTS => return crate::imports::execute(ws, arguments),
crate::instantiate::INSTANTIATE => {
return crate::instantiate::execute(ws, arguments).map(|edit| (edit, Vec::new()))
}
@@ -809,6 +1033,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");
@@ -829,8 +1369,144 @@ mod tests {
assert!(message.contains("position"), "{message}");
}
// ------------------------------------------------------------------
// the `.*` expansion (TODO §50)
// ------------------------------------------------------------------
/// A workspace whose `top.sv` instantiates `sub` with a wildcard.
fn wildcard(tree: &Tree) -> (Workspace, Uri, &'static str) {
const TEXT: &str =
"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());
(ws, uri, TEXT)
}
#[test]
fn expand_wildcard_takes_a_position() {
let tree = Tree::new("expand");
let (ws, uri, text) = wildcard(&tree);
let arguments = vec![
serde_json::to_value(&uri).expect("uri"),
serde_json::to_value(Position { line: 2, character: 24 }).expect("position"),
];
let (edit, warnings) = execute(&ws, EXPAND_WILDCARD, &arguments).expect("expands");
assert!(warnings.is_empty(), "{warnings:?}");
let edits = edits_for(&edit, &uri);
assert_eq!(edits.len(), 1, "{edits:#?}");
assert_eq!(edits[0].new_text, ".rst(rst)");
// The range is the `.*` itself, in the client's own coordinates.
assert_eq!(edits[0].range.start.character, 24);
assert_eq!(edits[0].range.end.character, 26);
assert_eq!(&text[text.find(".*").expect("the wildcard")..][..2], ".*");
}
#[test]
fn expand_wildcard_refuses_where_there_is_no_wildcard() {
let tree = Tree::new("expand_none");
let (ws, top_uri, _) = opened(&tree);
let arguments = vec![
serde_json::to_value(&top_uri).expect("uri"),
serde_json::to_value(Position { line: 2, character: 6 }).expect("position"),
];
let message = execute(&ws, EXPAND_WILDCARD, &arguments).expect_err("no wildcard");
assert!(message.contains("writes no `.*` to expand"), "{message}");
}
#[test]
fn the_wildcard_action_is_offered_lazily_and_resolves_to_the_eager_edit() {
let tree = Tree::new("expand_action");
let (ws, uri, text) = wildcard(&tree);
let offset = text.find(".*").expect("the wildcard") as u32;
let lazy = offered(&ws, &uri, offset);
assert_eq!(menu(&lazy), menu(&code_actions(&ws, &uri, offset)));
// The count is the connections the wildcard becomes, and the index's
// instantiation census must not overwrite it.
assert_eq!(menu(&lazy)[0].0, "lucisv: expand .* (1 connection)");
assert!(only(&lazy).edit.is_none(), "an offer carries no edit");
let resolved = resolve(&ws, only(&lazy).clone()).expect("edit");
assert_eq!(resolved.title, "lucisv: expand .* (1 connection)");
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)");
}
// ------------------------------------------------------------------
// the non-ANSI → ANSI conversion (TODO §51)
// ------------------------------------------------------------------
/// A workspace whose `legacy.sv` writes a Verilog-2001 header.
const LEGACY: &str =
"module legacy (\n a,\n b\n);\n input a;\n output [7:0] b;\n reg [7:0] b;\nendmodule\n";
fn legacy(tree: &Tree) -> (Workspace, Uri) {
let path = tree.write("legacy.sv", LEGACY);
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), LEGACY.to_string());
(ws, uri)
}
#[test]
fn convert_to_ansi_takes_a_position() {
let tree = Tree::new("ansi");
let (ws, uri) = legacy(&tree);
let arguments = vec![
serde_json::to_value(&uri).expect("uri"),
// The module's own name — inside the header, and nowhere near a
// port declaration.
serde_json::to_value(Position { line: 0, character: 8 }).expect("position"),
];
// Two insertions — the ANSI prefixes — and three deletions: `input a;`,
// `output [7:0] b;` and the `reg [7:0] b;` that completed it.
let (edit, warnings) = execute(&ws, CONVERT_TO_ANSI, &arguments).expect("converts");
assert!(warnings.is_empty(), "{warnings:?}");
let edits = edits_for(&edit, &uri);
let written: Vec<&str> = edits.iter().map(|e| e.new_text.as_str()).collect();
assert_eq!(written, vec!["input ", "output reg [7:0] ", "", "", ""], "{edits:#?}");
}
#[test]
fn convert_to_ansi_refuses_an_ansi_header() {
let tree = Tree::new("ansi_none");
let (ws, top_uri, _) = opened(&tree);
let arguments = vec![
serde_json::to_value(&top_uri).expect("uri"),
serde_json::to_value(Position { line: 0, character: 8 }).expect("position"),
];
let message = execute(&ws, CONVERT_TO_ANSI, &arguments).expect_err("nothing to convert");
assert!(message.contains("declares no ports"), "{message}");
}
#[test]
fn the_ansi_action_is_offered_lazily_and_resolves_to_the_eager_edit() {
let tree = Tree::new("ansi_action");
let (ws, uri) = legacy(&tree);
// The cursor on the module's name: in the header, on no port.
let offset = LEGACY.find("legacy (").expect("the name") 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: convert ports to ANSI (2 ports)");
assert!(only(&lazy).edit.is_none(), "an offer carries no edit");
let resolved = resolve(&ws, only(&lazy).clone()).expect("edit");
assert_eq!(resolved.title, "lucisv: convert ports to ANSI (2 ports)");
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, "input ");
}
#[test]
fn the_command_list_is_what_the_server_advertises() {
assert_eq!(commands(), vec![ADD_PORT, REMOVE_PORT, PROPAGATE_PORTS]);
assert_eq!(
commands(),
vec![ADD_PORT, REMOVE_PORT, PROPAGATE_PORTS, EXPAND_WILDCARD, CONVERT_TO_ANSI]
);
}
}
+33 -2
View File
@@ -795,11 +795,16 @@ mod tests {
/// workspace was never consulted), so the file should not even be pulled
/// in — and if it were, the rename must still succeed, since no capture is
/// possible against a symbol nothing outside that file can see.
///
/// The symbol is a **function's** local, not a module's net: since
/// 2026-09-05 a net is a declaration on the module's hierarchical surface
/// and joins the fan-out by that rung (the test below), which would answer
/// this one for the wrong reason. A name inside a subprogram body is on
/// neither surface, which is what this attack needs.
#[test]
fn a_local_only_symbol_sharing_the_new_names_spelling_is_not_a_bogus_refusal() {
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
const LOCAL_ONLY: &str =
"module unrelated;\n wire taken_local;\n assign taken_local = 1'b0;\nendmodule\n";
const LOCAL_ONLY: &str = "module unrelated;\n function automatic int f();\n int taken_local = 0;\n return taken_local;\n endfunction\nendmodule\n";
let tree = Tree::new("fanout_local_only");
let files = [("pkg.sv", PKG), ("local.sv", LOCAL_ONLY)];
let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]);
@@ -816,6 +821,32 @@ mod tests {
assert!(edit.edits_for(&tree.path.join("local.sv")).is_empty());
}
/// The rung the hierarchical surface added: a module's internal **net**
/// spelled like the new name *is* a declaration the fan-out has to hold,
/// because `assign w = u_unrelated.taken_net;` in a fourth file resolves
/// to it now. So the file is pulled in — and the rename still succeeds
/// and still writes nothing there, because a package name and a net
/// inside a module capture nothing of each other.
#[test]
fn a_module_net_sharing_the_new_names_spelling_joins_the_fan_out_and_refuses_nothing() {
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
const NET_ONLY: &str =
"module unrelated;\n wire taken_net;\n assign taken_net = 1'b0;\nendmodule\n";
let tree = Tree::new("fanout_hierarchical_net");
let files = [("pkg.sv", PKG), ("net.sv", NET_ONLY)];
let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]);
let path = tree.path.join("pkg.sv");
let at = at(PKG, "cfg_pkg;");
let fan = fan_out(&ws, &path, at, "taken_net");
assert!(
fan.contains(&tree.path.join("net.sv")),
"a net is a hierarchical declaration of its name: {fan:?}"
);
let edit = same_answer(&ws, &path, at, "taken_net").expect("renames, no capture possible");
assert!(edit.edits_for(&tree.path.join("net.sv")).is_empty());
}
/// Attack on the old-name exemption: a shadowing/"unmasking" hunt. Two
/// packages, `p_pkg` and `q_pkg`, both export a member spelled the same
/// (`shared_name`); a third file imports both, `p_pkg` first, so
+1
View File
@@ -117,6 +117,7 @@ fn items(list: &[Item], offset: u32, out: &mut Vec<TextRange>) {
ItemKind::Class(class) => items(&class.items, offset, out),
ItemKind::Package { items: inner, .. } => items(inner, offset, out),
ItemKind::GenerateRegion { items: inner, .. } => items(inner, offset, out),
ItemKind::GenBlock(b) => items(&b.items, offset, out),
ItemKind::GenIf(gen_if) => gen_if_blocks(gen_if, offset, out),
ItemKind::GenFor(gen_for) => gen_block(&gen_for.body, offset, out),
ItemKind::GenCase(gen_case) => {
+38 -4
View File
@@ -94,10 +94,44 @@ impl Server {
fn diagnostics_of(&self, uri: &Uri) -> Vec<lsp_types::Diagnostic> {
let Some(doc) = self.workspace.document(uri) else { return Vec::new() };
// The lint pass is given the project: the rule selection
// `lucisv.lint.*` resolved to, and the index's identifier census, which
// is what lets the semantic rules default on here without accusing a
// signal another file reads (`docs/features/semantic-lints-on/`).
diagnostics::all_in(doc, &crate::lint::LintRun::for_document(&self.workspace, doc))
// `lucisv.lint.*` and the buffer's `[lint]` table resolved to, and the
// index's identifier census, which is what lets the semantic rules
// default on here without accusing a signal another file reads
// (`docs/features/semantic-lints-on/`).
let run = crate::lint::LintRun::for_document(&self.workspace, doc);
self.report_config_problems(&run);
diagnostics::all_in(doc, &run)
}
/// Say, once, what this buffer's `lucisv.toml` asked for and did not get.
///
/// Once per (config file, entry), not once per pass: this runs on every
/// keystroke and every index rebuild. The words are the ones `lucisv
/// check` fails the run with, `<file>:<line>: <message>`, so one mistake
/// reads the same in CI and here — but nothing is fatal, the entry is
/// dropped and the buffer is still linted with everything understood
/// (§42.2). Logged, not shown: a typo in a checked-in config is not worth
/// a popup on every editor in the project.
fn report_config_problems(&self, run: &crate::lint::LintRun) {
let problems = run.config_problems();
if problems.is_empty() {
return;
}
// The borrow is released before anything is sent: `notify` takes
// `&self` and could otherwise reach a second borrow one day.
let unsaid = match self.lint_config_problems.try_borrow_mut() {
Ok(mut log) => log.unsaid(problems),
Err(_) => return,
};
for message in unsaid {
self.notify(
LogMessage::METHOD,
LogMessageParams {
typ: MessageType::WARNING,
message: format!("lucisv: {message}; ignored"),
},
);
}
}
/// Publish everything known about a buffer — parse errors and lint
+91 -18
View File
@@ -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,
@@ -44,9 +44,9 @@ use serde_json::Value;
use super::client::ms;
use super::Server;
use crate::{
code_action, completion, design_hierarchy, file_ops, folding, format, hierarchy, hover,
includes, inlay, inline, lens, linked, nav, pairs, ports, rename, selection, signature,
symbols, tokens, type_def, type_hierarchy,
code_action, completion, design_hierarchy, extract, file_ops, folding, format, hierarchy,
hover, imports, includes, inlay, inline, inline_module, lens, linked, lint, nav, pairs, ports,
rename, selection, signature, symbols, tokens, type_def, type_hierarchy,
};
impl Server {
@@ -251,17 +251,65 @@ impl Server {
// or from the built-in default.
let tab_width =
format::indent_width(doc.path.as_deref(), self.workspace.client_settings());
let run = lint::LintRun::for_document(&self.workspace, doc);
let mut actions =
code_action::code_actions(&uri, doc, p.range, only.as_deref(), tab_width);
code_action::code_actions(&run, &uri, doc, p.range, only.as_deref(), tab_width);
// The port refactorings answer for the cursor, not for a range:
// the request's start is where the user is.
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),
});
}
// Organizing imports is filed under LSP's own
// `source.organizeImports`, which is the kind an editor's
// organize-on-save asks for by name.
if code_action::wanted(only.as_deref(), &imports::kind()) {
let offset = doc.positions().offset(p.range.start);
actions.extend(match self.abilities.code_action_resolve {
true => imports::offers(&self.workspace, &uri, p.range.start, offset),
false => imports::code_actions(&self.workspace, &uri, offset),
});
}
// Extracting a selection into a module of its own. This one
// answers for the *range*, not the cursor, and carries a
// command rather than an edit — it needs a name for the new
// module, and only a command can be intercepted by a client
// that wants to ask the user for one.
if code_action::wanted(only.as_deref(), &extract::kind()) {
actions.extend(extract::code_actions(&self.workspace, &uri, p.range));
}
// Inlining the module instantiated under the cursor — the
// mirror of the extraction, and lazy for the same reason: the
// offer parses one buffer and the command reads the workspace.
if code_action::wanted(only.as_deref(), &inline_module::kind()) {
actions.extend(inline_module::code_actions(&self.workspace, &uri, p.range));
}
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| {
// Each family resolves its own offers: the two carry different
// `data`, and the kind the client hands back says which.
let organize = action.kind.as_ref() == Some(&imports::kind());
let resolved = match organize {
true => imports::resolve(&self.workspace, action),
false => ports::resolve(&self.workspace, action),
};
match resolved {
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.
@@ -326,6 +374,31 @@ impl Server {
Err(message) => Err(Failure::Request(message)),
};
}
// Extracting takes the client's own capability with it: only
// a client that can apply a `CreateFile` gets the new module
// in a file of its own.
if p.command == extract::EXTRACT_MODULE {
return match extract::execute(
&self.workspace,
&p.arguments,
self.abilities.create_files,
) {
Ok((edit, warnings)) => {
self.report_scope(warnings);
self.deliver(&p.command, edit)
}
Err(message) => Err(Failure::Request(message)),
};
}
if p.command == inline_module::INLINE_MODULE {
return match inline_module::execute(&self.workspace, &p.arguments) {
Ok((edit, warnings)) => {
self.report_scope(warnings);
self.deliver(&p.command, edit)
}
Err(message) => Err(Failure::Request(message)),
};
}
match ports::execute(&self.workspace, &p.command, &p.arguments) {
Ok((edit, warnings)) => {
self.report_scope(warnings);
+29
View File
@@ -104,6 +104,20 @@ 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,
/// Whether the client can apply a `WorkspaceEdit` that creates a file —
/// `workspace.workspaceEdit.documentChanges` plus a `resourceOperations`
/// list containing `create`. Only then does an extracted module get a
/// file of its own; a client that said nothing gets it written below the
/// module it came from
/// (`docs/features/extract-inline-module/README.md`).
pub create_files: bool,
}
/// Everything the server owns.
@@ -114,6 +128,19 @@ pub struct Server {
/// for a document whenever its text changes, so the warning is said once
/// per file change rather than once per format-on-save.
config_warnings: HashSet<Uri>,
/// Which `[lint]` entries of which `lucisv.toml` have already been
/// reported (§42.2). Interior-mutable because a lint pass runs behind
/// `&self` — the pull models compute diagnostics inside a `map` over the
/// open buffers — and the memo is the one thing a pass has to write.
/// Nothing is called while it is borrowed.
lint_config_problems: std::cell::RefCell<crate::lint::ProblemLog>,
/// The unknown-rule-name lines already logged for the **editor's**
/// `lucisv.lint.select`/`ignore` (§45.1), exactly as the last settings
/// value produced them. A client that re-pushes the same section — VS Code
/// does, whenever anything in it changes — says nothing again; a list the
/// user edited re-arms every name that is new to it. The project file's
/// twin memo is `lint_config_problems` above.
said_lint_names: Vec<String>,
abilities: ClientAbilities,
/// The id of the file-watcher registration in force, if any. Kept so a
/// changed `lucisv.filelist` can replace it: the watched filelist path is
@@ -293,6 +320,8 @@ impl Server {
connection,
workspace: Workspace::default(),
config_warnings: HashSet::new(),
lint_config_problems: std::cell::RefCell::default(),
said_lint_names: Vec::new(),
abilities,
watchers: None,
registrations: 0,
@@ -12,19 +12,20 @@ use lsp_server::{ExtractError, Notification};
use lsp_types::notification::{
DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles,
DidChangeWorkspaceFolders, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument,
DidRenameFiles, DidSaveTextDocument, Notification as _,
DidRenameFiles, DidSaveTextDocument, LogMessage, Notification as _,
};
use lsp_types::{
DeleteFilesParams, DidChangeConfigurationParams, DidChangeTextDocumentParams,
DidChangeWatchedFilesParams, DidChangeWorkspaceFoldersParams, DidCloseTextDocumentParams,
DidOpenTextDocumentParams, DidSaveTextDocumentParams, RenameFilesParams, Uri, WorkspaceFolder,
DidOpenTextDocumentParams, DidSaveTextDocumentParams, LogMessageParams, MessageType,
RenameFilesParams, Uri, WorkspaceFolder,
};
use serde::de::DeserializeOwned;
use super::batch::{widen_of, Widen};
use super::client::ms;
use super::Server;
use crate::{file_ops, settings, sync, watch};
use crate::{file_ops, lint, settings, sync, watch};
impl Server {
/// Handle one notification, timing it when `--verbose` asked. A
@@ -244,14 +245,62 @@ impl Server {
pub(super) fn apply_settings(&mut self, settings: settings::ClientSettings) {
let watched = self.workspace.filelist_path();
let linted = self.lint_selection();
// A `lucisv.lint.options` entry the registry refused is dropped, not
// fatal (`settings::rule_options`) — so the log line is the only way
// the user learns their option is doing nothing. Logged, not shown: a
// typo in a settings file is not worth a popup, and a client that
// resends its whole section would raise the same one repeatedly.
for warning in &settings.lint_option_warnings {
self.notify(
LogMessage::METHOD,
LogMessageParams {
typ: MessageType::WARNING,
message: format!("lucisv: {warning}"),
},
);
}
// A name in `lucisv.lint.select`/`ignore` the registry does not know is
// dropped just as silently, and the same typo in a `lucisv.toml`'s
// `[lint] select` has been said since §42. Said here too — but **once**
// per (setting, name): unlike the options warnings above, which cost a
// line each time the setting arrives, a client that re-pushes its whole
// section on every keystroke must not repeat these. A list the user
// edited re-arms whatever is new in it. See §2.9-29.
for warning in unsaid(&settings.lint_name_warnings, &self.said_lint_names) {
self.notify(
LogMessage::METHOD,
LogMessageParams {
typ: MessageType::WARNING,
message: format!("lucisv: {warning}"),
},
);
}
self.said_lint_names.clone_from(&settings.lint_name_warnings);
// And the same for `lucisv.lint.waivers`: a file that is not there, or
// a directive that does not parse, is dropped and said once — here,
// where the setting arrives, rather than on every keystroke from the
// lint pass that reads the files. Only the setting's own files are
// checked; a `lucisv.toml`'s `[lint] waivers` is that file's problem
// and `lucisv check` fails the run over it.
for problem in waiver_problems(&settings, self.workspace.roots()) {
self.notify(
LogMessage::METHOD,
LogMessageParams {
typ: MessageType::WARNING,
message: format!("lucisv: lucisv.lint.waivers: {problem}; ignored"),
},
);
}
// Only `exclude` and `filelist` change which files exist as far as
// this server is concerned; the other settings are read afresh by the
// next request that wants them and need no invalidation.
if self.workspace.set_client_settings(settings) {
self.reindex();
} else if self.lint_selection() != linted {
// `lucisv.lint.select`/`ignore` change which rules run and nothing
// else: no file's contents moved, so there is nothing to rescan —
// `lucisv.lint.select`/`ignore`, the class switches, the per-rule
// toggles and the per-rule *options* change which rules run and
// what they report, and nothing else: no file's contents moved,
// so there is nothing to rescan —
// but every published squiggle was drawn under the old selection,
// and a client that pulls has cached answers under it too.
self.generation += 1;
@@ -268,9 +317,13 @@ impl Server {
/// The rule selection in force, as a value two settings pushes can be
/// compared by.
fn lint_selection(&self) -> (Vec<String>, Vec<String>) {
let client = self.workspace.client_settings();
(client.lint_select.clone(), client.lint_ignore.clone())
///
/// All four lint settings, not just the two lists: since §33.1 a class
/// switch (`lucisv.lint.severity.*`) and a per-rule toggle
/// (`lucisv.lint.rules.*`) change which rules run too, and a change to one
/// of them must republish exactly as a change to `select`/`ignore` does.
fn lint_selection(&self) -> settings::LintSelection {
settings::lint_selection(self.workspace.client_settings())
}
}
@@ -301,3 +354,32 @@ fn closing_uri(notification: &Notification) -> Option<Uri> {
fn folder_paths(folders: &[WorkspaceFolder]) -> Vec<std::path::PathBuf> {
folders.iter().filter_map(|folder| crate::uri::uri_to_path(&folder.uri)).collect()
}
/// What `lucisv.lint.waivers` names that could not be used: a file that is not
/// there, or a directive that does not parse.
///
/// Read here rather than trusted, because a path is not something a settings
/// parser can validate: only opening the file says whether it exists. The
/// files are read again by the lint pass that actually applies them — a few
/// small files beside a parse and an analysis — which keeps one reader for
/// both and no cache to go stale when the user edits a waiver file.
fn waiver_problems(
settings: &settings::ClientSettings,
roots: &[std::path::PathBuf],
) -> Vec<String> {
if settings.lint_waivers.is_empty() {
return Vec::new();
}
let paths = lint::waiver_paths(settings, roots, &lucisv_core::config::FileConfig::default());
lint::external_waivers(&paths).1
}
/// The lines of `warnings` that `said` does not already hold, in order.
///
/// The whole of §45.1's "once": the memo is the previous settings value's own
/// warning list, so re-pushing a section says nothing and editing the list
/// says exactly what is new in it. Both lists are a handful of entries at
/// most — one per typo — so a scan is cheaper than a set.
fn unsaid<'a>(warnings: &'a [String], said: &[String]) -> Vec<&'a String> {
warnings.iter().filter(|w| !said.contains(w)).collect()
}
@@ -408,3 +408,95 @@ fn an_answer_to_a_request_the_server_never_tracked_is_silently_ignored() {
session.answer(RequestId::from("never-sent".to_string()), serde_json::json!([{ "indent": 2 }]));
assert_eq!(session.server.workspace.client_settings().indent, Some(4));
}
// ------------------------------------------------------------------
// the editor's unknown rule name (TODO §45.1, docs/topo.md §2.9-29)
// ------------------------------------------------------------------
/// A `didChangeConfiguration` push with the given `lucisv.lint` section.
fn push_lint(session: &mut Session, lint: Value) {
session.notify(
DidChangeConfiguration::METHOD,
serde_json::json!({ "settings": { "lucisv": { "lint": lint } } }),
);
}
/// The unknown-rule lines the server logged since the last drain.
fn unknown_rule_lines(session: &Session) -> Vec<String> {
session
.logged()
.into_iter()
.map(|(_, message)| message)
.filter(|message| message.contains("unknown rule"))
.collect()
}
#[test]
fn an_unknown_rule_name_in_the_editors_select_is_logged_once() {
let tree = Tree::new("unknownrule");
tree.write("m.sv", "module m;\nendmodule\n");
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
let _ = session.drain();
push_lint(&mut session, serde_json::json!({ "select": ["no-tabs", "no-tab"] }));
assert_eq!(
unknown_rule_lines(&session),
["lucisv: lucisv.lint.select: unknown rule: no-tab"],
"said once, naming the list and the name"
);
// Four diagnostics passes later it has not been said again: the pass runs
// on every keystroke and the log is not a place to shout from.
for _ in 0..4 {
session.server.publish(&uri);
}
assert!(unknown_rule_lines(&session).is_empty(), "not repeated by a diagnostics pass");
// Nor by the same section arriving again, which is what VS Code sends
// whenever anything at all in it changes.
push_lint(&mut session, serde_json::json!({ "select": ["no-tabs", "no-tab"] }));
assert!(unknown_rule_lines(&session).is_empty(), "not repeated by an identical push");
}
#[test]
fn a_changed_list_re_arms_the_log() {
let tree = Tree::new("unknownrulearm");
let mut session = Session::new(vec![tree.path.clone()], false);
let _ = session.drain();
push_lint(&mut session, serde_json::json!({ "select": ["no-tab"] }));
assert_eq!(unknown_rule_lines(&session).len(), 1);
// A second typo added to the list is new, and is said; the first is not.
push_lint(&mut session, serde_json::json!({ "select": ["no-tab", "nope"] }));
assert_eq!(
unknown_rule_lines(&session),
["lucisv: lucisv.lint.select: unknown rule: nope"],
"only what is new in the list"
);
// Cleared and re-typed: the memo is the previous value, so it is armed
// again.
push_lint(&mut session, serde_json::json!({ "select": [] }));
assert!(unknown_rule_lines(&session).is_empty(), "an empty list has nothing to say");
push_lint(&mut session, serde_json::json!({ "select": ["no-tab"] }));
assert_eq!(unknown_rule_lines(&session).len(), 1, "re-armed by the change");
}
#[test]
fn a_select_emptied_by_the_dropping_falls_through_the_ladder_unchanged() {
// §42's ladder: a `select` that named nothing the registry knows is an
// empty `select`, which is no opinion at all — the project's list, then
// the base set. The log line is the whole of what §45.1 changed.
let tree = Tree::new("unknownruleladder");
let mut session = Session::new(vec![tree.path.clone()], false);
let base = settings::lint_selection(session.server.workspace.client_settings());
let _ = session.drain();
push_lint(&mut session, serde_json::json!({ "select": ["no-tab", "nope"] }));
assert_eq!(unknown_rule_lines(&session).len(), 2, "both names said");
let now = session.server.workspace.client_settings();
assert!(now.lint_select.is_empty(), "the dropping left an empty select");
assert_eq!(settings::lint_selection(now), base, "and the rule set is untouched");
}
+476 -9
View File
@@ -13,9 +13,11 @@
//! Not to be confused with `format::Settings`, which is what one formatting
//! request resolved to after every rung of that ladder was applied.
use std::collections::BTreeMap;
use std::ops::RangeInclusive;
use serde_json::Value;
use vlog_linter::{OptionValue, RuleOptions, Severity};
/// Accepted `line-length`, and accepted `indent`.
///
@@ -104,6 +106,12 @@ pub struct ClientSettings {
/// or relative to the workspace root. Empty means "unset", which is what
/// the VS Code default is — see `docs/features/filelist/README.md`.
pub filelist: Option<String>,
/// `lucisv.format.uvmUtilsIndent`: whether the `` `uvm_field_* `` macros
/// written between `` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` are
/// indented one level. Unset means off, which is what the VS Code default
/// declares — the key changes bytes in files that already format cleanly,
/// so nothing turns it on for a user who did not ask.
pub uvm_utils_indent: Option<bool>,
/// `lucisv.inlineTemplates`: whether `if (` and `begin` grow ghost text.
/// Unset means on, which is what the VS Code default declares — see
/// `docs/features/inline-templates/README.md`.
@@ -174,6 +182,53 @@ pub struct ClientSettings {
/// `lucisv.lint.ignore`: rules dropped from whatever `select` left. Same
/// validation, same reason.
pub lint_ignore: Vec<String>,
/// `lucisv.lint.severity.error` / `.warning` / `.style`: the master switch
/// of each class. Every class is present and `true` unless a client turned
/// one off — see `lint::enabled_rules` for where it sits in the ladder.
pub lint_severity: BTreeMap<Severity, bool>,
/// `lucisv.lint.rules.<rule-name>`: the rules a client said something
/// **explicit** about — `true` for `on`, `false` for `off`.
///
/// A rule left at `default` is *absent from this map*, and that is the
/// whole reason the setting is a three-word enum rather than a boolean: a
/// client sends the whole section, every key at its default, so "unset"
/// and "set to the shipped value" would arrive identically and a per-rule
/// toggle nobody touched would silently override `select` and the class
/// switches.
pub lint_rules: BTreeMap<String, bool>,
/// `lucisv.lint.options`: `{"<rule>": {"<key>": value}}`, validated
/// against the rule registry.
///
/// Refused entries are **dropped**, not fatal — this module's standing
/// rule, and the reason it matters here more than anywhere else: one
/// typo in an options object must not be able to switch the linter off
/// for a whole session. What was refused is kept in
/// [`ClientSettings::lint_option_warnings`] so the user is told.
pub lint_options: RuleOptions,
/// One line per refused `lucisv.lint.options` entry, ready for a
/// `window/logMessage`. Empty for a settings push that was all valid.
pub lint_option_warnings: Vec<String>,
/// One line per name in `lucisv.lint.select` / `lucisv.lint.ignore` that
/// the registry does not know, in the shape
/// `lucisv.lint.select: unknown rule: <name>`.
///
/// Separate from [`ClientSettings::lint_option_warnings`] because the two
/// are said differently: an options warning is raised every time the
/// setting arrives, while an unknown name is said **once** per (setting,
/// name) and re-armed only when the list changes — a client that re-pushes
/// its whole section on every keystroke must not repeat it
/// (`docs/features/small-items-4/README.md`).
pub lint_name_warnings: Vec<String>,
/// `lucisv.lint.waivers`: external waiver files, each absolute or relative
/// to the first workspace root — the editor's spelling of
/// `lucisv check --waiver-file` and of `waivers` under `[lint]` in a
/// `lucisv.toml`. They **add** to whatever that table names.
///
/// The paths are taken as written and nothing is read here: whether a file
/// exists and whether its directives parse is answered where the files are
/// read (`lint::external_waivers`), and reported once through the log when
/// this value arrives.
pub lint_waivers: Vec<String>,
}
/// The settings a client that said nothing is treated as having asked for.
@@ -188,6 +243,7 @@ impl Default for ClientSettings {
indent: None,
exclude: Vec::new(),
filelist: None,
uvm_utils_indent: None,
inline_templates: None,
inline_instantiation: None,
format_on_save: false,
@@ -200,10 +256,54 @@ impl Default for ClientSettings {
large_file_threshold: DEFAULT_LARGE_FILE_THRESHOLD,
lint_select: Vec::new(),
lint_ignore: Vec::new(),
lint_severity: every_class_on(),
lint_rules: BTreeMap::new(),
lint_options: RuleOptions::new(),
lint_option_warnings: Vec::new(),
lint_name_warnings: Vec::new(),
lint_waivers: Vec::new(),
}
}
}
/// Every severity class switched on — what a client that said nothing means.
fn every_class_on() -> BTreeMap<Severity, bool> {
Severity::ALL.into_iter().map(|severity| (severity, true)).collect()
}
/// Everything about a settings value that decides **which rules run**: the two
/// name lists, the class switches and the per-rule toggles.
///
/// Its only use is equality — the server compares it across a settings change
/// to decide whether every open file must be published again.
pub type LintSelection = (
Vec<String>,
Vec<String>,
BTreeMap<Severity, bool>,
BTreeMap<String, bool>,
RuleOptions,
Vec<String>,
);
/// The lint settings of `settings`, as one comparable value.
///
/// The options are in here with the four that choose rules, because a changed
/// option changes what a rule *reports* — a `line-length` of 120 unpublishes
/// every finding drawn at 100 — and every open file must be published again
/// for exactly the same reason a changed selection does.
pub fn lint_selection(settings: &ClientSettings) -> LintSelection {
(
settings.lint_select.clone(),
settings.lint_ignore.clone(),
settings.lint_severity.clone(),
settings.lint_rules.clone(),
settings.lint_options.clone(),
// A waiver file added or dropped changes which findings survive, so it
// republishes for exactly the reason a changed option does.
settings.lint_waivers.clone(),
)
}
/// Read the `lucisv` section out of a `workspace/didChangeConfiguration` payload.
///
/// **Nothing here trusts the client.** `package.json`'s JSON schema constrains
@@ -231,11 +331,18 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
let large_file = lucisv.get("largeFile");
// And `lucisv.lint.select` / `lucisv.lint.ignore` the same way again.
let lint = lucisv.get("lint");
let (options, warnings) = rule_options(lint.and_then(|l| l.get("options")));
// The names the registry did not know, collected as the two lists are
// filtered so the user hears about a typo instead of losing a rule to it.
let mut names = Vec::new();
let lint_select = rules(lint.and_then(|l| l.get("select")), "select", &mut names);
let lint_ignore = rules(lint.and_then(|l| l.get("ignore")), "ignore", &mut names);
ClientSettings {
line_length: bounded(lucisv.get("lineLength"), LINE_LENGTH_RANGE),
indent: bounded(lucisv.get("indent"), INDENT_RANGE),
exclude: strings(lucisv.get("exclude")),
filelist: path(lucisv.get("filelist")),
uvm_utils_indent: flag(lucisv.get("format").and_then(|f| f.get("uvmUtilsIndent"))),
inline_templates: flag(lucisv.get("inlineTemplates")),
inline_instantiation: flag(lucisv.get("inlineInstantiation")),
// Anything that is not `true` leaves the hook declining, wrong-typed
@@ -272,19 +379,133 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
// prevent.
large_file_threshold: count(large_file.and_then(|f| f.get("threshold")))
.unwrap_or(DEFAULT_LARGE_FILE_THRESHOLD),
lint_select: rules(lint.and_then(|l| l.get("select"))),
lint_ignore: rules(lint.and_then(|l| l.get("ignore"))),
lint_select,
lint_ignore,
// `lucisv.lint.severity.<class>` and `lucisv.lint.rules.<name>` nest
// one level deeper again, for the same reason `index.*` does.
lint_severity: severity_switches(lint.and_then(|l| l.get("severity"))),
lint_rules: rule_toggles(lint.and_then(|l| l.get("rules"))),
lint_options: options,
lint_option_warnings: warnings,
lint_name_warnings: names,
// Paths, not rule names: nothing to validate against the registry, and
// a path that names nothing is reported when the file is read.
lint_waivers: strings(lint.and_then(|l| l.get("waivers"))),
}
}
/// The rule names in a settings array, dropping every one the registry does
/// not know.
/// The rule names in a settings array, dropping every one that names neither a
/// rule nor a severity class and describing each drop in `warnings`.
///
/// Silence rather than an error, on this module's standing rule: a push is
/// JSON on a socket, and a typo in one name must not cost the user every
/// diagnostic in the file. A dropped name leaves the rule where it was.
fn rules(value: Option<&Value>) -> Vec<String> {
strings(value).into_iter().filter(|name| vlog_linter::rule_by_name(name).is_some()).collect()
/// The drop itself is this module's standing rule: a push is JSON on a socket,
/// and a typo in one name must not cost the user every diagnostic in the file,
/// so a name the registry does not know leaves the rule where it was. Silence
/// about it was not the rule, only the state of things — `[lint] select` in a
/// `lucisv.toml` has said the same mistake out loud since §42, and this is the
/// editor's half of that (`docs/topo.md` §2.9-29).
///
/// `setting` is `select` or `ignore`, so the line names the list the user
/// typed in.
fn rules(value: Option<&Value>, setting: &str, warnings: &mut Vec<String>) -> Vec<String> {
strings(value)
.into_iter()
.filter(|name| {
let known = vlog_linter::rules_named(name).is_some();
if !known {
warnings.push(format!("lucisv.lint.{setting}: unknown rule: {name}"));
}
known
})
.collect()
}
/// The three class master switches, each `true` unless a client turned it off.
///
/// A missing or wrong-typed switch leaves its class on: the safe direction for
/// a switch that silences a whole family of diagnostics is the one that shows
/// them, exactly as an unreadable size cap leaves the cap on.
fn severity_switches(value: Option<&Value>) -> BTreeMap<Severity, bool> {
Severity::ALL
.into_iter()
.map(|severity| {
let on = flag(value.and_then(|v| v.get(severity.as_str()))).unwrap_or(true);
(severity, on)
})
.collect()
}
/// The rules a client said something explicit about: `on` and `off` only.
///
/// `default` — and any word that is neither, and any key that is not a rule —
/// contributes nothing, which is what leaves the rule wherever the rest of the
/// ladder put it. See [`ClientSettings::lint_rules`].
fn rule_toggles(value: Option<&Value>) -> BTreeMap<String, bool> {
let Some(Value::Object(map)) = value else { return BTreeMap::new() };
map.iter()
.filter(|(name, _)| vlog_linter::rule_by_name(name).is_some())
.filter_map(|(name, choice)| match choice.as_str() {
Some("on") => Some((name.clone(), true)),
Some("off") => Some((name.clone(), false)),
_ => None,
})
.collect()
}
/// The `lucisv.lint.options` object, validated against the rule registry.
///
/// The shape is `{"<rule>": {"<key>": value}}` — the nesting VS Code's
/// settings model produces for an object setting, and the one a hand-written
/// Neovim config writes. Every entry goes through the **same** validator a
/// `[lint.<rule>]` table in a `lucisv.toml` goes through
/// (`RuleOptions::set`), so an option means one thing in both front ends.
///
/// A refused entry is dropped and described, rather than failing the push:
/// the CLI can fail a run over a typo because a user typed it and is watching,
/// while a settings push arrives on a socket and failing it would leave an
/// editor with no diagnostics and no way to see why. The descriptions are
/// returned for the caller to log.
fn rule_options(value: Option<&Value>) -> (RuleOptions, Vec<String>) {
let mut options = RuleOptions::new();
let mut warnings = Vec::new();
let Some(Value::Object(rules)) = value else { return (options, warnings) };
for (rule, keys) in rules {
let Some(Value::Object(keys)) = Some(keys) else {
warnings.push(format!("lucisv.lint.options.{rule} is not an object; ignored"));
continue;
};
for (key, raw) in keys {
let Some(value) = option_value(raw) else {
warnings.push(format!(
"lucisv.lint.options.{rule}.{key}: {raw} is not a boolean, number, \
string or list of strings; ignored"
));
continue;
};
if let Err(problem) = options.set(rule, key, value) {
warnings.push(format!("lucisv.lint.options.{rule}.{key}: {problem}; ignored"));
}
}
}
(options, warnings)
}
/// One JSON value as an option value, or nothing for a shape no option takes.
///
/// Structural only — whether the *kind* is the one the option declares is
/// `RuleOptions::set`'s answer, so the error a user reads names the option
/// and its kind rather than JSON's.
fn option_value(raw: &Value) -> Option<OptionValue> {
match raw {
Value::Bool(b) => Some(OptionValue::Bool(*b)),
Value::Number(n) => n.as_i64().map(OptionValue::Int),
Value::String(s) => Some(OptionValue::Str(s.clone())),
Value::Array(items) => items
.iter()
.map(|item| item.as_str().map(str::to_string))
.collect::<Option<Vec<String>>>()
.map(OptionValue::List),
_ => None,
}
}
/// One of the two `lucisv.index.scope` words, or nothing. Matched exactly —
@@ -623,6 +844,252 @@ mod tests {
}
}
/// **The drift guard.** `editors/vscode/package.json` declares one switch
/// per severity class and one per rule, generated by
/// `vlog_linter::vscode_lint_settings`. This compares the two as JSON
/// *values*, so formatting is free but a rule added without its toggle —
/// or a summary, default or severity edited on one side only — fails here.
///
/// Regenerate with
/// `cargo run -p vlog_linter --example vscode_lint_settings`.
#[test]
fn the_vscode_lint_toggles_match_the_registry() {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../editors/vscode/package.json");
let text = std::fs::read_to_string(&path).expect("the extension manifest");
let manifest: Value = serde_json::from_str(&text).expect("valid json");
let properties = manifest["contributes"]["configuration"]["properties"]
.as_object()
.expect("a properties object");
let declared: serde_json::Map<String, Value> = properties
.iter()
.filter(|(key, _)| {
key.starts_with("lucisv.lint.severity.") || key.starts_with("lucisv.lint.rules.")
})
.map(|(key, value)| (key.clone(), value.clone()))
.collect();
let generated: Value = serde_json::from_str(&vlog_linter::vscode_lint_settings())
.expect("the generator emits valid json");
let generated = generated.as_object().expect("an object");
let names = |map: &serde_json::Map<String, Value>| {
let mut keys: Vec<String> = map.keys().cloned().collect();
keys.sort();
keys
};
assert_eq!(
names(&declared),
names(generated),
"package.json and the rule registry disagree about which lint settings exist; \
regenerate with `cargo run -p vlog_linter --example vscode_lint_settings`"
);
for (key, value) in generated {
assert_eq!(declared.get(key), Some(value), "{key} drifted");
}
// And every rule really does have one, which is the promise the whole
// generator exists to keep.
for rule in vlog_linter::all_rules() {
assert!(declared.contains_key(&vlog_linter::rule_setting(rule)), "{}", rule.name());
}
}
/// A default-everything payload — which is what a client sends for a user
/// who has touched nothing — must say nothing about any rule.
#[test]
fn the_shipped_lint_toggles_are_no_opinion() {
let mut rules = serde_json::Map::new();
for rule in vlog_linter::all_rules() {
rules.insert(rule.name().to_string(), json!("default"));
}
let found = settings(json!({"lucisv": {"lint": {
"severity": {"error": true, "warning": true, "style": true},
"rules": Value::Object(rules),
}}}));
assert_eq!(found, ClientSettings::default(), "every shipped value is silence");
}
#[test]
fn the_severity_switches_and_rule_toggles_are_read() {
let found = settings(json!({"lucisv": {"lint": {
"severity": {"style": false, "warning": "yes"},
"rules": {"no-tabs": "on", "unused-signal": "off", "empty-item": "default",
"no-such-rule": "on", "case-missing-default": 3},
}}}));
assert!(!found.lint_severity[&Severity::Style]);
assert!(found.lint_severity[&Severity::Warning], "a wrong type leaves it on");
assert!(found.lint_severity[&Severity::Error], "and so does absence");
assert_eq!(
found.lint_rules,
[("no-tabs".to_string(), true), ("unused-signal".to_string(), false)]
.into_iter()
.collect::<BTreeMap<_, _>>(),
"`default`, an unknown rule and a wrong-typed choice all say nothing"
);
// A `lint` that is not an object leaves every class on and nothing said.
let junk = settings(json!({"lucisv": {"lint": 7}}));
assert_eq!(junk.lint_severity, every_class_on());
assert!(junk.lint_rules.is_empty());
}
/// A severity word is a legal `select`/`ignore` entry since §33.0, so the
/// validating filter must keep it.
#[test]
fn a_severity_word_survives_the_select_and_ignore_filter() {
let found = settings(json!({"lucisv": {"lint": {
"select": ["style", "no-tabs", "nope"],
"ignore": ["warning"],
}}}));
assert_eq!(found.lint_select, vec!["style", "no-tabs"]);
assert_eq!(found.lint_ignore, vec!["warning"]);
// And the one name that is neither is described, not just dropped.
assert_eq!(found.lint_name_warnings, vec!["lucisv.lint.select: unknown rule: nope"]);
}
/// TODO §45.1: a name the registry does not know is still dropped — the
/// rule stays where it was — and now says so, once per name, naming the
/// list the user typed it in.
#[test]
fn an_unknown_rule_name_is_described_for_each_list_it_appears_in() {
let found = settings(json!({"lucisv": {"lint": {
"select": ["no-tabs", "nope", "also-nope"],
"ignore": ["nope"],
}}}));
assert_eq!(found.lint_select, vec!["no-tabs"]);
assert!(found.lint_ignore.is_empty());
assert_eq!(
found.lint_name_warnings,
vec![
"lucisv.lint.select: unknown rule: nope",
"lucisv.lint.select: unknown rule: also-nope",
"lucisv.lint.ignore: unknown rule: nope",
]
);
}
#[test]
fn two_lists_of_known_names_describe_nothing() {
let found = settings(json!({"lucisv": {"lint": {
"select": ["no-tabs", "error"],
"ignore": ["unused-signal"],
}}}));
assert!(found.lint_name_warnings.is_empty(), "{:?}", found.lint_name_warnings);
assert!(settings(json!({"lucisv": {}})).lint_name_warnings.is_empty());
}
/// What the server compares two settings pushes by, to decide whether the
/// squiggles it already drew are still right.
#[test]
fn the_lint_selection_notices_every_setting_that_changes_the_rule_set() {
let base = ClientSettings::default();
let mut severity = base.clone();
severity.lint_severity.insert(Severity::Style, false);
let mut toggled = base.clone();
toggled.lint_rules.insert("no-tabs".to_string(), false);
let mut selected = base.clone();
selected.lint_select = vec!["error".to_string()];
let mut ignored = base.clone();
ignored.lint_ignore = vec!["no-tabs".to_string()];
let mut configured = base.clone();
configured.lint_options.set_raw("line-length", "length", "120").expect("accepted");
for changed in [severity, toggled, selected, ignored, configured] {
assert_ne!(lint_selection(&base), lint_selection(&changed));
}
// A setting that does not change which rules run does not republish.
let mut unrelated = base.clone();
unrelated.indent = Some(4);
assert_eq!(lint_selection(&base), lint_selection(&unrelated));
}
/// §34.0(c): the object is read, validated against the registry, and a
/// bad entry is dropped **with a warning** rather than failing the push.
#[test]
fn the_lint_options_object_is_read_and_validated() {
let found = settings(json!({"lucisv": {"lint": {"options": {
"line-length": {"length": 120},
"generate-label-prefix": {"prefix": ["blk_"]},
"typedef-structs-unions": {"allow_anonymous_nested": true},
"signal-name-style": {"style_regex": "[a-z_0-9]+"},
}}}}));
assert_eq!(found.lint_options.int("line-length", "length"), 120);
assert_eq!(
found.lint_options.list("generate-label-prefix", "prefix"),
vec!["blk_".to_string()]
);
assert!(found.lint_options.bool("typedef-structs-unions", "allow_anonymous_nested"));
assert_eq!(found.lint_options.str("signal-name-style", "style_regex"), "[a-z_0-9]+");
assert!(found.lint_option_warnings.is_empty(), "{:?}", found.lint_option_warnings);
}
#[test]
fn a_refused_option_is_dropped_and_described_rather_than_fatal() {
let found = settings(json!({"lucisv": {"lint": {"options": {
"line-length": {"length": 10, "len": 120},
"no-such-rule": {"x": 1},
"no-tabs": {"width": 4},
"signal-name-style": {"style_regex": "[a-"},
"interface-name-style": {"style_regex": "\\bword\\b"},
"macro-name-style": {"style_regex": 4},
"package-filename": "not-an-object",
"port-name-suffix": {"suffixes": [1, 2]},
}}}}));
// Nothing was accepted, and every refusal says which entry and why.
assert!(found.lint_options.is_empty(), "{:?}", found.lint_options);
let warnings = found.lint_option_warnings.join("\n");
for wanted in [
"line-length.length",
"must be between",
"has no option `len`",
"unknown rule `no-such-rule`",
"takes no options",
"not a valid pattern",
"unsupported escape `\\b`",
"expects a pattern, found an integer",
"package-filename is not an object",
"port-name-suffix.suffixes",
] {
assert!(warnings.contains(wanted), "{wanted} missing from:\n{warnings}");
}
// ... and the rest of the settings survived the bad object.
assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE);
}
/// `lucisv.lint.waivers` is a list of paths, taken as written: this module
/// has no filesystem to check them against, and whether a file exists or
/// parses is answered where it is read. TODO §39.
#[test]
fn the_waivers_setting_is_a_list_of_paths_taken_as_written() {
let found = settings(json!({"lucisv": {"lint": {
"waivers": ["project.waiver", "/abs/other.waiver", 7, null]
}}}));
assert_eq!(found.lint_waivers, vec!["project.waiver", "/abs/other.waiver"]);
assert!(settings(json!({"lucisv": {"lint": {}}})).lint_waivers.is_empty());
// Wrong-typed altogether: the whole list is "no opinion", never a
// guess, exactly as `select` and `exclude` are.
for bad in [json!("project.waiver"), json!(3), json!(null), json!({"a": 1})] {
assert!(
settings(json!({"lucisv": {"lint": {"waivers": bad}}})).lint_waivers.is_empty(),
"waivers {bad} must be ignored"
);
}
// A changed list republishes, for the reason a changed option does.
let one = settings(json!({"lucisv": {"lint": {"waivers": ["a.waiver"]}}}));
let two = settings(json!({"lucisv": {"lint": {"waivers": ["b.waiver"]}}}));
assert_ne!(lint_selection(&one), lint_selection(&two));
}
/// A settings payload with no options object is exactly today's
/// behaviour: every rule reads its own default.
#[test]
fn no_options_object_means_every_default() {
for payload in [json!({"lucisv": {}}), json!({"lucisv": {"lint": {}}})] {
let found = settings(payload);
assert!(found.lint_options.is_empty());
assert!(found.lint_option_warnings.is_empty());
assert_eq!(found.lint_options.int("line-length", "length"), 100, "the spec default");
}
}
#[test]
fn the_default_vscode_payload_is_no_opinion_about_anything() {
// Every setting at its `package.json` default: nulls and an empty
+120 -20
View File
@@ -625,6 +625,15 @@ impl Workspace {
!self.roots.is_empty()
}
/// The workspace folders, in the order the client named them.
///
/// The first one is what a relative path in a setting is resolved against,
/// which is what [`Workspace::filelist_path`] does inline and what
/// `lucisv.lint.waivers` needs too.
pub fn roots(&self) -> &[PathBuf] {
&self.roots
}
/// The directories the folder scope walks: every directory a buffer has
/// been opened from this session, each raised `lucisv.index.scopeDepth`
/// levels. **Empty when the folder scope is not the active rung** — a
@@ -999,11 +1008,12 @@ impl Workspace {
self.docs.values().filter_map(|doc| doc.path.as_deref()).collect();
let mut skipped = 0usize;
let mut texts: Vec<(PathBuf, String)> = Vec::new();
let mut warnings: Vec<String> = Vec::new();
// The walk of the *added* directories alone, by the same rung-3 rules
// `folder_files` follows — the whole scope is the union of these walks,
// so the files this one finds beyond what is already indexed are
// exactly the ones the widen owes.
for path in self.widened_files(added) {
for path in self.widened_files(added, &mut |w| warnings.push(w)) {
// Already indexed: by another scope directory this walk overlaps,
// or by an earlier scan. Re-reading it is the cost this path
// exists to avoid.
@@ -1064,9 +1074,9 @@ impl Workspace {
// `+incdir+`. Carried from the graph in hand rather than assumed
// empty, so folding a widen in never *changes* the search path.
incdirs: self.includes.incdirs().to_vec(),
// Warnings come from resolving the scope, and a widen resolves no
// filelist: rung 1 is not a scope an open buffer can widen.
warnings: Vec::new(),
// A widen resolves no filelist — rung 1 is not a scope an open
// buffer can widen — so the only warnings here are the walk's own.
warnings,
at: 0,
staged: Vec::new(),
staged_at: Vec::new(),
@@ -1079,11 +1089,11 @@ impl Workspace {
/// The files the directories a widen added bring into scope, by the same
/// rules [`Workspace::folder_files`] applies to the whole scope — including
/// the rootless-at-depth-0 flat read.
fn widened_files(&self, added: &[PathBuf]) -> Vec<PathBuf> {
fn widened_files(&self, added: &[PathBuf], warn: &mut dyn FnMut(String)) -> Vec<PathBuf> {
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
return sibling_files(added);
}
self.walked_files(added)
self.walked_files(added, warn)
}
/// Index the next file of `scan`, reporting whether there was one.
@@ -1511,6 +1521,10 @@ impl Workspace {
/// `follow_paths` only ever looks a reference's *own* name up, so a
/// set holding every declarer of `N` resolves every reference spelling
/// `N` exactly as the whole workspace does;
/// * **every file declaring `N` on a module's hierarchical surface**
/// ([`WorkspaceIndex::hierarchical_declarations`]) — an internal net
/// is not a workspace symbol, and a hierarchical tail in another file
/// resolves to one;
/// * **every file with a use the index resolved to one of them**
/// ([`WorkspaceIndex::references_to`]) — every file a rename can edit,
/// and every file whose meaning the verifier could see move;
@@ -1594,6 +1608,19 @@ impl Workspace {
containers.extend(symbol.container);
self.want_declaration(symbol.def, wanted);
}
// And every declaration of it on a module's **hierarchical** surface,
// which `workspace_symbols` deliberately does not list: an internal
// net is not a workspace symbol, but `assign w = u_x.sig;` in another
// file resolves to one and a rename must edit both ends. Without this
// rung the fan-out would hold the file that *names* the net and not
// the file that declares it (`docs/features/hierarchical-tail`).
for (unit, def) in self.index.hierarchical_declarations(name) {
if self.index.references_are_ambiguous(def) {
return false;
}
containers.insert(unit);
self.want_declaration(def, wanted);
}
self.want_sites(name, wanted);
self.want_macro_text(name, wanted);
for unit in containers {
@@ -1797,6 +1824,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>> {
@@ -1847,16 +1885,21 @@ impl Workspace {
/// none, so an `` `include`` there resolves against the including file's
/// own directory alone (`docs/features/include-nav/README.md`).
fn source_files(&self) -> Scope {
// The walk's own warnings join the scope's, so an unreadable directory
// reaches the output channel by the road a filelist's problems already
// travel — said once per scan and never per keystroke.
let mut warnings: Vec<String> = Vec::new();
let Some(path) = self.filelist_path() else {
return Scope { files: self.default_files(), ..Default::default() };
let files = self.default_files(&mut |w| warnings.push(w));
return Scope { files, warnings, ..Default::default() };
};
match lucisv_core::filelist::read(&path) {
Ok(list) => Scope { files: list.files, incdirs: list.incdirs, warnings: list.warnings },
Err(problem) => Scope {
files: self.default_files(),
incdirs: Vec::new(),
warnings: vec![format!("{problem} — indexing the workspace instead")],
},
Err(problem) => {
let files = self.default_files(&mut |w| warnings.push(w));
warnings.insert(0, format!("{problem} — indexing the workspace instead"));
Scope { files, incdirs: Vec::new(), warnings }
}
}
}
@@ -1883,11 +1926,11 @@ impl Workspace {
/// Rungs 2 and 3 of the ladder: the whole-workspace walk when the client
/// asked for it, else the folder scope.
fn default_files(&self) -> Vec<PathBuf> {
fn default_files(&self, warn: &mut dyn FnMut(String)) -> Vec<PathBuf> {
if self.walks_the_workspace() {
return self.walked_files(&self.roots);
return self.walked_files(&self.roots, warn);
}
self.folder_files()
self.folder_files(warn)
}
/// Rung 3: the folder scope — [`Workspace::scope_dirs`], walked with every
@@ -1899,12 +1942,12 @@ impl Workspace {
/// case, where descending a tree the user never named would be a surprise
/// — and the moment the user raises `scopeDepth` they have named one, so
/// the walk is what they asked for.
fn folder_files(&self) -> Vec<PathBuf> {
fn folder_files(&self, warn: &mut dyn FnMut(String)) -> Vec<PathBuf> {
let dirs = self.scope_dirs();
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
return sibling_files(&dirs);
}
self.walked_files(&dirs)
self.walked_files(&dirs, warn)
}
/// Every source file under `dirs`, found by the CLI's own walk: the same
@@ -1918,7 +1961,7 @@ impl Workspace {
/// written in a root's `.gitignore` does not apply to a rung-3 walk that
/// starts below it. The `exclude` patterns are matched against whole
/// paths and so behave identically either way.
fn walked_files(&self, dirs: &[PathBuf]) -> Vec<PathBuf> {
fn walked_files(&self, dirs: &[PathBuf], warn: &mut dyn FnMut(String)) -> Vec<PathBuf> {
let mut discovery = Discovery::new(true);
let mut out = Vec::new();
for root in dirs {
@@ -1938,8 +1981,9 @@ impl Workspace {
exclude.extend(self.client.exclude.iter().cloned());
// `.gitignore` is always honoured: it is the CLI's default, and an
// editor has no `--no-gitignore` to type. An unreadable directory
// is simply not indexed, exactly as before this walk was shared.
let _ = collect_files(input, &exclude, true, &mut out);
// is skipped and said — the warning rides out on the scope's own
// warnings, which `server/notification.rs` logs once per scan.
let _ = collect_files(input, &exclude, true, &mut out, &mut |w| warn(w.to_string()));
}
out.sort();
out.dedup();
@@ -2710,6 +2754,33 @@ mod tests {
);
}
/// A workspace whose tree links back into itself. Before the walk kept a
/// visited set (`docs/features/walk-cycles/README.md`) this scan never
/// finished — the editor's index simply never came up. Each directory is
/// entered once now, so each package is registered exactly once: a second
/// registration would make the name *ambiguous*, and `indexed` only
/// counts a name found exactly once.
#[cfg(unix)]
#[test]
fn a_cyclic_workspace_is_scanned_once_and_finishes() {
let tree = Tree::new("cycle");
tree.package("rtl/a.sv", "a");
tree.package("rtl/sub/b.sv", "b");
// `rtl/self` is `rtl` itself; `rtl/sub/up` is `rtl` from one level
// down. Either one alone runs until the OS refuses a path.
std::os::unix::fs::symlink("../rtl", tree.path.join("rtl/self")).expect("symlink");
std::os::unix::fs::symlink("..", tree.path.join("rtl/sub/up")).expect("symlink");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b"]), ["a", "b"]);
assert_eq!(
ws.walked_files(from_ref(&tree.path), &mut |_| {}).len(),
2,
"two files, once each"
);
}
#[test]
fn a_folder_change_that_changes_nothing_asks_for_no_rescan() {
// Every no-op shape a client can send. Each must leave the root set
@@ -3317,6 +3388,35 @@ mod tests {
assert!(warnings[0].contains("indexing the workspace instead"), "{warnings:?}");
}
#[test]
#[cfg(unix)]
fn an_unreadable_directory_is_said_once_per_scan_and_the_rest_is_indexed() {
// TODO §45.2: the walk's warnings ride out on the scope's own
// warnings, which the server logs once per scan. Before the channel
// existed the walk returned an error the index simply dropped, so a
// permission-denied directory cost every file after it silently.
use std::os::unix::fs::PermissionsExt;
let tree = Tree::new("walkwarn");
tree.package("rtl/a.sv", "a");
tree.package("rtl/z.sv", "z");
tree.package("locked/hidden.sv", "hidden");
std::os::unix::fs::symlink("nowhere.sv", tree.path.join("rtl/gone.sv")).expect("symlink");
let locked = tree.path.join("locked");
fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).expect("chmod");
let mut ws = Workspace::default();
let warnings = ws.open_whole_workspace(vec![tree.path.clone()]);
let _ = fs::set_permissions(&locked, fs::Permissions::from_mode(0o755));
assert_eq!(indexed(&ws, &["a", "z", "hidden"]), ["a", "z"], "the scan finished");
assert_eq!(warnings.len(), 2, "{warnings:?}");
assert!(warnings.iter().any(|w| w.contains("locked")), "{warnings:?}");
assert!(
warnings.iter().any(|w| w.contains("gone.sv: broken symbolic link")),
"{warnings:?}"
);
}
#[test]
fn a_filelists_own_warnings_reach_the_caller() {
let tree = filelist_tree("filelistwarn");
+6 -2
View File
@@ -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)]
+11
View File
@@ -456,6 +456,17 @@ mod tests {
}
}
/// The premise [`every_untouched_expansion_parses`] rests on: the probe
/// can still fail. Header recovery (TODO §32) widened what a tolerant
/// parse reads, and a probe that answered "clean" for everything would
/// pass that test while proving nothing.
#[test]
fn the_expansion_probe_still_reports_text_that_does_not_parse() {
let probe = "module p;\n always_comb begin\n case (sel\n end\nendmodule\n";
let (_, diagnostics) = vlog_parser::parse_source_tolerant(probe);
assert!(!diagnostics.is_empty(), "recovery must not make a broken expansion look clean");
}
#[test]
fn every_hole_is_a_tabstop_the_snippet_grammar_reads() {
// The editor-snippets lesson, restated for generated text: VS Code
+10 -7
View File
@@ -41,7 +41,7 @@
use lsp_types::{Location, Uri};
use vlog_parser::ast::{
AnsiPort, DataType, Declarator, GenBlock, GenElse, GenIf, Instantiation, Item, ItemKind,
Module, ParamPort, PortList, Stmt, StmtKind, StructType, TfArg, TypeExtra, Typedef,
ListElem, Module, ParamPort, PortList, Stmt, StmtKind, StructType, TfArg, TypeExtra, Typedef,
TypedefKind,
};
use vlog_parser::TextRange;
@@ -180,6 +180,7 @@ fn item_site(item: &Item, offset: u32) -> Option<Site<'_>> {
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => {
site_at(items, offset)
}
ItemKind::GenBlock(b) => gen_block_site(b, offset),
ItemKind::GenIf(g) => gen_if_site(g, offset),
ItemKind::GenFor(g) => gen_block_site(&g.body, offset),
ItemKind::GenCase(g) => g.items.iter().find_map(|arm| gen_block_site(&arm.body, offset)),
@@ -250,18 +251,20 @@ fn module_site(m: &Module, offset: u32) -> Option<Site<'_>> {
.or_else(|| site_at(&m.items, offset))
}
fn ansi_port_site(ports: &[AnsiPort], offset: u32) -> Option<Site<'_>> {
let port = ports.iter().find(|p| p.span.contains(offset))?;
// The three header lists below skip their error elements: text a tolerant
// parse could not read names no type, so there is no definition to go to.
fn ansi_port_site(ports: &[ListElem<AnsiPort>], offset: u32) -> Option<Site<'_>> {
let port = ports.iter().filter_map(ListElem::ok).find(|p| p.span.contains(offset))?;
site(&port.ty.name, TextRange::new(port.span.start, port.name_span.start))
}
fn param_port_site(ports: &[ParamPort], offset: u32) -> Option<Site<'_>> {
let port = ports.iter().find(|p| p.span.contains(offset))?;
fn param_port_site(ports: &[ListElem<ParamPort>], offset: u32) -> Option<Site<'_>> {
let port = ports.iter().filter_map(ListElem::ok).find(|p| p.span.contains(offset))?;
site(&port.ty.name, TextRange::new(port.span.start, port.name_span.start))
}
fn tf_arg_site(args: &[TfArg], offset: u32) -> Option<Site<'_>> {
let arg = args.iter().find(|a| a.span.contains(offset))?;
fn tf_arg_site(args: &[ListElem<TfArg>], offset: u32) -> Option<Site<'_>> {
let arg = args.iter().filter_map(ListElem::ok).find(|a| a.span.contains(offset))?;
site(&arg.ty.name, TextRange::new(arg.span.start, arg.name_span.start))
}
File diff suppressed because it is too large. Load diff
+1
View File
@@ -245,6 +245,7 @@ fn scan_nested(src: &str, item: &Item, out: &mut Vec<Region>) {
ItemKind::Module(m) => scan_scope(src, &m.items, &m.dangling, out),
ItemKind::Package { items, dangling, .. } => scan_scope(src, items, dangling, out),
ItemKind::GenerateRegion { items, dangling } => scan_scope(src, items, dangling, out),
ItemKind::GenBlock(b) => scan_gen_block(src, b, out),
ItemKind::GenIf(g) => scan_gen_if(src, g, out),
ItemKind::GenFor(g) => scan_gen_block(src, &g.body, out),
ItemKind::GenCase(g) => {
+10 -2
View File
@@ -38,7 +38,11 @@ impl<'a> Fmt<'a> {
if let Some(params) = &c.param_ports {
let items: Vec<ListItem> = params
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma))
.map(|p| {
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma)
})
})
.collect();
let items = self.list_entries(items, &c.param_directives);
let broken = !c.param_directives.is_empty();
@@ -52,7 +56,11 @@ impl<'a> Fmt<'a> {
if let Some(params) = &ext.params {
let items: Vec<ListItem> = params
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.connection(p)).with_comma(p.comma))
.map(|p| {
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.connection(p)).with_comma(p.comma)
})
})
.collect();
let items = self.list_entries(items, &ext.param_directives);
let broken = !ext.param_directives.is_empty();
+35 -7
View File
@@ -11,6 +11,7 @@ use crate::doc::*;
use vlog_parser::ast::*;
use super::comment::is_line_comment;
use super::instance::drive_strength;
use super::list::ListItem;
use super::{name_doc, Fmt};
@@ -296,22 +297,49 @@ impl<'a> Fmt<'a> {
pub(super) fn data_decl(&self, d: &DataDecl) -> Doc {
let mut docs = Vec::new();
if let Some(net) = &d.net {
docs.push(text(format!("{net} ")));
}
if let Some(delay) = &d.delay {
docs.push(text("#"));
docs.push(self.expr(delay));
docs.push(text(" "));
docs.push(text(net.clone()));
// `wire (strong0, weak1) #5 w;` — the strength stands between the
// net keyword and the delay, and owns the gap in front of its `(`.
if let Some(s) = &d.strength {
docs.push(drive_strength(self, s));
}
self.net_delay(d, false, &mut docs);
}
self.qualifier_run(&d.qualifiers, &mut docs);
if let Some(t) = self.data_type(&d.ty) {
docs.push(t);
docs.push(text(" "));
self.net_delay(d, true, &mut docs);
}
// Neither arm needs an `else`: a delay before the type is only read
// after a net keyword, and one after the type only when a type was
// actually written, so an implicit type has none to print.
docs.push(self.declarators(&d.declarators));
concat(docs)
}
/// The separator that follows the word just emitted, and then `#5` when
/// the declaration's net delay was written on the side of the data type
/// `after_type` names. IEEE 1800 §6.7 allows either side and lucisv
/// prints it where the source put it; moving it across the type would
/// reorder tokens, which `verify.rs` refuses.
///
/// The separator is the delay's `before_hash` comments when it has any
/// (`wire /* c */ #5 w;`) and a plain space otherwise — so a declaration
/// with no comment there is laid out exactly as it was before the slot
/// existed, delay or no delay.
fn net_delay(&self, d: &DataDecl, after_type: bool, docs: &mut Vec<Doc>) {
let delay = d.delay.as_ref().filter(|n| n.after_type == after_type);
match delay.map(|n| &n.before_hash).filter(|c| !c.is_empty()) {
Some(comments) => self.inline_comments_spaced(comments, docs),
None => docs.push(text(" ")),
}
let Some(delay) = delay else { return };
docs.push(text("#"));
self.slot_comments(&delay.after_hash, docs);
docs.push(self.expr(&delay.expr));
docs.push(text(" "));
}
pub(super) fn port_decl(&self, d: &PortDecl) -> Doc {
let mut docs = vec![text(format!("{} ", d.dir))];
if let Some(net) = &d.net {
+33 -4
View File
@@ -169,12 +169,16 @@ impl<'a> Fmt<'a> {
text("}"),
]),
// `{<<8{v}}` — written tight, like a replication.
ExprKind::Stream { dir, slice, inner } => {
let mut docs = vec![text("{"), text(dir.clone())];
ExprKind::Stream { dir, slice, inner, comments } => {
let mut docs = vec![text("{")];
self.slot_comments(&comments.after_open, &mut docs);
docs.push(text(dir.clone()));
if let Some(s) = slice {
docs.push(self.expr(s));
}
self.slot_comments(&comments.before_inner, &mut docs);
docs.push(self.expr_list("{", inner, "}"));
self.slot_comments(&comments.before_close, &mut docs);
docs.push(text("}"));
concat(docs)
}
@@ -241,6 +245,17 @@ impl<'a> Fmt<'a> {
ExprKind::With { base, arg, comments } => {
concat(vec![self.with_head(base, comments), self.expr(arg)])
}
// `a with [0:3]` — the same head every postfix `with` has, then
// the bracket printed through the slots a part select's uses.
ExprKind::StreamWith { base, range } => {
let mut docs = vec![self.with_head(base, &range.with_comments)];
let rest = match (&range.op, &range.lsb) {
(Some(op), Some(lsb)) => Some((op.as_str(), self.expr_compact(lsb))),
_ => None,
};
docs.push(self.bracket_slots(&range.comments, self.expr_compact(&range.msb), rest));
concat(docs)
}
ExprKind::WithConstraint { base, block, comments } => {
let body = match &**block {
ConstraintBody::Items(set) => self.with_constraint_block(set),
@@ -305,8 +320,22 @@ impl<'a> Fmt<'a> {
// region never begins its own line, so a dedent-by-column would
// drift instead of reaching a fixed point.
ExprKind::Verbatim(raw) => self.raw_inline(raw),
ExprKind::MinTypMax { min, typ, max } => {
concat(vec![self.expr(min), text(":"), self.expr(typ), text(":"), self.expr(max)])
// Unreachable from `format_source`, as `ItemKind::Error` is: only
// a tolerant parse builds this leaf, and the formatter parses
// strictly. Printed verbatim so nothing is lost if that ever
// changes — see `ListItem::from_raw`.
ExprKind::Error(raw) => self.raw_inline(raw),
ExprKind::MinTypMax { min, typ, max, comments } => {
let mut docs = vec![self.expr(min)];
self.slot_comments(&comments.before_typ, &mut docs);
docs.push(text(":"));
self.slot_comments(&comments.after_typ, &mut docs);
docs.push(self.expr(typ));
self.slot_comments(&comments.before_max, &mut docs);
docs.push(text(":"));
self.slot_comments(&comments.after_max, &mut docs);
docs.push(self.expr(max));
concat(docs)
}
}
}
+125 -27
View File
@@ -28,7 +28,11 @@ impl<'a> Fmt<'a> {
if let Some(params) = &inst.params {
let items: Vec<ListItem> = params
.iter()
.map(|c| ListItem::from_meta(&c.meta, self.connection(c)).with_comma(c.comma))
.map(|c| {
self.list_elem(c, |c| {
ListItem::from_meta(&c.meta, self.connection(c)).with_comma(c.comma)
})
})
.collect();
let items = self.list_entries(items, &inst.param_directives);
let broken = !inst.param_directives.is_empty() || holds_verbatim_value(params);
@@ -109,19 +113,23 @@ impl<'a> Fmt<'a> {
list.iter()
.zip(&aligns)
.map(|(c, a)| {
ListItem::from_meta(&c.meta, self.connection_aligned(c, a.as_ref()))
.with_comma(c.comma)
self.list_elem(c, |c| {
ListItem::from_meta(&c.meta, self.connection_aligned(c, a.as_ref()))
.with_comma(c.comma)
})
})
.collect()
}
Connections::Ordered(list) => list
.iter()
.map(|c| {
let d = match &c.expr {
Some(e) => self.expr(e),
None => text(""),
};
ListItem::from_meta(&c.meta, d).with_comma(c.comma)
self.list_elem(c, |c| {
let d = match &c.expr {
Some(e) => self.expr(e),
None => text(""),
};
ListItem::from_meta(&c.meta, d).with_comma(c.comma)
})
})
.collect(),
};
@@ -132,18 +140,20 @@ impl<'a> Fmt<'a> {
/// The alignment plan for an instance's named connection list.
fn connection_aligns(
&self,
conns: &[Connection],
conns: &[ListElem<Connection>],
directives: &[ListDirective],
depth: usize,
) -> Vec<Option<Align>> {
let rows: Vec<Option<Row>> = conns
.iter()
.map(|c| {
// An error element has no cells to align, so it has no row.
let c = c.ok()?;
let paren = self.open_paren_offset(c.name_span.end)?;
Self::row_of(&self.connection_cells(c), vec![paren], usize::from(c.comma))
})
.collect();
let breaks = Self::list_breaks(conns.iter().map(|c| &c.meta), directives);
let breaks = Self::list_breaks(conns.iter().map(|c| c.ok().map(|c| &c.meta)), directives);
self.align_groups(&rows, &breaks, CONNECTION_COLS, depth)
}
@@ -330,32 +340,85 @@ impl<'a> Fmt<'a> {
pub(super) fn gate_instantiation(&self, g: &GateInstantiation) -> Doc {
let mut docs = vec![text(g.gate.clone())];
if let Some(s) = &g.strength {
docs.push(text(format!(" {}", drive_strength(s))));
docs.push(drive_strength(self, s));
}
if !g.delay.is_empty() {
// The gap in front of the `#` is a space unless the source wrote
// a comment in it, exactly as a net delay's `before_hash` is.
match g.before_hash.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(&g.before_hash, &mut docs),
}
docs.push(text("#"));
self.slot_comments(&g.after_hash, &mut docs);
}
if let [delay] = g.delay.as_slice() {
// One value prints itself, brackets and all (`#5`, `#(5)`).
docs.push(text(" #"));
docs.push(self.expr(delay));
docs.push(self.expr(&delay.expr));
} else if !g.delay.is_empty() {
// `#(rise, fall[, turn-off])` — the parens are the list's own.
docs.push(text(" #("));
// `#(rise, fall[, turn-off])` — the parens and the commas are the
// list's own, so the comments written around them are too.
docs.push(text("("));
for (i, d) in g.delay.iter().enumerate() {
if i > 0 {
docs.push(text(", "));
docs.push(text(","));
match d.leading.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(&d.leading, &mut docs),
}
} else {
self.slot_comments(&d.leading, &mut docs);
}
docs.push(self.expr(d));
docs.push(self.expr(&d.expr));
self.slot_comments(&d.trailing, &mut docs);
}
docs.push(text(")"));
}
let last = g.instances.len().saturating_sub(1);
// True once a trailing comment has ended the previous instance's line:
// the next instance then starts on a fresh, indented line, and the
// space that normally separates it from the `,` is not written.
let mut broke = false;
for (i, inst) in g.instances.iter().enumerate() {
docs.push(if i > 0 { text(", ") } else { text(" ") });
// What stands between the delay (or the previous instance's `,`)
// and this instance's name — a space when nothing does.
match (broke, inst.meta.leading.is_empty()) {
(true, true) => {}
(false, true) => docs.push(text(" ")),
(_, false) => self.inline_comments_spaced(&inst.meta.leading, &mut docs),
}
broke = false;
if let Some(name) = &inst.name {
docs.push(name_doc(name));
docs.push(text(" "));
match inst.before_args.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(&inst.before_args, &mut docs),
}
}
docs.push(self.expr_list("(", &inst.args, ")"));
if i == last {
continue;
}
// Comments written between the instance and its `,` print on the
// instance's side of it, as every list element's do.
if self.inline_comments(&inst.meta.before_sep, &mut docs) {
docs.push(Doc::HardLine);
}
docs.push(text(","));
if let Some(tr) = &inst.meta.trailing {
docs.push(text(" "));
docs.push(self.comment(tr));
// A line comment ends the line (a `// p` would otherwise
// swallow the next instance on re-lex — §45's QA); the next
// instance continues one level in. A block comment stays
// inline, as the case table for this slot expects.
if is_line_comment(&tr.text) {
docs.push(indent(vec![Doc::HardLine]));
broke = true;
}
}
}
docs.push(text(";"));
docs.push(self.semi(&g.before_semi));
concat(docs)
}
}
@@ -369,17 +432,52 @@ impl<'a> Fmt<'a> {
/// be measured as one short line and flattened around a value that is
/// twenty lines tall. It is exactly the reason a list holding a
/// [`ListDirective`] is broken, for exactly the same construct.
fn holds_verbatim_value(list: &[Connection]) -> bool {
list.iter().any(|c| match &c.expr {
fn holds_verbatim_value(list: &[ListElem<Connection>]) -> bool {
list.iter().filter_map(ListElem::ok).any(|c| match &c.expr {
Some(Expr { kind: ExprKind::Verbatim(raw), .. }) => raw.text.contains('\n'),
_ => false,
})
}
/// `(weak0, pull1)`, or the single-strength `(weak1)` a pull gate may write.
pub(super) fn drive_strength(s: &DriveStrength) -> String {
match &s.second {
Some(second) => format!("({}, {})", s.first, second),
None => format!("({})", s.first),
/// `(weak0, pull1)`, or the single-strength `(weak1)` a pull gate may write —
/// with the comments written in any of its five gaps back where they stood.
///
/// The gap in front of the `(` is the strength's own (`assign /*c*/ (weak0,
/// pull1) x = y;`), so — exactly as a net delay's `before_hash` is — this
/// prints the separator that precedes the `(` too: the comments when the
/// source wrote any there, and a plain space when it did not. A caller emits
/// nothing of its own in front of the call.
pub(super) fn drive_strength(fmt: &Fmt<'_>, s: &DriveStrength) -> Doc {
let c = &s.comments;
if c.before_open.is_empty()
&& c.after_open.is_empty()
&& c.before_comma.is_empty()
&& c.after_comma.is_empty()
&& c.before_close.is_empty()
{
return match &s.second {
Some(second) => text(format!(" ({}, {})", s.first, second)),
None => text(format!(" ({})", s.first)),
};
}
let mut docs = Vec::new();
match c.before_open.is_empty() {
true => docs.push(text(" ")),
false => fmt.inline_comments_spaced(&c.before_open, &mut docs),
}
docs.push(text("("));
fmt.slot_comments(&c.after_open, &mut docs);
docs.push(text(s.first.clone()));
if let Some(second) = &s.second {
fmt.slot_comments(&c.before_comma, &mut docs);
docs.push(text(","));
match c.after_comma.is_empty() {
true => docs.push(text(" ")),
false => fmt.inline_comments_spaced(&c.after_comma, &mut docs),
}
docs.push(text(second.clone()));
}
fmt.slot_comments(&c.before_close, &mut docs);
docs.push(text(")"));
concat(docs)
}
+97 -27
View File
@@ -66,23 +66,64 @@ impl<'a> Fmt<'a> {
pub(super) fn item_seq(&self, items: &[Item], depth: usize) -> Vec<Doc> {
let aligns = self.param_decl_aligns(items, depth);
let mut docs = Vec::new();
// The items between a `` `uvm_object_utils_begin `` and its `_end`,
// one entry per `_begin` still open while `uvm-utils-indent` is on.
// They are collected apart so each run can be indented at once — the
// macros declare no block, so there is nothing else to indent them by
// — and they are a stack so an `_end` closes the `_begin` it matches.
let mut utils: Vec<Vec<Doc>> = Vec::new();
// The last item that actually emitted something, which is what a
// glued null item glues to.
let mut prev: Option<&Item> = None;
let mut emitted = false;
for (item, align) in items.iter().zip(&aligns) {
let item_docs = self.item_docs(item, align.as_ref(), depth);
if item_docs.is_empty() {
continue;
}
if !docs.is_empty() && !prev.is_some_and(|p| self.glued_null_item(p, item)) {
docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
// The `_end` closes the level the innermost open `_begin` opened,
// so it prints back in that `_begin`'s own column. An `_end` with
// nothing open closes nothing and moves no indentation.
if self.at_utils_macro(item, "_end") {
if let Some(open) = utils.pop() {
utils.last_mut().unwrap_or(&mut docs).push(indent(open));
}
}
docs.extend(item_docs);
let sink = utils.last_mut().unwrap_or(&mut docs);
if emitted && !prev.is_some_and(|p| self.glued_null_item(p, item)) {
sink.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
}
sink.extend(item_docs);
prev = Some(item);
emitted = true;
if self.cfg.uvm_utils_indent && self.at_utils_macro(item, "_begin") {
utils.push(Vec::new());
}
}
// A `_begin` with no `_end` still prints everything it opened, one
// level in: lucisv reproduces the file it was given, unbalanced
// macros and all.
while let Some(open) = utils.pop() {
utils.last_mut().unwrap_or(&mut docs).push(indent(open));
}
docs
}
/// True when `item` is a `` `uvm_object_utils_begin `` /
/// `` `uvm_component_utils_begin `` macro (`suffix` = `"_begin"`) or the
/// matching `_end`.
///
/// Exactly those four names, matched on the macro's own text: the
/// `uvm-utils-indent` key is a targeted rule for one UVM idiom, not a
/// general "indent between two macros" heuristic that would guess at
/// anybody else's macros.
fn at_utils_macro(&self, item: &Item, suffix: &str) -> bool {
let ItemKind::MacroItem(m) = &item.kind else { return false };
let name = m.raw.text.trim_start_matches('`');
let name = name.split(['(', ' ', '\t']).next().unwrap_or("");
matches!(name.strip_suffix(suffix), Some("uvm_object_utils" | "uvm_component_utils"))
}
/// True when `item` is a null item (`;`) the source wrote on the line the
/// item before it ended on, which is how it is printed back:
/// `endgenerate;`, `end;`, `endmodule;`, `;;`.
@@ -274,6 +315,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),
@@ -337,18 +393,24 @@ impl<'a> Fmt<'a> {
// written after the keyword, and print there.
let lead = a.assigns.first().map(|p| p.meta.leading.as_slice()).unwrap_or(&[]);
let mut docs = vec![text("assign")];
// A strength owns the gap in front of its `(` — including the space —
// so it goes in before the separator the rest of the head needs.
if let Some(s) = &a.strength {
docs.push(drive_strength(self, s));
}
if lead.is_empty() {
docs.push(text(" "));
} else {
self.inline_comments_spaced(lead, &mut docs);
}
if let Some(s) = &a.strength {
docs.push(text(format!("{} ", drive_strength(s))));
}
if let Some(delay) = &a.delay {
docs.push(text("#"));
self.slot_comments(&a.after_hash, &mut docs);
docs.push(self.expr(delay));
docs.push(text(" "));
match a.after_delay.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(&a.after_delay, &mut docs),
}
}
let items: Vec<ListItem> = a
.assigns
@@ -464,26 +526,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 +535,33 @@ impl<'a> Fmt<'a> {
}
}
/// A generate block's `begin … end` and everything between, from the
/// keyword on — the separator in front of it is the caller's, because a
/// block hanging off an `if (…)` header needs one and a block standing on
/// its own as an item ([`ItemKind::GenBlock`]) does not.
fn begin_block(&self, docs: &mut Vec<Doc>, b: &GenBlock, depth: usize) {
docs.push(text("begin"));
if let Some(l) = &b.label {
self.slot_comments(&b.before_colon, docs);
docs.push(text(if b.before_colon.is_empty() { " :" } else { ":" }));
if b.after_colon.is_empty() {
docs.push(text(" "));
} else {
self.inline_comments_spaced(&b.after_colon, docs);
}
docs.push(text(named(l)));
}
let mut body = Vec::new();
if !b.items.is_empty() {
body.push(Doc::HardLine);
body.extend(self.item_seq(&b.items, depth + 1));
}
body.extend(self.dangling(&b.dangling));
docs.push(indent(body));
docs.push(Doc::HardLine);
docs.push(self.closing_labeled("end", &b.end_label, &b.end_label_comments));
}
fn gen_for(&self, g: &GenFor, depth: usize) -> Doc {
let mut header = Vec::new();
self.for_open(&g.comments, &mut header);
+40 -2
View File
@@ -38,6 +38,27 @@ pub(super) struct ListItem {
}
impl ListItem {
/// The entry an error element of a header list prints as: the text a
/// tolerant parse skipped, verbatim, carrying no comments of its own —
/// they are bytes of that text.
///
/// **Unreachable from `format_source`**, exactly as `ItemKind::Error` is:
/// the formatter parses strictly, and only [`vlog_parser::parse_tolerant`]
/// builds a [`ListElem::Error`]. Printing the bytes rather than nothing
/// means that if some future entry point ever did hand one over,
/// `verify.rs`'s token-equivalence check would see the tokens instead of
/// silently losing them.
pub(super) fn from_raw(doc: Doc) -> Self {
ListItem {
leading: Vec::new(),
doc,
before_sep: Vec::new(),
trailing: None,
comma: None,
directive: false,
}
}
pub(super) fn from_meta(meta: &Meta, doc: Doc) -> Self {
ListItem {
leading: meta.leading.clone(),
@@ -58,6 +79,20 @@ impl ListItem {
}
impl<'a> Fmt<'a> {
/// One entry of a **header** list: the element as `entry` prints it, or —
/// for an error element — its bytes; see [`ListItem::from_raw`] for why
/// the second case cannot be reached from `format_source`.
pub(super) fn list_elem<T>(
&self,
elem: &ListElem<T>,
entry: impl FnOnce(&T) -> ListItem,
) -> ListItem {
match elem {
ListElem::Ok(v) => entry(v),
ListElem::Error(raw) => ListItem::from_raw(self.raw_text(raw)),
}
}
/// A bracketed expression list (concatenation, call arguments, `inside`
/// set). Comments on an element ride along and break the list open.
pub(super) fn expr_list(&self, open: &str, items: &[ExprItem], close: &str) -> Doc {
@@ -316,15 +351,18 @@ impl<'a> Fmt<'a> {
/// with a comment or an attribute of their own — both print on their own
/// line — and those a compiler directive was written in front of.
///
/// A `None` meta is an error element, which has none; it always starts a
/// group, being raw bytes of a width no other row shares.
///
/// A blank line is deliberately *not* a boundary here: `delimited` drops
/// blank lines between list elements, so a boundary drawn at one would
/// vanish from the output and the next pass would group differently.
pub(super) fn list_breaks<'m>(
metas: impl Iterator<Item = &'m Meta>,
metas: impl Iterator<Item = Option<&'m Meta>>,
directives: &[ListDirective],
) -> Vec<bool> {
let mut breaks: Vec<bool> =
metas.map(|m| !m.leading.is_empty() || !m.attrs.is_empty()).collect();
metas.map(|m| m.is_none_or(|m| !m.leading.is_empty() || !m.attrs.is_empty())).collect();
for d in directives {
if let Some(b) = breaks.get_mut(d.before) {
*b = true;
+10 -1
View File
@@ -22,6 +22,7 @@ mod item;
mod list;
mod module;
mod phrase;
mod randsequence;
mod routine;
mod stmt;
mod sva;
@@ -38,11 +39,19 @@ use vlog_parser::ast::*;
pub struct Config {
pub max_width: usize,
pub indent_width: usize,
/// Indent the macro statements written between `` `uvm_object_utils_begin ``
/// / `` `uvm_component_utils_begin `` and their `_end`, which are plain
/// macro items with no block for the formatter to see.
///
/// **Off by default**: it changes the output of files that already format
/// cleanly, so a project opts in through `[format] uvm-utils-indent` and
/// nobody else moves a byte.
pub uvm_utils_indent: bool,
}
impl Default for Config {
fn default() -> Self {
Config { max_width: 100, indent_width: 2 }
Config { max_width: 100, indent_width: 2, uvm_utils_indent: false }
}
}
+102 -31
View File
@@ -67,7 +67,11 @@ impl<'a> Fmt<'a> {
if let Some(params) = &m.param_ports {
let items: Vec<ListItem> = params
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma))
.map(|p| {
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma)
})
})
.collect();
let items = self.list_entries(items, &m.param_directives);
let broken = !m.param_directives.is_empty();
@@ -94,15 +98,19 @@ impl<'a> Fmt<'a> {
.iter()
.zip(&aligns)
.map(|(p, a)| {
ListItem::from_meta(&p.meta, self.ansi_port(p, a.as_ref()))
.with_comma(p.comma)
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.ansi_port(p, a.as_ref()))
.with_comma(p.comma)
})
})
.collect()
}
PortList::NonAnsi(ports) => ports
.iter()
.map(|p| {
ListItem::from_meta(&p.meta, name_doc(&p.name)).with_comma(p.comma)
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, name_doc(&p.name)).with_comma(p.comma)
})
})
.collect(),
_ => Vec::new(),
@@ -223,13 +231,15 @@ impl<'a> Fmt<'a> {
/// The alignment plan for a module header's ANSI port list.
fn ansi_port_aligns(
&self,
ports: &[AnsiPort],
ports: &[ListElem<AnsiPort>],
directives: &[ListDirective],
depth: usize,
) -> Vec<Option<Align>> {
let rows: Vec<Option<Row>> = ports
.iter()
.map(|p| {
// An error element has no cells to align, so it has no row.
let p = p.ok()?;
Self::row_of(
&self.ansi_port_cells(p),
vec![p.name_span.start],
@@ -237,7 +247,7 @@ impl<'a> Fmt<'a> {
)
})
.collect();
let breaks = Self::list_breaks(ports.iter().map(|p| &p.meta), directives);
let breaks = Self::list_breaks(ports.iter().map(|p| p.ok().map(|p| &p.meta)), directives);
self.align_groups(&rows, &breaks, ANSI_PORT_COLS, depth)
}
@@ -306,25 +316,35 @@ impl<'a> Fmt<'a> {
/// item per line — the body is a declaration list, not an expression, so
/// there is nothing here worth collapsing onto the header's line.
pub(super) fn clocking(&self, c: &ClockingDecl) -> Doc {
let mut head = String::from(if c.is_default { "default clocking" } else { "clocking" });
if let Some(n) = &c.name {
head.push(' ');
head.push_str(&named(&n.text));
let mut docs = vec![text(if c.is_default { "default clocking" } else { "clocking" })];
match &c.name {
Some(n) => {
self.word_then("", &c.after_kw, &mut docs);
docs.push(name_doc(&n.text));
// The gap in front of the `@` is the event's; with no name the
// keyword's own gap is that same gap and was printed already.
match c.before_event.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(&c.before_event, &mut docs),
}
}
None => self.word_then("", &c.after_kw, &mut docs),
}
let mut docs = vec![text(head)];
// `default clocking cb;` selects an existing block: no event, no body.
let Some(event) = &c.event else {
docs.push(text(";"));
// Nothing follows the name, so the separator just written is not
// wanted: the `;` goes straight after it.
docs.pop();
docs.push(self.semi(&c.before_semi));
return concat(docs);
};
docs.push(text(" "));
docs.push(self.sens_list(event));
docs.push(text(";"));
docs.push(self.semi(&c.before_semi));
let mut body = Vec::new();
for item in &c.items {
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
body.extend(self.leading_comments(&item.meta));
body.push(concat(vec![self.clocking_item(&item.kind), text(";")]));
body.push(concat(vec![self.clocking_item(&item.kind), self.semi(&item.before_semi)]));
body.extend(self.trailing(&item.meta));
}
body.extend(self.dangling(&c.dangling));
@@ -343,25 +363,24 @@ impl<'a> Fmt<'a> {
fn clocking_item(&self, kind: &ClockingItemKind) -> Doc {
match kind {
ClockingItemKind::Default { input, output } => {
let mut s = String::from("default");
if let Some(skew) = input {
s.push_str(" input ");
s.push_str(skew);
}
if let Some(skew) = output {
s.push_str(" output ");
s.push_str(skew);
}
text(s)
let mut docs = vec![text("default")];
self.clocking_default(input.as_ref(), "input", &mut docs);
self.clocking_default(output.as_ref(), "output", &mut docs);
concat(docs)
}
ClockingItemKind::Signals { dir, skew, signals } => {
let mut head = dir.clone();
ClockingItemKind::Signals { dir, after_dir, skew, after_skew, signals } => {
let mut docs = vec![text(dir.clone())];
match after_dir.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(after_dir, &mut docs),
}
if let Some(skew) = skew {
head.push(' ');
head.push_str(skew);
docs.push(self.clocking_skew(skew));
match after_skew.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(after_skew, &mut docs),
}
}
head.push(' ');
let mut docs = vec![text(head)];
for (i, sig) in signals.iter().enumerate() {
if i > 0 {
docs.push(text(", "));
@@ -376,4 +395,56 @@ impl<'a> Fmt<'a> {
}
}
}
/// One half of a `default input #1step output #0;` item, or nothing at all
/// when that half was not written. The gap in front of the direction
/// keyword is the half's own, so this writes its own separator.
fn clocking_default(&self, half: Option<&ClockingDefault>, dir: &str, docs: &mut Vec<Doc>) {
let Some(half) = half else { return };
match half.before_dir.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(&half.before_dir, docs),
}
self.word_then(dir, &half.after_dir, docs);
docs.push(self.clocking_skew(&half.skew));
}
/// A clocking skew: an edge identifier and, when the source wrote one, the
/// delay behind it — IEEE 1800 §14.3's `edge_identifier [delay_control]`.
fn clocking_skew(&self, skew: &ClockingSkew) -> Doc {
match skew {
ClockingSkew::Edge { word, after_edge, delay } => {
let mut docs = vec![text(word.clone())];
if let Some(delay) = delay {
match after_edge.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(after_edge, &mut docs),
}
docs.push(self.clocking_delay(delay));
}
concat(docs)
}
ClockingSkew::Delay(delay) => self.clocking_delay(delay),
}
}
/// The `# …` half of a skew: the one-token spellings verbatim, the
/// parenthesized `#( … )` through the expression printer so its comment
/// slots print.
fn clocking_delay(&self, delay: &ClockingDelay) -> Doc {
match delay {
ClockingDelay::Word { after_hash, word } => {
let mut docs = vec![text("#")];
self.slot_comments(after_hash, &mut docs);
docs.push(text(word.clone()));
concat(docs)
}
ClockingDelay::Paren { after_hash, expr } => {
let mut docs = vec![text("#")];
self.slot_comments(after_hash, &mut docs);
docs.push(self.expr(expr));
concat(docs)
}
}
}
}
@@ -0,0 +1,225 @@
//! `randsequence` — laying out the production grammar of IEEE 1800 §18.17.
//!
//! One production per line, indented inside the `randsequence`/`endsequence`
//! pair; a production's alternatives print after the `:` and, when the line
//! does not fit, one per line with each `|` under that `:` — the shape the
//! LRM's own examples are written in.
use crate::doc::*;
use vlog_parser::ast::*;
use vlog_parser::token::Comment;
use super::{name_doc, Fmt};
impl<'a> Fmt<'a> {
/// `randsequence (main) … endsequence`.
pub(super) fn rand_sequence(&self, r: &RandSequence) -> Doc {
let mut docs = Vec::new();
self.word_then("randsequence", &r.after_kw, &mut docs);
docs.push(text("("));
self.slot_comments(&r.after_open, &mut docs);
if let Some(n) = &r.start {
docs.push(name_doc(&n.text));
}
self.slot_comments(&r.before_close, &mut docs);
docs.push(text(")"));
let mut body = Vec::new();
for p in &r.productions {
body.push(if p.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
body.extend(self.leading_comments(&p.meta));
body.push(self.production(p));
body.extend(self.trailing(&p.meta));
}
body.extend(self.dangling(&r.dangling));
docs.push(indent(body));
docs.push(Doc::HardLine);
docs.push(text("endsequence"));
concat(docs)
}
/// One production: its head, then the alternatives after the `:`.
///
/// The alternatives are one group: they stay on the head's line while they
/// fit, and otherwise break one per line with the `|` starting each new
/// one, aligned under the head's indent.
fn production(&self, p: &Production) -> Doc {
let mut head = Vec::new();
if let Some(t) = self.data_type(p.ret_type.as_ref().unwrap_or(&DataType::default())) {
head.push(t);
head.push(text(" "));
}
head.push(name_doc(&p.name));
if p.has_parens {
head.push(self.tf_args(&p.args, &[]));
}
self.slot_comments(&p.before_colon, &mut head);
head.push(text(if p.before_colon.is_empty() { " :" } else { ":" }));
// One alternative rides on the head's line: it is the common shape,
// and a code block inside it cuddles onto the `:` the way a `begin`
// cuddles onto an `if`. Several break one per line, each `|` starting
// its own, when they do not all fit.
if let [only] = p.alternatives.as_slice() {
self.after_bar(&only.after_bar, &mut head);
head.push(self.alternative(only));
return concat(vec![concat(head), self.semi(&p.before_semi)]);
}
let mut alts = Vec::new();
for (i, alt) in p.alternatives.iter().enumerate() {
// The comments written in front of the `|` print at the end of
// the alternative before it, which is where the source put them;
// a line comment among them forces the break the `|` needs.
let broke = i > 0 && self.inline_comments(&alt.before_bar, &mut alts);
if i > 0 {
alts.push(if broke { Doc::HardLine } else { Doc::Line });
alts.push(text("|"));
self.after_bar(&alt.after_bar, &mut alts);
} else if alt.after_bar.is_empty() {
alts.push(Doc::Line);
} else {
// A comment here is the separator; the break opportunity it
// replaces is not wanted on the first alternative, which has
// no `|` of its own to start a line with.
self.inline_comments_spaced(&alt.after_bar, &mut alts);
}
alts.push(self.alternative(alt));
}
head.push(indent(alts));
concat(vec![group(head), self.semi(&p.before_semi)])
}
/// The separator between the `:`/`|` an alternative follows and its first
/// item: the comments written there, or a plain space.
fn after_bar(&self, comments: &[Comment], docs: &mut Vec<Doc>) {
match comments.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(comments, docs),
}
}
/// One `|`-separated right-hand side, with its `:= weight` when it has
/// one. The separator in front of it is the caller's, since only the
/// caller knows whether a `|` or a line break stands there.
fn alternative(&self, a: &Alternative) -> Doc {
let mut docs = Vec::new();
for (i, item) in a.items.iter().enumerate() {
if i > 0 {
docs.push(text(" "));
}
docs.push(self.prod_item(item));
}
if let Some(w) = &a.weight {
self.slot_comments(&a.before_weight, &mut docs);
docs.push(text(if a.before_weight.is_empty() { " :=" } else { ":=" }));
self.word_then("", &w.after_op, &mut docs);
docs.push(self.expr(&w.expr));
if let Some(block) = &w.block {
docs.push(text(" "));
docs.push(self.code_block(block));
}
}
concat(docs)
}
/// One item of an alternative — a reference, a code block, or one of the
/// four control shapes.
fn prod_item(&self, item: &ProdItem) -> Doc {
match item {
ProdItem::Ref(r) => self.prod_ref(r),
ProdItem::Block(b) => self.code_block(b),
ProdItem::If { after_kw, cond, then, before_else, after_else, els } => {
let mut docs = vec![text("if")];
self.word_then("", after_kw, &mut docs);
docs.push(self.parens(cond));
docs.push(text(" "));
docs.push(self.prod_item(then));
if let Some(e) = els {
self.word_then("", before_else, &mut docs);
docs.push(text("else"));
self.word_then("", after_else, &mut docs);
docs.push(self.prod_item(e));
}
concat(docs)
}
ProdItem::Repeat { after_kw, count, body } => {
let mut docs = vec![text("repeat")];
self.word_then("", after_kw, &mut docs);
docs.push(self.parens(count));
docs.push(text(" "));
docs.push(self.prod_item(body));
concat(docs)
}
ProdItem::Case { after_kw, expr, items, dangling } => {
let mut docs = vec![text("case")];
self.word_then("", after_kw, &mut docs);
docs.push(self.parens(expr));
let mut body = Vec::new();
for arm in items {
body.push(if arm.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
body.extend(self.leading_comments(&arm.meta));
body.push(self.prod_case_item(arm));
body.extend(self.trailing(&arm.meta));
}
body.extend(self.dangling(dangling));
docs.push(indent(body));
docs.push(Doc::HardLine);
docs.push(text("endcase"));
concat(docs)
}
ProdItem::RandJoin { after_rand, weight, items } => {
let mut docs = vec![text("rand")];
self.word_then("", after_rand, &mut docs);
docs.push(text("join"));
if let Some(w) = weight {
docs.push(text(" "));
docs.push(self.parens(w));
}
for item in items {
docs.push(text(" "));
docs.push(self.prod_item(item));
}
concat(docs)
}
}
}
/// One arm of an `rs_case`: `labels : item;` or `default : item;`.
///
/// The labels and their `:` are printed by the same helper a `case`
/// statement's arm uses — including the `default` whose `:` IEEE 1800
/// leaves optional — because they are the same tokens with the same
/// comment slots; only the body is a production item rather than a
/// statement.
fn prod_case_item(&self, arm: &ProdCaseItem) -> Doc {
let mut docs = vec![self.case_labels(&arm.labels, &arm.before_colon, arm.span)];
self.word_then("", &arm.after_colon, &mut docs);
docs.push(self.prod_item(&arm.item));
docs.push(self.semi(&arm.before_semi));
concat(docs)
}
/// `name` or `name(a, b)`.
fn prod_ref(&self, r: &ProdRef) -> Doc {
let mut docs = vec![name_doc(&r.name)];
if r.has_parens {
self.slot_comments(&r.before_args, &mut docs);
docs.push(self.expr_list("(", &r.args, ")"));
}
concat(docs)
}
/// An `rs_code_block`: `{ statements }`, laid out as a `begin`/`end` body
/// is — one statement per line, indented, the braces on their own lines
/// when the block holds anything at all.
fn code_block(&self, b: &CodeBlock) -> Doc {
if b.stmts.is_empty() && b.dangling.is_empty() {
return text("{}");
}
let mut body = Vec::new();
if !b.stmts.is_empty() {
body.push(Doc::HardLine);
body.extend(self.stmt_seq(&b.stmts));
}
body.extend(self.dangling(&b.dangling));
concat(vec![text("{"), indent(body), Doc::HardLine, text("}")])
}
}
+21 -8
View File
@@ -27,7 +27,7 @@ pub(super) struct TfHeader<'h> {
name: &'h str,
has_parens: bool,
before_args: &'h [Comment],
args: &'h [TfArg],
args: &'h [ListElem<TfArg>],
args_dangling: &'h [Comment],
}
@@ -119,9 +119,11 @@ impl<'a> Fmt<'a> {
}
}
pub(super) fn tf_args(&self, args: &[TfArg], dangling: &[Comment]) -> Doc {
let items: Vec<ListItem> =
args.iter().map(|a| ListItem::from_meta(&a.meta, self.tf_arg(a))).collect();
pub(super) fn tf_args(&self, args: &[ListElem<TfArg>], dangling: &[Comment]) -> Doc {
let items: Vec<ListItem> = args
.iter()
.map(|a| self.list_elem(a, |a| ListItem::from_meta(&a.meta, self.tf_arg(a))))
.collect();
self.delimited_dangling("(", items, dangling, ")", false)
}
@@ -243,13 +245,24 @@ impl<'a> Fmt<'a> {
/// `let max(a, b) = (a > b) ? a : b;` (IEEE 1800 §11.12) — a name, an
/// optional port list laid out like a function's, and one expression.
pub(super) fn let_decl(&self, l: &LetDecl) -> Doc {
let mut docs = vec![text(format!("let {}", named(&l.name)))];
let mut docs = vec![text("let")];
self.word_then("", &l.after_kw, &mut docs);
docs.push(name_doc(&l.name));
if l.has_parens {
docs.push(self.tf_args(&l.ports, &[]));
}
docs.push(text(" ="));
docs.push(self.assign_rhs(self.expr(&l.value)));
concat(vec![group(docs), text(";")])
// The `=` and its two sides are laid out the way a declarator's
// initializer is: a comment on either side stays on that side of the
// sign, and only a clean `=` keeps the breakable right-hand side.
self.slot_comments(&l.eq_comments.before, &mut docs);
docs.push(text(if l.eq_comments.before.is_empty() { " =" } else { "=" }));
if l.eq_comments.after.is_empty() {
docs.push(self.assign_rhs(self.expr(&l.value)));
} else {
self.inline_comments_spaced(&l.eq_comments.after, &mut docs);
docs.push(self.expr(&l.value));
}
concat(vec![group(docs), self.semi(&l.before_semi)])
}
/// `export "DPI-C" function f;` / `export pkg::*;` — one line either way;
+18 -3
View File
@@ -460,12 +460,27 @@ impl<'a> Fmt<'a> {
None => concat(vec![text("wait "), self.parens(cond), self.semi(before_semi)]),
},
StmtKind::ExprStmt(e) => concat(vec![self.expr(e), self.semi(before_semi)]),
StmtKind::EventTrigger(e) => {
concat(vec![text("-> "), self.expr(e), self.semi(before_semi)])
StmtKind::EventTrigger(t) => {
let mut docs = Vec::new();
self.word_then(&t.arrow, &t.after_arrow, &mut docs);
if let Some(tc) = &t.timing {
docs.push(self.timing_control(tc));
if t.before_event.is_empty() {
docs.push(text(" "));
} else {
self.inline_comments_spaced(&t.before_event, &mut docs);
}
}
docs.push(self.expr(&t.expr));
docs.push(self.semi(before_semi));
concat(docs)
}
StmtKind::VarDecl(d) => concat(vec![self.data_decl(d), self.semi(before_semi)]),
// The item form prints its own `;`.
StmtKind::Typedef(t) => self.typedef(t),
StmtKind::Let(l) => self.let_decl(l),
// `randsequence` closes itself with `endsequence`; no `;`.
StmtKind::RandSequence(r) => self.rand_sequence(r),
StmtKind::ParamDecl(d) => {
concat(vec![self.param_decl(d, None), self.semi(before_semi)])
}
@@ -482,7 +497,7 @@ impl<'a> Fmt<'a> {
},
StmtKind::Break => concat(vec![text("break"), self.semi(before_semi)]),
StmtKind::Continue => concat(vec![text("continue"), self.semi(before_semi)]),
StmtKind::Disable(name) => {
StmtKind::Disable { name, .. } => {
concat(vec![text(format!("disable {}", named(name))), self.semi(before_semi)])
}
StmtKind::WaitFork => concat(vec![text("wait fork"), self.semi(before_semi)]),
@@ -0,0 +1,270 @@
# TODO §54.1 — the six small language shapes coverage gap L6 left open.
# None of them occurs in the corpus or in opentitan, so these hand-written
# cases and the gap fuzzers are the whole acceptance.
# docs/features/coverage-gaps-l/README.md
#
# 1. `->>`, the non-blocking event trigger (IEEE 1800 §15.5.2), with and
# without a delay or event control of its own. `->` is untouched.
module m;
event e;
initial begin
-> e;
->> e;
->> #5 e;
->> @(posedge clk) e;
->> @(a or b) e;
->> #(1:2:3) e;
end
endmodule
----
module m;
event e;
initial begin
-> e;
->> e;
->> #5 e;
->> @(posedge clk) e;
->> @(a or b) e;
->> #(1:2:3) e;
end
endmodule
====
# `->>` with a comment in each of its two gaps: after the arrow, and
# between the timing control and the event.
module m;
initial begin
->> /*a*/ #5 /*b*/ e;
->> /*c*/ e;
end
endmodule
----
module m;
initial begin
->> /*a*/ #5 /*b*/ e;
->> /*c*/ e;
end
endmodule
====
# 2. A stream expression's `with [range]` (IEEE 1800 §11.4.14) — the third
# postfix spelling of `with`, told from the other two by its `[`.
module m;
initial begin
a = {<<{b with [0:3]}};
c = {>>{d with [i+:4]}};
f = {<<{g with [i-:4]}};
h = {<<{j with [i]}};
k = {<<byte{l with [0 : 3]}};
end
endmodule
----
module m;
initial begin
a = {<<{b with [0:3]}};
c = {>>{d with [i+:4]}};
f = {<<{g with [i-:4]}};
h = {<<{j with [i]}};
k = {<<byte{l with [0:3]}};
end
endmodule
====
# The stream range's five comment slots: either side of the `with`, just
# inside the `[`, either side of the `:`, and before the `]`.
module m;
initial a = {<<{b /*a*/ with /*b*/ [ /*c*/ 0 /*d*/ : /*e*/ 3 /*f*/ ]}};
endmodule
----
module m;
initial a = {<<{b /*a*/ with /*b*/ [ /*c*/ 0 /*d*/ : /*e*/ 3 /*f*/ ]}};
endmodule
====
# The other two `with` spellings still parse as what they always were: a
# `(` is an array method's iterator argument, a `{` a constraint block.
module m;
initial begin
x = q.find(v) with (v > 3);
obj.randomize() with {a < 5;};
end
endmodule
----
module m;
initial begin
x = q.find(v) with (v > 3);
obj.randomize() with {a < 5;};
end
endmodule
====
# 3. The cast bases IEEE 1800 §6.24.1 allows besides a name and a system
# call: a parenthesised width, a sized literal, and a type with packed
# dimensions on it.
module m;
initial begin
x = (W+1)'(y);
z = 4'(y);
q = logic [3:0]'(y);
r = bit signed [7:0]'(y);
s = $clog2(N)'(y);
end
endmodule
----
module m;
initial begin
x = (W + 1)'(y);
z = 4'(y);
q = logic [3:0]'(y);
r = bit signed [7:0]'(y);
s = $clog2(N)'(y);
end
endmodule
====
# 4. Drive strength on a net declaration (IEEE 1800 §6.6), the position
# `ContAssign` has always read one in.
module m;
wire (strong0, weak1) w = a;
wire (supply0, supply1) [7:0] v;
wire (pull1, highz0) #5 d = e;
tri (weak1, weak0) t;
endmodule
----
module m;
wire (strong0, weak1) w = a;
wire (supply0, supply1) [7:0] v;
wire (pull1, highz0) #5 d = e;
tri (weak1, weak0) t;
endmodule
====
# The strength's five comment slots, on a net declaration and on the
# continuous assignment and the gate that already wrote one.
module m;
wire /*a*/ ( /*b*/ strong0 /*c*/ , /*d*/ weak1 /*e*/ ) w = a;
assign /*f*/ (weak0, pull1) x = y;
pullup /*g*/ ( /*h*/ weak1 /*i*/ ) p1 (n1);
endmodule
----
module m;
wire /*a*/ ( /*b*/ strong0 /*c*/ , /*d*/ weak1 /*e*/ ) w = a;
assign /*f*/ (weak0, pull1) x = y;
pullup /*g*/ ( /*h*/ weak1 /*i*/ ) p1 (n1);
endmodule
====
# A `(` after a net keyword that is not a strength is still not one: an
# implicitly-typed net whose value is parenthesised keeps its old parse.
module m;
wire w = (a & b);
assign (x) = y;
endmodule
----
module m;
wire w = (a & b);
assign (x) = y;
endmodule
====
# 5. `let` at statement position (IEEE 1800 §11.13) — the item-level
# grammar and the item-level layout, among a block's declarations.
module m;
initial begin
let sum = a + b;
let max(p, q) = (p > q) ? p : q;
x = sum + max(1, 2);
end
endmodule
----
module m;
initial begin
let sum = a + b;
let max(p, q) = (p > q) ? p : q;
x = sum + max(1, 2);
end
endmodule
====
# 6. The `#(min:typ:max)` clocking skew (IEEE 1800 §14.3), on a `default`
# item and on a direction group, beside the one-token spellings.
module m;
clocking cb @(posedge clk);
default input #(1:2:3) output #(2:3:4);
input #(1:2:3) sig;
output #(5) other;
input #1step a, b;
output negedge c;
endclocking
endmodule
----
module m;
clocking cb @(posedge clk);
default input #(1:2:3) output #(2:3:4);
input #(1:2:3) sig;
output #(5) other;
input #1step a, b;
output negedge c;
endclocking
endmodule
====
# The parenthesised skew's comment slots are the delay grammar's own:
# after the `#`, inside the parens and around each `:`.
module m;
clocking cb @(posedge clk);
default input # /*a*/ (1 /*c*/ : /*d*/ 2 /*e*/ : /*f*/ 3 /*g*/) output #(1:2:3);
endclocking
endmodule
----
module m;
clocking cb @(posedge clk);
default input # /*a*/ (1 /*c*/ : /*d*/ 2 /*e*/ : /*f*/ 3 /*g*/) output #(1:2:3);
endclocking
endmodule
====
# A comment written just inside the delay's `(` breaks the parens the way it
# does on a net delay (`wire # /*a*/ ( /*b*/ 1:2:3) a;`) — pre-existing
# layout the skew inherits by going through the same grammar.
module m;
clocking cb @(posedge clk);
default input # /*a*/ ( /*b*/ 1:2:3);
endclocking
endmodule
----
module m;
clocking cb @(posedge clk);
default input # /*a*/ (
/*b*/
1:2:3
);
endclocking
endmodule
====
# The other half of §14.3's `clocking_skew ::= edge_identifier
# [ delay_control ] | delay_control`: an edge that carries a delay of its
# own, in both spellings, on a `default` item and on a direction group.
module m;
clocking cb @(posedge clk);
default input negedge #(1:2:3) output posedge #5;
input negedge #(1:2:3) sig;
output posedge #5 other;
input posedge #1step a, b;
input edge c;
endclocking
endmodule
----
module m;
clocking cb @(posedge clk);
default input negedge #(1:2:3) output posedge #5;
input negedge #(1:2:3) sig;
output posedge #5 other;
input posedge #1step a, b;
input edge c;
endclocking
endmodule
====
# The gap between the edge and the `#` is the skew's own slot; the gap
# after a bare edge still belongs to what follows it.
module m;
clocking cb @(posedge clk);
default input negedge /*a*/ #2 output /*b*/ posedge /*c*/ #(1:2:3);
input edge /*d*/ sig;
endclocking
endmodule
----
module m;
clocking cb @(posedge clk);
default input negedge /*a*/ #2 output /*b*/ posedge /*c*/ #(1:2:3);
input edge /*d*/ sig;
endclocking
endmodule
@@ -0,0 +1,101 @@
# TODO §45.4 — the comment slots inside a delay list. `parse_delay_values`
# serves `#(1:2:3)` on nets and continuous assignments and `#(rise, fall)` on
# gates; the gaps around the `(`, the two `:` and the `,` had no owner, so a
# comment written in one moved and `verify.rs` refused the file.
#
# The `min:typ:max` colons: `MinTypMaxComments`, four slots, one grammar
# shared with the parenthesized `(a:b:c)` expression.
module m;
wire #(1 /* b */ : /* c */ 2 /* d */ : /* e */ 3) w;
endmodule
----
module m;
wire #(1 /* b */ : /* c */ 2 /* d */ : /* e */ 3) w;
endmodule
====
# The parentheses of a one-value delay are its own `ExprKind::Paren`, which
# has had the two slots all along — and a comment inside a bracket pair forces
# that pair open, as it does everywhere else in the formatter.
module m;
wire #( /* a */ 1:2:3 /* f */ ) w;
endmodule
----
module m;
wire #(
/* a */
1:2:3 /* f */
) w;
endmodule
====
# A continuous assignment's delay: the gap after its `#` and the gap between
# the delay and the first left-hand side. Without the second slot the comment
# joins the first pair's leading comments, which print in front of the delay.
module m;
assign # /* g */ (1:2:3) /* h */ z = a;
endmodule
----
module m;
assign # /* g */ (1:2:3) /* h */ z = a;
endmodule
====
# A gate's multi-value list writes its own parentheses and commas, so it owns
# the comments around them: `DelayValue::{leading, trailing}`. With them the
# gate's `before_hash`, `after_hash`, the instance's `before_args` and the
# item's `before_semi`.
module m;
and /* i */ # /* j */ ( /* k */ 2 /* l */ , /* m */ 3 /* n */ ) g1 /* o */ (y, a, b) /* p */ ;
endmodule
----
module m;
and /* i */ # /* j */ ( /* k */ 2 /* l */ , /* m */ 3 /* n */ ) g1 /* o */ (y, a, b) /* p */ ;
endmodule
====
# A line comment runs to end of line, so what follows it starts a new one —
# the same rule every other slot in the formatter obeys.
module m;
wire #(1 // why
:2:3) w;
endmodule
----
module m;
wire #(
1 // why
:2:3
) w;
endmodule
====
# Nothing written in any of the slots costs a byte: the comment-free spellings
# are laid out exactly as they were before the slots existed.
module m;
wire #(1:2:3) a;
assign #(1:2:3) z = a;
and #(1, 2, 3) g1 (o, a, b);
not #(1:2:3, 4:5:6) n0 (o, a);
buf #(5) b1 (o, a);
buf #5 b2 (o, a);
buf b3 (o, a);
nand (weak0, weak1) #2 n1 (o, a, b);
and #(2, 3) g0 (y, a), g2 (z, b);
endmodule
----
module m;
wire #(1:2:3) a;
assign #(1:2:3) z = a;
and #(1, 2, 3) g1 (o, a, b);
not #(1:2:3, 4:5:6) n0 (o, a);
buf #(5) b1 (o, a);
buf #5 b2 (o, a);
buf b3 (o, a);
nand (weak0, weak1) #2 n1 (o, a, b);
and #(2, 3) g0 (y, a), g2 (z, b);
endmodule
====
# A comment between two gate instances, and one written before the `,` that
# separates them: the element's own `leading` and `before_sep`.
module m;
and #(2, 3) g0 (y, a) /* before */ , /* after */ g1 (z, b);
endmodule
----
module m;
and #(2, 3) g0 (y, a) /* before */, /* after */ g1 (z, b);
endmodule
@@ -224,3 +224,42 @@ module tb;
sub #() u1 (.a(x));
sub #(.W(8)) u2 (.a(x));
endmodule
====
# TODO §45.3 — an inline aggregate as a parameter-override argument. It is a
# type where a type is legal (IEEE 1800 §6.19, §7.2), the override a
# `parameter type` defaulting to one takes, and it prints through the existing
# type printer: a struct or union body opens, an enum body stays inline.
module m;
sub #(.T(struct packed { logic a; })) u0 ();
sub #(.T(union packed { logic [7:0] a; })) u1 ();
sub #(.T(enum logic [1:0] {A, B})) u2 ();
sub #(.T(struct packed { /* why */ logic a; })) u3 ();
sub #(.T(logic [7:0])) u4 ();
endmodule
----
module m;
sub #(
.T(
struct packed {
logic a;
}
)
) u0 ();
sub #(
.T(
union packed {
logic [7:0] a;
}
)
) u1 ();
sub #(.T(enum logic [1:0] {A, B})) u2 ();
sub #(
.T(
struct packed {
/* why */
logic a;
}
)
) u3 ();
sub #(.T(logic [7:0])) u4 ();
endmodule
@@ -0,0 +1,121 @@
# TODO §38.2 — a net delay is printed on the side of the data type it was
# written on. IEEE 1800 §6.7 puts `delay3` after the type; the rest of the
# corpus puts it before. Neither spelling is normalised into the other.
# docs/features/parser-skips/README.md
module m;
wire #5 before_the_type;
wire [31:0] #0.1 after_the_type = y;
endmodule
----
module m;
wire #5 before_the_type;
wire [31:0] #0.1 after_the_type = y;
endmodule
====
# after a packed dimension, after a plain `logic`-typed net, and after a
# signing keyword — with the min:typ:max spelling of the delay itself
module m;
wire [7:0] #1 a;
wire logic #2 b;
wire signed [7:0] #(1:2:3) c;
wire #(1:2:3) signed [7:0] d;
endmodule
----
module m;
wire [7:0] #1 a;
wire logic #2 b;
wire signed [7:0] #(1:2:3) c;
wire #(1:2:3) signed [7:0] d;
endmodule
====
# the real lines: hw/vendor/pulp_riscv_dbg/tb/unused/SimDTM.sv:38-41
# (opentitan, read-only there), the §11 skip this item closes
module SimDTM (
input clk,
output [31:0] exit
);
bit r_reset;
wire #0.1 __debug_req_ready = debug_req_ready;
wire #0.1 __debug_resp_valid = debug_resp_valid;
wire [31:0] #0.1 __debug_resp_bits_resp = {30'b0, debug_resp_bits_resp};
wire [31:0] #0.1 __debug_resp_bits_data = debug_resp_bits_data;
endmodule
----
module SimDTM (input clk, output [31:0] exit);
bit r_reset;
wire #0.1 __debug_req_ready = debug_req_ready;
wire #0.1 __debug_resp_valid = debug_resp_valid;
wire [31:0] #0.1 __debug_resp_bits_resp = {30'b0, debug_resp_bits_resp};
wire [31:0] #0.1 __debug_resp_bits_data = debug_resp_bits_data;
endmodule
====
# a comment written directly in front of the `#` is the delay's own —
# `NetDelay::before_hash`, TODO §43.2. It was the `#SKIP` §38 recorded and
# `verify.rs` refused the file for; the slot prints it back where it was
# written, on either side of the data type.
module m;
wire /* c */ #5 x;
wire [7:0] /* d */ #1 z;
wire [3:0] /* one */ /* two */ #3 w;
endmodule
----
module m;
wire /* c */ #5 x;
wire [7:0] /* d */ #1 z;
wire [3:0] /* one */ /* two */ #3 w;
endmodule
====
# the delay's other gap, between the `#` and the value: `after_hash`. Both
# slots at once on one declaration, since the fuzzer asks for both
module m;
wire # /* why */ 5 x;
wire [7:0] /* a */ # /* b */ 1 z = q;
endmodule
----
module m;
wire # /* why */ 5 x;
wire [7:0] /* a */ # /* b */ 1 z = q;
endmodule
====
# a line comment in the same slot runs to end of line, so the `#` cannot
# follow it: it starts the next one, the way the `wire #5 /* after */` case
# below breaks before its declarator
module m;
wire // why the delay
#2 y;
endmodule
----
module m;
wire // why the delay
#2 y;
endmodule
====
# the other three gaps around a delay do have slots and round-trip
module m;
(* keep *) wire [3:0] #2 k = j;
wire #5 /* after */ x;
endmodule
----
module m;
(* keep *)
wire [3:0] #2 k = j;
wire #5 /* after */
x;
endmodule
====
# a line comment after a gate instance's comma ends the line: the next
# instance continues one level in (§45's QA; the module-instantiation
# printer already did this)
module m;
and #(2, 3) g0 (y, a), // p
g1 (z, b);
endmodule
----
module m;
and #(2, 3) g0 (y, a), // p
g1 (z, b);
endmodule
@@ -0,0 +1,257 @@
# TODO §54.2 — `randsequence` (IEEE 1800 §18.17) as real nodes: a production
# list with weighted alternatives, not an opaque leaf. Zero occurrences in the
# corpus and in opentitan, so the LRM's own examples are the cases.
# docs/features/coverage-gaps-l/README.md
#
# §18.17's opening example: a start production and three plain ones.
module m;
initial begin
randsequence (main)
main : first second done;
first : add | dec;
second : pop | push;
done : {$display("done");};
add : {$display("add");};
dec : {$display("dec");};
pop : {$display("pop");};
push : {$display("push");};
endsequence
end
endmodule
----
module m;
initial begin
randsequence (main)
main : first second done;
first : add | dec;
second : pop | push;
done : {
$display("done");
};
add : {
$display("add");
};
dec : {
$display("dec");
};
pop : {
$display("pop");
};
push : {
$display("push");
};
endsequence
end
endmodule
====
# Weighted alternatives (§18.17.2): `:= weight`, with and without the code
# block that runs when the alternative is chosen. Alternatives that fit stay
# on the production's line; the case after this one is the same list too wide
# for one, broken one per line with each `|` under the `:`.
module m;
initial begin
randsequence (top)
top : a := 3 | b := 2 | c := 1;
a : add;
b : dec := 5 {$display("chosen");};
c : add;
add : {x = x + 1;};
dec : {x = x - 1;};
endsequence
end
endmodule
----
module m;
initial begin
randsequence (top)
top : a := 3 | b := 2 | c := 1;
a : add;
b : dec := 5 {
$display("chosen");
};
c : add;
add : {
x = x + 1;
};
dec : {
x = x - 1;
};
endsequence
end
endmodule
====
# The three control shapes an alternative's items may take (§18.17.3–4) and
# the interleaving `rand join` (§18.17.6).
module m;
initial begin
randsequence (main)
main : gen loop sel mix;
gen : if (cond) add else dec;
loop : repeat (3) add;
sel : case (mode) 0, 1 : add; 2 : dec; default : add; endcase;
mix : rand join add dec;
bias : rand join (0.5) add dec;
add : {x++;};
dec : {x--;};
endsequence
end
endmodule
----
module m;
initial begin
randsequence (main)
main : gen loop sel mix;
gen : if (cond) add else dec;
loop : repeat (3) add;
sel : case (mode)
0, 1: add;
2: dec;
default: add;
endcase;
mix : rand join add dec;
bias : rand join (0.5) add dec;
add : {
x++;
};
dec : {
x--;
};
endsequence
end
endmodule
====
# A production with a return type and formal arguments (§18.17.5), and a
# reference that passes arguments to one.
module m;
initial begin
randsequence (main)
main : bump(3) use_it;
void bump(int step) : {
total = total + step;
};
int use_it : {
return total;
};
endsequence
end
endmodule
----
module m;
initial begin
randsequence (main)
main : bump(3) use_it;
void bump(int step) : {
total = total + step;
};
int use_it : {
return total;
};
endsequence
end
endmodule
====
# `break` and `return` inside a production's code block are the ordinary
# statements they are, and `randsequence ()` may name no start production.
module m;
initial begin
randsequence ()
main : {
if (done) break;
return;
};
endsequence
end
endmodule
----
module m;
initial begin
randsequence ()
main : {
if (done) break;
return;
};
endsequence
end
endmodule
====
# Every gap of the grammar takes a comment and prints it back where it was
# written: around the `(main)`, around the `:`, the `|` and the `:=`, and
# inside a code block and a case arm.
module m;
initial begin
randsequence /*a*/ ( /*b*/ main /*c*/ )
// above the production
main /*d*/ : /*e*/ first /*f*/ | /*g*/ second /*h*/ := /*i*/ 3 /*j*/ ; // after it
first : {
/*k*/
x = 1; /*l*/
};
second : if /*m*/ (c) first /*n*/ else /*o*/ first;
third : case /*p*/ (x)
1 /*q*/: /*r*/ first /*s*/ ;
default first;
endcase;
fourth : rand /*t*/ join (2) first second;
// before endsequence
endsequence
end
endmodule
----
module m;
initial begin
randsequence /*a*/ ( /*b*/ main /*c*/ )
// above the production
main /*d*/ : /*e*/ first /*f*/ | /*g*/ second /*h*/ := /*i*/ 3 /*j*/ ; // after it
first : {
/*k*/
x = 1; /*l*/
};
second : if /*m*/ (c) first /*n*/ else /*o*/ first;
third : case /*p*/ (x)
1 /*q*/: /*r*/ first /*s*/ ;
default first;
endcase;
fourth : rand /*t*/ join (2) first second;
// before endsequence
endsequence
end
endmodule
====
# The same production with alternatives too wide for one line: one per line,
# each `|` starting its own, indented under the production's head.
module m;
initial begin
randsequence (top)
top : first_alternative_name := 3 | second_alternative_name := 2 | third_alternative_name := 1;
first_alternative_name : {
x = 1;
};
second_alternative_name : {
x = 2;
};
third_alternative_name : {
x = 3;
};
endsequence
end
endmodule
----
module m;
initial begin
randsequence (top)
top :
first_alternative_name := 3
| second_alternative_name := 2
| third_alternative_name := 1;
first_alternative_name : {
x = 1;
};
second_alternative_name : {
x = 2;
};
third_alternative_name : {
x = 3;
};
endsequence
end
endmodule
@@ -0,0 +1,386 @@
# TODO §38.1 — two rival, bracket-balanced unit headers written across the
# arms of one `ifdef region. The whole unit is one verbatim item, so it comes
# back byte for byte apart from the block's own re-indent.
# docs/features/parser-skips/README.md
`ifdef A
interface i ();
`else
interface i ();
`endif
wire tck;
endinterface
parameter int AFTER = 1;
----
`ifdef A
interface i ();
`else
interface i ();
`endif
wire tck;
endinterface
parameter int AFTER = 1;
====
# a module spelling with a real port list and a closing label
`ifdef SYNTHESIS
module m (input a, output b);
`else
module m (input a, output b);
`endif
wire x;
endmodule : m
----
`ifdef SYNTHESIS
module m (input a, output b);
`else
module m (input a, output b);
`endif
wire x;
endmodule : m
====
# the block's *relative* layout is what survives: the whole unit is dedented
# to the item's own indent, exactly as every other verbatim block is
`ifdef A
interface i #(parameter int P = 1) ();
`else
interface i #(parameter int P = 2) ();
`endif
wire tck;
endinterface
----
`ifdef A
interface i #(parameter int P = 1) ();
`else
interface i #(parameter int P = 2) ();
`endif
wire tck;
endinterface
====
# the real file: hw/dv/sv/jtag_agent/jtag_if.sv (opentitan), the §11
# skip this item closes. Read-only there; copied here verbatim.
// Copyright lowRISC contributors (OpenTitan project).
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
// TODO(#24580): A JTAG UVM agent should configure the JTAG frequency (and not this interface)
`ifdef GATE_LEVEL
// jtag interface with default 24MHz tck for GLS
interface jtag_if #(parameter int unsigned JtagDefaultTckPeriodPs = 41_664) ();
`else
// jtag interface with default 50MHz tck for faster DV simulations
interface jtag_if #(parameter int unsigned JtagDefaultTckPeriodPs = 20_000) ();
`endif
// interface pins
wire tck;
wire trst_n;
wire tms;
wire tdi;
wire tdo;
// Is this interface being driven (through _drive_active and the clocking blocks), or is it just
// observing some signals from the wider simulation?
//
// The flag is defined as a wire with a weak pull-up. This ensures that a testbench that doesn't
// customise is_active will see the interface be driven actively, but allows a testbench that
// *does* want to customise the signal to pull it low.
wire is_active;
assign (weak0, weak1) is_active = 1'b1;
// Should this interface generate a local tck signal? To enable that, set tck_en as well as
// is_active.
bit tck_en;
// Output-enable flags for tms, tdi, tdo (which only have an effect if is_active is true). The
// default configuration enables tms and tdi, so acts as the root of the JTAG tree plus the
// "previous device in the scan chain".
bit tms_oe = 1'b1;
bit tdi_oe = 1'b1;
bit tdo_oe = 1'b0;
logic _tck_internal, _trst_n_internal, _tms_internal, _tdi_internal, _tdo_internal;
assign tck = (is_active === 1'b1) ? _tck_internal : 'z;
assign trst_n = (is_active === 1'b1) ? _trst_n_internal : 'z;
assign tms = ((is_active === 1'b1) && tms_oe) ? _tms_internal : 'z;
assign tdi = ((is_active === 1'b1) && tdi_oe) ? _tdi_internal : 'z;
assign tdo = ((is_active === 1'b1) && tdo_oe) ? _tdo_internal : 'z;
// Use negedge to drive jtag inputs because design also use posedge clock edge to sample.
clocking host_cb @(negedge tck);
default output #1ns;
output tms = _tms_internal;
output tdi = _tdi_internal;
input tdo;
endclocking
modport host_mp(clocking host_cb, output trst_n);
clocking device_cb @(posedge tck);
input tms;
input tdi;
output tdo = _tdo_internal;
endclocking
modport device_mp(clocking device_cb, input trst_n);
clocking mon_cb @(posedge tck);
input tms;
input tdi;
input tdo;
endclocking
modport mon_mp (clocking mon_cb, input trst_n);
// Signals for local tck
int unsigned _tck_period_ps = JtagDefaultTckPeriodPs;
int unsigned _clk_hi_ps, _clk_lo_ps;
assign _clk_hi_ps = _tck_period_ps / 2;
assign _clk_lo_ps = _tck_period_ps - _clk_hi_ps;
// Sets the TCK frequency.
function automatic void set_tck_period_ps(int unsigned value);
_tck_period_ps = value;
endfunction
function automatic int unsigned get_tck_period_ps();
return _tck_period_ps;
endfunction
// Wait for one TCK cycle
//
// This waits for TCK to clear and then be asserted (so is waiting for the next posedge), but
// bounds the wait by _tck_period_ps (in case the clock has stopped).
//
// Waiting for !tck, then for tck ensures that we don't get any strange races when the clock is
// enabled: no matter what the relative phase, we will definitely wait at least a half cycle.
task automatic wait_one_tck();
fork : isolation_fork begin
fork
begin
wait(!tck);
wait(tck);
end
#(_tck_period_ps * 1ps);
join_any
disable fork;
end join
endtask
// Wait for the given number of cycles of TCK
task automatic wait_tck(int cycles);
repeat (cycles) wait_one_tck();
endtask
// Start asserting a test reset through trst_n (no effect if the interface is not active)
function automatic void assert_test_reset();
_trst_n_internal <= 1'b0;
endfunction
// Clear any test reset asserted through trst_n (no effect if the interface is not active)
function automatic void clear_test_reset();
_trst_n_internal <= 1'b1;
endfunction
// Assert a test reset through trst_n (no effect if the interface is not active)
task automatic do_trst_n(int cycles = $urandom_range(5, 20));
assert_test_reset();
wait_tck(cycles);
clear_test_reset();
endtask
// Drive _tck_internal with period _tck_period_ps whenever tck_en is high. If active is true, this
// gets used to drive the tck signal.
task automatic _drive_active();
forever begin
wait(tck_en);
fork : isolation_fork begin
fork
wait(!tck_en);
forever begin
_tck_internal = 1'b1;
#(_clk_hi_ps * 1ps);
_tck_internal = 1'b0;
#(_clk_lo_ps * 1ps);
end
join_any
disable fork;
end join
end
endtask
initial begin
_tck_internal = 1'b1;
forever begin
wait(is_active === 1'b1);
fork : isolation_fork begin
fork
wait(is_active !== 1'b1);
_drive_active();
join_any
disable fork;
end join
end
end
endinterface
----
// Copyright lowRISC contributors (OpenTitan project).
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
// TODO(#24580): A JTAG UVM agent should configure the JTAG frequency (and not this interface)
`ifdef GATE_LEVEL
// jtag interface with default 24MHz tck for GLS
interface jtag_if #(parameter int unsigned JtagDefaultTckPeriodPs = 41_664) ();
`else
// jtag interface with default 50MHz tck for faster DV simulations
interface jtag_if #(parameter int unsigned JtagDefaultTckPeriodPs = 20_000) ();
`endif
// interface pins
wire tck;
wire trst_n;
wire tms;
wire tdi;
wire tdo;
// Is this interface being driven (through _drive_active and the clocking blocks), or is it just
// observing some signals from the wider simulation?
//
// The flag is defined as a wire with a weak pull-up. This ensures that a testbench that doesn't
// customise is_active will see the interface be driven actively, but allows a testbench that
// *does* want to customise the signal to pull it low.
wire is_active;
assign (weak0, weak1) is_active = 1'b1;
// Should this interface generate a local tck signal? To enable that, set tck_en as well as
// is_active.
bit tck_en;
// Output-enable flags for tms, tdi, tdo (which only have an effect if is_active is true). The
// default configuration enables tms and tdi, so acts as the root of the JTAG tree plus the
// "previous device in the scan chain".
bit tms_oe = 1'b1;
bit tdi_oe = 1'b1;
bit tdo_oe = 1'b0;
logic _tck_internal, _trst_n_internal, _tms_internal, _tdi_internal, _tdo_internal;
assign tck = (is_active === 1'b1) ? _tck_internal : 'z;
assign trst_n = (is_active === 1'b1) ? _trst_n_internal : 'z;
assign tms = ((is_active === 1'b1) && tms_oe) ? _tms_internal : 'z;
assign tdi = ((is_active === 1'b1) && tdi_oe) ? _tdi_internal : 'z;
assign tdo = ((is_active === 1'b1) && tdo_oe) ? _tdo_internal : 'z;
// Use negedge to drive jtag inputs because design also use posedge clock edge to sample.
clocking host_cb @(negedge tck);
default output #1ns;
output tms = _tms_internal;
output tdi = _tdi_internal;
input tdo;
endclocking
modport host_mp(clocking host_cb, output trst_n);
clocking device_cb @(posedge tck);
input tms;
input tdi;
output tdo = _tdo_internal;
endclocking
modport device_mp(clocking device_cb, input trst_n);
clocking mon_cb @(posedge tck);
input tms;
input tdi;
input tdo;
endclocking
modport mon_mp (clocking mon_cb, input trst_n);
// Signals for local tck
int unsigned _tck_period_ps = JtagDefaultTckPeriodPs;
int unsigned _clk_hi_ps, _clk_lo_ps;
assign _clk_hi_ps = _tck_period_ps / 2;
assign _clk_lo_ps = _tck_period_ps - _clk_hi_ps;
// Sets the TCK frequency.
function automatic void set_tck_period_ps(int unsigned value);
_tck_period_ps = value;
endfunction
function automatic int unsigned get_tck_period_ps();
return _tck_period_ps;
endfunction
// Wait for one TCK cycle
//
// This waits for TCK to clear and then be asserted (so is waiting for the next posedge), but
// bounds the wait by _tck_period_ps (in case the clock has stopped).
//
// Waiting for !tck, then for tck ensures that we don't get any strange races when the clock is
// enabled: no matter what the relative phase, we will definitely wait at least a half cycle.
task automatic wait_one_tck();
fork : isolation_fork begin
fork
begin
wait(!tck);
wait(tck);
end
#(_tck_period_ps * 1ps);
join_any
disable fork;
end join
endtask
// Wait for the given number of cycles of TCK
task automatic wait_tck(int cycles);
repeat (cycles) wait_one_tck();
endtask
// Start asserting a test reset through trst_n (no effect if the interface is not active)
function automatic void assert_test_reset();
_trst_n_internal <= 1'b0;
endfunction
// Clear any test reset asserted through trst_n (no effect if the interface is not active)
function automatic void clear_test_reset();
_trst_n_internal <= 1'b1;
endfunction
// Assert a test reset through trst_n (no effect if the interface is not active)
task automatic do_trst_n(int cycles = $urandom_range(5, 20));
assert_test_reset();
wait_tck(cycles);
clear_test_reset();
endtask
// Drive _tck_internal with period _tck_period_ps whenever tck_en is high. If active is true, this
// gets used to drive the tck signal.
task automatic _drive_active();
forever begin
wait(tck_en);
fork : isolation_fork begin
fork
wait(!tck_en);
forever begin
_tck_internal = 1'b1;
#(_clk_hi_ps * 1ps);
_tck_internal = 1'b0;
#(_clk_lo_ps * 1ps);
end
join_any
disable fork;
end join
end
endtask
initial begin
_tck_internal = 1'b1;
forever begin
wait(is_active === 1'b1);
fork : isolation_fork begin
fork
wait(is_active !== 1'b1);
_drive_active();
join_any
disable fork;
end join
end
end
endinterface
@@ -0,0 +1,240 @@
//! The `[format]` config keys — the layout choices that are off unless a
//! project turns them on (TODO §54.3).
//!
//! Every one of them changes the output of files that already format cleanly,
//! so each test asserts both directions: the shipped default leaves the file
//! exactly as it was, and the key on produces the asked-for layout and is
//! still idempotent.
use vlog_formatter::{format_source, Config};
/// A class body written the way UVM's own examples write one.
const UVM_CLASS: &str = "\
class c extends uvm_object;
`uvm_object_utils_begin(c)
`uvm_field_int(a, UVM_DEFAULT)
`uvm_field_string(b, UVM_DEFAULT)
`uvm_object_utils_end
function new(string name = \"c\");
super.new(name);
endfunction
endclass
";
/// The same body with the field macros indented one level.
const UVM_CLASS_INDENTED: &str = "\
class c extends uvm_object;
`uvm_object_utils_begin(c)
`uvm_field_int(a, UVM_DEFAULT)
`uvm_field_string(b, UVM_DEFAULT)
`uvm_object_utils_end
function new(string name = \"c\");
super.new(name);
endfunction
endclass
";
fn on() -> Config {
Config { uvm_utils_indent: true, ..Config::default() }
}
fn format(src: &str, config: &Config) -> String {
format_source(src, config).expect("formats")
}
#[test]
fn the_shipped_default_leaves_uvm_utils_macros_where_they_stand() {
assert_eq!(format(UVM_CLASS, &Config::default()), UVM_CLASS);
// And it un-indents a file that was written indented, which is exactly
// why the key exists: without it there is no way to keep that shape.
assert_eq!(format(UVM_CLASS_INDENTED, &Config::default()), UVM_CLASS);
}
#[test]
fn uvm_utils_indent_indents_the_run_between_begin_and_end() {
assert_eq!(format(UVM_CLASS, &on()), UVM_CLASS_INDENTED);
assert_eq!(format(UVM_CLASS_INDENTED, &on()), UVM_CLASS_INDENTED);
}
#[test]
fn uvm_utils_indent_is_idempotent() {
let once = format(UVM_CLASS, &on());
assert_eq!(format(&once, &on()), once);
}
#[test]
fn the_component_spelling_opens_the_same_level() {
let src = "\
class c extends uvm_component;
`uvm_component_utils_begin(c)
`uvm_field_int(a, UVM_DEFAULT)
`uvm_component_utils_end
endclass
";
let want = "\
class c extends uvm_component;
`uvm_component_utils_begin(c)
`uvm_field_int(a, UVM_DEFAULT)
`uvm_component_utils_end
endclass
";
assert_eq!(format(src, &on()), want);
}
#[test]
fn only_those_four_macro_names_open_a_level() {
// A macro pair that merely *looks* like the idiom is not it: the rule is
// four names, not a heuristic about `_begin`/`_end`.
let src = "\
class c;
`my_utils_begin(c)
`my_field(a)
`my_utils_end
endclass
";
assert_eq!(format(src, &on()), src);
}
#[test]
fn comments_inside_the_run_are_indented_with_it_and_never_dropped() {
let src = "\
class c extends uvm_object;
`uvm_object_utils_begin(c)
// why this field matters
`uvm_field_int(a, UVM_DEFAULT) // trailing
`uvm_object_utils_end
endclass
";
let want = "\
class c extends uvm_object;
`uvm_object_utils_begin(c)
// why this field matters
`uvm_field_int(a, UVM_DEFAULT) // trailing
`uvm_object_utils_end
endclass
";
assert_eq!(format(src, &on()), want);
}
#[test]
fn a_begin_with_no_end_still_prints_everything_it_opened() {
// lucisv reproduces the file it was given, unbalanced macros included.
let src = "\
class c extends uvm_object;
`uvm_object_utils_begin(c)
`uvm_field_int(a, UVM_DEFAULT)
endclass
";
let want = "\
class c extends uvm_object;
`uvm_object_utils_begin(c)
`uvm_field_int(a, UVM_DEFAULT)
endclass
";
assert_eq!(format(src, &on()), want);
assert_eq!(format(&format(src, &on()), &on()), want);
}
/// The other half of coverage gap L10: an enum body one-lined when it is
/// short. **This already is the default** — measured 2026-09-06, over every
/// shape the gap names — so no config key was added for it. The test pins the
/// behaviour so nothing takes it away.
#[test]
fn a_short_enum_body_is_already_one_lined_by_default() {
let broken = "\
package p;
typedef enum {
A,
B,
C
} e_t;
typedef enum logic [1:0] {
X = 0,
Y,
Z
} s_e;
enum {
IDLE,
BUSY
} state;
endpackage
";
let want = "\
package p;
typedef enum {A, B, C} e_t;
typedef enum logic [1:0] {X = 0, Y, Z} s_e;
enum {IDLE, BUSY} state;
endpackage
";
assert_eq!(format(broken, &Config::default()), want);
}
/// And a body with a comment in it still breaks, which is the condition the
/// gap named: one-lining it would put a `//` in front of the `}`.
#[test]
fn an_enum_body_with_a_comment_still_breaks_one_member_per_line() {
let src = "\
package p;
typedef enum {
A, // first
B
} e_t;
endpackage
";
assert_eq!(format(src, &Config::default()), src);
}
#[test]
fn a_nested_begin_opens_a_level_of_its_own_and_its_end_closes_that_one() {
// Real UVM code never nests these macros, but the rule tracks a stack all
// the same: the first `_end` closes the `_begin` it matches, not the run.
let src = "\
class c extends uvm_object;
`uvm_object_utils_begin(c)
`uvm_field_int(a, UVM_DEFAULT)
`uvm_object_utils_begin(d)
`uvm_field_int(b, UVM_DEFAULT)
`uvm_object_utils_end
`uvm_field_int(e, UVM_DEFAULT)
`uvm_object_utils_end
`uvm_field_int(f, UVM_DEFAULT)
endclass
";
let want = "\
class c extends uvm_object;
`uvm_object_utils_begin(c)
`uvm_field_int(a, UVM_DEFAULT)
`uvm_object_utils_begin(d)
`uvm_field_int(b, UVM_DEFAULT)
`uvm_object_utils_end
`uvm_field_int(e, UVM_DEFAULT)
`uvm_object_utils_end
`uvm_field_int(f, UVM_DEFAULT)
endclass
";
assert_eq!(format(src, &on()), want);
assert_eq!(format(want, &on()), want, "idempotent");
}
#[test]
fn an_end_with_no_begin_open_changes_no_indentation() {
// Nothing to close, so nothing moves — the file comes back as written.
let src = "\
class c extends uvm_object;
`uvm_object_utils_end
`uvm_field_int(a, UVM_DEFAULT)
endclass
";
assert_eq!(format(src, &on()), src);
// And an unmatched `_end` after a closed pair closes nothing either.
let after = "\
class c extends uvm_object;
`uvm_object_utils_begin(c)
`uvm_field_int(a, UVM_DEFAULT)
`uvm_object_utils_end
`uvm_object_utils_end
`uvm_field_int(b, UVM_DEFAULT)
endclass
";
assert_eq!(format(after, &on()), after);
}
+268 -3
View File
@@ -260,6 +260,136 @@ fn reindented_string_inside_a_with_block_is_rejected() {
expect_divergence(input, output);
}
// ----------------------------------------------------------------------
// The shapes TODO §54 added — masked-corruption attack pairs
//
// `verify.rs` was not touched by this round and no normalization was
// widened (CLAUDE.md invariant 4 asks for these anyway): each pair is a
// plausible way a new printer could have lost or rewritten something, and
// each must be refused. They are `(input, corrupted output)` pairs handed
// straight to the safety net, so they hold whether or not the formatter
// would ever produce that output.
// ----------------------------------------------------------------------
#[test]
fn an_event_trigger_arrow_rewritten_as_the_other_one_is_rejected() {
// `->` and `->>` are different statements — blocking and non-blocking —
// so normalizing one into the other changes the design.
expect_divergence(
"module m;\n initial -> e;\nendmodule\n",
"module m;\n initial ->> e;\nendmodule\n",
);
expect_divergence(
"module m;\n initial ->> e;\nendmodule\n",
"module m;\n initial -> e;\nendmodule\n",
);
}
#[test]
fn a_dropped_event_trigger_timing_control_is_rejected() {
expect_divergence(
"module m;\n initial ->> #5 e;\nendmodule\n",
"module m;\n initial ->> e;\nendmodule\n",
);
}
#[test]
fn a_stream_range_turned_into_an_index_is_rejected() {
// `a with [0:3]` and `a with [0]` select different bits.
expect_divergence(
"module m;\n initial q = {<<{a with [0:3]}};\nendmodule\n",
"module m;\n initial q = {<<{a with [0]}};\nendmodule\n",
);
// And a part-select operator swapped for another one.
expect_divergence(
"module m;\n initial q = {<<{a with [i+:4]}};\nendmodule\n",
"module m;\n initial q = {<<{a with [i-:4]}};\nendmodule\n",
);
}
#[test]
fn a_dropped_or_reordered_drive_strength_is_rejected() {
expect_divergence(
"module m;\n wire (strong0, weak1) w = a;\nendmodule\n",
"module m;\n wire w = a;\nendmodule\n",
);
// The two keywords may be written in either order and mean different
// things; a printer that sorted them would be corrupting the design.
expect_divergence(
"module m;\n wire (strong0, weak1) w = a;\nendmodule\n",
"module m;\n wire (weak1, strong0) w = a;\nendmodule\n",
);
}
#[test]
fn a_clocking_skew_rewritten_into_a_bare_delay_is_rejected() {
// `#(1:2:3)` is three values; `#1` is one.
expect_divergence(
"module m;\n clocking cb @(posedge clk);\n input #(1:2:3) sig;\n endclocking\nendmodule\n",
"module m;\n clocking cb @(posedge clk);\n input #1 sig;\n endclocking\nendmodule\n",
);
// An edge and the delay behind it are one skew (§14.3): losing either
// half changes when the signal is sampled.
expect_divergence(
"module m;\n clocking cb @(posedge clk);\n input negedge #5 sig;\n endclocking\nendmodule\n",
"module m;\n clocking cb @(posedge clk);\n input negedge sig;\n endclocking\nendmodule\n",
);
expect_divergence(
"module m;\n clocking cb @(posedge clk);\n input negedge #5 sig;\n endclocking\nendmodule\n",
"module m;\n clocking cb @(posedge clk);\n input #5 sig;\n endclocking\nendmodule\n",
);
}
#[test]
fn a_dropped_randsequence_production_is_rejected() {
let input = "module m;\n initial begin\n randsequence (main)\n main : a b;\n a : {x = 1;};\n b : {x = 2;};\n endsequence\n end\nendmodule\n";
let output = "module m;\n initial begin\n randsequence (main)\n main : a b;\n a : {x = 1;};\n endsequence\n end\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_reordered_randsequence_alternative_is_rejected() {
// The order of the alternatives is what `:=` weights are relative to.
let input = "module m;\n initial begin\n randsequence (main)\n main : a := 3 | b := 1;\n endsequence\n end\nendmodule\n";
let output = "module m;\n initial begin\n randsequence (main)\n main : b := 1 | a := 3;\n endsequence\n end\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_randsequence_bar_turned_into_a_juxtaposition_is_rejected() {
// `a | b` picks one; `a b` runs both. One token apart, opposite meanings.
let input = "module m;\n initial begin\n randsequence (main)\n main : a | b;\n endsequence\n end\nendmodule\n";
let output = "module m;\n initial begin\n randsequence (main)\n main : a b;\n endsequence\n end\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_randsequence_weight_is_rejected() {
let input = "module m;\n initial begin\n randsequence (main)\n main : a := 3 | b;\n endsequence\n end\nendmodule\n";
let output = "module m;\n initial begin\n randsequence (main)\n main : a | b;\n endsequence\n end\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_let_statement_losing_its_ports_is_rejected() {
expect_divergence(
"module m;\n initial begin\n let f(a) = a + 1;\n end\nendmodule\n",
"module m;\n initial begin\n let f = a + 1;\n end\nendmodule\n",
);
}
#[test]
fn uvm_utils_indentation_is_whitespace_the_net_ignores_and_a_dropped_macro_is_not() {
// The `uvm-utils-indent` key only ever moves leading whitespace, which is
// exactly what the net is allowed to forgive...
let flat = "class c;\n `uvm_object_utils_begin(c)\n `uvm_field_int(a, UVM_DEFAULT)\n `uvm_object_utils_end\nendclass\n";
let indented = "class c;\n `uvm_object_utils_begin(c)\n `uvm_field_int(a, UVM_DEFAULT)\n `uvm_object_utils_end\nendclass\n";
verify_equivalence(flat, indented).expect("indentation alone is not a divergence");
// ...and losing one of the macros it indents is not.
let dropped = "class c;\n `uvm_object_utils_begin(c)\n `uvm_object_utils_end\nendclass\n";
expect_divergence(flat, dropped);
}
#[test]
fn truncated_output_is_rejected() {
let input = "module m;\n wire x;\nendmodule\n";
@@ -1151,7 +1281,7 @@ fn a_dropped_method_qualifier_is_rejected() {
/// Format `src` at `width`, then format that again, and return both.
fn twice(src: &str, width: usize, indent: usize) -> (String, String) {
let config = Config { max_width: width, indent_width: indent };
let config = Config { max_width: width, indent_width: indent, ..Config::default() };
let once = format_source(src, &config).expect("first pass");
let again = format_source(&once, &config).expect("second pass");
(once, again)
@@ -2350,6 +2480,22 @@ const RTL_FIXTURES: &[&str] = &[
"package p;\n typedef struct packed {\n logic [3:0] hi;\n logic [3:0] lo;\n } word_t;\n typedef enum logic [1:0] {A = 2'd0, B, C} st_e;\nendpackage\n",
"module m;\n sub #(.W(8)) u0 (.clk(clk), .d(d[3:0]), .q());\nendmodule\n",
"module m;\n assign y = cond ? a[3:0] : pkg::f(b).c;\nendmodule\n",
// A net delay on either side of the data type: the gap in front of the
// `#` is `NetDelay::before_hash` (TODO §43.2), and the fuzzer is what
// says the other gaps around it kept their owners.
"module m;\n wire #5 a;\n wire [7:0] #1 b = c;\nendmodule\n",
// A delay *list*: the `min:typ:max` spelling a net and a continuous
// assignment take, and the `(rise, fall)` spelling only a gate takes
// (TODO §45.4). The gaps around the `(`, the two `:` and the `,` had no
// owner until this round — `MinTypMaxComments`, `DelayValue`, and the
// gate's own `before_hash`/`after_hash`/`before_args`/`before_semi`.
"module m;\n wire #(1:2:3) a;\n assign #(1:2:3) z = a;\n and #(2, 3) g1 (y, a, b);\nendmodule\n",
// The six shapes of TODO §54.1. Each opened a gap the parser had no slot
// for — the arrow of `->>`, the `with [ … ]` bracket, the five of a drive
// strength, the `let` head, and the parenthesized clocking skew — and
// this is what says every one of them found an owner.
"module m;\n wire (strong0, weak1) w = a;\n initial begin\n ->> #5 e;\n q = {<<{a with [i+:4]}};\n let sum = a + b;\n end\nendmodule\n",
"module m;\n clocking cb @(posedge clk);\n default input #(1:2:3) output #2;\n input #(5) sig;\n output negedge #5 o;\n endclocking\nendmodule\n",
];
#[test]
@@ -2357,8 +2503,24 @@ fn a_comment_in_every_rtl_gap_still_formats() {
assert_no_failing_gaps("RTL", RTL_FIXTURES, EXPECTED_RTL_GAPS);
}
/// Inter-token gaps across [`RTL_FIXTURES`].
const EXPECTED_RTL_GAPS: usize = 352;
/// Inter-token gaps across [`RTL_FIXTURES`]. 374 before TODO §45.4 added the
/// delay-list fixture, whose 45 gaps took it to 419; TODO §54.1's two
/// fixtures — the six L6 shapes and a clocking block — brought the 80 that
/// take it here. Nineteen of those 80 failed when the fixtures were written,
/// none of them because of the new shapes: the `let` head, the two brace
/// pairs of a streaming concatenation and the whole clocking grammar had no
/// comment slots at all, and fail identically on a tree without this round
/// (`let /*C*/ sum = a + b;` as an item, `{ /*C*/ <<{a}}`,
/// `clocking /*C*/ cb`). All nineteen have owners now — `LetDecl`'s
/// `after_kw`/`eq_comments`/`before_semi`, `StreamComments`,
/// `ClockingDecl`'s `after_kw`/`before_event`/`before_semi`,
/// `ClockingDefault`, `ClockingItem::before_semi` and the skew's own
/// `after_hash`. The rework of §54.1 added `output negedge #5 o;` to the
/// clocking fixture — the LRM's `edge_identifier [delay_control]`, which the
/// round's first pass could not parse — for the 6 that take it to 505, none of
/// them failing: the gap between the edge and its `#` is
/// `ClockingSkew::Edge::after_edge`.
const EXPECTED_RTL_GAPS: usize = 505;
// ----------------------------------------------------------------------
// Vendor and formal collateral — `vendor-formal-grammar`
@@ -2888,3 +3050,106 @@ fn a_structured_assertion_may_be_relaid_out() {
assert!(out.contains("lbl: assert property (@(posedge clk) disable iff (rst)"), "{out}");
assert_eq!(format_source(&out, &Config::default()).expect("and is a fixed point"), out);
}
// ----------------------------------------------------------------------
// The delay list's new comment slots — `docs/features/small-items-4/README.md`
//
// `verify.rs` was not touched and no normalization was widened; these are the
// standing attack pairs CLAUDE.md invariant 4 asks for anyway, one per token
// a slot added by TODO §45.4 is defined *between*. Each moves the comment
// across exactly that token, and each must be refused.
// ----------------------------------------------------------------------
#[test]
fn a_delay_comment_moved_across_a_min_typ_max_colon_is_rejected() {
expect_divergence(
"module m;\n wire #(1 /*c*/ : 2 : 3) w;\nendmodule\n",
"module m;\n wire #(1 : /*c*/ 2 : 3) w;\nendmodule\n",
);
expect_divergence(
"module m;\n wire #(1 : 2 /*c*/ : 3) w;\nendmodule\n",
"module m;\n wire #(1 : 2 : /*c*/ 3) w;\nendmodule\n",
);
}
#[test]
fn a_delay_comment_moved_across_the_lists_brackets_is_rejected() {
// The `(` of a one-value delay, whose slots are its `ExprKind::Paren`'s.
expect_divergence(
"module m;\n wire # /*c*/ (1:2:3) w;\nendmodule\n",
"module m;\n wire #( /*c*/ 1:2:3) w;\nendmodule\n",
);
// And the `)`.
expect_divergence(
"module m;\n wire #(1:2:3 /*c*/ ) w;\nendmodule\n",
"module m;\n wire #(1:2:3) /*c*/ w;\nendmodule\n",
);
}
#[test]
fn a_gate_delay_comment_moved_across_the_hash_or_a_comma_is_rejected() {
expect_divergence(
"module m;\n and /*c*/ #(2, 3) g (y, a);\nendmodule\n",
"module m;\n and # /*c*/ (2, 3) g (y, a);\nendmodule\n",
);
expect_divergence(
"module m;\n and #(2 /*c*/, 3) g (y, a);\nendmodule\n",
"module m;\n and #(2, /*c*/ 3) g (y, a);\nendmodule\n",
);
// The gate instance's own two new slots: before its `(` and before the `;`.
expect_divergence(
"module m;\n and #(2, 3) g /*c*/ (y, a);\nendmodule\n",
"module m;\n and #(2, 3) g ( /*c*/ y, a);\nendmodule\n",
);
expect_divergence(
"module m;\n and #(2, 3) g (y, a) /*c*/ ;\nendmodule\n",
"module m;\n and #(2, 3) g (y, a); /*c*/\nendmodule\n",
);
}
#[test]
fn a_continuous_assignments_delay_comment_moved_across_it_is_rejected() {
expect_divergence(
"module m;\n assign # /*c*/ (5) y = a;\nendmodule\n",
"module m;\n assign /*c*/ #(5) y = a;\nendmodule\n",
);
expect_divergence(
"module m;\n assign #(5) /*c*/ y = a;\nendmodule\n",
"module m;\n assign /*c*/ #(5) y = a;\nendmodule\n",
);
}
#[test]
fn a_dropped_delay_list_comment_is_rejected() {
expect_divergence(
"module m;\n and #(2 /*c*/, 3) g (y, a);\nendmodule\n",
"module m;\n and #(2, 3) g (y, a);\nendmodule\n",
);
}
// ----------------------------------------------------------------------
// The inline aggregate as a parameter-override argument — TODO §45.3
//
// A construct the parser refused until this round is a construct the safety
// net had never been asked about. These say it is asked now.
// ----------------------------------------------------------------------
#[test]
fn a_dropped_member_of_an_inline_aggregate_override_is_rejected() {
expect_divergence(
"module m;\n sub #(.T(struct packed {logic a; logic b;})) u ();\nendmodule\n",
"module m;\n sub #(.T(struct packed {logic a;})) u ();\nendmodule\n",
);
expect_divergence(
"module m;\n sub #(.T(enum logic [1:0] {A, B})) u ();\nendmodule\n",
"module m;\n sub #(.T(enum logic [1:0] {A})) u ();\nendmodule\n",
);
}
#[test]
fn a_dropped_packed_keyword_in_an_override_argument_is_rejected() {
expect_divergence(
"module m;\n sub #(.T(struct packed {logic a;})) u ();\nendmodule\n",
"module m;\n sub #(.T(struct {logic a;})) u ();\nendmodule\n",
);
}
+6
View File
@@ -12,6 +12,12 @@ vlog_parser = { path = "../vlog_parser" }
# workspace crate that answers that, and it depends on `vlog_parser` alone, so
# this adds no external code — see docs/features/semantic-lints/README.md.
vlog_semantic = { path = "../vlog_semantic" }
# A waiver file's `--location` is matched exactly the way an `--exclude`
# pattern is, and that matcher is `lucisv_core::walk::is_excluded`. Depending
# on it rather than copying it is the only way the two can be *the same*
# semantics; `lucisv_core` itself has no dependencies at all, so this adds no
# external code and closes no loop — see docs/features/waiver-files/README.md.
lucisv_core = { path = "../lucisv_core" }
[dev-dependencies]
# Tests only: the .lint case harness asserts that a lint fix never produces
@@ -0,0 +1,16 @@
//! Prints the `lucisv.lint.severity.*` and `lucisv.lint.rules.*` settings for
//! `editors/vscode/package.json`, generated from the rule registry.
//!
//! ```text
//! cargo run -p vlog_linter --example vscode_lint_settings
//! ```
//!
//! Paste the body of the printed object into that file's
//! `contributes.configuration.properties`, replacing the block that is there.
//! The drift test in `lucisv_server` (`settings::tests::
//! the_vscode_lint_toggles_match_the_registry`) fails whenever the two
//! disagree, so a rule cannot ship without its toggle.
fn main() {
print!("{}", vlog_linter::vscode_lint_settings());
}
+204 -1
View File
@@ -7,14 +7,22 @@ use vlog_parser::ast::SourceFile;
use vlog_parser::span::TextRange;
use vlog_parser::token::{Comment, Token, TokenKind};
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LexError, LineIndex};
use vlog_semantic::{analyze, Semantics};
use vlog_semantic::{analyze, Exports, PackageExports, Semantics};
use crate::options::RuleOptions;
use crate::signals::Signals;
/// The default tab stop used when a fix expands a tab, matching lucisv's
/// default indent. `LintContext::with_tab_width` follows `--indent`.
const DEFAULT_TAB_WIDTH: usize = 2;
/// The width `line-length` holds a file to when nothing says otherwise —
/// `vlog_formatter::Config`'s own default, because the two are the same
/// number: a formatted file that the linter then calls too wide would be
/// lucisv disagreeing with itself. `LintContext::with_line_length` follows
/// `--line-length` and `lucisv.toml`.
const DEFAULT_LINE_LENGTH: usize = 100;
/// One text, parsed once: the products a lint run reads.
///
/// This is the owned half of "one parse, two tools" (TODO §4): a caller with
@@ -84,6 +92,16 @@ impl ParsedSource {
&self.tokens
}
/// The tolerant parse itself — public for the same reason [`tokens`] is:
/// a caller that has already paid for the parse can read the tree for
/// something else (`lucisv check` harvests its interface census off it)
/// instead of parsing the same text twice.
///
/// [`tokens`]: ParsedSource::tokens
pub fn file(&self) -> &SourceFile {
&self.file
}
/// A lint context borrowing this parse. `path` is the file the text came
/// from, or `None` for a buffer (stdin) — rules that need a filename skip.
pub fn context(&self, path: Option<PathBuf>) -> LintContext<'_> {
@@ -125,6 +143,70 @@ enum Backing<'a> {
pub trait MentionOracle: Sync {
/// Whether any file **other than** the one being linted mentions `name`.
fn mentioned_elsewhere(&self, name: &str) -> bool;
/// What the project says the module or interface `name` declares, or
/// `None` when it cannot say — the unit is not in the project, or it is
/// declared more than once and the declarations disagree.
///
/// The second question a rule may ask about other files, added by TODO
/// §33.2 for `unknown-port` and `unknown-parameter`. It is deliberately
/// still a *closed* question — the names a connection list may use, and
/// nothing about them — and `None` is a first-class answer that every
/// caller must treat as silence rather than as an empty list. A front end
/// with no such table at all answers `None` to everything, which leaves
/// those two rules quiet and every other rule exactly where it was.
fn module_interface(&self, _name: &str) -> Option<ModuleInterface> {
None
}
/// Every name the package `package` exports, re-exports included — or
/// [`Exports::Unknown`] when the project holds no such package and
/// [`Exports::Ambiguous`] when it holds two.
///
/// The third closed question a rule may ask about other files, added by
/// TODO §52.2 for `unused-import`. It is deliberately the *same*
/// question `vlog_refactor`'s organize-imports engine asks its workspace
/// index — [`vlog_semantic::PackageExports`] — so the rule that squiggles
/// an unused import and the refactoring that deletes it cannot come to
/// disagree about what a package exports. A front end with no such table
/// answers `Unknown` to everything, which leaves the rule silent.
fn package_exports(&self, _package: &str) -> Exports {
Exports::Unknown
}
}
/// The project's package table as [`vlog_semantic`] wants to read it — one
/// [`MentionOracle`], asked through the trait the judgement takes.
pub(crate) struct OracleExports<'a>(pub(crate) Option<&'a dyn MentionOracle>);
impl PackageExports for OracleExports<'_> {
fn exports(&self, package: &str) -> Exports {
match self.0 {
Some(oracle) => oracle.package_exports(package),
None => Exports::Unknown,
}
}
}
/// The names a module or interface declares that an instantiation may write.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ModuleInterface {
/// Port names, as written.
pub ports: Vec<String>,
/// Overridable parameter names, as written — a `localparam` is not one.
pub parameters: Vec<String>,
}
impl ModuleInterface {
/// Whether the unit declares a port called `name`.
pub fn has_port(&self, name: &str) -> bool {
self.ports.iter().any(|port| port == name)
}
/// Whether the unit declares an overridable parameter called `name`.
pub fn has_parameter(&self, name: &str) -> bool {
self.parameters.iter().any(|parameter| parameter == name)
}
}
/// Where a context's symbol table comes from: lent by a caller that already
@@ -134,6 +216,12 @@ pub trait MentionOracle: Sync {
/// Lazy rather than eager because most rules are syntactic: a run with no
/// semantic rule enabled — which is every default `lucisv check`, since all
/// three semantic rules ship off — must not pay for an analysis nobody reads.
// The `Lazy` variant is the table itself, held inline on purpose: it is one
// per lint run, it is written exactly once, and boxing it would add an
// allocation to the path that already avoided one by not analyzing at all.
// `Semantics` grew past clippy's variant-size threshold when it gained its
// `duplicates` table (§33.2); nothing about the trade changed with it.
#[allow(clippy::large_enum_variant)]
enum SemanticsSlot<'a> {
Lent(&'a Semantics),
Lazy(OnceCell<Semantics>),
@@ -149,6 +237,10 @@ pub struct LintContext<'a> {
backing: Backing<'a>,
path: Option<PathBuf>,
tab_width: usize,
line_length: usize,
/// What the run configured about each rule, or `None` for a run that
/// configured nothing — which reads exactly as the specs' own defaults.
options: Option<&'a RuleOptions>,
/// Byte ranges of string literals, ascending — the one place text rules
/// must not rewrite, because there whitespace is data.
strings: Vec<TextRange>,
@@ -156,6 +248,9 @@ pub struct LintContext<'a> {
/// The signal table the semantic rules read, built once for all of them
/// the first time one asks — and never for a run with none enabled.
signals: OnceCell<Signals>,
/// Whether the tolerant parse produced no `Error` leaf, answered once for
/// the rules that read structure. See [`LintContext::parsed_cleanly`].
clean: OnceCell<bool>,
/// What the workspace says about a name, when the caller has a workspace.
/// `None` is a run that cannot see other files — a single-file
/// `lucisv check`, stdin, a unit test — and every rule that would consult
@@ -199,9 +294,12 @@ impl<'a> LintContext<'a> {
backing,
path,
tab_width: DEFAULT_TAB_WIDTH,
line_length: DEFAULT_LINE_LENGTH,
options: None,
strings: Vec::new(),
semantics: SemanticsSlot::Lazy(OnceCell::new()),
signals: OnceCell::new(),
clean: OnceCell::new(),
oracle: None,
};
ctx.strings =
@@ -215,6 +313,68 @@ impl<'a> LintContext<'a> {
self
}
/// Sets the width the run's formatter would wrap to, which is what
/// `line-length` holds the file to unless that rule's own `length` option
/// says otherwise.
pub fn with_line_length(mut self, line_length: usize) -> LintContext<'a> {
self.line_length = line_length.max(1);
self
}
/// Lends the per-rule options the run resolved. A context without them
/// reads every option at its declared default, which is the shipped
/// behaviour.
pub fn with_options(mut self, options: &'a RuleOptions) -> LintContext<'a> {
self.options = Some(options);
self
}
/// The width the run's formatter wraps to. See
/// [`with_line_length`](LintContext::with_line_length).
pub fn line_length(&self) -> usize {
self.line_length
}
/// What the run configured, or the empty set.
pub fn options(&self) -> &RuleOptions {
match self.options {
Some(options) => options,
None => RuleOptions::none(),
}
}
/// One boolean option of `rule`, or its declared default.
pub fn option_bool(&self, rule: &str, key: &str) -> bool {
self.options().bool(rule, key)
}
/// One integer option of `rule`, or its declared default.
pub fn option_int(&self, rule: &str, key: &str) -> i64 {
self.options().int(rule, key)
}
/// One string (or pattern) option of `rule`, or its declared default.
pub fn option_str(&self, rule: &str, key: &str) -> &str {
self.options().str(rule, key)
}
/// One list option of `rule`, or its declared default.
pub fn option_list(&self, rule: &str, key: &str) -> Vec<String> {
self.options().list(rule, key)
}
/// Whether the run said anything about this option at all — the question
/// a rule asks when its fallback is not its spec's default.
pub fn option_is_set(&self, rule: &str, key: &str) -> bool {
self.options().is_set(rule, key)
}
/// One pattern option of `rule`, compiled, or `None` if it does not
/// compile — which cannot happen for a value this run accepted.
pub(crate) fn option_pattern(&self, rule: &str, key: &str) -> Option<crate::regex::Regex> {
crate::options::pattern(self.options(), rule, key)
}
/// Lends the symbol table the caller already built for this exact text —
/// "one parse, two tools" extended to the analysis (the language server
/// analyzes every buffer anyway, so its lint pass must not analyze twice).
@@ -245,6 +405,23 @@ impl<'a> LintContext<'a> {
self.oracle.is_some_and(|oracle| oracle.mentioned_elsewhere(name))
}
/// What the project says the unit `name` declares. `None` — no oracle, no
/// such unit, or two that disagree — means the run cannot answer, and a
/// rule that asked must then say nothing.
pub fn module_interface(&self, name: &str) -> Option<ModuleInterface> {
self.oracle?.module_interface(name)
}
/// The project's package table, as the shared import judgement reads it.
///
/// A run with no oracle answers [`Exports::Unknown`] to every package,
/// which makes `vlog_semantic::import_usage` refuse rather than guess —
/// so `unused-import` is silent in a single-file run exactly as
/// `unused-signal` is.
pub fn package_exports(&self) -> impl PackageExports + '_ {
OracleExports(self.oracle)
}
/// Whether this run can see other files at all.
pub fn has_oracle(&self) -> bool {
self.oracle.is_some()
@@ -266,6 +443,32 @@ impl<'a> LintContext<'a> {
self.signals.get_or_init(|| Signals::scan(self))
}
/// Whether the whole file fit the grammar — no `Error` leaf anywhere in
/// the tolerant parse.
///
/// The tolerant parse is what makes a text rule work in a half-written
/// buffer, and most rules are right to ignore the difference. A rule that
/// reads **structure** is not: error recovery unwinds out of the construct
/// it failed in, so the declarations that followed are bound in whatever
/// scope recovery landed in — a class method's locals end up at file
/// scope, and every one of them looks like a redeclaration of the last
/// method's. Measured on opentitan: `spi_device_scoreboard.sv` (454 parse
/// errors, a macro-heavy UVM file) produced sixteen such phantoms, which
/// is sixteen wrong accusations from one file. A rule that would rather be
/// silent than wrong asks this first.
pub fn parsed_cleanly(&self) -> bool {
*self.clean.get_or_init(|| {
let mut clean = true;
crate::visit::walk_items(self.file(), &mut |item| {
clean &= !matches!(item.kind, vlog_parser::ast::ItemKind::Error(_));
});
crate::visit::walk_all_stmts(self.file(), &mut |stmt| {
clean &= !matches!(stmt.kind, vlog_parser::ast::StmtKind::Error(_));
});
clean
})
}
/// The source text being linted.
pub fn source(&self) -> &str {
match &self.backing {
+331
View File
@@ -0,0 +1,331 @@
//! Every declared type and every dimension in a file.
//!
//! A `DataType` is written in a dozen places — a port, a parameter, a
//! declarator, a typedef's base, a struct member, a subroutine's return type
//! and its arguments — and the rules that judge a *type* (the packed-dimension
//! ordering, a negative array bound) care about all of them equally. Collecting
//! them lives here rather than in `visit`, which is about the item and
//! statement spines; keeping the two apart is what stops either file from
//! becoming "everything a rule might want to walk".
use vlog_parser::ast::{
DataType, Dim, EnumType, FunctionDecl, ItemKind, ListElem, SourceFile, StmtKind, StructType,
TaskDecl, TfArg, TypeExtra, TypedefKind,
};
use vlog_parser::span::TextRange;
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
/// Where a dimension was written. The two are different constructs with
/// different conventions — `[N-1:0]` for a packed vector, `[N]` for an array —
/// so a rule that judges one must not judge the other by accident.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Packing {
/// Written before the declared name: a vector's width.
Packed,
/// Written after it: an array's extent.
Unpacked,
}
/// Calls `f` on every data type written in the file, an anonymous aggregate's
/// members and base included.
pub(crate) fn walk_data_types(file: &SourceFile, f: &mut dyn FnMut(&DataType)) {
let mut visit = |ty: &DataType| descend(ty, f);
walk_param_ports(file, &mut |port| visit(&port.ty));
walk_items(file, &mut |item| match &item.kind {
ItemKind::Module(module) => {
if let vlog_parser::ast::PortList::Ansi(ports) = &module.ports {
for port in ports.iter().filter_map(ListElem::ok) {
visit(&port.ty);
}
}
}
ItemKind::Typedef(typedef) => typedef_types(&typedef.kind, &mut visit),
ItemKind::ParamDecl(decl) => visit(&decl.ty),
ItemKind::DataDecl(decl) => visit(&decl.ty),
ItemKind::PortDecl(decl) => visit(&decl.ty),
ItemKind::Function(decl) => function_types(decl, &mut visit),
ItemKind::Task(decl) => task_types(decl, &mut visit),
_ => {}
});
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
StmtKind::VarDecl(decl) => visit(&decl.ty),
StmtKind::ParamDecl(decl) => visit(&decl.ty),
StmtKind::PortDecl(decl) => visit(&decl.ty),
StmtKind::Typedef(typedef) => typedef_types(&typedef.kind, &mut visit),
_ => {}
});
}
/// Calls `f` on every dimension in the file, saying which kind it is.
pub(crate) fn walk_dims(file: &SourceFile, f: &mut dyn FnMut(Packing, &Dim)) {
walk_data_types(file, &mut |ty| {
for dim in &ty.packed {
f(Packing::Packed, dim);
}
});
walk_unpacked(file, f);
}
/// The unpacked half: the `[…]` written *after* a declared name.
fn walk_unpacked(file: &SourceFile, f: &mut dyn FnMut(Packing, &Dim)) {
let mut unpacked = |dims: &[Dim]| {
for dim in dims {
f(Packing::Unpacked, dim);
}
};
walk_param_ports(file, &mut |port| unpacked(&port.unpacked));
walk_items(file, &mut |item| match &item.kind {
ItemKind::Module(module) => {
if let vlog_parser::ast::PortList::Ansi(ports) = &module.ports {
for port in ports.iter().filter_map(ListElem::ok) {
unpacked(&port.unpacked);
}
}
}
ItemKind::Typedef(typedef) => unpacked(&typedef.unpacked),
ItemKind::ParamDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
ItemKind::DataDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
ItemKind::PortDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
ItemKind::Function(decl) => arg_dims(&decl.args, &mut unpacked),
ItemKind::Task(decl) => arg_dims(&decl.args, &mut unpacked),
_ => {}
});
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
StmtKind::VarDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
StmtKind::ParamDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
StmtKind::PortDecl(decl) => declarator_dims(&decl.declarators, &mut unpacked),
StmtKind::Typedef(typedef) => unpacked(&typedef.unpacked),
_ => {}
});
}
fn declarator_dims(declarators: &[vlog_parser::ast::Declarator], unpacked: &mut dyn FnMut(&[Dim])) {
for declarator in declarators {
unpacked(&declarator.unpacked);
}
}
fn arg_dims(args: &[ListElem<TfArg>], unpacked: &mut dyn FnMut(&[Dim])) {
for arg in args.iter().filter_map(ListElem::ok) {
unpacked(&arg.unpacked);
}
}
fn typedef_types(kind: &TypedefKind, visit: &mut dyn FnMut(&DataType)) {
match kind {
TypedefKind::Alias(ty) => visit(ty),
TypedefKind::Enum(enum_ty) => enum_types(enum_ty, visit),
TypedefKind::Struct(struct_ty) => struct_types(struct_ty, visit),
TypedefKind::ForwardClass => {}
}
}
fn function_types(decl: &FunctionDecl, visit: &mut dyn FnMut(&DataType)) {
if let Some(ret) = &decl.ret {
visit(ret);
}
for arg in decl.args.iter().filter_map(ListElem::ok) {
visit(&arg.ty);
}
}
fn task_types(decl: &TaskDecl, visit: &mut dyn FnMut(&DataType)) {
for arg in decl.args.iter().filter_map(ListElem::ok) {
visit(&arg.ty);
}
}
fn enum_types(enum_ty: &EnumType, visit: &mut dyn FnMut(&DataType)) {
if let Some(base) = &enum_ty.base {
visit(base);
}
}
fn struct_types(struct_ty: &StructType, visit: &mut dyn FnMut(&DataType)) {
for member in &struct_ty.members {
visit(&member.ty);
}
}
/// A type written in a declaration, with the name that declaration gives.
///
/// What the two `typedef-*` rules need and `walk_data_types` cannot say: a
/// `DataType` carries no span of its own, so a rule that judges the *type* of
/// a declaration reports at the name — and needs to know whether that
/// declaration is nested inside another aggregate's body.
pub(crate) struct DeclaredType<'a> {
/// The type as written.
pub(crate) ty: &'a DataType,
/// The name declared with it.
pub(crate) name: &'a str,
/// Byte range of that name — where a finding points.
pub(crate) span: TextRange,
/// True when this declaration is a member of another `struct`/`union`.
pub(crate) nested: bool,
}
/// Calls `f` on every type written in a **declaration** — a data or port
/// declaration, an ANSI port, a variable declaration in a statement — and on
/// every member of an aggregate written inside one.
///
/// A `typedef`'s own base type is deliberately not visited: a named type is
/// exactly what the `typedef-*` rules ask for, so passing it to them would be
/// asking them to flag the shape they exist to encourage. Its members are
/// visited, as nested declarations.
pub(crate) fn walk_declared_types(file: &SourceFile, f: &mut dyn FnMut(&DeclaredType)) {
walk_items(file, &mut |item| match &item.kind {
ItemKind::Module(module) => {
if let vlog_parser::ast::PortList::Ansi(ports) = &module.ports {
for port in ports.iter().filter_map(ListElem::ok) {
declared(&port.ty, &port.name, port.name_span, false, f);
}
}
}
ItemKind::DataDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
ItemKind::PortDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
// Only the members: the typedef itself is the named type these rules
// want, and the naming rules judge its name.
ItemKind::Typedef(typedef) => typedef_members(&typedef.kind, f),
_ => {}
});
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
StmtKind::VarDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
StmtKind::PortDecl(decl) => declarator_types(&decl.ty, &decl.declarators, f),
StmtKind::Typedef(typedef) => typedef_members(&typedef.kind, f),
_ => {}
});
}
/// One declaration, and whatever aggregate its type carries.
fn declared(
ty: &DataType,
name: &str,
span: TextRange,
nested: bool,
f: &mut dyn FnMut(&DeclaredType),
) {
f(&DeclaredType { ty, name, span, nested });
members_of(ty, f);
}
/// One declaration's type, once per name it declares.
fn declarator_types(
ty: &DataType,
declarators: &[vlog_parser::ast::Declarator],
f: &mut dyn FnMut(&DeclaredType),
) {
for declarator in declarators {
declared(ty, &declarator.name, declarator.name_span, false, f);
}
}
/// The members of an anonymous aggregate, and of the aggregates inside it.
fn members_of(ty: &DataType, f: &mut dyn FnMut(&DeclaredType)) {
if let Some(TypeExtra::Struct(structure)) = ty.inline() {
struct_members(structure, f);
}
}
/// The members of a `struct`/`union` body, each as a nested declaration.
fn struct_members(structure: &StructType, f: &mut dyn FnMut(&DeclaredType)) {
for member in &structure.members {
for declarator in &member.declarators {
f(&DeclaredType {
ty: &member.ty,
name: &declarator.name,
span: declarator.name_span,
nested: true,
});
}
members_of(&member.ty, f);
}
}
/// A typedef's members — everything inside its body, but not the body itself.
fn typedef_members(kind: &TypedefKind, f: &mut dyn FnMut(&DeclaredType)) {
if let TypedefKind::Struct(structure) = kind {
struct_members(structure, f);
}
}
/// One type and whatever aggregate it *is*: an anonymous `enum`'s base and an
/// anonymous `struct`'s members are types written inside this one.
fn descend(ty: &DataType, f: &mut dyn FnMut(&DataType)) {
f(ty);
match ty.inline() {
Some(TypeExtra::Enum(enum_ty)) => enum_types(enum_ty, &mut |inner| descend(inner, f)),
Some(TypeExtra::Struct(struct_ty)) => {
struct_types(struct_ty, &mut |inner| descend(inner, f))
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::parse_source_tolerant;
fn packed_widths(src: &str) -> Vec<String> {
let (file, _) = parse_source_tolerant(src);
let mut out = Vec::new();
walk_dims(&file, &mut |packing, dim| {
if packing == Packing::Packed {
out.push(src[dim.span.as_range()].to_string());
}
});
out
}
fn unpacked_extents(src: &str) -> Vec<String> {
let (file, _) = parse_source_tolerant(src);
let mut out = Vec::new();
walk_dims(&file, &mut |packing, dim| {
if packing == Packing::Unpacked {
out.push(src[dim.span.as_range()].to_string());
}
});
out
}
#[test]
fn reaches_the_packed_dimensions_of_every_declaration_shape() {
let src = "module m #(parameter logic [1:0] P = 0) (\n\
input logic [2:0] a\n\
);\n\
logic [3:0] b;\n\
typedef logic [4:0] w_t;\n\
function logic [5:0] f(input logic [6:0] x);\n\
logic [7:0] local_v;\n\
return 0;\n\
endfunction\n\
endmodule\n";
assert_eq!(
packed_widths(src),
vec!["[1:0]", "[2:0]", "[3:0]", "[4:0]", "[5:0]", "[6:0]", "[7:0]"]
);
}
#[test]
fn reaches_an_anonymous_aggregates_members_and_base() {
let src = "module m;\n\
struct packed { logic [1:0] a; logic [2:0] b; } s;\n\
enum logic [3:0] { A } e;\n\
endmodule\n";
assert_eq!(packed_widths(src), vec!["[1:0]", "[2:0]", "[3:0]"]);
}
#[test]
fn packed_and_unpacked_are_told_apart() {
let src = "module m;\n logic [1:0] q [4];\nendmodule\n";
assert_eq!(packed_widths(src), vec!["[1:0]"]);
assert_eq!(unpacked_extents(src), vec!["[4]"]);
}
#[test]
fn a_struct_member_is_reached_through_a_typedef() {
let src = "typedef struct packed {\n logic [9:0] wide;\n} w_t;\n";
assert_eq!(packed_widths(src), vec!["[9:0]"]);
}
}
+315
View File
@@ -0,0 +1,315 @@
//! 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) => root(expr),
StmtKind::EventTrigger(t) => root(&t.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),
// The stream range's operands are reads like any index's.
ExprKind::StreamWith { base, range } => {
descend(base, f);
descend(&range.msb, f);
if let Some(lsb) = &range.lsb {
descend(lsb, 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);
}
}
+215
View File
@@ -0,0 +1,215 @@
//! What one file declares that a project census has to know: each module's
//! connectable surface, and each package's exported names.
//!
//! The language server answers [`MentionOracle::module_interface`] from its
//! workspace index, which already records every module's ports and parameters.
//! `lucisv check` has no index, so it reads the same facts off the parse it
//! makes anyway — this file is that reading, and it lives here so the CLI and
//! the linter cannot come to disagree about what "a port of this module" is.
//!
//! Erring is one-directional on purpose: a unit whose header lucisv cannot see
//! whole is reported as **unknowable** rather than as a short list, because a
//! short list is what turns a legal connection into an accusation.
use std::path::Path;
use vlog_parser::ast::{ItemKind, ListElem, Module, ParamPort, PortList, SourceFile};
use vlog_semantic::{SymbolKind, WorkspaceIndex};
use crate::context::ModuleInterface;
use crate::visit::walk_items;
/// Every package one file declares, with the names it exports — `None` for a
/// package this file alone cannot answer for.
///
/// The CLI's half of [`crate::MentionOracle::package_exports`], on the same
/// terms [`module_interfaces`] is the CLI's half of `module_interface`: the
/// language server reads the answer off its workspace index, and a run with
/// no index reads it off a **one-file** index of the very same kind, so the
/// two cannot come to disagree about what a package exports.
///
/// A package writing `export q::*;` answers `None`: which names that lets
/// through is a question only a whole-project index can settle, and a short
/// list is what would turn a used import into an accusation.
pub fn package_exports(path: &Path, src: &str) -> Vec<(String, Option<Vec<String>>)> {
let index = WorkspaceIndex::build([(path.to_path_buf(), src)]);
index
.units_of(SymbolKind::Package)
.map(|(name, _)| name.to_string())
.collect::<Vec<_>>()
.into_iter()
.map(|name| {
let answer = index
.reexported_packages(&name)
.is_empty()
.then(|| index.members_of(&name).map(|(member, _)| member.to_string()).collect());
(name, answer)
})
.collect()
}
/// Every module, interface and program the file declares, with what it
/// exposes. `None` for a unit whose header cannot be read whole.
///
/// A file may declare a name twice (two `` `ifdef`` arms, a copy-paste); the
/// caller merges across files and must treat any disagreement as unknowable,
/// so both entries are returned rather than one.
pub fn module_interfaces(file: &SourceFile) -> Vec<(String, Option<ModuleInterface>)> {
let mut out = Vec::new();
walk_items(file, &mut |item| {
if let ItemKind::Module(module) = &item.kind {
out.push((module.name.clone(), interface_of(module)));
}
});
out
}
/// One unit's surface, or `None` when its header is not fully visible.
fn interface_of(module: &Module) -> Option<ModuleInterface> {
// A directive written *between* ports or parameters may be a conditional
// — whose arms are all in the list, so the list stays a superset — or a
// macro invocation standing where a port belongs, whose expansion lucisv
// never sees. Telling the two apart would be a second preprocessor; a
// header with any directive in it is simply not answered for.
if !module.port_directives.is_empty() || !module.param_directives.is_empty() {
return None;
}
Some(ModuleInterface { ports: ports_of(module), parameters: parameters_of(module) })
}
/// The port names of either header style. A header with no port list at all
/// declares none, which is a fact rather than a gap: nothing may be connected
/// to it by name.
fn ports_of(module: &Module) -> Vec<String> {
match &module.ports {
PortList::Ansi(ports) => {
ports.iter().filter_map(ListElem::ok).map(|port| port.name.clone()).collect()
}
PortList::NonAnsi(ports) => {
ports.iter().filter_map(ListElem::ok).map(|port| port.name.clone()).collect()
}
PortList::None | PortList::Empty => Vec::new(),
}
}
/// The names an `#(.NAME(value))` override may write: every `parameter` in the
/// header and in the body.
///
/// A `localparam` is **not** one — it is the module's own constant and is not
/// overridable (IEEE 1800 §6.20.4), which is exactly the distinction
/// `SymbolKind::LocalParam` was parted out for. A header parameter written
/// without a keyword continues the previous declaration and inherits its
/// keyword, which is how `#(parameter int A = 1, B = 2)` declares two
/// overridable parameters.
fn parameters_of(module: &Module) -> Vec<String> {
let mut out = Vec::new();
let mut overridable = true;
for port in module.param_ports.iter().flatten().filter_map(ListElem::ok) {
overridable = is_parameter(port, overridable);
if overridable {
out.push(port.name.clone());
}
}
for item in &module.items {
if let ItemKind::ParamDecl(decl) = &item.kind {
if decl.kw == "parameter" {
out.extend(decl.declarators.iter().map(|d| d.name.clone()));
}
}
}
out
}
/// Whether this header parameter is overridable, given whether the one before
/// it was: a written keyword decides, and no keyword continues.
fn is_parameter(port: &ParamPort, previous: bool) -> bool {
match port.kw.as_deref() {
Some("localparam") => false,
Some(_) => true,
None => previous,
}
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::parse_source_tolerant;
fn interfaces(src: &str) -> Vec<(String, Option<ModuleInterface>)> {
let (file, _) = parse_source_tolerant(src);
module_interfaces(&file)
}
fn only(src: &str) -> ModuleInterface {
let found = interfaces(src);
assert_eq!(found.len(), 1, "{found:?}");
found.into_iter().next().and_then(|(_, i)| i).expect("a readable header")
}
#[test]
fn reads_an_ansi_header() {
let read = only(
"module m #(parameter int Width = 8, localparam int Derived = Width + 1) (\n\
input logic clk_i,\n\
output logic [7:0] data_o\n\
);\n\
endmodule\n",
);
assert_eq!(read.ports, vec!["clk_i", "data_o"]);
assert_eq!(read.parameters, vec!["Width"], "a localparam is not overridable");
}
#[test]
fn reads_a_non_ansi_header() {
let read = only("module m (clk, rst_n);\n input clk;\n input rst_n;\nendmodule\n");
assert_eq!(read.ports, vec!["clk", "rst_n"]);
}
#[test]
fn a_continuation_parameter_inherits_its_keyword() {
let read = only("module m #(parameter int A = 1, B = 2) ();\nendmodule\n");
assert_eq!(read.parameters, vec!["A", "B"]);
let local = only("module m #(localparam int A = 1, B = 2) ();\nendmodule\n");
assert!(local.parameters.is_empty(), "both continue the localparam");
}
#[test]
fn a_body_parameter_is_overridable_and_a_body_localparam_is_not() {
let read =
only("module m ();\n parameter int Depth = 4;\n localparam int W = 2;\nendmodule\n");
assert_eq!(read.parameters, vec!["Depth"]);
}
#[test]
fn a_header_with_a_directive_in_it_is_unknowable() {
let src = "module m (\n\
`ifdef X\n\
input logic a,\n\
`endif\n\
input logic b\n\
);\n\
endmodule\n";
assert_eq!(interfaces(src), vec![("m".to_string(), None)]);
}
#[test]
fn a_port_less_module_declares_no_ports() {
let read = only("module m;\nendmodule\n");
assert!(read.ports.is_empty());
assert!(read.parameters.is_empty());
let empty = only("module m ();\nendmodule\n");
assert!(empty.ports.is_empty());
}
#[test]
fn an_interface_is_read_the_same_way() {
let read = only("interface bus_if (input logic clk);\nendinterface\n");
assert_eq!(read.ports, vec!["clk"]);
}
#[test]
fn every_unit_of_a_file_is_returned() {
let found = interfaces("module a ();\nendmodule\nmodule b ();\nendmodule\n");
assert_eq!(found.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(), vec!["a", "b"]);
}
}
+107 -7
View File
@@ -21,27 +21,48 @@
//! `docs/features/linter-core/README.md`.
mod context;
mod decls;
mod exprs;
mod interfaces;
mod literal;
mod module_decls;
mod naming;
mod options;
mod preproc;
mod regex;
mod registry;
mod rule_docs;
mod rules;
mod severity;
mod signals;
mod violation;
mod visit;
mod vscode;
mod waiver;
mod waiver_file;
use std::path::PathBuf;
pub use context::{LintContext, MentionOracle, ParsedSource};
pub use registry::{all_rules, default_rules, rule_by_name, select_rules, workspace_rules, Rule};
pub use context::{LintContext, MentionOracle, ModuleInterface, ParsedSource};
pub use interfaces::{module_interfaces, package_exports};
pub use options::{OptionDefault, OptionKind, OptionSpec, OptionValue, RuleOptions};
pub use registry::{
all_rules, default_rules, rule_by_name, rules_named, select_rules, workspace_rules, Rule,
};
pub use rule_docs::rules_markdown;
pub use severity::Severity;
pub use violation::{apply_fixes, Applicability, Fix, Fixed, Violation};
/// The identifier census a [`MentionOracle`] is answered from, re-exported
/// from `vlog_semantic` so a front end that implements the oracle needs this
/// crate alone. One harvest for the whole workspace — see
/// `docs/features/semantic-lints-on/README.md`.
pub use vlog_semantic::words;
/// The package table a [`MentionOracle`] answers `package_exports` with,
/// re-exported so an implementor names one crate rather than two.
pub use vlog_semantic::Exports;
pub use vscode::{rule_setting, severity_setting, vscode_lint_settings, RULE_CHOICES};
pub use waiver::UNUSED_WAIVER;
pub use waiver_file::{ExternalWaivers, UnusedReport, WaiverUse};
use waiver::Waivers;
@@ -58,14 +79,32 @@ pub fn run(source: &str, path: Option<PathBuf>, enabled: &[&'static dyn Rule]) -
/// The result is sorted by position, then by rule name, so two runs over the
/// same file print in the same order whatever order the registry has.
pub fn lint(ctx: &LintContext, enabled: &[&'static dyn Rule]) -> Vec<Violation> {
lint_with(ctx, enabled, &ExternalWaivers::default()).0
}
/// [`lint`] with the run's external waiver files applied too, reporting which
/// of their directives fired.
///
/// **Precedence is union**: a violation is dropped when an inline waiver *or*
/// an external one covers it, and one both cover marks both used, so neither
/// is then reported as dead. The usage half is the caller's to keep — only a
/// whole run knows whether a `--location` matched some file somewhere, which
/// is why `lucisv check` reports unused external waivers and the server does
/// not. See `docs/features/waiver-files/README.md`.
pub fn lint_with(
ctx: &LintContext,
enabled: &[&'static dyn Rule],
external: &ExternalWaivers,
) -> (Vec<Violation>, WaiverUse) {
let names: Vec<&'static str> = enabled.iter().map(|rule| rule.name()).collect();
let mut waivers = Waivers::collect(ctx);
let mut used = WaiverUse::default();
let mut found = Vec::new();
for rule in enabled {
found.extend(rule.check(ctx));
}
let mut kept = waivers.filter(ctx, found);
let mut kept = waive(ctx, &mut waivers, external, &mut used, found);
if names.contains(&UNUSED_WAIVER) {
// `unused-waiver` findings are themselves waivable, which is circular:
@@ -76,7 +115,7 @@ pub fn lint(ctx: &LintContext, enabled: &[&'static dyn Rule]) -> Vec<Violation>
loop {
let before = waivers.used_count();
let unused = waivers.unused(&names);
let surviving = waivers.filter(ctx, unused);
let surviving = waive(ctx, &mut waivers, external, &mut used, unused);
if waivers.used_count() == before {
kept.extend(surviving);
break;
@@ -87,7 +126,46 @@ pub fn lint(ctx: &LintContext, enabled: &[&'static dyn Rule]) -> Vec<Violation>
kept.sort_by(|a, b| {
(a.span.start, a.span.end, a.rule).cmp(&(b.span.start, b.span.end, b.rule))
});
kept
stamp_severities(&mut kept);
(kept, used)
}
/// The violations neither an inline waiver nor an external one covers.
///
/// Both are always asked — never `||` short-circuited — because a violation
/// two waivers cover has to mark both of them used.
fn waive(
ctx: &LintContext,
inline: &mut Waivers,
external: &ExternalWaivers,
used: &mut WaiverUse,
violations: Vec<Violation>,
) -> Vec<Violation> {
let path = ctx.path();
violations
.into_iter()
.filter(|violation| {
let (line, _) = ctx.line_index().line_col(violation.span.start);
let inline_waived = inline.covers(violation.rule, line);
let external_waived =
!external.is_empty() && external.covers(path, violation.rule, line, used);
!(inline_waived || external_waived)
})
.collect()
}
/// Gives every finding the class its rule declares.
///
/// One place rather than one per rule: a rule's `check` builds violations
/// without knowing what it is called, the `unused-waiver` findings are built by
/// the waiver scanner and not by a rule at all, and a severity written twice
/// would eventually be written differently. See [`Violation::severity`].
fn stamp_severities(violations: &mut [Violation]) {
for violation in violations {
if let Some(rule) = rule_by_name(violation.rule) {
violation.severity = rule.severity();
}
}
}
#[cfg(test)]
@@ -172,11 +250,12 @@ mod tests {
// Real corpus RTL is annotated for Verible. Waivers naming rules lucisv
// has not implemented are that codebase's, not typos, so they are
// neither honored nor reported.
let src = "module m;\n // verilog_lint: waive macro-name-style\n wire a;\nendmodule\n";
let src = "module m;\n // verilog_lint: waive forbid-implicit-declarations\n wire a;\nendmodule\n";
assert!(lint_all(src).is_empty());
// lucisv's own spelling gets no such benefit of the doubt.
let src = "module m;\n // lucisv: waive macro-name-style\n wire a;\nendmodule\n";
let src =
"module m;\n // lucisv: waive forbid-implicit-declarations\n wire a;\nendmodule\n";
assert_eq!(names(&lint_all(src)), vec![UNUSED_WAIVER]);
}
@@ -211,6 +290,27 @@ mod tests {
assert!(run(src, None, &enabled).is_empty());
}
/// Every finding the runner returns carries its rule's class — including
/// the `unused-waiver` ones, which no rule's `check` produced.
#[test]
fn the_runner_stamps_every_finding_with_its_rules_severity() {
let src = "module m;\n\
\treg a; // lucisv: waive no-such-rule\n\
\talways_comb a <= 1'b0;\n\
endmodule\n";
let found = run(src, Some(PathBuf::from("rtl/m.sv")), &default_rules());
assert!(found.len() >= 3, "{found:#?}");
for violation in &found {
let rule = rule_by_name(violation.rule).expect("a registered rule");
assert_eq!(violation.severity, rule.severity(), "{}", violation.rule);
}
let by_rule =
|name: &str| found.iter().find(|v| v.rule == name).map(|v| v.severity).expect(name);
assert_eq!(by_rule("wire-reg-mixup"), Severity::Error);
assert_eq!(by_rule("always-comb-blocking"), Severity::Warning);
assert_eq!(by_rule(UNUSED_WAIVER), Severity::Style);
}
#[test]
fn a_file_that_does_not_parse_still_gets_its_text_rules() {
let src = "module m;\n\t@@@ this is not verilog\nendmodule\n";
+156
View File
@@ -0,0 +1,156 @@
//! Sized based literals, read the way the two width rules need them.
//!
//! `truncated-numeric-literal` asks "how many bits does what is written
//! actually need?" and `undersized-binary-literal` asks "how many digits were
//! written?". Both questions are about the same `<size>'<base><digits>` shape,
//! so it is parsed once here rather than twice, slightly differently.
/// One `<size>'[s]<base><digits>` literal, as written.
///
/// Only the *sized* spelling is modelled: an unsized `'h1f` takes its width
/// from context, so neither rule has anything to compare against and
/// [`parse`] returns `None` for it.
pub(crate) struct SizedLiteral<'a> {
/// The declared width, in bits.
pub width: u32,
/// The base letter, lower-cased: `b`, `o`, `d` or `h`.
pub base: char,
/// The digits as written, `_` separators included.
pub digits: &'a str,
}
impl SizedLiteral<'_> {
/// The digits with the `_` separators taken out.
pub fn packed_digits(&self) -> String {
self.digits.chars().filter(|c| *c != '_').collect()
}
/// How many bits the written value really needs, or `None` when that
/// cannot be said: an empty or malformed digit run, or a decimal value
/// carrying `x`/`z`.
///
/// A digit that is `x`, `z` or `?` counts as full-width — `4'hxF` needs
/// eight bits, because the unknown nibble is still a nibble.
pub fn significant_bits(&self) -> Option<u32> {
let digits = self.packed_digits();
let digits = digits.trim_start_matches('0');
if digits.is_empty() {
return Some(0);
}
let Some(per_digit) = bits_per_digit(self.base) else {
// Decimal: the whole run is one number, so an `x` in it makes the
// value unknown rather than one unknown digit.
let value: u128 = digits.parse().ok()?;
return Some(128 - value.leading_zeros());
};
let mut chars = digits.chars();
let first = chars.next()?;
let rest = chars.count() as u32;
let head = match first.to_ascii_lowercase() {
'x' | 'z' | '?' => per_digit,
c => bits_of(c, self.base)?,
};
Some(rest * per_digit + head)
}
}
/// Reads a sized based literal, or `None` for anything else — an unsized
/// literal, a plain decimal, a real, a time literal.
pub(crate) fn parse(text: &str) -> Option<SizedLiteral<'_>> {
let (size, rest) = text.split_once('\'')?;
let width: u32 = size.chars().filter(|c| *c != '_').collect::<String>().parse().ok()?;
// `8'sh1f` — the signedness marker sits between the tick and the base.
let rest = rest.strip_prefix(['s', 'S']).unwrap_or(rest);
let mut chars = rest.chars();
let base = chars.next()?.to_ascii_lowercase();
if !matches!(base, 'b' | 'o' | 'd' | 'h') {
return None;
}
let digits = rest.get(1..)?;
if digits.is_empty() || !digits.chars().all(|c| is_digit_of(c, base) || c == '_') {
return None;
}
Some(SizedLiteral { width, base, digits })
}
/// How many bits one digit of `base` carries; `None` for decimal, which is not
/// a per-digit base at all.
fn bits_per_digit(base: char) -> Option<u32> {
match base {
'b' => Some(1),
'o' => Some(3),
'h' => Some(4),
_ => None,
}
}
/// How many bits one known digit's value needs (`7` needs three, `1` needs
/// one), or `None` when the character is not a digit of this base.
fn bits_of(c: char, base: char) -> Option<u32> {
let value = c.to_digit(16)?;
let per_digit = bits_per_digit(base)?;
if value >= 1 << per_digit {
return None;
}
Some(32 - value.leading_zeros())
}
/// True when `c` may stand among `base`'s digits, unknowns included.
fn is_digit_of(c: char, base: char) -> bool {
let c = c.to_ascii_lowercase();
if matches!(c, 'x' | 'z' | '?') {
return true;
}
match base {
'b' => matches!(c, '0' | '1'),
'o' => c.is_digit(8),
'd' => c.is_ascii_digit(),
_ => c.is_ascii_hexdigit(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn bits(text: &str) -> Option<u32> {
parse(text)?.significant_bits()
}
#[test]
fn a_sized_literal_is_read_in_every_base() {
for (text, width, base, digits) in [
("8'hFF", 8, 'h', "FF"),
("4'b1010", 4, 'b', "1010"),
("3'o7", 3, 'o', "7"),
("16'd1000", 16, 'd', "1000"),
("8'sh1f", 8, 'h', "1f"),
("32'hdead_beef", 32, 'h', "dead_beef"),
] {
let found = parse(text).unwrap_or_else(|| panic!("{text}"));
assert_eq!((found.width, found.base, found.digits), (width, base, digits), "{text}");
}
}
#[test]
fn anything_that_is_not_a_sized_based_literal_is_declined() {
for text in ["'h1f", "42", "1.5", "10ns", "8'", "8'q1", "8'h", "8'hG", "'0"] {
assert!(parse(text).is_none(), "{text}");
}
}
#[test]
fn significant_bits_counts_what_is_written() {
assert_eq!(bits("4'h0"), Some(0));
assert_eq!(bits("4'h1"), Some(1));
assert_eq!(bits("4'h8"), Some(4));
assert_eq!(bits("4'hFFF"), Some(12), "three full nibbles");
assert_eq!(bits("8'b0000_0001"), Some(1), "leading zeros do not count");
assert_eq!(bits("4'o7"), Some(3));
assert_eq!(bits("8'd255"), Some(8));
assert_eq!(bits("8'd256"), Some(9));
assert_eq!(bits("4'hx"), Some(4), "an unknown nibble is still a nibble");
assert_eq!(bits("4'h0x"), Some(4), "and leading zeros still do not count");
assert_eq!(bits("8'dx"), None, "a decimal unknown says nothing about width");
}
}
+234
View File
@@ -0,0 +1,234 @@
//! The nets, variables and ports a module declares — what the two signal
//! naming rules judge.
//!
//! A module's own declarations are a different population from "every
//! declared name in the file": a class property, a loop variable and a
//! function local are not signals, and a rule that judged them would be
//! reporting on things the style guide says nothing about. Collecting them
//! lives here rather than in `visit` (the item and statement spines) or
//! `decls` (types and dimensions), so each of the three files stays one
//! sentence long.
use vlog_parser::ast::{
AnsiPort, GenBlock, GenElse, Item, ItemKind, ListElem, PortList, SourceFile,
};
use vlog_parser::span::TextRange;
/// One net, variable or port a module declares.
pub(crate) struct SignalDecl {
/// The declared name, as written.
pub(crate) name: String,
/// Byte range of that name.
pub(crate) span: TextRange,
/// The word a diagnostic calls it: `port` or `signal`.
pub(crate) what: &'static str,
/// The direction of a port, as written (`input`, `output`, `inout`), or
/// `None` for a signal.
pub(crate) dir: Option<String>,
}
/// Every net, variable and port declared inside a module, interface or
/// program of `file`, header and body alike, generate blocks included.
///
/// A `class` body is deliberately not descended into: its properties are not
/// signals. A function or task body is not either — a local is scoped to the
/// subroutine and named for it.
pub(crate) fn module_signals(file: &SourceFile) -> Vec<SignalDecl> {
let mut out = Vec::new();
for item in &file.items {
collect_item(item, &mut out);
}
out
}
fn collect_item(item: &Item, out: &mut Vec<SignalDecl>) {
match &item.kind {
ItemKind::Module(module) => {
header_ports(&module.ports, out);
for inner in &module.items {
collect_body(inner, out);
}
}
// A module may be written inside a package; nothing else at file
// level holds one.
ItemKind::Package { items, .. } => {
for inner in items {
collect_item(inner, out);
}
}
_ => {}
}
}
/// One item of a module body.
fn collect_body(item: &Item, out: &mut Vec<SignalDecl>) {
match &item.kind {
ItemKind::DataDecl(decl) => {
for declarator in &decl.declarators {
out.push(SignalDecl {
name: declarator.name.clone(),
span: declarator.name_span,
what: "signal",
dir: None,
});
}
}
ItemKind::PortDecl(decl) => {
for declarator in &decl.declarators {
out.push(SignalDecl {
name: declarator.name.clone(),
span: declarator.name_span,
what: "port",
dir: Some(decl.dir.clone()),
});
}
}
// A nested module is a module of its own.
ItemKind::Module(_) => collect_item(item, out),
ItemKind::GenerateRegion { items, .. } => {
for inner in items {
collect_body(inner, out);
}
}
ItemKind::GenBlock(b) => block(b, out),
ItemKind::GenIf(gen_if) => {
block(&gen_if.then, out);
let mut els = gen_if.els.as_deref();
while let Some(branch) = els {
match branch {
GenElse::If(_, nested) => {
block(&nested.then, out);
els = nested.els.as_deref();
}
GenElse::Block(inner) => {
block(inner, out);
els = None;
}
}
}
}
ItemKind::GenFor(gen_for) => block(&gen_for.body, out),
ItemKind::GenCase(gen_case) => {
for case_item in &gen_case.items {
block(&case_item.body, out);
}
}
_ => {}
}
}
fn block(block: &GenBlock, out: &mut Vec<SignalDecl>) {
for item in &block.items {
collect_body(item, out);
}
}
/// The ports of a module header, in either style.
fn header_ports(ports: &PortList, out: &mut Vec<SignalDecl>) {
match ports {
PortList::Ansi(ports) => {
// A port with no direction keyword continues the previous one, as
// the language says; a first port with none is `inout` by default.
let mut carried: Option<String> = None;
for port in ports.iter().filter_map(ListElem::ok) {
carried = direction(port).or(carried);
out.push(SignalDecl {
name: port.name.clone(),
span: port.name_span,
what: "port",
dir: carried.clone(),
});
}
}
// A non-ANSI header *names* its ports; the body declares them
// (`input clk;`), and that declaration is the one collected — so a
// rule reports each port once, where its direction is written.
PortList::NonAnsi(_) | PortList::None | PortList::Empty => {}
}
}
fn direction(port: &AnsiPort) -> Option<String> {
port.dir.clone()
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::parse_source_tolerant;
fn signals(src: &str) -> Vec<(String, &'static str, Option<String>)> {
let (file, _) = parse_source_tolerant(src);
module_signals(&file).into_iter().map(|decl| (decl.name, decl.what, decl.dir)).collect()
}
#[test]
fn collects_header_ports_body_ports_and_signals() {
let src = "module m (input logic clk, output data);\n\
\x20 wire a;\n\
\x20 logic [7:0] b, c;\n\
endmodule\n";
assert_eq!(
signals(src),
vec![
("clk".to_string(), "port", Some("input".to_string())),
("data".to_string(), "port", Some("output".to_string())),
("a".to_string(), "signal", None),
("b".to_string(), "signal", None),
("c".to_string(), "signal", None),
]
);
}
#[test]
fn a_port_with_no_direction_continues_the_previous_one() {
let src = "module m (input logic a, b, output c);\nendmodule\n";
let dirs: Vec<Option<String>> = signals(src).into_iter().map(|s| s.2).collect();
assert_eq!(
dirs,
vec![Some("input".to_string()), Some("input".to_string()), Some("output".to_string())]
);
}
/// A non-ANSI port is declared once, in the body: the header only lists
/// the names, and collecting those too would report every such port
/// twice.
#[test]
fn a_non_ansi_port_is_collected_where_the_body_declares_it() {
let src = "module m (a, b);\n input a;\n output b;\nendmodule\n";
assert_eq!(
signals(src),
vec![
("a".to_string(), "port", Some("input".to_string())),
("b".to_string(), "port", Some("output".to_string())),
]
);
}
#[test]
fn generate_blocks_are_descended_into_and_class_bodies_are_not() {
let src = "module m;\n\
\x20 generate\n\
\x20 if (A) begin : g\n wire in_gen;\n end\n\
\x20 endgenerate\n\
\x20 for (genvar i = 0; i < 2; i++) begin : l\n wire looped;\n end\n\
endmodule\n\
class c;\n logic property_of_a_class;\nendclass\n";
let names: Vec<String> = signals(src).into_iter().map(|s| s.0).collect();
assert_eq!(names, vec!["in_gen".to_string(), "looped".to_string()]);
}
#[test]
fn an_interface_and_a_module_in_a_package_are_covered() {
let src = "interface i (input clk);\n wire w;\nendinterface\n\
package p;\n module inner;\n wire deep;\n endmodule\nendpackage\n";
let names: Vec<String> = signals(src).into_iter().map(|s| s.0).collect();
assert_eq!(names, vec!["clk".to_string(), "w".to_string(), "deep".to_string()]);
}
#[test]
fn a_function_local_is_not_a_signal() {
let src = "module m;\n function void f();\n logic local_var;\n endfunction\n\
endmodule\n";
assert!(signals(src).is_empty());
}
}
+106 -21
View File
@@ -1,13 +1,12 @@
//! The naming-style presets the naming rules check against.
//!
//! Verible spells its naming conventions as RE2 regular expressions. lucisv
//! spells the same conventions as character-class predicates instead, on
//! purpose: every preset anyone actually uses is "these character classes, in
//! this order", which is four small functions — and a regex engine is a
//! dependency this crate (today: `vlog_parser` + std) does not otherwise need.
//! The cost is that user-supplied patterns are not expressible; that waits on
//! the `lint` key in `lucisv.toml` and is recorded as such in
//! `docs/features/lint-rules-2/README.md`.
//! Verible spells its naming conventions as RE2 regular expressions, and
//! since §34 so does lucisv: `crate::regex` reads the subset a style guide is
//! written in, and each naming rule takes the pattern as an option whose
//! default is the preset it shipped with. What survives here are the two
//! `CamelCase`/`ALL_CAPS` predicates — Verible spells those as *words* in
//! `parameter_style`, not as patterns — and the three small helpers every
//! naming rule shares.
//!
//! An **escaped identifier** (`\my$name `) is exempt from every style: its
//! whole point is to carry characters no convention allows.
@@ -17,13 +16,6 @@ pub(crate) fn is_escaped(name: &str) -> bool {
name.starts_with('\\')
}
/// `lower_snake_case`: starts with a lowercase letter, then lowercase
/// letters, digits and underscores.
pub(crate) fn is_lower_snake_case(name: &str) -> bool {
starts_with(name, char::is_ascii_lowercase)
&& name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}
/// `UPPER_SNAKE_CASE`: starts with an uppercase letter, then uppercase
/// letters, digits and underscores. Verible calls this preset `ALL_CAPS`.
pub(crate) fn is_upper_snake_case(name: &str) -> bool {
@@ -37,6 +29,80 @@ pub(crate) fn is_camel_case(name: &str) -> bool {
starts_with(name, char::is_ascii_uppercase) && name.chars().all(|c| c.is_ascii_alphanumeric())
}
/// The vocabulary Verible's `*_style` options are written in, and the one
/// [`matches_style_words`] reads.
pub(crate) const STYLE_WORDS: [&str; 2] = ["CamelCase", "ALL_CAPS"];
/// Whether `name` fits any of the `|`-separated preset words of a `*_style`
/// option (`CamelCase|ALL_CAPS`). A word outside the vocabulary cannot reach
/// here — the option refuses it — so an unknown one simply matches nothing.
pub(crate) fn matches_style_words(name: &str, spelling: &str) -> bool {
spelling.split('|').map(str::trim).any(|word| match word {
"CamelCase" => is_camel_case(name),
"ALL_CAPS" => is_upper_snake_case(name),
_ => false,
})
}
/// Whether `name` is one this rule accepts, given a `*_style_regex` override
/// the run may have set and the `*_style` words otherwise.
///
/// The two-key shape is Verible's: the words are what a style guide says, and
/// the pattern is the escape hatch for a project whose convention is neither.
/// An override that does not compile cannot be set (the option is validated
/// when it is read), so a `None` pattern here means "nobody set one".
pub(crate) fn fits_style(
ctx: &crate::context::LintContext,
rule: &str,
style_key: &str,
regex_key: &str,
name: &str,
) -> bool {
if ctx.option_is_set(rule, regex_key) {
return match ctx.option_pattern(rule, regex_key) {
Some(pattern) => pattern.is_match(name),
None => true,
};
}
matches_style_words(name, ctx.option_str(rule, style_key))
}
/// Whether `name` matches this rule's single pattern option — the shape the
/// three type-and-module naming rules take.
pub(crate) fn fits_pattern(
ctx: &crate::context::LintContext,
rule: &str,
regex_key: &str,
name: &str,
) -> bool {
match ctx.option_pattern(rule, regex_key) {
Some(pattern) => pattern.is_match(name),
// Unreachable for a validated option; being quiet is the safe
// direction for a rule that cannot tell what it was asked.
None => true,
}
}
/// What a naming rule says about a name it rejected.
///
/// A run that configured nothing reads the preset's own words — the sentence
/// the rule has always printed, so a default run's diagnostics are the ones
/// CI already has — and a run that set a pattern is told **which** pattern it
/// failed, because "is not lower_snake_case" would be a lie there.
pub(crate) fn style_message(
ctx: &crate::context::LintContext,
rule: &str,
regex_key: &str,
subject: &str,
preset: &str,
) -> String {
if ctx.option_is_set(rule, regex_key) {
format!("{subject} does not match `{}`", ctx.option_str(rule, regex_key))
} else {
format!("{subject} {preset}")
}
}
/// True when `name` is non-empty and its first character passes `first`.
fn starts_with(name: &str, first: impl Fn(&char) -> bool) -> bool {
name.chars().next().is_some_and(|c| first(&c))
@@ -46,13 +112,32 @@ fn starts_with(name: &str, first: impl Fn(&char) -> bool) -> bool {
mod tests {
use super::*;
/// The `lower_snake_case` preset the three type-and-module naming rules
/// used before §34 gave them `style_regex` is now spelled as the pattern
/// `[a-z][a-z_0-9]*`, and the two accept exactly the same names — which
/// is what keeps those rules' findings byte-identical.
#[test]
fn lower_snake_case_accepts_what_rtl_writes() {
for name in ["a", "clk", "data_i", "fifo2_wr_en", "a1_b2"] {
assert!(is_lower_snake_case(name), "{name}");
}
for name in ["", "Clk", "_clk", "clkA", "clk-en", "CLK", "1clk"] {
assert!(!is_lower_snake_case(name), "{name}");
fn the_lower_snake_case_pattern_is_the_preset_it_replaced() {
let pattern = crate::regex::Regex::compile("[a-z][a-z_0-9]*").expect("compiles");
let preset = |name: &str| {
name.chars().next().is_some_and(|c| c.is_ascii_lowercase())
&& name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
};
for name in [
"a",
"clk",
"data_i",
"fifo2_wr_en",
"a1_b2",
"",
"Clk",
"_clk",
"clkA",
"clk-en",
"CLK",
"1clk",
] {
assert_eq!(pattern.is_match(name), preset(name), "{name}");
}
}
+602
View File
@@ -0,0 +1,602 @@
//! Per-rule options: what a rule may be configured with, and the validated
//! map one run carries.
//!
//! Verible gives most of its rules a handful of options (`style_regex`,
//! `length`, the `*_enable` switches) and spells them
//! `--rules=rule-name=option:value`. lucisv spells them where its other
//! settings already live — a `[lint.<rule>]` table in `lucisv.toml`, a
//! `lucisv.lint.options` object in the editor — and both doors come through
//! this module, so the two front ends cannot disagree about what a value
//! means or which values are refused.
//!
//! A rule never sees "unset": every read falls back to the spec's own
//! default, which is also the default the generated rule reference prints.
//! See `docs/features/linter-expansion-2/README.md`.
use std::collections::BTreeMap;
use crate::regex::Regex;
use crate::registry::rule_by_name;
/// What kind of value one option takes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OptionKind {
/// `true` / `false`.
Bool,
/// An integer within the inclusive bounds.
Int {
/// Smallest accepted value.
min: i64,
/// Largest accepted value.
max: i64,
},
/// Any string.
Str,
/// A string that must compile as a pattern (see [`crate::regex`]).
Regex,
/// A list of strings.
List,
/// A list of strings, each of which must compile as a pattern.
RegexList,
/// One or more words from a fixed vocabulary, joined with `|` — how
/// Verible writes `parameter_style:CamelCase|ALL_CAPS`.
Words(&'static [&'static str]),
}
impl OptionKind {
/// The word `--rules-doc` and the settings UI name this kind with.
pub fn as_str(self) -> &'static str {
match self {
OptionKind::Bool => "boolean",
OptionKind::Int { .. } => "integer",
OptionKind::Str => "string",
OptionKind::Regex => "pattern",
OptionKind::List => "list of strings",
OptionKind::RegexList => "list of patterns",
OptionKind::Words(_) => "`|`-separated word list",
}
}
/// The vocabulary a [`OptionKind::Words`] option accepts, for the
/// generated reference; empty for every other kind.
pub fn vocabulary(self) -> &'static [&'static str] {
match self {
OptionKind::Words(words) => words,
_ => &[],
}
}
}
/// One option's value, as a run holds it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OptionValue {
/// A boolean.
Bool(bool),
/// An integer.
Int(i64),
/// A string — a pattern included, which is a string that compiled.
Str(String),
/// A list of strings.
List(Vec<String>),
}
impl OptionValue {
/// The word an error message calls this value's kind, so "expects an
/// integer, found a list" reads as a sentence.
fn kind_word(&self) -> &'static str {
match self {
OptionValue::Bool(_) => "a boolean",
OptionValue::Int(_) => "an integer",
OptionValue::Str(_) => "a string",
OptionValue::List(_) => "a list",
}
}
}
/// One option's default, as a rule declares it.
///
/// A second type rather than an [`OptionValue`], because a spec lives in a
/// `static` table: `&'static str` and `&'static [&'static str]` are
/// constructible there and `String`/`Vec<String>` are not. [`Self::value`]
/// is the bridge for a caller that wants the owned form.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OptionDefault {
/// A boolean default.
Bool(bool),
/// An integer default.
Int(i64),
/// A string (or pattern) default.
Str(&'static str),
/// A list default.
List(&'static [&'static str]),
}
impl OptionDefault {
/// The owned value this default stands for.
pub fn value(self) -> OptionValue {
match self {
OptionDefault::Bool(b) => OptionValue::Bool(b),
OptionDefault::Int(n) => OptionValue::Int(n),
OptionDefault::Str(s) => OptionValue::Str(s.to_string()),
OptionDefault::List(items) => {
OptionValue::List(items.iter().map(|s| s.to_string()).collect())
}
}
}
/// How the rule reference and the settings UI print this default.
pub fn as_written(self) -> String {
match self {
OptionDefault::Bool(b) => b.to_string(),
OptionDefault::Int(n) => n.to_string(),
OptionDefault::Str(s) => format!("\"{s}\""),
OptionDefault::List(items) => {
let inner: Vec<String> = items.iter().map(|s| format!("\"{s}\"")).collect();
format!("[{}]", inner.join(", "))
}
}
}
}
/// One option a rule declares: its name, its kind, what it is when nobody
/// says otherwise, and what it is for.
#[derive(Debug, Clone, Copy)]
pub struct OptionSpec {
/// The key a user writes, as Verible spells it where there is an
/// equivalent.
pub name: &'static str,
/// What kind of value it takes.
pub kind: OptionKind,
/// The value a rule reads when nobody configured it.
pub default: OptionDefault,
/// One line saying what it does — the text `--rules-doc` prints.
pub doc: &'static str,
}
/// The options a run resolved to: `rule → key → value`, validated.
///
/// Only what somebody actually set is in here. A rule asks for an option it
/// declares and gets the spec's default when this map is silent, which is why
/// no rule has an "unset" case to handle and why an empty map is exactly the
/// shipped behaviour.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RuleOptions {
values: BTreeMap<(String, String), OptionValue>,
}
/// The options a run with nothing configured has — what a context that was
/// lent none reads from.
static NONE: RuleOptions = RuleOptions::new();
impl RuleOptions {
/// An empty set of options.
pub const fn new() -> RuleOptions {
RuleOptions { values: BTreeMap::new() }
}
/// The shared empty set, for a caller with nothing to configure.
pub(crate) fn none() -> &'static RuleOptions {
&NONE
}
/// Whether anything at all was configured.
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
/// Sets one option from the text a `lucisv.toml` wrote after the `=`.
///
/// The value's shape is read **against the spec's kind** — `true`, `42`,
/// `"text"`, `["a", "b"]` — so the message a user gets names the kind the
/// option actually takes rather than TOML's idea of what they typed.
/// Unlike `lucisv_core::config`'s strings, a backslash is an ordinary
/// character here: a pattern is the one value that needs them.
pub fn set_raw(&mut self, rule: &str, key: &str, raw: &str) -> Result<(), String> {
let spec = spec_of(rule, key)?;
let value = parse_raw(&spec, raw)?;
self.insert(rule, key, value)
}
/// Sets one option from a value a front end already decoded (the editor's
/// JSON). Validated exactly as [`Self::set_raw`]'s is.
pub fn set(&mut self, rule: &str, key: &str, value: OptionValue) -> Result<(), String> {
let spec = spec_of(rule, key)?;
let value = check(&spec, value)?;
self.insert(rule, key, value)
}
fn insert(&mut self, rule: &str, key: &str, value: OptionValue) -> Result<(), String> {
self.values.insert((rule.to_string(), key.to_string()), value);
Ok(())
}
/// Lays `other`'s entries over this set's, key by key.
///
/// The merge the two front ends need: a `lucisv.toml`'s options are the
/// base and the editor's are laid over them one key at a time, so a
/// project that sets two options and a user who overrides one keep the
/// other. Both sides were validated when they were read, so nothing can
/// be refused here.
pub fn overlay(&mut self, other: &RuleOptions) {
for (key, value) in &other.values {
self.values.insert(key.clone(), value.clone());
}
}
/// Whether this run set `key` on `rule` at all — the one question a rule
/// asks when its default is not a constant (`line-length`'s `length`
/// falls back to the formatter's width).
pub fn is_set(&self, rule: &str, key: &str) -> bool {
self.lookup(rule, key).is_some()
}
/// A boolean option's value, or its default.
pub fn bool(&self, rule: &str, key: &str) -> bool {
match (self.lookup(rule, key), default_of(rule, key)) {
(Some(OptionValue::Bool(b)), _) => *b,
(_, Some(OptionDefault::Bool(b))) => b,
_ => false,
}
}
/// An integer option's value, or its default.
pub fn int(&self, rule: &str, key: &str) -> i64 {
match (self.lookup(rule, key), default_of(rule, key)) {
(Some(OptionValue::Int(n)), _) => *n,
(_, Some(OptionDefault::Int(n))) => n,
_ => 0,
}
}
/// A string (or pattern) option's value, or its default.
pub fn str(&self, rule: &str, key: &str) -> &str {
match (self.lookup(rule, key), default_of(rule, key)) {
(Some(OptionValue::Str(s)), _) => s,
(_, Some(OptionDefault::Str(s))) => s,
_ => "",
}
}
/// A list option's value, or its default.
pub fn list(&self, rule: &str, key: &str) -> Vec<String> {
match (self.lookup(rule, key), default_of(rule, key)) {
(Some(OptionValue::List(items)), _) => items.clone(),
(_, Some(OptionDefault::List(items))) => {
items.iter().map(|item| item.to_string()).collect()
}
_ => Vec::new(),
}
}
fn lookup(&self, rule: &str, key: &str) -> Option<&OptionValue> {
// A borrowed lookup without allocating the pair: the map is tiny (a
// handful of entries at most), so a scan is cheaper than the two
// `String`s a keyed lookup would build on every rule's every read.
self.values.iter().find(|((r, k), _)| r == rule && k == key).map(|(_, value)| value)
}
}
/// The spec for `rule`'s `key`, or the message a user should read instead.
fn spec_of(rule: &str, key: &str) -> Result<OptionSpec, String> {
let found = rule_by_name(rule).ok_or_else(|| format!("unknown rule `{rule}`"))?;
let options = found.options();
if options.is_empty() {
return Err(format!("rule `{rule}` takes no options"));
}
options.iter().find(|spec| spec.name == key).copied().ok_or_else(|| {
let known = options.iter().map(|spec| spec.name).collect::<Vec<_>>().join(", ");
format!("rule `{rule}` has no option `{key}`; it has: {known}")
})
}
/// One option's declared default, or `None` for a key no rule declares —
/// which the accessors treat as the type's own zero, since nothing can have
/// been stored under it either.
fn default_of(rule: &str, key: &str) -> Option<OptionDefault> {
let found = rule_by_name(rule)?;
found.options().iter().find(|spec| spec.name == key).map(|spec| spec.default)
}
/// Reads `raw` — the text after the `=` in a `lucisv.toml` — as the kind
/// `spec` declares.
fn parse_raw(spec: &OptionSpec, raw: &str) -> Result<OptionValue, String> {
let raw = raw.trim();
let value = match spec.kind {
OptionKind::Bool => match raw {
"true" => OptionValue::Bool(true),
"false" => OptionValue::Bool(false),
_ => return Err(expected(spec, "`true` or `false`", raw)),
},
OptionKind::Int { .. } => {
let digits = raw.strip_prefix('-').unwrap_or(raw);
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
return Err(expected(spec, "an integer", raw));
}
let n: i64 = raw.parse().map_err(|_| expected(spec, "an integer", raw))?;
OptionValue::Int(n)
}
OptionKind::Str | OptionKind::Regex | OptionKind::Words(_) => {
OptionValue::Str(unquote(spec, raw)?)
}
OptionKind::List | OptionKind::RegexList => {
let inner = raw
.strip_prefix('[')
.and_then(|rest| rest.strip_suffix(']'))
.ok_or_else(|| expected(spec, "a list like `[\"a\", \"b\"]`", raw))?;
let mut items: Vec<&str> = inner.split(',').map(str::trim).collect();
if items.last() == Some(&"") {
// Either an empty list or a permitted trailing comma.
items.pop();
}
OptionValue::List(
items.iter().map(|item| unquote(spec, item)).collect::<Result<_, _>>()?,
)
}
};
check(spec, value)
}
/// A `"quoted"` string, kept as written — backslashes and all.
fn unquote(spec: &OptionSpec, raw: &str) -> Result<String, String> {
let inner = raw
.strip_prefix('"')
.and_then(|rest| rest.strip_suffix('"'))
.ok_or_else(|| expected(spec, "a quoted string", raw))?;
if inner.contains('"') {
return Err(expected(spec, "a quoted string", raw));
}
Ok(inner.to_string())
}
/// Whether `value` is one this option accepts: the right kind, in range, and
/// — for a pattern — one that compiles.
fn check(spec: &OptionSpec, value: OptionValue) -> Result<OptionValue, String> {
match (spec.kind, &value) {
(OptionKind::Bool, OptionValue::Bool(_)) => Ok(value),
(OptionKind::Int { min, max }, OptionValue::Int(n)) => {
if *n < min || *n > max {
return Err(format!("`{}` must be between {min} and {max}, found {n}", spec.name));
}
Ok(value)
}
(OptionKind::Str, OptionValue::Str(_)) => Ok(value),
(OptionKind::Regex, OptionValue::Str(pattern)) => {
compile(spec, pattern)?;
Ok(value)
}
(OptionKind::List, OptionValue::List(_)) => Ok(value),
(OptionKind::RegexList, OptionValue::List(patterns)) => {
for pattern in patterns {
compile(spec, pattern)?;
}
Ok(value)
}
(OptionKind::Words(vocabulary), OptionValue::Str(spelling)) => {
let words: Vec<&str> = spelling.split('|').map(str::trim).collect();
if words.iter().any(|word| word.is_empty()) {
return Err(format!("`{}`: empty word in `{spelling}`", spec.name));
}
if let Some(bad) = words.iter().find(|word| !vocabulary.contains(word)) {
return Err(format!(
"`{}`: `{bad}` is not one of {}",
spec.name,
vocabulary.join(", ")
));
}
Ok(value)
}
_ => Err(format!(
"`{}` expects {}, found {}",
spec.name,
article(spec.kind),
value.kind_word()
)),
}
}
/// Compiles one pattern, naming the option in the message.
fn compile(spec: &OptionSpec, pattern: &str) -> Result<(), String> {
Regex::compile(pattern)
.map(|_| ())
.map_err(|e| format!("`{}`: `{pattern}` is not a valid pattern: {e}", spec.name))
}
/// The kind, with the article an error message wants in front of it.
fn article(kind: OptionKind) -> String {
match kind {
OptionKind::Int { .. } => "an integer".to_string(),
other => format!("a {}", other.as_str()),
}
}
fn expected(spec: &OptionSpec, wanted: &str, raw: &str) -> String {
format!("`{}` expects {wanted}, found `{raw}`", spec.name)
}
/// A compiled pattern option, or `None` when it does not compile.
///
/// Every pattern a run holds was compiled once when it was accepted, so
/// `None` here can only be a spec whose own default is wrong — which the
/// registry's tests forbid.
pub(crate) fn pattern(options: &RuleOptions, rule: &str, key: &str) -> Option<Regex> {
Regex::compile(options.str(rule, key)).ok()
}
#[cfg(test)]
mod tests {
use super::*;
fn options() -> RuleOptions {
RuleOptions::new()
}
#[test]
fn an_unset_option_reads_its_specs_default() {
let opts = options();
assert_eq!(opts.str("signal-name-style", "style_regex"), "[a-z_0-9]+");
assert_eq!(opts.int("line-length", "length"), 100);
assert!(!opts.is_set("line-length", "length"));
assert!(opts.is_empty());
}
#[test]
fn a_set_option_wins_and_is_remembered_as_set() {
let mut opts = options();
opts.set_raw("line-length", "length", "120").expect("accepted");
assert_eq!(opts.int("line-length", "length"), 120);
assert!(opts.is_set("line-length", "length"));
assert!(!opts.is_empty());
}
#[test]
fn every_kind_parses_from_the_text_a_toml_writes() {
let mut opts = options();
opts.set_raw("typedef-structs-unions", "allow_anonymous_nested", "true").expect("bool");
assert!(opts.bool("typedef-structs-unions", "allow_anonymous_nested"));
opts.set_raw("signal-name-style", "style_regex", "\"[a-z]+\"").expect("regex");
assert_eq!(opts.str("signal-name-style", "style_regex"), "[a-z]+");
opts.set_raw("generate-label-prefix", "prefix", "[ \"g_\", \"gen_\", ]").expect("list");
assert_eq!(
opts.list("generate-label-prefix", "prefix"),
vec!["g_".to_string(), "gen_".to_string()]
);
opts.set_raw("port-name-suffix", "suffixes", "[]").expect("empty list");
assert!(opts.list("port-name-suffix", "suffixes").is_empty());
}
#[test]
fn a_backslash_survives_into_a_pattern() {
// `lucisv_core::config` refuses escapes in its own strings; an option
// value is stored raw and read here, which is what lets `\d` through.
let mut opts = options();
opts.set_raw("signal-name-style", "style_regex", "\"[a-z]\\d+\"").expect("accepted");
assert_eq!(opts.str("signal-name-style", "style_regex"), "[a-z]\\d+");
}
#[test]
fn an_unknown_rule_or_key_says_what_exists() {
let mut opts = options();
let error = opts.set_raw("no-such-rule", "x", "1").err().unwrap_or_default();
assert!(error.contains("unknown rule `no-such-rule`"), "{error}");
let error = opts.set_raw("no-tabs", "width", "4").err().unwrap_or_default();
assert!(error.contains("takes no options"), "{error}");
let error = opts.set_raw("line-length", "len", "120").err().unwrap_or_default();
assert!(error.contains("has no option `len`"), "{error}");
assert!(error.contains("it has: length"), "{error}");
}
#[test]
fn a_wrong_kind_is_refused_through_both_doors() {
let mut opts = options();
assert!(opts.set_raw("line-length", "length", "\"120\"").is_err());
assert!(opts.set_raw("signal-name-style", "style_regex", "120").is_err());
assert!(opts.set_raw("port-name-suffix", "suffixes", "\"_i\"").is_err());
assert!(opts.set_raw("typedef-structs-unions", "allow_anonymous_nested", "yes").is_err());
let error = opts
.set("line-length", "length", OptionValue::Str("120".to_string()))
.err()
.unwrap_or_default();
assert!(error.contains("expects an integer, found a string"), "{error}");
}
#[test]
fn an_out_of_range_integer_is_refused() {
let mut opts = options();
let error = opts.set_raw("line-length", "length", "10").err().unwrap_or_default();
assert!(error.contains("must be between"), "{error}");
assert!(opts.set_raw("line-length", "length", "40").is_ok());
}
/// An escape this engine does not implement is refused when the option
/// is read, not read as a literal — the difference between an error a
/// user can see and a naming rule that quietly judges the wrong names
/// (QA, 2026-09-04).
#[test]
fn an_unsupported_escape_never_becomes_a_literal() {
let mut opts = options();
for pattern in ["\"\\bword\\b\"", "\"(a)\\1\"", "\"\\p{L}+\""] {
let error = opts
.set_raw("signal-name-style", "style_regex", pattern)
.err()
.unwrap_or_else(|| panic!("{pattern} was accepted"));
assert!(error.contains("unsupported escape"), "{pattern}: {error}");
assert!(error.contains("style_regex"), "{pattern}: {error}");
}
// ... and the option keeps its default, so the rule still works.
assert_eq!(opts.str("signal-name-style", "style_regex"), "[a-z_0-9]+");
}
#[test]
fn an_invalid_pattern_is_refused_by_name() {
let mut opts = options();
let error =
opts.set_raw("signal-name-style", "style_regex", "\"[a-\"").err().unwrap_or_default();
assert!(error.contains("not a valid pattern"), "{error}");
let error = opts
.set(
"banned-declared-name-patterns",
"patterns",
OptionValue::List(vec!["(ok".to_string()]),
)
.err()
.unwrap_or_default();
assert!(error.contains("not a valid pattern"), "{error}");
}
#[test]
fn a_style_word_outside_the_vocabulary_is_refused() {
let mut opts = options();
assert!(opts
.set_raw("parameter-name-style", "parameter_style", "\"CamelCase|ALL_CAPS\"")
.is_ok());
assert!(opts.set_raw("parameter-name-style", "localparam_style", "\"CamelCase\"").is_ok());
let error = opts
.set_raw("parameter-name-style", "parameter_style", "\"snake_case\"")
.err()
.unwrap_or_default();
assert!(error.contains("is not one of"), "{error}");
let error = opts
.set_raw("parameter-name-style", "parameter_style", "\"CamelCase|\"")
.err()
.unwrap_or_default();
assert!(error.contains("empty word"), "{error}");
}
#[test]
fn a_refused_value_leaves_the_previous_one_standing() {
let mut opts = options();
opts.set_raw("line-length", "length", "120").expect("accepted");
assert!(opts.set_raw("line-length", "length", "2").is_err());
assert_eq!(opts.int("line-length", "length"), 120);
}
/// Key by key: an overlay replaces the keys it names and leaves the
/// rest of the base standing.
#[test]
fn an_overlay_replaces_one_key_at_a_time() {
let mut base = options();
base.set_raw("line-length", "length", "120").expect("accepted");
base.set_raw("generate-label-prefix", "prefix", "[\"blk_\"]").expect("accepted");
let mut top = options();
top.set_raw("line-length", "length", "140").expect("accepted");
base.overlay(&top);
assert_eq!(base.int("line-length", "length"), 140, "the overlay wins");
assert_eq!(
base.list("generate-label-prefix", "prefix"),
vec!["blk_".to_string()],
"and the key it did not name survives"
);
// An empty overlay changes nothing.
base.overlay(&options());
assert_eq!(base.int("line-length", "length"), 140);
}
#[test]
fn defaults_are_written_the_way_a_user_would_type_them() {
assert_eq!(OptionDefault::Bool(true).as_written(), "true");
assert_eq!(OptionDefault::Int(100).as_written(), "100");
assert_eq!(OptionDefault::Str("[a-z]+").as_written(), "\"[a-z]+\"");
assert_eq!(OptionDefault::List(&["g_", "gen_"]).as_written(), "[\"g_\", \"gen_\"]");
assert_eq!(OptionDefault::List(&[]).as_written(), "[]");
}
}
+105
View File
@@ -0,0 +1,105 @@
//! What a preprocessor token says: the name a macro invocation calls, and the
//! word and operand a compiler directive carries.
//!
//! The lexer keeps both shapes as single tokens — a macro invocation
//! (`` `uvm_info("A", "B", UVM_LOW) ``) is one `Ident` whose text starts with
//! a backtick and swallows its balanced arguments, and a directive
//! (`` `ifdef FOO ``) is one `Directive` running to the end of its (possibly
//! continued) line. Four rules read those texts; reading them in one place is
//! what stops the four from disagreeing about where a name starts and ends.
use vlog_parser::token::{Token, TokenKind};
/// The macro this token invokes, without its backtick or arguments, or `None`
/// for a token that is not a macro invocation.
pub(crate) fn macro_name(token: &Token) -> Option<&str> {
if token.kind != TokenKind::Ident {
return None;
}
let rest = token.text.strip_prefix('`')?;
let end = rest.find(|c: char| !is_name_char(c)).unwrap_or(rest.len());
match end {
0 => None,
_ => Some(&rest[..end]),
}
}
/// The keyword of a compiler directive (`ifdef`, `endif`, `define`), or `None`
/// for a token that is not one.
pub(crate) fn directive_word(token: &Token) -> Option<&str> {
if token.kind != TokenKind::Directive {
return None;
}
let rest = token.text.strip_prefix('`')?;
let end = rest.find(|c: char| !is_name_char(c)).unwrap_or(rest.len());
match end {
0 => None,
_ => Some(&rest[..end]),
}
}
/// The name a directive names — the `FOO` of `` `ifdef FOO `` — or `None` when
/// it names nothing.
pub(crate) fn directive_operand(token: &Token) -> Option<&str> {
let word = directive_word(token)?;
let rest = token.text.get(1 + word.len()..)?.trim_start();
let end = rest.find(|c: char| !is_name_char(c)).unwrap_or(rest.len());
match end {
0 => None,
_ => Some(&rest[..end]),
}
}
/// The characters an identifier is made of, matching the lexer's own rule.
fn is_name_char(c: char) -> bool {
c == '_' || c == '$' || c.is_ascii_alphanumeric()
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::tokenize;
fn tokens(src: &str) -> Vec<Token> {
tokenize(src).expect("lexes")
}
#[test]
fn a_macro_invocation_gives_its_name() {
let toks = tokens("module m;\n initial `uvm_info(\"A\", \"B\", UVM_LOW);\nendmodule\n");
let names: Vec<&str> = toks.iter().filter_map(macro_name).collect();
assert_eq!(names, vec!["uvm_info"]);
}
#[test]
fn a_macro_without_arguments_gives_its_name_too() {
let toks = tokens("module m;\n `ASSERT_INIT\nendmodule\n");
assert_eq!(toks.iter().filter_map(macro_name).collect::<Vec<_>>(), vec!["ASSERT_INIT"]);
}
#[test]
fn an_ordinary_identifier_is_not_a_macro() {
let toks = tokens("module m;\n wire uvm_info;\nendmodule\n");
assert!(toks.iter().filter_map(macro_name).next().is_none());
}
#[test]
fn a_directive_gives_its_word_and_operand() {
let toks = tokens("`ifdef FOO\n`endif\n`define BAR 1\nmodule m;\nendmodule\n");
let words: Vec<&str> = toks.iter().filter_map(directive_word).collect();
assert_eq!(words, vec!["ifdef", "endif", "define"]);
let operands: Vec<Option<&str>> =
toks.iter().filter(|t| t.kind == TokenKind::Directive).map(directive_operand).collect();
assert_eq!(operands, vec![Some("FOO"), None, Some("BAR")]);
}
#[test]
fn a_directive_is_not_a_macro_invocation_and_the_other_way_round() {
let toks = tokens("`ifdef FOO\nmodule m;\n `ASSERT\nendmodule\n`endif\n");
assert_eq!(toks.iter().filter_map(macro_name).collect::<Vec<_>>(), vec!["ASSERT"]);
assert!(toks
.iter()
.filter(|t| t.kind == TokenKind::Ident)
.all(|t| directive_word(t).is_none()));
}
}
+716
View File
@@ -0,0 +1,716 @@
//! The small regular-expression engine the naming options are spelled with.
//!
//! Verible spells every naming convention as an RE2 pattern, and §34's
//! `style_regex` options are the same patterns typed by the same users, so
//! lucisv has to read them. What it does **not** need is RE2: the patterns
//! that appear in a style guide are character classes, alternation and the
//! three postfix repeats, which is one small engine — and this crate's
//! dependency list (`vlog_parser` + std) is worth more than the syntax nobody
//! writes here.
//!
//! # The supported subset
//!
//! - literals, and `.` for any character except a newline;
//! - `[...]` classes, with `^` negation, `a-z` ranges, a leading `]` or a
//! trailing `-` as a literal, and the `\d`/`\w`/`\s` shorthands inside;
//! - the escapes `\d \D \w \W \s \S` (classes), `\n \t \r` (control
//! characters) and `\<punctuation>` (that character, literally);
//! - groups `( ... )`, alternation `|`, and the postfix `*`, `+`, `?`;
//! - a `^` at the very start and a `$` at the very end, accepted and ignored
//! because the match is **anchored at both ends** anyway: a name matches
//! its style when the whole name matches the pattern, which is how Verible
//! reads its own.
//!
//! **Everything else is refused when the option is read, by name**: counted
//! repetition (`{2,3}`), lookaround (`(?=...)`), and every escape not in the
//! list above — a backreference (`\1`), a word boundary (`\b`), `\A`, `\z`,
//! `\p{...}`, `\x41`. Refusing is the whole point: an unsupported escape
//! treated as a literal would quietly accuse or excuse the wrong names, which
//! is worse than an error the user can read (QA, 2026-09-04).
//!
//! # Why it cannot hang
//!
//! The matcher is a **Thompson NFA simulation** (a Pike VM without capture
//! groups): the pattern is compiled to a small instruction program, and the
//! set of live program counters is advanced one character at a time, each
//! state entered at most once per character. Matching is therefore
//! `O(pattern × name)` **by construction**, whatever shape the pattern has.
//! The backtracking matcher this replaced was exponential on an ambiguous
//! repeat — QA measured `(a*)*b` against a 30-character name at 20.6 s and a
//! guard kill on the shipped binary (2026-09-04), which a user could
//! configure into every future lint run and into every keystroke of an editor
//! session.
/// One compiled pattern, matched whole against a name.
pub(crate) struct Regex {
prog: Vec<Inst>,
}
/// One instruction of the compiled program.
///
/// `Split` and `Jump` are the only control flow, and the only instructions
/// that consume no input; everything else advances one character.
#[derive(Debug, Clone)]
enum Inst {
/// Match this character exactly.
Char(char),
/// Match any character except a newline (`.`).
Any,
/// Match any character of this set.
Class(Class),
/// Continue at **both** targets — the alternation and repeat primitive.
Split(usize, usize),
/// Continue at this target.
Jump(usize),
/// The whole pattern matched, if the input is also finished.
Match,
}
/// A set of characters: ranges, plus an optional negation.
#[derive(Debug, Clone)]
struct Class {
ranges: Vec<(char, char)>,
negated: bool,
}
impl Class {
fn contains(&self, c: char) -> bool {
let hit = self.ranges.iter().any(|(lo, hi)| *lo <= c && c <= *hi);
hit != self.negated
}
}
/// The syntax tree the parser builds and the compiler walks.
enum Node {
/// Matches the empty string.
Empty,
/// One literal character.
Char(char),
/// `.` — any character except a newline.
Any,
/// One `[...]` class, or one of the `\d`-style shorthands.
Class(Class),
/// A sequence, matched left to right.
Concat(Vec<Node>),
/// Alternatives.
Alt(Vec<Node>),
/// A repeated node: `*`, `+` or `?`.
Repeat { node: Box<Node>, kind: RepeatKind },
}
/// Which postfix repeat was written.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RepeatKind {
/// `*` — zero or more.
Star,
/// `+` — one or more.
Plus,
/// `?` — zero or one.
Question,
}
impl Regex {
/// Compiles `pattern`, or says what is wrong with it.
pub(crate) fn compile(pattern: &str) -> Result<Regex, String> {
let chars: Vec<char> = pattern.chars().collect();
let mut parser = Parser { chars, at: 0 };
// `^ ... $` is how the same convention is often written down; the
// match is anchored either way, so the anchors are accepted and
// dropped rather than rejected as unsupported.
if parser.chars.first() == Some(&'^') {
parser.at = 1;
}
if parser.chars.last() == Some(&'$') && parser.chars.len() > parser.at && !escaped(&parser)
{
parser.chars.pop();
}
let root = parser.alternation()?;
if let Some(left) = parser.chars.get(parser.at) {
return Err(match left {
')' => "unmatched `)`".to_string(),
c => format!("unexpected `{c}`"),
});
}
let mut prog = Vec::new();
emit(&root, &mut prog);
prog.push(Inst::Match);
Ok(Regex { prog })
}
/// Whether the **whole** of `text` matches the pattern.
///
/// One pass over the characters, carrying the set of live program
/// counters: every state is entered at most once per character, so the
/// cost is `O(prog × text)` however ambiguous the pattern is.
pub(crate) fn is_match(&self, text: &str) -> bool {
let mut current: Vec<usize> = Vec::with_capacity(self.prog.len());
let mut next: Vec<usize> = Vec::with_capacity(self.prog.len());
let mut on_current = vec![false; self.prog.len()];
let mut on_next = vec![false; self.prog.len()];
self.add(0, &mut current, &mut on_current);
for c in text.chars() {
next.clear();
on_next.iter_mut().for_each(|seen| *seen = false);
for &pc in &current {
let takes = match &self.prog[pc] {
Inst::Char(want) => *want == c,
Inst::Any => c != '\n',
Inst::Class(class) => class.contains(c),
// `Match` mid-input is a pattern that ended before the
// name did, which a whole-name match refuses.
Inst::Match | Inst::Split(..) | Inst::Jump(_) => false,
};
if takes {
self.add(pc + 1, &mut next, &mut on_next);
}
}
std::mem::swap(&mut current, &mut next);
std::mem::swap(&mut on_current, &mut on_next);
if current.is_empty() {
return false;
}
}
current.iter().any(|pc| matches!(self.prog[*pc], Inst::Match))
}
/// Adds a thread at `pc`, following the instructions that consume no
/// input. `seen` keeps each state to one visit per character, which is
/// what bounds the work — and what makes a loop of empty matches
/// terminate instead of spinning.
fn add(&self, pc: usize, list: &mut Vec<usize>, seen: &mut [bool]) {
if seen.get(pc).copied().unwrap_or(true) {
return;
}
seen[pc] = true;
match self.prog[pc] {
Inst::Jump(to) => self.add(to, list, seen),
Inst::Split(a, b) => {
self.add(a, list, seen);
self.add(b, list, seen);
}
_ => list.push(pc),
}
}
}
/// Compiles one node onto the end of `prog`.
fn emit(node: &Node, prog: &mut Vec<Inst>) {
match node {
Node::Empty => {}
Node::Char(c) => prog.push(Inst::Char(*c)),
Node::Any => prog.push(Inst::Any),
Node::Class(class) => prog.push(Inst::Class(class.clone())),
Node::Concat(parts) => parts.iter().for_each(|part| emit(part, prog)),
Node::Alt(branches) => emit_alt(branches, prog),
Node::Repeat { node, kind } => emit_repeat(node, *kind, prog),
}
}
/// `split L1, L2; L1: first; jmp end; L2: rest…; end:`
fn emit_alt(branches: &[Node], prog: &mut Vec<Inst>) {
let Some((first, rest)) = branches.split_first() else { return };
if rest.is_empty() {
emit(first, prog);
return;
}
let split = prog.len();
prog.push(Inst::Split(0, 0)); // patched below
emit(first, prog);
let jump = prog.len();
prog.push(Inst::Jump(0)); // patched below
let second = prog.len();
emit_alt(rest, prog);
let end = prog.len();
prog[split] = Inst::Split(split + 1, second);
prog[jump] = Inst::Jump(end);
}
/// The three postfix repeats, each as a split around the body.
fn emit_repeat(node: &Node, kind: RepeatKind, prog: &mut Vec<Inst>) {
match kind {
// L: split body, end; body: … ; jmp L; end:
RepeatKind::Star => {
let split = prog.len();
prog.push(Inst::Split(0, 0));
emit(node, prog);
prog.push(Inst::Jump(split));
let end = prog.len();
prog[split] = Inst::Split(split + 1, end);
}
// body: … ; split body, end; end:
RepeatKind::Plus => {
let body = prog.len();
emit(node, prog);
let split = prog.len();
prog.push(Inst::Split(body, split + 1));
}
// split body, end; body: … ; end:
RepeatKind::Question => {
let split = prog.len();
prog.push(Inst::Split(0, 0));
emit(node, prog);
let end = prog.len();
prog[split] = Inst::Split(split + 1, end);
}
}
}
/// Whether the pattern's last character is escaped — so a trailing `\$` is
/// the literal dollar it was written as and not the anchor.
fn escaped(parser: &Parser) -> bool {
let before = parser.chars.len().saturating_sub(1);
parser.chars[..before].iter().rev().take_while(|c| **c == '\\').count() % 2 == 1
}
/// The escapes this engine understands, for the message a refusal prints.
const SUPPORTED_ESCAPES: &str =
"\\d \\D \\w \\W \\s \\S \\n \\t \\r, and \\<punctuation> for that character";
/// The recursive-descent parser for the subset.
struct Parser {
chars: Vec<char>,
at: usize,
}
impl Parser {
fn peek(&self) -> Option<char> {
self.chars.get(self.at).copied()
}
fn bump(&mut self) -> Option<char> {
let c = self.peek();
self.at += c.is_some() as usize;
c
}
/// `branch ( '|' branch )*`
fn alternation(&mut self) -> Result<Node, String> {
let mut branches = vec![self.concatenation()?];
while self.peek() == Some('|') {
self.at += 1;
branches.push(self.concatenation()?);
}
Ok(if branches.len() == 1 {
branches.pop().unwrap_or(Node::Empty)
} else {
Node::Alt(branches)
})
}
/// `repeated*`, stopping at `|` or the group's `)`.
fn concatenation(&mut self) -> Result<Node, String> {
let mut parts = Vec::new();
while !matches!(self.peek(), None | Some('|') | Some(')')) {
parts.push(self.repeated()?);
}
Ok(match parts.len() {
0 => Node::Empty,
1 => parts.pop().unwrap_or(Node::Empty),
_ => Node::Concat(parts),
})
}
/// One atom with its postfix `*`, `+` or `?`.
fn repeated(&mut self) -> Result<Node, String> {
let atom = self.atom()?;
let kind = match self.peek() {
Some('*') => RepeatKind::Star,
Some('+') => RepeatKind::Plus,
Some('?') => RepeatKind::Question,
_ => return Ok(atom),
};
self.at += 1;
if matches!(self.peek(), Some('*' | '+' | '?')) {
return Err(format!("`{}` cannot follow a repeat", self.peek().unwrap_or('?')));
}
Ok(Node::Repeat { node: Box::new(atom), kind })
}
fn atom(&mut self) -> Result<Node, String> {
match self.bump() {
Some('(') => {
// `(?...)` is lookaround or a flag group — RE2 syntax this
// engine does not implement, and refusing it by name is what
// stops it being read as a literal `?`.
if self.peek() == Some('?') {
return Err(
"`(?...)` groups (lookaround, flags, non-capturing) are unsupported in \
lucisv patterns"
.to_string(),
);
}
let inner = self.alternation()?;
if self.bump() != Some(')') {
return Err("unmatched `(`".to_string());
}
Ok(inner)
}
Some('[') => self.class(),
Some('.') => Ok(Node::Any),
Some('\\') => self.escape(),
Some(c @ ('*' | '+' | '?')) => Err(format!("`{c}` has nothing to repeat")),
Some(c @ ('{' | '}')) => {
Err(format!("`{c}` (counted repetition) is unsupported in lucisv patterns"))
}
Some(c @ ('^' | '$')) => {
Err(format!("`{c}` is only accepted at the start or end of a pattern"))
}
Some(')') => Err("unmatched `)`".to_string()),
Some(c) => Ok(Node::Char(c)),
None => Err("pattern ends where a character was expected".to_string()),
}
}
/// `\d`, `\w`, `\s`, their negations, the three control characters, or a
/// punctuation character escaped to itself.
///
/// **Anything else is an error.** A letter or digit escape this engine
/// does not implement — `\b`, `\A`, `\1`, `\p` — is a pattern from
/// another dialect that would mean something quite different if it were
/// read as a literal, so it is named and refused.
fn escape(&mut self) -> Result<Node, String> {
let c = self.bump().ok_or("a `\\` at the end of the pattern escapes nothing")?;
Ok(match c {
'd' => Node::Class(digits(false)),
'D' => Node::Class(digits(true)),
'w' => Node::Class(word(false)),
'W' => Node::Class(word(true)),
's' => Node::Class(space(false)),
'S' => Node::Class(space(true)),
'n' => Node::Char('\n'),
't' => Node::Char('\t'),
'r' => Node::Char('\r'),
other if other.is_alphanumeric() => return Err(unsupported_escape(other)),
other => Node::Char(other),
})
}
/// A `[...]` class, the `[` already consumed.
fn class(&mut self) -> Result<Node, String> {
let negated = self.peek() == Some('^');
self.at += negated as usize;
let mut ranges: Vec<(char, char)> = Vec::new();
// A `]` written first is a literal `]`, as in every regex dialect.
let mut first = true;
loop {
let c = match self.bump() {
Some(']') if !first => break,
Some(c) => c,
None => return Err("unmatched `[`".to_string()),
};
first = false;
let lo = if c == '\\' { self.class_escape(&mut ranges)? } else { Some(c) };
let Some(lo) = lo else { continue };
// `a-z`, but a `-` before the closing `]` is a literal `-`.
if self.peek() == Some('-') && self.chars.get(self.at + 1) != Some(&']') {
self.at += 1;
let hi = match self.bump() {
Some('\\') => self.class_literal_escape()?,
Some(c) => c,
None => return Err("unmatched `[`".to_string()),
};
if hi < lo {
return Err(format!("class range `{lo}-{hi}` runs backwards"));
}
ranges.push((lo, hi));
} else {
ranges.push((lo, lo));
}
}
if ranges.is_empty() {
return Err("empty character class".to_string());
}
Ok(Node::Class(Class { ranges, negated }))
}
/// An escape inside a class: a shorthand adds its ranges and yields
/// nothing, an escaped punctuation or control character yields itself,
/// and anything else is refused by name.
///
/// The **negated** shorthands (`\D`, `\W`, `\S`) are refused inside a
/// class rather than accepted: a class is one set of ranges with one
/// negation flag, and mixing a complemented set into it would need set
/// arithmetic this engine does not do. Refusing says so; accepting would
/// have to guess.
fn class_escape(&mut self, ranges: &mut Vec<(char, char)>) -> Result<Option<char>, String> {
let c = self.bump().ok_or("a `\\` at the end of a class escapes nothing")?;
let shorthand = match c {
'd' => Some(digits(false)),
'w' => Some(word(false)),
's' => Some(space(false)),
_ => None,
};
if let Some(class) = shorthand {
ranges.extend(class.ranges);
return Ok(None);
}
Ok(Some(match c {
'n' => '\n',
't' => '\t',
'r' => '\r',
'D' | 'W' | 'S' => {
return Err(format!(
"`\\{c}` is unsupported inside a `[...]` class; write it outside one"
))
}
other if other.is_alphanumeric() => return Err(unsupported_escape(other)),
other => other,
}))
}
/// The far end of a class range, which must be one character — a
/// shorthand there (`[a-\d]`) is meaningless.
fn class_literal_escape(&mut self) -> Result<char, String> {
let c = self.bump().ok_or("a `\\` at the end of a class escapes nothing")?;
Ok(match c {
'n' => '\n',
't' => '\t',
'r' => '\r',
other if other.is_alphanumeric() => return Err(unsupported_escape(other)),
other => other,
})
}
}
/// The one message an unimplemented escape gets, wherever it was written.
fn unsupported_escape(c: char) -> String {
format!("unsupported escape `\\{c}` (supported: {SUPPORTED_ESCAPES})")
}
fn digits(negated: bool) -> Class {
Class { ranges: vec![('0', '9')], negated }
}
fn word(negated: bool) -> Class {
Class { ranges: vec![('a', 'z'), ('A', 'Z'), ('0', '9'), ('_', '_')], negated }
}
fn space(negated: bool) -> Class {
Class { ranges: vec![(' ', ' '), ('\t', '\t'), ('\n', '\n'), ('\r', '\r')], negated }
}
#[cfg(test)]
mod tests {
use super::*;
fn hit(pattern: &str, text: &str) -> bool {
Regex::compile(pattern).unwrap_or_else(|e| panic!("{pattern}: {e}")).is_match(text)
}
#[test]
fn the_patterns_the_naming_options_ship_with_work() {
// Every default this round introduces, against real names.
assert!(hit("[a-z_0-9]+", "wr_en"));
assert!(!hit("[a-z_0-9]+", "wrEn"));
assert!(hit("[a-z_0-9]+(_if)", "bus_if"));
assert!(!hit("[a-z_0-9]+(_if)", "bus"));
assert!(hit("[A-Z_0-9]+", "MY_MACRO"));
assert!(!hit("[A-Z_0-9]+", "my_macro"));
assert!(hit("([a-z0-9]+_)+c", "addr_range_c"));
assert!(!hit("([a-z0-9]+_)+c", "addr_range"));
assert!(hit("[a-z_0-9]+(_t|_e)", "state_e"));
assert!(hit("[a-z_0-9]+(_t|_e)", "word_t"));
assert!(!hit("[a-z_0-9]+(_t|_e)", "word"));
}
/// The probe table, every verdict checked against Python's
/// `re.fullmatch` (QA's 46 probes of 2026-09-04 plus this round's own).
/// It is written down rather than described so a change to the engine
/// has to disagree with CPython in public.
#[test]
fn every_probe_agrees_with_python_re_fullmatch() {
// (pattern, text, re.fullmatch(pattern, text) is not None)
let probes: &[(&str, &str, bool)] = &[
// literals and anchoring
("abc", "abc", true),
("abc", "abcd", false),
("abc", "xabcx", false),
("abc", "ab", false),
("", "", true),
("", "a", false),
// `.`
("a.c", "abc", true),
("a.c", "a_c", true),
("a.c", "ac", false),
(".*", "anything", true),
("a.b", "a\nb", false),
// classes
("[a-z]+", "abc", true),
("[a-z]+", "abC", false),
("[a-z_0-9]+", "a_1", true),
("[^0-9]+", "abc", true),
("[^0-9]+", "ab1", false),
("[a-]+", "a-a", true),
("[]a]+", "]a", true),
("[\\]]", "]", true),
("[a-c-e]+", "a-e", true),
("[A-Za-z][A-Za-z0-9]*", "Ab9", true),
("[A-Za-z][A-Za-z0-9]*", "9Ab", false),
// shorthands
("\\d+", "42", true),
("\\d+", "4a", false),
("\\D+", "abc", true),
("\\D+", "ab1", false),
("\\w+", "a_1", true),
("\\w+", "a-1", false),
("\\W+", "-", true),
("\\W+", "a", false),
("\\s+", " \t", true),
("\\s+", " a", false),
("\\S+", "abc", true),
("[\\d_]+", "4_2", true),
("[\\w]+", "a_1", true),
("a\\.b", "a.b", true),
("a\\.b", "axb", false),
// groups, alternation, nesting
("(a|b)(c|d)", "ad", true),
("(a|b)(c|d)", "ac", true),
("(a|b)(c|d)", "bb", false),
("(ab|a)+b", "aab", true),
("((a|b)+_)?x", "abab_x", true),
("((a|b)+_)?x", "x", true),
("(a|)b", "b", true),
("(|a)b", "ab", true),
("(ab)+", "ababab", true),
("(ab)+", "ababa", false),
// repeats, including the ambiguous shapes that used to blow up
("a*ab", "aaab", true),
("a+b", "b", false),
("a?b", "b", true),
("(a?)*b", "b", true),
("(a*)*b", "aaab", true),
("(a*)*b", "aaaa", false),
("(a|aa)*b", "aaaab", true),
("(a|aa)*b", "aaaa", false),
("(.*)*x", "abcx", true),
("(.*)*x", "abc", false),
("((a*)*)*b", "aab", true),
("(a+)+b", "aaab", true),
("(a+)+b", "aaa", false),
// the shipped defaults, both ways
("[a-z][a-z_0-9]*(_t|_e)", "state_e", true),
("[a-z][a-z_0-9]*(_t|_e)", "_state_e", false),
("[a-z][a-z_0-9]*_t", "word_t", true),
("[a-z][a-z_0-9]*_t", "wordt", false),
("[a-z_0-9]+(_if)", "clk_rst_if", true),
("[a-z_0-9]+(_if)", "bus_intf", false),
("([a-z0-9]+_)+c", "addr_range_c", true),
("([a-z0-9]+_)+c", "c", false),
("[A-Z_0-9]+", "W2", true),
("[a-z][a-z_0-9]*", "fifo2_ctrl", true),
("[a-z][a-z_0-9]*", "Fifo2Ctrl", false),
];
for (pattern, text, expected) in probes {
assert_eq!(hit(pattern, text), *expected, "{pattern:?} vs {text:?}");
}
assert!(probes.len() >= 60, "the table is the pin; keep it wide");
}
#[test]
fn the_match_is_anchored_at_both_ends() {
assert!(!hit("[a-z]+", "abc1"));
assert!(!hit("bc", "abc"));
assert!(hit("^[a-z]+$", "abc"), "explicit anchors are accepted and ignored");
assert!(hit("a\\$", "a$"), "an escaped `$` at the end is a literal");
}
/// The HIGH finding of 2026-09-04: an ambiguous repeat was exponential
/// under the old backtracking matcher (30 characters took 20.6 s and hit
/// the runaway guard). The NFA simulation is linear by construction, so
/// the same shapes finish on a 200-character name in microseconds.
#[test]
fn an_ambiguous_repeat_is_linear_not_exponential() {
let long = "a".repeat(200);
let start = std::time::Instant::now();
for pattern in ["(a*)*b", "(a|aa)*b", "(.*)*x", "((a*)*)*b", "(a+)+b", "(a?)*b"] {
assert!(!hit(pattern, &long), "{pattern} must not match a name of only `a`s");
}
let elapsed = start.elapsed();
assert!(
elapsed < std::time::Duration::from_millis(500),
"six ambiguous patterns over 200 characters took {elapsed:?}; \
the matcher is backtracking again"
);
}
/// An unsupported escape is refused **by name**, never read as a
/// literal — the second HIGH finding of 2026-09-04. QA's two cases are
/// the first two rows.
#[test]
fn an_unsupported_escape_is_refused_by_name() {
for pattern in [
"(a)\\1", // a backreference: must not match `a1`
"\\bword\\b", // a word boundary: must not match `bwordb`
"\\B",
"\\A",
"\\z",
"\\Z",
"\\p{L}",
"\\x41",
"\\u0041",
"\\Q",
"\\9",
"\\0",
"\\f",
"\\v",
"[\\b]",
"[a\\1]",
"[a-\\d]",
"[\\D]",
"[\\S]",
"[\\W]",
] {
let error = Regex::compile(pattern).err().unwrap_or_else(|| {
panic!("{pattern} compiled; an unimplemented escape must be refused")
});
assert!(
error.contains("unsupported") || error.contains("unsupported inside"),
"{pattern}: {error}"
);
}
// The message names the escape and what is available instead.
let error = Regex::compile("\\bword\\b").err().unwrap_or_default();
assert!(error.contains("`\\b`"), "{error}");
assert!(error.contains("\\d"), "{error}");
// And the supported ones still compile.
for pattern in [
"\\d", "\\D", "\\w", "\\W", "\\s", "\\S", "\\n", "\\t", "\\r", "\\.", "\\\\", "\\[",
"\\]", "\\(", "\\)", "\\|", "\\+", "\\*", "\\?", "\\-", "\\{", "\\}", "\\^", "\\$",
"[\\d]", "[\\w]", "[\\s]", "[\\-]",
] {
assert!(Regex::compile(pattern).is_ok(), "{pattern} must compile");
}
}
#[test]
fn a_bad_pattern_says_what_is_wrong() {
for (pattern, wanted) in [
("(a", "unmatched `("),
("a)", "unmatched `)`"),
("[a", "unmatched `["),
("[]", "unmatched `["),
("[^]", "unmatched `["),
("*a", "nothing to repeat"),
("a**", "cannot follow a repeat"),
("a{2}", "counted repetition"),
("a{2,3}", "counted repetition"),
("(?=a)b", "(?...)"),
("(?:a)b", "(?...)"),
("a$b", "start or end"),
("[z-a]", "runs backwards"),
("a\\", "escapes nothing"),
] {
let error = Regex::compile(pattern).err().unwrap_or_default();
assert!(error.contains(wanted), "{pattern}: {error}");
}
}
#[test]
fn unicode_passes_through_as_literals() {
assert!(hit("naïve", "naïve"));
assert!(!hit("[a-z]+", "naïve"));
// A non-ASCII letter escape is still an escape nobody implements.
assert!(Regex::compile("\\é").is_err());
}
}
+267 -11
View File
@@ -1,7 +1,9 @@
//! The rule trait and the table of rules that exist.
use crate::context::LintContext;
use crate::options::OptionSpec;
use crate::rules;
use crate::severity::Severity;
use crate::violation::{Applicability, Violation};
/// One lint rule.
@@ -17,6 +19,14 @@ pub trait Rule: Sync {
/// One line, imperative, no trailing period.
fn summary(&self) -> &'static str;
/// How bad this rule's findings are.
///
/// Deliberately without a default: a class is a claim about what a finding
/// means to the user, and a rule that inherited one silently would be
/// making that claim by accident. The reason for the class chosen belongs
/// in [`Rule::doc`].
fn severity(&self) -> Severity;
/// Why the rule exists — the style-guide rationale, in prose.
fn doc(&self) -> &'static str;
@@ -50,6 +60,18 @@ pub trait Rule: Sync {
None
}
/// What a user may configure about this rule, or nothing.
///
/// The keys are Verible's wherever it has the same option, so a project
/// migrating a `.rules.verible` file types the same words. A rule reads
/// one through [`LintContext`], never from a run's settings directly, and
/// always gets a value: the spec's default is the fallback, so there is no
/// "unset" case in any rule. See
/// `docs/features/linter-expansion-2/README.md`.
fn options(&self) -> &'static [OptionSpec] {
&[]
}
/// Everything this rule finds in one file.
fn check(&self, ctx: &LintContext) -> Vec<Violation>;
}
@@ -57,22 +79,79 @@ pub trait Rule: Sync {
/// Every rule that exists, in a stable order.
pub fn all_rules() -> Vec<&'static dyn Rule> {
vec![
&rules::always_comb::AlwaysComb,
&rules::always_comb_blocking::AlwaysCombBlocking,
&rules::always_ff_non_blocking::AlwaysFfNonBlocking,
&rules::banned_declared_name_patterns::BannedDeclaredNamePatterns,
&rules::case_missing_default::CaseMissingDefault,
&rules::constraint_name_style::ConstraintNameStyle,
&rules::create_object_name_match::CreateObjectNameMatch,
&rules::dff_name_style::DffNameStyle,
&rules::disable_statement::DisableStatement,
&rules::duplicate_declaration::DuplicateDeclaration,
&rules::empty_item::EmptyItem,
&rules::endif_comment::EndifComment,
&rules::enum_name_style::EnumNameStyle,
&rules::explicit_begin::ExplicitBegin,
&rules::explicit_function_lifetime::ExplicitFunctionLifetime,
&rules::explicit_function_task_parameter_type::ExplicitFunctionTaskParameterType,
&rules::explicit_parameter_storage_type::ExplicitParameterStorageType,
&rules::explicit_task_lifetime::ExplicitTaskLifetime,
&rules::forbid_consecutive_null_statements::ForbidConsecutiveNullStatements,
&rules::forbid_defparam::ForbidDefparam,
&rules::forbid_line_continuations::ForbidLineContinuations,
&rules::forbid_negative_array_dim::ForbidNegativeArrayDim,
&rules::forbidden_macro::ForbiddenMacro,
&rules::generate_label::GenerateLabel,
&rules::generate_label_prefix::GenerateLabelPrefix,
&rules::incomplete_assignment::IncompleteAssignment,
&rules::instance_shadowing::InstanceShadowing,
&rules::interface_name_style::InterfaceNameStyle,
&rules::invalid_system_task_function::InvalidSystemTaskFunction,
&rules::legacy_generate_region::LegacyGenerateRegion,
&rules::legacy_genvar_declaration::LegacyGenvarDeclaration,
&rules::line_length::LineLength,
&rules::macro_name_style::MacroNameStyle,
&rules::macro_string_concatenation::MacroStringConcatenation,
&rules::mismatched_labels::MismatchedLabels,
&rules::module_begin_block::ModuleBeginBlock,
&rules::module_filename::ModuleFilename,
&rules::module_name_style::ModuleNameStyle,
&rules::module_parameter::ModuleParameter,
&rules::module_port::ModulePort,
&rules::multiply_driven::MultiplyDriven,
&rules::no_tabs::NoTabs,
&rules::no_trailing_whitespace::NoTrailingWhitespace,
&rules::numeric_format_string_style::NumericFormatStringStyle,
&rules::one_module_per_file::OneModulePerFile,
&rules::package_filename::PackageFilename,
&rules::packed_dimensions_range_ordering::PackedDimensionsRangeOrdering,
&rules::parameter_name_style::ParameterNameStyle,
&rules::parameter_type_name_style::ParameterTypeNameStyle,
&rules::plusarg_assignment::PlusargAssignment,
&rules::port_name_suffix::PortNameSuffix,
&rules::positive_meaning_parameter_name::PositiveMeaningParameterName,
&rules::posix_eof::PosixEof,
&rules::proper_parameter_declaration::ProperParameterDeclaration,
&rules::signal_name_style::SignalNameStyle,
&rules::struct_union_name_style::StructUnionNameStyle,
&rules::suggest_parentheses::SuggestParentheses,
&rules::suspicious_semicolon::SuspiciousSemicolon,
&rules::truncated_numeric_literal::TruncatedNumericLiteral,
&rules::typedef_enums::TypedefEnums,
&rules::typedef_structs_unions::TypedefStructsUnions,
&rules::undeclared_identifier::UndeclaredIdentifier,
&rules::undersized_binary_literal::UndersizedBinaryLiteral,
&rules::undriven_net::UndrivenNet,
&rules::unknown_parameter::UnknownParameter,
&rules::unknown_port::UnknownPort,
&rules::unpacked_dimensions_range_ordering::UnpackedDimensionsRangeOrdering,
&rules::unused_import::UnusedImport,
&rules::unused_signal::UnusedSignal,
&rules::unused_waiver::UnusedWaiver,
&rules::uvm_macro_semicolon::UvmMacroSemicolon,
&rules::v2001_generate_begin::V2001GenerateBegin,
&rules::void_cast::VoidCast,
&rules::wire_reg_mixup::WireRegMixup,
]
}
@@ -112,10 +191,25 @@ pub fn rule_by_name(name: &str) -> Option<&'static dyn Rule> {
all_rules().into_iter().find(|rule| rule.name() == name)
}
/// The rules one `--select` / `--ignore` name stands for.
///
/// A rule name stands for itself; a **severity name** (`error`, `warning`,
/// `style`) stands for every rule of that class, so `--ignore style` is one
/// word for the whole family. `None` for a name that is neither, which is what
/// makes a typo a failed run rather than a silently empty selection.
pub fn rules_named(name: &str) -> Option<Vec<&'static dyn Rule>> {
if let Some(rule) = rule_by_name(name) {
return Some(vec![rule]);
}
let severity = Severity::from_name(name)?;
Some(all_rules().into_iter().filter(|rule| rule.severity() == severity).collect())
}
/// The rules a run should use: `select` replaces the default set (empty means
/// keep it), then `ignore` removes from whatever is left. An unknown name on
/// either list is an error rather than a silent no-op — a typo'd `--select`
/// that quietly ran everything would be worse than a failed run.
/// keep it), then `ignore` removes from whatever is left. Either list may name
/// a rule or a whole severity ([`rules_named`]). An unknown name on either
/// list is an error rather than a silent no-op — a typo'd `--select` that
/// quietly ran everything would be worse than a failed run.
///
/// `workspace` only reaches [`default_rules`]: an explicit `select` names the
/// rules it wants and gets them, oracle or no oracle, exactly as an explicit
@@ -128,25 +222,27 @@ pub fn select_rules(
let mut chosen = if select.is_empty() {
enabled_rules(workspace)
} else {
let mut chosen = Vec::new();
let mut chosen: Vec<&'static dyn Rule> = Vec::new();
for name in select {
let rule = rule_by_name(name).ok_or_else(|| unknown(name))?;
if !chosen.iter().any(|r: &&'static dyn Rule| r.name() == rule.name()) {
chosen.push(rule);
for rule in rules_named(name).ok_or_else(|| unknown(name))? {
if !chosen.iter().any(|r| r.name() == rule.name()) {
chosen.push(rule);
}
}
}
chosen
};
for name in ignore {
rule_by_name(name).ok_or_else(|| unknown(name))?;
chosen.retain(|rule| rule.name() != name);
let dropped = rules_named(name).ok_or_else(|| unknown(name))?;
chosen.retain(|rule| !dropped.iter().any(|d| d.name() == rule.name()));
}
Ok(chosen)
}
fn unknown(name: &str) -> String {
let known = all_rules().iter().map(|r| r.name()).collect::<Vec<_>>().join(", ");
format!("unknown rule: {name} (known rules: {known})")
let severities = Severity::ALL.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
format!("unknown rule: {name} (severities: {severities}; known rules: {known})")
}
#[cfg(test)]
@@ -211,7 +307,17 @@ mod tests {
let project: Vec<&str> = workspace_rules().iter().map(|r| r.name()).collect();
let added: Vec<&str> =
project.iter().copied().filter(|name| !alone.contains(name)).collect();
assert_eq!(added, vec!["multiply-driven", "undriven-net", "unused-signal"]);
assert_eq!(
added,
vec![
"multiply-driven",
"undeclared-identifier",
"undriven-net",
"unknown-parameter",
"unknown-port",
"unused-signal",
]
);
assert!(alone.iter().all(|name| project.contains(name)), "a workspace never removes one");
for rule in all_rules() {
assert_eq!(rule.needs_workspace(), added.contains(&rule.name()), "{}", rule.name());
@@ -283,6 +389,156 @@ mod tests {
assert!(message.contains("no-tabs"), "the error must list what is known: {message}");
}
/// Every rule states a class, and no rule name collides with a class
/// name — otherwise `--select error` would mean two things.
#[test]
fn every_rule_has_a_severity_and_no_name_shadows_a_class() {
for rule in all_rules() {
assert!(Severity::ALL.contains(&rule.severity()), "{}", rule.name());
assert!(
Severity::from_name(rule.name()).is_none(),
"{} shadows a severity word",
rule.name()
);
}
}
/// The assignments §33.0 wrote down for the seventeen rules that predate
/// severities. A rule moving class is a user-visible change, so it moves
/// here first.
#[test]
fn the_original_seventeen_keep_the_classes_they_were_given() {
let expected: &[(&str, Severity)] = &[
("multiply-driven", Severity::Error),
("wire-reg-mixup", Severity::Error),
("always-comb-blocking", Severity::Warning),
("always-ff-non-blocking", Severity::Warning),
("case-missing-default", Severity::Warning),
("undriven-net", Severity::Warning),
("unused-signal", Severity::Warning),
("empty-item", Severity::Style),
("enum-name-style", Severity::Style),
("explicit-parameter-storage-type", Severity::Style),
("module-filename", Severity::Style),
("module-name-style", Severity::Style),
("no-tabs", Severity::Style),
("no-trailing-whitespace", Severity::Style),
("parameter-name-style", Severity::Style),
("struct-union-name-style", Severity::Style),
("unused-waiver", Severity::Style),
];
for (name, severity) in expected {
let rule = rule_by_name(name).unwrap_or_else(|| panic!("{name} exists"));
assert_eq!(rule.severity(), *severity, "{name}");
}
}
#[test]
fn a_severity_name_stands_for_every_rule_of_that_class() {
for severity in Severity::ALL {
let named = rules_named(severity.as_str()).unwrap_or_default();
let expected: Vec<&str> = all_rules()
.into_iter()
.filter(|rule| rule.severity() == severity)
.map(|rule| rule.name())
.collect();
assert_eq!(named.iter().map(|r| r.name()).collect::<Vec<_>>(), expected);
assert!(!expected.is_empty(), "{severity:?} has no rules");
}
assert!(rules_named("no-tabs").is_some_and(|rules| rules.len() == 1));
assert!(rules_named("no-such-thing").is_none());
}
/// `--select style`, `--ignore warning`: the whole point of the words.
#[test]
fn select_and_ignore_accept_a_severity_wherever_a_rule_fits() {
let styled = select_rules(&["style".to_string()], &[], true).unwrap();
assert!(styled.iter().all(|rule| rule.severity() == Severity::Style));
assert!(styled.iter().any(|rule| rule.name() == "no-tabs"));
let quiet = select_rules(&[], &["style".to_string()], true).unwrap();
assert!(quiet.iter().all(|rule| rule.severity() != Severity::Style));
assert!(quiet.iter().any(|rule| rule.name() == "unused-signal"), "warnings survive");
// A severity and a rule name mix on one list, and the same rule named
// twice is still selected once.
let mixed =
select_rules(&["style".to_string(), "no-tabs".to_string()], &[], false).unwrap();
assert_eq!(mixed.iter().filter(|rule| rule.name() == "no-tabs").count(), 1);
// Ignoring a class removes it from an explicit selection too.
let none = select_rules(&["no-tabs".to_string()], &["style".to_string()], false).unwrap();
assert!(none.is_empty());
}
#[test]
fn the_unknown_name_error_names_the_severity_words_too() {
let message = select_rules(&["styles".to_string()], &[], false).err().unwrap_or_default();
assert!(message.contains("style"), "{message}");
assert!(message.contains("no-tabs"), "{message}");
}
/// Every option a rule declares is one a user could actually write down,
/// and one whose own default is acceptable to itself — a default outside
/// its range, or a pattern that does not compile, would be a rule nobody
/// could satisfy.
#[test]
fn every_declared_option_is_well_formed() {
use crate::options::{OptionKind, RuleOptions};
for rule in all_rules() {
let mut names: Vec<&str> = rule.options().iter().map(|spec| spec.name).collect();
let count = names.len();
names.sort_unstable();
names.dedup();
assert_eq!(names.len(), count, "{}: duplicate option names", rule.name());
for spec in rule.options() {
let where_ = format!("{}.{}", rule.name(), spec.name);
assert!(
spec.name.chars().all(|c| c.is_ascii_lowercase()
|| c.is_ascii_digit()
|| c == '_'
|| c == '-'),
"{where_}: option names are lower-case words",
);
assert!(spec.doc.len() > 10, "{where_}: doc too thin");
assert!(!spec.doc.ends_with('.'), "{where_}: doc ends in a period");
let mut options = RuleOptions::new();
options
.set(rule.name(), spec.name, spec.default.value())
.unwrap_or_else(|e| panic!("{where_}: its own default is refused: {e}"));
if let OptionKind::Int { min, max } = spec.kind {
assert!(min <= max, "{where_}: empty range");
}
}
}
}
/// The options §34 gave the four naming rules that predate them, spelled
/// as Verible spells the same options.
#[test]
fn the_naming_rules_take_the_options_verible_gives_them() {
let names = |rule: &str| {
rule_by_name(rule)
.unwrap_or_else(|| panic!("{rule} exists"))
.options()
.iter()
.map(|spec| spec.name)
.collect::<Vec<_>>()
};
assert_eq!(names("enum-name-style"), vec!["style_regex"]);
assert_eq!(names("struct-union-name-style"), vec!["style_regex"]);
assert_eq!(names("module-name-style"), vec!["style_regex"]);
assert_eq!(
names("parameter-name-style"),
vec![
"localparam_style",
"localparam_style_regex",
"parameter_style",
"parameter_style_regex"
]
);
}
#[test]
fn lookup_by_name_finds_every_rule_and_nothing_else() {
for rule in all_rules() {
+161 -19
View File
@@ -6,7 +6,10 @@
//! per rule. If a rule exists, it is in here; if its `doc` changes, so does
//! this.
use crate::options::OptionKind;
use crate::registry::all_rules;
use crate::severity::Severity;
use crate::Rule;
/// The whole rule reference as one markdown document.
pub fn rules_markdown() -> String {
@@ -15,6 +18,12 @@ pub fn rules_markdown() -> String {
out.push_str(
"Generated from the rule registry by `vlog_linter::rules_markdown` — \
do not edit by hand.\n\n\
Every rule is in one of three **severity** classes, and the class is \
a word `--select` and `--ignore` accept wherever a rule name fits \
(`--ignore style`, `--select error`). **error** is code that would \
very likely fail to compile, elaborate or synthesize; **warning** is \
code that compiles but very likely does not mean what it says; \
**style** is code that is correct and reads badly.\n\n\
A rule marked **on** runs for a plain `lucisv check`; the others need \
`--select <name>`. A rule marked **on (project)** runs by default \
only where lucisv can see the other files of the project — \
@@ -23,30 +32,78 @@ pub fn rules_markdown() -> String {
a stdin buffer it is off and must be selected. Any rule can be turned \
off with `--ignore <name>`, with `ignore` under `[lint]` in \
`lucisv.toml`, or waived in the source with `// lucisv: waive \
<name>`.\n\n",
<name>`.\n\n\
A rule with **options** is configured in a `[lint.<rule-name>]` \
table of a `lucisv.toml`, or from an editor with \
`lucisv.lint.options`; an option nobody sets reads the default \
listed with it. An unknown option name, a value of the wrong kind, \
an integer out of range and a pattern that does not compile are all \
refused, naming the file and the line.\n\n",
);
out.push_str("| Rule | Default | Fix |\n|---|---|---|\n");
out.push_str("| Rule | Severity | Default | Fix |\n|---|---|---|---|\n");
for rule in all_rules() {
out.push_str(&format!(
"| [`{name}`](#{name}) | {default} | {fix} |\n",
"| [`{name}`](#{name}) | {severity} | {default} | {fix} |\n",
name = rule.name(),
severity = rule.severity().as_str(),
default = default_word(rule),
fix = fix_word(rule),
));
}
out.push('\n');
for rule in all_rules() {
out.push_str(&format!("## {}\n\n", rule.name()));
out.push_str(&format!("{}.\n\n", capitalize(rule.summary())));
out.push_str(&format!("- Default: {}\n- Fix: {}\n\n", default_word(rule), fix_word(rule)));
out.push_str(rule.doc());
out.push_str("\n\n");
for severity in Severity::ALL {
out.push_str(&format!("# {} — {}\n\n", severity.as_str(), severity.describes()));
for rule in all_rules().into_iter().filter(|rule| rule.severity() == severity) {
out.push_str(&format!("## {}\n\n", rule.name()));
out.push_str(&format!("{}.\n\n", capitalize(rule.summary())));
out.push_str(&format!(
"- Severity: {}\n- Default: {}\n- Fix: {}\n\n",
severity.as_str(),
default_word(rule),
fix_word(rule),
));
out.push_str(rule.doc());
out.push_str("\n\n");
out.push_str(&options_table(rule));
}
}
out
}
/// A rule's options, as a small table under its prose — empty for a rule
/// that takes none, which is most of them.
fn options_table(rule: &dyn Rule) -> String {
if rule.options().is_empty() {
return String::new();
}
let mut out = String::from("| Option | Kind | Default | Meaning |\n|---|---|---|---|\n");
for spec in rule.options() {
out.push_str(&format!(
"| `{name}` | {kind} | `{default}` | {doc} |\n",
name = spec.name,
kind = kind_word(spec.kind),
default = spec.default.as_written(),
doc = spec.doc,
));
}
out.push('\n');
out
}
/// How the reference spells an option's kind, a `Words` option's vocabulary
/// included — a user cannot guess `CamelCase|ALL_CAPS` from "word list".
fn kind_word(kind: OptionKind) -> String {
match kind {
OptionKind::Int { min, max } => format!("integer {min}–{max}"),
OptionKind::Words(vocabulary) => {
format!("one or more of {} joined with `\\|`", vocabulary.join(", "))
}
other => other.as_str().to_string(),
}
}
/// How the table spells a rule's default: on, off, or on wherever there is a
/// project to ask about ([`crate::Rule::needs_workspace`]).
fn default_word(rule: &dyn crate::Rule) -> &'static str {
@@ -98,7 +155,7 @@ mod tests {
fn the_index_lists_every_rule_once() {
let markdown = rules_markdown();
for rule in all_rules() {
let row = format!("| [`{0}`](#{0}) |", rule.name());
let row = format!("| [`{0}`](#{0}) | ", rule.name());
assert_eq!(markdown.matches(&row).count(), 1, "{}", rule.name());
}
}
@@ -106,27 +163,96 @@ mod tests {
#[test]
fn defaults_and_fixes_are_rendered_from_the_registry() {
let markdown = rules_markdown();
assert!(markdown.contains("| [`no-tabs`](#no-tabs) | **on** | safe |"));
assert!(markdown.contains("| [`module-name-style`](#module-name-style) | off | none |"));
assert!(markdown.contains("| [`no-tabs`](#no-tabs) | style | **on** | safe |"));
assert!(
markdown.contains("| [`module-name-style`](#module-name-style) | style | off | none |")
);
// The three semantic rules are fixless, and default on exactly where
// there is a project to ask about a name — see
// docs/features/semantic-lints-on/README.md.
for name in ["multiply-driven", "undriven-net", "unused-signal"] {
for (name, severity) in [
("multiply-driven", "error"),
("undriven-net", "warning"),
("unused-signal", "warning"),
] {
assert!(
markdown.contains(&format!("| [`{name}`](#{name}) | **on (project)** | none |")),
markdown.contains(&format!(
"| [`{name}`](#{name}) | {severity} | **on (project)** | none |"
)),
"{name}"
);
}
assert_eq!(fix_word(&crate::rules::no_tabs::NoTabs), Applicability::Safe.as_str());
}
/// Every rule sits under the heading of its own class, and the three
/// headings are written worst-first.
#[test]
fn the_sections_are_grouped_by_severity() {
let markdown = rules_markdown();
let heading = |severity: Severity| {
markdown
.find(&format!("\n# {} — ", severity.as_str()))
.unwrap_or_else(|| panic!("{severity:?} heading"))
};
let (error, warning, style) =
(heading(Severity::Error), heading(Severity::Warning), heading(Severity::Style));
assert!(error < warning && warning < style, "worst first");
for rule in all_rules() {
let at = markdown
.find(&format!("\n## {}\n", rule.name()))
.unwrap_or_else(|| panic!("{}", rule.name()));
let own = heading(rule.severity());
let next = [error, warning, style]
.into_iter()
.filter(|start| *start > own)
.min()
.unwrap_or(markdown.len());
assert!(own < at && at < next, "{} is under the wrong heading", rule.name());
}
}
/// Every option a rule declares is in the reference, with the default a
/// run that configures nothing actually reads.
#[test]
fn every_option_is_listed_with_its_kind_and_default() {
let markdown = rules_markdown();
for rule in all_rules() {
for spec in rule.options() {
assert!(
markdown.contains(&format!("| `{}` |", spec.name)),
"{}.{}",
rule.name(),
spec.name
);
assert!(markdown.contains(spec.doc), "{}.{}: doc", rule.name(), spec.name);
}
}
assert!(markdown.contains("| `length` | integer 40–400 | `100` |"), "line-length");
assert!(
markdown.contains("| `prefix` | list of strings | `[\"g_\", \"gen_\"]` |"),
"generate-label-prefix"
);
assert!(
markdown.contains("one or more of CamelCase, ALL_CAPS joined with"),
"parameter-name-style's vocabulary"
);
// A rule with no options gets no table.
let no_tabs = markdown
.split("## no-tabs\n")
.nth(1)
.and_then(|rest| rest.split("\n## ").next())
.unwrap_or_default();
assert!(!no_tabs.contains("| Option |"), "{no_tabs}");
}
#[test]
fn the_document_shape_is_pinned() {
// A golden test on the *shape*, not on the prose: the heading, the
// generated-by note, the index table header, and the first per-rule
// section, which together are what a reader (and any renderer) sees.
let markdown = rules_markdown();
let head: Vec<&str> = markdown.lines().take(8).collect();
let head: Vec<&str> = markdown.lines().take(12).collect();
assert_eq!(
head,
vec![
@@ -135,6 +261,12 @@ mod tests {
"Generated from the rule registry by `vlog_linter::rules_markdown` — do not edit \
by hand.",
"",
"Every rule is in one of three **severity** classes, and the class is a word \
`--select` and `--ignore` accept wherever a rule name fits (`--ignore style`, \
`--select error`). **error** is code that would very likely fail to compile, \
elaborate or synthesize; **warning** is code that compiles but very likely does \
not mean what it says; **style** is code that is correct and reads badly.",
"",
"A rule marked **on** runs for a plain `lucisv check`; the others need \
`--select <name>`. A rule marked **on (project)** runs by default only where \
lucisv can see the other files of the project — `lucisv check <dir>`, or the \
@@ -143,18 +275,28 @@ mod tests {
rule can be turned off with `--ignore <name>`, with `ignore` under `[lint]` in \
`lucisv.toml`, or waived in the source with `// lucisv: waive <name>`.",
"",
"| Rule | Default | Fix |",
"|---|---|---|",
"A rule with **options** is configured in a `[lint.<rule-name>]` table of a \
`lucisv.toml`, or from an editor with `lucisv.lint.options`; an option nobody \
sets reads the default listed with it. An unknown option name, a value of the \
wrong kind, an integer out of range and a pattern that does not compile are \
all refused, naming the file and the line.",
"",
"| Rule | Severity | Default | Fix |",
"|---|---|---|---|",
]
);
let first_rule = all_rules()[0];
let first_rule = all_rules()
.into_iter()
.find(|rule| rule.severity() == Severity::Error)
.expect("some rule is an error");
let section = format!(
"## {}\n\n{}.\n\n- Default: {}\n- Fix: {}\n\n{}\n\n",
"## {}\n\n{}.\n\n- Severity: error\n- Default: {}\n- Fix: {}\n\n{}\n\n{}",
first_rule.name(),
capitalize(first_rule.summary()),
default_word(first_rule),
fix_word(first_rule),
first_rule.doc(),
options_table(first_rule),
);
assert!(markdown.contains(&section), "per-rule section shape changed:\n{section}");
assert!(markdown.ends_with("\n\n"));
+164
View File
@@ -0,0 +1,164 @@
//! `always-comb` — write combinational logic as `always_comb`.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use crate::visit::walk_items;
use vlog_parser::ast::{ItemKind, SensList, StmtKind, TimingControl};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct AlwaysComb;
const NAME: &str = "always-comb";
impl Rule for AlwaysComb {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"write `always_comb` instead of `always @*`"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"`always_comb` says what the block is *for*, and the language checks \
the claim: the tool errors if anything else drives one of its \
left-hand sides, and it infers the sensitivity list including the \
functions the block calls — which `always @*` does not. Verible's \
`always-comb` (enabled by default) asks for the SystemVerilog \
spelling wherever `always @*` or `always @(*)` is written, and lucisv \
checks the same thing.\n\n\
The fix is offered but **unsafe**, and the reason is real: an \
`always_comb` block runs once at time zero and an `always @*` block \
does not run until something in its sensitivity list changes, so a \
testbench that samples before the first change can see a different \
value. It also becomes an error for the block's outputs to be driven \
anywhere else, which is usually the bug being found but is still a \
change in what compiles. `--unsafe-fixes` applies it; the edit is the \
keyword and its `@(*)`, nothing else."
}
fn fix(&self) -> Option<Applicability> {
Some(Applicability::Unsafe)
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::Always { kw, stmt } = &item.kind else { return };
if kw != "always" {
return;
}
let StmtKind::Timing { control: TimingControl::Event(sens), stmt: Some(body) } =
&stmt.kind
else {
return;
};
if !matches!(sens, SensList::Star { .. }) {
return;
}
let Some(header) = header_span(ctx, item.span.start, body.span.start) else { return };
out.push(
Violation::new(NAME, "use `always_comb` instead of `always @*`", header)
.with_fix(Fix::unsafe_fix(vec![(header, "always_comb".to_string())])),
);
});
out
}
}
/// The `always @(*)` in front of the body: from the keyword to the end of the
/// last token before the body starts.
///
/// Read off the tokens rather than assumed, because the sensitivity control
/// may be written `@*`, `@ (*)` or `@( /* why */ * )`, and the fix must
/// replace exactly what was written and not a byte more.
fn header_span(ctx: &LintContext, start: u32, body: u32) -> Option<TextRange> {
let end = ctx
.tokens()
.iter()
.filter(|token| token.span.start >= start && token.span.end <= body)
.map(|token| token.span.end)
.max()?;
(end > start).then(|| TextRange::new(start, end))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::violation::apply_fixes;
fn violations(src: &str) -> Vec<Violation> {
AlwaysComb.check(&LintContext::new(src, None))
}
#[test]
fn flags_both_spellings_and_rewrites_only_the_header() {
for src in [
"module m;\n always @(*) x = 1;\nendmodule\n",
"module m;\n always @* x = 1;\nendmodule\n",
] {
let found = violations(src);
assert_eq!(found.len(), 1, "{src}");
let fixed = apply_fixes(src, &found, true);
assert_eq!(fixed.output, "module m;\n always_comb x = 1;\nendmodule\n", "{src}");
}
}
#[test]
fn the_fix_is_unsafe() {
let src = "module m;\n always @(*) x = 1;\nendmodule\n";
let found = violations(src);
assert_eq!(found[0].fix.as_ref().map(|f| f.applicability), Some(Applicability::Unsafe));
assert_eq!(apply_fixes(src, &found, false).applied, 0, "not without --unsafe-fixes");
}
#[test]
fn a_multi_line_block_keeps_its_layout() {
let src = "module m;\n always @(*) begin\n x = 1;\n end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1);
assert_eq!(
apply_fixes(src, &found, true).output,
"module m;\n always_comb begin\n x = 1;\n end\nendmodule\n"
);
}
#[test]
fn a_comment_inside_the_control_is_replaced_with_it() {
// The whole header is one edit, so a comment written inside `@( * )`
// goes with it — which is why the fix is offered, not applied.
let src = "module m;\n always @( /* all */ * ) x = 1;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1);
assert_eq!(
apply_fixes(src, &found, true).output,
"module m;\n always_comb x = 1;\nendmodule\n"
);
}
#[test]
fn an_explicit_sensitivity_list_is_none_of_its_business() {
for src in [
"module m;\n always @(a or b) x = 1;\nendmodule\n",
"module m;\n always @(posedge clk) q <= d;\nendmodule\n",
"module m;\n always_comb x = 1;\nendmodule\n",
"module m;\n always_ff @(posedge clk) q <= d;\nendmodule\n",
"module m;\n always @(*);\nendmodule\n",
] {
assert!(violations(src).is_empty(), "{src}");
}
}
#[test]
fn an_always_star_inside_a_generate_block_is_covered() {
let src = "module m;\n if (A) begin : g\n always @(*) x = 1;\n end\nendmodule\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
}
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_items, walk_stmts};
use vlog_parser::ast::{ItemKind, StmtKind};
@@ -20,6 +21,10 @@ impl Rule for AlwaysCombBlocking {
"assign with `=` inside always_comb"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A non-blocking assignment in a combinational block schedules its \
update for the end of the time step, so a value read later in the same \
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_items, walk_stmts};
use vlog_parser::ast::{ItemKind, StmtKind};
@@ -20,6 +21,10 @@ impl Rule for AlwaysFfNonBlocking {
"assign with `<=` inside always_ff"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A blocking assignment in a clocked block updates immediately, so two \
flops written in one `always_ff` can see each other's new value in \
@@ -0,0 +1,139 @@
//! `banned-declared-name-patterns` — names a project has forbidden.
use crate::context::LintContext;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::regex::Regex;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
/// See [`Rule::doc`].
pub struct BannedDeclaredNamePatterns;
const NAME: &str = "banned-declared-name-patterns";
impl Rule for BannedDeclaredNamePatterns {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"do not declare a name the project has banned"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"Every codebase has words it has decided against — a deprecated \
prefix, a vendor's reserved namespace, the `tmp`/`foo` a review keeps \
catching — and none of them are anybody else's business. Verible's \
`banned-declared-name-patterns` is the rule a project points at its \
own list, and it ships **off** with an empty list, which is exactly \
what lucisv does: with no `patterns` set the rule reports nothing and \
costs nothing.\n\n\
It judges **declared** names, not uses: every name the file's symbol \
table holds — modules, packages, types, parameters, signals, ports, \
instances, block labels, class members. A pattern must match the whole \
name, so `tmp.*` bans `tmp_addr` and `.*_tmp` bans `addr_tmp`. There \
is no fix: only the author knows what the name should have been."
}
fn default_on(&self) -> bool {
false
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "patterns",
kind: OptionKind::RegexList,
default: OptionDefault::List(&[]),
doc: "the patterns a declared name may not match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let patterns: Vec<(String, Regex)> = ctx
.option_list(NAME, "patterns")
.into_iter()
// A pattern that does not compile cannot be configured — the
// option is validated when it is read — so filtering here only
// ever drops what could not have arrived.
.filter_map(|text| Regex::compile(&text).ok().map(|regex| (text, regex)))
.collect();
if patterns.is_empty() {
return Vec::new();
}
let mut out = Vec::new();
for symbol in ctx.semantics().symbols() {
let Some((pattern, _)) =
patterns.iter().find(|(_, regex)| regex.is_match(&symbol.name))
else {
continue;
};
out.push(Violation::new(
NAME,
format!("`{}` matches the banned pattern `{pattern}`", symbol.name),
symbol.name_span,
));
}
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn banning(patterns: &str, src: &str) -> Vec<Violation> {
let mut options = RuleOptions::new();
options.set_raw(NAME, "patterns", patterns).expect("accepted");
BannedDeclaredNamePatterns.check(&LintContext::new(src, None).with_options(&options))
}
#[test]
fn nothing_is_banned_by_default() {
let src = "module m;\n logic tmp_addr;\nendmodule\n";
assert!(BannedDeclaredNamePatterns.check(&LintContext::new(src, None)).is_empty());
assert!(!BannedDeclaredNamePatterns.default_on());
}
#[test]
fn a_banned_name_is_reported_where_it_is_declared() {
let src = "module m;\n logic tmp_addr;\n logic keep_me;\nendmodule\n";
let found = banning("[\"tmp.*\"]", src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("banned pattern `tmp.*`"), "{}", found[0].message);
assert_eq!(&src[found[0].span.as_range()], "tmp_addr");
assert!(found[0].fix.is_none());
}
#[test]
fn the_match_is_the_whole_name() {
let src = "module m;\n logic addr_tmp;\nendmodule\n";
assert!(banning("[\"tmp\"]", src).is_empty(), "a substring is not a match");
assert_eq!(banning("[\".*_tmp\"]", src).len(), 1);
}
#[test]
fn every_kind_of_declared_name_is_covered() {
let src = "package foo_pkg;\n typedef logic foo_t;\nendpackage\n\
module foo_mod (input logic foo_port);\n logic foo_sig;\nendmodule\n";
let found = banning("[\"foo.*\"]", src);
let names: Vec<&str> = found.iter().map(|v| &src[v.span.as_range()]).collect();
for wanted in ["foo_pkg", "foo_t", "foo_mod", "foo_port", "foo_sig"] {
assert!(names.contains(&wanted), "{wanted} missing from {names:?}");
}
}
#[test]
fn several_patterns_are_all_applied_and_findings_come_back_in_order() {
let src = "module m;\n logic tmp_a;\n logic bad_b;\nendmodule\n";
let found = banning("[\"tmp.*\", \"bad.*\"]", src);
assert_eq!(found.len(), 2);
assert!(found[0].span.start < found[1].span.start);
}
}
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_all_stmts, walk_items};
use vlog_parser::ast::{CaseItem, GenCaseItem, ItemKind, StmtKind};
@@ -21,6 +22,10 @@ impl Rule for CaseMissingDefault {
"give every case statement a default branch"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A case statement with no `default` infers a latch in combinational \
logic and leaves the unlisted patterns unspecified in simulation — the \
@@ -0,0 +1,127 @@
//! `constraint-name-style` — constraint names end in `_c`.
use crate::context::LintContext;
use crate::naming::{fits_pattern, is_escaped, style_message};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::ItemKind;
/// See [`Rule::doc`].
pub struct ConstraintNameStyle;
const NAME: &str = "constraint-name-style";
impl Rule for ConstraintNameStyle {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name constraints in lower_snake_case ending in _c"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A constraint block's name is what a test turns off — \
`obj.addr_range_c.constraint_mode(0)` — so it is read far from its \
declaration and needs to say what it is at the use site. Verible's \
`constraint-name-style` (enabled by default) spells the convention as \
`([a-z0-9]+_)+c`: lower-case words, then a `_c` suffix. lucisv checks \
the same pattern, on the constraints a class declares and on the \
out-of-block `constraint cls::name { … }` form.\n\n\
A prototype (`constraint c;`) is judged like a definition — it \
declares the same name. Escaped identifiers are exempt, and there is \
no fix: a rename reaches every `constraint_mode` call."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "pattern",
kind: OptionKind::Regex,
default: OptionDefault::Str("([a-z0-9]+_)+c"),
doc: "the pattern a constraint's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let ItemKind::Constraint(decl) = &item.kind else { return };
let name = &decl.name.text;
if is_escaped(name) || fits_pattern(ctx, NAME, "pattern", name) {
return;
}
out.push(Violation::new(
NAME,
style_message(
ctx,
NAME,
"pattern",
&format!("constraint `{name}`"),
"is not lower_snake_case ending in `_c`",
),
decl.name.span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
ConstraintNameStyle.check(&LintContext::new(src, None))
}
fn constraint(name: &str) -> String {
format!("class c;\n rand int addr;\n constraint {name} {{ addr > 0; }}\nendclass\n")
}
#[test]
fn flags_a_missing_suffix_and_points_at_the_name() {
let src = constraint("addr_range");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "addr_range");
assert!(found[0].fix.is_none());
}
#[test]
fn the_convention_is_clean() {
for name in ["addr_range_c", "a_c", "addr2_range_c"] {
assert!(violations(&constraint(name)).is_empty(), "{name}");
}
for name in ["c", "AddrRangeC", "addr_range", "_addr_c"] {
assert_eq!(violations(&constraint(name)).len(), 1, "{name}");
}
}
#[test]
fn a_prototype_and_an_out_of_block_definition_are_judged_too() {
let src = "class c;\n extern constraint addr_range;\nendclass\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
let src = "constraint c::addr_range { x > 0; }\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn a_configured_pattern_replaces_the_default() {
let mut options = RuleOptions::new();
options.set_raw(NAME, "pattern", "\"c_[a-z_0-9]+\"").expect("accepted");
let src = constraint("c_addr_range");
let ctx = LintContext::new(&src, None).with_options(&options);
assert!(ConstraintNameStyle.check(&ctx).is_empty());
let src = constraint("addr_range_c");
let ctx = LintContext::new(&src, None).with_options(&options);
assert_eq!(ConstraintNameStyle.check(&ctx).len(), 1);
}
}
@@ -0,0 +1,178 @@
//! `create-object-name-match` — `type_id::create("x")` names the variable `x`.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_all_stmts, walk_items};
use vlog_parser::ast::{Expr, ExprKind, ItemKind, StmtKind};
/// See [`Rule::doc`].
pub struct CreateObjectNameMatch;
const NAME: &str = "create-object-name-match";
impl Rule for CreateObjectNameMatch {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"give `type_id::create` the name of the variable it is assigned to"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"The string handed to `type_id::create()` becomes the object's UVM \
instance name, and that name is what `uvm_config_db` paths, factory \
overrides, `+uvm_set_config` plusargs and every report line are \
written against. When it does not match the handle it was assigned \
to, a config setting aimed at `env.agent.driver` silently misses the \
object the reader believes it is aimed at — and nothing fails, it \
just does not take. Verible's `create-object-name-match` (\"Checks \
that the 'name' argument of `type_id::create()` matches the assigned \
variable name.\", enabled by default) is the same rule and the same \
default.\n\n\
Judged where Verible judges it: a right-hand side of the shape \
`<type>::type_id::create(\"name\", …)`, however the type is \
qualified (`pkg::cls::type_id::create`), assigned to a **plain \
variable** — a `this.h` or an array element is not one, and neither \
is a `create` whose first argument is not a string literal. No \
automatic fix: rewriting the string changes the object's UVM path, \
and rewriting the variable renames it everywhere; which is meant is \
the author's to say."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
let mut judge = |lhs: &str, rhs: &Expr| {
let Some(arg) = create_name(rhs) else { return };
let Some(written) = string_value(arg) else { return };
if written == lhs {
return;
}
out.push(Violation::new(
NAME,
format!(
"`type_id::create` is named `{written}` but assigned to `{lhs}`; \
the two must match"
),
arg.span,
));
};
walk_all_stmts(ctx.file(), &mut |stmt| match &stmt.kind {
StmtKind::Assign { lhs, rhs, .. } => {
if let ExprKind::Ident(name) = &lhs.kind {
judge(name, rhs);
}
}
StmtKind::VarDecl(decl) => {
for declarator in &decl.declarators {
if let Some(init) = &declarator.init {
judge(&declarator.name, init);
}
}
}
_ => {}
});
walk_items(ctx.file(), &mut |item| {
let ItemKind::DataDecl(decl) = &item.kind else { return };
for declarator in &decl.declarators {
if let Some(init) = &declarator.init {
judge(&declarator.name, init);
}
}
});
out
}
}
/// The first argument of a `…::type_id::create(…)` call, or `None` for
/// anything else.
fn create_name(expr: &Expr) -> Option<&Expr> {
let ExprKind::Call { callee, args, .. } = &expr.kind else { return None };
let ExprKind::Scope { base, name, .. } = &callee.kind else { return None };
if name != "create" {
return None;
}
let ExprKind::Scope { name: middle, .. } = &base.kind else { return None };
if middle != "type_id" {
return None;
}
args.first().map(|arg| &arg.expr)
}
/// The text of a string literal, without its quotes.
fn string_value(expr: &Expr) -> Option<&str> {
let ExprKind::Str(text) = &expr.kind else { return None };
text.strip_prefix('"')?.strip_suffix('"')
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
CreateObjectNameMatch.check(&LintContext::new(src, None))
}
fn body(text: &str) -> String {
format!(
"class c;\n function automatic void build();\n {text}\n endfunction\nendclass\n"
)
}
#[test]
fn flags_a_mismatched_name_and_underlines_the_string() {
let src = body("driver_h = my_driver::type_id::create(\"drv\", this);");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "\"drv\"");
assert!(found[0].fix.is_none());
}
#[test]
fn a_matching_name_is_what_the_rule_wants() {
for text in [
"driver_h = my_driver::type_id::create(\"driver_h\", this);",
"driver_h = pkg::my_driver::type_id::create(\"driver_h\");",
] {
let src = body(text);
assert!(violations(&src).is_empty(), "{text}: {:?}", violations(&src));
}
}
#[test]
fn a_declaration_with_an_initialiser_is_judged_too() {
let src = body("my_driver driver_h = my_driver::type_id::create(\"drv\");");
assert_eq!(violations(&src).len(), 1, "{:?}", violations(&src));
}
#[test]
fn something_that_is_not_a_type_id_create_is_left_alone() {
for text in [
"driver_h = my_driver::create(\"drv\");",
"driver_h = my_driver::type_id::get();",
"driver_h = new(\"drv\");",
"driver_h = f(\"drv\");",
] {
let src = body(text);
assert!(violations(&src).is_empty(), "{text}: {:?}", violations(&src));
}
}
#[test]
fn a_non_literal_name_or_a_non_plain_target_says_nothing() {
for text in [
"driver_h = my_driver::type_id::create(name_s, this);",
"this.driver_h = my_driver::type_id::create(\"drv\");",
"agents[0] = my_agent::type_id::create(\"drv\");",
] {
let src = body(text);
assert!(violations(&src).is_empty(), "{text}: {:?}", violations(&src));
}
}
}
@@ -0,0 +1,459 @@
//! `dff-name-style` — a flip-flop's output and its next-state input are named
//! for each other.
use crate::context::LintContext;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_all_stmts, walk_items};
use vlog_parser::ast::{Expr, ExprKind, ItemKind, Stmt, StmtKind};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct DffNameStyle;
const NAME: &str = "dff-name-style";
/// Verible's four options. Its `input` / `output` / `waive_ifs_with_conditions`
/// are comma-separated strings there and lists here, which is how every other
/// lucisv list option is spelled; `waive_lhs_regex`'s default is Verible's
/// `(?i)mem.*` written without the inline flag this engine does not implement.
const OPTIONS: &[OptionSpec] = &[
OptionSpec {
name: "input",
kind: OptionKind::List,
default: OptionDefault::List(&["next", "n", "d"]),
doc: "suffixes that mark the next-state input of a flip-flop",
},
OptionSpec {
name: "output",
kind: OptionKind::List,
default: OptionDefault::List(&["reg", "r", "ff", "q"]),
doc: "suffixes that mark the registered output of a flip-flop",
},
OptionSpec {
name: "waive_ifs_with_conditions",
kind: OptionKind::List,
default: OptionDefault::List(&[
"!rst_ni",
"flush_i",
"!rst_ni || flush_i",
"flush_i || !rst_ni",
]),
doc: "conditions whose branches are reset or flush paths and are not judged",
},
OptionSpec {
name: "waive_lhs_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str("[mM][eE][mM].*"),
doc: "names that are not flip-flops at all and are left alone",
},
];
impl Rule for DffNameStyle {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name a flip-flop's output and its next-state input for each other"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn default_on(&self) -> bool {
false
}
fn options(&self) -> &'static [OptionSpec] {
OPTIONS
}
fn doc(&self) -> &'static str {
"The `_q`/`_d` convention makes a design's state visible at a glance: \
`count_q <= count_d` says \"this is the register, that is the \
combinational next value\", so a waveform, a schematic and the source \
all name the same two nets, and a signal called `count_q` driven by \
a `always_comb` is a mistake the reader can see without following it. \
Verible's `dff-name-style` (\"Checks that D Flip-Flops use \
appropriate naming conventions in input/output ports.\", **disabled** \
by default) is the same rule and the same default, with the same four \
options.\n\n\
Two things are checked. **In an `always_ff`**, a nonblocking \
assignment's left-hand side must end with one of the `output` \
suffixes (`_q`, `_r`, `_ff`, `_reg`, optionally with a pipeline \
number: `data_q2`); and when its right-hand side is a plain name \
ending with one of the `input` suffixes (`_d`, `_n`, `_next`), the \
two must share a base — `data_q <= data_d` is right, `data_q <= \
other_d` is not. **Outside one**, a blocking or continuous \
assignment to a name ending in an `output` suffix is reported: that \
name promises a register and is not one.\n\n\
Only a **plain identifier** is judged on either side; an indexed, \
member-selected or concatenated target is not something a naming \
convention can speak about. A branch whose `if` condition is one of \
`waive_ifs_with_conditions` is skipped, which is what keeps reset \
and flush paths quiet, and a name matching `waive_lhs_regex` is \
skipped entirely (memories are not flip-flops). Conditions are \
compared ignoring whitespace, so `!rst_ni` and `! rst_ni` are the \
same waiver. No automatic fix: renaming a signal is a rename."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let settings = Settings::read(ctx);
let mut out = Vec::new();
registered(ctx, &settings, &mut out);
unregistered(ctx, &settings, &mut out);
out.sort_by_key(|violation| (violation.span.start, violation.span.end));
out
}
}
/// The four options, read once for the whole file.
struct Settings {
input: Vec<String>,
output: Vec<String>,
waived_conditions: Vec<String>,
waived_lhs: Option<crate::regex::Regex>,
}
impl Settings {
fn read(ctx: &LintContext) -> Settings {
Settings {
input: ctx.option_list(NAME, "input"),
output: ctx.option_list(NAME, "output"),
waived_conditions: ctx
.option_list(NAME, "waive_ifs_with_conditions")
.iter()
.map(|text| squeeze(text))
.collect(),
waived_lhs: ctx.option_pattern(NAME, "waive_lhs_regex"),
}
}
/// Whether this left-hand side is one the project asked not to judge.
fn waives(&self, name: &str) -> bool {
self.waived_lhs.as_ref().is_some_and(|pattern| pattern.is_match(name))
}
}
/// The `always_ff` half: every nonblocking assignment inside one.
fn registered(ctx: &LintContext, settings: &Settings, out: &mut Vec<Violation>) {
walk_items(ctx.file(), &mut |item| {
let ItemKind::Always { kw, stmt } = &item.kind else { return };
if kw != "always_ff" {
return;
}
let mut conditions: Vec<String> = Vec::new();
clocked(ctx, settings, stmt, &mut conditions, out);
});
}
/// Walks one `always_ff` body, remembering which `if` conditions hold.
fn clocked(
ctx: &LintContext,
settings: &Settings,
stmt: &Stmt,
conditions: &mut Vec<String>,
out: &mut Vec<Violation>,
) {
match &stmt.kind {
StmtKind::Assign { lhs, rhs, op, .. } if op == "<=" => {
if conditions.iter().any(|cond| settings.waived_conditions.contains(cond)) {
return;
}
judge_flop(settings, lhs, rhs, out);
}
StmtKind::If { cond, then, els, .. } => {
conditions.push(squeeze(text_of(ctx, cond.span)));
clocked(ctx, settings, then, conditions, out);
conditions.pop();
if let Some(els) = els {
clocked(ctx, settings, els, conditions, out);
}
}
StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => {
for inner in stmts {
clocked(ctx, settings, inner, conditions, out);
}
}
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
for case_item in items {
clocked(ctx, settings, &case_item.stmt, conditions, out);
}
}
StmtKind::Labeled { stmt: inner, .. }
| StmtKind::For { body: inner, .. }
| StmtKind::While { body: inner, .. }
| StmtKind::DoWhile { body: inner, .. }
| StmtKind::Repeat { body: inner, .. }
| StmtKind::Forever { body: inner }
| StmtKind::Foreach { body: inner, .. } => clocked(ctx, settings, inner, conditions, out),
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
clocked(ctx, settings, inner, conditions, out)
}
_ => {}
}
}
/// One `q <= d` inside an `always_ff`.
fn judge_flop(settings: &Settings, lhs: &Expr, rhs: &Expr, out: &mut Vec<Violation>) {
let Some(target) = plain_name(lhs) else { return };
if settings.waives(target) {
return;
}
let Some(base) = base_of(target, &settings.output) else {
out.push(Violation::new(
NAME,
format!(
"`{target}` is assigned in an `always_ff` but does not end with {}",
one_of(&settings.output)
),
lhs.span,
));
return;
};
if base.is_empty() {
out.push(Violation::new(
NAME,
format!("`{target}` is nothing but a flip-flop suffix; name the signal too"),
lhs.span,
));
return;
}
let Some(source) = plain_name(rhs) else { return };
let Some(source_base) = base_of(source, &settings.input) else { return };
if source_base != base {
out.push(Violation::new(
NAME,
format!(
"`{target}` is driven by `{source}`; the parts before the suffixes must \
match, but `{base}` is not `{source_base}`"
),
rhs.span,
));
}
}
/// The other half: a name that promises a register, driven by something that
/// is not one.
fn unregistered(ctx: &LintContext, settings: &Settings, out: &mut Vec<Violation>) {
let mut judge = |lhs: &Expr| {
let Some(target) = plain_name(lhs) else { return };
if settings.waives(target) {
return;
}
if base_of(target, &settings.output).is_some_and(|base| !base.is_empty()) {
out.push(Violation::new(
NAME,
format!(
"`{target}` is named like a flip-flop output but is not driven by a \
nonblocking assignment in an `always_ff`"
),
lhs.span,
));
}
};
walk_items(ctx.file(), &mut |item| {
let ItemKind::ContAssign(assign) = &item.kind else { return };
for pair in &assign.assigns {
judge(&pair.lhs);
}
});
// A blocking assignment anywhere — in an `always_comb`, an `initial`, or
// inside the `always_ff` itself, which is the shape the rule most wants.
walk_all_stmts(ctx.file(), &mut |stmt| {
let StmtKind::Assign { lhs, op, .. } = &stmt.kind else { return };
if op == "<=" {
return;
}
judge(lhs);
});
}
/// The name of a plain identifier, or `None` for any other target.
fn plain_name(expr: &Expr) -> Option<&str> {
match &expr.kind {
ExprKind::Ident(name) => Some(name),
_ => None,
}
}
/// The part of `name` before its `_<suffix>[digits]` tail, or `None` when it
/// carries none of `suffixes`.
fn base_of<'a>(name: &'a str, suffixes: &[String]) -> Option<&'a str> {
let trimmed = name.trim_end_matches(|c: char| c.is_ascii_digit());
for suffix in suffixes {
if let Some(base) = trimmed.strip_suffix(suffix.as_str()) {
if let Some(base) = base.strip_suffix('_') {
return Some(base);
}
// `_q` on its own: a suffix with nothing in front of it.
if base.is_empty() && trimmed.len() == suffix.len() {
return Some("");
}
}
}
None
}
/// `` `_q`, `_r` or `_ff` `` — the suffix list, as a message says it.
fn one_of(suffixes: &[String]) -> String {
let quoted: Vec<String> = suffixes.iter().map(|s| format!("`_{s}`")).collect();
match quoted.split_last() {
Some((last, [])) => last.clone(),
Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
None => "a registered-output suffix".to_string(),
}
}
/// The source text of a span.
fn text_of<'a>(ctx: &'a LintContext, span: TextRange) -> &'a str {
ctx.source().get(span.as_range()).unwrap_or("")
}
/// The same text with every space taken out, so `!rst_ni` and `! rst_ni` are
/// one waiver rather than two.
fn squeeze(text: &str) -> String {
text.chars().filter(|c| !c.is_whitespace()).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
fn violations(src: &str) -> Vec<Violation> {
DffNameStyle.check(&LintContext::new(src, None))
}
fn with(src: &str, key: &str, raw: &str) -> Vec<Violation> {
let mut options = RuleOptions::new();
options.set_raw(NAME, key, raw).expect("accepted");
DffNameStyle.check(&LintContext::new(src, None).with_options(&options))
}
fn flop(body: &str) -> String {
format!("module m;\n always_ff @(posedge clk) begin\n {body}\n end\nendmodule\n")
}
#[test]
fn the_convention_is_clean() {
for body in [
"data_q <= data_d;",
"data_r <= data_n;",
"data_ff <= data_next;",
"data_reg <= data_d;",
"data_q2 <= data_d2;",
"data_q <= other_signal;",
"data_q <= a + b;",
] {
let src = flop(body);
assert!(violations(&src).is_empty(), "{body}: {:?}", violations(&src));
}
}
#[test]
fn flags_a_registered_name_without_a_suffix() {
let src = flop("data <= data_d;");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "data");
assert!(found[0].message.contains("`_q`"), "{}", found[0].message);
assert!(found[0].fix.is_none());
}
#[test]
fn flags_a_mismatched_pair_and_points_at_the_source() {
let src = flop("a_q <= b_n;");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "b_n");
assert!(found[0].message.contains("`a` is not `b`"), "{}", found[0].message);
}
#[test]
fn a_bare_suffix_names_nothing() {
let src = flop("_q <= data_d;");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(
found[0].message.contains("nothing but a flip-flop suffix"),
"{}",
found[0].message
);
}
#[test]
fn a_reset_branch_is_waived_whatever_its_spacing() {
for cond in ["!rst_ni", "! rst_ni", "flush_i", "!rst_ni || flush_i"] {
let src = flop(&format!("if ({cond}) data <= '0; else data_q <= data_d;"));
assert!(violations(&src).is_empty(), "{cond}: {:?}", violations(&src));
}
}
#[test]
fn a_condition_that_is_not_waived_is_still_judged() {
let src = flop("if (enable_i) data <= data_d;");
assert_eq!(violations(&src).len(), 1, "{:?}", violations(&src));
}
#[test]
fn a_memory_name_is_waived_by_the_default_pattern() {
for name in ["mem_array", "MEM_ARRAY", "Memory"] {
let src = flop(&format!("{name} <= data_d;"));
assert!(violations(&src).is_empty(), "{name}: {:?}", violations(&src));
}
}
#[test]
fn a_flip_flop_name_driven_by_anything_else_is_reported() {
let combinational = "module m;\n always_comb data_q = data_d;\nendmodule\n";
assert_eq!(violations(combinational).len(), 1, "{:?}", violations(combinational));
let continuous = "module m;\n assign data_q = data_d;\nendmodule\n";
assert_eq!(violations(continuous).len(), 1, "{:?}", violations(continuous));
let blocking_in_ff = flop("data_q = data_d;");
assert_eq!(violations(&blocking_in_ff).len(), 1, "{:?}", violations(&blocking_in_ff));
}
#[test]
fn a_plain_signal_driven_combinationally_is_nobodys_business() {
let src = "module m;\n assign data_d = a + b;\n always_comb next = 1;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_non_plain_target_is_not_judged() {
for body in ["data[0] <= data_d;", "s.f <= data_d;", "{a, b} <= data_d;"] {
let src = flop(body);
assert!(violations(&src).is_empty(), "{body}: {:?}", violations(&src));
}
}
#[test]
fn the_suffix_lists_are_configurable() {
let src = flop("data_ptr <= data_nxt;");
assert_eq!(violations(&src).len(), 1);
let mut options = RuleOptions::new();
options.set_raw(NAME, "output", "[\"ptr\"]").expect("accepted");
options.set_raw(NAME, "input", "[\"nxt\"]").expect("accepted");
let found = DffNameStyle.check(&LintContext::new(&src, None).with_options(&options));
assert!(found.is_empty(), "{found:?}");
}
#[test]
fn the_lhs_waiver_pattern_is_configurable() {
let src = flop("scratch <= data_d;");
assert_eq!(violations(&src).len(), 1);
assert!(with(&src, "waive_lhs_regex", "\"scratch.*\"").is_empty());
}
#[test]
fn the_waived_conditions_are_configurable() {
let src = flop("if (my_reset) data <= '0;");
assert_eq!(violations(&src).len(), 1);
assert!(with(&src, "waive_ifs_with_conditions", "[\"my_reset\"]").is_empty());
}
}
@@ -0,0 +1,157 @@
//! `disable-statement` — `disable` only a sequential block, or `disable fork`.
use std::collections::BTreeSet;
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_all_stmts, walk_items};
use vlog_parser::ast::{ItemKind, SourceFile, StmtKind};
/// See [`Rule::doc`].
pub struct DisableStatement;
const NAME: &str = "disable-statement";
impl Rule for DisableStatement {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"`disable` a sequential block or a task, and write `disable fork` for processes"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn default_on(&self) -> bool {
false
}
fn doc(&self) -> &'static str {
"`disable label` terminates the named sequential block, and \
`disable fork` terminates the calling process's children (IEEE 1800 \
§9.6.2, §9.6.3). Naming a `fork` block instead of writing \
`disable fork` is the mistake this rule exists for: it reads as \
though it kills the forked processes and does something else \
entirely, and in the common `fork … join_none` idiom it kills \
nothing at all. Verible's `disable-statement` (\"Checks that there \
are no occurrences of `disable some_label` if label refers to \
non-sequential blocks.\", **disabled** by default) is the same rule \
and the same default.\n\n\
What counts as a valid target here is the label of a \
`begin : name` block, a statement label (`name : begin`) — and, \
**wider than Verible**, the name of a task or function declared in \
the same file, because `disable task_name` is a legal and ordinary \
thing to write (§9.6.2) and reporting it would be a false positive. \
A name lucisv cannot see at all — a block in another file, a label a \
macro produces — is therefore reported; that is the rule's one \
false-positive mode and the reason it ships off. No automatic fix: \
whether the author meant `disable fork` or a different label is not \
something the source says."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let targets = disableable(ctx.file());
let mut out = Vec::new();
walk_all_stmts(ctx.file(), &mut |stmt| {
let StmtKind::Disable { name, .. } = &stmt.kind else { return };
// `disable fork` is the keyword form, not a label.
if name == "fork" || targets.contains(name.as_str()) {
return;
}
out.push(Violation::new(
NAME,
format!(
"`disable {name}` names no sequential block or task; write `disable fork` \
to stop forked processes"
),
stmt.span,
));
});
out
}
}
/// Every name a `disable` may legitimately mention in this file: the labels of
/// sequential blocks and statement labels, plus the tasks and functions the
/// file declares.
fn disableable(file: &SourceFile) -> BTreeSet<String> {
let mut out = BTreeSet::new();
walk_all_stmts(file, &mut |stmt| match &stmt.kind {
StmtKind::Block { label: Some(label), .. } => {
out.insert(label.clone());
}
StmtKind::Labeled { name, stmt: inner, .. } => {
if matches!(inner.kind, StmtKind::Block { .. }) {
out.insert(name.clone());
}
}
_ => {}
});
walk_items(file, &mut |item| match &item.kind {
ItemKind::Task(decl) => {
out.insert(decl.name.clone());
}
ItemKind::Function(decl) => {
out.insert(decl.name.clone());
}
_ => {}
});
out
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
DisableStatement.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_disable_of_a_fork_label() {
let src = "module m;\n initial begin\n fork : threads\n join_none\n \
disable threads;\n end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "disable threads;");
assert!(found[0].fix.is_none());
}
#[test]
fn disable_fork_is_the_spelling_the_rule_asks_for() {
let src = "module m;\n initial begin\n fork\n join_none\n disable fork;\n \
end\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_sequential_block_label_is_a_valid_target() {
let src = "module m;\n initial begin : seq\n disable seq;\n end\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_statement_label_on_a_block_counts_too() {
let src = "module m;\n initial begin\n outer : begin\n disable outer;\n \
end\n end\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_task_of_the_same_file_is_a_legal_target() {
let src = "module m;\n task automatic t();\n endtask\n initial begin\n \
disable t;\n end\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_name_this_file_does_not_declare_is_reported() {
let src = "module m;\n initial begin\n disable somewhere_else;\n end\nendmodule\n";
assert_eq!(violations(src).len(), 1);
}
}
@@ -0,0 +1,197 @@
//! `duplicate-declaration` — one name declared twice in one scope.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use vlog_semantic::{ScopeKind, SymbolKind};
/// See [`Rule::doc`].
pub struct DuplicateDeclaration;
const NAME: &str = "duplicate-declaration";
impl Rule for DuplicateDeclaration {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"declare each name once per scope"
}
fn severity(&self) -> Severity {
Severity::Error
}
fn doc(&self) -> &'static str {
"Two declarations of one name in one scope is an elaboration error in \
every tool (IEEE 1800 §3.13 — an identifier is unique within its \
namespace and scope). It happens when a signal is copied and the \
paste is not renamed, when two parameters are merged from different \
branches, or when a `logic` is declared beside the `input` of the \
same name. Verible has no equivalent rule; this is TODO §33's own, \
and it is an **Error** because the file will not compile.\n\n\
**Silent whenever the second declaration might be legal**, which is \
the rule every Error-class check here follows. It says nothing when \
either declaration is a **port** — a non-ANSI port is *completed* by \
a body `input clk;` and then by a `logic clk;`, all three of which \
are the same port and all three legal — nor about a function, task, \
class, constraint, covergroup, property, sequence, modport or \
clocking name, each of which has a legal prototype-plus-definition \
or forward-declaration shape. It says nothing inside a `generate` \
scope, where only one arm is ever elaborated, and nothing when a \
conditional-compilation directive stands between the two \
declarations, which is that same exclusivity written for the \
preprocessor. What is left is two ordinary declarations of one name, \
side by side, in one scope. No automatic fix: which of the two the \
author meant to keep is not something a linter can know."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
// Error recovery rebinds whatever followed a construct it could not
// parse into whatever scope it unwound to, which turns every later
// local into a phantom redeclaration. An Error-class rule says nothing
// about a file it cannot trust the shape of.
if !ctx.parsed_cleanly() {
return Vec::new();
}
let semantics = ctx.semantics();
let mut out = Vec::new();
for duplicate in semantics.duplicates() {
let Some(first) = semantics.symbol(duplicate.first) else { continue };
if !plain(duplicate.kind) || !plain(first.kind) {
continue;
}
let scope = semantics.scope(duplicate.scope).map(|scope| scope.kind);
// A generate scope elaborates one arm at a time; the file scope is
// where a `` `include``d fragment and a recovered construct both
// land, and two file-scope units of one name are the workspace's
// business rather than this file's.
if matches!(scope, Some(ScopeKind::Generate) | Some(ScopeKind::File)) {
continue;
}
let spans = [first.name_span.start, duplicate.name_span.start];
if ctx.signals().conditional_between(&spans) {
continue;
}
out.push(Violation::new(
NAME,
format!("`{}` is already declared in this scope", duplicate.name),
duplicate.name_span,
));
}
out
}
}
/// True for the declaration kinds that may be written **once** and once only.
///
/// Everything left out has a legal shape in which the same name is written
/// twice: a port is completed by its body declaration, a function or task by
/// its out-of-body definition, a class by its `typedef class` forward
/// declaration, and a constraint, covergroup, property or sequence by its own
/// prototype. An **enum member** is left out for a different reason: IEEE 1800
/// §6.19's name *range* (`RvCoreCsrGprT[0:2]`) declares a run of members under
/// one written identifier, and the binder records the identifier — so two
/// disjoint ranges of one base name look like one name declared twice when the
/// members they declare do not collide at all (measured on opentitan:
/// `jtag_rv_debugger_pkg.sv`). Listed positively rather than as an exclusion
/// list, so a kind added to `vlog_semantic` later is silent until somebody
/// decides it belongs.
fn plain(kind: SymbolKind) -> bool {
matches!(
kind,
SymbolKind::Net
| SymbolKind::Var
| SymbolKind::Param
| SymbolKind::LocalParam
| SymbolKind::Genvar
| SymbolKind::Typedef
| SymbolKind::Instance
| SymbolKind::TfArg
| SymbolKind::StructMember
)
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
DuplicateDeclaration.check(&LintContext::new(src, None))
}
#[test]
fn flags_two_signals_of_one_name() {
let src = "module m;\n logic a;\n logic a;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`a`"), "{}", found[0].message);
assert_eq!(found[0].span.start as usize, src.rfind('a').map(|i| i - 1).unwrap_or(0) + 1);
assert!(found[0].fix.is_none());
}
#[test]
fn flags_two_parameters_two_typedefs_and_two_instances() {
for src in [
"module m;\n parameter int W = 1;\n parameter int W = 2;\nendmodule\n",
"module m;\n typedef logic t;\n typedef bit t;\nendmodule\n",
"module m;\n sub u ();\n sub u ();\nendmodule\n",
] {
assert_eq!(violations(src).len(), 1, "{src}");
}
}
/// The non-ANSI shape: the header names the port, the body declares its
/// direction and then its type. Three declarations, one port, all legal.
#[test]
fn a_non_ansi_port_completed_in_the_body_is_never_flagged() {
let src = "module m (clk);\n input clk;\n logic clk;\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
assert!(violations("module m (clk);\n input wire clk;\nendmodule\n").is_empty());
// An ANSI port redeclared in the body is left alone too, for the same
// reason: a rule that cannot tell the two apart must not accuse.
assert!(violations("module m (input logic clk);\n logic clk;\nendmodule\n").is_empty());
}
#[test]
fn a_prototype_and_its_definition_are_one_declaration() {
let src = "class c;\n extern function void f();\nendclass\n\
function void c::f();\nendfunction\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
let forward = "package p;\n typedef class c;\n class c;\n endclass\nendpackage\n";
assert!(violations(forward).is_empty(), "{:?}", violations(forward));
}
#[test]
fn conditional_arms_are_exclusive_so_they_are_not_flagged() {
let src = "module m;\n`ifdef X\n logic b;\n`else\n logic b;\n`endif\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_generate_scope_elaborates_one_arm_at_a_time() {
let src = "module m;\n\
generate\n\
if (A) begin : g\n\
logic x;\n\
end else begin : g\n\
logic x;\n\
end\n\
endgenerate\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_name_reused_in_a_nested_scope_is_not_a_duplicate() {
// That is shadowing, which is `instance-shadowing`'s subject.
let src =
"module m;\n logic a;\n always_comb begin : blk\n logic a;\n end\nendmodule\n";
assert!(violations(src).is_empty());
// And two modules may each declare `a`.
let two = "module m;\n logic a;\nendmodule\nmodule n;\n logic a;\nendmodule\n";
assert!(violations(two).is_empty());
}
}
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use crate::visit::walk_items;
use vlog_parser::ast::ItemKind;
@@ -21,6 +22,10 @@ impl Rule for EmptyItem {
"drop a `;` that stands where an item belongs"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A lone `;` in a module, generate, package, interface, program or class \
body is a *null item* (IEEE 1800-2017 A.1.4). It is legal and it means \
@@ -0,0 +1,194 @@
//! `endif-comment` — say which `` `ifdef `` an `` `endif `` closes.
use crate::context::LintContext;
use crate::preproc::{directive_operand, directive_word};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use vlog_parser::span::TextRange;
use vlog_parser::token::Token;
/// See [`Rule::doc`].
pub struct EndifComment;
const NAME: &str = "endif-comment";
impl Rule for EndifComment {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"name the condition an `` `endif `` closes in a comment beside it"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn default_on(&self) -> bool {
false
}
fn fix(&self) -> Option<Applicability> {
Some(Applicability::Safe)
}
fn doc(&self) -> &'static str {
"A bare `` `endif `` two hundred lines below its `` `ifdef `` tells \
the reader nothing: which condition just ended, and whether the \
nesting is what they think it is, both take a scroll to answer. \
`` `endif // SYNTHESIS `` answers them in place, which is the same \
argument `mismatched-labels` makes for `end : name`. Verible's \
`endif-comment` (\"Checks that a Verilog `` `endif `` directive is \
followed by a matching comment.\", **disabled** by default) is the \
same rule and the same default.\n\n\
The comment must **name the condition** — any comment on the \
`` `endif ``'s own line that writes the macro name as a word will \
do, so `// SYNTHESIS`, `` // `ifdef SYNTHESIS `` and `/* SYNTHESIS \
*/` all pass. An `` `endif `` whose `` `ifdef `` lucisv cannot see \
(an unbalanced file, a condition opened in an included header) is \
left alone: there is no name to ask for.\n\n\
The fix is **safe** and only offered where there is no comment at \
all: it appends `` // <name> `` after the directive, adding text and \
removing none. A comment that is there but names something else is \
reported without a fix — rewriting somebody's words is not a repair."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut open: Vec<Option<String>> = Vec::new();
let mut out = Vec::new();
for token in ctx.tokens() {
match directive_word(token) {
Some("ifdef") | Some("ifndef") => {
open.push(directive_operand(token).map(str::to_string))
}
Some("endif") => {
// An `endif` with nothing open is an unbalanced file, or a
// condition opened in an included header: no name to ask
// for, so nothing to say.
let Some(Some(name)) = open.pop() else { continue };
if let Some(violation) = judge(ctx, token, &name) {
out.push(violation);
}
}
_ => {}
}
}
out
}
}
/// The finding this `` `endif `` earns, or `None` when its comment names the
/// condition.
fn judge(ctx: &LintContext, token: &Token, name: &str) -> Option<Violation> {
let beside: Vec<&str> = ctx
.comments()
.into_iter()
.filter(|comment| comment.line == token.line && comment.span.start >= token.span.end)
.map(|comment| comment.text.as_str())
.collect();
if beside.iter().any(|text| names(text, name)) {
return None;
}
let violation = Violation::new(
NAME,
format!("`endif` does not say what it closes; write `// {name}`"),
token.span,
);
match beside.is_empty() {
true => Some(violation.with_fix(Fix::safe(vec![(
TextRange::new(token.span.end, token.span.end),
format!(" // {name}"),
)]))),
// There is a comment; it just names something else. Replacing it would
// throw away what somebody wrote.
false => Some(violation),
}
}
/// True when `text` writes `name` as a whole word.
fn names(text: &str, name: &str) -> bool {
let is_part = |c: char| c == '_' || c == '$' || c.is_ascii_alphanumeric();
let mut rest = text;
while let Some(at) = rest.find(name) {
let before = rest[..at].chars().next_back();
let after = rest[at + name.len()..].chars().next();
if !before.is_some_and(is_part) && !after.is_some_and(is_part) {
return true;
}
rest = &rest[at + name.len()..];
}
false
}
#[cfg(test)]
mod tests {
use super::*;
use crate::violation::apply_fixes;
fn violations(src: &str) -> Vec<Violation> {
EndifComment.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_bare_endif_and_offers_the_comment() {
let src = "`ifdef SYNTHESIS\nmodule m;\nendmodule\n`endif\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "`endif");
let fixed = apply_fixes(src, &found, false);
assert_eq!(fixed.output, "`ifdef SYNTHESIS\nmodule m;\nendmodule\n`endif // SYNTHESIS\n");
assert!(violations(&fixed.output).is_empty(), "the fix settles");
}
#[test]
fn a_naming_comment_of_any_shape_passes() {
for comment in ["// SYNTHESIS", "// `ifdef SYNTHESIS", "/* SYNTHESIS */", "//SYNTHESIS"] {
let src = format!("`ifdef SYNTHESIS\nmodule m;\nendmodule\n`endif {comment}\n");
assert!(violations(&src).is_empty(), "{comment}: {:?}", violations(&src));
}
}
#[test]
fn a_comment_naming_something_else_is_reported_without_a_fix() {
let src = "`ifdef SYNTHESIS\nmodule m;\nendmodule\n`endif // done\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].fix.is_none(), "somebody's comment is not ours to rewrite");
}
#[test]
fn a_name_that_only_contains_the_condition_is_not_a_match() {
let src = "`ifdef SYN\nmodule m;\nendmodule\n`endif // SYNTHESIS\n";
assert_eq!(violations(src).len(), 1, "{:?}", violations(src));
}
#[test]
fn nesting_pairs_each_endif_with_its_own_condition() {
let src = "`ifdef A\n`ifdef B\nmodule m;\nendmodule\n`endif\n`endif\n";
let found = violations(src);
assert_eq!(found.len(), 2, "{found:?}");
assert!(found[0].message.contains("// B"), "{}", found[0].message);
assert!(found[1].message.contains("// A"), "{}", found[1].message);
}
#[test]
fn an_ifndef_and_an_else_are_handled_like_the_ifdef() {
let src = "`ifndef A\nmodule m;\nendmodule\n`else\nmodule n;\nendmodule\n`endif\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("// A"), "{}", found[0].message);
}
#[test]
fn an_unbalanced_endif_has_no_name_to_ask_for() {
assert!(violations("`endif\nmodule m;\nendmodule\n").is_empty());
}
#[test]
fn a_comment_on_the_next_line_is_not_beside_the_endif() {
let src = "`ifdef A\nmodule m;\nendmodule\n`endif\n// A\n";
assert_eq!(violations(src).len(), 1);
}
}
@@ -2,8 +2,10 @@
//! or `_t`.
use crate::context::LintContext;
use crate::naming::{is_escaped, is_lower_snake_case};
use crate::naming::{fits_pattern, is_escaped};
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::{ItemKind, TypedefKind};
@@ -22,6 +24,10 @@ impl Rule for EnumNameStyle {
"name enum typedefs in lower_snake_case ending in _e or _t"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A type name that looks like a type name is what makes a declaration \
readable at a glance: `state_e cur_state` says which identifier is the \
@@ -31,7 +37,20 @@ impl Rule for EnumNameStyle {
same shape. Only a `typedef enum` is judged: an anonymous enum has no \
name to check, and giving it one is Verible's separate \
`typedef-enums` idea. Escaped identifiers are exempt, and there is no \
fix: a type rename reaches every use."
fix: a type rename reaches every use.\n\n\
The shape is the `style_regex` option, and its default is \
`[a-z][a-z_0-9]*(_t|_e)` — Verible's pattern with the first character \
pinned to a letter, which is what lucisv's preset checked before the \
option existed and what keeps a leading `_` reported."
}
fn options(&self) -> &'static [OptionSpec] {
&[OptionSpec {
name: "style_regex",
kind: OptionKind::Regex,
default: OptionDefault::Str(DEFAULT_STYLE),
doc: "the pattern an enum typedef's whole name must match",
}]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
@@ -42,13 +61,18 @@ impl Rule for EnumNameStyle {
return;
}
let name = &typedef.name;
let suffixed = name.ends_with("_e") || name.ends_with("_t");
if is_lower_snake_case(name) && suffixed {
if fits_pattern(ctx, NAME, "style_regex", name) {
return;
}
out.push(Violation::new(
NAME,
format!("enum `{name}` is not lower_snake_case ending in `_e` or `_t`"),
crate::naming::style_message(
ctx,
NAME,
"style_regex",
&format!("enum `{name}`"),
"is not lower_snake_case ending in `_e` or `_t`",
),
typedef.name_span,
));
});
@@ -56,6 +80,10 @@ impl Rule for EnumNameStyle {
}
}
/// Today's preset, written as a pattern: `lower_snake_case` (a letter first)
/// ending in `_e` or `_t`.
const DEFAULT_STYLE: &str = "[a-z][a-z_0-9]*(_t|_e)";
#[cfg(test)]
mod tests {
use super::*;
@@ -104,4 +132,31 @@ mod tests {
let src = typedef("state");
assert_eq!(&src[violations(&src)[0].span.as_range()], "state");
}
/// The default pattern is today's preset, character for character: a
/// leading `_` or digit is still rejected, which Verible's own
/// `[a-z_0-9]+(_t|_e)` would accept.
#[test]
fn the_default_pattern_is_the_preset_it_replaced() {
for bad in ["_state_t", "State_t", "state"] {
assert_eq!(violations(&typedef(bad)).len(), 1, "{bad}");
}
for good in ["state_t", "state_e", "s_t", "fifo2_state_e"] {
assert!(violations(&typedef(good)).is_empty(), "{good}");
}
}
#[test]
fn a_configured_pattern_replaces_it_and_is_named_in_the_message() {
let mut options = crate::options::RuleOptions::new();
options.set_raw(NAME, "style_regex", "\"[a-z_0-9]+_e\"").expect("accepted");
let src = typedef("state_t");
let ctx = LintContext::new(&src, None).with_options(&options);
let found = EnumNameStyle.check(&ctx);
assert_eq!(found.len(), 1, "`_t` is no longer accepted");
assert!(found[0].message.contains("[a-z_0-9]+_e"), "{}", found[0].message);
let src = typedef("_state_e");
let ctx = LintContext::new(&src, None).with_options(&options);
assert!(EnumNameStyle.check(&ctx).is_empty(), "and a leading `_` now passes");
}
}
@@ -0,0 +1,330 @@
//! `explicit-begin` — a body is a `begin ... end` block, always.
use crate::context::LintContext;
use crate::options::{OptionDefault, OptionKind, OptionSpec};
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
use crate::visit::{walk_all_stmts, walk_items};
use vlog_parser::ast::{ItemKind, Stmt, StmtKind};
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct ExplicitBegin;
const NAME: &str = "explicit-begin";
/// The eleven constructs Verible lets a project switch on one at a time, each
/// with the keyword a diagnostic names it by.
const ENABLES: [(&str, &str); 11] = [
("always_comb_enable", "always_comb"),
("always_enable", "always"),
("always_ff_enable", "always_ff"),
("always_latch_enable", "always_latch"),
("else_enable", "else"),
("final_enable", "final"),
("for_enable", "for"),
("forever_enable", "forever"),
("if_enable", "if"),
("initial_enable", "initial"),
("while_enable", "while"),
];
impl Rule for ExplicitBegin {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"wrap every body in `begin` and `end`"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"The classic C bug transplanted: `if (a) x = 1;` grows a second \
statement in a later edit, the author indents it, and the compiler \
reads it as unconditional. Writing `begin ... end` from the start \
makes that edit impossible to get wrong, which is why several house \
styles require it. Verible's `explicit-begin` ships **off** — the \
style is far from universal, and a codebase that does not follow it \
would light up on the first run — and lucisv keeps it off for the same \
reason.\n\n\
Eleven `*_enable` options, exactly Verible's, switch the constructs on \
and off one at a time; all are on when the rule is. An `else if` is \
never reported: the `else`'s body is another `if`, which is the \
chained form every style guide writes. A null body (`if (a) ;`) is \
left to `suspicious-semicolon`, which has more to say about it. The \
fix wraps the body in `begin`/`end` and is **safe** — a block around \
one statement changes nothing — and running the formatter afterwards \
lays it out."
}
fn default_on(&self) -> bool {
false
}
fn fix(&self) -> Option<Applicability> {
Some(Applicability::Safe)
}
fn options(&self) -> &'static [OptionSpec] {
// Written out rather than generated, because a spec table is a
// `static` and every entry needs its own `&'static str` doc.
&[
OptionSpec {
name: "always_comb_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `always_comb`",
},
OptionSpec {
name: "always_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `always`",
},
OptionSpec {
name: "always_ff_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `always_ff`",
},
OptionSpec {
name: "always_latch_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `always_latch`",
},
OptionSpec {
name: "else_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `else`",
},
OptionSpec {
name: "final_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of a `final`",
},
OptionSpec {
name: "for_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of a `for` loop",
},
OptionSpec {
name: "forever_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of a `forever` loop",
},
OptionSpec {
name: "if_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `if`",
},
OptionSpec {
name: "initial_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of an `initial`",
},
OptionSpec {
name: "while_enable",
kind: OptionKind::Bool,
default: OptionDefault::Bool(true),
doc: "check the body of a `while` loop",
},
]
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
let mut report = |keyword: &'static str, body: &Stmt| {
if !enabled(ctx, keyword) || is_block(body) || matches!(body.kind, StmtKind::Null) {
return;
}
out.push(
Violation::new(
NAME,
format!("`{keyword}` body is not a `begin ... end` block"),
body.span,
)
.with_fix(Fix::safe(vec![
(TextRange::new(body.span.start, body.span.start), "begin ".to_string()),
(TextRange::new(body.span.end, body.span.end), " end".to_string()),
])),
);
};
walk_items(ctx.file(), &mut |item| match &item.kind {
ItemKind::Always { kw, stmt } => {
let keyword = ENABLES
.iter()
.find_map(|(_, word)| (*word == kw).then_some(*word))
.unwrap_or("always");
if let Some(body) = procedural_body(stmt) {
report(keyword, body);
}
}
ItemKind::Initial(stmt) => {
if let Some(body) = procedural_body(stmt) {
report("initial", body);
}
}
ItemKind::Final(stmt) => {
if let Some(body) = procedural_body(stmt) {
report("final", body);
}
}
_ => {}
});
walk_all_stmts(ctx.file(), &mut |stmt| match &stmt.kind {
StmtKind::If { then, els, .. } => {
report("if", then);
// `else if` is the chained form, not a missing block.
if let Some(els) = els {
if !matches!(els.kind, StmtKind::If { .. }) {
report("else", els);
}
}
}
StmtKind::For { body, .. } => report("for", body),
StmtKind::While { body, .. } => report("while", body),
StmtKind::Forever { body } => report("forever", body),
_ => {}
});
out
}
}
/// Whether the run wants this construct checked.
fn enabled(ctx: &LintContext, keyword: &str) -> bool {
ENABLES
.iter()
.find(|(_, word)| *word == keyword)
.is_none_or(|(option, _)| ctx.option_bool(NAME, option))
}
/// The statement a procedural block really runs: the one under its timing
/// control, when it has one (`always_ff @(posedge clk) q <= d;`).
///
/// `None` for a timing control with no body at all (`always @(posedge clk);`),
/// which has nothing to wrap.
fn procedural_body(stmt: &Stmt) -> Option<&Stmt> {
match &stmt.kind {
StmtKind::Timing { stmt, .. } => stmt.as_deref(),
_ => Some(stmt),
}
}
/// Whether this statement is already a block.
fn is_block(stmt: &Stmt) -> bool {
matches!(stmt.kind, StmtKind::Block { .. } | StmtKind::ForkJoin { .. })
}
#[cfg(test)]
mod tests {
use super::*;
use crate::options::RuleOptions;
use crate::violation::apply_fixes;
fn violations(src: &str) -> Vec<Violation> {
ExplicitBegin.check(&LintContext::new(src, None))
}
#[test]
fn it_is_off_by_default_and_takes_veribles_eleven_options() {
assert!(!ExplicitBegin.default_on());
let names: Vec<&str> = ExplicitBegin.options().iter().map(|spec| spec.name).collect();
assert_eq!(names.len(), 11);
assert!(names.contains(&"if_enable") && names.contains(&"always_ff_enable"));
}
#[test]
fn flags_an_unblocked_if_body_and_wraps_it() {
let src = "module m;\n initial begin\n if (a) x = 1;\n end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "x = 1;");
let fixed = apply_fixes(src, &found, false);
assert_eq!(
fixed.output,
"module m;\n initial begin\n if (a) begin x = 1; end\n end\nendmodule\n"
);
assert!(violations(&fixed.output).is_empty(), "the fix satisfies the rule");
}
#[test]
fn a_blocked_body_is_clean() {
let src = "module m;\n initial begin\n if (a) begin\n x = 1;\n end\n end\n\
endmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn every_construct_is_covered() {
let src = "module m;\n\
\x20 always_comb x = 1;\n\
\x20 always_ff @(posedge clk) q <= d;\n\
\x20 always @(a) y = 2;\n\
\x20 always_latch if (en) z = 3;\n\
\x20 initial x = 0;\n\
\x20 final $display(\"bye\");\n\
endmodule\n";
let found = violations(src);
// Six bodies, plus the `if` inside the always_latch.
assert_eq!(found.len(), 7, "{:#?}", found.iter().map(|v| &v.message).collect::<Vec<_>>());
let src = "module m;\n initial begin\n\
\x20 for (int i = 0; i < 2; i++) x = i;\n\
\x20 while (a) y = 1;\n\
\x20 forever z = 2;\n\
\x20 end\nendmodule\n";
assert_eq!(violations(src).len(), 3, "{:?}", violations(src));
}
#[test]
fn an_else_if_chain_is_not_a_missing_block() {
let src = "module m;\n initial begin\n if (a) begin\n x = 1;\n end\n\
\x20 else if (b) begin\n x = 2;\n end\n end\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_bare_else_body_is_reported() {
let src =
"module m;\n initial begin\n if (a) begin\n x = 1;\n end else x = 2;\n\
\x20 end\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`else`"), "{}", found[0].message);
}
#[test]
fn a_null_body_is_left_to_suspicious_semicolon() {
let src = "module m;\n initial begin\n if (a) ;\n end\nendmodule\n";
assert!(violations(src).is_empty());
}
#[test]
fn each_option_switches_its_own_construct_off() {
let src = "module m;\n initial begin\n if (a) x = 1;\n while (b) y = 2;\n end\n\
endmodule\n";
assert_eq!(violations(src).len(), 2);
let mut options = RuleOptions::new();
options.set_raw(NAME, "if_enable", "false").expect("accepted");
let found = ExplicitBegin.check(&LintContext::new(src, None).with_options(&options));
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`while`"), "{}", found[0].message);
}
#[test]
fn a_fork_join_body_is_already_a_block() {
let src = "module m;\n initial fork\n x = 1;\n join\nendmodule\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
}
@@ -0,0 +1,149 @@
//! `explicit-function-lifetime` — say `automatic` or `static` outside a class.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_items_scoped, ItemScope};
use vlog_parser::ast::ItemKind;
/// See [`Rule::doc`].
pub struct ExplicitFunctionLifetime;
const NAME: &str = "explicit-function-lifetime";
/// The two words that state a lifetime, wherever a subroutine writes them.
pub(crate) const LIFETIMES: [&str; 2] = ["automatic", "static"];
impl Rule for ExplicitFunctionLifetime {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"state `automatic` or `static` on a function declared outside a class"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A function with no stated lifetime is `static` in a module and \
`automatic` in a class (IEEE 1800 §13.4.2), and a static function's \
locals are shared by every call — so one written without the keyword \
is a re-entrancy bug waiting for the second caller, and a reader \
cannot tell whether the author knew. Writing the word costs nine \
characters and removes the question. Verible's \
`explicit-function-lifetime` (\"Checks that every function declared \
outside of a class is declared with an explicit lifetime.\", enabled \
by default) is the same rule and the same default; a class method is \
exempt in both, because there the default is already the safe one.\n\n\
A body-less **prototype** — `extern function f;`, a `pure virtual`, a \
DPI import — is not judged: it declares no locals, and the definition \
that follows is where the lifetime belongs. Nor is an **out-of-body \
definition** (`function cls::f(...); … endfunction`), which is \
**wider than Verible**: lexically it sits outside the class, and \
Verible reports it, but it *is* a class method and its lifetime is \
already automatic — 948 of the 960 opentitan findings this rule and \
its task twin produced before the exemption were exactly that shape. \
No automatic fix: \
`automatic` is the answer a reader expects and `static` is what the \
language would have picked, so choosing between them changes what \
the code does."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items_scoped(ctx.file(), &mut |scope, item| {
let ItemKind::Function(decl) = &item.kind else { return };
// An out-of-body definition (`function cls::f(...)`) is a class
// method written outside the class body; `scope` is non-empty for
// exactly those.
if scope == ItemScope::Class
|| !decl.scope.is_empty()
|| decl.is_prototype
|| decl.dpi.is_some()
{
return;
}
if decl.qualifiers.iter().any(|q| LIFETIMES.contains(&q.text.as_str())) {
return;
}
out.push(Violation::new(
NAME,
format!(
"function `{}` has no explicit lifetime; write `automatic` or `static`",
decl.name
),
decl.name_span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ExplicitFunctionLifetime.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_module_function_and_points_at_its_name() {
let src = "module m;\n function int f(int x);\n return x;\n endfunction\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "f");
assert!(found[0].fix.is_none());
}
#[test]
fn either_keyword_satisfies_the_rule() {
for kw in ["automatic", "static"] {
let src = format!(
"module m;\n function {kw} int f(int x);\n return x;\n endfunction\nendmodule\n"
);
assert!(violations(&src).is_empty(), "{kw}: {:?}", violations(&src));
}
}
#[test]
fn a_class_method_is_exempt() {
let src = "class c;\n function int f(int x);\n return x;\n endfunction\nendclass\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_package_or_file_scope_function_is_judged() {
let pkg = "package p;\n function int f();\n return 0;\n endfunction\nendpackage\n";
assert_eq!(violations(pkg).len(), 1);
let top = "function int f();\n return 0;\nendfunction\n";
assert_eq!(violations(top).len(), 1);
}
#[test]
fn a_prototype_declares_no_locals() {
let src = "class c;\n extern function int f();\nendclass\n\
import \"DPI-C\" function int c_f(input int x);\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
/// An `extern` method defined outside its class body is still a class
/// method; Verible reports it, lucisv does not (see the rule's doc).
#[test]
fn an_out_of_body_definition_is_a_class_method() {
let src = "class c;\n extern function int f();\nendclass\n\
function c::f();\n return 0;\nendfunction\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
#[test]
fn a_class_nested_in_a_package_is_still_a_class() {
let src = "package p;\n class c;\n function int f();\n return 0;\n \
endfunction\n endclass\nendpackage\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
}
@@ -0,0 +1,152 @@
//! `explicit-function-task-parameter-type` — every formal gets a storage type.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::walk_items;
use vlog_parser::ast::{ItemKind, ListElem, TfArg};
/// See [`Rule::doc`].
pub struct ExplicitFunctionTaskParameterType;
const NAME: &str = "explicit-function-task-parameter-type";
impl Rule for ExplicitFunctionTaskParameterType {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"declare a storage type on every function and task argument"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn doc(&self) -> &'static str {
"A task or function formal written without a type is a **one-bit \
`logic`** (IEEE 1800 §13.3), so `function f(input a);` truncates \
every caller's argument to its low bit and nothing complains — the \
function simply returns the wrong answer for anything wider than a \
flag. Verible's `explicit-function-task-parameter-type` (\"Checks \
that every function and task parameter is declared with an explicit \
storage type.\", enabled by default) is the same rule and the same \
default. **A continuation formal inherits**: in `f(input int a, b)` \
the `b` is an `int`, so only the argument that *opens* a declaration \
— the first one, or the first after a direction keyword — is judged, \
which is exactly the language's own rule. A DPI import's unnamed \
formal (`import \"DPI-C\" function int f(int);`) names a type and no \
identifier and is not this rule's subject. No automatic fix: only the \
author knows how wide the argument was meant to be."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
let (kw, args) = match &item.kind {
ItemKind::Function(decl) => ("function", &decl.args),
ItemKind::Task(decl) => ("task", &decl.args),
_ => return,
};
out.extend(untyped(kw, args));
});
out
}
}
/// The formals of one argument list that end up implicitly typed.
///
/// Walked in order with the declaration's type carried along, which is how the
/// language reads them: a formal that writes a type sets it, a formal that
/// writes a direction keyword opens a new declaration (and so a new type,
/// implicit until written), and a formal that writes neither inherits whatever
/// is in force.
fn untyped(kw: &'static str, args: &[ListElem<TfArg>]) -> Vec<Violation> {
let mut out = Vec::new();
let mut opened = false;
for arg in args.iter().filter_map(ListElem::ok) {
let opens = !opened || arg.dir.is_some() || !arg.ty.is_implicit();
opened = true;
if !opens || !arg.ty.is_implicit() || arg.name.is_empty() {
continue;
}
out.push(Violation::new(
NAME,
format!("{kw} argument `{}` has no storage type; it is a 1-bit `logic`", arg.name),
arg.span,
));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ExplicitFunctionTaskParameterType.check(&LintContext::new(src, None))
}
fn wrap(header: &str) -> String {
format!("module m;\n {header}\n endfunction\nendmodule\n")
}
#[test]
fn flags_an_untyped_formal() {
let src = wrap("function void f(input a);");
let found = violations(&src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`a`"), "{}", found[0].message);
assert!(found[0].message.contains("1-bit"), "{}", found[0].message);
assert!(found[0].fix.is_none());
}
#[test]
fn a_typed_formal_is_what_the_rule_wants() {
for header in [
"function void f(input logic a);",
"function void f(input int a);",
"function void f(input logic [7:0] a);",
"function void f(my_t a);",
"function void f();",
] {
assert!(
violations(&wrap(header)).is_empty(),
"{header}: {:?}",
violations(&wrap(header))
);
}
}
#[test]
fn a_continuation_formal_inherits_the_type_before_it() {
// `b` is an `int`, so only a genuinely untyped run may be reported.
assert!(violations(&wrap("function void f(input int a, b);")).is_empty());
// ... and a new direction keyword opens a new, untyped declaration.
let found = violations(&wrap("function void f(input int a, output b);"));
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("`b`"), "{}", found[0].message);
}
#[test]
fn a_task_is_judged_the_same_way() {
let src = "module m;\n task t(input a);\n endtask\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert!(found[0].message.contains("task"), "{}", found[0].message);
}
#[test]
fn an_unnamed_dpi_formal_is_not_this_rules_subject() {
let src = "import \"DPI-C\" function int f(int, chandle);\n";
assert!(violations(src).is_empty());
}
#[test]
fn a_class_method_is_reached() {
let src = "class c;\n function void f(input a);\n endfunction\nendclass\n";
assert_eq!(violations(src).len(), 1);
}
}
@@ -2,6 +2,7 @@
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_all_stmts, walk_items, walk_param_ports};
use vlog_parser::ast::{ItemKind, ParamDecl, StmtKind};
@@ -20,6 +21,10 @@ impl Rule for ExplicitParameterStorageType {
"declare a storage type on every parameter"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"A parameter with no declared type takes its type from whatever it is \
assigned — and an override at instantiation can change that type, not \
@@ -0,0 +1,120 @@
//! `explicit-task-lifetime` — say `automatic` or `static` outside a class.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::rules::explicit_function_lifetime::LIFETIMES;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::visit::{walk_items_scoped, ItemScope};
use vlog_parser::ast::ItemKind;
/// See [`Rule::doc`].
pub struct ExplicitTaskLifetime;
const NAME: &str = "explicit-task-lifetime";
impl Rule for ExplicitTaskLifetime {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"state `automatic` or `static` on a task declared outside a class"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"The same argument `explicit-function-lifetime` makes, and worse: a \
task can block, so a `static` one is routinely called from two \
processes at once and its locals are one set of variables shared \
between them (IEEE 1800 §13.4.2). A task with no stated lifetime is \
`static` in a module and `automatic` in a class, and nothing in the \
source says which the author meant. Verible's \
`explicit-task-lifetime` (\"Checks that every task declared outside \
of a class is declared with an explicit lifetime.\", enabled by \
default) is the same rule and the same default.\n\n\
A body-less prototype, a DPI import and an out-of-body definition \
(`task cls::t(); … endtask`) are not judged, and no automatic fix is \
offered — all for the reasons `explicit-function-lifetime` gives."
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let mut out = Vec::new();
walk_items_scoped(ctx.file(), &mut |scope, item| {
let ItemKind::Task(decl) = &item.kind else { return };
// An out-of-body definition (`function cls::f(...)`) is a class
// method written outside the class body; `scope` is non-empty for
// exactly those.
if scope == ItemScope::Class
|| !decl.scope.is_empty()
|| decl.is_prototype
|| decl.dpi.is_some()
{
return;
}
if decl.qualifiers.iter().any(|q| LIFETIMES.contains(&q.text.as_str())) {
return;
}
out.push(Violation::new(
NAME,
format!(
"task `{}` has no explicit lifetime; write `automatic` or `static`",
decl.name
),
decl.name_span,
));
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn violations(src: &str) -> Vec<Violation> {
ExplicitTaskLifetime.check(&LintContext::new(src, None))
}
#[test]
fn flags_a_module_task_and_points_at_its_name() {
let src = "module m;\n task t();\n endtask\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(&src[found[0].span.as_range()], "t");
assert!(found[0].fix.is_none());
}
#[test]
fn either_keyword_satisfies_the_rule() {
for kw in ["automatic", "static"] {
let src = format!("module m;\n task {kw} t();\n endtask\nendmodule\n");
assert!(violations(&src).is_empty(), "{kw}: {:?}", violations(&src));
}
}
#[test]
fn a_class_method_is_exempt() {
assert!(violations("class c;\n task t();\n endtask\nendclass\n").is_empty());
}
#[test]
fn a_function_is_the_other_rules_business() {
let src = "module m;\n function int f();\n return 0;\n endfunction\nendmodule\n";
assert!(violations(src).is_empty());
}
#[test]
fn a_prototype_declares_no_locals() {
assert!(violations("class c;\n extern task t();\nendclass\n").is_empty());
}
#[test]
fn an_out_of_body_definition_is_a_class_method() {
let src = "class c;\n extern task t();\nendclass\ntask c::t();\nendtask\n";
assert!(violations(src).is_empty(), "{:?}", violations(src));
}
}
Loaded 100 of 392 files, more files were not shown because too many files have changed in this diff. Show more