Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dd4aa498bb | ||
|
|
7d637323a5 | ||
|
|
df85fd3b54 | ||
|
|
bbf87976a1 | ||
|
|
2a2334ef5a | ||
|
|
95f930cf20 | ||
|
|
311551f232 | ||
|
|
ff67281995 | ||
|
|
7ca2508ec7 | ||
|
|
91b7c2fd67 | ||
|
|
ce2f858e5e | ||
|
|
14fbdab717 | ||
|
|
f8401a0024 | ||
|
|
307a56e921 | ||
|
|
1e30ea0fb5 | ||
|
|
3f912e7fce | ||
|
|
f3b5a9d189 | ||
|
|
02b4204536 | ||
|
|
03a4958294 | ||
|
|
f27fa1c045 | ||
|
|
cadb4319e4 | ||
|
|
1cfbab4a56 | ||
|
|
a1fa402fd8 | ||
|
|
bc533c6cb1 | ||
|
|
5ad0772475 | ||
|
|
af3280c651 | ||
|
|
24b0dd9912 | ||
|
|
852d05d9ad | ||
|
|
98675c630a | ||
|
|
7f65a2449a | ||
|
|
3f300fa9e9 | ||
|
|
7881cc869c | ||
|
|
89186a8eaa | ||
|
|
27a652ee3d | ||
|
|
d3deacf0f6 | ||
|
|
17633d2214 | ||
|
|
e2c954ba77 | ||
|
|
e565dc0812 | ||
|
|
34b766cbef | ||
|
|
8cdc1b3375 | ||
|
|
651e58bfb3 | ||
|
|
37560cad5e | ||
|
|
e4407984cb | ||
|
|
40094c4c4e | ||
|
|
829302d0bf | ||
|
|
ee1efe3fb1 | ||
|
|
1029d2f199 | ||
|
|
36caf1dd19 | ||
|
|
61f345aca7 | ||
|
|
ad27ed23dc | ||
|
|
bf9170a850 | ||
|
|
b7a934080a | ||
|
|
172a034c67 | ||
|
|
20567e1a7f | ||
|
|
17214ac8db | ||
|
|
d4eb8f48ff | ||
|
|
cf32e92e58 | ||
|
|
097498da23 | ||
|
|
4f7b4a9f91 | ||
|
|
574ab833e3 | ||
|
|
12d0bbad51 | ||
|
|
de8a7e129c | ||
|
|
611dd23069 | ||
|
|
a4f23db2c7 | ||
|
|
d94f9e3de0 | ||
|
|
94b130aca1 | ||
|
|
efe67bde65 | ||
|
|
e70d979e51 | ||
|
|
b2d778eb8d | ||
|
|
27fc216df3 | ||
|
|
4665641e42 | ||
|
|
bc606dd6bd | ||
|
|
5e98b1a669 | ||
|
|
2e258df9a7 | ||
|
|
e4b1f55c12 | ||
|
|
5e4aa7bd6f | ||
|
|
7266b13702 | ||
|
|
8c8cfc538e | ||
|
|
8d070a4277 | ||
|
|
64d6e9a55d | ||
|
|
cebb333bd7 | ||
|
|
0a93143bfb | ||
|
|
ec65e0831f | ||
|
|
a399f81ad9 | ||
|
|
20ad318d4e |
No files matched your search
@@ -1,9 +1,15 @@
|
||||
# Release: pushing a tag `vX.Y.Z` builds every distribution artifact and
|
||||
# publishes a Gitea release with the CHANGELOG section for that version as
|
||||
# its notes. The artifact set is exactly what tools/release.sh --cross
|
||||
# produces: host (Apple Silicon) + x86_64 macOS + static-musl Linux +
|
||||
# RHEL 8-compatible linux-gnu + Windows binaries for both lucisv and
|
||||
# lucisv-server, the platform-independent .vsix, and SHA256SUMS.
|
||||
# its notes. What the release page carries is the seven .vsix packages —
|
||||
# the universal one, the five (darwin-arm64/darwin-x64/linux-x64/
|
||||
# linux-arm64/win32-x64) with the lucisv + lucisv-server binaries embedded,
|
||||
# and the all-platforms one carrying every pair at once — plus SHA256SUMS.
|
||||
# Every package is a must: a missing one fails the release, by name
|
||||
# (tools/prune_release_assets.sh). The loose binaries are still built for
|
||||
# every target
|
||||
# (the packages are made from them) and still audited, but they are not
|
||||
# attached: anyone who wants a standalone binary builds it with
|
||||
# `cargo build --release` (docs/features/editor-platform-vsix).
|
||||
#
|
||||
# The release fails, deliberately, when the tag does not match the
|
||||
# workspace version or CHANGELOG.md has no section for it: every release
|
||||
@@ -30,6 +36,11 @@ jobs:
|
||||
echo "tag $GITHUB_REF_NAME does not match crate version $v" >&2
|
||||
exit 1
|
||||
}
|
||||
# The release page ships extension packages only: all seven checked by
|
||||
# name, SHA256SUMS filtered down to them and re-verified, the loose
|
||||
# binaries (needed to build and audit the packages) dropped.
|
||||
- name: Keep only the extension packages
|
||||
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
|
||||
- name: Create the release and attach the artifacts
|
||||
|
||||
@@ -5,3 +5,5 @@
|
||||
/.lucisv_cache
|
||||
/.score-results.tsv
|
||||
.DS_Store
|
||||
/.zcode
|
||||
/.claude
|
||||
+733
@@ -4,6 +4,739 @@ 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.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
|
||||
**every platform's binaries in one file**, and a Marketplace-grade
|
||||
extension page.
|
||||
|
||||
### The all-platforms package
|
||||
|
||||
`lucisv-<version>-all.vsix` embeds all five platforms' `lucisv` and
|
||||
`lucisv-server` pairs under `bin/<platform>-<arch>/`, and the extension
|
||||
picks the right pair at runtime from `process.platform` and
|
||||
`process.arch`. It is deliberately target-less, which makes it the
|
||||
package for machines the targeted five cannot name: Alpine (VS Code
|
||||
there asks for an `alpine-*` target, but reports plain `linux` at
|
||||
runtime, so the static musl binaries just work), mixed fleets, or one
|
||||
file mirrored internally. The cost is download size — about 13 MB
|
||||
against 3 MB for a single-platform package — and nothing else. The
|
||||
resolution order is unchanged: an explicit `lucisv.serverPath` first,
|
||||
then the bundled binary (flat `bin/` before the platform subdirectory),
|
||||
then `PATH`. Details: `docs/features/editor-platform-vsix/README.md`.
|
||||
|
||||
### One consolidated release flow
|
||||
|
||||
The release workflow's publish-only-the-packages logic now lives in
|
||||
`tools/prune_release_assets.sh`, and it requires **all seven** packages
|
||||
by name — five platform, `all`, and the universal no-binary fallback —
|
||||
before anything is published; a missing one fails the release. Every
|
||||
tagged release follows this same flow with no manual steps beyond the
|
||||
version bump, the changelog section, and the tag.
|
||||
|
||||
### A Marketplace-grade extension page
|
||||
|
||||
`editors/vscode/README.md` is rewritten for end users — install matrix,
|
||||
capability tables, snippet library, settings ladder, troubleshooting —
|
||||
with an icon and diagrams, and the manifest gains the Marketplace
|
||||
metadata (icon, banner, keywords, categories). Troubleshooting now also
|
||||
names the duplicate-hover trap: the pre-rename **vfmt** extension left
|
||||
installed next to lucisv attaches a second language server, and every
|
||||
hover and diagnostic shows twice. Uninstall `vfmt` and reload.
|
||||
|
||||
## 0.10.1 — 2026-08-27
|
||||
|
||||
The install-in-one-step release: the VS Code extension now ships as
|
||||
**platform-specific packages with the binaries inside**, and the release
|
||||
page carries exactly those packages — nothing to build, nothing to put on
|
||||
`PATH`.
|
||||
|
||||
### Platform packages for the VS Code extension
|
||||
|
||||
Five new `.vsix` packages — `darwin-arm64`, `darwin-x64`, `linux-x64`,
|
||||
`linux-arm64`, `win32-x64` — each embedding that platform's `lucisv` and
|
||||
`lucisv-server` under `bin/` inside the extension. Install the one
|
||||
matching your machine with `code --install-extension` and the extension
|
||||
spawns its own server; both Linux packages are statically linked (musl),
|
||||
so they run on any distro, and `linux-arm64` is a **new build target**
|
||||
altogether. The extension resolves the server as: an explicitly set
|
||||
`lucisv.serverPath` first, then the bundled binary (made executable on
|
||||
activation — VSIX extraction drops the bit), then `PATH` — so pointing at
|
||||
your own `target/release` build still works, and clearing the setting
|
||||
falls back to the bundled server. The universal `lucisv-<version>.vsix`
|
||||
(no binaries, server from `PATH`) remains the fallback for platforms
|
||||
without a package. Details and the verification story:
|
||||
`docs/features/editor-platform-vsix/README.md`.
|
||||
|
||||
### The release page ships packages only
|
||||
|
||||
A tagged release now publishes the six `.vsix` files and `SHA256SUMS`,
|
||||
nothing else. Every platform package is checked by name before publishing
|
||||
— a missing one fails the release — and the per-platform binaries are
|
||||
still built and audited (static-linkage, glibc ceiling, file types) since
|
||||
the packages embed them, but no longer attached as loose assets: a
|
||||
standalone binary is a `cargo build --release` away. The host package's
|
||||
embedded server is smoke-tested through a full LSP session, straight out
|
||||
of the zip, on every release.
|
||||
|
||||
## 0.10.0 — 2026-08-27
|
||||
|
||||
The audit-complete release: TODO.md §9c, the last section of the LSP
|
||||
|
||||
@@ -86,3 +86,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
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.10.0"
|
||||
version = "0.26.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.10.0"
|
||||
version = "0.26.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.10.0"
|
||||
version = "0.26.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.10.0"
|
||||
version = "0.26.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.10.0"
|
||||
version = "0.26.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -264,11 +264,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.10.0"
|
||||
version = "0.26.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.10.0"
|
||||
version = "0.26.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
@@ -276,7 +276,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.10.0"
|
||||
version = "0.26.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.10.0"
|
||||
version = "0.26.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -610,30 +610,43 @@ go-to-definition, references and document/workspace symbols — the full list,
|
||||
and what is deliberately *not* advertised yet, is in
|
||||
`docs/features/lucisv-server/README.md`.
|
||||
|
||||
**The binary comes from the same build as the CLI.** Download it from the
|
||||
[releases page](https://git.luci.ooo/lucio/lucisv/releases) for your
|
||||
platform, or build it yourself:
|
||||
**VS Code needs no separate binary**: every release on the
|
||||
[releases page](https://git.luci.ooo/lucio/lucisv/releases) carries a
|
||||
platform-specific `.vsix` with both binaries inside it — pick yours
|
||||
(`darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`, `win32-x64`)
|
||||
and sideload it:
|
||||
|
||||
```bash
|
||||
code --install-extension lucisv-<version>-darwin-arm64.vsix
|
||||
```
|
||||
|
||||
— or take `lucisv-<version>-all.vsix`, which carries all five platforms' binaries
|
||||
in one file and picks the right pair at startup, when the machine is not known
|
||||
in advance (or is Alpine, which VS Code never offers a Linux package to).
|
||||
|
||||
Every other editor (and the universal `lucisv-<version>.vsix`, the fallback
|
||||
for platforms not listed) finds `lucisv-server` on `PATH`; the binary comes
|
||||
from the same build as the CLI:
|
||||
|
||||
```bash
|
||||
cargo build --release # target/release/lucisv-server (and target/release/lucisv)
|
||||
cp target/release/lucisv-server ~/.local/bin/ # anywhere on PATH
|
||||
```
|
||||
|
||||
Every editor below defaults to finding `lucisv-server` on `PATH`; each also
|
||||
accepts an absolute path if you would rather leave the binary in `target/`.
|
||||
Each editor also accepts an absolute path if you would rather leave the
|
||||
binary in `target/`.
|
||||
|
||||
**VS Code** — a thin extension in `editors/vscode/` whose entire job is
|
||||
registering the file types and starting the server:
|
||||
registering the file types and starting the server (bundled, from `PATH`, or
|
||||
from the `lucisv.serverPath` setting). To build the packages yourself:
|
||||
|
||||
```bash
|
||||
tools/release.sh # builds dist/lucisv-<version>.vsix
|
||||
code --install-extension dist/lucisv-<version>.vsix
|
||||
tools/release.sh # dist/lucisv-<version>.vsix + the host platform package
|
||||
code --install-extension dist/lucisv-<version>-darwin-arm64.vsix
|
||||
```
|
||||
|
||||
The `.vsix` is also attached to every release on the
|
||||
[releases page](https://git.luci.ooo/lucio/lucisv/releases). Sideloading it
|
||||
is the supported install; the extension is not on any marketplace. To package it by hand instead: `cd editors/vscode && npm ci &&
|
||||
npx @vscode/vsce package`.
|
||||
Sideloading is the supported install; the extension is not on any
|
||||
marketplace.
|
||||
|
||||
Settings are listed in `editors/vscode/README.md`, along with the full steps,
|
||||
the F5 development flow and troubleshooting.
|
||||
@@ -665,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
|
||||
@@ -694,20 +711,26 @@ expected outputs with `UPDATE_SNAPSHOTS=1 cargo test -p vlog_formatter`.
|
||||
|
||||
Prebuilt downloads live on the
|
||||
[releases page](https://git.luci.ooo/lucio/lucisv/releases): every tagged
|
||||
version carries `lucisv` and `lucisv-server` for Apple Silicon and Intel
|
||||
macOS, static-musl and RHEL 8-compatible glibc Linux, and Windows, plus the
|
||||
`.vsix` and a `SHA256SUMS` to verify them with
|
||||
(`shasum -a 256 -c SHA256SUMS`). Copy the two binaries onto your `PATH` and
|
||||
sideload the extension with `code --install-extension`. The macOS binaries
|
||||
are smoke-tested on the build machine; the Linux and Windows ones are
|
||||
cross-built and audited (file type, dynamic-linkage, glibc-version ceiling),
|
||||
not executed — there is no Linux or Windows machine in the loop.
|
||||
version carries **seven `.vsix` packages** — platform-specific ones for
|
||||
Apple Silicon and Intel macOS, x86-64 and ARM64 Linux (static musl) and
|
||||
Windows, each with `lucisv` and `lucisv-server` embedded, an
|
||||
all-platforms one carrying every pair at once for unknown or mixed
|
||||
machines, plus the universal no-binary fallback — and a `SHA256SUMS` to
|
||||
verify them with
|
||||
(`shasum -a 256 -c SHA256SUMS`). Sideload the one for your machine with
|
||||
`code --install-extension`. Standalone binaries are not published; build
|
||||
them with `cargo build --release` (or `tools/release.sh --cross` for the
|
||||
full set — the release binaries are cut from the same scripts). The macOS
|
||||
binaries inside the packages are smoke-tested on the build machine; the
|
||||
Linux and Windows ones are cross-built and audited (file type,
|
||||
dynamic-linkage, glibc-version ceiling), not executed — there is no Linux
|
||||
or Windows machine in the loop.
|
||||
|
||||
To build the same artifact set yourself:
|
||||
|
||||
```bash
|
||||
tools/release.sh # host binaries + the .vsix + SHA256SUMS, into dist/
|
||||
tools/release.sh --cross # ...plus the four cross-built platforms
|
||||
tools/release.sh --cross # ...plus the four cross-built platforms and the all package
|
||||
```
|
||||
|
||||
The script itself publishes nothing anywhere; publishing is CI's job —
|
||||
|
||||
+37
-11
@@ -32,12 +32,7 @@ use lucisv_core::config::Discovery;
|
||||
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,10 +45,40 @@ 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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,11 +297,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}"))
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+2596
-215
File diff suppressed because it is too large.
Load diff
@@ -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:#?}"))
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,15 @@ pub const SOURCE: &str = "lucisv";
|
||||
/// error rather than add an opinion, and they exist at all only when the parse
|
||||
/// already failed (`pairs::missing_end_diagnostics`).
|
||||
pub fn all(doc: &Document) -> 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));
|
||||
|
||||
@@ -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 {
|
||||
@@ -1391,11 +1570,17 @@ mod tests {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
let target_dir = root.join("ibex/vendor/lowrisc_ip/ip/prim/rtl");
|
||||
let old = target_dir.join("prim_assert.sv");
|
||||
assert!(old.is_file(), "the corpus is checked in: {old:?}");
|
||||
// Skipped when `corpus/` is not checked out, like every other
|
||||
// corpus test in this crate — asserting its presence panicked any
|
||||
// environment (a bare CI checkout, `act`) that never fetched it.
|
||||
if !old.is_file() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
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 = || {
|
||||
|
||||
@@ -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)
|
||||
|
||||
+1178
-26
File diff suppressed because it is too large.
Load diff
@@ -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
@@ -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());
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
}]
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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,10 @@ mod format;
|
||||
mod hierarchy;
|
||||
mod hover;
|
||||
mod includes;
|
||||
mod index_cache;
|
||||
mod inlay;
|
||||
mod inline;
|
||||
mod instantiations;
|
||||
mod large;
|
||||
mod lens;
|
||||
mod linked;
|
||||
mod lint;
|
||||
@@ -28,6 +30,8 @@ mod locate;
|
||||
mod nav;
|
||||
mod on_type;
|
||||
mod pairs;
|
||||
#[cfg(test)]
|
||||
mod perf;
|
||||
mod ports;
|
||||
mod rename;
|
||||
mod selection;
|
||||
@@ -61,10 +65,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 +105,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(¶ms);
|
||||
// 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(¶ms);
|
||||
let hierarchy_view = hierarchy_view_support(¶ms);
|
||||
// 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 +123,50 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
code_lens_refresh: code_lens_refresh_support(¶ms),
|
||||
show_document: show_document_support(¶ms),
|
||||
configuration: configuration_support(¶ms),
|
||||
token_server_cancel: token_server_cancel_support(¶ms),
|
||||
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 +278,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,
|
||||
@@ -374,6 +458,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 +511,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 +622,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 +866,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 +1076,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]
|
||||
|
||||
+918
-36
File diff suppressed because it is too large.
Load diff
@@ -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;
|
||||
}
|
||||
@@ -264,9 +270,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 +655,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() }
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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,11 +113,13 @@ 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)?
|
||||
}
|
||||
other => return Err(format!("`{other}` is not a lucisv command.")),
|
||||
@@ -121,6 +127,22 @@ pub fn execute(
|
||||
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 +266,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 +345,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 +379,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");
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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> {
|
||||
|
||||
+3381
-182
File diff suppressed because it is too large.
Load diff
@@ -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,73 @@ 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,
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the `lucisv` section out of a `workspace/didChangeConfiguration` payload.
|
||||
@@ -78,16 +205,68 @@ 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");
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 +330,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 +372,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(§ion);
|
||||
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 +564,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 +628,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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
+4436
-88
File diff suppressed because it is too large.
Load diff
@@ -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",
|
||||
@@ -34,11 +38,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,
|
||||
@@ -145,6 +154,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 +213,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();
|
||||
|
||||
@@ -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,11 +235,19 @@ 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::Port
|
||||
@@ -221,6 +255,7 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
|
||||
| SymbolKind::Var
|
||||
| SymbolKind::Genvar
|
||||
| SymbolKind::Instance
|
||||
| SymbolKind::Clocking
|
||||
| SymbolKind::Block => Highlight::Variable,
|
||||
}
|
||||
}
|
||||
@@ -233,11 +268,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 +477,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 +674,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`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
@@ -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),
|
||||
@@ -364,6 +393,27 @@ mod tests {
|
||||
// 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 +679,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 +1330,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);
|
||||
|
||||
@@ -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,16 +125,6 @@ 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 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.
|
||||
fn bases_of(
|
||||
ws: &Workspace,
|
||||
@@ -200,20 +183,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 +241,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 +319,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());
|
||||
@@ -718,7 +686,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 +695,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 +710,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 +1067,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 +1126,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 +1135,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 {
|
||||
|
||||
@@ -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.
|
||||
///
|
||||
|
||||
+2744
-35
File diff suppressed because it is too large.
Load diff
+397
-108
@@ -77,6 +77,11 @@ impl From<VerificationError> for FormatError {
|
||||
/// The output is only returned if it re-lexes to the same token stream as the
|
||||
/// input (comments included) and formatting it again is a fixed point;
|
||||
/// otherwise the caller gets an error and must leave the original text alone.
|
||||
///
|
||||
/// Parses `source` (twice, for verification), so call this only on a thread
|
||||
/// with at least `vlog_parser::PARSE_STACK_SIZE` of stack — a smaller one
|
||||
/// lets sufficiently nested input abort the process instead of returning
|
||||
/// `Err` (see `docs/features/recursion-limit/README.md`).
|
||||
pub fn format_source(source: &str, config: &Config) -> Result<String, FormatError> {
|
||||
let output = format_once(source, config).map_err(FormatError::Source)?;
|
||||
verify_equivalence(source, &output)?;
|
||||
@@ -93,6 +98,9 @@ pub fn format_source(source: &str, config: &Config) -> Result<String, FormatErro
|
||||
/// formatter output, and both checks are global. Convergence is checked by
|
||||
/// replaying the same per-item decisions against the output — see
|
||||
/// `docs/features/range-formatting/README.md`.
|
||||
///
|
||||
/// Same stack requirement as [`format_source`]: needs a thread with at least
|
||||
/// `vlog_parser::PARSE_STACK_SIZE` of stack.
|
||||
pub fn format_range(
|
||||
source: &str,
|
||||
config: &Config,
|
||||
@@ -313,7 +321,7 @@ impl<'a> Fmt<'a> {
|
||||
/// Matches the `endmodule : m` spelling used for module footers.
|
||||
fn closing(kw: &str, label: &Option<String>) -> Doc {
|
||||
match label {
|
||||
Some(l) => text(format!("{kw} : {l}")),
|
||||
Some(l) => text(format!("{kw} : {}", named(l))),
|
||||
None => text(kw),
|
||||
}
|
||||
}
|
||||
@@ -405,9 +413,16 @@ impl<'a> Fmt<'a> {
|
||||
/// printing every comment and then every attribute moves a comment across
|
||||
/// an attribute in the token stream, which the safety net rejects.
|
||||
fn leading(&self, meta: &Meta) -> Vec<Doc> {
|
||||
self.leading_from(meta, 0)
|
||||
}
|
||||
|
||||
/// The same, minus the first `skip` leading comments — the ones a
|
||||
/// statement header already printed inside its own parentheses. See
|
||||
/// [`Fmt::header_parens`].
|
||||
fn leading_from(&self, meta: &Meta, skip: usize) -> Vec<Doc> {
|
||||
let mut docs = Vec::new();
|
||||
let mut attrs = meta.attrs.iter().peekable();
|
||||
for c in &meta.leading {
|
||||
for c in meta.leading.iter().skip(skip) {
|
||||
while let Some(attr) = attrs.next_if(|a| a.span.start < c.span.start) {
|
||||
Self::push_leading(&mut docs, self.raw_text(attr), false);
|
||||
}
|
||||
@@ -824,25 +839,118 @@ impl<'a> Fmt<'a> {
|
||||
group(vec![text("("), indent(vec![Doc::SoftLine, self.expr(e)]), Doc::SoftLine, text(")")])
|
||||
}
|
||||
|
||||
/// `( expr )` with the comments the source wrote just inside the
|
||||
/// parentheses. A comment there forces them open, the same way a comment
|
||||
/// inside a port list does.
|
||||
fn paren_comments(&self, inner: &Expr, before: &[&Comment], after: &[&Comment]) -> Doc {
|
||||
let mut docs = vec![Doc::SoftLine];
|
||||
for c in before {
|
||||
docs.push(self.comment(c));
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(self.expr(inner));
|
||||
let mut outer = vec![text("("), indent(docs)];
|
||||
for c in after {
|
||||
outer.push(text(" "));
|
||||
outer.push(self.comment(c));
|
||||
}
|
||||
let ends_line = after.iter().any(|c| is_line_comment(&c.text));
|
||||
outer.push(if ends_line { Doc::HardLine } else { Doc::SoftLine });
|
||||
outer.push(text(")"));
|
||||
group(outer)
|
||||
}
|
||||
|
||||
/// The `(cond)` of a statement header, taking back the comments the parser
|
||||
/// handed to the construct's *body* because they were written before the
|
||||
/// closing `)`.
|
||||
///
|
||||
/// Nothing between `(` and `)` owns trivia, so a comment written inside a
|
||||
/// header's parentheses stays queued and lands on the next node that takes
|
||||
/// meta — the body statement, or a `case`'s first item. Printed there it
|
||||
/// would sit *after* a `)` it was written before, and `verify.rs` refuses
|
||||
/// the file, rightly: the comment moved across a token.
|
||||
///
|
||||
/// Returns the header doc and how many of `body`'s leading comments it
|
||||
/// consumed, which the caller must then skip. When the source does not
|
||||
/// have the expected shape nothing is taken and the plain parentheses are
|
||||
/// printed, so an unrecognized header is left exactly as it was.
|
||||
fn header_parens(&self, cond: &Expr, body: &Meta) -> (Doc, usize) {
|
||||
let close = match skip_trivia(self.src, cond.span.end as usize) {
|
||||
Some(i) if self.src.as_bytes().get(i) == Some(&b')') => i as u32,
|
||||
_ => return (self.parens(cond), 0),
|
||||
};
|
||||
let taken = body.leading.iter().take_while(|c| c.span.start < close).count();
|
||||
if taken == 0 {
|
||||
return (self.parens(cond), 0);
|
||||
}
|
||||
let (before, after): (Vec<&Comment>, Vec<&Comment>) =
|
||||
body.leading[..taken].iter().partition(|c| c.span.start < cond.span.start);
|
||||
(self.paren_comments(cond, &before, &after), taken)
|
||||
}
|
||||
|
||||
/// True when the source wrote the optional `:` after a `default` case
|
||||
/// label. IEEE 1800 §12.5 makes it optional — `default;` is legal — and
|
||||
/// the token stream has to come back with exactly what was written.
|
||||
fn default_has_colon(&self, span: TextRange) -> bool {
|
||||
let after = span.start as usize + "default".len();
|
||||
matches!(skip_trivia(self.src, after), Some(i) if self.src.as_bytes()[i] == b':')
|
||||
}
|
||||
|
||||
/// Sequence of items at one indent level, preserving single blank lines
|
||||
/// between them. An item a fenced region swallowed emits nothing, and
|
||||
/// contributes no separator either.
|
||||
fn item_seq(&self, items: &[Item], depth: usize) -> Vec<Doc> {
|
||||
let aligns = self.param_decl_aligns(items, depth);
|
||||
let mut docs = Vec::new();
|
||||
// The last item that actually emitted something, which is what a
|
||||
// glued null item glues to.
|
||||
let mut prev: Option<&Item> = None;
|
||||
for (item, align) in items.iter().zip(&aligns) {
|
||||
let item_docs = self.item_docs(item, align.as_ref(), depth);
|
||||
if item_docs.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if !docs.is_empty() {
|
||||
if !docs.is_empty() && !prev.is_some_and(|p| self.glued_null_item(p, item)) {
|
||||
docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
}
|
||||
docs.extend(item_docs);
|
||||
prev = Some(item);
|
||||
}
|
||||
docs
|
||||
}
|
||||
|
||||
/// True when `item` is a null item (`;`) the source wrote on the line the
|
||||
/// item before it ended on, which is how it is printed back:
|
||||
/// `endgenerate;`, `end;`, `endmodule;`, `;;`.
|
||||
///
|
||||
/// The question is asked of the source rather than of the AST because it
|
||||
/// is a layout fact about the gap between two siblings, and this is the
|
||||
/// one place that gap is laid out — the same reason `eq_offset` and
|
||||
/// `default_has_colon` read `src` here. A null item that begins a body has
|
||||
/// no sibling to glue to and prints on its own line.
|
||||
///
|
||||
/// Anything that gives the `;` docs of its own — a leading comment, an
|
||||
/// attribute, a blank line, a format-off fence opening on it — takes the
|
||||
/// own-line path instead, so the glue only ever appends a bare `;`. Note
|
||||
/// that a `//` comment cannot stand in a newline-free gap: it would
|
||||
/// swallow the `;` that follows it. The only comment that fits is a
|
||||
/// one-line block comment, which prints inline before the `;`, in the
|
||||
/// order it was written.
|
||||
fn glued_null_item(&self, prev: &Item, item: &Item) -> bool {
|
||||
if !matches!(item.kind, ItemKind::Empty) {
|
||||
return false;
|
||||
}
|
||||
if item.meta.blank_before || !item.meta.leading.is_empty() || !item.meta.attrs.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if self.is_verbatim(item.span) || self.opens_at(item.span.start as usize).is_some() {
|
||||
return false;
|
||||
}
|
||||
self.src
|
||||
.get(prev.span.end as usize..item.span.start as usize)
|
||||
.is_some_and(|gap| !gap.contains('\n'))
|
||||
}
|
||||
|
||||
fn stmt_seq(&self, stmts: &[Stmt]) -> Vec<Doc> {
|
||||
let mut docs = Vec::new();
|
||||
for (i, s) in stmts.iter().enumerate() {
|
||||
@@ -969,7 +1077,7 @@ impl<'a> Fmt<'a> {
|
||||
fn head_doc(&self, kind: &ItemKind, depth: usize) -> Option<Doc> {
|
||||
match kind {
|
||||
ItemKind::Module(m) => Some(self.module_head(m, depth)),
|
||||
ItemKind::Package { kw, name, .. } => Some(text(format!("{kw} {name};"))),
|
||||
ItemKind::Package { kw, name, .. } => Some(text(format!("{kw} {};", named(name)))),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -987,7 +1095,7 @@ impl<'a> Fmt<'a> {
|
||||
match kind {
|
||||
ItemKind::Module(m) => self.module(m, depth),
|
||||
ItemKind::Package { kw, name, items, dangling, end_label, .. } => {
|
||||
let mut docs = vec![text(format!("{kw} {name};"))];
|
||||
let mut docs = vec![text(format!("{kw} {};", named(name)))];
|
||||
let mut body = Vec::new();
|
||||
if !items.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
@@ -1041,6 +1149,9 @@ impl<'a> Fmt<'a> {
|
||||
ItemKind::Modport(decls) => self.modport(decls),
|
||||
ItemKind::Clocking(c) => self.clocking(c),
|
||||
ItemKind::Verbatim(raw) => self.raw_text(raw),
|
||||
// A null item is its `;`. Whether it keeps the previous item's
|
||||
// line or takes one of its own is `item_seq`'s call.
|
||||
ItemKind::Empty => text(";"),
|
||||
ItemKind::Defparam(pairs) => {
|
||||
let parts: Vec<Doc> = pairs
|
||||
.iter()
|
||||
@@ -1077,7 +1188,7 @@ impl<'a> Fmt<'a> {
|
||||
/// Split out from the body so a range run can keep one and lay out the
|
||||
/// other (`range.rs`); a whole-file run always emits both.
|
||||
fn module_head(&self, m: &Module, depth: usize) -> Doc {
|
||||
let mut docs = vec![text(format!("{} {}", m.kw, m.name))];
|
||||
let mut docs = vec![text(format!("{} {}", m.kw, named(&m.name)))];
|
||||
let has_imports = !m.imports.is_empty();
|
||||
if has_imports {
|
||||
// One line per `import` statement the header wrote: folding two of
|
||||
@@ -1135,7 +1246,7 @@ impl<'a> Fmt<'a> {
|
||||
PortList::NonAnsi(ports) => ports
|
||||
.iter()
|
||||
.map(|p| {
|
||||
ListItem::from_meta(&p.meta, text(p.name.clone())).with_comma(p.comma)
|
||||
ListItem::from_meta(&p.meta, name_doc(&p.name)).with_comma(p.comma)
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
@@ -1170,7 +1281,7 @@ impl<'a> Fmt<'a> {
|
||||
docs.push(t);
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text(p.name.clone()));
|
||||
docs.push(name_doc(&p.name));
|
||||
docs.extend(self.unpacked_dims(&p.unpacked));
|
||||
if let Some(d) = &p.default {
|
||||
docs.push(text(" = "));
|
||||
@@ -1206,7 +1317,7 @@ impl<'a> Fmt<'a> {
|
||||
last.pop();
|
||||
}
|
||||
}
|
||||
let mut docs = vec![text(p.name.clone())];
|
||||
let mut docs = vec![name_doc(&p.name)];
|
||||
docs.extend(self.unpacked_dims(&p.unpacked));
|
||||
if let Some(d) = &p.default {
|
||||
docs.push(text(" = "));
|
||||
@@ -1238,7 +1349,7 @@ impl<'a> Fmt<'a> {
|
||||
if need_space {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text(ty.name.clone()));
|
||||
docs.push(name_doc(&ty.name));
|
||||
need_space = true;
|
||||
}
|
||||
// `uvm_analysis_port #(bit [31:0]) port;` — spaced before the `#(`,
|
||||
@@ -1355,7 +1466,7 @@ impl<'a> Fmt<'a> {
|
||||
let items: Vec<ListItem> = decls
|
||||
.iter()
|
||||
.map(|d| {
|
||||
let mut docs = vec![text(d.name.clone())];
|
||||
let mut docs = vec![name_doc(&d.name)];
|
||||
docs.extend(self.unpacked_dims(&d.unpacked));
|
||||
if let Some(init) = &d.init {
|
||||
docs.push(text(" ="));
|
||||
@@ -1450,7 +1561,7 @@ impl<'a> Fmt<'a> {
|
||||
prefix.push(text(" "));
|
||||
prefix.push(t);
|
||||
}
|
||||
let mut name = vec![text(decl.name.clone())];
|
||||
let mut name = vec![name_doc(&decl.name)];
|
||||
name.extend(self.unpacked_dims(&decl.unpacked));
|
||||
vec![
|
||||
concat(prefix),
|
||||
@@ -1495,24 +1606,28 @@ impl<'a> Fmt<'a> {
|
||||
|
||||
fn typedef(&self, t: &Typedef) -> Doc {
|
||||
match &t.kind {
|
||||
TypedefKind::ForwardClass => text(format!("typedef class {};", t.name)),
|
||||
TypedefKind::ForwardClass => text(format!("typedef class {};", named(&t.name))),
|
||||
TypedefKind::Alias(ty) => {
|
||||
let mut docs = vec![text("typedef ")];
|
||||
if let Some(d) = self.data_type(ty) {
|
||||
docs.push(d);
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text(t.name.clone()));
|
||||
docs.push(name_doc(&t.name));
|
||||
docs.extend(self.unpacked_dims(&t.unpacked));
|
||||
docs.push(text(";"));
|
||||
concat(docs)
|
||||
}
|
||||
TypedefKind::Enum(e) => {
|
||||
concat(vec![text("typedef "), self.enum_type(e), text(format!(" {};", t.name))])
|
||||
}
|
||||
TypedefKind::Struct(s) => {
|
||||
concat(vec![text("typedef "), self.struct_type(s), text(format!(" {};", t.name))])
|
||||
}
|
||||
TypedefKind::Enum(e) => concat(vec![
|
||||
text("typedef "),
|
||||
self.enum_type(e),
|
||||
text(format!(" {};", named(&t.name))),
|
||||
]),
|
||||
TypedefKind::Struct(s) => concat(vec![
|
||||
text("typedef "),
|
||||
self.struct_type(s),
|
||||
text(format!(" {};", named(&t.name))),
|
||||
]),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1532,7 +1647,10 @@ impl<'a> Fmt<'a> {
|
||||
.members
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let mut d = vec![text(m.name.clone())];
|
||||
let mut d = vec![name_doc(&m.name)];
|
||||
// Tight against the name: `OtbnDmem[16]` is one enum name
|
||||
// range, not a name with a dimension beside it.
|
||||
d.extend(m.range.iter().map(|r| self.dim(r)));
|
||||
if let Some(v) = &m.value {
|
||||
d.push(text(" = "));
|
||||
d.push(self.expr(v));
|
||||
@@ -1568,6 +1686,9 @@ impl<'a> Fmt<'a> {
|
||||
inner.push(Doc::HardLine);
|
||||
inner.extend(self.leading(&m.meta));
|
||||
let mut d = Vec::new();
|
||||
for q in &m.qualifiers {
|
||||
d.push(text(format!("{q} ")));
|
||||
}
|
||||
if let Some(ty) = self.data_type(&m.ty) {
|
||||
d.push(ty);
|
||||
d.push(text(" "));
|
||||
@@ -1601,7 +1722,7 @@ impl<'a> Fmt<'a> {
|
||||
fn cont_assign(&self, a: &ContAssign) -> Doc {
|
||||
let mut docs = vec![text("assign ")];
|
||||
if let Some(s) = &a.strength {
|
||||
docs.push(text(format!("({}, {}) ", s.first, s.second)));
|
||||
docs.push(text(format!("{} ", drive_strength(s))));
|
||||
}
|
||||
if let Some(delay) = &a.delay {
|
||||
docs.push(text("#"));
|
||||
@@ -1656,9 +1777,9 @@ impl<'a> Fmt<'a> {
|
||||
/// instantiation written on its own would be.
|
||||
fn bind(&self, b: &BindDirective, depth: usize) -> Doc {
|
||||
let head = if b.instances.is_empty() {
|
||||
b.target.clone()
|
||||
named(&b.target)
|
||||
} else {
|
||||
format!("{} : {}", b.target, join_names(&b.instances))
|
||||
format!("{} : {}", named(&b.target), join_names(&b.instances))
|
||||
};
|
||||
// The comments around the head have no node of their own; each prints
|
||||
// back between the two tokens it was written between.
|
||||
@@ -1671,7 +1792,7 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
|
||||
fn instantiation(&self, inst: &Instantiation, depth: usize) -> Doc {
|
||||
let mut docs = vec![text(inst.module.clone())];
|
||||
let mut docs = vec![name_doc(&inst.module)];
|
||||
let mut on_fresh_line = self.bracket_comments(&inst.param_comments, &mut docs, false);
|
||||
// An empty `#()` was written by hand and is reprinted as `#()`; a
|
||||
// missing one stays missing.
|
||||
@@ -1730,7 +1851,7 @@ impl<'a> Fmt<'a> {
|
||||
|
||||
/// One instance of a module instantiation: `u0 [3:0] (.a(x))`.
|
||||
fn instance(&self, instance: &Instance, depth: usize) -> Doc {
|
||||
let mut docs = vec![text(instance.name.clone())];
|
||||
let mut docs = vec![name_doc(&instance.name)];
|
||||
if !instance.dims.is_empty() {
|
||||
docs.push(text(" "));
|
||||
for d in &instance.dims {
|
||||
@@ -1805,7 +1926,7 @@ impl<'a> Fmt<'a> {
|
||||
let ends_line = self.inline_comments(&c.close_comments, &mut inner);
|
||||
let close = if ends_line { Doc::HardLine } else { Doc::SoftLine };
|
||||
vec![
|
||||
text(format!(".{}", c.name)),
|
||||
text(format!(".{}", named(&c.name))),
|
||||
concat(vec![text("("), group(vec![indent(inner), close]), text(")")]),
|
||||
]
|
||||
}
|
||||
@@ -1840,9 +1961,9 @@ impl<'a> Fmt<'a> {
|
||||
};
|
||||
}
|
||||
match &c.expr {
|
||||
None => text(format!(".{}", c.name)),
|
||||
None => text(format!(".{}", named(&c.name))),
|
||||
Some(Expr { kind: ExprKind::Empty(comments), .. }) => {
|
||||
let mut docs = vec![text(format!(".{}(", c.name))];
|
||||
let mut docs = vec![text(format!(".{}(", named(&c.name)))];
|
||||
let mut ends_line = false;
|
||||
for cm in comments {
|
||||
if ends_line {
|
||||
@@ -1862,7 +1983,7 @@ impl<'a> Fmt<'a> {
|
||||
let ends_line = self.inline_comments(&c.close_comments, &mut inner);
|
||||
let close = if ends_line { Doc::HardLine } else { Doc::SoftLine };
|
||||
concat(vec![
|
||||
text(format!(".{}(", c.name)),
|
||||
text(format!(".{}(", named(&c.name))),
|
||||
group(vec![indent(inner), close]),
|
||||
text(")"),
|
||||
])
|
||||
@@ -1872,14 +1993,28 @@ impl<'a> Fmt<'a> {
|
||||
|
||||
fn gate_instantiation(&self, g: &GateInstantiation) -> Doc {
|
||||
let mut docs = vec![text(g.gate.clone())];
|
||||
if let Some(delay) = &g.delay {
|
||||
if let Some(s) = &g.strength {
|
||||
docs.push(text(format!(" {}", drive_strength(s))));
|
||||
}
|
||||
if let [delay] = g.delay.as_slice() {
|
||||
// One value prints itself, brackets and all (`#5`, `#(5)`).
|
||||
docs.push(text(" #"));
|
||||
docs.push(self.expr(delay));
|
||||
} else if !g.delay.is_empty() {
|
||||
// `#(rise, fall[, turn-off])` — the parens are the list's own.
|
||||
docs.push(text(" #("));
|
||||
for (i, d) in g.delay.iter().enumerate() {
|
||||
if i > 0 {
|
||||
docs.push(text(", "));
|
||||
}
|
||||
docs.push(self.expr(d));
|
||||
}
|
||||
docs.push(text(")"));
|
||||
}
|
||||
for (i, inst) in g.instances.iter().enumerate() {
|
||||
docs.push(if i > 0 { text(", ") } else { text(" ") });
|
||||
if let Some(name) = &inst.name {
|
||||
docs.push(text(name.clone()));
|
||||
docs.push(name_doc(name));
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.expr_list("(", &inst.args, ")"));
|
||||
@@ -1929,7 +2064,7 @@ impl<'a> Fmt<'a> {
|
||||
fn gen_block(&self, docs: &mut Vec<Doc>, b: &GenBlock, depth: usize) -> bool {
|
||||
if b.is_block {
|
||||
match &b.label {
|
||||
Some(l) => docs.push(text(format!(" begin : {l}"))),
|
||||
Some(l) => docs.push(text(format!(" begin : {}", named(l)))),
|
||||
None => docs.push(text(" begin")),
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
@@ -1973,7 +2108,7 @@ impl<'a> Fmt<'a> {
|
||||
for item in &g.items {
|
||||
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
body.extend(self.leading(&item.meta));
|
||||
let mut item_docs = vec![self.case_labels(&item.labels)];
|
||||
let mut item_docs = vec![self.case_labels(&item.labels, item.span)];
|
||||
self.gen_block(&mut item_docs, &item.body, depth + 1);
|
||||
body.push(concat(item_docs));
|
||||
body.extend(self.trailing(&item.meta));
|
||||
@@ -2010,7 +2145,7 @@ impl<'a> Fmt<'a> {
|
||||
docs.push(t);
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(text(a.name.clone()));
|
||||
docs.push(name_doc(&a.name));
|
||||
docs.extend(self.unpacked_dims(&a.unpacked));
|
||||
if let Some(d) = &a.default {
|
||||
docs.push(text(" = "));
|
||||
@@ -2036,7 +2171,7 @@ impl<'a> Fmt<'a> {
|
||||
head.push_str(lifetime);
|
||||
head.push(' ');
|
||||
}
|
||||
head.push_str(&c.name);
|
||||
head.push_str(&named(&c.name));
|
||||
let mut docs = vec![text(head)];
|
||||
let on_fresh_line = self.bracket_comments(&c.param_comments, &mut docs, false);
|
||||
if let Some(params) = &c.param_ports {
|
||||
@@ -2050,7 +2185,7 @@ impl<'a> Fmt<'a> {
|
||||
docs.push(self.delimited_dangling("(", items, &c.param_dangling, ")", broken));
|
||||
}
|
||||
if let Some(ext) = &c.extends {
|
||||
docs.push(text(format!(" extends {}", ext.name)));
|
||||
docs.push(text(format!(" extends {}", named(&ext.name))));
|
||||
let fresh = self.bracket_comments(&ext.param_comments, &mut docs, false);
|
||||
if let Some(params) = &ext.params {
|
||||
let items: Vec<ListItem> = params
|
||||
@@ -2094,7 +2229,7 @@ impl<'a> Fmt<'a> {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.extend(self.leading(&d.meta));
|
||||
docs.push(text(format!("{} ", d.name)));
|
||||
docs.push(text(format!("{} ", named(&d.name))));
|
||||
let items: Vec<ListItem> = d
|
||||
.ports
|
||||
.iter()
|
||||
@@ -2134,7 +2269,7 @@ impl<'a> Fmt<'a> {
|
||||
let mut head = String::from(if c.is_default { "default clocking" } else { "clocking" });
|
||||
if let Some(n) = &c.name {
|
||||
head.push(' ');
|
||||
head.push_str(&n.text);
|
||||
head.push_str(&named(&n.text));
|
||||
}
|
||||
let mut docs = vec![text(head)];
|
||||
// `default clocking cb;` selects an existing block: no event, no body.
|
||||
@@ -2161,6 +2296,10 @@ impl<'a> Fmt<'a> {
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// One clocking-block item. A `= expression` binding
|
||||
/// (`output tms = _tms_internal;`) prints on the item's own line: the
|
||||
/// bound expression is a signal name, never long enough to be worth a
|
||||
/// breakable group.
|
||||
fn clocking_item(&self, kind: &ClockingItemKind) -> Doc {
|
||||
match kind {
|
||||
ClockingItemKind::Default { input, output } => {
|
||||
@@ -2175,15 +2314,25 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
text(s)
|
||||
}
|
||||
ClockingItemKind::Signals { dir, skew, names } => {
|
||||
let mut s = dir.clone();
|
||||
ClockingItemKind::Signals { dir, skew, signals } => {
|
||||
let mut head = dir.clone();
|
||||
if let Some(skew) = skew {
|
||||
s.push(' ');
|
||||
s.push_str(skew);
|
||||
head.push(' ');
|
||||
head.push_str(skew);
|
||||
}
|
||||
s.push(' ');
|
||||
s.push_str(&join_names(names));
|
||||
text(s)
|
||||
head.push(' ');
|
||||
let mut docs = vec![text(head)];
|
||||
for (i, sig) in signals.iter().enumerate() {
|
||||
if i > 0 {
|
||||
docs.push(text(", "));
|
||||
}
|
||||
docs.push(name_doc(&sig.name.text));
|
||||
if let Some(value) = &sig.value {
|
||||
docs.push(text(" = "));
|
||||
docs.push(self.expr(value));
|
||||
}
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2195,10 +2344,10 @@ impl<'a> Fmt<'a> {
|
||||
ExportDecl::Dpi(d) => {
|
||||
let mut head = format!("export {} ", d.spec);
|
||||
if let Some(c) = &d.c_identifier {
|
||||
head.push_str(&c.text);
|
||||
head.push_str(&named(&c.text));
|
||||
head.push_str(" = ");
|
||||
}
|
||||
text(format!("{head}{} {};", d.kw, d.name.text))
|
||||
text(format!("{head}{} {};", d.kw, named(&d.name.text)))
|
||||
}
|
||||
ExportDecl::Package(paths) => text(format!("export {};", join_paths(paths))),
|
||||
}
|
||||
@@ -2207,7 +2356,7 @@ impl<'a> Fmt<'a> {
|
||||
/// `let max(a, b) = (a > b) ? a : b;` (IEEE 1800 §11.12) — a name, an
|
||||
/// optional port list laid out like a function's, and one expression.
|
||||
fn let_decl(&self, l: &LetDecl) -> Doc {
|
||||
let mut docs = vec![text(format!("let {}", l.name))];
|
||||
let mut docs = vec![text(format!("let {}", named(&l.name)))];
|
||||
if l.has_parens {
|
||||
docs.push(self.tf_args(&l.ports));
|
||||
}
|
||||
@@ -2235,9 +2384,9 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
}
|
||||
if let Some(scope) = &f.scope {
|
||||
header.push(text(format!("{scope}::")));
|
||||
header.push(text(format!("{}::", named(scope))));
|
||||
}
|
||||
header.push(text(f.name.clone()));
|
||||
header.push(name_doc(&f.name));
|
||||
if f.has_parens {
|
||||
header.push(self.tf_args(&f.args));
|
||||
}
|
||||
@@ -2275,9 +2424,9 @@ impl<'a> Fmt<'a> {
|
||||
header.push(text(format!("{q} ")));
|
||||
}
|
||||
if let Some(scope) = &t.scope {
|
||||
header.push(text(format!("{scope}::")));
|
||||
header.push(text(format!("{}::", named(scope))));
|
||||
}
|
||||
header.push(text(t.name.clone()));
|
||||
header.push(name_doc(&t.name));
|
||||
if t.has_parens {
|
||||
header.push(self.tf_args(&t.args));
|
||||
}
|
||||
@@ -2312,10 +2461,17 @@ impl<'a> Fmt<'a> {
|
||||
/// blocks cuddle onto the prefix line, single statements go on the same
|
||||
/// line if they fit, otherwise indented on the next line.
|
||||
fn stmt_as_body(&self, prefix: Doc, s: &Stmt) -> Doc {
|
||||
self.stmt_as_body_from(prefix, s, 0)
|
||||
}
|
||||
|
||||
/// The same, skipping the body's first `skip` leading comments because
|
||||
/// `prefix` already printed them inside its parentheses. See
|
||||
/// [`Fmt::header_parens`].
|
||||
fn stmt_as_body_from(&self, prefix: Doc, s: &Stmt, skip: usize) -> Doc {
|
||||
match &s.kind {
|
||||
StmtKind::Block { label, stmts, dangling, end_label, .. } => {
|
||||
let mut docs = vec![prefix, text(" ")];
|
||||
docs.extend(self.leading(&s.meta));
|
||||
docs.extend(self.leading_from(&s.meta, skip));
|
||||
docs.push(self.block_doc(label, stmts, dangling, end_label));
|
||||
docs.extend(self.trailing(&s.meta));
|
||||
concat(docs)
|
||||
@@ -2323,13 +2479,19 @@ impl<'a> Fmt<'a> {
|
||||
StmtKind::Timing { control, stmt: Some(inner) } => {
|
||||
// e.g. `always @(posedge clk) begin ... end`
|
||||
let mut docs = vec![prefix, text(" ")];
|
||||
docs.extend(self.leading(&s.meta));
|
||||
docs.extend(self.leading_from(&s.meta, skip));
|
||||
let control_doc = self.timing_control(control);
|
||||
docs.push(self.stmt_as_body(control_doc, inner));
|
||||
docs.extend(self.trailing(&s.meta));
|
||||
concat(docs)
|
||||
}
|
||||
_ => group(vec![prefix, indent(vec![Doc::Line, self.stmt(s)])]),
|
||||
// The same three parts `stmt` prints, with the skip applied.
|
||||
_ => {
|
||||
let mut body = self.leading_from(&s.meta, skip);
|
||||
body.push(self.stmt_kind(&s.kind));
|
||||
body.extend(self.trailing(&s.meta));
|
||||
group(vec![prefix, indent(vec![Doc::Line, concat(body)])])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2341,7 +2503,7 @@ impl<'a> Fmt<'a> {
|
||||
end_label: &Option<String>,
|
||||
) -> Doc {
|
||||
let mut docs = vec![match label {
|
||||
Some(l) => text(format!("begin : {l}")),
|
||||
Some(l) => text(format!("begin : {}", named(l))),
|
||||
None => text("begin"),
|
||||
}];
|
||||
let mut body = Vec::new();
|
||||
@@ -2417,6 +2579,12 @@ impl<'a> Fmt<'a> {
|
||||
parts.push(text(format!("{e} ")));
|
||||
}
|
||||
parts.push(self.expr(&i.expr));
|
||||
// `posedge clk iff enable` — the gate belongs to this
|
||||
// term, so it prints before the separator, not after it.
|
||||
if let Some(iff) = &i.iff {
|
||||
parts.push(text(" iff "));
|
||||
parts.push(self.expr(iff));
|
||||
}
|
||||
if self.inline_comments(&i.meta.before_sep, &mut parts) {
|
||||
parts.push(Doc::HardLine);
|
||||
}
|
||||
@@ -2436,7 +2604,7 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
StmtKind::ForkJoin { label, join_kw, stmts, dangling, end_label, .. } => {
|
||||
let mut docs = vec![match label {
|
||||
Some(l) => text(format!("fork : {l}")),
|
||||
Some(l) => text(format!("fork : {}", named(l))),
|
||||
None => text("fork"),
|
||||
}];
|
||||
let mut body = Vec::new();
|
||||
@@ -2461,17 +2629,21 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
head.push_str(kw);
|
||||
head.push(' ');
|
||||
let mut docs = vec![text(head), self.parens(expr)];
|
||||
let (parens, taken) = match items.first() {
|
||||
Some(first) => self.header_parens(expr, &first.meta),
|
||||
None => (self.parens(expr), 0),
|
||||
};
|
||||
let mut docs = vec![text(head), parens];
|
||||
if *inside {
|
||||
docs.push(text(" inside"));
|
||||
}
|
||||
docs.push(self.case_body(items, dangling));
|
||||
docs.push(self.case_body(items, dangling, taken));
|
||||
concat(docs)
|
||||
}
|
||||
// `randcase` is a `case` body with weights for labels and no
|
||||
// selector, so it shares the body layout.
|
||||
StmtKind::RandCase { items, dangling } => {
|
||||
concat(vec![text("randcase"), self.case_body(items, dangling)])
|
||||
concat(vec![text("randcase"), self.case_body(items, dangling, 0)])
|
||||
}
|
||||
StmtKind::For { init, cond, step, body } => {
|
||||
let mut header = vec![text("for (")];
|
||||
@@ -2503,7 +2675,8 @@ impl<'a> Fmt<'a> {
|
||||
self.stmt_as_body(concat(header), body)
|
||||
}
|
||||
StmtKind::While { cond, body } => {
|
||||
self.stmt_as_body(concat(vec![text("while "), self.parens(cond)]), body)
|
||||
let (parens, taken) = self.header_parens(cond, &body.meta);
|
||||
self.stmt_as_body_from(concat(vec![text("while "), parens]), body, taken)
|
||||
}
|
||||
StmtKind::DoWhile { body, cond } => {
|
||||
let mut docs = vec![text("do")];
|
||||
@@ -2524,7 +2697,8 @@ impl<'a> Fmt<'a> {
|
||||
concat(docs)
|
||||
}
|
||||
StmtKind::Repeat { count, body } => {
|
||||
self.stmt_as_body(concat(vec![text("repeat "), self.parens(count)]), body)
|
||||
let (parens, taken) = self.header_parens(count, &body.meta);
|
||||
self.stmt_as_body_from(concat(vec![text("repeat "), parens]), body, taken)
|
||||
}
|
||||
StmtKind::Forever { body } => self.stmt_as_body(text("forever"), body),
|
||||
StmtKind::Foreach { target, vars, body } => {
|
||||
@@ -2581,16 +2755,18 @@ impl<'a> Fmt<'a> {
|
||||
None => concat(vec![control_doc, text(";")]),
|
||||
}
|
||||
}
|
||||
StmtKind::Wait { cond, stmt } => {
|
||||
let head = concat(vec![text("wait "), self.parens(cond)]);
|
||||
match stmt {
|
||||
Some(s) => self.stmt_as_body(head, s),
|
||||
None => concat(vec![head, text(";")]),
|
||||
StmtKind::Wait { cond, stmt } => match stmt {
|
||||
Some(s) => {
|
||||
let (parens, taken) = self.header_parens(cond, &s.meta);
|
||||
self.stmt_as_body_from(concat(vec![text("wait "), parens]), s, taken)
|
||||
}
|
||||
}
|
||||
None => concat(vec![text("wait "), self.parens(cond), text(";")]),
|
||||
},
|
||||
StmtKind::ExprStmt(e) => concat(vec![self.expr(e), text(";")]),
|
||||
StmtKind::EventTrigger(e) => concat(vec![text("-> "), self.expr(e), text(";")]),
|
||||
StmtKind::VarDecl(d) => concat(vec![self.data_decl(d), text(";")]),
|
||||
// The item form prints its own `;`.
|
||||
StmtKind::Typedef(t) => self.typedef(t),
|
||||
StmtKind::ParamDecl(d) => concat(vec![self.param_decl(d, None), text(";")]),
|
||||
StmtKind::PortDecl(d) => concat(vec![self.port_decl(d), text(";")]),
|
||||
StmtKind::Return(e) => match e {
|
||||
@@ -2599,13 +2775,13 @@ impl<'a> Fmt<'a> {
|
||||
},
|
||||
StmtKind::Break => text("break;"),
|
||||
StmtKind::Continue => text("continue;"),
|
||||
StmtKind::Disable(name) => text(format!("disable {name};")),
|
||||
StmtKind::Disable(name) => text(format!("disable {};", named(name))),
|
||||
StmtKind::WaitFork => text("wait fork;"),
|
||||
StmtKind::Import(paths) => text(format!("import {};", join_paths(paths))),
|
||||
// A statement label prints tight against its `:`, the way a case
|
||||
// label does: `check_decode: assert (...)`.
|
||||
StmtKind::Labeled { name, stmt, .. } => {
|
||||
concat(vec![text(format!("{name}: ")), self.stmt(stmt)])
|
||||
concat(vec![text(format!("{}: ", named(name))), self.stmt(stmt)])
|
||||
}
|
||||
StmtKind::Directive(d) => self.raw_text(d),
|
||||
// See `ItemKind::Error`: unreachable from `format_source`, present
|
||||
@@ -2652,9 +2828,13 @@ impl<'a> Fmt<'a> {
|
||||
head.push(' ');
|
||||
}
|
||||
head.push_str("if ");
|
||||
let prefix = concat(vec![text(head), self.parens(cond)]);
|
||||
let then_is_block = matches!(then.kind, StmtKind::Block { .. });
|
||||
let mut docs = vec![self.stmt_as_body(prefix, then)];
|
||||
let (parens, taken) = self.header_parens(cond, &then.meta);
|
||||
let prefix = concat(vec![text(head), parens]);
|
||||
// A line comment trailing the then-branch runs to end of line, so a
|
||||
// cuddled `else` would be swallowed into its text.
|
||||
let then_is_block =
|
||||
matches!(then.kind, StmtKind::Block { .. }) && !trailing_ends_line(&then.meta);
|
||||
let mut docs = vec![self.stmt_as_body_from(prefix, then, taken)];
|
||||
if let Some(els) = els {
|
||||
// A comment written before `else` prints before it, each on its
|
||||
// own line: it is where the source put it, and after the keyword
|
||||
@@ -2692,9 +2872,9 @@ impl<'a> Fmt<'a> {
|
||||
/// Labels normally share one line; as soon as any of them carries a
|
||||
/// comment they go one per line, so a comment written between two labels
|
||||
/// is printed between the same two labels instead of drifting past them.
|
||||
fn case_labels(&self, labels: &[ExprItem]) -> Doc {
|
||||
fn case_labels(&self, labels: &[ExprItem], item: TextRange) -> Doc {
|
||||
if labels.is_empty() {
|
||||
return text("default:");
|
||||
return text(if self.default_has_colon(item) { "default:" } else { "default" });
|
||||
}
|
||||
let plain = labels.iter().all(|l| {
|
||||
l.meta.leading.is_empty() && l.meta.before_sep.is_empty() && l.meta.trailing.is_none()
|
||||
@@ -2736,16 +2916,27 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
|
||||
fn case_item(&self, item: &CaseItem) -> Doc {
|
||||
self.stmt_as_body(self.case_labels(&item.labels), &item.stmt)
|
||||
// `default;` — the colon IEEE 1800 §12.5 makes optional, with a null
|
||||
// body. The `;` closes the keyword rather than standing as a body of
|
||||
// its own, so it hugs instead of going through `stmt_as_body`.
|
||||
if item.labels.is_empty()
|
||||
&& matches!(item.stmt.kind, StmtKind::Null)
|
||||
&& is_bare(&item.stmt.meta)
|
||||
&& !self.default_has_colon(item.span)
|
||||
{
|
||||
return text("default;");
|
||||
}
|
||||
self.stmt_as_body(self.case_labels(&item.labels, item.span), &item.stmt)
|
||||
}
|
||||
|
||||
/// The indented items of a `case`/`randcase` body and the `endcase` that
|
||||
/// closes it.
|
||||
fn case_body(&self, items: &[CaseItem], dangling: &[Comment]) -> Doc {
|
||||
/// The items of a `case`/`randcase` body. `skip` is the number of leading
|
||||
/// comments of the *first* item the `case (...)` header already printed
|
||||
/// inside its parentheses (see [`Fmt::header_parens`]).
|
||||
fn case_body(&self, items: &[CaseItem], dangling: &[Comment], skip: usize) -> Doc {
|
||||
let mut body = Vec::new();
|
||||
for item in items {
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
body.extend(self.leading(&item.meta));
|
||||
body.extend(self.leading_from(&item.meta, if i == 0 { skip } else { 0 }));
|
||||
body.push(self.case_item(item));
|
||||
body.extend(self.trailing(&item.meta));
|
||||
}
|
||||
@@ -2781,7 +2972,7 @@ impl<'a> Fmt<'a> {
|
||||
|
||||
fn expr(&self, e: &Expr) -> Doc {
|
||||
match &e.kind {
|
||||
ExprKind::Ident(s) => text(s.clone()),
|
||||
ExprKind::Ident(s) => name_doc(s),
|
||||
ExprKind::Number(s) => text(s.clone()),
|
||||
ExprKind::Str(s) => text(s.clone()),
|
||||
// Only reachable through `connection`, which handles the comments.
|
||||
@@ -2836,10 +3027,10 @@ impl<'a> Fmt<'a> {
|
||||
text("]"),
|
||||
]),
|
||||
ExprKind::Member { base, name } => {
|
||||
concat(vec![self.expr(base), text(format!(".{name}"))])
|
||||
concat(vec![self.expr(base), text(format!(".{}", named(name)))])
|
||||
}
|
||||
ExprKind::Scope { base, name } => {
|
||||
concat(vec![self.expr(base), text(format!("::{name}"))])
|
||||
concat(vec![self.expr(base), text(format!("::{}", named(name)))])
|
||||
}
|
||||
// Written tight, like the `::` it almost always precedes.
|
||||
ExprKind::Parameterized { base, params } => {
|
||||
@@ -2866,25 +3057,16 @@ impl<'a> Fmt<'a> {
|
||||
if before.is_empty() && after.is_empty() {
|
||||
return self.parens(inner);
|
||||
}
|
||||
// A comment inside the parens forces them open, the same way
|
||||
// a comment inside a port list does.
|
||||
let mut docs = vec![Doc::SoftLine];
|
||||
for c in before {
|
||||
docs.push(self.comment(c));
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(self.expr(inner));
|
||||
let mut outer = vec![text("("), indent(docs)];
|
||||
for c in after {
|
||||
outer.push(text(" "));
|
||||
outer.push(self.comment(c));
|
||||
}
|
||||
let ends_line = after.iter().any(|c| is_line_comment(&c.text));
|
||||
outer.push(if ends_line { Doc::HardLine } else { Doc::SoftLine });
|
||||
outer.push(text(")"));
|
||||
group(outer)
|
||||
let before: Vec<&Comment> = before.iter().collect();
|
||||
let after: Vec<&Comment> = after.iter().collect();
|
||||
self.paren_comments(inner, &before, &after)
|
||||
}
|
||||
ExprKind::Cast { ty, expr } => {
|
||||
// `ty'{...}` prints no brackets of its own: the assignment
|
||||
// pattern already carries the `'{` and the `}`.
|
||||
ExprKind::Cast { ty, expr, pattern: true } => {
|
||||
concat(vec![self.expr(ty), self.expr(expr)])
|
||||
}
|
||||
ExprKind::Cast { ty, expr, .. } => {
|
||||
concat(vec![self.expr(ty), text("'("), self.expr(expr), text(")")])
|
||||
}
|
||||
ExprKind::AssignPattern(items) => {
|
||||
@@ -2926,7 +3108,7 @@ impl<'a> Fmt<'a> {
|
||||
// `.name(value)`, tight, with a break opportunity inside.
|
||||
ExprKind::NamedArg { name, value, close_comments, .. } => match &value.kind {
|
||||
ExprKind::Empty(comments) => {
|
||||
let mut docs = vec![text(format!(".{name}("))];
|
||||
let mut docs = vec![text(format!(".{}(", named(name)))];
|
||||
let mut ends_line = false;
|
||||
for cm in comments {
|
||||
if ends_line {
|
||||
@@ -2946,7 +3128,7 @@ impl<'a> Fmt<'a> {
|
||||
let ends_line = self.inline_comments(close_comments, &mut inner);
|
||||
let close = if ends_line { Doc::HardLine } else { Doc::SoftLine };
|
||||
concat(vec![
|
||||
text(format!(".{name}(")),
|
||||
text(format!(".{}(", named(name))),
|
||||
group(vec![indent(inner), close]),
|
||||
text(")"),
|
||||
])
|
||||
@@ -3044,16 +3226,73 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `(weak0, pull1)`, or the single-strength `(weak1)` a pull gate may write.
|
||||
fn drive_strength(s: &DriveStrength) -> String {
|
||||
match &s.second {
|
||||
Some(second) => format!("({}, {})", s.first, second),
|
||||
None => format!("({})", s.first),
|
||||
}
|
||||
}
|
||||
|
||||
/// A name, plus the space that terminates it when it is an escaped identifier.
|
||||
///
|
||||
/// An escaped identifier runs from its `\` to the next **whitespace**
|
||||
/// character and to nothing else (IEEE 1800-2017 §5.6.1), so `\my-signal;`
|
||||
/// lexes as one identifier that swallows the `;`, and `.\my-port(x)` as one
|
||||
/// that swallows the rest of the line. Every name this file writes goes
|
||||
/// through here (or through [`name_doc`], its `Doc` twin): declarators,
|
||||
/// ANSI and non-ANSI ports, parameters and their aligned cells, type names,
|
||||
/// typedef/enum/genvar/`let` names, module, package, class, function, task,
|
||||
/// modport and clocking names, instance and module-instance names, port
|
||||
/// connections and named call arguments, `extends`, scopes, hierarchical
|
||||
/// members, tf arguments, block/fork/statement labels, every `end : label`,
|
||||
/// `disable`, and the `join_names`/`join_paths` lists. The audit that built
|
||||
/// that list is a grep of `text(` and `format!(` over this file; a site that
|
||||
/// grows a name later belongs on it.
|
||||
///
|
||||
/// The space is unconditional. Where the layout already writes a separator
|
||||
/// the output carries two (`logic \a = 1;`) — legal, a fixed point under
|
||||
/// re-formatting, and cheaper than a second rule about what comes next.
|
||||
fn named(s: &str) -> String {
|
||||
if ends_escaped(s) {
|
||||
format!("{s} ")
|
||||
} else {
|
||||
s.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// [`named`] as a `Doc`.
|
||||
fn name_doc(s: &str) -> Doc {
|
||||
text(named(s))
|
||||
}
|
||||
|
||||
/// Whether `s` ends *inside* an escaped identifier, and so cannot be followed
|
||||
/// directly by punctuation.
|
||||
///
|
||||
/// Whitespace is the only terminator, so the question is exactly whether a
|
||||
/// `\` survives in the run of characters after the last whitespace — which
|
||||
/// also answers it for the composites the AST hands over already joined
|
||||
/// (`a.\b`, `pkg::\x`). Conservative by construction: a false positive
|
||||
/// writes one harmless extra space. `vlog_refactor::instantiate` carries the
|
||||
/// same two-line rule for the skeletons it splices.
|
||||
fn ends_escaped(s: &str) -> bool {
|
||||
s.rsplit(char::is_whitespace).next().unwrap_or(s).contains('\\')
|
||||
}
|
||||
|
||||
/// A comma-separated list of names, as the source wrote them. The parser
|
||||
/// keeps each name's byte range alongside its text, so the joined spelling is
|
||||
/// rebuilt here rather than stored.
|
||||
fn join_names(names: &[Name]) -> String {
|
||||
names.iter().map(|n| n.text.as_str()).collect::<Vec<_>>().join(", ")
|
||||
names.iter().map(|n| named(&n.text)).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
/// The same for a list of `pkg::item` import paths.
|
||||
fn join_paths(paths: &[ImportPath]) -> String {
|
||||
paths.iter().map(ImportPath::text).collect::<Vec<_>>().join(", ")
|
||||
paths
|
||||
.iter()
|
||||
.map(|p| format!("{}::{}", named(&p.pkg.text), named(&p.item.text)))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
|
||||
/// `import "DPI-C" [context|pure ][c_name = ]` — the linkage prefix a DPI
|
||||
@@ -3065,7 +3304,7 @@ fn dpi_import_prefix(d: &DpiImport) -> String {
|
||||
s.push(' ');
|
||||
}
|
||||
if let Some(c) = &d.c_identifier {
|
||||
s.push_str(&c.text);
|
||||
s.push_str(&named(&c.text));
|
||||
s.push_str(" = ");
|
||||
}
|
||||
s
|
||||
@@ -3094,3 +3333,53 @@ fn strip_blanks(line: &str, n: usize) -> &str {
|
||||
fn is_line_comment(text: &str) -> bool {
|
||||
text.starts_with("//")
|
||||
}
|
||||
|
||||
/// True when a node carries no trivia at all, so printing it cannot move a
|
||||
/// comment anywhere.
|
||||
fn is_bare(meta: &Meta) -> bool {
|
||||
meta.leading.is_empty()
|
||||
&& meta.trailing.is_none()
|
||||
&& meta.before_sep.is_empty()
|
||||
&& meta.attrs.is_empty()
|
||||
}
|
||||
|
||||
/// True when a node's trailing comments end in a line comment, so anything
|
||||
/// printed after them on the same line would be swallowed into the comment's
|
||||
/// text. `trailing` prints `before_sep` first and `trailing` last.
|
||||
fn trailing_ends_line(meta: &Meta) -> bool {
|
||||
match &meta.trailing {
|
||||
Some(tr) => is_line_comment(&tr.text),
|
||||
None => meta.before_sep.last().is_some_and(|c| is_line_comment(&c.text)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Offset of the first byte at or after `from` that is neither whitespace nor
|
||||
/// part of a comment, or `None` if the text ends first.
|
||||
///
|
||||
/// Used to ask what a node is followed by in the source — a `)` that closes
|
||||
/// the header it sits in, the optional `:` of a `default` case label — when
|
||||
/// the AST does not record it.
|
||||
fn skip_trivia(src: &str, from: usize) -> Option<usize> {
|
||||
let bytes = src.as_bytes();
|
||||
let mut i = from;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'/' if bytes.get(i + 1) == Some(&b'/') => {
|
||||
i += 2;
|
||||
while i < bytes.len() && bytes[i] != b'\n' {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
b'/' if bytes.get(i + 1) == Some(&b'*') => {
|
||||
i += 2;
|
||||
while i < bytes.len() && !(bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/')) {
|
||||
i += 1;
|
||||
}
|
||||
i = (i + 2).min(bytes.len());
|
||||
}
|
||||
c if c.is_ascii_whitespace() => i += 1,
|
||||
_ => return Some(i),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
# 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
|
||||
@@ -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,263 @@
|
||||
# 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 -- the whole instantiation becomes the
|
||||
# block, ending at its `;`
|
||||
# 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
|
||||
@@ -0,0 +1,309 @@
|
||||
# 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
|
||||
====
|
||||
# SKIP a `pkg::type` chain is joined into one string by the parser, so the
|
||||
# SKIP boundary between the two escaped names is lost and the safety net
|
||||
# SKIP rejects the file (no output, no corruption). Fixing it needs
|
||||
# SKIP `parse_scoped_name` to keep its segments — see the Handshakes section
|
||||
# SKIP of docs/features/escaped-identifiers/README.md.
|
||||
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,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,86 @@
|
||||
# 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. The whole item is an
|
||||
# ItemKind::Verbatim leaf, so the body is reproduced byte for byte; only the
|
||||
# block's absolute indent is re-set, exactly as for an in-class constraint.
|
||||
|
||||
# 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
|
||||
@@ -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) {
|
||||
|
||||
@@ -1257,3 +1257,423 @@ fn an_opaque_body_cannot_launder_a_stray_endif_into_a_split() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Assert `format_source` refuses `input` with a verification error, i.e. the
|
||||
/// safety net caught the layout and the caller keeps the original bytes.
|
||||
fn expect_refusal(input: &str) {
|
||||
match format_source(input, &Config::default()) {
|
||||
Err(FormatError::Verification(_)) => {}
|
||||
Ok(out) => panic!("expected a refusal, got:\n{out}"),
|
||||
Err(e) => panic!("expected a verification refusal, got {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The header shapes `header_parens` deliberately does *not* cover, pinned as
|
||||
/// clean refusals so a future round sees them move rather than appear.
|
||||
///
|
||||
/// `for` and `foreach` do not end their header in a single condition
|
||||
/// expression, and a `do ... while (c);` has no body after its parentheses to
|
||||
/// take the comment back from. All three still leave the file untouched.
|
||||
#[test]
|
||||
fn a_comment_in_a_for_foreach_or_do_while_header_is_still_refused() {
|
||||
for input in [
|
||||
"module m;\n initial begin\n for (int i = 0; i < 4; i++ // why\n ) begin\n y = 1;\n end\n end\nendmodule\n",
|
||||
"module m;\n initial begin\n foreach (arr[i] // why\n ) begin\n y = 1;\n end\n end\nendmodule\n",
|
||||
"module m;\n initial begin\n do begin\n y = 1;\n end while (c // why\n );\n end\nendmodule\n",
|
||||
] {
|
||||
expect_refusal(input);
|
||||
}
|
||||
}
|
||||
|
||||
/// The three bucket-2 shapes, formatted for real: every comment comes back
|
||||
/// with its own text, none merged into the code that follows it, and the
|
||||
/// second pass is a fixed point.
|
||||
#[test]
|
||||
fn the_repaired_comment_shapes_keep_every_comment_intact() {
|
||||
for (input, kept, banned) in [
|
||||
(
|
||||
"module m;\n always_comb begin\n if (a) begin\n x = 1;\n end // addr_phase_write\n else if (b) begin\n x = 2;\n end\n end\nendmodule\n",
|
||||
"// addr_phase_write",
|
||||
"// addr_phase_write else",
|
||||
),
|
||||
(
|
||||
"module m;\n always_comb begin\n if (// why not\n a || b) begin\n x = 1;\n end\n end\nendmodule\n",
|
||||
"// why not",
|
||||
") // why not",
|
||||
),
|
||||
(
|
||||
"module m;\n always_comb begin\n if (a /* and here */) begin\n x = 1;\n end\n end\nendmodule\n",
|
||||
"/* and here */",
|
||||
") /* and here */",
|
||||
),
|
||||
] {
|
||||
let out = format_source(input, &Config::default()).expect("formats cleanly");
|
||||
assert!(out.contains(kept), "comment lost:\n{out}");
|
||||
assert!(!out.contains(banned), "comment merged or moved:\n{out}");
|
||||
let again = format_source(&out, &Config::default()).expect("formats again");
|
||||
assert_eq!(out, again, "not idempotent");
|
||||
}
|
||||
}
|
||||
|
||||
/// Standing rule (`topo.md` §2.1): `verify.rs` was not widened for any of
|
||||
/// these fixes, and the corruptions they used to produce must still be
|
||||
/// rejected if a future layout change reintroduces them.
|
||||
#[test]
|
||||
fn the_bucket_two_corruptions_are_still_rejected() {
|
||||
// A trailing line comment swallowing the `else if` that followed it.
|
||||
expect_divergence(
|
||||
"module m;\n always_comb begin\n if (a) begin\n x = 1;\n end // note\n else if (b) begin\n x = 2;\n end\n end\nendmodule\n",
|
||||
"module m;\n always_comb begin\n if (a) begin\n x = 1;\n end // note else if (b) begin\n x = 2;\n end\n end\nendmodule\n",
|
||||
);
|
||||
// A comment written inside the condition, printed after the `)`.
|
||||
expect_divergence(
|
||||
"module m;\n always_comb begin\n if (// note\n a) begin\n x = 1;\n end\n end\nendmodule\n",
|
||||
"module m;\n always_comb begin\n if (a) // note\n begin\n x = 1;\n end\n end\nendmodule\n",
|
||||
);
|
||||
// The `:` a `default;` did not write, invented by the printer.
|
||||
expect_divergence(
|
||||
"module m;\n always_comb begin\n case (s)\n A: y = 1;\n default;\n endcase\n end\nendmodule\n",
|
||||
"module m;\n always_comb begin\n case (s)\n A: y = 1;\n default: ;\n endcase\n end\nendmodule\n",
|
||||
);
|
||||
// And its mirror: a `default: ;` losing the colon it did write.
|
||||
expect_divergence(
|
||||
"module m;\n always_comb begin\n case (s)\n A: y = 1;\n default: ;\n endcase\n end\nendmodule\n",
|
||||
"module m;\n always_comb begin\n case (s)\n A: y = 1;\n default;\n endcase\n end\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
/// A comment written just after a statement header's `(` is queued by the
|
||||
/// parser and drained onto the first bracket it meets — so when the condition
|
||||
/// started with a call, `CallComments::before_open` swallowed it and the
|
||||
/// comment printed between the callee and its `(`. This was pinned as a
|
||||
/// refusal until the directive-in-statements round delivered the parser's
|
||||
/// `take_gap` fix (2026-08-29); the pin flips exactly as the Handshake said
|
||||
/// it should: the shape now formats, the comment keeps its place inside the
|
||||
/// parens, and the round trip is a fixed point. The last of bucket 2's 12.
|
||||
#[test]
|
||||
fn a_comment_before_a_call_in_a_condition_now_formats() {
|
||||
let input = "module m;\n function automatic int f();\n if (// why\n !en() || b\n ) begin\n return 1;\n end\n endfunction\nendmodule\n";
|
||||
let expected = "module m;\n function automatic int f();\n if (\n // why\n !en() || b\n ) begin\n return 1;\n end\n endfunction\nendmodule\n";
|
||||
let config = Config::default();
|
||||
let once = format_source(input, &config).expect("the delivered handshake formats this");
|
||||
assert_eq!(once, expected, "the comment stays inside the parens");
|
||||
let twice = format_source(&once, &config).expect("and the result still formats");
|
||||
assert_eq!(twice, once, "fixed point");
|
||||
}
|
||||
|
||||
/// The standing template applied to directive-in-statements' verbatim
|
||||
/// capture (the round could not add these itself — this file was Lane B's
|
||||
/// during the wave): crafted (input, corrupted output) pairs the capture
|
||||
/// could plausibly produce if its extent scan slipped, each asserted
|
||||
/// rejected. An `` `else `` arm dropped, the arms swapped, and the
|
||||
/// `` `endif `` lost — every one is a divergence the safety net must see.
|
||||
#[test]
|
||||
fn a_corrupted_directive_capture_is_rejected() {
|
||||
// The `` `else `` arm dropped from the captured region.
|
||||
expect_divergence(
|
||||
"module m;\n assign x =\n`ifdef A\n a;\n`else\n b;\n`endif\nendmodule\n",
|
||||
"module m;\n assign x =\n`ifdef A\n a;\n`endif\nendmodule\n",
|
||||
);
|
||||
// The two arms swapped.
|
||||
expect_divergence(
|
||||
"module m;\n assign x =\n`ifdef A\n a;\n`else\n b;\n`endif\nendmodule\n",
|
||||
"module m;\n assign x =\n`ifdef A\n b;\n`else\n a;\n`endif\nendmodule\n",
|
||||
);
|
||||
// The `` `endif `` lost, leaking the region into the module tail.
|
||||
expect_divergence(
|
||||
"module m;\n assign x =\n`ifdef A\n a;\n`else\n b;\n`endif\nendmodule\n",
|
||||
"module m;\n assign x =\n`ifdef A\n a;\n`else\n b;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
/// QA (2026-08-29, Lane B): `trailing_ends_line` decides whether `end`'s
|
||||
/// trailing comments swallow a cuddled `else` by checking whether the
|
||||
/// *merged* trailing text starts with `//` (`is_line_comment` is a prefix
|
||||
/// test). A block comment followed by a line comment on the same trailing
|
||||
/// group — `end /* a */ // b` — merges into one string that starts with
|
||||
/// `/*`, so the check says "does not end in a line comment" and `else` still
|
||||
/// tries to cuddle, which does produce the merge this whole fix exists to
|
||||
/// prevent. The safety net catches it (the reparsed output has one big
|
||||
/// comment where the input had two), so the file is refused rather than
|
||||
/// corrupted — this pins that it stays a safe refusal, not a fix for the
|
||||
/// gap. If a later round teaches `trailing_ends_line` to look at the last
|
||||
/// merged comment instead of the first, this test should flip to a `.cases`
|
||||
/// entry the same way the parser handshake above is meant to.
|
||||
#[test]
|
||||
fn a_block_comment_merged_with_a_trailing_line_comment_before_else_is_still_refused() {
|
||||
expect_refusal(
|
||||
"module m;\n always_comb begin\n if (a) begin\n x = 1;\n end /* a */ // b\n else if (c) begin\n x = 2;\n end\n end\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The clocking wave's new verbatim capture: `default disable iff expr;`
|
||||
// (`docs/features/clocking-wave/README.md`).
|
||||
//
|
||||
// It is copied out of the source by span and re-indented, exactly like
|
||||
// `constraint` and a concurrent assertion, so the net must still see every
|
||||
// token inside it. Per CLAUDE.md hard invariant #4 these are the attack
|
||||
// pairs for that capture: **no normalization was added or widened for it**,
|
||||
// and each pair below is a real change inside the captured bytes that the
|
||||
// existing forgiveness could plausibly have masked (indentation, a moved
|
||||
// line break, a dropped comment) — asserted rejected.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_default_disable_iff_may_be_reindented() {
|
||||
let input = "module m;\n default disable iff !rst_ni;\nendmodule\n";
|
||||
let output = "module m;\n default disable iff !rst_ni;\nendmodule\n";
|
||||
verify_equivalence(input, output).expect("only per-line indentation changed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_default_disable_condition_is_rejected() {
|
||||
// The polarity of a disable condition is the difference between an
|
||||
// assertion that runs in reset and one that does not.
|
||||
expect_divergence(
|
||||
"module m;\n default disable iff !rst_ni;\nendmodule\n",
|
||||
"module m;\n default disable iff rst_ni;\nendmodule\n",
|
||||
);
|
||||
expect_divergence(
|
||||
"module m;\n default disable iff a || !b;\nendmodule\n",
|
||||
"module m;\n default disable iff a && !b;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_default_disable_operand_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n default disable iff disable_sva || !rst_ni;\nendmodule\n",
|
||||
"module m;\n default disable iff !rst_ni;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_default_disable_item_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n default disable iff !rst_ni;\n wire w;\nendmodule\n",
|
||||
"module m;\n wire w;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_inside_a_default_disable_may_not_be_dropped() {
|
||||
expect_divergence(
|
||||
"module m;\n default disable iff /* why */ !rst_ni;\nendmodule\n",
|
||||
"module m;\n default disable iff !rst_ni;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_default_disable_split_over_lines_may_not_lose_a_token() {
|
||||
// The capture spans several source lines, so the line-break normalization
|
||||
// is exactly what a masked corruption here would ride on.
|
||||
expect_divergence(
|
||||
"module m;\n default disable iff\n !rst_ni ||\n !en;\nendmodule\n",
|
||||
"module m;\n default disable iff !rst_ni || en;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_default_disable_carrying_a_dist_set_keeps_every_byte() {
|
||||
// A `;` inside the set does not end the item, so the whole set is in the
|
||||
// captured bytes — and a changed weight there must still be refused.
|
||||
let input = "module m;\n default disable iff x dist {1 := 1, 2 := 2};\nendmodule\n";
|
||||
let output = format_source(input, &Config::default()).expect("must format");
|
||||
assert!(output.contains("dist {1 := 1, 2 := 2}"), "the set's bytes changed:\n{output}");
|
||||
expect_divergence(
|
||||
input,
|
||||
"module m;\n default disable iff x dist {1 := 1, 2 := 9};\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Null items (`;` where an item belongs) — `docs/features/null-items/README.md`
|
||||
//
|
||||
// `verify.rs` was not widened for null items and needs no new forgiveness:
|
||||
// a `;` is an ordinary token and the net compares token streams. These pairs
|
||||
// are the standing attack tests anyway (CLAUDE.md invariant 4), one per way
|
||||
// the layout rule could plausibly go wrong.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_dropped_null_item_is_rejected() {
|
||||
// What the `empty-item` lint's fix does deliberately, the formatter must
|
||||
// never do silently — in either direction.
|
||||
expect_divergence(
|
||||
"module m;\n generate\n endgenerate;\nendmodule\n",
|
||||
"module m;\n generate\n endgenerate\nendmodule\n",
|
||||
);
|
||||
expect_divergence(
|
||||
"module m;\n wire a;\n ;;\nendmodule\n",
|
||||
"module m;\n wire a;\n ;\nendmodule\n",
|
||||
);
|
||||
// And a `;` invented where the source wrote none.
|
||||
expect_divergence(
|
||||
"module m;\n generate\n endgenerate\nendmodule\n",
|
||||
"module m;\n generate\n endgenerate;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_null_item_moved_across_a_comment_is_rejected() {
|
||||
// The glue prints a null item onto the previous item's line. A one-line
|
||||
// block comment is the only comment that can stand in that gap, and the
|
||||
// `;` must stay on the far side of it.
|
||||
expect_divergence(
|
||||
"module m;\n generate\n endgenerate /* b */ ;\nendmodule\n",
|
||||
"module m;\n generate\n endgenerate; /* b */\nendmodule\n",
|
||||
);
|
||||
expect_divergence(
|
||||
"module m;\n wire a;\n // why\n ;\nendmodule\n",
|
||||
"module m;\n wire a;\n ;\n // why\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_null_item_moved_into_a_procedural_block_is_rejected() {
|
||||
// An item-level `;` and a procedural null statement print identically, so
|
||||
// nothing but token order tells the net that one became the other.
|
||||
expect_divergence(
|
||||
"module m;\n initial begin\n x = 1;\n end\n ;\nendmodule\n",
|
||||
"module m;\n initial begin\n x = 1;\n ;\n end\nendmodule\n",
|
||||
);
|
||||
expect_divergence(
|
||||
"module m;\n generate\n ;\n endgenerate\nendmodule\n",
|
||||
"module m;\n generate\n endgenerate;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
// QA addition (2026-09-01): the item list is flat across `` `ifdef ``/``
|
||||
// `else ``/`` `endif `` — a null item inside one arm is a sibling of the
|
||||
// `Directive` items, not nested under them — so a corruption that carries a
|
||||
// null item from one arm to the other is a plain token-stream reorder around
|
||||
// a `Directive` token rather than around an ordinary item. Confirmed rejected
|
||||
// (checklist item 4's suggested gap; `verify.rs`'s comparison is positional
|
||||
// and directive-token-agnostic, so this was expected to hold, not a bug).
|
||||
#[test]
|
||||
fn a_null_item_moved_from_one_ifdef_arm_to_the_other_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n`ifdef A\n ;\n`else\n wire x;\n`endif\nendmodule\n",
|
||||
"module m;\n`ifdef A\n`else\n wire x;\n ;\n`endif\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Escaped identifiers (2026-09-02)
|
||||
// ----------------------------------------------------------------------
|
||||
//
|
||||
// An escaped identifier is ended by whitespace and by nothing else (IEEE
|
||||
// 1800-2017 §5.6.1), so dropping the space the formatter writes after one
|
||||
// does not just move layout around: the next character is swallowed into the
|
||||
// name and the token stream changes shape. These are the corruptions the
|
||||
// choke point in `format.rs` exists to prevent, asserted rejected — the net
|
||||
// is what stands behind it if a name emission is ever added without going
|
||||
// through `named`.
|
||||
|
||||
#[test]
|
||||
fn a_semicolon_glued_onto_an_escaped_name_is_rejected() {
|
||||
// The original bug: `wire \my-signal ;` printed as `wire \my-signal;`,
|
||||
// whose second token is the identifier `\my-signal;`.
|
||||
expect_divergence(
|
||||
"module m;\n wire \\my-signal ;\nendmodule\n",
|
||||
"module m;\n wire \\my-signal;\nendmodule\n",
|
||||
);
|
||||
// The same glue one scope down, where a class body's declaration is laid
|
||||
// out by a different path than a module item's.
|
||||
expect_divergence("class c;\n int \\fld ;\nendclass\n", "class c;\n int \\fld;\nendclass\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_connection_that_loses_the_space_before_its_paren_is_rejected() {
|
||||
// `.\my-port (x)` is three tokens; `.\my-port(x)` is two, the second one
|
||||
// being the identifier `\my-port(x)` — the whole connection eaten.
|
||||
expect_divergence(
|
||||
"module m;\n sub u0 (.\\my-port (x));\nendmodule\n",
|
||||
"module m;\n sub u0 (.\\my-port(x));\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_escaped_names_merged_into_one_are_rejected() {
|
||||
// `\a \b` are two identifiers; `\a\b` is one.
|
||||
expect_divergence(
|
||||
"module m;\n wire \\a \\b ;\nendmodule\n",
|
||||
"module m;\n wire \\a\\b ;\nendmodule\n",
|
||||
);
|
||||
// And the instance-name form of the same merge.
|
||||
expect_divergence(
|
||||
"module m;\n \\sub-mod \\u-0 ();\nendmodule\n",
|
||||
"module m;\n \\sub-mod\\u-0 ();\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escaped_label_glued_to_what_follows_it_is_rejected() {
|
||||
// A block label shares its line with the first statement, so the
|
||||
// terminator is the only thing between `\blk` and `x`.
|
||||
expect_divergence(
|
||||
"module m;\n initial begin : \\blk x = 1; end\nendmodule\n",
|
||||
"module m;\n initial begin : \\blkx = 1; end\nendmodule\n",
|
||||
);
|
||||
// An end label is terminated by the line break; a layout that folds the
|
||||
// next keyword onto its line without a space swallows the keyword.
|
||||
expect_divergence(
|
||||
"module m;\n initial begin : \\blk\n end : \\blk\nendmodule\n",
|
||||
"module m;\n initial begin : \\blk\n end : \\blkendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_terminating_space_itself_is_only_whitespace() {
|
||||
// The flip side: writing the space (or two, where the layout also writes
|
||||
// one) is a whitespace-only difference, which is what lets the formatter
|
||||
// add it at all.
|
||||
verify_equivalence(
|
||||
"module m;wire \\a ;assign \\a =\\b ;endmodule",
|
||||
"module m;\n wire \\a ;\n assign \\a = \\b ;\nendmodule\n",
|
||||
)
|
||||
.expect("only whitespace between the same tokens");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_space_dropped_before_a_scope_operator_is_rejected() {
|
||||
// `join_paths` writes `named(pkg) + "::" + named(item)`; if that first
|
||||
// `named` call were ever lost, `\a-pkg ::\b-item` (three tokens) would
|
||||
// print as `\a-pkg::\b-item` — one token, since `::` is not whitespace
|
||||
// and so does not terminate the escaped name on its own. QA-added
|
||||
// (2026-09-02): no existing pair attacked this specific position.
|
||||
expect_divergence(
|
||||
"package p;\n import \\a-pkg ::\\b-item ;\nendpackage\n",
|
||||
"package p;\n import \\a-pkg::\\b-item ;\nendpackage\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escaped_name_in_a_scoped_type_is_rejected_rather_than_corrupted() {
|
||||
// `\my-pkg ::\state-t` is joined into one string by `parse_scoped_name`,
|
||||
// so the formatter reprints it without the space it cannot know was
|
||||
// there. The net catches it: an error, never a corrupted file. See the
|
||||
// Handshakes section of docs/features/escaped-identifiers/README.md.
|
||||
let src = "module m;\n \\my-pkg ::\\state-t \\st ;\nendmodule\n";
|
||||
match format_source(src, &Config::default()) {
|
||||
Err(FormatError::Verification(_)) => {}
|
||||
other => panic!("expected the net to reject the scoped name, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escaped_identifiers_survive_a_real_format_run() {
|
||||
let src = "module \\my-mod (input logic \\a-in , output \\b-out );\n\
|
||||
wire \\my-signal ;\n\
|
||||
assign \\b-out = \\my-signal & \\a-in ;\n\
|
||||
sub \\u-0 (.\\p-in (\\my-signal ), .b(1'b0));\n\
|
||||
endmodule : \\my-mod\n";
|
||||
let out = format_source(src, &Config::default()).expect("escaped identifiers format");
|
||||
assert!(out.contains("wire \\my-signal ;"), "{out}");
|
||||
assert!(out.contains(".\\p-in (\\my-signal )"), "{out}");
|
||||
// A name that ends the line needs no space: the newline terminates it,
|
||||
// and the printer trims the trailing space it was given.
|
||||
assert!(out.ends_with("endmodule : \\my-mod\n"), "{out}");
|
||||
assert!(!out.contains(" \n"), "no trailing whitespace: {out}");
|
||||
}
|
||||
@@ -44,6 +44,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,
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
@@ -116,3 +116,33 @@ 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
|
||||
@@ -247,6 +247,18 @@ pub enum ItemKind {
|
||||
/// `docs/features/assertions/README.md` for why each one is verbatim.
|
||||
Verbatim(RawText),
|
||||
Defparam(Vec<(Expr, Expr)>),
|
||||
/// A **null item**: a lone `;` standing where an item belongs
|
||||
/// (IEEE 1800-2017 A.1.4 `package_or_generate_item_declaration ::= … | ;`
|
||||
/// and `class_item ::= … | ;`). Legal and meaningless in every item
|
||||
/// scope, and written constantly after `endgenerate`, after a generate
|
||||
/// block's `end` and after `endmodule`. The span is the `;` itself; the
|
||||
/// `empty-item` lint is what tells the user about it.
|
||||
///
|
||||
/// The `;` after `endfunction`/`endtask` is *not* one of these: it is
|
||||
/// consumed inside the declaration and recorded as
|
||||
/// [`FunctionDecl::end_semi`] / [`TaskDecl::end_semi`], which predates
|
||||
/// this variant.
|
||||
Empty,
|
||||
/// Source that could not be parsed as an item, kept verbatim.
|
||||
///
|
||||
/// Only error-tolerant parsing
|
||||
@@ -300,12 +312,13 @@ pub struct Module {
|
||||
}
|
||||
|
||||
impl Module {
|
||||
/// The keyword that closes this declaration: `endmodule` or `endinterface`.
|
||||
/// The keyword that closes this declaration: `endmodule`, `endinterface`
|
||||
/// or `endprogram`.
|
||||
pub fn end_kw(&self) -> &'static str {
|
||||
if self.kw == "interface" {
|
||||
"endinterface"
|
||||
} else {
|
||||
"endmodule"
|
||||
match self.kw.as_str() {
|
||||
"interface" => "endinterface",
|
||||
"program" => "endprogram",
|
||||
_ => "endmodule",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -532,6 +545,12 @@ pub struct EnumMember {
|
||||
pub name: String,
|
||||
/// Byte range of `name`.
|
||||
pub name_span: TextRange,
|
||||
/// The enum name range of IEEE 1800 §6.19 — `Name[N]` or `Name[hi:lo]`,
|
||||
/// which declares a run of sequentially-valued members. One dimension is
|
||||
/// all the LRM allows; it is kept as an ordinary [`Dim`] so the existing
|
||||
/// dimension parser and printer serve it, and it is printed back tight
|
||||
/// against the name because it is part of the name, not a layout choice.
|
||||
pub range: Vec<Dim>,
|
||||
pub value: Option<Expr>,
|
||||
/// True when a `,` followed this element in the source; see
|
||||
/// [`NonAnsiPort::comma`].
|
||||
@@ -553,6 +572,12 @@ pub struct StructType {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StructMember {
|
||||
pub meta: Meta,
|
||||
/// `rand` / `randc` written before the member's type. The LRM allows the
|
||||
/// randomization qualifiers only on a class property, but vendor tools
|
||||
/// accept them on a plain struct member and real code uses them
|
||||
/// (`spi_host/dv/env/spi_host_env_pkg.sv:64`); lucisv models no
|
||||
/// randomization semantics, so the words are simply carried and printed.
|
||||
pub qualifiers: Vec<String>,
|
||||
pub ty: DataType,
|
||||
pub declarators: Vec<Declarator>,
|
||||
/// Code extent of the member, its `;` included.
|
||||
@@ -617,13 +642,15 @@ pub struct ContAssign {
|
||||
pub assigns: Vec<AssignPair>,
|
||||
}
|
||||
|
||||
/// The `( strength0 , strength1 )` pair of a continuous assignment. The two
|
||||
/// strengths are stored in the order the source wrote them — the language
|
||||
/// The `( strength0 , strength1 )` of a continuous assignment or a gate. The
|
||||
/// two strengths are stored in the order the source wrote them — the language
|
||||
/// allows either order and lucisv is not a legality checker.
|
||||
#[derive(Debug)]
|
||||
pub struct DriveStrength {
|
||||
pub first: String,
|
||||
pub second: String,
|
||||
/// `None` for the single-strength spelling `pullup (weak1) p (x);`
|
||||
/// (IEEE 1800 §28.3's `pullup_strength`), which only a pull gate takes.
|
||||
pub second: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -665,6 +692,9 @@ pub struct SensItem {
|
||||
pub sep: Option<SensSep>,
|
||||
pub edge: Option<String>,
|
||||
pub expr: Expr,
|
||||
/// The gating condition of `@(posedge clk iff enable)` — IEEE 1800
|
||||
/// §9.4.2's optional `iff expression` on one event expression term.
|
||||
pub iff: Option<Expr>,
|
||||
}
|
||||
|
||||
/// How two event-list items were separated in the source. Both spellings are
|
||||
@@ -789,7 +819,14 @@ pub struct BindDirective {
|
||||
pub struct GateInstantiation {
|
||||
/// `and`, `or`, `not`, ...
|
||||
pub gate: String,
|
||||
pub delay: Option<Expr>,
|
||||
/// The `(weak1)` in `pullup (weak1) p (x);` (IEEE 1800 §28.3), or the
|
||||
/// `(strong0, strong1)` pair every driving gate also accepts.
|
||||
pub strength: Option<DriveStrength>,
|
||||
/// The delay written after `#`: empty when there is none, one element for
|
||||
/// every spelling a net or a continuous assignment also accepts, and two
|
||||
/// or three for the `(rise, fall[, turn-off])` list that only a gate
|
||||
/// takes (IEEE 1800 §28.14, `top_earlgrey/ip/ast/rtl/aon_osc.sv:41`).
|
||||
pub delay: Vec<Expr>,
|
||||
pub instances: Vec<GateInstance>,
|
||||
}
|
||||
|
||||
@@ -993,7 +1030,18 @@ pub enum ClockingItemKind {
|
||||
Default { input: Option<String>, output: Option<String> },
|
||||
/// `input #2 a, b;`, `output negedge c;`, `inout d;`. `skew` is the delay
|
||||
/// or edge as written (`#2`, `negedge`), or `None` when omitted.
|
||||
Signals { dir: String, skew: Option<String>, names: Vec<Name> },
|
||||
Signals { dir: String, skew: Option<String>, signals: Vec<ClockingSignal> },
|
||||
}
|
||||
|
||||
/// One `signal [= expression]` of a clocking direction group — IEEE 1800
|
||||
/// §14.4's `clocking_decl_assign`. The expression binds the clocking signal to
|
||||
/// something other than the same-named signal in the enclosing scope:
|
||||
/// `output tms = _tms_internal;`.
|
||||
#[derive(Debug)]
|
||||
pub struct ClockingSignal {
|
||||
pub name: Name,
|
||||
/// `None` for the plain `input tdo;` spelling.
|
||||
pub value: Option<Expr>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -1193,6 +1241,11 @@ pub enum StmtKind {
|
||||
/// declarations (IEEE 1800 §13.4.2) — the statement twin of
|
||||
/// [`ItemKind::Import`].
|
||||
Import(Vec<ImportPath>),
|
||||
/// `typedef enum bit {WRITE, READ} rdwr_e;` written inside a
|
||||
/// function/task body or a `begin` block, scoping the type to that block
|
||||
/// (IEEE 1800 §6.18) — the statement twin of [`ItemKind::Typedef`], with
|
||||
/// the same payload and the same layout.
|
||||
Typedef(Typedef),
|
||||
/// `name : stmt` — a statement label (IEEE 1800 §9.3.5).
|
||||
///
|
||||
/// `begin`/`fork` keep their label inside their own node, because the
|
||||
@@ -1414,11 +1467,18 @@ pub enum ExprKind {
|
||||
},
|
||||
/// `ty'(expr)` cast. The casting type is an expression because it may be
|
||||
/// a name (`int`, `my_t`), a package-scoped name
|
||||
/// (`lc_ctrl_pkg::TxWidth'(x)`), a size (`4'(x)`) or a parenthesized
|
||||
/// constant expression (`(DepthW + 3)'(1'b1)`) — IEEE 1800 §6.24.1.
|
||||
/// (`lc_ctrl_pkg::TxWidth'(x)`), a size (`4'(x)`), a parenthesized
|
||||
/// constant expression (`(DepthW + 3)'(1'b1)`) or a system function call
|
||||
/// (`$bits(x)'(y)`) — IEEE 1800 §6.24.1.
|
||||
Cast {
|
||||
ty: Box<Expr>,
|
||||
expr: Box<Expr>,
|
||||
/// True for the `ty'{...}` spelling (IEEE 1800 §10.9.1), where the
|
||||
/// argument is an assignment pattern. The pattern brings its own
|
||||
/// `'{` and `}`, so such a cast prints no brackets of its own —
|
||||
/// which is also why the two spellings must stay distinguishable:
|
||||
/// `ty'('{a: 1})` is a different token stream from `ty'{a: 1}`.
|
||||
pattern: bool,
|
||||
},
|
||||
/// `'{...}` assignment pattern.
|
||||
AssignPattern(Vec<PatternItem>),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1030,6 +1030,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");
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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";
|
||||
|
||||
+1880
-153
File diff suppressed because it is too large.
Load diff
@@ -19,6 +19,7 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::parser::PARSE_STACK_SIZE;
|
||||
use vlog_parser::{parse_source, parse_source_tolerant, ParseDiagnostic};
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -248,6 +249,83 @@ fn tolerant_parse_equals_strict_parse_on_valid_sources() {
|
||||
println!("{valid} valid sources agreed with the strict parser, {invalid} reported errors");
|
||||
}
|
||||
|
||||
/// The out-of-block constraint cascade, pinned as a regression
|
||||
/// (`docs/features/out-of-class-constraints/README.md`).
|
||||
///
|
||||
/// Before the fix, `constraint C::name { ... }` failed one token into the
|
||||
/// header (`expected `{` (found "::")`); the recovery loop then resynchronized
|
||||
/// inside the constraint body, and every out-of-block item after it produced
|
||||
/// its own diagnostics. On the real corpus that turned one construct into 322
|
||||
/// diagnostics in `cip_base_vseq.sv` and 274 in `hmac_base_vseq.sv` — a buffer
|
||||
/// an editor cannot show usefully. This fixture is that shape in miniature:
|
||||
/// with the fix it must be silent, not merely quieter.
|
||||
#[test]
|
||||
fn out_of_block_constraints_do_not_cascade() {
|
||||
let src = "\
|
||||
class my_seq;
|
||||
rand int num_trans;
|
||||
rand int delay;
|
||||
extern constraint num_trans_c;
|
||||
extern constraint delay_c;
|
||||
extern function void configure();
|
||||
endclass : my_seq
|
||||
|
||||
constraint my_seq::num_trans_c {
|
||||
num_trans inside {[1:20]};
|
||||
solve num_trans before delay;
|
||||
}
|
||||
|
||||
constraint my_seq::delay_c {
|
||||
soft delay dist {0 :/ 5, [1:10] :/ 5};
|
||||
}
|
||||
|
||||
function void my_seq::configure();
|
||||
num_trans = 1;
|
||||
endfunction : my_seq
|
||||
";
|
||||
let (_, diags) = parse_source_tolerant(src);
|
||||
assert!(diags.is_empty(), "out-of-block constraints still report: {diags:?}");
|
||||
assert!(parse_source(src).is_ok(), "strict parse must agree with tolerant");
|
||||
}
|
||||
|
||||
/// The mop-up round's nine shapes, all in one buffer: the strict parser
|
||||
/// accepts them, so the tolerant parser must report nothing at all. A gap
|
||||
/// that still failed here would be worse than a plain refusal — an editor
|
||||
/// would show the diagnostic on every keystroke.
|
||||
///
|
||||
/// See `docs/features/testbench-mopup/README.md`.
|
||||
#[test]
|
||||
fn the_mopup_shapes_report_nothing_in_tolerant_mode() {
|
||||
let src = "\
|
||||
package p;
|
||||
typedef enum logic [1:0] {ReqPeriResetIdx[0:1], ReqMainPwrResetIdx} reset_idx_e;
|
||||
typedef struct {
|
||||
rand bit cpol;
|
||||
randc bit [3:0] csnlead;
|
||||
} cfg_t;
|
||||
endpackage
|
||||
|
||||
module tb;
|
||||
virtual spi_if.tb tb_sif = sif.tb;
|
||||
buf #(ast_bhv_pkg::AON_EN_RDLY, 0) b0 (en_osc_re_buf, (vcore_pok_h_i && aon_en_i));
|
||||
assign periph_data_mux = $bits(periph_data_mux)'({periph_to_mio_i, 1'b0});
|
||||
|
||||
bind prim_packer_fifo : dut.u_core.u_fifo fifo_if #(.P(1)) u_fifo_exc_if (.clk_i);
|
||||
|
||||
initial begin
|
||||
typedef enum bit {WRITE = 1'b1, READ = 1'b0} rdwr_e;
|
||||
typedef bit data_result[];
|
||||
foreach (cfg.mem_bkdr_util_h[, bank]) begin
|
||||
q.push_back(mem_item_t'{addr, mask});
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let (_, diags) = parse_source_tolerant(src);
|
||||
assert!(diags.is_empty(), "a mop-up shape still reports: {diags:?}");
|
||||
assert!(parse_source(src).is_ok(), "strict parse must agree with tolerant");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Guarantee 2: diagnostics and error nodes stay inside the file
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -466,7 +544,7 @@ fn the_depth_limit_still_fires_and_is_recovered_from() {
|
||||
")".repeat(400)
|
||||
);
|
||||
let (file, diags) = std::thread::Builder::new()
|
||||
.stack_size(16 * 1024 * 1024)
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(move || {
|
||||
let (f, d) = parse_source_tolerant(&src);
|
||||
(format!("{:?}", f.items.iter().map(kind_name).collect::<Vec<_>>()), d)
|
||||
@@ -495,7 +573,7 @@ fn recovery_does_not_reset_the_nesting_budget() {
|
||||
"end\n".repeat(outer),
|
||||
);
|
||||
let diags = std::thread::Builder::new()
|
||||
.stack_size(16 * 1024 * 1024)
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(move || parse_source_tolerant(&src).1)
|
||||
.expect("spawn parser thread")
|
||||
.join()
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
//! The null item — a lone `;` where an item belongs (IEEE 1800-2017 A.1.4
|
||||
//! `package_or_generate_item_declaration ::= … | ;` and `class_item ::= … | ;`).
|
||||
//! See `docs/features/null-items/README.md`.
|
||||
//!
|
||||
//! Every item list in the parser reaches `parse_item_kind` through
|
||||
//! `item_or_recover`, so one branch is meant to cover all eight scopes. That
|
||||
//! claim is checked here by parsing one source per scope rather than by
|
||||
//! reading the parser.
|
||||
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::{parse_source, parse_source_tolerant};
|
||||
|
||||
/// Parses `src` strictly and returns the tree; panics with the parse error.
|
||||
fn tree(src: &str) -> SourceFile {
|
||||
parse_source(src).unwrap_or_else(|e| panic!("{src}\n=> {e}"))
|
||||
}
|
||||
|
||||
/// Every null item in `file`, as its source slice — which must be `";"`.
|
||||
fn null_item_slices(src: &str, file: &SourceFile) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
walk(&file.items, &mut |item| {
|
||||
if matches!(item.kind, ItemKind::Empty) {
|
||||
out.push(src[item.span.as_range()].to_string());
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn walk(items: &[Item], f: &mut dyn FnMut(&Item)) {
|
||||
for item in items {
|
||||
f(item);
|
||||
match &item.kind {
|
||||
ItemKind::Module(m) => walk(&m.items, f),
|
||||
ItemKind::Package { items, .. } => walk(items, f),
|
||||
ItemKind::Class(c) => walk(&c.items, f),
|
||||
ItemKind::GenerateRegion { items, .. } => walk(items, f),
|
||||
ItemKind::GenFor(g) => walk(&g.body.items, f),
|
||||
ItemKind::GenIf(g) => {
|
||||
walk(&g.then.items, f);
|
||||
let mut els = g.els.as_deref();
|
||||
while let Some(branch) = els {
|
||||
match branch {
|
||||
GenElse::If(_, nested) => {
|
||||
walk(&nested.then.items, f);
|
||||
els = nested.els.as_deref();
|
||||
}
|
||||
GenElse::Block(block) => {
|
||||
walk(&block.items, f);
|
||||
els = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::GenCase(g) => {
|
||||
for case_item in &g.items {
|
||||
walk(&case_item.body.items, f);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One `;` per scope, and every one of them is an `ItemKind::Empty` whose span
|
||||
/// is exactly the semicolon.
|
||||
#[test]
|
||||
fn a_null_item_parses_in_every_item_scope() {
|
||||
let scopes = [
|
||||
("file scope", "module m;\nendmodule;\n"),
|
||||
("module body", "module m;\n wire a;\n ;\nendmodule\n"),
|
||||
("interface body", "interface ifc;\n logic a;\n ;\nendinterface\n"),
|
||||
("program body", "program p;\n ;\nendprogram\n"),
|
||||
("package body", "package p;\n localparam int W = 1;\n ;\nendpackage\n"),
|
||||
("class body", "class c;\n int x;\n ;\nendclass\n"),
|
||||
("generate region", "module m;\n generate\n ;\n endgenerate\nendmodule\n"),
|
||||
(
|
||||
"generate-for body",
|
||||
"module m;\n for (genvar i = 0; i < 2; i++) begin : g\n ;\n end\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"generate-if body",
|
||||
"module m;\n if (A) begin : g\n ;\n end else begin : h\n ;\n end\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"generate-case body",
|
||||
"module m;\n case (A)\n 1: begin : g\n ;\n end\n endcase\nendmodule\n",
|
||||
),
|
||||
];
|
||||
for (what, src) in scopes {
|
||||
let file = tree(src);
|
||||
let found = null_item_slices(src, &file);
|
||||
assert!(!found.is_empty(), "{what}: no null item parsed from\n{src}");
|
||||
assert!(found.iter().all(|s| s == ";"), "{what}: span is not the `;`: {found:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The shape the owner reported, and its neighbours: a `;` after a closing
|
||||
/// keyword rather than on a line of its own.
|
||||
#[test]
|
||||
fn a_semicolon_after_a_closing_keyword_is_a_null_item() {
|
||||
let sources = [
|
||||
"module m;\n generate\n endgenerate;\nendmodule\n",
|
||||
"module m;\n generate\n if (A) begin : g\n wire x;\n end;\n endgenerate\nendmodule\n",
|
||||
"module m;\n if (A) begin : g\n wire x;\n end;\nendmodule\n",
|
||||
"module m;\nendmodule;\n",
|
||||
];
|
||||
for src in sources {
|
||||
let file = tree(src);
|
||||
assert_eq!(null_item_slices(src, &file), vec![";"], "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `;;` is two of them, not one.
|
||||
#[test]
|
||||
fn repeated_semicolons_are_one_null_item_each() {
|
||||
let src = "module m;\n ;;;\nendmodule\n";
|
||||
let file = tree(src);
|
||||
assert_eq!(null_item_slices(src, &file).len(), 3);
|
||||
}
|
||||
|
||||
/// Comments ride the ordinary `Meta`, like any other item's.
|
||||
#[test]
|
||||
fn comments_around_a_null_item_are_kept() {
|
||||
let src = "module m;\n // lead\n ; // trail\nendmodule\n";
|
||||
let file = tree(src);
|
||||
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
|
||||
let item = m.items.iter().find(|i| matches!(i.kind, ItemKind::Empty)).expect("a null item");
|
||||
assert_eq!(item.meta.leading.iter().map(|c| c.text.as_str()).collect::<Vec<_>>(), ["// lead"]);
|
||||
assert_eq!(item.meta.trailing.as_ref().map(|c| c.text.as_str()), Some("// trail"));
|
||||
}
|
||||
|
||||
/// Tolerant mode is silent about a null item: it is a successful parse, not a
|
||||
/// recovery, so an editor shows the `empty-item` lint and no parse error.
|
||||
#[test]
|
||||
fn tolerant_parsing_reports_no_diagnostic() {
|
||||
let sources = [
|
||||
"module m;\n generate\n endgenerate;\nendmodule\n",
|
||||
"module m;\n ;;\nendmodule\n",
|
||||
"package p;\n ;\nendpackage\n",
|
||||
"class c;\n ;\nendclass\n",
|
||||
"module m;\nendmodule;\n",
|
||||
];
|
||||
for src in sources {
|
||||
let (file, diagnostics) = parse_source_tolerant(src);
|
||||
assert!(diagnostics.is_empty(), "{src}=> {diagnostics:?}");
|
||||
assert!(!null_item_slices(src, &file).is_empty(), "{src}");
|
||||
assert!(
|
||||
null_item_slices(src, &file).iter().all(|s| s == ";"),
|
||||
"an error leaf, not a null item: {src}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The `;` after `endfunction`/`endtask` stays where it always was — on
|
||||
/// `FunctionDecl::end_semi` / `TaskDecl::end_semi`, consumed inside the
|
||||
/// declaration — so the two mechanisms do not both claim it.
|
||||
#[test]
|
||||
fn endfunction_and_endtask_keep_their_own_semicolon_flag() {
|
||||
let src = "module m;\n function int f();\n return 1;\n endfunction;\n task t();\n endtask;\nendmodule\n";
|
||||
let file = tree(src);
|
||||
assert!(null_item_slices(src, &file).is_empty(), "the `;` must not become a null item");
|
||||
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
|
||||
let mut seen = 0;
|
||||
for item in &m.items {
|
||||
match &item.kind {
|
||||
ItemKind::Function(f) => {
|
||||
assert!(f.end_semi);
|
||||
seen += 1;
|
||||
}
|
||||
ItemKind::Task(t) => {
|
||||
assert!(t.end_semi);
|
||||
seen += 1;
|
||||
}
|
||||
_ => panic!("unexpected item"),
|
||||
}
|
||||
}
|
||||
assert_eq!(seen, 2);
|
||||
}
|
||||
@@ -71,6 +71,16 @@ const SOURCES: &[&str] = &[
|
||||
"virtual class base #(parameter int W = 8) extends pkg::top #(.A(1), b) implements i, j;\n rand bit [W-1:0] v;\n local int n;\n virtual my_if h;\n pure virtual function void f();\n extern task t(int x);\nendclass : base\n",
|
||||
"class c;\n port_t #(bit [3:0]) p;\n constraint x {\n a == 0; // why\n } // after\n covergroup g;\n coverpoint a;\n endgroup : g\n function new(string name);\n super.new(name);\n x = db#(virtual bus_if)::get(this);\n endfunction : new\nendclass\n",
|
||||
"typedef class fwd;\npackage p;\n class inner extends fwd;\n endclass\nendpackage\nfunction void inner::configure(int x);\nendfunction\n",
|
||||
// Out-of-block constraints: the verbatim leaf reached from item position,
|
||||
// at file scope and inside a package, with a scope chain and a stray `;`.
|
||||
"class c;\n extern constraint x;\nendclass\nconstraint c::x {\n a == 0; // why\n}; // after\npackage p;\n constraint q::inner::deep_c { b < 4; }\nendpackage\n",
|
||||
// The mop-up round: a block-scoped typedef, enum name ranges, a cast over
|
||||
// an assignment pattern and one over a system function call, a gate delay
|
||||
// list, a modport-qualified virtual interface, a `rand` struct member, a
|
||||
// skipped `foreach` dimension, and a hierarchical `bind` instance path.
|
||||
"package p;\n typedef enum logic [1:0] {A[0:1], B, C[4] = 5} e_t;\n typedef struct {\n rand bit cpol;\n randc int n;\n } cfg_t;\nendpackage\n",
|
||||
"module m;\n virtual spi_if.tb tb_sif = sif.tb;\n buf #(RDLY, 0) b0 (o, a);\n and #(1, 2, 3) g (o, a, b);\n assign y = $bits(x)'({a, b});\n assign z = item_t'{addr: a, data: d};\n initial begin\n typedef enum bit {W = 1'b1} rdwr_e;\n typedef bit dyn_t[];\n foreach (h[, bank]) x = 1;\n foreach (h[i, , k]) y = 2;\n end\nendmodule\n",
|
||||
"bind prim_packer_fifo : dut.u_core.u_fifo fifo_if #(.P(1)) u (.clk_i);\nbind foo : a.b, plain bar u (.x);\n",
|
||||
// Dynamic types: queues, dynamic and associative arrays, `$` indexes,
|
||||
// named call arguments, `case ... inside`, a bare event control.
|
||||
"class c;\n string q[$] = {};\n rand int offset[];\n logic hits[*];\n string lut[string];\n item_t #(A, B) rq[NumInp-1:0][$:8];\n function void f(string ops[$], output int outs[]);\n q[$].label = ops[$-1];\n offset = new[n];\n endfunction\nendclass\n",
|
||||
@@ -82,6 +92,13 @@ const SOURCES: &[&str] = &[
|
||||
"class c;\n task t();\n if (!req.randomize() with {\n a == 1;\n b dist { 0 :/ 1 };\n }) $fatal(1, \"no\");\n endtask : t;\nendclass\n",
|
||||
// DPI imports and exports, plus package re-exports.
|
||||
"package p;\n import \"DPI-C\"\n function void env_final();\n import \"DPI-C\" context function chandle mk(int unsigned k, bit [7:0] v);\n import \"DPI-C\" function chandle get;\n import \"DPI-C\" pure c_name = task tick(input int n);\n export \"DPI-C\" function f;\n export \"DPI-C\" ex_name = task t;\n export q::*;\n export r::a, s::b;\n export *::*;\nendpackage\n",
|
||||
// The clocking wave: clocking signals bound to an expression, the
|
||||
// verbatim `default disable iff`, an `iff` on an event-control term, a
|
||||
// bare event control over an indexed hierarchical path, a gate's single
|
||||
// and paired drive strengths, and a `program` block.
|
||||
"interface i;\n clocking cb @(negedge tck);\n default output #1ns;\n output tms = _tms_internal, tdi = _tdi[0]; // bound\n input tdo;\n endclocking\n modport host_mp(clocking cb, output trst_n);\nendinterface\n",
|
||||
"module m;\n default disable iff disable_sva || !rst_ni;\n default clocking @(posedge clk_i); endclocking\n always @(posedge clk iff en or negedge rst_n) x <= 1;\n pullup (weak1) pd (x);\n pulldown (supply0, supply1) pd2 (y);\n initial forever @cfg.cfgs[\"a\"].vif.cb z <= 1;\nendmodule\n",
|
||||
"program p #(parameter int W = 1) (input logic csb);\n logic [7:0] cmd;\n initial cmd = 8'h0;\nendprogram : p\n",
|
||||
];
|
||||
|
||||
/// A token or a comment, in source order.
|
||||
@@ -463,30 +480,7 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
|
||||
ItemKind::Directive(raw) | ItemKind::MacroItem(MacroCall { raw, .. }) => {
|
||||
assert_inside(src, "raw text", raw.span, here);
|
||||
}
|
||||
ItemKind::Typedef(t) => {
|
||||
check_name(src, "typedef name", &t.name, t.name_span, here);
|
||||
if let TypedefKind::Enum(e) = &t.kind {
|
||||
for d in &e.directives {
|
||||
assert_inside(src, "list directive", d.raw.span, here);
|
||||
}
|
||||
for member in &e.members {
|
||||
assert_inside(src, "enum member", member.span, here);
|
||||
check_name(
|
||||
src,
|
||||
"enum member name",
|
||||
&member.name,
|
||||
member.name_span,
|
||||
member.span,
|
||||
);
|
||||
}
|
||||
}
|
||||
if let TypedefKind::Struct(s) = &t.kind {
|
||||
for member in &s.members {
|
||||
assert_inside(src, "struct member", member.span, here);
|
||||
check_declarators(src, &member.declarators, member.span);
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::Typedef(t) => check_typedef(src, t, here),
|
||||
ItemKind::ParamDecl(p) => check_declarators(src, &p.declarators, here),
|
||||
ItemKind::DataDecl(d) => check_declarators(src, &d.declarators, here),
|
||||
ItemKind::PortDecl(p) => check_declarators(src, &p.declarators, here),
|
||||
@@ -512,10 +506,22 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
|
||||
despace(&b.target),
|
||||
"the bind target span does not slice back to its name"
|
||||
);
|
||||
check_names(src, "bind instance name", &b.instances, here);
|
||||
// An instance may itself be a hierarchical path, glued the same
|
||||
// way, so it gets the same modulo-whitespace comparison.
|
||||
for i in &b.instances {
|
||||
assert_inside(src, "bind instance name", i.span, here);
|
||||
assert_eq!(
|
||||
despace(slice(src, i.span)),
|
||||
despace(&i.text),
|
||||
"the bind instance span does not slice back to its name"
|
||||
);
|
||||
}
|
||||
check_instantiation(src, &b.inst, here);
|
||||
}
|
||||
ItemKind::GateInstantiation(g) => {
|
||||
for d in &g.delay {
|
||||
check_expr(src, d, here);
|
||||
}
|
||||
for i in &g.instances {
|
||||
assert_inside(src, "gate instance", i.span, here);
|
||||
check_opt_name(src, "gate instance name", i.name.as_ref(), i.name_span, i.span);
|
||||
@@ -589,14 +595,18 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
|
||||
check_opt_name(src, "endclocking label", c.end_label.as_ref(), c.end_label_span, here);
|
||||
for item in &c.items {
|
||||
assert_inside(src, "clocking item", item.span, here);
|
||||
if let ClockingItemKind::Signals { names, .. } = &item.kind {
|
||||
check_names(src, "clocking signal", names, item.span);
|
||||
if let ClockingItemKind::Signals { signals, .. } = &item.kind {
|
||||
for s in signals {
|
||||
check_name(src, "clocking signal", &s.name.text, s.name.span, item.span);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// A `constraint`/`covergroup` block: one verbatim leaf whose span is
|
||||
// the item's own, checked above.
|
||||
ItemKind::Verbatim(_) => {}
|
||||
// the item's own, checked above. A null item is a leaf too — its span
|
||||
// is the `;`, which the caller has already asserted sits inside its
|
||||
// parent.
|
||||
ItemKind::Verbatim(_) | ItemKind::Empty => {}
|
||||
ItemKind::Function(f) => {
|
||||
check_name(src, "function name", &f.name, f.name_span, here);
|
||||
check_dpi_import(src, f.dpi.as_ref(), here);
|
||||
@@ -712,6 +722,30 @@ fn check_gen_block(src: &str, b: &GenBlock, parent: TextRange) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared by the item form and the block-scoped statement form, which carry
|
||||
/// the same [`Typedef`] payload.
|
||||
fn check_typedef(src: &str, t: &Typedef, here: TextRange) {
|
||||
check_name(src, "typedef name", &t.name, t.name_span, here);
|
||||
if let TypedefKind::Enum(e) = &t.kind {
|
||||
for d in &e.directives {
|
||||
assert_inside(src, "list directive", d.raw.span, here);
|
||||
}
|
||||
for member in &e.members {
|
||||
assert_inside(src, "enum member", member.span, here);
|
||||
check_name(src, "enum member name", &member.name, member.name_span, member.span);
|
||||
for dim in &member.range {
|
||||
assert_inside(src, "enum member range", dim.span, member.span);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let TypedefKind::Struct(s) = &t.kind {
|
||||
for member in &s.members {
|
||||
assert_inside(src, "struct member", member.span, here);
|
||||
check_declarators(src, &member.declarators, member.span);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn check_declarators(src: &str, declarators: &[Declarator], parent: TextRange) {
|
||||
for d in declarators {
|
||||
assert_inside(src, "declarator", d.span, parent);
|
||||
@@ -792,6 +826,7 @@ fn check_stmt(src: &str, stmt: &Stmt, parent: TextRange) {
|
||||
}
|
||||
StmtKind::ExprStmt(e) | StmtKind::EventTrigger(e) => check_expr(src, e, here),
|
||||
StmtKind::VarDecl(d) => check_declarators(src, &d.declarators, here),
|
||||
StmtKind::Typedef(t) => check_typedef(src, t, here),
|
||||
StmtKind::ParamDecl(p) => check_declarators(src, &p.declarators, here),
|
||||
StmtKind::PortDecl(p) => check_declarators(src, &p.declarators, here),
|
||||
StmtKind::Return(e) => check_opt_expr(src, e.as_ref(), here),
|
||||
@@ -842,7 +877,7 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) {
|
||||
ExprKind::Unary { expr, .. }
|
||||
| ExprKind::Postfix { expr, .. }
|
||||
| ExprKind::Paren { inner: expr, .. } => check_expr(src, expr, here),
|
||||
ExprKind::Cast { ty, expr } => {
|
||||
ExprKind::Cast { ty, expr, .. } => {
|
||||
check_expr(src, ty, here);
|
||||
check_expr(src, expr, here);
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ use std::path::Path;
|
||||
use vlog_parser::ast::{AnsiPort, ItemKind, Module, ParamPort, PortList};
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::{Semantics, SymbolKind, WorkspaceIndex};
|
||||
use vlog_semantic::{Semantics, WorkspaceIndex};
|
||||
|
||||
use crate::ports::{find_module, visible_in};
|
||||
|
||||
@@ -114,7 +114,7 @@ impl Default for Layout {
|
||||
/// completing.
|
||||
pub fn module_definition<'i>(index: &'i WorkspaceIndex, module: &str) -> Result<&'i Path, String> {
|
||||
let defs: Vec<_> =
|
||||
index.units(module).iter().filter(|def| def.kind == SymbolKind::Module).collect();
|
||||
index.units(module).iter().filter(|def| def.kind.is_instantiable()).collect();
|
||||
let [def] = defs.as_slice() else {
|
||||
return Err(match defs.len() {
|
||||
0 => format!("lucisv indexes no module named `{module}`."),
|
||||
@@ -468,7 +468,7 @@ pub fn module_names<'i>(index: &'i WorkspaceIndex, query: &str) -> Vec<&'i str>
|
||||
let mut out: Vec<&str> = index
|
||||
.workspace_symbols(query)
|
||||
.into_iter()
|
||||
.filter(|hit| hit.container.is_none() && hit.def.kind == SymbolKind::Module)
|
||||
.filter(|hit| hit.container.is_none() && hit.def.kind.is_instantiable())
|
||||
.map(|hit| hit.name)
|
||||
.collect();
|
||||
out.dedup();
|
||||
@@ -513,6 +513,26 @@ endmodule
|
||||
.expect("a plan")
|
||||
}
|
||||
|
||||
/// An interface is instantiated exactly as a module is, and since
|
||||
/// 2026-09-01 it carries `SymbolKind::Interface`
|
||||
/// (`docs/features/interface-semantics/README.md`) — so both unit lookups
|
||||
/// here ask `is_instantiable()` and answer what they always did.
|
||||
#[test]
|
||||
fn an_interface_is_a_unit_this_module_will_instantiate() {
|
||||
let index = index_of(&[
|
||||
("/rtl/bus_if.sv", "interface bus_if (input logic clk);\nendinterface\n"),
|
||||
("/rtl/sub.sv", SUB),
|
||||
]);
|
||||
assert_eq!(
|
||||
module_definition(&index, "bus_if").map(|p| p.display().to_string()),
|
||||
Ok("/rtl/bus_if.sv".to_string())
|
||||
);
|
||||
assert_eq!(module_names(&index, ""), ["bus_if", "sub"]);
|
||||
let plan = plan("interface bus_if (input logic clk);\nendinterface\n", "bus_if");
|
||||
let names: Vec<&str> = plan.ports.iter().map(|p| p.name.as_str()).collect();
|
||||
assert_eq!(names, ["clk"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plan_reads_the_parameters_and_ports_in_declaration_order() {
|
||||
let plan = plan(SUB, "sub");
|
||||
|
||||
@@ -40,10 +40,12 @@ pub use instantiate::{
|
||||
PlanPort, Site,
|
||||
};
|
||||
pub use ports::{
|
||||
add_port, may_have_port_action, port_actions, propagate_ports, remove_port, ModuleRef,
|
||||
PortAction,
|
||||
add_port, enclosing_module, may_have_port_action, port_action_modules, port_actions,
|
||||
propagate_ports, remove_port, ModuleRef, PortAction,
|
||||
};
|
||||
pub use rename::{
|
||||
contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, RenameTarget,
|
||||
};
|
||||
pub use rename::{prepare_rename, rename, RenameTarget};
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
|
||||
@@ -155,29 +155,70 @@ pub fn port_actions(files: &[(PathBuf, String)], file: &Path, offset: u32) -> Ve
|
||||
/// microseconds. It never says `false` where a refactoring would have
|
||||
/// succeeded: every one of the three starts by locating exactly one of these
|
||||
/// three constructs.
|
||||
///
|
||||
/// Exactly [`port_action_modules`] asked for emptiness — one walk, two
|
||||
/// readers, so the gate and the fan-out cannot come to disagree about which
|
||||
/// positions carry an action.
|
||||
pub fn may_have_port_action(text: &str, offset: u32) -> bool {
|
||||
!port_action_modules(text, offset).is_empty()
|
||||
}
|
||||
|
||||
/// Every module name a port refactoring at this position could act on: the
|
||||
/// module an instantiation under the cursor names, or the module whose port
|
||||
/// the cursor sits on.
|
||||
///
|
||||
/// [`may_have_port_action`]'s own walk, saying *which* module it found rather
|
||||
/// than only that it found one — which is what lets a server hand
|
||||
/// [`port_actions`] the handful of files that module fans out to instead of
|
||||
/// the whole workspace. Empty for exactly the positions the gate refuses.
|
||||
pub fn port_action_modules(text: &str, offset: u32) -> Vec<String> {
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
let mut instantiations = Vec::new();
|
||||
collect_instantiations(&tree.items, &mut instantiations);
|
||||
let at_instantiation = instantiations.iter().any(|instantiation| {
|
||||
instantiation.module_span.contains(offset)
|
||||
|| instantiation.instances.iter().any(|instance| instance.span.contains(offset))
|
||||
});
|
||||
if at_instantiation {
|
||||
return true;
|
||||
let named: Vec<String> = instantiations
|
||||
.iter()
|
||||
.filter(|instantiation| {
|
||||
instantiation.module_span.contains(offset)
|
||||
|| instantiation.instances.iter().any(|instance| instance.span.contains(offset))
|
||||
})
|
||||
.map(|instantiation| instantiation.module.clone())
|
||||
.collect();
|
||||
if !named.is_empty() {
|
||||
return named;
|
||||
}
|
||||
let mut module = None;
|
||||
module_at(&tree.items, offset, &mut module);
|
||||
let Some((module, _)) = module.and_then(|name| find_module(&tree, &name)) else {
|
||||
return false;
|
||||
let Some((name, (module, _))) =
|
||||
module.and_then(|name| Some((name.clone(), find_module(&tree, &name)?)))
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
if declared_ports(module).iter().any(|port| port.span.contains(offset)) {
|
||||
return true;
|
||||
return vec![name];
|
||||
}
|
||||
module.items.iter().any(|item| match &item.kind {
|
||||
let on_body_declaration = module.items.iter().any(|item| match &item.kind {
|
||||
ItemKind::PortDecl(decl) => decl.declarators.iter().any(|d| d.span.contains(offset)),
|
||||
_ => false,
|
||||
})
|
||||
});
|
||||
match on_body_declaration {
|
||||
true => vec![name],
|
||||
false => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The module whose declaration covers this offset — what
|
||||
/// `ModuleRef::At { file, offset }` will resolve to.
|
||||
///
|
||||
/// The fan-out question for the *command* path, which takes a position
|
||||
/// anywhere in a module rather than on one of its ports: `lucisv.addPort` with
|
||||
/// a `Position` names the module the cursor is inside, and a server working
|
||||
/// out which files that refactoring needs has to name it the same way
|
||||
/// `locate_module` will.
|
||||
pub fn enclosing_module(text: &str, offset: u32) -> Option<String> {
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
let mut module = None;
|
||||
module_at(&tree.items, offset, &mut module);
|
||||
module
|
||||
}
|
||||
|
||||
/// "updates 3 instantiations" / "updates 1 instantiation" / "no instantiation
|
||||
@@ -354,7 +395,7 @@ fn locate_module(scope: &mut Scope, module: ModuleRef<'_>) -> Result<ModuleSite,
|
||||
.index()
|
||||
.units(&name)
|
||||
.iter()
|
||||
.filter(|def| def.kind == SymbolKind::Module)
|
||||
.filter(|def| def.kind.is_instantiable())
|
||||
.cloned()
|
||||
.collect();
|
||||
let [def] = defs.as_slice() else {
|
||||
@@ -1724,6 +1765,7 @@ pub(crate) fn visible_in(semantics: &Semantics, offset: u32, name: &str) -> bool
|
||||
| SymbolKind::Var
|
||||
| SymbolKind::Port
|
||||
| SymbolKind::Param
|
||||
| SymbolKind::LocalParam
|
||||
| SymbolKind::Genvar
|
||||
| SymbolKind::TfArg
|
||||
)
|
||||
@@ -1742,6 +1784,33 @@ mod tests {
|
||||
text.find(needle).expect("needle present") as u32
|
||||
}
|
||||
|
||||
/// An interface is `SymbolKind::Interface` since 2026-09-01
|
||||
/// (`docs/features/interface-semantics/README.md`), and `locate_module`
|
||||
/// asks `is_instantiable()` rather than `kind == Module` — so adding a
|
||||
/// port to an interface, and rewriting every instantiation of it, works
|
||||
/// exactly as it did when an interface was indexed as a module.
|
||||
#[test]
|
||||
fn a_port_refactoring_finds_an_interface_the_way_it_finds_a_module() {
|
||||
let files = vec![
|
||||
(
|
||||
std::path::PathBuf::from("/rtl/bus_if.sv"),
|
||||
"interface bus_if (input logic clk);\nendinterface\n".to_string(),
|
||||
),
|
||||
(
|
||||
std::path::PathBuf::from("/rtl/top.sv"),
|
||||
"module top;\n logic c;\n bus_if u_bus (.clk(c));\nendmodule\n".to_string(),
|
||||
),
|
||||
];
|
||||
let edit = crate::add_port(&files, crate::ModuleRef::Name("bus_if"), "input logic rst_n")
|
||||
.expect("an interface's port list is refactored like a module's");
|
||||
let paths: Vec<String> = edit.edits.iter().map(|(p, _)| p.display().to_string()).collect();
|
||||
assert!(paths.contains(&"/rtl/bus_if.sv".to_string()), "{paths:?}");
|
||||
assert!(
|
||||
paths.contains(&"/rtl/top.sv".to_string()),
|
||||
"the instantiation is rewritten too: {paths:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_declaration_must_be_exactly_one_directed_port() {
|
||||
assert_eq!(parse_port_decl("input logic [7:0] cfg").map(|p| p.name), Ok("cfg".into()));
|
||||
|
||||
@@ -15,7 +15,7 @@ use vlog_parser::token::{is_keyword, TokenKind};
|
||||
use vlog_parser::{parse_source_tolerant, tokenize, LineIndex};
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, Def, ExternalResolutions, ExternalTarget, FileId, ReferenceId,
|
||||
Resolution, Semantics, SymbolId, WorkspaceIndex,
|
||||
Resolution, Semantics, Symbol, SymbolId, WorkspaceIndex,
|
||||
};
|
||||
|
||||
use crate::{check, RefactorEdit, TextEdit};
|
||||
@@ -44,6 +44,93 @@ pub fn prepare_rename(
|
||||
Ok(RenameTarget { range: target.cursor, name: target.name })
|
||||
}
|
||||
|
||||
/// [`prepare_rename`] answered from one buffer's finished analysis and the
|
||||
/// workspace index, reading no file at all.
|
||||
///
|
||||
/// `textDocument/prepareRename` fires the instant the rename key is pressed,
|
||||
/// and its whole answer — the identifier's range and its placeholder — is in
|
||||
/// the buffer already. Answering it through [`prepare_rename`] meant reading,
|
||||
/// parsing and indexing every in-scope file first: 2.5–3.0 s on OpenTitan, on
|
||||
/// a keypress that has committed to nothing, with a single-threaded server
|
||||
/// answering nothing else meanwhile.
|
||||
///
|
||||
/// Every refusal [`prepare_rename`] can reach without the *declaring file's*
|
||||
/// own text is reached here too, in the same words. The ones that need that
|
||||
/// text are deferred to [`rename`], which reads it — LSP allows an optimistic
|
||||
/// `prepareRename` whose rename then refuses, and never the other way round.
|
||||
/// The refusal-by-refusal table is in `docs/features/refactor-rename/README.md`.
|
||||
pub fn prepare_rename_here(
|
||||
semantics: &Semantics,
|
||||
external: &ExternalResolutions,
|
||||
index: &WorkspaceIndex,
|
||||
offset: u32,
|
||||
) -> Result<RenameTarget, String> {
|
||||
let found =
|
||||
semantics.reference_id_at(offset).and_then(|id| Some((id, semantics.reference(id)?)));
|
||||
let Some((id, reference)) = found else {
|
||||
// The cursor is on a declaration, or on nothing at all.
|
||||
let here = semantics.symbol_at(offset).and_then(|symbol| semantics.symbol(symbol));
|
||||
let Some(declaration) = here else { return Err(NOTHING_HERE.to_string()) };
|
||||
renameable_here(semantics, index, declaration)?;
|
||||
return Ok(RenameTarget { range: declaration.name_span, name: declaration.name.clone() });
|
||||
};
|
||||
let cursor = reference.name_span;
|
||||
match &reference.resolution {
|
||||
Resolution::Resolved(symbol) => {
|
||||
let Some(declaration) = semantics.symbol(*symbol) else {
|
||||
return Err(NOTHING_HERE.to_string());
|
||||
};
|
||||
renameable_here(semantics, index, declaration)?;
|
||||
Ok(RenameTarget { range: cursor, name: declaration.name.clone() })
|
||||
}
|
||||
Resolution::NotFound => Err(unresolved(&reference.name)),
|
||||
Resolution::InheritedCandidate { base, .. } => Err(from_base(&reference.name, base)),
|
||||
// The overlay is `resolve_external` against this very index, which is
|
||||
// the same call `Scope::declaration_across_files` makes — so which
|
||||
// declaration the use names, and whether several do, is settled here.
|
||||
// What is *not* settled is anything about that declaration's own file.
|
||||
Resolution::ExternalCandidate { .. } => match external.get(id) {
|
||||
Some(ExternalTarget::Resolved(_)) => {
|
||||
Ok(RenameTarget { range: cursor, name: reference.name.clone() })
|
||||
}
|
||||
Some(ExternalTarget::Ambiguous(_)) => Err(ambiguous(&reference.name)),
|
||||
_ => Err(declared_outside(&reference.name)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The two refusals [`Scope::declaration`] applies to a declaration written in
|
||||
/// the file the request named, asked of that buffer and the index.
|
||||
fn renameable_here(
|
||||
semantics: &Semantics,
|
||||
index: &WorkspaceIndex,
|
||||
declaration: &Symbol,
|
||||
) -> Result<(), String> {
|
||||
if declaration.name_span.is_empty() {
|
||||
return Err(unspelled(&declaration.name));
|
||||
}
|
||||
if declaration.scope == semantics.file_scope() && index.units(&declaration.name).len() > 1 {
|
||||
return Err(ambiguous(&declaration.name));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The identifier a rename at `offset` would act on, read from one buffer's
|
||||
/// analysis alone: the name, with no opinion on whether it may be renamed.
|
||||
///
|
||||
/// What the server needs to ask the index for the rename's fan-out. Every
|
||||
/// refusal stays with [`rename`], which is the call that sees the files — a
|
||||
/// second opinion here could only disagree with it.
|
||||
pub fn rename_name_at(semantics: &Semantics, offset: u32) -> Option<String> {
|
||||
match semantics.reference_id_at(offset).and_then(|id| semantics.reference(id)) {
|
||||
Some(reference) => Some(reference.name.clone()),
|
||||
None => semantics
|
||||
.symbol_at(offset)
|
||||
.and_then(|symbol| semantics.symbol(symbol))
|
||||
.map(|declaration| declaration.name.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rename the symbol at `offset` in `file` to `new_name`, across every file in
|
||||
/// `files`.
|
||||
///
|
||||
@@ -230,12 +317,10 @@ impl<'a> Scope<'a> {
|
||||
let (name, cursor) = (reference.name.clone(), reference.name_span);
|
||||
match &reference.resolution {
|
||||
Resolution::Resolved(symbol) => Found::Here(*symbol, cursor),
|
||||
Resolution::NotFound => return Err(format!(
|
||||
"`{name}` is not resolved to any declaration, so lucisv cannot tell what renaming it would mean."
|
||||
)),
|
||||
Resolution::InheritedCandidate { base, .. } => return Err(format!(
|
||||
"`{name}` could only come from the base class `{base}`, which lucisv does not resolve; renaming it would be a guess."
|
||||
)),
|
||||
Resolution::NotFound => return Err(unresolved(&name)),
|
||||
Resolution::InheritedCandidate { base, .. } => {
|
||||
return Err(from_base(&name, base))
|
||||
}
|
||||
Resolution::ExternalCandidate { .. } => {
|
||||
Found::Elsewhere(name, cursor, analysis.external.get(id).cloned())
|
||||
}
|
||||
@@ -282,9 +367,7 @@ impl<'a> Scope<'a> {
|
||||
)
|
||||
};
|
||||
if name_span.is_empty() {
|
||||
return Err(format!(
|
||||
"lucisv cannot find where `{name}` is spelled in its declaration, so it will not edit it."
|
||||
));
|
||||
return Err(unspelled(&name));
|
||||
}
|
||||
if at_file_scope && self.index.units(&name).len() > 1 {
|
||||
return Err(ambiguous(&name));
|
||||
@@ -302,11 +385,7 @@ impl<'a> Scope<'a> {
|
||||
let def = match target {
|
||||
Some(ExternalTarget::Resolved(def)) => def,
|
||||
Some(ExternalTarget::Ambiguous(_)) => return Err(ambiguous(name)),
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"`{name}` is declared outside the files lucisv indexes, so a rename here would only be half a rename."
|
||||
))
|
||||
}
|
||||
_ => return Err(declared_outside(name)),
|
||||
};
|
||||
let Some(file) = self.index.path(def.file).and_then(|p| self.index_of(p)) else {
|
||||
return Err(format!("`{name}`'s declaring file is not in scope."));
|
||||
@@ -631,12 +710,41 @@ pub(crate) struct ArgumentSite {
|
||||
|
||||
const NOTHING_HERE: &str = "there is no symbol to rename at this position.";
|
||||
|
||||
// The refusal sentences, each written once. Two callers reach four of them
|
||||
// now: the whole-workspace `Scope::locate` and the buffer-and-index
|
||||
// `prepare_rename_here`, which must refuse in exactly the same words or the
|
||||
// user gets two different explanations for one situation.
|
||||
|
||||
fn ambiguous(name: &str) -> String {
|
||||
format!(
|
||||
"`{name}` is declared in more than one indexed file; lucisv will not guess which declaration this rename means."
|
||||
)
|
||||
}
|
||||
|
||||
fn unresolved(name: &str) -> String {
|
||||
format!(
|
||||
"`{name}` is not resolved to any declaration, so lucisv cannot tell what renaming it would mean."
|
||||
)
|
||||
}
|
||||
|
||||
fn from_base(name: &str, base: &str) -> String {
|
||||
format!(
|
||||
"`{name}` could only come from the base class `{base}`, which lucisv does not resolve; renaming it would be a guess."
|
||||
)
|
||||
}
|
||||
|
||||
fn declared_outside(name: &str) -> String {
|
||||
format!(
|
||||
"`{name}` is declared outside the files lucisv indexes, so a rename here would only be half a rename."
|
||||
)
|
||||
}
|
||||
|
||||
fn unspelled(name: &str) -> String {
|
||||
format!(
|
||||
"lucisv cannot find where `{name}` is spelled in its declaration, so it will not edit it."
|
||||
)
|
||||
}
|
||||
|
||||
/// Why an identifier spelling the name is not a reference lucisv can edit,
|
||||
/// read off its neighbours in the token stream. Naming the actual construct
|
||||
/// is the difference between a warning the user can act on and one they have
|
||||
@@ -679,7 +787,12 @@ pub(crate) fn display(path: &Path) -> String {
|
||||
/// True when `needle` occurs in `haystack` as a whole identifier — the test
|
||||
/// macro text and the verification pass's file filter get, where there is no
|
||||
/// token stream to consult (or where the token is opaque).
|
||||
pub(crate) fn contains_word(haystack: &str, needle: &str) -> bool {
|
||||
///
|
||||
/// Public because the server asks the same question of a `` `define`` body it
|
||||
/// reads out of the index, to put that macro's file in a rename's fan-out:
|
||||
/// [`Scope::define_sites`] decides with this function, so the fan-out must
|
||||
/// decide with it too or the two disagree about which files carry a warning.
|
||||
pub fn contains_word(haystack: &str, needle: &str) -> bool {
|
||||
if needle.is_empty() {
|
||||
return false;
|
||||
}
|
||||
@@ -719,6 +832,185 @@ mod tests {
|
||||
assert!(check_new_name("a ").is_err(), "trailing space");
|
||||
}
|
||||
|
||||
/// A `(path, text)` list from `(name, text)` pairs, the shape both entry
|
||||
/// points take.
|
||||
fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
|
||||
files.iter().map(|(name, text)| (PathBuf::from(name), (*text).to_string())).collect()
|
||||
}
|
||||
|
||||
/// [`prepare_rename_here`] and [`prepare_rename`] asked the same question
|
||||
/// at **every byte** of one file, with the parity contract asserted at
|
||||
/// each: a refusal is never invented and never reworded, and an answer is
|
||||
/// never a different answer. The one asymmetry the contract allows is the
|
||||
/// deferral — the cheap path saying yes where the whole-workspace path
|
||||
/// refuses for a reason only the declaring file's own text carries.
|
||||
///
|
||||
/// Returns how many offsets were deferrals, so a test can assert it found
|
||||
/// the case it was built to find.
|
||||
fn parity_at_every_offset(files: &[(&str, &str)], file: &str) -> usize {
|
||||
let sources = workspace(files);
|
||||
let path = PathBuf::from(file);
|
||||
let text = sources
|
||||
.iter()
|
||||
.find(|(p, _)| *p == path)
|
||||
.map(|(_, text)| text.clone())
|
||||
.expect("the file is in the workspace");
|
||||
|
||||
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let semantics = analyze(&parse_source_tolerant(&text).0, &text);
|
||||
let external = resolve_external(&semantics, &index);
|
||||
|
||||
let mut deferred = 0usize;
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let whole = prepare_rename(&sources, &path, offset);
|
||||
let here = prepare_rename_here(&semantics, &external, &index, offset);
|
||||
match (&whole, &here) {
|
||||
(Ok(whole), Ok(here)) => {
|
||||
assert_eq!(whole, here, "at byte {offset} of {file}");
|
||||
}
|
||||
(Err(whole), Err(here)) => {
|
||||
assert_eq!(whole, here, "refusal reworded at byte {offset} of {file}");
|
||||
}
|
||||
// Allowed, and only in this direction: the buffer said yes,
|
||||
// the workspace refused for something only the declaring
|
||||
// file's own analysis knows. `rename` still delivers it.
|
||||
(Err(_), Ok(_)) => deferred += 1,
|
||||
(Ok(whole), Err(here)) => panic!(
|
||||
"a refusal was invented at byte {offset} of {file}: the workspace answered {whole:?}, the buffer refused with {here:?}"
|
||||
),
|
||||
}
|
||||
}
|
||||
deferred
|
||||
}
|
||||
|
||||
const SUB: &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 TOP: &str = "module top;\n logic c, d;\n sub #(.W(2)) u_sub (.clk(c), .q(d));\n sub u_two (.clk(c), .q(d));\nendmodule\n";
|
||||
const PKG: &str =
|
||||
"package cfg_pkg;\n parameter int DEPTH = 4;\n typedef logic [1:0] mode_t;\nendpackage\n";
|
||||
const USER: &str = "module user;\n import cfg_pkg::*;\n cfg_pkg::mode_t m;\n localparam int D = cfg_pkg::DEPTH;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn the_buffer_answers_a_prepare_exactly_as_the_workspace_does() {
|
||||
let files = [("sub.sv", SUB), ("top.sv", TOP)];
|
||||
parity_at_every_offset(&files, "top.sv");
|
||||
parity_at_every_offset(&files, "sub.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prepare_over_packages_and_qualified_names_keeps_parity() {
|
||||
let files = [("pkg.sv", PKG), ("user.sv", USER)];
|
||||
parity_at_every_offset(&files, "user.sv");
|
||||
parity_at_every_offset(&files, "pkg.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prepare_keeps_parity_where_the_workspace_declares_a_name_twice() {
|
||||
// Two modules called `sub`, so every route to that declaration must
|
||||
// refuse — from the use in `top.sv`, and from either declaration.
|
||||
let files =
|
||||
[("a.sv", SUB), ("b.sv", SUB), ("top.sv", TOP), ("pkg.sv", PKG), ("user.sv", USER)];
|
||||
parity_at_every_offset(&files, "top.sv");
|
||||
parity_at_every_offset(&files, "a.sv");
|
||||
|
||||
let sources = workspace(&files);
|
||||
let path = PathBuf::from("top.sv");
|
||||
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let semantics = analyze(&parse_source_tolerant(TOP).0, TOP);
|
||||
let external = resolve_external(&semantics, &index);
|
||||
let at = TOP.find("sub #").expect("the instantiation") as u32;
|
||||
let refusal =
|
||||
prepare_rename_here(&semantics, &external, &index, at).expect_err("declared twice");
|
||||
assert_eq!(refusal, ambiguous("sub"), "the index-shaped refusal, in its own words");
|
||||
assert_eq!(refusal, prepare_rename(&sources, &path, at).expect_err("declared twice"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prepare_keeps_parity_where_nothing_resolves() {
|
||||
// `missing` is instantiated and declared nowhere; `base_t` comes from
|
||||
// a base class this workspace does not hold.
|
||||
const STRAY: &str = "class kid extends absent_base;\n function void go();\n inherited_thing = 1;\n endfunction\nendclass\nmodule holder;\n missing u_missing (.a(b));\nendmodule\n";
|
||||
parity_at_every_offset(&[("stray.sv", STRAY), ("sub.sv", SUB)], "stray.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prepare_keeps_parity_through_generate_blocks_and_macros() {
|
||||
const GEN: &str = "`define BUMP(x) x + 1\n`define WIDTH 8\nmodule gen_holder;\n genvar i;\n generate\n for (i = 0; i < 2; i++) begin : lane\n sub u_lane (.clk(1'b0), .q());\n end\n endgenerate\n wire [`WIDTH-1:0] w;\n assign w = `BUMP(sub);\nendmodule\n";
|
||||
parity_at_every_offset(&[("gen.sv", GEN), ("sub.sv", SUB)], "gen.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prepare_on_an_unparseable_buffer_keeps_parity() {
|
||||
const BROKEN: &str =
|
||||
"module broken (input logic clk;\n wire a\n assign a = clk\nendmodule\n";
|
||||
parity_at_every_offset(&[("broken.sv", BROKEN), ("sub.sv", SUB)], "broken.sv");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// QA, 2026-08-28: prepare parity fuzz beyond the dev's six buffers
|
||||
// ------------------------------------------------------------------
|
||||
//
|
||||
// Same contract, hostile shapes the dev's suite didn't try: a valid head
|
||||
// followed by garbage (as opposed to garbage throughout), CRLF line
|
||||
// endings (byte offsets a naive line-based tool would get wrong), and
|
||||
// multi-byte UTF-8 text sitting before the identifiers being probed.
|
||||
|
||||
#[test]
|
||||
fn a_prepare_keeps_parity_with_a_valid_head_and_an_unparseable_tail() {
|
||||
const HEAD_THEN_GARBAGE: &str = "module ok_head;\n wire a;\n assign a = 1'b0;\nendmodule\n\n)}]224$@#(garbage tail not even lexable as verilog{{{\n";
|
||||
parity_at_every_offset(&[("tail.sv", HEAD_THEN_GARBAGE), ("sub.sv", SUB)], "tail.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prepare_keeps_parity_over_crlf_line_endings() {
|
||||
const CRLF: &str = "module crlf_mod;\r\n wire local_net;\r\n sub u_inst (.clk(1'b0), .q());\r\n assign local_net = 1'b0;\r\nendmodule\r\n";
|
||||
parity_at_every_offset(&[("crlf.sv", CRLF), ("sub.sv", SUB)], "crlf.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prepare_keeps_parity_with_multi_byte_text_before_the_identifiers() {
|
||||
const MULTI_BYTE: &str = "// \u{00e9}\u{00e9} \u{1f389} a comment with accents and an emoji before anything else\nmodule multi_byte_mod;\n // \u{4e2d}\u{6587}\u{6ce8}\u{91ca} more non-ascii, mid-file\n wire local_net;\n sub u_inst (.clk(1'b0), .q());\n assign local_net = 1'b0;\nendmodule\n";
|
||||
parity_at_every_offset(&[("multibyte.sv", MULTI_BYTE), ("sub.sv", SUB)], "multibyte.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prepare_keeps_parity_over_a_macro_heavy_buffer() {
|
||||
const MACRO_HEAVY: &str = "`define WIDTH 8\n`define BUMP(x) x = x + 1\n`ifdef NEVER_DEFINED\n `define shadow_sub sub\n`else\n module macro_heavy;\n wire [`WIDTH-1:0] w;\n sub u_real (.clk(1'b0), .q());\n initial `BUMP(w);\n endmodule\n`endif\n";
|
||||
parity_at_every_offset(&[("macro.sv", MACRO_HEAVY), ("sub.sv", SUB)], "macro.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cheap_prepare_reads_nothing_but_the_buffer_and_the_index() {
|
||||
// The declaring file is *not* in the index, so nothing about it can be
|
||||
// consulted — and the answer is still the refusal that says so.
|
||||
let sources = workspace(&[("top.sv", TOP)]);
|
||||
let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
let semantics = analyze(&parse_source_tolerant(TOP).0, TOP);
|
||||
let external = resolve_external(&semantics, &index);
|
||||
let at = TOP.find("sub #").expect("the instantiation") as u32;
|
||||
assert_eq!(
|
||||
prepare_rename_here(&semantics, &external, &index, at).expect_err("not indexed"),
|
||||
declared_outside("sub")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_name_a_fan_out_is_built_from_is_the_name_the_engine_acts_on() {
|
||||
let files = [("sub.sv", SUB), ("top.sv", TOP), ("pkg.sv", PKG), ("user.sv", USER)];
|
||||
let sources = workspace(&files);
|
||||
for (path, text) in &sources {
|
||||
let semantics = analyze(&parse_source_tolerant(text).0, text);
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let Ok(target) = prepare_rename(&sources, path, offset) else { continue };
|
||||
assert_eq!(
|
||||
rename_name_at(&semantics, offset).as_deref(),
|
||||
Some(target.name.as_str()),
|
||||
"at byte {offset} of {}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_word_search_ignores_substrings() {
|
||||
assert!(contains_word("a + WIDTH - 1", "WIDTH"));
|
||||
|
||||
@@ -642,6 +642,41 @@ fn the_cheap_pre_check_says_yes_exactly_where_an_action_could_be_offered() {
|
||||
assert!(may_have_port_action(non_ansi, at(non_ansi, "input a") + 6), "a non-ANSI declaration");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pre_check_names_the_module_whose_files_the_action_will_need() {
|
||||
use vlog_refactor::{may_have_port_action, port_action_modules};
|
||||
let text = "module sub (\n input a,\n input b\n);\n wire c;\n assign c = a;\n other u1 (.x(c));\nendmodule\n";
|
||||
// On a port of `sub`, the module whose signature would change; on the
|
||||
// instantiation, the module instantiated — never the one it is written in.
|
||||
assert_eq!(port_action_modules(text, at(text, "input b") + 6), ["sub"]);
|
||||
assert_eq!(port_action_modules(text, at(text, "u1")), ["other"]);
|
||||
assert_eq!(port_action_modules(text, at(text, "other")), ["other"]);
|
||||
assert!(port_action_modules(text, at(text, "assign")).is_empty());
|
||||
|
||||
let non_ansi = "module sub (a);\n input a;\nendmodule\n";
|
||||
assert_eq!(port_action_modules(non_ansi, at(non_ansi, "input a") + 6), ["sub"]);
|
||||
|
||||
// The gate is this walk asked for emptiness, at every byte of the file.
|
||||
for offset in 0..text.len() as u32 {
|
||||
assert_eq!(
|
||||
may_have_port_action(text, offset),
|
||||
!port_action_modules(text, offset).is_empty(),
|
||||
"at byte {offset}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_enclosing_module_is_the_one_a_position_would_add_a_port_to() {
|
||||
use vlog_refactor::enclosing_module;
|
||||
let text = "module sub (input a);\n wire c;\nendmodule\n\nmodule top;\n sub u1 (.a(c));\nendmodule\n";
|
||||
// A position `lucisv.addPort` would take: inside the module, nowhere near
|
||||
// a port element — which is exactly where `port_action_modules` is empty.
|
||||
assert_eq!(enclosing_module(text, at(text, "wire c")).as_deref(), Some("sub"));
|
||||
assert_eq!(enclosing_module(text, at(text, "sub u1")).as_deref(), Some("top"));
|
||||
assert_eq!(enclosing_module(text, at(text, "\n\nmodule top") + 1), None, "between modules");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// what the preprocessor owns
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@@ -357,20 +357,31 @@ fn an_interface_renames_through_a_direction_less_ansi_port() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_the_modport_half_of_a_port_type_is_refused() {
|
||||
// QA attack (`docs/features/ansi-first-port/README.md`): `bus_if.mp bus`
|
||||
// glues the modport onto the type name, but only the interface half is
|
||||
// bound (`ItemKind::Modport` is a leaf in `vlog_semantic`, `bind.rs:364`).
|
||||
// A rename request on the `mp` half must find nothing to rename — never
|
||||
// silently rename the interface instead, and never corrupt the modport
|
||||
// spelling.
|
||||
let iface = "interface bus_if;\n modport mp (input a);\nendinterface\n";
|
||||
let top = "module top (bus_if.mp bus);\nendmodule\n";
|
||||
fn renaming_the_modport_half_of_a_port_type_renames_the_modport() {
|
||||
// Flipped at lead review of interface-semantics (2026-09-01). Until then
|
||||
// `bus_if.mp bus` bound only the interface half and a rename request on
|
||||
// `mp` had nothing to rename (`ItemKind::Modport` was a leaf); now a
|
||||
// modport is a symbol and the `mp` half of a glued type name is a
|
||||
// reference to it, so renaming from the type position rewrites the
|
||||
// declaration and every type-position use — and nothing else: the
|
||||
// interface's own name is untouched, as is every other spelling of `mp`.
|
||||
let iface = "interface bus_if;\n logic a;\n modport mp (input a);\n modport other (output a);\nendinterface\n";
|
||||
let top = "module top (bus_if.mp bus, bus_if.other o);\n logic mp;\nendmodule\n";
|
||||
let files = workspace(&[("bus_if.sv", iface), ("top.sv", top)]);
|
||||
let offset = at(top, "bus_if.", "mp");
|
||||
let err = rename(&files, &path("top.sv"), offset, "mp2")
|
||||
.expect_err("the modport half of the type name is not a bound symbol");
|
||||
assert!(!err.is_empty());
|
||||
let edit = rename(&files, &path("top.sv"), offset, "mp2").expect("a modport renames");
|
||||
let iface_after = apply(iface, &edit, &path("bus_if.sv"));
|
||||
let top_after = apply(top, &edit, &path("top.sv"));
|
||||
assert!(iface_after.contains("modport mp2 (input a);"), "{iface_after}");
|
||||
assert!(iface_after.contains("modport other (output a);"), "{iface_after}");
|
||||
assert!(top_after.contains("bus_if.mp2 bus"), "{top_after}");
|
||||
assert!(top_after.contains("bus_if.other o"), "the other modport is untouched: {top_after}");
|
||||
assert!(top_after.contains("logic mp;"), "an unrelated `mp` is untouched: {top_after}");
|
||||
assert!(
|
||||
iface_after.contains("interface bus_if;"),
|
||||
"the interface keeps its name: {iface_after}"
|
||||
);
|
||||
assert_eq!(edit.edit_count(), 2, "declaration + the one type-position use: {edit:?}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -815,7 +826,13 @@ fn a_mismatched_end_label_is_left_alone_and_says_which_construct_it_is() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hierarchical_tail_is_left_alone_and_named_as_such() {
|
||||
fn a_hierarchical_tail_that_resolves_is_renamed_with_its_declaration() {
|
||||
// Since class-member-access round 2 (2026-09-01) an instance head's tail
|
||||
// resolves through the instance's module, so `u_sub.sig` *is* sub's
|
||||
// `wire sig` and a rename must rewrite it — leaving it would hand back a
|
||||
// design that no longer elaborates. Before that round this test pinned
|
||||
// the opposite as an honest limitation ("the tail is not resolved, so
|
||||
// not edited"); the limitation is gone and the truth flipped with it.
|
||||
let text = concat!(
|
||||
"module sub;\n wire sig;\nendmodule\n",
|
||||
"module top;\n",
|
||||
@@ -828,10 +845,41 @@ fn a_hierarchical_tail_is_left_alone_and_named_as_such() {
|
||||
let edit = rename(&files, &path("m.sv"), at(text, "wire", "sig"), "signal").expect("renames");
|
||||
let after = apply(text, &edit, &path("m.sv"));
|
||||
assert!(after.contains("wire signal;"), "{after}");
|
||||
assert!(after.contains("u_sub.sig;"), "the tail is not resolved, so not edited: {after}");
|
||||
assert!(after.contains("u_sub.signal;"), "the tail resolves, so it is edited: {after}");
|
||||
assert!(
|
||||
edit.warnings.iter().any(|w| w.contains("hierarchical or member tail")),
|
||||
"{:?}",
|
||||
!edit.warnings.iter().any(|w| w.contains("hierarchical or member tail")),
|
||||
"a resolved tail is an edit, not a warning: {:?}",
|
||||
edit.warnings
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hierarchical_tail_that_cannot_resolve_is_left_alone_and_named_as_such() {
|
||||
// The module behind the instance is nowhere in the workspace, so the tail
|
||||
// records nothing and the rename can only say so: the old-spelled tail is
|
||||
// left as written and the warning names it.
|
||||
let text = concat!(
|
||||
"module top;\n",
|
||||
" wire sig;\n",
|
||||
" unknown_mod u_x ();\n",
|
||||
" wire w;\n",
|
||||
" assign w = u_x.sig;\n",
|
||||
"endmodule\n"
|
||||
);
|
||||
let files = workspace(&[("m.sv", text)]);
|
||||
let edit = rename(&files, &path("m.sv"), at(text, "wire", "sig"), "signal").expect("renames");
|
||||
let after = apply(text, &edit, &path("m.sv"));
|
||||
assert!(after.contains("wire signal;"), "{after}");
|
||||
assert!(after.contains("u_x.sig;"), "an unresolved tail is not edited: {after}");
|
||||
// Known gap, filed as `docs/topo.md` §2.9-20 (lead, 2026-09-01): before
|
||||
// class-member-access such a tail had no reference at all and the stray
|
||||
// scan (`stray_reason`) warned about it; now it carries an
|
||||
// `ExternalCandidate` the workspace cannot answer, which the engine
|
||||
// neither edits nor warns about. The edit behavior is right; the missing
|
||||
// heads-up is the same class as §2.9-18's lost macro-argument warnings.
|
||||
assert!(
|
||||
!edit.warnings.iter().any(|w| w.contains("u_x")),
|
||||
"premise of the filed gap — no warning names the tail today: {:?}",
|
||||
edit.warnings
|
||||
);
|
||||
}
|
||||
|
||||
@@ -44,6 +44,35 @@ pub(crate) enum Target {
|
||||
UnitMember(String),
|
||||
/// The `.port` of a connection to the named module.
|
||||
Port(String),
|
||||
/// A name that may only be looked up in the scope it is **written in**,
|
||||
/// never outward: a modport's port list (IEEE 1800 §25.5 — every name it
|
||||
/// governs is declared in that very interface) and a clocking block's
|
||||
/// signal list (§14.4). Walking outward here would be a wrong answer
|
||||
/// waiting to happen: `modport mp (input other_if)` must not find a
|
||||
/// file-scope `other_if` because the interface itself declares no such
|
||||
/// signal. A miss records **nothing**.
|
||||
InScope,
|
||||
/// The `mp` of a glued interface type name — `bus_if.mp bus`,
|
||||
/// `virtual bus_if.mp vif` (IEEE 1800 §25.4/§25.9). `unit` is the
|
||||
/// interface half, which [`Binder::bind_data_type`] binds beside this as
|
||||
/// an ordinary [`Target::Type`]; the tail is a *member* of it, looked up
|
||||
/// in the interface's own scope when this file declares it and handed to
|
||||
/// the workspace as `unit::name` when it does not. A tail an interface
|
||||
/// this file declares whole does not bind records nothing, on the same
|
||||
/// rule [`Target::MemberOf`] follows.
|
||||
TypeMember { unit: String },
|
||||
/// The `member` of `head.mids….member`, where `head` is a plain
|
||||
/// identifier this file may declare: looked up in the scope of the head's
|
||||
/// **declared type**, then up that type's `extends` chain, one hop per
|
||||
/// name in `mids`.
|
||||
///
|
||||
/// Carries the *spellings* rather than the inner tails' resolutions,
|
||||
/// because the type of a link is only known once the link before it is
|
||||
/// resolved, which is pass two's job — and because a spelling is all the
|
||||
/// workspace layer gets either way: a chain that leaves this file becomes
|
||||
/// one composed path (`pkt_t::hdr::addr`), read by the same
|
||||
/// `follow_one` every other path goes through.
|
||||
MemberOf { head: String, mids: Vec<String> },
|
||||
/// The `x` of `this.x`: the enclosing class's scope only.
|
||||
ThisMember,
|
||||
/// The `x` of `super.x`: always the base class's business.
|
||||
@@ -142,6 +171,8 @@ impl<'a> Binder<'a> {
|
||||
kind,
|
||||
name_span,
|
||||
decl_span,
|
||||
detail_span: None,
|
||||
type_name: None,
|
||||
scope,
|
||||
child_scope: None,
|
||||
});
|
||||
@@ -151,6 +182,31 @@ impl<'a> Binder<'a> {
|
||||
Some(id)
|
||||
}
|
||||
|
||||
/// [`Binder::declare`] for a declaration written with a type, recording
|
||||
/// that type's name on the symbol — what `handle.member` is looked up
|
||||
/// with. A redeclaration binds nothing and records nothing here either.
|
||||
///
|
||||
/// `ty` is `None` where the declared name is not itself a value of the
|
||||
/// type: an **unpacked** declarator (`c1 q[$]`, `item_t pool[4]`) names a
|
||||
/// container, and `q.size()` is a built-in array method, not a member of
|
||||
/// `c1` — the element is reached through an index, which is a head this
|
||||
/// crate does not type (TODO.md §15, round 2).
|
||||
fn declare_typed(
|
||||
&mut self,
|
||||
scope: ScopeId,
|
||||
name: &str,
|
||||
kind: SymbolKind,
|
||||
name_span: TextRange,
|
||||
decl_span: TextRange,
|
||||
ty: Option<&DataType>,
|
||||
) -> Option<SymbolId> {
|
||||
let id = self.declare(scope, name, kind, name_span, decl_span);
|
||||
if let Some(id) = id {
|
||||
self.symbols[id.0 as usize].type_name = ty.and_then(type_name_of);
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// Declare `name` and open the scope it owns.
|
||||
fn declare_with_scope(
|
||||
&mut self,
|
||||
@@ -281,7 +337,7 @@ impl<'a> Binder<'a> {
|
||||
}
|
||||
ItemKind::Typedef(t) => self.bind_typedef(t, item.span, scope),
|
||||
ItemKind::ParamDecl(p) => {
|
||||
self.bind_declarators(&p.declarators, SymbolKind::Param, &p.ty, item.span, scope)
|
||||
self.bind_declarators(&p.declarators, param_kind(&p.kw), &p.ty, item.span, scope)
|
||||
}
|
||||
ItemKind::DataDecl(d) => self.bind_data_decl(d, item.span, scope),
|
||||
ItemKind::PortDecl(p) => self.bind_port_decl(p, item.span, scope),
|
||||
@@ -307,7 +363,9 @@ impl<'a> Binder<'a> {
|
||||
// Handshakes.
|
||||
ItemKind::Bind(b) => self.bind_instantiation_module(&b.inst, scope),
|
||||
ItemKind::GateInstantiation(g) => {
|
||||
self.bind_opt_expr(g.delay.as_ref(), scope);
|
||||
for d in &g.delay {
|
||||
self.bind_expr(d, scope);
|
||||
}
|
||||
for inst in &g.instances {
|
||||
if let (Some(name), Some(ns)) = (&inst.name, inst.name_span) {
|
||||
self.declare(scope, name, SymbolKind::Instance, ns, inst.span);
|
||||
@@ -340,6 +398,12 @@ impl<'a> Binder<'a> {
|
||||
ItemKind::Function(f) => self.bind_function(f, item.span, scope),
|
||||
ItemKind::Task(t) => self.bind_task(t, item.span, scope),
|
||||
ItemKind::Class(c) => self.bind_class(c, item.span, scope),
|
||||
ItemKind::Modport(decls) => {
|
||||
for d in decls {
|
||||
self.bind_modport(d, scope);
|
||||
}
|
||||
}
|
||||
ItemKind::Clocking(c) => self.bind_clocking(c, item.span, scope),
|
||||
ItemKind::Defparam(pairs) => {
|
||||
for (lhs, rhs) in pairs {
|
||||
self.bind_expr(lhs, scope);
|
||||
@@ -355,32 +419,29 @@ impl<'a> Binder<'a> {
|
||||
// (an `import` alongside it does that). Resolving either one is a
|
||||
// vlog_semantic decision, not the parser's — see
|
||||
// `docs/features/dpi-export/README.md` Handshakes.
|
||||
// `modport` and `clocking` are leaves here for now: both name
|
||||
// signals that are declared in the enclosing interface, so
|
||||
// resolving them is a reference-binding question rather than a
|
||||
// declaration one, and whether a modport or a clocking block
|
||||
// should itself be a symbol is a vlog_semantic decision — see
|
||||
// `docs/features/interfaces/README.md` Handshakes.
|
||||
ItemKind::Modport(_)
|
||||
| ItemKind::Clocking(_)
|
||||
| ItemKind::Export(_)
|
||||
ItemKind::Export(_)
|
||||
| ItemKind::Directive(_)
|
||||
| ItemKind::MacroItem(_)
|
||||
| ItemKind::Timeunit(_)
|
||||
| ItemKind::Error(_)
|
||||
// A null item (`;`) declares nothing and references nothing.
|
||||
| ItemKind::Empty
|
||||
| ItemKind::Verbatim(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_module(&mut self, m: &'a Module, span: TextRange, scope: ScopeId) {
|
||||
let inner = self.declare_with_scope(
|
||||
scope,
|
||||
&m.name,
|
||||
SymbolKind::Module,
|
||||
m.name_span,
|
||||
span,
|
||||
ScopeKind::Module,
|
||||
);
|
||||
// One AST node, three keywords. `interface` gets its own kind — its
|
||||
// signals are its surface and another file may reach them, which is
|
||||
// exactly what a module never grants. `program` stays a `Module`: it is
|
||||
// a module body with a different closing keyword and no export rule of
|
||||
// its own to write (`docs/features/interface-semantics/README.md`).
|
||||
let kind = match m.kw.as_str() {
|
||||
"interface" => SymbolKind::Interface,
|
||||
_ => SymbolKind::Module,
|
||||
};
|
||||
let inner =
|
||||
self.declare_with_scope(scope, &m.name, kind, m.name_span, span, ScopeKind::Module);
|
||||
for import in &m.imports {
|
||||
for path in &import.paths {
|
||||
self.bind_import_path(path, inner);
|
||||
@@ -395,7 +456,14 @@ impl<'a> Binder<'a> {
|
||||
TextRange::new(p.span.start, p.name_span.start),
|
||||
inner,
|
||||
);
|
||||
self.declare(inner, &p.name, SymbolKind::Port, p.name_span, p.span);
|
||||
self.declare_typed(
|
||||
inner,
|
||||
&p.name,
|
||||
SymbolKind::Port,
|
||||
p.name_span,
|
||||
p.span,
|
||||
p.unpacked.is_empty().then_some(&p.ty),
|
||||
);
|
||||
self.bind_dims(&p.unpacked, inner);
|
||||
self.bind_opt_expr(p.default.as_ref(), inner);
|
||||
}
|
||||
@@ -412,10 +480,24 @@ impl<'a> Binder<'a> {
|
||||
}
|
||||
|
||||
/// A `#( ... )` header parameter list — module and class headers share it.
|
||||
///
|
||||
/// The keyword decides the kind, and it is **sticky**: a continuation
|
||||
/// entry writes none (`#(parameter A = 1, B = 2)`) and inherits the one
|
||||
/// before it, so `#(parameter int Depth = 4, localparam int DepthW = 3,
|
||||
/// DepthX = 4)` declares one `Param` and two `LocalParam`s. Exactly the
|
||||
/// rule `vlog_refactor::instantiate::params` already applies to decide
|
||||
/// what an instantiation may override — the two now agree because they
|
||||
/// read the same field the same way, where before this one read nothing
|
||||
/// and called everything a `Param`.
|
||||
fn bind_param_ports(&mut self, ports: impl Iterator<Item = &'a ParamPort>, scope: ScopeId) {
|
||||
let mut kw = String::new();
|
||||
for p in ports {
|
||||
if let Some(written) = &p.kw {
|
||||
kw.clone_from(written);
|
||||
}
|
||||
self.bind_data_type(&p.ty, TextRange::new(p.span.start, p.name_span.start), scope);
|
||||
self.declare(scope, &p.name, SymbolKind::Param, p.name_span, p.span);
|
||||
let ty = p.unpacked.is_empty().then_some(&p.ty);
|
||||
self.declare_typed(scope, &p.name, param_kind(&kw), p.name_span, p.span, ty);
|
||||
self.bind_dims(&p.unpacked, scope);
|
||||
self.bind_opt_expr(p.default.as_ref(), scope);
|
||||
}
|
||||
@@ -446,20 +528,19 @@ impl<'a> Binder<'a> {
|
||||
fn bind_typedef(&mut self, t: &Typedef, span: TextRange, scope: ScopeId) {
|
||||
let ns = t.name_span;
|
||||
match &t.kind {
|
||||
// The aliased type is recorded on the alias, so `typedef c1 my_t;
|
||||
// my_t h; h.x` can follow the alias to the class (round 2). An
|
||||
// alias **with unpacked dimensions** (`typedef c1 q_t[4];`) names
|
||||
// a container, not a value of the type, and is left untyped on
|
||||
// the same rule every other unpacked declarator follows.
|
||||
TypedefKind::Alias(ty) => {
|
||||
self.bind_data_type(ty, TextRange::new(span.start, ns.start), scope);
|
||||
self.declare(scope, &t.name, SymbolKind::Typedef, ns, span);
|
||||
let ty = t.unpacked.is_empty().then_some(ty);
|
||||
self.declare_typed(scope, &t.name, SymbolKind::Typedef, ns, span, ty);
|
||||
}
|
||||
TypedefKind::Enum(e) => {
|
||||
self.declare(scope, &t.name, SymbolKind::Typedef, ns, span);
|
||||
if let Some(base) = &e.base {
|
||||
self.bind_data_type(base, TextRange::new(span.start, ns.start), scope);
|
||||
}
|
||||
// LRM: enum names belong to the scope holding the enum.
|
||||
for m in &e.members {
|
||||
self.declare(scope, &m.name, SymbolKind::EnumVariant, m.name_span, m.span);
|
||||
self.bind_opt_expr(m.value.as_ref(), scope);
|
||||
}
|
||||
self.bind_enum_body(e, TextRange::new(span.start, ns.start), scope);
|
||||
}
|
||||
TypedefKind::Struct(s) => {
|
||||
let inner = self.declare_with_scope(
|
||||
@@ -470,15 +551,8 @@ impl<'a> Binder<'a> {
|
||||
span,
|
||||
ScopeKind::Struct,
|
||||
);
|
||||
for m in &s.members {
|
||||
let first = m.declarators.first().map(|d| d.span.start).unwrap_or(m.span.end);
|
||||
self.bind_data_type(&m.ty, TextRange::new(m.span.start, first), scope);
|
||||
for d in &m.declarators {
|
||||
self.declare(inner, &d.name, SymbolKind::StructMember, d.name_span, d.span);
|
||||
self.bind_dims(&d.unpacked, scope);
|
||||
self.bind_opt_expr(d.init.as_ref(), scope);
|
||||
}
|
||||
}
|
||||
self.bind_struct_uses(s, scope);
|
||||
self.bind_struct_members(s, inner);
|
||||
}
|
||||
// `typedef class c;` promises a class declared elsewhere; the
|
||||
// name is declared here so a reference to it resolves to the
|
||||
@@ -490,6 +564,78 @@ impl<'a> Binder<'a> {
|
||||
self.bind_dims(&t.unpacked, scope);
|
||||
}
|
||||
|
||||
/// An `enum` body: its base type, and its member names — which IEEE 1800
|
||||
/// §6.19 binds in the scope **holding** the enum, not in the enum itself,
|
||||
/// which is why `IDLE` is written bare. One function for all three
|
||||
/// spellings that can write one: `typedef enum {…} e_t;`, an anonymous
|
||||
/// `enum {…} x;`, and an anonymous enum standing as a struct member's type.
|
||||
fn bind_enum_body(&mut self, e: &EnumType, window: TextRange, scope: ScopeId) {
|
||||
if let Some(base) = &e.base {
|
||||
self.bind_data_type(base, window, scope);
|
||||
}
|
||||
for m in &e.members {
|
||||
self.declare(scope, &m.name, SymbolKind::EnumVariant, m.name_span, m.span);
|
||||
self.bind_opt_expr(m.value.as_ref(), scope);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every *use* written inside a `struct`/`union` body — each member's type
|
||||
/// name, its dimensions, its initializer — recorded in the scope the body
|
||||
/// is written in, because that is where those names are looked up from.
|
||||
///
|
||||
/// Split from [`Binder::bind_struct_members`], which declares the members
|
||||
/// themselves, so that a body written once and declared under several
|
||||
/// declarators (`struct { hdr_t h; } a, b;`) records its type names once
|
||||
/// rather than once per declarator.
|
||||
fn bind_struct_uses(&mut self, s: &StructType, scope: ScopeId) {
|
||||
for m in &s.members {
|
||||
let first = m.declarators.first().map(|d| d.span.start).unwrap_or(m.span.end);
|
||||
self.bind_data_type(&m.ty, TextRange::new(m.span.start, first), scope);
|
||||
for d in &m.declarators {
|
||||
self.bind_dims(&d.unpacked, scope);
|
||||
self.bind_opt_expr(d.init.as_ref(), scope);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The members of one `struct`/`union` body, declared in `inner` — the
|
||||
/// scope hanging off whatever names the aggregate (a `typedef`, a plain
|
||||
/// declarator, or an enclosing member).
|
||||
///
|
||||
/// Each member carries its own declared type, so `s.hdr.addr` hops through
|
||||
/// it exactly as a class property does. A member whose type is an **inline
|
||||
/// nested** aggregate (`struct packed { struct packed { logic q; } ctrl; }`
|
||||
/// — the shape every generated register package is made of) has no type
|
||||
/// name to hop through at all, so it gets a `Struct` scope of its own and
|
||||
/// `resolve.rs` reaches its members through that instead.
|
||||
fn bind_struct_members(&mut self, s: &StructType, inner: ScopeId) {
|
||||
for m in &s.members {
|
||||
for d in &m.declarators {
|
||||
// The unpacked-declarator rule, as everywhere: `logic [7:0]
|
||||
// arr [4]` names a container, not a value of the type.
|
||||
let plain = d.unpacked.is_empty();
|
||||
let id = self.declare_typed(
|
||||
inner,
|
||||
&d.name,
|
||||
SymbolKind::StructMember,
|
||||
d.name_span,
|
||||
d.span,
|
||||
plain.then_some(&m.ty),
|
||||
);
|
||||
let (Some(id), Some(TypeExtra::Struct(nested))) = (id, m.ty.inline()) else {
|
||||
continue;
|
||||
};
|
||||
if !plain {
|
||||
continue;
|
||||
}
|
||||
let child = self.new_scope(ScopeKind::Struct, inner, d.span);
|
||||
self.symbols[id.0 as usize].child_scope = Some(child);
|
||||
self.scopes[child.0 as usize].owner = Some(id);
|
||||
self.bind_struct_members(nested, child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_data_decl(&mut self, d: &DataDecl, span: TextRange, scope: ScopeId) {
|
||||
let kind = if d.net.is_some() { SymbolKind::Net } else { SymbolKind::Var };
|
||||
self.bind_opt_expr(d.delay.as_ref(), scope);
|
||||
@@ -501,6 +647,40 @@ impl<'a> Binder<'a> {
|
||||
ScopeKind::Function | ScopeKind::Task => SymbolKind::TfArg,
|
||||
_ => SymbolKind::Port,
|
||||
};
|
||||
// A non-ANSI port's body declaration (`input signed [31:0] data_in;`)
|
||||
// completes a port the header only named (`data_in,`). `declare`
|
||||
// below attaches it as a reference to that header symbol — and here,
|
||||
// the whole declaration's span is recorded on the symbol as where its
|
||||
// direction, type and width are written. First writer wins, so a
|
||||
// header that names a port twice is the linter's to complain about
|
||||
// and this stays deterministic.
|
||||
//
|
||||
// An old-style task or function argument (`task t(a);` finished by
|
||||
// `input [7:0] a;`) is the same header-names-it, body-completes-it
|
||||
// shape and merges through the same `declare`, so it is recorded on
|
||||
// the same terms — matching on `kind` rather than on `Port` alone.
|
||||
//
|
||||
// The type is recorded on the same terms: a header port is named
|
||||
// without one, and the body declaration is where it is written.
|
||||
let names = &self.scopes[scope.0 as usize].names;
|
||||
let existing: Vec<(SymbolId, bool)> = p
|
||||
.declarators
|
||||
.iter()
|
||||
.filter_map(|d| Some((names.get(d.name.as_str()).copied()?, d.unpacked.is_empty())))
|
||||
.collect();
|
||||
for (id, plain) in existing {
|
||||
let type_name = plain.then(|| type_name_of(&p.ty)).flatten();
|
||||
let symbol = &mut self.symbols[id.0 as usize];
|
||||
if symbol.kind != kind {
|
||||
continue;
|
||||
}
|
||||
if symbol.detail_span.is_none() {
|
||||
symbol.detail_span = Some(span);
|
||||
}
|
||||
if symbol.type_name.is_none() {
|
||||
symbol.type_name = type_name;
|
||||
}
|
||||
}
|
||||
self.bind_declarators(&p.declarators, kind, &p.ty, span, scope);
|
||||
}
|
||||
|
||||
@@ -515,7 +695,19 @@ impl<'a> Binder<'a> {
|
||||
let first = declarators.first().map(|d| d.span.start).unwrap_or(span.end);
|
||||
self.bind_data_type(ty, TextRange::new(span.start, first), scope);
|
||||
for d in declarators {
|
||||
self.declare(scope, &d.name, kind, d.name_span, d.span);
|
||||
let plain = d.unpacked.is_empty();
|
||||
let id =
|
||||
self.declare_typed(scope, &d.name, kind, d.name_span, d.span, plain.then_some(ty));
|
||||
// An **anonymous** aggregate (`struct packed { logic a; } s;`) has
|
||||
// no type name for `s.a` to be looked up through, so the members
|
||||
// hang off the declarator itself. In-file only: no other file can
|
||||
// name this variable's type, because it has none.
|
||||
if let (Some(id), Some(TypeExtra::Struct(s)), true) = (id, ty.inline(), plain) {
|
||||
let child = self.new_scope(ScopeKind::Struct, scope, d.span);
|
||||
self.symbols[id.0 as usize].child_scope = Some(child);
|
||||
self.scopes[child.0 as usize].owner = Some(id);
|
||||
self.bind_struct_members(s, child);
|
||||
}
|
||||
self.bind_dims(&d.unpacked, scope);
|
||||
self.bind_opt_expr(d.init.as_ref(), scope);
|
||||
}
|
||||
@@ -530,7 +722,23 @@ impl<'a> Binder<'a> {
|
||||
self.bind_connection(c, &i.module, scope);
|
||||
}
|
||||
for inst in &i.instances {
|
||||
self.declare(scope, &inst.name, SymbolKind::Instance, inst.name_span, inst.span);
|
||||
let id =
|
||||
self.declare(scope, &inst.name, SymbolKind::Instance, inst.name_span, inst.span);
|
||||
// An instance's "declared type" is the module it instantiates, so
|
||||
// `u.port` and `u.internal_sig` are looked up exactly as a class
|
||||
// handle's members are — in the module's own scope, or in the
|
||||
// workspace's member table when the module is another file's.
|
||||
// An **array** of instances (`sub u[3:0] (...)`) is not one of
|
||||
// them, on the same rule an unpacked declarator follows: the
|
||||
// element is reached through an index, which is not a head this
|
||||
// crate types.
|
||||
// A macro standing where the module name belongs (`` `REGS u ()``)
|
||||
// names no declaration, exactly as it names none in `use_name`.
|
||||
let named =
|
||||
!i.module.is_empty() && !i.module.starts_with('`') && !is_keyword(&i.module);
|
||||
if let (Some(id), true) = (id, inst.dims.is_empty() && named) {
|
||||
self.symbols[id.0 as usize].type_name = Some(i.module.clone());
|
||||
}
|
||||
self.bind_dims(&inst.dims, scope);
|
||||
match &inst.conns {
|
||||
Connections::Named(conns) => {
|
||||
@@ -656,12 +864,100 @@ impl<'a> Binder<'a> {
|
||||
fn bind_tf_args(&mut self, args: &'a [TfArg], scope: ScopeId) {
|
||||
for a in args {
|
||||
self.bind_data_type(&a.ty, TextRange::new(a.span.start, a.name_span.start), scope);
|
||||
self.declare(scope, &a.name, SymbolKind::TfArg, a.name_span, a.span);
|
||||
let ty = a.unpacked.is_empty().then_some(&a.ty);
|
||||
self.declare_typed(scope, &a.name, SymbolKind::TfArg, a.name_span, a.span, ty);
|
||||
self.bind_dims(&a.unpacked, scope);
|
||||
self.bind_opt_expr(a.default.as_ref(), scope);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Interfaces
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// One `modport mp (input a, output b)` of a `modport` declaration.
|
||||
///
|
||||
/// The name is a **declaration**: it is what an interface port's
|
||||
/// `bus_if.mp` type names, what a connection's `b_if.mp` names, and what a
|
||||
/// hover on either should show. Every name in the port list is a *use* of
|
||||
/// something the interface itself declares — a signal for
|
||||
/// `input`/`output`/`inout`/`ref`, a method for `import`/`export`, the
|
||||
/// clocking block for `clocking cb` — and all of them are one lookup in
|
||||
/// this very scope ([`Target::InScope`]), because IEEE 1800 §25.5 says a
|
||||
/// modport port names a member of the interface and nothing else.
|
||||
fn bind_modport(&mut self, d: &ModportDecl, scope: ScopeId) {
|
||||
self.declare(scope, &d.name, SymbolKind::Modport, d.name_span, d.span);
|
||||
for port in &d.ports {
|
||||
for name in &port.names {
|
||||
self.use_name(scope, &name.text, name.span, Target::InScope);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A `clocking cb @(posedge clk); … endclocking` block.
|
||||
///
|
||||
/// A **named** block with an event declares a symbol whose declared type is
|
||||
/// the enclosing unit's own name. A clocking signal is an alias of the
|
||||
/// same-named signal in that unit (IEEE 1800 §14.4), so pointing the
|
||||
/// block's "type" back at the interface makes `vif.cb.data` and `cb.data`
|
||||
/// answer with `data`'s own declaration — the honest answer — through
|
||||
/// exactly the member chase round 2 already built, with no new machinery.
|
||||
///
|
||||
/// `default clocking cb;` selects a block declared elsewhere in the same
|
||||
/// scope and is therefore a *use*; an anonymous `default clocking @(...)`
|
||||
/// names nothing and declares nothing.
|
||||
fn bind_clocking(&mut self, c: &ClockingDecl, span: TextRange, scope: ScopeId) {
|
||||
match (&c.name, &c.event) {
|
||||
(Some(name), Some(_)) => {
|
||||
let ty = self.enclosing_unit_name(scope);
|
||||
let id = self.declare(scope, &name.text, SymbolKind::Clocking, name.span, span);
|
||||
if let Some(id) = id {
|
||||
self.symbols[id.0 as usize].type_name = ty;
|
||||
}
|
||||
}
|
||||
(Some(name), None) => self.use_name(scope, &name.text, name.span, Target::InScope),
|
||||
(None, _) => {}
|
||||
}
|
||||
if let Some(event) = &c.event {
|
||||
self.bind_sens_list(event, scope);
|
||||
}
|
||||
for item in &c.items {
|
||||
let ClockingItemKind::Signals { signals, .. } = &item.kind else {
|
||||
continue;
|
||||
};
|
||||
for signal in signals {
|
||||
match &signal.value {
|
||||
// `output tms = _tms_internal;` binds the clocking name to
|
||||
// something *else*, so the name on the left is the block's
|
||||
// own and names no signal of the enclosing scope
|
||||
// (IEEE 1800 §14.4). Only the value is a use.
|
||||
Some(value) => self.bind_expr(value, scope),
|
||||
None => {
|
||||
self.use_name(scope, &signal.name.text, signal.name.span, Target::InScope)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of the nearest enclosing `module` or `interface` — what a
|
||||
/// clocking block records as its declared type. `None` at file scope, and
|
||||
/// inside a class, where a clocking block cannot stand anyway.
|
||||
fn enclosing_unit_name(&self, scope: ScopeId) -> Option<String> {
|
||||
let mut current = Some(scope);
|
||||
while let Some(id) = current {
|
||||
let s = self.scopes.get(id.0 as usize)?;
|
||||
if let Some(owner) = s.owner {
|
||||
let symbol = self.symbols.get(owner.0 as usize)?;
|
||||
if symbol.kind.is_instantiable() {
|
||||
return Some(symbol.name.clone());
|
||||
}
|
||||
}
|
||||
current = s.parent;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Classes
|
||||
// ------------------------------------------------------------------
|
||||
@@ -814,8 +1110,22 @@ impl<'a> Binder<'a> {
|
||||
}
|
||||
|
||||
// The method's home: the class scope when the class is in this file,
|
||||
// else the scope the definition is written in.
|
||||
let home = self.find_unit_scope(decl_scope, path).unwrap_or(decl_scope);
|
||||
// else a scope standing in for that class — empty, so every lookup
|
||||
// falls straight through it to the writing scope, but marked with the
|
||||
// class path as its `extends`, so a name nothing else binds is an
|
||||
// `InheritedCandidate` against the class rather than a `NotFound`.
|
||||
// That is what lets `task c2::update(...)` see `c2`'s properties when
|
||||
// `c2` is declared in another file: the workspace index finishes the
|
||||
// candidate through its member table.
|
||||
let home = match self.find_unit_scope(decl_scope, path) {
|
||||
Some(scope) => scope,
|
||||
None if path.is_empty() => decl_scope,
|
||||
None => {
|
||||
let stand_in = self.new_scope(ScopeKind::Class, decl_scope, span);
|
||||
self.scopes[stand_in.0 as usize].extends = Some(path.to_string());
|
||||
stand_in
|
||||
}
|
||||
};
|
||||
let sym = self.declare(home, name, kind, name_span, span);
|
||||
let body = self.new_scope(scope_kind, home, span);
|
||||
match sym {
|
||||
@@ -975,6 +1285,8 @@ impl<'a> Binder<'a> {
|
||||
StmtKind::Foreach { target, vars, body } => {
|
||||
let inner = self.new_scope(ScopeKind::Block, scope, stmt.span);
|
||||
self.bind_expr(target, scope);
|
||||
// A skipped dimension (`arr[, j]`) arrives as an empty name;
|
||||
// `declare` already ignores those, so it declares nothing.
|
||||
for v in vars {
|
||||
self.declare(inner, &v.text, SymbolKind::Var, v.span, v.span);
|
||||
}
|
||||
@@ -1005,8 +1317,12 @@ impl<'a> Binder<'a> {
|
||||
}
|
||||
StmtKind::ExprStmt(e) | StmtKind::EventTrigger(e) => self.bind_expr(e, scope),
|
||||
StmtKind::VarDecl(d) => self.bind_data_decl(d, stmt.span, scope),
|
||||
// A block-scoped type binds exactly as an item-level one does; the
|
||||
// scope it lands in is the enclosing block's, which is what
|
||||
// IEEE 1800 §6.18 asks for.
|
||||
StmtKind::Typedef(t) => self.bind_typedef(t, stmt.span, scope),
|
||||
StmtKind::ParamDecl(p) => {
|
||||
self.bind_declarators(&p.declarators, SymbolKind::Param, &p.ty, stmt.span, scope)
|
||||
self.bind_declarators(&p.declarators, param_kind(&p.kw), &p.ty, stmt.span, scope)
|
||||
}
|
||||
StmtKind::PortDecl(p) => self.bind_port_decl(p, stmt.span, scope),
|
||||
StmtKind::Return(e) => self.bind_opt_expr(e.as_ref(), scope),
|
||||
@@ -1051,14 +1367,27 @@ impl<'a> Binder<'a> {
|
||||
fn bind_timing(&mut self, t: &'a TimingControl, scope: ScopeId) {
|
||||
match t {
|
||||
TimingControl::Delay(e) => self.bind_expr(e, scope),
|
||||
TimingControl::Event(SensList::List(items)) => {
|
||||
TimingControl::Event(list) => self.bind_sens_list(list, scope),
|
||||
}
|
||||
}
|
||||
|
||||
/// An `@( ... )` sensitivity list — a statement's timing control, and a
|
||||
/// clocking block's event, which is the same grammar.
|
||||
fn bind_sens_list(&mut self, list: &SensList, scope: ScopeId) {
|
||||
match list {
|
||||
SensList::List(items) => {
|
||||
for i in items {
|
||||
self.bind_expr(&i.expr, scope);
|
||||
// `@(posedge clk iff enable)` reads `enable` as ordinarily
|
||||
// as it reads `clk`.
|
||||
if let Some(iff) = &i.iff {
|
||||
self.bind_expr(iff, scope);
|
||||
}
|
||||
}
|
||||
}
|
||||
TimingControl::Event(SensList::Star { .. }) => {}
|
||||
SensList::Star { .. } => {}
|
||||
// `@name;` without parens — the expression is an ordinary use.
|
||||
TimingControl::Event(SensList::Bare(e)) => self.bind_expr(e, scope),
|
||||
SensList::Bare(e) => self.bind_expr(e, scope),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1118,8 +1447,17 @@ impl<'a> Binder<'a> {
|
||||
self.bind_expr(msb, scope);
|
||||
self.bind_expr(lsb, scope);
|
||||
}
|
||||
// `a.b`: only the head is resolved (see the README) — except
|
||||
// `this.b` and `super.b`, whose member is the whole point.
|
||||
// `a.b`, `a.b.c`, `tb.dut.u_core.sig`: every link is bound —
|
||||
// the head as an ordinary use, each `.name` as a tail against the
|
||||
// type of what precedes it (`Target::MemberOf`) — because the
|
||||
// recursion below meets each `Member` node in turn. `this.b` and
|
||||
// `super.b` go to the enclosing class instead, and a spine that
|
||||
// starts at one of them stops there: `this.a.b` records `a` and
|
||||
// nothing more (`this` is not a name this crate binds, so there
|
||||
// is no head to walk from). An indexed or called head
|
||||
// (`a[i].b`, `f().b`) still resolves its own head and stops:
|
||||
// chasing those needs the element type of a container, which
|
||||
// this crate does not model (TODO.md §15).
|
||||
ExprKind::Member { base, name } => match &base.kind {
|
||||
ExprKind::Ident(head) if head == "this" => {
|
||||
self.use_member(scope, name, member_tail(e.span, name), Target::ThisMember)
|
||||
@@ -1127,7 +1465,19 @@ impl<'a> Binder<'a> {
|
||||
ExprKind::Ident(head) if head == "super" => {
|
||||
self.use_member(scope, name, member_tail(e.span, name), Target::SuperMember)
|
||||
}
|
||||
_ => self.bind_expr(base, scope),
|
||||
_ => {
|
||||
self.bind_expr(base, scope);
|
||||
if let Some((head, mids)) = spine(base) {
|
||||
// The tail's range is derived from the whole
|
||||
// expression's, so it is verified before use: a
|
||||
// spelling this crate cannot place costs a reference,
|
||||
// never a wrong span.
|
||||
let tail = self.exact_or_empty(member_tail(e.span, name), name);
|
||||
if !tail.is_empty() {
|
||||
self.use_member(scope, name, tail, Target::MemberOf { head, mids });
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
ExprKind::Scope { base, name } => self.bind_scoped(base, name, e.span, scope),
|
||||
// The `#( ... )` is verbatim text this crate makes no claims
|
||||
@@ -1226,21 +1576,101 @@ impl<'a> Binder<'a> {
|
||||
self.use_name(scope, unit, unit_span, Target::Unit);
|
||||
self.use_name(scope, item, item_span, Target::UnitMember(unit.to_string()));
|
||||
}
|
||||
// `bus_if.mp bus`, `virtual bus_if.mp vif` — the parser glues
|
||||
// an interface port's modport onto the type name (IEEE 1800
|
||||
// §25.4, §25.9). The interface is the type and the modport is
|
||||
// a **member** of it, so both halves are bound: the head as
|
||||
// any other type name, the tail against the interface's own
|
||||
// scope (or, cross-file, as `bus_if::mp` in the workspace's
|
||||
// member table). "The tail is where to bind them" —
|
||||
// `docs/features/ansi-first-port/README.md`.
|
||||
None => {
|
||||
// `bus_if.mp bus` — the parser glues an interface port's
|
||||
// modport onto the type name (IEEE 1800 §25.4). The
|
||||
// interface is the type; the modport is a member of it,
|
||||
// and this crate declares no symbol for a modport
|
||||
// (`ItemKind::Modport` is a leaf here), so the tail is
|
||||
// left unbound rather than recorded as a name that can
|
||||
// never resolve.
|
||||
let name = ty.name.split_once('.').map_or(ty.name.as_str(), |(iface, _)| iface);
|
||||
let (name, modport) = match ty.name.split_once('.') {
|
||||
Some((iface, modport)) => (iface, Some(modport)),
|
||||
None => (ty.name.as_str(), None),
|
||||
};
|
||||
let ns = crate::scan::name_span(self.src, window, name);
|
||||
self.use_name(scope, name, ns, Target::Type);
|
||||
if let Some(modport) = modport {
|
||||
let tail = self.modport_tail(ns, modport);
|
||||
if !tail.is_empty() {
|
||||
self.use_member(
|
||||
scope,
|
||||
modport,
|
||||
tail,
|
||||
Target::TypeMember { unit: name.to_string() },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.bind_dims(&ty.packed, scope);
|
||||
// An anonymous aggregate written where a type name would go. Its
|
||||
// *names* are declared by whoever owns the declarator (an enum's
|
||||
// variants below, a struct's members in `bind_struct_members`); what
|
||||
// is written here is every use inside it, recorded once for the type
|
||||
// however many declarators share it.
|
||||
match ty.inline() {
|
||||
Some(TypeExtra::Enum(e)) => self.bind_enum_body(e, window, scope),
|
||||
Some(TypeExtra::Struct(s)) => self.bind_struct_uses(s, scope),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The byte range of the `mp` in a glued `bus_if.mp` type name, given the
|
||||
/// range the interface half was located at.
|
||||
///
|
||||
/// Derived rather than received — a `DataType` carries no spans at all —
|
||||
/// so it is verified twice over: the byte after the interface half must be
|
||||
/// a literal `.`, and the bytes after that must spell the modport exactly.
|
||||
/// A source that wrote the two apart, or a name a macro produced, costs the
|
||||
/// reference and never mislocates it.
|
||||
fn modport_tail(&self, iface: TextRange, modport: &str) -> TextRange {
|
||||
if iface.is_empty() || self.src.as_bytes().get(iface.end as usize) != Some(&b'.') {
|
||||
return TextRange::empty(iface.end);
|
||||
}
|
||||
let start = iface.end.saturating_add(1);
|
||||
let span = TextRange::new(start, start.saturating_add(modport.len() as u32));
|
||||
self.exact_or_empty(span, modport)
|
||||
}
|
||||
}
|
||||
|
||||
/// The chain of names written before a member access's tail: the plain
|
||||
/// identifier it starts at, and the members already selected from it, in the
|
||||
/// order they are written (`a.b.c`'s tail `c` gives `("a", ["b"])`).
|
||||
///
|
||||
/// `None` for a spine this crate cannot start walking — an index, a call, a
|
||||
/// cast, or `this`/`super`, which name no declaration to take a type from.
|
||||
fn spine(base: &Expr) -> Option<(String, Vec<String>)> {
|
||||
let mut mids = Vec::new();
|
||||
let mut current = base;
|
||||
loop {
|
||||
match ¤t.kind {
|
||||
ExprKind::Ident(name) if matches!(name.as_str(), "this" | "super") => return None,
|
||||
ExprKind::Ident(name) => {
|
||||
mids.reverse();
|
||||
return Some((name.clone(), mids));
|
||||
}
|
||||
ExprKind::Member { base, name } => {
|
||||
mids.push(name.clone());
|
||||
current = base;
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Which kind a parameter declaration's keyword names.
|
||||
///
|
||||
/// `localparam` is the only spelling that is not overridable, and it is the
|
||||
/// only thing this distinction is for; anything else — `parameter`, and the
|
||||
/// empty string a continuation entry leaves behind before any keyword has
|
||||
/// been written at all — is a [`SymbolKind::Param`].
|
||||
fn param_kind(kw: &str) -> SymbolKind {
|
||||
match kw {
|
||||
"localparam" => SymbolKind::LocalParam,
|
||||
_ => SymbolKind::Param,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1250,6 +1680,15 @@ fn member_tail(span: TextRange, name: &str) -> TextRange {
|
||||
TextRange::new(span.end.saturating_sub(name.len() as u32), span.end)
|
||||
}
|
||||
|
||||
/// The type name to record on a declaration: the name as written, minus the
|
||||
/// interface port's glued-on modport (`bus_if.mp bus` — the interface is the
|
||||
/// type, exactly as [`Binder::bind_data_type`] reads it). `None` for a
|
||||
/// built-in type, whose keyword names no declaration to look members up in.
|
||||
fn type_name_of(ty: &DataType) -> Option<String> {
|
||||
let name = ty.name.split_once('.').map_or(ty.name.as_str(), |(iface, _)| iface);
|
||||
(!name.is_empty() && !is_keyword(name)).then(|| name.to_string())
|
||||
}
|
||||
|
||||
/// The last `::` segment of a possibly-qualified path (`pkg::cls` → `cls`).
|
||||
fn last_segment(path: &str) -> &str {
|
||||
path.rsplit("::").next().unwrap_or(path)
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Finding class declarations in a parse tree — one walk, two readers.
|
||||
//!
|
||||
//! `type_hierarchy.rs` wants every class in a file so it can build a hierarchy
|
||||
//! item for the one the cursor names; the workspace index wants the same walk
|
||||
//! so it can record who extends whom as it builds
|
||||
//! (`docs/features/incremental-index/README.md`). One walk here, so the census
|
||||
//! the index holds and the declaration the hierarchy shows can never disagree.
|
||||
//!
|
||||
//! **Lifted from `lucisv_server::type_hierarchy` on 2026-08-27**, unchanged by
|
||||
//! the move.
|
||||
|
||||
use vlog_parser::ast::{ClassDecl, Item, ItemKind};
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
/// One class declaration: the node, and the extent of the whole
|
||||
/// `class ... endclass` it was written as.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Decl<'a> {
|
||||
/// The declaration node, for its name and its `extends` clause.
|
||||
pub class: &'a ClassDecl,
|
||||
/// Code extent of the declaration, attributes included — what a type
|
||||
/// hierarchy item's `range` is.
|
||||
pub span: TextRange,
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub fn declarations(items: &[Item]) -> Vec<Decl<'_>> {
|
||||
let mut out = Vec::new();
|
||||
collect(items, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// The base class one declaration names, as written — `None` when the header
|
||||
/// has no `extends`.
|
||||
///
|
||||
/// The name is the bare base: `extends base #(8)` reads `base`, because the
|
||||
/// parser keeps the parameter overrides on their own field, so a parameterized
|
||||
/// base needs no unwrapping here.
|
||||
pub fn extends_name(class: &ClassDecl) -> Option<&str> {
|
||||
class.extends.as_ref().map(|extends| extends.name.as_str())
|
||||
}
|
||||
|
||||
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),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
|
||||
/// Every class name a file declares, in walk order, with its base.
|
||||
fn declared(text: &str) -> Vec<(String, String)> {
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
declarations(&tree.items)
|
||||
.iter()
|
||||
.map(|decl| {
|
||||
(decl.class.name.clone(), extends_name(decl.class).unwrap_or("-").to_string())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_class_is_found_wherever_it_may_be_written() {
|
||||
let text = "\
|
||||
class top extends base;
|
||||
class nested extends top;
|
||||
endclass
|
||||
endclass
|
||||
|
||||
package p;
|
||||
class in_pkg extends top;
|
||||
endclass
|
||||
endpackage
|
||||
|
||||
module m;
|
||||
class in_mod;
|
||||
endclass
|
||||
endmodule
|
||||
";
|
||||
assert_eq!(
|
||||
declared(text),
|
||||
[
|
||||
("top".to_string(), "base".to_string()),
|
||||
("nested".to_string(), "top".to_string()),
|
||||
("in_pkg".to_string(), "top".to_string()),
|
||||
("in_mod".to_string(), "-".to_string()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameterized_base_names_the_bare_class() {
|
||||
assert_eq!(
|
||||
declared("class d extends b #(8);\nendclass\n"),
|
||||
[("d".to_string(), "b".to_string())]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declarations_extent_contains_its_own_name() {
|
||||
let text = "class first;\nendclass\n\nclass second;\nendclass\n";
|
||||
let (tree, _) = parse_source_tolerant(text);
|
||||
let decls = declarations(&tree.items);
|
||||
assert_eq!(decls.len(), 2);
|
||||
for decl in &decls {
|
||||
assert!(decl.span.start <= decl.class.name_span.start);
|
||||
assert!(decl.class.name_span.end <= decl.span.end);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,643 @@
|
||||
//! [`FileFacts`] as one line of text: the format the index cache stores a
|
||||
//! parse's result in, and reads it back from.
|
||||
//!
|
||||
//! Hand-rolled, because the alternative is a serialization dependency in a
|
||||
//! crate that has one dependency and it is the parser. The shape is the one
|
||||
//! `lucisv_core::cache` established for the formatter's store — tab-separated
|
||||
//! fields on one line, so a torn write is a line without a newline and a
|
||||
//! record that does not parse is a record that is dropped — with lists
|
||||
//! length-prefixed rather than nested, so reading a record is one pass over a
|
||||
//! flat token stream and nothing is ambiguous.
|
||||
//!
|
||||
//! **Anything that changes what a record holds, or how it is written, bumps
|
||||
//! [`FACTS_FORMAT`].** A record written by another format is not read at all;
|
||||
//! see `docs/features/index-persistence/README.md` for why the cache would
|
||||
//! rather redo the work than guess.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use vlog_parser::defines::{Define, DefineKind, DefineTable};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
use crate::model::SymbolKind;
|
||||
use crate::workspace::{
|
||||
Decl, DeclLines, DeclPositions, DeclSite, FileFacts, InstanceOccurrence, ReferenceFact,
|
||||
SiteFact, Utf16Pos, Utf16Range,
|
||||
};
|
||||
|
||||
/// The version of the encoding below. Bump it on **any** change to what a
|
||||
/// record holds or to how it is written: a store stamped with another number
|
||||
/// is discarded whole, which is the only way a reader can be sure it is not
|
||||
/// reading last month's field order as this month's.
|
||||
///
|
||||
/// 5 → 6 (2026-09-01, class-member-access): the field *layout* is unchanged,
|
||||
/// but the reference census a record carries is not — `head.member` tails and
|
||||
/// names inside an out-of-class method body are references now, so a store
|
||||
/// written by an older build would silently hold fewer `R` entries than the
|
||||
/// same file produces today, and half the workspace's postings would be
|
||||
/// missing depending on which files happened to be cached.
|
||||
///
|
||||
/// 6 → 7 (2026-09-01, class-member-access round 2): the layout **and** the
|
||||
/// census. Every declaration carries its declared type name (what a member
|
||||
/// chain `a.b.c` hops through across files), and an external reference
|
||||
/// carries the base class an inherited miss was recorded against (what gives
|
||||
/// `this.x` an index posting) — two new fields, plus the chain tails and
|
||||
/// instance-head tails that are now references at all.
|
||||
///
|
||||
/// 7 → 8 (2026-09-01, interface-semantics): three new kind names —
|
||||
/// `interface`, `modport`, `clocking` — which an older reader has no name for
|
||||
/// at all, and once more a wider census. An interface exports its signals now,
|
||||
/// a modport and a named clocking block are declarations, and every name
|
||||
/// written inside either is a reference, so a store written by an older build
|
||||
/// holds a strictly smaller `M` and `R` group for the same file.
|
||||
///
|
||||
/// 8 → 9 (2026-09-01, struct-members): the census again, in both groups. A
|
||||
/// `struct`/`union` typedef now exports its fields — and an inline nested
|
||||
/// field its own fields, under a synthesized `owner.field` key — so the `M`
|
||||
/// group of a register package grows from nothing to hundreds of entries; a
|
||||
/// member carries the declared type it is hopped through; and `s.field` is a
|
||||
/// reference where it used to be silence, so the `R` group grows too. A store
|
||||
/// written by an older build would answer `reg2hw.ctrl.q` for the files it
|
||||
/// cached and not for the files it did not.
|
||||
///
|
||||
/// 9 → 10 (2026-09-02, member-completion QA finding 1): a new kind name,
|
||||
/// `localparam`. A store written by an older build records every `localparam`
|
||||
/// — header and body alike — as a `param`, which is not a label difference
|
||||
/// but a **wrong answer**: a `#(.` override list offers what the module's
|
||||
/// member table calls a `param`, and a header `localparam` is not overridable
|
||||
/// (`prim_fifo_sync`'s `localparam int DepthW = $clog2(Depth)` was offered).
|
||||
/// An older reader has no name for the new kind either, so the bump is needed
|
||||
/// in both directions.
|
||||
pub const FACTS_FORMAT: u32 = 10;
|
||||
|
||||
impl FileFacts {
|
||||
/// These facts as one line's worth of fields, tab-separated.
|
||||
///
|
||||
/// `None` for a path that cannot be written on a line of text — not UTF-8,
|
||||
/// or holding a tab or a newline. Such a file is simply never cached, the
|
||||
/// same answer `lucisv_core::cache` gives for the same shape of path.
|
||||
/// Every *other* string a record holds is escaped instead, because a macro
|
||||
/// body really can contain a tab.
|
||||
pub fn encode(&self) -> Option<String> {
|
||||
let path = self.path.to_str()?;
|
||||
let mut out = Writer::default();
|
||||
out.text(path);
|
||||
out.tag("D", self.defines.entries().len());
|
||||
for define in self.defines.entries() {
|
||||
out.define(define);
|
||||
}
|
||||
out.tag("U", self.units.len());
|
||||
for decl in &self.units {
|
||||
out.decl(decl);
|
||||
// Only the `U` group carries client positions, so the `M` group
|
||||
// below stays exactly as wide as it was — see
|
||||
// `vlog_semantic::DeclPositions` for why members are left out.
|
||||
out.positions(&decl.lines.positions.unwrap_or_default());
|
||||
}
|
||||
out.tag("M", self.members.len());
|
||||
for (unit, decl) in &self.members {
|
||||
out.text(unit);
|
||||
out.decl(decl);
|
||||
}
|
||||
out.tag("I", self.instantiations.len());
|
||||
for (module, site) in &self.instantiations {
|
||||
out.text(module);
|
||||
out.site(&site.owner);
|
||||
out.range(site.site_span);
|
||||
out.num(site.instances.len() as u32);
|
||||
for instance in &site.instances {
|
||||
out.text(&instance.name);
|
||||
out.range(instance.name_span);
|
||||
out.range(instance.span);
|
||||
out.utf16(instance.name_positions);
|
||||
out.utf16(instance.positions);
|
||||
}
|
||||
}
|
||||
out.tag("S", self.subclasses.len());
|
||||
for (base, subclass) in &self.subclasses {
|
||||
out.text(base);
|
||||
out.site(subclass);
|
||||
}
|
||||
out.tag("R", self.references.len());
|
||||
for reference in &self.references {
|
||||
out.reference(reference);
|
||||
}
|
||||
Some(out.out)
|
||||
}
|
||||
|
||||
/// The facts a record describes, or `None` for anything that is not
|
||||
/// exactly one whole record of this format.
|
||||
///
|
||||
/// Strict on purpose, in both directions: a field missing, a number that
|
||||
/// does not parse, a kind this version has no name for, a count that
|
||||
/// outruns the line, **or a field left over at the end** all mean the same
|
||||
/// thing — this is not a record this version wrote, so nothing is taken
|
||||
/// from it. A dropped record costs one file's parse; a half-read one would
|
||||
/// cost correctness.
|
||||
pub fn decode(line: &str) -> Option<FileFacts> {
|
||||
let mut input = Reader::new(line);
|
||||
let path = PathBuf::from(input.text()?);
|
||||
let mut defines = Vec::new();
|
||||
for _ in 0..input.tag("D")? {
|
||||
defines.push(input.define()?);
|
||||
}
|
||||
let mut units = Vec::new();
|
||||
for _ in 0..input.tag("U")? {
|
||||
let mut decl = input.decl()?;
|
||||
decl.lines.positions = Some(input.positions()?);
|
||||
units.push(decl);
|
||||
}
|
||||
let mut members = Vec::new();
|
||||
for _ in 0..input.tag("M")? {
|
||||
members.push((input.text()?, input.decl()?));
|
||||
}
|
||||
let mut instantiations = Vec::new();
|
||||
for _ in 0..input.tag("I")? {
|
||||
let module = input.text()?;
|
||||
let owner = input.site()?;
|
||||
let site_span = input.range()?;
|
||||
let mut instances = Vec::new();
|
||||
for _ in 0..input.num()? {
|
||||
instances.push(InstanceOccurrence {
|
||||
name: input.text()?,
|
||||
name_span: input.range()?,
|
||||
span: input.range()?,
|
||||
name_positions: input.utf16()?,
|
||||
positions: input.utf16()?,
|
||||
});
|
||||
}
|
||||
instantiations.push((module, SiteFact { owner, site_span, instances }));
|
||||
}
|
||||
let mut subclasses = Vec::new();
|
||||
for _ in 0..input.tag("S")? {
|
||||
subclasses.push((input.text()?, input.site()?));
|
||||
}
|
||||
let mut references = Vec::new();
|
||||
for _ in 0..input.tag("R")? {
|
||||
references.push(input.reference()?);
|
||||
}
|
||||
if !input.done() {
|
||||
return None;
|
||||
}
|
||||
Some(FileFacts {
|
||||
path,
|
||||
defines: DefineTable::from_entries(defines),
|
||||
units,
|
||||
members,
|
||||
instantiations,
|
||||
subclasses,
|
||||
references,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The path a record is for, without decoding the rest of it.
|
||||
///
|
||||
/// A store keyed by path has to read this out of every record it holds, and
|
||||
/// only ever decodes the handful it is asked for — so the cheap half of the
|
||||
/// format is public separately from [`FileFacts::decode`]. `None` for a record
|
||||
/// whose first field is not a readable path, which is a record that would not
|
||||
/// decode either.
|
||||
pub fn record_path(record: &str) -> Option<PathBuf> {
|
||||
let field = record.split('\t').next()?;
|
||||
Some(PathBuf::from(unescape(field)?))
|
||||
}
|
||||
|
||||
/// A record under construction: fields pushed in order, separated by tabs.
|
||||
#[derive(Default)]
|
||||
struct Writer {
|
||||
out: String,
|
||||
/// Whether a field has been written yet, so the separator goes *between*
|
||||
/// fields — asked of a flag rather than of `out.is_empty()`, which would
|
||||
/// be wrong for a first field that is itself empty.
|
||||
written: bool,
|
||||
}
|
||||
|
||||
impl Writer {
|
||||
/// One string field, escaped.
|
||||
fn text(&mut self, text: &str) {
|
||||
self.field();
|
||||
for ch in text.chars() {
|
||||
match ch {
|
||||
'\\' => self.out.push_str("\\\\"),
|
||||
'\t' => self.out.push_str("\\t"),
|
||||
'\n' => self.out.push_str("\\n"),
|
||||
'\r' => self.out.push_str("\\r"),
|
||||
_ => self.out.push(ch),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One number field.
|
||||
fn num(&mut self, n: u32) {
|
||||
self.field();
|
||||
self.out.push_str(&n.to_string());
|
||||
}
|
||||
|
||||
/// A list's marker and its length — the length prefix that makes the
|
||||
/// stream flat and still unambiguous.
|
||||
fn tag(&mut self, tag: &str, len: usize) {
|
||||
self.field();
|
||||
self.out.push_str(tag);
|
||||
self.num(len as u32);
|
||||
}
|
||||
|
||||
fn range(&mut self, range: TextRange) {
|
||||
self.num(range.start);
|
||||
self.num(range.end);
|
||||
}
|
||||
|
||||
fn decl(&mut self, decl: &Decl) {
|
||||
self.text(&decl.name);
|
||||
self.field();
|
||||
self.out.push_str(kind_name(decl.kind));
|
||||
self.range(decl.name_span);
|
||||
self.range(decl.decl_span);
|
||||
// The detail span is written unconditionally — `0 0` for the `None`
|
||||
// every ordinary declaration has — so the stream stays flat. Adding it
|
||||
// changed what a record holds, so `FACTS_FORMAT` is bumped and a store
|
||||
// written before it is discarded whole rather than read field-shifted
|
||||
// by two (`docs/features/port-detail-spans/README.md`).
|
||||
match decl.detail_span {
|
||||
Some(span) => self.range(span),
|
||||
None => {
|
||||
self.num(0);
|
||||
self.num(0);
|
||||
}
|
||||
}
|
||||
// The declaration's lines, on the same unconditional-pair rule: the
|
||||
// name's line, then the detail span's or `0` for the `None` above.
|
||||
// `FACTS_FORMAT` is bumped for these two fields, so a store written
|
||||
// before them is discarded rather than read short by two
|
||||
// (`docs/features/hover-line-index/README.md`).
|
||||
self.num(decl.lines.name);
|
||||
self.num(decl.lines.detail.unwrap_or(0));
|
||||
// The declared type, or the empty string for the `None` most
|
||||
// declarations have — a type name is never empty, so the two cannot be
|
||||
// confused. One more field per declaration, and the `FACTS_FORMAT`
|
||||
// bump that goes with it
|
||||
// (`docs/features/class-member-access/README.md`, round 2).
|
||||
self.text(decl.type_name.as_deref().unwrap_or(""));
|
||||
}
|
||||
|
||||
/// One [`Utf16Range`]: four numbers, in the order a reader takes them.
|
||||
fn utf16(&mut self, range: Utf16Range) {
|
||||
self.num(range.start.line);
|
||||
self.num(range.start.character);
|
||||
self.num(range.end.line);
|
||||
self.num(range.end.character);
|
||||
}
|
||||
|
||||
/// A file-scope declaration's two client ranges, written after its decl.
|
||||
fn positions(&mut self, positions: &DeclPositions) {
|
||||
self.utf16(positions.name);
|
||||
self.utf16(positions.decl);
|
||||
}
|
||||
|
||||
fn site(&mut self, site: &DeclSite) {
|
||||
self.text(&site.name);
|
||||
self.range(site.name_span);
|
||||
self.range(site.span);
|
||||
}
|
||||
|
||||
fn define(&mut self, define: &Define) {
|
||||
self.field();
|
||||
self.out.push(match define.kind {
|
||||
DefineKind::Define => 'd',
|
||||
DefineKind::Undef => 'u',
|
||||
});
|
||||
self.text(&define.name);
|
||||
match &define.params {
|
||||
// A macro with no parameter list at all is not a macro with an
|
||||
// empty one — `` `define A x`` against `` `define A() x`` — so the
|
||||
// two cannot share a spelling.
|
||||
None => {
|
||||
self.field();
|
||||
self.out.push('-');
|
||||
}
|
||||
Some(params) => {
|
||||
self.num(params.len() as u32);
|
||||
for param in params {
|
||||
self.text(param);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.text(&define.body);
|
||||
self.range(define.span);
|
||||
self.range(define.name_span);
|
||||
}
|
||||
|
||||
fn reference(&mut self, reference: &ReferenceFact) {
|
||||
match reference {
|
||||
ReferenceFact::Local { definition, occurrence } => {
|
||||
self.field();
|
||||
self.out.push('l');
|
||||
self.range(*definition);
|
||||
self.range(*occurrence);
|
||||
}
|
||||
ReferenceFact::External { name, base, paths, occurrence } => {
|
||||
self.field();
|
||||
self.out.push('e');
|
||||
self.text(name);
|
||||
// The base class, or the empty string for the `None` every
|
||||
// ordinary external reference has — on the same rule as a
|
||||
// declaration's type name above.
|
||||
self.text(base.as_deref().unwrap_or(""));
|
||||
self.num(paths.len() as u32);
|
||||
for path in paths {
|
||||
self.text(path);
|
||||
}
|
||||
self.range(*occurrence);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The separator before every field but the first.
|
||||
fn field(&mut self) {
|
||||
if self.written {
|
||||
self.out.push('\t');
|
||||
}
|
||||
self.written = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// A record being read, one field at a time.
|
||||
struct Reader<'a> {
|
||||
fields: Vec<&'a str>,
|
||||
at: usize,
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
fn new(line: &'a str) -> Reader<'a> {
|
||||
Reader { fields: line.split('\t').collect(), at: 0 }
|
||||
}
|
||||
|
||||
fn next(&mut self) -> Option<&'a str> {
|
||||
let field = self.fields.get(self.at)?;
|
||||
self.at += 1;
|
||||
Some(field)
|
||||
}
|
||||
|
||||
/// Whether every field has been read — the check that makes a record with
|
||||
/// something extra on the end invalid rather than merely surprising.
|
||||
fn done(&self) -> bool {
|
||||
self.at == self.fields.len()
|
||||
}
|
||||
|
||||
fn text(&mut self) -> Option<String> {
|
||||
unescape(self.next()?)
|
||||
}
|
||||
|
||||
fn num(&mut self) -> Option<u32> {
|
||||
self.next()?.parse().ok()
|
||||
}
|
||||
|
||||
fn range(&mut self) -> Option<TextRange> {
|
||||
Some(TextRange::new(self.num()?, self.num()?))
|
||||
}
|
||||
|
||||
/// A list's length, once its marker has been confirmed. The marker is what
|
||||
/// turns a misaligned read into a dropped record instead of a plausible
|
||||
/// one.
|
||||
fn tag(&mut self, tag: &str) -> Option<usize> {
|
||||
if self.next()? != tag {
|
||||
return None;
|
||||
}
|
||||
Some(self.num()? as usize)
|
||||
}
|
||||
|
||||
fn decl(&mut self) -> Option<Decl> {
|
||||
let name = self.text()?;
|
||||
let kind = kind_of(self.next()?)?;
|
||||
let name_span = self.range()?;
|
||||
let decl_span = self.range()?;
|
||||
// The mirror of the encoder's unconditional pair: `(0, 0)` is the
|
||||
// `None`, and a real span can never be, because a declaration's span
|
||||
// is never empty.
|
||||
let start = self.num()?;
|
||||
let end = self.num()?;
|
||||
let detail_span = (start != 0 || end != 0).then_some(TextRange::new(start, end));
|
||||
// A line is 1-based, so `0` is the `None` here too — and a detail line
|
||||
// is present exactly when a detail span is, which a record written by
|
||||
// this format always agrees with.
|
||||
let name_line = self.num()?;
|
||||
let detail_line = self.num()?;
|
||||
let type_name = self.text()?;
|
||||
let type_name = (!type_name.is_empty()).then_some(type_name);
|
||||
// Client positions are not one of a declaration's shared fields: a
|
||||
// caller reading the `U` group takes them from `positions()` next, and
|
||||
// a member has none at all (`vlog_semantic::DeclPositions`).
|
||||
let lines = DeclLines {
|
||||
name: name_line,
|
||||
detail: (detail_line != 0).then_some(detail_line),
|
||||
positions: None,
|
||||
};
|
||||
Some(Decl { name, name_span, decl_span, kind, detail_span, lines, type_name })
|
||||
}
|
||||
|
||||
fn utf16(&mut self) -> Option<Utf16Range> {
|
||||
Some(Utf16Range {
|
||||
start: Utf16Pos { line: self.num()?, character: self.num()? },
|
||||
end: Utf16Pos { line: self.num()?, character: self.num()? },
|
||||
})
|
||||
}
|
||||
|
||||
fn positions(&mut self) -> Option<DeclPositions> {
|
||||
Some(DeclPositions { name: self.utf16()?, decl: self.utf16()? })
|
||||
}
|
||||
|
||||
fn site(&mut self) -> Option<DeclSite> {
|
||||
Some(DeclSite { name: self.text()?, name_span: self.range()?, span: self.range()? })
|
||||
}
|
||||
|
||||
fn define(&mut self) -> Option<Define> {
|
||||
let kind = match self.next()? {
|
||||
"d" => DefineKind::Define,
|
||||
"u" => DefineKind::Undef,
|
||||
_ => return None,
|
||||
};
|
||||
let name = self.text()?;
|
||||
let params = match self.next()? {
|
||||
"-" => None,
|
||||
count => {
|
||||
let count: u32 = count.parse().ok()?;
|
||||
let mut params = Vec::new();
|
||||
for _ in 0..count {
|
||||
params.push(self.text()?);
|
||||
}
|
||||
Some(params)
|
||||
}
|
||||
};
|
||||
Some(Define {
|
||||
kind,
|
||||
name,
|
||||
params,
|
||||
body: self.text()?,
|
||||
span: self.range()?,
|
||||
name_span: self.range()?,
|
||||
})
|
||||
}
|
||||
|
||||
fn reference(&mut self) -> Option<ReferenceFact> {
|
||||
match self.next()? {
|
||||
"l" => {
|
||||
Some(ReferenceFact::Local { definition: self.range()?, occurrence: self.range()? })
|
||||
}
|
||||
"e" => {
|
||||
let name = self.text()?;
|
||||
let base = self.text()?;
|
||||
let count = self.num()? as usize;
|
||||
let mut paths = Vec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
paths.push(self.text()?);
|
||||
}
|
||||
Some(ReferenceFact::External {
|
||||
name,
|
||||
base: (!base.is_empty()).then_some(base),
|
||||
paths,
|
||||
occurrence: self.range()?,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One escaped string field, back as it was written. `None` for an escape
|
||||
/// this format does not write, which is a record it did not write either.
|
||||
fn unescape(field: &str) -> Option<String> {
|
||||
let mut out = String::with_capacity(field.len());
|
||||
let mut chars = field.chars();
|
||||
while let Some(ch) = chars.next() {
|
||||
if ch != '\\' {
|
||||
out.push(ch);
|
||||
continue;
|
||||
}
|
||||
out.push(match chars.next()? {
|
||||
'\\' => '\\',
|
||||
't' => '\t',
|
||||
'n' => '\n',
|
||||
'r' => '\r',
|
||||
_ => return None,
|
||||
});
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// A [`SymbolKind`]'s name in a record. Written out rather than numbered, so
|
||||
/// a variant inserted in the middle of the enum cannot silently turn one kind
|
||||
/// into another — and a name this version does not know drops the record.
|
||||
fn kind_name(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 => "var",
|
||||
SymbolKind::Param => "param",
|
||||
SymbolKind::LocalParam => "localparam",
|
||||
SymbolKind::Genvar => "genvar",
|
||||
SymbolKind::Typedef => "typedef",
|
||||
SymbolKind::EnumVariant => "enumvariant",
|
||||
SymbolKind::Function => "function",
|
||||
SymbolKind::Task => "task",
|
||||
SymbolKind::TfArg => "tfarg",
|
||||
SymbolKind::Instance => "instance",
|
||||
SymbolKind::Block => "block",
|
||||
SymbolKind::StructMember => "structmember",
|
||||
SymbolKind::Class => "class",
|
||||
}
|
||||
}
|
||||
|
||||
/// The inverse of [`kind_name`], total in the other direction: anything else
|
||||
/// is not a kind this version writes.
|
||||
fn kind_of(name: &str) -> Option<SymbolKind> {
|
||||
Some(match name {
|
||||
"module" => SymbolKind::Module,
|
||||
"interface" => SymbolKind::Interface,
|
||||
"modport" => SymbolKind::Modport,
|
||||
"clocking" => SymbolKind::Clocking,
|
||||
"package" => SymbolKind::Package,
|
||||
"port" => SymbolKind::Port,
|
||||
"net" => SymbolKind::Net,
|
||||
"var" => SymbolKind::Var,
|
||||
"param" => SymbolKind::Param,
|
||||
"localparam" => SymbolKind::LocalParam,
|
||||
"genvar" => SymbolKind::Genvar,
|
||||
"typedef" => SymbolKind::Typedef,
|
||||
"enumvariant" => SymbolKind::EnumVariant,
|
||||
"function" => SymbolKind::Function,
|
||||
"task" => SymbolKind::Task,
|
||||
"tfarg" => SymbolKind::TfArg,
|
||||
"instance" => SymbolKind::Instance,
|
||||
"block" => SymbolKind::Block,
|
||||
"structmember" => SymbolKind::StructMember,
|
||||
"class" => SymbolKind::Class,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Every kind round-trips, and the two directions are inverses. If a
|
||||
/// variant is added to `SymbolKind` this fails to compile in `kind_name`
|
||||
/// first, which is the point of writing both matches out.
|
||||
#[test]
|
||||
fn every_symbol_kind_has_a_name_and_only_its_own() {
|
||||
let kinds = [
|
||||
SymbolKind::Module,
|
||||
SymbolKind::Interface,
|
||||
SymbolKind::Modport,
|
||||
SymbolKind::Clocking,
|
||||
SymbolKind::Package,
|
||||
SymbolKind::Port,
|
||||
SymbolKind::Net,
|
||||
SymbolKind::Var,
|
||||
SymbolKind::Param,
|
||||
SymbolKind::LocalParam,
|
||||
SymbolKind::Genvar,
|
||||
SymbolKind::Typedef,
|
||||
SymbolKind::EnumVariant,
|
||||
SymbolKind::Function,
|
||||
SymbolKind::Task,
|
||||
SymbolKind::TfArg,
|
||||
SymbolKind::Instance,
|
||||
SymbolKind::Block,
|
||||
SymbolKind::StructMember,
|
||||
SymbolKind::Class,
|
||||
];
|
||||
let mut names: Vec<&str> = kinds.iter().map(|k| kind_name(*k)).collect();
|
||||
for kind in kinds {
|
||||
assert_eq!(kind_of(kind_name(kind)), Some(kind));
|
||||
}
|
||||
names.sort_unstable();
|
||||
let before = names.len();
|
||||
names.dedup();
|
||||
assert_eq!(names.len(), before, "two kinds share a name: {names:?}");
|
||||
assert_eq!(kind_of("Module"), None, "the names are exact");
|
||||
assert_eq!(kind_of(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_escape_survives_a_round_trip() {
|
||||
for text in ["", "plain", "a\tb", "a\nb", "a\\b", "a\\\\tb", "\r\n", "\\", "üñî"] {
|
||||
let mut out = Writer::default();
|
||||
out.text(text);
|
||||
let field = out.out;
|
||||
assert_eq!(unescape(&field).as_deref(), Some(text), "{text:?}");
|
||||
assert!(!field.contains('\t'), "a field never holds a raw tab: {field:?}");
|
||||
assert!(!field.contains('\n'), "nor a newline: {field:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escape_this_format_does_not_write_is_not_read() {
|
||||
assert_eq!(unescape("a\\qb"), None);
|
||||
assert_eq!(unescape("trailing\\"), None);
|
||||
}
|
||||
}
|
||||
+9
@@ -11,6 +11,13 @@
|
||||
//! Gate primitives are not instantiations here: `and (q, a, b)` is an
|
||||
//! [`ItemKind::GateInstantiation`], names no module, and is nobody's edge in
|
||||
//! the hierarchy.
|
||||
//!
|
||||
//! **Lifted from `lucisv_server` on 2026-08-27** so the workspace index can
|
||||
//! record instantiation edges as it builds
|
||||
//! (`docs/features/incremental-index/README.md`). The walk is the census —
|
||||
//! what counts as one instantiation site — and a second copy of it in the
|
||||
//! index would have been free to drift from the one the call hierarchy uses.
|
||||
//! The code is unchanged by the move.
|
||||
|
||||
use vlog_parser::ast::{GenBlock, GenElse, Instantiation, Item, ItemKind, Module};
|
||||
use vlog_parser::TextRange;
|
||||
@@ -19,6 +26,7 @@ use vlog_parser::TextRange;
|
||||
/// `module ... endmodule` it was written as.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Decl<'a> {
|
||||
/// The declaration node, for its name and its own items.
|
||||
pub module: &'a Module,
|
||||
/// Code extent of the declaration, attributes included — what a call
|
||||
/// hierarchy item's `range` is.
|
||||
@@ -27,6 +35,7 @@ pub struct Decl<'a> {
|
||||
|
||||
/// One module instantiation, and the module whose body it sits in.
|
||||
pub struct Site<'a> {
|
||||
/// The instantiation node: the module it names, and its connections.
|
||||
pub inst: &'a Instantiation,
|
||||
/// The innermost module the instantiation is written inside. `None` for
|
||||
/// one written at file scope — illegal SystemVerilog, and reachable
|
||||
+127
-12
@@ -17,18 +17,24 @@
|
||||
//! the simplifications taken.
|
||||
|
||||
mod bind;
|
||||
pub mod classes;
|
||||
mod facts;
|
||||
pub mod instantiations;
|
||||
mod model;
|
||||
mod resolve;
|
||||
mod scan;
|
||||
mod workspace;
|
||||
|
||||
pub use facts::{record_path, FACTS_FORMAT};
|
||||
pub use model::{
|
||||
DocumentSymbol, Import, Reference, ReferenceId, Resolution, Scope, ScopeId, ScopeKind, Symbol,
|
||||
SymbolId, SymbolKind,
|
||||
DocumentSymbol, Import, MemberSite, Reference, ReferenceId, Resolution, Scope, ScopeId,
|
||||
ScopeKind, Symbol, SymbolId, SymbolKind,
|
||||
};
|
||||
pub use workspace::{
|
||||
resolve_external, Def, Definition, ExternalResolutions, ExternalTarget, FileId, IndexCounts,
|
||||
WorkspaceIndex, WorkspaceSymbol,
|
||||
index_order, resolve_external, DeclLines, DeclPositions, DeclSite, Def, Definition,
|
||||
DefinitionKey, ExternalResolutions, ExternalTarget, FileFacts, FileId, IndexBuilder,
|
||||
IndexCounts, InheritanceEdge, InstanceOccurrence, InstantiationEdge, ReferenceSite, Utf16Pos,
|
||||
Utf16Range, WorkspaceIndex, WorkspaceSymbol,
|
||||
};
|
||||
|
||||
use std::collections::HashMap;
|
||||
@@ -43,6 +49,16 @@ pub struct Semantics {
|
||||
references: Vec<Reference>,
|
||||
/// symbol → indices into `references`, in source order.
|
||||
uses: HashMap<SymbolId, Vec<usize>>,
|
||||
/// Non-empty declaration-name spans, sorted by start for cursor lookup.
|
||||
symbol_positions: Vec<(TextRange, SymbolId)>,
|
||||
/// Non-empty reference-name spans, sorted by start for cursor lookup.
|
||||
reference_positions: Vec<(TextRange, ReferenceId)>,
|
||||
/// Every symbol id, sorted by the name it declares, ties in declaration
|
||||
/// order — so looking a name up is a binary search rather than a walk of
|
||||
/// every symbol. A side table rather than a `HashMap<String, _>` because
|
||||
/// this way `Semantics` does not carry a second copy of every name it
|
||||
/// already holds, and it is cloned per document.
|
||||
by_name: Vec<SymbolId>,
|
||||
}
|
||||
|
||||
/// Build the symbol table for one parsed file. `src` must be the text the
|
||||
@@ -60,11 +76,18 @@ pub fn analyze(file: &SourceFile, src: &str) -> Semantics {
|
||||
|
||||
let mut references = Vec::with_capacity(pending.len());
|
||||
for p in &pending {
|
||||
// A pending use pass two has nothing to say about is not a reference
|
||||
// at all — the member tail of `a.b` where `a`'s type is not one this
|
||||
// crate can look members up in (`resolve::member_of`). Every other
|
||||
// target always resolves, `NotFound` included.
|
||||
let Some(resolution) = resolve::resolve(&scopes, &symbols, p) else {
|
||||
continue;
|
||||
};
|
||||
references.push(Reference {
|
||||
name: p.name.clone(),
|
||||
name_span: p.name_span,
|
||||
scope: p.scope,
|
||||
resolution: resolve::resolve(&scopes, &symbols, p),
|
||||
resolution,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -74,7 +97,26 @@ pub fn analyze(file: &SourceFile, src: &str) -> Semantics {
|
||||
uses.entry(id).or_default().push(i);
|
||||
}
|
||||
}
|
||||
Semantics { scopes, symbols, references, uses }
|
||||
let mut symbol_positions: Vec<(TextRange, SymbolId)> = symbols
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, symbol)| !symbol.name_span.is_empty())
|
||||
.map(|(i, symbol)| (symbol.name_span, SymbolId(i as u32)))
|
||||
.collect();
|
||||
symbol_positions.sort_by_key(|(span, _)| (span.start, span.end));
|
||||
let mut reference_positions: Vec<(TextRange, ReferenceId)> = references
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, reference)| !reference.name_span.is_empty())
|
||||
.map(|(i, reference)| (reference.name_span, ReferenceId(i as u32)))
|
||||
.collect();
|
||||
reference_positions.sort_by_key(|(span, _)| (span.start, span.end));
|
||||
// A *stable* sort by name, so symbols sharing a name keep the order they
|
||||
// were declared in — the order a caller filtering `symbols()` by name
|
||||
// would have seen, which is what makes swapping the two an identity.
|
||||
let mut by_name: Vec<SymbolId> = (0..symbols.len() as u32).map(SymbolId).collect();
|
||||
by_name.sort_by(|a, b| symbols[a.0 as usize].name.cmp(&symbols[b.0 as usize].name));
|
||||
Semantics { scopes, symbols, references, uses, symbol_positions, reference_positions, by_name }
|
||||
}
|
||||
|
||||
/// Point every import at the package it names, when this file declares it.
|
||||
@@ -122,24 +164,34 @@ impl Semantics {
|
||||
self.symbols.get(id.0 as usize)
|
||||
}
|
||||
|
||||
/// Every declaration that spells `name`, in declaration order — the same
|
||||
/// symbols, in the same order, that filtering [`Semantics::symbols`] by
|
||||
/// name yields, without walking the ones that cannot match.
|
||||
pub fn symbols_named(&self, name: &str) -> impl Iterator<Item = SymbolId> + '_ {
|
||||
// Two binary searches over the name-sorted side table: the first name
|
||||
// that is not less than the one asked for, then the first one past it.
|
||||
let spelling = |id: &SymbolId| self.symbol(*id).map_or("", |symbol| symbol.name.as_str());
|
||||
let start = self.by_name.partition_point(|id| spelling(id) < name);
|
||||
let rest = self.by_name.get(start..).unwrap_or(&[]);
|
||||
let end = rest.partition_point(|id| spelling(id) == name);
|
||||
rest.get(..end).unwrap_or(&[]).iter().copied()
|
||||
}
|
||||
|
||||
/// The declaration whose *name* covers `offset` — a cursor sitting on a
|
||||
/// declared name, not anywhere in its declaration.
|
||||
pub fn symbol_at(&self, offset: u32) -> Option<SymbolId> {
|
||||
self.symbols.iter().position(|s| s.name_span.contains(offset)).map(|i| SymbolId(i as u32))
|
||||
position_at(&self.symbol_positions, offset)
|
||||
}
|
||||
|
||||
/// The use whose name covers `offset`.
|
||||
pub fn reference_at(&self, offset: u32) -> Option<&Reference> {
|
||||
self.references.iter().find(|r| r.name_span.contains(offset))
|
||||
self.reference_id_at(offset).and_then(|id| self.reference(id))
|
||||
}
|
||||
|
||||
/// The id of the use whose name covers `offset` — the key the workspace
|
||||
/// index's overlay uses.
|
||||
pub fn reference_id_at(&self, offset: u32) -> Option<ReferenceId> {
|
||||
self.references
|
||||
.iter()
|
||||
.position(|r| r.name_span.contains(offset))
|
||||
.map(|i| ReferenceId(i as u32))
|
||||
position_at(&self.reference_positions, offset)
|
||||
}
|
||||
|
||||
/// One use by id.
|
||||
@@ -206,8 +258,71 @@ impl Semantics {
|
||||
(self.references.iter().filter(|r| r.resolved().is_some()).count(), self.references.len())
|
||||
}
|
||||
|
||||
/// Where `head.mids….` puts the cursor: the site the next `.name` would
|
||||
/// be looked up in, with nothing looked up yet.
|
||||
///
|
||||
/// **The prefix of the walk that resolves `head.mids….name`**, and the
|
||||
/// same code — `resolve::member_of` is this function plus one lookup in
|
||||
/// what it returns. That is the whole point of it: a completion list
|
||||
/// after a `.` must offer exactly the names hover and go-to-definition
|
||||
/// would resolve there, and the only way to promise that is to ask the
|
||||
/// same question of the same walk.
|
||||
///
|
||||
/// `head` is the first identifier of the spine, `mids` the names between
|
||||
/// it and the cursor (`item.hdr.` is `head = "item"`, `mids = ["hdr"]`).
|
||||
/// `this` and `super` are accepted as heads and mean the enclosing class
|
||||
/// and its base. `None` means this crate has nothing to say — an
|
||||
/// unresolvable head, a type it cannot look members up in, a chain it
|
||||
/// cannot finish — and a caller must answer nothing rather than guess.
|
||||
pub fn member_site(&self, from: ScopeId, head: &str, mids: &[String]) -> Option<MemberSite> {
|
||||
resolve::member_site(&self.scopes, &self.symbols, from, head, mids)
|
||||
}
|
||||
|
||||
/// Where `path::` puts the cursor — the package or class the `::` reaches
|
||||
/// into, as a scope this file holds or as a workspace unit name.
|
||||
///
|
||||
/// The prefix of the walk that resolves `path::name`, on the same terms
|
||||
/// [`Semantics::member_site`] is the prefix of the other one. `None` when
|
||||
/// a `pkg::cls` path names a segment this file's own container does not
|
||||
/// hold — this file has answered, and the answer is nothing.
|
||||
pub fn unit_site(&self, from: ScopeId, path: &str) -> Option<MemberSite> {
|
||||
resolve::unit_site(&self.scopes, &self.symbols, from, path)
|
||||
}
|
||||
|
||||
/// The scope the module or interface `name` opens, when **this file**
|
||||
/// declares one — the scope a `.port` connection to it is resolved in.
|
||||
///
|
||||
/// Literally the call `resolve`'s [`Target::Port`] arm makes
|
||||
/// (`owning_scope(..., is_instantiable)`), so a completion list of a
|
||||
/// connection's legal names and the resolution of one of them look in one
|
||||
/// scope, found one way. `None` when this file does not declare the
|
||||
/// module — which is exactly when `Target::Port` hands the question to the
|
||||
/// workspace's member table instead.
|
||||
pub fn instantiable_scope(&self, name: &str) -> Option<ScopeId> {
|
||||
resolve::owning_scope(&self.scopes, &self.symbols, name, resolve::is_instantiable)
|
||||
}
|
||||
|
||||
/// Every scope a member of `scope` may be declared in, nearest first, and
|
||||
/// the base class the `extends` chain left this file at — `None` when it
|
||||
/// ended here.
|
||||
///
|
||||
/// The walk a member *lookup* takes, with the lookup left out, so that
|
||||
/// listing a class's members and resolving one of them cannot disagree
|
||||
/// about which classes are on the chain. For a non-class scope this is
|
||||
/// the scope itself and nothing more.
|
||||
pub fn member_scopes(&self, scope: ScopeId) -> (Vec<ScopeId>, Option<String>) {
|
||||
resolve::extends_chain(&self.scopes, &self.symbols, scope)
|
||||
}
|
||||
|
||||
/// The span the file covers, as the parser saw it.
|
||||
pub fn file_span(&self) -> TextRange {
|
||||
self.scopes.first().map_or(TextRange::empty(0), |s| s.span)
|
||||
}
|
||||
}
|
||||
|
||||
/// The source span covering `offset` in a non-overlapping, start-sorted table.
|
||||
fn position_at<Id: Copy>(positions: &[(TextRange, Id)], offset: u32) -> Option<Id> {
|
||||
let after = positions.partition_point(|(span, _)| span.start <= offset);
|
||||
let (span, id) = positions.get(after.checked_sub(1)?)?;
|
||||
span.contains(offset).then_some(*id)
|
||||
}
|
||||
@@ -21,6 +21,24 @@ pub struct ReferenceId(pub u32);
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SymbolKind {
|
||||
Module,
|
||||
/// An `interface … endinterface`. The parser models it as a
|
||||
/// [`vlog_parser::ast::Module`] with a different keyword, and everything an
|
||||
/// instantiation, a connection or a hierarchical name may do to a module it
|
||||
/// may do to an interface — so this kind travels beside `Module` almost
|
||||
/// everywhere ([`SymbolKind::is_instantiable`]). What it buys is the two
|
||||
/// places the two really differ: an editor label that says "interface", and
|
||||
/// an export rule that lets another file reach an interface's *signals*,
|
||||
/// which is what a `virtual bus_if vif; vif.sig` needs and what a module
|
||||
/// never grants. `program … endprogram` is still a `Module` — see
|
||||
/// `docs/features/interface-semantics/README.md`.
|
||||
Interface,
|
||||
/// A `modport mp (...)` inside an interface (IEEE 1800 §25.5): a named view
|
||||
/// of the interface's signals.
|
||||
Modport,
|
||||
/// A **named** `clocking cb @(...); … endclocking` block (IEEE 1800 §14.3).
|
||||
/// An anonymous `default clocking @(...)` declares no name and so no
|
||||
/// symbol.
|
||||
Clocking,
|
||||
Package,
|
||||
/// A module port, from either header style.
|
||||
Port,
|
||||
@@ -29,6 +47,21 @@ pub enum SymbolKind {
|
||||
/// A variable declaration (`logic`, `reg`, `int`, ...).
|
||||
Var,
|
||||
Param,
|
||||
/// A `localparam` — a constant the module derives for itself, written
|
||||
/// either in the body or inside the `#( … )` header after the keyword.
|
||||
///
|
||||
/// Parted from [`SymbolKind::Param`] on 2026-09-02 for one reason, and it
|
||||
/// is a *correctness* one rather than a labelling one: a `localparam` in a
|
||||
/// header is **not overridable**, so it must never be offered in a
|
||||
/// `#(.` override list, and the only place that fact survives is the
|
||||
/// keyword the source wrote. (QA found `prim_fifo_sync`'s header
|
||||
/// `localparam int DepthW = $clog2(Depth)` offered as an override.)
|
||||
/// Everything else a parameter can do a localparam can do too — it is read
|
||||
/// hierarchically (`u_fifo.DepthW` is legal and resolves), it is exported
|
||||
/// by the same units, it hovers and highlights the same way — so every
|
||||
/// other site treats the two alike and says so out loud.
|
||||
/// See `docs/features/member-completion/README.md`.
|
||||
LocalParam,
|
||||
Genvar,
|
||||
Typedef,
|
||||
/// A name introduced by an `enum` body, visible in the enclosing scope.
|
||||
@@ -47,6 +80,18 @@ pub enum SymbolKind {
|
||||
Class,
|
||||
}
|
||||
|
||||
impl SymbolKind {
|
||||
/// True for the kinds an *instantiation* may name: a `module` and an
|
||||
/// `interface`. An interface is instantiated exactly as a module is
|
||||
/// (`bus_if u_bus ();`), connected exactly as a module is, and shows up in
|
||||
/// the design hierarchy and the code lens on exactly the same terms — so
|
||||
/// every filter that used to spell `kind == Module` for "a thing you can
|
||||
/// instantiate" asks this instead, and answers what it always did.
|
||||
pub fn is_instantiable(self) -> bool {
|
||||
matches!(self, SymbolKind::Module | SymbolKind::Interface)
|
||||
}
|
||||
}
|
||||
|
||||
/// A declaration: a name bound in one scope.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Symbol {
|
||||
@@ -57,6 +102,24 @@ pub struct Symbol {
|
||||
/// Byte range of the construct that owns the name (the whole `module`,
|
||||
/// the whole declarator, the whole port declaration).
|
||||
pub decl_span: TextRange,
|
||||
/// Where the *complete* declaration is written, when that is not
|
||||
/// `decl_span`: a non-ANSI port's header names it and a body `input
|
||||
/// signed [31:0] data_in;` finishes it, so hover and go-to-definition
|
||||
/// point here — the line that carries the direction, the type and the
|
||||
/// width — while `name_span`/`decl_span` stay in the header. `None` for
|
||||
/// every declaration that is complete where it is named.
|
||||
pub detail_span: Option<TextRange>,
|
||||
/// The declared type **as written**, for the declarations that have one:
|
||||
/// `c1` for `c1 in_item`, `pkg::c1` for a qualified spelling,
|
||||
/// `clk_rst_if` for `virtual clk_rst_if vif`. `None` for a built-in type
|
||||
/// (`logic`, `bit`, `int` — a keyword names no declaration) and for every
|
||||
/// declaration that has no type at all (a module, a block label, an
|
||||
/// instance). It is a *name*, not a resolved type: what member access
|
||||
/// (`handle.member`) needs is the spelling to look the type up with, and
|
||||
/// resolving it is `resolve.rs`'s business, on the same lexical chain the
|
||||
/// type reference itself takes. See
|
||||
/// `docs/features/class-member-access/README.md`.
|
||||
pub type_name: Option<String>,
|
||||
/// The scope the name is bound in.
|
||||
pub scope: ScopeId,
|
||||
/// The scope this declaration opens, for the kinds that open one
|
||||
@@ -82,12 +145,13 @@ pub enum Resolution {
|
||||
/// `extends` could: `base` is the base-class path as written
|
||||
/// (`uvm_component`, `pkg::base`), and `paths` are the import paths the
|
||||
/// lexical walk collected — plus the use's own name when it was written in
|
||||
/// a type position — any of which could supply it. Nothing chases `base`,
|
||||
/// in this file or out of it; the
|
||||
/// workspace overlay may answer from `paths` without displacing what this
|
||||
/// says, because a resolved base would have been `Resolved` already. See
|
||||
/// `docs/features/class-semantics/README.md` and
|
||||
/// `docs/features/overlay-promotion/README.md`.
|
||||
/// a type position — any of which could supply it. The single-file layer
|
||||
/// never chases `base`; the workspace overlay now does, upward through
|
||||
/// [`crate::WorkspaceIndex::base_of`] after its `paths` miss, without
|
||||
/// displacing what this says — a base resolved *in this file* would have
|
||||
/// been `Resolved` already. See `docs/features/class-semantics/README.md`,
|
||||
/// `docs/features/overlay-promotion/README.md` and
|
||||
/// `docs/features/class-member-access/README.md`.
|
||||
InheritedCandidate { base: String, paths: Vec<String> },
|
||||
/// Nothing in this file binds it and no external unit could: a member of a
|
||||
/// package this file fully declares, a `.port` of a module it declares, a
|
||||
@@ -98,6 +162,34 @@ pub enum Resolution {
|
||||
NotFound,
|
||||
}
|
||||
|
||||
/// Where the `.name` after a head is looked up: a scope this file holds, or
|
||||
/// the composed workspace path the index answers by.
|
||||
///
|
||||
/// This is the **prefix** of a member resolution, split out so that a caller
|
||||
/// wanting the *list* of members (completion) and the caller wanting one of
|
||||
/// them (hover, definition, references) walk the same steps —
|
||||
/// [`Semantics::member_site`](crate::Semantics::member_site) is what
|
||||
/// `resolve::member_of` itself runs before looking the tail up, and
|
||||
/// [`Semantics::unit_site`](crate::Semantics::unit_site) is what
|
||||
/// `resolve::unit_member` runs. A second answer to "where do this head's
|
||||
/// members live" would eventually disagree with the first, which is the one
|
||||
/// thing the member-resolution rounds forbid.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum MemberSite {
|
||||
/// A class, module, interface or `struct` body **this file declares**.
|
||||
/// The members are the scope's own symbols, plus — for a class — those of
|
||||
/// every scope [`Semantics::member_scopes`](crate::Semantics::member_scopes)
|
||||
/// adds from the `extends` chain.
|
||||
Scope(ScopeId),
|
||||
/// A type this file does not declare, as the unit name plus any member
|
||||
/// names already selected from it — `pkt_t`, `pkt_t::hdr` — in exactly the
|
||||
/// spelling [`crate::WorkspaceIndex`]'s member lookup walks. The tail
|
||||
/// resolution appends `::<name>` to it and hands the result to
|
||||
/// `follow_one`; the *list* is
|
||||
/// [`WorkspaceIndex::members_of_chain`](crate::WorkspaceIndex::members_of_chain).
|
||||
Unit(String),
|
||||
}
|
||||
|
||||
/// A *use* of a name: an expression identifier, a type name, an instantiated
|
||||
/// module's name, a `.port` in a connection list, a package in an `import`.
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -134,6 +226,12 @@ impl Reference {
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ScopeKind {
|
||||
File,
|
||||
/// A `module`, an `interface` or a `program` body. One kind for all three
|
||||
/// because a scope's kind governs *lookup rules*, and those are identical:
|
||||
/// names bind in declaration order, imports are consulted, the enclosing
|
||||
/// scope is the file. What differs between a module and an interface is
|
||||
/// which of its members another file may reach, and that is a property of
|
||||
/// the declaration ([`SymbolKind::Interface`]), not of the scope.
|
||||
Module,
|
||||
Package,
|
||||
Function,
|
||||
@@ -208,6 +306,12 @@ impl Scope {
|
||||
pub fn lookup_local(&self, name: &str) -> Option<SymbolId> {
|
||||
self.names.get(name).copied()
|
||||
}
|
||||
|
||||
/// The `extends` path this class scope was written with, as written.
|
||||
/// `None` for every other scope, and for a class that extends nothing.
|
||||
pub fn extends(&self) -> Option<&str> {
|
||||
self.extends.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
/// One node of the outline tree returned by
|
||||
|
||||
@@ -5,21 +5,30 @@
|
||||
//! requires at module scope and what an editor needs mid-edit.
|
||||
|
||||
use crate::bind::{Pending, Target};
|
||||
use crate::model::{Resolution, Scope, ScopeId, Symbol, SymbolId, SymbolKind};
|
||||
use crate::model::{MemberSite, Resolution, Scope, ScopeId, Symbol, SymbolId, SymbolKind};
|
||||
|
||||
/// Resolve one pending use against the finished scope tree.
|
||||
pub(crate) fn resolve(scopes: &[Scope], symbols: &[Symbol], p: &Pending) -> Resolution {
|
||||
match &p.target {
|
||||
///
|
||||
/// `None` means **record no reference at all**: the targets that can arrive
|
||||
/// here with nothing to say are [`Target::MemberOf`] (the tail of `a.b`),
|
||||
/// [`Target::InScope`] (a modport or clocking name) and [`Target::TypeMember`]
|
||||
/// (the `mp` of `bus_if.mp`) — each answered only when this crate can say
|
||||
/// something honest about it. Every other target always produces a resolution,
|
||||
/// `NotFound` included, exactly as it did before.
|
||||
pub(crate) fn resolve(scopes: &[Scope], symbols: &[Symbol], p: &Pending) -> Option<Resolution> {
|
||||
Some(match &p.target {
|
||||
// An end label names the construct it closes; the binder already knew
|
||||
// which symbol that is, so there is nothing to look up.
|
||||
Target::Declaration(id) => Resolution::Resolved(*id),
|
||||
Target::Lexical => lexical(scopes, p.scope, &p.name, false),
|
||||
Target::Type => lexical(scopes, p.scope, &p.name, true),
|
||||
Target::Package => named_at_file_scope(scopes, symbols, &p.name, SymbolKind::Package),
|
||||
Target::Module => named_at_file_scope(scopes, symbols, &p.name, SymbolKind::Module),
|
||||
Target::Package => named_at_file_scope(scopes, symbols, &p.name, is_package),
|
||||
// An interface is instantiated, connected and hierarchically named
|
||||
// exactly as a module is, so both kinds answer here.
|
||||
Target::Module => named_at_file_scope(scopes, symbols, &p.name, is_instantiable),
|
||||
Target::Unit => unit(scopes, symbols, p.scope, &p.name),
|
||||
Target::UnitMember(unit) => unit_member(scopes, symbols, p.scope, unit, &p.name),
|
||||
Target::Port(module) => match owning_scope(scopes, symbols, module, SymbolKind::Module) {
|
||||
Target::Port(module) => match owning_scope(scopes, symbols, module, is_instantiable) {
|
||||
Some(scope) => match scopes[scope.0 as usize].lookup_local(&p.name) {
|
||||
Some(id) => Resolution::Resolved(id),
|
||||
None => Resolution::NotFound,
|
||||
@@ -27,11 +36,465 @@ pub(crate) fn resolve(scopes: &[Scope], symbols: &[Symbol], p: &Pending) -> Reso
|
||||
// The port list lives in whatever file declares the module.
|
||||
None => Resolution::ExternalCandidate { paths: vec![module.clone()] },
|
||||
},
|
||||
Target::ThisMember => this_member(scopes, p.scope, &p.name),
|
||||
Target::InScope => return in_scope(scopes, p.scope, &p.name),
|
||||
Target::TypeMember { unit } => return type_member(scopes, symbols, p.scope, unit, &p.name),
|
||||
Target::MemberOf { head, mids } => {
|
||||
return member_of(scopes, symbols, p.scope, head, mids, &p.name)
|
||||
}
|
||||
Target::ThisMember => this_member(scopes, symbols, p.scope, &p.name),
|
||||
Target::SuperMember => super_member(scopes, p.scope),
|
||||
})
|
||||
}
|
||||
|
||||
/// A name looked up **only** in the scope it is written in, never outward: a
|
||||
/// modport's port list and a clocking block's signal list, both of which name
|
||||
/// members of the interface (or module) they are written in and nothing else.
|
||||
///
|
||||
/// `None` — no reference recorded at all — when that scope does not bind the
|
||||
/// name. The construct is written here whole, so no other file can supply the
|
||||
/// name; and walking outward to find *something* is exactly the wrong answer
|
||||
/// this crate refuses to give, because a file-scope `other_if` is not the
|
||||
/// signal `modport mp (input other_if)` was meant to name.
|
||||
fn in_scope(scopes: &[Scope], scope: ScopeId, name: &str) -> Option<Resolution> {
|
||||
scopes.get(scope.0 as usize)?.lookup_local(name).map(Resolution::Resolved)
|
||||
}
|
||||
|
||||
/// The `mp` of a glued `bus_if.mp` type name: a member of the *type*, looked
|
||||
/// up on exactly the terms [`member_of`]'s last link is.
|
||||
///
|
||||
/// The interface's scope when this file declares it — a hit is the modport's
|
||||
/// declaration, a miss is nothing at all, because this file has answered what
|
||||
/// `bus_if` is and it holds no such modport. A name this file declares as
|
||||
/// something without members ([`TypeHere::NotAUnit`]) is nothing either. Only a
|
||||
/// name **nothing here declares** reaches the workspace, as the one composed
|
||||
/// path `follow_one` reads back as `member(bus_if, mp)`.
|
||||
fn type_member(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
from: ScopeId,
|
||||
unit: &str,
|
||||
name: &str,
|
||||
) -> Option<Resolution> {
|
||||
match type_here(scopes, symbols, from, unit) {
|
||||
TypeHere::Scope(scope) => {
|
||||
scopes.get(scope.0 as usize)?.lookup_local(name).map(Resolution::Resolved)
|
||||
}
|
||||
TypeHere::NotAUnit => None,
|
||||
TypeHere::Absent => Some(Resolution::ExternalCandidate {
|
||||
paths: vec![format!("{}::{name}", last_segment(unit))],
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `member` of `head.mids….member`: the head is resolved on the ordinary
|
||||
/// lexical chain, its **declared type** is resolved on the same chain, each
|
||||
/// name in `mids` is looked up in that type's scope (and up its `extends`
|
||||
/// chain) to give the next type, and the tail is looked up in the last one.
|
||||
///
|
||||
/// `None` — no reference recorded at all — whenever this crate has nothing to
|
||||
/// say, which is the shape every pre-2026-09-01 hierarchical name had: a head
|
||||
/// nothing in this file declares, a head that is neither typed nor a unit a
|
||||
/// hierarchical name may start at (a `logic [3:0]`, a block label, a
|
||||
/// built-in), a type **this file declares** as something with no members to
|
||||
/// search (a struct or enum typedef — see [`TypeHere::NotAUnit`]), or a
|
||||
/// member genuinely absent from a class this file declares whole. Recording a
|
||||
/// `NotFound` for those would move `reference_at` under every `a.b` in the
|
||||
/// corpus to answer "a name that resolves to nothing", which is a different
|
||||
/// claim than "not modelled". **A link that cannot be resolved honestly stops
|
||||
/// the chain**: nothing is recorded for it or for anything after it.
|
||||
///
|
||||
/// Only a type name **nothing in this file declares** reaches the workspace.
|
||||
/// The distinction is the whole of QA finding 1 (2026-09-01): a `bus_t` this
|
||||
/// file declares as a struct typedef must not be asked about in a workspace
|
||||
/// where some unrelated file declares a *class* `bus_t`, or `s.field` lands on
|
||||
/// a stranger's property — a wrong answer, where recording nothing is merely a
|
||||
/// missing one.
|
||||
fn member_of(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
from: ScopeId,
|
||||
head: &str,
|
||||
mids: &[String],
|
||||
name: &str,
|
||||
) -> Option<Resolution> {
|
||||
match member_site(scopes, symbols, from, head, mids)? {
|
||||
MemberSite::Scope(scope) => match member_in_chain(scopes, symbols, scope, name) {
|
||||
Ok(id) => Some(Resolution::Resolved(id)),
|
||||
// The chain leaves this file: the base, plus the path the
|
||||
// workspace's member table answers it by. Only a **direct**
|
||||
// `head.member` reports the base — for a longer chain the base is
|
||||
// the owner of an earlier link, not of this name, and claiming it
|
||||
// here would send the overlay's inheritance chase after the wrong
|
||||
// class.
|
||||
Err(Some(base)) if mids.is_empty() => Some(Resolution::InheritedCandidate {
|
||||
paths: vec![format!("{}::{name}", last_segment(&base))],
|
||||
base,
|
||||
}),
|
||||
Err(Some(base)) => Some(Resolution::ExternalCandidate {
|
||||
paths: vec![format!("{}::{name}", last_segment(&base))],
|
||||
}),
|
||||
// A class this file declares whole, with no such member: nothing
|
||||
// to say that `NotFound` would not overstate.
|
||||
Err(None) => None,
|
||||
},
|
||||
// A type this file does not declare: the workspace's member table is
|
||||
// the only layer that can say. The last `::` segment names the unit,
|
||||
// the spelling `follow_one` turns back into `member(unit, name)`.
|
||||
MemberSite::Unit(path) => {
|
||||
Some(Resolution::ExternalCandidate { paths: vec![format!("{path}::{name}")] })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// **The prefix of [`member_of`]**, and the whole of what a completion list
|
||||
/// after a `.` needs: where `head.mids….` puts the cursor, with no tail
|
||||
/// looked up yet.
|
||||
///
|
||||
/// One walk, called by both — `member_of` is this function plus one lookup in
|
||||
/// what it returns. Every stopping condition is therefore shared: a head
|
||||
/// nothing here declares, a head with no type this crate can look members up
|
||||
/// in, a mid that leaves the chain unfinishable. `None` means *nothing to
|
||||
/// say*, which for a completion list means no popup and for a resolution
|
||||
/// means no reference recorded.
|
||||
///
|
||||
/// `this` and `super` are heads here even though [`Target::MemberOf`] never
|
||||
/// carries them (the binder sends those to [`this_member`]/[`super_member`],
|
||||
/// which resolve one member and stop): a `this.` popup is asking the same
|
||||
/// question about the same class, and answering it from the same walk is what
|
||||
/// keeps the two from drifting. `super` names the first hop of the `extends`
|
||||
/// chain — the base's scope when this file declares it, the base's *name*
|
||||
/// when it does not, which is the unit the overlay's own chase starts at.
|
||||
pub(crate) fn member_site(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
from: ScopeId,
|
||||
head: &str,
|
||||
mids: &[String],
|
||||
) -> Option<MemberSite> {
|
||||
let mut here = head_site(scopes, symbols, from, head)?;
|
||||
for mid in mids {
|
||||
here = match here {
|
||||
MemberSite::Scope(scope) => match member_in_chain(scopes, symbols, scope, mid) {
|
||||
Ok(id) => link_type(scopes, symbols, id)?,
|
||||
// The chain leaves this file at a base class: everything from
|
||||
// here on is one composed path for the workspace to walk.
|
||||
Err(Some(base)) => MemberSite::Unit(format!("{}::{mid}", last_segment(&base))),
|
||||
Err(None) => return None,
|
||||
},
|
||||
// Already outside this file — each further name is one more
|
||||
// segment of the path `follow_one` walks member by member.
|
||||
MemberSite::Unit(path) => MemberSite::Unit(format!("{path}::{mid}")),
|
||||
};
|
||||
}
|
||||
Some(here)
|
||||
}
|
||||
|
||||
/// Where the *first* segment of a spine puts the cursor.
|
||||
fn head_site(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
from: ScopeId,
|
||||
head: &str,
|
||||
) -> Option<MemberSite> {
|
||||
match head {
|
||||
// Neither is a name this crate binds, so neither goes through
|
||||
// `lexical`; both are the enclosing class, one hop apart.
|
||||
"this" => nearest_class(scopes, from).map(MemberSite::Scope),
|
||||
"super" => {
|
||||
let class = nearest_class(scopes, from)?;
|
||||
let (chain, base) = extends_chain(scopes, symbols, class);
|
||||
match chain.get(1) {
|
||||
Some(&base_scope) => Some(MemberSite::Scope(base_scope)),
|
||||
None => Some(MemberSite::Unit(last_segment(&base?).to_string())),
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let Resolution::Resolved(id) = lexical(scopes, from, head, false) else {
|
||||
return None;
|
||||
};
|
||||
link_type(scopes, symbols, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// **The prefix of [`unit_member`]**: which unit `unit::` names, without
|
||||
/// looking a member up in it.
|
||||
///
|
||||
/// The same outward walk, with the same kind filter — a package or class
|
||||
/// declared here answers with its own scope, a `typedef class c;` forward
|
||||
/// declaration and a name nothing here declares answer with the workspace
|
||||
/// unit, and a non-unit shadower is stepped over. A `pkg::cls` path descends
|
||||
/// segment by segment afterwards, on [`type_here`]'s terms: a segment missing
|
||||
/// from a container this file holds is `None`, because this file has answered
|
||||
/// what the container holds.
|
||||
pub(crate) fn unit_site(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
from: ScopeId,
|
||||
path: &str,
|
||||
) -> Option<MemberSite> {
|
||||
let mut segments = path.split("::");
|
||||
let mut here = unit_scope(scopes, symbols, from, segments.next()?);
|
||||
for segment in segments {
|
||||
here = match here {
|
||||
MemberSite::Scope(scope) => {
|
||||
let id = scopes.get(scope.0 as usize)?.lookup_local(segment)?;
|
||||
MemberSite::Scope(container_scope(symbols, id)?)
|
||||
}
|
||||
MemberSite::Unit(unit) => MemberSite::Unit(format!("{unit}::{segment}")),
|
||||
};
|
||||
}
|
||||
Some(here)
|
||||
}
|
||||
|
||||
/// One `::` segment: the scope this file opens for it, else the workspace
|
||||
/// unit of that name. Never `None` — a name nothing here declares is exactly
|
||||
/// what the index is for.
|
||||
fn unit_scope(scopes: &[Scope], symbols: &[Symbol], from: ScopeId, unit: &str) -> MemberSite {
|
||||
let mut current = Some(from);
|
||||
while let Some(id) = current {
|
||||
let scope = &scopes[id.0 as usize];
|
||||
if let Some(sym) = scope.lookup_local(unit) {
|
||||
match symbols[sym.0 as usize].kind {
|
||||
SymbolKind::Package | SymbolKind::Class => {
|
||||
if let Some(child) = symbols[sym.0 as usize].child_scope {
|
||||
return MemberSite::Scope(child);
|
||||
}
|
||||
}
|
||||
// `typedef class c;` promises the class lives elsewhere.
|
||||
SymbolKind::Typedef => break,
|
||||
// A non-unit shadower; keep walking outward.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
current = scope.parent;
|
||||
}
|
||||
MemberSite::Unit(unit.to_string())
|
||||
}
|
||||
|
||||
/// Where the members of one declaration live: its **declared type**'s scope
|
||||
/// when this file declares that type, else the workspace path for it.
|
||||
///
|
||||
/// A declaration with no declared type at all can still be a chain's head when
|
||||
/// it opens a scope a `.` may name members of — a module or an interface,
|
||||
/// which is how `tb.dut.u_core.sig` reaches into `tb` (IEEE 1800 §23.6: a
|
||||
/// top-level module name is the root of a hierarchical path), or a class,
|
||||
/// where the answer can only ever be that very class's own member. Everything
|
||||
/// else — a `logic` net, a genvar, a block label, a package — answers `None`,
|
||||
/// which stops the chain.
|
||||
fn link_type(scopes: &[Scope], symbols: &[Symbol], id: SymbolId) -> Option<MemberSite> {
|
||||
let symbol = symbols.get(id.0 as usize)?;
|
||||
let Some(type_name) = symbol.type_name.as_deref() else {
|
||||
return member_scope(scopes, symbols, id).map(MemberSite::Scope);
|
||||
};
|
||||
// The type name is looked up where the declaration is written, by the same
|
||||
// walk the type *reference* itself took.
|
||||
match type_here(scopes, symbols, symbol.scope, type_name) {
|
||||
TypeHere::Scope(scope) => Some(MemberSite::Scope(scope)),
|
||||
// This file says what the type is, and it is not something with
|
||||
// members. No other file can override that, so nothing is recorded.
|
||||
TypeHere::NotAUnit => None,
|
||||
TypeHere::Absent => Some(MemberSite::Unit(last_segment(type_name).to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` in a class (or interface) scope this file holds, then up its
|
||||
/// `extends` chain as far as this file goes.
|
||||
///
|
||||
/// `Ok` is the declaration; `Err(Some(base))` means the chain left this file
|
||||
/// at `base`, which the workspace index chases further
|
||||
/// ([`crate::WorkspaceIndex::base_of`]); `Err(None)` means the chain ended
|
||||
/// here — every class on it is declared in this file and none of them binds
|
||||
/// the name.
|
||||
fn member_in_chain(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
scope: ScopeId,
|
||||
name: &str,
|
||||
) -> Result<SymbolId, Option<String>> {
|
||||
let (chain, base) = extends_chain(scopes, symbols, scope);
|
||||
for id in chain {
|
||||
if let Some(found) = scopes[id.0 as usize].lookup_local(name) {
|
||||
return Ok(found);
|
||||
}
|
||||
}
|
||||
Err(base)
|
||||
}
|
||||
|
||||
/// **The walk [`member_in_chain`] does**, with the lookup left to the caller:
|
||||
/// every scope a member of `scope` may be declared in, nearest first, and the
|
||||
/// base the chain left this file at (`None` when it ended here — a class
|
||||
/// extending nothing, a cycle, or a chain every link of which this file
|
||||
/// declares).
|
||||
///
|
||||
/// Split out so that a completion list of *all* the members and a resolution
|
||||
/// of *one* of them cannot walk different chains: [`member_in_chain`] is this
|
||||
/// function plus a `lookup_local` in each scope it names, in the same order,
|
||||
/// which is the same first-hit-wins shadowing it always had.
|
||||
///
|
||||
/// `extends` can be written in a cycle; the visited set is what makes this
|
||||
/// terminate on `class a extends b; class b extends a;`.
|
||||
pub(crate) fn extends_chain(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
scope: ScopeId,
|
||||
) -> (Vec<ScopeId>, Option<String>) {
|
||||
let mut visited: Vec<ScopeId> = Vec::new();
|
||||
let mut current = scope;
|
||||
loop {
|
||||
if visited.contains(¤t) {
|
||||
return (visited, None);
|
||||
}
|
||||
visited.push(current);
|
||||
let Some(base) = &scopes[current.0 as usize].extends else {
|
||||
return (visited, None);
|
||||
};
|
||||
match type_here(scopes, symbols, enclosing(scopes, current), base) {
|
||||
TypeHere::Scope(next) => current = next,
|
||||
// Whether the base is absent from this file or declared here as
|
||||
// something without a member scope — a `typedef class base;`
|
||||
// forward declaration is exactly that — it is the workspace's to
|
||||
// finish. `extends` names a class by the grammar's own claim, so
|
||||
// asking the index about it is not the guess `member_of`'s
|
||||
// `NotAUnit` arm refuses to make about a data declaration's type.
|
||||
TypeHere::NotAUnit | TypeHere::Absent => return (visited, Some(base.clone())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The scope enclosing one — a class's base is resolved from *outside* it, as
|
||||
/// `extends` itself is (class-semantics rule 5).
|
||||
fn enclosing(scopes: &[Scope], scope: ScopeId) -> ScopeId {
|
||||
scopes[scope.0 as usize].parent.unwrap_or(ScopeId(0))
|
||||
}
|
||||
|
||||
/// What **this file** says about a type name — the three-way answer
|
||||
/// `handle.member` needs, where a two-way one is a wrong answer waiting to
|
||||
/// happen (QA finding 1, 2026-09-01).
|
||||
enum TypeHere {
|
||||
/// Declared here as something with members to look in: a class, a module,
|
||||
/// or an interface — so `virtual clk_rst_if vif; vif.clk` reaches the
|
||||
/// interface's signals.
|
||||
Scope(ScopeId),
|
||||
/// Declared here as something else — a struct, enum or alias `typedef`, a
|
||||
/// parameter, a variable shadowing the name. This file has *answered* the
|
||||
/// question "what is this type", and the answer is one with no members
|
||||
/// this crate models (struct fields are round 2, `docs/topo.md` §2.9-13).
|
||||
/// No other file can override that answer, so the workspace is never
|
||||
/// asked — which is what keeps a locally-declared `bus_t` from being
|
||||
/// looked up in a stranger's class of the same name.
|
||||
NotAUnit,
|
||||
/// Nothing in this file declares the name at all — the only case the
|
||||
/// workspace's tables can honestly answer.
|
||||
Absent,
|
||||
}
|
||||
|
||||
/// Look a written type name up in this file: on the lexical chain for its
|
||||
/// first segment, then descended segment by segment for `pkg::cls`.
|
||||
///
|
||||
/// The first segment goes through [`lexical`] itself — the same walk, the same
|
||||
/// shadowing, the same import precedence the type *reference* took — so what
|
||||
/// this says and what go-to-definition on the type name answers cannot
|
||||
/// disagree. A qualified path then descends only through containers: a
|
||||
/// package, class or module scope. A segment missing from a container this
|
||||
/// file holds is [`TypeHere::NotAUnit`], not [`TypeHere::Absent`] — the
|
||||
/// container is fully known here, the same reason [`unit_member`] answers a
|
||||
/// missing package member with `NotFound` rather than sending it to the
|
||||
/// workspace (vlog-semantic rule 6).
|
||||
///
|
||||
/// A name landing on a `typedef` **that aliases another type** is followed to
|
||||
/// what it aliases (`typedef c1 my_t;` → `c1`), from the typedef's own scope,
|
||||
/// as many hops as are written; `seen` is what makes a chain of aliases that
|
||||
/// meets itself terminate. A typedef with no aliased type — a `struct`, an
|
||||
/// `enum`, an alias of a built-in, a `typedef class c;` forward declaration —
|
||||
/// stays [`TypeHere::NotAUnit`] exactly as it was: this file has answered what
|
||||
/// the type is, and the answer has no members this crate models.
|
||||
fn type_here(scopes: &[Scope], symbols: &[Symbol], from: ScopeId, path: &str) -> TypeHere {
|
||||
type_here_seen(scopes, symbols, from, path, &mut Vec::new())
|
||||
}
|
||||
|
||||
fn type_here_seen(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
from: ScopeId,
|
||||
path: &str,
|
||||
seen: &mut Vec<SymbolId>,
|
||||
) -> TypeHere {
|
||||
let mut segments = path.split("::");
|
||||
let Some(head) = segments.next() else {
|
||||
return TypeHere::Absent;
|
||||
};
|
||||
let Resolution::Resolved(mut current) = lexical(scopes, from, head, false) else {
|
||||
return TypeHere::Absent;
|
||||
};
|
||||
for segment in segments {
|
||||
let Some(scope) = container_scope(symbols, current) else {
|
||||
return TypeHere::NotAUnit;
|
||||
};
|
||||
match scopes.get(scope.0 as usize).and_then(|s| s.lookup_local(segment)) {
|
||||
Some(next) => current = next,
|
||||
None => return TypeHere::NotAUnit,
|
||||
}
|
||||
}
|
||||
if let Some(scope) = member_scope(scopes, symbols, current) {
|
||||
return TypeHere::Scope(scope);
|
||||
}
|
||||
match alias_target(symbols, current) {
|
||||
Some((aliased, written_in)) if !seen.contains(¤t) => {
|
||||
seen.push(current);
|
||||
type_here_seen(scopes, symbols, written_in, &aliased, seen)
|
||||
}
|
||||
_ => TypeHere::NotAUnit,
|
||||
}
|
||||
}
|
||||
|
||||
/// The type a `typedef` aliases, and the scope the alias is written in —
|
||||
/// `None` for every other declaration, and for a typedef whose target names no
|
||||
/// declaration at all (a `struct` or `enum` body, an alias of a built-in, a
|
||||
/// forward class declaration).
|
||||
fn alias_target(symbols: &[Symbol], id: SymbolId) -> Option<(String, ScopeId)> {
|
||||
let symbol = symbols.get(id.0 as usize)?;
|
||||
if symbol.kind != SymbolKind::Typedef {
|
||||
return None;
|
||||
}
|
||||
Some((symbol.type_name.clone()?, symbol.scope))
|
||||
}
|
||||
|
||||
/// The scope a symbol opens when it is a container a type path may pass
|
||||
/// *through*: a package, a class or a module.
|
||||
fn container_scope(symbols: &[Symbol], id: SymbolId) -> Option<ScopeId> {
|
||||
let symbol = symbols.get(id.0 as usize)?;
|
||||
matches!(symbol.kind, SymbolKind::Package | SymbolKind::Class)
|
||||
.then_some(symbol.child_scope)
|
||||
.or_else(|| symbol.kind.is_instantiable().then_some(symbol.child_scope))?
|
||||
}
|
||||
|
||||
/// The scope a symbol opens when a `.` may name its members: a class, a
|
||||
/// module, or an interface — which is what makes `vif.sig` and `u.internal`
|
||||
/// reach into one — **or** a `struct`/`union` body, whoever names it. A
|
||||
/// package is a container to pass through, never a thing a handle can be.
|
||||
///
|
||||
/// The struct half is deliberately written as "any symbol whose child scope is
|
||||
/// a struct body", not "a `Typedef` whose child scope is one": the same rule
|
||||
/// then serves all three ways a body gets named — the `typedef` that names it,
|
||||
/// an **anonymous** aggregate's own declarator (`struct { logic a; } s;`), and
|
||||
/// an **inline nested** member (`struct { struct { logic q; } ctrl; }`), where
|
||||
/// no type name exists to look anything up by. `docs/features/struct-members/README.md`.
|
||||
fn member_scope(scopes: &[Scope], symbols: &[Symbol], id: SymbolId) -> Option<ScopeId> {
|
||||
let symbol = symbols.get(id.0 as usize)?;
|
||||
if symbol.kind == SymbolKind::Class || symbol.kind.is_instantiable() {
|
||||
return symbol.child_scope;
|
||||
}
|
||||
let child = symbol.child_scope?;
|
||||
(scopes.get(child.0 as usize)?.kind == crate::model::ScopeKind::Struct).then_some(child)
|
||||
}
|
||||
|
||||
/// The last `::` segment of a possibly-qualified path (`pkg::cls` → `cls`) —
|
||||
/// the segment the workspace's member table is keyed by.
|
||||
fn last_segment(path: &str) -> &str {
|
||||
path.rsplit("::").next().unwrap_or(path)
|
||||
}
|
||||
|
||||
/// Walk the scope chain outward: names declared in a scope first, then the
|
||||
/// packages that scope imports, then the enclosing scope. A miss inside a
|
||||
/// class whose header says `extends` becomes an inheritance candidate — the
|
||||
@@ -140,58 +603,45 @@ fn unit_member(
|
||||
unit: &str,
|
||||
name: &str,
|
||||
) -> Resolution {
|
||||
let mut current = Some(from);
|
||||
while let Some(id) = current {
|
||||
let scope = &scopes[id.0 as usize];
|
||||
if let Some(sym) = scope.lookup_local(unit) {
|
||||
match symbols[sym.0 as usize].kind {
|
||||
SymbolKind::Package | SymbolKind::Class => {
|
||||
if let Some(child) = symbols[sym.0 as usize].child_scope {
|
||||
if let Some(found) = scopes[child.0 as usize].lookup_local(name) {
|
||||
return Resolution::Resolved(found);
|
||||
}
|
||||
return match (
|
||||
symbols[sym.0 as usize].kind,
|
||||
&scopes[child.0 as usize].extends,
|
||||
) {
|
||||
// A static member may be inherited; the base is
|
||||
// recorded, never chased.
|
||||
(SymbolKind::Class, Some(base)) => Resolution::InheritedCandidate {
|
||||
base: base.clone(),
|
||||
paths: Vec::new(),
|
||||
},
|
||||
// A package fully known locally: no workspace
|
||||
// index could change the answer.
|
||||
_ => Resolution::NotFound,
|
||||
};
|
||||
}
|
||||
match unit_scope(scopes, symbols, from, unit) {
|
||||
MemberSite::Scope(child) => {
|
||||
if let Some(found) = scopes[child.0 as usize].lookup_local(name) {
|
||||
return Resolution::Resolved(found);
|
||||
}
|
||||
// A static member may be inherited; the base is recorded, never
|
||||
// chased. Only a class scope carries an `extends`, so this is the
|
||||
// old `(SymbolKind::Class, Some(base))` arm exactly. A package
|
||||
// fully known locally is `NotFound`: no workspace index could
|
||||
// change the answer.
|
||||
match &scopes[child.0 as usize].extends {
|
||||
Some(base) => {
|
||||
Resolution::InheritedCandidate { base: base.clone(), paths: Vec::new() }
|
||||
}
|
||||
// `typedef class c;` promises the class lives elsewhere: the
|
||||
// member is the workspace's to find.
|
||||
SymbolKind::Typedef => {
|
||||
return Resolution::ExternalCandidate { paths: vec![format!("{unit}::{name}")] }
|
||||
}
|
||||
// A non-unit shadower; keep walking outward.
|
||||
_ => {}
|
||||
None => Resolution::NotFound,
|
||||
}
|
||||
}
|
||||
current = scope.parent;
|
||||
// Nothing here declares the unit, or a `typedef class c;` promises it
|
||||
// lives elsewhere: the member is the workspace's to find.
|
||||
MemberSite::Unit(_) => {
|
||||
Resolution::ExternalCandidate { paths: vec![format!("{unit}::{name}")] }
|
||||
}
|
||||
}
|
||||
Resolution::ExternalCandidate { paths: vec![format!("{unit}::{name}")] }
|
||||
}
|
||||
|
||||
/// `this.x`: the enclosing class's own scope only — a member access cannot
|
||||
/// name a method local or an enclosing module net.
|
||||
fn this_member(scopes: &[Scope], from: ScopeId, name: &str) -> Resolution {
|
||||
/// `this.x`: the enclosing class's own scope and the classes it extends — a
|
||||
/// member access cannot name a method local or an enclosing module net, but it
|
||||
/// can name an inherited member, and since 2026-09-01 the `extends` chain is
|
||||
/// walked as far as this file declares it (topo §2.9-9). A chain that leaves
|
||||
/// the file keeps the answer it has always given — the base, no paths — which
|
||||
/// the workspace overlay now chases through the member tables.
|
||||
fn this_member(scopes: &[Scope], symbols: &[Symbol], from: ScopeId, name: &str) -> Resolution {
|
||||
let Some(class) = nearest_class(scopes, from) else {
|
||||
return Resolution::NotFound;
|
||||
};
|
||||
if let Some(sym) = scopes[class.0 as usize].lookup_local(name) {
|
||||
return Resolution::Resolved(sym);
|
||||
}
|
||||
match &scopes[class.0 as usize].extends {
|
||||
Some(base) => Resolution::InheritedCandidate { base: base.clone(), paths: Vec::new() },
|
||||
None => Resolution::NotFound,
|
||||
match member_in_chain(scopes, symbols, class, name) {
|
||||
Ok(id) => Resolution::Resolved(id),
|
||||
Err(Some(base)) => Resolution::InheritedCandidate { base, paths: Vec::new() },
|
||||
Err(None) => Resolution::NotFound,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,39 +715,53 @@ fn is_unit_kind(symbols: &[Symbol], sym: SymbolId) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
/// The kind an `import p::…` may name.
|
||||
fn is_package(kind: SymbolKind) -> bool {
|
||||
kind == SymbolKind::Package
|
||||
}
|
||||
|
||||
/// The kinds an instantiation may name — a module or an interface.
|
||||
pub(crate) fn is_instantiable(kind: SymbolKind) -> bool {
|
||||
kind.is_instantiable()
|
||||
}
|
||||
|
||||
fn named_at_file_scope(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
name: &str,
|
||||
kind: SymbolKind,
|
||||
wanted: fn(SymbolKind) -> bool,
|
||||
) -> Resolution {
|
||||
match file_symbol(scopes, symbols, name, kind) {
|
||||
match file_symbol(scopes, symbols, name, wanted) {
|
||||
Some(id) => Resolution::Resolved(id),
|
||||
None => Resolution::ExternalCandidate { paths: vec![name.to_string()] },
|
||||
}
|
||||
}
|
||||
|
||||
fn owning_scope(
|
||||
/// The scope a file-scope declaration of `name` opens, when it is one of the
|
||||
/// `wanted` kinds.
|
||||
///
|
||||
/// `pub(crate)` since 2026-09-02 for [`crate::Semantics::instantiable_scope`],
|
||||
/// which is this function with [`is_instantiable`] passed in — the very call
|
||||
/// [`Target::Port`] makes. A connection list's completion and a `.port`
|
||||
/// resolution therefore look in one scope, found one way.
|
||||
pub(crate) fn owning_scope(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
name: &str,
|
||||
kind: SymbolKind,
|
||||
wanted: fn(SymbolKind) -> bool,
|
||||
) -> Option<ScopeId> {
|
||||
let id = file_symbol(scopes, symbols, name, kind)?;
|
||||
let id = file_symbol(scopes, symbols, name, wanted)?;
|
||||
symbols[id.0 as usize].child_scope
|
||||
}
|
||||
|
||||
/// Modules and packages are file-scope names, so one lookup finds them.
|
||||
/// Modules, interfaces and packages are file-scope names, so one lookup finds
|
||||
/// them.
|
||||
fn file_symbol(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
name: &str,
|
||||
kind: SymbolKind,
|
||||
wanted: fn(SymbolKind) -> bool,
|
||||
) -> Option<SymbolId> {
|
||||
let id = scopes.first()?.lookup_local(name)?;
|
||||
if symbols.get(id.0 as usize)?.kind == kind {
|
||||
Some(id)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
wanted(symbols.get(id.0 as usize)?.kind).then_some(id)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -5,8 +5,8 @@
|
||||
use std::path::PathBuf;
|
||||
use vlog_parser::parse_source;
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, Definition, Resolution, ScopeKind, Semantics, SymbolId, SymbolKind,
|
||||
WorkspaceIndex,
|
||||
analyze, resolve_external, Definition, ExternalTarget, Resolution, ScopeKind, Semantics,
|
||||
SymbolId, SymbolKind, WorkspaceIndex,
|
||||
};
|
||||
|
||||
fn sem(src: &str) -> Semantics {
|
||||
@@ -65,7 +65,9 @@ endclass
|
||||
("prop", SymbolKind::Var),
|
||||
("bits", SymbolKind::Var),
|
||||
("count", SymbolKind::Var),
|
||||
("LP", SymbolKind::Param),
|
||||
// `localparam int LP = 2;` — its own kind since 2026-09-02, so a
|
||||
// header `localparam` can be kept out of a `#(.` override list.
|
||||
("LP", SymbolKind::LocalParam),
|
||||
("state_e", SymbolKind::Typedef),
|
||||
("IDLE", SymbolKind::EnumVariant),
|
||||
("BUSY", SymbolKind::EnumVariant),
|
||||
@@ -623,6 +625,40 @@ endclass
|
||||
}
|
||||
}
|
||||
|
||||
/// Pins the opacity promise `docs/features/out-of-class-constraints/README.md`
|
||||
/// makes without a test of its own: an out-of-block `constraint C::name { ... }`
|
||||
/// is exactly as opaque as the in-class form above — same `ItemKind::Verbatim(_)`
|
||||
/// arm in `bind.rs`, reached by the same item walker, item position never
|
||||
/// entered into it.
|
||||
#[test]
|
||||
fn an_out_of_block_constraint_is_absent_but_nothing_crashes() {
|
||||
let src = "\
|
||||
class my_seq;
|
||||
rand int num_trans;
|
||||
extern constraint num_trans_c;
|
||||
endclass
|
||||
|
||||
constraint my_seq::num_trans_c {
|
||||
num_trans inside {[1:20]};
|
||||
}
|
||||
";
|
||||
let s = sem(src);
|
||||
// No symbol for the constraint name, in-class prototype or out-of-block
|
||||
// definition alike — both are `ItemKind::Verbatim(_)` leaves.
|
||||
assert!(s.symbols().iter().all(|sym| sym.name != "num_trans_c"));
|
||||
assert_eq!(
|
||||
s.symbols().iter().map(|sym| sym.name.as_str()).collect::<Vec<_>>(),
|
||||
vec!["my_seq", "num_trans"]
|
||||
);
|
||||
assert!(s.reference_at(nth(src, "num_trans inside", 0)).is_none());
|
||||
// Queries at every offset stay panic-free.
|
||||
for offset in 0..=src.len() as u32 {
|
||||
let _ = s.definition_of(offset);
|
||||
let _ = s.symbol_at(offset);
|
||||
let _ = s.reference_at(offset);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Workspace index
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -686,10 +722,13 @@ fn a_package_nested_class_reaches_through_imports_and_static_access() {
|
||||
// item::K → through the member table keyed by the class name.
|
||||
match overlay.definition_of(&s, nth(sources[1].1, "item::K", 0) + 6) {
|
||||
Some(Definition::External(defs)) => {
|
||||
assert_eq!(defs[0].kind, SymbolKind::Param);
|
||||
// A `localparam` is still exported by its class and still
|
||||
// resolves through the member table — the 2026-09-02 split
|
||||
// changes what it may be *offered* for, never what it resolves to.
|
||||
assert_eq!(defs[0].kind, SymbolKind::LocalParam);
|
||||
assert_eq!(&sources[0].1[defs[0].name_span.as_range()], "K");
|
||||
}
|
||||
other => panic!("expected the param, got {other:?}"),
|
||||
other => panic!("expected the localparam, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -705,8 +744,15 @@ fn workspace_symbols_list_classes_and_their_members() {
|
||||
assert!(runs.iter().any(|h| h.name == "run" && h.container == Some("driver")));
|
||||
}
|
||||
|
||||
/// **Changed 2026-09-01 by class-member-access** (topo §2.9-9, filed by this
|
||||
/// feature and delivered there). The single-file answer is exactly what it
|
||||
/// was — this crate still never chases a base, in this file or out of it — but
|
||||
/// the *overlay* now does: `resolve_external` follows the recorded base
|
||||
/// through the workspace's member tables and up its own `extends` chain. The
|
||||
/// old name of this test was
|
||||
/// `inherited_candidates_are_not_the_workspace_overlays_business`.
|
||||
#[test]
|
||||
fn inherited_candidates_are_not_the_workspace_overlays_business() {
|
||||
fn inherited_candidates_are_chased_by_the_overlay_and_only_by_it() {
|
||||
let sources = [
|
||||
("base.svh", "class base;\n int held;\nendclass\n"),
|
||||
(
|
||||
@@ -717,19 +763,27 @@ fn inherited_candidates_are_not_the_workspace_overlays_business() {
|
||||
let ws = index(&sources);
|
||||
let file = parse_source(sources[1].1).expect("child parses");
|
||||
let s = analyze(&file, sources[1].1);
|
||||
// The miss on `held` is an inherited candidate — never chased, even
|
||||
// though the base is right there in the workspace (the documented
|
||||
// future round).
|
||||
// The single-file layer's answer is unchanged: the base, and the (empty)
|
||||
// import paths the lexical walk collected. `held = 1` is a value
|
||||
// position, so the type-position promotion gave it no path to sweep.
|
||||
let held = s.reference_at(nth(sources[1].1, "held = 1", 0)).expect("the use");
|
||||
assert_eq!(
|
||||
held.resolution,
|
||||
Resolution::InheritedCandidate { base: "base".into(), paths: Vec::new() }
|
||||
);
|
||||
// Two reasons it is absent from the overlay, and both hold: `held = 1` is
|
||||
// a value position, so the promotion never gave it a path to sweep; and
|
||||
// even with one, a class property is not a unit, so the sweep would find
|
||||
// nothing and record nothing.
|
||||
// The overlay chases `base` itself: `member("base", "held")` answers.
|
||||
let overlay = resolve_external(&s, &ws);
|
||||
let id = s.reference_id_at(nth(sources[1].1, "held = 1", 0)).expect("an id");
|
||||
let def = overlay.get(id).and_then(ExternalTarget::best).expect("the inherited property");
|
||||
assert_eq!(ws.path(def.file).map(|p| p.file_name().unwrap()), Some("base.svh".as_ref()));
|
||||
assert_eq!(def.kind, SymbolKind::Var);
|
||||
|
||||
// A base the workspace does not hold is still absent from the overlay:
|
||||
// the chase ends at the first name nothing declares, and records nothing.
|
||||
let orphan = "class child extends nowhere_c;\n function void f();\n held = 1;\n endfunction\nendclass\n";
|
||||
let file = parse_source(orphan).expect("child parses");
|
||||
let s = analyze(&file, orphan);
|
||||
let overlay = resolve_external(&s, &ws);
|
||||
let id = s.reference_id_at(nth(orphan, "held = 1", 0)).expect("an id");
|
||||
assert!(overlay.get(id).is_none(), "a name the workspace cannot answer is not in the overlay");
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
//! Deeply nested input against the stack the parse actually runs on.
|
||||
//!
|
||||
//! `vlog_parser` turns nesting past `MAX_NESTING_DEPTH` into an ordinary
|
||||
//! diagnostic, but only above `PARSE_STACK_SIZE`: reaching level 64 costs
|
||||
//! stack, and a thread too small to hold it overflows before the guard ever
|
||||
//! fires — an abort, not a `Result`. These tests run the whole indexing
|
||||
//! pipeline (tokenize → tolerant parse → `analyze` → facts) on exactly that
|
||||
//! stack, so they fail if either half of the contract is cut.
|
||||
//!
|
||||
//! Reported 2026-08-28: 500 nested `begin`/`end` through `FileFacts::of`
|
||||
//! aborted the process on a default 2 MiB test thread.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use vlog_parser::PARSE_STACK_SIZE;
|
||||
use vlog_semantic::{FileFacts, IndexBuilder, WorkspaceIndex};
|
||||
|
||||
/// Run `f` on the stack every production parse site is given — the CLI's
|
||||
/// worker thread and rayon pool, the language server's message loop. Not a
|
||||
/// generous number picked for the test: the constant itself, so shrinking
|
||||
/// the guarantee below what the depth limit needs fails here.
|
||||
fn on_parse_stack<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
|
||||
std::thread::Builder::new()
|
||||
.stack_size(PARSE_STACK_SIZE)
|
||||
.spawn(f)
|
||||
.expect("spawn a parse-sized thread")
|
||||
.join()
|
||||
.expect("the parse thread died")
|
||||
}
|
||||
|
||||
/// The index one file's facts build, read off on the same stack.
|
||||
fn index_of(src: String) -> WorkspaceIndex {
|
||||
on_parse_stack(move || {
|
||||
let mut builder = IndexBuilder::new();
|
||||
builder.add_facts(FileFacts::of(PathBuf::from("/w/deep.sv"), &src));
|
||||
builder.finish()
|
||||
})
|
||||
}
|
||||
|
||||
/// `n` nested `begin`/`end` inside an `initial`, in a module.
|
||||
fn nested_begins(n: usize) -> String {
|
||||
format!(
|
||||
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
|
||||
"begin\n".repeat(n),
|
||||
"end\n".repeat(n)
|
||||
)
|
||||
}
|
||||
|
||||
/// Every block-structured shape that nests, at a depth far past the limit.
|
||||
/// Each is `(name, source)`; the innermost body is a statement or an item, so
|
||||
/// the shape is what real generated code would produce, not a bare skeleton.
|
||||
fn deep_block_shapes(n: usize) -> Vec<(&'static str, String)> {
|
||||
let stmt = |open: &str, close: &str| {
|
||||
format!(
|
||||
"module m;\ninitial begin\n{}x <= 1;\n{}end\nendmodule\n",
|
||||
open.repeat(n),
|
||||
close.repeat(n)
|
||||
)
|
||||
};
|
||||
vec![
|
||||
("begin/end", nested_begins(n)),
|
||||
("if/begin", stmt("if (c) begin\n", "end\n")),
|
||||
("fork/join", stmt("fork\n", "join\n")),
|
||||
("case/endcase", stmt("case (s)\n1: ", "endcase\n")),
|
||||
("foreach", stmt("foreach (a[j])\n", "")),
|
||||
("while", stmt("while (c)\n", "")),
|
||||
("for", stmt("for (int i = 0; i < 4; i++)\n", "")),
|
||||
(
|
||||
"else-if chain",
|
||||
format!(
|
||||
"module m;\ninitial\n{}x <= 0;\nendmodule\n",
|
||||
"if (c) x <= 1; else\n".repeat(n)
|
||||
),
|
||||
),
|
||||
(
|
||||
"generate if",
|
||||
format!(
|
||||
"module m;\ngenerate\n{}wire w;\n{}endgenerate\nendmodule\n",
|
||||
"if (1) begin\n".repeat(n),
|
||||
"end\n".repeat(n)
|
||||
),
|
||||
),
|
||||
(
|
||||
"generate for",
|
||||
format!(
|
||||
"module m;\ngenerate\n{}wire w;\n{}endgenerate\nendmodule\n",
|
||||
"for (i = 0; i < 2; i = i + 1) begin\n".repeat(n),
|
||||
"end\n".repeat(n)
|
||||
),
|
||||
),
|
||||
(
|
||||
"nested modules",
|
||||
format!("{}wire w;\n{}", "module m;\n".repeat(n), "endmodule\n".repeat(n)),
|
||||
),
|
||||
(
|
||||
// Not legal SystemVerilog at all — a `task` cannot open inside a
|
||||
// task body — so this errors early rather than on depth. It is
|
||||
// here because "errors early" is a claim about the stack too.
|
||||
"nested tasks",
|
||||
format!(
|
||||
"module m;\n{}x = 1;\n{}endmodule\n",
|
||||
"task t;\n".repeat(n),
|
||||
"endtask\n".repeat(n)
|
||||
),
|
||||
),
|
||||
(
|
||||
"nested functions",
|
||||
format!(
|
||||
"module m;\n{}f = 1;\n{}endmodule\n",
|
||||
"function int f;\n".repeat(n),
|
||||
"endfunction\n".repeat(n)
|
||||
),
|
||||
),
|
||||
("nested parens", {
|
||||
format!("module m;\nassign x = {}1{};\nendmodule\n", "(".repeat(n), ")".repeat(n))
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn five_hundred_nested_blocks_are_indexed_not_aborted() {
|
||||
// The reported repro, verbatim in shape. The depth limit rejects the
|
||||
// `initial` block, tolerant recovery turns it into an error leaf, and the
|
||||
// module around it is still a fact — a graceful result, not a dead
|
||||
// process.
|
||||
let index = index_of(nested_begins(500));
|
||||
assert_eq!(index.files().len(), 1);
|
||||
assert_eq!(index.units("m").len(), 1, "the module survives the unparsable body");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_block_shape_can_abort_the_parse_stack() {
|
||||
// 400 levels is far past `MAX_NESTING_DEPTH` for every family, so each of
|
||||
// these either errors on depth or errors earlier; what is asserted is
|
||||
// that the pipeline *returns* on the guaranteed stack. A regression here
|
||||
// is a SIGABRT, so the assertion below is secondary — reaching it is the
|
||||
// test.
|
||||
for (name, src) in deep_block_shapes(400) {
|
||||
let index = index_of(src);
|
||||
assert_eq!(index.files().len(), 1, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nesting_just_under_the_limit_still_yields_its_facts() {
|
||||
// Legal depth, so nothing is rejected and the whole 64-level tree is
|
||||
// parsed, analyzed and walked on this stack — the expensive direction,
|
||||
// and the one a smaller stack fails first.
|
||||
let index = index_of(nested_begins(vlog_parser::parser::MAX_NESTING_DEPTH as usize - 6));
|
||||
assert_eq!(index.units("m").len(), 1, "a legally deep file is indexed like any other");
|
||||
}
|
||||
@@ -0,0 +1,539 @@
|
||||
//! `interface`, `modport` and `clocking` as declarations and references: the
|
||||
//! kind an interface gets, the members another file may reach through a
|
||||
//! `virtual` handle, and the two constructs that only live inside an interface.
|
||||
//! The rules live in `docs/features/interface-semantics/README.md`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use vlog_parser::parse_source;
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, Def, ExternalTarget, FileFacts, Resolution, Semantics, Symbol,
|
||||
SymbolKind, WorkspaceIndex,
|
||||
};
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// helpers
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
fn sem(src: &str) -> Semantics {
|
||||
let file = parse_source(src).expect("fixture must parse");
|
||||
analyze(&file, src)
|
||||
}
|
||||
|
||||
fn index(files: &[(&str, &str)]) -> WorkspaceIndex {
|
||||
WorkspaceIndex::build(files.iter().map(|(name, src)| (PathBuf::from(name), *src)))
|
||||
}
|
||||
|
||||
/// Offset of the `n`th (0-based) occurrence of `needle`.
|
||||
fn nth(src: &str, needle: &str, n: usize) -> u32 {
|
||||
src.match_indices(needle).nth(n).expect("occurrence must exist").0 as u32
|
||||
}
|
||||
|
||||
/// Offset of the first occurrence of `needle`.
|
||||
fn at(src: &str, needle: &str) -> u32 {
|
||||
nth(src, needle, 0)
|
||||
}
|
||||
|
||||
/// Offset of the name written just after `prefix` — the way a cursor lands on
|
||||
/// the second half of `bus_if.mp` or on the tail of `vif.sig`.
|
||||
fn after(src: &str, prefix: &str) -> u32 {
|
||||
at(src, prefix) + prefix.len() as u32
|
||||
}
|
||||
|
||||
/// The resolution of the reference written at `offset`, or `None` when this
|
||||
/// crate recorded no reference there at all.
|
||||
fn resolution(s: &Semantics, offset: u32) -> Option<Resolution> {
|
||||
s.reference_at(offset).map(|r| r.resolution.clone())
|
||||
}
|
||||
|
||||
/// The declaration the in-file layer says the use at `offset` names.
|
||||
fn resolved(s: &Semantics, offset: u32) -> &Symbol {
|
||||
let id = s
|
||||
.reference_at(offset)
|
||||
.unwrap_or_else(|| panic!("no reference at {offset}"))
|
||||
.resolved()
|
||||
.unwrap_or_else(|| panic!("the reference at {offset} resolves to nothing"));
|
||||
s.symbol(id).expect("a resolved id names a symbol")
|
||||
}
|
||||
|
||||
fn symbol<'a>(s: &'a Semantics, name: &str) -> &'a Symbol {
|
||||
s.symbols()
|
||||
.iter()
|
||||
.find(|sym| sym.name == name)
|
||||
.unwrap_or_else(|| panic!("no symbol named {name}"))
|
||||
}
|
||||
|
||||
/// The workspace's answer for the use at `offset` in `src`.
|
||||
fn overlay_def(ws: &WorkspaceIndex, src: &str, offset: u32) -> Option<Def> {
|
||||
let s = sem(src);
|
||||
let id = s.reference_id_at(offset)?;
|
||||
resolve_external(&s, ws).get(id).and_then(ExternalTarget::best).cloned()
|
||||
}
|
||||
|
||||
/// The text a workspace definition points at, read back out of the sources it
|
||||
/// was built from.
|
||||
fn slice<'a>(ws: &WorkspaceIndex, files: &[(&'a str, &'a str)], def: &Def) -> &'a str {
|
||||
let path = ws.path(def.file).expect("an indexed def names a file");
|
||||
let src = files
|
||||
.iter()
|
||||
.find(|(name, _)| Path::new(name) == path)
|
||||
.expect("the file is one of the sources")
|
||||
.1;
|
||||
&src[def.name_span.as_range()]
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the interface itself
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_interface_is_its_own_kind_and_a_program_is_not() {
|
||||
let src = "interface bus_if;\nendinterface\nmodule m;\nendmodule\nprogram p;\nendprogram\n";
|
||||
let s = sem(src);
|
||||
assert_eq!(symbol(&s, "bus_if").kind, SymbolKind::Interface);
|
||||
assert_eq!(symbol(&s, "m").kind, SymbolKind::Module);
|
||||
assert_eq!(
|
||||
symbol(&s, "p").kind,
|
||||
SymbolKind::Module,
|
||||
"a program is a module body with another closing keyword; it gets no export rule of its own this round"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_instantiation_resolves_in_file_and_across_files() {
|
||||
let together = "interface bus_if;\nendinterface\nmodule top;\n bus_if u_bus ();\nendmodule\n";
|
||||
let s = sem(together);
|
||||
assert_eq!(resolved(&s, at(together, "bus_if u_bus")).kind, SymbolKind::Interface);
|
||||
|
||||
let sources = [
|
||||
("bus_if.sv", "interface bus_if;\nendinterface\n"),
|
||||
("top.sv", "module top;\n bus_if u_bus ();\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let use_at = at(sources[1].1, "bus_if u_bus");
|
||||
assert_eq!(
|
||||
resolution(&sem(sources[1].1), use_at),
|
||||
Some(Resolution::ExternalCandidate { paths: vec!["bus_if".to_string()] })
|
||||
);
|
||||
let def = overlay_def(&ws, sources[1].1, use_at).expect("the unit table answers");
|
||||
assert_eq!(def.kind, SymbolKind::Interface);
|
||||
assert_eq!(slice(&ws, &sources, &def), "bus_if");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_connection_into_an_interface_instance_names_its_port() {
|
||||
let src = "interface bus_if (input logic clk);\nendinterface\nmodule top;\n logic c;\n bus_if u_bus (.clk(c));\nendmodule\n";
|
||||
let s = sem(src);
|
||||
let port = resolved(&s, after(src, "(."));
|
||||
assert_eq!(port.name, "clk");
|
||||
assert_eq!(port.kind, SymbolKind::Port);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interfaces_stay_instantiable_units_beside_modules() {
|
||||
let sources = [
|
||||
("bus_if.sv", "interface bus_if;\nendinterface\n"),
|
||||
("top.sv", "module top;\n bus_if u_bus ();\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let units: Vec<(&str, SymbolKind)> =
|
||||
ws.instantiable_units().map(|(name, def)| (name, def.kind)).collect();
|
||||
assert_eq!(units, [("bus_if", SymbolKind::Interface), ("top", SymbolKind::Module)]);
|
||||
|
||||
// The instantiation census is unchanged: an interface instance is an edge.
|
||||
assert_eq!(ws.instantiations_of("bus_if").len(), 1);
|
||||
|
||||
let counts = ws.counts();
|
||||
assert_eq!(counts.modules, 1, "an interface is not counted as a module");
|
||||
assert_eq!(counts.interfaces, 1);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// modports
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
const IFACE: &str = "interface bus_if;\n logic a;\n logic b;\n logic c;\n task drive ();\n endtask\n clocking cb @(posedge a);\n input b;\n endclocking\n modport mp (input a, output b, inout c, import drive, clocking cb);\nendinterface\n";
|
||||
|
||||
#[test]
|
||||
fn a_modport_is_a_symbol_spanning_its_own_declaration() {
|
||||
let s = sem(IFACE);
|
||||
let mp = symbol(&s, "mp");
|
||||
assert_eq!(mp.kind, SymbolKind::Modport);
|
||||
assert_eq!(&IFACE[mp.name_span.as_range()], "mp");
|
||||
assert_eq!(
|
||||
&IFACE[mp.decl_span.as_range()],
|
||||
"mp (input a, output b, inout c, import drive, clocking cb)",
|
||||
"the declaration span is this modport's own, not the whole `modport ...;` statement"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_name_in_a_modport_port_list_is_a_reference_to_the_interfaces_own() {
|
||||
let s = sem(IFACE);
|
||||
for (prefix, name, kind) in [
|
||||
("modport mp (input ", "a", SymbolKind::Var),
|
||||
("output ", "b", SymbolKind::Var),
|
||||
("inout ", "c", SymbolKind::Var),
|
||||
("import ", "drive", SymbolKind::Task),
|
||||
(", clocking ", "cb", SymbolKind::Clocking),
|
||||
] {
|
||||
let target = resolved(&s, after(IFACE, prefix));
|
||||
assert_eq!(target.name, name, "{prefix}");
|
||||
assert_eq!(target.kind, kind, "{prefix}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_modport_name_that_names_nothing_records_nothing() {
|
||||
// IEEE 1800 §25.5: a modport port names a member of *this* interface. A
|
||||
// name the interface does not declare must not be walked outward onto the
|
||||
// file-scope `other_if` that happens to share it — a wrong answer where
|
||||
// recording nothing is merely a missing one.
|
||||
let src = "interface other_if;\nendinterface\ninterface bus_if;\n modport mp (input other_if);\nendinterface\n";
|
||||
let s = sem(src);
|
||||
assert_eq!(resolution(&s, after(src, "modport mp (input ")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_modport_half_of_a_port_type_resolves_in_file() {
|
||||
let src = "interface bus_if;\n logic a;\n modport mp (input a);\nendinterface\nmodule sub (bus_if.mp bus);\nendmodule\n";
|
||||
let s = sem(src);
|
||||
assert_eq!(resolved(&s, at(src, "bus_if.mp")).kind, SymbolKind::Interface);
|
||||
let mp = resolved(&s, after(src, "bus_if."));
|
||||
assert_eq!(mp.kind, SymbolKind::Modport);
|
||||
assert_eq!(mp.name, "mp");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_modport_half_of_a_port_type_resolves_across_files() {
|
||||
let sources = [
|
||||
("bus_if.sv", "interface bus_if;\n logic a;\n modport mp (input a);\nendinterface\n"),
|
||||
("sub.sv", "module sub (bus_if.mp bus);\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let src = sources[1].1;
|
||||
let tail = after(src, "bus_if.");
|
||||
assert_eq!(
|
||||
resolution(&sem(src), tail),
|
||||
Some(Resolution::ExternalCandidate { paths: vec!["bus_if::mp".to_string()] })
|
||||
);
|
||||
let def = overlay_def(&ws, src, tail).expect("the member table answers");
|
||||
assert_eq!(def.kind, SymbolKind::Modport);
|
||||
assert_eq!(slice(&ws, &sources, &def), "mp");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_virtual_interface_handle_keeps_its_modport_reference_and_its_bare_type() {
|
||||
let sources = [
|
||||
("bus_if.sv", "interface bus_if;\n logic a;\n modport mp (input a);\nendinterface\n"),
|
||||
("env.sv", "class env;\n virtual bus_if.mp vif;\nendclass\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let src = sources[1].1;
|
||||
let s = sem(src);
|
||||
assert_eq!(
|
||||
symbol(&s, "vif").type_name.as_deref(),
|
||||
Some("bus_if"),
|
||||
"a modport restricts direction, not membership: the handle's type is the interface"
|
||||
);
|
||||
let def = overlay_def(&ws, src, after(src, "bus_if.")).expect("the member table answers");
|
||||
assert_eq!(def.kind, SymbolKind::Modport);
|
||||
assert_eq!(slice(&ws, &sources, &def), "mp");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_modport_named_in_a_connection_resolves_through_the_instance() {
|
||||
let together = "interface bus_if;\n logic a;\n modport mp (input a);\nendinterface\nmodule sub (bus_if.mp bus);\nendmodule\nmodule top;\n bus_if b_if ();\n sub u (.bus(b_if.mp));\nendmodule\n";
|
||||
let s = sem(together);
|
||||
let mp = resolved(&s, after(together, ".bus(b_if."));
|
||||
assert_eq!(mp.kind, SymbolKind::Modport);
|
||||
|
||||
let sources = [
|
||||
("bus_if.sv", "interface bus_if;\n logic a;\n modport mp (input a);\nendinterface\n"),
|
||||
("top.sv", "module top;\n bus_if b_if ();\n sub u (.bus(b_if.mp));\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let src = sources[1].1;
|
||||
let def = overlay_def(&ws, src, after(src, ".bus(b_if.")).expect("the member table answers");
|
||||
assert_eq!(def.kind, SymbolKind::Modport);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_interfaces_with_the_same_modport_name_answer_for_themselves() {
|
||||
let a = "interface a_if;\n logic x;\n modport mp (input x);\nendinterface\n";
|
||||
let b = "interface b_if;\n logic y;\n modport mp (input y);\nendinterface\n";
|
||||
let sources = [
|
||||
("a_if.sv", a),
|
||||
("b_if.sv", b),
|
||||
("sub.sv", "module sub (a_if.mp p, b_if.mp q);\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let src = sources[2].1;
|
||||
|
||||
for (prefix, want) in [("a_if.", "a_if.sv"), ("b_if.", "b_if.sv")] {
|
||||
let def = overlay_def(&ws, src, after(src, prefix)).expect("the member table answers");
|
||||
assert_eq!(def.kind, SymbolKind::Modport);
|
||||
let file = ws.path(def.file).and_then(|p| p.file_name()).unwrap().to_string_lossy();
|
||||
assert_eq!(file, want, "{prefix} must answer with its own interface's modport");
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// clocking blocks
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
const CLOCKED: &str = "interface bus_if;\n logic clk;\n logic data;\n clocking cb @(posedge clk);\n input data;\n endclocking\nendinterface\n";
|
||||
|
||||
#[test]
|
||||
fn a_named_clocking_block_is_a_symbol_typed_by_its_enclosing_unit() {
|
||||
let s = sem(CLOCKED);
|
||||
let cb = symbol(&s, "cb");
|
||||
assert_eq!(cb.kind, SymbolKind::Clocking);
|
||||
assert_eq!(
|
||||
cb.type_name.as_deref(),
|
||||
Some("bus_if"),
|
||||
"a clocking signal aliases the enclosing unit's own signal, so the block's type is that unit"
|
||||
);
|
||||
// The event and the signal list are both ordinary uses of the interface's
|
||||
// declarations.
|
||||
assert_eq!(resolved(&s, at(CLOCKED, "posedge clk") + 8).name, "clk");
|
||||
assert_eq!(resolved(&s, after(CLOCKED, " input ")).name, "data");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clocking_signal_is_reached_through_the_block_in_file_and_across_files() {
|
||||
let together = format!("{CLOCKED}class env;\n virtual bus_if vif;\n task go ();\n if (vif.cb.data) begin\n end\n endtask\nendclass\n");
|
||||
let s = sem(&together);
|
||||
let hit = resolved(&s, after(&together, "vif.cb."));
|
||||
assert_eq!(hit.name, "data");
|
||||
assert_eq!(hit.kind, SymbolKind::Var, "the honest answer is the signal's own declaration");
|
||||
|
||||
let env = "class env;\n virtual bus_if vif;\n task go ();\n if (vif.cb.data) begin\n end\n endtask\nendclass\n";
|
||||
let sources = [("bus_if.sv", CLOCKED), ("env.sv", env)];
|
||||
let ws = index(&sources);
|
||||
let tail = after(env, "vif.cb.");
|
||||
assert_eq!(
|
||||
resolution(&sem(env), tail),
|
||||
Some(Resolution::ExternalCandidate { paths: vec!["bus_if::cb::data".to_string()] })
|
||||
);
|
||||
let def = overlay_def(&ws, env, tail).expect("the member chain answers");
|
||||
assert_eq!(slice(&ws, &sources, &def), "data");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clocking_block_is_a_chain_head_inside_its_own_interface() {
|
||||
let src = "interface bus_if;\n logic clk;\n logic data;\n clocking cb @(posedge clk);\n input data;\n endclocking\n initial d = cb.data;\nendinterface\n";
|
||||
let s = sem(src);
|
||||
let hit = resolved(&s, after(src, "cb."));
|
||||
assert_eq!(hit.name, "data");
|
||||
assert_eq!(hit.kind, SymbolKind::Var);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_anonymous_default_clocking_declares_nothing() {
|
||||
let src = "interface bus_if;\n logic clk;\n default clocking @(posedge clk);\n endclocking\nendinterface\n";
|
||||
let s = sem(src);
|
||||
assert!(
|
||||
s.symbols().iter().all(|sym| sym.kind != SymbolKind::Clocking),
|
||||
"an unnamed block binds no name, so there is nothing to declare"
|
||||
);
|
||||
assert_eq!(resolved(&s, at(src, "posedge clk") + 8).name, "clk");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_body_less_default_clocking_names_an_existing_block() {
|
||||
let src = "interface bus_if;\n logic clk;\n clocking cb @(posedge clk);\n endclocking\n default clocking cb;\nendinterface\n";
|
||||
let s = sem(src);
|
||||
let hit = resolved(&s, at(src, "default clocking cb") + 17);
|
||||
assert_eq!(hit.kind, SymbolKind::Clocking);
|
||||
assert_eq!(hit.name, "cb");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clocking_block_in_a_module_behaves_the_same_way() {
|
||||
let src = "module tb;\n logic clk;\n logic data;\n clocking cb @(posedge clk);\n input data;\n endclocking\n initial d = cb.data;\nendmodule\n";
|
||||
let s = sem(src);
|
||||
assert_eq!(symbol(&s, "cb").type_name.as_deref(), Some("tb"));
|
||||
assert_eq!(resolved(&s, after(src, "cb.")).name, "data");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// what an interface exports
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
const EXPORTER: &str = "interface bus_if;\n parameter int WIDTH = 8;\n wire net_sig;\n logic var_sig;\n task drive ();\n endtask\nendinterface\n";
|
||||
|
||||
#[test]
|
||||
fn an_interfaces_signals_are_reachable_through_a_virtual_handle_across_files() {
|
||||
let env = "class env;\n virtual bus_if vif;\n task go ();\n x = vif.net_sig;\n y = vif.var_sig;\n z = vif.WIDTH;\n vif.drive();\n endtask\nendclass\n";
|
||||
let sources = [("bus_if.sv", EXPORTER), ("env.sv", env)];
|
||||
let ws = index(&sources);
|
||||
|
||||
for (want, kind) in [
|
||||
("net_sig", SymbolKind::Net),
|
||||
("var_sig", SymbolKind::Var),
|
||||
("WIDTH", SymbolKind::Param),
|
||||
("drive", SymbolKind::Task),
|
||||
] {
|
||||
let offset = at(env, &format!("vif.{want}")) + 4;
|
||||
let def =
|
||||
overlay_def(&ws, env, offset).unwrap_or_else(|| panic!("vif.{want} is unanswered"));
|
||||
assert_eq!(slice(&ws, &sources, &def), want);
|
||||
assert_eq!(def.kind, kind, "vif.{want}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_the_interface_does_not_declare_is_still_unanswered() {
|
||||
let env = "class env;\n virtual bus_if vif;\n task go ();\n x = vif.nope;\n endtask\nendclass\n";
|
||||
let ws = index(&[("bus_if.sv", EXPORTER), ("env.sv", env)]);
|
||||
assert_eq!(
|
||||
overlay_def(&ws, env, after(env, "vif.")),
|
||||
None,
|
||||
"a signal the interface does not declare has no honest answer"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_modules_internals_are_still_not_exported() {
|
||||
// The module ruling (`docs/features/class-member-access/README.md`, round
|
||||
// 2) is untouched: an interface's signals are its surface, a module's are
|
||||
// not.
|
||||
let sub = "module sub (input logic p);\n logic internal;\nendmodule\n";
|
||||
let ws = index(&[("sub.sv", sub)]);
|
||||
let members: Vec<&str> = ws.members_of("sub").map(|(name, _)| name).collect();
|
||||
assert_eq!(members, ["p"]);
|
||||
|
||||
let iface = index(&[("bus_if.sv", EXPORTER)]);
|
||||
let members: Vec<&str> = iface.members_of("bus_if").map(|(name, _)| name).collect();
|
||||
assert_eq!(members, ["WIDTH", "drive", "net_sig", "var_sig"]);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the index's own equalities, over the new declarations
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_interface_survives_encode_and_decode_unchanged() {
|
||||
let facts = FileFacts::of(PathBuf::from("bus_if.sv"), IFACE);
|
||||
let line = facts.encode().expect("a plain path encodes");
|
||||
assert_eq!(FileFacts::decode(&line), Some(facts), "modport and clocking kinds round-trip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incrementally_indexing_an_interface_gives_the_index_a_build_would() {
|
||||
let files = [
|
||||
("bus_if.sv", IFACE),
|
||||
("sub.sv", "module sub (bus_if.mp bus);\nendmodule\n"),
|
||||
("top.sv", "module top;\n bus_if b_if ();\n sub u (.bus(b_if.mp));\nendmodule\n"),
|
||||
];
|
||||
let whole = index(&files);
|
||||
|
||||
let mut incremental = index(&files[..1]);
|
||||
for (path, src) in &files[1..] {
|
||||
incremental.update_file(PathBuf::from(path), src);
|
||||
}
|
||||
assert_eq!(incremental.fingerprint(), whole.fingerprint());
|
||||
|
||||
let mut absorbed = index(&[]);
|
||||
absorbed.absorb(files.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect(), &[]);
|
||||
assert_eq!(absorbed.fingerprint(), whole.fingerprint());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_modport_and_a_clocking_block_are_exported_members() {
|
||||
let ws = index(&[("bus_if.sv", IFACE)]);
|
||||
let members: Vec<(&str, SymbolKind)> =
|
||||
ws.members_of("bus_if").map(|(name, defs)| (name, defs[0].kind)).collect();
|
||||
assert!(members.contains(&("mp", SymbolKind::Modport)), "{members:?}");
|
||||
assert!(members.contains(&("cb", SymbolKind::Clocking)), "{members:?}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// measurement
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// What this round costs the index over the real corpus: the store's size and
|
||||
/// what it is *made of*, group by group, so a byte delta can be attributed
|
||||
/// rather than guessed at.
|
||||
///
|
||||
/// `#[ignore]`d, asserting nothing — the house shape for a measurement probe
|
||||
/// (`crates/lucisv_server/src/perf.rs`), and it reads only public API so the
|
||||
/// same file can be dropped into a checkout of an older revision to produce
|
||||
/// the "before" column. Run with
|
||||
/// `cargo test -p vlog_semantic --release --test interfaces -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "measurement over corpus/, printed rather than asserted"]
|
||||
fn what_interface_semantics_cost_the_index() {
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !root.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
collect(&root, &mut files);
|
||||
files.sort();
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
let (mut bytes, mut records) = (0usize, 0usize);
|
||||
// The record's own length-prefixed groups: units, members, references.
|
||||
let (mut units, mut members, mut refs) = (0usize, 0usize, 0usize);
|
||||
let (mut local, mut external) = (0usize, 0usize);
|
||||
let (mut paths, mut path_bytes) = (0usize, 0usize);
|
||||
for path in &files {
|
||||
let Ok(src) = std::fs::read_to_string(path) else {
|
||||
continue;
|
||||
};
|
||||
let Some(line) = FileFacts::of(path.clone(), &src).encode() else {
|
||||
continue;
|
||||
};
|
||||
bytes += line.len() + 1;
|
||||
records += 1;
|
||||
let fields: Vec<&str> = line.split('\t').collect();
|
||||
let group = |tag: &str| -> usize {
|
||||
fields
|
||||
.iter()
|
||||
.position(|f| *f == tag)
|
||||
.and_then(|at| fields.get(at + 1))
|
||||
.and_then(|n| n.parse().ok())
|
||||
.unwrap_or(0)
|
||||
};
|
||||
units += group("U");
|
||||
members += group("M");
|
||||
refs += group("R");
|
||||
local += fields.iter().filter(|f| **f == "l").count();
|
||||
external += fields.iter().filter(|f| **f == "e").count();
|
||||
// An external fact's bytes are dominated by the paths it carries, so
|
||||
// the path text is counted apart from everything else.
|
||||
let mut at = 0;
|
||||
while at < fields.len() {
|
||||
if fields[at] == "e" {
|
||||
let count: usize = fields.get(at + 3).and_then(|n| n.parse().ok()).unwrap_or(0);
|
||||
paths += count;
|
||||
for i in 0..count {
|
||||
path_bytes += fields.get(at + 4 + i).map_or(0, |f| f.len());
|
||||
}
|
||||
at += 4 + count + 2;
|
||||
} else {
|
||||
at += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let elapsed = start.elapsed();
|
||||
println!("corpus: {records} records, {bytes} store bytes, {elapsed:?} to read them all");
|
||||
println!("corpus groups: {units} units, {members} members, {refs} references ({local} local, {external} external)");
|
||||
println!("corpus paths: {paths} recorded paths, {path_bytes} bytes of path text");
|
||||
}
|
||||
|
||||
fn collect(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
collect(&path, out);
|
||||
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "v" | "svh")) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,767 @@
|
||||
//! The **public prefix walk**: `Semantics::member_site`, `unit_site` and
|
||||
//! `member_scopes`, plus the index's `members_of_chain` and `member_unit`.
|
||||
//!
|
||||
//! Every test here exists to pin one property: **the site a completion list
|
||||
//! is built from is the site a resolution walks through.** They are not two
|
||||
//! answers that happen to agree — `member_of` is `member_site` plus one
|
||||
//! lookup, `member_in_chain` is `member_scopes` plus one lookup per scope,
|
||||
//! and `member_chain` is `members_of_chain`'s hops plus one lookup per hop.
|
||||
//! What these tests check is that the *split* is exactly where it claims to
|
||||
//! be, by re-deriving each resolution from its own prefix.
|
||||
//!
|
||||
//! `docs/features/member-completion/README.md`.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use vlog_parser::parse_source;
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, MemberSite, Resolution, Scope, ScopeId, Semantics, SymbolKind,
|
||||
WorkspaceIndex,
|
||||
};
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// helpers
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
fn sem(src: &str) -> Semantics {
|
||||
let file = parse_source(src).expect("fixture must parse");
|
||||
analyze(&file, src)
|
||||
}
|
||||
|
||||
fn index(files: &[(&str, &str)]) -> WorkspaceIndex {
|
||||
WorkspaceIndex::build(files.iter().map(|(name, src)| (PathBuf::from(name), *src)))
|
||||
}
|
||||
|
||||
/// The offset of the member half of the first `head….member` written as
|
||||
/// `needle` — the tail, which is the reference `member_of` recorded.
|
||||
fn tail(src: &str, needle: &str) -> u32 {
|
||||
let at = src.find(needle).unwrap_or_else(|| panic!("no {needle}")) as u32;
|
||||
at + needle.rfind(['.', ':']).expect("a separator") as u32 + 1
|
||||
}
|
||||
|
||||
fn resolution_at(s: &Semantics, offset: u32) -> Resolution {
|
||||
s.reference_at(offset).unwrap_or_else(|| panic!("no reference at {offset}")).resolution.clone()
|
||||
}
|
||||
|
||||
/// The scope the use at `offset` was written in — the scope a completion
|
||||
/// request at the same place would ask from.
|
||||
fn scope_at(s: &Semantics, offset: u32) -> ScopeId {
|
||||
s.reference_at(offset).expect("a reference").scope
|
||||
}
|
||||
|
||||
/// The innermost scope covering `offset`, the way `lucisv_server` finds it.
|
||||
fn innermost(s: &Semantics, offset: u32) -> ScopeId {
|
||||
s.scopes()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, scope)| scope.span.contains(offset))
|
||||
.min_by_key(|(_, scope)| scope.span.len())
|
||||
.map(|(i, _)| ScopeId(i as u32))
|
||||
.expect("some scope covers every offset")
|
||||
}
|
||||
|
||||
/// Every name a `MemberSite::Scope` offers, the way completion collects them:
|
||||
/// `member_scopes`'s chain, nearest first, each name once.
|
||||
fn names_in(s: &Semantics, scope: ScopeId) -> Vec<String> {
|
||||
let (scopes, _) = s.member_scopes(scope);
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for id in scopes {
|
||||
let Some(sc) = s.scope(id) else { continue };
|
||||
for symbol in sc.symbols.iter().filter_map(|&id| s.symbol(id)) {
|
||||
if !out.contains(&symbol.name) {
|
||||
out.push(symbol.name.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn site_names(index: &WorkspaceIndex, unit: &str) -> Vec<String> {
|
||||
index.members_of_chain(unit).into_iter().map(|(name, _)| name.to_string()).collect()
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the one-walk pin: a site is the prefix of the resolution
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// One file holding every in-file shape the walk has: a class chain, a
|
||||
/// struct, an interface, a typedef alias, an instance head and a two-link
|
||||
/// chain.
|
||||
const MIXED: &str = "\
|
||||
interface bus_if;
|
||||
logic clk;
|
||||
logic [7:0] data;
|
||||
modport mp (input clk);
|
||||
endinterface
|
||||
|
||||
typedef struct packed { logic [7:0] addr; logic vld; } hdr_t;
|
||||
|
||||
class u1;
|
||||
bit base_field;
|
||||
endclass
|
||||
|
||||
class c1 extends u1;
|
||||
bit user_id;
|
||||
hdr_t hdr;
|
||||
endclass
|
||||
|
||||
typedef c1 c1_alias_t;
|
||||
|
||||
module top;
|
||||
bus_if bif ();
|
||||
virtual bus_if vif;
|
||||
c1 item;
|
||||
c1_alias_t aliased;
|
||||
hdr_t h;
|
||||
initial begin
|
||||
$display(item.user_id);
|
||||
$display(item.base_field);
|
||||
$display(item.hdr.addr);
|
||||
$display(aliased.user_id);
|
||||
$display(h.vld);
|
||||
$display(vif.data);
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// **The pin the whole round rests on.** For every `head….member` in the
|
||||
/// fixture that resolves in this file, the declaration the resolution names
|
||||
/// is one of the names `member_site` + `member_scopes` offer — same walk,
|
||||
/// same chain, same first-hit-wins shadowing. A completion list that offered
|
||||
/// a name definition could not reach, or missed one it could, breaks here.
|
||||
#[test]
|
||||
fn every_in_file_member_that_resolves_is_a_name_the_site_offers() {
|
||||
let s = sem(MIXED);
|
||||
let cases: &[(&str, &str, &[&str], &str)] = &[
|
||||
("item.user_id", "item", &[], "user_id"),
|
||||
("item.base_field", "item", &[], "base_field"),
|
||||
("item.hdr.addr", "item", &["hdr"], "addr"),
|
||||
("aliased.user_id", "aliased", &[], "user_id"),
|
||||
("h.vld", "h", &[], "vld"),
|
||||
("vif.data", "vif", &[], "data"),
|
||||
];
|
||||
for (needle, head, mids, member) in cases {
|
||||
let at = tail(MIXED, needle);
|
||||
let Resolution::Resolved(id) = resolution_at(&s, at) else {
|
||||
panic!("{needle} must resolve in this file");
|
||||
};
|
||||
let declared = &s.symbol(id).expect("a symbol").name;
|
||||
assert_eq!(declared, member, "{needle} resolved to the wrong name");
|
||||
|
||||
let mids: Vec<String> = mids.iter().map(|m| (*m).to_string()).collect();
|
||||
let site = s
|
||||
.member_site(scope_at(&s, at), head, &mids)
|
||||
.unwrap_or_else(|| panic!("{needle}'s site must resolve"));
|
||||
let MemberSite::Scope(scope) = site else {
|
||||
panic!("{needle}'s site is in this file");
|
||||
};
|
||||
assert!(
|
||||
names_in(&s, scope).iter().any(|name| name == member),
|
||||
"{needle}: the site must offer the very name the resolution found",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The site a request from the innermost scope covering the cursor asks for
|
||||
/// is the site the *binder's* own scope asks for. The server has no
|
||||
/// reference to read the scope off — it only has an offset — so the two ways
|
||||
/// of naming the scope have to agree.
|
||||
#[test]
|
||||
fn the_innermost_scope_at_the_cursor_answers_the_same_site() {
|
||||
let s = sem(MIXED);
|
||||
for needle in ["item.user_id", "item.hdr.addr", "vif.data", "h.vld"] {
|
||||
let at = tail(MIXED, needle);
|
||||
let mut segments: Vec<String> = needle.split('.').map(String::from).collect();
|
||||
segments.pop();
|
||||
let head = segments.remove(0);
|
||||
let mids = segments;
|
||||
assert_eq!(
|
||||
s.member_site(scope_at(&s, at), &head, &mids),
|
||||
s.member_site(innermost(&s, at), &head, &mids),
|
||||
"{needle}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A head whose type leaves the file answers with the composed path, and the
|
||||
/// path is **exactly** the resolution's own path with the tail cut off. That
|
||||
/// is the cross-file half of the same claim: `follow_one` walks
|
||||
/// `<site>::<name>`, so a list built from `<site>` lists what it walks to.
|
||||
#[test]
|
||||
fn a_site_that_leaves_the_file_is_the_resolutions_path_minus_the_tail() {
|
||||
let src = "\
|
||||
module top;
|
||||
pkt_t p;
|
||||
initial begin
|
||||
$display(p.hdr);
|
||||
$display(p.hdr.addr);
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let cases: &[(&str, &str, &[&str], &str)] =
|
||||
&[("p.hdr", "p", &[], "pkt_t"), ("p.hdr.addr", "p", &["hdr"], "pkt_t::hdr")];
|
||||
for (needle, head, mids, expected_site) in cases {
|
||||
let at = tail(src, needle);
|
||||
let Resolution::ExternalCandidate { paths } = resolution_at(&s, at) else {
|
||||
panic!("{needle} must be the workspace's business");
|
||||
};
|
||||
let member = needle.rsplit('.').next().expect("a tail");
|
||||
assert_eq!(paths, vec![format!("{expected_site}::{member}")], "{needle}");
|
||||
|
||||
let mids: Vec<String> = mids.iter().map(|m| (*m).to_string()).collect();
|
||||
assert_eq!(
|
||||
s.member_site(scope_at(&s, at), head, &mids),
|
||||
Some(MemberSite::Unit((*expected_site).to_string())),
|
||||
"{needle}: the site is the path the resolution walks, minus the tail",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// An in-file class extending a class in another file: the site is this
|
||||
/// file's scope, and `member_scopes` hands back the base by name so the
|
||||
/// caller can finish the list from the index — which is the very base the
|
||||
/// resolution records as its `InheritedCandidate`.
|
||||
#[test]
|
||||
fn an_extends_that_leaves_the_file_reports_the_base_the_resolution_records() {
|
||||
let src = "\
|
||||
class here extends there;
|
||||
bit mine;
|
||||
endclass
|
||||
|
||||
module top;
|
||||
here h;
|
||||
initial $display(h.theirs);
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let at = tail(src, "h.theirs");
|
||||
let Resolution::InheritedCandidate { base, .. } = resolution_at(&s, at) else {
|
||||
panic!("an absent base is an inheritance candidate");
|
||||
};
|
||||
assert_eq!(base, "there");
|
||||
|
||||
let site = s.member_site(scope_at(&s, at), "h", &[]).expect("a site");
|
||||
let MemberSite::Scope(scope) = site else { panic!("`here` is declared here") };
|
||||
let (scopes, chain_base) = s.member_scopes(scope);
|
||||
assert_eq!(scopes.len(), 1, "the chain ends at the file's edge");
|
||||
assert_eq!(chain_base.as_deref(), Some("there"), "and names the base the resolution named");
|
||||
assert_eq!(names_in(&s, scope), vec!["mine"], "the known members still list");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// member_scopes
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn member_scopes_walks_the_whole_in_file_extends_chain_nearest_first() {
|
||||
let src = "\
|
||||
class a;
|
||||
bit from_a;
|
||||
bit shared;
|
||||
endclass
|
||||
class b extends a;
|
||||
bit from_b;
|
||||
bit shared;
|
||||
endclass
|
||||
class c extends b;
|
||||
bit from_c;
|
||||
endclass
|
||||
module top;
|
||||
c h;
|
||||
initial $display(h.from_a);
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let at = tail(src, "h.from_a");
|
||||
let MemberSite::Scope(scope) = s.member_site(scope_at(&s, at), "h", &[]).expect("a site")
|
||||
else {
|
||||
panic!("in this file");
|
||||
};
|
||||
let (scopes, base) = s.member_scopes(scope);
|
||||
assert_eq!(scopes.len(), 3, "c, b, a");
|
||||
assert_eq!(base, None, "every link is declared here");
|
||||
assert_eq!(names_in(&s, scope), vec!["from_c", "from_b", "shared", "from_a"]);
|
||||
// The nearest declaration of a shadowed name is the one offered: `shared`
|
||||
// is listed between `from_b` and `from_a`, which is `b`'s copy, and `b`
|
||||
// is where a lookup stops too.
|
||||
assert!(
|
||||
s.scope(scopes[1]).expect("b's scope").lookup_local("shared").is_some(),
|
||||
"b declares the `shared` that wins",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cycle_in_extends_terminates_and_offers_both_classes_members() {
|
||||
let src = "\
|
||||
class a extends b;
|
||||
bit from_a;
|
||||
endclass
|
||||
class b extends a;
|
||||
bit from_b;
|
||||
endclass
|
||||
module top;
|
||||
a h;
|
||||
initial $display(h.from_b);
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let at = tail(src, "h.from_b");
|
||||
let MemberSite::Scope(scope) = s.member_site(scope_at(&s, at), "h", &[]).expect("a site")
|
||||
else {
|
||||
panic!("in this file");
|
||||
};
|
||||
let (scopes, base) = s.member_scopes(scope);
|
||||
assert_eq!(scopes.len(), 2);
|
||||
assert_eq!(base, None, "a cycle ends the chain here, it does not blame a base");
|
||||
assert_eq!(names_in(&s, scope), vec!["from_a", "from_b"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_class_scope_is_its_own_whole_chain() {
|
||||
let s = sem(MIXED);
|
||||
let at = tail(MIXED, "vif.data");
|
||||
let MemberSite::Scope(scope) = s.member_site(scope_at(&s, at), "vif", &[]).expect("a site")
|
||||
else {
|
||||
panic!("bus_if is declared here");
|
||||
};
|
||||
let (scopes, base) = s.member_scopes(scope);
|
||||
assert_eq!(scopes.len(), 1);
|
||||
assert_eq!(base, None);
|
||||
// An interface's surface is its signals *and* its modports — the export
|
||||
// rule interface-semantics settled, read straight off the scope.
|
||||
let names = names_in(&s, scope);
|
||||
for wanted in ["clk", "data", "mp"] {
|
||||
assert!(names.contains(&wanted.to_string()), "{wanted} missing from {names:?}");
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// this / super
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
const INHERITING: &str = "\
|
||||
class base_c;
|
||||
bit from_base;
|
||||
endclass
|
||||
|
||||
class derived_c extends base_c;
|
||||
bit from_derived;
|
||||
function void f();
|
||||
$display(this.from_base);
|
||||
$display(super.from_base);
|
||||
endfunction
|
||||
endclass
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn this_is_the_enclosing_class_and_sees_the_whole_chain() {
|
||||
let s = sem(INHERITING);
|
||||
let at = tail(INHERITING, "this.from_base");
|
||||
let MemberSite::Scope(scope) =
|
||||
s.member_site(scope_at(&s, at), "this", &[]).expect("`this` has a class")
|
||||
else {
|
||||
panic!("in this file");
|
||||
};
|
||||
assert_eq!(names_in(&s, scope), vec!["from_derived", "f", "from_base"]);
|
||||
// And it is the class the resolution used: `this.from_base` resolves to
|
||||
// the base's declaration in this very file.
|
||||
let Resolution::Resolved(id) = resolution_at(&s, at) else {
|
||||
panic!("an in-file base resolves");
|
||||
};
|
||||
assert_eq!(s.symbol(id).expect("a symbol").name, "from_base");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn super_is_the_base_and_does_not_offer_the_derived_classs_own_members() {
|
||||
let s = sem(INHERITING);
|
||||
let at = tail(INHERITING, "super.from_base");
|
||||
let MemberSite::Scope(scope) =
|
||||
s.member_site(scope_at(&s, at), "super", &[]).expect("a base in this file")
|
||||
else {
|
||||
panic!("in this file");
|
||||
};
|
||||
assert_eq!(names_in(&s, scope), vec!["from_base"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn super_with_a_base_in_another_file_names_that_base_as_the_unit() {
|
||||
let src = "class here extends elsewhere_c;\n function void f();\n $display(super.x);\n endfunction\nendclass\n";
|
||||
let s = sem(src);
|
||||
let at = tail(src, "super.x");
|
||||
assert_eq!(
|
||||
s.member_site(scope_at(&s, at), "super", &[]),
|
||||
Some(MemberSite::Unit("elsewhere_c".to_string())),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn this_outside_a_class_answers_nothing() {
|
||||
let src = "module top;\n initial $display(1);\nendmodule\n";
|
||||
let s = sem(src);
|
||||
let at = src.find("$display").expect("a spot") as u32;
|
||||
assert_eq!(s.member_site(innermost(&s, at), "this", &[]), None);
|
||||
assert_eq!(s.member_site(innermost(&s, at), "super", &[]), None);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// heads that answer nothing
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_unresolvable_head_answers_nothing() {
|
||||
let s = sem(MIXED);
|
||||
let at = tail(MIXED, "item.user_id");
|
||||
let from = scope_at(&s, at);
|
||||
assert_eq!(s.member_site(from, "no_such_name", &[]), None, "nothing declares it");
|
||||
assert_eq!(s.member_site(from, "item", &["no_such_member".to_string()]), None, "a dead mid");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_head_this_file_declares_without_members_answers_nothing() {
|
||||
let src = "\
|
||||
module top;
|
||||
typedef enum { A, B } e_t;
|
||||
e_t e;
|
||||
logic [7:0] v;
|
||||
initial $display(1);
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let at = src.find("$display").expect("a spot") as u32;
|
||||
let from = innermost(&s, at);
|
||||
assert_eq!(s.member_site(from, "e", &[]), None, "an enum has no members to name");
|
||||
assert_eq!(s.member_site(from, "v", &[]), None, "nor does a built-in type");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// unit_site — the `::` half
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
const PACKAGED: &str = "\
|
||||
package p;
|
||||
typedef struct packed { logic a; } s_t;
|
||||
localparam int W = 8;
|
||||
class inner_c;
|
||||
bit prop;
|
||||
endclass
|
||||
endpackage
|
||||
|
||||
module top;
|
||||
initial $display(p::W);
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn a_package_this_file_declares_is_its_own_scope_and_lists_its_members() {
|
||||
let s = sem(PACKAGED);
|
||||
let at = tail(PACKAGED, "p::W");
|
||||
let MemberSite::Scope(scope) = s.unit_site(scope_at(&s, at), "p").expect("a site") else {
|
||||
panic!("declared here");
|
||||
};
|
||||
let names = names_in(&s, scope);
|
||||
for wanted in ["s_t", "W", "inner_c"] {
|
||||
assert!(names.contains(&wanted.to_string()), "{wanted} missing from {names:?}");
|
||||
}
|
||||
// And it is the same scope the resolution looked in.
|
||||
let Resolution::Resolved(id) = resolution_at(&s, at) else { panic!("declared here") };
|
||||
assert_eq!(s.symbol(id).expect("a symbol").name, "W");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_class_inside_a_package_is_reached_by_descending_the_path() {
|
||||
let s = sem(PACKAGED);
|
||||
let at = tail(PACKAGED, "p::W");
|
||||
let MemberSite::Scope(scope) =
|
||||
s.unit_site(scope_at(&s, at), "p::inner_c").expect("a nested class")
|
||||
else {
|
||||
panic!("declared here");
|
||||
};
|
||||
assert_eq!(names_in(&s, scope), vec!["prop"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_segment_a_container_here_does_not_hold_answers_nothing() {
|
||||
let s = sem(PACKAGED);
|
||||
let at = tail(PACKAGED, "p::W");
|
||||
assert_eq!(
|
||||
s.unit_site(scope_at(&s, at), "p::no_such_class"),
|
||||
None,
|
||||
"this file has answered what `p` holds",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_no_file_here_declares_is_the_workspaces_unit() {
|
||||
let src = "module top;\n initial $display(other_pkg::x);\nendmodule\n";
|
||||
let s = sem(src);
|
||||
let at = tail(src, "other_pkg::x");
|
||||
assert_eq!(
|
||||
s.unit_site(scope_at(&s, at), "other_pkg"),
|
||||
Some(MemberSite::Unit("other_pkg".to_string())),
|
||||
);
|
||||
// Which is exactly the unit the resolution's own path names.
|
||||
let Resolution::ExternalCandidate { paths } = resolution_at(&s, at) else {
|
||||
panic!("the workspace's business");
|
||||
};
|
||||
assert_eq!(paths, vec!["other_pkg::x".to_string()]);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the index: members_of_chain and member_unit
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
const IDX_BASE: &str = "class base_c;\n bit from_base;\n bit shared;\nendclass\n";
|
||||
const IDX_MID: &str = "class mid_c extends base_c;\n bit from_mid;\n bit shared;\nendclass\n";
|
||||
const IDX_TOP: &str = "class top_c extends mid_c;\n bit from_top;\nendclass\n";
|
||||
|
||||
#[test]
|
||||
fn members_of_chain_includes_two_hops_of_inherited_members() {
|
||||
let ws = index(&[("base.sv", IDX_BASE), ("mid.sv", IDX_MID), ("top.sv", IDX_TOP)]);
|
||||
assert_eq!(site_names(&ws, "top_c"), vec!["from_base", "from_mid", "from_top", "shared"]);
|
||||
// `members_of` alone is the round's motivation: it stops at the class.
|
||||
let own: Vec<&str> = ws.members_of("top_c").map(|(name, _)| name).collect();
|
||||
assert_eq!(own, vec!["from_top"], "the uninherited list is what this replaces");
|
||||
}
|
||||
|
||||
/// The dedup rule, stated as the one-walk property it exists for: for **every
|
||||
/// name** the list offers, the `Def` listed is the `Def` a lookup of that
|
||||
/// name finds. A subclass's `shared` shadows the base's in both.
|
||||
#[test]
|
||||
fn every_listed_member_is_the_def_a_lookup_of_that_name_finds() {
|
||||
let ws = index(&[("base.sv", IDX_BASE), ("mid.sv", IDX_MID), ("top.sv", IDX_TOP)]);
|
||||
for (name, listed) in ws.members_of_chain("top_c") {
|
||||
let found = follow(&ws, "top_c", name);
|
||||
assert_eq!(Some(listed), found, "{name}: the list and the lookup must name one file");
|
||||
}
|
||||
// And the shadowed one really is shadowed: `shared` comes from mid_c,
|
||||
// not base_c.
|
||||
let shared = ws.members_of_chain("top_c").into_iter().find(|(n, _)| *n == "shared");
|
||||
let (_, def) = shared.expect("shared is listed");
|
||||
assert_eq!(ws.path(def.file).and_then(|p| p.file_name()).unwrap(), "mid.sv");
|
||||
}
|
||||
|
||||
/// What `member_chain` finds for one name, re-derived through the public API
|
||||
/// the same way the overlay does: the unit, then its bases.
|
||||
fn follow<'i>(ws: &'i WorkspaceIndex, unit: &str, name: &str) -> Option<&'i vlog_semantic::Def> {
|
||||
let mut current = unit.to_string();
|
||||
let mut seen: Vec<String> = Vec::new();
|
||||
while !seen.contains(¤t) {
|
||||
seen.push(current.clone());
|
||||
if let [def, ..] = ws.member(¤t, name) {
|
||||
return Some(def);
|
||||
}
|
||||
let next = ws.base_of(¤t)?;
|
||||
current = next.rsplit("::").next().unwrap_or(next).to_string();
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn members_of_chain_follows_a_file_scope_typedef_alias() {
|
||||
let ws = index(&[("base.sv", IDX_BASE), ("alias.sv", "typedef base_c alias_t;\n")]);
|
||||
assert_eq!(site_names(&ws, "alias_t"), vec!["from_base", "shared"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cycle_in_the_indexs_own_chain_terminates() {
|
||||
let ws = index(&[
|
||||
("a.sv", "class a_c extends b_c;\n bit from_a;\nendclass\n"),
|
||||
("b.sv", "class b_c extends a_c;\n bit from_b;\nendclass\n"),
|
||||
]);
|
||||
assert_eq!(site_names(&ws, "a_c"), vec!["from_a", "from_b"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_base_the_workspace_does_not_declare_still_lists_what_it_knows() {
|
||||
let ws = index(&[("here.sv", "class here_c extends nowhere_c;\n bit mine;\nendclass\n")]);
|
||||
assert_eq!(site_names(&ws, "here_c"), vec!["mine"]);
|
||||
assert!(site_names(&ws, "nowhere_c").is_empty(), "and an unknown unit lists nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_lists_its_members_and_has_no_chain_to_walk() {
|
||||
let ws = index(&[(
|
||||
"p.sv",
|
||||
"package p;\n typedef struct packed { logic a; } s_t;\n localparam int W = 8;\nendpackage\n",
|
||||
)]);
|
||||
let names = site_names(&ws, "p");
|
||||
for wanted in ["s_t", "W"] {
|
||||
assert!(names.contains(&wanted.to_string()), "{wanted} missing from {names:?}");
|
||||
}
|
||||
assert_eq!(ws.base_of("p"), None);
|
||||
}
|
||||
|
||||
/// `member_unit` is the old private `member_type`, unchanged in behaviour —
|
||||
/// the hop `follow_one` folds a composed path by, now public so a completion
|
||||
/// list can fold the very same path the very same way.
|
||||
#[test]
|
||||
fn member_unit_answers_the_declared_type_of_one_member() {
|
||||
let ws = index(&[
|
||||
("hdr.sv", "typedef struct packed { logic [7:0] addr; } hdr_t;\n"),
|
||||
("pkt.sv", "class pkt_t;\n hdr_t hdr;\nendclass\n"),
|
||||
]);
|
||||
assert_eq!(ws.member_unit("pkt_t", "hdr").as_deref(), Some("hdr_t"));
|
||||
assert_eq!(ws.member_unit("pkt_t", "nope"), None, "no such member");
|
||||
assert_eq!(ws.member_unit("nope_t", "hdr"), None, "no such unit");
|
||||
// A member with no recorded type takes no hop.
|
||||
let plain = index(&[("c.sv", "class c_t;\n bit flag;\nendclass\n")]);
|
||||
assert_eq!(plain.member_unit("c_t", "flag"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn member_unit_refuses_a_type_name_the_workspace_declares_twice() {
|
||||
let ws = index(&[
|
||||
("one.sv", "typedef struct packed { logic a; } dup_t;\n"),
|
||||
("two.sv", "class dup_t;\n bit b;\nendclass\n"),
|
||||
("pkt.sv", "class pkt_t;\n dup_t d;\nendclass\n"),
|
||||
]);
|
||||
assert_eq!(ws.member_unit("pkt_t", "d"), None, "two declarations are two answers");
|
||||
assert!(ws.members_of_chain("pkt_t::d").is_empty(), "so the composed path lists nothing");
|
||||
}
|
||||
|
||||
/// A composed `MemberSite::Unit` path is folded by exactly the hops
|
||||
/// `follow_one` folds it by — this is the cross-file half of the one-walk
|
||||
/// claim, checked against the synthesized key struct-members mints.
|
||||
#[test]
|
||||
fn a_composed_path_lists_the_members_the_same_hops_reach() {
|
||||
let ws = index(&[(
|
||||
"regs.sv",
|
||||
"package p;\n typedef struct packed {\n struct packed { logic q; logic qe; } ctrl;\n } reg2hw_t;\nendpackage\n",
|
||||
)]);
|
||||
assert_eq!(site_names(&ws, "reg2hw_t"), vec!["ctrl"]);
|
||||
assert_eq!(site_names(&ws, "reg2hw_t::ctrl"), vec!["q", "qe"]);
|
||||
// And a lookup of one of them lands where the list says it does.
|
||||
let listed = ws.members_of_chain("reg2hw_t::ctrl");
|
||||
let (_, def) = listed.iter().find(|(n, _)| *n == "q").expect("q is listed");
|
||||
assert_eq!(ws.member("reg2hw_t.ctrl", "q"), std::slice::from_ref(*def));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the two halves together: an in-file class whose base is elsewhere
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_in_file_class_merges_its_own_scope_with_the_indexs_base_members() {
|
||||
let ws = index(&[("base.sv", IDX_BASE)]);
|
||||
let src = "\
|
||||
class local_c extends base_c;
|
||||
bit mine;
|
||||
endclass
|
||||
module top;
|
||||
local_c h;
|
||||
initial $display(h.mine);
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let at = tail(src, "h.mine");
|
||||
let MemberSite::Scope(scope) = s.member_site(scope_at(&s, at), "h", &[]).expect("a site")
|
||||
else {
|
||||
panic!("declared here");
|
||||
};
|
||||
let (_, base) = s.member_scopes(scope);
|
||||
let base = base.expect("the chain leaves the file");
|
||||
let mut names = names_in(&s, scope);
|
||||
names.extend(site_names(&ws, &base));
|
||||
assert_eq!(names, vec!["mine", "from_base", "shared"]);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// nothing about the existing walk changed
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The refactor is an extraction, not a rewrite: the kinds and the scope
|
||||
/// shapes the mixed fixture resolves through are what they were, checked
|
||||
/// through the same public surface every other consumer reads.
|
||||
#[test]
|
||||
fn the_mixed_fixture_still_resolves_exactly_what_it_resolved() {
|
||||
let s = sem(MIXED);
|
||||
let kind_of = |needle: &str| {
|
||||
let Resolution::Resolved(id) = resolution_at(&s, tail(MIXED, needle)) else {
|
||||
panic!("{needle} resolves in this file");
|
||||
};
|
||||
s.symbol(id).expect("a symbol").kind
|
||||
};
|
||||
assert_eq!(kind_of("item.user_id"), SymbolKind::Var);
|
||||
assert_eq!(kind_of("item.hdr.addr"), SymbolKind::StructMember);
|
||||
assert_eq!(kind_of("vif.data"), SymbolKind::Var);
|
||||
assert_eq!(kind_of("h.vld"), SymbolKind::StructMember);
|
||||
// And a `Scope` value is still just a scope: nothing here mutates one.
|
||||
let _: &Scope = s.scope(s.file_scope()).expect("the file scope");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// `localparam` is its own kind (2026-09-02, QA finding 1)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The opentitan shape that found this: `prim_fifo_sync`'s header derives a
|
||||
/// width with a `localparam`, which is **not overridable** — and before this
|
||||
/// round it was bound as a `Param` and offered in a `#(.` override list.
|
||||
const DERIVED: &str = "\
|
||||
module fifo #(
|
||||
parameter int Depth = 4,
|
||||
localparam int DepthW = 3,
|
||||
DepthX = 4,
|
||||
parameter int Again = 1
|
||||
) (
|
||||
input logic clk
|
||||
);
|
||||
localparam int Body = 7;
|
||||
parameter int BodyP = 8;
|
||||
endmodule
|
||||
";
|
||||
|
||||
fn kind_of(s: &Semantics, name: &str) -> SymbolKind {
|
||||
let id = s.symbols_named(name).next().unwrap_or_else(|| panic!("no symbol {name}"));
|
||||
s.symbol(id).expect("a symbol").kind
|
||||
}
|
||||
|
||||
/// The keyword decides the kind, and it is **sticky**: a continuation entry
|
||||
/// writes none and inherits the one before it, so `DepthX` is a localparam
|
||||
/// and `Again` — which writes `parameter` again — is not.
|
||||
#[test]
|
||||
fn the_parameter_keyword_decides_the_kind_and_carries_forward() {
|
||||
let s = sem(DERIVED);
|
||||
assert_eq!(kind_of(&s, "Depth"), SymbolKind::Param);
|
||||
assert_eq!(kind_of(&s, "DepthW"), SymbolKind::LocalParam);
|
||||
assert_eq!(kind_of(&s, "DepthX"), SymbolKind::LocalParam, "a continuation inherits the kw");
|
||||
assert_eq!(kind_of(&s, "Again"), SymbolKind::Param, "and a written kw takes over again");
|
||||
assert_eq!(kind_of(&s, "Body"), SymbolKind::LocalParam, "a body localparam too");
|
||||
assert_eq!(kind_of(&s, "BodyP"), SymbolKind::Param);
|
||||
}
|
||||
|
||||
/// The **exports are unchanged**: a hierarchical read `u_fifo.DepthW` is legal
|
||||
/// SystemVerilog and resolved before this round, so it still does. What the
|
||||
/// split changes is what may be *offered* as an override, which is
|
||||
/// `lucisv_server`'s business and pinned there.
|
||||
#[test]
|
||||
fn a_localparam_is_still_exported_and_still_resolves() {
|
||||
let ws = index(&[("fifo.sv", DERIVED)]);
|
||||
let names = site_names(&ws, "fifo");
|
||||
for wanted in ["Depth", "DepthW", "DepthX", "Again", "Body", "BodyP"] {
|
||||
assert!(names.contains(&wanted.to_string()), "{wanted} missing from {names:?}");
|
||||
}
|
||||
// …and one by one, through the very lookup a `.DepthW` use takes.
|
||||
let [def] = ws.member("fifo", "DepthW") else { panic!("one declaration") };
|
||||
assert_eq!(def.kind, SymbolKind::LocalParam);
|
||||
let [def] = ws.member("fifo", "Depth") else { panic!("one declaration") };
|
||||
assert_eq!(def.kind, SymbolKind::Param);
|
||||
}
|
||||
|
||||
/// An **override written in source** still resolves to the declaration it
|
||||
/// names. `.DepthW(1)` is illegal SystemVerilog, but naming the localparam is
|
||||
/// the honest answer to "what does this identifier refer to" — the compiler's
|
||||
/// complaint is the compiler's, and answering nothing would be a worse lie.
|
||||
#[test]
|
||||
fn an_override_written_against_a_localparam_still_names_it() {
|
||||
let src = "module top;\n fifo #(.DepthW(1), .Depth(8)) u ();\nendmodule\n";
|
||||
let s = sem(src);
|
||||
let ws = index(&[("fifo.sv", DERIVED), ("top.sv", src)]);
|
||||
let overlay = resolve_external(&s, &ws);
|
||||
for (needle, kind) in [(".DepthW", SymbolKind::LocalParam), (".Depth(8)", SymbolKind::Param)] {
|
||||
let at = src.find(needle).expect("an override") as u32 + 1;
|
||||
let id = s.reference_id_at(at).expect("a reference at the override");
|
||||
let defs = overlay.get(id).expect("an answer").defs();
|
||||
assert_eq!(defs.len(), 1, "{needle}");
|
||||
assert_eq!(defs[0].kind, kind, "{needle}");
|
||||
}
|
||||
}
|
||||
@@ -70,7 +70,9 @@ endmodule
|
||||
("q", SymbolKind::Port),
|
||||
("net_w", SymbolKind::Net),
|
||||
("var_l", SymbolKind::Var),
|
||||
("LP", SymbolKind::Param),
|
||||
// A body `localparam` — its own kind since 2026-09-02, beside the
|
||||
// header `parameter` W two lines up.
|
||||
("LP", SymbolKind::LocalParam),
|
||||
("gi", SymbolKind::Genvar),
|
||||
("two_t", SymbolKind::Typedef),
|
||||
("f", SymbolKind::Function),
|
||||
@@ -284,7 +286,7 @@ endmodule
|
||||
// From a use, too — including a package-scoped one.
|
||||
let k = s.definition_of(nth(src, "p::K", 0) + 3).expect("go to definition of p::K");
|
||||
assert_eq!(k.name, "K");
|
||||
assert_eq!(k.kind, SymbolKind::Param);
|
||||
assert_eq!(k.kind, SymbolKind::LocalParam, "`localparam int K = 1;` — and it still resolves");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -511,7 +513,98 @@ endmodule
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hierarchical_name_resolves_only_its_head() {
|
||||
fn a_non_ansi_port_records_where_its_body_declaration_completes_it() {
|
||||
let src = "\
|
||||
module m (a, b);
|
||||
input [7:0] a;
|
||||
output b;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let a = symbol_named(&s, "a");
|
||||
let detail = a.detail_span.expect("the body declaration's span");
|
||||
assert!(
|
||||
src[detail.start as usize..detail.end as usize].starts_with("input [7:0] a"),
|
||||
"the detail site covers the body declaration: {:?}",
|
||||
&src[detail.start as usize..detail.end as usize]
|
||||
);
|
||||
// ...while the name stays in the header.
|
||||
assert_eq!(&src[a.name_span.start as usize..a.name_span.end as usize], "a");
|
||||
assert!(a.name_span.start < detail.start);
|
||||
|
||||
// An ANSI port is complete where it is named: no detail site.
|
||||
let ansi = sem("module m (input wire clk);\nendmodule\n");
|
||||
assert_eq!(symbol_named(&ansi, "clk").detail_span, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_old_style_task_argument_records_its_body_declaration_too() {
|
||||
// `task t(a);` names the argument and `input [7:0] a;` finishes it —
|
||||
// the same shape a non-ANSI module port has, merged by the same
|
||||
// `declare`, so it carries the same detail site (QA, PDS-3).
|
||||
let src = "\
|
||||
module m;
|
||||
task t(a);
|
||||
input [7:0] a;
|
||||
$display(a);
|
||||
endtask
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let a = symbol_named(&s, "a");
|
||||
assert_eq!(a.kind, SymbolKind::TfArg);
|
||||
let detail = a.detail_span.expect("the body declaration's span");
|
||||
assert_eq!(&src[detail.start as usize..detail.end as usize], "input [7:0] a;");
|
||||
assert!(a.name_span.start < detail.start, "the name stays in the header");
|
||||
|
||||
// An argument complete where it is named has no detail site, as before.
|
||||
let ansi = sem("module m;\n task t(input [7:0] a);\n endtask\nendmodule\n");
|
||||
assert_eq!(symbol_named(&ansi, "a").detail_span, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn looking_a_name_up_answers_exactly_what_scanning_every_symbol_would() {
|
||||
// The name-keyed lookup exists so a caller never walks the whole symbol
|
||||
// table to find the declarations spelling one name. It is only a
|
||||
// substitution if it answers the same symbols in the same order — and the
|
||||
// order is what decides the tie when one buffer holds two declarations of
|
||||
// one name, as a mid-edit buffer does.
|
||||
// One scope never binds a name twice (`bind::declare`), so two
|
||||
// declarations of one name means two scopes — a buffer holding an old
|
||||
// module and its half-written replacement, which is the tie
|
||||
// `hover::live_symbol` has to break.
|
||||
let src = "\
|
||||
module m (input wire dup);
|
||||
wire other;
|
||||
endmodule
|
||||
module n (input wire [7:0] dup);
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
for name in ["dup", "other", "m", "n", "absent"] {
|
||||
let scanned: Vec<SymbolId> = s
|
||||
.symbols()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, sym)| sym.name == name)
|
||||
.map(|(i, _)| SymbolId(i as u32))
|
||||
.collect();
|
||||
let looked_up: Vec<SymbolId> = s.symbols_named(name).collect();
|
||||
assert_eq!(looked_up, scanned, "the two answers must agree for {name}");
|
||||
}
|
||||
// The one that matters: two `dup`s, and the first is the earlier one.
|
||||
let dups: Vec<SymbolId> = s.symbols_named("dup").collect();
|
||||
assert_eq!(dups.len(), 2, "{dups:?}");
|
||||
assert!(dups[0].0 < dups[1].0, "declaration order, so the first match is the first written");
|
||||
}
|
||||
|
||||
/// A hierarchical name through an **instance** resolves both halves since
|
||||
/// 2026-09-01 (class-member-access round 2): the instance's declared type is
|
||||
/// the module it instantiates, so the tail is looked up in that module's
|
||||
/// scope. A head that is neither typed nor a unit still resolves alone, which
|
||||
/// is what this test pinned before and still pins in its second half.
|
||||
#[test]
|
||||
fn a_hierarchical_name_through_an_instance_resolves_both_halves() {
|
||||
let src = "\
|
||||
module m;
|
||||
sub u ();
|
||||
@@ -526,7 +619,24 @@ endmodule
|
||||
let s = sem(src);
|
||||
let head = s.reference_at(nth(src, "u.inner_sig", 0)).expect("the head");
|
||||
assert_eq!(head.resolved(), Some(symbol_id(&s, "u")));
|
||||
// The tail is not recorded at all — see the README's non-goals.
|
||||
let tail = s.reference_at(nth(src, "u.inner_sig", 0) + 2).expect("the tail");
|
||||
assert_eq!(tail.resolved(), Some(symbol_id(&s, "inner_sig")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hierarchical_name_off_an_untyped_head_resolves_only_its_head() {
|
||||
let src = "\
|
||||
module m;
|
||||
logic [3:0] u;
|
||||
assign x = u.inner_sig;
|
||||
wire x;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let head = s.reference_at(nth(src, "u.inner_sig", 0)).expect("the head");
|
||||
assert_eq!(head.resolved(), Some(symbol_id(&s, "u")));
|
||||
// The tail is not recorded at all — a built-in type names no declaration
|
||||
// to look a member up in.
|
||||
let tail = nth(src, "u.inner_sig", 0) + 2;
|
||||
assert!(s.reference_at(tail).is_none());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,588 @@
|
||||
//! `s.field` through a `struct`/`union`-typed value: the in-file lookup, the
|
||||
//! cross-file member table, and the three anonymous forms that had no symbols
|
||||
//! at all before this round. The rules live in
|
||||
//! `docs/features/struct-members/README.md`.
|
||||
//!
|
||||
//! The governing rule, inherited from class-member-access and load-bearing for
|
||||
//! every "records nothing" assertion below: **a link that cannot be resolved
|
||||
//! honestly records nothing, and nothing after it — a wrong answer is the only
|
||||
//! forbidden outcome.**
|
||||
|
||||
use std::path::PathBuf;
|
||||
use vlog_parser::parse_source;
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, Def, ExternalTarget, FileFacts, Resolution, Semantics, SymbolId,
|
||||
SymbolKind, WorkspaceIndex,
|
||||
};
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// helpers — the same shapes `member_access.rs` uses, so the two files read
|
||||
// alike and a reader moving between them is never guessing.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
fn sem(src: &str) -> Semantics {
|
||||
let file = parse_source(src).expect("fixture must parse");
|
||||
analyze(&file, src)
|
||||
}
|
||||
|
||||
/// Offset of the `n`th (0-based) occurrence of `needle`.
|
||||
fn nth(src: &str, needle: &str, n: usize) -> u32 {
|
||||
src.match_indices(needle).nth(n).expect("occurrence must exist").0 as u32
|
||||
}
|
||||
|
||||
/// The offset of the **last** `.`-separated name of the `n`th occurrence of
|
||||
/// `needle` — the tail of a member access, which is what this feature records.
|
||||
fn tail(src: &str, needle: &str, n: usize) -> u32 {
|
||||
let at = nth(src, needle, n);
|
||||
at + needle.rfind('.').expect("a member access") as u32 + 1
|
||||
}
|
||||
|
||||
/// The offset of the link `k` dots into the `n`th occurrence of `needle`
|
||||
/// (`link(src, "a.b.c", 0, 1)` is `b`).
|
||||
fn link(src: &str, needle: &str, n: usize, k: usize) -> u32 {
|
||||
let at = nth(src, needle, n);
|
||||
let dot = needle.match_indices('.').nth(k - 1).expect("that many dots").0;
|
||||
at + dot as u32 + 1
|
||||
}
|
||||
|
||||
fn resolution_at(s: &Semantics, offset: u32) -> Resolution {
|
||||
s.reference_at(offset).unwrap_or_else(|| panic!("no reference at {offset}")).resolution.clone()
|
||||
}
|
||||
|
||||
fn symbol_named(s: &Semantics, name: &str) -> SymbolId {
|
||||
let (i, _) = s
|
||||
.symbols()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_, sym)| sym.name == name)
|
||||
.unwrap_or_else(|| panic!("no symbol {name}"));
|
||||
SymbolId(i as u32)
|
||||
}
|
||||
|
||||
fn index(files: &[(&str, &str)]) -> WorkspaceIndex {
|
||||
WorkspaceIndex::build(files.iter().map(|(name, src)| (PathBuf::from(name), *src)))
|
||||
}
|
||||
|
||||
/// The workspace's answer for the use at `offset` in `src`, resolved against
|
||||
/// `ws`.
|
||||
fn overlay_def(ws: &WorkspaceIndex, src: &str, offset: u32) -> Option<Def> {
|
||||
let s = sem(src);
|
||||
let id = s.reference_id_at(offset)?;
|
||||
resolve_external(&s, ws).get(id).and_then(ExternalTarget::best).cloned()
|
||||
}
|
||||
|
||||
/// Every workspace answer for the use at `offset`, ambiguity included.
|
||||
fn overlay_target(ws: &WorkspaceIndex, src: &str, offset: u32) -> Option<ExternalTarget> {
|
||||
let s = sem(src);
|
||||
let id = s.reference_id_at(offset)?;
|
||||
resolve_external(&s, ws).get(id).cloned()
|
||||
}
|
||||
|
||||
fn file_name(ws: &WorkspaceIndex, def: &Def) -> String {
|
||||
ws.path(def.file)
|
||||
.and_then(|p| p.file_name())
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// in one file
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The gap this round exists to close, in both spellings the grammar has: a
|
||||
/// `struct` and a `union` answer their own fields.
|
||||
#[test]
|
||||
fn a_struct_and_a_union_both_answer_their_fields() {
|
||||
let src = "\
|
||||
typedef struct packed { logic [7:0] addr; logic valid; } bus_t;
|
||||
typedef union packed { logic [7:0] byte_view; logic [7:0] raw; } view_t;
|
||||
|
||||
module m;
|
||||
bus_t s;
|
||||
view_t v;
|
||||
initial begin
|
||||
y = s.addr;
|
||||
y = s.valid;
|
||||
y = v.byte_view;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
for spelling in ["s.addr", "s.valid", "v.byte_view"] {
|
||||
let name = spelling.split('.').nth(1).expect("a member");
|
||||
assert_eq!(
|
||||
resolution_at(&s, tail(src, spelling, 0)),
|
||||
Resolution::Resolved(symbol_named(&s, name)),
|
||||
"{spelling}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A field is a declaration with a **declared type**, so the chain hops
|
||||
/// through it exactly as a class property's does.
|
||||
#[test]
|
||||
fn a_chain_hops_through_a_fields_own_type() {
|
||||
let src = "\
|
||||
typedef struct packed { logic [7:0] addr; } hdr_t;
|
||||
typedef struct packed { hdr_t hdr; logic ok; } pkt_t;
|
||||
|
||||
module m;
|
||||
pkt_t p;
|
||||
initial y = p.hdr.addr;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
assert_eq!(
|
||||
resolution_at(&s, link(src, "p.hdr.addr", 0, 1)),
|
||||
Resolution::Resolved(symbol_named(&s, "hdr")),
|
||||
"the middle link"
|
||||
);
|
||||
assert_eq!(
|
||||
resolution_at(&s, tail(src, "p.hdr.addr", 0)),
|
||||
Resolution::Resolved(symbol_named(&s, "addr")),
|
||||
"and the tail, in the field's own type"
|
||||
);
|
||||
}
|
||||
|
||||
/// A field's type carries the same unpacked rule every other declarator does:
|
||||
/// `hdr_t hdrs [4]` names a container, not a value of the type, so the chain
|
||||
/// stops rather than pretending the array is one element.
|
||||
#[test]
|
||||
fn an_unpacked_field_carries_no_type_and_stops_the_chain() {
|
||||
let src = "\
|
||||
typedef struct packed { logic [7:0] addr; } hdr_t;
|
||||
typedef struct packed { hdr_t hdrs [4]; } pkt_t;
|
||||
|
||||
module m;
|
||||
pkt_t p;
|
||||
initial y = p.hdrs.addr;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
assert_eq!(
|
||||
resolution_at(&s, link(src, "p.hdrs.addr", 0, 1)),
|
||||
Resolution::Resolved(symbol_named(&s, "hdrs")),
|
||||
"the field itself is still a declaration"
|
||||
);
|
||||
assert!(
|
||||
s.reference_at(tail(src, "p.hdrs.addr", 0)).is_none(),
|
||||
"but its element's type is not the array's"
|
||||
);
|
||||
}
|
||||
|
||||
/// A field a struct genuinely does not have records nothing: the body is
|
||||
/// written here whole, so no other file could supply it and `NotFound` would
|
||||
/// overstate what is known.
|
||||
#[test]
|
||||
fn a_field_absent_from_a_struct_declared_here_records_nothing() {
|
||||
let src = "\
|
||||
typedef struct packed { logic a; } s_t;
|
||||
|
||||
module m;
|
||||
s_t s;
|
||||
initial y = s.nope;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
assert!(s.reference_at(tail(src, "s.nope", 0)).is_none());
|
||||
}
|
||||
|
||||
/// The two heads that still record nothing, and must: an `enum` typedef, whose
|
||||
/// `.name()`/`.next()` are built-in methods rather than members of anything
|
||||
/// this crate models, and an alias of a built-in.
|
||||
#[test]
|
||||
fn enum_and_builtin_alias_heads_are_untouched_by_this_round() {
|
||||
let src = "\
|
||||
typedef int alias_t;
|
||||
typedef enum { IDLE, RUN } state_e;
|
||||
|
||||
module m;
|
||||
alias_t v;
|
||||
state_e st;
|
||||
initial begin
|
||||
y = v.whatever;
|
||||
y = st.name;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
assert!(s.reference_at(tail(src, "v.whatever", 0)).is_none(), "an alias of a built-in");
|
||||
assert!(s.reference_at(tail(src, "st.name", 0)).is_none(), "an enum's built-in method");
|
||||
}
|
||||
|
||||
/// A struct typedef inside an **in-file** package answers through the
|
||||
/// qualified spelling, on the same descent every other qualified type takes.
|
||||
/// The round-1 pin for a *non*-aggregate typedef in an in-file package
|
||||
/// (`p::alias_t`) is untouched and is re-asserted here beside it.
|
||||
#[test]
|
||||
fn a_struct_typedef_in_an_in_file_package_answers_and_an_alias_still_does_not() {
|
||||
let src = "\
|
||||
package p;
|
||||
typedef struct packed { logic [7:0] addr; } bus_t;
|
||||
typedef int alias_t;
|
||||
endpackage
|
||||
|
||||
module m;
|
||||
p::bus_t s;
|
||||
p::alias_t v;
|
||||
initial begin
|
||||
y = s.addr;
|
||||
y = v.whatever;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
assert_eq!(
|
||||
resolution_at(&s, tail(src, "s.addr", 0)),
|
||||
Resolution::Resolved(symbol_named(&s, "addr")),
|
||||
"the package is walked through and the struct answers"
|
||||
);
|
||||
assert!(
|
||||
s.reference_at(tail(src, "v.whatever", 0)).is_none(),
|
||||
"an int alias in the same package still says nothing"
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the anonymous forms (topo §2.9-13)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// `enum {A, B} x;` declares its variants in the enclosing scope, exactly as
|
||||
/// `typedef enum {A, B} e_t;` always has — one helper, both spellings, and the
|
||||
/// LRM's own rule (IEEE 1800 §6.19).
|
||||
#[test]
|
||||
fn an_anonymous_enums_variants_are_declared_in_the_enclosing_scope() {
|
||||
let src = "\
|
||||
module m;
|
||||
enum logic [1:0] { IDLE, RUN, DONE } state;
|
||||
initial begin
|
||||
state = RUN;
|
||||
if (state == DONE) state = IDLE;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
for name in ["IDLE", "RUN", "DONE"] {
|
||||
assert_eq!(
|
||||
s.symbol(symbol_named(&s, name)).map(|sym| sym.kind),
|
||||
Some(SymbolKind::EnumVariant),
|
||||
"{name} is declared"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
resolution_at(&s, nth(src, "= RUN", 0) + 2),
|
||||
Resolution::Resolved(symbol_named(&s, "RUN")),
|
||||
"and a bare use of one resolves"
|
||||
);
|
||||
}
|
||||
|
||||
/// The same, one level in: an anonymous enum standing as a **struct field's**
|
||||
/// type declares its variants in the scope the struct body is written in.
|
||||
#[test]
|
||||
fn an_enum_inside_a_struct_field_declares_its_variants_outside_the_struct() {
|
||||
let src = "\
|
||||
typedef struct packed {
|
||||
enum logic [1:0] { A_IDLE, A_RUN } mode;
|
||||
logic ok;
|
||||
} cfg_t;
|
||||
|
||||
module m;
|
||||
cfg_t c;
|
||||
initial begin
|
||||
y = c.mode;
|
||||
y = A_RUN;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
assert_eq!(
|
||||
resolution_at(&s, tail(src, "c.mode", 0)),
|
||||
Resolution::Resolved(symbol_named(&s, "mode")),
|
||||
"the field itself"
|
||||
);
|
||||
assert_eq!(
|
||||
resolution_at(&s, nth(src, "= A_RUN", 0) + 2),
|
||||
Resolution::Resolved(symbol_named(&s, "A_RUN")),
|
||||
"and the variant, bare, from outside the struct"
|
||||
);
|
||||
}
|
||||
|
||||
/// An **anonymous** `struct {…} s;` has no type name for `s.a` to be looked up
|
||||
/// through, so its members hang off the declarator itself.
|
||||
#[test]
|
||||
fn an_anonymous_struct_variable_answers_its_own_fields() {
|
||||
let src = "\
|
||||
module m;
|
||||
struct packed { logic [7:0] addr; logic valid; } s;
|
||||
initial begin
|
||||
y = s.addr;
|
||||
y = s.nope;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
assert_eq!(
|
||||
resolution_at(&s, tail(src, "s.addr", 0)),
|
||||
Resolution::Resolved(symbol_named(&s, "addr"))
|
||||
);
|
||||
assert!(
|
||||
s.reference_at(tail(src, "s.nope", 0)).is_none(),
|
||||
"a field it does not have is still nothing"
|
||||
);
|
||||
}
|
||||
|
||||
/// A body written once and declared under **two** declarators gives each its
|
||||
/// own members — and records the names written inside it exactly once, which
|
||||
/// is why the declaration half and the use half of the binder are separate.
|
||||
#[test]
|
||||
fn two_declarators_share_one_anonymous_body_without_doubling_its_uses() {
|
||||
let src = "\
|
||||
typedef logic [7:0] byte_t;
|
||||
|
||||
module m;
|
||||
struct packed { byte_t addr; } a, b;
|
||||
initial begin
|
||||
y = a.addr;
|
||||
y = b.addr;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
assert!(s.reference_at(tail(src, "a.addr", 0)).is_some(), "the first declarator");
|
||||
assert!(s.reference_at(tail(src, "b.addr", 0)).is_some(), "and the second");
|
||||
let byte_uses =
|
||||
s.references().iter().filter(|r| r.name == "byte_t" && !r.name_span.is_empty()).count();
|
||||
assert_eq!(byte_uses, 1, "the field's type name is written once and recorded once");
|
||||
}
|
||||
|
||||
/// The generated-register-package shape, in one file: an **inline nested**
|
||||
/// field, reached through the scope it opens rather than through a type name
|
||||
/// it does not have. Three levels deep, because register packages are.
|
||||
#[test]
|
||||
fn an_inline_nested_field_answers_in_file_to_any_depth() {
|
||||
let src = "\
|
||||
typedef struct packed {
|
||||
struct packed {
|
||||
struct packed {
|
||||
logic q;
|
||||
logic qe;
|
||||
} inner;
|
||||
} ctrl;
|
||||
} reg2hw_t;
|
||||
|
||||
module m;
|
||||
reg2hw_t reg2hw;
|
||||
initial begin
|
||||
y = reg2hw.ctrl.inner.q;
|
||||
y = reg2hw.ctrl.inner.qe;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
assert_eq!(
|
||||
resolution_at(&s, link(src, "reg2hw.ctrl.inner.q", 0, 1)),
|
||||
Resolution::Resolved(symbol_named(&s, "ctrl"))
|
||||
);
|
||||
assert_eq!(
|
||||
resolution_at(&s, link(src, "reg2hw.ctrl.inner.q", 0, 2)),
|
||||
Resolution::Resolved(symbol_named(&s, "inner"))
|
||||
);
|
||||
assert_eq!(
|
||||
resolution_at(&s, tail(src, "reg2hw.ctrl.inner.q", 0)),
|
||||
Resolution::Resolved(symbol_named(&s, "q"))
|
||||
);
|
||||
assert_eq!(
|
||||
resolution_at(&s, tail(src, "reg2hw.ctrl.inner.qe", 0)),
|
||||
Resolution::Resolved(symbol_named(&s, "qe"))
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// across files
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
const BUS: &str = "typedef struct packed { logic [7:0] addr; logic valid; } bus_t;\n";
|
||||
const USER: &str = "module m;\n bus_t s;\n initial y = s.addr;\nendmodule\n";
|
||||
|
||||
/// A struct typedef at **file scope** in another file: the member table is
|
||||
/// keyed by the typedef's own name, which is what the composed path spells.
|
||||
#[test]
|
||||
fn a_file_scope_struct_typedef_answers_from_another_file() {
|
||||
let ws = index(&[("bus.sv", BUS), ("m.sv", USER)]);
|
||||
let def = overlay_def(&ws, USER, tail(USER, "s.addr", 0)).expect("the field");
|
||||
assert_eq!(def.kind, SymbolKind::StructMember);
|
||||
assert_eq!(file_name(&ws, &def), "bus.sv");
|
||||
}
|
||||
|
||||
/// And the same typedef **inside a package**, which is where a real one lives:
|
||||
/// the members land under the typedef's bare name, exactly as a class nested
|
||||
/// in a package already does, and the qualified spelling composes to it.
|
||||
#[test]
|
||||
fn a_package_nested_struct_typedef_answers_from_another_file() {
|
||||
const PKG: &str =
|
||||
"package bus_pkg;\n typedef struct packed { logic [7:0] addr; } bus_t;\nendpackage\n";
|
||||
const TOP: &str = "module m;\n bus_pkg::bus_t s;\n initial y = s.addr;\nendmodule\n";
|
||||
let ws = index(&[("pkg.sv", PKG), ("m.sv", TOP)]);
|
||||
assert!(ws.units("bus_t").is_empty(), "a typedef inside a package is no file-scope unit");
|
||||
let def = overlay_def(&ws, TOP, tail(TOP, "s.addr", 0)).expect("the field");
|
||||
assert_eq!(def.kind, SymbolKind::StructMember);
|
||||
assert_eq!(file_name(&ws, &def), "pkg.sv");
|
||||
}
|
||||
|
||||
/// The opentitan register-package shape, literally: a package of struct
|
||||
/// typedefs whose fields are inline nested aggregates, and a module in another
|
||||
/// file whose port is typed by the outermost one. `reg2hw.ctrl.tx.q` is the
|
||||
/// most common member access in the whole of RTL.
|
||||
#[test]
|
||||
fn the_register_package_shape_walks_four_links_across_files() {
|
||||
const REG_PKG: &str = "\
|
||||
package uart_reg_pkg;
|
||||
typedef struct packed {
|
||||
struct packed {
|
||||
logic q;
|
||||
} tx;
|
||||
struct packed {
|
||||
logic q;
|
||||
logic qe;
|
||||
} rxrst;
|
||||
} uart_reg2hw_ctrl_reg_t;
|
||||
|
||||
typedef struct packed {
|
||||
uart_reg2hw_ctrl_reg_t ctrl;
|
||||
} uart_reg2hw_t;
|
||||
endpackage
|
||||
";
|
||||
const CORE: &str = "\
|
||||
module uart_core (
|
||||
input uart_reg_pkg::uart_reg2hw_t reg2hw
|
||||
);
|
||||
assign tx_enable = reg2hw.ctrl.tx.q;
|
||||
assign fifo_rst = reg2hw.ctrl.rxrst.qe;
|
||||
endmodule
|
||||
";
|
||||
let ws = index(&[("uart_core.sv", CORE), ("uart_reg_pkg.sv", REG_PKG)]);
|
||||
|
||||
// The synthesized key is what carries the inline nested hop across files.
|
||||
assert_eq!(
|
||||
ws.member("uart_reg2hw_ctrl_reg_t.tx", "q").len(),
|
||||
1,
|
||||
"the inner field is registered under `owner.field`"
|
||||
);
|
||||
assert!(ws.member("uart_reg2hw_ctrl_reg_t.tx", "q")[0].type_name.is_none(), "a plain `logic`");
|
||||
|
||||
let def = overlay_def(&ws, CORE, tail(CORE, "reg2hw.ctrl.tx.q", 0)).expect("the tail");
|
||||
assert_eq!(def.kind, SymbolKind::StructMember);
|
||||
assert_eq!(file_name(&ws, &def), "uart_reg_pkg.sv");
|
||||
assert_eq!(def.lines.name, 4, "the `logic q;` inside `tx`");
|
||||
|
||||
// `qe` and `q` sit in the same inner struct and are told apart, which is
|
||||
// the whole reason the key is synthesized rather than the bare field name.
|
||||
let def = overlay_def(&ws, CORE, tail(CORE, "reg2hw.ctrl.rxrst.qe", 0)).expect("the tail");
|
||||
assert_eq!(def.lines.name, 8);
|
||||
}
|
||||
|
||||
/// The collision the bare-name convention buys, stated as a measurement rather
|
||||
/// than argued away: two packages each declaring `cfg_t` put two `field`s in
|
||||
/// one member table, and the lookup answers **both** or nothing — never one of
|
||||
/// them chosen silently.
|
||||
#[test]
|
||||
fn two_packages_with_the_same_struct_typedef_name_never_answer_one_of_them() {
|
||||
const A: &str = "package pa;\n typedef struct packed { logic field; } cfg_t;\nendpackage\n";
|
||||
const B: &str = "package pb;\n typedef struct packed { logic field; } cfg_t;\nendpackage\n";
|
||||
const TOP: &str = "module m;\n pa::cfg_t c;\n initial y = c.field;\nendmodule\n";
|
||||
let ws = index(&[("a.sv", A), ("b.sv", B), ("top.sv", TOP)]);
|
||||
assert_eq!(ws.member("cfg_t", "field").len(), 2, "the premise: one key, two declarations");
|
||||
match overlay_target(&ws, TOP, tail(TOP, "c.field", 0)) {
|
||||
Some(ExternalTarget::Ambiguous(defs)) => assert_eq!(defs.len(), 2, "every candidate"),
|
||||
Some(ExternalTarget::StillUnresolved) | None => {}
|
||||
other => panic!("a silent pick between two packages: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A hop whose type name the **workspace** declares twice is refused outright,
|
||||
/// which is round 2's guard doing its job now that the struct half can answer.
|
||||
#[test]
|
||||
fn a_hop_through_a_name_the_workspace_declares_twice_is_refused() {
|
||||
const HDR: &str = "typedef struct packed { logic [7:0] addr; } hdr_t;\n";
|
||||
const STRANGER: &str = "class hdr_t;\n bit [7:0] addr;\nendclass\n";
|
||||
const PKT: &str = "typedef struct packed { hdr_t hdr; } pkt_t;\n";
|
||||
const TOP: &str = "module m;\n pkt_t p;\n initial y = p.hdr.addr;\nendmodule\n";
|
||||
let ws = index(&[("hdr.sv", HDR), ("stranger.sv", STRANGER), ("pkt.sv", PKT), ("m.sv", TOP)]);
|
||||
assert_eq!(ws.units("hdr_t").len(), 2, "the premise");
|
||||
assert!(
|
||||
overlay_def(&ws, TOP, tail(TOP, "p.hdr.addr", 0)).is_none(),
|
||||
"two answers is not one answer"
|
||||
);
|
||||
}
|
||||
|
||||
/// A struct-typed value whose type this file declares is **never** handed to
|
||||
/// the workspace, however tempting a same-named class elsewhere looks. Round
|
||||
/// 1's rule, re-attacked now that the in-file answer exists.
|
||||
#[test]
|
||||
fn the_in_file_struct_answers_and_a_stranger_class_never_does() {
|
||||
const A: &str = "\
|
||||
typedef struct packed { logic field; } bus_t;
|
||||
|
||||
module m;
|
||||
bus_t s;
|
||||
initial y = s.field;
|
||||
endmodule
|
||||
";
|
||||
const B: &str = "class bus_t;\n bit field;\nendclass\n";
|
||||
let ws = index(&[("a.sv", A), ("b.sv", B)]);
|
||||
let s = sem(A);
|
||||
assert_eq!(
|
||||
resolution_at(&s, tail(A, "s.field", 0)),
|
||||
Resolution::Resolved(symbol_named(&s, "field")),
|
||||
"answered here"
|
||||
);
|
||||
assert!(
|
||||
overlay_def(&ws, A, tail(A, "s.field", 0)).is_none(),
|
||||
"so the workspace is never asked at all"
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// determinism
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The new member census survives the record format and every index mutation,
|
||||
/// and does not depend on the order files arrive in.
|
||||
#[test]
|
||||
fn struct_members_survive_the_record_format_and_every_index_mutation() {
|
||||
const PKG: &str = "\
|
||||
package p;
|
||||
typedef struct packed {
|
||||
struct packed { logic q; } ctrl;
|
||||
} reg2hw_t;
|
||||
endpackage
|
||||
";
|
||||
const TOP: &str = "module m;\n p::reg2hw_t r;\n initial y = r.ctrl.q;\nendmodule\n";
|
||||
|
||||
// A record encoded and decoded is the same record.
|
||||
let facts = FileFacts::of(PathBuf::from("p.sv"), PKG);
|
||||
let line = facts.encode().expect("encodable");
|
||||
assert_eq!(FileFacts::decode(&line).as_ref(), Some(&facts), "round trip");
|
||||
|
||||
let forward = index(&[("p.sv", PKG), ("top.sv", TOP)]);
|
||||
let backward = index(&[("top.sv", TOP), ("p.sv", PKG)]);
|
||||
assert_eq!(forward.fingerprint(), backward.fingerprint(), "insertion order is not an input");
|
||||
|
||||
let answer = |ws: &WorkspaceIndex| {
|
||||
overlay_def(ws, TOP, tail(TOP, "r.ctrl.q", 0)).map(|d| (d.kind, d.lines.name))
|
||||
};
|
||||
let expected = answer(&forward);
|
||||
assert!(expected.is_some(), "the premise: it answers at all");
|
||||
assert_eq!(answer(&backward), expected);
|
||||
|
||||
// Rebuild the same index by hand, then mutate it back to itself.
|
||||
let mut ws = index(&[("p.sv", PKG), ("top.sv", TOP)]);
|
||||
ws.update_file(PathBuf::from("p.sv"), PKG);
|
||||
assert_eq!(ws.fingerprint(), forward.fingerprint(), "a no-op update is a no-op");
|
||||
assert_eq!(answer(&ws), expected);
|
||||
|
||||
assert!(ws.remove_file(&PathBuf::from("p.sv")));
|
||||
assert!(answer(&ws).is_none(), "the declaring file is gone, so the answer is");
|
||||
ws.absorb(vec![FileFacts::of(PathBuf::from("p.sv"), PKG)], &[]);
|
||||
assert_eq!(answer(&ws), expected, "and comes back when it returns");
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,110 @@
|
||||
# Verilog/SystemVerilog coverage gaps — ranked (2026-09-01)
|
||||
|
||||
What lucisv 0.21.0 does not yet handle, ranked by severity, from two
|
||||
independent sweeps crossed against each other:
|
||||
|
||||
- **Empirical probe** — 71 minimal-but-realistic files (44 RTL, 27 DV)
|
||||
covering the Verilog-2005 / SV-2017 features an RTL or DV engineer
|
||||
writes, each run through `--check`, `--stdout`, a second `--stdout`
|
||||
(idempotency) and a comment/layout eyeball; plus 13 headless LSP
|
||||
hover/definition spot checks. Probe files, harness and logs:
|
||||
the session scratchpad `survey/` (re-runnable). Snapshot binaries were
|
||||
used so concurrent dev rebuilds could not skew results.
|
||||
- **Documentation inventory** — every non-goal, deferral, verbatim
|
||||
capture, non-resolution rule, parse-error string and open handshake
|
||||
across `TODO.md`, `docs/topo.md` §2.9, `syntax_coverage.md` and all
|
||||
108 feature READMEs.
|
||||
|
||||
**Headline:** across every file that parsed, `format(format(x)) ==
|
||||
format(x)` held with zero exceptions and no comment was moved or lost.
|
||||
The gaps are (1) grammar holes, (2) regions the parser captures as opaque
|
||||
verbatim text — they *format* but nothing inside is navigable, renamable
|
||||
or lintable — and (3) semantic blind spots where the LSP answers nothing
|
||||
or, worse, the wrong thing.
|
||||
|
||||
Severity scale: **Critical** = wrong answer or a correctness risk on
|
||||
common code · **High** = common construct with no formatting or no
|
||||
navigation · **Medium** = less common construct, or partial behavior ·
|
||||
**Low** = rare construct or deliberate non-goal worth revisiting only on
|
||||
request.
|
||||
|
||||
---
|
||||
|
||||
## Critical
|
||||
|
||||
| # | Gap | Evidence | Why it ranks here |
|
||||
|---|---|---|---|
|
||||
| C1 | **Rename/references do not see inside verbatim regions** — constraint blocks, covergroups, `property`/`sequence` bodies, concurrent-assertion expressions, `randomize() with {…}`. | Documented: classes, assertions, dv-statements READMEs; vlog-semantic non-goals. | A DV rename of `user_id` rewrites every declaration and use the binder knows and **silently leaves `constraint c { user_id < 5; }` untouched** — output that does not compile. Same for a coverpoint on the renamed field. This is the one gap that turns a refactor into a correctness problem, and constraints/covergroups are in every UVM sequence item and coverage class. Fix path: parse constraint bodies (an expression grammar plus `inside`/`dist`/`->`/`soft`/`solve … before`/`foreach`/`if-else`) and covergroup bodies as real nodes; SVA property expressions can stay opaque longer but must at least yield *identifier occurrences* so rename can warn or refuse. |
|
||||
| C2 | **Modport port resolves to the wrong symbol.** Hover on `.m(b_if.mp)` answers with the instantiated *module*, definition jumps to the module, not the modport. | Probe: LSP check "modport port, used". Documented root: interfaces indexed as `Module`, modport names unbound (topo §2.9-7). | A wrong answer is worse than none. Needs `SymbolKind::Interface` + modport symbols; unlocks C3/H2 too. |
|
||||
|
||||
## High
|
||||
|
||||
| # | Gap | Evidence | Why |
|
||||
|---|---|---|---|
|
||||
| H1 | **Struct field access `s.field` — hover null, definition empty.** | Probe: struct field LSP check. Documented: vlog-semantic rule 4 ("nothing ever looks up into it"), topo §2.9-13. | `typedef struct packed {…} bus_t;` is the standard way RTL carries buses; every `.field` use is dark to hover/definition/references. Needs struct members as symbols (named typedefs and the anonymous form) plus the `type_name` link the §15 round-1 work introduces — the natural §15 round 2. |
|
||||
| H2 | **Virtual-interface signal access `vif.sig` — hover null.** | Probe: `vif.sig_a` LSP check. | The DV daily driver. Same mechanism as H1 once interfaces export their signals (C2's `SymbolKind::Interface`) and `virtual my_if vif` carries `type_name`. |
|
||||
| H3 | **Escaped identifiers are unformattable.** `wire \my-signal ;` → `verification failed: … output has identifier "\my-signal;"`. | Probe: two RTL files, both refused. | The formatter drops the mandatory terminating space, verify.rs catches it (invariant 1 holds), and the whole file is refused. Netlists and synthesis/tool-generated RTL are full of escaped names, so those files cannot be formatted at all. Small formatter fix (emit the space), attack tests owed. |
|
||||
| H4 | **Include-fragment files (`*.svh` class-body pieces) do not parse at all.** | The 6 remaining opentitan sweep failures (clocking-wave README §"11 left"); `cip_base_vseq__tl_errors.svh`, `riscv_custom_instr_enum.sv` etc. | UVM codebases split classes across `` `include``d fragments routinely; a fragment file gets no formatting, no diagnostics, no navigation — the LSP is simply off in it. A "fragment mode" (tolerant top-level fallback to a class-item / module-item / enum-member list when the file's top level fails) is bounded work and does not require preprocessing. |
|
||||
| H5 | **`` `define`` go-to-definition returns nothing** while hover shows the body. | Probe: macro LSP check. | Inconsistent and cheap: the define table already knows the site. |
|
||||
| H6 | **Class member chains `a.b.c` and instance heads `u.port`** through the index. | TODO §15 round 2 (filed); vlog-semantic rule 8. | Follows directly from §15 round 1 (needs `Def::type_name`, FACTS_FORMAT bump). `cfg.vif.clk` and `item.hdr.addr` are the common DV shapes; `u_sub.port` is the common RTL one. |
|
||||
|
||||
## Medium
|
||||
|
||||
| # | Gap | Evidence | Why |
|
||||
|---|---|---|---|
|
||||
| M1 | `specify … endspecify` / `specparam` and UDP `primitive … endprimitive` — hard parse errors. | Probe (3 files); README "still open". Corpus count 0, opentitan 0. | Absent from hand-written RTL, present in every std-cell / IO / memory simulation model a project vendors. Exclude patterns cover most; parsing (opaque-verbatim capture is enough) would stop the errors. |
|
||||
| M2 | `checker … endchecker` — parse error on the checker's port list; `checker` not even a keyword. | Probe; corpus has **13** files with it. | Formal-verification collateral; 13 corpus hits says it is real. |
|
||||
| M3 | `interface class` + `implements` — parse error. | Probe; interfaces/type-hierarchy READMEs. | UVM-style DV uses it occasionally; also blocks type-hierarchy's `implements` edges. |
|
||||
| M4 | Macro call with a space before `(` — `` `uvm_field_int (x, y) `` — clean parse error at item position. | macro-items/lexer-cleanup READMEs; measured 11 opentitan files. | A UVM spelling people actually type. Deliberately deferred because the lexer fix could break expression position; needs a careful round. |
|
||||
| M5 | Directives inside a list *element* or between an instance name and its `(`. | directives-in-instances README; measured 13 files. | The `.a(` ⏎ `` `ifdef `` ⏎ … ⏎ `)` shape in real port maps. |
|
||||
| M6 | Indexed hierarchical `bind` target (`bind top.gen[0].u_core …`). | bind README non-goals. | Binding SVA into generate arrays is common in formal setups. |
|
||||
| M7 | Semantic lints (`unused-signal`, `undriven-net`, `multiply-driven`) ship **off by default**. | linter-core / semantic-lints READMEs; blocked on topo §2.9-6 (workspace-wide "does any file mention this name"). | These are the lints RTL engineers want most; the index now has reference postings and `files_spelling`, so §2.9-6 is closer than when filed. |
|
||||
| M8 | Lint rules do not descend into verbatim regions; clocking blocks routed to `opaque_spans`. | assertions / clocking-wave READMEs. | Same root as C1; resolves with it. |
|
||||
| M9 | Statement-level format fences (inside `always`, case items, port lists) and fences inside class bodies (topo §2.9-3). | format-fences / classes READMEs. | Users protect hand-aligned tables inside procedural blocks; DV users protect them in classes. |
|
||||
| M10 | Error recovery does not reach headers and lists (port lists, parameter lists, for-headers) — a half-typed port list yields a garbage tree. | error-recovery README (QA-confirmed). | Editing experience: diagnostics cascade while typing a header. |
|
||||
| M11 | Anonymous aggregate members (`enum {A,B} x;`) not symbols (topo §2.9-13); cast type `state_t'(0)` records no reference. | overlay-promotion README; probe: enum *typedef'd* members do work. | Partial: named enums navigate, anonymous ones do not. |
|
||||
| M12 | No `lint` key in `lucisv.toml` (topo §2.9-4); no `--rules-doc`. | four READMEs. | Config surface, not language — but it gates per-project rule selection. |
|
||||
| M13 | Modport method prototypes (`import task drive(int x);`), `const` task/function arguments, unnamed DPI formals. | interfaces / dpi-export READMEs. | Real interface-class idioms; each a small grammar arm. |
|
||||
|
||||
## Low
|
||||
|
||||
| # | Gap | Evidence |
|
||||
|---|---|---|
|
||||
| L1 | `expect (@(posedge clk) prop);` — parsed as a call, not a keyword. | Probe. |
|
||||
| L2 | Tagged unions (`union tagged`, `tagged Valid`, `case … matches`). | Probe. |
|
||||
| L3 | `randsequence` production bodies. | Probe; classes README ("building for a user that does not exist" — corpus 0). |
|
||||
| L4 | `alias` statement. | Probe. |
|
||||
| L5 | `config … endconfig`, `library`. | Probe. |
|
||||
| L6 | `->>` non-blocking event trigger; stream `with [range]`; cast bases other than a name/system call; drive strength on a net declaration; net delay written after the type; `let` at statement position; `#(min:typ:max)` clocking skew. | expressions-2 / interfaces / dv-statements READMEs, TODO §11 skips. |
|
||||
| L7 | `` `ifdef `` conditions never evaluated (both arms listed); no macro expansion; stringification passes through. | TODO §7 non-goal — by design, like Verible. |
|
||||
| L8 | Execute-command spelling of the instantiation skeleton for clients without `inlineCompletion` (topo §2.9-19). | inline-instantiation README. |
|
||||
| L9 | `codeAction/resolve` laziness; `inlayHint` zero at default scope; index widen not interleaved. | TODO §10 deferred. |
|
||||
| L10 | Cosmetic: an enum body one-lined when short; `` `uvm_field_* `` lines dedented to the `` `uvm_object_utils_begin `` column (they are plain macro statements — no block for the formatter to see). | Probe observations. |
|
||||
|
||||
---
|
||||
|
||||
## What passed (so nobody re-probes it)
|
||||
|
||||
RTL: `always_ff`/`always_comb`/`always_latch`; `unique`/`unique0`/`priority`; `casez`/`casex`/`inside`; packed/unpacked struct/union/enum + typedefs; multi-dim packed arrays; `'{…}` patterns with default/index keys; streaming and replication; `+:`/`-:`; interfaces with modports, parameterized interface instantiation, interface ports; generate if/case/for with named blocks; `defparam`; `parameter type`; `$clog2`; gate primitives with strengths and delays; `wand`/`wor`/`tri1`/`supply0`; `@*`/`@(*)`; net/procedural/assign delays; `timeunit`/`` `timescale``; `` `define`` with args, `` `ifdef``/`` `elsif``/`` `else``, `` `include``, `` `default_nettype``; attributes; `import`/`export`; `let` (item); `bind`; `$unit`; every literal form; `++`/`+=`/`do while`/`foreach`/`repeat`/`forever`; `fork`/`join_any`/`join_none`, named events, `wait`, `wait fork`, `disable fork`; `void'()`; `static`/`automatic`; DPI import/export; `q[$]`.
|
||||
|
||||
DV: parameterized classes and `extends #()`; `virtual`/`pure virtual`/`extern` + out-of-class bodies; `static`/`local`/`protected`/`const`; `typedef class`; `this`/`super`/`new`; `rand`/`randc`; constraints with `inside`/`dist`/`->`/`if-else`/`soft`/`solve … before`/`foreach`/`unique`; `randomize() with`; `std::randomize`; queues/dynamic/associative arrays and their methods; `.sum`/`.find with`; virtual interfaces + clocking blocks; `program`, `mailbox`, `semaphore`, `process`; covergroups with `bins`/`cross`/`iff`/`sample()`; `property`/`sequence` with arguments; `assert`/`cover`/`assume property` with `|->`/`|=>`/`##[1:$]`/`throughout`/`$rose`/`$past`/`disable iff`; immediate assertions; `$cast`/`$sformatf`/`int'()`; string and enum methods; `$bits`/`$size`/`$typename`; UVM macro blocks incl. multi-line `` `uvm_info``; macro-as-statement; `case … inside` with `?`.
|
||||
|
||||
LSP: hover + definition for package-imported parameters, enum members, class parameters, function arguments, genvars, hierarchical instance ports (`u_sub.port_q`), `let` names.
|
||||
|
||||
## Recommended order
|
||||
|
||||
1. **§15 round 1** (in flight) → **H6 chains** as its round 2 — the same machinery, and it unlocks H1/H2 once the member tables exist.
|
||||
2. **C2 + H2**: `SymbolKind::Interface`, modport symbols, interface member export — fixes a wrong answer and the DV daily driver together.
|
||||
3. **H1**: struct members as symbols (with §2.9-13's anonymous forms).
|
||||
4. **H3**: the escaped-identifier space — a one-line formatter fix with attack tests; ship it in any adjacent round.
|
||||
5. **C1**: constraint and covergroup bodies as real nodes — the biggest single DV win and the one correctness risk; SVA expressions can follow.
|
||||
6. **H4**: fragment mode for `.svh` pieces.
|
||||
7. **M1–M3** grammar arms (specify/UDP/checker/interface class) as one "vendor and formal collateral" round, verbatim capture acceptable.
|
||||
8. **M7** semantic lints on by default via §2.9-6.
|
||||
|
||||
Two stale READMEs found by the inventory, to fix on the next docs pass:
|
||||
`docs/features/interfaces/README.md` still lists `program` and the
|
||||
clocking `= expression` as unsupported (delivered in §11 round 2);
|
||||
`docs/features/dv-statements/README.md` lists `foreach (a[, j])` as not
|
||||
done (delivered by testbench-mopup); `docs/features/assertions/README.md`
|
||||
says `interface` is still a parse error.
|
||||
@@ -36,11 +36,16 @@ write the port *second* to have anything to test.
|
||||
string; `bus_if.mp` follows the same rule, so no consumer needed a new
|
||||
field. The one place the two halves matter is `vlog_semantic`, which binds
|
||||
the interface half (below).
|
||||
- **A modport is not a symbol.** `ItemKind::Modport` is a leaf in
|
||||
`vlog_semantic` (it declares nothing into a scope), so the modport half of
|
||||
the type name is left unbound rather than recorded as a name that could
|
||||
never resolve. The day modports become symbols, the tail is where to bind
|
||||
them.
|
||||
- ~~**A modport is not a symbol.**~~ **Delivered 2026-09-01** by
|
||||
`docs/features/interface-semantics/README.md`: a modport is a
|
||||
`SymbolKind::Modport` declared in its interface's scope, and the tail of the
|
||||
glued type name is bound where this said it would be — in
|
||||
`bind_data_type`, as `Target::TypeMember { unit }`, resolved through the
|
||||
interface's own scope in-file and as the path `bus_if::mp` across files.
|
||||
Until then it read: *`ItemKind::Modport` is a leaf in `vlog_semantic` (it
|
||||
declares nothing into a scope), so the modport half of the type name is left
|
||||
unbound rather than recorded as a name that could never resolve. The day
|
||||
modports become symbols, the tail is where to bind them.*
|
||||
- **`module m (interface bus);`** — the *generic* interface port, whose type
|
||||
is the `interface` keyword itself — is a separate production and still does
|
||||
not parse. It is neither one of the three shapes filed nor reachable from
|
||||
@@ -105,10 +110,15 @@ its name, so it reports `iface_bus.mst` as the type with no change either.
|
||||
itself. It is a different production, none of the three filed shapes
|
||||
needs it, and it wants a `DataType` that can say "any interface", which
|
||||
is a modelling question this round should not answer in passing.
|
||||
- [ ] **Not done, deliberately: `virtual bus_if.mp v;`** — a modport-qualified
|
||||
virtual interface in a *declaration* (§25.9). Reaching it means teaching
|
||||
`parse_opt_data_type` about the dot, which changes how an identifier is
|
||||
read in every position; it needs its own round and its own attack tests.
|
||||
- [x] ~~**Not done, deliberately: `virtual bus_if.mp v;`**~~ — delivered by
|
||||
the testbench-mopup round (2026-08-29): `at_modport_port` — this
|
||||
feature's own gate — is reused at the two `virtual` positions, so the
|
||||
dot is read only where a modport can legally follow, exactly the
|
||||
narrow reading this item said a broad `parse_opt_data_type` change
|
||||
would violate. The pinning test here was amended in the same round
|
||||
(`the_two_shapes_left_open_by_ansi_first_port_still_refuse` still
|
||||
pins what genuinely remains open). See
|
||||
`docs/features/testbench-mopup/README.md`.
|
||||
- [ ] **Not done, pre-existing: `module m (a[3], b);`** — a non-ANSI port with
|
||||
a bit-select. It failed before this round and fails identically after
|
||||
(pinned by `a_broken_header_still_reports_its_own_token`), and it is not
|
||||
@@ -148,9 +158,10 @@ its name, so it reports `iface_bus.mst` as the type with no change either.
|
||||
- **`vlog_semantic` binds the interface, not the glued string.** Left alone,
|
||||
`bind_data_type` would have recorded a use of the name `bus_if.mp`, which
|
||||
resolves nowhere and never could. It now takes the half before the dot. The
|
||||
modport half is dropped rather than bound because this crate declares no
|
||||
symbol for a modport (`ItemKind::Modport` is a leaf, `bind.rs:364`) — a
|
||||
reference to a name nothing can declare is worse than no reference.
|
||||
modport half was dropped rather than bound because this crate declared no
|
||||
symbol for a modport — a reference to a name nothing can declare is worse
|
||||
than no reference. **Since 2026-09-01 it does declare one**, and both halves
|
||||
are bound (`docs/features/interface-semantics/README.md`).
|
||||
- **`type_def::type_span` needed the mirror of that.** The server matches a
|
||||
declaration site's type name against the references the binder left in the
|
||||
same window; with the site saying `bus_if.mp` and the reference saying
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
# change-debounce
|
||||
|
||||
## Goal
|
||||
|
||||
Stop paying a full reanalysis for every keystroke. Before this round each
|
||||
`textDocument/didChange` notification ran `set_document` immediately — lex,
|
||||
parse, `analyze`, `resolve_external`, lint, publish — so a burst of ten
|
||||
keystrokes cost ten of everything and nine of those answers were thrown away
|
||||
before anyone could read them. A `didChange` now only records the buffer's new
|
||||
text as *dirty*; the analysis runs at the first moment anything actually needs
|
||||
it: the next request, the next non-`didChange` notification, or a 150 ms
|
||||
quiet-period timer in the message loop. The buffer's **text** is still exactly
|
||||
current after every notification — only the analysis of it is deferred — so
|
||||
nothing that reads `didChange` results out of order can see a stale buffer.
|
||||
On a 10 000-line file one deferred keystroke saves 31 ms of work
|
||||
(`docs/perf/README.md`); a ten-keystroke burst saves nine of them.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A client sends a burst, not a single change.** Typing produces
|
||||
notifications faster than 150 ms apart; the debounce only pays off while
|
||||
that is true, and costs at most 150 ms of latency when it is not.
|
||||
- **150 ms is short enough not to be felt and long enough to coalesce a
|
||||
burst.** It is the same order as the debounce every mainstream language
|
||||
server uses. It is a constant (`CHANGE_DEBOUNCE` in `server.rs`), not a
|
||||
setting: a knob here would be one more thing to get wrong, and no user has
|
||||
asked for one (`TODO.md` §7, "no option explosion").
|
||||
- **Diagnostics are the one answer nobody requests.** A pushing client never
|
||||
asks for them, so waiting for "the next request" alone would leave a file
|
||||
undiagnosed indefinitely for a user who types and then stops. That is the
|
||||
whole reason the timer exists, rather than flushing only on demand.
|
||||
- **A flush is cheap to trigger from anywhere.** `flush_dirty` returns
|
||||
immediately when nothing is dirty, so the calls at the top of `request` and
|
||||
`notification` cost a `Vec::is_empty` on every message.
|
||||
- **Order within a burst does not matter, order across buffers does.** Dirty
|
||||
buffers are flushed oldest-first (`mark_dirty` replaces an entry in place
|
||||
rather than moving it to the back), so the sequence of `publish` calls a
|
||||
client sees for two edited files is the order they were first edited in.
|
||||
- **Losing an unanalyzed change with its buffer is correct.** `didClose`
|
||||
drops the buffer's pending text: there is nothing left to flush it into,
|
||||
and the client is not looking at the file any more. The drop happens at the
|
||||
*top* of `notification`, ahead of the universal flush — doing it in the
|
||||
`didClose` arm is too late, because the flush has already run by then (QA,
|
||||
CD-1). Closing one buffer says nothing about the others, so every other
|
||||
dirty buffer flushes on that same notification exactly as before.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Amends `docs/features/incremental-sync/README.md`'s pinned invariant.**
|
||||
That round promised "one `didChange` = one `set_document` = one generation
|
||||
bump, however many ranges". The promise is now: **one *flush* is one
|
||||
`set_document`, one generation bump and one `publish` per dirty buffer** —
|
||||
however many ranges *and however many notifications* were coalesced into it.
|
||||
Everything the old promise protected still holds: the generation counter
|
||||
(which is `docs/features/pull-diagnostics/README.md`'s whole `resultId`)
|
||||
never moves twice for work that happened once, and never fails to move for
|
||||
a buffer whose text changed. `incremental-sync`'s own test,
|
||||
`one_notification_is_one_generation_bump_however_many_ranges`, still passes
|
||||
unchanged, because the test helper flushes after each notification — which
|
||||
is exactly the quiet-period timer firing.
|
||||
- **Observable consequence, pinned in `crates/lucisv_server/tests/e2e.rs`**
|
||||
(`incremental_changes_are_advertised_and_applied_over_the_wire`):
|
||||
**intermediate diagnostics states are no longer published**. Two changes
|
||||
arriving back to back — the first breaking a line, the second finishing it
|
||||
— used to produce three publishes (open, broken, fixed) and now produce two
|
||||
(open, composed). Every state that *is* published is a state the buffer
|
||||
really passed through; there are simply fewer of them. That test asserted
|
||||
the old count and now asserts the new one, with the reason written beside
|
||||
it.
|
||||
- **Consumes `sync::apply_changes` unchanged.** Ranged changes are composed
|
||||
against the newest text the server holds, which while a buffer is dirty is
|
||||
the *pending* text, not the last analyzed one. `Server::notification` looks
|
||||
in `dirty` before `workspace.document`. Nothing in `sync.rs` moved.
|
||||
- **Consumes `lsp_server`'s queue as a `std::sync::mpsc` receiver.** The
|
||||
timer is `Receiver::recv_timeout` on the queue `cancel-request` already
|
||||
introduced (`docs/features/cancel-request/README.md`); no thread and no
|
||||
timer object was added. A `Disconnected` receiver ends the loop exactly as
|
||||
the old `while let Ok(..)` did.
|
||||
- **Promises every request still sees the client's own changes.** The flush
|
||||
at the top of `Server::request` runs before dispatch, so a request answered
|
||||
after a `didChange` is answered from that change's analysis — the order
|
||||
contract the loop always had. The large-file fast path is behind that
|
||||
flush, not in front of it.
|
||||
- **No protocol change, no settings change, no index change.** The
|
||||
capabilities advertised at `initialize` are byte-identical.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `dirty: Vec<(Uri, String)>` on `Server` — newest text per buffer, in
|
||||
first-dirtied order.
|
||||
- [x] `mark_dirty` replaces in place, so a burst does not reorder buffers.
|
||||
- [x] `flush_dirty` — one `set_document` + one `publish` per dirty buffer.
|
||||
- [x] `didChange` composes ranges against the pending text when there is one.
|
||||
- [x] Flush on every request, before dispatch.
|
||||
- [x] Flush on every notification that is not a `didChange`.
|
||||
- [x] `CHANGE_DEBOUNCE` (150 ms) quiet-period flush in `run`, via
|
||||
`recv_timeout`, only while something is dirty.
|
||||
- [x] `didClose` drops the buffer's pending change — before the flush, so the
|
||||
drop is real (QA, CD-1), pinned by
|
||||
`closing_a_dirty_buffer_discards_its_change_and_leaves_the_others_alone`.
|
||||
- [x] Test: a burst is one reparse
|
||||
(`a_burst_of_changes_coalesces_into_one_reparse`).
|
||||
- [x] Server tests drive one notification at a time, so the test helper
|
||||
`change()` flushes — documented there as the timer firing.
|
||||
- [x] e2e: the publish count and the reason for it.
|
||||
- [ ] Not done: a flush for a *long* burst that never pauses (a paste-and-hold
|
||||
or a client replaying a file's history sends changes closer together
|
||||
than 150 ms forever). Today such a burst is analyzed when it ends or
|
||||
when the next request arrives. A "flush after N pending changes"
|
||||
backstop is the obvious answer if anyone ever reports it; it is not
|
||||
written because no client behaves that way and an untested backstop is
|
||||
worse than none.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-08-28 — dev.** Implemented as part of the LSP performance round
|
||||
(plan: "Improve LSP performance + hover accuracy", part A1).
|
||||
|
||||
- The deferral is a `Vec`, not a `HashMap`: it holds one entry per *dirty*
|
||||
buffer, which is one in practice and two while a user alt-tabs. A linear
|
||||
scan of that is cheaper than hashing a `Uri`, and the `Vec` gives the flush
|
||||
order for free.
|
||||
- Deferred **analysis only, never text**. The alternative — deferring
|
||||
`apply_changes` too and keeping a queue of unapplied changes — was
|
||||
rejected: every reader of `Document::text` would then need to know about
|
||||
the queue, and the ones that forgot would be silently wrong. Composing the
|
||||
text eagerly keeps the pending state to exactly one `String` that only
|
||||
`didChange` and `flush_dirty` know about.
|
||||
- The flush points were chosen to be exhaustive rather than clever: *every*
|
||||
request and *every* notification except the one being deferred. Anything
|
||||
that needs analysis is downstream of one of those two, so there is no
|
||||
handler that has to remember to flush for itself.
|
||||
- `run` only arms the timeout while something is dirty, so an idle server
|
||||
still blocks in `recv()` and wakes for nothing.
|
||||
- The server unit tests drive notifications one at a time through a helper
|
||||
rather than through the loop, so no burst ever forms and nothing would
|
||||
flush them; the helper flushes explicitly, which is the timer's behavior.
|
||||
Three tests that hand-rolled a `didChange` notification were moved onto
|
||||
that helper.
|
||||
|
||||
**2026-08-28 — dev (QA fix).**
|
||||
|
||||
- **CD-1 — fixed.** The `didClose` arm's `dirty.retain` was dead code: the
|
||||
universal flush at the top of `notification` had already drained `dirty`
|
||||
through `std::mem::take` by the time the arm ran, so a buffer closed
|
||||
mid-edit paid a full `Document::new` and published its real diagnostics one
|
||||
line before the close cleared them. The retain moved to the top of
|
||||
`notification`, *ahead* of the flush, guarded on the method name; the arm's
|
||||
comment now says where the drop happened instead of pretending to do it.
|
||||
- The uri has to be read without consuming the notification, since
|
||||
`extract` takes it by value and the arm below still needs it. That is a
|
||||
four-line `closing_uri` beside `extract`, deserializing a clone of the
|
||||
params — a `didClose`'s params are a single uri, so the clone is not
|
||||
worth avoiding with a peek into the raw `Value`. `None` (params that do
|
||||
not parse) drops nothing, which is exactly what the arm below already
|
||||
does with the same params.
|
||||
- The "flush on every notification but `didChange`" rule is unchanged: the
|
||||
flush still runs for `didClose`, and every *other* dirty buffer still
|
||||
goes through it. What changed is only that the closing buffer is no
|
||||
longer in `dirty` when it does.
|
||||
- Pinned by `closing_a_dirty_buffer_discards_its_change_and_leaves_the_others_alone`
|
||||
(`server.rs`): two buffers dirtied with text that would diagnose, one
|
||||
closed with no request in between; the generation bumps exactly once (the
|
||||
buffer still open), the closed buffer gets exactly one publish and it is
|
||||
the clearing one, and the other buffer's pending edit is published as
|
||||
usual. Verified the test fails on the pre-fix code — `left: 5, right: 4`
|
||||
on the generation assertion — before keeping it.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-08-28 — QA.** Gates run and green: `cargo fmt --check`,
|
||||
`cargo clippy --all-targets --workspace -- -D warnings`, `cargo test
|
||||
--workspace` (0 failed everywhere; `lucisv_server`: 1179 passed, 19 ignored
|
||||
perf tests), `cargo test -p vlog_formatter` (114 passed). All findings below
|
||||
were reproduced with temporary `#[test]`s added to `server.rs`, run, and then
|
||||
removed once confirmed — none are left in the tree.
|
||||
|
||||
- **Finding CD-1 (medium — contradicts a checked-off invariant, wastes work,
|
||||
does not corrupt anything).** `didClose` does **not** actually drop a
|
||||
buffer's pending dirty change before analyzing it. `Server::notification`
|
||||
(`server.rs:1247`) flushes unconditionally for any non-`didChange` method
|
||||
(`server.rs:1253`, `if method != DidChangeTextDocument::METHOD { self
|
||||
.flush_dirty(); }`) — and `didClose` is such a method. That flush runs
|
||||
*before* the `match` statement even reaches the `DidCloseTextDocument::
|
||||
METHOD` arm (`server.rs:1407`), so by the time `self.dirty.retain(|(pending,
|
||||
_)| *pending != uri)` executes (`server.rs:1413`), `flush_dirty` has already
|
||||
drained `self.dirty` via `std::mem::take` — the retain is a no-op in the
|
||||
normal flow. Net effect: closing a buffer that was mid-edit costs one full,
|
||||
wasted reparse + `publish` of the real (about-to-be-discarded) diagnostics,
|
||||
immediately followed by the close handler's own `send_diagnostics(uri,
|
||||
Vec::new())` clearing them — **two** publishes instead of the zero extra
|
||||
ones the design claims. This directly contradicts both the checked-off
|
||||
status-line "`[x]` `didClose` drops the buffer's pending change" and the
|
||||
code comment beside the (dead) retain: "there is nothing left to flush it
|
||||
into" — there is, and it does get flushed.
|
||||
- Repro (temporary test, `server.rs`, removed after confirming): open a
|
||||
clean buffer (`module m;\nendmodule\n`), drain the open publish, note
|
||||
`generation`, send one `didChange` to `module m;\n wire ;\nendmodule\n`
|
||||
(introduces a parse error, buffer stays dirty — `generation` provably
|
||||
unchanged, `dirty` non-empty), then send `didClose` with **no** request
|
||||
in between (`session.notify`, which calls `Server::notification`
|
||||
directly, exactly the production path — no manual flush helper
|
||||
involved). Observed: `generation` bumps by exactly one during the
|
||||
`didClose` call (`2` → `3`), and `session.published()` returns **2**
|
||||
messages: one carrying the real parse-error diagnostic
|
||||
(`"expected identifier (found \";\")"`), then one with `diagnostics: []`.
|
||||
- Not a data-corruption bug — the client ends up with the correct final
|
||||
state (empty diagnostics for a closed file) — but it is a real,
|
||||
reproducible functional gap in exactly the case the debounce is supposed
|
||||
to help most: a user who edits and then immediately closes a buffer pays
|
||||
the full analysis cost the feature exists to avoid, silently. Left
|
||||
unfixed (not small/unambiguous — the right fix wants a decision about
|
||||
whether the top-of-`notification` flush should special-case `didClose`,
|
||||
or whether `didClose` should remove its own `dirty` entry *before* that
|
||||
flush runs, which touches the "flush on every notification but
|
||||
`didChange`" rule this round explicitly checked off).
|
||||
|
||||
- **Attack angles from the brief, checked and clean:**
|
||||
- *An un-flushed edge, generally.* Every request and every non-`didChange`
|
||||
notification flushes at its own top (`server.rs:1253` for notifications,
|
||||
the equivalent at the top of `request`), so the only genuinely
|
||||
un-flushed state is "nothing has asked for analysis yet" — which is
|
||||
exactly what the quiet-period timer exists to bound at 150 ms, and the
|
||||
documented, un-checked TODO item (a burst that never pauses) is real but
|
||||
already honestly disclosed, not silently missing.
|
||||
- *`didChange` on a file the client never opened.* `mark_dirty` does not
|
||||
require a prior `didOpen`, and neither did the pre-debounce
|
||||
`set_document` call it replaces — `flush_dirty`'s `set_document` creates
|
||||
the buffer exactly as before. No new behavior here.
|
||||
- *`didChange` racing `didSave`.* `didSave` is not `didChange`, so it
|
||||
flushes first (`server.rs:1253`) — a save's reindex always sees the
|
||||
latest edited text analyzed, never a stale buffer racing a fresh disk
|
||||
scan.
|
||||
- *Version-number ordering.* The server does not track LSP version numbers
|
||||
at all (`publishDiagnostics`'s own `version` field is hard-coded `None`
|
||||
at `server.rs:1848`, unchanged by this round) — nothing new to get out of
|
||||
order.
|
||||
- *Pending vs. analyzed text observed inconsistent by a request.* Cannot
|
||||
happen: `request` flushes before dispatch (`server.rs`'s `fn request`),
|
||||
so a request is always answered from the analysis of whatever is
|
||||
currently held, dirty or not.
|
||||
- *The `e2e.rs` publish-count change (3 → 2).* Confirmed the buffer
|
||||
genuinely passed through both published states and no diagnostic was
|
||||
lost: traced `incremental_changes_are_advertised_and_applied_over_the_wire`
|
||||
— the two `didChange` notifications and the `textDocument/formatting`
|
||||
request all arrive in one write to the mock transport, so the request's
|
||||
own top-of-`request` flush (or the burst's internal ordering) coalesces
|
||||
both notifications into the one flush that produces publish #2; publish
|
||||
#1 is the clean `didOpen`. The removed middle publish (the transiently
|
||||
*broken* half-edited state) was never a state a real, unhurried client
|
||||
would see anyway — it is the debounce's whole point.
|
||||
- *`a_burst_of_changes_coalesces_into_one_reparse`.* Re-derived by hand:
|
||||
`generation` provably does not move across the two-notification burst,
|
||||
then moves by exactly one at the first request after it, and `dirty` is
|
||||
empty afterward — matches the claimed semantics exactly.
|
||||
|
||||
- **Perf claims (A1's "before/after" in `docs/perf/README.md`).** Arithmetic
|
||||
over already-measured numbers, not a separate measurement — reviewed there,
|
||||
no finding.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-28 — lead.** Accepted. Gates re-run independently of both agents:
|
||||
`cargo fmt --check` clean, `cargo clippy --all-targets --workspace -D
|
||||
warnings` silent, `cargo test --workspace` green.
|
||||
|
||||
The shape is right. Deferring analysis while applying text immediately is the
|
||||
standard split, and flushing before every request and before every
|
||||
non-`didChange` notification means no handler ever reads a stale buffer —
|
||||
today's correctness guarantee is preserved exactly, and only keystroke-storm
|
||||
reparses are coalesced. The quiet-period timer in `run()` matters as much as
|
||||
the coalescing: diagnostics are the one answer a client never asks for, so a
|
||||
burst that ends in silence still gets drawn.
|
||||
|
||||
QA's CD-1 was a real finding and correctly diagnosed: the universal flush ran
|
||||
*before* the `didClose` arm, so the arm's `retain` was dead and a buffer
|
||||
closed mid-burst paid a full `Document::new` and published diagnostics for a
|
||||
file the user had stopped looking at, only to clear them a line later. The
|
||||
fix drops the pending text ahead of the flush rather than special-casing the
|
||||
flush, which keeps "every other dirty buffer still flushes" true by
|
||||
construction. The dev verified the pinning test fails on pre-fix code before
|
||||
keeping it; that is the right standard.
|
||||
|
||||
The one honest cost is recorded in `docs/perf/README.md` and is not hidden: a
|
||||
keystroke with *nothing* following it now publishes at 164 ms rather than one
|
||||
flush, because it waits out the 150 ms quiet period. Any request flushes
|
||||
early, so a real editor sees 4.35 ms / 37.6 ms instead — but the regression
|
||||
is real for a client that asks for nothing, and the number is written down
|
||||
rather than argued away.
|
||||
|
||||
@@ -5,11 +5,18 @@
|
||||
Automate the checks and the release. Every push to master runs the three
|
||||
checks CLAUDE.md requires (fmt, clippy, test) on Gitea Actions; every tag
|
||||
`vX.Y.Z` builds the full cross-platform artifact set (Apple Silicon +
|
||||
x86_64 macOS, static-musl and RHEL 8-compatible Linux, Windows — both
|
||||
binaries each — plus the `.vsix` and `SHA256SUMS`) and publishes a Gitea
|
||||
release whose notes are the CHANGELOG section for that version. The point
|
||||
is that a release is one `git tag` + `git push` and cannot ship without
|
||||
green checks, matching versions, and written notes.
|
||||
x86_64 macOS, static-musl x86-64/ARM64 and RHEL 8-compatible Linux,
|
||||
Windows — both binaries each — plus the seven `.vsix` packages and
|
||||
`SHA256SUMS`) and publishes a Gitea release whose notes are the CHANGELOG
|
||||
section for that version. **Published assets are the seven `.vsix` packages
|
||||
only** (since 2026-08-27, owner decision): the extension is the product a
|
||||
release delivers, every package is checked by name before publishing, and
|
||||
the loose binaries — still built and audited, since the packages embed
|
||||
them — stay unpublished; a standalone binary is
|
||||
`cargo build --release` for whoever wants one
|
||||
(docs/features/editor-platform-vsix). The point is that a release is one
|
||||
`git tag` + `git push` and cannot ship without green checks, matching
|
||||
versions, written notes, and all seven packages.
|
||||
|
||||
## Assumptions
|
||||
|
||||
@@ -38,8 +45,20 @@ green checks, matching versions, and written notes.
|
||||
## Handshakes
|
||||
|
||||
- Consumes `tools/release.sh --cross` unchanged: artifact names
|
||||
(`lucisv[-server]-<version>-<triple>[.exe]`, `lucisv-<version>.vsix`,
|
||||
(`lucisv[-server]-<version>-<triple>[.exe]`,
|
||||
`lucisv-<version>[-<vsce-target>].vsix`, `lucisv-<version>-all.vsix`,
|
||||
`SHA256SUMS`) and the version-from-binary convention.
|
||||
`tools/prune_release_assets.sh` depends on those `.vsix` names exactly —
|
||||
it checks all **seven** by name and filters `SHA256SUMS` down to `.vsix`
|
||||
lines before publishing. A package added, renamed or dropped in
|
||||
`release.sh` must be reflected in that script's suffix list, or the
|
||||
release fails naming the file it could not find
|
||||
(docs/features/editor-platform-vsix).
|
||||
- The workflow's steps are one-liners calling `tools/` scripts, so every
|
||||
release step is runnable by hand on a developer machine and testable
|
||||
without pushing a tag. `prune_release_assets.sh` in particular is safe to
|
||||
re-run: a second run over an already-pruned directory finds the same seven
|
||||
packages and verifies them again.
|
||||
- Consumes `CHANGELOG.md`'s heading convention: `## <version> — <date>`;
|
||||
`tools/release_notes.sh` keys on the second word of `## ` headings.
|
||||
- `tools/publish_release.sh` expects the GitHub-compatible CI environment
|
||||
@@ -68,6 +87,18 @@ green checks, matching versions, and written notes.
|
||||
automates what RELEASING.md documented as manual; Linux/Windows binaries
|
||||
remain audited, never executed (no such machine in the loop, and no
|
||||
container runtime on the runner).
|
||||
- [x] Publish `.vsix` packages only (2026-08-27): after the audit, the
|
||||
workflow asserts all seven packages exist by name, filters `SHA256SUMS`
|
||||
down to them (keeping the audited hashes), re-verifies it, and deletes
|
||||
the loose binaries from `dist/` so `publish_release.sh` attaches only
|
||||
the packages. Prune logic tested locally against a real `--cross`
|
||||
`dist/`, with a negative control (one package removed → the step fails
|
||||
naming it).
|
||||
- [x] That logic lives in `tools/prune_release_assets.sh` (2026-08-27), not
|
||||
inline in the workflow: every release step is a one-line call into
|
||||
`tools/`, so it can be run and negative-controlled on a developer machine
|
||||
without pushing a tag. The seventh (all-platforms) package joined the
|
||||
must-exist list at the same time.
|
||||
- [ ] A second runner on a non-macOS host, if native-built (rather than
|
||||
cross-built) Linux artifacts are ever wanted.
|
||||
|
||||
@@ -92,6 +123,69 @@ green checks, matching versions, and written notes.
|
||||
rejected: no container runtime exists on the runner Mac, and installing
|
||||
a VM stack is an owner decision, not a CI increment.
|
||||
|
||||
- 2026-08-27 — lead. Owner decision: the release page ships the six
|
||||
`.vsix` packages only (each platform package a must, checked by name;
|
||||
the universal fallback included), no loose binaries — the platform
|
||||
packages embed them, and an experienced user builds standalone binaries
|
||||
with cargo. Implemented as a "Keep only the extension packages" step in
|
||||
`release.yml` between the artifact audit and the notes extraction: the
|
||||
audit still sees (and gates on) the loose binaries, then the step
|
||||
filters `SHA256SUMS` to `.vsix` lines — the published hashes are the
|
||||
audited ones, not recomputed — deletes everything else from `dist/`,
|
||||
and re-runs `shasum -c`. `publish_release.sh` is untouched: it attaches
|
||||
whatever `dist/` holds. Tested against the real 0.10.0 `--cross` dist
|
||||
(six packages verify, correct survivors) and negative-controlled (one
|
||||
package removed → fails naming `lucisv-0.10.0-linux-arm64.vsix`). Docs
|
||||
trued up: RELEASING.md (publishing + CI sections), top-level README
|
||||
(Editor setup and Install-and-releases sections now lead with the
|
||||
platform package and say binaries are build-your-own), and this README's
|
||||
Goal/Handshakes/Status.
|
||||
|
||||
- 2026-08-27 — dev (all-platforms package round). Two changes here, both
|
||||
in service of the seventh `.vsix` (`docs/features/editor-platform-vsix`):
|
||||
|
||||
- **The inline "Keep only the extension packages" step became
|
||||
`tools/prune_release_assets.sh <dist-dir> <version>`.** Same logic,
|
||||
same order — check every package by name, filter `SHA256SUMS` to its
|
||||
`.vsix` lines rather than recompute, delete everything else, re-verify
|
||||
with `shasum -c` — now in a script with a usage header like its
|
||||
siblings, so `release.yml` is back to one-line steps and the step is
|
||||
testable without a tag. It grew the `-all` suffix and argument
|
||||
validation (`[ $# -eq 2 ]`, missing dir, missing `SHA256SUMS` → exit 2,
|
||||
matching `publish_release.sh`'s convention); a missing package is still
|
||||
exit 1 naming the file.
|
||||
- **`release.yml`**: the step body is now
|
||||
`tools/prune_release_assets.sh dist "${GITHUB_REF_NAME#v}"`, and the
|
||||
header comment says seven packages. Nothing else in the workflow moved;
|
||||
the prune still sits between the artifact audit and the notes
|
||||
extraction, so the audit keeps gating on the loose binaries before they
|
||||
are deleted.
|
||||
|
||||
**Verified**, from the real repo path, against the real `dist/` from a
|
||||
`tools/release.sh --cross` run of 0.10.1 (copies only — `dist/` itself was
|
||||
left intact for the lead, since the script deletes files):
|
||||
|
||||
| Check | Result |
|
||||
|---|---|
|
||||
| `bash -n tools/prune_release_assets.sh` | clean |
|
||||
| positive: a 20-file `dist/` copy | exit 0, 8 survivors (7 `.vsix` + `SHA256SUMS`), `SHA256SUMS` down to 7 lines, all 7 verify `OK` |
|
||||
| negative: `lucisv-0.10.1-all.vsix` removed | exit 1, `missing lucisv-0.10.1-all.vsix`, **and nothing deleted** — all 19 remaining files still there, because the name check runs before any destructive step |
|
||||
| negative: wrong version argument (`0.10.0`) | exit 1, `missing lucisv-0.10.0.vsix`, nothing deleted |
|
||||
| negative: one argument / missing dir / dir without `SHA256SUMS` | exit 2 each, with the usage or the specific reason |
|
||||
| re-run over an already-pruned directory | exit 0, same 7 packages verify again — a CI job re-run is safe |
|
||||
| `python3 -c yaml.safe_load` on `release.yml` | parses; the six step names unchanged |
|
||||
|
||||
The negative controls were run on copies in the session scratchpad, but
|
||||
the script itself and every `release.sh` run were driven from
|
||||
`/Users/guoliangchen/repo/verilogrustformatter` — `vsce` collects zero
|
||||
files under the scratchpad's UUID path
|
||||
(`docs/features/editor-packaging` QA Finding 2).
|
||||
|
||||
Not verified: the workflow has not been run on the Gitea runner in this
|
||||
round — no tag was pushed (and pushing one is the lead's call). The step
|
||||
is a one-line invocation of a script proven by hand on the same machine
|
||||
the runner is, which is as close as this gets without cutting a release.
|
||||
|
||||
## QA log
|
||||
|
||||
_(no QA round — infrastructure, verified by the live v0.7.1 run; see work log)_
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -41,7 +41,13 @@ the deviations are stated where they happen.
|
||||
lucisv cannot see into a base class it does not model, so the full lexical
|
||||
chain is searched first and inheritance is the fallback. An in-file name
|
||||
therefore always wins over a hypothetical inherited one.
|
||||
4. **Inheritance is never chased — not even in-file.** `extends Base` itself
|
||||
4. **Inheritance is never chased — not even in-file.**
|
||||
*(Amended 2026-09-01 by class-member-access: an `extends` chain **this
|
||||
file declares** is now walked, so a `this.x` or a `handle.x` naming a base
|
||||
class's property in the same file resolves outright; a chain that leaves
|
||||
the file still stops here, exactly as below, and the workspace overlay
|
||||
chases it from there. Everything else in this rule stands.)*
|
||||
`extends Base` itself
|
||||
is resolved as a reference (rule 5). But a member use that misses the
|
||||
whole lexical chain, written inside a class whose nearest
|
||||
extends-carrying enclosing class says `extends Base`, becomes
|
||||
@@ -134,9 +140,11 @@ the deviations are stated where they happen.
|
||||
answers even though the class is not a file-scope unit.
|
||||
- `IndexCounts` gains a `classes` field (additive; all existing fields
|
||||
unchanged).
|
||||
- `resolve_external` does **not** chase `InheritedCandidate` — that is the
|
||||
documented future round, and the variant exists precisely so the index
|
||||
can do it without re-deriving anything.
|
||||
- ~~`resolve_external` does **not** chase `InheritedCandidate`~~ — **it does
|
||||
since 2026-09-01** (class-member-access), through the reverse edge
|
||||
`WorkspaceIndex::base_of` built from this same inheritance census. The
|
||||
variant existed precisely so the index could do it without re-deriving
|
||||
anything, and that is what happened: no `FileFacts` field was added.
|
||||
|
||||
## scan.rs status
|
||||
|
||||
@@ -213,10 +221,11 @@ variant does not compile without them; each is one arm, no logic):
|
||||
- `crates/lucisv_server/src/symbols.rs` — `SymbolKind::Class => "class"` in
|
||||
`kind_label`, `SymbolKind::Class => LspKind::CLASS` in `lsp_kind`.
|
||||
|
||||
**Requested of a future round (not done here):** chasing
|
||||
`InheritedCandidate` — in-file via `Semantics`, cross-file via the
|
||||
workspace member table (`member(base_tail, name)` is already the right
|
||||
lookup); and hover text for "class c extends base".
|
||||
**Requested of a future round:** ~~chasing `InheritedCandidate` — in-file via
|
||||
`Semantics`, cross-file via the workspace member table (`member(base_tail,
|
||||
name)` is already the right lookup)~~ — **delivered 2026-09-01 by
|
||||
class-member-access**, and by exactly that lookup. Still open: hover text for
|
||||
"class c extends base".
|
||||
|
||||
## Corpus acceptance
|
||||
|
||||
@@ -298,8 +307,18 @@ absent sources (`sail_ibexspec`, `SB_SPRAM256KA`, `PLLE2_ADV`, `uvm_pkg`).
|
||||
report prints the classes count, no existing assertion weakened or
|
||||
removed
|
||||
- [x] TODO.md §6 annotation; classes README handshake annotated delivered
|
||||
- [ ] Future round: chase `InheritedCandidate` (in-file + workspace);
|
||||
hover "extends base"
|
||||
- [x] ~~Future round: chase `InheritedCandidate` (in-file + workspace)~~ —
|
||||
**delivered 2026-09-01 by class-member-access** (topo §2.9-9):
|
||||
`resolve.rs` walks the `extends` chain as far as this file declares it
|
||||
(`member_in_chain`, feeding `this.x` and the new `head.member` tail),
|
||||
and `workspace.rs` walks it across files (`member_chain` inside
|
||||
`follow_one`, plus `resolve_external`'s chase of a bare `base`). Rule 4
|
||||
below is amended there: the *single-file* layer still never chases a
|
||||
base out of this file, and `base` still stays on the resolution — what
|
||||
changed is that an in-file base is now resolved outright, and the
|
||||
overlay finishes the rest. See
|
||||
`docs/features/class-member-access/README.md`.
|
||||
- [ ] Future round: hover "extends base"
|
||||
- [ ] Still blocked on parser handshake item 2: delete `scan.rs`
|
||||
|
||||
## Work log
|
||||
|
||||
@@ -0,0 +1,831 @@
|
||||
# clocking-wave
|
||||
|
||||
## Goal
|
||||
|
||||
Round 2 of the testbench-syntax wave: close every remaining bucket of the
|
||||
OpenTitan sweep that is a *grammar* gap rather than a preprocessing one, in one
|
||||
round. Six shapes — clocking-block signal bindings (`output tms = _tms;`), the
|
||||
standing `default disable iff`, an `iff` gate on an event-control term, a bare
|
||||
event control naming an indexed hierarchical path, a gate's drive strength, and
|
||||
`program … endprogram` — plus one engineering measurement: the chain-length
|
||||
limit, which real generated register files had outgrown. The sweep goes
|
||||
**43 → 11 failures**, and the eleven that remain are the two OUT rows the brief
|
||||
named (macro fragments that need preprocessing, and vendor files that are not
|
||||
SystemVerilog).
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Clocking blocks are already modelled, not verbatim.** The brief expected
|
||||
the house verbatim-capture precedent to apply here (`constraint`,
|
||||
`covergroup`, concurrent assertions). It does not: `ClockingDecl` /
|
||||
`ClockingItem` have been real AST since the `interfaces` feature, with a
|
||||
printer arm, span coverage and a linter guard. Converting a working modelled
|
||||
construct into opaque bytes to close a one-field gap would have *lost*
|
||||
information, so the fix is the one field the grammar was missing. See the
|
||||
work log for the deviation.
|
||||
- **The 14-file "clocking" bucket is two shapes, not one.** Reading all
|
||||
fourteen sites showed seven failing on a clocking item's `= expression` and
|
||||
seven on `default disable iff` — which is not a clocking construct at all
|
||||
(IEEE 1800 §16.12, assertion control). The bucket label was a guess from the
|
||||
error text (`unsupported construct starting with keyword 'default'`); every
|
||||
site was read before a line was written.
|
||||
- **A clocking block stays opaque to the semantic layer.** `analyze` treats
|
||||
`ItemKind::Clocking` as a leaf and the linter takes the whole clocking item's
|
||||
span out through `opaque_spans`. The `= expression` a binding adds sits
|
||||
*inside* that span, so it neither declares, reads nor drives anything as far
|
||||
as the lints are concerned. That is deliberate — a clocking block's signals
|
||||
are driven and sampled by whatever testbench drives the block, which lucisv
|
||||
does not see — and it is pinned by a lint case rather than left implicit.
|
||||
- **`default disable iff` belongs in the verbatim bucket.** It holds
|
||||
`expression_or_dist` (a `dist { … }` set is legal there) and it exists to
|
||||
govern the concurrent assertions in its scope, which are already verbatim. A
|
||||
modelled node would have been half of a grammar lucisv deliberately does not
|
||||
model. It is the round's only new capture, and it ships with attack pairs.
|
||||
- **A `program` block is a module.** IEEE 1800 §24.3's `program_declaration` is
|
||||
the module header over the module body list with a different closer, so it
|
||||
reuses `Module` the way `interface` already does. The stricter *legality*
|
||||
rules a program has (no `always`, only interface instantiations) are a
|
||||
checker's business; lucisv is not a legality checker.
|
||||
- **Chain links, not source terms.** `MAX_CHAIN_LENGTH` counts AST layers on a
|
||||
path. A generated `|` chain of *N* registers costs *N* links for the
|
||||
operators plus whatever its deepest operand adds, so the number measured
|
||||
below is the budget, not the register count.
|
||||
- **Trailing commas are not SystemVerilog.** `named_parameter_assignment` has
|
||||
no empty alternative, so `#(.A(1), .B(2),)` is invalid input that some
|
||||
simulators tolerate. Skipped deliberately; see Status.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `vlog_parser`:** nothing new.
|
||||
|
||||
**Promised to `vlog_formatter` / `vlog_semantic` / `vlog_linter` — AST changes
|
||||
this round makes.** Every one is additive except the two marked *changed*,
|
||||
which are source-incompatible and were fixed up at each site:
|
||||
|
||||
| node | change | consumers touched |
|
||||
|---|---|---|
|
||||
| `ClockingItemKind::Signals` | *changed*: `names: Vec<Name>` → `signals: Vec<ClockingSignal>` | `format.rs::clocking_item`, `vlog_parser/tests/spans.rs`; `vlog_linter/src/signals.rs` matches `{ .. }` and is unaffected |
|
||||
| `ClockingSignal` | new: `{ name: Name, value: Option<Expr> }` | as above |
|
||||
| `SensItem::iff` | new: `Option<Expr>` | `format.rs::sens_list`, `vlog_semantic/src/bind.rs::bind_timing` |
|
||||
| `GateInstantiation::strength` | new: `Option<DriveStrength>` | `format.rs::gate_instantiation` |
|
||||
| `DriveStrength::second` | *changed*: `String` → `Option<String>` | `format.rs` (one new helper, `drive_strength`) |
|
||||
| `Module::end_kw()` | now answers `endprogram` for `kw == "program"` | every `Module` consumer, transparently |
|
||||
|
||||
**Promised to `vlog_semantic`:** an `iff` gate on an event-control term is
|
||||
bound as an ordinary read (`bind_timing`). A clocking block — bindings included
|
||||
— stays a leaf, and `ItemKind::Verbatim` (which `default disable iff` now also
|
||||
produces at module scope) keeps its existing "mentions nothing" contract.
|
||||
|
||||
**Promised to `vlog_linter`:** unchanged for the verbatim capture —
|
||||
`ItemKind::Verbatim` already routes to `opaque_spans`, so it inherits the right
|
||||
behaviour by doing nothing, the property
|
||||
`docs/features/directive-split/README.md` calls "not item scope, does not
|
||||
count" as the default.
|
||||
|
||||
**Widened for `vlog_linter`, deliberately: a `program` is a module to every
|
||||
rule.** Because `program` reuses `ItemKind::Module`, every generic
|
||||
`ItemKind::Module(_)` match now picks it up for free (QA, 2026-08-29) — so
|
||||
`vlog_linter::visit::items` descends into program bodies and `module-filename`
|
||||
holds a one-program file to the same name-matches-file convention as a module
|
||||
or an interface. That is the intended consequence of "a program is a module",
|
||||
not an accident: a program block is a compilation unit with a name, a header
|
||||
and a body, and every one of these rules is about exactly that. It is the same
|
||||
widening `interface` already made, and it is now pinned by two cases in
|
||||
`module_name_style.lint` so it cannot be reversed silently. **Filed, not fixed
|
||||
here:** `rules/module_name_style.rs` hardcodes the word "module" in its
|
||||
violation message regardless of `Module::kw`, so a badly-named program is
|
||||
reported as ``module `FooBar` is not lower_snake_case``. That inaccuracy is
|
||||
pre-existing — it has said the same thing about `interface` since before this
|
||||
round — and correcting it changes a message shared with `interface` and its own
|
||||
tests, which is outside this round's file set. One-line fix for whoever owns
|
||||
that rule next; the cases above pin today's behaviour either way.
|
||||
|
||||
**Requirement met, from `docs/features/recursion-limit/README.md`:** the bare
|
||||
event control's segment loop wraps what it has already built
|
||||
(`Box::new(previous)` per `.name` / `[expr]`), so it charges `link()` and
|
||||
restores the count it started from, the way `parse_postfix` does. It did *not*
|
||||
charge before this round — a pre-existing hole in the same shape that README's
|
||||
Handshakes warns about, closed here and pinned by a test.
|
||||
|
||||
**Changed for every consumer: `PARSE_STACK_SIZE` is now 32 MiB** (was 16). The
|
||||
rule is unchanged — any thread that can reach a parse is spawned with the
|
||||
constant — but the number moved, because `MAX_CHAIN_LENGTH` moved with it. See
|
||||
the recursion-limit README's round 4 for the measurement.
|
||||
|
||||
## The chain limit — measured, not guessed
|
||||
|
||||
`MAX_CHAIN_LENGTH = 256` rejected seven real files. The question is not "is 256
|
||||
too small" but "how long is the longest chain real code actually contains", and
|
||||
then "what does that cost on the stack".
|
||||
|
||||
**What is needed.** A high-water-mark probe (a scratchpad copy of the
|
||||
workspace, `links` recorded per file, limit raised out of the way; never built
|
||||
inside the repo) over all **3,943** OpenTitan files:
|
||||
|
||||
| file | links needed |
|
||||
|---|---|
|
||||
| `top_earlgrey/ip_autogen/pinmux/rtl/pinmux_reg_top.sv` | **567** |
|
||||
| `top_englishbreakfast/…/pinmux_reg_top.sv` | 519 |
|
||||
| `top_darjeeling/…/pinmux_reg_top.sv` | 502 |
|
||||
| `top_darjeeling/…/alert_handler_reg_top.sv` | 397 |
|
||||
| `top_earlgrey/…/alert_handler_reg_top.sv` | 353 |
|
||||
| `rv_dm/rtl/rv_dm_mem_reg_top.sv` | 280 |
|
||||
| `top_darjeeling/…/rv_core_ibex_cfg_reg_top.sv` | 266 |
|
||||
|
||||
Distribution over the whole tree: 3,932 files under 128, four in 129–256, five
|
||||
in 257–512, two over 512. The shape is one `|` chain per generated register
|
||||
file — `(addr_hit[N] & (|(PERMIT[N] & ~reg_be))) | …` — so the number tracks
|
||||
the register count and grows with the design.
|
||||
|
||||
**What it costs.** Minimum surviving thread stack for the whole
|
||||
`format_source` pipeline, bisected one trial per subprocess (house method, same
|
||||
probe style as the recursion-limit rounds), rustc 1.97.1:
|
||||
|
||||
| shape | debug | release |
|
||||
|---|---|---|
|
||||
| nested `case` at the depth limit — the old global worst case | 5 959 KiB | 775 KiB |
|
||||
| `+` chain, 2048 terms | 567 KiB | 183 KiB |
|
||||
| the real `or_chain` shape, 2048 terms | 567 KiB | 183 KiB |
|
||||
| postfix chain (`a.b…`), 640 links | 5 911 KiB | 375 KiB |
|
||||
| postfix chain, 768 | 7 079 KiB | 455 KiB |
|
||||
| postfix chain, **1024** | **9 430 KiB** | 615 KiB |
|
||||
| postfix chain, 1280 | 11 798 KiB | 775 KiB |
|
||||
| 28 nested `case` **+** a 1024-link postfix chain inside | **9 894 KiB** | 727 KiB |
|
||||
| 64 nested `case` (trips depth) + a 1024-link chain inside | 5 959 KiB | 775 KiB |
|
||||
|
||||
Per link: (11 798 − 5 911) / 640 = **9.20 KiB debug**, 0.63 KiB release. The
|
||||
binary-operator chains that actually appear in the generated files are ~40×
|
||||
cheaper than that (the formatter's `binary_chain` flattens the left spine); the
|
||||
*postfix* chain is the worst case the limit has to be safe for, and it is what
|
||||
the numbers above are chosen from.
|
||||
|
||||
**The choice: 1024, and `PARSE_STACK_SIZE` 32 MiB.**
|
||||
|
||||
- 1024 is 1.8× the largest chain the real tree contains, on a number that grows
|
||||
with design size. 640 would have cleared today's files by 13 %, which is a
|
||||
fit, not a margin — and this limit has now been outgrown once.
|
||||
- At 1024 the debug worst case moves from 5 959 KiB (nesting) to **9 894 KiB**
|
||||
(a maximal chain inside nesting). So, for the first time, *the chain budget
|
||||
sets the global peak* — the "chains do not move the worst case" line in the
|
||||
recursion-limit README stops being true and is corrected there.
|
||||
- 16 MiB against 9.9 MiB is 1.65×, below the 2.7× the stack round settled on
|
||||
for a failure mode that is an abort rather than a diagnostic. 32 MiB is
|
||||
**3.3×**, and a thread stack costs address space rather than resident memory.
|
||||
- The two peaks still compose additively rather than multiplicatively, and the
|
||||
measurement shows why: 64 nested `case` *with* a 1024-link chain inside
|
||||
bisects to exactly the same byte as without it (5 959 KiB), because tripping
|
||||
the depth limit peaks in the parser and the chain peaks in the formatter.
|
||||
|
||||
The invariant becomes **64 + 1024 = 1088 layers**.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] **Clocking signal bindings** — `ClockingItemKind::Signals` carries
|
||||
`Vec<ClockingSignal>`; one new parse function, one printer arm. 7 files.
|
||||
- [x] **`default disable iff expr;`** — verbatim item, one dispatch arm, one
|
||||
scanner. 7 files (4 of them behind a second blocker, below).
|
||||
- [x] **A macro as a concurrent assertion's action statement** — not in the
|
||||
brief, but the next blocker on 4 of the 7 `default disable iff` files and
|
||||
on 2 more. `skip_action_stmt` ends the statement at a macro invocation
|
||||
when — and only when — nothing that could continue a statement follows
|
||||
it (`Parser::at_statement_tail`). **This is the one change with a
|
||||
whole-tree output effect; see the work log.** *Reworked after QA:* the
|
||||
first shipping shape decided from the macro *starting* a statement,
|
||||
which regressed four idioms where the macro is a name the statement goes
|
||||
on to use.
|
||||
- [x] **`iff` on an event-control term** — `SensItem::iff`, IEEE 1800 §9.4.2.
|
||||
5 files. LRM scope checked: `iff` gates one *event expression term*, so
|
||||
the parenthesized list is the only place it can appear — the bare
|
||||
`@name` form is a `hierarchical_event_identifier` with no `iff`
|
||||
alternative, and `wait`/`wait_order` take an expression, not an event
|
||||
expression. Both `,` and `or` separators still work around it.
|
||||
- [x] **Bare event control over an indexed path** — `.name` and `[expr]`
|
||||
segments, chain-budget charged. 3 files.
|
||||
- [x] **A gate's drive strength** — `GateInstantiation::strength`,
|
||||
`DriveStrength::second: Option<String>`; the mop-up's documented skip.
|
||||
1 file.
|
||||
- [x] **`program … endprogram`** — one dispatch arm reusing `parse_module`,
|
||||
one `end_kw` arm, `endprogram` added to `SYNC_CLOSERS` and `program` to
|
||||
`SYNC_OPENERS`. 3 files.
|
||||
- [x] **Chain limit 256 → 1024, `PARSE_STACK_SIZE` 16 → 32 MiB**, measured
|
||||
above; the recursion-limit README's invariant, tables and Status updated.
|
||||
7 files.
|
||||
- [x] OpenTitan sweep **43 → 11**, set difference: **0 newly failing**.
|
||||
- [x] Whole-tree superset check over all 3,943 files: exactly **one**
|
||||
previously-passing file's output moves, and it moves because 55 lines
|
||||
that used to be swallowed into an opaque verbatim blob are now parsed —
|
||||
see the work log.
|
||||
- [x] Corpus gate byte-identical: 813/820, and all **860** corpus files hash
|
||||
identically to trunk's output.
|
||||
- [x] `verify.rs` untouched; attack pairs for the one new capture.
|
||||
- [x] 12 parser unit tests (negatives and a tolerant regression included), 7
|
||||
`verification.rs` tests (1 re-indent + **6 attack pairs**), 3 new
|
||||
`spans.rs` `SOURCES` entries, 12 formatter cases in a new
|
||||
`clocking_wave.cases`, 3 lint cases pinning the opacity, 1 new
|
||||
`deep_nesting` test at the combined worst case. Workspace total
|
||||
2 425 → **2 625**.
|
||||
- [x] **QA rework (2026-08-29):** the macro-action decision moved onto what
|
||||
*follows* the call; QA's three `#[ignore]`d pins un-ignored and passing,
|
||||
plus the fourth shape and both sides of the decision. Tests now
|
||||
2 425 → **2 633**; the `program`-as-`Module` lint widening documented in
|
||||
Handshakes and pinned by two `module_name_style.lint` cases.
|
||||
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test --workspace`.
|
||||
|
||||
**Skipped, deliberately, with reasons:**
|
||||
|
||||
- [ ] **`hw/dv/sv/jtag_agent/jtag_if.sv`** — its clocking blocker *is* fixed;
|
||||
a second, independent, **pre-existing** blocker sits behind it. The file
|
||||
opens with two rival interface headers in an `` `ifdef ``/`` `else ``
|
||||
region (lines 6–12). Both are bracket-balanced complete headers, so
|
||||
`at_split_conditional` — which requires the arm to have left a bracket
|
||||
open — does not fire, and the parser nests the second header inside the
|
||||
first and runs out of `endinterface`s. Reproduced on trunk grammar
|
||||
alone (`` `ifdef G / module i #(…)(); / `else / module i #(…)(); /
|
||||
`endif / wire w; / endmodule ``), so it is not a regression of this
|
||||
round. Closing it means teaching `directive-split` about rival
|
||||
*declaration heads that are complete*, which is a design change to the
|
||||
safety-sensitive recovery, not a bucket fix. **Handshake request to a
|
||||
future `directive-split` round.**
|
||||
- [ ] **`SimDTM.sv`** — `wire [31:0] #0.1 x = y;`: a net delay written *after*
|
||||
the type, which is where IEEE 1800 A.2.1.3 puts it. lucisv parses a net
|
||||
delay only *before* the type, and `DataDecl` has one `delay` field with
|
||||
one print position — so accepting the other spelling and printing it back
|
||||
where it was written needs a positional field, or the safety net rightly
|
||||
refuses the reordered token stream. Two AST changes for one vendor file
|
||||
in `tb/unused/`. Bounded follow-up whenever a second file wants it.
|
||||
- [ ] **`kmac_reduced_tb.sv`** — a trailing comma in a *named* parameter
|
||||
override list (`.EntropyWidth(EntropyWidth),\n)`). Not legal
|
||||
SystemVerilog: `list_of_parameter_assignments` has no empty alternative
|
||||
(the empty-element allowance is for *ordered* port connections only).
|
||||
lucisv rejects invalid input on purpose, and nothing else in the tree
|
||||
writes it.
|
||||
- [ ] **`edn_env_cfg.sv`, `compare_helper.sv`** — a `for` loop standing where a
|
||||
class item goes, inside `` `uvm_object_utils_begin/end ``; and
|
||||
`assign x = `X_EACH_CSR 1;` where the macro expands to a run of
|
||||
`a == b &&`. Both are macro fragments: they are only grammatical after
|
||||
expansion. OUT per the brief.
|
||||
|
||||
**Out of scope, unchanged (the 11 remaining sweep failures):**
|
||||
|
||||
| file | why |
|
||||
|---|---|
|
||||
| `cip_base_vseq__tl_errors.svh` | `include fragment — a class body with no class |
|
||||
| `keccak_2share_fpv.sv`, `spi_device_scoreboard.sv` | case-arm macros |
|
||||
| `riscv_custom_instr_enum.sv` | `include fragment — enum members with no enum |
|
||||
| `riscv_instr_cover_group.sv` | covergroup fragment behind a macro |
|
||||
| `edn_env_cfg.sv`, `compare_helper.sv` | macro fragments (above) |
|
||||
| `riscv_core_setting.tpl.sv` | a Mako template, not SystemVerilog |
|
||||
| `SimDTM.sv`, `kmac_reduced_tb.sv`, `jtag_if.sv` | the three skips above |
|
||||
|
||||
**Recommended exclude patterns** rather than grammar work, for the files that
|
||||
are not SystemVerilog at all: `**/*.tpl.sv` (Mako templates),
|
||||
`**/vendor/google_riscv-dv/**` and `**/pulp_riscv_dbg/tb/unused/**`. Two of the
|
||||
eleven fall under these; the rest are real SystemVerilog that needs a
|
||||
preprocessor.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-29 — dev (round 2, the clocking wave)
|
||||
|
||||
**Method, and the hard rule.** Every sweep against
|
||||
`/Users/guoliangchen/repo/opentitan` used `--check` or `--stdout` only, with
|
||||
`git -C … status --porcelain` after every one; the checkout's single legitimate
|
||||
modification (`hw/ip/aes/dv/tb/tb.sv`) was the only thing it ever reported, on
|
||||
all five sweeps and both hash passes. Every bucket was read at its real
|
||||
`file:line` before a line was written — which is what caught the bucket
|
||||
mis-label below.
|
||||
|
||||
**Baseline: 43 failures over 3,943 files at trunk `5ad0772`** (the brief said
|
||||
44; the difference is the brief's own count, not a moved file). Recorded
|
||||
per-file with its message so every later claim is a set operation.
|
||||
|
||||
**The bucket table was wrong in one place, and reading the sites is what
|
||||
found it.** All seven "unsupported construct starting with keyword `default`"
|
||||
failures are `default disable iff <expr>;` — assertion control (§16.12), not a
|
||||
clocking construct. `default clocking @(posedge clk); endclocking` already
|
||||
parsed on trunk; I checked before assuming. So the 14-file bucket is 7 + 7.
|
||||
|
||||
**Deviation from the brief: no verbatim capture for clocking.** The brief asked
|
||||
for `clocking … endclocking` captured byte-exact as a leaf, on the house
|
||||
precedent. Clocking is already a modelled node with a printer, spans and a
|
||||
linter guard, and the seven failures are one missing production —
|
||||
`clocking_decl_assign`, §14.4's optional `= expression` on a signal. Replacing
|
||||
a working model with opaque bytes to fix a one-field gap would lose the
|
||||
structure the LSP and the linter already use, so the fix is the field. The
|
||||
brief's *opacity* requirement still applies and is honoured where it actually
|
||||
lives: `analyze` keeps `ItemKind::Clocking` a leaf and the linter takes the
|
||||
clocking item's whole span — the new binding expression included — out through
|
||||
`opaque_spans`, now pinned by a lint case instead of being implicit.
|
||||
|
||||
**The one new verbatim capture, and its attack pairs.** `default disable iff`
|
||||
scans to its own `;`, skipping bracketed runs whole so a `;` inside a
|
||||
`dist { … }` set does not end it early, then copies the bytes by span exactly
|
||||
as `parse_concurrent_assertion` does. `verify.rs` was **not touched** and **no
|
||||
normalization was added or widened**; the six attack pairs in
|
||||
`tests/verification.rs` are the ones the *existing* forgiveness (indentation,
|
||||
line breaks, comment re-indentation) could plausibly have masked — a flipped
|
||||
polarity, a dropped operand, a dropped comment, a dropped item, a re-joined
|
||||
multi-line condition, a changed `dist` weight — each asserted rejected.
|
||||
|
||||
**The macro action block: a bucket the brief did not have, and the round's only
|
||||
output move.** Fixing `default disable iff` moved four of its seven files onto
|
||||
a *new* first error, and two clocking files (`jtag_if`, `kmac_app_if`) onto one
|
||||
too. All six were the same shape: `assert property (p) else `ASSERT_ERROR(A)`
|
||||
with no `;`. `skip_action_stmt` scanned for a `;` and, not finding one, ran
|
||||
through whatever followed. So `skip_action_stmt` now ends the statement at a
|
||||
macro invocation — but **only one that starts a statement**, tracked with an
|
||||
`at_stmt_start` flag reset after an `else` continues one, because a macro
|
||||
standing mid-expression (`x = `VAL + 1;`) is an operand and the `;` still
|
||||
terminates. Both readings have a test.
|
||||
|
||||
That fix is what moves `hw/ip/prim/rtl/prim_sync_reqack.sv`, the **only** one
|
||||
of 3,943 files whose output changed. Before it, the `else `ASSERT_ERROR(…)` at
|
||||
line 364 ran the scan through the `` `endif ``, through
|
||||
`if (EnRstChks) begin : gen_assert_en_rst_chks`, and out at that block's `end`
|
||||
— so ~55 lines of ordinary generate-block code were absorbed into the
|
||||
assertion's opaque bytes and printed back unformatted. Now they are parsed and
|
||||
laid out. Verified: the new output is a fixed point, and a whitespace-insensitive
|
||||
token comparison against the source shows only line joins. This is a
|
||||
correctness improvement, not a regression, and it is the reason the round's
|
||||
superset check reports one move rather than zero.
|
||||
|
||||
**`iff`, and the LRM scope the brief asked about.** §9.4.2's
|
||||
`event_expression ::= [edge_identifier] expression [iff expression]` gates one
|
||||
*term*, and terms only exist inside `@( … )`. The paren-less form is
|
||||
`@ hierarchical_event_identifier`, which has no `iff` alternative; `wait` takes
|
||||
an expression, not an event expression. So one field on `SensItem` and one
|
||||
parse line covers every position, and `iff` being a keyword means
|
||||
`parse_expr` already stops in front of it. The formatter prints the gate before
|
||||
the separator so it stays attached to its own term.
|
||||
|
||||
**The bare event control, and a pre-existing chain hole.** The `@name` path
|
||||
grew `[expr]` segments beside the `.name` ones it already had (§A.9.3's
|
||||
`hierarchical_identifier` is exactly names with optional bit-selects), which is
|
||||
what the three rstmgr copies need. Taking both greedily is safe because no
|
||||
statement begins with `.` or `[`. Lifting the loop into
|
||||
`parse_bare_event_name` also closed a hole: the *existing* `.name` loop boxed
|
||||
one layer per iteration without charging `link()`, which is precisely the shape
|
||||
`docs/features/recursion-limit/README.md` makes a standing requirement. It now
|
||||
charges, and the caller restores the count it started from the way
|
||||
`parse_postfix` does.
|
||||
|
||||
**The gate strength, at the amortized cost the mop-up predicted.**
|
||||
`DriveStrength::second` becomes `Option<String>` (one new formatter helper,
|
||||
`drive_strength`, so `assign` and gates share one spelling) and
|
||||
`GateInstantiation` gains `strength`. The `(` still only opens a strength when
|
||||
a strength *keyword* follows it, so `buf b1 ((a & b), c);` is untouched — a
|
||||
case in the table pins that.
|
||||
|
||||
**`program`, not in the brief's table.** Three files, and it is IEEE 1800
|
||||
§24.3's "module header, module body, different closer". One dispatch arm
|
||||
reusing `parse_module`, one `Module::end_kw` arm, and the two sync lists.
|
||||
Taking it brings the sweep to exactly the brief's ~11 target.
|
||||
|
||||
**The chain limit, measured in three stages** (all in a scratchpad copy;
|
||||
nothing built inside the repo, and the probes' `unsafe` static and
|
||||
million-link limit never leave it): what the files need (567, whole-tree
|
||||
distribution), what a link costs (9.20 KiB debug per postfix link, bisected
|
||||
across four lengths so the slope is measured and not assumed), and what the
|
||||
combined worst case is (9 894 KiB at 1024). Full tables and the choice above.
|
||||
The one thing worth flagging is that the previous rounds' "chains do not move
|
||||
the worst case" no longer holds at this budget — it did at 256, where a
|
||||
maximal chain cost 2.4 MiB against nesting's 5.9 — so `PARSE_STACK_SIZE` is now
|
||||
measured against the chain, and moved to 32 MiB to keep the 2.7×-or-better
|
||||
margin the stack round argued for. `MAX_NESTING_DEPTH` is untouched: nothing
|
||||
about this round changes which nesting a file may use.
|
||||
|
||||
**Deliberately not done: making the chain non-recursive in the AST.** The
|
||||
brief allows that consideration only if the needed limit were absurd (>10k).
|
||||
567 is not; it is a limit that was set for a smaller tree.
|
||||
|
||||
**Verification, in this order.** Sweep 43 → 19 → 14 → 11, `git status` clean
|
||||
after each. Set difference over the failing file names: **0 newly failing**.
|
||||
Whole-tree superset: `--stdout` hashed for all 3,943 files under trunk's binary
|
||||
(built in a temporary detached worktree, removed afterwards) and under this
|
||||
one — 0 newly failing, 32 newly passing, 1 moved (analysed above). Corpus: all
|
||||
860 files hash identically to trunk, and the gate reports 813/820 unchanged.
|
||||
|
||||
**Files touched.** `crates/vlog_parser/src/ast.rs`,
|
||||
`crates/vlog_parser/src/parser.rs`, `crates/vlog_parser/tests/spans.rs`,
|
||||
`crates/vlog_formatter/src/format.rs`,
|
||||
`crates/vlog_formatter/tests/cases/clocking_wave.cases` (new),
|
||||
`crates/vlog_formatter/tests/verification.rs`,
|
||||
`crates/vlog_formatter/tests/deep_nesting.rs`,
|
||||
`crates/vlog_semantic/src/bind.rs`,
|
||||
`crates/vlog_linter/tests/cases/unused_signal.lint`,
|
||||
`docs/features/recursion-limit/README.md`, `TODO.md`, this README.
|
||||
`crates/vlog_formatter/src/verify.rs` is **not** among them.
|
||||
|
||||
### 2026-08-29 (later) — dev, QA-driven rework
|
||||
|
||||
**QA's finding is correct, and the fix was the wrong shape rather than a
|
||||
missing guard.** The first version asked *"does a macro start this
|
||||
statement?"* — a question about the token before, when the information needed
|
||||
is entirely in the tokens after. A macro's expansion is a piece of text: it can
|
||||
be a whole statement (`` `ASSERT_ERROR(A) ``) or a signal name the statement
|
||||
goes on to assign to, read or increment (`` `SIG = 1'b1; ``, `` `CNT <= `CNT +
|
||||
1; ``, `` `MSG(x) + 1; ``, `` `CNT++; ``). The macro itself cannot tell those
|
||||
apart; the next token can. So the decision moved:
|
||||
|
||||
```rust
|
||||
let call = self.parse_macro_call()?;
|
||||
if call.semi || !self.at_statement_tail() { … return/chain … }
|
||||
// The macro was a name, not a statement. Scan on.
|
||||
```
|
||||
|
||||
`at_statement_tail` is one line — *the cursor is a `Symbol`* — because every
|
||||
way a statement continues past a name is spelled with one (`=`, `<=`, `+`,
|
||||
`++`, `.`, `[`, `::`), while everything that can stand after a complete action
|
||||
is a keyword, an identifier, another macro, a directive or EOF. Its doc comment
|
||||
records the asymmetry that makes the one-liner safe: guessing "continues" when
|
||||
the statement was in fact complete only falls back to the brute-force scan that
|
||||
ran before this case existed, i.e. to trunk; guessing "complete" when it was
|
||||
not is the regression, and non-symbols cannot continue an expression.
|
||||
|
||||
**Why not QA's literal suggestion** ("fall through to the ordinary scan
|
||||
whenever `;`/`else` does not follow"): that is the *old* over-scan for the case
|
||||
this round exists to fix — `` else `ASSERT_ERROR(A) `` has neither, and falling
|
||||
through is exactly what swallowed 55 lines of `prim_sync_reqack.sv`. The
|
||||
predicate is the missing third answer between "ends" and "scan on".
|
||||
|
||||
**Verified both directions against the real trunk binary**, not just the suite.
|
||||
All four QA shapes now produce **byte-identical** output to `5ad0772`
|
||||
(`--stdout`, diffed per shape). The six OpenTitan files this case unblocked
|
||||
still parse, `prim_sync_reqack.sv` still moves exactly as documented, and the
|
||||
sweep and whole-tree superset re-ran with the same numbers.
|
||||
|
||||
**Tests.** QA's three `#[ignore]`d pins are now active and green (their
|
||||
`#[ignore]` attributes removed and the "not fixed here" comment above them
|
||||
replaced with what the fix does). Added
|
||||
`a_macro_postfix_increment_is_not_the_whole_action_statement` (QA's fourth
|
||||
shape) and `a_macro_action_still_ends_where_no_statement_tail_follows`, which
|
||||
walks the four token kinds that can stand after a complete macro action — a
|
||||
keyword, a label identifier, another macro, a directive — so the *other* side
|
||||
of the decision is pinned too, not just the regression side. One more
|
||||
`clocking_wave.cases` entry round-trips all four shapes through the formatter.
|
||||
|
||||
**QA's LOW note folded in.** The `program`-as-`ItemKind::Module` lint widening
|
||||
is documented in Handshakes as deliberate, with the `module-name-style` message
|
||||
wording filed rather than fixed (pre-existing for `interface`, shared rule,
|
||||
outside this round's file set), and pinned by two new cases in
|
||||
`module_name_style.lint`.
|
||||
|
||||
**Files touched by the rework:** `crates/vlog_parser/src/parser.rs`,
|
||||
`crates/vlog_formatter/tests/cases/clocking_wave.cases`,
|
||||
`crates/vlog_linter/tests/cases/module_name_style.lint`, this README.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-29 — QA agent (round 2 verification)
|
||||
|
||||
**Verdict: REWORK (medium-high severity, one finding), everything else
|
||||
confirmed.** One real bug in the round's own charter-flagged risk area
|
||||
(the `skip_action_stmt` macro heuristic); every other claim in the work
|
||||
log reproduced exactly, including the chain-limit margin math with a
|
||||
sabotage check that genuinely aborts.
|
||||
|
||||
**Method.** Read CLAUDE.md, the work log above (all three premise
|
||||
corrections, all three skips), `docs/features/recursion-limit/README.md`
|
||||
round 4, and the dev brief. Built the round-2 tree and a detached
|
||||
`5ad0772` worktree, both `--release`, so every comparison below is
|
||||
binary-vs-binary, not test-suite-vs-claim. Every OpenTitan sweep used
|
||||
`--check`/`--stdout` only; `git -C .../opentitan status --porcelain`
|
||||
after every pass showed only `hw/ip/aes/dv/tb/tb.sv`, never anything else.
|
||||
|
||||
**BLOCKING — `skip_action_stmt`'s macro-at-statement-start check ends the
|
||||
scan too early when the macro is an operand or an lvalue, not a whole
|
||||
statement** (`crates/vlog_parser/src/parser.rs`, the `at_stmt_start` branch
|
||||
added this round, ~line 2021). The check assumes any macro token standing
|
||||
first in an action is *the entire action*, terminated by its own `;` or by
|
||||
chaining another one via `else`. That assumption is false whenever the
|
||||
macro's expansion is only the first sub-token of a larger statement — it
|
||||
stands for a signal name, not a full statement — and this happens for
|
||||
completely ordinary RTL/testbench idioms:
|
||||
|
||||
```
|
||||
A_A: assert property (a) else `SOME_SIGNAL = 1'b1; // macro as an lvalue
|
||||
A_A: assert property (a) else `MSG(x) + 1; // macro as an operand (the charter's own example)
|
||||
A_A: assert property (a) else `CNT <= `CNT + 1; // macro standing for a counter register
|
||||
A_A: assert property (a) else `CNT++;
|
||||
```
|
||||
|
||||
In each case `parse_macro_call` fails to eat a `;` (the next token is `=`,
|
||||
`+`, `<=`, `++`), `eat_kw("else")` then also fails, and the function
|
||||
returns `Ok(())` immediately — leaving the rest of the statement
|
||||
(`= 1'b1;`, `+ 1;`, …) on the token stream to be misread as the start of a
|
||||
new module item, which is a parse error (`expected item (found "=")`,
|
||||
etc.). **Confirmed on the real debug binary, both directions:**
|
||||
|
||||
```
|
||||
$ ./target/debug/lucisv --stdout a1_macro_lvalue.sv # round 2
|
||||
error: ...: parse error: 2:46: expected item (found "=")
|
||||
$ git stash && cargo build -p lucisv && ./target/debug/lucisv --stdout a1_macro_lvalue.sv # trunk 5ad0772
|
||||
module m;
|
||||
A_A: assert property (a) else `SOME_SIGNAL = 1'b1;
|
||||
assign y = 1;
|
||||
endmodule
|
||||
```
|
||||
|
||||
All four shapes above parse cleanly on trunk (no macro special-case at all
|
||||
— the old brute-force scan just runs to the real `;`) and fail to parse on
|
||||
round 2. This is exactly the charter's sin #1 ("an action scan that ends
|
||||
too early") and exactly the shape the charter's own example
|
||||
(`` `MSG(x) + 1; ``) named as worth checking. It does **not** corrupt
|
||||
output — invariant #1 holds, because the failure is an outright parse
|
||||
error, not a silently-wrong reformat — but it is a genuine, reproducible
|
||||
regression in *acceptance*: files with this pattern that parsed
|
||||
successfully on trunk now fail to format at all. It happens not to appear
|
||||
anywhere in the swept 3,943-file OpenTitan tree or the 860-file corpus
|
||||
today (both reproduced clean below), which is why the round's own
|
||||
sweep/superset checks did not catch it — but that is a statement about
|
||||
today's two trees, not about the fix's correctness.
|
||||
|
||||
The macro-terminates-the-action case the round actually needed
|
||||
(`` else `ASSERT_ERROR(A_A) `` with nothing after it, or chained with
|
||||
`else`) is real and correctly fixed; the bug is only in how the code tells
|
||||
that case apart from "a macro starts a larger statement". A plausible fix:
|
||||
before committing to the short return, check that `;` or `else` *actually*
|
||||
follows the macro (which the code already does, via `eat_sym`/`eat_kw`);
|
||||
on failure it currently just returns anyway. It needs to instead fall back
|
||||
to the ordinary token-by-token scan from wherever the macro call left the
|
||||
cursor, the same way it would have if the macro check didn't exist. Left
|
||||
to the dev — this changes control flow in a checked capture, not a
|
||||
one-line fix.
|
||||
|
||||
**Permanent regression tests added**, `crates/vlog_parser/src/parser.rs`
|
||||
(`mod tests`), marked `#[ignore]` (not left red — see below) with the
|
||||
finding quoted in the doc comment:
|
||||
`a_macro_used_as_an_lvalue_is_not_the_whole_action_statement`,
|
||||
`a_macro_used_as_an_operand_before_an_operator_is_not_the_whole_action_statement`,
|
||||
`a_macro_counter_increment_is_not_the_whole_action_statement`. Verified
|
||||
each one currently **fails** when run explicitly
|
||||
(`cargo test -p vlog_parser -- --ignored <name>`, 3 failed / 0 passed),
|
||||
confirming they pin the real bug rather than being vacuous; un-ignore once
|
||||
fixed. Also added three passing tests for edges that *did* hold up (below).
|
||||
|
||||
**Everything else in the charter, confirmed:**
|
||||
|
||||
1. **`default disable iff` bracket scan — solid.** Attacked with the real
|
||||
binary: a `;` inside a string (`x == "a;b"`), a `;` inside a block
|
||||
comment (`/* ; */`), two `default disable iff` items back to back, and
|
||||
EOF before the terminating `;`. All four behave correctly (string/
|
||||
comment cases parse through unaffected because the lexer already
|
||||
tokenizes strings whole and comments as trivia, not because the scanner
|
||||
does anything special; two-in-a-row capture separately; EOF is a clean
|
||||
`expected \`;\`` error, not a swallowed rest-of-file). Added as permanent
|
||||
tests: `a_default_disable_iff_is_not_ended_by_a_semicolon_inside_a_string`,
|
||||
`a_default_disable_iff_is_not_ended_by_a_semicolon_inside_a_comment`,
|
||||
`two_default_disable_iffs_in_a_row_are_captured_separately`. The six
|
||||
`verification.rs` attack pairs are legitimate: `verify.rs` was not
|
||||
touched, and none of the six rely on a normalization the capture
|
||||
introduced — they exercise the *pre-existing* generic net (byte-exact
|
||||
comparison outside `Directive`/`Attribute`/backtick-`Ident` tokens,
|
||||
line-trim only for comments) against a new *source* of `RawText`, which
|
||||
is the correct, minimal thing to test per CLAUDE.md rule 4 (no
|
||||
normalization was added, so there is nothing new to attack beyond
|
||||
proving the generic net still sees every token inside this capture —
|
||||
which the six pairs do).
|
||||
|
||||
2. **Chain math — reproduced, and the margin is real, not overstated.**
|
||||
`cargo test -p vlog_formatter --test deep_nesting`: 5/5 pass, including
|
||||
`a_maximal_chain_inside_deep_nesting_formats` (the 9.9 MiB combined
|
||||
worst case) at the shipped `PARSE_STACK_SIZE = 32 MiB`. **Sabotage
|
||||
check, as the charter asked**: set `MAX_CHAIN_LENGTH = 4096` with the
|
||||
stack left at 32 MiB, rebuilt — `a_maximal_chain_inside_deep_nesting_formats`
|
||||
(spelled generically off the constant) now dies with a genuine
|
||||
`SIGABRT` / "stack overflow" (not a graceful test failure), confirming
|
||||
the chosen 1024 actually needs the 32 MiB and the margin claim is not
|
||||
inflated. Reverted immediately; `cargo test -p vlog_formatter --test
|
||||
deep_nesting` back to 5/5 green.
|
||||
`pinmux_reg_top.sv` (567 links, the file that started the round) parses
|
||||
with the release binary — `--check` reports "would reformat", not a
|
||||
parse error.
|
||||
|
||||
3. **New-field audit.** `ClockingSignal.value`: only consumed in
|
||||
`format.rs::clocking_item` and matched by `signals.rs:366`'s
|
||||
`ClockingItemKind::Signals { .. }` wildcard (correctly opaque — pinned
|
||||
by the three new `unused_signal.lint` cases, which I re-ran directly and
|
||||
confirm: the clocking-bound signal, the `default disable iff` name, and
|
||||
the `iff`-gated `enable` behave exactly as documented — opaque, opaque,
|
||||
read respectively). `SensItem::iff` is bound as an ordinary read in
|
||||
`bind.rs:1084-1090` (`bind_expr`), matching the lint case. `DriveStrength
|
||||
::second`/`GateInstantiation::strength`: the one non-test consumer,
|
||||
`format.rs::gate_instantiation`/`drive_strength`, handles `None`
|
||||
correctly (prints the single-strength form). **`program`-as-`Module`
|
||||
wildcard side effect (not a bug, but undocumented):** because `program`
|
||||
reuses `ItemKind::Module`, every generic `ItemKind::Module(_)` match
|
||||
picks it up for free — including `vlog_linter::visit::items` (so every
|
||||
lint rule now descends into program bodies) and
|
||||
`rules/module_filename.rs` (a one-program file is now held to the same
|
||||
"file name matches the construct's name" convention as a module or
|
||||
interface). Both are reasonable, consistent with the "a program is a
|
||||
module" design decision, and neither is exercised by a program-specific
|
||||
linter test in this round. `rules/module_name_style.rs` hardcodes the
|
||||
word "module" in its violation message regardless of `.kw` — a
|
||||
pre-existing cosmetic inaccuracy for `interface` from before this round
|
||||
(not introduced here), now also reachable for `program`. Low severity,
|
||||
not blocking; worth a one-line doc/message fix and a program lint case
|
||||
whenever this area is touched again.
|
||||
|
||||
4. **Reproduce, all exact:**
|
||||
- Sweep: **43 → 11** (trunk / round 2 release binaries, `--check` over
|
||||
all 3,943 real `.sv`/`.svh` files, 32 excluded symlinks). Set
|
||||
difference (round-2-fail minus trunk-fail): **empty** — zero newly
|
||||
failing. The 11 match the README's table exactly (the 3 skips +
|
||||
the 8 OUT files), by name.
|
||||
- Whole-tree superset: hashed `--stdout` output over the 3,900
|
||||
trunk-passing files under both binaries — **exactly 1** moves,
|
||||
`hw/ip/prim/rtl/prim_sync_reqack.sv`. Diffed it: the moved lines are
|
||||
precisely the ~55-line generate block the old scan used to swallow
|
||||
into the assertion's opaque bytes (re-indented from 2-space to
|
||||
4-space now that it is a real nested `if`/`always_ff`, `else if(` →
|
||||
`else if (`, nothing else). Re-formatted the round-2 output a second
|
||||
time: byte-identical — idempotent.
|
||||
- Corpus: `scripts/corpus_gate.sh` → `813/820` passing, gate exits 0.
|
||||
All **860** `.sv`/`.v`/`.svh`/`.vh` corpus files hash identical
|
||||
between trunk and round 2.
|
||||
- The three skips: `kmac_reduced_tb.sv` and `SimDTM.sv` fail with
|
||||
byte-identical messages on both binaries. `jtag_if.sv`'s message
|
||||
*does* change (trunk: `51:17 expected \`;\` (found "=")` — the
|
||||
clocking blocker; round 2: `163:1 expected \`endinterface\` (found
|
||||
"<eof>")` — the rival-`ifdef`-headers blocker) — this is the
|
||||
documented, correct behavior, not a violation: the first blocker is
|
||||
genuinely fixed, and the second is independent and pre-existing.
|
||||
Verified pre-existence directly: fed the work log's own minimal
|
||||
repro (`` `ifdef G / module i #(...)() / `else / module i #(...)()
|
||||
/ `endif / wire w; / endmodule ``) to **both** binaries — identical
|
||||
`8:1 expected \`endmodule\` (found "<eof>")` on trunk and round 2, so
|
||||
the second blocker is provably not something this round introduced.
|
||||
|
||||
5. **Gates.** `cargo fmt --check`: clean. `cargo clippy --all-targets`:
|
||||
silent. `cargo test --workspace`: green (0 failed) both before and
|
||||
after my additions; my 3 new active tests pass, my 3 `#[ignore]`d
|
||||
regression tests are excluded from the default run so the gate stays
|
||||
green while still pinning the bug for whoever reworks it.
|
||||
|
||||
**Files touched by this QA pass:** `crates/vlog_parser/src/parser.rs`
|
||||
(6 new tests only — 3 active, 3 `#[ignore]`d), this README's QA log.
|
||||
Nothing else in the tree was modified; the `MAX_CHAIN_LENGTH` sabotage
|
||||
edit was reverted before any test run that could persist it, and confirmed
|
||||
reverted (`git diff 5ad0772 --stat` unchanged from the dev's own file
|
||||
list). No commits made.
|
||||
|
||||
### 2026-08-29 (later) — QA agent, rework verification
|
||||
|
||||
**Verdict: SHIP.** The rework fixes the blocking finding correctly and the
|
||||
fix shape (deciding by what *follows* the macro, not by what precedes it)
|
||||
is the right one — my own suggested "fall through whenever `;`/`else`
|
||||
doesn't follow" would have reintroduced the exact over-scan
|
||||
`prim_sync_reqack.sv` needed fixed, and the dev's writeup says so
|
||||
explicitly. Two new informational findings surfaced while attacking the
|
||||
asymmetry claim, neither blocking; everything else reproduces.
|
||||
|
||||
**Charter 1 — attacking the asymmetry claim ("wrongly continues ⇒
|
||||
trunk-identical").** Confirmed the mechanism first: no lexer changes this
|
||||
round (`ast.rs`/`parser.rs`/tests only in the diff), `BLOCK_OPENERS`/
|
||||
`BLOCK_CLOSERS` byte-identical to trunk, and the fallback loop body after
|
||||
the new macro branch is textually unchanged from trunk's
|
||||
`skip_action_stmt`. So *when the predicate is correct*, the fallback walks
|
||||
the identical token stream through identical code from the identical
|
||||
cursor position trunk would reach — the claim holds by construction, not
|
||||
just by observation. Tested it anyway, real binary, both directions, per
|
||||
shape:
|
||||
|
||||
| shape | round 2 vs trunk |
|
||||
|---|---|
|
||||
| `;` immediately following the macro, written on the **next source line** | byte-identical (`eat_sym` is whitespace/line-blind, so `call.semi` is `true` here regardless of the line break — the charter's premised "call.semi false" doesn't arise for a directly-adjacent `;`) |
|
||||
| macro call's close paren followed by `::` (`` `GET_TYPE(x)::CONST = 1; ``) | byte-identical — `::` is a `Symbol`, correctly reads "continues," falls through, matches trunk |
|
||||
| macro-only action immediately followed by `{p, q} = c;` | byte-identical — `{` is a `Symbol`, "continues," and trunk's own brute scan already swallowed the same statement (this is the *pre-existing* over-swallow class, not a new one) |
|
||||
| macro-only action immediately followed by `#5 x <= 1;` | byte-identical, same reasoning |
|
||||
|
||||
**Two informational findings, not blocking, from pushing on the *other*
|
||||
side of the same question — cases where the predicate correctly says
|
||||
"complete" and *that* is what moves output away from trunk:**
|
||||
|
||||
- `` else `ASSERT_ERROR(A_A) `` directly followed by `(* foo *) wire w;`:
|
||||
`(* ... *)` lexes as `TokenKind::Attribute`, not `Symbol`, so
|
||||
`at_statement_tail` correctly says "complete." Trunk's un-special-cased
|
||||
scan swallowed the attribute *and* the declaration into the assertion's
|
||||
opaque bytes (same class as `prim_sync_reqack.sv`), so it printed
|
||||
`(* foo *) wire w;` on one line, byte-for-byte as written. Round 2
|
||||
correctly cuts the action off before the attribute, so `wire w;` is
|
||||
reparsed as its own item and the formatter's ordinary
|
||||
attribute-before-item rule puts `(* foo *)` on its own line — a second,
|
||||
undocumented, correct output-moving case of exactly the same species as
|
||||
the one the work log calls out. It does not show up in either swept
|
||||
corpus today (both re-verified below at zero newly-failing / exactly one
|
||||
move), so the round's specific count is accurate for the trees it was
|
||||
measured against — but the "exactly one move" framing describes today's
|
||||
corpora, not a ceiling on how many files this class of shape could ever
|
||||
move. Worth a one-line note in the Handshakes section next time this
|
||||
area is touched; not a defect.
|
||||
- `` else `ASSERT_ERROR(A_A) `` directly followed by `B_LBL: assign x =
|
||||
1;` (a labelled *procedural continuous assignment*, IEEE 1800 §10.6):
|
||||
round 2 correctly separates the two statements (the label is an
|
||||
`Ident`, not a `Symbol`), but the parser has no support for `assign` as
|
||||
a *statement* inside a procedural block at all — confirmed pre-existing
|
||||
and identical on trunk with the construct in isolation, no macro
|
||||
involved (`initial begin assign x = 1; end` errors identically,
|
||||
byte-for-byte same message and column, on both binaries). On trunk the
|
||||
gap was invisible because the whole labelled statement was swallowed as
|
||||
opaque verbatim bytes next to the macro; round 2's correct boundary
|
||||
detection now *reaches* the gap and reports a clean parse error instead
|
||||
of silently accepting unparsed text. This does not corrupt anything
|
||||
(invariant #1 holds — a clean error, not partial output) and the shape
|
||||
does not occur in either swept tree, so it is not a regression against
|
||||
either corpus today. It is a real (if obscure) residual: any future file
|
||||
combining a bare-macro assertion action with a procedural `assign`
|
||||
statement immediately after it would newly report an error rather than
|
||||
silently mis-swallow. Filing rather than fixing — supporting procedural
|
||||
`assign`/`deassign` as statements is unrelated grammar work, out of this
|
||||
round's scope.
|
||||
|
||||
**Charter 2 — attacking `at_statement_tail`'s `Symbol` test from the other
|
||||
side.** Both named traps checked directly with the real binary: a `;` on
|
||||
the line after the macro (covered in the table above — resolves via
|
||||
`call.semi`, not via the predicate, so the "symbol ⇒ continues" path never
|
||||
even gets exercised for this shape) and `::` after the macro's close paren
|
||||
(covered above — correctly "continues," matches trunk). No case found
|
||||
where the `Symbol` test itself picks the wrong side for a real construct.
|
||||
|
||||
**Charter 3 — pins, then sabotage.** `cargo test -p vlog_parser --lib`
|
||||
filtered to the seven relevant tests (my four un-ignored pins, the dev's
|
||||
new `a_macro_action_still_ends_where_no_statement_tail_follows`, and the
|
||||
two originals `a_macro_may_be_a_concurrent_assertions_whole_action_statement`
|
||||
/ `a_macro_inside_an_action_statement_is_an_operand_not_a_terminator`):
|
||||
7/7 green, none `#[ignore]`d anymore. Inverted `at_statement_tail`
|
||||
(`==` → `!=`) and reran the same seven: **6 of 7 failed** — all four of my
|
||||
"continues" pins, the dev's new "complete" pin, and the original
|
||||
whole-action test all broke; only the pre-existing mid-expression test
|
||||
survived (it never reaches the predicate — the macro isn't at
|
||||
`at_stmt_start` there). This is a stronger result than a single-direction
|
||||
check: inverting the boolean breaks tests on *both* sides of the decision,
|
||||
so the suite is not merely pinned to one branch. Reverted; reran clean
|
||||
(7/7).
|
||||
|
||||
**Charter 4 — spot-re-verification, all against fresh binaries (release,
|
||||
rebuilt from the reworked source; a fresh detached `5ad0772` worktree for
|
||||
trunk, removed after use).** `--check`/`--stdout` only throughout;
|
||||
`git -C .../opentitan status --porcelain` after every sweep showed only
|
||||
`hw/ip/aes/dv/tb/tb.sv`, on every pass below.
|
||||
- Sweep: **43 → 11**, identical to the pre-rework run — diffed the two
|
||||
11-line failure lists directly, byte-identical set. Zero newly-failing
|
||||
against trunk's 43, reconfirmed by `comm`.
|
||||
- The four attack-pair table shapes above are the dev's own claim,
|
||||
independently reproduced: byte-identical `--stdout` output between
|
||||
trunk and round 2 for all four, diffed directly rather than taken on
|
||||
the work log's word.
|
||||
- Whole-tree superset: re-hashed all 3,900 trunk-passing files —
|
||||
**exactly 1** moves (`prim_sync_reqack.sv`), same file as before the
|
||||
rework.
|
||||
- The six previously-blocked files individually re-checked: `adc_ctrl_
|
||||
fsm_sva_if.sv`, `kmac_app_if.sv`, `prim_sync_reqack.sv` all "would
|
||||
reformat" (no error); `jtag_if.sv` still fails at its documented,
|
||||
independent second blocker (`163:1 expected endinterface`), unchanged
|
||||
from the pre-rework check.
|
||||
- Corpus: `scripts/corpus_gate.sh` → `813/820`, gate exits 0. All 860
|
||||
`.sv`/`.v`/`.svh`/`.vh` corpus files hash identical to trunk.
|
||||
|
||||
**Charter 5 — gates.** `cargo fmt --check`: clean. `cargo clippy
|
||||
--all-targets`: silent. `cargo test --workspace`: **2633 passed, 0
|
||||
failed, 36 ignored** — up from my pre-rework count of 2628/0/39, consistent
|
||||
with my three `#[ignore]`d pins now being active and green (+3 passed, -3
|
||||
ignored) plus the dev's new `#[test]` additions; the `.cases`/`.lint`
|
||||
additions are new cases inside existing fixture-driver tests, not new
|
||||
`#[test]` functions, so they don't add to the raw count directly but are
|
||||
covered by `cargo test -p vlog_formatter --test fixtures` (2/2) and
|
||||
`cargo test -p vlog_linter --test lint_cases` (14/14), both green. The
|
||||
number that matters — **0 failed** — is unambiguous either way.
|
||||
|
||||
**Files touched by this pass:** none in the tracked tree (the
|
||||
`at_statement_tail` sabotage was reverted immediately after the two test
|
||||
runs that bracket it, confirmed by `git diff 5ad0772 --stat` matching the
|
||||
dev's rework file list exactly); this README's QA log only. No commits
|
||||
made.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-29 — lead.** Reviewed across dev, QA REWORK (a real
|
||||
regression in four macro-action shapes trunk parses — latent on both
|
||||
swept corpora, found only by crafted idiom), the rework, and QA's SHIP
|
||||
on re-verification; gates re-run by the lead. Three things distinguish
|
||||
this round. First, it corrected its own brief twice by reading real
|
||||
sites — the 14-file "clocking" bucket was two seven-file families, and
|
||||
clocking itself was already modelled, needing one production rather
|
||||
than the capture the brief presumed. Second, the chain-limit change is
|
||||
what a limit change should be: measured need (567), measured per-link
|
||||
cost, a stack resized to restore the house margin, a sabotage probe
|
||||
proving the margin real, one of the feature's own published claims
|
||||
("chains do not move the worst case") retired on the numbers, and a
|
||||
pre-existing uncharged loop closed in passing. Third, the rework's
|
||||
predicate decides on the token after the macro with the failure
|
||||
direction argued and then attacked: QA verified "wrongly continues
|
||||
degrades to trunk-identical" by construction against the diff, not by
|
||||
trust. The dev's rejection of QA's literal fix suggestion, with
|
||||
reasons, is the loop working as peers rather than as a pipeline. The
|
||||
two informational finds (the attribute-after-action instance of the
|
||||
explained output-move class; a pre-existing procedural-assign gap now
|
||||
surfacing as a clean error) are filed. Accepted; committed by the
|
||||
lead. OpenTitan sweep: 151 at the wave's start, 11 now — the remainder
|
||||
being macro fragments awaiting a preprocessing decision, vendor
|
||||
non-SV recommended for exclusion, and three written-up skips.
|
||||
@@ -68,22 +68,46 @@ computed by, so the lens and the hierarchy view can never disagree (TODO.md
|
||||
invalidate. Not on a keystroke either — a `didChange` cannot change any
|
||||
count, since the census is over instantiations in *other* files and a client
|
||||
re-requests lenses for the buffer it just edited anyway.
|
||||
- **The count is computed against `Workspace::sources()`**, which reads every
|
||||
- ~~**The count is computed against `Workspace::sources()`**, which reads every
|
||||
in-scope file from disk with open buffers overriding it. So an unsaved
|
||||
instantiation typed into another open buffer *is* counted, and a file
|
||||
changed on disk that no watcher reported is counted as of this request.
|
||||
- **The cost is one workspace walk per request, not one per module.**
|
||||
changed on disk that no watcher reported is counted as of this request.~~
|
||||
**Superseded (incremental-index, 2026-08-27)** — see the assumption above.
|
||||
- ~~**The cost is one workspace walk per request, not one per module.**
|
||||
`hierarchy::callers_of_each` takes a batch precisely because `sources()`
|
||||
re-reads the whole file set: measured over the 860-file corpus, a
|
||||
three-module file costs 133 ms against 93 ms for a single name (debug build)
|
||||
— amortized, not tripled. The absolute number is the honest cost of having
|
||||
no instantiation-edge table in the index; see Status / TODO.
|
||||
no instantiation-edge table in the index; see Status / TODO.~~
|
||||
**Superseded (incremental-index, 2026-08-27): the cost is a lookup.** The
|
||||
count comes from 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 names,
|
||||
to turn recorded byte spans into ranges — 0.26 ms for the same three-module
|
||||
file over the same corpus. The batch stays the primitive for the same
|
||||
reason at a smaller scale: one file instantiating three of the names is read
|
||||
once.
|
||||
- **The count is as of the index, which is as of its last build or update**
|
||||
(incremental-index, 2026-08-27) — superseding the assumption below that the
|
||||
count is computed against `Workspace::sources()` per request. A save, or any
|
||||
other rescan trigger, folds every open buffer in and makes an edit count; a
|
||||
keystroke alone no longer does. The trade and the alternatives considered are
|
||||
in `docs/features/incremental-index/README.md`.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### Request to `vlog_semantic` — an instantiation-edge table in the index
|
||||
|
||||
Filed by the lead (2026-08-26) on QA's recommendation, since **two** shipped
|
||||
**Delivered (incremental-index, 2026-08-27).** `WorkspaceIndex::instantiations_of`
|
||||
exists with the shape proposed below — plus the owning declaration's name and
|
||||
full extent, which is what stopped `callers_of_each` re-parsing the file to
|
||||
find them — and `hierarchy::callers_of_each` is a lookup with its walk-and-parse
|
||||
body deleted. The census policies carried over by construction: the table is
|
||||
built by the same `instantiations::sites` walk the handler used to run, which
|
||||
was lifted into `vlog_semantic` for exactly that reason, and every one of this
|
||||
feature's QA tests passes unchanged. Measured 92 ms → 0.26 ms for a
|
||||
three-module file over the corpus. The original request, kept legible:
|
||||
|
||||
~~Filed by the lead (2026-08-26) on QA's recommendation, since **two** shipped
|
||||
features now pay the same cost: every `textDocument/codeLens` request and
|
||||
every `callHierarchy/incomingCalls` walks `Workspace::sources()` — a re-read
|
||||
and tolerant re-parse of every in-scope file — because `WorkspaceIndex`
|
||||
@@ -100,7 +124,7 @@ pub fn instantiations_of(&self, name: &str) -> &[InstantiationEdge]
|
||||
so `hierarchy::callers_of_each` becomes a lookup and its whole
|
||||
walk-and-parse body is deleted. The census policies (multi-instance
|
||||
statements = one site, textual not elaborated, both `ifdef` arms) must carry
|
||||
over unchanged — `lens.rs`'s QA tests pin the numbers that must not move.
|
||||
over unchanged — `lens.rs`'s QA tests pin the numbers that must not move.~~
|
||||
|
||||
|
||||
### `lucisv_server::hierarchy` — **changed, deliberately**
|
||||
@@ -206,7 +230,7 @@ no-showDocument path — verified by running it.
|
||||
is an instantiation-edge table in `WorkspaceIndex`, built once per
|
||||
rescan, which would make both this and `incomingCalls` a lookup. That is
|
||||
a `vlog_semantic` change and belongs in its own round; **request
|
||||
recorded here, not made.**
|
||||
recorded here, not made.** — **done, incremental-index, 2026-08-27.**
|
||||
|
||||
## Work log
|
||||
|
||||
|
||||
@@ -81,20 +81,52 @@ workspace index, from the same file list, and are replaced with it.
|
||||
- **Consumes `vlog_parser`**: `tokenize` for the word harvest, `KEYWORDS` for
|
||||
the keyword tier, `defines::DefineKind` to keep `` `undef`` entries out of the
|
||||
macro table.
|
||||
- **Consumes `vlog_refactor`** exactly as M4 did — `module_names`,
|
||||
`module_definition`, `instantiation_plan`, `render_with` — through the
|
||||
unchanged `module_tier`. Nothing in `vlog_refactor` was touched.
|
||||
- **Consumes `vlog_refactor`** — `instantiation_plan`, `render_with` —
|
||||
through the planning half (`plan_for`), which since 2026-08-30 serves only
|
||||
`inline.rs`'s ghost; `module_tier` itself reads no files. The
|
||||
`module_definition` consumption ended with round 2 of inline-instantiation:
|
||||
the file is chosen by `completion::nearest_definition` (most shared leading
|
||||
path components with the asking buffer, then shallowest, then
|
||||
lexicographic), which never refuses on multiplicity the way
|
||||
`module_definition` deliberately does. Nothing in `vlog_refactor` was
|
||||
touched, then or since.
|
||||
- **Stopped consuming `vlog_refactor::module_names` (2026-08-28).** That
|
||||
function is `WorkspaceIndex::workspace_symbols("")` filtered to modules, and
|
||||
`workspace_symbols` builds and sorts a record per declaration in the whole
|
||||
workspace — 43 140 of them in opentitan, on *every keystroke*.
|
||||
`Candidates::modules` is the same list, built once beside the index and
|
||||
filtered per request, and
|
||||
`candidates::tests::the_module_table_answers_exactly_what_module_names_answers`
|
||||
asserts the two agree — set *and* order — at eleven queries.
|
||||
`vlog_refactor::module_names` is unchanged and still has its own callers;
|
||||
only tier 0 stopped asking it. **Note for whoever changes it**: the two are
|
||||
now pinned against each other by that test, so a change to `module_names`'s
|
||||
match rule or ordering breaks the build rather than silently diverging.
|
||||
- **Reads `WorkspaceIndex::units`'s `Def::name_span` directly (2026-08-28)**,
|
||||
to anchor the header slice (`module_header`). Treated as advisory, never as
|
||||
truth: the byte range is checked against the text actually read, and a
|
||||
mismatch — a file edited on disk since the last scan — declines the slice
|
||||
and parses the whole file, exactly as before.
|
||||
- **Duplicated deliberately, not shared**: `vlog_refactor::ports::visible_in`
|
||||
answers "is this *one* name visible here" and is `pub(crate)` to that crate;
|
||||
`completion::visible_symbols` answers "what is visible here". They share the
|
||||
innermost-scope idea and nothing else, and lifting one to fit both would have
|
||||
meant widening another crate's API for a second caller that wants a different
|
||||
answer. Recorded so the lead can overrule it cheaply.
|
||||
- **Promises `lucisv_server`'s own callers**: `completions` never panics, always
|
||||
returns items whose `textEdit` replaces exactly the typed word (plus the
|
||||
backtick, in the macro case), and never returns a module item whose text
|
||||
differs from what M4 returned — the M4 tests assert the skeleton byte for
|
||||
byte and still pass.
|
||||
- **Promises `lucisv_server`'s own callers**: `completions` never panics, and
|
||||
always returns items whose `textEdit` replaces exactly the typed word (plus
|
||||
the backtick, in the macro case).
|
||||
- ~~"never returns a module item whose text differs from what M4 returned"~~ —
|
||||
**superseded 2026-08-30** by the owner's two-level ruling. A tier-0 item now
|
||||
inserts the module's **name**; the instantiation is ghost text served by
|
||||
`inline.rs`, planned once, for the one module the user has spelled out. The
|
||||
byte-for-byte skeleton pins moved with it. See
|
||||
`docs/features/inline-instantiation/README.md`.
|
||||
- **Provides `at_instantiation_site` (new, 2026-08-30, `pub(crate)`)** — tier
|
||||
0's own position gate, lifted out of `completions` so `inline.rs` asks the
|
||||
identical question rather than growing a second answer to it. `plan_for` and
|
||||
`snippet_hole` became `pub(crate)` for the same caller; `module_header`
|
||||
already was. Nothing about what any of the three computes changed.
|
||||
- **`editors/vscode` needs no change.** No new setting, no new capability: the
|
||||
completion provider was already advertised, and `snippetSupport` is read the
|
||||
same way.
|
||||
@@ -106,22 +138,48 @@ alphabetically within a tier.
|
||||
|
||||
| Tier | What | `CompletionItemKind` | Where it comes from |
|
||||
|---|---|---|---|
|
||||
| `0` | Module instantiation skeletons | `MODULE` | M4, unchanged — module-item position only |
|
||||
| `0` | Module **names** (instantiation candidates) | `MODULE` | `Candidates::modules`, module-item position only |
|
||||
| `1` | Declarations the scope chain at the cursor binds | the declaration's own kind | this file's `Semantics` |
|
||||
| `2` | Packages, package members, typedefs, classes, modules, `` `define`` names | the declaration's own kind, `CONSTANT` for a macro | `WorkspaceIndex`, tabled at build time |
|
||||
| `3` | Every reserved word | `KEYWORD` | `vlog_parser::KEYWORDS` |
|
||||
| `4` | Every identifier used anywhere in the project | `TEXT` | token harvest, tabled at build time |
|
||||
| `3` | Statement / item / declaration templates | `SNIPPET` | `templates.rs`, gated by position |
|
||||
| `4` | Every reserved word | `KEYWORD` | `vlog_parser::KEYWORDS` |
|
||||
| `5` | Every identifier used anywhere in the project | `TEXT` | token harvest, tabled at build time |
|
||||
|
||||
Tier 0 is first because at module-item position a fifteen-line skeleton is what
|
||||
the user is reaching for, and it is the only tier that is *position*-gated at
|
||||
all: M4's gate (nothing but whitespace before the word on its line, plus
|
||||
Two responses are **exclusive** and contain none of the six: the backtick
|
||||
response (`` `WI| ``, macro names only — *The backtick ruling* below) and,
|
||||
since 2026-09-02, the **member** response after a `.` or a `::` (the members
|
||||
of what stands before it, `sortText` digit `0`, nothing else at all). Neither
|
||||
is a tier; each is the whole answer to a different question, and the tier
|
||||
table above is what a *plain identifier* gets. See
|
||||
`docs/features/member-completion/README.md`.
|
||||
|
||||
Tier 0 is first because at module-item position a module name is what the user
|
||||
is reaching for — and, since 2026-08-30, a *name* is all it inserts: the
|
||||
instantiation follows as ghost text once the name is spelled exactly and a
|
||||
space typed after it (`docs/features/inline-instantiation/README.md`). For a
|
||||
module declared in more than one file, the item's detail names the copy the
|
||||
ghost will read (`nearest_definition`'s pick for this buffer). It is still the only tier
|
||||
that is *position*-gated at all: M4's gate (nothing but whitespace before the word on its line, plus
|
||||
`pairs::analyze`'s scope chain) is unchanged and still declines inside a
|
||||
procedural block, a function, a class, a connection list and an expression.
|
||||
Every other tier ignores position entirely — a name is a name wherever it is
|
||||
written — which is why M4's "nothing is offered here" tests became "no
|
||||
*skeleton* is offered here".
|
||||
|
||||
Tier 4 deliberately includes names that are **not** visible at the cursor. That
|
||||
**Amended 2026-09-02.** That last sentence is still true of the tiers and no
|
||||
longer true of the *response*. Two byte sequences immediately before the typed
|
||||
run — a `` ` `` and, now, a `.` or a `::` — make the answer something other
|
||||
than the six tiers: they say what kind of name may be written here at all, and
|
||||
the response becomes only that kind. The difference from tier 0's gate is
|
||||
worth stating, because it is the difference between withholding items and
|
||||
replacing the answer: tier 0 declining leaves the other five to answer, where
|
||||
a separator leaves nothing else to say. An unreadable or unresolvable head
|
||||
after a separator therefore answers **nothing** rather than falling back to
|
||||
the six tiers — which, until 2026-09-02, is exactly what the cursor after a
|
||||
dot got: the whole-index dump, 512 items of everything.
|
||||
See `docs/features/member-completion/README.md`.
|
||||
|
||||
Tier 5 deliberately includes names that are **not** visible at the cursor. That
|
||||
is the point of it: it is the rope / VS Code word-completion tier, and a name
|
||||
used three files away is a better guess than nothing. It is last, and it is
|
||||
`TEXT`, so it never pretends to be a resolved symbol.
|
||||
@@ -130,6 +188,39 @@ Dedup is by label, first tier wins. A name that is both a local declaration and
|
||||
a word used elsewhere in the project is offered once, in tier 1, with its real
|
||||
kind and its declaration line as detail.
|
||||
|
||||
### Amendment, 2026-08-30 — how a tier *matches*
|
||||
|
||||
Tier ordering, `sortText`, dedup, the caps and the position gates are all
|
||||
unchanged. What changed is the comparison three of the tiers make, and only
|
||||
from the third typed character up:
|
||||
|
||||
| Tier | Matched by, ≥3 characters typed | Was |
|
||||
|---|---|---|
|
||||
| `0` module names | substring | substring — unchanged |
|
||||
| `1` declarations in scope | **subsequence** | prefix |
|
||||
| `2` index names | **subsequence** | prefix |
|
||||
| `2` `` `define`` names | prefix — unchanged | prefix |
|
||||
| `3` templates | prefix — unchanged | prefix |
|
||||
| `4` keywords | prefix — unchanged | prefix |
|
||||
| `5` project words | **subsequence** | prefix |
|
||||
| the backtick response | prefix — unchanged | prefix |
|
||||
|
||||
**Below three characters every tier matches exactly as it did before**, item
|
||||
for item. The one thing that had to change there is `isIncomplete`: a 1- or
|
||||
2-character response now always sets it, because VS Code re-asks the server
|
||||
only when the last answer said so, and a complete 2-character answer would
|
||||
swallow the third keystroke — the one that turns subsequence matching on.
|
||||
|
||||
Within a tier the fuzzy hits are ordered prefix-first, then by a boundary /
|
||||
contiguity / gap score, then by name; that order is the order of the `items`
|
||||
array, and decides which items survive the cap. `sortText` is still
|
||||
`<tier digit><name>` and still means the tier order and nothing else.
|
||||
|
||||
Rules, scoring, the `isIncomplete` argument and the measurements are in
|
||||
`docs/features/fuzzy-completion/README.md`. The prefix API this file describes
|
||||
(`Candidates::units`/`words`/`macros`/`modules`/`has_module`) is untouched and
|
||||
still answers exactly what it answered.
|
||||
|
||||
## The backtick ruling
|
||||
|
||||
`` `define`` names are the one candidate whose spelling depends on where the
|
||||
@@ -217,9 +308,89 @@ sorted case-insensitively, so a match is a `partition_point` and then a
|
||||
`take_while` over one contiguous run. Nothing allocates a lowercase copy —
|
||||
`lower_cmp` compares byte iterators.
|
||||
|
||||
The one request that is *not* microseconds is a module-item position, which
|
||||
still parses up to 64 defining files. That is M4's cost, unchanged and
|
||||
separately capped.
|
||||
The one request that was *not* microseconds was a module-item position, which
|
||||
parsed up to 64 defining files. Two rounds took that apart: the header slice
|
||||
below (2026-08-28) and, finally, the two-level split (2026-08-30) that stopped
|
||||
the popup planning anything at all. Tier 0 is now a scan of a table like every
|
||||
other tier.
|
||||
|
||||
### The module tier, 2026-08-28
|
||||
|
||||
That last paragraph was the whole bill. `performance.md` §6d measured
|
||||
completion at **34–66 ms per keystroke** against opentitan, worst at 0–4 typed
|
||||
characters, and typing an eleven-character identifier at **201 ms** of blocked
|
||||
single-threaded loop. The probe
|
||||
(`perf::completing_one_keystroke_at_a_time`) runs the same request with the
|
||||
cursor at module-item position and inside an expression, where tier 0 is gated
|
||||
off:
|
||||
|
||||
| generated corpus, 4 000 files | at an item | in an expression |
|
||||
|---|---:|---:|
|
||||
| empty prefix, before | 53.2 ms | 0.19 ms |
|
||||
| empty prefix, after | **3.17 ms** | 0.19 ms |
|
||||
|
||||
Every other tier put together is 0.19 ms and always was. Two changes, neither
|
||||
of which may alter an item:
|
||||
|
||||
1. **`module_header` — parse the header, not the file.** A plan reads a
|
||||
module's parameter list and port list and nothing else, and both are in the
|
||||
header; the body was being parsed to reach them. The slice is the file's
|
||||
text up to the `;` that ends the header, **kept byte for byte** so every
|
||||
span the plan reads still points where it did, with an `endmodule` written
|
||||
in place of the body. It is anchored on the index's `Def::name_span`
|
||||
(checked against the text, so a file edited under the index declines rather
|
||||
than slices at a stale offset) and the end is found by lexing a bounded
|
||||
window and walking a **whitelist**: `static`/`automatic`, `import …;`,
|
||||
`#(…)`, `(…)`, `;`. Anything else answers "no slice" and the whole file is
|
||||
parsed exactly as before — `module aes import aes_pkg::*; #(…) (…);` writes
|
||||
three semicolons and only the last ends the header, which is why this is a
|
||||
whitelist and not a search for the first `;`.
|
||||
2. **`Candidates::modules` — table the module names.** See Handshakes.
|
||||
|
||||
Two guards keep the answer identical, and both are load-bearing rather than
|
||||
decoration:
|
||||
|
||||
- **A non-ANSI port list writes its directions in the module *body***
|
||||
(`module m (a); input wire [7:0] a;`), which is the part the slice drops. A
|
||||
plan whose ports have neither a direction nor a type is the signature of
|
||||
that, and `plan_for` re-plans from the whole file when it sees one.
|
||||
`a_non_ansi_port_list_is_planned_from_the_whole_file` asserts both halves —
|
||||
that the header alone really does lose them, and that the guard really does
|
||||
get them back.
|
||||
- **A slice that fails to plan is re-planned whole**, so the list can only
|
||||
ever lose an item where it would have lost it anyway.
|
||||
|
||||
`the_header_slice_plans_exactly_what_the_whole_file_plans` is the argument, not
|
||||
the prose: fifteen header shapes — imports, two imports, no ports, an empty
|
||||
port list, non-ANSI with and without body declarations, a comment inside the
|
||||
header, a lifetime qualifier, a directive between the name and the port list, a
|
||||
directive *inside* the port list, an escaped module and port name, a second
|
||||
module before and after the one being planned, and a header wider than the
|
||||
first window rung — each planned both ways and compared field by field.
|
||||
|
||||
`HEADER_WINDOWS` is a ladder because the lex is the whole cost of the slice and
|
||||
it is linear in what it is handed. The rungs are measured, not guessed: over
|
||||
opentitan's 344 RTL modules 59% of headers end inside 256 bytes and 90% inside
|
||||
2 KB, and the largest is 6.6 KB — so a top rung of 16 KB, because a rung that
|
||||
is too small is not a wrong answer but a 2–4 ms whole-file parse. The full
|
||||
before/after, including the four `aes_control*` modules that found this, is in
|
||||
`docs/perf/README.md`, *Before / after — round 7*.
|
||||
|
||||
Against the real checkout, over the wire: **63–66 ms → 13.1–15.0 ms** at the
|
||||
empty prefix, and typing `aes_reg_top` **200.9 ms → 64.5 ms**. What was left
|
||||
was 64 real header parses, and the two ways down from there — memoizing the
|
||||
plan, or `completionItem/resolve` — both changed something that round was not
|
||||
allowed to change.
|
||||
|
||||
### The module tier, 2026-08-30
|
||||
|
||||
The owner took the third way: **stop planning on the popup path entirely.**
|
||||
Tier 0 answers with module *names*, and the instantiation is offered as ghost
|
||||
text once the user has typed a name exactly — one plan, for one module, at the
|
||||
moment they have said which one they mean. The 64 remaining header parses are
|
||||
gone with it, and `module_header`/`plan_for` live on unchanged as the ghost's
|
||||
planner. See `docs/features/inline-instantiation/README.md`; the numbers on
|
||||
opentitan are QA's to record there.
|
||||
|
||||
## Version 0.3.0
|
||||
|
||||
@@ -269,9 +440,47 @@ incidental; they exercise the parser, not the version.
|
||||
- [x] Version 0.3.0 across the workspace, the extension and the docs
|
||||
- [x] `cargo fmt --all -- --check`, `cargo clippy --all-targets`,
|
||||
`cargo test --workspace` all clean; `smoke.js` OK
|
||||
- [x] **Performance wave, Lane B (2026-08-28):** completion 34–66 ms per
|
||||
keystroke → 13–15 ms worst case on opentitan and 3.2 ms on the
|
||||
same-sized generated corpus, with the items pinned identical. Tier 0
|
||||
parses the header instead of the whole declaring file
|
||||
(`module_header` / `plan_for`), and the module-name list is a table
|
||||
built with the index (`Candidates::modules`) instead of a
|
||||
whole-symbol-table sort per keystroke.
|
||||
|
||||
## Work log
|
||||
|
||||
- **2026-08-28 (dev, performance wave Lane B)** — the module tier.
|
||||
|
||||
Profiled first, as the brief asked, with an `#[ignore]`d house probe rather
|
||||
than a guess: `perf::completing_one_keystroke_at_a_time` measures the whole
|
||||
request at nine prefixes with tier 0 on and off. The answer was that
|
||||
**everything except tier 0 costs 0.19 ms at every prefix**, so
|
||||
`performance.md`'s hypothesis — "scanning/filtering the candidate set, and
|
||||
the broader the prefix the more of the 3 976-file symbol table is walked" —
|
||||
was half right: the symbol-table walk was real but it was
|
||||
`vlog_refactor::module_names`'s, inside tier 0, not the word or index tiers'.
|
||||
|
||||
What changed is in *The module tier, 2026-08-28* above, with the identity
|
||||
argument and the fifteen-shape test that carries it. Two decisions worth
|
||||
naming:
|
||||
|
||||
- **No cache.** The obvious fix is to memoize the plan per module. It was not
|
||||
taken: `Candidates` is rebuilt at `didSave`, and tier 0 reads
|
||||
`ws.text_of`, which sees an *unsaved* buffer — so a cache there would go
|
||||
stale exactly where `another_open_buffer_overlays_disk_once_the_index_is_rebuilt`
|
||||
says it must not. Slicing needed no new invalidation rule at all, and it
|
||||
makes the cold request fast rather than only the repeat.
|
||||
- **The whitelist is a whitelist.** `header_end` refuses every shape it does
|
||||
not recognise instead of scanning for the first `;`. `module aes import
|
||||
aes_pkg::*; #(…) (…);` is the case that makes the difference, and it is
|
||||
what most of opentitan's `aes*` modules are written as: a first-`;` scan
|
||||
would have silently reported them as having no ports.
|
||||
|
||||
Deviations from the brief: none on this item. The measurement is on
|
||||
`docs/perf/README.md` rather than here, because that is where this
|
||||
repository keeps before/after numbers; this section keeps the argument.
|
||||
|
||||
- **2026-08-24 (dev)** — implemented.
|
||||
|
||||
**Keyword list.** `vlog_parser/src/token.rs`'s `is_keyword` was a 181-arm
|
||||
@@ -637,8 +846,128 @@ unambiguous" (typo/missing assertion) territory; all three are judgment
|
||||
calls for the dev/lead. No commits, no edits to `TODO.md` or the umbrella
|
||||
`docs/features/refactor/README.md`.
|
||||
|
||||
### 2026-08-28 — QA agent (performance wave Lane B: the module tier)
|
||||
|
||||
Verdict: **the fix holds. No corruption found, one pre-existing parser gap
|
||||
surfaced (filed below, not fixed here — out of this feature's touched
|
||||
files).**
|
||||
|
||||
**What I attacked.** The whitelist walk in `header_end`, the guard in
|
||||
`plan_for`, and `Candidates::modules`'s parity with
|
||||
`vlog_refactor::module_names`, per the adversarial list in the round brief:
|
||||
header-slice mis-slicing, stale-span handling, and the module-table's set
|
||||
*and* order against hostile queries.
|
||||
|
||||
**Header-slice attacks — all safe, one gap in the dev's own test found and
|
||||
fixed.** Extended `SHAPES` in `completion.rs` (in
|
||||
`the_header_slice_plans_exactly_what_the_whole_file_plans`) with: a single
|
||||
`import a::*, b::*;` declaration (comma-chained packages, one statement —
|
||||
`skip_to_semicolon` must not stop at the first `::`), a parameter default
|
||||
whose string literal contains a literal `;` and `)` (`"a;b)c"`), CRLF line
|
||||
endings through the whole header, a genuine attribute instance right after
|
||||
the module name, and one inside the port list on a single port. All five
|
||||
plan identically sliced vs. whole-file; the two attribute shapes exposed
|
||||
something worth recording (next paragraph). Added
|
||||
`the_attack_shapes_actually_slice_rather_than_passing_the_pin_vacuously`
|
||||
(`completion.rs`) asserting the first three actually invoke the slice path
|
||||
(`module_header(..).is_some()`) rather than passing the comparison
|
||||
vacuously by both sides falling back to the whole file — a real risk with
|
||||
this style of pinned-equality test, since a shape the whitelist declines
|
||||
passes the assertion for free.
|
||||
|
||||
**Finding (LOW, not a regression this round introduced) — `completion.rs`,
|
||||
`module_header`, and transitively `vlog_semantic`/`vlog_parser`: a module
|
||||
with an attribute instance (`(* ... *)`) anywhere near its header is not
|
||||
indexed as a `Module` unit at all.** `WorkspaceIndex::units("attributed")`
|
||||
and `..("port_attributed")` both come back empty for
|
||||
`module attributed (* some_attr *) #(...) (...);` and
|
||||
`module port_attributed (input logic clk, (* keep *) output logic q);`.
|
||||
`module_header` correctly declines at its very first line (`let [def] =
|
||||
index.units(module)...else { return None }`, `completion.rs:99-103`) —
|
||||
this is the documented whole-file fallback working exactly as designed,
|
||||
not a slicing bug — but it means completion's module tier, which sources
|
||||
its candidate names from the same index, never offers such a module as a
|
||||
completion candidate in the first place, attribute-based header or not.
|
||||
This predates 2026-08-28 (the index-level gap is not something tier 0's
|
||||
change touches), so it is filed rather than fixed: out of Lane B's stated
|
||||
files (`vlog_semantic`/`vlog_parser` are not touched-file scope for this
|
||||
round). Reproduction: `cargo test -p lucisv_server -- completion::tests::
|
||||
a_module_with_an_attribute_near_its_header_is_not_indexed_at_all`, a new
|
||||
permanent regression pinning the current (gap) behavior so a future fix to
|
||||
the indexer is *noticed* here rather than silently changing what
|
||||
`module_header` sees.
|
||||
This also means the dev's own `noisy` shape's doc comment ("a comment and
|
||||
an attribute inside the header") was inaccurate — it has two comments and
|
||||
no attribute; I did not edit that comment since fixing it is a one-line
|
||||
call for the dev, and the actual behavior is now separately pinned above.
|
||||
|
||||
**Stale-span attack**: `a_stale_index_span_declines_to_slice_rather_than_
|
||||
slicing_the_wrong_bytes` (dev's own test) re-verified by hand — re-ran with
|
||||
`cargo test -p lucisv_server -- completion::tests::a_stale_index_span` in
|
||||
isolation, passes. No addition needed; the test already does the right
|
||||
thing (name-span-vs-text mismatch declines).
|
||||
|
||||
**`Candidates::modules` parity**: `contains_ignore_case` (`candidates.rs`)
|
||||
and `contains_ignore_ascii_case` (`vlog_semantic::workspace`) are
|
||||
byte-identical implementations, and both `Candidates::modules` and
|
||||
`vlog_refactor::module_names` ultimately filter the same
|
||||
`workspace_symbols`-sorted, `container.is_none() && kind == Module` slice
|
||||
with the same predicate — so parity is structural, not incidental, and
|
||||
holds for any name content (case-different names, escaped identifiers,
|
||||
duplicate names across files) without needing per-shape tests. Traced by
|
||||
hand rather than by adding more cases to the dev's own
|
||||
`the_module_table_answers_exactly_what_module_names_answers` (which
|
||||
already covers duplicates-across-files and query-case-differences); no
|
||||
counter-example found.
|
||||
|
||||
**Numbers reproduced** (release build, this machine, M1 Max):
|
||||
- `perf::completing_one_keystroke_at_a_time`: empty prefix at item position
|
||||
**3.28 ms** (dev's claim: 3.17 ms — within machine noise), expression
|
||||
position 190 µs unchanged. Whole-file plan 2.68 ms vs. header-alone
|
||||
16.3 µs for one skeleton off the 1214-line generated file — matches the
|
||||
claimed order of magnitude.
|
||||
- `LUCISV_PERF_CORPUS=/Users/guoliangchen/repo/opentitan cargo test
|
||||
--release -p lucisv_server perf::completing_over_a_real_project`: empty
|
||||
prefix **11.6 ms** (dev's claim against the real wire protocol: 13.1–15.0
|
||||
ms; this is the in-process `completions()` call without LSP round-trip
|
||||
overhead, so a bit faster is expected, same order of magnitude). Zero
|
||||
modules fell back to whole-file parsing across every prefix tested
|
||||
(`parsed whole: []`), confirming the slice fires in practice on real RTL,
|
||||
not just in the synthetic corpus.
|
||||
- Live end-to-end confirmation against the real opentitan checkout with
|
||||
this worktree's release binary (`node`-free, via a copy of the
|
||||
scratchpad's `lspclient.py`/`bench.py` pointed at
|
||||
`target/release/lucisv-server`): completion itself was not re-measured
|
||||
over the wire (out of scope to re-run the whole battery), but see the
|
||||
references-nav QA log below for the documentHighlight leg of the same
|
||||
session, which used the identical harness.
|
||||
|
||||
**Gates**: `cargo fmt --check`, `cargo clippy --all-targets`, `cargo test
|
||||
--workspace` (1261 passed, up from 1259 with my additions), `node
|
||||
editors/vscode/smoke.js target/release/lucisv-server` — all clean, run
|
||||
against the worktree with my additional tests included.
|
||||
|
||||
No fixes applied beyond the two new permanent regression tests (attack
|
||||
shapes actually slicing; the attribute-indexing gap pinned). No commits.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-28 — lead, performance-wave Lane B.** Reviewed after QA's
|
||||
SHIP; gates re-run on the worktree (fmt clean, clippy silent, 2495
|
||||
workspace tests green). The header-slice design is right because of
|
||||
what it refuses: a whitelist walk that re-plans from the whole file on
|
||||
anything it does not positively recognize — including the non-ANSI
|
||||
signature — is the honest shape, and QA's seven added attack shapes
|
||||
plus the field-by-field plan-equality pin make the "items byte
|
||||
identical" claim tested rather than asserted. The stale-span decline
|
||||
and the Candidates::modules order-and-set parity are correctly pinned.
|
||||
QA's LOW (attribute-instance modules not indexed as units — a
|
||||
pre-existing parser/semantic gap the guard already declines safely) is
|
||||
accepted as filed with its regression pin; it belongs to a parser
|
||||
round, not this one. The residual opentitan cost is real header
|
||||
parses, with the plan-cache and completionItem/resolve options filed
|
||||
where the numbers are. Accepted.
|
||||
|
||||
**2026-08-24 — lead.** Reviewed after QA's ship verdict — the first
|
||||
milestone through with no rework round; gates run independently (1262
|
||||
tests, 0 failures, clippy silent). The keyword-table refactor was verified
|
||||
|
||||
@@ -197,7 +197,7 @@ nothing, and the same is true of a buffer that does not lex.
|
||||
|
||||
| Tier | What |
|
||||
|---|---|
|
||||
| `0` | module instantiation skeletons (M4) |
|
||||
| `0` | module names (the instantiation follows as ghost text) |
|
||||
| `1` | declarations the scope chain binds |
|
||||
| `2` | what the project declares |
|
||||
| `3` | **templates** |
|
||||
@@ -291,17 +291,21 @@ as it is… the client will not apply any kind of adjustments". The vendored
|
||||
*that* into the `KeepWhitespace` rule that clears `adjustWhitespace`.
|
||||
|
||||
So `completion.rs` sends `insertTextMode: asIs` (the `KEEP_MY_INDENTATION`
|
||||
constant) on the two item builders that write more than one line: the template
|
||||
tier and the module-instantiation skeleton. Single-line items neither need it
|
||||
nor are harmed by it, so they do not send it. It is the right answer for the
|
||||
plain-text spelling as well — that text is absolutely positioned too — which
|
||||
is why this path did **not** switch to relative indentation the way ghost text
|
||||
had to. An inline completion has no `insertTextMode` field at all; see
|
||||
constant) on every item builder that writes more than one line. Single-line
|
||||
items neither need it nor are harmed by it, so they do not send it. It is the
|
||||
right answer for the plain-text spelling as well — that text is absolutely
|
||||
positioned too — which is why this path did **not** switch to relative
|
||||
indentation the way ghost text had to. An inline completion has no
|
||||
`insertTextMode` field at all; see
|
||||
`docs/features/inline-templates/README.md`'s *The indentation contract*.
|
||||
|
||||
Pinned by `tests/e2e.rs` (`insertTextMode == 1` on both the template item and
|
||||
the module skeleton), over the wire, beside the `newText` each already
|
||||
asserted.
|
||||
**Amended 2026-08-30:** that used to be *two* builders, the template tier and
|
||||
the module-instantiation skeleton. The module item is a plain word now — the
|
||||
instantiation moved to ghost text
|
||||
(`docs/features/inline-instantiation/README.md`) — so the template tier is the
|
||||
only multi-line item left, and the module item sends no `insertTextMode` at
|
||||
all. Pinned by `tests/e2e.rs`: `insertTextMode == 1` on the template item, and
|
||||
absent on the module item.
|
||||
|
||||
## Reconciliation with the static VS Code snippets
|
||||
|
||||
|
||||
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user