Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ce2f7190ed | ||
|
|
aa479cf701 | ||
|
|
d9ed2c447a | ||
|
|
1da0a303cc | ||
|
|
f476c31483 | ||
|
|
9ef1058059 | ||
|
|
4d59e80568 | ||
|
|
859742ac84 |
No files matched your search
@@ -4,6 +4,63 @@ 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.46.0 — 2026-09-05
|
||||
|
||||
### Two refactorings: expand `.*`, convert ports to ANSI
|
||||
|
||||
- **Expand `.*`.** A wildcard connection is written out as the named
|
||||
connections it stands for, in the module's declaration order, through
|
||||
the port engine's splice and verifier. The wildcard rule is read
|
||||
strictly (IEEE 1800 §23.3.2.4): a same-named net, variable or port
|
||||
binds; a parameter, genvar, type or instance does not, and that port
|
||||
becomes `.p()` with a warning naming it. Refused inside a `bind`
|
||||
directive, on a positional list, on two `.*`, or when a file does not
|
||||
parse. Code action `lucisv: expand .* (N connections)` and command
|
||||
`lucisv.expandWildcard`.
|
||||
- **Convert ports to ANSI.** A Verilog-2001 header with body
|
||||
declarations becomes an ANSI header (`output b; reg [7:0] b;` →
|
||||
`output reg [7:0] b`, every merge of §23.2.2.2), the absorbed
|
||||
declarations deleted and their comments carried onto the ports. The
|
||||
edit inserts around each header name so nothing that referenced the
|
||||
port moves; twenty-three shapes are refused with a sentence rather
|
||||
than guessed (port expressions, disagreeing ranges, initialisers,
|
||||
directives, a comment that would have to move into a one-line list).
|
||||
Code action `lucisv: convert ports to ANSI (N ports)` and command
|
||||
`lucisv.convertToAnsi`.
|
||||
- **The refactoring verifier's comment rule is stricter, and covers
|
||||
attributes.** Every comment and every `(* … *)` attribute a file had it
|
||||
still has, by exact text and count; a piece a deletion covers is
|
||||
written back exactly as many times as it was deleted, and an edit may
|
||||
not duplicate one nothing touched — which also catches a comment
|
||||
rewritten, truncated or duplicated. Ships with masked-corruption
|
||||
attack tests, re-attacked by QA.
|
||||
|
||||
## 0.45.0 — 2026-09-05
|
||||
|
||||
### Cross-file semantics: type spans, re-exports, hierarchical tails
|
||||
|
||||
- **Type names carry spans.** Every `DataType` and `disable` target knows
|
||||
its range on the AST; the semantic crate's text scanner (`scan.rs`) is
|
||||
deleted. Definition and hover on a type name land exactly, `pkg::t`
|
||||
selecting `t`; a segment the source spells differently from the
|
||||
parser's join is recorded with an empty range rather than guessed.
|
||||
- **Package re-exports are real references.** `export pkg::item;` and
|
||||
`export pkg::*;` bind both halves, the index records each package's
|
||||
re-exports, and definition, hover, completion after `pkg::`, references
|
||||
and rename follow them transitively. On opentitan a name reached only
|
||||
through `export spi_device_reg_pkg::SramDepth;` now resolves.
|
||||
- **Renaming an internal net edits its hierarchical uses in other files.**
|
||||
A module now has a hierarchical surface (nets, variables, instances)
|
||||
read only behind an instance head — `assign w = u_x.sig;` in another
|
||||
file renames with `sig`'s declaration, nested `u_a.u_b.sig` included —
|
||||
while connection lists still see ports and parameters only. Completion
|
||||
after `u_x.` in an expression lists the hierarchical members. Over
|
||||
opentitan's `hw/`, 514 hierarchical references resolve that did not
|
||||
before; a rename that now reaches one more file costs one more file's
|
||||
read.
|
||||
- The index facts format is 19; stores written by earlier releases are
|
||||
rebuilt on first use.
|
||||
|
||||
## 0.44.0 — 2026-09-05
|
||||
|
||||
### Opening a file no longer stalls the editor
|
||||
|
||||
Generated
+9
-8
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.44.0"
|
||||
version = "0.46.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.44.0"
|
||||
version = "0.46.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.44.0"
|
||||
version = "0.46.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.44.0"
|
||||
version = "0.46.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.44.0"
|
||||
version = "0.46.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"vlog_formatter",
|
||||
@@ -265,19 +265,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.44.0"
|
||||
version = "0.46.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.44.0"
|
||||
version = "0.46.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.44.0"
|
||||
version = "0.46.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.44.0"
|
||||
version = "0.46.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -112,6 +112,12 @@ trailing `/` (matches directories only), and `!` negation. **Not** supported:
|
||||
git's "already-tracked files are never ignored" rule. See
|
||||
`docs/features/parallel-files/README.md` for the exact subset.
|
||||
|
||||
Directory walks enter each directory once by identity, so symlink cycles
|
||||
terminate. Inputs resolving to one canonical file path are processed once.
|
||||
Unreadable directories or `.gitignore` files and dangling source links found
|
||||
during a walk warn on stderr and are skipped without changing the exit code;
|
||||
a missing explicitly named input is still an error.
|
||||
|
||||
## Configuration
|
||||
|
||||
Settings live in a `lucisv.toml` (or `.lucisv.toml`) file, ruff-style. For each
|
||||
|
||||
@@ -710,8 +710,26 @@ section only tracks the milestones.
|
||||
- [x] **M14 `macro-expansion`** — single-step macro expansion on hover
|
||||
(the define-table README's promised follow-up); version 0.5.0 with a
|
||||
CHANGELOG entry covering M7–M14.
|
||||
- [ ] Backlog (extract module, inline, `.*` expansion, ANSI conversion,
|
||||
organize imports, …) — triaged in the umbrella README after M5.
|
||||
- [ ] Backlog (extract module, inline, ~~`.*` expansion~~, ~~ANSI
|
||||
conversion~~, organize imports, …) — triaged in the umbrella README after M5.
|
||||
**`.*` expansion shipped 2026-09-05 (§50,
|
||||
`docs/features/expand-wildcard/README.md`)**: the wildcard written out as
|
||||
the named connections it stands for, per IEEE 1800 §23.3.2.4, with a code
|
||||
action and `lucisv.expandWildcard`. It leaves one thing behind, added to
|
||||
this backlog: **a `.*` written in a `bind` directive**, which binds in the
|
||||
target's scope rather than the one it is written in — elaboration, not
|
||||
lexical lookup, and 57 of OpenTitan's 66 wildcard sites.
|
||||
**Non-ANSI → ANSI conversion shipped 2026-09-05 (§51,
|
||||
`docs/features/ansi-conversion/README.md`)**: a Verilog-2001 header rewritten
|
||||
the modern way, each port declaration merged with the net or variable
|
||||
declaration that completes it per IEEE 1800 §23.2.2.2, with a code action and
|
||||
`lucisv.convertToAnsi`. It leaves two things behind, added to this backlog:
|
||||
**an `interface`'s non-ANSI header**, which needs the `modport`s that name
|
||||
the same ports read first; and **an attribute instance on an absorbed
|
||||
declaration** (`(* keep *) input a;`), which the conversion refuses rather
|
||||
than moves — where a `(* ... *)` belongs in an ANSI port list, and whether
|
||||
the same one may be split across the ports a multi-name declaration
|
||||
declares, is a design question the merge rule does not answer.
|
||||
|
||||
## 9. LSP 3.18 protocol audit (2026-08-26)
|
||||
|
||||
@@ -4787,11 +4805,349 @@ census, 21 485 symbols).
|
||||
sweep unchanged; a before/after of `definition` on 200 type-name
|
||||
positions over opentitan (read-only) to show nothing regressed.
|
||||
|
||||
- [ ] 47.1 `DataType::name_span` + `segments()`, size ruled
|
||||
- [ ] 47.2 `StmtKind::Disable` name span
|
||||
- [ ] 47.3 `scan.rs` deleted; binder reads spans; census pin extended
|
||||
- [ ] docs: feature README; topo §2.9-2 struck (lead); semantic READMEs
|
||||
- [ ] Gates (guarded)
|
||||
- [ ] QA: census re-derived; escaped and scoped type names; `iface.mp`
|
||||
- [x] 47.1 `DataType::name_span` + `segments()`, size ruled
|
||||
- [x] 47.2 `StmtKind::Disable` name span
|
||||
- [x] 47.3 `scan.rs` deleted; binder reads spans; census pin extended
|
||||
- [x] docs: feature README; topo §2.9-2 struck (lead); semantic READMEs
|
||||
- [x] Gates (guarded): 3 814 tests / 0 failed / 44 ignored (the 0.44.0 count
|
||||
exactly — six `scan.rs` unit tests out, six new ones in); corpus 814/820,
|
||||
the per-file TSV byte-identical to the committed one; `format --stdout`
|
||||
of all 860 corpus files identical to `lucisv-0.44.0`; clippy and fmt
|
||||
clean; release server smoke OK; census 27 486 symbols / 103 870
|
||||
references / 0 unplaced, identical to a `v0.44.0` scratch worktree; 200
|
||||
`definition` positions over opentitan identical old vs new
|
||||
- [x] QA: census re-derived; escaped and scoped type names; `iface.mp`
|
||||
ports; implicit types; definition/hover on type names over
|
||||
opentitan (read-only)
|
||||
|
||||
## 48. Package re-exports as real references (planned 2026-09-05) — topo §2.9-16
|
||||
|
||||
One lane after §47 merges, §36's protocol. Feature README:
|
||||
`docs/features/package-reexports/README.md`. Ships in 0.45.0.
|
||||
|
||||
`ItemKind::Export(paths)` is bound as an opaque leaf (`bind/item.rs`, the
|
||||
dpi-export handshake). Two halves, both here:
|
||||
|
||||
- **The binding half.** `export pkg::item;` and `export pkg::*;` record
|
||||
`pkg` as a `Target::Unit` reference and `item` as a
|
||||
`Target::UnitMember(pkg)` reference — exactly the halves
|
||||
`bind_import_path` records — **without** pushing a scope import: a
|
||||
re-export brings nothing into the exporting scope (IEEE 1800 §26.6). One
|
||||
new binder function beside `bind_import_path`, sharing its path walk.
|
||||
`export *::*;` records no references (there is no name to resolve) and
|
||||
is documented as "everything this package imports is re-exported".
|
||||
- **The resolution half.** A file that does `import a_pkg::*` (or names
|
||||
`a_pkg::x`) must resolve `x` when `a_pkg` re-exports it from `b_pkg`.
|
||||
The index records each package's re-exports as facts (`FACTS_FORMAT`
|
||||
17 → 18: an `RX` group — `(pkg, item|*)` pairs plus the `*::*` flag;
|
||||
`index_cache` drops older stores by format as it already does), and the
|
||||
member walk in `workspace/external.rs` that lists a unit's members
|
||||
follows re-exports: `a_pkg`'s members += `b_pkg`'s exported `item`, or
|
||||
all of `b_pkg`'s exports for `b_pkg::*`, or all of every package
|
||||
`a_pkg` imports for `*::*` — with a visited set so a re-export cycle
|
||||
terminates. Completion after `a_pkg::` lists them; hover/definition on
|
||||
`x` lands on `b_pkg`'s declaration; references of `b_pkg::x` include the
|
||||
uses through `a_pkg`; rename of `x` edits the re-export line's `item`
|
||||
too (the rename engine reads references, so this should follow — pin
|
||||
it).
|
||||
- Tests: binding — the two halves recorded with exact spans; no scope
|
||||
import (a name re-exported is NOT visible bare inside the exporting
|
||||
package unless also imported — pin the negative); resolution — a
|
||||
three-file workspace (b_pkg declares, a_pkg re-exports one/`*`/`*::*`,
|
||||
top imports a_pkg::*) for definition, hover, completion, references and
|
||||
rename over the wire; a re-export cycle; a re-export of a name b_pkg
|
||||
does not declare (unresolved, no panic); the census numbers re-derived
|
||||
and the delta explained (new references only); FACTS_FORMAT bump test
|
||||
(an older store is dropped whole).
|
||||
|
||||
- [x] 48.1 binding of `export` halves, no scope import
|
||||
- [x] 48.2 `RX` facts, FACTS_FORMAT 18, member walk through re-exports
|
||||
- [x] docs: feature README; topo §2.9-16 struck (lead); dpi-export
|
||||
handshake (a) answered
|
||||
- [x] Gates (guarded); census delta explained — references 103 870 → 103 875
|
||||
(+5: the corpus's two package `export` lines, five name halves in all),
|
||||
every other number flat
|
||||
- [x] QA: the three-file workspace over the wire; cycles; unknown items;
|
||||
an opentitan UVM package tree read-only (definition through a
|
||||
re-export, before/after)
|
||||
|
||||
## 49. Cross-file instance-member tail in rename (planned 2026-09-05) — topo §2.9-23
|
||||
|
||||
One lane after §48 merges, §36's protocol. Feature README:
|
||||
`docs/features/hierarchical-tail/README.md`. Ships in 0.45.0.
|
||||
|
||||
With `module sub` in `sub.sv` and `assign w = u_x.sig;` in `top.sv`,
|
||||
renaming `sub`'s internal `wire sig` edits `sub.sv` only and warns (item
|
||||
20's warning); the same shape in one file resolves and is edited. The
|
||||
cause is the export rule in `workspace/record.rs::is_exported`: a module
|
||||
exports ports and parameters only, so the cross-file member walk cannot see
|
||||
`sig` through `u_x`.
|
||||
|
||||
**Ruling (lead): a module gains a second, distinct surface.** Its
|
||||
*connection* surface stays ports + parameters (what a connection list may
|
||||
name; completion in a connection list and the `propagate-ports` engine keep
|
||||
reading exactly this). Its *hierarchical* surface is its nets, variables
|
||||
and (for nested reach) instances, which a hierarchical path may name from
|
||||
anywhere (IEEE 1800 §23.6). The index records both, tagged
|
||||
(`FACTS_FORMAT` 18 → 19 if §48 already bumped to 18, else 17 → 18: the
|
||||
member record carries a `surface` bit), and only the tail walk behind an
|
||||
*instance* (`Target::MemberOf { head: an instance … }`) reads the
|
||||
hierarchical surface. Nothing else changes what it sees.
|
||||
|
||||
- `resolve_external`: a `MemberOf` whose head resolves to an instance of
|
||||
module `M` looks `tail` up in `M`'s hierarchical surface (then nested
|
||||
instances for `u_a.u_b.sig`); the answer is a `Def` in `M`'s file, so
|
||||
rename's reference set now includes the cross-file tail and the edit
|
||||
lands on it; the §2.9-20 warning is no longer raised for a tail that
|
||||
resolved (it stays for one that did not).
|
||||
- Not widened: completion after `u_x.` in an expression MAY list the
|
||||
hierarchical surface (it is what the user is typing) — say whether it
|
||||
does and pin it either way; a connection list's completion must not.
|
||||
- Tests: `a_hierarchical_tail_that_resolves_is_renamed_with_its_declaration`
|
||||
gets its cross-file twin (two files, the edit lands in both; the warning
|
||||
gone); nested `u_a.u_b.sig`; a tail naming a port (both surfaces — one
|
||||
answer); a tail naming a parameter; a generate-block-scoped net
|
||||
(`u_x.gen[0].sig` — refuse honestly, pin); an interface instance tail
|
||||
(already resolves — unchanged); the `--check` of rename's verifier still
|
||||
refuses when a tail is ambiguous (two `sub` declarations); the census
|
||||
delta explained; opentitan (read-only): rename of an internal net used
|
||||
hierarchically from a DV bench, timing before/after, and the count of
|
||||
newly resolved references over `hw/ip/aes`.
|
||||
|
||||
- [x] 49.1 surface bit in facts, FACTS_FORMAT bump (18 → 19), index member
|
||||
walk — `workspace/hierarchy.rs`, a second `hier_members` table
|
||||
- [x] 49.2 `MemberOf` behind an instance reads the hierarchical surface;
|
||||
rename edits the tail; the warning retired for resolved tails
|
||||
- [x] docs: feature README (`docs/features/hierarchical-tail/README.md`);
|
||||
topo §2.9-23 struck (lead — strike text in the README); record.rs's
|
||||
export doc rewritten (the ruling moved to `hierarchy::surface_of`)
|
||||
- [x] Gates (guarded): 3 839 tests / 0 failed / 44 ignored (baseline 3 829,
|
||||
+10 new); corpus 814/820, the same six; `format --stdout` of all 860
|
||||
corpus files byte-identical to `lucisv-0.44.0`, 0 differing; clippy and
|
||||
fmt clean; release server smoke OK. Census: single-file corpus census
|
||||
unmoved (860 / 27 486 / 103 875 / 1 197 / 0), index gains 5 239
|
||||
hierarchical-only members beside an unchanged 12 939, and 335 corpus
|
||||
references resolve that could not before. opentitan (read-only,
|
||||
requests never applied): `lc_ctrl`'s `fsm_state_q` rename now names
|
||||
`dv/tb.sv` as well as `rtl/lc_ctrl_fsm.sv` (10 → 22 ms; prepareRename
|
||||
unmoved); over `hw/ip/aes` the newly resolved count is **0** (every
|
||||
`aes` hierarchical path goes through a generate block or a `bind`) and
|
||||
rename is 41 → 55 ms for the same answer; over all of `hw/` 514
|
||||
references newly resolve; store +10.7 % on `aes`, +6.2 % on `lc_ctrl`
|
||||
- [x] QA: the shapes above over the wire; the connection-list completion
|
||||
unchanged; rename verifier refusals unchanged; opentitan before/after
|
||||
|
||||
## 55. Filed 2026-09-05 — `lucisv_server/src/state.rs` over the size threshold
|
||||
|
||||
The §49 dev measured `crates/lucisv_server/src/state.rs` at 957 production
|
||||
lines outside tests, over the 800 "consider splitting" mark and past the
|
||||
§28 decomposition note in CLAUDE.md (which is stale for it). A pure-move
|
||||
decomposition round (Fable refactor-dev, per the refactor policy): the
|
||||
scope/widen logic, the document store, and the source selectors
|
||||
(`module_sources`, `rename_sources`) are three sentences. Not planned; the
|
||||
owner decides where it goes in loop 2.
|
||||
|
||||
- [ ] `state.rs` decomposition (pure move, byte-identical output, test
|
||||
count unchanged); CLAUDE.md's measurement line refreshed
|
||||
|
||||
## 50. `.*` expansion (planned 2026-09-05) — the first §8 refactoring
|
||||
|
||||
One lane after 0.45.0, §36's protocol. Feature README:
|
||||
`docs/features/expand-wildcard/README.md`. Ships in 0.46.0 with §51.
|
||||
|
||||
A wildcard connection `sub u_x (.clk(clk), .*);` binds every remaining
|
||||
port to the same-named signal in scope (IEEE 1800 §23.3.2.4). Expanding it
|
||||
writes those bindings out — the refactoring people reach for before a
|
||||
port list diverges, and the one the ports engine already refuses to edit
|
||||
around (`add`/`remove` warn and leave `.*` sites alone; `propagate`
|
||||
declines a wildcard site).
|
||||
|
||||
- **Engine** (`vlog_refactor::ports`, new `expand.rs` beside
|
||||
`propagate.rs` — the closest sibling: it already computes "the ports the
|
||||
instantiation does not name" from the instantiated module's declaration):
|
||||
`expand_wildcard(files, file, offset) -> Result<RefactorEdit, String>`.
|
||||
At the cursor's instantiation: refuse unless the connection list holds a
|
||||
`.*`; take the instantiated module's port list (through `Scope`, the
|
||||
fan-out reader `propagate` uses); for every port not explicitly
|
||||
connected, emit `.name(name)` when a signal `name` is declared in the
|
||||
instantiating scope (the wildcard's own rule: same name, in scope, any
|
||||
kind — net, var, port, parameter is *not* a signal); a port with no
|
||||
same-named signal in scope is what the wildcard would have left
|
||||
unconnected → emit `.name()` and a warning naming it (the compiler
|
||||
would have errored; saying so is the point of the expansion). Replace the
|
||||
`.*` token with the generated connections in the port's declaration
|
||||
order, one per line when the list is already multi-line, inline
|
||||
otherwise — then let the formatter's verified splice do the layout
|
||||
(the ports engine's lexical splice + "the file still parses" rule,
|
||||
README §"How an edit is made"). The `.*` element's comments (before/after
|
||||
slots) go on the first generated connection.
|
||||
- **Refusals** (the verifier's whole-edit rule): the instantiated module
|
||||
unknown or declared twice; a parse diagnostic in either file; a port
|
||||
list carrying compiler directives (`ListDirective` — the same refusal
|
||||
`instantiation_plan` makes); an instance with more than one `.*` (illegal);
|
||||
a `.*` inside a `bind` directive (out of scope, say so).
|
||||
- **Server:** a code action `lucisv: expand .* (N connections)` offered at
|
||||
a `.*` under the cursor, through the lazy offer path (§37.1: the offer
|
||||
reads the buffer + the declaration, `resolve` computes the edit); a
|
||||
command `lucisv.expandWildcard [uri, position]` for clients without
|
||||
code actions; the VS Code extension needs nothing new (commands are
|
||||
discovered). Title count from the plan.
|
||||
- Tests: engine — a three-port module with one explicit and `.*`; all
|
||||
ports present in scope; one missing (`.name()` + warning); a port whose
|
||||
same-named signal is a *parameter* (not bound — pin per the LRM);
|
||||
nested/generate instantiation; multi-line vs inline lists; comments on
|
||||
the `.*`; the five refusals; idempotency of the result (formatting the
|
||||
edited file changes nothing further); the formatter's byte contract on
|
||||
three corpus files edited in a scratch copy. Server — offer + resolve
|
||||
over the wire; the command; opentitan read-only: count the `.*` sites
|
||||
under `hw/ip` and expand ten of them into scratch copies, each result
|
||||
formatting cleanly and parsing with the same instance count.
|
||||
|
||||
- [x] 50.1 `expand_wildcard` engine + refusals
|
||||
- [x] 50.2 code action (lazy) + command
|
||||
- [x] docs: feature README; README/site rows (lead applies); §8 line
|
||||
annotated
|
||||
- [x] Gates (guarded); byte-identity vs 0.45.0
|
||||
- [x] QA: the LRM rule attacked (kinds, scopes, generate, parameters);
|
||||
refusals; ten opentitan sites in scratch copies
|
||||
|
||||
## 51. Non-ANSI → ANSI port conversion (planned 2026-09-05) — the second §8 refactoring
|
||||
|
||||
One lane after §50 merges, §36's protocol. Feature README:
|
||||
`docs/features/ansi-conversion/README.md`. Ships in 0.46.0.
|
||||
|
||||
A Verilog-2001 header `module m (a, b, c);` with body declarations
|
||||
`input a; output [7:0] b; inout c;` (and optionally `reg b;` beside the
|
||||
`output`) becomes `module m (input a, output reg [7:0] b, inout c);` with
|
||||
the body declarations removed. The ports engine already edits headers of
|
||||
both shapes (`ports/add.rs::header_edits`: the ANSI list, the non-ANSI
|
||||
list plus the body declaration) and its lexical splice + "the file still
|
||||
parses" verifier is the safety net; this is the whole-header version.
|
||||
|
||||
- **Engine** (`vlog_refactor::ports`, new `ansi.rs`):
|
||||
`convert_to_ansi(files, file, offset) -> Result<RefactorEdit, String>` on
|
||||
a module whose header is `PortList::NonAnsi`. For each header name in
|
||||
header order: find its body `PortDecl` (direction, net type or `reg`/
|
||||
`logic`, signing, packed dims — from the port declaration and, when a
|
||||
separate `reg`/`wire`/`logic` declaration of the same name exists, its
|
||||
type merged per IEEE 1800 §23.2.2.2: `output [7:0] b; reg [7:0] b;` →
|
||||
`output reg [7:0] b`); emit the ANSI port; delete the body declarations
|
||||
it absorbed (whole items, with their trailing comments moved onto the
|
||||
ANSI port's slot — comments are never dropped). Leading comments of a
|
||||
body declaration go before the ANSI port on its own line if the list is
|
||||
multi-line, else are the reason to refuse (say so).
|
||||
- **Refusals:** a header name with no body declaration (an implicit port —
|
||||
illegal); a body declaration for a name not in the header; a port
|
||||
declared twice; a non-ANSI port whose header entry is an expression or
|
||||
concatenation (`.a({x,y})`, `{x,y}` — §23.2.2.1 port expressions: refuse
|
||||
with the reason); a `PortDecl` with an unpacked dimension differing from
|
||||
its variable declaration; any compiler directive in the header or in an
|
||||
absorbed declaration; a body declaration inside a generate or
|
||||
conditional region; an `interface`/`program` (out of scope in this
|
||||
round, say so); the module declared twice in the workspace (the port
|
||||
engine's own rule); a parse diagnostic in the file.
|
||||
- **Server:** code action `lucisv: convert ports to ANSI (N ports)` offered
|
||||
with the cursor anywhere in a non-ANSI module's header, lazy per §37.1;
|
||||
command `lucisv.convertToAnsi [uri, position]`.
|
||||
- Tests: engine — the LRM examples of §23.2.2.2 (each merge rule), a
|
||||
header with 20 ports and mixed declarations, comments on every absorbed
|
||||
declaration (all kept, positions pinned), `reg` and `logic` and `wire`
|
||||
variants, signed, packed dims, a `parameter` between the declarations
|
||||
(untouched), every refusal, idempotency (the result formats unchanged;
|
||||
re-running the action refuses because the header is ANSI); the corpus:
|
||||
count non-ANSI modules (`PortList::NonAnsi`) and convert every one in a
|
||||
scratch copy — each result parses, formats, and has the same port names
|
||||
in the same order (a census assertion, not a byte one). Server — offer +
|
||||
resolve over the wire; the command; opentitan read-only: the count of
|
||||
non-ANSI modules under `hw/vendor` and ten conversions into scratch
|
||||
copies.
|
||||
|
||||
- [x] 51.1 `convert_to_ansi` engine + refusals — `ports/ansi.rs` (the planner)
|
||||
plus `ports/merge.rs` (IEEE 1800 §23.2.2.2), 23 refusals, each a sentence
|
||||
- [x] 51.2 code action (lazy) + command — the fourth `port_actions` offer, so
|
||||
both offer paths get it; `lucisv.convertToAnsi` is the fifth command
|
||||
- [x] docs: feature README; README/site rows (lead applies); §8 line
|
||||
annotated
|
||||
- [x] Gates (guarded); byte-identity vs 0.45.0; the corpus conversion census
|
||||
— **zero non-ANSI headers in corpus/ and in all of OpenTitan**, so the
|
||||
acceptance material is real ANSI headers made non-ANSI and converted
|
||||
back: 5 in the shipped suite, 290 verified under `hw/ip`
|
||||
- [x] QA: every §23.2.2.2 merge rule attacked; comments; refusals; the
|
||||
corpus census re-derived; opentitan scratch conversions — verdict
|
||||
REWORK, two findings in `docs/features/ansi-conversion/README.md`'s
|
||||
QA log (V-1: `comments_kept` forgives a duplicated *untouched*
|
||||
comment, no attack test; V-2: an attribute on an absorbed
|
||||
declaration is silently dropped)
|
||||
|
||||
## 52. Organize imports (planned 2026-09-05) — the third §8 refactoring
|
||||
|
||||
One lane after 0.46.0, §36's protocol. Feature README:
|
||||
`docs/features/organize-imports/README.md`. Ships in 0.47.0 with §53.
|
||||
|
||||
`import pkg::*;` / `import pkg::item;` items accumulate at the top of a
|
||||
module, package, class or compilation unit. "Organize" does what Pylance's
|
||||
does: remove the imports nothing uses, merge exact duplicates, and sort the
|
||||
contiguous run at the scope's top — package name, then item, `*` first
|
||||
within one package — keeping every comment. The same computation is a
|
||||
lint rule, `unused-import` (Style, default off; safe fix = the removal),
|
||||
so the editor squiggles what the action would delete.
|
||||
|
||||
- **What "used" means (the whole risk).** An import `p::*` in scope S is
|
||||
used when some reference in S or a scope nested in S resolves to a
|
||||
member of `p` *through that import* — i.e. the name is not declared
|
||||
locally between the reference and S, and `p` exports it (same-file
|
||||
package: the binder's own tables; cross-file: the index's member table
|
||||
for `p`, including §48's re-exports). `p::x` is used when `x` is
|
||||
referenced that way. A qualified use `p::y` does NOT use the import.
|
||||
**Refuse to judge — never remove — when `p` is unknown to the index
|
||||
(not indexed, or in an unindexed scope), when `p` is declared twice,
|
||||
when S or any nested scope contains a macro call or a conditional
|
||||
directive (a name may live in text lucisv did not read), when S is a
|
||||
class with a base class outside the file (an inherited member could be
|
||||
the use), or when the file has a parse diagnostic.** The verifier's
|
||||
resolution check is the second net: after the edit every reference in
|
||||
the file must resolve to what it resolved to before (that is what the
|
||||
ports engine's `verify_splice` already asserts — reuse it).
|
||||
- **Engine** (`vlog_refactor`, new `imports.rs` + `imports/` if it grows):
|
||||
`organize_imports(files, file, offset) -> Result<RefactorEdit, String>`
|
||||
for the scope at the cursor (the innermost module/package/class/unit),
|
||||
and `unused_imports(files, file) -> Vec<(TextRange, reason)>` for the
|
||||
rule. Edits: deletions of whole `import` items (with their line) and
|
||||
one replacement for the sorted run; an import that carries a comment
|
||||
is never deleted (refuse with a sentence: "delete the comment first")
|
||||
and is sorted with its comment attached (the `pieces` rule of §51's
|
||||
verifier). Exact duplicates keep the first.
|
||||
- **Rule** `unused-import` in `vlog_linter` (Style, default off; option
|
||||
none), reading the same engine function through the project-facts
|
||||
oracle the semantic rules use (`ctx.mentioned_elsewhere`-style —
|
||||
whatever gives the index's member table; if the linter cannot reach it
|
||||
in single-file mode, the rule is silent there, as `unused-signal` is).
|
||||
Safe fix: delete the item. Docs row + toggle regenerated.
|
||||
- **Server:** code action `lucisv: organize imports (removes N, sorts M)`
|
||||
on a cursor in an import run or the scope header (lazy per §37.1),
|
||||
`source.organizeImports` kind so editors' organize-on-save wires it;
|
||||
command `lucisv.organizeImports [uri, position]`.
|
||||
- Tests: engine — used/unused for `*` and item forms, same-file and
|
||||
cross-file packages, a re-export chain (§48), a name shadowed locally
|
||||
(import unused), a nested class using the outer scope's import (used),
|
||||
duplicates, sort order with mixed `*`/items, comments on imports (kept,
|
||||
moved with their line, deletion refused), every refusal; the verifier's
|
||||
resolution check catches a wrong removal (an attack pair: remove an
|
||||
import a reference needs → must be refused); idempotency; corpus census
|
||||
over every scope with ≥ 2 imports: organize in a scratch copy, result
|
||||
parses/formats/converges, resolution counts unchanged, counts of
|
||||
removed/sorted/refused reported. Rule — true positives, near-misses,
|
||||
the census over the corpus with counts. Server — offer/resolve, the
|
||||
`source.organizeImports` kind honoured on `codeAction` with `only`,
|
||||
the command; opentitan read-only: UVM env packages (`hw/ip/*/dv/env/*_pkg.sv`)
|
||||
organized into scratch copies, counts, and every "unused" claim
|
||||
checked by grep for the package's members in the file.
|
||||
|
||||
- [ ] 52.1 engine: used/unused, sort, dedup, refusals
|
||||
- [ ] 52.2 `unused-import` rule + safe fix + toggle
|
||||
- [ ] 52.3 code action (`source.organizeImports`, lazy) + command
|
||||
- [ ] docs; §8 line annotated; README/site rows (lead)
|
||||
- [ ] Gates (guarded); byte-identity vs 0.46.0; corpus census
|
||||
- [ ] QA: every "unused" claim attacked (shadowing, nested scopes,
|
||||
re-exports, macros, directives, unknown packages); the verifier
|
||||
attack pair; opentitan UVM packages
|
||||
@@ -14,7 +14,7 @@ use std::collections::HashSet;
|
||||
|
||||
use lsp_types::CompletionResponse;
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_semantic::{MemberSite, Semantics, SymbolKind, WorkspaceIndex};
|
||||
use vlog_semantic::{MemberSite, Semantics, Surface, SymbolKind, WorkspaceIndex};
|
||||
|
||||
use super::site::balanced;
|
||||
use super::tiers::innermost_scope;
|
||||
@@ -168,6 +168,14 @@ fn members_at(
|
||||
site: &MemberSite,
|
||||
) -> Vec<Member> {
|
||||
let mut members = Members::new();
|
||||
// A cross-file site says which surface its own tail resolution reads, and
|
||||
// the list follows it: behind `u_x.` in an *expression* that is the
|
||||
// module's hierarchical surface — its nets, variables and instances as
|
||||
// well as its ports and parameters — which is exactly what the in-file
|
||||
// `MemberSite::Scope` half above offers for an instance this file
|
||||
// declares. A connection list's `.` never arrives here; it is
|
||||
// `connection_members` below, and it is the connection surface.
|
||||
let mut surface = Surface::Connection;
|
||||
let base = match site {
|
||||
MemberSite::Scope(scope) => {
|
||||
let (scopes, base) = semantics.member_scopes(*scope);
|
||||
@@ -181,10 +189,13 @@ fn members_at(
|
||||
// overlay's own inheritance chase does.
|
||||
base.map(|path| last_segment(&path).to_string())
|
||||
}
|
||||
MemberSite::Unit(unit) => Some(unit.clone()),
|
||||
MemberSite::Unit { path, surface: reads } => {
|
||||
surface = *reads;
|
||||
Some(path.clone())
|
||||
}
|
||||
};
|
||||
if let Some(unit) = base {
|
||||
for (name, def) in index.members_of_chain(&unit) {
|
||||
for (name, def) in index.members_of_chain_in(&unit, surface) {
|
||||
members.push(name, def.kind, indexed_detail(def.kind, def.type_name.as_deref()));
|
||||
}
|
||||
}
|
||||
@@ -983,6 +994,53 @@ endmodule
|
||||
assert_eq!(clk.detail.as_deref(), Some("port"), "table-only across files");
|
||||
}
|
||||
|
||||
/// **§49's completion decision, and its limit.** Behind `u_sub.` in an
|
||||
/// *expression* the list is the module's **hierarchical** surface — its
|
||||
/// nets, its variables and its instances as well as its ports and its
|
||||
/// parameters — because that is what a hierarchical path may name and
|
||||
/// exactly what the tail resolution will find, so every item offered is
|
||||
/// an item hover and go-to-definition answer. Behind the `.` of a
|
||||
/// **connection list** it is the connection surface and nothing more:
|
||||
/// `.internal(w)` is not a legal connection, and an item the resolution
|
||||
/// could not find is a wrong answer rather than a generous one.
|
||||
#[test]
|
||||
fn an_instance_head_lists_the_hierarchical_surface_and_a_connection_list_does_not() {
|
||||
const SUB: &str = "module sub (input logic clk);\n wire internal;\n int counter;\n leaf u_leaf ();\nendmodule\n";
|
||||
let hierarchical = {
|
||||
let tree = Tree::new("hiersurface_expr");
|
||||
tree.write("sub.sv", SUB);
|
||||
tree.write("leaf.sv", "module leaf;\nendmodule\n");
|
||||
let top = "module top;\n sub u_sub ();\n initial y = u_sub.;\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "= u_sub.");
|
||||
let mut found = labels(&items(completions(&ws, &uri, position, true)))
|
||||
.iter()
|
||||
.map(|l| l.to_string())
|
||||
.collect::<Vec<_>>();
|
||||
found.sort();
|
||||
found
|
||||
};
|
||||
assert_eq!(
|
||||
hierarchical,
|
||||
vec!["clk", "counter", "internal", "u_leaf"],
|
||||
"the port and the three hierarchical-only members"
|
||||
);
|
||||
|
||||
let connection = {
|
||||
let tree = Tree::new("hiersurface_conn");
|
||||
tree.write("sub.sv", SUB);
|
||||
tree.write("leaf.sv", "module leaf;\nendmodule\n");
|
||||
let top = "module top;\n sub u_sub (\n .\n );\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, " .");
|
||||
let mut found = labels(&items(completions(&ws, &uri, position, true)))
|
||||
.iter()
|
||||
.map(|l| l.to_string())
|
||||
.collect::<Vec<_>>();
|
||||
found.sort();
|
||||
found
|
||||
};
|
||||
assert_eq!(connection, vec!["clk"], "the connection list is the port list, unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_instance_lists_its_ports_too() {
|
||||
let tree = Tree::new("ifaceconn");
|
||||
|
||||
@@ -552,6 +552,51 @@ mod tests {
|
||||
assert_eq!(locations[0].range.start.line, 1);
|
||||
}
|
||||
|
||||
/// A qualified type name is two references, each addressable on its own
|
||||
/// half: the parser spans `pkg::t` and `DataType::segments` splits it, so
|
||||
/// F12 on the *item* lands on the typedef rather than on the package.
|
||||
#[test]
|
||||
fn a_scoped_type_name_jumps_from_its_item_half() {
|
||||
let text = "\
|
||||
package pkg;
|
||||
typedef logic [1:0] t;
|
||||
endpackage
|
||||
module m;
|
||||
pkg::t x;
|
||||
endmodule
|
||||
";
|
||||
let (ws, uri) = document(text);
|
||||
let item = definition(&ws, &uri, at(text, "pkg::t x") + 5);
|
||||
assert_eq!(item.len(), 1, "the typedef");
|
||||
assert_eq!(item[0].range.start.line, 1, "the `typedef ... t;` line");
|
||||
assert_eq!(item[0].range.start.character, 22, "the name `t`, not the keyword");
|
||||
let unit = definition(&ws, &uri, at(text, "pkg::t x"));
|
||||
assert_eq!(unit.len(), 1, "the package");
|
||||
assert_eq!(unit[0].range.start.line, 0);
|
||||
}
|
||||
|
||||
/// `bus_if.mp bus` — the interface is the type, so the head range is what
|
||||
/// F12 answers from; the modport tail is a member of it.
|
||||
#[test]
|
||||
fn an_interface_port_type_jumps_from_its_head() {
|
||||
let text = "\
|
||||
interface bus_if;
|
||||
logic clk;
|
||||
modport mp (input clk);
|
||||
endinterface
|
||||
module m (bus_if.mp bus);
|
||||
endmodule
|
||||
";
|
||||
let (ws, uri) = document(text);
|
||||
let head = definition(&ws, &uri, at(text, "bus_if.mp bus") + 2);
|
||||
assert_eq!(head.len(), 1, "the interface");
|
||||
assert_eq!(head[0].range.start.line, 0);
|
||||
assert_eq!(head[0].range.start.character, 10, "the interface name");
|
||||
let tail = definition(&ws, &uri, at(text, "bus_if.mp bus") + 7);
|
||||
assert_eq!(tail.len(), 1, "the modport");
|
||||
assert_eq!(tail[0].range.start.line, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_use_jumps_to_its_define_in_the_same_file() {
|
||||
let text = "`define WIDTH 8\nmodule m;\n logic [`WIDTH-1:0] a;\nendmodule\n";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The port refactorings on the wire: `textDocument/codeAction` for the two
|
||||
//! that need no typing, and `workspace/executeCommand` for all three.
|
||||
//! The port refactorings on the wire: `textDocument/codeAction` for the four
|
||||
//! that need no typing, and `workspace/executeCommand` for all five.
|
||||
//!
|
||||
//! Protocol only. Every edit is computed by `vlog_refactor` over the same file
|
||||
//! set the workspace index was built from; this module turns the result into a
|
||||
@@ -8,9 +8,10 @@
|
||||
//!
|
||||
//! **Why commands as well as code actions.** Adding a port needs a
|
||||
//! declaration typed by the user, and a code action carries no input — so
|
||||
//! `lucisv.addPort` is the API a UI calls once it has asked. `lucisv.removePort`
|
||||
//! and `lucisv.propagatePorts` take a position and exist for the same reason a
|
||||
//! Vim user has no lightbulb: a command works everywhere a keybinding does.
|
||||
//! `lucisv.addPort` is the API a UI calls once it has asked. `lucisv.removePort`,
|
||||
//! `lucisv.propagatePorts`, `lucisv.expandWildcard` and `lucisv.convertToAnsi`
|
||||
//! take a position and exist for the same reason a Vim user has no lightbulb:
|
||||
//! a command works everywhere a keybinding does.
|
||||
//! See `docs/features/refactor-ports/README.md`.
|
||||
//!
|
||||
//! **Two shapes of code action.** A client that can resolve is *offered*
|
||||
@@ -48,10 +49,20 @@ pub const ADD_PORT: &str = "lucisv.addPort";
|
||||
pub const REMOVE_PORT: &str = "lucisv.removePort";
|
||||
/// Connect an instantiation's missing ports: `[uri, position]`.
|
||||
pub const PROPAGATE_PORTS: &str = "lucisv.propagatePorts";
|
||||
/// Write out the `.*` at a position: `[uri, position]`.
|
||||
pub const EXPAND_WILDCARD: &str = "lucisv.expandWildcard";
|
||||
/// Rewrite the non-ANSI header at a position ANSI-style: `[uri, position]`.
|
||||
pub const CONVERT_TO_ANSI: &str = "lucisv.convertToAnsi";
|
||||
|
||||
/// Every command this server executes.
|
||||
pub fn commands() -> Vec<String> {
|
||||
vec![ADD_PORT.to_string(), REMOVE_PORT.to_string(), PROPAGATE_PORTS.to_string()]
|
||||
vec![
|
||||
ADD_PORT.to_string(),
|
||||
REMOVE_PORT.to_string(),
|
||||
PROPAGATE_PORTS.to_string(),
|
||||
EXPAND_WILDCARD.to_string(),
|
||||
CONVERT_TO_ANSI.to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
/// The port actions available at a position, each carrying its own computed
|
||||
@@ -243,12 +254,21 @@ fn key(title: &str) -> &str {
|
||||
|
||||
/// An offered title with the workspace's own instantiation count in it,
|
||||
/// replacing the one the offer's one or two files could see.
|
||||
///
|
||||
/// Only a title whose count *is* an instantiation census is recounted:
|
||||
/// `lucisv: expand .* (3 connections)` counts the connections one wildcard
|
||||
/// becomes, which the offer's own two files already know exactly and no index
|
||||
/// lookup could improve (`vlog_refactor::is_sites_phrase`).
|
||||
fn counted(ws: &Workspace, title: String, modules: &[String]) -> String {
|
||||
let Some(head) = title.strip_suffix(')').and_then(|head| head.rsplit_once(" (")) else {
|
||||
let Some((head, phrase)) = title.strip_suffix(')').and_then(|head| head.rsplit_once(" ("))
|
||||
else {
|
||||
return title;
|
||||
};
|
||||
if !vlog_refactor::is_sites_phrase(phrase) {
|
||||
return title;
|
||||
}
|
||||
let sites = modules.iter().map(|name| instances_of(ws, name)).sum();
|
||||
format!("{} ({})", head.0, vlog_refactor::sites_phrase(sites))
|
||||
format!("{head} ({})", vlog_refactor::sites_phrase(sites))
|
||||
}
|
||||
|
||||
/// Every instance of `name` the index has seen. An edge is one written
|
||||
@@ -267,7 +287,7 @@ fn declared_twice(ws: &Workspace, name: &str) -> bool {
|
||||
ws.index().units(name).iter().filter(|def| def.kind.is_instantiable()).count() > 1
|
||||
}
|
||||
|
||||
/// Run one of the three commands, or say why it cannot run.
|
||||
/// Run one of the five commands, or say why it cannot run.
|
||||
///
|
||||
/// The answer is the `WorkspaceEdit` to apply plus the engine's warnings. How
|
||||
/// it reaches the editor is `server.rs`'s business: it is pushed as a
|
||||
@@ -313,6 +333,18 @@ pub fn execute(
|
||||
let sources = sources_at(ws, &path, offset);
|
||||
vlog_refactor::propagate_ports(&sources, &path, offset)?
|
||||
}
|
||||
EXPAND_WILDCARD => {
|
||||
let (_, path) = target(ws, arguments.first())?;
|
||||
let offset = position_argument(ws, arguments, EXPAND_WILDCARD)?;
|
||||
let sources = sources_at(ws, &path, offset);
|
||||
vlog_refactor::expand_wildcard(&sources, &path, offset)?
|
||||
}
|
||||
CONVERT_TO_ANSI => {
|
||||
let (_, path) = target(ws, arguments.first())?;
|
||||
let offset = position_argument(ws, arguments, CONVERT_TO_ANSI)?;
|
||||
let sources = sources_at(ws, &path, offset);
|
||||
vlog_refactor::convert_to_ansi(&sources, &path, offset)?
|
||||
}
|
||||
// The instantiation skeleton is not a port refactoring and computes
|
||||
// its own `WorkspaceEdit`, but `server.rs` routes every non-lens
|
||||
// `workspace/executeCommand` through here — this is the one place an
|
||||
@@ -1336,8 +1368,144 @@ mod tests {
|
||||
assert!(message.contains("position"), "{message}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the `.*` expansion (TODO §50)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A workspace whose `top.sv` instantiates `sub` with a wildcard.
|
||||
fn wildcard(tree: &Tree) -> (Workspace, Uri, &'static str) {
|
||||
const TEXT: &str =
|
||||
"module top;\n logic clk, rst;\n sub u_sub (.clk(clk), .*);\nendmodule\n";
|
||||
tree.write("sub.sv", SUB);
|
||||
let top = tree.write("top.sv", TEXT);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&top).expect("uri");
|
||||
ws.set_document(uri.clone(), TEXT.to_string());
|
||||
(ws, uri, TEXT)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_wildcard_takes_a_position() {
|
||||
let tree = Tree::new("expand");
|
||||
let (ws, uri, text) = wildcard(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
serde_json::to_value(Position { line: 2, character: 24 }).expect("position"),
|
||||
];
|
||||
let (edit, warnings) = execute(&ws, EXPAND_WILDCARD, &arguments).expect("expands");
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
let edits = edits_for(&edit, &uri);
|
||||
assert_eq!(edits.len(), 1, "{edits:#?}");
|
||||
assert_eq!(edits[0].new_text, ".rst(rst)");
|
||||
// The range is the `.*` itself, in the client's own coordinates.
|
||||
assert_eq!(edits[0].range.start.character, 24);
|
||||
assert_eq!(edits[0].range.end.character, 26);
|
||||
assert_eq!(&text[text.find(".*").expect("the wildcard")..][..2], ".*");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_wildcard_refuses_where_there_is_no_wildcard() {
|
||||
let tree = Tree::new("expand_none");
|
||||
let (ws, top_uri, _) = opened(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&top_uri).expect("uri"),
|
||||
serde_json::to_value(Position { line: 2, character: 6 }).expect("position"),
|
||||
];
|
||||
let message = execute(&ws, EXPAND_WILDCARD, &arguments).expect_err("no wildcard");
|
||||
assert!(message.contains("writes no `.*` to expand"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_wildcard_action_is_offered_lazily_and_resolves_to_the_eager_edit() {
|
||||
let tree = Tree::new("expand_action");
|
||||
let (ws, uri, text) = wildcard(&tree);
|
||||
let offset = text.find(".*").expect("the wildcard") as u32;
|
||||
|
||||
let lazy = offered(&ws, &uri, offset);
|
||||
assert_eq!(menu(&lazy), menu(&code_actions(&ws, &uri, offset)));
|
||||
// The count is the connections the wildcard becomes, and the index's
|
||||
// instantiation census must not overwrite it.
|
||||
assert_eq!(menu(&lazy)[0].0, "lucisv: expand .* (1 connection)");
|
||||
assert!(only(&lazy).edit.is_none(), "an offer carries no edit");
|
||||
|
||||
let resolved = resolve(&ws, only(&lazy).clone()).expect("edit");
|
||||
assert_eq!(resolved.title, "lucisv: expand .* (1 connection)");
|
||||
assert_eq!(resolved.edit, only(&code_actions(&ws, &uri, offset)).edit);
|
||||
assert_eq!(edits_for(resolved.edit.as_ref().expect("edit"), &uri)[0].new_text, ".rst(rst)");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the non-ANSI → ANSI conversion (TODO §51)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A workspace whose `legacy.sv` writes a Verilog-2001 header.
|
||||
const LEGACY: &str =
|
||||
"module legacy (\n a,\n b\n);\n input a;\n output [7:0] b;\n reg [7:0] b;\nendmodule\n";
|
||||
|
||||
fn legacy(tree: &Tree) -> (Workspace, Uri) {
|
||||
let path = tree.write("legacy.sv", LEGACY);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), LEGACY.to_string());
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_to_ansi_takes_a_position() {
|
||||
let tree = Tree::new("ansi");
|
||||
let (ws, uri) = legacy(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&uri).expect("uri"),
|
||||
// The module's own name — inside the header, and nowhere near a
|
||||
// port declaration.
|
||||
serde_json::to_value(Position { line: 0, character: 8 }).expect("position"),
|
||||
];
|
||||
// Two insertions — the ANSI prefixes — and three deletions: `input a;`,
|
||||
// `output [7:0] b;` and the `reg [7:0] b;` that completed it.
|
||||
let (edit, warnings) = execute(&ws, CONVERT_TO_ANSI, &arguments).expect("converts");
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
let edits = edits_for(&edit, &uri);
|
||||
let written: Vec<&str> = edits.iter().map(|e| e.new_text.as_str()).collect();
|
||||
assert_eq!(written, vec!["input ", "output reg [7:0] ", "", "", ""], "{edits:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_to_ansi_refuses_an_ansi_header() {
|
||||
let tree = Tree::new("ansi_none");
|
||||
let (ws, top_uri, _) = opened(&tree);
|
||||
let arguments = vec![
|
||||
serde_json::to_value(&top_uri).expect("uri"),
|
||||
serde_json::to_value(Position { line: 0, character: 8 }).expect("position"),
|
||||
];
|
||||
let message = execute(&ws, CONVERT_TO_ANSI, &arguments).expect_err("nothing to convert");
|
||||
assert!(message.contains("declares no ports"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ansi_action_is_offered_lazily_and_resolves_to_the_eager_edit() {
|
||||
let tree = Tree::new("ansi_action");
|
||||
let (ws, uri) = legacy(&tree);
|
||||
// The cursor on the module's name: in the header, on no port.
|
||||
let offset = LEGACY.find("legacy (").expect("the name") as u32;
|
||||
|
||||
let lazy = offered(&ws, &uri, offset);
|
||||
assert_eq!(menu(&lazy), menu(&code_actions(&ws, &uri, offset)));
|
||||
assert_eq!(menu(&lazy)[0].0, "lucisv: convert ports to ANSI (2 ports)");
|
||||
assert!(only(&lazy).edit.is_none(), "an offer carries no edit");
|
||||
|
||||
let resolved = resolve(&ws, only(&lazy).clone()).expect("edit");
|
||||
assert_eq!(resolved.title, "lucisv: convert ports to ANSI (2 ports)");
|
||||
assert_eq!(resolved.edit, only(&code_actions(&ws, &uri, offset)).edit);
|
||||
assert_eq!(edits_for(resolved.edit.as_ref().expect("edit"), &uri)[0].new_text, "input ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_list_is_what_the_server_advertises() {
|
||||
assert_eq!(commands(), vec![ADD_PORT, REMOVE_PORT, PROPAGATE_PORTS]);
|
||||
assert_eq!(
|
||||
commands(),
|
||||
vec![ADD_PORT, REMOVE_PORT, PROPAGATE_PORTS, EXPAND_WILDCARD, CONVERT_TO_ANSI]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -795,11 +795,16 @@ mod tests {
|
||||
/// workspace was never consulted), so the file should not even be pulled
|
||||
/// in — and if it were, the rename must still succeed, since no capture is
|
||||
/// possible against a symbol nothing outside that file can see.
|
||||
///
|
||||
/// The symbol is a **function's** local, not a module's net: since
|
||||
/// 2026-09-05 a net is a declaration on the module's hierarchical surface
|
||||
/// and joins the fan-out by that rung (the test below), which would answer
|
||||
/// this one for the wrong reason. A name inside a subprogram body is on
|
||||
/// neither surface, which is what this attack needs.
|
||||
#[test]
|
||||
fn a_local_only_symbol_sharing_the_new_names_spelling_is_not_a_bogus_refusal() {
|
||||
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
|
||||
const LOCAL_ONLY: &str =
|
||||
"module unrelated;\n wire taken_local;\n assign taken_local = 1'b0;\nendmodule\n";
|
||||
const LOCAL_ONLY: &str = "module unrelated;\n function automatic int f();\n int taken_local = 0;\n return taken_local;\n endfunction\nendmodule\n";
|
||||
let tree = Tree::new("fanout_local_only");
|
||||
let files = [("pkg.sv", PKG), ("local.sv", LOCAL_ONLY)];
|
||||
let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]);
|
||||
@@ -816,6 +821,32 @@ mod tests {
|
||||
assert!(edit.edits_for(&tree.path.join("local.sv")).is_empty());
|
||||
}
|
||||
|
||||
/// The rung the hierarchical surface added: a module's internal **net**
|
||||
/// spelled like the new name *is* a declaration the fan-out has to hold,
|
||||
/// because `assign w = u_unrelated.taken_net;` in a fourth file resolves
|
||||
/// to it now. So the file is pulled in — and the rename still succeeds
|
||||
/// and still writes nothing there, because a package name and a net
|
||||
/// inside a module capture nothing of each other.
|
||||
#[test]
|
||||
fn a_module_net_sharing_the_new_names_spelling_joins_the_fan_out_and_refuses_nothing() {
|
||||
const PKG: &str = "package cfg_pkg;\n parameter int DEPTH = 4;\nendpackage\n";
|
||||
const NET_ONLY: &str =
|
||||
"module unrelated;\n wire taken_net;\n assign taken_net = 1'b0;\nendmodule\n";
|
||||
let tree = Tree::new("fanout_hierarchical_net");
|
||||
let files = [("pkg.sv", PKG), ("net.sv", NET_ONLY)];
|
||||
let (ws, _) = tree_with(&tree, &files, &["pkg.sv"]);
|
||||
let path = tree.path.join("pkg.sv");
|
||||
let at = at(PKG, "cfg_pkg;");
|
||||
|
||||
let fan = fan_out(&ws, &path, at, "taken_net");
|
||||
assert!(
|
||||
fan.contains(&tree.path.join("net.sv")),
|
||||
"a net is a hierarchical declaration of its name: {fan:?}"
|
||||
);
|
||||
let edit = same_answer(&ws, &path, at, "taken_net").expect("renames, no capture possible");
|
||||
assert!(edit.edits_for(&tree.path.join("net.sv")).is_empty());
|
||||
}
|
||||
|
||||
/// Attack on the old-name exemption: a shadowing/"unmasking" hunt. Two
|
||||
/// packages, `p_pkg` and `q_pkg`, both export a member spelled the same
|
||||
/// (`shared_name`); a third file imports both, `p_pkg` first, so
|
||||
|
||||
@@ -1521,6 +1521,10 @@ impl Workspace {
|
||||
/// `follow_paths` only ever looks a reference's *own* name up, so a
|
||||
/// set holding every declarer of `N` resolves every reference spelling
|
||||
/// `N` exactly as the whole workspace does;
|
||||
/// * **every file declaring `N` on a module's hierarchical surface**
|
||||
/// ([`WorkspaceIndex::hierarchical_declarations`]) — an internal net
|
||||
/// is not a workspace symbol, and a hierarchical tail in another file
|
||||
/// resolves to one;
|
||||
/// * **every file with a use the index resolved to one of them**
|
||||
/// ([`WorkspaceIndex::references_to`]) — every file a rename can edit,
|
||||
/// and every file whose meaning the verifier could see move;
|
||||
@@ -1604,6 +1608,19 @@ impl Workspace {
|
||||
containers.extend(symbol.container);
|
||||
self.want_declaration(symbol.def, wanted);
|
||||
}
|
||||
// And every declaration of it on a module's **hierarchical** surface,
|
||||
// which `workspace_symbols` deliberately does not list: an internal
|
||||
// net is not a workspace symbol, but `assign w = u_x.sig;` in another
|
||||
// file resolves to one and a rename must edit both ends. Without this
|
||||
// rung the fan-out would hold the file that *names* the net and not
|
||||
// the file that declares it (`docs/features/hierarchical-tail`).
|
||||
for (unit, def) in self.index.hierarchical_declarations(name) {
|
||||
if self.index.references_are_ambiguous(def) {
|
||||
return false;
|
||||
}
|
||||
containers.insert(unit);
|
||||
self.want_declaration(def, wanted);
|
||||
}
|
||||
self.want_sites(name, wanted);
|
||||
self.want_macro_text(name, wanted);
|
||||
for unit in containers {
|
||||
|
||||
@@ -1587,6 +1587,223 @@ fn a_client_that_resolves_is_offered_the_port_action_without_its_edit() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A top whose instantiation of `sub` connects one port and wildcards the
|
||||
/// rest. Line 2, character 24 is the `.*`.
|
||||
const WILDCARD_TOP: &str =
|
||||
"module top;\n logic clk, rst;\n sub u_sub (.clk(clk), .*);\nendmodule\n";
|
||||
|
||||
const LEGACY_TOP: &str =
|
||||
"module legacy (\n a,\n b\n);\n input a;\n output [7:0] b;\n reg [7:0] b;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn the_ansi_conversion_is_offered_resolved_and_commanded_over_the_wire() {
|
||||
// TODO §51 on the wire: the action is offered with the cursor on the
|
||||
// module's own name — anywhere in a non-ANSI header — with the port count
|
||||
// in its title, the resolve hands back the insertions and deletions, and
|
||||
// the command answers with the same edit for a client with no lightbulb.
|
||||
let dir = temp_dir("ansi");
|
||||
let legacy = dir.join("legacy.sv");
|
||||
std::fs::write(&legacy, LEGACY_TOP).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", legacy.display());
|
||||
|
||||
let boot = |id: u32| {
|
||||
[
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"codeAction":{{"resolveSupport":{{"properties":["edit"]}}}}}}}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(LEGACY_TOP).expect("json")
|
||||
)),
|
||||
]
|
||||
.concat()
|
||||
};
|
||||
|
||||
let session = [
|
||||
boot(1),
|
||||
// The cursor on the module's name, which is in the header and on no port.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":0,"character":9}},"end":{{"line":0,"character":9}}}},"context":{{"diagnostics":[]}}}}}}"#
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":3,"method":"workspace/executeCommand","params":{{"command":"lucisv.convertToAnsi","arguments":["{uri}",{{"line":0,"character":9}}]}}}}"#
|
||||
)),
|
||||
// ...and a position inside the body is refused with the engine's sentence.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":4,"method":"workspace/executeCommand","params":{{"command":"lucisv.convertToAnsi","arguments":["{uri}",{{"line":7,"character":9}}]}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
let messages = talk(&session);
|
||||
|
||||
// 1. The command is advertised beside the other four.
|
||||
let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
|
||||
let commands = initialize["result"]["capabilities"]["executeCommandProvider"]["commands"]
|
||||
.as_array()
|
||||
.expect("the commands are listed");
|
||||
assert!(commands.iter().any(|c| c == "lucisv.convertToAnsi"), "{commands:#?}");
|
||||
|
||||
// 2. The offer names the conversion and its port count, with no edit.
|
||||
let actions = messages.iter().find(|m| m["id"] == 2).expect("codeAction response");
|
||||
let offered = actions["result"].as_array().expect("an array of actions");
|
||||
let action = offered
|
||||
.iter()
|
||||
.find(|a| a["kind"] == "refactor.rewrite.lucisv.ports")
|
||||
.unwrap_or_else(|| panic!("no port action in {offered:#?}"));
|
||||
assert_eq!(action["title"], "lucisv: convert ports to ANSI (2 ports)");
|
||||
assert!(action["edit"].is_null(), "an offer carries no edit: {action:#?}");
|
||||
|
||||
// 3. The command answers with the two insertions and the three deletions:
|
||||
// `b`'s port declaration and the `reg` that completed it both go.
|
||||
let converted = messages.iter().find(|m| m["id"] == 3).expect("executeCommand response");
|
||||
let edits = converted["result"]["changes"][&uri].as_array().expect("edits");
|
||||
let written: Vec<&str> = edits.iter().map(|e| e["newText"].as_str().unwrap_or("?")).collect();
|
||||
assert_eq!(written, vec!["input ", "output reg [7:0] ", "", "", ""], "{edits:#?}");
|
||||
assert_eq!(edits[0]["range"]["start"]["line"], 1, "the first port's own line");
|
||||
assert_eq!(edits[0]["range"]["start"], edits[0]["range"]["end"], "an insertion, not a rewrite");
|
||||
|
||||
// 4. ...and a refusal is `RequestFailed` with the engine's own sentence.
|
||||
let refused = messages.iter().find(|m| m["id"] == 4).expect("refusal response");
|
||||
assert_eq!(refused["error"]["code"], -32803, "LSP's RequestFailed");
|
||||
assert!(
|
||||
refused["error"]["message"]
|
||||
.as_str()
|
||||
.is_some_and(|m| m.contains("no module declaration at this position")),
|
||||
"{refused:#?}"
|
||||
);
|
||||
|
||||
// 5. Handing the offered action back resolves it to that same edit.
|
||||
let resolve = [
|
||||
boot(1),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":3,"method":"codeAction/resolve","params":{}}}"#,
|
||||
serde_json::to_string(action).expect("json")
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
let messages = talk(&resolve);
|
||||
let resolved = messages.iter().find(|m| m["id"] == 3).expect("resolve response");
|
||||
let edits = resolved["result"]["edit"]["changes"][&uri]
|
||||
.as_array()
|
||||
.unwrap_or_else(|| panic!("no edit in {resolved:#?}"));
|
||||
assert_eq!(edits[0]["newText"], "input ");
|
||||
assert_eq!(resolved["result"]["title"], "lucisv: convert ports to ANSI (2 ports)");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_wildcard_expansion_is_offered_resolved_and_commanded_over_the_wire() {
|
||||
// TODO §50 on the wire: the action is offered lazily at the `.*` with the
|
||||
// count of connections it becomes (not the instantiation census the other
|
||||
// port titles carry), the resolve hands back the edit, and the command
|
||||
// answers with the same edit for a client with no lightbulb.
|
||||
let dir = temp_dir("wildcard");
|
||||
let sub = dir.join("sub.sv");
|
||||
std::fs::write(&sub, PORTS_SUB).expect("write");
|
||||
let top = dir.join("top.sv");
|
||||
std::fs::write(&top, WILDCARD_TOP).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let top_uri = format!("file://{}", top.display());
|
||||
|
||||
let boot = |id: u32| {
|
||||
[
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"codeAction":{{"resolveSupport":{{"properties":["edit"]}}}}}}}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(WILDCARD_TOP).expect("json")
|
||||
)),
|
||||
]
|
||||
.concat()
|
||||
};
|
||||
|
||||
let session = [
|
||||
boot(1),
|
||||
// The cursor on the `.*` itself.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{top_uri}"}},"range":{{"start":{{"line":2,"character":24}},"end":{{"line":2,"character":24}}}},"context":{{"diagnostics":[]}}}}}}"#
|
||||
)),
|
||||
// ...and the command, which needs no lightbulb at all.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":3,"method":"workspace/executeCommand","params":{{"command":"lucisv.expandWildcard","arguments":["{top_uri}",{{"line":2,"character":24}}]}}}}"#
|
||||
)),
|
||||
// ...and a position with no `.*` is refused with the engine's sentence.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":4,"method":"workspace/executeCommand","params":{{"command":"lucisv.expandWildcard","arguments":["{top_uri}",{{"line":1,"character":4}}]}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
let messages = talk(&session);
|
||||
|
||||
// 1. The command is advertised beside the other three.
|
||||
let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
|
||||
let commands = initialize["result"]["capabilities"]["executeCommandProvider"]["commands"]
|
||||
.as_array()
|
||||
.expect("the commands are listed");
|
||||
assert!(commands.iter().any(|c| c == "lucisv.expandWildcard"), "{commands:#?}");
|
||||
|
||||
// 2. The offer names the wildcard and its connection count, with no edit.
|
||||
let actions = messages.iter().find(|m| m["id"] == 2).expect("codeAction response");
|
||||
let offered = actions["result"].as_array().expect("an array of actions");
|
||||
let action = offered
|
||||
.iter()
|
||||
.find(|a| a["kind"] == "refactor.rewrite.lucisv.ports")
|
||||
.unwrap_or_else(|| panic!("no port action in {offered:#?}"));
|
||||
assert_eq!(action["title"], "lucisv: expand .* (1 connection)");
|
||||
assert!(action["edit"].is_null(), "an offer carries no edit: {action:#?}");
|
||||
|
||||
// 3. The command answers with the edit that replaces the `.*`.
|
||||
let expanded = messages.iter().find(|m| m["id"] == 3).expect("executeCommand response");
|
||||
let edits = expanded["result"]["changes"][&top_uri].as_array().expect("edits");
|
||||
assert_eq!(edits.len(), 1, "{edits:#?}");
|
||||
assert_eq!(edits[0]["newText"], ".rst(rst)");
|
||||
assert_eq!(edits[0]["range"]["start"]["line"], 2);
|
||||
assert_eq!(edits[0]["range"]["start"]["character"], 24, "the `.*` itself is replaced");
|
||||
assert_eq!(edits[0]["range"]["end"]["character"], 26);
|
||||
|
||||
// 4. ...and a refusal is `RequestFailed` with the engine's own sentence.
|
||||
let refused = messages.iter().find(|m| m["id"] == 4).expect("refusal response");
|
||||
assert_eq!(refused["error"]["code"], -32803, "LSP's RequestFailed");
|
||||
assert!(
|
||||
refused["error"]["message"]
|
||||
.as_str()
|
||||
.is_some_and(|m| m.contains("no module instantiation at this position")),
|
||||
"{refused:#?}"
|
||||
);
|
||||
|
||||
// 5. Handing the offered action back resolves it to that same edit.
|
||||
let resolve = [
|
||||
boot(1),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":3,"method":"codeAction/resolve","params":{}}}"#,
|
||||
serde_json::to_string(action).expect("json")
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
let messages = talk(&resolve);
|
||||
let resolved = messages.iter().find(|m| m["id"] == 3).expect("resolve response");
|
||||
let edits = resolved["result"]["edit"]["changes"][&top_uri]
|
||||
.as_array()
|
||||
.unwrap_or_else(|| panic!("no edit in {resolved:#?}"));
|
||||
assert_eq!(edits[0]["newText"], ".rst(rst)");
|
||||
assert_eq!(resolved["result"]["title"], "lucisv: expand .* (1 connection)");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The module hinting pair: a definition worth a skeleton, and a top that is
|
||||
/// half-way through instantiating it.
|
||||
const HINT_SUB: &str = "module hint_sub #(\n parameter int WIDTH = 8\n) (\n input logic clk,\n input logic [WIDTH-1:0] data,\n output logic ready\n);\nendmodule\n";
|
||||
@@ -6405,7 +6622,10 @@ endclass
|
||||
|
||||
/// An instance head: `u.clk_i` where `u` instantiates a module declared in
|
||||
/// another file. The instance's declared type is the module, so the port is
|
||||
/// hovered exactly as a class property is.
|
||||
/// hovered exactly as a class property is — and, since the hierarchical
|
||||
/// surface (2026-09-05), so is `u.internal`: a hierarchical path may name a
|
||||
/// module's internal net, and hover follows the same resolution the rename
|
||||
/// does.
|
||||
#[test]
|
||||
fn an_instance_heads_port_is_hovered_across_files() {
|
||||
let dir = temp_dir("instancehead");
|
||||
@@ -6455,14 +6675,11 @@ fn an_instance_heads_port_is_hovered_across_files() {
|
||||
assert!(port.contains("sub.sv:1"), "the port's own file and line: got {port}");
|
||||
assert!(port.contains("clk_i"), "got {port}");
|
||||
|
||||
// A module exports its ports and parameters and nothing else, so an
|
||||
// internal net of another file answers nothing rather than something —
|
||||
// the round-2 ruling in the feature README.
|
||||
assert!(
|
||||
response(3)["result"].is_null(),
|
||||
"an internal signal is not exported across files: {:#?}",
|
||||
response(3)
|
||||
);
|
||||
// An internal net reached through an instance head is the hierarchical
|
||||
// surface, and it answers with the net's own declaration in its own file.
|
||||
let net = response(3)["result"]["contents"]["value"].as_str().expect("hover markdown");
|
||||
assert!(net.contains("sub.sv:2"), "the net's own file and line: got {net}");
|
||||
assert!(net.contains("wire internal"), "got {net}");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -8167,3 +8384,148 @@ fn an_open_still_publishes_its_diagnostics_with_no_edit_behind_it() {
|
||||
let codes: Vec<&str> = items.iter().filter_map(|d| d["code"].as_str()).collect();
|
||||
assert!(codes.contains(&"no-tabs"), "the open published nothing about the tab: {items:#?}");
|
||||
}
|
||||
|
||||
/// package-reexports (2026-09-05, TODO §48): `export b_pkg::x;` over the real
|
||||
/// wire, in the shape a UVM tree writes it — a package that declares, a
|
||||
/// package that re-exports, and a third file that only ever names the
|
||||
/// re-exporting one.
|
||||
///
|
||||
/// What only an e2e test can settle: that all five capabilities read the same
|
||||
/// re-export edge. Definition and hover land on `b_pkg`'s declaration however
|
||||
/// the name is reached (bare under `import a_pkg::*`, or written out as
|
||||
/// `a_pkg::x`); completion after `a_pkg::` offers it; find-references from
|
||||
/// `x`'s own declaration lists the `export` line **and** the uses through it;
|
||||
/// and a rename edits every one of them, the `export` line's item half
|
||||
/// included. The wildcard forms are here too — `export b_pkg::*;` and
|
||||
/// `export *::*;` beside an `import` — because the walk that follows them is
|
||||
/// the walk definition asks (`docs/features/package-reexports/README.md`).
|
||||
#[test]
|
||||
fn a_name_reached_through_a_package_reexport_is_navigated_listed_and_renamed() {
|
||||
let dir = temp_dir("reexport");
|
||||
let b = dir.join("b_pkg.sv");
|
||||
let b_text = "package b_pkg;\n localparam int x = 8;\n localparam int y = 9;\nendpackage\n";
|
||||
std::fs::write(&b, b_text).expect("write");
|
||||
let a = dir.join("a_pkg.sv");
|
||||
let a_text = "package a_pkg;\n export b_pkg::x;\nendpackage\n";
|
||||
std::fs::write(&a, a_text).expect("write");
|
||||
std::fs::write(dir.join("w_pkg.sv"), "package w_pkg;\n export b_pkg::*;\nendpackage\n")
|
||||
.expect("write");
|
||||
std::fs::write(
|
||||
dir.join("s_pkg.sv"),
|
||||
"package s_pkg;\n import b_pkg::*;\n export *::*;\nendpackage\n",
|
||||
)
|
||||
.expect("write");
|
||||
let top = dir.join("top.sv");
|
||||
let top_text = "\
|
||||
module top;
|
||||
import a_pkg::*;
|
||||
localparam W = x;
|
||||
localparam V = a_pkg::x;
|
||||
localparam Y = w_pkg::y;
|
||||
localparam Z = s_pkg::y;
|
||||
endmodule
|
||||
";
|
||||
std::fs::write(&top, top_text).expect("write");
|
||||
|
||||
let root = format!("file://{}", dir.display());
|
||||
let a_uri = format!("file://{}", a.display());
|
||||
let b_uri = format!("file://{}", b.display());
|
||||
let top_uri = format!("file://{}", top.display());
|
||||
let at = |id: u32, method: &str, line: u32, character: u32| {
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/{method}","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":{line},"character":{character}}}}}}}"#
|
||||
))
|
||||
};
|
||||
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(WIDE_SCOPE),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(top_text).expect("json")
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{b_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(b_text).expect("json")
|
||||
)),
|
||||
// The bare `x`, reached through `import a_pkg::*`.
|
||||
at(2, "definition", 2, 17),
|
||||
// ...and written out as `a_pkg::x`, hovered and completed.
|
||||
at(3, "hover", 3, 24),
|
||||
at(4, "completion", 3, 24),
|
||||
// The two wildcard forms, each in its own package.
|
||||
at(5, "definition", 4, 24),
|
||||
at(6, "definition", 5, 24),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":7,"method":"textDocument/references","params":{{"textDocument":{{"uri":"{b_uri}"}},"position":{{"line":1,"character":17}},"context":{{"includeDeclaration":false}}}}}}"#
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":8,"method":"textDocument/rename","params":{{"textDocument":{{"uri":"{b_uri}"}},"position":{{"line":1,"character":17}},"newName":"addr"}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&session);
|
||||
let response = |id: u32| -> &serde_json::Value {
|
||||
messages
|
||||
.iter()
|
||||
.find(|m| m["id"] == id)
|
||||
.unwrap_or_else(|| panic!("no response {id} in {messages:#?}"))
|
||||
};
|
||||
let jumped_to = |id: u32, line: u64| {
|
||||
let result = &response(id)["result"];
|
||||
let target = result.get("uri").map_or(&result[0], |_| result);
|
||||
assert!(
|
||||
target["uri"].as_str().expect("a uri").ends_with("b_pkg.sv"),
|
||||
"response {id} did not land in the declaring package: {result:#?}"
|
||||
);
|
||||
assert_eq!(target["range"]["start"]["line"], line, "response {id}");
|
||||
};
|
||||
|
||||
jumped_to(2, 1);
|
||||
let hover = response(3)["result"]["contents"]["value"].as_str().expect("hover markdown");
|
||||
assert!(hover.contains("b_pkg.sv:2"), "the declaring file and line: got {hover}");
|
||||
assert!(hover.contains("localparam int x = 8"), "got {hover}");
|
||||
|
||||
let items = response(4)["result"]["items"].as_array().expect("a completion list");
|
||||
let labels: Vec<&str> = items.iter().filter_map(|item| item["label"].as_str()).collect();
|
||||
assert!(labels.contains(&"x"), "the re-exported name is offered: {labels:?}");
|
||||
assert!(!labels.contains(&"y"), "and only what `a_pkg` re-exports: {labels:?}");
|
||||
|
||||
jumped_to(5, 2);
|
||||
jumped_to(6, 2);
|
||||
|
||||
let references = response(7)["result"].as_array().expect("a list");
|
||||
let sites: Vec<(&str, u64)> = references
|
||||
.iter()
|
||||
.map(|site| {
|
||||
let uri = site["uri"].as_str().expect("a uri");
|
||||
(
|
||||
uri.rsplit('/').next().unwrap_or(uri),
|
||||
site["range"]["start"]["line"].as_u64().unwrap_or(u64::MAX),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert!(sites.contains(&("a_pkg.sv", 1)), "the `export` line itself: {sites:?}");
|
||||
assert!(sites.contains(&("top.sv", 2)), "the bare use: {sites:?}");
|
||||
assert!(sites.contains(&("top.sv", 3)), "and the qualified one: {sites:?}");
|
||||
|
||||
let changes = &response(8)["result"]["changes"];
|
||||
assert_eq!(
|
||||
changes[&a_uri].as_array().expect("the export line is rewritten").len(),
|
||||
1,
|
||||
"{changes:#?}"
|
||||
);
|
||||
assert_eq!(changes[&a_uri][0]["newText"], "addr");
|
||||
assert_eq!(changes[&a_uri][0]["range"]["start"]["line"], 1);
|
||||
assert_eq!(changes[&a_uri][0]["range"]["start"]["character"], 16);
|
||||
assert_eq!(changes[&top_uri].as_array().expect("both uses").len(), 2, "{changes:#?}");
|
||||
assert_eq!(changes[&b_uri].as_array().expect("the declaration").len(), 1, "{changes:#?}");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -482,7 +482,7 @@ impl<'a> Fmt<'a> {
|
||||
},
|
||||
StmtKind::Break => concat(vec![text("break"), self.semi(before_semi)]),
|
||||
StmtKind::Continue => concat(vec![text("continue"), self.semi(before_semi)]),
|
||||
StmtKind::Disable(name) => {
|
||||
StmtKind::Disable { name, .. } => {
|
||||
concat(vec![text(format!("disable {}", named(name))), self.semi(before_semi)])
|
||||
}
|
||||
StmtKind::WaitFork => concat(vec![text("wait fork"), self.semi(before_semi)]),
|
||||
|
||||
@@ -58,7 +58,7 @@ impl Rule for DisableStatement {
|
||||
let targets = disableable(ctx.file());
|
||||
let mut out = Vec::new();
|
||||
walk_all_stmts(ctx.file(), &mut |stmt| {
|
||||
let StmtKind::Disable(name) = &stmt.kind else { return };
|
||||
let StmtKind::Disable { name, .. } = &stmt.kind else { return };
|
||||
// `disable fork` is the keyword form, not a label.
|
||||
if name == "fork" || targets.contains(name.as_str()) {
|
||||
return;
|
||||
|
||||
@@ -5,7 +5,10 @@
|
||||
use super::*;
|
||||
|
||||
/// A data type: keyword or user-defined name, plus signing and packed dims.
|
||||
/// `name` may be empty for implicit types (`input [7:0] x`).
|
||||
/// `name` may be empty for implicit types (`input [7:0] x`), and is the whole
|
||||
/// chain a qualified type reference writes: `pkg::item`, `bus_if.mp`.
|
||||
/// [`DataType::name_span`] says where it is written and
|
||||
/// [`DataType::segments`] splits it.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct DataType {
|
||||
/// The `virtual` / `virtual interface` prefix of a virtual interface type
|
||||
@@ -22,6 +25,14 @@ pub struct DataType {
|
||||
/// so a rare field must not widen the common case.
|
||||
pub virt: Option<VirtualKw>,
|
||||
pub name: String,
|
||||
/// Where [`DataType::name`] is written. Read it through
|
||||
/// [`DataType::name_span`], which pairs it with the name's own length.
|
||||
///
|
||||
/// Four bytes rather than a whole [`TextRange`] because they fit in the
|
||||
/// padding this struct already has: an eight-byte span pushes `DataType`
|
||||
/// to 96 and, through [`ExprKind::Type`], every `Expr` to 104, past the
|
||||
/// 96-byte pin in `size_pins`.
|
||||
pub(crate) name_start: u32,
|
||||
/// The rare tail of a type: parameterization or an anonymous aggregate
|
||||
/// body. See [`TypeExtra`]; read it through [`DataType::params`] /
|
||||
/// [`DataType::inline`].
|
||||
@@ -57,6 +68,70 @@ impl DataType {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The byte range [`DataType::name`] occupies: `src[name_span] == name`
|
||||
/// for every name the source spells the way the AST joined it, which is
|
||||
/// every name but the pathological spacings [`DataType::segments`]
|
||||
/// documents. An implicit type has no name, so this is the empty range at
|
||||
/// the position a name would have been written — the same convention an
|
||||
/// unnamed DPI formal's `name_span` uses.
|
||||
pub fn name_span(&self) -> TextRange {
|
||||
TextRange::new(self.name_start, self.name_start.saturating_add(self.name.len() as u32))
|
||||
}
|
||||
|
||||
/// The `::`- and `.`-separated segments of the name — `pkg`, `item` of
|
||||
/// `pkg::item`; `bus_if`, `mp` of `bus_if.mp` — each with the byte range
|
||||
/// it occupies.
|
||||
///
|
||||
/// Derived from [`DataType::name_span`] and the name's own text: the
|
||||
/// construct is never rescanned. So a source that spells the name
|
||||
/// differently from the way the parser joined it — an escaped segment
|
||||
/// terminated by a newline rather than a space, a `bus_if . mp` written
|
||||
/// apart — hands back ranges that do not slice back to their segment.
|
||||
/// A caller that must not mislocate checks the slice and drops the
|
||||
/// segment; `vlog_semantic`'s binder does.
|
||||
pub fn segments(&self) -> impl Iterator<Item = (&str, TextRange)> + '_ {
|
||||
let base = self.name_start;
|
||||
let mut rest = Some((0usize, self.name.as_str()));
|
||||
std::iter::from_fn(move || {
|
||||
let (at, text) = rest.take()?;
|
||||
let (seg, tail) = match separator(text) {
|
||||
Some((i, len)) => (&text[..i], Some((at + i + len, &text[i + len..]))),
|
||||
None => (text, None),
|
||||
};
|
||||
rest = tail;
|
||||
let start = base.saturating_add(at as u32);
|
||||
Some((seg, TextRange::new(start, start.saturating_add(seg.len() as u32))))
|
||||
})
|
||||
.filter(|(seg, _): &(&str, TextRange)| !seg.is_empty())
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the first `::`/`.` that separates two name segments starts, and how
|
||||
/// many bytes it is.
|
||||
///
|
||||
/// An escaped identifier swallows both spellings (`\a.b ::x` is two segments,
|
||||
/// not three), so one that leads the text runs to its terminating whitespace —
|
||||
/// which the parser keeps in the joined name (§29) — before the search for a
|
||||
/// separator begins.
|
||||
fn separator(text: &str) -> Option<(usize, usize)> {
|
||||
let bytes = text.as_bytes();
|
||||
let mut i = 0;
|
||||
if bytes.first() == Some(&b'\\') {
|
||||
while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
|
||||
i += 1;
|
||||
}
|
||||
// The terminator belongs to the segment; anything else is a separator.
|
||||
i = (i + 1).min(bytes.len());
|
||||
}
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b':' if bytes.get(i + 1) == Some(&b':') => return Some((i, 2)),
|
||||
b'.' => return Some((i, 1)),
|
||||
_ => i += 1,
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// What a type carries beyond its name, signing and packed dimensions. A type
|
||||
|
||||
@@ -266,7 +266,14 @@ pub enum StmtKind {
|
||||
},
|
||||
Break,
|
||||
Continue,
|
||||
Disable(String),
|
||||
/// `disable blk;`, `disable fork;` — the label or task the statement
|
||||
/// names, with the range it is written in. A *use*, not a declaration,
|
||||
/// but it is addressable all the same, so it carries a span like every
|
||||
/// other name (`disable fork` spans the `fork` keyword).
|
||||
Disable {
|
||||
name: String,
|
||||
name_span: TextRange,
|
||||
},
|
||||
Directive(RawText),
|
||||
/// Macro invocation used as a statement.
|
||||
MacroStmt(MacroCall),
|
||||
@@ -323,7 +330,7 @@ impl StmtKind {
|
||||
| StmtKind::Return { .. }
|
||||
| StmtKind::Break
|
||||
| StmtKind::Continue
|
||||
| StmtKind::Disable(_)
|
||||
| StmtKind::Disable { .. }
|
||||
| StmtKind::WaitFork
|
||||
| StmtKind::DoWhile { .. } => true,
|
||||
StmtKind::Timing { stmt, .. } => stmt.is_none(),
|
||||
|
||||
@@ -10,14 +10,26 @@ use super::item::MEMBER_QUALIFIERS;
|
||||
use super::*;
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
/// A type with nothing written for it, spanning the empty range at the
|
||||
/// cursor: what a `parameter type T` and an implicit `input [7:0] x`
|
||||
/// both carry. Distinct from [`DataType::default`] only in that its
|
||||
/// `name_span` points at the source rather than at offset zero.
|
||||
pub(super) fn implicit_type(&self) -> DataType {
|
||||
DataType { name_start: self.here(), ..DataType::default() }
|
||||
}
|
||||
|
||||
/// Parse a possibly-implicit data type. Stops before the declarator name.
|
||||
pub(super) fn parse_opt_data_type(&mut self) -> PResult<DataType> {
|
||||
let mut ty = DataType::default();
|
||||
// An implicit type writes no name at all, so its `name_span` is the
|
||||
// empty range where a name would have gone: right here, before
|
||||
// anything of the type has been consumed.
|
||||
let mut ty = self.implicit_type();
|
||||
// `property p(sequence a, property b);` — inside a property's or a
|
||||
// sequence's formal list, and nowhere else, the two keywords name a
|
||||
// formal's *type* (IEEE 1800 §16.8). `untyped` needs no case: it is
|
||||
// an ordinary identifier and already reads as a user-defined type.
|
||||
if self.sva_formals && (self.cur().is_kw("sequence") || self.cur().is_kw("property")) {
|
||||
ty.name_start = self.here();
|
||||
ty.name = self.bump().text;
|
||||
return Ok(ty);
|
||||
}
|
||||
@@ -35,7 +47,9 @@ impl<'a> Parser<'a> {
|
||||
// Glued onto the interface name exactly as an interface *port*'s
|
||||
// modport is, so every consumer still sees one type-name string.
|
||||
if self.at_modport_port() {
|
||||
ty.name = self.parse_modport_port_type()?.name;
|
||||
let head = self.parse_modport_port_type()?;
|
||||
ty.name = head.name;
|
||||
ty.name_start = head.name_start;
|
||||
return Ok(ty);
|
||||
}
|
||||
}
|
||||
@@ -53,18 +67,15 @@ impl<'a> Parser<'a> {
|
||||
return Ok(ty);
|
||||
}
|
||||
if t.kind == TokenKind::Keyword && TYPE_KEYWORDS.contains(&t.text.as_str()) {
|
||||
ty.name_start = self.here();
|
||||
ty.name = self.bump().text;
|
||||
} else if t.kind == TokenKind::Ident {
|
||||
// User-defined type only if what follows still leaves an
|
||||
// identifier for the declarator name.
|
||||
if self.at_typed_declarator() {
|
||||
let mut name = self.expect_ident()?;
|
||||
while self.cur().is_sym("::") {
|
||||
self.bump();
|
||||
let segment = self.expect_ident()?;
|
||||
Self::push_scope_segment(&mut name, &segment);
|
||||
}
|
||||
let (name, span) = self.parse_scoped_name()?;
|
||||
ty.name = name;
|
||||
ty.name_start = span.start;
|
||||
if self.at_type_params() {
|
||||
ty.extra = Some(Box::new(TypeExtra::Params(self.parse_type_params()?)));
|
||||
}
|
||||
@@ -187,7 +198,7 @@ impl<'a> Parser<'a> {
|
||||
// parameter outside the `#( ... )` list
|
||||
// (lossy_valid_to_stream_tb.sv:26). Its default is a type, not a value.
|
||||
let is_type = self.eat_kw("type");
|
||||
let ty = if is_type { DataType::default() } else { self.parse_opt_data_type()? };
|
||||
let ty = if is_type { self.implicit_type() } else { self.parse_opt_data_type()? };
|
||||
let declarators = self.parse_declarator_list(is_type)?;
|
||||
Ok(ParamDecl { kw, after_kw, is_type, ty, declarators })
|
||||
}
|
||||
@@ -474,13 +485,8 @@ impl<'a> Parser<'a> {
|
||||
if !ty.is_implicit() || self.cur().kind != TokenKind::Ident {
|
||||
return Ok(ty);
|
||||
}
|
||||
let mut name = self.expect_ident()?;
|
||||
while self.cur().is_sym("::") {
|
||||
self.bump();
|
||||
let segment = self.expect_ident()?;
|
||||
Self::push_scope_segment(&mut name, &segment);
|
||||
}
|
||||
let mut ty = DataType { name, ..DataType::default() };
|
||||
let (name, span) = self.parse_scoped_name()?;
|
||||
let mut ty = DataType { name, name_start: span.start, ..DataType::default() };
|
||||
if self.at_type_params() {
|
||||
ty.extra = Some(Box::new(TypeExtra::Params(self.parse_type_params()?)));
|
||||
}
|
||||
|
||||
@@ -167,18 +167,21 @@ impl<'a> Parser<'a> {
|
||||
// `disable fork;` kills every process the enclosing `fork`
|
||||
// started; `fork` is a keyword, not a block name.
|
||||
if self.cur().is_kw("fork") {
|
||||
let name_span = self.cur().span;
|
||||
self.bump();
|
||||
self.expect_stmt_semi()?;
|
||||
return Ok(StmtKind::Disable("fork".to_string()));
|
||||
return Ok(StmtKind::Disable { name: "fork".to_string(), name_span });
|
||||
}
|
||||
let start = self.here();
|
||||
let mut name = self.expect_ident()?;
|
||||
while self.cur().is_sym(".") {
|
||||
self.bump();
|
||||
name.push('.');
|
||||
name.push_str(&self.expect_ident()?);
|
||||
}
|
||||
let name_span = self.span_from(start);
|
||||
self.expect_stmt_semi()?;
|
||||
Ok(StmtKind::Disable(name))
|
||||
Ok(StmtKind::Disable { name, name_span })
|
||||
}
|
||||
"wait" => {
|
||||
self.bump();
|
||||
|
||||
@@ -412,7 +412,7 @@ impl<'a> Parser<'a> {
|
||||
meta,
|
||||
kw,
|
||||
after_kw,
|
||||
ty: DataType::default(),
|
||||
ty: self.implicit_type(),
|
||||
is_type: true,
|
||||
before_name,
|
||||
name,
|
||||
@@ -624,12 +624,15 @@ impl<'a> Parser<'a> {
|
||||
|
||||
/// The `bus_if.mp` of an interface port, as its type. The modport is glued
|
||||
/// onto the interface name exactly as a `pkg::` qualifier is, so every
|
||||
/// consumer that prints or scans a type name still sees one string.
|
||||
/// consumer that prints a type name still sees one string;
|
||||
/// [`DataType::segments`] splits it back into its two halves and their
|
||||
/// ranges.
|
||||
pub(super) fn parse_modport_port_type(&mut self) -> PResult<DataType> {
|
||||
let name_start = self.here();
|
||||
let mut name = self.expect_ident()?;
|
||||
self.expect_sym(".")?;
|
||||
name.push('.');
|
||||
name.push_str(&self.expect_ident()?);
|
||||
Ok(DataType { name, ..DataType::default() })
|
||||
Ok(DataType { name, name_start, ..DataType::default() })
|
||||
}
|
||||
}
|
||||
@@ -1011,10 +1011,12 @@ fn check_stmt(src: &str, stmt: &Stmt, parent: TextRange) {
|
||||
check_stmt(src, inner, here);
|
||||
}
|
||||
StmtKind::Import(paths) => check_import_paths(src, paths, here),
|
||||
StmtKind::Disable { name, name_span } => {
|
||||
check_name(src, "disable target", name, *name_span, here)
|
||||
}
|
||||
StmtKind::Break
|
||||
| StmtKind::Continue
|
||||
| StmtKind::WaitFork
|
||||
| StmtKind::Disable(_)
|
||||
| StmtKind::Null
|
||||
| StmtKind::Error(_) => {}
|
||||
StmtKind::Assertion(a) => check_assertion(src, a, here),
|
||||
@@ -1669,3 +1671,117 @@ fn check_constraint_set(src: &str, set: &ConstraintSet, parent: TextRange) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Type-name spans (TODO.md §47)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// Every `DataType` a source file writes, in item order, with the declarator
|
||||
/// it belongs to left behind — enough to reach each construction site by hand.
|
||||
fn module_types(file: &SourceFile) -> Vec<&DataType> {
|
||||
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
|
||||
let mut out = Vec::new();
|
||||
if let PortList::Ansi(ports) = &m.ports {
|
||||
out.extend(ports.iter().filter_map(ListElem::ok).map(|p| &p.ty));
|
||||
}
|
||||
for item in &m.items {
|
||||
match &item.kind {
|
||||
ItemKind::DataDecl(d) => out.push(&d.ty),
|
||||
ItemKind::Typedef(t) => {
|
||||
if let TypedefKind::Alias(ty) = &t.kind {
|
||||
out.push(ty);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_type_name_span_slices_back_to_the_name_as_written() {
|
||||
let src = "\
|
||||
module m (input bus_if.mp bus, input [7:0] raw);
|
||||
typedef pkg_a::state_t alias_t;
|
||||
logic [3:0] plain;
|
||||
my_type_t user;
|
||||
virtual clk_rst_if vif;
|
||||
endmodule
|
||||
";
|
||||
let file = parse_source(src).expect("parse error");
|
||||
let types = module_types(&file);
|
||||
let seen: Vec<&str> = types.iter().map(|ty| slice(src, ty.name_span())).collect();
|
||||
assert_eq!(seen, ["bus_if.mp", "", "pkg_a::state_t", "logic", "my_type_t", "clk_rst_if"]);
|
||||
for ty in &types {
|
||||
assert_eq!(slice(src, ty.name_span()), ty.name, "a type-name span moved off its name");
|
||||
}
|
||||
|
||||
// The implicit `input [7:0] raw` has no name, so its span is the empty
|
||||
// range where one would have been written — at the `[`.
|
||||
let implicit = types[1].name_span();
|
||||
assert!(implicit.is_empty());
|
||||
assert_eq!(&src[implicit.start as usize..implicit.start as usize + 1], "[");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn segments_split_a_qualified_type_name_without_rescanning() {
|
||||
let src = "\
|
||||
module m (input bus_if.mp bus);
|
||||
pkg_a::state_t s;
|
||||
logic plain;
|
||||
endmodule
|
||||
";
|
||||
let file = parse_source(src).expect("parse error");
|
||||
let types = module_types(&file);
|
||||
let split = |ty: &DataType| -> Vec<(String, String)> {
|
||||
ty.segments().map(|(seg, span)| (seg.to_string(), slice(src, span).to_string())).collect()
|
||||
};
|
||||
assert_eq!(split(types[0]), [("bus_if".into(), "bus_if".into()), ("mp".into(), "mp".into())]);
|
||||
assert_eq!(
|
||||
split(types[1]),
|
||||
[("pkg_a".into(), "pkg_a".into()), ("state_t".into(), "state_t".into())]
|
||||
);
|
||||
assert_eq!(split(types[2]), [("logic".to_string(), "logic".to_string())]);
|
||||
|
||||
// An implicit type has no name and so no segments at all.
|
||||
let empty = DataType::default();
|
||||
assert_eq!(empty.segments().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escaped_segment_keeps_its_terminating_space_in_span_and_segment() {
|
||||
// §29: the parser joins `\a+b ::state_t` with the space the escaped
|
||||
// identifier needs, so the joined name is what the source spells and the
|
||||
// first segment carries the terminator.
|
||||
let src = "module m;\n \\a+b ::state_t s;\nendmodule\n";
|
||||
let file = parse_source(src).expect("parse error");
|
||||
let types = module_types(&file);
|
||||
assert_eq!(types[0].name, "\\a+b ::state_t");
|
||||
assert_eq!(slice(src, types[0].name_span()), "\\a+b ::state_t");
|
||||
let segs: Vec<&str> = types[0].segments().map(|(_, span)| slice(src, span)).collect();
|
||||
assert_eq!(segs, ["\\a+b ", "state_t"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_disable_names_its_target_with_a_span() {
|
||||
let src = "\
|
||||
module m;
|
||||
initial begin : blk
|
||||
disable blk;
|
||||
disable fork;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let file = parse_source(src).expect("parse error");
|
||||
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
|
||||
let ItemKind::Initial(outer) = &m.items[0].kind else { panic!("expected an initial") };
|
||||
let StmtKind::Block { stmts, .. } = &outer.kind else { panic!("expected a block") };
|
||||
let targets: Vec<&str> = stmts
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let StmtKind::Disable { name_span, .. } = &s.kind else { panic!("expected a disable") };
|
||||
slice(src, *name_span)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(targets, ["blk", "fork"]);
|
||||
}
|
||||
@@ -8,3 +8,11 @@ description = "Refactorings for Verilog/SystemVerilog, computed from resolved re
|
||||
[dependencies]
|
||||
vlog_parser = { path = "../vlog_parser" }
|
||||
vlog_semantic = { path = "../vlog_semantic" }
|
||||
|
||||
[dev-dependencies]
|
||||
# Tests only, the same arrangement `vlog_linter` uses: the `.*` expansion's
|
||||
# acceptance test asserts that what the refactoring writes is something the
|
||||
# formatter accepts and leaves alone the second time. The library still
|
||||
# depends on vlog_parser + vlog_semantic alone
|
||||
# (`cargo tree -p vlog_refactor -e normal`).
|
||||
vlog_formatter = { path = "../vlog_formatter" }
|
||||
@@ -10,9 +10,9 @@
|
||||
//! [`verify`] is the *rename* contract: the token stream may not change shape
|
||||
//! at all. [`verify_splice`] is the same contract for a refactoring that
|
||||
//! deliberately writes or deletes text (the port ones): the token stream may
|
||||
//! change only by exactly the pieces the edits spell, no comment may be
|
||||
//! deleted, no file may gain a parse error, and every name *outside* the
|
||||
//! edited ranges must still resolve to exactly what it did.
|
||||
//! change only by exactly the pieces the edits spell, no comment and no
|
||||
//! attribute may be deleted, no file may gain a parse error, and every name
|
||||
//! *outside* the edited ranges must still resolve to exactly what it did.
|
||||
//!
|
||||
//! Nothing here touches `vlog_formatter` or its `verify.rs`: this is the same
|
||||
//! contract, kept separately, so the formatter's safety net does not widen.
|
||||
@@ -120,9 +120,11 @@ pub(crate) fn verify(
|
||||
/// in at the edits' positions and nothing else moved. An edit that landed
|
||||
/// in a string, split a token or wrote a `,` into a line comment cannot
|
||||
/// survive it.
|
||||
/// 2. **Comments are never dropped** (CLAUDE.md invariant 3): no deletion may
|
||||
/// cover a comment. A port or connection with a comment on it is refused,
|
||||
/// not silently un-commented.
|
||||
/// 2. **Comments and attributes are never dropped** (CLAUDE.md invariant 3):
|
||||
/// every comment and every `(* ... *)` the file had it still has, and no
|
||||
/// more. A deletion may cover one only when the edits write it back — which
|
||||
/// is how the ANSI conversion moves a body declaration's comment onto the
|
||||
/// port it becomes; see [`never_dropped`].
|
||||
/// 3. **The file still parses**: a touched file may not gain a parse
|
||||
/// diagnostic it did not have.
|
||||
/// 4. **Resolution identity outside the edits.** Every declaration and every
|
||||
@@ -400,22 +402,6 @@ fn pieces_match(
|
||||
display(path)
|
||||
));
|
||||
};
|
||||
// Invariant 3, checked here rather than trusted to the planner: a deletion
|
||||
// that covers a comment would delete it from both sides of this comparison
|
||||
// and pass, so it is refused outright.
|
||||
for (span, piece) in &old {
|
||||
let deleted = edits.iter().any(|e| !e.range.is_empty() && overlaps(e.range, *span));
|
||||
if deleted && matches!(piece, Piece::Comment(_)) {
|
||||
return Err(format!(
|
||||
"{what} would delete {} in {}; comments are never dropped, so nothing was edited.",
|
||||
piece.describe(),
|
||||
display(path)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let mut expected: Vec<Piece> = Vec::new();
|
||||
let mut next = 0usize;
|
||||
let mut written: Vec<Vec<(TextRange, Piece)>> = Vec::new();
|
||||
for edit in edits {
|
||||
let Some(pieces) = pieces(&edit.new_text) else {
|
||||
@@ -423,6 +409,10 @@ fn pieces_match(
|
||||
};
|
||||
written.push(pieces);
|
||||
}
|
||||
never_dropped(&old, &new, edits, &written, path, what)?;
|
||||
|
||||
let mut expected: Vec<Piece> = Vec::new();
|
||||
let mut next = 0usize;
|
||||
for (span, piece) in old {
|
||||
while let (Some(edit), Some(pieces)) = (edits.get(next), written.get(next)) {
|
||||
if edit.range.start > span.start {
|
||||
@@ -478,6 +468,145 @@ fn pieces_match(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The pieces an edit may never lose, gain or duplicate: a **comment**
|
||||
/// (CLAUDE.md invariant 3) and an **attribute instance** `(* ... *)`.
|
||||
///
|
||||
/// The piece comparison above cannot see either on its own. A piece inside a
|
||||
/// deleted range disappears from *both* sides of it — from `expected`, because
|
||||
/// pieces inside an edit are skipped, and from `actual`, because it is really
|
||||
/// gone — so a dropped comment, or a dropped `(* keep *)`, would pass
|
||||
/// unnoticed. An attribute is a code token rather than trivia, but a deletion
|
||||
/// hides it exactly the way it hides a comment, and losing one changes what a
|
||||
/// synthesizer does; so both are counted here, by exact text.
|
||||
///
|
||||
/// Three equations, over every text that appears on any side. `had` and `has`
|
||||
/// are the file's counts before and after, `gone` counts the old pieces a
|
||||
/// non-empty edit range covers, and `wrote` counts the pieces lexed out of the
|
||||
/// edits' own inserted text.
|
||||
///
|
||||
/// 1. **`has >= had`** — nothing is ever lost. This is the whole of invariant
|
||||
/// 3 and the only half the rule this replaced had.
|
||||
/// 2. **`wrote <= gone`**, unless the text is one a refactoring
|
||||
/// [`generated`] itself — a piece is written back *where it was deleted*,
|
||||
/// and nowhere else. This refuses a planner that takes the comment on
|
||||
/// `input a, b;` and writes it onto *both* ports (one really did, on the
|
||||
/// way — see the work log), and equally one that duplicates the text of a
|
||||
/// comment it never touched.
|
||||
/// 3. **`has == had - gone + wrote`** — the applied text says exactly what the
|
||||
/// edits say. An application that grew a second copy of a comment the edits
|
||||
/// write once is masked corruption the first two equations would forgive.
|
||||
///
|
||||
/// Where each piece now *sits* is the piece comparison's business, not this
|
||||
/// one's; between them a moved comment is verified as exactly as a stationary
|
||||
/// one.
|
||||
fn never_dropped(
|
||||
old: &[(TextRange, Piece)],
|
||||
new: &[(TextRange, Piece)],
|
||||
edits: &[TextEdit],
|
||||
written: &[Vec<(TextRange, Piece)>],
|
||||
path: &Path,
|
||||
what: &str,
|
||||
) -> Result<(), String> {
|
||||
let covered = |span: TextRange| {
|
||||
edits.iter().any(|edit| !edit.range.is_empty() && overlaps(edit.range, span))
|
||||
};
|
||||
let before = tally(old.iter().map(|(_, piece)| piece));
|
||||
let after = tally(new.iter().map(|(_, piece)| piece));
|
||||
let deleted = tally(old.iter().filter(|(span, _)| covered(*span)).map(|(_, piece)| piece));
|
||||
let writes = tally(written.iter().flatten().map(|(_, piece)| piece));
|
||||
|
||||
let mut texts: Vec<&Kept> = before.keys().chain(after.keys()).chain(writes.keys()).collect();
|
||||
texts.sort_unstable();
|
||||
texts.dedup();
|
||||
let count = |tally: &Tally, key: &Kept| tally.get(key).copied().unwrap_or(0);
|
||||
|
||||
// Three passes rather than three tests in one pass, so that the sentence
|
||||
// the user reads is the worst thing wrong with the edit rather than
|
||||
// whichever text sorted first.
|
||||
if let Some(Kept(noun, text)) =
|
||||
texts.iter().find(|key| count(&after, key) < count(&before, key))
|
||||
{
|
||||
return Err(format!(
|
||||
"{what} would delete the {noun} `{text}` in {}; {noun}s are never dropped, so nothing was edited.",
|
||||
display(path)
|
||||
));
|
||||
}
|
||||
if let Some(key) =
|
||||
texts.iter().find(|key| count(&writes, key) > count(&deleted, key) && !generated(&key.1))
|
||||
{
|
||||
let Kept(noun, text) = key;
|
||||
let (gone, wrote) = (count(&deleted, key), count(&writes, key));
|
||||
let deletes = match gone {
|
||||
0 => "without deleting it".to_string(),
|
||||
gone => format!("where it deletes it {}", times(gone)),
|
||||
};
|
||||
return Err(format!(
|
||||
"{what} would write the {noun} `{text}` {} in {} {deletes}; {noun}s are never duplicated, so nothing was edited.",
|
||||
times(wrote),
|
||||
display(path)
|
||||
));
|
||||
}
|
||||
// `deleted` is a subset of `before`, so the subtraction cannot go under —
|
||||
// saturating rather than plain because an arithmetic panic is not a
|
||||
// refusal, and this is a safety net.
|
||||
let accounted =
|
||||
|key: &Kept| count(&before, key).saturating_sub(count(&deleted, key)) + count(&writes, key);
|
||||
if let Some(key) = texts.iter().find(|key| count(&after, key) != accounted(key)) {
|
||||
let Kept(noun, text) = key;
|
||||
return Err(format!(
|
||||
"{what} would leave the {noun} `{text}` in {} {}, where its edits account for it {}; nothing was edited.",
|
||||
display(path),
|
||||
times(count(&after, key)),
|
||||
times(accounted(key))
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One never-dropped piece, keyed for counting: the noun a refusal calls it by
|
||||
/// (`comment` or `attribute`) and its exact text.
|
||||
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
struct Kept(&'static str, String);
|
||||
|
||||
type Tally = HashMap<Kept, usize>;
|
||||
|
||||
/// How many of each never-dropped piece a stream of pieces holds. Every other
|
||||
/// piece is a code token the comparison above already pins position by
|
||||
/// position, so it is not counted here.
|
||||
fn tally<'p>(pieces: impl Iterator<Item = &'p Piece>) -> Tally {
|
||||
let mut out = Tally::new();
|
||||
for piece in pieces {
|
||||
let key = match piece {
|
||||
Piece::Comment(text) => Kept("comment", text.clone()),
|
||||
Piece::Code(TokenKind::Attribute, text) => Kept("attribute", text.clone()),
|
||||
Piece::Code(..) => continue,
|
||||
};
|
||||
*out.entry(key).or_insert(0) += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The comments a refactoring writes itself rather than moves, which it may
|
||||
/// therefore write however many times it needs and even where the file already
|
||||
/// has one. `add_port` and `propagate_ports` both leave
|
||||
/// `/* TODO: connect */` at a connection they cannot name a signal for, and a
|
||||
/// module gains its ports one at a time — so the second addition to a file
|
||||
/// finds the first one's placeholder already sitting there. Everything else a
|
||||
/// refactoring writes has to be a piece it is deleting somewhere else.
|
||||
fn generated(text: &str) -> bool {
|
||||
text == "/* TODO: connect */"
|
||||
}
|
||||
|
||||
/// A count, in prose, so a refusal reads like a sentence.
|
||||
fn times(n: usize) -> String {
|
||||
match n {
|
||||
0 => "never".to_string(),
|
||||
1 => "once".to_string(),
|
||||
2 => "twice".to_string(),
|
||||
n => format!("{n} times"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two byte ranges share a byte. Empty ranges — the insertions —
|
||||
/// overlap nothing: they replace no text, so they delete nothing.
|
||||
fn overlaps(a: TextRange, b: TextRange) -> bool {
|
||||
@@ -777,7 +906,8 @@ mod tests {
|
||||
#[test]
|
||||
fn a_splice_that_also_dropped_a_comment_is_rejected() {
|
||||
let corrupted = apply(PORTS, &add_edits()).replace(" // a", "");
|
||||
assert!(splice_attack(&corrupted).is_err(), "comments are never dropped");
|
||||
let message = splice_attack(&corrupted).expect_err("a dropped comment is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -822,6 +952,267 @@ mod tests {
|
||||
assert!(splice_attack(&corrupted).is_err(), "an unlexable result is a failure, not output");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the moved-comment rule, and the attacks on it (CLAUDE.md invariant 4)
|
||||
// ------------------------------------------------------------------
|
||||
//
|
||||
// 2026-09-05: `comments_kept` replaced "no deletion may cover a comment",
|
||||
// so that `ports::ansi` can move a body declaration's comment onto the
|
||||
// ANSI port that declaration becomes. Every attack below is a crafted
|
||||
// (input, corrupted output) pair the relaxation could plausibly forgive.
|
||||
|
||||
/// A Verilog-2001 header whose two declarations each carry a comment —
|
||||
/// the shape the ANSI conversion has to move a comment out of.
|
||||
const MOVED: &str =
|
||||
"module m (\n a,\n b\n);\n input a; // the note\n output b; // the note\nendmodule\n";
|
||||
|
||||
/// The edits `convert_to_ansi` really produces for `MOVED`.
|
||||
fn move_edits() -> Vec<TextEdit> {
|
||||
let files = vec![(PathBuf::from("/rtl/m.sv"), MOVED.to_string())];
|
||||
let at = MOVED.find("module m").expect("header") as u32;
|
||||
let edit = crate::convert_to_ansi(&files, Path::new("/rtl/m.sv"), at)
|
||||
.expect("the conversion the attacks corrupt");
|
||||
edit.edits.into_iter().next().expect("one file").1
|
||||
}
|
||||
|
||||
fn move_attack(corrupted: &str) -> Result<(), String> {
|
||||
pieces_match(
|
||||
MOVED,
|
||||
corrupted,
|
||||
&move_edits(),
|
||||
Path::new("/rtl/m.sv"),
|
||||
"converting `m`'s ports to ANSI",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_moved_comments_the_engine_actually_writes_verify() {
|
||||
let honest = apply(MOVED, &move_edits());
|
||||
assert_eq!(move_attack(&honest), Ok(()), "the real output must pass");
|
||||
assert_eq!(honest.matches("// the note").count(), 2, "both comments survive: {honest}");
|
||||
assert!(honest.contains("input a, // the note"), "{honest}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_that_kept_only_one_of_two_identical_comments_is_rejected() {
|
||||
// The exact hole the character budget exists for: one of the two
|
||||
// `// the note`s is dropped, and a search for its text still finds
|
||||
// the other one.
|
||||
let corrupted = apply(MOVED, &move_edits()).replacen(" // the note", "", 1);
|
||||
let message = move_attack(&corrupted).expect_err("one comment short is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_that_dropped_a_comment_and_invented_another_is_rejected() {
|
||||
// Same character count, different text: the budget alone would
|
||||
// forgive this one, and the per-comment search does not.
|
||||
let corrupted = apply(MOVED, &move_edits()).replacen("// the note", "// the NOTE", 1);
|
||||
let message = move_attack(&corrupted).expect_err("a rewritten comment is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_that_shortened_a_comment_is_rejected() {
|
||||
let corrupted = apply(MOVED, &move_edits()).replacen("// the note", "// the", 1);
|
||||
let message = move_attack(&corrupted).expect_err("a truncated comment is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_that_left_the_comment_where_it_was_is_rejected() {
|
||||
// The deletion really deleted, but the comment was written back into
|
||||
// the *body* rather than into the header: every comment is still
|
||||
// there, and the piece order is not what the edits promised.
|
||||
let honest = apply(MOVED, &move_edits());
|
||||
let corrupted = honest
|
||||
.replace("input a, // the note", "input a,")
|
||||
.replace("endmodule", "// the note\nendmodule");
|
||||
// `never_dropped` passes this one: every count is equal on both sides
|
||||
// (the comment really was deleted and really was written back once).
|
||||
// The *piece comparison* is the guard, because where a comment lands
|
||||
// is bound to where the edits put it — which is also the answer to
|
||||
// "a comment deleted here and written back somewhere unrelated".
|
||||
let message = move_attack(&corrupted).expect_err("a misplaced comment is a refusal");
|
||||
assert!(message.contains("where the comment `// the note` belongs"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_that_wrote_the_comment_onto_two_ports_is_rejected() {
|
||||
// The bug this half of the rule was added for, reproduced as the edits
|
||||
// that caused it: one declaration declares two ports, and its comment
|
||||
// is written onto *both*. Nothing is dropped, and the piece comparison
|
||||
// cannot object — it checks the edits against themselves, and the
|
||||
// duplicate is in the edits. Only counting the file's comments sees it.
|
||||
const SHARED: &str = "module m (\n a,\n b\n);\n input a, b; // both\nendmodule\n";
|
||||
let at = |needle: &str| SHARED.find(needle).expect(needle) as u32;
|
||||
let (a, b) = (at("\n a,") + 3, at("\n b\n") + 3);
|
||||
let edits = vec![
|
||||
TextEdit { range: TextRange::empty(a), new_text: "input ".into() },
|
||||
TextEdit { range: TextRange::empty(a + 2), new_text: " // both".into() },
|
||||
TextEdit { range: TextRange::empty(b), new_text: "input ".into() },
|
||||
TextEdit { range: TextRange::empty(b + 1), new_text: " // both".into() },
|
||||
TextEdit {
|
||||
range: TextRange::new(at(" input a,"), at("endmodule")),
|
||||
new_text: String::new(),
|
||||
},
|
||||
];
|
||||
let corrupted = apply(SHARED, &edits);
|
||||
assert_eq!(corrupted.matches("// both").count(), 2, "the attack really doubles it");
|
||||
let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
|
||||
.expect_err("a doubled comment is a refusal");
|
||||
assert!(message.contains("would write the comment"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deletion_that_swallows_a_comment_nothing_writes_back_is_still_refused() {
|
||||
// The old rule's own case, restated: no edit writes the comment, so
|
||||
// the relaxation must not reach it.
|
||||
let start = MOVED.find("input a;").expect("a") as u32;
|
||||
let end = MOVED.find("\n output").expect("output") as u32;
|
||||
let edits = vec![TextEdit { range: TextRange::new(start, end), new_text: String::new() }];
|
||||
let corrupted = apply(MOVED, &edits);
|
||||
let message = pieces_match(MOVED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
|
||||
.expect_err("a deleted comment nothing writes back is a refusal");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 2026-09-05 rework: the duplication half, the equation, and attributes
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_insertion_that_duplicates_an_untouched_comment_is_rejected() {
|
||||
// QA's V-1 pair. Nothing deletes — or even overlaps — the body's own
|
||||
// `// shared`, and two pure insertions each write it again. Every
|
||||
// count only grows, so "before is a subset of after" forgives it, and
|
||||
// the piece comparison cannot object because the duplicates are in the
|
||||
// edits. Only `wrote <= gone` sees it.
|
||||
const SHARED: &str =
|
||||
"module m (\n a,\n b\n);\n input a; // shared\n output b;\nendmodule\n";
|
||||
let at = |needle: &str| SHARED.find(needle).expect(needle) as u32;
|
||||
let (a, b) = (at("\n a,") + 4, at("\n b\n") + 4);
|
||||
let edits = vec![
|
||||
TextEdit { range: TextRange::empty(a), new_text: " // shared".into() },
|
||||
TextEdit { range: TextRange::empty(b), new_text: " // shared".into() },
|
||||
];
|
||||
let corrupted = apply(SHARED, &edits);
|
||||
assert_eq!(corrupted.matches("// shared").count(), 3, "the attack really triples it");
|
||||
let message = pieces_match(SHARED, &corrupted, &edits, Path::new("/rtl/m.sv"), "an edit")
|
||||
.expect_err("a duplicated comment is a refusal");
|
||||
assert!(message.contains("comments are never duplicated"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generated_placeholder_may_be_written_where_the_file_already_has_one() {
|
||||
// The whitelist, and the whole of it. `add_port` and
|
||||
// `propagate_ports` write `/* TODO: connect */` themselves, and a
|
||||
// module gains its ports one at a time — so the second addition to a
|
||||
// file finds the first one's placeholder already sitting there and
|
||||
// writes another. `wrote > gone` with nothing deleted, and legitimate.
|
||||
let source = "module top;\n sub u1 (.a(/* TODO: connect */));\nendmodule\n";
|
||||
let at = source.find("))").expect("list") as u32 + 1;
|
||||
let edits = vec![TextEdit {
|
||||
range: TextRange::empty(at),
|
||||
new_text: ", .b(/* TODO: connect */)".into(),
|
||||
}];
|
||||
let spliced = apply(source, &edits);
|
||||
assert_eq!(spliced.matches("TODO").count(), 2, "{spliced}");
|
||||
let outcome =
|
||||
pieces_match(source, &spliced, &edits, Path::new("/rtl/top.sv"), "adding port `b`");
|
||||
assert_eq!(outcome, Ok(()), "a generated placeholder is the engine's own text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_application_that_grew_a_copy_the_edits_do_not_write_is_rejected() {
|
||||
// Masked corruption of the third kind: the edits are honest — they
|
||||
// delete both `// the note`s and write both back — and the *applied*
|
||||
// text carries a third. Neither "nothing is lost" nor "written back
|
||||
// where it was deleted" can see that; only the equation can.
|
||||
let corrupted = apply(MOVED, &move_edits()).replace("endmodule", "// the note\nendmodule");
|
||||
let message = move_attack(&corrupted).expect_err("an invented copy is a refusal");
|
||||
assert!(message.contains("where its edits account for it"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_written_back_inside_a_string_or_another_comment_is_rejected() {
|
||||
// A `//` is only a comment where the lexer says it is. Written back
|
||||
// inside a string literal, or swallowed into the comment next to it,
|
||||
// the text is present in the file and absent from its pieces — which
|
||||
// is exactly the substring search this rule refuses to be.
|
||||
let honest = apply(MOVED, &move_edits());
|
||||
let in_string = honest
|
||||
.replacen(" // the note", "", 1)
|
||||
.replace("endmodule", " initial $display(\"// the note\");\nendmodule");
|
||||
let message = move_attack(&in_string).expect_err("a string is not a comment");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
|
||||
let nested = honest
|
||||
.replacen(" // the note", "", 1)
|
||||
.replace("// the note", "// the note // the note");
|
||||
let message = move_attack(&nested).expect_err("one comment is not two");
|
||||
assert!(message.contains("comments are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
/// A body declaration carrying an attribute instance. `Item.span` covers
|
||||
/// the `(* keep *)`, so a deletion hides it from *both* sides of the piece
|
||||
/// comparison exactly the way it hides a comment — QA's finding V-2.
|
||||
const ATTRIBUTED: &str = "module m (\n a\n);\n (* keep *) input a;\nendmodule\n";
|
||||
|
||||
/// The edits an absorbing conversion of `ATTRIBUTED` makes: `input ` (plus
|
||||
/// whatever `written` says) before the header name, and the whole body
|
||||
/// declaration gone.
|
||||
fn attribute_edits(written: &str) -> Vec<TextEdit> {
|
||||
let at = |needle: &str| ATTRIBUTED.find(needle).expect(needle) as u32;
|
||||
vec![
|
||||
TextEdit { range: TextRange::empty(at("\n a\n") + 3), new_text: written.into() },
|
||||
TextEdit {
|
||||
range: TextRange::new(at(" (* keep *)"), at("endmodule")),
|
||||
new_text: String::new(),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn attribute_attack(edits: &[TextEdit]) -> Result<(), String> {
|
||||
let corrupted = apply(ATTRIBUTED, edits);
|
||||
pieces_match(
|
||||
ATTRIBUTED,
|
||||
&corrupted,
|
||||
edits,
|
||||
Path::new("/rtl/m.sv"),
|
||||
"converting `m`'s ports to ANSI",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deletion_that_swallows_an_attribute_is_rejected() {
|
||||
// The planner refuses this one first (`ports::ansi::attributes_clear`,
|
||||
// pinned in `tests/ansi.rs`); this is the verifier saying so a second
|
||||
// time, from the edits alone, for whatever writes them next.
|
||||
let message = attribute_attack(&attribute_edits("input "))
|
||||
.expect_err("a dropped attribute is a refusal");
|
||||
assert!(message.contains("attributes are never dropped"), "{message}");
|
||||
assert!(message.contains("`(* keep *)`"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_that_moves_an_attribute_verifies() {
|
||||
// What the refusal above is protecting: an edit that really does carry
|
||||
// the attribute over is not what this rule is for.
|
||||
let edits = attribute_edits("(* keep *) input ");
|
||||
assert_eq!(attribute_attack(&edits), Ok(()), "a moved attribute is a kept attribute");
|
||||
assert!(apply(ATTRIBUTED, &edits).contains("(* keep *) input a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_that_rewrote_an_attribute_is_rejected() {
|
||||
// `(* keep *)` and `(* keep=1 *)` are not the same instruction to a
|
||||
// synthesizer, and an attribute is matched by exact text.
|
||||
let message = attribute_attack(&attribute_edits("(* keep=1 *) input "))
|
||||
.expect_err("a rewritten attribute is a refusal");
|
||||
assert!(message.contains("attributes are never dropped"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_splice_that_captures_a_name_outside_the_edit_is_rejected() {
|
||||
// The resolution half: the module already has a net called `cfg`, and
|
||||
|
||||
@@ -315,7 +315,7 @@ fn terminate(out: &mut String, text: &str) {
|
||||
/// the question is exactly whether a `\` survives in the run of characters
|
||||
/// after the last whitespace. Conservative by construction: a false positive
|
||||
/// writes one harmless extra space.
|
||||
fn ends_escaped(text: &str) -> bool {
|
||||
pub(crate) fn ends_escaped(text: &str) -> bool {
|
||||
text.rsplit(char::is_whitespace).next().unwrap_or(text).contains('\\')
|
||||
}
|
||||
|
||||
|
||||
@@ -41,8 +41,9 @@ pub use instantiate::{
|
||||
PlanPort, Site,
|
||||
};
|
||||
pub use ports::{
|
||||
add_port, enclosing_module, may_have_port_action, port_action_modules, port_actions,
|
||||
propagate_ports, remove_port, sites_phrase, ModuleRef, PortAction,
|
||||
add_port, convert_to_ansi, enclosing_module, expand_wildcard, is_sites_phrase,
|
||||
may_have_port_action, port_action_modules, port_actions, propagate_ports, remove_port,
|
||||
sites_phrase, ModuleRef, PortAction,
|
||||
};
|
||||
pub use rename::{
|
||||
contains_word, prepare_rename, prepare_rename_here, rename, rename_name_at, RenameTarget,
|
||||
|
||||
@@ -229,19 +229,19 @@ pub(super) fn element_spans(ports: &[DeclaredPort]) -> Vec<TextRange> {
|
||||
|
||||
/// One compiler directive written inside a port list or a module body, and
|
||||
/// where it is written.
|
||||
struct Directive {
|
||||
text: String,
|
||||
span: TextRange,
|
||||
pub(super) struct Directive {
|
||||
pub(super) text: String,
|
||||
pub(super) span: TextRange,
|
||||
}
|
||||
|
||||
/// What a directive does to the conditional nesting depth.
|
||||
enum Nesting {
|
||||
pub(super) enum Nesting {
|
||||
Open,
|
||||
Close,
|
||||
Neither,
|
||||
}
|
||||
|
||||
fn nesting_of(directive: &str) -> Nesting {
|
||||
pub(super) fn nesting_of(directive: &str) -> Nesting {
|
||||
let word = directive.split_whitespace().next().unwrap_or_default();
|
||||
match word {
|
||||
"`ifdef" | "`ifndef" => Nesting::Open,
|
||||
@@ -264,7 +264,7 @@ fn list_directives(module: &Module) -> Vec<Directive> {
|
||||
/// The directives written among a module's items — where a non-ANSI port
|
||||
/// declaration goes. A macro *item* (`` `ASSERT_INIT(...) ``) is not collected:
|
||||
/// it is a call, not a directive, and cannot open a conditional region.
|
||||
fn body_directives(module: &Module) -> Vec<Directive> {
|
||||
pub(super) fn body_directives(module: &Module) -> Vec<Directive> {
|
||||
module
|
||||
.items
|
||||
.iter()
|
||||
|
||||
@@ -0,0 +1,488 @@
|
||||
//! Converting a Verilog-2001 header to an ANSI one: `module m (a, b);` with
|
||||
//! `input a; output [7:0] b; reg [7:0] b;` in the body becomes
|
||||
//! `module m (input a, output reg [7:0] b);` with the body declarations gone.
|
||||
//!
|
||||
//! **The edit is insertions, never a rewrite of the list.** Each header name
|
||||
//! keeps the bytes it already occupies; what an ANSI port adds is written
|
||||
//! *around* it — the direction, type and packed dimensions just before the
|
||||
//! name, an unpacked dimension just after it. Two things follow from that, and
|
||||
//! both are the reason it is done this way:
|
||||
//!
|
||||
//! * The header's own layout, commas and comments are not touched at all, so a
|
||||
//! one-per-line list stays one per line and a comment written beside a port
|
||||
//! name stays beside it.
|
||||
//! * `Shift::map` maps the port's name span onto exactly the bytes the name
|
||||
//! occupies afterwards, so `check::verify_splice`'s resolution check — which
|
||||
//! requires every reference outside the edits to resolve to the *same*
|
||||
//! declaration, at the same place — passes. A conversion that replaced the
|
||||
//! element wholesale would move the declaration the body's references point
|
||||
//! at, and the verifier would rightly refuse the whole refactoring.
|
||||
//!
|
||||
//! The merge itself is `merge.rs` (IEEE 1800 §23.2.2.2). This file locates the
|
||||
//! module, refuses everything lucisv will not convert, decides where each
|
||||
//! absorbed declaration's comments go, and writes the edits.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use vlog_parser::ast::{
|
||||
GenBlock, GenElse, Item, ItemKind, ListElem, Module, NonAnsiPort, PortList,
|
||||
};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::Comment;
|
||||
use vlog_parser::{parse_source_tolerant, tokenize, LineIndex, ParseDiagnostic};
|
||||
|
||||
use crate::rename::{display, Scope};
|
||||
use crate::TextEdit;
|
||||
|
||||
use super::add::{body_directives, nesting_of, Directive, Nesting};
|
||||
use super::find::{find_module, locate_module, module_at, not_in_scope, ModuleSite};
|
||||
use super::list::{after_same_line_comments, comma_after, insert, line_indent, whole_line};
|
||||
use super::merge::{absorb, Absorbed};
|
||||
use super::{shape, ModuleRef, Plan};
|
||||
|
||||
/// One planned conversion: what to edit, and what the title will promise.
|
||||
pub(super) struct Conversion {
|
||||
pub(super) site: ModuleSite,
|
||||
pub(super) plan: Plan,
|
||||
/// How many ports the header declares — what the code action counts.
|
||||
pub(super) count: usize,
|
||||
}
|
||||
|
||||
pub(super) fn plan_convert(
|
||||
scope: &mut Scope,
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
) -> Result<Conversion, String> {
|
||||
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
||||
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
let mut found = None;
|
||||
module_at(&tree.items, offset, &mut found);
|
||||
let Some(name) = found else {
|
||||
return Err("there is no module declaration at this position.".to_string());
|
||||
};
|
||||
let Some((module, _)) = find_module(&tree, &name) else {
|
||||
return Err(format!("lucisv can no longer find the declaration of `{name}`."));
|
||||
};
|
||||
let ports = header(module)?;
|
||||
unparsed(file, &diagnostics)?;
|
||||
let names = header_names(module, &ports)?;
|
||||
if !module.port_directives.is_empty() {
|
||||
return Err(format!(
|
||||
"`{name}`'s port list carries compiler directives, so which ports it declares depends on the configuration; lucisv does not preprocess, so it made no edits."
|
||||
));
|
||||
}
|
||||
if let Some(hidden) = in_generate(&module.items, &names) {
|
||||
return Err(format!(
|
||||
"`{name}` declares `{hidden}` inside a generate region, where lucisv will not read a port's declaration; it made no edits."
|
||||
));
|
||||
}
|
||||
let site = locate_module(scope, ModuleRef::Name(&name))?;
|
||||
if site.file != i {
|
||||
return Err(format!(
|
||||
"`{name}`'s indexed declaration is in another file than the one under the cursor; lucisv made no edits."
|
||||
));
|
||||
}
|
||||
|
||||
let absorbed = absorb(text, &name, &module.items, &names)?;
|
||||
attributes_clear(&name, &absorbed)?;
|
||||
directives_clear(text, file, module, &absorbed)?;
|
||||
let comments = comments_of(text, file)?;
|
||||
let mut plan = Plan::default();
|
||||
// One declaration may declare several ports (`input a, b;`), and its
|
||||
// comments belong to the first of them: written onto both they would be
|
||||
// duplicated, which is as much a corruption as dropping them.
|
||||
let mut claimed: Vec<TextRange> = Vec::new();
|
||||
for (port, absorbed) in ports.iter().zip(&absorbed) {
|
||||
plan.add(i, port_edits(text, &name, port, absorbed, &comments, &mut claimed)?);
|
||||
}
|
||||
plan.add(i, deletions(text, &name, &absorbed, &comments)?);
|
||||
plan.expected.push((i, shape(text, &name)));
|
||||
Ok(Conversion { site, plan, count: ports.len() })
|
||||
}
|
||||
|
||||
/// The non-ANSI port list this conversion needs, or the sentence saying why
|
||||
/// there is not one.
|
||||
fn header(module: &Module) -> Result<Vec<&NonAnsiPort>, String> {
|
||||
let name = &module.name;
|
||||
if module.kw == "interface" || module.kw == "program" {
|
||||
return Err(format!(
|
||||
"`{name}` is an `{}`, not a module, and lucisv does not convert an {}'s non-ANSI header in this round; it made no edits.",
|
||||
module.kw, module.kw
|
||||
));
|
||||
}
|
||||
let ports = match &module.ports {
|
||||
PortList::NonAnsi(ports) => ports,
|
||||
PortList::Ansi(_) => {
|
||||
return Err(format!(
|
||||
"`{name}`'s header already declares its ports ANSI-style, so there is nothing to convert."
|
||||
))
|
||||
}
|
||||
PortList::Empty | PortList::None => {
|
||||
return Err(format!("`{name}` declares no ports, so there is nothing to convert."))
|
||||
}
|
||||
};
|
||||
if ports.iter().any(ListElem::is_error) {
|
||||
return Err(format!(
|
||||
"`{name}`'s header writes a port expression (IEEE 1800 §23.2.2.1's `.a({{x,y}})` or `{{x,y}}`), which has no ANSI spelling; lucisv made no edits."
|
||||
));
|
||||
}
|
||||
Ok(ports.iter().filter_map(ListElem::ok).collect())
|
||||
}
|
||||
|
||||
/// The header's names in header order, with a repeated one refused: a list
|
||||
/// that names a port twice is not one lucisv will guess at.
|
||||
fn header_names(module: &Module, ports: &[&NonAnsiPort]) -> Result<Vec<String>, String> {
|
||||
let mut names: Vec<String> = Vec::new();
|
||||
for port in ports {
|
||||
if names.contains(&port.name) {
|
||||
return Err(format!(
|
||||
"`{}`'s header names `{}` twice; lucisv will not guess which port that is.",
|
||||
module.name, port.name
|
||||
));
|
||||
}
|
||||
names.push(port.name.clone());
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
/// The refusal a file that does not parse earns. Stricter than the verifier's
|
||||
/// "no *new* diagnostic" rule, and for the same reason the `.*` expansion is:
|
||||
/// a header lucisv misread is a header whose ports it would declare twice.
|
||||
fn unparsed(file: &Path, diagnostics: &[ParseDiagnostic]) -> Result<(), String> {
|
||||
match diagnostics.first() {
|
||||
None => Ok(()),
|
||||
Some(problem) => Err(format!(
|
||||
"{} does not parse ({} at line {}), so lucisv will not convert its ports to ANSI.",
|
||||
display(file),
|
||||
problem.message,
|
||||
problem.line
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A header port declared inside a generate construct is a declaration in
|
||||
/// another scope, which lucisv will not absorb into the header.
|
||||
fn in_generate(items: &[Item], names: &[String]) -> Option<String> {
|
||||
fn walk(items: &[Item], names: &[String], inside: bool, found: &mut Option<String>) {
|
||||
for item in items {
|
||||
match &item.kind {
|
||||
ItemKind::PortDecl(decl) if inside => {
|
||||
named(decl.declarators.iter().map(|d| &d.name), names, found);
|
||||
}
|
||||
ItemKind::DataDecl(decl) if inside => {
|
||||
named(decl.declarators.iter().map(|d| &d.name), names, found);
|
||||
}
|
||||
ItemKind::GenerateRegion { items, .. } => walk(items, names, true, found),
|
||||
ItemKind::GenBlock(block) => walk(&block.items, names, true, found),
|
||||
ItemKind::GenFor(gen) => block(&gen.body, names, found),
|
||||
ItemKind::GenCase(gen) => {
|
||||
for arm in &gen.items {
|
||||
block(&arm.body, names, found);
|
||||
}
|
||||
}
|
||||
ItemKind::GenIf(gen) => {
|
||||
block(&gen.then, names, found);
|
||||
let mut els = gen.els.as_deref();
|
||||
while let Some(next) = els {
|
||||
match next {
|
||||
GenElse::If(_, gen) => {
|
||||
block(&gen.then, names, found);
|
||||
els = gen.els.as_deref();
|
||||
}
|
||||
GenElse::Block(b) => {
|
||||
block(b, names, found);
|
||||
els = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn block(b: &GenBlock, names: &[String], found: &mut Option<String>) {
|
||||
walk(&b.items, names, true, found);
|
||||
}
|
||||
fn named<'a>(
|
||||
declared: impl Iterator<Item = &'a String>,
|
||||
names: &[String],
|
||||
found: &mut Option<String>,
|
||||
) {
|
||||
for name in declared {
|
||||
if found.is_none() && names.contains(name) {
|
||||
*found = Some(name.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut found = None;
|
||||
walk(items, names, false, &mut found);
|
||||
found
|
||||
}
|
||||
|
||||
/// Refuse a declaration that carries an attribute instance.
|
||||
///
|
||||
/// `Item.span` covers the `(* ... *)` written before it, so the deletion takes
|
||||
/// the attribute with the declaration and only the *comments* are carried onto
|
||||
/// the port — a silent loss of something that changes what a synthesizer does.
|
||||
/// Where an attribute belongs in an ANSI port list is a design question rather
|
||||
/// than a merge rule, so the conversion refuses instead of guessing, the same
|
||||
/// way it refuses an initialiser or a qualifier. `check::never_dropped` counts
|
||||
/// attributes too, so a planner that ever misses one is refused a second time.
|
||||
fn attributes_clear(module: &str, absorbed: &[Absorbed<'_>]) -> Result<(), String> {
|
||||
for port in absorbed {
|
||||
for item in &port.items {
|
||||
let Some(attr) = item.meta.attrs.first() else { continue };
|
||||
return Err(format!(
|
||||
"`{}` on `{module}`'s declaration of `{}` would be dropped, and lucisv does not decide where an attribute belongs in an ANSI port list; move the attribute onto the port by hand, and it made no edits.",
|
||||
attr.text.trim(),
|
||||
port.name
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// lucisv does not preprocess, so a declaration it deletes must not be one an
|
||||
/// `` `ifdef`` arm holds, and no directive may stand between the declarations
|
||||
/// it deletes: either way the body it leaves behind is one no configuration
|
||||
/// ever had.
|
||||
fn directives_clear(
|
||||
text: &str,
|
||||
file: &Path,
|
||||
module: &Module,
|
||||
absorbed: &[Absorbed<'_>],
|
||||
) -> Result<(), String> {
|
||||
let directives = body_directives(module);
|
||||
if directives.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let spans: Vec<TextRange> =
|
||||
absorbed.iter().flat_map(|a| a.items.iter().map(|i| i.span)).collect();
|
||||
let (Some(first), Some(last)) =
|
||||
(spans.iter().map(|span| span.start).min(), spans.iter().map(|span| span.end).max())
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let region = format!("`{}`'s body", module.name);
|
||||
for span in &spans {
|
||||
depth_zero(&directives, span.start, ®ion)?;
|
||||
}
|
||||
match directives.iter().find(|d| d.span.start >= first && d.span.start < last) {
|
||||
None => Ok(()),
|
||||
Some(directive) => Err(format!(
|
||||
"a compiler directive (`{}` at {}:{}) is written among the declarations converting `{}` would delete, so lucisv does not know what the body it leaves behind would say; it made no edits.",
|
||||
directive.text.trim().lines().next().unwrap_or_default().trim_end(),
|
||||
display(file),
|
||||
LineIndex::new(text).line_col(directive.span.start).0,
|
||||
module.name
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuse a declaration that stands inside a conditional arm.
|
||||
fn depth_zero(directives: &[Directive], at: u32, region: &str) -> Result<(), String> {
|
||||
let mut depth = 0i32;
|
||||
for directive in directives.iter().filter(|d| d.span.start < at) {
|
||||
match nesting_of(&directive.text) {
|
||||
Nesting::Open => depth += 1,
|
||||
Nesting::Close => depth -= 1,
|
||||
Nesting::Neither => {}
|
||||
}
|
||||
}
|
||||
match depth {
|
||||
0 => Ok(()),
|
||||
_ => Err(format!(
|
||||
"{region} is conditionally compiled, and one of the declarations the conversion would delete stands inside an `ifdef arm; a port declared in one arm does not exist in the other, so lucisv made no edits."
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every comment in the file, with the bytes it occupies — the same pieces
|
||||
/// `check::pieces` reads, so a comment this file moves is a comment the
|
||||
/// verifier can account for.
|
||||
fn comments_of(text: &str, file: &Path) -> Result<Vec<(TextRange, String)>, String> {
|
||||
let Ok(tokens) = tokenize(text) else {
|
||||
return Err(format!("{} does not lex, so lucisv will not edit it.", display(file)));
|
||||
};
|
||||
let mut out: Vec<(TextRange, String)> = Vec::new();
|
||||
let mut push = |comment: &Comment| out.push((comment.span, comment.text.clone()));
|
||||
for token in &tokens {
|
||||
token.leading.iter().for_each(&mut push);
|
||||
if let Some(trailing) = &token.trailing {
|
||||
push(trailing);
|
||||
}
|
||||
}
|
||||
out.sort_by_key(|(span, _)| (span.start, span.end));
|
||||
out.dedup_by_key(|(span, _)| *span);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The comments one absorbed declaration carries, and the bytes a deletion
|
||||
/// must therefore cover.
|
||||
#[derive(Default)]
|
||||
struct Carried {
|
||||
before: Vec<String>,
|
||||
after: Vec<String>,
|
||||
}
|
||||
|
||||
/// What one body item takes with it: its own bytes plus the comments written
|
||||
/// before and after it, which move onto the ANSI port.
|
||||
fn carried(
|
||||
text: &str,
|
||||
module: &str,
|
||||
item: &Item,
|
||||
comments: &[(TextRange, String)],
|
||||
) -> Result<(TextRange, Carried), String> {
|
||||
let start = item.meta.leading.first().map_or(item.span.start, |c| c.span.start);
|
||||
let end = item.meta.trailing.as_ref().map_or(item.span.end, |c| c.span.end);
|
||||
let mut carried = Carried::default();
|
||||
for (span, comment) in
|
||||
comments.iter().filter(|(span, _)| span.start >= start && span.end <= end)
|
||||
{
|
||||
if span.start >= item.span.start && span.end <= item.span.end {
|
||||
return Err(format!(
|
||||
"`{module}` writes the comment `{comment}` inside a declaration the conversion would delete, and lucisv will not decide where a comment written inside a declaration goes in an ANSI port; it made no edits."
|
||||
));
|
||||
}
|
||||
match span.end <= item.span.start {
|
||||
true => carried.before.push(comment.clone()),
|
||||
false => carried.after.push(comment.clone()),
|
||||
}
|
||||
}
|
||||
Ok((whole_line(text, TextRange::new(start, end)), carried))
|
||||
}
|
||||
|
||||
/// The insertions that turn one header name into an ANSI port declaration.
|
||||
///
|
||||
/// The comments the absorbed declarations carried go in one of two places.
|
||||
/// The first choice, for a comment written *after* a declaration, is the end
|
||||
/// of the port's own line — where the source had it, relative to what it
|
||||
/// describes. That is only free when nothing else is written there and the
|
||||
/// header wrote no comment of its own beside the port, and there is exactly
|
||||
/// one of them. Everything else goes on its own line above the port, which
|
||||
/// always works for a list written one port per line; a list written on one
|
||||
/// line takes a block comment inline and refuses a `//`.
|
||||
fn port_edits(
|
||||
text: &str,
|
||||
module: &str,
|
||||
port: &NonAnsiPort,
|
||||
absorbed: &Absorbed<'_>,
|
||||
comments: &[(TextRange, String)],
|
||||
claimed: &mut Vec<TextRange>,
|
||||
) -> Result<Vec<TextEdit>, String> {
|
||||
let mut moved = Carried::default();
|
||||
for item in &absorbed.items {
|
||||
let (_, carried) = carried(text, module, item, comments)?;
|
||||
// A declaration this port shares with an earlier one has already
|
||||
// handed its comments over; taking them again would write them twice.
|
||||
if claimed.contains(&item.span) {
|
||||
continue;
|
||||
}
|
||||
claimed.push(item.span);
|
||||
moved.before.extend(carried.before);
|
||||
moved.after.extend(carried.after);
|
||||
}
|
||||
let at = tail(text, port);
|
||||
// Exactly one comment may go beside the port, because two comments landing
|
||||
// on one line become *one* comment — a `//` runs to the end of the line and
|
||||
// the lexer merges what follows it into the same trailing comment — and a
|
||||
// refactoring that joins two comments the source kept apart is one the
|
||||
// verifier rightly refuses. The rest go above.
|
||||
let beside = moved.after.len() == 1
|
||||
&& after_same_line_comments(text, at).at == at
|
||||
&& line_free(text, at);
|
||||
let mut above = moved.before;
|
||||
if !beside {
|
||||
above.extend(moved.after.iter().cloned());
|
||||
}
|
||||
|
||||
let mut edits = vec![insert(port.span.start, prefix(text, module, port, absorbed, &above)?)];
|
||||
if !absorbed.unpacked.is_empty() {
|
||||
edits.push(insert(port.span.end, absorbed.unpacked.clone()));
|
||||
}
|
||||
if beside {
|
||||
edits.push(insert(at, format!(" {}", moved.after.join(" "))));
|
||||
}
|
||||
Ok(edits)
|
||||
}
|
||||
|
||||
/// What is written just before the port's name: the comments its declarations
|
||||
/// carried, then the declaration itself.
|
||||
fn prefix(
|
||||
text: &str,
|
||||
module: &str,
|
||||
port: &NonAnsiPort,
|
||||
absorbed: &Absorbed<'_>,
|
||||
above: &[String],
|
||||
) -> Result<String, String> {
|
||||
let mut out = String::new();
|
||||
match own_line(text, port.span.start) {
|
||||
Some(indent) => {
|
||||
for comment in above {
|
||||
out.push_str(comment);
|
||||
out.push('\n');
|
||||
out.push_str(&indent);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
for comment in above {
|
||||
if !inline_safe(comment) {
|
||||
return Err(format!(
|
||||
"the comment `{comment}` on `{module}`'s declaration of `{}` would have to move into a port list written on one line, where it would swallow the rest of it; break `{module}`'s port list across lines first, and lucisv made no edits.",
|
||||
absorbed.name
|
||||
));
|
||||
}
|
||||
out.push_str(comment);
|
||||
out.push(' ');
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(&absorbed.prefix);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Where a port's trailing comment goes: past the `,` that follows the name,
|
||||
/// or — for the last port — straight after it.
|
||||
fn tail(text: &str, port: &NonAnsiPort) -> u32 {
|
||||
comma_after(text, port.span.end).map_or(port.span.end, |comma| comma + 1)
|
||||
}
|
||||
|
||||
/// The deletions that take the absorbed body declarations away, comments
|
||||
/// included: each one moved onto its port above.
|
||||
fn deletions(
|
||||
text: &str,
|
||||
module: &str,
|
||||
absorbed: &[Absorbed<'_>],
|
||||
comments: &[(TextRange, String)],
|
||||
) -> Result<Vec<TextEdit>, String> {
|
||||
let mut ranges: Vec<TextRange> = Vec::new();
|
||||
for item in absorbed.iter().flat_map(|a| a.items.iter()) {
|
||||
let (range, _) = carried(text, module, item, comments)?;
|
||||
if !ranges.contains(&range) {
|
||||
ranges.push(range);
|
||||
}
|
||||
}
|
||||
Ok(ranges.into_iter().map(|range| TextEdit { range, new_text: String::new() }).collect())
|
||||
}
|
||||
|
||||
/// The indentation of the line `at` starts, or `None` when something else is
|
||||
/// written on that line before it.
|
||||
fn own_line(text: &str, at: u32) -> Option<String> {
|
||||
let indent = line_indent(text, at);
|
||||
let start = (at as usize).checked_sub(indent.len())?;
|
||||
(start == 0 || text.as_bytes().get(start - 1) == Some(&b'\n')).then_some(indent)
|
||||
}
|
||||
|
||||
/// Whether the rest of the line from `at` is blank — which is what makes room
|
||||
/// for a `//` comment.
|
||||
fn line_free(text: &str, at: u32) -> bool {
|
||||
text.get(at as usize..)
|
||||
.is_none_or(|rest| rest.split('\n').next().is_none_or(|line| line.trim().is_empty()))
|
||||
}
|
||||
|
||||
/// Whether a comment can be written in the middle of a line: a block comment
|
||||
/// that stays on it.
|
||||
fn inline_safe(comment: &str) -> bool {
|
||||
comment.starts_with("/*") && !comment.contains('\n')
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
//! Expanding `.*`: the wildcard connection written out as the named
|
||||
//! connections it stands for.
|
||||
//!
|
||||
//! **The rule, as implemented.** IEEE 1800 §23.3.2.4: a `.*` binds every port
|
||||
//! the instance does not connect explicitly to the *same-named* declaration
|
||||
//! visible in the scope the instantiation is written in. lucisv reads "a
|
||||
//! signal" strictly — a net, a variable, or a port of the enclosing module —
|
||||
//! because those are the only declarations a port connection may bind to; a
|
||||
//! parameter, a localparam, a genvar or a type of that name is not a signal
|
||||
//! and the wildcard does not bind it. A port with nothing to bind to is one
|
||||
//! the compiler would have rejected, so it is written `.name()` and named in a
|
||||
//! warning: saying so is the point of the expansion.
|
||||
//!
|
||||
//! Everything else is `propagate.rs`'s shape — the same `Scope`, the same
|
||||
//! declared-port reader, the same `Plan` verified by `finish` — with one
|
||||
//! difference: this refactoring *replaces* a token rather than appending after
|
||||
//! one, so the `.*`'s own span is the edit's range and the comment written
|
||||
//! after it is stepped over the way `append_to_list` steps over one.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use vlog_parser::ast::{Connection, Connections, Instance, Instantiation, Item, ListElem};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::{parse_source_tolerant, LineIndex, ParseDiagnostic};
|
||||
use vlog_semantic::SymbolKind;
|
||||
|
||||
use crate::rename::{display, Scope};
|
||||
use crate::TextEdit;
|
||||
|
||||
use super::add::not_indexed;
|
||||
use super::find::{
|
||||
declared_ports, find_module, kind_visible_in, locate_module, not_in_scope, walk_instantiations,
|
||||
ModuleSite,
|
||||
};
|
||||
use super::list::{after_same_line_comments, conn_list_open, elem_spans, insert, line_indent};
|
||||
use super::{shape, ModuleRef, Plan};
|
||||
|
||||
/// One planned expansion: what to edit, and what the title will promise.
|
||||
pub(super) struct Expansion {
|
||||
pub(super) site: ModuleSite,
|
||||
pub(super) plan: Plan,
|
||||
/// How many connections the `.*` becomes.
|
||||
pub(super) count: usize,
|
||||
/// The instance the wildcard belongs to, for the verifier's sentence.
|
||||
pub(super) instance: String,
|
||||
}
|
||||
|
||||
pub(super) fn plan_expand(
|
||||
scope: &mut Scope,
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
) -> Result<Expansion, String> {
|
||||
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
|
||||
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
unparsed(file, &diagnostics)?;
|
||||
let Wildcard { instantiation, instance, conns, wildcard } = wildcard_at(&tree.items, offset)?;
|
||||
if !instance.conn_directives.is_empty() {
|
||||
return Err(directives(&instance.name, "connection list"));
|
||||
}
|
||||
let site = locate_module(scope, ModuleRef::Name(&instantiation.module))?;
|
||||
|
||||
let missing = unconnected(scope, &site, conns)?;
|
||||
if missing.is_empty() {
|
||||
return Err(format!(
|
||||
"`{}` already connects every port `{}` declares, so its `.*` binds nothing.",
|
||||
instance.name, site.name
|
||||
));
|
||||
}
|
||||
|
||||
let (connections, unbound) = written(scope, i, instance, &missing);
|
||||
let spans: Vec<TextRange> = elem_spans(conns, |c| c.span);
|
||||
let Some(open) = conn_list_open(text, instance, spans.first().copied()) else {
|
||||
return Err(format!(
|
||||
"lucisv cannot find the parentheses of `{}`'s connection list.",
|
||||
instance.name
|
||||
));
|
||||
};
|
||||
let previous = wildcard.checked_sub(1).and_then(|n| spans.get(n)).map_or(open + 1, |e| e.end);
|
||||
let Some(&at) = spans.get(wildcard) else {
|
||||
return Err("lucisv lost track of the `.*` it was expanding.".to_string());
|
||||
};
|
||||
|
||||
let mut plan = Plan { sites: 1, ..Plan::default() };
|
||||
plan.add(i, replacement(text, previous, at, &connections));
|
||||
if !unbound.is_empty() {
|
||||
plan.warnings.push(unbound_warning(text, file, instance, &unbound));
|
||||
}
|
||||
plan.expected.push((i, expected(text, &site.name, instance, conns, wildcard, &missing)));
|
||||
Ok(Expansion { site, plan, count: connections.len(), instance: instance.name.clone() })
|
||||
}
|
||||
|
||||
/// The refusal a file that does not parse earns. A connection list lucisv
|
||||
/// misread is a list whose ports it would connect twice, so — unlike the
|
||||
/// verifier's "no *new* diagnostic" rule — this one asks for none at all.
|
||||
fn unparsed(file: &Path, diagnostics: &[ParseDiagnostic]) -> Result<(), String> {
|
||||
match diagnostics.first() {
|
||||
None => Ok(()),
|
||||
Some(problem) => Err(format!(
|
||||
"{} does not parse ({} at line {}), so lucisv will not expand a `.*` in it.",
|
||||
display(file),
|
||||
problem.message,
|
||||
problem.line
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn directives(what: &str, list: &str) -> String {
|
||||
format!(
|
||||
"`{what}`'s {list} carries compiler directives, so which ports `.*` binds depends on the configuration; lucisv does not preprocess, so it made no edits."
|
||||
)
|
||||
}
|
||||
|
||||
/// What the cursor found: an instance, its named connection list, and which
|
||||
/// element of it is the `.*`.
|
||||
struct Wildcard<'t> {
|
||||
instantiation: &'t Instantiation,
|
||||
instance: &'t Instance,
|
||||
conns: &'t [ListElem<Connection>],
|
||||
wildcard: usize,
|
||||
}
|
||||
|
||||
/// The instantiation the cursor names and the `.*` inside it, or the sentence
|
||||
/// saying why there is none to expand.
|
||||
fn wildcard_at(items: &[Item], offset: u32) -> Result<Wildcard<'_>, String> {
|
||||
let (instantiation, instance, bound) = instance_at(items, offset)?;
|
||||
if bound {
|
||||
return Err(format!(
|
||||
"`{}` is instantiated by a `bind` directive, where `.*` binds in the target's scope rather than in this one; lucisv does not expand it there.",
|
||||
instance.name
|
||||
));
|
||||
}
|
||||
let conns = match &instance.conns {
|
||||
Connections::Ordered(_) => {
|
||||
return Err(format!(
|
||||
"`{}` connects `{}`'s ports by position; there is no `.*` to expand.",
|
||||
instance.name, instantiation.module
|
||||
))
|
||||
}
|
||||
Connections::Named(conns) => conns.as_slice(),
|
||||
};
|
||||
let wildcards: Vec<usize> = conns
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, c)| c.ok().is_some_and(|c| c.name == "*"))
|
||||
.map(|(n, _)| n)
|
||||
.collect();
|
||||
match wildcards.as_slice() {
|
||||
[only] => Ok(Wildcard { instantiation, instance, conns, wildcard: *only }),
|
||||
[] => Err(format!("`{}` writes no `.*` to expand.", instance.name)),
|
||||
_ => Err(format!(
|
||||
"`{}` writes `.*` {} times, which is illegal; lucisv will not guess what it means.",
|
||||
instance.name,
|
||||
wildcards.len()
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The instance under the cursor, or the only one of the statement the
|
||||
/// cursor's module name belongs to — `propagate`'s rule, plus whether the
|
||||
/// instantiation is a `bind` directive's.
|
||||
fn instance_at(items: &[Item], offset: u32) -> Result<(&Instantiation, &Instance, bool), String> {
|
||||
let mut all: Vec<(&Instantiation, bool)> = Vec::new();
|
||||
walk_instantiations(items, &mut |instantiation, bound| all.push((instantiation, bound)));
|
||||
let mut found = None;
|
||||
for (instantiation, bound) in all {
|
||||
for instance in &instantiation.instances {
|
||||
if instance.span.contains(offset) {
|
||||
found = Some((instantiation, instance, bound));
|
||||
}
|
||||
}
|
||||
if found.is_none() && instantiation.module_span.contains(offset) {
|
||||
let [only] = instantiation.instances.as_slice() else {
|
||||
return Err(format!(
|
||||
"this statement declares {} instances of `{}`; put the cursor on the one to expand.",
|
||||
instantiation.instances.len(),
|
||||
instantiation.module
|
||||
));
|
||||
};
|
||||
found = Some((instantiation, only, bound));
|
||||
}
|
||||
}
|
||||
found.ok_or_else(|| "there is no module instantiation at this position.".to_string())
|
||||
}
|
||||
|
||||
/// The declared ports the instance does not connect explicitly, in declaration
|
||||
/// order — exactly what the wildcard stands for.
|
||||
fn unconnected(
|
||||
scope: &mut Scope,
|
||||
site: &ModuleSite,
|
||||
conns: &[ListElem<Connection>],
|
||||
) -> Result<Vec<String>, String> {
|
||||
let Some(text) = scope.text(site.file) else { return Err(not_indexed(&site.name)) };
|
||||
let Some(path) = scope.path(site.file) else { return Err(not_indexed(&site.name)) };
|
||||
let (tree, diagnostics) = parse_source_tolerant(text);
|
||||
unparsed(path, &diagnostics)?;
|
||||
let Some((module, _)) = find_module(&tree, &site.name) else {
|
||||
return Err(not_indexed(&site.name));
|
||||
};
|
||||
if !module.port_directives.is_empty() {
|
||||
return Err(directives(&site.name, "port list"));
|
||||
}
|
||||
Ok(declared_ports(module)
|
||||
.into_iter()
|
||||
.map(|port| port.name)
|
||||
.filter(|name| conns.iter().filter_map(ListElem::ok).all(|c| &c.name != name))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Each missing port as the connection lucisv writes for it, plus the ports
|
||||
/// nothing in scope binds.
|
||||
fn written(
|
||||
scope: &mut Scope,
|
||||
file: usize,
|
||||
instance: &Instance,
|
||||
missing: &[String],
|
||||
) -> (Vec<String>, Vec<String>) {
|
||||
let at = instance.name_span.start;
|
||||
let mut connections = Vec::new();
|
||||
let mut unbound = Vec::new();
|
||||
for name in missing {
|
||||
let bound = signal_visible(scope, file, at, name);
|
||||
if !bound {
|
||||
unbound.push(name.clone());
|
||||
}
|
||||
connections.push(connection(name, bound));
|
||||
}
|
||||
(connections, unbound)
|
||||
}
|
||||
|
||||
/// `.name(name)`, or `.name()` for a port nothing binds — with the space an
|
||||
/// **escaped identifier** needs after it.
|
||||
///
|
||||
/// An escaped identifier runs from its `\` to the next whitespace and to
|
||||
/// nothing else (IEEE 1800 §5.6.1), so `.\my-port(\my-port)` is one enormous
|
||||
/// token that swallows the parens, the comma and the rest of the line. The
|
||||
/// instantiation skeleton learned this from QA (`instantiate::terminate`);
|
||||
/// the test for "does this end inside an escape" is shared rather than
|
||||
/// spelled twice.
|
||||
fn connection(name: &str, bound: bool) -> String {
|
||||
let mut out = String::from(".");
|
||||
terminate(&mut out, name);
|
||||
out.push('(');
|
||||
if bound {
|
||||
terminate(&mut out, name);
|
||||
}
|
||||
out.push(')');
|
||||
out
|
||||
}
|
||||
|
||||
fn terminate(out: &mut String, name: &str) {
|
||||
out.push_str(name);
|
||||
if crate::instantiate::ends_escaped(name) {
|
||||
out.push(' ');
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `.*` would bind `name` here: a net, a variable or a port of that
|
||||
/// name, declared in the instantiating scope or one enclosing it.
|
||||
///
|
||||
/// A parameter is deliberately not one. `parameter int clk = 0;` beside an
|
||||
/// instance leaves the module's `clk` port unbound, and writing `.clk(clk)`
|
||||
/// for it would connect a port to a constant — a legal, silent, wrong
|
||||
/// expansion. The kinds are the LRM's, not the ones a connection lucisv
|
||||
/// *writes* may name (`find::visible_in`).
|
||||
fn signal_visible(scope: &mut Scope, file: usize, offset: u32, name: &str) -> bool {
|
||||
let Some(analysis) = scope.analysis(file) else { return false };
|
||||
kind_visible_in(&analysis.semantics, offset, name)
|
||||
.is_some_and(|kind| matches!(kind, SymbolKind::Net | SymbolKind::Var | SymbolKind::Port))
|
||||
}
|
||||
|
||||
/// The edits that put the connections where the `.*` was.
|
||||
///
|
||||
/// The layout is the list's own, read the way `append_to_list` reads it: the
|
||||
/// gap before the wildcard tells one-element-per-line from inline, and the
|
||||
/// indentation is the wildcard's own line's. A comment written after the `.*`
|
||||
/// on its own line stays with the **first** connection — the comma goes before
|
||||
/// it and the rest after it — because a `,` written after `//` is a `,` inside
|
||||
/// a comment, and because the comment was about the wildcard, whose first
|
||||
/// connection is what replaces it.
|
||||
fn replacement(text: &str, previous: u32, at: TextRange, connections: &[String]) -> Vec<TextEdit> {
|
||||
let one_per_line =
|
||||
text.get(previous as usize..at.start as usize).is_some_and(|gap| gap.contains('\n'));
|
||||
let indent = line_indent(text, at.start);
|
||||
let br = match one_per_line {
|
||||
true => format!("\n{indent}"),
|
||||
false => " ".to_string(),
|
||||
};
|
||||
let separator = format!(",{br}");
|
||||
let replace = |text: String| TextEdit { range: at, new_text: text };
|
||||
|
||||
let after = after_same_line_comments(text, at.end);
|
||||
let [first, rest @ ..] = connections else { return Vec::new() };
|
||||
if after.at == at.end || rest.is_empty() {
|
||||
return vec![replace(connections.join(&separator))];
|
||||
}
|
||||
vec![replace(format!("{first},")), insert(after.at, format!("{br}{}", rest.join(&separator)))]
|
||||
}
|
||||
|
||||
fn unbound_warning(text: &str, file: &Path, instance: &Instance, unbound: &[String]) -> String {
|
||||
let lines = LineIndex::new(text);
|
||||
format!(
|
||||
"no net, variable or port named {} is declared where `{}` is instantiated ({}:{}), so `.*` never bound {} — lucisv wrote {} unconnected.",
|
||||
unbound.iter().map(|n| format!("`{n}`")).collect::<Vec<_>>().join(", "),
|
||||
instance.name,
|
||||
display(file),
|
||||
lines.line_col(instance.name_span.start).0,
|
||||
if unbound.len() == 1 { "it" } else { "them" },
|
||||
if unbound.len() == 1 { "it" } else { "them" },
|
||||
)
|
||||
}
|
||||
|
||||
/// What the file must say afterwards: this instance's connection names with
|
||||
/// the `*` replaced, in place, by the ports it stood for.
|
||||
fn expected(
|
||||
text: &str,
|
||||
module: &str,
|
||||
instance: &Instance,
|
||||
conns: &[ListElem<Connection>],
|
||||
wildcard: usize,
|
||||
missing: &[String],
|
||||
) -> super::Shape {
|
||||
let mut names: Vec<String> =
|
||||
conns.iter().map(|c| c.ok().map(|c| c.name.clone()).unwrap_or_default()).collect();
|
||||
names.splice(wildcard..wildcard + 1, missing.iter().cloned());
|
||||
let mut shape = shape(text, module);
|
||||
for (name, conns) in &mut shape.instances {
|
||||
if name == &instance.name {
|
||||
*conns = names.clone();
|
||||
}
|
||||
}
|
||||
shape
|
||||
}
|
||||
@@ -143,34 +143,45 @@ pub(super) fn declared_ports(module: &Module) -> Vec<DeclaredPort> {
|
||||
/// Every instantiation written in a file, generate blocks and `bind`
|
||||
/// directives included.
|
||||
pub(super) fn collect_instantiations<'t>(items: &'t [Item], out: &mut Vec<&'t Instantiation>) {
|
||||
walk_instantiations(items, &mut |instantiation, _| out.push(instantiation));
|
||||
}
|
||||
|
||||
/// [`collect_instantiations`]'s walk, saying of each instantiation whether it
|
||||
/// is a `bind` directive's own — which is where a `.*` binds in the *target's*
|
||||
/// scope rather than in the one it is written in, and therefore the one site
|
||||
/// the wildcard expansion declines.
|
||||
pub(super) fn walk_instantiations<'t>(
|
||||
items: &'t [Item],
|
||||
visit: &mut dyn FnMut(&'t Instantiation, bool),
|
||||
) {
|
||||
for item in items {
|
||||
match &item.kind {
|
||||
ItemKind::Instantiation(inst) => out.push(inst),
|
||||
ItemKind::Bind(bind) => out.push(&bind.inst),
|
||||
ItemKind::Module(module) => collect_instantiations(&module.items, out),
|
||||
ItemKind::Package { items, .. } => collect_instantiations(items, out),
|
||||
ItemKind::GenerateRegion { items, .. } => collect_instantiations(items, out),
|
||||
ItemKind::GenBlock(b) => collect_instantiations(&b.items, out),
|
||||
ItemKind::Instantiation(inst) => visit(inst, false),
|
||||
ItemKind::Bind(bind) => visit(&bind.inst, true),
|
||||
ItemKind::Module(module) => walk_instantiations(&module.items, visit),
|
||||
ItemKind::Package { items, .. } => walk_instantiations(items, visit),
|
||||
ItemKind::GenerateRegion { items, .. } => walk_instantiations(items, visit),
|
||||
ItemKind::GenBlock(b) => walk_instantiations(&b.items, visit),
|
||||
ItemKind::GenIf(gen) => {
|
||||
collect_gen_block(&gen.then, out);
|
||||
walk_gen_block(&gen.then, visit);
|
||||
let mut els = gen.els.as_deref();
|
||||
while let Some(next) = els {
|
||||
match next {
|
||||
GenElse::If(_, gen) => {
|
||||
collect_gen_block(&gen.then, out);
|
||||
walk_gen_block(&gen.then, visit);
|
||||
els = gen.els.as_deref();
|
||||
}
|
||||
GenElse::Block(block) => {
|
||||
collect_gen_block(block, out);
|
||||
walk_gen_block(block, visit);
|
||||
els = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::GenFor(gen) => collect_gen_block(&gen.body, out),
|
||||
ItemKind::GenFor(gen) => walk_gen_block(&gen.body, visit),
|
||||
ItemKind::GenCase(gen) => {
|
||||
for arm in &gen.items {
|
||||
collect_gen_block(&arm.body, out);
|
||||
walk_gen_block(&arm.body, visit);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -178,8 +189,8 @@ pub(super) fn collect_instantiations<'t>(items: &'t [Item], out: &mut Vec<&'t In
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_gen_block<'t>(block: &'t GenBlock, out: &mut Vec<&'t Instantiation>) {
|
||||
collect_instantiations(&block.items, out);
|
||||
fn walk_gen_block<'t>(block: &'t GenBlock, visit: &mut dyn FnMut(&'t Instantiation, bool)) {
|
||||
walk_instantiations(&block.items, visit);
|
||||
}
|
||||
|
||||
/// Whether a signal called `name` is visible at `offset` in a file — the test
|
||||
@@ -190,6 +201,32 @@ pub(super) fn name_visible(scope: &mut Scope, file: usize, offset: u32, name: &s
|
||||
}
|
||||
|
||||
pub(crate) fn visible_in(semantics: &Semantics, offset: u32, name: &str) -> bool {
|
||||
kind_visible_in(semantics, offset, name).is_some_and(|kind| {
|
||||
matches!(
|
||||
kind,
|
||||
SymbolKind::Net
|
||||
| SymbolKind::Var
|
||||
| SymbolKind::Port
|
||||
| SymbolKind::Param
|
||||
| SymbolKind::LocalParam
|
||||
| SymbolKind::Genvar
|
||||
| SymbolKind::TfArg
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// What a lookup of `name` from the innermost scope covering `offset` finds —
|
||||
/// the scope walk itself, without the judgement about which kinds count.
|
||||
///
|
||||
/// Two callers want different answers from the same walk: a connection lucisv
|
||||
/// *writes* may name anything a reader could have written there, while `.*`
|
||||
/// binds only a net, a variable or a port (IEEE 1800 §23.3.2.4), so the
|
||||
/// wildcard expansion asks the same question and reads the kind itself.
|
||||
pub(crate) fn kind_visible_in(
|
||||
semantics: &Semantics,
|
||||
offset: u32,
|
||||
name: &str,
|
||||
) -> Option<SymbolKind> {
|
||||
let scopes = semantics.scopes();
|
||||
// The innermost scope covering the offset: the smallest span that holds it.
|
||||
let mut best: Option<usize> = None;
|
||||
@@ -206,24 +243,13 @@ pub(crate) fn visible_in(semantics: &Semantics, offset: u32, name: &str) -> bool
|
||||
}
|
||||
let mut at = best;
|
||||
while let Some(i) = at {
|
||||
let Some(current) = scopes.get(i) else { return false };
|
||||
let current = scopes.get(i)?;
|
||||
if let Some(symbol) = current.lookup_local(name) {
|
||||
return semantics.symbol(symbol).is_some_and(|s| {
|
||||
matches!(
|
||||
s.kind,
|
||||
SymbolKind::Net
|
||||
| SymbolKind::Var
|
||||
| SymbolKind::Port
|
||||
| SymbolKind::Param
|
||||
| SymbolKind::LocalParam
|
||||
| SymbolKind::Genvar
|
||||
| SymbolKind::TfArg
|
||||
)
|
||||
});
|
||||
return semantics.symbol(symbol).map(|s| s.kind);
|
||||
}
|
||||
at = current.parent.map(|p| p.0 as usize);
|
||||
}
|
||||
false
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -174,7 +174,7 @@ pub(super) fn line_indent(text: &str, offset: u32) -> String {
|
||||
}
|
||||
|
||||
/// The `,` written after `end`, skipping whitespace and comments.
|
||||
fn comma_after(text: &str, end: u32) -> Option<u32> {
|
||||
pub(super) fn comma_after(text: &str, end: u32) -> Option<u32> {
|
||||
let mut at = end as usize;
|
||||
loop {
|
||||
let rest = text.get(at..)?;
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
//! IEEE 1800 §23.2.2.2: pairing each name of a non-ANSI header with the body
|
||||
//! declarations that describe it, and merging the two into the one ANSI port
|
||||
//! declaration that says the same thing.
|
||||
//!
|
||||
//! The LRM's rule in one paragraph. A non-ANSI header names its ports and the
|
||||
//! body declares them. The *port declaration* (`output [7:0] b;`) always
|
||||
//! carries the direction; when it also carries a net or a variable type
|
||||
//! (`output reg [7:0] b;`, `input wire a;`) the port is **completely
|
||||
//! declared** and declaring it again is an error. When it does not, a separate
|
||||
//! net or variable declaration of the same name (`reg [7:0] b;`) finishes it,
|
||||
//! and the two must agree: identical packed ranges, identical unpacked
|
||||
//! dimensions, one signing. The merge is the union — `output [7:0] b;` plus
|
||||
//! `reg [7:0] b;` is `output reg [7:0] b`.
|
||||
//!
|
||||
//! Everything this module produces is *text*, written in the order the
|
||||
//! formatter's own ANSI port printer writes it (`vlog_formatter`'s
|
||||
//! `ansi_port_cells`: direction, net, type, signing, packed dimensions, name,
|
||||
//! unpacked dimensions), so a converted header formats to itself.
|
||||
|
||||
use vlog_parser::ast::{DataDecl, DataType, Declarator, Dim, Item, ItemKind, PortDecl};
|
||||
|
||||
/// One header port, once its body declarations have been read and merged.
|
||||
pub(super) struct Absorbed<'t> {
|
||||
pub(super) name: String,
|
||||
/// The body items this port takes with it: its port declaration, and the
|
||||
/// net or variable declaration that completed it, if there was one.
|
||||
pub(super) items: Vec<&'t Item>,
|
||||
/// Everything an ANSI port writes before its name: `output reg [7:0] `.
|
||||
pub(super) prefix: String,
|
||||
/// Everything it writes after it: ` [0:3]` for an unpacked dimension.
|
||||
pub(super) unpacked: String,
|
||||
}
|
||||
|
||||
/// Where one declarator of one body declaration is written.
|
||||
struct Site<'t> {
|
||||
item: &'t Item,
|
||||
declarator: &'t Declarator,
|
||||
}
|
||||
|
||||
/// Read a module's body declarations and merge each header name with its own.
|
||||
///
|
||||
/// `names` is the header's port list in header order; the answer is in the
|
||||
/// same order, which is what makes the converted list the list the source
|
||||
/// wrote.
|
||||
pub(super) fn absorb<'t>(
|
||||
text: &str,
|
||||
module: &str,
|
||||
items: &'t [Item],
|
||||
names: &[String],
|
||||
) -> Result<Vec<Absorbed<'t>>, String> {
|
||||
let Body { ports, vars } = collect(module, items, names)?;
|
||||
let mut out = Vec::new();
|
||||
for name in names {
|
||||
let port = one(
|
||||
&ports,
|
||||
name,
|
||||
|| {
|
||||
format!(
|
||||
"`{module}`'s header names `{name}`, but its body declares no direction for it; a port with no declaration is illegal, so lucisv made no edits."
|
||||
)
|
||||
},
|
||||
|| {
|
||||
format!(
|
||||
"`{module}` declares a direction for `{name}` twice; lucisv will not guess which one is the port."
|
||||
)
|
||||
},
|
||||
)?;
|
||||
let var = match vars.iter().filter(|site| site.declarator.name == *name).count() {
|
||||
0 => None,
|
||||
1 => vars.iter().find(|site| site.declarator.name == *name),
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"`{module}` declares `{name}` twice outside its port declaration; lucisv will not guess which one completes the port."
|
||||
))
|
||||
}
|
||||
};
|
||||
out.push(merged(text, module, name, port, var)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A module body as the merge reads it: the port declarations that give the
|
||||
/// directions, and the net/variable declarations that complete them.
|
||||
struct Body<'t> {
|
||||
ports: Vec<Site<'t>>,
|
||||
vars: Vec<Site<'t>>,
|
||||
}
|
||||
|
||||
/// Read the body, with the declarations lucisv will not absorb refused.
|
||||
fn collect<'t>(module: &str, items: &'t [Item], names: &[String]) -> Result<Body<'t>, String> {
|
||||
let mut ports = Vec::new();
|
||||
let mut vars = Vec::new();
|
||||
for item in items {
|
||||
match &item.kind {
|
||||
ItemKind::PortDecl(decl) => {
|
||||
for declarator in &decl.declarators {
|
||||
if !names.contains(&declarator.name) {
|
||||
return Err(format!(
|
||||
"`{module}` declares a direction for `{}`, which its header does not name; lucisv made no edits.",
|
||||
declarator.name
|
||||
));
|
||||
}
|
||||
no_initialiser(module, declarator)?;
|
||||
ports.push(Site { item, declarator });
|
||||
}
|
||||
}
|
||||
ItemKind::DataDecl(decl) => {
|
||||
let mine = decl.declarators.iter().filter(|d| names.contains(&d.name)).count();
|
||||
if mine == 0 {
|
||||
continue;
|
||||
}
|
||||
shared(module, decl, mine)?;
|
||||
for declarator in &decl.declarators {
|
||||
no_initialiser(module, declarator)?;
|
||||
vars.push(Site { item, declarator });
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(Body { ports, vars })
|
||||
}
|
||||
|
||||
/// A declaration that names a header port *and* something else cannot be
|
||||
/// deleted: the local it also declares would go with it.
|
||||
fn shared(module: &str, decl: &DataDecl, mine: usize) -> Result<(), String> {
|
||||
if mine == decl.declarators.len() {
|
||||
return no_qualifier(module, decl);
|
||||
}
|
||||
Err(format!(
|
||||
"`{module}` declares {} in one declaration, of which only {mine} {} a port; lucisv cannot absorb one without the other, so split the declaration first.",
|
||||
decl.declarators.iter().map(|d| format!("`{}`", d.name)).collect::<Vec<_>>().join(", "),
|
||||
if mine == 1 { "is" } else { "are" }
|
||||
))
|
||||
}
|
||||
|
||||
/// What lucisv refuses to carry from a variable declaration into a port list:
|
||||
/// a `var`/`const`/`automatic` qualifier, and a net delay.
|
||||
fn no_qualifier(module: &str, decl: &DataDecl) -> Result<(), String> {
|
||||
if let Some(qualifier) = decl.qualifiers.first() {
|
||||
return Err(format!(
|
||||
"`{module}` writes `{}` where it completes a port's declaration, and lucisv does not move a qualifier into a port list; it made no edits.",
|
||||
qualifier.text
|
||||
));
|
||||
}
|
||||
if decl.delay.is_some() {
|
||||
return Err(format!(
|
||||
"`{module}` writes a net delay where it completes a port's declaration, and lucisv does not move a delay into a port list; it made no edits."
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn no_initialiser(module: &str, declarator: &Declarator) -> Result<(), String> {
|
||||
match declarator.init {
|
||||
None => Ok(()),
|
||||
Some(_) => Err(format!(
|
||||
"`{module}` initialises `{}` where it declares it, and lucisv does not move an initialiser into a port list; it made no edits.",
|
||||
declarator.name
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The one site declaring `name`, or the sentence for none and for several.
|
||||
fn one<'a, 't>(
|
||||
sites: &'a [Site<'t>],
|
||||
name: &str,
|
||||
none: impl Fn() -> String,
|
||||
several: impl Fn() -> String,
|
||||
) -> Result<&'a Site<'t>, String> {
|
||||
let mut found = sites.iter().filter(|site| site.declarator.name == name);
|
||||
let first = found.next().ok_or_else(none)?;
|
||||
match found.next() {
|
||||
None => Ok(first),
|
||||
Some(_) => Err(several()),
|
||||
}
|
||||
}
|
||||
|
||||
/// One header name plus its declarations, written out as an ANSI port.
|
||||
fn merged<'t>(
|
||||
text: &str,
|
||||
module: &str,
|
||||
name: &str,
|
||||
port: &Site<'t>,
|
||||
var: Option<&Site<'t>>,
|
||||
) -> Result<Absorbed<'t>, String> {
|
||||
let ItemKind::PortDecl(decl) = &port.item.kind else {
|
||||
return Err(format!("lucisv lost track of `{module}`'s declaration of `{name}`."));
|
||||
};
|
||||
let variable = match var.map(|site| &site.item.kind) {
|
||||
Some(ItemKind::DataDecl(decl)) => Some(decl),
|
||||
_ => None,
|
||||
};
|
||||
if variable.is_some() && complete(decl) {
|
||||
return Err(format!(
|
||||
"`{module}` gives `{name}` a type in its port declaration and declares it again; IEEE 1800 §23.2.2.2 makes that an error, so lucisv made no edits."
|
||||
));
|
||||
}
|
||||
plain(module, name, &decl.ty)?;
|
||||
if let Some(variable) = variable {
|
||||
plain(module, name, &variable.ty)?;
|
||||
}
|
||||
|
||||
let net = decl.net.clone().or_else(|| variable.and_then(|v| v.net.clone()));
|
||||
let ty = pick_name(&decl.ty, variable.map(|v| &v.ty));
|
||||
let signing = signing(
|
||||
module,
|
||||
name,
|
||||
decl.ty.signing.clone(),
|
||||
variable.and_then(|v| v.ty.signing.clone()),
|
||||
)?;
|
||||
let var_packed = variable.map_or(&[][..], |v| v.ty.packed.as_slice());
|
||||
let packed = dims(text, module, name, "packed range", &decl.ty.packed, var_packed)?;
|
||||
let unpacked = dims(
|
||||
text,
|
||||
module,
|
||||
name,
|
||||
"unpacked dimension",
|
||||
&port.declarator.unpacked,
|
||||
var.map_or(&[][..], |site| site.declarator.unpacked.as_slice()),
|
||||
)?;
|
||||
|
||||
let mut prefix = String::new();
|
||||
let mut word = |part: &str| {
|
||||
prefix.push_str(part);
|
||||
prefix.push(' ');
|
||||
};
|
||||
word(&decl.dir);
|
||||
for part in [net.as_deref(), ty.as_deref(), signing.as_deref()].into_iter().flatten() {
|
||||
word(part);
|
||||
}
|
||||
if !packed.is_empty() {
|
||||
word(&packed);
|
||||
}
|
||||
|
||||
let mut items = vec![port.item];
|
||||
if let Some(site) = var {
|
||||
items.push(site.item);
|
||||
}
|
||||
let unpacked = match unpacked.is_empty() {
|
||||
true => String::new(),
|
||||
false => format!(" {unpacked}"),
|
||||
};
|
||||
Ok(Absorbed { name: name.to_string(), items, prefix, unpacked })
|
||||
}
|
||||
|
||||
/// Whether a port declaration already says what the port *is* — a net type or
|
||||
/// a data type — which is what makes it complete under §23.2.2.2.
|
||||
fn complete(decl: &PortDecl) -> bool {
|
||||
decl.net.is_some() || !decl.ty.name.is_empty()
|
||||
}
|
||||
|
||||
/// A type lucisv writes into a port list is a name, a signing and packed
|
||||
/// dimensions and nothing else: an anonymous `enum`/`struct` body, a
|
||||
/// parameterized `#( ... )` reference or a `virtual` interface type is text
|
||||
/// lucisv will not move for the user.
|
||||
fn plain(module: &str, name: &str, ty: &DataType) -> Result<(), String> {
|
||||
match ty.virt.is_none() && ty.extra.is_none() {
|
||||
true => Ok(()),
|
||||
false => Err(format!(
|
||||
"`{module}` declares `{name}` with a type lucisv does not move into a port list (an anonymous aggregate, a parameterized reference or a virtual interface); it made no edits."
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The type name the merge writes: the port declaration's own, or — when it
|
||||
/// declared none — the one the variable declaration finished it with.
|
||||
fn pick_name(port: &DataType, var: Option<&DataType>) -> Option<String> {
|
||||
let from_var = var.map(|ty| ty.name.clone()).filter(|name| !name.is_empty());
|
||||
match port.name.is_empty() {
|
||||
true => from_var,
|
||||
false => Some(port.name.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The signing the merge writes. Two halves of one declaration must not
|
||||
/// disagree; `None` on either side is silence, not disagreement.
|
||||
fn signing(
|
||||
module: &str,
|
||||
name: &str,
|
||||
port: Option<String>,
|
||||
var: Option<String>,
|
||||
) -> Result<Option<String>, String> {
|
||||
match (port, var) {
|
||||
(Some(a), Some(b)) if a == b => Ok(Some(a)),
|
||||
(Some(a), Some(b)) => Err(format!(
|
||||
"`{module}` declares `{name}` `{a}` in its port declaration and `{b}` where it completes it; IEEE 1800 §23.2.2.2 asks the two to agree, so lucisv made no edits."
|
||||
)),
|
||||
(Some(a), None) | (None, Some(a)) => Ok(Some(a)),
|
||||
(None, None) => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The dimensions the merge writes, as the source spells them. Two lists that
|
||||
/// are both written must be the same list — that is the LRM's "identical
|
||||
/// range" — compared with the whitespace taken out, so `[7 : 0]` and `[7:0]`
|
||||
/// agree.
|
||||
fn dims(
|
||||
text: &str,
|
||||
module: &str,
|
||||
name: &str,
|
||||
what: &str,
|
||||
port: &[Dim],
|
||||
var: &[Dim],
|
||||
) -> Result<String, String> {
|
||||
let written = |list: &[Dim]| -> String {
|
||||
list.iter()
|
||||
.map(|dim| text.get(dim.span.start as usize..dim.span.end as usize).unwrap_or_default())
|
||||
.collect()
|
||||
};
|
||||
let (a, b) = (written(port), written(var));
|
||||
if a.is_empty() || b.is_empty() {
|
||||
return Ok(match a.is_empty() {
|
||||
true => b,
|
||||
false => a,
|
||||
});
|
||||
}
|
||||
let tight = |s: &str| s.chars().filter(|c| !c.is_whitespace()).collect::<String>();
|
||||
match tight(&a) == tight(&b) {
|
||||
true => Ok(a),
|
||||
false => Err(format!(
|
||||
"`{module}` declares `{name}` with the {what} `{a}` in its port declaration and `{b}` where it completes it; IEEE 1800 §23.2.2.2 asks for identical ones, so lucisv made no edits."
|
||||
)),
|
||||
}
|
||||
}
|
||||
@@ -22,8 +22,11 @@
|
||||
//! parenthesis finding they share.
|
||||
|
||||
mod add;
|
||||
mod ansi;
|
||||
mod expand;
|
||||
mod find;
|
||||
mod list;
|
||||
mod merge;
|
||||
mod propagate;
|
||||
mod remove;
|
||||
|
||||
@@ -31,13 +34,15 @@ pub(crate) use find::{find_module, visible_in};
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::ast::{Connections, ItemKind};
|
||||
use vlog_parser::ast::{Connections, ItemKind, Module, PortList};
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
|
||||
use crate::rename::{display, Scope};
|
||||
use crate::{check, RefactorEdit, TextEdit};
|
||||
|
||||
use add::{parse_port_decl, plan_add};
|
||||
use ansi::plan_convert;
|
||||
use expand::plan_expand;
|
||||
use find::{collect_instantiations, declared_ports, locate_module, module_at};
|
||||
use propagate::plan_propagate;
|
||||
use remove::{locate_port, plan_remove};
|
||||
@@ -125,6 +130,65 @@ pub fn propagate_ports(
|
||||
Ok(finish(&mut scope, plan, &site.name, &what)?.0)
|
||||
}
|
||||
|
||||
/// Write out the `.*` at `offset`: every port the instantiation does not
|
||||
/// connect explicitly, bound to the same-named signal in the instantiating
|
||||
/// scope (IEEE 1800 §23.3.2.4), in the module's declaration order.
|
||||
///
|
||||
/// A port with no such signal is one the wildcard never bound — a compiler
|
||||
/// would have rejected the instantiation — so it is written `.name()` and
|
||||
/// named in a warning. Nothing outside the cursor's own file is edited.
|
||||
pub fn expand_wildcard(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
) -> Result<RefactorEdit, String> {
|
||||
Ok(expansion(files, file, offset)?.0)
|
||||
}
|
||||
|
||||
/// The expansion and how many connections it writes — what a code action's
|
||||
/// title promises.
|
||||
fn expansion(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
) -> Result<(RefactorEdit, usize), String> {
|
||||
let mut scope = Scope::build(files);
|
||||
let expansion = plan_expand(&mut scope, file, offset)?;
|
||||
let what = format!("expanding the `.*` of `{}`", expansion.instance);
|
||||
let edit = finish(&mut scope, expansion.plan, &expansion.site.name, &what)?.0;
|
||||
Ok((edit, expansion.count))
|
||||
}
|
||||
|
||||
/// Rewrite a Verilog-2001 header as an ANSI one: every port the header names
|
||||
/// gains the direction, type, signing and dimensions its body declarations
|
||||
/// gave it (IEEE 1800 §23.2.2.2), and those declarations go.
|
||||
///
|
||||
/// The header's own layout, commas and comments are untouched — what an ANSI
|
||||
/// port adds is inserted around each name — and a comment on an absorbed
|
||||
/// declaration moves onto the port it described. Nothing outside the module's
|
||||
/// own file is edited.
|
||||
pub fn convert_to_ansi(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
) -> Result<RefactorEdit, String> {
|
||||
Ok(conversion(files, file, offset)?.0)
|
||||
}
|
||||
|
||||
/// The conversion and how many ports it declares — what a code action's title
|
||||
/// promises.
|
||||
fn conversion(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
) -> Result<(RefactorEdit, usize), String> {
|
||||
let mut scope = Scope::build(files);
|
||||
let conversion = plan_convert(&mut scope, file, offset)?;
|
||||
let what = format!("converting `{}`'s ports to ANSI", conversion.site.name);
|
||||
let edit = finish(&mut scope, conversion.plan, &conversion.site.name, &what)?.0;
|
||||
Ok((edit, conversion.count))
|
||||
}
|
||||
|
||||
/// Every port refactoring available at a position, each with its edit already
|
||||
/// computed and verified — which is what lets a code action carry its own
|
||||
/// `WorkspaceEdit` instead of a command the editor has to resolve.
|
||||
@@ -153,6 +217,24 @@ pub fn port_actions(files: &[(PathBuf, String)], file: &Path, offset: u32) -> Ve
|
||||
edit,
|
||||
});
|
||||
}
|
||||
if let Ok((edit, count)) = expansion(files, file, offset) {
|
||||
out.push(PortAction {
|
||||
title: format!(
|
||||
"lucisv: expand .* ({count} connection{})",
|
||||
if count == 1 { "" } else { "s" }
|
||||
),
|
||||
edit,
|
||||
});
|
||||
}
|
||||
if let Ok((edit, count)) = conversion(files, file, offset) {
|
||||
out.push(PortAction {
|
||||
title: format!(
|
||||
"lucisv: convert ports to ANSI ({count} port{})",
|
||||
if count == 1 { "" } else { "s" }
|
||||
),
|
||||
edit,
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -213,10 +295,29 @@ pub fn port_action_modules(text: &str, offset: u32) -> Vec<String> {
|
||||
ItemKind::PortDecl(decl) => decl.declarators.iter().any(|d| d.span.contains(offset)),
|
||||
_ => false,
|
||||
});
|
||||
match on_body_declaration {
|
||||
true => vec![name],
|
||||
false => Vec::new(),
|
||||
if on_body_declaration || in_non_ansi_header(module, offset) {
|
||||
return vec![name];
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Whether the cursor is anywhere in the header of a module written the
|
||||
/// Verilog-2001 way — the one position the ANSI conversion is offered at that
|
||||
/// no other port refactoring cares about.
|
||||
///
|
||||
/// The header is everything from the module's keyword to the first item it
|
||||
/// declares (that item's own leading comments included, since a cursor there
|
||||
/// is still above the body). An ANSI module answers `false`: nothing would be
|
||||
/// offered, and the gate exists to keep a cursor that carries no action from
|
||||
/// materializing a workspace.
|
||||
fn in_non_ansi_header(module: &Module, offset: u32) -> bool {
|
||||
if !matches!(module.ports, PortList::NonAnsi(_)) {
|
||||
return false;
|
||||
}
|
||||
let body = module.items.first().map(|item| {
|
||||
item.meta.leading.first().map_or(item.span.start, |comment| comment.span.start)
|
||||
});
|
||||
offset < body.unwrap_or(u32::MAX)
|
||||
}
|
||||
|
||||
/// The module whose declaration covers this offset — what
|
||||
@@ -249,6 +350,17 @@ pub fn sites_phrase(sites: usize) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a title's parenthesized tail is one [`sites_phrase`] wrote.
|
||||
///
|
||||
/// A server that recounts an offered title's instantiations from its index
|
||||
/// must not recount a title counting something else: `lucisv: expand .* (3
|
||||
/// connections)` says how many connections one `.*` becomes, which no
|
||||
/// instantiation census can answer. One spelling of the phrase, and one
|
||||
/// reader of it, both here.
|
||||
pub fn is_sites_phrase(phrase: &str) -> bool {
|
||||
phrase == sites_phrase(0) || phrase.starts_with("updates ")
|
||||
}
|
||||
|
||||
/// Everything a port refactoring wants done, before it is verified.
|
||||
#[derive(Default)]
|
||||
struct Plan {
|
||||
|
||||
@@ -324,7 +324,7 @@ impl<'a> Scope<'a> {
|
||||
/// not about every unresolved identifier in the file.
|
||||
fn unresolved_unit(resolution: &Resolution) -> Option<String> {
|
||||
match resolution {
|
||||
Resolution::ExternalCandidate { paths } => {
|
||||
Resolution::ExternalCandidate { paths, .. } => {
|
||||
let first = paths.first()?;
|
||||
Some(first.rsplit_once("::")?.0.to_string())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,551 @@
|
||||
//! `convert_to_ansi`: a Verilog-2001 header rewritten ANSI-style.
|
||||
//!
|
||||
//! Behaviour tests, written against the public API the way an editor calls it.
|
||||
//! The merge rules are IEEE 1800 §23.2.2.2's, one test each; the refusals are
|
||||
//! the list in `docs/features/ansi-conversion/README.md`, one test each.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_refactor::{convert_to_ansi, port_actions, RefactorEdit, TextEdit};
|
||||
|
||||
const TOP: &str = "/rtl/m.sv";
|
||||
|
||||
fn files(source: &str) -> Vec<(PathBuf, String)> {
|
||||
vec![(PathBuf::from(TOP), source.to_string())]
|
||||
}
|
||||
|
||||
/// Apply an edit to the one file it touches.
|
||||
fn applied(source: &str, edit: &RefactorEdit) -> String {
|
||||
let (_, edits) = edit.edits.first().expect("one file edited");
|
||||
let mut out = String::new();
|
||||
let mut cursor = 0usize;
|
||||
for TextEdit { range, new_text } in edits {
|
||||
out.push_str(&source[cursor..range.start as usize]);
|
||||
out.push_str(new_text);
|
||||
cursor = range.end as usize;
|
||||
}
|
||||
out.push_str(&source[cursor..]);
|
||||
out
|
||||
}
|
||||
|
||||
/// Convert at the module's name, which is inside every non-ANSI header.
|
||||
fn convert(source: &str) -> Result<String, String> {
|
||||
let at = source.find("module ").map_or(0, |i| i + 7) as u32;
|
||||
let edit = convert_to_ansi(&files(source), Path::new(TOP), at)?;
|
||||
assert!(edit.edits.len() == 1, "only the module's own file is edited");
|
||||
Ok(applied(source, &edit))
|
||||
}
|
||||
|
||||
/// The sentence a refusal is.
|
||||
fn refused(source: &str) -> String {
|
||||
convert(source).expect_err("this one is refused")
|
||||
}
|
||||
|
||||
fn count_comments(text: &str) -> usize {
|
||||
text.match_indices("//").count() + text.match_indices("/*").count()
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// IEEE 1800 §23.2.2.2, one merge rule at a time
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_bare_port_declaration_becomes_a_bare_ansi_port() {
|
||||
let source = "module m (a, b);\n input a;\n inout b;\nendmodule\n";
|
||||
assert_eq!(convert(source).expect("converted"), "module m (input a, inout b);\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vector_port_keeps_its_packed_range() {
|
||||
let source = "module m (b);\n output [7:0] b;\nendmodule\n";
|
||||
assert_eq!(convert(source).expect("converted"), "module m (output [7:0] b);\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_completed_by_a_variable_declaration_merges_the_two() {
|
||||
// The LRM's own example: `output [7:0] b; reg [7:0] b;` is `output reg
|
||||
// [7:0] b`.
|
||||
let source = "module m (b);\n output [7:0] b;\n reg [7:0] b;\nendmodule\n";
|
||||
assert_eq!(convert(source).expect("converted"), "module m (output reg [7:0] b);\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scalar_port_completed_by_a_scalar_variable_merges_too() {
|
||||
let source = "module m (b);\n output b;\n reg b;\nendmodule\n";
|
||||
assert_eq!(convert(source).expect("converted"), "module m (output reg b);\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_completed_by_a_logic_declaration_merges() {
|
||||
let source = "module m (b);\n output b;\n logic [3:0] b;\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(source).expect("converted"),
|
||||
"module m (output logic [3:0] b);\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_completed_by_a_net_declaration_merges() {
|
||||
let source = "module m (a);\n input a;\n wire [1:0] a;\nendmodule\n";
|
||||
assert_eq!(convert(source).expect("converted"), "module m (input wire [1:0] a);\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_declaration_that_is_already_complete_needs_no_second_one() {
|
||||
let source = "module m (a);\n input wire signed [7:0] a;\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(source).expect("converted"),
|
||||
"module m (input wire signed [7:0] a);\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signing_written_on_either_half_reaches_the_ansi_port() {
|
||||
let port = "module m (b);\n output signed [7:0] b;\n reg [7:0] b;\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(port).expect("converted"),
|
||||
"module m (output reg signed [7:0] b);\nendmodule\n"
|
||||
);
|
||||
let var = "module m (b);\n output [7:0] b;\n reg signed [7:0] b;\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(var).expect("converted"),
|
||||
"module m (output reg signed [7:0] b);\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_packed_range_written_on_only_one_half_is_the_merged_one() {
|
||||
let source = "module m (b);\n output b;\n reg [7:0] b;\nendmodule\n";
|
||||
assert_eq!(convert(source).expect("converted"), "module m (output reg [7:0] b);\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identical_unpacked_dimensions_survive_the_merge() {
|
||||
let source = "module m (mem);\n output [7:0] mem [0:3];\n reg [7:0] mem [0:3];\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(source).expect("converted"),
|
||||
"module m (output reg [7:0] mem [0:3]);\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_declaration_may_declare_several_ports() {
|
||||
let source = "module m (a, b, c);\n input a, b;\n output c;\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(source).expect("converted"),
|
||||
"module m (input a, input b, output c);\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_user_defined_type_is_written_as_the_source_spells_it() {
|
||||
let source = "module m (a);\n input a;\n pkg::word_t a;\nendmodule\n";
|
||||
assert_eq!(convert(source).expect("converted"), "module m (input pkg::word_t a);\nendmodule\n");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// layout, comments and the body
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_one_per_line_header_stays_one_per_line() {
|
||||
let source = "module m (\n a,\n b\n);\n input a;\n output [7:0] b;\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(source).expect("converted"),
|
||||
"module m (\n input a,\n output [7:0] b\n);\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_headers_own_comments_are_not_touched() {
|
||||
let source = "module m (\n a, // the clock\n b\n);\n input a;\n output b;\nendmodule\n";
|
||||
let out = convert(source).expect("converted");
|
||||
assert!(out.contains("input a, // the clock"), "{out}");
|
||||
assert_eq!(count_comments(&out), count_comments(source));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trailing_comment_moves_onto_the_port_it_described() {
|
||||
let source =
|
||||
"module m (\n a,\n b\n);\n input a; // the clock\n output b; // the data\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(source).expect("converted"),
|
||||
"module m (\n input a, // the clock\n output b // the data\n);\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leading_comment_moves_onto_its_own_line_above_the_port() {
|
||||
let source =
|
||||
"module m (\n a,\n b\n);\n // the clock\n input a;\n output b;\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(source).expect("converted"),
|
||||
"module m (\n // the clock\n input a,\n output b\n);\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_halves_of_a_merged_port_keep_their_comments() {
|
||||
// Two comments never become one: a `//` swallows the line, so only one
|
||||
// may sit beside the port and the rest go above it.
|
||||
let source = "module m (\n b\n);\n output [7:0] b; // the port\n reg [7:0] b; // the storage\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(source).expect("converted"),
|
||||
"module m (\n // the port\n // the storage\n output reg [7:0] b\n);\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_comment_moves_into_an_inline_header() {
|
||||
let source = "module m (a, b);\n /* first */ input a;\n output b;\nendmodule\n";
|
||||
let out = convert(source).expect("converted");
|
||||
assert!(out.contains("/* first */ input a"), "{out}");
|
||||
assert_eq!(count_comments(&out), count_comments(source));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_comment_in_the_module_survives_the_conversion() {
|
||||
let source = concat!(
|
||||
"// about the file\n",
|
||||
"module m (\n",
|
||||
" a, // in the header\n",
|
||||
" b\n",
|
||||
");\n",
|
||||
" // above the input\n",
|
||||
" input a; // beside the input\n",
|
||||
" /* above the output */\n",
|
||||
" output [7:0] b; /* beside the output */\n",
|
||||
" // an ordinary body comment\n",
|
||||
" wire c;\n",
|
||||
"endmodule\n"
|
||||
);
|
||||
let out = convert(source).expect("converted");
|
||||
assert_eq!(count_comments(&out), count_comments(source), "{out}");
|
||||
for comment in [
|
||||
"// about the file",
|
||||
"// in the header",
|
||||
"// above the input",
|
||||
"// beside the input",
|
||||
"/* above the output */",
|
||||
"/* beside the output */",
|
||||
"// an ordinary body comment",
|
||||
] {
|
||||
assert!(out.contains(comment), "{comment} is gone from {out}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_written_between_the_declarations_is_left_alone() {
|
||||
let source =
|
||||
"module m (a, b);\n input a;\n parameter W = 8;\n output [W-1:0] b;\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(source).expect("converted"),
|
||||
"module m (input a, output [W-1:0] b);\n parameter W = 8;\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn body_declarations_that_are_not_ports_stay_where_they_are() {
|
||||
let source = "module m (a);\n input a;\n wire b;\n reg [3:0] c;\nendmodule\n";
|
||||
assert_eq!(
|
||||
convert(source).expect("converted"),
|
||||
"module m (input a);\n wire b;\n reg [3:0] c;\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_twenty_port_header_of_mixed_declarations_converts_whole() {
|
||||
let mut header = String::from("module wide (\n");
|
||||
let mut body = String::new();
|
||||
for n in 0..20 {
|
||||
let comma = if n == 19 { "" } else { "," };
|
||||
header.push_str(&format!(" p{n}{comma}\n"));
|
||||
match n % 5 {
|
||||
0 => body.push_str(&format!(" input p{n};\n")),
|
||||
1 => body.push_str(&format!(" input [7:0] p{n};\n")),
|
||||
2 => body.push_str(&format!(" output p{n};\n reg p{n};\n")),
|
||||
3 => {
|
||||
body.push_str(&format!(" output signed [3:0] p{n};\n wire signed [3:0] p{n};\n"))
|
||||
}
|
||||
_ => body.push_str(&format!(" inout wire p{n};\n")),
|
||||
}
|
||||
}
|
||||
let source = format!("{header});\n{body}endmodule\n");
|
||||
let out = convert(&source).expect("converted");
|
||||
assert!(out.contains(" input p0,"), "{out}");
|
||||
assert!(out.contains(" input [7:0] p1,"), "{out}");
|
||||
assert!(out.contains(" output reg p2,"), "{out}");
|
||||
assert!(out.contains(" output wire signed [3:0] p3,"), "{out}");
|
||||
assert!(out.contains(" inout wire p4,"), "{out}");
|
||||
assert!(out.contains(" inout wire p19\n);"), "{out}");
|
||||
assert!(!out.contains(" input p0;"), "the body declarations are gone: {out}");
|
||||
assert_eq!(out.matches("p19").count(), 1, "{out}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// idempotency
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn converting_a_converted_header_refuses_because_it_is_already_ansi() {
|
||||
let source = "module m (a, b);\n input a;\n output [7:0] b;\nendmodule\n";
|
||||
let once = convert(source).expect("converted");
|
||||
let again = convert(&once).expect_err("nothing left to convert");
|
||||
assert!(again.contains("already declares its ports ANSI-style"), "{again}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the refusals
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_position_in_no_module_is_refused() {
|
||||
let source = "// nothing here\nmodule m (a);\n input a;\nendmodule\n";
|
||||
let said = convert_to_ansi(&files(source), Path::new(TOP), 2).expect_err("no module");
|
||||
assert_eq!(said, "there is no module declaration at this position.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_outside_the_scope_is_refused() {
|
||||
let source = "module m (a);\n input a;\nendmodule\n";
|
||||
let said = convert_to_ansi(&files(source), Path::new("/elsewhere.sv"), 8)
|
||||
.expect_err("outside the scope");
|
||||
assert!(said.contains("is not one of the files lucisv indexes"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ansi_header_is_refused() {
|
||||
let said = refused("module m (input a);\nendmodule\n");
|
||||
assert!(said.contains("already declares its ports ANSI-style"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_with_no_ports_is_refused() {
|
||||
assert!(refused("module m ();\nendmodule\n").contains("declares no ports"));
|
||||
assert!(refused("module m;\nendmodule\n").contains("declares no ports"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interface_is_out_of_scope_this_round() {
|
||||
let source = "interface it (a);\n input a;\nendinterface\n";
|
||||
let at = source.find("it (").expect("name") as u32;
|
||||
let said = convert_to_ansi(&files(source), Path::new(TOP), at).expect_err("an interface");
|
||||
assert!(said.contains("is an `interface`, not a module"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_expression_is_refused() {
|
||||
let concat = "module m ({x, y}, b);\n input x, y;\n input b;\nendmodule\n";
|
||||
assert!(refused(concat).contains("writes a port expression"), "{}", refused(concat));
|
||||
let named = "module m (.a({x, y}), b);\n input x, y;\n input b;\nendmodule\n";
|
||||
assert!(refused(named).contains("writes a port expression"), "{}", refused(named));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_parse_is_refused() {
|
||||
let source = "module m (a);\n input a;\n always @(posedge do begin end\nendmodule\n";
|
||||
assert!(refused(source).contains("does not parse"), "{}", refused(source));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_name_with_no_declaration_is_refused() {
|
||||
let source = "module m (a, c);\n input a;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("names `c`, but its body declares no direction for it"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declaration_for_a_name_the_header_does_not_carry_is_refused() {
|
||||
let source = "module m (a);\n input a;\n output z;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(
|
||||
said.contains("declares a direction for `z`, which its header does not name"),
|
||||
"{said}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_declared_twice_is_refused() {
|
||||
let source = "module m (a);\n input a;\n input a;\nendmodule\n";
|
||||
assert!(refused(source).contains("declares a direction for `a` twice"), "{}", refused(source));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_variable_declared_twice_is_refused() {
|
||||
let source = "module m (b);\n output b;\n reg b;\n reg b;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("declares `b` twice outside its port declaration"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_complete_port_declared_again_is_refused() {
|
||||
let source = "module m (b);\n output reg b;\n reg b;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("IEEE 1800 §23.2.2.2 makes that an error"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packed_ranges_that_disagree_are_refused() {
|
||||
let source = "module m (b);\n output [7:0] b;\n reg [3:0] b;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("packed range"), "{said}");
|
||||
assert!(said.contains("asks for identical ones"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unpacked_dimensions_that_disagree_are_refused() {
|
||||
let source = "module m (mem);\n output [7:0] mem [0:3];\n reg [7:0] mem [0:7];\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("unpacked dimension"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signing_that_disagrees_is_refused() {
|
||||
let source = "module m (b);\n output signed [7:0] b;\n reg unsigned [7:0] b;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("`signed`") && said.contains("`unsigned`"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declaration_shared_with_a_local_is_refused() {
|
||||
let source = "module m (b);\n output [7:0] b;\n reg [7:0] b, scratch;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("split the declaration first"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_initialiser_is_refused() {
|
||||
let source = "module m (b);\n output b;\n reg b = 1'b0;\nendmodule\n";
|
||||
assert!(refused(source).contains("does not move an initialiser"), "{}", refused(source));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_attribute_on_an_absorbed_declaration_is_refused() {
|
||||
// `Item.span` covers the `(* ... *)`, so the deletion would take it with
|
||||
// the declaration and only the comments are carried; `(* keep *)` changes
|
||||
// what a synthesizer does, and where an attribute belongs in an ANSI port
|
||||
// list is a design question rather than a merge rule.
|
||||
let source = "module m (a);\n (* keep *) input a;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("`(* keep *)` on `m`'s declaration of `a` would be dropped"), "{said}");
|
||||
assert!(said.contains("move the attribute onto the port by hand"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_attribute_on_the_completing_declaration_is_refused_too() {
|
||||
// The other half of the merge is absorbed by the same deletion.
|
||||
let source = "module m (b);\n output b;\n (* mark_debug = \"true\" *) reg b;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("would be dropped"), "{said}");
|
||||
assert!(said.contains("mark_debug"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declaration_inside_a_generate_region_is_refused() {
|
||||
let source = "module m (b);\n output b;\n generate\n reg b;\n endgenerate\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("inside a generate region"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compiler_directives_in_the_port_list_are_refused() {
|
||||
let source = "module m (\n a,\n`ifdef WIDE\n b,\n`endif\n c\n);\n input a;\n input b;\n input c;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("port list carries compiler directives"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declaration_inside_a_conditional_arm_is_refused() {
|
||||
let source = "module m (a, b);\n input a;\n`ifdef WIDE\n input b;\n`endif\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("conditionally compiled"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directive_between_the_declarations_is_refused() {
|
||||
let source = "module m (a, b);\n input a;\n`include \"more.svh\"\n input b;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("is written among the declarations"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_written_inside_a_declaration_is_refused() {
|
||||
let source = "module m (a);\n input /* which */ a;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("inside a declaration the conversion would delete"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_comment_that_has_nowhere_to_go_is_refused() {
|
||||
let source = "module m (a, b);\n input a; // the clock\n output b;\nendmodule\n";
|
||||
let said = refused(source);
|
||||
assert!(said.contains("break `m`'s port list across lines first"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_declared_twice_in_the_workspace_is_refused() {
|
||||
let source = "module m (a);\n input a;\nendmodule\n";
|
||||
let files = vec![
|
||||
(PathBuf::from(TOP), source.to_string()),
|
||||
(PathBuf::from("/rtl/other.sv"), source.to_string()),
|
||||
];
|
||||
let said = convert_to_ansi(&files, Path::new(TOP), 8).expect_err("declared twice");
|
||||
assert!(said.contains("is declared in more than one indexed file"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_that_names_a_port_twice_is_refused() {
|
||||
let source = "module m (a, a);\n input a;\nendmodule\n";
|
||||
assert!(refused(source).contains("names `a` twice"), "{}", refused(source));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the code action
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_action_is_offered_anywhere_in_a_non_ansi_header() {
|
||||
let source = "module m (\n a,\n b\n);\n input a;\n output [7:0] b;\nendmodule\n";
|
||||
let files = files(source);
|
||||
for needle in ["module m", "m (", "a,", "b\n)"] {
|
||||
let at = source.find(needle).expect(needle) as u32;
|
||||
let titles: Vec<String> =
|
||||
port_actions(&files, Path::new(TOP), at).into_iter().map(|a| a.title).collect();
|
||||
assert!(
|
||||
titles.iter().any(|t| t == "lucisv: convert ports to ANSI (2 ports)"),
|
||||
"at {needle:?}: {titles:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_action_is_not_offered_in_the_body_or_in_an_ansi_module() {
|
||||
let source = "module m (\n a\n);\n input a;\n wire w;\n assign w = a;\nendmodule\n";
|
||||
let at = source.find("assign").expect("body") as u32;
|
||||
assert!(port_actions(&files(source), Path::new(TOP), at).is_empty());
|
||||
|
||||
let ansi = "module m (input a);\n wire w;\n assign w = a;\nendmodule\n";
|
||||
let at = ansi.find("module m").expect("header") as u32;
|
||||
let titles: Vec<String> =
|
||||
port_actions(&files(ansi), Path::new(TOP), at).into_iter().map(|a| a.title).collect();
|
||||
assert!(!titles.iter().any(|t| t.contains("convert ports to ANSI")), "{titles:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_action_says_one_port_in_the_singular() {
|
||||
let source = "module m (a);\n input a;\nendmodule\n";
|
||||
let at = source.find("module m").expect("header") as u32;
|
||||
let titles: Vec<String> =
|
||||
port_actions(&files(source), Path::new(TOP), at).into_iter().map(|a| a.title).collect();
|
||||
assert!(titles.contains(&"lucisv: convert ports to ANSI (1 port)".to_string()), "{titles:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_on_a_declaration_of_two_ports_is_written_once() {
|
||||
// The declaration is absorbed by both ports; its comment belongs to the
|
||||
// first of them and must not be copied onto the second.
|
||||
let source = "module m (\n a,\n b\n);\n input a, b; // both of them\nendmodule\n";
|
||||
let out = convert(source).expect("converted");
|
||||
assert_eq!(out.matches("// both of them").count(), 1, "{out}");
|
||||
assert_eq!(out, "module m (\n input a, // both of them\n input b\n);\nendmodule\n");
|
||||
}
|
||||
@@ -10,9 +10,10 @@ use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Instant;
|
||||
|
||||
use vlog_parser::ast::{Item, ItemKind, ListElem, PortList};
|
||||
use vlog_refactor::{
|
||||
add_port, instantiation_plan, module_definition, port_actions, prepare_rename, rename, Layout,
|
||||
ModuleRef,
|
||||
add_port, convert_to_ansi, expand_wildcard, instantiation_plan, module_definition,
|
||||
port_actions, prepare_rename, rename, Layout, ModuleRef,
|
||||
};
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
@@ -260,3 +261,395 @@ fn module_names_in(text: &str) -> Vec<String> {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_expanded_in_the_corpus_is_something_the_formatter_accepts() {
|
||||
// The `.*` sites in the corpus are real ones — testbenches and formal
|
||||
// wrappers, where the wildcard is written most — and the property that
|
||||
// matters is the same one the whole formatter lives by: what the
|
||||
// refactoring writes must format, and formatting it twice must not move
|
||||
// it. The edit is applied to a *copy* of the text; nothing is written back
|
||||
// to `corpus/`.
|
||||
let Some(files) = corpus() else { return };
|
||||
let sources = read(&files);
|
||||
assert!(!sources.is_empty(), "corpus/ exists but holds no Verilog");
|
||||
let config = vlog_formatter::Config::default();
|
||||
|
||||
let mut expanded: Vec<String> = Vec::new();
|
||||
let mut refused: Vec<String> = Vec::new();
|
||||
for (path, text) in &sources {
|
||||
if expanded.len() >= 3 {
|
||||
break;
|
||||
}
|
||||
let Some(offset) = wildcard_offset(text) else { continue };
|
||||
let started = Instant::now();
|
||||
match expand_wildcard(&sources, path, offset) {
|
||||
Err(said) => refused.push(format!("{}: {said}", path.display())),
|
||||
Ok(edit) => {
|
||||
let edits = edit.edits_for(path);
|
||||
assert!(!edits.is_empty(), "{} was expanded with no edit", path.display());
|
||||
let mut copy = text.clone();
|
||||
for change in edits.iter().rev() {
|
||||
copy.replace_range(
|
||||
change.range.start as usize..change.range.end as usize,
|
||||
&change.new_text,
|
||||
);
|
||||
}
|
||||
assert_ne!(©, text, "the expansion changed nothing in {}", path.display());
|
||||
let once = vlog_formatter::format_source(©, &config).unwrap_or_else(|e| {
|
||||
panic!("the formatter refuses the expansion of {}: {e}\n{copy}", path.display())
|
||||
});
|
||||
let twice =
|
||||
vlog_formatter::format_source(&once, &config).expect("formats a second time");
|
||||
assert_eq!(once, twice, "formatting {}'s expansion diverges", path.display());
|
||||
expanded.push(format!(
|
||||
"{} in {:.2}s ({} edits)",
|
||||
path.display(),
|
||||
started.elapsed().as_secs_f64(),
|
||||
edits.len()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
println!("corpus `.*` expansions:\n {}", expanded.join("\n "));
|
||||
if !refused.is_empty() {
|
||||
println!("refused:\n {}", refused.join("\n "));
|
||||
}
|
||||
assert!(expanded.len() >= 3, "three real expansions, got {expanded:?}; refused: {refused:?}");
|
||||
}
|
||||
|
||||
/// The offset of the first `.*` connection a file writes, found the way the
|
||||
/// plan's census counts them: a `.*` followed by a `,` or a `)`.
|
||||
fn wildcard_offset(text: &str) -> Option<u32> {
|
||||
let mut at = 0usize;
|
||||
while let Some(found) = text.get(at..)?.find(".*") {
|
||||
let start = at + found;
|
||||
let rest = text.get(start + 2..)?.trim_start();
|
||||
if rest.starts_with(',') || rest.starts_with(')') {
|
||||
return Some(start as u32);
|
||||
}
|
||||
at = start + 2;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// TODO §51 — the non-ANSI → ANSI conversion
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The census the plan asks for: how many modules in the corpus write a
|
||||
/// Verilog-2001 header, and does every one of them convert?
|
||||
///
|
||||
/// **The count is zero, and that is the finding.** common_cells, ibex,
|
||||
/// opentitan and picorv32 are all written ANSI-style — even picorv32, the
|
||||
/// oldest of them — so there is no non-ANSI header in 860 files to convert.
|
||||
/// The assertion is therefore written as a census rather than as a number: it
|
||||
/// converts *every* one it finds, and stays honest the day the corpus gains
|
||||
/// one. The real-RTL exercise the conversion does get is
|
||||
/// `an_ansi_header_written_the_2001_way_converts_back_to_itself` below, which
|
||||
/// makes its material out of the corpus's own ANSI modules.
|
||||
#[test]
|
||||
fn every_non_ansi_module_in_the_corpus_converts() {
|
||||
let Some(files) = corpus() else { return };
|
||||
let sources = read(&files);
|
||||
assert!(!sources.is_empty(), "corpus/ exists but holds no Verilog");
|
||||
let config = vlog_formatter::Config::default();
|
||||
|
||||
let sites: Vec<(PathBuf, String, u32)> = sources
|
||||
.iter()
|
||||
.flat_map(|(path, text)| {
|
||||
non_ansi_modules(text).into_iter().map(move |(name, at)| (path.clone(), name, at))
|
||||
})
|
||||
.collect();
|
||||
println!("corpus non-ANSI module headers: {}", sites.len());
|
||||
|
||||
let mut refused: Vec<String> = Vec::new();
|
||||
for (path, name, at) in &sites {
|
||||
let Some((_, text)) = sources.iter().find(|(held, _)| held == path) else { continue };
|
||||
match convert_to_ansi(&sources, path, *at) {
|
||||
Err(said) => refused.push(format!("{} :: {name}: {said}", path.display())),
|
||||
Ok(edit) => {
|
||||
let copy = edited(text, edit.edits_for(path));
|
||||
let once = vlog_formatter::format_source(©, &config).unwrap_or_else(|e| {
|
||||
panic!("the formatter refuses {} :: {name}: {e}\n{copy}", path.display())
|
||||
});
|
||||
let twice =
|
||||
vlog_formatter::format_source(&once, &config).expect("formats a second time");
|
||||
assert_eq!(once, twice, "{} :: {name} does not converge", path.display());
|
||||
assert_eq!(
|
||||
port_names(©, name),
|
||||
port_names(text, name),
|
||||
"{} :: {name} changed its port list",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
println!("refused: {}\n {}", refused.len(), refused.join("\n "));
|
||||
}
|
||||
|
||||
/// Real RTL, made non-ANSI and converted back.
|
||||
///
|
||||
/// The corpus writes no Verilog-2001 header, so this test manufactures them out
|
||||
/// of real ones: a corpus module's ANSI port list is rewritten the 2001 way —
|
||||
/// bare names in the header, each declaration moved into the body verbatim —
|
||||
/// and `convert_to_ansi` is asked to undo it. Three properties, on real port
|
||||
/// lists of up to a few dozen ports:
|
||||
///
|
||||
/// * the converted file **parses with no diagnostic** and formats, and
|
||||
/// formatting it twice does not move it;
|
||||
/// * its module declares the **same ports, in the same order, with the same
|
||||
/// direction, net, type, signing and dimensions** as the module the corpus
|
||||
/// ships — [`signature`], which is the whole of what the conversion promises;
|
||||
/// * and the file's comment count is unchanged.
|
||||
///
|
||||
/// Not byte-identity after formatting: the formatter keeps the *author's*
|
||||
/// column alignment in an ANSI port list, and a refactoring writes edited
|
||||
/// source rather than formatted source, so the alignment the corpus wrote by
|
||||
/// hand is not something the conversion undertakes to reproduce.
|
||||
///
|
||||
/// Nothing is written back to `corpus/`; every edit is applied to a copy.
|
||||
#[test]
|
||||
fn an_ansi_header_written_the_2001_way_converts_back_to_itself() {
|
||||
let Some(files) = corpus() else { return };
|
||||
let sources = read(&files);
|
||||
let config = vlog_formatter::Config::default();
|
||||
|
||||
let mut done: Vec<String> = Vec::new();
|
||||
for (path, text) in &sources {
|
||||
if done.len() >= 5 {
|
||||
break;
|
||||
}
|
||||
let Some((name, legacy)) = as_non_ansi(text) else { continue };
|
||||
let mut scratch = sources.clone();
|
||||
let Some(slot) = scratch.iter_mut().find(|(held, _)| held == path) else { continue };
|
||||
slot.1 = legacy.clone();
|
||||
let at = legacy.find(&format!("module {name}")).expect("the header") as u32;
|
||||
|
||||
let started = Instant::now();
|
||||
let edit = match convert_to_ansi(&scratch, path, at) {
|
||||
Ok(edit) => edit,
|
||||
Err(said) => {
|
||||
println!("skipped {} :: {name}: {said}", path.display());
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let back = edited(&legacy, edit.edits_for(path));
|
||||
assert!(
|
||||
vlog_parser::parse_source_tolerant(&back).1.is_empty(),
|
||||
"{} :: {name} does not parse after the conversion\n{back}",
|
||||
path.display()
|
||||
);
|
||||
assert_eq!(
|
||||
signature(&back, &name),
|
||||
signature(text, &name),
|
||||
"{} :: {name} did not come back to what the corpus ships",
|
||||
path.display()
|
||||
);
|
||||
assert_eq!(
|
||||
back.matches("//").count() + back.matches("/*").count(),
|
||||
text.matches("//").count() + text.matches("/*").count(),
|
||||
"{} :: {name} lost or gained a comment",
|
||||
path.display()
|
||||
);
|
||||
let once = vlog_formatter::format_source(&back, &config).expect("the conversion formats");
|
||||
let twice = vlog_formatter::format_source(&once, &config).expect("formats a second time");
|
||||
assert_eq!(once, twice, "{} :: {name} does not converge", path.display());
|
||||
done.push(format!(
|
||||
"{} :: {name} in {:.2}s",
|
||||
path.display(),
|
||||
started.elapsed().as_secs_f64()
|
||||
));
|
||||
}
|
||||
println!("round-tripped:\n {}", done.join("\n "));
|
||||
assert!(done.len() >= 5, "five real round trips, got {done:?}");
|
||||
}
|
||||
|
||||
/// Every module in a file whose header is a `PortList::NonAnsi`, with the
|
||||
/// offset of its name.
|
||||
fn non_ansi_modules(text: &str) -> Vec<(String, u32)> {
|
||||
fn walk(items: &[Item], out: &mut Vec<(String, u32)>) {
|
||||
for item in items {
|
||||
match &item.kind {
|
||||
ItemKind::Module(module) => {
|
||||
if matches!(module.ports, PortList::NonAnsi(_)) {
|
||||
out.push((module.name.clone(), module.name_span.start));
|
||||
}
|
||||
walk(&module.items, out);
|
||||
}
|
||||
ItemKind::Package { items, .. } => walk(items, out),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk(&vlog_parser::parse_source_tolerant(text).0.items, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// What a module's ANSI port list says, port by port: direction, net type,
|
||||
/// data type, signing, packed and unpacked dimensions, and the name.
|
||||
///
|
||||
/// The whole of what the conversion promises, and the one thing a
|
||||
/// non-ANSI header and the ANSI header it becomes must agree about.
|
||||
/// Whitespace is taken out, since a `[7 : 0]` and a `[7:0]` are one range.
|
||||
fn signature(text: &str, module: &str) -> Vec<String> {
|
||||
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
||||
fn walk<'t>(items: &'t [Item], module: &str) -> Option<&'t vlog_parser::ast::Module> {
|
||||
for item in items {
|
||||
match &item.kind {
|
||||
ItemKind::Module(found) if found.name == module => return Some(found),
|
||||
ItemKind::Module(found) => {
|
||||
if let Some(found) = walk(&found.items, module) {
|
||||
return Some(found);
|
||||
}
|
||||
}
|
||||
ItemKind::Package { items, .. } => {
|
||||
if let Some(found) = walk(items, module) {
|
||||
return Some(found);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
let tight = |s: &str| s.chars().filter(|c| !c.is_whitespace()).collect::<String>();
|
||||
let dims = |list: &[vlog_parser::ast::Dim]| -> String {
|
||||
list.iter()
|
||||
.map(|d| tight(text.get(d.span.start as usize..d.span.end as usize).unwrap_or("")))
|
||||
.collect()
|
||||
};
|
||||
let Some(module) = walk(&tree.items, module) else { return Vec::new() };
|
||||
let PortList::Ansi(ports) = &module.ports else { return Vec::new() };
|
||||
ports
|
||||
.iter()
|
||||
.filter_map(ListElem::ok)
|
||||
.map(|p| {
|
||||
format!(
|
||||
"{}|{}|{}|{}|{}|{}|{}",
|
||||
p.dir.clone().unwrap_or_default(),
|
||||
p.net.clone().unwrap_or_default(),
|
||||
p.ty.name,
|
||||
p.ty.signing.clone().unwrap_or_default(),
|
||||
dims(&p.ty.packed),
|
||||
dims(&p.unpacked),
|
||||
p.name
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The port names a module declares, in order.
|
||||
fn port_names(text: &str, module: &str) -> Vec<String> {
|
||||
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
||||
fn walk(items: &[Item], module: &str) -> Option<Vec<String>> {
|
||||
for item in items {
|
||||
match &item.kind {
|
||||
ItemKind::Module(found) if found.name == module => {
|
||||
return Some(match &found.ports {
|
||||
PortList::Ansi(ports) => {
|
||||
ports.iter().filter_map(ListElem::ok).map(|p| p.name.clone()).collect()
|
||||
}
|
||||
PortList::NonAnsi(ports) => {
|
||||
ports.iter().filter_map(ListElem::ok).map(|p| p.name.clone()).collect()
|
||||
}
|
||||
PortList::Empty | PortList::None => Vec::new(),
|
||||
})
|
||||
}
|
||||
ItemKind::Module(found) => {
|
||||
if let Some(names) = walk(&found.items, module) {
|
||||
return Some(names);
|
||||
}
|
||||
}
|
||||
ItemKind::Package { items, .. } => {
|
||||
if let Some(names) = walk(items, module) {
|
||||
return Some(names);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
walk(&tree.items, module).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// One file's first ANSI module rewritten the Verilog-2001 way: the header
|
||||
/// keeps the names, each declaration moves into the body verbatim.
|
||||
///
|
||||
/// `None` for a file with no module the rewrite is faithful for — a port with
|
||||
/// a default value, a comment inside the list, an interface port or a
|
||||
/// direction-less continuation port all make the two spellings say different
|
||||
/// things, and this is a test fixture rather than a second refactoring.
|
||||
fn as_non_ansi(text: &str) -> Option<(String, String)> {
|
||||
let (tree, diagnostics) = vlog_parser::parse_source_tolerant(text);
|
||||
if !diagnostics.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let ItemKind::Module(module) = &tree
|
||||
.items
|
||||
.iter()
|
||||
.find(|item| {
|
||||
matches!(&item.kind, ItemKind::Module(m)
|
||||
if m.kw == "module" && m.port_directives.is_empty())
|
||||
})?
|
||||
.kind
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let PortList::Ansi(ports) = &module.ports else { return None };
|
||||
let ports: Vec<&vlog_parser::ast::AnsiPort> =
|
||||
ports.iter().map(ListElem::ok).collect::<Option<Vec<_>>>()?;
|
||||
let (first, last) = (ports.first()?, ports.last()?);
|
||||
let list = text.get(first.span.start as usize..last.span.end as usize)?;
|
||||
if list.contains("//") || list.contains("/*") {
|
||||
return None;
|
||||
}
|
||||
for port in &ports {
|
||||
let plain = port.dir.is_some()
|
||||
&& port.default.is_none()
|
||||
&& port.meta.leading.is_empty()
|
||||
&& port.meta.trailing.is_none()
|
||||
&& port.meta.before_sep.is_empty()
|
||||
&& port.after_dir.is_empty()
|
||||
&& port.before_name.is_empty()
|
||||
&& port.ty.extra.is_none()
|
||||
&& port.ty.virt.is_none();
|
||||
if !plain {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
// The header's `;`, which is where the body declarations go.
|
||||
let semi = last.span.end as usize + text.get(last.span.end as usize..)?.find(';')? + 1;
|
||||
// Each element is replaced by its own name, so the list keeps the layout
|
||||
// the file wrote — the conversion is asked to put the declarations back,
|
||||
// not to reflow anything.
|
||||
let mut out = String::new();
|
||||
let mut cursor = 0usize;
|
||||
for port in &ports {
|
||||
out.push_str(text.get(cursor..port.span.start as usize)?);
|
||||
out.push_str(&port.name);
|
||||
cursor = port.span.end as usize;
|
||||
}
|
||||
out.push_str(text.get(cursor..semi)?);
|
||||
for port in &ports {
|
||||
out.push_str("\n ");
|
||||
out.push_str(text.get(port.span.start as usize..port.span.end as usize)?);
|
||||
out.push(';');
|
||||
}
|
||||
out.push_str(text.get(semi..)?);
|
||||
Some((module.name.clone(), out))
|
||||
}
|
||||
|
||||
/// A copy of `text` with one file's edits applied.
|
||||
fn edited(text: &str, edits: &[vlog_refactor::TextEdit]) -> String {
|
||||
let mut copy = text.to_string();
|
||||
for change in edits.iter().rev() {
|
||||
copy.replace_range(
|
||||
change.range.start as usize..change.range.end as usize,
|
||||
&change.new_text,
|
||||
);
|
||||
}
|
||||
copy
|
||||
}
|
||||
@@ -0,0 +1,414 @@
|
||||
//! Behavior tests for `expand_wildcard`: what the `.*` expansion writes, what
|
||||
//! it refuses, and what the formatter says about the result.
|
||||
//!
|
||||
//! Every test states the whole workspace and asserts on the *applied* text,
|
||||
//! because that is what the user ends up with. A refusal is asserted on its
|
||||
//! sentence, since that sentence is the entire answer the editor shows.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use vlog_refactor::{expand_wildcard, port_actions, RefactorEdit};
|
||||
|
||||
/// A workspace: `(path, text)` pairs, the shape the engine takes.
|
||||
fn files(pairs: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
|
||||
pairs.iter().map(|(path, text)| (PathBuf::from(*path), text.to_string())).collect()
|
||||
}
|
||||
|
||||
fn at(text: &str, needle: &str) -> u32 {
|
||||
text.find(needle).expect("needle present") as u32
|
||||
}
|
||||
|
||||
/// One file's text with the refactoring applied, the way a client applies a
|
||||
/// `WorkspaceEdit`: back to front, so every range still means what it said.
|
||||
fn applied(files: &[(PathBuf, String)], edit: &RefactorEdit, path: &str) -> String {
|
||||
let path = PathBuf::from(path);
|
||||
let mut text = files
|
||||
.iter()
|
||||
.find(|(p, _)| *p == path)
|
||||
.map(|(_, text)| text.clone())
|
||||
.expect("a file in the workspace");
|
||||
for change in edit.edits_for(&path).iter().rev() {
|
||||
text.replace_range(
|
||||
change.range.start as usize..change.range.end as usize,
|
||||
&change.new_text,
|
||||
);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// The three-port module every test instantiates.
|
||||
const SUB: &str =
|
||||
"module sub (\n input logic clk,\n input logic rst,\n output logic done\n);\nendmodule\n";
|
||||
|
||||
/// The workspace, the expansion, and the cursor's file afterwards.
|
||||
fn expand(top: &str, needle: &str) -> Result<(RefactorEdit, String), String> {
|
||||
let workspace = files(&[("/rtl/sub.sv", SUB), ("/rtl/top.sv", top)]);
|
||||
let edit = expand_wildcard(&workspace, &PathBuf::from("/rtl/top.sv"), at(top, needle))?;
|
||||
let text = applied(&workspace, &edit, "/rtl/top.sv");
|
||||
Ok((edit, text))
|
||||
}
|
||||
|
||||
/// What the refusal at this cursor says.
|
||||
fn refusal(top: &str, needle: &str) -> String {
|
||||
expand(top, needle).expect_err("a refusal").to_string()
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// what it writes
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_wildcard_becomes_every_port_the_instance_does_not_name() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (\n .clk(clk),\n .*\n );\nendmodule\n";
|
||||
let (edit, text) = expand(top, ".*").expect("expands");
|
||||
assert_eq!(
|
||||
text,
|
||||
"module top;\n logic clk, rst, done;\n sub u_sub (\n .clk(clk),\n .rst(rst),\n .done(done)\n );\nendmodule\n"
|
||||
);
|
||||
assert_eq!(edit.file_count(), 1, "nothing outside the cursor's file is touched");
|
||||
assert!(edit.warnings.is_empty(), "{:?}", edit.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inline_list_stays_inline() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.clk(clk), .*);\nendmodule\n";
|
||||
let (_, text) = expand(top, ".*").expect("expands");
|
||||
assert_eq!(
|
||||
text,
|
||||
"module top;\n logic clk, rst, done;\n sub u_sub (.clk(clk), .rst(rst), .done(done));\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_alone_on_its_line_writes_one_connection_per_line() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (\n .*\n );\nendmodule\n";
|
||||
let (_, text) = expand(top, ".*").expect("expands");
|
||||
assert_eq!(
|
||||
text,
|
||||
"module top;\n logic clk, rst, done;\n sub u_sub (\n .clk(clk),\n .rst(rst),\n .done(done)\n );\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_alone_inline_writes_one_line() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.*);\nendmodule\n";
|
||||
let (_, text) = expand(top, ".*").expect("expands");
|
||||
assert_eq!(
|
||||
text,
|
||||
"module top;\n logic clk, rst, done;\n sub u_sub (.clk(clk), .rst(rst), .done(done));\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_with_no_signal_in_scope_is_written_unconnected_and_said_out_loud() {
|
||||
let top = "module top;\n logic clk, rst;\n sub u_sub (.*);\nendmodule\n";
|
||||
let (edit, text) = expand(top, ".*").expect("expands");
|
||||
assert_eq!(
|
||||
text,
|
||||
"module top;\n logic clk, rst;\n sub u_sub (.clk(clk), .rst(rst), .done());\nendmodule\n"
|
||||
);
|
||||
let warning = edit.warnings.join("\n");
|
||||
assert!(warning.contains("`done`"), "{warning}");
|
||||
assert!(warning.contains("no net, variable or port named"), "{warning}");
|
||||
assert!(warning.contains("top.sv:3"), "the site is named: {warning}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_same_named_parameter_is_not_a_signal_the_wildcard_binds() {
|
||||
// IEEE 1800 §23.3.2.4: `.*` binds a port to a net or variable of the same
|
||||
// name. `done` here is a constant, and `.done(done)` would connect an
|
||||
// output port to it — legal-looking, silent, and wrong.
|
||||
let top = "module top;\n logic clk, rst;\n localparam int done = 1;\n sub u_sub (.*);\nendmodule\n";
|
||||
let (edit, text) = expand(top, ".*").expect("expands");
|
||||
assert!(text.contains(".done()"), "{text}");
|
||||
assert!(!text.contains(".done(done)"), "the parameter is not bound: {text}");
|
||||
assert!(edit.warnings.join("\n").contains("`done`"), "{:?}", edit.warnings);
|
||||
|
||||
// ...and the same for a `parameter` in the header.
|
||||
let top = "module top #(parameter int done = 1) ();\n logic clk, rst;\n sub u_sub (.*);\nendmodule\n";
|
||||
let (_, text) = expand(top, ".*").expect("expands");
|
||||
assert!(text.contains(".done()"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_genvar_of_the_same_name_is_not_bound_either() {
|
||||
let sub = "module sub (\n input logic clk,\n input logic i\n);\nendmodule\n";
|
||||
let top = "module top;\n logic clk;\n for (genvar i = 0; i < 2; i++) begin : g\n sub u_sub (.*);\n end\nendmodule\n";
|
||||
let workspace = files(&[("/rtl/sub.sv", sub), ("/rtl/top.sv", top)]);
|
||||
let edit =
|
||||
expand_wildcard(&workspace, &PathBuf::from("/rtl/top.sv"), at(top, ".*")).expect("expands");
|
||||
let text = applied(&workspace, &edit, "/rtl/top.sv");
|
||||
assert!(text.contains(".clk(clk), .i()"), "a genvar is not a net or a variable: {text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generate_blocks_own_declaration_is_in_scope_and_so_is_the_modules() {
|
||||
let top = "module top;\n logic clk, rst;\n if (1) begin : g\n logic done;\n sub u_sub (.*);\n end\nendmodule\n";
|
||||
let (edit, text) = expand(top, ".*").expect("expands");
|
||||
assert!(
|
||||
text.contains("sub u_sub (.clk(clk), .rst(rst), .done(done));"),
|
||||
"the block's `done` and the module's `clk`/`rst`: {text}"
|
||||
);
|
||||
assert!(edit.warnings.is_empty(), "{:?}", edit.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ports_are_written_in_the_modules_declaration_order() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.done(done), .*);\nendmodule\n";
|
||||
let (_, text) = expand(top, ".*").expect("expands");
|
||||
assert!(text.contains(".done(done), .clk(clk), .rst(rst)"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_written_before_an_explicit_connection_expands_in_place() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.*, .done(done));\nendmodule\n";
|
||||
let (_, text) = expand(top, ".*").expect("expands");
|
||||
assert!(text.contains("(.clk(clk), .rst(rst), .done(done))"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_implicit_or_empty_connection_counts_as_explicit() {
|
||||
// `.clk` and `.rst()` are connections the source wrote, so `.*` never
|
||||
// bound those ports and the expansion must not write them a second time.
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.clk, .rst(), .*);\nendmodule\n";
|
||||
let (_, text) = expand(top, ".*").expect("expands");
|
||||
assert_eq!(
|
||||
text,
|
||||
"module top;\n logic clk, rst, done;\n sub u_sub (.clk, .rst(), .done(done));\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// comments
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_comment_after_the_wildcard_stays_with_the_first_connection() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (\n .clk(clk),\n .* // and the rest\n );\nendmodule\n";
|
||||
let (_, text) = expand(top, ".*").expect("expands");
|
||||
assert_eq!(
|
||||
text,
|
||||
"module top;\n logic clk, rst, done;\n sub u_sub (\n .clk(clk),\n .rst(rst), // and the rest\n .done(done)\n );\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_comment_before_the_wildcard_stays_before_the_first_connection() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (\n .clk(clk),\n // bind the rest\n .*\n );\nendmodule\n";
|
||||
let (_, text) = expand(top, ".*").expect("expands");
|
||||
assert_eq!(
|
||||
text,
|
||||
"module top;\n logic clk, rst, done;\n sub u_sub (\n .clk(clk),\n // bind the rest\n .rst(rst),\n .done(done)\n );\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_comment_written_inside_the_wildcard_refuses_rather_than_dropping_it() {
|
||||
// The comment sits between the `.` and the `*`, inside the element the
|
||||
// expansion replaces. Comments are never dropped (invariant 3), and lucisv
|
||||
// will not decide where this one should move.
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (. /* here */ *);\nendmodule\n";
|
||||
let said = refusal(top, ". /* here */ *");
|
||||
assert!(said.contains("comments are never dropped"), "{said}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// refusals
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_instantiation_without_a_wildcard_is_refused() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.clk(clk));\nendmodule\n";
|
||||
assert!(refusal(top, "u_sub").contains("writes no `.*` to expand"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_position_that_is_not_an_instantiation_is_refused() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.*);\nendmodule\n";
|
||||
assert!(refusal(top, "logic clk").contains("no module instantiation at this position"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_positional_connection_list_is_refused() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (clk, rst, done);\nendmodule\n";
|
||||
let said = refusal(top, "u_sub");
|
||||
assert!(said.contains("by position"), "{said}");
|
||||
assert!(said.contains("no `.*` to expand"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_wildcards_in_one_instance_are_refused() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.*, .*);\nendmodule\n";
|
||||
let said = refusal(top, ".*");
|
||||
assert!(said.contains("writes `.*` 2 times"), "{said}");
|
||||
assert!(said.contains("illegal"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_inside_a_bind_directive_is_refused() {
|
||||
let top = "module top;\n logic clk, rst, done;\nendmodule\nbind top sub u_sub (.*);\n";
|
||||
let said = refusal(top, ".*");
|
||||
assert!(said.contains("`bind` directive"), "{said}");
|
||||
assert!(said.contains("target's scope"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_the_workspace_does_not_declare_is_refused() {
|
||||
let top = "module top;\n logic clk;\n nowhere u_x (.*);\nendmodule\n";
|
||||
assert!(refusal(top, ".*").contains("indexes no module named `nowhere`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_declared_twice_is_refused() {
|
||||
let workspace = files(&[
|
||||
("/rtl/sub.sv", SUB),
|
||||
("/rtl/other.sv", SUB),
|
||||
("/rtl/top.sv", "module top;\n logic clk, rst, done;\n sub u_sub (.*);\nendmodule\n"),
|
||||
]);
|
||||
let top = &workspace[2].1.clone();
|
||||
let said = expand_wildcard(&workspace, &PathBuf::from("/rtl/top.sv"), at(top, ".*"))
|
||||
.expect_err("a refusal");
|
||||
assert!(said.contains("declared in more than one indexed file"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_parse_is_refused_on_either_side() {
|
||||
// The cursor's own file.
|
||||
let top = "module top;\n logic clk;\n sub u_sub (.*);\n always @(begin\nendmodule\n";
|
||||
let said = refusal(top, ".*");
|
||||
assert!(said.contains("does not parse"), "{said}");
|
||||
assert!(said.contains("top.sv"), "{said}");
|
||||
|
||||
// ...and the module's.
|
||||
let workspace = files(&[
|
||||
("/rtl/sub.sv", "module sub (input logic clk);\n always @(begin\nendmodule\n"),
|
||||
("/rtl/top.sv", "module top;\n logic clk;\n sub u_sub (.*);\nendmodule\n"),
|
||||
]);
|
||||
let top = workspace[1].1.clone();
|
||||
let said = expand_wildcard(&workspace, &PathBuf::from("/rtl/top.sv"), at(&top, ".*"))
|
||||
.expect_err("a refusal");
|
||||
assert!(said.contains("sub.sv"), "{said}");
|
||||
assert!(said.contains("does not parse"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_list_carrying_compiler_directives_is_refused() {
|
||||
let workspace = files(&[
|
||||
(
|
||||
"/rtl/sub.sv",
|
||||
"module sub (\n input logic clk\n`ifdef HAS_RST\n , input logic rst\n`endif\n);\nendmodule\n",
|
||||
),
|
||||
("/rtl/top.sv", "module top;\n logic clk, rst;\n sub u_sub (.*);\nendmodule\n"),
|
||||
]);
|
||||
let top = workspace[1].1.clone();
|
||||
let said = expand_wildcard(&workspace, &PathBuf::from("/rtl/top.sv"), at(&top, ".*"))
|
||||
.expect_err("a refusal");
|
||||
assert!(said.contains("carries compiler directives"), "{said}");
|
||||
assert!(said.contains("depends on the configuration"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_connection_list_carrying_compiler_directives_is_refused() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (\n .clk(clk),\n`ifdef X\n .rst(rst),\n`endif\n .*\n );\nendmodule\n";
|
||||
let said = refusal(top, ".*\n )");
|
||||
assert!(said.contains("connection list carries compiler directives"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_that_binds_nothing_is_refused_rather_than_deleted() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.clk(clk), .rst(rst), .done(done), .*);\nendmodule\n";
|
||||
let said = refusal(top, ".*");
|
||||
assert!(said.contains("already connects every port"), "{said}");
|
||||
assert!(said.contains("binds nothing"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_statement_declaring_several_instances_asks_for_a_cursor_on_one() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_a (.*), u_b (.*);\nendmodule\n";
|
||||
let said = refusal(top, "sub u_a");
|
||||
assert!(said.contains("declares 2 instances"), "{said}");
|
||||
assert!(said.contains("put the cursor on the one to expand"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_outside_the_workspace_is_refused() {
|
||||
let workspace = files(&[("/rtl/sub.sv", SUB)]);
|
||||
let said =
|
||||
expand_wildcard(&workspace, &PathBuf::from("/rtl/elsewhere.sv"), 0).expect_err("a refusal");
|
||||
assert!(said.contains("is not one of the files lucisv indexes"), "{said}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the code action, and what the formatter says
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_action_is_offered_at_the_wildcard_with_its_count_in_the_title() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.clk(clk), .*);\nendmodule\n";
|
||||
let workspace = files(&[("/rtl/sub.sv", SUB), ("/rtl/top.sv", top)]);
|
||||
let actions = port_actions(&workspace, &PathBuf::from("/rtl/top.sv"), at(top, ".*"));
|
||||
let titles: Vec<&str> = actions.iter().map(|a| a.title.as_str()).collect();
|
||||
assert!(titles.contains(&"lucisv: expand .* (2 connections)"), "{titles:?}");
|
||||
// The wildcard is why `propagate` declines here, so it is the only offer.
|
||||
assert_eq!(titles.len(), 1, "{titles:?}");
|
||||
|
||||
// One connection is one connection, not "1 connections".
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.clk(clk), .rst(rst), .*);\nendmodule\n";
|
||||
let workspace = files(&[("/rtl/sub.sv", SUB), ("/rtl/top.sv", top)]);
|
||||
let actions = port_actions(&workspace, &PathBuf::from("/rtl/top.sv"), at(top, ".*"));
|
||||
assert_eq!(actions[0].title, "lucisv: expand .* (1 connection)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_is_offered_where_the_expansion_would_be_refused() {
|
||||
let top = "module top;\n logic clk, rst, done;\n sub u_sub (.*, .*);\nendmodule\n";
|
||||
let workspace = files(&[("/rtl/sub.sv", SUB), ("/rtl/top.sv", top)]);
|
||||
let actions = port_actions(&workspace, &PathBuf::from("/rtl/top.sv"), at(top, ".*"));
|
||||
assert!(actions.is_empty(), "{:?}", actions.iter().map(|a| &a.title).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_expanded_file_formats_and_formatting_it_again_changes_nothing() {
|
||||
let config = vlog_formatter::Config::default();
|
||||
for top in [
|
||||
"module top;\n logic clk, rst, done;\n sub u_sub (.clk(clk), .*);\nendmodule\n",
|
||||
"module top;\n logic clk, rst;\n sub u_sub (\n .clk(clk),\n .* // the rest\n );\nendmodule\n",
|
||||
"module top;\n logic clk, rst, done;\n sub u_sub (\n .*\n );\nendmodule\n",
|
||||
] {
|
||||
let (_, text) = expand(top, ".*").expect("expands");
|
||||
let once = vlog_formatter::format_source(&text, &config)
|
||||
.unwrap_or_else(|e| panic!("the formatter refuses the expansion: {e}\n{text}"));
|
||||
let twice = vlog_formatter::format_source(&once, &config).expect("formats again");
|
||||
assert_eq!(once, twice, "formatting the expansion does not converge");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escaped_port_name_is_terminated_on_both_sides_of_the_parens() {
|
||||
// An escaped identifier runs to the next whitespace and to nothing else
|
||||
// (IEEE 1800 §5.6.1), so `.\my-port(\my-port)` is one token that swallows
|
||||
// the parens and the rest of the line. The instantiation skeleton learned
|
||||
// this from QA; the expansion writes the same shape.
|
||||
let sub = "module sub (\n input logic \\my-port ,\n input logic clk\n);\nendmodule\n";
|
||||
let top = "module top;\n logic clk;\n logic \\my-port ;\n sub u_sub (.*);\nendmodule\n";
|
||||
let workspace = files(&[("/rtl/sub.sv", sub), ("/rtl/top.sv", top)]);
|
||||
let edit =
|
||||
expand_wildcard(&workspace, &PathBuf::from("/rtl/top.sv"), at(top, ".*")).expect("expands");
|
||||
let text = applied(&workspace, &edit, "/rtl/top.sv");
|
||||
assert!(text.contains("(.\\my-port (\\my-port ), .clk(clk))"), "{text}");
|
||||
let (_, diagnostics) = vlog_parser::parse_source_tolerant(&text);
|
||||
assert!(diagnostics.is_empty(), "{diagnostics:?}\n{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unbound_escaped_port_is_terminated_too() {
|
||||
let sub = "module sub (\n input logic \\my-port ,\n input logic clk\n);\nendmodule\n";
|
||||
let top = "module top;\n logic clk;\n sub u_sub (.*);\nendmodule\n";
|
||||
let workspace = files(&[("/rtl/sub.sv", sub), ("/rtl/top.sv", top)]);
|
||||
let edit =
|
||||
expand_wildcard(&workspace, &PathBuf::from("/rtl/top.sv"), at(top, ".*")).expect("expands");
|
||||
let text = applied(&workspace, &edit, "/rtl/top.sv");
|
||||
assert!(text.contains("(.\\my-port (), .clk(clk))"), "{text}");
|
||||
let (_, diagnostics) = vlog_parser::parse_source_tolerant(&text);
|
||||
assert!(diagnostics.is_empty(), "{diagnostics:?}\n{text}");
|
||||
}
|
||||
@@ -88,6 +88,28 @@ fn a_connection_with_no_signal_of_that_name_is_left_as_a_todo() {
|
||||
assert!(warnings(&edit).contains("`u1` (top.sv:2)"), "{:?}", edit.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_port_may_leave_a_second_todo_where_the_first_one_already_is() {
|
||||
// A module gains its ports one at a time, so the second addition finds the
|
||||
// first one's `/* TODO: connect */` already sitting in the file and writes
|
||||
// another. `check::never_dropped` refuses an edit that writes a comment it
|
||||
// is not deleting — this is the one flow that legitimately does, and the
|
||||
// reason the rule keeps a whitelist of the text the engine writes itself.
|
||||
let first = files(&[
|
||||
("/rtl/sub.sv", SUB),
|
||||
("/rtl/top.sv", "module top;\n sub u1 (.clk(c), .rst(r));\nendmodule\n"),
|
||||
]);
|
||||
let edit = add_port(&first, ModuleRef::Name("sub"), "input logic cfg").expect("adds `cfg`");
|
||||
let second = files(&[
|
||||
("/rtl/sub.sv", &applied(&first, &edit, "/rtl/sub.sv")),
|
||||
("/rtl/top.sv", &applied(&first, &edit, "/rtl/top.sv")),
|
||||
]);
|
||||
let edit = add_port(&second, ModuleRef::Name("sub"), "input logic mode").expect("adds `mode`");
|
||||
let top = applied(&second, &edit, "/rtl/top.sv");
|
||||
assert_eq!(top.matches("/* TODO: connect */").count(), 2, "{top}");
|
||||
assert!(top.contains(".cfg(/* TODO: connect */), .mode(/* TODO: connect */)"), "{top}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_one_per_line_connection_list_stays_one_per_line() {
|
||||
let workspace = files(&[
|
||||
|
||||
@@ -853,6 +853,186 @@ fn a_hierarchical_tail_that_resolves_is_renamed_with_its_declaration() {
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// the hierarchical surface, across files (TODO.md §49)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The cross-file twin of the test above, which is the whole of §49: the
|
||||
/// module and the instance that names into it are in **different** files, and
|
||||
/// the edit has to land in both. Before 2026-09-05 a module exported its
|
||||
/// ports and parameters only, so `u_sub.sig` could not be finished across a
|
||||
/// file boundary — `sub.sv` was edited alone and `top.sv` got the §2.9-20
|
||||
/// warning instead of an edit.
|
||||
#[test]
|
||||
fn a_cross_file_hierarchical_tail_is_renamed_with_its_declaration() {
|
||||
const SUB: &str = "module sub;\n wire sig;\n assign sig = 1'b0;\nendmodule\n";
|
||||
const TOP: &str =
|
||||
"module top;\n sub u_sub ();\n wire w;\n assign w = u_sub.sig;\nendmodule\n";
|
||||
let files = workspace(&[("sub.sv", SUB), ("top.sv", TOP)]);
|
||||
|
||||
for (from, text, name) in [("sub.sv", SUB, "wire"), ("top.sv", TOP, "u_sub.")] {
|
||||
let edit = rename(&files, &path(from), at(text, name, "sig"), "signal")
|
||||
.unwrap_or_else(|e| panic!("renames from {from}: {e}"));
|
||||
assert_eq!(
|
||||
apply(SUB, &edit, &path("sub.sv")),
|
||||
"module sub;\n wire signal;\n assign signal = 1'b0;\nendmodule\n",
|
||||
"the declaration and its own file's uses, from {from}"
|
||||
);
|
||||
assert_eq!(
|
||||
apply(TOP, &edit, &path("top.sv")),
|
||||
"module top;\n sub u_sub ();\n wire w;\n assign w = u_sub.signal;\nendmodule\n",
|
||||
"and the tail in the other file, from {from}"
|
||||
);
|
||||
assert!(
|
||||
!edit.warnings.iter().any(|w| w.contains("could not be resolved")),
|
||||
"the §2.9-20 warning is retired for a tail that resolved, from {from}: {:?}",
|
||||
edit.warnings
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `u_a.u_b.sig`: two hops, three files. The middle hop is an **instance**,
|
||||
/// which is on the hierarchical surface for exactly this reason — without it
|
||||
/// `u_b` has no declared type and the walk stops one segment short of `sig`.
|
||||
#[test]
|
||||
fn a_nested_cross_file_hierarchical_tail_is_renamed_through_both_hops() {
|
||||
const LEAF: &str = "module leaf;\n wire sig;\nendmodule\n";
|
||||
const MID: &str = "module mid;\n leaf u_b ();\nendmodule\n";
|
||||
const TOP: &str =
|
||||
"module top;\n mid u_a ();\n wire w;\n assign w = u_a.u_b.sig;\nendmodule\n";
|
||||
let files = workspace(&[("leaf.sv", LEAF), ("mid.sv", MID), ("top.sv", TOP)]);
|
||||
|
||||
let edit =
|
||||
rename(&files, &path("leaf.sv"), at(LEAF, "wire", "sig"), "signal").expect("renames");
|
||||
assert_eq!(apply(LEAF, &edit, &path("leaf.sv")), "module leaf;\n wire signal;\nendmodule\n");
|
||||
assert_eq!(
|
||||
apply(TOP, &edit, &path("top.sv")),
|
||||
"module top;\n mid u_a ();\n wire w;\n assign w = u_a.u_b.signal;\nendmodule\n",
|
||||
"the two-hop tail is edited"
|
||||
);
|
||||
assert_eq!(apply(MID, &edit, &path("mid.sv")), MID, "and the file in between is untouched");
|
||||
}
|
||||
|
||||
/// A tail naming a **port**, which is on the connection surface and therefore
|
||||
/// found by *both* reads. One declaration, one answer, one edit — the check
|
||||
/// that the hierarchical read consulting the connection table first is not
|
||||
/// producing a duplicate.
|
||||
#[test]
|
||||
fn a_tail_naming_a_port_is_one_answer_and_one_edit() {
|
||||
const SUB: &str = "module sub (input wire clk_i);\n wire w;\n assign w = clk_i;\nendmodule\n";
|
||||
const TOP: &str =
|
||||
"module top;\n wire c;\n sub u_sub (.clk_i(c));\n wire w;\n assign w = u_sub.clk_i;\nendmodule\n";
|
||||
let files = workspace(&[("sub.sv", SUB), ("top.sv", TOP)]);
|
||||
|
||||
let edit = rename(&files, &path("sub.sv"), at(SUB, "input wire", "clk_i"), "clock_i")
|
||||
.expect("renames");
|
||||
assert_eq!(
|
||||
apply(SUB, &edit, &path("sub.sv")),
|
||||
"module sub (input wire clock_i);\n wire w;\n assign w = clock_i;\nendmodule\n"
|
||||
);
|
||||
assert_eq!(
|
||||
apply(TOP, &edit, &path("top.sv")),
|
||||
"module top;\n wire c;\n sub u_sub (.clock_i(c));\n wire w;\n assign w = u_sub.clock_i;\nendmodule\n",
|
||||
"the connection and the hierarchical tail, each once"
|
||||
);
|
||||
let tail = at(TOP, "u_sub.", "clk_i");
|
||||
assert_eq!(
|
||||
edit.edits_for(&path("top.sv")).iter().filter(|e| e.range.start == tail).count(),
|
||||
1,
|
||||
"the tail is edited once, not once per surface: {:?}",
|
||||
edit.edits_for(&path("top.sv"))
|
||||
);
|
||||
}
|
||||
|
||||
/// The same for a **parameter**, the other half of the connection surface.
|
||||
#[test]
|
||||
fn a_tail_naming_a_parameter_is_renamed_across_files() {
|
||||
const SUB: &str = "module sub #(parameter int W = 8) ();\nendmodule\n";
|
||||
const TOP: &str = "module top;\n sub u_sub ();\n localparam int N = u_sub.W;\nendmodule\n";
|
||||
let files = workspace(&[("sub.sv", SUB), ("top.sv", TOP)]);
|
||||
|
||||
let edit =
|
||||
rename(&files, &path("sub.sv"), at(SUB, "parameter int", "W"), "WIDTH").expect("renames");
|
||||
assert_eq!(
|
||||
apply(SUB, &edit, &path("sub.sv")),
|
||||
"module sub #(parameter int WIDTH = 8) ();\nendmodule\n"
|
||||
);
|
||||
assert_eq!(
|
||||
apply(TOP, &edit, &path("top.sv")),
|
||||
"module top;\n sub u_sub ();\n localparam int N = u_sub.WIDTH;\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
/// The honest refusal, pinned. A net declared inside a **generate block** is
|
||||
/// not a member of the module: its scope is the block's, and the member table
|
||||
/// records a unit's own scope only. `u_x.gen_b.sig` therefore does not
|
||||
/// resolve, the tail is left as written, and the rename says so rather than
|
||||
/// editing half a design. Widening this means teaching the index about
|
||||
/// generate scopes and their loop indices (`u_x.gen[0].sig`), which §49
|
||||
/// deliberately did not do.
|
||||
#[test]
|
||||
fn a_generate_block_scoped_net_named_through_an_instance_is_refused_honestly() {
|
||||
const SUB: &str = concat!(
|
||||
"module sub;\n",
|
||||
" if (1) begin : gen_b\n",
|
||||
" wire sig;\n",
|
||||
" end\n",
|
||||
"endmodule\n"
|
||||
);
|
||||
const TOP: &str =
|
||||
"module top;\n sub u_x ();\n wire w;\n assign w = u_x.gen_b.sig;\nendmodule\n";
|
||||
let files = workspace(&[("sub.sv", SUB), ("top.sv", TOP)]);
|
||||
|
||||
let edit = rename(&files, &path("sub.sv"), at(SUB, "wire", "sig"), "signal").expect("renames");
|
||||
assert!(apply(SUB, &edit, &path("sub.sv")).contains("wire signal;"), "the declaration moves");
|
||||
assert_eq!(
|
||||
apply(TOP, &edit, &path("top.sv")),
|
||||
TOP,
|
||||
"a generate-scoped name is not on either surface, so the tail is left alone"
|
||||
);
|
||||
}
|
||||
|
||||
/// An **interface** instance's tail already resolved before §49 — an
|
||||
/// interface's signals are its connection surface (2026-09-01) — and it must
|
||||
/// still resolve exactly the same way, through the connection table.
|
||||
#[test]
|
||||
fn an_interface_instance_tail_is_unchanged_by_the_hierarchical_surface() {
|
||||
const IF: &str = "interface bus_if;\n logic data;\nendinterface\n";
|
||||
const TOP: &str =
|
||||
"module top;\n bus_if u_bus ();\n wire w;\n assign w = u_bus.data;\nendmodule\n";
|
||||
let files = workspace(&[("bus_if.sv", IF), ("top.sv", TOP)]);
|
||||
|
||||
let edit =
|
||||
rename(&files, &path("bus_if.sv"), at(IF, "logic", "data"), "payload").expect("renames");
|
||||
assert_eq!(
|
||||
apply(IF, &edit, &path("bus_if.sv")),
|
||||
"interface bus_if;\n logic payload;\nendinterface\n"
|
||||
);
|
||||
assert_eq!(
|
||||
apply(TOP, &edit, &path("top.sv")),
|
||||
"module top;\n bus_if u_bus ();\n wire w;\n assign w = u_bus.payload;\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
/// The verifier's refusal is not weakened by the new surface: two files each
|
||||
/// declaring `module sub`, and a tail naming into one of them. Which `sub`
|
||||
/// the instance means is not something the workspace can say, so the rename
|
||||
/// refuses from either end rather than editing one of the two.
|
||||
#[test]
|
||||
fn an_ambiguous_module_behind_a_hierarchical_tail_is_still_refused() {
|
||||
const ONE: &str = "module sub;\n wire sig;\nendmodule\n";
|
||||
const TWO: &str = "module sub;\n wire sig;\nendmodule\n";
|
||||
const TOP: &str = "module top;\n sub u_x ();\n wire w;\n assign w = u_x.sig;\nendmodule\n";
|
||||
let files = workspace(&[("one.sv", ONE), ("two.sv", TWO), ("top.sv", TOP)]);
|
||||
|
||||
let message = rename(&files, &path("one.sv"), at(ONE, "wire", "sig"), "signal")
|
||||
.expect_err("an ambiguous tail must be refused");
|
||||
assert!(message.contains("more than one"), "{message}");
|
||||
let message = rename(&files, &path("top.sv"), at(TOP, "u_x.", "sig"), "signal")
|
||||
.expect_err("and from the tail itself");
|
||||
assert!(message.contains("more than one"), "{message}");
|
||||
}
|
||||
|
||||
#[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
|
||||
|
||||
@@ -352,7 +352,7 @@ impl<'a> Binder<'a> {
|
||||
// Return type, arguments and body all resolve from inside the class,
|
||||
// as the LRM says an out-of-body declaration does.
|
||||
if let Some(ret) = ret {
|
||||
self.bind_data_type(ret, TextRange::new(span.start, name_span.start), body);
|
||||
self.bind_data_type(ret, body);
|
||||
}
|
||||
self.bind_tf_args(args, body);
|
||||
self.bind_stmts(stmts, body);
|
||||
|
||||
@@ -9,7 +9,6 @@ use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::is_keyword;
|
||||
|
||||
use crate::model::{ScopeId, ScopeKind, SymbolId, SymbolKind};
|
||||
use crate::scan::NameScanner;
|
||||
|
||||
use super::{type_name_of, Binder, Target};
|
||||
|
||||
@@ -39,7 +38,7 @@ impl<'a> Binder<'a> {
|
||||
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.bind_data_type(&p.ty, scope);
|
||||
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);
|
||||
@@ -51,7 +50,7 @@ impl<'a> Binder<'a> {
|
||||
/// in [`Binder::bind_param_ports`].
|
||||
pub(super) fn bind_tf_args(&mut self, args: &'a [ListElem<TfArg>], scope: ScopeId) {
|
||||
for a in args.iter().filter_map(ListElem::ok) {
|
||||
self.bind_data_type(&a.ty, TextRange::new(a.span.start, a.name_span.start), scope);
|
||||
self.bind_data_type(&a.ty, scope);
|
||||
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);
|
||||
@@ -68,13 +67,13 @@ impl<'a> Binder<'a> {
|
||||
// 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.bind_data_type(ty, scope);
|
||||
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);
|
||||
self.bind_enum_body(e, TextRange::new(span.start, ns.start), scope);
|
||||
self.bind_enum_body(e, scope);
|
||||
}
|
||||
TypedefKind::Struct(s) => {
|
||||
let inner = self.declare_with_scope(
|
||||
@@ -103,9 +102,9 @@ impl<'a> Binder<'a> {
|
||||
/// 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) {
|
||||
fn bind_enum_body(&mut self, e: &EnumType, scope: ScopeId) {
|
||||
if let Some(base) = &e.base {
|
||||
self.bind_data_type(base, window, scope);
|
||||
self.bind_data_type(base, scope);
|
||||
}
|
||||
self.bind_enum_members(&e.members, scope);
|
||||
}
|
||||
@@ -130,8 +129,7 @@ impl<'a> Binder<'a> {
|
||||
/// 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);
|
||||
self.bind_data_type(&m.ty, scope);
|
||||
for d in &m.declarators {
|
||||
self.bind_dims(&d.unpacked, scope);
|
||||
self.bind_opt_expr(d.init.as_ref(), scope);
|
||||
@@ -177,10 +175,10 @@ impl<'a> Binder<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn bind_data_decl(&mut self, d: &DataDecl, span: TextRange, scope: ScopeId) {
|
||||
pub(super) fn bind_data_decl(&mut self, d: &DataDecl, scope: ScopeId) {
|
||||
let kind = if d.net.is_some() { SymbolKind::Net } else { SymbolKind::Var };
|
||||
self.bind_opt_expr(d.delay.as_ref().map(|n| &n.expr), scope);
|
||||
self.bind_declarators(&d.declarators, kind, &d.ty, span, scope);
|
||||
self.bind_declarators(&d.declarators, kind, &d.ty, scope);
|
||||
}
|
||||
|
||||
pub(super) fn bind_port_decl(&mut self, p: &PortDecl, span: TextRange, scope: ScopeId) {
|
||||
@@ -222,7 +220,7 @@ impl<'a> Binder<'a> {
|
||||
symbol.type_name = type_name;
|
||||
}
|
||||
}
|
||||
self.bind_declarators(&p.declarators, kind, &p.ty, span, scope);
|
||||
self.bind_declarators(&p.declarators, kind, &p.ty, scope);
|
||||
}
|
||||
|
||||
pub(super) fn bind_declarators(
|
||||
@@ -230,11 +228,9 @@ impl<'a> Binder<'a> {
|
||||
declarators: &[Declarator],
|
||||
kind: SymbolKind,
|
||||
ty: &DataType,
|
||||
span: TextRange,
|
||||
scope: ScopeId,
|
||||
) {
|
||||
let first = declarators.first().map(|d| d.span.start).unwrap_or(span.end);
|
||||
self.bind_data_type(ty, TextRange::new(span.start, first), scope);
|
||||
self.bind_data_type(ty, scope);
|
||||
for d in declarators {
|
||||
let plain = d.unpacked.is_empty();
|
||||
let id =
|
||||
@@ -254,49 +250,12 @@ impl<'a> Binder<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A user-defined type name is a use like any other. `window` is the
|
||||
/// source range the name was written in — everything before the declared
|
||||
/// name, which is where a data type always sits. A `DataType` has no span
|
||||
/// of its own (vlog-semantic handshake item 2, still open), so this is
|
||||
/// the one declaration surface still located by scanning.
|
||||
pub(super) fn bind_data_type(&mut self, ty: &DataType, window: TextRange, scope: ScopeId) {
|
||||
/// A user-defined type name is a use like any other, and the parser hands
|
||||
/// over where every segment of it is written
|
||||
/// ([`DataType::segments`]), so nothing here rescans the source.
|
||||
pub(super) fn bind_data_type(&mut self, ty: &DataType, scope: ScopeId) {
|
||||
if !ty.name.is_empty() && !is_keyword(&ty.name) {
|
||||
match ty.name.split_once("::") {
|
||||
Some((unit, item)) => {
|
||||
let mut scanner = NameScanner::new(self.src, window);
|
||||
let unit_span = scanner.find(unit).unwrap_or(TextRange::empty(window.start));
|
||||
let item_span = scanner.find(item).unwrap_or(TextRange::empty(window.start));
|
||||
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 => {
|
||||
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_type_name(ty, scope);
|
||||
}
|
||||
self.bind_dims(&ty.packed, scope);
|
||||
// An anonymous aggregate written where a type name would go. Its
|
||||
@@ -305,27 +264,50 @@ impl<'a> Binder<'a> {
|
||||
// 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::Enum(e)) => self.bind_enum_body(e, 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.
|
||||
/// The segments of a written type name, each recorded as a use.
|
||||
///
|
||||
/// 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
|
||||
/// `pkg::item` is a unit and a member of it. `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) — is the interface as the
|
||||
/// type plus the modport as a **member** of it, bound 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`.
|
||||
///
|
||||
/// Every span is checked against the source before it is recorded, the
|
||||
/// rule the modport tail has always followed: a name the source spells
|
||||
/// differently from the way the parser joined it — an escaped segment
|
||||
/// terminated by a newline, a `bus_if . mp` written apart — 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);
|
||||
fn bind_type_name(&mut self, ty: &DataType, scope: ScopeId) {
|
||||
let scoped = ty.name.contains("::");
|
||||
let mut head: Option<&str> = None;
|
||||
for (seg, span) in ty.segments() {
|
||||
// A segment whose derived range does not read back as its own
|
||||
// text (`pkg :: item`, a comment inside the name) is recorded
|
||||
// with the empty range at its start, never dropped: an empty
|
||||
// range is what the corpus census counts as *unplaced*, so a
|
||||
// parser regression in the join would trip that alarm instead of
|
||||
// silently lowering the resolution rate (§47's QA).
|
||||
let span = self.exact_or_empty(span, seg);
|
||||
match (head, scoped) {
|
||||
(None, true) => self.use_name(scope, seg, span, Target::Unit),
|
||||
(None, false) => self.use_name(scope, seg, span, Target::Type),
|
||||
(Some(unit), true) => {
|
||||
self.use_name(scope, seg, span, Target::UnitMember(unit.to_string()))
|
||||
}
|
||||
(Some(unit), false) => {
|
||||
self.use_member(scope, seg, span, Target::TypeMember { unit: unit.to_string() })
|
||||
}
|
||||
}
|
||||
head = Some(seg);
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -174,7 +174,7 @@ impl<'a> Binder<'a> {
|
||||
// is the callee's formal, which this crate does not model (the
|
||||
// same rule connection port names follow).
|
||||
ExprKind::NamedArg { value, .. } => self.bind_expr(value, scope),
|
||||
ExprKind::Type(ty) => self.bind_data_type(ty, e.span, scope),
|
||||
ExprKind::Type(ty) => self.bind_data_type(ty, scope),
|
||||
ExprKind::MinTypMax { min, typ, max, .. } => {
|
||||
self.bind_expr(min, scope);
|
||||
self.bind_expr(typ, scope);
|
||||
|
||||
@@ -88,9 +88,9 @@ impl<'a> Binder<'a> {
|
||||
}
|
||||
ItemKind::Typedef(t) => self.bind_typedef(t, item.span, scope),
|
||||
ItemKind::ParamDecl(p) => {
|
||||
self.bind_declarators(&p.declarators, param_kind(&p.kw), &p.ty, item.span, scope)
|
||||
self.bind_declarators(&p.declarators, param_kind(&p.kw), &p.ty, scope)
|
||||
}
|
||||
ItemKind::DataDecl(d) => self.bind_data_decl(d, item.span, scope),
|
||||
ItemKind::DataDecl(d) => self.bind_data_decl(d, scope),
|
||||
ItemKind::PortDecl(p) => self.bind_port_decl(p, item.span, scope),
|
||||
ItemKind::ContAssign(c) => {
|
||||
self.bind_opt_expr(c.delay.as_ref(), scope);
|
||||
@@ -169,16 +169,21 @@ impl<'a> Binder<'a> {
|
||||
self.bind_expr(net, scope);
|
||||
}
|
||||
}
|
||||
// A package re-export names two things another file declares, and
|
||||
// both are references — see [`Binder::bind_export_path`]. A **DPI**
|
||||
// export stays the opaque leaf it was: it names a function
|
||||
// declared elsewhere in this same scope, and saying which one is a
|
||||
// separate question (`docs/features/dpi-export/README.md`).
|
||||
ItemKind::Export(ExportDecl::Package(paths)) => {
|
||||
for path in paths {
|
||||
self.bind_export_path(path, scope);
|
||||
}
|
||||
}
|
||||
// Opaque leaves: verbatim text this crate makes no claims about.
|
||||
// `Verbatim` is a constraint or covergroup body — no symbol is
|
||||
// bound for its name and nothing inside it is scanned, the same
|
||||
// contract macro invocations have. `Export` is a leaf too: a DPI
|
||||
// export names a function declared elsewhere in the same scope,
|
||||
// and a package re-export does not bring the name into this scope
|
||||
// (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.
|
||||
ItemKind::Export(_)
|
||||
// contract macro invocations have.
|
||||
ItemKind::Export(ExportDecl::Dpi(_))
|
||||
| ItemKind::Directive(_)
|
||||
| ItemKind::MacroItem(_)
|
||||
| ItemKind::Timeunit(_)
|
||||
@@ -212,11 +217,7 @@ impl<'a> Binder<'a> {
|
||||
// declares nothing, exactly as an `ItemKind::Error` does.
|
||||
PortList::Ansi(ports) => {
|
||||
for p in ports.iter().filter_map(ListElem::ok) {
|
||||
self.bind_data_type(
|
||||
&p.ty,
|
||||
TextRange::new(p.span.start, p.name_span.start),
|
||||
inner,
|
||||
);
|
||||
self.bind_data_type(&p.ty, inner);
|
||||
self.declare_typed(
|
||||
inner,
|
||||
&p.name,
|
||||
@@ -262,6 +263,36 @@ impl<'a> Binder<'a> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Record one `pkg::item` / `pkg::*` path of an `export` — **the two
|
||||
/// halves an import records, and no import at all**.
|
||||
///
|
||||
/// A re-export makes the name visible to whoever imports *this* package;
|
||||
/// it brings nothing into the exporting package's own scope (IEEE 1800
|
||||
/// §26.6). So `pkg` and `item` are ordinary uses — that is what makes
|
||||
/// `export b_pkg::x;` a go-to-definition into `b_pkg` and puts the line in
|
||||
/// `x`'s reference set — and no [`Import`] is pushed, which is what keeps
|
||||
/// a bare `x` written beside it unresolved unless an `import` says
|
||||
/// otherwise.
|
||||
///
|
||||
/// `export *::*;` names nothing at all: both halves are the `*` the
|
||||
/// parser stores as a name, and there is nothing to resolve. What it
|
||||
/// *means* — everything this package imports is re-exported — is the
|
||||
/// workspace layer's business (`workspace::reexport`).
|
||||
pub(super) fn bind_export_path(&mut self, path: &ImportPath, scope: ScopeId) {
|
||||
if path.pkg.text == "*" {
|
||||
return;
|
||||
}
|
||||
if path.item.text != "*" {
|
||||
self.use_name(
|
||||
scope,
|
||||
&path.item.text,
|
||||
path.item.span,
|
||||
Target::UnitMember(path.pkg.text.clone()),
|
||||
);
|
||||
}
|
||||
self.use_name(scope, &path.pkg.text, path.pkg.span, Target::Package);
|
||||
}
|
||||
|
||||
fn bind_instantiation(&mut self, i: &Instantiation, scope: ScopeId) {
|
||||
// `module_span` has the documented despace caveat for `pkg :: mod`,
|
||||
// so it is taken only when it slices back to the stored name.
|
||||
@@ -419,7 +450,7 @@ impl<'a> Binder<'a> {
|
||||
return;
|
||||
}
|
||||
if let Some(ret) = &f.ret {
|
||||
self.bind_data_type(ret, TextRange::new(span.start, f.name_span.start), scope);
|
||||
self.bind_data_type(ret, scope);
|
||||
}
|
||||
let inner = self.declare_with_scope(
|
||||
scope,
|
||||
@@ -487,7 +518,7 @@ impl<'a> Binder<'a> {
|
||||
fn bind_modport_prototype(&mut self, p: &'a TfPrototype, span: TextRange, scope: ScopeId) {
|
||||
self.use_name(scope, &p.name, p.name_span, Target::InScope);
|
||||
if let Some(ret) = &p.ret {
|
||||
self.bind_data_type(ret, TextRange::new(span.start, p.name_span.start), scope);
|
||||
self.bind_data_type(ret, scope);
|
||||
}
|
||||
let inner = self.new_scope(ScopeKind::Block, scope, span);
|
||||
self.bind_tf_args(&p.args, inner);
|
||||
|
||||
@@ -4,10 +4,8 @@
|
||||
//! covergroups and property specs share with them.
|
||||
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
use crate::model::{ScopeId, ScopeKind, SymbolKind};
|
||||
use crate::scan::name_after_kw;
|
||||
|
||||
use super::decl::param_kind;
|
||||
use super::{Binder, Target};
|
||||
@@ -66,11 +64,7 @@ impl<'a> Binder<'a> {
|
||||
match &i.ty {
|
||||
Some(ty) => {
|
||||
if let ExprKind::Ident(name) = &i.assign.lhs.kind {
|
||||
self.bind_data_type(
|
||||
ty,
|
||||
TextRange::new(stmt.span.start, i.assign.lhs.span.start),
|
||||
scope,
|
||||
);
|
||||
self.bind_data_type(ty, scope);
|
||||
self.declare(
|
||||
inner,
|
||||
name,
|
||||
@@ -140,21 +134,25 @@ 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),
|
||||
StmtKind::VarDecl(d) => self.bind_data_decl(d, 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, param_kind(&p.kw), &p.ty, stmt.span, scope)
|
||||
self.bind_declarators(&p.declarators, param_kind(&p.kw), &p.ty, scope)
|
||||
}
|
||||
StmtKind::PortDecl(p) => self.bind_port_decl(p, stmt.span, scope),
|
||||
StmtKind::Return { expr: e, .. } => self.bind_opt_expr(e.as_ref(), scope),
|
||||
StmtKind::Disable(name) => {
|
||||
// A use, not a declaration, so name-spans deliberately gave it
|
||||
// no range — the one statement still located by scanning.
|
||||
let ns = name_after_kw(self.src, stmt.span, "disable", name);
|
||||
self.use_name(scope, name, ns, Target::Lexical);
|
||||
StmtKind::Disable { name, name_span } => {
|
||||
// A use, not a declaration, but the parser spans it like any
|
||||
// other name. Checked before it is recorded, the rule every
|
||||
// derived span here follows: `disable a . b` written apart
|
||||
// costs the reference rather than mislocating it.
|
||||
let ns = self.exact_or_empty(*name_span, name);
|
||||
if !ns.is_empty() {
|
||||
self.use_name(scope, name, ns, Target::Lexical);
|
||||
}
|
||||
}
|
||||
StmtKind::Assert { cond, then, els, .. } => {
|
||||
self.bind_expr(cond, scope);
|
||||
|
||||
@@ -19,10 +19,10 @@ use std::path::PathBuf;
|
||||
use vlog_parser::defines::{Define, DefineKind, DefineTable};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
use crate::model::SymbolKind;
|
||||
use crate::model::{Surface, SymbolKind};
|
||||
use crate::workspace::{
|
||||
Decl, DeclLines, DeclPositions, DeclSite, FileFacts, InstanceOccurrence, ReferenceFact,
|
||||
SiteFact, Utf16Pos, Utf16Range,
|
||||
Decl, DeclLines, DeclPositions, DeclSite, FileFacts, InstanceOccurrence, Reexport,
|
||||
ReferenceFact, SiteFact, Utf16Pos, Utf16Range,
|
||||
};
|
||||
|
||||
/// The version of the encoding below. Bump it on **any** change to what a
|
||||
@@ -121,7 +121,31 @@ use crate::workspace::{
|
||||
/// cached — silence about a macro argument the rename really did leave
|
||||
/// behind, which is the failure the warning exists to prevent. See
|
||||
/// `docs/features/macro-word-census/README.md`.
|
||||
pub const FACTS_FORMAT: u32 = 17;
|
||||
///
|
||||
/// 17 → 18 (2026-09-05, package-reexports): a new `RX` group — each package's
|
||||
/// re-exports (`export b_pkg::x;`, `export b_pkg::*;`, and `export *::*;`
|
||||
/// already expanded to that package's imports), and once more a wider
|
||||
/// reference census, since both halves of a re-export line are references
|
||||
/// where they used to be nothing at all. It is a new field, so an older record
|
||||
/// would be read short by one group; and it is what makes `a_pkg::x` resolve
|
||||
/// to `b_pkg`'s declaration, so a store written by a 0.44.0 build would answer
|
||||
/// definition, hover, completion, find-references and the rename preflight as
|
||||
/// though no package in the workspace re-exported anything — for exactly the
|
||||
/// files it had cached, which is the half-right answer this bump exists to
|
||||
/// prevent. See `docs/features/package-reexports/README.md`.
|
||||
///
|
||||
/// 18 → 19 (2026-09-05, hierarchical-tail): a **surface** letter on every
|
||||
/// declaration and on every external reference — `c` for the connection
|
||||
/// surface, `h` for the hierarchical one. It is two new fields, so an older
|
||||
/// record would be read field-shifted; and the census grows with it, since a
|
||||
/// module now exports its nets, its variables and its instances on the
|
||||
/// hierarchical surface where it exported nothing at all before. A store
|
||||
/// written by a 0.44.0 build would answer definition, find-references and the
|
||||
/// rename of an internal net named through an instance (`assign w =
|
||||
/// u_x.sig;`) as though the tail resolved to nothing — for exactly the files
|
||||
/// it had cached, which is the half-right answer every one of these bumps
|
||||
/// exists to prevent. See `docs/features/hierarchical-tail/README.md`.
|
||||
pub const FACTS_FORMAT: u32 = 19;
|
||||
|
||||
impl FileFacts {
|
||||
/// These facts as one line's worth of fields, tab-separated.
|
||||
@@ -171,6 +195,15 @@ impl FileFacts {
|
||||
out.text(base);
|
||||
out.site(subclass);
|
||||
}
|
||||
// Three strings an edge: the package that writes the `export`, the
|
||||
// package it takes the name from, and the name (or `*`). Two letters
|
||||
// because `R` is the reference group.
|
||||
out.tag("RX", self.reexports.len());
|
||||
for (exporter, entry) in &self.reexports {
|
||||
out.text(exporter);
|
||||
out.text(&entry.package);
|
||||
out.text(&entry.item);
|
||||
}
|
||||
out.tag("R", self.references.len());
|
||||
for reference in &self.references {
|
||||
out.reference(reference);
|
||||
@@ -236,6 +269,11 @@ impl FileFacts {
|
||||
for _ in 0..input.tag("S")? {
|
||||
subclasses.push((input.text()?, input.site()?));
|
||||
}
|
||||
let mut reexports = Vec::new();
|
||||
for _ in 0..input.tag("RX")? {
|
||||
let exporter = input.text()?;
|
||||
reexports.push((exporter, Reexport { package: input.text()?, item: input.text()? }));
|
||||
}
|
||||
let mut references = Vec::new();
|
||||
for _ in 0..input.tag("R")? {
|
||||
references.push(input.reference()?);
|
||||
@@ -258,6 +296,7 @@ impl FileFacts {
|
||||
members,
|
||||
instantiations,
|
||||
subclasses,
|
||||
reexports,
|
||||
references,
|
||||
words,
|
||||
macro_words,
|
||||
@@ -352,6 +391,19 @@ impl Writer {
|
||||
// bump that goes with it
|
||||
// (`docs/features/class-member-access/README.md`, round 2).
|
||||
self.text(decl.type_name.as_deref().unwrap_or(""));
|
||||
// The surface the owner exports this declaration on. One letter, on
|
||||
// every declaration rather than only on the `M` group, so the two
|
||||
// groups keep the one shared `decl` shape they have always had.
|
||||
self.surface(decl.surface);
|
||||
}
|
||||
|
||||
/// One [`Surface`] as the letter a reader takes it back by.
|
||||
fn surface(&mut self, surface: Surface) {
|
||||
self.field();
|
||||
self.out.push(match surface {
|
||||
Surface::Connection => 'c',
|
||||
Surface::Hierarchical => 'h',
|
||||
});
|
||||
}
|
||||
|
||||
/// One [`Utf16Range`]: four numbers, in the order a reader takes them.
|
||||
@@ -409,7 +461,7 @@ impl Writer {
|
||||
self.range(*definition);
|
||||
self.range(*occurrence);
|
||||
}
|
||||
ReferenceFact::External { name, base, paths, occurrence } => {
|
||||
ReferenceFact::External { name, base, paths, surface, occurrence } => {
|
||||
self.field();
|
||||
self.out.push('e');
|
||||
self.text(name);
|
||||
@@ -421,6 +473,10 @@ impl Writer {
|
||||
for path in paths {
|
||||
self.text(path);
|
||||
}
|
||||
// Which surface those paths are walked in — the one field
|
||||
// that makes a cross-file hierarchical tail resolve from a
|
||||
// restored record exactly as it does from a fresh parse.
|
||||
self.surface(*surface);
|
||||
self.range(*occurrence);
|
||||
}
|
||||
}
|
||||
@@ -498,6 +554,7 @@ impl<'a> Reader<'a> {
|
||||
let detail_line = self.num()?;
|
||||
let type_name = self.text()?;
|
||||
let type_name = (!type_name.is_empty()).then_some(type_name);
|
||||
let surface = self.surface()?;
|
||||
// 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`).
|
||||
@@ -506,7 +563,17 @@ impl<'a> Reader<'a> {
|
||||
detail: (detail_line != 0).then_some(detail_line),
|
||||
positions: None,
|
||||
};
|
||||
Some(Decl { name, name_span, decl_span, kind, detail_span, lines, type_name })
|
||||
Some(Decl { name, name_span, decl_span, kind, detail_span, lines, type_name, surface })
|
||||
}
|
||||
|
||||
/// The mirror of the encoder's one-letter surface: anything else is a
|
||||
/// record this format did not write.
|
||||
fn surface(&mut self) -> Option<Surface> {
|
||||
match self.next()? {
|
||||
"c" => Some(Surface::Connection),
|
||||
"h" => Some(Surface::Hierarchical),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn utf16(&mut self) -> Option<Utf16Range> {
|
||||
@@ -569,6 +636,7 @@ impl<'a> Reader<'a> {
|
||||
name,
|
||||
base: (!base.is_empty()).then_some(base),
|
||||
paths,
|
||||
surface: self.surface()?,
|
||||
occurrence: self.range()?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -22,14 +22,13 @@ mod facts;
|
||||
pub mod instantiations;
|
||||
mod model;
|
||||
mod resolve;
|
||||
mod scan;
|
||||
pub mod words;
|
||||
mod workspace;
|
||||
|
||||
pub use facts::{record_path, FACTS_FORMAT};
|
||||
pub use model::{
|
||||
DocumentSymbol, Duplicate, Import, MemberSite, Reference, ReferenceId, Resolution, Scope,
|
||||
ScopeId, ScopeKind, Symbol, SymbolId, SymbolKind,
|
||||
ScopeId, ScopeKind, Surface, Symbol, SymbolId, SymbolKind,
|
||||
};
|
||||
pub use workspace::{
|
||||
index_order, resolve_external, DeclLines, DeclPositions, DeclSite, Def, Definition,
|
||||
|
||||
@@ -186,6 +186,39 @@ pub struct Duplicate {
|
||||
pub scope: ScopeId,
|
||||
}
|
||||
|
||||
/// Which of a unit's two member surfaces a lookup reads.
|
||||
///
|
||||
/// A **package**, a **class** and a `struct` typedef have one surface and this
|
||||
/// is noise for them. A **module** has two, and they are not the same set
|
||||
/// (IEEE 1800 §23.3 vs §23.6):
|
||||
///
|
||||
/// * its **connection** surface is what a connection list may name — its
|
||||
/// ports and its parameters (plus the properties and sequences a bound-in
|
||||
/// checker instantiates). `.sig(w)` in an instantiation, and the completion
|
||||
/// list behind that `.`, read exactly this and nothing more: an internal net
|
||||
/// is not connectable, and offering one would be an item the resolution
|
||||
/// could not find.
|
||||
/// * its **hierarchical** surface is everything a hierarchical path may name
|
||||
/// from anywhere in the design — the connection surface *plus* its nets, its
|
||||
/// variables and its instances (the last so `u_a.u_b.sig` has a hop to
|
||||
/// take). Only the tail walk behind an instance head reads it.
|
||||
///
|
||||
/// The hierarchical surface **contains** the connection one, so a tail naming
|
||||
/// a port has one answer and not two: a member record is tagged with the
|
||||
/// narrowest surface it joins, the connection query reads only the records
|
||||
/// tagged [`Surface::Connection`], and the hierarchical query reads those
|
||||
/// first and the [`Surface::Hierarchical`] ones after.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub enum Surface {
|
||||
/// Ports and parameters: what a connection list may name, and what every
|
||||
/// package, class and struct exports. The default for everything that is
|
||||
/// not a hierarchical tail.
|
||||
Connection,
|
||||
/// The whole of what a hierarchical path may name: the connection surface
|
||||
/// plus a module's nets, variables and instances.
|
||||
Hierarchical,
|
||||
}
|
||||
|
||||
/// What a [`Reference`] turned out to name.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Resolution {
|
||||
@@ -199,7 +232,14 @@ pub enum Resolution {
|
||||
/// those units — a path containing `::` is a package path, a bare name is a
|
||||
/// module, package or class name — in the order they are tried, the use's
|
||||
/// own name last. The workspace index (TODO.md §6) is what finishes these.
|
||||
ExternalCandidate { paths: Vec<String> },
|
||||
///
|
||||
/// `surface` is which of the named unit's two member surfaces the lookup
|
||||
/// reads ([`Surface`]). It is [`Surface::Connection`] for every candidate
|
||||
/// but one: the tail of `u_x.sig` whose head resolved to an **instance**,
|
||||
/// which is a hierarchical path and reads the module's hierarchical
|
||||
/// surface. Carried here rather than worked out again at lookup time
|
||||
/// because only the file that wrote the path knows what its head was.
|
||||
ExternalCandidate { paths: Vec<String>, surface: Surface },
|
||||
/// A use inside a class that nothing lexical binds, where the class's
|
||||
/// `extends` could: `base` is the base-class path as written
|
||||
/// (`uvm_component`, `pkg::base`), and `paths` are the import paths the
|
||||
@@ -242,11 +282,16 @@ pub enum MemberSite {
|
||||
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),
|
||||
/// spelling [`crate::WorkspaceIndex`]'s member lookup walks, with the
|
||||
/// [`Surface`] the walk reads. The tail resolution appends `::<name>` to
|
||||
/// the path and hands the pair to `follow_one`; the *list* is
|
||||
/// [`WorkspaceIndex::members_of_chain_in`](crate::WorkspaceIndex::members_of_chain_in).
|
||||
///
|
||||
/// The surface is [`Surface::Hierarchical`] exactly when the head of the
|
||||
/// spine was an **instance**, and it stays that for every further hop:
|
||||
/// `u_a.u_b.` is one hierarchical path, and each hop is an instance inside
|
||||
/// the module before it.
|
||||
Unit { path: String, surface: Surface },
|
||||
}
|
||||
|
||||
/// A *use* of a name: an expression identifier, a type name, an instantiated
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
//! requires at module scope and what an editor needs mid-edit.
|
||||
|
||||
use crate::bind::{Pending, Target};
|
||||
use crate::model::{MemberSite, Resolution, Scope, ScopeId, Symbol, SymbolId, SymbolKind};
|
||||
use crate::model::{MemberSite, Resolution, Scope, ScopeId, Surface, Symbol, SymbolId, SymbolKind};
|
||||
|
||||
/// Resolve one pending use against the finished scope tree.
|
||||
///
|
||||
@@ -34,7 +34,10 @@ pub(crate) fn resolve(scopes: &[Scope], symbols: &[Symbol], p: &Pending) -> Opti
|
||||
None => Resolution::NotFound,
|
||||
},
|
||||
// The port list lives in whatever file declares the module.
|
||||
None => Resolution::ExternalCandidate { paths: vec![module.clone()] },
|
||||
None => Resolution::ExternalCandidate {
|
||||
paths: vec![module.clone()],
|
||||
surface: Surface::Connection,
|
||||
},
|
||||
},
|
||||
Target::InScope => return in_scope(scopes, p.scope, &p.name),
|
||||
Target::TypeMember { unit } => return type_member(scopes, symbols, p.scope, unit, &p.name),
|
||||
@@ -95,7 +98,10 @@ fn in_bind_target(
|
||||
) -> Option<Resolution> {
|
||||
match owning_scope(scopes, symbols, target, is_instantiable) {
|
||||
Some(scope) => scopes.get(scope.0 as usize)?.lookup_local(name).map(Resolution::Resolved),
|
||||
None => Some(Resolution::ExternalCandidate { paths: vec![target.to_string()] }),
|
||||
None => Some(Resolution::ExternalCandidate {
|
||||
paths: vec![target.to_string()],
|
||||
surface: Surface::Connection,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,6 +141,7 @@ fn type_member(
|
||||
TypeHere::NotAUnit => None,
|
||||
TypeHere::Absent => Some(Resolution::ExternalCandidate {
|
||||
paths: vec![format!("{}::{name}", last_segment(unit))],
|
||||
surface: Surface::Connection,
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -185,6 +192,7 @@ fn member_of(
|
||||
}),
|
||||
Err(Some(base)) => Some(Resolution::ExternalCandidate {
|
||||
paths: vec![format!("{}::{name}", last_segment(&base))],
|
||||
surface: Surface::Connection,
|
||||
}),
|
||||
// A class this file declares whole, with no such member: nothing
|
||||
// to say that `NotFound` would not overstate.
|
||||
@@ -193,8 +201,8 @@ fn member_of(
|
||||
// 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}")] })
|
||||
MemberSite::Unit { path, surface } => {
|
||||
Some(Resolution::ExternalCandidate { paths: vec![format!("{path}::{name}")], surface })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -231,12 +239,17 @@ pub(crate) fn member_site(
|
||||
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(Some(base)) => MemberSite::Unit {
|
||||
path: format!("{}::{mid}", last_segment(&base)),
|
||||
surface: Surface::Connection,
|
||||
},
|
||||
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}")),
|
||||
MemberSite::Unit { path, surface } => {
|
||||
MemberSite::Unit { path: format!("{path}::{mid}"), surface }
|
||||
}
|
||||
};
|
||||
}
|
||||
Some(here)
|
||||
@@ -258,7 +271,10 @@ fn head_site(
|
||||
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())),
|
||||
None => Some(MemberSite::Unit {
|
||||
path: last_segment(&base?).to_string(),
|
||||
surface: Surface::Connection,
|
||||
}),
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
@@ -294,7 +310,9 @@ pub(crate) fn unit_site(
|
||||
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}")),
|
||||
MemberSite::Unit { path, surface } => {
|
||||
MemberSite::Unit { path: format!("{path}::{segment}"), surface }
|
||||
}
|
||||
};
|
||||
}
|
||||
Some(here)
|
||||
@@ -322,7 +340,7 @@ fn unit_scope(scopes: &[Scope], symbols: &[Symbol], from: ScopeId, unit: &str) -
|
||||
}
|
||||
current = scope.parent;
|
||||
}
|
||||
MemberSite::Unit(unit.to_string())
|
||||
MemberSite::Unit { path: unit.to_string(), surface: Surface::Connection }
|
||||
}
|
||||
|
||||
/// Where the members of one declaration live: its **declared type**'s scope
|
||||
@@ -347,7 +365,26 @@ fn link_type(scopes: &[Scope], symbols: &[Symbol], id: SymbolId) -> Option<Membe
|
||||
// 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())),
|
||||
TypeHere::Absent => Some(MemberSite::Unit {
|
||||
path: last_segment(type_name).to_string(),
|
||||
surface: head_surface(symbol.kind),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Which member surface a link of a spine opens: the **hierarchical** one when
|
||||
/// the link is an instance, the connection one for everything else.
|
||||
///
|
||||
/// `u_x.sig` is a hierarchical path (IEEE 1800 §23.6) and `sig` may be any of
|
||||
/// `sub`'s own declarations; `handle.field` is a member access on a type, and
|
||||
/// `pkt_t` has one surface anyway. The distinction only ever matters for a
|
||||
/// module — the one unit whose two surfaces differ — and it is settled here,
|
||||
/// in the file that can see what the head is, because the path handed to the
|
||||
/// workspace is only a spelling.
|
||||
fn head_surface(kind: SymbolKind) -> Surface {
|
||||
match kind {
|
||||
SymbolKind::Instance => Surface::Hierarchical,
|
||||
_ => Surface::Connection,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -678,9 +715,10 @@ fn unit_member(
|
||||
}
|
||||
// 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}")] }
|
||||
}
|
||||
MemberSite::Unit { .. } => Resolution::ExternalCandidate {
|
||||
paths: vec![format!("{unit}::{name}")],
|
||||
surface: Surface::Connection,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -724,7 +762,7 @@ fn super_member(scopes: &[Scope], from: ScopeId) -> Resolution {
|
||||
/// because the use was not a type — is `NotFound`.
|
||||
fn miss(scopes: &[Scope], from: ScopeId, external: Vec<String>, unit_lookup: bool) -> Resolution {
|
||||
if unit_lookup {
|
||||
return Resolution::ExternalCandidate { paths: external };
|
||||
return Resolution::ExternalCandidate { paths: external, surface: Surface::Connection };
|
||||
}
|
||||
if let Some(base) = nearest_extends(scopes, from) {
|
||||
return Resolution::InheritedCandidate { base, paths: external };
|
||||
@@ -732,7 +770,7 @@ fn miss(scopes: &[Scope], from: ScopeId, external: Vec<String>, unit_lookup: boo
|
||||
if external.is_empty() {
|
||||
Resolution::NotFound
|
||||
} else {
|
||||
Resolution::ExternalCandidate { paths: external }
|
||||
Resolution::ExternalCandidate { paths: external, surface: Surface::Connection }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -789,7 +827,10 @@ fn named_at_file_scope(
|
||||
) -> Resolution {
|
||||
match file_symbol(scopes, symbols, name, wanted) {
|
||||
Some(id) => Resolution::Resolved(id),
|
||||
None => Resolution::ExternalCandidate { paths: vec![name.to_string()] },
|
||||
None => Resolution::ExternalCandidate {
|
||||
paths: vec![name.to_string()],
|
||||
surface: Surface::Connection,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,193 +0,0 @@
|
||||
//! Recovering the byte range of a name the AST kept only as a `String`.
|
||||
//!
|
||||
//! Most declarations in `vlog_parser`'s AST store their name as a plain
|
||||
//! `String` and give a span only for the whole construct (`module m ... `,
|
||||
//! `input logic [W-1:0] d`). A language server needs the range of the *name*,
|
||||
//! so this scans the construct's own source text for it. See the README's
|
||||
//! Handshakes section: once the parser carries `name_span` on those nodes,
|
||||
//! this module goes away.
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// A cursor over one source window that hands out the ranges of successive
|
||||
/// identifiers, skipping comments, strings and macro invocations.
|
||||
pub(crate) struct NameScanner<'a> {
|
||||
src: &'a [u8],
|
||||
pos: usize,
|
||||
end: usize,
|
||||
}
|
||||
|
||||
impl<'a> NameScanner<'a> {
|
||||
/// A scanner over `window` of `src`.
|
||||
pub(crate) fn new(src: &'a str, window: TextRange) -> Self {
|
||||
let end = (window.end as usize).min(src.len());
|
||||
let pos = (window.start as usize).min(end);
|
||||
NameScanner { src: src.as_bytes(), pos, end }
|
||||
}
|
||||
|
||||
/// The range of the next whole-word `name`, or `None` if the window holds
|
||||
/// no more. The cursor moves past what it returns, so repeated calls walk
|
||||
/// a list (`genvar i, j;`) left to right.
|
||||
pub(crate) fn find(&mut self, name: &str) -> Option<TextRange> {
|
||||
while let Some(word) = self.next_word() {
|
||||
if &self.src[word.as_range()] == name.as_bytes() {
|
||||
return Some(word);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The range of the next identifier of any spelling.
|
||||
fn next_word(&mut self) -> Option<TextRange> {
|
||||
while self.pos < self.end {
|
||||
let b = self.src[self.pos];
|
||||
match b {
|
||||
b'/' if self.peek(1) == Some(b'/') => self.skip_line(),
|
||||
b'/' if self.peek(1) == Some(b'*') => self.skip_block_comment(),
|
||||
b'"' => self.skip_string(),
|
||||
// A macro invocation is one opaque token: `` `WIDTH `` must
|
||||
// not answer a search for the identifier `WIDTH`.
|
||||
b'`' => {
|
||||
self.pos += 1;
|
||||
self.skip_word();
|
||||
}
|
||||
_ if is_ident_start(b) => {
|
||||
let start = self.pos;
|
||||
self.skip_word();
|
||||
return Some(TextRange::new(start as u32, self.pos as u32));
|
||||
}
|
||||
_ => self.pos += 1,
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn peek(&self, n: usize) -> Option<u8> {
|
||||
self.src.get(self.pos + n).copied()
|
||||
}
|
||||
|
||||
fn skip_word(&mut self) {
|
||||
// An escaped identifier (`\a+b `) runs to the next whitespace.
|
||||
if self.src.get(self.pos) == Some(&b'\\') {
|
||||
self.pos += 1;
|
||||
while self.pos < self.end && !self.src[self.pos].is_ascii_whitespace() {
|
||||
self.pos += 1;
|
||||
}
|
||||
return;
|
||||
}
|
||||
while self.pos < self.end && is_ident_continue(self.src[self.pos]) {
|
||||
self.pos += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn skip_line(&mut self) {
|
||||
while self.pos < self.end && self.src[self.pos] != b'\n' {
|
||||
self.pos += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn skip_block_comment(&mut self) {
|
||||
self.pos += 2;
|
||||
while self.pos < self.end {
|
||||
if self.src[self.pos] == b'*' && self.peek(1) == Some(b'/') {
|
||||
self.pos += 2;
|
||||
return;
|
||||
}
|
||||
self.pos += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn skip_string(&mut self) {
|
||||
self.pos += 1;
|
||||
while self.pos < self.end {
|
||||
match self.src[self.pos] {
|
||||
b'\\' => self.pos += 2,
|
||||
b'"' => {
|
||||
self.pos += 1;
|
||||
return;
|
||||
}
|
||||
_ => self.pos += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_ident_start(b: u8) -> bool {
|
||||
b.is_ascii_alphabetic() || b == b'_' || b == b'$' || b == b'\\'
|
||||
}
|
||||
|
||||
fn is_ident_continue(b: u8) -> bool {
|
||||
b.is_ascii_alphanumeric() || b == b'_' || b == b'$'
|
||||
}
|
||||
|
||||
/// The range of `name` inside `window`, or an empty range at the window start
|
||||
/// when the scan comes up empty (a name the source spells differently — an
|
||||
/// escaped identifier, or text a macro produced).
|
||||
pub(crate) fn name_span(src: &str, window: TextRange, name: &str) -> TextRange {
|
||||
NameScanner::new(src, window).find(name).unwrap_or(TextRange::empty(window.start))
|
||||
}
|
||||
|
||||
/// The range of `name` written *after* the first `kw` in `window`. Used where
|
||||
/// the construct starts with a keyword and the name follows it, possibly
|
||||
/// past qualifiers (`function automatic int f`).
|
||||
pub(crate) fn name_after_kw(src: &str, window: TextRange, kw: &str, name: &str) -> TextRange {
|
||||
let mut scanner = NameScanner::new(src, window);
|
||||
if scanner.find(kw).is_none() {
|
||||
return TextRange::empty(window.start);
|
||||
}
|
||||
scanner.find(name).unwrap_or(TextRange::empty(window.start))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn whole(src: &str) -> TextRange {
|
||||
TextRange::new(0, src.len() as u32)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_a_name_after_its_keyword() {
|
||||
let src = "module top (input a);";
|
||||
let span = name_after_kw(src, whole(src), "module", "top");
|
||||
assert_eq!(&src[span.as_range()], "top");
|
||||
assert_eq!(span.start, 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_comments_and_strings() {
|
||||
let src = "/* d */ \"d\" // d\n d;";
|
||||
let span = name_span(src, whole(src), "d");
|
||||
assert_eq!(span.start, 18);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_whole_words_only() {
|
||||
let src = "input wire [W-1:0] w;";
|
||||
let span = name_span(src, whole(src), "w");
|
||||
assert_eq!(&src[span.as_range()], "w");
|
||||
assert_eq!(span.start, 19);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_invocation_is_one_opaque_token() {
|
||||
let src = "`WIDTH WIDTH";
|
||||
let span = name_span(src, whole(src), "WIDTH");
|
||||
assert_eq!(span.start, 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_that_is_not_there_gives_an_empty_range() {
|
||||
let src = "module m;";
|
||||
let span = name_span(src, whole(src), "nope");
|
||||
assert!(span.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successive_finds_walk_a_list() {
|
||||
let src = "genvar i, j;";
|
||||
let mut scanner = NameScanner::new(src, whole(src));
|
||||
assert_eq!(scanner.find("i").map(|s| s.start), Some(7));
|
||||
assert_eq!(scanner.find("j").map(|s| s.start), Some(10));
|
||||
}
|
||||
}
|
||||
@@ -5,12 +5,12 @@
|
||||
//! unit — are the same functions `index` lists members with, so a completion
|
||||
//! list and a lookup cannot disagree.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::model::{ReferenceId, Resolution, Symbol, SymbolKind};
|
||||
use crate::model::{ReferenceId, Resolution, Surface, Symbol, SymbolKind};
|
||||
use crate::Semantics;
|
||||
|
||||
use super::{Def, WorkspaceIndex};
|
||||
use super::{hierarchy, reexport, Def, WorkspaceIndex};
|
||||
|
||||
/// What the workspace layer made of one external-candidate reference.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -79,9 +79,11 @@ pub fn resolve_external(sem: &Semantics, index: &WorkspaceIndex) -> ExternalReso
|
||||
let mut targets = HashMap::new();
|
||||
for (i, reference) in sem.references().iter().enumerate() {
|
||||
let target = match &reference.resolution {
|
||||
Resolution::ExternalCandidate { paths } => follow_paths(index, &reference.name, paths),
|
||||
Resolution::ExternalCandidate { paths, surface } => {
|
||||
follow_paths(index, &reference.name, paths, *surface)
|
||||
}
|
||||
Resolution::InheritedCandidate { base, paths } => {
|
||||
match resolve_fact(index, &reference.name, Some(base), paths) {
|
||||
match resolve_fact(index, &reference.name, Some(base), paths, Surface::Connection) {
|
||||
ExternalTarget::StillUnresolved => continue,
|
||||
answered => answered,
|
||||
}
|
||||
@@ -106,10 +108,14 @@ pub(super) fn resolve_fact(
|
||||
name: &str,
|
||||
base: Option<&str>,
|
||||
paths: &[String],
|
||||
surface: Surface,
|
||||
) -> ExternalTarget {
|
||||
match follow_paths(index, name, paths) {
|
||||
match follow_paths(index, name, paths, surface) {
|
||||
ExternalTarget::StillUnresolved => match base {
|
||||
Some(base) => target(member_chain(index, last_segment(base), name)),
|
||||
// A base class is a class, and a class has one surface.
|
||||
Some(base) => {
|
||||
target(member_chain(index, last_segment(base), name, Surface::Connection))
|
||||
}
|
||||
None => ExternalTarget::StillUnresolved,
|
||||
},
|
||||
answered => answered,
|
||||
@@ -122,18 +128,52 @@ pub(super) fn resolve_fact(
|
||||
/// the inherited ones too. A unit that extends nothing (every package, every
|
||||
/// module) is one map lookup, exactly as before.
|
||||
///
|
||||
/// A miss there is then asked of the packages `unit` **re-exports** from
|
||||
/// (`export b_pkg::x;` — [`reexport::member`]), which is what makes
|
||||
/// `a_pkg::x` find `x` where `b_pkg` declares it. That walk is a no-op — one
|
||||
/// empty map lookup — for a unit that re-exports nothing, which is every unit
|
||||
/// in almost every workspace.
|
||||
///
|
||||
/// Map reads only — [`WorkspaceIndex::member`] and
|
||||
/// [`WorkspaceIndex::base_of`], both `BTreeMap`s — so a hover pays a handful
|
||||
/// of comparisons and no file is read. The walk is bounded by the visited set
|
||||
/// as well as by the workspace: `class a extends b; class b extends a;`
|
||||
/// terminates, and so does a chain that meets itself further up.
|
||||
pub(super) fn member_chain<'i>(index: &'i WorkspaceIndex, unit: &str, name: &str) -> &'i [Def] {
|
||||
let found = index.member(unit, name);
|
||||
pub(super) fn member_chain<'i>(
|
||||
index: &'i WorkspaceIndex,
|
||||
unit: &str,
|
||||
name: &str,
|
||||
surface: Surface,
|
||||
) -> &'i [Def] {
|
||||
let found = own_chain(index, unit, name, surface);
|
||||
if !found.is_empty() {
|
||||
return found;
|
||||
}
|
||||
// A re-export is a package's business and a package has one surface, so
|
||||
// this hop is the connection one whatever the tail was.
|
||||
reexport::member(index, unit, name)
|
||||
}
|
||||
|
||||
/// [`member_chain`] **without** the re-export hop: `unit` and its `extends`
|
||||
/// chain, and nothing else.
|
||||
///
|
||||
/// Split out because the re-export walk needs it: every hop it takes asks one
|
||||
/// package for one name, and asking through [`member_chain`] there would
|
||||
/// recurse into the very walk that called it. So the layering is exactly two
|
||||
/// deep — a re-export hop reaches a package's own members and its bases, and
|
||||
/// the re-export walk itself is what chases a chain of re-exports.
|
||||
pub(super) fn own_chain<'i>(
|
||||
index: &'i WorkspaceIndex,
|
||||
unit: &str,
|
||||
name: &str,
|
||||
surface: Surface,
|
||||
) -> &'i [Def] {
|
||||
let found = hierarchy::member(index, unit, name, surface);
|
||||
if !found.is_empty() {
|
||||
return found;
|
||||
}
|
||||
for hop in base_chain(index, unit) {
|
||||
let found = index.member(hop, name);
|
||||
let found = hierarchy::member(index, hop, name, surface);
|
||||
if !found.is_empty() {
|
||||
return found;
|
||||
}
|
||||
@@ -141,6 +181,33 @@ pub(super) fn member_chain<'i>(index: &'i WorkspaceIndex, unit: &str, name: &str
|
||||
&[]
|
||||
}
|
||||
|
||||
/// Every member `unit` and its bases export, nearest first and one entry per
|
||||
/// name — the listing half of [`own_chain`], and the same first-hit-wins rule
|
||||
/// it applies, so what is listed for a unit is what a lookup in it would find.
|
||||
///
|
||||
/// [`WorkspaceIndex::members_of_chain`]'s inner half, shared with the
|
||||
/// re-export walk for the same reason [`own_chain`] is.
|
||||
pub(super) fn own_members<'i>(
|
||||
index: &'i WorkspaceIndex,
|
||||
unit: &str,
|
||||
surface: Surface,
|
||||
) -> Vec<(&'i str, &'i Def)> {
|
||||
let mut hops: Vec<&str> = vec![unit];
|
||||
hops.extend(base_chain(index, unit));
|
||||
let mut out: Vec<(&'i str, &'i Def)> = Vec::new();
|
||||
let mut seen: HashSet<&str> = HashSet::new();
|
||||
for hop in hops {
|
||||
for (name, defs) in hierarchy::members_of(index, hop, surface) {
|
||||
if let Some(def) = defs.first() {
|
||||
if seen.insert(name) {
|
||||
out.push((name, def));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// **The hops [`member_chain`] takes past `unit` itself**, with the lookup
|
||||
/// left to the caller: what `unit` extends, then what *that* extends, and so
|
||||
/// on upward.
|
||||
@@ -179,11 +246,11 @@ pub(super) fn base_chain<'i>(index: &'i WorkspaceIndex, unit: &str) -> Vec<&'i s
|
||||
///
|
||||
/// The same fold [`follow_one`] runs before its own lookup — shared, so a
|
||||
/// list and a lookup of the same path cannot land in different units.
|
||||
pub(super) fn fold_path(index: &WorkspaceIndex, path: &str) -> Option<String> {
|
||||
pub(super) fn fold_path(index: &WorkspaceIndex, path: &str, surface: Surface) -> Option<String> {
|
||||
let mut segments = path.split("::");
|
||||
let mut unit = segments.next()?.to_string();
|
||||
for segment in segments {
|
||||
unit = index.member_unit(&unit, segment)?;
|
||||
unit = index.member_unit_in(&unit, segment, surface)?;
|
||||
}
|
||||
Some(unit)
|
||||
}
|
||||
@@ -216,9 +283,14 @@ pub(super) fn last_segment(path: &str) -> &str {
|
||||
|
||||
/// Try the recorded paths in the order `analyze` wrote them — which is the
|
||||
/// order the imports are written in — and take the first that has an answer.
|
||||
fn follow_paths(index: &WorkspaceIndex, name: &str, paths: &[String]) -> ExternalTarget {
|
||||
fn follow_paths(
|
||||
index: &WorkspaceIndex,
|
||||
name: &str,
|
||||
paths: &[String],
|
||||
surface: Surface,
|
||||
) -> ExternalTarget {
|
||||
for path in paths {
|
||||
match target(follow_one(index, name, path)) {
|
||||
match target(follow_one(index, name, path, surface)) {
|
||||
ExternalTarget::StillUnresolved => continue,
|
||||
answered => return answered,
|
||||
}
|
||||
@@ -243,22 +315,31 @@ fn follow_paths(index: &WorkspaceIndex, name: &str, paths: &[String]) -> Externa
|
||||
/// `handle.member` and `this.member` reach a base class in a third file, and
|
||||
/// what keeps the overlay and the index's own reference postings (which run
|
||||
/// through this same function) from disagreeing about what a use names.
|
||||
fn follow_one<'i>(index: &'i WorkspaceIndex, name: &str, path: &str) -> &'i [Def] {
|
||||
fn follow_one<'i>(
|
||||
index: &'i WorkspaceIndex,
|
||||
name: &str,
|
||||
path: &str,
|
||||
surface: Surface,
|
||||
) -> &'i [Def] {
|
||||
let mut segments: Vec<&str> = path.split("::").collect();
|
||||
if segments.is_empty() {
|
||||
return &[];
|
||||
}
|
||||
if segments.len() < 2 {
|
||||
return if path == name { index.units(name) } else { member_chain(index, path, name) };
|
||||
return if path == name {
|
||||
index.units(name)
|
||||
} else {
|
||||
member_chain(index, path, name, surface)
|
||||
};
|
||||
}
|
||||
// The last segment is the use's own name, which `name` already carries
|
||||
// (and which a `p::*` import spells as a wildcard); the ones before it are
|
||||
// the hops.
|
||||
segments.pop();
|
||||
let Some(unit) = fold_path(index, &segments.join("::")) else {
|
||||
let Some(unit) = fold_path(index, &segments.join("::"), surface) else {
|
||||
return &[];
|
||||
};
|
||||
member_chain(index, &unit, name)
|
||||
member_chain(index, &unit, name, surface)
|
||||
}
|
||||
|
||||
impl ExternalResolutions {
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
//! A unit's two member surfaces: which surface each declaration joins
|
||||
//! ([`surface_of`]), and the index reads that take a [`Surface`] rather than
|
||||
//! assuming one.
|
||||
//!
|
||||
//! Every unit but a module has one surface, and for those this module is a
|
||||
//! formality — the same set answers a `pkg::x` and a `handle.field`. A module
|
||||
//! has two, because SystemVerilog gives it two different ways of being reached
|
||||
//! from outside: a **connection list** may name its ports and parameters
|
||||
//! (§23.3), and a **hierarchical path** may name anything it declares (§23.6).
|
||||
//! Merging them would make `.internal_net(w)` a legal connection; keeping only
|
||||
//! the first is what made `assign w = u_x.sig;` unresolvable across files
|
||||
//! (`docs/topo.md` §2.9-23).
|
||||
//!
|
||||
//! So the index stores both, tagged, and every read says which one it wants.
|
||||
//! The connection surface is the whole of what was there before this module
|
||||
//! existed; the hierarchical surface is that set **plus** a module's nets,
|
||||
//! variables and instances, which is why a record is tagged with the narrowest
|
||||
//! surface it joins and a hierarchical read consults the connection table
|
||||
//! first. A port has one record, is found by both reads, and is one answer.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::model::{Surface, SymbolKind};
|
||||
|
||||
use super::{Def, WorkspaceIndex};
|
||||
|
||||
/// Which surface `member` joins in `unit`, or `None` when `unit` does not
|
||||
/// export it at all.
|
||||
///
|
||||
/// A **package** or **class** exports everything declared at its top level (a
|
||||
/// package's classes included — that is what lets `import uvm_pkg::*` answer
|
||||
/// `uvm_object`), and it has no second surface: nothing reaches into a package
|
||||
/// by a hierarchical path.
|
||||
///
|
||||
/// A **module** is the unit with two. Its connection surface is what a
|
||||
/// connection list may name — ports and parameters — plus the properties and
|
||||
/// sequences a bound-in checker instantiates (`top.u_dut.p_req`, and an
|
||||
/// `` `include``d assertion file's bare-name instantiation). Its hierarchical
|
||||
/// surface adds its **nets**, its **variables** and its **instances**: those
|
||||
/// are what `u_x.sig` and `u_a.u_b.sig` name, they are not connectable, and
|
||||
/// before 2026-09-05 they were not exported at all — which is what made a
|
||||
/// cross-file rename of an internal net edit one file and warn about the
|
||||
/// other. The instances are in it for the hop as much as for themselves:
|
||||
/// `u_a.u_b.sig` needs `u_b`'s declared type to know where `sig` lives.
|
||||
///
|
||||
/// An **interface** is the 2026-09-01 exception and is unchanged: its signals
|
||||
/// *are* its connection surface, because `virtual bus_if vif; vif.data` is how
|
||||
/// every DV testbench reaches `data` and `vif` is a variable, not an instance.
|
||||
/// It gains its instances hierarchically for the same hop reason, and nothing
|
||||
/// else moves.
|
||||
///
|
||||
/// A `typedef struct`/`union` exports its fields, and a field that is itself
|
||||
/// an inline aggregate exports its own — which is what a generated register
|
||||
/// package is: `reg2hw_t` → `ctrl` → `q`. A covergroup's surface is its
|
||||
/// labelled coverpoints and crosses plus the `sample` method its header
|
||||
/// declares. Neither has a hierarchical surface: a struct is a type, and a
|
||||
/// path reaches a covergroup's coverpoints the same single way from anywhere.
|
||||
pub(super) fn surface_of(unit: SymbolKind, member: SymbolKind) -> Option<Surface> {
|
||||
match unit {
|
||||
SymbolKind::Package | SymbolKind::Class => matches!(
|
||||
member,
|
||||
SymbolKind::Param
|
||||
| SymbolKind::LocalParam
|
||||
| SymbolKind::Typedef
|
||||
| SymbolKind::EnumVariant
|
||||
| SymbolKind::Function
|
||||
| SymbolKind::Task
|
||||
| SymbolKind::Net
|
||||
| SymbolKind::Var
|
||||
| SymbolKind::Class
|
||||
| SymbolKind::Constraint
|
||||
| SymbolKind::Covergroup
|
||||
| SymbolKind::Property
|
||||
| SymbolKind::Sequence
|
||||
)
|
||||
.then_some(Surface::Connection),
|
||||
SymbolKind::Module => match member {
|
||||
SymbolKind::Port
|
||||
| SymbolKind::Param
|
||||
| SymbolKind::LocalParam
|
||||
| SymbolKind::Property
|
||||
| SymbolKind::Sequence => Some(Surface::Connection),
|
||||
SymbolKind::Net | SymbolKind::Var | SymbolKind::Instance => Some(Surface::Hierarchical),
|
||||
_ => None,
|
||||
},
|
||||
SymbolKind::Typedef | SymbolKind::StructMember => {
|
||||
(member == SymbolKind::StructMember).then_some(Surface::Connection)
|
||||
}
|
||||
SymbolKind::Covergroup => {
|
||||
matches!(member, SymbolKind::Coverpoint | SymbolKind::Cross | SymbolKind::Function)
|
||||
.then_some(Surface::Connection)
|
||||
}
|
||||
SymbolKind::Interface => match member {
|
||||
SymbolKind::Net
|
||||
| SymbolKind::Var
|
||||
| SymbolKind::Port
|
||||
| SymbolKind::Param
|
||||
| SymbolKind::LocalParam
|
||||
| SymbolKind::Typedef
|
||||
| SymbolKind::Function
|
||||
| SymbolKind::Task
|
||||
| SymbolKind::Modport
|
||||
| SymbolKind::Clocking => Some(Surface::Connection),
|
||||
SymbolKind::Instance => Some(Surface::Hierarchical),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `member` of `unit` in one surface: the connection records, and — for
|
||||
/// [`Surface::Hierarchical`] — the hierarchical-only ones after them.
|
||||
///
|
||||
/// Connection first, so a name in both surfaces has exactly one answer and it
|
||||
/// is the same declaration either read finds. Two map reads at worst, and one
|
||||
/// for every lookup that is not a hierarchical tail.
|
||||
pub(super) fn member<'i>(
|
||||
index: &'i WorkspaceIndex,
|
||||
unit: &str,
|
||||
member: &str,
|
||||
surface: Surface,
|
||||
) -> &'i [Def] {
|
||||
let found = index.member(unit, member);
|
||||
match surface {
|
||||
Surface::Connection => found,
|
||||
Surface::Hierarchical if !found.is_empty() => found,
|
||||
Surface::Hierarchical => index.hierarchical_member(unit, member),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every member of `unit` in one surface, connection records first, each name
|
||||
/// once — the listing half of [`member`] and the same first-hit-wins rule, so
|
||||
/// a completion list offers what a lookup in the same surface would find.
|
||||
pub(super) fn members_of<'i>(
|
||||
index: &'i WorkspaceIndex,
|
||||
unit: &str,
|
||||
surface: Surface,
|
||||
) -> Vec<(&'i str, &'i [Def])> {
|
||||
let mut out: Vec<(&'i str, &'i [Def])> = index.members_of(unit).collect();
|
||||
if surface == Surface::Hierarchical {
|
||||
let held: HashSet<&str> = out.iter().map(|(name, _)| *name).collect();
|
||||
out.extend(index.hierarchical_members_of(unit).filter(|(name, _)| !held.contains(name)));
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -11,13 +11,14 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::defines::{Define, DefineTable};
|
||||
|
||||
use crate::model::SymbolKind;
|
||||
use crate::model::{Surface, SymbolKind};
|
||||
|
||||
use super::external::{base_chain, fold_path, last_segment, member_chain};
|
||||
use super::external::{fold_path, last_segment, member_chain, own_members};
|
||||
use super::hierarchy;
|
||||
use super::record::{FileFacts, ReferenceFact};
|
||||
use super::{
|
||||
Def, DefinitionKey, FileId, IndexCounts, InheritanceEdge, InstantiationEdge, ReferenceSite,
|
||||
WorkspaceIndex, WorkspaceSymbol,
|
||||
reexport, Def, DefinitionKey, FileId, IndexCounts, InheritanceEdge, InstantiationEdge,
|
||||
Reexport, ReferenceSite, WorkspaceIndex, WorkspaceSymbol,
|
||||
};
|
||||
|
||||
impl WorkspaceIndex {
|
||||
@@ -69,15 +70,30 @@ impl WorkspaceIndex {
|
||||
self.units.get(name).map_or(&[], Vec::as_slice)
|
||||
}
|
||||
|
||||
/// Every declaration of `member` exported by `unit`. This is what makes
|
||||
/// `p::x` and `import p::*` reach into another file, and what makes a
|
||||
/// `.port` connection reach into the instantiated module.
|
||||
/// Every declaration of `member` `unit` exports on its **connection**
|
||||
/// surface. This is what makes `p::x` and `import p::*` reach into
|
||||
/// another file, and what makes a `.port` connection reach into the
|
||||
/// instantiated module.
|
||||
///
|
||||
/// The connection surface is the whole surface of a package, a class and
|
||||
/// a struct; for a module it is its ports and parameters, and what a
|
||||
/// hierarchical path may name besides is
|
||||
/// [`WorkspaceIndex::member_in`]'s business ([`Surface`]).
|
||||
pub fn member(&self, unit: &str, member: &str) -> &[Def] {
|
||||
self.members.get(unit).and_then(|m| m.get(member)).map_or(&[], Vec::as_slice)
|
||||
}
|
||||
|
||||
/// Every exported member of `unit`, sorted by name — the completion list
|
||||
/// behind `p::` and behind an instantiation's connection list.
|
||||
/// [`WorkspaceIndex::member`] in a named surface: the same answer for
|
||||
/// [`Surface::Connection`], and for [`Surface::Hierarchical`] the
|
||||
/// connection records first and a module's nets, variables and instances
|
||||
/// after them.
|
||||
pub fn member_in(&self, unit: &str, member: &str, surface: Surface) -> &[Def] {
|
||||
hierarchy::member(self, unit, member, surface)
|
||||
}
|
||||
|
||||
/// Every member `unit` exports on its connection surface, sorted by name
|
||||
/// — the completion list behind `p::` and behind an instantiation's
|
||||
/// connection list.
|
||||
pub fn members_of(&self, unit: &str) -> impl Iterator<Item = (&str, &[Def])> {
|
||||
self.members
|
||||
.get(unit)
|
||||
@@ -85,6 +101,44 @@ impl WorkspaceIndex {
|
||||
.flat_map(|m| m.iter().map(|(name, defs)| (name.as_str(), defs.as_slice())))
|
||||
}
|
||||
|
||||
/// Every member of `unit` a hierarchical path may name and a connection
|
||||
/// list may not, sorted by name — the second half of a hierarchical
|
||||
/// listing, never a listing on its own.
|
||||
pub(super) fn hierarchical_members_of(
|
||||
&self,
|
||||
unit: &str,
|
||||
) -> impl Iterator<Item = (&str, &[Def])> {
|
||||
self.hier_members
|
||||
.get(unit)
|
||||
.into_iter()
|
||||
.flat_map(|m| m.iter().map(|(name, defs)| (name.as_str(), defs.as_slice())))
|
||||
}
|
||||
|
||||
/// [`WorkspaceIndex::member`] on the hierarchical-only half alone.
|
||||
pub(super) fn hierarchical_member(&self, unit: &str, member: &str) -> &[Def] {
|
||||
self.hier_members.get(unit).and_then(|m| m.get(member)).map_or(&[], Vec::as_slice)
|
||||
}
|
||||
|
||||
/// Every unit that declares `name` on its **hierarchical** surface, with
|
||||
/// the declaration — the census `workspace_symbols` deliberately does not
|
||||
/// hold.
|
||||
///
|
||||
/// A module's internal net is not a workspace symbol: `workspace/symbol`
|
||||
/// answers what a user can name from outside, and a design with 20 000
|
||||
/// modules has hundreds of thousands of internal signals. But a rename's
|
||||
/// fan-out has to find the *declaring file* of a name a hierarchical tail
|
||||
/// resolves to, and that is exactly this question — asked once per
|
||||
/// rename, over a map, reading nothing. See
|
||||
/// `docs/features/hierarchical-tail/README.md`.
|
||||
pub fn hierarchical_declarations<'a>(
|
||||
&'a self,
|
||||
name: &'a str,
|
||||
) -> impl Iterator<Item = (&'a str, &'a Def)> + 'a {
|
||||
self.hier_members.iter().flat_map(move |(unit, members)| {
|
||||
members.get(name).into_iter().flatten().map(move |def| (unit.as_str(), def))
|
||||
})
|
||||
}
|
||||
|
||||
/// Every member `path::` can name, **inherited ones included**, sorted by
|
||||
/// name with one declaration each — the completion list behind `pkg::`,
|
||||
/// `handle.` and `vif.` when the type is another file's.
|
||||
@@ -97,32 +151,45 @@ impl WorkspaceIndex {
|
||||
/// empty list, never a guess.
|
||||
///
|
||||
/// **The same walk one member lookup takes.** The units searched are
|
||||
/// `unit` and then [`base_chain`]'s hops, in that order, and a name
|
||||
/// declared in more than one of them is listed once from the nearest —
|
||||
/// which is the first-hit-wins rule `member_chain` applies, so a
|
||||
/// subclass's override is what is listed *and* what a lookup would find.
|
||||
/// Map reads only: no file is opened.
|
||||
/// `unit` and then its `extends` hops ([`own_members`]), then the packages
|
||||
/// `unit` **re-exports** from ([`reexport::members`]) — exactly
|
||||
/// `member_chain`'s order — and a name found in more than one of them is
|
||||
/// listed once from the nearest. So a subclass's override, and a package's
|
||||
/// own declaration of a name it also re-exports, are what is listed *and*
|
||||
/// what a lookup would find. Map reads only: no file is opened.
|
||||
pub fn members_of_chain(&self, path: &str) -> Vec<(&str, &Def)> {
|
||||
let Some(unit) = fold_path(self, path) else {
|
||||
self.members_of_chain_in(path, Surface::Connection)
|
||||
}
|
||||
|
||||
/// [`WorkspaceIndex::members_of_chain`] in a named surface — the list
|
||||
/// behind `u_x.` in an expression, where the module's nets, variables and
|
||||
/// instances are what the user is reaching for and what the tail
|
||||
/// resolution will find. A connection list's `.` is the other surface and
|
||||
/// its own function (`completion::connection_members`).
|
||||
pub fn members_of_chain_in(&self, path: &str, surface: Surface) -> Vec<(&str, &Def)> {
|
||||
let Some(unit) = fold_path(self, path, surface) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut hops: Vec<&str> = vec![unit.as_str()];
|
||||
hops.extend(base_chain(self, &unit));
|
||||
let mut out: Vec<(&str, &Def)> = Vec::new();
|
||||
let mut seen: HashSet<&str> = HashSet::new();
|
||||
for hop in hops {
|
||||
for (name, defs) in self.members_of(hop) {
|
||||
if let Some(def) = defs.first() {
|
||||
if seen.insert(name) {
|
||||
out.push((name, def));
|
||||
}
|
||||
}
|
||||
for (name, def) in
|
||||
own_members(self, &unit, surface).into_iter().chain(reexport::members(self, &unit))
|
||||
{
|
||||
if seen.insert(name) {
|
||||
out.push((name, def));
|
||||
}
|
||||
}
|
||||
out.sort_by_key(|(name, _)| *name);
|
||||
out
|
||||
}
|
||||
|
||||
/// What one package re-exports, in file order then source order — the
|
||||
/// edges `reexport`'s two walks follow. Empty for every unit that
|
||||
/// re-exports nothing, which is all but a handful in any workspace.
|
||||
pub(super) fn reexports(&self, unit: &str) -> &[Reexport] {
|
||||
self.reexports.get(unit).map_or(&[], Vec::as_slice)
|
||||
}
|
||||
|
||||
/// The **declared type** of one member of one unit, as the next unit name
|
||||
/// to look in — the hop that walks a chain `pkt_t::hdr::addr` across
|
||||
/// files, and the one a `MemberSite::Unit` path is folded by.
|
||||
@@ -136,7 +203,14 @@ impl WorkspaceIndex {
|
||||
/// class declared inside a package declares no file-scope unit at all —
|
||||
/// the dominant UVM shape — and is unaffected.
|
||||
pub fn member_unit(&self, unit: &str, member: &str) -> Option<String> {
|
||||
let [def] = member_chain(self, unit, member) else {
|
||||
self.member_unit_in(unit, member, Surface::Connection)
|
||||
}
|
||||
|
||||
/// [`WorkspaceIndex::member_unit`] in a named surface: the hop
|
||||
/// `u_a.u_b.sig` takes, where `u_b` is an instance inside `a` and only
|
||||
/// the hierarchical surface holds it.
|
||||
pub fn member_unit_in(&self, unit: &str, member: &str, surface: Surface) -> Option<String> {
|
||||
let [def] = member_chain(self, unit, member, surface) else {
|
||||
return None;
|
||||
};
|
||||
let next = last_segment(def.type_name.as_deref()?);
|
||||
@@ -411,6 +485,12 @@ impl WorkspaceIndex {
|
||||
.filter(|d| d.kind == SymbolKind::Class)
|
||||
.count(),
|
||||
members: self.members.values().flat_map(|m| m.values()).map(Vec::len).sum(),
|
||||
hierarchical_members: self
|
||||
.hier_members
|
||||
.values()
|
||||
.flat_map(|m| m.values())
|
||||
.map(Vec::len)
|
||||
.sum(),
|
||||
defines: self.facts.iter().map(|f| f.defines.entries().len()).sum(),
|
||||
instantiations: self.instantiations.values().map(Vec::len).sum(),
|
||||
inheritances: self.subclasses.values().map(Vec::len).sum(),
|
||||
|
||||
@@ -16,19 +16,26 @@
|
||||
//! This file is the index's vocabulary: the records it hands out ([`Def`],
|
||||
//! [`DeclLines`], the edges) and the [`WorkspaceIndex`] tables themselves.
|
||||
//! `index` answers questions of a built index, `update` changes one after it
|
||||
//! is built, `record` reads off what one file contributes ([`FileFacts`]), and
|
||||
//! is built, `record` reads off what one file contributes ([`FileFacts`]),
|
||||
//! `external` is the overlay — [`resolve_external`] — and the member and
|
||||
//! inheritance walks it shares with `index`.
|
||||
//! inheritance walks it shares with `index`, `reexport` is the one edge
|
||||
//! neither of those two could hold — what `export b_pkg::x;` makes reachable
|
||||
//! through the package that writes it — and `hierarchy` is which of a unit's
|
||||
//! two member surfaces holds what, and the reads that take a
|
||||
//! [`crate::Surface`] instead of assuming one.
|
||||
|
||||
mod external;
|
||||
mod hierarchy;
|
||||
mod index;
|
||||
mod record;
|
||||
mod reexport;
|
||||
mod update;
|
||||
|
||||
pub use external::{resolve_external, Definition, ExternalResolutions, ExternalTarget};
|
||||
pub use index::{index_order, IndexBuilder};
|
||||
pub use record::FileFacts;
|
||||
pub(crate) use record::{Decl, ReferenceFact, SiteFact};
|
||||
pub(crate) use reexport::Reexport;
|
||||
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
@@ -287,13 +294,28 @@ pub struct WorkspaceIndex {
|
||||
facts: Vec<FileFacts>,
|
||||
/// File-scope name → every declaration of it, in disambiguation order.
|
||||
units: BTreeMap<String, Vec<Def>>,
|
||||
/// Unit name → member name → every declaration of it.
|
||||
/// Unit name → member name → every declaration of it, on the
|
||||
/// **connection** surface: what a connection list, a `pkg::x` and a
|
||||
/// `handle.field` may name. This is the whole member table as it was
|
||||
/// before 2026-09-05, and every query that does not name a surface reads
|
||||
/// exactly this.
|
||||
members: BTreeMap<String, BTreeMap<String, Vec<Def>>>,
|
||||
/// The same shape for the members a **hierarchical path** may name and a
|
||||
/// connection list may not — a module's (or an interface's) nets,
|
||||
/// variables and instances. Kept apart rather than tagged in place so
|
||||
/// that every existing read stays the read it was, and a hierarchical
|
||||
/// read is `members` first and this second (`hierarchy`).
|
||||
hier_members: BTreeMap<String, BTreeMap<String, Vec<Def>>>,
|
||||
/// Instantiated module name → every site, in file order then walk order.
|
||||
instantiations: BTreeMap<String, Vec<InstantiationEdge>>,
|
||||
/// Base class name → every class extending it, in file order then walk
|
||||
/// order.
|
||||
subclasses: BTreeMap<String, Vec<InheritanceEdge>>,
|
||||
/// Exporting package name → the packages and names it re-exports, in file
|
||||
/// order then source order. Followed at *query* time rather than folded
|
||||
/// into `members`, so a re-export costs nothing until something asks a
|
||||
/// package for a name it does not itself declare. See `reexport`.
|
||||
reexports: BTreeMap<String, Vec<Reexport>>,
|
||||
/// The same census read the other way: class name → the base it extends,
|
||||
/// as written. Built in [`WorkspaceIndex::merge`] from the very edges that
|
||||
/// fill `subclasses`, so the two cannot disagree and no [`FileFacts`]
|
||||
@@ -327,9 +349,14 @@ pub struct IndexCounts {
|
||||
/// Class declarations reachable in the index — file-scope units plus
|
||||
/// classes registered as members of a package or an enclosing class.
|
||||
pub classes: usize,
|
||||
/// Package, class and module member declarations, duplicates counted
|
||||
/// separately.
|
||||
/// Package, class and module member declarations on the **connection**
|
||||
/// surface, duplicates counted separately.
|
||||
pub members: usize,
|
||||
/// Member declarations only a hierarchical path can name — a module's or
|
||||
/// an interface's nets, variables and instances — duplicates counted
|
||||
/// separately. Disjoint from `members`, so the whole member census is the
|
||||
/// two added.
|
||||
pub hierarchical_members: usize,
|
||||
/// `` `define``/`` `undef`` directives recorded across all files.
|
||||
pub defines: usize,
|
||||
/// Instantiation sites recorded — one per written statement, inside a
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
//! What one file contributes to an index, read off its parse: the
|
||||
//! [`FileFacts`] record and the per-file shapes inside it ([`Decl`],
|
||||
//! [`SiteFact`], [`ReferenceFact`]), the read-off itself
|
||||
//! ([`facts_from_analysis`]), and the two rulings it applies — which
|
||||
//! file-scope kinds are units, and what each kind of unit exports. A record
|
||||
//! is the unit of persistence (`facts.rs` encodes exactly this) and of
|
||||
//! incremental update, which is why it is a module of its own.
|
||||
//! ([`facts_from_analysis`]), and the ruling it applies about which
|
||||
//! file-scope kinds are units. What each kind of unit *exports*, and on which
|
||||
//! surface, moved to [`hierarchy::surface_of`] when a module gained a second
|
||||
//! one. A record is the unit of persistence (`facts.rs` encodes exactly this)
|
||||
//! and of incremental update, which is why it is a module of its own.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -15,10 +16,13 @@ use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::Token;
|
||||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex};
|
||||
|
||||
use crate::model::{Resolution, Symbol, SymbolKind};
|
||||
use crate::model::{Resolution, Surface, Symbol, SymbolKind};
|
||||
use crate::{analyze, classes, instantiations, Semantics};
|
||||
|
||||
use super::{DeclLines, DeclPositions, DeclSite, Def, FileId, InstanceOccurrence, Utf16Range};
|
||||
use super::{
|
||||
hierarchy, reexport, DeclLines, DeclPositions, DeclSite, Def, FileId, InstanceOccurrence,
|
||||
Reexport, Utf16Range,
|
||||
};
|
||||
|
||||
/// One declaration as a single file contributes it, before that file has a
|
||||
/// [`FileId`]. The id depends on where the file's path sorts among all of
|
||||
@@ -32,12 +36,19 @@ pub(crate) struct Decl {
|
||||
pub(crate) detail_span: Option<TextRange>,
|
||||
pub(crate) lines: DeclLines,
|
||||
pub(crate) type_name: Option<String>,
|
||||
/// Which of its owner's member surfaces this declaration joins — the
|
||||
/// narrowest one, so a connection-surface record is found by a
|
||||
/// hierarchical read too ([`hierarchy::surface_of`]). Always
|
||||
/// [`Surface::Connection`] for a unit, which has no owner and is reached
|
||||
/// by name.
|
||||
pub(crate) surface: Surface,
|
||||
}
|
||||
|
||||
impl Decl {
|
||||
/// A member's declaration: lines only, no client positions — see
|
||||
/// [`DeclPositions`] for why the cheap half is the only half a member gets.
|
||||
fn member(symbol: &Symbol, lines: &LineIndex) -> Decl {
|
||||
/// A member's declaration, on the surface its owner exports it: lines
|
||||
/// only, no client positions — see [`DeclPositions`] for why the cheap
|
||||
/// half is the only half a member gets.
|
||||
fn member(symbol: &Symbol, lines: &LineIndex, surface: Surface) -> Decl {
|
||||
Decl {
|
||||
name: symbol.name.clone(),
|
||||
name_span: symbol.name_span,
|
||||
@@ -46,13 +57,14 @@ impl Decl {
|
||||
detail_span: symbol.detail_span,
|
||||
lines: DeclLines::of(lines, symbol.name_span, symbol.detail_span),
|
||||
type_name: symbol.type_name.clone(),
|
||||
surface,
|
||||
}
|
||||
}
|
||||
|
||||
/// A file-scope declaration: the same, plus the two ranges a client is
|
||||
/// pointed at, converted here so no one converts them later.
|
||||
fn unit(symbol: &Symbol, src: &str, lines: &LineIndex) -> Decl {
|
||||
let mut decl = Decl::member(symbol, lines);
|
||||
let mut decl = Decl::member(symbol, lines, Surface::Connection);
|
||||
decl.lines.positions = Some(DeclPositions {
|
||||
name: Utf16Range::of(src, lines, symbol.name_span),
|
||||
decl: Utf16Range::of(src, lines, symbol.decl_span),
|
||||
@@ -99,7 +111,8 @@ pub struct FileFacts {
|
||||
pub(crate) defines: DefineTable,
|
||||
/// File-scope declarations, in declaration order.
|
||||
pub(crate) units: Vec<Decl>,
|
||||
/// Members, each under the name of the unit that exports it, in the order
|
||||
/// Members, each under the name of the unit that exports it and tagged
|
||||
/// with the surface it is exported on ([`Decl::surface`]), in the order
|
||||
/// the scope tree yields them.
|
||||
pub(crate) members: Vec<(String, Decl)>,
|
||||
/// Instantiation sites, each under the name of the module instantiated, in
|
||||
@@ -108,6 +121,10 @@ pub struct FileFacts {
|
||||
/// Class declarations with a base, each under the base's name, in walk
|
||||
/// order.
|
||||
pub(crate) subclasses: Vec<(String, DeclSite)>,
|
||||
/// Package re-exports, each under the name of the package that writes it,
|
||||
/// in source order — [`super::reexport::of`]'s answer, `export *::*;`
|
||||
/// already expanded to that package's imports.
|
||||
pub(crate) reexports: Vec<(String, Reexport)>,
|
||||
/// Uses of declarations another file may name, stored before file ids and
|
||||
/// cross-file candidates have been resolved by the finished index.
|
||||
pub(crate) references: Vec<ReferenceFact>,
|
||||
@@ -148,7 +165,17 @@ pub(crate) enum ReferenceFact {
|
||||
/// chases it. Without it a `this.x` whose class is another file's had no
|
||||
/// posting at all, so a cross-file find-references from the property's
|
||||
/// own declaration did not list it (round 1's residue).
|
||||
External { name: String, base: Option<String>, paths: Vec<String>, occurrence: TextRange },
|
||||
External {
|
||||
name: String,
|
||||
base: Option<String>,
|
||||
paths: Vec<String>,
|
||||
/// Which member surface the recorded paths are walked in — carried
|
||||
/// straight from [`Resolution::ExternalCandidate`], because the file
|
||||
/// that wrote the path is the only layer that knows whether its head
|
||||
/// was an instance.
|
||||
surface: Surface,
|
||||
occurrence: TextRange,
|
||||
},
|
||||
}
|
||||
|
||||
impl ReferenceFact {
|
||||
@@ -274,6 +301,7 @@ fn facts_from_analysis(
|
||||
members: Vec::new(),
|
||||
instantiations: edges_of(tree, src, lines),
|
||||
subclasses: inheritance_of(tree),
|
||||
reexports: reexport::of(tree),
|
||||
references: Vec::new(),
|
||||
words: census.words,
|
||||
macro_words: census.macro_words,
|
||||
@@ -291,11 +319,29 @@ fn facts_from_analysis(
|
||||
facts.units.push(Decl::unit(unit, src, lines));
|
||||
collect_members(sem, &unit.name, unit, lines, &mut facts.members);
|
||||
}
|
||||
// The **connection** surface only. A `Local` posting exists so that a
|
||||
// declaration another file can point at carries its own file's uses
|
||||
// without that file being re-read, and every consumer of the postings
|
||||
// that matters here — the rename, which re-analyses the declaring file
|
||||
// anyway — already has them. Posting a module's every internal net use
|
||||
// would multiply the reference table by the size of an RTL body for an
|
||||
// answer nothing reads; the hierarchical surface is what a *cross-file*
|
||||
// tail resolves through, and that half is an `External` fact below.
|
||||
// See `docs/features/hierarchical-tail/README.md`, "what did not widen".
|
||||
// Which kind lands on which surface is `hierarchy::surface_of`, the one
|
||||
// rule this filter and the member tables both read (§49's QA asked for
|
||||
// the pointer).
|
||||
let exported: HashSet<(u32, u32)> = facts
|
||||
.units
|
||||
.iter()
|
||||
.map(|decl| (decl.name_span.start, decl.name_span.end))
|
||||
.chain(facts.members.iter().map(|(_, decl)| (decl.name_span.start, decl.name_span.end)))
|
||||
.chain(
|
||||
facts
|
||||
.members
|
||||
.iter()
|
||||
.filter(|(_, decl)| decl.surface == Surface::Connection)
|
||||
.map(|(_, decl)| (decl.name_span.start, decl.name_span.end)),
|
||||
)
|
||||
.collect();
|
||||
for reference in sem.references() {
|
||||
let fact = match &reference.resolution {
|
||||
@@ -305,21 +351,25 @@ fn facts_from_analysis(
|
||||
.contains(&(definition.start, definition.end))
|
||||
.then_some(ReferenceFact::Local { definition, occurrence: reference.name_span })
|
||||
}),
|
||||
Resolution::ExternalCandidate { paths } if !paths.is_empty() => {
|
||||
Resolution::ExternalCandidate { paths, surface } if !paths.is_empty() => {
|
||||
Some(ReferenceFact::External {
|
||||
name: reference.name.clone(),
|
||||
base: None,
|
||||
paths: paths.clone(),
|
||||
surface: *surface,
|
||||
occurrence: reference.name_span,
|
||||
})
|
||||
}
|
||||
// An inherited candidate is recorded even with **no** paths: the
|
||||
// base alone is a handle on the declaration, and the merge chases
|
||||
// it through the same member tables the overlay does.
|
||||
// An inherited miss is a class's business, and a class has one
|
||||
// surface.
|
||||
Resolution::InheritedCandidate { base, paths } => Some(ReferenceFact::External {
|
||||
name: reference.name.clone(),
|
||||
base: Some(base.clone()),
|
||||
paths: paths.clone(),
|
||||
surface: Surface::Connection,
|
||||
occurrence: reference.name_span,
|
||||
}),
|
||||
_ => None,
|
||||
@@ -409,10 +459,13 @@ fn collect_members(
|
||||
let Some(member) = sem.symbol(id) else {
|
||||
continue;
|
||||
};
|
||||
if !is_exported(unit.kind, member.kind) || member.name_span.is_empty() {
|
||||
let Some(surface) = hierarchy::surface_of(unit.kind, member.kind) else {
|
||||
continue;
|
||||
};
|
||||
if member.name_span.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut decl = Decl::member(member, lines);
|
||||
let mut decl = Decl::member(member, lines, surface);
|
||||
let nested = nested_key(key, member);
|
||||
if let Some(nested) = &nested {
|
||||
decl.type_name = Some(nested.clone());
|
||||
@@ -479,80 +532,3 @@ fn is_unit(kind: SymbolKind) -> bool {
|
||||
matches!(kind, SymbolKind::Package | SymbolKind::Typedef | SymbolKind::Class)
|
||||
|| kind.is_instantiable()
|
||||
}
|
||||
|
||||
/// What `unit::member` / `.member` may reach.
|
||||
///
|
||||
/// A package or class exports everything declared at its top level (a
|
||||
/// package's classes included — that is what lets `import uvm_pkg::*` answer
|
||||
/// `uvm_object`). A **module** exports only what a connection list can name —
|
||||
/// its ports and its parameters — so an internal net is never reachable from
|
||||
/// another file.
|
||||
///
|
||||
/// An **interface** is the exception the 2026-09-01 round exists for: its
|
||||
/// signals *are* its surface. `virtual bus_if vif; vif.data` is how every DV
|
||||
/// testbench in the world reaches `data`, and `data` is an ordinary net or
|
||||
/// variable declared inside the interface, not a port of it. So an interface
|
||||
/// exports its nets, variables, ports, parameters, typedefs, methods, modports
|
||||
/// and clocking blocks. The module ruling is untouched: a module handle is an
|
||||
/// *instance*, whose internals no other file's connection list may name.
|
||||
fn is_exported(unit: SymbolKind, member: SymbolKind) -> bool {
|
||||
match unit {
|
||||
SymbolKind::Package | SymbolKind::Class => matches!(
|
||||
member,
|
||||
SymbolKind::Param
|
||||
| SymbolKind::LocalParam
|
||||
| SymbolKind::Typedef
|
||||
| SymbolKind::EnumVariant
|
||||
| SymbolKind::Function
|
||||
| SymbolKind::Task
|
||||
| SymbolKind::Net
|
||||
| SymbolKind::Var
|
||||
| SymbolKind::Class
|
||||
| SymbolKind::Constraint
|
||||
| SymbolKind::Covergroup
|
||||
| SymbolKind::Property
|
||||
| SymbolKind::Sequence
|
||||
),
|
||||
// A module exports its ports and parameters — and, since
|
||||
// `sva-bodies`, the properties and sequences declared in its body: a
|
||||
// bound-in checker module names them as `top.u_dut.p_req`, and an
|
||||
// `` `include``d assertion file instantiates them by bare name.
|
||||
SymbolKind::Module => matches!(
|
||||
member,
|
||||
SymbolKind::Port
|
||||
| SymbolKind::Param
|
||||
| SymbolKind::LocalParam
|
||||
| SymbolKind::Property
|
||||
| SymbolKind::Sequence
|
||||
),
|
||||
// A `typedef struct`/`union` exports its fields, and a field that is
|
||||
// itself an inline aggregate exports its own — which is what a
|
||||
// generated register package is: `reg2hw_t` → `ctrl` → `q`. Nothing
|
||||
// else lives in a struct body, so this arm is exhaustive by
|
||||
// construction rather than by policy.
|
||||
SymbolKind::Typedef | SymbolKind::StructMember => {
|
||||
matches!(member, SymbolKind::StructMember)
|
||||
}
|
||||
// A covergroup's surface is its labelled coverpoints and crosses —
|
||||
// `cg.cp` is how a cross in another covergroup, or a `get_coverage`
|
||||
// call in another file, names one — plus the `sample` method the
|
||||
// header declares.
|
||||
SymbolKind::Covergroup => {
|
||||
matches!(member, SymbolKind::Coverpoint | SymbolKind::Cross | SymbolKind::Function)
|
||||
}
|
||||
SymbolKind::Interface => matches!(
|
||||
member,
|
||||
SymbolKind::Net
|
||||
| SymbolKind::Var
|
||||
| SymbolKind::Port
|
||||
| SymbolKind::Param
|
||||
| SymbolKind::LocalParam
|
||||
| SymbolKind::Typedef
|
||||
| SymbolKind::Function
|
||||
| SymbolKind::Task
|
||||
| SymbolKind::Modport
|
||||
| SymbolKind::Clocking
|
||||
),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
//! Package re-exports (IEEE 1800 §26.6) as real edges of the index: the
|
||||
//! [`Reexport`] record one file contributes, the read-off that produces it,
|
||||
//! and the two walks that follow it — one name looked up through a chain of
|
||||
//! re-exports ([`member`]), and every name such a chain offers ([`members`]).
|
||||
//!
|
||||
//! `export b_pkg::x;` inside `a_pkg` does not put `x` in `a_pkg`'s scope; it
|
||||
//! makes `x` reachable to whoever imports `a_pkg`. The binder records the two
|
||||
//! halves as references and nothing more (`bind::Binder::bind_export_path`),
|
||||
//! so everything that makes `a_pkg::x` *mean* `b_pkg`'s `x` is here.
|
||||
//!
|
||||
//! See `docs/features/package-reexports/README.md`.
|
||||
|
||||
use std::collections::{HashSet, VecDeque};
|
||||
|
||||
use vlog_parser::ast::{ExportDecl, Item, ItemKind, SourceFile};
|
||||
|
||||
use crate::model::Surface;
|
||||
|
||||
use super::external::{own_chain, own_members};
|
||||
use super::{Def, WorkspaceIndex};
|
||||
|
||||
/// One name (or one wildcard) a package re-exports from another.
|
||||
///
|
||||
/// The two halves as written, with no interpretation applied: `item` is the
|
||||
/// bare `*` of `export b_pkg::*;` exactly as the parser stores it, because
|
||||
/// "everything that package exports" is a question only the finished index
|
||||
/// can answer.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct Reexport {
|
||||
/// The package the name is taken from, as written.
|
||||
pub(crate) package: String,
|
||||
/// The name re-exported, or `*` for every name `package` exports.
|
||||
pub(crate) item: String,
|
||||
}
|
||||
|
||||
impl Reexport {
|
||||
/// Whether this edge lets `name` through.
|
||||
fn admits(&self, name: &str) -> bool {
|
||||
self.item == "*" || self.item == name
|
||||
}
|
||||
|
||||
/// The one name this edge carries, or `None` for a wildcard.
|
||||
fn only(&self) -> Option<&str> {
|
||||
(self.item != "*").then_some(self.item.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// Every package re-export one file writes, under the name of the package
|
||||
/// that writes it, in source order.
|
||||
///
|
||||
/// **`export *::*;` is expanded here, into the exporting package's own
|
||||
/// imports.** It means "everything imported into this package is re-exported"
|
||||
/// (§26.6), and which packages those are is a property of this one file — the
|
||||
/// very file being read off — so recording it as a flag for a later walk to
|
||||
/// interpret would only move the same lookup somewhere with less information.
|
||||
/// `export *::*;` in a package that imports nothing therefore records nothing,
|
||||
/// which is also what it re-exports.
|
||||
pub(super) fn of(tree: &SourceFile) -> Vec<(String, Reexport)> {
|
||||
let mut out = Vec::new();
|
||||
for item in &tree.items {
|
||||
let ItemKind::Package { name, items, .. } = &item.kind else {
|
||||
continue;
|
||||
};
|
||||
for entry in exports_of(items) {
|
||||
out.push((name.clone(), entry));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The re-export edges one package body writes.
|
||||
fn exports_of(items: &[Item]) -> Vec<Reexport> {
|
||||
let mut out: Vec<Reexport> = Vec::new();
|
||||
let mut everything = false;
|
||||
for item in items {
|
||||
let ItemKind::Export(ExportDecl::Package(paths)) = &item.kind else {
|
||||
continue;
|
||||
};
|
||||
for path in paths {
|
||||
if path.pkg.text == "*" {
|
||||
everything = true;
|
||||
} else {
|
||||
add(&mut out, &path.pkg.text, &path.item.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
if everything {
|
||||
for item in items {
|
||||
if let ItemKind::Import(paths) = &item.kind {
|
||||
for path in paths {
|
||||
add(&mut out, &path.pkg.text, &path.item.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One edge, unless the package already writes it — `export b_pkg::x;` beside
|
||||
/// an `import b_pkg::x;` under an `export *::*;` is one edge, not two.
|
||||
fn add(out: &mut Vec<Reexport>, package: &str, item: &str) {
|
||||
let entry = Reexport { package: package.to_string(), item: item.to_string() };
|
||||
if !out.contains(&entry) {
|
||||
out.push(entry);
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` in the packages `unit` re-exports it from, transitively.
|
||||
///
|
||||
/// Breadth-first over the edges that *admit* `name` — `pkg::name` and
|
||||
/// `pkg::*`, never `pkg::other` — asking each package reached for `name` in
|
||||
/// its own members and its bases ([`own_chain`]). The first package that has
|
||||
/// it answers, so the nearest re-export wins, on the same first-hit-wins rule
|
||||
/// the `extends` chain follows.
|
||||
///
|
||||
/// **Terminates on any workspace.** A package is asked at most once (the
|
||||
/// visited set), so `a_pkg` re-exporting `b_pkg::*` while `b_pkg` re-exports
|
||||
/// `a_pkg::*` walks two hops and stops. Map reads only: no file is opened.
|
||||
pub(super) fn member<'i>(index: &'i WorkspaceIndex, unit: &str, name: &str) -> &'i [Def] {
|
||||
// The overwhelmingly common case, and the one every member miss in a
|
||||
// workspace without re-exports pays: one map read, nothing allocated.
|
||||
if index.reexports(unit).is_empty() {
|
||||
return &[];
|
||||
}
|
||||
let mut seen: HashSet<&str> = HashSet::from([unit]);
|
||||
let mut queue: VecDeque<&'i str> = VecDeque::new();
|
||||
admitting(index, unit, name, &mut queue);
|
||||
while let Some(hop) = queue.pop_front() {
|
||||
if !seen.insert(hop) {
|
||||
continue;
|
||||
}
|
||||
// A package's surface is a package's surface: one, and connection.
|
||||
let found = own_chain(index, hop, name, Surface::Connection);
|
||||
if !found.is_empty() {
|
||||
return found;
|
||||
}
|
||||
admitting(index, hop, name, &mut queue);
|
||||
}
|
||||
&[]
|
||||
}
|
||||
|
||||
/// The packages one hop further on that still let `name` through.
|
||||
fn admitting<'i>(index: &'i WorkspaceIndex, unit: &str, name: &str, queue: &mut VecDeque<&'i str>) {
|
||||
queue.extend(
|
||||
index.reexports(unit).iter().filter(|e| e.admits(name)).map(|e| e.package.as_str()),
|
||||
);
|
||||
}
|
||||
|
||||
/// Every name `unit` re-exports, with the declaration each one names — the
|
||||
/// listing twin of [`member`], and what a completion after `a_pkg::` adds to
|
||||
/// the package's own members.
|
||||
///
|
||||
/// A `pkg::*` edge contributes everything that package exports **and** carries
|
||||
/// on through that package's own re-exports; a `pkg::x` edge contributes at
|
||||
/// most `x`, and carries on only through edges that admit `x`. The visited set
|
||||
/// is keyed by (package, name-filter), so a cycle terminates here too, and a
|
||||
/// name reached twice is left to the caller to deduplicate against the unit's
|
||||
/// own members — which is what keeps a local declaration ahead of a
|
||||
/// re-exported one of the same name.
|
||||
pub(super) fn members<'i>(index: &'i WorkspaceIndex, unit: &str) -> Vec<(&'i str, &'i Def)> {
|
||||
let mut out: Vec<(&'i str, &'i Def)> = Vec::new();
|
||||
let mut seen: HashSet<(&str, Option<&str>)> = HashSet::new();
|
||||
let mut queue: VecDeque<(&'i str, Option<&'i str>)> = hops(index, unit);
|
||||
while let Some((package, only)) = queue.pop_front() {
|
||||
if !seen.insert((package, only)) {
|
||||
continue;
|
||||
}
|
||||
match only {
|
||||
None => {
|
||||
out.extend(own_members(index, package, Surface::Connection));
|
||||
queue.extend(hops(index, package));
|
||||
}
|
||||
Some(name) => {
|
||||
out.extend(
|
||||
own_chain(index, package, name, Surface::Connection)
|
||||
.first()
|
||||
.map(|def| (name, def)),
|
||||
);
|
||||
queue.extend(
|
||||
index
|
||||
.reexports(package)
|
||||
.iter()
|
||||
.filter(|e| e.admits(name))
|
||||
.map(|e| (e.package.as_str(), Some(name))),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One package's re-export edges as walk items: the package reached, and the
|
||||
/// one name the edge carries (`None` for a wildcard).
|
||||
fn hops<'i>(index: &'i WorkspaceIndex, unit: &str) -> VecDeque<(&'i str, Option<&'i str>)> {
|
||||
index.reexports(unit).iter().map(|e| (e.package.as_str(), e.only())).collect()
|
||||
}
|
||||
@@ -9,6 +9,8 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::defines::DefineKind;
|
||||
|
||||
use crate::model::Surface;
|
||||
|
||||
use super::external::{resolve_fact, ExternalTarget};
|
||||
use super::record::{facts_of, FileFacts, ReferenceFact};
|
||||
use super::{
|
||||
@@ -216,6 +218,15 @@ impl WorkspaceIndex {
|
||||
}
|
||||
}
|
||||
}
|
||||
// The re-export edges, which decide what `a_pkg::x` means and are
|
||||
// therefore an observable in their own right — a merge that dropped
|
||||
// one would otherwise show up only as whichever references happened to
|
||||
// resolve through it.
|
||||
for (exporter, edges) in &self.reexports {
|
||||
for edge in edges {
|
||||
out.push_str(&format!("reexport {exporter} <- {}::{}\n", edge.package, edge.item));
|
||||
}
|
||||
}
|
||||
for (name, edges) in self.subclasses() {
|
||||
for edge in edges {
|
||||
out.push_str(&format!(
|
||||
@@ -242,8 +253,10 @@ impl WorkspaceIndex {
|
||||
None => {
|
||||
self.units.clear();
|
||||
self.members.clear();
|
||||
self.hier_members.clear();
|
||||
self.instantiations.clear();
|
||||
self.subclasses.clear();
|
||||
self.reexports.clear();
|
||||
self.macro_definitions.clear();
|
||||
}
|
||||
Some(affected) => {
|
||||
@@ -252,6 +265,7 @@ impl WorkspaceIndex {
|
||||
}
|
||||
for name in &affected.containers {
|
||||
self.members.remove(name);
|
||||
self.hier_members.remove(name);
|
||||
}
|
||||
for name in &affected.modules {
|
||||
self.instantiations.remove(name);
|
||||
@@ -259,6 +273,9 @@ impl WorkspaceIndex {
|
||||
for name in &affected.bases {
|
||||
self.subclasses.remove(name);
|
||||
}
|
||||
for name in &affected.exporters {
|
||||
self.reexports.remove(name);
|
||||
}
|
||||
for name in &affected.macros {
|
||||
self.macro_definitions.remove(name);
|
||||
}
|
||||
@@ -276,7 +293,14 @@ impl WorkspaceIndex {
|
||||
if affected.is_some_and(|a| !a.containers.contains(unit)) {
|
||||
continue;
|
||||
}
|
||||
self.members
|
||||
// The record's own tag picks the table; the two are keyed
|
||||
// alike, are cleared together above, and a caller that names
|
||||
// no surface reads the connection one.
|
||||
let table = match decl.surface {
|
||||
Surface::Connection => &mut self.members,
|
||||
Surface::Hierarchical => &mut self.hier_members,
|
||||
};
|
||||
table
|
||||
.entry(unit.clone())
|
||||
.or_default()
|
||||
.entry(decl.name.clone())
|
||||
@@ -303,6 +327,12 @@ impl WorkspaceIndex {
|
||||
.or_default()
|
||||
.push(InheritanceEdge { file, subclass: subclass.clone() });
|
||||
}
|
||||
for (exporter, entry) in &facts.reexports {
|
||||
if affected.is_some_and(|a| !a.exporters.contains(exporter)) {
|
||||
continue;
|
||||
}
|
||||
self.reexports.entry(exporter.clone()).or_default().push(entry.clone());
|
||||
}
|
||||
for (entry, define) in facts.defines.entries().iter().enumerate() {
|
||||
if define.kind != DefineKind::Define
|
||||
|| affected.is_some_and(|a| !a.macros.contains(&define.name))
|
||||
@@ -346,8 +376,8 @@ impl WorkspaceIndex {
|
||||
};
|
||||
sites.entry(key).or_default().push(site);
|
||||
}
|
||||
ReferenceFact::External { name, base, paths, .. } => {
|
||||
match resolve_fact(self, name, base.as_deref(), paths) {
|
||||
ReferenceFact::External { name, base, paths, surface, .. } => {
|
||||
match resolve_fact(self, name, base.as_deref(), paths, *surface) {
|
||||
ExternalTarget::Resolved(def) => {
|
||||
sites.entry(DefinitionKey::of(&def)).or_default().push(site);
|
||||
}
|
||||
@@ -377,6 +407,10 @@ pub(super) struct Affected {
|
||||
containers: HashSet<String>,
|
||||
modules: HashSet<String>,
|
||||
bases: HashSet<String>,
|
||||
/// Keys of the `reexports` table — the package that writes the `export`,
|
||||
/// never the package it takes the name from: a file changing what `a_pkg`
|
||||
/// re-exports moves `a_pkg`'s edges and no one else's.
|
||||
exporters: HashSet<String>,
|
||||
macros: HashSet<String>,
|
||||
}
|
||||
|
||||
@@ -392,6 +426,7 @@ impl Affected {
|
||||
self.containers.extend(facts.members.iter().map(|(unit, _)| unit.clone()));
|
||||
self.modules.extend(facts.instantiations.iter().map(|(module, _)| module.clone()));
|
||||
self.bases.extend(facts.subclasses.iter().map(|(base, _)| base.clone()));
|
||||
self.exporters.extend(facts.reexports.iter().map(|(exporter, _)| exporter.clone()));
|
||||
self.macros.extend(facts.defines.entries().iter().map(|define| define.name.clone()));
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ use std::path::PathBuf;
|
||||
use vlog_parser::parse_source;
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, Definition, ExternalTarget, Resolution, ScopeKind, Semantics,
|
||||
SymbolId, SymbolKind, WorkspaceIndex,
|
||||
Surface, SymbolId, SymbolKind, WorkspaceIndex,
|
||||
};
|
||||
|
||||
fn sem(src: &str) -> Semantics {
|
||||
@@ -309,7 +309,7 @@ endclass
|
||||
";
|
||||
let s = sem(src);
|
||||
match resolution_at(&s, nth(src, "uvm_object", 0)) {
|
||||
Resolution::ExternalCandidate { paths } => {
|
||||
Resolution::ExternalCandidate { paths, .. } => {
|
||||
// The wildcard import and the bare unit name, in that order.
|
||||
assert_eq!(paths, vec!["uvm_pkg::*".to_string(), "uvm_object".to_string()]);
|
||||
}
|
||||
@@ -393,11 +393,17 @@ endclass
|
||||
let s = sem(src);
|
||||
assert_eq!(
|
||||
resolution_at(&s, nth(src, "other_pkg", 0)),
|
||||
Resolution::ExternalCandidate { paths: vec!["other_pkg".to_string()] }
|
||||
Resolution::ExternalCandidate {
|
||||
paths: vec!["other_pkg".to_string()],
|
||||
surface: Surface::Connection,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
resolution_at(&s, nth(src, "other_base", 0)),
|
||||
Resolution::ExternalCandidate { paths: vec!["other_base".to_string()] }
|
||||
Resolution::ExternalCandidate {
|
||||
paths: vec!["other_base".to_string()],
|
||||
surface: Surface::Connection,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
resolution_at(&s, nth(src, "member_miss", 0)),
|
||||
@@ -482,7 +488,7 @@ endfunction
|
||||
let s = sem(src);
|
||||
// The class is not in this file: the head is an external candidate...
|
||||
match resolution_at(&s, nth(src, "elsewhere", 0)) {
|
||||
Resolution::ExternalCandidate { paths } => {
|
||||
Resolution::ExternalCandidate { paths, .. } => {
|
||||
assert_eq!(paths, vec!["elsewhere".to_string()])
|
||||
}
|
||||
other => panic!("expected an external candidate, got {other:?}"),
|
||||
@@ -562,7 +568,10 @@ endmodule
|
||||
let s = sem(src);
|
||||
assert_eq!(
|
||||
resolution_at(&s, nth(src, "later::K", 0) + 7),
|
||||
Resolution::ExternalCandidate { paths: vec!["later::K".to_string()] }
|
||||
Resolution::ExternalCandidate {
|
||||
paths: vec!["later::K".to_string()],
|
||||
surface: Surface::Connection,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use vlog_parser::parse_source;
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, Def, ExternalTarget, FileFacts, Resolution, Semantics, Symbol,
|
||||
SymbolKind, WorkspaceIndex,
|
||||
analyze, resolve_external, Def, ExternalTarget, FileFacts, Resolution, Semantics, Surface,
|
||||
Symbol, SymbolKind, WorkspaceIndex,
|
||||
};
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -112,7 +112,10 @@ fn an_interface_instantiation_resolves_in_file_and_across_files() {
|
||||
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()] })
|
||||
Some(Resolution::ExternalCandidate {
|
||||
paths: vec!["bus_if".to_string()],
|
||||
surface: Surface::Connection,
|
||||
})
|
||||
);
|
||||
let def = overlay_def(&ws, sources[1].1, use_at).expect("the unit table answers");
|
||||
assert_eq!(def.kind, SymbolKind::Interface);
|
||||
@@ -251,7 +254,10 @@ fn the_modport_half_of_a_port_type_resolves_across_files() {
|
||||
let tail = after(src, "bus_if.");
|
||||
assert_eq!(
|
||||
resolution(&sem(src), tail),
|
||||
Some(Resolution::ExternalCandidate { paths: vec!["bus_if::mp".to_string()] })
|
||||
Some(Resolution::ExternalCandidate {
|
||||
paths: vec!["bus_if::mp".to_string()],
|
||||
surface: Surface::Connection,
|
||||
})
|
||||
);
|
||||
let def = overlay_def(&ws, src, tail).expect("the member table answers");
|
||||
assert_eq!(def.kind, SymbolKind::Modport);
|
||||
@@ -350,7 +356,10 @@ fn a_clocking_signal_is_reached_through_the_block_in_file_and_across_files() {
|
||||
let tail = after(env, "vif.cb.");
|
||||
assert_eq!(
|
||||
resolution(&sem(env), tail),
|
||||
Some(Resolution::ExternalCandidate { paths: vec!["bus_if::cb::data".to_string()] })
|
||||
Some(Resolution::ExternalCandidate {
|
||||
paths: vec!["bus_if::cb::data".to_string()],
|
||||
surface: Surface::Connection,
|
||||
})
|
||||
);
|
||||
let def = overlay_def(&ws, env, tail).expect("the member chain answers");
|
||||
assert_eq!(slice(&ws, &sources, &def), "data");
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
use std::path::PathBuf;
|
||||
use vlog_parser::parse_source;
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, Def, ExternalTarget, Resolution, Semantics, SymbolKind,
|
||||
analyze, resolve_external, Def, ExternalTarget, Resolution, Semantics, Surface, SymbolKind,
|
||||
WorkspaceIndex,
|
||||
};
|
||||
|
||||
@@ -284,11 +284,17 @@ endmodule
|
||||
let s = sem(src);
|
||||
assert_eq!(
|
||||
resolution_at(&s, tail(src, "h.user_id", 0)),
|
||||
Resolution::ExternalCandidate { paths: vec!["c1::user_id".to_string()] }
|
||||
Resolution::ExternalCandidate {
|
||||
paths: vec!["c1::user_id".to_string()],
|
||||
surface: Surface::Connection,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
resolution_at(&s, tail(src, "q.other", 0)),
|
||||
Resolution::ExternalCandidate { paths: vec!["c2::other".to_string()] }
|
||||
Resolution::ExternalCandidate {
|
||||
paths: vec!["c2::other".to_string()],
|
||||
surface: Surface::Connection,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -525,7 +531,10 @@ fn a_qualified_type_from_a_package_elsewhere_still_reaches_the_workspace() {
|
||||
let s = sem(src);
|
||||
assert_eq!(
|
||||
resolution_at(&s, tail(src, "h.user_id", 0)),
|
||||
Resolution::ExternalCandidate { paths: vec!["c1::user_id".to_string()] }
|
||||
Resolution::ExternalCandidate {
|
||||
paths: vec!["c1::user_id".to_string()],
|
||||
surface: Surface::Connection,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -795,7 +804,10 @@ fn a_chain_resolves_link_by_link_in_one_file() {
|
||||
fn a_chain_resolves_across_three_files() {
|
||||
assert_eq!(
|
||||
resolution_at(&sem(DRIVER), tail(DRIVER, "item.hdr.addr", 0)),
|
||||
Resolution::ExternalCandidate { paths: vec!["item_t::hdr::addr".to_string()] },
|
||||
Resolution::ExternalCandidate {
|
||||
paths: vec!["item_t::hdr::addr".to_string()],
|
||||
surface: Surface::Connection,
|
||||
},
|
||||
"the single-file layer composes the path and stops"
|
||||
);
|
||||
for order in [
|
||||
@@ -929,8 +941,11 @@ endmodule
|
||||
}
|
||||
|
||||
/// Across files, an instance head reaches what the index holds for the module
|
||||
/// — its **ports and parameters**, which is what a module exports (see the
|
||||
/// feature README's round-2 ruling on internal signals).
|
||||
/// on its **hierarchical** surface: its ports and parameters, and — since
|
||||
/// 2026-09-05 — its internal nets and variables too, because `u.internal` is
|
||||
/// a hierarchical path and IEEE 1800 §23.6 says a hierarchical path may name
|
||||
/// any of them (`docs/features/hierarchical-tail/README.md`). A `.internal(w)`
|
||||
/// *connection* is still refused: that reads the connection surface.
|
||||
#[test]
|
||||
fn an_instance_head_reaches_a_module_in_another_file() {
|
||||
const SUB: &str =
|
||||
@@ -938,16 +953,27 @@ fn an_instance_head_reaches_a_module_in_another_file() {
|
||||
const TOP: &str = "module m;\n sub u ();\n initial begin\n y = u.clk_i;\n y = u.W;\n y = u.internal;\n end\nendmodule\n";
|
||||
assert_eq!(
|
||||
resolution_at(&sem(TOP), tail(TOP, "u.clk_i", 0)),
|
||||
Resolution::ExternalCandidate { paths: vec!["sub::clk_i".to_string()] }
|
||||
// An instance head is a hierarchical path, and its tail reads the
|
||||
// module's hierarchical surface — which holds the connection surface
|
||||
// whole, so a *port* named through one has exactly one answer.
|
||||
Resolution::ExternalCandidate {
|
||||
paths: vec!["sub::clk_i".to_string()],
|
||||
surface: Surface::Hierarchical,
|
||||
}
|
||||
);
|
||||
let ws = index(&[("sub.sv", SUB), ("top.sv", TOP)]);
|
||||
let port = overlay_def(&ws, TOP, tail(TOP, "u.clk_i", 0)).expect("the port");
|
||||
assert_eq!(port.kind, SymbolKind::Port);
|
||||
let param = overlay_def(&ws, TOP, tail(TOP, "u.W", 0)).expect("the parameter");
|
||||
assert_eq!(param.kind, SymbolKind::Param);
|
||||
// An internal net is not exported to any other file — the same rule a
|
||||
// `.secret(w)` connection has always followed.
|
||||
assert!(overlay_def(&ws, TOP, tail(TOP, "u.internal", 0)).is_none());
|
||||
// An internal net is reached hierarchically and nowhere else: the tail
|
||||
// resolves to `sub`'s own declaration of it...
|
||||
let net = overlay_def(&ws, TOP, tail(TOP, "u.internal", 0)).expect("the internal net");
|
||||
assert_eq!(net.kind, SymbolKind::Net);
|
||||
// ...while the connection surface — what a `.internal(w)` connection and a
|
||||
// connection list's completion read — still does not hold it.
|
||||
assert!(ws.member("sub", "internal").is_empty());
|
||||
assert_eq!(ws.member("sub", "clk_i").len(), 1, "a port is on both surfaces, once");
|
||||
}
|
||||
|
||||
/// The spines a chain is **not** walked from, each still resolving whatever
|
||||
@@ -1035,7 +1061,10 @@ fn a_hierarchical_path_crosses_a_file_boundary() {
|
||||
const TB: &str = "module dut;\n core u_core ();\nendmodule\n\nmodule tb;\n dut dut_i ();\nendmodule\n\nmodule probe;\n initial y = tb.dut_i.u_core.sig;\nendmodule\n";
|
||||
assert_eq!(
|
||||
resolution_at(&sem(TB), tail(TB, "tb.dut_i.u_core.sig", 0)),
|
||||
Resolution::ExternalCandidate { paths: vec!["core::sig".to_string()] }
|
||||
Resolution::ExternalCandidate {
|
||||
paths: vec!["core::sig".to_string()],
|
||||
surface: Surface::Hierarchical,
|
||||
}
|
||||
);
|
||||
let ws = index(&[("core.sv", CORE), ("tb.sv", TB)]);
|
||||
let def = overlay_def(&ws, TB, tail(TB, "tb.dut_i.u_core.sig", 0)).expect("the leaf signal");
|
||||
|
||||
@@ -14,8 +14,8 @@
|
||||
use std::path::PathBuf;
|
||||
use vlog_parser::parse_source;
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, MemberSite, Resolution, Scope, ScopeId, Semantics, SymbolKind,
|
||||
WorkspaceIndex,
|
||||
analyze, resolve_external, MemberSite, Resolution, Scope, ScopeId, Semantics, Surface,
|
||||
SymbolKind, WorkspaceIndex,
|
||||
};
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -202,7 +202,7 @@ endmodule
|
||||
&[("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 {
|
||||
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");
|
||||
@@ -211,7 +211,10 @@ endmodule
|
||||
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())),
|
||||
Some(MemberSite::Unit {
|
||||
path: (*expected_site).to_string(),
|
||||
surface: Surface::Connection,
|
||||
}),
|
||||
"{needle}: the site is the path the resolution walks, minus the tail",
|
||||
);
|
||||
}
|
||||
@@ -390,7 +393,7 @@ fn super_with_a_base_in_another_file_names_that_base_as_the_unit() {
|
||||
let at = tail(src, "super.x");
|
||||
assert_eq!(
|
||||
s.member_site(scope_at(&s, at), "super", &[]),
|
||||
Some(MemberSite::Unit("elsewhere_c".to_string())),
|
||||
Some(MemberSite::Unit { path: "elsewhere_c".to_string(), surface: Surface::Connection }),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -497,10 +500,10 @@ fn a_package_no_file_here_declares_is_the_workspaces_unit() {
|
||||
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())),
|
||||
Some(MemberSite::Unit { path: "other_pkg".to_string(), surface: Surface::Connection }),
|
||||
);
|
||||
// Which is exactly the unit the resolution's own path names.
|
||||
let Resolution::ExternalCandidate { paths } = resolution_at(&s, at) else {
|
||||
let Resolution::ExternalCandidate { paths, .. } = resolution_at(&s, at) else {
|
||||
panic!("the workspace's business");
|
||||
};
|
||||
assert_eq!(paths, vec!["other_pkg::x".to_string()]);
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
//! Package re-exports (IEEE 1800 §26.6), both halves: what the binder records
|
||||
//! for an `export` line, and what the workspace index makes of it — the walk
|
||||
//! that lets `a_pkg::x` find the `x` `b_pkg` declares.
|
||||
//!
|
||||
//! See `docs/features/package-reexports/README.md`.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, Def, Definition, FileFacts, Resolution, Semantics, Surface,
|
||||
SymbolKind, WorkspaceIndex,
|
||||
};
|
||||
|
||||
fn semantics(src: &str) -> Semantics {
|
||||
let (file, _) = parse_source_tolerant(src);
|
||||
analyze(&file, src)
|
||||
}
|
||||
|
||||
fn index(files: &[(&str, &str)]) -> WorkspaceIndex {
|
||||
WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(*p), *s)))
|
||||
}
|
||||
|
||||
/// The one reference spelled `name`, or a panic naming what was recorded.
|
||||
fn only_reference<'a>(sem: &'a Semantics, name: &str) -> &'a vlog_semantic::Reference {
|
||||
let mut found = sem.references().iter().filter(|r| r.name == name);
|
||||
let first = found.next().unwrap_or_else(|| {
|
||||
panic!("no reference to `{name}`: {:?}", sem.references().iter().map(|r| &r.name))
|
||||
});
|
||||
assert!(found.next().is_none(), "more than one reference to `{name}`");
|
||||
first
|
||||
}
|
||||
|
||||
/// The workspace declarations go-to-definition offers at `needle`.
|
||||
fn external_defs(sem: &Semantics, ws: &WorkspaceIndex, src: &str, needle: &str) -> Vec<Def> {
|
||||
let offset = src.find(needle).expect("needle is in the source") as u32;
|
||||
match resolve_external(sem, ws).definition_of(sem, offset) {
|
||||
Some(Definition::External(defs)) => defs.to_vec(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The names completion offers after `unit::`.
|
||||
fn offered(ws: &WorkspaceIndex, unit: &str) -> Vec<String> {
|
||||
ws.members_of_chain(unit).into_iter().map(|(name, _)| name.to_string()).collect()
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// 48.1 — the binding half
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// Both halves of `export b_pkg::x;` are uses, each on its own bytes: the
|
||||
/// package half is what a jump to `b_pkg` follows, and the item half is what
|
||||
/// puts this very line in `x`'s reference set (and so in a rename's edit set).
|
||||
#[test]
|
||||
fn an_export_records_both_halves_on_exactly_their_own_bytes() {
|
||||
let src = "package a_pkg;\n export b_pkg::x;\nendpackage\n";
|
||||
let sem = semantics(src);
|
||||
|
||||
for name in ["b_pkg", "x"] {
|
||||
let reference = only_reference(&sem, name);
|
||||
assert_eq!(
|
||||
&src[reference.name_span.as_range()],
|
||||
name,
|
||||
"the span of `{name}` covers other bytes"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
only_reference(&sem, "x").resolution,
|
||||
Resolution::ExternalCandidate {
|
||||
paths: vec!["b_pkg::x".to_string()],
|
||||
surface: Surface::Connection,
|
||||
},
|
||||
"the item is a member of the package it is taken from"
|
||||
);
|
||||
assert_eq!(
|
||||
only_reference(&sem, "b_pkg").resolution,
|
||||
Resolution::ExternalCandidate {
|
||||
paths: vec!["b_pkg".to_string()],
|
||||
surface: Surface::Connection,
|
||||
},
|
||||
"the package half is the package itself"
|
||||
);
|
||||
}
|
||||
|
||||
/// `export b_pkg::*;` has no item to name — the `*` is a wildcard, not an
|
||||
/// identifier — so only the package half is recorded, exactly as
|
||||
/// `import b_pkg::*;` records only the package half.
|
||||
#[test]
|
||||
fn a_wildcard_export_records_the_package_half_alone() {
|
||||
let sem = semantics("package a_pkg;\n export b_pkg::*;\nendpackage\n");
|
||||
assert_eq!(
|
||||
sem.references().iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
|
||||
["b_pkg"],
|
||||
"the `*` is not a name"
|
||||
);
|
||||
}
|
||||
|
||||
/// `export *::*;` names nothing at all — neither half is an identifier.
|
||||
#[test]
|
||||
fn an_export_of_everything_records_no_reference() {
|
||||
let sem = semantics("package a_pkg;\n import b_pkg::*;\n export *::*;\nendpackage\n");
|
||||
assert_eq!(
|
||||
sem.references().iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
|
||||
["b_pkg"],
|
||||
"only the `import` line names anything"
|
||||
);
|
||||
}
|
||||
|
||||
/// **The negative that defines a re-export.** `export b_pkg::x;` makes `x`
|
||||
/// visible to whoever imports `a_pkg`; it does not make `x` visible *inside*
|
||||
/// `a_pkg`. So a bare `x` written beside the export is not found and carries
|
||||
/// no path to the workspace — until an `import` alongside it says otherwise,
|
||||
/// which is the second half of the test.
|
||||
#[test]
|
||||
fn a_reexported_name_is_not_visible_bare_inside_the_exporting_package() {
|
||||
let exported = "package a_pkg;\n export b_pkg::x;\n localparam Y = x;\nendpackage\n";
|
||||
let sem = semantics(exported);
|
||||
let uses: Vec<&Resolution> =
|
||||
sem.references().iter().filter(|r| r.name == "x").map(|r| &r.resolution).collect();
|
||||
assert_eq!(uses.len(), 2, "the export's item and the bare use");
|
||||
assert!(
|
||||
uses.contains(&&Resolution::NotFound),
|
||||
"the bare `x` is not found and offers the workspace nothing: {uses:?}"
|
||||
);
|
||||
|
||||
let imported =
|
||||
"package a_pkg;\n import b_pkg::*;\n export b_pkg::x;\n localparam Y = x;\nendpackage\n";
|
||||
let sem = semantics(imported);
|
||||
assert!(
|
||||
sem.references()
|
||||
.iter()
|
||||
.filter(|r| r.name == "x")
|
||||
.any(|r| matches!(&r.resolution, Resolution::ExternalCandidate { paths, .. }
|
||||
if paths.contains(&"b_pkg::*".to_string()))),
|
||||
"an `import` beside the `export` is what brings the name in"
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// 48.2 — the resolution half
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The three-file shape: `b_pkg` declares, `a_pkg` re-exports one name, and a
|
||||
/// third file reaches it two ways — `a_pkg::x` written out, and a bare `x`
|
||||
/// under `import a_pkg::*`.
|
||||
const B_PKG: &str =
|
||||
"package b_pkg;\n localparam int x = 8;\n localparam int y = 9;\nendpackage\n";
|
||||
|
||||
#[test]
|
||||
fn a_single_name_reexport_answers_for_the_package_that_declares_it() {
|
||||
let sources = [
|
||||
("a.sv", "package a_pkg;\n export b_pkg::x;\nendpackage\n"),
|
||||
("b.sv", B_PKG),
|
||||
("top.sv", "module top;\n import a_pkg::*;\n localparam W = x;\n localparam V = a_pkg::x;\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let sem = semantics(sources[2].1);
|
||||
|
||||
for needle in ["x;\n localparam V", "x;\nendmodule"] {
|
||||
let defs = external_defs(&sem, &ws, sources[2].1, needle);
|
||||
assert_eq!(defs.len(), 1, "{needle}: {defs:?}");
|
||||
assert_eq!(ws.path(defs[0].file).expect("indexed"), PathBuf::from("b.sv"));
|
||||
assert_eq!(defs[0].kind, SymbolKind::LocalParam);
|
||||
assert_eq!(defs[0].lines.name, 2, "b_pkg's own declaration line");
|
||||
}
|
||||
|
||||
assert_eq!(offered(&ws, "a_pkg"), ["x"], "the one name it re-exports, and not `y`");
|
||||
}
|
||||
|
||||
/// `export b_pkg::*;` offers every member `b_pkg` exports, and answers for
|
||||
/// each of them.
|
||||
#[test]
|
||||
fn a_wildcard_reexport_offers_every_member_of_the_package() {
|
||||
let sources = [
|
||||
("a.sv", "package a_pkg;\n export b_pkg::*;\nendpackage\n"),
|
||||
("b.sv", B_PKG),
|
||||
("top.sv", "module top;\n localparam W = a_pkg::y;\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let sem = semantics(sources[2].1);
|
||||
|
||||
assert_eq!(offered(&ws, "a_pkg"), ["x", "y"]);
|
||||
let defs = external_defs(&sem, &ws, sources[2].1, "y;\nendmodule");
|
||||
assert_eq!(defs.len(), 1, "{defs:?}");
|
||||
assert_eq!(ws.path(defs[0].file).expect("indexed"), PathBuf::from("b.sv"));
|
||||
}
|
||||
|
||||
/// `export *::*;` re-exports what the package **imports**, which is the one
|
||||
/// reading of §26.6 a single file can settle — so `a_pkg::y` resolves through
|
||||
/// an `import b_pkg::*` that the export makes visible onward.
|
||||
#[test]
|
||||
fn an_export_of_everything_reexports_what_the_package_imports() {
|
||||
let sources = [
|
||||
("a.sv", "package a_pkg;\n import b_pkg::*;\n export *::*;\nendpackage\n"),
|
||||
("b.sv", B_PKG),
|
||||
("top.sv", "module top;\n localparam W = a_pkg::y;\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let sem = semantics(sources[2].1);
|
||||
|
||||
assert_eq!(offered(&ws, "a_pkg"), ["x", "y"]);
|
||||
assert_eq!(external_defs(&sem, &ws, sources[2].1, "y;\nendmodule").len(), 1);
|
||||
|
||||
// And a package that imports one name re-exports exactly that one.
|
||||
let narrow = [
|
||||
("a.sv", "package a_pkg;\n import b_pkg::x;\n export *::*;\nendpackage\n"),
|
||||
("b.sv", B_PKG),
|
||||
];
|
||||
assert_eq!(offered(&index(&narrow), "a_pkg"), ["x"]);
|
||||
|
||||
// A package that imports nothing re-exports nothing, which is what
|
||||
// `export *::*;` means there.
|
||||
let empty = [("a.sv", "package a_pkg;\n export *::*;\nendpackage\n"), ("b.sv", B_PKG)];
|
||||
assert!(offered(&index(&empty), "a_pkg").is_empty());
|
||||
}
|
||||
|
||||
/// A chain of re-exports is followed to its end: `a_pkg` ← `mid_pkg` ←
|
||||
/// `b_pkg`.
|
||||
#[test]
|
||||
fn a_chain_of_reexports_is_followed_transitively() {
|
||||
let sources = [
|
||||
("a.sv", "package a_pkg;\n export mid_pkg::*;\nendpackage\n"),
|
||||
("b.sv", B_PKG),
|
||||
("mid.sv", "package mid_pkg;\n export b_pkg::x;\nendpackage\n"),
|
||||
("top.sv", "module top;\n localparam W = a_pkg::x;\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let sem = semantics(sources[3].1);
|
||||
|
||||
assert_eq!(offered(&ws, "a_pkg"), ["x"], "`y` is not re-exported by the middle package");
|
||||
let defs = external_defs(&sem, &ws, sources[3].1, "x;\nendmodule");
|
||||
assert_eq!(defs.len(), 1, "{defs:?}");
|
||||
assert_eq!(ws.path(defs[0].file).expect("indexed"), PathBuf::from("b.sv"));
|
||||
}
|
||||
|
||||
/// A cycle terminates and answers honestly: `a_pkg` re-exports `b_pkg::*`
|
||||
/// while `b_pkg` re-exports `a_pkg::*`. Each package is asked once, so the
|
||||
/// name that really is declared is found and the name that is not simply is
|
||||
/// not.
|
||||
#[test]
|
||||
fn a_reexport_cycle_terminates() {
|
||||
let sources = [
|
||||
("a.sv", "package a_pkg;\n export b_pkg::*;\nendpackage\n"),
|
||||
("b.sv", "package b_pkg;\n localparam int x = 8;\n export a_pkg::*;\nendpackage\n"),
|
||||
(
|
||||
"top.sv",
|
||||
"module top;\n localparam W = a_pkg::x;\n localparam V = a_pkg::nope;\nendmodule\n",
|
||||
),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let sem = semantics(sources[2].1);
|
||||
|
||||
assert_eq!(offered(&ws, "a_pkg"), ["x"]);
|
||||
assert_eq!(offered(&ws, "b_pkg"), ["x"], "and the other way round");
|
||||
assert_eq!(external_defs(&sem, &ws, sources[2].1, "x;\n localparam V").len(), 1);
|
||||
assert!(
|
||||
external_defs(&sem, &ws, sources[2].1, "nope;\nendmodule").is_empty(),
|
||||
"a name nobody declares stays unanswered rather than looping"
|
||||
);
|
||||
}
|
||||
|
||||
/// A re-export of a name the package does not declare resolves to nothing and
|
||||
/// panics nowhere — the `export` line's item is simply an unanswered
|
||||
/// reference, exactly like any other name the workspace does not hold.
|
||||
#[test]
|
||||
fn a_reexport_of_a_name_the_package_does_not_declare_is_unresolved() {
|
||||
let sources = [
|
||||
("a.sv", "package a_pkg;\n export b_pkg::missing;\nendpackage\n"),
|
||||
("b.sv", B_PKG),
|
||||
("top.sv", "module top;\n localparam W = a_pkg::missing;\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let sem = semantics(sources[0].1);
|
||||
|
||||
assert!(external_defs(&sem, &ws, sources[0].1, "missing;\nendpackage").is_empty());
|
||||
assert!(offered(&ws, "a_pkg").is_empty(), "nothing is offered that nothing declares");
|
||||
let top = semantics(sources[2].1);
|
||||
assert!(external_defs(&top, &ws, sources[2].1, "missing;\nendmodule").is_empty());
|
||||
}
|
||||
|
||||
/// A package's own declaration beats a name it also re-exports — the
|
||||
/// first-hit-wins rule the `extends` chain follows, applied one hop further
|
||||
/// out. Listed once, and from the nearer of the two.
|
||||
#[test]
|
||||
fn a_local_declaration_wins_over_a_reexported_name_of_the_same_spelling() {
|
||||
let sources = [
|
||||
("a.sv", "package a_pkg;\n localparam int x = 1;\n export b_pkg::*;\nendpackage\n"),
|
||||
("b.sv", B_PKG),
|
||||
("top.sv", "module top;\n localparam W = a_pkg::x;\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let sem = semantics(sources[2].1);
|
||||
|
||||
assert_eq!(offered(&ws, "a_pkg"), ["x", "y"], "one `x`, not two");
|
||||
let defs = external_defs(&sem, &ws, sources[2].1, "x;\nendmodule");
|
||||
assert_eq!(defs.len(), 1, "{defs:?}");
|
||||
assert_eq!(
|
||||
ws.path(defs[0].file).expect("indexed"),
|
||||
PathBuf::from("a.sv"),
|
||||
"the package's own declaration answers"
|
||||
);
|
||||
}
|
||||
|
||||
/// The reference posting a rename fans out from: every use of `b_pkg`'s `x`,
|
||||
/// **including the `export` line's item half**, is filed under `x`'s own
|
||||
/// declaration.
|
||||
#[test]
|
||||
fn the_export_line_and_every_use_through_it_post_against_the_declaration() {
|
||||
let sources = [
|
||||
("a.sv", "package a_pkg;\n export b_pkg::x;\nendpackage\n"),
|
||||
("b.sv", B_PKG),
|
||||
("top.sv", "module top;\n import a_pkg::*;\n localparam W = x;\nendmodule\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let x = ws.member("b_pkg", "x").first().expect("b_pkg declares x").clone();
|
||||
|
||||
let sites: Vec<PathBuf> = ws
|
||||
.references_to(&x)
|
||||
.iter()
|
||||
.map(|site| ws.path(site.file).expect("indexed").to_path_buf())
|
||||
.collect();
|
||||
assert!(sites.contains(&PathBuf::from("a.sv")), "the export line itself: {sites:?}");
|
||||
assert!(sites.contains(&PathBuf::from("top.sv")), "and the use through it: {sites:?}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The record: the `RX` group and the format bump
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The new group round-trips, and a record written **without** it — which is
|
||||
/// every record a `FACTS_FORMAT` 17 build wrote — decodes to nothing rather
|
||||
/// than being read short by one group.
|
||||
#[test]
|
||||
fn the_reexport_group_round_trips_and_a_format_17_record_is_rejected() {
|
||||
for src in [
|
||||
"package a_pkg;\n import c_pkg::*;\n export b_pkg::x, b_pkg::*;\n export *::*;\nendpackage\n",
|
||||
// ... and a record with an empty `RX` group, which is nearly every file.
|
||||
"module plain;\n wire clk;\nendmodule\n",
|
||||
] {
|
||||
let facts = FileFacts::of(PathBuf::from("/w/r.sv"), src);
|
||||
let line = facts.encode().expect("encodes");
|
||||
let back = FileFacts::decode(&line).expect("decodes");
|
||||
assert_eq!(back, facts, "every field, the re-exports included");
|
||||
assert_eq!(back.encode(), Some(line.clone()), "and re-encodes byte for byte");
|
||||
|
||||
let fields: Vec<&str> = line.split('\t').collect();
|
||||
let at = fields.iter().position(|field| *field == "RX").expect("RX tag");
|
||||
let format_17 = [&fields[..at], &fields[at + 2 + 3 * facts_rx_len(&facts)..]]
|
||||
.concat()
|
||||
.join("\t");
|
||||
assert!(
|
||||
FileFacts::decode(&format_17).is_none(),
|
||||
"a format-17 record decoded as a format-18 one: {format_17}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// How many `RX` entries a record holds, counted off its encoding — the test
|
||||
/// above cuts exactly that many triples out.
|
||||
fn facts_rx_len(facts: &FileFacts) -> usize {
|
||||
let line = facts.encode().expect("encodes");
|
||||
let fields: Vec<&str> = line.split('\t').collect();
|
||||
let at = fields.iter().position(|field| *field == "RX").expect("RX tag");
|
||||
fields[at + 1].parse().expect("a count")
|
||||
}
|
||||
|
||||
/// An incremental update produces the very index a full build would — with
|
||||
/// the re-export table included, which the fingerprint now names.
|
||||
#[test]
|
||||
fn an_update_and_a_build_agree_on_the_reexport_table() {
|
||||
let a = "package a_pkg;\n export b_pkg::x;\nendpackage\n";
|
||||
let b = B_PKG;
|
||||
let built = index(&[("a.sv", a), ("b.sv", b)]);
|
||||
|
||||
let mut updated = index(&[("a.sv", "package a_pkg;\nendpackage\n"), ("b.sv", b)]);
|
||||
assert!(!updated.fingerprint().contains("reexport a_pkg"), "nothing re-exported yet");
|
||||
updated.update_file(PathBuf::from("a.sv"), a);
|
||||
assert_eq!(updated.fingerprint(), built.fingerprint());
|
||||
assert!(built.fingerprint().contains("reexport a_pkg <- b_pkg::x"));
|
||||
|
||||
// And removing the export again leaves the table as empty as it started.
|
||||
updated.update_file(PathBuf::from("a.sv"), "package a_pkg;\nendpackage\n");
|
||||
assert!(!updated.fingerprint().contains("reexport a_pkg"));
|
||||
assert!(updated.members_of_chain("a_pkg").is_empty());
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//! What `analyze` binds, what it resolves, and what it refuses to guess.
|
||||
|
||||
use vlog_parser::{parse_source, parse_source_tolerant};
|
||||
use vlog_semantic::{analyze, Resolution, Semantics, SymbolId, SymbolKind};
|
||||
use vlog_semantic::{analyze, Resolution, Semantics, Surface, SymbolId, SymbolKind};
|
||||
|
||||
fn sem(src: &str) -> Semantics {
|
||||
let file = parse_source(src).expect("fixture must parse");
|
||||
@@ -310,25 +310,37 @@ endmodule
|
||||
let some = s.reference_at(nth(src, "SOMETHING", 0)).expect("the use");
|
||||
assert_eq!(
|
||||
some.resolution,
|
||||
Resolution::ExternalCandidate { paths: vec!["other_pkg::*".into()] }
|
||||
Resolution::ExternalCandidate {
|
||||
paths: vec!["other_pkg::*".into()],
|
||||
surface: Surface::Connection,
|
||||
}
|
||||
);
|
||||
let thing = s.reference_at(nth(src, "named_pkg::THING", 0) + 11).expect("the imported name");
|
||||
assert_eq!(
|
||||
thing.resolution,
|
||||
Resolution::ExternalCandidate { paths: vec!["named_pkg::THING".into()] }
|
||||
Resolution::ExternalCandidate {
|
||||
paths: vec!["named_pkg::THING".into()],
|
||||
surface: Surface::Connection,
|
||||
}
|
||||
);
|
||||
|
||||
let scoped = s.reference_at(nth(src, "elsewhere_pkg::VALUE", 0) + 15).expect("the tail");
|
||||
assert_eq!(
|
||||
scoped.resolution,
|
||||
Resolution::ExternalCandidate { paths: vec!["elsewhere_pkg::VALUE".into()] }
|
||||
Resolution::ExternalCandidate {
|
||||
paths: vec!["elsewhere_pkg::VALUE".into()],
|
||||
surface: Surface::Connection,
|
||||
}
|
||||
);
|
||||
|
||||
// An instantiation of a module this file does not declare, and its ports.
|
||||
let module = s.reference_at(nth(src, "missing_mod", 0)).expect("the module name");
|
||||
assert_eq!(
|
||||
module.resolution,
|
||||
Resolution::ExternalCandidate { paths: vec!["missing_mod".into()] }
|
||||
Resolution::ExternalCandidate {
|
||||
paths: vec!["missing_mod".into()],
|
||||
surface: Surface::Connection,
|
||||
}
|
||||
);
|
||||
let port = s.reference_at(nth(src, ".p(w)", 0) + 1).expect("the port name");
|
||||
assert!(port.is_external_candidate());
|
||||
@@ -798,7 +810,10 @@ endmodule
|
||||
assert_eq!(item.name, "t");
|
||||
assert_eq!(
|
||||
item.resolution,
|
||||
Resolution::ExternalCandidate { paths: vec!["pkg::t".into()] },
|
||||
Resolution::ExternalCandidate {
|
||||
paths: vec!["pkg::t".into()],
|
||||
surface: Surface::Connection,
|
||||
},
|
||||
"the same candidate `pkg::t x;` would record"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use vlog_parser::defines::{collect_defines, DefineTable};
|
||||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize};
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, Def, Definition, ExternalTarget, FileFacts, FileId, Resolution,
|
||||
Semantics, SymbolKind, Utf16Pos, WorkspaceIndex,
|
||||
Semantics, Surface, SymbolKind, Utf16Pos, WorkspaceIndex,
|
||||
};
|
||||
|
||||
/// Build an index from `(path, source)` literals, as a server would from disk.
|
||||
@@ -529,7 +529,10 @@ fn an_unqualified_type_miss_carries_its_own_name_to_the_unit_table() {
|
||||
|
||||
assert_eq!(
|
||||
resolution(&sem, sources[1].1, "bus_if bus"),
|
||||
Resolution::ExternalCandidate { paths: vec!["bus_if".to_string()] }
|
||||
Resolution::ExternalCandidate {
|
||||
paths: vec!["bus_if".to_string()],
|
||||
surface: Surface::Connection,
|
||||
}
|
||||
);
|
||||
let defs = external_defs(&sem, &ws, sources[1].1, "bus_if bus");
|
||||
assert_eq!(defs.len(), 1, "{defs:?}");
|
||||
@@ -600,7 +603,10 @@ fn a_direction_less_first_ansi_port_binds_its_interface_type_cross_file() {
|
||||
let sem = semantics(src);
|
||||
assert_eq!(
|
||||
resolution(&sem, src, needle),
|
||||
Resolution::ExternalCandidate { paths: vec!["bus_if".to_string()] },
|
||||
Resolution::ExternalCandidate {
|
||||
paths: vec!["bus_if".to_string()],
|
||||
surface: Surface::Connection,
|
||||
},
|
||||
"{needle}"
|
||||
);
|
||||
let defs = external_defs(&sem, &ws, src, needle);
|
||||
@@ -771,7 +777,10 @@ fn an_import_that_can_supply_the_name_still_wins_over_a_same_named_unit() {
|
||||
|
||||
assert_eq!(
|
||||
resolution(&sem, sources[2].1, "state_t s"),
|
||||
Resolution::ExternalCandidate { paths: vec!["tdp::*".to_string(), "state_t".to_string()] }
|
||||
Resolution::ExternalCandidate {
|
||||
paths: vec!["tdp::*".to_string(), "state_t".to_string()],
|
||||
surface: Surface::Connection,
|
||||
}
|
||||
);
|
||||
let defs = external_defs(&sem, &ws, sources[2].1, "state_t s");
|
||||
assert_eq!(defs.len(), 1, "{defs:?}");
|
||||
@@ -896,7 +905,7 @@ fn the_corpus_index_finishes_most_external_references() {
|
||||
let counts = ws.counts();
|
||||
println!(
|
||||
"workspace index: {} files in {:.2}s — {} modules, {} packages, {} file-scope typedefs, \
|
||||
{} classes, {} exported members, {} define directives",
|
||||
{} classes, {} exported members (+{} hierarchical-only), {} define directives",
|
||||
counts.files,
|
||||
build.as_secs_f64(),
|
||||
counts.modules,
|
||||
@@ -904,6 +913,7 @@ fn the_corpus_index_finishes_most_external_references() {
|
||||
counts.typedefs,
|
||||
counts.classes,
|
||||
counts.members,
|
||||
counts.hierarchical_members,
|
||||
counts.defines,
|
||||
);
|
||||
|
||||
@@ -1004,7 +1014,7 @@ impl Tally {
|
||||
ExternalTarget::StillUnresolved => {
|
||||
self.unresolved += 1;
|
||||
let paths = match &reference.resolution {
|
||||
Resolution::ExternalCandidate { paths } => paths.join(" | "),
|
||||
Resolution::ExternalCandidate { paths, .. } => paths.join(" | "),
|
||||
_ => String::new(),
|
||||
};
|
||||
let entry = self.misses.entry(paths).or_insert((0, reference.name.clone()));
|
||||
@@ -1064,6 +1074,72 @@ impl Tally {
|
||||
}
|
||||
}
|
||||
|
||||
/// **The §49 census delta, measured rather than asserted.** Over the whole
|
||||
/// corpus, how many references the hierarchical surface is the *only* reason
|
||||
/// the workspace can answer: a candidate carrying [`Surface::Hierarchical`]
|
||||
/// that lands on a record the *hierarchical-only* table holds. Membership of
|
||||
/// that table is the exact test — a hierarchical candidate landing on a port,
|
||||
/// a parameter or an **interface's** signal is not part of the delta, because
|
||||
/// those are on the connection surface and resolved before §49 too, through
|
||||
/// the connection table the hierarchical read consults first.
|
||||
///
|
||||
/// The number is printed, not pinned to a constant: the corpus moves, and a
|
||||
/// hard number here would be a test that fails for the wrong reason. What is
|
||||
/// pinned is the direction — the hierarchical surface must actually be
|
||||
/// answering something, and every answer it gives must be one of the three
|
||||
/// kinds that live on it.
|
||||
#[test]
|
||||
fn the_hierarchical_surface_is_what_answers_a_measurable_slice_of_the_corpus() {
|
||||
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 paths = Vec::new();
|
||||
collect(&root, &mut paths);
|
||||
paths.sort();
|
||||
let sources: Vec<(PathBuf, String)> = paths
|
||||
.iter()
|
||||
.filter_map(|p| std::fs::read_to_string(p).ok().map(|s| (p.clone(), s)))
|
||||
.collect();
|
||||
let ws = WorkspaceIndex::build(sources.iter().map(|(p, s)| (p.clone(), s.as_str())));
|
||||
|
||||
let (mut candidates, mut answered, mut only_hierarchical) = (0usize, 0usize, 0usize);
|
||||
for (_, src) in &sources {
|
||||
let (tree, _) = parse_source_tolerant(src);
|
||||
let sem = analyze(&tree, src);
|
||||
let overlay = resolve_external(&sem, &ws);
|
||||
for (i, reference) in sem.references().iter().enumerate() {
|
||||
if !matches!(
|
||||
reference.resolution,
|
||||
Resolution::ExternalCandidate { surface: Surface::Hierarchical, .. }
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
candidates += 1;
|
||||
let Some(ExternalTarget::Resolved(def)) =
|
||||
overlay.get(vlog_semantic::ReferenceId(i as u32))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
answered += 1;
|
||||
let hierarchical_only = ws
|
||||
.hierarchical_declarations(&reference.name)
|
||||
.any(|(_, d)| d.file == def.file && d.name_span == def.name_span);
|
||||
only_hierarchical += usize::from(hierarchical_only);
|
||||
}
|
||||
}
|
||||
println!(
|
||||
"hierarchical tails: {candidates} candidates, {answered} answered, \
|
||||
{only_hierarchical} of them only because of the hierarchical surface"
|
||||
);
|
||||
assert!(candidates > 0, "the corpus does write hierarchical paths");
|
||||
assert!(
|
||||
only_hierarchical > 0,
|
||||
"the hierarchical surface answers references the connection surface could not"
|
||||
);
|
||||
}
|
||||
|
||||
fn collect(dir: &std::path::Path, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return;
|
||||
@@ -1936,8 +2012,8 @@ fn a_format_3_record_with_two_declarations_is_rejected_not_misread() {
|
||||
/// this format wrote back into what `FACTS_FORMAT` 3 wrote for the same file —
|
||||
/// remove, from every one of `units` unit-decls and `members` member-decls, the
|
||||
/// client positions added in format 5, the `decl_span` added in format 5, the
|
||||
/// declared type name added in format 7, and the two trailing (`name_line`,
|
||||
/// `detail_line`) fields added in format 4.
|
||||
/// surface letter added in format 19, the declared type name added in format 7,
|
||||
/// and the two trailing (`name_line`, `detail_line`) fields added in format 4.
|
||||
/// Assumes `D0` (no `` `define``s), which every fixture here satisfies, so the
|
||||
/// `U` tag's field index is fixed and decl positions can be computed directly
|
||||
/// rather than parsed.
|
||||
@@ -1946,8 +2022,8 @@ fn strip_every_decls_line_fields(encoded: &str, units: usize, members: usize) ->
|
||||
let units_at = fields.iter().position(|f| *f == "U").expect("a U tag");
|
||||
assert_eq!(fields[units_at + 1], units.to_string(), "premise: unit count");
|
||||
// A member's decl = name, kind, name_span×2, decl_span×2, detail_span×2,
|
||||
// line×2, type_name — 11 fields. A unit's is that plus its two client
|
||||
// ranges, four numbers each — 19.
|
||||
// line×2, type_name, surface — 12 fields. A unit's is that plus its two
|
||||
// client ranges, four numbers each — 20.
|
||||
let members_at = units_at + 2 + units * UNIT_DECL_FIELDS;
|
||||
assert_eq!(fields[members_at], "M", "premise: members tag follows the units");
|
||||
assert_eq!(fields[members_at + 1], members.to_string(), "premise: member count");
|
||||
@@ -1968,6 +2044,7 @@ fn strip_every_decls_line_fields(encoded: &str, units: usize, members: usize) ->
|
||||
if is_unit {
|
||||
fields.drain(start + MEMBER_DECL_FIELDS..start + UNIT_DECL_FIELDS);
|
||||
}
|
||||
fields.drain(start + 11..start + 12);
|
||||
fields.drain(start + 10..start + 11);
|
||||
fields.drain(start + 8..start + 10);
|
||||
fields.drain(start + 4..start + 6);
|
||||
@@ -1976,7 +2053,7 @@ fn strip_every_decls_line_fields(encoded: &str, units: usize, members: usize) ->
|
||||
}
|
||||
|
||||
/// Fields one member declaration occupies in a record this format writes.
|
||||
const MEMBER_DECL_FIELDS: usize = 11;
|
||||
const MEMBER_DECL_FIELDS: usize = 12;
|
||||
/// The same for a unit, which also carries its two client ranges.
|
||||
const UNIT_DECL_FIELDS: usize = MEMBER_DECL_FIELDS + 8;
|
||||
|
||||
|
||||
+16
-16
@@ -1,23 +1,23 @@
|
||||
# Verilog/SystemVerilog coverage gaps — ranked (2026-09-01)
|
||||
|
||||
**Reading this report today (2026-09-04).** The survey below is a historical
|
||||
**Reading this report today (2026-09-05).** The survey below is a historical
|
||||
v0.21.0 measurement with later amendments, not a fresh list of current failures.
|
||||
For the current implementation and outstanding contracts, use
|
||||
[repository-analysis.md](repository-analysis.md) and [topo.md](topo.md).
|
||||
Since the original survey, interface/modport and struct-member semantics,
|
||||
statement/class fences, header/list recovery, rule documentation, and three
|
||||
lint expansion waves have landed. The old probes were not re-run as part of
|
||||
the documentation audit; their historical counts are retained.
|
||||
Use [repository-analysis.md](repository-analysis.md) and [topo.md](topo.md) for
|
||||
current implementation status. Original probe counts remain historical.
|
||||
|
||||
Current follow-ups to the latest addendum: v0.40.0 recovers bare item-level
|
||||
`begin` blocks as `ItemKind::GenBlock` **in tolerant mode**, so lint rules see
|
||||
their contents; strict formatting still refuses them. It also improves recovery
|
||||
for unclosed overrides that would consume the following instance. The
|
||||
post-v0.41.0 `parser-skips` commit accepts rival conditional unit headers as
|
||||
verbatim units and preserves net delays before or after the type. Its QA is
|
||||
accepted; release v0.42.0 is pending. Comments immediately before a net-delay
|
||||
`#` still cause a formatter verification refusal. External waiver files remain
|
||||
planned, not implemented.
|
||||
Through v0.44.0, external waivers, rival conditional headers, net-delay
|
||||
positions and comment slots, inline aggregate overrides, statement/class
|
||||
fences, header recovery, and the three lint-expansion waves have shipped.
|
||||
The prior audit's atomic-write, project lint-selection and directory-cycle
|
||||
findings are also fixed. Bare item-level `begin` blocks are recovered for
|
||||
lint/editor consumers; strict formatting still refuses them.
|
||||
|
||||
At committed `9ef1058`, type-name spans replace `vlog_semantic/src/scan.rs`,
|
||||
and package re-exports resolve through shared member edges (facts codec 18).
|
||||
Both are accepted for the next release. The active hierarchical-tail work
|
||||
proposes codec 19; QA is pending, and handshake 23 remains open. DPI-export
|
||||
name binding is a separate remaining gap (handshake 31), and generate-block
|
||||
hierarchy and cross-file macro expansion remain outside these fixes.
|
||||
|
||||
What lucisv 0.21.0 does not yet handle, ranked by severity, from two
|
||||
independent sweeps crossed against each other:
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -124,6 +124,10 @@ where marked; no existing field changed meaning.
|
||||
edited (`a_hierarchical_tail_that_resolves_is_renamed_with_its_declaration`
|
||||
is the pin). Not this round's to fix — the warning is exactly the heads-up
|
||||
§2.9-20 asked for — but it is a real gap worth a row of its own.
|
||||
**Closed 2026-09-05 by TODO §49 / `docs/features/hierarchical-tail`:** a
|
||||
module's hierarchical surface makes the cross-file tail resolve, so the
|
||||
edit lands in both files and the warning is retired for a tail that
|
||||
resolved.
|
||||
3. **`docs/topo.md` rows 20, 21 and 22 are closed** and want striking by the
|
||||
lead (this round does not edit `topo.md`).
|
||||
|
||||
|
||||
@@ -86,6 +86,11 @@ taught anything new.
|
||||
unasked; (b) a DPI export's `name` refers to a function declared elsewhere in
|
||||
the same scope and could be a `use_name`. Note the `*::*` form has `"*"` as
|
||||
its **package** name, which no existing code expects.
|
||||
**(a) answered 2026-09-05 by TODO §48** — `bind_export_path` records exactly
|
||||
those two halves and pushes no scope import, and the index follows the edge
|
||||
(`docs/features/package-reexports/README.md`). `*::*` still records no
|
||||
reference, for the reason given: neither half is a name. **(b) is still
|
||||
open** — a DPI export's `name` is unbound.
|
||||
- **vlog_semantic / vlog_linter**: DPI-imported functions and tasks now arrive
|
||||
as ordinary `ItemKind::Function` / `ItemKind::Task` with `stmts` empty and
|
||||
`is_prototype` set, so `bind_function` already declares them as symbols — a
|
||||
|
||||
@@ -0,0 +1,657 @@
|
||||
# expand-wildcard
|
||||
|
||||
TODO §50 — the first of the §8 refactoring backlog to ship. One engine
|
||||
function, one code action, one command.
|
||||
|
||||
## Goal
|
||||
|
||||
`sub u_x (.clk(clk), .*);` binds every remaining port of `sub` to the
|
||||
same-named signal in the scope the instantiation is written in (IEEE 1800
|
||||
§23.3.2.4). **Expanding** the wildcard writes those bindings out: the
|
||||
refactoring an RTL engineer reaches for the moment a port list is about to
|
||||
diverge from the wrapper around it, and the one the ports engine already
|
||||
refuses to edit around — `add_port` and `remove_port` warn and leave a `.*`
|
||||
site alone, and `propagate_ports` declines a wildcard outright, because none of
|
||||
them can rewrite a connection nobody wrote. After this round the user can turn
|
||||
the wildcard into text first and then use all three.
|
||||
|
||||
The engine is `vlog_refactor::expand_wildcard`, so Vim, VS Code and any future
|
||||
CLI get identical behavior; `lucisv_server` maps the protocol and decides
|
||||
nothing. Whole-edit-or-nothing, through the ports engine's lexical splice and
|
||||
its "the file still parses" verifier: an `Ok` is safe to apply, an `Err` is a
|
||||
sentence for the user and no edits at all.
|
||||
|
||||
## API as built
|
||||
|
||||
```rust
|
||||
// crates/vlog_refactor/src/lib.rs
|
||||
pub fn expand_wildcard(files: &[(PathBuf, String)], file: &Path, offset: u32)
|
||||
-> Result<RefactorEdit, String>;
|
||||
// new beside `sites_phrase`, for the server's title arithmetic:
|
||||
pub fn is_sites_phrase(phrase: &str) -> bool;
|
||||
```
|
||||
|
||||
`files`, `RefactorEdit`, `TextEdit` and the `Err(String)`-is-a-sentence
|
||||
convention are M2's, unchanged. `port_actions` gained a third offer, so the
|
||||
code-action path needed no new entry point at all.
|
||||
|
||||
## The rule, exactly as implemented
|
||||
|
||||
At the cursor's instantiation — the instance whose span covers the offset, or
|
||||
the only instance of the statement whose module name it covers, which is
|
||||
`propagate_ports`'s own rule:
|
||||
|
||||
1. The connection list must be **named** and hold exactly **one** `.*`.
|
||||
2. Every port the instantiated module declares that the list does **not**
|
||||
name explicitly is what the wildcard stands for, in the module's
|
||||
**declaration order**. `.clk`, `.clk()` and `.clk(x)` all count as
|
||||
explicit — they are connections the source wrote, so `.*` never bound
|
||||
those ports.
|
||||
3. For each of them, lucisv asks `vlog_semantic` what the name means in the
|
||||
scope the *instance name* sits in — the generate block's, then its
|
||||
parents', up to the module's:
|
||||
- **a net, a variable, or a port** of that name → `.name(name)`;
|
||||
- **anything else, or nothing** → `.name()`, and a warning naming every
|
||||
port left that way.
|
||||
|
||||
"A signal" is read strictly, and that is the whole of the LRM rule that
|
||||
matters here: a **parameter**, a **localparam**, a **genvar**, a **type**,
|
||||
an **instance** or a **task/function argument** of the same name is *not* a
|
||||
net or a variable, so `.*` does not bind it. This is a narrower set than
|
||||
the one `add_port`/`propagate_ports` use when they *write* a connection
|
||||
(`find::visible_in`, which happily writes `.p(p)` for a parameter, because
|
||||
there the user asked for a connection and a parameter is a legal
|
||||
expression). Here the question is not "what could be connected" but "what
|
||||
*was* connected", and connecting an output port to a constant because a
|
||||
`localparam` happened to share its name would be a legal-looking, silent,
|
||||
wrong expansion. The two readers share one scope walk
|
||||
(`find::kind_visible_in`) so they cannot come to disagree about *which*
|
||||
declaration a name means, only about whether that kind counts.
|
||||
4. A port with nothing to bind to is one the wildcard never bound either —
|
||||
the compiler would have rejected the instantiation — so `.name()` plus the
|
||||
warning is the honest answer, and saying it out loud is half the point of
|
||||
the expansion. (It found two real ones in OpenTitan; see Acceptance.)
|
||||
|
||||
### Escaped identifiers
|
||||
|
||||
A port named `\my-port` is written `.\my-port (\my-port )`, with the space an
|
||||
escaped identifier needs after it: an escaped identifier runs from its `\` to
|
||||
the next **whitespace** and to nothing else (IEEE 1800 §5.6.1), so
|
||||
`.\my-port(\my-port)` would be one enormous token swallowing the parens, the
|
||||
comma and the rest of the line. `instantiate.rs` learned this from a QA
|
||||
finding on the skeleton renderer; `ends_escaped` is now `pub(crate)` and the
|
||||
expansion asks the same question rather than spelling the rule a second time.
|
||||
Two behavior tests pin it, bound and unbound.
|
||||
|
||||
### Layout
|
||||
|
||||
The `.*` element is **replaced**, in place, by the generated connections. The
|
||||
list's own layout is copied the way `append_to_list` copies it: the gap before
|
||||
the wildcard (from the previous element, or from the list's `(`) decides
|
||||
**one connection per line** — at the wildcard's own indentation — from
|
||||
**inline**, `, `-separated. Refactored output is *edited source*, not
|
||||
reformatted source (umbrella Handshakes); the user runs the formatter
|
||||
afterwards if they want more, and the acceptance tests below prove the
|
||||
formatter is happy with what is written.
|
||||
|
||||
### Comments
|
||||
|
||||
- A comment written **before** the `.*` is outside the replaced span and stays
|
||||
exactly where it is, which puts it before the first generated connection.
|
||||
- A comment written **after** it on the same line (`.* // and the rest`) gets
|
||||
the `append_to_list` treatment, for the same reason: the comma is written
|
||||
*before* the comment and the remaining connections after it, so the comment
|
||||
stays with the **first** generated connection instead of drifting onto the
|
||||
last, and no `,` is ever written inside a `//`.
|
||||
- A comment written **inside** the element (`. /* here */ *`) is inside the
|
||||
span the expansion replaces, so the verifier's comment rule refuses the
|
||||
whole refactoring. Comments are never dropped (invariant 3), and lucisv will
|
||||
not decide where that one should move.
|
||||
|
||||
## The refusal list — exact
|
||||
|
||||
`expand_wildcard` refuses when:
|
||||
|
||||
1. **The position is not an instantiation** — *"there is no module
|
||||
instantiation at this position."*
|
||||
2. **The statement declares several instances** — *"this statement declares 2
|
||||
instances of `sub`; put the cursor on the one to expand."*
|
||||
3. **The instance is a `bind` directive's** — *"`u_x` is instantiated by a
|
||||
`bind` directive, where `.*` binds in the target's scope rather than in
|
||||
this one; lucisv does not expand it there."* §23.3.2.4 resolves a bound
|
||||
instance's wildcard in the *target's* scope, which lucisv would have to
|
||||
elaborate a hierarchy to know. Out of scope for this round, and said so.
|
||||
(This is the majority of real `.*` sites in OpenTitan — see Acceptance.)
|
||||
4. **The list connects positionally** — *"`u_x` connects `sub`'s ports by
|
||||
position; there is no `.*` to expand."*
|
||||
5. **There is no `.*`** — *"`u_x` writes no `.*` to expand."*
|
||||
6. **There is more than one** — *"`u_x` writes `.*` 2 times, which is illegal;
|
||||
lucisv will not guess what it means."*
|
||||
7. **Either file carries a parse diagnostic** — *"top.sv does not parse (… at
|
||||
line N), so lucisv will not expand a `.*` in it."* Stricter than the
|
||||
verifier's "no *new* diagnostic" rule on purpose: a connection list lucisv
|
||||
misread is a list whose ports it would connect a second time, and a
|
||||
duplicate connection is not a refactoring, it is corruption.
|
||||
8. **The instantiated module's port list carries compiler directives** —
|
||||
*"`sub`'s port list carries compiler directives, so which ports `.*` binds
|
||||
depends on the configuration; lucisv does not preprocess, so it made no
|
||||
edits."* Writing every arm's ports out produces a connection list no
|
||||
configuration ever had. The same sentence guards the **connection list's**
|
||||
own directives, where lucisv equally cannot tell which connections are
|
||||
explicit in which arm.
|
||||
9. **The module is unknown or declared twice** — `locate_module`'s two
|
||||
existing sentences, unchanged.
|
||||
10. **Nothing is left to bind** — *"`u_x` already connects every port `sub`
|
||||
declares, so its `.*` binds nothing."* Not in the plan's list; derived
|
||||
from `propagate_ports`'s refusal 16 (*"a 'did nothing' success is a worse
|
||||
answer than a sentence"*). Deleting the `.*` instead would be a different
|
||||
refactoring — a removal, with a removal's comma and comment problems —
|
||||
and nobody asked for it.
|
||||
11. **The file is outside the in-scope set**, and **verification fails**
|
||||
(the five checks in `docs/features/refactor-ports/README.md`), the ports
|
||||
engine's own rules unchanged.
|
||||
|
||||
Refusals 3–8 and 10 are pinned by a behavior test each; 1, 2, 4, 5, 6, 9 and
|
||||
the outside-the-scope one too. Nothing is offered as a code action where the
|
||||
refactoring would be refused, so the lightbulb never appears to explain itself.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The `.*` is the only thing the edit touches.** Nothing outside the
|
||||
cursor's own file is read for the edit itself (the module's declaration is
|
||||
read, not edited), so `RefactorEdit` names one file. That is what makes the
|
||||
lazy code action exact rather than optimistic: the offer's two files —
|
||||
buffer plus declaration — are already everything the resolve will read.
|
||||
- **A third offer costs a third attempt.** `port_actions` tries three
|
||||
refactorings where it tried two, and each one builds its own `Scope` (the
|
||||
index over the files it was handed) before it can refuse. So an offered
|
||||
menu is now three index builds over that file set rather than two — but the
|
||||
file set is the thing §37.1 already shrank: on the lazy path it is the
|
||||
buffer plus one declaration, and the gate (`may_have_port_action`, one parse
|
||||
of one file, no workspace, no I/O) still answers "nothing here" for almost
|
||||
every cursor before any of the three runs. Nothing in this round re-reads
|
||||
the fan-out that §37.1 took off the cursor path. A `Scope` shared by all
|
||||
three attempts is the obvious next economy and is deliberately not taken
|
||||
here: it changes the signatures of three shipped refactorings for a saving
|
||||
only the eager path sees.
|
||||
- **lucisv does not elaborate.** "Is a signal called `p` in scope here?" is a
|
||||
lexical-scope question `vlog_semantic` answers. A name that would come from
|
||||
a wildcard package import lucisv cannot resolve reads as *not in scope*, so
|
||||
the port is written `.p()` — visibly, in the warning, never `.p(p)` on a
|
||||
guess. This is the ports engine's standing assumption; the difference is
|
||||
that here a wrong "not in scope" writes an unconnected port rather than a
|
||||
`/* TODO */`, which is why the warning names every one of them.
|
||||
- **lucisv does not preprocess**, so a port list or a connection list split
|
||||
across `` `ifdef`` arms is refused rather than read straight through (the
|
||||
refusals above). This is stricter than `add_port`, which warns and appends
|
||||
outside every arm; appending one element is configuration-independent,
|
||||
while enumerating a whole port set is not.
|
||||
- **A module name is unique in scope**, and the index is the server's
|
||||
authority on where it is declared — the ports engine's assumptions,
|
||||
unchanged.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `vlog_parser`** (no change required): `parse_source_tolerant`
|
||||
and its `ParseDiagnostic` (refusal 7), `LineIndex`, `TextRange`, and
|
||||
`ast::{Connection, Connections, Instance, Instantiation, Item, ListElem}` —
|
||||
`Connection::name == "*"` is how the wildcard is recognized, and
|
||||
`Connection::span` (the element's *code* extent, comments outside it) is what
|
||||
makes the replacement exact. `Instance::conn_directives` is what makes refusal
|
||||
8's second half possible.
|
||||
|
||||
**Consumed from `vlog_semantic`** (no change required, nothing patched):
|
||||
`Semantics::{scopes, symbols, symbol}`, `Scope::{span, parent, lookup_local}`,
|
||||
and `SymbolKind` — the kind is now *read* rather than only matched against a
|
||||
fixed set (below).
|
||||
|
||||
**Changed inside `vlog_refactor`** — four edits to existing files, all of them
|
||||
pure factorings with no behavior change:
|
||||
|
||||
- `ports/find.rs`: `collect_instantiations` is now a wrapper over
|
||||
`walk_instantiations`, which reports of each instantiation whether it is a
|
||||
`bind` directive's own. Same walk, same order, one extra bit; every existing
|
||||
caller ignores the bit.
|
||||
- `ports/find.rs`: `visible_in`'s scope walk moved into `kind_visible_in`,
|
||||
which returns the `SymbolKind` it found; `visible_in` is that function plus
|
||||
the kind set it always had, so `add_port`, `propagate_ports` and
|
||||
`instantiate.rs` answer byte-for-byte as before.
|
||||
- `ports/mod.rs`: `expand_wildcard`, `expansion` (the edit plus its connection
|
||||
count) and the third `port_actions` offer; plus `is_sites_phrase` beside
|
||||
`sites_phrase`.
|
||||
- `instantiate.rs`: `ends_escaped` is `pub(crate)` instead of private. One
|
||||
word; no call site changed.
|
||||
|
||||
**Promised to `lucisv_server`**: everything the other port refactorings
|
||||
promise. `expand_wildcard` does not panic, returns no partial edit, sorts and
|
||||
de-overlaps its edits, and its warnings are informational.
|
||||
`PortAction.title` is user-facing text the server does not rewrite — with one
|
||||
new obligation, which is why `is_sites_phrase` exists: the server *does*
|
||||
rewrite the count in an offered title from its index, and the expansion's
|
||||
count is not an instantiation census. The server now asks before recounting.
|
||||
|
||||
**Changed in `lucisv_server`** (protocol layer only): `EXPAND_WILDCARD`
|
||||
(`lucisv.expandWildcard`) added to `ports::commands()` and to
|
||||
`ports::execute`; `ports::counted` gated on `vlog_refactor::is_sites_phrase`.
|
||||
The dispatch arm, the capability advertisement and the code-action path needed
|
||||
no change — commands are advertised from `commands()` and every
|
||||
`workspace/executeCommand` already routes through `ports::execute`. **The VS
|
||||
Code extension needed nothing**: `editors/vscode/package.json` contributes only
|
||||
its own webview commands, and server commands are discovered over LSP.
|
||||
|
||||
**Requested of nobody.** No change was needed in `vlog_parser`,
|
||||
`vlog_semantic`, `vlog_formatter` or `lucisv_core`.
|
||||
|
||||
**One new dev-dependency**: `vlog_formatter` on `vlog_refactor`, **tests
|
||||
only**, the arrangement `vlog_linter` already uses and with the same
|
||||
justification written into `Cargo.toml`: the acceptance tests assert that what
|
||||
the expansion writes is something the formatter accepts and leaves alone the
|
||||
second time, and that cross-tool guarantee cannot be asserted from either
|
||||
crate alone. The library still depends on `vlog_parser` + `vlog_semantic`
|
||||
alone (`cargo tree -p vlog_refactor -e normal`), and no cycle is possible:
|
||||
`vlog_formatter` depends on `vlog_parser` and nothing else.
|
||||
|
||||
## The LSP surface
|
||||
|
||||
| Surface | What it says |
|
||||
|---|---|
|
||||
| Code action, kind `refactor.rewrite.lucisv.ports` | *"lucisv: expand .* (3 connections)"* — offered at a `.*` under the cursor, lazily (`offers` → `resolve`, §37.1) or eagerly (`code_actions`), whichever the client supports. |
|
||||
| `lucisv.expandWildcard [uri, Position]` | The same edit for a client with no lightbulb — a Vim user's keybinding. |
|
||||
|
||||
The count is the connections the wildcard becomes, and it is exact in the
|
||||
offer already: the offer's file set (buffer + declaring file) is everything
|
||||
the expansion reads. It is written `1 connection` for one, which is why the
|
||||
plan's *"(N connections)"* is a shape rather than a literal.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] 50.1 `expand_wildcard` engine (`ports/expand.rs`, 308 lines, 233 of
|
||||
them code) + every refusal above
|
||||
- [x] 50.1 the LRM kind rule, sharing one scope walk with `visible_in`
|
||||
- [x] 50.1 layout (multi-line vs inline) and the three comment positions
|
||||
- [x] 50.2 code action through the lazy offer path, with `is_sites_phrase`
|
||||
keeping the index from recounting its title — pinned at the level that
|
||||
matters rather than as a predicate unit test: the server test
|
||||
`the_wildcard_action_is_offered_lazily_and_resolves_to_the_eager_edit`
|
||||
asserts the offered title is `lucisv: expand .* (1 connection)` in a
|
||||
workspace whose instantiation census would have said something else,
|
||||
and the e2e session asserts the same string over the wire
|
||||
- [x] 50.2 `lucisv.expandWildcard` in `commands()` / `execute`
|
||||
- [x] 50.1 escaped identifiers terminated on both sides of the parens
|
||||
- [x] Tests: 32 behavior tests in `vlog_refactor/tests/expand.rs`, 1 corpus
|
||||
acceptance test in `tests/corpus.rs`, 3 in `lucisv_server`'s `ports.rs`,
|
||||
1 e2e session over the wire
|
||||
- [x] Gates: `cargo fmt` per crate, clippy `--all-targets` clean, the
|
||||
workspace suite, the corpus gate, byte-identity vs 0.45.0, the VS Code
|
||||
smoke test
|
||||
- [x] OpenTitan read-only census and ten scratch expansions
|
||||
- [ ] Deferred, deliberately: a `.*` inside a `bind` directive (refusal 3) —
|
||||
it needs the target's scope, which is elaboration, not lexical lookup.
|
||||
It is the *majority* of real wildcard sites in OpenTitan, so it is worth
|
||||
a backlog line of its own.
|
||||
- [ ] Deferred: the inverse refactoring (named connections → `.*`), which is
|
||||
§8's list, not this round's.
|
||||
|
||||
## Docs to apply at merge (lead)
|
||||
|
||||
`README.md`, `docs/topo.md`, `docs/repository-analysis.md` and `docs/site/`
|
||||
are the lead's; the text for them is here rather than edited in place.
|
||||
|
||||
**`README.md` — the refactoring list** gains a row beside
|
||||
"connect missing ports":
|
||||
|
||||
> | **expand `.*`** | Writes a wildcard connection out as the named
|
||||
> connections it stands for, in the module's declaration order — a port with
|
||||
> no same-named signal in scope becomes `.p()` and is named in a warning.
|
||||
> Code action at the `.*`, or `lucisv.expandWildcard`. |
|
||||
|
||||
**`docs/site/` (editors / language-tools page)** — the same sentence in the
|
||||
code-action list: *"expand `.*` — the wildcard connection written out as the
|
||||
`.p(p)` connections it stands for, so the port list can then diverge from the
|
||||
wrapper around it."*
|
||||
|
||||
**TODO.md §8** (the refactoring backlog): the `.*`-expansion line gains
|
||||
*"— shipped in 0.46.0, `docs/features/expand-wildcard/README.md`"*, and the
|
||||
list gains a new backlog entry: *"expand a `.*` written in a `bind` directive
|
||||
(needs the target's scope — elaboration, not lexical lookup)."*
|
||||
|
||||
**`docs/topo.md`**: one new edge to record — `vlog_refactor ──▶
|
||||
vlog_formatter` **(dev-dependency, tests only)**, the same shape §2's
|
||||
`vlog_linter ──▶ vlog_formatter` dev edge already has. No production edge
|
||||
changed.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-09-05 — dev agent.** Built `ports/expand.rs`, the third `port_actions`
|
||||
offer, and the fourth command. The decisions worth recording:
|
||||
|
||||
- **A replacement, not an append plus a deletion.** `propagate_ports` was the
|
||||
obvious template, and it appends — but the `.*` has to *go*, and the
|
||||
cleanest expression of that is one `TextEdit` whose range is the element's
|
||||
own span. `check::pieces_match` already handles a replacement exactly (it
|
||||
skips old pieces overlapping a non-empty edit range and splices the edit's
|
||||
own pieces in at its start); `Shift::map` already handles the length change
|
||||
(`a_longer_replacement_shifts_forward` was written for it in M2). So the
|
||||
verifier needed nothing new, which is the outcome hard invariant 4 wants:
|
||||
no widening of anybody's forgiveness, no new attack surface to test.
|
||||
- **The comment rule fell out.** Because the edit's range is the element's
|
||||
*code* span, a comment before or after the `.*` is not inside it and is
|
||||
simply not touched; a comment *inside* it is, and the splice verifier's
|
||||
comment rule refuses the whole thing. Two of the three comment cases are
|
||||
therefore properties of the span choice rather than code, and the third is
|
||||
a refusal rather than a guess. The one piece of code is the
|
||||
comma-before-the-line-comment split, lifted verbatim from
|
||||
`append_to_list`'s reasoning.
|
||||
- **Parameters are the crux, and they get their own kind reader.** The LRM
|
||||
binds `.*` to a net or a variable. `find::visible_in` — the "may lucisv
|
||||
write `.p(p)` here" test the other two refactorings use — says yes to
|
||||
parameters, localparams, genvars and task arguments as well, and that is
|
||||
right *for them*: the user asked for a connection and a parameter is a legal
|
||||
expression. It is wrong here, where the question is what the wildcard
|
||||
already bound. Rather than adding a flag to `visible_in`, the scope walk was
|
||||
factored into `kind_visible_in` (which returns the kind) and each caller
|
||||
states its own set. Both readers therefore agree about which declaration a
|
||||
name means — the thing that must never diverge — and disagree only where
|
||||
they should.
|
||||
- **Two refusals stricter than `add_port`'s.** A file with a parse diagnostic,
|
||||
and a list carrying compiler directives, are *warnings* or read-throughs
|
||||
elsewhere in the ports engine. Here they are refusals, because this
|
||||
refactoring enumerates a whole port set rather than appending one element:
|
||||
a misread list connects a port twice, and an `` `ifdef``-split port list
|
||||
expands into a connection list no configuration ever had. Both are cheap to
|
||||
detect and impossible for the verifier to catch (the result parses, resolves
|
||||
and matches its shape — it is simply not what the source meant).
|
||||
- **`is_sites_phrase` was the one real surprise.** `ports::counted` in the
|
||||
server rewrites *any* offered title ending in `(…)` with the index's
|
||||
instantiation count, which would have turned "expand .* (3 connections)"
|
||||
into "expand .* (updates 5 instantiations)" — a wrong sentence produced by
|
||||
a function that had never been wrong before, because until now every title
|
||||
with a count carried the same count. The predicate lives next to
|
||||
`sites_phrase` in the engine so the phrase has one spelling and one reader.
|
||||
- **The bind refusal is not a corner case.** 24 of the 31 `.*` sites under
|
||||
OpenTitan's `hw/ip` are inside a `bind` directive. Refusing them is correct
|
||||
(§23.3.2.4 resolves those in the target's scope), and it is the reason the
|
||||
acceptance sample had to be drawn from a wider tree than `hw/ip` to reach
|
||||
ten — recorded in Acceptance and as a backlog line above.
|
||||
|
||||
Checks at the end are in Acceptance and in the gate list. No
|
||||
`unwrap`/`expect`/`panic!` and no `unsafe` in any library path (test modules
|
||||
only); `expand.rs` is 308 lines with no function over 45, and every file it
|
||||
touches stayed inside the size rule — `ports/mod.rs` 433, `ports/find.rs` 283,
|
||||
`lucisv_server/src/ports.rs` 1 430 of which 981 are its `#[cfg(test)]` module.
|
||||
|
||||
## Gates
|
||||
|
||||
All guarded (`tools/guard.sh`, 8 GB / 30 min defaults); no guard kill.
|
||||
|
||||
- **fmt**: `cargo fmt -p vlog_refactor`, `cargo fmt -p lucisv_server`;
|
||||
`cargo fmt --all -- --check` clean.
|
||||
- **clippy**: `cargo clippy --all-targets`, **0 warnings**, and no new
|
||||
`#[allow]` anywhere in the diff.
|
||||
- **suite**: `cargo test --workspace` — **3 876 passed, 0 failed, 44 ignored**
|
||||
across 50 test binaries (baseline 3 839, +37: 32 behavior, 1 corpus, 3
|
||||
server unit, 1 e2e).
|
||||
- **corpus gate**: `tools/corpus_check.sh` — **814/820 (99.3%)**, the same six
|
||||
known parse errors (`ibex` compare_helper / riscv_core_setting.tpl /
|
||||
latch_map.v / riscv_instr_cover_group, `picorv32` romload testbench /
|
||||
smtbmc mulcmp), **0 verification errors, 0 crashes**.
|
||||
- **formatter byte-identity**: `lucisv format --stdout` over all corpus files,
|
||||
this build vs `~/.cache/lucisv-baselines/lucisv-0.45.0` — **854 checked, 0
|
||||
differing**, 6 refused by both. `git diff` over `vlog_formatter`,
|
||||
`vlog_parser` and `verify.rs` is empty; this round touched neither.
|
||||
- **vsix smoke**: `node editors/vscode/smoke.js target/release/lucisv-server`
|
||||
— OK, 20 messages.
|
||||
- **opentitan after the round**: `git -C ~/repo/opentitan status --porcelain`
|
||||
shows only the three pre-existing modifications. Every run over it was
|
||||
read-only, and every edited copy went to the session scratchpad.
|
||||
|
||||
## Acceptance
|
||||
|
||||
### The corpus
|
||||
|
||||
`cargo test -p vlog_refactor --test corpus` gained
|
||||
`a_wildcard_expanded_in_the_corpus_is_something_the_formatter_accepts`: the
|
||||
first three corpus files with a `.*` are expanded into an in-memory copy and
|
||||
the copy must format, and formatting it twice must not move it. It expands
|
||||
`common_cells`' `cdc_2phase_clearable_tb.sv`, `cdc_2phase_synth.sv` and
|
||||
`cdc_2phase_tb.sv` (~2.4 s each in debug, the index build over 860 files) and
|
||||
refuses the three `formal/*_properties.sv` sites — every one of them a `bind`.
|
||||
|
||||
### OpenTitan (read-only)
|
||||
|
||||
Counted with the plan's grep and with the engine's own scan, which also sees a
|
||||
`.*` whose `,`/`)` is on the next line:
|
||||
|
||||
| Tree | Files | `.*` sites | Expanded | Refused |
|
||||
|---|---|---|---|---|
|
||||
| `hw/ip` | 1 807 | **31** (29 by line-based grep) | 7 | 24, every one a `bind` |
|
||||
| `hw` (all of OpenTitan's Verilog) | 3 979 | **66** | **9** | 57: **50** `bind`, **6** `pinmux` declared in three tops, **1** `ibex_top`'s `` `ifdef``-split port list |
|
||||
|
||||
**Deviation from the plan, stated plainly: ten expandable sites do not
|
||||
exist.** The plan asked for ten scratch expansions; OpenTitan holds nine.
|
||||
Every `.sv`/`.svh`/`.v` file in the repository is under `hw/` (checked), and
|
||||
of its 66 wildcard sites, 57 are refused — 50 of them by the `bind` rule,
|
||||
which is correct and is the backlog line above. So the sample is **all nine**
|
||||
of them rather than a chosen ten, plus the three corpus expansions in the test
|
||||
suite: twelve real-world expansions, all verified the same way. Each of the
|
||||
seven refusal categories that fired did so for a reason on the list, including
|
||||
two the synthetic tests could only fake: `pinmux` really is declared three
|
||||
times in OpenTitan (one per top), and `ibex_top`'s port list really is split
|
||||
across `` `ifdef`` arms.
|
||||
|
||||
Every expansion was written to a **copy** under the session scratchpad;
|
||||
nothing was written into `/Users/guoliangchen/repo/opentitan`, and
|
||||
`git -C … status --porcelain` shows the same three pre-existing modifications
|
||||
before and after (`hw/ip/aes/dv/tb/tb.sv`,
|
||||
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`).
|
||||
|
||||
Each of the nine: the copy parses with **zero** diagnostics, formats, formats
|
||||
again to the same bytes, and holds the **same instance count** as the
|
||||
original. Two of them carry a warning, and both are real findings rather than
|
||||
lucisv guessing:
|
||||
|
||||
- `kmac/fpv/tb/sha3_fpv.sv` — `u_sha3`'s `.*` covers nine ports of `sha3`
|
||||
(`rand_update_o`, `squeezing_o`, `block_processed_o`, `run_req_o`,
|
||||
`run_ack_i`, `lc_escalate_en_i`, `sparse_fsm_error_o`, `count_error_o`,
|
||||
`keccak_storage_rst_error_o`) that the FPV wrapper's own header does not
|
||||
declare. The wrapper has drifted behind the module it wraps; the wildcard
|
||||
was hiding it, and the expansion says so.
|
||||
- `kmac/fpv/tb/sha3pad_fpv.sv` — the same story for `u_keccak`, five ports.
|
||||
|
||||
The five `aes/dv/err_injection_if/fi_*_wrapper.sv` expansions are the
|
||||
textbook case: `fi_core_if fi_if (.*)` becomes
|
||||
`fi_core_if fi_if (.clk_i(clk_i), .rst_ni(rst_ni), .aes_ctrl_cs(aes_ctrl_cs))`.
|
||||
The last two are `vendor/lowrisc_ibex`'s icache agent interfaces.
|
||||
|
||||
Reproduced by a throwaway probe binary in the session scratchpad
|
||||
(`otprobe`), which depends on `vlog_refactor` + `vlog_formatter` +
|
||||
`vlog_parser` by path, walks a tree read-only, and writes every edited copy
|
||||
into the scratchpad. Nothing of it is checked in.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-09-05 — QA agent.** Attacked the engine directly
|
||||
(`vlog_refactor::expand_wildcard`, temporary `#[test]`s added and removed —
|
||||
`tests/zz_qa_expand_attack.rs`, `tests/zz_qa_corpus_sweep.rs`, never
|
||||
committed) plus the shipped suites, the two full-workspace gates, a
|
||||
full-`hw/` opentitan census (not just the plan's ten), and a diff of every
|
||||
opentitan scratch expansion against its original. Verdict: **PASS**.
|
||||
|
||||
### LRM-rule matrix (18 scratch tests, all against a fresh build)
|
||||
|
||||
| # | Case | Result |
|
||||
|---|---|---|
|
||||
| enclosing module's own port | binds (`.clk(clk)`) | as specified |
|
||||
| typedef of the same name | not bound, `.done()` + warning | as specified |
|
||||
| instance name of the same name | not bound, `.done()` + warning | as specified |
|
||||
| instantiation lexically inside a function body | no panic (refusal or edit, either is fine — the plan only asks for no crash) | no crash |
|
||||
| sibling generate block's declaration | not visible, `.done()` + warning | as specified |
|
||||
| declared *after* the instantiation, module scope | still visible and bound | as specified — declaration order does not matter |
|
||||
| `import pkg::*` bringing a same-named package variable into scope | **not bound** — `.name()` + warning, exactly as an unrelated name would be | matches the README's stated assumption, see below |
|
||||
| port name shared by both the instantiated and enclosing module | binds (the common case) | as specified |
|
||||
| width/type mismatch (`input logic [7:0] clk` vs a 1-bit `clk` in scope) | still binds by name, no warning | as specified — lucisv cannot check types, README says so |
|
||||
| interface port (`bus_if.master b`, interface instance `bus_if b()` of the same name) | **not bound** — `.b()` + warning | see finding QA-1 below |
|
||||
| escaped port name `\my-port` | bound and terminated on both sides of the parens (`.\my-port (\my-port )`), and unbound the same way | dev's own tests, re-verified |
|
||||
| port with an unpacked dimension (`input logic [7:0] data [4]`) | binds (`.data(data)`) | as specified |
|
||||
|
||||
None of the eighteen attack tests found a mis-binding (an output silently
|
||||
tied to a parameter, a genvar, a typedef, an instance, or anything else the
|
||||
LRM does not call a signal) or a crash. Two are worth recording explicitly:
|
||||
|
||||
- **The package-import choice, pinned.** A name reaching the instantiating
|
||||
scope only through `import pkg::*;` is read as **not in scope**: `.*`
|
||||
writes `.name()` and warns, exactly as if the name did not exist anywhere.
|
||||
Traced to source: `kind_visible_in`
|
||||
(`crates/vlog_refactor/src/ports/find.rs:214-253`) walks
|
||||
`Scope::lookup_local` up the `parent` chain only, and never reads
|
||||
`Scope.imports` — the second, separate lookup
|
||||
`vlog_semantic::resolve::{lexical, unit}` perform to make a wildcard
|
||||
import's names resolvable for *reference* resolution
|
||||
(`crates/vlog_semantic/src/resolve.rs:607-684`). So `vlog_semantic`'s own
|
||||
full resolver *can* see a wildcard-imported name; `kind_visible_in`
|
||||
deliberately (per the README's Assumptions section) does not re-implement
|
||||
that half of it. This matches the feature's stated assumption
|
||||
word-for-word ("a name that would come from a wildcard package import
|
||||
lucisv cannot resolve reads as *not in scope*") — **not a defect**, a
|
||||
documented, safe-by-construction limitation: it under-expands (leaves a
|
||||
port unconnected and says so) rather than mis-expands. Filing it here
|
||||
because the plan asked to "pin it and report the choice."
|
||||
- **QA-1 (LOW, pre-existing, not introduced by this round): interface
|
||||
instances are never a `.*` target.** `bus_if b(); sub u_sub(.*)` where
|
||||
`sub` declares `bus_if.master b` leaves `.b()` unconnected with a warning,
|
||||
even though the interface instance `b` is exactly the identifier IEEE 1800
|
||||
§23.3.2.4 means to bind an interface port to. Root cause: an interface
|
||||
instantiation gets `SymbolKind::Instance`
|
||||
(`crates/vlog_semantic/src/bind/item.rs:306`, the same kind a module
|
||||
instantiation gets — interfaces are modeled as `Module`s with a different
|
||||
keyword), and `signal_visible`'s allowed set
|
||||
(`crates/vlog_refactor/src/ports/expand.rs:266-270`) is `Net | Var | Port`
|
||||
only. This is not new: `find::visible_in`, which `add_port` and
|
||||
`propagate_ports` already share, excludes `Instance` from its own allowed
|
||||
set too (`crates/vlog_refactor/src/ports/find.rs:203-217`), so no port
|
||||
refactoring in the engine today treats an interface instance as a
|
||||
connectable signal by name. Nothing in this round narrowed that — it is
|
||||
inherited, and it fails safe (unconnected + warned, never mis-bound) — but
|
||||
it means every interface-port wildcard site in a design is likely to
|
||||
surface a spurious warning rather than a clean bind. Worth a backlog line
|
||||
for the ports engine generally, not a blocker for §50.
|
||||
|
||||
### Text/layout and refusals
|
||||
|
||||
Re-verified against source and by test: trailing-comma legality (no result
|
||||
ever ends `,)` or has a dangling comma before a line comment), idempotency
|
||||
(expanding the result a second time refuses with the exact "writes no `.*`
|
||||
to expand" sentence; formatting twice converges; re-expanding the *formatted*
|
||||
result also correctly refuses), comment-count preservation, `#(...)`
|
||||
parameterized instantiations, and a cursor placed inside one instance of a
|
||||
two-instance statement (`sub u_a (.*), u_b (.*);`) expanding only that
|
||||
instance rather than tripping the "declares 2 instances" refusal — confirmed
|
||||
this refusal fires only when the cursor is on the shared module name/keyword,
|
||||
matching `propagate_ports`'s documented rule. All eleven refusal sentences
|
||||
in the README's list were exercised (by the dev's own 32-test suite, which
|
||||
this session re-ran clean) and match character-for-character.
|
||||
|
||||
**Server, cursor away from the `.*`:** a cursor placed on `.clk(clk)` inside
|
||||
the *same* instantiation as a `.*` still offers `lucisv: expand .* (2
|
||||
connections)` — the cursor rule is instance-level (any offset inside the
|
||||
instance's span), not token-level, matching `propagate_ports`'s and
|
||||
`remove_port`'s own precedent. This is not a bug: the plan's "only the port
|
||||
actions that apply" is satisfied — every offered action is one that would
|
||||
actually succeed at that instance, and none is limited to the exact `.*`
|
||||
token by design elsewhere in the engine either.
|
||||
|
||||
### Corpus (full sweep, not a sample)
|
||||
|
||||
Independently re-implemented the dev's own `.*` census (a `.*` followed by
|
||||
`,`/`)`, matching the engine's own scan rather than a naïve line grep) and
|
||||
ran it over every corpus file, not just the first three the dev's acceptance
|
||||
test samples: **21 sites, 11 expanded, 10 refused** — 6 `bind` directives, 2
|
||||
"declared in more than one indexed file" (`formal_tb`, genuinely declared
|
||||
twice under `corpus/ibex/formal/`), 1 compiler-directives-in-the-port-list
|
||||
(`ibex_top`), 1 "no module instantiation at this position" (a `.*` mentioned
|
||||
inside a *comment* in `formal_tb_frag.svh`, correctly refused rather than
|
||||
corrupting anything). Every one of the 11 expansions: same instance count
|
||||
before/after, zero parse diagnostics afterward, formats, and converges on a
|
||||
second format. No panics anywhere in the sweep (38.7 s under
|
||||
`tools/guard.sh`, no kill).
|
||||
|
||||
### OpenTitan (read-only, full `hw/`, not a ten-site sample)
|
||||
|
||||
Reproduced independently with a throwaway probe (`otqa`, path-dependent on
|
||||
`vlog_refactor`/`vlog_formatter`/`vlog_parser`, built and run under
|
||||
`tools/guard.sh -m 8 -t 600`, nothing checked in): **66 sites, 9 expanded, 57
|
||||
refused (50 bind, 6 declared-twice/pinmux, 1 compiler-directives/`ibex_top`)
|
||||
— exactly the dev's table.** `git -C ~/repo/opentitan status --porcelain`
|
||||
showed only the three pre-existing modifications both before and after.
|
||||
|
||||
Diffed each of the nine scratch expansions against its opentitan original:
|
||||
**every diff touches only the `.*` element** — one line replaced for the
|
||||
seven simple sites (the five `fi_*_wrapper.sv` interfaces plus the two
|
||||
`ibex_icache_*_if.sv` checkers), a multi-line replacement confined to the
|
||||
`u_sha3`/`u_keccak` instantiation block for the two FPV files. Nothing else
|
||||
in any of the nine files changed.
|
||||
|
||||
Verified the two FPV warnings are real, not lucisv guessing: grepped
|
||||
`hw/ip/kmac/rtl/sha3.sv`'s port list and confirmed all nine names in
|
||||
`sha3_fpv.sv`'s warning (`rand_update_o`, `squeezing_o`, `block_processed_o`,
|
||||
`run_req_o`, `run_ack_i`, `lc_escalate_en_i`, `sparse_fsm_error_o`,
|
||||
`count_error_o`, `keccak_storage_rst_error_o`) are genuine output/input ports
|
||||
of `sha3` absent from `sha3_fpv`'s own header; same check against
|
||||
`hw/ip/kmac/rtl/keccak_round.sv` for `sha3pad_fpv.sv`'s five
|
||||
(`rand_update_o`, `lc_escalate_en_i`, `sparse_fsm_error_o`,
|
||||
`round_count_error_o`, `rst_storage_error_o`). Both wrappers have genuinely
|
||||
drifted behind the modules they wrap.
|
||||
|
||||
### Gates (guarded, re-run independently)
|
||||
|
||||
- `cargo clippy -p vlog_refactor -p lucisv_server --all-targets` — **0
|
||||
warnings**; `cargo clippy --all-targets` over the whole workspace also
|
||||
clean.
|
||||
- `cargo fmt -p vlog_refactor -p lucisv_server -- --check` and
|
||||
`cargo fmt --all -- --check` — clean.
|
||||
- `tools/guard.sh -t 1800 -- cargo test --workspace` — **3 876 passed, 0
|
||||
failed, 44 ignored**, 50 test binaries — matches the dev's number exactly.
|
||||
No guard kill.
|
||||
- `tools/guard.sh -t 900 -- tools/corpus_check.sh` — **814/820 (99.3%)
|
||||
parsed & formattable, 0 verification errors, 0 crashes**, same six known
|
||||
parse errors — matches exactly.
|
||||
- Byte-identity: `lucisv format --stdout` over every corpus file, this build
|
||||
vs `~/.cache/lucisv-baselines/lucisv-0.45.0` — **860 total, 854 checked
|
||||
identical, 0 differing, 6 refused by both** — matches exactly.
|
||||
- `node editors/vscode/smoke.js target/release/lucisv-server` — OK, 20
|
||||
messages.
|
||||
|
||||
### Findings
|
||||
|
||||
- **QA-1 (LOW, informational, not a blocker):** interface instances are
|
||||
never bound by `.*` (nor writable by `add_port`/`propagate_ports`) because
|
||||
`SymbolKind::Instance` is outside every port refactoring's allowed-kind
|
||||
set. Pre-existing across the ports engine, not introduced by §50; fails
|
||||
safe (unconnected + warned). Suggest a backlog line for the ports engine
|
||||
generally: "an interface instance of the same name as an interface port
|
||||
should bind, per IEEE 1800 §23.3.2.4."
|
||||
- **Package-import scope choice — verified as documented, not a defect.**
|
||||
See the matrix above; matches the README's Assumptions section exactly.
|
||||
- No corruption, no dropped comments, no panics, no idempotency break, no
|
||||
byte-identity regression found in any of the above. All temporary test
|
||||
files and scratch copies were removed after verification; the repository
|
||||
tree touched by this QA pass is unchanged apart from this log entry and
|
||||
the §50 QA checkbox in `TODO.md`.
|
||||
|
||||
**Verdict: PASS.**
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-05 — lead.** Accepted; ships in 0.46.0 with §51. The engine is
|
||||
one replacement edit through the ports engine's existing splice and
|
||||
verifier, which is exactly the shape a lexical refactoring should have,
|
||||
and the LRM rule is read strictly — a parameter or genvar of the same name
|
||||
does not bind, which is what the compiler would say. The refusal list is
|
||||
complete and each refusal is a sentence. The dev found and fixed a real
|
||||
title-rewrite bug in the lazy offer path on the way (`counted` rewrote
|
||||
any parenthesised title). Ten expandable opentitan sites do not exist —
|
||||
57 of the 66 `.*` sites are inside `bind` directives, which need the
|
||||
target's scope and are filed as a backlog entry — so the nine that do
|
||||
exist were all expanded and verified, and two of them surfaced real
|
||||
drift between an FPV wrapper and the module it wraps. The vlog_formatter
|
||||
dev-dependency mirrors the linter's and is recorded in topo.
|
||||
@@ -0,0 +1,532 @@
|
||||
# hierarchical-tail
|
||||
|
||||
TODO.md §49 — the cross-file instance-member tail in rename. `docs/topo.md`
|
||||
§2.9 row 23. Ships in 0.45.0.
|
||||
|
||||
## Goal
|
||||
|
||||
With `module sub` in `sub.sv` and `assign w = u_x.sig;` in `top.sv`, renaming
|
||||
`sub`'s internal `wire sig` used to edit `sub.sv` alone and warn about the
|
||||
tail in `top.sv` — a rename that hands back a design which no longer
|
||||
elaborates, with an apology. The same shape in one file resolved and was
|
||||
edited. The cause was the export rule in `workspace/record.rs::is_exported`:
|
||||
a module exported its ports and its parameters and nothing else, so the
|
||||
cross-file member walk could not see `sig` through `u_x`.
|
||||
|
||||
The lead's ruling, implemented here: a module gains a **second, distinct
|
||||
member surface**. Its *connection* surface stays what it was — ports and
|
||||
parameters, what a connection list may name (IEEE 1800 §23.3). Its
|
||||
*hierarchical* surface is that set **plus** its nets, its variables and its
|
||||
instances, which is what a hierarchical path may name from anywhere in the
|
||||
design (§23.6). The index records both, tagged; only the tail walk behind an
|
||||
**instance** head reads the hierarchical one. Rename's reference set then
|
||||
includes the cross-file tail, the edit lands in both files, and the §2.9-20
|
||||
"the rename says so" warning is no longer raised for a tail that resolved (it
|
||||
stays, unchanged, for one that did not).
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A hierarchical path is what an instance head opens, and nothing else
|
||||
is.** `resolve.rs::head_surface` returns `Surface::Hierarchical` for exactly
|
||||
`SymbolKind::Instance` and `Surface::Connection` for every other link of a
|
||||
spine. A class handle, a struct field, a virtual interface and a package
|
||||
path are all the connection surface, and for those units the distinction is
|
||||
noise anyway — a package, a class, a struct and a covergroup have one
|
||||
surface each.
|
||||
- **The hierarchical surface contains the connection one.** A record is
|
||||
tagged with the *narrowest* surface it joins, and a hierarchical read
|
||||
consults the connection table first. So a tail naming a port has exactly one
|
||||
answer, from one record, and it is the same declaration a connection-list
|
||||
lookup finds. This is asserted, not assumed:
|
||||
`a_tail_naming_a_port_is_one_answer_and_one_edit`.
|
||||
- **A unit's members are the symbols of its own scope.** `collect_members`
|
||||
walks `unit.child_scope` and no deeper (except into a nested class, struct
|
||||
or covergroup, whose members are keyed under their own name). A net declared
|
||||
inside a **generate block** therefore joins neither surface: its scope is
|
||||
the block's. `u_x.gen_b.sig` does not resolve, and the rename leaves the
|
||||
tail alone and says so — the honest refusal, pinned by
|
||||
`a_generate_block_scoped_net_named_through_an_instance_is_refused_honestly`.
|
||||
Widening that means teaching the index about generate scopes and their loop
|
||||
indices (`u_x.gen[0].sig`), which §49 deliberately did not do.
|
||||
- **An interface is unchanged.** Its signals *are* its connection surface
|
||||
(the 2026-09-01 ruling: `virtual bus_if vif; vif.data` is how every DV
|
||||
testbench reaches `data`, and `vif` is a variable, not an instance). It
|
||||
gains only its **instances** on the hierarchical surface, for the same hop
|
||||
reason a module does.
|
||||
- **Two instances of a name in one module cannot happen**, so the
|
||||
hierarchical table's `Vec<Def>` per name holds duplicates only across files
|
||||
— the same ambiguity rule, and the same refusal, the connection table has
|
||||
always had.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### What this consumes
|
||||
|
||||
- `vlog_semantic::Semantics` — `member_site` / `unit_site` return the site a
|
||||
tail is walked from, and a `Symbol`'s `kind` is what says whether a link is
|
||||
an instance.
|
||||
- `vlog_parser` — unchanged; nothing in the parser moved.
|
||||
|
||||
### What this promises
|
||||
|
||||
**`vlog_semantic` (the surface encoding).**
|
||||
|
||||
- `pub enum Surface { Connection, Hierarchical }` in `model.rs`, re-exported
|
||||
from the crate root.
|
||||
- `Resolution::ExternalCandidate { paths, surface }` — a new field. Every
|
||||
construction site outside a hierarchical tail passes `Surface::Connection`;
|
||||
`resolve.rs::head_surface` is the one place that can return the other.
|
||||
- `MemberSite::Unit { path, surface }` — was `MemberSite::Unit(String)`. The
|
||||
surface is `Hierarchical` exactly when the head of the spine was an
|
||||
instance, and it stays that for every further hop: `u_a.u_b.` is one
|
||||
hierarchical path.
|
||||
- `WorkspaceIndex` gains `member_in(unit, member, surface)`,
|
||||
`members_of_chain_in(path, surface)`, `member_unit_in(unit, member,
|
||||
surface)` and `hierarchical_declarations(name)`. **Every existing method
|
||||
reads the connection surface and answers exactly what it answered before**:
|
||||
`member`, `members_of`, `members_of_chain`, `member_unit`,
|
||||
`workspace_symbols`.
|
||||
- `IndexCounts` gains `hierarchical_members`, disjoint from `members`, so the
|
||||
whole member census is the two added.
|
||||
- `FACTS_FORMAT` 18 → 19. Two new fields — a one-letter surface on every
|
||||
declaration and on every `External` reference fact — so an older record
|
||||
would be read field-shifted, and `index_cache` drops a store by format as it
|
||||
already does.
|
||||
|
||||
**`lucisv_server`.** `Workspace::rename_sources`' fan-out gains one rung:
|
||||
every file declaring the name on a module's hierarchical surface. `state.rs`
|
||||
is the only server file whose *behaviour* changed;
|
||||
`completion/member.rs` follows the site's own surface (below).
|
||||
|
||||
**`vlog_refactor`.** No behaviour of its own changed. `rename/warnings.rs`
|
||||
took a mechanical `..` in one pattern for the new `ExternalCandidate` field;
|
||||
the §2.9-20 warning retires itself, because it is raised only when the overlay
|
||||
answers `StillUnresolved` and a resolved tail no longer does.
|
||||
|
||||
### The completion decision, said plainly
|
||||
|
||||
Behind `u_x.` **in an expression**, completion lists the module's
|
||||
**hierarchical** surface — its nets, its variables and its instances as well
|
||||
as its ports and its parameters. That is what the user is reaching for, it is
|
||||
exactly what the tail resolution will find, and it is what the *in-file* half
|
||||
of the same function has always offered for an instance this file declares
|
||||
(`MemberSite::Scope` pushes every symbol of the module's scope). Making the
|
||||
two halves disagree would have been the odd choice.
|
||||
|
||||
Behind the `.` of a **connection list** it is the connection surface and
|
||||
nothing more. `.internal_net(w)` is not a legal connection, so an item there
|
||||
would be one the resolution could not answer — a wrong answer rather than a
|
||||
generous one. That path is `connection_members`, which reads
|
||||
`WorkspaceIndex::members_of` (the connection table) and filters to `Port` or
|
||||
`Param`; it never reaches `members_at`. Both halves are pinned in one test:
|
||||
`an_instance_head_lists_the_hierarchical_surface_and_a_connection_list_does_not`.
|
||||
|
||||
The `propagate-ports` engine reads `member`/`members_of` and is untouched.
|
||||
|
||||
### What did not widen
|
||||
|
||||
- **Reference postings.** `facts_from_analysis` records a `Local` posting only
|
||||
for a use whose declaration is on the **connection** surface. Posting a
|
||||
module's every internal-net use would multiply the reference table by the
|
||||
size of an RTL body for an answer nothing reads: the only consumer is a
|
||||
rename, which re-analyses the declaring file anyway. The *cross-file* half —
|
||||
the tail in the other file — is an `External` fact, and that is what makes
|
||||
the rename work.
|
||||
- **`workspace/symbol`.** An internal net is still not a workspace symbol: the
|
||||
request answers what a user can name from outside, and a design with 20 000
|
||||
modules has hundreds of thousands of internal signals.
|
||||
`hierarchical_declarations` is the separate, map-only question the rename
|
||||
fan-out asks instead.
|
||||
- **`verify.rs`.** Untouched. No normalization was added or broadened, so no
|
||||
masked-corruption attack tests are owed.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] 49.1 surface bit in facts, `FACTS_FORMAT` 18 → 19, index member walk
|
||||
- [x] 49.2 `MemberOf` behind an instance reads the hierarchical surface;
|
||||
rename edits the tail; the warning retired for resolved tails
|
||||
- [x] `workspace/hierarchy.rs` — `surface_of` (the old `is_exported`,
|
||||
re-ruled) plus the two surface-taking reads; `record.rs`'s export doc
|
||||
comment rewritten to say the ruling moved
|
||||
- [x] Completion decision made, said here, and pinned both ways
|
||||
- [x] Tests: the cross-file twin of the rename pin; nested `u_a.u_b.sig`; a
|
||||
tail naming a port (one answer, one edit); a parameter; the
|
||||
generate-block refusal; the interface tail unchanged; the ambiguous
|
||||
`sub` still refused; the connection list unchanged; the census delta
|
||||
- [x] Gates (guarded); census delta explained; opentitan before/after
|
||||
- [ ] QA
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-05 — dev (agent 2, resuming)
|
||||
|
||||
**The state I found.** The first dev agent on this lane was cut off by a
|
||||
network failure mid-round, leaving uncommitted work in the tree: 20 modified
|
||||
files plus a new `crates/vlog_semantic/src/workspace/hierarchy.rs`, and no
|
||||
feature README at all. `cargo check --workspace --all-targets` passed; the
|
||||
agent's last words were "now the test compile errors across the workspace",
|
||||
and that is exactly where it stood — the *library* half of §49 was complete
|
||||
and coherent, the test suite was not green, and no new tests had been written.
|
||||
|
||||
What the first agent had already built, and which I kept unchanged: the
|
||||
`Surface` enum and its two carriers (`Resolution::ExternalCandidate`,
|
||||
`MemberSite::Unit`), `head_surface` in `resolve.rs`, `hierarchy.rs` with
|
||||
`surface_of` and the two surface-taking reads, the second `hier_members` table
|
||||
in `WorkspaceIndex` with its update/clear paths, the `FACTS_FORMAT` 18 → 19
|
||||
encoding, `hierarchical_declarations` and the fan-out rung in the server's
|
||||
`state.rs`, and the completion follow-the-site change in
|
||||
`completion/member.rs`. It is a good design and I did not redo any of it.
|
||||
|
||||
**What I finished.**
|
||||
|
||||
1. Made the workspace suite green. Four failures, each a real consequence of
|
||||
the change rather than a bug:
|
||||
- `lucisv_server` `a_local_only_symbol_sharing_the_new_names_spelling_is_not_a_bogus_refusal`
|
||||
— its fixture was a module's `wire`, which is now a hierarchical
|
||||
declaration and joins the fan-out by the new rung, so the test would have
|
||||
passed for the wrong reason ever after. The fixture is now a **function's
|
||||
local**, which is on neither surface, and the rung-6 attack it exists for
|
||||
is intact. The behaviour it used to pin got its own test beside it,
|
||||
`a_module_net_sharing_the_new_names_spelling_joins_the_fan_out_and_refuses_nothing`:
|
||||
the file *is* pulled in, and the rename still succeeds and still writes
|
||||
nothing there.
|
||||
- `vlog_semantic` `a_format_3_record_with_two_declarations_is_rejected_not_misread`
|
||||
— the record stripper counts a decl's fields. `MEMBER_DECL_FIELDS`
|
||||
11 → 12, `UNIT_DECL_FIELDS` 19 → 20, and one more `drain` for the surface
|
||||
letter.
|
||||
- `vlog_semantic` `an_instance_head_reaches_a_module_in_another_file` — its
|
||||
`u.internal` assertion was the old ruling. It now asserts the net
|
||||
resolves, *and* that the connection table still does not hold it, *and*
|
||||
that a port has one record on it.
|
||||
- `lucisv_server` e2e `an_instance_heads_port_is_hovered_across_files` —
|
||||
hover of `u.internal` across files now answers with the net's own
|
||||
declaration. The test asserts the file and line it names.
|
||||
2. Wrote the plan's tests (all passed first time against the first agent's
|
||||
library code, which is the strongest evidence I have that it was finished):
|
||||
the cross-file twin driven from **both** ends, nested `u_a.u_b.sig` over
|
||||
three files, the port, the parameter, the generate-block refusal, the
|
||||
interface tail, the ambiguous-`sub` refusal from both ends, and the
|
||||
two-way completion pin.
|
||||
3. Added the census-delta measurement as a corpus test rather than a prose
|
||||
claim, and put the hierarchical count into the index census line.
|
||||
4. Wrote this README, which the first agent had not started.
|
||||
|
||||
**Deviations and files touched outside the plan's expected set.** The plan
|
||||
named `crates/vlog_semantic/{facts.rs,workspace/*}`,
|
||||
`crates/vlog_refactor/src/rename/*`,
|
||||
`crates/lucisv_server/src/{completion/*,state.rs}`, tests, this README and
|
||||
`TODO.md`. Beyond those I touched:
|
||||
|
||||
- `crates/lucisv_server/src/rename.rs` — **tests only** (the `#[cfg(test)]`
|
||||
block): the fixture swap and the new sibling test above. No production line
|
||||
in that file changed.
|
||||
- `crates/lucisv_server/tests/e2e.rs` — the hover assertion above.
|
||||
- `crates/vlog_semantic/src/{lib.rs,model.rs,resolve.rs}` — the first agent's
|
||||
work, and unavoidable: `Surface` has to live in the model and be exported,
|
||||
and `resolve.rs` is where a spine's head is visible.
|
||||
|
||||
**One size flag for the lead.** `crates/lucisv_server/src/state.rs` is **957
|
||||
production lines outside its test module** — already well over the 800
|
||||
threshold before this lane, and CLAUDE.md's post-§28 measurement (which names
|
||||
only `perf.rs` and `lexer.rs` as over 600) is stale for it. This lane added
|
||||
**13** production lines there: the fan-out's new rung, seven lines inside
|
||||
`fan_out_of` plus its doc bullet. The rule says a dev adding to a file near
|
||||
600 puts the code in a new module; I did not, because the rung reads
|
||||
`self.index`, `want_declaration` and the caller's `containers` set and a
|
||||
module holding seven lines of it would be worse than the disease. The file
|
||||
wants a split of its own, which is a decomposition round, not a paragraph in
|
||||
this one. Every other file this lane touched is inside the rule:
|
||||
`workspace/hierarchy.rs` 80 production lines, `workspace/index.rs` 283,
|
||||
`workspace/record.rs` 315 (it *lost* the 60-line `is_exported`),
|
||||
`model.rs` 161, `resolve.rs` 520, `facts.rs` 526. Every function added or
|
||||
changed is under 50 lines.
|
||||
|
||||
**The gates.** `cargo fmt -p vlog_semantic -p lucisv_server -p vlog_refactor`
|
||||
(never `--all`) and `cargo clippy --all-targets` clean; `cargo test
|
||||
--workspace` **3 839 passed / 0 failed / 44 ignored** (baseline 3 829, +10:
|
||||
seven new rename tests, one new server fan-out test, one new completion test,
|
||||
one new census test); `tools/corpus_check.sh` **814/820**, the same six
|
||||
pre-existing parse errors (`compare_helper.sv`, `riscv_core_setting.tpl.sv`,
|
||||
`latch_map.v`, `riscv_instr_cover_group.sv`, `romload/testbench.v`,
|
||||
`smtbmc/mulcmp.v`); `format --stdout` over all **860** corpus files
|
||||
**byte-identical** to `~/.cache/lucisv-baselines/lucisv-0.44.0`, 0 differing;
|
||||
`cargo build --release -p lucisv_server` + `node editors/vscode/smoke.js` OK.
|
||||
Everything through `tools/guard.sh`; no guard kill, no limit raised.
|
||||
|
||||
**The census delta.** The single-file corpus census does not move at all —
|
||||
860 files, 27 486 symbols, 103 875 references, 1 197 unresolved, 0 unplaced,
|
||||
identical to the number the brief carried. It cannot move: §49 adds a tag to
|
||||
a resolution, not a resolution. What moves is the *workspace* census:
|
||||
|
||||
| | before | after |
|
||||
|---|---|---|
|
||||
| exported members (connection surface) | 12 939 | 12 939 |
|
||||
| hierarchical-only members | — | **5 239** |
|
||||
| corpus references only the hierarchical surface answers | 0 | **335** |
|
||||
|
||||
The connection count is unchanged **by construction**: `surface_of`'s
|
||||
`Surface::Connection` arms are the old `is_exported`'s `true` arms, name for
|
||||
name, with the hierarchical kinds added as new arms. The 5 239 new records are
|
||||
the corpus's modules' and interfaces' nets, variables and instances. Over the
|
||||
whole corpus 707 references carry a hierarchical candidate and 668 of them
|
||||
resolve; **335** of those land in the hierarchical-only table, which is the
|
||||
slice that could not resolve before.
|
||||
`the_hierarchical_surface_is_what_answers_a_measurable_slice_of_the_corpus`
|
||||
prints the three numbers on every run and pins the direction, not the
|
||||
constants.
|
||||
|
||||
A note on how that 335 is counted, because the obvious way is wrong. "The
|
||||
declaration's kind is `Net`, `Var` or `Instance`" over-counts by 216 on this
|
||||
corpus: an **interface's** signals are `Net`/`Var` and are on the *connection*
|
||||
surface, so they resolved before §49 as well. The exact test is membership of
|
||||
the hierarchical-only table itself
|
||||
(`WorkspaceIndex::hierarchical_declarations`), which is what the test does.
|
||||
|
||||
### opentitan (read-only, scratch index store)
|
||||
|
||||
Everything below is a `textDocument/rename` **request** whose returned edit
|
||||
was inspected and never applied.
|
||||
`git -C ~/repo/opentitan status --porcelain` reported the same three
|
||||
pre-existing files (`hw/ip/aes/dv/tb/tb.sv`,
|
||||
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`)
|
||||
before and after every run. Baseline binary: `lucisv-server` built
|
||||
`--release` from the `v0.44.0` tag in a scratch `git worktree` under the
|
||||
scratchpad, removed afterwards. Guard on every command; **no guard kill**.
|
||||
|
||||
**The headline — a DV bench reaching an IP module's internal variable.**
|
||||
`hw/ip/lc_ctrl/dv/tb.sv:229` writes
|
||||
`assign #1ps lc_ctrl_if.lc_ctrl_fsm_state = dut.u_lc_ctrl_fsm.fsm_state_q;`,
|
||||
and `fsm_state_q` is declared at `hw/ip/lc_ctrl/rtl/lc_ctrl_fsm.sv:173`.
|
||||
Renaming it (root `hw/ip/lc_ctrl`, cursor on the declaration):
|
||||
|
||||
| | 0.44.0 | this branch |
|
||||
|---|---|---|
|
||||
| files in the returned edit | `rtl/lc_ctrl_fsm.sv` (8 edits) | `rtl/lc_ctrl_fsm.sv` (8) **+ `dv/tb.sv` (1)** |
|
||||
| `rename`, three tries | 10 / 9 / 10 ms | 22 / 23 / 22 ms |
|
||||
| `prepareRename`, three tries | 1 / 0 / 1 ms | 0 / 0 / 1 ms |
|
||||
|
||||
That is the whole feature in one row: 0.44.0 edited the RTL and left the
|
||||
bench spelling the old name, and now the bench moves with it. It is also the
|
||||
whole cost: the tail's file is in the rename's fan-out now, so it is read,
|
||||
parsed and verified — 10 ms → 22 ms on this cursor. `prepareRename` does not
|
||||
move, because it does not fan out.
|
||||
|
||||
**`hw/ip/aes`, the tree the brief named.** Rename of
|
||||
`hw/ip/aes/rtl/aes_core.sv:87`'s `logic key_touch_forces_reseed`, root
|
||||
`hw/ip/aes`: **the same answer before and after** — `rtl/aes_core.sv`, 3
|
||||
edits — at 40 / 41 / 41 ms before and 53 / 55 / 57 ms after; `prepareRename`
|
||||
≈ 1 ms in both. And the count of newly resolved `MemberOf` references over
|
||||
`hw/ip/aes` is **0**, before and after. That is not a disappointment to hide,
|
||||
it is the shape of the IP: `aes`'s 5 hierarchical candidates all reach through
|
||||
a **generate block** (`u_aes_core.u_aes_control.gen_fsm[i]. … `,
|
||||
`u_aes_core.gen_ghash.u_aes_ghash. … ` in `rtl/aes.sv`) or sit inside a
|
||||
`bind aes …` in `dv/sva/aes_bind.sv`, where the head is resolved in the bind
|
||||
target's scope in another file and is therefore not an instance symbol this
|
||||
file can see. Neither is on either surface, and §49 said so in advance.
|
||||
|
||||
Over **all of `hw/`** (3 979 files) the picture is the one the corpus
|
||||
predicts: 91 930 connection members + **71 849** hierarchical-only ones;
|
||||
1 611 references carry a hierarchical candidate, 1 290 resolve, and **514**
|
||||
of those are answers only the hierarchical surface can give — `lc_ctrl`,
|
||||
`otbn`, `keymgr`, `dma` and `entropy_src` benches reaching into their DUTs.
|
||||
|
||||
**Store size** (the scratch `initializationOptions.storagePath`, the whole
|
||||
index cache for that root):
|
||||
|
||||
| root | 0.44.0 | this branch | delta |
|
||||
|---|---|---|---|
|
||||
| `hw/ip/aes` (124 files) | 1 459 576 B | 1 615 179 B | +155 603 B, **+10.7 %** |
|
||||
| `hw/ip/lc_ctrl` | 765 347 B | 813 065 B | +47 718 B, **+6.2 %** |
|
||||
|
||||
Two things are in that delta and they are not the same size: the one-letter
|
||||
surface field on every declaration and every external reference fact (small,
|
||||
and paid whether or not a module has internals), and the hierarchical member
|
||||
records themselves (the bulk).
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-05 — QA
|
||||
|
||||
**Diffs read in full**: `resolve.rs`, `model.rs`, `workspace/{hierarchy.rs (new),
|
||||
external.rs, index.rs, mod.rs, record.rs, reexport.rs, update.rs}`, `facts.rs`,
|
||||
`lib.rs`, `rename/warnings.rs`, `completion/member.rs`, `state.rs`, `rename.rs`,
|
||||
`e2e.rs`, all touched test files. Traced `head_surface` end to end — a link
|
||||
opens `Surface::Hierarchical` exactly when the *head symbol's own kind* is
|
||||
`SymbolKind::Instance` (`resolve.rs::link_type`/`head_surface`), never off a
|
||||
type name's spelling; a same-file spine stays on `MemberSite::Scope`
|
||||
untouched by any surface at all, exactly as before this feature. The `Local`
|
||||
reference-posting filter to `Surface::Connection` only in `record.rs` is by
|
||||
design and doesn't widen anything: an internal net's own-file uses are found
|
||||
by re-analysing its declaring file directly (which rename always does for
|
||||
the file it edits), not through the posting table that filter narrows.
|
||||
|
||||
**Gates (guarded, `tools/guard.sh` throughout).** `cargo fmt --check` clean;
|
||||
`cargo clippy --all-targets` clean; `cargo test --workspace`: **3 839 passed
|
||||
/ 0 failed / 44 ignored** — matches the dev's claim exactly (re-verified
|
||||
twice: once with the QA attack tests added, once after removing them, same
|
||||
count both times save for the attacks themselves). `tools/corpus_check.sh`:
|
||||
**814/820**, the same six pre-existing parse errors. `format --stdout` over
|
||||
all 860 corpus files vs `~/.cache/lucisv-baselines/lucisv-0.44.0`: **0
|
||||
differing**. Release build (`lucisv`, `lucisv_server`) + VS Code smoke
|
||||
(`node editors/vscode/smoke.js target/release/lucisv-server`): OK. Census:
|
||||
`the_corpus_index_finishes_most_external_references` prints 860 files,
|
||||
103 875 references, 12 939 connection members + **5 239** hierarchical-only —
|
||||
matches the README's table exactly.
|
||||
|
||||
**Rename matrix, driven through the public engine API (`vlog_refactor`) and
|
||||
confirmed by the dev's own tests plus attacks I added and then removed
|
||||
(temporary `qa_49_*` tests, run green, then deleted — the tree is back to
|
||||
exactly the dev's diff):**
|
||||
|
||||
- Cross-file twin from both ends, nested `u_a.u_b.sig` over three files, a
|
||||
port (one answer, one edit — checked the tail's edit range fires once, not
|
||||
once per surface), a parameter, the generate-block-scoped net refused
|
||||
honestly with no edit, an interface instance tail unchanged, the ambiguous
|
||||
two-`sub` case refused from both ends: all the dev's own tests, read and
|
||||
re-run green.
|
||||
- **New attack — rename onto a name already in the module, via the
|
||||
hierarchical tail, from both ends**: refused (`"would change what..."`).
|
||||
The live cross-file tail does not bypass the ordinary same-module capture
|
||||
check.
|
||||
- **New attack — rename a hierarchically-reached net onto a sibling port's
|
||||
name**: refused. A capture across the connection/hierarchical surface
|
||||
boundary is caught exactly like one within a surface.
|
||||
- **New attack — a non-instance head whose *type name* happens to spell a
|
||||
module name** (`sub h;` with no parens, a data declaration, not an
|
||||
instantiation): `head_surface` correctly reads the head symbol's own kind
|
||||
(`Var`, not `Instance`), so `h.internal` reads the connection surface and
|
||||
refuses the net. No crash.
|
||||
- **New attack — a hierarchical path inside a `bind` connection expression,
|
||||
through an instance declared *inside the bind target's module* in another
|
||||
file** (the shape behind the aes `bind` zero-count in the README): no
|
||||
crash, and the tail never resolves through the wrong scope — the head is
|
||||
looked up (if at all) in the writing scope, never the target's, exactly as
|
||||
the README predicts. Pinned with a temporary test, then removed.
|
||||
- **New attack — `didChange` promotes an internal net to a port**: before,
|
||||
hierarchical-only (1 record); after, on the connection table (1 record,
|
||||
not 2 — the hierarchical read still finds exactly one), and the cross-file
|
||||
tail still resolves exactly once, now to the port. **New attack —
|
||||
`didChange` removes the net entirely**: the hierarchical table drops the
|
||||
record and the cross-file tail goes back to unresolved. Both via
|
||||
`WorkspaceIndex::update_file` at the library level (no server session
|
||||
needed) — the incremental-update code path (`update.rs`) is exercised
|
||||
identically for hierarchical and connection tables, which is by
|
||||
construction from the diff (same `absorb`/`update_file` code, dispatched
|
||||
on `decl.surface`) and confirmed by these two round-trips.
|
||||
- **New attack — a hierarchical declaration's own reference postings
|
||||
include the cross-file tail** (`WorkspaceIndex::references_to` on a net's
|
||||
`Def`, gotten via `hierarchical_declarations`): confirmed — this is the
|
||||
exact mechanism `state.rs::want_declaration` stands on to pull the tail's
|
||||
file into a rename's fan-out.
|
||||
|
||||
**Completion.** The dev's own two-way pin
|
||||
(`an_instance_head_lists_the_hierarchical_surface_and_a_connection_list_does_not`)
|
||||
read and re-run. **New attacks, run green then removed**: `u_a.u_b.`
|
||||
(nested) lists `u_b`'s module's own hierarchical surface, not `u_a`'s and
|
||||
not empty; an instance of an **unknown** module in *expression* position
|
||||
(not just the connection-list shape the dev's own
|
||||
`a_module_the_workspace_does_not_declare_answers_nothing` already covered)
|
||||
answers empty, no panic.
|
||||
|
||||
**Opentitan (read-only; every`textDocument/rename` a request, inspected,
|
||||
never applied).** Built `v0.44.0`'s `lucisv-server` in a scratch worktree
|
||||
(`git worktree add`, removed after). `git -C ~/repo/opentitan status
|
||||
--porcelain` showed only the three pre-existing files
|
||||
(`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/.../ast.sv`,
|
||||
`hw/top_earlgrey/.../ast.sv`) before and after every run — reproduced
|
||||
independently, not assumed from the dev's log.
|
||||
|
||||
- `lc_ctrl_fsm.sv:173`'s `fsm_state_q`, renamed from the declaration: 0.44.0
|
||||
→ `rtl/lc_ctrl_fsm.sv` alone, 8 edits, 9–10 ms rename / 0–1 ms
|
||||
prepareRename. This branch → **+ `dv/tb.sv`, 1 edit**, same 8 in the rtl
|
||||
file, 22–24 ms rename / 0–1 ms prepareRename. Matches the README exactly.
|
||||
Dumped every edit's range and the *exact source text at that range* on
|
||||
both files: **every one reads `"fsm_state_q"`**, character-for-character,
|
||||
new file included (`dv/tb.sv:229`, columns 63–74).
|
||||
- `aes_core.sv:87`'s `key_touch_forces_reseed`: **identical answer** before
|
||||
and after — `rtl/aes_core.sv`, 3 edits — 38–41 ms → 55–56 ms. Matches.
|
||||
- Sampled the newly-resolved references over `hw/` with an independent
|
||||
read-only tool (not the dev's — built fresh against the library API):
|
||||
**1611 hierarchical candidates, 1290 answered, 514 hierarchical-only** —
|
||||
matches the README's table exactly. Printed 20 of the 514 with the
|
||||
occurrence line, the resolved declaration's file:line, and the
|
||||
declaration's own source text. All 20 are genuine DV-bench-into-DUT
|
||||
reaches (`dut.reg2hw...`, `dut.u_x.state_q`, `dut.lfsr_en`, …), every
|
||||
declaration's source text actually spells the referenced name at the
|
||||
claimed location, and every one is a plausible member of the instance's
|
||||
module — no false positive found in the sample.
|
||||
|
||||
**Findings.** None at HIGH or MEDIUM severity. Two LOW observations, neither
|
||||
blocking:
|
||||
|
||||
- LOW — `crates/lucisv_server/src/state.rs` is already flagged by the dev
|
||||
(957 production lines) and separately filed by the lead as TODO §55; no
|
||||
new action from this QA pass beyond confirming the number.
|
||||
- LOW — the `Local`-reference-posting filter to the connection surface
|
||||
(`record.rs::facts_from_analysis`) is a quiet, easy-to-miss line to
|
||||
re-derive from first principles (it looks at first glance like it could
|
||||
under-post same-file hierarchical uses). Traced it through
|
||||
`merge_references`/`want_declaration` and confirmed by the incremental
|
||||
`didChange` attacks above that nothing is actually lost — worth a comment
|
||||
pointer from `record.rs` to `hierarchy.rs::surface_of` for the next reader,
|
||||
but not a functional gap.
|
||||
|
||||
**Verdict: PASS.** Rename correctness, the completion split, the verifier's
|
||||
refusals, the two-table index mechanics, the census delta and the opentitan
|
||||
before/after all hold under attack, including several shapes beyond the
|
||||
dev's own plan (own-scope and cross-surface capture through a hierarchical
|
||||
tail, a non-instance head sharing a module's name, a bind-through-target
|
||||
scope, and both `didChange` directions). Every temporary QA test was
|
||||
removed after running green; the tree's diff against master is byte-for-byte
|
||||
the dev's original plus this log entry and the TODO.md checkbox below.
|
||||
|
||||
## Docs to apply at merge (lead)
|
||||
|
||||
**`docs/topo.md` §2.9 row 23** — strike, with:
|
||||
|
||||
> ~~A **cross-file instance-member tail does not resolve for rename** …~~ —
|
||||
> **delivered 2026-09-05 by hierarchical-tail (TODO §49):** a module now has
|
||||
> two member surfaces. Its *connection* surface is unchanged — ports and
|
||||
> parameters, what a connection list may name and what `member` /
|
||||
> `members_of` / `members_of_chain` / the `propagate-ports` engine /
|
||||
> connection-list completion read. Its *hierarchical* surface is that set plus
|
||||
> its nets, variables and instances (§23.6), recorded in a second index table
|
||||
> and tagged on the fact (`FACTS_FORMAT` 18 → 19), and read **only** by the
|
||||
> tail walk behind an instance head (`Resolution::ExternalCandidate` carrying
|
||||
> `Surface::Hierarchical`, set by `resolve.rs::head_surface`). `assign w =
|
||||
> u_x.sig;` in `top.sv` now resolves to `sub.sv`'s `wire sig`, the rename
|
||||
> edits both files, and the §2.9-20 warning is retired for a tail that
|
||||
> resolved. A generate-block-scoped net (`u_x.gen[0].sig`) is on neither
|
||||
> surface and is still refused honestly — the one gap this row leaves behind.
|
||||
|
||||
**`docs/features/comment-slots/README.md`, "Findings" item 2** — the gap it
|
||||
flagged is closed. **Already applied by this lane** (the one line the brief
|
||||
allowed); nothing for the lead to do, it is recorded here so the merge sees
|
||||
it:
|
||||
|
||||
> **Closed 2026-09-05 by TODO §49 / `docs/features/hierarchical-tail`:** a
|
||||
> module's hierarchical surface makes the cross-file tail resolve, so the edit
|
||||
> lands in both files and the warning is retired for it.
|
||||
|
||||
**`README.md`** — no change needed; it does not describe the member tables at
|
||||
this depth.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-05 — lead.** Accepted; ships in 0.45.0 with §47 and §48. The
|
||||
first dev was cut off by the outage with the library half complete and
|
||||
sound; the second kept all of it and finished the tests, the README and
|
||||
the gates — the right call. The ruling is implemented as ruled: two
|
||||
disjoint tables, the hierarchical one read by exactly one walk, and the
|
||||
connection surface byte-identical for every existing reader (the census's
|
||||
12 939 connection members unchanged by construction). QA's matrix is the
|
||||
proof that matters for a rename: refusals on capture across the surface
|
||||
boundary, on an ambiguous module, on a generate-scoped net; the lc_ctrl
|
||||
edit inspected range by range; 20 of the 514 newly resolved opentitan
|
||||
references sampled and all genuine. The completion decision (hierarchical
|
||||
members behind `u_x.` in an expression, ports only in a connection list)
|
||||
is what a user typing a hierarchical path wants. The rename cost of one
|
||||
more file's read is the feature. QA's two LOWs: `state.rs` is filed as
|
||||
§55; the `Local`-posting doc pointer is added at review.
|
||||
|
||||
*(reserved for the lead — do not write here)*
|
||||
@@ -0,0 +1,481 @@
|
||||
# package re-exports (TODO §48)
|
||||
|
||||
## Goal
|
||||
|
||||
`export b_pkg::x;` inside `package a_pkg` was an opaque leaf: the binder bound
|
||||
nothing for it and the index recorded nothing about it, so a file that did
|
||||
`import a_pkg::*` and named `x` resolved nothing, `a_pkg::` offered nothing,
|
||||
and a rename of `x` left the `export` line behind. This round makes the
|
||||
re-export a real edge in both layers, which is `docs/topo.md` §2.9-16 and
|
||||
request (a) of `docs/features/dpi-export/README.md`.
|
||||
|
||||
**The binding half.** `bind_export_path` (beside `bind_import_path`, sharing
|
||||
its path walk) records the two halves an import records — `pkg` as a
|
||||
`Target::Package` use, `item` as a `Target::UnitMember(pkg)` use — and pushes
|
||||
**no** scope import, because a re-export brings nothing into the exporting
|
||||
package (IEEE 1800 §26.6). `export *::*;` records nothing: neither half is an
|
||||
identifier. A DPI export (`export "DPI-C" function f;`) stays the opaque leaf
|
||||
it was.
|
||||
|
||||
**The resolution half.** `FileFacts` gains an `RX` group (`FACTS_FORMAT`
|
||||
17 → 18): per package, the packages and names it re-exports. The member walk
|
||||
in `workspace/external.rs` — the one lookup both the overlay and the index's
|
||||
own reference postings go through — follows those edges after a unit's own
|
||||
members and its `extends` chain, with a visited set so a cycle terminates. So
|
||||
definition, hover, completion after `a_pkg::`, find-references and rename all
|
||||
read the same edge and cannot disagree about it.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **`export *::*;` is expanded at record time into the exporting package's own
|
||||
imports**, rather than stored as a flag for a later walk to interpret. §26.6
|
||||
reads "everything imported into this package is re-exported", and which
|
||||
packages those are is a property of the very file being read off — so a flag
|
||||
would only move the same lookup somewhere with strictly less information,
|
||||
and nothing would ever read it. `export *::*;` in a package that imports
|
||||
nothing therefore records nothing, which is also what it re-exports. **This
|
||||
is the one deviation from §48's letter**, which asked for "`(pkg, item)`
|
||||
pairs, `(pkg, "*")`, and a `*::*` flag"; the first two are exactly what `RX`
|
||||
holds, and the third is expanded instead of stored. Behaviour is identical
|
||||
either way (pinned in `an_export_of_everything_reexports_what_the_package_imports`).
|
||||
- **A re-export is followed only for a *package*.** The `RX` group is keyed by
|
||||
the name of the package whose body writes the `export`, and only
|
||||
`ItemKind::Package` bodies are scanned. A compilation-unit-scope `export` is
|
||||
not recorded; the LRM does not put one there.
|
||||
- **The re-export hop is taken after a unit's own members and its bases**,
|
||||
never before, so a package's own declaration of a name it also re-exports is
|
||||
what a lookup finds and what completion lists
|
||||
(`a_local_declaration_wins_over_a_reexported_name_of_the_same_spelling`).
|
||||
- **The walk is two levels deep, deliberately.** Each hop of the re-export walk
|
||||
asks `own_chain` — a package and its `extends` chain — not `member_chain`,
|
||||
which would recurse into the very walk that called it. Chasing a chain of
|
||||
re-exports is the walk's own job, and it does it with an explicit queue.
|
||||
- **The visited set is package names for a lookup, `(package, name)` pairs for
|
||||
a listing.** A lookup for one name only ever follows edges that admit that
|
||||
name, so the filter is constant and a package need be asked once; a listing
|
||||
follows every edge, so the same package may be reached once per specific
|
||||
name it is re-exported through. Both sets are bounded by the workspace.
|
||||
- **`WorkspaceIndex::member` is unchanged** — it stays the raw table read.
|
||||
Every walk that should follow re-exports goes through `member_chain` or
|
||||
`members_of_chain`, which is where the hop was added.
|
||||
- **A re-export edge is untyped.** Nothing checks that the named package
|
||||
exists, that it declares the name, or that the exporting package imports it
|
||||
(§26.6 requires the last of these, and lucisv is not an elaborator). An edge
|
||||
that leads nowhere simply answers nothing.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **vlog_parser → vlog_semantic (consumed, unchanged).** `ItemKind::Export`
|
||||
carries `ExportDecl::Package(Vec<ImportPath>)`, each `ImportPath` holding two
|
||||
`Name`s with exact token spans, and `export *::*;` is one path whose
|
||||
**package** half is `"*"`. Both halves' spans come straight off the token, so
|
||||
§47's `exact_or_empty` guard is not needed here (there is no derived span to
|
||||
check) — `an_export_records_both_halves_on_exactly_their_own_bytes` asserts
|
||||
the bytes anyway.
|
||||
- **vlog_semantic → lucisv_server (promised, additive).** `FACTS_FORMAT` is
|
||||
**18**. `index_cache` drops a store stamped with any other number, which it
|
||||
already did; its `a_store_from_any_previous_facts_format_is_dropped_not_misread`
|
||||
enumerates `1..FACTS_FORMAT` and needed no change.
|
||||
`WorkspaceIndex::members_of_chain` and the member lookup behind
|
||||
`resolve_external` may now answer with a `Def` in a package the asking path
|
||||
never named — the declaring one. No signature changed and no caller was
|
||||
touched.
|
||||
- **vlog_semantic internal.** `external::member_chain` keeps its signature and
|
||||
its contract; `own_chain` and `own_members` are the base-chain halves split
|
||||
out of it and out of `members_of_chain`, so a re-export hop lists exactly
|
||||
what a lookup through it would find. `WorkspaceIndex::fingerprint` gained
|
||||
`reexport …` lines: the edges decide what `a_pkg::x` means, so a merge that
|
||||
dropped one must be visible as more than whichever references happened to
|
||||
resolve through it.
|
||||
- **dpi-export README, request (a): answered** (edited there, one paragraph).
|
||||
Request (b) — binding a DPI export's `name` — is untouched and still open.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] 48.1 `bind_export_path`: both halves recorded, no scope import,
|
||||
`export *::*;` records nothing; the negative pinned
|
||||
- [x] 48.2 `RX` group, `FACTS_FORMAT` 17 → 18, the member walk and the member
|
||||
listing follow re-exports transitively with a visited set
|
||||
- [x] `Affected::exporters` so a restricted merge rebuilds the table, and the
|
||||
fingerprint witnesses it
|
||||
- [x] unit tests (`crates/vlog_semantic/tests/reexports.rs`, 14) and one
|
||||
wire-level e2e (`crates/lucisv_server/tests/e2e.rs`)
|
||||
- [x] cycle, unknown item, transitive chain, local-beats-reexported
|
||||
- [x] census re-derived and the delta explained
|
||||
- [x] gates
|
||||
- [x] QA
|
||||
|
||||
## Files touched
|
||||
|
||||
Exactly the expected set, plus the two docs edits:
|
||||
|
||||
- `crates/vlog_semantic/src/bind/item.rs` — the `Export` arm split,
|
||||
`bind_export_path`
|
||||
- `crates/vlog_semantic/src/workspace/reexport.rs` — **new** (189 lines)
|
||||
- `crates/vlog_semantic/src/workspace/mod.rs` — `mod reexport;`, the
|
||||
`reexports` table
|
||||
- `crates/vlog_semantic/src/workspace/record.rs` — the `FileFacts` field
|
||||
- `crates/vlog_semantic/src/workspace/index.rs` — `reexports()`,
|
||||
`members_of_chain`
|
||||
- `crates/vlog_semantic/src/workspace/external.rs` — `own_chain`,
|
||||
`own_members`, the hop in `member_chain`
|
||||
- `crates/vlog_semantic/src/workspace/update.rs` — merge, `Affected`,
|
||||
fingerprint
|
||||
- `crates/vlog_semantic/src/facts.rs` — the `RX` group, `FACTS_FORMAT` 18
|
||||
- `crates/vlog_semantic/tests/reexports.rs` — **new**
|
||||
- `crates/lucisv_server/tests/e2e.rs` — one test appended
|
||||
- `docs/features/dpi-export/README.md` — request (a) answered
|
||||
- `TODO.md` — §48's own checkboxes
|
||||
|
||||
## Docs to apply at merge (lead)
|
||||
|
||||
**`docs/topo.md` §2.9 row 16** — strike it. Suggested text:
|
||||
|
||||
> ~~16. `ItemKind::Export` is an opaque leaf: a package re-export's `pkg::item`
|
||||
> halves are not references, so `export b_pkg::x;` is invisible to
|
||||
> go-to-definition, to find-references and to a rename, and a file importing
|
||||
> the re-exporting package cannot resolve the name at all.~~ **Closed
|
||||
> 2026-09-05 (§48, `docs/features/package-reexports/README.md`).** Both halves
|
||||
> are references (`bind_export_path`, no scope import), the index records each
|
||||
> package's re-exports (`FACTS_FORMAT` 18, the `RX` group), and the member
|
||||
> walk follows them transitively with a visited set — definition, hover,
|
||||
> completion, references and rename all read the one edge. A **DPI** export's
|
||||
> `name` is still unbound (dpi-export request (b)).
|
||||
|
||||
Nothing to change in `README.md`, `docs/repository-analysis.md` or
|
||||
`docs/site/`.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-09-05 — dev (Opus 5).**
|
||||
|
||||
- Read the plan, `docs/topo.md` §2.9-16 and dpi-export's request (a). The
|
||||
parser already had everything: `ExportDecl::Package(Vec<ImportPath>)` with
|
||||
exact spans on both halves, and `"*"` as the package name for `*::*`.
|
||||
- **48.1.** Split the `ItemKind::Export` arm in `bind/item.rs`: the package
|
||||
form calls a new `bind_export_path`, the DPI form stays in the opaque-leaf
|
||||
arm. `bind_export_path` is `bind_import_path` minus the
|
||||
`scopes[scope].imports.push(...)`, plus the early return for a `*` package.
|
||||
Used `Target::Package` rather than the plan's `Target::Unit`, because that is
|
||||
what `bind_import_path` records for the same half and the plan's own words
|
||||
were "exactly the halves `bind_import_path` records"; `Package` is the
|
||||
narrower and therefore the more honest of the two (only a package may be
|
||||
re-exported), and it produces the same `ExternalCandidate { paths: ["b_pkg"] }`
|
||||
for the workspace.
|
||||
- **48.2.** New module `workspace/reexport.rs` — the `Reexport` record, the
|
||||
read-off (`of`, with the `*::*` expansion), and the two walks (`member`,
|
||||
`members`). `external.rs` grew `own_chain` and `own_members`, the base-chain
|
||||
halves the walk asks at each hop; `member_chain` is now `own_chain` else
|
||||
`reexport::member`, and `members_of_chain` is `own_members` chained with
|
||||
`reexport::members` under one dedup. New machinery went in the new module
|
||||
rather than into `external.rs` (301 → 349 lines) or `index.rs` (521 → 523),
|
||||
as the brief asked.
|
||||
- Cost of the hop for a workspace with no re-exports: one `BTreeMap` lookup
|
||||
returning an empty slice, per member miss — `reexport::member` returns on
|
||||
that lookup before it allocates anything, which matters because
|
||||
`merge_references` asks `member_chain` once per external reference in the
|
||||
workspace (hundreds of thousands on opentitan). Nothing else changed shape.
|
||||
- The fingerprint gained `reexport <exporter> <- <pkg>::<item>` lines, and
|
||||
`Affected` gained `exporters` so a one-file update rebuilds only that
|
||||
package's edges — checked by `an_update_and_a_build_agree_on_the_reexport_table`.
|
||||
- Wrote 14 unit tests and one e2e. Confirmed the e2e really depends on the
|
||||
feature by temporarily emptying `FileFacts::reexports` (it failed on the
|
||||
first definition), then restored — the same trick that produced the "before"
|
||||
binary for the opentitan probe.
|
||||
|
||||
### Census delta
|
||||
|
||||
Re-derived with `cargo test -p vlog_semantic --test corpus -- --nocapture`:
|
||||
|
||||
| | before | after |
|
||||
|---|---|---|
|
||||
| files | 860 | 860 |
|
||||
| symbols | 27 486 | 27 486 |
|
||||
| references | 103 870 | **103 875** |
|
||||
| unresolved | 1 197 | 1 197 |
|
||||
| names unplaced | 0 | 0 |
|
||||
|
||||
**+5 references, nothing else moved** — and they are exactly the five names the
|
||||
corpus's two *package* re-export lines write:
|
||||
|
||||
- `ibex_mem_intf_agent_pkg.sv:28` `export ibex_mem_intf_pkg::*;` — 1 (the
|
||||
package half; the `*` is not a name)
|
||||
- `csr_utils_pkg.sv:10`
|
||||
`export dv_base_reg_pkg::csr_field_t, dv_base_reg_pkg::decode_csr_or_field;`
|
||||
— 4 (two package halves, two item halves)
|
||||
|
||||
The corpus's other nine `export` lines are all DPI exports, which are
|
||||
deliberately unchanged. Unresolved is flat, so all five became external
|
||||
candidates rather than dead ends; no symbol was declared and no span was
|
||||
derived, so `symbols` and `unplaced` could not move.
|
||||
|
||||
### Gates (all through `tools/guard.sh`; no guard kill)
|
||||
|
||||
| gate | result |
|
||||
|---|---|
|
||||
| `cargo fmt -p vlog_semantic -p lucisv_server` | clean (never `--all`); `--check` clean at the end |
|
||||
| `cargo clippy --all-targets` | clean, no new `#[allow]` |
|
||||
| `cargo test --workspace` | **3 829 passed, 0 failed, 44 ignored** — baseline 3 814, **+15** (14 unit tests in `tests/reexports.rs`, 1 e2e) |
|
||||
| `tools/corpus_check.sh corpus` | **814/820 (99.3%)**, the same six parse errors; `corpus-check-results.tsv` unmodified in `git status` |
|
||||
| formatter byte-identity | `format --stdout` of all **860** corpus files, this build vs `~/.cache/lucisv-baselines/lucisv-0.44.0`: **0 differ** |
|
||||
| `cargo build --release -p lucisv_server` + smoke | OK — the release server answers `definition` on a name reached through `export b_pkg::x;` in a three-file scratch workspace |
|
||||
| semantic corpus census | 860 files, 27 486 symbols, **103 875** references, 1 197 unresolved, **0 unplaced** (delta above) |
|
||||
| opentitan `definition` through a re-export | **before `[]`, after the declaration** — see below |
|
||||
|
||||
Largest resident set observed by the guard: nothing came near the 8 GB limit,
|
||||
and no command was killed.
|
||||
|
||||
### opentitan (read-only, scratch index store)
|
||||
|
||||
The tree does have real package re-exports, so the check was run rather than
|
||||
skipped:
|
||||
|
||||
- `hw/ip/spi_device/rtl/spi_device_pkg.sv:425-451` — eight (QA's count; the work log first said nine)
|
||||
`export spi_device_reg_pkg::<name>;` lines, each beside its `import`
|
||||
- `hw/top_englishbreakfast/ip_autogen/flash_ctrl/rtl/flash_ctrl_top_specific_pkg.sv:12-18`
|
||||
— seven `export flash_ctrl_pkg::<name>;` lines
|
||||
- `hw/ip/spi_host/dv/env/spi_host_env_pkg.sv:21` — one, used by
|
||||
`hw/ip/spi_host/dv/tb.sv:31` (added at review from QA's inventory)
|
||||
- `hw/dv/sv/csr_utils/csr_utils_pkg.sv:10` — the two-path line the corpus copy
|
||||
also holds
|
||||
|
||||
**The probe.** `hw/ip/spi_device/pre_dv/program/prog_passthrough_sw.sv:205`
|
||||
writes `spi_device_pkg::SramDepth`, and `SramDepth` is declared in
|
||||
`spi_device_reg_pkg.sv:10` and reaches `spi_device_pkg` only through
|
||||
`spi_device_pkg.sv:451`'s `export`. One server session per binary, root
|
||||
`hw/ip/spi_device`, `index.scope: "workspace"`, `initializationOptions.storagePath`
|
||||
pointed at a scratch directory, one read-only `didOpen`, one
|
||||
`textDocument/definition` at line 205 char 52:
|
||||
|
||||
| build | answer |
|
||||
|---|---|
|
||||
| before (this tree with `FileFacts::reexports` emptied, release) | `[]` |
|
||||
| after (this tree, release) | `spi_device_reg_pkg.sv`, LSP range line 9 chars 25–34 — i.e. `SramDepth` on line 10, the declaration |
|
||||
|
||||
The "before" binary was produced by temporarily emptying the record's re-export
|
||||
list and rebuilding, then restoring it and rebuilding again; `git diff` of
|
||||
`record.rs` afterwards shows only this round's intended change, and the tree was
|
||||
never checked out, reset or stashed. `git -C ~/repo/opentitan status --porcelain`
|
||||
showed only the three pre-existing modifications (`hw/ip/aes/dv/tb/tb.sv`,
|
||||
`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`)
|
||||
before and after. Probe script:
|
||||
`<scratchpad>/defprobe.py`.
|
||||
|
||||
### File sizes after the round
|
||||
|
||||
`reexport.rs` 189, `external.rs` 301 → 346, `index.rs` 521 → 525, `mod.rs`
|
||||
340 → 349, `record.rs` 558 → 566, `update.rs` 397 → 421, `bind/item.rs`
|
||||
555 → 590, `facts.rs` 733 → 760 (all raw line counts, comments included).
|
||||
Nothing crossed 600; the new machinery went in the new module, as the brief
|
||||
asked.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-09-05 — QA (Sonnet).**
|
||||
|
||||
Read the plan (TODO §48), the feature README in full, and the diffs of every
|
||||
file it lists plus `crates/lucisv_server/tests/e2e.rs`. Built
|
||||
`cargo build --release -p lucisv -p lucisv_server` once. Every suite run and
|
||||
every server session below went through `tools/guard.sh`; no guard kill.
|
||||
Attacked the two stated deviations (`Target::Package`, `*::*` expanded at
|
||||
record time) directly by reading `bind_export_path` against `bind_import_path`
|
||||
and `reexport::of`/`exports_of` line by line — both match the README's
|
||||
justification and produce the documented behavior.
|
||||
|
||||
**Gates.**
|
||||
|
||||
| gate | result |
|
||||
|---|---|
|
||||
| `cargo clippy --all-targets` | clean, no new `#[allow]` |
|
||||
| `tools/guard.sh -- cargo test --workspace` | **3 829 passed, 0 failed, 44 ignored** — matches the dev's number exactly, both before and after my scratch files were removed |
|
||||
| `tools/guard.sh -- tools/corpus_check.sh corpus` | **814/820 (99.3%)**, same six parse errors; `corpus-check-results.tsv` untouched in `git status` |
|
||||
| formatter byte-identity vs `~/.cache/lucisv-baselines/lucisv-0.44.0` | 860/860 corpus files, **0 differ** (script wrapped in `tools/guard.sh`) |
|
||||
| semantic corpus census (`cargo test -p vlog_semantic --test corpus -- --nocapture`) | **860 files, 27 486 symbols, 103 875 references, 1 197 unresolved, 0 unplaced** — exact match |
|
||||
| census delta grep | confirmed by hand: `corpus/ibex/dv/uvm/core_ibex/common/ibex_mem_intf_agent/ibex_mem_intf_agent_pkg.sv:28` (`export ibex_mem_intf_pkg::*;`, 1 name — the package half) and `corpus/ibex/vendor/lowrisc_ip/dv/sv/csr_utils/csr_utils_pkg.sv:10` (two paths, 4 names) sum to exactly **+5**; the corpus's other 9 `export` lines are all `"DPI-C"` (confirmed by grep), unchanged |
|
||||
|
||||
**Attack 1 — the three-file shape, wire-level (`tests/reexports.rs`, the dev's
|
||||
`e2e.rs` test, and two temporary tests of my own added to `e2e.rs` and removed
|
||||
after).** The dev's 14 unit tests and the one e2e test all pass and were read
|
||||
line-by-line, not just run: they cover single-name, `pkg::*`, `*::*` (with and
|
||||
without a same-named import), a chain, a two-package cycle, an undeclared
|
||||
name, local-beats-reexported, and the reference-posting/rename fan-out
|
||||
(`export` line rewritten, package half untouched implicitly since it is a
|
||||
different reference). Two gaps I closed with temporary `#[test]`s in
|
||||
`e2e.rs` (run, confirmed, then deleted — `git diff` on that file is exactly
|
||||
the dev's 145-line addition again):
|
||||
- A bare re-exported-but-not-imported name inside the exporting package stays
|
||||
unresolved **over the real wire**, and a rename of the source declaration
|
||||
edits **exactly one** site in the exporting file — the `export` line's item
|
||||
half, column 16 — never the bare use (still `NotFound`) and never the
|
||||
package half (column 9, a different reference entirely).
|
||||
- `export *::*;` with **no** `import` beside it offers nothing in completion
|
||||
and resolves nothing in definition — the negative half of the dev's own
|
||||
`an_export_of_everything_reexports_what_the_package_imports` unit test,
|
||||
confirmed again over the wire.
|
||||
|
||||
**Attack 2 — chains, cycles, negatives (12 temporary tests in a new
|
||||
`crates/vlog_semantic/tests/qa_reexport_attack.rs`, run then deleted).** All
|
||||
12 passed on the first try — no findings:
|
||||
- three-package cycle (a→b→c→a via `*`), terminates and answers correctly;
|
||||
- self re-export of an undeclared name (`export a_pkg::thing;` inside
|
||||
`a_pkg`) terminates in <2 s and stays unresolved — the visited set seeds
|
||||
itself with `unit`, so the one-hop-back edge is dropped without a second
|
||||
lookup;
|
||||
- self re-export of a name the package **does** declare is indistinguishable
|
||||
from an ordinary local declaration, because `own_chain` (tried first) wins
|
||||
before the reexport hop is ever asked;
|
||||
- re-export of a nonexistent package: unresolved, no panic;
|
||||
- a package that only **imports** a name (no `export` line at all) does not
|
||||
leak it — `offered()` is empty, matching §26.6 and the README's stated
|
||||
assumption;
|
||||
- duplicate `export b_pkg::x;` lines: the edge table dedupes to one listed
|
||||
name, but **both** source lines remain real references (`references_to`
|
||||
finds both) — correct, since dedup lives in `reexport::add`, not in the
|
||||
binder;
|
||||
- 50 packages in a straight re-export chain: build + lookup in **2.7 ms**
|
||||
— no accidental quadratic walk;
|
||||
- two packages both re-exporting the same name into a third: no panic, one
|
||||
deterministic answer (whichever edge the BFS queue reaches first, which is
|
||||
file order — not specified by the plan but not undefined either, and
|
||||
`members_of_chain`'s dedup-by-first-hit makes the listing agree with the
|
||||
lookup);
|
||||
- a DPI export beside a package export inside the same package body
|
||||
contributes no edge to the reexport table (the split arm in `bind/item.rs`
|
||||
holds);
|
||||
- **incremental**: editing the *declaring* package (`b_pkg`, not the
|
||||
exporter) to drop the re-exported name unresolves `a_pkg::x` on the very
|
||||
next lookup with only `b.sv` touched — `Affected::exporters` is keyed by
|
||||
the exporter for good reason, and nothing else needed to invalidate for
|
||||
this case to work; and adding a fresh `export` line to a package that had
|
||||
none is visible on the very next lookup, no separate rebuild step.
|
||||
|
||||
**Attack 3 — incremental,** covered above and by the dev's own
|
||||
`an_update_and_a_build_agree_on_the_reexport_table` (read and re-run).
|
||||
|
||||
**Attack 4 — the `FACTS_FORMAT` 18 bump, for real, not just the existing unit
|
||||
test.** Built the real `v0.44.0` server in a worktree
|
||||
(`git worktree add … v0.44.0`, removed after). Ran it against a fresh 3-file
|
||||
scratch workspace (`b_pkg` declares `x`; `a_pkg` does `export b_pkg::x;`;
|
||||
`top.sv` does `import a_pkg::*` and uses both the bare and qualified form),
|
||||
`initializationOptions.storagePath` pointed at a scratch dir:
|
||||
- 0.44.0, cold: `scan finished: 3 files (0 skipped, 0 from cache)`,
|
||||
`definition` on `a_pkg::x` → `[]` (matches the README's "before").
|
||||
Store header afterward: `lucisv-index-cache 2 17 0.44.0`.
|
||||
- 0.44.0 again, same store: `3 from cache` — sanity that the store format
|
||||
itself round-trips for the version that wrote it.
|
||||
- **New server, same (format-17) store**: `scan finished: 3 files (0 skipped,
|
||||
**0** from cache)` — dropped whole, not misread, exactly as
|
||||
`index_cache.rs`'s module doc promises (silent, not logged as an error;
|
||||
the "0 from cache" `--verbose` timing line is the observable). `definition`
|
||||
now correctly lands on `b_pkg.sv`'s declaration. Store header rewritten to
|
||||
`lucisv-index-cache 2 18 …`; `RX 1` appears for `a.sv`, `RX 0` for the
|
||||
other two.
|
||||
- **New server again, same (now format-18) store**: `3 from cache` — the
|
||||
round trip holds, same correct answer, `RX` group intact.
|
||||
|
||||
**Attack 5 — census,** re-run and cross-checked by hand above; matches
|
||||
exactly.
|
||||
|
||||
**Attack 6 — opentitan, read-only, scratch stores throughout.** Enumerated
|
||||
every `^\s*export ` line under `hw/` myself rather than trusting the dev's
|
||||
inventory, and found it **incomplete**: `hw/ip/spi_device/rtl/spi_device_pkg.sv`
|
||||
has **8** `export spi_device_reg_pkg::<name>;` lines (425, 431, 433, 435, 437,
|
||||
439, 441, 451), not the nine the dev's work log states, and the dev's list
|
||||
omits `hw/ip/spi_host/dv/env/spi_host_env_pkg.sv:21`
|
||||
(`export spi_host_env_cfg_pkg::SPI_HOST_NUM_CS;`) entirely — see **findings**
|
||||
below. Both are documentation-accuracy issues in the work log, not behavior
|
||||
bugs; I tested the missed file anyway.
|
||||
- **Reproduced the dev's own probe with the real `v0.44.0` binary** (not the
|
||||
dev's "emptied-`reexports`-field" stand-in): root `hw/ip/spi_device`,
|
||||
`prog_passthrough_sw.sv:205` char 52 — real 0.44.0 → `[]`; new server, same
|
||||
workspace → `spi_device_reg_pkg.sv` line 9 chars 25–34 (`SramDepth`'s
|
||||
declaration). Exact match to the dev's claim.
|
||||
- **Every other real-world re-export site**, new server only (all correct,
|
||||
real UVM/DV code, not synthetic):
|
||||
- `hw/ip/spi_host/dv/tb.sv:31` — bare `SPI_HOST_NUM_CS` under
|
||||
`import spi_host_env_pkg::*` → `spi_host_env_cfg_pkg.sv:7`, the real
|
||||
declaration, through the exact chain the missed inventory entry describes.
|
||||
- `hw/top_englishbreakfast/ip_autogen/flash_ctrl/rtl/flash_ctrl_lcmgr.sv:56`
|
||||
— bare `NumSeeds` under `import flash_ctrl_top_specific_pkg::*` →
|
||||
`hw/ip/flash_ctrl/rtl/flash_ctrl_pkg.sv:10`, across two disjoint top-level
|
||||
`hw/` subtrees (root had to be the whole `hw/`, 3 976 files, 182 s to
|
||||
scan — well inside the guard's defaults, no kill).
|
||||
- `hw/vendor/.../ibex_mem_intf_agent/ibex_mem_intf_agent_pkg.sv:28`
|
||||
(`export ibex_mem_intf_pkg::*;`) — completion after
|
||||
`ibex_mem_intf_agent_pkg::` in a synthetic **in-memory-only** overlay
|
||||
buffer (a `didOpen` at a URI under the read-only tree that was never
|
||||
saved, so nothing touched disk) lists exactly `ibex_mem_intf_pkg`'s five
|
||||
members plus the package's own local `ibex_mem_intf_request_sequencer`
|
||||
and `rw_e` — and none of `uvm_pkg`/`mem_model_pkg`/`ibex_cosim_agent_pkg`,
|
||||
which that package only imports, never re-exports. Definition on
|
||||
`DATA_WIDTH` through the same path lands on `ibex_mem_intf_pkg.sv`.
|
||||
- `hw/dv/sv/csr_utils/csr_utils_pkg.sv:10` — both `csr_field_t` and
|
||||
`decode_csr_or_field` (the export line's own item halves) resolve to
|
||||
`dv_base_reg_pkg.sv`.
|
||||
- **30 random `pkg::name` positions**, old vs new server, same workspace
|
||||
(`hw/ip/spi_device`, 64 files): first pass (no file opened) was a false
|
||||
start — this server needs the target file **open** for `definition` to
|
||||
answer at all, old or new, so I reran with the 8 distinct files in the
|
||||
sample opened first. **29 of 29 usable positions** (one sample line fell
|
||||
outside `.sv`/`.svh` and was dropped) answered **identically** between
|
||||
0.44.0 and the new build but one: `spi_device_pkg.sv:433`
|
||||
(`export spi_device_reg_pkg::SramPayloadDepth;`) — old `[]`, new resolves to
|
||||
`spi_device_reg_pkg.sv`. That is the export line's own item reference,
|
||||
exactly the new capability `bind_export_path` adds — not a regression, the
|
||||
feature working as designed on real code outside the corpus. No other
|
||||
position moved.
|
||||
- `git -C ~/repo/opentitan status --porcelain` before and after every session:
|
||||
only the three pre-existing modifications
|
||||
(`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`,
|
||||
`hw/top_earlgrey/ip/ast/rtl/ast.sv`).
|
||||
|
||||
**Attack 7 — formatter byte-identity,** covered in the gates table; the
|
||||
`ExportDecl::Package`/`Dpi` arm split changes no formatting.
|
||||
|
||||
### Findings
|
||||
|
||||
- **LOW — doc accuracy, `docs/features/package-reexports/README.md` Work
|
||||
log, "opentitan" section.** States "nine `export spi_device_reg_pkg::…;`
|
||||
lines" for `hw/ip/spi_device/rtl/spi_device_pkg.sv`; there are 8
|
||||
(lines 425, 431, 433, 435, 437, 439, 441, 451 — verified by
|
||||
`grep -c '^\s*export spi_device_reg_pkg::'`). Off-by-one in the write-up
|
||||
only; every one of the 8 resolves correctly (checked above).
|
||||
- **LOW — doc completeness, same section.** The inventory of real package
|
||||
`export` lines under `hw/` omits
|
||||
`hw/ip/spi_host/dv/env/spi_host_env_pkg.sv:21`
|
||||
(`export spi_host_env_cfg_pkg::SPI_HOST_NUM_CS;`), a genuine re-export used
|
||||
by real code (`hw/ip/spi_host/dv/tb.sv:31`, bare `SPI_HOST_NUM_CS` through
|
||||
`import spi_host_env_pkg::*`). Tested directly above — resolves correctly —
|
||||
so this is a documentation gap, not a functional one.
|
||||
- No MEDIUM or HIGH findings. No panic, no corruption, no idempotency
|
||||
violation, no incorrect resolution, no regression in any of the attacks
|
||||
above, across both a synthetic scratch workspace and ~4 000 files of real
|
||||
read-only opentitan RTL/DV code.
|
||||
|
||||
### Verdict
|
||||
|
||||
**PASS.** The two findings above are both LOW (documentation accuracy in the
|
||||
feature README's Work log, not in the shipped behavior) and do not block
|
||||
merge; the lead may want the dev to fix the "nine" → "eight" count and add
|
||||
the missed `spi_host_env_pkg.sv` line to the inventory, but nothing about the
|
||||
binding, the resolution walk, the incremental update, the on-disk format
|
||||
bump, or the formatter needs rework.
|
||||
|
||||
## Review
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-05 — lead.** Accepted; ships in 0.45.0 with §47 and §49. Both
|
||||
halves of the plan are the ruled ones and the two deviations are right:
|
||||
`Target::Package` is what the import half already records, and expanding
|
||||
`export *::*` into the package's own imports at record time is the honest
|
||||
encoding of §26.6 — a stored flag would have had no reader. The walk is
|
||||
two layers deep by construction (`own_chain` at every hop, never back into
|
||||
`member_chain`) with a visited set seeded on the starting unit, and QA's
|
||||
cycles, 50-package chain (2.7 ms) and self re-export all terminate. The
|
||||
store bump was verified against a genuine 0.44.0-written store. The census
|
||||
moved by exactly the five references the corpus's two package export lines
|
||||
carry. On opentitan a real gap closed: `spi_device_pkg::SramDepth` is
|
||||
reached only through a re-export and now resolves, with the four further
|
||||
sites QA found all correct. The two doc counts QA caught are corrected
|
||||
above.
|
||||
@@ -0,0 +1,453 @@
|
||||
# Type-name spans
|
||||
|
||||
## Goal
|
||||
|
||||
TODO.md §47 / `docs/topo.md` §2.9-2. `vlog_semantic/src/scan.rs` (193 lines)
|
||||
recovered the byte range of a name the AST kept only as a `String` by scanning
|
||||
the construct's own source text. Every declared name got a real `name_span`
|
||||
from the parser in the 2026-08-19 `name-spans` round; two *uses* did not, and
|
||||
they were the module's only remaining callers — the type name of a declaration
|
||||
(`DataType::name`, split as `pkg::item` or `iface.modport`) and `disable
|
||||
<label>`.
|
||||
|
||||
This round puts both spans on the AST, deletes `scan.rs`, and has the binder
|
||||
read what the parser already knew. A type reference is now located by
|
||||
construction rather than by a text search that is only right in practice, and
|
||||
the corpus census pin (`src[name_span] == name`) covers type-name references
|
||||
for the first time.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A name's span slices back to the name.** `DataType::name_span` is derived
|
||||
as `name_start .. name_start + name.len()`, so it is exact for every name the
|
||||
source spells the way the parser joined it. **Any** whitespace or comment
|
||||
around a `::` or `.` separator (`pkg :: item`, `pkg /* c */ :: item`, a
|
||||
name split across a line, `bus_if . mp`), an escaped segment terminated by
|
||||
a newline rather than a space, and spacing inside a dotted `disable` target
|
||||
spell the name differently from the AST's join (QA's census of the
|
||||
spellings, 2026-09-05). The binder therefore checks every segment's span
|
||||
against the source (`Binder::exact_or_empty`) before it records a
|
||||
reference, which is the rule the modport tail has always followed: such a
|
||||
segment is recorded with the **empty range at its start** — never a wrong
|
||||
non-empty range, and never dropped, because an empty range is what the
|
||||
corpus census counts as *unplaced*, so a parser regression in the join
|
||||
trips that alarm (lead's rework of QA's MEDIUM). `scan.rs` failed the
|
||||
same cases (its `find` matches whole words, so it never found `\a+b ` with
|
||||
its trailing space either), so this is parity, not a new gap.
|
||||
- **The token text of a plain identifier is its source text.** Pinned by the
|
||||
lexer (`src[span] == text`, `an_escaped_identifier_ends_before_its_terminating_whitespace`).
|
||||
Everything above rests on it.
|
||||
- **`DataType::name_start` is only ever written by the parser.** It is
|
||||
`pub(crate)` in `vlog_parser`; no other crate builds a `DataType` (grep:
|
||||
the only `DataType { … }` literals in the workspace are the two in
|
||||
`vlog_parser/src/parser/`).
|
||||
- opentitan is read-only. The before/after sweep used the server's scratch
|
||||
index store (`docs/performance_take3.md` §9) and
|
||||
`git -C ~/repo/opentitan status --porcelain` reported only the three
|
||||
pre-existing modified files before and after.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `vlog_parser`:**
|
||||
|
||||
- `DataType::name_span() -> TextRange` — where the type name is written, the
|
||||
empty range at the would-be position when the type is implicit.
|
||||
- `DataType::segments() -> impl Iterator<Item = (&str, TextRange)>` — the
|
||||
`::`/`.`-separated segments with their ranges, derived from `name_span` and
|
||||
the name's own text. Never rescans the construct.
|
||||
- `StmtKind::Disable { name, name_span }` — was `Disable(String)`.
|
||||
|
||||
**Promised to `vlog_semantic`'s callers:** `analyze(file, src)` keeps its `src`
|
||||
parameter. It is no longer used to *find* names — nothing in the crate scans
|
||||
source text any more — but it is still read by `Binder::exact_or_empty`, the
|
||||
"verify before recording" oracle used by eleven call sites (instance module
|
||||
names, class `extends` heads and tails, member tails, end labels, the type-name
|
||||
segments and the `disable` target). Removing it would remove that check, which
|
||||
is the opposite of what §47 is for. The vlog-semantic README's handshake item 2
|
||||
("a span for `DataType`") is delivered; the `src` half of item 1's promise
|
||||
("this parameter goes away") is amended to "src stops being a scanner and
|
||||
becomes a verifier".
|
||||
|
||||
**Not changed, and why:** `lucisv_server/src/type_def.rs` still finds a type
|
||||
site by a window (`site(&ty.name, TextRange::new(span.start, first))`) rather
|
||||
than by `DataType::name_span()`. That is a `textDocument/typeDefinition`
|
||||
concern in another crate and outside §47's file set; it is a clean follow-up
|
||||
now that the span exists. Filed here rather than edited.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] 47.1 `DataType::name_span` at every construction site + `segments()`;
|
||||
size ruled (below)
|
||||
- [x] 47.2 `StmtKind::Disable` name span
|
||||
- [x] 47.3 `scan.rs` deleted, its `mod` removed, binder reads the spans,
|
||||
census pin now covers type-name references
|
||||
- [x] Consumers: `nav`/`hover` already go through `Reference::name_span`
|
||||
(confirmed: `nav.rs` reads only `symbol.name_span` / `reference.name_span`);
|
||||
two definition tests added
|
||||
- [x] Gates (guarded)
|
||||
|
||||
## The size ruling
|
||||
|
||||
`DataType` rides in every `Expr` through `ExprKind::Type`, and `size_pins`
|
||||
holds `Expr <= 96`. Measured with a throwaway probe test on `v0.44.0`:
|
||||
|
||||
| | `DataType` | `ExprKind` | `Expr` | `StmtKind` | `Stmt` |
|
||||
|---|---|---|---|---|---|
|
||||
| before | 88 | 88 | 96 | 392 | 552 |
|
||||
| `pub name_span: TextRange` | 96 | 96 | **104** | **416** | **576** |
|
||||
| `pub(crate) name_start: u32` | 88 | 88 | 96 | 392 | 552 |
|
||||
|
||||
A whole `TextRange` breaks the pin — and `StmtKind`/`Stmt`'s pins with it.
|
||||
`DataType`'s eight-byte-aligned fields total 80 bytes and `virt` is one more,
|
||||
so the struct already carries seven bytes of padding: a `u32` fits in it for
|
||||
free, an eight-byte span does not.
|
||||
|
||||
So the span is stored as its **start** and paired with `name.len()` by
|
||||
`DataType::name_span()`. The plan offered two fallbacks — move the span into
|
||||
the already-boxed `TypeExtra`, or box it — and this is a third that is better
|
||||
than both: they would put a heap allocation on *every* `DataType`, because
|
||||
`name_span` is wanted for the implicit case too (the empty range at the
|
||||
would-be position), and an implicit type is the common one. The pin did not
|
||||
move. `name_start` is `pub(crate)`, so the invariant `end == start + len` has
|
||||
exactly one writer, the parser.
|
||||
|
||||
## Construction sites
|
||||
|
||||
Five, all in `vlog_parser/src/parser/`:
|
||||
|
||||
1. `parse_opt_data_type`'s `sequence`/`property` SVA-formal arm — the keyword
|
||||
token's start.
|
||||
2. `parse_opt_data_type`'s `virtual bus_if.mp` arm — delegates to (5).
|
||||
3. `parse_opt_data_type`'s type-keyword arm (`logic`, `int`, …) — the keyword
|
||||
token's start.
|
||||
4. `parse_opt_data_type`'s user-type arm — now calls the existing
|
||||
`parse_scoped_name`, which already returned the joined text plus the whole
|
||||
chain's range, so the `::` loop is no longer written twice.
|
||||
`parse_type_ref` (a bare `my_type_t` where a type is required) calls the
|
||||
same helper for the same reason.
|
||||
5. `parse_modport_port_type` — the head identifier's start.
|
||||
|
||||
The **implicit** case is spanned by `Parser::implicit_type()`: a `DataType`
|
||||
whose `name_start` is `self.here()`, the cursor before any of the type has
|
||||
been consumed. `parse_opt_data_type` starts from it, so an `input [7:0] x`
|
||||
whose type is nothing at all reports the empty range at the `[`; so does the
|
||||
`parameter type T` placeholder in `parse_param_decl` and in the parameter-port
|
||||
list, which write no data type at all. This is the convention `name_span`
|
||||
already used for an unnamed DPI formal.
|
||||
|
||||
## Docs to apply at merge (lead)
|
||||
|
||||
Three places in `docs/topo.md`:
|
||||
|
||||
- **§2.9 row 2** (line ~618) — struck. Suggested replacement row:
|
||||
|
||||
> | ~~2~~ | ~~A span for `DataType` (and `ExprKind::Cast::ty` tails) — the last thing keeping `vlog_semantic/src/scan.rs` alive~~ — **delivered 2026-09-05 by type-name-spans (TODO §47)**: `DataType::name_span()` (stored as a `u32` start paired with `name.len()`, so `Expr` stays inside its 96-byte pin) and `DataType::segments()` (the `::`/`.` split, derived from the span's own text); `StmtKind::Disable` carries its target's span too. `scan.rs` is deleted — nothing in `vlog_semantic` scans source text for a name any more. `analyze`'s `src` parameter stays, no longer as a scanner but as `Binder::exact_or_empty`'s verification oracle. The corpus census pin now covers type-name references. | vlog-semantic (item 2); restated by class-semantics | ~~vlog_parser~~ done |
|
||||
|
||||
- **§1.3's `vlog_semantic` layout paragraph** (line ~201) — drop the
|
||||
`` `scan.rs` (residual text-scanning for the one span the parser doesn't
|
||||
carry — `DataType`; shrinks to zero when open handshake §2.9-2 lands); ``
|
||||
clause outright; the file is gone.
|
||||
|
||||
- **§1.2's `name-spans ◀──▶ vlog-semantic` row** (line ~449) — the tail
|
||||
"shrinking `scan.rs` to the `DataType` case (still open — §2.9)" becomes
|
||||
"…; type-name-spans (§47) delivered the `DataType` case and deleted
|
||||
`scan.rs`".
|
||||
- **`crates/vlog_semantic/README.md` does not exist** (the crate has no
|
||||
top-level README; `docs/features/vlog-semantic/README.md` is the one the
|
||||
§47 brief means). Its Handshakes/Deviations text was edited in place by this
|
||||
lane — see the work log.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-09-05 — dev agent.**
|
||||
|
||||
- Measured the sizes first (throwaway `tests/zz_size_probe.rs`, deleted), which
|
||||
ruled out the plain `TextRange` field before a line of it was written. See
|
||||
"The size ruling".
|
||||
- `DataType` gained `pub(crate) name_start: u32`, `pub fn name_span()` and
|
||||
`pub fn segments()`, plus a free `separator()` that finds the first `::`/`.`
|
||||
that is not inside a leading escaped identifier. `segments()` yields nothing
|
||||
for an implicit type.
|
||||
- Five parser construction sites set the start; `parse_scoped_name` is now
|
||||
reused by the two that had open-coded its `::` loop, which is a small
|
||||
de-duplication that fell out of needing the range.
|
||||
- `StmtKind::Disable(String)` became `Disable { name, name_span }`. The `fork`
|
||||
form spans the `fork` keyword; the dotted form spans the whole `a.b` chain.
|
||||
Formatter (`format/stmt.rs`) and linter (`rules/disable_statement.rs`) match
|
||||
arms updated; neither reads the span, so no output moves.
|
||||
- `Binder::bind_data_type` lost its `window` parameter and gained
|
||||
`bind_type_name`, which walks `ty.segments()` and records the head as a
|
||||
`Target::Unit` (`::`) or `Target::Type` (`.` or bare) and each following
|
||||
segment as a member of the one before it. The old code split once and bound
|
||||
two halves; a three-segment `a::b::c` used to bind `a` plus a `b::c` that no
|
||||
scan could ever locate, and now binds all three.
|
||||
- Every span is passed through `exact_or_empty`; a segment that does not
|
||||
verify was, in the dev's version, the end of the chain (the reference
|
||||
dropped). **Changed at review:** every segment is recorded, a failing one
|
||||
with the empty range, so the census's `unplaced` counter — not a quieter
|
||||
resolution rate — is what a future join regression would move.
|
||||
Corpus-neutral (`unplaced` was and is 0; no corpus file spells a type name
|
||||
with spaces around its separators).
|
||||
- Dropping `window` removed the window computations at ten call sites, and with
|
||||
them the now-unused `span` parameters of `bind_data_decl`,
|
||||
`bind_declarators` and `bind_enum_body`.
|
||||
- `crates/vlog_semantic/src/scan.rs` deleted along with `mod scan;`. Its six
|
||||
unit tests went with it (they tested the scanner, not a behaviour).
|
||||
- Tests added: four in `vlog_parser/tests/spans.rs` (a type name slices back to
|
||||
the name as written across all five sites; `segments()` splits `pkg::state_t`
|
||||
and `bus_if.mp` and yields nothing for an implicit type; an escaped segment
|
||||
keeps its terminating space in both the span and the first segment; a
|
||||
`disable`'s target has a span). The generic statement walker in `spans.rs`
|
||||
now checks `Disable`'s span instead of skipping the arm. Two in
|
||||
`lucisv_server/src/nav.rs`: F12 on the item half of `pkg::t` and on both
|
||||
halves of `bus_if.mp`.
|
||||
|
||||
## Gates (all through `tools/guard.sh`; no guard kill)
|
||||
|
||||
| gate | result |
|
||||
|---|---|
|
||||
| `cargo fmt -p vlog_parser -p vlog_semantic -p vlog_formatter -p vlog_linter -p lucisv_server` | clean |
|
||||
| `cargo clippy --all-targets` | clean, no new `#[allow]` |
|
||||
| `cargo test --workspace` | **3 814 passed, 0 failed, 44 ignored** — the 0.44.0 baseline exactly: six `scan.rs` unit tests left, six new ones arrived |
|
||||
| `tools/corpus_check.sh corpus` | 814/820 (99.3%), the same six parse errors; the per-file TSV is **byte-identical** to the committed `corpus-check-results.tsv` |
|
||||
| formatter byte-identity | `format --stdout` of all 860 corpus files, new vs `~/.cache/lucisv-baselines/lucisv-0.44.0`: **0 differ** |
|
||||
| `cargo build --release -p lucisv_server` + smoke | OK — F12 on `pkg::t`'s head and item, on `bus_if.mp`'s head and modport, and on a `disable`'s target all answer the right ranges; hover and `documentSymbol` answer |
|
||||
| semantic corpus census | 860 files, 27 486 symbols, 103 870 references, 1 197 unresolved, **0 unplaced** — byte-identical to the same test run in a `v0.44.0` scratch worktree |
|
||||
| opentitan `definition` sweep | 200 type-name positions over 74 files (50 scoped heads, 36 scoped items, 105 bare `_t`/`_e` types, 9 `virtual …_if`), 0.44.0 server vs the new one: **200/200 identical**, 180 of them non-empty answers. opentitan `status --porcelain` reported only the three pre-existing modified files after |
|
||||
|
||||
The 0.44.0 baseline binary was built in a scratch `git worktree` at the tag
|
||||
(`~/.cache/lucisv-baselines/lucisv-0.44.0`, sha256 `4d928238…`, kept for the
|
||||
next round); the worktree was removed afterwards. Sweep scripts:
|
||||
`<scratchpad>/defcmp/{lspclient,positions,run}.py`.
|
||||
|
||||
### Census: before and after
|
||||
|
||||
The plan asked for the new count. The corpus test's numbers are **unchanged in
|
||||
every field** — 27 486 / 103 870 / 1 197 / 0 unplaced on both sides — which is
|
||||
the strongest form of the answer: type-name references were already counted,
|
||||
they were merely located by a scan, and the parser's spans put them in exactly
|
||||
the same places. (The `21 485` the §47 brief quotes is the 2026-08-19
|
||||
figure; the corpus and the crate have both grown a great deal since, and the
|
||||
vlog-semantic README's copy of it has been refreshed to today's numbers.)
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-09-05 — QA agent.**
|
||||
|
||||
Verdict: **PASS**. No hard-invariant violation, no mislocation, no
|
||||
formatter-output change, no corpus regression. One MEDIUM documentation/
|
||||
observability finding below; recommend fixing at the lead's discretion
|
||||
(does not block merge).
|
||||
|
||||
### What was verified, and how
|
||||
|
||||
1. **Attack battery on `bind_type_name`/`exact_or_empty` (never mislocate).**
|
||||
Built a scratch integration test
|
||||
(`crates/vlog_semantic/tests/zz_qa_type_name_spans.rs`, removed before
|
||||
finishing) exercising `analyze()` over: plain `pkg::item`, spaced
|
||||
`pkg :: item`, a `/* c */`-interrupted `pkg :: item`, `pkg::` / `item`
|
||||
split across a line, `\my-pkg ::\state-t` (escaped both sides, space
|
||||
terminator), `\my-pkg\n::item` (escaped, newline terminator), an escaped
|
||||
segment whose own text contains `::` (`\a::b ::c`), `bus_if.mp`,
|
||||
`bus_if . mp` (spaced), `virtual bus_if.mp`, `virtual interface bus_if`
|
||||
with no modport, `pkg::t` used bare (parameterized-type source next to a
|
||||
typedef target lacking params — the plain scoped case), an inline `enum`,
|
||||
an inline `struct`, three implicit-type shapes (`input [7:0] x`,
|
||||
`parameter type T`, `wire w`), a class-scoped `cls::t`, a cast `int'(x)`,
|
||||
a scoped cast `pkg::t'(x)`, and five `disable` shapes (`fork`, a plain
|
||||
label, a dotted `a.b.c`, an escaped label, and a spaced dotted
|
||||
`a . b . c`).
|
||||
|
||||
For every reference `analyze()` recorded across this whole battery,
|
||||
`src[name_span] == name` held, or the span was empty — **zero
|
||||
non-empty-but-wrong spans** ("MISMATCH") anywhere. The hard property the
|
||||
round is built on holds under adversarial input.
|
||||
|
||||
**Fallback / dropped-reference count** — spellings where a reference
|
||||
either fell back to empty or was not recorded at all:
|
||||
- `\my-pkg\n::item` (escaped, newline-terminated) — **0 references
|
||||
recorded** (both segments; documented in Assumptions as a known
|
||||
disagreement).
|
||||
- `pkg :: item` (spaced) — **`item` not recorded** (only `pkg` is; the
|
||||
early-return in `bind_type_name` stops at the first segment whose
|
||||
derived span fails `exact_or_empty`, so everything after it, correct
|
||||
or not, is silently dropped rather than recorded empty).
|
||||
- `pkg /* c */ :: item` (comment-interrupted) — same as above, `item`
|
||||
dropped.
|
||||
- `pkg::` / `item` split across a line — same, `item` dropped.
|
||||
- `disable a . b . c` (spaced dotted) — **0 references recorded** (the
|
||||
whole chain, since `exact_or_empty` checks the joined `a.b.c` against
|
||||
the real, spaced span as one unit).
|
||||
- `disable fork` recorded 0 references, but this is pre-existing,
|
||||
unrelated behavior: `Binder::use_member` filters `is_keyword(name)` and
|
||||
`fork` is a keyword; confirmed by reading `bind/mod.rs:296-297` and by
|
||||
the fact the 0.44.0 baseline drops it identically (see below).
|
||||
|
||||
No other spelling in the battery fell back to empty or was dropped —
|
||||
in particular, both escaped-with-space-terminator (`\my-pkg ::\state-t`)
|
||||
and plain dotted `disable a.b.c` located **exactly**, which is new
|
||||
(see next point).
|
||||
|
||||
2. **0.44.0 baseline comparison (built in a `git worktree` at `v0.44.0`,
|
||||
removed after).** Ran the identical battery through the old
|
||||
`scan.rs`-based binder to see what changed, not just what the README
|
||||
claims:
|
||||
- **Improvements over 0.44.0** (old code got these wrong, new code gets
|
||||
them right): `\my-pkg ::\state-t` (old: both halves **empty** — the
|
||||
scanner's whole-word matcher never includes the escaped segment's
|
||||
trailing space, so it could never match `push_scope_segment`'s own
|
||||
join; new: both **exact**). Plain `disable a.b.c` (old: **empty** —
|
||||
`NameScanner::find` only ever returns single-token words, so a
|
||||
dotted name can never match as one word; new: **exact**). These are
|
||||
real, verified accuracy wins from moving off text-scanning.
|
||||
- **A narrower regression, corpus-neutral in practice**: for
|
||||
`pkg :: item`, `pkg /* c */ :: item`, and `pkg::`/`item` split across
|
||||
a line, the **0.44.0 scanner found both `pkg` and `item` at their
|
||||
correct positions** (whole-word search tokenizes past whitespace and
|
||||
comments, skipping them — see `scan.rs`'s `next_word`), while the new
|
||||
code drops `item` entirely once its derived offset (computed from the
|
||||
tightly-joined `name` string, which does not reflect arbitrary
|
||||
inter-segment whitespace/comments) no longer covers real source bytes.
|
||||
This never mislocates — `item` is simply absent from `s.references()`
|
||||
rather than present with a wrong span — but it is a real loss of
|
||||
find-and-locate capability for these three SV-legal (if unusual)
|
||||
spellings, and the old code additionally always recorded *some*
|
||||
`Reference` (even an empty-span one) where the new code, for the
|
||||
type-name path specifically, now sometimes records **nothing at all**.
|
||||
- The `disable`/type-name **modport-tail** shapes (`bus_if.mp`,
|
||||
`bus_if . mp` spaced) are **byte-for-byte identical** old vs new,
|
||||
confirming the modport tail's own pre-existing "skip if empty"
|
||||
convention was carried over unchanged, as the work log claims.
|
||||
|
||||
Finding (**MEDIUM**, doc/observability, not a correctness bug): the
|
||||
README's Assumptions section names only two "joins that can disagree"
|
||||
(an escaped segment's space, and the modport `.`). Empirically, *any*
|
||||
whitespace or comment between `::`-separated segments, and any spacing
|
||||
in a dotted `disable` target, also disagrees and silently drops the
|
||||
affected reference — and, specific to the binder's new early-return in
|
||||
`bind_type_name` (`crates/vlog_semantic/src/bind/decl.rs`), a segment
|
||||
past the first divergence is not merely mislocated-and-caught but never
|
||||
recorded as a `Reference` at all (0.44.0 always recorded one, with an
|
||||
empty span, via `NameScanner`'s always-recording callers). This means a
|
||||
future regression in the parser's own joining logic for these
|
||||
constructs would no longer surface as `unplaced > 0` in the corpus
|
||||
census (`crates/vlog_semantic/tests/corpus.rs`'s `covers()` only counts
|
||||
spans that exist; a dropped reference contributes nothing) — it would
|
||||
have to be caught by resolution-rate drift instead, which is a weaker
|
||||
signal. Recommend the Assumptions section name the fuller set of
|
||||
disagreeing spellings (whitespace/comments around any `::`/`.`, not
|
||||
only the escaped-segment case), and/or that `bind_type_name` record a
|
||||
trailing empty-span reference on early return the way the pre-round
|
||||
code did, so the census keeps its loud-failure property. Not a merge
|
||||
blocker: corpus-neutral (verified below), never mislocates, and the
|
||||
`disable`/type-name-with-whitespace spellings are rare in real RTL.
|
||||
|
||||
3. **Census pin.** `tools/guard.sh -- cargo test -p vlog_semantic --test
|
||||
corpus -- --nocapture`: **860 files, 27 486 symbols, 103 870
|
||||
references, 1 197 unresolved (1.15%), 0 unplaced** — matches the
|
||||
README's claim exactly (re-derived independently, not read off the
|
||||
README). Confirmed `covers()` (`tests/corpus.rs:69-80`) asserts
|
||||
`src[span] == name` for every non-empty-span reference and symbol
|
||||
uniformly (not type-references-only, but type references are now part
|
||||
of that population for the first time, per the round's stated purpose)
|
||||
and that an empty span is counted as "unplaced" rather than exempted —
|
||||
so the 0-unplaced result is a real assertion, not a vacuous one, over
|
||||
the actual corpus.
|
||||
|
||||
4. **`disable` spans + formatter/linter round-trip.** Confirmed via the
|
||||
parser's own new tests (`a_disable_names_its_target_with_a_span`,
|
||||
`spans.rs`) and independently via `lucisv format --stdout` /
|
||||
`lucisv check` on a hand-written `fork`/label/dotted-label file: output
|
||||
is idempotent (`format(format(x)) == format(x)`) and byte-identical to
|
||||
the `lucisv-0.44.0` baseline binary, and `lucisv check`'s
|
||||
`disable-statement` diagnostic is identical old vs new. Confirms the
|
||||
formatter/linter genuinely ignore the new span (as the work log
|
||||
claims) — output moved nowhere.
|
||||
|
||||
5. **Size pins.** `tools/guard.sh -- cargo test -p vlog_parser --lib
|
||||
size_pins`: `expr_stmt_and_stmt_kind_stay_within_their_pinned_sizes`
|
||||
passes (`Expr <= 96`, `StmtKind <= 392`, `Stmt <= 552`), confirming the
|
||||
`name_start: u32` design keeps every pin where §36's protocol left it.
|
||||
|
||||
6. **Server: definition/hover/typeDefinition/rename, in-tree and over
|
||||
opentitan.**
|
||||
- `cargo test -p lucisv_server`: the dev's two new `nav.rs` tests pass
|
||||
(`a_scoped_type_name_jumps_from_its_item_half`,
|
||||
`an_interface_port_type_jumps_from_its_head`), as part of the full
|
||||
3 814-test run below.
|
||||
- Added a temporary `#[test]` in `crates/lucisv_server/src/rename.rs`
|
||||
(removed before finishing; `git diff` on that file is empty now) that
|
||||
renames a package typedef `t` used as `pkg::t` from three files.
|
||||
Result: **all three files edited, each edit's range slicing to
|
||||
exactly `t`** (verified by slicing the edit's own `TextEdit.range`
|
||||
out of the source line) — never `pkg::t`, confirming attack item 4's
|
||||
rename requirement directly rather than by inspection.
|
||||
- `lucisv_server/src/type_def.rs` is untouched by this round (confirmed
|
||||
by `git diff --stat`) and still locates a type site by its own
|
||||
from-scratch window/`site()` walk, independent of
|
||||
`DataType::name_span`/`segments()` — exactly what the Handshakes
|
||||
section says. Verified it still answers correctly (see next point),
|
||||
so the "clean follow-up, not a regression" framing holds.
|
||||
- **Opentitan sweep, independently re-derived** (attack item 5): wrote
|
||||
a second position-picker (`<scratchpad>/defcmp/qa_positions.py`)
|
||||
targeting a **disjoint set of directories** from the dev's own script
|
||||
(`hw/ip/otp_ctrl/rtl`, `hw/ip/flash_ctrl/rtl`, `hw/ip/i2c/rtl`,
|
||||
`hw/ip/rv_dm/rtl`, `hw/ip/spi_host/rtl`, `hw/dv/sv/tl_agent`,
|
||||
`hw/dv/sv/csr_utils` — the dev used `aes`/`hmac`/`spi_device`/`uart`/
|
||||
`uart_agent`/`cip_lib`/`dv_lib`), picking 200 positions over 43
|
||||
files. Built the 0.44.0 `lucisv-server` in the same `v0.44.0`
|
||||
worktree used for the binder comparison, and ran both
|
||||
`textDocument/definition`, `textDocument/hover`, and
|
||||
`textDocument/typeDefinition` over all 200 positions with both
|
||||
servers (`<scratchpad>/defcmp/run.py`, `run_hover_typedef.py` — the
|
||||
latter is a QA-added twin of the dev's `run.py` adding hover/
|
||||
typeDefinition, since the original only asked `definition`).
|
||||
Results: **definition 200/200 identical (149 non-empty)**, **hover
|
||||
200/200 identical (149 non-empty)**, **typeDefinition 200/200
|
||||
identical (63 non-empty)**. `git -C ~/repo/opentitan status
|
||||
--porcelain` reported only the three pre-existing modified files
|
||||
after every run (before, during, and after — checked three times).
|
||||
|
||||
### Gates re-run independently (all guarded, all matched the dev's numbers)
|
||||
|
||||
| gate | result |
|
||||
|---|---|
|
||||
| `cargo clippy --all-targets` | clean (fully cached; 0 warnings/errors) |
|
||||
| `tools/guard.sh -- cargo test --workspace` | **3 814 passed** (3 815 with my scratch test counted, subtracted), **0 failed, 44 ignored** — exact match |
|
||||
| `tools/guard.sh -- tools/corpus_check.sh corpus` | 814/820 (99.3%), same six parse errors, 0 verification errors, 0 crashes; `git diff --stat -- corpus-check-results.tsv` empty (byte-identical) |
|
||||
| formatter byte-identity | wrote an independent diff script; `lucisv format --stdout` on all 860 corpus files vs `~/.cache/lucisv-baselines/lucisv-0.44.0`: **0 differ** |
|
||||
| census | 860 files / 27 486 symbols / 103 870 references / 1 197 unresolved / **0 unplaced** — re-derived, not copied |
|
||||
| opentitan definition/hover/typeDefinition sweep | 200/200/200 identical old vs new on an independently-chosen position set; opentitan `status --porcelain` clean (only the three pre-existing files) throughout |
|
||||
|
||||
No guard kill anywhere.
|
||||
|
||||
### Cleanup
|
||||
|
||||
Removed: `crates/vlog_semantic/tests/zz_qa_type_name_spans.rs` (scratch
|
||||
test), the temporary `#[test]` in `crates/lucisv_server/src/rename.rs`
|
||||
(confirmed `git diff` on that file is now empty), the `v0.44.0` scratch
|
||||
`git worktree` (`git worktree remove`, confirmed gone from
|
||||
`git worktree list`), and both scratch server storage directories. Left
|
||||
in the scratchpad (not the repo) for the lead's reference:
|
||||
`<scratchpad>/defcmp/qa_positions.py`, `qa_positions.json`,
|
||||
`qa_old.json`/`qa_new.json` (definition), `qa_old_ht.json`/`qa_new_ht.json`
|
||||
(hover/typeDefinition), `run_hover_typedef.py`, `byte_identity_check.sh`.
|
||||
|
||||
## Review
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-05 — lead.** Accepted with one rework; ships in 0.45.0 with §48
|
||||
and §49. The size ruling is the right one: a `u32` start in the padding
|
||||
`DataType` already had keeps `Expr` at 96 with no allocation on the common
|
||||
implicit case, and the derived end is verified against the source before
|
||||
any reference is recorded, so the "never mislocate" invariant held under
|
||||
QA's whole battery. QA's MEDIUM was fair — a dropped reference silences the
|
||||
census alarm the pin exists for — and is fixed by recording the empty-range
|
||||
placeholder instead of returning early; the README's list of disagreeing
|
||||
spellings is now the full one QA found. Two shapes the old scanner always
|
||||
failed (an escaped segment with a space terminator, a dotted `disable`
|
||||
target) are now exact. Census unchanged in every field, 0 of 860 corpus
|
||||
files differ, 200/200 opentitan answers identical for definition, hover and
|
||||
typeDefinition. The `type_def.rs` window lookup is filed as a follow-up in
|
||||
Handshakes, not a regression.
|
||||
@@ -62,16 +62,23 @@ enum Resolution {
|
||||
|
||||
### Deviations from the sketch in the task, and why
|
||||
|
||||
- **`analyze` takes `src` as well as the tree.** Most declarations in the AST
|
||||
keep their name as a plain `String` and carry a span only for the whole
|
||||
construct, so the *name's* range — the thing an editor highlights — is not
|
||||
recoverable from the tree alone. `scan.rs` finds it by scanning the
|
||||
construct's own source bytes (comments, strings and macro invocations
|
||||
skipped) inside a window narrowed by the sub-spans that *do* exist. The
|
||||
corpus test asserts `src[name_span] == name` for all 21 485 symbols and
|
||||
73 708 references it builds, so the scan is not a guess in practice. A
|
||||
Handshake request to put `name_span` on the AST is filed below; when it
|
||||
lands, `scan.rs` and this parameter go away.
|
||||
- **`analyze` takes `src` as well as the tree.** Originally because most
|
||||
declarations kept their name as a plain `String` inside a construct-wide
|
||||
span, so the *name's* range — the thing an editor highlights — was not
|
||||
recoverable from the tree at all; `scan.rs` found it by scanning the
|
||||
construct's own source bytes inside a window narrowed by the sub-spans that
|
||||
did exist. **Both halves of that are gone**: `name-spans` (2026-08-19) put
|
||||
`name_span` on every declaring node, `type-name-spans` (2026-09-05, TODO
|
||||
§47) put `DataType::name_span()`/`segments()` and `StmtKind::Disable`'s span
|
||||
on the last two, and `scan.rs` is deleted. `src` stays, in a different
|
||||
role: `Binder::exact_or_empty` checks a derived span against the source
|
||||
before a reference is recorded, so a name the source spells differently from
|
||||
the way the parser joined it (`bus_if . mp` written apart, an escaped
|
||||
segment terminated by a newline) costs the reference rather than
|
||||
mislocating it. Eleven call sites rely on that oracle. The corpus test still
|
||||
asserts `src[name_span] == name` for every symbol and reference it builds —
|
||||
27 486 and 103 870 as of 2026-09-05, type-name references now among them,
|
||||
0 unplaced.
|
||||
- **`Reference.resolution: Resolution` instead of `resolved:
|
||||
Option<SymbolId>`.** The task asked for both an `Option<SymbolId>` and an
|
||||
`ExternalCandidate` state carrying the import path; one enum says that once.
|
||||
@@ -280,15 +287,21 @@ region | generate block | for-generate header | for/foreach statement`.
|
||||
- `src` passed to `analyze` is the exact text the tree was parsed from. Spans
|
||||
index into it; a mismatched string yields wrong name spans, not a panic
|
||||
(every slice is bounds-checked and clamped).
|
||||
- A construct's keyword is written before its name (`module m`, `function
|
||||
- ~~A construct's keyword is written before its name (`module m`, `function
|
||||
automatic int f`), and the name is a plain identifier. Where a type name and
|
||||
the declared name are the same token text (`function foo_t foo_t;`) the scan
|
||||
can pick the first of the two; nothing in the corpus does this.
|
||||
can pick the first of the two; nothing in the corpus does this.~~ Retired
|
||||
2026-09-05 by `type-name-spans`: nothing here scans for a name any more, so
|
||||
no assumption about where one is written is left to make.
|
||||
- The parser bounds nesting depth (`MAX_NESTING_DEPTH`, TODO.md §1), so the
|
||||
recursive walk here inherits a bounded stack and needs no depth counter of
|
||||
its own.
|
||||
- Identifiers are ASCII in practice; the scanner treats non-ASCII bytes as
|
||||
non-identifier bytes and never slices inside a multi-byte character.
|
||||
- A span derived rather than received is checked against the source before it
|
||||
becomes a reference (`Binder::exact_or_empty`). What is derived is small and
|
||||
named: a `Member`/`Scope` tail, a class `extends` head and tail, an instance
|
||||
module name, an end label, the `::`/`.` segments of a type name, and a
|
||||
`disable` target. Anything that does not slice back to the name costs the
|
||||
reference; nothing is ever recorded at a guessed position.
|
||||
|
||||
## Handshakes
|
||||
|
||||
@@ -332,6 +345,11 @@ feature, and the crate works without it):
|
||||
`docs/features/name-spans/README.md`.
|
||||
2. **A span for `DataType`** (and for `ExprKind::Cast::ty`), so a type
|
||||
reference does not need a window computed from its neighbours' spans.
|
||||
**Delivered 2026-09-05 by `type-name-spans`** (TODO §47) — `DataType`
|
||||
carries `name_span()` and `segments()`, `StmtKind::Disable` carries its
|
||||
target's span, `bind_data_type` lost its `window` parameter, and
|
||||
`crates/vlog_semantic/src/scan.rs` is deleted; see
|
||||
`docs/features/type-name-spans/README.md`.
|
||||
3. Nice to have, much smaller: the byte range of `Member`/`Scope` tails, which
|
||||
is today derived as `span.end - name.len()`.
|
||||
|
||||
@@ -433,6 +451,20 @@ anywhere, and under 3 % unresolved on cleanly-parsed files.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-09-05 — type-name-spans (TODO.md §47).** `scan.rs` deleted, `mod scan;`
|
||||
with it: the parser now carries `DataType::name_span()` /
|
||||
`DataType::segments()` and `StmtKind::Disable`'s span, so the two remaining
|
||||
scan callers read them instead. `bind_data_type` lost its `window` parameter
|
||||
(and with it the window computations at ten call sites, plus the now-unused
|
||||
`span` parameters of `bind_data_decl`, `bind_declarators` and
|
||||
`bind_enum_body`) and gained `bind_type_name`, which walks the segments and
|
||||
records the head as `Target::Unit`/`Target::Type` and each following segment
|
||||
as a member of the one before it — so a three-segment `a::b::c`, which used to
|
||||
bind an unlocatable `b::c`, binds all three. Every segment goes through
|
||||
`exact_or_empty` first. Corpus census byte-identical before and after: 860
|
||||
files, 27 486 symbols, 103 870 references, 1 197 unresolved, 0 unplaced.
|
||||
Details in `docs/features/type-name-spans/README.md`.
|
||||
|
||||
**2026-08-27 — indexed navigation.** `Semantics` now builds compact sorted
|
||||
`(TextRange, SymbolId/ReferenceId)` position tables with the analysis.
|
||||
`symbol_at`, `reference_at` and `reference_id_at` binary-search those tables;
|
||||
|
||||
+122
-167
@@ -1,195 +1,150 @@
|
||||
# Repository analysis
|
||||
|
||||
Audited 2026-09-04 against HEAD `d5abf81`. The manifest still declares
|
||||
**v0.41.0**; HEAD includes the accepted parser-skips work intended for
|
||||
v0.42.0. This is a source and documentation audit, not a new performance or
|
||||
full language-conformance measurement.
|
||||
Refreshed **2026-09-05**. Latest release: **v0.44.0** (`66f3898`). This
|
||||
review uses committed snapshot **`9ef1058`**, which also includes accepted
|
||||
type-name-spans and package-reexports work intended for v0.45.0. The active
|
||||
hierarchical-tail changes are described separately; their QA is still open.
|
||||
|
||||
## Assessment
|
||||
## Assessment and current status
|
||||
|
||||
lucisv is a complete developer-tool stack, with eight Rust crates (six
|
||||
libraries and two binaries), a VS Code extension, Neovim/Vim configuration,
|
||||
release/corpus scripts, and an Astro/Starlight documentation site. Its strongest
|
||||
architectural choices are shared language engines, runtime formatter checks,
|
||||
conservative semantic resolution, and a single owner for mutable LSP state.
|
||||
lucisv remains an eight-crate toolchain: six reusable Rust libraries, CLI and
|
||||
LSP binaries, editor integration, corpus/release tools, and a static docs site.
|
||||
The architecture still separates syntax, formatting, semantics, linting,
|
||||
refactoring, and project inputs. The three issues raised by the September 4
|
||||
audit have been fixed; they should no longer be treated as open priorities.
|
||||
|
||||
The most consequential remaining issues found in this audit are coordination
|
||||
between atomic writers and disagreement between project-file and editor lint
|
||||
selection. The test suite passes, but neither result establishes those contracts:
|
||||
the atomic tests exercise sequential replacement, and editor rule-selection
|
||||
tests exercise client settings. Documentation had also fallen behind the
|
||||
recent implementation rounds.
|
||||
| Change | Status at this refresh | Implementation and contract |
|
||||
|---|---|---|
|
||||
| External waiver files | Released in v0.42.0 | `ExternalWaivers`, `WaiverUse`, and `lint_with`; CLI, project config and editor paths add together; inline/external suppression is a union; unused external waivers are reported only after a complete CLI run |
|
||||
| Rival conditional headers and net-delay position | Released in v0.42.0 | Split units stay verbatim; delays print before or after the type according to their original position |
|
||||
| Atomic-write coordination | Released in v0.43.0 | Exclusive per-operation temp files, permissions applied before bytes, CLI dedup by canonical path; separate processes remain last-writer-wins |
|
||||
| Project/editor lint agreement | Released in v0.43.0 | Non-empty editor select/ignore lists override project lists independently; rejected project entries log once with file and line; valid entries continue to apply |
|
||||
| Cycle-aware walks and net-delay comment slots | Released in v0.43.0 | Directory identity prevents cycles; comments around a delay's `#` are preserved |
|
||||
| Walk warnings, editor rule-name warnings, aggregate overrides and delay-list comments | Released in v0.44.0 | Recoverable walk problems warn and continue; editor name typos log once; aggregate override expressions and delay-list comment slots are handled |
|
||||
| didOpen cost | Released in v0.44.0 | `undriven-net` asks the workspace mention oracle after local guards; findings and synchronous request ordering stay unchanged |
|
||||
| Type-name spans | Committed, accepted for v0.45.0 | `DataType::name_span()` / `segments()` and disable-target spans replace semantic name scanning; `scan.rs` is deleted |
|
||||
| Package re-exports | Committed, accepted for v0.45.0 | Export name halves are references; the shared member walk follows cycle-guarded re-export edges; persisted facts gain `RX`, codec **18** |
|
||||
| Hierarchical tails | **Working tree, QA pending** | Proposed codec **19**, tagged member/reference surfaces, instance-tail resolution and completion, and cross-file rename updates |
|
||||
|
||||
The current source of truth for feature acceptance is each feature's QA/review
|
||||
log and [TODO.md](../TODO.md). The [topology](topo.md) records the interfaces
|
||||
that future changes must preserve. A missing documented edge is not proof that
|
||||
two edits have disjoint ownership.
|
||||
|
||||
## Repository map
|
||||
|
||||
| Location | Responsibility and starting point |
|
||||
|---|---|
|
||||
| `crates/vlog_parser` | Lexer and trivia, strict/tolerant recursive descent, AST and source coordinates; start at `src/lib.rs`, then `parser/` and `ast/` |
|
||||
| `crates/vlog_formatter` | AST → document IR → printer, alignment, fences, ranges, token equivalence and convergence; start at `src/format/mod.rs` and `src/verify.rs` |
|
||||
| `crates/vlog_semantic` | File binding/resolution and workspace facts; start at `src/lib.rs`, `bind/`, `workspace/`, and `facts.rs` |
|
||||
| `crates/vlog_linter` | 73-rule registry, lazy analysis, options, severity, inline waivers and fixes; start at `src/lib.rs`, `context.rs`, and `registry.rs` |
|
||||
| `crates/vlog_refactor` | Rename/references, port edits and instance plans; shared `src/scope.rs`, whole-edit checks in `check.rs` |
|
||||
| `crates/lucisv_core` | Config, filelists, walking, format cache and atomic replacement; no language-engine dependency |
|
||||
| `crates/lucisv` | CLI argument handling, discovery, worker pool, reports and writes; `src/main.rs`, `args.rs`, `lint.rs` |
|
||||
| `crates/lucisv_server` | Synchronous LSP transport, workspace state, overlays, scans and capability handlers; `src/main.rs`, `server/`, `state.rs` |
|
||||
| `editors/` | VS Code client/grammar/settings/hierarchy UI, plus configuration examples for other editors |
|
||||
| `tools/`, `scripts/`, `.gitea/workflows/` | Resource guard, corpus evaluation, artifact audits and release automation |
|
||||
| `docs/features/` | Feature-specific contracts, implementation history, QA and review; 135 READMEs at audit time |
|
||||
| `crates/vlog_parser` | Lexer/trivia, strict and tolerant recursive descent, AST/spans; `src/lib.rs`, `parser/`, `ast/` |
|
||||
| `crates/vlog_formatter` | AST → document IR → printer, alignment, fences/ranges, equivalence and convergence; `format/mod.rs`, `verify.rs` |
|
||||
| `crates/vlog_semantic` | File binding/resolution, workspace facts and member lookup; `bind/`, `resolve.rs`, `workspace/`, `facts.rs`; committed `workspace/reexport.rs`, active `workspace/hierarchy.rs` |
|
||||
| `crates/vlog_linter` | 73-rule registry, lazy semantics, options, severities, inline/external waivers and fixes; `lib.rs`, `context.rs`, `registry.rs`, `waiver_file.rs` |
|
||||
| `crates/vlog_refactor` | Rename/references, port edits, instance plans; shared `scope.rs`, whole-edit verification in `check.rs` |
|
||||
| `crates/lucisv_core` | Config, filelists, cycle-aware walks and warning channel, format cache, atomic replacement; no language-engine dependency |
|
||||
| `crates/lucisv` | Argument handling, input discovery/dedup, worker pool, reports and source writes |
|
||||
| `crates/lucisv_server` | Ordered LSP loop and workspace overlays; `server/`, `state.rs`, capability handlers; project lint validation/logging in `lint/project.rs` |
|
||||
| `editors/` | VS Code client/grammar/settings/hierarchy UI and configuration for other editors |
|
||||
| `tools/`, `scripts/`, `.gitea/workflows/` | Resource guard, corpus evaluation, artifact checks and releases |
|
||||
| `docs/features/` | Implementation contracts, dated measurements, QA and acceptance records |
|
||||
| `docs/site/` | User-facing static documentation and tracked generated output |
|
||||
|
||||
[topo.md](topo.md) gives dependency directions, recent cross-crate contracts,
|
||||
shared interfaces, and numbered open handshakes. The manifests are authoritative
|
||||
for crate edges; an absent documented edge alone does not prove two edits safe
|
||||
to perform concurrently.
|
||||
The crate dependency graph is unchanged. Parser and core have no dependencies;
|
||||
formatter and semantics each depend on parser; linter and refactor depend on
|
||||
parser and semantics. The linter depends on the formatter only in tests.
|
||||
The CLI composes core/parser/formatter/linter; the server composes all six
|
||||
libraries. External Rust dependencies stay in the CLI worker pool and server
|
||||
LSP/JSON stack.
|
||||
|
||||
## Runtime behavior and limits
|
||||
## Runtime contracts worth preserving
|
||||
|
||||
**Formatting.** `format_source` strictly parses input, renders a document tree,
|
||||
re-lexes both versions and compares normalized tokens (including comments),
|
||||
then parses/formats the output again and checks convergence. A failed check
|
||||
returns an error instead of a candidate string. The CLI leaves the affected
|
||||
source file alone. This protects lexical fidelity and stable layout; it does
|
||||
not elaborate SystemVerilog or prove hardware equivalence. Fenced text still
|
||||
has to parse. Ranges select items; fences can additionally protect statements
|
||||
and class members.
|
||||
**Formatting:** strict parse, layout, normalized token comparison (including
|
||||
comments), then a second parse/format and convergence check. Failure returns
|
||||
an error, not a candidate output. These are lexical/layout checks, not design
|
||||
elaboration or proof of hardware equivalence. Fenced text must still parse;
|
||||
ranges select items, while fences also protect statement and class scopes.
|
||||
|
||||
**Linting.** `ParsedSource` shares a tokenization and tolerant parse, and
|
||||
`LintContext` computes semantics lazily. Rules consume text, tokens, AST, and
|
||||
optional project facts; malformed AST elements remain opaque. Inline waivers
|
||||
filter findings, and severity is stamped centrally. The CLI/server filter
|
||||
fixes through the formatter's fence API: `apply_fixes` alone does not provide
|
||||
that protection. `always-comb` offers an unsafe fix; editor actions offer only
|
||||
safe fixes.
|
||||
**Linting:** one prepared tokenization/tolerant parse feeds rules and lazy
|
||||
semantics. Malformed AST elements remain opaque. Front ends call `lint_with`
|
||||
when applying external waivers and filter automatic edits through the formatter's
|
||||
fence API; `apply_fixes` alone does not protect fenced bytes. Editor actions
|
||||
continue to offer only safe fixes. The mention oracle is a pure predicate;
|
||||
asking it after cheap local guards avoids repeated workspace scans.
|
||||
|
||||
**Refactoring and editor state.** Refactors use resolved source spans and check
|
||||
the whole edit; source selectors must remain supersets of every file an engine
|
||||
could edit or refuse over. The LSP loop owns workspace mutation, open documents
|
||||
overlay disk facts, and stepped scans publish related index/include/completion
|
||||
state together. Facts persist under `FACTS_FORMAT = 17`. Lazy port code actions
|
||||
compute their edits on selection for capable clients. Recorded UTF-16 positions
|
||||
avoid reads for closed-file file-scope definitions; members and open buffers
|
||||
still use text-based locations.
|
||||
**Editor and refactors:** one loop owns workspace mutation; buffers overlay
|
||||
disk facts and scans publish related index/include/completion state together.
|
||||
Lazy port actions defer edits until selection. File-scope definition positions
|
||||
can come from the index; members and open buffers use text-based positions.
|
||||
Refactor source selectors must include every file an engine might edit or
|
||||
refuse over, even when completion or navigation can answer from fewer files.
|
||||
|
||||
**Intentional scope.** Neither parser mode performs cross-file macro expansion
|
||||
or compiler elaboration. Missing definitions outside an index scope can mean
|
||||
missing hints or conservative lint silence. Rootless indexing never climbs;
|
||||
with depth 0 it reads siblings flat, while positive depth walks descendants.
|
||||
The published 814/820 frozen-corpus result is historical feature QA evidence,
|
||||
not a new corpus sweep performed by this audit. Performance reports under
|
||||
`docs/performance*.md` and `docs/perf/` likewise remain dated measurements.
|
||||
**New committed semantic contracts:** a type-name segment is derived from AST
|
||||
span data and verified against the source by `Binder::exact_or_empty`. The
|
||||
source parameter to analysis remains necessary even though `scan.rs` is gone.
|
||||
A package re-export records reference edges without adding a local import.
|
||||
`export *::*` expands the package's imports into re-export facts; member lookup
|
||||
follows those edges with cycle guards. Cache codec 18 prevents older stores
|
||||
from silently omitting this information.
|
||||
|
||||
## Findings and follow-up priorities
|
||||
## Active work and remaining limits
|
||||
|
||||
### 1. Coordinate writes to a shared target
|
||||
TODO §49 owns hierarchical-tail resolution. At this refresh, its working tree
|
||||
adds `Surface::{Connection, Hierarchical}`, a second member table, surface tags
|
||||
on persisted declarations/references, and codec 19. Connection completion and
|
||||
port propagation retain the existing ports/parameters view; paths behind an
|
||||
instance can additionally reach internal nets, variables and nested instances.
|
||||
Member completion and rename fan-out are part of the same contract. The feature
|
||||
README reports development checks; independent QA is still pending, so topology
|
||||
handshake 23 remains open. No working-tree API is treated as released here.
|
||||
|
||||
Evidence: [atomic.rs](../crates/lucisv_core/src/atomic.rs) canonicalizes the
|
||||
target, then derives a temp name from the target filename and process ID.
|
||||
`fs::write` opens that predictable path without exclusive creation.
|
||||
[CLI dedup](../crates/lucisv/src/main.rs) folds lexical path components but
|
||||
intentionally leaves symlinks unresolved. Two rayon jobs reaching one target
|
||||
through different spellings can therefore share a temporary file.
|
||||
Remaining constraints include generate-block-scoped hierarchical paths,
|
||||
cross-file macro expansion, and compiler elaboration. Package re-export support
|
||||
does not bind a DPI-export function name; that residue is now separated into
|
||||
topology handshake 31. Shared path normalization (1) and structured formatter
|
||||
error output (11) also remain open. Inline aggregate override arguments are
|
||||
supported, but instance templates still omit a type default written across
|
||||
multiple lines. These are narrower limits than the old audit's unresolved
|
||||
entries 2, 16 and 17 suggested.
|
||||
|
||||
A disposable probe compiled the actual `atomic.rs` and used two barrier-started
|
||||
threads per round to write different 1 MiB buffers to one target. Across
|
||||
**100 rounds / 200 calls, 100 writes failed**. The final file in every round
|
||||
was a complete one-writer buffer; **no mixed final bytes were observed**. This
|
||||
reproduces the helper's collision, not an end-to-end formatter corruption.
|
||||
The probe used only `/tmp` files and ran under the resource guard.
|
||||
## Historical audit findings and evidence
|
||||
|
||||
Recommended follow-up: exclusive, unique per-operation temp files; coordinate
|
||||
or deduplicate writes by target identity; add a concurrent alias regression.
|
||||
The existing temp-and-rename helper is useful for sequential replacement, but
|
||||
its tests do not justify a same-target concurrency guarantee. Tracked as
|
||||
[topology handshake 26](topo.md).
|
||||
The **2026-09-04** audit reproduced a temp-file collision at the old revision:
|
||||
100 errors in 200 concurrent helper calls, with no mixed final bytes observed.
|
||||
That is historical evidence, not a current failure. The
|
||||
[atomic-write-coordination QA](features/atomic-write-coordination/README.md)
|
||||
records the committed regression test and successful 2/4/8-thread checks.
|
||||
[Lint-config-contract](features/lint-config-contract/README.md) records CLI/LSP
|
||||
selection parity and once-only logging checks.
|
||||
[Walk-cycles](features/walk-cycles/README.md) and
|
||||
[small-items-4](features/small-items-4/README.md) record cycle handling, recoverable
|
||||
warnings and the closed delay-comment gaps.
|
||||
|
||||
**Fixed by TODO §41 (0.43.0, 2026-09-05):** the probe now runs as
|
||||
`atomic::tests::two_threads_writing_one_target_never_collide` and reports
|
||||
0 write errors in 200 calls (QA re-ran it at 4 and 8 threads: 0 in 400 and
|
||||
0 in 800); the symlink alias closes as `cli::a_symlink_and_its_target_are_one_file`.
|
||||
Two processes writing one target remain last-writer-wins, stated in
|
||||
`atomic.rs`. See `docs/features/atomic-write-coordination/README.md`.
|
||||
[Performance take 3](performance_take3.md) measures v0.43.0 and predates the
|
||||
v0.44.0 fix. The later [didOpen-cost report](features/didopen-cost/README.md)
|
||||
records 1,742 ms → 117 ms on the large pinmux file at workspace scope, with
|
||||
unchanged diagnostics. These are feature measurements on one machine, not
|
||||
fresh measurements by this documentation refresh. The 814/820 frozen-corpus
|
||||
result likewise remains attributed to feature QA; no corpus or OpenTitan sweep
|
||||
is part of this refresh.
|
||||
|
||||
### 2. Define a consistent project lint configuration contract
|
||||
## Validation of this refresh
|
||||
|
||||
Evidence: [server linting](../crates/lucisv_server/src/lint.rs) selects rules in
|
||||
`enabled_rules` from `ClientSettings` only. Its `configured` function discovers
|
||||
`lucisv.toml` but reads `lint_options` and line length, not `lint_select` or
|
||||
`lint_ignore`. In contrast, [CLI linting](../crates/lucisv/src/lint.rs) consumes
|
||||
project selection. The server also discards invalid project option entries
|
||||
with `let _ = options.set_raw(...)`; only invalid *editor* option settings
|
||||
receive the corresponding per-entry log.
|
||||
|
||||
**Fixed by TODO §42 (0.43.0, 2026-09-05):** `enabled_rules` now takes the
|
||||
project's selection beside the editor's and picks the editor's list when it
|
||||
is non-empty, the project's otherwise, key by key — the CLI's `pick` applied
|
||||
to the editor. Rejected project entries are logged once per (configuration
|
||||
file, entry) as `<file>:<line>: <message>`, the wording `lucisv check` fails
|
||||
with, and the buffer is still linted with the entry dropped. Pinned by
|
||||
`lint::project`'s four-way table test and by three wire-level tests in
|
||||
`crates/lucisv_server/tests/e2e.rs`, one of which asserts the CLI's and the
|
||||
server's rule lists equal for three configurations. See
|
||||
`docs/features/lint-config-contract/README.md`.
|
||||
|
||||
### 3. Keep traversal and semantic gaps explicit
|
||||
|
||||
The shared [directory walker](../crates/lucisv_core/src/walk.rs) recursively
|
||||
follows `Path::is_dir()` with no visited-directory set. Symlink cycles remain
|
||||
an existing open issue (topology handshake 8); eventual filesystem refusal is
|
||||
not an explicit traversal budget or cycle policy. Prioritize a deliberate
|
||||
cycle policy before broadening traversal.
|
||||
|
||||
Other concrete open contracts include missing type spans (handshake 2),
|
||||
package re-export resolution (16), inline aggregate type arguments (17), and
|
||||
cross-file rename of an internal module net (23). The parser-skips regression
|
||||
suite also retains a refusal for comments immediately before a net-delay `#`
|
||||
(27). These limitations should remain visible when widening grammar or index
|
||||
coverage; formatter verification must continue to reject unsupported output.
|
||||
|
||||
**Fixed by TODO §43 (0.43.0, 2026-09-05):** the walker enters each directory
|
||||
once by identity (`(dev, ino)` on unix, the canonical path elsewhere); a
|
||||
symlink cycle terminates and a doubly reachable file is reported once. The
|
||||
"no traversal budget" ruling was the lead's: identity is the policy. The
|
||||
net-delay comment refusal (handshake 27) is closed by `NetDelay`'s comment
|
||||
slots. Still open from this finding: handshakes 2, 16, 17, 23, and the new 30
|
||||
(an unreadable directory aborts the walk). See
|
||||
`docs/features/walk-cycles/README.md`.
|
||||
|
||||
## Documentation changes from this audit
|
||||
|
||||
- Expanded the README's architecture to cover all eight crates and documented
|
||||
the runtime checks, actual indexing behavior, documentation entry points,
|
||||
and guarded verification commands.
|
||||
- Updated topology facts to codec 17, corrected moved module paths, recorded
|
||||
recent recovery/lint/fence/atomic/LSP contracts, and closed the stale `program`
|
||||
linked-editing request using the existing module-shaped AST path.
|
||||
- Updated site configuration, formatter/linter guides, CLI, language tools,
|
||||
architecture and API navigation for current behavior. The API index now
|
||||
explicitly defers to rustdoc for exhaustive signatures and fields.
|
||||
- Removed the stale `0.9.0` product version from site structured metadata;
|
||||
release versions remain owned by the workspace/release files.
|
||||
|
||||
The parser-skips changes were already present when the audit started and were
|
||||
committed by another workflow during the audit. Their QA log now records PASS;
|
||||
the topology reflects that final state. This audit made no Rust implementation
|
||||
changes and did not modify their feature log or backlog checkboxes.
|
||||
|
||||
## Validation
|
||||
Checks ran against an isolated archive of committed `9ef1058`, with a separate
|
||||
build directory and the repository resource guard. This avoids the live agents'
|
||||
target directory and does not certify their uncommitted changes.
|
||||
|
||||
- `cargo fmt --all -- --check`: passed.
|
||||
- `cargo clippy --workspace --all-targets -- -D warnings`: passed.
|
||||
- `tools/guard.sh -- cargo test --workspace`: **3,745 passed, 0 failed,
|
||||
44 ignored**, summed across 48 test/doc-test harnesses. Counts include the
|
||||
post-v0.41.0 parser-skip cases and one passing doctest; ignored measurement
|
||||
tests were not enabled.
|
||||
- Documentation build: `ASTRO_TELEMETRY_DISABLED=1 npm run build` in
|
||||
`docs/site` passed; 13 pages, Pagefind index and sitemaps generated.
|
||||
- Generated-site verification: 817 local links, assets and anchors checked,
|
||||
zero failures; relative links in the repository documentation checked.
|
||||
`git diff --check` passed.
|
||||
- Atomic-write probe: collision reproduced as described above, no repository
|
||||
source files written.
|
||||
- `cargo clippy --offline --workspace --all-targets -- -D warnings`: passed.
|
||||
- `cargo test --offline --workspace`: **3,829 passed, 0 failed, 44 ignored**,
|
||||
across 49 harnesses, under `tools/guard.sh`. The archive did not include the
|
||||
ignored/untracked corpus checkout, and ignored measurement tests were not run.
|
||||
- `ASTRO_TELEMETRY_DISABLED=1 npm run build` in `docs/site`: passed;
|
||||
13 pages, Pagefind search and sitemaps rebuilt.
|
||||
- Generated-site validation: **820** local links, assets and anchors checked,
|
||||
zero errors. Relative links in the root analysis/topology/coverage docs also
|
||||
passed. `git diff --check` passed for these documentation changes.
|
||||
|
||||
The first test attempt was stopped because sandboxed `ps` prevented the guard
|
||||
from measuring memory; the successful rerun used an approved environment where
|
||||
monitoring worked. No corpus sweep, OpenTitan sweep, ignored benchmark run,
|
||||
release packaging, or external publishing was performed by this audit.
|
||||
The previous audit's 3,745 passing tests describe its September 4 snapshot;
|
||||
they are not reused as the test result for this revision. This refresh changes
|
||||
documentation only and leaves feature QA logs and backlog checkboxes to their
|
||||
owners. No corpus/OpenTitan sweep, new benchmark, release packaging or
|
||||
publishing was performed.
|
||||
+1
-1
@@ -116,4 +116,4 @@ to the lucisv log whether the file was named by the editor setting or by
|
||||
are reported under <code dir="auto">unused-waiver</code> at their line of the waiver file, by
|
||||
<code dir="auto">lucisv check</code> only and only after the whole run.</p>
|
||||
<p>See the <a href="/reference/rules/">complete rule reference</a>.</p>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/guides/linter.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T05:03:07.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/guides/formatter/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Formatter</span></span></a><a href="/guides/editors/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Editors & LSP</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/guides/linter.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T06:45:48.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/guides/formatter/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Formatter</span></span></a><a href="/guides/editors/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Editors & LSP</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1
-1
@@ -1 +1 @@
|
||||
{"version":"1.5.2","languages":{"en":{"hash":"en_e88e94fa5c","wasm":"en","page_count":12}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]}
|
||||
{"version":"1.5.2","languages":{"en":{"hash":"en_bd6347a7d0","wasm":"en","page_count":12}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]}
|
||||
Binary file not shown.
Binary file not shown.
+17
-4
@@ -70,7 +70,7 @@
|
||||
})();
|
||||
</script></sl-sidebar-state-persist><div class="md:sl-hidden"><div class="mobile-preferences sl-flex astro-b5gddk54"><div class="social-icons astro-b5gddk54"><a href="https://git.luci.ooo/lucio/verilogrustformatter" rel="me" class="sl-flex astro-cg55etiy"><span class="sr-only astro-cg55etiy">Source repository</span><svg aria-hidden="true" class="astro-cg55etiy astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M12 .3a12 12 0 0 0-3.8 23.38c.6.12.83-.26.83-.57L9 21.07c-3.34.72-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.08-.74.09-.73.09-.73 1.2.09 1.83 1.24 1.83 1.24 1.08 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.67-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.14-.3-.54-1.52.1-3.18 0 0 1-.32 3.3 1.23a11.5 11.5 0 0 1 6 0c2.28-1.55 3.29-1.23 3.29-1.23.64 1.66.24 2.88.12 3.18a4.65 4.65 0 0 1 1.23 3.22c0 4.61-2.8 5.63-5.48 5.92.42.36.81 1.1.81 2.22l-.01 3.29c0 .31.2.69.82.57A12 12 0 0 0 12 .3Z"/></svg></a></div><starlight-theme-select><label style="--sl-select-width: 6.25em" class="astro-r2p65idu"><span class="sr-only astro-r2p65idu">Select theme</span><svg aria-hidden="true" class="icon label-icon astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M21 14h-1V7a3 3 0 0 0-3-3H7a3 3 0 0 0-3 3v7H3a1 1 0 0 0-1 1v2a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-2a1 1 0 0 0-1-1ZM6 7a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v7H6V7Zm14 10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-1h16v1Z"/></svg><select autocomplete="off" class="astro-r2p65idu"><option value="dark" class="astro-r2p65idu">Dark</option><option value="light" class="astro-r2p65idu">Light</option><option value="auto" selected class="astro-r2p65idu">Auto</option></select><svg aria-hidden="true" class="icon caret astro-r2p65idu astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1em;"><path d="M17 9.17a1 1 0 0 0-1.41 0L12 12.71 8.46 9.17a1 1 0 1 0-1.41 1.42l4.24 4.24a1.002 1.002 0 0 0 1.42 0L17 10.59a1.002 1.002 0 0 0 0-1.42Z"/></svg></label></starlight-theme-select><script>
|
||||
StarlightThemeProvider.updatePickers();
|
||||
</script></div></div></div></div></nav><div class="main-frame astro-gqpr5s5a"><script type="module">var e=document.getElementById(`starlight__sidebar`),t=e?.querySelector(`sl-sidebar-state-persist`),n=`sl-sidebar-state`,r=()=>{let r=[],i=t?.dataset.hash||``;try{let e=sessionStorage.getItem(n),t=JSON.parse(e||`{}`);Array.isArray(t.open)&&t.hash===i&&(r=t.open)}catch{}return{hash:i,open:r,scroll:e?.scrollTop||0}},i=e=>{try{sessionStorage.setItem(n,JSON.stringify(e))}catch{}},a=()=>i(r()),o=(e,t)=>{let n=r();n.open[t]=e,i(n)};t?.addEventListener(`click`,e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`summary`)?.closest(`details`);if(!t)return;let n=t.querySelector(`sl-sidebar-restore`),r=parseInt(n?.dataset.index||``);isNaN(r)||o(!t.open,r)}),addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&a()});</script><div class="lg:sl-flex astro-abfeecmu"><aside class="right-sidebar-container print:hidden astro-abfeecmu"><div class="right-sidebar astro-abfeecmu"><div class="lg:sl-hidden astro-q5mffni3"><mobile-starlight-toc data-min-h="2" data-max-h="3" class="astro-5ulgm6bh"><nav aria-labelledby="starlight__on-this-page--mobile" class="astro-5ulgm6bh"><details id="starlight__mobile-toc" class="astro-5ulgm6bh"><summary id="starlight__on-this-page--mobile" class="sl-flex astro-5ulgm6bh"><span class="toggle sl-flex astro-5ulgm6bh">On this page<svg aria-hidden="true" class="caret astro-5ulgm6bh astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></span><span class="display-current astro-5ulgm6bh"></span></summary><div class="dropdown astro-5ulgm6bh"><ul class="isMobile astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#data-flow" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Data flow</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#execution-paths-and-ownership" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Execution paths and ownership</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#design-invariants" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Design invariants</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#release-surface" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Release surface</span></a></li></ul></div></details></nav></mobile-starlight-toc><script type="module" src="/_astro/MobileTableOfContents.astro_astro_type_script_index_0_lang.BcSo_yiZ.js"></script></div><div class="right-sidebar-panel sl-hidden lg:sl-block astro-q5mffni3"><div class="sl-container astro-q5mffni3"><starlight-toc data-min-h="2" data-max-h="3"><nav aria-labelledby="starlight__on-this-page"><h2 id="starlight__on-this-page">On this page</h2><ul class="astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#data-flow" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Data flow</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#execution-paths-and-ownership" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Execution paths and ownership</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#design-invariants" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Design invariants</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#release-surface" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Release surface</span></a></li></ul></nav></starlight-toc><script type="module" src="/_astro/TableOfContents.astro_astro_type_script_index_0_lang.Csloo1VZ.js"></script></div></div></div></aside><div class="main-pane astro-abfeecmu"><main data-pagefind-body class="astro-vdxcvpsm" lang="en" dir="ltr"><div class="content-panel astro-oil7k7jf"><div class="sl-container astro-oil7k7jf"><h1 id="_top" class="astro-2sm4b3ln">Architecture</h1></div></div><div class="content-panel astro-oil7k7jf"><div class="sl-container astro-oil7k7jf"><div class="sl-markdown-content"><p>lucisv follows the same separation of concerns that makes ruff fast and maintainable: syntax and source fidelity at the bottom,Line truncated
|
||||
</script></div></div></div></div></nav><div class="main-frame astro-gqpr5s5a"><script type="module">var e=document.getElementById(`starlight__sidebar`),t=e?.querySelector(`sl-sidebar-state-persist`),n=`sl-sidebar-state`,r=()=>{let r=[],i=t?.dataset.hash||``;try{let e=sessionStorage.getItem(n),t=JSON.parse(e||`{}`);Array.isArray(t.open)&&t.hash===i&&(r=t.open)}catch{}return{hash:i,open:r,scroll:e?.scrollTop||0}},i=e=>{try{sessionStorage.setItem(n,JSON.stringify(e))}catch{}},a=()=>i(r()),o=(e,t)=>{let n=r();n.open[t]=e,i(n)};t?.addEventListener(`click`,e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`summary`)?.closest(`details`);if(!t)return;let n=t.querySelector(`sl-sidebar-restore`),r=parseInt(n?.dataset.index||``);isNaN(r)||o(!t.open,r)}),addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&a()});</script><div class="lg:sl-flex astro-abfeecmu"><aside class="right-sidebar-container print:hidden astro-abfeecmu"><div class="right-sidebar astro-abfeecmu"><div class="lg:sl-hidden astro-q5mffni3"><mobile-starlight-toc data-min-h="2" data-max-h="3" class="astro-5ulgm6bh"><nav aria-labelledby="starlight__on-this-page--mobile" class="astro-5ulgm6bh"><details id="starlight__mobile-toc" class="astro-5ulgm6bh"><summary id="starlight__on-this-page--mobile" class="sl-flex astro-5ulgm6bh"><span class="toggle sl-flex astro-5ulgm6bh">On this page<svg aria-hidden="true" class="caret astro-5ulgm6bh astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></span><span class="display-current astro-5ulgm6bh"></span></summary><div class="dropdown astro-5ulgm6bh"><ul class="isMobile astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#data-flow" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Data flow</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#execution-paths-and-ownership" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Execution paths and ownership</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#recent-changes-and-release-boundary" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Recent changes and release boundary</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#design-invariants" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Design invariants</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#release-surface" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Release surface</span></a></li></ul></div></details></nav></mobile-starlight-toc><script type="module" src="/_astro/MobileTableOfContents.astro_astro_type_script_index_0_lang.BcSo_yiZ.js"></script></div><div class="right-sidebar-panel sl-hidden lg:sl-block astro-q5mffni3"><div class="sl-container astro-q5mffni3"><starlight-toc data-min-h="2" data-max-h="3"><nav aria-labelledby="starlight__on-this-page"><h2 id="starlight__on-this-page">On this page</h2><ul class="astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#data-flow" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Data flow</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#execution-paths-and-ownership" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Execution paths and ownership</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#recent-changes-and-release-boundary" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Recent changes and release boundary</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#design-invariants" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Design invariants</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#release-surface" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Release surface</span></a></li></ul></nav></starlight-toc><script type="module" src="/_astro/TableOfContents.astro_astro_type_script_index_0_lang.Csloo1VZ.js"></script></div></div></div></aside><div class="main-pane astroLine truncated
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
@@ -142,7 +142,7 @@ Only a verified string is returned. Ranges splice whole items; format fences
|
||||
also protect statement scopes, and verification covers the complete output.</li>
|
||||
<li><strong>Lint:</strong> <code dir="auto">ParsedSource</code> bundles one tokenization and tolerant parse;
|
||||
<code dir="auto">LintContext</code> supplies source facts and lazy semantics. The registry selects
|
||||
73 rules with severities and validated options. Inline waivers filter findings,
|
||||
73 rules with severities and validated options. Inline and external waivers filter findings,
|
||||
and the front ends protect fenced bytes before applying fixes.</li>
|
||||
<li><strong>Refactor:</strong> parsed spans and resolved references produce an edit plan;
|
||||
the engine checks the whole candidate edit before returning it. Server source
|
||||
@@ -150,7 +150,7 @@ selectors bound the input set but must include every file the engine might
|
||||
edit or refuse over. No formatter dependency is involved.</li>
|
||||
<li><strong>Editor:</strong> one ordered synchronous loop owns <code dir="auto">Workspace</code>; open documents
|
||||
overlay disk facts. Scans publish index/include/completion batches together.
|
||||
Closed-file facts persist under codec 17; a bounded file-view cache serves
|
||||
Committed closed-file facts persist under codec 18, including package re-exports; a bounded file-view cache serves
|
||||
queries that still need source text. Lazy port actions defer the edit until
|
||||
selection; recorded file-scope definition positions avoid a closed-file read.</li>
|
||||
</ul>
|
||||
@@ -164,6 +164,19 @@ server’s synchronous LSP/JSON stack.</p>
|
||||
verification, persisted semantic facts, server state/ordering, and matching
|
||||
server/editor setting names. Source modules are split by grammar domain under
|
||||
<code dir="auto">parser/</code>, <code dir="auto">ast/</code>, <code dir="auto">format/</code>, <code dir="auto">bind/</code>, <code dir="auto">workspace/</code>, <code dir="auto">ports/</code>, and <code dir="auto">server/</code>.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="recent-changes-and-release-boundary">Recent changes and release boundary</h2><a class="sl-anchor-link" href="#recent-changes-and-release-boundary"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Recent changes and release boundary”</span></a></div>
|
||||
<p>v0.42–0.44 added external waiver files, exclusive atomic temp files with
|
||||
canonical CLI deduplication, shared project/editor lint configuration,
|
||||
cycle-aware directory walks with recoverable warnings, and inline aggregate
|
||||
overrides. The v0.44.0 <code dir="auto">undriven-net</code> fix asks the workspace mention census only
|
||||
after local guards, reducing editor open/flush latency without changing the
|
||||
rule’s findings or the synchronous request-ordering contract.</p>
|
||||
<p>Two accepted changes are committed after v0.44.0: type names now carry exact
|
||||
AST spans (<code dir="auto">scan.rs</code> is retired), and package re-exports are references and
|
||||
cycle-guarded member edges in codec 18. Re-exporting a name does not import it
|
||||
into the exporting package’s local scope. DPI-export names remain unbound.
|
||||
The separate hierarchical-tail work proposes codec 19 and a module member
|
||||
surface for instance paths; it is still under QA and is not a released API.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="design-invariants">Design invariants</h2><a class="sl-anchor-link" href="#design-invariants"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Design invariants”</span></a></div>
|
||||
<ul>
|
||||
<li><strong>Source fidelity:</strong> comments and blank-line intent survive the parser.</li>
|
||||
@@ -175,4 +188,4 @@ server/editor setting names. Source modules are split by grammar domain under
|
||||
</ul>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="release-surface">Release surface</h2><a class="sl-anchor-link" href="#release-surface"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Release surface”</span></a></div>
|
||||
<p>The supported publication surface is seven VS Code <code dir="auto">.vsix</code> packages plus checksums: five platform packages (Apple Silicon/Intel macOS, x86-64/ARM64 static-musl Linux, Windows), one all-platform package, and one universal package requiring binaries on <code dir="auto">PATH</code>. Both <code dir="auto">lucisv</code> and <code dir="auto">lucisv-server</code> are bundled in platform packages. Standalone binaries are built by the tooling but are not published as release assets. The release tooling audits file type, dynamic linkage, and the glibc ceiling for cross-built artifacts.</p>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/architecture.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T04:37:55.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/rust-api/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Rust API index</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/architecture.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T18:35:57.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/rust-api/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Rust API index</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
+7
-1
@@ -247,6 +247,12 @@
|
||||
<p>Filelist paths bypass <code dir="auto">--exclude</code> and <code dir="auto">.gitignore</code>, just like direct command-line files. Duplicates are processed once. Unknown options, unset variables, and missing listed files warn without changing the exit code; an unreadable filelist is an error.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="ignore-patterns">Ignore patterns</h2><a class="sl-anchor-link" href="#ignore-patterns"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Ignore patterns”</span></a></div>
|
||||
<p>Directory walks read <code dir="auto">.gitignore</code> in each directory. Deeper rules override shallower rules; the last matching line wins. Supported syntax includes comments, blank lines, <code dir="auto">*</code> within a component, anchored <code dir="auto">/</code>, directory-only trailing <code dir="auto">/</code>, and <code dir="auto">!</code> negation. <code dir="auto">**</code>, <code dir="auto">?</code>, character classes, escapes, global excludes, and tracked-file exceptions are not implemented.</p>
|
||||
<p>A directory is visited once by identity, so symlink cycles terminate. CLI
|
||||
inputs resolving to the same canonical path are processed once. An unreadable
|
||||
directory or <code dir="auto">.gitignore</code>, or a dangling source-file link encountered while
|
||||
walking, produces <code dir="auto">warning: <path>: <message></code> on stderr and the walk continues;
|
||||
these warnings do not change the exit code. A missing explicitly named input
|
||||
remains an error.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="exit-codes">Exit codes</h2><a class="sl-anchor-link" href="#exit-codes"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Exit codes”</span></a></div>
|
||||
<table>
|
||||
<thead>
|
||||
@@ -271,4 +277,4 @@
|
||||
</tbody>
|
||||
</table>
|
||||
<p>An error outranks “would change.” Every file involved in an error is left untouched.</p>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/cli.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T05:03:07.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/guides/syntax/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Supported syntax</span></span></a><a href="/reference/rules/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Lint rules</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/cli.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T18:35:57.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/guides/syntax/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Supported syntax</span></span></a><a href="/reference/rules/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Lint rules</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
+2
-2
@@ -289,7 +289,7 @@ index scope when the defining module lives outside the default folder scope.</p>
|
||||
<tr>
|
||||
<td>Port actions</td>
|
||||
<td>code actions / commands</td>
|
||||
<td>Adds, removes, and propagates module ports</td>
|
||||
<td>Adds, removes, and propagates module ports; expands a <code dir="auto">.*</code> wildcard into the named connections it stands for (a port with no same-named signal in scope becomes <code dir="auto">.p()</code> and is named in a warning) — <code dir="auto">lucisv.expandWildcard</code>; converts a Verilog-2001 header to ANSI, each body declaration merged into the port it described (IEEE 1800 §23.2.2.2) with its comments carried along — <code dir="auto">lucisv.convertToAnsi</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Instantiate module</td>
|
||||
@@ -342,4 +342,4 @@ index scope when the defining module lives outside the default folder scope.</p>
|
||||
</table>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="workspace-lifecycle">Workspace lifecycle</h2><a class="sl-anchor-link" href="#workspace-lifecycle"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Workspace lifecycle”</span></a></div>
|
||||
<p>The server handles <code dir="auto">didOpen</code>, incremental <code dir="auto">didChange</code>, <code dir="auto">didSave</code>, <code dir="auto">didClose</code>, watched-file changes, configuration changes, cancellation, shutdown, and exit. It dynamically registers file watchers, emits work-done progress while building large indexes, coalesces code-lens refreshes, and promotes open-buffer overlays into the workspace without waiting for disk writes.</p>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/language-tools.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T04:37:55.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/rules/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Lint rules</span></span></a><a href="/reference/rust-api/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Rust API index</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/language-tools.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T20:03:11.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/rules/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Lint rules</span></span></a><a href="/reference/rust-api/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Rust API index</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
+2
-2
@@ -74,7 +74,7 @@
|
||||
<p>Every rule is in one of three <strong>severity</strong> classes. <code dir="auto">error</code> is code that would very likely fail to compile, elaborate or synthesize; <code dir="auto">warning</code> is code that compiles and very likely does not mean what it says; <code dir="auto">style</code> is code that is correct and reads badly. The class is the word in the CLI diagnostic line (<code dir="auto">FILE:LINE:COL: warning: …</code>), the <code dir="auto">severity</code> field of <code dir="auto">--output-format json</code>, and the colour of the editor’s squiggle — and it is accepted wherever a rule name is, so <code dir="auto">--ignore style</code> and <code dir="auto">--select error</code> both work.</p>
|
||||
<p>Every <code dir="auto">error</code>-class rule is held to one discipline: it goes <strong>silent whenever the run cannot answer</strong> — a file that did not fully parse, a module the project does not hold or holds twice, a name a macro produces, a fragment written to be <code dir="auto"> `include</code>d. A wrong accusation in that class is worse than a hundred missed ones.</p>
|
||||
<p>This page is hand-written prose. The generated truth is <code dir="auto">lucisv check --rules-doc</code>, which prints every rule with its class, default, fix and rationale straight from the registry — <strong>and every option a rule takes, with its kind and default</strong>.</p>
|
||||
<p>A configurable rule is configured in a <code dir="auto">[lint.<rule-name>]</code> table of a <code dir="auto">lucisv.toml</code>, or from an editor in the <code dir="auto">lucisv.lint.options</code> object; the option names are Verible’s wherever it has the same option. An unknown rule or option name, a value of the wrong kind, an out-of-range integer or a pattern that does not compile fails a CLI run naming the file and the line. Invalid editor option settings are logged and dropped; invalid project-file option entries are currently dropped silently by server linting.</p>
|
||||
<p>A configurable rule is configured in a <code dir="auto">[lint.<rule-name>]</code> table of a <code dir="auto">lucisv.toml</code>, or from an editor in the <code dir="auto">lucisv.lint.options</code> object; the option names are Verible’s wherever it has the same option. An unknown rule or option name, a value of the wrong kind, an out-of-range integer or a pattern that does not compile fails a CLI run naming the file and the line. Rejected project entries are logged once with file and line and dropped by server linting; invalid editor options and unknown editor select/ignore names are also logged. Valid entries continue to apply.</p>
|
||||
<div class="expressive-code"><link rel="stylesheet" href="/_astro/ec.w36nc.css"><script type="module" src="/_astro/ec.0vx5m.js"></script><figure class="frame not-content"><figcaption class="header"></figcaption><pre data-language="toml"><code><div class="ec-line"><div class="code"><span style="--0:#D6DEEB;--1:#403F53">[lint.line-length]</span></div></div><div class="ec-line"><div class="code"><span style="--0:#C5E478;--1:#3B61B0">length</span><span style="--0:#D6DEEB;--1:#403F53"> = </span><span style="--0:#F78C6C;--1:#AA0982">120</span></div></div><div class="ec-line"><div class="code">
|
||||
</div></div><div class="ec-line"><div class="code"><span style="--0:#D6DEEB;--1:#403F53">[lint.typedef-structs-unions]</span></div></div><div class="ec-line"><div class="code"><span style="--0:#C5E478;--1:#3B61B0">allow_anonymous_nested</span><span style="--0:#D6DEEB;--1:#403F53"> = </span><span style="--0:#FF6A83;--1:#A24848">true</span></div></div></code></pre><div class="copy"><div aria-live="polite"></div><button title="Copy to clipboard" data-copied="Copied!" data-code="[lint.line-length]length = 120[lint.typedef-structs-unions]allow_anonymous_nested = true"><div></div></button></div></figure></div>
|
||||
<p>A rule marked <strong>on (project)</strong> runs by default only where lucisv can see the other files of your project — <code dir="auto">lucisv check <dir></code>, or the language server. Over a single file or a stdin buffer it is off and must be <code dir="auto">--select</code>ed, because its one false-positive mode is a use in another file. Turn any rule off with <code dir="auto">--ignore</code>, with <code dir="auto">ignore</code> under <code dir="auto">[lint]</code> in <code dir="auto">lucisv.toml</code>, or with <code dir="auto">lucisv.lint.ignore</code> in your editor.</p>
|
||||
@@ -748,4 +748,4 @@
|
||||
<p>Reports a <code dir="auto">;</code> written after a <code dir="auto">`uvm_*</code> macro invocation. The macros expand to a <code dir="auto">begin … end</code>, so the <code dir="auto">;</code> is a null statement — usually inert, and not after <code dir="auto">if (x) </code>uvm_info(…); else …<code dir="auto">, where the </code>else<code dir="auto">then belongs to nothing. Off by default in both, because the semicolon is written everywhere in existing UVM code. No fix: deleting it is exactly the edit that is unsafe in the shape the rule exists for. Verible's</code>uvm-macro-semicolon`, same default.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="v2001-generate-begin">v2001-generate-begin</h2><a class="sl-anchor-link" href="#v2001-generate-begin"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “v2001-generate-begin”</span></a></div>
|
||||
<p>Reports a bare <code dir="auto">begin … end</code> written directly inside a <code dir="auto">generate … endgenerate</code> with no <code dir="auto">if</code>, <code dir="auto">for</code> or <code dir="auto">case</code> around it. It opens an unnamed generate block — an invented path segment that renumbers when a block is added above it — and buys nothing, because the region is already a scope. Read from the same recovered block <code dir="auto">module-begin-block</code> reads, one scope in. Verible’s <code dir="auto">v2001-generate-begin</code>, same default.</p>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/rules.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T04:37:55.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/cli/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">CLI</span></span></a><a href="/reference/language-tools/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Language tools</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/rules.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T18:35:57.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/cli/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">CLI</span></span></a><a href="/reference/language-tools/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Language tools</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
+22
-8
@@ -72,7 +72,9 @@
|
||||
StarlightThemeProvider.updatePickers();
|
||||
</script></div></div></div></div></nav><div class="main-frame astro-gqpr5s5a"><script type="module">var e=document.getElementById(`starlight__sidebar`),t=e?.querySelector(`sl-sidebar-state-persist`),n=`sl-sidebar-state`,r=()=>{let r=[],i=t?.dataset.hash||``;try{let e=sessionStorage.getItem(n),t=JSON.parse(e||`{}`);Array.isArray(t.open)&&t.hash===i&&(r=t.open)}catch{}return{hash:i,open:r,scroll:e?.scrollTop||0}},i=e=>{try{sessionStorage.setItem(n,JSON.stringify(e))}catch{}},a=()=>i(r()),o=(e,t)=>{let n=r();n.open[t]=e,i(n)};t?.addEventListener(`click`,e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`summary`)?.closest(`details`);if(!t)return;let n=t.querySelector(`sl-sidebar-restore`),r=parseInt(n?.dataset.index||``);isNaN(r)||o(!t.open,r)}),addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&a()});</script><div class="lg:sl-flex astro-abfeecmu"><aside class="right-sidebar-container print:hidden astro-abfeecmu"><div class="right-sidebar astro-abfeecmu"><div class="lg:sl-hidden astro-q5mffni3"><mobile-starlight-toc data-min-h="2" data-max-h="3" class="astro-5ulgm6bh"><nav aria-labelledby="starlight__on-this-page--mobile" class="astro-5ulgm6bh"><details id="starlight__mobile-toc" class="astro-5ulgm6bh"><summary id="starlight__on-this-page--mobile" class="sl-flex astro-5ulgm6bh"><span class="toggle sl-flex astro-5ulgm6bh">On this page<svg aria-hidden="true" class="caret astro-5ulgm6bh astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1rem;"><path d="m14.83 11.29-4.24-4.24a1 1 0 1 0-1.42 1.41L12.71 12l-3.54 3.54a1 1 0 0 0 0 1.41 1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.24-4.24a1.002 1.002 0 0 0 0-1.42Z"/></svg></span><span class="display-current astro-5ulgm6bh"></span></summary><div class="dropdown astro-5ulgm6bh"><ul class="isMobile astro-cxyftcne" style="--depth: 0;"><li style="--depth: 0;" class="astro-cxyftcne"><a href="#_top" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">Overview</span></a></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#vlog_parser" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">vlog_parser</span></a><ul class="isMobile astro-cxyftcne" style="--depth: 1;"><li style="--depth: 1;" class="astro-cxyftcne"><a href="#entry-points-and-lexical-utilities" style="--depth: 1;" class="astro-cxyftcne"><span style="--depth: 1;" class="astro-cxyftcne">Entry points and lexical utilities</span></a></li><li style="--depth: 1;" class="astro-cxyftcne"><a href="#coordinates-and-token-queries" style="--depth: 1;" class="astro-cxyftcne"><span style="--depth: 1;" class="astro-cxyftcne">Coordinates and token queries</span></a></li><li style="--depth: 1;" class="astro-cxyftcne"><a href="#ast-queries" style="--depth: 1;" class="astro-cxyftcne"><span style="--depth: 1;" class="astro-cxyftcne">AST queries</span></a></li></ul></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#vlog_formatter" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">vlog_formatter</span></a><ul class="isMobile astro-cxyftcne" style="--depth: 1;"><li style="--depth: 1;" class="astro-cxyftcne"><a href="#formatting-and-verification" style="--depth: 1;" class="astro-cxyftcne"><span style="--depth: 1;" class="astro-cxyftcne">Formatting and verification</span></a></li><li style="--depth: 1;" class="astro-cxyftcne"><a href="#document-model-and-printer" style="--depth: 1;" class="astro-cxyftcne"><span style="--depth: 1;" class="astro-cxyftcne">Document model and printer</span></a></li><li style="--depth: 1;" class="astro-cxyftcne"><a href="#alignment-fences-and-ranges" style="--depth: 1;" class="astro-cxyftcne"><span style="--depth: 1;" class="astro-cxyftcne">Alignment, fences, and ranges</span></a></li></ul></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#vlog_linter" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">vlog_linter</span></a><ul class="isMobile astro-cxyftcne" style="--depth: 1;"><li style="--depth: 1;" class="astro-cxyftcne"><a href="#run-and-select-rules" style="--depth: 1;" class="astro-cxyftcne"><span style="--depth: 1;" class="astro-cxyftcne">Run and select rules</span></a></li><li style="--depth: 1;" class="astro-cxyftcne"><a href="#context-diagnostics-and-fixes" style="--depth: 1;" class="astro-cxyftcne"><span style="--depth: 1;" class="astro-cxyftcne">Context, diagnostics, and fixes</span></a></li></ul></li><li style="--depth: 0;" class="astro-cxyftcne"><a href="#vlog_semantic" style="--depth: 0;" class="astro-cxyftcne"><span style="--depth: 0;" class="astro-cxyftcne">vlog_semantic</span></a><ul class="isMobile astro-cxyftcne" style="--depth: 1;"><li style="--depth: 1;" class="astro-cxyftcne"><a href="#file-semantics" style="--depth: 1;" class="astro-cxyftcne"><span style="--depth: 1;" class="astro-cxyftcne">File semantics</spanLine truncated
|
||||
<p>This is a navigational API index, not source documentation. It summarizes the main public callable surface of the six reusable library crates in the workspace; command-line and language-server binaries are documented in their dedicated references.</p>
|
||||
<p>The workspace baseline is v0.41.0. For the complete signatures and fields,
|
||||
<p>The latest release is v0.44.0. This index includes the accepted type-name-span
|
||||
and package-re-export additions committed at <code dir="auto">9ef1058</code> for the next release;
|
||||
it excludes the in-progress hierarchical-tail API and codec 19. For the complete signatures and fields,
|
||||
run <code dir="auto">cargo doc --workspace --no-deps</code>; this hand-maintained index is not an
|
||||
exhaustive replacement for rustdoc. The parser’s strict and tolerant entry
|
||||
points share one grammar; tolerant errors do not imply formatter acceptance.
|
||||
@@ -189,7 +191,7 @@ The CLI and server configure their worker threads accordingly.</p>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code dir="auto">DataType</code></td>
|
||||
<td><code dir="auto">is_implicit</code>, <code dir="auto">params</code>, <code dir="auto">inline</code></td>
|
||||
<td><code dir="auto">is_implicit</code>, <code dir="auto">params</code>, <code dir="auto">inline</code>, <code dir="auto">name_span</code>, <code dir="auto">segments</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code dir="auto">VirtualKw</code></td>
|
||||
@@ -311,7 +313,11 @@ The CLI and server configure their worker threads accordingly.</p>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code dir="auto">lint</code></td>
|
||||
<td>Run enabled rules against a prepared context</td>
|
||||
<td>Run enabled rules against a prepared context with inline waivers</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code dir="auto">lint_with</code></td>
|
||||
<td>Apply inline and external waivers and return external usage alongside findings</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code dir="auto">all_rules</code></td>
|
||||
@@ -397,6 +403,14 @@ The CLI and server configure their worker threads accordingly.</p>
|
||||
<td><code dir="auto">as_str</code>, <code dir="auto">vocabulary</code> / <code dir="auto">value</code>, <code dir="auto">as_written</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code dir="auto">ExternalWaivers</code></td>
|
||||
<td><code dir="auto">read</code>, <code dir="auto">parse</code>, <code dir="auto">absorb</code>, <code dir="auto">is_empty</code>, <code dir="auto">unused</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code dir="auto">WaiverUse</code></td>
|
||||
<td><code dir="auto">merge</code> (aggregate usage across a complete run before reporting unused waivers)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>editor settings functions</td>
|
||||
<td><code dir="auto">vscode_lint_settings</code>, <code dir="auto">rule_setting</code>, <code dir="auto">severity_setting</code></td>
|
||||
</tr>
|
||||
@@ -481,8 +495,8 @@ The CLI and server configure their worker threads accordingly.</p>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p><code dir="auto">FACTS_FORMAT</code> is <strong>17</strong>. Cached facts include normal and macro identifier
|
||||
censuses; <code dir="auto">Def::lines.positions</code> can carry <code dir="auto">DeclPositions</code> with UTF-16 ranges
|
||||
<p><code dir="auto">FACTS_FORMAT</code> is <strong>18</strong> in the committed snapshot. Cached facts include
|
||||
normal/macro identifier censuses and package re-export edges (the <code dir="auto">RX</code> group); <code dir="auto">Def::lines.positions</code> can carry <code dir="auto">DeclPositions</code> with UTF-16 ranges
|
||||
for file-scope declarations. Any persisted shape or fact-census change needs
|
||||
a codec-version decision so stale caches cannot silently omit answers.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="vlog_refactor"><code dir="auto">vlog_refactor</code></h2><a class="sl-anchor-link" href="#vlog_refactor"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “vlog_refactor”</span></a></div>
|
||||
@@ -608,7 +622,7 @@ a codec-version decision so stale caches cannot silently omit answers.</p>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code dir="auto">walk::collect_files</code></td>
|
||||
<td>Walk inputs with ignores and exclusions</td>
|
||||
<td>Walk inputs with ignores, exclusions and directory-cycle detection; accepts a <code dir="auto">FnMut(Warning)</code> sink for recoverable failures</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code dir="auto">walk::is_excluded</code></td>
|
||||
@@ -627,7 +641,7 @@ a codec-version decision so stale caches cannot silently omit answers.</p>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><code dir="auto">atomic::write_atomic</code></td>
|
||||
<td>Replace file contents through a sibling temp file and rename; callers must coordinate concurrent writes to one target</td>
|
||||
<td>Replace contents using an exclusively created per-operation temp file; concurrent replacements publish one whole buffer, last writer wins</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code dir="auto">content_hash</code></td>
|
||||
@@ -640,4 +654,4 @@ a codec-version decision so stale caches cannot silently omit answers.</p>
|
||||
</tbody>
|
||||
</table>
|
||||
<aside aria-label="Types" class="starlight-aside starlight-aside--note"><p class="starlight-aside__title" aria-hidden="true"><svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" class="starlight-aside__icon"><path d="M12 11a1 1 0 0 0-1 1v4a1 1 0 0 0 2 0v-4a1 1 0 0 0-1-1Zm.38-3.92a1 1 0 0 0-.76 0 1 1 0 0 0-.33.21 1.15 1.15 0 0 0-.21.33 1 1 0 0 0 .21 1.09c.097.088.209.16.33.21A1 1 0 0 0 13 8a1.05 1.05 0 0 0-.29-.71 1 1 0 0 0-.33-.21ZM12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20Zm0 18a8 8 0 1 1 0-16.001A8 8 0 0 1 12 20Z"/></svg>Types</p><div class="starlight-aside__content"><p>The crates also expose their data models—AST nodes, diagnostics, rule traits, workspace identifiers, edits, plans, and formatter document nodes. This page intentionally indexes callable behavior; generated Rust API docs remain the right place for field-level type details.</p></div></aside>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/rust-api.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T04:37:55.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/language-tools/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Language tools</span></span></a><a href="/reference/architecture/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Architecture</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/reference/rust-api.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T18:35:57.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/reference/language-tools/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Language tools</span></span></a><a href="/reference/architecture/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Architecture</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
+10
-6
@@ -292,11 +292,15 @@ setting is non-empty and the project’s <code dir="auto">[lint] select</code> o
|
||||
is decided the same way and independently. The severity switches and
|
||||
per-rule toggles are editor-only — a <code dir="auto">lucisv.toml</code> has no such keys — and
|
||||
apply over whichever selection stands. Editor rule options overlay project
|
||||
rule options key by key. An entry that cannot be used is dropped and logged
|
||||
once per configuration file and entry, in the same <code dir="auto"><file>:<line>: <message></code> wording <code dir="auto">lucisv check</code> fails with: an invalid editor option, an
|
||||
invalid <code dir="auto">[lint.<rule>]</code> entry, an unknown rule name in <code dir="auto">[lint] select</code>/<code dir="auto">ignore</code>, or an unreadable waiver file. <code dir="auto">lucisv check</code> treats each
|
||||
of these as a configuration error and exits 2; the server keeps linting with
|
||||
the entry dropped.</p>
|
||||
rule options key by key. An invalid project option, unknown project rule name,
|
||||
or bad waiver entry is dropped and logged once with the same
|
||||
<code dir="auto"><file>:<line>: <message></code> wording the CLI reports. The CLI treats those
|
||||
project errors as exit 2; the server keeps linting with the valid entries.
|
||||
Editor-only settings are validated separately: bad options are logged, and an
|
||||
unknown select/ignore name is logged once as
|
||||
<code dir="auto">lucisv.lint.select: unknown rule: <name></code> (or <code dir="auto">ignore</code>). Changing that list
|
||||
re-arms logging for newly introduced mistakes. An empty editor selection is
|
||||
the fallback sentinel, so it does not clear a non-empty project selection.</p>
|
||||
<div class="sl-heading-wrapper level-h2"><h2 id="cache">Cache</h2><a class="sl-anchor-link" href="#cache"><span aria-hidden="true" class="sl-anchor-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="m12.11 15.39-3.88 3.88a2.52 2.52 0 0 1-3.5 0 2.47 2.47 0 0 1 0-3.5l3.88-3.88a1 1 0 1 0-1.42-1.42l-3.88 3.89a4.48 4.48 0 0 0 6.33 6.33l3.89-3.88a1 1 0 0 0-1.42-1.42m8.58-12.08a4.49 4.49 0 0 0-6.33 0l-3.89 3.88a1 1 0 1 0 1.42 1.42l3.88-3.88a2.52 2.52 0 0 1 3.5 0 2.47 2.47 0 0 1 0 3.5l-3.88 3.88a1 1 0 0 0 0 1.42 1 1 0 0 0 1.42 0l3.88-3.89a4.49 4.49 0 0 0 0-6.33M8.83 15.17a1 1 0 0 0 .71.29 1 1 0 0 0 .71-.29l4.92-4.92a1 1 0 1 0-1.42-1.42l-4.92 4.92a1 1 0 0 0 0 1.42"></path></svg></span><span class="sr-only" data-pagefind-ignore>Section titled “Cache”</span></a></div>
|
||||
<p>Successful “already formatted” verdicts are cached under <code dir="auto">.lucisv_cache/</code>. Entries are keyed by file, content hash, line length, indentation, and lucisv version. Files that would change or fail are never cached. Use <code dir="auto">--no-cache</code> to disable reads and writes or <code dir="auto">--cache-dir</code> to relocate the store.</p>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/start/configuration.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T05:03:07.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/start/quick-start/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Quick start</span></span></a><a href="/guides/formatter/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Formatter</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
</div><footer class="sl-flex astro-xhxjzfa7"><div class="meta sl-flex astro-xhxjzfa7"><a href="https://git.luci.ooo/lucio/verilogrustformatter/src/branch/master/docs/site/src/content/docs/start/configuration.md" class="sl-flex print:hidden astro-xk5gmzsg"><svg aria-hidden="true" class="astro-xk5gmzsg astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.2em;"><path d="M22 7.24a1 1 0 0 0-.29-.71l-4.24-4.24a1 1 0 0 0-1.1-.22 1 1 0 0 0-.32.22l-2.83 2.83L2.29 16.05a1 1 0 0 0-.29.71V21a1 1 0 0 0 1 1h4.24a1 1 0 0 0 .76-.29l10.87-10.93L21.71 8c.1-.1.17-.2.22-.33a1 1 0 0 0 0-.24v-.14l.07-.05ZM6.83 20H4v-2.83l9.93-9.93 2.83 2.83L6.83 20ZM18.17 8.66l-2.83-2.83 1.42-1.41 2.82 2.82-1.41 1.42Z"/></svg>Edit page</a><p>Last updated: <time datetime="2026-09-05T18:35:57.000Z">Sep 5, 2026</time></p></div><div class="pagination-links print:hidden astro-jgq3vlii" dir="ltr"><a href="/start/quick-start/" rel="prev" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17 11H9.41l3.3-3.29a1.004 1.004 0 1 0-1.42-1.42l-5 5a1 1 0 0 0-.21.33 1 1 0 0 0 0 .76 1 1 0 0 0 .21.33l5 5a1.002 1.002 0 0 0 1.639-.325 1 1 0 0 0-.219-1.095L9.41 13H17a1 1 0 0 0 0-2Z"/></svg><span class="astro-jgq3vlii">Previous<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Quick start</span></span></a><a href="/guides/formatter/" rel="next" class="astro-jgq3vlii"><svg aria-hidden="true" class="astro-jgq3vlii astro-n5k4ipy7" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="--sl-icon-size: 1.5rem;"><path d="M17.92 11.62a1.001 1.001 0 0 0-.21-.33l-5-5a1.003 1.003 0 1 0-1.42 1.42l3.3 3.29H7a1 1 0 0 0 0 2h7.59l-3.3 3.29a1.002 1.002 0 0 0 .325 1.639 1 1 0 0 0 1.095-.219l5-5a1 1 0 0 0 .21-.33 1 1 0 0 0 0-.76Z"/></svg><span class="astro-jgq3vlii">Next<br class="astro-jgq3vlii"><span class="link-title astro-jgq3vlii">Formatter</span></span></a></div></footer></div></div></main></div></div></div></div></body></html>
|
||||
@@ -39,7 +39,7 @@ lucisv follows the same separation of concerns that makes ruff fast and maintain
|
||||
also protect statement scopes, and verification covers the complete output.
|
||||
- **Lint:** `ParsedSource` bundles one tokenization and tolerant parse;
|
||||
`LintContext` supplies source facts and lazy semantics. The registry selects
|
||||
73 rules with severities and validated options. Inline waivers filter findings,
|
||||
73 rules with severities and validated options. Inline and external waivers filter findings,
|
||||
and the front ends protect fenced bytes before applying fixes.
|
||||
- **Refactor:** parsed spans and resolved references produce an edit plan;
|
||||
the engine checks the whole candidate edit before returning it. Server source
|
||||
@@ -47,7 +47,7 @@ lucisv follows the same separation of concerns that makes ruff fast and maintain
|
||||
edit or refuse over. No formatter dependency is involved.
|
||||
- **Editor:** one ordered synchronous loop owns `Workspace`; open documents
|
||||
overlay disk facts. Scans publish index/include/completion batches together.
|
||||
Closed-file facts persist under codec 17; a bounded file-view cache serves
|
||||
Committed closed-file facts persist under codec 18, including package re-exports; a bounded file-view cache serves
|
||||
queries that still need source text. Lazy port actions defer the edit until
|
||||
selection; recorded file-scope definition positions avoid a closed-file read.
|
||||
|
||||
@@ -63,6 +63,22 @@ verification, persisted semantic facts, server state/ordering, and matching
|
||||
server/editor setting names. Source modules are split by grammar domain under
|
||||
`parser/`, `ast/`, `format/`, `bind/`, `workspace/`, `ports/`, and `server/`.
|
||||
|
||||
## Recent changes and release boundary
|
||||
|
||||
v0.42–0.44 added external waiver files, exclusive atomic temp files with
|
||||
canonical CLI deduplication, shared project/editor lint configuration,
|
||||
cycle-aware directory walks with recoverable warnings, and inline aggregate
|
||||
overrides. The v0.44.0 `undriven-net` fix asks the workspace mention census only
|
||||
after local guards, reducing editor open/flush latency without changing the
|
||||
rule's findings or the synchronous request-ordering contract.
|
||||
|
||||
Two accepted changes are committed after v0.44.0: type names now carry exact
|
||||
AST spans (`scan.rs` is retired), and package re-exports are references and
|
||||
cycle-guarded member edges in codec 18. Re-exporting a name does not import it
|
||||
into the exporting package's local scope. DPI-export names remain unbound.
|
||||
The separate hierarchical-tail work proposes codec 19 and a module member
|
||||
surface for instance paths; it is still under QA and is not a released API.
|
||||
|
||||
## Design invariants
|
||||
|
||||
- **Source fidelity:** comments and blank-line intent survive the parser.
|
||||
|
||||
@@ -60,6 +60,13 @@ Filelist paths bypass `--exclude` and `.gitignore`, just like direct command-lin
|
||||
|
||||
Directory walks read `.gitignore` in each directory. Deeper rules override shallower rules; the last matching line wins. Supported syntax includes comments, blank lines, `*` within a component, anchored `/`, directory-only trailing `/`, and `!` negation. `**`, `?`, character classes, escapes, global excludes, and tracked-file exceptions are not implemented.
|
||||
|
||||
A directory is visited once by identity, so symlink cycles terminate. CLI
|
||||
inputs resolving to the same canonical path are processed once. An unreadable
|
||||
directory or `.gitignore`, or a dangling source-file link encountered while
|
||||
walking, produces `warning: <path>: <message>` on stderr and the walk continues;
|
||||
these warnings do not change the exit code. A missing explicitly named input
|
||||
remains an error.
|
||||
|
||||
## Exit codes
|
||||
|
||||
| Code | Meaning |
|
||||
|
||||
@@ -68,7 +68,7 @@ index scope when the defining module lives outside the default folder scope.
|
||||
|---|---|---|
|
||||
| Prepare rename | `textDocument/prepareRename` | Verifies the target and returns its editable range |
|
||||
| Rename | `textDocument/rename` | Renames local or workspace-resolved symbols |
|
||||
| Port actions | code actions / commands | Adds, removes, and propagates module ports |
|
||||
| Port actions | code actions / commands | Adds, removes, and propagates module ports; expands a `.*` wildcard into the named connections it stands for (a port with no same-named signal in scope becomes `.p()` and is named in a warning) — `lucisv.expandWildcard`; converts a Verilog-2001 header to ANSI, each body declaration merged into the port it described (IEEE 1800 §23.2.2.2) with its comments carried along — `lucisv.convertToAnsi` |
|
||||
| Instantiate module | inline completion / `lucisv.instantiate` | Builds an instance from an indexed module interface, including in clients without ghost text |
|
||||
| Apply workspace edit | `workspace/applyEdit` | Delivers multi-file refactor changes to the client |
|
||||
| Show definition | `window/showDocument` | Opens a generated or resolved target after an action |
|
||||
|
||||
@@ -11,7 +11,7 @@ Every `error`-class rule is held to one discipline: it goes **silent whenever th
|
||||
|
||||
This page is hand-written prose. The generated truth is `lucisv check --rules-doc`, which prints every rule with its class, default, fix and rationale straight from the registry — **and every option a rule takes, with its kind and default**.
|
||||
|
||||
A configurable rule is configured in a `[lint.<rule-name>]` table of a `lucisv.toml`, or from an editor in the `lucisv.lint.options` object; the option names are Verible's wherever it has the same option. An unknown rule or option name, a value of the wrong kind, an out-of-range integer or a pattern that does not compile fails a CLI run naming the file and the line. Invalid editor option settings are logged and dropped; invalid project-file option entries are currently dropped silently by server linting.
|
||||
A configurable rule is configured in a `[lint.<rule-name>]` table of a `lucisv.toml`, or from an editor in the `lucisv.lint.options` object; the option names are Verible's wherever it has the same option. An unknown rule or option name, a value of the wrong kind, an out-of-range integer or a pattern that does not compile fails a CLI run naming the file and the line. Rejected project entries are logged once with file and line and dropped by server linting; invalid editor options and unknown editor select/ignore names are also logged. Valid entries continue to apply.
|
||||
|
||||
```toml
|
||||
[lint.line-length]
|
||||
|
||||
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user