Compare commits

...
97 Commits
Author SHA1 Message Date
lucioandClaude Fable 5 159f6a0bd8 Release 0.33.0 — SVA bodies as real nodes
ci / checks (push) Successful in 57s
ci / corpus (push) Successful in 26s
release / build-and-publish (push) Successful in 5m56s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 16:08:19 -07:00
lucioandClaude Fable 5 a045cd7649 SVA bodies as real nodes: property and sequence expressions with Table 16-3 precedence, declarations, assertions, symbols, and a fallback that speaks
TODO section 27; the SVA half of coverage_gaps C1/M8; docs/topo.md
2.9-18's engine half.
property/sequence declarations, concurrent assert/assume/cover/restrict
property, expect, cover sequence and default disable iff were verbatim
text. They are nodes now: sequence_expr/property_expr as one
precedence-climbing extension of parse_expr (IEEE 1800-2017 Table 16-3
row by row - QA caught two rows transcribed from Table 11-2 and the
rework fixed them: nexttime on not's row, the whole loosest row read
position-independently), typed formals, assertion variables, action
blocks as the statements they are - behind a Rewind snapshot with a
byte-exact per-construct fallback that fires on 0 of 4 792 corpus and
opentitan files. No keyword reserved: operator words are text-matched
in SVA position only. One layout rule: top-level |->, |=>, ##, and, or
break one per line at the parent's indent when the spec does not fit.
SVA gap fuzzer 705 gaps / 0 failing; 46 attack pairs; verify.rs
untouched.
Semantics: SymbolKind::{Property, Sequence}, ScopeKind::PropSeq, formals
and locals scoped, instances resolve in-file and cross-file
(FACTS_FORMAT 15 -> 16); rename, references, document symbols and the
lints see inside; Scope::sva_fallback_warnings names what would still
fall back. macro_use_warnings pinned for a file whose only relationship
to the name is a macro argument (the server half stays filed).
Output moved in 13 corpus and 36 opentitan files, every changed line
inside an SVA construct (proved by tests/census.rs::sva_lines and by
QA's independent re-implementation); the 4 854 ASSERT macro uses are
byte-identical. Corpus 814/820.

docs/features/sva-bodies/README.md. Also carries TODO section 28
(decomposition, planned) and the topo rows for this round.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 16:02:29 -07:00
lucioandClaude Fable 5 f3af34980a CLAUDE.md: the file and function size rule — 300–600 production lines per file, split at 800, a reason above 1 200
ci / checks (push) Successful in 56s
ci / corpus (push) Successful in 25s
Set by the owner on 2026-09-02. Measured at the same time: thirteen
files over 800 production lines and eight over 1 200, led by
parser.rs (8 786), format.rs (5 444), ast.rs (3 313) and server.rs
(2 559 + 6 293 test) - the same files every feature lane collides in.
Decomposition is planned as TODO section 28: pure moves, public paths
kept by re-export, byte-identical output proven by the corpus and
opentitan gates.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 15:18:18 -07:00
lucioandClaude Fable 5 c2f107444c docs: coverage_gaps addendum at 0.32.0 — the recommended order is complete; TODO §27 planned (SVA bodies as real nodes, §2.9-18)
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 40s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 13:22:42 -07:00
lucioandClaude Fable 5 baf0bf16f0 Release 0.32.0 — bind semantics, macro and directive residues, lucisv.instantiate
release / build-and-publish (push) Successful in 6m14s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 13:21:09 -07:00
lucioandClaude Fable 5 81df63d942 Bind semantics, the spaced macro call and the directive inside a connection, and lucisv.instantiate
TODO section 26; closes docs/topo.md 2.9-15 and 2.9-19; coverage_gaps
M4/M5/M6 corrected against a fresh opentitan census.
A bind directive's target is a path of segments with optional indices
(bind top.gen[0].u_core chk u_chk (...)); a lone target binds as a
module reference, an instance path records nothing rather than a guess.
Each connection's port half resolves against the module being bound in
and its expression half in the target module's scope first, the
workspace's member path when the target lives elsewhere, the writing
scope last (Target::BindScope, resolve::in_bind_target - the
inline-constraint shape). FACTS_FORMAT 14 -> 15: binds now post
references and an instantiation edge.
Expression-position spaced macro calls (assign x = `WIDTH (a + b);)
keep the author's gap, read from the source as glued_null_item reads
its gap; verify.rs untouched, both pins stand. A conditional directive
inside a connection value becomes ExprKind::Verbatim, byte-exact
through raw_inline as Doc::Inline, with the closing paren's line and
the list's break read from the source - so the instantiation keeps its
edge, lens and port references instead of collapsing to opaque bytes
(opentitan: the two padring sites in chip_earlgrey_{asic,cw340}.sv,
+2 edges, everything else byte-identical to 0.31.0).
lucisv.instantiate [uri, position, module] renders the inline ghost's
plan as plain text through workspace/applyEdit for clients without
inline completion; the Neovim README documents it.
QA: 3186 tests / 47 binaries, corpus 814/820, independent binary diff
over corpus and 2 645 opentitan files: only the two named files differ.

docs/features/bind-semantics/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 13:15:21 -07:00
lucioandClaude Fable 5 a0c290ccc2 Comment slots in shared machinery: an owner for every gap, four fuzzers at zero, and the small-correctness residue
ci / checks (push) Successful in 57s
ci / corpus (push) Successful in 26s
release / build-and-publish (push) Successful in 5m49s
TODO section 25; closes docs/topo.md 2.9-20, 2.9-21, 2.9-22; opens 2.9-23.
A comment written where no AST node had a field was never deleted: bump
queued it and take_meta handed it to the next node, so it printed one
node later and verify.rs refused the whole file. About seventy named
comment fields now own those gaps - SegmentComments on member/scope/
index/range segments (one parse_postfix_segment replacing three
hand-copied loops), one [a:b] grammar, BinaryComments on inside, casts,
unary/postfix, if/case/for/foreach/do-while headers, @ and # timing,
Stmt::before_semi with StmtKind::takes_semi() as the single owner of
the ; (debug_assert enforced), labels on ten nodes, qualifier runs as
Vec<Qualifier>, function/task/module/package/class/typedef/enum/struct
headers, declarators, ports, connections, instantiations. Each prints
through Fmt::slot_comments, a no-op when empty: 860 corpus and 3 975
opentitan files are byte-identical to v0.30.0 (QA reproduced from an
independent baseline build). Four exhaustive gap fuzzers at zero -
covergroup 329, fragment 153, constraint 395 (committed at last), RTL
352 (new) - are the regression gate. verify.rs untouched, ten attack
pairs. Expression slots are boxed so Expr stays 96 bytes; ast::size_pins
asserts it (QA's one finding).

Also: nav::definition gains the macro branch hover already had (H5);
a cast's type binds as a type via bind_type_expr, FACTS_FORMAT 13 -> 14
(M11); rename reports the candidate references that stayed unresolved
through the overlay, one line per file and unit (2.9-20); the scoped
name join keeps an escaped segment's terminator (2.9-21). One flagged
edit outside scope: a .. in vlog_linter/src/signals.rs patterns.

docs/features/comment-slots/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 11:32:16 -07:00
lucioandClaude Fable 5 58112d4d3b release: retry uploads past Cloudflare's 524, re-checking the server first; optional direct API URL
ci / checks (push) Successful in 58s
ci / corpus (push) Successful in 39s
0.29.0 and 0.30.0 both died in the publish step with curl: (56) ...
error: 524 - Cloudflare's origin timeout, because GITHUB_SERVER_URL is
the public host and every upload crosses the proxy. tools/
publish_release.sh now retries each upload (UPLOAD_ATTEMPTS, default 5,
backing off) and asks the server what it holds before every retry: an
asset already there at the local size is done, one at another size is a
truncated upload and is deleted before re-sending. LUCISV_API_URL, an
optional repository Actions variable passed through release.yml, names a
direct http://host:port so the API bypasses the proxy; unset, the public
URL is used as before. Mock-tested with a curl stand-in reproducing the
524-then-partial sequence. Work log in docs/features/ci-release.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 11:13:19 -07:00
lucioandClaude Fable 5 51869c8bf4 Release 0.30.0 — semantic lints on, vendor and formal collateral
release / build-and-publish (push) Failing after 7m36s
ci / corpus (push) Successful in 29s
ci / checks (push) Successful in 1m1s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 09:06:13 -07:00
lucioandClaude Fable 5 5051bbdf15 Semantic lints on by default: the index knows who mentions what, and the linter finally asks
TODO section 24, coverage_gaps M7 via topo 2.9-6 and 2.9-4.
unused-signal, undriven-net and multiply-driven shipped off because a
per-file analysis cannot see a signal read or driven from another
file's hierarchy. The index now carries a per-file identifier census -
FileFacts::words, FACTS_FORMAT 12 -> 13, one harvest lifted from the
server's completion candidates and now feeding them back from the store
instead of re-lexing every file at startup (scan -28 percent) - and the
linter gains a MentionOracle: unused-signal and undriven-net say nothing
when the name is mentioned in any other indexed file, the
false-negative-safe direction; multiply-driven shares the gate but never
reads it. The three are on wherever an oracle exists (the editor always,
the CLI when it walks a project) and off for a single file or stdin.
With them, the missing off switch: [lint] select/ignore in lucisv.toml
with CLI flags winning key by key, and lucisv.lint.select/ignore in the
editor.

QA's finding, reworked: the census dropped macro invocations whole, so a
signal named only inside `uvm_info(..., dut.sig) was not silenced; the
harvest now splits macro, directive and attribute words, skipping
double-quoted runs so a "%d" cannot silence a signal named d
project-wide, with workspace-defined macro names filtered out of the
completion table at the reader. Store +16.9 percent corpus / +15.0
percent opentitan, measured.

Corpus unused-signal 52 -> 44 and undriven-net 3 -> 0 with every
silencing hand-checked, nothing added; opentitan - lint-clean under its
own tools - 14 findings, all classified true against the whole repo.
Also: the docs-site rules page gains the empty-item row it lacked.

docs/features/semantic-lints-on/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 09:06:08 -07:00
lucioandClaude Fable 5 29096cbbac Vendor and formal collateral: specify, UDPs, checkers, configs, interface classes, alias, union tagged - proven output-neutral
TODO section 23, coverage_gaps M1-M3 with the evidence corrected: every
construct here has zero declarations in the corpus and in opentitan (the
analysis's '13 checker files' were UVM protocol-checker filenames), so
this is a completeness round for vendored cell/IO/memory models and
formal collateral, and the formatted output of all 860 corpus and all
3975 opentitan files is byte-identical to v0.29.0.

Five keywords reserved on a measured zero-collision census (checker,
endchecker, config, endconfig, library); five deliberately not - expect
has 41 real task-call sites, so the statement form is recognised only
when its parentheses hold a sequence operator. One parse_opaque_block
(counts its own opener, keeps the label, leaves a trailing ';' as the
null item empty-item sees) serves specify, primitive with table,
checker and config; library lines parse; specparam is a real
declaration with a rewind for PATHPULSE$; alias a = b = c binds every
term; union tagged formats; interface class routes through the class
prefix with no new kind and no FACTS bump - deliberately, so it cannot
collide with the parallel lane's bump - and implements now contributes
type-hierarchy supertypes. pairs.rs pairs table, checker and config.

docs/features/vendor-formal-grammar/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 08:33:30 -07:00
lucioandClaude Fable 5 c40e720518 Release 0.29.0 — fragment mode and define continuation
release / build-and-publish (push) Failing after 15m23s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 07:35:24 -07:00
lucioandClaude Fable 5 4e62a14af6 Fragment mode and define continuation: the three .svh shapes that did not parse, and the define that was blamed on its class body
TODO section 22, coverage_gaps H4 corrected. Class-body and module-item
include fragments already parsed - the file-scope item loop is the
class-item loop. The three shapes that did not - a bare statement list,
an enum-member list (riscv-dv's CUSTOM_1, file, included between enum
members), a covergroup-item list - become SourceFile::fragment, detected
by a whole-file rule that cannot misfire on a valid file: the first
structural item failed (directives, macros and null items do not count;
a tolerant Ok that recorded a diagnostic counts as failed - an existing
parity test caught if/else reading as a generate-if to one parser and a
statement to the other), the file does not open with a design-unit
keyword, and a shape consumes the file to EOF, tried narrowest-first.
Each shape re-lexes a fresh token stream - Rewind does not restore the
tokens' comment buckets and the first draft lost comments on
non-fragment files. A fragment formats at indent zero through the
existing printers; its declarations bind; its enum variants are not
exported (pkg::CUSTOM_1 must not resolve to a name that does not
exist). FACTS stays 12.

The other .svh was never a fragment problem: a define whose formal
argument list spans two lines with no backslash. The lexer continues
such a directive until the list closes - incrementally, after QA found
the first cut quadratic on an unclosed list (20000 lines: 2.5 s ->
0.56 ms), pinned by a byte-visit counter.

Opentitan 12 -> 10 failing files, exactly the two predicted; corpus
813 -> 814 of 820; every remaining comment-gap failure proven to fail
identically outside a fragment.

docs/features/fragment-mode/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 07:34:31 -07:00
lucioandClaude Fable 5 cbb80e884f docs: clocking-wave README — tl_errors.svh's blocker is a define continuation, not its class body
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 06:11:32 -07:00
lucioandClaude Fable 5 3ee1c558b3 docs: coverage_gaps.md status addendum at 0.28.0 — C1, C2, H1, H2, H3, H6 delivered; H4 next
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 06:03:21 -07:00
lucioandClaude Fable 5 fae939119a Release 0.28.0 — covergroup bodies
release / build-and-publish (push) Successful in 7m44s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 06:02:23 -07:00
lucioandClaude Fable 5 2734885f2b Covergroup bodies: coverpoints, bins, transitions and crosses are real code - 544 of 544 on opentitan, zero fallbacks
TODO section 21, round 2 of coverage_gaps C1, closing it. A covergroup
was a flat token scan into verbatim text; now ItemKind::Covergroup with
CoverItemKind::{Coverpoint, Cross, Option, Directive, Empty}, BinDecl
(wildcard, kind, array, spec: Values / Transitions / Default /
DefaultSequence / Select, with, iff) and SelectExpr for binsof ...
intersect ... && !binsof - behind the same Rewind fallback as
constraints (v0.27.0's scan re-run character for character on any
failure), no keywords reserved. The bin '(' ambiguity is settled by
position, the LRM's own rule, which replaced a lookahead scan and took
the fallback count to zero. Two guards in shared expression machinery -
an index cannot begin with *, -> or =; a bin's own with (...) filter is
not an array-method iterator argument - both attacked across the corpus
and the opentitan tree. Canonical layout, verify.rs untouched, thirteen
attack pairs. Every sampled expression binds to the class's properties;
cg_inst.cp resolves cross-file; FACTS_FORMAT 11 -> 12. The gap fuzzer
was built in from day one and its classification is asserted, not
claimed.

Opentitan: 544/544 structured, 87/87 DV covergroup files idempotent
with comment streams byte-identical, sweep and per-file diagnostics
identical. Corpus +1139 references, 1135 answered.

docs/features/covergroup-bodies/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 06:01:48 -07:00
lucioandClaude Fable 5 53bc293c37 Release 0.27.0 — constraint bodies
release / build-and-publish (push) Successful in 5m49s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 04:19:08 -07:00
lucioandClaude Fable 5 bce167c052 Constraint bodies: constraint c { ... } is real code - soft, dist, ->, foreach, solve before - with a rewind to the verbatim it always had
TODO section 20 round 1, coverage_gaps C1 for constraints. A constraint
declaration was opaque text with no name span; renaming a rand field
left constraint c { user_id < 5; } as non-compiling code. Now
ItemKind::Constraint with a structured ConstraintSet (Expr{soft},
Implication, If, Foreach, SolveBefore, Unique, DisableSoft, Directive,
Empty), ExprKind::Dist, and randomize() with bodies as
ConstraintBody::{Items, Verbatim}. The parser attempts the structured
body behind a Rewind snapshot - cursor, both pending-comment buckets,
depth, links, open_conds, diagnostics - and on any error re-runs
v0.26.0's verbatim capture character for character, so an unknown body
IS the old behavior. No keywords reserved: soft/dist/solve/before are
matched by text, so logic before; keeps working and token.rs, pairs.rs
and the editor grammar are untouched. Canonical layout, verify.rs
untouched, attack pairs re-derived and extended. Every operand binds to
the class's properties (foreach vars nest; a with block resolves against
the randomized object's class first), so hover, definition, references
and rename reach inside. FACTS_FORMAT 10 -> 11. Lint rules read
constraint operands.

QA's finding - comments after the round's own words were dropped and
the safety net refused the file - answered with an exhaustive gap fuzzer
(358 gaps, format and idempotency demanded) and fourteen named comment
fields; the forty gaps that remain are shared machinery that fails
identically outside a constraint, filed as topo 2.9-22. Opentitan: 1993
of 2009 bodies structured, sweep unchanged, 48 DV files idempotent with
comment streams byte-identical, per-file diagnostics identical.

docs/features/constraint-bodies/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 04:18:18 -07:00
lucioandClaude Fable 5 dd4aa498bb Release 0.26.0 — member completion and escaped identifiers
ci / checks (push) Successful in 57s
ci / corpus (push) Successful in 22s
release / build-and-publish (push) Successful in 5m16s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 02:19:17 -07:00
lucioandClaude Fable 5 7d637323a5 Escaped identifiers: the terminating space, written once at fifty sites
coverage_gaps H3. An escaped identifier ends at whitespace (IEEE 1800
5.6.1) and the lexer stops the token before it; the formatter emitted
every name bare or through a format! splice, so \my-signal; re-lexed
as one token and the safety net refused the whole file - netlists and
generated RTL could not be formatted at all. One choke point
(format::named / name_doc, predicate ends_escaped because parser-joined
composites like a.\b end inside an escaped name) now terminates the
name; the space is unconditional and the printer's trailing trim
removes it before a break, so doc.rs and printer.rs are untouched.
verify.rs untouched; eight masked-corruption attack pairs; corpus
byte-identical by construction (every corpus backslash is inside a
string or a comment). Ran in its own worktree in parallel with member
completion. Open, filed as topo 2.9-21: a scoped name whose segment is
escaped is refused, never corrupted, until the parser keeps segments.

docs/features/escaped-identifiers/README.md; TODO.md section 19.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 02:17:43 -07:00
lucioandClaude Fable 5 df85fd3b54 Member completion: a dot means members - item., reg2hw.ctrl., vif.cb., pkg::, and the port map
TODO section 18. Typing a dot used to get the whole-index dump (every
keyword and project word, capped at 512); now the answer after a
separator is exclusively the members of what precedes it, or nothing.
The prefix walk is published from vlog_semantic as MemberSite /
Semantics::member_site / WorkspaceIndex::members_of_chain and the
resolver's own member_of, unit_member, member_in_chain and follow_one
are rewritten to call it - one walk, so the popup cannot list a member
hover would not resolve (pinned structurally). Inherited members ride
the same base chain; this./super./pkg::/cls:: are the same question.
A headless dot inside an instantiation's (...) or #(...) lists the
module's ports or parameters through signature.rs's own list detector
and the Target::Port walk, already-connected ports dropped. Trigger
characters '.' and ':'. Measured cheaper than the dump it replaces
(6-62 us vs 212 us).

QA's finding fixed at the root: the binder had discarded ParamPort.kw
and bound every localparam as Param, so #(. offered prim_fifo_sync's
DepthW. SymbolKind::LocalParam, keyword sticky across continuation
entries as instantiate::params reads it, exported wherever Param is,
'localparam' on the hover card, excluded from the override list only.
FACTS_FORMAT 9 -> 10.

Also carried: TODO sections 19 and 20 (the escaped-identifier and
constraint-body plans) and the topo rows for both lanes.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 02:05:03 -07:00
lucioandClaude Fable 5 bbf87976a1 Release 0.25.0 — struct members
ci / checks (push) Successful in 59s
ci / corpus (push) Successful in 22s
release / build-and-publish (push) Successful in 5m16s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 23:56:22 -07:00
lucioandClaude Fable 5 2a2334ef5a Struct members: s.field, reg2hw.ctrl.q and the anonymous aggregates resolve
coverage_gaps H1 + topo 2.9-13 delivered. The in-file gap was one
resolver gate: member_scope now returns any symbol's child scope when it
is a Struct scope, so a typedef, an anonymous struct declarator and an
inline nested field are one rule; fields declare with their own type so
s.hdr.addr hops through a member. Cross-file, struct members export
under the typedef's name, package-nested struct typedefs under their
bare name (the nested-class convention, ambiguity refused), and inline
nested fields - the opentitan register-package shape - under a
synthesized owner.field key carried as the field's type: joined with
'.', not '::', because member_type's last_segment would collapse the
latter to the bare field name and q/d/qe live in every register
package. Anonymous enum variants land in the enclosing scope like
typedef ones. FACTS_FORMAT 8 -> 9; typeDefinition descends into
typedef struct bodies.

Unresolved fell 1203 -> 1162; the corpus store shrank 1.1 percent
(resolved locals encode smaller than the candidates they replaced),
opentitan's register packages grow it 4.3 percent. QA: 28 opentitan
probes, three planted sibling pairs (rxfull/fmtfull, avsetup_rst/
avout_rst, tpm_csb/csb) all correct, zero wrong answers, hover under
0.5 ms.

docs/features/struct-members/README.md; TODO.md section 17.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 23:53:45 -07:00
lucioandClaude Fable 5 95f930cf20 Release 0.24.0 — interface semantics
ci / checks (push) Successful in 49s
ci / corpus (push) Successful in 20s
release / build-and-publish (push) Successful in 4m40s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 22:55:31 -07:00
lucioandClaude Fable 5 311551f232 Interface semantics: interfaces, modports and clocking blocks become symbols; vif.sig crosses files
coverage_gaps C2/H2, topo 2.9-7 delivered. SymbolKind::{Interface,
Modport, Clocking}; is_instantiable() (Module | Interface) is the one
predicate every 'is this a module' filter reads, pinned in place, so
interfaces stay in the module table, the ghost, the hierarchies and the
refactorings while the card finally says 'interface'. An interface
exports its signals - they ARE its surface - where a module still exports
ports and params only, which is what lets virtual my_if vif; vif.sig
resolve across files. Modport and clocking-internal names bind as
scope-local references (nothing on a miss - a lexical walk would land a
modport port on a file-scope lure); the modport half of bus_if.mp in a
type position is Target::TypeMember, resolved through type_here; a
clocking block carries type_name = its enclosing unit so vif.cb.data
hops through round-2 machinery unchanged. FACTS_FORMAT 7 -> 8.

Unresolved fell 1256 -> 1203 on the corpus, the first movement in three
rounds: the @(cb) / cb.data names that had nothing to bind. Store +1.2
percent. A modport now renames from its type-position use (the refactor
pin flipped at review). QA: 17 opentitan probes, zero wrong answers, all
sub-millisecond; vif.cb.scl_i lands on i2c_if.sv's own signal.

docs/features/interface-semantics/README.md; TODO.md section 16.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 22:53:27 -07:00
lucioandClaude Fable 5 ff67281995 Release 0.23.0 — member chains and instance heads
ci / checks (push) Successful in 51s
ci / corpus (push) Successful in 21s
release / build-and-publish (push) Successful in 4m50s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 21:37:28 -07:00
lucioandClaude Fable 5 7ca2508ec7 Member chains and instance heads: cfg.vif.clk, item.hdr.addr, u_sub.port resolve through the index
DV round 2 (TODO section 15 round 2). A chain tail carries spellings -
Target::MemberOf { head, mids } - so in-file it hops declared type to
declared type, and a chain that leaves the file becomes one composed path
Unit::mid::tail that follow_one walks with member_type hops: no deferred
resolution, no ordering assumption, and chain tails post to the index
through the existing contract so hover, references and rename agree.
Def::type_name rides every indexed declaration (FACTS_FORMAT 6 -> 7,
with ReferenceFact base so this.x uses post cross-file); an instance
symbol's type is its module, and modules export ports and parameters -
nets/vars stayed in-file on measurement (+24 percent store, and .port(w)
connections would have resolved to internal nets). Typedef aliases are
chased with a visited guard; a type the workspace declares twice with
different kinds is refused one hop out, the round-1 lesson applied.

The rename truth flipped with it: u_sub.sig IS sub's wire sig and is
renamed alongside it; an unresolvable tail is left alone but no longer
warned about, filed as topo 2.9-20.

Corpus: references 97454 -> 98919, unresolved unchanged at 1256,
store +15.4 percent. QA: zero wrong answers across the attack suite and
15 live opentitan probes.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 21:35:11 -07:00
lucioandClaude Fable 5 91b7c2fd67 Release 0.22.0 — class member access
ci / checks (push) Successful in 49s
ci / corpus (push) Successful in 19s
release / build-and-publish (push) Successful in 4m51s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 20:19:23 -07:00
lucioandClaude Fable 5 ce2f858e5e Class member access: in_item.user_id resolves, through the handle's type and up its extends chain
DV round 1 (TODO section 15). The tail of head.member gets a reference
when the head is a plain identifier whose declared type (Symbol::type_name,
new) is a class or module: the member is found in that scope, else up the
in-file extends chain, else the workspace's member table chases
WorkspaceIndex::base_of (a subclass-to-base map rebuilt from the existing
inheritance census, no new facts field) - cycle-guarded on both sides and
placed in follow_one so hover, cross-file references and rename cannot
disagree. this.x/super.x misses ride the same loop, delivering topo
2.9-9. An out-of-class method body (task c2::update) sees its class's
members through a stand-in Class scope. FACTS_FORMAT 5 -> 6: the layout is
unchanged but the reference census grew.

Honesty by construction, after QA's one REWORK: a head whose type is
declared in-file as anything without a member scope (typedef, alias,
enum, param) records nothing - a two-state Option had stood in for the
three-state TypeHere question, and a typedef named bus_t could have been
answered by an unrelated class bus_t elsewhere. The fix removed exactly
438 wrong postings from the corpus with unresolved unchanged at 1256.

Hover 7-143 us; opentitan tl_seq_item member 0.12 ms cold, 0.01 ms warm;
store +2.85 percent.

docs/features/class-member-access/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 20:17:18 -07:00
lucioandClaude Fable 5 14fbdab717 docs: coverage_gaps.md — the ranked Verilog/SV gap analysis at 0.21.0
ci / checks (push) Successful in 57s
ci / corpus (push) Successful in 23s
Two sweeps crossed: a 71-file empirical probe (44 RTL, 27 DV, 13 LSP
spot checks) against snapshot binaries, and an inventory of every
documented non-goal, verbatim capture, non-resolution rule and open
handshake. Idempotency and comment preservation held everywhere that
parsed; the gaps are grammar holes, opaque verbatim regions and
semantic blind spots, ranked Critical/High/Medium/Low with a
recommended order.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 16:34:53 -07:00
lucioandClaude Fable 5 f8401a0024 Release 0.21.0 — null items and the empty-item lint
ci / checks (push) Successful in 49s
ci / corpus (push) Successful in 20s
release / build-and-publish (push) Successful in 4m58s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 15:03:36 -07:00
lucioandClaude Fable 5 307a56e921 Null items: the semicolon after endgenerate, and everywhere else an item may stand
Owner report: 'for loop inside generate shows expected item (found ;) at
endgenerate;'. Lead diagnosis before dispatch: every generate-for spelling
and three systemverilog.io examples already parsed; the failing token was
the lone ';' - IEEE 1800-2017 A.1.4's null item, legal in module,
generate, package, interface, program and class scope and at file scope,
rejected by lucisv in all of them.

ItemKind::Empty, one branch at the top of parse_item_kind, the three
exhaustive arms topo 3.3 predicts and no others. The formatter keeps the
';' where it was written - glued to the previous sibling's line
(endgenerate; end; endmodule; ;;) when no newline separates them and the
';' carries no docs of its own, else on a line of its own - decided from
src spans in item_seq rather than a parser flag. verify.rs untouched,
eight attack pairs. New empty-item lint (slang's -Wempty-member) with a
safe fix whose deletion range structurally cannot swallow a comment.

Corpus byte-identical at 813/820 against the pre-change binary; opentitan
sweep identical file-for-file; empty-item fires zero times there. The LSP
now publishes a warning with a quick fix where it used to publish a parse
error.

docs/features/null-items/README.md; TODO.md section 14.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-01 15:01:33 -07:00
lucioandClaude Fable 5 1e30ea0fb5 gitignore: the owner's .zcode and the agent-harness .claude directory
ci / checks (push) Successful in 54s
ci / corpus (push) Successful in 23s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-31 21:51:35 -07:00
lucioandClaude Fable 5 3f912e7fce Release 0.20.0 — fuzzy completion at VS Code's floor
ci / checks (push) Successful in 46s
ci / corpus (push) Successful in 20s
release / build-and-publish (push) Successful in 4m35s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-30 19:04:41 -07:00
lucioandClaude Fable 5 f3b5a9d189 Fuzzy completion: clkenq reaches clk_osc_en_q, at VS Code's own floor
Prefix matching below three typed characters, subsequence from three
up — the owner's ruling, which is VS Code's own rule. The scope,
index-name and word tiers match by case-insensitive subsequence at 3+,
ranked prefix-first then by a three-pass greedy-tighten scorer
(boundary and contiguity bonuses, gap penalties); module, keyword,
template and macro tiers unchanged, and the instantiation ghost's
exact-match probe deliberately stays exact.

The scan is affordable because every word and unit name carries a
32-bit character mask beside it, written in exactly two places so
table and mask cannot desync: a clkenq keystroke rejects 99.6% of
opentitan's 100k-word table with one AND each (+0.05 ms); the
pathological class is three very common letters (aes +0.8 ms, QA's
ena ~3-4 ms answered-in), accepted at lead review as imperceptible
in a popup. Responses below the floor are always isIncomplete — a
complete two-character answer would be client-filtered and the third
keystroke, the one that turns fuzzy on, would never reach the server.

QA verified clkenq -> clk_osc_en_q live in a real opentitan buffer
(gfr_clk_mux2.sv) and the 2-to-3 transition over the wire; ten
adversarial matcher attacks all passed.

docs/features/fuzzy-completion/README.md; TODO.md section 13.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-30 19:02:42 -07:00
lucioandClaude Fable 5 02b4204536 Release 0.19.0 — the space-armed ghost, every module answering
ci / checks (push) Successful in 50s
ci / corpus (push) Successful in 21s
release / build-and-publish (push) Successful in 4m47s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-30 17:17:44 -07:00
lucioandClaude Fable 5 03a4958294 Inline instantiation round 2: the space is the commitment, and every indexed module answers
Two owner rulings from live use. The ghost now fires only after
'name<space>' — aes alone may still be growing into aes_dft, so the
typed space is what says the name is finished; an Ident ending at the
cursor offers nothing at all. And a module declared in more than one
file no longer declines: completion::nearest_definition picks the copy
sharing the most leading path components with the asking buffer (a
top_earlgrey buffer gets top_earlgrey's ast_dft), then the shallowest,
then the lexicographically smallest — the depth term is QA's catch,
fixed at review, so a direct sibling beats a deeper subdirectory copy
that ties on the prefix. vlog_refactor::module_definition keeps its
ambiguity refusal for its own callers.

The refusal residue is now the enumerable inline::NoGhost, and QA's
sweep proves the ruling: 1131/1131 opentitan module names ghost, zero
declines (199 multiply-declared, tb 61 ways), ast_dft and io_osc
verified from both tops over the wire, 0.05-0.08 ms per non-matching
keystroke.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-30 17:15:42 -07:00
lucioandClaude Fable 5 f27fa1c045 Release 0.18.0 — inline instantiation, two levels
ci / checks (push) Successful in 50s
ci / corpus (push) Successful in 21s
release / build-and-publish (push) Successful in 4m56s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-30 14:47:40 -07:00
lucioandClaude Fable 5 cadb4319e4 Inline instantiation: the popup names the module, the ghost writes the rest
ci / checks (push) Successful in 45s
ci / corpus (push) Successful in 19s
Two levels, sized for opentitan. Tier 0 of the completion popup stops
planning skeletons (up to 64 file reads + header parses per keystroke)
and offers module names alone; once the identifier at the cursor exactly
matches an indexed module, textDocument/inlineCompletion ghosts the full
instantiation — every parameter, every port, each a tabstop, in-scope
signals auto-connected — planned once through the existing header-slice
path and the FileView cache. Candidates::has_module is the per-keystroke
probe: a case-sensitive binary search whose str-order premise is pinned.
lucisv.inlineInstantiation (default on) gates it, independent of
inlineTemplates.

Measured on opentitan: non-matching keystroke 0.10-0.17 ms warm, ghost
0.6-1.1 ms for aes (14 params/16 ports), 2.5 ms cold for the
112-parameter top_earlgrey; popup module tier reads no files at all.

Lead corrections at merge: four doc references to a lucisv/instantiate
command that never existed, replaced by the honest gap (topo 2.9-19: no
skeleton path for clients without inlineCompletion); extension and nvim
README docs delivered.

docs/features/inline-instantiation/README.md; TODO.md section 12.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-30 14:17:16 -07:00
lucioandClaude Fable 5 1cfbab4a56 Docs debt: performance_take2.md, the merged-wave measurement, finally checked in beside take 1
Written 2026-08-29 as the owner-requested second opentitan round; referenced
by CHANGELOG 0.15.0, docs/perf/README.md and the index-scope README ever
since, but never staged. Placed in docs/ so its relative link to
performance.md resolves.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-30 14:17:00 -07:00
lucioandClaude Fable 5 a1fa402fd8 Release 0.17.0 — the testbench wave, complete
ci / checks (push) Successful in 53s
ci / corpus (push) Successful in 22s
release / build-and-publish (push) Successful in 5m4s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 18:47:45 -07:00
lucioandClaude Fable 5 bc533c6cb1 The clocking wave: eight buckets in one round, 43 -> 11 on opentitan
ci / checks (push) Successful in 56s
ci / corpus (push) Successful in 22s
Clocking signal bindings (the one production the modelled node was
missing), default disable iff captured verbatim with six rejection
pairs, iff on event-control terms, indexed bare event names
(chain-charged), gate drive strengths (the mop-up's amortized skip),
program blocks as modules with a different closer, and macros as a
concurrent assertion's whole action — where QA caught a real
regression (a macro BEGINNING a statement, four UVM-idiom shapes) and
the rework moved the decision to the token after the call:
at_statement_tail, one line, with the failure asymmetry argued in the
doc and attacked by QA against the diff rather than trusted. Chain
limit 256 -> 1024 on measured need (567 links in pinmux_reg_top) with
PARSE_STACK_SIZE 16 -> 32 MiB restoring the 3.3x margin, a sabotage
probe proving it real, and parse_sens_list's uncharged chain loop
closed. Whole-tree superset: exactly one output move, ~55 lines of
prim_sync_reqack generate code freed from an assertion's opaque
bytes. Corpus 860 files byte-identical, 813/820. The 11 remaining:
macro fragments (preprocessing decision), vendor non-SV (exclude
patterns recommended), three written-up skips.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 18:46:58 -07:00
lucioandClaude Fable 5 5ad0772475 Merge testbench-syntax mop-up round
ci / checks (push) Successful in 45s
ci / corpus (push) Successful in 18s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 16:08:59 -07:00
lucioandClaude Fable 5 af3280c651 The mop-up: nine small buckets, forty-five files, no new surface where none was needed
Block-scoped typedef statements (new StmtKind, three arms plus the
typeDefinition hop QA's audit caught missing), system-function casting
types (the bucket the analysis had mislabeled as drive strengths),
enum member ranges, casts over assignment patterns, gate delay lists,
virtual iface.modport through ansi-first-port's own gate, rand on
struct members, foreach skipped dimensions, hierarchical bind instance
paths. OpenTitan sweep 88 -> 43 with zero newly-failing files and the
whole-tree superset check proving 0 of 3,855 previously-passing files
moved; corpus byte-identical at 813/820; tolerant diagnostics 147 -> 0
on the fixed set and 0 files worse anywhere. One skip written up
(pullup drive strength: two AST changes for one file). verify.rs
untouched, no capture added.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 16:08:51 -07:00
lucioandClaude Fable 5 24b0dd9912 Docs debt from the wave: changelog fold, coverage correction, stale non-goal
ci / checks (push) Successful in 46s
ci / corpus (push) Successful in 18s
The extension changelog's outside-edit "Unreleased" section described
the hierarchy sidebar 0.15.0 had already shipped — folded into that
entry, keeping its two specifics the entry lacked. syntax_coverage.md
carries the mop-up's correction (bucket 6 was system-function casting
types, never drive strengths; bucket 12 is six files) and is committed
as the pre-wave snapshot it is. ansi-first-port's deliberate non-goal
for virtual bus_if.mp is un-staled: the mop-up delivered it through
this feature's own gate, the narrow way the item asked for.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 15:42:28 -07:00
lucioandClaude Fable 5 852d05d9ad Release 0.16.0 — the testbench-syntax release
ci / checks (push) Successful in 52s
ci / corpus (push) Successful in 23s
release / build-and-publish (push) Successful in 4m52s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 15:34:30 -07:00
lucioandClaude Fable 5 98675c630a docs/topo.md: the testbench wave's edges
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 15:33:43 -07:00
lucioandClaude Fable 5 7f65a2449a The merged-tree pins both lanes promised each other
ci / checks (push) Successful in 48s
ci / corpus (push) Successful in 21s
The refusal pin a_comment_before_a_call_in_a_condition_is_still_refused
flips exactly as Lane B's Handshake said it should now that take_gap
and header_parens share a tree: the shape formats, the comment stays
inside the parens, fixed point asserted, plus the keymgr .cases entry.
And the standing invariant-4 template applied to the directive
capture: three (input, corrupted output) pairs — a dropped `else arm,
swapped arms, a lost `endif — each asserted rejected by the safety
net. Both were flagged by the serial round as the lead's first
post-merge task; done by the lead.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 13:43:24 -07:00
lucio 3f300fa9e9 Merge testbench-syntax serial round (directive-in-statements + take_gap)
Co-Authored-By: Claude Fable 5 <[email protected]>

# Conflicts:
#	docs/features/formatter-bug-fixes/README.md
2026-08-29 13:38:32 -07:00
lucioandClaude Fable 5 7881cc869c Directives may open inside a statement, and comments keep their owners
Bucket 7: the mirror image of directive-split — an `ifdef opening
INSIDE an assign RHS, expression or instantiation head, where all
three existing directive features trigger on a closing directive and
could not fire. The construct is captured verbatim by two mirror
recoveries sharing one capture step (statement-level first, item-level
behind it), construct_end classifying the head (Semi /
endfunction+label / Unknown -> refuse rather than guess), and
terminated_in_arm honoring both real terminator placements. Both
flagship tb.sv files needed only take_list_directives to stop
harvesting an outer region's `else as a list element. OpenTitan sweep
107 -> 100, exactly the 7 targets (chip_if.sv x2, chip_earlgrey
asic/cw340, jtag_dtm_reg_block, both top_* tb.sv), zero regressions,
corpus per-file byte-identical to baseline.

Also delivers Lane B's Handshake: take_before_open's queue drain was
necessary-but-not-sufficient — CallComments::dangling drained the
same way — both now behind Parser::take_gap (comments kept only when
span.start >= last_end()), verified by composing with Lane B's tree:
keymgr_scoreboard.sv formats, closing the last bucket-2 file.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 13:38:02 -07:00
lucio 89186a8eaa docs: move performance and topology notes
ci / checks (push) Successful in 53s
ci / corpus (push) Successful in 21s
2026-08-29 13:29:57 -07:00
lucio 27a652ee3d Merge testbench-syntax Lane B (formatter round-trip bugs)
ci / checks (push) Successful in 54s
ci / corpus (push) Successful in 21s
Co-Authored-By: Claude Fable 5 <[email protected]>

# Conflicts:
#	TODO.md
2026-08-29 12:56:47 -07:00
lucioandClaude Fable 5 d3deacf0f6 Three formatter comment bugs fixed where they lived, safety net unwidened
Bucket 2 of syntax_coverage.md: 12 opentitan files parsed but failed
the formatter's own verification. Three shapes: (A) a line comment
trailing 'end' swallowed a cuddled 'else' into the comment — cuddling
now requires no trailing line comment (block comments still cuddle);
(B) a comment inside if/while/repeat/wait/case header parens printed
after the ')' — Fmt::header_parens finds the real ')' and prints the
split comments through the shared paren layout; (C) 'default;' grew an
invented ':' — the optional colon is read from the source byte. 11 of
12 files now format and round-trip (12 -> 1 verification failures on
the sweep); the 12th is a parser bug filed as a specified Handshake
and delivered by the directive round, not edited cross-lane. verify.rs
untouched; four masked-corruption rejection pairs added per the
standing template; QA's ~30-attack sweep found zero corruption and
pinned two informational boundaries. Formatter output changed:
release must bump the workspace version (format-cache rule).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 12:55:51 -07:00
lucio 17633d2214 Merge testbench-syntax Lane A (out-of-class constraints)
ci / checks (push) Successful in 55s
ci / corpus (push) Successful in 22s
Co-Authored-By: Claude Fable 5 <[email protected]>

# Conflicts:
#	TODO.md
2026-08-29 11:11:29 -07:00
lucioandClaude Fable 5 e2c954ba77 Out-of-class constraints parse: one line, 45 files, a cascade gone
constraint C::name { ... } at file/package scope failed at the `::` —
parse_constraint's name was expect_name where the out-of-body method
path already existed; it is now parse_method_name, and nothing else
moved: the item was always a verbatim leaf, so no AST variant, no
formatter/binder/spans arm, verify.rs untouched. On the real opentitan
checkout: 45 of 45 bucket-1 files unblocked (44 fully clean, the 45th
advancing to its documented bucket-10 gap), whole-sweep failures
151 -> 107 with zero newly-failing files, and the tolerant-mode
cascade collapsing 1,349 diagnostics -> 1 across the bucket — the LSP
win the round was chosen for. Corpus gate exactly at baseline. QA
reproduced every number independently via stash before/after,
attacked the grammar widening and the verbatim byte-integrity, and
pinned the index-opacity promise with the corrected semantic test.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 11:05:34 -07:00
lucioandClaude Fable 5 e565dc0812 TODO.md: the testbench-syntax wave, planned from syntax_coverage.md
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 10:33:38 -07:00
lucioandClaude Fable 5 34b766cbef Release 0.15.0 — the interactive-latency release
ci / checks (push) Successful in 44s
ci / corpus (push) Successful in 19s
release / build-and-publish (push) Successful in 4m25s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 03:48:48 -07:00
lucio 8cdc1b3375 Merge the design-hierarchy sidebar (codex + integration round)
ci / checks (push) Successful in 47s
ci / corpus (push) Successful in 19s
Co-Authored-By: Claude Fable 5 <[email protected]>

# Conflicts:
#	crates/lucisv_server/src/main.rs
2026-08-29 03:39:31 -07:00
lucioandClaude Fable 5 651e58bfb3 The design-hierarchy sidebar: codex's feature, integrated
An instance-oriented hierarchy view in the Activity Bar —
lucisv/moduleHierarchy snapshots (schema 2: uri table, flat ranges,
derived ids; 11.6 MB -> 2.3 MB on opentitan) plus
lucisv/moduleHierarchyChanged invalidation, gated on the extension's
initializationOptions. Format 5 carries decl spans, instance
occurrences and client positions for file-scope declarations
(+1.7-1.9 % store), so a snapshot reads no files at all: handler
145-167 -> 17-20 ms settled, a save with the sidebar open 366 ->
141 ms. complete is !scanning && !must_wait, pinned. Owner UI rounds:
no hover preview, all levels collapsed by default with stable ids
across refreshes, and search over a resident flat model (freeze
diagnosed: materialized expanded tree x undebounced double
fuzzyScore x whole-tree clone per keystroke) — prebuilt lowercased
index, bitmask prefilter, top-K counting, 200-row cap with an honest
remainder, single-digit ms over a 120k-entry fixture.
LineIndex::utf16_position unifies the index's and the wire's position
math under a cross-crate agreement test.

Implementation: codex. Integration fixes + owner items: Opus dev.
QA: lead (measurement pass) + Sonnet (SHIP, independent oracles).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 03:39:06 -07:00
lucioandClaude Fable 5 37560cad5e A subsuming widen was already incremental; its word merge was not
ci / checks (push) Failing after 1m4s
ci / corpus (push) Successful in 26s
Take 2 filed the RTL didOpen freeze as a chooser bug; measuring with
the HEAD binary refuted that — scope_dirs keeps every raised dir so
subsumption is Added, and begin_widen has file-diffed against the
index since the widen round; the 1.4-1.7 s figures were cold-store.
The real cost was candidates.absorb inserting each new word into the
sorted table one memmove at a time — quadratic in the batch, 403 ms
of a 935 ms warm jump — replaced by a counted one-pass merge whose
equivalence with build's sort is structural (43 ms). Warm hw/ip jump
935/881 -> 555/564 ms (QA: 872-880 -> 535-546 from its own builds);
the residual is real work, 1 683 new files and a 325 ms word re-lex
filed as the store's FACTS_FORMAT follow-up. The two previously
accidental properties are now pinned, QA's five-mutation matrix
confirming each test binds exactly its property. TODO.md carries take
2's other findings (codeAction big-fan-out zero-offers, inlayHint at
default scope) as deferred items.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 02:52:55 -07:00
lucioandClaude Fable 5 e4407984cb Hotfix: --stdio is accepted, because real VS Code sessions send it
ci / checks (push) Successful in 1m3s
ci / corpus (push) Successful in 21s
vscode-languageclient appends --stdio for TransportKind.stdio — the
spawn the shipped extension actually makes — and the --verbose round's
strict argument parser refused it: exit 2, five crashes, the client
gives up. Nothing in the loop caught it because smoke.js and the
restart harness spawn the binary directly, never through the library.
--stdio now parses as the statement of fact it is (stdio is the only
transport), in every combination, changing nothing; near misses and
genuinely unknown args still exit 2 with the usage line, which now
names both flags. smoke.js spawns with --stdio so the library's real
spawn shape stays covered from here on.

Found live by the owner installing the hierarchy preview build.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 02:48:56 -07:00
lucioandClaude Fable 5 40094c4c4e lucisv-server --verbose: per-operation timing as a shipped toggle
ci / checks (push) Successful in 50s
ci / corpus (push) Successful in 21s
The hand-patched diagnostic build becomes a feature: --verbose gates
the timing lines (request answered / notification handled / HELD
behind a rescan / scan and widen lifecycle / flush / reindex_one, the
exact wordings of the two diagnostic builds) as LOG messages into the
client's output channel; without the flag not one line is sent and
the cost is one branch, measured unmeasurable against HEAD. Unknown
args exit 2 with usage before the transport opens. The extension
gains lucisv.verbose (default off) and its first restart-on-settings
machinery: restart.js, one serialized chain reconciling to the last
toggle, no client transition outside it — activation and deactivate
included — after QA twice caught the alternatives (a mid-start toggle
silently rejoining the stale start; deactivate's out-of-chain stop
orphaning a spawn). Headless node harness restart_test.js, 44 checks,
five mutations caught. Spawn contract amended everywhere it is
written: no args required, --verbose optional.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 01:44:56 -07:00
lucioandClaude Fable 5 829302d0bf CLAUDE.md: the 2-agent parallel-lane loop, codified
ci / checks (push) Successful in 55s
ci / corpus (push) Successful in 24s
Up to two dev/QA lanes concurrently when TOPO.md proves the features
independent (no shared edges, disjoint files; unanswerable = serial).
Each lane: own worktree off one trunk commit, a brief whose file list
is the merge contract, dev then QA in that worktree, lead review and
merge per lane with full gates on the merged tree. Wave tracking in a
TODO.md section written on trunk before branching. Distilled from the
2026-08-28 performance wave, where the shape was proven end to end.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 00:55:45 -07:00
lucio ee1efe3fb1 Merge performance-wave Lane A (prepareRename, rename, willRenameFiles)
ci / checks (push) Successful in 50s
ci / corpus (push) Successful in 20s
Co-Authored-By: Claude Fable 5 <[email protected]>

# Conflicts:
#	docs/perf/README.md
2026-08-29 00:11:42 -07:00
lucioandClaude Fable 5 1029d2f199 Performance wave Lane A: the rename family reads its fan-out
prepareRename answered F2 by reading every in-scope file (1.6-3.0 s on
opentitan, blocking the loop); it now answers from the open buffer and
the index in 139 ns, with a refusal-by-refusal parity table (7
reproduced, 4 deferred to rename, none lost). rename computes over
rename_sources — declarers, reference postings, open buffers, and,
after QA's HIGH finding gated the round, rung 6: files_spelling over
the index's reference facts (resolved or not, FACTS_FORMAT untouched),
restoring the dangling-new-name capture refusal the first five rungs
lost; the old name needs no rung and the argument is written and
pinned, QA's shadowing hunt included. 3.47 s -> 105 ms at a 7-file
fan-out, rung cost 852 us worst-case, byte-parity swept at four real
cursors and 564 offsets, ambiguity escaping to the whole scope.
willRenameFiles rides IncludeGraph::includers(): 249 ms -> 14 ms over
331 includers of 3 976 files. Accepted residue, documented: files
whose only mention of the name is inside opaque macro tokens lose one
warning flavour; the FileFacts macro census is filed as the real fix.

Dev Opus + QA Sonnet (REWORK-gate, fix, SHIP on re-verify) in a
dedicated worktree. Lead-reviewed and merged.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 00:11:13 -07:00
lucioandClaude Fable 5 36caf1dd19 Merge performance-wave Lane B (completion, documentHighlight, scope default)
ci / checks (push) Successful in 47s
ci / corpus (push) Successful in 20s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 23:58:29 -07:00
lucioandClaude Fable 5 61f345aca7 Performance wave Lane B: completion hot path, highlight fix, scope default
Completion stops parsing whole declaring files per keystroke: tier 0
slices the module header at its terminating ';' via a whitelist walk
over a bounded lex window, anchored on the index span and re-planning
whole-file on anything unrecognized (non-ANSI included); the module
table replaces a per-keystroke workspace_symbols(""). 53 -> 3.2 ms at
the empty prefix (opentitan wire 63-66 -> 13-15 ms; typing an 11-char
word 201 -> 64 ms), items pinned byte-identical.

documentHighlight answered 0 on any name the file uses but does not
declare (both cursor questions were single-file); nav gains
external_occurrences over the overlay, grouping by the whole defs()
slice, written failing-first and pinned at the two opentitan
positions over the wire.

lucisv.index.scopeDepth default 0 -> 2 (behavior change; CHANGELOG at
release): a dv/tb file now indexes its IP block (21 files / 15 ms)
instead of one file with every cross-file answer empty. Rootless
sessions no longer climb (latent unnamed-tree walk removed).

Dev Opus + QA Sonnet in a dedicated worktree; QA SHIP with one LOW
(pre-existing attribute-instance indexing gap, pinned) and one
recorded asymmetry. Lead-reviewed.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 23:58:22 -07:00
lucioandClaude Fable 5 ad27ed23dc codeAction reads the module's fan-out, not the workspace
ci / checks (push) Successful in 46s
ci / corpus (push) Successful in 20s
The owner's slow-F12 root cause: textDocument/codeAction on a module
instantiation read every in-scope file through ws.sources() and ran
the port-refactor engine over them, per cursor move — 3.1-4.6 s on
opentitan's 3 976 files, blocking the single-threaded loop so every
queued definition/hover paid the bill. Workspace::module_sources now
hands the engine the cursor modules' fan-out: declarers (units),
instantiation-edge files, references_to postings (the fourth rung —
edges_of drops owner-less file-scope instantiations, so edges alone
are not a superset), and every open buffer. 4.56 s -> 7.1 ms typical,
83 ms at a 36-file fan-out; equality with the whole-workspace
computation pinned by four dev + six QA equivalence/attack tests.
Disclosed behavior change: the answer now sees the workspace as the
index describes it, like every other index-backed answer.

Also: performance.md (full opentitan benchmark of every LSP action)
committed at the root, and TODO.md gains section 10 tracking the
performance wave the benchmark spawned (rename family, completion,
documentHighlight, scope default) with per-lane file ownership.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 22:35:00 -07:00
lucioandClaude Fable 5 bf9170a850 A scope widen indexes the folders it added, not everything again
ci / checks (push) Successful in 46s
ci / corpus (push) Successful in 20s
Every F12 jump into a new folder didOpen-widened the scope and re-ran
a full rescan of all folders accumulated so far, growing with browsing
(opentitan, warm: 120-169 ms per jump, ~90 ms of it re-opening and
decoding the whole persistent store). widen_of chooses: pure folder
adds take a widen scan over only the new files (absorbed into the live
index/candidates/includes, open buffers refreshed from held analyses,
store handle kept, no compaction); anything else still takes the whole
rescan; mid-scan defers to one whole follow-up. Jumps now cost the new
folder alone (12-44 ms flat), first definition of a session 99.7 ->
0.9 ms. IncludeGraph stores edges as the filesystem answered them and
re-spells on relearn so a newly scoped file lends its spelling to
earlier edges. Watcher-coverage narrowing documented: watcher-less
clients lose the widen's incidental disk re-read, same staleness class
as the save path since 2026-08-27. QA was stopped by the owner
mid-gates after its adversarial phases; lead gates run twice, green.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 21:36:55 -07:00
lucioandClaude Fable 5 b7a934080a Release 0.14.0 — the first-hover release
ci / checks (push) Successful in 52s
ci / corpus (push) Successful in 22s
release / build-and-publish (push) Successful in 4m54s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 20:22:30 -07:00
lucioandClaude Fable 5 172a034c67 The startup scan answers requests as it goes
ci / checks (push) Successful in 50s
ci / corpus (push) Successful in 21s
A request sent right after initialized waited out the whole startup
scan — 780 ms cold, 287 ms warm over 200 files, against 26-64 us once
the scan was done. The scan is now a value (Scan: begin/step/publish/
finish; rebuild_index_with is the same three-line loop, so one-shot
and interleaved are structurally the same code and fingerprint
identically), fed to the live index with one WorkspaceIndex::absorb
per drain — per-file merging measured quadratic, 11.7 s over 800
files — and the message queue drains between files: the first hover of
a session answers in 15.5 ms cold / 12.8 ms warm against the index so
far, open file first, scan totals inside noise. Order contract kept:
only the startup scan answers mid-way (must_wait holds requests queued
behind any rescan), scans under 64 files stay one-shot (a count, not a
clock), mid-scan rescan requests coalesce into exactly one follow-up,
shutdown stops the scan where it stands. All three tables publish
together. QA pinned the INTERLEAVE_ABOVE boundary, the absorb
duplicate-path edge and the mid-scan didOpen double-publish; the whole
pre-existing suite passes unmodified, stable over repeated runs.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 20:20:20 -07:00
lucioandClaude Fable 5 20567e1a7f The index carries every declaration's line, and hover stops re-reading files
ci / checks (push) Successful in 40s
ci / corpus (push) Successful in 18s
The owner's first-level cache, realized on the carrier the index
already had: DeclLines (name line + detail line) on every Decl/Def,
computed at index time from the LineIndex the analysis already holds —
tens of KB for 20k modules, FACTS_FORMAT 3->4, old stores discarded
whole. A closed file's hover heading now costs zero I/O (it survives
the file being deleted), and the snippet's one remaining read is
served from a bounded FileView LRU (4 entries / 8 MiB, newest kept,
dropped on set_document/close/update_one/rebuild): repeat hovers into
a 12 MB file go 5.8 ms -> ~1 us, cross-file hover means 40/157 us ->
4.7/12.9 us. Ports ride the same member entries, so their lines came
free. Stale-disk edits leave heading and snippet stale together, the
spells_exactly guard still omits rather than lies, and QA pinned the
pair. Measured and filed, not fixed here: the first request of a
session waits 287-780 ms behind the startup scan (handshake for the
next round).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 18:04:38 -07:00
lucioandClaude Fable 5 17214ac8db Release 0.13.1 — the F12-latency release
ci / checks (push) Successful in 44s
ci / corpus (push) Successful in 20s
release / build-and-publish (push) Successful in 4m37s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 16:31:47 -07:00
lucioandClaude Fable 5 d4eb8f48ff The stack fits the nesting limit by construction, on every thread
ci / checks (push) Successful in 42s
ci / corpus (push) Successful in 19s
MAX_NESTING_DEPTH turns over-deep input into a parse error only on a
stack big enough to reach level 64, and that was an unenforced README
assumption: debug frames drifted to ~94 KiB/level under rustc 1.97
(worst family nested case, 5.9 MiB at the limit), so a default 2 MiB
spawned thread aborted around level 30 with the limiter never firing.
New vlog_parser::PARSE_STACK_SIZE (16 MiB, 2.7x the re-measured worst
case) is applied at every parse-reaching site: both binaries' work
moved onto named spawned threads (a main stack is the OS's to size —
1 MiB on win32; pre-fix lucisv aborts under ulimit -s 1024, fixed one
diagnoses), rayon pool workers resized, forwarder and lsp-server IO
threads audited parse-free. Deep-nesting suites across four crates on
controlled stacks, sabotage-verified; caller-side stack contract added
to every public parse entry point's rustdoc. analyze measured at
71 KiB on a max-legal tree — no second bound needed.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 16:26:06 -07:00
lucioandClaude Fable 5 cf32e92e58 A rescan reuses what open buffers already analyzed
ci / checks (push) Successful in 46s
ci / corpus (push) Successful in 21s
A scope-widening didOpen re-parsed every open buffer's text twice —
once for its index facts, once for its completion words — 210 ms of a
223 ms rescan for one 1.4 MB top.sv. FileFacts::of and words_in each
split so their post-parse half is callable on a finished analysis
(facts_from_analysis, words_of_tokens; one implementation per path, so
the routes cannot drift), and collect_sources hands the index and
candidates builds each open buffer's held analysis instead of its
text, on the whole-rebuild path and didSave's. ~228 ms -> ~23 ms.
Equivalence pinned: encoded facts and fingerprints byte-identical
between the two routes over the corpus and 16 crafted non-corpus
shapes; unsaved-edit, didClose-revert, size-cap and large-file
threshold boundaries tested both directions. IndexEvent::Analyzed
keeps "from cache" meaning the persistent store.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 15:28:27 -07:00
lucioandClaude Fable 5 097498da23 References stop sweeping the whole open buffer per request
The open-document overlay loop in indexed_references did two index
lookups and a scope walk for every reference in every open buffer.
A spelled-name prefilter (sound: every Def is filed under exactly its
own declared name, so a mismatched name can never match the target)
plus a hoisted file_id take a 70k-reference open top from 3.2 ms to
110 us per request, both directions. In-file references and
documentHighlight batch-convert spans through the walker (1.76 ms ->
1.18 ms / 917 us on a 10k-use signal). Answers byte-identical; the
refactor-walk equivalence suite extended with a unit-vs-member
same-spelling case. Measurements also acquitted references of the
owner-reported direction asymmetry: the felt cost is the didOpen
scope-widening rescan re-parsing open buffers (210 of 223 ms), filed
as a Handshake for the next round.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-28 14:02:15 -07:00
lucioandClaude Opus 5 4f7b4a9f91 Release 0.13.0 — the responsiveness release
ci / checks (push) Successful in 49s
ci / corpus (push) Successful in 21s
release / build-and-publish (push) Successful in 4m55s
Typing no longer reanalyzes the buffer on every keystroke, cursor
answers binary-search the token stream instead of sweeping it, and
hover finally reads an old-style split port the way a designer wrote
it — header and body declaration, each with its comments.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:17:39 -07:00
lucioandClaude Opus 5 574ab833e3 Feature docs for the responsiveness round, and a perf record
Three new feature READMEs — change-debounce, port-detail-spans,
interactive-latency — each with the mandated sections, dev work logs,
QA findings and their dispositions, and the lead's review. Plus
`docs/perf/README.md`, the record of what was measured, on what, on
which machine, and with which command, so a later round can say
whether it made something faster or only different.

`topo.md` is added to the tree: the dependency topology the round was
planned against, with this round's new edges — the `detail_span` and
`symbols_named` handshake between the server and `vlog_semantic`, and
the facts-format edge to index persistence.

The perf record keeps its losses as well as its wins. A keystroke
followed by nothing now publishes at 164 ms rather than one
reanalysis, because it waits out the quiet period; a perf document
that only records improvements is not a perf document.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:16:54 -07:00
lucioandClaude Opus 5 12d0bbad51 Measure the paths a keystroke and a hover run through
Twelve `#[ignore]`d measurements, standard library only — `Instant`,
a mean over 10 to 1 000 runs and `black_box`, which is the shape this
repo already uses for perf notes. No benchmark dependency: the
workspace pins six direct ones and `CLAUDE.md` wants a written
justification for a seventh, which statistical rigor on numbers that
assert nothing does not earn.

They answer where a flush's time goes, and the answer is that lexing
and parsing are 79% of it. `analyze` is 5.5 ms of 31 ms, the lint pass
4%, and `resolve_external` — the one the plan expected to matter — is
49 µs, one part in six hundred. The breakdown sums to `Document::new`,
so nothing is unaccounted for.

They also take the numbers this round's changes are argued from: the
cost of one read and one `LineIndex` inside a cross-file hover, the
name lookup against the scan it replaced, and the token search against
the sweep it replaced.

Nothing here is a budget. A test that fails when the machine is busy
is a test that gets deleted.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:16:45 -07:00
lucioandClaude Opus 5 de8a7e129c Cursor answers binary-search the token stream instead of sweeping it
Expand-selection, on-type formatting, the completion scope gates and
the inline template trigger each walked every token in the file to
find the one at the cursor. The stream is sorted by start and does not
overlap, so the position is a binary search: 77 µs → 20 ns in a
10 000-line buffer, and 130 µs → 36 ns for completion's balanced
window, which had no upper bound and so swept the whole file to reach
a window a few dozen tokens wide.

Two primitives rather than one, and deliberately not `token_at`:
`selection.rs`'s `covers` takes `span.end` inclusively, so at a byte
two tokens share, the sweep returned the *earlier* token where
`token_at` returns the later one. Reaching for the existing helper
would have changed an answer.

No answer changes. Each swap is pinned by a test comparing the new
expression against the predicate it replaced at every byte of a buffer
written to be full of touching tokens, and the precondition they all
rest on — that the stream rises and never overlaps — is pinned
separately, so it is the test that fails first if the parser ever
changes shape.

Left alone, with reasons: signature help's paren depth is a function
of every bracket before the cursor and so is inherently a prefix scan;
`pairs.rs` is not a position query; and completion's comment gate
cannot be answered by any search of the stream, because comments are
trivia attached to whichever token happens to be adjacent. That last
one is the remaining per-keystroke whole-buffer walk.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:16:34 -07:00
lucioandClaude Opus 5 611dd23069 Hover shows a split port's real declaration, and its comments
A non-ANSI port's card used to show `data_in,` — the header line that
names it and says nothing else. It now shows two fenced sections: the
header, then the body declaration carrying the direction, the type and
the width. Go-to-definition offers both, body declaration first, so
hover and the jump agree. It works into closed files, because the
detail span travels through the workspace index.

Each section also carries the comments that document it: the comment
beside the declaration, the comment-only lines above it, and the
comment-only lines below it — all three where all three are written.
The guards are what make this safe rather than a guess. The walk above
stops at the first line that is not comment-only, so a line carrying
another port never contributes its trailing comment. The block below
attaches only when the line after it is one that positively reads as a
closer — a whitelist, deliberately, so that a line the predicate does
not recognise reads as another declaration and the comment stays with
it. Only a false "another declaration is here" is safe: it merely
declines to attach a comment, while a false "nothing here" would print
one declaration's comment on another's card.

Also: a hover into a closed file now reads that file once. The heading
line and the snippet used to take a read and a `LineIndex` each, since
neither shared the other's; a per-request memo keyed on the path
serves both, and `locate::line_number` answers from an open buffer's
existing index rather than re-reading it. On a 31.7 MB file that is
34 ms → 16.3 ms.

And `live_symbol` asks `symbols_named` for the candidates instead of
walking every symbol in the target buffer and calling
`indexed_def_for_symbol` on each.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:16:23 -07:00
lucioandClaude Opus 5 a4f23db2c7 Typing costs one reanalysis per burst, not one per keystroke
Every `didChange` used to run a full reparse, reanalysis, lint and
diagnostics publish. In a 10 000-line buffer that is 31 ms of work per
keystroke, nearly all of it thrown away by the next one.

The text stays exactly current after every notification — incremental
sync is applied immediately, and while a change is pending the buffer
the server holds *is* the pending text. Only the analysis is deferred,
and it is flushed by the first thing that needs it: the next request,
the next non-`didChange` notification, or a 150 ms quiet-period timer
in the message loop. Requests therefore see exactly what they saw
before; nothing answers from a stale buffer.

The invariant this replaces was "one didChange = one set_document =
one generation bump". It is now one *flush* = one `set_document` per
dirty buffer. The observable consequence is that intermediate
diagnostics states are no longer published, which the e2e test pins:
what is drawn is always a state the buffer really passed through,
there are simply fewer of them.

Closing a buffer drops its pending text before the flush rather than
after it, so a file closed mid-edit is not analyzed and republished
for nobody a line before its squiggles are cleared.

Also measures it over the wire, against the shipped binary: a burst of
ten keystrokes produces one `publishDiagnostics`, counted at the drain
rather than reasoned about. The burst is measured last, because every
`wait_for` accepts any publish and an earlier position would let a
second one be absorbed by the next row's wait and never counted.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:16:10 -07:00
lucioandClaude Opus 5 d94f9e3de0 Non-ANSI ports carry where their declaration is completed
A port declared the old way is one symbol named in the module header
and finished in the body by `input signed [31:0] data_in;`. The binder
already merged the two; what was missing was a record of *where* the
declaration is completed, so everything reading the symbol saw only
the header's bare `data_in,`.

`Symbol` and the index's `Def` gain `detail_span`, set by the binder
when a body port declaration resolves to a port already declared in
that scope — first writer wins, so a header naming a port twice stays
deterministic and is the linter's to complain about. Old-style task
and function arguments take the same path: the binder performs the
same merge for them, so they are not special-cased.

The persisted facts record grows two numbers per declaration, written
unconditionally so the stream stays flat. `FACTS_FORMAT` moves 2 → 3
because a store written before this cannot be read after it: only the
last declaration in a record is short enough to fail `done()`, and
every earlier one would be read field-shifted by two — a cache handing
back wrong spans, which is the shape the safety invariants exist to
catch. A store from the old format is now discarded whole.

Also: `Semantics::symbols_named`, a name-sorted side table of symbol
ids searched with two `partition_point`s, so looking a name up is a
binary search instead of a walk of every symbol. Stable-sorted, so
symbols sharing a name keep declaration order and the lookup is an
identity against the scan it replaces. A side table rather than a map
keyed by name, because `Semantics` is cloned per document and need not
hold a second copy of every name it already has.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-28 03:15:58 -07:00
lucioandClaude Fable 5 94b130aca1 Release 0.12.1 — hover shows the declaration itself
ci / checks (push) Successful in 48s
ci / corpus (push) Successful in 22s
release / build-and-publish (push) Successful in 5m0s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 22:35:56 -07:00
lucioandClaude Fable 5 efe67bde65 Hover shows the cross-file declaration itself, not just where it lives
ci / checks (push) Successful in 48s
ci / corpus (push) Successful in 21s
The Definition::External card now renders the declaration's source
line(s) fenced under the "declared in file:line" heading — direction,
type and width for a port, the header line for a module, the
declaration line for package members. No facts change: snippets are
fetched at hover time, from the live buffer via nav's logical matcher
when the target is open, from disk (what the index was built from)
otherwise. A boundary-checking guard (spells_exactly) drops the
snippet rather than ever showing a wrong line — QA's attack proved
prefix matching alone was forgivable (addr vs addr2) and the fix is
pinned. Caps at 5 lines / 400 chars with notes. 18 new tests.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 22:32:59 -07:00
lucioandClaude Fable 5 e70d979e51 Release 0.12.0 — the indexed-navigation release
ci / checks (push) Successful in 46s
ci / corpus (push) Successful in 21s
release / build-and-publish (push) Successful in 4m58s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 21:39:02 -07:00
lucioandClaude Fable 5 b2d778eb8d Indexed references: postings replace the per-request refactor walk
textDocument/references now reads declaration-to-occurrence postings
merged in WorkspaceIndex from compact per-file reference facts, with
open buffers overlaying live semantics — 0.062 ms/request over 820
files vs 21.7 ms for the old Workspace::sources() walk (~350x). The
walk stays as rename's engine and the equivalence oracle in tests.
FACTS_FORMAT 1->2 discards v1 caches whole. Cursor lookups
(symbol_at/reference_at/token_at) and macro-define lookup move to
binary-searched sorted tables; include definition inspects only the
cursor's line. Ambiguity refusals preserved throughout.

External dev: codex. Lead-reviewed, gates re-run, probe reproduced.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 21:36:01 -07:00
lucioandClaude Fable 5 27fc216df3 Marketplace page: absolute changelog link — vsce cannot resolve relative
ci / checks (push) Successful in 44s
ci / corpus (push) Successful in 20s
release / build-and-publish (push) Successful in 4m37s
vsce package validates README links and auto-resolves relative ones
only for GitHub/GitLab repositories; the Gitea remote is neither, so
the relative CHANGELOG.md link failed the v0.11.0 release build.
Absolute git.luci.ooo URL instead, the same convention the page's
images already use (the Marketplace's own Changelog tab is unaffected
— it reads the file directly). Reported by the owner from the failed
workflow log.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 19:46:49 -07:00
lucioandClaude Fable 5 4665641e42 Release 0.11.0 — the large-workarea release
ci / checks (push) Successful in 45s
ci / corpus (push) Successful in 20s
release / build-and-publish (push) Failing after 4m12s
Version bump (workspace + extension), the root CHANGELOG section
covering the six rounds (folder scope, incremental index + edge
tables, persistent cache, large-file mode, size cap + counting bar +
output log), the extension changelog's Unreleased flipped to 0.11.0,
and the Marketplace page's release-time pass: the Large workspaces
section drops its coming-soon framing, the stale Workspace
intelligence rows now describe the shipped scope model and counting
bar, and 0.11.0 highlights join the page. The scope-default behavior
change and its one-line migration are called out in the CHANGELOG.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 19:17:31 -07:00
lucioandClaude Fable 5 bc606dd6bd Large-file fast path: 100 MB netlists open in 40 ms
ci / checks (push) Successful in 45s
ci / corpus (push) Successful in 21s
Owner-requested round, the last of the large-workarea wave. Above
lucisv.largeFile.threshold (4 MiB default, 0 disables) a buffer opens
as a line index and nothing else — no lex, no parse, no semantics, and
its path removed from the index sources so nothing describes it by
stale disk bytes. Viewport highlighting lexes only the requested
window (snap to a line boundary, budget-bounded backward comment scan,
imperfection documented); semanticTokens/full answers the spec's
cancellation errors because the shipped VS Code binary marks tokens
complete on ANY non-error answer and never asks for ranges again —
settled by reading the bundle, verified independently by QA, pinned
with the client-library citations. Same-file definition/references
shipped on measurement (worst 37 ms vs the 150 ms budget); every
other handler answers as the empty file by construction; formatting
alone says why aloud. Two client facts recorded: VS Code never syncs
files over 50 MB, and above 20 MB our viewport tokens are the only
color.

QA rejected the first cut on the round's true shape — thousands of
tokens on one long line went quadratic through per-call UTF-16
conversion (7.86 s to color one 269 KB line). The fix adds a monotonic
PositionWalker to convert.rs (restart-on-backwards proven load-bearing
by the out-of-order tail-comment shape), adopted at three sites for
546x/759x on the probes — and it fixed ordinary files' semantic
tokens too (2.06 s to 232 ms on a one-line buffer), a cost the normal
path had always paid. Probes are now normally-running gates with 4.5x
margins, walker-vs-per-call equivalence swept over gnarly fixtures
and adversarial ping-pong.

51 tests added across both rounds (dev 43+5, QA 6+3, minus overlaps),
2 ignored probes. Completes the owner's large-workarea requests.

docs/features/large-file-mode/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 18:58:17 -07:00
lucioandClaude Fable 5 5e98b1a669 Marketplace page: the large-workarea wave documented, changelog added
ci / checks (push) Successful in 43s
ci / corpus (push) Successful in 21s
Owner-requested docs round, scoped to editors/vscode. The README's
settings table gains the seven new keys (index.scope/scopeDepth/
maxFileSize/logFiles/persist/cachePath, largeFile.threshold) with
their honest notes — scope-relative answers and the one-line
migration, the cap's open-buffer exemption, viewport-only highlighting
above the threshold — plus the formatOnSave tab-size caveat, and a new
'Large workspaces' section marked as coming in the next release
(nothing claims the wave as shipped; the 0.10.2 highlights and feature
tables stand as released). New editors/vscode/CHANGELOG.md gives the
Marketplace its Changelog tab: an Unreleased section for the wave and
condensed extension-user entries for every release 0.2.0 through
0.10.2, derived from the root changelog. Every setting name verified
against package.json; every claim traced to a feature README (the
claim-by-claim table is in the dev report); the two perf claims
qualified with their build profile by lead review.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 17:47:55 -07:00
lucioandClaude Fable 5 2e258df9a7 vlog_parser: the defines round-trip pieces the cache commit left behind
ci / checks (push) Successful in 41s
ci / corpus (push) Successful in 20s
DefineTable::from_entries and the PartialEq/Eq derives on
Define/DefineTable belong to the index-persistence round (e4b1f55) —
its facts.rs references from_entries — but the lead's explicit-path
staging missed the vlog_parser crate, so e4b1f55 does not build on a
clean checkout. Caught by the next round's dev noticing an uncommitted
change it did not make. The working tree was always green, which is
why every gate passed locally; the remote CI on e4b1f55 is the run
this fixes.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 17:25:19 -07:00
lucioandClaude Fable 5 e4b1f55c12 Persistent index cache: a half-indexed workarea resumes where it stopped
ci / checks (push) Failing after 8s
ci / corpus (push) Failing after 5s
Owner-requested round. Every parsed file's FileFacts record is written
through to an index-cache store (append per file, atomic compaction at
scan end — a crash loses at most the file in flight), keyed by a
content hash that is the whole key: no mtime fast path, by measured
argument (6 ms of a 181 ms warm scan, and unsound against save-time
write-through). On reopen, hits skip parsing and the resume is
visible — cached: vs indexing: log lines, the bar counting through
hits, and an end message saying how many came from cache. Warm rescan
322 to 179 ms release, 1.5 s to 0.76 s debug; 910 KB store for the
860-file corpus. Location: lucisv.index.cachePath > the extension's
context.storageUri via initializationOptions (the one extension.js
change) > the OS cache dir keyed by workspace identity > nowhere;
lucisv.index.persist (default on) gates both directions immediately.

The cache is a performance artifact, never a correctness input, and
after the fix round that promise is total against everything but
intentional forgery — which the threat model now formally excludes
(same-user disk; a keyed MAC would be theater): a per-record checksum
drops every corrupt-but-parseable line (poisoned and reforged shapes
both pinned so the checksum is never mistaken for a MAC), first-writer
initialization is a create_new claim with structural 100/100 survival,
and a torn multi-byte tail costs exactly the torn record (0 of 583
offsets lose more). Old-format stores discard wholesale. Load==fresh
fingerprint equality swept over the corpus.

45 tests added across the main and fix rounds (dev 33+2, QA 9+3, one
QA test-construction bug self-caught), 2 ignored probes.

docs/features/index-persistence/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 16:33:52 -07:00
lucioandClaude Fable 5 5e4aa7bd6f Incremental indexing + the edge tables: one file changed, one file merged
Owner-requested round. WorkspaceIndex::update_file/remove_file replace
one file's contribution without reading or parsing anything else;
Server::reindex_one takes the fast path for a didSave of one held file
or a one-file watcher event (33 ms vs 1.5 s on the corpus, 45x), with
everything else — settings, scope, filelist, multi-file events —
keeping the full rebuild, pinned by a trigger-table test. FileIds stay
sorted positions by deliberate deviation: renumbering through the one
merge both finish and update_file end in makes build(W) byte-identical
to build(W minus F).update_file(F) — fingerprint equality, attacked by
QA across long interleaved sequences, disambiguation flips, define
shadowing and the ghost hunt (the affected-keys union reads old and
new records both). The per-file FileFacts the index retains are the
documented memory cost (~1.4 MB on the corpus).

The two oldest filed Handshakes land: instantiation and inheritance
edge tables, built by the byte-for-byte moved census walks, turn
codeLens counts (92 ms to 0.26 ms), incomingCalls and typeHierarchy
subtypes into lookups — census policies pinned unchanged at both the
consumers and now the source. Counts are as of the index, not of
unsaved keystrokes: the freshness delta is documented and pinned from
both sides. Saves no longer raise a progress bar; generation and lens
refresh still ride. Round 18's three inherited scope obligations are
pinned permanent.

36 tests added (dev 27 + QA 9). Left open, filed: wholesale republish,
Candidates re-derivation cost, incremental removal vs include
re-resolution.

docs/features/incremental-index/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 14:35:27 -07:00
lucioandClaude Fable 5 7266b13702 Index scope: open-file-first, folder-scoped by default
Owner-requested round. The scope ladder: a filelist still defines the
whole project and outranks everything; lucisv.index.scope=workspace
restores the walk-the-roots behavior (the same function, not an
equal-output one — pinned); the new default walks only the union of
folders a buffer has been opened from, each raised
lucisv.index.scopeDepth ancestor levels (default 0), clamped at the
deepest containing root. Opening a file outside the scope widens it
and reindexes through the existing progress/generation machinery;
scope grows only along the open axis within a session. Cross-file
answers are scope-relative and the docs say so loudly, with the
one-line migration in the setting description.

The round also closes indexing-ux QA's MEDIUM builder footgun:
IndexBuilder::finish now sorts and dedups before assigning FileIds, so
no insertion order can reach the result — pinned by a permanent
three-order fingerprint test — which makes feeding open files first
provably a progress nicety. 151 existing tests swept mechanically
(QA sampled 40+ sites: constructor swaps only); lead fixed the one
vacuous tail QA found plus two premise/comment hygiene items.

19 tests added. Known deltas documented: a root's .gitignore does not
reach a walk starting below it (filed against lucisv_core); rootless
depth-0 keeps its flat read; startup index is empty until the first
didOpen.

docs/features/index-scope/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 13:12:27 -07:00
lucioandClaude Fable 5 8c8cfc538e Indexing UX for large workareas: size cap, counting bar, output log
ci / checks (push) Successful in 44s
ci / corpus (push) Successful in 21s
Owner-requested round. lucisv.index.maxFileSize (default 1 MiB, 0
disables, junk values fall back to the default — misparse must never
un-cap) skips walked files at one fs::metadata call before any read;
open buffers are always served uncapped, a cap change rescans like
exclude does, and the cap reads consistently through every sources()
consumer — documented per consumer, with the write-path warning gap
(a rename silently leaving a capped file stale) filed as a follow-up.

The indexing bar now counts: $/progress reports '137/860 path' with a
monotonic percentage over the post-exclude post-cap denominator,
throttled to ≤1000 reports per rescan with the last file always
reporting. Enabled by vlog_semantic's new IndexBuilder (add_file/
finish) with build() redefined as the loop over the newly-exported
index_order — the FileId ordering rule is now a call, not a comment.
QA proved both production callers order correctly; hardening the
builder against out-of-order future callers is round 18's acceptance
test. lucisv.index.logFiles (default on) streams 'indexing: path' and
cap-skip lines to the editor's Output panel at LOG level; the skip
count survives in the end message when logging is off. Measured
overhead ≈2.6% on the 860-file corpus; 0 corpus files exceed 1 MiB
and the default-capped index is pinned identical to uncapped.

21 tests added + QA's attack set + the lead's human_size boundary fix
('1024.0 KiB' can no longer be printed for a byte short of a MiB).

docs/features/indexing-ux/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 11:56:30 -07:00
239 changed files with 99137 additions and 3017 deletions

No files matched your search

+5
View File
@@ -43,7 +43,12 @@ jobs:
run: tools/prune_release_assets.sh dist "${GITHUB_REF_NAME#v}"
- name: Extract the release notes from CHANGELOG.md
run: tools/release_notes.sh "${GITHUB_REF_NAME#v}" > dist/RELEASE_NOTES.md
# LUCISV_API_URL is an optional repository Actions variable naming a
# direct http://host:port for the Gitea API, so the uploads do not go
# through Cloudflare's 100-second origin timeout (0.29.0 and 0.30.0
# both died there with a 524). Unset, the public URL is used.
- name: Create the release and attach the artifacts
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
LUCISV_API_URL: ${{ vars.LUCISV_API_URL }}
run: tools/publish_release.sh "$GITHUB_REF_NAME" dist
+2
View File
@@ -5,3 +5,5 @@
/.lucisv_cache
/.score-results.tsv
.DS_Store
/.zcode
/.claude
+949
View File
@@ -4,6 +4,955 @@ 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.33.0 — 2026-09-02
### Assertions are code now
`property`/`sequence` declarations and concurrent assertions (`assert`,
`assume`, `cover`, `restrict property`, `expect`, `cover sequence`,
`default disable iff`) were verbatim text: kept byte for byte, invisible
to everything else. They are real nodes now — every sequence and
property operator (`##`, `[*n]`, `|->`, `|=>`, `throughout`, `within`,
`intersect`, `until`, `implies`, `iff`, `nexttime`, `always`,
`eventually`, `first_match`, `accept_on`…, property `if`/`case`, typed
formals, local variables, match items) with the LRM's precedence, no
new reserved words, and a byte-exact fallback for anything the grammar
cannot take (it fires on none of 4 792 corpus and opentitan files).
- **Rename and references see inside assertions.** A signal named only
in a property is renamed with its declaration; a property's formal is
scoped to the property. Anything that still falls back warns instead
of staying silent.
- **Formatting**: one rule — the spec's top-level `|->`/`|=>`/`##`/
`and`/`or` break one per line when the spec does not fit; everything
else inline. 13 corpus and 36 opentitan files move, all inside
assertion text; every `` `ASSERT* `` macro invocation is
byte-identical.
- Properties and sequences appear in document symbols; `undriven-net`
sees a net driven or read inside an assertion.
- The index store format changed; it rebuilds once after updating.
## 0.32.0 — 2026-09-02
### `bind` directives mean something now
- **Bind targets are real.** `bind top.gen[0].u_core chk u_chk (.clk(clk));`
parses and formats with its indexed path; a lone target
(`bind prim_fifo_sync …`) is a reference to the module, so go-to-
definition and hover work on it. An instance path records nothing —
no file knows an elaborated hierarchy, and a guess would be wrong.
- **Bind connections resolve where the LRM says they live**: the
`.port` half against the module being bound in, the expression half
in the *target* module's scope first (then the workspace, then the
scope the directive is written in). Hover on `.x(top_sig)` in a bind
finds `top_sig` in the target.
- The index store format changed (`FACTS_FORMAT` 15); it rebuilds once.
### Two macro-and-directive shapes that used to leave a file unformattable
- **A spaced macro call in an expression** — `assign x = \`WIDTH (a + b);`,
a parameter override `` `MACRO (1) `` — keeps the author's space
between the macro name and its `(`. The gap is token text (a macro
defined with formals reads it differently), so the formatter keeps
it rather than guessing; the safety net still refuses either
rewrite.
- **A conditional directive inside a connection value** — `.a(` ⏎
`` `ifdef X `` ⏎ … ⏎ `` `endif `` ⏎ `)` — no longer turns the whole
instantiation into opaque bytes: the directive region is kept
byte-for-byte as a verbatim value, and the instantiation keeps its
edge, code lens, hierarchy entry and port references. In opentitan
the two `padring` instantiations in `chip_earlgrey_{asic,cw340}.sv`
lay out canonically and gain their edges; the `` `ifdef `` that
splits two instantiation *heads* (`tb.sv`) stays as it was.
### Editor
- **`lucisv.instantiate`** — an execute command
(`[uri, position, module]`) that inserts the same instantiation
skeleton the inline ghost offers, as plain text through
`workspace/applyEdit`. For clients without inline completion; the
Neovim README shows the keymap.
## 0.31.0 — 2026-09-02
### Comments are never dropped — now at every gap
A comment written between two tokens that no AST node owned was never
deleted, but it was printed one node later, and the safety net refused
the whole file for it (exit 2, no output). Three rounds had filed their
leftovers (52 covergroup gaps, 41 fragment gaps, 40 constraint gaps) and
plain RTL had never been measured. This release gives every such gap an
owner: about seventy named comment slots across expressions (`q[/*c*/ i]`,
`pkg /*c*/ ::name`, `x /*c*/ inside {…}`, casts, unary/postfix operators),
statements (`if`/`case`/`for`/`foreach`/`do…while` headers, `@`/`#`
timing, the gap before every `;`, block and generate labels) and
declarations (qualifier runs like `pure /*c*/ static`, function/task
headers and ports, module/package/class headers, typedefs, enums,
structs, declarators, port lists, connections, instantiations).
Four exhaustive gap fuzzers — a `/*C*/` in every inter-token gap of
fixture sets for covergroups (329 gaps), fragments (153), constraints
(395) and ordinary RTL (352) — all format and re-format identically, and
are the regression gate from here on. The formatter's output for every
comment-free construct is unchanged: all 860 corpus files and 3 975
opentitan files are byte-identical to 0.30.0. `verify.rs` is untouched;
ten new attack pairs assert a comment moved across any newly slotted
token is still refused.
- **Escaped names inside scoped names** (`\my-pkg ::\state-t` as a
type, an instantiated module, a `bind` target) now keep their
terminating space instead of being refused.
### Editor
- **Go to definition on a macro use** (`` `WIDTH ``, `` `uvm_info ``)
jumps to the `` `define`` — the file's own definition first, otherwise
every workspace candidate the include graph cannot rule out; nothing
for a macro nothing defines.
- **A cast's type is a reference.** `state_t'(0)` and `pkg::t'(x)` now
light up find-all-references, go-to-type-definition and rename of
the typedef (`FACTS_FORMAT` 13 → 14: the index rebuilds once).
- **Rename warns about what it could not finish.** A `u_x.sig` whose
module is indexed nowhere is left unchanged and now *named* — one
line per file and unit — instead of silently skipped.
## 0.30.0 — 2026-09-02
Two lanes, run in parallel: semantic lints on by default, and the
vendor/formal collateral grammar.
### Semantic lints on by default
`unused-signal`, `undriven-net` and `multiply-driven` shipped off
because a per-file analysis cannot see a signal read or driven from
another file's hierarchy. The index now carries a per-file identifier
census (`FileFacts::words`, `FACTS_FORMAT` 12 → 13 — one harvest,
which also builds the completion word table so the server no longer
re-lexes every file at startup: scan time −28 %), and the linter gains
a mention oracle: `unused-signal` and `undriven-net` say nothing when
the name is mentioned in any other indexed file. The three rules are
on whenever an oracle exists — always in the editor, and in the CLI
when it walks a project — and stay off for a single file or stdin.
With them came the missing off switch: `[lint] select = […]` /
`ignore = […]` in `lucisv.toml` (CLI flags win key by key) and
`lucisv.lint.select` / `lucisv.lint.ignore` in the editor.
Measured: corpus `unused-signal` 52 → 44 and `undriven-net` 3 → 0 with
every silencing hand-checked as a genuine cross-file use, nothing
added; across opentitan — lint-clean under its own tools — 14
findings, spot-checked true. Store +14 %.
### Vendor and formal collateral grammar
The gap analysis ranked `specify`/UDP/`checker`/`interface class` as
Medium on the strength of "13 corpus checker files"; the round's
census found those were UVM protocol-checker *filenames*, and that
every construct here has zero declarations in the corpus and in
opentitan. So this is a completeness round for vendored cell, IO and
memory models and formal collateral — and it is proven
output-neutral: formatted output is byte-identical for all 860 corpus
files and all 3 975 opentitan files against the previous release.
Five keywords reserved on a measured zero-collision census
(`checker`, `endchecker`, `config`, `endconfig`, `library`); five
deliberately not (`expect` has 41 real task-call sites — the statement
form is recognised only when its parentheses hold a sequence operator).
`specify … endspecify`, `primitive … endprimitive` with `table`,
`checker … endchecker` and `config … endconfig` parse as opaque blocks
that format byte-for-byte and fold in the editor; `library …;` lines
parse; `specparam` is a real declaration that hovers and resolves;
`alias a = b = c;` parses with every term a reference; `union tagged`
formats; `interface class … endclass` parses as a class and
`implements` now contributes supertypes to the type hierarchy. Filed:
the `tagged` pattern grammar, checker/UDP names as instantiable
symbols, the reverse `implements` edge.
## 0.29.0 — 2026-09-02
Fragment mode, and `` `define`` continuation.
The gap analysis had this one wrong in an interesting way: class-body
and module-item `` `include`` fragments already parsed, because the
file-scope item loop *is* the class-item loop. What did not parse were
three narrower shapes — a bare statement list, an enum-member list
(riscv-dv's `CUSTOM_1,` file, included between enum members), a
covergroup-item list — and all three failed at one call site. They are
now `SourceFile::fragment`, detected by a whole-file rule that cannot
misfire on a valid file: the first structural item failed (directives,
macros and stray `;` do not count, and a tolerant parse that quietly
recorded a diagnostic counts as failed — an existing parity test
caught `if … else` reading as a generate-if to one parser and a
statement to the other), the file does not open with a design-unit
keyword, and a shape consumes the file to its end, tried
narrowest-first because the wider grammars mis-read the narrower. A
fragment formats at indent zero through the existing printers, its
declarations bind, and its enum variants are deliberately *not*
exported (a package that includes the fragment is the real home of
`CUSTOM_1`; resolving it elsewhere would name something that does not
exist).
The other opentitan `.svh` that would not parse was never a fragment
problem: a `` `define`` whose formal-argument list spans two lines with
no backslash, which every tool accepts. The lexer now continues such a
directive until the list closes.
Opentitan: 12 → 10 failing files, exactly the two predicted, nothing
else moved. Corpus baseline 813 → 814 of 820. Comment-gap fuzzer:
every remaining failing slot proven to fail identically outside a
fragment (§2.9-22). Formatter output unchanged for every file that
parsed before.
## 0.28.0 — 2026-09-02
Covergroup bodies — round 2 of coverage_gaps C1, closing it.
`covergroup … endgroup` was a flat token scan into verbatim text: no
name span, no coverpoint names, nothing inside bound. Now a covergroup
is a real node — the header with its argument list, `with function
sample(…)` and `@(…)` event, labelled and unlabelled coverpoints,
`bins`/`ignore_bins`/`illegal_bins` with arrays, value lists, `$`,
transition lists (`=>`, `[*n]`, `[->n]`, `[=n]`), `default` and
`default sequence`, `with (…)` filters, `wildcard`, `iff`, crosses with
`binsof … intersect … && !binsof` select expressions, `option.`/
`type_option.` assignments, `` `ifdef `` arms, and the `endgroup : g`
label — behind the same rewind snapshot as constraints, so an unknown
shape restores both comment buckets and re-runs the old scan character
for character. No keywords were reserved. Two disambiguations are by
position, the LRM's own rule (a coverpoint bin's `(…)` is a transition
list, a cross bin's is a select expression), which replaced a lookahead
scan and took opentitan's fallback count from two to zero.
Two guards were added to shared expression machinery and are the
round's one risk, stated plainly: an index cannot begin with `*`, `->`
or `=` (so `1'b1[*5]` reads as a transition repeat), and a bin's own
`with (…)` filter is not consumed as an array-method iterator
argument. The whole corpus and the whole opentitan tree re-verified
under both.
Layout is canonical (one cover item per line, `{ }` bin bodies like
constraint sets, the label at the header's column); `verify.rs`
untouched, twelve attack pairs. The comment-gap fuzzer was built in
from the start: 329 gaps, the 52 that fail are all the shared-machinery
slots already filed as §2.9-22 — and that classification is asserted by
a test that runs each shape outside a covergroup and requires the same
failure. Every sampled expression, bin value and `iff` binds to the
class's properties; `cg_inst.cp` resolves cross-file; renaming a `rand`
field rewrites the coverpoints that sample it. `FACTS_FORMAT` 11 → 12.
Opentitan: 544 of 544 covergroups structured, 87 of 87 DV covergroup
files idempotent with comment streams byte-identical, 81 of 3 963 files
re-laid-out and every one verified, the sweep's failure set and per-file
diagnostics identical. Corpus: 10 files change layout, all verify;
+1 139 references, 1 135 answered.
## 0.27.0 — 2026-09-02
Constraint bodies — round 1 of coverage_gaps C1, the DV correctness
item.
`constraint c { … }`, `constraint C::c { … }` and `randomize() with
{ … }` were opaque verbatim text: no name span, nothing inside bound,
so renaming a `rand` field left `constraint c { user_id < 5; }` as
non-compiling code with, at best, a generic warning. Now a constraint
declaration is a real node — `soft`, `dist` (`:=`/`:/`), `->`
implication, `if`/`else`, `foreach`, `solve … before`, `unique`,
`disable soft`, `` `ifdef `` arms — and the parser attempts the
structured body behind a rewind snapshot: any shape it does not know
restores the cursor *and both pending-comment buckets* and re-runs the
verbatim capture character for character, so an unknown body is the
old behavior, not an approximation. No keywords were reserved —
`soft`/`dist`/`solve`/`before` are matched by text — so `logic before;`
keeps working and the editor grammar is untouched.
Layout is canonical: one constraint item per line, `}` at the header's
column, `dist` weights broken like a braced list; a `with` block keeps
its one-line-or-not shape. `verify.rs` untouched; the constraint attack
pairs re-derived and extended (a dropped `soft`, `:=` for `:/`,
swapped `solve`/`before`, a dropped `else` set, a flattened
implication, a comment moved across `}`). Every operand binds to the
class's properties (`this.` implicit; `foreach` variables nest; a
`with` block resolves against the randomized object's class first), so
hover, definition, references and rename reach inside; renaming a
`rand` field from its declaration rewrites its constraint uses in-file
and cross-file. `FACTS_FORMAT` 10 → 11. Lint rules read constraint
operands instead of treating the body as opaque.
QA's finding — a comment right after `soft`, `dist`, `solve`,
`before` or the constraint name was dropped, so the safety net refused
the file — was answered with an exhaustive gap fuzzer (a block comment
in every inter-token gap of fifteen fixtures, 358 gaps, format and
idempotency both demanded) and fourteen named comment fields; the
forty gaps that remain are shared expression machinery that behaves
identically outside a constraint (`q[/*c*/ i]`, `inside {[/*c*/ 0:3]}`,
scoped-name chains) and are filed as a parser-wide round. No opentitan
file hits one.
Opentitan: 1 993 of 2 009 constraint bodies parse structured (the 16
fallbacks are macro-item bodies and non-LRM shapes), all laid out,
token-equivalent and idempotent; 48 DV files across 16 IPs re-format
idempotently with their comment streams byte-identical; the sweep's
failure set unchanged and the tolerant-diagnostic count per file
identical. Corpus: 37 files change layout, all verified; +1 646
references, 84 % answered. Covergroups are round 2.
## 0.26.0 — 2026-09-02
Two lanes, run in parallel: member completion, and escaped identifiers.
### Member completion — a dot means members
Typing `item.` used to get the whole-index dump — every keyword and
every project word, capped at 512 — because the empty word after a dot
fell through to the ordinary tiers. Now the answer after `.` or `::` is
exclusively the members of what precedes it: a class's properties and
methods (inherited ones included, through the same base chain hover
follows), a struct's fields (`reg2hw.ctrl.` via the synthesized nested
keys), an interface's signals, modports and clocking blocks (`vif.`,
`vif.cb.`), a package's members (`tlul_pkg::`), `this.`/`super.`. The
walk is published from `vlog_semantic` (`Semantics::member_site`,
`WorkspaceIndex::members_of_chain`) and the resolver's own member
resolution is rewritten to call it, so the popup cannot list a name
hover would not resolve. A dot inside an instantiation's `(…)` or
`#(…)` lists the module's ports or parameters, already-connected ones
dropped. `.` and `:` are trigger characters. An unreadable head answers
nothing — never the dump. Cheaper than what it replaces: 6–62 µs
against 212 µs.
QA's finding, fixed at the root: `#(.` offered header `localparam`s
because the binder had discarded the `parameter`/`localparam` keyword.
`SymbolKind::LocalParam` is now bound from the keyword (sticky across
continuation entries, as the ghost skeleton already read it), shows as
"localparam" on the hover card, is excluded from override lists only,
and still resolves for hierarchical reads. `FACTS_FORMAT` 9 → 10.
### Escaped identifiers format
`wire \my-signal ;` was refused outright: the lexer ends an escaped
identifier before its terminating whitespace and the formatter emitted
every name bare, so `\my-signal;` re-lexed as one token and the safety
net — correctly — rejected the file. Fifty name-emission sites now go
through one choke point that writes the IEEE 1800 §5.6.1 space;
`verify.rs` untouched, eight masked-corruption attack pairs; the corpus
is byte-identical by construction. Netlists and generated RTL format.
One shape is refused rather than corrupted and filed (`\my-pkg ::x`,
whose segments the parser joins).
## 0.25.0 — 2026-09-01
Struct members — `s.field`, `reg2hw.ctrl.q` and the anonymous
aggregates resolve.
`typedef struct packed {…} bus_t; bus_t s; s.field` recorded nothing.
The in-file gap was a single resolver gate: a struct typedef's member
scope already existed, hung off the typedef, and lookup simply never
entered it. Now any symbol whose child scope is a struct scope — a
typedef, an anonymous `struct {…} s;` declarator, or an inline nested
field — answers member access with one rule, and fields carry their
own type so `s.hdr.addr` hops through a member. Unions are the same
node. Anonymous `enum {A, B} x;` variants land in the enclosing scope
exactly like typedef'd ones (the open handshake since types-decls).
Across files, struct members are exported under the typedef's name,
and inline nested fields — the shape opentitan's generated register
packages use everywhere — under a synthesized `owner.field` key
carried as the field's type, so `hw2reg.status.txfull.d` lands on
`txfull`'s `d` and never `rxfull`'s two lines up (bare-name keys would
collide on `q`/`d`/`qe` in every register package). Same-named struct
typedefs in two packages answer ambiguity, never a guess. `FACTS_FORMAT`
8 → 9 (older stores rebuild once); `typeDefinition` works inside a
`typedef struct` body.
Unresolved names on the corpus fell 1 203 → 1 162; its store shrank
1.1 % (a resolved local fact encodes smaller than the external
candidate it replaced) while opentitan's register packages grow theirs
4.3 %. QA: 28 live opentitan probes across six IPs with three planted
sibling-field pairs, zero wrong answers, hover under 0.5 ms. Known
remaining shape: an indexed link mid-chain (`reg2hw.key_share0[i].q`),
pre-existing and filed.
## 0.24.0 — 2026-09-01
Interface semantics — interfaces, modports and clocking blocks become
symbols, and `vif.sig` crosses files.
An interface was indexed as a `Module` (its hover card said "module"),
modports and clocking blocks declared nothing, the signal names inside
them were not references, and one export line kept an interface's
signals out of the workspace's member table — so `virtual my_if vif;
vif.sig` resolved only when the interface was in the same file. Now:
`SymbolKind::{Interface, Modport, Clocking}`; an interface exports its
signals (they are its surface — a module still exports ports and
parameters only); every name inside a modport or clocking block is a
reference to the interface's signal, method or block; the modport half
of `bus_if.mp` in a port type or a `virtual bus_if.mp` handle resolves
to the modport; a clocking block carries its enclosing interface as its
type, so `vif.cb.data` reaches `data`'s declaration through the member
chase unchanged. `FACTS_FORMAT` 7 → 8 (older stores rebuild once).
Interfaces stay in the completion/ghost module table, the design
hierarchy and the port refactorings — pinned unchanged — while hover,
outline and completion kinds become honest.
Unresolved names on the 860-file corpus fell 1 256 → 1 203, the first
movement in three rounds — the `@(cb)` and `cb.data` names that had
nothing to bind. Store +1.2 %. Renaming a modport from its
type-position use now rewrites its declaration and every use. QA: 17
live opentitan probes, zero wrong answers, every hover sub-millisecond.
## 0.23.0 — 2026-09-01
Member chains and instance heads — DV class-semantics round 2.
`cfg.vif.clk`, `item.hdr.addr`, `u_sub.port`, `tb.dut.u_core.done_o`:
the tail of a chain now resolves link by link through each link's
declared type. In one file the resolver hops declared type → declared
type; across files a chain becomes one composed path (`item_t::hdr::addr`)
the workspace's member table walks, so hover, find-references and rename
agree by construction. `Def::type_name` rides every indexed declaration
(`FACTS_FORMAT` 6 → 7; older stores rebuild once), and `this.x`/`super.x`
uses now post to the index, so references from a base class's
declaration list its subclasses' uses in other files.
Instance heads: an instance's type is its module, and modules export
their ports and parameters — so `u_sub.port` resolves cross-file;
internal nets and vars resolve in the declaring file only, by ruling:
exporting them cost +24 % store and made `.port(w)` connections resolve
to internals. Typedef'd class aliases (`typedef c1 my_t; my_t h; h.x`)
are chased, visited-guarded. A chain link whose type is declared twice
in the workspace with different kinds is refused — round 1's lesson,
one hop out. No link ever guesses.
Rename's truth moved with it: renaming `sub`'s `wire sig` now rewrites
`u_sub.sig` too, which a compiler needs; an unresolvable tail is left
alone (and, a known gap filed as topo §2.9-20, no longer warned about).
Corpus: unresolved unchanged at 1 256; store +15.4 % (opentitan
30.8 → 35.4 MB), most of it the inherited-member postings. Zero wrong
answers in QA's 15 live opentitan probes. Formatter output unchanged.
## 0.22.0 — 2026-09-01
Class member access — the first DV class-semantics round.
`task class2::update(c1 in_item); address = in_item.user_id; …` —
hovering `user_id` used to show nothing. Now the tail of `handle.member`
resolves through the handle's declared type: a new `Symbol::type_name`
records the type as written; the member is found in that class's scope,
else up its `extends` chain in the file, else through the workspace's
member table, which chases `WorkspaceIndex::base_of` — a subclass→base
map built from the inheritance census the index already keeps —
cycle-guarded on both sides. Hover shows `rand bit user_id;` with its
file and line; go-to-definition, find-references (from either end) and
rename follow. `this.x`/`super.x` misses resolve to inherited members
through the same chase (the open handshake since the classes wave), and
an out-of-class method body sees its class's members. `FACTS_FORMAT`
5 → 6 (the reference census grew; older stores are discarded).
Honest by construction: a head whose type is declared in the file as
anything without a member scope — a struct typedef, an alias, an enum —
records nothing rather than reaching the workspace, after QA caught the
first cut answering `bus_t s; s.field` from an unrelated class named
`bus_t` elsewhere. Module-instance heads, chains `a.b.c`, struct fields
and typedef'd class aliases are round 2.
Cost: hover 7–143 µs; on opentitan a `tl_seq_item` member resolves in
0.12 ms cold / 0.01 ms warm; store +2.85 %. Formatter output unchanged.
## 0.21.0 — 2026-09-01
Null items: `endgenerate;` parses — and everywhere else a stray `;` may
legally stand.
The report was "for loop inside generate fails"; the diagnosis was that
every generate-for spelling — and three published examples — already
parsed, and the failing token was the lone `;` after `endgenerate`.
IEEE 1800-2017 A.1.4 makes that a *null item*, legal in module,
generate, package, interface, program and class scope and at file
scope; lucisv rejected it in all of them with `expected item`. Now
`ItemKind::Empty`, accepted by one parser branch, laid out where it
was written (glued to the previous line for `endgenerate;` / `end;` /
`endmodule;` / `;;`, or on its own line), token-preserving and
idempotent both ways. `verify.rs` untouched; eight masked-corruption
attack pairs (a dropped `;`, one moved across a comment, into a
procedural block, between `` `ifdef `` arms) all rejected.
New lint **`empty-item`** (slang's `-Wempty-member`): warns on a null
item; its safe fix deletes the `;` — and the line, when nothing else
stood on it — with a deletion range that structurally cannot swallow a
comment. In the editor, a file that used to show a parse error now
shows a warning with a quick fix and *fix all*.
Formatter output changes only for files that contain a null item;
the 820-file corpus is byte-identical (813/820) and the opentitan
sweep is unchanged file-for-file. Version bumped per the format-cache
rule.
## 0.20.0 — 2026-08-30
Fuzzy completion: `clkenq` reaches `clk_osc_en_q`.
Identifier completion now matches by **subsequence** — the typed
letters present in the name, in order — at three or more typed
characters, and by prefix below that: VS Code's own rule, ruled by the
owner. The scope-visible, project-declaration and project-word tiers
go fuzzy; modules (substring), keywords, templates and `` `define ``
names keep their own semantics, and the instantiation ghost's
exact-match trigger deliberately stays exact.
Ranking is prefix-first, then a boundary-aware score: letters landing
at the starts of name parts (`c`·`l`·`k` at `clk_…`'s components)
outrank accidental scatter, contiguous runs outrank gaps, and the
order is deterministic. The scan is affordable because every table
entry carries a 32-bit character mask — a `clkenq` keystroke rejects
99.6 % of opentitan's 100 022-word table with one AND each and costs
+0.05 ms; the expensive class is three very common letters (`aes`,
`ena`), measured at 1–4 ms server-side and accepted as imperceptible
in a popup. 1–2-character responses are always `isIncomplete`, so the
third keystroke — the one that turns fuzzy on — always reaches the
server.
Formatter output unchanged; the bump is the completion behavior.
## 0.19.0 — 2026-08-30
Inline instantiation, round 2 — two rulings from first live use.
**The space is the commitment.** The ghost now appears only after
`name<space>`: `aes` alone may still be growing into `aes_dft`, so the
typed space is what says the name is finished. An exactly-typed name
with the cursor at its end offers nothing; one space arms it; two
spaces or a tab do not. The popup flow is accept the name, type the
space you were going to type anyway, Tab the ghost.
**Every indexed module answers.** A module declared in more than one
file used to get no ghost (`ast_dft` and `io_osc` are each declared
under both `top_earlgrey` and `top_darjeeling` in opentitan — two
whole IP blocks silenced). The server now picks the declaration
nearest the file being edited: most shared leading path components,
then the shallower copy, then the smallest path — deterministic, and
the popup's detail names the file that will be read. The refusal
residue is a named enum, and the QA sweep proves the ruling: **all
1,131 opentitan module names ghost, zero declines** (199 of them
multiply declared, one of them 61 ways), at 0.05–0.08 ms per
non-matching keystroke and ~0.5 ms per ghost.
Formatter output unchanged; the bump is the trigger and chooser
behavior.
## 0.18.0 — 2026-08-30
Inline instantiation: the popup names the module, the ghost writes the
rest. Two levels, sized for a 4,000-file SoC.
### The two-level split
**Level 1 — the completion popup offers module names.** Tier 0 used to
plan a full instantiation skeleton for up to 64 candidate modules on
every keystroke — each one a definition-file read and a header parse.
It is now a scan of the in-memory module table and nothing else: the
item inserts the name, `Module` icon and declaring file beside it.
**Level 2 — the exact name grows a ghost.** The moment the identifier
at the cursor exactly (case-sensitively) matches an indexed module, at
a position where an instantiation is legal, with nothing after the
cursor, `textDocument/inlineCompletion` offers the rest of the
instantiation in grey: every parameter override, every port
connection, each a snippet tabstop, ports matching an in-scope signal
auto-connected. Tab writes it; the editor's own tab settings indent
it. Works the same whether the name was typed by hand or accepted
from the popup. Exactly one module is ever planned, through the
guarded header-slice path and the file-view cache.
The per-keystroke probe is `Candidates::has_module` — a case-sensitive
binary search whose sorted-table premise is pinned by test. Measured
on opentitan (3,976 files): a keystroke that is not a module name
costs 0.10–0.17 ms; the ghost for `aes` (14 parameters, 16 ports)
0.6–1.1 ms; the 112-parameter `top_earlgrey` 2.5 ms cold.
New setting: `lucisv.inlineInstantiation` (default on), independent of
`lucisv.inlineTemplates`.
Honest losses, written down: the popup's per-module documentation
panel is gone (it cost a plan per item); a client without
`inlineCompletion` support (Neovim's built-in LSP today) gets names
but no skeleton — filed as `docs/topo.md` §2.9-19 for an
execute-command spelling. A module declared in two files now appears
in the popup by name (it used to vanish entirely); its ghost declines
rather than guess which file.
Formatter output is unchanged; the bump is the two-level completion
behavior itself. Also checked in: `docs/performance_take2.md`
(referenced since 0.15.0, never staged — `performance.md`,
`performance_take2.md`).
## 0.17.0 — 2026-08-29
The wave's second half: from 100 sweep failures to **11** on the
3,943-file opentitan checkout — 99.7 % of the tree parses, formats and
round-trips clean, and what remains is macro `` `include `` fragments
(a preprocessing decision), vendor files that are not SystemVerilog
(exclude patterns recommended in the analysis), and three written-up
skips.
### The mop-up: nine small buckets
Block-scoped `typedef` statements, system-function casting types
(`$bits(x)'(…)`), enum member ranges, casts over assignment patterns,
gate delay lists, `virtual iface.modport` declarations, `rand` on
struct members, `foreach` skipped dimensions, hierarchical `bind`
instance paths — 45 files, seven of the nine buckets needing no new
AST surface at all.
### The clocking wave: eight more, one round
Clocking signal bindings, `default disable iff` (half of what the
analysis had called "clocking"), `iff` on event-control terms, indexed
event names, gate drive strengths, `program` blocks, and macros as a
concurrent assertion's action — where QA caught a real regression in
four UVM-idiom shapes and the rework decides by the token after the
macro, with the failure direction proven trunk-identical rather than
assumed. The expression-chain limit rises 256 → 1024 on measured need
(a generated pinmux file chains 567 links) with the parse stack
resized to keep its safety margin, sabotage-proven.
**Formatter output moved in exactly one file-class** (code previously
swallowed into an assertion's opaque bytes is now parsed and laid
out), so this release bumps the version and warm format caches
re-verify.
## 0.16.0 — 2026-08-29
The testbench-syntax release: the coverage gap named by
`syntax_coverage.md` (a full sweep of a 3,943-file opentitan checkout),
closed bucket by bucket. Sweep failures 151 → 100 across three
lead-reviewed rounds.
### Out-of-class constraints parse
`constraint ClassName::name { ... }` at file or package scope — the
single biggest bucket, 45 files — was a one-line grammar fix reusing
the out-of-body method-name path. The real win is tolerant-mode: the
cascade of bogus diagnostics these files produced in the editor
(300+ per file, 1,349 across the bucket) collapses to at most one
honest report.
### Directives may open inside a statement
An `` `ifdef `` splitting the right-hand side of an assign, an
expression, or an instantiation head — the mirror image of every
previous directive feature, which all recovered at a *closing*
directive — is captured verbatim, with a head classifier that refuses
what it cannot prove rather than guessing. Fixes chip_if.sv in both
opentitan tops, both flagship tb.sv testbenches, and friends. Crafted
corrupted-capture pairs are asserted rejected by the safety net.
### Three formatter comment bugs, fixed where they lived
A line comment trailing `end` no longer swallows a cuddled `else`; a
comment inside an `if`/`while`/`repeat`/`wait`/`case` header's parens
stays inside them; `default;` no longer grows an invented `:`. Eleven
of the twelve files the safety net had (correctly) refused now format
and round-trip; the twelfth needed a parser-side pending-comment fix
(`take_gap`) delivered by the directive round — all twelve close on
the merged tree. `verify.rs`'s forgiveness was not widened; the
attack-test template was applied anyway.
**Formatter output changed for the comment shapes above, so this
release bumps the version and warm format caches re-verify** (the
format-cache rule).
## 0.15.0 — 2026-08-29
The interactive-latency release, benchmarked twice against a real
3 976-file opentitan checkout (`performance.md`, `performance_take2.md`
at the repo root), plus a design-hierarchy sidebar contributed by
codex.
### Every hot path measured, then fixed
- **codeAction** (fires per cursor move): 3.1–4.6 s → **7 ms** — the
port-refactor engine reads the cursor module's indexed fan-out, not
the workspace; equality with the whole-workspace computation is
pinned, ambiguity refusals intact.
- **prepareRename** (pressing F2): 2.5–3.0 s → **microseconds**, flat
in project size — answered from the open buffer and the index, with
a refusal-by-refusal parity table; refusals are deferred to the
rename, never lost.
- **rename**: 3.6–8.7 s → **~105 ms** over the reference-postings
fan-out, including a sixth rung over unresolved spellings so the
dangling-import capture refusal fires exactly as the whole-workspace
walk's did. willRenameFiles rides the include graph: 250 → 14 ms.
- **completion**: 34–66 ms per keystroke → **3–15 ms** — module
headers are sliced, not whole-file-parsed, with whole-file re-plans
wherever the slice cannot be proven identical; items byte-identical.
- **documentHighlight**: fixed — it answered nothing for any name the
file uses but does not declare (a module instance, a connected
port), which is most of what a tb hovers.
- A widen that subsumes the old scope indexes only its new files, and
the word table merges per batch instead of per word (935 → 555 ms
for the first jump into a 1 685-file root, warm).
### The scope default finds your block
**Behavior change:** `lucisv.index.scopeDepth` defaults to **2** (was
0). Opening `hw/ip/aes/dv/tb/tb.sv` now indexes the aes block and
cross-file answers work immediately, where before exactly one file was
indexed and every cross-file answer was empty until a jump widened the
scope. An explicit `0` restores the old behavior exactly.
### `--verbose`, when you want receipts
`lucisv-server --verbose` (or the `lucisv.verbose` setting, which
restarts the server through a race-proof one-chain restarter) prints a
`timing:` line for every operation into the output channel. Off by
default and free when off. `--stdio` is accepted as the statement of
fact it is.
### The design-hierarchy sidebar (contributed by codex)
An instance-oriented hierarchy in the Activity Bar: every module, its
instances, search over the whole design, bookmarks, click-to-jump.
Snapshots read no files at all — the index now carries client
positions — so the handler answers in ~17 ms on opentitan and a save
with the sidebar open costs ~141 ms total. Search runs over a resident
model in single-digit milliseconds at 120 000 entries, collapsed by
default, expansion preserved across refreshes.
### One-time index rebuild
The persisted facts format moved to 5 (declaration spans, instance
occurrences, client positions; ~+2 % store). The first scan after
upgrading rebuilds the store once.
## 0.14.0 — 2026-08-28
The first-hover release: the owner's "hover is really slow on first
try," traced to three costs and each one removed. Hover's steady state
was already microseconds; now the firsts are too — or as close as
physics allows.
### The index carries every declaration's line
Each indexed declaration — modules, and ports/parameters through the
same member entries — now records its line number(s), computed at index
time for a `u32` per name (+68 KB over the 860-file corpus). A hover
heading into a closed file costs zero I/O: it survives the file being
deleted. The persisted facts format moved to 4; an older cache is
discarded whole and rebuilt once (~175 ms on the corpus).
### Closed files are read once, not per hover
The snippet's one remaining read is served from a small bounded view
cache (4 files / 8 MiB, newest kept, invalidated on every path that can
change a file's text): a repeat hover into a 12 MB closed file goes
5.8 ms → ~1 µs, and mean cross-file hover 40/157 µs → 4.7/12.9 µs.
A stale view can only ever omit a snippet — the wrong-line guard is
unchanged.
### The startup scan answers requests as it goes
A request sent right after `initialized` used to wait out the whole
scan: 780 ms cold / 287 ms warm over 200 files. The scan now feeds the
live index incrementally and drains the message queue between files —
the first hover of a session answers in ~15 ms against the index so
far, with the open file indexed first. One merge per drain (per-file
merging measured quadratic: 11.7 s over 800 files), scans under 64
files stay one-shot, only the startup scan answers mid-way so the
request-order contract holds, and the finished index fingerprints
byte-identical to the old all-at-once scan. Scan totals unchanged
within noise.
## 0.13.1 — 2026-08-28
The F12-latency release: the two costs behind a slow jump out of a big
open file, found by measurement and removed, plus a stack-safety hole
closed.
### References stop sweeping the open buffer
The open-document overlay in find-references did index lookups for
every reference in every open buffer. A spelled-name prefilter and a
hoisted file lookup take a 70 000-reference open `top.sv` from 3.2 ms
to **0.11 ms** per request, both directions; in-file references and
occurrence highlighting on a heavily used signal drop ~40 %. Answers
are byte-identical — the old refactor walk remains the tested oracle.
### A rescan reuses what open buffers already analyzed
Jumping into a folder the index scope had not reached triggered a
rescan that re-parsed every open buffer's text twice — once for index
facts, once for completion words. Both now come from the analysis the
buffer already holds (one implementation per path, byte-identical facts
pinned over the corpus): the folder-widening jump drops from **228 ms
to 23 ms**, and didSave's incremental update rides the same reuse.
### The stack now fits the nesting limit by construction
The parser's 64-level nesting limit only turns over-deep input into an
error on a stack big enough to reach level 64 — an assumption that had
drifted out from under the 2026-08 measurement (~94 KiB per level in
debug under rustc 1.97; a default 2 MiB thread aborted near level 30).
`PARSE_STACK_SIZE` (16 MiB) is now applied at every parse-reaching
thread, both binaries' work included — the CLI previously aborted under
a 1 MiB main stack (`ulimit`, win32 default) on 500 nested `begin`s and
now emits an ordinary diagnostic. Deep-nesting suites across four
crates pin it, sabotage-verified.
## 0.13.0 — 2026-08-28
Editor responsiveness, and hover for old-style ports.
### Typing costs one reanalysis, not one per keystroke
`didChange` no longer reparses and re-lints the buffer on every
keystroke. The text the server holds is still exactly current after
every notification; only the analysis is deferred, and it runs at the
first moment anything needs it — the next request, the next
non-`didChange` notification, or a 150 ms quiet period. A burst of ten
keystrokes in a 10 000-line file therefore costs one 31 ms reanalysis
instead of ten. The visible consequence: intermediate diagnostics
states are no longer published, so squiggles for a half-typed line that
was finished a moment later never appear. Every state that is published
is one the buffer really passed through. Closing a file that was
mid-edit discards its pending change instead of analyzing it, so it
costs one publish — the one that clears its squiggles — and not two.
The one case this makes slower is a single keystroke followed by
nothing at all: it now waits out the quiet period before publishing,
164 ms instead of one reanalysis. Editors ask for something after every
change — semantic tokens, inlay hints, highlights — and any request
flushes the buffer before it is answered, so the latency a user
actually meets is 4.4 ms in a 1 000-line file and 37.6 ms in a
10 000-line one.
### Hover shows a non-ANSI port's real declaration
A port declared the old way — named in the module header, completed in
the body by `input signed [31:0] data_in;` — now hovers as two fenced
sections: the header line, then the body declaration that carries the
direction, the type and the width. Go-to-definition offers both, the
body declaration first. It works cross-file, into files that are not
open, because the span travels through the workspace index. An
old-style task or function argument (`task t(a);` finished by
`input [7:0] a;`) reads the same way. Each section also carries every
comment that documents it: the lines above it, the comment beside it,
and the lines below it when nothing else could claim them — all three
at once where all three are written.
### Faster hover and navigation
A hover into a closed file reads that file once instead of twice (34 ms
→ 16.3 ms on a 31.7 MB file), and resolving a live declaration looks
its name up instead of walking every symbol in the buffer. Measurements
and how to reproduce them: `docs/perf/README.md`.
### Cursor-position answers stop walking the whole buffer
Expand-selection, on-type formatting, the completion scope gates and
the inline template trigger each used to scan every token in the file
to find the one at the cursor. They now binary-search for it: 77 µs →
20 ns in a 10 000-line buffer, and 130 µs → 36 ns for the widest of
them. No answer changed — each swap is pinned by a test that compares
it against the scan it replaced at every byte of the buffer.
The persistent index cache's record format changed to carry the new
span, so the first session after upgrading rebuilds its index rather
than reading the old store.
## 0.12.1 — 2026-08-27
Hover shows the cross-file declaration itself. A name declared in
another file — a port at an instantiation, a module instance, a package
member — now renders its declaration's source line, fenced and
highlighted, under the existing "declared in `file:line`" heading:
direction, type and width for a port, the header line for a module.
Snippets come from the live buffer when the declaring file is open
(unsaved edits included) and from disk otherwise, with a
boundary-checking guard that drops the snippet rather than ever
showing a wrong line, and caps of 5 lines / 400 characters for
netlist-sized declarations. No settings and no index format change.
## 0.12.0 — 2026-08-27
The indexed-navigation release: find-all-references stops paying a
project scan per request.
### References become a lookup
Each indexed file now persists compact reference facts — same-file uses
of its exported declarations, plus unresolved cross-file candidates —
and the workspace index resolves them once into
declaration-to-occurrence postings. `textDocument/references` reads
that posting list and overlays every open buffer's live analysis, so
unsaved additions, deletions and moved declarations stay visible with
no request-time scan: **0.06 ms per request over an 820-file workspace
where the old walk cost 22 ms (~350×)**. The old walk remains rename's
engine and is pinned equal to the indexed answer by test; ambiguity
still degrades to the in-file answer exactly as before.
### Cursor lookups stop sweeping
Declaration, reference and macro-token lookups under the cursor —
hover, definition, references entry points — binary-search sorted
position tables instead of scanning every symbol in the buffer, and
`` `include`` definition inspects only the cursor's line.
### One-time cache rebuild
The persisted facts format moved to version 2 for the new reference
records. An existing index cache from 0.11.0 is discarded whole on
first open and rebuilt — one re-scan, never a misread record.
## 0.11.0 — 2026-08-27
The large-workarea release: a project too big to scan is now a project
lucisv keeps up with. Six owner-requested rounds, one dev/QA/review
cycle each.
### Indexing starts where you are
`lucisv.index.scope` defaults to `folder`: the index covers the folders
your open files live in — raised `lucisv.index.scopeDepth` ancestor
levels — and widens as you open more. Cross-file answers are
scope-relative until the scope reaches a folder; a filelist still
defines the whole project, and `"workspace"` restores the previous
walk exactly (the same code path, not an equal-output one). **This is
a behavior change for workspace users without a filelist** — the
migration is that one setting.
### One file changed, one file merged
A save re-indexes only the saved file — 33 ms where the corpus rescan
cost 1.5 s — through an index whose incremental histories are
byte-identical to fresh builds. Instantiation counts, incoming calls
and subtype answers now come from edge tables built at index time
(code lens 92 ms → 0.26 ms), so they read as of the index rather than
of unsaved keystrokes.
### The index survives a restart
Per-file index records persist under the editor's workarea storage
(`lucisv.index.persist`, on by default), keyed by content hash: a
crashed or closed session resumes where it stopped, cached files fly
through the progress bar, and the end message says how many came from
cache. The cache is a performance artifact with a per-record checksum
— a damaged entry costs a re-parse, never an answer.
### Netlists open instantly
Above `lucisv.largeFile.threshold` (4 MiB) a buffer skips the pipeline
entirely: a 104 MB netlist opens in 40 ms, viewport syntax
highlighting answers in a quarter of a millisecond, and same-file
definition/references run as bounded text scans. Most other features
deliberately answer nothing there. Fixing this path's long-line
behavior also made ordinary files' semantic tokens up to 9× faster.
### The scan explains itself
The indexing bar counts `n/total` through the files; the output
channel logs each file as indexed, cached, or skipped;
`lucisv.index.maxFileSize` (1 MiB default) keeps generated files out
of the index, with skips counted in the closing message.
## 0.10.2 — 2026-08-27
The works-anywhere release: a seventh extension package that carries
+67
View File
@@ -29,6 +29,38 @@ doing anything.
- Match the style of the surrounding code (comment density, naming,
module layout).
## File and function size
Files and functions are sized for a human reader, not a compiler.
- **Target 300–600 production lines per file.** At 800, consider
splitting. Above 1,200, an explicit reason not to split goes in the
feature README. Test lines do not count, but a `#[cfg(test)]` block
that dwarfs its file moves to its own module or `tests/` file.
- **Functions: 10–50 lines.** Investigate anything over 80; anything
over 150 needs a reason in a comment (a dispatch table over an enum
is the usual one).
- Looser for declarative tables, generated code, snapshots and
repetitive tests. Complexity matters more than the count: 800 lines
of grammar productions read more easily than 250 lines of state.
- **The real test is one sentence.** A human should be able to say what
a file is responsible for in one sentence and predict which parts a
change touches. Several "and" clauses mean the file wants to be
several modules.
- A split is a **pure move**: public paths stay the same (re-export from
the old `mod`), behaviour and output stay byte-identical, the test
count does not drop. Measured, not asserted — the corpus and
opentitan byte-identity gates are the proof.
Measured 2026-09-02 (production lines): `vlog_parser/src/parser.rs`
8 786, `vlog_formatter/src/format.rs` 5 444, `vlog_parser/src/ast.rs`
3 313, `lucisv_server/src/server.rs` 2 559 (+6 300 test),
`vlog_semantic/src/bind.rs` 2 378, `vlog_semantic/src/workspace.rs`
1 975, `vlog_refactor/src/ports.rs` 1 778,
`lucisv_server/src/completion.rs` 1 716 — thirteen files over 800.
These are decomposition work (TODO §28), and every one of them is where
feature lanes collide, which is the other reason to split them.
## Rust standards
- `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
@@ -86,3 +118,38 @@ Rules:
(`cargo test -p vlog_formatter`).
- Update `TODO.md`: check items your feature completes (leave the item
text intact).
## Parallel lanes (the 2-agent loop)
Up to **two dev/QA lanes may run concurrently** when — and only when —
their features do not collide in `docs/topo.md`: no shared edge between them
(no `──▶`, no `◀──▶`, and neither touching the same open handshake in
§2.9), and disjoint file sets. `docs/topo.md` is the authority; if the
collision question is not answerable from it, the features are not
proven independent and run serially. Rules for a parallel wave:
- **The lead plans the lanes** before anything is dispatched: one brief
per lane with an explicit file-ownership list. That list is the merge
contract — a lane touches nothing outside it. A needed change to a
file the other lane owns (or to any unlisted file) is a Handshake
request in the lane's README plus a flag in its report, never a
silent edit; the lead rules on it at merge.
- **Each lane works in its own git worktree** branched from the same
trunk commit. Never two agents in one tree. Trunk stays untouched
while lanes are in flight; the lead merges each lane back only after
that lane's QA verdict and lead review, and re-runs the full gates on
the merged tree before pushing.
- **Roles per lane are unchanged**: one dev (Opus), then one QA
(Sonnet) in the same worktree, then the lead's review — so at most
2 devs + 2 QA agents exist at once, and a lane's QA starts only when
its own dev is done. A QA rework loops inside its lane without
blocking the other lane.
- **Tracking lives in `TODO.md`**: the lead writes the wave's section
(one subsection per lane, each item naming its files) on trunk before
branching; each lane ticks only its own lines. Shared-by-nature files
(`TODO.md`, `docs/perf/README.md`) may be appended to by both lanes
in their own sections — the lead resolves the trivially-parallel
merge; anything worse than trivially-parallel means the lanes were
not actually independent, which is a planning failure to record.
- After merging, the lead updates `docs/topo.md` for any edge a lane added
or amended, so the next wave plans against reality.
Generated
+8 -8
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.10.2"
version = "0.33.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.10.2"
version = "0.33.0"
[[package]]
name = "lucisv_server"
version = "0.10.2"
version = "0.33.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.10.2"
version = "0.33.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.10.2"
version = "0.33.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -264,11 +264,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.10.2"
version = "0.33.0"
[[package]]
name = "vlog_refactor"
version = "0.10.2"
version = "0.33.0"
dependencies = [
"vlog_parser",
"vlog_semantic",
@@ -276,7 +276,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.10.2"
version = "0.33.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.10.2"
version = "0.33.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+5 -1
View File
@@ -678,7 +678,11 @@ to the folder walk, so the index is never silently empty.
<path-to-binary>` spawns it exactly as the extension does and drives a whole
`initialize`/`didOpen`/`shutdown`/`exit` session over stdio, exiting 0 only if
the handshake and the advertised capabilities are intact — which tells you
whether a failure is the server or your editor config.
whether a failure is the server or your editor config. Its neighbour
`node editors/vscode/restart_test.js` needs no binary at all: it drives the
extension's server-restart chain (the one `lucisv.verbose` uses) against a
scripted fake client, so a toggle can never be lost to a restart that was
already in flight.
**Formatting through an editor reads `lucisv.toml` too**, discovered from the
buffer's own path by the CLI's rule, so format-on-save agrees with what
+2010 -7
View File
File diff suppressed because it is too large. Load diff
+11 -2
View File
@@ -188,6 +188,13 @@ OPTIONS:
CHECK OPTIONS (`lucisv check` only):
--select <RULES> run only these rules (comma-separated, repeatable)
--ignore <RULES> drop these rules from the set that would run
Three rules read the *project* rather than one file — `unused-signal`,
`undriven-net`, `multiply-driven`. They run by default over more than one
file, where lucisv can ask whether another file mentions a name, and stay
off for a single file or a stdin buffer, where it cannot. `--select` runs
one either way; `--ignore`, or `ignore` under `[lint]` in lucisv.toml,
turns one off.
--output-format <FMT> `text` (default): FILE:LINE:COL: message [rule];
`json`: one array of diagnostic objects
--fix apply safe fixes and write the files back
@@ -233,8 +240,10 @@ CONFIGURATION:
optional: `line-length` (40-400), `indent` (1-8), `exclude` (array of
patterns, added to `--exclude`), `filelist` (path to an EDA `.f` file,
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). A command
line flag overrides the file.
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.
RANGE FORMATTING:
`--lines` formats one construct at a time: an item whose lines meet a range
+142 -14
View File
@@ -5,13 +5,16 @@
//! is handed the same `(path, config)` job list `format` gets. Only what
//! happens to one file differs.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use lucisv_core::config::FileConfig;
use rayon::prelude::*;
use vlog_formatter::fence::{self, Region};
use vlog_formatter::Config;
use vlog_linter::{apply_fixes, lint, Fix, ParsedSource, Rule, Violation};
use vlog_linter::words;
use vlog_linter::{apply_fixes, lint, Fix, MentionOracle, ParsedSource, Rule, Violation};
use vlog_parser::LineIndex;
use crate::args::{Options, OutputFormat};
@@ -22,6 +25,114 @@ use crate::args::{Options, OutputFormat};
/// cap only bounds a rule that would fight itself forever.
const MAX_FIX_ROUNDS: usize = 10;
/// One file to lint, with the rules the command line and its own
/// `lucisv.toml` resolved to.
pub struct Job {
path: PathBuf,
config: Config,
rules: Vec<&'static dyn Rule>,
}
/// A whole `lucisv check` run: what to lint, and what the project says about
/// names.
pub struct Plan {
jobs: Vec<Job>,
/// 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>,
}
/// How many of the run's files write each identifier down.
///
/// The CLI's answer to the question the language server answers from its
/// index: it has none, so it builds one — a read and a lex of every file in
/// the run, before the first rule sees anything. Only the *counts* are kept;
/// a rule asks about one name at a time and never about a file.
pub struct Census {
files: HashMap<String, u32>,
}
impl Census {
/// The census of every file in the run, harvested in parallel.
///
/// A file that cannot be read or does not lex contributes nothing, which
/// is the same all-or-nothing rule the rest of the run gives it: the
/// file's own check reports the error.
fn of(jobs: &[Job]) -> Census {
let per_file: Vec<Vec<String>> = jobs
.par_iter()
.map(|job| match std::fs::read_to_string(&job.path) {
Ok(src) => words::harvest_text(&src),
Err(_) => Vec::new(),
})
.collect();
let mut files: HashMap<String, u32> = HashMap::new();
for words in per_file {
for word in words {
*files.entry(word).or_default() += 1;
}
}
Census { files }
}
/// How many files in the run write `name` down.
fn count(&self, name: &str) -> u32 {
self.files.get(name).copied().unwrap_or(0)
}
}
/// One file's view of the census: everything the project says, minus what
/// this file says about itself.
struct Elsewhere<'a> {
census: &'a Census,
/// This file's own words, sorted — [`words::harvest`]'s answer over the
/// tokens the file was linted from, so the subtraction is exact rather
/// than assumed.
own: Vec<String>,
}
impl MentionOracle for Elsewhere<'_> {
fn mentioned_elsewhere(&self, name: &str) -> bool {
let mine = u32::from(self.own.binary_search_by(|w| w.as_str().cmp(name)).is_ok());
self.census.count(name) > mine
}
}
/// Resolve the run: the rules for each file, and whether a census is owed.
///
/// **Precedence is CLI over config, key by key**: `--select` replaces a
/// `[lint] select`, `--ignore` replaces a `[lint] ignore`, and a key the
/// command line does not mention is the config file's to answer — the same
/// ladder `--line-length` and `--indent` already climb.
///
/// A rule that [`Rule::needs_workspace`] is on by default here exactly when
/// the run holds more than one file: one file is one file whatever directory
/// it was found in, and a census of it could only ever say what the file
/// already says about itself.
pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Result<Plan, String> {
let workspace = gathered.len() > 1;
let mut jobs = Vec::with_capacity(gathered.len());
for (path, config, file_config) in gathered {
let select = pick(&opts.select, file_config.lint_select.as_deref());
let ignore = pick(&opts.ignore, file_config.lint_ignore.as_deref());
let rules = vlog_linter::select_rules(select, ignore, workspace)
.map_err(|e| format!("{}: {e}", path.display()))?;
jobs.push(Job { path, config, rules });
}
let wanted = jobs.iter().any(|job| job.rules.iter().any(|rule| rule.needs_workspace()));
let census = (workspace && wanted).then(|| Census::of(&jobs));
Ok(Plan { jobs, census })
}
/// 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() {
config.unwrap_or(&[])
} else {
cli
}
}
/// What linting one file produced.
struct Report {
path: String,
@@ -39,13 +150,12 @@ struct Report {
/// 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,
jobs: &[(PathBuf, Config)],
rules: &[&'static dyn Rule],
) -> ExitCode {
let mut reports: Vec<Report> =
jobs.par_iter().map(|(file, config)| check_one(file, config, opts, rules)).collect();
pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
let mut reports: Vec<Report> = plan
.jobs
.par_iter()
.map(|job| check_one(&job.path, &job.config, opts, &job.rules, plan.census.as_ref()))
.collect();
// 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.
@@ -63,7 +173,7 @@ pub fn check_stdin(
) -> 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);
let (violations, lex_error) = run_rules(src, path, config, rules, None);
// Nothing is ever written back for stdin, so `--fix` has nothing to do
// here; the violations are reported as they are.
let error = lex_error.map(|e| format!("{name}: {e}"));
@@ -72,7 +182,13 @@ pub fn check_stdin(
}
/// 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]) -> Report {
fn check_one(
file: &Path,
config: &Config,
opts: &Options,
rules: &[&'static dyn Rule],
census: Option<&Census>,
) -> Report {
let path = file.display().to_string();
let failed = |error: String| Report {
path: path.clone(),
@@ -88,9 +204,10 @@ fn check_one(file: &Path, config: &Config, opts: &Options, rules: &[&'static dyn
};
let outcome = crate::catch_panic(|| {
if opts.fix {
fix_source(&src, file, config, opts, rules)
fix_source(&src, file, config, opts, rules, census)
} else {
let (violations, lex_error) = run_rules(&src, Some(file.to_path_buf()), config, rules);
let (violations, lex_error) =
run_rules(&src, Some(file.to_path_buf()), config, rules, census);
(violations, None, 0, lex_error)
}
});
@@ -121,6 +238,7 @@ fn run_rules(
path: Option<PathBuf>,
config: &Config,
rules: &[&'static dyn Rule],
census: Option<&Census>,
) -> (Vec<Violation>, Option<String>) {
// 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
@@ -129,9 +247,17 @@ fn run_rules(
// saves a parse; a plain `lucisv check` always does.
let parsed = ParsedSource::parse(src);
let lex_error = parsed.lex_error().map(|e| format!("lex error: {e}"));
// This file's own words, off the tokens it was just lexed from rather
// than off a second lex — what the oracle subtracts from the project's
// census so a signal never counts as mentioned by its own declaration.
let elsewhere = census.map(|census| Elsewhere { census, own: words::harvest(parsed.tokens()) });
// The indent width the formatter would use is also the width a tab
// expands to, so `--indent 4` fixes tabs into four spaces.
let ctx = parsed.context(path).with_tab_width(config.indent_width);
let ctx = match &elsewhere {
Some(elsewhere) => ctx.with_oracle(elsewhere),
None => ctx,
};
(lint(&ctx, rules), lex_error)
}
@@ -174,10 +300,12 @@ fn fix_source(
config: &Config,
opts: &Options,
rules: &[&'static dyn Rule],
census: Option<&Census>,
) -> (Vec<Violation>, Option<String>, usize, Option<String>) {
let mut text = src.to_string();
let mut fixed = 0;
let (mut violations, mut lex_error) = run_rules(&text, Some(file.to_path_buf()), config, rules);
let (mut violations, mut lex_error) =
run_rules(&text, Some(file.to_path_buf()), config, rules, census);
for _ in 0..MAX_FIX_ROUNDS {
let round =
apply_fixes(&text, &fixable_outside_fences(&text, &violations), opts.unsafe_fixes);
@@ -186,7 +314,7 @@ fn fix_source(
}
fixed += round.applied;
text = round.output;
(violations, lex_error) = run_rules(&text, Some(file.to_path_buf()), config, rules);
(violations, lex_error) = run_rules(&text, Some(file.to_path_buf()), config, rules, census);
}
let rewritten = (text != src).then_some(text);
(violations, rewritten, fixed, lex_error)
+72 -25
View File
@@ -28,16 +28,11 @@ use rayon::prelude::*;
use args::{Command, Options};
use lucisv_core::cache::{content_hash, Cache, Entry};
use lucisv_core::config::Discovery;
use lucisv_core::config::{Discovery, FileConfig};
use lucisv_core::filelist;
use lucisv_core::walk::{collect_files, EXTENSIONS};
use vlog_formatter::{format_range, format_source, Config, LineRanges};
/// Worker stack size. `docs/features/recursion-limit/README.md` measured
/// the full pipeline's worst-case peak at ~3.9 MiB in a debug build on
/// input that trips the parser's nesting limit; rayon's own default is
/// 2 MiB, which would put that crash back.
const WORKER_STACK: usize = 8 * 1024 * 1024;
use vlog_parser::PARSE_STACK_SIZE;
fn main() -> ExitCode {
let opts = match args::parse() {
@@ -50,22 +45,52 @@ fn main() -> ExitCode {
// Once, before any worker thread exists, so nothing ever races on it.
install_panic_hook();
// Nothing parses on the main thread, because its stack is not ours to
// state: 8 MiB on a stock macOS or Linux, whatever `ulimit -s` says in a
// container, 1 MiB on Windows. The parser's nesting limit only turns
// over-deep input into an error on a stack of at least
// `PARSE_STACK_SIZE` — below that the overflow, which aborts the
// process, comes first. A thread we spawn is the one stack whose size is
// ours to guarantee. The pool's workers cover the file-at-a-time paths
// (`build_pool`), but not the ones that never reach it: `-` reads and
// formats a buffer right here, and so does `lucisv check -`.
let spawned = std::thread::Builder::new()
.name("lucisv".to_string())
.stack_size(PARSE_STACK_SIZE)
.spawn(move || run(&opts));
let handle = match spawned {
Ok(handle) => handle,
Err(e) => {
eprintln!("error: could not start the worker thread: {e}");
return ExitCode::from(2);
}
};
match handle.join() {
Ok(code) => code,
// An uncontained panic, already printed by the hook above. 101 is
// what the same panic on the main thread would have exited with.
Err(_) => ExitCode::from(101),
}
}
/// The run itself, on the stack `main` sized for it.
fn run(opts: &Options) -> ExitCode {
match opts.command {
Command::Format if opts.is_stdin() => run_stdin(&opts),
Command::Format => run_files(&opts),
Command::Check => run_check(&opts),
Command::Format if opts.is_stdin() => run_stdin(opts),
Command::Format => run_files(opts),
Command::Check => run_check(opts),
}
}
/// `lucisv check`: the linter over the same file set the formatter would take.
fn run_check(opts: &Options) -> ExitCode {
let rules = match vlog_linter::select_rules(&opts.select, &opts.ignore) {
Ok(rules) => rules,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
// The command line's own names are checked before anything is walked, so
// a typo'd `--select` fails in milliseconds rather than after the scan.
// A `lucisv.toml`'s names are checked per file below, where they are read.
if let Err(e) = vlog_linter::select_rules(&opts.select, &opts.ignore, false) {
eprintln!("error: {e}");
return ExitCode::from(2);
}
if opts.is_stdin() {
let config = match stdin_config(opts) {
Ok(c) => c,
@@ -79,6 +104,16 @@ fn run_check(opts: &Options) -> ExitCode {
eprintln!("error: reading stdin: {e}");
return ExitCode::from(2);
}
// A stdin buffer is one text with nothing around it: there is no
// census to build and no other file to ask about, so the rules that
// need a project stay off. `--select` still reaches them.
let rules = match vlog_linter::select_rules(&opts.select, &opts.ignore, false) {
Ok(rules) => rules,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
return lint::check_stdin(opts, &src, &config, &rules);
}
let jobs = match gather(opts).and_then(|jobs| build_pool(opts).map(|()| jobs)) {
@@ -88,7 +123,13 @@ fn run_check(opts: &Options) -> ExitCode {
return ExitCode::from(2);
}
};
lint::check_files(opts, &jobs, &rules)
match lint::plan(opts, jobs) {
Ok(plan) => lint::check_files(opts, &plan),
Err(e) => {
eprintln!("error: {e}");
ExitCode::from(2)
}
}
}
fn run_stdin(opts: &Options) -> ExitCode {
@@ -149,11 +190,11 @@ fn run_files(opts: &Options) -> ExitCode {
// The cache is only read here; entries ride back with the results and
// are recorded serially below, so nothing is shared mutably.
let results: Vec<FileResult> =
jobs.par_iter().map(|(file, config)| process_file(file, config, opts, &cache)).collect();
jobs.par_iter().map(|(file, config, _)| process_file(file, config, opts, &cache)).collect();
let (mut changed, mut unchanged, mut errors, mut cached) = (0usize, 0usize, 0usize, 0usize);
for (index, result) in results.into_iter().enumerate() {
let (file, config) = &jobs[index];
let (file, config, _) = &jobs[index];
if let Some(content) = result.clean {
cache.record(file, entry_for(content, config));
}
@@ -272,11 +313,12 @@ fn entry_for(content: u64, config: &Config) -> Entry {
}
/// Builds rayon's global pool. Worker stacks are sized for the parser's
/// recursion limit (see `WORKER_STACK`); `--threads 0` lets rayon pick.
/// recursion limit (`PARSE_STACK_SIZE` — rayon's own default is 2 MiB, which
/// would put the overflow back); `--threads 0` lets rayon pick the count.
fn build_pool(opts: &Options) -> Result<(), String> {
rayon::ThreadPoolBuilder::new()
.num_threads(opts.thread_count())
.stack_size(WORKER_STACK)
.stack_size(PARSE_STACK_SIZE)
.build_global()
.map_err(|e| format!("could not start the worker pool: {e}"))
}
@@ -287,7 +329,7 @@ fn build_pool(opts: &Options) -> Result<(), String> {
/// filelists name (exact paths, filtered by neither — they were named).
/// Every config file is read here, before anything is written, so a broken
/// one aborts the whole run instead of leaving it half applied.
fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config)>, String> {
fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config, FileConfig)>, String> {
let mut discovery = Discovery::new(!opts.no_config);
let mut files = Vec::new();
for input in &opts.inputs {
@@ -311,8 +353,13 @@ fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config)>, String> {
}
let mut jobs = Vec::with_capacity(files.len());
for file in files {
let config = opts.config_with(&discovery.for_file(&file)?);
jobs.push((file, config));
// The whole `FileConfig` rides along, not just the formatter settings
// it resolves to: `lucisv check` needs its `[lint]` keys too, and
// discovering them a second time would read every config file twice
// and could answer differently if one changed underneath the run.
let file_config = discovery.for_file(&file)?;
let config = opts.config_with(&file_config);
jobs.push((file, config, file_config));
}
Ok(jobs)
}
+184 -2
View File
@@ -407,7 +407,8 @@ fn a_deeply_nested_file_formats_on_a_worker_thread() {
// costs two levels), so it parses — and needs several MiB of stack to
// do it in a debug build: without the depth limit this family died at
// 15 levels on a 2 MiB thread, which is exactly rayon's default worker
// stack. This test crashes the process if the pool's 8 MiB is dropped.
// stack. This test crashes the process if the pool's `PARSE_STACK_SIZE`
// is dropped.
let deep = format!(
"module m;\nalways @(posedge clk) begin\n{}x <= 1;\n{}end\nendmodule\n",
"if (clk) begin\n".repeat(28),
@@ -425,6 +426,34 @@ fn a_deeply_nested_file_formats_on_a_worker_thread() {
assert!(stdout(&out).contains("deep.sv"), "{}", stdout(&out));
}
#[test]
fn a_deeply_nested_buffer_from_stdin_is_a_diagnostic_not_a_crash() {
// The stdin path never touches the worker pool: it formats on the thread
// `main` spawned, which is the only stack whose size lucisv gets to
// state. 500 nested blocks are far past the parser's limit, so the run
// must end with an ordinary parse error — and not with a SIGABRT, which
// is what an unstated stack gives instead.
let deep = format!(
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
"begin\n".repeat(500),
"end\n".repeat(500)
);
let out = run_with_stdin(&["-"], &deep);
assert_eq!(code(&out), 2, "{}", stderr(&out));
assert!(stderr(&out).contains("nesting too deep"), "{}", stderr(&out));
assert!(stdout(&out).is_empty(), "a rejected buffer prints nothing: {}", stdout(&out));
// And the deepest *legal* buffer formats on that same stack.
let legal = format!(
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
"begin\n".repeat(58),
"end\n".repeat(58)
);
let out = run_with_stdin(&["-"], &legal);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(stdout(&out).contains("endmodule"), "{}", stdout(&out));
}
#[test]
fn every_file_keeps_its_own_config_when_formatted_in_parallel() {
let dir = TempDir::new("configpar");
@@ -633,7 +662,7 @@ fn a_broken_config_exits_2_before_writing_anything() {
for (contents, expected) in [
("indent = 99\n", "between 1 and 8"),
("line-length = wide\n", "expects an integer"),
("[tool.lucisv]\nindent = 2\n", "tables"),
("[tool.lucisv]\nindent = 2\n", "unknown table"),
("exclude = [\n \"a\",\n]\n", "multi-line arrays are unsupported"),
] {
dir.write("lucisv.toml", contents);
@@ -1698,3 +1727,156 @@ fn help_documents_the_filelist_flag() {
assert!(text.contains("-f <FILELIST>"), "{text}");
assert!(text.contains("read by lucisv-server only"), "the toml key stays server-only: {text}");
}
// ----------------------------------------------------------------------
// The semantic rules and the project census (semantic-lints-on, 2026-09-02)
// ----------------------------------------------------------------------
/// A module whose `dbg_probe` only a *second* file reads, hierarchically.
const DUT: &str = "module dut;\n logic dbg_probe;\n logic dead;\nendmodule\n";
const TB: &str = "module tb;\n dut d ();\n initial $display(\"%b\", d.dbg_probe);\nendmodule\n";
/// The round's headline: over a project the semantic rules run by default,
/// and the file that reads `d.dbg_probe` is what keeps `dbg_probe` quiet.
/// `dead`, which nothing anywhere writes down twice, is still reported.
#[test]
fn a_mention_in_another_file_silences_unused_signal_over_a_project() {
let dir = TempDir::new("census");
dir.write("dut.sv", DUT);
dir.write("tb.sv", TB);
let out = run(&["check", &dir.root()]);
let text = stdout(&out);
assert!(text.contains("`dead` is declared but never used"), "{text}");
assert!(!text.contains("dbg_probe"), "the other file reads it: {text}");
assert_eq!(code(&out), 1);
}
/// One file is not a project: there is nothing to ask, so the rules that
/// need a workspace stay off and the run is exactly v0.29.0's.
#[test]
fn a_single_file_run_leaves_the_semantic_rules_off() {
let dir = TempDir::new("alone");
let dut = dir.write("dut.sv", DUT);
let out = run(&["check", &dut]);
assert_eq!(stdout(&out), "");
assert_eq!(code(&out), 0);
// ... and naming the rule still runs it, oracle or no oracle.
let named = run(&["check", &dut, "--select", "unused-signal"]);
let text = stdout(&named);
assert!(text.contains("dbg_probe"), "{text}");
assert!(text.contains("dead"), "{text}");
assert_eq!(code(&named), 1);
}
/// A stdin buffer has no project either, and no file to build one from.
#[test]
fn a_stdin_buffer_leaves_the_semantic_rules_off() {
let out = run_with_stdin(&["check", "-"], DUT);
assert_eq!(stdout(&out), "");
assert_eq!(code(&out), 0);
let named = run_with_stdin(&["check", "-", "--select", "unused-signal"], DUT);
assert!(stdout(&named).contains("dbg_probe"), "{}", stdout(&named));
}
/// The off switch a default-on rule owes its users: `[lint] ignore` in the
/// `lucisv.toml` governing the files.
#[test]
fn a_lint_table_in_the_config_turns_a_rule_off() {
let dir = TempDir::new("lint-table");
dir.write("dut.sv", DUT);
dir.write("tb.sv", TB);
dir.write("lucisv.toml", "[lint]\nignore = [\"unused-signal\"]\n");
let out = run(&["check", &dir.root()]);
assert_eq!(stdout(&out), "", "the config silenced the rule");
assert_eq!(code(&out), 0);
}
/// `[lint] select` replaces the default set, exactly as `--select` does.
#[test]
fn a_lint_table_can_select_instead_of_ignore() {
let dir = TempDir::new("lint-select");
dir.write("dut.sv", DUT);
dir.write("tb.sv", TB);
dir.write("lucisv.toml", "[lint]\nselect = [\"unused-signal\"]\n");
let out = run(&["check", &dir.root()]);
let text = stdout(&out);
assert!(text.contains("`dead` is declared but never used"), "{text}");
assert!(!text.contains("dbg_probe"), "{text}");
}
/// Precedence, key by key: the command line beats the config file, and a key
/// the command line does not mention stays the config file's.
#[test]
fn the_command_line_beats_the_lint_table() {
let dir = TempDir::new("lint-precedence");
dir.write("dut.sv", DUT);
dir.write("tb.sv", TB);
dir.write("lucisv.toml", "[lint]\nignore = [\"unused-signal\"]\n");
// `--ignore` replaces the config's ignore list, so `unused-signal` is back.
let out = run(&["check", &dir.root(), "--ignore", "no-tabs"]);
assert!(stdout(&out).contains("`dead` is declared but never used"), "{}", stdout(&out));
// `--select` replaces the default set; the config's ignore still applies.
let selected = run(&["check", &dir.root(), "--select", "unused-signal,no-tabs"]);
assert_eq!(stdout(&selected), "", "the config's ignore survives a CLI select");
}
/// An unknown rule name in a config file fails the run and says what is
/// known — the same answer a typo'd `--select` gets, named by file.
#[test]
fn an_unknown_rule_in_the_lint_table_is_an_error() {
let dir = TempDir::new("lint-unknown");
dir.write("dut.sv", DUT);
dir.write("tb.sv", TB);
dir.write("lucisv.toml", "[lint]\nignore = [\"no-such-rule\"]\n");
let out = run(&["check", &dir.root()]);
let text = stderr(&out);
assert!(text.contains("unknown rule: no-such-rule"), "{text}");
assert!(text.contains("unused-signal"), "the error lists what is known: {text}");
assert_eq!(code(&out), 2);
}
/// Per-rule tables are named rather than silently ignored, so a user who
/// writes one finds out it does nothing yet.
#[test]
fn a_per_rule_lint_table_is_refused_by_name() {
let dir = TempDir::new("lint-per-rule");
dir.write("dut.sv", DUT);
dir.write("lucisv.toml", "[lint.unused-signal]\nignore = \"tmp_*\"\n");
let out = run(&["check", &dir.root()]);
assert!(stderr(&out).contains("per-rule lint settings"), "{}", stderr(&out));
assert_eq!(code(&out), 2);
}
/// The QA finding of 2026-09-02, pinned end to end: a testbench that reads an
/// RTL signal only inside a macro argument — `` `uvm_info(..., $sformatf("%b",
/// dut.sig), ...) ``, the commonest VPI-probe shape there is — must silence
/// `unused-signal` for that signal. The lexer hands the whole invocation over
/// as one token, so this works only because the census splits it.
#[test]
fn a_signal_named_only_inside_a_macro_argument_is_not_reported_unused() {
let dir = TempDir::new("macroarg");
dir.write("dut.sv", DUT);
dir.write(
"tb.sv",
"module tb;\n dut u_dut ();\n initial begin\n\
\x20 `uvm_info(\"tb\", $sformatf(\"probe=%b\", u_dut.dbg_probe), UVM_LOW)\n\
\x20 end\nendmodule\n",
);
let out = run(&["check", &dir.root()]);
let text = stdout(&out);
assert!(!text.contains("dbg_probe"), "the macro argument names it: {text}");
assert!(text.contains("`dead` is declared but never used"), "and `dead` still reports: {text}");
// The format string is a value: a signal called `probe` in another file
// must not be silenced by `"probe=%b"` here.
let other = TempDir::new("macroargstring");
other.write("a.sv", "module a;\n logic probe;\nendmodule\n");
other.write(
"b.sv",
"module b;\n initial `uvm_info(\"t\", $sformatf(\"probe=%b\", 1'b0), UVM_LOW)\nendmodule\n",
);
assert!(
stdout(&run(&["check", &other.root()])).contains("`probe` is declared but never used"),
"a string's contents are not mentions"
);
}
+94 -10
View File
@@ -1,8 +1,8 @@
//! `lucisv.toml` / `.lucisv.toml` discovery and its TOML-subset parser.
//!
//! Only what a three-key config file needs is supported (comments,
//! `key = int`, `key = "string"`, `key = ["a", "b"]`); everything else is
//! rejected by name rather than ignored. See
//! Only what a small config file needs is supported (comments, `key = int`,
//! `key = "string"`, `key = ["a", "b"]`, and the single table `[lint]`);
//! everything else is rejected by name rather than ignored. See
//! `docs/features/config-discovery/README.md` for the grammar and the
//! reasoning behind not taking a TOML dependency.
@@ -29,6 +29,13 @@ 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>,
/// `[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
/// run's rules, with the same error a bad `--select` gets.
pub lint_select: Option<Vec<String>>,
/// `[lint] ignore`: rules dropped from whatever `select` left.
pub lint_ignore: Option<Vec<String>>,
}
/// Parses the supported TOML subset. Errors are prefixed `<line>: ` so the
@@ -38,19 +45,36 @@ pub fn parse(text: &str) -> Result<FileConfig, String> {
// Editors on some platforms prepend a BOM; it would otherwise garble
// key matching on line 1 into an `unknown key` with invisible cause.
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
// Which table the keys below belong to. There is exactly one table, so
// this is a flag rather than a path: `[lint]` opens it and nothing closes
// it, which is TOML's own rule.
let mut in_lint = false;
for (index, raw) in text.lines().enumerate() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
parse_entry(line, &mut config).map_err(|e| format!("{}: {e}", index + 1))?;
parse_entry(line, &mut config, &mut in_lint).map_err(|e| format!("{}: {e}", index + 1))?;
}
Ok(config)
}
fn parse_entry(line: &str, config: &mut FileConfig) -> Result<(), String> {
fn parse_entry(line: &str, config: &mut FileConfig, in_lint: &mut bool) -> Result<(), String> {
if line.starts_with('[') {
return Err("tables (`[section]`) are unsupported in lucisv.toml".to_string());
// `[lint]` is the one table lucisv reads. `[lint.<rule>]` — per-rule
// settings — is named in the error rather than ignored, so a user who
// writes one finds out it is not supported yet instead of wondering
// why it did nothing (topo §2.9-4 keeps the per-rule half open).
if line == "[lint]" {
*in_lint = true;
return Ok(());
}
if line.starts_with("[lint.") {
return Err(format!(
"per-rule lint settings (`{line}`) are not supported yet; `[lint]` takes `select` and `ignore`"
));
}
return Err(format!("unknown table `{line}` (the only table is `[lint]`)"));
}
let (key, value) =
line.split_once('=').ok_or_else(|| format!("expected `key = value`, found `{line}`"))?;
@@ -59,6 +83,9 @@ fn parse_entry(line: &str, config: &mut FileConfig) -> Result<(), String> {
if value.is_empty() {
return Err(format!("`{key}` has no value"));
}
if *in_lint {
return parse_lint_entry(key, value, config);
}
match key {
"line-length" => set_int(&mut config.line_length, key, value, 40, 400),
"indent" => set_int(&mut config.indent, key, value, 1, 8),
@@ -76,12 +103,29 @@ fn parse_entry(line: &str, config: &mut FileConfig) -> Result<(), String> {
config.filelist = Some(PathBuf::from(parse_string(value)?));
Ok(())
}
_ => {
Err(format!("unknown key `{key}` (known keys: line-length, indent, exclude, filelist)"))
}
_ => Err(format!(
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
and select, ignore under `[lint]`)"
)),
}
}
/// One key of the `[lint]` table.
fn parse_lint_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
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)"))
}
};
if slot.is_some() {
return Err(format!("duplicate key `{key}`"));
}
*slot = Some(parse_array(value)?);
Ok(())
}
fn set_int(
slot: &mut Option<usize>,
key: &str,
@@ -366,7 +410,7 @@ exclude = [ \"build\", \"*_gen.sv\", ]
#[test]
fn unsupported_toml_is_named_not_ignored() {
assert!(err("[tool.lucisv]\nindent = 2").contains("tables"));
assert!(err("[tool.lucisv]\nindent = 2").contains("unknown table"));
assert!(err("exclude = [\n \"a\",\n]").contains("multi-line arrays are unsupported"));
assert!(err("exclude = [\"a\\tb\"]").contains("escapes"));
assert!(err("indent").contains("expected `key = value`"));
@@ -376,6 +420,46 @@ exclude = [ \"build\", \"*_gen.sv\", ]
fn duplicate_keys_are_rejected() {
assert!(err("indent = 2\nindent = 4").contains("duplicate key `indent`"));
assert!(err("exclude = []\nexclude = []").contains("duplicate key `exclude`"));
assert!(
err("[lint]\nignore = [\"a\"]\nignore = [\"b\"]").contains("duplicate key `ignore`")
);
}
/// The `[lint]` table: the off switch a round that turns rules on by
/// default owes its users (topo §2.9-4).
#[test]
fn the_lint_table_carries_select_and_ignore() {
let config =
parse("[lint]\nselect = [\"no-tabs\", \"unused-signal\"]\nignore = [\"no-tabs\"]")
.expect("parses");
assert_eq!(
config.lint_select.as_deref(),
Some(&["no-tabs".to_string(), "unused-signal".to_string()][..])
);
assert_eq!(config.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
// Both are absent unless written, and the formatter keys still work
// above the table.
let mixed = parse("indent = 4\n\n[lint]\nignore = [\"unused-signal\"]").expect("parses");
assert_eq!(mixed.indent, Some(4));
assert_eq!(mixed.lint_select, None);
assert_eq!(parse("indent = 4").expect("parses").lint_ignore, None);
}
/// Rule *names* are not this crate's business — it has no registry to
/// check them against — but everything about the table's shape is.
#[test]
fn the_lint_table_rejects_what_it_does_not_support() {
assert!(err("[lint]\nbogus = [\"a\"]").contains("unknown key `bogus` under `[lint]`"));
assert!(err("[lint]\nselect = \"no-tabs\"").contains("multi-line arrays are unsupported"));
assert!(err("[lint.no-tabs]\nseverity = \"error\"").contains("per-rule lint settings"));
assert!(err("[lint]\nindent = 4").contains("unknown key `indent` under `[lint]`"));
// A key before any table still belongs to the top level.
assert!(err("select = [\"no-tabs\"]").contains("unknown key `select`"));
// Nothing closes the table — TOML's own rule, spelled out.
assert_eq!(
parse("[lint]\nselect = [\"no-tabs\"]").expect("parses").lint_select.as_deref(),
Some(&["no-tabs".to_string()][..])
);
}
/// A throwaway directory tree under the system temp dir.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+234 -8
View File
@@ -24,15 +24,20 @@ impl<'a> Positions<'a> {
/// The LSP position of a byte offset. An offset inside a multi-byte
/// character is floored to that character's start.
///
/// The conversion itself lives on [`LineIndex`], so that the semantic
/// index — which records the same positions for a declaration while its
/// file is scanned — cannot answer differently from the wire.
pub fn position(&self, offset: u32) -> Position {
let offset = self.floor_boundary(offset);
let (line, _) = self.index.line_col(offset);
let start = self.index.line_range(line).map_or(0, |r| r.start) as usize;
let slice = self.text.get(start..offset as usize).unwrap_or("");
// LSP line content excludes the whole `\r\n`; `LineIndex` keeps the
// `\r` as an ordinary byte of its line, so drop it here.
let slice = slice.strip_suffix('\r').unwrap_or(slice);
Position { line: line - 1, character: utf16_len(slice) }
let (line, character) = self.index.utf16_position(self.text, offset);
Position { line, character }
}
/// A cursor for converting many byte offsets in one non-decreasing sweep,
/// in amortized O(1) each rather than [`position`](Self::position)'s
/// O(offset within its line).
pub fn walker(&self) -> PositionWalker<'_> {
PositionWalker { positions: self, line: 0, line_start: 0, cursor: 0, units: 0 }
}
/// The byte offset of an LSP position, clamped into the document.
@@ -112,6 +117,62 @@ impl<'a> Positions<'a> {
}
}
/// A monotonic byte-offset → [`Position`] cursor, for a caller that has a
/// whole sequence of offsets to convert and already has them in order.
///
/// [`Positions::position`] measures a line from its start on every call, which
/// is free on ordinary source and quadratic when thousands of tokens sit on
/// **one** very long line — the netlist shape the large-file fast path exists
/// for, where it cost seconds per keystroke. The walker carries the
/// measurement forward instead: one line lookup per call, and each byte of a
/// line counted once however many offsets fall on it.
///
/// **Total, not merely fast.** An offset below the last one is not an error
/// and never panics: the walker restarts at that line's start and re-measures,
/// which is exactly the work [`Positions::position`] would have done. So every
/// answer is that function's answer — by construction, and pinned by
/// `the_walker_agrees_with_the_per_call_converter_on_every_shape`.
pub struct PositionWalker<'a> {
positions: &'a Positions<'a>,
/// The 1-based line the cursor sits on. Zero before the first call, which
/// is a line number no offset has, so the first call always restarts.
line: u32,
/// The byte offset that line starts at.
line_start: u32,
/// How far into the text the cursor has measured, on that line.
cursor: u32,
/// UTF-16 units of `line_start..cursor`, before the `\r` rule below.
units: u32,
}
impl PositionWalker<'_> {
/// The LSP position of a byte offset — [`Positions::position`]'s answer,
/// reached without re-measuring the line for offsets already passed.
pub fn position(&mut self, offset: u32) -> Position {
let offset = self.positions.floor_boundary(offset);
let (line, _) = self.positions.index.line_col(offset);
if line != self.line || offset < self.cursor {
self.line = line;
self.line_start = self.positions.index.line_range(line).map_or(0, |r| r.start);
self.cursor = self.line_start;
self.units = 0;
}
let step = self.positions.text.get(self.cursor as usize..offset as usize).unwrap_or("");
self.units += utf16_len(step);
self.cursor = offset;
// The one `\r` `Positions::position`'s `strip_suffix` would drop: LSP
// line content excludes the whole `\r\n`, and `\r` is one UTF-16 unit.
let carriage = offset > self.line_start
&& self.positions.text.as_bytes().get(offset as usize - 1) == Some(&b'\r');
Position { line: line - 1, character: self.units - u32::from(carriage) }
}
/// The LSP range of a byte range, whose two ends are in order already.
pub fn range(&mut self, span: TextRange) -> Range {
Range { start: self.position(span.start), end: self.position(span.end) }
}
}
/// How many UTF-16 code units a string occupies — the unit LSP counts in.
fn utf16_len(s: &str) -> u32 {
s.chars().map(|c| c.len_utf16() as u32).sum()
@@ -283,6 +344,171 @@ mod tests {
});
}
// ------------------------------------------------------------------
// the monotonic walker
// ------------------------------------------------------------------
/// A fixed-seed linear congruential generator — deterministic randomness
/// with no dependency. The constants are Knuth's MMIX, as `sync.rs` and
/// `tokens.rs` use.
struct Lcg(u64);
impl Lcg {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
self.0 >> 33
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n.max(1)
}
}
/// Every shape a byte → position converter has to survive: multi-byte and
/// astral characters, CRLF, empty lines, a last line with no terminator,
/// and a buffer that is one enormous line — the shape the walker exists
/// for.
fn fixtures() -> Vec<String> {
let mut giant = String::from("module m; wire ");
for n in 0..2_000 {
giant.push_str(&format!("a{n},"));
}
giant.push_str("last;\nendmodule\n");
let mut wide_and_wide = String::from("// é ✓ 🎉 ");
for n in 0..500 {
wide_and_wide.push_str(&format!("würe_{n}_✓, "));
}
wide_and_wide.push_str("\r\nendmodule\n");
vec![
String::new(),
"module m;\nendmodule\n".to_string(),
"// é ✓ 🎉\r\nmodule mü;\n wire ✓a;\r\nendmodule".to_string(),
"ab\r\ncd\r\n\r\nef\r\n".to_string(),
"\n".repeat(50),
giant,
wide_and_wide,
]
}
#[test]
fn the_walker_agrees_with_the_per_call_converter_on_every_shape() {
let mut rng = Lcg(0x5EEDA11);
for text in fixtures() {
let index = LineIndex::new(&text);
let positions = Positions::new(&text, &index);
let len = text.len() as u64;
for trial in 0..20 {
// Two strides, alternating: a crawl of a few bytes at a time
// (many offsets on one line, which is what the walker is for)
// and one that crosses the whole fixture in a few dozen steps.
let stride = if trial % 2 == 0 { 4 } else { (len / 20).max(1) };
let mut offset = rng.below(len + 1) as u32;
let mut walker = positions.walker();
for _ in 0..60 {
assert_eq!(
walker.position(offset),
positions.position(offset),
"{text:?} at {offset}"
);
offset += rng.below(stride * 2) as u32;
}
}
}
}
#[test]
fn the_walker_agrees_at_every_byte_of_a_gnarly_buffer() {
// Ascending one byte at a time walks through the middle of every
// multi-byte character and over both bytes of every `\r\n`.
let text = "// é ✓ 🎉\r\nmodule mü;\n\r\n wire ✓a;\r\nendmodule";
let index = LineIndex::new(text);
let positions = Positions::new(text, &index);
let mut walker = positions.walker();
for offset in 0..=text.len() as u32 + 2 {
assert_eq!(walker.position(offset), positions.position(offset), "at {offset}");
}
}
#[test]
fn a_walker_handed_offsets_out_of_order_still_answers_the_per_call_position() {
// Out of order is debug-unreachable for the callers, but the walker
// is total: a backwards offset restarts the measurement rather than
// returning a stale column.
let text = "// é ✓ 🎉\r\nmodule mü;\n wire ✓a;\r\nendmodule";
let index = LineIndex::new(text);
let positions = Positions::new(text, &index);
let mut rng = Lcg(0xBACC1);
let mut walker = positions.walker();
for _ in 0..500 {
let offset = rng.below(text.len() as u64 + 4) as u32;
assert_eq!(walker.position(offset), positions.position(offset), "at {offset}");
}
}
/// QA attack (fix-round re-verification): the walker's restart is a
/// per-line promise, not a per-document one. Two huge lines far apart,
/// hit in alternation — the shape that would expose an accidental
/// document-wide rescan hiding inside the "reset to line start" path.
/// Each call still answers `Positions::position`'s answer exactly, and
/// (checked by hand alongside this test, not asserted here to keep the
/// test itself fast and non-flaky) costs only that one line's length,
/// never the whole document's.
#[test]
fn a_walker_ping_ponged_between_two_far_apart_lines_still_answers_correctly() {
let mut text = String::new();
text.push_str(&"a".repeat(20_000));
text.push('\n');
text.push_str(&"b".repeat(20_000));
text.push('\n');
let index = LineIndex::new(&text);
let positions = Positions::new(&text, &index);
let line1_positions = [0u32, 1, 5_000, 19_999, 20_000];
let line2_start = 20_001u32;
let line2_positions =
[line2_start, line2_start + 1, line2_start + 5_000, line2_start + 19_999];
let mut walker = positions.walker();
for round in 0..50 {
let (a, b) = line1_positions
.iter()
.zip(line2_positions.iter().cycle())
.nth(round % line1_positions.len())
.expect("non-empty");
for &offset in [*a, *b].iter() {
assert_eq!(
walker.position(offset),
positions.position(offset),
"round {round}, offset {offset}"
);
}
}
}
#[test]
fn the_walkers_range_is_the_per_call_range() {
let text = "module m;\r\n wire ✓a, b, c;\nendmodule\n";
let index = LineIndex::new(text);
let positions = Positions::new(text, &index);
let mut walker = positions.walker();
for span in [
TextRange::new(0, 6),
TextRange::new(9, 11),
TextRange::new(13, 17),
TextRange::new(20, 21),
TextRange::new(30, text.len() as u32),
] {
assert_eq!(walker.range(span), positions.range(span), "{span:?}");
}
}
#[test]
fn a_walker_over_an_empty_document_answers_the_one_position_there_is() {
with("", |p| {
let mut walker = p.walker();
assert_eq!(walker.position(0), pos(0, 0));
assert_eq!(walker.position(99), pos(0, 0));
});
}
#[test]
fn an_empty_document_has_one_position() {
with("", |p| {
@@ -0,0 +1,525 @@
//! The VS Code instance-oriented design hierarchy.
//!
//! LSP call hierarchy deliberately groups a module's calls by target module
//! type. The sidebar needs the other view of the same facts: every individual
//! instance name, its source range, and every declaration its module type may
//! name. The response stays flat; the client chooses roots and expands paths,
//! which keeps recursion out of the protocol and lets one snapshot serve
//! search as well as rendering.
//!
//! **Two things this answer must not be, and the shape follows from both.** It
//! must not read files — every line and character below was converted once,
//! when the declaring file was scanned, and rides the index
//! (`vlog_semantic::DeclPositions`, `InstanceOccurrence::positions`). And it
//! must not be enormous: a whole design re-sent on every save is a message the
//! request queue is blocked writing. So a URI is written **once**, in `files`,
//! and every location names it by index; a range is four numbers rather than
//! four nested objects; a row carries no id, because the client can compose the
//! one it used to be sent; and an instance carries no copy of the declarations
//! its module name resolves to, because the client already has every module.
//! Those four together are 11.6 MB → 1.9 MB on opentitan, and the client
//! rebuilds the richer shape in `hierarchyModel.js`'s `validateSnapshot` — see
//! `docs/features/vscode-hierarchy-sidebar/README.md`.
use std::collections::HashMap;
use serde::Serialize;
use vlog_semantic::{FileId, Utf16Range, WorkspaceIndex};
use crate::state::Workspace;
use crate::uri::path_to_uri;
pub const METHOD: &str = "lucisv/moduleHierarchy";
pub const CHANGED_METHOD: &str = "lucisv/moduleHierarchyChanged";
/// The wire version. Bumped on any change to the shape below; the client
/// refuses a snapshot it does not recognise rather than half-reading one.
const SCHEMA_VERSION: u32 = 2;
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Snapshot {
schema_version: u32,
revision: u64,
complete: bool,
/// Every file a location below names, once. Locations index into this.
files: Vec<String>,
modules: Vec<Module>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct Module {
module_name: String,
definition: Location,
instances: Vec<Instance>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct Instance {
instance_name: String,
module_name: String,
site: Location,
}
/// A place in the workspace: which file, the whole construct, and the name
/// inside it. Each range is `[startLine, startCharacter, endLine,
/// endCharacter]`, 0-based lines and UTF-16 characters — an LSP `Range` with
/// its four field names left off.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct Location {
file: u32,
range: [u32; 4],
selection_range: [u32; 4],
}
/// A complete snapshot of the index currently installed in `workspace`.
///
/// **It reads no files.** The first shape of this function read every
/// module-declaring file and built a `LineIndex` over each — 5.0 s cold and
/// ~300 ms warm on opentitan, on *every* request, which is the per-request
/// whole-workspace read the release before it existed to kill.
///
/// `complete` is false only when the request arrived between two files of the
/// startup scan. The server sends `CHANGED_METHOD` when that scan lands, so a
/// client can render the partial answer as loading and replace it once.
pub fn snapshot(workspace: &Workspace, revision: u64, complete: bool) -> Snapshot {
let index = workspace.index();
let mut files = FileTable::default();
let mut modules = Vec::new();
let mut module_at = HashMap::new();
// An interface instance is an instantiation edge exactly as a module
// instance is, so both kinds are roots here — the wire shape is unchanged.
for (name, def) in index.instantiable_units() {
// Every file-scope declaration carries its positions; one without them
// would be a declaration the index built by some other route, and
// dropping it beats inventing a range for it.
let Some(positions) = def.lines.positions else { continue };
let Some(file) = files.of(index, def.file) else { continue };
module_at.insert((def.file, def.name_span.start, def.name_span.end), modules.len());
modules.push(Module {
module_name: name.to_string(),
definition: location(file, positions.name, positions.decl),
instances: Vec::new(),
});
}
for (target_name, edges) in index.instantiations() {
for edge in edges {
let owner = (edge.file, edge.owner.name_span.start, edge.owner.name_span.end);
let Some(&owner_at) = module_at.get(&owner) else { continue };
let Some(file) = files.of(index, edge.file) else { continue };
for occurrence in &edge.instances {
modules[owner_at].instances.push(Instance {
instance_name: occurrence.name.clone(),
module_name: target_name.to_string(),
site: location(file, occurrence.name_positions, occurrence.positions),
});
}
}
}
// `sort_by_cached_key`, not `sort_by`: both keys lowercase a name, and
// paying for that once per element rather than twice per comparison is the
// difference between a few and a few hundred thousand allocations on a
// workspace with 14 000 instances in it.
for module in &mut modules {
module.instances.sort_by_cached_key(|instance| instance_key(&files, instance));
}
modules.sort_by_cached_key(|module| module_key(&files, module));
Snapshot { schema_version: SCHEMA_VERSION, revision, complete, files: files.uris, modules }
}
/// The snapshot's file table: one URI per file, given an index the first time
/// a location needs it.
#[derive(Default)]
struct FileTable {
uris: Vec<String>,
at: HashMap<FileId, Option<u32>>,
}
impl FileTable {
/// This file's index, adding it if it is new. `None` for a path that is
/// not a URI — the same answer every other feature gives for such a path,
/// and it drops that file's rows rather than the whole snapshot.
fn of(&mut self, index: &WorkspaceIndex, file: FileId) -> Option<u32> {
if let Some(&known) = self.at.get(&file) {
return known;
}
let found = index.path(file).and_then(path_to_uri).map(|uri| {
self.uris.push(uri.as_str().to_string());
self.uris.len() as u32 - 1
});
self.at.insert(file, found);
found
}
fn uri(&self, file: u32) -> &str {
self.uris.get(file as usize).map_or("", |uri| uri.as_str())
}
}
/// One location, built from ranges the index already holds.
fn location(file: u32, selection: Utf16Range, whole: Utf16Range) -> Location {
Location { file, range: range(whole), selection_range: range(selection) }
}
fn range(range: Utf16Range) -> [u32; 4] {
[range.start.line, range.start.character, range.end.line, range.end.character]
}
fn module_key(files: &FileTable, module: &Module) -> (String, String, u32, u32) {
(
module.module_name.to_ascii_lowercase(),
files.uri(module.definition.file).to_string(),
module.definition.selection_range[0],
module.definition.selection_range[1],
)
}
fn instance_key(files: &FileTable, instance: &Instance) -> (String, String, String, u32, u32) {
(
instance.instance_name.to_ascii_lowercase(),
instance.module_name.to_ascii_lowercase(),
files.uri(instance.site.file).to_string(),
instance.site.selection_range[0],
instance.site.selection_range[1],
)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::{json, Value};
use std::path::PathBuf;
struct Tree(PathBuf);
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("lucisv_design_hierarchy_{}_{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("temp dir");
Tree(path)
}
fn write(&self, name: &str, text: &str) {
std::fs::write(self.0.join(name), text).expect("write fixture");
}
fn workspace(&self) -> Workspace {
let mut workspace = Workspace::default();
workspace.open_whole_workspace(vec![self.0.clone()]);
workspace
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn taken(workspace: &Workspace) -> Value {
serde_json::to_value(snapshot(workspace, 7, true)).expect("serializes")
}
#[test]
fn a_snapshot_is_flat_sorted_and_keeps_every_individual_instance() {
let tree = Tree::new("flat");
tree.write("leaf.sv", "module leaf; endmodule\n");
tree.write("top.sv", "module top;\n leaf zed (), alpha ();\nendmodule\n");
tree.write("tb.sv", "module TB; top dut (); missing u_missing (); endmodule\n");
let value = taken(&tree.workspace());
assert_eq!(value["schemaVersion"], 2);
assert_eq!(value["revision"], 7);
assert_eq!(value["complete"], true);
let modules = value["modules"].as_array().expect("modules");
let names: Vec<&str> =
modules.iter().map(|module| module["moduleName"].as_str().expect("name")).collect();
assert_eq!(names, ["leaf", "TB", "top"], "case-insensitive alphabetical order");
let top = module(modules, "top");
// `[startLine, startCharacter, endLine, endCharacter]`: the whole
// module for `range`, its name alone for `selectionRange`.
assert_eq!(top["definition"]["range"], json!([0, 0, 2, 9]));
assert_eq!(top["definition"]["selectionRange"], json!([0, 7, 0, 10]));
let instances = top["instances"].as_array().expect("instances");
let names: Vec<&str> = instances
.iter()
.map(|instance| instance["instanceName"].as_str().expect("name"))
.collect();
assert_eq!(names, ["alpha", "zed"], "one statement became two sorted children");
let tb = module(modules, "TB");
let missing = tb["instances"]
.as_array()
.expect("instances")
.iter()
.find(|instance| instance["instanceName"] == "u_missing")
.expect("unresolved instance is still a row");
// Nothing on the wire says "unresolved": the client asks its own module
// table for `missing`, finds none, and that is the same answer.
assert_eq!(missing["moduleName"], "missing");
assert_eq!(missing["site"]["selectionRange"][0], 0);
}
/// An interface is an instantiable unit, so it is a row of the sidebar
/// and an interface instance is an ordinary child — exactly as both were
/// when an interface was indexed as a `SymbolKind::Module`
/// (`docs/features/interface-semantics/README.md`). The wire shape is
/// unchanged: schema 2, the same fields, one more module row.
#[test]
fn an_interface_is_a_row_and_its_instance_a_child_like_any_other() {
let tree = Tree::new("iface");
tree.write("bus_if.sv", "interface bus_if;\nendinterface\n");
tree.write("top.sv", "module top;\n bus_if u_bus ();\nendmodule\n");
let value = taken(&tree.workspace());
assert_eq!(value["schemaVersion"], 2);
let modules = value["modules"].as_array().expect("modules");
let names: Vec<&str> =
modules.iter().map(|module| module["moduleName"].as_str().expect("name")).collect();
assert_eq!(names, ["bus_if", "top"]);
let instances = module(modules, "top")["instances"].as_array().expect("instances");
assert_eq!(instances.len(), 1);
assert_eq!(instances[0]["instanceName"], "u_bus");
assert_eq!(instances[0]["moduleName"], "bus_if");
}
/// The round's central claim, pinned the way `hover-line-index` pinned its
/// own: delete every source file after indexing, and the answer is
/// byte-identical, because no part of it comes from a file.
#[test]
fn a_snapshot_reads_no_files_at_all() {
let tree = Tree::new("noreads");
tree.write("leaf.sv", "module leaf; endmodule\n");
tree.write("top.sv", "module top;\n leaf u_leaf ();\nendmodule\n");
let workspace = tree.workspace();
let before = taken(&workspace);
assert_eq!(
before["modules"].as_array().expect("modules").len(),
2,
"premise: both indexed"
);
for name in ["leaf.sv", "top.sv"] {
std::fs::remove_file(tree.0.join(name)).expect("delete");
}
assert_eq!(taken(&workspace), before, "the snapshot came from the index, not the disk");
}
/// A URI appears once however many rows name it, and a range is four
/// numbers — the two decisions that took the opentitan answer from 11.6 MB
/// to under 2 MB.
#[test]
fn every_file_is_named_once_and_a_range_is_four_numbers() {
let tree = Tree::new("filetable");
tree.write("leaf.sv", "module leaf; endmodule\n");
tree.write("top.sv", "module top;\n leaf a (), b (), c ();\nendmodule\n");
let value = taken(&tree.workspace());
let files = value["files"].as_array().expect("files");
assert_eq!(files.len(), 2, "one entry per file, not one per row: {files:#?}");
let text = serde_json::to_string(&value).expect("serializes");
for uri in files {
let uri = uri.as_str().expect("a uri string");
assert_eq!(text.matches(uri).count(), 1, "{uri} is written more than once");
}
let top = module(value["modules"].as_array().expect("modules"), "top");
for instance in top["instances"].as_array().expect("instances") {
assert!(instance["site"]["file"].is_number(), "a file index, not a URI");
assert_eq!(instance["site"]["range"].as_array().expect("range").len(), 4);
}
}
/// Positions are the client's, not the index's: 0-based lines and UTF-16
/// code units, so a two-byte character before a name still counts one.
#[test]
fn positions_are_zero_based_utf16_even_through_multibyte_text() {
let tree = Tree::new("utf16");
// `🎉` is four UTF-8 bytes and two UTF-16 units, so every column after
// it on that line differs from the byte column the index records.
tree.write("m.sv", "module top;\n /*\u{1F389}*/ sub u_x ();\nendmodule\n");
let value = taken(&tree.workspace());
let top = module(value["modules"].as_array().expect("modules"), "top");
assert_eq!(
top["definition"]["selectionRange"],
json!([0, 7, 0, 10]),
"line 0 counting from 0, `top` at character 7"
);
let instance = &top["instances"].as_array().expect("instances")[0];
assert_eq!(instance["instanceName"], "u_x");
assert_eq!(instance["site"]["selectionRange"], json!([1, 13, 1, 16]));
assert_eq!(instance["site"]["range"], json!([1, 13, 1, 19]));
}
/// **The one property the whole zero-I/O trick rests on**: a position the
/// index recorded while a file was scanned is the position `convert` would
/// have produced from that file's text on the wire. The two answers come
/// from one function on `LineIndex`, and this is what says so out loud —
/// over the shapes that break naive conversions.
#[test]
fn an_indexed_position_is_the_position_the_wire_converter_would_have_given() {
let sources = [
"module plain;\n sub u ();\nendmodule\n",
// A CRLF file: `\r` is a byte of its line but not of its content.
"module crlf;\r\n sub u_crlf ();\r\nendmodule\r\n",
// Two, three and four byte characters ahead of the names.
"// \u{e9}\u{2713}\u{1F389}\nmodule wide;\n /*\u{1F389}*/ sub u_wide ();\nendmodule\n",
// A name on the last line, with no trailing newline at all.
"module tail;\n sub u_tail ();\nendmodule",
// Two instances in one statement, and an attribute before `module`.
"(* keep *) module many;\n sub a (), b ();\nendmodule\n",
// CRLF and bare LF mixed in one file: the `\r`-stripping rule must
// apply per line, not once for the whole file.
"module mixed;\r\n sub u_a ();\n sub u_b ();\r\nendmodule\n",
// The instance on the very same line as the module header, so the
// name and the instance share a line's worth of UTF-16 columns.
"module oneline; sub u_same ();\nendmodule\n",
];
let tree = Tree::new("agreement");
let mut texts = Vec::new();
for (at, source) in sources.iter().enumerate() {
tree.write(&format!("f{at}.sv"), source);
texts.push((tree.0.join(format!("f{at}.sv")), *source));
}
let workspace = tree.workspace();
let index = workspace.index();
let mut checked = 0usize;
for (path, text) in &texts {
let lines = vlog_parser::LineIndex::new(text);
let positions = crate::convert::Positions::new(text, &lines);
let file = index.file_id(path).expect("the file is indexed");
for (_, def) in index.instantiable_units() {
if def.file != file {
continue;
}
let recorded = def.lines.positions.expect("a unit carries positions");
assert_eq!(range(recorded.name), as_four(positions.range(def.name_span)));
assert_eq!(range(recorded.decl), as_four(positions.range(def.decl_span)));
checked += 1;
}
for (_, edges) in index.instantiations() {
for edge in edges.iter().filter(|edge| edge.file == file) {
for occurrence in &edge.instances {
assert_eq!(
range(occurrence.name_positions),
as_four(positions.range(occurrence.name_span))
);
assert_eq!(
range(occurrence.positions),
as_four(positions.range(occurrence.span))
);
checked += 1;
}
}
}
}
assert!(checked >= 16, "premise: every fixture contributed rows, got {checked}");
}
/// QA (2026-08-29): two files declaring the same module name must each
/// keep their own row, their own instances, and never merge — the wire's
/// only handle on a module is `(file, definition range)`, exactly as an
/// ambiguous type is meant to look on the client.
#[test]
fn duplicate_module_names_across_files_stay_two_distinct_rows() {
let tree = Tree::new("duplicate");
tree.write("a.sv", "module dup;\n sub u_in_a ();\nendmodule\n");
tree.write("b.sv", "module dup;\n sub u_in_b ();\nendmodule\n");
tree.write("sub.sv", "module sub; endmodule\n");
let value = taken(&tree.workspace());
let modules = value["modules"].as_array().expect("modules");
let dups: Vec<&Value> =
modules.iter().filter(|module| module["moduleName"] == "dup").collect();
assert_eq!(dups.len(), 2, "one row per declaration, not one merged row: {dups:#?}");
assert_ne!(
dups[0]["definition"]["file"], dups[1]["definition"]["file"],
"the only thing distinguishing them is which file",
);
let mut instance_names: Vec<&str> = dups
.iter()
.flat_map(|module| module["instances"].as_array().expect("instances"))
.map(|instance| instance["instanceName"].as_str().expect("name"))
.collect();
instance_names.sort_unstable();
assert_eq!(
instance_names,
["u_in_a", "u_in_b"],
"each declaration keeps only the instances its own body writes",
);
}
/// QA (2026-08-29): an escaped Verilog identifier (`\foo$bar `, terminated
/// by whitespace, the space itself not part of the name) is as ordinary a
/// module or instance name as any other — the wire and the position
/// conversion must not choke on the backslash or the trailing space.
#[test]
fn an_escaped_identifier_names_a_module_and_an_instance() {
let tree = Tree::new("escaped");
tree.write(
"m.sv",
"module \\weird$leaf ;\nendmodule\n\
module top;\n \\weird$leaf \\u$inst ();\nendmodule\n",
);
let value = taken(&tree.workspace());
let modules = value["modules"].as_array().expect("modules");
let leaf = module(modules, "\\weird$leaf");
assert_eq!(leaf["instances"].as_array().expect("instances").len(), 0);
let top = module(modules, "top");
let instances = top["instances"].as_array().expect("instances");
assert_eq!(instances.len(), 1);
assert_eq!(instances[0]["instanceName"], "\\u$inst");
assert_eq!(instances[0]["moduleName"], "\\weird$leaf");
}
/// QA (2026-08-29): a module instantiated 100 times in one statement list
/// produces 100 individual, individually sorted instance rows — the
/// flattening the sidebar exists for, at a scale one instance would not
/// exercise.
#[test]
fn one_hundred_instances_of_one_module_are_one_hundred_sorted_rows() {
let tree = Tree::new("manyinstances");
tree.write("leaf.sv", "module leaf; endmodule\n");
let instances: Vec<String> = (0..100).map(|n| format!("u_{n:03} ()", n = n)).collect();
tree.write(
"top.sv",
&format!("module top;\n leaf {};\nendmodule\n", instances.join(", ")),
);
let value = taken(&tree.workspace());
let top = module(value["modules"].as_array().expect("modules"), "top");
let instances = top["instances"].as_array().expect("instances");
assert_eq!(instances.len(), 100, "every one of the 100 instances is its own row");
let names: Vec<&str> = instances
.iter()
.map(|instance| instance["instanceName"].as_str().expect("name"))
.collect();
let mut sorted = names.clone();
sorted.sort_unstable();
assert_eq!(names, sorted, "sorted by instance name, as every module's instances are");
assert!(instances.iter().all(|instance| instance["moduleName"] == "leaf"));
}
fn as_four(range: lsp_types::Range) -> [u32; 4] {
[range.start.line, range.start.character, range.end.line, range.end.character]
}
fn module<'a>(modules: &'a [Value], name: &str) -> &'a Value {
modules
.iter()
.find(|module| module["moduleName"] == name)
.unwrap_or_else(|| panic!("no module {name}: {modules:#?}"))
}
}
+23 -1
View File
@@ -23,10 +23,32 @@ pub const SOURCE: &str = "lucisv";
/// The missing-closer warnings sit between the two: they explain a parse
/// error rather than add an opinion, and they exist at all only when the parse
/// already failed (`pairs::missing_end_diagnostics`).
///
/// `#[cfg(test)]` for the same reason `lint::diagnostics` is: the server
/// always has a workspace and always calls [`all_in`], so this is the door the
/// tests that predate the project-aware pass come in by.
#[cfg(test)]
pub fn all(doc: &Document) -> Vec<Diagnostic> {
all_in(doc, &crate::lint::LintRun::default())
}
/// [`all`] for a lint pass that knows what the project says — the workspace's
/// rule selection and its identifier census
/// (`docs/features/semantic-lints-on/README.md`). The parse and missing-closer
/// halves are unaffected by either; only the lint pass reads `run`.
pub fn all_in(doc: &Document, run: &crate::lint::LintRun) -> Vec<Diagnostic> {
// A buffer on the large-file fast path was never parsed, so there is
// nothing to say about it — and both passes below would read its *text*
// (the lint context builds one, the fence filter scans for them), which is
// the whole-file work the fast path exists to skip. The empty list is not
// a silent no-op either: it is what clears the squiggles a buffer that has
// just grown past the threshold left behind.
if doc.large {
return Vec::new();
}
let mut all = diagnostics(doc);
all.extend(crate::pairs::missing_end_diagnostics(doc));
all.extend(crate::lint::diagnostics(doc));
all.extend(crate::lint::diagnostics_in(doc, run));
all
}
+187 -8
View File
@@ -105,10 +105,15 @@ pub struct Rewrite {
/// Rewrite every `` `include`` in the workspace that resolves to a file the
/// client is about to rename.
///
/// The sweep reads the in-scope files (`Workspace::sources`, so an unopened
/// file is read off disk and an open buffer contributes its unsaved text), and
/// asks the include graph — never the filename — which of them point at
/// something that moves.
/// The sweep reads the files the include graph recorded an `` `include`` in
/// (`Workspace::include_sources`, so an unopened one is read off disk and an
/// open buffer contributes its unsaved text), and asks the include graph —
/// never the filename — which of them point at something that moves.
///
/// It used to read *every* in-scope file, which on a 3 976-file workspace is
/// 3 900-odd reads to answer "this file has no `` `include``". The graph
/// already holds that answer; the argument that the smaller set gives the
/// identical `Rewrite` is in `docs/features/file-operations/README.md`.
pub fn will_rename(ws: &Workspace, files: &[FileRename]) -> Rewrite {
let moves = Moves::announced(files);
if moves.0.is_empty() {
@@ -117,7 +122,7 @@ pub fn will_rename(ws: &Workspace, files: &[FileRename]) -> Rewrite {
let graph = ws.includes();
let mut changes: HashMap<Uri, Vec<TextEdit>> = HashMap::new();
let mut warnings = Vec::new();
for (path, text) in ws.sources() {
for (path, text) in ws.include_sources() {
// The overwhelming majority of files include nothing; one substring
// test each is what keeps this off the resolver for all of them.
if !text.contains("`include") {
@@ -520,7 +525,7 @@ mod tests {
..Default::default()
});
}
ws.open_roots(vec![self.path.clone()]);
ws.open_whole_workspace(vec![self.path.clone()]);
ws
}
@@ -542,6 +547,35 @@ mod tests {
path_to_uri(path).expect("uri").as_str().to_string()
}
/// The sufficiency property [`will_rename`]'s narrowed sweep rests on,
/// asserted directly over whatever tree the caller built: every in-scope
/// file the sweep no longer reads writes no `` `include`` this workspace
/// can resolve, so its turn in the loop could only ever have `continue`d.
///
/// Checked as the complement rather than as an equality because it is the
/// complement that could hide a lost edit: an extra file in the set costs
/// a read, a missing one costs an `` `include`` left pointing at nothing.
fn nothing_skipped_has_an_include_to_rewrite(ws: &Workspace) {
let read: Vec<PathBuf> = ws.include_sources().into_iter().map(|(path, _)| path).collect();
let graph = ws.includes();
let mut skipped = 0usize;
for (path, text) in ws.sources() {
if read.contains(&path) {
continue;
}
skipped += 1;
for include in scan(&text) {
assert!(
graph.resolve(Some(&path), &include).is_none(),
"{} was skipped but its `include \"{}\"` resolves",
path.display(),
include.target
);
}
}
assert!(skipped > 0, "the tree must actually exercise the narrowing");
}
/// The one file the rewrite touches, as (uri, the new path spellings).
fn only_file(rewrite: &Rewrite) -> (String, Vec<String>) {
let edit = rewrite.edit.as_ref().expect("an edit");
@@ -579,6 +613,120 @@ mod tests {
out
}
/// A wide workspace where almost nothing includes anything — the shape a
/// real one has, and the reason the sweep no longer reads all of it. The
/// answer must be the one the whole-workspace sweep gave, and the property
/// above must hold over the same tree.
#[test]
fn the_narrowed_sweep_reads_the_includers_and_answers_the_same() {
let tree = Tree::new("narrowed");
tree.write("rtl/defs.svh", "`define W 8\n");
let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\nmodule t;\nendmodule\n");
let mut list = String::from("rtl/top.sv\nrtl/defs.svh\n");
// Twenty files with no `include at all, plus two whose includes name
// nothing on disk — both kinds are files the sweep may skip.
for n in 0..20 {
let rel = format!("rtl/quiet{n}.sv");
tree.write(&rel, &format!("module quiet{n};\n wire w;\nendmodule\n"));
list.push_str(&format!("{rel}\n"));
}
for n in 0..2 {
let rel = format!("rtl/dangling{n}.sv");
tree.write(&rel, &format!("`include \"no_such_{n}.svh\"\nmodule d{n};\nendmodule\n"));
list.push_str(&format!("{rel}\n"));
}
tree.write("files.f", &list);
let ws = tree.workspace();
assert_eq!(ws.sources().len(), 24, "the whole scope");
assert_eq!(ws.include_sources().len(), 1, "only `top.sv` includes anything that lands");
nothing_skipped_has_an_include_to_rewrite(&ws);
let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]);
assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings);
assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()]));
}
/// An `` `include`` typed into a buffer and not yet saved is in no edge the
/// graph holds — the graph is rebuilt on save. The buffer is in the sweep
/// whatever the graph says, which is what keeps that include rewritten.
#[test]
fn an_unsaved_include_is_still_rewritten() {
let tree = Tree::new("unsaved_include");
tree.write("rtl/defs.svh", "`define W 8\n");
let top = tree.write("rtl/top.sv", "module t;\nendmodule\n");
tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n");
let mut ws = tree.workspace();
assert_eq!(ws.include_sources().len(), 0, "premise: the graph knows of no include");
let buffered = "`include \"defs.svh\"\nmodule t;\nendmodule\n";
ws.set_document(path_to_uri(&top).expect("uri"), buffered.to_string());
let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]);
assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()]));
assert_eq!(
applied(buffered, &rewrite, &uri_of(&top)),
"`include \"widths.svh\"\nmodule t;\nendmodule\n"
);
}
/// QA, 2026-08-28 attack: a chain `a.svh -> b.svh`. Renaming `b.svh` must
/// narrow to `a.svh` (its *direct* includer, via `includers()`), and must
/// **not** narrow away a file that includes `a.svh` but never spells
/// `b.svh` at all — `will_rename` only ever rewrites a *direct* include of
/// the file that moves, so a third-order includer has nothing to rewrite
/// either way, but it must still not be mistaken for a candidate (which
/// would cost a read, not a corruption, but is worth pinning).
#[test]
fn an_include_chain_narrows_to_the_direct_includer_of_the_moved_file() {
let tree = Tree::new("chain");
tree.write("rtl/b.svh", "`define W 8\n");
let a = tree.write("rtl/a.svh", "`include \"b.svh\"\n");
let c = tree.write("rtl/c.sv", "`include \"a.svh\"\nmodule c;\nendmodule\n");
tree.write("files.f", "rtl/a.svh\nrtl/b.svh\nrtl/c.sv\n");
let ws = tree.workspace();
let read: Vec<PathBuf> = ws.include_sources().into_iter().map(|(path, _)| path).collect();
assert!(read.contains(&a), "a.svh includes b.svh directly: {read:?}");
assert!(read.contains(&c), "c.sv includes a.svh directly: {read:?}");
nothing_skipped_has_an_include_to_rewrite(&ws);
let rewrite = will_rename(&ws, &[tree.rename("rtl/b.svh", "rtl/renamed_b.svh")]);
assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings);
// Only a.svh's own `include \"b.svh\"` line changes; c.sv's
// `include \"a.svh\"` is untouched because a.svh itself did not move.
assert_eq!(only_file(&rewrite), (uri_of(&a), vec!["renamed_b.svh".to_string()]));
}
/// QA, 2026-08-28 attack: an include spelled with different letter case
/// than the file actually has on disk (`` `include "DEFS.svh"`` against a
/// real `defs.svh`) — legal and silently resolved on the common
/// case-insensitive filesystems (confirmed case-insensitive in this test
/// environment). `IncludeGraph::found`/`found_as_if` resolve through the
/// filesystem's own `Path::is_file`, so the includer still lands in `raw`
/// (keyed by the *includer's* path, not the target's spelling) and
/// therefore in `includers()`/`include_sources()` — the narrowing must not
/// accidentally depend on the include's target spelling matching the
/// disk's.
#[test]
fn a_case_mismatched_include_spelling_still_narrows_in_and_rewrites() {
let tree = Tree::new("case_mismatch");
tree.write("rtl/defs.svh", "`define W 8\n");
let top = tree.write("rtl/top.sv", "`include \"DEFS.svh\"\nmodule t;\nendmodule\n");
tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n");
let ws = tree.workspace();
let read: Vec<PathBuf> = ws.include_sources().into_iter().map(|(path, _)| path).collect();
assert!(
read.contains(&top),
"top.sv's case-mismatched include still resolves and must narrow in: {read:?}"
);
let rewrite = will_rename(&ws, &[tree.rename("rtl/defs.svh", "rtl/widths.svh")]);
assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings);
assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["widths.svh".to_string()]));
}
#[test]
fn a_same_directory_rename_keeps_the_bare_form() {
let tree = Tree::new("samedir");
@@ -599,6 +747,37 @@ mod tests {
);
}
/// Renaming a file that is open **on the large-file fast path**
/// (`docs/features/large-file-mode/README.md`). The renamed file's own
/// `` `include``s (it has none here — a netlist would not) are out of
/// `will_rename`'s sweep because `Workspace::sources()` already leaves a
/// fast-path buffer out entirely; what this pins is the other half: an
/// **unrelated** small file's include *of* the large file still resolves
/// and still gets rewritten, because resolution walks the filesystem
/// (`IncludeGraph::resolve`, `Path::is_file`) rather than the source list
/// the fast-path buffer was excluded from.
#[test]
fn renaming_a_large_open_buffer_still_rewrites_other_files_includes_to_it() {
let tree = Tree::new("largerename");
let net = tree.write("rtl/net.v", "module net;\nendmodule\n");
let top = tree.write("rtl/top.sv", "`include \"net.v\"\nmodule t;\nendmodule\n");
tree.write("files.f", "rtl/top.sv\nrtl/net.v\n");
let mut ws = tree.workspace();
ws.set_client_settings(crate::settings::ClientSettings {
filelist: Some(tree.path.join("files.f").display().to_string()),
large_file_threshold: 10,
..Default::default()
});
let net_uri = path_to_uri(&net).expect("uri");
// Padded past the 10-byte test threshold, so it opens on the fast path.
ws.set_document(net_uri.clone(), format!("module net;\nendmodule\n{}", " ".repeat(20)));
assert!(ws.document(&net_uri).expect("open").large, "premise: the fast path");
let rewrite = will_rename(&ws, &[tree.rename("rtl/net.v", "rtl/netlist.v")]);
assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings);
assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["netlist.v".to_string()]));
}
#[test]
fn a_cross_directory_rename_re_spells_through_an_incdir() {
let tree = Tree::new("crossdir");
@@ -1055,7 +1234,7 @@ mod tests {
// same read the index rebuild already pays on every save.
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
let mut ws = Workspace::default();
ws.open_roots(vec![root.clone()]);
ws.open_whole_workspace(vec![root.clone()]);
let files = ws.index().files().len();
assert!(files > 500, "the corpus is checked in: got {files}");
let rename = FileRename {
@@ -1401,7 +1580,7 @@ mod tests {
let new = target_dir.join("prim_assert_renamed.sv");
let mut ws = Workspace::default();
ws.open_roots(vec![root.clone()]);
ws.open_whole_workspace(vec![root.clone()]);
let rename = FileRename { old_uri: uri_of(&old), new_uri: uri_of(&new) };
let run = || {
+110 -66
View File
@@ -22,10 +22,11 @@ use lsp_types::{
};
use vlog_parser::ast::Item;
use vlog_parser::{parse_source_tolerant, LineIndex, TextRange};
use vlog_semantic::SymbolKind as SemanticKind;
use vlog_semantic::instantiations::{self, Decl};
use vlog_semantic::{DeclSite, InstantiationEdge};
use crate::convert::Positions;
use crate::instantiations::{self, Decl, Site};
use crate::state::Workspace;
use crate::uri::{path_to_uri, uri_to_path};
@@ -69,41 +70,49 @@ pub fn incoming(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyIn
/// Who instantiates each of `names`, answered one list per name in the order
/// asked.
///
/// Every in-scope file is walked, because the workspace index records what a
/// file *declares* and not what it instantiates — there is no edge table to
/// consult. A file whose text contains none of the names is skipped before it
/// is parsed, which is what keeps the walk affordable: an instantiation of
/// `fifo` has to write `fifo`.
/// **A lookup in the workspace index's instantiation-edge table** since
/// 2026-08-27, where it used to be a re-read and re-parse of every in-scope
/// file. The census is unchanged — the table is built by the same
/// [`instantiations::sites`] walk this function used to run, at index time
/// (`docs/features/incremental-index/README.md`) — and so is the answer's
/// shape and order. What changed is the cost: only the files that really do
/// instantiate one of the names are read, to turn the recorded byte spans into
/// the protocol's line/character ranges.
///
/// The **batch** is the primitive rather than the single name because
/// [`Workspace::sources`] re-reads every in-scope file: one question per name
/// would re-read the whole workspace once per name, and `lens.rs` asks about
/// every module declared in a buffer at once. A file is parsed once for the
/// whole batch.
/// The **batch** stays the primitive: `lens.rs` asks about every module
/// declared in a buffer at once, and one file that instantiates three of them
/// is read once for the batch rather than once per name.
///
/// An empty name is answered with nothing rather than searched for: nothing
/// this server hands out is nameless, and the prefilter matches every file for
/// one, which would parse the whole workspace to find nothing.
/// An empty name is answered with nothing rather than looked up: nothing this
/// server hands out is nameless, and a nameless question has no answer.
pub fn callers_of_each(ws: &Workspace, names: &[&str]) -> Vec<Vec<CallHierarchyIncomingCall>> {
let index = ws.index();
let mut answers: Vec<Vec<CallHierarchyIncomingCall>> =
names.iter().map(|_| Vec::new()).collect();
for (path, text) in ws.sources() {
let wanted: Vec<usize> = names
.iter()
.enumerate()
.filter(|(_, name)| !name.is_empty() && text.contains(**name))
.map(|(index, _)| index)
.collect();
if wanted.is_empty() {
continue;
}
let Some(uri) = path_to_uri(&path) else { continue };
let (tree, _) = parse_source_tolerant(&text);
let sites = instantiations::sites(&tree.items);
// Every file holding an edge for any of the names, once, in path order.
let mut files: Vec<vlog_semantic::FileId> = names
.iter()
.filter(|name| !name.is_empty())
.flat_map(|name| index.instantiations_of(name).iter().map(|edge| edge.file))
.collect();
files.sort();
files.dedup();
for file in files {
let Some(path) = index.path(file) else { continue };
let Some(uri) = path_to_uri(path) else { continue };
// The spans were recorded against the text the index was built from;
// this is the text now. The two differ only for a buffer edited since
// the last rebuild, which is the same staleness `item_in_file` has
// always carried.
let Some(text) = ws.text_of(path) else { continue };
let line_index = LineIndex::new(&text);
let positions = Positions::new(&text, &line_index);
for index in wanted {
answers[index].extend(callers_in(&uri, &positions, &sites, names[index]));
for (at, name) in names.iter().enumerate() {
if name.is_empty() {
continue;
}
let edges = index.instantiations_of(name).iter().filter(|edge| edge.file == file);
answers[at].extend(callers_in(&uri, &positions, edges));
}
}
for answer in &mut answers {
@@ -152,31 +161,29 @@ pub fn outgoing(ws: &Workspace, item: &CallHierarchyItem) -> Vec<CallHierarchyOu
.collect()
}
/// Every module in one already-parsed file that instantiates `name`, with its
/// sites.
/// One file's edges for one module, as incoming calls: one call per
/// instantiating module, with every site inside it.
///
/// Sites are grouped by the declaration they sit in rather than by adjacency,
/// because a module written inside another can put its own sites between two
/// of the outer module's.
fn callers_in<'a>(
uri: &Uri,
positions: &Positions,
sites: &[Site<'a>],
name: &str,
edges: impl Iterator<Item = &'a InstantiationEdge>,
) -> Vec<CallHierarchyIncomingCall> {
let mut callers: Vec<(Decl<'a>, Vec<TextRange>)> = Vec::new();
for site in sites {
if site.inst.module != name {
continue;
}
// An instantiation at file scope has no calling module to report.
let Some(owner) = site.owner else { continue };
match callers.iter_mut().find(|(decl, _)| decl.span == owner.span) {
Some((_, spans)) => spans.push(site.inst.module_span),
None => callers.push((owner, vec![site.inst.module_span])),
let mut callers: Vec<(&DeclSite, Vec<TextRange>)> = Vec::new();
for edge in edges {
match callers.iter_mut().find(|(owner, _)| owner.span == edge.owner.span) {
Some((_, spans)) => spans.push(edge.site_span),
None => callers.push((&edge.owner, vec![edge.site_span])),
}
}
callers
.into_iter()
.filter_map(|(decl, spans)| {
.filter_map(|(owner, spans)| {
Some(CallHierarchyIncomingCall {
from: item(uri.clone(), positions, decl)?,
from: item_of(uri.clone(), positions, &owner.name, owner.name_span, owner.span)?,
from_ranges: spans.into_iter().map(|span| positions.range(span)).collect(),
})
})
@@ -186,20 +193,28 @@ fn callers_in<'a>(
/// The hierarchy item for one module declaration, positioned against the text
/// it was parsed from.
fn item(uri: Uri, positions: &Positions, decl: Decl) -> Option<CallHierarchyItem> {
let name_span = decl.module.name_span;
item_of(uri, positions, &decl.module.name, decl.module.name_span, decl.span)
}
/// [`item`] from the parts, for a caller reading them out of the index's edge
/// table rather than off a parse tree.
fn item_of(
uri: Uri,
positions: &Positions,
name: &str,
name_span: TextRange,
span: TextRange,
) -> Option<CallHierarchyItem> {
if name_span.is_empty() {
return None;
}
// The protocol requires `selectionRange` inside `range`; a declaration the
// parser could not close is the case where that may not hold, and there
// the name alone is the honest extent.
let full = if decl.span.start <= name_span.start && name_span.end <= decl.span.end {
decl.span
} else {
name_span
};
let full =
if span.start <= name_span.start && name_span.end <= span.end { span } else { name_span };
Some(CallHierarchyItem {
name: decl.module.name.clone(),
name: name.to_string(),
kind: SymbolKind::MODULE,
tags: None,
detail: None,
@@ -215,7 +230,7 @@ fn declarations_of(ws: &Workspace, name: &str) -> Vec<CallHierarchyItem> {
ws.index()
.units(name)
.iter()
.filter(|def| def.kind == SemanticKind::Module)
.filter(|def| def.kind.is_instantiable())
.filter_map(|def| {
let path = ws.index().path(def.file)?;
item_in_file(ws, path, name, Some(def.name_span))
@@ -335,7 +350,7 @@ mod tests {
}
}
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let (path, text) = first.expect("at least one file");
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), text.to_string());
@@ -391,6 +406,19 @@ endmodule
assert_eq!(items[0].range.end.line, 1, "through `endmodule`");
}
/// An interface is instantiated exactly as a module is, so the call
/// hierarchy still finds its declaration from an instantiation site
/// (`docs/features/interface-semantics/README.md`).
#[test]
fn the_cursor_on_an_interface_instantiation_prepares_the_interface() {
const IFACE: &str = "interface bus_if;\nendinterface\n";
const USER: &str = "module top;\n bus_if u_bus ();\nendmodule\n";
let (_tree, ws, uri) = workspace("ifaceprepare", &[("top.sv", USER), ("bus_if.sv", IFACE)]);
let items = prepare(&ws, &uri, at(USER, "bus_if")).expect("the interface");
assert_eq!(items.len(), 1);
assert_eq!(shape(&items[0]), ("bus_if".to_string(), "bus_if.sv".to_string(), 0));
}
#[test]
fn the_cursor_on_an_instantiation_prepares_the_module_it_names() {
let (_tree, ws, uri) = three("inst");
@@ -527,7 +555,7 @@ endmodule
tree.write("files.f", "sub.sv\n");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let sub_uri = path_to_uri(&tree.path.join("sub.sv")).expect("uri");
ws.set_document(sub_uri.clone(), SUB.to_string());
@@ -536,9 +564,15 @@ endmodule
}
#[test]
fn an_unsaved_instantiation_is_a_caller_before_it_is_saved() {
// The sources a walk reads are the open buffers overlaid on disk, so a
// just-typed instantiation counts.
fn an_edited_buffers_instantiation_counts_from_the_moment_the_index_sees_it() {
// Superseded this round (incremental-index, 2026-08-27):
// `an_unsaved_instantiation_is_a_caller_before_it_is_saved` pinned the
// census reading `Workspace::sources()` on every request, so a
// keystroke in *another* buffer moved the count before anything
// rebuilt. The census is the index's edge table now, and an index is
// only ever as of its last build or update — which does fold every
// open buffer in, so a save (or any other rescan trigger) makes the
// edit count. The rule the test pins is the new one, from both sides.
let (tree, mut ws, uri) = three("unsaved");
let root = prepare(&ws, &uri, at(TOP, "sub u_a")).expect("sub")[0].clone();
assert_eq!(incoming(&ws, &root).len(), 2, "premise");
@@ -546,7 +580,14 @@ endmodule
let fresh = tree.path.join("other.sv");
let other_uri = path_to_uri(&fresh).expect("uri");
ws.set_document(other_uri, "module other;\nendmodule\n".to_string());
assert_eq!(incoming(&ws, &root).len(), 1, "the buffer removed its instantiation");
assert_eq!(
incoming(&ws, &root).len(),
2,
"the buffer alone does not move the census — the index has not seen it"
);
// What a save does, and what the incremental path does with it.
assert!(ws.update_one(&fresh), "the file is in scope, so one file is enough");
assert_eq!(incoming(&ws, &root).len(), 1, "the edit removed its instantiation");
}
// ------------------------------------------------------------------
@@ -935,17 +976,20 @@ endmodule
#[test]
#[ignore]
fn qa_perf_worst_case_common_word_module_name() {
// A single-letter module name is a substring of nearly every file's
// text, so the prefilter admits nearly everything — the worst case
// the prefilter can face. Measures whether that worst case is still
// sane, not a specific number.
// A single-letter module name used to be the worst case there was: it
// is a substring of nearly every file, so the prefilter over
// `Workspace::sources()` admitted nearly everything. There is no
// prefilter and no walk since 2026-08-27 — the census is a lookup in
// the index's edge table, and a name nothing instantiates is an empty
// slice — so this probe is kept for what it now measures: that the
// shape which used to be the worst case is not a case at all.
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let mut ws = Workspace::default();
ws.open_roots(vec![corpus]);
ws.open_whole_workspace(vec![corpus]);
let item = CallHierarchyItem {
name: "d".to_string(),
kind: SymbolKind::MODULE,
@@ -993,7 +1037,7 @@ endmodule
return;
};
let mut ws = Workspace::default();
ws.open_roots(vec![corpus]);
ws.open_whole_workspace(vec![corpus]);
let uri = path_to_uri(&declaring).expect("uri");
ws.set_document(uri.clone(), text.clone());
let root = prepare(&ws, &uri, at(&text, "module prim_flop_2sync") + 7)
File diff suppressed because it is too large. Load diff
+190 -29
View File
@@ -84,16 +84,29 @@ fn include_on_line(line: &str, base: u32) -> Option<Include> {
/// Where `` `include``s are looked for, and which file includes which.
///
/// Rebuilt whole on every index rebuild, from the same source list: includes
/// are a handful of lines per file, so there is nothing here worth updating
/// incrementally.
/// Rebuilt whole on every index rebuild, from the same source list — and
/// patched one file at a time when only one file's text moved
/// ([`IncludeGraph::update_file`]).
#[derive(Debug, Default, Clone)]
pub struct IncludeGraph {
/// The `+incdir+` directories of the configured filelist, in filelist
/// order. Empty when no filelist governs the workspace.
incdirs: Vec<PathBuf>,
/// Including file → the files it resolves to, in source order.
/// Including file → the files it resolves to, in source order, spelled the
/// way the index spells them. Derived from `raw` by [`IncludeGraph::respell`]
/// and never written to directly.
edges: HashMap<PathBuf, Vec<PathBuf>>,
/// The same edges as the *filesystem* answered them: normalized, but
/// before [`IncludeGraph::as_the_index_spells_it`] re-spells them against
/// the in-scope file list.
///
/// Kept because which file an `` `include`` lands on is a question for the
/// disk and which *spelling* that file has is a question for the scope, and
/// only the second one moves when the scope grows. Holding the first means
/// a scope widen can re-spell every edge it already had without re-reading
/// a single file — which is what makes an incrementally widened graph
/// byte-identical to a rebuilt one (`docs/features/index-scope/README.md`).
raw: HashMap<PathBuf, Vec<PathBuf>>,
/// Every in-scope file, exactly as the index spells it.
known: HashSet<PathBuf>,
/// Lower-cased spelling → the one in-scope file that has it, or `None`
@@ -104,34 +117,117 @@ pub struct IncludeGraph {
impl IncludeGraph {
/// Scan every in-scope file for its `` `include``s and resolve them.
pub fn build(sources: &[(PathBuf, String)], incdirs: Vec<PathBuf>) -> IncludeGraph {
let mut graph = IncludeGraph {
incdirs,
edges: HashMap::new(),
known: sources.iter().map(|(path, _)| path.clone()).collect(),
folded: HashMap::new(),
let mut graph = IncludeGraph { incdirs, ..IncludeGraph::default() };
// Learned before the edges: `resolve` consults both tables, and an edge
// resolved against a half-filled one would be keyed inconsistently.
let paths: Vec<PathBuf> = sources.iter().map(|(path, _)| path.clone()).collect();
graph.relearn(&paths);
for (path, text) in sources {
graph.rescan_edges(path, text);
}
graph.respell();
graph
}
/// Re-scan one file's `` `include``s, the rest of the graph left standing.
///
/// `known` is the index's file list as it stands *after* the update, which
/// is what the known-file and folded-spelling tables are: cheap to rebuild
/// from a list already in memory, and wrong to leave stale when a file has
/// come or gone.
///
/// One honest limit, and the reason the incremental path in `state.rs`
/// takes it only for a file that already existed: an edge of a *different*
/// file is not re-**resolved** against the disk. So a file appearing or
/// vanishing on disk does not change whether some other file's
/// `` `include "x.svh"`` finds anything until the next whole rebuild. Every
/// held edge *is* re-spelled against the new file list, because that half
/// costs no filesystem call — see [`IncludeGraph::respell`]. For the case
/// this is used in — one file's text changed, the file set did not — there
/// is nothing stale at all.
pub fn update_file(&mut self, path: &Path, text: &str, known: &[PathBuf]) {
self.relearn(known);
self.rescan_edges(path, text);
self.respell();
}
/// [`IncludeGraph::update_file`] for a batch of files, with the `+incdir+`s
/// the scope resolves to right now — the form a scan publishing what it
/// has indexed so far uses.
///
/// `known` is the scan's whole work list rather than the files it has
/// reached, so the known-file and folded-spelling tables are complete from
/// the first publish: which files *exist* is settled the moment the scope
/// is resolved, and only the edges are discovered file by file. One
/// `relearn` for the batch, for the same reason
/// [`Candidates::absorb`](crate::candidates::Candidates::absorb) re-derives
/// its index tables once.
pub fn absorb(&mut self, incdirs: &[PathBuf], known: &[PathBuf], batch: &[(&Path, &str)]) {
self.incdirs = incdirs.to_vec();
self.relearn(known);
for (path, text) in batch {
self.rescan_edges(path, text);
}
self.respell();
}
/// Drop one file from the graph: its own edges, and its place among the
/// known files.
pub fn remove_file(&mut self, path: &Path, known: &[PathBuf]) {
self.relearn(known);
self.raw.remove(path);
self.respell();
}
/// Read one file's `` `include``s off its text and hold where the disk says
/// each one lands. A file that includes nothing holds no entry at all,
/// which is what keeps `raw` a set of edges rather than a set of files.
fn rescan_edges(&mut self, path: &Path, text: &str) {
let targets: Vec<PathBuf> =
scan(text).iter().filter_map(|include| self.found(Some(path), include)).collect();
match targets.is_empty() {
true => self.raw.remove(path),
false => self.raw.insert(path.to_path_buf(), targets),
};
// Built before the edges: `resolve` consults it, and an edge resolved
// against a half-filled table would be keyed inconsistently.
for (path, _) in sources {
}
/// Re-derive every edge's spelling from the file list learned last.
///
/// The cheap half of resolving an include: which file it lands on was
/// settled by the filesystem when the edge was read, and only how the index
/// spells that file depends on which files are in scope. So a scope that
/// grows re-spells what it already had here, in memory, rather than
/// re-reading and re-scanning every file it already knew about.
fn respell(&mut self) {
// Taken out and put back so the re-spelling may read the tables on
// `self` while it walks the edges — the same map, never a copy of it.
let raw = std::mem::take(&mut self.raw);
self.edges = raw
.iter()
.map(|(path, targets)| {
let spelled =
targets.iter().map(|to| self.as_the_index_spells_it(to.clone())).collect();
(path.clone(), spelled)
})
.collect();
self.raw = raw;
}
/// Re-derive the known-file set and the folded-spelling table from the
/// index's file list. The same two loops [`IncludeGraph::build`] runs, over
/// paths rather than over `(path, text)` pairs.
fn relearn(&mut self, known: &[PathBuf]) {
self.known = known.iter().cloned().collect();
self.folded.clear();
for path in known {
let Some(key) = path.to_str().map(str::to_lowercase) else { continue };
graph
.folded
self.folded
.entry(key)
// A second file with the same folded spelling makes the
// spelling ambiguous, and an ambiguous one decides nothing.
.and_modify(|found| *found = None)
.or_insert_with(|| Some(path.clone()));
}
for (path, text) in sources {
let targets: Vec<PathBuf> = scan(text)
.iter()
.filter_map(|include| graph.resolve(Some(path), include))
.collect();
if !targets.is_empty() {
graph.edges.insert(path.clone(), targets);
}
}
graph
}
/// The `+incdir+` directories an include is looked for in, in filelist
@@ -164,10 +260,29 @@ impl IncludeGraph {
from: Option<&Path>,
include: &Include,
exists: &dyn Fn(&Path) -> bool,
) -> Option<PathBuf> {
self.found_as_if(from, include, exists).map(|found| self.as_the_index_spells_it(found))
}
/// [`IncludeGraph::resolve`] as far as the *filesystem* answers it: the
/// search rungs and `normalize`, without the index's own spelling.
///
/// The half of an edge that only a disk change can move, which is what the
/// graph holds in `raw`.
fn found(&self, from: Option<&Path>, include: &Include) -> Option<PathBuf> {
self.found_as_if(from, include, &|path| path.is_file())
}
/// [`IncludeGraph::found`] against a filesystem `exists` describes.
fn found_as_if(
&self,
from: Option<&Path>,
include: &Include,
exists: &dyn Fn(&Path) -> bool,
) -> Option<PathBuf> {
let target = Path::new(&include.target);
if target.is_absolute() {
return exists(target).then(|| self.as_the_index_spells_it(normalize(target)));
return exists(target).then(|| normalize(target));
}
let own = match include.system {
true => None,
@@ -177,7 +292,7 @@ impl IncludeGraph {
.chain(self.incdirs.iter().map(PathBuf::as_path))
.map(|dir| dir.join(target))
.find(|candidate| exists(candidate))
.map(|found| self.as_the_index_spells_it(normalize(&found)))
.map(|found| normalize(&found))
}
/// A resolved path, re-spelled the way the index spells that file.
@@ -210,6 +325,18 @@ impl IncludeGraph {
}
}
/// Every file that writes at least one `` `include`` the disk answered —
/// the keys of the edge table, in no particular order.
///
/// The complement is the interesting half: a file that is *not* here
/// either includes nothing or includes only what nothing resolves, so
/// [`IncludeGraph::resolve`] answers `None` for every include it writes.
/// `file_ops.rs` reads that as "this file cannot produce an edit or a
/// warning" and never reads it (`Workspace::include_sources`).
pub fn includers(&self) -> impl Iterator<Item = &PathBuf> {
self.raw.keys()
}
/// Every file reachable from `seeds` through include edges, the seeds
/// themselves included.
///
@@ -229,6 +356,33 @@ impl IncludeGraph {
}
seen
}
/// Everything this graph answers with, as one deterministic string.
///
/// Test-only, and the witness for "a graph widened one folder at a time is
/// the graph a whole rebuild would have produced": the two hash maps are
/// rendered in sorted order, so the comparison is of the contents and never
/// of the iteration order.
#[cfg(test)]
pub fn fingerprint(&self) -> String {
let mut out = format!("incdirs {:?}\n", self.incdirs);
let mut known: Vec<&PathBuf> = self.known.iter().collect();
known.sort();
out.push_str(&format!("known {known:?}\n"));
let mut folded: Vec<(&String, &Option<PathBuf>)> = self.folded.iter().collect();
folded.sort();
out.push_str(&format!("folded {folded:?}\n"));
let mut edges: Vec<(&PathBuf, &Vec<PathBuf>)> = self.edges.iter().collect();
edges.sort();
out.push_str(&format!("edges {edges:?}\n"));
// The unspelled edges too, so a widen that left a stale entry behind
// fails here rather than waiting for the scope to grow far enough for
// the spelling to notice.
let mut raw: Vec<(&PathBuf, &Vec<PathBuf>)> = self.raw.iter().collect();
raw.sort();
out.push_str(&format!("raw {raw:?}\n"));
out
}
}
/// Fold `.`/`..` away so one file has one spelling, and so a resolved include
@@ -298,7 +452,14 @@ pub fn document_links(ws: &Workspace, uri: &Uri) -> Vec<DocumentLink> {
/// The same computation the links use, so F12 and ctrl-click can never
/// disagree about where a line goes.
pub fn definition(ws: &Workspace, doc: &Document, offset: u32) -> Option<Location> {
let (_, path) = resolved(ws, doc).into_iter().find(|(inc, _)| inc.span.contains(offset))?;
// Definition is a cursor request, so inspect only its line. `documentLink`
// still scans the whole file because it must return every include.
let (line, _) = doc.line_index.line_col(offset);
let line = doc.line_index.line_range(line)?;
let text = doc.text.get(line.as_range())?;
let include =
include_on_line(text, line.start).filter(|include| include.span.contains(offset))?;
let path = ws.includes().resolve(doc.path.as_deref(), &include)?;
Some(Location { uri: path_to_uri(&path)?, range: Range::default() })
}
@@ -541,7 +702,7 @@ mod tests {
filelist: Some(tree.path.join("files.f").display().to_string()),
..Default::default()
});
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let path = tree.path.join(rel);
let uri = path_to_uri(&path).expect("uri");
let text = fs::read_to_string(&path).expect("read");
@@ -735,7 +896,7 @@ mod qa_scope_probe {
filelist: Some(dir.join("files.f").display().to_string()),
..Default::default()
});
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let uri = path_to_uri(&top).expect("uri");
ws.set_document(uri.clone(), fs::read_to_string(&top).expect("read"));
File diff suppressed because it is too large. Load diff
+6 -6
View File
@@ -25,9 +25,9 @@ use lsp_types::{InlayHint, InlayHintKind, InlayHintLabel, Range, Uri};
use vlog_parser::ast::{Connections, Expr, Instance, Instantiation};
use vlog_parser::TextRange;
use vlog_refactor::InstantiationPlan;
use vlog_semantic::instantiations;
use crate::convert::Positions;
use crate::instantiations;
use crate::state::Workspace;
/// The ghost labels for one range of a buffer.
@@ -280,7 +280,7 @@ endmodule
}
let path = tree.write("top.sv", top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
inlay_hints(&ws, &uri, range)
@@ -321,7 +321,7 @@ endmodule
let top = "module top;\n sub u1 (clk);\nendmodule\n";
let path = tree.write("top.sv", top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
let hints = inlay_hints(&ws, &uri, everything());
@@ -708,7 +708,7 @@ endmodule
let top = "module top;\n sub u1 (clk, rst_n, data);\nendmodule\n";
let top_path = tree.write("top.sv", top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let sub_uri = path_to_uri(&sub_path).expect("uri");
let top_uri = path_to_uri(&top_path).expect("uri");
ws.set_document(top_uri.clone(), top.to_string());
@@ -758,7 +758,7 @@ endmodule
top.push_str("endmodule\n");
let path = tree.write("top.sv", &top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.clone());
let screen = Range {
@@ -793,7 +793,7 @@ endmodule
top.push_str("endmodule\n");
let path = tree.write("top.sv", &top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.clone());
let _ = inlay_hints(&ws, &uri, everything());
+785 -22
View File
@@ -1,11 +1,20 @@
//! `textDocument/inlineCompletion` — the ghost text that finishes a block as
//! you open it.
//! you open it, and the instantiation that follows a module's name.
//!
//! Type `if (` and grey `) begin … end` follows the cursor; type `begin` at the
//! end of a line and its `end` does. Accepting one is a snippet insertion, so
//! the tabstops land the cursor inside the parens first and on the indented
//! body line second.
//!
//! Type the whole name of a module the workspace declares **and a space**,
//! somewhere an instantiation may be written, and the rest of the
//! instantiation follows the same way: every parameter, every port, each a
//! tabstop. That is the second level of the two the completion popup's module
//! tier is the first of — the popup offers *names*, cheaply, and exactly one
//! name is ever planned. The space is what says the name is finished: `aes`
//! alone may still be growing into `aes_dft` (owner ruling, 2026-08-30). See
//! `docs/features/inline-instantiation/README.md`.
//!
//! Three things here are deliberate. The **triggers are data** — a keyword, the
//! punctuation that must follow it, the dialect it belongs to, the check that
//! says the construct is still unfinished, and one body per item in
@@ -21,7 +30,9 @@
use lsp_types::{Position, Range, Uri};
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::TextRange;
use vlog_refactor::{Layout, Site};
use crate::completion;
use crate::pairs;
use crate::state::{Document, Workspace};
use crate::templates::{self, Dialect};
@@ -227,9 +238,6 @@ pub struct InlineItems {
/// editor treats both the same, and `null` is the cheaper answer to a request
/// that arrives on every keystroke.
pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Option<InlineItems> {
if !ws.client_settings().inline_templates.unwrap_or(true) {
return None;
}
let doc = ws.document(uri)?;
// No token stream, no answer — the same trade `completion.rs` makes. A
// half-typed string or block comment is what breaks the lexer, and those
@@ -241,11 +249,59 @@ pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Opti
if !rest_of_line_is_blank(&doc.text, offset) {
return None;
}
let (trigger, opened) = triggered(doc, offset)?;
let at = Range { start: position, end: position };
// Two ghosts, told apart by the shape of the text just before the cursor.
// An identifier followed by exactly one space may be a module name the
// user has committed to; a token ending *at* the cursor may open a
// construct. No keystroke reaches both — a space is not a token, so
// nothing ends at the cursor when one was just typed — and each carries
// its own setting, so a user who turned one off still has the other.
if let Some(name) = name_then_space(doc, offset) {
return instantiation(ws, doc, name, at);
}
let last = last_token(doc, offset)?;
match doc.tokens.get(last)?.kind {
// A name with nothing after it is not an offer (owner ruling,
// 2026-08-30): `aes` may still be growing into `aes_dft`, and the
// space is the user saying that it is not. No trigger's own last token
// is an `Ident` either, so nothing is lost by stopping here.
TokenKind::Ident => None,
_ => template(ws, doc, last, at),
}
}
/// The identifier the user has just finished and armed with a space: the token
/// ending exactly at `offset - 1`, when that byte is a space and the byte
/// before it is not.
///
/// **One space, and the one just typed.** Two of them is not "you have just
/// finished the name" — it is a cursor parked in whitespace — and the crisp
/// rule is what keeps the ghost from appearing at every idle position on a
/// blank-ish line. A tab is not a space either: only the character a user types
/// after a module name arms this.
fn name_then_space(doc: &Document, offset: u32) -> Option<usize> {
let space = offset.checked_sub(1)?;
let bytes = doc.text.as_bytes();
if bytes.get(space as usize) != Some(&b' ') {
return None;
}
if space > 0 && bytes.get(space as usize - 1) == Some(&b' ') {
return None;
}
let index = last_token(doc, space)?;
(doc.tokens.get(index)?.kind == TokenKind::Ident).then_some(index)
}
/// The block-opening ghost: the trigger table, its gate, and one item per
/// body.
fn template(ws: &Workspace, doc: &Document, last: usize, at: Range) -> Option<InlineItems> {
if !ws.client_settings().inline_templates.unwrap_or(true) {
return None;
}
let (trigger, opened) = triggered(doc, last)?;
if !unfinished(doc, trigger, opened) {
return None;
}
let at = Range { start: position, end: position };
Some(InlineItems {
items: trigger
.bodies
@@ -258,6 +314,120 @@ pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Opti
})
}
/// The instantiation ghost: everything but the name of the module the user has
/// just finished spelling, and the space they armed it with.
///
/// The order of the questions is the feature. A keystroke that is not an exact
/// module name — which is nearly every keystroke — costs one binary search in
/// a table (`Candidates::has_module`) and stops there: no scope chain is built,
/// no file is opened, nothing is parsed. Only an exact match pays for the
/// position gate, and only a gated exact match pays for a plan.
///
/// The gate is asked at the **name's own start**, not at the cursor: the space
/// is the arming keystroke, and the instantiation would still be written where
/// the name begins.
fn instantiation(ws: &Workspace, doc: &Document, last: usize, at: Range) -> Option<InlineItems> {
if !ws.client_settings().inline_instantiation.unwrap_or(true) {
return None;
}
let name = doc.tokens.get(last)?;
if !ws.candidates().has_module(&name.text) {
return None;
}
if !completion::at_instantiation_site(doc, name.span.start) {
return None;
}
let value = instantiation_ghost(ws, doc, &name.text, name.span.start).ok()?;
Some(InlineItems {
items: vec![InlineItem { insert_text: SnippetValue { kind: "snippet", value }, range: at }],
})
}
/// Why a module the workspace really declares has no ghost behind it.
///
/// **The residue, enumerated.** Since round 2 the ghost no longer declines
/// because a name is declared twice — `completion::nearest_definition` chooses
/// — so what is left is this list and nothing else, and a sweep over a whole
/// workspace can bucket its misses by reason instead of shrugging at them.
/// `the_only_residue_over_a_workspace_is_the_escaped_identifier` is that sweep
/// in miniature.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NoGhost {
/// The index names no module by this name whose declaring file it can
/// place — the caller's `has_module` probe and the index disagreeing,
/// which only a scope change mid-request can produce.
Undeclared,
/// The declaring file could not be read.
Unreadable,
/// Neither the header slice nor the whole file planned: the definition is
/// written in syntax this parser does not read as a module header.
Unplannable,
/// The plan carries an **escaped identifier**, which may legally contain
/// `$`, `}` and `\` — the snippet grammar's own punctuation — written by
/// the layout where no per-hole escaping can reach it. The popup's answer
/// to that was a plain-text item; an inline completion has no plain-text
/// spelling to fall back to (there is no `snippetSupport` to negotiate on
/// this request), so the honest answer is no ghost at all.
EscapedIdentifier,
/// The rendered skeleton did not begin with the module's name and exactly
/// one space, so there is nothing to cut off its front. Unreachable with
/// today's layout and pinned as such
/// (`the_rendered_skeleton_really_does_put_one_space_after_the_name`); it
/// is here so a change to `vlog_refactor`'s spelling fails loudly in a
/// sweep rather than silently truncating a ghost.
UnexpectedLayout,
}
/// The instantiation of `module` as it appears behind the cursor: the
/// skeleton `completion.rs` plans, laid out **relatively**, with the name the
/// user has already typed *and the space after it* cut off the front.
fn instantiation_ghost(
ws: &Workspace,
doc: &Document,
module: &str,
at: u32,
) -> Result<String, NoGhost> {
let path = completion::nearest_definition(ws.index(), module, doc.path.as_deref())
.ok_or(NoGhost::Undeclared)?;
let site = Site { semantics: &doc.semantics, offset: at };
// A closed file goes through the view cache, so holding the cursor on a
// name — every keystroke of which re-asks this question — reads the disk
// once. An open one has no view by design: its buffer is the authority.
let plan = match ws.file_view(path) {
Some(view) => completion::plan_for(ws.index(), module, &view.text, site),
None => {
let text = ws.text_of(path).ok_or(NoGhost::Unreadable)?;
completion::plan_for(ws.index(), module, &text, site)
}
}
.map_err(|_| NoGhost::Unplannable)?;
if plan.has_escaped_identifier() {
return Err(NoGhost::EscapedIdentifier);
}
let skeleton = plan.render_with(&relative(), &mut completion::snippet_hole);
// The user typed the name and the space; the ghost is what follows both.
// The same "cut off what is already there" rule every trigger above
// follows — the layout writes exactly one space between the module's name
// and whatever comes next, whether that is a `#(` or an instance name.
skeleton
.strip_prefix(module)
.and_then(|rest| rest.strip_prefix(' '))
.map(str::to_string)
.ok_or(NoGhost::UnexpectedLayout)
}
/// The layout an inline completion is written in: no base at all, one `\t` per
/// step.
///
/// The [`render`] contract, in the shape `vlog_refactor` renders a plan
/// through. A `base` here would be the site's own indentation baked in, which
/// is exactly the double-indentation bug `render`'s doc comment describes; a
/// step of anything but `\t` would be this server deciding how wide the user's
/// tab stops are, which the editor re-spells anyway.
fn relative() -> Layout {
Layout { base: String::new(), step: "\t".to_string() }
}
/// The two tokens a gate can ask about: the keyword that opens the construct,
/// and the last token the user typed — the `(` whenever the trigger has one.
#[derive(Clone, Copy)]
@@ -266,29 +436,34 @@ struct Opened {
last: TextRange,
}
/// The trigger the tokens ending at `offset` spell, and the spans its gate
/// needs.
/// The token the user has just finished typing: the last one that is not the
/// `Eof` sentinel, and only when it ends **exactly** at the cursor.
///
/// The cursor must sit *exactly* at the last token's end: that is the crisp
/// "you just typed this" rule, and it is what keeps the body's first character
/// from landing after stray spaces. It is also what makes a comment or a
/// string safe without a single check of its own — a comment is lexer trivia
/// and never a token, and `"if ("` is one `String` token whose text is not a
/// keyword.
fn triggered(doc: &Document, offset: u32) -> Option<(&'static Trigger, Opened)> {
/// That equality is the crisp "you just typed this" rule, and it is what keeps
/// a body's first character from landing after stray spaces. It is also what
/// makes a comment or a string safe without a single check of its own — a
/// comment is lexer trivia and never a token, and `"if ("` is one `String`
/// token whose text is not a keyword.
fn last_token(doc: &Document, offset: u32) -> Option<usize> {
// `Eof` is a zero-width sentinel `tokenize` appends at `text.len()`, so
// when the buffer's very last byte is the trigger's own last character —
// no trailing newline, nothing typed after it yet — it shares the
// trigger token's `span.end`. Skipping it here is what lets a trigger at
// the true end of the file still fire (QA find, 2026-08-25).
let index = doc
.tokens
.iter()
.rposition(|token| token.kind != TokenKind::Eof && token.span.end <= offset)?;
//
// Token ends rise across the vector, so the tokens ending at or before
// `offset` are a prefix of it: no token outside that prefix could have
// satisfied the reverse sweep this replaced, and inside it the sweep's
// remaining condition is the `Eof` test alone.
let reached = doc.tokens.partition_point(|token| token.span.end <= offset);
let index = doc.tokens[..reached].iter().rposition(|token| token.kind != TokenKind::Eof)?;
(doc.tokens.get(index)?.span.end == offset).then_some(index)
}
/// The trigger the token at `index` and its neighbours spell, and the spans
/// its gate needs.
fn triggered(doc: &Document, index: usize) -> Option<(&'static Trigger, Opened)> {
let last = doc.tokens.get(index)?;
if last.span.end != offset {
return None;
}
let dialect = templates::dialect(doc.path.as_deref());
for trigger in TRIGGERS {
if matches!(trigger.dialect, Some(only) if only != dialect) {
@@ -412,6 +587,29 @@ mod tests {
(ws, uri, position)
}
/// [`triggered`] used to sweep the token vector backwards from its end for
/// the last non-`Eof` token ending at or before the cursor. It now bounds
/// that sweep with a binary search; the token it lands on must be the same
/// one at every byte.
#[test]
fn the_last_token_before_the_cursor_is_the_one_the_reverse_sweep_found() {
let text = crate::state::mixed_buffer(20);
let uri = path_to_uri(&PathBuf::from("/rtl/top.sv")).expect("uri");
let mut ws = Workspace::default();
ws.set_document(uri.clone(), text.clone());
let doc = ws.document(&uri).expect("open");
for offset in 0..=text.len() as u32 {
let swept = doc
.tokens
.iter()
.rposition(|token| token.kind != TokenKind::Eof && token.span.end <= offset);
let reached = doc.tokens.partition_point(|token| token.span.end <= offset);
let searched =
doc.tokens[..reached].iter().rposition(|token| token.kind != TokenKind::Eof);
assert_eq!(swept, searched, "at offset {offset}");
}
}
/// The same, in a SystemVerilog buffer.
fn asking(text: &str, needle: &str) -> (Workspace, Uri, Position) {
asking_in("/rtl/top.sv", text, needle)
@@ -1452,4 +1650,569 @@ endmodule
let items = inline_completions(&ws, &uri, position).expect("a ghost");
assert_eq!(items.items[0].range.start, Position { line: 2, character: 19 });
}
// ------------------------------------------------------------------
// the instantiation ghost (2026-08-30)
// ------------------------------------------------------------------
/// A scratch workspace root, removed on drop. The instantiation ghost is
/// the one path here that reads the index, so its tests need real files.
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 _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("temp dir");
Tree { path }
}
fn write(&self, rel: &str, text: &str) -> PathBuf {
let path = self.path.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("temp dir");
}
std::fs::write(&path, text).expect("write");
path
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
/// The module every ghost below instantiates: parameters *and* ports, one
/// of which (`clk`) the buffer declares and so binds itself.
const SUB: &str = "\
module sub #(
parameter int WIDTH = 8
) (
input logic clk,
input logic [WIDTH-1:0] data,
output logic ready
);
endmodule
";
/// The ghost `SUB`'s header produces, with the name the user typed *and
/// the space that armed it* already cut off the front. Written out once,
/// because half the tests below are about whether it appears at all rather
/// than about what it says.
const SUB_GHOST: &str = "#(\n\t.WIDTH(${1:8})\n) ${2:u_sub} (\n\t.clk(clk),\n\t\
.data(${3:data}),\n\t.ready(${4:ready})\n);";
/// A workspace holding `files` plus an open `top.sv`, with the cursor at
/// `needle`'s end.
fn workspace(
name: &str,
files: &[(&str, &str)],
top: &str,
needle: &str,
) -> (Tree, Workspace, Uri, Position) {
workspace_at(name, files, "top.sv", top, needle)
}
/// The same, with the open buffer written at `top_rel` — which is what the
/// nearest-definition rule reads, so a test about *which* copy is chosen
/// has to be able to say where the asking buffer lives.
fn workspace_at(
name: &str,
files: &[(&str, &str)],
top_rel: &str,
top: &str,
needle: &str,
) -> (Tree, Workspace, Uri, Position) {
let tree = Tree::new(name);
for (rel, text) in files {
tree.write(rel, text);
}
let path = tree.write(top_rel, top);
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(), top.to_string());
let offset = (top.find(needle).expect("needle present") + needle.len()) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
(tree, ws, uri, position)
}
/// The one ghost offered at `needle`'s end in a workspace declaring `SUB`.
///
/// `needle` names the text the cursor sits after, and every caller here
/// spells the arming space into it: since 2026-08-30 the ghost answers
/// `sub ` and never `sub`, because `sub` alone may still be growing into
/// `sub_dft`.
fn ghosted(name: &str, top: &str, needle: &str) -> Option<String> {
ghosted_among(name, &[("sub.sv", SUB)], top, needle)
}
/// The same, over a workspace spelled out by the caller.
fn ghosted_among(
name: &str,
files: &[(&str, &str)],
top: &str,
needle: &str,
) -> Option<String> {
ghosted_at(name, files, "top.sv", top, needle)
}
/// The same again, with the asking buffer's own path spelled out.
fn ghosted_at(
name: &str,
files: &[(&str, &str)],
top_rel: &str,
top: &str,
needle: &str,
) -> Option<String> {
let (_tree, ws, uri, position) = workspace_at(name, files, top_rel, top, needle);
let items = inline_completions(&ws, &uri, position)?;
assert_eq!(items.items.len(), 1, "an instantiation is one offer, not a menu");
Some(items.items[0].insert_text.value.clone())
}
#[test]
fn an_exactly_spelled_module_name_and_a_space_ghost_the_whole_instantiation() {
let top = "module top;\n logic clk;\n sub \nendmodule\n";
assert_eq!(ghosted("exact", top, " sub ").as_deref(), Some(SUB_GHOST));
}
/// The owner's ruling of 2026-08-30, both halves in one place: the space is
/// what arms the ghost, and without it there is nothing — *even though*
/// `sub` is a module the workspace really declares and the cursor really is
/// at a legal site. `aes` is not a commitment while `aes_dft` may still be
/// coming; `aes ` is.
#[test]
fn the_name_alone_offers_nothing_and_the_name_and_a_space_offer_everything() {
let top = "module top;\n logic clk;\n sub \nendmodule\n";
assert_eq!(ghosted("armed_no", top, " sub"), None, "the name alone is not a commitment");
assert_eq!(ghosted("armed_yes", top, " sub ").as_deref(), Some(SUB_GHOST));
}
/// One space, and the one just typed. Two of them is a cursor parked in
/// whitespace rather than a name just finished, and a tab is not the
/// character this rule is about at all.
#[test]
fn only_a_single_space_arms_the_ghost() {
let top = "module top;\n logic clk;\n sub \nendmodule\n";
assert_eq!(ghosted("twospaces", top, " sub "), None, "two spaces is not `just typed`");
let top = "module top;\n logic clk;\n sub\t\nendmodule\n";
assert_eq!(ghosted("tab", top, " sub\t"), None, "a tab does not arm it");
// …and the first of the two spaces still does, which is the same rule
// read from the other side: the byte before the cursor is a space and
// the byte before that is not.
let top = "module top;\n logic clk;\n sub \nendmodule\n";
assert_eq!(ghosted("firstspace", top, " sub ").as_deref(), Some(SUB_GHOST));
}
/// A name that is not a module, followed by a space, is the overwhelmingly
/// common keystroke on this path — it must cost the binary search and stop.
#[test]
fn a_space_after_a_name_that_is_not_a_module_ghosts_nothing() {
let top = "module top;\n logic clk;\n widget \nendmodule\n";
assert_eq!(ghosted("notamodule", top, " widget "), None);
}
/// The layout `vlog_refactor` renders really does put exactly one space
/// between a module's name and whatever follows it, in both shapes: a
/// parameterised header (`sub #(`) and a bare one (`bare u_bare`). The cut
/// in `instantiation_ghost` asserts this rather than assuming it — see
/// [`NoGhost::UnexpectedLayout`] — and this is what would fail first if the
/// spelling ever changed.
#[test]
fn the_rendered_skeleton_really_does_put_one_space_after_the_name() {
for (name, module, files) in [
("layout_params", "sub", &[("sub.sv", SUB)][..]),
("layout_bare", "bare", &[("bare.sv", "module bare;\nendmodule\n")][..]),
] {
let top = format!("module top;\n logic clk;\n {module} \nendmodule\n");
let ghost = ghosted_among(name, files, &top, &format!(" {module} ")).expect("a ghost");
assert!(
!ghost.starts_with(char::is_whitespace),
"{module}: the arming space is the ghost's, not the user's: {ghost:?}"
);
}
}
/// The accepted text is what the popup's skeleton used to insert, byte for
/// byte — which is the argument that level 2 gives up nothing level 1 gave
/// away. The layout the server sends is relative; the editor supplies the
/// site's own indentation and the width of a step.
#[test]
fn the_accepted_ghost_is_the_skeleton_the_popup_used_to_insert() {
let top = "module top;\n logic clk;\n sub \nendmodule\n";
let ghost = ghosted("accepted", top, " sub ").expect("a ghost");
assert_eq!(
format!("sub {}", accepted(&ghost, " ", " ")),
"\
sub #(
.WIDTH(${1:8})
) ${2:u_sub} (
.clk(clk),
.data(${3:data}),
.ready(${4:ready})
);"
);
// …and it follows the editor's tabs, not `lucisv.indent`, at any depth.
assert!(accepted(&ghost, "\t\t", "\t").contains("\n\t\t\t.clk(clk),"), "{ghost}");
}
/// What the user ends up with must parse. The typed name, the accepted
/// body, every hole filled in the way the editor preselects it, planted at
/// the item position the gate insisted on.
#[test]
fn the_accepted_ghost_parses_where_it_was_offered() {
for (name, module, files, holes) in [
("ports", "sub", &[("sub.sv", SUB)][..], 4),
("bare", "bare", &[("bare.sv", "module bare;\nendmodule\n")][..], 1),
(
"portless",
"empty",
&[("empty.sv", "module empty #(\n parameter int W = 2\n) ();\nendmodule\n")][..],
2,
),
] {
let top = format!("module top;\n logic clk;\n {module} \nendmodule\n");
let ghost = ghosted_among(name, files, &top, &format!(" {module} ")).expect("a ghost");
assert_eq!(
ghost.matches("${").count(),
holes,
"{module}: every fill-in is a tabstop: {ghost}"
);
// The name, the space that armed the ghost, and the ghost itself —
// which is exactly what the buffer holds after Tab.
let written = filled(&format!("{module} {}", accepted(&ghost, " ", " ")));
let probe = format!("module lucisv_probe;\n logic clk;\n {written}\nendmodule\n");
assert!(
vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
"the accepted text must parse:\n{probe}"
);
}
}
#[test]
fn a_module_with_no_ports_ghosts_a_sane_instantiation() {
let top = "module top;\n bare \nendmodule\n";
assert_eq!(
ghosted_among("bareports", &[("bare.sv", "module bare;\nendmodule\n")], top, " bare ")
.as_deref(),
Some("${1:u_bare} ();")
);
}
#[test]
fn a_half_typed_name_ghosts_nothing() {
// The popup is what answers here — with the *name*, which is the whole
// division of labour between the two levels.
let top = "module top;\n logic clk;\n su \nendmodule\n";
assert_eq!(ghosted("partial", top, " su "), None);
// …and one character past the name is not the name either.
let top = "module top;\n logic clk;\n subs \nendmodule\n";
assert_eq!(ghosted("past", top, " subs "), None);
}
#[test]
fn a_case_mismatched_name_ghosts_nothing() {
// The popup's substring match folds case; this one must not. `SUB` is
// not a module any Verilog tool would find.
for typed in ["SUB", "Sub", "sUb"] {
let top = format!("module top;\n logic clk;\n {typed} \nendmodule\n");
assert_eq!(ghosted("case", &top, &format!(" {typed} ")), None, "{typed}");
}
}
#[test]
fn a_name_the_workspace_does_not_declare_as_a_module_ghosts_nothing() {
let files =
&[("sub.sv", SUB), ("p.sv", "package pkg;\n localparam int W = 1;\nendpackage\n")];
for typed in ["pkg", "W", "clk", "nothing_at_all"] {
let top = format!("module top;\n logic clk;\n {typed} \nendmodule\n");
assert_eq!(
ghosted_among("nonmodule", files, &top, &format!(" {typed} ")),
None,
"{typed} is not a module"
);
}
}
#[test]
fn anything_after_the_cursor_on_the_line_ghosts_nothing() {
// The rest-of-line rule the templates already live by: a name with a
// `;` after it is code the user has finished writing.
let top = "module top;\n logic clk;\n sub u_sub ();\nendmodule\n";
assert_eq!(ghosted("after", top, " sub "), None);
}
#[test]
fn a_name_that_is_not_at_item_position_ghosts_nothing() {
// Every one of these spells `sub` exactly and none of them is a place
// an instantiation may be written. The gate is `completion.rs`'s own,
// so this is the ghost inheriting the popup's answer rather than
// inventing a second one.
for (name, top, needle) in [
("connection", "module top;\n other u (.aes(sub \nendmodule\n", ".aes(sub "),
("assign", "module top;\n wire x;\n assign x = sub \nendmodule\n", "= sub "),
("declaration", "module top;\n logic sub \nendmodule\n", "logic sub "),
(
"procedural",
"module top;\n initial begin\n sub \n end\nendmodule\n",
" sub ",
),
(
"function",
"module top;\n function int f();\n sub \n endfunction\nendmodule\n",
" sub ",
),
("file scope", "sub \nmodule top;\nendmodule\n", "sub "),
("port list", "module top (sub \n);\nendmodule\n", "top (sub "),
] {
assert_eq!(ghosted("position", top, needle), None, "{name}: {top}");
}
}
#[test]
fn a_generate_block_is_still_item_position_for_the_ghost() {
let top = "module top;\n logic clk;\n generate\n sub \n endgenerate\nendmodule\n";
assert_eq!(ghosted("gen", top, " sub ").as_deref(), Some(SUB_GHOST));
}
#[test]
fn a_module_name_in_a_comment_or_a_string_ghosts_nothing() {
// A token property, not a check of this module's own: a comment is
// lexer trivia and never a token, and a string literal is one `String`
// token whose kind is not `Ident`.
let top = "module top;\n // sub \nendmodule\n";
assert_eq!(ghosted("comment", top, "// sub "), None);
let top = "module top;\n initial $display(\"sub \nendmodule\n";
assert_eq!(ghosted("string", top, "\"sub "), None);
}
#[test]
fn a_buffer_that_does_not_lex_ghosts_nothing() {
let top = "module top;\n /* unterminated\n sub \n";
let (_tree, ws, uri, position) = workspace("nolex", &[("sub.sv", SUB)], top, " sub ");
assert!(ws.document(&uri).expect("open").tokens.is_empty(), "premise: no tokens");
assert!(inline_completions(&ws, &uri, position).is_none());
}
#[test]
fn an_exact_name_at_the_true_end_of_the_file_still_ghosts() {
// The `Eof` sentinel shares the last real token's end, so the same
// skip the templates needed (QA find, 2026-08-25) is what lets a name
// typed as the buffer's very last bytes answer.
// True EOF is now the buffer ending with the *space*: the name plus
// the keystroke that arms it, with nothing after either.
let top = "module top;\n logic clk;\n sub ";
assert_eq!(ghosted("eof", top, " sub ").as_deref(), Some(SUB_GHOST));
}
/// opentitan's `ast_dft` and `io_osc` in miniature: one module, one copy
/// under each of two tops, with headers that differ so the ghost says which
/// copy it read.
const TWO_TOPS: &[(&str, &str)] = &[
("top_earlgrey/ast_dft.sv", "module ast_dft (input logic clk_earlgrey);\nendmodule\n"),
("top_darjeeling/ast_dft.sv", "module ast_dft (input logic clk_darjeeling);\nendmodule\n"),
];
/// What each copy of `ast_dft` ghosts. Neither port is declared in the
/// asking buffer, so neither auto-connects and the port name is visible in
/// the hole — which is how these tests tell the two copies apart.
const EARLGREY_GHOST: &str = "${1:u_ast_dft} (\n\t.clk_earlgrey(${2:clk_earlgrey})\n);";
const DARJEELING_GHOST: &str = "${1:u_ast_dft} (\n\t.clk_darjeeling(${2:clk_darjeeling})\n);";
#[test]
fn a_module_declared_twice_ghosts_the_copy_nearest_the_buffer() {
// Round 1 gave a twice-declared module no ghost at all:
// `module_definition` refuses to guess which file to read, and the
// ghost inherited the refusal. In opentitan that silenced `ast_dft`
// and `io_osc`, each declared once under `hw/top_earlgrey/ip/ast/rtl`
// and once under `hw/top_darjeeling/ip/ast/rtl` — two whole IP blocks.
// Owner ruling, 2026-08-30: every indexed module expands, so the
// server chooses the copy whose path shares the longest run of leading
// path components with the buffer asking.
let top = "module top;\n ast_dft \nendmodule\n";
assert_eq!(
ghosted_at("earlgrey", TWO_TOPS, "top_earlgrey/top.sv", top, " ast_dft ").as_deref(),
Some(EARLGREY_GHOST),
"a buffer under top_earlgrey gets top_earlgrey's copy"
);
assert_eq!(
ghosted_at("darjeeling", TWO_TOPS, "top_darjeeling/top.sv", top, " ast_dft ")
.as_deref(),
Some(DARJEELING_GHOST),
"…and one under top_darjeeling gets the other"
);
}
#[test]
fn a_buffer_near_neither_copy_gets_the_lexicographically_smaller_path() {
// No shared prefix to rank by, so the tie-break decides — and it is a
// property of the paths rather than of the order the index was built
// in, which is what makes it reproducible. `top_darjeeling` sorts
// before `top_earlgrey`.
let top = "module top;\n ast_dft \nendmodule\n";
assert_eq!(
ghosted_at("neither", TWO_TOPS, "elsewhere/top.sv", top, " ast_dft ").as_deref(),
Some(DARJEELING_GHOST)
);
}
#[test]
fn the_two_copies_may_have_different_headers_and_the_nearest_one_wins() {
// The accepted semantics, written down: the copies are not required to
// agree, and the user gets the one their own file is nearest to. Here
// one copy has a parameter the other has not, so the two ghosts do not
// even have the same shape.
let files = &[
(
"top_a/dup.sv",
"module dup #(\n parameter int W = 4\n) (input logic a);\nendmodule\n",
),
("top_b/dup.sv", "module dup (input logic b);\nendmodule\n"),
];
let top = "module top;\n dup \nendmodule\n";
assert_eq!(
ghosted_at("hdr_a", files, "top_a/top.sv", top, " dup ").as_deref(),
Some("#(\n\t.W(${1:4})\n) ${2:u_dup} (\n\t.a(${3:a})\n);")
);
assert_eq!(
ghosted_at("hdr_b", files, "top_b/top.sv", top, " dup ").as_deref(),
Some("${1:u_dup} (\n\t.b(${2:b})\n);")
);
}
#[test]
fn a_plan_with_an_escaped_identifier_gets_no_ghost() {
// An escaped identifier may legally contain `$`, `}` and `\` — the
// snippet grammar's own punctuation — and the names are written by the
// layout, outside every hole, where no escaping can reach them. The
// popup answered this with a plain-text item; an inline completion has
// no plain-text spelling, so it answers with nothing.
let files =
&[("odd.sv", "module odd (input logic \\my-port$1 , input logic clk);\nendmodule\n")];
let top = "module top;\n logic clk;\n odd \nendmodule\n";
assert_eq!(ghosted_among("escaped", files, top, " odd "), None);
}
#[test]
fn a_module_may_ghost_itself() {
// Cursor inside `top`, typing `top`. The plan is real — `top` is a
// module the workspace declares and the instantiation is legal
// Verilog — so it is offered. Whether instantiating yourself is a good
// idea is the user's business; an elaborator will tell them soon
// enough, and refusing would be this server having an opinion about
// recursion that it cannot back up (a `generate` guarded by a
// parameter is a legitimate recursive structure).
let top = "module top (input logic clk);\n top \nendmodule\n";
assert_eq!(
ghosted("self", top, " top ").as_deref(),
Some("${1:u_top} (\n\t.clk(clk)\n);")
);
}
#[test]
fn the_setting_turns_the_instantiation_ghost_off_and_leaves_the_templates_on() {
let top = "module top;\n logic clk;\n sub \nendmodule\n";
let (_tree, mut ws, uri, position) =
workspace("setting", &[("sub.sv", SUB)], top, " sub ");
assert!(inline_completions(&ws, &uri, position).is_some(), "premise: on by default");
ws.set_client_settings(ClientSettings {
inline_instantiation: Some(false),
..Default::default()
});
assert!(inline_completions(&ws, &uri, position).is_none());
ws.set_client_settings(ClientSettings {
inline_instantiation: Some(true),
..Default::default()
});
assert!(inline_completions(&ws, &uri, position).is_some(), "and back on again");
// The two settings are independent in both directions: the templates
// answer with the instantiation off, and the reverse.
let (_tree, mut ws, uri, position) =
workspace("both", &[("sub.sv", SUB)], "module top;\n always_comb begin\n", "begin");
ws.set_client_settings(ClientSettings {
inline_instantiation: Some(false),
..Default::default()
});
assert!(
inline_completions(&ws, &uri, position).is_some(),
"a template is not an offer \
the instantiation setting governs"
);
let top = "module top;\n logic clk;\n sub \nendmodule\n";
let (_tree, mut ws, uri, position) =
workspace("tmploff", &[("sub.sv", SUB)], top, " sub ");
ws.set_client_settings(ClientSettings {
inline_templates: Some(false),
..Default::default()
});
assert!(inline_completions(&ws, &uri, position).is_some(), "…and the other way round");
}
#[test]
fn the_only_residue_over_a_workspace_is_the_escaped_identifier() {
// Round 2, part C: after the space-armed trigger and the
// nearest-definition chooser, the reasons an indexed module does *not*
// ghost have to be enumerable — so a sweep over every module a
// workspace declares can bucket its misses by reason instead of
// shrugging at them. This is that sweep in miniature, over a workspace
// carrying one of every shape the planner meets: parameters and ports,
// neither, parameters only, a non-ANSI port list, a name two files
// declare, and the one shape that genuinely cannot be ghosted.
let files = &[
("sub.sv", SUB),
("bare.sv", "module bare;\nendmodule\n"),
("empty.sv", "module empty #(\n parameter int W = 2\n) ();\nendmodule\n"),
(
"nonansi.sv",
"module nonansi (a, b);\n input wire a;\n output wire b;\nendmodule\n",
),
("odd.sv", "module odd (input logic \\my-port$1 , input logic clk);\nendmodule\n"),
("top_a/dup.sv", "module dup (input logic a);\nendmodule\n"),
("top_b/dup.sv", "module dup (input logic b);\nendmodule\n"),
];
let top = "module top;\n logic clk;\n probe \nendmodule\n";
let (_tree, ws, uri, _) = workspace("residue", files, top, " probe ");
let doc = ws.document(&uri).expect("open");
let at = top.find(" probe").expect("the probe line") as u32 + 2;
let modules: Vec<String> =
ws.candidates().modules("").iter().map(|name| name.to_string()).collect();
assert!(modules.len() >= 7, "premise: the sweep really covers the workspace: {modules:?}");
let refused: Vec<(&str, NoGhost)> = modules
.iter()
.filter_map(|module| {
instantiation_ghost(&ws, doc, module, at).err().map(|why| (module.as_str(), why))
})
.collect();
assert_eq!(
refused,
vec![("odd", NoGhost::EscapedIdentifier)],
"the residue is the escaped identifier and nothing else"
);
}
#[test]
fn the_instantiation_wire_shape_is_one_snippet_item_at_the_cursor() {
let top = "module top;\n logic clk;\n sub \nendmodule\n";
let (_tree, ws, uri, position) = workspace("wire", &[("sub.sv", SUB)], top, " sub ");
let items = inline_completions(&ws, &uri, position).expect("a ghost");
assert_eq!(
serde_json::to_value(&items).expect("serializes"),
serde_json::json!({
"items": [{
"insertText": { "kind": "snippet", "value": SUB_GHOST },
"range": {
"start": { "line": 2, "character": 6 },
"end": { "line": 2, "character": 6 }
}
}]
})
);
}
}
+292
View File
@@ -0,0 +1,292 @@
//! `lucisv.instantiate` — the instantiation skeleton as an execute command,
//! for clients that have no `textDocument/inlineCompletion`.
//!
//! Since the names-only completion popup of 2026-08-30 the full skeleton is
//! offered by exactly one surface: ghost text. A client without that request —
//! Neovim's built-in LSP, today — had no path to it at all
//! (`docs/topo.md` §2.9-19). A command is the path a keybinding can take,
//! exactly as `lucisv.removePort` is for a Vim user with no lightbulb.
//!
//! **One planner.** Everything here goes through `completion::plan_for` and
//! `completion::nearest_definition`, the same two calls `inline.rs`'s ghost
//! makes, so the command cannot offer a skeleton the ghost would not — the
//! difference is the *rendering*: a snippet with tabstops there, plain text
//! with each fill-in written as its default here. See
//! `docs/features/bind-semantics/README.md`.
// See `rename.rs` for why this is a `WorkspaceEdit`'s problem and not ours.
#![allow(clippy::mutable_key_type)]
use std::collections::HashMap;
use lsp_types::{Position, TextEdit, Uri, WorkspaceEdit};
use serde_json::Value;
use vlog_refactor::{InstantiationPlan, Site};
use crate::completion;
use crate::state::{Document, Workspace};
/// Insert an instantiation of a module at a position:
/// `[uri, position, "module_name"]`.
pub const INSTANTIATE: &str = "lucisv.instantiate";
/// Every command this module executes.
pub fn commands() -> Vec<String> {
vec![INSTANTIATE.to_string()]
}
/// Run `lucisv.instantiate`, or say why it cannot run.
///
/// The answer is a one-edit `WorkspaceEdit` inserting the skeleton at the
/// given position. `server.rs` pushes it as a `workspace/applyEdit` the way
/// it does every port command's — this module knows nothing about that.
///
/// **An escaped identifier is fine here.** The ghost declines such a plan
/// because an inline completion has no plain-text spelling to fall back to
/// (`inline::NoGhost::EscapedIdentifier`); a `TextEdit` is plain text by
/// construction, so there is nothing to escape and nothing to decline.
pub fn execute(ws: &Workspace, arguments: &[Value]) -> Result<WorkspaceEdit, String> {
let uri: Uri =
arguments
.first()
.and_then(|value| serde_json::from_value(value.clone()).ok())
.ok_or_else(|| format!("{INSTANTIATE} 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!("{INSTANTIATE} wants a position as its second argument."))?;
let module = arguments
.get(2)
.and_then(Value::as_str)
.ok_or_else(|| format!("{INSTANTIATE} wants a module name as its third argument."))?;
let doc = ws.document(&uri).ok_or_else(|| {
format!("{INSTANTIATE} can only write into a buffer lucisv has been sent.")
})?;
let offset = doc.positions().offset(position);
// The same gate tier 0 and the ghost ask, so the three surfaces agree on
// where an instantiation may go.
if !completion::at_instantiation_site(doc, offset) {
return Err(format!(
"An instantiation cannot be written at {}:{}.",
position.line, position.character
));
}
let plan = plan_at(ws, doc, module)?;
let text = plan.render(&completion::layout_at(ws, doc, offset));
let edit =
TextEdit { range: lsp_types::Range { start: position, end: position }, new_text: text };
let mut changes: HashMap<Uri, Vec<TextEdit>> = HashMap::new();
changes.insert(uri, vec![edit]);
Ok(WorkspaceEdit::new(changes))
}
/// The plan for `module` as read from the file that declares it.
///
/// The same two calls `inline.rs`'s ghost makes, in the same order and with
/// the same view cache, so the two surfaces cannot plan different skeletons.
/// `pub(crate)` for the test that pins exactly that.
pub(crate) fn plan_at(
ws: &Workspace,
doc: &Document,
module: &str,
) -> Result<InstantiationPlan, String> {
let path = completion::nearest_definition(ws.index(), module, doc.path.as_deref())
.ok_or_else(|| format!("lucisv does not know a module called `{module}`."))?;
// The site is only read for the ports the skeleton may auto-connect, and
// the position was already checked above.
let site = Site { semantics: &doc.semantics, offset: 0 };
let text = match ws.file_view(path) {
Some(view) => return completion::plan_for(ws.index(), module, &view.text, site),
None => {
ws.text_of(path).ok_or_else(|| format!("lucisv cannot read {}.", path.display()))?
}
};
completion::plan_for(ws.index(), module, &text, site)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::inline;
use crate::uri::path_to_uri;
use std::fs;
use std::path::PathBuf;
use vlog_refactor::Layout;
/// 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_instantiate_{}_{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 SUB: &str =
"module sub #(parameter int W = 8) (\n input logic clk,\n output logic [W-1:0] q\n);\nendmodule\n";
fn workspace(tree: &Tree, top: &str) -> (Workspace, Uri) {
tree.write("sub.sv", SUB);
let path = tree.write("top.sv", top);
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(), top.to_string());
(ws, uri)
}
fn text_of(edit: &WorkspaceEdit, uri: &Uri) -> String {
let edits = edit.changes.as_ref().expect("changes").get(uri).expect("one file's edits");
assert_eq!(edits.len(), 1, "one insertion, nothing else");
edits[0].new_text.clone()
}
#[test]
fn the_command_inserts_a_skeleton_at_the_position() {
let tree = Tree::new("basic");
let top = "module top;\n \nendmodule\n";
let (ws, uri) = workspace(&tree, top);
let position = Position { line: 1, character: 2 };
let edit = execute(
&ws,
&[
serde_json::to_value(&uri).expect("uri"),
serde_json::to_value(position).expect("position"),
Value::String("sub".to_string()),
],
)
.expect("the command runs");
let text = text_of(&edit, &uri);
assert!(text.starts_with("sub #("), "{text:?}");
assert!(text.contains(".W(8)"), "the parameter default is written plainly: {text:?}");
assert!(text.contains("u_sub"), "{text:?}");
assert!(text.contains(".clk("), "{text:?}");
assert!(!text.contains("${"), "a plain render writes no tabstops: {text:?}");
// The edit is an insertion: an empty range at the position asked for.
let edits = edit.changes.as_ref().expect("changes").get(&uri).expect("edits");
assert_eq!(edits[0].range.start, position);
assert_eq!(edits[0].range.end, position);
}
#[test]
fn the_command_inserts_the_same_text_the_ghost_would() {
// One planner: rendered through the ghost's own layout and hole
// spelling, the command's plan *is* the ghost's text with the module
// name and the space the user already typed put back in front.
let tree = Tree::new("ghost");
let top = "module top;\n sub \nendmodule\n";
let (ws, uri) = workspace(&tree, top);
let ghost = inline::inline_completions(&ws, &uri, Position { line: 1, character: 6 })
.expect("the ghost is offered");
// Read off the wire shape, so this pin holds against what a client
// actually receives rather than against a private field.
let ghost = serde_json::to_value(&ghost).expect("the ghost serializes");
let ghost = ghost["items"][0]["insertText"]["value"].as_str().expect("a snippet value");
let ours = {
let doc = ws.document(&uri).expect("the buffer");
plan_at(&ws, doc, "sub")
.expect("the plan")
.render_with(&relative(), &mut completion::snippet_hole)
};
assert_eq!(ours, format!("sub {ghost}"));
}
/// `inline.rs`'s own layout, spelled here so the pin above compares like
/// with like.
fn relative() -> Layout {
Layout { base: String::new(), step: "\t".to_string() }
}
#[test]
fn an_escaped_identifier_is_inserted_as_plain_text() {
// The ghost declines such a plan — a snippet has no way to spell a
// `\name` containing `$`, `}` or `\` — but a `TextEdit` is plain text,
// so the command answers where the ghost cannot.
let tree = Tree::new("escaped");
tree.write("esc.sv", "module \\my-sub (\n input logic \\a$b\n);\nendmodule\n");
let top = "module top;\n \nendmodule\n";
let path = tree.write("top.sv", top);
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(), top.to_string());
let edit = execute(
&ws,
&[
serde_json::to_value(&uri).expect("uri"),
serde_json::to_value(Position { line: 1, character: 2 }).expect("position"),
Value::String("\\my-sub".to_string()),
],
)
.expect("the command runs");
let text = text_of(&edit, &uri);
assert!(text.starts_with("\\my-sub "), "{text:?}");
assert!(text.contains("\\a$b"), "{text:?}");
}
#[test]
fn a_position_that_is_not_an_instantiation_site_is_refused() {
let tree = Tree::new("site");
let top = "module top;\n always_comb begin\n \n end\nendmodule\n";
let (ws, uri) = workspace(&tree, top);
let err = execute(
&ws,
&[
serde_json::to_value(&uri).expect("uri"),
serde_json::to_value(Position { line: 2, character: 4 }).expect("position"),
Value::String("sub".to_string()),
],
)
.expect_err("a statement is not an item position");
assert!(err.contains("cannot be written"), "{err}");
}
#[test]
fn a_module_the_workspace_does_not_know_is_refused() {
let tree = Tree::new("unknown");
let top = "module top;\n \nendmodule\n";
let (ws, uri) = workspace(&tree, top);
let err = execute(
&ws,
&[
serde_json::to_value(&uri).expect("uri"),
serde_json::to_value(Position { line: 1, character: 2 }).expect("position"),
Value::String("nowhere".to_string()),
],
)
.expect_err("no such module");
assert!(err.contains("nowhere"), "{err}");
}
#[test]
fn missing_arguments_are_named_in_the_refusal() {
let tree = Tree::new("args");
let top = "module top;\n \nendmodule\n";
let (ws, uri) = workspace(&tree, top);
let uri_value = serde_json::to_value(&uri).expect("uri");
let position = serde_json::to_value(Position { line: 1, character: 2 }).expect("position");
assert!(execute(&ws, &[]).expect_err("no uri").contains("URI"));
assert!(execute(&ws, std::slice::from_ref(&uri_value))
.expect_err("no position")
.contains("position"));
assert!(execute(&ws, &[uri_value, position]).expect_err("no module").contains("module"));
}
}
+897
View File
@@ -0,0 +1,897 @@
//! The large-file fast path: what a buffer nobody lexed can still answer.
//!
//! A buffer over `lucisv.largeFile.threshold` is opened by
//! [`crate::state::Document::large`] — one newline scan, no lex, no parse, no
//! semantics, no index. This module is everything that then reads such a
//! buffer *on demand*:
//!
//! * [`window`] lexes one viewport's worth of source for
//! `textDocument/semanticTokens/range`, which is what paints the file;
//! * [`definition`] and [`references`] scan the buffer once per request for a
//! name.
//!
//! Nothing here is exact, and the rules it approximates by are stated in
//! `docs/features/large-file-mode/README.md`. The contract is only that an
//! answer costs a bounded amount of work and never a pass over the whole
//! file — except the two scans, which are one linear pass and are measured.
use vlog_parser::token::Token;
use vlog_parser::{tokenize, LineIndex, TextRange};
use crate::state::Document;
/// How far back [`inside_block_comment`] looks for the marker that decides
/// whether a window opens inside `/* ... */`.
///
/// 64 KiB. A block comment longer than this is a licence header nobody is
/// scrolled to the middle of, and the cost of the decision has to stay flat in
/// the file's size: this is the one backwards read the fast path does, and it
/// is a `memchr`-shaped search over a fixed slice however big the file is.
const BACKSCAN: u32 = 64 * 1024;
/// The most source one window may lex, 1 MiB.
///
/// A client is free to ask for `semanticTokens/range` over the whole document
/// — VS Code's own `_provideDocumentRangeSemanticTokens` command does exactly
/// that — and answering it over 100 MB would be the whole-file pass this mode
/// exists to avoid. A viewport plus the pages above and below it is a few tens
/// of kilobytes, so the cap is three orders of magnitude clear of anything an
/// editor asks for while scrolling.
const MAX_WINDOW: u32 = 1024 * 1024;
/// How many times [`lex`] may shrink a window that does not lex before giving
/// up on it. Each attempt drops the lines from the failure onwards, and the
/// failure moves backwards every time, so this is a belt-and-braces bound
/// rather than a number anything real reaches.
const SHRINK_ATTEMPTS: usize = 4;
/// The most occurrences `textDocument/references` reports on a large buffer.
/// A name in a netlist can occur a hundred thousand times, and a reference
/// list nobody can read costs the editor more than it gives.
pub const REFERENCE_LIMIT: usize = 1000;
/// One window of a large buffer, lexed.
///
/// Both fields are in **document** offsets: the caller never sees the slice
/// the lexer actually ran on.
pub struct Window {
/// What the lexer made of the window. Empty when the window could not be
/// lexed at all, which is not an error — it is a window whose text is one
/// unterminated construct.
pub tokens: Vec<Token>,
/// Block-comment text the lexer was never shown: the tail of a comment the
/// window opens inside, and the head of one it ends inside. Colouring
/// these is the whole reason the fast path looks backwards at all.
pub comments: Vec<TextRange>,
}
/// Lex the lines `range` touches, and nothing else.
///
/// The window is snapped out to whole lines, capped at [`MAX_WINDOW`], and
/// then treated as a self-contained piece of source. The two things that
/// makes wrong, and what is done about each:
///
/// * **A comment the window opens inside.** Decided by a bounded backwards
/// scan ([`inside_block_comment`]); the tail of the comment is returned as a
/// comment span and the lexer starts after it.
/// * **A construct the window ends inside.** The lexer is all-or-nothing, so
/// an unterminated comment or string at the far edge would cost the whole
/// window; [`lex`] shrinks the window to the last line that does lex, and
/// what is left over is coloured as a comment when it opens one.
pub fn window(doc: &Document, range: lsp_types::Range) -> Window {
let text = &doc.text;
let (start, end) = bounds(&doc.line_index, text.len() as u32, range);
let mut comments = Vec::new();
let mut from = start;
if inside_block_comment(text, start) {
let Some(rest) = text.get(start as usize..end as usize) else {
return Window { tokens: Vec::new(), comments };
};
match rest.find("*/") {
// The comment ends inside the window: colour its tail and lex
// from the first byte after it.
Some(at) => {
from = start + at as u32 + 2;
comments.push(TextRange::new(start, from));
}
// The whole window is inside one comment. Nothing to lex at all,
// which is the cheapest window there is.
None => {
comments.push(TextRange::new(start, end));
return Window { tokens: Vec::new(), comments };
}
}
}
let Some(slice) = text.get(from as usize..end as usize) else {
return Window { tokens: Vec::new(), comments };
};
let (mut tokens, lexed) = lex(slice);
for token in &mut tokens {
rebase(token, from);
}
if let Some(tail) = trailing_comment(slice, lexed) {
comments.push(TextRange::new(from + tail.start, from + tail.end));
}
Window { tokens, comments }
}
/// The byte range one `Range` asks about, snapped out to whole lines and
/// capped.
///
/// Both ends land on a character boundary: a line start and a line end always
/// do, and the cap is floored onto one.
fn bounds(index: &LineIndex, len: u32, range: lsp_types::Range) -> (u32, u32) {
let last = index.line_count();
let first_line = (range.start.line + 1).min(last);
let last_line = (range.end.line + 1).clamp(first_line, last);
let start = index.line_range(first_line).map_or(0, |line| line.start);
let mut end = index.line_range(last_line).map_or(len, |line| line.end);
if end.saturating_sub(start) > MAX_WINDOW {
// Snapped to the line the cap lands in where that helps, and cut
// mid-line where it does not: a single line longer than the cap is
// exactly the netlist shape the cap is for. A token cut in half at the
// far edge still colours as what it started as.
let capped = start + MAX_WINDOW;
end = match index.line_range(index.line_col(capped).0) {
Some(line) if line.end <= capped => line.end,
_ => capped,
};
}
(start, end.max(start))
}
/// Whether the byte at `at` is inside a `/* ... */` comment, as far as a
/// backwards scan of at most [`BACKSCAN`] bytes can tell.
///
/// **Deliberately approximate.** It reads the last `/*` or `*/` before `at`
/// and believes it: a `/*` written inside a string or after a `//` fools it,
/// and so does a comment whose opener is further back than the budget, in
/// which case the answer is "code". Both mis-colour a screen and neither can
/// corrupt anything, which is the trade the whole mode is built on.
fn inside_block_comment(text: &str, at: u32) -> bool {
let at = at as usize;
let mut from = at.saturating_sub(BACKSCAN as usize);
while from < at && !text.is_char_boundary(from) {
from += 1;
}
let Some(hay) = text.get(from..at) else { return false };
match (hay.rfind("/*"), hay.rfind("*/")) {
(Some(open), Some(close)) => open > close,
(Some(_), None) => true,
_ => false,
}
}
/// Lex as much of `slice` as lexes, reporting how many bytes that was.
///
/// The lexer is all-or-nothing (`docs/features/error-recovery/README.md`), and
/// a window cut out of the middle of a file ends wherever the viewport ended —
/// so an unterminated comment or string at the far edge is the *normal* case
/// here, not a broken file. Its error names the line it gave up on, so the
/// retry drops that line and everything after it.
fn lex(slice: &str) -> (Vec<Token>, u32) {
let mut end = slice.len();
for _ in 0..SHRINK_ATTEMPTS {
let Some(head) = slice.get(..end) else { return (Vec::new(), 0) };
match tokenize(head) {
Ok(tokens) => return (tokens, end as u32),
Err(problem) => match line_start(head, problem.line) {
// Line 1 failed: there is nothing left to keep.
Some(0) | None => return (Vec::new(), 0),
Some(shorter) => end = shorter,
},
}
}
(Vec::new(), 0)
}
/// The byte offset of a 1-based line of `text`, or `None` when it has no such
/// line. Used only on the failure path, so it walks rather than indexing.
fn line_start(text: &str, line: u32) -> Option<usize> {
if line <= 1 {
return Some(0);
}
let mut seen = 1;
for (at, byte) in text.bytes().enumerate() {
if byte == b'\n' {
seen += 1;
if seen == line {
return Some(at + 1);
}
}
}
None
}
/// The block comment the leftovers of a shrunk window open, if they open one.
///
/// A banner comment crossing the bottom of the viewport is the shape this is
/// for: the lexer refused the window because of it, and colouring the rest of
/// the window as comment is both what it is and what the *next* window (once
/// the user scrolls) will say too.
fn trailing_comment(slice: &str, lexed: u32) -> Option<TextRange> {
let rest = slice.get(lexed as usize..)?;
let open = rest.find("/*")?;
// A `/*` that is closed inside the leftovers was not what stopped the
// lexer, so this is not the shape above and guessing would be wrong.
if rest[open..].contains("*/") {
return None;
}
Some(TextRange::new(lexed + open as u32, lexed + rest.len() as u32))
}
/// Move a token, and the comments hanging off it, from window offsets to
/// document offsets.
fn rebase(token: &mut Token, by: u32) {
token.span = shift(token.span, by);
for comment in &mut token.leading {
comment.span = shift(comment.span, by);
}
if let Some(comment) = &mut token.trailing {
comment.span = shift(comment.span, by);
}
}
fn shift(span: TextRange, by: u32) -> TextRange {
TextRange::new(span.start + by, span.end + by)
}
// ----------------------------------------------------------------------
// the two scans
// ----------------------------------------------------------------------
/// The keywords that make the identifier after them a declaration, as far as
/// the fast path is concerned.
///
/// A heuristic, and a small one on purpose: it is read backwards from an
/// occurrence, not parsed, so a declaration written any other way (a port
/// listed in an ANSI header after its direction and type, a `typedef`'s new
/// name, an instance name) is simply not found and the request answers
/// nothing. Every word here is a real keyword — pinned by a test against
/// `vlog_parser::KEYWORDS`, so a typo cannot sit here quietly.
const DECLARATORS: [&str; 22] = [
"module",
"macromodule",
"interface",
"package",
"program",
"primitive",
"class",
"function",
"task",
"input",
"output",
"inout",
"wire",
"reg",
"logic",
"bit",
"integer",
"int",
"real",
"genvar",
"parameter",
"localparam",
];
/// The identifier `offset` sits in, if it sits in one.
pub fn word_at(text: &str, offset: u32) -> Option<TextRange> {
let bytes = text.as_bytes();
let at = (offset as usize).min(bytes.len());
let mut start = at;
while start > 0 && is_word(bytes[start - 1]) {
start -= 1;
}
let mut end = at;
while end < bytes.len() && is_word(bytes[end]) {
end += 1;
}
// A cursor in whitespace between two words has an empty range, and an
// empty name would match everywhere.
(start < end).then(|| TextRange::new(start as u32, end as u32))
}
/// Where the name at `offset` looks declared: the first occurrence of it
/// preceded by a declaring keyword, or nothing.
///
/// One linear pass over the buffer, which is what a request on a file nothing
/// has indexed costs. The measurement is in the feature README.
pub fn definition(doc: &Document, offset: u32) -> Option<TextRange> {
let name = word_at(&doc.text, offset)?;
let name = doc.text.get(name.as_range())?;
occurrences(&doc.text, name).find(|at| declares(&doc.text, *at))
}
/// Every occurrence of the name at `offset`, capped at [`REFERENCE_LIMIT`].
///
/// Occurrences of the *text*, whole-word: this buffer has no scopes, so a
/// local `i` in one module and a local `i` in another are one answer. That is
/// the honest thing a text scan can say, and it is what the README calls
/// checking-light.
pub fn references(doc: &Document, offset: u32, include_declaration: bool) -> Vec<TextRange> {
let Some(name) = word_at(&doc.text, offset) else { return Vec::new() };
let Some(text) = doc.text.get(name.as_range()) else { return Vec::new() };
let declaration = (!include_declaration).then(|| definition(doc, offset)).flatten();
occurrences(&doc.text, text)
.filter(|found| Some(*found) != declaration)
.take(REFERENCE_LIMIT)
.collect()
}
/// Every whole-word occurrence of `name` in `text`, in order.
fn occurrences<'a>(text: &'a str, name: &'a str) -> impl Iterator<Item = TextRange> + 'a {
let bytes = text.as_bytes();
text.match_indices(name).filter_map(move |(at, _)| {
let before = at.checked_sub(1).map(|i| bytes[i]);
let after = bytes.get(at + name.len()).copied();
let bounded = !before.is_some_and(is_word) && !after.is_some_and(is_word);
bounded.then(|| TextRange::new(at as u32, (at + name.len()) as u32))
})
}
/// Whether the word before this occurrence declares it.
fn declares(text: &str, occurrence: TextRange) -> bool {
let bytes = text.as_bytes();
let mut end = occurrence.start as usize;
while end > 0 && bytes[end - 1].is_ascii_whitespace() {
end -= 1;
}
let mut start = end;
while start > 0 && is_word(bytes[start - 1]) {
start -= 1;
}
text.get(start..end).is_some_and(|word| DECLARATORS.contains(&word))
}
/// Whether a byte can be part of an identifier. `$` is in, for the system
/// tasks; the escaped-identifier form (`\name `) is not modelled at all.
fn is_word(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$'
}
#[cfg(test)]
mod tests {
use super::*;
use lsp_types::{Position, Range};
use std::path::PathBuf;
/// A fast-path document over `text`.
fn large(text: &str) -> Document {
Document::large(Some(PathBuf::from("/rtl/net.v")), text.to_string())
}
fn range(from: u32, to: u32) -> Range {
Range {
start: Position { line: from, character: 0 },
end: Position { line: to, character: 0 },
}
}
/// The text of every token a window produced, in order.
fn words(doc: &Document, window: &Window) -> Vec<String> {
window
.tokens
.iter()
.filter(|t| t.kind != vlog_parser::token::TokenKind::Eof)
.map(|t| doc.text[t.span.as_range()].to_string())
.collect()
}
// ------------------------------------------------------------------
// the window
// ------------------------------------------------------------------
#[test]
fn a_window_lexes_its_own_lines_and_reports_document_offsets() {
let doc = large("module a;\nwire b;\nwire c;\nendmodule\n");
let window = window(&doc, range(1, 2));
assert_eq!(words(&doc, &window), ["wire", "b", ";", "wire", "c", ";"]);
// The spans are the document's, not the slice's: the first token is
// `wire` on line 1, which starts at byte 10.
assert_eq!(window.tokens[0].span.start, 10);
}
#[test]
fn a_window_starting_mid_line_is_snapped_back_to_the_line_start() {
let doc = large("module a;\nwire b;\n");
let mid = Range {
start: Position { line: 1, character: 4 },
end: Position { line: 1, character: 6 },
};
assert_eq!(words(&doc, &window(&doc, mid)), ["wire", "b", ";"]);
}
#[test]
fn a_window_past_the_end_of_the_file_is_empty_and_does_not_panic() {
let doc = large("module a;\nendmodule\n");
assert!(words(&doc, &window(&doc, range(900, 999))).is_empty());
}
#[test]
fn a_window_opening_inside_a_block_comment_colours_the_tail_and_lexes_the_rest() {
let doc = large("/* a\n b\n c */ wire d;\nwire e;\n");
// Lines 1..3: the window opens on ` b`, which is inside the comment
// opened on line 0, so the tail up to `*/` is a comment span and the
// lexer only saw what followed it.
let window = window(&doc, range(1, 3));
assert_eq!(window.comments.len(), 1);
let comment = &doc.text[window.comments[0].as_range()];
assert!(comment.ends_with("*/"), "{comment:?}");
assert!(comment.starts_with(" b"), "{comment:?}");
assert_eq!(words(&doc, &window), ["wire", "d", ";", "wire", "e", ";"]);
}
#[test]
fn a_window_wholly_inside_a_block_comment_is_one_comment_and_no_tokens() {
let mut text = String::from("/* opener\n");
for _ in 0..40 {
text.push_str(" still a comment\n");
}
text.push_str("*/\nwire a;\n");
let doc = large(&text);
let window = window(&doc, range(10, 20));
assert!(window.tokens.is_empty());
assert_eq!(window.comments.len(), 1);
}
#[test]
fn the_backward_scan_gives_up_beyond_its_budget_and_assumes_code() {
// A block comment opened further back than BACKSCAN: the decision
// cannot be made, and the documented answer is "code".
let mut text = String::from("/* opener\n");
text.push_str(&" filler filler filler filler\n".repeat(4000));
assert!(text.len() as u32 > BACKSCAN, "the premise: past the budget");
text.push_str("wire a;\n");
let doc = large(&text);
let last = doc.line_index.line_count() - 2;
let window = window(&doc, range(last, last));
assert!(window.comments.is_empty(), "no comment was detected");
assert_eq!(words(&doc, &window), ["wire", "a", ";"], "it lexed as code");
}
#[test]
fn a_window_ending_inside_a_block_comment_keeps_the_lines_that_lex() {
let doc = large("wire a;\nwire b;\n/* an unterminated banner\n");
let window = window(&doc, range(0, 2));
assert_eq!(words(&doc, &window), ["wire", "a", ";", "wire", "b", ";"]);
assert_eq!(window.comments.len(), 1, "the banner is coloured as a comment");
assert!(doc.text[window.comments[0].as_range()].starts_with("/*"));
}
#[test]
fn a_window_ending_inside_a_string_keeps_the_lines_that_lex() {
let doc = large("wire a;\n$display(\"unterminated\n");
let window = window(&doc, range(0, 1));
assert_eq!(words(&doc, &window), ["wire", "a", ";"]);
assert!(window.comments.is_empty(), "an unterminated string is not a comment");
}
#[test]
fn a_window_whose_first_line_cannot_lex_answers_nothing_rather_than_guessing() {
let doc = large("$display(\"unterminated\nwire a;\n");
let window = window(&doc, range(0, 0));
assert!(window.tokens.is_empty());
assert!(window.comments.is_empty());
}
#[test]
fn a_window_is_capped_however_much_the_client_asks_for() {
// Every line is 8 bytes, so 200_000 lines is 1.6 MB — a client asking
// for the whole document must still lex at most MAX_WINDOW of it.
let text = "wire a;\n".repeat(200_000);
assert!(text.len() as u32 > MAX_WINDOW, "the premise");
let doc = large(&text);
let window = window(&doc, range(0, doc.line_index.line_count()));
let last = window.tokens.iter().map(|t| t.span.end).max().unwrap_or(0);
assert!(last <= MAX_WINDOW, "lexed past the cap: {last}");
assert!(last > MAX_WINDOW - 64, "and up to it: {last}");
}
#[test]
fn one_line_longer_than_the_cap_is_cut_rather_than_lexed_whole() {
let mut text = String::from("wire ");
text.push_str(&"a".repeat(MAX_WINDOW as usize + 1000));
text.push_str(";\n");
let doc = large(&text);
let window = window(&doc, range(0, 0));
// It still answers, and it did not read the whole line.
let last = window.tokens.iter().map(|t| t.span.end).max().unwrap_or(0);
assert!(last <= MAX_WINDOW, "{last}");
}
#[test]
fn an_empty_buffer_answers_an_empty_window() {
let doc = large("");
let window = window(&doc, range(0, 10));
assert!(window.tokens.is_empty() || words(&doc, &window).is_empty());
assert!(window.comments.is_empty());
}
/// QA attack: a buffer of nothing but newlines. Every line is empty, so
/// every byte offset the code touches (line starts, line ends, the
/// backward scan's window) coincides with several others — the shape most
/// likely to trip an off-by-one into an out-of-range slice.
#[test]
fn a_buffer_of_only_newlines_does_not_panic_and_answers_no_tokens() {
let doc = large(&"\n".repeat(5_000));
for (from, to) in [(0, 1), (0, 5000), (4998, 4999), (2500, 2500)] {
let window = window(&doc, range(from, to));
// Only the EOF token, which every `tokenize` call ends with even
// over blank input — no real token, and no panic getting there.
assert!(words(&doc, &window).is_empty(), "nothing to lex: {from}..{to}");
}
}
/// QA attack: a CRLF netlist. `LineIndex` keeps the `\r` as an ordinary
/// byte of its line (`convert.rs`'s own rule), so a window boundary lands
/// right before a `\r` rather than a `\n` — this pins that the window
/// still lexes the same tokens CRLF or not, and that the trailing `\r` on
/// each line does not get coloured as part of the token before it.
#[test]
fn a_crlf_netlist_windows_the_same_as_its_lf_twin() {
let lf = "module m;\r\n wire sig_a;\r\n wire sig_b;\r\nendmodule\r\n";
let doc = large(lf);
let window = window(&doc, range(1, 2));
assert_eq!(words(&doc, &window), ["wire", "sig_a", ";", "wire", "sig_b", ";"]);
// No token swallowed the `\r`: every token's text is exactly itself.
for token in &window.tokens {
let text = &doc.text[token.span.as_range()];
assert!(!text.contains('\r'), "a token ate the line ending: {text:?}");
}
}
// ------------------------------------------------------------------
// the shrink helper on its own
// ------------------------------------------------------------------
#[test]
fn lex_reports_how_much_of_the_slice_it_used() {
let (tokens, used) = lex("wire a;\n");
assert!(!tokens.is_empty());
assert_eq!(used, 8);
let (tokens, used) = lex("wire a;\n/* open");
assert!(!tokens.is_empty());
assert_eq!(used, 8, "the comment line was dropped");
}
#[test]
fn line_start_counts_lines_from_one() {
assert_eq!(line_start("a\nb\nc", 1), Some(0));
assert_eq!(line_start("a\nb\nc", 2), Some(2));
assert_eq!(line_start("a\nb\nc", 3), Some(4));
assert_eq!(line_start("a\nb\nc", 4), None);
}
// ------------------------------------------------------------------
// definition and references
// ------------------------------------------------------------------
const NETLIST: &str = "module top;\n wire sig_a;\n wire sig_b;\n sub u0 (.a(sig_a), \
.b(sig_b));\n assign sig_a = sig_b;\nendmodule\n";
/// The offset of the `n`-th occurrence of `needle`.
fn at(text: &str, needle: &str, n: usize) -> u32 {
text.match_indices(needle).nth(n).expect("occurrence").0 as u32
}
#[test]
fn a_declaration_is_found_by_the_keyword_before_it() {
let doc = large(NETLIST);
let found = definition(&doc, at(NETLIST, "sig_a", 2)).expect("a declaration");
assert_eq!(found.start, at(NETLIST, "sig_a", 0), "the `wire sig_a;` line");
assert_eq!(&NETLIST[found.as_range()], "sig_a");
}
#[test]
fn a_name_no_keyword_introduces_has_no_definition() {
let doc = large(NETLIST);
assert!(definition(&doc, at(NETLIST, "u0", 0)).is_none(), "an instance name");
}
#[test]
fn a_cursor_that_is_not_on_a_word_answers_nothing() {
let doc = large(NETLIST);
let space = NETLIST.find(" wire").expect("indent") as u32;
assert!(definition(&doc, space).is_none());
assert!(references(&doc, space, true).is_empty());
}
#[test]
fn references_are_whole_word_and_in_order() {
let doc = large(NETLIST);
let found = references(&doc, at(NETLIST, "sig_a", 0), true);
assert_eq!(found.len(), 3, "declaration, connection, assignment");
assert!(found.windows(2).all(|pair| pair[0].start < pair[1].start));
// `sig_a` is not found inside `sig_ab`.
let doc = large("wire sig_ab;\nwire sig_a;\n");
assert_eq!(references(&doc, at(&doc.text, "sig_a", 1), true).len(), 1);
}
#[test]
fn excluding_the_declaration_drops_exactly_the_declaration() {
let doc = large(NETLIST);
let with = references(&doc, at(NETLIST, "sig_a", 1), true);
let without = references(&doc, at(NETLIST, "sig_a", 1), false);
assert_eq!(without.len(), with.len() - 1);
assert!(!without.contains(&with[0]));
}
#[test]
fn the_reference_list_is_capped() {
let text = format!("wire sig;\n{}", "assign x = sig;\n".repeat(REFERENCE_LIMIT + 500));
let doc = large(&text);
assert_eq!(references(&doc, 5, true).len(), REFERENCE_LIMIT);
}
// ------------------------------------------------------------------
// the 100 MB probes
// ------------------------------------------------------------------
/// A netlist-shaped buffer of about `bytes` bytes.
///
/// Instantiation lines, which is what a synthesized netlist really is, with
/// a declaration and a comment every so often so the scans have something
/// to find and the windows have something to colour.
fn netlist(bytes: usize) -> String {
let mut text = String::with_capacity(bytes + 4096);
text.push_str("module netlist_top;\n wire needle;\n");
let mut n = 0u64;
while text.len() < bytes {
text.push_str(&format!(
" sky130_fd_sc_hd__inv_2 _{n}_ (.A(net{n}), .Y(net{}));\n",
n + 1
));
if n.is_multiple_of(500) {
text.push_str(" /* a banner comment, so the windows are not all code */\n");
text.push_str(" wire net_local;\n");
}
n += 1;
}
// A second declaration at the far end: a scan for it is the worst
// case, since the answer is the last thing in the file.
text.push_str(" wire tail_needle;\nendmodule\n");
text
}
/// **The measurement the feature README quotes.** Ignored by default: it
/// builds a 100 MB buffer, which is not something `cargo test` should do
/// on every run. Run it as
/// `cargo test -p lucisv_server --release -- --ignored --nocapture
/// large::tests::the_hundred_megabyte_probes`.
///
/// The bounds asserted are deliberately loose — an order of magnitude over
/// what the numbers actually are on the machine this was written on — so
/// the probe fails on a regression in *kind* (someone made the open path
/// scan the file twice, someone made the window lex the document) rather
/// than on a slow CI box.
#[test]
#[ignore = "synthesizes a 100 MB buffer; run with --release --ignored --nocapture"]
fn the_hundred_megabyte_probes() {
use std::time::Instant;
let text = netlist(100 * 1024 * 1024);
let bytes = text.len();
let clock = Instant::now();
let doc = Document::large(Some(PathBuf::from("/rtl/netlist.v")), text);
let open = clock.elapsed();
let lines = doc.line_index.line_count();
let middle = lines / 2;
let viewport = Range {
start: Position { line: middle, character: 0 },
end: Position { line: middle + 60, character: 0 },
};
// Twice: the first call is where any accidental one-off whole-file
// work would hide.
let clock = Instant::now();
let first = window(&doc, viewport);
let first_window = clock.elapsed();
let clock = Instant::now();
let again = window(&doc, viewport);
let second_window = clock.elapsed();
assert_eq!(first.tokens.len(), again.tokens.len());
assert!(!first.tokens.is_empty(), "the window really did lex something");
// The worst case for both scans: the name is declared in the *last*
// line of the file, so the answer is only found after a whole pass.
let tail = doc.text.rfind("tail_needle").expect("the tail declaration") as u32;
let clock = Instant::now();
let found = definition(&doc, tail);
let definition_scan = clock.elapsed();
assert!(found.is_some());
let clock = Instant::now();
let refs = references(&doc, tail, true);
let reference_scan = clock.elapsed();
assert!(!refs.is_empty());
// And the shape that is worst for the search itself: a short name
// that occurs as a *prefix* of a million others, so the whole-word
// filter runs on every one of them.
let common = doc.text.find("net1)").expect("a net use") as u32;
let clock = Instant::now();
let many = references(&doc, common, true);
let capped_scan = clock.elapsed();
eprintln!(
"100 MB probe: {bytes} bytes, {lines} lines\n \
open (line index only): {open:?}\n \
semanticTokens/range window (60 lines): {first_window:?} then {second_window:?}\n \
definition scan (declared in the last line): {definition_scan:?}\n \
references scan (2 hits, whole file): {reference_scan:?}\n \
references scan (short name, {} hits among a million prefixes): {capped_scan:?}",
many.len()
);
assert!(open.as_millis() < 5_000, "opening cost {open:?}");
assert!(first_window.as_millis() < 200, "the first window cost {first_window:?}");
assert!(second_window.as_millis() < 200, "the second window cost {second_window:?}");
assert!(
definition_scan.as_millis() < 1_000,
"the definition scan cost {definition_scan:?}"
);
assert!(reference_scan.as_millis() < 1_000, "the reference scan cost {reference_scan:?}");
assert!(capped_scan.as_millis() < 1_000, "the worst-case scan cost {capped_scan:?}");
}
/// What the fast path is worth, measured rather than asserted: the same
/// buffer through [`Document::new`] and through [`Document::large`].
///
/// Ten megabytes rather than a hundred, because the point is the *ratio*
/// and because a 100 MB full analysis is minutes and gigabytes — which is
/// itself the finding, and is why the threshold exists.
#[test]
#[ignore = "analyzes a 10 MB buffer in full; run with --release --ignored --nocapture"]
fn the_full_pipeline_probe_says_what_the_fast_path_saves() {
use std::time::Instant;
let text = netlist(10 * 1024 * 1024);
let clock = Instant::now();
let fast = Document::large(None, text.clone());
let fast_open = clock.elapsed();
let clock = Instant::now();
let full = Document::new(None, text, &vlog_semantic::WorkspaceIndex::default());
let full_open = clock.elapsed();
eprintln!(
"10 MB open: fast path {fast_open:?} ({} tokens), full pipeline {full_open:?} \
({} tokens) — {:.0}x",
fast.tokens.len(),
full.tokens.len(),
full_open.as_secs_f64() / fast_open.as_secs_f64().max(f64::MIN_POSITIVE)
);
assert!(fast_open < full_open, "the fast path is the fast one");
}
#[test]
fn every_declarator_is_a_real_keyword() {
for word in DECLARATORS {
assert!(
vlog_parser::KEYWORDS.contains(&word),
"{word} is not a keyword the lexer knows"
);
}
}
/// **QA finding 1 (2026-08-27), fixed and now a gate.** A single line far
/// longer than [`BACKSCAN`], packed with thousands of short tokens rather
/// than one long one — a wide bus concatenation or a one-line generated
/// port list, both ordinary netlist shapes. `window()` itself only ever
/// touches [`MAX_WINDOW`] bytes, so the *lexer* side was always bounded by
/// construction. But colouring the window also converts every token's byte
/// span to a UTF-16 LSP position (`tokens::flatten`), and that conversion
/// used to scan from the **start of the token's line** every time: on an
/// ordinary file a few dozen bytes of work, on a window that is all one
/// line O(line length) per token, i.e. **O(tokens²)**. Measured at
/// 107.8 ms → 439.3 ms → 1.85 s → **7.86 s** across the four sizes below
/// (release) — 4x the time for 2x the tokens, the signature of a quadratic
/// wall rather than the "bounded, however big the file is" cost the
/// feature README promises.
///
/// `tokens::flatten` now converts through `Positions::walker`
/// (`convert.rs`), which measures each line once however many offsets fall
/// on it. The same four sizes are **1.7 / 3.3 / 6.4 / 13.2 ms** — 2x for
/// 2x, and 596x faster at the top.
///
/// The bound is wall-clock, loose, and in debug (this test runs in the
/// normal suite): ~4x the measured debug cost of the largest size, which
/// the quadratic version overshoots by more than two orders of magnitude.
/// A regression in *kind* fails it; a slow CI box does not.
#[test]
fn a_window_of_many_tokens_on_one_line_colours_in_linear_time() {
use std::time::Instant;
for count in [5_000u32, 10_000, 20_000, 40_000] {
// One line: `module m; wire a0,a1,...,last;` — realistic in shape
// (a wide declaration), synthetic only in how wide.
let mut text = String::from("module m; wire ");
for n in 0..count {
text.push_str(&format!("a{n},"));
}
text.push_str("last;\nendmodule\n");
let doc = large(&text);
let clock = Instant::now();
let window = window(&doc, range(0, 1));
let lex_elapsed = clock.elapsed();
assert!(!window.tokens.is_empty());
let clock2 = Instant::now();
let data = crate::tokens::semantic_tokens_in_window(&doc, range(0, 1));
let colour_elapsed = clock2.elapsed();
eprintln!(
"{count} tokens, {}-byte line: lex {lex_elapsed:?}, colour {colour_elapsed:?}, \
{} tokens answered",
text.len(),
data.len() / 5
);
assert!(!data.is_empty(), "the window really did colour something");
assert!(
colour_elapsed.as_millis() < COLOUR_BUDGET_MS,
"colouring {count} tokens on one line cost {colour_elapsed:?} — \
the quadratic conversion is back"
);
}
}
/// The wall-clock ceiling the test above holds the colourer to, in a
/// **debug** build: 4.5x the slowest of the four sizes as measured on the
/// machine this was written on (77 ms at 40,000 tokens, ±0.5 ms over
/// four runs), where the quadratic version this replaced would need tens
/// of seconds.
const COLOUR_BUDGET_MS: u128 = 350;
/// **QA finding 1 (2026-08-27), fixed and now a gate**, on the *other*
/// fast-path consumer of `Positions`: `references`' hits still have to
/// become `lsp_types::Location`s (`Server::large_scan`, `server.rs`), one
/// `Positions::range` each. `large::references` itself was always linear;
/// the wall was entirely in turning up to [`REFERENCE_LIMIT`] hits on one
/// gigantic line into positions — 206 ms → 789 ms → 3.15 s → **12.6 s**
/// for 100 → 800 hits (release), against a scan of 0.9 → 6.4 ms.
///
/// `large_scan` now walks the hits with one `Positions::walker`, which
/// they are already in ascending order for. This runs at an eighth of the
/// original probe's line lengths so it can live in the normal suite; the
/// bound is debug wall-clock and ~4x the measured cost, which a return of
/// the per-hit rescan overshoots by two orders of magnitude.
#[test]
fn references_on_one_giant_line_locate_their_hits_in_linear_time() {
use std::time::Instant;
for width in [100u32, 200, 400, 800] {
// One line: `wire sig;` filler `sig` filler `sig` ... — `width`
// occurrences of the needle spread over one line, all comfortably
// under REFERENCE_LIMIT so the cap is not what is being timed.
let mut text = String::from("wire sig;");
for _ in 0..width {
text.push_str(&" filler_word ".repeat(250));
text.push_str("sig");
}
text.push('\n');
let doc = large(&text);
let clock = Instant::now();
let hits = references(&doc, 5, true);
let scan_elapsed = clock.elapsed();
assert_eq!(hits.len() as u32, width + 1, "the declaration plus every use");
let positions = doc.positions();
let clock2 = Instant::now();
// Exactly what `Server::large_scan` does with them.
let mut walker = positions.walker();
for hit in &hits {
std::hint::black_box(walker.range(*hit));
}
let locate_elapsed = clock2.elapsed();
eprintln!(
"{width} hits on one {}-byte line: scan {scan_elapsed:?}, locate {locate_elapsed:?}",
text.len()
);
assert!(
locate_elapsed.as_millis() < LOCATE_BUDGET_MS,
"locating {width} hits on one line cost {locate_elapsed:?} — \
the per-hit line rescan is back"
);
}
}
/// The wall-clock ceiling for the locator above, in a **debug** build:
/// 4.7x the slowest of the four sizes as measured on the machine this was
/// written on (32 ms at 800 hits on a 2.6 MB line, ±0.2 ms over four
/// runs).
const LOCATE_BUDGET_MS: u128 = 150;
}
+79 -15
View File
@@ -25,8 +25,10 @@
use lsp_types::{CodeLens, Command, Location, Uri};
use serde_json::Value;
use vlog_semantic::instantiations;
use crate::hierarchy;
use crate::state::Workspace;
use crate::{hierarchy, instantiations};
/// Show every instantiation of a module: `[module-name]`.
pub const SHOW_INSTANTIATIONS: &str = "lucisv.showInstantiations";
@@ -179,7 +181,7 @@ mod tests {
}
}
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let (path, text) = first.expect("at least one file");
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), text.to_string());
@@ -505,7 +507,7 @@ endmodule
return;
};
let mut ws = Workspace::default();
ws.open_roots(vec![corpus]);
ws.open_whole_workspace(vec![corpus]);
let uri = path_to_uri(&file).expect("uri");
ws.set_document(uri.clone(), text);
let lenses = code_lenses(&ws, &uri).expect("open");
@@ -567,7 +569,7 @@ endmodule
tree_b.write("a/m.sv", m_a);
let path_b = tree_b.write("b/m.sv", m_b);
tree_b.write("top.sv", user);
ws_b.open_roots(vec![tree_b.path.clone()]);
ws_b.open_whole_workspace(vec![tree_b.path.clone()]);
let uri_b = path_to_uri(&path_b).expect("uri");
ws_b.set_document(uri_b.clone(), m_b.to_string());
assert_eq!(
@@ -639,17 +641,73 @@ endmodule
// the performance claim, measured
// ------------------------------------------------------------------
/// What a whole file's lenses cost over the real corpus, and — the point
/// of the batch — that asking about three modules at once costs about what
/// asking about one does, not three times as much.
/// The number the round's Handshake was filed for, measured: what a whole
/// file's lenses cost before the edge table (a walk of every in-scope
/// file, re-read and re-parsed) and what they cost after (a lookup).
///
/// `#[ignore]`d like the other measurement probes in this crate — it prints
/// a number rather than asserting one, and the assertion that must hold is
/// `code_lenses_for_a_whole_file_cost_a_fraction_of_a_workspace_walk`
/// above. Run with `cargo test -p lucisv_server -- --ignored --nocapture`.
#[test]
#[ignore]
fn qa_perf_lens_lookup_against_the_walk_it_replaced() {
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let file = corpus.join("common_cells/src/cdc_fifo_gray.sv");
let Ok(text) = fs::read_to_string(&file) else {
eprintln!("cdc_fifo_gray.sv is not in this corpus — skipping");
return;
};
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![corpus]);
let uri = path_to_uri(&file).expect("uri");
ws.set_document(uri.clone(), text);
let _ = code_lenses(&ws, &uri);
let mut lenses = std::time::Duration::ZERO;
let mut walk = std::time::Duration::ZERO;
for _ in 0..3 {
let started = std::time::Instant::now();
let _ = code_lenses(&ws, &uri).expect("open");
lenses = lenses.max(started.elapsed());
// What `callers_of_each` used to begin with, every request.
let started = std::time::Instant::now();
let _ = ws.sources();
walk = walk.max(started.elapsed());
}
eprintln!(
"codeLens over {} files: {lenses:?} for the whole file; one workspace walk \
(what the old census re-read on every request) is {walk:?}",
ws.index().files().len()
);
}
/// What a whole file's lenses cost over the real corpus, against what one
/// workspace walk costs.
///
/// **Superseded this round (incremental-index, 2026-08-27):**
/// `code_lenses_for_a_whole_file_cost_about_one_workspace_walk` asserted
/// `whole_file < one_name * 2` — that asking about three modules cost about
/// what asking about one did, because both were *one walk* of the whole
/// workspace. There is no walk any more: the count is a lookup in the
/// index's instantiation-edge table, and the only I/O left is reading the
/// handful of files that really do instantiate one of the three. Both sides
/// of that ratio are now microseconds dominated by a file read each, so the
/// ratio pins noise. The property worth pinning is the stronger one this
/// round bought: **a whole file's lenses cost a small fraction of one
/// workspace walk**, measured here rather than asserted.
///
/// Skipped when `corpus/` is not checked out (`tools/corpus_fetch.sh`),
/// like the other corpus tests. The budget is deliberately loose: a debug
/// build on a loaded machine is the worst case this ever runs in, and this
/// exists to catch an order-of-magnitude regression — a lens handler that
/// re-read the workspace once per declaration would fail the ratio.
/// went back to re-reading the workspace would fail it by two.
#[test]
fn code_lenses_for_a_whole_file_cost_about_one_workspace_walk() {
fn code_lenses_for_a_whole_file_cost_a_fraction_of_a_workspace_walk() {
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
@@ -663,14 +721,17 @@ endmodule
return;
};
let mut ws = Workspace::default();
ws.open_roots(vec![corpus]);
ws.open_whole_workspace(vec![corpus]);
let uri = path_to_uri(&file).expect("uri");
ws.set_document(uri.clone(), text);
// Warm, then the worst of three, for the whole file and for one name.
// Warm, then the worst of three, for the whole file and for one name;
// and the best of three for the walk it used to be, so the comparison
// is stacked against the claim rather than for it.
let _ = code_lenses(&ws, &uri);
let mut whole_file = std::time::Duration::ZERO;
let mut one_name = std::time::Duration::ZERO;
let mut walk = std::time::Duration::MAX;
let mut count = 0;
for _ in 0..3 {
let started = std::time::Instant::now();
@@ -680,18 +741,21 @@ endmodule
let started = std::time::Instant::now();
let _ = sites_of(&ws, "cdc_fifo_gray");
one_name = one_name.max(started.elapsed());
let started = std::time::Instant::now();
let _ = ws.sources();
walk = walk.min(started.elapsed());
}
eprintln!(
"corpus: {} files, {count} lenses for cdc_fifo_gray.sv in {whole_file:?} \
(one name alone: {one_name:?})",
(one name alone: {one_name:?}; one workspace walk: {walk:?})",
ws.index().files().len(),
);
assert!(count >= 3, "the file declares three modules: {count}");
assert!(whole_file < std::time::Duration::from_millis(1500), "lenses cost {whole_file:?}");
assert!(
whole_file < one_name * 2,
"the batch is one walk, not one per module: {count} names cost {whole_file:?} \
against {one_name:?} for one"
whole_file * 10 < walk,
"the lens is a lookup, not a walk: {count} names cost {whole_file:?} against \
{walk:?} for one walk of the workspace"
);
}
}
+217 -13
View File
@@ -2,17 +2,102 @@
//!
//! `vlog_linter` is the same engine `lucisv check` runs, with the same default
//! rule set — an editor that disagreed with CI about what a violation is would
//! be worse than one that showed none. Selection (`--select`/`--ignore`) has no
//! `lucisv.toml` key yet, so there is nothing here to configure; see
//! be worse than one that showed none. Since 2026-09-02 that includes the two
//! things a project-wide run has and a single file does not: a **census** the
//! semantic rules ask about names in other files, taken from the workspace
//! index, and a **selection** (`lucisv.lint.select` / `lucisv.lint.ignore`),
//! which is the same `--select`/`--ignore` the CLI has and the same `[lint]`
//! table `lucisv.toml` now carries. See
//! `docs/features/semantic-lints-on/README.md` and
//! `docs/features/server-lint/README.md`.
use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString};
use vlog_formatter::fence::{self, Region};
use vlog_linter::{default_rules, lint, LintContext, Violation};
use vlog_linter::{
default_rules, lint, workspace_rules, LintContext, MentionOracle, Rule, Violation,
};
use vlog_semantic::{FileId, WorkspaceIndex};
use crate::convert::Positions;
use crate::diagnostics::SOURCE;
use crate::state::Document;
use crate::state::{Document, Workspace};
/// What one lint pass runs: which rules, and what it may ask about the files
/// around this one.
///
/// [`LintRun::default`] is a pass with no census and the rules a run without
/// one gets — exactly what this server did before the census existed, and what
/// every caller that has no [`Workspace`] in hand still gets.
pub struct LintRun<'a> {
rules: Vec<&'static dyn Rule>,
oracle: Option<IndexMentions<'a>>,
}
impl Default for LintRun<'_> {
fn default() -> LintRun<'static> {
LintRun { rules: default_rules(), oracle: None }
}
}
impl<'a> LintRun<'a> {
/// The pass this workspace's settings and index describe for one buffer.
///
/// The census exists when the index holds **some other file**: an index of
/// this buffer alone (or of nothing at all — a rootless session before its
/// first scan) can only repeat what the buffer says about itself, and
/// treating that as a project would switch the semantic rules on with no
/// cross-file evidence behind them, which is the false-positive mode this
/// whole round exists to close.
pub fn for_document(ws: &'a Workspace, doc: &Document) -> LintRun<'a> {
let index = ws.index();
let own = doc.path.as_deref().and_then(|path| index.file_id(path));
let workspace = index.files().len() > usize::from(own.is_some());
let client = ws.client_settings();
// Every name in the settings was checked against the registry when the
// settings were parsed, so this cannot fail; if it somehow does, the
// defaults are the answer a dropped setting always gets here.
let rules = vlog_linter::select_rules(&client.lint_select, &client.lint_ignore, workspace)
.unwrap_or_else(|_| if workspace { workspace_rules() } else { default_rules() });
let oracle = workspace.then_some(IndexMentions { index, own });
LintRun { rules, oracle }
}
/// This run's context over a buffer's own parse products.
fn context<'d>(&'d self, doc: &'d Document) -> LintContext<'d> {
let ctx = context(doc);
match &self.oracle {
Some(oracle) => ctx.with_oracle(oracle),
None => ctx,
}
}
}
/// The workspace index, asked the one question a lint rule may ask about other
/// files.
///
/// Answered from [`WorkspaceIndex::files_mentioning`] — the *textual* census,
/// which holds the hierarchical uses (`tb.dut.sig`) and `bind` connections the
/// resolved reference tables never see. The buffer's own file is subtracted:
/// a signal's own declaration is not evidence that something else uses it.
///
/// **Staleness is the index's, not this type's.** A file saved but not yet
/// rescanned answers with its last-scanned words, exactly as hover and
/// find-references do; an open buffer's unsaved edits reach the census when
/// its facts are folded in. No new staleness is introduced here.
struct IndexMentions<'a> {
index: &'a WorkspaceIndex,
/// The buffer's own file, when the index holds it. `None` — an untitled
/// buffer, or one outside the indexed scope — means nothing is subtracted,
/// which can only ever make the oracle answer *yes* more often, i.e. make
/// a rule quieter. That is the safe direction.
own: Option<FileId>,
}
impl MentionOracle for IndexMentions<'_> {
fn mentioned_elsewhere(&self, name: &str) -> bool {
self.index.mentioned_outside(name, self.own)
}
}
/// The document's own parse products, lent to the linter — "one parse, two
/// tools" (`docs/features/one-parse/README.md`): the buffer was tokenized and
@@ -28,12 +113,12 @@ fn context(doc: &Document) -> LintContext<'_> {
.with_semantics(&doc.semantics)
}
/// Every violation the default rules find in a buffer.
/// Every violation `run`'s rules find in a buffer.
///
/// 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.
pub fn violations(doc: &Document) -> Vec<Violation> {
lint(&context(doc), &default_rules())
pub fn violations_in(doc: &Document, run: &LintRun) -> Vec<Violation> {
lint(&run.context(doc), &run.rules)
}
/// The findings a code action may offer a fix for, with their fixes built for
@@ -71,10 +156,21 @@ fn fix_touches_fence(violation: &Violation, regions: &[Region]) -> bool {
})
}
/// One LSP diagnostic per lint violation.
/// One LSP diagnostic per lint violation, with no census.
///
/// `#[cfg(test)]` because the server itself always has a workspace to hand and
/// therefore always goes through [`diagnostics_in`]; this is the door the
/// tests that predate the project-aware pass come in by, and keeping it means
/// they go on asserting about the same code with one fewer thing supplied.
#[cfg(test)]
pub fn diagnostics(doc: &Document) -> Vec<Diagnostic> {
diagnostics_in(doc, &LintRun::default())
}
/// [`diagnostics`] for a run that knows what the project says.
pub fn diagnostics_in(doc: &Document, run: &LintRun) -> Vec<Diagnostic> {
let positions = doc.positions();
violations(doc).iter().map(|v| diagnostic(&positions, v)).collect()
violations_in(doc, run).iter().map(|v| diagnostic(&positions, v)).collect()
}
/// The diagnostic a violation becomes.
@@ -97,8 +193,10 @@ pub fn diagnostic(positions: &Positions<'_>, violation: &Violation) -> Diagnosti
#[cfg(test)]
mod tests {
use super::*;
use crate::settings::ClientSettings;
use crate::state::Workspace;
use lsp_types::Uri;
use std::path::PathBuf;
use std::str::FromStr;
fn doc_of(text: &str) -> (Workspace, Uri) {
@@ -201,10 +299,10 @@ mod tests {
#[test]
fn a_semantic_rule_reads_the_documents_own_analysis() {
// The rule is off by default, so this goes through `context()`
// directly — which is the point: the wiring must be in place before
// any semantic rule is ever selected here, so the server never
// analyzes a buffer twice per keystroke.
// The buffer here has no project behind it, so the rule is off by
// default and this goes through `context()` directly — which is the
// point: whichever door a semantic rule comes in by, it must read the
// analysis the server already made, so no keystroke analyzes twice.
let (ws, uri) = doc_of("module m;\n wire spare;\nendmodule\n");
let doc = ws.document(&uri).expect("open");
let rule = vlog_linter::rule_by_name("unused-signal").expect("the rule exists");
@@ -212,6 +310,112 @@ mod tests {
assert_eq!(found.len(), 1, "{found:#?}");
assert!(found[0].message.contains("spare"), "{}", found[0].message);
assert!(std::ptr::eq(context(doc).semantics(), &doc.semantics), "the lent table");
// ... including the project-aware door, which wraps that same context
// in the census rather than building a second one.
let run = LintRun::for_document(&ws, doc);
assert!(std::ptr::eq(run.context(doc).semantics(), &doc.semantics), "still lent");
}
/// A workspace of two files on disk, the second of which reads the
/// first's signal through a hierarchical path — QA's cross-file
/// false-positive repro, made real rather than synthetic.
fn two_file_project(tag: &str) -> (Workspace, PathBuf, Uri) {
let dir = std::env::temp_dir().join(format!("lucisv_lint_{}_{tag}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
std::fs::write(
dir.join("dut.sv"),
"module dut;\n logic dbg_probe;\n logic dead;\nendmodule\n",
)
.expect("write");
std::fs::write(
dir.join("tb.sv"),
"module tb;\n dut d ();\n initial $display(\"%b\", d.dbg_probe);\nendmodule\n",
)
.expect("write");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let uri = Uri::from_str(&format!("file://{}", dir.join("dut.sv").display())).expect("uri");
ws.set_document(uri.clone(), std::fs::read_to_string(dir.join("dut.sv")).expect("read"));
(ws, dir, uri)
}
fn codes(diags: &[Diagnostic]) -> Vec<String> {
diags
.iter()
.filter_map(|d| match &d.code {
Some(NumberOrString::String(name)) => Some(name.clone()),
_ => None,
})
.collect()
}
/// The round's headline, through the server: with a project behind it the
/// semantic rules run, and the file that reads `d.dbg_probe` is what keeps
/// `dbg_probe` quiet while `dead` is still reported.
#[test]
fn a_project_turns_the_semantic_rules_on_and_its_census_keeps_them_honest() {
let (ws, dir, uri) = two_file_project("project");
let doc = ws.document(&uri).expect("open");
let run = LintRun::for_document(&ws, doc);
let diags = diagnostics_in(doc, &run);
assert_eq!(codes(&diags), vec!["unused-signal"], "{diags:#?}");
assert!(diags[0].message.contains("dead"), "{}", diags[0].message);
assert!(!diags[0].message.contains("dbg_probe"));
// And the same buffer with no project behind it is v0.29.0's answer.
assert!(diagnostics(doc).is_empty(), "no census, no semantic rules");
let _ = std::fs::remove_dir_all(dir);
}
/// The off switch, over the settings door: `lucisv.lint.ignore` takes a
/// rule out of the published set.
#[test]
fn the_lint_settings_select_what_the_server_publishes() {
let (mut ws, dir, uri) = two_file_project("settings");
ws.set_client_settings(ClientSettings {
lint_ignore: vec!["unused-signal".to_string()],
..ClientSettings::default()
});
let doc = ws.document(&uri).expect("open");
let run = LintRun::for_document(&ws, doc);
assert!(diagnostics_in(doc, &run).is_empty(), "the setting silenced the rule");
// `select` replaces the default set, exactly as `--select` does: the
// tab is reported by default and not when something else is selected.
ws.set_client_settings(ClientSettings::default());
ws.set_document(uri.clone(), "module dut;\n\tlogic dead;\nendmodule\n".to_string());
let doc = ws.document(&uri).expect("open");
let mut by_default = codes(&diagnostics_in(doc, &LintRun::for_document(&ws, doc)));
by_default.sort();
assert_eq!(by_default, vec!["no-tabs", "unused-signal"], "premise");
ws.set_client_settings(ClientSettings {
lint_select: vec!["unused-signal".to_string()],
..ClientSettings::default()
});
let doc = ws.document(&uri).expect("open");
let run = LintRun::for_document(&ws, doc);
assert_eq!(codes(&diagnostics_in(doc, &run)), vec!["unused-signal"], "the tab is dropped");
let _ = std::fs::remove_dir_all(dir);
}
/// An index that holds only this buffer is not a project: there is nothing
/// to ask, so the rules that need one stay off.
#[test]
fn a_workspace_of_one_file_is_not_a_project() {
let dir = std::env::temp_dir().join(format!("lucisv_lint_{}_alone", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
std::fs::write(dir.join("dut.sv"), "module dut;\n logic dead;\nendmodule\n")
.expect("write");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![dir.clone()]);
let uri = Uri::from_str(&format!("file://{}", dir.join("dut.sv").display())).expect("uri");
ws.set_document(uri.clone(), "module dut;\n logic dead;\nendmodule\n".to_string());
let doc = ws.document(&uri).expect("open");
assert!(diagnostics_in(doc, &LintRun::for_document(&ws, doc)).is_empty());
let _ = std::fs::remove_dir_all(dir);
}
#[test]
+22 -8
View File
@@ -3,12 +3,15 @@
//! The workspace index deliberately keeps no file contents
//! (`docs/features/workspace-index/README.md`), so a span in another file has
//! to be converted against that file's text, fetched here with the same
//! open-buffer-beats-disk precedence the index rebuild uses.
//! open-buffer-beats-disk precedence the index rebuild uses — from the
//! 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.
use std::path::Path;
use lsp_types::Location;
use vlog_parser::{LineIndex, TextRange};
use vlog_parser::TextRange;
use crate::convert::Positions;
use crate::state::Workspace;
@@ -17,17 +20,28 @@ use crate::uri::path_to_uri;
/// The location of a byte span inside a workspace file.
pub fn location(ws: &Workspace, path: &Path, span: TextRange) -> Option<Location> {
let uri = path_to_uri(path)?;
let text = ws.text_of(path)?;
let index = LineIndex::new(&text);
let range = Positions::new(&text, &index).range(span);
Some(Location { uri, range })
if let Some(doc) = ws.document_for_path(path) {
return Some(Location { uri, range: doc.positions().range(span) });
}
let view = ws.file_view(path)?;
Some(Location { uri, range: Positions::new(&view.text, &view.lines).range(span) })
}
/// The 1-based line a byte offset falls on, for hover text that names a file
/// and a line rather than jumping to it.
///
/// An open buffer answers from the line index it already carries; a closed
/// file answers from the shared view cache. **An indexed declaration should
/// not come here at all** — `Def::lines` already holds its line, recorded when
/// the file was indexed, and that answer costs nothing
/// (`docs/features/hover-line-index/README.md`). What is left for this
/// function is the spans the index records no line for, which today is a
/// `` `define``'s.
pub fn line_number(ws: &Workspace, path: &Path, offset: u32) -> Option<u32> {
let text = ws.text_of(path)?;
Some(LineIndex::new(&text).line_col(offset).0)
if let Some(doc) = ws.document_for_path(path) {
return Some(doc.line_index.line_col(offset).0);
}
Some(ws.file_view(path)?.lines.line_col(offset).0)
}
/// How a file is named in hover text: its file name, which is what a Verilog
+231 -12
View File
@@ -10,6 +10,7 @@ mod candidates;
mod code_action;
mod completion;
mod convert;
mod design_hierarchy;
mod diagnostics;
mod expand;
mod file_ops;
@@ -18,9 +19,11 @@ mod format;
mod hierarchy;
mod hover;
mod includes;
mod index_cache;
mod inlay;
mod inline;
mod instantiations;
mod instantiate;
mod large;
mod lens;
mod linked;
mod lint;
@@ -28,6 +31,8 @@ mod locate;
mod nav;
mod on_type;
mod pairs;
#[cfg(test)]
mod perf;
mod ports;
mod rename;
mod selection;
@@ -61,10 +66,39 @@ use lsp_types::{
WorkDoneProgressOptions, WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities,
};
use vlog_parser::PARSE_STACK_SIZE;
use crate::server::{ClientAbilities, Server};
use crate::uri::uri_to_path;
/// The one flag this binary takes: per-operation timing lines in the client's
/// log channel. One spelling, no `-v` — see
/// `docs/features/verbose-timing/README.md`.
const VERBOSE: &str = "--verbose";
/// `vscode-languageclient` (and other LSP clients) append `--stdio` to the
/// spawn when the transport is stdio — the only transport this server has.
/// Accepted as the statement of fact it is; rejecting it turned out to crash
/// every real VS Code session the moment strict argument parsing shipped
/// (lead hotfix, 2026-08-29 — the smoke and restart harnesses spawn the
/// binary directly, so nothing in the loop exercised the library's spawn).
const STDIO: &str = "--stdio";
/// What someone who spelled an argument wrong is told, on stderr. One line:
/// this binary is spawned by an editor, not typed at a prompt.
const USAGE: &str = "usage: lucisv-server [--verbose] [--stdio]";
fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
// Before the transport: an argument we do not understand means the client
// asked for something we are not doing, and answering LSP anyway would
// hide that for the whole session.
let verbose = match verbose_flag(std::env::args().skip(1)) {
Ok(verbose) => verbose,
Err(unknown) => {
eprintln!("error: unknown option: {unknown}");
eprintln!("{USAGE}");
std::process::exit(2);
}
};
let (connection, io_threads) = Connection::stdio();
let (id, params) = connection.initialize_start()?;
@@ -72,6 +106,11 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
// capabilities have no field for it and drop it on the floor — see
// `ranges_formatting_support`.
let ranges_formatting = ranges_formatting_support(&params);
// Read from the raw params for the same reason, and because it is not a
// capability at all: `initializationOptions` is whatever the client's
// extension put there.
let storage = storage_path(&params);
let hierarchy_view = hierarchy_view_support(&params);
// A client that sends params we cannot read still gets a server; every
// field we want is optional anyway.
let params: InitializeParams = serde_json::from_value(params).unwrap_or_default();
@@ -85,14 +124,50 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
code_lens_refresh: code_lens_refresh_support(&params),
show_document: show_document_support(&params),
configuration: configuration_support(&params),
token_server_cancel: token_server_cancel_support(&params),
hierarchy_view,
};
connection.initialize_finish(id, initialize_value(ranges_formatting)?)?;
Server::new(connection, roots, abilities).run()?;
// The message loop parses every buffer it is handed, so it does not run
// on the main thread: that stack is whatever the OS and `ulimit -s` left
// it, and the parser's nesting limit only turns over-deep input into a
// diagnostic above `PARSE_STACK_SIZE` (below it the overflow aborts the
// whole server, taking the editor session with it). Nothing else here
// parses — `lsp-server`'s reader and writer threads move JSON, and the
// forwarder in `Server::queue` moves messages.
std::thread::Builder::new()
.name("lucisv-main".to_string())
.stack_size(PARSE_STACK_SIZE)
.spawn(move || Server::new(connection, roots, abilities, storage, verbose).run())?
.join()
.map_err(|_| "the server thread panicked")??;
io_threads.join()?;
Ok(())
}
/// Whether the arguments ask for verbose timing, or the first argument this
/// binary does not take.
///
/// Refused rather than ignored: a client that spawns `lucisv-server --verbos`
/// would otherwise get a whole session of silence and no way to tell it from a
/// flag that does not work. Repeating the flag is not an error — it says the
/// same thing twice — and no argument at all is the spawn every editor has
/// always used.
fn verbose_flag(args: impl Iterator<Item = String>) -> Result<bool, String> {
let mut verbose = false;
for arg in args {
if arg == STDIO {
continue;
}
if arg != VERBOSE {
return Err(arg);
}
verbose = true;
}
Ok(verbose)
}
/// What the server tells the client it can do. Nothing is advertised that is
/// not implemented: a capability an editor discovers to be a lie is worse than
/// one it never had.
@@ -204,14 +279,24 @@ fn capabilities() -> ServerCapabilities {
// `codeLens/resolve` to do, which is said out loud rather than left
// unset. See `docs/features/code-lens/README.md`.
code_lens_provider: Some(CodeLensOptions { resolve_provider: Some(false) }),
// Module hinting. No trigger characters: an identifier being typed is
// what asks for these, and the handler declines every position that is
// not a module item, so an unprompted request costs a token scan.
// Names, templates and — since 2026-09-02 — members. An identifier
// being typed asks for the first two on its own, with no trigger
// needed; a **member** list has no identifier to be asked by, because
// the user has typed a separator and nothing after it yet. So `.` and
// `:` are advertised, and nothing else: they are the two bytes that
// can turn the cursor into a member position.
//
// The trigger is a *prompt*, never an instruction. The handler reads
// the buffer and decides — `server.rs` discards the request's
// `context` — so a `.` in a connection list, a lone `:` of a case
// item and a `::` after nothing readable all answer exactly what they
// would have answered had the user pressed the key themselves. See
// `docs/features/member-completion/README.md`.
completion_provider: Some(CompletionOptions {
// Every item is returned complete — skeleton, documentation and
// all — so there is nothing for `completionItem/resolve` to do.
resolve_provider: None,
trigger_characters: None,
trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
all_commit_characters: None,
work_done_progress_options: WorkDoneProgressOptions::default(),
completion_item: None,
@@ -306,10 +391,11 @@ fn capabilities() -> ServerCapabilities {
}
}
/// Every command this server executes: the three port refactorings, and the
/// jump the code lens hangs off.
/// Every command this server executes: the three port refactorings, the
/// instantiation skeleton, and the jump the code lens hangs off.
fn commands() -> Vec<String> {
let mut commands = ports::commands();
commands.extend(instantiate::commands());
commands.extend(lens::commands());
commands
}
@@ -374,6 +460,29 @@ fn ranges_formatting_support(params: &serde_json::Value) -> bool {
params["capabilities"]["textDocument"]["rangeFormatting"]["rangesSupport"] == true
}
/// The folder the client set aside for this workspace's server state —
/// `initializationOptions.storagePath`, which the VS Code extension fills in
/// with `context.storageUri`.
///
/// The persistent index cache goes here when there is one: it is
/// per-workspace, the editor cleans it up when the workspace is forgotten,
/// and it needs no guess about where this platform keeps caches. A client
/// that sends nothing — every client but ours, and ours before this — leaves
/// the OS cache directory to decide
/// (`docs/features/index-persistence/README.md`). A blank value counts as
/// unset, the same reading `lucisv.serverPath` gives a blank setting.
fn storage_path(params: &serde_json::Value) -> Option<PathBuf> {
let path = params["initializationOptions"]["storagePath"].as_str()?;
(!path.trim().is_empty()).then(|| PathBuf::from(path))
}
/// Whether this client hosts lucisv's custom hierarchy view and therefore
/// wants invalidation notifications for it. The snapshot request itself is
/// always served; this gate prevents unsolicited traffic to other LSP clients.
fn hierarchy_view_support(params: &serde_json::Value) -> bool {
params["initializationOptions"]["hierarchyView"] == true
}
/// Whether the client can expand `${1:x}` tabstops in a completion item.
///
/// A client that did not say so gets the skeleton as plain text: a literal
@@ -404,6 +513,26 @@ fn apply_edit_support(params: &InitializeParams) -> bool {
.unwrap_or(false)
}
/// Whether the client lets the *server* cancel a semantic-tokens request —
/// `textDocument.semanticTokens.serverCancelSupport`.
///
/// The large-file fast path declines `semanticTokens/full`, and this decides
/// with which error code: `ServerCancelled` for a client that says it
/// understands one (the spec restricts that code to requests "that explicitly
/// support being server cancellable", and this capability is how a client
/// says so), `ContentModified` for one that does not. Both leave
/// `vscode-languageclient` throwing a `CancellationError`, which is what keeps
/// the range provider alive — see
/// `docs/features/large-file-mode/README.md`.
fn token_server_cancel_support(params: &InitializeParams) -> bool {
params.capabilities.text_document.as_ref().is_some_and(|text_document| {
text_document
.semantic_tokens
.as_ref()
.is_some_and(|tokens| tokens.server_cancel_support == Some(true))
})
}
/// Whether the client pulls diagnostics (LSP 3.17).
///
/// Sending the capability at all is what says so; its two fields are about
@@ -495,6 +624,68 @@ fn workspace_roots(params: &InitializeParams) -> Vec<PathBuf> {
mod tests {
use super::*;
/// [`verbose_flag`] over what a spawn would really hand it.
fn args(args: &[&str]) -> Result<bool, String> {
verbose_flag(args.iter().map(|arg| (*arg).to_string()))
}
#[test]
fn no_arguments_is_the_spawn_every_editor_has_always_used() {
assert_eq!(args(&[]), Ok(false), "and it must never become verbose by accident");
}
#[test]
fn the_one_flag_is_the_one_spelling() {
assert_eq!(args(&["--verbose"]), Ok(true));
// Twice says the same thing twice.
assert_eq!(args(&["--verbose", "--verbose"]), Ok(true));
// Every near miss is refused, `-v` included: one spelling, so a client
// that guessed is told rather than silently given nothing.
for wrong in ["-v", "--Verbose", "--verbos", "verbose", "--verbose=true", "--help"] {
assert_eq!(args(&[wrong]), Err(wrong.to_string()), "{wrong} is not the flag");
}
}
#[test]
fn stdio_is_accepted_as_the_statement_of_fact_it_is() {
// `vscode-languageclient` appends `--stdio` for TransportKind.stdio —
// the spawn every real VS Code session actually makes. Rejecting it
// crashed the extension five times and gave up (lead hotfix,
// 2026-08-29); it must parse in every combination and change nothing.
assert_eq!(args(&["--stdio"]), Ok(false));
assert_eq!(args(&["--stdio", "--verbose"]), Ok(true));
assert_eq!(args(&["--verbose", "--stdio"]), Ok(true));
assert_eq!(args(&["--stdio", "--stdio"]), Ok(false));
// And a near miss of IT is still refused.
assert_eq!(args(&["--Stdio"]), Err("--Stdio".to_string()));
}
#[test]
fn the_first_argument_we_do_not_take_is_the_one_reported() {
// Named, so the message can say which word was wrong — the whole
// reason this refuses instead of ignoring.
assert_eq!(args(&["--verbose", "--colour"]), Err("--colour".to_string()));
assert_eq!(args(&["--colour", "--verbose"]), Err("--colour".to_string()));
assert_eq!(args(&["/some/file.sv"]), Err("/some/file.sv".to_string()));
}
#[test]
fn the_extension_ships_the_flag_off_which_is_what_no_argument_means() {
// The two halves of the contract live in different languages: the
// manifest's default decides whether `extension.js` puts `--verbose`
// in the spawn arguments, and `verbose_flag` decides what the server
// does with the arguments it gets. They must agree that the shipped
// state is off.
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../editors/vscode/package.json");
let text = std::fs::read_to_string(&path).expect("the extension manifest");
let manifest: serde_json::Value = serde_json::from_str(&text).expect("valid json");
let verbose = &manifest["contributes"]["configuration"]["properties"]["lucisv.verbose"];
assert_eq!(verbose["type"], serde_json::json!("boolean"), "{verbose:#?}");
assert_eq!(verbose["default"], serde_json::json!(false), "{verbose:#?}");
assert_eq!(args(&[]), Ok(false), "which is what the server does with no argument");
}
#[test]
fn every_advertised_capability_is_implemented() {
let caps = capabilities();
@@ -677,6 +868,20 @@ mod tests {
assert!(!ranges_formatting_support(&serde_json::Value::Null));
}
#[test]
fn hierarchy_notifications_are_an_explicit_initialization_option() {
let saying = serde_json::json!({ "initializationOptions": { "hierarchyView": true } });
assert!(hierarchy_view_support(&saying));
for silent in [
serde_json::json!({}),
serde_json::json!({ "initializationOptions": { "hierarchyView": false } }),
serde_json::json!({ "initializationOptions": { "hierarchyView": "yes" } }),
serde_json::Value::Null,
] {
assert!(!hierarchy_view_support(&silent), "{silent:#?}");
}
}
#[test]
fn a_client_that_did_not_ask_sees_the_capability_exactly_as_it_always_was() {
// The gate's whole point: every client that shipped before this round
@@ -873,7 +1078,16 @@ mod tests {
fn completion_resolves_nothing_because_every_item_is_complete() {
let options = capabilities().completion_provider.expect("completion");
assert_eq!(options.resolve_provider, None);
assert_eq!(options.trigger_characters, None);
}
#[test]
fn completion_triggers_on_the_two_separators_that_start_a_member_list() {
let options = capabilities().completion_provider.expect("completion");
assert_eq!(
options.trigger_characters,
Some(vec![".".to_string(), ":".to_string()]),
"a member list has no identifier to ask for it, so the separator must",
);
}
#[test]
@@ -940,9 +1154,14 @@ mod tests {
fn every_advertised_command_is_one_the_server_runs() {
let options = capabilities().execute_command_provider.expect("commands");
assert_eq!(options.commands, commands());
// Both halves of the list, so neither can go missing quietly: a lens
// whose command is not advertised is a lens no client will run.
for command in ports::commands().iter().chain(lens::commands().iter()) {
// Every half of the list, so none can go missing quietly: a lens
// whose command is not advertised is a lens no client will run, and
// an unadvertised `lucisv.instantiate` is the whole of §2.9-19 gone.
for command in ports::commands()
.iter()
.chain(instantiate::commands().iter())
.chain(lens::commands().iter())
{
assert!(options.commands.contains(command), "{command} is not advertised");
}
assert!(
File diff suppressed because it is too large. Load diff
+77 -8
View File
@@ -26,7 +26,7 @@ use vlog_parser::token::{Token, TokenKind};
use crate::format;
use crate::pairs;
use crate::state::Document;
use crate::state::{first_token_from, first_token_reaching, Document};
/// The character the client is told to trigger on. A newline is the one
/// keystroke that opens a line whose indentation nobody has chosen yet.
@@ -71,8 +71,14 @@ fn statement_edit(doc: &Document, position: Position, config: &Config) -> Option
let offset = doc.positions().offset(position);
// The character the client named has to actually be there, and it has to
// be a `;` the lexer sees: one inside a string or a comment ends no
// statement, and re-laying-out its line would be a guess.
let typed = doc.tokens.iter().find(|token| token.span.end == offset)?;
// statement, and re-laying-out its line would be a guess. A token that
// ends exactly at `offset` is the first one that *reaches* it — everything
// before ends earlier, everything after ends later — so a binary search
// finds what the sweep this replaced found.
let typed = doc
.tokens
.get(first_token_reaching(&doc.tokens, offset))
.filter(|t| t.span.end == offset)?;
if !typed.is_sym(SEMICOLON) {
return None;
}
@@ -130,7 +136,17 @@ fn indent_edit(doc: &Document, position: Position, indent_width: usize) -> Optio
/// whatever the user wrote is what a whole-file run emits, so this model has no
/// opinion there. `constraint c { ... }` needs no entry — its body is behind a
/// brace, and any open bracket already silences this.
const OPAQUE: &[&str] = &["covergroup", "property", "sequence"];
///
/// `covergroup` **left** this list in the `covergroup-bodies` round: its items
/// are laid out from a real tree now, at one indent from the header, which is
/// exactly what an ordinary block frame computes. Its bins bodies are behind a
/// `{`, so they need no entry either, for the reason a constraint's do not.
/// The five vendor/formal blocks joined the list in `vendor-formal-grammar`
/// (2026-09-02): a specify path, a UDP truth table, a checker body and a
/// config's library clauses are all emitted byte-for-byte, so this model has
/// no opinion inside any of them either.
const OPAQUE: &[&str] =
&["property", "sequence", "specify", "primitive", "table", "checker", "config"];
/// Keywords whose statement body follows them directly, after an optional
/// `@(...)` event control or `#delay`.
@@ -264,9 +280,12 @@ fn inside_a_comment(token: &Token, at: u32) -> bool {
/// line the user has just opened has none.
fn first_on_line(doc: &Document, content: u32) -> Option<&Token> {
let line = doc.line_index.line_col(content).0;
doc.tokens
// Every token before this index starts before `content`, so none of them
// could have satisfied the sweep this replaced; within the tail the sweep's
// remaining condition is the `Eof` test alone.
doc.tokens[first_token_from(&doc.tokens, content)..]
.iter()
.find(|token| token.kind != TokenKind::Eof && token.span.start >= content)
.find(|token| token.kind != TokenKind::Eof)
.filter(|token| doc.line_index.line_col(token.span.start).0 == line)
}
@@ -646,6 +665,43 @@ mod tests {
f(ws.document(&uri).expect("open"))
}
/// The `;` handler used to sweep the token vector for the token ending at
/// the cursor. Every byte of a buffer full of touching tokens must still
/// name the same token — or no token, where the sweep found none.
#[test]
fn the_token_ending_at_the_cursor_is_the_one_the_sweep_returned() {
let text = crate::state::mixed_buffer(20);
with(&text, |doc| {
for offset in 0..=text.len() as u32 {
let swept = doc.tokens.iter().find(|token| token.span.end == offset);
let searched = doc
.tokens
.get(first_token_reaching(&doc.tokens, offset))
.filter(|t| t.span.end == offset);
assert_eq!(swept.map(|t| t.span), searched.map(|t| t.span), "at offset {offset}");
}
});
}
/// The same, for the indent handler's "first token at or after this byte":
/// [`first_on_line`] is compared against the sweep it was written as.
#[test]
fn the_first_token_on_a_line_is_the_one_the_sweep_returned() {
let text = crate::state::mixed_buffer(20);
with(&text, |doc| {
for content in 0..=text.len() as u32 {
let line = doc.line_index.line_col(content).0;
let swept = doc
.tokens
.iter()
.find(|token| token.kind != TokenKind::Eof && token.span.start >= content)
.filter(|token| doc.line_index.line_col(token.span.start).0 == line);
let searched = first_on_line(doc, content);
assert_eq!(swept.map(|t| t.span), searched.map(|t| t.span), "at byte {content}");
}
});
}
fn config(indent_width: usize) -> Config {
Config { indent_width, ..Config::default() }
}
@@ -840,12 +896,25 @@ mod tests {
#[test]
fn a_verbatim_scope_has_no_indent_this_model_can_name() {
// A covergroup's body is emitted byte-for-byte, so whatever the user
// A property's body is emitted byte-for-byte, so whatever the user
// wrote there is already what a whole-file run produces.
let text = "module m;\n covergroup cg;\n\n cp: coverpoint x;\n endgroup\nendmodule\n";
let text = "module m;\n property p;\n\n a |-> b;\n endproperty\nendmodule\n";
assert_eq!(indent(text, 2), None);
}
#[test]
fn a_covergroup_body_indents_like_any_other_block() {
// Since `covergroup-bodies` its items are laid out from a real tree,
// so the model has an answer where it used to have none.
let text = "module m;\n covergroup cg;\n\n cp: coverpoint x;\n endgroup\nendmodule\n";
assert_eq!(indent(text, 2).as_deref(), Some(" "));
// A bin body is behind a `{`, where an open bracket silences the
// model exactly as it does inside a constraint.
let text =
"module m;\n covergroup cg;\n cp: coverpoint x {\n\n }\n endgroup\nendmodule\n";
assert_eq!(indent(text, 3), None);
}
#[test]
fn an_assertion_statement_is_silent_for_as_long_as_it_runs() {
// `assert (c) pass; else fail;` is verbatim, and its `else` runs past
+35
View File
@@ -48,6 +48,13 @@ const RULES: &[Rule] = &[
Rule { open: "covergroup", close: &["endgroup"] },
Rule { open: "specify", close: &["endspecify"] },
Rule { open: "primitive", close: &["endprimitive"] },
// `vendor-formal-grammar`, 2026-09-02. `table`/`endtable` could not be a
// rule before this round for a reason worth writing down: a rule only
// fires on a `TokenKind::Keyword`, and `checker`/`config` were not
// keywords — `table` was, so its row is simply the one nobody had added.
Rule { open: "table", close: &["endtable"] },
Rule { open: "checker", close: &["endchecker"] },
Rule { open: "config", close: &["endconfig"] },
];
/// Keywords that turn the rest of their statement into a declaration without a
@@ -599,6 +606,34 @@ mod tests {
scopes(text).unmatched_open.iter().map(|u| u.keyword).collect()
}
#[test]
fn the_vendor_and_formal_blocks_are_scopes() {
// `vendor-formal-grammar`, 2026-09-02. A rule only fires on a
// `TokenKind::Keyword`, so `checker` and `config` became matchable
// the moment the lexer reserved them; `table` was a keyword all along
// and simply had no row.
assert_eq!(
matched("primitive p (q, a);\n table\n 0 : 1;\n endtable\nendprimitive\n"),
["primitive..endprimitive", "table..endtable"]
);
assert_eq!(
matched("checker c (logic a);\n checker d (logic b);\n endchecker\nendchecker\n"),
["checker..endchecker", "checker..endchecker"]
);
assert_eq!(matched("config cfg;\n design work.top;\nendconfig\n"), ["config..endconfig"]);
assert_eq!(
matched("module m;\n specify\n endspecify\nendmodule\n"),
["module..endmodule", "specify..endspecify"]
);
}
#[test]
fn an_unclosed_vendor_block_is_reported_against_its_own_keyword() {
assert_eq!(unclosed("checker c (logic a);\n"), ["checker"]);
assert_eq!(unclosed("config cfg;\n"), ["config"]);
assert_eq!(orphan_closers("endchecker\n"), ["endchecker"]);
}
/// The keyword of every closer that closed nothing.
fn orphan_closers(text: &str) -> Vec<&'static str> {
scopes(text).unmatched_close.iter().map(|u| u.keyword).collect()
File diff suppressed because it is too large. Load diff
+462 -10
View File
@@ -17,7 +17,7 @@
#![allow(clippy::mutable_key_type)]
use std::collections::HashMap;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use lsp_types::{
CodeAction, CodeActionKind, CodeActionOrCommand, Position, TextEdit, Uri, WorkspaceEdit,
@@ -51,14 +51,17 @@ pub fn commands() -> Vec<String> {
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() };
// A code-action request arrives on every cursor move, and `sources()`
// reads the whole in-scope file set from disk. The engine's one-file
// question answers "there is nothing here" for almost every position
// without any of that.
if !vlog_refactor::may_have_port_action(&doc.text, offset) {
// A code-action request arrives on every cursor move, so neither half of
// this may walk the workspace. The engine's one-file question answers
// "there is nothing here" for almost every position — and where it does
// find something, it says which module, so the files handed to the engine
// are that module's own fan-out rather than every file in scope
// (`Workspace::module_sources`).
let modules = vlog_refactor::port_action_modules(&doc.text, offset);
if modules.is_empty() {
return Vec::new();
}
let sources = ws.sources();
let sources = ws.module_sources(&path, &modules);
vlog_refactor::port_actions(&sources, &path, offset)
.into_iter()
.filter_map(|action| {
@@ -84,7 +87,6 @@ pub fn execute(
command: &str,
arguments: &[Value],
) -> Result<(WorkspaceEdit, Vec<String>), String> {
let sources = ws.sources();
let refactoring = match command {
ADD_PORT => {
let (_, path) = target(ws, arguments.first())?;
@@ -93,10 +95,12 @@ pub fn execute(
})?;
match module_argument(arguments.get(1)) {
ModuleArgument::Name(name) => {
let sources = ws.module_sources(&path, std::slice::from_ref(&name));
vlog_refactor::add_port(&sources, ModuleRef::Name(&name), decl)?
}
ModuleArgument::Position(position) => {
let offset = offset_of(ws, arguments.first(), position)?;
let sources = sources_at(ws, &path, offset);
vlog_refactor::add_port(&sources, ModuleRef::At { file: &path, offset }, decl)?
}
ModuleArgument::Missing => {
@@ -109,18 +113,43 @@ pub fn execute(
REMOVE_PORT => {
let (_, path) = target(ws, arguments.first())?;
let offset = position_argument(ws, arguments, REMOVE_PORT)?;
let sources = sources_at(ws, &path, offset);
vlog_refactor::remove_port(&sources, &path, offset)?
}
PROPAGATE_PORTS => {
let (_, path) = target(ws, arguments.first())?;
let offset = position_argument(ws, arguments, PROPAGATE_PORTS)?;
let sources = sources_at(ws, &path, offset);
vlog_refactor::propagate_ports(&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::instantiate::INSTANTIATE => {
return crate::instantiate::execute(ws, arguments).map(|edit| (edit, Vec::new()))
}
other => return Err(format!("`{other}` is not a lucisv command.")),
};
Ok((workspace_edit(ws, &refactoring)?, refactoring.warnings))
}
/// The files a port refactoring **at a position** reads: the fan-out of every
/// module that position could name.
///
/// A command's position is looser than a code action's — `lucisv.addPort`
/// takes one anywhere in the module it adds to — so the module the cursor sits
/// *inside* is asked for as well as the ones its port element or its
/// instantiation names. Both questions are the engine's own
/// (`vlog_refactor`), so the set cannot drift from what the engine will then
/// go looking for.
fn sources_at(ws: &Workspace, path: &Path, offset: u32) -> Vec<(PathBuf, String)> {
let Some(text) = ws.text_of(path) else { return ws.module_sources(path, &[]) };
let mut modules = vlog_refactor::port_action_modules(&text, offset);
modules.extend(vlog_refactor::enclosing_module(&text, offset));
ws.module_sources(path, &modules)
}
/// What the second argument of `lucisv.addPort` said.
enum ModuleArgument {
Name(String),
@@ -244,7 +273,7 @@ mod tests {
let sub = tree.write("sub.sv", SUB);
let top = tree.write("top.sv", TOP);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let top_uri = path_to_uri(&top).expect("uri");
let sub_uri = path_to_uri(&sub).expect("uri");
ws.set_document(top_uri.clone(), TOP.to_string());
@@ -323,7 +352,7 @@ mod tests {
tree.write("sub.sv", SUB);
let top = tree.write("top.sv", text);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
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 arguments = vec![
@@ -357,6 +386,429 @@ mod tests {
assert_eq!(edits_for(edit, &top_uri).len(), 2, "the connection and its comma");
}
// ------------------------------------------------------------------
// the answer is the whole workspace's answer, computed over a subset
// ------------------------------------------------------------------
/// One action's title and the edits it carries, per file in path order.
type Shape = (String, Vec<(String, Vec<String>)>);
/// A code action as a comparable value: its title and every edit it
/// carries, per file in path order — the whole of what a client receives.
/// `WorkspaceEdit.changes` is a `HashMap`, so it is sorted here rather
/// than compared as it is stored.
fn shape(actions: &[CodeActionOrCommand]) -> Vec<Shape> {
actions
.iter()
.map(|action| {
let CodeActionOrCommand::CodeAction(action) = action else {
return ("a command".to_string(), Vec::new());
};
let mut changes: Vec<(String, Vec<String>)> = action
.edit
.as_ref()
.and_then(|edit| edit.changes.as_ref())
.map(|changes| {
changes
.iter()
.map(|(uri, edits)| {
let edits = edits
.iter()
.map(|edit| format!("{:?}{}", edit.range, edit.new_text))
.collect();
(uri.as_str().to_string(), edits)
})
.collect()
})
.unwrap_or_default();
changes.sort();
(action.title.clone(), changes)
})
.collect()
}
/// What `code_actions` used to compute: the same engine call over every
/// in-scope file. The equivalence tests below assert the new answer
/// against this one rather than against a transcription of it.
fn whole_workspace_at(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<CodeActionOrCommand> {
let doc = ws.document(uri).expect("an open document");
let path = doc.path.clone().expect("a saved file");
let sources = ws.sources();
vlog_refactor::port_actions(&sources, &path, offset)
.into_iter()
.filter_map(|action| {
let edit = workspace_edit(ws, &action.edit).ok()?;
Some(CodeActionOrCommand::CodeAction(CodeAction {
title: action.title,
kind: Some(CodeActionKind::new(REFACTOR_PORTS)),
edit: Some(edit),
..Default::default()
}))
})
.collect()
}
/// A workspace of `noise` files that have nothing to do with `sub`, plus
/// `sub.sv` and three files that instantiate it.
fn crowded(tree: &Tree, noise: usize) -> Workspace {
tree.write("sub.sv", SUB);
for n in 0..3 {
tree.write(
&format!("top{n}.sv"),
&format!(
"module top{n};\n logic c, r;\n sub u_sub (.clk(c), .rst(r));\nendmodule\n"
),
);
}
for n in 0..noise {
tree.write(
&format!("noise{n}.sv"),
&format!("module noise{n};\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()]);
ws
}
#[test]
fn a_code_action_answers_what_the_whole_workspace_would() {
let tree = Tree::new("equivalence");
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 subset = code_actions(&ws, &sub_uri, offset);
assert_eq!(subset.len(), 1, "{subset:#?}");
let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") };
assert_eq!(action.title, "lucisv: remove port `rst` (updates 3 instantiations)");
assert_eq!(
shape(&subset),
shape(&whole_workspace_at(&ws, &sub_uri, offset)),
"the subset must answer exactly what every file would have"
);
}
#[test]
fn the_files_a_code_action_reads_are_the_modules_own_fan_out() {
let tree = Tree::new("fanout");
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");
let read = ws.module_sources(&sub, &["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", "top1.sv", "top2.sv"], "and not one noise file");
}
#[test]
fn an_unsaved_buffer_contributes_the_instantiation_the_index_has_not_seen() {
let tree = Tree::new("unsaved");
let mut ws = crowded(&tree, 20);
// A file the index knows as instantiating nothing, whose buffer now
// instantiates `sub`. No save, so no edge in the index.
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());
assert!(
ws.index()
.instantiations_of("sub")
.iter()
.all(|edge| ws.index().path(edge.file) != Some(extra.as_path())),
"the index has not seen the unsaved instantiation"
);
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());
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
let subset = code_actions(&ws, &sub_uri, offset);
let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") };
assert_eq!(action.title, "lucisv: remove port `rst` (updates 4 instantiations)");
let edit = action.edit.as_ref().expect("an edit");
assert_eq!(edits_for(edit, &extra_uri).len(), 2, "the unsaved buffer is disconnected too");
assert_eq!(shape(&subset), shape(&whole_workspace_at(&ws, &sub_uri, offset)));
}
#[test]
fn a_module_declared_twice_is_refused_through_the_subset_as_well() {
let tree = Tree::new("ambiguous");
let mut ws = crowded(&tree, 10);
// A second declaration of `sub`, in a file nothing else names.
tree.write("clone.sv", SUB);
ws.rebuild_index();
assert_eq!(ws.index().units("sub").len(), 2, "two declarations");
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());
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
// Both definers are in the set, so the engine sees the ambiguity and
// refuses — which is no action, exactly as over the whole workspace.
assert!(ws
.module_sources(&sub, &["sub".to_string()])
.iter()
.any(|(path, _)| path.ends_with("clone.sv")));
assert!(code_actions(&ws, &sub_uri, offset).is_empty());
assert!(whole_workspace_at(&ws, &sub_uri, offset).is_empty());
}
#[test]
fn a_command_computes_over_the_subset_and_answers_the_same() {
let tree = Tree::new("command");
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());
let arguments = vec![
serde_json::to_value(&sub_uri).expect("uri"),
Value::String("sub".into()),
Value::String("input logic cfg".into()),
];
let (edit, warnings) = execute(&ws, ADD_PORT, &arguments).expect("adds");
let whole =
vlog_refactor::add_port(&ws.sources(), ModuleRef::Name("sub"), "input logic cfg")
.expect("adds");
assert_eq!(warnings, whole.warnings);
assert_eq!(edit, workspace_edit(&ws, &whole).expect("an edit"));
assert_eq!(edit.changes.as_ref().expect("changes").len(), 4, "sub.sv and its three tops");
}
#[test]
fn qa_file_scope_instantiation_lands_in_the_subset() {
let tree = Tree::new("qa_filescope");
let mut ws = crowded(&tree, 20);
// A file-scope (owner-less) instantiation of `sub` — illegal SV, but
// a tolerant parse still produces an Instantiation item, and the old
// whole-workspace engine would still edit it (collect_instantiations
// walks tree.items directly). It records no InstantiationEdge (edges_of
// requires an owner), so only the references_to half of rung 3 can
// possibly find it.
let filescope_path = tree.write("filescope.sv", "sub u_fs (.clk(c), .rst(r));\n");
ws.rebuild_index();
assert!(
ws.index()
.instantiations_of("sub")
.iter()
.all(|edge| ws.index().path(edge.file) != Some(filescope_path.as_path())),
"file-scope site records no edge, as documented"
);
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());
let read = ws.module_sources(&sub, &["sub".to_string()]);
let names: Vec<String> = read
.iter()
.map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string())
.collect();
assert!(
names.contains(&"filescope.sv".to_string()),
"file-scope instantiation site must be in the subset: {names:?}"
);
// And the whole-workspace engine really would have edited it, so
// omitting it from the subset would be a real divergence.
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
let whole = whole_workspace_at(&ws, &sub_uri, offset);
let CodeActionOrCommand::CodeAction(action) = &whole[0] else { panic!("an action") };
let edit = action.edit.as_ref().expect("an edit");
let fs_uri = path_to_uri(&filescope_path).expect("uri");
assert_eq!(
edits_for(edit, &fs_uri).len(),
2,
"the whole-workspace answer edits the file-scope site"
);
let subset = code_actions(&ws, &sub_uri, offset);
assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly");
}
#[test]
fn qa_a_duplicate_definer_unindexed_on_disk_is_a_stale_answer_not_a_corruption() {
// The subset builder trusts the index for rungs 2/3, so a file that
// changed on disk with nothing telling the server (no rebuild_index,
// no didChange) is invisible to it — unlike the old `sources()` path,
// which re-reads the directory fresh every call. Attack: write a
// *second* definer of `sub` straight to disk, do NOT reindex, and
// fire a code action. Judged against invariant 1 (never corrupt), not
// against freshness: an answer that goes stale (or a refusal) is
// fine; an edit that is not internally verified would not be.
let tree = Tree::new("qa_stale_dup");
let mut ws = crowded(&tree, 10);
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());
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
// Sanity: before the duplicate exists anywhere, the subset offers the
// action normally.
assert_eq!(code_actions(&ws, &sub_uri, offset).len(), 1);
// Write a duplicate declaration straight to disk, bypassing the
// server entirely (no rebuild_index, no set_document for this path).
tree.write("dupe.sv", SUB);
// The index still knows only one definer, so the subset the server
// computes is unaware of the ambiguity and still offers the action.
assert_eq!(ws.index().units("sub").len(), 1, "the index has not been told");
let subset = code_actions(&ws, &sub_uri, offset);
assert_eq!(subset.len(), 1, "stale, but not refused — the index has not seen dupe.sv");
// The critical assertion: whatever it produced must still be an
// honest, self-consistent, verified edit over the files it actually
// read — not corruption of a file it never looked at. `dupe.sv`
// itself must be untouched (never read, never in the edit) and the
// edit that *was* produced must still verify against what changed.
let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") };
let dupe_uri = path_to_uri(&tree.path.join("dupe.sv")).expect("uri");
let edit = action.edit.as_ref().expect("an edit");
assert!(
edit.changes.as_ref().is_none_or(|c| !c.contains_key(&dupe_uri)),
"the unindexed duplicate must not be touched: {edit:?}"
);
// Once the index is told (rebuild_index, exactly what the watcher
// does on a save it's told about), parity is restored: the subset
// now sees the duplicate and refuses, exactly like the whole
// workspace always would have.
ws.rebuild_index();
assert_eq!(ws.index().units("sub").len(), 2, "now indexed");
assert!(code_actions(&ws, &sub_uri, offset).is_empty(), "refuses once told");
}
#[test]
fn qa_generate_block_instantiation_lands_in_the_subset() {
let tree = Tree::new("qa_generate");
let mut ws = crowded(&tree, 20);
let gen_path = tree.write(
"gen.sv",
"module gen;\n genvar i;\n generate\n for (i = 0; i < 2; i = i + 1) begin : g\n logic c, r;\n sub u_g (.clk(c), .rst(r));\n end\n endgenerate\nendmodule\n",
);
ws.rebuild_index();
assert!(
ws.index()
.instantiations_of("sub")
.iter()
.any(|edge| ws.index().path(edge.file) == Some(gen_path.as_path())),
"the generate-for body instantiation is a real edge"
);
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());
let read = ws.module_sources(&sub, &["sub".to_string()]);
let names: Vec<String> = read
.iter()
.map(|(path, _)| path.file_name().expect("name").to_string_lossy().to_string())
.collect();
assert!(names.contains(&"gen.sv".to_string()), "{names:?}");
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
let subset = code_actions(&ws, &sub_uri, offset);
let whole = whole_workspace_at(&ws, &sub_uri, offset);
assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly");
}
#[test]
fn qa_escaped_module_name_instantiation_parity_with_whole_workspace() {
// Not a subset-specific question: does an escaped-identifier
// instantiation (`\sub$weird u1 (...)`) even resolve to the module it
// names, workspace-index-wise, so the subset builder's `units`/
// `instantiations_of`/`references_to` lookups have anything to find?
// Attacking whether the *subset* diverges from the *whole-workspace*
// answer here, not whether escaped identifiers work at all (a
// pre-existing question this round did not touch).
let tree = Tree::new("qa_escaped");
tree.write("esc.sv", "module esc;\n \\sub u_esc (.clk(c), .rst(r));\nendmodule\n");
let mut ws = crowded(&tree, 10);
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());
let offset = SUB.find("input logic rst").expect("rst") as u32 + 12;
let subset = code_actions(&ws, &sub_uri, offset);
let whole = whole_workspace_at(&ws, &sub_uri, offset);
// Whichever way the parser/binder treats the escaped identifier
// `\sub ` (as `sub`, or as a distinct name), the subset and the
// whole-workspace computation must agree either way.
assert_eq!(shape(&subset), shape(&whole), "subset must match whole-workspace exactly");
}
#[test]
fn qa_add_port_by_position_still_fans_out_to_instantiation_files() {
// `a_command_computes_over_the_subset_and_answers_the_same` (the
// dev's own equivalence test) drives `lucisv.addPort` with a
// *module-name* argument. The *Position* argument takes a completely
// different path to the module (`sources_at` → `port_action_modules`
// + `enclosing_module`, rather than `module_sources` fed the name
// directly) and is exactly the code action's own code path
// (`ModuleArgument::Position` mirrors `ModuleRef::At`). Confirm it
// still reaches every instantiating file, not just the declaring one.
let tree = Tree::new("qa_add_by_position");
let mut ws = crowded(&tree, 30);
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());
let arguments = vec![
serde_json::to_value(&sub_uri).expect("uri"),
serde_json::to_value(Position { line: 0, character: 8 }).expect("position"),
Value::String("input logic cfg".into()),
];
let (edit, warnings) = execute(&ws, ADD_PORT, &arguments).expect("adds");
assert_eq!(warnings.len(), 3, "one TODO warning per instantiating top: {warnings:?}");
let changes = edit.changes.as_ref().expect("changes");
assert_eq!(changes.len(), 4, "sub.sv and its three instantiating tops: {changes:?}");
for n in 0..3 {
let top_uri = path_to_uri(&tree.path.join(format!("top{n}.sv"))).expect("uri");
assert_eq!(edits_for(&edit, &top_uri).len(), 1, "top{n}.sv must gain the connection");
}
let whole =
vlog_refactor::add_port(&ws.sources(), ModuleRef::Name("sub"), "input logic cfg")
.expect("adds");
assert_eq!(edit, workspace_edit(&ws, &whole).expect("an edit"));
}
#[test]
fn qa_a_module_declared_only_in_an_unsaved_new_file_is_still_handled() {
// A module the index has never seen at all — not stale, genuinely
// absent, e.g. a brand-new buffer the user has not saved yet. Rung 2
// (`index.units`) has nothing; only rung 1 (the request's own file)
// can supply it. The cursor sits in that same new buffer, so rung 1
// must be enough on its own — and it must not panic or silently
// return no action just because the index is empty for this name.
let tree = Tree::new("qa_unsaved_new_module");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
assert!(ws.index().units("brandnew").is_empty(), "the index has never heard of it");
let text = "module brandnew (\n input logic a,\n input logic b\n);\nendmodule\n";
let new_path = tree.path.join("brandnew.sv"); // never written to disk
let new_uri = path_to_uri(&new_path).expect("uri");
ws.set_document(new_uri.clone(), text.to_string());
let offset = text.find("input logic b").expect("b") as u32 + 12;
let subset = code_actions(&ws, &new_uri, offset);
assert_eq!(subset.len(), 1, "{subset:#?}");
let CodeActionOrCommand::CodeAction(action) = &subset[0] else { panic!("an action") };
assert_eq!(action.title, "lucisv: remove port `b` (no instantiation in scope)");
assert_eq!(edits_for(action.edit.as_ref().expect("edit"), &new_uri).len(), 2);
}
#[test]
fn an_unknown_command_is_declined() {
let tree = Tree::new("unknown");
+637 -7
View File
@@ -24,10 +24,20 @@ use crate::uri::path_to_uri;
/// The identifier at `offset` and its current name, or the reason it cannot
/// be renamed. Returning the reason — rather than `null` — is what puts the
/// engine's sentence in the editor's rename box instead of a shrug.
///
/// Answered from the buffer's own analysis and the index alone: no file is
/// read, nothing is parsed. This request is what the rename key sends before
/// the rename box even opens, and reading the workspace for it froze the whole
/// server for 2.5–3.0 s on OpenTitan. Which refusals that costs — and which of
/// them `rename` then delivers instead — is the table in
/// `docs/features/refactor-rename/README.md`.
pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Result<PrepareRenameResponse, String> {
let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?;
let path = doc.path.clone().ok_or_else(|| UNSAVED.to_string())?;
let target = vlog_refactor::prepare_rename(&ws.sources(), &path, offset)?;
if doc.path.is_none() {
return Err(UNSAVED.to_string());
}
let target =
vlog_refactor::prepare_rename_here(&doc.semantics, &doc.external, ws.index(), offset)?;
Ok(PrepareRenameResponse::RangeWithPlaceholder {
range: doc.positions().range(target.range),
placeholder: target.name,
@@ -44,7 +54,16 @@ pub fn rename(
) -> Result<(WorkspaceEdit, Vec<String>), String> {
let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?;
let path = doc.path.clone().ok_or_else(|| UNSAVED.to_string())?;
let refactoring = vlog_refactor::rename(&ws.sources(), &path, offset, new_name)?;
// The name the cursor sits on, read off the buffer, is what the index is
// asked for the fan-out. No refusal is taken here: `vlog_refactor::rename`
// is the one voice that decides, and it decides over the files below. A
// cursor on nothing has no fan-out to ask for, so the whole scope goes —
// the engine will say so, and saying it is cheap either way.
let sources = match vlog_refactor::rename_name_at(&doc.semantics, offset) {
Some(name) => ws.rename_sources(&path, &name, Some(new_name)),
None => ws.sources(),
};
let refactoring = vlog_refactor::rename(&sources, &path, offset, new_name)?;
let mut changes: HashMap<Uri, Vec<TextEdit>> = HashMap::new();
for (path, edits) in &refactoring.edits {
@@ -80,7 +99,7 @@ const UNSAVED: &str = "lucisv can only rename inside a saved file.";
mod tests {
use super::*;
use std::fs;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::str::FromStr;
/// A scratch workspace root. Removed on drop.
@@ -122,7 +141,7 @@ mod tests {
tree.write("sub.sv", SUB);
let top = tree.write("top.sv", TOP);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
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)
@@ -194,7 +213,7 @@ mod tests {
let text = "module m;\n // é 🎉\n wire a;\n assign a = 1;\nendmodule\n";
let file = tree.write("m.sv", text);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&file).expect("uri");
ws.set_document(uri.clone(), text.to_string());
@@ -206,13 +225,624 @@ mod tests {
assert_eq!(edits[0].range.start.character, 7);
}
// ------------------------------------------------------------------
// The fan-out equivalence suite
// ------------------------------------------------------------------
//
// `rename` is handed the symbol's fan-out through the index instead of
// every in-scope file. A rename that edits fewer files than the truth is
// corruption (CLAUDE.md invariant 1), and a refusal the narrow set cannot
// reach is a refusal the user never sees — so every case below asks the
// engine the same question twice, over the subset and over the whole
// workspace, and asserts the two answers are the same bytes and the same
// sentences. The sufficiency argument they are the evidence for is in
// `docs/features/refactor-rename/README.md`.
/// The file set the server would hand `rename` for a cursor at `offset`.
fn fan_out(ws: &Workspace, path: &Path, offset: u32, new_name: &str) -> Vec<PathBuf> {
let doc = ws.document_for_path(path).expect("the request's file is open");
match vlog_refactor::rename_name_at(&doc.semantics, offset) {
Some(name) => ws.rename_sources(path, &name, Some(new_name)),
None => ws.sources(),
}
.into_iter()
.map(|(path, _)| path)
.collect()
}
/// Ask the engine over the fan-out and over the whole workspace, and
/// assert the two answers are indistinguishable. Returns the answer, so a
/// caller can also assert *what* it was.
fn same_answer(
ws: &Workspace,
path: &Path,
offset: u32,
new_name: &str,
) -> Result<vlog_refactor::RefactorEdit, String> {
let everything = ws.sources();
let doc = ws.document_for_path(path).expect("the request's file is open");
let subset = match vlog_refactor::rename_name_at(&doc.semantics, offset) {
Some(name) => ws.rename_sources(path, &name, Some(new_name)),
None => everything.clone(),
};
for (path, text) in &subset {
let found = everything.iter().find(|(held, _)| held == path);
assert_eq!(
found.map(|(_, text)| text),
Some(text),
"{} is in the fan-out with text the whole scope does not have",
path.display()
);
}
let whole = vlog_refactor::rename(&everything, path, offset, new_name);
let narrow = vlog_refactor::rename(&subset, path, offset, new_name);
match (&whole, &narrow) {
(Ok(whole), Ok(narrow)) => {
assert_eq!(whole.edits, narrow.edits, "the fan-out edited different bytes");
assert_eq!(whole.warnings, narrow.warnings, "the fan-out warned differently");
}
(Err(whole), Err(narrow)) => {
assert_eq!(whole, narrow, "the fan-out refused in different words");
}
(Ok(whole), Err(narrow)) => panic!(
"the fan-out invented a refusal: {narrow}, where the workspace edited {} files",
whole.file_count()
),
(Err(whole), Ok(narrow)) => panic!(
"the fan-out lost the refusal `{whole}` and edited {} files instead",
narrow.file_count()
),
}
narrow
}
/// A workspace of `files`, every one of them also opened as a buffer when
/// `open` names it, with the first named file's URI returned.
fn tree_with(tree: &Tree, files: &[(&str, &str)], open: &[&str]) -> (Workspace, Vec<PathBuf>) {
let paths: Vec<PathBuf> = files.iter().map(|(name, text)| tree.write(name, text)).collect();
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
for name in open {
let path = tree.path.join(name);
let text = fs::read_to_string(&path).expect("written above");
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri, text);
}
(ws, paths)
}
const MOD: &str = "module sub #(parameter int W = 1) (input logic clk, output logic q);\n wire local_net;\n assign q = clk & local_net;\nendmodule : sub\n";
const ONE: &str = "module one;\n logic c, d;\n sub u_a (.clk(c), .q(d));\nendmodule\n";
const TWO: &str =
"module two;\n logic c, d;\n sub #(.W(3)) u_b (.clk(c), .q(d));\nendmodule\n";
const GEN: &str = "module three;\n genvar i;\n generate\n for (i = 0; i < 2; i++) begin : lane\n sub u_c (.clk(1'b0), .q());\n end\n endgenerate\nendmodule\n";
const QUIET: &str = "module quiet;\n wire unrelated;\n assign unrelated = 1'b0;\nendmodule\n";
#[test]
fn the_fan_out_answers_a_cross_file_module_rename_exactly_as_the_workspace_does() {
let tree = Tree::new("fanout_module");
let files = [
("sub.sv", MOD),
("one.sv", ONE),
("two.sv", TWO),
("three.sv", GEN),
("quiet.sv", QUIET),
];
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
let path = tree.path.join("one.sv");
let at = at(ONE, "sub u_a");
let edit = same_answer(&ws, &path, at, "child").expect("renames");
assert_eq!(edit.file_count(), 4, "the declaration and the three files naming it");
// And the narrowing is real: the file that never spells the name is
// not read at all.
let fan = fan_out(&ws, &path, at, "child");
assert!(!fan.contains(&tree.path.join("quiet.sv")), "{fan:?}");
assert!(fan.contains(&tree.path.join("three.sv")), "the generate-block site: {fan:?}");
}
#[test]
fn the_fan_out_keeps_the_end_label_and_the_declaration_together() {
let tree = Tree::new("fanout_endlabel");
let (ws, _) = tree_with(&tree, &[("sub.sv", MOD), ("one.sv", ONE)], &["sub.sv"]);
let path = tree.path.join("sub.sv");
let edit = same_answer(&ws, &path, at(MOD, "sub #"), "child").expect("renames");
let own = edit.edits_for(&path);
assert_eq!(own.len(), 2, "the header name and the `endmodule : sub` label");
}
#[test]
fn the_fan_out_carries_a_port_rename_to_every_connection() {
let tree = Tree::new("fanout_port");
let files = [("sub.sv", MOD), ("one.sv", ONE), ("two.sv", TWO), ("quiet.sv", QUIET)];
let (ws, _) = tree_with(&tree, &files, &["sub.sv"]);
let path = tree.path.join("sub.sv");
let edit = same_answer(&ws, &path, at(MOD, "clk,"), "clock").expect("renames");
assert_eq!(edit.file_count(), 3, "the module and both files connecting `.clk`");
}
#[test]
fn the_fan_out_carries_a_package_member_rename_to_every_importer() {
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
const IMPORTER: &str =
"module reader;\n import cfg_pkg::*;\n localparam int D = DEPTH;\nendmodule\n";
const QUALIFIER: &str =
"module qualifier;\n localparam int D = cfg_pkg::DEPTH;\nendmodule\n";
let tree = Tree::new("fanout_pkg");
let files =
[("pkg.sv", PKG), ("reader.sv", IMPORTER), ("qual.sv", QUALIFIER), ("quiet.sv", QUIET)];
let (ws, _) = tree_with(&tree, &files, &["reader.sv"]);
let path = tree.path.join("reader.sv");
let edit = same_answer(&ws, &path, at(IMPORTER, "DEPTH;"), "SIZE").expect("renames");
assert_eq!(edit.file_count(), 3, "the package and both files reading it");
}
#[test]
fn the_fan_out_sees_a_reference_only_an_unsaved_buffer_has() {
let tree = Tree::new("fanout_unsaved");
// On disk `two.sv` says nothing about `sub`; the buffer instantiates
// it. The index has never seen the buffer's text.
let files = [("sub.sv", MOD), ("one.sv", ONE), ("two.sv", QUIET)];
let (mut ws, _) = tree_with(&tree, &files, &["one.sv"]);
let two = tree.path.join("two.sv");
ws.set_document(path_to_uri(&two).expect("uri"), TWO.to_string());
assert!(
ws.index().instantiations_of("sub").len() < 2,
"premise: the index has not seen the buffer's instantiation"
);
let path = tree.path.join("one.sv");
let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames");
assert!(!edit.edits_for(&two).is_empty(), "the unsaved instantiation is renamed too");
}
#[test]
fn the_fan_out_refuses_a_name_the_workspace_declares_twice_in_the_same_words() {
let tree = Tree::new("fanout_dup");
let files = [("sub.sv", MOD), ("copy.sv", MOD), ("one.sv", ONE)];
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
let path = tree.path.join("one.sv");
let refusal =
same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect_err("declared twice");
assert!(refusal.contains("more than one indexed file"), "{refusal}");
}
#[test]
fn the_fan_out_still_refuses_a_rename_that_would_capture_a_name_elsewhere() {
// `three.sv` names `sub`; `taken.sv` declares the module the rename
// wants to become. Renaming `sub` to `taken` makes every `sub` site
// ambiguous — a file the postings for `sub` alone would never name.
const TAKEN: &str = "module taken;\nendmodule\n";
const USES_TAKEN: &str = "module holder;\n taken u_t ();\nendmodule\n";
let tree = Tree::new("fanout_capture");
let files =
[("sub.sv", MOD), ("one.sv", ONE), ("taken.sv", TAKEN), ("uses.sv", USES_TAKEN)];
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
let path = tree.path.join("one.sv");
let refusal =
same_answer(&ws, &path, at(ONE, "sub u_a"), "taken").expect_err("would capture");
assert!(refusal.contains("would change what"), "{refusal}");
let fan = fan_out(&ws, &path, at(ONE, "sub u_a"), "taken");
assert!(fan.contains(&tree.path.join("uses.sv")), "the new name's own fan-out: {fan:?}");
}
/// The two `` `define`` warnings come from files the index's own define
/// tables name, so both survive the narrowing: a macro *called* the name,
/// and a macro whose **body** spells it, each in a file that has nothing
/// else to do with the symbol.
#[test]
fn the_fan_out_keeps_the_define_warnings_of_files_it_would_not_otherwise_read() {
const NAMED: &str = "`define sub 1\nmodule named_holder;\nendmodule\n";
const BODY: &str = "`define WRAP(x) sub x\nmodule body_holder;\n wire w;\nendmodule\n";
let tree = Tree::new("fanout_macro");
let files = [
("sub.sv", MOD),
("one.sv", ONE),
("named.sv", NAMED),
("body.svh", BODY),
("quiet.sv", QUIET),
];
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
let path = tree.path.join("one.sv");
let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames");
assert!(
edit.warnings.iter().any(|w| w.contains("is also a macro defined")),
"{:?}",
edit.warnings
);
assert!(
edit.warnings.iter().any(|w| w.contains("in the body of macro `WRAP`")),
"{:?}",
edit.warnings
);
let fan = fan_out(&ws, &path, at(ONE, "sub u_a"), "child");
assert!(fan.contains(&tree.path.join("named.sv")), "the macro's own name: {fan:?}");
assert!(fan.contains(&tree.path.join("body.svh")), "the macro's body: {fan:?}");
assert!(!fan.contains(&tree.path.join("quiet.sv")), "and nothing else: {fan:?}");
}
#[test]
fn every_file_the_workspace_rename_edits_is_in_the_fan_out() {
// The invariant-1 assertion, made directly rather than through an
// equality: whatever the whole workspace would rewrite, the narrow set
// must contain — otherwise a rename edits fewer files than the truth.
let tree = Tree::new("fanout_covers");
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
const IMPORTER: &str = "module reader;\n import cfg_pkg::*;\n localparam int D = DEPTH;\n sub u (.clk(1'b0), .q());\nendmodule\n";
let files = [
("sub.sv", MOD),
("one.sv", ONE),
("two.sv", TWO),
("three.sv", GEN),
("pkg.sv", PKG),
("reader.sv", IMPORTER),
("quiet.sv", QUIET),
];
let (ws, _) = tree_with(&tree, &files, &["reader.sv"]);
let path = tree.path.join("reader.sv");
let everything = ws.sources();
let text = fs::read_to_string(&path).expect("written");
for offset in 0..=text.len() as u32 {
let Ok(whole) = vlog_refactor::rename(&everything, &path, offset, "renamed_thing")
else {
continue;
};
let fan = fan_out(&ws, &path, offset, "renamed_thing");
for (edited, _) in &whole.edits {
assert!(
fan.contains(edited),
"byte {offset} renames {} and the fan-out does not hold it: {fan:?}",
edited.display()
);
}
let _ = same_answer(&ws, &path, offset, "renamed_thing");
}
}
/// QA, 2026-08-28 attack: an instantiation spelled with an escaped
/// identifier (`` \sub ``) is a *different* name from `sub` to
/// `vlog_semantic` today (a pre-existing simplification, noted in this
/// feature's own 2026-08-24 QA round for a declaration, not an
/// instantiation) — it resolves to nothing, so it is renamed by neither
/// path. The question this pins is narrower: does narrowing the file set
/// change that answer? It must not, since both paths call the identical
/// engine; the risk would be the fan-out *dropping* the file outright
/// while the whole-workspace run still watches it (`\sub` contains the
/// word `sub`, so `contains_word` — and hence `watched_files` — still
/// picks it up in the whole run). `same_answer` checks the observable
/// output only (edits, warnings, or refusal), which is what must agree.
#[test]
fn an_escaped_identifier_instantiation_does_not_break_fan_out_parity() {
const ESCAPED: &str = "module holder;\n \\sub u_weird (.clk(1'b0), .q());\nendmodule\n";
let tree = Tree::new("fanout_escaped");
let files = [("sub.sv", MOD), ("one.sv", ONE), ("escaped.sv", ESCAPED)];
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
let path = tree.path.join("one.sv");
let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames");
assert!(
edit.edits_for(&tree.path.join("escaped.sv")).is_empty(),
"the escaped spelling is a different name to vlog_semantic and must stay untouched"
);
}
/// QA, 2026-08-28 attack: a same-spelling but *different* symbol (a
/// module unit named `sub` vs. a port/member also named `sub` in an
/// unrelated module) must not cross-contaminate the fan-out — renaming
/// the unit must not touch the member's own declaration or its file.
#[test]
fn a_same_spelling_different_symbol_kind_is_not_captured_by_the_fan_out() {
const OTHER_MODULE_WITH_A_PORT_NAMED_SUB: &str =
"module other;\n wire sub;\n assign sub = 1'b0;\nendmodule\n";
let tree = Tree::new("fanout_same_spelling_different_symbol");
let files =
[("sub.sv", MOD), ("one.sv", ONE), ("other.sv", OTHER_MODULE_WITH_A_PORT_NAMED_SUB)];
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
let path = tree.path.join("one.sv");
let edit = same_answer(&ws, &path, at(ONE, "sub u_a"), "child").expect("renames");
assert!(
edit.edits_for(&tree.path.join("other.sv")).is_empty(),
"the unrelated wire named `sub` must not be touched: {:?}",
edit.edits_for(&tree.path.join("other.sv"))
);
// other.sv may legitimately be *watched* by the whole-word text
// search (it spells "sub"), but it must never be *edited* — checked
// above — nor must its own local wire's meaning change, which
// `same_answer`'s byte-identical edits/warnings assertion already
// confirmed by passing at all.
}
/// QA, 2026-08-28 attack: the escape hatch (refusal 10 / ambiguous
/// posting) must fire even when the ambiguity is on the **new** name,
/// discovered on the second spelling `fan_out_of` walks, not the first.
/// `Workspace::rename_sources` iterates `[name, new_name]` in that order
/// and bails to `sources()` on the first ambiguous hit — this attacks the
/// case where the *old* name's rung is completely unambiguous and only
/// the second iteration finds the problem, to check the early return
/// doesn't leak a partially-built (too-narrow) `wanted` set instead of
/// truly falling back to the whole scope.
#[test]
fn the_escape_hatch_fires_when_only_the_new_names_posting_is_ambiguous() {
const A: &str = "package taken_pkg;\n parameter int DEPTH = 1;\nendpackage\n";
const B: &str = "package taken_pkg;\n parameter int DEPTH = 2;\nendpackage\n";
const READER: &str =
"module reader;\n import taken_pkg::*;\n localparam int D = DEPTH;\nendmodule\n";
let tree = Tree::new("fanout_ambig_on_new_name");
let files =
[("sub.sv", MOD), ("one.sv", ONE), ("a.sv", A), ("b.sv", B), ("reader.sv", READER)];
let (ws, _) = tree_with(&tree, &files, &["one.sv"]);
let path = tree.path.join("one.sv");
let at = at(ONE, "sub u_a");
// `sub` (the old name) has an unambiguous, tiny fan-out on its own.
let fan = fan_out(&ws, &path, at, "taken_pkg");
assert_eq!(
fan.len(),
ws.sources().len(),
"the new name's own ambiguity must still hand back the whole scope: {fan:?}"
);
same_answer(&ws, &path, at, "taken_pkg").expect_err("ambiguous new name");
}
#[test]
fn an_ambiguously_referenced_declaration_falls_back_to_the_whole_scope() {
// Two files declare the *same* package, so `cfg_pkg::DEPTH` names
// either declaration equally. The index records that the declarations
// are ambiguously referenced but not which file does it, so the
// fan-out refuses to narrow at all — which is how the refusal
// survives.
const A: &str = "package cfg_pkg;\n parameter int DEPTH = 1;\nendpackage\n";
const B: &str = "package cfg_pkg;\n parameter int DEPTH = 2;\nendpackage\n";
const READER: &str =
"module reader;\n import cfg_pkg::*;\n localparam int D = DEPTH;\nendmodule\n";
let tree = Tree::new("fanout_ambig");
let files = [("a.sv", A), ("b.sv", B), ("reader.sv", READER), ("quiet.sv", QUIET)];
let (ws, _) = tree_with(&tree, &files, &["a.sv"]);
let path = tree.path.join("a.sv");
let at = at(A, "DEPTH =");
let fan = fan_out(&ws, &path, at, "SIZE");
assert_eq!(
fan.len(),
ws.sources().len(),
"an ambiguous posting hands back the whole scope: {fan:?}"
);
same_answer(&ws, &path, at, "SIZE").expect_err("ambiguous");
}
/// Found by QA on 2026-08-28 as a **lost refusal**, and closed by the
/// sixth rung the lead ruled for the same day; kept as the regression
/// test for it, now asserting parity rather than pinning the divergence.
///
/// A file whose only mention of the **new** name is a bare use that
/// resolves to nothing today — `import taken_pkg::*` of a package nobody
/// declares yet — declares nothing, references nothing under the *old*
/// name, instantiates nothing and defines no macro, so the first five
/// rungs of the fan-out cannot see it. The rename is exactly what gives
/// that import a meaning, which is what capture rule 12 refuses over, so
/// the narrow path used to answer `Ok` where the whole workspace refused
/// — a materially weaker answer, not a lost warning.
/// `WorkspaceIndex::files_spelling` is the rung that finds it: the
/// per-file records keep every external use under the name it spells,
/// including the ones that resolved to nothing.
#[test]
fn a_dangling_import_of_the_new_name_is_refused_by_both_paths() {
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
const STRAY_IMPORT: &str = "module strayer;\n import taken_pkg::*;\nendmodule\n";
let tree = Tree::new("fanout_dangling_import");
let files = [("pkg.sv", PKG), ("stray.sv", STRAY_IMPORT)];
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_pkg");
assert!(
fan.contains(&tree.path.join("stray.sv")),
"the dangling import's file is in the fan-out through `files_spelling`: {fan:?}"
);
let refusal =
same_answer(&ws, &path, at, "taken_pkg").expect_err("would capture the import");
assert!(refusal.contains("would change what"), "{refusal}");
assert!(refusal.contains("taken_pkg"), "{refusal}");
}
/// The other half of the ruling: the **old** name needs no such rung, and
/// this is the case that would expose it if it did. `stray.sv`'s only tie
/// to the rename is an `import cfg_pkg::*`-shaped use of a name that
/// resolves to nothing — spelled with the name being renamed *away*.
/// A rename only ever removes declarations of the old name, so a lookup
/// that failed before still fails after; the answer cannot move, and both
/// paths agree without `stray.sv` being read.
#[test]
fn a_dangling_use_of_the_old_name_needs_no_rung_of_its_own() {
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
// `absent_pkg` is declared nowhere, and is what the rename renames to
// nothing: the file's only spelling of it stays unresolved throughout.
const STRAY: &str = "module strayer;\n import absent_pkg::*;\nendmodule\n";
let tree = Tree::new("fanout_dangling_old");
let files = [("pkg.sv", PKG), ("stray.sv", STRAY)];
let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]);
let path = tree.path.join("pkg.sv");
// Rename the *package* to `absent_pkg` — the new-name rung must pull
// `stray.sv` in and both paths must refuse …
let package = at(PKG, "cfg_pkg;");
same_answer(&ws, &path, package, "absent_pkg").expect_err("would capture the import");
// … while a rename whose *old* name is the dangling one has nothing to
// capture: renaming `DEPTH`, which `stray.sv` never spells, leaves it
// out of the set and both paths agree.
let depth = at(PKG, "DEPTH =");
let edit = same_answer(&ws, &path, depth, "SIZE").expect("renames");
assert_eq!(edit.file_count(), 1, "only the package's own file");
let fan = fan_out(&ws, &path, depth, "SIZE");
assert!(!fan.contains(&tree.path.join("stray.sv")), "{fan:?}");
}
// ------------------------------------------------------------------
// QA, 2026-08-29: re-verification of rung 6 (files_spelling) after the
// lead-authorized fix for the dangling-import residue.
// ------------------------------------------------------------------
/// Attack on rung 6's completeness: the new name spelled **only** as the
/// base of an `extends` clause the workspace does not (yet) declare. This
/// goes through `Target::Unit`, not `Target::Package` — a different
/// resolution path than the import case rung 6 was built for — so it is
/// worth checking on its own rather than trusting the same mechanism
/// covers it by analogy.
#[test]
fn a_new_name_spelled_only_as_an_extends_base_is_still_caught_by_rung_6() {
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
const STRAY_EXTENDS: &str =
"class derived extends taken_base;\n function void go();\n endfunction\nendclass\n";
let tree = Tree::new("fanout_extends_base");
let files = [("pkg.sv", PKG), ("stray.sv", STRAY_EXTENDS)];
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_base");
assert!(
fan.contains(&tree.path.join("stray.sv")),
"the extends base is a Target::Unit miss, always non-empty paths: {fan:?}"
);
let refusal =
same_answer(&ws, &path, at, "taken_base").expect_err("would give the base a meaning");
assert!(refusal.contains("would change what"), "{refusal}");
}
/// Attack on rung 6's completeness: a bare, unqualified reference to the
/// new name written inside a class that `extends` an **existing,
/// unrelated** base, with no import in scope — the one shape that
/// produces `Resolution::InheritedCandidate` with genuinely **empty**
/// paths (`miss()`'s branch when `nearest_extends` finds a base but no
/// import supplied anything), which `files_spelling` cannot see (it reads
/// only facts with non-empty paths). The argument this pins: such a
/// reference is resolved *purely* from the file's own unedited text and
/// never depends on the workspace (`resolve_external` never even tries
/// `follow_paths` against an empty list), so it cannot change meaning
/// under any rename — excluding the file costs nothing, on this rung or
/// the whole-workspace path alike.
#[test]
fn an_unqualified_use_inside_an_extending_class_with_empty_paths_needs_no_rung() {
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
const EXISTING_BASE: &str = "class existing_base;\nendclass\n";
// No import anywhere in `stray.sv`, so the lexical miss on
// `taken_member` inside `derived` (which extends `existing_base`)
// collects an empty `external` list and becomes an `InheritedCandidate`
// with `paths: []` — recorded nowhere, per `facts_from_analysis`.
const STRAY: &str = "class derived extends existing_base;\n function void go();\n taken_member = 1;\n endfunction\nendclass\n";
let tree = Tree::new("fanout_inherited_empty_paths");
let files = [("pkg.sv", PKG), ("base.sv", EXISTING_BASE), ("stray.sv", STRAY)];
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_member");
assert!(
!fan.contains(&tree.path.join("stray.sv")),
"an empty-paths InheritedCandidate is invisible to files_spelling by design: {fan:?}"
);
// Parity must still hold: excluding the file must not change the
// answer, because the reference inside it can never resolve
// differently regardless of what `cfg_pkg` becomes.
same_answer(&ws, &path, at, "taken_member").expect("renames, no capture possible");
}
/// Attack on rung 6's soundness: a **local-only** symbol in a third file
/// that happens to share the new name's spelling must not trigger a
/// bogus refusal. `files_spelling` explicitly excludes `ReferenceFact::Local`
/// facts (a local declaration/use resolves inside its own file and the
/// 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.
#[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";
let tree = Tree::new("fanout_local_only");
let files = [("pkg.sv", PKG), ("local.sv", LOCAL_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_local");
assert!(
!fan.contains(&tree.path.join("local.sv")),
"a purely local declaration/use is not an external fact: {fan:?}"
);
let edit =
same_answer(&ws, &path, at, "taken_local").expect("renames, no capture possible");
assert!(edit.edits_for(&tree.path.join("local.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
/// "first-written import wins" resolves `shared_name` to `p_pkg`'s
/// declaration. Renaming *away* `p_pkg::shared_name` removes the winning
/// candidate, so the same reference should fall through to `q_pkg`'s
/// pre-existing, completely unrelated declaration — a meaning change the
/// whole-workspace verifier must refuse over (rule 12, in the direction
/// "an existing use is captured by nothing new — it silently rebinds to
/// another *existing* declaration"). The old-name argument says this
/// cannot be missed because rung 1 walks *every* declaration named
/// `shared_name` (both `p_pkg`'s and `q_pkg`'s, not just the target's),
/// so the importer is pulled in via `references_to` of `p_pkg`'s
/// declaration regardless.
#[test]
fn removing_the_old_names_winning_declaration_does_not_escape_the_fan_out() {
const P: &str = "package p_pkg;\n parameter int shared_name = 1;\nendpackage\n";
const Q: &str = "package q_pkg;\n parameter int shared_name = 2;\nendpackage\n";
const USER: &str = "module user;\n import p_pkg::*;\n import q_pkg::*;\n localparam int X = shared_name;\nendmodule\n";
let tree = Tree::new("fanout_shadow_unmask");
let files = [("p.sv", P), ("q.sv", Q), ("user.sv", USER)];
let (ws, _) = tree_with(&tree, &files, &["p.sv"]);
let path = tree.path.join("p.sv");
let at = at(P, "shared_name =");
let fan = fan_out(&ws, &path, at, "renamed_thing");
assert!(
fan.contains(&tree.path.join("user.sv")),
"the importer is posted against p_pkg's declaration today: {fan:?}"
);
assert!(
fan.contains(&tree.path.join("q.sv")),
"rung 1 walks every declaration named `shared_name`, not only the target's: {fan:?}"
);
// Whichever way the whole-workspace path answers this (refuse, since
// `user.sv`'s meaning silently moves from p_pkg to q_pkg; or edit,
// if some other rule intervenes first), the subset must answer
// identically — that is the property under attack, not a specific
// outcome.
// The hunt comes up empty, and reading why is the point: `user.sv`'s
// `shared_name` currently resolves to `p_pkg`'s declaration — the
// rename target itself — so it is not a bystander a removal could
// silently unmask, it is an *edit site*: the rename rewrites it to
// `renamed_thing` along with the declaration, so the text never says
// `shared_name` again for `follow_paths` to re-resolve against
// `q_pkg`. A reference can only be affected by a name's removal by
// spelling that exact name, and by the Lemma any such reference
// either resolves to the target (edited away, as here) or to some
// *other* declaration of the same name (already covered by rung 1/2's
// sweep over every declarer, not only the target's) — there is no
// third case for the old name to fall into.
let edit = same_answer(&ws, &path, at, "renamed_thing").expect("renames");
assert_eq!(edit.file_count(), 2, "the declaration and the importer's edited reference");
assert!(
edit.edits_for(&tree.path.join("q.sv")).is_empty(),
"q_pkg's own unrelated declaration is never touched"
);
}
#[test]
fn an_open_buffer_beats_disk_when_the_rename_is_computed() {
let tree = Tree::new("buffer");
tree.write("sub.sv", SUB);
let top_path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
// The buffer instantiates `sub`; the file on disk does not.
let uri = path_to_uri(&top_path).expect("uri");
ws.set_document(uri.clone(), TOP.to_string());
+32 -2
View File
@@ -13,7 +13,7 @@ use vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind, Stmt, StmtKind}
use vlog_parser::TextRange;
use crate::pairs::analyze;
use crate::state::Document;
use crate::state::{first_token_reaching, Document};
/// One chain per requested position, in the order they were asked for.
///
@@ -41,7 +41,17 @@ fn chain(doc: &Document, offset: u32) -> SelectionRange {
/// source, unordered and possibly overlapping — [`nested`] sorts it out.
fn enclosing(doc: &Document, offset: u32) -> Vec<TextRange> {
let mut spans = Vec::new();
if let Some(token) = doc.tokens.iter().find(|token| covers(token.span, offset)) {
// The first token that reaches `offset` is the first that can cover it,
// and — because the tokens after it all start no earlier — the only one
// the sweep this replaced could ever have returned. Note that `covers`
// takes `span.end` inclusively, so this is deliberately *not*
// `Document::token_at`: at a byte two adjacent tokens share, the sweep
// answered with the earlier one and so does this.
if let Some(token) = doc
.tokens
.get(first_token_reaching(&doc.tokens, offset))
.filter(|token| covers(token.span, offset))
{
spans.push(token.span);
}
items(&doc.tree.items, offset, &mut spans);
@@ -219,6 +229,26 @@ mod tests {
Document::new(None, text.to_string(), &WorkspaceIndex::default())
}
/// The innermost step of a chain used to come from a sweep of the whole
/// token vector; it now comes from a binary search. `covers` takes
/// `span.end` inclusively, so at a byte two adjacent tokens share the
/// sweep answered with the earlier of the two — this pins that the search
/// answers with the earlier one too, at every byte of a buffer written to
/// have plenty of them.
#[test]
fn the_innermost_step_is_the_token_the_sweep_returned_at_every_offset() {
let text = crate::state::mixed_buffer(20);
let doc = doc_of(&text);
for offset in 0..=text.len() as u32 {
let swept = doc.tokens.iter().find(|token| covers(token.span, offset));
let searched = doc
.tokens
.get(first_token_reaching(&doc.tokens, offset))
.filter(|token| covers(token.span, offset));
assert_eq!(swept.map(|t| t.span), searched.map(|t| t.span), "at offset {offset}");
}
}
/// The chain for the first occurrence of `needle`, as the source text of
/// each step, innermost first.
fn steps(text: &str, needle: &str) -> Vec<String> {
File diff suppressed because it is too large. Load diff
+486 -7
View File
@@ -28,6 +28,58 @@ use serde_json::Value;
const LINE_LENGTH_RANGE: RangeInclusive<u64> = 40..=400;
const INDENT_RANGE: RangeInclusive<u64> = 1..=8;
/// `lucisv.index.maxFileSize`'s default: 1 MiB. A source file bigger than this
/// is almost always a generated netlist or a dumped trace, which costs minutes
/// to index and answers nothing a user asked. `0` means no cap; see
/// `docs/features/indexing-ux/README.md`.
pub const DEFAULT_MAX_FILE_SIZE: u64 = 1024 * 1024;
/// `lucisv.largeFile.threshold`'s default: 4 MiB. A buffer bigger than this is
/// opened on the fast path — line index only, no lex, no parse, no index — and
/// coloured a viewport at a time. `0` turns the fast path off, so every buffer
/// is analyzed in full however big it is; see
/// `docs/features/large-file-mode/README.md`.
pub const DEFAULT_LARGE_FILE_THRESHOLD: u64 = 4 * 1024 * 1024;
/// `lucisv.index.scopeDepth`'s default: 2 levels above the open file's own
/// folder, clamped at the workspace root that contains it.
///
/// **Changed from 0 on 2026-08-28**, and it is a behaviour change, not a
/// tuning one. At 0 the folder scope indexed the opened file's directory and
/// nothing else, and the measurement that forced the change is in
/// `performance.md` §4: opening `hw/ip/aes/dv/tb/tb.sv` in opentitan gave an
/// index of **one file**, so definition, hover, references, `workspace/symbol`
/// and signature help all answered *nothing* until some later jump widened the
/// scope. A user's first experience of the server was silence.
///
/// Two levels is the smallest raise that turns a `dv/tb` or an `rtl` file into
/// the IP block it belongs to — `hw/ip/aes`, a few hundred files — which is
/// the unit an engineer actually works in. What keeps the cost bounded is
/// everything the scope ladder already has: the size cap, the persistent
/// cache, the interleaved scan and the incremental widen. See
/// `docs/features/index-scope/README.md`.
pub const DEFAULT_SCOPE_DEPTH: u64 = 2;
/// What `lucisv.index.scope` chooses: how wide the workspace walk goes.
///
/// The default is deliberately the narrow one. A large project is the case
/// worth optimising for, and in it the files a user is working with are the
/// ones beside the file they opened; walking every workspace folder to answer
/// a question about one folder is minutes of work nobody asked for. See
/// `docs/features/index-scope/README.md` for what the narrow scope costs,
/// which is cross-folder answers until the scope reaches the other folder.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum IndexScope {
/// The open buffers' own folders, each raised
/// [`ClientSettings::index_scope_depth`] levels, walked.
#[default]
Folder,
/// Every workspace folder, walked whole — what the server did before
/// 2026-08-27, and what a user with a small project or a big machine can
/// ask for back.
Workspace,
}
/// The configuration section these settings live in — the key a push nests
/// them under, and the `section` a pull asks for. One constant, because the
/// two must name the same thing or the pull would answer settings the parser
@@ -36,8 +88,11 @@ pub const SECTION: &str = "lucisv";
/// The `lucisv.*` settings in force, after validation. Every field is "no
/// opinion" until a client says otherwise, which is exactly what an unset
/// VS Code setting means.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
/// VS Code setting means — except the two whose own default is not silence
/// (`index.maxFileSize`, `index.logFiles`), which resolve to it here so no
/// use site has to remember what "unset" meant. See the hand-written
/// [`Default`] below.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientSettings {
/// `lucisv.lineLength`.
pub line_length: Option<usize>,
@@ -53,6 +108,11 @@ pub struct ClientSettings {
/// Unset means on, which is what the VS Code default declares — see
/// `docs/features/inline-templates/README.md`.
pub inline_templates: Option<bool>,
/// `lucisv.inlineInstantiation`: whether a module name the workspace
/// declares grows a ghost instantiation once it is spelled exactly and
/// followed by a space. Unset means on, the same way `inline_templates`
/// does — see `docs/features/inline-instantiation/README.md`.
pub inline_instantiation: Option<bool>,
/// `lucisv.formatOnSave`: whether `textDocument/willSaveWaitUntil` formats
/// the buffer. A plain `bool` rather than an `Option`, because unset and
/// off are the same answer here: an editor with a format-on-save of its
@@ -60,6 +120,88 @@ pub struct ClientSettings {
/// also formatted would format twice. See
/// `docs/features/will-save-wait-until/README.md`.
pub format_on_save: bool,
/// `lucisv.index.maxFileSize`: the largest *walked* file, in bytes, that
/// the workspace index will read. `0` is no cap. An open buffer is
/// indexed whatever its size — the user opened it deliberately. Defaults
/// to [`DEFAULT_MAX_FILE_SIZE`] rather than to 0, so a plain
/// `ClientSettings::default()` is the capped behaviour the server ships
/// with.
pub max_file_size: u64,
/// `lucisv.index.logFiles`: whether each file the index reads is named in
/// a `window/logMessage`, and each oversized one in a skip line. On
/// unless a client says otherwise — the Output panel it lands in is
/// hidden until somebody opens it.
pub log_files: bool,
/// `lucisv.index.scope`: whether the walk covers the open files' folders
/// or every workspace folder. Defaults to [`IndexScope::Folder`], which
/// is a narrower index than the server built before 2026-08-27 — see
/// `docs/features/index-scope/README.md`.
pub index_scope: IndexScope,
/// `lucisv.index.scopeDepth`: how many directory levels above an open
/// file's own folder the folder scope starts, clamped so it never climbs
/// out of the workspace folder containing it. `0` is the file's own folder
/// and the default is [`DEFAULT_SCOPE_DEPTH`]. Ignored when `index_scope`
/// is [`IndexScope::Workspace`] or when a filelist defines the scope.
pub index_scope_depth: u64,
/// `lucisv.index.persist`: whether what a scan parsed is written to disk
/// so the next session can skip parsing the files that have not changed.
/// On unless a client says otherwise — a half-finished scan that has to
/// start again from zero is the thing this exists to prevent. Off means
/// off in both directions: nothing is read and nothing is written
/// (`docs/features/index-persistence/README.md`).
pub index_persist: bool,
/// `lucisv.index.cachePath`: where that store lives, absolute or relative
/// to the first workspace root. Empty means "unset", and then the
/// editor's own storage folder — or this platform's cache directory —
/// decides; see `index_cache::cache_dir` for the ladder.
pub index_cache_path: Option<String>,
/// `lucisv.largeFile.threshold`: the size in bytes above which an **open
/// buffer** is served by the fast path instead of being analyzed. `0`
/// disables the fast path. Unlike `index.maxFileSize`, which is about
/// files on disk that nobody asked for, this one is about the file on
/// screen — see `docs/features/large-file-mode/README.md`.
pub large_file_threshold: u64,
/// `lucisv.lint.select`: run exactly these rules, replacing the default
/// set — `lucisv check --select` and `lucisv.toml`'s `[lint] select`, said
/// from the editor. Empty means "no opinion", which is the default set.
///
/// **Names are validated here**, against the rule registry, and an unknown
/// one is dropped like every other unreadable value in this module: the
/// CLI can fail a run over a typo because a user typed it and is watching,
/// while a settings push arrives on a socket and failing it would leave an
/// editor with no diagnostics and no way to see why.
pub lint_select: Vec<String>,
/// `lucisv.lint.ignore`: rules dropped from whatever `select` left. Same
/// validation, same reason.
pub lint_ignore: Vec<String>,
}
/// The settings a client that said nothing is treated as having asked for.
///
/// Hand-written because two of them do not default to silence: the size cap
/// is on at 1 MiB and the file log is on. Every other field is its type's own
/// zero, exactly as the derive produced.
impl Default for ClientSettings {
fn default() -> ClientSettings {
ClientSettings {
line_length: None,
indent: None,
exclude: Vec::new(),
filelist: None,
inline_templates: None,
inline_instantiation: None,
format_on_save: false,
max_file_size: DEFAULT_MAX_FILE_SIZE,
log_files: true,
index_scope: IndexScope::Folder,
index_scope_depth: DEFAULT_SCOPE_DEPTH,
index_persist: true,
index_cache_path: None,
large_file_threshold: DEFAULT_LARGE_FILE_THRESHOLD,
lint_select: Vec::new(),
lint_ignore: Vec::new(),
}
}
}
/// Read the `lucisv` section out of a `workspace/didChangeConfiguration` payload.
@@ -78,16 +220,82 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
// the section (including the `{"settings": null}` a client sends when it
// syncs no section at all) means "no opinion about anything".
let Some(lucisv) = settings.get(SECTION) else { return ClientSettings::default() };
// `lucisv.index.maxFileSize` is a dotted id, and both doors nest it: VS
// Code's settings model turns every segment into an object, so the section
// arrives as `{"index": {"maxFileSize": …}}`. An `index` that is missing —
// or is not an object at all — leaves both of its keys at their defaults,
// which is what `Value::get` on a non-object already returns.
let index = lucisv.get("index");
// `lucisv.largeFile.threshold` nests exactly as `index.*` does, for the
// same reason: VS Code turns every dotted segment into an object.
let large_file = lucisv.get("largeFile");
// And `lucisv.lint.select` / `lucisv.lint.ignore` the same way again.
let lint = lucisv.get("lint");
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")),
inline_templates: flag(lucisv.get("inlineTemplates")),
inline_instantiation: flag(lucisv.get("inlineInstantiation")),
// Anything that is not `true` leaves the hook declining, wrong-typed
// values included: the safe direction for a setting that rewrites the
// user's buffer on every save is the one that does nothing.
format_on_save: flag(lucisv.get("formatOnSave")).unwrap_or(false),
// The safe direction for these two is the shipped default, not zero:
// a wrong-typed cap that read as `0` would index the netlist the
// setting exists to skip.
max_file_size: count(index.and_then(|i| i.get("maxFileSize")))
.unwrap_or(DEFAULT_MAX_FILE_SIZE),
log_files: flag(index.and_then(|i| i.get("logFiles"))).unwrap_or(true),
// An unreadable scope leaves the narrow default standing, for the
// same reason a junk cap leaves the cap on: the direction that
// silently costs a user minutes of scanning is the wrong one to
// guess in.
index_scope: scope(index.and_then(|i| i.get("scope"))).unwrap_or_default(),
// A junk depth leaves the shipped default standing, like every
// other setting here: an unreadable value must never be the reason a
// user's index is narrower than the server promised.
index_scope_depth: count(index.and_then(|i| i.get("scopeDepth")))
.unwrap_or(DEFAULT_SCOPE_DEPTH),
// A wrong-typed `persist` leaves the cache on. The direction that
// costs something is turning it *off* by accident — a user who never
// touched the setting would silently pay for every parse again — and
// a cache that is on can only ever cost a file's parse, because every
// hit is verified against the file's own bytes.
index_persist: flag(index.and_then(|i| i.get("persist"))).unwrap_or(true),
index_cache_path: path(index.and_then(|i| i.get("cachePath"))),
// The safe direction again: a wrong-typed threshold leaves the fast
// path armed at its default. A junk value that read as `0` would turn
// it off, and the first 100 MB netlist opened after that would hang
// the editor for minutes — which is the whole thing this exists to
// 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"))),
}
}
/// The rule names in a settings array, dropping every one the registry does
/// not know.
///
/// Silence rather than an error, on this module's standing rule: a push is
/// JSON on a socket, and a typo in one name must not cost the user every
/// diagnostic in the file. A dropped name leaves the rule where it was.
fn rules(value: Option<&Value>) -> Vec<String> {
strings(value).into_iter().filter(|name| vlog_linter::rule_by_name(name).is_some()).collect()
}
/// One of the two `lucisv.index.scope` words, or nothing. Matched exactly —
/// case and all — because the enum in `package.json` is what a settings UI
/// offers, and forgiving `"Workspace"` here would make a typo mean something
/// on one client and nothing on another.
fn scope(value: Option<&Value>) -> Option<IndexScope> {
match value?.as_str()? {
"folder" => Some(IndexScope::Folder),
"workspace" => Some(IndexScope::Workspace),
_ => None,
}
}
@@ -151,6 +359,16 @@ fn bounded(value: Option<&Value>, range: RangeInclusive<u64>) -> Option<usize> {
range.contains(&number).then_some(number as usize)
}
/// A JSON count — any unsigned integer, `0` included — or nothing.
///
/// Unbounded on purpose: there is no size a cap may not take, and a cap larger
/// than any file on disk is the same as no cap at all. `as_u64` still rejects
/// the negatives, the fractions, the strings and the booleans, exactly as
/// [`bounded`] does.
fn count(value: Option<&Value>) -> Option<u64> {
value?.as_u64()
}
/// Every string in a JSON array, or an empty list for anything else. Entries
/// that are not strings are dropped rather than stringified: a number in an
/// exclude list is a mistake, and guessing what it meant would hide it.
@@ -183,11 +401,175 @@ mod tests {
"exclude": exclude,
"filelist": "",
"inlineTemplates": true,
"formatOnSave": false
"inlineInstantiation": true,
"formatOnSave": false,
"index": {
"maxFileSize": 1048576, "logFiles": true,
"scope": "folder", "scopeDepth": DEFAULT_SCOPE_DEPTH
}
}
})
}
#[test]
fn the_size_cap_defaults_to_a_mebibyte_and_zero_turns_it_off() {
assert_eq!(settings(json!({ "lucisv": {} })).max_file_size, DEFAULT_MAX_FILE_SIZE);
assert_eq!(DEFAULT_MAX_FILE_SIZE, 1_048_576, "1 MiB, as the setting's description says");
// The whole sub-section missing is the same as the key missing.
assert_eq!(settings(json!({ "lucisv": { "index": {} } })).max_file_size, 1_048_576);
let off = settings(json!({ "lucisv": { "index": { "maxFileSize": 0 } } }));
assert_eq!(off.max_file_size, 0, "0 is the client asking for no cap at all");
let raised = settings(json!({ "lucisv": { "index": { "maxFileSize": 20_000_000 } } }));
assert_eq!(raised.max_file_size, 20_000_000, "and there is no upper bound");
}
#[test]
fn a_wrong_typed_size_cap_leaves_the_default_standing() {
// The safe direction is the shipped cap: reading junk as `0` would
// turn the cap *off*, which is the failure the setting exists to
// prevent.
for bad in
[json!("1048576"), json!(-1), json!(1.5), json!(true), json!(null), json!([1048576])]
{
let found = settings(json!({ "lucisv": { "index": { "maxFileSize": bad } } }));
assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE, "maxFileSize {bad} is ignored");
}
// An `index` that is not an object at all is the same as no `index`.
for bad in [json!(null), json!(7), json!("index"), json!([])] {
let found = settings(json!({ "lucisv": { "index": bad } }));
assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE, "index {bad} is ignored");
assert!(found.log_files, "and so is its logFiles");
assert_eq!(found.index_scope, IndexScope::Folder, "and its scope");
assert_eq!(found.index_scope_depth, DEFAULT_SCOPE_DEPTH, "and its scopeDepth");
}
}
#[test]
fn the_file_log_is_on_until_a_client_turns_it_off() {
assert!(settings(json!({ "lucisv": {} })).log_files, "absence is on");
assert!(
settings(json!({ "lucisv": { "index": {} } })).log_files,
"and so is an empty section"
);
assert!(settings(json!({ "lucisv": { "index": { "logFiles": true } } })).log_files);
assert!(!settings(json!({ "lucisv": { "index": { "logFiles": false } } })).log_files);
for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] {
let found = settings(json!({ "lucisv": { "index": { "logFiles": bad } } }));
assert!(found.log_files, "logFiles {bad} must be ignored");
}
}
#[test]
fn the_index_settings_come_through_the_pull_door_too() {
// `from_section` is the same parser, and these were the first nested
// keys to go through it — a section that lost the nesting on the way
// would silently un-cap every pulling client.
let section = json!({
"index": {
"maxFileSize": 4096, "logFiles": false,
"scope": "workspace", "scopeDepth": 2,
"persist": false, "cachePath": "/tmp/store"
}
});
let pulled = from_section(&section);
assert_eq!(pulled.max_file_size, 4096);
assert!(!pulled.log_files);
assert_eq!(pulled.index_scope, IndexScope::Workspace);
assert_eq!(pulled.index_scope_depth, 2);
assert!(!pulled.index_persist);
assert_eq!(pulled.index_cache_path.as_deref(), Some("/tmp/store"));
assert_eq!(pulled, settings(json!({ "lucisv": section })), "one set of rules");
}
#[test]
fn the_index_cache_is_on_until_a_client_turns_it_off() {
// Same shape as the file log, and the same direction for junk: the
// setting that costs a user work if it is guessed wrong is "off", so
// anything unreadable leaves it on.
assert!(settings(json!({ "lucisv": {} })).index_persist, "absence is on");
assert!(settings(json!({ "lucisv": { "index": {} } })).index_persist, "so is an empty one");
assert!(settings(json!({ "lucisv": { "index": { "persist": true } } })).index_persist);
assert!(!settings(json!({ "lucisv": { "index": { "persist": false } } })).index_persist);
for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] {
let found = settings(json!({ "lucisv": { "index": { "persist": bad } } }));
assert!(found.index_persist, "persist {bad} must be ignored");
}
}
#[test]
fn the_cache_path_is_unset_until_a_client_names_one() {
// The empty string is `lucisv.index.cachePath`'s own default and means
// "you decide", exactly as it does for `lucisv.filelist` — not "the
// directory named by the empty path".
assert_eq!(settings(json!({ "lucisv": {} })).index_cache_path, None);
assert_eq!(
settings(json!({ "lucisv": { "index": { "cachePath": "" } } })).index_cache_path,
None
);
assert_eq!(
settings(json!({ "lucisv": { "index": { "cachePath": ".cache/lucisv" } } }))
.index_cache_path
.as_deref(),
Some(".cache/lucisv")
);
for bad in [json!(1), json!(true), json!(null), json!(["/a"]), json!({ "path": "/a" })] {
let found = settings(json!({ "lucisv": { "index": { "cachePath": bad } } }));
assert_eq!(found.index_cache_path, None, "cachePath {bad} must be ignored");
}
}
#[test]
fn the_index_scope_is_the_open_folder_until_a_client_asks_for_the_workspace() {
// The default is the narrow one, and it is what silence, an empty
// sub-section and a missing `index` all resolve to.
assert_eq!(settings(json!({ "lucisv": {} })).index_scope, IndexScope::Folder);
assert_eq!(settings(json!({ "lucisv": { "index": {} } })).index_scope, IndexScope::Folder);
assert_eq!(IndexScope::default(), IndexScope::Folder, "and the enum agrees");
let wide = settings(json!({ "lucisv": { "index": { "scope": "workspace" } } }));
assert_eq!(wide.index_scope, IndexScope::Workspace, "the migration setting");
let narrow = settings(json!({ "lucisv": { "index": { "scope": "folder" } } }));
assert_eq!(narrow.index_scope, IndexScope::Folder, "spelled out, same thing");
// Anything else is junk, and junk leaves the *narrow* default: a
// misparse must never buy a whole-workspace scan silently.
for bad in
[json!("Workspace"), json!("all"), json!(""), json!(2), json!(true), json!(["folder"])]
{
let found = settings(json!({ "lucisv": { "index": { "scope": bad } } }));
assert_eq!(found.index_scope, IndexScope::Folder, "scope {bad} must be ignored");
}
}
#[test]
fn the_scope_depth_is_two_until_a_client_says_otherwise() {
// Two, not zero, since 2026-08-28: `performance.md` §4 measured the
// file's-own-folder default indexing exactly one file in opentitan's
// `dv/tb` layout, so every cross-file answer was empty until some
// later jump widened the scope. See [`DEFAULT_SCOPE_DEPTH`].
assert_eq!(settings(json!({ "lucisv": {} })).index_scope_depth, DEFAULT_SCOPE_DEPTH);
assert_eq!(
settings(json!({ "lucisv": { "index": {} } })).index_scope_depth,
DEFAULT_SCOPE_DEPTH
);
let raised = settings(json!({ "lucisv": { "index": { "scopeDepth": 3 } } }));
assert_eq!(raised.index_scope_depth, 3);
// Zero is still exactly what it always was — the file's own folder and
// nothing above it — and asking for it still gets it.
let narrow = settings(json!({ "lucisv": { "index": { "scopeDepth": 0 } } }));
assert_eq!(narrow.index_scope_depth, 0, "an explicit 0 is honoured, not defaulted");
// No upper bound here: the clamp is structural — `state.rs` stops at
// the workspace root — so an absurd number is not wrong, just fully
// clamped.
let absurd = settings(json!({ "lucisv": { "index": { "scopeDepth": 9999 } } }));
assert_eq!(absurd.index_scope_depth, 9999);
for bad in [json!(-1), json!(1.5), json!("2"), json!(true), json!(null), json!([2])] {
let found = settings(json!({ "lucisv": { "index": { "scopeDepth": bad } } }));
assert_eq!(
found.index_scope_depth, DEFAULT_SCOPE_DEPTH,
"scopeDepth {bad} must be ignored"
);
}
}
#[test]
fn a_filelist_is_taken_when_it_names_something() {
let found = settings(json!({ "lucisv": { "filelist": "rtl/files.f" } }));
@@ -211,17 +593,52 @@ mod tests {
assert_eq!(settings(json!({ "lucisv": {} })).filelist, None, "and so must its absence");
}
/// [`vscode_payload`] above is a hand-written copy of what the extension
/// declares, and a copy that drifts proves nothing. The extension's own
/// `package.json` is the thing a user's settings UI reads, so the two
/// defaults that are not "no opinion" are checked against it directly.
#[test]
fn the_extensions_declared_defaults_are_the_ones_this_module_ships() {
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../editors/vscode/package.json");
let text = std::fs::read_to_string(&path).expect("the extension manifest");
let manifest: Value = serde_json::from_str(&text).expect("valid json");
let properties = &manifest["contributes"]["configuration"]["properties"];
assert_eq!(
properties["lucisv.index.scopeDepth"]["default"],
json!(DEFAULT_SCOPE_DEPTH),
"the settings UI and the server must ship the same scope depth"
);
assert_eq!(
properties["lucisv.index.maxFileSize"]["default"],
json!(DEFAULT_MAX_FILE_SIZE),
"and the same size cap"
);
// The two ghost-text settings are the ones whose absence resolves to
// `true` here, so a `false` default in the manifest would make the
// settings UI and the server disagree about a feature being on.
for ghost in ["lucisv.inlineTemplates", "lucisv.inlineInstantiation"] {
assert_eq!(properties[ghost]["default"], json!(true), "{ghost}");
assert_eq!(properties[ghost]["type"], json!("boolean"), "{ghost}");
}
}
#[test]
fn the_default_vscode_payload_is_no_opinion_about_anything() {
// Every setting at its `package.json` default: nulls and an empty
// list, which must leave today's behaviour exactly unchanged.
// `inlineTemplates` is the one default that is not "no opinion" — it
// defaults to `true`, and `None` resolves to the same thing.
// The two ghost-text settings are the defaults that are not "no
// opinion" — both default to `true`, and `None` resolves to the same
// thing.
let found = settings(vscode_payload(json!(null), json!(null), json!([])));
assert_eq!(
found,
ClientSettings { inline_templates: Some(true), ..Default::default() },
"the only difference from silence must be the one setting whose \
ClientSettings {
inline_templates: Some(true),
inline_instantiation: Some(true),
..Default::default()
},
"the only difference from silence must be the settings whose \
default is not null"
);
}
@@ -240,6 +657,23 @@ mod tests {
}
}
#[test]
fn inline_instantiation_is_a_boolean_and_nothing_else() {
let found = settings(json!({ "lucisv": { "inlineInstantiation": false } }));
assert_eq!(found.inline_instantiation, Some(false));
let found = settings(json!({ "lucisv": { "inlineInstantiation": true } }));
assert_eq!(found.inline_instantiation, Some(true));
// Absence is not `false`: the feature is on unless a client says no.
assert_eq!(settings(json!({ "lucisv": {} })).inline_instantiation, None);
for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] {
let found = settings(json!({ "lucisv": { "inlineInstantiation": bad } }));
assert_eq!(found.inline_instantiation, None, "inlineInstantiation {bad} ignored");
}
// The two ghost settings are independent: one off leaves the other on.
let found = settings(json!({ "lucisv": { "inlineInstantiation": false } }));
assert_eq!(found.inline_templates, None, "the templates setting is untouched");
}
#[test]
fn format_on_save_is_off_until_a_client_asks_for_it() {
assert!(settings(json!({ "lucisv": { "formatOnSave": true } })).format_on_save);
@@ -397,4 +831,49 @@ mod tests {
assert!(ok("line-length = 40") && ok("line-length = 400"), "the line-length edges");
assert!(!ok("line-length = 39") && !ok("line-length = 401"), "just outside line-length");
}
/// `lucisv.lint.select` / `lucisv.lint.ignore` nest like every other dotted
/// id, and carry only names the rule registry knows.
#[test]
fn the_lint_selection_is_read_and_validated() {
let read = settings(json!({"lucisv": {"lint": {
"select": ["unused-signal", "no-tabs"],
"ignore": ["no-tabs"],
}}}));
assert_eq!(read.lint_select, vec!["unused-signal", "no-tabs"]);
assert_eq!(read.lint_ignore, vec!["no-tabs"]);
// A name the registry does not know is dropped, not an error: a push
// is JSON on a socket, and one typo must not cost every diagnostic.
let typo = settings(json!({"lucisv": {"lint": {
"select": ["unused-signal", "unusedsignal", 7, null],
"ignore": "no-tabs",
}}}));
assert_eq!(typo.lint_select, vec!["unused-signal"]);
assert!(typo.lint_ignore.is_empty(), "an array is required");
// Absent, or absent-shaped, is "no opinion".
assert!(settings(json!({"lucisv": {}})).lint_select.is_empty());
assert!(settings(json!({"lucisv": {"lint": 3}})).lint_ignore.is_empty());
assert!(ClientSettings::default().lint_select.is_empty());
}
/// The pull door reads the same keys as the push door — the property the
/// whole module is built on, asserted for the new keys too.
#[test]
fn a_pull_reads_the_lint_selection_the_same_way() {
let pulled = from_section(&json!({"lint": {"ignore": ["unused-signal"]}}));
assert_eq!(pulled.lint_ignore, vec!["unused-signal"]);
assert_eq!(pulled, settings(json!({"lucisv": {"lint": {"ignore": ["unused-signal"]}}})));
}
/// The rule names the settings accept are the ones `lucisv check` accepts:
/// one registry, not a list copied into a schema.
#[test]
fn the_accepted_rule_names_are_the_registrys() {
for rule in vlog_linter::all_rules() {
let read = settings(json!({"lucisv": {"lint": {"ignore": [rule.name()]}}}));
assert_eq!(read.lint_ignore, vec![rule.name()], "{}", rule.name());
}
}
}
+13 -8
View File
@@ -108,7 +108,7 @@ fn utf16_len(text: &str) -> u32 {
/// Which of an instantiation's two lists the cursor is in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
pub(crate) enum Kind {
/// `sub #( ... )`
Params,
/// `sub u_sub ( ... )`
@@ -116,11 +116,16 @@ enum Kind {
}
/// The list the cursor is inside.
struct List {
module: String,
kind: Kind,
///
/// `pub(crate)` since 2026-09-02: `completion.rs` asks the identical question
/// when a `.` is typed with nothing before it, so that the popup after the dot
/// and the signature card above it can never disagree about which module's
/// list the cursor is in. See `docs/features/member-completion/README.md`.
pub(crate) struct List {
pub(crate) module: String,
pub(crate) kind: Kind,
/// Index of the `(` token that opens it.
open: usize,
pub(crate) open: usize,
}
/// The innermost instantiation list the cursor sits in, if any.
@@ -133,7 +138,7 @@ struct List {
/// optionally with the module's own `#( ... )` in between. `foo(bar|)` inside
/// a connected expression fails that test, because the token before `foo` is
/// the `(` of the connection and not a name.
fn enclosing_list(tokens: &[Token], offset: u32) -> Option<List> {
pub(crate) fn enclosing_list(tokens: &[Token], offset: u32) -> Option<List> {
let mut open: Vec<usize> = Vec::new();
for (i, token) in tokens.iter().enumerate() {
if token.span.start >= offset {
@@ -321,7 +326,7 @@ endmodule
tree.write("sub.sv", SUB);
let path = tree.write("top.sv", top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
let offset = (top.find(needle).expect("needle present") + needle.len()) as u32;
@@ -456,7 +461,7 @@ endmodule
let top = "module top;\n bare #(\n";
let path = tree.write("top.sv", top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
let offset = top.len() as u32 - 1;
File diff suppressed because it is too large. Load diff
+57 -2
View File
@@ -11,11 +11,15 @@ use crate::state::{Document, Workspace, WORKSPACE_SYMBOL_LIMIT};
pub fn kind_label(kind: SymbolKind) -> &'static str {
match kind {
SymbolKind::Module => "module",
SymbolKind::Interface => "interface",
SymbolKind::Modport => "modport",
SymbolKind::Clocking => "clocking",
SymbolKind::Package => "package",
SymbolKind::Port => "port",
SymbolKind::Net => "net",
SymbolKind::Var => "variable",
SymbolKind::Param => "parameter",
SymbolKind::LocalParam => "localparam",
SymbolKind::Genvar => "genvar",
SymbolKind::Typedef => "type",
SymbolKind::EnumVariant => "enum variant",
@@ -26,6 +30,12 @@ pub fn kind_label(kind: SymbolKind) -> &'static str {
SymbolKind::Block => "block",
SymbolKind::StructMember => "struct member",
SymbolKind::Class => "class",
SymbolKind::Constraint => "constraint",
SymbolKind::Covergroup => "covergroup",
SymbolKind::Coverpoint => "coverpoint",
SymbolKind::Cross => "cross",
SymbolKind::Property => "property",
SymbolKind::Sequence => "sequence",
}
}
@@ -34,11 +44,16 @@ pub fn kind_label(kind: SymbolKind) -> &'static str {
pub fn lsp_kind(kind: SymbolKind) -> LspKind {
match kind {
SymbolKind::Module => LspKind::CLASS,
// A modport is a named view *of* an interface, so it takes the same
// icon; a clocking block is an event-driven grouping and takes LSP's
// own `EVENT`.
SymbolKind::Interface | SymbolKind::Modport => LspKind::INTERFACE,
SymbolKind::Clocking => LspKind::EVENT,
SymbolKind::Package => LspKind::NAMESPACE,
SymbolKind::Port | SymbolKind::Net | SymbolKind::Var | SymbolKind::Genvar => {
LspKind::VARIABLE
}
SymbolKind::Param | SymbolKind::TfArg => LspKind::CONSTANT,
SymbolKind::Param | SymbolKind::LocalParam | SymbolKind::TfArg => LspKind::CONSTANT,
SymbolKind::Typedef => LspKind::TYPE_PARAMETER,
SymbolKind::EnumVariant => LspKind::ENUM_MEMBER,
SymbolKind::Function | SymbolKind::Task => LspKind::FUNCTION,
@@ -46,6 +61,21 @@ pub fn lsp_kind(kind: SymbolKind) -> LspKind {
SymbolKind::Block => LspKind::MODULE,
SymbolKind::StructMember => LspKind::FIELD,
SymbolKind::Class => LspKind::CLASS,
// A constraint is a named member of a class that holds a
// declaration rather than code anyone calls, which is exactly what
// LSP's `PROPERTY` is for; `FUNCTION` would promise a call site
// that does not exist.
SymbolKind::Constraint => LspKind::PROPERTY,
// A covergroup is a named container whose members are reached with a
// `.`, which is what `CLASS` means to an editor; a coverpoint and a
// cross are named members of it that hold a declaration rather than
// code, so they take `PROPERTY` for the reason a constraint does.
SymbolKind::Covergroup => LspKind::CLASS,
SymbolKind::Coverpoint | SymbolKind::Cross => LspKind::PROPERTY,
// A property and a sequence are named declarations that take formal
// arguments and are instantiated by name, which is what `FUNCTION`
// means to an editor.
SymbolKind::Property | SymbolKind::Sequence => LspKind::FUNCTION,
}
}
@@ -145,6 +175,31 @@ mod tests {
assert_eq!(symbols[1].kind, LspKind::NAMESPACE);
}
/// The labels and icons coverage_gaps C2 was about: an interface that used
/// to read "module", and a modport and a clocking block that used to be no
/// outline entry at all (`docs/features/interface-semantics/README.md`).
#[test]
fn an_interface_its_modport_and_its_clocking_block_are_named_and_iconed() {
assert_eq!(kind_label(SymbolKind::Interface), "interface");
assert_eq!(kind_label(SymbolKind::Modport), "modport");
assert_eq!(kind_label(SymbolKind::Clocking), "clocking");
assert_eq!(lsp_kind(SymbolKind::Interface), LspKind::INTERFACE);
assert_eq!(lsp_kind(SymbolKind::Modport), LspKind::INTERFACE);
assert_eq!(lsp_kind(SymbolKind::Clocking), LspKind::EVENT);
let (ws, uri) = document(
"interface bus_if;\n logic clk;\n modport mp (input clk);\n clocking cb @(posedge clk);\n endclocking\nendinterface\n",
);
let symbols = document_symbols(ws.document(&uri).expect("open"));
assert_eq!(symbols.len(), 1);
assert_eq!(symbols[0].kind, LspKind::INTERFACE);
let children = symbols[0].children.as_ref().expect("interface contents");
let shape: Vec<(&str, LspKind)> =
children.iter().map(|c| (c.name.as_str(), c.kind)).collect();
assert!(shape.contains(&("mp", LspKind::INTERFACE)), "{shape:?}");
assert!(shape.contains(&("cb", LspKind::EVENT)), "{shape:?}");
}
#[test]
fn the_selection_range_is_always_inside_the_full_range() {
let (ws, uri) = document("module top;\n wire [7:0] wide;\nendmodule\n");
@@ -179,7 +234,7 @@ mod tests {
.expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let hits = workspace_symbols(&ws, "alpha");
let names: Vec<_> = hits.iter().map(|h| h.name.as_str()).collect();
+331 -15
View File
@@ -121,18 +121,35 @@ pub fn semantic_tokens_in_range(doc: &Document, range: Range) -> Vec<SemanticTok
encode(&within(absolute(doc), range))
}
/// The tokens a range covers of a buffer nothing has lexed — the large-file
/// fast path's answer to `semanticTokens/range`.
///
/// Identical to [`semantic_tokens_in_range`] in everything the client can see:
/// the same classification, the same line splitting, the same encoding from
/// the start of the document, the same overlap filter. The only difference is
/// where the tokens come from — `large::window` lexes the window instead of
/// the document's own (empty) token stream — and that a plain identifier can
/// only ever be `variable`, because there is no `Semantics` to refine it with.
/// See `docs/features/large-file-mode/README.md`.
pub fn semantic_tokens_in_window(doc: &Document, range: Range) -> Vec<SemanticToken> {
let window = crate::large::window(doc, range);
let mut pieces = Vec::new();
// The comment spans the lexer never saw go in first; `flatten` sorts, so
// the order they are collected in cannot reach the wire.
for span in &window.comments {
pieces.push(Piece { span: *span, ty: Highlight::Comment, modifiers: 0 });
}
for token in &window.tokens {
collect(token, &doc.semantics, &mut pieces);
}
encode(&within(flatten(pieces, doc), range))
}
/// Classify the whole buffer, split at line boundaries, in wire order.
fn absolute(doc: &Document) -> Vec<Absolute> {
let mut pieces = Vec::new();
for token in &doc.tokens {
collect_trivia(token, &mut pieces);
if let Some(ty) = classify(token, &doc.semantics) {
pieces.push(Piece {
span: token.span,
ty,
modifiers: modifiers(token, &doc.semantics),
});
}
collect(token, &doc.semantics, &mut pieces);
}
flatten(pieces, doc)
}
@@ -151,13 +168,22 @@ fn within(tokens: Vec<Absolute>, range: Range) -> Vec<Absolute> {
tokens.into_iter().filter(|t| t.from() < range.end && range.start < t.to()).collect()
}
/// One token's pieces: its comments and the token itself.
///
/// Comments live as trivia on the token that follows (or, for a trailing
/// comment, precedes) them — including on the EOF token, which is what makes
/// a comment at the end of the file reachable.
fn collect_trivia(token: &Token, out: &mut Vec<Piece>) {
/// a comment at the end of the file reachable. They are pushed **in source
/// order** — leading comments, the token, then the trailing comment that sits
/// after it on the same line — because [`flatten`] converts the offsets with a
/// single forward cursor. Ordering is otherwise invisible: `flatten` sorts,
/// and no two pieces here can start at the same byte.
fn collect(token: &Token, semantics: &Semantics, out: &mut Vec<Piece>) {
for comment in &token.leading {
out.push(Piece { span: comment.span, ty: Highlight::Comment, modifiers: 0 });
}
if let Some(ty) = classify(token, semantics) {
out.push(Piece { span: token.span, ty, modifiers: modifiers(token, semantics) });
}
if let Some(comment) = &token.trailing {
out.push(Piece { span: comment.span, ty: Highlight::Comment, modifiers: 0 });
}
@@ -209,19 +235,37 @@ fn identifier_type(offset: u32, semantics: &Semantics) -> Highlight {
fn symbol_type(kind: SymbolKind) -> Highlight {
match kind {
SymbolKind::Module | SymbolKind::Class => Highlight::Class,
// The legend this server advertises has no `interface` token type,
// and its indices are the wire contract — adding one would renumber
// every highlight a live client already holds. An interface and a
// modport are type-like names, so they keep the `class` highlight a
// module has always had; a clocking block is a named block, and takes
// the `variable` one a block label takes.
SymbolKind::Module | SymbolKind::Class | SymbolKind::Interface | SymbolKind::Modport => {
Highlight::Class
}
SymbolKind::Package => Highlight::Namespace,
SymbolKind::Typedef => Highlight::Type,
SymbolKind::EnumVariant => Highlight::EnumMember,
SymbolKind::Param | SymbolKind::TfArg => Highlight::Parameter,
SymbolKind::Param | SymbolKind::LocalParam | SymbolKind::TfArg => Highlight::Parameter,
SymbolKind::Function | SymbolKind::Task => Highlight::Function,
SymbolKind::StructMember => Highlight::Property,
SymbolKind::StructMember
| SymbolKind::Constraint
| SymbolKind::Coverpoint
| SymbolKind::Cross => Highlight::Property,
// A covergroup is a type-like container, the way a class is, and the
// legend's indices are a wire contract that cannot gain a member.
SymbolKind::Covergroup => Highlight::Class,
SymbolKind::Port
| SymbolKind::Net
| SymbolKind::Var
| SymbolKind::Genvar
| SymbolKind::Instance
| SymbolKind::Clocking
| SymbolKind::Block => Highlight::Variable,
// A property and a sequence are named, instantiated by name and take
// arguments, so they highlight the way a function does.
SymbolKind::Property | SymbolKind::Sequence => Highlight::Function,
}
}
@@ -233,11 +277,18 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
/// multi-line macro invocation.
fn flatten(pieces: Vec<Piece>, doc: &Document) -> Vec<Absolute> {
let positions = doc.positions();
// The pieces arrive in source order (see [`collect`]), so one monotonic
// cursor measures each line once however many tokens sit on it. The
// per-call converter re-measures from the line's start every time, which
// is quadratic on a netlist's single million-byte line — seconds per
// viewport, measured. Out-of-order pieces (the fast path's window-edge
// comments) are answered identically, just without the saving.
let mut walker = positions.walker();
let mut flat: Vec<Absolute> = Vec::new();
for piece in pieces {
for line_span in split_lines(&doc.text, piece.span) {
let start = positions.position(line_span.start);
let end = positions.position(line_span.end);
let start = walker.position(line_span.start);
let end = walker.position(line_span.end);
if end.character <= start.character {
continue;
}
@@ -435,6 +486,44 @@ mod tests {
assert_eq!(comments[1].0, 3);
}
/// QA (fix-round re-verification): `collect_trivia` became `collect`,
/// folding two callers' duplicated classify-and-push into one function
/// that pushes a token's own piece *between* its leading comments and its
/// trailing one. A single token flanked by both is the shape that
/// exercises every branch of that function on one token, and `flatten`'s
/// stable sort means the exact byte offsets have to be right regardless
/// of the order `collect` happened to push them in.
#[test]
fn a_token_with_both_a_leading_and_a_trailing_comment_positions_all_three_pieces() {
let text = "/* lead */\nwire /* mid */ a;\n";
let out = decoded(text);
let comment = |n: usize| {
out.iter()
.filter(|&&(.., t, _)| t == Highlight::Comment as u32)
.nth(n)
.copied()
.unwrap_or_else(|| panic!("comment {n} missing in {out:?}"))
};
// Line 0: "/* lead */" is 10 bytes, all ASCII.
assert_eq!(comment(0), (0, 0, 10, Highlight::Comment as u32, 0));
// Line 1: "wire /* mid */ a;" — `wire` at 0..4, the comment at 5..14
// (9 bytes), `a` at 15.
let keyword = out
.iter()
.find(|&&(l, c, _, t, _)| l == 1 && c == 0 && t == Highlight::Keyword as u32)
.copied()
.expect("the `wire` keyword");
assert_eq!(keyword, (1, 0, 4, Highlight::Keyword as u32, 0));
assert_eq!(comment(1), (1, 5, 9, Highlight::Comment as u32, 0));
let ident = out
.iter()
.find(|&&(l, c, _, t, _)| l == 1 && c == 15 && t == Highlight::Variable as u32)
.copied()
.expect("the `a` identifier");
// `a` is a real declaration in this fragment's full semantics.
assert_eq!(ident, (1, 15, 1, Highlight::Variable as u32, DECLARATION));
}
#[test]
fn no_token_ever_spans_a_line_break() {
let text = "/* a\n b\n c */\nmodule m;\nendmodule\n";
@@ -594,6 +683,233 @@ mod tests {
assert!(windows_checked > 20, "the corpus really is checked out: {windows_checked}");
}
/// The legend's indices are the wire contract, so the three kinds added
/// on 2026-09-01 take existing highlights rather than new token types
/// (`docs/features/interface-semantics/README.md`). Pinned so a later
/// round that wants an `interface` token type has to *append* it — and
/// notice it is doing so.
#[test]
fn the_new_kinds_reuse_the_legend_rather_than_growing_it() {
assert_eq!(token_types().len(), 14, "the legend is a wire contract");
assert_eq!(symbol_type(SymbolKind::Interface), Highlight::Class);
assert_eq!(symbol_type(SymbolKind::Modport), Highlight::Class);
assert_eq!(symbol_type(SymbolKind::Clocking), Highlight::Variable);
let src = "interface bus_if;\nendinterface\n";
let name = decode(&tokens_of(src))
.into_iter()
.find(|&(line, col, ..)| line == 0 && col == 10)
.expect("the interface's name");
assert_eq!(name.3, Highlight::Class as u32);
}
// ------------------------------------------------------------------
// the large-file fast path's window
// ------------------------------------------------------------------
/// The classes a plain identifier can take once `Semantics` has spoken.
/// A fast-path buffer has no `Semantics`, so every one of them is
/// `variable` there — the one difference between the two paths, and the
/// one this normalization folds away so the rest can be compared.
fn coarse(ty: u32) -> u32 {
let refined = [
Highlight::Namespace,
Highlight::Class,
Highlight::Type,
Highlight::EnumMember,
Highlight::Parameter,
Highlight::Variable,
Highlight::Property,
Highlight::Function,
];
match refined.iter().any(|&r| r as u32 == ty) {
true => Highlight::Variable as u32,
false => ty,
}
}
/// Decoded tokens with the identifier refinement folded away.
fn coarsely(data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32)> {
decode(data).into_iter().map(|(l, c, len, ty, _)| (l, c, len, coarse(ty))).collect()
}
/// Whether any construct in `doc` crosses `offset` — a block comment, a
/// continued `` `define``, a multi-line macro call. A window boundary
/// inside one of those is exactly where the fast path is *documented* to
/// disagree, so the agreement property excludes them rather than
/// pretending they do not exist.
fn crosses(doc: &Document, offset: u32) -> bool {
doc.tokens.iter().any(|token| {
let spans = token
.leading
.iter()
.map(|c| c.span)
.chain(token.trailing.iter().map(|c| c.span))
.chain(std::iter::once(token.span));
spans.into_iter().any(|span| span.start < offset && offset < span.end)
})
}
/// **The agreement anchor.** For a window no multi-line construct reaches
/// into, the fast path's answer is the full pipeline's answer — same
/// spans, same lengths, same classes. Run over real corpus files, in the
/// forty-line windows an editor asks for.
#[test]
fn the_window_lexer_answers_what_the_full_pipeline_answers() {
let corpus = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let files = [
corpus.join("picorv32/picorv32.v"),
corpus.join("common_cells/src/fifo_v3.sv"),
corpus.join("common_cells/src/rr_arb_tree.sv"),
];
let (mut compared, mut skipped) = (0, 0);
for path in files {
let Ok(text) = std::fs::read_to_string(&path) else {
eprintln!("{} not checked out — skipping", path.display());
continue;
};
let full = Document::new(Some(path.clone()), text.clone(), &WorkspaceIndex::default());
let fast = Document::large(Some(path.clone()), text);
assert!(!full.tokens.is_empty(), "{}: the premise", path.display());
assert!(fast.tokens.is_empty(), "the fast path lexed nothing at open");
let lines = full.line_index.line_count();
let mut from = 0;
while from < lines {
let to = (from + 40).min(lines);
let window = range((from, 0), (to, 0));
// The two boundaries in bytes: the start of the first line and
// the end of the last line the window lexes.
let start = full.line_index.line_range(from + 1).map_or(0, |l| l.start);
let end =
full.line_index.line_range(to + 1).map_or(full.text.len() as u32, |l| l.end);
if crosses(&full, start) || crosses(&full, end) {
skipped += 1;
from = to;
continue;
}
assert_eq!(
coarsely(&semantic_tokens_in_window(&fast, window)),
coarsely(&semantic_tokens_in_range(&full, window)),
"{}: lines {from}..{to}",
path.display()
);
compared += 1;
from = to;
}
}
assert!(compared > 50, "the corpus really is checked out: {compared} (skipped {skipped})");
// The excluded windows are a small minority; if they ever became the
// majority the property would be vacuous.
assert!(skipped * 4 < compared, "too many windows excluded: {skipped} of {compared}");
}
#[test]
fn a_window_of_a_fast_path_buffer_is_self_contained_like_a_range_answer() {
let text = "module m;\n wire a;\n wire b;\nendmodule\n";
let doc = Document::large(None, text.to_string());
let data = semantic_tokens_in_window(&doc, range((2, 0), (3, 0)));
let first = data.first().expect("line 2 has tokens");
assert_eq!(first.delta_line, 2, "encoded from the start of the document");
assert_eq!(first.delta_start, 2, "the `wire` keyword's own column");
assert!(decode(&data).iter().all(|&(line, ..)| line == 2));
}
#[test]
fn a_fast_path_identifier_is_a_plain_variable_with_no_declaration_modifier() {
// The one documented difference: nothing analyzed the buffer, so the
// module name is not a `class` and carries no `declaration` bit.
let text = "module top;\nendmodule\n";
let doc = Document::large(None, text.to_string());
let data = decode(&semantic_tokens_in_window(&doc, range((0, 0), (1, 0))));
let name = data.iter().find(|&&(l, c, ..)| l == 0 && c == 7).expect("`top`");
assert_eq!(name.3, Highlight::Variable as u32);
assert_eq!(name.4, 0);
}
#[test]
fn a_fast_path_window_never_carries_a_token_from_outside_the_range() {
let text = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n";
let doc = Document::large(None, text.to_string());
let inside = decode(&semantic_tokens_in_window(&doc, range((2, 0), (3, 0))));
assert!(!inside.is_empty(), "premise: line 2 has tokens");
assert!(inside.iter().all(|&(line, ..)| line == 2), "{inside:?}");
}
/// QA (fix-round re-verification): the load-bearing claim behind the
/// walker's restart-on-backwards-offset behaviour is that a window's tail
/// comment genuinely arrives at `flatten` *after* every token in byte
/// order but is pushed into `pieces` *before* them (`semantic_tokens_in_window`
/// pushes `window.comments` ahead of the token loop). This reproduces that
/// exact shape through the real request path — a long declaration line
/// followed by a banner comment that never closes — and checks two
/// things: that the comment really is a byte-order tail relative to every
/// token (the premise the walker's reset exists for), and that every
/// token's and the comment's own position, once decoded off the wire,
/// matches what `Positions::position` would say for the same offset —
/// i.e. the single mid-window restart the out-of-order comment forces
/// does not corrupt anything that comes after it.
#[test]
fn a_window_edge_tail_comment_arrives_out_of_order_and_still_positions_correctly() {
let mut text = String::from("wire ");
for n in 0..500 {
text.push_str(&format!("a{n},"));
}
text.push_str("last;\n");
let declaration_line_len = text.len() as u32;
text.push_str("/* a banner that never closes\n");
let doc = Document::large(None, text.clone());
// The final `within` filter re-checks the *exact* requested LSP
// range (not the whole-line window `large::window` snapped to), so
// the end has to reach past the comment's own start on line 1 for it
// to survive onto the wire at all.
let window_range = range((0, 0), (1, 50));
let window = crate::large::window(&doc, window_range);
assert!(!window.tokens.is_empty(), "premise: the declaration line lexed");
assert_eq!(window.comments.len(), 1, "premise: the banner is one tail comment");
let comment_span = window.comments[0];
let last_token_end = window.tokens.iter().map(|t| t.span.end).max().expect("a token");
assert!(
comment_span.start >= declaration_line_len,
"premise: the comment opens on the second line, after every token byte-wise"
);
assert!(
comment_span.start >= last_token_end,
"premise: the out-of-order shape this test targets — the comment \
collected before the tokens in `pieces` has the higher byte offset"
);
let positions = doc.positions();
let decoded = decode(&semantic_tokens_in_window(&doc, window_range));
assert!(decoded.iter().any(|&(_, _, _, ty, _)| ty == Highlight::Comment as u32));
// Punctuation (`,`, `;`) is deliberately not classified at all, so it
// never reaches `pieces` — only the tokens `classify` keeps are
// expected on the wire.
for token in window.tokens.iter().filter(|t| classify(t, &doc.semantics).is_some()) {
let expected = positions.position(token.span.start);
let found = decoded
.iter()
.find(|&&(line, start, ..)| line == expected.line && start == expected.character);
assert!(
found.is_some(),
"token at byte {} expected at {expected:?}, not found in {decoded:?}",
token.span.start
);
}
let comment_expected = positions.position(comment_span.start);
assert!(
decoded.iter().any(|&(line, start, _, ty, _)| line == comment_expected.line
&& start == comment_expected.character
&& ty == Highlight::Comment as u32),
"comment at byte {} expected at {comment_expected:?}, not found in {decoded:?}",
comment_span.start
);
}
// ------------------------------------------------------------------
// `semanticTokens/full/delta`
// ------------------------------------------------------------------
+104 -11
View File
@@ -41,7 +41,8 @@
use lsp_types::{Location, Uri};
use vlog_parser::ast::{
AnsiPort, DataType, Declarator, GenBlock, GenElse, GenIf, Instantiation, Item, ItemKind,
Module, ParamPort, PortList, Stmt, StmtKind, TfArg, Typedef, TypedefKind,
Module, ParamPort, PortList, Stmt, StmtKind, StructType, TfArg, TypeExtra, Typedef,
TypedefKind,
};
use vlog_parser::TextRange;
use vlog_semantic::{Semantics, SymbolKind};
@@ -96,10 +97,13 @@ fn type_name(doc: &Document, offset: u32) -> Option<TextRange> {
fn type_use_at(doc: &Document, offset: u32) -> Option<TextRange> {
let reference = doc.semantics.reference_at(offset)?;
let kind = doc.semantics.symbol(reference.resolved()?)?.kind;
// `Module` is also an `interface` and a `program` — one node, one kind
// (`vlog_parser::ast::Module`).
// `Module` is also a `program` — one node, one kind
// (`vlog_parser::ast::Module`); an `interface` has its own since
// 2026-09-01, and is just as much a type a declaration may name.
match kind {
SymbolKind::Typedef | SymbolKind::Class | SymbolKind::Module => Some(reference.name_span),
SymbolKind::Typedef | SymbolKind::Class | SymbolKind::Module | SymbolKind::Interface => {
Some(reference.name_span)
}
_ => None,
}
}
@@ -168,7 +172,7 @@ fn item_site(item: &Item, offset: u32) -> Option<Site<'_>> {
ItemKind::DataDecl(d) => declarator_site(&d.ty, item.span, &d.declarators),
ItemKind::PortDecl(p) => declarator_site(&p.ty, item.span, &p.declarators),
ItemKind::ParamDecl(p) => declarator_site(&p.ty, item.span, &p.declarators),
ItemKind::Typedef(t) => alias_site(t, item.span),
ItemKind::Typedef(t) => alias_site(t, item.span, offset),
ItemKind::Instantiation(i) => instance_site(i, item.span),
ItemKind::Module(m) => module_site(m, offset),
ItemKind::Class(c) => param_port_site(c.param_ports.as_deref().unwrap_or(&[]), offset)
@@ -200,16 +204,36 @@ fn declarator_site<'a>(
site(&ty.name, TextRange::new(span.start, first))
}
/// `typedef state_t alias_t;` — the alias's own type. The other typedef
/// spellings declare their type inline (`enum`, `struct`) or promise one
/// elsewhere (`typedef class c;`), and so name nothing to jump to.
fn alias_site(t: &Typedef, span: TextRange) -> Option<Site<'_>> {
/// `typedef state_t alias_t;` — the alias's own type; and, since
/// struct-members (2026-09-01), a `typedef struct { hdr_t hdr; … }` body,
/// whose **fields** are declarations with types of their own and so have
/// somewhere to jump to. An `enum` body declares its type inline and a
/// `typedef class c;` promises one elsewhere, so both still name nothing.
fn alias_site(t: &Typedef, span: TextRange, offset: u32) -> Option<Site<'_>> {
match &t.kind {
TypedefKind::Alias(ty) => site(&ty.name, TextRange::new(span.start, t.name_span.start)),
TypedefKind::Struct(s) => struct_member_site(s, offset),
_ => None,
}
}
/// The field of a `struct`/`union` body the cursor is in, as a type site.
///
/// Inline nested bodies are descended first, so the innermost field wins — the
/// generated-register-package shape (`struct packed { struct packed { logic q;
/// } ctrl; }`) is nested arbitrarily deep. A field whose type *is* an inline
/// aggregate has no name to jump to, and falls out through [`site`]'s own
/// empty-name refusal rather than through a check here.
fn struct_member_site(s: &StructType, offset: u32) -> Option<Site<'_>> {
let member = s.members.iter().find(|m| m.span.contains(offset))?;
if let Some(TypeExtra::Struct(nested)) = member.ty.inline() {
if let Some(inner) = struct_member_site(nested, offset) {
return Some(inner);
}
}
declarator_site(&member.ty, member.span, &member.declarators)
}
/// `sub u_sub (...)`, and every interface instance written the same way. The
/// instance name's type is the module it instantiates.
fn instance_site(i: &Instantiation, span: TextRange) -> Option<Site<'_>> {
@@ -282,6 +306,11 @@ fn stmt_site(stmt: &Stmt, offset: u32) -> Option<Site<'_>> {
return None;
}
match &stmt.kind {
// A block-scoped typedef answers exactly as the item form does: the
// cursor on the alias name jumps one hop to the aliased type. Added
// when `StmtKind::Typedef` landed (testbench-mopup, 2026-08-29) —
// QA's blast-radius audit caught this arm missing.
StmtKind::Typedef(t) => alias_site(t, stmt.span, offset),
StmtKind::VarDecl(d) => declarator_site(&d.ty, stmt.span, &d.declarators),
StmtKind::ParamDecl(p) => declarator_site(&p.ty, stmt.span, &p.declarators),
StmtKind::PortDecl(p) => declarator_site(&p.ty, stmt.span, &p.declarators),
@@ -360,10 +389,74 @@ mod tests {
dir
}
// ------------------------------------------------------------------
// casts — `docs/features/comment-slots/README.md` (M11)
//
// The doc comment on `type_name` has always claimed case 2 "is what
// reaches a cast (`state_t'(0)`)". It only became true when `bind_expr`
// started binding the casting type; these pin it.
// ------------------------------------------------------------------
#[test]
fn a_cast_reaches_the_typedef_it_names() {
let text = "\
module m;
typedef logic [1:0] state_t;
logic [1:0] s;
initial s = state_t'(0);
endmodule
";
let (ws, uri) = document(text);
let cursor = text.rfind("state_t'").expect("the cast") as u32 + 2;
assert_eq!(jumps(&ws, &uri, cursor), vec![(1, 22)], "the `typedef` line's name");
}
#[test]
fn a_keyword_cast_asks_nothing_of_the_index() {
let text = "module m;\n initial x = int'(y);\nendmodule\n";
let (ws, uri) = document(text);
assert!(jumps(&ws, &uri, at(text, "int'") + 1).is_empty(), "`int` declares nothing");
}
#[test]
fn a_sized_or_computed_cast_answers_for_its_own_operand() {
// `$bits(t)'(x)` and `(N)'(x)` are widths, not type names: the cursor
// inside them is on an ordinary use, and answers as one.
let text = "\
module m;
typedef logic [3:0] nib_t;
initial a = $bits(nib_t)'(x);
endmodule
";
let (ws, uri) = document(text);
assert_eq!(jumps(&ws, &uri, at(text, "nib_t)") + 1), vec![(1, 22)], "the typedef");
}
// ------------------------------------------------------------------
// in-file types
// ------------------------------------------------------------------
#[test]
fn a_block_scoped_typedefs_alias_jumps_one_hop_to_its_type() {
// QA (testbench-mopup, 2026-08-29): the item-level alias hop worked,
// the new statement-level typedef silently answered nothing. Both
// forms now answer through the same alias_site.
let text = "\
module m;
typedef logic [7:0] byte_t;
initial begin
typedef byte_t word_t;
word_t w;
end
endmodule
";
let (ws, uri) = document(text);
assert!(
!jumps(&ws, &uri, at(text, "word_t;") + 3).is_empty(),
"the block-scoped alias hops to byte_t instead of answering nothing"
);
}
#[test]
fn a_variable_jumps_to_the_typedef_of_its_type() {
let text = "\
@@ -629,7 +722,7 @@ endmodule
fs::write(dir.join(name), text).expect("write");
}
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
ws.open_whole_workspace(vec![dir.clone()]);
let path = dir.join(which);
let uri = path_to_uri(&path).expect("uri");
let text = fs::read_to_string(&path).expect("read");
@@ -1280,7 +1373,7 @@ endmodule
return;
}
let mut ws = Workspace::default();
ws.open_roots(vec![root.clone()]);
ws.open_whole_workspace(vec![root.clone()]);
let open = |ws: &mut Workspace, rel: &str| -> (Uri, String) {
let file = root.join(rel);
+165 -109
View File
@@ -21,24 +21,15 @@
//! See `docs/features/type-hierarchy/README.md`.
use lsp_types::{Range, SymbolKind, TypeHierarchyItem, Uri};
use vlog_parser::ast::{ClassDecl, Item, ItemKind};
use vlog_parser::ast::Item;
use vlog_parser::{parse_source_tolerant, LineIndex, TextRange};
use vlog_semantic::classes::{self, Decl};
use vlog_semantic::{Definition, SymbolKind as SemanticKind};
use crate::convert::Positions;
use crate::state::{Document, Workspace};
use crate::uri::{path_to_uri, uri_to_path};
/// One class declaration: the node, and the extent of the whole
/// `class ... endclass` it was written as.
#[derive(Clone, Copy)]
struct Decl<'a> {
class: &'a ClassDecl,
/// Code extent of the declaration, attributes included — what a type
/// hierarchy item's `range` is.
span: TextRange,
}
/// The class the cursor names, as the root of a type hierarchy — its own
/// declaration, or any use of its name.
///
@@ -53,8 +44,9 @@ pub fn prepare(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Vec<TypeHierarc
let doc = ws.document(uri)?;
// The cursor on a declaration written in this buffer answers from the
// buffer, unsaved edits and all — no index lookup can beat that.
if let Some(decl) =
declarations(&doc.tree.items).into_iter().find(|decl| touches(decl.class.name_span, offset))
if let Some(decl) = classes::declarations(&doc.tree.items)
.into_iter()
.find(|decl| touches(decl.class.name_span, offset))
{
let positions = doc.positions();
return Some(vec![item(uri.clone(), &positions, decl)?]);
@@ -94,37 +86,38 @@ pub fn supertypes(ws: &Workspace, item: &TypeHierarchyItem) -> Vec<TypeHierarchy
/// Who extends this class, across the workspace.
///
/// Every in-scope file is walked, because the workspace index records what a
/// file *declares* and not what it extends — there is no edge table to consult,
/// exactly as there is none for instantiations
/// (`docs/features/hierarchy/README.md`). A file whose text does not contain
/// the name is skipped before it is parsed, which is what keeps the walk
/// affordable: `extends base` has to write `base`.
/// **A lookup in the workspace index's inheritance-edge table** since
/// 2026-08-27, where it used to be a re-read and re-parse of every in-scope
/// file. The edges are recorded by the same [`classes::declarations`] walk this
/// function used to run, at index time
/// (`docs/features/incremental-index/README.md`), so the answer and its order
/// are unchanged; only the files that really do extend the class are read now,
/// and only to turn the recorded byte spans into line/character ranges.
///
/// An empty name is answered with nothing rather than searched for: nothing
/// this server hands out is nameless, and the prefilter matches every file for
/// one, which would parse the whole workspace to find nothing.
/// An empty name is answered with nothing rather than looked up: nothing this
/// server hands out is nameless, and a nameless question has no answer.
pub fn subtypes(ws: &Workspace, item: &TypeHierarchyItem) -> Vec<TypeHierarchyItem> {
if item.name.is_empty() {
return Vec::new();
}
let index = ws.index();
let mut found: Vec<TypeHierarchyItem> = Vec::new();
for (path, text) in ws.sources() {
if !text.contains(&item.name) {
continue;
}
let Some(uri) = path_to_uri(&path) else { continue };
let (tree, _) = parse_source_tolerant(&text);
let edges = index.subclasses_of(&item.name);
let mut at = 0;
while at < edges.len() {
// The edges arrive in file order, so one file's are consecutive: read
// its text once and build every item it holds.
let file = edges[at].file;
let group = &edges[at..][..edges[at..].iter().take_while(|e| e.file == file).count()];
at += group.len();
let Some(path) = index.path(file) else { continue };
let Some(uri) = path_to_uri(path) else { continue };
let Some(text) = ws.text_of(path) else { continue };
let line_index = LineIndex::new(&text);
let positions = Positions::new(&text, &line_index);
for decl in declarations(&tree.items) {
if extends_name(decl.class) != Some(item.name.as_str()) {
continue;
}
if let Some(built) = self::item(uri.clone(), &positions, decl) {
found.push(built);
}
}
found.extend(group.iter().map(|edge| &edge.subclass).filter_map(|subclass| {
item_of(uri.clone(), &positions, &subclass.name, subclass.name_span, subclass.span)
}));
}
found.sort_by(|a, b| {
(a.uri.as_str(), key(a.selection_range)).cmp(&(b.uri.as_str(), key(b.selection_range)))
@@ -132,17 +125,15 @@ pub fn subtypes(ws: &Workspace, item: &TypeHierarchyItem) -> Vec<TypeHierarchyIt
found
}
/// The base class of one class declaration, as written — `None` when the
/// header has no `extends`.
/// The supertypes of the class an item names, in the file it names: the one
/// it `extends`, and every interface class it `implements`.
///
/// The name is the bare base: `extends base #(8)` stores `base`, because the
/// parser keeps the parameter overrides on their own field, so a parameterized
/// base needs no unwrapping here.
fn extends_name(class: &ClassDecl) -> Option<&str> {
class.extends.as_ref().map(|extends| extends.name.as_str())
}
/// The base classes of the class an item names, in the file it names.
/// Both clauses are edges of the same graph — a class's method set comes from
/// its base *and* from every interface it promises to implement — and both
/// resolve through the same hop, so they are read together here. `implements`
/// joined in `vendor-formal-grammar` (2026-09-02), when `interface class`
/// became an ordinary class declaration and there was finally something to
/// point at.
fn bases_of(
ws: &Workspace,
doc: &Document,
@@ -152,16 +143,24 @@ fn bases_of(
let positions = doc.positions();
let at = span(&positions, item.selection_range);
let Some(decl) = find_class(&doc.tree.items, &item.name, Some(at)) else { return Vec::new() };
let Some(extends) = decl.class.extends.as_ref() else { return Vec::new() };
if extends.name_span.is_empty() {
return Vec::new();
let mut out = Vec::new();
// The last byte of a supertype's name span. For `pkg::base` that is inside
// the *tail's* own reference, which is the one that names a class — the
// head names the package. For a bare `base` it is that one reference.
// Either way the answer comes from the same two layers
// `textDocument/definition` uses, so a supertype in another file needs no
// lookup of this feature's own.
if let Some(extends) = decl.class.extends.as_ref() {
if !extends.name_span.is_empty() {
out.extend(classes_at(ws, doc, uri, extends.name_span.end - 1));
}
}
// The last byte of the base-name span. For `pkg::base` that is inside the
// *tail's* own reference, which is the one that names a class — the head
// names the package. For a bare `base` it is that one reference. Either
// way the answer comes from the same two layers `textDocument/definition`
// uses, so a base in another file needs no lookup of this feature's own.
classes_at(ws, doc, uri, extends.name_span.end - 1)
for name in &decl.class.implements {
if !name.span.is_empty() {
out.extend(classes_at(ws, doc, uri, name.span.end - 1));
}
}
out
}
/// Every class declaration the name at `offset` resolves to, through both
@@ -200,20 +199,28 @@ fn classes_at(ws: &Workspace, doc: &Document, uri: &Uri, offset: u32) -> Vec<Typ
/// The hierarchy item for one class declaration, positioned against the text it
/// was parsed from.
fn item(uri: Uri, positions: &Positions, decl: Decl) -> Option<TypeHierarchyItem> {
let name_span = decl.class.name_span;
item_of(uri, positions, &decl.class.name, decl.class.name_span, decl.span)
}
/// [`item`] from the parts, for a caller reading them out of the index's
/// inheritance-edge table rather than off a parse tree.
fn item_of(
uri: Uri,
positions: &Positions,
name: &str,
name_span: TextRange,
span: TextRange,
) -> Option<TypeHierarchyItem> {
if name_span.is_empty() {
return None;
}
// The protocol requires `selectionRange` inside `range`; a declaration the
// parser could not close is the case where that may not hold, and there the
// name alone is the honest extent.
let full = if decl.span.start <= name_span.start && name_span.end <= decl.span.end {
decl.span
} else {
name_span
};
let full =
if span.start <= name_span.start && name_span.end <= span.end { span } else { name_span };
Some(TypeHierarchyItem {
name: decl.class.name.clone(),
name: name.to_string(),
// `interface class` is a different construct (IEEE 1800 §8.26) that
// `vlog_parser` does not model at all, so there is nothing here that
// could carry `SymbolKind::INTERFACE`.
@@ -250,34 +257,11 @@ fn item_in_file(
item(uri, &Positions::new(&text, &line_index), decl)
}
/// Every class declaration in `items`, wherever a class may be written: at file
/// scope, inside a `package`, inside a `module`, and nested inside another
/// class.
fn declarations(items: &[Item]) -> Vec<Decl<'_>> {
let mut out = Vec::new();
collect(items, &mut out);
out
}
fn collect<'a>(items: &'a [Item], out: &mut Vec<Decl<'a>>) {
for item in items {
match &item.kind {
ItemKind::Class(class) => {
out.push(Decl { class, span: item.span });
collect(&class.items, out);
}
ItemKind::Package { items, .. } => collect(items, out),
ItemKind::Module(module) => collect(&module.items, out),
_ => {}
}
}
}
/// The declaration of `name` in a parsed file: the one whose name sits at `at`,
/// else the first of that name.
fn find_class<'a>(items: &'a [Item], name: &str, at: Option<TextRange>) -> Option<Decl<'a>> {
let decls: Vec<Decl> =
declarations(items).into_iter().filter(|d| d.class.name == name).collect();
classes::declarations(items).into_iter().filter(|d| d.class.name == name).collect();
if let Some(at) = at {
if let Some(exact) = decls.iter().find(|d| d.class.name_span == at) {
return Some(*exact);
@@ -351,7 +335,7 @@ mod tests {
}
}
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let (path, text) = first.expect("at least one file");
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), text.to_string());
@@ -483,14 +467,18 @@ endmodule
}
#[test]
fn an_interface_class_is_not_a_node_because_the_parser_does_not_model_one() {
// `interface class` is a different construct (IEEE 1800 §8.26) that
// `vlog_parser` rejects, so it never becomes a `ClassDecl` and there is
// no item — and no `SymbolKind::INTERFACE` case — to build. Pinned so a
// future parser round that models it is forced past this test.
fn an_interface_class_is_a_node() {
// Was `..._is_not_a_node_because_the_parser_does_not_model_one` until
// `vendor-formal-grammar` (2026-09-02) made `interface class` an
// ordinary `ClassDecl` carrying the word in its prefix. It declares a
// class symbol, so it prepares like any other class — which is what
// gives the `implements` edge below something to point at.
let text = "interface class ic;\n pure virtual function void f();\nendclass\n";
let (_tree, ws, uri) = workspace("ifaceclass", &[("ic.sv", text)]);
assert!(prepare(&ws, &uri, at(text, "ic")).is_none());
let items = prepare(&ws, &uri, at(text, "ic")).expect("the interface class");
assert_eq!(items.len(), 1);
assert_eq!(items[0].name, "ic");
assert!(supertypes(&ws, &items[0]).is_empty(), "and it implements nothing");
}
#[test]
@@ -587,16 +575,30 @@ endclass
}
#[test]
fn an_implements_clause_names_no_supertype() {
// `implements` names an *interface* class, which `vlog_parser` does not
// model — so there is never a declaration to point at, and matching one
// by name would claim an unrelated ordinary class. Only `extends` is an
// edge here.
let base = "class base;\nendclass\n";
let child = "class child implements base;\nendclass\n";
let (_tree, ws, uri) = workspace("implements", &[("child.sv", child), ("base.sv", base)]);
fn an_implements_clause_names_a_supertype() {
// Was `..._names_no_supertype` until `vendor-formal-grammar`
// (2026-09-02): `implements` names an interface class, and now that one
// is a `ClassDecl` there is a declaration to point at. The hop is the
// same one `extends` takes, so a supertype in another file works with
// no lookup of this feature's own.
let base = "interface class api;\n pure virtual function void f();\nendclass\n";
let child = "class child implements api;\nendclass\n";
let (_tree, ws, uri) = workspace("implements", &[("child.sv", child), ("api.sv", base)]);
let root = prepare(&ws, &uri, at(child, "child")).expect("child")[0].clone();
assert!(supertypes(&ws, &root).is_empty(), "pinning today's answer and its reason");
let bases = supertypes(&ws, &root);
assert_eq!(shape(&bases[0]), ("api".to_string(), "api.sv".to_string(), 0));
}
#[test]
fn extends_and_implements_are_both_edges_of_the_same_answer() {
let api = "interface class api;\nendclass\n";
let base = "class base;\nendclass\n";
let child = "class child extends base implements api;\nendclass\n";
let (_tree, ws, uri) =
workspace("both", &[("child.sv", child), ("base.sv", base), ("api.sv", api)]);
let root = prepare(&ws, &uri, at(child, "child")).expect("child")[0].clone();
let names: Vec<String> = supertypes(&ws, &root).iter().map(|i| i.name.clone()).collect();
assert_eq!(names, ["base", "api"], "the base first, then the interfaces, in source order");
}
#[test]
@@ -718,7 +720,7 @@ endclass
tree.write("files.f", "base.sv\n");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
ws.open_whole_workspace(vec![tree.path.clone()]);
let base_uri = path_to_uri(&tree.path.join("base.sv")).expect("uri");
ws.set_document(base_uri.clone(), BASE.to_string());
@@ -727,9 +729,14 @@ endclass
}
#[test]
fn an_unsaved_extends_is_a_subtype_before_it_is_saved() {
// The sources a walk reads are the open buffers overlaid on disk, so a
// just-typed `extends` counts.
fn an_edited_buffers_extends_counts_from_the_moment_the_index_sees_it() {
// Superseded this round (incremental-index, 2026-08-27):
// `an_unsaved_extends_is_a_subtype_before_it_is_saved` pinned the walk
// over `Workspace::sources()`, so a keystroke in another buffer moved
// the answer before anything rebuilt. Subtypes are the index's
// inheritance-edge table now — as of its last build or update, both of
// which fold every open buffer in. Same rule as the call hierarchy's
// census, pinned from both sides.
let (tree, mut ws, uri) = two("unsaved");
let root = prepare(&ws, &uri, at(CHILD, "extends base") + 8).expect("base")[0].clone();
assert_eq!(subtypes(&ws, &root).len(), 1, "premise");
@@ -737,7 +744,13 @@ endclass
let fresh = tree.path.join("child.sv");
let child_uri = path_to_uri(&fresh).expect("uri");
ws.set_document(child_uri, "class child;\nendclass\n".to_string());
assert!(subtypes(&ws, &root).is_empty(), "the buffer took the `extends` away");
assert_eq!(
subtypes(&ws, &root).len(),
1,
"the buffer alone does not move the answer — the index has not seen it"
);
assert!(ws.update_one(&fresh), "the file is in scope, so one file is enough");
assert!(subtypes(&ws, &root).is_empty(), "the edit took the `extends` away");
}
// ------------------------------------------------------------------
@@ -1088,6 +1101,49 @@ endclass
// the corpus, smoke-tested
// ------------------------------------------------------------------
/// What `subtypes` costs after the inheritance-edge table, against the
/// workspace walk it replaced. `#[ignore]`d: it prints a number rather
/// than asserting one — the budget is asserted in
/// `the_corpus_uvm_classes_answer_all_three_requests`.
#[test]
#[ignore]
fn qa_perf_subtypes_lookup_against_the_walk_it_replaced() {
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let lib = corpus.join("ibex/dv/uvm/core_ibex/tests/core_ibex_test_lib.sv");
let Ok(text) = fs::read_to_string(&lib) else {
eprintln!("core_ibex_test_lib.sv is not in this corpus — skipping");
return;
};
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![corpus]);
let uri = path_to_uri(&lib).expect("uri");
ws.set_document(uri.clone(), text.clone());
let offset = at(&text, "class core_ibex_debug_intr_basic_test") + 6;
let child = prepare(&ws, &uri, offset).expect("the class")[0].clone();
let base = supertypes(&ws, &child).first().cloned().expect("core_ibex_base_test");
let mut lookup = std::time::Duration::ZERO;
let mut walk = std::time::Duration::ZERO;
for _ in 0..3 {
let started = std::time::Instant::now();
let found = subtypes(&ws, &base);
lookup = lookup.max(started.elapsed());
assert!(!found.is_empty());
let started = std::time::Instant::now();
let _ = ws.sources();
walk = walk.max(started.elapsed());
}
eprintln!(
"typeHierarchy/subtypes over {} files: {lookup:?}; one workspace walk (what it \
used to begin with) is {walk:?}",
ws.index().files().len()
);
}
/// Every class of a real UVM-shaped corpus file, through all three
/// requests, plus one known `extends` chain. Skipped when `corpus/` is not
/// checked out (`tools/corpus_fetch.sh`), like the other corpus tests.
@@ -1104,7 +1160,7 @@ endclass
return;
};
let mut ws = Workspace::default();
ws.open_roots(vec![corpus]);
ws.open_whole_workspace(vec![corpus]);
let uri = path_to_uri(&lib).expect("uri");
ws.set_document(uri.clone(), text.clone());
let files = ws.index().files().len();
@@ -1113,7 +1169,7 @@ endclass
// every item the protocol's containment rule.
let doc = ws.document(&uri).expect("the open buffer");
let names: Vec<String> =
declarations(&doc.tree.items).iter().map(|d| d.class.name.clone()).collect();
classes::declarations(&doc.tree.items).iter().map(|d| d.class.name.clone()).collect();
assert!(names.len() > 20, "the file really is class-heavy: {}", names.len());
let mut with_a_base = 0;
for name in &names {
+24 -1
View File
@@ -8,7 +8,7 @@
//! module asks it to say what it sees. See
//! `docs/features/file-watching/README.md`.
use std::path::Path;
use std::path::{Path, PathBuf};
use lsp_types::notification::{DidChangeWatchedFiles, Notification as _};
use lsp_types::{
@@ -112,6 +112,29 @@ pub fn touches_scope(changes: &[FileEvent], filelist: Option<&Path>) -> bool {
.any(|path| watched(&path, filelist))
}
/// The one file an event named, when it named exactly one and that one is not
/// the filelist.
///
/// The gate on the incremental rescan path (`server.rs`'s `reindex_one`): a
/// checkout fills this list, and a list of one is the case a single file's
/// contribution can be replaced in place. The filelist is excluded because a
/// change to it moves the whole scope, which is a rebuild by definition. An
/// event naming the same path twice — a client is free to send `Changed` and
/// `Created` for one file — is still one file.
pub fn one_scope_file(changes: &[FileEvent], filelist: Option<&Path>) -> Option<PathBuf> {
let mut named: Vec<PathBuf> = changes
.iter()
.filter_map(|change| uri_to_path(&change.uri))
.filter(|path| watched(path, filelist))
.collect();
named.sort();
named.dedup();
match named.as_slice() {
[only] if Some(only.as_path()) != filelist => Some(only.clone()),
_ => None,
}
}
/// Whether one path is something the index reads: a source file, or the
/// filelist that decides which source files there are.
///
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -20,8 +20,9 @@ module counter_properties;
assume property (@(posedge clk_i) (!init) |-> !rst_ni);
endmodule
====
# a multi-line property spec keeps its own line structure, re-indented as a
# whole -- exactly what a `constraint` block does
# a multi-line property spec is laid out by the round's one rule: the clocking
# event, the `disable iff` and the property expression one per line, one indent
# inside the parentheses, when the three do not fit on one
# corpus/common_cells/formal/counter_properties.sv:48-50
module counter_properties;
assert property (@(posedge clk_i)
@@ -31,8 +32,8 @@ endmodule
----
module counter_properties;
assert property (@(posedge clk_i)
disable iff (!rst_ni)
(count_up && !resetting) |=> q_o == $past(q_o) + {{WIDTH-1{1'b0}}, 1'b1});
disable iff (!rst_ni)
(count_up && !resetting) |=> q_o == $past(q_o) + {{WIDTH - 1{1'b0}}, 1'b1});
endmodule
====
# `cover property` and `restrict property`; `restrict` is not a lexer keyword,
@@ -64,9 +65,7 @@ LoadMemEarlyResp: assume property (
early_resp |-> data_rdata_i == spec_mem_read_fst_rdata
);
----
LoadMemEarlyResp: assume property (
early_resp |-> data_rdata_i == spec_mem_read_fst_rdata
);
LoadMemEarlyResp: assume property (early_resp |-> data_rdata_i == spec_mem_read_fst_rdata);
====
# an `else` action block, at item position inside a generate `begin`
# corpus/common_cells/test/fifo_tb.sv:155-156
@@ -80,7 +79,7 @@ endmodule
module fifo_tb;
if (FALL_THROUGH) begin
assert property (@(posedge clk_i) ((empty & ~push) ##1 push) |-> rdata == wdata)
else $error("Input did not fall through");
else $error("Input did not fall through");
end
endmodule
====
@@ -95,18 +94,21 @@ endmodule
----
module clk_int_div_static_tb;
for (genvar i = 1; i < MaxClkDiv; i++) begin : gen_clk_divs
assert_period_period: assert property (@(posedge clk_out[i]) T_clk(TClkIn*i)) else
$error("Output period of div %d clock is incorrect.", i);
assert_period_period: assert property (@(posedge clk_out[i]) T_clk(TClkIn * i))
else $error("Output period of div %d clock is incorrect.", i);
end
endmodule
====
# both halves of an action block: pass statement, then `else`
# both halves of an action block: pass statement, then `else`. A pass
# statement that is not a block puts the `else` on the next line, which is
# what a statement `if` already does with a non-block then-branch.
module m;
assert property (@(posedge clk) w) $info("pass"); else $error("fail");
endmodule
----
module m;
assert property (@(posedge clk) w) $info("pass"); else $error("fail");
assert property (@(posedge clk) w) $info("pass");
else $error("fail");
endmodule
====
# an action block written as a `begin`/`end` block, with no trailing `;`
@@ -137,7 +139,7 @@ endmodule
module prim_alert_sender;
if (AsyncOn) begin : gen_async_assert
sequence PingSigInt_S;
alert_rx_i.ping_p == alert_rx_i.ping_n [*2];
alert_rx_i.ping_p == alert_rx_i.ping_n[*2];
endsequence
end
endmodule
@@ -156,11 +158,10 @@ endmodule
----
module clk_int_div_static_tb;
property T_clk(real clk_period);
realtime current_time;
realtime actual_period;
realtime current_time;
realtime actual_period;
disable iff (!rstn || !enable)
(('1, current_time = $realtime)) |=>
('1, actual_period = $realtime - current_time);
(('1, current_time = $realtime)) |=> ('1, actual_period = $realtime - current_time);
endproperty : T_clk
endmodule
====
@@ -212,7 +213,9 @@ module m;
wire w;
endmodule
====
# a comment written *inside* the captured span stays inside it, printed once
# a comment written between the clocking event and the property expression has
# a slot of its own (`PropSpec::before_expr`) and prints back between the same
# two tokens
module m;
assert property (@(posedge clk)
// only while enabled
@@ -221,8 +224,8 @@ endmodule
----
module m;
assert property (@(posedge clk)
// only while enabled
en |-> ready);
// only while enabled
en |-> ready);
endmodule
====
# a `// verilog_format: off` fence still wins: every byte as written
@@ -250,24 +253,28 @@ else $error("line one
endmodule
----
module m;
assert property (@(posedge clk) a |-> b)
else $error("line one
assert property (@(posedge clk) a |-> b) else $error("line one
line two indented");
endmodule
====
# a property spec far past the line limit is *not* broken: the property
# expression is a grammar lucisv does not model, so it is reproduced as written
# a property spec far past the line limit *is* broken now: `sva-bodies` gave
# the property expression a grammar, so the one layout rule applies -- the
# clocking event, the `disable iff` and the expression one per line
module m;
assert property (@(posedge clk_i) disable iff (!rst_ni) some_very_long_signal_name_here |-> ##[1:3] another_quite_long_signal_name);
endmodule
----
module m;
assert property (@(posedge clk_i) disable iff (!rst_ni) some_very_long_signal_name_here |-> ##[1:3] another_quite_long_signal_name);
assert property (@(posedge clk_i)
disable iff (!rst_ni)
some_very_long_signal_name_here |-> ##[1:3] another_quite_long_signal_name);
endmodule
====
# an action block whose pass statement is an `if` with a `begin ... end`
# body: the block -- and the `else` after it -- belong to the assertion,
# and the item after it survives
# body. The `else` binds to the nearest `if`, which is the dangling-else rule
# the language has everywhere -- the pre-`sva-bodies` text scan could not see
# that, and read it as the assertion's own fail arm. Same tokens either way;
# the item after it still survives.
module m;
always @(posedge clk)
assert property (@(posedge clk) a |-> b)
@@ -283,8 +290,7 @@ module m;
assert property (@(posedge clk) a |-> b)
if (cond) begin
x = 1;
end
else y = 2;
end else y = 2;
wire w;
endmodule
====
@@ -309,8 +315,7 @@ module m;
begin
disable fork;
end
join_none
else $error("no");
join_none else $error("no");
wire w;
endmodule
====
+41 -14
View File
@@ -1,10 +1,10 @@
# a bind directive is a module instantiation with a target scope in front
module m;
bind target_mod checker u_chk(.a(x),.b(y));
bind target_mod chk_mod u_chk(.a(x),.b(y));
endmodule
----
module m;
bind target_mod checker u_chk (.a(x), .b(y));
bind target_mod chk_mod u_chk (.a(x), .b(y));
endmodule
====
# implicit named connections, target on its own line
@@ -171,11 +171,11 @@ endmodule
====
# a hierarchical target path
module m;
bind top.u_dut.u_core checker u_chk(.*);
bind top.u_dut.u_core chk_mod u_chk(.*);
endmodule
----
module m;
bind top.u_dut.u_core checker u_chk (.*);
bind top.u_dut.u_core chk_mod u_chk (.*);
endmodule
====
# a bind directive at top level, outside any module
@@ -187,7 +187,7 @@ bind cpu cpu_assert u_cpu_assert (.clk_i, .rst_ni);
module m;
generate
if (Enable) begin : g_chk
bind sub checker u_chk(.*);
bind sub chk_mod u_chk(.*);
end
endgenerate
endmodule
@@ -195,7 +195,7 @@ endmodule
module m;
generate
if (Enable) begin : g_chk
bind sub checker u_chk (.*);
bind sub chk_mod u_chk (.*);
end
endgenerate
endmodule
@@ -203,7 +203,7 @@ endmodule
# comments attached to a bind directive are kept
module m;
// bind the checker in
bind dut checker u_chk (
bind dut chk_mod u_chk (
// clock and reset come in implicitly
.clk_i,
.rst_ni // active low
@@ -212,7 +212,7 @@ endmodule
----
module m;
// bind the checker in
bind dut checker u_chk (
bind dut chk_mod u_chk (
// clock and reset come in implicitly
.clk_i,
.rst_ni // active low
@@ -221,7 +221,7 @@ endmodule
====
# an `ifdef inside the connection list of a bind
module m;
bind dut checker u_chk (
bind dut chk_mod u_chk (
.clk_i,
`ifdef FPV
.fpv_only_i,
@@ -231,7 +231,7 @@ module m;
endmodule
----
module m;
bind dut checker u_chk (
bind dut chk_mod u_chk (
.clk_i,
`ifdef FPV
.fpv_only_i,
@@ -243,16 +243,16 @@ endmodule
# a bind directive inside a `verilog_format: off` fence is untouched
module m;
// verilog_format: off
bind dut checker u_chk ( .clk_i ,.rst_ni );
bind dut chk_mod u_chk ( .clk_i ,.rst_ni );
// verilog_format: on
bind dut2 checker u_chk2 ( .clk_i ,.rst_ni );
bind dut2 chk_mod u_chk2 ( .clk_i ,.rst_ni );
endmodule
----
module m;
// verilog_format: off
bind dut checker u_chk ( .clk_i ,.rst_ni );
bind dut chk_mod u_chk ( .clk_i ,.rst_ni );
// verilog_format: on
bind dut2 checker u_chk2 (.clk_i, .rst_ni);
bind dut2 chk_mod u_chk2 (.clk_i, .rst_ni);
endmodule
====
# at the line-length boundary: exactly 100 columns stays on one line
@@ -317,3 +317,30 @@ module m;
dut checker_mod c_inst (.clk(clk));
endmodule
====
====
# an indexed hierarchical target -- binding SVA into a generate array (coverage_gaps M6)
module tb;
bind top.gen[0].u_core chk c_inst (.clk(clk));
endmodule
----
module tb;
bind top.gen[0].u_core chk c_inst (.clk(clk));
endmodule
====
# a selector on the head alone, with an expression inside it
module tb;
bind arr[N-1] chk c (.*);
endmodule
----
module tb;
bind arr[N-1] chk c (.*);
endmodule
====
# an escaped segment keeps the whitespace that terminates it
module tb;
bind \my-inst .u_core chk c (.*);
endmodule
----
module tb;
bind \my-inst .u_core chk c (.*);
endmodule
+11 -10
View File
@@ -189,7 +189,7 @@ function void dv_base_mem::set_enable(bit enable);
this.enable = enable;
endfunction
====
# a constraint block is reproduced byte for byte, only re-indented
# a constraint block: one item per line, at one indent step inside the header
class item;
constraint c_branch_addr_alignment {
// The branch address is always required to be half-word aligned.
@@ -208,7 +208,7 @@ class item;
}
endclass
====
# a constraint written at column 1 is re-indented into the class body
# a constraint written at column 1 takes the class body's indent, body and all
class item;
constraint c_dist {
num_insns dist { 0 :/ 5, [1:20] :/ 20, [21:100] :/ 1 };
@@ -217,11 +217,12 @@ endclass
----
class item;
constraint c_dist {
num_insns dist { 0 :/ 5, [1:20] :/ 20, [21:100] :/ 1 };
num_insns dist {0 :/ 5, [1:20] :/ 20, [21:100] :/ 1};
}
endclass
====
# a covergroup is reproduced byte for byte too, endgroup label included
# a covergroup is laid out canonically since the covergroup-bodies round: the
# header on one line, one cover item per line, the endgroup label kept
class cov;
covergroup branch_dest_cg with function sample (bit [31:0] addr);
coverpoint addr {
@@ -232,10 +233,10 @@ class cov;
endclass
----
class cov;
covergroup branch_dest_cg with function sample (bit [31:0] addr);
covergroup branch_dest_cg with function sample(bit [31:0] addr);
coverpoint addr {
bins zero = { 0 };
bins mid = default;
bins zero = {0};
bins mid = default;
}
endgroup : branch_dest_cg
endclass
@@ -477,7 +478,7 @@ class c;
constraint x;
endclass
====
# a string inside a constraint keeps its bytes when the block is re-indented
# a string inside a constraint keeps its bytes when the block is laid out
class c;
constraint x {
name == "a
@@ -487,9 +488,9 @@ endclass
----
class c;
constraint x {
name == "a
name == "a
b";
}
}
endclass
====
# a shallow copy: `new <expression>` (IEEE 1800 8.12)
@@ -0,0 +1,239 @@
# Round 2 of the testbench wave: clocking-block signal bindings, the standing
# `default disable iff`, `iff` on an event-control term, a bare event control
# naming an indexed hierarchical path, a gate's drive strength, and `program`.
# See docs/features/clocking-wave/README.md. Every case here is a shape the
# OpenTitan sweep contains.
# --- clocking_decl_assign: `output tms = _tms_internal;` (IEEE 1800 §14.4) ---
# The binding prints on the item's own line. Nothing here is breakable: the
# bound expression is a signal name, and the body was already one item per line.
interface jtag_if;
clocking host_cb @(negedge tck);
default output #1ns;
output tms = _tms_internal;
output tdi = _tdi_internal;
input tdo;
endclocking
endinterface
----
interface jtag_if;
clocking host_cb @(negedge tck);
default output #1ns;
output tms = _tms_internal;
output tdi = _tdi_internal;
input tdo;
endclocking
endinterface
====
# a direction group may bind several signals, and the value is a real expression
interface i;
clocking cb @(posedge clk_i);
input pwrmgr_data = pwrmgr_data_o_i, keymgr_data = keymgr_data_o_i;
output #2 h2d = h2d_int[1], d2h;
inout x = a.b.c;
endclocking
endinterface
----
interface i;
clocking cb @(posedge clk_i);
input pwrmgr_data = pwrmgr_data_o_i, keymgr_data = keymgr_data_o_i;
output #2 h2d = h2d_int[1], d2h;
inout x = a.b.c;
endclocking
endinterface
====
# a clocking block in a module, with comments around the bindings
module tb;
clocking cb @(posedge clk);
// driven by the sequence
output req = req_int; // through the internal net
input rsp;
endclocking
endmodule
----
module tb;
clocking cb @(posedge clk);
// driven by the sequence
output req = req_int; // through the internal net
input rsp;
endclocking
endmodule
====
# --- `default disable iff expr;` (IEEE 1800 §16.12), kept verbatim ---
# It governs the concurrent assertions in its scope, which are verbatim too, so
# it is copied out by span: the bytes are reproduced, the indent is the item's.
module m;
bit disable_sva;
default disable iff disable_sva || !rst_ni;
default disable iff !rst_n;
endmodule
----
module m;
bit disable_sva;
default disable iff disable_sva || !rst_ni;
default disable iff !rst_n;
endmodule
====
# it stands inside a generate block next to a `default clocking` and assertions
module m;
if (1) begin : gen_checks
default disable iff !rst_n || en != On;
default clocking @(posedge clk); endclocking
CheckA: assert property (a |=> b) else `uvm_error("CheckA", "no")
end
endmodule
----
module m;
if (1) begin : gen_checks
default disable iff !rst_n || en != On;
default clocking @(posedge clk);
endclocking
CheckA: assert property (a |=> b) else `uvm_error("CheckA", "no")
end
endmodule
====
# --- `iff` on an event-control term (IEEE 1800 §9.4.2) ---
module m;
initial begin
@(posedge clk iff rvalid);
@(negedge clk_i iff (write ? sram_we : sram_req));
@(posedge cfg.vif.enable iff cfg.vif.rst_n);
end
endmodule
----
module m;
initial begin
@(posedge clk iff rvalid);
@(negedge clk_i iff (write ? sram_we : sram_req));
@(posedge cfg.vif.enable iff cfg.vif.rst_n);
end
endmodule
====
# the gate belongs to its own term: both separators keep working around it
module m;
always @(posedge a iff en or negedge b) x <= 1;
always @(posedge a iff en, negedge b iff en2) y <= 1;
always @(a iff b) z <= 1;
endmodule
----
module m;
always @(posedge a iff en or negedge b) x <= 1;
always @(posedge a iff en, negedge b iff en2) y <= 1;
always @(a iff b) z <= 1;
endmodule
====
# --- a bare event control naming an indexed hierarchical path ---
# `@name` is printed back without parens; the bit-selects on the path are part
# of the name (IEEE 1800 §A.9.3), so nothing about the shape changes.
class c;
task wait_for_ready();
forever @cfg.m_alert_agent_cfgs["fatal_cnsty_fault"].vif.sender_cb begin
if (done) return;
end
endtask
endclass
----
class c;
task wait_for_ready();
forever @cfg.m_alert_agent_cfgs["fatal_cnsty_fault"].vif.sender_cb begin
if (done) return;
end
endtask
endclass
====
# --- a gate's drive strength, single and paired (IEEE 1800 §28.3) ---
module m;
for (genvar i = 0; i < 4; i++) begin : gen_tri_state
pullup (weak1) pd_in_i (si_pulldown[i]);
pulldown (supply0, supply1) pd_out_i (so_pulldown[i]);
end
and (strong0, strong1) g1 (o, a, b), g2 (o2, c, d);
assign (weak0, pull1) w = 1'b1;
endmodule
----
module m;
for (genvar i = 0; i < 4; i++) begin : gen_tri_state
pullup (weak1) pd_in_i (si_pulldown[i]);
pulldown (supply0, supply1) pd_out_i (so_pulldown[i]);
end
and (strong0, strong1) g1 (o, a, b), g2 (o2, c, d);
assign (weak0, pull1) w = 1'b1;
endmodule
====
# a gate whose first argument is parenthesized is still an argument, not a
# strength: only a strength keyword after the `(` opens one.
module m;
buf b1 ((a & b), c);
not (o, (x | y));
endmodule
----
module m;
buf b1 ((a & b), c);
not (o, (x | y));
endmodule
====
# --- `program ... endprogram` (IEEE 1800 §24.3): a module header, a module
# body, a different closer.
program spiflash #(
parameter int unsigned FlashSize = 1024,
parameter bit EnFastSim = 1'b1
) (
input logic csb,
input logic sck
);
logic [7:0] cmd;
initial begin
cmd = 8'h0;
end
task automatic step();
@(posedge sck iff !csb);
endtask
endprogram : spiflash
----
program spiflash #(
parameter int unsigned FlashSize = 1024,
parameter bit EnFastSim = 1'b1
) (input logic csb, input logic sck);
logic [7:0] cmd;
initial begin
cmd = 8'h0;
end
task automatic step();
@(posedge sck iff !csb);
endtask
endprogram : spiflash
====
# --- a macro invocation as a concurrent assertion's action statement ---
# `else `ASSERT_ERROR(A)` ends with the macro; there is no `;` to scan to.
module m;
FsmStateSwReset_A:
assert property (rst |=> state == Reset)
else `ASSERT_ERROR(FsmStateSwReset_A)
assign x = 1;
Other_A: assert property (c) else `uvm_error("a", "b");
endmodule
----
module m;
FsmStateSwReset_A: assert property (rst |=> state == Reset) else `ASSERT_ERROR(FsmStateSwReset_A)
assign x = 1;
Other_A: assert property (c) else `uvm_error("a", "b");
endmodule
====
# ... and the other side of that decision: when the macro expands to a signal
# name, the statement runs on past it and ends at its own `;`. All four shapes
# round-trip byte-for-byte, exactly as they did before the macro case existed.
module m;
A_A: assert property (a) else `SOME_SIGNAL = 1'b1;
B_B: assert property (b) else `MSG(x) + 1;
C_C: assert property (c) else `CNT <= `CNT + 1;
D_D: assert property (d) else `CNT++;
assign y = 1;
endmodule
----
module m;
A_A: assert property (a) else `SOME_SIGNAL = 1'b1;
B_B: assert property (b) else `MSG(x) + 1;
C_C: assert property (c) else `CNT <= `CNT + 1;
D_D: assert property (d) else `CNT++;
assign y = 1;
endmodule
@@ -0,0 +1,424 @@
# Every comment slot `docs/features/comment-slots/README.md` added, one case
# per slot, with the comment written exactly where the slot owns it. The
# numbers in the comments are positions, not content: `/*1*/` is the first
# gap of the construct, `/*2*/` the second, and so on, so a comment that
# drifts across a token shows up as a renumbering rather than as a diff you
# have to squint at.
#
# A comment inside a bracket pair forces that pair open, which is why a few
# of these lay out across several lines. That is the same rule a comment
# inside a port list has always followed.
# a postfix member and scope chain, both gaps of each joiner
module m;
assign y = a /*1*/ . /*2*/ b;
assign z = pkg /*3*/ :: /*4*/ item;
endmodule
----
module m;
assign y = a /*1*/ . /*2*/ b;
assign z = pkg /*3*/ :: /*4*/ item;
endmodule
====
# an index expression, all three of its slots
module m;
assign y = q /*1*/ [ /*2*/ i /*3*/ ];
endmodule
----
module m;
assign y = q /*1*/ [ /*2*/ i /*3*/ ];
endmodule
====
# a part-select range, all five of its slots
module m;
assign y = q /*1*/ [ /*2*/ hi /*3*/ : /*4*/ lo /*5*/ ];
assign z = q[hi /*6*/ -: /*7*/ w];
endmodule
----
module m;
assign y = q /*1*/ [ /*2*/ hi /*3*/ : /*4*/ lo /*5*/ ];
assign z = q[hi /*6*/ -: /*7*/ w];
endmodule
====
# a value range inside an `inside` set
module m;
assign y = a inside {[ /*1*/ 0 /*2*/ : /*3*/ 3 /*4*/ ], 7};
endmodule
----
module m;
assign y = a inside {[ /*1*/ 0 /*2*/ : /*3*/ 3 /*4*/ ], 7};
endmodule
====
# the `inside` operator keeps a comment on each of its sides
module m;
assign y = a /*1*/ inside /*2*/ {1, 2};
endmodule
----
module m;
assign y = a /*1*/ inside /*2*/ {1, 2};
endmodule
====
# a packed dimension's own five slots
module m;
logic /*1*/ [ /*2*/ 7 /*3*/ : /*4*/ 0 /*5*/ ] w;
endmodule
----
module m;
logic /*1*/ [ /*2*/ 7 /*3*/ : /*4*/ 0 /*5*/ ] w;
endmodule
====
# a dynamic and an associative dimension keep what stands between the brackets
module m;
int q[ /*1*/ ];
int a[ /*2*/ * /*3*/ ];
endmodule
----
module m;
int q [ /*1*/ ];
int a [ /*2*/ * /*3*/ ];
endmodule
====
# a statement's own `;` gap, every kind that owns one
module m;
initial begin
x = 1 /*1*/ ;
y <= 2 /*2*/ ;
f(x) /*3*/ ;
-> ev /*4*/ ;
#10 /*5*/ ;
end
endmodule
----
module m;
initial begin
x = 1 /*1*/ ;
y <= 2 /*2*/ ;
f(x) /*3*/ ;
-> ev /*4*/ ;
#10 /*5*/ ;
end
endmodule
====
# a `return`, a `break` and a `continue` keep the gap before their `;`
class c;
function int f();
break /*1*/ ;
continue /*2*/ ;
return /*3*/ x /*4*/ ;
endfunction
endclass
----
class c;
function int f();
break /*1*/ ;
continue /*2*/ ;
return /*3*/ x /*4*/ ;
endfunction
endclass
====
# a statement `if` header's keyword gap
module m;
initial if /*1*/ (a) x = 1;
endmodule
----
module m;
initial if /*1*/ (a) x = 1;
endmodule
====
# a statement `case` header's keyword gap and a `default` label's colon
module m;
always_comb begin
case /*1*/ (sel)
2'd0: y = a;
default /*2*/ : y = c;
endcase
end
endmodule
----
module m;
always_comb begin
case /*1*/ (sel)
2'd0: y = a;
default /*2*/ : y = c;
endcase
end
endmodule
====
# a statement `foreach` header, all four of its slots
module m;
initial foreach /*1*/ ( /*2*/ q[i] /*3*/ ) q[i] = i;
endmodule
----
module m;
initial foreach /*1*/ ( /*2*/ q[i] /*3*/ ) q[i] = i;
endmodule
====
# a `foreach` loop-variable list keeps a comment between two slots
module m;
initial foreach (q[i /*1*/ , /*2*/ j]) q[i][j] = 0;
endmodule
----
module m;
initial foreach (q[i /*1*/ , /*2*/ j]) q[i][j] = 0;
endmodule
====
# a `for` header's seven slots
module m;
initial for /*1*/ ( /*2*/ int i = 0 /*3*/ ; /*4*/ i < N /*5*/ ; /*6*/ i++ /*7*/ ) x = i;
endmodule
----
module m;
initial for /*1*/ ( /*2*/ int i = 0 /*3*/ ; /*4*/ i < N /*5*/ ; /*6*/ i++ /*7*/ ) x = i;
endmodule
====
# a generate `for` header and its block label
module m;
for /*1*/ (genvar /*2*/ i = 0; i < N; i /*3*/ ++) /*4*/ begin /*5*/ : /*6*/ g
sub u (.a(a[i]));
end
endmodule
----
module m;
for /*1*/ (genvar /*2*/ i = 0; i < N; i /*3*/ ++) /*4*/ begin /*5*/ : /*6*/ g
sub u (.a(a[i]));
end
endmodule
====
# a `do ... while` header, which has no body to hand a comment back to
module m;
initial do x = 1; while /*1*/ ( /*2*/ c /*3*/ );
endmodule
----
module m;
initial
do x = 1;
while /*1*/ (
/*2*/
c /*3*/
);
endmodule
====
# an event control's `@`, its edge keyword and its parenthesis
module m;
always @ /*1*/ (posedge /*2*/ clk) q <= d;
endmodule
----
module m;
always @ /*1*/ (posedge /*2*/ clk) q <= d;
endmodule
====
# a delay control's `#`
module m;
initial # /*1*/ 10 x = 1;
endmodule
----
module m;
initial # /*1*/ 10 x = 1;
endmodule
====
# a unary and a postfix operator keep the gap beside them
module m;
assign y = ~ /*1*/ a;
initial x = b /*2*/ ++;
endmodule
----
module m;
assign y = ~ /*1*/ a;
initial x = b /*2*/ ++;
endmodule
====
# a cast's four slots
module m;
assign y = state_t /*1*/ ' /*2*/ ( /*3*/ 0 /*4*/ );
endmodule
----
module m;
assign y = state_t /*1*/ ' /*2*/ ( /*3*/ 0 /*4*/ );
endmodule
====
# a module header: after the keyword, after the `#`, and before the `;`
module /*1*/ m # /*2*/ (parameter int W = 8) (input logic clk) /*3*/ ;
endmodule
----
module /*1*/ m # /*2*/ (parameter int W = 8) (input logic clk) /*3*/ ;
endmodule
====
# a package header and its `endpackage` label
package /*1*/ p /*2*/ ;
endpackage /*3*/ : /*4*/ p
----
package /*1*/ p /*2*/ ;
endpackage /*3*/ : /*4*/ p
====
# a class header, its qualifier run and its `endclass` label
class c;
local /*1*/ static /*2*/ int n;
endclass
----
class c;
local /*1*/ static /*2*/ int n;
endclass
====
# a parameter port's four slots
module m #(parameter /*1*/ int /*2*/ W /*3*/ = /*4*/ 8) ();
endmodule
----
module m #(parameter /*1*/ int /*2*/ W /*3*/ = /*4*/ 8) ();
endmodule
====
# an ANSI port's direction and name gaps
module m (
input /*1*/ logic [3:0] /*2*/ a
);
endmodule
----
module m (input /*1*/ logic [3:0] /*2*/ a);
endmodule
====
# a `localparam` item's keyword and `=` gaps
module m;
localparam /*1*/ int N /*2*/ = /*3*/ 4;
endmodule
----
module m;
localparam /*1*/ int N /*2*/ = /*3*/ 4;
endmodule
====
# a continuous assignment's keyword and operator gaps
module m;
assign /*1*/ y /*2*/ = /*3*/ a;
endmodule
----
module m;
assign /*1*/ y /*2*/ = /*3*/ a;
endmodule
====
# a function header: keyword, return type, name, arguments and `;`
class c;
function /*1*/ void /*2*/ f /*3*/ ( /*4*/ ) /*5*/ ;
endfunction
endclass
----
class c;
function /*1*/ void /*2*/ f /*3*/ (
/*4*/
) /*5*/ ;
endfunction
endclass
====
# a task/function argument's direction, name and default gaps
class c;
function void f(input /*1*/ int /*2*/ n /*3*/ = /*4*/ 0);
endfunction
endclass
----
class c;
function void f(input /*1*/ int /*2*/ n /*3*/ = /*4*/ 0);
endfunction
endclass
====
# an out-of-body definition's scope chain
class c;
extern function void f();
endclass
function void c /*1*/ :: /*2*/ f();
endfunction
----
class c;
extern function void f();
endclass
function void c /*1*/ :: /*2*/ f();
endfunction
====
# a typedef's keyword, name and `;` gaps, and a struct header's
package p;
typedef /*1*/ struct /*2*/ packed /*3*/ {
logic a;
} /*4*/ w_t /*5*/ ;
endpackage
----
package p;
typedef /*1*/ struct /*2*/ packed /*3*/ {
logic a;
} /*4*/ w_t /*5*/ ;
endpackage
====
# an enum's keyword, base and brace gaps, and a member's `=`
package p;
typedef enum /*1*/ logic [1:0] /*2*/ {A /*3*/ = /*4*/ 2'd0, B} e_t;
endpackage
----
package p;
typedef enum /*1*/ logic [1:0] /*2*/ {A /*3*/ = /*4*/ 2'd0, B} e_t;
endpackage
====
# an instantiation's `#`, its named connections and its `;`
module m;
sub # /*1*/ (.W(8)) u0 (. /*2*/ clk /*3*/ ( /*4*/ clk)) /*5*/ ;
endmodule
----
module m;
sub # /*1*/ (.W(8)) u0 (. /*2*/ clk /*3*/ ( /*4*/ clk)) /*5*/ ;
endmodule
====
# a `begin : label` and its `end : label`
module m;
initial begin /*1*/ : /*2*/ blk
x = 1;
end /*3*/ : /*4*/ blk
endmodule
----
module m;
initial begin /*1*/ : /*2*/ blk
x = 1;
end /*3*/ : /*4*/ blk
endmodule
====
# a `fork` label and a `join` label
module m;
initial fork /*1*/ : /*2*/ f
x = 1;
join /*3*/ : /*4*/ f
endmodule
----
module m;
initial
fork /*1*/ : /*2*/ f
x = 1;
join /*3*/ : /*4*/ f
endmodule
====
# a covergroup's qualifier run and its `endgroup` label
class c;
local /*1*/ covergroup cg;
cp: coverpoint a;
endgroup /*2*/ : /*3*/ cg
endclass
----
class c;
local /*1*/ covergroup cg;
cp: coverpoint a;
endgroup /*2*/ : /*3*/ cg
endclass
====
# a constraint's out-of-body scope and its qualifier run
class c;
static /*1*/ constraint c1 {
a < 5;
}
endclass
----
class c;
static /*1*/ constraint c1 {
a < 5;
}
endclass
====
# every escaped segment of a scoped type name keeps its terminator
module m;
\my-pkg ::\state-t \st ;
endmodule
----
module m;
\my-pkg ::\state-t \st ;
endmodule
@@ -1191,3 +1191,227 @@ endmodule
module m;
sub /* the one */ u (.a(b));
endmodule
====
# a line comment trailing `end` pushes `else if` onto the next line
module m;
always_comb begin
if (a) begin
x = 1;
end // addr_phase_write
else if (b) begin
x = 2;
end
else begin
x = 3;
end
end
endmodule
----
module m;
always_comb begin
if (a) begin
x = 1;
end // addr_phase_write
else if (b) begin
x = 2;
end else begin
x = 3;
end
end
endmodule
====
# a line comment trailing `end` pushes a one-statement `else` down too
module m;
always_comb begin
if (a) begin
x = 1;
end // fell through
else if (b) x = 2;
else x = 3;
end
endmodule
----
module m;
always_comb begin
if (a) begin
x = 1;
end // fell through
else if (b) x = 2;
else x = 3;
end
endmodule
====
# a block comment trailing `end` still lets `else` cuddle
module m;
always_comb begin
if (a) begin
x = 1;
end /* why */ else begin
x = 2;
end
end
endmodule
----
module m;
always_comb begin
if (a) begin
x = 1;
end /* why */ else begin
x = 2;
end
end
endmodule
====
# a comment after `if (` stays inside the parentheses
module m;
always_comb begin
if (// the first transaction
a ||
// or the last one
b) begin
x = 1;
end
end
endmodule
----
module m;
always_comb begin
if (
// the first transaction
a || // or the last one
b
) begin
x = 1;
end
end
endmodule
====
# a block comment before an if condition's `)` stays inside them
module m;
always_comb begin
if (bitstuff /* && !serial_tx_se0 */) begin
x = 1;
end
end
endmodule
----
module m;
always_comb begin
if (bitstuff /* && !serial_tx_se0 */) begin
x = 1;
end
end
endmodule
====
# an if condition keeps comments on both sides of it
module m;
always_comb begin
if (// only the leading one
a) begin
x = 1;
end
if (b /* and a trailing one */) begin
x = 2;
end
if (// both ends
c /* like this */) begin
x = 3;
end
end
endmodule
----
module m;
always_comb begin
if (
// only the leading one
a
) begin
x = 1;
end
if (b /* and a trailing one */) begin
x = 2;
end
if (
// both ends
c /* like this */
) begin
x = 3;
end
end
endmodule
====
# a comment after `while (` stays inside the parentheses
module m;
initial begin
while (// keep adding while the agent wants more
rcvd < sent ||
// and while there are transactions left to drive
cnt < num) begin
x = 1;
end
end
endmodule
----
module m;
initial begin
while (
// keep adding while the agent wants more
rcvd < sent || // and while there are transactions left to drive
cnt < num
) begin
x = 1;
end
end
endmodule
====
# `repeat` and `wait` keep a comment written before their `)`
module m;
initial begin
repeat (n // how many
) begin
x = 1;
end
wait (w // until this settles
) begin
x = 2;
end
end
endmodule
----
module m;
initial begin
repeat (
n // how many
) begin
x = 1;
end
wait (
w // until this settles
) begin
x = 2;
end
end
endmodule
====
# a comment after `case (` stays inside the parentheses
module m;
always_comb begin
case (// the decoded opcode
op)
A: y = 1;
default: y = 0;
endcase
end
endmodule
----
module m;
always_comb begin
case (
// the decoded opcode
op
)
A: y = 1;
default: y = 0;
endcase
end
endmodule
@@ -0,0 +1,652 @@
# Constraint bodies (IEEE 1800 §18.5) — the canonical layout the
# constraint-bodies round introduced. See
# docs/features/constraint-bodies/README.md.
#
# A named constraint is a block and is laid out like one: the header keeps
# the `{`, one constraint item per line at one further indent, and the `}`
# closes at the header's column. A body the grammar does not recognise
# rewinds to the byte-for-byte verbatim capture constraints had before this
# round; a `randomize() with { ... }` block may stay on the statement's line
# when it holds one item and nothing inside it forces a break.
# a constraint block: one item per line, indented one step, `}` at the header's column
class item;
constraint c_len {
len > 0;
len < 64;
}
endclass
----
class item;
constraint c_len {
len > 0;
len < 64;
}
endclass
====
# an empty constraint body
class item;
constraint c_none { }
endclass
----
class item;
constraint c_none {}
endclass
====
# a constraint prototype, and its `extern`/`pure static` spellings
class item;
constraint c_a;
extern constraint c_b;
pure static constraint c_c;
endclass
----
class item;
constraint c_a;
extern constraint c_b;
pure static constraint c_c;
endclass
====
# a stray `;` after the closing brace is reproduced
class item;
constraint c { a == 0; };
endclass
----
class item;
constraint c {
a == 0;
};
endclass
====
# soft constraints and a `dist` set, both weight operators kept apart
class item;
constraint c_dist {
soft len dist { 0 := 5, [1:20] :/ 20, [21:100] :/ 1 };
kind dist { READ := 1, WRITE := 1 };
}
endclass
----
class item;
constraint c_dist {
soft len dist {0 := 5, [1:20] :/ 20, [21:100] :/ 1};
kind dist {READ := 1, WRITE := 1};
}
endclass
====
# a long dist set breaks one weight per line
class item;
constraint c_dist {
delay dist { 0 := 500, [1:16] := 200, [17:64] := 100, [65:256] := 50, [257:1024] := 10, [1025:4096] := 1 };
}
endclass
----
class item;
constraint c_dist {
delay dist {
0 := 500,
[1:16] := 200,
[17:64] := 100,
[65:256] := 50,
[257:1024] := 10,
[1025:4096] := 1
};
}
endclass
====
# a dist item with no weight at all
class item;
constraint c { a dist { 0, 1, [2:3] }; }
endclass
----
class item;
constraint c {
a dist {0, 1, [2:3]};
}
endclass
====
# `inside` and `!` and index expressions inside a constraint
class item;
constraint c_align {
// The branch address is always required to be half-word aligned.
!addr[0];
addr inside {[0:255], 512};
}
endclass
----
class item;
constraint c_align {
// The branch address is always required to be half-word aligned.
!addr[0];
addr inside {[0:255], 512};
}
endclass
====
# an implication with a braced set, and one with a bare item
class item;
constraint c_impl {
(kind != Branch) -> addr == 0;
kind == Branch -> { addr[1:0] == 0; addr < 1024; }
}
endclass
----
class item;
constraint c_impl {
(kind != Branch) -> addr == 0;
kind == Branch -> {
addr[1:0] == 0;
addr < 1024;
}
}
endclass
====
# `<->` is an operator, not an implication
class item;
constraint c { a <-> b; }
endclass
----
class item;
constraint c {
a <-> b;
}
endclass
====
# a constraint if/else-if chain, braced and bare
class item;
constraint c_if {
if (mode == 0) len == 1;
else if (mode == 1) { len == 2; kind == READ; }
else len == 3;
}
endclass
----
class item;
constraint c_if {
if (mode == 0) len == 1;
else if (mode == 1) {
len == 2;
kind == READ;
} else len == 3;
}
endclass
====
# a constraint foreach, including a skipped dimension
class item;
constraint c_each {
foreach (data[i]) data[i] < 256;
foreach (grid[, j]) { grid[j] inside {0, 1}; }
}
endclass
----
class item;
constraint c_each {
foreach (data[i]) data[i] < 256;
foreach (grid[, j]) {
grid[j] inside {0, 1};
}
}
endclass
====
# solve ... before, with lists on both sides
class item;
constraint c_order { solve kind, mode before len, addr; }
endclass
----
class item;
constraint c_order {
solve kind, mode before len, addr;
}
endclass
====
# unique and disable soft
class item;
constraint c_u {
unique {a, b, c};
disable soft len;
}
endclass
----
class item;
constraint c_u {
unique {a, b, c};
disable soft len;
}
endclass
====
# a null constraint item is its own `;`
class item;
constraint c {
a == 0;
;
}
endclass
----
class item;
constraint c {
a == 0;
;
}
endclass
====
# comments in every slot of a constraint body
class item;
// why this constraint exists
constraint c { // opening
// before the item
a == 0; // after the item
b == 1;
// before the closing brace
}
endclass
----
class item;
// why this constraint exists
constraint c {
// opening
// before the item
a == 0; // after the item
b == 1;
// before the closing brace
}
endclass
====
# a blank line between constraint items is kept
class item;
constraint c {
a == 0;
b == 1;
}
endclass
----
class item;
constraint c {
a == 0;
b == 1;
}
endclass
====
# an `ifdef inside a constraint body keeps both arms as ordinary items
class item;
constraint c {
`ifdef FAST
len < 4;
`else
len < 64;
`endif
}
endclass
----
class item;
constraint c {
`ifdef FAST
len < 4;
`else
len < 64;
`endif
}
endclass
====
# a constraint written at column 1 is re-indented into the class body
class item;
constraint c_dist {
num_insns dist { 0 :/ 5, [1:20] :/ 20, [21:100] :/ 1 };
}
endclass
----
class item;
constraint c_dist {
num_insns dist {0 :/ 5, [1:20] :/ 20, [21:100] :/ 1};
}
endclass
====
# a body the grammar does not know falls back to the byte-for-byte capture
class item;
constraint c {
`MY_CONSTRAINT_HALF
len < 4;
}
endclass
----
class item;
constraint c {
`MY_CONSTRAINT_HALF
len < 4;
}
endclass
====
# a nested implication inside a foreach inside an if
class item;
constraint c {
if (enable) {
foreach (q[i]) {
q[i] > 0 -> { q[i] < 100; }
}
}
}
endclass
----
class item;
constraint c {
if (enable) {
foreach (q[i]) {
q[i] > 0 -> {
q[i] < 100;
}
}
}
}
endclass
====
# a randomize() with block stays on the statement line when it fits
module m;
initial begin
if (!req.randomize() with { addr == 0; }) $fatal(1, "no");
end
endmodule
----
module m;
initial begin
if (!req.randomize() with {addr == 0;}) $fatal(1, "no");
end
endmodule
====
# a randomize() with block of several items breaks like a constraint body
module m;
initial begin
void'(std::randomize(x, y) with { x > 3; y < x; });
end
endmodule
----
module m;
initial begin
void'(std::randomize(x, y) with {
x > 3;
y < x;
});
end
endmodule
====
# a with block the grammar does not know keeps its bytes
module m;
initial begin
void'(std::randomize(x) with { `MY_HALF x > 3; });
end
endmodule
----
module m;
initial begin
void'(std::randomize(x) with { `MY_HALF x > 3; });
end
endmodule
====
# a with block carrying a comment breaks so the `}` cannot be swallowed
module m;
initial begin
void'(std::randomize(x) with { x > 3; // at least four
});
end
endmodule
----
module m;
initial begin
void'(std::randomize(x) with {
x > 3; // at least four
});
end
endmodule
====
# a constraint carrying a multi-line string leaves the string's bytes alone
class item;
constraint c {
n == "a
b";
}
endclass
----
class item;
constraint c {
n == "a
b";
}
endclass
====
# an escaped identifier as a constraint name, and inside the body
class item;
constraint \c-1 {
\a-1 == 0;
}
endclass
----
class item;
constraint \c-1 {
\a-1 == 0;
}
endclass
====
# a very long constraint expression wraps like any other expression
class item;
constraint c {
a_very_long_signal_name + another_long_signal_name + a_third_long_signal_name == 0;
}
endclass
----
class item;
constraint c {
a_very_long_signal_name + another_long_signal_name + a_third_long_signal_name == 0;
}
endclass
====
# ----------------------------------------------------------------------
# Comment slots (the 2026-09-02 rework). Every keyword and punctuation
# position this round introduced owns the comments written in front of it,
# so none of them drifts across a token and `format_source` never has to
# refuse the file. Each case is asserted for output *and* idempotency.
# ----------------------------------------------------------------------
# a comment after `soft` prints between `soft` and the expression
class item;
constraint c {
soft /* pick one */ len < 5;
}
endclass
----
class item;
constraint c {
soft /* pick one */ len < 5;
}
endclass
====
# comments on both sides of `dist`, and on both sides of each weight operator
class item;
constraint c {
len /* the field */ dist /* the set */ { 0 /* zero */ := /* five */ 5, [1:3] :/ /* two */ 2 };
}
endclass
----
class item;
constraint c {
len /* the field */ dist /* the set */ {0 /* zero */ := /* five */ 5, [1:3] :/ /* two */ 2};
}
endclass
====
# comments on both sides of the `soft` of a `disable soft`
class item;
constraint c {
disable /* off */ soft /* the soft one */ len;
}
endclass
----
class item;
constraint c {
disable /* off */ soft /* the soft one */ len;
}
endclass
====
# a comment before `before`, and one after it, in a solve list
class item;
constraint c {
solve kind /* first */ before /* then */ len;
}
endclass
----
class item;
constraint c {
solve kind /* first */ before /* then */ len;
}
endclass
====
# a comment between `unique` and its set
class item;
constraint c {
unique /* all four */ {a, b, c, d};
}
endclass
----
class item;
constraint c {
unique /* all four */ {a, b, c, d};
}
endclass
====
# comments in the constraint header: after the keyword, and before the `{`
class item;
constraint /* the name */ c_len /* the body */ {
len < 5;
}
endclass
----
class item;
constraint /* the name */ c_len /* the body */ {
len < 5;
}
endclass
====
# the same two slots on a prototype and on an out-of-block definition
class item;
extern constraint /* named */ c_len /* nothing follows */ ;
endclass
constraint item::c_len /* out of block */ {
len < 5;
} /* and a stray semicolon */ ;
----
class item;
extern constraint /* named */ c_len /* nothing follows */;
endclass
constraint item::c_len /* out of block */ {
len < 5;
} /* and a stray semicolon */;
====
# a comment written in front of the item's own `;` stays on the item's side
class item;
constraint c {
len < 5 /* inclusive */ ;
unique {a, b} /* distinct */ ;
disable soft len /* not this one */ ;
solve a before b /* in that order */ ;
}
endclass
----
class item;
constraint c {
len < 5 /* inclusive */;
unique {a, b} /* distinct */;
disable soft len /* not this one */;
solve a before b /* in that order */;
}
endclass
====
# a line comment in front of the `;` forces the break the comment demands
class item;
constraint c {
len < 5 // inclusive
;
}
endclass
----
class item;
constraint c {
len < 5 // inclusive
;
}
endclass
====
# every slot of a constraint `if` header, and the one after `else`
class item;
constraint c {
if /* test */ ( /* the mode */ mode == 0 /* only zero */ ) /* then */ {
len == 1;
} else /* otherwise */ {
len == 2;
}
}
endclass
----
class item;
constraint c {
if /* test */ (
/* the mode */
mode == 0 /* only zero */
) /* then */ {
len == 1;
} else /* otherwise */ {
len == 2;
}
}
endclass
====
# the `foreach` header's slots: after the keyword, inside the `(`, before the `)`, before the body
class item;
constraint c {
foreach /* each */ ( /* the array */ data[i] /* done */ ) /* then */ {
data[i] < 4;
}
}
endclass
----
class item;
constraint c {
foreach /* each */ ( /* the array */ data[i] /* done */ ) /* then */ {
data[i] < 4;
}
}
endclass
====
# a comment after the `->` of an implication, and after an `else if`
class item;
constraint c {
m -> /* then */ { a == 1; }
if (m) a == 1;
else /* chained */ if (n) a == 2;
}
endclass
----
class item;
constraint c {
m -> /* then */ {
a == 1;
}
if (m) a == 1;
else /* chained */ if (n) a == 2;
}
endclass
====
# the same slots inside a randomize() with block
module m;
initial begin
void'(req.randomize() with {
soft /* pick */ addr dist /* set */ { 0 := 5 };
addr < 9 /* inclusive */ ;
});
end
endmodule
----
module m;
initial begin
void'(req.randomize() with {
soft /* pick */ addr dist /* set */ {0 := 5};
addr < 9 /* inclusive */;
});
end
endmodule
@@ -0,0 +1,616 @@
# Covergroup bodies (IEEE 1800 §19) — the canonical layout the
# covergroup-bodies round introduced. See
# docs/features/covergroup-bodies/README.md.
#
# A covergroup is a block and is laid out like one: the whole header on the
# header line, one cover item per line at one further indent, and `endgroup`
# back at the header's column with whatever label the source wrote. A
# coverpoint or cross body is laid out like a constraint set, one bin per
# line. A covergroup the grammar does not recognise rewinds to the
# byte-for-byte verbatim capture covergroups had before this round.
# a covergroup is a block: the header on one line, one cover item per line,
# `endgroup` back at the header's column
class cov;
covergroup cg;
coverpoint addr;
endgroup
endclass
----
class cov;
covergroup cg;
coverpoint addr;
endgroup
endclass
====
# the whole header on one line: formals, the sample function, the end label
class cov;
covergroup cg (bit [3:0] a, int n) with function sample (bit [31:0] addr, bit rw);
cp_addr : coverpoint addr {
bins lo = { [0:9] };
bins hi = {[10:$]};
}
endgroup : cg
endclass
----
class cov;
covergroup cg(bit [3:0] a, int n) with function sample(bit [31:0] addr, bit rw);
cp_addr: coverpoint addr {
bins lo = {[0:9]};
bins hi = {[10:$]};
}
endgroup : cg
endclass
====
# a clocking event header, and the option assignments a covergroup body may hold
module m;
covergroup cg @(posedge clk);
option.per_instance = 1;
option.name = "cg";
type_option.weight = 5;
coverpoint x;
endgroup
endmodule
----
module m;
covergroup cg @(posedge clk);
option.per_instance = 1;
option.name = "cg";
type_option.weight = 5;
coverpoint x;
endgroup
endmodule
====
# every bin shape: wildcard, the three keywords, defaults, transitions with
# their three repetitions, a `with` filter and a per-bin `iff`
class c;
covergroup cg;
cp : coverpoint a iff (en) {
wildcard bins w[4] = {4'b1??1};
ignore_bins ig = {2, 3};
illegal_bins bad = default;
bins seq = default sequence;
bins t = (0 => 1, 2 => 3), (4 => 5);
bins r = (1'b0[*1:10] => 1'b1[->2] => 1'b0[=1]);
bins e[] = cp_x with (item % 2 == 0);
bins v = {[0:$]} with ($countones(item) != 1);
bins g = {1} iff (en);
}
endgroup : cg
endclass
----
class c;
covergroup cg;
cp: coverpoint a iff (en) {
wildcard bins w[4] = {4'b1??1};
ignore_bins ig = {2, 3};
illegal_bins bad = default;
bins seq = default sequence;
bins t = (0 => 1, 2 => 3), (4 => 5);
bins r = (1'b0[*1:10] => 1'b1[->2] => 1'b0[=1]);
bins e[] = cp_x with (item % 2 == 0);
bins v = {[0:$]} with ($countones(item) != 1);
bins g = {1} iff (en);
}
endgroup : cg
endclass
====
# a cross body: `binsof ... intersect`, the boolean operators, a nested paren
class c;
covergroup cg;
cr : cross cp_a, cp_b {
bins sel = binsof(cp_a.x) intersect {0, [1:2]} && !binsof(cp_b);
bins two = (binsof(cp_a) || binsof(cp_b)) && binsof(cp_c) intersect {1};
option.weight = 0;
}
endgroup : cg
endclass
----
class c;
covergroup cg;
cr: cross cp_a, cp_b {
bins sel = binsof(cp_a.x) intersect {0, [1:2]} && !binsof(cp_b);
bins two = (binsof(cp_a) || binsof(cp_b)) && binsof(cp_c) intersect {1};
option.weight = 0;
}
endgroup : cg
endclass
====
# an empty body prints `{}`, a null item and a stray `;` after `endgroup` are
# both reproduced
class c;
covergroup cg;
cp: coverpoint a {
}
cr: cross a, b;
;
endgroup;
endclass
----
class c;
covergroup cg;
cp: coverpoint a {}
cr: cross a, b;
;
endgroup;
endclass
====
# every header and bin comment slot prints back where it was written
class c;
covergroup /*a*/ cg /*b*/ (int n) /*c*/ with /*d*/ function /*e*/ sample /*f*/ (int x) /*g*/ ;
cp /*h*/ : /*i*/ coverpoint /*j*/ x /*k*/ iff /*l*/ ( /*m*/ en /*n*/ ) /*o*/ {
wildcard /*p*/ bins /*q*/ v /*r*/ [ /*s*/ 4 /*t*/ ] /*u*/ = /*v*/ {1} /*w*/ with /*x*/ ( /*y*/ item /*z*/ ) /*A*/ iff /*B*/ ( /*C*/ en /*D*/ ) /*E*/ ;
}
endgroup : cg /*F*/ ;
endclass
----
class c;
covergroup /*a*/ cg /*b*/ (int n) /*c*/ with /*d*/ function /*e*/ sample /*f*/ (int x) /*g*/;
cp /*h*/: /*i*/ coverpoint /*j*/ x /*k*/ iff /*l*/ (
/*m*/
en /*n*/
) /*o*/ {
wildcard /*p*/ bins /*q*/ v /*r*/ [ /*s*/ 4 /*t*/ ] /*u*/ = /*v*/ {1} /*w*/ with /*x*/ (
/*y*/
item /*z*/
) /*A*/ iff /*B*/ (
/*C*/
en /*D*/
) /*E*/;
}
endgroup : cg /*F*/;
endclass
====
# leading, trailing and dangling comments in a covergroup body
class c;
covergroup cg;
// a leading comment
cp: coverpoint a { // trailing
// inside
bins v = {1}; // after
// dangling
}
cr: cross a, b;
// last
endgroup
endclass
----
class c;
covergroup cg;
// a leading comment
cp: coverpoint a {
// trailing
// inside
bins v = {1}; // after
// dangling
}
cr: cross a, b;
// last
endgroup
endclass
====
# both arms of an `ifdef stand as ordinary cover items
class c;
covergroup cg;
`ifdef FOO
cp: coverpoint a;
`else
cp: coverpoint b;
`endif
endgroup
endclass
----
class c;
covergroup cg;
`ifdef FOO
cp: coverpoint a;
`else
cp: coverpoint b;
`endif
endgroup
endclass
====
# a long sample-function list breaks like a port list; a long value list breaks
# like every other braced list
class c;
covergroup cg_with_a_really_long_name_here with function sample (bit [31:0] address_value, bit read_write_flag, int unsigned index);
cp: coverpoint address_value {
bins many = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22};
}
endgroup
endclass
----
class c;
covergroup cg_with_a_really_long_name_here with function sample(
bit [31:0] address_value,
bit read_write_flag,
int unsigned index
);
cp: coverpoint address_value {
bins many = {
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22
};
}
endgroup
endclass
====
# a macro supplying a coverpoint's whole bin body rewinds to the byte-for-byte
# verbatim capture covergroups had before this round
class c;
covergroup cg;
cp: coverpoint a `GPR_BIN_TYPES
endgroup : cg
endclass
----
class c;
covergroup cg;
cp: coverpoint a `GPR_BIN_TYPES
endgroup : cg
endclass
====
# a macro standing where a cover item belongs is passed through, the way one
# standing where an item or a statement belongs is
class c;
covergroup cg;
`MY_CP(a, b)
cp: coverpoint a;
endgroup
endclass
----
class c;
covergroup cg;
`MY_CP(a, b)
cp: coverpoint a;
endgroup
endclass
====
# a covergroup at package scope
package p;
covergroup cg;
coverpoint x;
endgroup
endpackage
----
package p;
covergroup cg;
coverpoint x;
endgroup
endpackage
====
# the member qualifiers a covergroup may carry
class c;
local covergroup cg;
coverpoint x;
endgroup
static covergroup cg2;
coverpoint y;
endgroup
endclass
----
class c;
local covergroup cg;
coverpoint x;
endgroup
static covergroup cg2;
coverpoint y;
endgroup
endclass
====
# every name goes through `name_doc`: an escaped identifier keeps its
# terminating space
class c;
covergroup \cg-1 ;
\cp-1 : coverpoint \a-1 {
bins \b-1 = {1};
}
endgroup : \cg-1
endclass
----
class c;
covergroup \cg-1 ;
\cp-1 : coverpoint \a-1 {
bins \b-1 = {1};
}
endgroup : \cg-1
endclass
====
# a covergroup with no items at all
class c;
covergroup cg;
endgroup
endclass
----
class c;
covergroup cg;
endgroup
endclass
====
# a blank line between two cover items is kept
class c;
covergroup cg;
cp1: coverpoint a;
cp2: coverpoint b;
endgroup
endclass
----
class c;
covergroup cg;
cp1: coverpoint a;
cp2: coverpoint b;
endgroup
endclass
====
# the unsized `[]` array spelling, on both a value and a default bin
class c;
covergroup cg with function sample(bit a);
cp: coverpoint a {
bins v[] = {[0:$]};
bins w[] = default;
}
endgroup
endclass
----
class c;
covergroup cg with function sample(bit a);
cp: coverpoint a {
bins v[] = {[0:$]};
bins w[] = default;
}
endgroup
endclass
====
# a bare `@ev` event keeps its lack of parentheses; an `or` list keeps its
# spelling
module m;
covergroup cg @ev;
coverpoint x;
endgroup
covergroup cg2 @(a or b);
coverpoint y;
endgroup
endmodule
----
module m;
covergroup cg @ev;
coverpoint x;
endgroup
covergroup cg2 @(a or b);
coverpoint y;
endgroup
endmodule
====
# a concatenation as the sampled expression, and an `iff` guard on it
class c;
covergroup cg;
cp: coverpoint {a, b, (c != d)} iff (!rst) {
bins z = {0};
}
endgroup
endclass
----
class c;
covergroup cg;
cp: coverpoint {a, b, (c != d)} iff (!rst) {
bins z = {0};
}
endgroup
endclass
====
# a `{` written on its own line cuddles onto the header
class c;
covergroup cg;
cp: coverpoint a
{
bins v = {1};
}
endgroup
endclass
----
class c;
covergroup cg;
cp: coverpoint a {
bins v = {1};
}
endgroup
endclass
====
# a covergroup whose `endgroup` label is missing keeps none
class c;
covergroup cg;
cp: coverpoint a;
endgroup
endclass
----
class c;
covergroup cg;
cp: coverpoint a;
endgroup
endclass
====
# `option` and `type_option` inside a coverpoint body, beside its bins
class c;
covergroup cg;
cp: coverpoint a {
option.weight = 3;
type_option.merge_instances = 1;
bins v = {1};
}
endgroup
endclass
----
class c;
covergroup cg;
cp: coverpoint a {
option.weight = 3;
type_option.merge_instances = 1;
bins v = {1};
}
endgroup
endclass
====
# an unlabelled coverpoint and an unlabelled cross
class c;
covergroup cg;
coverpoint a;
cross a, b;
endgroup
endclass
----
class c;
covergroup cg;
coverpoint a;
cross a, b;
endgroup
endclass
====
# a transition bin whose ranges carry value ranges of their own
class c;
covergroup cg;
cp: coverpoint a {
bins any2any[] = ([None:Bidir] => [None:Bidir]);
bins two = (Read, Write => RStart);
}
endgroup
endclass
----
class c;
covergroup cg;
cp: coverpoint a {
bins any2any[] = ([None:Bidir] => [None:Bidir]);
bins two = (Read, Write => RStart);
}
endgroup
endclass
====
# a scope-qualified name in a bin value and in a `with` filter
class c;
covergroup cg;
cp: coverpoint a {
bins on = {lc_ctrl_pkg::On};
bins bad = {[0:$]} with (!(item inside {lc_ctrl_pkg::Off, lc_ctrl_pkg::On}));
}
endgroup
endclass
----
class c;
covergroup cg;
cp: coverpoint a {
bins on = {lc_ctrl_pkg::On};
bins bad = {[0:$]} with (!(item inside {lc_ctrl_pkg::Off, lc_ctrl_pkg::On}));
}
endgroup
endclass
====
# a covergroup nested in a class that also carries a constraint: both bodies
# are laid out, and neither reaches into the other
class item;
rand int addr;
constraint c_addr { addr < 64; }
covergroup cg_addr with function sample (int a);
cp: coverpoint a { bins lo = {[0:31]}; }
endgroup
endclass
----
class item;
rand int addr;
constraint c_addr {
addr < 64;
}
covergroup cg_addr with function sample(int a);
cp: coverpoint a {
bins lo = {[0:31]};
}
endgroup
endclass
====
# a comment written where the `;` of an item was not written belongs to the
# item that follows it
class c;
covergroup cg;
cp: coverpoint x {
}
// why
cr: cross a, b;
endgroup
endclass
----
class c;
covergroup cg;
cp: coverpoint x {}
// why
cr: cross a, b;
endgroup
endclass
====
# a coverpoint bin's `( ... )` is a transition list even with no arrow; a
# cross bin's is a parenthesized select expression
class c;
covergroup cg;
cp: coverpoint a {
bins zero_delay_5 = (1'b1[*5]);
bins stall_long = (1'b0[*5:10] => 1'b1);
}
cr: cross a, b {
bins any = (binsof(a) || binsof(b)) && !binsof(c);
}
endgroup
endclass
----
class c;
covergroup cg;
cp: coverpoint a {
bins zero_delay_5 = (1'b1[*5]);
bins stall_long = (1'b0[*5:10] => 1'b1);
}
cr: cross a, b {
bins any = (binsof(a) || binsof(b)) && !binsof(c);
}
endgroup
endclass
====
# a call may stand as a bin spec, and a concatenation may stand as a
# transition item
class c;
covergroup cg;
cp: coverpoint a {
bins single_exc[] = single_masks(num_hw_apps);
bins req_before_done = ({1'b1, pkg::False} => {1'b1, pkg::True});
}
endgroup
endclass
----
class c;
covergroup cg;
cp: coverpoint a {
bins single_exc[] = single_masks(num_hw_apps);
bins req_before_done = ({1'b1, pkg::False} => {1'b1, pkg::True});
}
endgroup
endclass
====
@@ -0,0 +1,261 @@
# a `ifdef opened part-way through an assign, each arm carrying the
# construct's own `;` -- the block ends at the `endif, because there is no
# `;` after it to stop at
# hw/top_earlgrey/dv/env/chip_if.sv:1189 (the anchor)
module m;
// Signal probe function for `rnd_ctr` of AES_CIPHER_CTRL
wire [3:0] aes_ctrl_rnd_ctr;
assign aes_ctrl_rnd_ctr =
`ifdef GATE_LEVEL
`AES_HIER.u_aes_core.u_aes_cipher_control.mr_rnd_ctr[3:0];
`else
`AES_HIER.u_aes_core.u_aes_cipher_control.rnd_ctr;
`endif
wire after;
endmodule
----
module m;
// Signal probe function for `rnd_ctr` of AES_CIPHER_CTRL
wire [3:0] aes_ctrl_rnd_ctr;
assign aes_ctrl_rnd_ctr =
`ifdef GATE_LEVEL
`AES_HIER.u_aes_core.u_aes_cipher_control.mr_rnd_ctr[3:0];
`else
`AES_HIER.u_aes_core.u_aes_cipher_control.rnd_ctr;
`endif
wire after;
endmodule
====
# the same shape at *statement* level: a region between two call arguments,
# balanced inside the parens, so the statement ends at its own `;`. Only the
# statement is captured -- the function around it still formats
# hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv:173
class c;
virtual function void build();
abits = (dv_base_reg_field::type_id::create("abits"));
abits.configure(
.parent(this),
.size(6),
`ifdef USE_DMI_INTERFACE
.reset(32'h10),
`else
.reset(32'h07),
`endif
.has_reset(1));
dmistat = 1;
endfunction
endclass
----
class c;
virtual function void build();
abits = (dv_base_reg_field::type_id::create("abits"));
abits.configure(
.parent(this),
.size(6),
`ifdef USE_DMI_INTERFACE
.reset(32'h10),
`else
.reset(32'h07),
`endif
.has_reset(1));
dmistat = 1;
endfunction
endclass
====
# a region between the elements of a concatenation, three brackets deep inside
# an instantiation's parameter override. Since TODO 26 only the ONE override
# value is verbatim -- the instantiation itself is structural again, so the
# lists around the region are laid out canonically
# hw/top_earlgrey/rtl/autogen/chip_earlgrey_asic.sv:621
module chip;
padring #(
.DioPadType ({
AnalogIn0, // RRAM_ANALOG
`ifdef ANALOGSIM
'0,
`else
CC2,
`endif
DualBidirTol // USB_N
})
) u_padring (
.clk_scan_i(ast_base_clks.clk_sys),
.scanmode_i(scanmode)
);
wire after;
endmodule
----
module chip;
padring #(
.DioPadType({
AnalogIn0, // RRAM_ANALOG
`ifdef ANALOGSIM
'0,
`else
CC2,
`endif
DualBidirTol // USB_N
})
) u_padring (.clk_scan_i(ast_base_clks.clk_sys), .scanmode_i(scanmode));
wire after;
endmodule
====
# two instantiation *heads* behind one `ifdef, sharing a connection list. The
# region opened before the item, so this is the closing shape the
# `directive-split` recovery already knew -- what changed is that
# `take_list_directives` no longer harvests the `else as a list element and
# reads the second arm's head as a positional connection
# hw/top_earlgrey/dv/tb/tb.sv:105
module tb;
`ifdef DISABLE_ROM_INTEGRITY_CHECK
chip_earlgrey_asic #(
// This is to be used carefully, and should never be on for synthesis.
.SecRomCtrlDisableScrambling(1'b1)
) dut (
`else
chip_earlgrey_asic dut (
`endif
// Dedicated Pads
.POR_N(dut.chip_if.dios[DioPadPorN]),
`ifdef ANALOGSIM
.CC1(cc1),
`else
.CC1(dut.chip_if.dios[DioPadCc1]),
`endif
.SPI_HOST_D0(dut.chip_if.dios[DioPadSpiHostD0])
);
wire after;
endmodule
----
module tb;
`ifdef DISABLE_ROM_INTEGRITY_CHECK
chip_earlgrey_asic #(
// This is to be used carefully, and should never be on for synthesis.
.SecRomCtrlDisableScrambling(1'b1)
) dut (
`else
chip_earlgrey_asic dut (
`endif
// Dedicated Pads
.POR_N(dut.chip_if.dios[DioPadPorN]),
`ifdef ANALOGSIM
.CC1(cc1),
`else
.CC1(dut.chip_if.dios[DioPadCc1]),
`endif
.SPI_HOST_D0(dut.chip_if.dios[DioPadSpiHostD0])
);
wire after;
endmodule
====
# a split `function` header: the header's own `;` closes a *header*, so the
# block runs to `endfunction` and takes the `: label` with it
# hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv:273
class jtag_dtm_reg_dmi;
function new(string name = "",
`ifdef USE_DMI_INTERFACE
int unsigned n_bits = 50,
`else
int unsigned n_bits = 41,
`endif
int has_coverage = UVM_NO_COVERAGE);
super.new(name, n_bits, has_coverage);
endfunction : new
int after;
endclass
----
class jtag_dtm_reg_dmi;
function new(string name = "",
`ifdef USE_DMI_INTERFACE
int unsigned n_bits = 50,
`else
int unsigned n_bits = 41,
`endif
int has_coverage = UVM_NO_COVERAGE);
super.new(name, n_bits, has_coverage);
endfunction : new
int after;
endclass
====
# the control: a region opened *and* closed inside the connection list still
# conditions list elements, even with an outer region live, and the
# instantiation still parses as an instantiation rather than becoming opaque
module m;
`ifdef OUTER
chip dut (
.A(a),
`ifdef ANALOGSIM
.CC1(c1),
`else
.CC1(d1),
`endif
.B(b)
);
`endif
endmodule
----
module m;
`ifdef OUTER
chip dut (
.A(a),
`ifdef ANALOGSIM
.CC1(c1),
`else
.CC1(d1),
`endif
.B(b)
);
`endif
endmodule
====
# comments survive: the ones written inside the block print once, as part of
# its bytes, and the ones around it stay outside
module m;
// before the block
assign y =
`ifdef A
a; // inside the first arm
`else
b; /* inside the second */
`endif
// after the block
wire after;
endmodule
----
module m;
// before the block
assign y =
`ifdef A
a; // inside the first arm
`else
b; /* inside the second */
`endif
// after the block
wire after;
endmodule
====
# the keymgr shape: the take_gap parser fix and header_parens in one tree —
# the comment written after `if (` stays inside the parens (the last of
# bucket 2's 12; merged-tree pin the serial round could not add itself)
module m;
function automatic int f();
if (// why
!en() || b
) begin
return 1;
end
endfunction
endmodule
----
module m;
function automatic int f();
if (
// why
!en() || b
) begin
return 1;
end
endfunction
endmodule
@@ -250,8 +250,8 @@ wire a;
`endif
int x [] = {1};
====
# over-suppression guard: directives written inside an opaque `constraint`
# body no longer touch item-scope nesting, but the region around the body
# over-suppression guard: directives written inside a `constraint` body are
# constraint items, not item-scope nesting, but the region around the body
# still counts, so a genuine split after it still recovers
class c;
constraint co {
@@ -272,9 +272,9 @@ parameter int AFTER = 1;
----
class c;
constraint co {
`ifdef X
`ifdef X
x < 10;
`endif
`endif
}
endclass
@@ -287,8 +287,8 @@ const int y[] = {
};
parameter int AFTER = 1;
====
# under-suppression guard: an earlier verbatim item (a constraint) inside the
# very region the split sits in -- the outer `ifdef must still be counted
# under-suppression guard: an earlier constraint item inside the very region
# the split sits in -- the outer `ifdef must still be counted
`ifdef OUTER
class c;
constraint co {x < 10;}
@@ -306,7 +306,9 @@ parameter int AFTER = 1;
----
`ifdef OUTER
class c;
constraint co {x < 10;}
constraint co {
x < 10;
}
endclass
`ifdef DSIM
@@ -852,3 +852,81 @@ module m;
.b(y)
);
endmodule
====
# a conditional directive inside a connection's VALUE: the value alone is verbatim, the instantiation is not
module m;
sub u_sub (
.a(
`ifdef X
foo
`else
bar
`endif
),
.b(b)
);
endmodule
----
module m;
sub u_sub (
.a(
`ifdef X
foo
`else
bar
`endif
),
.b(b)
);
endmodule
====
# the same inside a concatenation, the shape opentitan writes: the `)` follows the `}` on its line
module m;
sub u_sub (.pads({
A,
`ifdef X
B,
`else
C,
`endif
D
}), .b(b));
endmodule
----
module m;
sub u_sub (
.pads({
A,
`ifdef X
B,
`else
C,
`endif
D
}),
.b(b)
);
endmodule
====
# and in a parameter override value
module m;
sub #(.P(
`ifdef X
1
`else
2
`endif
)) u_sub (.a(a));
endmodule
----
module m;
sub #(
.P(
`ifdef X
1
`else
2
`endif
)
) u_sub (.a(a));
endmodule
@@ -1,4 +1,4 @@
#a randomize() with { ... } condition keeps its constraint block verbatim (ibex_mem_intf_response_seq_lib.sv:104)
#a randomize() with { ... } written across lines is laid out as a constraint body, and the condition wraps as any multi-line condition does (ibex_mem_intf_response_seq_lib.sv:104)
class c;
task body();
if (!req.randomize() with {
@@ -12,10 +12,12 @@ endclass
----
class c;
task body();
if (!req.randomize() with {
addr == item.addr;
read_write == item.read_write;
}) begin
if (
!req.randomize() with {
addr == item.addr;
read_write == item.read_write;
}
) begin
`uvm_fatal(`gfn, "Cannot randomize response request")
end
endtask
@@ -42,7 +44,7 @@ module m;
endtask
endmodule
====
#a dist { } inside the constraint block is part of the verbatim capture (ibex_mem_intf_response_driver.sv:94)
#a dist { } inside the constraint block is a real weight list, broken one per line when it does not fit (ibex_mem_intf_response_driver.sv:94)
class c;
task body();
if (!std::randomize(gnt_delay) with {
@@ -58,18 +60,20 @@ endclass
----
class c;
task body();
if (!std::randomize(gnt_delay) with {
gnt_delay dist {
cfg.gnt_delay_min :/ 10,
[cfg.gnt_delay_min+1 : cfg.gnt_delay_max-1] :/ 5
};
}) begin
if (
!std::randomize(gnt_delay) with {
gnt_delay dist {
cfg.gnt_delay_min :/ 10,
[cfg.gnt_delay_min + 1:cfg.gnt_delay_max - 1] :/ 5
};
}
) begin
`uvm_fatal(`gfn, "Cannot randomize grant")
end
endtask
endclass
====
#a constraint if inside the block is verbatim too (riscv_load_store_instr_lib.sv:79)
#a constraint if inside the block is laid out like a statement if (riscv_load_store_instr_lib.sv:79)
class c;
function void f();
if (!std::randomize(offset_, addr_) with {
@@ -87,14 +91,16 @@ endclass
----
class c;
function void f();
if (!std::randomize(offset_, addr_) with {
if (locality == NARROW) {
soft offset_ inside {[-16:16]};
} else {
soft offset_ inside {[-64:64]};
if (
!std::randomize(offset_, addr_) with {
if (locality == NARROW) {
soft offset_ inside {[-16:16]};
} else {
soft offset_ inside {[-64:64]};
}
addr_ == base + offset_;
}
addr_ == base + offset_;
}) begin
) begin
`uvm_fatal(`gfn, "Cannot randomize load/store offset")
end
endfunction
@@ -140,7 +146,7 @@ class c;
endfunction
endclass
====
#a one-line constraint block stays on its line
#a with block the source wrote on one line stays on one line
class c;
function void f();
if (!req.randomize() with { addr == 0; }) $fatal(1, "no");
@@ -149,7 +155,7 @@ endclass
----
class c;
function void f();
if (!req.randomize() with { addr == 0; }) $fatal(1, "no");
if (!req.randomize() with {addr == 0;}) $fatal(1, "no");
endfunction
endclass
====
@@ -589,9 +595,13 @@ endclass
----
class c;
task t;
if (req.randomize() with {
addr == 32'h1000;
} && cfg.enable_the_long_named_feature_flag && other_condition_name_goes_right_here) begin
if (
req.randomize() with {
addr == 32'h1000;
} &&
cfg.enable_the_long_named_feature_flag &&
other_condition_name_goes_right_here
) begin
z = 1;
end
endtask
@@ -612,8 +622,10 @@ class c;
task t;
if (
req.randomize() with {
addr == 32'h1000;
} && cfg.enable_the_long_named_feature_flag && other_condition_name_goes_right_here_ok
addr == 32'h1000;
} &&
cfg.enable_the_long_named_feature_flag &&
other_condition_name_goes_right_here_ok
) begin
z = 1;
end
@@ -639,3 +651,4 @@ class c;
endtask
endclass
====
@@ -0,0 +1,308 @@
# An escaped identifier (IEEE 1800-2017 5.6.1) runs from its backslash to the
# next whitespace character and to nothing else, so every name the formatter
# writes next to punctuation carries a terminating space. Where the layout
# already writes a separator the output has two spaces (`logic \x = 1;`):
# deliberate, and a fixed point on the next pass.
# escaped declarators: net, variable, list, unpacked, parameter
module m;
wire \my-signal ;
logic \x = 1'b0;
reg [7:0] \r-a , \r-b [0:3];
parameter int \P-WIDTH = 8;
localparam \Q = 1;
endmodule
----
module m;
wire \my-signal ;
logic \x = 1'b0;
reg [7:0] \r-a , \r-b [0:3];
parameter int \P-WIDTH = 8;
localparam \Q = 1;
endmodule
====
# escaped ANSI ports, module name and end label
module \my-mod (input logic \a-in , output wire [7:0] \b-out , input \c = 1);
endmodule : \my-mod
----
module \my-mod (input logic \a-in , output wire [7:0] \b-out , input \c = 1);
endmodule : \my-mod
====
# escaped non-ANSI ports, declared in the body
module \m2 (\a-p , \b-p );
input \a-p ;
output \b-p ;
endmodule
----
module \m2 (\a-p , \b-p );
input \a-p ;
output \b-p ;
endmodule
====
# escaped package, typedefs, enum members and struct fields
package \my-pkg ;
typedef logic [7:0] \byte-t ;
typedef enum logic [1:0] {\A-0 , \B-1 = 2'd2} \state-t ;
typedef struct packed {logic \f-a ; logic [3:0] \f-b ;} \s-t ;
typedef class \fwd-c ;
endpackage : \my-pkg
----
package \my-pkg ;
typedef logic [7:0] \byte-t ;
typedef enum logic [1:0] {\A-0 , \B-1 = 2'd2} \state-t ;
typedef struct packed {
logic \f-a ;
logic [3:0] \f-b ;
} \s-t ;
typedef class \fwd-c ;
endpackage : \my-pkg
====
# escaped class, extends, members, tf arguments and end labels
class \base-c ;
endclass : \base-c
class \my-c extends \base-c ;
int \fld ;
extern function void \do-it (input int \arg-a , output bit \arg-b );
function void \f2 (int \q );
this.\fld = \q ;
endfunction : \f2
task \tsk ();
endtask : \tsk
endclass : \my-c
----
class \base-c ;
endclass : \base-c
class \my-c extends \base-c ;
int \fld ;
extern function void \do-it (input int \arg-a , output bit \arg-b );
function void \f2 (int \q );
this.\fld = \q ;
endfunction : \f2
task \tsk ();
endtask : \tsk
endclass : \my-c
====
# escaped instance, overrides, instance array and port connections
module m;
\sub-mod #(.\P-A (2), .P_B(3)) \u-inst [3:0] (.\p-in (a), .\p-out (\w ), .*);
sub \u2 (.\c-in );
endmodule
----
module m;
\sub-mod #(.\P-A (2), .P_B(3)) \u-inst [3:0] (.\p-in (a), .\p-out (\w ), .*);
sub \u2 (.\c-in );
endmodule
====
# escaped names in expressions: member, index, scope, named argument
module m;
assign \b-out = \iface .\vld [3] & \my-pkg ::\A-0 ;
initial begin
$display("%d", \q .\r );
\f (.\arg-a (1), .b(2));
end
endmodule
----
module m;
assign \b-out = \iface .\vld [3] & \my-pkg ::\A-0 ;
initial begin
$display("%d", \q .\r );
\f (.\arg-a (1), .b(2));
end
endmodule
====
# escaped genvar and generate block label
module m;
genvar \i ;
generate
for (\i = 0; \i < 4; \i = \i + 1) begin : \gen-blk
wire \w ;
end : \gen-blk
endgenerate
endmodule
----
module m;
genvar \i ;
generate
for (\i = 0; \i < 4; \i = \i + 1) begin : \gen-blk
wire \w ;
end : \gen-blk
endgenerate
endmodule
====
# escaped block, fork and statement labels, disable, foreach
module m;
initial begin : \blk-1
\lbl-1 : assert (\st == 0);
disable \blk-1 ;
foreach (\w2 [\i ]) $display("%d", \w2 [\i ]);
fork : \frk-1
join : \frk-1
end : \blk-1
endmodule
----
module m;
initial begin : \blk-1
\lbl-1 : assert (\st == 0);
disable \blk-1 ;
foreach (\w2 [\i ]) $display("%d", \w2 [\i ]);
fork : \frk-1
join : \frk-1
end : \blk-1
endmodule
====
# escaped interface, modport and clocking block
interface \my-if (input \clk );
logic \vld ;
modport \mp-a (input \vld , output \clk );
clocking \cb-1 @(posedge \clk );
input \vld ;
output \drv = \vld ;
endclocking : \cb-1
endinterface : \my-if
----
interface \my-if (input \clk );
logic \vld ;
modport \mp-a (input \vld , output \clk );
clocking \cb-1 @(posedge \clk );
input \vld ;
output \drv = \vld ;
endclocking : \cb-1
endinterface : \my-if
====
# escaped import and export paths
package p;
import \my-pkg ::\thing ;
import \my-pkg ::*;
export \my-pkg ::*;
endpackage
----
package p;
import \my-pkg ::\thing ;
import \my-pkg ::*;
export \my-pkg ::*;
endpackage
====
# a Vivado-style netlist fragment: brackets and dots inside the name
module \netlist-top (\clk );
input \clk ;
wire \u_x/y_reg[3] ;
wire \gen[0].u/z ;
FDRE #(.INIT(1'b0)) \u_x/y_reg[3]_i_1 (.C(\clk ), .D(\gen[0].u/z ), .Q(\u_x/y_reg[3] ));
and \g-1 (\u_x/y_reg[3] , \clk , \gen[0].u/z );
endmodule
----
module \netlist-top (\clk );
input \clk ;
wire \u_x/y_reg[3] ;
wire \gen[0].u/z ;
FDRE #(.INIT(1'b0)) \u_x/y_reg[3]_i_1 (.C(\clk ), .D(\gen[0].u/z ), .Q(\u_x/y_reg[3] ));
and \g-1 (\u_x/y_reg[3] , \clk , \gen[0].u/z );
endmodule
====
# an escaped name inside an aligned port, parameter and connection group
module m (
input logic \clk-i ,
input logic [7:0] \data-i ,
output logic q
);
parameter int \P-A = 1;
parameter int LONGER_NAME = 2;
sub u0 (
.\a-in (\clk-i ),
.bbbb (\data-i ),
.c (q)
);
endmodule
----
module m (
input logic \clk-i ,
input logic [7:0] \data-i ,
output logic q
);
parameter int \P-A = 1;
parameter int LONGER_NAME = 2;
sub u0 (
.\a-in (\clk-i ),
.bbbb (\data-i ),
.c (q)
);
endmodule
====
# escaped let declaration, defparam target and call
module m;
let \max-2 (\a , \b ) = (\a > \b ) ? \a : \b ;
defparam \u-inst .\P-A = 4;
initial \x = \max-2 (1, 2);
endmodule
----
module m;
let \max-2 (\a , \b ) = (\a > \b ) ? \a : \b ;
defparam \u-inst .\P-A = 4;
initial \x = \max-2 (1, 2);
endmodule
====
# escaped case labels
module m;
always_comb begin
case (\st )
\A-0 , \B-1 : \st = 1;
default: \st = 0;
endcase
end
endmodule
----
module m;
always_comb begin
case (\st )
\A-0 , \B-1 : \st = 1;
default: \st = 0;
endcase
end
endmodule
====
# escaped connections keep their terminator when the list breaks
module m;
sub u0 (.\a-in (\some-long-signal-name-here ), .\b-in (\another-long-signal-name ), .\c-in (\third-long-signal-name ));
endmodule
----
module m;
sub u0 (
.\a-in (\some-long-signal-name-here ),
.\b-in (\another-long-signal-name ),
.\c-in (\third-long-signal-name )
);
endmodule
====
# an out-of-class method definition scoped by an escaped class name
function void \my-c ::\do-it ();
endfunction
----
function void \my-c ::\do-it ();
endfunction
====
# a `pkg::type` chain whose every segment is escaped: the join keeps the
# whitespace that terminates each one, so the three tokens stay three
# (docs/topo.md §2.9-21, closed by docs/features/comment-slots/README.md).
# The doubled space is what a bare escaped type name already prints.
module m;
\my-pkg ::\state-t \st ;
endmodule
----
module m;
\my-pkg ::\state-t \st ;
endmodule
====
# an escaped type name widens the alignment column by its terminator
module m (
input \my-t \a-in-with-a-long-name ,
input logic [31:0] bbbb_long_name_here,
output \other-type-t \c-out-long-name
);
endmodule
----
module m (
input \my-t \a-in-with-a-long-name ,
input logic [31:0] bbbb_long_name_here,
output \other-type-t \c-out-long-name
);
endmodule
@@ -0,0 +1,185 @@
# Fragment files: a whole file that is the bare middle of some larger
# construct's body, `include`d at exactly that point. See
# docs/features/fragment-mode/README.md.
#
# Three shapes reach fragment mode — an enum-member list, a covergroup-item
# list and a statement list — and each is printed at indent 0 through the very
# printer the body it belongs to uses. A class-body fragment and a module-item
# fragment are ordinary item lists and never enter fragment mode at all; the
# last two cases here pin that they still format.
# the riscv-dv enum fragment, verbatim: one comment and one member with a
# trailing comma, included between two members of riscv_instr_pkg's enum
// TODO: Add custom instruction name enum
CUSTOM_1,
----
// TODO: Add custom instruction name enum
CUSTOM_1,
====
# a run of enum members, one per line, values and name ranges kept
A ,
B=2,
ReqPeriResetIdx[0:1],
OtbnDmem[16],
C
----
A,
B = 2,
ReqPeriResetIdx[0:1],
OtbnDmem[16],
C
====
# a single member with no trailing comma
CUSTOM_1
----
CUSTOM_1
====
# comments in every slot of an enum-member fragment
// before A
A, // after A
/* before B */ B = 2,
// before C
C
// after the last member
----
// before A
A, // after A
/* before B */
B = 2,
// before C
C
// after the last member
====
# `ifdef arms between enum members stay where they were written
`ifdef ADD_CUSTOM
CUSTOM_1,
CUSTOM_2,
`endif
LAST
----
`ifdef ADD_CUSTOM
CUSTOM_1,
CUSTOM_2,
`endif
LAST
====
# a statement fragment: the middle of a procedural block
a = 1;
b<=2;
foo( x , y );
----
a = 1;
b <= 2;
foo(x, y);
====
# a statement fragment with a begin/end block and an if/else
if (a) begin
x = 1;
end else begin
x = 2;
end
----
if (a) begin
x = 1;
end else begin
x = 2;
end
====
# a statement fragment with a loop and a case
foreach (q[i]) begin
q[i] = i;
end
case (y)
0: z = 1;
default: z = 0;
endcase
----
foreach (q[i]) begin
q[i] = i;
end
case (y)
0: z = 1;
default: z = 0;
endcase
====
# comments in every slot of a statement fragment
// leading
a = 1; // trailing
/* inline */ b = 2;
// after a blank line
c = 3;
// dangling at the end
----
// leading
a = 1; // trailing
/* inline */
b = 2;
// after a blank line
c = 3;
// dangling at the end
====
# a timing control leads a statement fragment
@(posedge clk) x <= y;
#10 z = 1;
----
@(posedge clk) x <= y;
#10 z = 1;
====
# a cover-item fragment: labelled coverpoints with bodies
cp_addr : coverpoint addr {
bins lo = { [0:9] };
bins hi = {[10:$]};
}
cp_rw: coverpoint rw;
----
cp_addr: coverpoint addr {
bins lo = {[0:9]};
bins hi = {[10:$]};
}
cp_rw: coverpoint rw;
====
# a cover-item fragment with a cross and an option
cp_a: coverpoint a;
cp_b: coverpoint b;
x_ab : cross cp_a , cp_b;
option.per_instance = 1;
----
cp_a: coverpoint a;
cp_b: coverpoint b;
x_ab: cross cp_a, cp_b;
option.per_instance = 1;
====
# comments in every slot of a cover-item fragment
// before the coverpoint
cp_a: coverpoint a; // after it
// after a blank line
x: cross cp_a, cp_b;
// dangling at the end
----
// before the coverpoint
cp_a: coverpoint a; // after it
// after a blank line
x: cross cp_a, cp_b;
// dangling at the end
====
# a class-body fragment is an ordinary item list and formats as it always did
rand bit [31:0] addr;
function void do_it();
x = 1;
endfunction
----
rand bit [31:0] addr;
function void do_it();
x = 1;
endfunction
====
# a module-item fragment is an ordinary item list too
assign y = a & b;
always_comb z = y;
----
assign y = a & b;
always_comb z = y;
@@ -451,3 +451,51 @@ class c extends b;
@(posedge clk);
endtask
endclass
====
# a spaced macro call in expression position keeps its gap (M4 residue)
module m;
localparam int W = `WIDTH (8);
assign x = `WIDTH (a + b);
endmodule
----
module m;
localparam int W = `WIDTH (8);
assign x = `WIDTH (a + b);
endmodule
====
# the same macro glued to its `(` stays glued: the two spellings are one token each
module m;
assign x = `WIDTH(a + b);
endmodule
----
module m;
assign x = `WIDTH(a + b);
endmodule
====
# a spaced macro call in a parameter override and in both connection kinds
module m;
sub #(.P(`MACRO (1))) u_sub (.a(`FOO (1)), `BAR (2));
endmodule
----
module m;
sub #(.P(`MACRO (1))) u_sub (.a(`FOO (1)), `BAR (2));
endmodule
====
# a comment in the gap owns the space; the macro is still not glued to its `(`
module m;
assign x = `W /*c*/ (a);
endmodule
----
module m;
assign x = `W /*c*/ (a);
endmodule
====
# a `(` opening the next line becomes one space, which is still two tokens
module m;
assign z = `W
(a);
endmodule
----
module m;
assign z = `W (a);
endmodule
@@ -0,0 +1,230 @@
# The mop-up round: the small parser buckets of syntax_coverage.md, bundled.
# See docs/features/testbench-mopup/README.md. Every case here is a shape the
# OpenTitan sweep contains; none of them needed a layout decision, because in
# every one the new surface is data the source already laid out (a bracket, a
# qualifier word, a modport suffix) rather than a construct to break.
# --- bucket 4: a block-scoped `typedef` statement (IEEE 1800 §6.18) ---
# The statement form is the item form, indented to the block. Same node, same
# printer, so `typedef enum` still fits on one line if it fits.
class c;
task access_data_fifo(ref bit [7:0] data_q[$]);
typedef enum bit {WRITE = 1'b1, READ = 1'b0} rdwr_e;
rdwr_e rw = WRITE;
endtask
endclass
----
class c;
task access_data_fifo(ref bit [7:0] data_q [$]);
typedef enum bit {WRITE = 1'b1, READ = 1'b0} rdwr_e;
rdwr_e rw = WRITE;
endtask
endclass
====
# every typedef spelling reaches statement position, comments included
module m;
initial begin
// a block-scoped alias, a dynamic-array alias and a struct
typedef logic [2*$bits(mubi4_t) - 1:0] extclk_ctrl_t;
typedef bit data_result[];
typedef struct {
trans_e unit;
uvm_reg_field hint_bit;
} hint_t;
typedef class fwd;
data_result data_array;
end
endmodule
----
module m;
initial begin
// a block-scoped alias, a dynamic-array alias and a struct
typedef logic [2*$bits(mubi4_t)-1:0] extclk_ctrl_t;
typedef bit data_result [];
typedef struct {
trans_e unit;
uvm_reg_field hint_bit;
} hint_t;
typedef class fwd;
data_result data_array;
end
endmodule
====
# --- bucket 6: a system function call as the casting type ---
# `$bits(x)'(y)` / `$clog2(N)'(y)` — a `constant_primary` per IEEE 1800
# §6.24.1, and the only call shape admitted left of a cast's `'`.
module m;
assign periph_data_mux = $bits(periph_data_mux)'({periph_to_mio_i, 1'b0});
assign a = $clog2(RomSize)'(RomSize);
assign b = data_q[$clog2(dm::DataCount)'(autoexecdata_idx)];
endmodule
----
module m;
assign periph_data_mux = $bits(periph_data_mux)'({periph_to_mio_i, 1'b0});
assign a = $clog2(RomSize)'(RomSize);
assign b = data_q[$clog2(dm::DataCount)'(autoexecdata_idx)];
endmodule
====
# --- bucket 8: enum member ranges (IEEE 1800 §6.19) ---
# The bracket prints tight against the name: it is part of the name, not a
# dimension standing beside it, and there is no layout decision in it.
package p;
typedef enum logic [ResetWidths-1:0] {
ReqPeriResetIdx[0:1],
ReqMainPwrResetIdx,
ReqEscResetIdx
} reset_idx_e;
typedef enum {
OtbnDmem[16],
OtbnImem,
RamMain[16] = 5,
Otp
} mem_e;
endpackage
----
package p;
typedef enum logic [ResetWidths-1:0] {
ReqPeriResetIdx[0:1],
ReqMainPwrResetIdx,
ReqEscResetIdx
} reset_idx_e;
typedef enum {OtbnDmem[16], OtbnImem, RamMain[16] = 5, Otp} mem_e;
endpackage
====
# --- bucket 10: a cast applied to an assignment pattern, `ty'{...}` ---
# The pattern brings its own `'{` and `}`, so the cast prints no brackets of
# its own. The last line is the reason the two spellings stay distinguishable
# in the tree: `ty'('{...})` is a different token stream and must survive as
# itself.
class c;
function void f();
exp_alert_q[alert_name].push_back(expected_alert_t'{1, is_fatal, max_delay});
q.push_back(mem_item_t'{addr: a, data: d});
x = pkg::cfg_t'{default: 0};
endfunction
endclass
module m;
assign tag = {ibex_pkg::IC_NUM_WAYS{prim_ram_1p_pkg::ram_1p_cfg_req_t'{req: spram_rm.cfg}}};
assign y = bar_t'('{a: 1});
endmodule
----
class c;
function void f();
exp_alert_q[alert_name].push_back(expected_alert_t'{1, is_fatal, max_delay});
q.push_back(mem_item_t'{addr: a, data: d});
x = pkg::cfg_t'{default: 0};
endfunction
endclass
module m;
assign tag = {ibex_pkg::IC_NUM_WAYS{prim_ram_1p_pkg::ram_1p_cfg_req_t'{req: spram_rm.cfg}}};
assign y = bar_t'('{a: 1});
endmodule
====
# --- bucket 11: a gate's `#(rise, fall[, turn-off])` delay list (§28.14) ---
# The one-value spellings keep the node they always had, so `#(5)` and `#5`
# still print exactly as written; only a real comma list prints its own parens.
module m;
buf #(ast_bhv_pkg::AON_EN_RDLY, 0) b0 (en_osc_re_buf, (vcore_pok_h_i && aon_en_i));
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);
endmodule
----
module m;
buf #(ast_bhv_pkg::AON_EN_RDLY, 0) b0 (en_osc_re_buf, (vcore_pok_h_i && aon_en_i));
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);
endmodule
====
# --- bucket 12: `virtual iface.modport name;` (IEEE 1800 §25.9) ---
# The modport is glued onto the interface name, exactly as an interface
# *port*'s already is, so the type prints as the one string it is.
module tb;
virtual spi_if.tb tb_sif = sif.tb;
virtual spi_if.dut dut_sif;
virtual interface bus_if plain_vif;
task automatic spi_transaction(virtual spi_if.tb sif, ref spi_fifo_t d_in[$]);
endtask
endmodule
----
module tb;
virtual spi_if.tb tb_sif = sif.tb;
virtual spi_if.dut dut_sif;
virtual interface bus_if plain_vif;
task automatic spi_transaction(virtual spi_if.tb sif, ref spi_fifo_t d_in [$]);
endtask
endmodule
====
# --- bucket 14: `rand`/`randc` on a plain struct member ---
# Not LRM-legal, but vendor-accepted and real. Carried and printed; lucisv
# models no randomization semantics either way.
package p;
typedef struct {
rand bit cpol;
randc bit [3:0] csnlead;
rand mubi4_t en; // enable this region
bit plain;
} cfg_t;
endpackage
----
package p;
typedef struct {
rand bit cpol;
randc bit [3:0] csnlead;
rand mubi4_t en; // enable this region
bit plain;
} cfg_t;
endpackage
====
# --- bucket 15: a `foreach` with a skipped dimension (IEEE 1800 §12.7.3) ---
# A skipped slot is an empty name written where the source wrote nothing: it
# declares no loop variable, and it prints as nothing.
module m;
initial begin
foreach (cfg.mem_bkdr_util_h[, bank]) x = 1;
foreach (h[i, , k]) y = 2;
foreach (q[i, j]) w = 4;
end
endmodule
----
module m;
initial begin
foreach (cfg.mem_bkdr_util_h[, bank]) x = 1;
foreach (h[i, , k]) y = 2;
foreach (q[i, j]) w = 4;
end
endmodule
====
# --- bucket 16: a hierarchical path in a `bind`'s instance list ---
# The dots are glued into the one name the list already carries, the way
# `bind`'s own target path is.
module tb;
bind prim_packer_fifo : dut.u_entropy_src_core.u_prim_packer_fifo_precon
entropy_subsys_fifo_exception_if #(
.IsPackerFifo(1)
) u_fifo_exc_if (
.clk_i,
.rst_ni
);
bind foo : a.b, plain_inst bar u (.x);
endmodule
----
module tb;
bind prim_packer_fifo : dut.u_entropy_src_core.u_prim_packer_fifo_precon entropy_subsys_fifo_exception_if #(
.IsPackerFifo(1)
) u_fifo_exc_if (.clk_i, .rst_ni);
bind foo : a.b, plain_inst bar u (.x);
endmodule
@@ -0,0 +1,327 @@
# the owner's report: a stray `;` after `endgenerate`
module m #(parameter int N = 4) (input logic [N-1:0] a, output logic [N-1:0] y);
generate
for (genvar i = 0; i < N; i++) begin : g
assign y[i] = ~a[i];
end
endgenerate;
endmodule
----
module m #(parameter int N = 4) (input logic [N-1:0] a, output logic [N-1:0] y);
generate
for (genvar i = 0; i < N; i++) begin : g
assign y[i] = ~a[i];
end
endgenerate;
endmodule
====
# a null item on its own line at module scope
module m (input logic clk, output logic q);
always_ff @(posedge clk) q <= ~q;
;
endmodule
----
module m (input logic clk, output logic q);
always_ff @(posedge clk) q <= ~q;
;
endmodule
====
# slang's -Wempty-member example: `module m; ; endmodule`
module m; ; endmodule
----
module m;
;
endmodule
====
# a null item that opens a generate region takes its own line
module m; generate ; endgenerate endmodule
----
module m;
generate
;
endgenerate
endmodule
====
# `end;` after a generate block inside a region
module m #(parameter int N = 2) (output logic [N-1:0] y);
generate
for (genvar i = 0; i < N; i++) begin : g
assign y[i] = 1'b0;
end;
endgenerate
endmodule
----
module m #(parameter int N = 2) (output logic [N-1:0] y);
generate
for (genvar i = 0; i < N; i++) begin : g
assign y[i] = 1'b0;
end;
endgenerate
endmodule
====
# region-less `end;`, and `;;` after it
module m #(parameter int N = 2) (output logic [N-1:0] y);
if (N > 1) begin : g1
assign y = '0;
end;
;;
endmodule
----
module m #(parameter int N = 2) (output logic [N-1:0] y);
if (N > 1) begin : g1
assign y = '0;
end;
;;
endmodule
====
# a null item in a package body
package p;
localparam int W = 1;
;
endpackage
----
package p;
localparam int W = 1;
;
endpackage
====
# a null item in an interface body
interface ifc;
logic a;
;
endinterface
----
interface ifc;
logic a;
;
endinterface
====
# a null item in a class body
class c;
int x;
;
endclass
----
class c;
int x;
;
endclass
====
# `endmodule;` — a null item at file scope
module m;
endmodule;
----
module m;
endmodule;
====
# glued stays glued: the output of the owner's shape formats to itself
module m;
generate
endgenerate;
endmodule
----
module m;
generate
endgenerate;
endmodule
====
# own-line stays own-line
module m;
wire a;
;
endmodule
----
module m;
wire a;
;
endmodule
====
# a trailing comment after a glued `;` stays on that line
module m;
generate
endgenerate; // note
endmodule
----
module m;
generate
endgenerate; // note
endmodule
====
# a leading comment keeps the `;` on a line of its own
module m;
wire a;
// why the semicolon is here
;
endmodule
----
module m;
wire a;
// why the semicolon is here
;
endmodule
====
# a blank line before a null item is kept, and unglues it
module m;
wire a;
;
endmodule
----
module m;
wire a;
;
endmodule
====
# a block comment between the item and its `;` keeps its place
module m;
generate endgenerate /* b */ ;
endmodule
----
module m;
generate
endgenerate /* b */;
endmodule
====
# a null item splits an alignment group
module m;
localparam int A = 1;
localparam int LONGER = 22;
;
localparam int B = 3;
localparam int OTHER = 44;
endmodule
----
module m;
localparam int A = 1;
localparam int LONGER = 22;
;
localparam int B = 3;
localparam int OTHER = 44;
endmodule
====
# the null *statement* is untouched (slang's -Wempty-stmt example)
module m;
initial begin
;
end
endmodule
----
module m;
initial begin
;
end
endmodule
====
# `endfunction;`/`endtask;` still print through `end_semi`, not as null items
module m;
function int f(); return 1; endfunction;
task t(); endtask;
endmodule
----
module m;
function int f();
return 1;
endfunction;
task t();
endtask;
endmodule
====
# systemverilog.io: a 16-input mux built with a generate for
module mux16 (input logic [3:0] select, input logic [15:0] mux_in, output logic mux_out);
logic [15:0] temp;
genvar i;
generate
for (i=0; i < 16; i++) begin
assign temp[i] = (select == i) ? mux_in[i] : 0;
end
endgenerate
assign mux_out = |temp;
endmodule
----
module mux16 (input logic [3:0] select, input logic [15:0] mux_in, output logic mux_out);
logic [15:0] temp;
genvar i;
generate
for (i = 0; i < 16; i++) begin
assign temp[i] = (select == i) ? mux_in[i] : 0;
end
endgenerate
assign mux_out = |temp;
endmodule
====
# systemverilog.io: `assert property` inside a generate for
module arb_sva (input logic clk, input logic [7:0] req, input logic [7:0] ack);
genvar k;
generate
for (k=0; k < 8; k++) begin
req_a: assert property (@(posedge clk) req[k] |=> ack[k]);
end
endgenerate
endmodule
----
module arb_sva (input logic clk, input logic [7:0] req, input logic [7:0] ack);
genvar k;
generate
for (k = 0; k < 8; k++) begin
req_a: assert property (@(posedge clk) req[k] |=> ack[k]);
end
endgenerate
endmodule
====
# systemverilog.io: a generate case with a nested for and instantiations
module mem #(parameter MEM_SIZE = 8, parameter MEM_WIDTH = 16) (
input clk, input csx, input cke, input [1:0] ba, input [11:0] addr,
input rasx, input casx, input wex, input [7:0] dqm, inout [63:0] data, input [3:0] dev_id);
genvar i;
case ({MEM_SIZE, MEM_WIDTH})
{32'd8, 32'd16}:
begin: memory
for (i=0; i<4; i=i+1) begin:word16
sms_08b216t0 p(.clk(clk), .csb(csx), .cke(cke),.ba(ba),
.addr(addr), .rasb(rasx), .casb(casx),
.web(wex), .udqm(dqm[2*i+1]), .ldqm(dqm[2*i]),
.dqi(data[15+16*i:16*i]), .dev_id(dev_id));
end
end
endcase
endmodule
----
module mem #(
parameter MEM_SIZE = 8,
parameter MEM_WIDTH = 16
) (
input clk,
input csx,
input cke,
input [1:0] ba,
input [11:0] addr,
input rasx,
input casx,
input wex,
input [7:0] dqm,
inout [63:0] data,
input [3:0] dev_id
);
genvar i;
case ({MEM_SIZE, MEM_WIDTH})
{32'd8, 32'd16}: begin : memory
for (i = 0; i < 4; i = i + 1) begin : word16
sms_08b216t0 p (
.clk(clk),
.csb(csx),
.cke(cke),
.ba(ba),
.addr(addr),
.rasb(rasx),
.casb(casx),
.web(wex),
.udqm(dqm[2*i+1]),
.ldqm(dqm[2*i]),
.dqi(data[15+16*i:16*i]),
.dev_id(dev_id)
);
end
end
endcase
endmodule
@@ -0,0 +1,88 @@
# Out-of-block constraint definitions (IEEE 1800 §18.5.2), the constraint
# sibling of `function C::method`. See
# docs/features/out-of-class-constraints/README.md. Since the
# constraint-bodies round the whole item is an ItemKind::Constraint with a
# parsed body, laid out canonically — exactly as an in-class constraint is.
# an extern constraint prototype and its out-of-block definition
class my_item;
rand int delay;
extern constraint delay_c;
endclass : my_item
constraint my_item::delay_c {
soft delay dist {0 :/ 5, [1:10] :/ 5};
solve delay before other;
}
----
class my_item;
rand int delay;
extern constraint delay_c;
endclass : my_item
constraint my_item::delay_c {
soft delay dist {0 :/ 5, [1:10] :/ 5};
solve delay before other;
}
====
# inside a package: the block is re-indented, its relative layout is not
package p;
constraint my_item::delay_c {
soft delay dist {0 :/ 5};
}
endpackage
----
package p;
constraint my_item::delay_c {
soft delay dist {0 :/ 5};
}
endpackage
====
# a scope chain, a stray `;`, and comments on both sides of the block
// why this constraint exists
constraint pkg::cls::deep_c { x < 4; }; // and a trailing note
int b;
----
// why this constraint exists
constraint pkg::cls::deep_c {
x < 4;
}; // and a trailing note
int b;
====
# an empty body and a prototype next to a definition
class c;
extern constraint empty_c;
endclass
constraint c::empty_c {}
----
class c;
extern constraint empty_c;
endclass
constraint c::empty_c {}
====
# the body's own second grammar survives untouched: dist, ->, foreach, if
constraint seq::mode_c {
r_esc_rsp == 1 -> (!s_alert_send && !r_alert_rsp);
foreach (ranges[i]) {
ranges[i].base % 4 == 0;
}
if (enabled) {
delay dist {0 :/ 5, [1:10] :/ 5};
} else {
delay == 0;
}
}
----
constraint seq::mode_c {
r_esc_rsp == 1 -> (!s_alert_send && !r_alert_rsp);
foreach (ranges[i]) {
ranges[i].base % 4 == 0;
}
if (enabled) {
delay dist {0 :/ 5, [1:10] :/ 5};
} else {
delay == 0;
}
}
@@ -587,3 +587,54 @@ endmodule
module m;
always @(a or b or c) y = a & b & c;
endmodule
====
# `default;` keeps IEEE 1800 §12.5's optional colon off; `default: ;` keeps it
module m;
always_comb begin
unique case (digest_size_i)
SHA2_256: y = 1;
default;
endcase
unique case (other)
SHA2_256: y = 1;
default: ;
endcase
end
endmodule
----
module m;
always_comb begin
unique case (digest_size_i)
SHA2_256: y = 1;
default;
endcase
unique case (other)
SHA2_256: y = 1;
default: ;
endcase
end
endmodule
====
# a trailing comment on a colon-less `default;` keeps the comment and the
# missing colon; the null statement is no longer bare, so the hug shortcut
# does not fire and a space appears before the `;` (QA-found nit: a real
# statement or comment on the null body falls through to the general path,
# which spaces `default` off whatever follows it the same way it would any
# other case label)
module m;
always_comb begin
case (s)
A: y = 1;
default; // fallback
endcase
end
endmodule
----
module m;
always_comb begin
case (s)
A: y = 1;
default ; // fallback
endcase
end
endmodule
@@ -0,0 +1,293 @@
# Canonical layout for the SVA grammar — docs/features/sva-bodies/README.md.
# One rule: the spec's top-level operators (`|->`, `|=>`, `##`, `and`, `or`)
# break one per line at the parent's indent when the spec does not fit on one
# line; everything else is inline.
#
# The whole spec on one line when it fits, however the source wrote it.
module m;
assert
property
(
@(posedge clk)
a
|->
b
);
endmodule
----
module m;
assert property (@(posedge clk) a |-> b);
endmodule
====
# and one per line when it does not: the clocking event, the `disable iff`,
# then the top-level operator's operands
module m;
assert property (@(posedge clk_i) disable iff (!rst_ni) a_very_long_signal_name_indeed |-> another_long_signal_name_here ##1 a_third_long_signal_name);
endmodule
----
module m;
assert property (@(posedge clk_i)
disable iff (!rst_ni)
a_very_long_signal_name_indeed |-> another_long_signal_name_here ##1 a_third_long_signal_name);
endmodule
====
# an operator that is not one of the five stays inline even past the limit:
# `throughout`, `until`, `intersect`, `within`, `iff`, `implies`
module m;
assert property (a_long_enough_signal_name throughout another_long_signal_name until a_third_signal);
endmodule
----
module m;
assert property (a_long_enough_signal_name throughout another_long_signal_name until a_third_signal);
endmodule
====
# every cycle-delay spelling, printed back as written
module m;
assert property (a ##1 b ##[1:3] c ##[+] d ##[*] e ##[2:$] f ##(N + 1) g);
endmodule
----
module m;
assert property (a ##1 b ##[1:3] c ##[+] d ##[*] e ##[2:$] f ##(N + 1) g);
endmodule
====
# a leading cycle delay, and the repetition suffixes, which hug their operand
module m;
assert property ( ##1 a [* 3] ##1 b [* 1 : $] ##1 c [= 2] ##1 d [-> 1 : 2] ##1 e [*] ##1 f [+] );
endmodule
----
module m;
assert property (##1 a[*3] ##1 b[*1:$] ##1 c[=2] ##1 d[->1:2] ##1 e[*] ##1 f[+]);
endmodule
====
# the prefix operators, with and without a bracketed count
module m;
assert property (not a);
assert property (always b);
assert property (s_eventually c);
assert property (nexttime [2] d);
assert property (s_always [1:3] e);
assert property (accept_on (x) f);
assert property (sync_reject_on (y) g);
endmodule
----
module m;
assert property (not a);
assert property (always b);
assert property (s_eventually c);
assert property (nexttime [2] d);
assert property (s_always [1:3] e);
assert property (accept_on (x) f);
assert property (sync_reject_on (y) g);
endmodule
====
# `strong`, `weak` and `first_match` hug their parentheses, and `first_match`
# keeps its match items
module m;
assert property (strong ( a ##1 b ) |-> weak ( c ) ##1 first_match ( d ##1 e , x = 1 , y ++ ));
endmodule
----
module m;
assert property (strong(a ##1 b) |-> weak(c) ##1 first_match(d ##1 e, x = 1, y++));
endmodule
====
# a parenthesised sequence with match items; written parentheses are printed
# back and the formatter invents none of its own
module m;
assert property ((a ##1 b, x = c, y++) |-> d);
endmodule
----
module m;
assert property ((a ##1 b, x = c, y++) |-> d);
endmodule
====
# a nested clocking event inside parentheses
module m;
assert property ((@(posedge clk) a |-> b) and c);
endmodule
----
module m;
assert property ((@(posedge clk) a |-> b) and c);
endmodule
====
# property `if` / `else`
module m;
assert property (if (sel) a |-> b else c |-> d);
endmodule
----
module m;
assert property (if (sel) a |-> b else c |-> d);
endmodule
====
# property `case`: one arm per line, `endcase` back at the header's column
module m;
assert property (case (sel) 0: a |-> b; 1, 2: c; default: d; endcase);
endmodule
----
module m;
assert property (case (sel)
0: a |-> b;
1, 2: c;
default: d;
endcase);
endmodule
====
# a `property` declaration: the header on one line, the formals like any port
# list, the local variables one per line, the spec at one indent, `endproperty`
# back at the header's column with the label the source wrote
module m;
property p (sequence s, property q, untyped u, int w = 3) ;
logic v ;
@(posedge clk) disable iff (rst) s ##1 q ;
endproperty : p
endmodule
----
module m;
property p(sequence s, property q, untyped u, int w = 3);
logic v;
@(posedge clk) disable iff (rst) s ##1 q;
endproperty : p
endmodule
====
# a `sequence` declaration with no formals and no end label
module m;
sequence s;
a ##1 b [* 2];
endsequence
endmodule
----
module m;
sequence s;
a ##1 b[*2];
endsequence
endmodule
====
# a sequence instance with arguments, `.triggered` and `.matched`
module m;
assert property (my_seq(a, b) |-> other_seq.triggered ##1 third_seq.matched);
endmodule
----
module m;
assert property (my_seq(a, b) |-> other_seq.triggered ##1 third_seq.matched);
endmodule
====
# `cover sequence` — the one spelling that names `sequence` rather than
# `property`
module m;
cover sequence (@(posedge clk) a ##1 b);
endmodule
----
module m;
cover sequence (@(posedge clk) a ##1 b);
endmodule
====
# `default disable iff`, as the node it is
module m;
default disable iff ( !rst_ni ) ;
endmodule
----
module m;
default disable iff (!rst_ni);
endmodule
====
# an `expect` statement, its spec structured and its action block the
# statement it already was
module m;
initial begin
expect (@(posedge clk) a ##1 b) else $error("no");
end
endmodule
----
module m;
initial begin
expect (@(posedge clk) a ##1 b) else $error("no");
end
endmodule
====
# a comment in each of the spec's own slots, printed back between the same two
# tokens it was written between
module m;
assert property (@(posedge clk) /*a*/ disable /*b*/ iff /*c*/ ( /*d*/ rst /*e*/ ) /*f*/ x |-> y);
endmodule
----
module m;
assert property (@(posedge clk)
/*a*/ disable /*b*/ iff /*c*/ (
/*d*/
rst /*e*/
)
/*f*/
x |-> y);
endmodule
====
# a comment in each of a repetition's and a delay's slots
module m;
assert property (a ## /*a*/ [ /*b*/ 1 /*c*/ : /*d*/ 3 /*e*/ ] b /*f*/ [ /*g*/ * /*h*/ 2 /*i*/ ]);
endmodule
----
module m;
assert property (a ## /*a*/ [ /*b*/ 1 /*c*/ : /*d*/ 3 /*e*/ ] b /*f*/ [ /*g*/ * /*h*/ 2 /*i*/ ]);
endmodule
====
# a spec the grammar cannot read falls back to the byte-exact verbatim capture
# the `assertions` round wrote: the `$` here is not a legal operand, and the
# whole item keeps its own spacing rather than being half-structured
module m;
assert property (@(posedge clk) a |-> $blah $blah);
endmodule
----
module m;
assert property (@(posedge clk) a |-> $blah $blah);
endmodule
====
# QA §27 round 1 (HIGH): IEEE 1800-2017 Table 16-3 puts `nexttime`/`s_nexttime`
# on `not`'s row, and ties `always`/`s_always`/`eventually`/`s_eventually` and
# the four `accept_on` operators to `if`/`case` on the loosest row. Everything
# on that loosest row is therefore read wherever a property expression may
# stand -- `p1 and always p2` is legal SVA -- and every shape here used to fall
# back to the verbatim capture. The tokens come back in source order, with no
# parenthesis added and none removed.
module m;
assert property (p1 and nexttime p2);
assert property (p1 and always p2);
assert property (p1 and accept_on(e) p2);
assert property (p1 and s_eventually p2);
assert property (p1 or s_always p2);
assert property (p1 and sync_reject_on(e) p2);
assert property (a |-> nexttime b);
endmodule
----
module m;
assert property (p1 and nexttime p2);
assert property (p1 and always p2);
assert property (p1 and accept_on (e) p2);
assert property (p1 and s_eventually p2);
assert property (p1 or s_always p2);
assert property (p1 and sync_reject_on (e) p2);
assert property (a |-> nexttime b);
endmodule
====
# the two rows read in opposite directions, and the layout shows which is
# which: `nexttime` binds tighter than `and` (so the `and` is the top-level
# operator the one rule breaks on), `always` binds looser (so it is the root
# and the `and` inside it is not top-level)
module m;
assert property (not nexttime a and b);
assert property (a or always b |-> c);
endmodule
----
module m;
assert property (not nexttime a and b);
assert property (a or always b |-> c);
endmodule
====
# a bracketed count survives the regrouping: it is the one thing `nexttime`
# does that `not` does not
module m;
assert property (nexttime [2] a and b);
assert property (s_nexttime [1:3] a and b);
endmodule
----
module m;
assert property (nexttime [2] a and b);
assert property (s_nexttime [1:3] a and b);
endmodule
@@ -0,0 +1,270 @@
# a specify block is re-indented as a unit and kept byte-for-byte inside
# The block moves from column 1 to column 3, so every line inside it moves
# by the same two columns — the `col` contract every verbatim leaf keeps.
module m;
input a; output b;
specify
(a => b) = (1.0, 1.2);
$setuphold(posedge a, b, 0.1, 0.2);
endspecify
endmodule
----
module m;
input a;
output b;
specify
(a => b) = (1.0, 1.2);
$setuphold(posedge a, b, 0.1, 0.2);
endspecify
endmodule
====
# a specify block's inner alignment is the user's, not ours
module m;
specify
(A => Z) = (1,2);
if (S) (A => Z) = 1.5;
endspecify
endmodule
----
module m;
specify
(A => Z) = (1,2);
if (S) (A => Z) = 1.5;
endspecify
endmodule
====
# a UDP declaration, its truth table swallowed whole
primitive udp_mux (q, sel, a, b);
output q;
input sel, a, b;
table
// sel a b : q
0 1 ? : 1;
1 ? 0 : 0;
x 0 0 : 0;
endtable
endprimitive
----
primitive udp_mux (q, sel, a, b);
output q;
input sel, a, b;
table
// sel a b : q
0 1 ? : 1;
1 ? 0 : 0;
x 0 0 : 0;
endtable
endprimitive
====
# a UDP with a label after endprimitive, and the null item after it
primitive p (q, a);
table
0 : 1;
endtable
endprimitive : p
;
----
primitive p (q, a);
table
0 : 1;
endtable
endprimitive : p
;
====
# a checker declaration at file scope, and one nested inside it
checker outer (logic clk);
checker inner (logic a);
a1: assert property (@(posedge clk) a);
endchecker : inner
inner u_inner (x);
endchecker : outer
----
checker outer (logic clk);
checker inner (logic a);
a1: assert property (@(posedge clk) a);
endchecker : inner
inner u_inner (x);
endchecker : outer
====
# a config block
config cfg;
design work.top;
default liblist libA libB;
instance top.u1 use work.impl;
endconfig : cfg
----
config cfg;
design work.top;
default liblist libA libB;
instance top.u1 use work.impl;
endconfig : cfg
====
# a library map line
library rtlLib "/proj/rtl/*.v", "/proj/rtl/*.sv" -incdir "/proj/inc";
----
library rtlLib "/proj/rtl/*.v", "/proj/rtl/*.sv" -incdir "/proj/inc";
====
# specparam outside a specify block is a declaration, laid out like a localparam
module m;
specparam tSETUP=0.12 ,tHOLD = 0.08;
specparam [3:0] tRANGE = 4'd3;
endmodule
----
module m;
specparam tSETUP = 0.12, tHOLD = 0.08;
specparam [3:0] tRANGE = 4'd3;
endmodule
====
# a specparam spelling the declaration grammar cannot read stays verbatim
module m;
specparam PATHPULSE$a$b = (1.0, 1.2);
endmodule
----
module m;
specparam PATHPULSE$a$b = (1.0, 1.2);
endmodule
====
# an alias item
module m;
wire a,b,c;
alias a =b = c ;
alias {x, y} = z;
endmodule
----
module m;
wire a, b, c;
alias a = b = c;
alias {x, y} = z;
endmodule
====
# an interface class is a class, printed with its keyword in front
interface class api #(int W = 8) ;
pure virtual function void run(int x) ;
endclass : api
----
interface class api #(int W = 8);
pure virtual function void run(int x);
endclass : api
====
# an interface class extends another, and a class implements two
interface class b extends a;
endclass
class impl extends base implements a, b;
endclass
----
interface class b extends a;
endclass
class impl extends base implements a, b;
endclass
====
# a tagged union keeps its keyword, in the LRM's order
typedef union tagged packed {
logic [7:0] v;
} u_t;
----
typedef union tagged packed {
logic [7:0] v;
} u_t;
====
# a plain union is untouched by the tagged flag
typedef union packed {
logic [7:0] v;
} u_t;
----
typedef union packed {
logic [7:0] v;
} u_t;
====
# `expect` with a sequence operator is an assertion, kept byte-for-byte
module m;
initial begin
expect (@(posedge clk) a ##1 b) else $error("no");
end
endmodule
----
module m;
initial begin
expect (@(posedge clk) a ##1 b) else $error("no");
end
endmodule
====
# `expect(x);` is a task call and is laid out like one — the 41-site guard
module m;
initial begin
expect(word1[7:0]);
expect ( x , y ) ;
end
endmodule
----
module m;
initial begin
expect(word1[7:0]);
expect(x, y);
end
endmodule
====
# a name that merely contains a new keyword is still a name
module checker_x;
wire config_reg;
logic library_sel;
assign config_reg = library_sel;
endmodule
----
module checker_x;
wire config_reg;
logic library_sel;
assign config_reg = library_sel;
endmodule
====
# a whole vendored cell: UDP, specify, specparam, alias, in one file
`timescale 1ns / 1ps
primitive udp_buf (q, a);
output q;
input a;
table
0 : 0;
1 : 1;
endtable
endprimitive
module DFFQX1 (D, CK, Q);
input D, CK;
output Q;
reg Q;
specparam tSETUP = 0.12, tHOLD = 0.08;
wire n1;
alias n1 = D;
always @(posedge CK) Q <= D;
specify
specparam tRISE = 1.0;
(CK => Q) = (tRISE, 1.2);
$setuphold(posedge CK, D, tSETUP, tHOLD);
endspecify
endmodule
----
`timescale 1ns / 1ps
primitive udp_buf (q, a);
output q;
input a;
table
0 : 0;
1 : 1;
endtable
endprimitive
module DFFQX1 (D, CK, Q);
input D, CK;
output Q;
reg Q;
specparam tSETUP = 0.12, tHOLD = 0.08;
wire n1;
alias n1 = D;
always @(posedge CK) Q <= D;
specify
specparam tRISE = 1.0;
(CK => Q) = (tRISE, 1.2);
$setuphold(posedge CK, D, tSETUP, tHOLD);
endspecify
endmodule
+24 -5
View File
@@ -7,13 +7,15 @@
//! the formatter at all.
use vlog_formatter::{format_source, Config, FormatError};
use vlog_parser::parser::{MAX_CHAIN_LENGTH, MAX_NESTING_DEPTH};
use vlog_parser::parser::{MAX_CHAIN_LENGTH, MAX_NESTING_DEPTH, PARSE_STACK_SIZE};
/// Formatting the deepest legal tree peaks around 4 MiB of stack in an
/// unoptimized build, more than a default test thread's 2 MiB.
/// Formatting the deepest legal tree peaks around 9.7 MiB of stack in an
/// unoptimized build, far more than a default test thread's 2 MiB. The size is
/// the one every production parse site is given, so these tests fail if the
/// guarantee is ever cut below what the two limits need.
fn format_deep(source: String) -> Result<String, FormatError> {
std::thread::Builder::new()
.stack_size(16 * 1024 * 1024)
.stack_size(PARSE_STACK_SIZE)
.spawn(move || format_source(&source, &Config::default()))
.expect("spawn formatter thread")
.join()
@@ -68,12 +70,29 @@ fn longest_legal_chain_formats() {
assert_eq!(out, again, "formatting a maximal chain is a fixed point");
}
/// The stack worst case: a maximal chain inside statement nesting. The two
/// peak in different phases — nesting while parsing, chains while formatting —
/// so this is the input `PARSE_STACK_SIZE` is measured against.
#[test]
fn a_maximal_chain_inside_deep_nesting_formats() {
let depth = MAX_NESTING_DEPTH as usize / 2 - 4;
let src = format!(
"module m;\ninitial\n{}x <= a{};\n{}\nendmodule\n",
"begin\n".repeat(depth),
".b".repeat(MAX_CHAIN_LENGTH as usize),
"end\n".repeat(depth)
);
let out = format_deep(src).expect("a maximal chain inside deep nesting must format");
let again = format_deep(out.clone()).expect("reformat");
assert_eq!(out, again, "the combined worst case is a fixed point");
}
#[test]
fn nesting_past_the_limit_never_reaches_the_formatter() {
let cases = [
(nested_begins(400), "nesting too deep"),
(nested_parens(400), "nesting too deep"),
(member_chain(1500), "expression chain too long"),
(member_chain(MAX_CHAIN_LENGTH as usize + 1), "expression chain too long"),
];
for (src, expected) in cases {
match format_deep(src) {
File diff suppressed because it is too large. Load diff
+59
View File
@@ -74,6 +74,16 @@ impl ParsedSource {
self.lex_error.as_ref()
}
/// The token stream this parse was built from — empty when the text does
/// not lex, which is the lexer's all-or-nothing rule.
///
/// Public so a caller that has already paid for the lex can read the
/// tokens for something else (the CLI harvests its identifier census off
/// them) instead of lexing the same text twice.
pub fn tokens(&self) -> &[Token] {
&self.tokens
}
/// A lint context borrowing this parse. `path` is the file the text came
/// from, or `None` for a buffer (stdin) — rules that need a filename skip.
pub fn context(&self, path: Option<PathBuf>) -> LintContext<'_> {
@@ -97,6 +107,26 @@ enum Backing<'a> {
},
}
/// What the workspace around a file says about a name.
///
/// The one question a lint rule may ask about *other* files, and it is
/// deliberately the smallest one: "does anything outside this file write this
/// word down?". Not where, not how many, not what it means there — a rule that
/// could ask more would start making claims a textual census cannot support.
///
/// `unused-signal` and `undriven-net` are silent about any name the oracle
/// says yes to, which is the same false-negative-safe direction the in-file
/// mention guard already takes: a signal read through `tb.dut.sig`, forced by
/// a testbench, or named in another file's macro argument is used, and no
/// single-file analysis can see it. See
/// `docs/features/semantic-lints-on/README.md`.
///
/// `Sync` because one oracle answers a whole parallel `lucisv check` run.
pub trait MentionOracle: Sync {
/// Whether any file **other than** the one being linted mentions `name`.
fn mentioned_elsewhere(&self, name: &str) -> bool;
}
/// Where a context's symbol table comes from: lent by a caller that already
/// built one (the language server's document), or built here the first time a
/// rule asks for it.
@@ -126,6 +156,11 @@ pub struct LintContext<'a> {
/// The signal table the semantic rules read, built once for all of them
/// the first time one asks — and never for a run with none enabled.
signals: OnceCell<Signals>,
/// What the workspace says about a name, when the caller has a workspace.
/// `None` is a run that cannot see other files — a single-file
/// `lucisv check`, stdin, a unit test — and every rule that would consult
/// it then keeps its single-file answer.
oracle: Option<&'a dyn MentionOracle>,
}
impl<'a> LintContext<'a> {
@@ -167,6 +202,7 @@ impl<'a> LintContext<'a> {
strings: Vec::new(),
semantics: SemanticsSlot::Lazy(OnceCell::new()),
signals: OnceCell::new(),
oracle: None,
};
ctx.strings =
ctx.tokens().iter().filter(|t| t.kind == TokenKind::String).map(|t| t.span).collect();
@@ -191,6 +227,29 @@ impl<'a> LintContext<'a> {
self
}
/// Lends the workspace census a rule may consult about *other* files.
///
/// A context without one is a context that cannot see past its own file,
/// which is what [`LintContext::mentioned_elsewhere`] then answers.
pub fn with_oracle(mut self, oracle: &'a dyn MentionOracle) -> LintContext<'a> {
self.oracle = Some(oracle);
self
}
/// Whether the workspace says some **other** file mentions `name`.
///
/// `false` when there is no oracle — the honest answer for a run that
/// cannot see other files, and the one that leaves every rule exactly
/// where a single-file run left it.
pub fn mentioned_elsewhere(&self, name: &str) -> bool {
self.oracle.is_some_and(|oracle| oracle.mentioned_elsewhere(name))
}
/// Whether this run can see other files at all.
pub fn has_oracle(&self) -> bool {
self.oracle.is_some()
}
/// The file's scopes, declarations and resolved uses — what a semantic
/// rule reads. Built on first use unless a caller lent one.
pub fn semantics(&self) -> &Semantics {
+9 -4
View File
@@ -32,10 +32,15 @@ mod waiver;
use std::path::PathBuf;
pub use context::{LintContext, ParsedSource};
pub use registry::{all_rules, default_rules, rule_by_name, select_rules, Rule};
pub use context::{LintContext, MentionOracle, ParsedSource};
pub use registry::{all_rules, default_rules, rule_by_name, select_rules, workspace_rules, Rule};
pub use rule_docs::rules_markdown;
pub use violation::{apply_fixes, Applicability, Fix, Fixed, Violation};
/// The identifier census a [`MentionOracle`] is answered from, re-exported
/// from `vlog_semantic` so a front end that implements the oracle needs this
/// crate alone. One harvest for the whole workspace — see
/// `docs/features/semantic-lints-on/README.md`.
pub use vlog_semantic::words;
pub use waiver::UNUSED_WAIVER;
use waiver::Waivers;
@@ -186,7 +191,7 @@ mod tests {
#[test]
fn a_waiver_for_a_rule_this_run_did_not_enable_is_silent() {
let src = "module m;\n wire a; // lucisv: waive no-tabs\nendmodule\n";
let enabled = select_rules(&[], &["no-tabs".to_string()]).unwrap();
let enabled = select_rules(&[], &["no-tabs".to_string()], false).unwrap();
assert!(run(src, None, &enabled).is_empty());
}
@@ -202,7 +207,7 @@ mod tests {
#[test]
fn disabling_the_pseudo_rule_silences_unused_reporting() {
let src = "module m;\n wire a; // lucisv: waive no-tabs\nendmodule\n";
let enabled = select_rules(&[], &[UNUSED_WAIVER.to_string()]).unwrap();
let enabled = select_rules(&[], &[UNUSED_WAIVER.to_string()], false).unwrap();
assert!(run(src, None, &enabled).is_empty());
}
+106 -18
View File
@@ -20,13 +20,29 @@ pub trait Rule: Sync {
/// Why the rule exists — the style-guide rationale, in prose.
fn doc(&self) -> &'static str;
/// Whether a plain `lucisv check` runs this rule. A rule is default-on only
/// where Verible defaults its equivalent on; see
/// Whether a plain `lucisv check` runs this rule **without a workspace**. A
/// rule is default-on only where Verible defaults its equivalent on; see
/// `docs/features/lint-rules-2/README.md` for the citation per rule.
fn default_on(&self) -> bool {
true
}
/// Whether this rule wants a [`MentionOracle`](crate::MentionOracle) —
/// a run that can see the other files of the project.
///
/// Such a rule is **off** in a run that has no oracle (one file, stdin)
/// and **on** in one that has, whatever [`Rule::default_on`] says: its one
/// false-positive mode is a use in another file, so the census is the
/// difference between a safe default and a wrong accusation. Two of the
/// three rules that say yes here read the oracle directly; the third
/// (`multiply-driven`) cannot be wrong about a cross-file use but shares
/// the gate, because "the semantic rules need a project" is one rule to
/// explain rather than three. See
/// `docs/features/semantic-lints-on/README.md`.
fn needs_workspace(&self) -> bool {
false
}
/// The applicability of the fix this rule can offer, or `None` when it
/// never offers one. Declarative metadata for the rule reference — the
/// authority is still the [`Fix`](crate::Fix) on each violation.
@@ -44,6 +60,7 @@ pub fn all_rules() -> Vec<&'static dyn Rule> {
&rules::always_comb_blocking::AlwaysCombBlocking,
&rules::always_ff_non_blocking::AlwaysFfNonBlocking,
&rules::case_missing_default::CaseMissingDefault,
&rules::empty_item::EmptyItem,
&rules::enum_name_style::EnumNameStyle,
&rules::explicit_parameter_storage_type::ExplicitParameterStorageType,
&rules::module_filename::ModuleFilename,
@@ -60,10 +77,34 @@ pub fn all_rules() -> Vec<&'static dyn Rule> {
]
}
/// The rules a plain `lucisv check` runs: every rule whose
/// The rules a `lucisv check` over **one file** runs: every rule whose
/// [`default_on`](Rule::default_on) says so.
///
/// A run that can see the other files of the project runs
/// [`workspace_rules`] instead, which is this set plus the rules that
/// [`needs_workspace`](Rule::needs_workspace).
pub fn default_rules() -> Vec<&'static dyn Rule> {
all_rules().into_iter().filter(|rule| rule.default_on()).collect()
enabled_rules(false)
}
/// [`default_rules`] plus every rule that
/// [`needs_workspace`](Rule::needs_workspace) — the set a run that can ask
/// whether another file mentions a name uses.
///
/// "Can see the project" means a `lucisv check` over more than one file, or a
/// language server whose index holds something besides the buffer being
/// linted. Anything else — one file, a stdin buffer — runs
/// [`default_rules`], which is exactly the set v0.29.0 ran.
pub fn workspace_rules() -> Vec<&'static dyn Rule> {
enabled_rules(true)
}
/// The one filter both default sets are made of.
fn enabled_rules(workspace: bool) -> Vec<&'static dyn Rule> {
all_rules()
.into_iter()
.filter(|rule| rule.default_on() || (workspace && rule.needs_workspace()))
.collect()
}
/// The rule with this name, if there is one.
@@ -75,12 +116,17 @@ pub fn rule_by_name(name: &str) -> Option<&'static dyn Rule> {
/// keep it), then `ignore` removes from whatever is left. An unknown name on
/// either list is an error rather than a silent no-op — a typo'd `--select`
/// that quietly ran everything would be worse than a failed run.
///
/// `workspace` only reaches [`default_rules`]: an explicit `select` names the
/// rules it wants and gets them, oracle or no oracle, exactly as an explicit
/// `--select unused-signal` on one file has always run that rule.
pub fn select_rules(
select: &[String],
ignore: &[String],
workspace: bool,
) -> Result<Vec<&'static dyn Rule>, String> {
let mut chosen = if select.is_empty() {
default_rules()
enabled_rules(workspace)
} else {
let mut chosen = Vec::new();
for name in select {
@@ -142,11 +188,33 @@ mod tests {
#[test]
fn the_default_set_is_a_subset_of_every_rule() {
let all: Vec<&str> = all_rules().iter().map(|r| r.name()).collect();
let default: Vec<&str> = default_rules().iter().map(|r| r.name()).collect();
assert!(default.iter().all(|name| all.contains(name)));
assert!(default.len() < all.len(), "some rule must ship off by default");
for workspace in [false, true] {
let default: Vec<&str> = enabled_rules(workspace).iter().map(|r| r.name()).collect();
assert!(default.iter().all(|name| all.contains(name)));
assert!(
default.len() < all.len(),
"some rule must ship off by default even with a workspace"
);
for rule in all_rules() {
let on = rule.default_on() || (workspace && rule.needs_workspace());
assert_eq!(on, default.contains(&rule.name()), "{} {workspace}", rule.name());
}
}
}
/// The round's central claim: a run that can see the project runs strictly
/// more rules than one that cannot, and the difference is exactly the
/// rules that asked for a workspace.
#[test]
fn a_workspace_turns_on_exactly_the_rules_that_asked_for_one() {
let alone: Vec<&str> = default_rules().iter().map(|r| r.name()).collect();
let project: Vec<&str> = workspace_rules().iter().map(|r| r.name()).collect();
let added: Vec<&str> =
project.iter().copied().filter(|name| !alone.contains(name)).collect();
assert_eq!(added, vec!["multiply-driven", "undriven-net", "unused-signal"]);
assert!(alone.iter().all(|name| project.contains(name)), "a workspace never removes one");
for rule in all_rules() {
assert_eq!(rule.default_on(), default.contains(&rule.name()), "{}", rule.name());
assert_eq!(rule.needs_workspace(), added.contains(&rule.name()), "{}", rule.name());
}
}
@@ -154,31 +222,51 @@ mod tests {
fn an_off_by_default_rule_is_still_selectable() {
let off = all_rules()
.into_iter()
.find(|rule| !rule.default_on())
.find(|rule| !rule.default_on() && !rule.needs_workspace())
.map(|rule| rule.name().to_string())
.unwrap();
let chosen = select_rules(std::slice::from_ref(&off), &[]).unwrap();
let chosen = select_rules(std::slice::from_ref(&off), &[], false).unwrap();
assert_eq!(chosen.iter().map(|r| r.name()).collect::<Vec<_>>(), vec![off.as_str()]);
}
/// A named rule runs because it was named, not because the run happens to
/// have a workspace — the property that keeps `--select unused-signal` on
/// one file meaning what it has always meant.
#[test]
fn an_explicit_selection_ignores_whether_there_is_a_workspace() {
for workspace in [false, true] {
let chosen = select_rules(&["unused-signal".to_string()], &[], workspace).unwrap();
assert_eq!(chosen.iter().map(|r| r.name()).collect::<Vec<_>>(), vec!["unused-signal"]);
}
}
#[test]
fn selection_defaults_to_the_default_set() {
let chosen = select_rules(&[], &[]).unwrap();
assert_eq!(chosen.len(), default_rules().len());
for workspace in [false, true] {
let chosen = select_rules(&[], &[], workspace).unwrap();
assert_eq!(chosen.len(), enabled_rules(workspace).len());
}
}
#[test]
fn select_narrows_and_ignore_subtracts() {
let only = select_rules(&["no-tabs".to_string()], &[]).unwrap();
let only = select_rules(&["no-tabs".to_string()], &[], false).unwrap();
assert_eq!(only.iter().map(|r| r.name()).collect::<Vec<_>>(), vec!["no-tabs"]);
let without = select_rules(&[], &["no-tabs".to_string()]).unwrap();
let without = select_rules(&[], &["no-tabs".to_string()], false).unwrap();
assert!(!without.iter().any(|r| r.name() == "no-tabs"));
assert_eq!(without.len(), default_rules().len() - 1);
// And `ignore` is what turns a workspace rule back off — the off
// switch this round owes the user it switched a rule on for.
let quiet = select_rules(&[], &["unused-signal".to_string()], true).unwrap();
assert!(!quiet.iter().any(|r| r.name() == "unused-signal"));
assert_eq!(quiet.len(), workspace_rules().len() - 1);
let both = select_rules(
&["no-tabs".to_string(), "no-trailing-whitespace".to_string()],
&["no-tabs".to_string()],
false,
)
.unwrap();
assert_eq!(
@@ -189,9 +277,9 @@ mod tests {
#[test]
fn an_unknown_name_is_an_error_on_either_list() {
assert!(select_rules(&["nope".to_string()], &[]).is_err());
assert!(select_rules(&[], &["nope".to_string()]).is_err());
let message = select_rules(&["nope".to_string()], &[]).err().unwrap_or_default();
assert!(select_rules(&["nope".to_string()], &[], false).is_err());
assert!(select_rules(&[], &["nope".to_string()], false).is_err());
let message = select_rules(&["nope".to_string()], &[], false).err().unwrap_or_default();
assert!(message.contains("no-tabs"), "the error must list what is known: {message}");
}
+33 -23
View File
@@ -15,9 +15,15 @@ pub fn rules_markdown() -> String {
out.push_str(
"Generated from the rule registry by `vlog_linter::rules_markdown` — \
do not edit by hand.\n\n\
A rule marked **default** runs for a plain `lucisv check`; the others \
need `--select <name>`. Any rule can be turned off with `--ignore \
<name>` or waived in the source with `// lucisv: waive <name>`.\n\n",
A rule marked **on** runs for a plain `lucisv check`; the others need \
`--select <name>`. A rule marked **on (project)** runs by default \
only where lucisv can see the other files of the project — \
`lucisv check <dir>`, or the language server — because its one \
false-positive mode is a use in another file; over a single file or \
a stdin buffer it is off and must be selected. Any rule can be turned \
off with `--ignore <name>`, with `ignore` under `[lint]` in \
`lucisv.toml`, or waived in the source with `// lucisv: waive \
<name>`.\n\n",
);
out.push_str("| Rule | Default | Fix |\n|---|---|---|\n");
@@ -25,7 +31,7 @@ pub fn rules_markdown() -> String {
out.push_str(&format!(
"| [`{name}`](#{name}) | {default} | {fix} |\n",
name = rule.name(),
default = on_off(rule.default_on()),
default = default_word(rule),
fix = fix_word(rule),
));
}
@@ -34,23 +40,20 @@ pub fn rules_markdown() -> String {
for rule in all_rules() {
out.push_str(&format!("## {}\n\n", rule.name()));
out.push_str(&format!("{}.\n\n", capitalize(rule.summary())));
out.push_str(&format!(
"- Default: {}\n- Fix: {}\n\n",
on_off(rule.default_on()),
fix_word(rule)
));
out.push_str(&format!("- Default: {}\n- Fix: {}\n\n", default_word(rule), fix_word(rule)));
out.push_str(rule.doc());
out.push_str("\n\n");
}
out
}
/// How the table spells an on/off default.
fn on_off(on: bool) -> &'static str {
if on {
"**on**"
} else {
"off"
/// How the table spells a rule's default: on, off, or on wherever there is a
/// project to ask about ([`crate::Rule::needs_workspace`]).
fn default_word(rule: &dyn crate::Rule) -> &'static str {
match (rule.default_on(), rule.needs_workspace()) {
(true, _) => "**on**",
(false, true) => "**on (project)**",
(false, false) => "off",
}
}
@@ -105,11 +108,14 @@ mod tests {
let markdown = rules_markdown();
assert!(markdown.contains("| [`no-tabs`](#no-tabs) | **on** | safe |"));
assert!(markdown.contains("| [`module-name-style`](#module-name-style) | off | none |"));
// The three semantic rules ship off and fixless — see
// docs/features/semantic-lints/README.md for the corpus measurement
// behind each default.
// The three semantic rules are fixless, and default on exactly where
// there is a project to ask about a name — see
// docs/features/semantic-lints-on/README.md.
for name in ["multiply-driven", "undriven-net", "unused-signal"] {
assert!(markdown.contains(&format!("| [`{name}`](#{name}) | off | none |")), "{name}");
assert!(
markdown.contains(&format!("| [`{name}`](#{name}) | **on (project)** | none |")),
"{name}"
);
}
assert_eq!(fix_word(&crate::rules::no_tabs::NoTabs), Applicability::Safe.as_str());
}
@@ -129,9 +135,13 @@ mod tests {
"Generated from the rule registry by `vlog_linter::rules_markdown` — do not edit \
by hand.",
"",
"A rule marked **default** runs for a plain `lucisv check`; the others need \
`--select <name>`. Any rule can be turned off with `--ignore <name>` or waived \
in the source with `// lucisv: waive <name>`.",
"A rule marked **on** runs for a plain `lucisv check`; the others need \
`--select <name>`. A rule marked **on (project)** runs by default only where \
lucisv can see the other files of the project — `lucisv check <dir>`, or the \
language server — because its one false-positive mode is a use in another \
file; over a single file or a stdin buffer it is off and must be selected. Any \
rule can be turned off with `--ignore <name>`, with `ignore` under `[lint]` in \
`lucisv.toml`, or waived in the source with `// lucisv: waive <name>`.",
"",
"| Rule | Default | Fix |",
"|---|---|---|",
@@ -142,7 +152,7 @@ mod tests {
"## {}\n\n{}.\n\n- Default: {}\n- Fix: {}\n\n{}\n\n",
first_rule.name(),
capitalize(first_rule.summary()),
on_off(first_rule.default_on()),
default_word(first_rule),
fix_word(first_rule),
first_rule.doc(),
);
+189
View File
@@ -0,0 +1,189 @@
//! `empty-item` — no stray `;` where an item belongs.
use crate::context::LintContext;
use crate::registry::Rule;
use crate::violation::{Applicability, Fix, Violation};
use crate::visit::walk_items;
use vlog_parser::ast::ItemKind;
use vlog_parser::span::TextRange;
/// See [`Rule::doc`].
pub struct EmptyItem;
const NAME: &str = "empty-item";
impl Rule for EmptyItem {
fn name(&self) -> &'static str {
NAME
}
fn summary(&self) -> &'static str {
"drop a `;` that stands where an item belongs"
}
fn doc(&self) -> &'static str {
"A lone `;` in a module, generate, package, interface, program or class \
body is a *null item* (IEEE 1800-2017 A.1.4). It is legal and it means \
nothing, so it is almost always a typo — the habit of ending a block \
with a semicolon, carried over from C or from a statement context: \
`endgenerate;`, `end;`, `endmodule;`. slang reports the same thing as \
`-Wempty-member` (\"an unnecessary semicolon is located in a \
non-procedural scope\"). The fix deletes the `;`, and the line with it \
when the line held nothing else; a comment written on that line is \
kept. The procedural null *statement* (`begin ; end`) is a different \
construct and is not reported here."
}
fn fix(&self) -> Option<Applicability> {
Some(Applicability::Safe)
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let src = ctx.source();
let mut out = Vec::new();
walk_items(ctx.file(), &mut |item| {
if !matches!(item.kind, ItemKind::Empty) {
return;
}
let mut violation =
Violation::new(NAME, "unnecessary `;`; a null item does nothing", item.span);
if let Some(range) = deletion(src, item.span) {
violation = violation.with_fix(Fix::safe(vec![(range, String::new())]));
}
out.push(violation);
});
out
}
}
/// The bytes to delete for the null item at `semi`: the `;`, the horizontal
/// whitespace before it on its line, and — when nothing but whitespace and
/// other null items shared that line — the line's newline too.
///
/// `None` when the range would cover anything but `;` and whitespace, which
/// cannot happen given how it is built and is checked anyway: a fix that
/// swallowed a comment would break a hard invariant, so the guard is cheaper
/// than the risk.
fn deletion(src: &str, semi: TextRange) -> Option<TextRange> {
let bytes = src.as_bytes();
let mut start = semi.start as usize;
while start > 0 && matches!(bytes[start - 1], b' ' | b'\t') {
start -= 1;
}
let mut end = semi.end as usize;
// The rest of the line: only whitespace means the line can go, but only if
// what stood before this `;` on it was whitespace and null items — a `;`
// written after real code leaves that code, and its line, alone.
let mut after = end;
while matches!(bytes.get(after), Some(b' ' | b'\t' | b'\r')) {
after += 1;
}
let line_is_ours = src[line_start(src, start)..start]
.bytes()
.all(|b| matches!(b, b' ' | b'\t' | b';' | b'\r'));
if line_is_ours {
match bytes.get(after) {
Some(b'\n') => end = after + 1,
// A last line with no newline of its own.
None => end = after,
_ => {}
}
}
let range = TextRange::new(start as u32, end as u32);
src.get(range.as_range())?
.bytes()
.all(|b| matches!(b, b';' | b' ' | b'\t' | b'\r' | b'\n'))
.then_some(range)
}
/// Byte offset of the start of the line `at` sits on.
fn line_start(src: &str, at: usize) -> usize {
src[..at].rfind('\n').map_or(0, |i| i + 1)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::violation::apply_fixes;
fn violations(src: &str) -> Vec<Violation> {
EmptyItem.check(&LintContext::new(src, None))
}
fn fix(src: &str) -> String {
apply_fixes(src, &violations(src), false).output
}
#[test]
fn the_owners_shape_is_reported_and_the_semicolon_alone_is_removed() {
let src = "module m;\n generate\n endgenerate;\nendmodule\n";
let found = violations(src);
assert_eq!(found.len(), 1);
assert_eq!(found[0].rule, NAME);
assert_eq!(&src[found[0].span.as_range()], ";");
assert_eq!(fix(src), "module m;\n generate\n endgenerate\nendmodule\n");
}
#[test]
fn a_null_item_on_its_own_line_takes_the_line_with_it() {
let src = "module m;\n wire a;\n ;\nendmodule\n";
assert_eq!(fix(src), "module m;\n wire a;\nendmodule\n");
}
#[test]
fn a_comment_on_the_line_survives_the_fix() {
let src = "module m;\n generate\n endgenerate; // note\nendmodule\n";
assert_eq!(fix(src), "module m;\n generate\n endgenerate // note\nendmodule\n");
let src = "module m;\n wire a;\n ; // why\nendmodule\n";
let fixed = fix(src);
assert!(fixed.contains("// why"), "the comment was dropped:\n{fixed}");
}
#[test]
fn a_leading_comment_is_left_where_it_was() {
let src = "module m;\n // why\n ;\nendmodule\n";
assert_eq!(fix(src), "module m;\n // why\nendmodule\n");
}
#[test]
fn a_run_of_null_items_is_one_finding_each_and_the_line_goes() {
let src = "module m;\n wire a;\n ;;;\nendmodule\n";
assert_eq!(violations(src).len(), 3);
assert_eq!(fix(src), "module m;\n wire a;\nendmodule\n");
}
#[test]
fn every_item_scope_is_reached() {
let sources = [
"module m;\nendmodule;\n",
"module m;\n ;\nendmodule\n",
"interface ifc;\n ;\nendinterface\n",
"package p;\n ;\nendpackage\n",
"class c;\n ;\nendclass\n",
"module m;\n generate\n ;\n endgenerate\nendmodule\n",
"module m;\n for (genvar i = 0; i < 2; i++) begin : g\n ;\n end\nendmodule\n",
];
for src in sources {
assert_eq!(violations(src).len(), 1, "{src}");
}
}
#[test]
fn the_procedural_null_statement_is_not_this_rule() {
assert!(violations("module m;\n initial begin\n ;\n end\nendmodule\n").is_empty());
}
#[test]
fn endfunction_and_endtask_semicolons_are_not_reported() {
// They are recorded on the declaration, not as null items.
let src =
"module m;\n function int f();\n endfunction;\n task t();\n endtask;\nendmodule\n";
assert!(violations(src).is_empty());
}
#[test]
fn a_clean_file_is_clean() {
assert!(violations("module m;\n wire a;\nendmodule\n").is_empty());
}
}
+1
View File
@@ -8,6 +8,7 @@
pub mod always_comb_blocking;
pub mod always_ff_non_blocking;
pub mod case_missing_default;
pub mod empty_item;
pub mod enum_name_style;
pub mod explicit_parameter_storage_type;
pub mod module_filename;
@@ -48,6 +48,16 @@ impl Rule for MultiplyDriven {
false
}
fn needs_workspace(&self) -> bool {
// This rule never consults the oracle: nothing another file does can
// take an in-file driver away, so a cross-file use cannot make one of
// its findings wrong. It shares the gate anyway, so "the semantic
// rules need a project" is one rule to explain rather than three, and
// so a single-file run keeps v0.29.0's answers exactly — see
// `docs/features/semantic-lints-on/README.md`.
true
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let signals = ctx.signals();
let mut found = Vec::new();
@@ -116,6 +126,29 @@ mod tests {
violations(src).iter().map(|v| v.message.clone()).collect()
}
/// An oracle that says exactly these names are mentioned in another file.
struct Elsewhere(&'static [&'static str]);
impl crate::MentionOracle for Elsewhere {
fn mentioned_elsewhere(&self, name: &str) -> bool {
self.0.contains(&name)
}
}
/// This rule never consults the oracle: nothing another file does can take
/// an in-file driver away, so silencing on a mention would be a false
/// negative bought for nothing. It shares the *default* gate with the
/// other two and nothing else.
#[test]
fn a_name_other_files_mention_is_still_reported() {
let src = "module m (input logic d);\n logic a;\n always_comb a = d;\n\
\x20 always_comb a = ~d;\nendmodule\n";
let oracle = Elsewhere(&["a"]);
let ctx = LintContext::new(src, None).with_oracle(&oracle);
assert_eq!(MultiplyDriven.check(&ctx).len(), 1, "the oracle must not silence it");
assert_eq!(MultiplyDriven.check(&LintContext::new(src, None)).len(), 1);
}
#[test]
fn two_always_blocks_driving_one_variable_are_reported() {
let src = "module m (input logic c, output logic q);\n logic a;\n\
+53 -2
View File
@@ -35,15 +35,27 @@ impl Rule for UndrivenNet {
module that instantiates with `.*`, anything declared with an \
initializer, and anything nothing reads (that is `unused-signal`'s \
subject, not this one). What is left is the honest case: a plain \
name read in ordinary code with no assignment anywhere in the file."
name read in ordinary code with no assignment anywhere in the file.\n\n\
When the run can see the project, a name any **other** file writes \
down is left alone too: it may be driven from there through a \
hierarchical assignment or a testbench `force`. That is why this \
rule runs by default over a directory and stays off for a single \
file or a stdin buffer."
}
fn default_on(&self) -> bool {
// See docs/features/semantic-lints/README.md: measured over the
// 860-file corpus before this was decided.
// 860-file corpus before this was decided. Off without a workspace,
// where a signal driven from another file's hierarchy is invisible.
false
}
fn needs_workspace(&self) -> bool {
// With a `MentionOracle` the cross-file blind spot is closed and the
// rule defaults on — `docs/features/semantic-lints-on/README.md`.
true
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let signals = ctx.signals();
let mut found = Vec::new();
@@ -51,6 +63,13 @@ 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.
@@ -83,6 +102,38 @@ mod tests {
.collect()
}
/// An oracle that says exactly these names are mentioned in another file.
struct Elsewhere(&'static [&'static str]);
impl crate::MentionOracle for Elsewhere {
fn mentioned_elsewhere(&self, name: &str) -> bool {
self.0.contains(&name)
}
}
fn names_in_a_project(src: &str, elsewhere: &'static [&'static str]) -> Vec<String> {
let oracle = Elsewhere(elsewhere);
let ctx = LintContext::new(src, None).with_oracle(&oracle);
UndrivenNet
.check(&ctx)
.iter()
.map(|v| v.message.split('`').nth(1).unwrap_or_default().to_string())
.collect()
}
/// The cross-file driver: a testbench that writes `tb.dut.a` — or forces
/// it — drives a signal this file sees no driver for. The census cannot
/// tell a cross-file *read* from a cross-file *drive*, so the rule takes
/// the silent direction for both.
#[test]
fn a_signal_another_file_mentions_may_be_driven_from_there() {
let src = "module m (output logic q, output logic r);\n wire a;\n wire b;\n\
\x20 assign q = a;\n assign r = b;\nendmodule\n";
assert_eq!(names(src), vec!["a", "b"], "without a project, both");
assert_eq!(names_in_a_project(src, &["a"]), vec!["b"]);
assert_eq!(names_in_a_project(src, &[]), names(src), "an empty project changes nothing");
}
#[test]
fn a_read_but_undriven_signal_is_reported() {
let src = "module m (output logic q);\n wire a;\n assign q = a;\nendmodule\n";
+66 -2
View File
@@ -38,15 +38,29 @@ impl Rule for UnusedSignal {
`` `MY_ASSERT(foo) `` would otherwise be reported as unused. The \
cost of the guard is that two same-named unused signals in one file \
shield each other — a false negative, which is the harmless \
direction for a rule like this."
direction for a rule like this.\n\n\
The same guard reaches past the file when the run can see the \
project: a name any **other** file writes down is left alone, \
because a signal read through `tb.dut.sig`, forced from a testbench \
or named in another file's macro argument is used and no single-file \
analysis can tell. That is why this rule runs by default over a \
directory and stays off for a single file or a stdin buffer, where \
there is nothing to ask."
}
fn default_on(&self) -> bool {
// See docs/features/semantic-lints/README.md: measured over the
// 860-file corpus before this was decided.
// 860-file corpus before this was decided. Off without a workspace,
// where a signal read from another file's hierarchy is invisible.
false
}
fn needs_workspace(&self) -> bool {
// With a `MentionOracle` the cross-file blind spot is closed and the
// rule defaults on — `docs/features/semantic-lints-on/README.md`.
true
}
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
let signals = ctx.signals();
let semantics = ctx.semantics();
@@ -62,6 +76,14 @@ impl Rule for UnusedSignal {
if signals.mentioned_outside_declarations(&decl.name) {
continue;
}
// The same guard, past the file boundary: a name some other file
// in the project writes down may be read through a hierarchical
// path, forced by a testbench, or passed to a macro there. This
// is the rule's one remaining false-positive mode, and it is why
// the rule is off in a run with no oracle to ask.
if ctx.mentioned_elsewhere(&decl.name) {
continue;
}
found.push(Violation::new(
NAME,
format!("`{}` is declared but never used", decl.name),
@@ -80,6 +102,48 @@ mod tests {
UnusedSignal.check(&LintContext::new(src, None))
}
/// An oracle that says exactly these names are mentioned in another file.
struct Elsewhere(&'static [&'static str]);
impl crate::MentionOracle for Elsewhere {
fn mentioned_elsewhere(&self, name: &str) -> bool {
self.0.contains(&name)
}
}
/// The rule's answer when the project mentions `elsewhere`.
fn names_in_a_project(src: &str, elsewhere: &'static [&'static str]) -> Vec<String> {
let oracle = Elsewhere(elsewhere);
let ctx = LintContext::new(src, None).with_oracle(&oracle);
UnusedSignal
.check(&ctx)
.iter()
.map(|v| v.message.split('`').nth(1).unwrap_or_default().to_string())
.collect()
}
/// QA's two-file false positive, from `docs/features/semantic-lints/`:
/// `dut.sv` declares `dbg_probe`, `tb.sv` reads `d.dbg_probe`. Linting
/// `dut.sv` alone reported it; with the project's census it says nothing.
#[test]
fn a_signal_another_file_mentions_is_not_reported() {
let src = "module dut;\n logic dbg_probe;\n logic dead;\nendmodule\n";
assert_eq!(names(src), vec!["dbg_probe", "dead"], "without a project, both");
assert_eq!(
names_in_a_project(src, &["dbg_probe"]),
vec!["dead"],
"with one, only the name nothing else writes down"
);
}
/// The oracle is additional, never a replacement: an empty project says
/// exactly what no project says.
#[test]
fn an_oracle_that_knows_nothing_changes_nothing() {
let src = "module dut;\n logic dbg_probe;\n logic dead;\nendmodule\n";
assert_eq!(names_in_a_project(src, &[]), names(src));
}
fn names(src: &str) -> Vec<String> {
violations(src)
.iter()
+31 -1
View File
@@ -394,6 +394,31 @@ impl Scanner {
// An `include` in a module body is arbitrary code — it may
// declare, read or drive anything — and lucisv does not follow one.
ItemKind::Directive(raw) if is_include(&raw.text) => self.blind(module),
// A constraint reads its operands and drives nothing, so it
// records nothing here: since `constraint-bodies` its names are
// ordinary resolved references, which `finish` counts as reads.
// Routing it to `opaque_spans` — where it went while it was a
// verbatim leaf — would now throw that away. A body that fell
// back to a verbatim capture is still an `ItemKind::Verbatim`
// and keeps the opaque posture below.
// A covergroup samples its operands and drives nothing, so it
// records nothing here either: since `covergroup-bodies` the
// names inside it are ordinary resolved references, which
// `finish` counts as reads. A covergroup that fell back to a
// verbatim capture is still an `ItemKind::Verbatim` and keeps the
// opaque posture below.
// An assertion, a `property`/`sequence` declaration and a
// `default disable iff` read their operands and drive nothing,
// for exactly the reason a constraint and a covergroup do: since
// `sva-bodies` every name inside one is an ordinary resolved
// reference, which `finish` counts as a read. A spec that fell
// back to a verbatim capture is still an `ItemKind::Verbatim` and
// keeps the opaque posture below.
ItemKind::Constraint(_)
| ItemKind::Covergroup(_)
| ItemKind::PropSeqDecl(_)
| ItemKind::Assertion(_)
| ItemKind::DefaultDisable(_) => {}
// Nothing here can be read: a macro is not expanded, a directive
// is not evaluated, a verbatim block is not modelled, and an
// error leaf did not parse. Every name they mention is dropped.
@@ -612,7 +637,12 @@ fn lvalue_targets(expr: &Expr, whole: bool, out: &mut Vec<(TextRange, bool)>) {
/// expression.
fn increment_target(expr: &Expr) -> Option<&Expr> {
match &expr.kind {
ExprKind::Postfix { expr, op } | ExprKind::Unary { expr, op }
// `..` skips the `comments` slot the comment-slots round added to
// `ExprKind::Unary` and `ExprKind::Postfix`
// (docs/features/comment-slots/README.md) — a mechanical pattern
// update, flagged there as a handshake request against this file,
// which that round does not otherwise touch.
ExprKind::Postfix { expr, op, .. } | ExprKind::Unary { expr, op, .. }
if op == "++" || op == "--" =>
{
Some(expr)
+43 -1
View File
@@ -4,7 +4,9 @@
//! decides what it cares about. `Error` leaves from a tolerant parse hold raw
//! text and no children, so they are visited and matched by nothing.
use vlog_parser::ast::{GenBlock, GenElse, Item, ItemKind, ParamPort, SourceFile, Stmt, StmtKind};
use vlog_parser::ast::{
Fragment, GenBlock, GenElse, Item, ItemKind, ParamPort, SourceFile, Stmt, StmtKind,
};
/// Calls `f` on every item in the file, nested items included.
pub(crate) fn walk_items(file: &SourceFile, f: &mut dyn FnMut(&Item)) {
@@ -37,6 +39,21 @@ fn items(list: &[Item], f: &mut dyn FnMut(&Item)) {
}
}
}
// A `constraint` body holds constraint items — expressions and
// nested sets — and neither an `Item` nor a `Stmt`, so there is
// nothing here for an item or statement walk to descend into.
// The rules that need to see inside a constraint read the
// reference table, which since `constraint-bodies` reaches every
// name in the body. Recorded as its own arm rather than left to
// the catch-all so the next reader does not re-derive it.
ItemKind::Constraint(_) => {}
// A covergroup body holds cover items — coverpoints, crosses,
// bins, options — and neither an `Item` nor a `Stmt`, so there is
// nothing here for an item or statement walk to descend into
// either. The rules that need to see inside read the reference
// table, which since `covergroup-bodies` reaches every name a
// covergroup samples.
ItemKind::Covergroup(_) => {}
ItemKind::GenFor(gen_for) => gen_block(&gen_for.body, f),
ItemKind::GenCase(gen_case) => {
for case_item in &gen_case.items {
@@ -54,6 +71,18 @@ fn gen_block(block: &GenBlock, f: &mut dyn FnMut(&Item)) {
/// Calls `f` on every statement of the file, nested statements included.
pub(crate) fn walk_all_stmts(file: &SourceFile, f: &mut dyn FnMut(&Stmt)) {
// A statement fragment is a whole file of statements with no item around
// them (`docs/features/fragment-mode/README.md`). Every statement rule
// applies to them exactly as it does inside an `always` body — the code is
// the same code, it is just `` `include``d rather than written in place.
// The other two fragment shapes hold no `Item` and no `Stmt`, so an item
// or statement walk has nothing to descend into, which is the posture a
// constraint and a covergroup body already keep.
if let Some(Fragment::Statements(stmts)) = &file.fragment {
for stmt in stmts {
walk_stmts(stmt, f);
}
}
walk_items(file, &mut |item| match &item.kind {
ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => {
walk_stmts(stmt, f)
@@ -171,6 +200,19 @@ mod tests {
assert_eq!(count_assignments(src), 2);
}
#[test]
fn reaches_the_statements_of_a_statement_fragment() {
// A `.svh` that is nothing but the middle of a procedural block has no
// item around its statements, so the item walk cannot reach them —
// without the fragment arm every statement rule goes silent on the
// file. See `docs/features/fragment-mode/README.md`.
let src = "x = 1;\nif (a) begin\n y = 2;\nend\n";
let (file, diagnostics) = parse_source_tolerant(src);
assert!(diagnostics.is_empty(), "{diagnostics:?}");
assert!(file.items.is_empty(), "a fragment file has no items");
assert_eq!(count_assignments(src), 2);
}
#[test]
fn reaches_items_and_statements_inside_a_class_body() {
let src = "class c;\n\
@@ -0,0 +1,47 @@
# The linter's posture on assertion bodies, after TODO.md §27 gave them a real
# AST. See docs/features/sva-bodies/README.md.
# undriven-net now sees a read written inside a concurrent assertion: the
# operand of a property expression is an ordinary resolved reference, so a net
# read only there is no longer invisible. Before the sva-bodies round the whole
# assertion was an opaque span and `clk` had zero reads, so it was skipped.
# This is the same verdict change `covergroup-bodies` made, for the same
# reason.
#select undriven-net
module m;
logic clk;
//^ 9 undriven-net
logic sig;
assign sig = 1'b1;
assert property (@(posedge clk) sig |-> ##[1:2] sig);
endmodule
====
# the same for a name written only inside a `property` declaration's body
#select undriven-net
module m;
logic clk;
//^ 9 undriven-net
property p;
@(posedge clk) 1'b1;
endproperty
endmodule
====
# an assertion the grammar cannot read is opaque again: the names inside it
# bind nothing, exactly as they did before the round, so nothing is reported
#select undriven-net
module m;
logic clk;
assert property (@(posedge clk) $blah $blah);
endmodule
====
# unused-signal is unchanged, and deliberately so: its mention guard already
# shielded a name written inside a verbatim region, so a signal read only by an
# assertion was never reported and still is not. `constraint-bodies` made the
# same observation about its own round.
#select unused-signal
module m;
logic clk;
logic sig;
assign sig = 1'b1;
assert property (@(posedge clk) sig);
endmodule
@@ -0,0 +1,53 @@
# The linter's posture on constraint bodies, after TODO.md §20 gave them a
# real AST. See docs/features/constraint-bodies/README.md.
# undriven-net now sees a read written inside a `randomize() with` block: the
# names in the block are ordinary resolved references, so a net read only
# there is no longer invisible. Before the constraint-bodies round only `req`
# was reported.
#select undriven-net
class item;
rand int addr;
endclass
module m;
wire w;
//^ 8 undriven-net
item req;
//^ 8 undriven-net
bit ok;
initial ok = req.randomize() with { addr == w; };
endmodule
====
# a `with` block the grammar does not know is opaque again: the names inside
# it bind nothing, exactly as they did before the round
#select undriven-net
class item;
rand int addr;
endclass
module m;
wire w;
item req;
//^ 8 undriven-net
bit ok;
initial ok = req.randomize() with { `MY_HALF addr == w; };
endmodule
====
# empty-item does not fire on a null *constraint* item: a `;` inside a
# constraint body is a ConstraintItemKind::Empty, not an ItemKind::Empty
#select empty-item
class item;
rand int n;
constraint c {
n < 4;
;
}
endclass
====
# an item walk still reaches a class body past a constraint
#select explicit-parameter-storage-type
class item;
rand int n;
constraint c { n < 4; }
localparam B = 2;
//^ 14 explicit-parameter-storage-type
endclass
@@ -0,0 +1,49 @@
# The linter's posture on covergroup bodies, after TODO.md §21 gave them a
# real AST. See docs/features/covergroup-bodies/README.md.
# undriven-net now sees a read written inside a covergroup: the sampled
# expression is an ordinary resolved reference, so a net read only there is no
# longer invisible. Before the covergroup-bodies round the whole block was an
# opaque span and `w` had zero reads, so it was skipped.
#select undriven-net
module m;
wire w;
//^ 8 undriven-net
covergroup cg;
cp: coverpoint w;
endgroup
endmodule
====
# a covergroup the grammar does not know is opaque again: the names inside it
# bind nothing, exactly as they did before the round
#select undriven-net
module m;
wire w;
covergroup cg;
cp: coverpoint w `GPR_BIN_TYPES
endgroup
endmodule
====
# empty-item does not fire on a null *cover* item, nor on a null bin item: a
# `;` inside a covergroup body is a CoverItemKind::Empty, not an ItemKind::Empty
#select empty-item
module m;
covergroup cg;
cp: coverpoint a {
bins v = {1};
;
}
;
endgroup
endmodule
====
# an item walk still reaches a class body past a covergroup
#select explicit-parameter-storage-type
class item;
rand int n;
covergroup cg;
cp: coverpoint n;
endgroup
localparam B = 2;
//^ 14 explicit-parameter-storage-type
endclass
@@ -0,0 +1,181 @@
# the owner's report: a stray `;` after `endgenerate`
module m;
generate
endgenerate;
//^ 14 empty-item
endmodule
====
# a null item on its own line at module scope
module m;
wire a;
;
//^ 3 empty-item
endmodule
====
# `endmodule;` — a null item at file scope
module m;
endmodule;
//^ 10 empty-item
====
# every non-procedural scope is reached: package
package p;
localparam int W = 1;
;
//^ 3 empty-item
endpackage
====
# every non-procedural scope is reached: interface
interface ifc;
logic a;
;
//^ 3 empty-item
endinterface
====
# every non-procedural scope is reached: class
class c;
int x;
;
//^ 3 empty-item
endclass
====
# every non-procedural scope is reached: inside a generate region
module m;
generate
;
//^ 5 empty-item
endgenerate
endmodule
====
# every non-procedural scope is reached: inside a generate-for body
module m;
for (genvar i = 0; i < 2; i++) begin : g
;
//^ 5 empty-item
end
endmodule
====
# `end;` after a generate block, and a run of null items after it
module m;
if (N > 1) begin : g1
wire x;
end;
//^ 6 empty-item
;;
//^ 3 empty-item
//^ 4 empty-item
endmodule
====
# the procedural null statement is a different construct and is quiet
module m;
initial begin
;
end
endmodule
====
# `endfunction;` / `endtask;` are recorded on the declaration, not as null items
module m;
function int f();
endfunction;
task t();
endtask;
endmodule
====
# waived on the same line
module m;
wire a;
; // lucisv: waive empty-item
endmodule
====
# a clean file is clean
module m;
wire a;
endmodule
====
# fix: the `;` alone goes, the closing keyword stays
module m;
generate
endgenerate;
//^ 14 empty-item
endmodule
----
module m;
generate
endgenerate
//^ 14 empty-item
endmodule
====
# fix: a null item alone on its line takes the line with it
module m;
wire a;
;
//^ 3 empty-item
endmodule
----
module m;
wire a;
//^ 3 empty-item
endmodule
====
# fix: a run of null items leaves no blank line behind
module m;
wire a;
;;;
//^ 3 empty-item
//^ 4 empty-item
//^ 5 empty-item
endmodule
----
module m;
wire a;
//^ 3 empty-item
//^ 4 empty-item
//^ 5 empty-item
endmodule
====
# fix: a comment written after the `;` survives it
module m;
generate
endgenerate; // note
//^ 14 empty-item
endmodule
----
module m;
generate
endgenerate // note
//^ 14 empty-item
endmodule
====
# fix: a comment on a null item's own line keeps the line alive
module m;
wire a;
; // why it was here
//^ 3 empty-item
endmodule
----
module m;
wire a;
// why it was here
//^ 3 empty-item
endmodule
====
# fix: a comment written above a null item stays where it was
module m;
// why it was here
;
//^ 3 empty-item
endmodule
----
module m;
// why it was here
//^ 3 empty-item
endmodule
====
# fix: `endmodule;` at file scope
module m;
endmodule;
//^ 10 empty-item
----
module m;
endmodule
//^ 10 empty-item
====
@@ -23,3 +23,21 @@ endmodule
module foo_bar; // lucisv: waive module-name-style
//^ 17 unused-waiver
endmodule
====
# a `program` reuses `ItemKind::Module`, so every rule that matches a module
# matches it — deliberately, and pinned here so the decision is not silently
# reversed. The rule's *message* still says "module"; that wording is
# pre-existing for `interface` and filed, not fixed, in
# docs/features/clocking-wave/README.md's Handshakes.
#select module-name-style,unused-waiver
program FooBar;
//^ 9 module-name-style
endprogram
====
# ... and the body of a program is descended into like a module's
#select module-name-style,unused-waiver
program top;
module Inner;
//^ 10 module-name-style
endmodule
endprogram
@@ -161,3 +161,22 @@ module m (input logic c, output logic q);
always_comb a = c;
assign q = a;
endmodule
====
# with a project behind it the rule is on by default — no #select needed
#workspace
module m (input logic clk, input logic d);
logic a;
//^ 9 multiply-driven
always_comb a = d;
always_comb a = ~d;
endmodule
====
# it never consults the oracle: a name other files mention still reports,
# because nothing another file does can take an in-file driver away
#workspace a
module m (input logic clk, input logic d);
logic a;
//^ 9 multiply-driven
always_comb a = d;
always_comb a = ~d;
endmodule
@@ -161,3 +161,18 @@ module m (input logic c, output logic q);
assign a = c;
assign q = a;
endmodule
====
# with a project behind it the rule is on by default — no #select needed
#workspace
module m (output logic q);
wire a;
//^ 8 undriven-net
assign q = a;
endmodule
====
# a signal another file writes down may be driven from there: silence
#workspace a
module m (output logic q);
wire a;
assign q = a;
endmodule
@@ -116,3 +116,56 @@ module m (input logic c, output logic q);
assign a = c;
assign q = a;
endmodule
====
# a clocking block is opaque: the signals it names — and the expressions its
# items bind them to — are taken out through the token-level guard, so neither
# the clocking signal nor what it drives is ever reported.
# See docs/features/clocking-wave/README.md.
#select unused-signal,unused-waiver
module m;
wire tms_int;
wire tdo;
clocking cb @(posedge clk);
output tms = tms_int;
input tdo;
endclocking
endmodule
====
# a `default disable iff` is a verbatim item, so it is opaque the same way a
# concurrent assertion is: it neither reports nor rescues the names it mentions
#select unused-signal,unused-waiver
module m;
wire rst_n;
default disable iff !rst_n;
endmodule
====
# an `iff` gate on an event-control term is an ordinary read, so the signal it
# names is not reported unused
#select unused-signal,unused-waiver
module m (input logic clk, output logic q);
wire enable;
always @(posedge clk iff enable) q <= 1;
endmodule
====
# with a project behind it the rule is on by default — no #select needed
#workspace
module m;
wire a;
//^ 8 unused-signal
endmodule
====
# and a name some other file writes down is left alone (QA's two-file repro)
#workspace dbg_probe
module dut;
logic dbg_probe;
logic really_dead;
//^ 9 unused-signal
endmodule
====
# the oracle only speaks about other files: an in-file name is judged as ever
#select unused-signal,unused-waiver
#workspace something_else
module m;
wire a;
//^ 8 unused-signal
endmodule
+55 -16
View File
@@ -20,6 +20,11 @@
//! - `#path <p>` — lint the source as if it were read from this file path.
//! - `#select ...` — comma-separated rule names, `lucisv check --select`
//! semantics (replaces the default rule set).
//! - `#workspace [name,...]` — run the case as part of a *project*: the rules
//! that need a workspace default on, and a `MentionOracle` answers "yes,
//! some other file mentions this" for each listed name (an empty list is a
//! project in which nothing else mentions anything). Without the header
//! there is no oracle at all, which is a single-file `lucisv check`.
//!
//! A `----` line splits a case into `(input, expected fixed output)`: the
//! harness then applies Safe fixes in the CLI's fix→re-lint loop and asserts
@@ -36,7 +41,8 @@ use std::path::PathBuf;
use vlog_formatter::{format_source, Config};
use vlog_linter::{
apply_fixes, lint, rule_by_name, run, select_rules, Applicability, ParsedSource, Rule,
apply_fixes, lint, rule_by_name, select_rules, Applicability, LintContext, MentionOracle,
ParsedSource, Rule,
};
use vlog_parser::LineIndex;
@@ -48,10 +54,23 @@ struct Case {
tolerant: bool,
path: Option<String>,
select: Vec<String>,
/// `#workspace`: `None` is a run with no oracle; `Some(names)` is a run
/// with one that says those names are mentioned in some other file.
workspace: Option<Vec<String>>,
input: String,
fixed: Option<String>,
}
/// The `#workspace` header's oracle: a fixed list of names other files
/// mention.
struct Elsewhere(Vec<String>);
impl MentionOracle for Elsewhere {
fn mentioned_elsewhere(&self, name: &str) -> bool {
self.0.iter().any(|held| held == name)
}
}
/// One `//^ <col> <rule>` marker, resolved to the line it points at.
struct Expect {
line: u32,
@@ -92,6 +111,7 @@ fn split_case(file: &str, start: usize, block: &[&str]) -> Result<Case, String>
let mut tolerant = false;
let mut path = None;
let mut select = Vec::new();
let mut workspace = None;
let mut body = block;
while let Some(first) = body.first() {
if !first.starts_with('#') && !first.trim().is_empty() {
@@ -109,6 +129,12 @@ fn split_case(file: &str, start: usize, block: &[&str]) -> Result<Case, String>
path = Some(p.trim().to_string());
} else if let Some(s) = rest.strip_prefix("select ") {
select = s.split(',').map(|r| r.trim().to_string()).collect();
} else if rest == "workspace" {
workspace = Some(Vec::new());
} else if let Some(s) = rest.strip_prefix("workspace ") {
workspace = Some(
s.split(',').map(|n| n.trim().to_string()).filter(|n| !n.is_empty()).collect(),
);
} else if rest == "tolerant" {
tolerant = true;
} else if rest.starts_with("SKIP") {
@@ -120,7 +146,7 @@ fn split_case(file: &str, start: usize, block: &[&str]) -> Result<Case, String>
} else if directive_like {
return Err(format!(
"{file}:{start}: unknown directive `#{}` \
(known: #path, #select, #tolerant, #SKIP; \
(known: #path, #select, #workspace, #tolerant, #SKIP; \
a case name needs a space after `#`)",
rest.split_whitespace().next().unwrap_or(rest)
));
@@ -143,7 +169,15 @@ fn split_case(file: &str, start: usize, block: &[&str]) -> Result<Case, String>
if input.trim().is_empty() {
return Err(format!("{file}:{start}: case has no source"));
}
Ok(Case { name, line: start, skip, tolerant, path, select, input, fixed })
Ok(Case { name, line: start, skip, tolerant, path, select, workspace, input, fixed })
}
/// Attaches the case's oracle, if it declared one.
fn with_oracle<'a>(ctx: LintContext<'a>, oracle: Option<&'a Elsewhere>) -> LintContext<'a> {
match oracle {
Some(oracle) => ctx.with_oracle(oracle),
None => ctx,
}
}
/// Rejoins lines into a source string with a trailing newline (empty stays empty).
@@ -183,7 +217,8 @@ fn expectations(input: &str) -> Result<Vec<Expect>, String> {
/// Runs one case; `Err` is the complete, readable failure report.
fn check_case(file: &str, case: &Case) -> Result<(), String> {
let at = format!("{file}:{} [{}]", case.line, case.name);
let rules = select_rules(&case.select, &[]).map_err(|e| format!("{at}: bad #select: {e}"))?;
let rules = select_rules(&case.select, &[], case.workspace.is_some())
.map_err(|e| format!("{at}: bad #select: {e}"))?;
let expected = expectations(&case.input).map_err(|e| format!("{at}: {e}"))?;
for expect in &expected {
if rule_by_name(&expect.rule).is_none() {
@@ -202,13 +237,15 @@ fn check_case(file: &str, case: &Case) -> Result<(), String> {
}
let path = case.path.clone().map(PathBuf::from);
let violations = run(&case.input, path.clone(), &rules);
let oracle = case.workspace.clone().map(Elsewhere);
let own = LintContext::new(&case.input, path.clone());
let violations = lint(&with_oracle(own, oracle.as_ref()), &rules);
// "One parse, two tools", held over every case: a context built from
// pre-parsed products must find exactly what one built from the source
// does — rule, message, span and fix alike (the Debug form carries all).
let parsed = ParsedSource::parse(&case.input);
let via_products = lint(&parsed.context(path.clone()), &rules);
let via_products = lint(&with_oracle(parsed.context(path.clone()), oracle.as_ref()), &rules);
if format!("{violations:?}") != format!("{via_products:?}") {
return Err(format!(
"{at}: linting from pre-parsed products found something different from \
@@ -233,7 +270,7 @@ fn check_case(file: &str, case: &Case) -> Result<(), String> {
}
match &case.fixed {
Some(expected_fixed) => check_fix(&at, case, &rules, path, expected_fixed),
Some(expected_fixed) => check_fix(&at, case, &rules, path, oracle.as_ref(), expected_fixed),
None => Ok(()),
}
}
@@ -294,6 +331,7 @@ fn check_fix(
case: &Case,
rules: &[&'static dyn Rule],
path: Option<PathBuf>,
oracle: Option<&Elsewhere>,
expected_fixed: &str,
) -> Result<(), String> {
let mut fixed = case.input.clone();
@@ -301,7 +339,7 @@ fn check_fix(
if round >= 10 {
return Err(format!("{at}: fixing did not settle within 10 rounds"));
}
let found = run(&fixed, path.clone(), rules);
let found = lint(&with_oracle(LintContext::new(&fixed, path.clone()), oracle), rules);
let out = apply_fixes(&fixed, &found, false);
if out.applied == 0 {
break;
@@ -319,14 +357,15 @@ fn check_fix(
// offer a Safe fix — a violation without a fix (or with an Unsafe one)
// may legitimately survive.
let index = LineIndex::new(&fixed);
let still_fixable: Vec<String> = run(&fixed, path.clone(), rules)
.iter()
.filter(|v| v.fix.as_ref().is_some_and(|f| f.applicability == Applicability::Safe))
.map(|v| {
let (line, col) = index.line_col(v.span.start);
format!(" {line}:{col} {} — {}", v.rule, v.message)
})
.collect();
let still_fixable: Vec<String> =
lint(&with_oracle(LintContext::new(&fixed, path.clone()), oracle), rules)
.iter()
.filter(|v| v.fix.as_ref().is_some_and(|f| f.applicability == Applicability::Safe))
.map(|v| {
let (line, col) = index.line_col(v.span.start);
format!(" {line}:{col} {} — {}", v.rule, v.message)
})
.collect();
if !still_fixable.is_empty() {
return Err(format!(
"{at}: the fixed output still has Safe-fixable findings:\n{}",
File diff suppressed because it is too large. Load diff
+14 -2
View File
@@ -22,7 +22,7 @@ pub enum DefineKind {
}
/// One `` `define`` or `` `undef`` directive, as written.
#[derive(Debug, Clone)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Define {
/// Whether this entry defines the name or undefines it.
pub kind: DefineKind,
@@ -48,12 +48,24 @@ pub struct Define {
///
/// Redefinition is legal Verilog, so a name can have several definitions; they
/// are all kept and [`DefineTable::latest`] picks the last one.
#[derive(Debug, Clone, Default)]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DefineTable {
entries: Vec<Define>,
}
impl DefineTable {
/// A table from entries that are already known, in source order.
///
/// The inverse of [`DefineTable::entries`], for the one caller that has a
/// file's directives without the file's tokens: the workspace index's
/// persistent cache, which stores what a parse found and restores it
/// (`docs/features/index-persistence/README.md`). Nothing is re-derived
/// here — `collect_defines` is still the only thing that *reads* a table
/// out of a file.
pub fn from_entries(entries: Vec<Define>) -> DefineTable {
DefineTable { entries }
}
/// Every recorded directive, `` `undef``s included, in source order.
pub fn entries(&self) -> &[Define] {
&self.entries
+474 -3
View File
@@ -187,9 +187,31 @@ impl<'a> RawLexer<'a> {
// Compiler directives: capture through end of line, honoring `\`
// continuations (used by `define).
if c == b'`' {
while self.pos < self.src.len() && self.peek() != b'\n' {
// Stop before a trailing comment on the same line.
if self.peek() == b'/' && (self.peek_at(1) == b'/' || self.peek_at(1) == b'*') {
// One tracker per directive: it carries the formal list's paren
// depth across the lines below instead of re-deriving it, which is
// what keeps an *unclosed* list linear. See [`DefineParams`].
let mut params = DefineParams::new();
loop {
while self.pos < self.src.len() && self.peek() != b'\n' {
// Stop before a trailing comment on the same line — unless
// a formal-argument list is still open, in which case the
// comment is written *inside* the directive and rides
// along with it, exactly as one on a backslash-continued
// line does (`docs/features/define-table/README.md`).
if self.peek() == b'/'
&& (self.peek_at(1) == b'/' || self.peek_at(1) == b'*')
&& !params.open(self.src, start, self.pos)
{
break;
}
self.bump();
}
// A function-like `` `define`` whose formal-argument list is
// still open at end of line continues onto the next one with
// no backslash: every tool accepts it and real code writes it
// (`cip_base_vseq__tl_errors.svh:8`). The macro *body* is
// unaffected — it still needs the backslashes below.
if self.peek() != b'\n' || !params.open(self.src, start, self.pos) {
break;
}
self.bump();
@@ -664,6 +686,175 @@ impl<'a> RawLexer<'a> {
}
}
/// Incremental tracker for a function-like `` `define``'s formal-argument
/// list: how deep its parens are, and whether it is still open.
///
/// One of these lives for the length of one directive, and
/// [`DefineParams::open`] walks **only the bytes added since the last call**.
/// That is the whole point of the type: the question is asked once per line
/// the list stays open on, so re-deriving the depth from the directive's first
/// byte every time would be quadratic in the number of lines — and an
/// unclosed list never stops asking, so a vendor file with one dropped `)`
/// would stall the lexer for minutes (QA, 2026-09-02: 20 000 unclosed lines
/// took 2.5 s that way, and it grew with the square).
struct DefineParams {
/// Absolute byte offset in the source that the scan has consumed.
scanned: usize,
/// Open parens at `scanned`, counting the `(` that opens the list.
depth: u32,
/// What the scan is in the middle of, carried across lines: a default
/// value may hold a paren inside a string or a comment.
mode: ScanMode,
/// `None` until the header has been read. `Some(false)` is **terminal** —
/// either this is not a function-like `` `define``, or its list has
/// closed — and no byte is ever looked at again.
open: Option<bool>,
/// Bytes [`DefineParams::advance`] has actually looked at. Counted only in
/// test builds, where it is the structural pin that this scan is one pass
/// and not a rescan — the property a wall-clock bound can only imply.
#[cfg(test)]
walked: usize,
}
/// What [`DefineParams::advance`] is in the middle of.
#[derive(Clone, Copy, PartialEq)]
enum ScanMode {
Code,
String,
LineComment,
BlockComment,
}
impl DefineParams {
fn new() -> DefineParams {
DefineParams {
scanned: 0,
depth: 0,
mode: ScanMode::Code,
open: None,
#[cfg(test)]
walked: 0,
}
}
/// True when the directive running from `start` to `end` is a
/// function-like `` `define`` whose formal-argument list is still open.
///
/// `end` must never move backwards between calls, which is what makes the
/// whole scan one pass over the directive.
fn open(&mut self, src: &[u8], start: usize, end: usize) -> bool {
if self.open.is_none() {
// The header is decided once. It is a prefix of the directive, so
// the answer cannot change later: the only case where the text so
// far is too short to see a `(` is one where the directive ends
// right there anyway (a `\n` or a comment straight after the name).
self.open = Some(match define_params_start(&src[start..end]) {
Some(at) => {
self.scanned = start + at;
true
}
None => false,
});
}
if self.open != Some(true) {
return false;
}
self.advance(src, end);
self.open == Some(true)
}
/// Walk the bytes added since the last call, and nothing else.
fn advance(&mut self, src: &[u8], end: usize) {
#[cfg(test)]
let from = self.scanned;
let mut i = self.scanned;
while i < end {
match self.mode {
ScanMode::String => match src[i] {
b'\\' => i += 1,
b'"' => self.mode = ScanMode::Code,
_ => {}
},
ScanMode::LineComment => {
if src[i] == b'\n' {
self.mode = ScanMode::Code;
}
}
ScanMode::BlockComment => {
if src[i] == b'*' && src.get(i + 1) == Some(&b'/') {
self.mode = ScanMode::Code;
i += 1;
}
}
ScanMode::Code => match src[i] {
b'"' => self.mode = ScanMode::String,
b'/' if src.get(i + 1) == Some(&b'/') => {
self.mode = ScanMode::LineComment;
i += 1;
}
b'/' if src.get(i + 1) == Some(&b'*') => {
self.mode = ScanMode::BlockComment;
i += 1;
}
b'(' => self.depth += 1,
b')' => {
self.depth = self.depth.saturating_sub(1);
if self.depth == 0 {
// The list closed: the parens of the macro *body*
// can never reopen it, so this is the last byte
// this tracker ever looks at.
self.open = Some(false);
self.scanned = i + 1;
#[cfg(test)]
{
self.walked += self.scanned - from;
}
return;
}
}
_ => {}
},
}
i += 1;
}
// `i`, not `end`: a two-byte step (`\` in a string, `//`, `*/`) may
// have carried the scan one past `end`, and that byte is consumed.
self.scanned = i;
#[cfg(test)]
{
self.walked += self.scanned - from;
}
}
}
/// The offset of the `(` that opens a function-like `` `define``'s formal
/// argument list, or `None` when `text` does not start one.
///
/// Only a `(` that *touches* the macro name opens a list (IEEE 1800 §22.5.1,
/// the same rule `defines.rs` reads the parameters by): `` `define A (x) `` is
/// object-like and its body merely starts with a paren. Everything else that
/// begins with a backtick — a macro invocation above all — answers `None` and
/// keeps the one-line capture it always had.
fn define_params_start(text: &[u8]) -> Option<usize> {
const KEYWORD: &[u8] = b"`define";
let rest = text.strip_prefix(KEYWORD)?;
if !matches!(rest.first(), Some(b' ' | b'\t')) {
return None;
}
let mut i = 0;
while matches!(rest.get(i), Some(b' ' | b'\t')) {
i += 1;
}
let name_start = i;
while rest.get(i).is_some_and(|&c| is_ident_char(c)) {
i += 1;
}
if i == name_start || rest.get(i) != Some(&b'(') {
return None;
}
Some(KEYWORD.len() + i)
}
fn is_ident_char(c: u8) -> bool {
c == b'_' || c == b'$' || c.is_ascii_alphanumeric()
}
@@ -828,6 +1019,263 @@ mod tests {
assert!(toks[..7].iter().all(|(k, _)| *k == TokenKind::Number));
}
// ------------------------------------------------------------------
// `define formal-argument continuation — TODO.md §22
// ------------------------------------------------------------------
#[test]
fn a_define_formal_list_continues_across_lines_without_a_backslash() {
// opentitan `cip_base_vseq__tl_errors.svh:8` — no backslash on the
// line that opens the list, and every tool accepts it.
let src = "`define A(x,\n y = 3,\n z) body\nwire w;\n";
let toks = tokenize(src).unwrap();
assert_eq!(toks[0].kind, TokenKind::Directive);
assert_eq!(toks[0].text, "`define A(x,\n y = 3,\n z) body");
assert_eq!(&src[toks[0].span.as_range()], toks[0].text);
assert!(toks[1].is_kw("wire"), "the next line is ordinary code again");
}
#[test]
fn a_closed_formal_list_stops_the_directive_at_end_of_line() {
// The body still needs its backslashes: the paren rule is about the
// *formal list* and nothing else.
let toks = tokenize("`define A(x) foo(\nwire w;\n").unwrap();
assert_eq!(toks[0].text, "`define A(x) foo(");
assert!(toks[1].is_kw("wire"));
}
#[test]
fn only_a_paren_touching_the_name_opens_a_formal_list() {
// `define A (x) is object-like (IEEE 1800 §22.5.1): its body merely
// starts with a paren, so end of line ends the directive.
let toks = tokenize("`define A (x,\nwire w;\n").unwrap();
assert_eq!(toks[0].text, "`define A (x,");
assert!(toks[1].is_kw("wire"));
// And a macro *usage* is not a `define at all.
let toks = tokenize("`uvm_info(a,\n b)\n").unwrap();
assert_eq!(toks[0].kind, TokenKind::Ident);
}
#[test]
fn a_string_or_a_comment_inside_a_formal_list_does_not_close_it() {
let toks = tokenize("`define A(s = \")\",\n t) body\nwire w;\n").unwrap();
assert_eq!(toks[0].text, "`define A(s = \")\",\n t) body");
assert!(toks[1].is_kw("wire"));
// A comment written inside the list rides along with the directive,
// exactly as one on a backslash-continued line does.
let toks = tokenize("`define A(x, // why\n y) body\nwire w;\n").unwrap();
assert_eq!(toks[0].text, "`define A(x, // why\n y) body");
assert!(toks[1].is_kw("wire"));
}
#[test]
fn a_formal_list_that_never_closes_stops_at_end_of_file() {
// Degenerate input, pinned so it cannot loop or panic.
let toks = tokenize("`define A(x,\n y\n").unwrap();
assert_eq!(toks[0].text, "`define A(x,\n y");
assert_eq!(toks[1].kind, TokenKind::Eof);
}
#[test]
fn a_nested_paren_inside_a_formal_list_does_not_close_it() {
// opentitan's real shape: a default value whose type is
// parameterized, so the list's own `)` is the *second* one.
let src = "`define A(x,\n t = seq #(item),\n y) body\nwire w;\n";
let toks = tokenize(src).unwrap();
assert_eq!(toks[0].text, "`define A(x,\n t = seq #(item),\n y) body");
assert!(toks[1].is_kw("wire"));
// A block comment spanning the line break is carried too.
let src = "`define A(x, /* one\n two */ y) body\nwire w;\n";
let toks = tokenize(src).unwrap();
assert_eq!(toks[0].text, "`define A(x, /* one\n two */ y) body");
assert!(toks[1].is_kw("wire"));
}
// ------------------------------------------------------------------
// `DefineParams` is incremental — QA finding, 2026-09-02
//
// The tracker is asked once per line the formal list stays open on. It
// must answer from the bytes added since the last question, never by
// re-deriving the depth from the directive's first byte: an *unclosed*
// list never stops asking, so a from-scratch rescan is quadratic in the
// number of lines and one dropped `)` in a vendor file stalls the editor.
// Two pins: the answers still match a from-scratch scan exactly, and the
// work really is one pass.
// ------------------------------------------------------------------
/// The from-scratch scan the incremental tracker replaced, kept as the
/// reference the tracker is held to. Deliberately the naive shape.
fn params_open_rescan(text: &[u8]) -> bool {
let Some(at) = define_params_start(text) else {
return false;
};
let mut depth = 0u32;
let mut mode = ScanMode::Code;
let mut i = at;
while i < text.len() {
match mode {
ScanMode::String => match text[i] {
b'\\' => i += 1,
b'"' => mode = ScanMode::Code,
_ => {}
},
ScanMode::LineComment => {
if text[i] == b'\n' {
mode = ScanMode::Code;
}
}
ScanMode::BlockComment => {
if text[i] == b'*' && text.get(i + 1) == Some(&b'/') {
mode = ScanMode::Code;
i += 1;
}
}
ScanMode::Code => match text[i] {
b'"' => mode = ScanMode::String,
b'/' if text.get(i + 1) == Some(&b'/') => {
mode = ScanMode::LineComment;
i += 1;
}
b'/' if text.get(i + 1) == Some(&b'*') => {
mode = ScanMode::BlockComment;
i += 1;
}
b'(' => depth += 1,
b')' => {
depth = depth.saturating_sub(1);
if depth == 0 {
return false;
}
}
_ => {}
},
}
i += 1;
}
depth > 0
}
/// Every directive shape the scan has to get right, as a whole source.
const PARAM_SHAPES: &[&str] = &[
"`define A(x, y) body",
"`define A(x,\n y) body",
"`define A(x,\n t = seq #(item),\n y) body",
"`define A(s = \")\", t) body",
"`define A(s = \"a\\\"b)\", t) body",
"`define A(x, // why\n y) body",
"`define A(x, /* one\n two */ y) body",
"`define A(x,\n y",
"`define A (x, y) body",
"`define A body(x, y)",
"`define A",
"`uvm_info(a,\n b)",
"`ifdef X",
"`define A() body",
];
/// Where the lexer actually asks the question: at every end of line, and
/// at every `//` or `/*` start, plus once at the end of the text. Driving
/// the tracker anywhere else would be testing a call pattern that does not
/// happen — in particular a question asked before the macro name is
/// complete, which the lexer can never ask.
fn question_points(src: &[u8]) -> Vec<usize> {
let mut out = Vec::new();
for (i, &b) in src.iter().enumerate() {
let comment = b == b'/' && matches!(src.get(i + 1), Some(b'/') | Some(b'*'));
if b == b'\n' || comment {
out.push(i);
}
}
out.push(src.len());
out
}
#[test]
fn the_incremental_tracker_answers_exactly_what_a_rescan_would() {
for shape in PARAM_SHAPES {
let src = shape.as_bytes();
let mut params = DefineParams::new();
for end in question_points(src) {
assert_eq!(
params.open(src, 0, end),
params_open_rescan(&src[..end]),
"{shape:?} at {end}: incremental and rescan disagree"
);
}
}
}
#[test]
fn the_incremental_tracker_visits_each_byte_at_most_once() {
// The structural half of the fix. `walked` is the real loop count, so
// a regression to a from-scratch rescan fails here with a number
// rather than with a stopwatch — and it fails on a 20-byte fixture,
// long before it is slow enough for anyone to notice.
for shape in PARAM_SHAPES {
let src = shape.as_bytes();
let mut params = DefineParams::new();
let mut last = 0usize;
for end in question_points(src) {
params.open(src, 0, end);
assert!(params.scanned >= last, "{shape:?}: the scan moved backwards");
last = params.scanned;
}
assert!(
params.walked <= src.len(),
"{shape:?}: walked {} bytes of a {}-byte directive",
params.walked,
src.len()
);
}
}
#[test]
fn the_work_stays_one_pass_however_many_lines_the_list_spans() {
// The same structural pin at the size that made the bug visible: a
// rescan walks ~n^2/2 bytes here, which is over 17 billion.
let mut src = String::from("`define A(x,\n");
for i in 0..20_000 {
src.push_str(" p");
src.push_str(&i.to_string());
src.push_str(",\n");
}
let bytes = src.as_bytes();
let mut params = DefineParams::new();
for end in question_points(bytes) {
assert!(params.open(bytes, 0, end), "the list never closes, so it is always open");
}
assert!(
params.walked <= bytes.len(),
"walked {} bytes of a {}-byte directive",
params.walked,
bytes.len()
);
}
#[test]
fn a_formal_list_that_never_closes_lexes_in_linear_time() {
// The regression this guards, end to end and through `tokenize`: one
// dropped `)` in a vendored macro. With the from-scratch rescan this
// took 2.5 s in release and far worse in debug; it is now well under a
// millisecond in release, so the bound is generous by three orders of
// magnitude in either build and cannot flake.
let mut src = String::from("`define A(x,\n");
for i in 0..20_000 {
src.push_str(" p");
src.push_str(&i.to_string());
src.push_str(",\n");
}
let started = std::time::Instant::now();
let toks = tokenize(&src).expect("lex");
let took = started.elapsed();
// The whole file really is the one directive, so the scan did not stop
// early and the timing means what it says.
assert_eq!(toks[0].kind, TokenKind::Directive);
assert_eq!(toks[0].text, src.trim_end());
assert_eq!(toks[1].kind, TokenKind::Eof);
assert!(took.as_secs() < 5, "20 000 unclosed formal-argument lines took {took:?}");
}
#[test]
fn trailing_comment_attaches() {
let toks = tokenize("assign x = y; // comment\nwire z;").unwrap();
@@ -1030,6 +1478,29 @@ mod tests {
assert_eq!((err.line, err.col), (1, 15));
}
/// IEEE 1800-2017 §5.6.1: an escaped identifier runs from its `\` to the
/// next whitespace character, which is *not* part of the token. Everything
/// downstream depends on this split — the formatter has to write that
/// terminator back itself, because the token it is handed does not carry
/// it (see `docs/features/escaped-identifiers/README.md`).
#[test]
fn an_escaped_identifier_ends_before_its_terminating_whitespace() {
let toks = kinds("wire \\my-signal ;");
assert_eq!(toks[1], (TokenKind::Ident, "\\my-signal".to_string()));
assert_eq!(toks[2], (TokenKind::Symbol, ";".to_string()));
// Any whitespace ends it, and punctuation ends nothing: `\a;` is one
// identifier that has swallowed the semicolon.
let texts: Vec<String> = kinds("\\a\tb \\c\n\\d ;").into_iter().map(|(_, t)| t).collect();
assert_eq!(texts, ["\\a", "b", "\\c", "\\d", ";", ""]);
assert_eq!(kinds("wire \\a;")[1], (TokenKind::Ident, "\\a;".to_string()));
// A name may end the file: there is nothing left to terminate it.
assert_eq!(kinds("wire \\a")[1], (TokenKind::Ident, "\\a".to_string()));
// The span stops with the text, so `src[span] == text`.
let toks = tokenize("wire \\my-signal ;").unwrap();
let span = toks[1].span;
assert_eq!(&"wire \\my-signal ;"[span.start as usize..span.end as usize], "\\my-signal");
}
#[test]
fn operators() {
let toks = kinds("a <<< b === c !== d <= e");
+1 -1
View File
@@ -14,7 +14,7 @@ pub mod token;
pub use lexer::{tokenize, LexError};
pub use line_index::LineIndex;
pub use parser::{parse, parse_tolerant, ParseDiagnostic, ParseError};
pub use parser::{parse, parse_tolerant, ParseDiagnostic, ParseError, PARSE_STACK_SIZE};
pub use span::TextRange;
pub use token::KEYWORDS;
+62
View File
@@ -46,6 +46,30 @@ impl LineIndex {
(line as u32, offset - self.line_starts[line - 1] + 1)
}
/// The **0-based** line and **UTF-16** column of a byte offset — the units
/// a language-server `Position` counts in, as opposed to
/// [`line_col`](Self::line_col)'s 1-based bytes. `text` must be the text
/// this index was built from.
///
/// An offset inside a multi-byte character is floored to that character's
/// start, and the `\r` of a CRLF line ending is not part of its line's
/// content. It lives here, beside the table it reads, because two callers
/// need the same answer: a server converting a span for the wire, and the
/// semantic index recording a declaration's position so no one has to.
pub fn utf16_position(&self, text: &str, offset: u32) -> (u32, u32) {
let mut floored = (offset as usize).min(text.len());
while floored > 0 && !text.is_char_boundary(floored) {
floored -= 1;
}
let (line, _) = self.line_col(floored as u32);
let start = self.line_range(line).map_or(0, |r| r.start) as usize;
let slice = text.get(start..floored).unwrap_or("");
// LSP line content excludes the whole `\r\n`; this index keeps the
// `\r` as an ordinary byte of its line, so drop it here.
let slice = slice.strip_suffix('\r').unwrap_or(slice);
(line - 1, utf16_len(slice))
}
/// The byte offset of a 1-based line and column, or `None` if the text
/// has no such line. A column past the end of its line is clamped to the
/// line's end, so the result never lands on another line.
@@ -77,6 +101,17 @@ impl LineIndex {
}
}
/// How many UTF-16 code units a string occupies — the unit LSP counts in.
///
/// ASCII is answered by the length, which is what source text almost always
/// is; the decoding loop is for the rest.
fn utf16_len(s: &str) -> u32 {
if s.is_ascii() {
return s.len() as u32;
}
s.chars().map(|c| c.len_utf16() as u32).sum()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -141,6 +176,33 @@ mod tests {
}
}
#[test]
fn utf16_positions_are_zero_based_and_count_code_units() {
let src = "module m;\n// 🎉 é\nendmodule";
let idx = LineIndex::new(src);
assert_eq!(idx.utf16_position(src, 0), (0, 0));
assert_eq!(idx.utf16_position(src, 7), (0, 7));
assert_eq!(idx.utf16_position(src, 10), (1, 0));
let party = src.find('🎉').unwrap() as u32;
assert_eq!(idx.utf16_position(src, party), (1, 3));
// Four UTF-8 bytes, two UTF-16 units — the surrogate pair.
assert_eq!(idx.utf16_position(src, party + 4), (1, 5));
// An offset inside the pair floors to its start.
for inside in 1..4 {
assert_eq!(idx.utf16_position(src, party + inside), (1, 3));
}
assert_eq!(idx.utf16_position(src, src.len() as u32 + 99), (2, 9));
}
#[test]
fn a_crlf_is_not_part_of_its_lines_utf16_content() {
let src = "ab\r\ncd\r\n";
let idx = LineIndex::new(src);
assert_eq!(idx.utf16_position(src, 2), (0, 2), "at the `\\r`");
assert_eq!(idx.utf16_position(src, 3), (0, 2), "at the `\\n`, past the `\\r`");
assert_eq!(idx.utf16_position(src, 4), (1, 0));
}
#[test]
fn out_of_range_positions_are_clamped() {
let src = "abc\nde";
File diff suppressed because it is too large. Load diff
+15
View File
@@ -293,6 +293,21 @@ keywords![
"endspecify",
"table",
"endtable",
// Vendor and formal collateral (`vendor-formal-grammar`, 2026-09-02).
// All five are reserved words in IEEE 1800 Table B.1, so a file that
// spells one as an identifier is already illegal SystemVerilog — and a
// census of 4 839 corpus + opentitan files found **zero** code-shaped
// uses of any of them. The rest of the vendor/config vocabulary
// (`expect`, `tagged`, `design`, `instance`, `cell`, `liblist`, `use`,
// `showcancelled`, `ifnone`) is deliberately *not* here: real code does
// spell those as identifiers — `expect(word1[7:0]);` is a task call in 41
// corpus sites — so they are matched by text where they are needed at
// all. See `docs/features/vendor-formal-grammar/README.md`.
"checker",
"endchecker",
"config",
"endconfig",
"library",
"small",
"medium",
"large",
+201
View File
@@ -0,0 +1,201 @@
//! A read-only sweep probe: set CENSUS to a directory and this prints the
//! covergroup and SVA structured/fallback counts and the tolerant diagnostics
//! over every `.sv`/`.svh` under it. Ignored; run by hand for the feature
//! README.
use std::path::{Path, PathBuf};
fn collect(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
for e in entries.flatten() {
let p = e.path();
if p.is_dir() {
collect(&p, out);
} else if matches!(p.extension().and_then(|s| s.to_str()), Some("sv") | Some("svh")) {
out.push(p);
}
}
}
/// The 1-based line ranges of every SVA construct in one file, printed as
/// `SVA_LINES <path> <start>-<end> …`.
///
/// What the sweep's "the output moved only inside assertion text" claim is
/// checked against: a diff hunk that falls outside every one of these ranges
/// is a construct this round had no business touching. Set `SVA_LINES` to a
/// file list (one path per line) rather than `CENSUS` to a directory.
#[test]
#[ignore]
fn sva_lines() {
std::thread::Builder::new()
.stack_size(vlog_parser::PARSE_STACK_SIZE)
.spawn(run_sva_lines)
.expect("spawn")
.join()
.expect("join");
}
fn run_sva_lines() {
let list = std::env::var("SVA_LINES").expect("SVA_LINES");
let paths = std::fs::read_to_string(&list).expect("the file list");
for path in paths.lines().filter(|l| !l.trim().is_empty()) {
let Ok(src) = std::fs::read_to_string(path) else { continue };
let (file, _) = vlog_parser::parse_source_tolerant(&src);
let index = vlog_parser::LineIndex::new(&src);
let mut spans: Vec<(u32, u32)> = Vec::new();
collect_sva(&file.items, &mut spans);
let ranges: Vec<String> = spans
.iter()
.map(|(a, b)| {
format!("{}-{}", index.line_col(*a).0, index.line_col(b.saturating_sub(1)).0)
})
.collect();
println!("SVA_LINES {path} {}", ranges.join(" "));
}
}
/// Every assertion-ish item's span, at any item depth. Statement-position
/// assertions are inside a construct whose own span already covers them.
fn collect_sva(items: &[vlog_parser::ast::Item], out: &mut Vec<(u32, u32)>) {
use vlog_parser::ast::ItemKind;
for item in items {
match &item.kind {
ItemKind::Assertion(_)
| ItemKind::PropSeqDecl(_)
| ItemKind::DefaultDisable(_)
| ItemKind::Verbatim(_) => out.push((item.span.start, item.span.end)),
ItemKind::Module(m) => collect_sva(&m.items, out),
ItemKind::Package { items, .. } => collect_sva(items, out),
ItemKind::Class(c) => collect_sva(&c.items, out),
ItemKind::GenerateRegion { items, .. } => collect_sva(items, out),
ItemKind::GenIf(g) => {
collect_sva(&g.then.items, out);
match g.els.as_deref() {
Some(vlog_parser::ast::GenElse::Block(b)) => collect_sva(&b.items, out),
Some(vlog_parser::ast::GenElse::If(_, inner)) => {
collect_sva(&inner.then.items, out)
}
None => {}
}
}
ItemKind::GenFor(g) => collect_sva(&g.body.items, out),
ItemKind::GenCase(g) => {
for it in &g.items {
collect_sva(&it.body.items, out);
}
}
// A procedural block may hold an assertion *statement*. Pushing
// the whole block would make the check vacuous for a 250-line
// `always`, so the statements are walked and only the assertion
// ones are pushed.
ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => {
collect_sva_stmt(stmt, out)
}
ItemKind::Function(f) => {
for st in &f.stmts {
collect_sva_stmt(st, out);
}
}
ItemKind::Task(t) => {
for st in &t.stmts {
collect_sva_stmt(st, out);
}
}
_ => {}
}
}
}
/// The assertion statements inside one statement, at any nesting depth.
fn collect_sva_stmt(stmt: &vlog_parser::ast::Stmt, out: &mut Vec<(u32, u32)>) {
use vlog_parser::ast::StmtKind;
if matches!(stmt.kind, StmtKind::Assertion(_) | StmtKind::Verbatim(_)) {
out.push((stmt.span.start, stmt.span.end));
return;
}
vlog_linter_visit(stmt, out);
}
/// A hand-rolled statement walk — `vlog_linter::visit` is another crate's.
fn vlog_linter_visit(stmt: &vlog_parser::ast::Stmt, out: &mut Vec<(u32, u32)>) {
use vlog_parser::ast::StmtKind;
match &stmt.kind {
StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => {
for st in stmts {
collect_sva_stmt(st, out);
}
}
StmtKind::If { then, els, .. } => {
collect_sva_stmt(then, out);
if let Some(e) = els {
collect_sva_stmt(e, out);
}
}
StmtKind::Case { items, .. } => {
for it in items {
collect_sva_stmt(&it.stmt, out);
}
}
StmtKind::For { body, .. } => collect_sva_stmt(body, out),
StmtKind::Timing { stmt: Some(inner), .. } => collect_sva_stmt(inner, out),
StmtKind::Labeled { stmt: inner, .. } => collect_sva_stmt(inner, out),
_ => {}
}
}
#[test]
#[ignore]
fn census() {
std::thread::Builder::new()
.stack_size(vlog_parser::PARSE_STACK_SIZE)
.spawn(run)
.expect("spawn")
.join()
.expect("join");
}
// `CENSUS` is read relative to the crate directory — cargo runs a test
// binary with the crate as its working directory — so a relative path
// typed at the workspace root (`CENSUS=corpus`) finds nothing and reports
// `files=0`. Pass an absolute path.
fn run() {
let root = std::env::var("CENSUS").expect("CENSUS");
let mut files = Vec::new();
collect(Path::new(&root), &mut files);
files.sort();
let (mut cg, mut fb, mut cf, mut diags, mut with_diags) = (0u64, 0u64, 0u64, 0u64, 0u64);
let (mut pd, mut pdf, mut asrt, mut asrtf) = (0u64, 0u64, 0u64, 0u64);
for p in &files {
let Ok(src) = std::fs::read_to_string(p) else { continue };
let (file, ds) = vlog_parser::parse_source_tolerant(&src);
cg += u64::from(file.covergroups);
fb += u64::from(file.covergroup_fallbacks);
cf += u64::from(file.constraint_fallbacks);
pd += u64::from(file.prop_seq_decls);
pdf += u64::from(file.prop_seq_fallbacks);
asrt += u64::from(file.assertions);
asrtf += u64::from(file.assertion_fallbacks);
if file.prop_seq_fallbacks > 0 || file.assertion_fallbacks > 0 {
println!(
"SVA_FALLBACK {} decls={} assertions={}",
p.display(),
file.prop_seq_fallbacks,
file.assertion_fallbacks
);
}
if file.covergroup_fallbacks > 0 {
println!("FALLBACK {} {}", p.display(), file.covergroup_fallbacks);
}
if !ds.is_empty() {
with_diags += 1;
println!("DIAGS {} {}", p.display(), ds.len());
}
diags += ds.len() as u64;
}
println!(
"files={} covergroups={cg} covergroup_fallbacks={fb} constraint_fallbacks={cf} diagnostics={diags} files_with_diagnostics={with_diags}",
files.len()
);
println!(
"prop_seq_decls={pd} prop_seq_fallbacks={pdf} assertions={asrt} assertion_fallbacks={asrtf}"
);
}
Loaded 100 of 239 files, more files were not shown because too many files have changed in this diff. Show more