Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ce2f7190ed | ||
|
|
aa479cf701 | ||
|
|
d9ed2c447a | ||
|
|
1da0a303cc | ||
|
|
f476c31483 | ||
|
|
9ef1058059 | ||
|
|
4d59e80568 | ||
|
|
859742ac84 | ||
|
|
66f38987ac | ||
|
|
8145a67be6 | ||
|
|
f7956060b3 | ||
|
|
f302b471a7 | ||
|
|
7aedfe2554 | ||
|
|
73799f3d53 | ||
|
|
ec9ec42276 | ||
|
|
4b2dad87fe | ||
|
|
3b08c0753c | ||
|
|
972bd1cff1 | ||
|
|
8a92e79fc0 | ||
|
|
f6f18de10d | ||
|
|
d5abf81563 |
No files matched your search
+132
@@ -4,6 +4,138 @@ 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
|
||||
|
||||
- **`undriven-net` asked the workspace census once per declaration**,
|
||||
ahead of the local guards that silence almost every one, so a
|
||||
`didOpen` — and every keystroke flush — of a large file paid a walk
|
||||
over every indexed file thousands of times. Asked last now, the way
|
||||
its twin `unused-signal` always did. Opening opentitan's 42 192-line
|
||||
`pinmux_reg_top.sv` at workspace scope: 1 742 ms → 117 ms; typical
|
||||
IP files 51–95 ms → 5–8 ms. Same findings in the same order.
|
||||
- **Walk warnings.** An unreadable directory, an unreadable `.gitignore`
|
||||
or a dangling source-file symlink no longer fails a run: the CLI
|
||||
prints `warning: <path>: <message>` on stderr before the report with
|
||||
the exit code unchanged, and the server logs once per scan.
|
||||
- **A typo in `lucisv.lint.select` or `ignore`** is logged once
|
||||
(`lucisv.lint.select: unknown rule: <name>`) instead of silently
|
||||
emptying the selection.
|
||||
- **Inline aggregate types as parameter-override arguments**
|
||||
(`m #(.T(struct packed { logic a; })) u ();`) parse, format and are
|
||||
emitted by the instantiation skeleton.
|
||||
- **Comment slots inside delay lists** (`#( /*a*/ 1 : 2 : 3 )`, gate
|
||||
`#(rise, fall)`), and a line comment after a gate instance's comma
|
||||
now ends the line.
|
||||
|
||||
## 0.43.0 — 2026-09-05
|
||||
|
||||
### The repository analysis's three findings
|
||||
|
||||
- **Atomic writers cannot collide.** In-place writes use an exclusive,
|
||||
per-operation temp file (`.{name}.{pid}.{n}.lucisv-tmp`, created
|
||||
0600 when a target exists and given the target's mode before the bytes
|
||||
land); the CLI deduplicates its inputs by canonical identity, so a
|
||||
symlink alias of a file reaches one worker and is reported once. Two
|
||||
processes on one target remain last-writer-wins, which the formatter's
|
||||
idempotence makes safe.
|
||||
- **One lint-configuration contract.** The editor now honours a project's
|
||||
`[lint] select` and `[lint] ignore` the way the CLI honours its flags:
|
||||
`lucisv.lint.select` when set, else the project's, key by key, with the
|
||||
editor-only severity switches and per-rule toggles applied over whichever
|
||||
stands. A project entry the server cannot use — a rejected `[lint.<rule>]`
|
||||
option, an unknown rule name, a bad waiver directive — is logged once with
|
||||
file and line in `lucisv check`'s wording and dropped; the buffer keeps
|
||||
linting. The CLI's and the server's rule lists are asserted equal over
|
||||
the wire.
|
||||
- **Directory walks terminate on symlink cycles.** Each directory is
|
||||
entered once by identity; a link to a directory already entered is
|
||||
skipped, one not yet entered is followed once, a dangling directory link
|
||||
is skipped and a dangling source-file link is still reported. Both the
|
||||
CLI and the server's index scan.
|
||||
- A comment before a net delay's `#` (`wire /* c */ #5 w;`) now formats.
|
||||
|
||||
## 0.42.0 — 2026-09-05
|
||||
|
||||
### External waiver files, and the two vendor shapes the sweep skipped
|
||||
|
||||
- **External waiver files** in Verible's format: `waive --rule=<rule>
|
||||
[--line=N|N-M] [--location=<pattern>]`, `#` comments. Read from
|
||||
`[lint] waivers` in `lucisv.toml`, `lucisv check --waiver-file` (repeatable)
|
||||
and the editor setting `lucisv.lint.waivers`; the three add up.
|
||||
`--location` is an `--exclude`-style pattern, not a regex, and a
|
||||
regex-looking one is refused by name. Union with inline waivers; unused
|
||||
external waivers are reported under `unused-waiver` at their line of the
|
||||
waiver file by `lucisv check`, after the whole run. The editor's quick
|
||||
fixes and fix-on-save honour external waivers too.
|
||||
- **Rival module/interface headers across an `ifdef`/`else`** (opentitan's
|
||||
`jtag_if.sv`) now parse: the unit is kept verbatim as a whole, the
|
||||
standing directive-split trade, instead of nesting and losing its
|
||||
closer.
|
||||
- **A net delay after the type** (`wire [31:0] #0.1 x = y;`, where the LRM
|
||||
puts it) is accepted and printed where it was written.
|
||||
- Documentation: the repository analysis audit's README and site rewrite
|
||||
(architecture across all eight crates, topo facts at codec 17) is
|
||||
committed; its three findings are planned as TODO §41–§43.
|
||||
|
||||
## 0.41.0 — 2026-09-04
|
||||
|
||||
### Code actions off the fan-out
|
||||
|
||||
Generated
+10
-8
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.41.0"
|
||||
version = "0.46.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.41.0"
|
||||
version = "0.46.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.41.0"
|
||||
version = "0.46.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -248,15 +248,16 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.41.0"
|
||||
version = "0.46.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.41.0"
|
||||
version = "0.46.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
@@ -264,19 +265,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.41.0"
|
||||
version = "0.46.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.41.0"
|
||||
version = "0.46.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.41.0"
|
||||
version = "0.46.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -12,7 +12,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.41.0"
|
||||
version = "0.46.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -2,6 +2,12 @@
|
||||
|
||||
A Verilog and SystemVerilog formatter, linter, and language server written in Rust.
|
||||
|
||||
Start with the [repository analysis](docs/repository-analysis.md) for a code-based
|
||||
assessment and [dependency topology](docs/topo.md) for interfaces and change
|
||||
impact. The [documentation site source](docs/site/README.md) contains usage
|
||||
guides and references; [CHANGELOG.md](CHANGELOG.md) records releases, and
|
||||
[TODO.md](TODO.md) tracks work in progress.
|
||||
|
||||
An opinionated, fast formatter and linter for Verilog-2001 and SystemVerilog
|
||||
RTL, built in the image of [ruff](https://github.com/astral-sh/ruff), with
|
||||
layout conventions and lint ergonomics borrowed from
|
||||
@@ -106,6 +112,12 @@ trailing `/` (matches directories only), and `!` negation. **Not** supported:
|
||||
git's "already-tracked files are never ignored" rule. See
|
||||
`docs/features/parallel-files/README.md` for the exact subset.
|
||||
|
||||
Directory walks enter each directory once by identity, so symlink cycles
|
||||
terminate. Inputs resolving to one canonical file path are processed once.
|
||||
Unreadable directories or `.gitignore` files and dangling source links found
|
||||
during a walk warn on stderr and are skipped without changing the exit code;
|
||||
a missing explicitly named input is still an error.
|
||||
|
||||
## Configuration
|
||||
|
||||
Settings live in a `lucisv.toml` (or `.lucisv.toml`) file, ruff-style. For each
|
||||
@@ -160,9 +172,9 @@ with a file that sets only `line-length` uses both). `exclude` is the
|
||||
exception: config patterns are *added* to `--exclude`, not replaced by it.
|
||||
|
||||
An unknown key, a bad value, an out-of-range number, or any TOML beyond the
|
||||
supported subset (tables other than `[lint]`, multi-line arrays, string
|
||||
escapes) is a hard error naming the file and line — exit 2, with nothing
|
||||
written. This is deliberate:
|
||||
supported subset (tables other than `[lint]` and `[lint.<rule>]`, multi-line
|
||||
arrays, unsupported string escapes) is a hard error naming the file and
|
||||
line — exit 2, with nothing written. This is deliberate:
|
||||
a silently ignored `line_length` typo costs more than a strict parser does.
|
||||
|
||||
## Linting
|
||||
@@ -387,13 +399,61 @@ wire a; // lucisv: waive no-tabs suppresses that rule on this line
|
||||
works unedited — including waivers naming Verible rules lucisv has not
|
||||
implemented, which are ignored rather than reported. A waiver of lucisv's own
|
||||
that suppresses nothing, names an unknown rule or is malformed is reported
|
||||
under `unused-waiver`. External waiver files are not supported. Full rules:
|
||||
under `unused-waiver`.
|
||||
|
||||
Findings can also be suppressed from **outside** the RTL, in Verible's
|
||||
waiver-file format — one directive per line, `#` comments and blank lines
|
||||
ignored:
|
||||
|
||||
```text
|
||||
# every line of every file
|
||||
waive --rule=no-tabs
|
||||
# one line, or a range with both ends included
|
||||
waive --rule=line-length --line=12
|
||||
waive --rule=line-length --line=12-20
|
||||
# only the files a pattern names
|
||||
waive --rule=no-tabs --location=legacy/top.sv
|
||||
```
|
||||
|
||||
`--rule` is required and names exactly one rule (a severity word is not
|
||||
accepted). `--line` is 1-based. `--location` is matched the way an
|
||||
`--exclude` pattern is — `*` within one path component, a pattern with `/`
|
||||
matching a path suffix, one without matching the file name at any depth — and
|
||||
**not** as a regular expression; a pattern that looks like one (`.*`, `\.`,
|
||||
`[…]`) is an error naming the difference.
|
||||
|
||||
Waiver files come from three places, and they add up: `lucisv check
|
||||
--waiver-file <path>` (repeatable, relative to the working directory),
|
||||
`waivers` under `[lint]` in `lucisv.toml` (relative to that file; read by the
|
||||
CLI and the editor), and the editor setting `lucisv.lint.waivers` (relative to
|
||||
the first workspace folder). External and inline waivers are a union: a
|
||||
finding either covers is suppressed, and one both cover leaves neither
|
||||
reported as dead. A missing file or an unparsable directive fails `lucisv
|
||||
check` with `<file>:<line>: <message>` and exit 2; in an editor the bad line
|
||||
is dropped and the rest of the file applies, and the bad line is written once
|
||||
to the lucisv log whether the file was named by the editor setting or by
|
||||
`lucisv.toml`. Unused external waivers
|
||||
are reported under `unused-waiver` at their line of the waiver file, by
|
||||
`lucisv check` only and only after the whole run.
|
||||
Both front ends read the same configuration, and the editor's settings play
|
||||
the role the CLI's flags play: `lucisv.lint.select` when it is set, else
|
||||
`[lint] select` from the buffer's `lucisv.toml`, else the default set — and
|
||||
the same for `ignore`, decided independently. `lucisv.lint.severity.*` and
|
||||
`lucisv.lint.rules.*` have no project counterpart and apply over whichever
|
||||
selection stands. Project per-rule options are read by both front ends. A
|
||||
project entry lucisv cannot use — an unknown rule name in `[lint]
|
||||
select`/`ignore`, a rejected `[lint.<rule>]` option, an unreadable waiver
|
||||
file or a directive that does not parse — fails `lucisv check` with
|
||||
`<file>:<line>: <message>` and exit 2; in an editor it is dropped, written
|
||||
once to the lucisv log in the same words, and everything lucisv did
|
||||
understand still lints the buffer. Full rules:
|
||||
`docs/features/linter-core/README.md`.
|
||||
|
||||
## Architecture (the ruff mapping)
|
||||
|
||||
The workspace mirrors ruff's crate layout — a comment-preserving parser, a
|
||||
generic pretty-printing IR, language formatting rules, and a thin CLI:
|
||||
The eight-crate workspace separates source syntax, reusable engines, project
|
||||
inputs, and the CLI/LSP front ends. The formatter follows ruff's separation
|
||||
of document layout from language rules:
|
||||
|
||||
| This repo | ruff equivalent | Role |
|
||||
|---|---|---|
|
||||
@@ -401,7 +461,20 @@ generic pretty-printing IR, language formatting rules, and a thin CLI:
|
||||
| `crates/vlog_formatter/src/{doc,printer}.rs` | `ruff_formatter` | Wadler/prettier-style document IR (`Text`/`Line`/`Group`/`Indent`) + width-aware printer |
|
||||
| `crates/vlog_formatter/src/format/` | `ruff_python_formatter` | Per-node formatting rules, one module per grammar domain (`item`, `module`, `instance`, `decl`, `stmt`, `expr`, `class`, `cover`, `sva`, …) |
|
||||
| `crates/vlog_linter` | `ruff_linter` | Rule registry, violations, fix applicability, waivers |
|
||||
| `crates/lucisv` | the `ruff` CLI | File discovery, in-place rewriting, `--check`, `check`, stdin mode |
|
||||
| `crates/vlog_semantic` | — | File scopes and references, workspace index, conservative cross-file resolution |
|
||||
| `crates/vlog_refactor` | — | Verified rename, references, port refactors, instantiation plans |
|
||||
| `crates/lucisv_core` | — | Shared config, filelists, walks, format cache, atomic replacement |
|
||||
| `crates/lucisv` | the `ruff` CLI | Parallel per-file formatting/linting, reports, stdin, in-place writes |
|
||||
| `crates/lucisv_server` | — | Synchronous LSP loop, open-buffer overlays, indexing, editor capabilities |
|
||||
|
||||
`vlog_parser` and `lucisv_core` have no dependencies. The formatter depends
|
||||
only on the parser; semantic analysis also depends only on the parser.
|
||||
Linting consumes the parser, semantics and `lucisv_core` (for the one
|
||||
`--exclude`-style matcher a waiver file's `--location` shares with the CLI);
|
||||
refactoring consumes the parser and semantics. The CLI reaches
|
||||
semantics through the linter and has no refactoring dependency. The server
|
||||
composes all six libraries. See [topo.md](docs/topo.md) for the full graph,
|
||||
including the linter's formatter dependency used only by tests.
|
||||
|
||||
Key ideas carried over from ruff/prettier:
|
||||
|
||||
@@ -414,8 +487,15 @@ Key ideas carried over from ruff/prettier:
|
||||
lists, expressions, concatenations) is a `Group`: it renders on one line if
|
||||
it fits within the line limit, otherwise it breaks one-element-per-line.
|
||||
A comment inside a group forces it to break.
|
||||
- **Idempotency as a hard invariant.** The test suite formats every fixture
|
||||
twice and asserts a fixed point.
|
||||
- **Verification on every formatting call.** The engine re-lexes input and
|
||||
output and compares normalized tokens, including comments. It then parses
|
||||
and formats the output again and requires a fixed point. Either check can
|
||||
reject the result; the caller retains the original file. This is a lexical
|
||||
safety net, not compiler elaboration or a proof of hardware equivalence.
|
||||
- **Two parsing modes.** Formatting uses strict parsing. Linting and the
|
||||
editor use tolerant parsing: failed elements become error leaves while
|
||||
valid siblings remain available for analysis. A lexer failure is still
|
||||
all-or-nothing. Neither mode performs cross-file macro expansion.
|
||||
|
||||
## Style
|
||||
|
||||
@@ -871,8 +951,11 @@ vim.lsp.enable('lucisv')
|
||||
**Which files the server indexes.** A filelist if the project has one — the
|
||||
`filelist` key of its `lucisv.toml`, or the editor setting `lucisv.filelist`
|
||||
(a path, absolute or relative to the workspace folder) — and then exactly the
|
||||
files it names. Otherwise the workspace folder, walked as the CLI walks it;
|
||||
and with no folder open at all, the current file's own directory. Open buffers
|
||||
files it names. Otherwise the default `lucisv.index.scope = "folder"` starts
|
||||
from open-file folders, widens by `lucisv.index.scopeDepth` (default 2), and stays bounded by
|
||||
the workspace roots; `"workspace"` walks the full roots. With no folder open,
|
||||
the server stays in the current file's directory: depth 0 scans it flat; a
|
||||
positive depth walks its descendants but never climbs to a parent. Open buffers
|
||||
are always indexed on top. A filelist that cannot be read warns and falls back
|
||||
to the folder walk, so the index is never silently empty.
|
||||
|
||||
@@ -903,11 +986,20 @@ expected; no PRs or review required.
|
||||
|
||||
```bash
|
||||
cargo build --release # binaries at target/release/{lucisv,lucisv-server}
|
||||
cargo test # unit + snapshot + idempotency tests
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
tools/guard.sh -- cargo test --workspace # unit, integration, snapshots, doc tests
|
||||
```
|
||||
|
||||
Snapshot tests live in `crates/vlog_formatter/tests/fixtures/`; regenerate
|
||||
expected outputs with `UPDATE_SNAPSHOTS=1 cargo test -p vlog_formatter`.
|
||||
expected outputs only for intentional formatting changes with
|
||||
`UPDATE_SNAPSHOTS=1 tools/guard.sh -- cargo test -p vlog_formatter`.
|
||||
Table-driven cases live in `crates/vlog_formatter/tests/cases/`; lint cases
|
||||
live in `crates/vlog_linter/tests/cases/`. All tests, fuzzers, and corpus/tree
|
||||
sweeps must run through `tools/guard.sh` (8 GiB RSS / 30 minutes by default),
|
||||
as required by [CLAUDE.md](CLAUDE.md). A guard kill is a finding, not a reason
|
||||
to increase the limit. Documentation build instructions are in
|
||||
[docs/site/README.md](docs/site/README.md).
|
||||
|
||||
## Install and releases
|
||||
|
||||
|
||||
@@ -71,6 +71,12 @@ pub struct Options {
|
||||
pub select: Vec<String>,
|
||||
/// `check` only: rules to drop from whatever `--select` left.
|
||||
pub ignore: Vec<String>,
|
||||
/// `check` only: external waiver files, relative to the current
|
||||
/// directory. They *add* to whatever `[lint] waivers` in a `lucisv.toml`
|
||||
/// names — a waiver file suppresses findings and can only ever suppress
|
||||
/// fewer of them by being left out, so there is nothing here for a
|
||||
/// command line flag to override.
|
||||
pub waiver_files: Vec<String>,
|
||||
/// `check` only: print the generated rule reference and exit, reading no
|
||||
/// file at all.
|
||||
pub rules_doc: bool,
|
||||
@@ -203,6 +209,9 @@ CHECK OPTIONS (`lucisv check` only):
|
||||
--fix apply safe fixes and write the files back
|
||||
--unsafe-fixes let --fix apply unsafe fixes too (no rule ships
|
||||
one yet, so today this changes nothing)
|
||||
--waiver-file <PATH> read waiver directives from this file; may be
|
||||
repeated, and adds to whatever `[lint] waivers`
|
||||
in a lucisv.toml already names
|
||||
--rules-doc print the rule reference — every rule, what it
|
||||
reports and whether it has a fix — as Markdown on
|
||||
stdout and exit 0. Generated from the registry, so
|
||||
@@ -215,6 +224,31 @@ CHECK OPTIONS (`lucisv check` only):
|
||||
accepted in place of `lucisv:`. A waiver that suppresses nothing is
|
||||
reported under the `unused-waiver` rule.
|
||||
|
||||
WAIVER FILES:
|
||||
Findings can also be suppressed from outside the RTL, in Verible's waiver
|
||||
file format — one directive per line, `#` comments and blank lines ignored:
|
||||
|
||||
waive --rule=<rule> every line of every file
|
||||
waive --rule=<rule> --line=12 one line
|
||||
waive --rule=<rule> --line=12-20 a range, both ends included
|
||||
waive --rule=<rule> --location=legacy.sv the files that pattern names
|
||||
|
||||
`--rule` is required and names one rule (a severity word is not accepted);
|
||||
`--line` is 1-based and a range includes both ends; `--location` is matched
|
||||
the way an `--exclude` pattern is — `*` within one path component, a
|
||||
pattern with `/` against a path suffix and one without against the file
|
||||
name. Unlike Verible's, it is **not** a regular expression, and a pattern
|
||||
that looks like one is an error rather than a silent mismatch.
|
||||
|
||||
lucisv reads `--waiver-file <PATH>` (relative to the current directory) and
|
||||
every path in `waivers` under `[lint]` in a `lucisv.toml` (relative to that
|
||||
file). An external waiver and an inline one are a union: a finding either
|
||||
covers is suppressed, and neither is then reported as dead. A file that
|
||||
does not exist, or a directive that does not parse, fails the run with
|
||||
`<file>:<line>: message` and exit 2. An external waiver that suppressed
|
||||
nothing anywhere in the run is reported under `unused-waiver`, at the line
|
||||
of the waiver file it was written on.
|
||||
|
||||
IGNORE FILES:
|
||||
While walking a directory, lucisv reads a `.gitignore` in every directory it
|
||||
enters and skips what it names; a deeper file overrides a shallower one and
|
||||
@@ -250,8 +284,11 @@ CONFIGURATION:
|
||||
read by lucisv-server only — the CLI reads a filelist only when `-f` names
|
||||
one, so `lucisv rtl/` always means the directory it was given). One table
|
||||
is recognized, `[lint]`, with `select` and `ignore` (arrays of rule names,
|
||||
`--select`/`--ignore` semantics). A command line flag overrides the file's
|
||||
corresponding key; the other keys still apply.
|
||||
`--select`/`--ignore` semantics) and `waivers` (an array of waiver file
|
||||
paths, resolved against the config file's own directory). A command line
|
||||
flag overrides the file's corresponding key; the other keys still apply —
|
||||
`--waiver-file` is the exception, and adds to `waivers` rather than
|
||||
replacing it.
|
||||
|
||||
RANGE FORMATTING:
|
||||
`--lines` formats one construct at a time: an item whose lines meet a range
|
||||
@@ -298,6 +335,7 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
unsafe_fixes: false,
|
||||
select: Vec::new(),
|
||||
ignore: Vec::new(),
|
||||
waiver_files: Vec::new(),
|
||||
rules_doc: false,
|
||||
inputs: Vec::new(),
|
||||
filelists: Vec::new(),
|
||||
@@ -378,6 +416,10 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
let v = args.next().ok_or("--ignore requires a value")?;
|
||||
opts.ignore.extend(split_rules(&v));
|
||||
}
|
||||
"--waiver-file" => {
|
||||
let v = args.next().ok_or("--waiver-file requires a value")?;
|
||||
opts.waiver_files.push(v);
|
||||
}
|
||||
"--rules-doc" => opts.rules_doc = true,
|
||||
"-h" | "--help" => {
|
||||
print_help();
|
||||
@@ -444,6 +486,7 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
|
||||
(opts.output_format != OutputFormat::Text, "--output-format"),
|
||||
(!opts.select.is_empty(), "--select"),
|
||||
(!opts.ignore.is_empty(), "--ignore"),
|
||||
(!opts.waiver_files.is_empty(), "--waiver-file"),
|
||||
(opts.rules_doc, "--rules-doc"),
|
||||
];
|
||||
let format_only = [
|
||||
@@ -614,6 +657,16 @@ mod tests {
|
||||
assert!(parse(&["--no-gitignore", "rtl"]).unwrap().no_gitignore);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn waiver_files_are_collected_in_order_and_are_lint_only() {
|
||||
let opts = parse(&["check", "--waiver-file", "a.waiver", "--waiver-file", "b", "rtl"])
|
||||
.expect("parsed");
|
||||
assert_eq!(opts.waiver_files, vec!["a.waiver", "b"]);
|
||||
assert!(parse(&["check", "rtl"]).unwrap().waiver_files.is_empty());
|
||||
assert!(parse(&["check", "--waiver-file"]).is_err(), "a value is required");
|
||||
assert!(parse(&["--waiver-file", "a.waiver", "rtl"]).is_err(), "not a formatter flag");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_doc_is_the_one_check_that_needs_no_input() {
|
||||
assert!(parse(&["check", "--rules-doc"]).unwrap().rules_doc);
|
||||
|
||||
+163
-40
@@ -16,7 +16,8 @@ use vlog_formatter::fence::{self, Region};
|
||||
use vlog_formatter::Config;
|
||||
use vlog_linter::words;
|
||||
use vlog_linter::{
|
||||
apply_fixes, lint, Fix, MentionOracle, ParsedSource, Rule, RuleOptions, Violation,
|
||||
apply_fixes, lint_with, ExternalWaivers, Fix, MentionOracle, ParsedSource, Rule, RuleOptions,
|
||||
Violation, WaiverUse,
|
||||
};
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
@@ -46,6 +47,15 @@ pub struct Plan {
|
||||
/// The project's identifier census, built when at least one selected rule
|
||||
/// asks for a workspace and there is more than one file to ask about.
|
||||
census: Option<Census>,
|
||||
/// Every external waiver file the run reads, applied to every job.
|
||||
///
|
||||
/// One set for the whole run rather than one per file, because a
|
||||
/// `--location` pattern names files and a waiver is only *unused* when no
|
||||
/// file in the run matched it — a question only the whole run can answer.
|
||||
external: ExternalWaivers,
|
||||
/// Every rule name any job in the run has switched on, for deciding which
|
||||
/// external waivers never had a chance to fire.
|
||||
enabled: Vec<&'static str>,
|
||||
}
|
||||
|
||||
/// How many of the run's files write each identifier down.
|
||||
@@ -163,6 +173,7 @@ impl MentionOracle for Elsewhere<'_> {
|
||||
/// already says about itself.
|
||||
pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Result<Plan, String> {
|
||||
let workspace = gathered.len() > 1;
|
||||
let external = external_waivers(opts, gathered.iter().map(|(_, _, file)| file))?;
|
||||
let mut jobs = Vec::with_capacity(gathered.len());
|
||||
for (path, config, file_config) in gathered {
|
||||
let select = pick(&opts.select, file_config.lint_select.as_deref());
|
||||
@@ -175,7 +186,56 @@ pub fn plan(opts: &Options, gathered: Vec<(PathBuf, Config, FileConfig)>) -> Res
|
||||
let wanted = jobs.iter().any(|job| job.rules.iter().any(|rule| rule.needs_workspace()));
|
||||
let interfaces = jobs.iter().any(|job| job.rules.iter().any(|rule| reads_interfaces(*rule)));
|
||||
let census = (workspace && wanted).then(|| Census::of(&jobs, workspace && interfaces));
|
||||
Ok(Plan { jobs, census })
|
||||
let mut enabled: Vec<&'static str> =
|
||||
jobs.iter().flat_map(|job| job.rules.iter().map(|rule| rule.name())).collect();
|
||||
enabled.sort_unstable();
|
||||
enabled.dedup();
|
||||
Ok(Plan { jobs, census, external, enabled })
|
||||
}
|
||||
|
||||
/// The run's external waiver files, read once each: `--waiver-file` in flag
|
||||
/// order, then every `[lint] waivers` entry of a config file governing an
|
||||
/// input.
|
||||
///
|
||||
/// The two **add up** rather than override: a waiver file only ever suppresses
|
||||
/// findings, so there is nothing for a command line to take back. A file named
|
||||
/// twice over — the flag and a `lucisv.toml`, or one `lucisv.toml` governing
|
||||
/// five hundred files — is read once, or its directives would each be reported
|
||||
/// unused as many times as the file was read.
|
||||
///
|
||||
/// A file that cannot be read, or a directive that does not parse, fails the
|
||||
/// run naming the file and the line, exactly as a bad `[lint.<rule>]` entry
|
||||
/// does and for the same reason: a user wrote it and is watching.
|
||||
pub fn external_waivers<'a>(
|
||||
opts: &Options,
|
||||
configs: impl Iterator<Item = &'a FileConfig>,
|
||||
) -> Result<ExternalWaivers, String> {
|
||||
let mut paths: Vec<PathBuf> = opts.waiver_files.iter().map(PathBuf::from).collect();
|
||||
for config in configs {
|
||||
for path in config.lint_waivers.iter().flatten() {
|
||||
paths.push(path.clone());
|
||||
}
|
||||
}
|
||||
let mut read: Vec<PathBuf> = Vec::new();
|
||||
let mut waivers = ExternalWaivers::default();
|
||||
for path in paths {
|
||||
// Compared canonically, because the flag's path is relative to the
|
||||
// working directory and a `lucisv.toml`'s is absolute: the same file
|
||||
// named both ways is still one file, and reading it twice would report
|
||||
// each of its dead directives twice. Only the *comparison* is
|
||||
// canonical — the path a diagnostic names stays the one written.
|
||||
let key = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
|
||||
if read.contains(&key) {
|
||||
continue;
|
||||
}
|
||||
let (file, problems) = ExternalWaivers::read(&path)?;
|
||||
if let Some(problem) = problems.first() {
|
||||
return Err(problem.clone());
|
||||
}
|
||||
waivers.absorb(file);
|
||||
read.push(key);
|
||||
}
|
||||
Ok(waivers)
|
||||
}
|
||||
|
||||
/// The `[lint.<rule>]` entries of one file's config, resolved against the
|
||||
@@ -234,12 +294,30 @@ struct Report {
|
||||
violations: Vec<Violation>,
|
||||
/// Violations whose fix was applied and written back.
|
||||
fixed: usize,
|
||||
/// Which of the run's external waivers suppressed something in this file.
|
||||
/// Merged across every file before the dead ones are reported.
|
||||
used: WaiverUse,
|
||||
/// Set when the file could not be fully checked: unreadable, unwritable,
|
||||
/// or — because the lexer is all-or-nothing — unlexable, in which case
|
||||
/// only the text-level rules saw it.
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
/// Everything one file's lint pass reads besides the file itself.
|
||||
///
|
||||
/// One value rather than six parameters: every function below the driver
|
||||
/// needs the same set, and the `--fix` loop passes it down another level
|
||||
/// again.
|
||||
struct Pass<'a> {
|
||||
config: &'a Config,
|
||||
rules: &'a [&'static dyn Rule],
|
||||
options: &'a RuleOptions,
|
||||
census: Option<&'a Census>,
|
||||
/// The run's external waiver files. Empty unless `--waiver-file` or a
|
||||
/// `[lint] waivers` named one, and then costing nothing.
|
||||
external: &'a ExternalWaivers,
|
||||
}
|
||||
|
||||
/// Lints every gathered file and reports. Exit 1 if anything is left over,
|
||||
/// 2 if a file could not be read, written, or lexed.
|
||||
pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
|
||||
@@ -247,9 +325,20 @@ pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
|
||||
.jobs
|
||||
.par_iter()
|
||||
.map(|job| {
|
||||
check_one(&job.path, &job.config, opts, &job.rules, &job.options, plan.census.as_ref())
|
||||
let pass = Pass {
|
||||
config: &job.config,
|
||||
rules: &job.rules,
|
||||
options: &job.options,
|
||||
census: plan.census.as_ref(),
|
||||
external: &plan.external,
|
||||
};
|
||||
check_one(&job.path, opts, &pass)
|
||||
})
|
||||
.collect();
|
||||
// The dead external waivers are found once every file has been linted,
|
||||
// and reported against the waiver file, which then sorts in among the
|
||||
// sources like any other path.
|
||||
reports.extend(dead_waivers(&plan.external, &reports, &plan.enabled));
|
||||
// Diagnostics are printed sorted by path, then by position within the
|
||||
// file (`lint` already sorts those), so a run over a directory reads
|
||||
// top to bottom whatever order the walk or the worker pool produced.
|
||||
@@ -257,6 +346,37 @@ pub fn check_files(opts: &Options, plan: &Plan) -> ExitCode {
|
||||
finish(opts, reports)
|
||||
}
|
||||
|
||||
/// The `unused-waiver` reports for external waivers no file in the run used.
|
||||
///
|
||||
/// **After the whole run**, which is the whole reason this is the CLI's job
|
||||
/// and not the linter's: a `--location` pattern may match a file the run has
|
||||
/// not reached yet, so a waiver is only dead once every file has been asked.
|
||||
fn dead_waivers(
|
||||
external: &ExternalWaivers,
|
||||
reports: &[Report],
|
||||
enabled: &[&'static str],
|
||||
) -> Vec<Report> {
|
||||
if external.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut used = WaiverUse::default();
|
||||
for report in reports {
|
||||
used.merge(&report.used);
|
||||
}
|
||||
external
|
||||
.unused(&used, enabled)
|
||||
.into_iter()
|
||||
.map(|dead| Report {
|
||||
path: dead.path.display().to_string(),
|
||||
index: LineIndex::new(&dead.text),
|
||||
violations: dead.violations,
|
||||
fixed: 0,
|
||||
used: WaiverUse::default(),
|
||||
error: None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Lints a buffer piped in on stdin. `--stdin-filename` names it, and is
|
||||
/// what the rules that need a file name see.
|
||||
pub fn check_stdin(
|
||||
@@ -265,32 +385,34 @@ pub fn check_stdin(
|
||||
config: &Config,
|
||||
rules: &[&'static dyn Rule],
|
||||
options: &RuleOptions,
|
||||
external: &ExternalWaivers,
|
||||
) -> ExitCode {
|
||||
let name = opts.stdin_filename.clone().unwrap_or_else(|| "<stdin>".to_string());
|
||||
let path = opts.stdin_filename.as_ref().map(PathBuf::from);
|
||||
let (violations, lex_error) = run_rules(src, path, config, rules, options, None);
|
||||
let pass = Pass { config, rules, options, census: None, external };
|
||||
let (violations, used, lex_error) = run_rules(src, path, &pass);
|
||||
// Nothing is ever written back for stdin, so `--fix` has nothing to do
|
||||
// here; the violations are reported as they are.
|
||||
let error = lex_error.map(|e| format!("{name}: {e}"));
|
||||
let report = Report { path: name, index: LineIndex::new(src), violations, fixed: 0, error };
|
||||
finish(opts, vec![report])
|
||||
let report =
|
||||
Report { path: name, index: LineIndex::new(src), violations, fixed: 0, used, error };
|
||||
// One buffer is a whole run too, so a waiver that covered nothing in it is
|
||||
// as dead as one that covered nothing in a directory.
|
||||
let names: Vec<&'static str> = rules.iter().map(|rule| rule.name()).collect();
|
||||
let mut reports = vec![report];
|
||||
reports.extend(dead_waivers(external, &reports, &names));
|
||||
finish(opts, reports)
|
||||
}
|
||||
|
||||
/// Lints one file, optionally fixing it, and never panics out of its worker.
|
||||
fn check_one(
|
||||
file: &Path,
|
||||
config: &Config,
|
||||
opts: &Options,
|
||||
rules: &[&'static dyn Rule],
|
||||
options: &RuleOptions,
|
||||
census: Option<&Census>,
|
||||
) -> Report {
|
||||
fn check_one(file: &Path, opts: &Options, pass: &Pass) -> Report {
|
||||
let path = file.display().to_string();
|
||||
let failed = |error: String| Report {
|
||||
path: path.clone(),
|
||||
index: LineIndex::new(""),
|
||||
violations: Vec::new(),
|
||||
fixed: 0,
|
||||
used: WaiverUse::default(),
|
||||
error: Some(error),
|
||||
};
|
||||
|
||||
@@ -300,14 +422,13 @@ fn check_one(
|
||||
};
|
||||
let outcome = crate::catch_panic(|| {
|
||||
if opts.fix {
|
||||
fix_source(&src, file, config, opts, rules, options, census)
|
||||
fix_source(&src, file, opts, pass)
|
||||
} else {
|
||||
let (violations, lex_error) =
|
||||
run_rules(&src, Some(file.to_path_buf()), config, rules, options, census);
|
||||
(violations, None, 0, lex_error)
|
||||
let (violations, used, lex_error) = run_rules(&src, Some(file.to_path_buf()), pass);
|
||||
(violations, used, None, 0, lex_error)
|
||||
}
|
||||
});
|
||||
let (violations, rewritten, fixed, lex_error) = match outcome {
|
||||
let (violations, used, rewritten, fixed, lex_error) = match outcome {
|
||||
Ok(outcome) => outcome,
|
||||
Err(msg) => return failed(format!("{path}: panicked while linting: {msg}")),
|
||||
};
|
||||
@@ -322,21 +443,20 @@ fn check_one(
|
||||
// so the file must not pass as checked. It is an error (exit 2), exactly
|
||||
// as `lucisv format` treats the same file.
|
||||
let error = lex_error.map(|e| format!("{path}: {e}"));
|
||||
Report { path, index, violations, fixed, error }
|
||||
Report { path, index, violations, fixed, used, error }
|
||||
}
|
||||
|
||||
/// Runs the rules over one text. The second half of the answer is the lex
|
||||
/// error when the text does not lex — rendered `line:col: message`, ready
|
||||
/// for a path prefix — because a file with no tokens was only text-linted
|
||||
/// and must be reported as an error, not passed off as clean.
|
||||
/// Runs the rules over one text, reporting which external waivers fired. The
|
||||
/// last part of the answer is the lex error when the text does not lex —
|
||||
/// rendered `line:col: message`, ready for a path prefix — because a file with
|
||||
/// no tokens was only text-linted and must be reported as an error, not passed
|
||||
/// off as clean.
|
||||
fn run_rules(
|
||||
src: &str,
|
||||
path: Option<PathBuf>,
|
||||
config: &Config,
|
||||
rules: &[&'static dyn Rule],
|
||||
options: &RuleOptions,
|
||||
census: Option<&Census>,
|
||||
) -> (Vec<Violation>, Option<String>) {
|
||||
pass: &Pass,
|
||||
) -> (Vec<Violation>, WaiverUse, Option<String>) {
|
||||
let Pass { config, rules, options, census, external } = *pass;
|
||||
// One parse per file (TODO §4): the products are built here, once, and
|
||||
// lent to the context. Under `--fix` each *round* re-enters through this
|
||||
// function with rewritten text — that re-parse is inherent (the old
|
||||
@@ -360,7 +480,8 @@ fn run_rules(
|
||||
Some(elsewhere) => ctx.with_oracle(elsewhere),
|
||||
None => ctx,
|
||||
};
|
||||
(lint(&ctx, rules), lex_error)
|
||||
let (violations, used) = lint_with(&ctx, rules, external);
|
||||
(violations, used, lex_error)
|
||||
}
|
||||
|
||||
/// The violations whose fix may be applied: everything except a fix that
|
||||
@@ -399,16 +520,15 @@ fn touches_fence(fix: &Fix, regions: &[Region]) -> bool {
|
||||
fn fix_source(
|
||||
src: &str,
|
||||
file: &Path,
|
||||
config: &Config,
|
||||
opts: &Options,
|
||||
rules: &[&'static dyn Rule],
|
||||
options: &RuleOptions,
|
||||
census: Option<&Census>,
|
||||
) -> (Vec<Violation>, Option<String>, usize, Option<String>) {
|
||||
pass: &Pass,
|
||||
) -> (Vec<Violation>, WaiverUse, Option<String>, usize, Option<String>) {
|
||||
let mut text = src.to_string();
|
||||
let mut fixed = 0;
|
||||
let (mut violations, mut lex_error) =
|
||||
run_rules(&text, Some(file.to_path_buf()), config, rules, options, census);
|
||||
let mut used = WaiverUse::default();
|
||||
let (mut violations, mut round_used, mut lex_error) =
|
||||
run_rules(&text, Some(file.to_path_buf()), pass);
|
||||
used.merge(&round_used);
|
||||
for _ in 0..MAX_FIX_ROUNDS {
|
||||
let round =
|
||||
apply_fixes(&text, &fixable_outside_fences(&text, &violations), opts.unsafe_fixes);
|
||||
@@ -417,11 +537,14 @@ fn fix_source(
|
||||
}
|
||||
fixed += round.applied;
|
||||
text = round.output;
|
||||
(violations, lex_error) =
|
||||
run_rules(&text, Some(file.to_path_buf()), config, rules, options, census);
|
||||
(violations, round_used, lex_error) = run_rules(&text, Some(file.to_path_buf()), pass);
|
||||
// A waiver that covered a finding in an earlier round did its job even
|
||||
// though the fix then removed the finding, so usage accumulates over
|
||||
// the rounds rather than being the last round's.
|
||||
used.merge(&round_used);
|
||||
}
|
||||
let rewritten = (text != src).then_some(text);
|
||||
(violations, rewritten, fixed, lex_error)
|
||||
(violations, used, rewritten, fixed, lex_error)
|
||||
}
|
||||
|
||||
/// Prints the run and turns it into an exit code.
|
||||
|
||||
@@ -128,7 +128,17 @@ fn run_check(opts: &Options) -> ExitCode {
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
return lint::check_stdin(opts, &src, &config, &rules, &options);
|
||||
// A stdin buffer has one config file too — the one governing
|
||||
// `--stdin-filename`, or the working directory's — so `[lint] waivers`
|
||||
// reaches it exactly as `[lint] select` does.
|
||||
let external = match lint::external_waivers(opts, std::iter::once(&file_config)) {
|
||||
Ok(external) => external,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
return lint::check_stdin(opts, &src, &config, &rules, &options, &external);
|
||||
}
|
||||
let jobs = match gather(opts).and_then(|jobs| build_pool(opts).map(|()| jobs)) {
|
||||
Ok(jobs) => jobs,
|
||||
@@ -356,7 +366,12 @@ fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config, FileConfig)>, String>
|
||||
return Err(format!("--lines needs a file, not a directory: {input}"));
|
||||
}
|
||||
let exclude = opts.exclude_with(&discovery.for_input(Path::new(input))?);
|
||||
collect_files(input, &exclude, !opts.no_gitignore, &mut files)?;
|
||||
// The walk's own warnings — an unreadable directory, a source file
|
||||
// that is only a broken link — go to stderr as they are found, before
|
||||
// the report and exactly as a filelist's do. A warning is not a
|
||||
// failure: the exit code is the formatting's alone.
|
||||
let mut warn = |w| eprintln!("warning: {w}");
|
||||
collect_files(input, &exclude, !opts.no_gitignore, &mut files, &mut warn)?;
|
||||
}
|
||||
// Filelists come after the command line's own inputs, in flag order: they
|
||||
// add files, they never replace or reorder what was named directly.
|
||||
@@ -405,13 +420,25 @@ fn filelist_files(opts: &Options) -> Result<Vec<PathBuf>, String> {
|
||||
fn dedup(files: Vec<PathBuf>) -> Vec<PathBuf> {
|
||||
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
|
||||
let mut seen = HashSet::new();
|
||||
files.into_iter().filter(|file| seen.insert(absolute(&cwd, file))).collect()
|
||||
files.into_iter().filter(|file| seen.insert(identity(&cwd, file))).collect()
|
||||
}
|
||||
|
||||
/// The key two spellings of one file share: the file's canonical path when it
|
||||
/// is there, and the lexical fold when it is not.
|
||||
///
|
||||
/// Canonical means symlinks resolved, which is the only way to see that
|
||||
/// `b.sv -> a.sv` is the file `a.sv` already named — two rayon workers on one
|
||||
/// target otherwise, each rewriting what the other just wrote. A path with no
|
||||
/// file behind it has no canonical form, and the lexical fold is then the
|
||||
/// best two names for it can be compared by. Neither is ever the path lucisv
|
||||
/// reports: that stays the first spelling seen.
|
||||
fn identity(cwd: &Path, path: &Path) -> PathBuf {
|
||||
std::fs::canonicalize(path).unwrap_or_else(|_| absolute(cwd, path))
|
||||
}
|
||||
|
||||
/// `path` folded to the absolute, `.`/`..`-free spelling two names for one
|
||||
/// file share. Lexical, like `lucisv_core`'s own normalization: symlinks are
|
||||
/// deliberately left unresolved, so this is only ever a dedup key and never
|
||||
/// the path lucisv reports.
|
||||
/// file share. Purely lexical, like `lucisv_core`'s own normalization — it
|
||||
/// answers for paths that do not exist, where there is nothing to resolve.
|
||||
fn absolute(cwd: &Path, path: &Path) -> PathBuf {
|
||||
let joined = if path.is_absolute() { path.to_path_buf() } else { cwd.join(path) };
|
||||
let mut out = PathBuf::new();
|
||||
@@ -592,6 +619,37 @@ mod tests {
|
||||
assert_eq!(dedup(files), [cwd.join("rtl/a.sv")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dedup_folds_a_symlink_onto_the_file_it_points_at() {
|
||||
// A directory walk lists `b.sv` as a file of its own; lexically the
|
||||
// two names share nothing, and two workers would rewrite one file.
|
||||
let dir = std::env::temp_dir().join(format!("lucisv-dedup-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
let real = dir.join("a.sv");
|
||||
let link = dir.join("b.sv");
|
||||
std::fs::write(&real, "module m;\nendmodule\n").expect("seed");
|
||||
std::os::unix::fs::symlink(&real, &link).expect("symlink");
|
||||
|
||||
assert_eq!(dedup(vec![real.clone(), link.clone()]), std::slice::from_ref(&real));
|
||||
// Whichever spelling comes first is the one kept and reported.
|
||||
assert_eq!(dedup(vec![link.clone(), real.clone()]), std::slice::from_ref(&link));
|
||||
// And a `..` detour through the same link is still the same file.
|
||||
std::fs::create_dir(dir.join("sub")).expect("sub dir");
|
||||
let detour = dir.join("sub/../b.sv");
|
||||
assert_eq!(dedup(vec![real.clone(), detour]), std::slice::from_ref(&real));
|
||||
|
||||
// A file that is not there has no canonical path: the key is lexical,
|
||||
// which still folds `.` and `..`, and two missing files stay two.
|
||||
let gone = dir.join("gone.sv");
|
||||
let same = dir.join("./sub/../gone.sv");
|
||||
let other = dir.join("other.sv");
|
||||
assert_eq!(dedup(vec![gone.clone(), same, other.clone()]), [gone, other]);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_contained_reports_parse_errors() {
|
||||
let err = format_contained("module", &Config::default(), None).unwrap_err();
|
||||
|
||||
@@ -136,6 +136,57 @@ fn formats_files_in_place() {
|
||||
assert!(stderr(&out).contains("2 files left unchanged"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
/// A directory walk lists a symlink as a file of its own, so `b.sv -> a.sv`
|
||||
/// used to put two workers on one file: two report lines for one file, and
|
||||
/// two writers racing to replace it. It is one file now, named once.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_symlink_and_its_target_are_one_file() {
|
||||
let dir = TempDir::new("alias");
|
||||
dir.write("a.sv", UNFORMATTED);
|
||||
std::os::unix::fs::symlink(dir.path.join("a.sv"), dir.path.join("b.sv")).expect("symlink");
|
||||
|
||||
let out = run(&["--check", &dir.root()]);
|
||||
assert_eq!(code(&out), 1, "{}", stderr(&out));
|
||||
let reported = stdout(&out);
|
||||
let named: Vec<&str> = reported.lines().filter(|l| l.contains("would reformat")).collect();
|
||||
assert_eq!(named.len(), 1, "one file, one line: {named:?}");
|
||||
assert!(named[0].ends_with("a.sv"), "the first spelling walked is the one reported: {named:?}");
|
||||
assert!(stderr(&out).contains("1 file would be reformatted"), "{}", stderr(&out));
|
||||
|
||||
let out = run(&[&dir.root()]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("1 file reformatted"), "{}", stderr(&out));
|
||||
assert_eq!(dir.read("a.sv"), FORMATTED);
|
||||
assert_eq!(dir.read("b.sv"), FORMATTED, "and the link still reaches it");
|
||||
assert!(
|
||||
std::fs::symlink_metadata(dir.path.join("b.sv")).expect("stat").file_type().is_symlink(),
|
||||
"the link was not replaced by a copy"
|
||||
);
|
||||
}
|
||||
|
||||
/// A directory that links back into itself. Before the walk kept a visited
|
||||
/// set (`docs/features/walk-cycles/README.md`) this run recursed until the
|
||||
/// OS refused the path; now each directory is entered once, so each file is
|
||||
/// named once — under the first spelling that reaches it.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_symlink_cycle_terminates_and_names_each_file_once() {
|
||||
let dir = TempDir::new("cycle");
|
||||
dir.write("rtl/a.sv", UNFORMATTED);
|
||||
dir.write("rtl/sub/b.sv", UNFORMATTED);
|
||||
// `rtl/self` is `rtl` itself; `rtl/sub/up` is `rtl` from one level down.
|
||||
std::os::unix::fs::symlink("../rtl", dir.path.join("rtl/self")).expect("symlink");
|
||||
std::os::unix::fs::symlink("..", dir.path.join("rtl/sub/up")).expect("symlink");
|
||||
|
||||
let out = run(&["--check", &dir.root()]);
|
||||
assert_eq!(code(&out), 1, "{}", stderr(&out));
|
||||
let reported = stdout(&out);
|
||||
let named: Vec<&str> = reported.lines().filter(|l| l.contains("would reformat")).collect();
|
||||
assert_eq!(named.len(), 2, "two files, two lines: {named:?}");
|
||||
assert!(stderr(&out).contains("2 files would be reformatted"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_reports_without_writing() {
|
||||
let dir = TempDir::new("check");
|
||||
@@ -935,6 +986,89 @@ fn check_honors_inline_waivers_and_reports_dead_ones() {
|
||||
assert!(stdout(&out).contains("[unused-waiver]"), "{}", stdout(&out));
|
||||
}
|
||||
|
||||
/// Two tabbed lines, one of which a waiver file's `--line` covers.
|
||||
const TABBED: &str = "module foo;\n\twire a;\n\twire b;\nendmodule\n";
|
||||
|
||||
/// `--waiver-file`: the suppression, the flag repeated, and the dead directive
|
||||
/// reported at the waiver file's own line. TODO §39.
|
||||
#[test]
|
||||
fn check_reads_external_waiver_files() {
|
||||
let dir = TempDir::new("check-waiver-file");
|
||||
let path = dir.write("foo.sv", TABBED);
|
||||
let one = dir.write("one.waiver", "# just line 2\nwaive --rule=no-tabs --line=2\n");
|
||||
let out = run(&["check", "--waiver-file", &one, &path]);
|
||||
assert_eq!(code(&out), 1, "{}", stdout(&out));
|
||||
assert_eq!(stdout(&out).lines().count(), 1, "one tab left: {}", stdout(&out));
|
||||
assert!(stdout(&out).contains("foo.sv:3:1"), "{}", stdout(&out));
|
||||
|
||||
// A second file adds to the first rather than replacing it, and both are
|
||||
// then used, so neither is reported.
|
||||
let two = dir.write("two.waiver", "waive --rule=no-tabs --line=3 --location=foo.sv\n");
|
||||
let out = run(&["check", "--waiver-file", &one, "--waiver-file", &two, &path]);
|
||||
assert_eq!(code(&out), 0, "{}", stdout(&out));
|
||||
|
||||
// A directive that covered nothing is reported against the waiver file.
|
||||
let dead = dir.write("dead.waiver", "waive --rule=no-tabs --location=elsewhere.sv\n");
|
||||
let out = run(&["check", "--waiver-file", &dead, &path]);
|
||||
assert_eq!(code(&out), 1);
|
||||
let text = stdout(&out);
|
||||
assert!(text.contains("dead.waiver:1:1: style: unused waiver for `no-tabs`"), "{text}");
|
||||
assert!(text.contains("[unused-waiver]"), "{text}");
|
||||
}
|
||||
|
||||
/// The `[lint] waivers` key, and that `--waiver-file` adds to it. TODO §39.
|
||||
#[test]
|
||||
fn check_reads_the_waiver_files_a_config_file_names() {
|
||||
let dir = TempDir::new("check-waiver-toml");
|
||||
let path = dir.write("rtl/foo.sv", TABBED);
|
||||
dir.write("lucisv.toml", "[lint]\nwaivers = [ \"project.waiver\" ]\n");
|
||||
dir.write("project.waiver", "waive --rule=no-tabs --line=2\n");
|
||||
// Relative to the config file, not to the working directory.
|
||||
let out = run_raw(&["check", "--no-cache", &path]);
|
||||
assert_eq!(code(&out), 1, "{}", stdout(&out));
|
||||
assert!(stdout(&out).contains("foo.sv:3:1"), "only line 3 survives: {}", stdout(&out));
|
||||
|
||||
let extra = dir.write("extra.waiver", "waive --rule=no-tabs --line=3\n");
|
||||
let out = run_raw(&["check", "--no-cache", "--waiver-file", &extra, &path]);
|
||||
assert_eq!(code(&out), 0, "the two lists add up: {}", stdout(&out));
|
||||
|
||||
// `--no-config` drops the config file's list with everything else in it.
|
||||
let out = run_raw(&["check", "--no-cache", "--no-config", &path]);
|
||||
assert_eq!(code(&out), 1);
|
||||
assert_eq!(stdout(&out).lines().count(), 2, "both tabs are back: {}", stdout(&out));
|
||||
}
|
||||
|
||||
/// A waiver file that cannot be read, or that has a line that does not parse,
|
||||
/// fails the run with `<file>:<line>: message` and exit 2. TODO §39.
|
||||
#[test]
|
||||
fn a_broken_waiver_file_fails_the_run() {
|
||||
let dir = TempDir::new("check-waiver-bad");
|
||||
let path = dir.write("foo.sv", TABBED);
|
||||
|
||||
let out = run(&["check", "--waiver-file", &dir.write("x.waiver", "hush\n"), &path]);
|
||||
assert_eq!(code(&out), 2, "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("x.waiver:1: expected a `waive` directive"), "{}", stderr(&out));
|
||||
|
||||
let bad = dir.write("y.waiver", "# fine\nwaive --rule=no-such-rule\n");
|
||||
let out = run(&["check", "--waiver-file", &bad, &path]);
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(stderr(&out).contains("y.waiver:2: unknown rule"), "{}", stderr(&out));
|
||||
|
||||
let regexy = dir.write("z.waiver", "waive --rule=no-tabs --location=.*foo.sv\n");
|
||||
let out = run(&["check", "--waiver-file", ®exy, &path]);
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(stderr(&out).contains("looks like a regular expression"), "{}", stderr(&out));
|
||||
|
||||
let out = run(&[
|
||||
"check",
|
||||
"--waiver-file",
|
||||
&dir.path.join("gone.waiver").display().to_string(),
|
||||
&path,
|
||||
]);
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(stderr(&out).contains("gone.waiver:"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_reads_stdin_and_names_it() {
|
||||
let out = run_with_stdin(&["check", "--stdin-filename", "rtl/z.sv", "-"], LINTY);
|
||||
@@ -2012,3 +2146,88 @@ fn rules_doc_refuses_files_and_belongs_to_check() {
|
||||
stderr(&out)
|
||||
);
|
||||
}
|
||||
|
||||
// --- the walk's own warnings (docs/features/small-items-4/README.md) -------
|
||||
|
||||
/// A tree with the two things the walk can only warn about: a directory it
|
||||
/// cannot read, and a source file that is only a broken link.
|
||||
#[cfg(unix)]
|
||||
fn unwalkable_tree(tag: &str) -> TempDir {
|
||||
use std::os::unix::fs::{symlink, PermissionsExt};
|
||||
let dir = TempDir::new(tag);
|
||||
dir.write("a.sv", UNFORMATTED);
|
||||
dir.write("z/late.sv", UNFORMATTED);
|
||||
dir.write("locked/hidden.sv", UNFORMATTED);
|
||||
symlink("nowhere.sv", dir.path.join("gone.sv")).expect("symlink");
|
||||
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o000))
|
||||
.expect("chmod");
|
||||
dir
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn lock(dir: &TempDir) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o000))
|
||||
.expect("chmod");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn unlock(dir: &TempDir) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let _ =
|
||||
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o755));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_unreadable_directory_is_a_warning_and_the_rest_of_the_tree_is_formatted() {
|
||||
// The finding TODO §45.2 closes: one permission-denied directory used to
|
||||
// propagate `read_dir`'s error and fail the whole run.
|
||||
let dir = unwalkable_tree("walk-warn");
|
||||
let out = run(&[&dir.root()]);
|
||||
unlock(&dir);
|
||||
|
||||
assert_eq!(code(&out), 0, "a warning is not a failure: {}", stderr(&out));
|
||||
let said = stderr(&out);
|
||||
assert_eq!(said.matches("warning: ").count(), 2, "{said}");
|
||||
assert!(said.contains("locked"), "{said}");
|
||||
assert!(said.contains("gone.sv: broken symbolic link"), "{said}");
|
||||
assert_eq!(dir.read("a.sv"), FORMATTED, "the other files were formatted");
|
||||
assert_eq!(dir.read("z/late.sv"), FORMATTED, "including the ones sorted after it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn the_walks_warnings_leave_check_modes_exit_code_alone() {
|
||||
let dir = unwalkable_tree("walk-warn-check");
|
||||
let out = run(&["--check", &dir.root()]);
|
||||
unlock(&dir);
|
||||
|
||||
// `--check` answers on formatting alone: two files would be reformatted.
|
||||
assert_eq!(code(&out), 1, "{}", stderr(&out));
|
||||
assert_eq!(stderr(&out).matches("warning: ").count(), 2, "{}", stderr(&out));
|
||||
assert!(!stdout(&out).contains("warning"), "warnings stay off stdout: {}", stdout(&out));
|
||||
|
||||
// And with nothing left to reformat the run is clean, warnings and all.
|
||||
dir.write("a.sv", FORMATTED);
|
||||
dir.write("z/late.sv", FORMATTED);
|
||||
lock(&dir);
|
||||
let out = run(&["--check", &dir.root()]);
|
||||
unlock(&dir);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(stderr(&out).matches("warning: ").count(), 2, "{}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_dangling_source_link_named_on_the_command_line_is_still_an_error() {
|
||||
// The walk drops the link; a path the user typed is not walked at all, so
|
||||
// "no such file or directory" is still what naming one gets.
|
||||
let dir = TempDir::new("walk-warn-named");
|
||||
std::os::unix::fs::symlink("nowhere.sv", dir.path.join("gone.sv")).expect("symlink");
|
||||
let named = dir.path.join("gone.sv").to_string_lossy().into_owned();
|
||||
|
||||
let out = run(&[&named]);
|
||||
assert_eq!(code(&out), 2, "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("no such file or directory"), "{}", stderr(&out));
|
||||
}
|
||||
@@ -7,11 +7,24 @@
|
||||
//! gets the bytes, and a `rename` over the target publishes them in one step
|
||||
//! that either happened or did not.
|
||||
//!
|
||||
//! See `docs/features/small-items-3/README.md`.
|
||||
//! Two threads of one process may write one target: the temp names carry a
|
||||
//! per-process counter as well as the pid and are created with `O_EXCL`, so
|
||||
//! each writer owns its own file and neither can see the other's bytes.
|
||||
//!
|
||||
//! Two *processes* writing one target are not coordinated, and deliberately
|
||||
//! so. Both renames are atomic, the later one wins, and the loser's bytes are
|
||||
//! discarded whole — never merged. Both processes formatted the same input
|
||||
//! and `format` is idempotent, so whichever rename lands last leaves the
|
||||
//! file complete and correctly formatted. A lock would buy nothing and would
|
||||
//! be one more thing to leave behind after a `^C`.
|
||||
//!
|
||||
//! See `docs/features/small-items-3/README.md` and
|
||||
//! `docs/features/atomic-write-coordination/README.md`.
|
||||
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// Writes `bytes` to `path`, replacing whatever was there in one step.
|
||||
///
|
||||
@@ -21,6 +34,12 @@ use std::path::{Path, PathBuf};
|
||||
/// sees either the old file or the new one and never a truncated one. A
|
||||
/// failure anywhere after the temp exists removes it before returning.
|
||||
///
|
||||
/// The temp is the caller's alone: [`temp_path`] hands out a name no other
|
||||
/// writer in this process will be given, and the file is created with
|
||||
/// `create_new`, so a name that somehow exists is an error and not a shared
|
||||
/// file. Two threads writing one target therefore both succeed, and the
|
||||
/// target ends up holding one thread's whole buffer.
|
||||
///
|
||||
/// A symlinked target is resolved first: `fs::write` writes *through* a
|
||||
/// symlink, so replacing the link itself would silently redirect it at a new
|
||||
/// file and leave the real one stale. The canonical path is what gets
|
||||
@@ -28,26 +47,22 @@ use std::path::{Path, PathBuf};
|
||||
/// filesystem — `rename` cannot cross one.
|
||||
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
let target = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
|
||||
let perms = target_permissions(&target);
|
||||
// A rename replaces a file whatever its mode, so a read-only target would
|
||||
// be silently overwritten where `fs::write` refuses it. Keep the refusal:
|
||||
// a file someone made read-only is asking not to be rewritten in place.
|
||||
if fs::metadata(&target).is_ok_and(|m| m.permissions().readonly()) {
|
||||
if perms.as_ref().is_some_and(fs::Permissions::readonly) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
format!("{} is read-only", path.display()),
|
||||
));
|
||||
}
|
||||
let tmp = temp_path(&target)?;
|
||||
if let Err(e) = fs::write(&tmp, bytes) {
|
||||
let (tmp, mut file) = create_temp(&target, perms.is_some())?;
|
||||
if let Err(e) = fill_temp(&mut file, &tmp, perms, bytes) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(e);
|
||||
}
|
||||
// A file someone made read-only, or executable, keeps its mode: the temp
|
||||
// was created with the process umask, not with the target's bits. No
|
||||
// target means a new file, which takes the umask as `fs::write` would.
|
||||
if let Ok(meta) = fs::metadata(&target) {
|
||||
let _ = fs::set_permissions(&tmp, meta.permissions());
|
||||
}
|
||||
drop(file);
|
||||
if let Err(e) = fs::rename(&tmp, &target) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(e);
|
||||
@@ -55,16 +70,106 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How many temp names one write tries before giving up.
|
||||
///
|
||||
/// A name is only ever handed out once per process, so a collision means a
|
||||
/// leftover from a *previous* process that crashed mid-write and whose pid
|
||||
/// this process now has. A handful of those may sit in one directory; a
|
||||
/// hundred is a directory to clean up by hand, not a race to retry through.
|
||||
const TEMP_ATTEMPTS: u32 = 32;
|
||||
|
||||
/// Creates the temp file, exclusively, and returns it with its path.
|
||||
///
|
||||
/// `replacing` says there is a target whose mode the temp is about to take.
|
||||
/// Then it is born 0600 on unix rather than at the umask's mode: a chmod does
|
||||
/// not revoke a descriptor someone already opened, so the only way a private
|
||||
/// file's replacement can never be read by anyone else is for the temp to be
|
||||
/// private from the moment it exists. With no target there is no earlier mode
|
||||
/// to honour and the umask decides, as `fs::write` would.
|
||||
fn create_temp(target: &Path, replacing: bool) -> io::Result<(PathBuf, File)> {
|
||||
let mut opts = OpenOptions::new();
|
||||
opts.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
if replacing {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
opts.mode(0o600);
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = replacing;
|
||||
for _ in 0..TEMP_ATTEMPTS {
|
||||
let tmp = temp_path(target)?;
|
||||
match opts.open(&tmp) {
|
||||
Ok(file) => return Ok((tmp, file)),
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::AlreadyExists,
|
||||
format!("no free temp file name beside {} after {TEMP_ATTEMPTS} tries", target.display()),
|
||||
))
|
||||
}
|
||||
|
||||
/// Puts the target's mode on the temp, then the bytes in it.
|
||||
///
|
||||
/// The order is the point on unix: a 0600 target's replacement must not spend
|
||||
/// even an instant holding the file's contents under the umask's broader
|
||||
/// bits. Chmod does not close the handle opened before it, so a mode without
|
||||
/// an owner-write bit still takes the write. Elsewhere `set_permissions`
|
||||
/// takes a path rather than a handle and the mode goes on after the bytes,
|
||||
/// which is the order this always had.
|
||||
fn fill_temp(
|
||||
file: &mut File,
|
||||
tmp: &Path,
|
||||
perms: Option<fs::Permissions>,
|
||||
bytes: &[u8],
|
||||
) -> io::Result<()> {
|
||||
if cfg!(unix) {
|
||||
copy_mode(file, perms);
|
||||
file.write_all(bytes)
|
||||
} else {
|
||||
file.write_all(bytes)?;
|
||||
if let Some(perms) = perms {
|
||||
let _ = fs::set_permissions(tmp, perms);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts the target's mode on the temp through its open handle, which is what
|
||||
/// lets it happen while the temp is still empty. No target means no earlier
|
||||
/// mode to honour, and the umask's stands.
|
||||
fn copy_mode(file: &File, perms: Option<fs::Permissions>) {
|
||||
if let Some(perms) = perms {
|
||||
let _ = file.set_permissions(perms);
|
||||
}
|
||||
}
|
||||
|
||||
/// The mode the temp must end up with: a file someone made executable, or
|
||||
/// private, keeps its bits, because the temp was created with the process
|
||||
/// umask (or 0600) and not with the target's. `None` means there is no target
|
||||
/// — a new file, which takes the umask as `fs::write` would.
|
||||
fn target_permissions(target: &Path) -> Option<fs::Permissions> {
|
||||
fs::metadata(target).ok().map(|m| m.permissions())
|
||||
}
|
||||
|
||||
/// Names handed out by [`temp_path`], one per call for the life of the
|
||||
/// process. Wrapping after 2^64 names is not a scenario.
|
||||
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// The temp file's path: hidden, in the target's own directory, and stamped
|
||||
/// with the process id so two lucisv runs over one tree cannot collide.
|
||||
/// with the process id and a per-process counter — the pid keeps two lucisv
|
||||
/// runs apart, the counter keeps two threads of one run apart, and together
|
||||
/// they mean no two writers anywhere are ever given the same name.
|
||||
fn temp_path(target: &Path) -> io::Result<PathBuf> {
|
||||
let dir = target.parent().unwrap_or_else(|| Path::new("."));
|
||||
let name = target
|
||||
.file_name()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no file name to write"))?;
|
||||
let n = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
let mut tmp = std::ffi::OsString::from(".");
|
||||
tmp.push(name);
|
||||
tmp.push(format!(".{}.lucisv-tmp", std::process::id()));
|
||||
tmp.push(format!(".{}.{n}.lucisv-tmp", std::process::id()));
|
||||
Ok(dir.join(tmp))
|
||||
}
|
||||
|
||||
@@ -199,4 +304,148 @@ mod tests {
|
||||
);
|
||||
assert_eq!(fs::read_to_string(&link).expect("read"), "new\n", "and still points at it");
|
||||
}
|
||||
|
||||
/// The audit's probe (`docs/repository-analysis.md` finding 1), which
|
||||
/// used to produce 100 write errors in 200 calls: both threads derived
|
||||
/// the same temp name from the target and the pid, so one deleted the
|
||||
/// other's file under it. Now every writer owns its own temp, so every
|
||||
/// call succeeds and the target holds one writer's whole buffer.
|
||||
#[test]
|
||||
fn two_threads_writing_one_target_never_collide() {
|
||||
const MIB: usize = 1024 * 1024;
|
||||
const ROUNDS: usize = 100;
|
||||
let dir = TempDir::new("race");
|
||||
let file = dir.file("a.sv");
|
||||
fs::write(&file, "seed\n").expect("seed");
|
||||
|
||||
// Three parties: the two writers and this thread, which inspects the
|
||||
// target between rounds. Nobody starts a round until everyone has
|
||||
// finished the last one.
|
||||
let start = std::sync::Arc::new(std::sync::Barrier::new(3));
|
||||
let done = std::sync::Arc::new(std::sync::Barrier::new(3));
|
||||
let writers: Vec<_> = (*b"ab")
|
||||
.into_iter()
|
||||
.map(|tag| {
|
||||
let (path, start, done) = (file.clone(), start.clone(), done.clone());
|
||||
std::thread::spawn(move || {
|
||||
let bytes = vec![tag; MIB];
|
||||
let mut errors = Vec::new();
|
||||
for _ in 0..ROUNDS {
|
||||
start.wait();
|
||||
if let Err(e) = write_atomic(&path, &bytes) {
|
||||
errors.push(e.to_string());
|
||||
}
|
||||
done.wait();
|
||||
}
|
||||
errors
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
for round in 0..ROUNDS {
|
||||
start.wait();
|
||||
done.wait();
|
||||
let got = fs::read(&file).expect("read");
|
||||
assert_eq!(got.len(), MIB, "round {round}: a partial buffer landed");
|
||||
let tag = got[0];
|
||||
assert!(tag == b'a' || tag == b'b', "round {round}: neither writer's byte");
|
||||
assert!(got.iter().all(|&b| b == tag), "round {round}: two buffers were mixed");
|
||||
assert_eq!(dir.names(), vec!["a.sv".to_string()], "round {round}: a temp was left");
|
||||
}
|
||||
|
||||
let errors: Vec<String> =
|
||||
writers.into_iter().flat_map(|w| w.join().expect("writer thread")).collect();
|
||||
assert!(
|
||||
errors.is_empty(),
|
||||
"{} write errors in {} calls: {errors:?}",
|
||||
errors.len(),
|
||||
2 * ROUNDS
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_thread_gets_its_own_temp_name() {
|
||||
const PER_THREAD: usize = 200;
|
||||
let dir = TempDir::new("names");
|
||||
let target = dir.file("a.sv");
|
||||
let threads: Vec<_> = (0..4)
|
||||
.map(|_| {
|
||||
let target = target.clone();
|
||||
std::thread::spawn(move || {
|
||||
(0..PER_THREAD)
|
||||
.map(|_| temp_path(&target).expect("temp name"))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let names: Vec<PathBuf> =
|
||||
threads.into_iter().flat_map(|t| t.join().expect("name thread")).collect();
|
||||
let unique: std::collections::HashSet<&PathBuf> = names.iter().collect();
|
||||
assert_eq!(unique.len(), names.len(), "a temp name was handed out twice");
|
||||
}
|
||||
|
||||
/// The mode goes on while the temp is still empty, so a 0600 file's
|
||||
/// replacement never holds its contents under the umask's wider bits.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_temp_takes_the_targets_mode_before_any_bytes() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = TempDir::new("modewindow");
|
||||
let target = dir.file("secret.sv");
|
||||
fs::write(&target, "old\n").expect("seed");
|
||||
fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).expect("chmod");
|
||||
|
||||
let perms = target_permissions(&target);
|
||||
let (tmp, mut file) = create_temp(&target, perms.is_some()).expect("temp");
|
||||
// Born private, before any mode is copied onto it: an fd opened by
|
||||
// someone else in this instant would not see the bytes to come.
|
||||
assert_eq!(
|
||||
fs::metadata(&tmp).expect("stat").permissions().mode() & 0o777,
|
||||
0o600,
|
||||
"the temp was created readable by others"
|
||||
);
|
||||
copy_mode(&file, perms.clone());
|
||||
let meta = fs::metadata(&tmp).expect("stat");
|
||||
assert_eq!(meta.len(), 0, "the mode is set before a single byte is written");
|
||||
assert_eq!(meta.permissions().mode() & 0o777, 0o600, "the temp is not world-readable");
|
||||
// And the chmod does not close the door on the handle opened before it.
|
||||
fill_temp(&mut file, &tmp, perms, b"new\n").expect("fill");
|
||||
assert_eq!(fs::read_to_string(&tmp).expect("read"), "new\n");
|
||||
let _ = fs::remove_file(&tmp);
|
||||
}
|
||||
|
||||
/// The same window seen from outside, through a real `write_atomic`: a
|
||||
/// big enough buffer that the temp is usually observable while it is
|
||||
/// being filled. It asserts about what it sees and never about seeing it,
|
||||
/// so a scheduler that hides the window cannot fail the test.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_temp_seen_mid_write_is_never_world_readable() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = TempDir::new("window");
|
||||
let target = dir.file("secret.sv");
|
||||
fs::write(&target, "old\n").expect("seed");
|
||||
fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).expect("chmod");
|
||||
|
||||
let path = target.clone();
|
||||
let writer = std::thread::spawn(move || {
|
||||
let bytes = vec![b'x'; 8 * 1024 * 1024];
|
||||
write_atomic(&path, &bytes)
|
||||
});
|
||||
while !writer.is_finished() {
|
||||
for entry in fs::read_dir(&dir.path).expect("read dir").flatten() {
|
||||
if !entry.file_name().to_string_lossy().ends_with(".lucisv-tmp") {
|
||||
continue;
|
||||
}
|
||||
let Ok(meta) = entry.metadata() else { continue };
|
||||
assert_eq!(
|
||||
meta.permissions().mode() & 0o777,
|
||||
0o600,
|
||||
"a temp for a 0600 target was readable by others"
|
||||
);
|
||||
}
|
||||
}
|
||||
writer.join().expect("writer thread").expect("write");
|
||||
assert_eq!(fs::metadata(&target).expect("stat").permissions().mode() & 0o777, 0o600);
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,15 @@ pub struct FileConfig {
|
||||
pub lint_select: Option<Vec<String>>,
|
||||
/// `[lint] ignore`: rules dropped from whatever `select` left.
|
||||
pub lint_ignore: Option<Vec<String>>,
|
||||
/// `[lint] waivers`: external waiver files, in the order written.
|
||||
///
|
||||
/// Like [`FileConfig::filelist`], these name *other files*: [`parse`]
|
||||
/// records them exactly as written and [`Discovery`] resolves each one
|
||||
/// against the config file's own directory, so every `FileConfig` a
|
||||
/// `Discovery` hands out carries usable paths. Nothing here reads them —
|
||||
/// their contents name lint rules, and this crate does not know the rule
|
||||
/// registry any more than it does for `select`.
|
||||
pub lint_waivers: Option<Vec<PathBuf>>,
|
||||
/// `[lint.<rule>]` tables, **as written**: one entry per key, in file
|
||||
/// order.
|
||||
///
|
||||
@@ -93,7 +102,7 @@ pub fn parse(text: &str) -> Result<FileConfig, String> {
|
||||
enum Table {
|
||||
/// Before any header: the formatter's own keys.
|
||||
Top,
|
||||
/// `[lint]`: `select` and `ignore`.
|
||||
/// `[lint]`: `select`, `ignore` and `waivers`.
|
||||
Lint,
|
||||
/// `[lint.<rule>]`: that rule's options.
|
||||
Rule(String),
|
||||
@@ -106,7 +115,7 @@ fn parse_entry(
|
||||
number: usize,
|
||||
) -> Result<(), String> {
|
||||
if line.starts_with('[') {
|
||||
// `[lint]` carries `select`/`ignore`; `[lint.<rule>]` carries that
|
||||
// `[lint]` carries `select`/`ignore`/`waivers`; `[lint.<rule>]` carries that
|
||||
// rule's options, which are stored raw and checked by whoever knows
|
||||
// the registry.
|
||||
if line == "[lint]" {
|
||||
@@ -155,19 +164,28 @@ fn parse_entry(
|
||||
}
|
||||
_ => Err(format!(
|
||||
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
|
||||
select, ignore under `[lint]`; and a rule's own options under \
|
||||
`[lint.<rule-name>]`)"
|
||||
select, ignore, waivers under `[lint]`; and a rule's own options \
|
||||
under `[lint.<rule-name>]`)"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// One key of the `[lint]` table.
|
||||
fn parse_lint_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
|
||||
if key == "waivers" {
|
||||
if config.lint_waivers.is_some() {
|
||||
return Err(format!("duplicate key `{key}`"));
|
||||
}
|
||||
config.lint_waivers = Some(parse_array(value)?.into_iter().map(PathBuf::from).collect());
|
||||
return Ok(());
|
||||
}
|
||||
let slot = match key {
|
||||
"select" => &mut config.lint_select,
|
||||
"ignore" => &mut config.lint_ignore,
|
||||
_ => {
|
||||
return Err(format!("unknown key `{key}` under `[lint]` (known keys: select, ignore)"))
|
||||
return Err(format!(
|
||||
"unknown key `{key}` under `[lint]` (known keys: select, ignore, waivers)"
|
||||
))
|
||||
}
|
||||
};
|
||||
if slot.is_some() {
|
||||
@@ -359,10 +377,16 @@ fn load(path: &Path) -> Result<FileConfig, String> {
|
||||
// `filelist` is the one value that names another file, so it is resolved
|
||||
// here — against the config file's own directory, which `parse` cannot
|
||||
// know. An absolute path is left alone (`join` already does that).
|
||||
let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();
|
||||
if let Some(filelist) = config.filelist.take() {
|
||||
let dir = path.parent().unwrap_or(Path::new("."));
|
||||
config.filelist = Some(dir.join(filelist));
|
||||
}
|
||||
// `[lint] waivers` names other files the same way, and is resolved the
|
||||
// same way: against the config file's directory, an absolute path left
|
||||
// alone by `join`.
|
||||
if let Some(waivers) = config.lint_waivers.take() {
|
||||
config.lint_waivers = Some(waivers.into_iter().map(|file| dir.join(file)).collect());
|
||||
}
|
||||
// So an error about a `[lint.<rule>]` entry can name the file to edit.
|
||||
config.source = Some(path.to_path_buf());
|
||||
Ok(config)
|
||||
@@ -428,6 +452,34 @@ exclude = [ \"build\", \"*_gen.sv\", ]
|
||||
);
|
||||
}
|
||||
|
||||
/// `[lint] waivers` names other files, so it resolves the way `filelist`
|
||||
/// does: against the config file's own directory, absolute paths left
|
||||
/// alone. See `docs/features/waiver-files/README.md`.
|
||||
#[test]
|
||||
fn lint_waivers_are_a_list_resolved_against_the_config_files_directory() {
|
||||
assert_eq!(
|
||||
ok("[lint]\nwaivers = [ \"a.waiver\", \"deep/b.waiver\" ]").lint_waivers,
|
||||
Some(vec![PathBuf::from("a.waiver"), PathBuf::from("deep/b.waiver")])
|
||||
);
|
||||
assert_eq!(
|
||||
ok("[lint]\nselect = [\"no-tabs\"]").lint_waivers,
|
||||
None,
|
||||
"absent unless written"
|
||||
);
|
||||
assert!(err("[lint]\nwaivers = \"a.waiver\"").contains("multi-line arrays"));
|
||||
assert!(err("[lint]\nwaivers = []\nwaivers = []").contains("duplicate key `waivers`"));
|
||||
assert!(err("[lint]\nwaiver = []").contains("unknown key `waiver` under `[lint]`"));
|
||||
|
||||
let tree = TempTree::new();
|
||||
tree.write("lucisv.toml", "[lint]\nwaivers = [ \"rtl/a.waiver\", \"/opt/b.waiver\" ]\n");
|
||||
let deep = tree.write("a/b/x.sv", "");
|
||||
let found = Discovery::new(true).for_file(&deep).unwrap();
|
||||
assert_eq!(
|
||||
found.lint_waivers,
|
||||
Some(vec![tree.path.join("rtl/a.waiver"), PathBuf::from("/opt/b.waiver")])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_file_sets_nothing() {
|
||||
assert_eq!(ok(""), FileConfig::default());
|
||||
|
||||
+383
-23
@@ -2,6 +2,7 @@
|
||||
//! `.gitignore` subset documented in
|
||||
//! `docs/features/parallel-files/README.md`.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// File extensions lucisv formats when walking a directory.
|
||||
@@ -10,20 +11,56 @@ pub const EXTENSIONS: &[&str] = &["v", "sv", "vh", "svh"];
|
||||
/// The name of the per-directory ignore file that is honoured by default.
|
||||
const GITIGNORE: &str = ".gitignore";
|
||||
|
||||
/// Something the walk could not do and went on regardless: a directory it
|
||||
/// could not read, an ignore file it could not open, a source file that is
|
||||
/// only a broken link.
|
||||
///
|
||||
/// The walk's warning channel exists because none of these is worth failing a
|
||||
/// run over — one unreadable directory used to drop every file already found
|
||||
/// — and because a silent skip loses the user the fact entirely. Rendering is
|
||||
/// the front end's job: the CLI writes `warning: <path>: <message>` to stderr,
|
||||
/// the server logs the same text once per scan.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Warning {
|
||||
/// What could not be used.
|
||||
pub path: PathBuf,
|
||||
/// Why, in the operating system's own words where there are any.
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Warning {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}: {}", self.path.display(), self.message)
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `input` to `files`: the file itself, or every Verilog file under
|
||||
/// it if it is a directory. Exclude patterns and `.gitignore` rules apply
|
||||
/// to directory walks only — a path named on the command line is always
|
||||
/// formatted.
|
||||
///
|
||||
/// `warn` is called once for everything the walk skipped and wants said; see
|
||||
/// [`Warning`]. Only `input` itself naming nothing is an error — that is the
|
||||
/// user's own typo, and the run has nothing to do.
|
||||
pub fn collect_files(
|
||||
input: &str,
|
||||
exclude: &[String],
|
||||
gitignore: bool,
|
||||
files: &mut Vec<PathBuf>,
|
||||
warn: &mut dyn FnMut(Warning),
|
||||
) -> Result<(), String> {
|
||||
let path = Path::new(input);
|
||||
if path.is_dir() {
|
||||
let mut walk = Walk { exclude, gitignore, ignores: Vec::new(), rel: Vec::new(), files };
|
||||
walk.dir(path).map_err(|e| format!("{input}: {e}"))?;
|
||||
let mut walk = Walk {
|
||||
exclude,
|
||||
gitignore,
|
||||
ignores: Vec::new(),
|
||||
rel: Vec::new(),
|
||||
visited: HashSet::new(),
|
||||
files,
|
||||
warn,
|
||||
};
|
||||
walk.dir(path);
|
||||
} else if path.is_file() {
|
||||
files.push(path.to_path_buf());
|
||||
} else {
|
||||
@@ -32,57 +69,166 @@ pub fn collect_files(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How a directory is recognised as one the walk has already entered. Two
|
||||
/// names for the same directory — a symlink and its target, or two symlinks
|
||||
/// pointing at one place — must map to the same identity, or a cycle has no
|
||||
/// end. On unix that is `(dev, ino)`, the pair the filesystem itself uses;
|
||||
/// elsewhere it is the canonical path, which resolves symlinks the same way
|
||||
/// at the cost of a real path lookup.
|
||||
#[cfg(unix)]
|
||||
type DirId = (u64, u64);
|
||||
#[cfg(not(unix))]
|
||||
type DirId = PathBuf;
|
||||
|
||||
/// The identity of the directory at `path`, or `None` when it cannot be
|
||||
/// read — a dangling symlink, or a directory that vanished mid-walk.
|
||||
#[cfg(unix)]
|
||||
fn dir_id(path: &Path) -> Option<DirId> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let meta = std::fs::metadata(path).ok()?;
|
||||
Some((meta.dev(), meta.ino()))
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn dir_id(path: &Path) -> Option<DirId> {
|
||||
std::fs::canonicalize(path).ok()
|
||||
}
|
||||
|
||||
/// True when `path` names one of the source files lucisv formats.
|
||||
fn is_source(path: &Path) -> bool {
|
||||
path.extension().and_then(|e| e.to_str()).is_some_and(|ext| EXTENSIONS.contains(&ext))
|
||||
}
|
||||
|
||||
/// One directory walk. `rel` is the path of the directory currently being
|
||||
/// read, in components relative to the walk root, which is what
|
||||
/// `.gitignore` rules are matched against; `ignores` is the stack of
|
||||
/// ignore files seen from the root down to it.
|
||||
/// ignore files seen from the root down to it; `visited` is every directory
|
||||
/// already entered, by identity rather than by spelling.
|
||||
struct Walk<'a> {
|
||||
exclude: &'a [String],
|
||||
gitignore: bool,
|
||||
ignores: Vec<Ignore>,
|
||||
rel: Vec<String>,
|
||||
visited: HashSet<DirId>,
|
||||
files: &'a mut Vec<PathBuf>,
|
||||
warn: &'a mut dyn FnMut(Warning),
|
||||
}
|
||||
|
||||
impl Walk<'_> {
|
||||
fn dir(&mut self, dir: &Path) -> std::io::Result<()> {
|
||||
let pushed = self.push_ignore(dir)?;
|
||||
let mut entries: Vec<_> = std::fs::read_dir(dir)?.collect::<Result<_, _>>()?;
|
||||
fn dir(&mut self, dir: &Path) {
|
||||
if !self.enter(dir) {
|
||||
return;
|
||||
}
|
||||
let pushed = self.push_ignore(dir);
|
||||
self.entries(dir);
|
||||
if pushed {
|
||||
self.ignores.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/// One directory's entries, in name order. A directory that cannot be read
|
||||
/// — the permission-denied one somewhere under the start — is said and
|
||||
/// skipped: everything already found stays found and the walk goes on,
|
||||
/// which is the whole reason this channel exists.
|
||||
fn entries(&mut self, dir: &Path) {
|
||||
let read = match std::fs::read_dir(dir) {
|
||||
Ok(read) => read,
|
||||
Err(e) => return self.say(dir, e.to_string()),
|
||||
};
|
||||
let mut entries = Vec::new();
|
||||
for entry in read {
|
||||
match entry {
|
||||
Ok(entry) => entries.push(entry),
|
||||
Err(e) => self.say(dir, e.to_string()),
|
||||
}
|
||||
}
|
||||
entries.sort_by_key(|e| e.path());
|
||||
for entry in entries {
|
||||
let path = entry.path();
|
||||
if is_excluded(&path, self.exclude) {
|
||||
continue;
|
||||
}
|
||||
let is_dir = path.is_dir();
|
||||
// One `metadata` call per entry, exactly as before — it follows
|
||||
// symlinks, so it answers "directory?" for a symlinked directory
|
||||
// the way `is_dir()` did. A dangling symlink has no metadata at
|
||||
// all. One that *names a source file* is warned about and dropped:
|
||||
// §43's QA was right that a silent skip loses the user the fact,
|
||||
// and §45.2 gives that fact a home of its own rather than handing
|
||||
// the path on to fail as "no such file" in the front end. One that
|
||||
// names anything else was never going to be read, and is skipped
|
||||
// as quietly as it always was.
|
||||
let Ok(meta) = std::fs::metadata(&path) else {
|
||||
if is_source(&path) {
|
||||
let why = broken_link_reason(&path);
|
||||
self.say(&path, why);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
self.rel.push(entry.file_name().to_string_lossy().into_owned());
|
||||
if !is_ignored(&self.ignores, &self.rel, is_dir) {
|
||||
if is_dir {
|
||||
self.dir(&path)?;
|
||||
} else if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
|
||||
if EXTENSIONS.contains(&ext) {
|
||||
self.files.push(path);
|
||||
}
|
||||
if !is_ignored(&self.ignores, &self.rel, meta.is_dir()) {
|
||||
if meta.is_dir() {
|
||||
self.dir(&path);
|
||||
} else if meta.is_file() && is_source(&path) {
|
||||
self.files.push(path);
|
||||
}
|
||||
}
|
||||
self.rel.pop();
|
||||
}
|
||||
if pushed {
|
||||
self.ignores.pop();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Hand one warning to the front end.
|
||||
fn say(&mut self, path: &Path, message: String) {
|
||||
(self.warn)(Warning { path: path.to_path_buf(), message });
|
||||
}
|
||||
|
||||
/// Records `dir` as entered, and answers whether it had not been entered
|
||||
/// already. Identity, not spelling: `a/loop -> a` and `a/b/up -> ..` name
|
||||
/// a directory the walk is already inside, and following either is the
|
||||
/// cycle that only ends when the OS refuses a path. A symlink to a
|
||||
/// directory the walk has *not* seen is followed once, so
|
||||
/// `rtl -> ../shared/rtl` still contributes its files; the second link to
|
||||
/// one target contributes nothing further, and the files are reported
|
||||
/// under the first spelling that reached them.
|
||||
///
|
||||
/// A directory whose identity cannot be read is not entered.
|
||||
fn enter(&mut self, dir: &Path) -> bool {
|
||||
dir_id(dir).is_some_and(|id| self.visited.insert(id))
|
||||
}
|
||||
|
||||
/// Reads `dir`'s `.gitignore`, if there is one, onto the rule stack.
|
||||
/// Returns whether anything was pushed, so `dir` can pop it again.
|
||||
fn push_ignore(&mut self, dir: &Path) -> std::io::Result<bool> {
|
||||
///
|
||||
/// An ignore file that cannot be read is said and ignored, for the same
|
||||
/// reason an unreadable directory is: the walk that finds too much is a
|
||||
/// better failure than the walk that finds nothing.
|
||||
fn push_ignore(&mut self, dir: &Path) -> bool {
|
||||
let path = dir.join(GITIGNORE);
|
||||
if !self.gitignore || !path.is_file() {
|
||||
return Ok(false);
|
||||
return false;
|
||||
}
|
||||
let rules = parse_gitignore(&std::fs::read_to_string(&path)?);
|
||||
self.ignores.push(Ignore { base: self.rel.len(), rules });
|
||||
Ok(true)
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(text) => {
|
||||
self.ignores.push(Ignore { base: self.rel.len(), rules: parse_gitignore(&text) });
|
||||
true
|
||||
}
|
||||
Err(e) => {
|
||||
self.say(&path, e.to_string());
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a directory entry has no metadata, said the way a person would.
|
||||
///
|
||||
/// A broken symbolic link is what this is nearly always about, and naming it
|
||||
/// as one is worth more than the bare `No such file or directory` the follow
|
||||
/// produced; anything else keeps the operating system's own words.
|
||||
fn broken_link_reason(path: &Path) -> String {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(meta) if meta.file_type().is_symlink() => "broken symbolic link".to_string(),
|
||||
Ok(_) => "cannot be read".to_string(),
|
||||
Err(e) => e.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,6 +360,8 @@ fn glob_component(pattern: &str, name: &str) -> bool {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[cfg(unix)]
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn excluded(path: &str, pattern: &str) -> bool {
|
||||
is_excluded(Path::new(path), &[pattern.to_string()])
|
||||
@@ -320,6 +468,218 @@ mod tests {
|
||||
assert!(!ignored_at(&[(0, "/x.sv")], "sub/x.sv"));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Symlink cycles — `docs/features/walk-cycles/README.md`
|
||||
//
|
||||
// Every test below builds a real tree with real symlinks, because the
|
||||
// question is what the filesystem answers, not what a mock does. Each
|
||||
// one would run until the OS refused a path before the visited set.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A throwaway directory tree under the system temp dir, removed on
|
||||
/// drop. `remove_dir_all` unlinks a symlink instead of following it, so
|
||||
/// a tree with a cycle in it is cleaned up like any other.
|
||||
#[cfg(unix)]
|
||||
struct TempTree {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl TempTree {
|
||||
fn new(tag: &str) -> TempTree {
|
||||
static COUNTER: AtomicUsize = AtomicUsize::new(0);
|
||||
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("lucisv-walk-{}-{tag}-{n}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(&path).expect("create temp dir");
|
||||
TempTree { path }
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, text: &str) {
|
||||
let path = self.path.join(rel);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).expect("create parent");
|
||||
}
|
||||
std::fs::write(&path, text).expect("write");
|
||||
}
|
||||
|
||||
/// A source file with enough in it to be worth finding.
|
||||
fn source(&self, rel: &str) {
|
||||
self.write(rel, "module m;\nendmodule\n");
|
||||
}
|
||||
|
||||
/// Set `rel`'s permission bits. `0o000` is how a test builds the
|
||||
/// directory the walk cannot read; the test puts them back so the
|
||||
/// temp tree can be removed.
|
||||
fn chmod(&self, rel: &str, mode: u32) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let path = self.path.join(rel);
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode))
|
||||
.expect("set permissions");
|
||||
}
|
||||
|
||||
/// `rel` as a symlink to `target`, which is relative to `rel`'s own
|
||||
/// directory — the spelling a checked-in symlink actually uses.
|
||||
fn link(&self, rel: &str, target: &str) {
|
||||
let path = self.path.join(rel);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).expect("create parent");
|
||||
}
|
||||
std::os::unix::fs::symlink(target, &path).expect("symlink");
|
||||
}
|
||||
|
||||
/// The walk from `rel` (empty for the root), as sorted paths
|
||||
/// relative to the tree root. Warnings are dropped; the tests that
|
||||
/// care about them call [`TempTree::warned`].
|
||||
fn walk(&self, rel: &str) -> Vec<String> {
|
||||
self.walked(rel).0
|
||||
}
|
||||
|
||||
/// The same, plus what the walk said, each warning's path made
|
||||
/// relative to the tree root so the assertions read.
|
||||
fn warned(&self, rel: &str) -> (Vec<String>, Vec<String>) {
|
||||
self.walked(rel)
|
||||
}
|
||||
|
||||
fn walked(&self, rel: &str) -> (Vec<String>, Vec<String>) {
|
||||
let start = if rel.is_empty() { self.path.clone() } else { self.path.join(rel) };
|
||||
let mut files = Vec::new();
|
||||
let mut warnings = Vec::new();
|
||||
collect_files(
|
||||
start.to_str().expect("utf-8 temp path"),
|
||||
&[],
|
||||
true,
|
||||
&mut files,
|
||||
&mut |w| warnings.push(format!("{}: {}", self.rel_of(&w.path), w.message)),
|
||||
)
|
||||
.expect("the walk finishes");
|
||||
let mut out: Vec<String> = files.iter().map(|p| self.rel_of(p)).collect();
|
||||
out.sort();
|
||||
warnings.sort();
|
||||
(out, warnings)
|
||||
}
|
||||
|
||||
fn rel_of(&self, path: &Path) -> String {
|
||||
path.strip_prefix(&self.path).unwrap_or(path).to_string_lossy().into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_directory_linking_to_itself_is_entered_once() {
|
||||
let tree = TempTree::new("selfloop");
|
||||
tree.source("a/x.sv");
|
||||
tree.link("a/loop", "../a");
|
||||
assert_eq!(tree.walk(""), ["a/x.sv"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_link_to_an_ancestor_terminates_from_a_nested_start() {
|
||||
let tree = TempTree::new("uplink");
|
||||
tree.source("root.sv");
|
||||
tree.source("a/x.sv");
|
||||
tree.link("a/up", "..");
|
||||
// Starting *inside* the cycle: `a` is entered, then `a/up` is the
|
||||
// root, which the walk has not seen yet and so does enter — once.
|
||||
// Its own `a` is the directory already being walked, and stops.
|
||||
assert_eq!(tree.walk("a"), ["a/up/root.sv", "a/x.sv"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn two_links_to_one_directory_yield_its_files_once() {
|
||||
let tree = TempTree::new("twolinks");
|
||||
tree.source("shared/x.sv");
|
||||
// Sorted after `shared`, so the real directory is the spelling that
|
||||
// reaches the file first; whichever name wins, the file is reported
|
||||
// exactly once.
|
||||
tree.link("z1", "shared");
|
||||
tree.link("z2", "shared");
|
||||
assert_eq!(tree.walk(""), ["shared/x.sv"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_link_to_a_directory_not_yet_walked_is_still_followed() {
|
||||
let tree = TempTree::new("sibling");
|
||||
tree.source("shared/rtl/x.sv");
|
||||
tree.link("proj/rtl", "../shared/rtl");
|
||||
// The `rtl -> ../shared/rtl` of a real checkout: the target is
|
||||
// outside the walk, so the link is the only way to it.
|
||||
assert_eq!(tree.walk("proj"), ["proj/rtl/x.sv"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_dangling_source_link_is_warned_about_and_not_handed_on() {
|
||||
// §43's review kept the dangling source link in the file list so the
|
||||
// front end's "no such file" error survived. TODO §45.2 reverses that
|
||||
// on purpose: the warning is now the error's home, so the link is said
|
||||
// once here and never reaches the formatter. A dangling link that
|
||||
// names no source file was never going to be read and stays silent.
|
||||
let tree = TempTree::new("dangling");
|
||||
tree.source("a/x.sv");
|
||||
tree.link("a/gone.sv", "nowhere.sv");
|
||||
tree.link("a/gonedir", "nowhere");
|
||||
let (files, warnings) = tree.warned("");
|
||||
assert_eq!(files, ["a/x.sv"]);
|
||||
assert_eq!(warnings, ["a/gone.sv: broken symbolic link"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_unreadable_directory_is_skipped_and_the_walk_goes_on() {
|
||||
// The finding this channel exists for: one permission-denied directory
|
||||
// used to propagate `read_dir`'s error out of the whole walk, dropping
|
||||
// every file already found and failing the run.
|
||||
let tree = TempTree::new("unreadable");
|
||||
tree.source("a.sv");
|
||||
tree.source("locked/hidden.sv");
|
||||
tree.source("z/late.sv");
|
||||
tree.chmod("locked", 0o000);
|
||||
let (files, warnings) = tree.warned("");
|
||||
tree.chmod("locked", 0o755);
|
||||
assert_eq!(files, ["a.sv", "z/late.sv"], "the walk finished");
|
||||
assert_eq!(warnings.len(), 1, "{warnings:?}");
|
||||
assert!(warnings[0].starts_with("locked: "), "the warning names it: {warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_unreadable_ignore_file_is_said_and_the_directory_is_still_walked() {
|
||||
let tree = TempTree::new("lockedignore");
|
||||
tree.write(".gitignore", "build\n");
|
||||
tree.source("keep.sv");
|
||||
tree.chmod(".gitignore", 0o000);
|
||||
let (files, warnings) = tree.warned("");
|
||||
tree.chmod(".gitignore", 0o644);
|
||||
assert_eq!(files, ["keep.sv"]);
|
||||
assert_eq!(warnings.len(), 1, "{warnings:?}");
|
||||
assert!(warnings[0].starts_with(".gitignore: "), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_clean_walk_says_nothing() {
|
||||
let tree = TempTree::new("quiet");
|
||||
tree.source("a/x.sv");
|
||||
tree.source("b/y.sv");
|
||||
assert_eq!(tree.warned(""), (vec!["a/x.sv".to_string(), "b/y.sv".to_string()], Vec::new()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_cycle_inside_an_ignored_directory_is_never_entered() {
|
||||
let tree = TempTree::new("ignoredcycle");
|
||||
tree.write(".gitignore", "build\n");
|
||||
tree.source("keep.sv");
|
||||
tree.source("build/y.sv");
|
||||
tree.link("build/loop", "../build");
|
||||
assert_eq!(tree.walk(""), ["keep.sv"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_syntax_degrades_to_plain_globbing() {
|
||||
// `**` is just two stars inside one component; documented.
|
||||
|
||||
@@ -14,6 +14,7 @@ use lsp_types::{
|
||||
use vlog_linter::{apply_fixes, rule_by_name, Applicability, Violation};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::lint::LintRun;
|
||||
use crate::state::Document;
|
||||
|
||||
/// The kind of the fix-everything action, namespaced under `source.fixAll` so
|
||||
@@ -27,6 +28,7 @@ pub const FIX_ALL: &str = "source.fixAll.lucisv";
|
||||
/// client, because a fix-on-save request asks for `source.fixAll.lucisv` alone
|
||||
/// and computing every quick fix for it would be work nobody reads.
|
||||
pub fn code_actions(
|
||||
run: &LintRun,
|
||||
uri: &Uri,
|
||||
doc: &Document,
|
||||
range: Range,
|
||||
@@ -34,7 +36,7 @@ pub fn code_actions(
|
||||
tab_width: usize,
|
||||
) -> Vec<CodeActionOrCommand> {
|
||||
let positions = doc.positions();
|
||||
let violations = crate::lint::fixable(doc, tab_width);
|
||||
let violations = crate::lint::fixable(run, doc, tab_width);
|
||||
let mut actions = Vec::new();
|
||||
if wanted(only, &CodeActionKind::QUICKFIX) {
|
||||
let quick = violations.iter().filter_map(|v| quick_fix(uri, &positions, v, range));
|
||||
@@ -170,7 +172,7 @@ mod tests {
|
||||
fn actions_of(ws: &Workspace) -> Vec<CodeAction> {
|
||||
let doc = ws.document(&uri()).expect("open");
|
||||
let whole = doc.positions().whole_document();
|
||||
code_actions(&uri(), doc, whole, None, 2)
|
||||
code_actions(&LintRun::default(), &uri(), doc, whole, None, 2)
|
||||
.into_iter()
|
||||
.map(|a| match a {
|
||||
CodeActionOrCommand::CodeAction(action) => action,
|
||||
@@ -248,7 +250,14 @@ mod tests {
|
||||
start: Position { line: 1, character: 0 },
|
||||
end: Position { line: 1, character: 0 },
|
||||
};
|
||||
let actions = code_actions(&uri(), doc, line1, Some(&[CodeActionKind::QUICKFIX]), 2);
|
||||
let actions = code_actions(
|
||||
&LintRun::default(),
|
||||
&uri(),
|
||||
doc,
|
||||
line1,
|
||||
Some(&[CodeActionKind::QUICKFIX]),
|
||||
2,
|
||||
);
|
||||
assert_eq!(actions.len(), 1, "the cursor's line only: {actions:#?}");
|
||||
}
|
||||
|
||||
@@ -320,14 +329,32 @@ mod tests {
|
||||
start: Position { line: fenced_line, character: 0 },
|
||||
end: Position { line: fenced_line, character: 0 },
|
||||
};
|
||||
let actions = code_actions(&uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]), 2);
|
||||
let actions = code_actions(
|
||||
&LintRun::default(),
|
||||
&uri(),
|
||||
doc,
|
||||
at,
|
||||
Some(&[CodeActionKind::QUICKFIX]),
|
||||
2,
|
||||
);
|
||||
assert!(actions.is_empty(), "no quick fix inside a fence: {actions:#?}");
|
||||
// The unfenced tab one line further down still has one.
|
||||
let at = Range {
|
||||
start: Position { line: 4, character: 0 },
|
||||
end: Position { line: 4, character: 0 },
|
||||
};
|
||||
assert_eq!(code_actions(&uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]), 2).len(), 1);
|
||||
assert_eq!(
|
||||
code_actions(
|
||||
&LintRun::default(),
|
||||
&uri(),
|
||||
doc,
|
||||
at,
|
||||
Some(&[CodeActionKind::QUICKFIX]),
|
||||
2
|
||||
)
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -370,14 +397,19 @@ mod tests {
|
||||
let doc = ws.document(&uri()).expect("open");
|
||||
let whole = doc.positions().whole_document();
|
||||
let fix_all_only = [CodeActionKind::new(FIX_ALL)];
|
||||
let actions = code_actions(&uri(), doc, whole, Some(&fix_all_only), 2);
|
||||
let actions = code_actions(&LintRun::default(), &uri(), doc, whole, Some(&fix_all_only), 2);
|
||||
assert_eq!(actions.len(), 1, "no quick fixes when only fixAll was asked for");
|
||||
// `source` is a prefix filter for `source.fixAll.lucisv`.
|
||||
let source = [CodeActionKind::SOURCE];
|
||||
assert_eq!(code_actions(&uri(), doc, whole, Some(&source), 2).len(), 1);
|
||||
assert_eq!(
|
||||
code_actions(&LintRun::default(), &uri(), doc, whole, Some(&source), 2).len(),
|
||||
1
|
||||
);
|
||||
// And an unrelated filter selects nothing.
|
||||
let refactor = [CodeActionKind::REFACTOR];
|
||||
assert!(code_actions(&uri(), doc, whole, Some(&refactor), 2).is_empty());
|
||||
assert!(
|
||||
code_actions(&LintRun::default(), &uri(), doc, whole, Some(&refactor), 2).is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -386,7 +418,14 @@ mod tests {
|
||||
let ws = workspace(text);
|
||||
let doc = ws.document(&uri()).expect("open");
|
||||
let whole = doc.positions().whole_document();
|
||||
let actions = code_actions(&uri(), doc, whole, Some(&[CodeActionKind::QUICKFIX]), 4);
|
||||
let actions = code_actions(
|
||||
&LintRun::default(),
|
||||
&uri(),
|
||||
doc,
|
||||
whole,
|
||||
Some(&[CodeActionKind::QUICKFIX]),
|
||||
4,
|
||||
);
|
||||
let CodeActionOrCommand::CodeAction(fix) = &actions[0] else { panic!("an action") };
|
||||
assert_eq!(applied(text, fix), "module m;\n wire a;\nendmodule\n");
|
||||
}
|
||||
@@ -407,4 +446,28 @@ mod tests {
|
||||
assert!(out.contains("é 🎉"), "comments are never dropped: {out:?}");
|
||||
assert_eq!(out, "module m;\n // é 🎉 wire a;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_externally_waived_finding_gets_no_quick_fix_and_fix_all_leaves_it() {
|
||||
// §39 QA's HIGH: `fixable` used `default_rules()` and no waivers, so
|
||||
// fix-on-save rewrote a line a checked-in waiver file had waived.
|
||||
let src = "module m;\n\twire a;\nendmodule\n";
|
||||
let ws = workspace(src);
|
||||
let doc = ws.document(&uri()).expect("open");
|
||||
let whole = doc.positions().whole_document();
|
||||
let (external, problems) = vlog_linter::ExternalWaivers::parse(
|
||||
std::path::Path::new("team.waiver"),
|
||||
"waive --rule=no-tabs\n",
|
||||
);
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
let waived = LintRun::default().with_external(external);
|
||||
assert!(
|
||||
code_actions(&waived, &uri(), doc, whole, None, 2).is_empty(),
|
||||
"no quick fix and no fix-all for a waived finding"
|
||||
);
|
||||
assert!(
|
||||
!code_actions(&LintRun::default(), &uri(), doc, whole, None, 2).is_empty(),
|
||||
"the same buffer without the waiver is fixable"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
@@ -10,14 +10,26 @@
|
||||
//! table `lucisv.toml` now carries. See
|
||||
//! `docs/features/semantic-lints-on/README.md` and
|
||||
//! `docs/features/server-lint/README.md`.
|
||||
//!
|
||||
//! Since §42 the two halves of that selection are one contract: the editor's
|
||||
//! settings play the role the CLI's flags play, and the project's `[lint]`
|
||||
//! table is what stands when the editor says nothing —
|
||||
//! `docs/features/lint-config-contract/README.md`, and [`project`] for the
|
||||
//! project's half.
|
||||
|
||||
mod project;
|
||||
|
||||
pub use project::{ConfigProblems, ProblemLog, ProjectLint};
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString};
|
||||
use lucisv_core::config::FileConfig;
|
||||
use vlog_formatter::fence::{self, Region};
|
||||
use vlog_linter::{
|
||||
default_rules, lint, workspace_rules, LintContext, MentionOracle, ModuleInterface, Rule,
|
||||
RuleOptions, Severity, Violation,
|
||||
default_rules, lint_with, workspace_rules, ExternalWaivers, LintContext, MentionOracle,
|
||||
ModuleInterface, Rule, RuleOptions, Severity, Violation,
|
||||
};
|
||||
use vlog_semantic::{FileId, SymbolKind, WorkspaceIndex};
|
||||
|
||||
@@ -41,6 +53,14 @@ pub struct LintRun<'a> {
|
||||
/// The width `line-length` holds this buffer to — the width the formatter
|
||||
/// would wrap it to, so the two halves of lucisv cannot disagree.
|
||||
line_length: usize,
|
||||
/// The external waiver files in force for this buffer, from its
|
||||
/// `lucisv.toml` and from `lucisv.lint.waivers`. Empty unless one is
|
||||
/// configured, and then costing the pass nothing.
|
||||
external: ExternalWaivers,
|
||||
/// What the buffer's `lucisv.toml` asked for and did not get. Reported by
|
||||
/// whoever can talk to the client — [`ProblemLog`] keeps it to once per
|
||||
/// (config file, message) — and never fatal here: §42.2.
|
||||
problems: ConfigProblems,
|
||||
}
|
||||
|
||||
impl Default for LintRun<'_> {
|
||||
@@ -50,6 +70,8 @@ impl Default for LintRun<'_> {
|
||||
oracle: None,
|
||||
options: RuleOptions::new(),
|
||||
line_length: DEFAULT_LINE_LENGTH,
|
||||
external: ExternalWaivers::default(),
|
||||
problems: ConfigProblems::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -71,10 +93,36 @@ impl<'a> LintRun<'a> {
|
||||
let index = ws.index();
|
||||
let own = doc.path.as_deref().and_then(|path| index.file_id(path));
|
||||
let workspace = index.files().len() > usize::from(own.is_some());
|
||||
let rules = enabled_rules(ws.client_settings(), workspace);
|
||||
let oracle = workspace.then_some(IndexMentions { index, own });
|
||||
let (options, line_length) = configured(ws.client_settings(), doc);
|
||||
LintRun { rules, oracle, options, line_length }
|
||||
// One discovery for the whole pass: the selection, the options, the
|
||||
// width and the waiver paths all read the same `FileConfig`, so
|
||||
// reading the project's rules costs no extra stat and no extra open.
|
||||
let (options, line_length, file, mut messages) = configured(ws.client_settings(), doc);
|
||||
let (from_file, bad_names) = ProjectLint::read(&file);
|
||||
messages.extend(bad_names);
|
||||
let rules = enabled_rules(ws.client_settings(), &from_file, workspace);
|
||||
let (mut external, bad_waivers) = external_waivers(&project_waivers(&file));
|
||||
messages.extend(bad_waivers);
|
||||
// The editor's own waiver files are read separately and their
|
||||
// problems dropped: `notification::apply_settings` already said them
|
||||
// once, where the setting arrived.
|
||||
external.absorb(external_waivers(&editor_waivers(ws.client_settings(), ws.roots())).0);
|
||||
let problems = ConfigProblems::new(&file, messages);
|
||||
LintRun { rules, oracle, options, line_length, external, problems }
|
||||
}
|
||||
|
||||
/// What this buffer's `lucisv.toml` asked for and did not get, for a
|
||||
/// caller that can tell the user about it.
|
||||
pub fn config_problems(&self) -> &ConfigProblems {
|
||||
&self.problems
|
||||
}
|
||||
|
||||
/// A run carrying these external waivers — for the tests that pin what a
|
||||
/// waiver keeps out of the code actions.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_external(mut self, external: ExternalWaivers) -> Self {
|
||||
self.external = external;
|
||||
self
|
||||
}
|
||||
|
||||
/// This run's context over a buffer's own parse products.
|
||||
@@ -109,51 +157,139 @@ impl<'a> LintRun<'a> {
|
||||
/// reads it per formatting request: a `lucisv.toml` edited while the server
|
||||
/// runs takes effect at the next publish, and the read is a few stats beside
|
||||
/// a parse and an analysis the same pass already paid for.
|
||||
fn configured(client: &ClientSettings, doc: &Document) -> (RuleOptions, usize) {
|
||||
fn configured(
|
||||
client: &ClientSettings,
|
||||
doc: &Document,
|
||||
) -> (RuleOptions, usize, FileConfig, Vec<String>) {
|
||||
let file = doc
|
||||
.path
|
||||
.as_deref()
|
||||
.and_then(|path| lucisv_core::config::Discovery::new(true).for_file(path).ok())
|
||||
.unwrap_or_default();
|
||||
let mut options = RuleOptions::new();
|
||||
let mut problems = Vec::new();
|
||||
for entry in &file.lint_options {
|
||||
// A broken entry in the file is dropped here rather than reported:
|
||||
// `format::settings_for` already surfaces a `lucisv.toml` problem to
|
||||
// the user, and `lucisv check` fails the run over it with file and
|
||||
// line, which is where a config error belongs.
|
||||
let _ = options.set_raw(&entry.rule, &entry.key, &entry.raw);
|
||||
// A broken entry in the file is dropped rather than fatal — an editor
|
||||
// cannot fail a run — but it is *said*, in the words `lucisv check`
|
||||
// fails with, once per (config file, entry): §42.2. Silently dropping
|
||||
// it left a user's option doing nothing with nothing to read about it.
|
||||
if let Err(problem) = options.set_raw(&entry.rule, &entry.key, &entry.raw) {
|
||||
let source = file
|
||||
.source
|
||||
.as_ref()
|
||||
.map_or_else(|| "lucisv.toml".to_string(), |path| path.display().to_string());
|
||||
problems.push(format!("{source}:{}: rule `{}` {problem}", entry.line, entry.rule));
|
||||
}
|
||||
}
|
||||
options.overlay(&client.lint_options);
|
||||
let width = file.line_length.or(client.line_length).unwrap_or(DEFAULT_LINE_LENGTH);
|
||||
(options, width)
|
||||
(options, width, file, problems)
|
||||
}
|
||||
|
||||
/// Which rules a buffer is linted with, given what the editor's settings say.
|
||||
/// The waiver files governing one buffer: its `lucisv.toml`'s `[lint] waivers`
|
||||
/// first, then `lucisv.lint.waivers` from the editor.
|
||||
///
|
||||
/// The two **add up**, the way they do on the command line — a waiver file
|
||||
/// only ever suppresses findings, so there is nothing here for one list to
|
||||
/// take back from the other. A relative setting path is resolved against the
|
||||
/// first workspace root, exactly as `lucisv.filelist` is; a `lucisv.toml`'s
|
||||
/// paths were already resolved against that file's own directory.
|
||||
pub fn waiver_paths(client: &ClientSettings, roots: &[PathBuf], file: &FileConfig) -> Vec<PathBuf> {
|
||||
let mut paths = project_waivers(file);
|
||||
paths.extend(editor_waivers(client, roots));
|
||||
paths
|
||||
}
|
||||
|
||||
/// The `[lint] waivers` of one config file, already resolved by `Discovery`
|
||||
/// against that file's own directory.
|
||||
///
|
||||
/// Read apart from the editor's since §42.2, because a problem in one of
|
||||
/// *these* is the project's and belongs in the output channel with the
|
||||
/// `lucisv.toml` that named it, while a problem in the editor's was already
|
||||
/// said where the setting arrived.
|
||||
fn project_waivers(file: &FileConfig) -> Vec<PathBuf> {
|
||||
file.lint_waivers.iter().flatten().cloned().collect()
|
||||
}
|
||||
|
||||
/// The waiver files `lucisv.lint.waivers` names, a relative one anchored at
|
||||
/// the first workspace root exactly as `lucisv.filelist` is.
|
||||
fn editor_waivers(client: &ClientSettings, roots: &[PathBuf]) -> Vec<PathBuf> {
|
||||
client
|
||||
.lint_waivers
|
||||
.iter()
|
||||
.map(|setting| {
|
||||
let path = Path::new(setting);
|
||||
match roots.first() {
|
||||
Some(root) if path.is_relative() => root.join(path),
|
||||
_ => path.to_path_buf(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Those files, read: the waivers and one message per file or line that could
|
||||
/// not be used.
|
||||
///
|
||||
/// **Nothing here is fatal.** A push arrives on a socket and a bad path in it
|
||||
/// must never cost a user every diagnostic in their file — this module's
|
||||
/// standing rule, and `settings::rule_options`'. The messages are logged once,
|
||||
/// when the settings arrive (`server::notification::apply_settings`); the lint
|
||||
/// pass, which runs on every keystroke, drops them silently rather than
|
||||
/// logging the same line a hundred times.
|
||||
pub fn external_waivers(paths: &[PathBuf]) -> (ExternalWaivers, Vec<String>) {
|
||||
let mut waivers = ExternalWaivers::default();
|
||||
let mut problems = Vec::new();
|
||||
for path in paths {
|
||||
match ExternalWaivers::read(path) {
|
||||
Ok((file, bad)) => {
|
||||
problems.extend(bad);
|
||||
waivers.absorb(file);
|
||||
}
|
||||
Err(problem) => problems.push(problem),
|
||||
}
|
||||
}
|
||||
(waivers, problems)
|
||||
}
|
||||
|
||||
/// Which rules a buffer is linted with, given what the editor's settings and
|
||||
/// the buffer's own `lucisv.toml` say.
|
||||
///
|
||||
/// **The one ladder**, top rung last — every rung may undo the one above it:
|
||||
///
|
||||
/// 1. the base set is what the rules themselves declare: `default_on`, plus
|
||||
/// the `needs_workspace` rules when `has_oracle`;
|
||||
/// 2. a non-empty `lucisv.lint.select` **replaces** that base set, exactly as
|
||||
/// `--select` replaces it on the command line;
|
||||
/// `--select` replaces it on the command line; when the editor names
|
||||
/// nothing, the project's `[lint] select` replaces it instead — the flag
|
||||
/// when there is one, else the file, which is `lucisv check`'s own `pick`;
|
||||
/// 3. a `lucisv.lint.severity.<class>` switched off **removes** every rule of
|
||||
/// that class;
|
||||
/// 4. a `lucisv.lint.rules.<name>` set to `on` or `off` sets or clears that
|
||||
/// one rule — the per-rule word beats the class word, which is what makes
|
||||
/// "all style off except `no-tabs`" expressible;
|
||||
/// 5. `lucisv.lint.ignore` **removes** — the off switch of last resort, the
|
||||
/// one a user reaches for when nothing else worked.
|
||||
/// one a user reaches for when nothing else worked; when the editor names
|
||||
/// nothing there either, the project's `[lint] ignore` removes instead.
|
||||
///
|
||||
/// Rungs 2 and 5 accept a severity word wherever a rule name fits.
|
||||
pub fn enabled_rules(settings: &ClientSettings, has_oracle: bool) -> Vec<&'static dyn Rule> {
|
||||
let base = if settings.lint_select.is_empty() {
|
||||
/// Rungs 3 and 4 are the **editor's alone**: a `lucisv.toml` has no such
|
||||
/// keys, and the command line has no such flags. Rungs 2 and 5 are decided
|
||||
/// independently — a project that selects and a user who only ignores keep
|
||||
/// both halves. Every list accepts a severity word wherever a rule name fits,
|
||||
/// the project's as much as the editor's.
|
||||
pub fn enabled_rules(
|
||||
settings: &ClientSettings,
|
||||
project: &ProjectLint,
|
||||
has_oracle: bool,
|
||||
) -> Vec<&'static dyn Rule> {
|
||||
let select = pick(&settings.lint_select, &project.select);
|
||||
let base = if select.is_empty() {
|
||||
if has_oracle {
|
||||
workspace_rules()
|
||||
} else {
|
||||
default_rules()
|
||||
}
|
||||
} else {
|
||||
named(&settings.lint_select)
|
||||
named(select)
|
||||
};
|
||||
let mut on: BTreeSet<&'static str> = base.iter().map(|rule| rule.name()).collect();
|
||||
|
||||
@@ -172,12 +308,22 @@ pub fn enabled_rules(settings: &ClientSettings, has_oracle: bool) -> Vec<&'stati
|
||||
on.remove(rule.name());
|
||||
}
|
||||
}
|
||||
for rule in named(&settings.lint_ignore) {
|
||||
for rule in named(pick(&settings.lint_ignore, &project.ignore)) {
|
||||
on.remove(rule.name());
|
||||
}
|
||||
vlog_linter::all_rules().into_iter().filter(|rule| on.contains(rule.name())).collect()
|
||||
}
|
||||
|
||||
/// The editor's list when it said anything, else the project's — the twin of
|
||||
/// `lucisv/src/lint.rs`'s `pick`, which is the whole of §42's contract.
|
||||
fn pick<'a>(editor: &'a [String], project: &'a [String]) -> &'a [String] {
|
||||
if editor.is_empty() {
|
||||
project
|
||||
} else {
|
||||
editor
|
||||
}
|
||||
}
|
||||
|
||||
/// Every rule a list of `--select`-style words names, unknown words skipped —
|
||||
/// they were already dropped when the settings were parsed, and a name that
|
||||
/// survived that filter always resolves.
|
||||
@@ -256,8 +402,13 @@ fn context(doc: &Document) -> LintContext<'_> {
|
||||
///
|
||||
/// This is the diagnostics path, which never looks at a fix, so the width a
|
||||
/// `no-tabs` fix would expand a tab to is left at the linter's own default.
|
||||
/// The external waivers apply here exactly as the inline ones do, as a union.
|
||||
/// Which of them *fired* is discarded: only a whole run can tell whether a
|
||||
/// waiver was dead, and a server never has one — it lints the buffers a user
|
||||
/// happens to have open. `lucisv check` is what reports an unused external
|
||||
/// waiver; see `docs/features/waiver-files/README.md`.
|
||||
pub fn violations_in(doc: &Document, run: &LintRun) -> Vec<Violation> {
|
||||
lint(&run.context(doc), &run.rules)
|
||||
lint_with(&run.context(doc), &run.rules, &run.external).0
|
||||
}
|
||||
|
||||
/// The findings a code action may offer a fix for, with their fixes built for
|
||||
@@ -274,8 +425,14 @@ pub fn violations_in(doc: &Document, run: &LintRun) -> Vec<Violation> {
|
||||
/// just has no lightbulb. Which bytes count as fenced is
|
||||
/// [`fence::protected_regions`]' answer, the one the CLI asks too; see
|
||||
/// `docs/features/shared-fence-filter/README.md`.
|
||||
pub fn fixable(doc: &Document, tab_width: usize) -> Vec<Violation> {
|
||||
let found = lint(&context(doc).with_tab_width(tab_width), &default_rules());
|
||||
pub fn fixable(run: &LintRun, doc: &Document, tab_width: usize) -> Vec<Violation> {
|
||||
// The buffer's own run: its enabled rules and its external waiver files,
|
||||
// so a fix is never offered — nor applied by fix-on-save — for a finding
|
||||
// the diagnostics pass would not have shown. Found by §39's QA: with
|
||||
// `default_rules()` and no waivers here, `source.fixAll.lucisv` rewrote a
|
||||
// line a checked-in waiver file had waived.
|
||||
let ctx = run.context(doc).with_tab_width(tab_width);
|
||||
let found = lint_with(&ctx, &run.rules, &run.external).0;
|
||||
// One tolerant parse per code-action request: `protected_regions` takes
|
||||
// text and parses internally, on purpose — one fence answer for every
|
||||
// front end, none of which can feed it a stale tree (see
|
||||
@@ -449,7 +606,7 @@ mod tests {
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let diags = diagnostics(doc);
|
||||
assert_eq!(diags.len(), 2, "both tabs are reported: {diags:#?}");
|
||||
let offered = fixable(doc, 2);
|
||||
let offered = fixable(&LintRun::default(), doc, 2);
|
||||
assert_eq!(offered.len(), 1, "only the unfenced one may be fixed: {offered:#?}");
|
||||
let free = text.find("\twire b").expect("the unfenced tab") as u32;
|
||||
assert_eq!(offered[0].span.start, free);
|
||||
@@ -469,7 +626,7 @@ mod tests {
|
||||
.any(|d| d.code == Some(NumberOrString::String("no-tabs".into()))),
|
||||
"still reported"
|
||||
);
|
||||
assert!(fixable(doc, 2).is_empty(), "and still not fixable");
|
||||
assert!(fixable(&LintRun::default(), doc, 2).is_empty(), "and still not fixable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -548,8 +705,14 @@ mod tests {
|
||||
/// be true of the result).
|
||||
#[test]
|
||||
fn the_enabled_rules_ladder_is_the_documented_one() {
|
||||
// The project's half of the ladder is `lint::project`'s own table
|
||||
// test; this one holds it empty, which is the editor-only ladder
|
||||
// §33.1 wrote.
|
||||
let names = |settings: &ClientSettings, oracle: bool| -> Vec<&'static str> {
|
||||
enabled_rules(settings, oracle).into_iter().map(|rule| rule.name()).collect()
|
||||
enabled_rules(settings, &ProjectLint::default(), oracle)
|
||||
.into_iter()
|
||||
.map(|rule| rule.name())
|
||||
.collect()
|
||||
};
|
||||
let with = |f: &dyn Fn(&mut ClientSettings)| {
|
||||
let mut settings = ClientSettings::default();
|
||||
@@ -711,7 +874,7 @@ mod tests {
|
||||
#[test]
|
||||
fn an_unfenced_file_offers_every_fix() {
|
||||
let (ws, uri) = doc_of("module m;\n// just a note\n\twire a;\nendmodule\n");
|
||||
assert_eq!(fixable(ws.document(&uri).expect("open"), 2).len(), 1);
|
||||
assert_eq!(fixable(&LintRun::default(), ws.document(&uri).expect("open"), 2).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -719,9 +882,60 @@ mod tests {
|
||||
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
for width in [2usize, 4] {
|
||||
let found = fixable(doc, width);
|
||||
let found = fixable(&LintRun::default(), doc, width);
|
||||
let fix = found[0].fix.as_ref().expect("no-tabs offers a fix");
|
||||
assert_eq!(fix.edits[0].1, " ".repeat(width));
|
||||
}
|
||||
}
|
||||
|
||||
/// The two waiver lists add up, and only the setting's relative paths are
|
||||
/// anchored at the first root — a `lucisv.toml`'s were resolved against
|
||||
/// that file's own directory before they got here. TODO §39.
|
||||
#[test]
|
||||
fn the_config_files_waivers_come_first_and_the_settings_are_rooted() {
|
||||
let file = FileConfig {
|
||||
lint_waivers: Some(vec![PathBuf::from("/proj/rtl/project.waiver")]),
|
||||
..Default::default()
|
||||
};
|
||||
let client = ClientSettings {
|
||||
lint_waivers: vec!["team.waiver".to_string(), "/etc/global.waiver".to_string()],
|
||||
..Default::default()
|
||||
};
|
||||
let roots = vec![PathBuf::from("/work/top")];
|
||||
assert_eq!(
|
||||
waiver_paths(&client, &roots, &file),
|
||||
vec![
|
||||
PathBuf::from("/proj/rtl/project.waiver"),
|
||||
PathBuf::from("/work/top/team.waiver"),
|
||||
PathBuf::from("/etc/global.waiver"),
|
||||
]
|
||||
);
|
||||
// With no root at all a relative path is left as written rather than
|
||||
// guessed at, exactly as `filelist_path` leaves it.
|
||||
assert_eq!(
|
||||
waiver_paths(&client, &[], &FileConfig::default()),
|
||||
vec![PathBuf::from("team.waiver"), PathBuf::from("/etc/global.waiver")]
|
||||
);
|
||||
assert!(waiver_paths(&ClientSettings::default(), &roots, &FileConfig::default()).is_empty());
|
||||
}
|
||||
|
||||
/// A waiver file that is missing, and one with a bad line, are both
|
||||
/// described rather than fatal — and the good directives of the second
|
||||
/// still apply. TODO §39.
|
||||
#[test]
|
||||
fn a_bad_waiver_file_is_described_and_its_good_directives_still_apply() {
|
||||
let dir = std::env::temp_dir().join(format!("lucisv_waiver_paths_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
let good = dir.join("good.waiver");
|
||||
std::fs::write(&good, "waive --rule=no-tabs\nwaive --rule=nope\n").expect("write");
|
||||
|
||||
let (waivers, problems) = external_waivers(&[good.clone(), dir.join("missing.waiver")]);
|
||||
assert!(!waivers.is_empty(), "the good directive survived its neighbour");
|
||||
assert_eq!(problems.len(), 2, "{problems:?}");
|
||||
assert!(problems[0].contains("good.waiver:2: unknown rule `nope`"), "{problems:?}");
|
||||
assert!(problems[1].contains("missing.waiver"), "{problems:?}");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
//! What a buffer's `lucisv.toml` says about linting, and what could not be
|
||||
//! used from it.
|
||||
//!
|
||||
//! The contract (§42): **the editor's settings play the role the CLI's flags
|
||||
//! play**. `lucisv check` picks the flag when one was given and the project
|
||||
//! file otherwise (`lucisv/src/lint.rs`'s `pick`); the server picks
|
||||
//! `lucisv.lint.select` when it is non-empty and `[lint] select` otherwise,
|
||||
//! key by key, so one buffer linted two ways is linted the same way. See
|
||||
//! `docs/features/lint-config-contract/README.md`.
|
||||
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use lucisv_core::config::FileConfig;
|
||||
|
||||
/// The selection a buffer's `lucisv.toml` carries: `[lint] select` and
|
||||
/// `[lint] ignore`, exactly as `--select` and `--ignore` carry them.
|
||||
///
|
||||
/// [`ProjectLint::default`] — both lists empty — is a buffer with no config
|
||||
/// file, or one whose `[lint]` table says nothing about rules: the editor's
|
||||
/// settings and the base set then decide everything, which is what this
|
||||
/// server did before §42.
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct ProjectLint {
|
||||
/// `[lint] select`: run exactly these rules, replacing the base set —
|
||||
/// unless the editor named some, which outranks it.
|
||||
pub select: Vec<String>,
|
||||
/// `[lint] ignore`: rules dropped from whatever `select` left — unless
|
||||
/// the editor named some.
|
||||
pub ignore: Vec<String>,
|
||||
}
|
||||
|
||||
impl ProjectLint {
|
||||
/// One config file's selection, with every name the registry does not
|
||||
/// know dropped and reported.
|
||||
///
|
||||
/// `lucisv check` *fails the run* over an unknown name, which an editor
|
||||
/// cannot do — but it must not silently obey a typo either: a
|
||||
/// `select = ["no-tab"]` taken at face value would resolve to no rules at
|
||||
/// all and blank the file's squiggles, which reads as "lucisv is happy"
|
||||
/// rather than "lucisv could not understand your config". So the name is
|
||||
/// dropped, said once, and the rest of the list still applies; a `select`
|
||||
/// left empty by the dropping falls back to the base set.
|
||||
pub fn read(file: &FileConfig) -> (ProjectLint, Vec<String>) {
|
||||
let mut problems = Vec::new();
|
||||
let select = known(file, "select", file.lint_select.as_deref(), &mut problems);
|
||||
let ignore = known(file, "ignore", file.lint_ignore.as_deref(), &mut problems);
|
||||
(ProjectLint { select, ignore }, problems)
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of one `[lint]` list that name something, the others reported.
|
||||
fn known(
|
||||
file: &FileConfig,
|
||||
key: &str,
|
||||
list: Option<&[String]>,
|
||||
problems: &mut Vec<String>,
|
||||
) -> Vec<String> {
|
||||
let mut kept = Vec::new();
|
||||
for name in list.unwrap_or(&[]) {
|
||||
if vlog_linter::rules_named(name).is_some() {
|
||||
kept.push(name.clone());
|
||||
} else {
|
||||
// No line number: `lucisv_core::config` records one per
|
||||
// `[lint.<rule>]` entry, because those are checked one by one,
|
||||
// and the list keys are one value each.
|
||||
problems.push(format!("{}: [lint] {key}: unknown rule: {name}", source_of(file)));
|
||||
}
|
||||
}
|
||||
kept
|
||||
}
|
||||
|
||||
/// The config file's path as an error should name it.
|
||||
fn source_of(file: &FileConfig) -> String {
|
||||
file.source.as_ref().map_or_else(|| "lucisv.toml".to_string(), |p| p.display().to_string())
|
||||
}
|
||||
|
||||
/// What one buffer's `lucisv.toml` asked for and did not get: a
|
||||
/// `[lint.<rule>]` entry the registry refused, a name in `[lint] select` that
|
||||
/// is not a rule, a `[lint] waivers` file that is not there or holds a
|
||||
/// directive that does not parse.
|
||||
///
|
||||
/// Every message is written the way `lucisv check` writes it —
|
||||
/// `<file>:<line>: <message>` — so the same mistake reads the same in CI and
|
||||
/// in an editor's output channel. **Nothing here is fatal**: the entry is
|
||||
/// dropped and the buffer is still linted with everything that was
|
||||
/// understood, because a server cannot fail a run the way a command can.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct ConfigProblems {
|
||||
/// The config file they came from. `None` — no config file was found —
|
||||
/// means there is nothing to complain about and `messages` is empty.
|
||||
source: Option<PathBuf>,
|
||||
/// A stamp of that file's lint content, so an edited config gets a fresh
|
||||
/// hearing: see [`ProblemLog`].
|
||||
stamp: u64,
|
||||
/// The messages, in file order.
|
||||
messages: Vec<String>,
|
||||
}
|
||||
|
||||
impl ConfigProblems {
|
||||
/// The problems found in this config file.
|
||||
pub fn new(file: &FileConfig, messages: Vec<String>) -> ConfigProblems {
|
||||
ConfigProblems { source: file.source.clone(), stamp: stamp_of(file), messages }
|
||||
}
|
||||
|
||||
/// Whether anything at all could not be used.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.messages.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// A stamp over everything in a config file that [`ConfigProblems`] can be
|
||||
/// about, so that editing the file re-arms the report and editing a source
|
||||
/// beside it does not.
|
||||
///
|
||||
/// A hash rather than a modification time: the file is re-read on every lint
|
||||
/// pass anyway (`configured`), and a hash of what was parsed cannot be fooled
|
||||
/// by a filesystem whose timestamps are coarse.
|
||||
fn stamp_of(file: &FileConfig) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
file.lint_select.hash(&mut hasher);
|
||||
file.lint_ignore.hash(&mut hasher);
|
||||
file.lint_waivers.hash(&mut hasher);
|
||||
for entry in &file.lint_options {
|
||||
entry.rule.hash(&mut hasher);
|
||||
entry.key.hash(&mut hasher);
|
||||
entry.raw.hash(&mut hasher);
|
||||
entry.line.hash(&mut hasher);
|
||||
}
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// Which config problems have already been said, so each is said **once**.
|
||||
///
|
||||
/// Once per (config file, message), not once per lint pass: the pass runs on
|
||||
/// every keystroke and every index rebuild, and a hundred copies of one line
|
||||
/// in the output channel is not a report, it is noise. The editor-settings
|
||||
/// path has said its own problems once since §34 — this is the same promise
|
||||
/// for the file a project checks in.
|
||||
///
|
||||
/// A config file whose lint content changed clears its own memo, so a user
|
||||
/// who edits `lucisv.toml` and gets it wrong again is told again. The memo is
|
||||
/// keyed by path, so it holds one small entry per config file a session ever
|
||||
/// linted through.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ProblemLog {
|
||||
said: HashMap<PathBuf, Said>,
|
||||
}
|
||||
|
||||
/// One config file's memo: the content it was taken under, and what was said.
|
||||
#[derive(Debug, Default)]
|
||||
struct Said {
|
||||
stamp: u64,
|
||||
messages: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl ProblemLog {
|
||||
/// The messages that have not been said yet for this config file, marked
|
||||
/// as said. An empty answer means the user has already been told.
|
||||
pub fn unsaid(&mut self, problems: &ConfigProblems) -> Vec<String> {
|
||||
let Some(source) = problems.source.clone() else { return Vec::new() };
|
||||
if problems.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let said = self.said.entry(source).or_default();
|
||||
if said.stamp != problems.stamp {
|
||||
said.stamp = problems.stamp;
|
||||
said.messages.clear();
|
||||
}
|
||||
problems
|
||||
.messages
|
||||
.iter()
|
||||
.filter(|message| said.messages.insert((*message).clone()))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::state::{Document, Workspace};
|
||||
use lsp_types::Uri;
|
||||
use std::str::FromStr;
|
||||
use vlog_linter::Severity;
|
||||
|
||||
fn config(text: &str) -> FileConfig {
|
||||
let mut file = lucisv_core::config::parse(text).expect("the config parses");
|
||||
file.source = Some(PathBuf::from("/rtl/lucisv.toml"));
|
||||
file
|
||||
}
|
||||
|
||||
fn names(settings: &ClientSettings, project: &ProjectLint, oracle: bool) -> Vec<&'static str> {
|
||||
super::super::enabled_rules(settings, project, oracle)
|
||||
.into_iter()
|
||||
.map(|rule| rule.name())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn editor(select: &[&str], ignore: &[&str]) -> ClientSettings {
|
||||
ClientSettings {
|
||||
lint_select: select.iter().map(|s| (*s).to_string()).collect(),
|
||||
lint_ignore: ignore.iter().map(|s| (*s).to_string()).collect(),
|
||||
..ClientSettings::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn project(select: &[&str], ignore: &[&str]) -> ProjectLint {
|
||||
ProjectLint {
|
||||
select: select.iter().map(|s| (*s).to_string()).collect(),
|
||||
ignore: ignore.iter().map(|s| (*s).to_string()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// §42.1's table: every combination of {toml select, editor select} ×
|
||||
/// {toml ignore, editor ignore}, against the ladder. The editor's list
|
||||
/// wins when it says anything, the project's is used when it does not,
|
||||
/// and the two keys are decided **independently** — the CLI's `pick`,
|
||||
/// applied twice.
|
||||
#[test]
|
||||
fn the_editor_outranks_the_project_key_by_key() {
|
||||
// Four rules stand in for the whole registry: two the project may
|
||||
// name and two the editor may, so a row's answer says which list was
|
||||
// consulted rather than which happened to be shorter.
|
||||
// (toml select, editor select, toml ignore, editor ignore, expected).
|
||||
type Row = (
|
||||
&'static [&'static str],
|
||||
&'static [&'static str],
|
||||
&'static [&'static str],
|
||||
&'static [&'static str],
|
||||
&'static [&'static str],
|
||||
);
|
||||
let rows: [Row; 8] = [
|
||||
// (toml select, editor select, toml ignore, editor ignore) => rules
|
||||
(&[], &[], &[], &[], &[]),
|
||||
(&["no-tabs"], &[], &[], &[], &["no-tabs"]),
|
||||
(&[], &["no-tabs"], &[], &[], &["no-tabs"]),
|
||||
(&["module-name-style"], &["no-tabs"], &[], &[], &["no-tabs"]),
|
||||
(&["no-tabs", "module-name-style"], &[], &["no-tabs"], &[], &["module-name-style"]),
|
||||
(&["no-tabs", "module-name-style"], &[], &[], &["no-tabs"], &["module-name-style"]),
|
||||
(
|
||||
&["no-tabs", "module-name-style"],
|
||||
&[],
|
||||
&["module-name-style"],
|
||||
&["no-tabs"],
|
||||
&["module-name-style"],
|
||||
),
|
||||
(
|
||||
&["module-name-style"],
|
||||
&["no-tabs", "module-name-style"],
|
||||
&["no-tabs"],
|
||||
&["module-name-style"],
|
||||
&["no-tabs"],
|
||||
),
|
||||
];
|
||||
for (toml_select, ed_select, toml_ignore, ed_ignore, want) in rows {
|
||||
let settings = editor(ed_select, ed_ignore);
|
||||
let from_file = project(toml_select, toml_ignore);
|
||||
let got = names(&settings, &from_file, false);
|
||||
if want.is_empty() {
|
||||
// The empty row is the base set, which is too long to spell.
|
||||
assert_eq!(
|
||||
got,
|
||||
super::super::default_rules().iter().map(|r| r.name()).collect::<Vec<_>>(),
|
||||
"neither list said anything, so the base set stands"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(
|
||||
got, want,
|
||||
"{toml_select:?} {ed_select:?} {toml_ignore:?} {ed_ignore:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A severity word stands for its whole class in the toml's lists exactly
|
||||
/// as it does in the editor's, and as `--select style` does.
|
||||
#[test]
|
||||
fn a_severity_word_works_in_the_projects_lists_too() {
|
||||
let styled = names(&ClientSettings::default(), &project(&["style"], &[]), true);
|
||||
assert!(!styled.is_empty());
|
||||
assert!(styled
|
||||
.iter()
|
||||
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
|
||||
== Severity::Style));
|
||||
|
||||
let quiet = names(&ClientSettings::default(), &project(&[], &["style"]), true);
|
||||
assert!(!quiet.is_empty());
|
||||
assert!(quiet
|
||||
.iter()
|
||||
.all(|name| vlog_linter::rule_by_name(name).expect("a rule").severity()
|
||||
!= Severity::Style));
|
||||
}
|
||||
|
||||
/// A rung 3 or 4 switch is the editor's alone, and still applies over a
|
||||
/// selection the project made.
|
||||
#[test]
|
||||
fn the_editor_only_rungs_still_apply_over_a_project_selection() {
|
||||
let mut settings = ClientSettings::default();
|
||||
settings.lint_severity.insert(Severity::Style, false);
|
||||
let from_file = project(&["no-tabs", "wire-reg-mixup"], &[]);
|
||||
assert_eq!(
|
||||
names(&settings, &from_file, false),
|
||||
vec!["wire-reg-mixup"],
|
||||
"the class switch removes the project's style rule"
|
||||
);
|
||||
|
||||
settings.lint_rules.insert("no-tabs".to_string(), true);
|
||||
assert_eq!(
|
||||
names(&settings, &from_file, false),
|
||||
vec!["no-tabs", "wire-reg-mixup"],
|
||||
"and the per-rule word puts it back"
|
||||
);
|
||||
}
|
||||
|
||||
/// A name the registry does not know is dropped and reported — the run
|
||||
/// `lucisv check` would have failed keeps going here with what was
|
||||
/// understood.
|
||||
#[test]
|
||||
fn an_unknown_name_in_the_projects_list_is_dropped_and_said() {
|
||||
let (from_file, problems) =
|
||||
ProjectLint::read(&config("[lint]\nselect = [\"no-tab\", \"no-tabs\"]\n"));
|
||||
assert_eq!(from_file.select, vec!["no-tabs"]);
|
||||
assert_eq!(problems, vec!["/rtl/lucisv.toml: [lint] select: unknown rule: no-tab"]);
|
||||
assert_eq!(names(&ClientSettings::default(), &from_file, false), vec!["no-tabs"]);
|
||||
|
||||
// Every name unknown leaves the list empty, which is the base set —
|
||||
// the safe direction: some rules rather than none.
|
||||
let (none, problems) = ProjectLint::read(&config("[lint]\nselect = [\"nope\"]\n"));
|
||||
assert!(none.select.is_empty());
|
||||
assert_eq!(problems.len(), 1);
|
||||
assert_eq!(
|
||||
names(&ClientSettings::default(), &none, false),
|
||||
super::super::default_rules().iter().map(|r| r.name()).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
/// §42.2: a `[lint.<rule>]` entry the registry refuses is reported once,
|
||||
/// however many lint passes run, and the buffer keeps being linted.
|
||||
#[test]
|
||||
fn a_rejected_option_is_said_once_and_the_lint_still_runs() {
|
||||
let dir = std::env::temp_dir()
|
||||
.join(format!("lucisv_lint_project_{}_rejected", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
std::fs::write(dir.join("lucisv.toml"), "[lint.line-length]\nlength = \"wide\"\n")
|
||||
.expect("write config");
|
||||
let path = dir.join("m.sv");
|
||||
let text = "module m;\n\twire a;\nendmodule\n";
|
||||
std::fs::write(&path, text).expect("write source");
|
||||
|
||||
let uri = Uri::from_str(&format!("file://{}", path.display())).expect("uri");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
let mut log = ProblemLog::default();
|
||||
|
||||
let mut said = Vec::new();
|
||||
for _ in 0..3 {
|
||||
let doc: &Document = ws.document(&uri).expect("open");
|
||||
let run = super::super::LintRun::for_document(&ws, doc);
|
||||
// The lint still runs: the tab is still a finding.
|
||||
assert!(
|
||||
super::super::violations_in(doc, &run).iter().any(|v| v.rule == "no-tabs"),
|
||||
"the buffer is still linted with the entry dropped"
|
||||
);
|
||||
said.extend(log.unsaid(run.config_problems()));
|
||||
}
|
||||
assert_eq!(said.len(), 1, "said once across three passes: {said:#?}");
|
||||
let expected = format!("{}:2: rule `line-length` ", dir.join("lucisv.toml").display());
|
||||
assert!(said[0].starts_with(&expected), "the wording `lucisv check` prints: {}", said[0]);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// An edited config gets a fresh hearing: the memo is keyed by the file's
|
||||
/// lint content, so the same mistake made again after a change is said
|
||||
/// again.
|
||||
#[test]
|
||||
fn an_edited_config_re_arms_the_report() {
|
||||
let first = config("[lint.line-length]\nlength = \"wide\"\n");
|
||||
let problems = ConfigProblems::new(&first, vec!["/rtl/lucisv.toml:2: bad".to_string()]);
|
||||
let mut log = ProblemLog::default();
|
||||
assert_eq!(log.unsaid(&problems).len(), 1);
|
||||
assert!(log.unsaid(&problems).is_empty(), "and not twice");
|
||||
|
||||
// Same message, different file content: the user has been editing.
|
||||
let edited = config("# a comment\n[lint.line-length]\nlength = \"wide\"\n");
|
||||
let again = ConfigProblems::new(&edited, vec!["/rtl/lucisv.toml:3: bad".to_string()]);
|
||||
assert_eq!(log.unsaid(&again).len(), 1, "a changed config is heard again");
|
||||
|
||||
// A buffer with no config file has nothing to report.
|
||||
let nowhere = ConfigProblems::new(&FileConfig::default(), vec!["never".to_string()]);
|
||||
assert!(log.unsaid(&nowhere).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -94,10 +94,44 @@ impl Server {
|
||||
fn diagnostics_of(&self, uri: &Uri) -> Vec<lsp_types::Diagnostic> {
|
||||
let Some(doc) = self.workspace.document(uri) else { return Vec::new() };
|
||||
// The lint pass is given the project: the rule selection
|
||||
// `lucisv.lint.*` resolved to, and the index's identifier census, which
|
||||
// is what lets the semantic rules default on here without accusing a
|
||||
// signal another file reads (`docs/features/semantic-lints-on/`).
|
||||
diagnostics::all_in(doc, &crate::lint::LintRun::for_document(&self.workspace, doc))
|
||||
// `lucisv.lint.*` and the buffer's `[lint]` table resolved to, and the
|
||||
// index's identifier census, which is what lets the semantic rules
|
||||
// default on here without accusing a signal another file reads
|
||||
// (`docs/features/semantic-lints-on/`).
|
||||
let run = crate::lint::LintRun::for_document(&self.workspace, doc);
|
||||
self.report_config_problems(&run);
|
||||
diagnostics::all_in(doc, &run)
|
||||
}
|
||||
|
||||
/// Say, once, what this buffer's `lucisv.toml` asked for and did not get.
|
||||
///
|
||||
/// Once per (config file, entry), not once per pass: this runs on every
|
||||
/// keystroke and every index rebuild. The words are the ones `lucisv
|
||||
/// check` fails the run with, `<file>:<line>: <message>`, so one mistake
|
||||
/// reads the same in CI and here — but nothing is fatal, the entry is
|
||||
/// dropped and the buffer is still linted with everything understood
|
||||
/// (§42.2). Logged, not shown: a typo in a checked-in config is not worth
|
||||
/// a popup on every editor in the project.
|
||||
fn report_config_problems(&self, run: &crate::lint::LintRun) {
|
||||
let problems = run.config_problems();
|
||||
if problems.is_empty() {
|
||||
return;
|
||||
}
|
||||
// The borrow is released before anything is sent: `notify` takes
|
||||
// `&self` and could otherwise reach a second borrow one day.
|
||||
let unsaid = match self.lint_config_problems.try_borrow_mut() {
|
||||
Ok(mut log) => log.unsaid(problems),
|
||||
Err(_) => return,
|
||||
};
|
||||
for message in unsaid {
|
||||
self.notify(
|
||||
LogMessage::METHOD,
|
||||
LogMessageParams {
|
||||
typ: MessageType::WARNING,
|
||||
message: format!("lucisv: {message}; ignored"),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Publish everything known about a buffer — parse errors and lint
|
||||
|
||||
@@ -45,7 +45,7 @@ use super::client::ms;
|
||||
use super::Server;
|
||||
use crate::{
|
||||
code_action, completion, design_hierarchy, file_ops, folding, format, hierarchy, hover,
|
||||
includes, inlay, inline, lens, linked, nav, pairs, ports, rename, selection, signature,
|
||||
includes, inlay, inline, lens, linked, lint, nav, pairs, ports, rename, selection, signature,
|
||||
symbols, tokens, type_def, type_hierarchy,
|
||||
};
|
||||
|
||||
@@ -251,8 +251,9 @@ impl Server {
|
||||
// or from the built-in default.
|
||||
let tab_width =
|
||||
format::indent_width(doc.path.as_deref(), self.workspace.client_settings());
|
||||
let run = lint::LintRun::for_document(&self.workspace, doc);
|
||||
let mut actions =
|
||||
code_action::code_actions(&uri, doc, p.range, only.as_deref(), tab_width);
|
||||
code_action::code_actions(&run, &uri, doc, p.range, only.as_deref(), tab_width);
|
||||
// The port refactorings answer for the cursor, not for a range:
|
||||
// the request's start is where the user is.
|
||||
if code_action::wanted(only.as_deref(), &CodeActionKind::new(ports::REFACTOR_PORTS))
|
||||
|
||||
@@ -121,6 +121,19 @@ pub struct Server {
|
||||
/// for a document whenever its text changes, so the warning is said once
|
||||
/// per file change rather than once per format-on-save.
|
||||
config_warnings: HashSet<Uri>,
|
||||
/// Which `[lint]` entries of which `lucisv.toml` have already been
|
||||
/// reported (§42.2). Interior-mutable because a lint pass runs behind
|
||||
/// `&self` — the pull models compute diagnostics inside a `map` over the
|
||||
/// open buffers — and the memo is the one thing a pass has to write.
|
||||
/// Nothing is called while it is borrowed.
|
||||
lint_config_problems: std::cell::RefCell<crate::lint::ProblemLog>,
|
||||
/// The unknown-rule-name lines already logged for the **editor's**
|
||||
/// `lucisv.lint.select`/`ignore` (§45.1), exactly as the last settings
|
||||
/// value produced them. A client that re-pushes the same section — VS Code
|
||||
/// does, whenever anything in it changes — says nothing again; a list the
|
||||
/// user edited re-arms every name that is new to it. The project file's
|
||||
/// twin memo is `lint_config_problems` above.
|
||||
said_lint_names: Vec<String>,
|
||||
abilities: ClientAbilities,
|
||||
/// The id of the file-watcher registration in force, if any. Kept so a
|
||||
/// changed `lucisv.filelist` can replace it: the watched filelist path is
|
||||
@@ -300,6 +313,8 @@ impl Server {
|
||||
connection,
|
||||
workspace: Workspace::default(),
|
||||
config_warnings: HashSet::new(),
|
||||
lint_config_problems: std::cell::RefCell::default(),
|
||||
said_lint_names: Vec::new(),
|
||||
abilities,
|
||||
watchers: None,
|
||||
registrations: 0,
|
||||
|
||||
@@ -25,7 +25,7 @@ use serde::de::DeserializeOwned;
|
||||
use super::batch::{widen_of, Widen};
|
||||
use super::client::ms;
|
||||
use super::Server;
|
||||
use crate::{file_ops, settings, sync, watch};
|
||||
use crate::{file_ops, lint, settings, sync, watch};
|
||||
|
||||
impl Server {
|
||||
/// Handle one notification, timing it when `--verbose` asked. A
|
||||
@@ -259,6 +259,38 @@ impl Server {
|
||||
},
|
||||
);
|
||||
}
|
||||
// A name in `lucisv.lint.select`/`ignore` the registry does not know is
|
||||
// dropped just as silently, and the same typo in a `lucisv.toml`'s
|
||||
// `[lint] select` has been said since §42. Said here too — but **once**
|
||||
// per (setting, name): unlike the options warnings above, which cost a
|
||||
// line each time the setting arrives, a client that re-pushes its whole
|
||||
// section on every keystroke must not repeat these. A list the user
|
||||
// edited re-arms whatever is new in it. See §2.9-29.
|
||||
for warning in unsaid(&settings.lint_name_warnings, &self.said_lint_names) {
|
||||
self.notify(
|
||||
LogMessage::METHOD,
|
||||
LogMessageParams {
|
||||
typ: MessageType::WARNING,
|
||||
message: format!("lucisv: {warning}"),
|
||||
},
|
||||
);
|
||||
}
|
||||
self.said_lint_names.clone_from(&settings.lint_name_warnings);
|
||||
// And the same for `lucisv.lint.waivers`: a file that is not there, or
|
||||
// a directive that does not parse, is dropped and said once — here,
|
||||
// where the setting arrives, rather than on every keystroke from the
|
||||
// lint pass that reads the files. Only the setting's own files are
|
||||
// checked; a `lucisv.toml`'s `[lint] waivers` is that file's problem
|
||||
// and `lucisv check` fails the run over it.
|
||||
for problem in waiver_problems(&settings, self.workspace.roots()) {
|
||||
self.notify(
|
||||
LogMessage::METHOD,
|
||||
LogMessageParams {
|
||||
typ: MessageType::WARNING,
|
||||
message: format!("lucisv: lucisv.lint.waivers: {problem}; ignored"),
|
||||
},
|
||||
);
|
||||
}
|
||||
// Only `exclude` and `filelist` change which files exist as far as
|
||||
// this server is concerned; the other settings are read afresh by the
|
||||
// next request that wants them and need no invalidation.
|
||||
@@ -322,3 +354,32 @@ fn closing_uri(notification: &Notification) -> Option<Uri> {
|
||||
fn folder_paths(folders: &[WorkspaceFolder]) -> Vec<std::path::PathBuf> {
|
||||
folders.iter().filter_map(|folder| crate::uri::uri_to_path(&folder.uri)).collect()
|
||||
}
|
||||
|
||||
/// What `lucisv.lint.waivers` names that could not be used: a file that is not
|
||||
/// there, or a directive that does not parse.
|
||||
///
|
||||
/// Read here rather than trusted, because a path is not something a settings
|
||||
/// parser can validate: only opening the file says whether it exists. The
|
||||
/// files are read again by the lint pass that actually applies them — a few
|
||||
/// small files beside a parse and an analysis — which keeps one reader for
|
||||
/// both and no cache to go stale when the user edits a waiver file.
|
||||
fn waiver_problems(
|
||||
settings: &settings::ClientSettings,
|
||||
roots: &[std::path::PathBuf],
|
||||
) -> Vec<String> {
|
||||
if settings.lint_waivers.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let paths = lint::waiver_paths(settings, roots, &lucisv_core::config::FileConfig::default());
|
||||
lint::external_waivers(&paths).1
|
||||
}
|
||||
|
||||
/// The lines of `warnings` that `said` does not already hold, in order.
|
||||
///
|
||||
/// The whole of §45.1's "once": the memo is the previous settings value's own
|
||||
/// warning list, so re-pushing a section says nothing and editing the list
|
||||
/// says exactly what is new in it. Both lists are a handful of entries at
|
||||
/// most — one per typo — so a scan is cheaper than a set.
|
||||
fn unsaid<'a>(warnings: &'a [String], said: &[String]) -> Vec<&'a String> {
|
||||
warnings.iter().filter(|w| !said.contains(w)).collect()
|
||||
}
|
||||
@@ -408,3 +408,95 @@ fn an_answer_to_a_request_the_server_never_tracked_is_silently_ignored() {
|
||||
session.answer(RequestId::from("never-sent".to_string()), serde_json::json!([{ "indent": 2 }]));
|
||||
assert_eq!(session.server.workspace.client_settings().indent, Some(4));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the editor's unknown rule name (TODO §45.1, docs/topo.md §2.9-29)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A `didChangeConfiguration` push with the given `lucisv.lint` section.
|
||||
fn push_lint(session: &mut Session, lint: Value) {
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "lint": lint } } }),
|
||||
);
|
||||
}
|
||||
|
||||
/// The unknown-rule lines the server logged since the last drain.
|
||||
fn unknown_rule_lines(session: &Session) -> Vec<String> {
|
||||
session
|
||||
.logged()
|
||||
.into_iter()
|
||||
.map(|(_, message)| message)
|
||||
.filter(|message| message.contains("unknown rule"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_rule_name_in_the_editors_select_is_logged_once() {
|
||||
let tree = Tree::new("unknownrule");
|
||||
tree.write("m.sv", "module m;\nendmodule\n");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
|
||||
push_lint(&mut session, serde_json::json!({ "select": ["no-tabs", "no-tab"] }));
|
||||
assert_eq!(
|
||||
unknown_rule_lines(&session),
|
||||
["lucisv: lucisv.lint.select: unknown rule: no-tab"],
|
||||
"said once, naming the list and the name"
|
||||
);
|
||||
|
||||
// Four diagnostics passes later it has not been said again: the pass runs
|
||||
// on every keystroke and the log is not a place to shout from.
|
||||
for _ in 0..4 {
|
||||
session.server.publish(&uri);
|
||||
}
|
||||
assert!(unknown_rule_lines(&session).is_empty(), "not repeated by a diagnostics pass");
|
||||
|
||||
// Nor by the same section arriving again, which is what VS Code sends
|
||||
// whenever anything at all in it changes.
|
||||
push_lint(&mut session, serde_json::json!({ "select": ["no-tabs", "no-tab"] }));
|
||||
assert!(unknown_rule_lines(&session).is_empty(), "not repeated by an identical push");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_list_re_arms_the_log() {
|
||||
let tree = Tree::new("unknownrulearm");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let _ = session.drain();
|
||||
|
||||
push_lint(&mut session, serde_json::json!({ "select": ["no-tab"] }));
|
||||
assert_eq!(unknown_rule_lines(&session).len(), 1);
|
||||
|
||||
// A second typo added to the list is new, and is said; the first is not.
|
||||
push_lint(&mut session, serde_json::json!({ "select": ["no-tab", "nope"] }));
|
||||
assert_eq!(
|
||||
unknown_rule_lines(&session),
|
||||
["lucisv: lucisv.lint.select: unknown rule: nope"],
|
||||
"only what is new in the list"
|
||||
);
|
||||
|
||||
// Cleared and re-typed: the memo is the previous value, so it is armed
|
||||
// again.
|
||||
push_lint(&mut session, serde_json::json!({ "select": [] }));
|
||||
assert!(unknown_rule_lines(&session).is_empty(), "an empty list has nothing to say");
|
||||
push_lint(&mut session, serde_json::json!({ "select": ["no-tab"] }));
|
||||
assert_eq!(unknown_rule_lines(&session).len(), 1, "re-armed by the change");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_select_emptied_by_the_dropping_falls_through_the_ladder_unchanged() {
|
||||
// §42's ladder: a `select` that named nothing the registry knows is an
|
||||
// empty `select`, which is no opinion at all — the project's list, then
|
||||
// the base set. The log line is the whole of what §45.1 changed.
|
||||
let tree = Tree::new("unknownruleladder");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let base = settings::lint_selection(session.server.workspace.client_settings());
|
||||
let _ = session.drain();
|
||||
|
||||
push_lint(&mut session, serde_json::json!({ "select": ["no-tab", "nope"] }));
|
||||
assert_eq!(unknown_rule_lines(&session).len(), 2, "both names said");
|
||||
let now = session.server.workspace.client_settings();
|
||||
assert!(now.lint_select.is_empty(), "the dropping left an empty select");
|
||||
assert_eq!(settings::lint_selection(now), base, "and the rule set is untouched");
|
||||
}
|
||||
@@ -202,6 +202,27 @@ pub struct ClientSettings {
|
||||
/// One line per refused `lucisv.lint.options` entry, ready for a
|
||||
/// `window/logMessage`. Empty for a settings push that was all valid.
|
||||
pub lint_option_warnings: Vec<String>,
|
||||
/// One line per name in `lucisv.lint.select` / `lucisv.lint.ignore` that
|
||||
/// the registry does not know, in the shape
|
||||
/// `lucisv.lint.select: unknown rule: <name>`.
|
||||
///
|
||||
/// Separate from [`ClientSettings::lint_option_warnings`] because the two
|
||||
/// are said differently: an options warning is raised every time the
|
||||
/// setting arrives, while an unknown name is said **once** per (setting,
|
||||
/// name) and re-armed only when the list changes — a client that re-pushes
|
||||
/// its whole section on every keystroke must not repeat it
|
||||
/// (`docs/features/small-items-4/README.md`).
|
||||
pub lint_name_warnings: Vec<String>,
|
||||
/// `lucisv.lint.waivers`: external waiver files, each absolute or relative
|
||||
/// to the first workspace root — the editor's spelling of
|
||||
/// `lucisv check --waiver-file` and of `waivers` under `[lint]` in a
|
||||
/// `lucisv.toml`. They **add** to whatever that table names.
|
||||
///
|
||||
/// The paths are taken as written and nothing is read here: whether a file
|
||||
/// exists and whether its directives parse is answered where the files are
|
||||
/// read (`lint::external_waivers`), and reported once through the log when
|
||||
/// this value arrives.
|
||||
pub lint_waivers: Vec<String>,
|
||||
}
|
||||
|
||||
/// The settings a client that said nothing is treated as having asked for.
|
||||
@@ -232,6 +253,8 @@ impl Default for ClientSettings {
|
||||
lint_rules: BTreeMap::new(),
|
||||
lint_options: RuleOptions::new(),
|
||||
lint_option_warnings: Vec::new(),
|
||||
lint_name_warnings: Vec::new(),
|
||||
lint_waivers: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -246,8 +269,14 @@ fn every_class_on() -> BTreeMap<Severity, bool> {
|
||||
///
|
||||
/// Its only use is equality — the server compares it across a settings change
|
||||
/// to decide whether every open file must be published again.
|
||||
pub type LintSelection =
|
||||
(Vec<String>, Vec<String>, BTreeMap<Severity, bool>, BTreeMap<String, bool>, RuleOptions);
|
||||
pub type LintSelection = (
|
||||
Vec<String>,
|
||||
Vec<String>,
|
||||
BTreeMap<Severity, bool>,
|
||||
BTreeMap<String, bool>,
|
||||
RuleOptions,
|
||||
Vec<String>,
|
||||
);
|
||||
|
||||
/// The lint settings of `settings`, as one comparable value.
|
||||
///
|
||||
@@ -262,6 +291,9 @@ pub fn lint_selection(settings: &ClientSettings) -> LintSelection {
|
||||
settings.lint_severity.clone(),
|
||||
settings.lint_rules.clone(),
|
||||
settings.lint_options.clone(),
|
||||
// A waiver file added or dropped changes which findings survive, so it
|
||||
// republishes for exactly the reason a changed option does.
|
||||
settings.lint_waivers.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -293,6 +325,11 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
||||
// And `lucisv.lint.select` / `lucisv.lint.ignore` the same way again.
|
||||
let lint = lucisv.get("lint");
|
||||
let (options, warnings) = rule_options(lint.and_then(|l| l.get("options")));
|
||||
// The names the registry did not know, collected as the two lists are
|
||||
// filtered so the user hears about a typo instead of losing a rule to it.
|
||||
let mut names = Vec::new();
|
||||
let lint_select = rules(lint.and_then(|l| l.get("select")), "select", &mut names);
|
||||
let lint_ignore = rules(lint.and_then(|l| l.get("ignore")), "ignore", &mut names);
|
||||
ClientSettings {
|
||||
line_length: bounded(lucisv.get("lineLength"), LINE_LENGTH_RANGE),
|
||||
indent: bounded(lucisv.get("indent"), INDENT_RANGE),
|
||||
@@ -334,25 +371,44 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
||||
// prevent.
|
||||
large_file_threshold: count(large_file.and_then(|f| f.get("threshold")))
|
||||
.unwrap_or(DEFAULT_LARGE_FILE_THRESHOLD),
|
||||
lint_select: rules(lint.and_then(|l| l.get("select"))),
|
||||
lint_ignore: rules(lint.and_then(|l| l.get("ignore"))),
|
||||
lint_select,
|
||||
lint_ignore,
|
||||
// `lucisv.lint.severity.<class>` and `lucisv.lint.rules.<name>` nest
|
||||
// one level deeper again, for the same reason `index.*` does.
|
||||
lint_severity: severity_switches(lint.and_then(|l| l.get("severity"))),
|
||||
lint_rules: rule_toggles(lint.and_then(|l| l.get("rules"))),
|
||||
lint_options: options,
|
||||
lint_option_warnings: warnings,
|
||||
lint_name_warnings: names,
|
||||
// Paths, not rule names: nothing to validate against the registry, and
|
||||
// a path that names nothing is reported when the file is read.
|
||||
lint_waivers: strings(lint.and_then(|l| l.get("waivers"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The rule names in a settings array, dropping every one that names neither a
|
||||
/// rule nor a severity class.
|
||||
/// rule nor a severity class and describing each drop in `warnings`.
|
||||
///
|
||||
/// Silence rather than an error, on this module's standing rule: a push is
|
||||
/// JSON on a socket, and a typo in one name must not cost the user every
|
||||
/// diagnostic in the file. A dropped name leaves the rule where it was.
|
||||
fn rules(value: Option<&Value>) -> Vec<String> {
|
||||
strings(value).into_iter().filter(|name| vlog_linter::rules_named(name).is_some()).collect()
|
||||
/// The drop itself is this module's standing rule: a push is JSON on a socket,
|
||||
/// and a typo in one name must not cost the user every diagnostic in the file,
|
||||
/// so a name the registry does not know leaves the rule where it was. Silence
|
||||
/// about it was not the rule, only the state of things — `[lint] select` in a
|
||||
/// `lucisv.toml` has said the same mistake out loud since §42, and this is the
|
||||
/// editor's half of that (`docs/topo.md` §2.9-29).
|
||||
///
|
||||
/// `setting` is `select` or `ignore`, so the line names the list the user
|
||||
/// typed in.
|
||||
fn rules(value: Option<&Value>, setting: &str, warnings: &mut Vec<String>) -> Vec<String> {
|
||||
strings(value)
|
||||
.into_iter()
|
||||
.filter(|name| {
|
||||
let known = vlog_linter::rules_named(name).is_some();
|
||||
if !known {
|
||||
warnings.push(format!("lucisv.lint.{setting}: unknown rule: {name}"));
|
||||
}
|
||||
known
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The three class master switches, each `true` unless a client turned it off.
|
||||
@@ -878,6 +934,39 @@ mod tests {
|
||||
}}}));
|
||||
assert_eq!(found.lint_select, vec!["style", "no-tabs"]);
|
||||
assert_eq!(found.lint_ignore, vec!["warning"]);
|
||||
// And the one name that is neither is described, not just dropped.
|
||||
assert_eq!(found.lint_name_warnings, vec!["lucisv.lint.select: unknown rule: nope"]);
|
||||
}
|
||||
|
||||
/// TODO §45.1: a name the registry does not know is still dropped — the
|
||||
/// rule stays where it was — and now says so, once per name, naming the
|
||||
/// list the user typed it in.
|
||||
#[test]
|
||||
fn an_unknown_rule_name_is_described_for_each_list_it_appears_in() {
|
||||
let found = settings(json!({"lucisv": {"lint": {
|
||||
"select": ["no-tabs", "nope", "also-nope"],
|
||||
"ignore": ["nope"],
|
||||
}}}));
|
||||
assert_eq!(found.lint_select, vec!["no-tabs"]);
|
||||
assert!(found.lint_ignore.is_empty());
|
||||
assert_eq!(
|
||||
found.lint_name_warnings,
|
||||
vec![
|
||||
"lucisv.lint.select: unknown rule: nope",
|
||||
"lucisv.lint.select: unknown rule: also-nope",
|
||||
"lucisv.lint.ignore: unknown rule: nope",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_lists_of_known_names_describe_nothing() {
|
||||
let found = settings(json!({"lucisv": {"lint": {
|
||||
"select": ["no-tabs", "error"],
|
||||
"ignore": ["unused-signal"],
|
||||
}}}));
|
||||
assert!(found.lint_name_warnings.is_empty(), "{:?}", found.lint_name_warnings);
|
||||
assert!(settings(json!({"lucisv": {}})).lint_name_warnings.is_empty());
|
||||
}
|
||||
|
||||
/// What the server compares two settings pushes by, to decide whether the
|
||||
@@ -957,6 +1046,30 @@ mod tests {
|
||||
assert_eq!(found.max_file_size, DEFAULT_MAX_FILE_SIZE);
|
||||
}
|
||||
|
||||
/// `lucisv.lint.waivers` is a list of paths, taken as written: this module
|
||||
/// has no filesystem to check them against, and whether a file exists or
|
||||
/// parses is answered where it is read. TODO §39.
|
||||
#[test]
|
||||
fn the_waivers_setting_is_a_list_of_paths_taken_as_written() {
|
||||
let found = settings(json!({"lucisv": {"lint": {
|
||||
"waivers": ["project.waiver", "/abs/other.waiver", 7, null]
|
||||
}}}));
|
||||
assert_eq!(found.lint_waivers, vec!["project.waiver", "/abs/other.waiver"]);
|
||||
assert!(settings(json!({"lucisv": {"lint": {}}})).lint_waivers.is_empty());
|
||||
// Wrong-typed altogether: the whole list is "no opinion", never a
|
||||
// guess, exactly as `select` and `exclude` are.
|
||||
for bad in [json!("project.waiver"), json!(3), json!(null), json!({"a": 1})] {
|
||||
assert!(
|
||||
settings(json!({"lucisv": {"lint": {"waivers": bad}}})).lint_waivers.is_empty(),
|
||||
"waivers {bad} must be ignored"
|
||||
);
|
||||
}
|
||||
// A changed list republishes, for the reason a changed option does.
|
||||
let one = settings(json!({"lucisv": {"lint": {"waivers": ["a.waiver"]}}}));
|
||||
let two = settings(json!({"lucisv": {"lint": {"waivers": ["b.waiver"]}}}));
|
||||
assert_ne!(lint_selection(&one), lint_selection(&two));
|
||||
}
|
||||
|
||||
/// A settings payload with no options object is exactly today's
|
||||
/// behaviour: every rule reads its own default.
|
||||
#[test]
|
||||
|
||||
@@ -625,6 +625,15 @@ impl Workspace {
|
||||
!self.roots.is_empty()
|
||||
}
|
||||
|
||||
/// The workspace folders, in the order the client named them.
|
||||
///
|
||||
/// The first one is what a relative path in a setting is resolved against,
|
||||
/// which is what [`Workspace::filelist_path`] does inline and what
|
||||
/// `lucisv.lint.waivers` needs too.
|
||||
pub fn roots(&self) -> &[PathBuf] {
|
||||
&self.roots
|
||||
}
|
||||
|
||||
/// The directories the folder scope walks: every directory a buffer has
|
||||
/// been opened from this session, each raised `lucisv.index.scopeDepth`
|
||||
/// levels. **Empty when the folder scope is not the active rung** — a
|
||||
@@ -999,11 +1008,12 @@ impl Workspace {
|
||||
self.docs.values().filter_map(|doc| doc.path.as_deref()).collect();
|
||||
let mut skipped = 0usize;
|
||||
let mut texts: Vec<(PathBuf, String)> = Vec::new();
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
// The walk of the *added* directories alone, by the same rung-3 rules
|
||||
// `folder_files` follows — the whole scope is the union of these walks,
|
||||
// so the files this one finds beyond what is already indexed are
|
||||
// exactly the ones the widen owes.
|
||||
for path in self.widened_files(added) {
|
||||
for path in self.widened_files(added, &mut |w| warnings.push(w)) {
|
||||
// Already indexed: by another scope directory this walk overlaps,
|
||||
// or by an earlier scan. Re-reading it is the cost this path
|
||||
// exists to avoid.
|
||||
@@ -1064,9 +1074,9 @@ impl Workspace {
|
||||
// `+incdir+`. Carried from the graph in hand rather than assumed
|
||||
// empty, so folding a widen in never *changes* the search path.
|
||||
incdirs: self.includes.incdirs().to_vec(),
|
||||
// Warnings come from resolving the scope, and a widen resolves no
|
||||
// filelist: rung 1 is not a scope an open buffer can widen.
|
||||
warnings: Vec::new(),
|
||||
// A widen resolves no filelist — rung 1 is not a scope an open
|
||||
// buffer can widen — so the only warnings here are the walk's own.
|
||||
warnings,
|
||||
at: 0,
|
||||
staged: Vec::new(),
|
||||
staged_at: Vec::new(),
|
||||
@@ -1079,11 +1089,11 @@ impl Workspace {
|
||||
/// The files the directories a widen added bring into scope, by the same
|
||||
/// rules [`Workspace::folder_files`] applies to the whole scope — including
|
||||
/// the rootless-at-depth-0 flat read.
|
||||
fn widened_files(&self, added: &[PathBuf]) -> Vec<PathBuf> {
|
||||
fn widened_files(&self, added: &[PathBuf], warn: &mut dyn FnMut(String)) -> Vec<PathBuf> {
|
||||
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
|
||||
return sibling_files(added);
|
||||
}
|
||||
self.walked_files(added)
|
||||
self.walked_files(added, warn)
|
||||
}
|
||||
|
||||
/// Index the next file of `scan`, reporting whether there was one.
|
||||
@@ -1511,6 +1521,10 @@ impl Workspace {
|
||||
/// `follow_paths` only ever looks a reference's *own* name up, so a
|
||||
/// set holding every declarer of `N` resolves every reference spelling
|
||||
/// `N` exactly as the whole workspace does;
|
||||
/// * **every file declaring `N` on a module's hierarchical surface**
|
||||
/// ([`WorkspaceIndex::hierarchical_declarations`]) — an internal net
|
||||
/// is not a workspace symbol, and a hierarchical tail in another file
|
||||
/// resolves to one;
|
||||
/// * **every file with a use the index resolved to one of them**
|
||||
/// ([`WorkspaceIndex::references_to`]) — every file a rename can edit,
|
||||
/// and every file whose meaning the verifier could see move;
|
||||
@@ -1594,6 +1608,19 @@ impl Workspace {
|
||||
containers.extend(symbol.container);
|
||||
self.want_declaration(symbol.def, wanted);
|
||||
}
|
||||
// And every declaration of it on a module's **hierarchical** surface,
|
||||
// which `workspace_symbols` deliberately does not list: an internal
|
||||
// net is not a workspace symbol, but `assign w = u_x.sig;` in another
|
||||
// file resolves to one and a rename must edit both ends. Without this
|
||||
// rung the fan-out would hold the file that *names* the net and not
|
||||
// the file that declares it (`docs/features/hierarchical-tail`).
|
||||
for (unit, def) in self.index.hierarchical_declarations(name) {
|
||||
if self.index.references_are_ambiguous(def) {
|
||||
return false;
|
||||
}
|
||||
containers.insert(unit);
|
||||
self.want_declaration(def, wanted);
|
||||
}
|
||||
self.want_sites(name, wanted);
|
||||
self.want_macro_text(name, wanted);
|
||||
for unit in containers {
|
||||
@@ -1858,16 +1885,21 @@ impl Workspace {
|
||||
/// none, so an `` `include`` there resolves against the including file's
|
||||
/// own directory alone (`docs/features/include-nav/README.md`).
|
||||
fn source_files(&self) -> Scope {
|
||||
// The walk's own warnings join the scope's, so an unreadable directory
|
||||
// reaches the output channel by the road a filelist's problems already
|
||||
// travel — said once per scan and never per keystroke.
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
let Some(path) = self.filelist_path() else {
|
||||
return Scope { files: self.default_files(), ..Default::default() };
|
||||
let files = self.default_files(&mut |w| warnings.push(w));
|
||||
return Scope { files, warnings, ..Default::default() };
|
||||
};
|
||||
match lucisv_core::filelist::read(&path) {
|
||||
Ok(list) => Scope { files: list.files, incdirs: list.incdirs, warnings: list.warnings },
|
||||
Err(problem) => Scope {
|
||||
files: self.default_files(),
|
||||
incdirs: Vec::new(),
|
||||
warnings: vec![format!("{problem} — indexing the workspace instead")],
|
||||
},
|
||||
Err(problem) => {
|
||||
let files = self.default_files(&mut |w| warnings.push(w));
|
||||
warnings.insert(0, format!("{problem} — indexing the workspace instead"));
|
||||
Scope { files, incdirs: Vec::new(), warnings }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1894,11 +1926,11 @@ impl Workspace {
|
||||
|
||||
/// Rungs 2 and 3 of the ladder: the whole-workspace walk when the client
|
||||
/// asked for it, else the folder scope.
|
||||
fn default_files(&self) -> Vec<PathBuf> {
|
||||
fn default_files(&self, warn: &mut dyn FnMut(String)) -> Vec<PathBuf> {
|
||||
if self.walks_the_workspace() {
|
||||
return self.walked_files(&self.roots);
|
||||
return self.walked_files(&self.roots, warn);
|
||||
}
|
||||
self.folder_files()
|
||||
self.folder_files(warn)
|
||||
}
|
||||
|
||||
/// Rung 3: the folder scope — [`Workspace::scope_dirs`], walked with every
|
||||
@@ -1910,12 +1942,12 @@ impl Workspace {
|
||||
/// case, where descending a tree the user never named would be a surprise
|
||||
/// — and the moment the user raises `scopeDepth` they have named one, so
|
||||
/// the walk is what they asked for.
|
||||
fn folder_files(&self) -> Vec<PathBuf> {
|
||||
fn folder_files(&self, warn: &mut dyn FnMut(String)) -> Vec<PathBuf> {
|
||||
let dirs = self.scope_dirs();
|
||||
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
|
||||
return sibling_files(&dirs);
|
||||
}
|
||||
self.walked_files(&dirs)
|
||||
self.walked_files(&dirs, warn)
|
||||
}
|
||||
|
||||
/// Every source file under `dirs`, found by the CLI's own walk: the same
|
||||
@@ -1929,7 +1961,7 @@ impl Workspace {
|
||||
/// written in a root's `.gitignore` does not apply to a rung-3 walk that
|
||||
/// starts below it. The `exclude` patterns are matched against whole
|
||||
/// paths and so behave identically either way.
|
||||
fn walked_files(&self, dirs: &[PathBuf]) -> Vec<PathBuf> {
|
||||
fn walked_files(&self, dirs: &[PathBuf], warn: &mut dyn FnMut(String)) -> Vec<PathBuf> {
|
||||
let mut discovery = Discovery::new(true);
|
||||
let mut out = Vec::new();
|
||||
for root in dirs {
|
||||
@@ -1949,8 +1981,9 @@ impl Workspace {
|
||||
exclude.extend(self.client.exclude.iter().cloned());
|
||||
// `.gitignore` is always honoured: it is the CLI's default, and an
|
||||
// editor has no `--no-gitignore` to type. An unreadable directory
|
||||
// is simply not indexed, exactly as before this walk was shared.
|
||||
let _ = collect_files(input, &exclude, true, &mut out);
|
||||
// is skipped and said — the warning rides out on the scope's own
|
||||
// warnings, which `server/notification.rs` logs once per scan.
|
||||
let _ = collect_files(input, &exclude, true, &mut out, &mut |w| warn(w.to_string()));
|
||||
}
|
||||
out.sort();
|
||||
out.dedup();
|
||||
@@ -2721,6 +2754,33 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A workspace whose tree links back into itself. Before the walk kept a
|
||||
/// visited set (`docs/features/walk-cycles/README.md`) this scan never
|
||||
/// finished — the editor's index simply never came up. Each directory is
|
||||
/// entered once now, so each package is registered exactly once: a second
|
||||
/// registration would make the name *ambiguous*, and `indexed` only
|
||||
/// counts a name found exactly once.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_cyclic_workspace_is_scanned_once_and_finishes() {
|
||||
let tree = Tree::new("cycle");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/sub/b.sv", "b");
|
||||
// `rtl/self` is `rtl` itself; `rtl/sub/up` is `rtl` from one level
|
||||
// down. Either one alone runs until the OS refuses a path.
|
||||
std::os::unix::fs::symlink("../rtl", tree.path.join("rtl/self")).expect("symlink");
|
||||
std::os::unix::fs::symlink("..", tree.path.join("rtl/sub/up")).expect("symlink");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["a", "b"]), ["a", "b"]);
|
||||
assert_eq!(
|
||||
ws.walked_files(from_ref(&tree.path), &mut |_| {}).len(),
|
||||
2,
|
||||
"two files, once each"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_change_that_changes_nothing_asks_for_no_rescan() {
|
||||
// Every no-op shape a client can send. Each must leave the root set
|
||||
@@ -3328,6 +3388,35 @@ mod tests {
|
||||
assert!(warnings[0].contains("indexing the workspace instead"), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_unreadable_directory_is_said_once_per_scan_and_the_rest_is_indexed() {
|
||||
// TODO §45.2: the walk's warnings ride out on the scope's own
|
||||
// warnings, which the server logs once per scan. Before the channel
|
||||
// existed the walk returned an error the index simply dropped, so a
|
||||
// permission-denied directory cost every file after it silently.
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tree = Tree::new("walkwarn");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/z.sv", "z");
|
||||
tree.package("locked/hidden.sv", "hidden");
|
||||
std::os::unix::fs::symlink("nowhere.sv", tree.path.join("rtl/gone.sv")).expect("symlink");
|
||||
let locked = tree.path.join("locked");
|
||||
fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).expect("chmod");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
let warnings = ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let _ = fs::set_permissions(&locked, fs::Permissions::from_mode(0o755));
|
||||
|
||||
assert_eq!(indexed(&ws, &["a", "z", "hidden"]), ["a", "z"], "the scan finished");
|
||||
assert_eq!(warnings.len(), 2, "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains("locked")), "{warnings:?}");
|
||||
assert!(
|
||||
warnings.iter().any(|w| w.contains("gone.sv: broken symbolic link")),
|
||||
"{warnings:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filelists_own_warnings_reach_the_caller() {
|
||||
let tree = filelist_tree("filelistwarn");
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -7542,6 +7759,87 @@ fn the_lint_options_setting_changes_what_is_published_and_a_bad_entry_is_logged(
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `lucisv.lint.waivers` over the wire — TODO §39.
|
||||
///
|
||||
/// Four claims a unit test cannot make: that a `[lint] waivers` in a checked-in
|
||||
/// `lucisv.toml` suppresses a finding the editor would otherwise draw; that the
|
||||
/// setting *adds* a second file mid-session and the squiggle goes away without
|
||||
/// a reload; that a waiver file with one bad directive is dropped **line by
|
||||
/// line** — the good directives still apply — and logged once; and that the
|
||||
/// server never publishes an `unused-waiver` for an external waiver, because
|
||||
/// it never sees a whole run.
|
||||
#[test]
|
||||
fn the_waivers_setting_suppresses_findings_and_a_bad_directive_is_logged() {
|
||||
let dir = temp_dir("lintwaivers");
|
||||
std::fs::write(dir.join("lucisv.toml"), "[lint]\nwaivers = [ \"project.waiver\" ]\n")
|
||||
.expect("write");
|
||||
std::fs::write(dir.join("project.waiver"), "waive --rule=no-tabs --line=2\n").expect("write");
|
||||
// One good directive and one that does not parse: the good one must still
|
||||
// apply, which is what "drops the line, never the file" means.
|
||||
std::fs::write(
|
||||
dir.join("extra.waiver"),
|
||||
"waive --rule=no-tabs --line=3\nwaive --rule=no-such-rule\n",
|
||||
)
|
||||
.expect("write");
|
||||
let file = dir.join("tabs.sv");
|
||||
let text = "module tabs;\n\twire a;\n\twire b;\nendmodule\n";
|
||||
std::fs::write(&file, text).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
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(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(text).expect("json")
|
||||
)),
|
||||
// The editor's list adds to the `lucisv.toml`'s, relative to the root.
|
||||
frame(
|
||||
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"lint":{"waivers":["extra.waiver","gone.waiver"]}}}}}"#,
|
||||
),
|
||||
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 tabs: Vec<Vec<&str>> = messages
|
||||
.iter()
|
||||
.filter(|m| m["method"] == "textDocument/publishDiagnostics")
|
||||
.filter(|m| m["params"]["uri"] == uri.as_str())
|
||||
.map(|m| {
|
||||
m["params"]["diagnostics"]
|
||||
.as_array()
|
||||
.map(|list| list.iter().filter_map(|d| d["code"].as_str()).collect())
|
||||
.unwrap_or_default()
|
||||
})
|
||||
.collect();
|
||||
assert!(tabs.len() >= 2, "one publish per state: {tabs:?}");
|
||||
assert_eq!(tabs[0], vec!["no-tabs"], "the toml waived line 2, line 3 is left: {tabs:?}");
|
||||
assert!(
|
||||
tabs[tabs.len() - 1].is_empty(),
|
||||
"the setting's good directive waived line 3 without a reload: {tabs:?}"
|
||||
);
|
||||
for published in &tabs {
|
||||
assert!(!published.contains(&"unused-waiver"), "never from the server: {tabs:?}");
|
||||
}
|
||||
|
||||
let logged: Vec<&str> = messages
|
||||
.iter()
|
||||
.filter(|m| m["method"] == "window/logMessage")
|
||||
.filter_map(|m| m["params"]["message"].as_str())
|
||||
.filter(|text| text.contains("lucisv.lint.waivers"))
|
||||
.collect();
|
||||
assert_eq!(logged.len(), 2, "the bad directive and the missing file: {logged:?}");
|
||||
assert!(logged.iter().any(|line| line.contains("unknown rule")), "{logged:?}");
|
||||
assert!(logged.iter().any(|line| line.contains("gone.waiver")), "{logged:?}");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `lucisv.instantiate` — `docs/topo.md` §2.9-19. What only an e2e test can
|
||||
/// check: that the command is advertised in `initialize`, that its three
|
||||
/// arguments survive the wire, and that the skeleton arrives as a
|
||||
@@ -7677,3 +7975,557 @@ fn a_property_declaration_hovers_and_appears_in_the_outline() {
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// §42 — one lint-configuration contract for the project file and the editor.
|
||||
//
|
||||
// `docs/features/lint-config-contract/README.md`: the editor's settings play
|
||||
// the role the CLI's flags play, so a `lucisv.toml` a project checks in
|
||||
// governs an editor exactly as it governs CI, and a `lucisv.lint.*` setting
|
||||
// replaces it the way a flag replaces it.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// A buffer with one tab and one trailing space: two style findings from two
|
||||
/// rules, so a selection that keeps one and drops the other is visible.
|
||||
const TWO_FINDINGS: &str = "module lint_contract;\n\twire a; \nendmodule\n";
|
||||
|
||||
/// The rule codes of every `publishDiagnostics` for one URI, in the order
|
||||
/// they arrived, with a repeat of the previous answer collapsed: a republish
|
||||
/// that says the same thing is not a step.
|
||||
fn published_codes(messages: &[serde_json::Value], uri: &str) -> Vec<Vec<String>> {
|
||||
let mut steps: Vec<Vec<String>> = Vec::new();
|
||||
for message in messages {
|
||||
if message["method"] != "textDocument/publishDiagnostics"
|
||||
|| message["params"]["uri"] != serde_json::Value::String(uri.to_string())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut codes: Vec<String> = message["params"]["diagnostics"]
|
||||
.as_array()
|
||||
.expect("an array")
|
||||
.iter()
|
||||
.filter_map(|d| d["code"].as_str().map(str::to_string))
|
||||
.collect();
|
||||
codes.sort();
|
||||
codes.dedup();
|
||||
if steps.last() != Some(&codes) {
|
||||
steps.push(codes);
|
||||
}
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
/// The `initialize`/`didOpen` prefix every session below opens with.
|
||||
fn lint_session_start(dir: &Path, uri: &str, text: &str) -> String {
|
||||
let root = format!("file://{}", dir.display());
|
||||
[
|
||||
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(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(text).expect("json")
|
||||
)),
|
||||
]
|
||||
.concat()
|
||||
}
|
||||
|
||||
/// A `didChangeConfiguration` carrying one `lucisv.lint.select` list.
|
||||
fn select_push(rules: &str) -> String {
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"lucisv":{{"lint":{{"select":[{rules}]}}}}}}}}}}"#
|
||||
))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_projects_lint_select_governs_an_editor_until_a_setting_replaces_it() {
|
||||
let dir = temp_dir("lint_contract_select");
|
||||
std::fs::write(dir.join("lucisv.toml"), "[lint]\nselect = [\"no-tabs\"]\n")
|
||||
.expect("write config");
|
||||
let file = dir.join("lint_contract.sv");
|
||||
std::fs::write(&file, TWO_FINDINGS).expect("write");
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
let session = [
|
||||
lint_session_start(&dir, &uri, TWO_FINDINGS),
|
||||
// The editor names a rule of its own: it replaces the project's, as
|
||||
// `--select` replaces it on the command line.
|
||||
select_push("\"no-trailing-whitespace\""),
|
||||
// ... and taking the setting back restores the project's.
|
||||
select_push(""),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let steps = published_codes(&talk(&session), &uri);
|
||||
assert_eq!(
|
||||
steps,
|
||||
vec![
|
||||
vec!["no-tabs".to_string()],
|
||||
vec!["no-trailing-whitespace".to_string()],
|
||||
vec!["no-tabs".to_string()],
|
||||
],
|
||||
"the project selects, the editor replaces, and an emptied setting hands it back"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A `[lint.<rule>]` entry the registry refuses is said **once** in the
|
||||
/// output channel — in the words `lucisv check` fails the run with — and the
|
||||
/// buffer keeps being linted with the entry dropped (§42.2).
|
||||
#[test]
|
||||
fn a_rejected_project_option_is_logged_once_and_the_buffer_is_still_linted() {
|
||||
let dir = temp_dir("lint_contract_option");
|
||||
let config = dir.join("lucisv.toml");
|
||||
std::fs::write(&config, "[lint.line-length]\nlength = \"wide\"\n").expect("write config");
|
||||
let file = dir.join("lint_contract.sv");
|
||||
std::fs::write(&file, TWO_FINDINGS).expect("write");
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
// Three settings pushes, each of which republishes every open buffer, so
|
||||
// the lint pass runs at least four times over the same bad config.
|
||||
let session = [
|
||||
lint_session_start(&dir, &uri, TWO_FINDINGS),
|
||||
select_push("\"no-tabs\""),
|
||||
select_push("\"no-trailing-whitespace\""),
|
||||
select_push(""),
|
||||
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 complaints: Vec<&str> = messages
|
||||
.iter()
|
||||
.filter(|m| m["method"] == "window/logMessage")
|
||||
.filter_map(|m| m["params"]["message"].as_str())
|
||||
.filter(|line| line.contains("line-length"))
|
||||
.collect();
|
||||
assert_eq!(complaints.len(), 1, "said once, not once per pass: {complaints:#?}");
|
||||
assert!(
|
||||
complaints[0].starts_with(&format!("lucisv: {}:2: rule `line-length` ", config.display())),
|
||||
"the file and line `lucisv check` would name: {}",
|
||||
complaints[0]
|
||||
);
|
||||
assert!(
|
||||
!messages.iter().any(|m| m["method"] == "window/showMessage"),
|
||||
"logged, not shown: {messages:#?}"
|
||||
);
|
||||
|
||||
// And the lint kept running with the entry dropped.
|
||||
let steps = published_codes(&messages, &uri);
|
||||
assert!(
|
||||
steps.iter().any(|codes| codes.contains(&"no-tabs".to_string())),
|
||||
"the buffer is still linted: {steps:#?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The rules `lucisv check` runs over a file and the rules the server runs
|
||||
/// over the same buffer, for three `lucisv.toml`s. Equal, or the two halves
|
||||
/// of lucisv disagree about what a violation is — which is the whole reason
|
||||
/// §42 exists.
|
||||
#[test]
|
||||
fn the_cli_and_the_server_run_the_same_rules_for_the_same_buffer() {
|
||||
let Some(lucisv) = lucisv_binary() else {
|
||||
eprintln!("skipped: the `lucisv` binary is not built next to `lucisv-server`");
|
||||
return;
|
||||
};
|
||||
let configs = [
|
||||
// No `[lint]` table at all: both front ends fall back to the base set.
|
||||
("none", "line-length = 80\n"),
|
||||
// A selection of one rule.
|
||||
("one", "[lint]\nselect = [\"no-tabs\"]\n"),
|
||||
// A severity word, and an `ignore` that takes one back out of it.
|
||||
("class", "[lint]\nselect = [\"style\"]\nignore = [\"no-trailing-whitespace\"]\n"),
|
||||
];
|
||||
for (tag, config) in configs {
|
||||
let dir = temp_dir(&format!("lint_contract_agree_{tag}"));
|
||||
std::fs::write(dir.join("lucisv.toml"), config).expect("write config");
|
||||
let file = dir.join("lint_contract.sv");
|
||||
std::fs::write(&file, TWO_FINDINGS).expect("write");
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
let output = Command::new(&lucisv)
|
||||
.args(["check", "--output-format", "json"])
|
||||
.arg(&file)
|
||||
.output()
|
||||
.expect("the lucisv binary runs");
|
||||
let json: serde_json::Value =
|
||||
serde_json::from_slice(&output.stdout).expect("the CLI prints one JSON array");
|
||||
let mut from_cli: Vec<String> = json
|
||||
.as_array()
|
||||
.expect("an array")
|
||||
.iter()
|
||||
.filter_map(|item| item["rule"].as_str().map(str::to_string))
|
||||
.collect();
|
||||
from_cli.sort();
|
||||
from_cli.dedup();
|
||||
|
||||
let session = [
|
||||
lint_session_start(&dir, &uri, TWO_FINDINGS),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
let from_server =
|
||||
published_codes(&talk(&session), &uri).pop().expect("the server published something");
|
||||
|
||||
assert_eq!(from_server, from_cli, "the two front ends disagree under {config:?}");
|
||||
assert!(!from_cli.is_empty(), "a config that reports nothing proves nothing: {config:?}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TODO.md §46 — what a `didOpen` costs the request behind it
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// `talk` writes a whole session before reading a byte, which is what every
|
||||
// test above wants and what a *timing* test cannot use: the number this round
|
||||
// is about is the gap between the `didOpen` frame going out and the next
|
||||
// response coming back. `Live` — the held-open session two hundred lines up —
|
||||
// is the one that can measure it. The three tests below are §46's contract:
|
||||
// the open returns to the loop fast, the first request after it is answered
|
||||
// from the **buffer**, and the diagnostics still arrive with no edit and no
|
||||
// further request behind them.
|
||||
|
||||
/// A started session over `root`, indexed at the whole-workspace scope with
|
||||
/// the scan already run — the barrier request at the end is what makes that
|
||||
/// true, since the loop answers nothing until a rescan a message asked for has
|
||||
/// finished.
|
||||
fn live_at(root: &Path) -> Live {
|
||||
let mut live = Live::start();
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"file://{}","capabilities":{{}}}}}}"#,
|
||||
root.display()
|
||||
));
|
||||
live.wait_for(|m| m["id"] == 1);
|
||||
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
|
||||
live.send(WIDE_SCOPE);
|
||||
live.send(r#"{"jsonrpc":"2.0","id":2,"method":"workspace/symbol","params":{"query":"zzz"}}"#);
|
||||
live.wait_for(|m| m["id"] == 2);
|
||||
live
|
||||
}
|
||||
|
||||
/// The `didOpen` frame for a buffer.
|
||||
fn open_frame(uri: &str, text: &str) -> String {
|
||||
format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(text).expect("json")
|
||||
)
|
||||
}
|
||||
|
||||
/// Open `uri` and ask for a `hover` in the same write, and report how long the
|
||||
/// hover took to come back.
|
||||
///
|
||||
/// That wait *is* the open: the loop is synchronous, so whatever the open does
|
||||
/// before returning to it is what the hover queues behind.
|
||||
fn open_then_hover(live: &mut Live, id: u32, uri: &str, text: &str) -> std::time::Duration {
|
||||
let hover = format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":0,"character":8}}}}}}"#
|
||||
);
|
||||
let started = std::time::Instant::now();
|
||||
live.send(&open_frame(uri, text));
|
||||
live.send(&hover);
|
||||
live.wait_for(|m| m["id"] == id);
|
||||
started.elapsed()
|
||||
}
|
||||
|
||||
/// A workspace of `files` small packages, so the index holds a *project*
|
||||
/// rather than one buffer — which is what switches the cross-file lint rules
|
||||
/// on at all (`LintRun::for_document`).
|
||||
fn indexed_neighbours(dir: &Path, files: usize) {
|
||||
for k in 0..files {
|
||||
std::fs::write(
|
||||
dir.join(format!("pkg{k}.sv")),
|
||||
format!("package pkg{k};\n localparam int K{k} = {k};\nendpackage\n"),
|
||||
)
|
||||
.expect("write neighbour");
|
||||
}
|
||||
}
|
||||
|
||||
/// §46's contract, on the wire: a `didOpen` of a 2 000-line buffer must not
|
||||
/// leave the request behind it waiting.
|
||||
///
|
||||
/// **An upper bound, not a benchmark, and a debug-build one.** `cargo test`
|
||||
/// builds unoptimized, where one tolerant parse of 2 000 lines is ~53 ms all
|
||||
/// by itself — measured on this machine, and stable to a millisecond across
|
||||
/// runs. So the 200 ms here is that floor with room for a loaded CI box, not
|
||||
/// the ≤ 25 ms §46 asked for: **that figure is a release number**, and the
|
||||
/// release binary opens the same buffer in 2–4 ms.
|
||||
///
|
||||
/// **What this test does and does not catch.** It catches an open that starts
|
||||
/// doing something *unbounded* — the shape §46 fixed. It cannot catch the
|
||||
/// §46 defect itself at this size: the census walk that cost 1.6 s on
|
||||
/// opentitan's 42 000-line `pinmux_reg_top.sv` costs milliseconds over a
|
||||
/// forty-file fixture, and a fixture of opentitan's four thousand files has
|
||||
/// no business in a unit-test suite. The exact pin for that is
|
||||
/// `undriven_net`'s `the_project_is_asked_only_about_the_signals_that_would_be_reported`,
|
||||
/// which counts the questions instead of timing them
|
||||
/// (`docs/features/didopen-cost/README.md`).
|
||||
///
|
||||
/// Best of three distinct buffers: the first open of a process pays cold code
|
||||
/// paths that have nothing to do with the buffer, and a wall-clock assertion
|
||||
/// that cannot tolerate one scheduling hiccup is a flake, not a pin.
|
||||
#[test]
|
||||
fn opening_a_two_thousand_line_buffer_does_not_delay_the_request_behind_it() {
|
||||
let dir = temp_dir("didopen_cost");
|
||||
indexed_neighbours(&dir, 40);
|
||||
let mut generated = Vec::new();
|
||||
for n in 0..3 {
|
||||
let name = format!("gen{n}");
|
||||
// The generator the perf tables use: a thousand declarations, every
|
||||
// one declared, driven and read — the cheap case for the *findings*
|
||||
// and the expensive one for the walk that decides there are none.
|
||||
let text = generated_module(&name, 2_000);
|
||||
assert!(text.lines().count() >= 2_000, "the premise: a 2 000-line buffer");
|
||||
let path = dir.join(format!("{name}.sv"));
|
||||
std::fs::write(&path, &text).expect("write");
|
||||
generated.push((path, text));
|
||||
}
|
||||
let mut live = live_at(&dir);
|
||||
// A warm-up open of a small buffer, for the cold code paths.
|
||||
let warm = format!("file://{}", dir.join("pkg0.sv").display());
|
||||
open_then_hover(&mut live, 10, &warm, "package pkg0;\n localparam int K0 = 0;\nendpackage\n");
|
||||
|
||||
let mut best = std::time::Duration::MAX;
|
||||
for (n, (path, text)) in generated.iter().enumerate() {
|
||||
let uri = format!("file://{}", path.display());
|
||||
best = best.min(open_then_hover(&mut live, 20 + n as u32, &uri, text));
|
||||
}
|
||||
live.finish();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
assert!(
|
||||
best <= std::time::Duration::from_millis(200),
|
||||
"a didOpen of a 2 000-line buffer delayed the next request by {best:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The other half of §46's contract: the request after an open is answered
|
||||
/// from the **buffer**, not from what is on disk.
|
||||
///
|
||||
/// Nothing about the open was deferred — it still analyzes the buffer before
|
||||
/// it returns to the loop — and this is what says so out loud. The buffer
|
||||
/// names something the file on disk does not, and declares it on a line the
|
||||
/// disk file does not, and the very first hover and the very first definition
|
||||
/// after the open both find the buffer's.
|
||||
#[test]
|
||||
fn the_first_hover_after_an_open_sees_the_buffer_and_not_the_disk() {
|
||||
let dir = temp_dir("didopen_buffer_wins");
|
||||
indexed_neighbours(&dir, 4);
|
||||
let file = dir.join("m.sv");
|
||||
std::fs::write(
|
||||
&file,
|
||||
"module m;\n localparam int ON_DISK = 1;\n logic a;\n assign a = ON_DISK;\nendmodule\n",
|
||||
)
|
||||
.expect("write");
|
||||
let uri = format!("file://{}", file.display());
|
||||
// What the editor holds: a different name, declared on a different line.
|
||||
let buffer = "module m;\n\n localparam int IN_BUFFER = 2;\n logic a;\n \
|
||||
assign a = IN_BUFFER;\nendmodule\n";
|
||||
|
||||
let mut live = live_at(&dir);
|
||||
live.send(&open_frame(&uri, buffer));
|
||||
// The cursor on `IN_BUFFER` where line 4 reads it.
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":30,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":4,"character":16}}}}}}"#
|
||||
));
|
||||
let card = live.wait_for(|m| m["id"] == 30)["result"]["contents"]["value"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":31,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":4,"character":16}}}}}}"#
|
||||
));
|
||||
let definition = live.wait_for(|m| m["id"] == 31);
|
||||
live.finish();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
assert!(card.contains("IN_BUFFER"), "the first hover did not read the buffer: {card:?}");
|
||||
assert!(!card.contains("ON_DISK"), "the first hover read the disk file: {card:?}");
|
||||
let locations = definition["result"].as_array().expect("an array of locations");
|
||||
assert_eq!(locations.len(), 1, "one declaration, got {locations:#?}");
|
||||
assert_eq!(locations[0]["range"]["start"]["line"], 2, "the buffer's line, not the disk's");
|
||||
}
|
||||
|
||||
/// And the third: the open still publishes, with no edit and no further
|
||||
/// request to trigger it.
|
||||
///
|
||||
/// **There is no debounce on the open.** §46 allowed the diagnostics to be
|
||||
/// moved onto the change debounce and to arrive one quiet period later; they
|
||||
/// were not, because the cost was never the publish — it was one rule inside
|
||||
/// it. So the guarantee is the one this server has always had: the diagnostics
|
||||
/// for an opened buffer go out inside the `didOpen`, ahead of anything queued
|
||||
/// behind it.
|
||||
#[test]
|
||||
fn an_open_still_publishes_its_diagnostics_with_no_edit_behind_it() {
|
||||
let dir = temp_dir("didopen_publishes");
|
||||
indexed_neighbours(&dir, 4);
|
||||
let file = dir.join("tabbed.sv");
|
||||
let text = "module tabbed;\n\twire a;\nendmodule\n";
|
||||
std::fs::write(&file, text).expect("write");
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
let mut live = live_at(&dir);
|
||||
live.send(&open_frame(&uri, text));
|
||||
let published = live.wait_for(|m| {
|
||||
m["method"] == "textDocument/publishDiagnostics" && m["params"]["uri"] == uri
|
||||
});
|
||||
live.finish();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
let items = published["params"]["diagnostics"].as_array().expect("a diagnostics array");
|
||||
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);
|
||||
}
|
||||
@@ -296,22 +296,44 @@ impl<'a> Fmt<'a> {
|
||||
pub(super) fn data_decl(&self, d: &DataDecl) -> Doc {
|
||||
let mut docs = Vec::new();
|
||||
if let Some(net) = &d.net {
|
||||
docs.push(text(format!("{net} ")));
|
||||
}
|
||||
if let Some(delay) = &d.delay {
|
||||
docs.push(text("#"));
|
||||
docs.push(self.expr(delay));
|
||||
docs.push(text(" "));
|
||||
docs.push(text(net.clone()));
|
||||
self.net_delay(d, false, &mut docs);
|
||||
}
|
||||
self.qualifier_run(&d.qualifiers, &mut docs);
|
||||
if let Some(t) = self.data_type(&d.ty) {
|
||||
docs.push(t);
|
||||
docs.push(text(" "));
|
||||
self.net_delay(d, true, &mut docs);
|
||||
}
|
||||
// Neither arm needs an `else`: a delay before the type is only read
|
||||
// after a net keyword, and one after the type only when a type was
|
||||
// actually written, so an implicit type has none to print.
|
||||
docs.push(self.declarators(&d.declarators));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// The separator that follows the word just emitted, and then `#5` when
|
||||
/// the declaration's net delay was written on the side of the data type
|
||||
/// `after_type` names. IEEE 1800 §6.7 allows either side and lucisv
|
||||
/// prints it where the source put it; moving it across the type would
|
||||
/// reorder tokens, which `verify.rs` refuses.
|
||||
///
|
||||
/// The separator is the delay's `before_hash` comments when it has any
|
||||
/// (`wire /* c */ #5 w;`) and a plain space otherwise — so a declaration
|
||||
/// with no comment there is laid out exactly as it was before the slot
|
||||
/// existed, delay or no delay.
|
||||
fn net_delay(&self, d: &DataDecl, after_type: bool, docs: &mut Vec<Doc>) {
|
||||
let delay = d.delay.as_ref().filter(|n| n.after_type == after_type);
|
||||
match delay.map(|n| &n.before_hash).filter(|c| !c.is_empty()) {
|
||||
Some(comments) => self.inline_comments_spaced(comments, docs),
|
||||
None => docs.push(text(" ")),
|
||||
}
|
||||
let Some(delay) = delay else { return };
|
||||
docs.push(text("#"));
|
||||
self.slot_comments(&delay.after_hash, docs);
|
||||
docs.push(self.expr(&delay.expr));
|
||||
docs.push(text(" "));
|
||||
}
|
||||
|
||||
pub(super) fn port_decl(&self, d: &PortDecl) -> Doc {
|
||||
let mut docs = vec![text(format!("{} ", d.dir))];
|
||||
if let Some(net) = &d.net {
|
||||
|
||||
@@ -310,8 +310,17 @@ impl<'a> Fmt<'a> {
|
||||
// strictly. Printed verbatim so nothing is lost if that ever
|
||||
// changes — see `ListItem::from_raw`.
|
||||
ExprKind::Error(raw) => self.raw_inline(raw),
|
||||
ExprKind::MinTypMax { min, typ, max } => {
|
||||
concat(vec![self.expr(min), text(":"), self.expr(typ), text(":"), self.expr(max)])
|
||||
ExprKind::MinTypMax { min, typ, max, comments } => {
|
||||
let mut docs = vec![self.expr(min)];
|
||||
self.slot_comments(&comments.before_typ, &mut docs);
|
||||
docs.push(text(":"));
|
||||
self.slot_comments(&comments.after_typ, &mut docs);
|
||||
docs.push(self.expr(typ));
|
||||
self.slot_comments(&comments.before_max, &mut docs);
|
||||
docs.push(text(":"));
|
||||
self.slot_comments(&comments.after_max, &mut docs);
|
||||
docs.push(self.expr(max));
|
||||
concat(docs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -342,30 +342,83 @@ impl<'a> Fmt<'a> {
|
||||
if let Some(s) = &g.strength {
|
||||
docs.push(text(format!(" {}", drive_strength(s))));
|
||||
}
|
||||
if !g.delay.is_empty() {
|
||||
// The gap in front of the `#` is a space unless the source wrote
|
||||
// a comment in it, exactly as a net delay's `before_hash` is.
|
||||
match g.before_hash.is_empty() {
|
||||
true => docs.push(text(" ")),
|
||||
false => self.inline_comments_spaced(&g.before_hash, &mut docs),
|
||||
}
|
||||
docs.push(text("#"));
|
||||
self.slot_comments(&g.after_hash, &mut docs);
|
||||
}
|
||||
if let [delay] = g.delay.as_slice() {
|
||||
// One value prints itself, brackets and all (`#5`, `#(5)`).
|
||||
docs.push(text(" #"));
|
||||
docs.push(self.expr(delay));
|
||||
docs.push(self.expr(&delay.expr));
|
||||
} else if !g.delay.is_empty() {
|
||||
// `#(rise, fall[, turn-off])` — the parens are the list's own.
|
||||
docs.push(text(" #("));
|
||||
// `#(rise, fall[, turn-off])` — the parens and the commas are the
|
||||
// list's own, so the comments written around them are too.
|
||||
docs.push(text("("));
|
||||
for (i, d) in g.delay.iter().enumerate() {
|
||||
if i > 0 {
|
||||
docs.push(text(", "));
|
||||
docs.push(text(","));
|
||||
match d.leading.is_empty() {
|
||||
true => docs.push(text(" ")),
|
||||
false => self.inline_comments_spaced(&d.leading, &mut docs),
|
||||
}
|
||||
} else {
|
||||
self.slot_comments(&d.leading, &mut docs);
|
||||
}
|
||||
docs.push(self.expr(d));
|
||||
docs.push(self.expr(&d.expr));
|
||||
self.slot_comments(&d.trailing, &mut docs);
|
||||
}
|
||||
docs.push(text(")"));
|
||||
}
|
||||
let last = g.instances.len().saturating_sub(1);
|
||||
// True once a trailing comment has ended the previous instance's line:
|
||||
// the next instance then starts on a fresh, indented line, and the
|
||||
// space that normally separates it from the `,` is not written.
|
||||
let mut broke = false;
|
||||
for (i, inst) in g.instances.iter().enumerate() {
|
||||
docs.push(if i > 0 { text(", ") } else { text(" ") });
|
||||
// What stands between the delay (or the previous instance's `,`)
|
||||
// and this instance's name — a space when nothing does.
|
||||
match (broke, inst.meta.leading.is_empty()) {
|
||||
(true, true) => {}
|
||||
(false, true) => docs.push(text(" ")),
|
||||
(_, false) => self.inline_comments_spaced(&inst.meta.leading, &mut docs),
|
||||
}
|
||||
broke = false;
|
||||
if let Some(name) = &inst.name {
|
||||
docs.push(name_doc(name));
|
||||
docs.push(text(" "));
|
||||
match inst.before_args.is_empty() {
|
||||
true => docs.push(text(" ")),
|
||||
false => self.inline_comments_spaced(&inst.before_args, &mut docs),
|
||||
}
|
||||
}
|
||||
docs.push(self.expr_list("(", &inst.args, ")"));
|
||||
if i == last {
|
||||
continue;
|
||||
}
|
||||
// Comments written between the instance and its `,` print on the
|
||||
// instance's side of it, as every list element's do.
|
||||
if self.inline_comments(&inst.meta.before_sep, &mut docs) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(","));
|
||||
if let Some(tr) = &inst.meta.trailing {
|
||||
docs.push(text(" "));
|
||||
docs.push(self.comment(tr));
|
||||
// A line comment ends the line (a `// p` would otherwise
|
||||
// swallow the next instance on re-lex — §45's QA); the next
|
||||
// instance continues one level in. A block comment stays
|
||||
// inline, as the case table for this slot expects.
|
||||
if is_line_comment(&tr.text) {
|
||||
docs.push(indent(vec![Doc::HardLine]));
|
||||
broke = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
docs.push(text(";"));
|
||||
docs.push(self.semi(&g.before_semi));
|
||||
concat(docs)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -362,8 +362,12 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
if let Some(delay) = &a.delay {
|
||||
docs.push(text("#"));
|
||||
self.slot_comments(&a.after_hash, &mut docs);
|
||||
docs.push(self.expr(delay));
|
||||
docs.push(text(" "));
|
||||
match a.after_delay.is_empty() {
|
||||
true => docs.push(text(" ")),
|
||||
false => self.inline_comments_spaced(&a.after_delay, &mut docs),
|
||||
}
|
||||
}
|
||||
let items: Vec<ListItem> = a
|
||||
.assigns
|
||||
|
||||
@@ -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)]),
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
# TODO §45.4 — the comment slots inside a delay list. `parse_delay_values`
|
||||
# serves `#(1:2:3)` on nets and continuous assignments and `#(rise, fall)` on
|
||||
# gates; the gaps around the `(`, the two `:` and the `,` had no owner, so a
|
||||
# comment written in one moved and `verify.rs` refused the file.
|
||||
#
|
||||
# The `min:typ:max` colons: `MinTypMaxComments`, four slots, one grammar
|
||||
# shared with the parenthesized `(a:b:c)` expression.
|
||||
module m;
|
||||
wire #(1 /* b */ : /* c */ 2 /* d */ : /* e */ 3) w;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire #(1 /* b */ : /* c */ 2 /* d */ : /* e */ 3) w;
|
||||
endmodule
|
||||
====
|
||||
# The parentheses of a one-value delay are its own `ExprKind::Paren`, which
|
||||
# has had the two slots all along — and a comment inside a bracket pair forces
|
||||
# that pair open, as it does everywhere else in the formatter.
|
||||
module m;
|
||||
wire #( /* a */ 1:2:3 /* f */ ) w;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire #(
|
||||
/* a */
|
||||
1:2:3 /* f */
|
||||
) w;
|
||||
endmodule
|
||||
====
|
||||
# A continuous assignment's delay: the gap after its `#` and the gap between
|
||||
# the delay and the first left-hand side. Without the second slot the comment
|
||||
# joins the first pair's leading comments, which print in front of the delay.
|
||||
module m;
|
||||
assign # /* g */ (1:2:3) /* h */ z = a;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign # /* g */ (1:2:3) /* h */ z = a;
|
||||
endmodule
|
||||
====
|
||||
# A gate's multi-value list writes its own parentheses and commas, so it owns
|
||||
# the comments around them: `DelayValue::{leading, trailing}`. With them the
|
||||
# gate's `before_hash`, `after_hash`, the instance's `before_args` and the
|
||||
# item's `before_semi`.
|
||||
module m;
|
||||
and /* i */ # /* j */ ( /* k */ 2 /* l */ , /* m */ 3 /* n */ ) g1 /* o */ (y, a, b) /* p */ ;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
and /* i */ # /* j */ ( /* k */ 2 /* l */ , /* m */ 3 /* n */ ) g1 /* o */ (y, a, b) /* p */ ;
|
||||
endmodule
|
||||
====
|
||||
# A line comment runs to end of line, so what follows it starts a new one —
|
||||
# the same rule every other slot in the formatter obeys.
|
||||
module m;
|
||||
wire #(1 // why
|
||||
:2:3) w;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire #(
|
||||
1 // why
|
||||
:2:3
|
||||
) w;
|
||||
endmodule
|
||||
====
|
||||
# Nothing written in any of the slots costs a byte: the comment-free spellings
|
||||
# are laid out exactly as they were before the slots existed.
|
||||
module m;
|
||||
wire #(1:2:3) a;
|
||||
assign #(1:2:3) z = a;
|
||||
and #(1, 2, 3) g1 (o, a, b);
|
||||
not #(1:2:3, 4:5:6) n0 (o, a);
|
||||
buf #(5) b1 (o, a);
|
||||
buf #5 b2 (o, a);
|
||||
buf b3 (o, a);
|
||||
nand (weak0, weak1) #2 n1 (o, a, b);
|
||||
and #(2, 3) g0 (y, a), g2 (z, b);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire #(1:2:3) a;
|
||||
assign #(1:2:3) z = a;
|
||||
and #(1, 2, 3) g1 (o, a, b);
|
||||
not #(1:2:3, 4:5:6) n0 (o, a);
|
||||
buf #(5) b1 (o, a);
|
||||
buf #5 b2 (o, a);
|
||||
buf b3 (o, a);
|
||||
nand (weak0, weak1) #2 n1 (o, a, b);
|
||||
and #(2, 3) g0 (y, a), g2 (z, b);
|
||||
endmodule
|
||||
====
|
||||
# A comment between two gate instances, and one written before the `,` that
|
||||
# separates them: the element's own `leading` and `before_sep`.
|
||||
module m;
|
||||
and #(2, 3) g0 (y, a) /* before */ , /* after */ g1 (z, b);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
and #(2, 3) g0 (y, a) /* before */, /* after */ g1 (z, b);
|
||||
endmodule
|
||||
@@ -224,3 +224,42 @@ module tb;
|
||||
sub #() u1 (.a(x));
|
||||
sub #(.W(8)) u2 (.a(x));
|
||||
endmodule
|
||||
====
|
||||
# TODO §45.3 — an inline aggregate as a parameter-override argument. It is a
|
||||
# type where a type is legal (IEEE 1800 §6.19, §7.2), the override a
|
||||
# `parameter type` defaulting to one takes, and it prints through the existing
|
||||
# type printer: a struct or union body opens, an enum body stays inline.
|
||||
module m;
|
||||
sub #(.T(struct packed { logic a; })) u0 ();
|
||||
sub #(.T(union packed { logic [7:0] a; })) u1 ();
|
||||
sub #(.T(enum logic [1:0] {A, B})) u2 ();
|
||||
sub #(.T(struct packed { /* why */ logic a; })) u3 ();
|
||||
sub #(.T(logic [7:0])) u4 ();
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub #(
|
||||
.T(
|
||||
struct packed {
|
||||
logic a;
|
||||
}
|
||||
)
|
||||
) u0 ();
|
||||
sub #(
|
||||
.T(
|
||||
union packed {
|
||||
logic [7:0] a;
|
||||
}
|
||||
)
|
||||
) u1 ();
|
||||
sub #(.T(enum logic [1:0] {A, B})) u2 ();
|
||||
sub #(
|
||||
.T(
|
||||
struct packed {
|
||||
/* why */
|
||||
logic a;
|
||||
}
|
||||
)
|
||||
) u3 ();
|
||||
sub #(.T(logic [7:0])) u4 ();
|
||||
endmodule
|
||||
@@ -0,0 +1,121 @@
|
||||
# TODO §38.2 — a net delay is printed on the side of the data type it was
|
||||
# written on. IEEE 1800 §6.7 puts `delay3` after the type; the rest of the
|
||||
# corpus puts it before. Neither spelling is normalised into the other.
|
||||
# docs/features/parser-skips/README.md
|
||||
module m;
|
||||
wire #5 before_the_type;
|
||||
wire [31:0] #0.1 after_the_type = y;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire #5 before_the_type;
|
||||
wire [31:0] #0.1 after_the_type = y;
|
||||
endmodule
|
||||
====
|
||||
# after a packed dimension, after a plain `logic`-typed net, and after a
|
||||
# signing keyword — with the min:typ:max spelling of the delay itself
|
||||
module m;
|
||||
wire [7:0] #1 a;
|
||||
wire logic #2 b;
|
||||
wire signed [7:0] #(1:2:3) c;
|
||||
wire #(1:2:3) signed [7:0] d;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire [7:0] #1 a;
|
||||
wire logic #2 b;
|
||||
wire signed [7:0] #(1:2:3) c;
|
||||
wire #(1:2:3) signed [7:0] d;
|
||||
endmodule
|
||||
====
|
||||
# the real lines: hw/vendor/pulp_riscv_dbg/tb/unused/SimDTM.sv:38-41
|
||||
# (opentitan, read-only there), the §11 skip this item closes
|
||||
module SimDTM (
|
||||
input clk,
|
||||
output [31:0] exit
|
||||
);
|
||||
|
||||
bit r_reset;
|
||||
|
||||
wire #0.1 __debug_req_ready = debug_req_ready;
|
||||
wire #0.1 __debug_resp_valid = debug_resp_valid;
|
||||
wire [31:0] #0.1 __debug_resp_bits_resp = {30'b0, debug_resp_bits_resp};
|
||||
wire [31:0] #0.1 __debug_resp_bits_data = debug_resp_bits_data;
|
||||
|
||||
endmodule
|
||||
----
|
||||
module SimDTM (input clk, output [31:0] exit);
|
||||
bit r_reset;
|
||||
|
||||
wire #0.1 __debug_req_ready = debug_req_ready;
|
||||
wire #0.1 __debug_resp_valid = debug_resp_valid;
|
||||
wire [31:0] #0.1 __debug_resp_bits_resp = {30'b0, debug_resp_bits_resp};
|
||||
wire [31:0] #0.1 __debug_resp_bits_data = debug_resp_bits_data;
|
||||
endmodule
|
||||
====
|
||||
# a comment written directly in front of the `#` is the delay's own —
|
||||
# `NetDelay::before_hash`, TODO §43.2. It was the `#SKIP` §38 recorded and
|
||||
# `verify.rs` refused the file for; the slot prints it back where it was
|
||||
# written, on either side of the data type.
|
||||
module m;
|
||||
wire /* c */ #5 x;
|
||||
wire [7:0] /* d */ #1 z;
|
||||
wire [3:0] /* one */ /* two */ #3 w;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire /* c */ #5 x;
|
||||
wire [7:0] /* d */ #1 z;
|
||||
wire [3:0] /* one */ /* two */ #3 w;
|
||||
endmodule
|
||||
====
|
||||
# the delay's other gap, between the `#` and the value: `after_hash`. Both
|
||||
# slots at once on one declaration, since the fuzzer asks for both
|
||||
module m;
|
||||
wire # /* why */ 5 x;
|
||||
wire [7:0] /* a */ # /* b */ 1 z = q;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire # /* why */ 5 x;
|
||||
wire [7:0] /* a */ # /* b */ 1 z = q;
|
||||
endmodule
|
||||
====
|
||||
# a line comment in the same slot runs to end of line, so the `#` cannot
|
||||
# follow it: it starts the next one, the way the `wire #5 /* after */` case
|
||||
# below breaks before its declarator
|
||||
module m;
|
||||
wire // why the delay
|
||||
#2 y;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
wire // why the delay
|
||||
#2 y;
|
||||
endmodule
|
||||
====
|
||||
# the other three gaps around a delay do have slots and round-trip
|
||||
module m;
|
||||
(* keep *) wire [3:0] #2 k = j;
|
||||
wire #5 /* after */ x;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
(* keep *)
|
||||
wire [3:0] #2 k = j;
|
||||
wire #5 /* after */
|
||||
x;
|
||||
endmodule
|
||||
====
|
||||
# a line comment after a gate instance's comma ends the line: the next
|
||||
# instance continues one level in (§45's QA; the module-instantiation
|
||||
# printer already did this)
|
||||
module m;
|
||||
and #(2, 3) g0 (y, a), // p
|
||||
g1 (z, b);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
and #(2, 3) g0 (y, a), // p
|
||||
g1 (z, b);
|
||||
endmodule
|
||||
@@ -0,0 +1,386 @@
|
||||
# TODO §38.1 — two rival, bracket-balanced unit headers written across the
|
||||
# arms of one `ifdef region. The whole unit is one verbatim item, so it comes
|
||||
# back byte for byte apart from the block's own re-indent.
|
||||
# docs/features/parser-skips/README.md
|
||||
`ifdef A
|
||||
interface i ();
|
||||
`else
|
||||
interface i ();
|
||||
`endif
|
||||
wire tck;
|
||||
endinterface
|
||||
|
||||
parameter int AFTER = 1;
|
||||
----
|
||||
`ifdef A
|
||||
interface i ();
|
||||
`else
|
||||
interface i ();
|
||||
`endif
|
||||
wire tck;
|
||||
endinterface
|
||||
|
||||
parameter int AFTER = 1;
|
||||
====
|
||||
# a module spelling with a real port list and a closing label
|
||||
`ifdef SYNTHESIS
|
||||
module m (input a, output b);
|
||||
`else
|
||||
module m (input a, output b);
|
||||
`endif
|
||||
wire x;
|
||||
endmodule : m
|
||||
----
|
||||
`ifdef SYNTHESIS
|
||||
module m (input a, output b);
|
||||
`else
|
||||
module m (input a, output b);
|
||||
`endif
|
||||
wire x;
|
||||
endmodule : m
|
||||
====
|
||||
# the block's *relative* layout is what survives: the whole unit is dedented
|
||||
# to the item's own indent, exactly as every other verbatim block is
|
||||
`ifdef A
|
||||
interface i #(parameter int P = 1) ();
|
||||
`else
|
||||
interface i #(parameter int P = 2) ();
|
||||
`endif
|
||||
wire tck;
|
||||
endinterface
|
||||
----
|
||||
`ifdef A
|
||||
interface i #(parameter int P = 1) ();
|
||||
`else
|
||||
interface i #(parameter int P = 2) ();
|
||||
`endif
|
||||
wire tck;
|
||||
endinterface
|
||||
====
|
||||
# the real file: hw/dv/sv/jtag_agent/jtag_if.sv (opentitan), the §11
|
||||
# skip this item closes. Read-only there; copied here verbatim.
|
||||
// Copyright lowRISC contributors (OpenTitan project).
|
||||
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// TODO(#24580): A JTAG UVM agent should configure the JTAG frequency (and not this interface)
|
||||
`ifdef GATE_LEVEL
|
||||
// jtag interface with default 24MHz tck for GLS
|
||||
interface jtag_if #(parameter int unsigned JtagDefaultTckPeriodPs = 41_664) ();
|
||||
`else
|
||||
// jtag interface with default 50MHz tck for faster DV simulations
|
||||
interface jtag_if #(parameter int unsigned JtagDefaultTckPeriodPs = 20_000) ();
|
||||
`endif
|
||||
|
||||
// interface pins
|
||||
wire tck;
|
||||
wire trst_n;
|
||||
wire tms;
|
||||
wire tdi;
|
||||
wire tdo;
|
||||
|
||||
// Is this interface being driven (through _drive_active and the clocking blocks), or is it just
|
||||
// observing some signals from the wider simulation?
|
||||
//
|
||||
// The flag is defined as a wire with a weak pull-up. This ensures that a testbench that doesn't
|
||||
// customise is_active will see the interface be driven actively, but allows a testbench that
|
||||
// *does* want to customise the signal to pull it low.
|
||||
wire is_active;
|
||||
assign (weak0, weak1) is_active = 1'b1;
|
||||
|
||||
// Should this interface generate a local tck signal? To enable that, set tck_en as well as
|
||||
// is_active.
|
||||
bit tck_en;
|
||||
|
||||
// Output-enable flags for tms, tdi, tdo (which only have an effect if is_active is true). The
|
||||
// default configuration enables tms and tdi, so acts as the root of the JTAG tree plus the
|
||||
// "previous device in the scan chain".
|
||||
bit tms_oe = 1'b1;
|
||||
bit tdi_oe = 1'b1;
|
||||
bit tdo_oe = 1'b0;
|
||||
|
||||
logic _tck_internal, _trst_n_internal, _tms_internal, _tdi_internal, _tdo_internal;
|
||||
assign tck = (is_active === 1'b1) ? _tck_internal : 'z;
|
||||
assign trst_n = (is_active === 1'b1) ? _trst_n_internal : 'z;
|
||||
assign tms = ((is_active === 1'b1) && tms_oe) ? _tms_internal : 'z;
|
||||
assign tdi = ((is_active === 1'b1) && tdi_oe) ? _tdi_internal : 'z;
|
||||
assign tdo = ((is_active === 1'b1) && tdo_oe) ? _tdo_internal : 'z;
|
||||
|
||||
// Use negedge to drive jtag inputs because design also use posedge clock edge to sample.
|
||||
clocking host_cb @(negedge tck);
|
||||
default output #1ns;
|
||||
output tms = _tms_internal;
|
||||
output tdi = _tdi_internal;
|
||||
input tdo;
|
||||
endclocking
|
||||
modport host_mp(clocking host_cb, output trst_n);
|
||||
|
||||
clocking device_cb @(posedge tck);
|
||||
input tms;
|
||||
input tdi;
|
||||
output tdo = _tdo_internal;
|
||||
endclocking
|
||||
modport device_mp(clocking device_cb, input trst_n);
|
||||
|
||||
clocking mon_cb @(posedge tck);
|
||||
input tms;
|
||||
input tdi;
|
||||
input tdo;
|
||||
endclocking
|
||||
modport mon_mp (clocking mon_cb, input trst_n);
|
||||
|
||||
// Signals for local tck
|
||||
int unsigned _tck_period_ps = JtagDefaultTckPeriodPs;
|
||||
int unsigned _clk_hi_ps, _clk_lo_ps;
|
||||
assign _clk_hi_ps = _tck_period_ps / 2;
|
||||
assign _clk_lo_ps = _tck_period_ps - _clk_hi_ps;
|
||||
|
||||
// Sets the TCK frequency.
|
||||
function automatic void set_tck_period_ps(int unsigned value);
|
||||
_tck_period_ps = value;
|
||||
endfunction
|
||||
|
||||
function automatic int unsigned get_tck_period_ps();
|
||||
return _tck_period_ps;
|
||||
endfunction
|
||||
|
||||
// Wait for one TCK cycle
|
||||
//
|
||||
// This waits for TCK to clear and then be asserted (so is waiting for the next posedge), but
|
||||
// bounds the wait by _tck_period_ps (in case the clock has stopped).
|
||||
//
|
||||
// Waiting for !tck, then for tck ensures that we don't get any strange races when the clock is
|
||||
// enabled: no matter what the relative phase, we will definitely wait at least a half cycle.
|
||||
task automatic wait_one_tck();
|
||||
fork : isolation_fork begin
|
||||
fork
|
||||
begin
|
||||
wait(!tck);
|
||||
wait(tck);
|
||||
end
|
||||
#(_tck_period_ps * 1ps);
|
||||
join_any
|
||||
disable fork;
|
||||
end join
|
||||
endtask
|
||||
|
||||
// Wait for the given number of cycles of TCK
|
||||
task automatic wait_tck(int cycles);
|
||||
repeat (cycles) wait_one_tck();
|
||||
endtask
|
||||
|
||||
// Start asserting a test reset through trst_n (no effect if the interface is not active)
|
||||
function automatic void assert_test_reset();
|
||||
_trst_n_internal <= 1'b0;
|
||||
endfunction
|
||||
|
||||
// Clear any test reset asserted through trst_n (no effect if the interface is not active)
|
||||
function automatic void clear_test_reset();
|
||||
_trst_n_internal <= 1'b1;
|
||||
endfunction
|
||||
|
||||
// Assert a test reset through trst_n (no effect if the interface is not active)
|
||||
task automatic do_trst_n(int cycles = $urandom_range(5, 20));
|
||||
assert_test_reset();
|
||||
wait_tck(cycles);
|
||||
clear_test_reset();
|
||||
endtask
|
||||
|
||||
// Drive _tck_internal with period _tck_period_ps whenever tck_en is high. If active is true, this
|
||||
// gets used to drive the tck signal.
|
||||
task automatic _drive_active();
|
||||
forever begin
|
||||
wait(tck_en);
|
||||
fork : isolation_fork begin
|
||||
fork
|
||||
wait(!tck_en);
|
||||
forever begin
|
||||
_tck_internal = 1'b1;
|
||||
#(_clk_hi_ps * 1ps);
|
||||
_tck_internal = 1'b0;
|
||||
#(_clk_lo_ps * 1ps);
|
||||
end
|
||||
join_any
|
||||
disable fork;
|
||||
end join
|
||||
end
|
||||
endtask
|
||||
|
||||
initial begin
|
||||
_tck_internal = 1'b1;
|
||||
forever begin
|
||||
wait(is_active === 1'b1);
|
||||
fork : isolation_fork begin
|
||||
fork
|
||||
wait(is_active !== 1'b1);
|
||||
_drive_active();
|
||||
join_any
|
||||
disable fork;
|
||||
end join
|
||||
end
|
||||
end
|
||||
|
||||
endinterface
|
||||
----
|
||||
// Copyright lowRISC contributors (OpenTitan project).
|
||||
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// TODO(#24580): A JTAG UVM agent should configure the JTAG frequency (and not this interface)
|
||||
`ifdef GATE_LEVEL
|
||||
// jtag interface with default 24MHz tck for GLS
|
||||
interface jtag_if #(parameter int unsigned JtagDefaultTckPeriodPs = 41_664) ();
|
||||
`else
|
||||
// jtag interface with default 50MHz tck for faster DV simulations
|
||||
interface jtag_if #(parameter int unsigned JtagDefaultTckPeriodPs = 20_000) ();
|
||||
`endif
|
||||
|
||||
// interface pins
|
||||
wire tck;
|
||||
wire trst_n;
|
||||
wire tms;
|
||||
wire tdi;
|
||||
wire tdo;
|
||||
|
||||
// Is this interface being driven (through _drive_active and the clocking blocks), or is it just
|
||||
// observing some signals from the wider simulation?
|
||||
//
|
||||
// The flag is defined as a wire with a weak pull-up. This ensures that a testbench that doesn't
|
||||
// customise is_active will see the interface be driven actively, but allows a testbench that
|
||||
// *does* want to customise the signal to pull it low.
|
||||
wire is_active;
|
||||
assign (weak0, weak1) is_active = 1'b1;
|
||||
|
||||
// Should this interface generate a local tck signal? To enable that, set tck_en as well as
|
||||
// is_active.
|
||||
bit tck_en;
|
||||
|
||||
// Output-enable flags for tms, tdi, tdo (which only have an effect if is_active is true). The
|
||||
// default configuration enables tms and tdi, so acts as the root of the JTAG tree plus the
|
||||
// "previous device in the scan chain".
|
||||
bit tms_oe = 1'b1;
|
||||
bit tdi_oe = 1'b1;
|
||||
bit tdo_oe = 1'b0;
|
||||
|
||||
logic _tck_internal, _trst_n_internal, _tms_internal, _tdi_internal, _tdo_internal;
|
||||
assign tck = (is_active === 1'b1) ? _tck_internal : 'z;
|
||||
assign trst_n = (is_active === 1'b1) ? _trst_n_internal : 'z;
|
||||
assign tms = ((is_active === 1'b1) && tms_oe) ? _tms_internal : 'z;
|
||||
assign tdi = ((is_active === 1'b1) && tdi_oe) ? _tdi_internal : 'z;
|
||||
assign tdo = ((is_active === 1'b1) && tdo_oe) ? _tdo_internal : 'z;
|
||||
|
||||
// Use negedge to drive jtag inputs because design also use posedge clock edge to sample.
|
||||
clocking host_cb @(negedge tck);
|
||||
default output #1ns;
|
||||
output tms = _tms_internal;
|
||||
output tdi = _tdi_internal;
|
||||
input tdo;
|
||||
endclocking
|
||||
modport host_mp(clocking host_cb, output trst_n);
|
||||
|
||||
clocking device_cb @(posedge tck);
|
||||
input tms;
|
||||
input tdi;
|
||||
output tdo = _tdo_internal;
|
||||
endclocking
|
||||
modport device_mp(clocking device_cb, input trst_n);
|
||||
|
||||
clocking mon_cb @(posedge tck);
|
||||
input tms;
|
||||
input tdi;
|
||||
input tdo;
|
||||
endclocking
|
||||
modport mon_mp (clocking mon_cb, input trst_n);
|
||||
|
||||
// Signals for local tck
|
||||
int unsigned _tck_period_ps = JtagDefaultTckPeriodPs;
|
||||
int unsigned _clk_hi_ps, _clk_lo_ps;
|
||||
assign _clk_hi_ps = _tck_period_ps / 2;
|
||||
assign _clk_lo_ps = _tck_period_ps - _clk_hi_ps;
|
||||
|
||||
// Sets the TCK frequency.
|
||||
function automatic void set_tck_period_ps(int unsigned value);
|
||||
_tck_period_ps = value;
|
||||
endfunction
|
||||
|
||||
function automatic int unsigned get_tck_period_ps();
|
||||
return _tck_period_ps;
|
||||
endfunction
|
||||
|
||||
// Wait for one TCK cycle
|
||||
//
|
||||
// This waits for TCK to clear and then be asserted (so is waiting for the next posedge), but
|
||||
// bounds the wait by _tck_period_ps (in case the clock has stopped).
|
||||
//
|
||||
// Waiting for !tck, then for tck ensures that we don't get any strange races when the clock is
|
||||
// enabled: no matter what the relative phase, we will definitely wait at least a half cycle.
|
||||
task automatic wait_one_tck();
|
||||
fork : isolation_fork begin
|
||||
fork
|
||||
begin
|
||||
wait(!tck);
|
||||
wait(tck);
|
||||
end
|
||||
#(_tck_period_ps * 1ps);
|
||||
join_any
|
||||
disable fork;
|
||||
end join
|
||||
endtask
|
||||
|
||||
// Wait for the given number of cycles of TCK
|
||||
task automatic wait_tck(int cycles);
|
||||
repeat (cycles) wait_one_tck();
|
||||
endtask
|
||||
|
||||
// Start asserting a test reset through trst_n (no effect if the interface is not active)
|
||||
function automatic void assert_test_reset();
|
||||
_trst_n_internal <= 1'b0;
|
||||
endfunction
|
||||
|
||||
// Clear any test reset asserted through trst_n (no effect if the interface is not active)
|
||||
function automatic void clear_test_reset();
|
||||
_trst_n_internal <= 1'b1;
|
||||
endfunction
|
||||
|
||||
// Assert a test reset through trst_n (no effect if the interface is not active)
|
||||
task automatic do_trst_n(int cycles = $urandom_range(5, 20));
|
||||
assert_test_reset();
|
||||
wait_tck(cycles);
|
||||
clear_test_reset();
|
||||
endtask
|
||||
|
||||
// Drive _tck_internal with period _tck_period_ps whenever tck_en is high. If active is true, this
|
||||
// gets used to drive the tck signal.
|
||||
task automatic _drive_active();
|
||||
forever begin
|
||||
wait(tck_en);
|
||||
fork : isolation_fork begin
|
||||
fork
|
||||
wait(!tck_en);
|
||||
forever begin
|
||||
_tck_internal = 1'b1;
|
||||
#(_clk_hi_ps * 1ps);
|
||||
_tck_internal = 1'b0;
|
||||
#(_clk_lo_ps * 1ps);
|
||||
end
|
||||
join_any
|
||||
disable fork;
|
||||
end join
|
||||
end
|
||||
endtask
|
||||
|
||||
initial begin
|
||||
_tck_internal = 1'b1;
|
||||
forever begin
|
||||
wait(is_active === 1'b1);
|
||||
fork : isolation_fork begin
|
||||
fork
|
||||
wait(is_active !== 1'b1);
|
||||
_drive_active();
|
||||
join_any
|
||||
disable fork;
|
||||
end join
|
||||
end
|
||||
end
|
||||
|
||||
endinterface
|
||||
@@ -2350,6 +2350,16 @@ const RTL_FIXTURES: &[&str] = &[
|
||||
"package p;\n typedef struct packed {\n logic [3:0] hi;\n logic [3:0] lo;\n } word_t;\n typedef enum logic [1:0] {A = 2'd0, B, C} st_e;\nendpackage\n",
|
||||
"module m;\n sub #(.W(8)) u0 (.clk(clk), .d(d[3:0]), .q());\nendmodule\n",
|
||||
"module m;\n assign y = cond ? a[3:0] : pkg::f(b).c;\nendmodule\n",
|
||||
// A net delay on either side of the data type: the gap in front of the
|
||||
// `#` is `NetDelay::before_hash` (TODO §43.2), and the fuzzer is what
|
||||
// says the other gaps around it kept their owners.
|
||||
"module m;\n wire #5 a;\n wire [7:0] #1 b = c;\nendmodule\n",
|
||||
// A delay *list*: the `min:typ:max` spelling a net and a continuous
|
||||
// assignment take, and the `(rise, fall)` spelling only a gate takes
|
||||
// (TODO §45.4). The gaps around the `(`, the two `:` and the `,` had no
|
||||
// owner until this round — `MinTypMaxComments`, `DelayValue`, and the
|
||||
// gate's own `before_hash`/`after_hash`/`before_args`/`before_semi`.
|
||||
"module m;\n wire #(1:2:3) a;\n assign #(1:2:3) z = a;\n and #(2, 3) g1 (y, a, b);\nendmodule\n",
|
||||
];
|
||||
|
||||
#[test]
|
||||
@@ -2357,8 +2367,9 @@ fn a_comment_in_every_rtl_gap_still_formats() {
|
||||
assert_no_failing_gaps("RTL", RTL_FIXTURES, EXPECTED_RTL_GAPS);
|
||||
}
|
||||
|
||||
/// Inter-token gaps across [`RTL_FIXTURES`].
|
||||
const EXPECTED_RTL_GAPS: usize = 352;
|
||||
/// Inter-token gaps across [`RTL_FIXTURES`]. 374 before TODO §45.4 added the
|
||||
/// delay-list fixture, whose 45 gaps brought the total here.
|
||||
const EXPECTED_RTL_GAPS: usize = 419;
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Vendor and formal collateral — `vendor-formal-grammar`
|
||||
@@ -2888,3 +2899,106 @@ fn a_structured_assertion_may_be_relaid_out() {
|
||||
assert!(out.contains("lbl: assert property (@(posedge clk) disable iff (rst)"), "{out}");
|
||||
assert_eq!(format_source(&out, &Config::default()).expect("and is a fixed point"), out);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The delay list's new comment slots — `docs/features/small-items-4/README.md`
|
||||
//
|
||||
// `verify.rs` was not touched and no normalization was widened; these are the
|
||||
// standing attack pairs CLAUDE.md invariant 4 asks for anyway, one per token
|
||||
// a slot added by TODO §45.4 is defined *between*. Each moves the comment
|
||||
// across exactly that token, and each must be refused.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_delay_comment_moved_across_a_min_typ_max_colon_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n wire #(1 /*c*/ : 2 : 3) w;\nendmodule\n",
|
||||
"module m;\n wire #(1 : /*c*/ 2 : 3) w;\nendmodule\n",
|
||||
);
|
||||
expect_divergence(
|
||||
"module m;\n wire #(1 : 2 /*c*/ : 3) w;\nendmodule\n",
|
||||
"module m;\n wire #(1 : 2 : /*c*/ 3) w;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delay_comment_moved_across_the_lists_brackets_is_rejected() {
|
||||
// The `(` of a one-value delay, whose slots are its `ExprKind::Paren`'s.
|
||||
expect_divergence(
|
||||
"module m;\n wire # /*c*/ (1:2:3) w;\nendmodule\n",
|
||||
"module m;\n wire #( /*c*/ 1:2:3) w;\nendmodule\n",
|
||||
);
|
||||
// And the `)`.
|
||||
expect_divergence(
|
||||
"module m;\n wire #(1:2:3 /*c*/ ) w;\nendmodule\n",
|
||||
"module m;\n wire #(1:2:3) /*c*/ w;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gate_delay_comment_moved_across_the_hash_or_a_comma_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n and /*c*/ #(2, 3) g (y, a);\nendmodule\n",
|
||||
"module m;\n and # /*c*/ (2, 3) g (y, a);\nendmodule\n",
|
||||
);
|
||||
expect_divergence(
|
||||
"module m;\n and #(2 /*c*/, 3) g (y, a);\nendmodule\n",
|
||||
"module m;\n and #(2, /*c*/ 3) g (y, a);\nendmodule\n",
|
||||
);
|
||||
// The gate instance's own two new slots: before its `(` and before the `;`.
|
||||
expect_divergence(
|
||||
"module m;\n and #(2, 3) g /*c*/ (y, a);\nendmodule\n",
|
||||
"module m;\n and #(2, 3) g ( /*c*/ y, a);\nendmodule\n",
|
||||
);
|
||||
expect_divergence(
|
||||
"module m;\n and #(2, 3) g (y, a) /*c*/ ;\nendmodule\n",
|
||||
"module m;\n and #(2, 3) g (y, a); /*c*/\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_continuous_assignments_delay_comment_moved_across_it_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n assign # /*c*/ (5) y = a;\nendmodule\n",
|
||||
"module m;\n assign /*c*/ #(5) y = a;\nendmodule\n",
|
||||
);
|
||||
expect_divergence(
|
||||
"module m;\n assign #(5) /*c*/ y = a;\nendmodule\n",
|
||||
"module m;\n assign /*c*/ #(5) y = a;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_delay_list_comment_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n and #(2 /*c*/, 3) g (y, a);\nendmodule\n",
|
||||
"module m;\n and #(2, 3) g (y, a);\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The inline aggregate as a parameter-override argument — TODO §45.3
|
||||
//
|
||||
// A construct the parser refused until this round is a construct the safety
|
||||
// net had never been asked about. These say it is asked now.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_dropped_member_of_an_inline_aggregate_override_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n sub #(.T(struct packed {logic a; logic b;})) u ();\nendmodule\n",
|
||||
"module m;\n sub #(.T(struct packed {logic a;})) u ();\nendmodule\n",
|
||||
);
|
||||
expect_divergence(
|
||||
"module m;\n sub #(.T(enum logic [1:0] {A, B})) u ();\nendmodule\n",
|
||||
"module m;\n sub #(.T(enum logic [1:0] {A})) u ();\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_packed_keyword_in_an_override_argument_is_rejected() {
|
||||
expect_divergence(
|
||||
"module m;\n sub #(.T(struct packed {logic a;})) u ();\nendmodule\n",
|
||||
"module m;\n sub #(.T(struct {logic a;})) u ();\nendmodule\n",
|
||||
);
|
||||
}
|
||||
@@ -12,6 +12,12 @@ vlog_parser = { path = "../vlog_parser" }
|
||||
# workspace crate that answers that, and it depends on `vlog_parser` alone, so
|
||||
# this adds no external code — see docs/features/semantic-lints/README.md.
|
||||
vlog_semantic = { path = "../vlog_semantic" }
|
||||
# A waiver file's `--location` is matched exactly the way an `--exclude`
|
||||
# pattern is, and that matcher is `lucisv_core::walk::is_excluded`. Depending
|
||||
# on it rather than copying it is the only way the two can be *the same*
|
||||
# semantics; `lucisv_core` itself has no dependencies at all, so this adds no
|
||||
# external code and closes no loop — see docs/features/waiver-files/README.md.
|
||||
lucisv_core = { path = "../lucisv_core" }
|
||||
|
||||
[dev-dependencies]
|
||||
# Tests only: the .lint case harness asserts that a lint fix never produces
|
||||
|
||||
@@ -39,6 +39,7 @@ mod violation;
|
||||
mod visit;
|
||||
mod vscode;
|
||||
mod waiver;
|
||||
mod waiver_file;
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -58,6 +59,7 @@ pub use violation::{apply_fixes, Applicability, Fix, Fixed, Violation};
|
||||
pub use vlog_semantic::words;
|
||||
pub use vscode::{rule_setting, severity_setting, vscode_lint_settings, RULE_CHOICES};
|
||||
pub use waiver::UNUSED_WAIVER;
|
||||
pub use waiver_file::{ExternalWaivers, UnusedReport, WaiverUse};
|
||||
|
||||
use waiver::Waivers;
|
||||
|
||||
@@ -74,14 +76,32 @@ pub fn run(source: &str, path: Option<PathBuf>, enabled: &[&'static dyn Rule]) -
|
||||
/// The result is sorted by position, then by rule name, so two runs over the
|
||||
/// same file print in the same order whatever order the registry has.
|
||||
pub fn lint(ctx: &LintContext, enabled: &[&'static dyn Rule]) -> Vec<Violation> {
|
||||
lint_with(ctx, enabled, &ExternalWaivers::default()).0
|
||||
}
|
||||
|
||||
/// [`lint`] with the run's external waiver files applied too, reporting which
|
||||
/// of their directives fired.
|
||||
///
|
||||
/// **Precedence is union**: a violation is dropped when an inline waiver *or*
|
||||
/// an external one covers it, and one both cover marks both used, so neither
|
||||
/// is then reported as dead. The usage half is the caller's to keep — only a
|
||||
/// whole run knows whether a `--location` matched some file somewhere, which
|
||||
/// is why `lucisv check` reports unused external waivers and the server does
|
||||
/// not. See `docs/features/waiver-files/README.md`.
|
||||
pub fn lint_with(
|
||||
ctx: &LintContext,
|
||||
enabled: &[&'static dyn Rule],
|
||||
external: &ExternalWaivers,
|
||||
) -> (Vec<Violation>, WaiverUse) {
|
||||
let names: Vec<&'static str> = enabled.iter().map(|rule| rule.name()).collect();
|
||||
let mut waivers = Waivers::collect(ctx);
|
||||
let mut used = WaiverUse::default();
|
||||
|
||||
let mut found = Vec::new();
|
||||
for rule in enabled {
|
||||
found.extend(rule.check(ctx));
|
||||
}
|
||||
let mut kept = waivers.filter(ctx, found);
|
||||
let mut kept = waive(ctx, &mut waivers, external, &mut used, found);
|
||||
|
||||
if names.contains(&UNUSED_WAIVER) {
|
||||
// `unused-waiver` findings are themselves waivable, which is circular:
|
||||
@@ -92,7 +112,7 @@ pub fn lint(ctx: &LintContext, enabled: &[&'static dyn Rule]) -> Vec<Violation>
|
||||
loop {
|
||||
let before = waivers.used_count();
|
||||
let unused = waivers.unused(&names);
|
||||
let surviving = waivers.filter(ctx, unused);
|
||||
let surviving = waive(ctx, &mut waivers, external, &mut used, unused);
|
||||
if waivers.used_count() == before {
|
||||
kept.extend(surviving);
|
||||
break;
|
||||
@@ -104,7 +124,31 @@ pub fn lint(ctx: &LintContext, enabled: &[&'static dyn Rule]) -> Vec<Violation>
|
||||
(a.span.start, a.span.end, a.rule).cmp(&(b.span.start, b.span.end, b.rule))
|
||||
});
|
||||
stamp_severities(&mut kept);
|
||||
kept
|
||||
(kept, used)
|
||||
}
|
||||
|
||||
/// The violations neither an inline waiver nor an external one covers.
|
||||
///
|
||||
/// Both are always asked — never `||` short-circuited — because a violation
|
||||
/// two waivers cover has to mark both of them used.
|
||||
fn waive(
|
||||
ctx: &LintContext,
|
||||
inline: &mut Waivers,
|
||||
external: &ExternalWaivers,
|
||||
used: &mut WaiverUse,
|
||||
violations: Vec<Violation>,
|
||||
) -> Vec<Violation> {
|
||||
let path = ctx.path();
|
||||
violations
|
||||
.into_iter()
|
||||
.filter(|violation| {
|
||||
let (line, _) = ctx.line_index().line_col(violation.span.start);
|
||||
let inline_waived = inline.covers(violation.rule, line);
|
||||
let external_waived =
|
||||
!external.is_empty() && external.covers(path, violation.rule, line, used);
|
||||
!(inline_waived || external_waived)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Gives every finding the class its rule declares.
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -68,13 +68,6 @@ impl Rule for UndrivenNet {
|
||||
if intentionally_unused(&decl.name) || !signals.judgeable(decl) || decl.has_init {
|
||||
continue;
|
||||
}
|
||||
// A name another file in the project writes down may be driven
|
||||
// from there — a hierarchical assignment, a `force` in a
|
||||
// testbench, a `bind`-ed override — none of which this file can
|
||||
// see. Silence is the only honest answer.
|
||||
if ctx.mentioned_elsewhere(&decl.name) {
|
||||
continue;
|
||||
}
|
||||
let Some(usage) = signals.usage(decl) else { continue };
|
||||
// A `release`/`deassign` is a write that establishes no value, so
|
||||
// it is not what saves a signal from this rule.
|
||||
@@ -82,6 +75,25 @@ impl Rule for UndrivenNet {
|
||||
if signals.connected(decl) || driven || usage.reads == 0 {
|
||||
continue;
|
||||
}
|
||||
// A name another file in the project writes down may be driven
|
||||
// from there — a hierarchical assignment, a `force` in a
|
||||
// testbench, a `bind`-ed override — none of which this file can
|
||||
// see. Silence is the only honest answer.
|
||||
//
|
||||
// **Asked last, of the handful of declarations that would
|
||||
// otherwise be reported**, and not second, of every declaration in
|
||||
// the file: the oracle walks every indexed file's word list per
|
||||
// question (`WorkspaceIndex::files_mentioning`), so at the position
|
||||
// this check used to sit at, a 42 000-line buffer asked it four
|
||||
// thousand times and the rule cost 1.6 s of every `didOpen` and
|
||||
// every keystroke flush. The guards above are all local and all
|
||||
// O(1)-ish, the whole condition is one conjunction of `continue`s,
|
||||
// and `unused-signal` — the twin rule with the same oracle — has
|
||||
// always asked last. Same findings, in the same order
|
||||
// (`docs/features/didopen-cost/README.md`).
|
||||
if ctx.mentioned_elsewhere(&decl.name) {
|
||||
continue;
|
||||
}
|
||||
found.push(Violation::new(
|
||||
NAME,
|
||||
format!("`{}` is read but never driven", decl.name),
|
||||
@@ -107,17 +119,56 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// An oracle that says exactly these names are mentioned in another file.
|
||||
struct Elsewhere(&'static [&'static str]);
|
||||
/// An oracle that says exactly these names are mentioned in another file,
|
||||
/// and counts how often it was asked.
|
||||
struct Elsewhere(&'static [&'static str], std::sync::atomic::AtomicUsize);
|
||||
|
||||
impl Elsewhere {
|
||||
fn new(names: &'static [&'static str]) -> Elsewhere {
|
||||
Elsewhere(names, std::sync::atomic::AtomicUsize::new(0))
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::MentionOracle for Elsewhere {
|
||||
fn mentioned_elsewhere(&self, name: &str) -> bool {
|
||||
self.1.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
self.0.contains(&name)
|
||||
}
|
||||
}
|
||||
|
||||
/// TODO.md §46: the oracle is asked about the declarations that would
|
||||
/// otherwise be **reported**, not about every declaration in the file.
|
||||
///
|
||||
/// One question per real candidate is the whole of the fix: the server's
|
||||
/// oracle walks every indexed file's word list per question, so asking it
|
||||
/// ahead of the local guards cost 1.6 s of every `didOpen` of opentitan's
|
||||
/// 42 000-line `pinmux_reg_top.sv` — see
|
||||
/// `docs/features/didopen-cost/README.md`. Asserted on the count, because
|
||||
/// the findings alone cannot tell the two orders apart.
|
||||
#[test]
|
||||
fn the_project_is_asked_only_about_the_signals_that_would_be_reported() {
|
||||
// Ten signals: nine driven and read, one read and undriven.
|
||||
let mut src = String::from("module m (output logic q);\n");
|
||||
for k in 0..9 {
|
||||
src.push_str(&format!(" wire d{k};\n assign d{k} = 1'b0;\n"));
|
||||
}
|
||||
src.push_str(" wire lonely;\n assign q = lonely");
|
||||
for k in 0..9 {
|
||||
src.push_str(&format!(" ^ d{k}"));
|
||||
}
|
||||
src.push_str(";\nendmodule\n");
|
||||
|
||||
let oracle = Elsewhere::new(&[]);
|
||||
let ctx = LintContext::new(&src, None).with_oracle(&oracle);
|
||||
let found = UndrivenNet.check(&ctx);
|
||||
assert_eq!(found.len(), 1, "only the undriven one: {found:#?}");
|
||||
assert!(found[0].message.contains("lonely"), "{:?}", found[0].message);
|
||||
let asked = oracle.1.load(std::sync::atomic::Ordering::Relaxed);
|
||||
assert_eq!(asked, 1, "the project was asked about the driven signals too");
|
||||
}
|
||||
|
||||
fn names_in_a_project(src: &str, elsewhere: &'static [&'static str]) -> Vec<String> {
|
||||
let oracle = Elsewhere(elsewhere);
|
||||
let oracle = Elsewhere::new(elsewhere);
|
||||
let ctx = LintContext::new(src, None).with_oracle(&oracle);
|
||||
UndrivenNet
|
||||
.check(&ctx)
|
||||
|
||||
@@ -113,26 +113,20 @@ impl Waivers {
|
||||
Waivers { entries }
|
||||
}
|
||||
|
||||
/// Drops the violations a waiver covers, marking those waivers used.
|
||||
pub(crate) fn filter(
|
||||
&mut self,
|
||||
ctx: &LintContext,
|
||||
violations: Vec<Violation>,
|
||||
) -> Vec<Violation> {
|
||||
violations
|
||||
.into_iter()
|
||||
.filter(|violation| {
|
||||
let (line, _) = ctx.line_index().line_col(violation.span.start);
|
||||
let mut waived = false;
|
||||
for entry in &mut self.entries {
|
||||
if entry.rule == violation.rule && entry.scope.covers(line) {
|
||||
entry.used = true;
|
||||
waived = true;
|
||||
}
|
||||
}
|
||||
!waived
|
||||
})
|
||||
.collect()
|
||||
/// True when some waiver covers `rule` at `line`, marking every waiver
|
||||
/// that does used.
|
||||
///
|
||||
/// Every one, not the first: a finding two waivers cover has both of them
|
||||
/// doing their job, and reporting the second as dead would be a lie.
|
||||
pub(crate) fn covers(&mut self, rule: &str, line: u32) -> bool {
|
||||
let mut waived = false;
|
||||
for entry in &mut self.entries {
|
||||
if entry.rule == rule && entry.scope.covers(line) {
|
||||
entry.used = true;
|
||||
waived = true;
|
||||
}
|
||||
}
|
||||
waived
|
||||
}
|
||||
|
||||
/// How many waivers have suppressed something so far. Grows only, which
|
||||
|
||||
@@ -0,0 +1,570 @@
|
||||
//! External waiver files: Verible's `waive` directives, written in a file of
|
||||
//! their own rather than in a comment in the RTL.
|
||||
//!
|
||||
//! Grammar (Verible's, so an existing `.waiver` file carries over unchanged) —
|
||||
//! one directive per line, `#` comments and blank lines ignored:
|
||||
//!
|
||||
//! ```text
|
||||
//! waive --rule=<rule> every line of every file
|
||||
//! waive --rule=<rule> --line=12 one line
|
||||
//! waive --rule=<rule> --line=12-20 a range, both ends included
|
||||
//! waive --rule=<rule> --location=legacy_top.sv the files that pattern names
|
||||
//! ```
|
||||
//!
|
||||
//! The one deliberate difference from Verible: `--location` is **not** a
|
||||
//! regular expression. It is matched exactly the way an `--exclude` pattern is
|
||||
//! ([`lucisv_core::walk::is_excluded`]), so a pattern means one thing across
|
||||
//! the whole tool; a pattern that looks like a regex is refused with a message
|
||||
//! saying so rather than silently matching nothing.
|
||||
//!
|
||||
//! Precedence is **union** with the inline waivers of `waiver.rs`: a violation
|
||||
//! is suppressed when either covers it, and a violation both cover marks both
|
||||
//! used. See `docs/features/waiver-files/README.md`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
use crate::registry::rule_by_name;
|
||||
use crate::severity::Severity;
|
||||
use crate::violation::Violation;
|
||||
use crate::waiver::UNUSED_WAIVER;
|
||||
|
||||
/// Every external waiver of one run, from any number of files.
|
||||
#[derive(Default)]
|
||||
pub struct ExternalWaivers {
|
||||
sources: Vec<Source>,
|
||||
directives: Vec<Directive>,
|
||||
}
|
||||
|
||||
/// One waiver file that was read. Its text is kept because an unused
|
||||
/// directive is reported at the line it was written on, and only the text
|
||||
/// turns that directive's span into a line and a column.
|
||||
struct Source {
|
||||
path: PathBuf,
|
||||
text: String,
|
||||
}
|
||||
|
||||
/// One `waive` directive.
|
||||
struct Directive {
|
||||
/// Index into [`ExternalWaivers::sources`].
|
||||
source: usize,
|
||||
/// The directive's own line, where an `unused-waiver` finding points.
|
||||
span: TextRange,
|
||||
/// The rule waived; always a name the registry knows.
|
||||
rule: String,
|
||||
/// `--line`: 1-based, both ends included. `None` is the whole file.
|
||||
lines: Option<(u32, u32)>,
|
||||
/// `--location`: an `--exclude` pattern. `None` is every file.
|
||||
location: Option<String>,
|
||||
}
|
||||
|
||||
/// Which external waivers have suppressed something.
|
||||
///
|
||||
/// One run's worth: the CLI lints its files in parallel and merges what each
|
||||
/// one used, because a `--location` pattern may cover files linted on several
|
||||
/// workers. Usage only ever grows.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct WaiverUse {
|
||||
used: Vec<bool>,
|
||||
}
|
||||
|
||||
impl WaiverUse {
|
||||
/// Folds another pass's usage into this one.
|
||||
pub fn merge(&mut self, other: &WaiverUse) {
|
||||
if self.used.len() < other.used.len() {
|
||||
self.used.resize(other.used.len(), false);
|
||||
}
|
||||
for (slot, fired) in self.used.iter_mut().zip(&other.used) {
|
||||
*slot |= *fired;
|
||||
}
|
||||
}
|
||||
|
||||
fn mark(&mut self, index: usize) {
|
||||
if self.used.len() <= index {
|
||||
self.used.resize(index + 1, false);
|
||||
}
|
||||
self.used[index] = true;
|
||||
}
|
||||
|
||||
fn fired(&self, index: usize) -> bool {
|
||||
self.used.get(index).copied().unwrap_or(false)
|
||||
}
|
||||
}
|
||||
|
||||
/// One waiver file's dead directives, ready to be reported: the file, its
|
||||
/// text — for the line and column — and one finding each.
|
||||
pub struct UnusedReport {
|
||||
/// The waiver file the directives were written in.
|
||||
pub path: PathBuf,
|
||||
/// That file's text.
|
||||
pub text: String,
|
||||
/// One `unused-waiver` violation per directive that suppressed nothing.
|
||||
pub violations: Vec<Violation>,
|
||||
}
|
||||
|
||||
impl ExternalWaivers {
|
||||
/// Reads one waiver file: the directives that parsed, and one
|
||||
/// `<file>:<line>: message` per line that did not.
|
||||
///
|
||||
/// A file that cannot be read at all is the `Err`; a file that reads and
|
||||
/// has bad lines is an `Ok` carrying both halves, so a front end may
|
||||
/// choose between failing the run (the CLI) and dropping the line and
|
||||
/// logging it (the server).
|
||||
pub fn read(path: &Path) -> Result<(ExternalWaivers, Vec<String>), String> {
|
||||
let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
Ok(ExternalWaivers::parse(path, &text))
|
||||
}
|
||||
|
||||
/// [`ExternalWaivers::read`] over text already in hand.
|
||||
pub fn parse(path: &Path, text: &str) -> (ExternalWaivers, Vec<String>) {
|
||||
let source = Source { path: path.to_path_buf(), text: text.to_string() };
|
||||
let mut waivers = ExternalWaivers { sources: vec![source], directives: Vec::new() };
|
||||
let mut problems = Vec::new();
|
||||
// `split_inclusive` rather than `lines`, so the offsets stay right in
|
||||
// a file with CRLF endings: `lines` drops bytes this has to count.
|
||||
let mut offset: u32 = 0;
|
||||
for (index, raw) in text.split_inclusive('\n').enumerate() {
|
||||
let trimmed = raw.trim_end_matches(['\n', '\r']);
|
||||
let span = TextRange::new(offset, offset + trimmed.len() as u32);
|
||||
offset += raw.len() as u32;
|
||||
// A BOM is not a directive, and an editor that writes one should
|
||||
// not turn the first line into an error naming an invisible byte.
|
||||
let line = trimmed.trim().trim_start_matches('\u{feff}');
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
match parse_directive(line, span) {
|
||||
Ok(directive) => waivers.directives.push(directive),
|
||||
Err(problem) => {
|
||||
problems.push(format!("{}:{}: {problem}", path.display(), index + 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
(waivers, problems)
|
||||
}
|
||||
|
||||
/// Adds another file's directives to these.
|
||||
pub fn absorb(&mut self, other: ExternalWaivers) {
|
||||
let offset = self.sources.len();
|
||||
self.sources.extend(other.sources);
|
||||
self.directives.extend(other.directives.into_iter().map(|mut directive| {
|
||||
directive.source += offset;
|
||||
directive
|
||||
}));
|
||||
}
|
||||
|
||||
/// True when no waiver file contributed a directive — the everyday case,
|
||||
/// and the one the linter must pay nothing for.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.directives.is_empty()
|
||||
}
|
||||
|
||||
/// True when some directive waives this finding, marking every directive
|
||||
/// that does used.
|
||||
///
|
||||
/// Every one, not the first: a finding two waivers cover has both of them
|
||||
/// doing their job, and reporting the second as dead afterwards would be a
|
||||
/// lie.
|
||||
pub(crate) fn covers(
|
||||
&self,
|
||||
path: Option<&Path>,
|
||||
rule: &str,
|
||||
line: u32,
|
||||
used: &mut WaiverUse,
|
||||
) -> bool {
|
||||
let mut waived = false;
|
||||
for (index, directive) in self.directives.iter().enumerate() {
|
||||
if directive.covers(path, rule, line) {
|
||||
used.mark(index);
|
||||
waived = true;
|
||||
}
|
||||
}
|
||||
waived
|
||||
}
|
||||
|
||||
/// The `unused-waiver` findings for directives that suppressed nothing,
|
||||
/// grouped by the file they were written in.
|
||||
///
|
||||
/// `enabled` is every rule the run had switched on. A waiver for a rule
|
||||
/// that never ran is silent, exactly as an inline one is — it never had a
|
||||
/// chance to fire — and so is everything here when `unused-waiver` itself
|
||||
/// is off.
|
||||
pub fn unused(&self, used: &WaiverUse, enabled: &[&'static str]) -> Vec<UnusedReport> {
|
||||
if !enabled.contains(&UNUSED_WAIVER) {
|
||||
return Vec::new();
|
||||
}
|
||||
let severity = rule_by_name(UNUSED_WAIVER).map_or(Severity::Style, |rule| rule.severity());
|
||||
let mut reports: Vec<UnusedReport> = self
|
||||
.sources
|
||||
.iter()
|
||||
.map(|source| UnusedReport {
|
||||
path: source.path.clone(),
|
||||
text: source.text.clone(),
|
||||
violations: Vec::new(),
|
||||
})
|
||||
.collect();
|
||||
for (index, directive) in self.directives.iter().enumerate() {
|
||||
if used.fired(index) || !enabled.contains(&directive.rule.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let message = format!("unused waiver for `{}`", directive.rule);
|
||||
let mut violation = Violation::new(UNUSED_WAIVER, message, directive.span);
|
||||
// Built outside `lint`, which is what stamps every other finding.
|
||||
violation.severity = severity;
|
||||
if let Some(report) = reports.get_mut(directive.source) {
|
||||
report.violations.push(violation);
|
||||
}
|
||||
}
|
||||
reports.retain(|report| !report.violations.is_empty());
|
||||
reports
|
||||
}
|
||||
}
|
||||
|
||||
impl Directive {
|
||||
/// True when this directive waives `rule` at `line` of `path`.
|
||||
///
|
||||
/// A buffer with no path (stdin) is covered by a directive with no
|
||||
/// `--location` and by no other: a pattern cannot match a name that does
|
||||
/// not exist.
|
||||
fn covers(&self, path: Option<&Path>, rule: &str, line: u32) -> bool {
|
||||
if self.rule != rule {
|
||||
return false;
|
||||
}
|
||||
if let Some((start, end)) = self.lines {
|
||||
if line < start || end < line {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
match &self.location {
|
||||
None => true,
|
||||
Some(pattern) => path.is_some_and(|path| {
|
||||
lucisv_core::walk::is_excluded(path, std::slice::from_ref(pattern))
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One directive line: its rule, its line range and its location pattern.
|
||||
///
|
||||
/// `span` is that line's own range in the waiver file, carried into the
|
||||
/// directive so an unused one can be reported where it was written. The
|
||||
/// source index is filled in by [`ExternalWaivers::absorb`].
|
||||
fn parse_directive(line: &str, span: TextRange) -> Result<Directive, String> {
|
||||
let mut words = line.split_whitespace();
|
||||
// The line was trimmed and is not empty, so there is a first word.
|
||||
let keyword = words.next().unwrap_or_default();
|
||||
if keyword != "waive" {
|
||||
return Err(format!("expected a `waive` directive, found `{keyword}`"));
|
||||
}
|
||||
let mut rule: Option<String> = None;
|
||||
let mut lines: Option<(u32, u32)> = None;
|
||||
let mut location: Option<String> = None;
|
||||
for word in words {
|
||||
let (flag, value) = split_flag(word)?;
|
||||
match flag {
|
||||
"--rule" => set_once(&mut rule, flag, parse_rule(value)?)?,
|
||||
"--line" => set_once(&mut lines, flag, parse_lines(value)?)?,
|
||||
_ => set_once(&mut location, flag, parse_location(value)?)?,
|
||||
}
|
||||
}
|
||||
let rule = rule.ok_or("`waive` needs a `--rule=<rule-name>`")?;
|
||||
Ok(Directive { source: 0, span, rule, lines, location })
|
||||
}
|
||||
|
||||
/// Fills a slot the directive may only fill once.
|
||||
fn set_once<T>(slot: &mut Option<T>, flag: &str, value: T) -> Result<(), String> {
|
||||
if slot.is_some() {
|
||||
return Err(format!("`{flag}` is given twice"));
|
||||
}
|
||||
*slot = Some(value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The `--flag=value` one word of a directive is.
|
||||
fn split_flag(word: &str) -> Result<(&str, &str), String> {
|
||||
let (flag, value) = word.split_once('=').unwrap_or((word, ""));
|
||||
match flag {
|
||||
"--rule" | "--line" | "--location" => {}
|
||||
// Verible's third matcher waives by the *text* of the line, which
|
||||
// needs the regex engine lucisv deliberately does not have.
|
||||
"--regex" => {
|
||||
return Err("`--regex` is not supported; waive by `--line` or `--location`".to_string())
|
||||
}
|
||||
other => {
|
||||
return Err(format!(
|
||||
"unknown option `{other}` (the options are `--rule`, `--line` and `--location`)"
|
||||
))
|
||||
}
|
||||
}
|
||||
if !word.contains('=') {
|
||||
return Err(format!("`{flag}` takes a value: write `{flag}=<value>`"));
|
||||
}
|
||||
if value.is_empty() {
|
||||
return Err(format!("`{flag}` has an empty value"));
|
||||
}
|
||||
Ok((flag, value))
|
||||
}
|
||||
|
||||
/// A `--rule` value: one rule the registry knows.
|
||||
///
|
||||
/// A severity word is refused rather than expanded. `--select style` turns a
|
||||
/// whole class on for a run the user is watching; a waiver file is checked in,
|
||||
/// and one word there quietly silencing every style rule in the project is not
|
||||
/// a thing anyone should be able to write by accident.
|
||||
fn parse_rule(value: &str) -> Result<String, String> {
|
||||
if rule_by_name(value).is_some() {
|
||||
return Ok(value.to_string());
|
||||
}
|
||||
if Severity::from_name(value).is_some() {
|
||||
return Err(format!(
|
||||
"`--rule={value}` names a severity class; a waiver names one rule at a time"
|
||||
));
|
||||
}
|
||||
Err(format!("unknown rule `{value}`"))
|
||||
}
|
||||
|
||||
/// A `--line` value: `N` or `N-M`, 1-based, both ends included.
|
||||
fn parse_lines(value: &str) -> Result<(u32, u32), String> {
|
||||
let malformed =
|
||||
|| format!("`--line={value}` is not a line or a line range (`--line=5`, `--line=5-9`)");
|
||||
let (start, end) = value.split_once('-').unwrap_or((value, value));
|
||||
let start: u32 = start.parse().map_err(|_| malformed())?;
|
||||
let end: u32 = end.parse().map_err(|_| malformed())?;
|
||||
if start == 0 {
|
||||
return Err(format!("`--line={value}` starts at 0; lines are numbered from 1"));
|
||||
}
|
||||
if end < start {
|
||||
return Err(format!("`--line={value}` counts backwards"));
|
||||
}
|
||||
Ok((start, end))
|
||||
}
|
||||
|
||||
/// A `--location` value: an `--exclude` pattern, never a regex.
|
||||
fn parse_location(value: &str) -> Result<String, String> {
|
||||
match regex_hint(value) {
|
||||
Some(found) => Err(format!(
|
||||
"`--location={value}` looks like a regular expression (`{found}`); lucisv matches a \
|
||||
location the way `--exclude` does — `*` stands for any run of characters within one \
|
||||
path component, a pattern with `/` matches a path suffix and one without matches the \
|
||||
file name, and nothing else is a metacharacter"
|
||||
)),
|
||||
None => Ok(value.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The first regex metacharacter in a pattern, if it has one.
|
||||
///
|
||||
/// A bare `.` is not one: `foo.sv` is a file name. `.*` and `.+` are, and so
|
||||
/// is every character that means nothing in a glob and something in a regex.
|
||||
fn regex_hint(pattern: &str) -> Option<String> {
|
||||
for token in [".*", ".+"] {
|
||||
if pattern.contains(token) {
|
||||
return Some(token.to_string());
|
||||
}
|
||||
}
|
||||
pattern.chars().find(|c| "\\^$[]()|?+{}".contains(*c)).map(|c| c.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn waivers(text: &str) -> (ExternalWaivers, Vec<String>) {
|
||||
ExternalWaivers::parse(Path::new("project.waiver"), text)
|
||||
}
|
||||
|
||||
/// The one problem `text` produces, without the `file:line: ` prefix.
|
||||
fn problem(text: &str) -> String {
|
||||
let (waivers, problems) = waivers(text);
|
||||
assert!(waivers.is_empty(), "a bad line contributes no directive");
|
||||
assert_eq!(problems.len(), 1, "{problems:?}");
|
||||
problems[0].split_once(": ").expect("a `file:line: message`").1.to_string()
|
||||
}
|
||||
|
||||
/// Whether the file's directives waive `rule` at `line` of `path`.
|
||||
fn covered(text: &str, path: Option<&str>, rule: &str, line: u32) -> bool {
|
||||
let (waivers, problems) = waivers(text);
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
let mut used = WaiverUse::default();
|
||||
waivers.covers(path.map(Path::new), rule, line, &mut used)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_directive_shape_parses() {
|
||||
let (waivers, problems) = waivers(
|
||||
"# a comment\n\
|
||||
\n\
|
||||
waive --rule=no-tabs\n\
|
||||
waive --rule=no-tabs --line=12\n\
|
||||
waive --rule=no-tabs --line=12-20\n\
|
||||
waive --rule=no-tabs --location=legacy.sv\n\
|
||||
\x20 waive --rule=no-tabs --line=3 --location=rtl/legacy.sv\n\
|
||||
waive --location=a.sv --rule=no-tabs\n",
|
||||
);
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
assert_eq!(waivers.directives.len(), 6);
|
||||
assert_eq!(waivers.directives[1].lines, Some((12, 12)));
|
||||
assert_eq!(waivers.directives[2].lines, Some((12, 20)));
|
||||
assert_eq!(waivers.directives[3].location.as_deref(), Some("legacy.sv"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_line_endings_do_not_shift_a_directives_span() {
|
||||
let (waivers, problems) = waivers("# note\r\nwaive --rule=no-tabs\r\n");
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
let span = waivers.directives[0].span;
|
||||
assert_eq!(span.start as usize, "# note\r\n".len());
|
||||
assert_eq!(span.end as usize, "# note\r\nwaive --rule=no-tabs".len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_error_names_the_file_the_line_and_the_difference() {
|
||||
let (_, problems) = waivers("waive --rule=no-such-rule\n");
|
||||
assert_eq!(problems[0], "project.waiver:1: unknown rule `no-such-rule`");
|
||||
|
||||
assert_eq!(problem("waive\n"), "`waive` needs a `--rule=<rule-name>`");
|
||||
assert_eq!(problem("waive --line=3\n"), "`waive` needs a `--rule=<rule-name>`");
|
||||
assert!(problem("skip --rule=no-tabs\n").contains("found `skip`"));
|
||||
assert!(problem("waive --rule=style\n").contains("names a severity class"));
|
||||
assert!(problem("waive --rule=no-tabs --line=0\n").contains("numbered from 1"));
|
||||
assert!(problem("waive --rule=no-tabs --line=9-5\n").contains("counts backwards"));
|
||||
assert!(problem("waive --rule=no-tabs --line=x\n").contains("is not a line or a line"));
|
||||
assert!(problem("waive --rule=no-tabs --line=5-\n").contains("is not a line or a line"));
|
||||
assert!(problem("waive --rule=no-tabs --rule=no-tabs\n").contains("given twice"));
|
||||
assert!(problem("waive --rule=no-tabs --lines=3\n").contains("unknown option `--lines`"));
|
||||
assert!(problem("waive --rule=no-tabs --regex=x\n").contains("`--regex` is not supported"));
|
||||
assert!(problem("waive --rule\n").contains("takes a value"));
|
||||
assert!(problem("waive --rule=\n").contains("empty value"));
|
||||
assert!(problem("waive --rule=no-tabs --location=x --location=y\n").contains("twice"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_regex_looking_location_is_refused_and_a_glob_is_not() {
|
||||
for pattern in [".*_pkg.sv", "top\\.sv", "^a.sv$", "(a|b).sv", "a?.sv", "a+.sv", "[ab].sv"]
|
||||
{
|
||||
let text = format!("waive --rule=no-tabs --location={pattern}\n");
|
||||
let message = problem(&text);
|
||||
assert!(message.contains("looks like a regular expression"), "{pattern}: {message}");
|
||||
assert!(message.contains("`--exclude`"), "{pattern}: {message}");
|
||||
}
|
||||
for pattern in ["a.sv", "*_gen.sv", "rtl/*.sv", "legacy/top.sv", "*"] {
|
||||
let text = format!("waive --rule=no-tabs --location={pattern}\n");
|
||||
let (_, problems) = waivers(&text);
|
||||
assert!(problems.is_empty(), "{pattern}: {problems:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directive_with_no_line_and_no_location_covers_everything() {
|
||||
let text = "waive --rule=no-tabs\n";
|
||||
assert!(covered(text, Some("rtl/a.sv"), "no-tabs", 1));
|
||||
assert!(covered(text, Some("elsewhere/b.sv"), "no-tabs", 900));
|
||||
assert!(covered(text, None, "no-tabs", 1), "a stdin buffer too");
|
||||
assert!(!covered(text, Some("rtl/a.sv"), "no-trailing-whitespace", 1), "another rule");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_covers_itself_and_a_range_covers_both_ends() {
|
||||
let one = "waive --rule=no-tabs --line=12\n";
|
||||
assert!(covered(one, Some("a.sv"), "no-tabs", 12));
|
||||
assert!(!covered(one, Some("a.sv"), "no-tabs", 11));
|
||||
assert!(!covered(one, Some("a.sv"), "no-tabs", 13));
|
||||
|
||||
let range = "waive --rule=no-tabs --line=12-14\n";
|
||||
for line in [12, 13, 14] {
|
||||
assert!(covered(range, Some("a.sv"), "no-tabs", line), "line {line}");
|
||||
}
|
||||
assert!(!covered(range, Some("a.sv"), "no-tabs", 11));
|
||||
assert!(!covered(range, Some("a.sv"), "no-tabs", 15));
|
||||
}
|
||||
|
||||
/// The `--exclude` semantics, at the waiver file's end of them: a pattern
|
||||
/// without `/` matches the file name at any depth, one with `/` matches a
|
||||
/// path suffix, and `*` stays inside one component.
|
||||
#[test]
|
||||
fn a_location_matches_the_way_an_exclude_pattern_does() {
|
||||
let by_name = "waive --rule=no-tabs --location=legacy.sv\n";
|
||||
assert!(covered(by_name, Some("a/b/legacy.sv"), "no-tabs", 1));
|
||||
assert!(!covered(by_name, Some("a/b/other.sv"), "no-tabs", 1));
|
||||
|
||||
let by_suffix = "waive --rule=no-tabs --location=vendor/legacy.sv\n";
|
||||
assert!(covered(by_suffix, Some("a/vendor/legacy.sv"), "no-tabs", 1));
|
||||
assert!(!covered(by_suffix, Some("a/rtl/legacy.sv"), "no-tabs", 1));
|
||||
|
||||
let glob = "waive --rule=no-tabs --location=*_gen.sv\n";
|
||||
assert!(covered(glob, Some("rtl/top_gen.sv"), "no-tabs", 1));
|
||||
assert!(!covered(glob, Some("rtl/top.sv"), "no-tabs", 1));
|
||||
// `*` does not cross a `/`, exactly as in a walk's exclude.
|
||||
let anchored = "waive --rule=no-tabs --location=rtl/*.sv\n";
|
||||
assert!(covered(anchored, Some("top/rtl/b.sv"), "no-tabs", 1));
|
||||
assert!(!covered(anchored, Some("rtl/a/b.sv"), "no-tabs", 1));
|
||||
|
||||
// A buffer with no path is covered by nothing that names a location.
|
||||
assert!(!covered(by_name, None, "no-tabs", 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directive_that_fired_is_not_reported_and_one_that_did_not_is() {
|
||||
let (waivers, problems) =
|
||||
waivers("waive --rule=no-tabs\nwaive --rule=no-trailing-whitespace\n");
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
let enabled = ["no-tabs", "no-trailing-whitespace", UNUSED_WAIVER];
|
||||
|
||||
let mut used = WaiverUse::default();
|
||||
assert!(waivers.covers(Some(Path::new("a.sv")), "no-tabs", 1, &mut used));
|
||||
|
||||
let reports = waivers.unused(&used, &enabled);
|
||||
assert_eq!(reports.len(), 1, "one waiver file, one group");
|
||||
assert_eq!(reports[0].path, PathBuf::from("project.waiver"));
|
||||
assert_eq!(reports[0].violations.len(), 1, "only the one that never fired");
|
||||
assert!(reports[0].violations[0].message.contains("no-trailing-whitespace"));
|
||||
assert_eq!(reports[0].violations[0].rule, UNUSED_WAIVER);
|
||||
assert_eq!(reports[0].violations[0].severity, Severity::Style, "stamped here");
|
||||
// The finding points at the dead directive's own line.
|
||||
assert_eq!(reports[0].violations[0].span.start as usize, "waive --rule=no-tabs\n".len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_waiver_for_a_rule_the_run_did_not_enable_is_silent() {
|
||||
let (waivers, _) = waivers("waive --rule=no-tabs\n");
|
||||
let used = WaiverUse::default();
|
||||
assert!(waivers.unused(&used, &["no-trailing-whitespace", UNUSED_WAIVER]).is_empty());
|
||||
// And so is everything when `unused-waiver` itself is off.
|
||||
assert!(waivers.unused(&used, &["no-tabs"]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absorbing_a_second_file_keeps_each_directive_with_its_own_file() {
|
||||
let (mut first, _) =
|
||||
ExternalWaivers::parse(Path::new("a.waiver"), "waive --rule=no-tabs\n");
|
||||
let (second, _) =
|
||||
ExternalWaivers::parse(Path::new("b.waiver"), "waive --rule=no-trailing-whitespace\n");
|
||||
first.absorb(second);
|
||||
assert_eq!(first.directives.len(), 2);
|
||||
|
||||
let mut used = WaiverUse::default();
|
||||
assert!(first.covers(Some(Path::new("a.sv")), "no-tabs", 1, &mut used));
|
||||
let reports = first.unused(&used, &["no-tabs", "no-trailing-whitespace", UNUSED_WAIVER]);
|
||||
assert_eq!(reports.len(), 1, "only the file with a dead directive: {}", reports.len());
|
||||
assert_eq!(reports[0].path, PathBuf::from("b.waiver"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_merges_across_the_files_a_run_linted_in_parallel() {
|
||||
let (waivers, _) = waivers(
|
||||
"waive --rule=no-tabs --location=a.sv\n\
|
||||
waive --rule=no-tabs --location=b.sv\n",
|
||||
);
|
||||
let enabled = ["no-tabs", UNUSED_WAIVER];
|
||||
|
||||
let mut first = WaiverUse::default();
|
||||
waivers.covers(Some(Path::new("a.sv")), "no-tabs", 1, &mut first);
|
||||
assert_eq!(waivers.unused(&first, &enabled)[0].violations.len(), 1, "b.sv's is dead");
|
||||
|
||||
let mut second = WaiverUse::default();
|
||||
waivers.covers(Some(Path::new("b.sv")), "no-tabs", 1, &mut second);
|
||||
first.merge(&second);
|
||||
assert!(waivers.unused(&first, &enabled).is_empty(), "both fired, over two files");
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,10 @@
|
||||
use super::*;
|
||||
|
||||
/// A data type: keyword or user-defined name, plus signing and packed dims.
|
||||
/// `name` may be empty for implicit types (`input [7:0] x`).
|
||||
/// `name` may be empty for implicit types (`input [7:0] x`), and is the whole
|
||||
/// chain a qualified type reference writes: `pkg::item`, `bus_if.mp`.
|
||||
/// [`DataType::name_span`] says where it is written and
|
||||
/// [`DataType::segments`] splits it.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct DataType {
|
||||
/// The `virtual` / `virtual interface` prefix of a virtual interface type
|
||||
@@ -22,6 +25,14 @@ pub struct DataType {
|
||||
/// so a rare field must not widen the common case.
|
||||
pub virt: Option<VirtualKw>,
|
||||
pub name: String,
|
||||
/// Where [`DataType::name`] is written. Read it through
|
||||
/// [`DataType::name_span`], which pairs it with the name's own length.
|
||||
///
|
||||
/// Four bytes rather than a whole [`TextRange`] because they fit in the
|
||||
/// padding this struct already has: an eight-byte span pushes `DataType`
|
||||
/// to 96 and, through [`ExprKind::Type`], every `Expr` to 104, past the
|
||||
/// 96-byte pin in `size_pins`.
|
||||
pub(crate) name_start: u32,
|
||||
/// The rare tail of a type: parameterization or an anonymous aggregate
|
||||
/// body. See [`TypeExtra`]; read it through [`DataType::params`] /
|
||||
/// [`DataType::inline`].
|
||||
@@ -57,6 +68,70 @@ impl DataType {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The byte range [`DataType::name`] occupies: `src[name_span] == name`
|
||||
/// for every name the source spells the way the AST joined it, which is
|
||||
/// every name but the pathological spacings [`DataType::segments`]
|
||||
/// documents. An implicit type has no name, so this is the empty range at
|
||||
/// the position a name would have been written — the same convention an
|
||||
/// unnamed DPI formal's `name_span` uses.
|
||||
pub fn name_span(&self) -> TextRange {
|
||||
TextRange::new(self.name_start, self.name_start.saturating_add(self.name.len() as u32))
|
||||
}
|
||||
|
||||
/// The `::`- and `.`-separated segments of the name — `pkg`, `item` of
|
||||
/// `pkg::item`; `bus_if`, `mp` of `bus_if.mp` — each with the byte range
|
||||
/// it occupies.
|
||||
///
|
||||
/// Derived from [`DataType::name_span`] and the name's own text: the
|
||||
/// construct is never rescanned. So a source that spells the name
|
||||
/// differently from the way the parser joined it — an escaped segment
|
||||
/// terminated by a newline rather than a space, a `bus_if . mp` written
|
||||
/// apart — hands back ranges that do not slice back to their segment.
|
||||
/// A caller that must not mislocate checks the slice and drops the
|
||||
/// segment; `vlog_semantic`'s binder does.
|
||||
pub fn segments(&self) -> impl Iterator<Item = (&str, TextRange)> + '_ {
|
||||
let base = self.name_start;
|
||||
let mut rest = Some((0usize, self.name.as_str()));
|
||||
std::iter::from_fn(move || {
|
||||
let (at, text) = rest.take()?;
|
||||
let (seg, tail) = match separator(text) {
|
||||
Some((i, len)) => (&text[..i], Some((at + i + len, &text[i + len..]))),
|
||||
None => (text, None),
|
||||
};
|
||||
rest = tail;
|
||||
let start = base.saturating_add(at as u32);
|
||||
Some((seg, TextRange::new(start, start.saturating_add(seg.len() as u32))))
|
||||
})
|
||||
.filter(|(seg, _): &(&str, TextRange)| !seg.is_empty())
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the first `::`/`.` that separates two name segments starts, and how
|
||||
/// many bytes it is.
|
||||
///
|
||||
/// An escaped identifier swallows both spellings (`\a.b ::x` is two segments,
|
||||
/// not three), so one that leads the text runs to its terminating whitespace —
|
||||
/// which the parser keeps in the joined name (§29) — before the search for a
|
||||
/// separator begins.
|
||||
fn separator(text: &str) -> Option<(usize, usize)> {
|
||||
let bytes = text.as_bytes();
|
||||
let mut i = 0;
|
||||
if bytes.first() == Some(&b'\\') {
|
||||
while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
|
||||
i += 1;
|
||||
}
|
||||
// The terminator belongs to the segment; anything else is a separator.
|
||||
i = (i + 1).min(bytes.len());
|
||||
}
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b':' if bytes.get(i + 1) == Some(&b':') => return Some((i, 2)),
|
||||
b'.' => return Some((i, 1)),
|
||||
_ => i += 1,
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// What a type carries beyond its name, signing and packed dimensions. A type
|
||||
@@ -235,12 +310,39 @@ pub struct ParamDecl {
|
||||
pub declarators: Vec<Declarator>,
|
||||
}
|
||||
|
||||
/// A net delay and the side of the data type it was written on.
|
||||
///
|
||||
/// IEEE 1800 §6.7 puts `delay3` *after* the type —
|
||||
/// `wire [31:0] #0.1 x = y;`, which is how
|
||||
/// `pulp_riscv_dbg/tb/unused/SimDTM.sv:38` writes it — while the spelling
|
||||
/// the rest of the corpus uses puts it between the net keyword and the type.
|
||||
/// Both are read, never both at once, and printed back where they were
|
||||
/// written: moving a delay across the type reorders tokens, which
|
||||
/// `verify.rs` rightly refuses.
|
||||
#[derive(Debug)]
|
||||
pub struct NetDelay {
|
||||
/// Comments written between whatever precedes the delay and its `#`:
|
||||
/// the `/* c */` of `wire /* c */ #5 w;` and of
|
||||
/// `wire [7:0] /* c */ #1 w;`. Without a slot here the comment would be
|
||||
/// printed one node later and `verify.rs` would refuse the file.
|
||||
pub before_hash: Vec<Comment>,
|
||||
/// Comments written between the `#` and the delay value — the delay's
|
||||
/// other gap, and the one the gap fuzzer asks about the moment the
|
||||
/// first one has an owner.
|
||||
pub after_hash: Vec<Comment>,
|
||||
/// The delay itself: the `5` of `wire #5 w;`.
|
||||
pub expr: Expr,
|
||||
/// True when it stood between the data type and the declarators.
|
||||
pub after_type: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DataDecl {
|
||||
/// Net type (`wire`, `tri`, ...) if any.
|
||||
pub net: Option<String>,
|
||||
/// Net delay: the `5` in `wire #5 w;`
|
||||
pub delay: Option<Expr>,
|
||||
/// Net delay, if any: the `5` in `wire #5 w;` or the `0.1` in
|
||||
/// `wire [31:0] #0.1 x = y;`.
|
||||
pub delay: Option<NetDelay>,
|
||||
/// Qualifiers written before the type, in source order: `var`,
|
||||
/// `automatic`, `static`, `const`, and — inside a class body — `rand`,
|
||||
/// `randc`, `local`, `protected`, and the `virtual [interface]` of a
|
||||
|
||||
@@ -259,9 +259,32 @@ pub enum ExprKind {
|
||||
min: Box<Expr>,
|
||||
typ: Box<Expr>,
|
||||
max: Box<Expr>,
|
||||
/// What was written around the two `:`.
|
||||
comments: Box<MinTypMaxComments>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Comments written around the two `:` of a `min : typ : max` delay
|
||||
/// (IEEE 1800 §28.14):
|
||||
///
|
||||
/// ```text
|
||||
/// min /*before_typ*/ : /*after_typ*/ typ /*before_max*/ : /*after_max*/ max
|
||||
/// ```
|
||||
///
|
||||
/// Boxed by its holder for the reason every expression-level slot is: `Expr`
|
||||
/// is walked recursively and its size is pinned at 96 bytes.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct MinTypMaxComments {
|
||||
/// Between `min` and the first `:`.
|
||||
pub before_typ: Vec<Comment>,
|
||||
/// Just after the first `:`.
|
||||
pub after_typ: Vec<Comment>,
|
||||
/// Between `typ` and the second `:`.
|
||||
pub before_max: Vec<Comment>,
|
||||
/// Just after the second `:`.
|
||||
pub after_max: Vec<Comment>,
|
||||
}
|
||||
|
||||
/// Comments written in the fixed slots of a **postfix segment** or a
|
||||
/// **bracketed range** — the one shape the grammar writes in five places:
|
||||
///
|
||||
|
||||
@@ -162,8 +162,15 @@ pub struct ContAssign {
|
||||
/// Drive strength: the `(weak0, pull1)` in
|
||||
/// `assign (weak0, pull1) x = y;` (IEEE 1800 §10.3.1), in source order.
|
||||
pub strength: Option<DriveStrength>,
|
||||
/// Comments written between the `#` and the delay itself.
|
||||
pub after_hash: Vec<Comment>,
|
||||
/// Delay expression: the `5` in `assign #5 x = y;`
|
||||
pub delay: Option<Expr>,
|
||||
/// Comments written between that delay and the first left-hand side.
|
||||
/// Without a slot here they would join the first pair's `meta.leading`,
|
||||
/// which prints straight after the `assign` — in front of the delay the
|
||||
/// source wrote them behind.
|
||||
pub after_delay: Vec<Comment>,
|
||||
pub assigns: Vec<AssignPair>,
|
||||
}
|
||||
|
||||
@@ -363,12 +370,37 @@ pub struct GateInstantiation {
|
||||
/// The `(weak1)` in `pullup (weak1) p (x);` (IEEE 1800 §28.3), or the
|
||||
/// `(strong0, strong1)` pair every driving gate also accepts.
|
||||
pub strength: Option<DriveStrength>,
|
||||
/// Comments written between the gate (or its drive strength) and the `#`
|
||||
/// of the delay: the `/* c */` of `and /* c */ #(2, 3) g (y, a, b);`.
|
||||
pub before_hash: Vec<Comment>,
|
||||
/// Comments written between that `#` and the delay itself.
|
||||
pub after_hash: Vec<Comment>,
|
||||
/// The delay written after `#`: empty when there is none, one element for
|
||||
/// every spelling a net or a continuous assignment also accepts, and two
|
||||
/// or three for the `(rise, fall[, turn-off])` list that only a gate
|
||||
/// takes (IEEE 1800 §28.14, `top_earlgrey/ip/ast/rtl/aon_osc.sv:41`).
|
||||
pub delay: Vec<Expr>,
|
||||
pub delay: Vec<DelayValue>,
|
||||
pub instances: Vec<GateInstance>,
|
||||
/// Comments written between the last instance and the `;`.
|
||||
pub before_semi: Vec<Comment>,
|
||||
}
|
||||
|
||||
/// One value of a delay list, with the comments written on either side of the
|
||||
/// separator that reaches it.
|
||||
///
|
||||
/// A one-value delay keeps its comments in its own [`ExprKind::Paren`], which
|
||||
/// has had the two slots all along; this shape exists for the multi-value
|
||||
/// `#(rise, fall[, turn-off])` list, whose parentheses and commas the printer
|
||||
/// writes itself and which therefore has nowhere else to put them. The first
|
||||
/// value's `leading` is what stood just inside the `(`, and the last value's
|
||||
/// `trailing` is what stood just before the `)`.
|
||||
#[derive(Debug)]
|
||||
pub struct DelayValue {
|
||||
/// Comments between the `(` or the `,` before this value and the value.
|
||||
pub leading: Vec<Comment>,
|
||||
pub expr: Expr,
|
||||
/// Comments between the value and the `,` or `)` that follows it.
|
||||
pub trailing: Vec<Comment>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -377,6 +409,9 @@ pub struct GateInstance {
|
||||
pub name: Option<String>,
|
||||
/// Byte range of `name`.
|
||||
pub name_span: Option<TextRange>,
|
||||
/// Comments written between the instance name and the `(` of its
|
||||
/// terminal list.
|
||||
pub before_args: Vec<Comment>,
|
||||
pub args: Vec<ExprItem>,
|
||||
/// Code extent of the gate instance.
|
||||
pub span: TextRange,
|
||||
|
||||
@@ -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 })
|
||||
}
|
||||
@@ -249,12 +260,7 @@ impl<'a> Parser<'a> {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let delay = if net.is_some() && self.cur().is_sym("#") {
|
||||
self.bump();
|
||||
Some(self.parse_delay_value()?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let before = self.parse_net_delay(net.is_some(), false)?;
|
||||
// A declaration reaches here with its `virtual` already in
|
||||
// `qualifiers`, so `parse_opt_data_type`'s own modport branch cannot
|
||||
// fire: `virtual spi_if.tb tb_sif = sif.tb;`
|
||||
@@ -265,11 +271,39 @@ impl<'a> Parser<'a> {
|
||||
} else {
|
||||
self.parse_opt_data_type()?
|
||||
};
|
||||
// IEEE 1800 §6.7 writes the delay *here*, after the data type
|
||||
// (`wire [31:0] #0.1 x = y;`, `pulp_riscv_dbg/tb/unused/SimDTM.sv:38`);
|
||||
// everything else in the corpus writes it before. Either is read and
|
||||
// printed back where it stood, but a declaration with one on each
|
||||
// side is not a shape the LRM has.
|
||||
let after = self.parse_net_delay(net.is_some(), true)?;
|
||||
let delay = match (before, after) {
|
||||
(Some(_), Some(_)) => {
|
||||
return self.error("a net delay is written before or after the type, not both")
|
||||
}
|
||||
(before, after) => before.or(after),
|
||||
};
|
||||
let declarators = self.parse_declarators()?;
|
||||
self.expect_sym(";")?;
|
||||
Ok(DataDecl { net, delay, qualifiers, ty, declarators })
|
||||
}
|
||||
|
||||
/// The net delay at the cursor, if one is written there: `#5`, `#0.1`,
|
||||
/// `#(1:2:3)`. Only a net declaration may carry one, so `is_net` gates
|
||||
/// the whole read — a `#` anywhere else belongs to whoever comes next.
|
||||
fn parse_net_delay(&mut self, is_net: bool, after_type: bool) -> PResult<Option<NetDelay>> {
|
||||
if !is_net || !self.cur().is_sym("#") {
|
||||
return Ok(None);
|
||||
}
|
||||
// The `#` is written, so the gap in front of it is the delay's own:
|
||||
// `wire /* c */ #5 w;`. Taken only here — when the read does not
|
||||
// happen the gap belongs to whatever comes next.
|
||||
let before_hash = self.take_gap();
|
||||
self.bump();
|
||||
let after_hash = self.take_gap();
|
||||
Ok(Some(NetDelay { before_hash, after_hash, expr: self.parse_delay_value()?, after_type }))
|
||||
}
|
||||
|
||||
pub(super) fn parse_port_decl(&mut self) -> PResult<PortDecl> {
|
||||
let dir = self.bump().text;
|
||||
let net = {
|
||||
@@ -451,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()?)));
|
||||
}
|
||||
|
||||
@@ -21,9 +21,17 @@ impl<'a> Parser<'a> {
|
||||
pub(super) fn parse_cont_assign(&mut self) -> PResult<ContAssign> {
|
||||
self.expect_kw("assign")?;
|
||||
let strength = self.parse_opt_drive_strength()?;
|
||||
let mut after_hash = Vec::new();
|
||||
let mut after_delay = Vec::new();
|
||||
let delay = if self.cur().is_sym("#") {
|
||||
self.bump();
|
||||
Some(self.parse_delay_value()?)
|
||||
after_hash = self.take_gap();
|
||||
let delay = self.parse_delay_value()?;
|
||||
// The gap between the delay and the first left-hand side is the
|
||||
// delay's, not the pair's: a pair's leading comments print right
|
||||
// after the `assign`, which is in front of the delay.
|
||||
after_delay = self.take_gap();
|
||||
Some(delay)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -55,7 +63,7 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
self.expect_sym(";")?;
|
||||
Ok(ContAssign { strength, delay, assigns })
|
||||
Ok(ContAssign { strength, after_hash, delay, after_delay, assigns })
|
||||
}
|
||||
|
||||
/// The optional `( strength0 , strength1 )` of a continuous assignment
|
||||
@@ -94,46 +102,75 @@ impl<'a> Parser<'a> {
|
||||
/// spelling has always produced, so `#(5)` and `#(1:2:3)` still print
|
||||
/// exactly as written; only a real comma list yields more than one
|
||||
/// element.
|
||||
fn parse_delay_values(&mut self) -> PResult<Vec<Expr>> {
|
||||
fn parse_delay_values(&mut self) -> PResult<Vec<DelayValue>> {
|
||||
if !self.cur().is_sym("(") {
|
||||
return Ok(vec![self.parse_primary()?]);
|
||||
let expr = self.parse_primary()?;
|
||||
return Ok(vec![DelayValue { leading: Vec::new(), expr, trailing: Vec::new() }]);
|
||||
}
|
||||
let start = self.here();
|
||||
self.bump(); // (
|
||||
let mut out = Vec::new();
|
||||
// What is written just inside the `(` belongs to the first value; the
|
||||
// gap before each `,` and the gap after it belong to the values either
|
||||
// side of it.
|
||||
self.bump();
|
||||
let mut leading = self.take_gap();
|
||||
let mut out: Vec<DelayValue> = Vec::new();
|
||||
loop {
|
||||
let inner_start = self.here();
|
||||
let first = self.parse_expr()?;
|
||||
out.push(if self.eat_sym(":") {
|
||||
let typ = self.parse_expr()?;
|
||||
self.expect_sym(":")?;
|
||||
let max = self.parse_expr()?;
|
||||
self.expr_at(
|
||||
inner_start,
|
||||
ExprKind::MinTypMax {
|
||||
min: Box::new(first),
|
||||
typ: Box::new(typ),
|
||||
max: Box::new(max),
|
||||
},
|
||||
)
|
||||
} else {
|
||||
first
|
||||
});
|
||||
let expr = self.parse_min_typ_max_tail(inner_start, first)?;
|
||||
let trailing = self.gap_before(",");
|
||||
out.push(DelayValue { leading: std::mem::take(&mut leading), expr, trailing });
|
||||
if !self.eat_sym(",") {
|
||||
break;
|
||||
}
|
||||
leading = self.take_gap();
|
||||
}
|
||||
if let Some(last) = out.last_mut() {
|
||||
last.trailing = self.gap_before(")");
|
||||
}
|
||||
self.expect_sym(")")?;
|
||||
if out.len() == 1 {
|
||||
let inner = out.remove(0);
|
||||
return Ok(vec![self.expr_at(
|
||||
// One value keeps the `( )` node the one-value spelling has always
|
||||
// produced, and its two comment slots are where the paren gaps go.
|
||||
let DelayValue { leading, expr, trailing } = out.remove(0);
|
||||
let paren = self.expr_at(
|
||||
start,
|
||||
ExprKind::Paren { inner: Box::new(inner), before: Vec::new(), after: Vec::new() },
|
||||
)]);
|
||||
ExprKind::Paren { inner: Box::new(expr), before: leading, after: trailing },
|
||||
);
|
||||
return Ok(vec![DelayValue { leading: Vec::new(), expr: paren, trailing: Vec::new() }]);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The `: typ : max` tail of a `min : typ : max` expression, or `min`
|
||||
/// unchanged when no `:` follows it.
|
||||
///
|
||||
/// One grammar for the two places that write it — a delay list and a
|
||||
/// parenthesized expression — so the four comment slots around the two
|
||||
/// colons exist in both.
|
||||
pub(super) fn parse_min_typ_max_tail(&mut self, start: u32, min: Expr) -> PResult<Expr> {
|
||||
let before_typ = self.gap_before(":");
|
||||
if !self.eat_sym(":") {
|
||||
return Ok(min);
|
||||
}
|
||||
let mut comments = MinTypMaxComments { before_typ, ..Default::default() };
|
||||
comments.after_typ = self.take_gap();
|
||||
let typ = self.parse_expr()?;
|
||||
comments.before_max = self.gap_before(":");
|
||||
self.expect_sym(":")?;
|
||||
comments.after_max = self.take_gap();
|
||||
let max = self.parse_expr()?;
|
||||
Ok(self.expr_at(
|
||||
start,
|
||||
ExprKind::MinTypMax {
|
||||
min: Box::new(min),
|
||||
typ: Box::new(typ),
|
||||
max: Box::new(max),
|
||||
comments: Box::new(comments),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// The single delay value a net declaration or a continuous assignment
|
||||
/// takes. The multi-value list is a gate-instantiation spelling only —
|
||||
/// see [`Parser::parse_delay_values`].
|
||||
@@ -142,7 +179,9 @@ impl<'a> Parser<'a> {
|
||||
if values.len() > 1 {
|
||||
return self.error("a multi-value delay list is only allowed on a gate instantiation");
|
||||
}
|
||||
Ok(values.remove(0))
|
||||
// A lone value carries no comments of its own: `parse_delay_values`
|
||||
// folded the paren gaps into its `ExprKind::Paren`.
|
||||
Ok(values.remove(0).expr)
|
||||
}
|
||||
|
||||
/// True when the cursor opens a `bind` directive (IEEE 1800 §23.11).
|
||||
@@ -647,8 +686,11 @@ impl<'a> Parser<'a> {
|
||||
// instance's argument list would, and only a strength keyword after
|
||||
// the `(` tells the two apart.
|
||||
let strength = self.parse_opt_drive_strength()?;
|
||||
let before_hash = self.take_before_open("#");
|
||||
let mut after_hash = Vec::new();
|
||||
let delay = if self.cur().is_sym("#") {
|
||||
self.bump();
|
||||
after_hash = self.take_gap();
|
||||
self.parse_delay_values()?
|
||||
} else {
|
||||
Vec::new()
|
||||
@@ -660,6 +702,7 @@ impl<'a> Parser<'a> {
|
||||
let name =
|
||||
if self.cur().kind == TokenKind::Ident { Some(self.expect_name()?) } else { None };
|
||||
let (name, name_span) = split_label(name);
|
||||
let before_args = self.take_before_open("(");
|
||||
self.expect_sym("(")?;
|
||||
let mut args = Vec::new();
|
||||
if !self.cur().is_sym(")") {
|
||||
@@ -673,12 +716,21 @@ impl<'a> Parser<'a> {
|
||||
if more {
|
||||
meta.trailing = self.take_trailing();
|
||||
}
|
||||
instances.push(GateInstance { meta, name, name_span, args, span });
|
||||
instances.push(GateInstance { meta, name, name_span, before_args, args, span });
|
||||
if !more {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let before_semi = self.gap_before(";");
|
||||
self.expect_sym(";")?;
|
||||
Ok(GateInstantiation { gate, strength, delay, instances })
|
||||
Ok(GateInstantiation {
|
||||
gate,
|
||||
strength,
|
||||
before_hash,
|
||||
after_hash,
|
||||
delay,
|
||||
instances,
|
||||
before_semi,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! belong only to them: parameter ports, ports (ANSI and non-ANSI),
|
||||
//! modports and clocking blocks.
|
||||
|
||||
use super::split::UnitHead;
|
||||
use super::*;
|
||||
|
||||
/// The three pieces a `#( parameter ... )` port list yields, so module and
|
||||
@@ -21,6 +22,7 @@ impl<'a> Parser<'a> {
|
||||
/// one header grammar (IEEE 1800 §23.2.1, §25.3) and one body item list —
|
||||
/// only the closing keyword differs, so `end_kw` is the whole difference.
|
||||
pub(super) fn parse_module(&mut self, end_kw: &str) -> PResult<Module> {
|
||||
let conds = self.open_conds;
|
||||
let kw = self.bump().text;
|
||||
let before_name = self.take_gap();
|
||||
let Name { text: name, span: name_span } = self.expect_name()?;
|
||||
@@ -47,8 +49,18 @@ impl<'a> Parser<'a> {
|
||||
// behind it is what the module is for.
|
||||
self.expect_after_recovery(";", self.recovered_since(mark))?;
|
||||
let mut items = Vec::new();
|
||||
let mut head = UnitHead { kw: &kw, name: &name, conds, floor: conds };
|
||||
while !self.at_body_end(end_kw) {
|
||||
// Two rival headers written across the arms of one `ifdef region
|
||||
// are bracket-balanced, so nothing else in the grammar objects
|
||||
// until this unit runs out of file looking for its `end` keyword.
|
||||
// Failing here instead routes the whole unit into the split
|
||||
// recovery; see `docs/features/parser-skips/README.md`.
|
||||
if self.at_rival_header(&head) {
|
||||
return self.error(format!("rival header for `{name}` in a conditional region"));
|
||||
}
|
||||
items.push(self.item_or_recover()?);
|
||||
head.floor = head.floor.min(self.open_conds);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_closer(end_kw)?;
|
||||
@@ -400,7 +412,7 @@ impl<'a> Parser<'a> {
|
||||
meta,
|
||||
kw,
|
||||
after_kw,
|
||||
ty: DataType::default(),
|
||||
ty: self.implicit_type(),
|
||||
is_type: true,
|
||||
before_name,
|
||||
name,
|
||||
@@ -612,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() })
|
||||
}
|
||||
}
|
||||
@@ -97,21 +97,7 @@ impl<'a> Parser<'a> {
|
||||
let mark = self.pending_trailing.len();
|
||||
let inner_start = self.here();
|
||||
let inner = self.parse_expr()?;
|
||||
let inner = if self.eat_sym(":") {
|
||||
let typ = self.parse_expr()?;
|
||||
self.expect_sym(":")?;
|
||||
let max = self.parse_expr()?;
|
||||
self.expr_at(
|
||||
inner_start,
|
||||
ExprKind::MinTypMax {
|
||||
min: Box::new(inner),
|
||||
typ: Box::new(typ),
|
||||
max: Box::new(max),
|
||||
},
|
||||
)
|
||||
} else {
|
||||
inner
|
||||
};
|
||||
let inner = self.parse_min_typ_max_tail(inner_start, inner)?;
|
||||
let after = self.take_around(mark);
|
||||
self.expect_sym(")")?;
|
||||
Ok(self.expr_at(
|
||||
@@ -454,8 +440,18 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
|
||||
/// In parameter connections a value may be a type (`.T(logic [7:0])`).
|
||||
///
|
||||
/// An **anonymous aggregate** is a type too — `.T(struct packed { logic a;
|
||||
/// })`, the override a `parameter type` defaulting to one takes (IEEE 1800
|
||||
/// §6.19, §7.2). `parse_type_ref` has read that body since the first day;
|
||||
/// only this door was closed, because `struct`/`union`/`enum` are not in
|
||||
/// [`TYPE_KEYWORDS`] and so fell through to `parse_expr`, whose keyword arm
|
||||
/// answers "unexpected keyword `struct` in expression".
|
||||
pub(super) fn parse_expr_or_type(&mut self) -> PResult<Expr> {
|
||||
let t = self.cur();
|
||||
if t.is_kw("struct") || t.is_kw("union") || t.is_kw("enum") {
|
||||
return self.parse_type_expr();
|
||||
}
|
||||
if t.kind == TokenKind::Keyword
|
||||
&& TYPE_KEYWORDS.contains(&t.text.as_str())
|
||||
&& !self.nth(1).is_sym("'")
|
||||
|
||||
@@ -10,8 +10,10 @@
|
||||
//! The recovery is deliberately hard to reach. It fires only after a real
|
||||
//! parse failure, and only when that failure is the grammar refusing a
|
||||
//! `else / `elsif / `endif that closes a region which is genuinely open
|
||||
//! and which the failed item did not open, with a bracket the arm left
|
||||
//! open. Everything else — a plain syntax error that merely sits near a
|
||||
//! and which the failed item did not open — with a bracket the arm left
|
||||
//! open, or with the arm behind the directive re-writing the very header
|
||||
//! the failed item began with (`docs/features/parser-skips/README.md`).
|
||||
//! Everything else — a plain syntax error that merely sits near a
|
||||
//! directive, a garbage token run with directives in it, an unterminated
|
||||
//! region, a stray closer with nothing open — still refuses.
|
||||
//! See `docs/features/directive-split/README.md`.
|
||||
@@ -106,7 +108,92 @@ fn construct_end(head: &[Token]) -> ConstructEnd {
|
||||
ConstructEnd::Unknown
|
||||
}
|
||||
|
||||
/// The unit whose body a loop is reading, as [`Parser::at_rival_header`]
|
||||
/// needs it.
|
||||
pub(super) struct UnitHead<'h> {
|
||||
/// The unit's keyword, as written: `module`, `macromodule`, `interface`
|
||||
/// or `program`.
|
||||
pub(super) kw: &'h str,
|
||||
/// The unit's name.
|
||||
pub(super) name: &'h str,
|
||||
/// Item-scope conditional regions open at the unit's own first token.
|
||||
pub(super) conds: u32,
|
||||
/// The lowest item-scope nesting the body has reached since it started.
|
||||
/// Below `conds` means the region that stood open at the header was
|
||||
/// closed inside the body, so a directive at the cursor continues some
|
||||
/// later region rather than that one.
|
||||
pub(super) floor: u32,
|
||||
}
|
||||
|
||||
/// The keyword that closes a unit, given its opening keyword — or `None` for
|
||||
/// a keyword that opens no unit. `interface class` is a class and closes with
|
||||
/// `endclass`; the caller rules it out by requiring a name after the keyword.
|
||||
fn unit_end_kw(t: &Token) -> Option<&'static str> {
|
||||
if t.kind != TokenKind::Keyword {
|
||||
return None;
|
||||
}
|
||||
match t.text.as_str() {
|
||||
"module" | "macromodule" => Some("endmodule"),
|
||||
"interface" => Some("endinterface"),
|
||||
"program" => Some("endprogram"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `t` opens a unit that `close` ends. Its own test, so a unit
|
||||
/// *nested* in a captured body cannot end the extent scan on its closer.
|
||||
fn opens_unit(t: &Token, close: &str) -> bool {
|
||||
unit_end_kw(t) == Some(close)
|
||||
}
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
/// True when the cursor stands on the `` `else `` / `` `elsif `` of a
|
||||
/// region opened *before* `head` was written, and the arm behind it
|
||||
/// re-writes `head`'s own keyword and name.
|
||||
///
|
||||
/// That is one header written twice across the arms of a region — the
|
||||
/// `jtag_if.sv` shape — not a unit nested inside another one. Both
|
||||
/// spellings are bracket-balanced, so nothing fails until the outer unit
|
||||
/// reaches EOF looking for its closer; the body loop asks this before
|
||||
/// each item instead, and fails where the evidence is.
|
||||
/// See `docs/features/parser-skips/README.md`.
|
||||
pub(super) fn at_rival_header(&self, head: &UnitHead) -> bool {
|
||||
if !continues_conditional(self.cur()) {
|
||||
return false;
|
||||
}
|
||||
// A region must have been open at the header, must still be the live
|
||||
// one (nothing opened since is still open) and must never have been
|
||||
// closed inside the body.
|
||||
if head.conds == 0 || self.open_conds != head.conds || head.floor != head.conds {
|
||||
return false;
|
||||
}
|
||||
self.nth(1).is_kw(head.kw)
|
||||
&& self.nth(2).kind == TokenKind::Ident
|
||||
&& self.nth(2).text == head.name
|
||||
}
|
||||
|
||||
/// The closing keyword of the unit a rival header opened, or `None` when
|
||||
/// the item that failed at `mark` is not one.
|
||||
///
|
||||
/// The mirror of [`Parser::at_rival_header`], read from the tokens rather
|
||||
/// than from a flag on the error: [`ParseError`] is public and carries
|
||||
/// only a message and a position, and every other condition of this
|
||||
/// trigger is already read from the mark and the cursor — so all of the
|
||||
/// evidence stays in one place and no error path can set the flag by
|
||||
/// accident.
|
||||
fn rival_end_kw(&self, mark: &ItemMark) -> Option<&'static str> {
|
||||
let head = self.tokens.get(mark.pos)?;
|
||||
let end = unit_end_kw(head)?;
|
||||
let name = self.tokens.get(mark.pos + 1)?;
|
||||
if name.kind != TokenKind::Ident {
|
||||
return None;
|
||||
}
|
||||
let rival = self.nth(1).is_kw(&head.text)
|
||||
&& self.nth(2).kind == TokenKind::Ident
|
||||
&& self.nth(2).text == name.text;
|
||||
rival.then_some(end)
|
||||
}
|
||||
|
||||
/// Count the conditional-compilation directive standing at the cursor,
|
||||
/// which the caller is about to consume as an `ItemKind::Directive`.
|
||||
///
|
||||
@@ -150,7 +237,9 @@ impl<'a> Parser<'a> {
|
||||
err: ParseError,
|
||||
) -> PResult<ItemKind> {
|
||||
if self.at_split_conditional(mark) {
|
||||
if let Some((end_pos, conds_after)) = self.scan_split_extent(mark) {
|
||||
if let Some((end_pos, conds_after)) =
|
||||
self.scan_split_extent(mark, self.rival_end_kw(mark))
|
||||
{
|
||||
// The block swallowed the region's own `else / `endif, which
|
||||
// *are* item-scope nesting even though they now sit inside
|
||||
// opaque bytes. The extent scan already worked out what they
|
||||
@@ -202,9 +291,12 @@ impl<'a> Parser<'a> {
|
||||
/// and ends nothing: it is broken input, and the parse error stands;
|
||||
/// 3. the item's own conditional nesting is back to zero there, so the
|
||||
/// live region is one opened *before* the item rather than by it;
|
||||
/// 4. the arm left a bracket open, i.e. it is structurally a fragment.
|
||||
/// A missing `;` leaves nothing open and is indistinguishable from a
|
||||
/// typo, so it is refused.
|
||||
/// 4. the arm is structurally a fragment. Two spellings qualify: it left
|
||||
/// a bracket open (`(`, `[` or `{` unmatched), or it is a **unit
|
||||
/// header the next arm writes again** ([`Parser::rival_end_kw`]) — a
|
||||
/// header written twice is as much a fragment as an unclosed bracket,
|
||||
/// and it is the only bracket-balanced shape allowed in. A missing `;`
|
||||
/// leaves neither, is indistinguishable from a typo, and is refused.
|
||||
fn at_split_conditional(&self, mark: &ItemMark) -> bool {
|
||||
let at = self.cur();
|
||||
if !continues_conditional(at) && !closes_conditional(at) {
|
||||
@@ -228,7 +320,7 @@ impl<'a> Parser<'a> {
|
||||
brackets -= 1;
|
||||
}
|
||||
}
|
||||
cond == 0 && brackets > 0
|
||||
cond == 0 && (brackets > 0 || self.rival_end_kw(mark).is_some())
|
||||
}
|
||||
|
||||
/// One past the last token of the construct the split region belongs to,
|
||||
@@ -248,13 +340,25 @@ impl<'a> Parser<'a> {
|
||||
/// no region live is a stray closer, not a split, and gives up — the same
|
||||
/// refusal the trigger makes, repeated here because the scan walks past
|
||||
/// the point the trigger looked at.
|
||||
fn scan_split_extent(&self, mark: &ItemMark) -> Option<(usize, u32)> {
|
||||
///
|
||||
/// `unit_end` is `Some(closing keyword)` for a rival unit header, whose
|
||||
/// `;` closes only its *header*: the block is the whole unit, so the scan
|
||||
/// runs to the matching `endmodule` / `endinterface` / `endprogram`
|
||||
/// instead — counting units of the same kind on the way, so one nested in
|
||||
/// the body cannot end it early. (An `interface class` nested in a
|
||||
/// captured `interface` closes with `endclass`, leaves the count above
|
||||
/// zero and makes the scan give up: the parse error stands, which is the
|
||||
/// safe side.)
|
||||
fn scan_split_extent(&self, mark: &ItemMark, unit_end: Option<&str>) -> Option<(usize, u32)> {
|
||||
// Regions this scan opened, and regions that were already open when
|
||||
// it started. A directive at scan level zero belongs to the latter.
|
||||
let mut cond = 0i32;
|
||||
let mut live = mark.conds;
|
||||
let mut closed_outer = false;
|
||||
let mut brackets = 0i32;
|
||||
// Units of the head's kind open at `i`, counted only in `unit_end`
|
||||
// mode. The head at `mark.pos` is itself the first one.
|
||||
let mut units = 0i32;
|
||||
let mut i = mark.pos;
|
||||
while let Some(t) = self.tokens.get(i) {
|
||||
if t.kind == TokenKind::Eof {
|
||||
@@ -283,6 +387,15 @@ impl<'a> Parser<'a> {
|
||||
if brackets < 0 {
|
||||
return None;
|
||||
}
|
||||
} else if let Some(close) = unit_end {
|
||||
if opens_unit(t, close) {
|
||||
units += 1;
|
||||
} else if t.is_kw(close) {
|
||||
units -= 1;
|
||||
if units == 0 && cond == 0 && closed_outer {
|
||||
return Some((self.past_end_label(i + 1), live));
|
||||
}
|
||||
}
|
||||
} else if t.is_sym(";") && brackets == 0 && cond == 0 && closed_outer {
|
||||
return Some((i + 1, live));
|
||||
}
|
||||
|
||||
@@ -290,3 +290,58 @@ fn a_struct_member_may_be_declared_rand() {
|
||||
assert!(s.members[2].qualifiers.is_empty());
|
||||
assert_eq!(s.members[0].declarators[0].name, "cpol");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Net delays on either side of the data type (TODO §38.2,
|
||||
// `docs/features/parser-skips/README.md`)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The net delay of a single-declaration module, with the side of the data
|
||||
/// type it was written on.
|
||||
fn net_delay_of(src: &str) -> (String, bool) {
|
||||
let f = parse_ok(src);
|
||||
let d = match &module_of(&f).items[0].kind {
|
||||
ItemKind::DataDecl(d) => d,
|
||||
_ => panic!("expected a declaration"),
|
||||
};
|
||||
let delay = d.delay.as_ref().expect("a net delay");
|
||||
(src[delay.expr.span.as_range()].to_string(), delay.after_type)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_net_delay_is_read_on_either_side_of_the_data_type() {
|
||||
// Before the type is what the corpus writes; after it is where IEEE
|
||||
// 1800 §6.7 puts `delay3`, and where
|
||||
// `pulp_riscv_dbg/tb/unused/SimDTM.sv:38` writes it.
|
||||
assert_eq!(net_delay_of("module m;\n wire #5 w;\nendmodule\n"), ("5".into(), false));
|
||||
assert_eq!(
|
||||
net_delay_of("module m;\n wire [31:0] #0.1 x = y;\nendmodule\n"),
|
||||
("0.1".into(), true)
|
||||
);
|
||||
// After a plain `logic`-typed net, and after a signed keyword run.
|
||||
assert_eq!(net_delay_of("module m;\n wire logic #3 a;\nendmodule\n"), ("3".into(), true));
|
||||
assert_eq!(
|
||||
net_delay_of("module m;\n wire signed [7:0] #(1:2:3) b;\nendmodule\n"),
|
||||
("(1:2:3)".into(), true)
|
||||
);
|
||||
// The before position is unmoved by any of it.
|
||||
assert_eq!(
|
||||
net_delay_of("module m;\n wire #(1:2:3) signed [7:0] c;\nendmodule\n"),
|
||||
("(1:2:3)".into(), false)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_net_delay_written_on_both_sides_is_an_error() {
|
||||
let msg = parse_err("module m;\n wire #5 [31:0] #6 x;\nendmodule\n");
|
||||
assert!(msg.contains("before or after the type, not both"), "{msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_net_declaration_reads_a_delay() {
|
||||
// A variable has no `delay3`, so the `#` is not swallowed here — it is
|
||||
// an ordinary syntax error, exactly as it was before either position
|
||||
// was accepted.
|
||||
assert!(parse_err("module m;\n logic #5 x;\nendmodule\n").contains("expected"));
|
||||
assert!(parse_err("module m;\n logic [7:0] #5 x;\nendmodule\n").contains("expected"));
|
||||
}
|
||||
@@ -190,7 +190,7 @@ fn a_gate_takes_a_multi_value_delay_list() {
|
||||
// The one-value parenthesized spelling keeps its `Paren` node, which
|
||||
// is what makes `#(5)` print back as `#(5)` and not as `#5`.
|
||||
let ItemKind::GateInstantiation(g) = &m.items[2].kind else { panic!("expected a gate") };
|
||||
assert!(matches!(g.delay[0].kind, ExprKind::Paren { .. }));
|
||||
assert!(matches!(g.delay[0].expr.kind, ExprKind::Paren { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -218,3 +218,41 @@ fn a_bind_instance_may_be_a_hierarchical_path() {
|
||||
let ItemKind::Bind(b) = &f.items[0].kind else { panic!("expected a bind") };
|
||||
assert_eq!(b.instances.iter().map(|i| i.text.as_str()).collect::<Vec<_>>(), ["a.b", "plain"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inline_aggregate_is_a_parameter_override_argument() {
|
||||
// TODO §45.3: a `parameter type` defaulting to an anonymous aggregate is
|
||||
// overridden with one, and `parse_type_ref` has read that body all along —
|
||||
// only `parse_expr_or_type`'s door was shut (`struct`/`union`/`enum` are
|
||||
// not `TYPE_KEYWORDS`), so the value read as an expression and failed.
|
||||
for src in [
|
||||
"module m;\n sub #(.T(struct packed { logic a; })) u ();\nendmodule\n",
|
||||
"module m;\n sub #(.T(union packed { logic [7:0] a; })) u ();\nendmodule\n",
|
||||
"module m;\n sub #(.T(enum logic [1:0] {A, B})) u ();\nendmodule\n",
|
||||
"module m;\n sub #(.T(struct packed { /* why */ logic a; })) u ();\nendmodule\n",
|
||||
] {
|
||||
let f = parse_ok(src);
|
||||
let ItemKind::Instantiation(i) = &module_of(&f).items[0].kind else {
|
||||
panic!("expected an instantiation")
|
||||
};
|
||||
let params = i.params.as_ref().expect("an override list");
|
||||
let value = oks(params)[0].expr.as_ref().expect("a value");
|
||||
assert!(matches!(value.kind, ExprKind::Type(_)), "{src:?} read as {:?}", value.kind);
|
||||
// Strict and tolerant must agree: the tolerant parser reports nothing
|
||||
// where the strict one succeeds.
|
||||
let (_, diags) = crate::parse_source_tolerant(src);
|
||||
assert!(diags.is_empty(), "{src:?} left {diags:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ordered_parameter_override_takes_an_inline_aggregate_too() {
|
||||
// The bare-expression arm of `parse_connection` shares `parse_expr_or_type`
|
||||
// with the named one, so both doors opened at once.
|
||||
let f = parse_ok("module m;\n sub #(struct packed { logic a; }) u ();\nendmodule\n");
|
||||
let ItemKind::Instantiation(i) = &module_of(&f).items[0].kind else {
|
||||
panic!("expected an instantiation")
|
||||
};
|
||||
let params = i.params.as_ref().expect("an override list");
|
||||
assert!(matches!(oks(params)[0].expr.as_ref().expect("a value").kind, ExprKind::Type(_)));
|
||||
}
|
||||
@@ -628,3 +628,158 @@ fn an_opening_split_that_is_the_last_item_does_not_eat_the_closing_keyword() {
|
||||
"a directive starting a statement list is pass-through, not a split"
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Rival unit headers written across the arms of one region
|
||||
// (`docs/features/parser-skips/README.md`)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The `jtag_if.sv` shape, in the four spellings that differ only in the
|
||||
/// header: `interface`/`module`, with and without `#( ... )`, with `()` and
|
||||
/// with a real port list. Every one of them is one verbatim item running
|
||||
/// from the first header to the unit's own closing keyword.
|
||||
#[test]
|
||||
fn rival_unit_headers_across_one_region_become_one_verbatim_item() {
|
||||
for (why, src, ends) in [
|
||||
(
|
||||
"interface, `#( ... ) ()` — hw/dv/sv/jtag_agent/jtag_if.sv:6",
|
||||
"`ifdef GATE_LEVEL\n interface jtag_if #(parameter int unsigned P = 41_664) \
|
||||
();\n`else\n interface jtag_if #(parameter int unsigned P = 20_000) \
|
||||
();\n`endif\n wire tck;\nendinterface\nparameter int AFTER = 1;\n",
|
||||
"endinterface",
|
||||
),
|
||||
(
|
||||
"interface, no parameter list",
|
||||
"`ifdef A\ninterface i ();\n`else\ninterface i ();\n`endif\n wire \
|
||||
tck;\nendinterface\nparameter int AFTER = 1;\n",
|
||||
"endinterface",
|
||||
),
|
||||
(
|
||||
"module, a real port list",
|
||||
"`ifdef A\nmodule m (input a, output b);\n`else\nmodule m (input a, output \
|
||||
b);\n`endif\n wire x;\nendmodule\nparameter int AFTER = 1;\n",
|
||||
"endmodule",
|
||||
),
|
||||
(
|
||||
"module, a closing label",
|
||||
"`ifdef A\nmodule m #(parameter int W = 1) ();\n`else\nmodule m #(parameter int W = \
|
||||
2) ();\n`endif\n wire x;\nendmodule : m\nparameter int AFTER = 1;\n",
|
||||
"endmodule : m",
|
||||
),
|
||||
] {
|
||||
let f = parse_ok(src);
|
||||
let kinds = split_items(&f);
|
||||
assert_eq!(kinds.len(), 3, "{why}: {kinds:?}");
|
||||
assert!(kinds[0].starts_with("directive:`ifdef"), "{why}: {kinds:?}");
|
||||
assert_eq!(kinds[2], "param", "{why}: the item after the unit was not swallowed");
|
||||
let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("{why}: expected verbatim") };
|
||||
assert_eq!(raw.text, src[raw.span.as_range()], "{why}");
|
||||
assert!(raw.text.ends_with(ends), "{why}: {:?}", raw.text);
|
||||
assert!(raw.text.contains("`else") && raw.text.contains("`endif"), "{why}: {:?}", raw.text);
|
||||
// The whole unit is inside the block, its body included.
|
||||
assert!(raw.text.contains("wire"), "{why}: {:?}", raw.text);
|
||||
assert_eq!(open_conds_after(src), 0, "{why}: the region's own `endif was accounted for");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rival_headers_produce_the_same_tree_in_both_modes() {
|
||||
let src = "`ifdef GATE_LEVEL\n interface jtag_if #(parameter int unsigned P = 41_664) \
|
||||
();\n`else\n interface jtag_if #(parameter int unsigned P = 20_000) \
|
||||
();\n`endif\n wire tck;\nendinterface\n";
|
||||
let strict = parse_ok(src);
|
||||
let toks = tokenize(src).expect("lex error");
|
||||
let (tolerant, diags) = parse_tolerant(toks, src);
|
||||
assert!(diags.is_empty(), "{diags:?}");
|
||||
assert_eq!(split_items(&strict), split_items(&tolerant));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_written_around_a_rival_header_are_kept() {
|
||||
// The real file writes a comment inside each arm and one before the
|
||||
// region; none of them may be dropped.
|
||||
let src = "// head\n`ifdef GATE_LEVEL // which\n // 24MHz for GLS\n interface jtag_if \
|
||||
();\n`else\n // 50MHz for DV\n interface jtag_if ();\n`endif\n // pins\n wire \
|
||||
tck;\nendinterface // done\n";
|
||||
let f = parse_ok(src);
|
||||
assert_eq!(texts(&f.items[0].meta.leading), ["// head"]);
|
||||
assert_eq!(f.items[0].meta.trailing.as_ref().expect("the `ifdef's comment").text, "// which");
|
||||
// The capture starts at the item's *first token*, so the comment written
|
||||
// in front of the header is the item's own leading comment — the same
|
||||
// place every other split puts it — and the rest are inside the block.
|
||||
assert_eq!(texts(&f.items[1].meta.leading), ["// 24MHz for GLS"]);
|
||||
let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") };
|
||||
for c in ["// 50MHz for DV", "// pins"] {
|
||||
assert!(raw.text.contains(c), "{c} was dropped from {:?}", raw.text);
|
||||
}
|
||||
assert!(!raw.text.contains("// done"), "the trailing comment was swallowed");
|
||||
assert_eq!(f.items[1].meta.trailing.as_ref().expect("the comment survived").text, "// done");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_unit_nested_in_a_captured_body_does_not_end_the_scan_early() {
|
||||
// The extent scan counts units of the head's kind, so the *inner*
|
||||
// `endmodule` cannot be mistaken for the rival unit's own.
|
||||
let src = "`ifdef A\nmodule m ();\n`else\nmodule m ();\n`endif\n module inner ();\n \
|
||||
endmodule\n wire x;\nendmodule\nparameter int AFTER = 1;\n";
|
||||
let f = parse_ok(src);
|
||||
let kinds = split_items(&f);
|
||||
assert_eq!(kinds.len(), 3, "{kinds:?}");
|
||||
let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") };
|
||||
assert!(raw.text.contains("module inner"), "{:?}", raw.text);
|
||||
assert!(raw.text.ends_with("endmodule"), "{:?}", raw.text);
|
||||
assert_eq!(kinds[2], "param", "{kinds:?}");
|
||||
}
|
||||
|
||||
// -- the three negatives ----------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_second_unit_in_an_arm_of_a_region_opened_inside_the_body_is_still_an_error() {
|
||||
// Two nested units, which is illegal: the region the `else belongs to
|
||||
// was opened *by the body*, not before the header, so the arm is not a
|
||||
// rival spelling of anything.
|
||||
let msg = parse_err(
|
||||
"`ifdef OUTER\nmodule m;\n`ifdef A\n wire a;\n`else\nmodule m;\n`endif\n wire \
|
||||
b;\nendmodule\n",
|
||||
);
|
||||
assert!(msg.contains("endmodule"), "{msg}");
|
||||
// The same shape with no region open at all around the outer unit.
|
||||
let msg = parse_err(
|
||||
"module m;\n`ifdef A\n wire a;\n`else\nmodule m;\n wire \
|
||||
b;\n`endif\nendmodule\n",
|
||||
);
|
||||
assert!(msg.contains("endmodule"), "{msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_different_name_after_the_else_is_not_a_rival_header() {
|
||||
let msg = parse_err(
|
||||
"`ifdef A\ninterface i ();\n`else\ninterface j ();\n`endif\n wire \
|
||||
x;\nendinterface\n",
|
||||
);
|
||||
assert!(msg.contains("endinterface"), "{msg}");
|
||||
// Nor is a different keyword for the same name.
|
||||
let msg = parse_err(
|
||||
"`ifdef A\ninterface i ();\n`else\nmodule i ();\n`endif\n wire x;\nendinterface\n",
|
||||
);
|
||||
assert!(msg.contains("endinterface"), "{msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_region_closed_before_the_header_leaves_the_else_stray() {
|
||||
// The region opened at the top of the file is closed before the
|
||||
// interface begins, so the `else below closes nothing: broken input,
|
||||
// and the parse error stands.
|
||||
let msg = parse_err(
|
||||
"`ifdef A\n wire a;\n`endif\ninterface i ();\n`else\n interface i ();\n`endif\n wire \
|
||||
x;\nendinterface\n",
|
||||
);
|
||||
assert!(msg.contains("endinterface"), "{msg}");
|
||||
// And a region closed *inside* the body before the `else: the header's
|
||||
// region is gone, so the live one is not the one it was written under.
|
||||
let msg = parse_err(
|
||||
"`ifdef OUTER\ninterface i ();\n`endif\n`ifdef B\n wire a;\n`else\n interface i \
|
||||
();\n`endif\nendinterface\n",
|
||||
);
|
||||
assert!(msg.contains("endinterface"), "{msg}");
|
||||
}
|
||||
@@ -614,7 +614,7 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
|
||||
}
|
||||
ItemKind::GateInstantiation(g) => {
|
||||
for d in &g.delay {
|
||||
check_expr(src, d, here);
|
||||
check_expr(src, &d.expr, here);
|
||||
}
|
||||
for i in &g.instances {
|
||||
assert_inside(src, "gate instance", i.span, here);
|
||||
@@ -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),
|
||||
@@ -1227,7 +1229,7 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) {
|
||||
check_expr(src, lo, here);
|
||||
check_expr(src, hi, here);
|
||||
}
|
||||
ExprKind::MinTypMax { min, typ, max } => {
|
||||
ExprKind::MinTypMax { min, typ, max, .. } => {
|
||||
check_expr(src, min, here);
|
||||
check_expr(src, typ, here);
|
||||
check_expr(src, max, here);
|
||||
@@ -1669,3 +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('\\')
|
||||
}
|
||||
|
||||
@@ -353,19 +353,24 @@ fn params(module: &Module, text: &str) -> Vec<PlanParam> {
|
||||
|
||||
/// A parameter's default as an override list can write it, or nothing.
|
||||
///
|
||||
/// Two things disqualify one, and the corpus produced both from a single
|
||||
/// header (`common_cells/src/ecc_encode.sv`, a `parameter type` defaulting to
|
||||
/// an anonymous multi-line `struct packed`):
|
||||
/// Two things disqualify one:
|
||||
///
|
||||
/// * it is written across several lines — the source's own indentation means
|
||||
/// nothing inside a `#( ... )` on someone else's line, and re-flowing it
|
||||
/// would risk rewriting a string literal's spaces;
|
||||
/// * writing it back does not parse — lucisv's expression grammar does not
|
||||
/// accept an inline aggregate as a parameter override, and a skeleton that
|
||||
/// does not parse hands the user a red squiggle from our own server.
|
||||
/// * writing it back does not parse, which the probe below asks rather than
|
||||
/// guesses, because a skeleton that does not parse hands the user a red
|
||||
/// squiggle from our own server.
|
||||
///
|
||||
/// A default lucisv cannot write back is simply not offered: the tabstop comes
|
||||
/// up empty and the user types what they meant.
|
||||
///
|
||||
/// The probe is what makes this grow with the grammar. An **inline aggregate**
|
||||
/// default (`parameter type T = struct packed { logic a; }`) used to fail it —
|
||||
/// the override grammar refused a `struct` head — and was dropped; since
|
||||
/// TODO §45.3 the same probe passes and the type text is emitted. Only the
|
||||
/// multi-line spelling, which the corpus's `common_cells/src/ecc_encode.sv`
|
||||
/// writes, is still refused, and by the first rule rather than the second.
|
||||
fn default_text(text: &str, param: &ParamPort) -> String {
|
||||
let Some(expr) = ¶m.default else { return String::new() };
|
||||
let written = slice(text, expr.span).trim();
|
||||
@@ -743,6 +748,38 @@ endmodule
|
||||
assert!(parse_source_tolerant(&probe).1.is_empty(), "the skeleton must parse: {skeleton}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_one_line_inline_aggregate_default_is_emitted() {
|
||||
// TODO §45.3: the override grammar accepts an inline aggregate, so the
|
||||
// probe in `default_text` passes and the type text is offered instead
|
||||
// of an empty tabstop. Only the multi-line spelling is still dropped,
|
||||
// by the "written across several lines" rule above it.
|
||||
let text = "\
|
||||
module agg #(
|
||||
parameter type packed_t = struct packed {logic parity; logic [7:0] word;},
|
||||
parameter type state_e = enum logic [1:0] {IDLE, BUSY}
|
||||
) ();
|
||||
endmodule
|
||||
";
|
||||
let plan = plan(text, "agg");
|
||||
assert_eq!(
|
||||
plan.params,
|
||||
vec![
|
||||
PlanParam {
|
||||
name: "packed_t".into(),
|
||||
default: "struct packed {logic parity; logic [7:0] word;}".into(),
|
||||
},
|
||||
PlanParam {
|
||||
name: "state_e".into(),
|
||||
default: "enum logic [1:0] {IDLE, BUSY}".into(),
|
||||
},
|
||||
]
|
||||
);
|
||||
let skeleton = plan.render(&Layout::default());
|
||||
let probe = format!("module p;\n{skeleton}\nendmodule\n");
|
||||
assert!(parse_source_tolerant(&probe).1.is_empty(), "the skeleton must parse: {skeleton}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_line_type_is_shown_on_one_line() {
|
||||
let text = "\
|
||||
|
||||
@@ -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(), scope);
|
||||
self.bind_declarators(&d.declarators, kind, &d.ty, span, scope);
|
||||
self.bind_opt_expr(d.delay.as_ref().map(|n| &n.expr), 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,8 +174,8 @@ 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::MinTypMax { min, typ, max } => {
|
||||
ExprKind::Type(ty) => self.bind_data_type(ty, scope),
|
||||
ExprKind::MinTypMax { min, typ, max, .. } => {
|
||||
self.bind_expr(min, scope);
|
||||
self.bind_expr(typ, scope);
|
||||
self.bind_expr(max, 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);
|
||||
@@ -108,7 +108,7 @@ impl<'a> Binder<'a> {
|
||||
ItemKind::Bind(b) => self.bind_bind(b, scope),
|
||||
ItemKind::GateInstantiation(g) => {
|
||||
for d in &g.delay {
|
||||
self.bind_expr(d, scope);
|
||||
self.bind_expr(&d.expr, scope);
|
||||
}
|
||||
for inst in &g.instances {
|
||||
if let (Some(name), Some(ns)) = (&inst.name, inst.name_span) {
|
||||
@@ -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;
|
||||
|
||||
|
||||
+22
-3
@@ -1,5 +1,24 @@
|
||||
# Verilog/SystemVerilog coverage gaps — ranked (2026-09-01)
|
||||
|
||||
**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.
|
||||
Use [repository-analysis.md](repository-analysis.md) and [topo.md](topo.md) for
|
||||
current implementation status. Original probe counts remain historical.
|
||||
|
||||
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:
|
||||
|
||||
@@ -149,8 +168,7 @@ signal named only inside a property edits it, references list it, and the
|
||||
"at least identifier occurrences" fallback the C1 row asked for was
|
||||
overtaken rather than built (what the grammar cannot read still rewinds to
|
||||
the byte-exact capture, and rename *names* those regions instead of going
|
||||
quiet). What the tables above still leave open, by weight: the second half of
|
||||
M12 (`--rules-doc`, §2.9-5); L3, L6, L9 and L10. M10's error recovery inside
|
||||
quiet). What the tables above still leave open, by weight: L3, L6, L9 and L10. M12's second half (`--rules-doc`, §2.9-5) was delivered by macro-word-census. M10's error recovery inside
|
||||
headers and lists is closed (TODO §32), with the narrowing recorded in its
|
||||
row: a truncated file reports *more* diagnostics than before, because the
|
||||
constructs that now survive say what closer they are missing. M13's small
|
||||
@@ -174,7 +192,8 @@ the generated truth.
|
||||
|
||||
Three coverage notes the wave produced, none of them a language gap:
|
||||
|
||||
- **`begin` where an item belongs is a parser gap, not a rule gap.** The
|
||||
- **Historical parser gap, closed in tolerant mode by v0.40.0:** `begin`
|
||||
where an item belongs. At the time of this addendum, the
|
||||
parser refuses a module-scope `begin … end` and a bare `begin` inside a
|
||||
`generate` region rather than recovering either as a block, so recovery
|
||||
unwinds and the rest of that unit is lost — `module-begin-block` and
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Loaded 100 of 169 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user