Compare commits

...
32 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
243 changed files with 42637 additions and 2215 deletions

No files matched your search

+259
View File
@@ -4,6 +4,265 @@ 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
Generated
+10 -8
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.40.0"
version = "0.49.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.40.0"
version = "0.49.0"
[[package]]
name = "lucisv_server"
version = "0.40.0"
version = "0.49.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,15 +248,16 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.40.0"
version = "0.49.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.40.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.40.0"
version = "0.49.0"
[[package]]
name = "vlog_refactor"
version = "0.40.0"
version = "0.49.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
"vlog_semantic",
]
[[package]]
name = "vlog_semantic"
version = "0.40.0"
version = "0.49.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.40.0"
version = "0.49.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+111 -13
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
@@ -275,6 +292,7 @@ makes an editor's red squiggle worth believing.
| `banned-declared-name-patterns` | style | — | no declared name matching a project's own list (off) |
| `explicit-begin` | style | safe | every body is a `begin ... end` block (off by default) |
| `unused-waiver` | style | — | waivers that suppress nothing |
| `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 |
@@ -387,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 |
|---|---|---|
@@ -401,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:
@@ -414,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
@@ -871,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.
@@ -903,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
+1518 -29
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);
+224 -50
View File
@@ -16,7 +16,8 @@ use vlog_formatter::fence::{self, Region};
use vlog_formatter::Config;
use vlog_linter::words;
use vlog_linter::{
apply_fixes, lint, Fix, MentionOracle, ParsedSource, Rule, RuleOptions, Violation,
apply_fixes, lint_with, ExternalWaivers, Fix, MentionOracle, ParsedSource, Rule, RuleOptions,
Violation, WaiverUse,
};
use vlog_parser::LineIndex;
@@ -46,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.
@@ -61,6 +71,11 @@ pub struct Census {
/// 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 {
@@ -75,30 +90,49 @@ impl Census {
/// of every file on top of the lex the word census already pays for, so
/// it is built only when some enabled rule asks — measured on opentitan
/// `hw/` in `docs/features/linter-expansion-1/README.md`.
fn of(jobs: &[Job], interfaces: bool) -> Census {
type PerFile = (Vec<String>, Vec<(String, Option<vlog_linter::ModuleInterface>)>);
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| {
let Ok(src) = std::fs::read_to_string(&job.path) else {
return (Vec::new(), Vec::new());
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());
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()))
(
words::harvest(parsed.tokens()),
vlog_linter::module_interfaces(parsed.file()),
exports,
)
})
.collect();
let mut files: HashMap<String, u32> = HashMap::new();
let mut units: HashMap<String, Option<vlog_linter::ModuleInterface>> = HashMap::new();
for (words, declared) in per_file {
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.
@@ -112,7 +146,7 @@ impl Census {
.or_insert(interface);
}
}
Census { files, interfaces: units }
Census { files, interfaces: units, packages: exported }
}
/// How many files in the run write `name` down.
@@ -124,6 +158,15 @@ impl Census {
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
@@ -148,6 +191,13 @@ impl MentionOracle for Elsewhere<'_> {
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.
@@ -163,6 +213,7 @@ 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());
@@ -172,10 +223,64 @@ pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Res
let options = rule_options(&file_config)?;
jobs.push(Job { path, config, rules, options });
}
let wanted = jobs.iter().any(|job| job.rules.iter().any(|rule| rule.needs_workspace()));
let interfaces = jobs.iter().any(|job| job.rules.iter().any(|rule| reads_interfaces(*rule)));
let census = (workspace && wanted).then(|| Census::of(&jobs, workspace && interfaces));
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
@@ -216,6 +321,12 @@ 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.
fn pick<'a>(cli: &'a [String], config: Option<&'a [String]>) -> &'a [String] {
if cli.is_empty() {
@@ -234,12 +345,30 @@ 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 {
@@ -247,9 +376,20 @@ pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
.jobs
.par_iter()
.map(|job| {
check_one(&job.path, &job.config, opts, &job.rules, &job.options, plan.census.as_ref())
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.
@@ -257,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(
@@ -265,32 +436,34 @@ pub fn check_stdin(
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, options, 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],
options: &RuleOptions,
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),
};
@@ -300,14 +473,13 @@ fn check_one(
};
let outcome = crate::catch_panic(|| {
if opts.fix {
fix_source(&src, file, config, opts, rules, options, census)
fix_source(&src, file, opts, pass)
} else {
let (violations, lex_error) =
run_rules(&src, Some(file.to_path_buf()), config, rules, options, 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}")),
};
@@ -322,21 +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],
options: &RuleOptions,
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
@@ -360,7 +531,8 @@ fn run_rules(
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
@@ -399,16 +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],
options: &RuleOptions,
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, options, 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);
@@ -417,11 +588,14 @@ fn fix_source(
}
fixed += round.applied;
text = round.output;
(violations, lex_error) =
run_rules(&text, Some(file.to_path_buf()), config, rules, options, 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.
+64 -6
View File
@@ -128,7 +128,17 @@ fn run_check(opts: &Options) -> ExitCode {
return ExitCode::from(2);
}
};
return lint::check_stdin(opts, &src, &config, &rules, &options);
// 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,
@@ -356,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.
@@ -405,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();
@@ -592,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();
+219
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");
@@ -935,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);
@@ -2012,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));
}
+263 -14
View File
@@ -7,11 +7,24 @@
//! gets the bytes, and a `rename` over the target publishes them in one step
//! that either happened or did not.
//!
//! See `docs/features/small-items-3/README.md`.
//! 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;
use std::io;
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.
///
@@ -21,6 +34,12 @@ use std::path::{Path, PathBuf};
/// 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
@@ -28,26 +47,22 @@ use std::path::{Path, PathBuf};
/// 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 fs::metadata(&target).is_ok_and(|m| m.permissions().readonly()) {
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 = temp_path(&target)?;
if let Err(e) = fs::write(&tmp, bytes) {
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);
}
// A file someone made read-only, or executable, keeps its mode: the temp
// was created with the process umask, not with the target's bits. No
// target means a new file, which takes the umask as `fs::write` would.
if let Ok(meta) = fs::metadata(&target) {
let _ = fs::set_permissions(&tmp, meta.permissions());
}
drop(file);
if let Err(e) = fs::rename(&tmp, &target) {
let _ = fs::remove_file(&tmp);
return Err(e);
@@ -55,16 +70,106 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
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 so two lucisv runs over one tree cannot collide.
/// 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!(".{}.lucisv-tmp", std::process::id()));
tmp.push(format!(".{}.{n}.lucisv-tmp", std::process::id()));
Ok(dir.join(tmp))
}
@@ -199,4 +304,148 @@ mod tests {
);
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);
}
}
+161 -7
View File
@@ -30,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
@@ -37,6 +41,15 @@ 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.
///
@@ -93,8 +106,10 @@ pub fn parse(text: &str) -> Result<FileConfig, String> {
enum Table {
/// Before any header: the formatter's own keys.
Top,
/// `[lint]`: `select` and `ignore`.
/// `[lint]`: `select`, `ignore` and `waivers`.
Lint,
/// `[format]`: the layout keys that are off by default.
Format,
/// `[lint.<rule>]`: that rule's options.
Rule(String),
}
@@ -106,13 +121,17 @@ fn parse_entry(
number: usize,
) -> Result<(), String> {
if line.starts_with('[') {
// `[lint]` carries `select`/`ignore`; `[lint.<rule>]` carries that
// `[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]" {
*table = Table::Lint;
return Ok(());
}
if line == "[format]" {
*table = Table::Format;
return Ok(());
}
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>]`"));
@@ -121,7 +140,8 @@ fn parse_entry(
return Ok(());
}
return Err(format!(
"unknown table `{line}` (the tables are `[lint]` and `[lint.<rule-name>]`)"
"unknown table `{line}` \
(the tables are `[format]`, `[lint]` and `[lint.<rule-name>]`)"
));
}
let (key, value) =
@@ -132,6 +152,7 @@ fn parse_entry(
return Err(format!("`{key}` has no value"));
}
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 => {}
@@ -155,19 +176,59 @@ fn parse_entry(
}
_ => Err(format!(
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
select, ignore under `[lint]`; and a rule's own options under \
`[lint.<rule-name>]`)"
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() {
@@ -359,10 +420,16 @@ 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)
@@ -428,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());
@@ -498,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]
+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");
+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();
}
}
+86
View File
@@ -755,6 +755,92 @@ endmodule
assert_eq!(labels, ["clk_renamed:", "rst_n:", "data:"]);
}
// ------------------------------------------------------------------
// the default scope (TODO §37.2 / `performance_take2.md` §4b, §8)
// ------------------------------------------------------------------
/// An opentitan-shaped tree: an IP block with its RTL and its testbench,
/// and a shared library folder outside that block. Opening
/// `ip/aes/dv/tb/tb.sv` at the shipped `scopeDepth` of 2 raises to
/// `ip/aes`, so `ip/aes/rtl/sub.sv` is indexed and `dv/common/far.sv` is
/// not — which is exactly the shape `hw/ip/aes/dv/tb/tb.sv` has against
/// `hw/dv/sv/common_ifs/pins_if.sv`.
fn default_scoped(name: &str) -> (Tree, Workspace, Uri, &'static str) {
const TB: &str =
"module tb;\n sub u_sub (clk, rst_n, data);\n far u_far (a);\nendmodule\n";
let tree = Tree::new(name);
fs::create_dir_all(tree.path.join("ip/aes/rtl")).expect("dirs");
fs::create_dir_all(tree.path.join("ip/aes/dv/tb")).expect("dirs");
fs::create_dir_all(tree.path.join("dv/common")).expect("dirs");
tree.write("ip/aes/rtl/sub.sv", SUB);
tree.write("dv/common/far.sv", "module far (\n input logic a\n);\nendmodule\n");
let tb = tree.write("ip/aes/dv/tb/tb.sv", TB);
let mut ws = Workspace::default();
// The shipped default: no `index.scope`, `scopeDepth` 2.
ws.set_client_settings(crate::settings::ClientSettings::default());
ws.adopt_roots(vec![tree.path.clone()]);
let uri = path_to_uri(&tb).expect("uri");
ws.set_document(uri.clone(), TB.to_string());
ws.rebuild_index();
(tree, ws, uri, TB)
}
#[test]
fn the_default_scope_hints_a_module_the_didopen_widen_reached() {
// `performance_take2.md` §4b measured 0 hints at the default scope
// where the workspace scope gives 4, and §8 filed it as a correctness
// gap. It is not one: the hints that scope answers are exactly the
// instantiations whose module the widen reached.
let (tree, ws, uri, _) = default_scoped("default_scope");
assert!(
ws.index().files().iter().any(|f| f.ends_with("sub.sv")),
"the widen reached the block's own RTL: {:?}",
ws.index().files()
);
assert!(
!ws.index().files().iter().any(|f| f.ends_with("far.sv")),
"and not the library folder beside it"
);
let hints = inlay_hints(&ws, &uri, everything());
let labels: Vec<String> = hints
.into_iter()
.map(|h| {
let InlayHintLabel::String(s) = h.label else { panic!("string") };
s
})
.collect();
assert_eq!(labels, ["clk:", "rst_n:", "data:"], "the in-scope instantiation is hinted");
drop(tree);
}
#[test]
fn an_out_of_scope_module_is_unhinted_exactly_as_it_is_undefined() {
// The other half of the same finding: the `far` instantiation gets no
// hints — and go-to-definition and hover give nothing for it either.
// The zero is the scope's, not this module's; inlay uses the same
// `module_definition` lookup its neighbours do.
let (tree, ws, uri, tb) = default_scoped("out_of_scope");
let hints = inlay_hints(&ws, &uri, everything());
assert!(
hints.iter().all(|hint| hint.position.line != 2),
"nothing on the `far` line: {hints:#?}"
);
let far = tb.find("far u_far").expect("the instantiation") as u32;
assert!(crate::nav::definition(&ws, &uri, far).is_empty(), "nor does F12 answer");
assert!(crate::hover::hover(&ws, &uri, far).is_none(), "nor does hover");
// And the moment the scope reaches it, all three answer.
let mut wide = Workspace::default();
wide.open_whole_workspace(vec![tree.path.clone()]);
wide.set_document(uri.clone(), tb.to_string());
let hints = inlay_hints(&wide, &uri, everything());
assert_eq!(hints.len(), 4, "three ports plus `far`'s one: {hints:#?}");
assert_eq!(crate::nav::definition(&wide, &uri, far).len(), 1);
}
/// Order-of-magnitude perf checks, not run as part of the ordinary suite:
/// timing assertions in a shared CI runner are flaky by nature. Run with
/// `cargo test --release -p lucisv_server --bin lucisv-server qa_perf -- --ignored --nocapture`.
+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));
}
}
+271 -28
View File
@@ -10,14 +10,26 @@
//! 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, ModuleInterface, Rule,
RuleOptions, Severity, Violation,
default_rules, lint_with, workspace_rules, Exports, ExternalWaivers, LintContext,
MentionOracle, ModuleInterface, Rule, RuleOptions, Severity, Violation,
};
use vlog_semantic::{FileId, SymbolKind, WorkspaceIndex};
@@ -41,6 +53,14 @@ pub struct LintRun<'a> {
/// 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<'_> {
@@ -50,6 +70,8 @@ impl Default for LintRun<'_> {
oracle: None,
options: RuleOptions::new(),
line_length: DEFAULT_LINE_LENGTH,
external: ExternalWaivers::default(),
problems: ConfigProblems::default(),
}
}
}
@@ -71,10 +93,36 @@ 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 rules = enabled_rules(ws.client_settings(), workspace);
let oracle = workspace.then_some(IndexMentions { index, own });
let (options, line_length) = configured(ws.client_settings(), doc);
LintRun { rules, oracle, options, line_length }
// 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.
@@ -109,51 +157,139 @@ impl<'a> LintRun<'a> {
/// 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) {
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 here rather than reported:
// `format::settings_for` already surfaces a `lucisv.toml` problem to
// the user, and `lucisv check` fails the run over it with file and
// line, which is where a config error belongs.
let _ = options.set_raw(&entry.rule, &entry.key, &entry.raw);
// 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)
(options, width, file, problems)
}
/// Which rules a buffer is linted with, given what the editor's settings say.
/// 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;
/// `--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.
/// one a user reaches for when nothing else worked; when the editor names
/// nothing there either, the project's `[lint] ignore` removes instead.
///
/// Rungs 2 and 5 accept a severity word wherever a rule name fits.
pub fn enabled_rules(settings: &ClientSettings, has_oracle: bool) -> Vec<&'static dyn Rule> {
let base = if settings.lint_select.is_empty() {
/// 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(&settings.lint_select)
named(select)
};
let mut on: BTreeSet<&'static str> = base.iter().map(|rule| rule.name()).collect();
@@ -172,12 +308,22 @@ pub fn enabled_rules(settings: &ClientSettings, has_oracle: bool) -> Vec<&'stati
on.remove(rule.name());
}
}
for rule in named(&settings.lint_ignore) {
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.
@@ -236,6 +382,18 @@ impl MentionOracle for IndexMentions<'_> {
}
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
@@ -256,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
@@ -274,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
@@ -359,6 +528,23 @@ 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");
@@ -449,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);
@@ -469,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]
@@ -548,8 +734,14 @@ mod tests {
/// 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, oracle).into_iter().map(|rule| rule.name()).collect()
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();
@@ -711,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]
@@ -719,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
+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,
@@ -25,7 +25,7 @@ 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
@@ -259,6 +259,38 @@ impl Server {
},
);
}
// 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.
@@ -322,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");
}
+131 -10
View File
@@ -106,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`.
@@ -202,6 +208,27 @@ pub struct ClientSettings {
/// 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.
@@ -216,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,
@@ -232,6 +260,8 @@ impl Default for ClientSettings {
lint_rules: BTreeMap::new(),
lint_options: RuleOptions::new(),
lint_option_warnings: Vec::new(),
lint_name_warnings: Vec::new(),
lint_waivers: Vec::new(),
}
}
}
@@ -246,8 +276,14 @@ fn every_class_on() -> BTreeMap<Severity, bool> {
///
/// Its only use is equality — the server compares it across a settings change
/// to decide whether every open file must be published again.
pub type LintSelection =
(Vec<String>, Vec<String>, BTreeMap<Severity, bool>, BTreeMap<String, bool>, RuleOptions);
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.
///
@@ -262,6 +298,9 @@ pub fn lint_selection(settings: &ClientSettings) -> LintSelection {
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(),
)
}
@@ -293,11 +332,17 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
// 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
@@ -334,25 +379,44 @@ 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 that names neither a
/// rule nor a severity class.
/// 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::rules_named(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.
@@ -878,6 +942,39 @@ mod tests {
}}}));
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
@@ -957,6 +1054,30 @@ mod tests {
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]
+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)]
File diff suppressed because it is too large. Load diff
+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 {
+28 -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),
@@ -310,8 +325,17 @@ impl<'a> Fmt<'a> {
// strictly. Printed verbatim so nothing is lost if that ever
// changes — see `ListItem::from_raw`.
ExprKind::Error(raw) => self.raw_inline(raw),
ExprKind::MinTypMax { min, typ, max } => {
concat(vec![self.expr(min), text(":"), self.expr(typ), text(":"), self.expr(max)])
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)
}
}
}
+103 -15
View File
@@ -340,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)
}
}
@@ -386,10 +439,45 @@ fn holds_verbatim_value(list: &[ListElem<Connection>]) -> bool {
})
}
/// `(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)
}
+54 -7
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;`, `;;`.
@@ -352,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
+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 }
}
}
+86 -25
View File
@@ -316,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));
@@ -353,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(", "));
@@ -386,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("}")])
}
}
+15 -4
View File
@@ -245,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
+39 -1
View File
@@ -7,7 +7,7 @@ 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;
@@ -158,6 +158,34 @@ pub trait MentionOracle: Sync {
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.
@@ -384,6 +412,16 @@ impl<'a> LintContext<'a> {
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()
+10 -1
View File
@@ -86,7 +86,8 @@ pub(crate) fn walk_exprs(file: &SourceFile, f: &mut dyn FnMut(&Expr)) {
root(expr);
}
}
StmtKind::ExprStmt(expr) | StmtKind::EventTrigger(expr) => root(expr),
StmtKind::ExprStmt(expr) => root(expr),
StmtKind::EventTrigger(t) => root(&t.expr),
StmtKind::If { cond, .. } => root(cond),
StmtKind::Case { expr, items, .. } => {
root(expr);
@@ -244,6 +245,14 @@ fn descend(expr: &Expr, f: &mut dyn FnMut(&Expr)) {
}
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) => {
+34 -1
View File
@@ -1,4 +1,5 @@
//! What each module in one file declares that an instantiation may name.
//! 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.
@@ -10,11 +11,43 @@
//! 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.
///
+51 -4
View File
@@ -39,11 +39,12 @@ mod violation;
mod visit;
mod vscode;
mod waiver;
mod waiver_file;
use std::path::PathBuf;
pub use context::{LintContext, MentionOracle, ModuleInterface, ParsedSource};
pub use interfaces::module_interfaces;
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,
@@ -56,8 +57,12 @@ pub use violation::{apply_fixes, Applicability, Fix, Fixed, Violation};
/// 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;
@@ -74,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:
@@ -92,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;
@@ -104,7 +127,31 @@ pub fn lint(ctx: &LintContext, enabled: &[&'static dyn Rule]) -> Vec<Violation>
(a.span.start, a.span.end, a.rule).cmp(&(b.span.start, b.span.end, b.rule))
});
stamp_severities(&mut kept);
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.
+1
View File
@@ -146,6 +146,7 @@ pub fn all_rules() -> Vec<&'static dyn Rule> {
&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,
@@ -58,7 +58,7 @@ impl Rule for DisableStatement {
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 };
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;
+1
View File
@@ -74,6 +74,7 @@ pub mod undriven_net;
pub mod unknown_parameter;
pub mod unknown_port;
pub mod unpacked_dimensions_range_ordering;
pub mod unused_import;
pub mod unused_signal;
pub mod unused_waiver;
pub mod uvm_macro_semicolon;
+61 -10
View File
@@ -68,13 +68,6 @@ impl Rule for UndrivenNet {
if intentionally_unused(&decl.name) || !signals.judgeable(decl) || decl.has_init {
continue;
}
// A name another file in the project writes down may be driven
// from there — a hierarchical assignment, a `force` in a
// testbench, a `bind`-ed override — none of which this file can
// see. Silence is the only honest answer.
if ctx.mentioned_elsewhere(&decl.name) {
continue;
}
let Some(usage) = signals.usage(decl) else { continue };
// A `release`/`deassign` is a write that establishes no value, so
// it is not what saves a signal from this rule.
@@ -82,6 +75,25 @@ impl Rule for UndrivenNet {
if signals.connected(decl) || driven || usage.reads == 0 {
continue;
}
// A name another file in the project writes down may be driven
// from there — a hierarchical assignment, a `force` in a
// testbench, a `bind`-ed override — none of which this file can
// see. Silence is the only honest answer.
//
// **Asked last, of the handful of declarations that would
// otherwise be reported**, and not second, of every declaration in
// the file: the oracle walks every indexed file's word list per
// question (`WorkspaceIndex::files_mentioning`), so at the position
// this check used to sit at, a 42 000-line buffer asked it four
// thousand times and the rule cost 1.6 s of every `didOpen` and
// every keystroke flush. The guards above are all local and all
// O(1)-ish, the whole condition is one conjunction of `continue`s,
// and `unused-signal` — the twin rule with the same oracle — has
// always asked last. Same findings, in the same order
// (`docs/features/didopen-cost/README.md`).
if ctx.mentioned_elsewhere(&decl.name) {
continue;
}
found.push(Violation::new(
NAME,
format!("`{}` is read but never driven", decl.name),
@@ -107,17 +119,56 @@ mod tests {
.collect()
}
/// An oracle that says exactly these names are mentioned in another file.
struct Elsewhere(&'static [&'static str]);
/// An oracle that says exactly these names are mentioned in another file,
/// and counts how often it was asked.
struct Elsewhere(&'static [&'static str], std::sync::atomic::AtomicUsize);
impl Elsewhere {
fn new(names: &'static [&'static str]) -> Elsewhere {
Elsewhere(names, std::sync::atomic::AtomicUsize::new(0))
}
}
impl crate::MentionOracle for Elsewhere {
fn mentioned_elsewhere(&self, name: &str) -> bool {
self.1.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
self.0.contains(&name)
}
}
/// TODO.md §46: the oracle is asked about the declarations that would
/// otherwise be **reported**, not about every declaration in the file.
///
/// One question per real candidate is the whole of the fix: the server's
/// oracle walks every indexed file's word list per question, so asking it
/// ahead of the local guards cost 1.6 s of every `didOpen` of opentitan's
/// 42 000-line `pinmux_reg_top.sv` — see
/// `docs/features/didopen-cost/README.md`. Asserted on the count, because
/// the findings alone cannot tell the two orders apart.
#[test]
fn the_project_is_asked_only_about_the_signals_that_would_be_reported() {
// Ten signals: nine driven and read, one read and undriven.
let mut src = String::from("module m (output logic q);\n");
for k in 0..9 {
src.push_str(&format!(" wire d{k};\n assign d{k} = 1'b0;\n"));
}
src.push_str(" wire lonely;\n assign q = lonely");
for k in 0..9 {
src.push_str(&format!(" ^ d{k}"));
}
src.push_str(";\nendmodule\n");
let oracle = Elsewhere::new(&[]);
let ctx = LintContext::new(&src, None).with_oracle(&oracle);
let found = UndrivenNet.check(&ctx);
assert_eq!(found.len(), 1, "only the undriven one: {found:#?}");
assert!(found[0].message.contains("lonely"), "{:?}", found[0].message);
let asked = oracle.1.load(std::sync::atomic::Ordering::Relaxed);
assert_eq!(asked, 1, "the project was asked about the driven signals too");
}
fn names_in_a_project(src: &str, elsewhere: &'static [&'static str]) -> Vec<String> {
let oracle = Elsewhere(elsewhere);
let oracle = Elsewhere::new(elsewhere);
let ctx = LintContext::new(src, None).with_oracle(&oracle);
UndrivenNet
.check(&ctx)
@@ -0,0 +1,228 @@
//! `unused-import` — an `import p::*;` nothing in its scope reaches through.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::severity::Severity;
use crate::violation::{Applicability, Fix, Violation};
/// See [`Rule::doc`].
pub struct UnusedImport;
const NAME: &str = "unused-import";
impl Rule for UnusedImport {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"delete an import nothing uses"
}
fn severity(&self) -> Severity {
Severity::Style
}
fn doc(&self) -> &'static str {
"`import p::*;` at the top of a module, a package or a class is the \
cheapest line in the file to leave behind: it survives every rename \
and every deletion of the code that needed it, and it goes on \
pulling a whole package's names into the scope, where they shadow \
nothing and collide with everything. This rule reports the ones \
nothing reaches through, and `lucisv: organize imports` is the same \
judgement applied as an edit — one computation, so the squiggle and \
the lightbulb can never disagree.\n\n\
**Used** means some reference in the scope, or in a scope nested \
inside it, could have got its name through that import: the name is \
not declared locally in between, the import's path admits it \
(`p::*` admits everything, `p::x` admits `x`), and `p` really \
exports it — including through a `export q::*;` re-export chain. A \
**qualified** `p::y` is not a use: it resolves inside `p` whether \
the import is written or not.\n\n\
What the rule deliberately **refuses to judge**, saying nothing at \
all rather than guessing: a package the project does not hold or \
holds twice; a scope containing a macro call or a conditional \
directive, because a name may live in text lucisv never expanded; \
and a class whose base class is declared in another file, because an \
inherited member could be the use. It is silent for a file it cannot \
see the project around — one file, a stdin buffer — for the same \
reason `unused-signal` is: there is nothing there to ask.\n\n\
The fix deletes the whole `import` item. An import carrying a \
comment is reported without one: the comment would have to go with \
the line, and lucisv never drops a comment."
}
fn default_on(&self) -> bool {
// Off, and off *with* a project too — hence no `needs_workspace`
// here, which would have switched it on wherever an oracle exists.
// An unused import is a tidiness finding, not a correctness one, and
// a whole existing tree lighting up on the day lucisv learns to see
// it is not a default anybody asked for. Silence in a single-file run
// needs no switch: with no project there is no package table, every
// scope refuses, and the rule reports nothing.
false
}
fn fix(&self) -> Option<Applicability> {
Some(Applicability::Safe)
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let exports = ctx.package_exports();
let semantics = ctx.semantics();
let source = ctx.source();
vlog_semantic::unused_imports(ctx.file(), semantics, ctx.tokens(), &exports)
.into_iter()
.map(|found| {
let violation = Violation::new(NAME, found.message(), found.span);
match deletion(source, found.span) {
Some(range) => violation.with_fix(Fix::safe(vec![(range, String::new())])),
None => violation,
}
})
.collect()
}
}
/// The bytes a fix deletes: the whole line the `import` sits on, its final
/// newline included.
///
/// `None` when the line holds anything else — another item, or a comment.
/// A comment is never dropped (CLAUDE.md invariant 3) and a second item is
/// not this finding's to delete, so the finding ships without a fix and the
/// user decides.
fn deletion(
source: &str,
span: vlog_parser::span::TextRange,
) -> Option<vlog_parser::span::TextRange> {
let start = source
.get(..span.start as usize)
.and_then(|head| head.rfind('\n'))
.map_or(0, |n| n as u32 + 1);
let end = match source.get(span.end as usize..).and_then(|tail| tail.find('\n')) {
Some(n) => span.end + n as u32 + 1,
None => source.len() as u32,
};
let before = source.get(start as usize..span.start as usize)?;
let after = source.get(span.end as usize..end as usize)?;
let clean = before.chars().all(char::is_whitespace) && after.chars().all(char::is_whitespace);
clean.then(|| vlog_parser::span::TextRange::new(start, end))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Exports, MentionOracle};
/// A project holding exactly these packages.
struct Project(&'static [(&'static str, &'static [&'static str])]);
impl MentionOracle for Project {
fn mentioned_elsewhere(&self, _name: &str) -> bool {
false
}
fn package_exports(&self, package: &str) -> Exports {
match self.0.iter().find(|(name, _)| *name == package) {
Some((_, names)) => {
Exports::Known(names.iter().map(|n| (*n).to_string()).collect())
}
None => Exports::Unknown,
}
}
}
const PROJECT: Project = Project(&[("a_pkg", &["a_t", "A_W"]), ("b_pkg", &["b_t"])]);
fn messages(src: &str) -> Vec<String> {
UnusedImport
.check(&LintContext::new(src, None).with_oracle(&PROJECT))
.into_iter()
.map(|v| v.message)
.collect()
}
/// The buffer with every fix applied, back to front.
fn fixed(src: &str) -> String {
let mut out = src.to_string();
let violations = UnusedImport.check(&LintContext::new(src, None).with_oracle(&PROJECT));
let mut edits: Vec<_> = violations
.iter()
.filter_map(|v| v.fix.as_ref())
.flat_map(|f| f.edits.clone())
.collect();
edits.sort_by_key(|(range, _)| range.start);
for (range, text) in edits.iter().rev() {
out.replace_range(range.start as usize..range.end as usize, text);
}
out
}
#[test]
fn an_import_nothing_uses_is_reported_and_fixed() {
let src = "module m;\n import a_pkg::*;\n import b_pkg::*;\n b_t q;\nendmodule\n";
assert_eq!(
messages(src),
vec!["`a_pkg::*` is imported but nothing in this scope uses it".to_string()]
);
assert_eq!(fixed(src), "module m;\n import b_pkg::*;\n b_t q;\nendmodule\n");
}
#[test]
fn an_import_the_scope_reaches_through_is_not_reported() {
let src = "module m;\n import a_pkg::*;\n a_t x;\nendmodule\n";
assert!(messages(src).is_empty(), "{:?}", messages(src));
}
#[test]
fn a_qualified_use_does_not_count() {
let src = "module m;\n import a_pkg::*;\n a_pkg::a_t x;\nendmodule\n";
assert_eq!(messages(src).len(), 1, "a `::` path resolves without the import");
}
#[test]
fn a_shadowing_declaration_does_not_count() {
let src = "module m;\n import a_pkg::*;\n typedef bit a_t;\n a_t x;\nendmodule\n";
assert_eq!(messages(src).len(), 1);
}
#[test]
fn a_nested_scope_s_use_counts() {
let src =
"module m;\n import a_pkg::*;\n initial begin\n int w = A_W;\n end\nendmodule\n";
assert!(messages(src).is_empty(), "{:?}", messages(src));
}
#[test]
fn a_macro_call_silences_the_scope() {
let src = "module m;\n import a_pkg::*;\n `MY_CHECK(x)\nendmodule\n";
assert!(messages(src).is_empty(), "a refusal is not an accusation");
}
#[test]
fn an_unknown_package_silences_the_scope() {
let src = "module m;\n import nowhere_pkg::*;\n wire a;\nendmodule\n";
assert!(messages(src).is_empty(), "{:?}", messages(src));
}
#[test]
fn a_run_with_no_project_says_nothing() {
let src = "module m;\n import a_pkg::*;\n wire a;\nendmodule\n";
let found = UnusedImport.check(&LintContext::new(src, None));
assert!(found.is_empty(), "no oracle, no accusation");
}
#[test]
fn an_import_carrying_a_comment_is_reported_without_a_fix() {
let src = "module m;\n import a_pkg::*; // why?\n wire a;\nendmodule\n";
let found = UnusedImport.check(&LintContext::new(src, None).with_oracle(&PROJECT));
assert_eq!(found.len(), 1);
assert!(found[0].fix.is_none(), "a fix here would delete the comment");
}
#[test]
fn a_package_scope_is_judged_like_a_module() {
let src = "package w_pkg;\n import a_pkg::*;\n import b_pkg::*;\n b_t q;\nendpackage\n";
assert_eq!(messages(src).len(), 1);
}
}
+2 -2
View File
@@ -466,8 +466,8 @@ impl Scanner {
None => self.unknown.push(expr.span),
},
// `-> ev;` is what drives a named event.
StmtKind::EventTrigger(expr) => {
self.write(expr, DriverKind::Trigger, block, in_generate)
StmtKind::EventTrigger(t) => {
self.write(&t.expr, DriverKind::Trigger, block, in_generate)
}
StmtKind::MacroStmt(_)
| StmtKind::Directive(_)
+14 -20
View File
@@ -113,26 +113,20 @@ impl Waivers {
Waivers { entries }
}
/// Drops the violations a waiver covers, marking those waivers used.
pub(crate) fn filter(
&mut self,
ctx: &LintContext,
violations: Vec<Violation>,
) -> Vec<Violation> {
violations
.into_iter()
.filter(|violation| {
let (line, _) = ctx.line_index().line_col(violation.span.start);
let mut waived = false;
for entry in &mut self.entries {
if entry.rule == violation.rule && entry.scope.covers(line) {
entry.used = true;
waived = true;
}
}
!waived
})
.collect()
/// True when some waiver covers `rule` at `line`, marking every waiver
/// that does used.
///
/// Every one, not the first: a finding two waivers cover has both of them
/// doing their job, and reporting the second as dead would be a lie.
pub(crate) fn covers(&mut self, rule: &str, line: u32) -> bool {
let mut waived = false;
for entry in &mut self.entries {
if entry.rule == rule && entry.scope.covers(line) {
entry.used = true;
waived = true;
}
}
waived
}
/// How many waivers have suppressed something so far. Grows only, which
+570
View File
@@ -0,0 +1,570 @@
//! External waiver files: Verible's `waive` directives, written in a file of
//! their own rather than in a comment in the RTL.
//!
//! Grammar (Verible's, so an existing `.waiver` file carries over unchanged) —
//! one directive per line, `#` comments and blank lines ignored:
//!
//! ```text
//! 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_top.sv the files that pattern names
//! ```
//!
//! The one deliberate difference from Verible: `--location` is **not** a
//! regular expression. It is matched exactly the way an `--exclude` pattern is
//! ([`lucisv_core::walk::is_excluded`]), so a pattern means one thing across
//! the whole tool; a pattern that looks like a regex is refused with a message
//! saying so rather than silently matching nothing.
//!
//! Precedence is **union** with the inline waivers of `waiver.rs`: a violation
//! is suppressed when either covers it, and a violation both cover marks both
//! used. See `docs/features/waiver-files/README.md`.
use std::path::{Path, PathBuf};
use vlog_parser::span::TextRange;
use crate::registry::rule_by_name;
use crate::severity::Severity;
use crate::violation::Violation;
use crate::waiver::UNUSED_WAIVER;
/// Every external waiver of one run, from any number of files.
#[derive(Default)]
pub struct ExternalWaivers {
sources: Vec<Source>,
directives: Vec<Directive>,
}
/// One waiver file that was read. Its text is kept because an unused
/// directive is reported at the line it was written on, and only the text
/// turns that directive's span into a line and a column.
struct Source {
path: PathBuf,
text: String,
}
/// One `waive` directive.
struct Directive {
/// Index into [`ExternalWaivers::sources`].
source: usize,
/// The directive's own line, where an `unused-waiver` finding points.
span: TextRange,
/// The rule waived; always a name the registry knows.
rule: String,
/// `--line`: 1-based, both ends included. `None` is the whole file.
lines: Option<(u32, u32)>,
/// `--location`: an `--exclude` pattern. `None` is every file.
location: Option<String>,
}
/// Which external waivers have suppressed something.
///
/// One run's worth: the CLI lints its files in parallel and merges what each
/// one used, because a `--location` pattern may cover files linted on several
/// workers. Usage only ever grows.
#[derive(Debug, Default, Clone)]
pub struct WaiverUse {
used: Vec<bool>,
}
impl WaiverUse {
/// Folds another pass's usage into this one.
pub fn merge(&mut self, other: &WaiverUse) {
if self.used.len() < other.used.len() {
self.used.resize(other.used.len(), false);
}
for (slot, fired) in self.used.iter_mut().zip(&other.used) {
*slot |= *fired;
}
}
fn mark(&mut self, index: usize) {
if self.used.len() <= index {
self.used.resize(index + 1, false);
}
self.used[index] = true;
}
fn fired(&self, index: usize) -> bool {
self.used.get(index).copied().unwrap_or(false)
}
}
/// One waiver file's dead directives, ready to be reported: the file, its
/// text — for the line and column — and one finding each.
pub struct UnusedReport {
/// The waiver file the directives were written in.
pub path: PathBuf,
/// That file's text.
pub text: String,
/// One `unused-waiver` violation per directive that suppressed nothing.
pub violations: Vec<Violation>,
}
impl ExternalWaivers {
/// Reads one waiver file: the directives that parsed, and one
/// `<file>:<line>: message` per line that did not.
///
/// A file that cannot be read at all is the `Err`; a file that reads and
/// has bad lines is an `Ok` carrying both halves, so a front end may
/// choose between failing the run (the CLI) and dropping the line and
/// logging it (the server).
pub fn read(path: &Path) -> Result<(ExternalWaivers, Vec<String>), String> {
let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
Ok(ExternalWaivers::parse(path, &text))
}
/// [`ExternalWaivers::read`] over text already in hand.
pub fn parse(path: &Path, text: &str) -> (ExternalWaivers, Vec<String>) {
let source = Source { path: path.to_path_buf(), text: text.to_string() };
let mut waivers = ExternalWaivers { sources: vec![source], directives: Vec::new() };
let mut problems = Vec::new();
// `split_inclusive` rather than `lines`, so the offsets stay right in
// a file with CRLF endings: `lines` drops bytes this has to count.
let mut offset: u32 = 0;
for (index, raw) in text.split_inclusive('\n').enumerate() {
let trimmed = raw.trim_end_matches(['\n', '\r']);
let span = TextRange::new(offset, offset + trimmed.len() as u32);
offset += raw.len() as u32;
// A BOM is not a directive, and an editor that writes one should
// not turn the first line into an error naming an invisible byte.
let line = trimmed.trim().trim_start_matches('\u{feff}');
if line.is_empty() || line.starts_with('#') {
continue;
}
match parse_directive(line, span) {
Ok(directive) => waivers.directives.push(directive),
Err(problem) => {
problems.push(format!("{}:{}: {problem}", path.display(), index + 1))
}
}
}
(waivers, problems)
}
/// Adds another file's directives to these.
pub fn absorb(&mut self, other: ExternalWaivers) {
let offset = self.sources.len();
self.sources.extend(other.sources);
self.directives.extend(other.directives.into_iter().map(|mut directive| {
directive.source += offset;
directive
}));
}
/// True when no waiver file contributed a directive — the everyday case,
/// and the one the linter must pay nothing for.
pub fn is_empty(&self) -> bool {
self.directives.is_empty()
}
/// True when some directive waives this finding, marking every directive
/// that does used.
///
/// Every one, not the first: a finding two waivers cover has both of them
/// doing their job, and reporting the second as dead afterwards would be a
/// lie.
pub(crate) fn covers(
&self,
path: Option<&Path>,
rule: &str,
line: u32,
used: &mut WaiverUse,
) -> bool {
let mut waived = false;
for (index, directive) in self.directives.iter().enumerate() {
if directive.covers(path, rule, line) {
used.mark(index);
waived = true;
}
}
waived
}
/// The `unused-waiver` findings for directives that suppressed nothing,
/// grouped by the file they were written in.
///
/// `enabled` is every rule the run had switched on. A waiver for a rule
/// that never ran is silent, exactly as an inline one is — it never had a
/// chance to fire — and so is everything here when `unused-waiver` itself
/// is off.
pub fn unused(&self, used: &WaiverUse, enabled: &[&'static str]) -> Vec<UnusedReport> {
if !enabled.contains(&UNUSED_WAIVER) {
return Vec::new();
}
let severity = rule_by_name(UNUSED_WAIVER).map_or(Severity::Style, |rule| rule.severity());
let mut reports: Vec<UnusedReport> = self
.sources
.iter()
.map(|source| UnusedReport {
path: source.path.clone(),
text: source.text.clone(),
violations: Vec::new(),
})
.collect();
for (index, directive) in self.directives.iter().enumerate() {
if used.fired(index) || !enabled.contains(&directive.rule.as_str()) {
continue;
}
let message = format!("unused waiver for `{}`", directive.rule);
let mut violation = Violation::new(UNUSED_WAIVER, message, directive.span);
// Built outside `lint`, which is what stamps every other finding.
violation.severity = severity;
if let Some(report) = reports.get_mut(directive.source) {
report.violations.push(violation);
}
}
reports.retain(|report| !report.violations.is_empty());
reports
}
}
impl Directive {
/// True when this directive waives `rule` at `line` of `path`.
///
/// A buffer with no path (stdin) is covered by a directive with no
/// `--location` and by no other: a pattern cannot match a name that does
/// not exist.
fn covers(&self, path: Option<&Path>, rule: &str, line: u32) -> bool {
if self.rule != rule {
return false;
}
if let Some((start, end)) = self.lines {
if line < start || end < line {
return false;
}
}
match &self.location {
None => true,
Some(pattern) => path.is_some_and(|path| {
lucisv_core::walk::is_excluded(path, std::slice::from_ref(pattern))
}),
}
}
}
/// One directive line: its rule, its line range and its location pattern.
///
/// `span` is that line's own range in the waiver file, carried into the
/// directive so an unused one can be reported where it was written. The
/// source index is filled in by [`ExternalWaivers::absorb`].
fn parse_directive(line: &str, span: TextRange) -> Result<Directive, String> {
let mut words = line.split_whitespace();
// The line was trimmed and is not empty, so there is a first word.
let keyword = words.next().unwrap_or_default();
if keyword != "waive" {
return Err(format!("expected a `waive` directive, found `{keyword}`"));
}
let mut rule: Option<String> = None;
let mut lines: Option<(u32, u32)> = None;
let mut location: Option<String> = None;
for word in words {
let (flag, value) = split_flag(word)?;
match flag {
"--rule" => set_once(&mut rule, flag, parse_rule(value)?)?,
"--line" => set_once(&mut lines, flag, parse_lines(value)?)?,
_ => set_once(&mut location, flag, parse_location(value)?)?,
}
}
let rule = rule.ok_or("`waive` needs a `--rule=<rule-name>`")?;
Ok(Directive { source: 0, span, rule, lines, location })
}
/// Fills a slot the directive may only fill once.
fn set_once<T>(slot: &mut Option<T>, flag: &str, value: T) -> Result<(), String> {
if slot.is_some() {
return Err(format!("`{flag}` is given twice"));
}
*slot = Some(value);
Ok(())
}
/// The `--flag=value` one word of a directive is.
fn split_flag(word: &str) -> Result<(&str, &str), String> {
let (flag, value) = word.split_once('=').unwrap_or((word, ""));
match flag {
"--rule" | "--line" | "--location" => {}
// Verible's third matcher waives by the *text* of the line, which
// needs the regex engine lucisv deliberately does not have.
"--regex" => {
return Err("`--regex` is not supported; waive by `--line` or `--location`".to_string())
}
other => {
return Err(format!(
"unknown option `{other}` (the options are `--rule`, `--line` and `--location`)"
))
}
}
if !word.contains('=') {
return Err(format!("`{flag}` takes a value: write `{flag}=<value>`"));
}
if value.is_empty() {
return Err(format!("`{flag}` has an empty value"));
}
Ok((flag, value))
}
/// A `--rule` value: one rule the registry knows.
///
/// A severity word is refused rather than expanded. `--select style` turns a
/// whole class on for a run the user is watching; a waiver file is checked in,
/// and one word there quietly silencing every style rule in the project is not
/// a thing anyone should be able to write by accident.
fn parse_rule(value: &str) -> Result<String, String> {
if rule_by_name(value).is_some() {
return Ok(value.to_string());
}
if Severity::from_name(value).is_some() {
return Err(format!(
"`--rule={value}` names a severity class; a waiver names one rule at a time"
));
}
Err(format!("unknown rule `{value}`"))
}
/// A `--line` value: `N` or `N-M`, 1-based, both ends included.
fn parse_lines(value: &str) -> Result<(u32, u32), String> {
let malformed =
|| format!("`--line={value}` is not a line or a line range (`--line=5`, `--line=5-9`)");
let (start, end) = value.split_once('-').unwrap_or((value, value));
let start: u32 = start.parse().map_err(|_| malformed())?;
let end: u32 = end.parse().map_err(|_| malformed())?;
if start == 0 {
return Err(format!("`--line={value}` starts at 0; lines are numbered from 1"));
}
if end < start {
return Err(format!("`--line={value}` counts backwards"));
}
Ok((start, end))
}
/// A `--location` value: an `--exclude` pattern, never a regex.
fn parse_location(value: &str) -> Result<String, String> {
match regex_hint(value) {
Some(found) => Err(format!(
"`--location={value}` looks like a regular expression (`{found}`); lucisv matches a \
location the way `--exclude` does — `*` stands for any run of characters within one \
path component, a pattern with `/` matches a path suffix and one without matches the \
file name, and nothing else is a metacharacter"
)),
None => Ok(value.to_string()),
}
}
/// The first regex metacharacter in a pattern, if it has one.
///
/// A bare `.` is not one: `foo.sv` is a file name. `.*` and `.+` are, and so
/// is every character that means nothing in a glob and something in a regex.
fn regex_hint(pattern: &str) -> Option<String> {
for token in [".*", ".+"] {
if pattern.contains(token) {
return Some(token.to_string());
}
}
pattern.chars().find(|c| "\\^$[]()|?+{}".contains(*c)).map(|c| c.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
fn waivers(text: &str) -> (ExternalWaivers, Vec<String>) {
ExternalWaivers::parse(Path::new("project.waiver"), text)
}
/// The one problem `text` produces, without the `file:line: ` prefix.
fn problem(text: &str) -> String {
let (waivers, problems) = waivers(text);
assert!(waivers.is_empty(), "a bad line contributes no directive");
assert_eq!(problems.len(), 1, "{problems:?}");
problems[0].split_once(": ").expect("a `file:line: message`").1.to_string()
}
/// Whether the file's directives waive `rule` at `line` of `path`.
fn covered(text: &str, path: Option<&str>, rule: &str, line: u32) -> bool {
let (waivers, problems) = waivers(text);
assert!(problems.is_empty(), "{problems:?}");
let mut used = WaiverUse::default();
waivers.covers(path.map(Path::new), rule, line, &mut used)
}
#[test]
fn every_directive_shape_parses() {
let (waivers, problems) = waivers(
"# a comment\n\
\n\
waive --rule=no-tabs\n\
waive --rule=no-tabs --line=12\n\
waive --rule=no-tabs --line=12-20\n\
waive --rule=no-tabs --location=legacy.sv\n\
\x20 waive --rule=no-tabs --line=3 --location=rtl/legacy.sv\n\
waive --location=a.sv --rule=no-tabs\n",
);
assert!(problems.is_empty(), "{problems:?}");
assert_eq!(waivers.directives.len(), 6);
assert_eq!(waivers.directives[1].lines, Some((12, 12)));
assert_eq!(waivers.directives[2].lines, Some((12, 20)));
assert_eq!(waivers.directives[3].location.as_deref(), Some("legacy.sv"));
}
#[test]
fn crlf_line_endings_do_not_shift_a_directives_span() {
let (waivers, problems) = waivers("# note\r\nwaive --rule=no-tabs\r\n");
assert!(problems.is_empty(), "{problems:?}");
let span = waivers.directives[0].span;
assert_eq!(span.start as usize, "# note\r\n".len());
assert_eq!(span.end as usize, "# note\r\nwaive --rule=no-tabs".len());
}
#[test]
fn every_error_names_the_file_the_line_and_the_difference() {
let (_, problems) = waivers("waive --rule=no-such-rule\n");
assert_eq!(problems[0], "project.waiver:1: unknown rule `no-such-rule`");
assert_eq!(problem("waive\n"), "`waive` needs a `--rule=<rule-name>`");
assert_eq!(problem("waive --line=3\n"), "`waive` needs a `--rule=<rule-name>`");
assert!(problem("skip --rule=no-tabs\n").contains("found `skip`"));
assert!(problem("waive --rule=style\n").contains("names a severity class"));
assert!(problem("waive --rule=no-tabs --line=0\n").contains("numbered from 1"));
assert!(problem("waive --rule=no-tabs --line=9-5\n").contains("counts backwards"));
assert!(problem("waive --rule=no-tabs --line=x\n").contains("is not a line or a line"));
assert!(problem("waive --rule=no-tabs --line=5-\n").contains("is not a line or a line"));
assert!(problem("waive --rule=no-tabs --rule=no-tabs\n").contains("given twice"));
assert!(problem("waive --rule=no-tabs --lines=3\n").contains("unknown option `--lines`"));
assert!(problem("waive --rule=no-tabs --regex=x\n").contains("`--regex` is not supported"));
assert!(problem("waive --rule\n").contains("takes a value"));
assert!(problem("waive --rule=\n").contains("empty value"));
assert!(problem("waive --rule=no-tabs --location=x --location=y\n").contains("twice"));
}
#[test]
fn a_regex_looking_location_is_refused_and_a_glob_is_not() {
for pattern in [".*_pkg.sv", "top\\.sv", "^a.sv$", "(a|b).sv", "a?.sv", "a+.sv", "[ab].sv"]
{
let text = format!("waive --rule=no-tabs --location={pattern}\n");
let message = problem(&text);
assert!(message.contains("looks like a regular expression"), "{pattern}: {message}");
assert!(message.contains("`--exclude`"), "{pattern}: {message}");
}
for pattern in ["a.sv", "*_gen.sv", "rtl/*.sv", "legacy/top.sv", "*"] {
let text = format!("waive --rule=no-tabs --location={pattern}\n");
let (_, problems) = waivers(&text);
assert!(problems.is_empty(), "{pattern}: {problems:?}");
}
}
#[test]
fn a_directive_with_no_line_and_no_location_covers_everything() {
let text = "waive --rule=no-tabs\n";
assert!(covered(text, Some("rtl/a.sv"), "no-tabs", 1));
assert!(covered(text, Some("elsewhere/b.sv"), "no-tabs", 900));
assert!(covered(text, None, "no-tabs", 1), "a stdin buffer too");
assert!(!covered(text, Some("rtl/a.sv"), "no-trailing-whitespace", 1), "another rule");
}
#[test]
fn a_line_covers_itself_and_a_range_covers_both_ends() {
let one = "waive --rule=no-tabs --line=12\n";
assert!(covered(one, Some("a.sv"), "no-tabs", 12));
assert!(!covered(one, Some("a.sv"), "no-tabs", 11));
assert!(!covered(one, Some("a.sv"), "no-tabs", 13));
let range = "waive --rule=no-tabs --line=12-14\n";
for line in [12, 13, 14] {
assert!(covered(range, Some("a.sv"), "no-tabs", line), "line {line}");
}
assert!(!covered(range, Some("a.sv"), "no-tabs", 11));
assert!(!covered(range, Some("a.sv"), "no-tabs", 15));
}
/// The `--exclude` semantics, at the waiver file's end of them: a pattern
/// without `/` matches the file name at any depth, one with `/` matches a
/// path suffix, and `*` stays inside one component.
#[test]
fn a_location_matches_the_way_an_exclude_pattern_does() {
let by_name = "waive --rule=no-tabs --location=legacy.sv\n";
assert!(covered(by_name, Some("a/b/legacy.sv"), "no-tabs", 1));
assert!(!covered(by_name, Some("a/b/other.sv"), "no-tabs", 1));
let by_suffix = "waive --rule=no-tabs --location=vendor/legacy.sv\n";
assert!(covered(by_suffix, Some("a/vendor/legacy.sv"), "no-tabs", 1));
assert!(!covered(by_suffix, Some("a/rtl/legacy.sv"), "no-tabs", 1));
let glob = "waive --rule=no-tabs --location=*_gen.sv\n";
assert!(covered(glob, Some("rtl/top_gen.sv"), "no-tabs", 1));
assert!(!covered(glob, Some("rtl/top.sv"), "no-tabs", 1));
// `*` does not cross a `/`, exactly as in a walk's exclude.
let anchored = "waive --rule=no-tabs --location=rtl/*.sv\n";
assert!(covered(anchored, Some("top/rtl/b.sv"), "no-tabs", 1));
assert!(!covered(anchored, Some("rtl/a/b.sv"), "no-tabs", 1));
// A buffer with no path is covered by nothing that names a location.
assert!(!covered(by_name, None, "no-tabs", 1));
}
#[test]
fn a_directive_that_fired_is_not_reported_and_one_that_did_not_is() {
let (waivers, problems) =
waivers("waive --rule=no-tabs\nwaive --rule=no-trailing-whitespace\n");
assert!(problems.is_empty(), "{problems:?}");
let enabled = ["no-tabs", "no-trailing-whitespace", UNUSED_WAIVER];
let mut used = WaiverUse::default();
assert!(waivers.covers(Some(Path::new("a.sv")), "no-tabs", 1, &mut used));
let reports = waivers.unused(&used, &enabled);
assert_eq!(reports.len(), 1, "one waiver file, one group");
assert_eq!(reports[0].path, PathBuf::from("project.waiver"));
assert_eq!(reports[0].violations.len(), 1, "only the one that never fired");
assert!(reports[0].violations[0].message.contains("no-trailing-whitespace"));
assert_eq!(reports[0].violations[0].rule, UNUSED_WAIVER);
assert_eq!(reports[0].violations[0].severity, Severity::Style, "stamped here");
// The finding points at the dead directive's own line.
assert_eq!(reports[0].violations[0].span.start as usize, "waive --rule=no-tabs\n".len());
}
#[test]
fn a_waiver_for_a_rule_the_run_did_not_enable_is_silent() {
let (waivers, _) = waivers("waive --rule=no-tabs\n");
let used = WaiverUse::default();
assert!(waivers.unused(&used, &["no-trailing-whitespace", UNUSED_WAIVER]).is_empty());
// And so is everything when `unused-waiver` itself is off.
assert!(waivers.unused(&used, &["no-tabs"]).is_empty());
}
#[test]
fn absorbing_a_second_file_keeps_each_directive_with_its_own_file() {
let (mut first, _) =
ExternalWaivers::parse(Path::new("a.waiver"), "waive --rule=no-tabs\n");
let (second, _) =
ExternalWaivers::parse(Path::new("b.waiver"), "waive --rule=no-trailing-whitespace\n");
first.absorb(second);
assert_eq!(first.directives.len(), 2);
let mut used = WaiverUse::default();
assert!(first.covers(Some(Path::new("a.sv")), "no-tabs", 1, &mut used));
let reports = first.unused(&used, &["no-tabs", "no-trailing-whitespace", UNUSED_WAIVER]);
assert_eq!(reports.len(), 1, "only the file with a dead directive: {}", reports.len());
assert_eq!(reports[0].path, PathBuf::from("b.waiver"));
}
#[test]
fn usage_merges_across_the_files_a_run_linted_in_parallel() {
let (waivers, _) = waivers(
"waive --rule=no-tabs --location=a.sv\n\
waive --rule=no-tabs --location=b.sv\n",
);
let enabled = ["no-tabs", UNUSED_WAIVER];
let mut first = WaiverUse::default();
waivers.covers(Some(Path::new("a.sv")), "no-tabs", 1, &mut first);
assert_eq!(waivers.unused(&first, &enabled)[0].violations.len(), 1, "b.sv's is dead");
let mut second = WaiverUse::default();
waivers.covers(Some(Path::new("b.sv")), "no-tabs", 1, &mut second);
first.merge(&second);
assert!(waivers.unused(&first, &enabled).is_empty(), "both fired, over two files");
}
}
+118 -3
View File
@@ -5,7 +5,10 @@
use super::*;
/// A data type: keyword or user-defined name, plus signing and packed dims.
/// `name` may be empty for implicit types (`input [7:0] x`).
/// `name` may be empty for implicit types (`input [7:0] x`), and is the whole
/// chain a qualified type reference writes: `pkg::item`, `bus_if.mp`.
/// [`DataType::name_span`] says where it is written and
/// [`DataType::segments`] splits it.
#[derive(Debug, Clone, Default)]
pub struct DataType {
/// The `virtual` / `virtual interface` prefix of a virtual interface type
@@ -22,6 +25,14 @@ pub struct DataType {
/// so a rare field must not widen the common case.
pub virt: Option<VirtualKw>,
pub name: String,
/// Where [`DataType::name`] is written. Read it through
/// [`DataType::name_span`], which pairs it with the name's own length.
///
/// Four bytes rather than a whole [`TextRange`] because they fit in the
/// padding this struct already has: an eight-byte span pushes `DataType`
/// to 96 and, through [`ExprKind::Type`], every `Expr` to 104, past the
/// 96-byte pin in `size_pins`.
pub(crate) name_start: u32,
/// The rare tail of a type: parameterization or an anonymous aggregate
/// body. See [`TypeExtra`]; read it through [`DataType::params`] /
/// [`DataType::inline`].
@@ -57,6 +68,70 @@ impl DataType {
_ => None,
}
}
/// The byte range [`DataType::name`] occupies: `src[name_span] == name`
/// for every name the source spells the way the AST joined it, which is
/// every name but the pathological spacings [`DataType::segments`]
/// documents. An implicit type has no name, so this is the empty range at
/// the position a name would have been written — the same convention an
/// unnamed DPI formal's `name_span` uses.
pub fn name_span(&self) -> TextRange {
TextRange::new(self.name_start, self.name_start.saturating_add(self.name.len() as u32))
}
/// The `::`- and `.`-separated segments of the name — `pkg`, `item` of
/// `pkg::item`; `bus_if`, `mp` of `bus_if.mp` — each with the byte range
/// it occupies.
///
/// Derived from [`DataType::name_span`] and the name's own text: the
/// construct is never rescanned. So a source that spells the name
/// differently from the way the parser joined it — an escaped segment
/// terminated by a newline rather than a space, a `bus_if . mp` written
/// apart — hands back ranges that do not slice back to their segment.
/// A caller that must not mislocate checks the slice and drops the
/// segment; `vlog_semantic`'s binder does.
pub fn segments(&self) -> impl Iterator<Item = (&str, TextRange)> + '_ {
let base = self.name_start;
let mut rest = Some((0usize, self.name.as_str()));
std::iter::from_fn(move || {
let (at, text) = rest.take()?;
let (seg, tail) = match separator(text) {
Some((i, len)) => (&text[..i], Some((at + i + len, &text[i + len..]))),
None => (text, None),
};
rest = tail;
let start = base.saturating_add(at as u32);
Some((seg, TextRange::new(start, start.saturating_add(seg.len() as u32))))
})
.filter(|(seg, _): &(&str, TextRange)| !seg.is_empty())
}
}
/// Where the first `::`/`.` that separates two name segments starts, and how
/// many bytes it is.
///
/// An escaped identifier swallows both spellings (`\a.b ::x` is two segments,
/// not three), so one that leads the text runs to its terminating whitespace —
/// which the parser keeps in the joined name (§29) — before the search for a
/// separator begins.
fn separator(text: &str) -> Option<(usize, usize)> {
let bytes = text.as_bytes();
let mut i = 0;
if bytes.first() == Some(&b'\\') {
while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
i += 1;
}
// The terminator belongs to the segment; anything else is a separator.
i = (i + 1).min(bytes.len());
}
while i < bytes.len() {
match bytes[i] {
b':' if bytes.get(i + 1) == Some(&b':') => return Some((i, 2)),
b'.' => return Some((i, 1)),
_ => i += 1,
}
}
None
}
/// What a type carries beyond its name, signing and packed dimensions. A type
@@ -235,12 +310,45 @@ pub struct ParamDecl {
pub declarators: Vec<Declarator>,
}
/// A net delay and the side of the data type it was written on.
///
/// IEEE 1800 §6.7 puts `delay3` *after* the type —
/// `wire [31:0] #0.1 x = y;`, which is how
/// `pulp_riscv_dbg/tb/unused/SimDTM.sv:38` writes it — while the spelling
/// the rest of the corpus uses puts it between the net keyword and the type.
/// Both are read, never both at once, and printed back where they were
/// written: moving a delay across the type reorders tokens, which
/// `verify.rs` rightly refuses.
#[derive(Debug)]
pub struct NetDelay {
/// Comments written between whatever precedes the delay and its `#`:
/// the `/* c */` of `wire /* c */ #5 w;` and of
/// `wire [7:0] /* c */ #1 w;`. Without a slot here the comment would be
/// printed one node later and `verify.rs` would refuse the file.
pub before_hash: Vec<Comment>,
/// Comments written between the `#` and the delay value — the delay's
/// other gap, and the one the gap fuzzer asks about the moment the
/// first one has an owner.
pub after_hash: Vec<Comment>,
/// The delay itself: the `5` of `wire #5 w;`.
pub expr: Expr,
/// True when it stood between the data type and the declarators.
pub after_type: bool,
}
#[derive(Debug)]
pub struct DataDecl {
/// Net type (`wire`, `tri`, ...) if any.
pub net: Option<String>,
/// Net delay: the `5` in `wire #5 w;`
pub delay: Option<Expr>,
/// Drive strength: the `(strong0, weak1)` of
/// `wire (strong0, weak1) w = a;` (IEEE 1800 §6.6), read only after a net
/// keyword — the one position the grammar allows it. Carried the way
/// [`ContAssign::strength`] is, and printed between the net keyword and
/// the delay, where the source wrote it.
pub strength: Option<DriveStrength>,
/// Net delay, if any: the `5` in `wire #5 w;` or the `0.1` in
/// `wire [31:0] #0.1 x = y;`.
pub delay: Option<NetDelay>,
/// Qualifiers written before the type, in source order: `var`,
/// `automatic`, `static`, `const`, and — inside a class body — `rand`,
/// `randc`, `local`, `protected`, and the `virtual [interface]` of a
@@ -375,6 +483,8 @@ pub struct TaskDecl {
/// growing a near-identical node of their own.
#[derive(Debug)]
pub struct LetDecl {
/// Comments written between the `let` keyword and the name.
pub after_kw: Vec<Comment>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
@@ -382,7 +492,12 @@ pub struct LetDecl {
/// written when this is true and [`LetDecl::ports`] is empty.
pub has_parens: bool,
pub ports: Vec<ListElem<TfArg>>,
/// Comments written on either side of the `=`, each kept on its own side
/// of it the way a declarator's `eq_comments` are.
pub eq_comments: Box<BinaryComments>,
pub value: Expr,
/// Comments written between the value and the `;`.
pub before_semi: Vec<Comment>,
}
#[derive(Debug)]
+74
View File
@@ -119,6 +119,18 @@ pub enum ExprKind {
/// The stream expressions, carrying their comments the way a
/// concatenation's elements do.
inner: Vec<ExprItem>,
/// The three gaps the two nested brace pairs open. Boxed to keep
/// `Expr` small, as for `TernaryComments`.
comments: Box<StreamComments>,
},
/// `expr with [ range ]` — a stream expression's array range
/// (IEEE 1800 §11.4.14): `{<< {a with [0:3]}}`, `{>> {a with [i+:4]}}`,
/// `{<< {a with [i]}}`. The only `with` whose argument is a bracket
/// rather than a `(` or a `{`, which is what tells it from an array
/// method's iterator argument and from a `randomize` constraint block.
StreamWith {
base: Box<Expr>,
range: Box<StreamRange>,
},
Paren {
inner: Box<Expr>,
@@ -259,9 +271,32 @@ pub enum ExprKind {
min: Box<Expr>,
typ: Box<Expr>,
max: Box<Expr>,
/// What was written around the two `:`.
comments: Box<MinTypMaxComments>,
},
}
/// Comments written around the two `:` of a `min : typ : max` delay
/// (IEEE 1800 §28.14):
///
/// ```text
/// min /*before_typ*/ : /*after_typ*/ typ /*before_max*/ : /*after_max*/ max
/// ```
///
/// Boxed by its holder for the reason every expression-level slot is: `Expr`
/// is walked recursively and its size is pinned at 96 bytes.
#[derive(Debug, Clone, Default)]
pub struct MinTypMaxComments {
/// Between `min` and the first `:`.
pub before_typ: Vec<Comment>,
/// Just after the first `:`.
pub after_typ: Vec<Comment>,
/// Between `typ` and the second `:`.
pub before_max: Vec<Comment>,
/// Just after the second `:`.
pub after_max: Vec<Comment>,
}
/// Comments written in the fixed slots of a **postfix segment** or a
/// **bracketed range** — the one shape the grammar writes in five places:
///
@@ -428,6 +463,45 @@ pub struct WithComments {
pub after_kw: Vec<Comment>,
}
/// The gaps of a streaming concatenation's own brackets:
/// `{ /*a*/ << byte /*b*/ { x } /*c*/ }`. The elements inside carry their own
/// comments the way a concatenation's do; these three are what the nesting of
/// the two brace pairs leaves over.
#[derive(Debug, Clone, Default)]
pub struct StreamComments {
/// Between the outer `{` and the `<<` or `>>`.
pub after_open: Vec<Comment>,
/// Between the direction (or the slice size) and the inner `{`.
pub before_inner: Vec<Comment>,
/// Between the inner `}` and the outer `}`.
pub before_close: Vec<Comment>,
}
/// The `with [ … ]` bracket of a stream expression: one index (`[i]`) or a
/// range in any of the three spellings a part select takes (`[m:l]`,
/// `[i+:n]`, `[i-:n]`).
///
/// It is not an [`ExprKind::Range`] because that node wraps a *base* — here
/// the base stands on the `with`'s left, outside the bracket — but it keeps
/// exactly the same comment slots, so the printer lays both out through one
/// function.
#[derive(Debug, Clone)]
pub struct StreamRange {
/// Comments written on either side of the `with` keyword.
pub with_comments: WithComments,
/// The single index, or the range's first operand.
pub msb: Expr,
/// `:`, `+:` or `-:`; `None` for the single-index spelling.
pub op: Option<String>,
/// The range's second operand; `None` for the single-index spelling.
pub lsb: Option<Expr>,
/// `[ /*a*/ m /*b*/ : /*c*/ l /*d*/ ]` — the slots
/// [`SegmentComments`] names. `before_open` is always empty here: what
/// was written between the `with` and the `[` belongs to the keyword, so
/// it goes in `with_comments.after_kw`.
pub comments: SegmentComments,
}
impl TernaryComments {
/// True when nothing was written inside the `? :` — the common case, laid
/// out without any comment handling.
+3
View File
@@ -33,6 +33,7 @@
//! | `expr` | [`Expr`], [`ExprKind`], the expression comment slots |
//! | `class`, `covergroup` | classes and constraints; covergroups |
//! | `sva` | assertions, `property`/`sequence`, the property-expression tree |
//! | `randsequence` | the `randsequence` production grammar (IEEE 1800 §18.17) |
use crate::span::TextRange;
use crate::token::Comment;
@@ -42,6 +43,7 @@ mod covergroup;
mod decl;
mod expr;
mod module;
mod randsequence;
mod stmt;
mod sva;
@@ -50,6 +52,7 @@ pub use covergroup::*;
pub use decl::*;
pub use expr::*;
pub use module::*;
pub use randsequence::*;
pub use stmt::*;
pub use sva::*;
+129 -3
View File
@@ -162,8 +162,15 @@ pub struct ContAssign {
/// Drive strength: the `(weak0, pull1)` in
/// `assign (weak0, pull1) x = y;` (IEEE 1800 §10.3.1), in source order.
pub strength: Option<DriveStrength>,
/// Comments written between the `#` and the delay itself.
pub after_hash: Vec<Comment>,
/// Delay expression: the `5` in `assign #5 x = y;`
pub delay: Option<Expr>,
/// Comments written between that delay and the first left-hand side.
/// Without a slot here they would join the first pair's `meta.leading`,
/// which prints straight after the `assign` — in front of the delay the
/// source wrote them behind.
pub after_delay: Vec<Comment>,
pub assigns: Vec<AssignPair>,
}
@@ -176,6 +183,24 @@ pub struct DriveStrength {
/// `None` for the single-strength spelling `pullup (weak1) p (x);`
/// (IEEE 1800 §28.3's `pullup_strength`), which only a pull gate takes.
pub second: Option<String>,
/// Boxed: five comment vectors dwarf the two strength words, and a
/// [`DataDecl`] carrying one of these is what `ast::size_pins` measures.
pub comments: Box<DriveStrengthComments>,
}
/// The five gaps of `/*a*/ ( /*b*/ strong0 /*c*/ , /*d*/ weak1 /*e*/ )`.
///
/// `before_open` is the gap in front of the `(` — the strength owns it because
/// the three constructs that write one (`assign`, a gate, a net declaration)
/// all have something of their own directly in front of it.
#[derive(Debug, Default)]
pub struct DriveStrengthComments {
pub before_open: Vec<Comment>,
pub after_open: Vec<Comment>,
/// Empty for the single-strength spelling, which has no `,`.
pub before_comma: Vec<Comment>,
pub after_comma: Vec<Comment>,
pub before_close: Vec<Comment>,
}
#[derive(Debug)]
@@ -363,12 +388,37 @@ pub struct GateInstantiation {
/// The `(weak1)` in `pullup (weak1) p (x);` (IEEE 1800 §28.3), or the
/// `(strong0, strong1)` pair every driving gate also accepts.
pub strength: Option<DriveStrength>,
/// Comments written between the gate (or its drive strength) and the `#`
/// of the delay: the `/* c */` of `and /* c */ #(2, 3) g (y, a, b);`.
pub before_hash: Vec<Comment>,
/// Comments written between that `#` and the delay itself.
pub after_hash: Vec<Comment>,
/// The delay written after `#`: empty when there is none, one element for
/// every spelling a net or a continuous assignment also accepts, and two
/// or three for the `(rise, fall[, turn-off])` list that only a gate
/// takes (IEEE 1800 §28.14, `top_earlgrey/ip/ast/rtl/aon_osc.sv:41`).
pub delay: Vec<Expr>,
pub delay: Vec<DelayValue>,
pub instances: Vec<GateInstance>,
/// Comments written between the last instance and the `;`.
pub before_semi: Vec<Comment>,
}
/// One value of a delay list, with the comments written on either side of the
/// separator that reaches it.
///
/// A one-value delay keeps its comments in its own [`ExprKind::Paren`], which
/// has had the two slots all along; this shape exists for the multi-value
/// `#(rise, fall[, turn-off])` list, whose parentheses and commas the printer
/// writes itself and which therefore has nowhere else to put them. The first
/// value's `leading` is what stood just inside the `(`, and the last value's
/// `trailing` is what stood just before the `)`.
#[derive(Debug)]
pub struct DelayValue {
/// Comments between the `(` or the `,` before this value and the value.
pub leading: Vec<Comment>,
pub expr: Expr,
/// Comments between the value and the `,` or `)` that follows it.
pub trailing: Vec<Comment>,
}
#[derive(Debug)]
@@ -377,6 +427,9 @@ pub struct GateInstance {
pub name: Option<String>,
/// Byte range of `name`.
pub name_span: Option<TextRange>,
/// Comments written between the instance name and the `(` of its
/// terminal list.
pub before_args: Vec<Comment>,
pub args: Vec<ExprItem>,
/// Code extent of the gate instance.
pub span: TextRange,
@@ -514,8 +567,16 @@ pub struct ModportPort {
pub struct ClockingDecl {
/// True when the declaration was written `default clocking ...`.
pub is_default: bool,
/// Comments written between the `clocking` keyword and whatever follows
/// it — the name, or the `@` of an anonymous block.
pub after_kw: Vec<Comment>,
/// `None` for the anonymous `default clocking @(posedge clk);` form.
pub name: Option<Name>,
/// Comments written between the name and the `@` of the clocking event.
/// Empty when no name or no event was written.
pub before_event: Vec<Comment>,
/// Comments written between the header's last token and its `;`.
pub before_semi: Vec<Comment>,
/// The `@( ... )` clocking event. `None` for `default clocking cb;`, which
/// selects an existing clocking block and has no body.
pub event: Option<SensList>,
@@ -537,6 +598,8 @@ pub struct ClockingDecl {
pub struct ClockingItem {
pub meta: Meta,
pub kind: ClockingItemKind,
/// Comments written between the item's last token and its `;`.
pub before_semi: Vec<Comment>,
/// Code extent of the item, its `;` excluded.
pub span: TextRange,
}
@@ -544,10 +607,73 @@ pub struct ClockingItem {
#[derive(Debug)]
pub enum ClockingItemKind {
/// `default input #1step output #0;` — at least one half is written.
Default { input: Option<String>, output: Option<String> },
Default { input: Option<ClockingDefault>, output: Option<ClockingDefault> },
/// `input #2 a, b;`, `output negedge c;`, `inout d;`. `skew` is the delay
/// or edge as written (`#2`, `negedge`), or `None` when omitted.
Signals { dir: String, skew: Option<String>, signals: Vec<ClockingSignal> },
Signals {
dir: String,
/// Comments written between the direction keyword and the skew — or,
/// when no skew was written, between it and the first signal name.
after_dir: Vec<Comment>,
skew: Option<ClockingSkew>,
/// Comments written between that skew and the first signal name.
/// Empty when no skew was written.
after_skew: Vec<Comment>,
signals: Vec<ClockingSignal>,
},
}
/// One half of a `default input #1step output #0;` item: a direction keyword
/// and the skew that follows it.
#[derive(Debug)]
pub struct ClockingDefault {
/// Comments written between whatever precedes the direction keyword — the
/// `default`, or the other half's skew — and the keyword itself.
pub before_dir: Vec<Comment>,
/// Comments written between the direction keyword and the skew.
pub after_dir: Vec<Comment>,
pub skew: ClockingSkew,
}
/// The skew of a clocking item — IEEE 1800 §14.3's
/// `clocking_skew ::= edge_identifier [ delay_control ] | delay_control`.
#[derive(Debug)]
pub enum ClockingSkew {
/// `posedge`, `negedge`, `edge`, each of which may carry a delay of its
/// own (`input negedge #(1:2:3) sig;`).
Edge {
/// The edge keyword as written.
word: String,
/// Comments written between that keyword and the `#` behind it. Empty
/// when no delay was written — the gap is then the caller's own slot
/// before the signal name or the other `default` half.
after_edge: Vec<Comment>,
delay: Option<ClockingDelay>,
},
/// A skew that is a `delay_control` alone: `#2`, `#(1:2:3)`.
Delay(ClockingDelay),
}
/// The `# …` half of a clocking skew — IEEE 1800 §14.3's `delay_control`,
/// written alone or behind an edge identifier.
#[derive(Debug)]
pub enum ClockingDelay {
/// `#2`, `#1step` — the one token written after the `#`, kept exactly as
/// written: it is a delay, never something lucisv re-lays out.
Word {
/// Comments written between the `#` and that token.
after_hash: Vec<Comment>,
word: String,
},
/// The parenthesized spelling `#(1:2:3)`, `#(5)` — the same delay
/// expression a net declaration writes, so it arrives with the comment
/// slots [`ExprKind::MinTypMax`] and [`ExprKind::Paren`] already have.
Paren {
/// Comments written between the `#` and the `(`.
after_hash: Vec<Comment>,
/// The parenthesized delay, `(` and `)` included.
expr: Expr,
},
}
/// One `signal [= expression]` of a clocking direction group — IEEE 1800
+173
View File
@@ -0,0 +1,173 @@
//! `randsequence` — the production grammar of IEEE 1800 §18.17.
//!
//! A `randsequence` statement is a little grammar of its own written inside a
//! procedural block: a list of *productions*, each a name with optional
//! arguments and return type, each defining one or more weighted
//! *alternatives*, each alternative a run of *items* — a reference to another
//! production, a code block of ordinary statements, or one of the three
//! control shapes (`if`/`else`, `repeat`, `case`).
//!
//! Every node here carries the comment slots its own tokens open, for the
//! reason the rest of the AST does: a comment written between two tokens must
//! print back between those same two tokens or `verify.rs` refuses the file.
use super::*;
/// `randsequence (main) … endsequence` (IEEE 1800 §18.17).
#[derive(Debug)]
pub struct RandSequence {
/// Comments written between the keyword and its `(`.
pub after_kw: Vec<Comment>,
/// Comments written just inside the `(`.
pub after_open: Vec<Comment>,
/// The starting production, `None` for the empty `randsequence ()`.
pub start: Option<Name>,
/// Comments written between that name and the `)`.
pub before_close: Vec<Comment>,
pub productions: Vec<Production>,
/// Comments written after the last production and before `endsequence`.
pub dangling: Vec<Comment>,
}
/// One production: `[type] name [(ports)] : alternative { | alternative } ;`.
#[derive(Debug)]
pub struct Production {
pub meta: Meta,
/// The production's return type, `None` when it declares none (or wrote
/// `void`, which is kept here as an ordinary type name).
pub ret_type: Option<DataType>,
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
/// True when the production wrote a `( … )` port list, even an empty one.
pub has_parens: bool,
/// The formal arguments, read as a subroutine's are (§18.17.5).
pub args: Vec<ListElem<TfArg>>,
/// Comments written between the head and the `:`.
pub before_colon: Vec<Comment>,
/// At least one; the `|`-separated right-hand sides.
pub alternatives: Vec<Alternative>,
/// Comments written between the last alternative and the `;`.
pub before_semi: Vec<Comment>,
/// Code extent of the production, its `;` excluded.
pub span: TextRange,
}
/// One `|`-separated right-hand side of a production, with the optional
/// `:= weight` that biases it.
#[derive(Debug)]
pub struct Alternative {
/// Comments written between the previous alternative and the `|` that
/// starts this one. Always empty on the first alternative, whose left
/// neighbour is the production's `:`.
pub before_bar: Vec<Comment>,
/// Comments written between the `:` (or the `|`) and the first item.
pub after_bar: Vec<Comment>,
pub items: Vec<ProdItem>,
/// Comments written between the last item and the `:=`.
pub before_weight: Vec<Comment>,
/// The `:= expr` weight (§18.17.2), `None` when unweighted.
pub weight: Option<Weight>,
}
/// The `:= weight [code block]` of a weighted alternative.
#[derive(Debug)]
pub struct Weight {
/// Comments written between the `:=` and the weight expression.
pub after_op: Vec<Comment>,
pub expr: Expr,
/// The optional code block run when the alternative is chosen.
pub block: Option<Box<CodeBlock>>,
}
/// One item of an alternative's right-hand side — §18.17's `rs_prod`.
#[derive(Debug)]
pub enum ProdItem {
/// `name`, or `name(args)` — a reference to another production.
Ref(ProdRef),
/// `{ … }` — ordinary statements, laid out as a `begin`/`end` body is.
Block(Box<CodeBlock>),
/// `if (expr) item [else item]`.
If {
/// Comments written between the `if` and its `(`.
after_kw: Vec<Comment>,
cond: Expr,
then: Box<ProdItem>,
/// Comments written between the `then` item and the `else`.
before_else: Vec<Comment>,
/// Comments written between the `else` and its item.
after_else: Vec<Comment>,
els: Option<Box<ProdItem>>,
},
/// `repeat (expr) item`.
Repeat {
/// Comments written between the `repeat` and its `(`.
after_kw: Vec<Comment>,
count: Expr,
body: Box<ProdItem>,
},
/// `case (expr) … endcase`, whose arms take production items rather than
/// statements.
Case {
/// Comments written between the `case` and its `(`.
after_kw: Vec<Comment>,
expr: Expr,
items: Vec<ProdCaseItem>,
/// Comments written after the last arm and before `endcase`.
dangling: Vec<Comment>,
},
/// `rand join [(expr)] item item { item }` (§18.17.6).
RandJoin {
/// Comments written between the `rand` and the `join`.
after_rand: Vec<Comment>,
/// The `( expr )` bias, `None` when omitted.
weight: Option<Expr>,
items: Vec<ProdItem>,
},
}
/// A reference to another production: `name` or `name(a, b)`.
#[derive(Debug)]
pub struct ProdRef {
pub name: String,
/// Byte range of `name`.
pub name_span: TextRange,
/// True when a `( … )` argument list was written, even an empty one.
pub has_parens: bool,
/// Comments written between the name and that `(`.
pub before_args: Vec<Comment>,
pub args: Vec<ExprItem>,
}
/// One arm of an `rs_case`: `expr, expr : item;` or `default [:] item;`.
#[derive(Debug)]
pub struct ProdCaseItem {
pub meta: Meta,
/// Empty for the `default` arm.
pub labels: Vec<ExprItem>,
/// True when the arm was written `default`.
pub is_default: bool,
/// Comments written between the labels (or the `default`) and the `:`.
pub before_colon: Vec<Comment>,
/// Comments written between the `:` and the item. A `default` arm may
/// write no `:` at all, and then this is the gap after the keyword.
pub after_colon: Vec<Comment>,
pub item: ProdItem,
/// Comments written between the item and the arm's `;`.
pub before_semi: Vec<Comment>,
/// Code extent of the arm, its `;` excluded.
pub span: TextRange,
}
/// An `rs_code_block`: `{ declarations statements }`. The braces are the
/// block's own, and what stands between them is the statement grammar.
///
/// There is no slot for the gap just inside the `{`: it belongs to the first
/// statement's leading comments, exactly as a `begin`/`end` block's does, and
/// to `dangling` when the block holds no statement at all.
#[derive(Debug)]
pub struct CodeBlock {
pub stmts: Vec<Stmt>,
/// Comments written after the last statement and before the `}`.
pub dangling: Vec<Comment>,
}
+48 -4
View File
@@ -253,9 +253,25 @@ pub enum StmtKind {
stmt: Option<Box<Stmt>>,
},
ExprStmt(Expr),
/// `-> event_name;`
EventTrigger(Expr),
/// `-> ev;` and the non-blocking `->> ev;` (IEEE 1800 §15.5.2), which may
/// carry a delay or event control of its own: `->> #5 ev;`,
/// `->> @(posedge clk) ev;`.
///
/// Boxed because the timing control is the size of a whole sensitivity
/// list and this is one of the smallest statements there is; see
/// `ast::size_pins`.
EventTrigger(Box<EventTrigger>),
VarDecl(DataDecl),
/// A block-scoped `let` (IEEE 1800 §11.13): `let sum = a + b;` written
/// among a `begin`/`end`'s declarations. Same grammar and same layout as
/// the item-level one, so it carries the item's node; boxed because a
/// `let` is rare and its node is wider than the statement kinds that are
/// not (see `ast::size_pins`).
Let(Box<LetDecl>),
/// `randsequence (main) … endsequence` (IEEE 1800 §18.17) — a production
/// grammar of its own, modelled in `ast::randsequence`. Boxed: a
/// production list is wide and a `randsequence` is rare.
RandSequence(Box<RandSequence>),
ParamDecl(ParamDecl),
/// Old-style task/function port declaration: `input [7:0] a;`
PortDecl(PortDecl),
@@ -266,7 +282,14 @@ pub enum StmtKind {
},
Break,
Continue,
Disable(String),
/// `disable blk;`, `disable fork;` — the label or task the statement
/// names, with the range it is written in. A *use*, not a declaration,
/// but it is addressable all the same, so it carries a span like every
/// other name (`disable fork` spans the `fork` keyword).
Disable {
name: String,
name_span: TextRange,
},
Directive(RawText),
/// Macro invocation used as a statement.
MacroStmt(MacroCall),
@@ -323,7 +346,7 @@ impl StmtKind {
| StmtKind::Return { .. }
| StmtKind::Break
| StmtKind::Continue
| StmtKind::Disable(_)
| StmtKind::Disable { .. }
| StmtKind::WaitFork
| StmtKind::DoWhile { .. } => true,
StmtKind::Timing { stmt, .. } => stmt.is_none(),
@@ -334,6 +357,27 @@ impl StmtKind {
}
}
/// An event trigger: `-> ev;` or the non-blocking `->> ev;`.
///
/// Only the non-blocking spelling may write a delay or an event control
/// between the arrow and the event (IEEE 1800 §15.5.2), but the node carries
/// one either way — lucisv reproduces what was written and is not a legality
/// checker.
#[derive(Debug)]
pub struct EventTrigger {
/// `->` or `->>`, as written.
pub arrow: String,
/// Comments written between the arrow and whatever follows it
/// (`->> /*c*/ #5 ev;`).
pub after_arrow: Vec<Comment>,
/// The `#5` or `@(posedge clk)` of `->> #5 ev;`.
pub timing: Option<TimingControl>,
/// Comments written between that timing control and the event name.
/// Empty when no timing control was written.
pub before_event: Vec<Comment>,
pub expr: Expr,
}
#[derive(Debug)]
pub enum TimingControl {
/// `#expr`
+3 -3
View File
@@ -52,9 +52,9 @@ struct RawLexer<'a> {
/// Multi-character operators, longest first so greedy matching works.
const OPERATORS: &[&str] = &[
"<<<=", ">>>=", "===", "!==", "==?", "!=?", "<<<", ">>>", "<<=", ">>=", "<->", "**", "==",
"!=", "<=", ">=", "&&", "||", "<<", ">>", "->", "=>", "::", "+:", "-:", "+=", "-=", "*=", "/=",
"%=", "&=", "|=", "^=", "++", "--", "~&", "~|", "~^", "^~", "##", "'{",
"<<<=", ">>>=", "===", "!==", "==?", "!=?", "<<<", ">>>", "<<=", ">>=", "<->", "->>", "**",
"==", "!=", "<=", ">=", "&&", "||", "<<", ">>", "->", "=>", "::", "+:", "-:", "+=", "-=", "*=",
"/=", "%=", "&=", "|=", "^=", "++", "--", "~&", "~|", "~^", "^~", "##", "'{",
];
const SINGLE_OPS: &[u8] = b"+-*/%&|^~!<>=?:;,.#@()[]{}'$";
+56 -23
View File
@@ -10,14 +10,26 @@ use super::item::MEMBER_QUALIFIERS;
use super::*;
impl<'a> Parser<'a> {
/// A type with nothing written for it, spanning the empty range at the
/// cursor: what a `parameter type T` and an implicit `input [7:0] x`
/// both carry. Distinct from [`DataType::default`] only in that its
/// `name_span` points at the source rather than at offset zero.
pub(super) fn implicit_type(&self) -> DataType {
DataType { name_start: self.here(), ..DataType::default() }
}
/// Parse a possibly-implicit data type. Stops before the declarator name.
pub(super) fn parse_opt_data_type(&mut self) -> PResult<DataType> {
let mut ty = DataType::default();
// An implicit type writes no name at all, so its `name_span` is the
// empty range where a name would have gone: right here, before
// anything of the type has been consumed.
let mut ty = self.implicit_type();
// `property p(sequence a, property b);` — inside a property's or a
// sequence's formal list, and nowhere else, the two keywords name a
// formal's *type* (IEEE 1800 §16.8). `untyped` needs no case: it is
// an ordinary identifier and already reads as a user-defined type.
if self.sva_formals && (self.cur().is_kw("sequence") || self.cur().is_kw("property")) {
ty.name_start = self.here();
ty.name = self.bump().text;
return Ok(ty);
}
@@ -35,7 +47,9 @@ impl<'a> Parser<'a> {
// Glued onto the interface name exactly as an interface *port*'s
// modport is, so every consumer still sees one type-name string.
if self.at_modport_port() {
ty.name = self.parse_modport_port_type()?.name;
let head = self.parse_modport_port_type()?;
ty.name = head.name;
ty.name_start = head.name_start;
return Ok(ty);
}
}
@@ -53,18 +67,15 @@ impl<'a> Parser<'a> {
return Ok(ty);
}
if t.kind == TokenKind::Keyword && TYPE_KEYWORDS.contains(&t.text.as_str()) {
ty.name_start = self.here();
ty.name = self.bump().text;
} else if t.kind == TokenKind::Ident {
// User-defined type only if what follows still leaves an
// identifier for the declarator name.
if self.at_typed_declarator() {
let mut name = self.expect_ident()?;
while self.cur().is_sym("::") {
self.bump();
let segment = self.expect_ident()?;
Self::push_scope_segment(&mut name, &segment);
}
let (name, span) = self.parse_scoped_name()?;
ty.name = name;
ty.name_start = span.start;
if self.at_type_params() {
ty.extra = Some(Box::new(TypeExtra::Params(self.parse_type_params()?)));
}
@@ -187,7 +198,7 @@ impl<'a> Parser<'a> {
// parameter outside the `#( ... )` list
// (lossy_valid_to_stream_tb.sv:26). Its default is a type, not a value.
let is_type = self.eat_kw("type");
let ty = if is_type { DataType::default() } else { self.parse_opt_data_type()? };
let ty = if is_type { self.implicit_type() } else { self.parse_opt_data_type()? };
let declarators = self.parse_declarator_list(is_type)?;
Ok(ParamDecl { kw, after_kw, is_type, ty, declarators })
}
@@ -249,12 +260,11 @@ impl<'a> Parser<'a> {
break;
}
}
let delay = if net.is_some() && self.cur().is_sym("#") {
self.bump();
Some(self.parse_delay_value()?)
} else {
None
};
// `wire (strong0, weak1) w = a;` — IEEE 1800 §6.6 writes the strength
// directly after the net keyword and nowhere else, so a `(` here is
// only read as one when a net keyword was actually written.
let strength = if net.is_some() { self.parse_opt_drive_strength()? } else { None };
let before = self.parse_net_delay(net.is_some(), false)?;
// A declaration reaches here with its `virtual` already in
// `qualifiers`, so `parse_opt_data_type`'s own modport branch cannot
// fire: `virtual spi_if.tb tb_sif = sif.tb;`
@@ -265,9 +275,37 @@ impl<'a> Parser<'a> {
} else {
self.parse_opt_data_type()?
};
// IEEE 1800 §6.7 writes the delay *here*, after the data type
// (`wire [31:0] #0.1 x = y;`, `pulp_riscv_dbg/tb/unused/SimDTM.sv:38`);
// everything else in the corpus writes it before. Either is read and
// printed back where it stood, but a declaration with one on each
// side is not a shape the LRM has.
let after = self.parse_net_delay(net.is_some(), true)?;
let delay = match (before, after) {
(Some(_), Some(_)) => {
return self.error("a net delay is written before or after the type, not both")
}
(before, after) => before.or(after),
};
let declarators = self.parse_declarators()?;
self.expect_sym(";")?;
Ok(DataDecl { net, delay, qualifiers, ty, declarators })
Ok(DataDecl { net, strength, delay, qualifiers, ty, declarators })
}
/// The net delay at the cursor, if one is written there: `#5`, `#0.1`,
/// `#(1:2:3)`. Only a net declaration may carry one, so `is_net` gates
/// the whole read — a `#` anywhere else belongs to whoever comes next.
fn parse_net_delay(&mut self, is_net: bool, after_type: bool) -> PResult<Option<NetDelay>> {
if !is_net || !self.cur().is_sym("#") {
return Ok(None);
}
// The `#` is written, so the gap in front of it is the delay's own:
// `wire /* c */ #5 w;`. Taken only here — when the read does not
// happen the gap belongs to whatever comes next.
let before_hash = self.take_gap();
self.bump();
let after_hash = self.take_gap();
Ok(Some(NetDelay { before_hash, after_hash, expr: self.parse_delay_value()?, after_type }))
}
pub(super) fn parse_port_decl(&mut self) -> PResult<PortDecl> {
@@ -451,13 +489,8 @@ impl<'a> Parser<'a> {
if !ty.is_implicit() || self.cur().kind != TokenKind::Ident {
return Ok(ty);
}
let mut name = self.expect_ident()?;
while self.cur().is_sym("::") {
self.bump();
let segment = self.expect_ident()?;
Self::push_scope_segment(&mut name, &segment);
}
let mut ty = DataType { name, ..DataType::default() };
let (name, span) = self.parse_scoped_name()?;
let mut ty = DataType { name, name_start: span.start, ..DataType::default() };
if self.at_type_params() {
ty.extra = Some(Box::new(TypeExtra::Params(self.parse_type_params()?)));
}
+44 -6
View File
@@ -265,14 +265,16 @@ impl<'a> Parser<'a> {
|| (t.is_sym("'{") && self.is_cast_base(base))
|| t.is_sym("++")
|| t.is_sym("--")
// `with ( ... )` (an array method's iterator argument) and
// `with { ... }` (a `randomize` constraint block) are the two
// postfix spellings of `with`; the delimiter tells them apart and
// demanding one keeps the `with [range]` of a stream expression,
// which lucisv does not model, out of this path.
// `with ( ... )` (an array method's iterator argument),
// `with { ... }` (a `randomize` constraint block) and
// `with [ ... ]` (a stream expression's array range,
// IEEE 1800 §11.4.14) are the three postfix spellings of `with`;
// the delimiter after the keyword is what tells them apart.
|| (t.is_kw("with")
&& !self.no_with
&& (self.nth(1).is_sym("(") || self.nth(1).is_sym("{")))
&& (self.nth(1).is_sym("(")
|| self.nth(1).is_sym("{")
|| self.nth(1).is_sym("[")))
}
/// True when the `[` at the cursor opens a transition or consecutive
@@ -363,6 +365,35 @@ impl<'a> Parser<'a> {
))
}
/// The `[ … ]` of a stream expression's `with` (IEEE 1800 §11.4.14), the
/// `with` already consumed: one index or a range in any of the three
/// spellings a part select takes.
///
/// `with_comments` arrives holding what was written in front of the
/// keyword; the gap after it is that same node's `after_kw`, so the two
/// halves of `a /*x*/ with /*y*/ [i]` keep their own sides of the word and
/// the printer lays the head out through the one function all three
/// postfix `with` forms share.
fn parse_stream_range(&mut self, mut with_comments: WithComments) -> PResult<StreamRange> {
with_comments.after_kw = self.take_before_open("[");
let mut comments = SegmentComments::default();
self.expect_sym("[")?;
comments.after_open = self.take_gap();
let msb = self.parse_expr()?;
let t = self.cur();
let (op, lsb) = if t.is_sym(":") || t.is_sym("+:") || t.is_sym("-:") {
comments.before_op = self.take_gap();
let op = self.bump().text;
comments.after_op = self.take_gap();
(Some(op), Some(self.parse_expr()?))
} else {
(None, None)
};
comments.before_close = self.gap_before("]");
self.expect_sym("]")?;
Ok(StreamRange { with_comments, msb, op, lsb, comments })
}
fn parse_postfix_inner(&mut self) -> PResult<Expr> {
let mut expr = self.parse_primary()?;
while self.at_postfix_segment(&expr) {
@@ -430,6 +461,13 @@ impl<'a> Parser<'a> {
comments: Box::new(comments),
},
);
} else if self.nth(1).is_sym("[") {
self.bump(); // with
let range = self.parse_stream_range(comments)?;
expr = self.expr_at(
start,
ExprKind::StreamWith { base: Box::new(expr), range: Box::new(range) },
);
} else {
self.bump(); // with
comments.after_kw = self.take_before_open("(");
+93 -31
View File
@@ -21,9 +21,17 @@ impl<'a> Parser<'a> {
pub(super) fn parse_cont_assign(&mut self) -> PResult<ContAssign> {
self.expect_kw("assign")?;
let strength = self.parse_opt_drive_strength()?;
let mut after_hash = Vec::new();
let mut after_delay = Vec::new();
let delay = if self.cur().is_sym("#") {
self.bump();
Some(self.parse_delay_value()?)
after_hash = self.take_gap();
let delay = self.parse_delay_value()?;
// The gap between the delay and the first left-hand side is the
// delay's, not the pair's: a pair's leading comments print right
// after the `assign`, which is in front of the delay.
after_delay = self.take_gap();
Some(delay)
} else {
None
};
@@ -55,7 +63,7 @@ impl<'a> Parser<'a> {
}
}
self.expect_sym(";")?;
Ok(ContAssign { strength, delay, assigns })
Ok(ContAssign { strength, after_hash, delay, after_delay, assigns })
}
/// The optional `( strength0 , strength1 )` of a continuous assignment
@@ -68,22 +76,32 @@ impl<'a> Parser<'a> {
/// strength when a strength keyword follows it, so a parenthesized
/// left-hand side — and a gate whose first argument is an expression — is
/// untouched.
fn parse_opt_drive_strength(&mut self) -> PResult<Option<DriveStrength>> {
pub(super) fn parse_opt_drive_strength(&mut self) -> PResult<Option<DriveStrength>> {
if !self.cur().is_sym("(") || !is_drive_strength(self.nth(1)) {
return Ok(None);
}
let mut comments =
Box::new(DriveStrengthComments { before_open: self.take_gap(), ..Default::default() });
self.bump(); // (
comments.after_open = self.take_gap();
let first = self.bump().text;
// The gap after the first strength ends either at the `,` or at the
// `)`, and it is that token which says which slot it belongs in.
let gap = self.take_gap();
if self.eat_sym(")") {
return Ok(Some(DriveStrength { first, second: None }));
comments.before_close = gap;
return Ok(Some(DriveStrength { first, second: None, comments }));
}
comments.before_comma = gap;
self.expect_sym(",")?;
comments.after_comma = self.take_gap();
if !is_drive_strength(self.cur()) {
return self.error("expected a drive strength");
}
let second = Some(self.bump().text);
comments.before_close = self.gap_before(")");
self.expect_sym(")")?;
Ok(Some(DriveStrength { first, second }))
Ok(Some(DriveStrength { first, second, comments }))
}
/// The value after a `#`: a bare primary, or a parenthesized delay —
@@ -94,46 +112,75 @@ impl<'a> Parser<'a> {
/// spelling has always produced, so `#(5)` and `#(1:2:3)` still print
/// exactly as written; only a real comma list yields more than one
/// element.
fn parse_delay_values(&mut self) -> PResult<Vec<Expr>> {
fn parse_delay_values(&mut self) -> PResult<Vec<DelayValue>> {
if !self.cur().is_sym("(") {
return Ok(vec![self.parse_primary()?]);
let expr = self.parse_primary()?;
return Ok(vec![DelayValue { leading: Vec::new(), expr, trailing: Vec::new() }]);
}
let start = self.here();
self.bump(); // (
let mut out = Vec::new();
// What is written just inside the `(` belongs to the first value; the
// gap before each `,` and the gap after it belong to the values either
// side of it.
self.bump();
let mut leading = self.take_gap();
let mut out: Vec<DelayValue> = Vec::new();
loop {
let inner_start = self.here();
let first = self.parse_expr()?;
out.push(if self.eat_sym(":") {
let typ = self.parse_expr()?;
self.expect_sym(":")?;
let max = self.parse_expr()?;
self.expr_at(
inner_start,
ExprKind::MinTypMax {
min: Box::new(first),
typ: Box::new(typ),
max: Box::new(max),
},
)
} else {
first
});
let expr = self.parse_min_typ_max_tail(inner_start, first)?;
let trailing = self.gap_before(",");
out.push(DelayValue { leading: std::mem::take(&mut leading), expr, trailing });
if !self.eat_sym(",") {
break;
}
leading = self.take_gap();
}
if let Some(last) = out.last_mut() {
last.trailing = self.gap_before(")");
}
self.expect_sym(")")?;
if out.len() == 1 {
let inner = out.remove(0);
return Ok(vec![self.expr_at(
// One value keeps the `( )` node the one-value spelling has always
// produced, and its two comment slots are where the paren gaps go.
let DelayValue { leading, expr, trailing } = out.remove(0);
let paren = self.expr_at(
start,
ExprKind::Paren { inner: Box::new(inner), before: Vec::new(), after: Vec::new() },
)]);
ExprKind::Paren { inner: Box::new(expr), before: leading, after: trailing },
);
return Ok(vec![DelayValue { leading: Vec::new(), expr: paren, trailing: Vec::new() }]);
}
Ok(out)
}
/// The `: typ : max` tail of a `min : typ : max` expression, or `min`
/// unchanged when no `:` follows it.
///
/// One grammar for the two places that write it — a delay list and a
/// parenthesized expression — so the four comment slots around the two
/// colons exist in both.
pub(super) fn parse_min_typ_max_tail(&mut self, start: u32, min: Expr) -> PResult<Expr> {
let before_typ = self.gap_before(":");
if !self.eat_sym(":") {
return Ok(min);
}
let mut comments = MinTypMaxComments { before_typ, ..Default::default() };
comments.after_typ = self.take_gap();
let typ = self.parse_expr()?;
comments.before_max = self.gap_before(":");
self.expect_sym(":")?;
comments.after_max = self.take_gap();
let max = self.parse_expr()?;
Ok(self.expr_at(
start,
ExprKind::MinTypMax {
min: Box::new(min),
typ: Box::new(typ),
max: Box::new(max),
comments: Box::new(comments),
},
))
}
/// The single delay value a net declaration or a continuous assignment
/// takes. The multi-value list is a gate-instantiation spelling only —
/// see [`Parser::parse_delay_values`].
@@ -142,7 +189,9 @@ impl<'a> Parser<'a> {
if values.len() > 1 {
return self.error("a multi-value delay list is only allowed on a gate instantiation");
}
Ok(values.remove(0))
// A lone value carries no comments of its own: `parse_delay_values`
// folded the paren gaps into its `ExprKind::Paren`.
Ok(values.remove(0).expr)
}
/// True when the cursor opens a `bind` directive (IEEE 1800 §23.11).
@@ -647,8 +696,11 @@ impl<'a> Parser<'a> {
// instance's argument list would, and only a strength keyword after
// the `(` tells the two apart.
let strength = self.parse_opt_drive_strength()?;
let before_hash = self.take_before_open("#");
let mut after_hash = Vec::new();
let delay = if self.cur().is_sym("#") {
self.bump();
after_hash = self.take_gap();
self.parse_delay_values()?
} else {
Vec::new()
@@ -660,6 +712,7 @@ impl<'a> Parser<'a> {
let name =
if self.cur().kind == TokenKind::Ident { Some(self.expect_name()?) } else { None };
let (name, name_span) = split_label(name);
let before_args = self.take_before_open("(");
self.expect_sym("(")?;
let mut args = Vec::new();
if !self.cur().is_sym(")") {
@@ -673,12 +726,21 @@ impl<'a> Parser<'a> {
if more {
meta.trailing = self.take_trailing();
}
instances.push(GateInstance { meta, name, name_span, args, span });
instances.push(GateInstance { meta, name, name_span, before_args, args, span });
if !more {
break;
}
}
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
Ok(GateInstantiation { gate, strength, delay, instances })
Ok(GateInstantiation {
gate,
strength,
before_hash,
after_hash,
delay,
instances,
before_semi,
})
}
}
+12 -2
View File
@@ -167,18 +167,21 @@ impl<'a> Parser<'a> {
// `disable fork;` kills every process the enclosing `fork`
// started; `fork` is a keyword, not a block name.
if self.cur().is_kw("fork") {
let name_span = self.cur().span;
self.bump();
self.expect_stmt_semi()?;
return Ok(StmtKind::Disable("fork".to_string()));
return Ok(StmtKind::Disable { name: "fork".to_string(), name_span });
}
let start = self.here();
let mut name = self.expect_ident()?;
while self.cur().is_sym(".") {
self.bump();
name.push('.');
name.push_str(&self.expect_ident()?);
}
let name_span = self.span_from(start);
self.expect_stmt_semi()?;
Ok(StmtKind::Disable(name))
Ok(StmtKind::Disable { name, name_span })
}
"wait" => {
self.bump();
@@ -235,6 +238,13 @@ impl<'a> Parser<'a> {
// A package import standing among a block's declarations
// (IEEE 1800 §13.4.2): the same statement the item level takes.
"import" => Ok(StmtKind::Import(self.parse_import_list()?)),
// A block-scoped `let` (IEEE 1800 §11.13). `parse_let` reads the
// `;` itself, which is why `takes_semi()` says this kind takes
// none — exactly as the item-level spelling works.
"let" => Ok(StmtKind::Let(Box::new(self.parse_let()?))),
// `randsequence` reads its own `endsequence`, so like a block it
// takes no `;` of its own (`takes_semi()` says so).
"randsequence" => Ok(StmtKind::RandSequence(Box::new(self.parse_randsequence()?))),
// A block-scoped type (IEEE 1800 §6.18), e.g.
// `spi_host/dv/env/seq_lib/spi_host_base_vseq.sv:577`. Same
// grammar and same layout as the item-level `typedef`.
+2
View File
@@ -37,6 +37,7 @@
//! | `expr`, `primary` | the operator grammar; its leaves and argument lists |
//! | `class`, `covergroup` | classes with their constraints; covergroups |
//! | `assertion`, `sva` | concurrent assertions and SVA declarations; the property grammar |
//! | `randsequence` | the `randsequence` production grammar (IEEE 1800 §18.17) |
//! | `directive` | `` `ifdef `` tracking, list directives, macros, fragment mode |
//! | `split` | conditional-directive split recovery |
//! | `verbatim` | vendor/formal blocks kept as bytes, and the capture helpers |
@@ -59,6 +60,7 @@ mod item;
mod keyword_stmt;
mod module;
mod primary;
mod randsequence;
mod recover;
mod recover_list;
mod split;
+90 -22
View File
@@ -2,6 +2,7 @@
//! belong only to them: parameter ports, ports (ANSI and non-ANSI),
//! modports and clocking blocks.
use super::split::UnitHead;
use super::*;
/// The three pieces a `#( parameter ... )` port list yields, so module and
@@ -21,6 +22,7 @@ impl<'a> Parser<'a> {
/// one header grammar (IEEE 1800 §23.2.1, §25.3) and one body item list —
/// only the closing keyword differs, so `end_kw` is the whole difference.
pub(super) fn parse_module(&mut self, end_kw: &str) -> PResult<Module> {
let conds = self.open_conds;
let kw = self.bump().text;
let before_name = self.take_gap();
let Name { text: name, span: name_span } = self.expect_name()?;
@@ -47,8 +49,18 @@ impl<'a> Parser<'a> {
// behind it is what the module is for.
self.expect_after_recovery(";", self.recovered_since(mark))?;
let mut items = Vec::new();
let mut head = UnitHead { kw: &kw, name: &name, conds, floor: conds };
while !self.at_body_end(end_kw) {
// Two rival headers written across the arms of one `ifdef region
// are bracket-balanced, so nothing else in the grammar objects
// until this unit runs out of file looking for its `end` keyword.
// Failing here instead routes the whole unit into the split
// recovery; see `docs/features/parser-skips/README.md`.
if self.at_rival_header(&head) {
return self.error(format!("rival header for `{name}` in a conditional region"));
}
items.push(self.item_or_recover()?);
head.floor = head.floor.min(self.open_conds);
}
let dangling = self.take_dangling();
self.expect_closer(end_kw)?;
@@ -205,15 +217,21 @@ impl<'a> Parser<'a> {
/// `default` keyword, when written, has already been consumed.
pub(super) fn parse_clocking(&mut self, is_default: bool) -> PResult<ClockingDecl> {
self.expect_kw("clocking")?;
let after_kw = self.take_gap();
let name =
if self.cur().kind == TokenKind::Ident { Some(self.expect_name()?) } else { None };
let before_event = if self.cur().is_sym("@") { self.take_gap() } else { Vec::new() };
// `default clocking cb;` selects an existing block and has no body.
let event = if self.eat_sym("@") { Some(self.parse_sens_list()?) } else { None };
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
if event.is_none() {
return Ok(ClockingDecl {
is_default,
after_kw,
name,
before_event,
before_semi,
event,
items: Vec::new(),
dangling: Vec::new(),
@@ -233,7 +251,10 @@ impl<'a> Parser<'a> {
let (end_label, end_label_span) = split_label(end_name);
Ok(ClockingDecl {
is_default,
after_kw,
name,
before_event,
before_semi,
event,
items,
dangling,
@@ -250,9 +271,8 @@ impl<'a> Parser<'a> {
let start = self.here();
let mut meta = self.take_meta();
let kind = if self.eat_kw("default") {
let input = if self.eat_kw("input") { Some(self.parse_clocking_skew()?) } else { None };
let output =
if self.eat_kw("output") { Some(self.parse_clocking_skew()?) } else { None };
let input = self.parse_clocking_default("input")?;
let output = self.parse_clocking_default("output")?;
if input.is_none() && output.is_none() {
return self.error("expected `input` or `output` after `default`");
}
@@ -263,20 +283,28 @@ impl<'a> Parser<'a> {
return self.error("expected a clocking item");
}
let dir = self.bump().text;
let skew =
if self.at_clocking_skew() { Some(self.parse_clocking_skew()?) } else { None };
let after_dir = self.take_gap();
let mut after_skew = Vec::new();
let skew = if self.at_clocking_skew() {
let skew = self.parse_clocking_skew()?;
after_skew = self.take_gap();
Some(skew)
} else {
None
};
let mut signals = vec![self.parse_clocking_signal()?];
while self.eat_sym(",") {
signals.push(self.parse_clocking_signal()?);
}
ClockingItemKind::Signals { dir, skew, signals }
ClockingItemKind::Signals { dir, after_dir, skew, after_skew, signals }
};
let span = self.span_from(start);
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
if meta.trailing.is_none() {
meta.trailing = self.take_trailing();
}
Ok(ClockingItem { meta, kind, span })
Ok(ClockingItem { meta, kind, before_semi, span })
}
/// One `signal [= expression]` of a clocking direction group — IEEE 1800
@@ -289,6 +317,21 @@ impl<'a> Parser<'a> {
Ok(ClockingSignal { name, value })
}
/// One half of a `default input #1step output #0;` item: the direction
/// keyword `dir` and its skew, or `None` when this half was not written.
///
/// The gap in front of the keyword is the half's own, so the two halves
/// keep their own sides of the word that separates them.
fn parse_clocking_default(&mut self, dir: &str) -> PResult<Option<ClockingDefault>> {
if !self.cur().is_kw(dir) {
return Ok(None);
}
let before_dir = self.take_gap();
self.bump();
let after_dir = self.take_gap();
Ok(Some(ClockingDefault { before_dir, after_dir, skew: self.parse_clocking_skew()? }))
}
/// True when the cursor is on a clocking skew rather than on the first
/// signal name: `#2`, `#1step`, `posedge`, `negedge`, `edge`.
fn at_clocking_skew(&self) -> bool {
@@ -296,25 +339,47 @@ impl<'a> Parser<'a> {
t.is_sym("#") || t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge")
}
/// A clocking skew, as written: `#2`, `#1step`, `negedge`. Kept as text —
/// it is a delay or an edge, never something lucisv re-lays out — so the
/// printer writes back exactly what the source said. The `#(min:typ:max)`
/// spelling is not supported; see the feature README's Assumptions.
fn parse_clocking_skew(&mut self) -> PResult<String> {
if self.eat_sym("#") {
let t = self.cur();
if !matches!(t.kind, TokenKind::Number | TokenKind::Ident) {
return self.error("expected a clocking skew delay");
}
return Ok(format!("#{}", self.bump().text));
/// A clocking skew, as written: `#2`, `#1step`, the parenthesized
/// `#(1:2:3)`, an edge identifier, or — IEEE 1800 §14.3's first
/// alternative — an edge identifier with a delay behind it
/// (`negedge #(1:2:3)`).
fn parse_clocking_skew(&mut self) -> PResult<ClockingSkew> {
if self.cur().is_sym("#") {
return Ok(ClockingSkew::Delay(self.parse_clocking_delay()?));
}
let t = self.cur();
if t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge") {
return Ok(self.bump().text);
let word = self.bump().text;
// Only a gap that really is in front of a `#` is the edge's own;
// otherwise it belongs to the caller's slot before the name.
let after_edge = self.gap_before("#");
let delay =
if self.cur().is_sym("#") { Some(self.parse_clocking_delay()?) } else { None };
return Ok(ClockingSkew::Edge { word, after_edge, delay });
}
self.error("expected a clocking skew")
}
/// The `# …` half of a clocking skew.
///
/// The one-token spellings are kept as text — a delay is never something
/// lucisv re-lays out — so the printer writes back exactly what the source
/// said. The parenthesized one goes through the delay-value grammar every
/// other `#( … )` uses, which is what gives its `:` and its parens their
/// comment slots.
fn parse_clocking_delay(&mut self) -> PResult<ClockingDelay> {
self.expect_sym("#")?;
let after_hash = self.take_gap();
if self.cur().is_sym("(") {
return Ok(ClockingDelay::Paren { after_hash, expr: self.parse_delay_value()? });
}
let t = self.cur();
if !matches!(t.kind, TokenKind::Number | TokenKind::Ident) {
return self.error("expected a clocking skew delay");
}
Ok(ClockingDelay::Word { after_hash, word: self.bump().text })
}
/// A `#( parameter ... )` port list, shared by module and class headers.
/// `ports` is `None` when no `#(` was written at the cursor at all.
pub(super) fn parse_param_port_list(&mut self) -> PResult<ParamPortList> {
@@ -400,7 +465,7 @@ impl<'a> Parser<'a> {
meta,
kw,
after_kw,
ty: DataType::default(),
ty: self.implicit_type(),
is_type: true,
before_name,
name,
@@ -612,12 +677,15 @@ impl<'a> Parser<'a> {
/// The `bus_if.mp` of an interface port, as its type. The modport is glued
/// onto the interface name exactly as a `pkg::` qualifier is, so every
/// consumer that prints or scans a type name still sees one string.
/// consumer that prints a type name still sees one string;
/// [`DataType::segments`] splits it back into its two halves and their
/// ranges.
pub(super) fn parse_modport_port_type(&mut self) -> PResult<DataType> {
let name_start = self.here();
let mut name = self.expect_ident()?;
self.expect_sym(".")?;
name.push('.');
name.push_str(&self.expect_ident()?);
Ok(DataType { name, ..DataType::default() })
Ok(DataType { name, name_start, ..DataType::default() })
}
}
+27 -18
View File
@@ -97,21 +97,7 @@ impl<'a> Parser<'a> {
let mark = self.pending_trailing.len();
let inner_start = self.here();
let inner = self.parse_expr()?;
let inner = if self.eat_sym(":") {
let typ = self.parse_expr()?;
self.expect_sym(":")?;
let max = self.parse_expr()?;
self.expr_at(
inner_start,
ExprKind::MinTypMax {
min: Box::new(inner),
typ: Box::new(typ),
max: Box::new(max),
},
)
} else {
inner
};
let inner = self.parse_min_typ_max_tail(inner_start, inner)?;
let after = self.take_around(mark);
self.expect_sym(")")?;
Ok(self.expr_at(
@@ -160,20 +146,25 @@ impl<'a> Parser<'a> {
/// its `<<` or `>>`: IEEE 1800 §11.4.14
/// `{ (<<|>>) [slice_size] { stream_expression {, stream_expression} } }`.
///
/// The `with [range]` form of a stream expression is not supported; a
/// file using it keeps its old "expected expression" error.
/// A stream expression's `with [range]` is read by `parse_postfix_inner`,
/// as the postfix segment it is; the elements here are ordinary
/// expressions either way.
fn parse_stream_concat(&mut self, start: u32) -> PResult<Expr> {
let mut comments =
Box::new(StreamComments { after_open: self.take_gap(), ..Default::default() });
let dir = self.bump().text;
// The slice size is optional and is a constant expression or a type
// (`{<< byte {x}}`); a `{` here means it was omitted.
let slice =
if self.cur().is_sym("{") { None } else { Some(Box::new(self.parse_expr_or_type()?)) };
comments.before_inner = self.take_before_open("{");
self.expect_sym("{")?;
let first = self.parse_expr_item()?;
let inner = self.parse_expr_list(first, "}")?;
self.expect_sym("}")?;
comments.before_close = self.gap_before("}");
self.expect_sym("}")?;
Ok(self.expr_at(start, ExprKind::Stream { dir, slice, inner }))
Ok(self.expr_at(start, ExprKind::Stream { dir, slice, inner, comments }))
}
/// True when `e` may stand left of a cast's `'` — the `constant_primary`
@@ -194,6 +185,14 @@ impl<'a> Parser<'a> {
| ExprKind::Scope { .. }
| ExprKind::Member { .. }
| ExprKind::Paren { .. } => true,
// A data type with dimensions on it — `logic [3:0]'(x)`,
// `bit signed [7:0]'(y)`. A bare `int'(x)` never reaches here
// (`parse_primary` takes the keyword-and-tick shape itself); this
// is the spelling whose `[3:0]` sent it down `parse_type_expr`
// instead. IEEE 1800 §6.24.1's `casting_type` names only
// `simple_type`, but every tool in use accepts the packed
// dimensions and lucisv is not a legality checker.
ExprKind::Type(_) => true,
ExprKind::Call { callee, .. } => {
matches!(&callee.kind, ExprKind::Ident(n) if n.starts_with('$'))
}
@@ -454,8 +453,18 @@ impl<'a> Parser<'a> {
}
/// In parameter connections a value may be a type (`.T(logic [7:0])`).
///
/// An **anonymous aggregate** is a type too — `.T(struct packed { logic a;
/// })`, the override a `parameter type` defaulting to one takes (IEEE 1800
/// §6.19, §7.2). `parse_type_ref` has read that body since the first day;
/// only this door was closed, because `struct`/`union`/`enum` are not in
/// [`TYPE_KEYWORDS`] and so fell through to `parse_expr`, whose keyword arm
/// answers "unexpected keyword `struct` in expression".
pub(super) fn parse_expr_or_type(&mut self) -> PResult<Expr> {
let t = self.cur();
if t.is_kw("struct") || t.is_kw("union") || t.is_kw("enum") {
return self.parse_type_expr();
}
if t.kind == TokenKind::Keyword
&& TYPE_KEYWORDS.contains(&t.text.as_str())
&& !self.nth(1).is_sym("'")
@@ -0,0 +1,316 @@
//! `randsequence` — the production grammar of IEEE 1800 §18.17.
//!
//! One file for one sub-grammar, the way the SVA and covergroup grammars each
//! have their own: a `randsequence` body is a production list, not a
//! statement list, and nothing outside it reads these productions.
//!
//! The nesting between an alternative's items and the control shapes that
//! wrap them is real recursion, so `parse_prod_item` brackets itself with
//! [`Parser::enter`] / [`Parser::leave`] the way every other recursive
//! production does.
use super::*;
impl<'a> Parser<'a> {
/// `randsequence ( [name] ) production { production } endsequence`
/// (IEEE 1800 §18.17), the cursor on the keyword.
pub(super) fn parse_randsequence(&mut self) -> PResult<RandSequence> {
self.expect_kw("randsequence")?;
let after_kw = self.take_before_open("(");
self.expect_sym("(")?;
let after_open = self.take_gap();
let start =
if self.cur().kind == TokenKind::Ident { Some(self.expect_name()?) } else { None };
let before_close = self.gap_before(")");
self.expect_sym(")")?;
let mut productions = Vec::new();
while !self.at_body_end("endsequence") {
productions.push(self.parse_production()?);
}
let dangling = self.take_dangling();
self.expect_closer("endsequence")?;
Ok(RandSequence { after_kw, after_open, start, before_close, productions, dangling })
}
/// One production: `[data_type] name [( ports )] : alternatives ;`.
///
/// The optional return type is told from the name by what follows the
/// identifier: a production's name is the last identifier before the `(`,
/// the `:` or another identifier, so a second identifier means the first
/// one was the type.
fn parse_production(&mut self) -> PResult<Production> {
let start = self.here();
let mut meta = self.take_meta();
let ret_type = self.parse_opt_production_type()?;
let Name { text: name, span: name_span } = self.expect_name()?;
let has_parens = self.cur().is_sym("(");
let args = self.parse_tf_ports(false)?.args;
let before_colon = self.gap_before(":");
self.expect_sym(":")?;
let mut alternatives = vec![self.parse_alternative(Vec::new())?];
while self.cur().is_sym("|") {
// The gap in front of the `|` belongs to the alternative it opens,
// so it prints on the bar's own side of the previous one.
let before_bar = self.take_gap();
self.bump();
alternatives.push(self.parse_alternative(before_bar)?);
}
let span = self.span_from(start);
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
if meta.trailing.is_none() {
meta.trailing = self.take_trailing();
}
Ok(Production {
meta,
ret_type,
name,
name_span,
has_parens,
args,
before_colon,
alternatives,
before_semi,
span,
})
}
/// The production's return type, when it wrote one. `void` is a keyword
/// rather than an identifier, so it is read here too and kept as the type
/// name it is written as.
fn parse_opt_production_type(&mut self) -> PResult<Option<DataType>> {
let t = self.cur();
let typed = if t.is_kw("void") {
true
} else if t.kind == TokenKind::Keyword {
// `int name : …`, `bit [3:0] name : …` — a type keyword can only
// be the type, never the production's own name.
TYPE_KEYWORDS.contains(&t.text.as_str())
} else {
// Two identifiers in a row: the first is a user-defined type.
t.kind == TokenKind::Ident && self.nth(1).kind == TokenKind::Ident
};
if !typed {
return Ok(None);
}
Ok(Some(self.parse_opt_data_type()?))
}
/// One `|`-separated right-hand side, with its optional `:= weight`.
fn parse_alternative(&mut self, before_bar: Vec<Comment>) -> PResult<Alternative> {
let after_bar = self.take_gap();
let mut items = vec![self.parse_prod_item()?];
while self.at_prod_item() {
items.push(self.parse_prod_item()?);
}
let mut before_weight = Vec::new();
let mut weight = None;
if self.at_weight_op() {
before_weight = self.take_gap();
self.bump(); // :
self.bump(); // =
weight = Some(self.parse_weight()?);
}
Ok(Alternative { before_bar, after_bar, items, before_weight, weight })
}
/// True when the cursor is on the `:=` of a weight. The lexer has no `:=`
/// token — it is a `:` and an `=` written adjacently, the same two tokens
/// a `dist` weight is read from — so adjacency is checked by span and
/// `a : = 5` written with a space is not one.
fn at_weight_op(&self) -> bool {
self.cur().is_sym(":")
&& self.nth(1).is_sym("=")
&& self.nth(1).span.start == self.cur().span.end
}
/// The `:= expr [ { code } ]` of a weighted alternative (§18.17.2).
///
/// §18.17.2's `weight_specification` is a number, a scoped name or a
/// *parenthesized* expression — never a bare operator expression — and
/// that is what keeps `a := 3 | b := 2` readable: an unparenthesized `|`
/// separates the alternatives, it does not or two weights together. So
/// the weight is read as a postfix expression and stops there.
fn parse_weight(&mut self) -> PResult<Weight> {
let after_op = self.take_gap();
let expr = self.parse_postfix()?;
let block =
if self.cur().is_sym("{") { Some(Box::new(self.parse_rs_code_block()?)) } else { None };
Ok(Weight { after_op, expr, block })
}
/// True when the cursor opens another item of the alternative rather than
/// ending it. An alternative ends at `|`, `:=`, `;`, or the `}` / `endcase`
/// of whatever encloses it.
fn at_prod_item(&self) -> bool {
let t = self.cur();
t.kind == TokenKind::Ident
|| t.is_sym("{")
|| t.is_kw("if")
|| t.is_kw("repeat")
|| t.is_kw("case")
|| t.is_kw("rand")
}
/// One `rs_prod`: a production reference, a code block, or one of the four
/// control shapes.
fn parse_prod_item(&mut self) -> PResult<ProdItem> {
self.enter()?;
let item = self.parse_prod_item_inner();
self.leave();
item
}
fn parse_prod_item_inner(&mut self) -> PResult<ProdItem> {
let t = self.cur();
if t.is_sym("{") {
return Ok(ProdItem::Block(Box::new(self.parse_rs_code_block()?)));
}
if t.is_kw("if") {
return self.parse_rs_if();
}
if t.is_kw("repeat") {
self.bump();
let after_kw = self.take_before_open("(");
self.expect_sym("(")?;
let count = self.parse_expr()?;
self.expect_sym(")")?;
let body = Box::new(self.parse_prod_item()?);
return Ok(ProdItem::Repeat { after_kw, count, body });
}
if t.is_kw("case") {
return self.parse_rs_case();
}
if t.is_kw("rand") {
return self.parse_rand_join();
}
Ok(ProdItem::Ref(self.parse_prod_ref()?))
}
/// `if ( expr ) item [ else item ]` — the arms are production items, not
/// statements, so this is not `parse_if_stmt`.
fn parse_rs_if(&mut self) -> PResult<ProdItem> {
self.expect_kw("if")?;
let after_kw = self.take_before_open("(");
self.expect_sym("(")?;
let cond = self.parse_expr()?;
self.expect_sym(")")?;
let then = Box::new(self.parse_prod_item()?);
// Whatever was written in the gap before `else` stays on the
// keyword's left, as an `if` statement's does.
let mut before_else = Vec::new();
if self.cur().is_kw("else") {
before_else = self.take_dangling();
}
let (after_else, els) = if self.eat_kw("else") {
(self.take_gap(), Some(Box::new(self.parse_prod_item()?)))
} else {
(Vec::new(), None)
};
Ok(ProdItem::If { after_kw, cond, then, before_else, after_else, els })
}
/// `case ( expr ) arm { arm } endcase`, whose arms take production items.
fn parse_rs_case(&mut self) -> PResult<ProdItem> {
self.expect_kw("case")?;
let after_kw = self.take_before_open("(");
self.expect_sym("(")?;
let expr = self.parse_expr()?;
self.expect_sym(")")?;
let mut items = Vec::new();
while !self.at_body_end("endcase") {
items.push(self.parse_rs_case_item()?);
}
let dangling = self.take_dangling();
self.expect_closer("endcase")?;
Ok(ProdItem::Case { after_kw, expr, items, dangling })
}
/// One arm: `expr {, expr} : item ;` or `default [:] item ;`.
fn parse_rs_case_item(&mut self) -> PResult<ProdCaseItem> {
let start = self.here();
let mut meta = self.take_meta();
let mut labels = Vec::new();
let is_default = self.eat_kw("default");
if !is_default {
let first = self.parse_expr_item()?;
labels = self.parse_expr_list(first, ":")?;
}
let before_colon = self.gap_before(":");
// A `default` arm may write no `:` at all (§18.17.4).
let has_colon = self.cur().is_sym(":");
if has_colon {
self.bump();
} else if !is_default {
return self.error("expected `:` in a randsequence case arm");
}
let after_colon = self.take_gap();
let item = self.parse_prod_item()?;
let span = self.span_from(start);
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
if meta.trailing.is_none() {
meta.trailing = self.take_trailing();
}
Ok(ProdCaseItem {
meta,
labels,
is_default,
before_colon,
after_colon,
item,
before_semi,
span,
})
}
/// `rand join [ ( expr ) ] item item { item }` (§18.17.6): the items are
/// interleaved rather than run in order, and there are at least two.
fn parse_rand_join(&mut self) -> PResult<ProdItem> {
self.expect_kw("rand")?;
let after_rand = self.take_gap();
self.expect_kw("join")?;
let weight = if self.cur().is_sym("(") {
self.bump();
let e = self.parse_expr()?;
self.expect_sym(")")?;
Some(e)
} else {
None
};
let mut items = vec![self.parse_prod_item()?];
while self.at_prod_item() {
items.push(self.parse_prod_item()?);
}
Ok(ProdItem::RandJoin { after_rand, weight, items })
}
/// A production reference: `name` or `name(a, b)`.
fn parse_prod_ref(&mut self) -> PResult<ProdRef> {
let Name { text: name, span: name_span } = self.expect_name()?;
let before_args = self.take_before_open("(");
let has_parens = self.cur().is_sym("(");
let mut args = Vec::new();
if has_parens {
self.bump();
if !self.cur().is_sym(")") {
let first = self.parse_expr_item()?;
args = self.parse_expr_list(first, ")")?;
}
self.expect_sym(")")?;
}
Ok(ProdRef { name, name_span, has_parens, before_args, args })
}
/// An `rs_code_block`: `{ … }` around ordinary statements.
fn parse_rs_code_block(&mut self) -> PResult<CodeBlock> {
self.expect_sym("{")?;
let mut stmts = Vec::new();
while !self.cur().is_sym("}") && !self.at_eof() {
stmts.push(self.stmt_or_recover()?);
}
let dangling = self.take_dangling();
self.expect_sym("}")?;
Ok(CodeBlock { stmts, dangling })
}
}
+121 -8
View File
@@ -10,8 +10,10 @@
//! The recovery is deliberately hard to reach. It fires only after a real
//! parse failure, and only when that failure is the grammar refusing a
//! `else / `elsif / `endif that closes a region which is genuinely open
//! and which the failed item did not open, with a bracket the arm left
//! open. Everything else — a plain syntax error that merely sits near a
//! and which the failed item did not open — with a bracket the arm left
//! open, or with the arm behind the directive re-writing the very header
//! the failed item began with (`docs/features/parser-skips/README.md`).
//! Everything else — a plain syntax error that merely sits near a
//! directive, a garbage token run with directives in it, an unterminated
//! region, a stray closer with nothing open — still refuses.
//! See `docs/features/directive-split/README.md`.
@@ -106,7 +108,92 @@ fn construct_end(head: &[Token]) -> ConstructEnd {
ConstructEnd::Unknown
}
/// The unit whose body a loop is reading, as [`Parser::at_rival_header`]
/// needs it.
pub(super) struct UnitHead<'h> {
/// The unit's keyword, as written: `module`, `macromodule`, `interface`
/// or `program`.
pub(super) kw: &'h str,
/// The unit's name.
pub(super) name: &'h str,
/// Item-scope conditional regions open at the unit's own first token.
pub(super) conds: u32,
/// The lowest item-scope nesting the body has reached since it started.
/// Below `conds` means the region that stood open at the header was
/// closed inside the body, so a directive at the cursor continues some
/// later region rather than that one.
pub(super) floor: u32,
}
/// The keyword that closes a unit, given its opening keyword — or `None` for
/// a keyword that opens no unit. `interface class` is a class and closes with
/// `endclass`; the caller rules it out by requiring a name after the keyword.
fn unit_end_kw(t: &Token) -> Option<&'static str> {
if t.kind != TokenKind::Keyword {
return None;
}
match t.text.as_str() {
"module" | "macromodule" => Some("endmodule"),
"interface" => Some("endinterface"),
"program" => Some("endprogram"),
_ => None,
}
}
/// True when `t` opens a unit that `close` ends. Its own test, so a unit
/// *nested* in a captured body cannot end the extent scan on its closer.
fn opens_unit(t: &Token, close: &str) -> bool {
unit_end_kw(t) == Some(close)
}
impl<'a> Parser<'a> {
/// True when the cursor stands on the `` `else `` / `` `elsif `` of a
/// region opened *before* `head` was written, and the arm behind it
/// re-writes `head`'s own keyword and name.
///
/// That is one header written twice across the arms of a region — the
/// `jtag_if.sv` shape — not a unit nested inside another one. Both
/// spellings are bracket-balanced, so nothing fails until the outer unit
/// reaches EOF looking for its closer; the body loop asks this before
/// each item instead, and fails where the evidence is.
/// See `docs/features/parser-skips/README.md`.
pub(super) fn at_rival_header(&self, head: &UnitHead) -> bool {
if !continues_conditional(self.cur()) {
return false;
}
// A region must have been open at the header, must still be the live
// one (nothing opened since is still open) and must never have been
// closed inside the body.
if head.conds == 0 || self.open_conds != head.conds || head.floor != head.conds {
return false;
}
self.nth(1).is_kw(head.kw)
&& self.nth(2).kind == TokenKind::Ident
&& self.nth(2).text == head.name
}
/// The closing keyword of the unit a rival header opened, or `None` when
/// the item that failed at `mark` is not one.
///
/// The mirror of [`Parser::at_rival_header`], read from the tokens rather
/// than from a flag on the error: [`ParseError`] is public and carries
/// only a message and a position, and every other condition of this
/// trigger is already read from the mark and the cursor — so all of the
/// evidence stays in one place and no error path can set the flag by
/// accident.
fn rival_end_kw(&self, mark: &ItemMark) -> Option<&'static str> {
let head = self.tokens.get(mark.pos)?;
let end = unit_end_kw(head)?;
let name = self.tokens.get(mark.pos + 1)?;
if name.kind != TokenKind::Ident {
return None;
}
let rival = self.nth(1).is_kw(&head.text)
&& self.nth(2).kind == TokenKind::Ident
&& self.nth(2).text == name.text;
rival.then_some(end)
}
/// Count the conditional-compilation directive standing at the cursor,
/// which the caller is about to consume as an `ItemKind::Directive`.
///
@@ -150,7 +237,9 @@ impl<'a> Parser<'a> {
err: ParseError,
) -> PResult<ItemKind> {
if self.at_split_conditional(mark) {
if let Some((end_pos, conds_after)) = self.scan_split_extent(mark) {
if let Some((end_pos, conds_after)) =
self.scan_split_extent(mark, self.rival_end_kw(mark))
{
// The block swallowed the region's own `else / `endif, which
// *are* item-scope nesting even though they now sit inside
// opaque bytes. The extent scan already worked out what they
@@ -202,9 +291,12 @@ impl<'a> Parser<'a> {
/// and ends nothing: it is broken input, and the parse error stands;
/// 3. the item's own conditional nesting is back to zero there, so the
/// live region is one opened *before* the item rather than by it;
/// 4. the arm left a bracket open, i.e. it is structurally a fragment.
/// A missing `;` leaves nothing open and is indistinguishable from a
/// typo, so it is refused.
/// 4. the arm is structurally a fragment. Two spellings qualify: it left
/// a bracket open (`(`, `[` or `{` unmatched), or it is a **unit
/// header the next arm writes again** ([`Parser::rival_end_kw`]) — a
/// header written twice is as much a fragment as an unclosed bracket,
/// and it is the only bracket-balanced shape allowed in. A missing `;`
/// leaves neither, is indistinguishable from a typo, and is refused.
fn at_split_conditional(&self, mark: &ItemMark) -> bool {
let at = self.cur();
if !continues_conditional(at) && !closes_conditional(at) {
@@ -228,7 +320,7 @@ impl<'a> Parser<'a> {
brackets -= 1;
}
}
cond == 0 && brackets > 0
cond == 0 && (brackets > 0 || self.rival_end_kw(mark).is_some())
}
/// One past the last token of the construct the split region belongs to,
@@ -248,13 +340,25 @@ impl<'a> Parser<'a> {
/// no region live is a stray closer, not a split, and gives up — the same
/// refusal the trigger makes, repeated here because the scan walks past
/// the point the trigger looked at.
fn scan_split_extent(&self, mark: &ItemMark) -> Option<(usize, u32)> {
///
/// `unit_end` is `Some(closing keyword)` for a rival unit header, whose
/// `;` closes only its *header*: the block is the whole unit, so the scan
/// runs to the matching `endmodule` / `endinterface` / `endprogram`
/// instead — counting units of the same kind on the way, so one nested in
/// the body cannot end it early. (An `interface class` nested in a
/// captured `interface` closes with `endclass`, leaves the count above
/// zero and makes the scan give up: the parse error stands, which is the
/// safe side.)
fn scan_split_extent(&self, mark: &ItemMark, unit_end: Option<&str>) -> Option<(usize, u32)> {
// Regions this scan opened, and regions that were already open when
// it started. A directive at scan level zero belongs to the latter.
let mut cond = 0i32;
let mut live = mark.conds;
let mut closed_outer = false;
let mut brackets = 0i32;
// Units of the head's kind open at `i`, counted only in `unit_end`
// mode. The head at `mark.pos` is itself the first one.
let mut units = 0i32;
let mut i = mark.pos;
while let Some(t) = self.tokens.get(i) {
if t.kind == TokenKind::Eof {
@@ -283,6 +387,15 @@ impl<'a> Parser<'a> {
if brackets < 0 {
return None;
}
} else if let Some(close) = unit_end {
if opens_unit(t, close) {
units += 1;
} else if t.is_kw(close) {
units -= 1;
if units == 0 && cond == 0 && closed_outer {
return Some((self.past_end_label(i + 1), live));
}
}
} else if t.is_sym(";") && brackets == 0 && cond == 0 && closed_outer {
return Some((i + 1, live));
}
+38 -5
View File
@@ -144,11 +144,8 @@ impl<'a> Parser<'a> {
let stmt = if self.eat_stmt_semi() { None } else { Some(Box::new(self.parse_stmt()?)) };
return Ok(StmtKind::Timing { control: TimingControl::Event(sens), stmt });
}
if t.is_sym("->") {
self.bump();
let e = self.parse_unary()?;
self.expect_stmt_semi()?;
return Ok(StmtKind::EventTrigger(e));
if t.is_sym("->") || t.is_sym("->>") {
return self.parse_event_trigger();
}
if t.kind == TokenKind::Keyword {
return self.parse_keyword_stmt();
@@ -157,6 +154,42 @@ impl<'a> Parser<'a> {
self.parse_assign_or_expr_stmt()
}
/// `-> ev;` and `->> [delay_or_event_control] ev;` (IEEE 1800 §15.5.2).
///
/// The arrow is kept as written: `->` and `->>` are different statements
/// (blocking and non-blocking), so rewriting one as the other would
/// change the design. Only `->>` may carry the timing control, but it is
/// read for both spellings — the parser reproduces what stands there and
/// leaves legality to the tools that check it.
fn parse_event_trigger(&mut self) -> PResult<StmtKind> {
let arrow = self.bump().text;
let after_arrow = self.take_gap();
let timing = self.parse_opt_timing_control()?;
let before_event = if timing.is_some() { self.take_gap() } else { Vec::new() };
let expr = self.parse_unary()?;
self.expect_stmt_semi()?;
Ok(StmtKind::EventTrigger(Box::new(EventTrigger {
arrow,
after_arrow,
timing,
before_event,
expr,
})))
}
/// The `#delay` or `@(event)` written at the cursor, if one is.
fn parse_opt_timing_control(&mut self) -> PResult<Option<TimingControl>> {
if self.eat_sym("#") {
let after_hash = self.take_gap();
let expr = self.parse_delay_value()?;
return Ok(Some(TimingControl::Delay { after_hash, expr }));
}
if self.eat_sym("@") {
return Ok(Some(TimingControl::Event(self.parse_sens_list()?)));
}
Ok(None)
}
pub(super) fn parse_if_stmt(&mut self, qualifier: Option<String>) -> PResult<StmtKind> {
self.expect_kw("if")?;
let after_kw = self.take_before_open("(");
@@ -290,3 +290,58 @@ fn a_struct_member_may_be_declared_rand() {
assert!(s.members[2].qualifiers.is_empty());
assert_eq!(s.members[0].declarators[0].name, "cpol");
}
// ------------------------------------------------------------------
// Net delays on either side of the data type (TODO §38.2,
// `docs/features/parser-skips/README.md`)
// ------------------------------------------------------------------
/// The net delay of a single-declaration module, with the side of the data
/// type it was written on.
fn net_delay_of(src: &str) -> (String, bool) {
let f = parse_ok(src);
let d = match &module_of(&f).items[0].kind {
ItemKind::DataDecl(d) => d,
_ => panic!("expected a declaration"),
};
let delay = d.delay.as_ref().expect("a net delay");
(src[delay.expr.span.as_range()].to_string(), delay.after_type)
}
#[test]
fn a_net_delay_is_read_on_either_side_of_the_data_type() {
// Before the type is what the corpus writes; after it is where IEEE
// 1800 §6.7 puts `delay3`, and where
// `pulp_riscv_dbg/tb/unused/SimDTM.sv:38` writes it.
assert_eq!(net_delay_of("module m;\n wire #5 w;\nendmodule\n"), ("5".into(), false));
assert_eq!(
net_delay_of("module m;\n wire [31:0] #0.1 x = y;\nendmodule\n"),
("0.1".into(), true)
);
// After a plain `logic`-typed net, and after a signed keyword run.
assert_eq!(net_delay_of("module m;\n wire logic #3 a;\nendmodule\n"), ("3".into(), true));
assert_eq!(
net_delay_of("module m;\n wire signed [7:0] #(1:2:3) b;\nendmodule\n"),
("(1:2:3)".into(), true)
);
// The before position is unmoved by any of it.
assert_eq!(
net_delay_of("module m;\n wire #(1:2:3) signed [7:0] c;\nendmodule\n"),
("(1:2:3)".into(), false)
);
}
#[test]
fn a_net_delay_written_on_both_sides_is_an_error() {
let msg = parse_err("module m;\n wire #5 [31:0] #6 x;\nendmodule\n");
assert!(msg.contains("before or after the type, not both"), "{msg}");
}
#[test]
fn only_a_net_declaration_reads_a_delay() {
// A variable has no `delay3`, so the `#` is not swallowed here — it is
// an ordinary syntax error, exactly as it was before either position
// was accepted.
assert!(parse_err("module m;\n logic #5 x;\nendmodule\n").contains("expected"));
assert!(parse_err("module m;\n logic [7:0] #5 x;\nendmodule\n").contains("expected"));
}
+28 -6
View File
@@ -226,13 +226,17 @@ fn only_a_brace_after_the_first_element_makes_an_assignment_pattern_a_replicatio
fn a_streaming_concatenation_keeps_its_direction_and_optional_slice_size() {
// corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_sha2_pkg.sv:123.
with_assign_rhs("module m;\n assign y = {<<8{v}};\nendmodule\n", |e| {
let ExprKind::Stream { dir, slice, inner } = &e.kind else { panic!("expected a stream") };
let ExprKind::Stream { dir, slice, inner, .. } = &e.kind else {
panic!("expected a stream")
};
assert_eq!(dir, "<<");
assert!(matches!(slice.as_deref().map(|s| &s.kind), Some(ExprKind::Number(_))));
assert_eq!(inner.len(), 1);
});
with_assign_rhs("module m;\n assign y = {>>{a, b}};\nendmodule\n", |e| {
let ExprKind::Stream { dir, slice, inner } = &e.kind else { panic!("expected a stream") };
let ExprKind::Stream { dir, slice, inner, .. } = &e.kind else {
panic!("expected a stream")
};
assert_eq!(dir, ">>");
assert!(slice.is_none(), "no slice size was written");
assert_eq!(inner.len(), 2);
@@ -287,10 +291,28 @@ fn an_argument_carries_its_own_comments_and_the_call_carries_none() {
}
#[test]
fn a_with_that_opens_neither_a_paren_nor_a_brace_is_not_a_postfix_segment() {
// The stream expression's `with [range]` is still unsupported, and
// still fails where it always did rather than being mis-read.
assert!(parse_err("module m;\n initial x = {<<{a with [0:1]}};\nendmodule\n").contains("with"));
fn a_with_that_opens_a_bracket_is_a_stream_range() {
// The third postfix spelling of `with` (TODO §54.1): `[` after the
// keyword is a stream expression's array range, not an array method's
// iterator argument and not a `randomize` constraint block.
let f = parse_ok("module m;\n initial x = {<<{a with [0:1]}};\nendmodule\n");
let ItemKind::Initial(stmt) = &module_of(&f).items[0].kind else {
panic!("expected an initial block")
};
let StmtKind::Assign { rhs, .. } = &stmt.kind else { panic!("expected an assignment") };
let ExprKind::Stream { inner, .. } = &rhs.kind else { panic!("expected a stream") };
let ExprKind::StreamWith { range, .. } = &inner[0].expr.kind else {
panic!("expected a stream range, got {:?}", inner[0].expr.kind)
};
assert_eq!(range.op.as_deref(), Some(":"));
assert!(range.lsb.is_some());
}
#[test]
fn a_with_that_opens_none_of_the_three_delimiters_is_not_a_postfix_segment() {
// A bare `with name` is no postfix segment at all, and still fails where
// it always did rather than being mis-read.
assert!(parse_err("module m;\n initial x = a with b;\nendmodule\n").contains("with"));
}
#[test]
@@ -190,7 +190,7 @@ fn a_gate_takes_a_multi_value_delay_list() {
// The one-value parenthesized spelling keeps its `Paren` node, which
// is what makes `#(5)` print back as `#(5)` and not as `#5`.
let ItemKind::GateInstantiation(g) = &m.items[2].kind else { panic!("expected a gate") };
assert!(matches!(g.delay[0].kind, ExprKind::Paren { .. }));
assert!(matches!(g.delay[0].expr.kind, ExprKind::Paren { .. }));
}
#[test]
@@ -218,3 +218,41 @@ fn a_bind_instance_may_be_a_hierarchical_path() {
let ItemKind::Bind(b) = &f.items[0].kind else { panic!("expected a bind") };
assert_eq!(b.instances.iter().map(|i| i.text.as_str()).collect::<Vec<_>>(), ["a.b", "plain"]);
}
#[test]
fn an_inline_aggregate_is_a_parameter_override_argument() {
// TODO §45.3: a `parameter type` defaulting to an anonymous aggregate is
// overridden with one, and `parse_type_ref` has read that body all along —
// only `parse_expr_or_type`'s door was shut (`struct`/`union`/`enum` are
// not `TYPE_KEYWORDS`), so the value read as an expression and failed.
for src in [
"module m;\n sub #(.T(struct packed { logic a; })) u ();\nendmodule\n",
"module m;\n sub #(.T(union packed { logic [7:0] a; })) u ();\nendmodule\n",
"module m;\n sub #(.T(enum logic [1:0] {A, B})) u ();\nendmodule\n",
"module m;\n sub #(.T(struct packed { /* why */ logic a; })) u ();\nendmodule\n",
] {
let f = parse_ok(src);
let ItemKind::Instantiation(i) = &module_of(&f).items[0].kind else {
panic!("expected an instantiation")
};
let params = i.params.as_ref().expect("an override list");
let value = oks(params)[0].expr.as_ref().expect("a value");
assert!(matches!(value.kind, ExprKind::Type(_)), "{src:?} read as {:?}", value.kind);
// Strict and tolerant must agree: the tolerant parser reports nothing
// where the strict one succeeds.
let (_, diags) = crate::parse_source_tolerant(src);
assert!(diags.is_empty(), "{src:?} left {diags:?}");
}
}
#[test]
fn an_ordered_parameter_override_takes_an_inline_aggregate_too() {
// The bare-expression arm of `parse_connection` shares `parse_expr_or_type`
// with the named one, so both doors opened at once.
let f = parse_ok("module m;\n sub #(struct packed { logic a; }) u ();\nendmodule\n");
let ItemKind::Instantiation(i) = &module_of(&f).items[0].kind else {
panic!("expected an instantiation")
};
let params = i.params.as_ref().expect("an override list");
assert!(matches!(oks(params)[0].expr.as_ref().expect("a value").kind, ExprKind::Type(_)));
}
+78 -3
View File
@@ -338,18 +338,93 @@ fn a_clocking_block_parses_its_items() {
assert_eq!(c.items.len(), 3);
assert!(matches!(
&c.items[0].kind,
ClockingItemKind::Default { input: Some(i), output: Some(o) } if i == "#2" && o == "#4"
ClockingItemKind::Default {
input: Some(ClockingDefault {
skew: ClockingSkew::Delay(ClockingDelay::Word { word: i, .. }), ..
}),
output: Some(ClockingDefault {
skew: ClockingSkew::Delay(ClockingDelay::Word { word: o, .. }), ..
}),
} if i == "2" && o == "4"
));
assert!(matches!(
&c.items[1].kind,
ClockingItemKind::Signals { dir, skew: None, signals } if dir == "input" && signals.len() == 2
ClockingItemKind::Signals { dir, skew: None, signals, .. }
if dir == "input" && signals.len() == 2
));
assert!(matches!(
&c.items[2].kind,
ClockingItemKind::Signals { dir, skew: Some(s), .. } if dir == "output" && s == "negedge"
ClockingItemKind::Signals {
dir,
skew: Some(ClockingSkew::Edge { word: s, delay: None, .. }),
..
} if dir == "output" && s == "negedge"
));
}
#[test]
fn a_clocking_skew_reads_a_delay_behind_its_edge() {
// IEEE 1800-2017 14.3: `clocking_skew ::= edge_identifier [ delay_control ]
// | delay_control`. The edge and the delay are one skew, not two.
let f = parse_ok(
"module m;\n clocking cb @(posedge clk);\n default input negedge #(1:2:3) output posedge #5;\n input posedge #1step a;\n input edge b;\n endclocking\nendmodule\n",
);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Clocking(c) = &m.items[0].kind else { panic!("expected a clocking block") };
assert!(matches!(
&c.items[0].kind,
ClockingItemKind::Default {
input: Some(ClockingDefault {
skew: ClockingSkew::Edge {
word: i,
delay: Some(ClockingDelay::Paren { .. }),
..
},
..
}),
output: Some(ClockingDefault {
skew: ClockingSkew::Edge {
word: o,
delay: Some(ClockingDelay::Word { word: d, .. }),
..
},
..
}),
} if i == "negedge" && o == "posedge" && d == "5"
));
assert!(matches!(
&c.items[1].kind,
ClockingItemKind::Signals {
skew: Some(ClockingSkew::Edge { delay: Some(ClockingDelay::Word { word, .. }), .. }),
..
} if word == "1step"
));
assert!(matches!(
&c.items[2].kind,
ClockingItemKind::Signals { skew: Some(ClockingSkew::Edge { word, delay: None, .. }), .. }
if word == "edge"
));
}
#[test]
fn an_edge_skews_delay_is_read_the_same_way_in_tolerant_mode() {
// Strict/tolerant parity: the shape is grammar, not recovery, so the
// tolerant parser reads it with no diagnostic of its own.
let src = "module m;\n clocking cb @(posedge clk);\n default input negedge #(1:2:3) output posedge #5;\n input edge /*c*/ #2 a;\n endclocking\nendmodule\n";
let (f, diags) = parse_tolerant(tokenize(src).expect("lex error"), src);
assert!(diags.is_empty(), "tolerant mode recovered from a legal skew: {diags:?}");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Clocking(c) = &m.items[0].kind else { panic!("expected a clocking block") };
let ClockingItemKind::Signals {
skew: Some(ClockingSkew::Edge { after_edge, delay, .. }), ..
} = &c.items[1].kind
else {
panic!("expected an edge skew with a delay")
};
assert_eq!(texts(after_edge), ["/*c*/"], "the gap in front of the `#` is the edge's own");
assert!(matches!(delay, Some(ClockingDelay::Word { word, .. }) if word == "2"));
}
#[test]
fn a_default_clocking_may_be_anonymous_or_body_less() {
// corpus/ibex/dv/formal/check/top.sv:143, and IEEE 1800-2017 14.12.
@@ -628,3 +628,158 @@ fn an_opening_split_that_is_the_last_item_does_not_eat_the_closing_keyword() {
"a directive starting a statement list is pass-through, not a split"
);
}
// ------------------------------------------------------------------
// Rival unit headers written across the arms of one region
// (`docs/features/parser-skips/README.md`)
// ------------------------------------------------------------------
/// The `jtag_if.sv` shape, in the four spellings that differ only in the
/// header: `interface`/`module`, with and without `#( ... )`, with `()` and
/// with a real port list. Every one of them is one verbatim item running
/// from the first header to the unit's own closing keyword.
#[test]
fn rival_unit_headers_across_one_region_become_one_verbatim_item() {
for (why, src, ends) in [
(
"interface, `#( ... ) ()` — hw/dv/sv/jtag_agent/jtag_if.sv:6",
"`ifdef GATE_LEVEL\n interface jtag_if #(parameter int unsigned P = 41_664) \
();\n`else\n interface jtag_if #(parameter int unsigned P = 20_000) \
();\n`endif\n wire tck;\nendinterface\nparameter int AFTER = 1;\n",
"endinterface",
),
(
"interface, no parameter list",
"`ifdef A\ninterface i ();\n`else\ninterface i ();\n`endif\n wire \
tck;\nendinterface\nparameter int AFTER = 1;\n",
"endinterface",
),
(
"module, a real port list",
"`ifdef A\nmodule m (input a, output b);\n`else\nmodule m (input a, output \
b);\n`endif\n wire x;\nendmodule\nparameter int AFTER = 1;\n",
"endmodule",
),
(
"module, a closing label",
"`ifdef A\nmodule m #(parameter int W = 1) ();\n`else\nmodule m #(parameter int W = \
2) ();\n`endif\n wire x;\nendmodule : m\nparameter int AFTER = 1;\n",
"endmodule : m",
),
] {
let f = parse_ok(src);
let kinds = split_items(&f);
assert_eq!(kinds.len(), 3, "{why}: {kinds:?}");
assert!(kinds[0].starts_with("directive:`ifdef"), "{why}: {kinds:?}");
assert_eq!(kinds[2], "param", "{why}: the item after the unit was not swallowed");
let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("{why}: expected verbatim") };
assert_eq!(raw.text, src[raw.span.as_range()], "{why}");
assert!(raw.text.ends_with(ends), "{why}: {:?}", raw.text);
assert!(raw.text.contains("`else") && raw.text.contains("`endif"), "{why}: {:?}", raw.text);
// The whole unit is inside the block, its body included.
assert!(raw.text.contains("wire"), "{why}: {:?}", raw.text);
assert_eq!(open_conds_after(src), 0, "{why}: the region's own `endif was accounted for");
}
}
#[test]
fn rival_headers_produce_the_same_tree_in_both_modes() {
let src = "`ifdef GATE_LEVEL\n interface jtag_if #(parameter int unsigned P = 41_664) \
();\n`else\n interface jtag_if #(parameter int unsigned P = 20_000) \
();\n`endif\n wire tck;\nendinterface\n";
let strict = parse_ok(src);
let toks = tokenize(src).expect("lex error");
let (tolerant, diags) = parse_tolerant(toks, src);
assert!(diags.is_empty(), "{diags:?}");
assert_eq!(split_items(&strict), split_items(&tolerant));
}
#[test]
fn comments_written_around_a_rival_header_are_kept() {
// The real file writes a comment inside each arm and one before the
// region; none of them may be dropped.
let src = "// head\n`ifdef GATE_LEVEL // which\n // 24MHz for GLS\n interface jtag_if \
();\n`else\n // 50MHz for DV\n interface jtag_if ();\n`endif\n // pins\n wire \
tck;\nendinterface // done\n";
let f = parse_ok(src);
assert_eq!(texts(&f.items[0].meta.leading), ["// head"]);
assert_eq!(f.items[0].meta.trailing.as_ref().expect("the `ifdef's comment").text, "// which");
// The capture starts at the item's *first token*, so the comment written
// in front of the header is the item's own leading comment — the same
// place every other split puts it — and the rest are inside the block.
assert_eq!(texts(&f.items[1].meta.leading), ["// 24MHz for GLS"]);
let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") };
for c in ["// 50MHz for DV", "// pins"] {
assert!(raw.text.contains(c), "{c} was dropped from {:?}", raw.text);
}
assert!(!raw.text.contains("// done"), "the trailing comment was swallowed");
assert_eq!(f.items[1].meta.trailing.as_ref().expect("the comment survived").text, "// done");
}
#[test]
fn a_unit_nested_in_a_captured_body_does_not_end_the_scan_early() {
// The extent scan counts units of the head's kind, so the *inner*
// `endmodule` cannot be mistaken for the rival unit's own.
let src = "`ifdef A\nmodule m ();\n`else\nmodule m ();\n`endif\n module inner ();\n \
endmodule\n wire x;\nendmodule\nparameter int AFTER = 1;\n";
let f = parse_ok(src);
let kinds = split_items(&f);
assert_eq!(kinds.len(), 3, "{kinds:?}");
let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") };
assert!(raw.text.contains("module inner"), "{:?}", raw.text);
assert!(raw.text.ends_with("endmodule"), "{:?}", raw.text);
assert_eq!(kinds[2], "param", "{kinds:?}");
}
// -- the three negatives ----------------------------------------------
#[test]
fn a_second_unit_in_an_arm_of_a_region_opened_inside_the_body_is_still_an_error() {
// Two nested units, which is illegal: the region the `else belongs to
// was opened *by the body*, not before the header, so the arm is not a
// rival spelling of anything.
let msg = parse_err(
"`ifdef OUTER\nmodule m;\n`ifdef A\n wire a;\n`else\nmodule m;\n`endif\n wire \
b;\nendmodule\n",
);
assert!(msg.contains("endmodule"), "{msg}");
// The same shape with no region open at all around the outer unit.
let msg = parse_err(
"module m;\n`ifdef A\n wire a;\n`else\nmodule m;\n wire \
b;\n`endif\nendmodule\n",
);
assert!(msg.contains("endmodule"), "{msg}");
}
#[test]
fn a_different_name_after_the_else_is_not_a_rival_header() {
let msg = parse_err(
"`ifdef A\ninterface i ();\n`else\ninterface j ();\n`endif\n wire \
x;\nendinterface\n",
);
assert!(msg.contains("endinterface"), "{msg}");
// Nor is a different keyword for the same name.
let msg = parse_err(
"`ifdef A\ninterface i ();\n`else\nmodule i ();\n`endif\n wire x;\nendinterface\n",
);
assert!(msg.contains("endinterface"), "{msg}");
}
#[test]
fn a_region_closed_before_the_header_leaves_the_else_stray() {
// The region opened at the top of the file is closed before the
// interface begins, so the `else below closes nothing: broken input,
// and the parse error stands.
let msg = parse_err(
"`ifdef A\n wire a;\n`endif\ninterface i ();\n`else\n interface i ();\n`endif\n wire \
x;\nendinterface\n",
);
assert!(msg.contains("endinterface"), "{msg}");
// And a region closed *inside* the body before the `else: the header's
// region is gone, so the live one is not the one it was written under.
let msg = parse_err(
"`ifdef OUTER\ninterface i ();\n`endif\n`ifdef B\n wire a;\n`else\n interface i \
();\n`endif\nendinterface\n",
);
assert!(msg.contains("endinterface"), "{msg}");
}
+15 -1
View File
@@ -134,13 +134,27 @@ impl<'a> Parser<'a> {
/// writes no parens at all, which is what `has_parens` records.
pub(super) fn parse_let(&mut self) -> PResult<LetDecl> {
self.expect_kw("let")?;
let after_kw = self.take_gap();
let Name { text: name, span: name_span } = self.expect_name()?;
let has_parens = self.cur().is_sym("(");
let ports = self.parse_tf_ports(false)?.args;
let mut eq_comments = Box::new(BinaryComments::default());
eq_comments.before = self.gap_before("=");
self.expect_sym("=")?;
eq_comments.after = self.take_gap();
let value = self.parse_expr()?;
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
Ok(LetDecl { name, name_span, has_parens, ports, value })
Ok(LetDecl {
after_kw,
name,
name_span,
has_parens,
ports,
eq_comments,
value,
before_semi,
})
}
/// The header a subroutine declaration and a `modport` method prototype
+1
View File
@@ -257,6 +257,7 @@ keywords![
"pure",
"extern",
"rand",
"randsequence",
"randc",
"local",
"protected",
+196 -4
View File
@@ -614,7 +614,7 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
}
ItemKind::GateInstantiation(g) => {
for d in &g.delay {
check_expr(src, d, here);
check_expr(src, &d.expr, here);
}
for i in &g.instances {
assert_inside(src, "gate instance", i.span, here);
@@ -980,9 +980,36 @@ fn check_stmt(src: &str, stmt: &Stmt, parent: TextRange) {
check_stmt(src, s, here);
}
}
StmtKind::ExprStmt(e) | StmtKind::EventTrigger(e) => check_expr(src, e, here),
StmtKind::ExprStmt(e) => check_expr(src, e, here),
StmtKind::EventTrigger(t) => check_expr(src, &t.expr, here),
StmtKind::VarDecl(d) => check_declarators(src, &d.declarators, here),
StmtKind::Typedef(t) => check_typedef(src, t, here),
StmtKind::RandSequence(r) => {
for p in &r.productions {
assert_inside(src, "production", p.span, here);
check_name(src, "production name", &p.name, p.name_span, p.span);
check_list(src, "production port", &p.args, p.span, |a| {
assert_inside(src, "production port", a.span, p.span);
check_name(src, "production port name", &a.name, a.name_span, a.span);
});
for alt in &p.alternatives {
for item in &alt.items {
check_prod_item(src, item, p.span);
}
if let Some(w) = &alt.weight {
check_expr(src, &w.expr, p.span);
}
}
}
}
StmtKind::Let(l) => {
check_name(src, "let name", &l.name, l.name_span, here);
check_list(src, "let port", &l.ports, here, |a| {
assert_inside(src, "let port", a.span, here);
check_name(src, "let port name", &a.name, a.name_span, a.span);
});
check_expr(src, &l.value, here);
}
StmtKind::ParamDecl(p) => check_declarators(src, &p.declarators, here),
StmtKind::PortDecl(p) => check_declarators(src, &p.declarators, here),
StmtKind::Return { expr, .. } => check_opt_expr(src, expr.as_ref(), here),
@@ -1011,10 +1038,12 @@ fn check_stmt(src: &str, stmt: &Stmt, parent: TextRange) {
check_stmt(src, inner, here);
}
StmtKind::Import(paths) => check_import_paths(src, paths, here),
StmtKind::Disable { name, name_span } => {
check_name(src, "disable target", name, *name_span, here)
}
StmtKind::Break
| StmtKind::Continue
| StmtKind::WaitFork
| StmtKind::Disable(_)
| StmtKind::Null
| StmtKind::Error(_) => {}
StmtKind::Assertion(a) => check_assertion(src, a, here),
@@ -1124,6 +1153,50 @@ fn check_match_items(src: &str, items: &[MatchItem], parent: TextRange) {
}
}
/// Every span a `randsequence` item and the items nested in it carry.
fn check_prod_item(src: &str, item: &ProdItem, parent: TextRange) {
match item {
ProdItem::Ref(r) => {
check_name(src, "production reference", &r.name, r.name_span, parent);
for a in &r.args {
check_expr(src, &a.expr, parent);
}
}
ProdItem::Block(b) => {
for s in &b.stmts {
check_stmt(src, s, parent);
}
}
ProdItem::If { cond, then, els, .. } => {
check_expr(src, cond, parent);
check_prod_item(src, then, parent);
if let Some(e) = els {
check_prod_item(src, e, parent);
}
}
ProdItem::Repeat { count, body, .. } => {
check_expr(src, count, parent);
check_prod_item(src, body, parent);
}
ProdItem::Case { expr, items, .. } => {
check_expr(src, expr, parent);
for arm in items {
assert_inside(src, "randsequence case arm", arm.span, parent);
for l in &arm.labels {
check_expr(src, &l.expr, arm.span);
}
check_prod_item(src, &arm.item, arm.span);
}
}
ProdItem::RandJoin { weight, items, .. } => {
check_opt_expr(src, weight.as_ref(), parent);
for i in items {
check_prod_item(src, i, parent);
}
}
}
}
fn check_opt_expr(src: &str, e: Option<&Expr>, parent: TextRange) {
if let Some(e) = e {
check_expr(src, e, parent);
@@ -1146,6 +1219,11 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) {
check_expr(src, base, here);
check_expr(src, arg, here);
}
ExprKind::StreamWith { base, range } => {
check_expr(src, base, here);
check_expr(src, &range.msb, here);
check_opt_expr(src, range.lsb.as_ref(), here);
}
ExprKind::WithConstraint { base, block, .. } => {
check_expr(src, base, here);
match &**block {
@@ -1227,7 +1305,7 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) {
check_expr(src, lo, here);
check_expr(src, hi, here);
}
ExprKind::MinTypMax { min, typ, max } => {
ExprKind::MinTypMax { min, typ, max, .. } => {
check_expr(src, min, here);
check_expr(src, typ, here);
check_expr(src, max, here);
@@ -1669,3 +1747,117 @@ fn check_constraint_set(src: &str, set: &ConstraintSet, parent: TextRange) {
}
}
}
// ----------------------------------------------------------------------
// Type-name spans (TODO.md §47)
// ----------------------------------------------------------------------
/// Every `DataType` a source file writes, in item order, with the declarator
/// it belongs to left behind — enough to reach each construction site by hand.
fn module_types(file: &SourceFile) -> Vec<&DataType> {
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let mut out = Vec::new();
if let PortList::Ansi(ports) = &m.ports {
out.extend(ports.iter().filter_map(ListElem::ok).map(|p| &p.ty));
}
for item in &m.items {
match &item.kind {
ItemKind::DataDecl(d) => out.push(&d.ty),
ItemKind::Typedef(t) => {
if let TypedefKind::Alias(ty) = &t.kind {
out.push(ty);
}
}
_ => {}
}
}
out
}
#[test]
fn a_type_name_span_slices_back_to_the_name_as_written() {
let src = "\
module m (input bus_if.mp bus, input [7:0] raw);
typedef pkg_a::state_t alias_t;
logic [3:0] plain;
my_type_t user;
virtual clk_rst_if vif;
endmodule
";
let file = parse_source(src).expect("parse error");
let types = module_types(&file);
let seen: Vec<&str> = types.iter().map(|ty| slice(src, ty.name_span())).collect();
assert_eq!(seen, ["bus_if.mp", "", "pkg_a::state_t", "logic", "my_type_t", "clk_rst_if"]);
for ty in &types {
assert_eq!(slice(src, ty.name_span()), ty.name, "a type-name span moved off its name");
}
// The implicit `input [7:0] raw` has no name, so its span is the empty
// range where one would have been written — at the `[`.
let implicit = types[1].name_span();
assert!(implicit.is_empty());
assert_eq!(&src[implicit.start as usize..implicit.start as usize + 1], "[");
}
#[test]
fn segments_split_a_qualified_type_name_without_rescanning() {
let src = "\
module m (input bus_if.mp bus);
pkg_a::state_t s;
logic plain;
endmodule
";
let file = parse_source(src).expect("parse error");
let types = module_types(&file);
let split = |ty: &DataType| -> Vec<(String, String)> {
ty.segments().map(|(seg, span)| (seg.to_string(), slice(src, span).to_string())).collect()
};
assert_eq!(split(types[0]), [("bus_if".into(), "bus_if".into()), ("mp".into(), "mp".into())]);
assert_eq!(
split(types[1]),
[("pkg_a".into(), "pkg_a".into()), ("state_t".into(), "state_t".into())]
);
assert_eq!(split(types[2]), [("logic".to_string(), "logic".to_string())]);
// An implicit type has no name and so no segments at all.
let empty = DataType::default();
assert_eq!(empty.segments().count(), 0);
}
#[test]
fn an_escaped_segment_keeps_its_terminating_space_in_span_and_segment() {
// §29: the parser joins `\a+b ::state_t` with the space the escaped
// identifier needs, so the joined name is what the source spells and the
// first segment carries the terminator.
let src = "module m;\n \\a+b ::state_t s;\nendmodule\n";
let file = parse_source(src).expect("parse error");
let types = module_types(&file);
assert_eq!(types[0].name, "\\a+b ::state_t");
assert_eq!(slice(src, types[0].name_span()), "\\a+b ::state_t");
let segs: Vec<&str> = types[0].segments().map(|(_, span)| slice(src, span)).collect();
assert_eq!(segs, ["\\a+b ", "state_t"]);
}
#[test]
fn a_disable_names_its_target_with_a_span() {
let src = "\
module m;
initial begin : blk
disable blk;
disable fork;
end
endmodule
";
let file = parse_source(src).expect("parse error");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let ItemKind::Initial(outer) = &m.items[0].kind else { panic!("expected an initial") };
let StmtKind::Block { stmts, .. } = &outer.kind else { panic!("expected a block") };
let targets: Vec<&str> = stmts
.iter()
.map(|s| {
let StmtKind::Disable { name_span, .. } = &s.kind else { panic!("expected a disable") };
slice(src, *name_span)
})
.collect();
assert_eq!(targets, ["blk", "fork"]);
}
+8
View File
@@ -8,3 +8,11 @@ description = "Refactorings for Verilog/SystemVerilog, computed from resolved re
[dependencies]
vlog_parser = { path = "../vlog_parser" }
vlog_semantic = { path = "../vlog_semantic" }
[dev-dependencies]
# Tests only, the same arrangement `vlog_linter` uses: the `.*` expansion's
# acceptance test asserts that what the refactoring writes is something the
# formatter accepts and leaves alone the second time. The library still
# depends on vlog_parser + vlog_semantic alone
# (`cargo tree -p vlog_refactor -e normal`).
vlog_formatter = { path = "../vlog_formatter" }
-885
View File
@@ -1,885 +0,0 @@
//! Whole-edit-or-nothing verification.
//!
//! Two independent checks, both run on the edited text in memory before any
//! edit is returned. **Token identity** catches lexical damage — an edit that
//! landed in a string, ate a comment, merged two tokens. **Resolution
//! identity** catches semantic damage — a name captured by an existing
//! declaration, or a cross-file use that quietly rebound. Neither implies the
//! other, and either one failing fails the entire refactoring.
//!
//! [`verify`] is the *rename* contract: the token stream may not change shape
//! at all. [`verify_splice`] is the same contract for a refactoring that
//! deliberately writes or deletes text (the port ones): the token stream may
//! change only by exactly the pieces the edits spell, no comment may be
//! deleted, no file may gain a parse error, and every name *outside* the
//! edited ranges must still resolve to exactly what it did.
//!
//! Nothing here touches `vlog_formatter` or its `verify.rs`: this is the same
//! contract, kept separately, so the formatter's safety net does not widen.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use vlog_parser::span::TextRange;
use vlog_parser::token::TokenKind;
use vlog_parser::{parse_source_tolerant, tokenize};
use vlog_semantic::{
analyze, resolve_external, ExternalResolutions, ExternalTarget, ReferenceId, Semantics,
SymbolKind, WorkspaceIndex,
};
use crate::rename::{contains_word, display, Scope};
use crate::{apply, Shift, TextEdit};
/// Check the whole edit, or refuse it whole.
pub(crate) fn verify(
scope: &mut Scope,
edits: &[(usize, Vec<TextEdit>)],
old_name: &str,
new_name: &str,
) -> Result<(), String> {
let edited: Vec<(PathBuf, String)> = edits
.iter()
.filter_map(|(i, edits)| {
let path = scope.path(*i)?.to_path_buf();
Some((path, apply(scope.text(*i)?, edits)))
})
.collect();
if edited.len() != edits.len() {
return Err(ABANDONED.to_string());
}
let shifts = Shifts::new(scope, edits, new_name);
// 1. The token stream of every touched file, before and after.
for ((i, edits), (path, text)) in edits.iter().zip(&edited) {
let Some(before) = scope.text(*i) else { return Err(ABANDONED.to_string()) };
tokens_match(before, text, &Shift::new(edits), new_name, path)?;
}
// 2. What every name resolves to, before and after — in every file the
// rename could possibly have moved, not only the ones it edited. A file
// that spells neither name cannot change meaning: an edit only adds and
// removes declarations of those two names, and a lookup of any other name
// cannot see them. A file that spells *either* is watched, which is what
// catches a third file whose existing `new_name` reference the rename
// would make ambiguous without touching a byte of it.
let watched = watched_files(scope, edits, old_name, new_name);
for &i in &watched {
if scope.analysis(i).is_none() {
return Err(ABANDONED.to_string());
}
}
let mut before: Vec<Print> = Vec::new();
for &i in &watched {
let (Some(path), Some(analysis)) = (scope.path(i), scope.cached(i)) else {
return Err(ABANDONED.to_string());
};
before.push(print(
&analysis.semantics,
&analysis.external,
scope.index(),
path,
&shifts,
&[],
));
}
let after_index = rebuilt_index(scope, &edited);
for (n, &i) in watched.iter().enumerate() {
let Some(path) = scope.path(i) else { return Err(ABANDONED.to_string()) };
let text = match edited.iter().find(|(edited_path, _)| edited_path == path) {
Some((_, edited_text)) => edited_text.as_str(),
None => match scope.text(i) {
Some(text) => text,
None => return Err(ABANDONED.to_string()),
},
};
let semantics = analyze(&parse_source_tolerant(text).0, text);
let external = resolve_external(&semantics, &after_index);
let after = print(&semantics, &external, &after_index, path, &Shifts::default(), &[]);
let Some(before) = before.get(n) else { return Err(ABANDONED.to_string()) };
if let Some(what) = before.first_difference(&after) {
return Err(format!(
"renaming `{old_name}` to `{new_name}` would change what {what} means in {}; the rename was abandoned.",
display(path)
));
}
}
Ok(())
}
/// Check the whole edit of a refactoring that adds or deletes text, or refuse
/// it whole. `watch_name` is the name whose meaning the refactoring changes —
/// the module whose ports moved — and `what` names the refactoring in the
/// refusal ("adding port `cfg`").
///
/// Four checks, in the order that gives the most useful sentence first:
///
/// 1. **Lexical splice.** Every touched file must lex to exactly the original
/// pieces — code tokens *and* comments — with the edits' own pieces written
/// in at the edits' positions and nothing else moved. An edit that landed
/// in a string, split a token or wrote a `,` into a line comment cannot
/// survive it.
/// 2. **Comments are never dropped** (CLAUDE.md invariant 3): no deletion may
/// cover a comment. A port or connection with a comment on it is refused,
/// not silently un-commented.
/// 3. **The file still parses**: a touched file may not gain a parse
/// diagnostic it did not have.
/// 4. **Resolution identity outside the edits.** Every declaration and every
/// reference whose name span does not overlap an edit must resolve to the
/// same place before and after — in every watched file, edited or not. This
/// is what refuses an added port that captures a body reference, or a
/// removed port some other name silently rebinds.
pub(crate) fn verify_splice(
scope: &mut Scope,
edits: &[(usize, Vec<TextEdit>)],
watch_name: &str,
what: &str,
) -> Result<(), String> {
let abandoned = format!("lucisv could not verify {what}, so it made no edits.");
let edited: Vec<(PathBuf, String)> = edits
.iter()
.filter_map(|(i, edits)| {
let path = scope.path(*i)?.to_path_buf();
Some((path, apply(scope.text(*i)?, edits)))
})
.collect();
if edited.len() != edits.len() {
return Err(abandoned);
}
for ((i, edits), (path, text)) in edits.iter().zip(&edited) {
let Some(before) = scope.text(*i) else { return Err(abandoned) };
pieces_match(before, text, edits, path, what)?;
// A tolerant parse of a file that was already broken still reports its
// old diagnostics, so the bar is "no *new* one", not "none".
let (before_count, after_count) =
(parse_source_tolerant(before).1.len(), parse_source_tolerant(text).1.len());
if after_count > before_count {
return Err(format!(
"{what} would leave {} unparseable; no edits were made.",
display(path)
));
}
}
let shifts = Shifts::new(scope, edits, "");
let excluded = Excluded::new(scope, edits);
let watched = watched_files(scope, edits, watch_name, watch_name);
for &i in &watched {
if scope.analysis(i).is_none() {
return Err(abandoned);
}
}
let mut before: Vec<Print> = Vec::new();
for &i in &watched {
let (Some(path), Some(analysis)) = (scope.path(i), scope.cached(i)) else {
return Err(abandoned);
};
before.push(print(
&analysis.semantics,
&analysis.external,
scope.index(),
path,
&shifts,
excluded.before(path),
));
}
let after_index = rebuilt_index(scope, &edited);
for (n, &i) in watched.iter().enumerate() {
let Some(path) = scope.path(i) else { return Err(abandoned) };
let text = match edited.iter().find(|(edited_path, _)| edited_path == path) {
Some((_, edited_text)) => edited_text.as_str(),
None => match scope.text(i) {
Some(text) => text,
None => return Err(abandoned),
},
};
let semantics = analyze(&parse_source_tolerant(text).0, text);
let external = resolve_external(&semantics, &after_index);
let after = print(
&semantics,
&external,
&after_index,
path,
&Shifts::default(),
excluded.after(path),
);
let Some(before) = before.get(n) else { return Err(abandoned) };
if let Some(what_moved) = before.first_difference(&after) {
return Err(format!(
"{what} would change what {what_moved} means in {}; no edits were made.",
display(path)
));
}
}
Ok(())
}
/// The byte ranges each refactoring deliberately changed, in the coordinates
/// of the text before the edits and of the text after them. Names inside them
/// are the ones the user asked to move, so they are the only ones the
/// resolution check does not hold fixed.
#[derive(Default)]
struct Excluded {
before: HashMap<PathBuf, Vec<TextRange>>,
after: HashMap<PathBuf, Vec<TextRange>>,
}
impl Excluded {
fn new(scope: &Scope, edits: &[(usize, Vec<TextEdit>)]) -> Excluded {
let mut out = Excluded::default();
for (i, edits) in edits {
let Some(path) = scope.path(*i) else { continue };
out.before.insert(path.to_path_buf(), edits.iter().map(|e| e.range).collect());
let mut after = Vec::new();
let mut delta: i64 = 0;
for edit in edits {
let start = (edit.range.start as i64 + delta).max(0) as u32;
after.push(TextRange::new(start, start + edit.new_text.len() as u32));
delta += edit.new_text.len() as i64 - i64::from(edit.range.len());
}
out.after.insert(path.to_path_buf(), after);
}
out
}
fn before(&self, path: &Path) -> &[TextRange] {
self.before.get(path).map_or(&[], Vec::as_slice)
}
fn after(&self, path: &Path) -> &[TextRange] {
self.after.get(path).map_or(&[], Vec::as_slice)
}
}
/// Every file whose resolution the rename could move: the ones it edits, plus
/// the ones that spell either name as a whole word. A whole-word text search
/// is a sound *superset* of "has a token spelling the name" — a token spells
/// its name literally, so it is always found — and it errs by watching a few
/// files whose only mention is in a comment.
fn watched_files(
scope: &Scope,
edits: &[(usize, Vec<TextEdit>)],
old_name: &str,
new_name: &str,
) -> Vec<usize> {
let mut watched: Vec<usize> = edits.iter().map(|(i, _)| *i).collect();
for i in 0..scope.len() {
let Some(text) = scope.text(i) else { continue };
if watched.contains(&i) {
continue;
}
if contains_word(text, old_name) || contains_word(text, new_name) {
watched.push(i);
}
}
watched.sort_unstable();
watched
}
const ABANDONED: &str = "lucisv could not verify the rename, so it made no edits.";
/// The workspace index as it would be after the edits, so that a cross-file
/// capture is caught exactly the way an in-file one is.
fn rebuilt_index(scope: &Scope, edited: &[(PathBuf, String)]) -> WorkspaceIndex {
let sources = scope.sources().iter().map(|(path, text)| {
let text = edited
.iter()
.find(|(edited_path, _)| edited_path == path)
.map_or(*text, |(_, edited_text)| edited_text.as_str());
(path.to_path_buf(), text)
});
WorkspaceIndex::build(sources.collect::<Vec<_>>())
}
// ----------------------------------------------------------------------
// token identity
// ----------------------------------------------------------------------
/// The edited file must lex to the same tokens as the original, except that
/// the tokens the edits replaced now spell the new name.
fn tokens_match(
before: &str,
after: &str,
shift: &Shift,
new_name: &str,
path: &Path,
) -> Result<(), String> {
let refusal = |what: &str| {
format!("the rename would change {what} in {}; no edits were made.", display(path))
};
let (Ok(old), Ok(new)) = (tokenize(before), tokenize(after)) else {
return Err(format!(
"{} would no longer lex after the rename; no edits were made.",
display(path)
));
};
if old.len() != new.len() {
return Err(refusal("the token stream's shape"));
}
for (old, new) in old.iter().zip(&new) {
let edited = shift.is_edited(old.span);
let expected_text = if edited { new_name } else { old.text.as_str() };
let expected_kind = if edited { TokenKind::Ident } else { old.kind };
if new.kind != expected_kind || new.text != expected_text {
return Err(refusal(&format!("the token `{}`", old.text)));
}
if new.span != shift.map(old.span) {
return Err(refusal(&format!("where `{}` sits", old.text)));
}
if new.blank_before != old.blank_before {
return Err(refusal("the blank lines"));
}
let comments_kept = old.leading.len() == new.leading.len()
&& old.leading.iter().zip(&new.leading).all(|(a, b)| a.text == b.text)
&& old.trailing.as_ref().map(|c| &c.text) == new.trailing.as_ref().map(|c| &c.text);
if !comments_kept {
return Err(refusal("a comment"));
}
}
Ok(())
}
// ----------------------------------------------------------------------
// lexical splice
// ----------------------------------------------------------------------
/// One lexical piece of a file, in source order: a code token, or a comment.
/// Comments are pieces of their own rather than trivia hanging off a token,
/// because an insertion can legitimately move which token a comment attaches
/// to without moving the comment itself.
#[derive(Debug, PartialEq, Eq)]
enum Piece {
Code(TokenKind, String),
Comment(String),
}
impl Piece {
/// How the piece is named in a refusal.
fn describe(&self) -> String {
match self {
Piece::Code(_, text) => format!("the token `{text}`"),
Piece::Comment(text) => format!("the comment `{text}`"),
}
}
}
/// Every piece of a file with the bytes it occupies, in source order.
fn pieces(text: &str) -> Option<Vec<(TextRange, Piece)>> {
let tokens = tokenize(text).ok()?;
let mut out: Vec<(TextRange, Piece)> = Vec::new();
for token in &tokens {
for comment in &token.leading {
out.push((comment.span, Piece::Comment(comment.text.clone())));
}
if token.kind != TokenKind::Eof {
out.push((token.span, Piece::Code(token.kind, token.text.clone())));
}
if let Some(comment) = &token.trailing {
out.push((comment.span, Piece::Comment(comment.text.clone())));
}
}
out.sort_by_key(|(span, _)| (span.start, span.end));
Some(out)
}
/// The edited file must lex to the original's pieces with the edits' own
/// pieces written in where the edits are — and to nothing else.
fn pieces_match(
before: &str,
after: &str,
edits: &[TextEdit],
path: &Path,
what: &str,
) -> Result<(), String> {
let (Some(old), Some(new)) = (pieces(before), pieces(after)) else {
return Err(format!(
"{} would no longer lex after {what}; no edits were made.",
display(path)
));
};
// Invariant 3, checked here rather than trusted to the planner: a deletion
// that covers a comment would delete it from both sides of this comparison
// and pass, so it is refused outright.
for (span, piece) in &old {
let deleted = edits.iter().any(|e| !e.range.is_empty() && overlaps(e.range, *span));
if deleted && matches!(piece, Piece::Comment(_)) {
return Err(format!(
"{what} would delete {} in {}; comments are never dropped, so nothing was edited.",
piece.describe(),
display(path)
));
}
}
let mut expected: Vec<Piece> = Vec::new();
let mut next = 0usize;
let mut written: Vec<Vec<(TextRange, Piece)>> = Vec::new();
for edit in edits {
let Some(pieces) = pieces(&edit.new_text) else {
return Err(format!("{what} would write text that does not lex; no edits were made."));
};
written.push(pieces);
}
for (span, piece) in old {
while let (Some(edit), Some(pieces)) = (edits.get(next), written.get(next)) {
if edit.range.start > span.start {
break;
}
expected.extend(pieces.iter().map(|(_, piece)| match piece {
Piece::Code(kind, text) => Piece::Code(*kind, text.clone()),
Piece::Comment(text) => Piece::Comment(text.clone()),
}));
next += 1;
}
if edits.iter().any(|e| !e.range.is_empty() && overlaps(e.range, span)) {
continue;
}
expected.push(piece);
}
while let Some(pieces) = written.get(next) {
expected.extend(pieces.iter().map(|(_, piece)| match piece {
Piece::Code(kind, text) => Piece::Code(*kind, text.clone()),
Piece::Comment(text) => Piece::Comment(text.clone()),
}));
next += 1;
}
let actual: Vec<Piece> = new.into_iter().map(|(_, piece)| piece).collect();
for (n, expected) in expected.iter().enumerate() {
match actual.get(n) {
Some(actual) if actual == expected => {}
Some(actual) => {
return Err(format!(
"{what} would write {} where {} belongs in {}; no edits were made.",
actual.describe(),
expected.describe(),
display(path)
))
}
None => {
return Err(format!(
"{what} would lose {} in {}; no edits were made.",
expected.describe(),
display(path)
))
}
}
}
if actual.len() > expected.len() {
let extra = actual.get(expected.len()).map_or_else(String::new, Piece::describe);
return Err(format!(
"{what} would add {extra} to {}, which is not part of the edit; no edits were made.",
display(path)
));
}
Ok(())
}
/// Whether two byte ranges share a byte. Empty ranges — the insertions —
/// overlap nothing: they replace no text, so they delete nothing.
fn overlaps(a: TextRange, b: TextRange) -> bool {
a.start < b.end && b.start < a.end
}
// ----------------------------------------------------------------------
// resolution identity
// ----------------------------------------------------------------------
/// Where the edits moved each touched file's bytes, keyed by path, plus the
/// name the edited occurrences now spell. The default value maps nothing,
/// which is what the post-edit side wants.
#[derive(Default)]
struct Shifts {
by_path: HashMap<PathBuf, Shift>,
new_name: String,
}
impl Shifts {
fn new(scope: &Scope, edits: &[(usize, Vec<TextEdit>)], new_name: &str) -> Shifts {
let mut by_path = HashMap::new();
for (i, edits) in edits {
if let Some(path) = scope.path(*i) {
by_path.insert(path.to_path_buf(), Shift::new(edits));
}
}
Shifts { by_path, new_name: new_name.to_string() }
}
fn map(&self, path: &Path, span: TextRange) -> TextRange {
self.by_path.get(path).map_or(span, |shift| shift.map(span))
}
/// The name an occurrence spells after the edits.
fn name(&self, path: &Path, span: TextRange, name: &str) -> String {
match self.by_path.get(path) {
Some(shift) if shift.is_edited(span) => self.new_name.clone(),
_ => name.to_string(),
}
}
}
/// What one name resolves to, said in terms that survive an edit: a file path
/// and a byte span, never a `SymbolId` or a `FileId` (both are positions in
/// tables that a re-analysis rebuilds).
#[derive(Debug, PartialEq, Eq)]
enum Anchor {
/// A declaration in the same file.
Local(u32, u32),
/// Declarations the workspace overlay answered with, in its own order.
External(Vec<(PathBuf, u32, u32)>),
/// Nothing resolves it — `NotFound`, an inherited candidate, or an
/// external candidate the workspace cannot answer.
Unresolved,
}
/// Everything one file declares and everything it names, with the spans and
/// anchors of the *edited* text. Built for the pre-edit analysis (shifted
/// forward) and for the post-edit one (as it is); the two must be equal.
#[derive(Debug, PartialEq, Eq, Default)]
struct Print {
declarations: Vec<(u32, u32, String, SymbolKind)>,
references: Vec<(u32, u32, String, Anchor)>,
}
impl Print {
/// The first entry the two prints disagree on, named for the user.
fn first_difference(&self, other: &Print) -> Option<String> {
if self.declarations.len() != other.declarations.len() {
return Some("the set of declarations".to_string());
}
for (a, b) in self.declarations.iter().zip(&other.declarations) {
if a != b {
return Some(format!("the declaration of `{}`", b.2));
}
}
if self.references.len() != other.references.len() {
return Some("the set of names".to_string());
}
for (a, b) in self.references.iter().zip(&other.references) {
if a != b {
return Some(format!("`{}`", b.2));
}
}
None
}
}
/// Everything one file declares and names, minus whatever sits inside
/// `excluded` — the ranges the refactoring deliberately wrote or deleted.
/// A rename passes no exclusions: it changes a spelling, never a structure.
fn print(
semantics: &Semantics,
external: &ExternalResolutions,
index: &WorkspaceIndex,
path: &Path,
shifts: &Shifts,
excluded: &[TextRange],
) -> Print {
let inside = |span: TextRange| excluded.iter().any(|range| overlaps(*range, span));
let mut declarations: Vec<(u32, u32, String, SymbolKind)> = semantics
.symbols()
.iter()
.filter(|symbol| !inside(symbol.name_span))
.map(|symbol| {
let span = shifts.map(path, symbol.name_span);
(span.start, span.end, shifts.name(path, symbol.name_span, &symbol.name), symbol.kind)
})
.collect();
declarations.sort_by_key(|d| (d.0, d.1));
let mut references: Vec<(u32, u32, String, Anchor)> = semantics
.references()
.iter()
.enumerate()
.filter(|(_, reference)| !inside(reference.name_span))
.map(|(id, reference)| {
let span = shifts.map(path, reference.name_span);
let anchor = anchor_of(semantics, external, index, path, shifts, id, reference);
(span.start, span.end, shifts.name(path, reference.name_span, &reference.name), anchor)
})
.collect();
references.sort_by_key(|r| (r.0, r.1));
Print { declarations, references }
}
fn anchor_of(
semantics: &Semantics,
external: &ExternalResolutions,
index: &WorkspaceIndex,
path: &Path,
shifts: &Shifts,
id: usize,
reference: &vlog_semantic::Reference,
) -> Anchor {
if let Some(symbol) = reference.resolved().and_then(|s| semantics.symbol(s)) {
let span = shifts.map(path, symbol.name_span);
return Anchor::Local(span.start, span.end);
}
let defs = match external.get(ReferenceId(id as u32)) {
Some(ExternalTarget::Resolved(def)) => std::slice::from_ref(def),
Some(ExternalTarget::Ambiguous(defs)) => defs.as_slice(),
_ => &[],
};
if defs.is_empty() {
return Anchor::Unresolved;
}
Anchor::External(
defs.iter()
.map(|def| {
let file = index.path(def.file).unwrap_or(Path::new("?")).to_path_buf();
let span = shifts.map(&file, def.name_span);
(file, span.start, span.end)
})
.collect(),
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::rename::Scope;
const SOURCE: &str =
"module m;\n wire a;\n assign a = 1; // a stays\n initial $display(\"a\");\nendmodule\n";
/// The two edits a `a` → `sig` rename of `SOURCE` would produce.
fn rename_edits() -> Vec<TextEdit> {
let declaration = SOURCE.find("wire a").expect("decl") as u32 + 5;
let use_ = SOURCE.find("assign a").expect("use") as u32 + 7;
vec![
TextEdit {
range: TextRange::new(declaration, declaration + 1),
new_text: "sig".into(),
},
TextEdit { range: TextRange::new(use_, use_ + 1), new_text: "sig".into() },
]
}
fn attack(corrupted: &str) -> Result<(), String> {
let edits = rename_edits();
tokens_match(SOURCE, corrupted, &Shift::new(&edits), "sig", Path::new("/rtl/m.sv"))
}
#[test]
fn the_edit_the_engine_actually_produces_verifies() {
let honest = apply(SOURCE, &rename_edits());
assert_eq!(attack(&honest), Ok(()), "the real output must pass");
assert!(honest.contains("wire sig;") && honest.contains("// a stays"));
}
// The masked-corruption attacks: crafted (input, corrupted output) pairs
// that a sloppier check would forgive.
#[test]
fn an_edit_that_also_rewrote_a_comment_is_rejected() {
let corrupted = apply(SOURCE, &rename_edits()).replace("// a stays", "// sig stays");
assert!(attack(&corrupted).is_err(), "a comment must not change");
}
#[test]
fn an_edit_that_also_rewrote_a_string_is_rejected() {
let corrupted = apply(SOURCE, &rename_edits()).replace("\"a\"", "\"sig\"");
assert!(attack(&corrupted).is_err(), "a string literal must not change");
}
#[test]
fn an_edit_that_dropped_a_comment_is_rejected() {
let corrupted = apply(SOURCE, &rename_edits()).replace(" // a stays", "");
assert!(attack(&corrupted).is_err(), "comments are never dropped");
}
#[test]
fn an_edit_that_lost_or_gained_a_token_is_rejected() {
let dropped = apply(SOURCE, &rename_edits()).replace("assign sig = 1;", "assign sig = 1");
assert!(attack(&dropped).is_err(), "a lost `;`");
let gained = apply(SOURCE, &rename_edits()).replace("wire sig;", "wire sig, extra;");
assert!(attack(&gained).is_err(), "an invented declaration");
}
#[test]
fn an_edit_that_wrote_a_different_name_is_rejected() {
let corrupted = apply(SOURCE, &rename_edits()).replacen("wire sig", "wire other", 1);
assert!(attack(&corrupted).is_err(), "the edited token must spell the new name");
}
#[test]
fn an_edit_that_moved_an_untouched_token_is_rejected() {
// Whitespace only — the token stream is otherwise identical, which is
// exactly what a check comparing texts alone would wave through.
let corrupted = apply(SOURCE, &rename_edits()).replace("assign sig", "assign sig");
assert!(attack(&corrupted).is_err(), "a shifted span must be caught");
}
#[test]
fn an_edit_whose_result_does_not_lex_is_rejected() {
let corrupted = apply(SOURCE, &rename_edits()).replace("endmodule", "/* oops");
assert!(attack(&corrupted).is_err(), "an unlexable result is a failure, not output");
}
// ------------------------------------------------------------------
// the splice verifier, and the attacks on it
// ------------------------------------------------------------------
/// A module whose port list is one per line, with a comment on each port —
/// the shape every one of the attacks below tries to damage.
const PORTS: &str =
"module m (\n input clk, // the clock\n input rst /* sync */\n);\n wire a; // a\nendmodule\n";
/// The edit `add_port` produces for `PORTS`: a `,` before the last port's
/// comment and the new port after it.
fn add_edits() -> Vec<TextEdit> {
let end = PORTS.find("input rst").expect("rst") as u32 + "input rst".len() as u32;
let after_comment = PORTS.find("*/").expect("comment") as u32 + 2;
vec![
TextEdit { range: TextRange::empty(end), new_text: ",".into() },
TextEdit {
range: TextRange::empty(after_comment),
new_text: "\n input logic [7:0] cfg".into(),
},
]
}
fn splice_attack(corrupted: &str) -> Result<(), String> {
pieces_match(PORTS, corrupted, &add_edits(), Path::new("/rtl/m.sv"), "adding port `cfg`")
}
#[test]
fn the_splice_the_engine_actually_produces_verifies() {
let honest = apply(PORTS, &add_edits());
assert_eq!(splice_attack(&honest), Ok(()), "the real output must pass");
assert!(honest.contains("input rst, /* sync */\n input logic [7:0] cfg"), "{honest}");
}
#[test]
fn a_splice_that_wrote_the_comma_into_a_line_comment_is_rejected() {
// The hazard the two-edit shape exists to avoid: a `,` after `//` is a
// `,` nobody will ever see.
let corrupted = PORTS
.replace("// the clock", "// the clock,")
.replace("input rst /* sync */", "input rst /* sync */\n input logic [7:0] cfg");
assert!(splice_attack(&corrupted).is_err(), "a comma inside a comment is not an edit");
}
#[test]
fn a_splice_that_landed_at_the_wrong_place_is_rejected() {
// The same tokens, spliced one port earlier: every piece is accounted
// for, but not in the order the edits promised.
let corrupted = apply(PORTS, &add_edits())
.replace("input clk,", "input clk, input logic [7:0] cfg,")
.replace(",\n input logic [7:0] cfg\n)", "\n)");
assert!(splice_attack(&corrupted).is_err(), "position is part of the promise");
}
#[test]
fn a_splice_that_also_dropped_a_comment_is_rejected() {
let corrupted = apply(PORTS, &add_edits()).replace(" // a", "");
assert!(splice_attack(&corrupted).is_err(), "comments are never dropped");
}
#[test]
fn a_splice_that_also_rewrote_an_untouched_token_is_rejected() {
let corrupted = apply(PORTS, &add_edits()).replace("wire a;", "wire b;");
assert!(splice_attack(&corrupted).is_err(), "nothing outside the edit may move");
}
#[test]
fn a_splice_that_wrote_more_than_it_promised_is_rejected() {
let corrupted = apply(PORTS, &add_edits()).replace("wire a;", "wire a; wire extra;");
assert!(splice_attack(&corrupted).is_err(), "an invented declaration");
}
#[test]
fn a_splice_that_landed_inside_a_string_is_rejected() {
let text = "module m;\n initial $display(\"hello\");\nendmodule\n";
let at = text.find("hello").expect("string") as u32;
let edits = vec![TextEdit { range: TextRange::empty(at), new_text: "x".into() }];
let corrupted = apply(text, &edits);
let outcome = pieces_match(text, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit");
assert!(outcome.is_err(), "the string's own text is not a token lucisv may write");
}
#[test]
fn a_deletion_that_would_swallow_a_comment_is_refused() {
// The one rule the piece comparison cannot see on its own: a comment
// inside a deleted range disappears from *both* sides.
let start = PORTS.find("input rst").expect("rst") as u32;
let end = PORTS.find("*/").expect("comment") as u32 + 2;
let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }];
let corrupted = apply(PORTS, &edits);
let outcome =
pieces_match(PORTS, &corrupted, &edits, Path::new("/rtl/m.sv"), "removing port `rst`");
let message = outcome.expect_err("a deleted comment is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
}
#[test]
fn a_splice_whose_result_does_not_lex_is_rejected() {
let corrupted = apply(PORTS, &add_edits()).replace("endmodule", "/* oops");
assert!(splice_attack(&corrupted).is_err(), "an unlexable result is a failure, not output");
}
#[test]
fn a_splice_that_captures_a_name_outside_the_edit_is_rejected() {
// The resolution half: the module already has a net called `cfg`, and
// the added port would take over what the body's `cfg` means.
let source = "module m (\n input clk\n);\n wire cfg;\n assign cfg = clk;\nendmodule\n";
let files = vec![(PathBuf::from("/rtl/m.sv"), source.to_string())];
let mut scope = Scope::build(&files);
let end = source.find("input clk").expect("clk") as u32 + "input clk".len() as u32;
let edits = vec![(
0usize,
vec![TextEdit { range: TextRange::empty(end), new_text: ",\n input cfg".into() }],
)];
let outcome = verify_splice(&mut scope, &edits, "m", "adding port `cfg`");
assert!(outcome.is_err(), "a captured body reference must refuse: {outcome:?}");
}
#[test]
fn a_splice_that_leaves_a_file_unparseable_is_rejected() {
let source = "module m (\n input clk\n);\nendmodule\n";
let files = vec![(PathBuf::from("/rtl/m.sv"), source.to_string())];
let mut scope = Scope::build(&files);
let end = source.find("input clk").expect("clk") as u32 + "input clk".len() as u32;
let edits = vec![(
0usize,
vec![TextEdit { range: TextRange::empty(end), new_text: ", input )( x".into() }],
)];
let outcome = verify_splice(&mut scope, &edits, "m", "adding port `x`");
assert!(outcome.is_err(), "a new parse error is a refusal: {outcome:?}");
}
#[test]
fn an_honest_port_addition_verifies() {
let source = "module m (\n input clk\n);\n wire a;\nendmodule\n";
let files = vec![(PathBuf::from("/rtl/m.sv"), source.to_string())];
let mut scope = Scope::build(&files);
let end = source.find("input clk").expect("clk") as u32 + "input clk".len() as u32;
let edits = vec![(
0usize,
vec![TextEdit { range: TextRange::empty(end), new_text: ",\n input rst".into() }],
)];
assert_eq!(verify_splice(&mut scope, &edits, "m", "adding port `rst`"), Ok(()));
}
#[test]
fn a_rename_that_edited_the_declaration_but_not_its_uses_is_rejected() {
// The whole point of the resolution check: the tokens are perfect, the
// file still parses, and `a` now names nothing.
let files = vec![(PathBuf::from("/rtl/m.sv"), SOURCE.to_string())];
let mut scope = Scope::build(&files);
let declaration = SOURCE.find("wire a").expect("decl") as u32 + 5;
let partial = vec![(
0usize,
vec![TextEdit {
range: TextRange::new(declaration, declaration + 1),
new_text: "sig".into(),
}],
)];
let outcome = verify(&mut scope, &partial, "a", "sig");
assert!(outcome.is_err(), "a half-done rename must not verify: {outcome:?}");
}
}
+929
View File
@@ -0,0 +1,929 @@
//! The lexical half of the splice contract: the pieces a file is made of, the
//! comparison that says an edit wrote exactly what it promised, and the ledger
//! of the pieces that are never dropped.
//!
//! [`super::verify_splice`] and [`super::verify_move`] are the callers, and the
//! difference between them lives here: a splice balances every never-dropped
//! piece inside one file, while a move is allowed to carry the pieces of one
//! region into the file that receives them — [`Transit`] is that allowance and
//! the whole of it.
use std::collections::HashMap;
use std::path::Path;
use vlog_parser::span::TextRange;
use vlog_parser::token::TokenKind;
use vlog_parser::tokenize;
use crate::rename::display;
use crate::TextEdit;
use super::{Moving, Origin};
// ----------------------------------------------------------------------
// lexical splice
// ----------------------------------------------------------------------
/// One lexical piece of a file, in source order: a code token, or a comment.
/// Comments are pieces of their own rather than trivia hanging off a token,
/// because an insertion can legitimately move which token a comment attaches
/// to without moving the comment itself.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Piece {
Code(TokenKind, String),
Comment(String),
}
impl Piece {
/// How the piece is named in a refusal.
fn describe(&self) -> String {
match self {
Piece::Code(_, text) => format!("the token `{text}`"),
Piece::Comment(text) => format!("the comment `{text}`"),
}
}
}
/// Every piece of a file with the bytes it occupies, in source order.
fn pieces(text: &str) -> Option<Vec<(TextRange, Piece)>> {
let tokens = tokenize(text).ok()?;
let mut out: Vec<(TextRange, Piece)> = Vec::new();
for token in &tokens {
for comment in &token.leading {
out.push((comment.span, Piece::Comment(comment.text.clone())));
}
if token.kind != TokenKind::Eof {
out.push((token.span, Piece::Code(token.kind, token.text.clone())));
}
if let Some(comment) = &token.trailing {
out.push((comment.span, Piece::Comment(comment.text.clone())));
}
}
out.sort_by_key(|(span, _)| (span.start, span.end));
Some(out)
}
/// One file's three streams of pieces: what it had, what it has, and what the
/// edits themselves spell.
pub(super) struct Split {
old: Vec<(TextRange, Piece)>,
new: Vec<(TextRange, Piece)>,
written: Vec<Vec<(TextRange, Piece)>>,
}
impl Split {
/// Lex all three, or say which one lucisv could not read.
pub(super) fn read(
before: &str,
after: &str,
edits: &[TextEdit],
path: &Path,
what: &str,
) -> Result<Split, String> {
let (Some(old), Some(new)) = (pieces(before), pieces(after)) else {
return Err(format!(
"{} would no longer lex after {what}; no edits were made.",
display(path)
));
};
let mut written: Vec<Vec<(TextRange, Piece)>> = Vec::new();
for edit in edits {
let Some(pieces) = pieces(&edit.new_text) else {
return Err(format!(
"{what} would write text that does not lex; no edits were made."
));
};
written.push(pieces);
}
Ok(Split { old, new, written })
}
/// The edited file must lex to the original's pieces with the edits' own
/// pieces written in where the edits are — and to nothing else.
pub(super) fn positions_match(
&self,
edits: &[TextEdit],
path: &Path,
what: &str,
) -> Result<(), String> {
let clone = |pieces: &[(TextRange, Piece)]| -> Vec<Piece> {
pieces
.iter()
.map(|(_, piece)| match piece {
Piece::Code(kind, text) => Piece::Code(*kind, text.clone()),
Piece::Comment(text) => Piece::Comment(text.clone()),
})
.collect()
};
let mut expected: Vec<Piece> = Vec::new();
let mut next = 0usize;
for (span, piece) in &self.old {
while let (Some(edit), Some(pieces)) = (edits.get(next), self.written.get(next)) {
if edit.range.start > span.start {
break;
}
expected.extend(clone(pieces));
next += 1;
}
if edits.iter().any(|e| !e.range.is_empty() && overlaps(e.range, *span)) {
continue;
}
expected.push(piece.clone());
}
while let Some(pieces) = self.written.get(next) {
expected.extend(clone(pieces));
next += 1;
}
let actual = clone(&self.new);
for (n, expected) in expected.iter().enumerate() {
match actual.get(n) {
Some(actual) if actual == expected => {}
Some(actual) => {
return Err(format!(
"{what} would write {} where {} belongs in {}; no edits were made.",
actual.describe(),
expected.describe(),
display(path)
))
}
None => {
return Err(format!(
"{what} would lose {} in {}; no edits were made.",
expected.describe(),
display(path)
))
}
}
}
if actual.len() > expected.len() {
let extra = actual.get(expected.len()).map_or_else(String::new, Piece::describe);
return Err(format!(
"{what} would add {extra} to {}, which is not part of the edit; no edits were made.",
display(path)
));
}
Ok(())
}
}
/// The per-file contract: the never-dropped ledger, checked on the spot, and
/// then the positional comparison. The order is the one that gives the most
/// useful sentence — a dropped comment is said as a dropped comment rather
/// than as a piece that went missing from position 47.
pub(super) fn pieces_match(
split: &Split,
edits: &[TextEdit],
path: &Path,
what: &str,
) -> Result<(), String> {
let ledger = Ledger::of(split, edits, TextRange::empty(0));
ledger.check(&display(path), what, &Tally::new())?;
split.positions_match(edits, path, what)
}
/// The range the move takes text out of file `i`, if it names that file as one
/// it *edits* at all: a source's own region, or the empty range that says
/// "this one only receives". A file the move does not name — and a file it
/// only copies out of, which it does not edit — has none, and keeps the
/// per-file contract.
pub(super) fn region_of(moving: &[Moving], i: usize) -> Option<TextRange> {
moving
.iter()
.find(|moving| moving.file == i && moving.origin == Origin::Moved)
.map(|moving| moving.region)
}
/// Whether a piece sits inside the bytes a move takes out of its file. An
/// empty region holds nothing: a destination has no region, and a piece that
/// only *overlaps* a region is one the move did not wholly carry, so it is an
/// ordinary deletion and has to be written back where it was.
fn within(region: TextRange, span: TextRange) -> bool {
!region.is_empty() && region.start <= span.start && span.end <= region.end
}
/// The pieces an edit may never lose, gain or duplicate: a **comment**
/// (CLAUDE.md invariant 3) and an **attribute instance** `(* ... *)`.
///
/// The piece comparison above cannot see either on its own. A piece inside a
/// deleted range disappears from *both* sides of it — from `expected`, because
/// pieces inside an edit are skipped, and from `actual`, because it is really
/// gone — so a dropped comment, or a dropped `(* keep *)`, would pass
/// unnoticed. An attribute is a code token rather than trivia, but a deletion
/// hides it exactly the way it hides a comment, and losing one changes what a
/// synthesizer does; so both are counted here, by exact text.
///
/// Three equations, over every text that appears on any side. `had` and `has`
/// are the file's counts before and after, `gone` counts the old pieces a
/// non-empty edit range covers, `wrote` counts the pieces lexed out of the
/// edits' own inserted text, and `out` counts the pieces of `gone` that a move
/// carried out of this file — zero for every file that is not the source of
/// one, which is every file but an extraction's.
///
/// 1. **`has + out >= had`** — nothing is ever lost. This is the whole of
/// invariant 3 and the only half the rule this replaced had; a file may end
/// up short only by exactly what left through its own moved region.
/// 2. **`wrote <= gone - out + in`**, unless the text is one a refactoring
/// [`generated`] itself — a piece is written back *where it was deleted*,
/// and nowhere else. This refuses a planner that takes the comment on
/// `input a, b;` and writes it onto *both* ports (one really did, on the
/// way — see the work log), and equally one that duplicates the text of a
/// comment it never touched. `in` is the transit a **destination** of a
/// move may receive and is zero everywhere else, so a deletion outside the
/// moved region has to be written back in its own file as it always did.
/// 3. **`has == had - gone + wrote`** — the applied text says exactly what the
/// edits say, transit out counted as gone and transit in as wrote. An
/// application that grew a second copy of a comment the edits write once is
/// masked corruption the first two equations would forgive.
///
/// Where each piece now *sits* is the piece comparison's business, not this
/// one's; between them a moved comment is verified as exactly as a stationary
/// one.
///
/// **A ledger is one file's**, always. [`pieces_match`] checks it with no
/// transit at all, which is the contract every refactoring that stays inside
/// one file has always had. [`super::verify_move`] gives the source of a move its
/// region — so the comment carried out of `M.sv` is `out` rather than lost —
/// and the destination the allowance to receive it, and then [`Transit`] holds
/// the two halves to each other. See
/// `docs/features/extract-inline-module/README.md` for the attack pairs.
#[derive(Default)]
struct Ledger {
/// The pieces the file had before the edits.
before: Tally,
/// The pieces it has after them.
after: Tally,
/// The old pieces a non-empty edit range covers.
deleted: Tally,
/// Of those, the ones inside the region a move takes out of this file.
out: Tally,
/// The pieces the edits' own inserted text spells.
writes: Tally,
}
impl Ledger {
/// Count one file's streams. `region` is the bytes a move carries out of
/// it — empty for every file that keeps the per-file contract, and for a
/// file that only receives.
fn of(split: &Split, edits: &[TextEdit], region: TextRange) -> Ledger {
let covered = |span: TextRange| {
edits.iter().any(|edit| !edit.range.is_empty() && overlaps(edit.range, span))
};
let mut out = Ledger::default();
tally_into(&mut out.before, split.old.iter().map(|(_, piece)| piece));
tally_into(&mut out.after, split.new.iter().map(|(_, piece)| piece));
tally_into(
&mut out.deleted,
split.old.iter().filter(|(span, _)| covered(*span)).map(|(_, piece)| piece),
);
tally_into(
&mut out.out,
split
.old
.iter()
.filter(|(span, _)| covered(*span) && within(region, *span))
.map(|(_, piece)| piece),
);
tally_into(&mut out.writes, split.written.iter().flatten().map(|(_, piece)| piece));
out
}
/// The three equations, for this one file. `where_` names it, already
/// quoted for a sentence; `receives` is the transit it may be handed by
/// the rest of the move, and is empty for every file that is not a
/// destination of one.
fn check(&self, where_: &str, what: &str, receives: &Tally) -> Result<(), String> {
let mut texts: Vec<&Kept> =
self.before.keys().chain(self.after.keys()).chain(self.writes.keys()).collect();
texts.sort_unstable();
texts.dedup();
let count = |tally: &Tally, key: &Kept| tally.get(key).copied().unwrap_or(0);
// `out` is a subset of `deleted`, so the subtraction cannot go under —
// saturating rather than plain because an arithmetic panic is not a
// refusal, and this is a safety net.
let ordinary = |key: &Kept| count(&self.deleted, key).saturating_sub(count(&self.out, key));
// Three passes rather than three tests in one pass, so that the
// sentence the user reads is the worst thing wrong with the edit
// rather than whichever text sorted first.
if let Some(Kept(noun, text)) = texts
.iter()
.find(|key| count(&self.after, key) + count(&self.out, key) < count(&self.before, key))
{
return Err(format!(
"{what} would delete the {noun} `{text}` in {where_}; {noun}s are never dropped, so nothing was edited."
));
}
if let Some(key) = texts.iter().find(|key| {
count(&self.writes, key) > ordinary(key) + count(receives, key) && !generated(&key.1)
}) {
let Kept(noun, text) = key;
let (gone, wrote) = (ordinary(key), count(&self.writes, key));
let deletes = match gone {
0 => "without deleting it".to_string(),
gone => format!("where it deletes it {}", times(gone)),
};
return Err(format!(
"{what} would write the {noun} `{text}` {} in {where_} {deletes}; {noun}s are never duplicated, so nothing was edited.",
times(wrote)
));
}
// `deleted` is a subset of `before`, so the subtraction cannot go
// under — saturating rather than plain because an arithmetic panic is
// not a refusal, and this is a safety net.
let accounted = |key: &Kept| {
count(&self.before, key).saturating_sub(count(&self.deleted, key))
+ count(&self.writes, key)
};
if let Some(key) = texts.iter().find(|key| count(&self.after, key) != accounted(key)) {
let Kept(noun, text) = key;
return Err(format!(
"{what} would leave the {noun} `{text}` in {where_} {}, where its edits account for it {}; nothing was edited.",
times(count(&self.after, key)),
times(accounted(key))
));
}
Ok(())
}
/// How many more of a piece this file's edits write than they delete —
/// what a destination of a move has to have received.
fn gained(&self, key: &Kept) -> i64 {
let count = |tally: &Tally| tally.get(key).copied().unwrap_or(0) as i64;
count(&self.writes) - count(&self.deleted)
}
}
/// The files a move names, and the never-dropped pieces travelling between
/// them: a **source** loses the pieces inside its own region, a **copy** keeps
/// them and lends them out, and a **destination** — a file the move names with
/// an empty range — is the only place they may land.
///
/// This is the whole of the widening [`super::verify_move`] exists for, and
/// the whole of what it is allowed to forgive: the allowance is bound to the
/// bytes that move, so a piece deleted anywhere else in one of these files is
/// an ordinary deletion its own ledger holds it to.
#[derive(Default)]
pub(super) struct Transit {
files: Vec<Moved>,
/// The files a move only copies out of: what a refusal calls each one, and
/// the never-dropped pieces its region holds. They have no ledger — a copy
/// is not edited, and [`super::verify_move`] refuses one that is.
copied: Vec<(String, Tally)>,
}
/// One file of a move: what a refusal calls it, whether it receives rather
/// than sends, and its own ledger.
struct Moved {
where_: String,
receives: bool,
ledger: Ledger,
}
impl Transit {
/// Take one file's counts, with the region the move carries text out of.
pub(super) fn add(
&mut self,
where_: &str,
region: TextRange,
split: &Split,
edits: &[TextEdit],
) {
self.files.push(Moved {
where_: where_.to_string(),
receives: region.is_empty(),
ledger: Ledger::of(split, edits, region),
});
}
/// Take the pieces a move **copies** out of a file it does not edit: what
/// that file's region holds, once, which is what the destinations between
/// them may write.
pub(super) fn copy(
&mut self,
where_: &str,
text: &str,
region: TextRange,
what: &str,
) -> Result<(), String> {
let Some(pieces) = pieces(text) else {
return Err(format!(
"{where_} does not lex, so {what} cannot say what it would copy out of it; no edits were made."
));
};
let mut tally = Tally::new();
tally_into(
&mut tally,
pieces.iter().filter(|(span, _)| within(region, *span)).map(|(_, piece)| piece),
);
self.copied.push((where_.to_string(), tally));
Ok(())
}
/// The three equations per file — the destinations, and only they, holding
/// the transit as their allowance — and then rule 4 over the move whole.
pub(super) fn check(&self, what: &str) -> Result<(), String> {
let mut sent = Tally::new();
for file in &self.files {
for (key, n) in &file.ledger.out {
*sent.entry(key.clone()).or_insert(0) += n;
}
}
for (_, tally) in &self.copied {
for (key, n) in tally {
*sent.entry(key.clone()).or_insert(0) += n;
}
}
let nothing = Tally::new();
for file in &self.files {
let receives = match file.receives {
true => &sent,
false => &nothing,
};
file.ledger.check(&file.where_, what, receives)?;
}
self.lands(&sent, what)
}
/// Rule 4: what left a region has to land, exactly once in total, in the
/// files the move named as destinations. Rule 2 lets each destination
/// receive the transit; this is what says the move as a whole received it
/// once — two destinations that each write the comment are two comments.
fn lands(&self, sent: &Tally, what: &str) -> Result<(), String> {
let names = |receives: bool| -> Vec<String> {
let named = self.files.iter().filter(move |f| f.receives == receives);
let copies = self.copied.iter().filter(|_| !receives);
named.map(|f| f.where_.clone()).chain(copies.map(|(name, _)| name.clone())).collect()
};
let mut texts: Vec<&Kept> = sent.keys().collect();
texts.sort_unstable();
for key in texts {
let out = sent.get(key).copied().unwrap_or(0);
let landed: i64 =
self.files.iter().filter(|f| f.receives).map(|f| f.ledger.gained(key)).sum();
if landed == out as i64 {
continue;
}
let Kept(noun, text) = key;
let rule = match landed < out as i64 {
true => format!("{noun}s are never dropped"),
false => format!("{noun}s are never duplicated"),
};
let (sources, destinations) = (names(false), names(true));
let landing = match landed > 0 {
true => format!("{} into {}", times(landed as usize), and_list(&destinations)),
false => "nowhere".to_string(),
};
return Err(format!(
"{what} would carry the {noun} `{text}` out of {} {} and write it back {landing}; {rule}, so nothing was edited.",
and_list(&sources),
times(out)
));
}
Ok(())
}
}
/// One never-dropped piece, keyed for counting: the noun a refusal calls it by
/// (`comment` or `attribute`) and its exact text.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct Kept(&'static str, String);
type Tally = HashMap<Kept, usize>;
/// How many of each never-dropped piece a stream of pieces holds. Every other
/// piece is a code token the comparison above already pins position by
/// position, so it is not counted here.
fn tally_into<'p>(out: &mut Tally, pieces: impl Iterator<Item = &'p Piece>) {
for piece in pieces {
let key = match piece {
Piece::Comment(text) => Kept("comment", text.clone()),
Piece::Code(TokenKind::Attribute, text) => Kept("attribute", text.clone()),
Piece::Code(..) => continue,
};
*out.entry(key).or_insert(0) += 1;
}
}
/// The comments a refactoring writes itself rather than moves, which it may
/// therefore write however many times it needs and even where the file already
/// has one. `add_port` and `propagate_ports` both leave
/// `/* TODO: connect */` at a connection they cannot name a signal for, and a
/// module gains its ports one at a time — so the second addition to a file
/// finds the first one's placeholder already sitting there. Everything else a
/// refactoring writes has to be a piece it is deleting somewhere else.
fn generated(text: &str) -> bool {
text == "/* TODO: connect */"
}
/// A count, in prose, so a refusal reads like a sentence.
fn times(n: usize) -> String {
match n {
0 => "never".to_string(),
1 => "once".to_string(),
2 => "twice".to_string(),
n => format!("{n} times"),
}
}
/// Whether two byte ranges share a byte. Empty ranges — the insertions —
/// overlap nothing: they replace no text, so they delete nothing.
pub(super) fn overlaps(a: TextRange, b: TextRange) -> bool {
a.start < b.end && b.start < a.end
}
/// A list of file names as a sentence reads them: `a.sv`, `a.sv` and `b.sv`,
/// `a.sv`, `b.sv` and `c.sv`.
fn and_list(names: &[String]) -> String {
let quoted: Vec<String> = names.iter().map(|name| format!("`{name}`")).collect();
match quoted.split_last() {
None => "no files".to_string(),
Some((last, [])) => last.clone(),
Some((last, head)) => format!("{} and {last}", head.join(", ")),
}
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use super::*;
use crate::apply;
/// The per-file splice contract, over texts — one lex plus the production
/// [`super::pieces_match`], so every attack below asks the real question.
fn pieces_match(
before: &str,
after: &str,
edits: &[TextEdit],
path: &Path,
what: &str,
) -> Result<(), String> {
let split = Split::read(before, after, edits, path, what)?;
super::pieces_match(&split, edits, path, what)
}
// ------------------------------------------------------------------
// the splice verifier, and the attacks on it
// ------------------------------------------------------------------
/// A module whose port list is one per line, with a comment on each port —
/// the shape every one of the attacks below tries to damage.
const PORTS: &str =
"module m (\n input clk, // the clock\n input rst /* sync */\n);\n wire a; // a\nendmodule\n";
/// The edit `add_port` produces for `PORTS`: a `,` before the last port's
/// comment and the new port after it.
fn add_edits() -> Vec<TextEdit> {
let end = PORTS.find("input rst").expect("rst") as u32 + "input rst".len() as u32;
let after_comment = PORTS.find("*/").expect("comment") as u32 + 2;
vec![
TextEdit { range: TextRange::empty(end), new_text: ",".into() },
TextEdit {
range: TextRange::empty(after_comment),
new_text: "\n input logic [7:0] cfg".into(),
},
]
}
fn splice_attack(corrupted: &str) -> Result<(), String> {
pieces_match(PORTS, corrupted, &add_edits(), Path::new("/rtl/m.sv"), "adding port `cfg`")
}
#[test]
fn the_splice_the_engine_actually_produces_verifies() {
let honest = apply(PORTS, &add_edits());
assert_eq!(splice_attack(&honest), Ok(()), "the real output must pass");
assert!(honest.contains("input rst, /* sync */\n input logic [7:0] cfg"), "{honest}");
}
#[test]
fn a_splice_that_wrote_the_comma_into_a_line_comment_is_rejected() {
// The hazard the two-edit shape exists to avoid: a `,` after `//` is a
// `,` nobody will ever see.
let corrupted = PORTS
.replace("// the clock", "// the clock,")
.replace("input rst /* sync */", "input rst /* sync */\n input logic [7:0] cfg");
assert!(splice_attack(&corrupted).is_err(), "a comma inside a comment is not an edit");
}
#[test]
fn a_splice_that_landed_at_the_wrong_place_is_rejected() {
// The same tokens, spliced one port earlier: every piece is accounted
// for, but not in the order the edits promised.
let corrupted = apply(PORTS, &add_edits())
.replace("input clk,", "input clk, input logic [7:0] cfg,")
.replace(",\n input logic [7:0] cfg\n)", "\n)");
assert!(splice_attack(&corrupted).is_err(), "position is part of the promise");
}
#[test]
fn a_splice_that_also_dropped_a_comment_is_rejected() {
let corrupted = apply(PORTS, &add_edits()).replace(" // a", "");
let message = splice_attack(&corrupted).expect_err("a dropped comment is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
}
#[test]
fn a_splice_that_also_rewrote_an_untouched_token_is_rejected() {
let corrupted = apply(PORTS, &add_edits()).replace("wire a;", "wire b;");
assert!(splice_attack(&corrupted).is_err(), "nothing outside the edit may move");
}
#[test]
fn a_splice_that_wrote_more_than_it_promised_is_rejected() {
let corrupted = apply(PORTS, &add_edits()).replace("wire a;", "wire a; wire extra;");
assert!(splice_attack(&corrupted).is_err(), "an invented declaration");
}
#[test]
fn a_splice_that_landed_inside_a_string_is_rejected() {
let text = "module m;\n initial $display(\"hello\");\nendmodule\n";
let at = text.find("hello").expect("string") as u32;
let edits = vec![TextEdit { range: TextRange::empty(at), new_text: "x".into() }];
let corrupted = apply(text, &edits);
let outcome = pieces_match(text, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit");
assert!(outcome.is_err(), "the string's own text is not a token lucisv may write");
}
#[test]
fn a_deletion_that_would_swallow_a_comment_is_refused() {
// The one rule the piece comparison cannot see on its own: a comment
// inside a deleted range disappears from *both* sides.
let start = PORTS.find("input rst").expect("rst") as u32;
let end = PORTS.find("*/").expect("comment") as u32 + 2;
let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }];
let corrupted = apply(PORTS, &edits);
let outcome =
pieces_match(PORTS, &corrupted, &edits, Path::new("/rtl/m.sv"), "removing port `rst`");
let message = outcome.expect_err("a deleted comment is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
}
#[test]
fn a_splice_whose_result_does_not_lex_is_rejected() {
let corrupted = apply(PORTS, &add_edits()).replace("endmodule", "/* oops");
assert!(splice_attack(&corrupted).is_err(), "an unlexable result is a failure, not output");
}
// ------------------------------------------------------------------
// the moved-comment rule, and the attacks on it (CLAUDE.md invariant 4)
// ------------------------------------------------------------------
//
// 2026-09-05: `comments_kept` replaced "no deletion may cover a comment",
// so that `ports::ansi` can move a body declaration's comment onto the
// ANSI port that declaration becomes. Every attack below is a crafted
// (input, corrupted output) pair the relaxation could plausibly forgive.
/// A Verilog-2001 header whose two declarations each carry a comment —
/// the shape the ANSI conversion has to move a comment out of.
const MOVED: &str =
"module m (\n a,\n b\n);\n input a; // the note\n output b; // the note\nendmodule\n";
/// The edits `convert_to_ansi` really produces for `MOVED`.
fn move_edits() -> Vec<TextEdit> {
let files = vec![(PathBuf::from("/rtl/m.sv"), MOVED.to_string())];
let at = MOVED.find("module m").expect("header") as u32;
let edit = crate::convert_to_ansi(&files, Path::new("/rtl/m.sv"), at)
.expect("the conversion the attacks corrupt");
edit.edits.into_iter().next().expect("one file").1
}
fn move_attack(corrupted: &str) -> Result<(), String> {
pieces_match(
MOVED,
corrupted,
&move_edits(),
Path::new("/rtl/m.sv"),
"converting `m`'s ports to ANSI",
)
}
#[test]
fn the_moved_comments_the_engine_actually_writes_verify() {
let honest = apply(MOVED, &move_edits());
assert_eq!(move_attack(&honest), Ok(()), "the real output must pass");
assert_eq!(honest.matches("// the note").count(), 2, "both comments survive: {honest}");
assert!(honest.contains("input a, // the note"), "{honest}");
}
#[test]
fn a_move_that_kept_only_one_of_two_identical_comments_is_rejected() {
// The exact hole the character budget exists for: one of the two
// `// the note`s is dropped, and a search for its text still finds
// the other one.
let corrupted = apply(MOVED, &move_edits()).replacen(" // the note", "", 1);
let message = move_attack(&corrupted).expect_err("one comment short is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
}
#[test]
fn a_move_that_dropped_a_comment_and_invented_another_is_rejected() {
// Same character count, different text: the budget alone would
// forgive this one, and the per-comment search does not.
let corrupted = apply(MOVED, &move_edits()).replacen("// the note", "// the NOTE", 1);
let message = move_attack(&corrupted).expect_err("a rewritten comment is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
}
#[test]
fn a_move_that_shortened_a_comment_is_rejected() {
let corrupted = apply(MOVED, &move_edits()).replacen("// the note", "// the", 1);
let message = move_attack(&corrupted).expect_err("a truncated comment is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
}
#[test]
fn a_move_that_left_the_comment_where_it_was_is_rejected() {
// The deletion really deleted, but the comment was written back into
// the *body* rather than into the header: every comment is still
// there, and the piece order is not what the edits promised.
let honest = apply(MOVED, &move_edits());
let corrupted = honest
.replace("input a, // the note", "input a,")
.replace("endmodule", "// the note\nendmodule");
// `never_dropped` passes this one: every count is equal on both sides
// (the comment really was deleted and really was written back once).
// The *piece comparison* is the guard, because where a comment lands
// is bound to where the edits put it — which is also the answer to
// "a comment deleted here and written back somewhere unrelated".
let message = move_attack(&corrupted).expect_err("a misplaced comment is a refusal");
assert!(message.contains("where the comment `// the note` belongs"), "{message}");
}
#[test]
fn a_move_that_wrote_the_comment_onto_two_ports_is_rejected() {
// The bug this half of the rule was added for, reproduced as the edits
// that caused it: one declaration declares two ports, and its comment
// is written onto *both*. Nothing is dropped, and the piece comparison
// cannot object — it checks the edits against themselves, and the
// duplicate is in the edits. Only counting the file's comments sees it.
const SHARED: &str = "module m (\n a,\n b\n);\n input a, b; // both\nendmodule\n";
let at = |needle: &str| SHARED.find(needle).expect(needle) as u32;
let (a, b) = (at("\n a,") + 3, at("\n b\n") + 3);
let edits = vec![
TextEdit { range: TextRange::empty(a), new_text: "input ".into() },
TextEdit { range: TextRange::empty(a + 2), new_text: " // both".into() },
TextEdit { range: TextRange::empty(b), new_text: "input ".into() },
TextEdit { range: TextRange::empty(b + 1), new_text: " // both".into() },
TextEdit {
range: TextRange::new(at(" input a,"), at("endmodule")),
new_text: String::new(),
},
];
let corrupted = apply(SHARED, &edits);
assert_eq!(corrupted.matches("// both").count(), 2, "the attack really doubles it");
let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
.expect_err("a doubled comment is a refusal");
assert!(message.contains("would write the comment"), "{message}");
}
#[test]
fn a_deletion_that_swallows_a_comment_nothing_writes_back_is_still_refused() {
// The old rule's own case, restated: no edit writes the comment, so
// the relaxation must not reach it.
let start = MOVED.find("input a;").expect("a") as u32;
let end = MOVED.find("\n output").expect("output") as u32;
let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }];
let corrupted = apply(MOVED, &edits);
let message = pieces_match(MOVED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
.expect_err("a deleted comment nothing writes back is a refusal");
assert!(message.contains("comments are never dropped"), "{message}");
}
// ------------------------------------------------------------------
// 2026-09-05 rework: the duplication half, the equation, and attributes
// ------------------------------------------------------------------
#[test]
fn an_insertion_that_duplicates_an_untouched_comment_is_rejected() {
// QA's V-1 pair. Nothing deletes — or even overlaps — the body's own
// `// shared`, and two pure insertions each write it again. Every
// count only grows, so "before is a subset of after" forgives it, and
// the piece comparison cannot object because the duplicates are in the
// edits. Only `wrote <= gone` sees it.
const SHARED: &str =
"module m (\n a,\n b\n);\n input a; // shared\n output b;\nendmodule\n";
let at = |needle: &str| SHARED.find(needle).expect(needle) as u32;
let (a, b) = (at("\n a,") + 4, at("\n b\n") + 4);
let edits = vec![
TextEdit { range: TextRange::empty(a), new_text: " // shared".into() },
TextEdit { range: TextRange::empty(b), new_text: " // shared".into() },
];
let corrupted = apply(SHARED, &edits);
assert_eq!(corrupted.matches("// shared").count(), 3, "the attack really triples it");
let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
.expect_err("a duplicated comment is a refusal");
assert!(message.contains("comments are never duplicated"), "{message}");
}
#[test]
fn a_generated_placeholder_may_be_written_where_the_file_already_has_one() {
// The whitelist, and the whole of it. `add_port` and
// `propagate_ports` write `/* TODO: connect */` themselves, and a
// module gains its ports one at a time — so the second addition to a
// file finds the first one's placeholder already sitting there and
// writes another. `wrote > gone` with nothing deleted, and legitimate.
let source = "module top;\n sub u1 (.a(/* TODO: connect */));\nendmodule\n";
let at = source.find("))").expect("list") as u32 + 1;
let edits = vec![TextEdit {
range: TextRange::empty(at),
new_text: ", .b(/* TODO: connect */)".into(),
}];
let spliced = apply(source, &edits);
assert_eq!(spliced.matches("TODO").count(), 2, "{spliced}");
let outcome =
pieces_match(source, &spliced, &edits, Path::new("/rtl/top.sv"), "adding port `b`");
assert_eq!(outcome, Ok(()), "a generated placeholder is the engine's own text");
}
#[test]
fn an_application_that_grew_a_copy_the_edits_do_not_write_is_rejected() {
// Masked corruption of the third kind: the edits are honest — they
// delete both `// the note`s and write both back — and the *applied*
// text carries a third. Neither "nothing is lost" nor "written back
// where it was deleted" can see that; only the equation can.
let corrupted = apply(MOVED, &move_edits()).replace("endmodule", "// the note\nendmodule");
let message = move_attack(&corrupted).expect_err("an invented copy is a refusal");
assert!(message.contains("where its edits account for it"), "{message}");
}
#[test]
fn a_comment_written_back_inside_a_string_or_another_comment_is_rejected() {
// A `//` is only a comment where the lexer says it is. Written back
// inside a string literal, or swallowed into the comment next to it,
// the text is present in the file and absent from its pieces — which
// is exactly the substring search this rule refuses to be.
let honest = apply(MOVED, &move_edits());
let in_string = honest
.replacen(" // the note", "", 1)
.replace("endmodule", " initial $display(\"// the note\");\nendmodule");
let message = move_attack(&in_string).expect_err("a string is not a comment");
assert!(message.contains("comments are never dropped"), "{message}");
let nested = honest
.replacen(" // the note", "", 1)
.replace("// the note", "// the note // the note");
let message = move_attack(&nested).expect_err("one comment is not two");
assert!(message.contains("comments are never dropped"), "{message}");
}
/// A body declaration carrying an attribute instance. `Item.span` covers
/// the `(* keep *)`, so a deletion hides it from *both* sides of the piece
/// comparison exactly the way it hides a comment — QA's finding V-2.
const ATTRIBUTED: &str = "module m (\n a\n);\n (* keep *) input a;\nendmodule\n";
/// The edits an absorbing conversion of `ATTRIBUTED` makes: `input ` (plus
/// whatever `written` says) before the header name, and the whole body
/// declaration gone.
fn attribute_edits(written: &str) -> Vec<TextEdit> {
let at = |needle: &str| ATTRIBUTED.find(needle).expect(needle) as u32;
vec![
TextEdit { range: TextRange::empty(at("\n a\n") + 3), new_text: written.into() },
TextEdit {
range: TextRange::new(at(" (* keep *)"), at("endmodule")),
new_text: String::new(),
},
]
}
fn attribute_attack(edits: &[TextEdit]) -> Result<(), String> {
let corrupted = apply(ATTRIBUTED, edits);
pieces_match(
ATTRIBUTED,
&corrupted,
edits,
Path::new("/rtl/m.sv"),
"converting `m`'s ports to ANSI",
)
}
#[test]
fn a_deletion_that_swallows_an_attribute_is_rejected() {
// The planner refuses this one first (`ports::ansi::attributes_clear`,
// pinned in `tests/ansi.rs`); this is the verifier saying so a second
// time, from the edits alone, for whatever writes them next.
let message = attribute_attack(&attribute_edits("input "))
.expect_err("a dropped attribute is a refusal");
assert!(message.contains("attributes are never dropped"), "{message}");
assert!(message.contains("`(* keep *)`"), "{message}");
}
#[test]
fn an_edit_that_moves_an_attribute_verifies() {
// What the refusal above is protecting: an edit that really does carry
// the attribute over is not what this rule is for.
let edits = attribute_edits("(* keep *) input ");
assert_eq!(attribute_attack(&edits), Ok(()), "a moved attribute is a kept attribute");
assert!(apply(ATTRIBUTED, &edits).contains("(* keep *) input a"));
}
#[test]
fn an_edit_that_rewrote_an_attribute_is_rejected() {
// `(* keep *)` and `(* keep=1 *)` are not the same instruction to a
// synthesizer, and an attribute is matched by exact text.
let message = attribute_attack(&attribute_edits("(* keep=1 *) input "))
.expect_err("a rewritten attribute is a refusal");
assert!(message.contains("attributes are never dropped"), "{message}");
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,469 @@
//! Which names cross the selection's boundary, and what the new module's
//! header is therefore made of.
//!
//! `flow` says what is *done* to each name on each side; this says what each
//! crossing name **becomes** — a port, a parameter, a copied `import`, or a
//! refusal. Three closures run here, and they are one closure really: the
//! signals the selection reads and drives, the parameters they and their own
//! types depend on, and the imports the whole of that needs to resolve.
//!
//! The last of the three is the subtle one. What the new module has to be able
//! to resolve is not "the names the selection writes down" but that *plus the
//! type names of its own header* — a port declared `input logic [N-1:0] a`
//! names `N` even though no statement in the selection does, and a port typed
//! `word_t` needs whatever import supplied it. Both were found by the corpus
//! and opentitan trials rather than by reasoning; see the feature README's
//! work log.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use vlog_parser::ast::{ItemKind, SourceFile};
use vlog_parser::span::TextRange;
use vlog_semantic::{Resolution, Semantics, SymbolId, SymbolKind};
use crate::rename::display;
use super::flow;
use super::region::Region;
use super::render::{self, Param, Port};
use super::{count, escaped, header_names, inside, inside_module, lost_name};
use super::{outside_module, outside_module_member};
use super::{slice, unmovable};
// ----------------------------------------------------------------------
// the boundary
// ----------------------------------------------------------------------
/// Everything that crosses the selection's boundary, classified.
pub(super) struct Crossing {
pub(super) ports: Vec<Port>,
pub(super) params: Vec<Param>,
pub(super) imports: Vec<String>,
}
impl Crossing {
pub(super) fn read(
text: &str,
semantics: &Semantics,
region: &Region<'_>,
flow: &flow::Flow,
packages: &[(String, TextRange)],
new_file: bool,
) -> Result<Crossing, String> {
let mut ports: Vec<(TextRange, Port)> = Vec::new();
let mut params: Vec<(TextRange, Param)> = Vec::new();
let module = region.module_name().to_string();
let mut wanted: Vec<String> = Vec::new();
// Names a `package` of this file declares. `N` reaches one the way
// `M` does — through a qualified spelling, or through an import of
// that package which the new module is given a copy of.
let mut from_package: Vec<(String, String)> = Vec::new();
for (n, symbol) in semantics.symbols().iter().enumerate() {
let sides = flow.sides(SymbolId(n as u32));
let declared_inside = inside(region, symbol.name_span);
if declared_inside {
if sides.used_outside() {
return Err(escaped(&symbol.name));
}
continue;
}
if !sides.used_inside() {
continue;
}
// A module, an interface and a package are visible from every
// file of the design, so one declared beside `M` is one `N` can
// reach too — they never become ports and never refuse.
if matches!(
symbol.kind,
SymbolKind::Module | SymbolKind::Interface | SymbolKind::Package
) {
continue;
}
if !inside_module(region, symbol.name_span) {
// Not a port: a name the module itself does not declare is
// one the new module reaches the way `M` did, or one `visible`
// below refuses because a file of its own would not see it.
if let Some(package) = package_of(packages, symbol.name_span) {
from_package.push((package.to_string(), symbol.name.clone()));
}
continue;
}
match symbol.kind {
SymbolKind::Port | SymbolKind::Net | SymbolKind::Var => {
let dir = direction(&symbol.name, sides)?;
let Some(site) = render::site_of(region.module, &symbol.name) else {
return Err(lost_name(&symbol.name));
};
let port = render::port(text, &module, &symbol.name, &site, dir)?;
ports.push((symbol.name_span, port));
}
SymbolKind::Param | SymbolKind::LocalParam => wanted.push(symbol.name.clone()),
kind => return Err(unmovable(&symbol.name, &module, kind)),
}
}
// A **port's own type** may name a parameter — `input logic [N-1:0] a`
// — and that parameter crosses the boundary as squarely as one the
// selection reads, or the new module's header names nothing. So does
// a parameter's type, and a parameter's default; the three are one
// closure, run below until nothing new is wanted.
let declared = declarations(semantics, region);
for (_, port) in &ports {
for word in &port.names {
depends(&declared, &module, &port.name, word, &mut wanted)?;
}
}
let mut seen: Vec<String> = Vec::new();
while let Some(name) = wanted.pop() {
if seen.contains(&name) {
continue;
}
let Some(site) = render::site_of(region.module, &name) else {
return Err(lost_name(&name));
};
let param = render::param(text, &module, &name, &site)?;
for word in &param.names {
depends(&declared, &module, &name, word, &mut wanted)?;
}
let span = span_of(semantics, region, &name);
params.push((span, param));
seen.push(name);
}
ports.sort_by_key(|(span, _)| (span.start, span.end));
params.sort_by_key(|(span, _)| (span.start, span.end));
let needed = needed(text, semantics, flow, &ports, &params);
visible(text, semantics, region, packages, &needed, &module, new_file)?;
let imports = imports(semantics, region, packages, &needed);
reachable(text, &needed, &from_package, &imports)?;
Ok(Crossing {
ports: ports.into_iter().map(|(_, port)| port).collect(),
params: params.into_iter().map(|(_, param)| param).collect(),
imports,
})
}
pub(super) fn warnings(
&self,
new_name: &str,
created: &Option<PathBuf>,
file: &Path,
) -> Vec<String> {
let mut out = Vec::new();
out.push(match created {
Some(path) => format!(
"`{new_name}` was written to a new file, `{}`.",
display(path)
),
None => format!(
"`{new_name}` was written below its neighbour in `{}`: this editor did not say it can create files, so lucisv did not make one.",
display(file)
),
});
out.push(format!(
"lucisv gave `{new_name}` {} and {} from the names the selection reads and drives; check the directions before you rely on them.",
count(self.ports.len(), "port"),
count(self.params.len(), "parameter"),
));
if !self.imports.is_empty() {
out.push(format!(
"`{new_name}` imports {}, which the selection needed.",
self.imports.iter().map(|path| format!("`{path}`")).collect::<Vec<_>>().join(", ")
));
}
out
}
}
/// The direction one crossing signal's port gets, or the sentence saying why
/// lucisv will not decide.
fn direction(name: &str, sides: flow::Sides) -> Result<&'static str, String> {
if sides.inside_unknown {
return Err(format!(
"the selection passes `{name}` to a task or function, and only that routine's declaration says whether it is an argument in or out; lucisv will not guess a port direction from it."
));
}
if !sides.inside_write {
return Ok("input");
}
if sides.outside_write {
return Err(format!("`{name}` is driven on both sides of the selection."));
}
if sides.outside_unknown {
return Err(format!(
"the selection drives `{name}`, and something outside it passes the same name to a task or function, which may drive it too; lucisv will not make it an output over that."
));
}
Ok("output")
}
/// One identifier written in a header lucisv is about to move: a parameter it
/// has to carry across too, a keyword or a package name it can ignore, or a
/// declaration of `M`'s that a header in another module could not name.
fn depends(
declared: &HashMap<&str, SymbolKind>,
module: &str,
owner: &str,
word: &str,
wanted: &mut Vec<String>,
) -> Result<(), String> {
match declared.get(word) {
// A keyword (`logic`, `int`), a system function, or a name that comes
// from somewhere `visible` and `reachable` judge on their own terms.
None => Ok(()),
Some(SymbolKind::Param | SymbolKind::LocalParam) => {
wanted.push(word.to_string());
Ok(())
}
Some(_) => Err(header_names(module, owner, word)),
}
}
/// Every name the module's own scope declares, with its kind — what a
/// parameter default is checked against.
fn declarations<'s>(semantics: &'s Semantics, region: &Region<'_>) -> HashMap<&'s str, SymbolKind> {
semantics
.symbols()
.iter()
.filter(|symbol| inside_module(region, symbol.name_span))
.map(|symbol| (symbol.name.as_str(), symbol.kind))
.collect()
}
/// Where the module declares `name`, for ordering a header the way the source
/// orders its declarations.
fn span_of(semantics: &Semantics, region: &Region<'_>, name: &str) -> TextRange {
semantics
.symbols()
.iter()
.find(|symbol| symbol.name == name && inside_module(region, symbol.name_span))
.map_or(TextRange::empty(0), |symbol| symbol.name_span)
}
/// Every name the new module has to be able to resolve for itself: the names
/// the selection writes down, plus the type names its own header will carry.
///
/// A header type is matched by the *text* the declaration wrote — the port's
/// prefix is that text — so a `word_t` in a port list is the same reference the
/// import judgement asks about, and not a second reading of it.
fn needed<'s>(
text: &str,
semantics: &'s Semantics,
flow: &flow::Flow,
ports: &[(TextRange, Port)],
params: &[(TextRange, Param)],
) -> Vec<&'s vlog_semantic::Reference> {
let mut out: Vec<&vlog_semantic::Reference> =
flow.inside.iter().filter_map(|n| semantics.references().get(*n)).collect();
let header: Vec<&str> = ports
.iter()
.map(|(_, port)| port.prefix.as_str())
.chain(params.iter().map(|(_, param)| param.prefix.as_str()))
.collect();
for reference in semantics.references() {
let written = slice(text, reference.name_span);
if written.is_empty() {
continue;
}
if header.iter().any(|prefix| prefix.split_whitespace().any(|word| word == written)) {
out.push(reference);
}
}
out
}
/// The `import` paths the new module gets: the ones written in `M` that one of
/// the names it needs could have come through.
fn imports(
semantics: &Semantics,
region: &Region<'_>,
packages: &[(String, TextRange)],
needed: &[&vlog_semantic::Reference],
) -> Vec<String> {
let Some(scope) = semantics
.symbol_at(region.module.name_span.start)
.and_then(|id| semantics.symbol(id))
.and_then(|symbol| symbol.child_scope)
.and_then(|id| semantics.scope(id))
else {
return Vec::new();
};
let mut out = Vec::new();
for import in &scope.imports {
let path = import.path();
if out.contains(&path) {
continue;
}
if needed.iter().any(|r| supplied_by(semantics, packages, import, r)) {
out.push(path);
}
}
out
}
/// Whether a use of a name could have come through an import of `package`.
///
/// Two shapes, because the binder answers them differently. A package
/// **another file** declares leaves an [`Resolution::ExternalCandidate`] whose
/// `paths` name it; a package **this file** declares is resolved on the spot,
/// and what says so is that the declaration sits inside that package's own
/// item span.
fn supplied_by(
semantics: &Semantics,
packages: &[(String, TextRange)],
import: &vlog_semantic::Import,
reference: &vlog_semantic::Reference,
) -> bool {
if !import.supplies(&reference.name) {
return false;
}
let package = import.package.as_str();
match &reference.resolution {
// The binder writes the import paths it walked into `paths`, in the
// spelling the source wrote them (`p::*`, `p::w_t`) — so the question
// is whether this very import is one of them, not whether some path
// happens to end in the name.
Resolution::ExternalCandidate { paths, .. }
| Resolution::InheritedCandidate { paths, .. } => {
paths.iter().any(|path| *path == import.path())
}
Resolution::Resolved(symbol) => semantics
.symbol(*symbol)
.and_then(|symbol| package_of(packages, symbol.name_span))
.is_some_and(|declared_in| declared_in == package),
Resolution::NotFound => false,
}
}
/// Every name the new module needs has to be one a file of its own can see: a
/// declaration of `M`'s own (which becomes a port or a parameter), a unit of
/// the design (a module, an interface, a package), or a member of a package.
///
/// What this refuses is the rest — a `typedef`, a `localparam` or a class
/// written at the **file scope** of `M`'s file, which is a compilation-unit
/// declaration and reaches exactly the files that were compiled with it. It
/// runs over the names the new module writes down *and* the type names of its
/// own header, so a port typed with a file-scope `typedef` is refused as
/// squarely as a body reference to one.
fn visible(
text: &str,
semantics: &Semantics,
region: &Region<'_>,
packages: &[(String, TextRange)],
needed: &[&vlog_semantic::Reference],
module: &str,
new_file: bool,
) -> Result<(), String> {
if !new_file {
return Ok(());
}
for reference in needed {
let Resolution::Resolved(id) = reference.resolution else { continue };
let Some(symbol) = semantics.symbol(id) else { continue };
if inside_module(region, symbol.name_span) {
continue;
}
if package_of(packages, symbol.name_span).is_some() {
continue;
}
if matches!(symbol.kind, SymbolKind::Module | SymbolKind::Interface | SymbolKind::Package) {
continue;
}
// A field of a struct and a signal of an interface each have a
// declaration of their own, and naming it is not what the user needs
// to read: what crosses the boundary is `s` or `bus`, and `f` is a
// name of *its* type. So the head goes first when there is one.
return Err(match access_head(text, reference.name_span) {
Some(head) => outside_module_member(head, &symbol.name, module),
None => outside_module(&symbol.name, module),
});
}
Ok(())
}
/// The head of a member access, if the reference is one: `s` in `s.f`, `bus`
/// in `bus.data`, and `u` in `u.v.w`.
///
/// Read from the text rather than from the tree because that is where the
/// question is cheap and exact: a reference's own span is the field, and what
/// precedes it — a `.` and an identifier — is the thing the field belongs to.
fn access_head(text: &str, span: TextRange) -> Option<&str> {
let (mut at, mut head) = dotted_word_before(text, span.start as usize)?;
while let Some((start, word)) = dotted_word_before(text, at) {
at = start;
head = word;
}
Some(head)
}
/// The identifier written immediately before `at` and a `.`, with where it
/// starts: `("s", …)` for `s.` and nothing at all for anything else.
fn dotted_word_before(text: &str, at: usize) -> Option<(usize, &str)> {
let rest = text.get(..at)?.trim_end().strip_suffix('.')?.trim_end();
let start = rest
.char_indices()
.rev()
.take_while(|(_, c)| c.is_alphanumeric() || *c == '_' || *c == '$')
.last()
.map(|(i, _)| i)?;
let word = rest.get(start..)?;
match word.starts_with(|c: char| c.is_ascii_digit()) {
true => None,
false => Some((start, word)),
}
}
/// A name a `package` of this file declares reaches the new module only if the
/// new module can spell it: either every use writes the package out
/// (`w_pkg::word_t`), or `M` imports it and lucisv copied that import across.
fn reachable(
text: &str,
needed: &[&vlog_semantic::Reference],
from_package: &[(String, String)],
imports: &[String],
) -> Result<(), String> {
for (package, name) in from_package {
let unqualified = needed
.iter()
.filter(|reference| reference.name == *name)
.any(|reference| !qualified(text, reference.name_span));
if !unqualified {
continue;
}
let imported = imports
.iter()
.any(|path| path == &format!("{package}::*") || path == &format!("{package}::{name}"));
if !imported {
return Err(format!(
"the selection uses `{name}`, which `{package}` declares, without writing `{package}::` in front of it and without an `import` lucisv could carry across; write the package out, or import it where the new module can see it."
));
}
}
Ok(())
}
/// Whether a name is written with its package in front of it: `w_pkg::word_t`.
fn qualified(text: &str, span: TextRange) -> bool {
text.get(..span.start as usize).is_some_and(|head| head.trim_end().ends_with("::"))
}
/// The `package` of this file whose body holds `span`, if any.
fn package_of(packages: &[(String, TextRange)], span: TextRange) -> Option<&str> {
packages
.iter()
.find(|(_, at)| at.start <= span.start && span.end <= at.end)
.map(|(name, _)| name.as_str())
}
/// Every `package` this file declares, with the bytes it occupies.
pub(super) fn packages(tree: &SourceFile) -> Vec<(String, TextRange)> {
tree.items
.iter()
.filter_map(|item| match &item.kind {
ItemKind::Package { name, .. } => Some((name.clone(), item.span)),
_ => None,
})
.collect()
}
+665
View File
@@ -0,0 +1,665 @@
//! Which names cross the selection's boundary, and in which direction.
//!
//! The whole of "what ports does the new module need" is here, and it is one
//! question asked of two tables: `vlog_semantic`'s references say *which
//! declaration* each name in the module means, and the tree says whether each
//! use of it is a **write** or a **read**. A name declared outside the
//! selection and used inside it becomes a port — `input` when the selection
//! only reads it, `output` when the selection writes it.
//!
//! **A name is written by the selection when, and only when, it is:** the
//! left-hand side of a continuous assignment; the left-hand side of a
//! blocking or non-blocking assignment (or of a `for` initialiser or step, or
//! the target of a `++`/`--`) anywhere inside an `always` block; the target of
//! a `force`, a `release` or a `deassign`; the target of a `-> ev`; the
//! declarator's own initialiser; or connected to an `output` or `inout` port
//! of an instantiated module — which is a fact only that module's own
//! declaration holds, so it is looked up through the workspace index and the
//! extraction is **refused** when the index cannot answer. Everything else is
//! a read. Two positions are neither, and both refuse rather than guess: an
//! argument of a task or function call, whose direction only the routine's
//! prototype knows, and a positional or `.*` connection, which names no port
//! at all.
//!
//! Nothing here edits. It answers, or it refuses with a sentence.
use std::collections::HashMap;
use vlog_parser::ast::{
Connections, Expr, ExprKind, ForStep, Instantiation, Item, ItemKind, ListElem, Stmt, StmtKind,
};
use vlog_parser::span::TextRange;
use vlog_semantic::{Reference, Resolution, Semantics, Surface, SymbolId, SymbolKind};
use crate::instantiate::{instantiation_plan, module_definition};
use crate::rename::Scope;
use super::region::Region;
/// What one use of a name is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Use {
Read,
Write,
/// A position whose direction lucisv cannot know: a call argument, a
/// connection to a port it could not read.
Unknown,
}
/// Everything done to one declaration, on each side of the boundary.
#[derive(Debug, Default, Clone, Copy)]
pub(super) struct Sides {
pub(super) inside_read: bool,
pub(super) inside_write: bool,
pub(super) inside_unknown: bool,
pub(super) outside_read: bool,
pub(super) outside_write: bool,
pub(super) outside_unknown: bool,
}
impl Sides {
pub(super) fn used_inside(&self) -> bool {
self.inside_read || self.inside_write || self.inside_unknown
}
pub(super) fn used_outside(&self) -> bool {
self.outside_read || self.outside_write || self.outside_unknown
}
}
/// The boundary table: what each declaration the module holds has done to it
/// on each side of the selection, and which of the module's own references sit
/// inside it.
pub(super) struct Flow {
sides: HashMap<SymbolId, Sides>,
/// The references written inside the region, in source order.
pub(super) inside: Vec<usize>,
}
impl Flow {
pub(super) fn sides(&self, symbol: SymbolId) -> Sides {
self.sides.get(&symbol).copied().unwrap_or_default()
}
}
/// Classify every use of every name in the module, on both sides of the
/// selection.
pub(super) fn read(
scope: &Scope<'_>,
text: &str,
semantics: &Semantics,
region: &Region<'_>,
) -> Result<Flow, String> {
let mut marks = Marks::default();
marks.items(scope, region, &region.module.items)?;
// Every reference in the file, placed on its side of the boundary and
// given the direction the tree marked its span with.
let mut sides: HashMap<SymbolId, Sides> = HashMap::new();
let mut inside = Vec::new();
for (n, reference) in semantics.references().iter().enumerate() {
let span = reference.name_span;
let within = region.span.start <= span.start && span.end <= region.span.end;
if within {
inside.push(n);
}
let Resolution::Resolved(symbol) = reference.resolution else { continue };
let use_ = marks.use_of(span);
let entry = sides.entry(symbol).or_default();
match (within, use_) {
(true, Use::Read) => entry.inside_read = true,
(true, Use::Write) => entry.inside_write = true,
(true, Use::Unknown) => entry.inside_unknown = true,
(false, Use::Read) => entry.outside_read = true,
(false, Use::Write) => entry.outside_write = true,
(false, Use::Unknown) => entry.outside_unknown = true,
}
}
// A declarator's own initialiser writes the declaration rather than
// referring to it, so it is not in the reference table at all.
for (span, within) in marks.initialised.drain(..) {
let Some(symbol) = semantics.symbol_at(span.start) else { continue };
let entry = sides.entry(symbol).or_default();
match within {
true => entry.inside_write = true,
false => entry.outside_write = true,
}
}
let _ = text;
Ok(Flow { sides, inside })
}
/// Whether any reference inside the region is a **hierarchical** one whose
/// head instance the region does not itself declare — `u_x.sig` reaching out
/// of the selection, which lucisv will not move across a module boundary.
///
/// The §49 surface is what says a tail is hierarchical at all
/// ([`Surface::Hierarchical`] is recorded exactly when the head resolved to an
/// instance); the head is then the nearest reference before it that resolved
/// to an [`SymbolKind::Instance`] with nothing but the dots of the path
/// between them.
pub(super) fn hierarchical_escape(
text: &str,
semantics: &Semantics,
region: &Region<'_>,
) -> Option<String> {
let refs = semantics.references();
for reference in refs {
let span = reference.name_span;
if span.start < region.span.start || region.span.end < span.end {
continue;
}
let Resolution::ExternalCandidate { surface: Surface::Hierarchical, .. } =
&reference.resolution
else {
continue;
};
match head_of(text, semantics, refs, reference) {
// The instance the path starts at moves with the selection, so
// the path is not crossing anything. It is the *declaration* that
// has to move, not the mention of it.
Some(head) if declared_inside(semantics, region, head) => continue,
Some(head) => return Some(format!("{}.{}", head.name, reference.name)),
None => return Some(format!("\u{2026}.{}", reference.name)),
}
}
None
}
/// The instance a hierarchical tail hangs off: the nearest earlier reference
/// that resolved to an instance, with only a dotted path between the two.
fn head_of<'r>(
text: &str,
semantics: &Semantics,
refs: &'r [Reference],
tail: &Reference,
) -> Option<&'r Reference> {
let mut best: Option<&Reference> = None;
for candidate in refs {
if candidate.name_span.end > tail.name_span.start {
continue;
}
let is_instance = candidate
.resolved()
.and_then(|id| semantics.symbol(id))
.is_some_and(|symbol| symbol.kind == SymbolKind::Instance);
if !is_instance {
continue;
}
if best.is_none_or(|found| candidate.name_span.end > found.name_span.end) {
best = Some(candidate);
}
}
let head = best?;
let between = text.get(head.name_span.end as usize..tail.name_span.start as usize)?;
// A dotted path, index selects included: `u_a.u_b`, `u_q[0].sig`.
let dotted = between
.chars()
.all(|c| c == '.' || c == '[' || c == ']' || c == ':' || c.is_alphanumeric() || c == '_');
dotted.then_some(head)
}
fn inside(region: &Region<'_>, span: TextRange) -> bool {
region.span.start <= span.start && span.end <= region.span.end
}
/// Whether the declaration a reference names is written inside the region.
fn declared_inside(semantics: &Semantics, region: &Region<'_>, reference: &Reference) -> bool {
reference
.resolved()
.and_then(|id| semantics.symbol(id))
.is_some_and(|symbol| inside(region, symbol.name_span))
}
// ----------------------------------------------------------------------
// marking the tree
// ----------------------------------------------------------------------
/// Where the tree says a name is written, and where it says lucisv cannot
/// know. Both are sets of *name spans*, which is what lets the reference table
/// be read straight off them.
#[derive(Default)]
struct Marks {
writes: Vec<TextRange>,
unknown: Vec<TextRange>,
/// `(declared name's span, inside the region)` for every declarator whose
/// own initialiser drives it.
initialised: Vec<(TextRange, bool)>,
}
impl Marks {
fn use_of(&self, span: TextRange) -> Use {
if self.unknown.iter().any(|marked| covers(*marked, span)) {
return Use::Unknown;
}
match self.writes.contains(&span) {
true => Use::Write,
false => Use::Read,
}
}
fn items(
&mut self,
scope: &Scope<'_>,
region: &Region<'_>,
items: &[Item],
) -> Result<(), String> {
for item in items {
self.item(scope, region, item)?;
}
Ok(())
}
fn item(&mut self, scope: &Scope<'_>, region: &Region<'_>, item: &Item) -> Result<(), String> {
match &item.kind {
ItemKind::DataDecl(decl) => {
for declarator in &decl.declarators {
if declarator.init.is_some() {
self.initialised
.push((declarator.name_span, inside(region, declarator.name_span)));
}
}
}
ItemKind::ContAssign(assign) => {
for pair in &assign.assigns {
self.write(&pair.lhs);
}
}
ItemKind::Always { stmt, .. } => self.body(stmt),
ItemKind::Initial(stmt) | ItemKind::Final(stmt) => self.body(stmt),
ItemKind::Function(decl) => {
for stmt in &decl.stmts {
self.body(stmt);
}
}
ItemKind::Task(decl) => {
for stmt in &decl.stmts {
self.body(stmt);
}
}
ItemKind::Instantiation(inst) => self.instantiation(scope, region, inst)?,
ItemKind::GateInstantiation(gates) => {
for instance in &gates.instances {
for arg in &instance.args {
self.unknown.push(arg.span);
}
}
}
ItemKind::GenerateRegion { items, .. } => self.items(scope, region, items)?,
ItemKind::GenBlock(block) => self.items(scope, region, &block.items)?,
ItemKind::GenIf(gen_if) => {
self.items(scope, region, &gen_if.then.items)?;
let mut els = gen_if.els.as_deref();
while let Some(branch) = els {
match branch {
vlog_parser::ast::GenElse::If(_, nested) => {
self.items(scope, region, &nested.then.items)?;
els = nested.els.as_deref();
}
vlog_parser::ast::GenElse::Block(block) => {
self.items(scope, region, &block.items)?;
els = None;
}
}
}
}
ItemKind::GenFor(gen_for) => self.items(scope, region, &gen_for.body.items)?,
ItemKind::GenCase(gen_case) => {
for case_item in &gen_case.items {
self.items(scope, region, &case_item.body.items)?;
}
}
_ => {}
}
Ok(())
}
/// Every write inside one procedural block, at any statement depth.
fn body(&mut self, stmt: &Stmt) {
walk(stmt, &mut |stmt| match &stmt.kind {
StmtKind::Assign { lhs, .. } | StmtKind::ForceRelease { lhs, .. } => self.write(lhs),
StmtKind::EventTrigger(t) => self.write(&t.expr),
StmtKind::For { init, step, .. } => {
for entry in init {
self.write(&entry.assign.lhs);
}
for entry in step {
match entry {
ForStep::Assign(assign) => self.write(&assign.lhs),
ForStep::Expr(expr) => match increment_target(expr) {
Some(target) => self.write(target),
None => self.unknown.push(expr.span),
},
}
}
}
// `x++;` is a write; every other expression statement is a call,
// whose arguments may be `output` arguments.
StmtKind::ExprStmt(expr) => match increment_target(expr) {
Some(target) => self.write(target),
None => self.unknown.push(expr.span),
},
_ => {}
});
// A call written anywhere in the block — in a condition, on the
// right-hand side of an assignment — passes arguments whose direction
// only the routine's own prototype knows.
walk(stmt, &mut |stmt| stmt_exprs(stmt, &mut |expr| self.calls(expr)));
}
/// An instantiation's connections, whose direction the instantiated
/// module's declaration holds.
fn instantiation(
&mut self,
scope: &Scope<'_>,
region: &Region<'_>,
inst: &Instantiation,
) -> Result<(), String> {
let touches = inst.instances.iter().any(|instance| inside(region, instance.name_span));
for instance in &inst.instances {
match &instance.conns {
Connections::Ordered(conns) => {
if touches {
return Err(positional(&inst.module, &instance.name));
}
for conn in conns {
self.unknown.push(match conn {
ListElem::Ok(conn) => conn.span,
ListElem::Error(raw) => raw.span,
});
}
}
Connections::Named(conns) => {
let ports = match touches {
true => Some(ports_of(scope, &inst.module)?),
false => None,
};
for conn in conns {
let conn = match conn {
ListElem::Ok(conn) => conn,
ListElem::Error(raw) => {
if touches {
return Err(unreadable(&inst.module, &instance.name));
}
self.unknown.push(raw.span);
continue;
}
};
let Some(ports) = ports.as_deref() else {
self.unknown.push(conn.span);
continue;
};
if conn.name == "*" {
return Err(wildcard(&inst.module, &instance.name));
}
// `.p` with no expression connects the same-named
// signal, whose own name is not written down here;
// the connection's port name is the signal's name.
let Some(port) = ports.iter().find(|(name, _)| *name == conn.name) else {
return Err(no_such_port(&inst.module, &conn.name));
};
let Some(expr) = &conn.expr else {
return Err(implicit(&inst.module, &instance.name, &conn.name));
};
match port.1.as_str() {
"output" | "inout" => self.write(expr),
"input" => {}
_ => return Err(no_direction(&inst.module, &conn.name)),
}
}
}
}
}
Ok(())
}
/// Every argument of every call in an expression, marked unknown.
fn calls(&mut self, expr: &Expr) {
walk_expr(expr, &mut |expr| {
if let ExprKind::Call { args, .. } = &expr.kind {
for arg in args {
self.unknown.push(arg.span);
}
}
});
}
/// Records every name an assignment's left-hand side writes.
fn write(&mut self, lhs: &Expr) {
lvalue_targets(lhs, &mut self.writes);
}
}
/// Whether `outer` covers `inner` entirely.
fn covers(outer: TextRange, inner: TextRange) -> bool {
outer.start <= inner.start && inner.end <= outer.end
}
/// The names one left-hand side writes. `a.b[3] = x` writes `a`, which is
/// what resolves.
fn lvalue_targets(expr: &Expr, out: &mut Vec<TextRange>) {
match &expr.kind {
ExprKind::Ident(_) => out.push(expr.span),
ExprKind::Paren { inner, .. } => lvalue_targets(inner, out),
ExprKind::Cast { expr, .. } => lvalue_targets(expr, out),
ExprKind::Index { base, .. } | ExprKind::Range { base, .. } => lvalue_targets(base, out),
ExprKind::Member { base, .. } => lvalue_targets(base, out),
ExprKind::Concat(items) | ExprKind::Stream { inner: items, .. } => {
for item in items {
lvalue_targets(&item.expr, out);
}
}
_ => {}
}
}
/// The target of `x++` / `x--` / `++x`, which is a write dressed as an
/// expression.
fn increment_target(expr: &Expr) -> Option<&Expr> {
match &expr.kind {
ExprKind::Postfix { expr, op, .. } | ExprKind::Unary { expr, op, .. }
if op == "++" || op == "--" =>
{
Some(expr)
}
_ => None,
}
}
/// The ports of an instantiated module: name and direction, read from the
/// file the workspace index says declares it.
fn ports_of(scope: &Scope<'_>, module: &str) -> Result<Vec<(String, String)>, String> {
let path =
module_definition(scope.index(), module).map_err(|_| unknown_module(module))?.to_path_buf();
let Some(text) = scope.index_of(&path).and_then(|i| scope.text(i)) else {
return Err(unknown_module(module));
};
let plan = instantiation_plan(module, text, None).map_err(|_| unknown_module(module))?;
Ok(plan.ports.into_iter().map(|port| (port.name, port.dir)).collect())
}
// ----------------------------------------------------------------------
// walks
// ----------------------------------------------------------------------
fn walk(stmt: &Stmt, f: &mut dyn FnMut(&Stmt)) {
f(stmt);
match &stmt.kind {
StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => {
for stmt in stmts {
walk(stmt, f);
}
}
StmtKind::If { then, els, .. } => {
walk(then, f);
if let Some(els) = els {
walk(els, f);
}
}
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
for item in items {
walk(&item.stmt, f);
}
}
StmtKind::Labeled { stmt, .. } => walk(stmt, f),
StmtKind::For { body, .. }
| StmtKind::While { body, .. }
| StmtKind::DoWhile { body, .. }
| StmtKind::Repeat { body, .. }
| StmtKind::Forever { body }
| StmtKind::Foreach { body, .. } => walk(body, f),
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
walk(inner, f)
}
StmtKind::Assert { then, els, .. } => {
if let Some(then) = then {
walk(then, f);
}
if let Some(els) = els {
walk(els, f);
}
}
_ => {}
}
}
/// The expressions one statement writes directly — not its children's.
fn stmt_exprs(stmt: &Stmt, f: &mut dyn FnMut(&Expr)) {
match &stmt.kind {
StmtKind::Assign { lhs, rhs, .. } => {
f(lhs);
f(rhs);
}
StmtKind::If { cond, .. } | StmtKind::While { cond, .. } | StmtKind::Wait { cond, .. } => {
f(cond)
}
StmtKind::DoWhile { cond, .. } => f(cond),
StmtKind::Case { expr, items, .. } => {
f(expr);
for item in items {
for label in &item.labels {
f(&label.expr);
}
}
}
StmtKind::Repeat { count, .. } => f(count),
StmtKind::ExprStmt(expr) => f(expr),
StmtKind::EventTrigger(t) => f(&t.expr),
StmtKind::ForceRelease { lhs, rhs, .. } => {
f(lhs);
if let Some(rhs) = rhs {
f(rhs);
}
}
StmtKind::For { init, cond, step, .. } => {
for entry in init {
f(&entry.assign.rhs);
}
if let Some(cond) = cond {
f(cond);
}
for entry in step {
match entry {
ForStep::Assign(assign) => f(&assign.rhs),
ForStep::Expr(expr) => f(expr),
}
}
}
StmtKind::Return { expr: Some(expr), .. } => f(expr),
StmtKind::Assert { cond, .. } => f(cond),
_ => {}
}
}
fn walk_expr(expr: &Expr, f: &mut dyn FnMut(&Expr)) {
f(expr);
match &expr.kind {
ExprKind::Unary { expr, .. } | ExprKind::Postfix { expr, .. } => walk_expr(expr, f),
ExprKind::Binary { lhs, rhs, .. } => {
walk_expr(lhs, f);
walk_expr(rhs, f);
}
ExprKind::Ternary { cond, then, els, .. } => {
walk_expr(cond, f);
walk_expr(then, f);
walk_expr(els, f);
}
ExprKind::Call { callee, args, .. } => {
walk_expr(callee, f);
for arg in args {
walk_expr(&arg.expr, f);
}
}
ExprKind::Index { base, index, .. } => {
walk_expr(base, f);
walk_expr(index, f);
}
ExprKind::Range { base, msb, lsb, .. } => {
walk_expr(base, f);
walk_expr(msb, f);
walk_expr(lsb, f);
}
ExprKind::Member { base, .. } | ExprKind::Scope { base, .. } => walk_expr(base, f),
ExprKind::Concat(items) | ExprKind::Stream { inner: items, .. } => {
for item in items {
walk_expr(&item.expr, f);
}
}
ExprKind::Repl { count, inner, .. } => {
walk_expr(count, f);
for item in inner {
walk_expr(&item.expr, f);
}
}
ExprKind::Paren { inner, .. } => walk_expr(inner, f),
ExprKind::Cast { expr, .. } => walk_expr(expr, f),
ExprKind::New(inner) => walk_expr(inner, f),
_ => {}
}
}
// ----------------------------------------------------------------------
// sentences
// ----------------------------------------------------------------------
fn positional(module: &str, instance: &str) -> String {
format!(
"`{instance}` connects `{module}` by position, so lucisv cannot tell which of its connections are outputs; convert it to named connections first."
)
}
fn wildcard(module: &str, instance: &str) -> String {
format!(
"`{instance}` connects `{module}` with `.*`, which names no signals; expand the `.*` first (lucisv offers that as its own refactoring)."
)
}
fn implicit(module: &str, instance: &str, port: &str) -> String {
format!(
"`{instance}` connects `{module}`'s `{port}` implicitly (`.{port}`), which names no expression for lucisv to move; write the signal out first."
)
}
fn unreadable(module: &str, instance: &str) -> String {
format!(
"lucisv could not read one of `{instance}`'s connections to `{module}`, so it cannot tell what the selection drives."
)
}
fn unknown_module(module: &str) -> String {
format!(
"the selection instantiates `{module}`, and lucisv has no single indexed declaration of it, so it cannot tell which of its connections are outputs."
)
}
fn no_such_port(module: &str, port: &str) -> String {
format!(
"the selection connects `.{port}`, which `{module}`'s declaration does not name, so lucisv cannot tell whether it is driven."
)
}
fn no_direction(module: &str, port: &str) -> String {
format!(
"`{module}` declares `{port}` without a direction, so lucisv cannot tell whether the selection drives it."
)
}
+514
View File
@@ -0,0 +1,514 @@
//! Extract a selection of whole module items into a module of its own.
//!
//! The user selects one or more contiguous items of a module `M` — an
//! `always` block, an `assign`, an instantiation, a declaration, a generate
//! construct — and names the module `N` they want them in. lucisv works out
//! `N`'s ports from the dataflow across the selection's boundary, writes `N`
//! into a file of its own beside `M`'s (or below `M`, for a client that cannot
//! create files), and replaces the selection with an instantiation of `N`
//! **rendered from `N`'s own text**, so the skeleton and the module can never
//! disagree about what `N`'s ports are.
//!
//! Three files, one question each:
//!
//! * `region` — *what does the selection cover?* The module, the run of whole
//! items, and the item kinds lucisv will not carry into another module.
//! * `flow` — *which names cross the boundary, and in which direction?* The
//! dataflow rule, and the two positions it refuses to guess at.
//! * `render` — *what does lucisv write?* A port's type as its declaration
//! spells it, the new module, and the instantiation.
//!
//! This file is the plan: the entry points, the classification of each
//! crossing name into a port, a parameter or a refusal, the edits, and the
//! verification. Everything is one [`check::verify_move`] over the whole edit,
//! which for a new file is the ordinary splice contract plus one deliberate
//! widening: the comments the selection carries are deleted in `M`'s file and
//! written in `N`'s, so the never-dropped ledger is kept over the pair rather
//! than over each file alone. See
//! `docs/features/extract-inline-module/README.md`.
mod boundary;
mod flow;
mod region;
mod render;
use std::path::{Path, PathBuf};
use vlog_parser::ast::{Item, ItemKind, SourceFile};
use vlog_parser::parse_source_tolerant;
use vlog_parser::span::TextRange;
use vlog_semantic::{analyze, SymbolKind};
use crate::rename::{display, Scope};
use crate::{check, RefactorEdit, TextEdit};
use boundary::Crossing;
use region::Region;
/// Where the extracted module is written.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Home {
/// A file `N.sv` beside `M`'s own — what a client that advertises
/// `workspace.workspaceEdit.documentChanges` with `CreateFile` support
/// gets, because only such a client can apply the creation.
NewFile,
/// Below `M`, in `M`'s own file — the fallback for every other client,
/// and for a caller that asked for it.
SameFile,
}
/// What the cheap gate found: the selection is in a module, and these are the
/// units whose files the engine needs read.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ExtractSite {
/// The module the selection is written in.
pub module: String,
/// The name the action proposes when the caller has none: `M_extracted`.
pub default_name: String,
/// Every unit whose declaration the engine will look up: the module
/// itself, the modules the selection instantiates, and the packages the
/// module imports.
pub units: Vec<String>,
}
/// Whether a selection is one lucisv could extract, and what it would need to
/// read to try.
///
/// **The cheap gate**: one parse of one buffer, no workspace and no I/O — the
/// bargain `port_action_modules` and `imported_packages` strike, and for the
/// same reason (a `textDocument/codeAction` arrives on every cursor move).
/// Empty exactly where [`extract_module`] would refuse for want of a module or
/// a whole item to move.
pub fn extract_site(text: &str, start: u32, end: u32) -> Option<ExtractSite> {
let (tree, diagnostics) = parse_source_tolerant(text);
if !diagnostics.is_empty() {
return None;
}
let region = Region::read(&tree, text, TextRange::new(start, end)).ok()?;
let module = region.module_name().to_string();
let mut units = vec![module.clone()];
for item in &region.items {
collect_instantiated(item, &mut units);
}
for import in &region.module.imports {
for path in &import.paths {
push(&mut units, path.pkg.text.clone());
}
}
for item in &region.module.items {
if let ItemKind::Import(paths) = &item.kind {
for path in paths {
push(&mut units, path.pkg.text.clone());
}
}
}
Some(ExtractSite { default_name: format!("{module}_extracted"), module, units })
}
/// The lightbulb's text, written here so every front end says the same thing.
pub fn extract_title() -> String {
"lucisv: extract selection into module…".to_string()
}
/// Extract the items `[start, end)` covers out of the module that holds them,
/// into a module called `new_name`.
pub fn extract_module(
files: &[(PathBuf, String)],
file: &Path,
start: u32,
end: u32,
new_name: &str,
home: Home,
) -> Result<RefactorEdit, String> {
plain_identifier(new_name)?;
// The new file joins the in-scope set as an *empty* file, so that every
// question below — the index, the analysis, the verification — is asked
// about it exactly the way it is asked about a file that was always there.
let mut sources: Vec<(PathBuf, String)> = files.to_vec();
let created = match home {
Home::SameFile => None,
Home::NewFile => {
let path = beside(file, new_name);
match sources.iter().find(|(held, _)| *held == path) {
Some((_, text)) if !text.trim().is_empty() => return Err(occupied(&path)),
Some(_) => {}
None => sources.push((path.clone(), String::new())),
}
Some(path)
}
};
let plan = Extraction::plan(&sources, file, start, end, new_name, created.clone())?;
Ok(RefactorEdit {
edits: plan.edits,
warnings: plan.warnings,
created: created.into_iter().collect(),
})
}
/// What the extraction produced, before it is dressed as a [`RefactorEdit`].
struct Extraction {
edits: Vec<(PathBuf, Vec<TextEdit>)>,
warnings: Vec<String>,
}
impl Extraction {
fn plan(
sources: &[(PathBuf, String)],
file: &Path,
start: u32,
end: u32,
new_name: &str,
created: Option<PathBuf>,
) -> Result<Extraction, String> {
let mut scope = Scope::build(sources);
let Some(here) = scope.index_of(file) else { return Err(not_in_scope(file)) };
let Some(text) = scope.text(here) else { return Err(not_in_scope(file)) };
let (tree, diagnostics) = parse_source_tolerant(text);
if let Some(problem) = diagnostics.first() {
return Err(format!(
"{} does not parse ({} at line {}), so lucisv will not extract from it.",
display(file),
problem.message,
problem.line
));
}
let region = Region::read(&tree, text, TextRange::new(start, end))?;
let module = region.module_name().to_string();
declared_once(&scope, &module)?;
undeclared(&scope, new_name)?;
if new_name == module {
return Err(format!("`{module}` is already the name of the module you are in."));
}
if created.is_some() {
no_directive(&tree, text, &region)?;
}
let semantics = analyze(&tree, text);
if let Some(path) = flow::hierarchical_escape(text, &semantics, &region) {
return Err(hierarchical(&path));
}
let flow = flow::read(&scope, text, &semantics, &region)?;
let packages = boundary::packages(&tree);
let crossing =
Crossing::read(text, &semantics, &region, &flow, &packages, created.is_some())?;
// The new module, then the instantiation read back out of it.
let body = format!("{}{}", region.indent, slice(text, region.span));
let module_text = render::new_module(
new_name,
&crossing.imports,
&crossing.params,
&crossing.ports,
&ensure_newline(&body),
);
let instance = render::instantiation(new_name, &module_text, &region.indent)?;
let mut edits: Vec<(usize, Vec<TextEdit>)> = Vec::new();
// What the verifier is allowed to let travel, and between which bytes:
// `M`'s file loses exactly the pieces inside the region, and the new
// file — named with an empty range, because it has no region of its
// own — is the only place they may land.
let mut moving: Vec<check::Moving> = Vec::new();
let replace = TextEdit { range: region.span, new_text: instance };
match &created {
Some(path) => {
let Some(there) = scope.index_of(path) else { return Err(not_in_scope(path)) };
edits.push((here, vec![replace]));
edits.push((
there,
vec![TextEdit { range: TextRange::empty(0), new_text: module_text.clone() }],
));
moving = vec![
check::Moving::source(here, region.span),
check::Moving::destination(there),
];
}
None => {
let append = TextEdit {
range: TextRange::empty(region.module_span.end),
new_text: format!("\n\n{module_text}"),
};
edits.push((here, vec![replace, append]));
}
}
edits.sort_by_key(|(i, _)| *i);
moving.sort_by_key(|moving| moving.file);
let what = format!("extracting `{new_name}` out of `{module}`");
check::verify_move(&mut scope, &edits, &[&module, new_name], &what, &moving)?;
confirm(&scope, &edits, new_name, &crossing, &what)?;
let mut out: Vec<(PathBuf, Vec<TextEdit>)> = Vec::new();
for (i, file_edits) in edits {
let Some(path) = scope.path(i) else { return Err(lost(&what)) };
out.push((path.to_path_buf(), file_edits));
}
out.sort_by(|a, b| a.0.cmp(&b.0));
Ok(Extraction { edits: out, warnings: crossing.warnings(new_name, &created, file) })
}
}
/// Read the edited text back and require the new module to declare exactly the
/// ports and parameters the plan promised.
///
/// `verify_move` proves the edit is lexically and semantically honest; nothing
/// in it proves the header lucisv wrote is the header it meant to write.
fn confirm(
scope: &Scope<'_>,
edits: &[(usize, Vec<TextEdit>)],
new_name: &str,
crossing: &Crossing,
what: &str,
) -> Result<(), String> {
for (i, file_edits) in edits {
let (Some(text), Some(path)) = (scope.text(*i), scope.path(*i)) else {
return Err(lost(what));
};
let edited = crate::apply(text, file_edits);
let Ok(plan) = crate::instantiate::instantiation_plan(new_name, &edited, None) else {
continue;
};
let ports: Vec<&str> = plan.ports.iter().map(|port| port.name.as_str()).collect();
let params: Vec<&str> = plan.params.iter().map(|param| param.name.as_str()).collect();
let wanted_ports: Vec<&str> = crossing.ports.iter().map(|p| p.name.as_str()).collect();
let wanted_params: Vec<&str> = crossing.params.iter().map(|p| p.name.as_str()).collect();
if ports != wanted_ports || params != wanted_params {
return Err(format!(
"{what} would not leave `{new_name}` with the header lucisv intended in {}; no edits were made.",
display(path)
));
}
return Ok(());
}
Err(lost(what))
}
// ----------------------------------------------------------------------
// odds and ends
// ----------------------------------------------------------------------
fn inside(region: &Region<'_>, span: TextRange) -> bool {
region.span.start <= span.start && span.end <= region.span.end
}
fn inside_module(region: &Region<'_>, span: TextRange) -> bool {
region.module_span.start <= span.start && span.end <= region.module_span.end
}
fn slice(text: &str, span: TextRange) -> &str {
text.get(span.start as usize..span.end as usize).unwrap_or("")
}
fn ensure_newline(text: &str) -> String {
match text.ends_with('\n') {
true => text.to_string(),
false => format!("{text}\n"),
}
}
fn push(out: &mut Vec<String>, name: String) {
if !out.contains(&name) {
out.push(name);
}
}
/// Every module an item instantiates, nested generate constructs included.
fn collect_instantiated(item: &Item, out: &mut Vec<String>) {
match &item.kind {
ItemKind::Instantiation(inst) => push(out, inst.module.clone()),
ItemKind::GenerateRegion { items, .. } => {
for item in items {
collect_instantiated(item, out);
}
}
ItemKind::GenBlock(block) => {
for item in &block.items {
collect_instantiated(item, out);
}
}
ItemKind::GenIf(gen_if) => {
for item in &gen_if.then.items {
collect_instantiated(item, out);
}
let mut els = gen_if.els.as_deref();
while let Some(branch) = els {
match branch {
vlog_parser::ast::GenElse::If(_, nested) => {
for item in &nested.then.items {
collect_instantiated(item, out);
}
els = nested.els.as_deref();
}
vlog_parser::ast::GenElse::Block(block) => {
for item in &block.items {
collect_instantiated(item, out);
}
els = None;
}
}
}
}
ItemKind::GenFor(gen_for) => {
for item in &gen_for.body.items {
collect_instantiated(item, out);
}
}
ItemKind::GenCase(gen_case) => {
for case_item in &gen_case.items {
for item in &case_item.body.items {
collect_instantiated(item, out);
}
}
}
_ => {}
}
}
/// The file the new module goes in: `N.sv`, beside the file it came out of.
fn beside(file: &Path, new_name: &str) -> PathBuf {
let parent = file.parent().map_or_else(PathBuf::new, Path::to_path_buf);
parent.join(format!("{new_name}.sv"))
}
/// A module name lucisv will write into a file name and a header: a plain
/// identifier, never an escaped one.
fn plain_identifier(name: &str) -> Result<(), String> {
let mut chars = name.chars();
let head = chars.next().filter(|c| c.is_ascii_alphabetic() || *c == '_');
let tail = chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$');
match head.is_some() && tail {
true => Ok(()),
false => Err(format!(
"`{name}` is not a plain SystemVerilog identifier, and lucisv will not name a module — or a file — with anything else."
)),
}
}
/// The module the selection is in must be declared exactly once in the
/// workspace: an extraction rewrites *this* `M`, and two of them means lucisv
/// does not know whose ports the selection reads.
fn declared_once(scope: &Scope<'_>, module: &str) -> Result<(), String> {
let defs = scope.index().units(module).iter().filter(|def| def.kind.is_instantiable()).count();
match defs {
1 => Ok(()),
0 => Err(format!("lucisv indexes no module named `{module}`.")),
_ => Err(format!(
"`{module}` is declared in more than one indexed file, so lucisv cannot tell which one the selection belongs to."
)),
}
}
fn undeclared(scope: &Scope<'_>, name: &str) -> Result<(), String> {
match scope.index().units(name).is_empty() {
true => Ok(()),
false => {
Err(format!("the workspace already declares `{name}`; pick a name nothing else uses."))
}
}
}
/// A `timescale` or a `default_nettype` in force where `M` is written does not
/// follow the items into a file of their own, and silently changing either one
/// changes what the design does.
fn no_directive(tree: &SourceFile, text: &str, region: &Region<'_>) -> Result<(), String> {
for item in &tree.items {
let ItemKind::Directive(raw) = &item.kind else { continue };
if item.span.start > region.module_span.end {
continue;
}
let word = raw.text.split_whitespace().next().unwrap_or("");
if word == "`timescale" || word == "`default_nettype" || word == "`resetall" {
return Err(format!(
"`{}` writes `{word}` before the module the selection is in, and a new file would not inherit it; extract into the same file, or move the directive into an include both files use.",
first_line(text, item.span.start)
));
}
}
Ok(())
}
/// The file's own name is not to hand here, so a directive refusal names the
/// line the directive is on instead.
fn first_line(text: &str, at: u32) -> String {
let line = text.get(..at as usize).map_or(0, |head| head.matches('\n').count()) + 1;
format!("line {line}")
}
fn count(n: usize, noun: &str) -> String {
match n {
1 => format!("1 {noun}"),
n => format!("{n} {noun}s"),
}
}
// ----------------------------------------------------------------------
// sentences
// ----------------------------------------------------------------------
fn not_in_scope(file: &Path) -> String {
format!("{} is not one of the files lucisv was given.", display(file))
}
fn occupied(path: &Path) -> String {
format!("there is already a `{}` beside this file; pick another name.", display(path))
}
fn escaped(name: &str) -> String {
format!(
"`{name}` is declared inside the selection and used outside it; move the declaration of `{name}` out of the selection first."
)
}
fn outside_module(name: &str, module: &str) -> String {
format!(
"the selection uses `{name}`, which is declared outside `{module}` in the same file; a module in a file of its own would not see it, so lucisv made no edits."
)
}
/// The same refusal for a **member access**, which names the head first.
/// `s.f` and `bus.data` cross the boundary as `s` and `bus` — the port or the
/// variable — and `f` and `data` are names of *their* types; a sentence that
/// leads with the field reads as if the field were a signal of `M`'s own.
fn outside_module_member(head: &str, name: &str, module: &str) -> String {
format!(
"the selection uses `{head}.{name}`, and `{head}` is declared with a type written outside `{module}` in the same file; a module in a file of its own would not see it, so lucisv made no edits."
)
}
fn unmovable(name: &str, module: &str, kind: SymbolKind) -> String {
let what = match kind {
SymbolKind::Genvar => "a `genvar`",
SymbolKind::Function => "a function",
SymbolKind::Task => "a task",
SymbolKind::Typedef => "a type",
SymbolKind::EnumVariant => "an enumeration member",
SymbolKind::Instance => "an instance",
SymbolKind::Modport => "a modport",
SymbolKind::Clocking => "a clocking block",
SymbolKind::Class => "a class",
SymbolKind::Block => "a named block",
_ => "a declaration",
};
format!(
"the selection uses `{name}`, {what} `{module}` declares outside it; lucisv makes ports out of signals and parameters and nothing else, so it made no edits."
)
}
fn header_names(module: &str, owner: &str, word: &str) -> String {
format!(
"`{module}` declares `{owner}` with something that names `{word}`, which is neither a parameter nor a name a module in another file could reach; lucisv made no edits."
)
}
fn hierarchical(path: &str) -> String {
format!(
"the selection reads `{path}` through the design hierarchy, and a hierarchical path does not survive being moved into another module; lucisv made no edits."
)
}
fn lost_name(name: &str) -> String {
format!("lucisv lost track of the declaration of `{name}`, so it made no edits.")
}
fn lost(what: &str) -> String {
format!("lucisv could not name one of the files it edited for {what}.")
}
+209
View File
@@ -0,0 +1,209 @@
//! What the selection covers: the module it is written in, the run of whole
//! module items it spans, and the bytes the extraction will delete.
//!
//! Nothing here reads the symbol table — this is the *shape* half of the
//! refusal list, answered from the tree and the text alone: the selection has
//! to cover whole items, and the items it covers have to be ones lucisv can
//! move without changing what they mean where they land.
use vlog_parser::ast::{Item, ItemKind, Module, SourceFile};
use vlog_parser::span::TextRange;
/// The selection, resolved.
pub(super) struct Region<'t> {
/// The module the selection is written in.
pub(super) module: &'t Module,
/// Where that module is written, `module` keyword to `endmodule`.
pub(super) module_span: TextRange,
/// The items the selection covers, in source order.
pub(super) items: Vec<&'t Item>,
/// The bytes the extraction deletes from the module's file: the covered
/// items and whatever of their own comments the selection covers too.
pub(super) span: TextRange,
/// The whitespace the region's first line begins with — what the
/// instantiation written in its place is laid out against.
pub(super) indent: String,
}
impl<'t> Region<'t> {
/// Read the selection, or say why lucisv will not extract it.
pub(super) fn read(
tree: &'t SourceFile,
text: &str,
selection: TextRange,
) -> Result<Region<'t>, String> {
let (module, module_span) =
module_at(&tree.items, selection).ok_or_else(|| NO_MODULE.to_string())?;
extractable(module)?;
// A cursor is a selection of one item: an editor sends the caret's
// own empty range when nothing is selected, and "extract the thing I
// am standing on" is what the user means by it.
let selection = match selection.is_empty() {
false => selection,
true => module
.items
.iter()
.map(|item| item.span)
.find(|span| span.contains(selection.start) || span.end == selection.start)
.ok_or_else(|| EMPTY.to_string())?,
};
let mut items: Vec<&Item> = Vec::new();
let mut span: Option<TextRange> = None;
for item in &module.items {
let extent = extent(item, selection);
if !overlaps(extent, selection) {
continue;
}
if extent.start < selection.start || selection.end < extent.end {
return Err(PARTIAL.to_string());
}
span = Some(match span {
None => extent,
Some(so_far) => TextRange::new(so_far.start, extent.end),
});
items.push(item);
}
let Some(span) = span else { return Err(EMPTY.to_string()) };
for item in &items {
movable(item)?;
}
Ok(Region { module, module_span, items, span, indent: indent_at(text, span.start) })
}
/// The module's name.
pub(super) fn module_name(&self) -> &str {
&self.module.name
}
}
/// The `module`, `interface` or `program` whose body covers the whole
/// selection — the parser writes all three as one node, and [`extractable`] is
/// what says only the first is one lucisv extracts out of.
fn module_at(items: &[Item], selection: TextRange) -> Option<(&Module, TextRange)> {
for item in items {
let ItemKind::Module(module) = &item.kind else { continue };
if !item.span.contains(selection.start) {
continue;
}
if selection.end > item.span.end {
return None;
}
return Some((module, item.span));
}
None
}
/// Only a `module` is a thing lucisv extracts out of.
///
/// The parser gives a `module`, an `interface` and a `program` one node —
/// their headers and bodies are the same grammar (IEEE 1800 §25.3) — and
/// [`Module::kw`] is the only thing that says which was written. Extracting is
/// a dataflow question about a boundary, and neither of the other two has the
/// boundary this rule assumes: an `interface`'s signals *are* its surface,
/// named by whoever instantiates it and driven from anywhere, so "what does
/// this region drive" does not answer what a port should be; a `program`'s
/// items are testbench code whose meaning depends on when they run.
fn extractable(module: &Module) -> Result<(), String> {
match module.kw.as_str() {
"module" | "macromodule" => Ok(()),
"interface" => Err(INTERFACE.to_string()),
"program" => Err(PROGRAM.to_string()),
kw => Err(format!(
"the selection is inside a `{kw}`, and lucisv extracts module items out of a `module`, so it made no edits."
)),
}
}
/// The bytes one item owns for the purpose of the selection: the item itself,
/// plus every comment and attribute of its own that the selection also covers.
///
/// A comment the user left *outside* the selection stays where it is, which is
/// what makes a selection that starts on the item's own line do the obvious
/// thing and one that starts a line earlier take the note with it.
fn extent(item: &Item, selection: TextRange) -> TextRange {
let mut spans = vec![item.span];
spans.extend(item.meta.leading.iter().map(|c| c.span));
spans.extend(item.meta.before_sep.iter().map(|c| c.span));
spans.extend(item.meta.trailing.iter().map(|c| c.span));
spans.extend(item.meta.attrs.iter().map(|a| a.span));
let mut out = item.span;
for span in spans {
if span.start < selection.start || selection.end < span.end {
continue;
}
out = TextRange::new(out.start.min(span.start), out.end.max(span.end));
}
out
}
fn overlaps(a: TextRange, b: TextRange) -> bool {
a.start < b.end && b.start < a.end
}
/// The item kinds lucisv will not carry into another module, each with the
/// sentence saying why.
fn movable(item: &Item) -> Result<(), String> {
match &item.kind {
ItemKind::PortDecl(_) => Err(kind_refusal("a port declaration")),
ItemKind::ParamDecl(decl) => Err(kind_refusal(match decl.kw.as_str() {
"localparam" => "a `localparam` declaration",
_ => "a `parameter` declaration",
})),
ItemKind::Genvar(_) => Err(kind_refusal("a `genvar` declaration")),
ItemKind::Bind(_) => Err(kind_refusal("a `bind` directive")),
ItemKind::Initial(_) => Err(
"the selection holds an `initial` block; that is testbench code whose meaning depends on when it runs, and lucisv does not move one into another module this round."
.to_string(),
),
ItemKind::Final(_) => Err(
"the selection holds a `final` block; that is testbench code whose meaning depends on when it runs, and lucisv does not move one into another module this round."
.to_string(),
),
ItemKind::MacroItem(_) => Err(
"the selection holds a macro invocation, and lucisv does not expand macros, so it cannot tell what would move with it."
.to_string(),
),
ItemKind::Directive(_) => Err(
"the selection holds a compiler directive, and lucisv does not evaluate one, so it cannot tell what the selection means in another module."
.to_string(),
),
ItemKind::Verbatim(_) => Err(
"the selection holds a block lucisv keeps verbatim (an assertion, a `property`, a `sequence`, a `constraint` or a `covergroup` body it could not read), so it cannot tell which names cross the boundary."
.to_string(),
),
ItemKind::Error(_) => Err(
"part of the selection did not parse, so lucisv cannot tell what it would be moving."
.to_string(),
),
ItemKind::Module(_) | ItemKind::Package { .. } | ItemKind::Class(_) => {
Err(kind_refusal("a declaration of its own"))
}
_ => Ok(()),
}
}
fn kind_refusal(what: &str) -> String {
format!(
"the selection holds {what}, which belongs to the module that wrote it; lucisv does not move one into a new module."
)
}
/// The whitespace the line holding `at` begins with.
fn indent_at(text: &str, at: u32) -> String {
let start = text.get(..at as usize).and_then(|head| head.rfind('\n')).map_or(0, |n| n + 1);
text.get(start..at as usize)
.unwrap_or("")
.chars()
.take_while(|c| *c == ' ' || *c == '\t')
.collect()
}
const NO_MODULE: &str =
"the selection is not inside one module's body, so there is nothing for lucisv to extract from.";
const PARTIAL: &str =
"the selection cuts an item in half; lucisv extracts whole module items, so select from the start of the first one to the end of the last.";
const EMPTY: &str = "the selection covers no module item, so there is nothing to extract.";
const INTERFACE: &str =
"the selection is inside an `interface`, whose signals are its surface — every one of them is driven and read by whatever instantiates it — so there is no boundary for lucisv to infer ports across; lucisv extracts out of a `module`.";
const PROGRAM: &str =
"the selection is inside a `program`, whose items are testbench code whose meaning depends on when it runs; lucisv extracts out of a `module`.";
+384
View File
@@ -0,0 +1,384 @@
//! Writing the new module, and the instantiation that stands where its items
//! used to be.
//!
//! Two rules govern everything here. A **port's type is the declaration's own
//! text**, reassembled from the tree in the order `vlog_formatter`'s ANSI port
//! printer writes it (direction, net, type, signing, packed dimensions, name),
//! so what lucisv writes is what the formatter would; anything the tree says is
//! not a plain name-signing-dimensions type — an anonymous aggregate, a
//! parameterized reference, a virtual interface, an unpacked dimension — is
//! refused rather than approximated. And the **instantiation is rendered from
//! the new module's own text**, through
//! [`instantiation_plan`](crate::instantiate::instantiation_plan), so the two
//! halves of the edit cannot disagree about what `N`'s ports are.
use vlog_parser::ast::{
AnsiPort, DataDecl, DataType, Declarator, Dim, ItemKind, ListElem, Module, ParamDecl,
ParamPort, PortDecl, PortList,
};
use vlog_parser::span::TextRange;
use crate::instantiate::{instantiation_plan, Layout};
/// Where a name that crosses the boundary is declared in the module.
pub(super) enum Site<'t> {
/// An ANSI port of the header.
Ansi(&'t AnsiPort),
/// A name-only header port, with the body declarations that describe it.
NonAnsi(&'t PortDecl, &'t Declarator, Option<(&'t DataDecl, &'t Declarator)>),
/// A net or variable declared in the body.
Data(&'t DataDecl, &'t Declarator),
/// A parameter or localparam declared in the body.
Param(&'t ParamDecl, &'t Declarator),
/// A parameter declared in the header's `#( ... )`.
ParamPort(&'t ParamPort),
}
/// Every declaration of the module that a crossing name could name.
pub(super) fn site_of<'t>(module: &'t Module, name: &str) -> Option<Site<'t>> {
if let PortList::Ansi(ports) = &module.ports {
if let Some(port) = ports.iter().filter_map(ListElem::ok).find(|p| p.name == name) {
return Some(Site::Ansi(port));
}
}
if let Some(params) = &module.param_ports {
if let Some(param) = params.iter().filter_map(ListElem::ok).find(|p| p.name == name) {
return Some(Site::ParamPort(param));
}
}
let mut port: Option<(&PortDecl, &Declarator)> = None;
let mut data: Option<(&DataDecl, &Declarator)> = None;
for item in &module.items {
match &item.kind {
ItemKind::PortDecl(decl) => {
if let Some(d) = decl.declarators.iter().find(|d| d.name == name) {
port = Some((decl, d));
}
}
ItemKind::DataDecl(decl) => {
if let Some(d) = decl.declarators.iter().find(|d| d.name == name) {
data = Some((decl, d));
}
}
ItemKind::ParamDecl(decl) => {
if let Some(d) = decl.declarators.iter().find(|d| d.name == name) {
return Some(Site::Param(decl, d));
}
}
_ => {}
}
}
match (port, data) {
(Some((decl, declarator)), other) => Some(Site::NonAnsi(decl, declarator, other)),
(None, Some((decl, declarator))) => Some(Site::Data(decl, declarator)),
(None, None) => None,
}
}
/// One port of the new module, ready to be written.
pub(super) struct Port {
pub(super) name: String,
/// `input logic [7:0] `, the name's own text excluded.
pub(super) prefix: String,
/// Every identifier that prefix spells — the direction and the type
/// keywords among them. A port whose width is `[N-1:0]` names `N`, and
/// `N` has to cross the boundary with it or the new module names nothing.
pub(super) names: Vec<String>,
}
/// One parameter of the new module.
pub(super) struct Param {
pub(super) name: String,
/// `parameter int `, the name's own text excluded.
pub(super) prefix: String,
/// The default as `M` writes it, or an empty string when it writes none.
pub(super) default: String,
/// Every identifier its type and its default name, for the closure that
/// carries the parameters one parameter depends on across with it.
pub(super) names: Vec<String>,
}
/// The declaration of a crossing signal, written as an ANSI port of the new
/// module.
pub(super) fn port(
text: &str,
module: &str,
name: &str,
site: &Site<'_>,
dir: &str,
) -> Result<Port, String> {
let (net, ty, unpacked) = match site {
Site::Ansi(port) => (port.net.as_deref(), &port.ty, port.unpacked.as_slice()),
Site::NonAnsi(decl, declarator, var) => {
let (net, ty) = match var {
Some((data, _)) if decl.net.is_none() && decl.ty.name.is_empty() => {
(data.net.as_deref().or(decl.net.as_deref()), &data.ty)
}
_ => (decl.net.as_deref(), &decl.ty),
};
if let Some((data, other)) = var {
if !data.qualifiers.is_empty() {
return Err(qualified(module, name));
}
if !other.unpacked.is_empty() {
return Err(unpacked_refusal(module, name));
}
}
(net, ty, declarator.unpacked.as_slice())
}
Site::Data(decl, declarator) => {
if !decl.qualifiers.is_empty() {
return Err(qualified(module, name));
}
if decl.delay.is_some() {
return Err(delayed(module, name));
}
(decl.net.as_deref(), &decl.ty, declarator.unpacked.as_slice())
}
Site::Param(..) | Site::ParamPort(_) => return Err(lost(name)),
};
if !unpacked.is_empty() {
return Err(unpacked_refusal(module, name));
}
let ty = type_text(text, module, name, ty)?;
let mut prefix = String::new();
let mut word = |part: &str| {
prefix.push_str(part);
prefix.push(' ');
};
word(dir);
if let Some(net) = net {
word(net);
}
if !ty.is_empty() {
word(&ty);
}
let names = words(&prefix);
Ok(Port { name: name.to_string(), prefix, names })
}
/// The declaration of a crossing parameter, written as a parameter of the new
/// module.
pub(super) fn param(
text: &str,
module: &str,
name: &str,
site: &Site<'_>,
) -> Result<Param, String> {
let (is_type, ty, default) = match site {
Site::Param(decl, declarator) => {
(decl.is_type, &decl.ty, declarator.init.as_ref().map(|e| e.span))
}
Site::ParamPort(param) => {
(param.is_type, &param.ty, param.default.as_ref().map(|e| e.span))
}
_ => return Err(lost(name)),
};
if is_type {
return Err(format!(
"`{module}`'s `{name}` is a type parameter, and lucisv does not carry one into a new module this round."
));
}
let ty = type_text(text, module, name, ty)?;
let mut prefix = String::from("parameter ");
if !ty.is_empty() {
prefix.push_str(&ty);
prefix.push(' ');
}
let default = default.map(|span| slice(text, span).trim().to_string()).unwrap_or_default();
if default.contains('\n') {
return Err(format!(
"`{module}` writes `{name}`'s default across several lines, and lucisv does not re-flow one into a new module's header."
));
}
let mut names = words(&prefix);
names.extend(words(&default));
Ok(Param { name: name.to_string(), prefix, default, names })
}
/// Everything a declaration writes between the direction and the name, as the
/// source spells it: `logic [7:0]`, `my_pkg::word_t`, `signed [31:0]`.
fn type_text(text: &str, module: &str, name: &str, ty: &DataType) -> Result<String, String> {
if ty.virt.is_some() || ty.extra.is_some() {
return Err(format!(
"`{module}` declares `{name}` with a type lucisv does not move into a port list (an anonymous aggregate, a parameterized reference or a virtual interface)."
));
}
let mut out = String::new();
for part in [ty.name.as_str(), ty.signing.as_deref().unwrap_or("")] {
if part.is_empty() {
continue;
}
if !out.is_empty() {
out.push(' ');
}
out.push_str(part);
}
let packed = dims(text, &ty.packed);
if !packed.is_empty() {
if !out.is_empty() {
out.push(' ');
}
out.push_str(&packed);
}
Ok(out)
}
fn dims(text: &str, list: &[Dim]) -> String {
list.iter().map(|dim| slice(text, dim.span)).collect()
}
fn slice(text: &str, span: TextRange) -> &str {
text.get(span.start as usize..span.end as usize).unwrap_or("")
}
/// Every whole word of an expression's text — what a parameter default may
/// depend on.
fn words(text: &str) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let bytes = text.as_bytes();
let mut i = 0usize;
while i < bytes.len() {
if !is_word_byte(bytes[i]) {
i += 1;
continue;
}
let start = i;
while i < bytes.len() && is_word_byte(bytes[i]) {
i += 1;
}
let leading_digit = bytes[start].is_ascii_digit();
let after_tick = start > 0 && bytes[start - 1] == b'\'';
if !leading_digit && !after_tick {
if let Some(word) = text.get(start..i) {
out.push(word.to_string());
}
}
}
out
}
fn is_word_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$'
}
// ----------------------------------------------------------------------
// the two texts
// ----------------------------------------------------------------------
/// The whole new module: header, the imports it needs, and the selection's own
/// bytes, verbatim.
///
/// Verbatim is the point. The items are module items in `M` and module items
/// in `N`, at the same nesting depth, so the source's own indentation is
/// already right — and every comment, every attribute and every string travels
/// byte for byte, which is what lets the splice verifier count them.
pub(super) fn new_module(
name: &str,
imports: &[String],
params: &[Param],
ports: &[Port],
body: &str,
) -> String {
let mut out = format!("module {name}");
for path in imports {
out.push_str("\n import ");
out.push_str(path);
out.push(';');
}
// A header import is written on its own line, which is where the formatter
// puts one; the list after it then starts a line of its own rather than
// continuing with a space.
let sep = match imports.is_empty() {
true => " ",
false => "\n",
};
if !params.is_empty() {
out.push_str(sep);
out.push_str("#(\n");
for (i, param) in params.iter().enumerate() {
out.push_str(" ");
out.push_str(&param.prefix);
out.push_str(&param.name);
if !param.default.is_empty() {
out.push_str(" = ");
out.push_str(&param.default);
}
out.push_str(if i + 1 < params.len() { ",\n" } else { "\n" });
}
out.push(')');
}
let sep = match params.is_empty() {
true => sep,
false => " ",
};
match ports.is_empty() {
true => {
out.push_str(sep);
out.push_str("();\n");
}
false => {
out.push_str(sep);
out.push_str("(\n");
for (i, port) in ports.iter().enumerate() {
out.push_str(" ");
out.push_str(&port.prefix);
out.push_str(&port.name);
out.push_str(if i + 1 < ports.len() { ",\n" } else { "\n" });
}
out.push_str(");\n");
}
}
out.push_str(body);
if !body.ends_with('\n') {
out.push('\n');
}
out.push_str("endmodule\n");
out
}
/// The instantiation that replaces the selection, read back out of the new
/// module's own text.
///
/// Every port connects to the signal of the same name — which is what the
/// extraction just made true — and every parameter to the parameter of the
/// same name.
pub(super) fn instantiation(name: &str, module_text: &str, indent: &str) -> Result<String, String> {
let mut plan = instantiation_plan(name, module_text, None)?;
for port in &mut plan.ports {
port.auto_connect = true;
}
let params = plan.params.len();
let names: Vec<String> = plan.params.iter().map(|param| param.name.clone()).collect();
let layout = Layout { base: indent.to_string(), step: " ".to_string() };
Ok(plan.render_with(&layout, &mut |n, default| match n <= params {
true => names.get(n - 1).cloned().unwrap_or_default(),
false => default.to_string(),
}))
}
// ----------------------------------------------------------------------
// sentences
// ----------------------------------------------------------------------
fn unpacked_refusal(module: &str, name: &str) -> String {
format!(
"`{name}` crosses the selection's boundary and `{module}` declares it with an unpacked dimension; lucisv does not turn one into a port this round."
)
}
fn qualified(module: &str, name: &str) -> String {
format!(
"`{module}` declares `{name}` with a qualifier (`var`, `const`, `automatic`), and lucisv does not move a qualifier into a port list."
)
}
fn delayed(module: &str, name: &str) -> String {
format!(
"`{module}` declares `{name}` with a net delay, and lucisv does not move a delay into a port list."
)
}
fn lost(name: &str) -> String {
format!("lucisv lost track of the declaration of `{name}`, so it made no edits.")
}
Loaded 100 of 243 files, more files were not shown because too many files have changed in this diff. Show more