Add vfmt-server and linter-core (jointly: round 11)
vfmt-server (new crate, binary vfmt-server): LSP over stdio on
rust-analyzer's minimal stack (lsp-server/lsp-types/serde/serde_json,
exact-pinned, 18 packages audited incl. all build scripts). Ships
formatting (byte-identical to the CLI), tolerant-parse diagnostics
with UTF-16-correct positions (CRLF collapse pinned; EOF spans
widened to drawable lines), semanticTokens/full, hover with `define
expansion (file table -> workspace fallback), definition through
both resolution layers (Ambiguous -> all locations), references,
documentSymbol and capped workspace/symbol. Deferred capabilities
are not advertised. 860-file corpus session: 0.79s, 29.5MB. QA drove
a real stdio session: diagnostics clear on fix, staleness model
honored, malformed frames survived.
linter-core (new crate vlog_linter + vfmt check): ruff-style rules
with Safe/Unsafe fix applicability, inline waivers with unused-
waiver detection (Verible-spelling waivers for unimplemented rules
deliberately tolerated -- corpus-driven), seven seed rules, --fix /
--select / --ignore / --output-format json, frozen exit codes, bare
vfmt byte-identical to before (worktree-proven). Corpus baseline:
7806 violations in 93 files, deterministic. Lead-directed fix:
--fix never edits inside // vfmt: off fences (reported, not
auto-fixed), with a scan backstop for tolerant-parse trees where
fence::collect sees no regions.
Both dev agents were interrupted by a session limit mid-round and
resumed from transcripts; the workspace survived intact.
Dev: 2 Opus agents; QA: 2 Sonnet agents; reviews in
docs/features/{vfmt-server,linter-core}/README.md.
Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
1ac9746c45
commit
c8b936a741
42 files changed
+7399
-27
No files matched your search
Generated
+183
@@ -2,6 +2,21 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-channel"
|
||||
version = "0.5.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d85363c37faeca707aef026efa9f3b34d077bce547e48f770770625c6013679e"
|
||||
dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-deque"
|
||||
version = "0.8.7"
|
||||
@@ -33,6 +48,77 @@ version = "1.17.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d"
|
||||
|
||||
[[package]]
|
||||
name = "fluent-uri"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "17c704e9dbe1ddd863da1e6ff3567795087b1eb201ce80d8fa81162e1516500d"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.33"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
|
||||
|
||||
[[package]]
|
||||
name = "lsp-server"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ee25a31f2e571e426eef2896179450cafc7e2f5be00d8a93b1c2d21c0ff7656"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lsp-types"
|
||||
version = "0.97.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "53353550a17c04ac46c585feb189c2db82154fc84b79c7a66c96c2c644f66071"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"fluent-uri",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_repr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rayon"
|
||||
version = "1.12.0"
|
||||
@@ -53,15 +139,105 @@ dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.140"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"ryu",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_repr"
|
||||
version = "0.1.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vfmt"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
"vlog_formatter",
|
||||
"vlog_linter",
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vfmt_server"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
"vlog_semantic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.1.0"
|
||||
@@ -69,6 +245,13 @@ dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.1.0"
|
||||
|
||||
+20
-1
@@ -1,6 +1,13 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["crates/vlog_parser", "crates/vlog_semantic", "crates/vlog_formatter", "crates/vfmt"]
|
||||
members = [
|
||||
"crates/vlog_parser",
|
||||
"crates/vlog_semantic",
|
||||
"crates/vlog_formatter",
|
||||
"crates/vlog_linter",
|
||||
"crates/vfmt",
|
||||
"crates/vfmt_server",
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
@@ -14,5 +21,17 @@ license = "MIT"
|
||||
[workspace.dependencies]
|
||||
rayon = "=1.12.0"
|
||||
|
||||
# The LSP stack, sanctioned by TODO.md §6 ("`tower-lsp` or `lsp-server`"), used
|
||||
# by `vfmt_server` only. `lsp-server` is rust-analyzer's synchronous transport
|
||||
# (no async runtime); `lsp-types` is the protocol's data model, which is not
|
||||
# something to hand-roll. All pinned exactly for the same reason `rayon` is: a
|
||||
# wire protocol's Rust bindings change shape between minor releases. Transitive
|
||||
# count, build scripts and the versions considered are audited in
|
||||
# docs/features/vfmt-server/README.md.
|
||||
lsp-server = "=0.10.0"
|
||||
lsp-types = "=0.97.0"
|
||||
serde = "=1.0.229"
|
||||
serde_json = "=1.0.140"
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
@@ -1,14 +1,17 @@
|
||||
# vfmt — a Verilog/SystemVerilog formatter in Rust
|
||||
# vfmt — a Verilog/SystemVerilog formatter and linter in Rust
|
||||
|
||||
An opinionated, fast formatter for Verilog-2001 and SystemVerilog RTL, built
|
||||
in the image of [ruff](https://github.com/astral-sh/ruff)'s formatter, with
|
||||
layout conventions borrowed from
|
||||
[Verible](https://github.com/chipsalliance/verible)'s `verible-verilog-format`.
|
||||
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
|
||||
[Verible](https://github.com/chipsalliance/verible).
|
||||
|
||||
```bash
|
||||
# format files / directories in place (like `ruff format`)
|
||||
vfmt rtl/ tb/top_tb.sv
|
||||
|
||||
# lint (like `ruff check`); `vfmt format ...` is the explicit spelling of the above
|
||||
vfmt check rtl/
|
||||
|
||||
# check mode for CI (exit 1 if anything would change)
|
||||
vfmt --check rtl/
|
||||
|
||||
@@ -36,8 +39,8 @@ cat foo.sv | vfmt --stdin-filename rtl/foo.sv -
|
||||
|
||||
| Code | Meaning |
|
||||
|---|---|
|
||||
| 0 | Success: files were formatted, or `--check`/`--diff` found nothing to change |
|
||||
| 1 | `--check`/`--diff` only: at least one file would be reformatted (nothing written) |
|
||||
| 0 | Success: files were formatted, `--check`/`--diff` found nothing to change, or `check` found no violations |
|
||||
| 1 | `--check`/`--diff`: at least one file would be reformatted (nothing written). `check`: at least one violation was reported |
|
||||
| 2 | An error occurred (bad arguments, I/O, or a file that could not be formatted); every file involved in an error is left untouched |
|
||||
|
||||
An error outranks "would reformat": a run with both exits 2.
|
||||
@@ -99,6 +102,58 @@ supported subset (tables, multi-line arrays, 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
|
||||
|
||||
`vfmt check` runs a set of syntactic lint rules over the same files `vfmt`
|
||||
would format — same walk, same `--exclude`, same `.gitignore` handling, same
|
||||
`vfmt.toml` discovery.
|
||||
|
||||
```bash
|
||||
vfmt check rtl/ # FILE:LINE:COL: message [rule-name]
|
||||
vfmt check --output-format json rtl/ # one JSON array, for editors and CI
|
||||
vfmt check --select no-tabs rtl/ # only these rules (comma-separated)
|
||||
vfmt check --ignore module-filename rtl/ # everything but these
|
||||
vfmt check --fix rtl/ # apply the safe fixes, write files back
|
||||
```
|
||||
|
||||
Exit codes are the frozen contract above: 0 clean (or everything fixed), 1
|
||||
violations remain, 2 error. Unlike the formatter, `check` uses the
|
||||
error-tolerant parser, so a file vfmt cannot fully parse is still linted for
|
||||
what it can see.
|
||||
|
||||
| Rule | Fix | What it wants |
|
||||
|---|---|---|
|
||||
| `no-tabs` | safe | spaces, not tabs (a tab inside a string is left alone) |
|
||||
| `no-trailing-whitespace` | safe | nothing but code before the newline |
|
||||
| `case-missing-default` | — | every `case`/`casex`/`casez` has a `default` |
|
||||
| `always-ff-non-blocking` | — | `<=` inside `always_ff` |
|
||||
| `always-comb-blocking` | — | `=` inside `always_comb` |
|
||||
| `explicit-parameter-storage-type` | — | `parameter int W = 8`, not `parameter W = 8` |
|
||||
| `module-filename` | — | a one-module file is named after its module |
|
||||
| `unused-waiver` | — | waivers that suppress nothing |
|
||||
|
||||
Fixes follow ruff's applicability model: `--fix` applies *safe* fixes (those
|
||||
that cannot change what the code means), `--unsafe-fixes` widens that — no
|
||||
rule ships an unsafe fix yet. Violations inside a `// verilog_format: off`
|
||||
region are reported but never fixed: `off` means hands-off for the linter too,
|
||||
so `--fix` leaves every byte of a fenced region exactly as written.
|
||||
|
||||
### Waivers
|
||||
|
||||
```systemverilog
|
||||
wire a; // vfmt: waive no-tabs suppresses that rule on this line
|
||||
// vfmt: waive no-tabs alone on a line: suppresses the next line
|
||||
// vfmt: waive-start no-tabs ... and everything through
|
||||
// vfmt: waive-stop no-tabs ... this line
|
||||
```
|
||||
|
||||
`verilog_lint:` is accepted in place of `vfmt:`, so code annotated for Verible
|
||||
works unedited — including waivers naming Verible rules vfmt has not
|
||||
implemented, which are ignored rather than reported. A waiver of vfmt'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:
|
||||
`docs/features/linter-core/README.md`.
|
||||
|
||||
## Architecture (the ruff mapping)
|
||||
|
||||
The workspace mirrors ruff's crate layout — a comment-preserving parser, a
|
||||
@@ -109,7 +164,8 @@ generic pretty-printing IR, language formatting rules, and a thin CLI:
|
||||
| `crates/vlog_parser` | `ruff_python_parser` + `ruff_python_ast` | Hand-written lexer and recursive-descent parser producing a comment-preserving AST |
|
||||
| `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.rs` | `ruff_python_formatter` | Per-node formatting rules |
|
||||
| `crates/vfmt` | the `ruff` CLI | File discovery, in-place rewriting, `--check`, stdin mode |
|
||||
| `crates/vlog_linter` | `ruff_linter` | Rule registry, violations, fix applicability, waivers |
|
||||
| `crates/vfmt` | the `ruff` CLI | File discovery, in-place rewriting, `--check`, `check`, stdin mode |
|
||||
|
||||
Key ideas carried over from ruff/prettier:
|
||||
|
||||
|
||||
@@ -132,20 +132,38 @@ Verible's rule ergonomics (waivers, configurable rules).
|
||||
|
||||
- [ ] **[R] One parse, two tools.** `vfmt check` and `vfmt format` must
|
||||
share `vlog_parser` output in a single invocation (`vfmt check --fix
|
||||
--format` style workflows come free later).
|
||||
- [ ] **[V+R] Rule trait + registry.** Each rule: stable kebab-case name,
|
||||
--format` style workflows come free later). *Not done:* `vfmt check`
|
||||
re-parses today (tolerantly, which the formatter does not), and nothing in
|
||||
`vlog_linter`'s API prevents sharing a tree later — only `LintContext` would
|
||||
change.
|
||||
- [x] **[V+R] Rule trait + registry.** Each rule: stable kebab-case name,
|
||||
one-line summary, longer doc with style-guide rationale (Verible links
|
||||
each rule to a style-guide section — do the same), and a
|
||||
`check(node/token) -> Vec<Diagnostic>` over syntax tree or token stream.
|
||||
- [ ] **[V] Diagnostic format `FILE:LINE:COL: message [rule-name]`** plus
|
||||
→ `crates/vlog_linter`: `Rule` (name/summary/doc/check over a `LintContext`
|
||||
carrying tokens, the tolerant AST, the source and a `LineIndex`),
|
||||
`all_rules`/`default_rules`/`rule_by_name`/`select_rules`. Rules, waiver
|
||||
grammar and the corpus baseline in `docs/features/linter-core/README.md`.
|
||||
- [x] **[V] Diagnostic format `FILE:LINE:COL: message [rule-name]`** plus
|
||||
**[R]** `--output-format json` for tooling from the start.
|
||||
- [ ] **[R] Fix applicability model.** ruff distinguishes *safe* vs
|
||||
→ `vfmt check`; text sorted by file then position, JSON one array on stdout
|
||||
(hand-rolled, no new dependency) with location, end_location, range and fix.
|
||||
- [x] **[R] Fix applicability model.** ruff distinguishes *safe* vs
|
||||
*unsafe* fixes (`--fix` vs `--unsafe-fixes`). Adopt it now — retrofitting
|
||||
safety classification is painful.
|
||||
→ `Fix { edits, applicability: Safe | Unsafe }` and `--fix` /
|
||||
`--unsafe-fixes`. Only `no-tabs` and `no-trailing-whitespace` ship fixes
|
||||
(both Safe); the unsafe path is plumbed and tested but no rule uses it yet.
|
||||
- [ ] **[V] Waiver mechanisms:** inline `// vfmt: waive rule-name` (accept
|
||||
`verilog_lint: waive` for migration), `waive-start`/`waive-stop` ranges,
|
||||
and external waiver files (`waive --rule=X --line=N --location=glob`) for
|
||||
code you can't touch. ruff's lesson: also warn about *unused* waivers.
|
||||
- [x] inline `waive`, `waive-start`/`waive-stop`, both spellings, and the
|
||||
`unused-waiver` pseudo-rule (unused, unknown rule, malformed, unmatched
|
||||
`waive-stop`). A `verilog_lint:` waiver naming a rule vfmt lacks is
|
||||
ignored rather than reported, so Verible-annotated code lints unedited.
|
||||
- [ ] external waiver files — needs a file format, a discovery rule and a
|
||||
precedence story against inline waivers.
|
||||
- [ ] **[V] Configurable naming rules via regex** (module/instance/
|
||||
parameter/enum naming), with named presets like Verible's
|
||||
(snake_case, ALL_CAPS, etc.).
|
||||
@@ -156,6 +174,12 @@ Verible's rule ergonomics (waivers, configurable rules).
|
||||
no-tabs, no-trailing-spaces, explicit-parameter-storage-type,
|
||||
case-missing-default, always-ff-non-blocking / always-comb-blocking,
|
||||
forbid `wire`-reg mixups in SV files, module-filename match.
|
||||
- [x] `no-tabs`, `no-trailing-whitespace`,
|
||||
`explicit-parameter-storage-type`, `case-missing-default`,
|
||||
`always-ff-non-blocking`, `always-comb-blocking`, `module-filename` —
|
||||
corpus baseline per rule in `docs/features/linter-core/README.md`.
|
||||
- [ ] `wire`/`reg` mixups in SV files — needs to know which files are
|
||||
SystemVerilog, a decision the linter does not make yet.
|
||||
|
||||
## 5. Testing — adapt Verible's methodology
|
||||
|
||||
@@ -303,7 +327,7 @@ later:
|
||||
external rate from 19.6 % to 2.6 % of all references. Duplicate-name
|
||||
policy, `` `define`` lookup (no include graph → no resolution order) and
|
||||
the honest gaps in `docs/features/workspace-index/README.md`.
|
||||
- [ ] **New crate `vfmt_server`** (analog of `ruff_server`): LSP over
|
||||
- [x] **New crate `vfmt_server`** (analog of `ruff_server`): LSP over
|
||||
stdio via `tower-lsp` or `lsp-server`. Order of capabilities:
|
||||
1. `textDocument/formatting` + `rangeFormatting` (reuses §2 `--lines`),
|
||||
2. publish parse/lint diagnostics,
|
||||
@@ -312,6 +336,17 @@ later:
|
||||
(needs `vlog_semantic` + workspace index),
|
||||
5. document/workspace symbols; then completion, rename, signature
|
||||
help for instantiations.
|
||||
→ `crates/vfmt_server`, binary `vfmt-server`, on `lsp-server` +
|
||||
`lsp-types` (synchronous, no async runtime). **Shipped:**
|
||||
`textDocument/formatting`, parse diagnostics on didOpen/didChange/didSave,
|
||||
`semanticTokens/full`, `hover` (in-file and workspace `` `define``
|
||||
expansion, declaration snippets), `definition` (both resolution layers,
|
||||
all locations when ambiguous), `references` (in-file), `documentSymbol`
|
||||
and `workspace/symbol`. **Not shipped, deliberately:** `rangeFormatting`
|
||||
(waits on §2 `--lines`), lint diagnostics (waits on `vlog_linter`),
|
||||
cross-file references, completion/rename/signature help. Byte↔UTF-16
|
||||
position conversion, the state/staleness model and the dependency audit
|
||||
are in `docs/features/vfmt-server/README.md`.
|
||||
- [ ] **Editor packaging.** A minimal VS Code extension (launch the
|
||||
server, register file types) and a documented Vim/Neovim `lspconfig`
|
||||
snippet. No editor-specific features beyond launching.
|
||||
|
||||
@@ -12,4 +12,5 @@ path = "src/main.rs"
|
||||
[dependencies]
|
||||
vlog_parser = { path = "../vlog_parser" }
|
||||
vlog_formatter = { path = "../vlog_formatter" }
|
||||
vlog_linter = { path = "../vlog_linter" }
|
||||
rayon = { workspace = true }
|
||||
+145
-5
@@ -3,8 +3,33 @@
|
||||
use crate::config::FileConfig;
|
||||
use vlog_formatter::Config;
|
||||
|
||||
/// Which tool this invocation runs.
|
||||
///
|
||||
/// A bare `vfmt <paths>` is [`Command::Format`], exactly as before
|
||||
/// subcommands existed; the word is only read when it is the **first**
|
||||
/// argument, so `vfmt --check rtl/` and every other old command line means
|
||||
/// what it always did.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Command {
|
||||
/// `vfmt`, `vfmt format` — the formatter.
|
||||
Format,
|
||||
/// `vfmt check` — the linter.
|
||||
Check,
|
||||
}
|
||||
|
||||
/// How `vfmt check` renders its diagnostics.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum OutputFormat {
|
||||
/// `FILE:LINE:COL: message [rule-name]`, one per line.
|
||||
Text,
|
||||
/// One JSON array of diagnostic objects.
|
||||
Json,
|
||||
}
|
||||
|
||||
/// Everything the driver needs to know about one invocation.
|
||||
pub struct Options {
|
||||
/// Formatter or linter.
|
||||
pub command: Command,
|
||||
/// Don't write; report files that would be reformatted.
|
||||
pub check: bool,
|
||||
/// Don't write; print a unified diff of what would change.
|
||||
@@ -27,6 +52,16 @@ pub struct Options {
|
||||
pub line_length: Option<usize>,
|
||||
/// `--indent`, if given; otherwise the config file decides.
|
||||
pub indent: Option<usize>,
|
||||
/// `check` only: how diagnostics are rendered.
|
||||
pub output_format: OutputFormat,
|
||||
/// `check` only: apply safe fixes and write the files back.
|
||||
pub fix: bool,
|
||||
/// `check` only: let `--fix` apply unsafe fixes too.
|
||||
pub unsafe_fixes: bool,
|
||||
/// `check` only: run exactly these rules (empty means the default set).
|
||||
pub select: Vec<String>,
|
||||
/// `check` only: rules to drop from whatever `--select` left.
|
||||
pub ignore: Vec<String>,
|
||||
/// Files, directories, or the single input `-`.
|
||||
pub inputs: Vec<String>,
|
||||
}
|
||||
@@ -37,6 +72,11 @@ impl Options {
|
||||
self.check || self.diff
|
||||
}
|
||||
|
||||
/// True when the single input is `-`, i.e. the buffer comes from stdin.
|
||||
pub fn is_stdin(&self) -> bool {
|
||||
self.inputs.len() == 1 && self.inputs[0] == "-"
|
||||
}
|
||||
|
||||
/// Formatter settings for one file: CLI flag > config file > default.
|
||||
pub fn config_with(&self, file: &FileConfig) -> Config {
|
||||
let mut config = Config::default();
|
||||
@@ -66,12 +106,18 @@ impl Options {
|
||||
/// Prints the `--help` text, including the frozen exit-code contract.
|
||||
pub fn print_help() {
|
||||
println!(
|
||||
"vfmt — a Verilog/SystemVerilog formatter
|
||||
"vfmt — a Verilog/SystemVerilog formatter and linter
|
||||
|
||||
USAGE:
|
||||
vfmt [OPTIONS] <file|dir>...
|
||||
vfmt [OPTIONS] <file|dir>... format files in place
|
||||
vfmt format [OPTIONS] <file|dir>... the same, spelled out
|
||||
vfmt check [OPTIONS] <file|dir>... lint files
|
||||
vfmt - read from stdin, write to stdout
|
||||
|
||||
A subcommand is only recognized as the *first* argument, so every command
|
||||
line that worked before subcommands existed still formats. To format a
|
||||
file actually named `check`, write `vfmt format check` or `./check`.
|
||||
|
||||
OPTIONS:
|
||||
--check don't write; exit 1 if any file would be reformatted
|
||||
--diff don't write; print a unified diff of what would change
|
||||
@@ -92,6 +138,21 @@ OPTIONS:
|
||||
-h, --help show this help
|
||||
-V, --version show version
|
||||
|
||||
CHECK OPTIONS (`vfmt check` only):
|
||||
--select <RULES> run only these rules (comma-separated, repeatable)
|
||||
--ignore <RULES> drop these rules from the set that would run
|
||||
--output-format <FMT> `text` (default): FILE:LINE:COL: message [rule];
|
||||
`json`: one array of diagnostic objects
|
||||
--fix apply safe fixes and write the files back
|
||||
--unsafe-fixes let --fix apply unsafe fixes too (no rule ships
|
||||
one yet, so today this changes nothing)
|
||||
|
||||
Suppress a finding with a comment: `// vfmt: waive <rule>` on the line
|
||||
itself or on the line above it, or a `// vfmt: waive-start <rule>` /
|
||||
`// vfmt: waive-stop <rule>` pair around a region. `verilog_lint:` is
|
||||
accepted in place of `vfmt:`. A waiver that suppresses nothing is
|
||||
reported under the `unused-waiver` rule.
|
||||
|
||||
IGNORE FILES:
|
||||
While walking a directory, vfmt reads a `.gitignore` in every directory it
|
||||
enters and skips what it names; a deeper file overrides a shallower one and
|
||||
@@ -109,8 +170,10 @@ CONFIGURATION:
|
||||
patterns, added to `--exclude`). A command line flag overrides the file.
|
||||
|
||||
EXIT CODES:
|
||||
0 nothing to do: files were formatted, or --check/--diff found no change
|
||||
1 --check/--diff only: at least one file would be reformatted
|
||||
0 nothing to do: files were formatted, --check/--diff found no change,
|
||||
or `check` found no violations (or fixed all of them)
|
||||
1 --check/--diff only: at least one file would be reformatted;
|
||||
`check`: at least one violation was reported
|
||||
2 an error occurred (bad arguments, I/O, a file that could not be
|
||||
formatted); files involved in an error are left untouched"
|
||||
);
|
||||
@@ -124,6 +187,7 @@ pub fn parse() -> Result<Options, String> {
|
||||
|
||||
fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
let mut opts = Options {
|
||||
command: Command::Format,
|
||||
check: false,
|
||||
diff: false,
|
||||
stdout: false,
|
||||
@@ -134,9 +198,26 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
exclude: Vec::new(),
|
||||
line_length: None,
|
||||
indent: None,
|
||||
output_format: OutputFormat::Text,
|
||||
fix: false,
|
||||
unsafe_fixes: false,
|
||||
select: Vec::new(),
|
||||
ignore: Vec::new(),
|
||||
inputs: Vec::new(),
|
||||
};
|
||||
let mut args = args;
|
||||
let mut args = args.peekable();
|
||||
// The subcommand, if there is one, is the very first argument — so every
|
||||
// command line that worked before subcommands existed still formats.
|
||||
match args.peek().map(String::as_str) {
|
||||
Some("check") => {
|
||||
opts.command = Command::Check;
|
||||
args.next();
|
||||
}
|
||||
Some("format") => {
|
||||
args.next();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--check" => opts.check = true,
|
||||
@@ -165,6 +246,24 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
let v = args.next().ok_or("--indent requires a value")?;
|
||||
opts.indent = Some(v.parse().map_err(|_| format!("invalid indent: {v}"))?);
|
||||
}
|
||||
"--output-format" => {
|
||||
let v = args.next().ok_or("--output-format requires a value")?;
|
||||
opts.output_format = match v.as_str() {
|
||||
"text" => OutputFormat::Text,
|
||||
"json" => OutputFormat::Json,
|
||||
other => return Err(format!("unknown output format: {other} (text, json)")),
|
||||
};
|
||||
}
|
||||
"--fix" => opts.fix = true,
|
||||
"--unsafe-fixes" => opts.unsafe_fixes = true,
|
||||
"--select" => {
|
||||
let v = args.next().ok_or("--select requires a value")?;
|
||||
opts.select.extend(split_rules(&v));
|
||||
}
|
||||
"--ignore" => {
|
||||
let v = args.next().ok_or("--ignore requires a value")?;
|
||||
opts.ignore.extend(split_rules(&v));
|
||||
}
|
||||
"-h" | "--help" => {
|
||||
print_help();
|
||||
std::process::exit(0);
|
||||
@@ -184,9 +283,50 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
if opts.diff && opts.stdout {
|
||||
return Err("--diff cannot be combined with --stdout".to_string());
|
||||
}
|
||||
check_flag_scopes(&opts)?;
|
||||
Ok(opts)
|
||||
}
|
||||
|
||||
/// A comma-separated rule list, `--select no-tabs,module-filename`. Repeating
|
||||
/// the flag works too and the lists are concatenated.
|
||||
fn split_rules(value: &str) -> Vec<String> {
|
||||
value.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_string).collect()
|
||||
}
|
||||
|
||||
/// Rejects a flag used with the wrong subcommand. A quiet no-op would be the
|
||||
/// worse outcome: `vfmt check --diff` looking like it worked, having linted
|
||||
/// nothing.
|
||||
fn check_flag_scopes(opts: &Options) -> Result<(), String> {
|
||||
let lint_only = [
|
||||
(opts.fix, "--fix"),
|
||||
(opts.unsafe_fixes, "--unsafe-fixes"),
|
||||
(opts.output_format != OutputFormat::Text, "--output-format"),
|
||||
(!opts.select.is_empty(), "--select"),
|
||||
(!opts.ignore.is_empty(), "--ignore"),
|
||||
];
|
||||
let format_only = [(opts.check, "--check"), (opts.diff, "--diff"), (opts.stdout, "--stdout")];
|
||||
match opts.command {
|
||||
Command::Format => {
|
||||
for (given, flag) in lint_only {
|
||||
if given {
|
||||
return Err(format!("{flag} is only valid for `vfmt check`"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Command::Check => {
|
||||
for (given, flag) in format_only {
|
||||
if given {
|
||||
return Err(format!("{flag} is not valid for `vfmt check`"));
|
||||
}
|
||||
}
|
||||
if opts.unsafe_fixes && !opts.fix {
|
||||
return Err("--unsafe-fixes requires --fix".to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,472 @@
|
||||
//! The `vfmt check` driver: lint files, print diagnostics, apply fixes.
|
||||
//!
|
||||
//! Everything about *which* files are linted — the walk, `--exclude`,
|
||||
//! `.gitignore`, config discovery — is the formatter's, unchanged: `check`
|
||||
//! is handed the same `(path, config)` job list `format` gets. Only what
|
||||
//! happens to one file differs.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
|
||||
use rayon::prelude::*;
|
||||
use vlog_formatter::fence::{self, Region};
|
||||
use vlog_formatter::Config;
|
||||
use vlog_linter::{apply_fixes, lint, Fix, LintContext, Rule, Violation};
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
use crate::args::{Options, OutputFormat};
|
||||
|
||||
/// How many fix-then-relint rounds one file gets. Two fixes that overlap
|
||||
/// cannot both land in one pass (a tab that is also trailing whitespace is
|
||||
/// the everyday case), so the loop runs until the file stops changing; the
|
||||
/// cap only bounds a rule that would fight itself forever.
|
||||
const MAX_FIX_ROUNDS: usize = 10;
|
||||
|
||||
/// What linting one file produced.
|
||||
struct Report {
|
||||
path: String,
|
||||
/// Positions of the text the violations point into — which is the
|
||||
/// *fixed* text when `--fix` rewrote the file.
|
||||
index: LineIndex,
|
||||
violations: Vec<Violation>,
|
||||
/// Violations whose fix was applied and written back.
|
||||
fixed: usize,
|
||||
/// Set when the file could not be read or written; nothing was changed.
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
/// Lints every gathered file and reports. Exit 1 if anything is left over,
|
||||
/// 2 if a file could not be read or written.
|
||||
pub fn check_files(
|
||||
opts: &Options,
|
||||
jobs: &[(PathBuf, Config)],
|
||||
rules: &[&'static dyn Rule],
|
||||
) -> ExitCode {
|
||||
let mut reports: Vec<Report> =
|
||||
jobs.par_iter().map(|(file, config)| check_one(file, config, opts, rules)).collect();
|
||||
// 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.
|
||||
reports.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
finish(opts, reports)
|
||||
}
|
||||
|
||||
/// 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(
|
||||
opts: &Options,
|
||||
src: &str,
|
||||
config: &Config,
|
||||
rules: &[&'static dyn Rule],
|
||||
) -> 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 = run_rules(src, path, config, rules);
|
||||
// Nothing is ever written back for stdin, so `--fix` has nothing to do
|
||||
// here; the violations are reported as they are.
|
||||
let report =
|
||||
Report { path: name, index: LineIndex::new(src), violations, fixed: 0, error: None };
|
||||
finish(opts, vec![report])
|
||||
}
|
||||
|
||||
/// Lints one file, optionally fixing it, and never panics out of its worker.
|
||||
fn check_one(file: &Path, config: &Config, opts: &Options, rules: &[&'static dyn Rule]) -> Report {
|
||||
let path = file.display().to_string();
|
||||
let failed = |error: String| Report {
|
||||
path: path.clone(),
|
||||
index: LineIndex::new(""),
|
||||
violations: Vec::new(),
|
||||
fixed: 0,
|
||||
error: Some(error),
|
||||
};
|
||||
|
||||
let src = match std::fs::read_to_string(file) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return failed(format!("{path}: {e}")),
|
||||
};
|
||||
let outcome = crate::catch_panic(|| {
|
||||
if opts.fix {
|
||||
fix_source(&src, file, config, opts, rules)
|
||||
} else {
|
||||
(run_rules(&src, Some(file.to_path_buf()), config, rules), None, 0)
|
||||
}
|
||||
});
|
||||
let (violations, rewritten, fixed) = match outcome {
|
||||
Ok(outcome) => outcome,
|
||||
Err(msg) => return failed(format!("{path}: panicked while linting: {msg}")),
|
||||
};
|
||||
let index = LineIndex::new(rewritten.as_deref().unwrap_or(&src));
|
||||
if let Some(text) = rewritten {
|
||||
if let Err(e) = std::fs::write(file, &text) {
|
||||
return failed(format!("{path}: {e}"));
|
||||
}
|
||||
}
|
||||
Report { path, index, violations, fixed, error: None }
|
||||
}
|
||||
|
||||
/// Runs the rules over one text.
|
||||
fn run_rules(
|
||||
src: &str,
|
||||
path: Option<PathBuf>,
|
||||
config: &Config,
|
||||
rules: &[&'static dyn Rule],
|
||||
) -> Vec<Violation> {
|
||||
// The indent width the formatter would use is also the width a tab
|
||||
// expands to, so `--indent 4` fixes tabs into four spaces.
|
||||
let ctx = LintContext::new(src, path).with_tab_width(config.indent_width);
|
||||
lint(&ctx, rules)
|
||||
}
|
||||
|
||||
/// The violations whose fix may be applied: everything except a fix that
|
||||
/// would edit bytes inside a `// verilog_format: off` region.
|
||||
///
|
||||
/// `off` means hands-off across both tools. The formatter emits a fenced
|
||||
/// region as the exact source bytes it was written with; a linter that
|
||||
/// rewrote those same bytes would make the fence a promise only half of vfmt
|
||||
/// keeps. The violation is still **reported** — a finding is information, and
|
||||
/// silencing it is what waivers are for — it just loses its automatic fix.
|
||||
fn fixable_outside_fences(text: &str, violations: &[Violation]) -> Vec<Violation> {
|
||||
// Two sources, unioned. `fence::collect` is the formatter's own answer and
|
||||
// the authority wherever the tree is good; the line scan is a backstop for
|
||||
// the files only the linter sees, where error recovery can swallow the
|
||||
// structure a fence hangs on and `collect` then reports no region at all.
|
||||
// Erring toward more protection only ever declines a fix.
|
||||
let (parsed, _) = vlog_parser::parse_source_tolerant(text);
|
||||
let mut regions = fence::collect(text, &parsed);
|
||||
regions.extend(scanned_fence_regions(text));
|
||||
if regions.is_empty() {
|
||||
return violations.to_vec();
|
||||
}
|
||||
violations
|
||||
.iter()
|
||||
.filter(|violation| violation.fix.as_ref().is_some_and(|fix| !touches_fence(fix, ®ions)))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Fenced regions found by reading lines, without a parse.
|
||||
///
|
||||
/// A fence is by definition a line comment alone on its line whose text
|
||||
/// matches exactly, so [`fence::fence_of`] — the formatter's own grammar — is
|
||||
/// all this needs. Pairing is deliberately cruder than the formatter's: an
|
||||
/// `off` runs to the next `on` or to the end of the file, with no notion of
|
||||
/// the enclosing scope. It can therefore protect a little more than the
|
||||
/// formatter would emit verbatim (and would be fooled by a fence spelled
|
||||
/// inside a block comment), which is the harmless direction: the only
|
||||
/// consequence is a fix vfmt declines to apply.
|
||||
fn scanned_fence_regions(text: &str) -> Vec<Region> {
|
||||
let index = LineIndex::new(text);
|
||||
let mut regions = Vec::new();
|
||||
let mut open: Option<usize> = None;
|
||||
for line in 1..=index.line_count() {
|
||||
let Some(range) = index.line_range(line) else { continue };
|
||||
let Some(spelling) = text.get(range.as_range()).and_then(|l| fence::fence_of(l.trim()))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
match (spelling, open) {
|
||||
(fence::Fence::Off, None) => open = Some(range.start as usize),
|
||||
(fence::Fence::On, Some(start)) => {
|
||||
regions.push(Region { fence: start, start, end: range.end as usize });
|
||||
open = None;
|
||||
}
|
||||
// A second `off`, or an `on` with nothing open, is just text.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(start) = open {
|
||||
regions.push(Region { fence: start, start, end: text.len() });
|
||||
}
|
||||
regions
|
||||
}
|
||||
|
||||
/// True when any edit of `fix` overlaps a fenced region.
|
||||
///
|
||||
/// The protected range is the whole `start..end` the formatter would emit
|
||||
/// verbatim, indentation of the fence line included — not just what
|
||||
/// `region_at` calls "inside" — because that is exactly the set of bytes the
|
||||
/// formatter promises to leave alone.
|
||||
fn touches_fence(fix: &Fix, regions: &[Region]) -> bool {
|
||||
fix.edits.iter().any(|(range, _)| {
|
||||
let start = range.start as usize;
|
||||
// An insertion has an empty range; treat it as covering the byte it
|
||||
// would land in front of, so nothing can be spliced into a region.
|
||||
let end = (range.end as usize).max(start + 1);
|
||||
regions.iter().any(|region| start < region.end && region.start < end)
|
||||
})
|
||||
}
|
||||
|
||||
/// Applies fixes until the file stops changing. Returns what is left over,
|
||||
/// the rewritten text (if it changed) and how many fixes landed.
|
||||
fn fix_source(
|
||||
src: &str,
|
||||
file: &Path,
|
||||
config: &Config,
|
||||
opts: &Options,
|
||||
rules: &[&'static dyn Rule],
|
||||
) -> (Vec<Violation>, Option<String>, usize) {
|
||||
let mut text = src.to_string();
|
||||
let mut fixed = 0;
|
||||
let mut violations = run_rules(&text, Some(file.to_path_buf()), config, rules);
|
||||
for _ in 0..MAX_FIX_ROUNDS {
|
||||
let round =
|
||||
apply_fixes(&text, &fixable_outside_fences(&text, &violations), opts.unsafe_fixes);
|
||||
if round.applied == 0 {
|
||||
break;
|
||||
}
|
||||
fixed += round.applied;
|
||||
text = round.output;
|
||||
violations = run_rules(&text, Some(file.to_path_buf()), config, rules);
|
||||
}
|
||||
let rewritten = (text != src).then_some(text);
|
||||
(violations, rewritten, fixed)
|
||||
}
|
||||
|
||||
/// Prints the run and turns it into an exit code.
|
||||
fn finish(opts: &Options, reports: Vec<Report>) -> ExitCode {
|
||||
let violations: usize = reports.iter().map(|r| r.violations.len()).sum();
|
||||
let fixed: usize = reports.iter().map(|r| r.fixed).sum();
|
||||
let errors = reports.iter().filter(|r| r.error.is_some()).count();
|
||||
|
||||
match opts.output_format {
|
||||
OutputFormat::Text => print_text(&reports),
|
||||
OutputFormat::Json => print_json(&reports),
|
||||
}
|
||||
for report in &reports {
|
||||
// Errors go to stderr in both formats, so `--output-format json`
|
||||
// emits one parsable array and nothing else on stdout.
|
||||
if let Some(error) = &report.error {
|
||||
eprintln!("error: {error}");
|
||||
}
|
||||
}
|
||||
summarize(violations, fixed, errors);
|
||||
|
||||
if errors > 0 {
|
||||
ExitCode::from(2)
|
||||
} else if violations > 0 {
|
||||
ExitCode::from(1)
|
||||
} else {
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
}
|
||||
|
||||
/// Verible's diagnostic line: `FILE:LINE:COL: message [rule-name]`.
|
||||
fn print_text(reports: &[Report]) {
|
||||
let mut out = String::new();
|
||||
for report in reports {
|
||||
for violation in &report.violations {
|
||||
let (line, col) = position(report, violation);
|
||||
out.push_str(&format!(
|
||||
"{}:{line}:{col}: {} [{}]\n",
|
||||
report.path, violation.message, violation.rule
|
||||
));
|
||||
}
|
||||
}
|
||||
print!("{out}");
|
||||
}
|
||||
|
||||
/// One JSON array of diagnostics, ruff-shaped: enough to drive an editor
|
||||
/// without reading the text output back.
|
||||
fn print_json(reports: &[Report]) {
|
||||
let mut items = Vec::new();
|
||||
for report in reports {
|
||||
for violation in &report.violations {
|
||||
let (line, col) = position(report, violation);
|
||||
let (end_line, end_col) = end_position(report, violation);
|
||||
items.push(format!(
|
||||
"{{\"filename\":{},\"rule\":{},\"message\":{},\
|
||||
\"location\":{{\"line\":{line},\"column\":{col}}},\
|
||||
\"end_location\":{{\"line\":{end_line},\"column\":{end_col}}},\
|
||||
\"range\":{{\"start\":{},\"end\":{}}},\"fix\":{}}}",
|
||||
quote(&report.path),
|
||||
quote(violation.rule),
|
||||
quote(&violation.message),
|
||||
violation.span.start,
|
||||
violation.span.end,
|
||||
fix_json(violation),
|
||||
));
|
||||
}
|
||||
}
|
||||
println!("[{}]", items.join(","));
|
||||
}
|
||||
|
||||
fn fix_json(violation: &Violation) -> String {
|
||||
let Some(fix) = &violation.fix else { return "null".to_string() };
|
||||
let edits = fix
|
||||
.edits
|
||||
.iter()
|
||||
.map(|(range, content)| {
|
||||
format!(
|
||||
"{{\"start\":{},\"end\":{},\"content\":{}}}",
|
||||
range.start,
|
||||
range.end,
|
||||
quote(content)
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
format!(
|
||||
"{{\"applicability\":{},\"edits\":[{}]}}",
|
||||
quote(fix.applicability.as_str()),
|
||||
edits.join(",")
|
||||
)
|
||||
}
|
||||
|
||||
/// A JSON string literal. Hand-rolled: the shape is three fields deep and
|
||||
/// pulling in a serialization framework for it is not a trade worth making.
|
||||
fn quote(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len() + 2);
|
||||
out.push('"');
|
||||
for c in text.chars() {
|
||||
match c {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
out
|
||||
}
|
||||
|
||||
/// 1-based line and column of a diagnostic's start.
|
||||
fn position(report: &Report, violation: &Violation) -> (u32, u32) {
|
||||
report.index.line_col(violation.span.start)
|
||||
}
|
||||
|
||||
/// 1-based line and column one past a diagnostic's last byte.
|
||||
fn end_position(report: &Report, violation: &Violation) -> (u32, u32) {
|
||||
report.index.line_col(violation.span.end)
|
||||
}
|
||||
|
||||
fn summarize(violations: usize, fixed: usize, errors: usize) {
|
||||
let mut summary = Vec::new();
|
||||
if violations > 0 {
|
||||
summary.push(format!("found {violations} violation{}", plural(violations)));
|
||||
}
|
||||
if fixed > 0 {
|
||||
summary.push(format!("fixed {fixed} violation{}", plural(fixed)));
|
||||
}
|
||||
if errors > 0 {
|
||||
summary.push(format!("{errors} file{} could not be checked", plural(errors)));
|
||||
}
|
||||
if !summary.is_empty() {
|
||||
eprintln!("{}", summary.join(", "));
|
||||
}
|
||||
}
|
||||
|
||||
fn plural(n: usize) -> &'static str {
|
||||
if n == 1 {
|
||||
""
|
||||
} else {
|
||||
"s"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
use vlog_linter::{Fix as LintFix, Violation as LintViolation};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// A region covering bytes 10..20, as `fence::collect` would report one.
|
||||
fn region() -> Vec<Region> {
|
||||
vec![Region { fence: 10, start: 10, end: 20 }]
|
||||
}
|
||||
|
||||
fn edit_at(start: u32, end: u32) -> LintFix {
|
||||
LintFix::safe(vec![(TextRange::new(start, end), "x".to_string())])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fix_is_blocked_exactly_at_the_fence_boundaries() {
|
||||
let regions = region();
|
||||
// First byte inside, last byte inside, and the whole span.
|
||||
assert!(touches_fence(&edit_at(10, 11), ®ions), "first byte inside");
|
||||
assert!(touches_fence(&edit_at(19, 20), ®ions), "last byte inside");
|
||||
assert!(touches_fence(&edit_at(10, 20), ®ions), "the whole region");
|
||||
// Adjacent on both ends, touching nothing inside.
|
||||
assert!(!touches_fence(&edit_at(9, 10), ®ions), "ends where the region starts");
|
||||
assert!(!touches_fence(&edit_at(20, 21), ®ions), "starts where the region ends");
|
||||
// Straddling either edge is still a hit.
|
||||
assert!(touches_fence(&edit_at(9, 11), ®ions), "straddles the start");
|
||||
assert!(touches_fence(&edit_at(19, 21), ®ions), "straddles the end");
|
||||
// An insertion (empty range) inside must not be spliced in either,
|
||||
// while one at the far edge is outside.
|
||||
assert!(touches_fence(&edit_at(15, 15), ®ions), "insertion inside");
|
||||
assert!(touches_fence(&edit_at(10, 10), ®ions), "insertion at the first byte");
|
||||
assert!(!touches_fence(&edit_at(20, 20), ®ions), "insertion just past the end");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_edit_fix_is_blocked_if_any_edit_lands_inside() {
|
||||
let fix = LintFix::safe(vec![
|
||||
(TextRange::new(0, 1), "x".to_string()),
|
||||
(TextRange::new(15, 16), "y".to_string()),
|
||||
]);
|
||||
assert!(touches_fence(&fix, ®ion()), "one edit inside blocks the whole fix");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixes_outside_a_fence_survive_the_filter() {
|
||||
// Line 2 is fenced, line 4 is not; both have a tab worth fixing.
|
||||
let text = "module m;\n// vfmt: off\n\ta = 1;\n// vfmt: on\n\tb = 2;\nendmodule\n";
|
||||
let fenced = text.find("\ta = 1").unwrap_or(0) as u32;
|
||||
let free = text.find("\tb = 2").unwrap_or(0) as u32;
|
||||
let violations = vec![
|
||||
LintViolation::new("no-tabs", "tab", TextRange::new(fenced, fenced + 1))
|
||||
.with_fix(edit_at(fenced, fenced + 1)),
|
||||
LintViolation::new("no-tabs", "tab", TextRange::new(free, free + 1))
|
||||
.with_fix(edit_at(free, free + 1)),
|
||||
];
|
||||
let kept = fixable_outside_fences(text, &violations);
|
||||
assert_eq!(kept.len(), 1, "only the unfenced fix survives");
|
||||
assert_eq!(kept[0].span.start, free);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_without_fences_keeps_every_fix() {
|
||||
let text = "module m;\n\ta = 1;\nendmodule\n";
|
||||
let violations =
|
||||
vec![LintViolation::new("no-tabs", "tab", TextRange::new(10, 11))
|
||||
.with_fix(edit_at(10, 11))];
|
||||
assert_eq!(fixable_outside_fences(text, &violations).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_line_scan_backstops_a_file_that_does_not_parse() {
|
||||
// Error recovery can swallow the structure `fence::collect` hangs a
|
||||
// region on; the scan still finds it.
|
||||
let text = "module m;\n@@@ junk;\n// vfmt: off\n\ta = 1;\n// vfmt: on\nendmodule\n";
|
||||
let regions = scanned_fence_regions(text);
|
||||
assert_eq!(regions.len(), 1, "{regions:?}");
|
||||
let tab = text.find("\ta = 1").unwrap_or(0);
|
||||
assert!(regions[0].start <= tab && tab < regions[0].end);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unclosed_fence_scan_runs_to_the_end_of_the_file() {
|
||||
let text = "module m;\n// vfmt: off\n\ta = 1;\nendmodule\n";
|
||||
let regions = scanned_fence_regions(text);
|
||||
assert_eq!(regions.len(), 1);
|
||||
assert_eq!(regions[0].end, text.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ordinary_comment_is_not_a_fence() {
|
||||
assert!(scanned_fence_regions("// vfmt: off-by-one\n\ta = 1;\n").is_empty());
|
||||
assert!(scanned_fence_regions("// just a note\n\ta = 1;\n").is_empty());
|
||||
assert!(scanned_fence_regions("// vfmt: on\n\ta = 1;\n").is_empty(), "a stray `on`");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_strings_are_escaped() {
|
||||
assert_eq!(quote("plain"), "\"plain\"");
|
||||
assert_eq!(quote("a\"b\\c"), "\"a\\\"b\\\\c\"");
|
||||
assert_eq!(quote("tab\there"), "\"tab\\there\"");
|
||||
assert_eq!(quote("bell\u{7}"), "\"bell\\u0007\"");
|
||||
}
|
||||
}
|
||||
+46
-8
@@ -1,17 +1,21 @@
|
||||
//! vfmt — a Verilog/SystemVerilog formatter in the spirit of `ruff format`.
|
||||
//! vfmt — a Verilog/SystemVerilog formatter and linter in the spirit of
|
||||
//! `ruff format` and `ruff check`.
|
||||
//!
|
||||
//! Usage:
|
||||
//! vfmt [OPTIONS] <file|dir>... format files in place
|
||||
//! vfmt --check <file|dir>... exit 1 if anything would change
|
||||
//! vfmt --diff <file|dir>... print a unified diff of what would change
|
||||
//! vfmt check <file|dir>... lint files (exit 1 if anything is found)
|
||||
//! vfmt - read stdin, write stdout
|
||||
//!
|
||||
//! Exit codes: 0 nothing to do, 1 `--check`/`--diff` found changes,
|
||||
//! 2 an error occurred (the affected files are left untouched).
|
||||
//! Exit codes: 0 nothing to do, 1 `--check`/`--diff` found changes or `check`
|
||||
//! found violations, 2 an error occurred (the affected files are left
|
||||
//! untouched).
|
||||
|
||||
mod args;
|
||||
mod config;
|
||||
mod diff;
|
||||
mod lint;
|
||||
mod walk;
|
||||
|
||||
use std::cell::Cell;
|
||||
@@ -22,7 +26,7 @@ use std::process::ExitCode;
|
||||
|
||||
use rayon::prelude::*;
|
||||
|
||||
use args::Options;
|
||||
use args::{Command, Options};
|
||||
use config::Discovery;
|
||||
use vlog_formatter::{format_source, Config};
|
||||
use walk::{collect_files, EXTENSIONS};
|
||||
@@ -44,13 +48,47 @@ fn main() -> ExitCode {
|
||||
// Once, before any worker thread exists, so nothing ever races on it.
|
||||
install_panic_hook();
|
||||
|
||||
if opts.inputs.len() == 1 && opts.inputs[0] == "-" {
|
||||
run_stdin(&opts)
|
||||
} else {
|
||||
run_files(&opts)
|
||||
match opts.command {
|
||||
Command::Format if opts.is_stdin() => run_stdin(&opts),
|
||||
Command::Format => run_files(&opts),
|
||||
Command::Check => run_check(&opts),
|
||||
}
|
||||
}
|
||||
|
||||
/// `vfmt check`: the linter over the same file set the formatter would take.
|
||||
fn run_check(opts: &Options) -> ExitCode {
|
||||
let rules = match vlog_linter::select_rules(&opts.select, &opts.ignore) {
|
||||
Ok(rules) => rules,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
if opts.is_stdin() {
|
||||
let config = match stdin_config(opts) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
let mut src = String::new();
|
||||
if let Err(e) = std::io::stdin().read_to_string(&mut src) {
|
||||
eprintln!("error: reading stdin: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
return lint::check_stdin(opts, &src, &config, &rules);
|
||||
}
|
||||
let jobs = match gather(opts).and_then(|jobs| build_pool(opts).map(|()| jobs)) {
|
||||
Ok(jobs) => jobs,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
lint::check_files(opts, &jobs, &rules)
|
||||
}
|
||||
|
||||
fn run_stdin(opts: &Options) -> ExitCode {
|
||||
let name = opts.stdin_filename.as_deref().unwrap_or("<stdin>");
|
||||
let config = match stdin_config(opts) {
|
||||
|
||||
@@ -681,3 +681,311 @@ fn the_search_stops_at_a_git_directory_after_checking_it() {
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(dir.read("repo/rtl/x.sv"), "module m;\n wire x;\nendmodule\n");
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------- vfmt check
|
||||
|
||||
/// Two findings: a tab on line 2 and a module/file-name mismatch.
|
||||
const LINTY: &str = "module foo;\n\twire a;\nendmodule\n";
|
||||
/// The same file with the tab expanded — `no-tabs` clean.
|
||||
const LINTY_FIXED: &str = "module foo;\n wire a;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn check_reports_violations_and_exits_1() {
|
||||
let dir = TempDir::new("check-lint");
|
||||
let path = dir.write("bar.sv", LINTY);
|
||||
|
||||
let out = run(&["check", &path]);
|
||||
assert_eq!(code(&out), 1, "violations must exit 1: {}", stderr(&out));
|
||||
let text = stdout(&out);
|
||||
assert!(text.contains(&format!("{path}:2:1: tab character")), "{text}");
|
||||
assert!(text.contains("[no-tabs]"), "{text}");
|
||||
assert!(text.contains("[module-filename]"), "{text}");
|
||||
assert!(stderr(&out).contains("found 2 violations"), "{}", stderr(&out));
|
||||
assert_eq!(dir.read("bar.sv"), LINTY, "check must not write");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_exits_0_on_a_clean_file() {
|
||||
let dir = TempDir::new("check-clean");
|
||||
let path = dir.write("foo.sv", LINTY_FIXED);
|
||||
|
||||
let out = run(&["check", &path]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(stdout(&out), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_diagnostics_are_sorted_by_file_then_position() {
|
||||
let dir = TempDir::new("check-order");
|
||||
dir.write("b.sv", LINTY);
|
||||
dir.write("a.sv", LINTY);
|
||||
|
||||
let out = run(&["check", &dir.root()]);
|
||||
let text = stdout(&out);
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
assert_eq!(lines.len(), 4, "{lines:?}");
|
||||
assert!(lines[0].contains("a.sv:1:"), "{lines:?}");
|
||||
assert!(lines[1].contains("a.sv:2:"), "{lines:?}");
|
||||
assert!(lines[2].contains("b.sv:1:"), "{lines:?}");
|
||||
assert!(lines[3].contains("b.sv:2:"), "{lines:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_json_is_one_array_with_positions_and_fixes() {
|
||||
let dir = TempDir::new("check-json");
|
||||
let path = dir.write("foo.sv", LINTY);
|
||||
|
||||
let out = run(&["check", "--output-format", "json", "--select", "no-tabs", &path]);
|
||||
assert_eq!(code(&out), 1);
|
||||
let text = stdout(&out);
|
||||
assert!(text.starts_with('['), "{text}");
|
||||
assert!(text.trim_end().ends_with(']'), "{text}");
|
||||
assert_eq!(text.matches("\"rule\":\"no-tabs\"").count(), 1, "{text}");
|
||||
assert!(text.contains("\"location\":{\"line\":2,\"column\":1}"), "{text}");
|
||||
assert!(text.contains("\"applicability\":\"safe\""), "{text}");
|
||||
assert!(text.contains("\"content\":\" \""), "{text}");
|
||||
|
||||
// A clean run still emits a parsable, empty array.
|
||||
dir.write("foo.sv", LINTY_FIXED);
|
||||
let out = run(&["check", "--output-format", "json", "--select", "no-tabs", &path]);
|
||||
assert_eq!(code(&out), 0);
|
||||
assert_eq!(stdout(&out).trim_end(), "[]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_fix_rewrites_the_file_and_the_result_relints_clean() {
|
||||
let dir = TempDir::new("check-fix");
|
||||
let path = dir.write("foo.sv", "module foo;\n\twire a; \nendmodule\n");
|
||||
|
||||
let out = run(&["check", "--fix", &path]);
|
||||
assert_eq!(code(&out), 0, "everything fixable was fixed: {}", stderr(&out));
|
||||
assert_eq!(dir.read("foo.sv"), LINTY_FIXED, "the tab and the trailing run are both gone");
|
||||
assert!(stderr(&out).contains("fixed 2 violations"), "{}", stderr(&out));
|
||||
|
||||
// The fixed file is clean for the rules that had fixes, and a second
|
||||
// --fix run has nothing left to do.
|
||||
let out = run(&["check", &path]);
|
||||
assert_eq!(code(&out), 0, "{}", stdout(&out));
|
||||
let out = run(&["check", "--fix", &path]);
|
||||
assert_eq!(code(&out), 0);
|
||||
assert_eq!(dir.read("foo.sv"), LINTY_FIXED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_fix_leaves_unfixable_findings_reported() {
|
||||
let dir = TempDir::new("check-fix-left");
|
||||
let path = dir.write("bar.sv", LINTY);
|
||||
|
||||
let out = run(&["check", "--fix", &path]);
|
||||
assert_eq!(code(&out), 1, "module-filename has no fix, so something is left");
|
||||
assert_eq!(dir.read("bar.sv"), LINTY_FIXED);
|
||||
assert!(stdout(&out).contains("[module-filename]"), "{}", stdout(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_select_and_ignore_pick_the_rule_set() {
|
||||
let dir = TempDir::new("check-select");
|
||||
let path = dir.write("bar.sv", LINTY);
|
||||
|
||||
let out = run(&["check", "--select", "no-tabs", &path]);
|
||||
assert_eq!(code(&out), 1);
|
||||
assert_eq!(stdout(&out).lines().count(), 1, "{}", stdout(&out));
|
||||
assert!(stdout(&out).contains("[no-tabs]"));
|
||||
|
||||
let out = run(&["check", "--ignore", "no-tabs,module-filename", &path]);
|
||||
assert_eq!(code(&out), 0, "{}", stdout(&out));
|
||||
|
||||
let out = run(&["check", "--select", "no-such-rule", &path]);
|
||||
assert_eq!(code(&out), 2, "an unknown rule is an error, not a silent no-op");
|
||||
assert!(stderr(&out).contains("unknown rule"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_honors_inline_waivers_and_reports_dead_ones() {
|
||||
let dir = TempDir::new("check-waive");
|
||||
let path = dir.write("foo.sv", "module foo;\n\twire a; // vfmt: waive no-tabs\nendmodule\n");
|
||||
let out = run(&["check", &path]);
|
||||
assert_eq!(code(&out), 0, "{}", stdout(&out));
|
||||
|
||||
dir.write("foo.sv", "module foo;\n wire a; // verilog_lint: waive no-tabs\nendmodule\n");
|
||||
let out = run(&["check", &path]);
|
||||
assert_eq!(code(&out), 1);
|
||||
assert!(stdout(&out).contains("[unused-waiver]"), "{}", stdout(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_reads_stdin_and_names_it() {
|
||||
let out = run_with_stdin(&["check", "--stdin-filename", "rtl/z.sv", "-"], LINTY);
|
||||
assert_eq!(code(&out), 1);
|
||||
assert!(stdout(&out).contains("rtl/z.sv:2:1:"), "{}", stdout(&out));
|
||||
|
||||
let out = run_with_stdin(&["check", "-"], LINTY);
|
||||
assert_eq!(code(&out), 1);
|
||||
assert!(stdout(&out).contains("<stdin>:2:1:"), "{}", stdout(&out));
|
||||
assert!(
|
||||
!stdout(&out).contains("module-filename"),
|
||||
"a rule that needs a file name stays quiet: {}",
|
||||
stdout(&out)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_reuses_the_walk_and_its_exclusions() {
|
||||
let dir = TempDir::new("check-walk");
|
||||
dir.write("keep.sv", LINTY);
|
||||
dir.write("skip_gen.sv", LINTY);
|
||||
dir.write("notes.txt", "\tnot verilog\n");
|
||||
|
||||
let out = run(&["check", "--exclude", "*_gen.sv", &dir.root()]);
|
||||
assert_eq!(code(&out), 1);
|
||||
let text = stdout(&out);
|
||||
assert!(text.contains("keep.sv"), "{text}");
|
||||
assert!(!text.contains("skip_gen.sv"), "--exclude applies to check: {text}");
|
||||
assert!(!text.contains("notes.txt"), "only Verilog files are linted: {text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_expands_tabs_to_the_configured_indent() {
|
||||
let dir = TempDir::new("check-indent");
|
||||
dir.write("vfmt.toml", "indent = 4\n");
|
||||
let path = dir.write("foo.sv", "module foo;\n\twire a;\nendmodule\n");
|
||||
|
||||
let out = run(&["check", "--fix", &path]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(dir.read("foo.sv"), "module foo;\n wire a;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_reports_an_unreadable_file_as_an_error() {
|
||||
let dir = TempDir::new("check-missing");
|
||||
let missing = format!("{}/nope.sv", dir.root());
|
||||
let out = run(&["check", &missing]);
|
||||
assert_eq!(code(&out), 2);
|
||||
}
|
||||
|
||||
// ------------------------------------------------- subcommand compatibility
|
||||
|
||||
#[test]
|
||||
fn a_bare_invocation_still_formats() {
|
||||
let dir = TempDir::new("compat-bare");
|
||||
let path = dir.write("a.sv", UNFORMATTED);
|
||||
|
||||
let out = run(&[&path]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(dir.read("a.sv"), FORMATTED);
|
||||
|
||||
// And every pre-subcommand flag combination behaves as it always did.
|
||||
dir.write("a.sv", UNFORMATTED);
|
||||
let out = run(&["--check", &path]);
|
||||
assert_eq!(code(&out), 1);
|
||||
assert!(stdout(&out).contains("would reformat:"));
|
||||
assert_eq!(dir.read("a.sv"), UNFORMATTED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_format_subcommand_is_an_alias_for_the_bare_invocation() {
|
||||
let dir = TempDir::new("compat-alias");
|
||||
let path = dir.write("a.sv", UNFORMATTED);
|
||||
|
||||
let bare = run(&["--check", &path]);
|
||||
let alias = run(&["format", "--check", &path]);
|
||||
assert_eq!(code(&bare), code(&alias));
|
||||
assert_eq!(stdout(&bare), stdout(&alias));
|
||||
assert_eq!(stderr(&bare), stderr(&alias));
|
||||
|
||||
let out = run(&["format", &path]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(dir.read("a.sv"), FORMATTED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_subcommand_is_only_read_as_the_first_argument() {
|
||||
let dir = TempDir::new("compat-first");
|
||||
// A file literally named `check`, formatted by naming it after `format`.
|
||||
let path = dir.write("check", UNFORMATTED);
|
||||
let out = run(&["format", &path]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
|
||||
// `--check check` is the old spelling and must still be the formatter.
|
||||
dir.write("check", UNFORMATTED);
|
||||
let out = run(&["--check", &path]);
|
||||
assert_eq!(code(&out), 1);
|
||||
assert!(stdout(&out).contains("would reformat:"), "{}", stdout(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_of_the_other_tool_are_rejected() {
|
||||
let dir = TempDir::new("compat-flags");
|
||||
let path = dir.write("a.sv", UNFORMATTED);
|
||||
|
||||
for args in [
|
||||
vec!["--fix", &path],
|
||||
vec!["--select", "no-tabs", &path],
|
||||
vec!["--output-format", "json", &path],
|
||||
] {
|
||||
let out = run(&args);
|
||||
assert_eq!(code(&out), 2, "{args:?} must not be accepted by the formatter");
|
||||
assert!(stderr(&out).contains("only valid for `vfmt check`"), "{}", stderr(&out));
|
||||
}
|
||||
for flag in ["--check", "--diff", "--stdout"] {
|
||||
let out = run(&["check", flag, &path]);
|
||||
assert_eq!(code(&out), 2, "{flag} must not be accepted by the linter");
|
||||
assert!(stderr(&out).contains("not valid for `vfmt check`"), "{}", stderr(&out));
|
||||
}
|
||||
let out = run(&["check", "--unsafe-fixes", &path]);
|
||||
assert_eq!(code(&out), 2, "--unsafe-fixes without --fix is a mistake");
|
||||
}
|
||||
|
||||
/// A fenced region (tab + trailing whitespace, deliberately hand-aligned) and
|
||||
/// an unfenced one with the same problems. `vfmt format` emits the fenced
|
||||
/// bytes verbatim; `vfmt check --fix` must do the same.
|
||||
const FENCED: &str = "module foo;\n\
|
||||
// vfmt: off\n\
|
||||
\tlocalparam int A = 1; \n\
|
||||
// vfmt: on\n\
|
||||
\tlocalparam int B = 2; \n\
|
||||
endmodule\n";
|
||||
|
||||
#[test]
|
||||
fn check_reports_inside_a_fence_but_never_fixes_there() {
|
||||
let dir = TempDir::new("check-fence");
|
||||
let path = dir.write("foo.sv", FENCED);
|
||||
|
||||
// Reporting is unaffected: both lines violate both text rules.
|
||||
let out = run(&["check", "--select", "no-tabs,no-trailing-whitespace", &path]);
|
||||
assert_eq!(code(&out), 1);
|
||||
assert_eq!(stdout(&out).lines().count(), 4, "{}", stdout(&out));
|
||||
|
||||
let out = run(&["check", "--fix", "--select", "no-tabs,no-trailing-whitespace", &path]);
|
||||
assert_eq!(code(&out), 1, "the fenced violations remain, so this is not a clean run");
|
||||
|
||||
let after = dir.read("foo.sv");
|
||||
let (before_lines, after_lines): (Vec<&str>, Vec<&str>) =
|
||||
(FENCED.lines().collect(), after.lines().collect());
|
||||
assert_eq!(after_lines[2], before_lines[2], "the fenced line must be byte-identical");
|
||||
assert!(after_lines[2].starts_with('\t'), "including its tab: {:?}", after_lines[2]);
|
||||
assert!(after_lines[2].ends_with(" "), "and its trailing run: {:?}", after_lines[2]);
|
||||
assert_eq!(after_lines[4], " localparam int B = 2;", "the unfenced line is still fixed");
|
||||
|
||||
// What is left over is exactly the two findings inside the fence.
|
||||
let out = run(&["check", "--select", "no-tabs,no-trailing-whitespace", &path]);
|
||||
assert_eq!(code(&out), 1);
|
||||
let text = stdout(&out);
|
||||
assert_eq!(text.lines().count(), 2, "{text}");
|
||||
assert!(text.lines().all(|l| l.contains(":3:")), "both point into the fence: {text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fence_holds_even_in_a_file_that_does_not_parse() {
|
||||
let dir = TempDir::new("check-fence-broken");
|
||||
let src = "module foo;\n @@@ not verilog;\n // vfmt: off\n\tlocalparam int A = 1; \n // vfmt: on\nendmodule\n";
|
||||
let path = dir.write("foo.sv", src);
|
||||
|
||||
let out = run(&["check", "--fix", &path]);
|
||||
assert_eq!(code(&out), 1);
|
||||
assert_eq!(dir.read("foo.sv"), src, "nothing inside the fence may be rewritten");
|
||||
|
||||
// And the formatter refuses this file outright, as it always has.
|
||||
let out = run(&["--check", &path]);
|
||||
assert_eq!(code(&out), 2);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "vfmt_server"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "vfmt-server"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
vlog_parser = { path = "../vlog_parser" }
|
||||
vlog_semantic = { path = "../vlog_semantic" }
|
||||
vlog_formatter = { path = "../vlog_formatter" }
|
||||
lsp-server = { workspace = true }
|
||||
lsp-types = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
@@ -0,0 +1,294 @@
|
||||
//! Byte offsets ↔ LSP positions.
|
||||
//!
|
||||
//! Everything below the protocol speaks UTF-8 byte offsets; LSP `Position`
|
||||
//! speaks UTF-16 code units within a line. The two agree only on ASCII, which
|
||||
//! is why getting this wrong survives to production. The exact rules — mid-
|
||||
//! character clamping, surrogate halves, CRLF — are in
|
||||
//! `docs/features/vfmt-server/README.md`.
|
||||
|
||||
use lsp_types::{Position, Range};
|
||||
use vlog_parser::{LineIndex, TextRange};
|
||||
|
||||
/// One document's text and line table, paired so positions can be converted
|
||||
/// in both directions. Borrows; there is no cached copy to invalidate.
|
||||
pub struct Positions<'a> {
|
||||
text: &'a str,
|
||||
index: &'a LineIndex,
|
||||
}
|
||||
|
||||
impl<'a> Positions<'a> {
|
||||
/// Pair a document's text with the line index built from it.
|
||||
pub fn new(text: &'a str, index: &'a LineIndex) -> Self {
|
||||
Positions { text, index }
|
||||
}
|
||||
|
||||
/// The LSP position of a byte offset. An offset inside a multi-byte
|
||||
/// character is floored to that character's start.
|
||||
pub fn position(&self, offset: u32) -> Position {
|
||||
let offset = self.floor_boundary(offset);
|
||||
let (line, _) = self.index.line_col(offset);
|
||||
let start = self.index.line_range(line).map_or(0, |r| r.start) as usize;
|
||||
let slice = self.text.get(start..offset as usize).unwrap_or("");
|
||||
// LSP line content excludes the whole `\r\n`; `LineIndex` keeps the
|
||||
// `\r` as an ordinary byte of its line, so drop it here.
|
||||
let slice = slice.strip_suffix('\r').unwrap_or(slice);
|
||||
Position { line: line - 1, character: utf16_len(slice) }
|
||||
}
|
||||
|
||||
/// The byte offset of an LSP position, clamped into the document.
|
||||
pub fn offset(&self, pos: Position) -> u32 {
|
||||
let Some(line) = self.index.line_range(pos.line.saturating_add(1)) else {
|
||||
return self.text.len() as u32;
|
||||
};
|
||||
let end = self.line_content_end(line);
|
||||
let mut units = 0u32;
|
||||
let mut offset = line.start;
|
||||
for ch in self.text.get(line.start as usize..end as usize).unwrap_or("").chars() {
|
||||
if units >= pos.character {
|
||||
break;
|
||||
}
|
||||
units += ch.len_utf16() as u32;
|
||||
offset += ch.len_utf8() as u32;
|
||||
}
|
||||
offset
|
||||
}
|
||||
|
||||
/// The LSP range of a byte range.
|
||||
pub fn range(&self, span: TextRange) -> Range {
|
||||
Range { start: self.position(span.start), end: self.position(span.end) }
|
||||
}
|
||||
|
||||
/// The whole document, as a range — what a full-document edit replaces.
|
||||
pub fn whole_document(&self) -> Range {
|
||||
self.range(TextRange::new(0, self.text.len() as u32))
|
||||
}
|
||||
|
||||
/// Widen a byte range to the whole lines it touches, for a hover snippet.
|
||||
pub fn whole_lines(&self, span: TextRange) -> &'a str {
|
||||
let (first, _) = self.index.line_col(span.start);
|
||||
let (last, _) = self.index.line_col(span.end);
|
||||
let start = self.index.line_range(first).map_or(0, |r| r.start);
|
||||
let end = self.index.line_range(last).map_or(self.text.len() as u32, |r| r.end);
|
||||
self.text.get(start as usize..end as usize).unwrap_or("")
|
||||
}
|
||||
|
||||
/// A range an editor can actually draw, for a diagnostic whose span is
|
||||
/// empty — a zero-width range underlines nothing.
|
||||
///
|
||||
/// An empty span becomes the whole line it sits on. A lex error reports
|
||||
/// at the point the lexer gave up, which for an unterminated comment or
|
||||
/// string is end-of-file — usually the empty line a trailing newline
|
||||
/// opens — so an empty line falls back to the one before it, where the
|
||||
/// text the user has to fix actually is.
|
||||
pub fn diagnostic_range(&self, span: TextRange) -> Range {
|
||||
if !span.is_empty() {
|
||||
return self.range(span);
|
||||
}
|
||||
let (line, _) = self.index.line_col(span.start);
|
||||
let mut target = self.index.line_range(line).unwrap_or(span);
|
||||
if target.is_empty() && line > 1 {
|
||||
target = self.index.line_range(line - 1).unwrap_or(target);
|
||||
}
|
||||
self.range(target)
|
||||
}
|
||||
|
||||
/// The end of a line's content: its `\r`, if it has one, is not content.
|
||||
fn line_content_end(&self, line: TextRange) -> u32 {
|
||||
match self.text.get(line.start as usize..line.end as usize) {
|
||||
Some(s) if s.ends_with('\r') => line.end - 1,
|
||||
_ => line.end,
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest character boundary at or below `offset`, clamped into the
|
||||
/// text. Slicing anywhere else panics, and an offset can land mid-
|
||||
/// character whenever a client's position rounding meets a surrogate pair.
|
||||
fn floor_boundary(&self, offset: u32) -> u32 {
|
||||
let mut offset = offset.min(self.text.len() as u32) as usize;
|
||||
while offset > 0 && !self.text.is_char_boundary(offset) {
|
||||
offset -= 1;
|
||||
}
|
||||
offset as u32
|
||||
}
|
||||
}
|
||||
|
||||
/// How many UTF-16 code units a string occupies — the unit LSP counts in.
|
||||
fn utf16_len(s: &str) -> u32 {
|
||||
s.chars().map(|c| c.len_utf16() as u32).sum()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn positions(text: &str) -> (LineIndex, String) {
|
||||
(LineIndex::new(text), text.to_string())
|
||||
}
|
||||
|
||||
/// Build a `Positions` and run `f` on it — the index has to outlive it.
|
||||
fn with<T>(text: &str, f: impl FnOnce(&Positions<'_>) -> T) -> T {
|
||||
let (index, owned) = positions(text);
|
||||
f(&Positions::new(&owned, &index))
|
||||
}
|
||||
|
||||
fn pos(line: u32, character: u32) -> Position {
|
||||
Position { line, character }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ascii_offsets_are_columns() {
|
||||
with("module m;\nendmodule\n", |p| {
|
||||
assert_eq!(p.position(0), pos(0, 0));
|
||||
assert_eq!(p.position(7), pos(0, 7));
|
||||
assert_eq!(p.position(10), pos(1, 0));
|
||||
assert_eq!(p.offset(pos(0, 7)), 7);
|
||||
assert_eq!(p.offset(pos(1, 0)), 10);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_two_byte_character_is_one_utf16_unit() {
|
||||
// "// é x" — `é` is 2 UTF-8 bytes, 1 UTF-16 unit.
|
||||
with("// é x\nwire a;\n", |p| {
|
||||
assert_eq!(p.position(3), pos(0, 3)); // at the `é`
|
||||
assert_eq!(p.position(5), pos(0, 4)); // after it: 4 units, 5 bytes
|
||||
assert_eq!(p.offset(pos(0, 4)), 5);
|
||||
assert_eq!(p.offset(pos(0, 6)), 7); // end of line content
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_three_byte_character_is_still_one_utf16_unit() {
|
||||
with("// ✓ ok\n", |p| {
|
||||
assert_eq!(p.position(6), pos(0, 4)); // `✓` is 3 bytes, 1 unit
|
||||
assert_eq!(p.offset(pos(0, 4)), 6);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_astral_character_is_two_utf16_units() {
|
||||
// `🎉` is one `char`, 4 UTF-8 bytes, 2 UTF-16 units — the surrogate
|
||||
// pair every naive implementation gets wrong.
|
||||
with("// 🎉 done\n", |p| {
|
||||
assert_eq!(p.position(3), pos(0, 3));
|
||||
assert_eq!(p.position(7), pos(0, 5)); // 3 + 2 units, 3 + 4 bytes
|
||||
assert_eq!(p.offset(pos(0, 5)), 7);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_position_inside_a_surrogate_pair_rounds_forward() {
|
||||
// Character 4 is the low half of `🎉`'s pair: there is no byte there,
|
||||
// so the whole character is consumed rather than sliced.
|
||||
with("// 🎉 done\n", |p| {
|
||||
assert_eq!(p.offset(pos(0, 4)), 7);
|
||||
assert!("// 🎉 done\n".is_char_boundary(7));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_offset_inside_a_character_floors_to_its_start() {
|
||||
with("// 🎉\n", |p| {
|
||||
// Bytes 4, 5, 6 are continuation bytes of `🎉`, which starts at 3.
|
||||
for offset in 3..=6 {
|
||||
assert_eq!(p.position(offset), pos(0, 3), "offset {offset}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_terminators_are_not_line_content() {
|
||||
// "module m;" is bytes 0..9; `\r` is 9, `\n` is 10, line 2 starts at 11.
|
||||
let text = "module m;\r\nendmodule\r\n";
|
||||
with(text, |p| {
|
||||
assert_eq!(p.position(8), pos(0, 8), "the `;`");
|
||||
assert_eq!(p.position(9), pos(0, 9), "the `\\r` is at end-of-content");
|
||||
assert_eq!(p.position(10), pos(0, 9), "and so is the `\\n`");
|
||||
assert_eq!(p.position(11), pos(1, 0));
|
||||
// A character past the content clamps before the `\r`.
|
||||
assert_eq!(p.offset(pos(0, 99)), 9);
|
||||
assert_eq!(p.offset(pos(1, 0)), 11);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crlf_terminator_is_the_one_place_the_round_trip_collapses() {
|
||||
// Both bytes of a `\r\n` are "the end of the line's content", and LSP
|
||||
// has one position for that, so byte → position → byte is not the
|
||||
// identity on the `\n`. Stated as a test so it stays a known,
|
||||
// deliberate collapse rather than a surprise.
|
||||
with("ab\r\ncd\n", |p| {
|
||||
assert_eq!(p.position(2), p.position(3));
|
||||
assert_eq!(p.offset(p.position(3)), 2, "rounds back to the `\\r`");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn out_of_range_positions_clamp() {
|
||||
let text = "wire a;\n";
|
||||
with(text, |p| {
|
||||
assert_eq!(p.offset(pos(99, 0)), text.len() as u32);
|
||||
assert_eq!(p.offset(pos(0, 99)), 7);
|
||||
assert_eq!(p.position(9_999), p.position(text.len() as u32));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_character_boundary_round_trips() {
|
||||
// Mixed widths, CRLF, an astral character and a trailing partial line.
|
||||
let text = "// é ✓ 🎉\r\nmodule mü;\n wire ✓a;\r\nendmodule";
|
||||
with(text, |p| {
|
||||
for (offset, _) in text.char_indices() {
|
||||
// The `\n` of a `\r\n` is the documented exception: it shares
|
||||
// its position with the `\r` before it.
|
||||
if text.as_bytes().get(offset.wrapping_sub(1)) == Some(&b'\r') {
|
||||
continue;
|
||||
}
|
||||
let offset = offset as u32;
|
||||
assert_eq!(p.offset(p.position(offset)), offset, "at byte {offset}");
|
||||
}
|
||||
let end = text.len() as u32;
|
||||
assert_eq!(p.offset(p.position(end)), end);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_span_becomes_a_visible_range() {
|
||||
with("wire a;\nendmodule\n", |p| {
|
||||
let r = p.diagnostic_range(TextRange::empty(2));
|
||||
assert_eq!(r.start, pos(0, 0), "the whole line it sits on");
|
||||
assert_eq!(r.end, pos(0, 7));
|
||||
// A non-empty span is passed through unchanged.
|
||||
assert_eq!(p.diagnostic_range(TextRange::new(0, 4)), p.range(TextRange::new(0, 4)));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_span_at_end_of_file_falls_back_to_the_line_before() {
|
||||
// A trailing newline opens an empty last line, which is where a lex
|
||||
// error lands; underlining nothing there helps nobody.
|
||||
let text = "module m;\n wire a; /* oops\n";
|
||||
with(text, |p| {
|
||||
let r = p.diagnostic_range(TextRange::empty(text.len() as u32));
|
||||
assert_eq!(r.start.line, 1);
|
||||
assert!(r.start.character < r.end.character, "must be drawable");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_lines_widens_a_span_to_its_lines() {
|
||||
with("module m;\n wire a;\nendmodule\n", |p| {
|
||||
assert_eq!(p.whole_lines(TextRange::new(14, 15)), " wire a;");
|
||||
assert_eq!(p.whole_lines(TextRange::new(7, 14)), "module m;\n wire a;");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_document_has_one_position() {
|
||||
with("", |p| {
|
||||
assert_eq!(p.position(0), pos(0, 0));
|
||||
assert_eq!(p.offset(pos(0, 0)), 0);
|
||||
assert_eq!(p.whole_document(), Range { start: pos(0, 0), end: pos(0, 0) });
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
//! Parse diagnostics, published on every buffer change.
|
||||
|
||||
use lsp_types::{Diagnostic, DiagnosticSeverity};
|
||||
|
||||
use crate::state::Document;
|
||||
|
||||
/// The source string every diagnostic this server publishes carries, so a
|
||||
/// user can tell ours from another server's.
|
||||
const SOURCE: &str = "vfmt";
|
||||
|
||||
/// One LSP diagnostic per diagnostic the tolerant parser recorded.
|
||||
///
|
||||
/// The list is always published, empty included: an empty publish is how a
|
||||
/// server clears the squiggles it drew for the previous keystroke.
|
||||
pub fn diagnostics(doc: &Document) -> Vec<Diagnostic> {
|
||||
let positions = doc.positions();
|
||||
doc.diagnostics
|
||||
.iter()
|
||||
.map(|d| Diagnostic {
|
||||
// A lex error's span is empty; widen it so the editor draws
|
||||
// something.
|
||||
range: positions.diagnostic_range(d.span),
|
||||
severity: Some(DiagnosticSeverity::ERROR),
|
||||
source: Some(SOURCE.to_string()),
|
||||
message: d.message.clone(),
|
||||
..Default::default()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::state::Workspace;
|
||||
use lsp_types::Uri;
|
||||
use std::str::FromStr;
|
||||
|
||||
fn doc_of(text: &str) -> (Workspace, Uri) {
|
||||
let uri = Uri::from_str("file:///rtl/m.sv").expect("uri");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clean_file_publishes_nothing() {
|
||||
let (ws, uri) = doc_of("module m;\n wire a;\nendmodule\n");
|
||||
assert!(diagnostics(ws.document(&uri).expect("open")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_file_reports_at_the_right_line() {
|
||||
let (ws, uri) = doc_of("module m;\n wire ;\nendmodule\n");
|
||||
let diags = diagnostics(ws.document(&uri).expect("open"));
|
||||
assert_eq!(diags.len(), 1);
|
||||
assert_eq!(diags[0].range.start.line, 1, "the broken line, 0-based");
|
||||
assert_eq!(diags[0].severity, Some(DiagnosticSeverity::ERROR));
|
||||
assert_eq!(diags[0].source.as_deref(), Some("vfmt"));
|
||||
assert!(diags[0].range.start < diags[0].range.end, "never zero-width");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_byte_content_before_the_error_shifts_the_character() {
|
||||
// The `é` is 2 bytes but 1 UTF-16 unit: a byte-based server reports
|
||||
// character 8 here, and the squiggle lands one column late.
|
||||
let (ws, uri) = doc_of("module m;\n // é\n wire ;\nendmodule\n");
|
||||
let diags = diagnostics(ws.document(&uri).expect("open"));
|
||||
assert_eq!(diags.len(), 1);
|
||||
assert_eq!(diags[0].range.start.line, 2);
|
||||
assert_eq!(diags[0].range.start.character, 7, "the `;`, in UTF-16 units");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lex_error_gets_a_visible_range() {
|
||||
// The lexer gives up at end of file, which a trailing newline makes
|
||||
// an empty line; the range falls back to the line that has the text.
|
||||
let (ws, uri) = doc_of("module m;\n wire a; /* unterminated\n");
|
||||
let diags = diagnostics(ws.document(&uri).expect("open"));
|
||||
assert_eq!(diags.len(), 1);
|
||||
assert_eq!(diags[0].message, "unterminated block comment");
|
||||
assert_eq!(diags[0].range.start.line, 1);
|
||||
assert!(diags[0].range.start < diags[0].range.end, "must be drawable");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
//! `textDocument/formatting`.
|
||||
//!
|
||||
//! The formatter's contract is all-or-nothing (CLAUDE.md invariant #1), and
|
||||
//! this handler keeps it: either one whole-document edit built from verified
|
||||
//! output, or no edit at all and an error for the user to read.
|
||||
|
||||
use lsp_types::{FormattingOptions, TextEdit};
|
||||
use vlog_formatter::{format_source, Config};
|
||||
|
||||
use crate::state::Document;
|
||||
|
||||
/// Indent widths a client may ask for. Wider than `vfmt.toml`'s own 1..8
|
||||
/// range would be, so the two agree.
|
||||
const INDENT_RANGE: std::ops::RangeInclusive<u32> = 1..=8;
|
||||
|
||||
/// Format a buffer.
|
||||
///
|
||||
/// `Ok(None)` means "nothing to do" — the buffer is already formatted, and an
|
||||
/// edit that changes nothing still moves the cursor in some editors. `Err`
|
||||
/// carries the formatter's own message; the caller surfaces it, and must not
|
||||
/// invent an edit from it.
|
||||
pub fn formatting(doc: &Document, options: &FormattingOptions) -> Result<Option<TextEdit>, String> {
|
||||
let config = config_from(options);
|
||||
let formatted = format_source(&doc.text, &config).map_err(|e| e.to_string())?;
|
||||
if formatted == doc.text {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted }))
|
||||
}
|
||||
|
||||
/// Map the client's tab options onto the formatter's config.
|
||||
///
|
||||
/// Only `indent_width` is taken, and only when the request is sane: a client
|
||||
/// asking for hard tabs, or for a 40-space indent, is asking for something
|
||||
/// vfmt does not do, and silently honoring half of it is worse than ignoring
|
||||
/// it. `max_width` stays at the default — line length comes from `vfmt.toml`,
|
||||
/// whose discovery lives in the CLI crate (see the feature README's
|
||||
/// Handshakes).
|
||||
fn config_from(options: &FormattingOptions) -> Config {
|
||||
let mut config = Config::default();
|
||||
if options.insert_spaces && INDENT_RANGE.contains(&options.tab_size) {
|
||||
config.indent_width = options.tab_size as usize;
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::state::Workspace;
|
||||
use lsp_types::Uri;
|
||||
use std::str::FromStr;
|
||||
|
||||
fn document(text: &str) -> (Workspace, Uri) {
|
||||
let uri = Uri::from_str("file:///rtl/m.sv").expect("uri");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
fn options(tab_size: u32, insert_spaces: bool) -> FormattingOptions {
|
||||
FormattingOptions { tab_size, insert_spaces, ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unformatted_buffer_gets_one_whole_document_edit() {
|
||||
let (ws, uri) = document("module m;\nwire a;\nendmodule\n");
|
||||
let edit = formatting(ws.document(&uri).expect("open"), &options(2, true))
|
||||
.expect("formats")
|
||||
.expect("changed");
|
||||
assert_eq!(edit.range.start.line, 0);
|
||||
assert_eq!(edit.range.start.character, 0);
|
||||
assert_eq!(edit.range.end.line, 3, "one past the last line");
|
||||
assert_eq!(edit.new_text, "module m;\n wire a;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_already_formatted_buffer_gets_no_edit() {
|
||||
let (ws, uri) = document("module m;\n wire a;\nendmodule\n");
|
||||
let edit =
|
||||
formatting(ws.document(&uri).expect("open"), &options(2, true)).expect("formats");
|
||||
assert_eq!(edit, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sane_tab_size_becomes_the_indent_width() {
|
||||
let (ws, uri) = document("module m;\nwire a;\nendmodule\n");
|
||||
let edit = formatting(ws.document(&uri).expect("open"), &options(4, true))
|
||||
.expect("formats")
|
||||
.expect("changed");
|
||||
assert_eq!(edit.new_text, "module m;\n wire a;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hard_tabs_and_absurd_widths_fall_back_to_the_default() {
|
||||
assert_eq!(config_from(&options(4, false)).indent_width, 2, "hard tabs ignored");
|
||||
assert_eq!(config_from(&options(40, true)).indent_width, 2, "out of range ignored");
|
||||
assert_eq!(config_from(&options(0, true)).indent_width, 2, "zero ignored");
|
||||
assert_eq!(config_from(&options(8, true)).indent_width, 8, "the top of the range");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_length_is_never_taken_from_the_client() {
|
||||
assert_eq!(config_from(&options(4, true)).max_width, Config::default().max_width);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unparsable_buffer_produces_no_edit() {
|
||||
let (ws, uri) = document("module m;\n wire ;\nendmodule\n");
|
||||
let result = formatting(ws.document(&uri).expect("open"), &options(2, true));
|
||||
let message = result.expect_err("must refuse");
|
||||
assert!(!message.is_empty(), "the user needs something to read");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_byte_content_survives_formatting() {
|
||||
let (ws, uri) = document("module m;\n// é ✓ 🎉\nwire a;\nendmodule\n");
|
||||
let edit = formatting(ws.document(&uri).expect("open"), &options(2, true))
|
||||
.expect("formats")
|
||||
.expect("changed");
|
||||
assert!(edit.new_text.contains("é ✓ 🎉"), "comments are never dropped");
|
||||
// The replaced range must cover the whole document in UTF-16 terms.
|
||||
assert_eq!(edit.range.end.line, 4);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
//! `textDocument/hover`.
|
||||
//!
|
||||
//! Four things can be under the cursor, tried in this order: a macro usage, a
|
||||
//! reference resolved in this file, a reference the workspace answered, and a
|
||||
//! declaration itself. The order and the rendering rules are in
|
||||
//! `docs/features/vfmt-server/README.md`.
|
||||
|
||||
use lsp_types::{Hover, HoverContents, MarkupContent, MarkupKind, Uri};
|
||||
use vlog_parser::defines::Define;
|
||||
use vlog_parser::token::Token;
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{Definition, Symbol};
|
||||
|
||||
use crate::locate::{display_name, line_number};
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::symbols::kind_label;
|
||||
|
||||
/// Hover text for the cursor at `offset`.
|
||||
pub fn hover(ws: &Workspace, uri: &Uri, offset: u32) -> Option<Hover> {
|
||||
let doc = ws.document(uri)?;
|
||||
macro_hover(ws, doc, offset).or_else(|| symbol_hover(ws, doc, offset))
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// `define expansion
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// A macro usage under the cursor: the file's own definition wins, then the
|
||||
/// workspace's — **all** of the workspace's, because no `` `include`` graph is
|
||||
/// modelled and picking one would be a guess.
|
||||
fn macro_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option<Hover> {
|
||||
let token = doc.tokens.iter().find(|t| t.is_macro() && t.span.contains(offset))?;
|
||||
let name = macro_name(token)?;
|
||||
|
||||
if let Some(define) = doc.defines.latest(name) {
|
||||
return Some(markdown(doc, define_text(name, define, None), token.span));
|
||||
}
|
||||
|
||||
let candidates = ws.index().find_define(name);
|
||||
if candidates.is_empty() {
|
||||
return Some(markdown(doc, format!("`` `{name} `` — no definition found"), token.span));
|
||||
}
|
||||
let mut parts = Vec::with_capacity(candidates.len());
|
||||
for (file, define) in &candidates {
|
||||
let where_ =
|
||||
ws.index().path(*file).map(|path| match line_number(ws, path, define.span.start) {
|
||||
Some(line) => format!("{}:{line}", display_name(path)),
|
||||
None => display_name(path),
|
||||
});
|
||||
parts.push(define_text(name, define, where_));
|
||||
}
|
||||
let joined = if parts.len() == 1 {
|
||||
parts.remove(0)
|
||||
} else {
|
||||
format!(
|
||||
"`` `{name} `` is defined {} times\n\n---\n\n{}",
|
||||
parts.len(),
|
||||
parts.join("\n\n---\n\n")
|
||||
)
|
||||
};
|
||||
Some(markdown(doc, joined, token.span))
|
||||
}
|
||||
|
||||
/// The macro's name: the identifier after the backtick, argument list excluded.
|
||||
fn macro_name(token: &Token) -> Option<&str> {
|
||||
let rest = token.text.strip_prefix('`')?;
|
||||
let end = rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '$');
|
||||
let name = match end {
|
||||
Some(end) => &rest[..end],
|
||||
None => rest,
|
||||
};
|
||||
if name.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(name)
|
||||
}
|
||||
}
|
||||
|
||||
/// One definition, rendered: its signature, its body, and where it came from.
|
||||
fn define_text(name: &str, define: &Define, origin: Option<String>) -> String {
|
||||
let signature = match &define.params {
|
||||
Some(params) => format!("`define {name}({})", params.join(", ")),
|
||||
None => format!("`define {name}"),
|
||||
};
|
||||
let mut out = String::new();
|
||||
if let Some(origin) = origin {
|
||||
out.push_str(&format!("defined in `{origin}`\n\n"));
|
||||
}
|
||||
out.push_str("```systemverilog\n");
|
||||
out.push_str(&signature);
|
||||
if !define.body.is_empty() {
|
||||
out.push(' ');
|
||||
out.push_str(&define.body);
|
||||
}
|
||||
out.push_str("\n```");
|
||||
out
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// declarations and references
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// A reference or a declaration under the cursor.
|
||||
fn symbol_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option<Hover> {
|
||||
let range = hovered_name_span(doc, offset)?;
|
||||
match doc.external.definition_of(&doc.semantics, offset)? {
|
||||
Definition::Local(symbol) => Some(markdown(doc, local_text(doc, symbol), range)),
|
||||
Definition::External(defs) => {
|
||||
let mut parts = Vec::with_capacity(defs.len());
|
||||
for def in defs {
|
||||
let label = kind_label(def.kind);
|
||||
let where_ = ws
|
||||
.index()
|
||||
.path(def.file)
|
||||
.map(|path| match line_number(ws, path, def.name_span.start) {
|
||||
Some(line) => format!("{}:{line}", display_name(path)),
|
||||
None => display_name(path),
|
||||
})
|
||||
.unwrap_or_else(|| "the workspace".to_string());
|
||||
parts.push(format!("**{label}** — declared in `{where_}`"));
|
||||
}
|
||||
Some(markdown(doc, parts.join("\n\n"), range))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A local declaration: what it is, and the lines it was written on.
|
||||
fn local_text(doc: &Document, symbol: &Symbol) -> String {
|
||||
let snippet = doc.positions().whole_lines(symbol.decl_span);
|
||||
format!(
|
||||
"**{}** `{}`\n\n```systemverilog\n{}\n```",
|
||||
kind_label(symbol.kind),
|
||||
symbol.name,
|
||||
snippet.trim_end()
|
||||
)
|
||||
}
|
||||
|
||||
/// The span the hover card should highlight: the name under the cursor.
|
||||
fn hovered_name_span(doc: &Document, offset: u32) -> Option<TextRange> {
|
||||
if let Some(reference) = doc.semantics.reference_at(offset) {
|
||||
return Some(reference.name_span);
|
||||
}
|
||||
doc.semantics.symbol_at(offset).and_then(|id| doc.semantics.symbol(id)).map(|s| s.name_span)
|
||||
}
|
||||
|
||||
/// A markdown hover card highlighting `span` in the hovered document.
|
||||
fn markdown(doc: &Document, value: String, span: TextRange) -> Hover {
|
||||
Hover {
|
||||
contents: HoverContents::Markup(MarkupContent { kind: MarkupKind::Markdown, value }),
|
||||
range: Some(doc.positions().range(span)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::uri::path_to_uri;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
|
||||
fn document(text: &str) -> (Workspace, Uri) {
|
||||
let uri = Uri::from_str("file:///rtl/m.sv").expect("uri");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
fn at(text: &str, needle: &str) -> u32 {
|
||||
text.find(needle).expect("needle present") as u32
|
||||
}
|
||||
|
||||
fn text_of(hover: &Hover) -> String {
|
||||
match &hover.contents {
|
||||
HoverContents::Markup(m) => m.value.clone(),
|
||||
other => panic!("expected markup, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn temp_dir(tag: &str) -> PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("vfmt_server_hover_{tag}_{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).expect("temp dir");
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hovering_a_macro_usage_shows_its_body() {
|
||||
let text = "`define WIDTH 8\nmodule m;\n wire [`WIDTH-1:0] a;\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
let hover = hover(&ws, &uri, at(text, "[`WIDTH") + 2).expect("hover");
|
||||
let body = text_of(&hover);
|
||||
assert!(body.contains("`define WIDTH 8"), "got {body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hovering_a_function_like_macro_shows_its_signature() {
|
||||
let text = "`define MAX(a, b) ((a) > (b) ? (a) : (b))\nmodule m;\n wire x = `MAX(1, 2);\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
let hover = hover(&ws, &uri, at(text, "`MAX(1")).expect("hover");
|
||||
let body = text_of(&hover);
|
||||
assert!(body.contains("`define MAX(a, b)"), "got {body}");
|
||||
assert!(body.contains("? (a) : (b)"), "got {body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_undefined_macro_says_so_rather_than_returning_nothing() {
|
||||
let text = "module m;\n wire x = `NOPE;\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
let hover = hover(&ws, &uri, at(text, "`NOPE")).expect("hover");
|
||||
assert!(text_of(&hover).contains("no definition found"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_workspace_define_is_found_when_this_file_does_not_define_it() {
|
||||
let dir = temp_dir("define");
|
||||
fs::write(dir.join("defs.svh"), "`define WIDTH 8\n").expect("write");
|
||||
let top_path = dir.join("top.sv");
|
||||
let top_text = "module top;\n wire [`WIDTH-1:0] a;\nendmodule\n";
|
||||
fs::write(&top_path, top_text).expect("write");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![dir.clone()]);
|
||||
let uri = path_to_uri(&top_path).expect("uri");
|
||||
ws.set_document(uri.clone(), top_text.to_string());
|
||||
|
||||
let hover = hover(&ws, &uri, at(top_text, "`WIDTH")).expect("hover");
|
||||
let body = text_of(&hover);
|
||||
assert!(body.contains("`define WIDTH 8"), "got {body}");
|
||||
assert!(body.contains("defs.svh:1"), "the file and line: got {body}");
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_workspace_definitions_are_all_listed() {
|
||||
let dir = temp_dir("dupdefine");
|
||||
fs::write(dir.join("a.svh"), "`define W 8\n").expect("write");
|
||||
fs::write(dir.join("b.svh"), "`define W 16\n").expect("write");
|
||||
let top_path = dir.join("top.sv");
|
||||
let top_text = "module top;\n wire [`W-1:0] a;\nendmodule\n";
|
||||
fs::write(&top_path, top_text).expect("write");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![dir.clone()]);
|
||||
let uri = path_to_uri(&top_path).expect("uri");
|
||||
ws.set_document(uri.clone(), top_text.to_string());
|
||||
|
||||
let body = text_of(&hover(&ws, &uri, at(top_text, "`W-")).expect("hover"));
|
||||
assert!(body.contains("is defined 2 times"), "got {body}");
|
||||
assert!(body.contains("`define W 8"), "got {body}");
|
||||
assert!(body.contains("`define W 16"), "got {body}");
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hovering_a_use_shows_its_declaration() {
|
||||
let text = "module m;\n localparam WIDTH = 8;\n wire [WIDTH-1:0] a;\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
let body = text_of(&hover(&ws, &uri, at(text, "[WIDTH") + 1).expect("hover"));
|
||||
assert!(body.contains("**parameter**"), "got {body}");
|
||||
assert!(body.contains("localparam WIDTH = 8;"), "the decl snippet: got {body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hovering_a_declaration_shows_its_own_info() {
|
||||
let text = "module top;\n wire a;\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
let body = text_of(&hover(&ws, &uri, at(text, "top")).expect("hover"));
|
||||
assert!(body.contains("**module** `top`"), "got {body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hovering_a_cross_file_module_names_its_file() {
|
||||
let dir = temp_dir("xhover");
|
||||
fs::write(dir.join("sub.sv"), "module sub (input clk);\nendmodule\n").expect("write");
|
||||
let top_path = dir.join("top.sv");
|
||||
let top_text = "module top;\n sub u (.clk(1'b0));\nendmodule\n";
|
||||
fs::write(&top_path, top_text).expect("write");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![dir.clone()]);
|
||||
let uri = path_to_uri(&top_path).expect("uri");
|
||||
ws.set_document(uri.clone(), top_text.to_string());
|
||||
|
||||
let body = text_of(&hover(&ws, &uri, at(top_text, "sub u")).expect("hover"));
|
||||
assert!(body.contains("**module**"), "got {body}");
|
||||
assert!(body.contains("sub.sv:1"), "got {body}");
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hovering_whitespace_returns_nothing() {
|
||||
let text = "module m;\n\n wire a;\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
assert!(hover(&ws, &uri, at(text, "\n\n") + 1).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_name_stops_at_its_argument_list() {
|
||||
let text = "`define M(a) a\nmodule m;\n wire x = `M(1);\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let token = doc.tokens.iter().find(|t| t.is_macro()).expect("a macro usage token");
|
||||
assert_eq!(macro_name(token), Some("M"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
//! Turning a `(file, byte span)` pair into an LSP `Location`.
|
||||
//!
|
||||
//! The workspace index deliberately keeps no file contents
|
||||
//! (`docs/features/workspace-index/README.md`), so a span in another file has
|
||||
//! to be converted against that file's text, fetched here with the same
|
||||
//! open-buffer-beats-disk precedence the index rebuild uses.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_types::Location;
|
||||
use vlog_parser::{LineIndex, TextRange};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::state::Workspace;
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
/// The location of a byte span inside a workspace file.
|
||||
pub fn location(ws: &Workspace, path: &Path, span: TextRange) -> Option<Location> {
|
||||
let uri = path_to_uri(path)?;
|
||||
let text = ws.text_of(path)?;
|
||||
let index = LineIndex::new(&text);
|
||||
let range = Positions::new(&text, &index).range(span);
|
||||
Some(Location { uri, range })
|
||||
}
|
||||
|
||||
/// The 1-based line a byte offset falls on, for hover text that names a file
|
||||
/// and a line rather than jumping to it.
|
||||
pub fn line_number(ws: &Workspace, path: &Path, offset: u32) -> Option<u32> {
|
||||
let text = ws.text_of(path)?;
|
||||
Some(LineIndex::new(&text).line_col(offset).0)
|
||||
}
|
||||
|
||||
/// How a file is named in hover text: its file name, which is what a Verilog
|
||||
/// author recognizes, since absolute paths in a hover card are unreadable.
|
||||
pub fn display_name(path: &Path) -> String {
|
||||
path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string()
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
//! `vfmt-server` — the vfmt language server, speaking LSP over stdio.
|
||||
//!
|
||||
//! One binary for every editor: VS Code through a thin extension, Vim/Neovim
|
||||
//! through built-in LSP config. No editor-specific logic lives below the
|
||||
//! protocol layer, and no language logic lives in it — every answer comes from
|
||||
//! `vlog_parser`, `vlog_semantic` or `vlog_formatter`. See
|
||||
//! `docs/features/vfmt-server/README.md`.
|
||||
|
||||
mod convert;
|
||||
mod diagnostics;
|
||||
mod format;
|
||||
mod hover;
|
||||
mod locate;
|
||||
mod nav;
|
||||
mod server;
|
||||
mod state;
|
||||
mod symbols;
|
||||
mod tokens;
|
||||
mod uri;
|
||||
|
||||
use std::error::Error;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use lsp_server::Connection;
|
||||
use lsp_types::{
|
||||
InitializeParams, OneOf, PositionEncodingKind, SemanticTokensFullOptions, SemanticTokensLegend,
|
||||
SemanticTokensOptions, SemanticTokensServerCapabilities, ServerCapabilities,
|
||||
TextDocumentSyncCapability, TextDocumentSyncKind, WorkDoneProgressOptions,
|
||||
};
|
||||
|
||||
use crate::server::Server;
|
||||
use crate::uri::uri_to_path;
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
let (connection, io_threads) = Connection::stdio();
|
||||
|
||||
let (id, params) = connection.initialize_start()?;
|
||||
// A client that sends params we cannot read still gets a server; every
|
||||
// field we want is optional anyway.
|
||||
let params: InitializeParams = serde_json::from_value(params).unwrap_or_default();
|
||||
let roots = workspace_roots(¶ms);
|
||||
connection.initialize_finish(id, serde_json::to_value(initialize_result())?)?;
|
||||
|
||||
Server::new(connection, roots).run()?;
|
||||
io_threads.join()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What the server tells the client it can do. Nothing is advertised that is
|
||||
/// not implemented: a capability an editor discovers to be a lie is worse than
|
||||
/// one it never had.
|
||||
fn capabilities() -> ServerCapabilities {
|
||||
ServerCapabilities {
|
||||
// The protocol default, and what the conversion in `convert.rs`
|
||||
// implements. Stated rather than left implicit.
|
||||
position_encoding: Some(PositionEncodingKind::UTF16),
|
||||
text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::FULL)),
|
||||
document_formatting_provider: Some(OneOf::Left(true)),
|
||||
definition_provider: Some(OneOf::Left(true)),
|
||||
references_provider: Some(OneOf::Left(true)),
|
||||
hover_provider: Some(lsp_types::HoverProviderCapability::Simple(true)),
|
||||
document_symbol_provider: Some(OneOf::Left(true)),
|
||||
workspace_symbol_provider: Some(OneOf::Left(true)),
|
||||
semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensOptions(
|
||||
SemanticTokensOptions {
|
||||
work_done_progress_options: WorkDoneProgressOptions::default(),
|
||||
legend: SemanticTokensLegend {
|
||||
token_types: tokens::token_types(),
|
||||
token_modifiers: tokens::token_modifiers(),
|
||||
},
|
||||
range: None,
|
||||
full: Some(SemanticTokensFullOptions::Bool(true)),
|
||||
},
|
||||
)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn initialize_result() -> lsp_types::InitializeResult {
|
||||
lsp_types::InitializeResult {
|
||||
capabilities: capabilities(),
|
||||
server_info: Some(lsp_types::ServerInfo {
|
||||
name: "vfmt-server".to_string(),
|
||||
version: Some(env!("CARGO_PKG_VERSION").to_string()),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The directories to index: the client's workspace folders, or the
|
||||
/// deprecated single root when that is all it sent.
|
||||
fn workspace_roots(params: &InitializeParams) -> Vec<PathBuf> {
|
||||
if let Some(folders) = ¶ms.workspace_folders {
|
||||
let roots: Vec<PathBuf> = folders.iter().filter_map(|f| uri_to_path(&f.uri)).collect();
|
||||
if !roots.is_empty() {
|
||||
return roots;
|
||||
}
|
||||
}
|
||||
#[allow(deprecated)] // `root_uri` is how older clients name the workspace.
|
||||
params.root_uri.as_ref().and_then(uri_to_path).into_iter().collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_advertised_capability_is_implemented() {
|
||||
let caps = capabilities();
|
||||
assert!(caps.document_formatting_provider.is_some());
|
||||
assert!(caps.definition_provider.is_some());
|
||||
assert!(caps.references_provider.is_some());
|
||||
assert!(caps.hover_provider.is_some());
|
||||
assert!(caps.document_symbol_provider.is_some());
|
||||
assert!(caps.workspace_symbol_provider.is_some());
|
||||
assert!(caps.semantic_tokens_provider.is_some());
|
||||
// Deliberately absent until the engines exist — see the README.
|
||||
assert!(caps.document_range_formatting_provider.is_none(), "no --lines yet");
|
||||
assert!(caps.completion_provider.is_none());
|
||||
assert!(caps.rename_provider.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_legend_and_the_encoder_agree_on_length() {
|
||||
// The wire format carries indices into these arrays, so a mismatch
|
||||
// between the legend and the encoder is a silent mis-colouring.
|
||||
assert_eq!(tokens::token_types().len(), 14);
|
||||
assert_eq!(tokens::token_modifiers().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf16_is_advertised_because_that_is_what_convert_implements() {
|
||||
assert_eq!(capabilities().position_encoding, Some(PositionEncodingKind::UTF16));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
//! `textDocument/definition` and `textDocument/references`.
|
||||
|
||||
use lsp_types::{Location, Uri};
|
||||
use vlog_semantic::Definition;
|
||||
|
||||
use crate::locate::location;
|
||||
use crate::state::Workspace;
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
/// Go-to-definition, through both layers: the in-file symbol table first, then
|
||||
/// the workspace overlay. An ambiguous workspace answer returns **every**
|
||||
/// location rather than guessing — LSP accepts a list, and the index's
|
||||
/// duplicate-name policy says the guess would be a coin flip.
|
||||
pub fn definition(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<Location> {
|
||||
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
||||
match doc.external.definition_of(&doc.semantics, offset) {
|
||||
Some(Definition::Local(symbol)) => {
|
||||
if symbol.name_span.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
match path_to_uri_or_self(ws, uri) {
|
||||
Some(target) => {
|
||||
vec![Location { uri: target, range: doc.positions().range(symbol.name_span) }]
|
||||
}
|
||||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
Some(Definition::External(defs)) => defs
|
||||
.iter()
|
||||
.filter_map(|def| {
|
||||
let path = ws.index().path(def.file)?;
|
||||
location(ws, path, def.name_span)
|
||||
})
|
||||
.collect(),
|
||||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The URI to report a local definition against — the document's own.
|
||||
fn path_to_uri_or_self(ws: &Workspace, uri: &Uri) -> Option<Uri> {
|
||||
match ws.document(uri).and_then(|d| d.path.clone()) {
|
||||
Some(path) => path_to_uri(&path),
|
||||
// An `untitled:` buffer has no path but is still its own document.
|
||||
None => Some(uri.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Find-all-references, within this file.
|
||||
///
|
||||
/// Cross-file references are out of scope this round: answering them means
|
||||
/// resolving every *other* file's references into this one, which is an
|
||||
/// inverted index the workspace layer does not build. See the feature
|
||||
/// README's Status/TODO.
|
||||
pub fn references(
|
||||
ws: &Workspace,
|
||||
uri: &Uri,
|
||||
offset: u32,
|
||||
include_declaration: bool,
|
||||
) -> Vec<Location> {
|
||||
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
||||
// The cursor may sit on a use or on the declaration itself; both lead to
|
||||
// the same symbol.
|
||||
let symbol_id = doc
|
||||
.semantics
|
||||
.reference_at(offset)
|
||||
.and_then(|r| r.resolved())
|
||||
.or_else(|| doc.semantics.symbol_at(offset));
|
||||
let Some(symbol_id) = symbol_id else { return Vec::new() };
|
||||
|
||||
let Some(target) = path_to_uri_or_self(ws, uri) else { return Vec::new() };
|
||||
let positions = doc.positions();
|
||||
let mut spans: Vec<_> =
|
||||
doc.semantics.references_of(symbol_id).iter().map(|r| r.name_span).collect();
|
||||
if include_declaration {
|
||||
if let Some(symbol) = doc.semantics.symbol(symbol_id) {
|
||||
spans.push(symbol.name_span);
|
||||
}
|
||||
}
|
||||
spans.retain(|s| !s.is_empty());
|
||||
spans.sort_by_key(|s| s.start);
|
||||
spans.dedup();
|
||||
spans.into_iter().map(|s| Location { uri: target.clone(), range: positions.range(s) }).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
|
||||
fn document(text: &str) -> (Workspace, Uri) {
|
||||
let uri = Uri::from_str("file:///rtl/m.sv").expect("uri");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
/// The byte offset of the first occurrence of `needle` in `text`.
|
||||
fn at(text: &str, needle: &str) -> u32 {
|
||||
text.find(needle).expect("needle present") as u32
|
||||
}
|
||||
|
||||
fn temp_dir(tag: &str) -> PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("vfmt_server_nav_{tag}_{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).expect("temp dir");
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_use_jumps_to_its_declaration_in_the_same_file() {
|
||||
let text = "module m;\n wire a;\n assign a = 1;\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
let offset = at(text, "assign a") + 7;
|
||||
let locations = definition(&ws, &uri, offset);
|
||||
assert_eq!(locations.len(), 1);
|
||||
assert_eq!(locations[0].range.start.line, 1, "the `wire a;` line");
|
||||
assert_eq!(locations[0].range.start.character, 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cursor_on_a_declaration_resolves_to_itself() {
|
||||
let text = "module m;\n wire a;\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
let locations = definition(&ws, &uri, at(text, "wire a") + 5);
|
||||
assert_eq!(locations.len(), 1);
|
||||
assert_eq!(locations[0].range.start.line, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_nothing_declares_has_no_definition() {
|
||||
let text = "module m;\n assign x = 1;\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
assert!(definition(&ws, &uri, at(text, "x")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_finds_every_use_and_honors_include_declaration() {
|
||||
let text = "module m;\n wire a;\n assign a = 1;\n assign b = a;\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
let offset = at(text, "wire a") + 5;
|
||||
|
||||
let without = references(&ws, &uri, offset, false);
|
||||
assert_eq!(without.len(), 2, "two uses");
|
||||
assert_eq!(without[0].range.start.line, 2);
|
||||
assert_eq!(without[1].range.start.line, 3);
|
||||
|
||||
let with = references(&ws, &uri, offset, true);
|
||||
assert_eq!(with.len(), 3, "the declaration is added");
|
||||
assert_eq!(with[0].range.start.line, 1, "declaration sorts first");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_work_from_a_use_as_well_as_from_the_declaration() {
|
||||
let text = "module m;\n wire a;\n assign a = 1;\n assign b = a;\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
let from_use = references(&ws, &uri, at(text, "assign a") + 7, false);
|
||||
assert_eq!(from_use.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_positions_are_utf16() {
|
||||
let text = "module m;\n wire a; // é 🎉\n assign a = 1;\nendmodule\n";
|
||||
let (ws, uri) = document(text);
|
||||
let locations = references(&ws, &uri, at(text, "wire a") + 5, false);
|
||||
assert_eq!(locations.len(), 1);
|
||||
assert_eq!(locations[0].range.start.character, 9);
|
||||
assert_eq!(locations[0].range.end.character, 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instantiation_jumps_into_another_file() {
|
||||
let dir = temp_dir("xfile");
|
||||
let sub = dir.join("sub.sv");
|
||||
fs::write(&sub, "module sub (input clk);\nendmodule\n").expect("write");
|
||||
let top_path = dir.join("top.sv");
|
||||
let top_text = "module top;\n sub u_sub (.clk(1'b0));\nendmodule\n";
|
||||
fs::write(&top_path, top_text).expect("write");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![dir.clone()]);
|
||||
let uri = path_to_uri(&top_path).expect("uri");
|
||||
ws.set_document(uri.clone(), top_text.to_string());
|
||||
|
||||
let locations = definition(&ws, &uri, at(top_text, "sub u_sub"));
|
||||
assert_eq!(locations.len(), 1, "the module in sub.sv");
|
||||
assert_eq!(locations[0].uri, path_to_uri(&sub).expect("uri"));
|
||||
assert_eq!(locations[0].range.start.line, 0);
|
||||
assert_eq!(locations[0].range.start.character, 7, "the name `sub`");
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ambiguous_workspace_name_returns_every_location() {
|
||||
let dir = temp_dir("ambig");
|
||||
for name in ["a.sv", "b.sv"] {
|
||||
fs::write(dir.join(name), "module dup;\nendmodule\n").expect("write");
|
||||
}
|
||||
let top_path = dir.join("top.sv");
|
||||
let top_text = "module top;\n dup u (.*);\nendmodule\n";
|
||||
fs::write(&top_path, top_text).expect("write");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![dir.clone()]);
|
||||
let uri = path_to_uri(&top_path).expect("uri");
|
||||
ws.set_document(uri.clone(), top_text.to_string());
|
||||
|
||||
let locations = definition(&ws, &uri, at(top_text, "dup u"));
|
||||
assert_eq!(locations.len(), 2, "both declarations, not a guess");
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_import_resolves_into_the_packages_file() {
|
||||
let dir = temp_dir("pkg");
|
||||
let pkg = dir.join("p_pkg.sv");
|
||||
fs::write(&pkg, "package p;\n localparam WIDTH = 8;\nendpackage\n").expect("write");
|
||||
let top_path = dir.join("top.sv");
|
||||
let top_text = "module top;\n import p::*;\n wire [WIDTH-1:0] a;\nendmodule\n";
|
||||
fs::write(&top_path, top_text).expect("write");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![dir.clone()]);
|
||||
let uri = path_to_uri(&top_path).expect("uri");
|
||||
ws.set_document(uri.clone(), top_text.to_string());
|
||||
|
||||
let locations = definition(&ws, &uri, at(top_text, "WIDTH-1"));
|
||||
assert_eq!(locations.len(), 1, "WIDTH is declared in p_pkg.sv");
|
||||
assert_eq!(locations[0].uri, path_to_uri(&pkg).expect("uri"));
|
||||
assert_eq!(locations[0].range.start.line, 1);
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
//! The request loop: one message in, one response out, on one thread.
|
||||
//!
|
||||
//! `lsp-server` runs two I/O threads of its own and hands this loop framed
|
||||
//! messages over a channel. Everything below is synchronous and un-cancellable
|
||||
//! — Verilog files are small, every handler is milliseconds, and a worker pool
|
||||
//! would buy nothing yet. See `docs/features/vfmt-server/README.md`.
|
||||
|
||||
use std::error::Error;
|
||||
|
||||
use lsp_server::{Connection, ExtractError, Message, Notification, Request, RequestId, Response};
|
||||
use lsp_types::notification::{
|
||||
DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument, DidSaveTextDocument,
|
||||
LogMessage, Notification as _, PublishDiagnostics, ShowMessage,
|
||||
};
|
||||
use lsp_types::request::{
|
||||
DocumentSymbolRequest, Formatting, GotoDefinition, HoverRequest, References, Request as _,
|
||||
SemanticTokensFullRequest, WorkspaceSymbolRequest,
|
||||
};
|
||||
use lsp_types::{
|
||||
DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams,
|
||||
DidSaveTextDocumentParams, DocumentFormattingParams, DocumentSymbolParams,
|
||||
DocumentSymbolResponse, GotoDefinitionParams, GotoDefinitionResponse, HoverParams,
|
||||
LogMessageParams, MessageType, Position, PublishDiagnosticsParams, ReferenceParams,
|
||||
SemanticTokensParams, SemanticTokensResult, ShowMessageParams, Uri, WorkspaceSymbolParams,
|
||||
WorkspaceSymbolResponse,
|
||||
};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::state::Workspace;
|
||||
use crate::{diagnostics, format, hover, nav, symbols, tokens};
|
||||
|
||||
/// Everything the server owns.
|
||||
pub struct Server {
|
||||
connection: Connection,
|
||||
workspace: Workspace,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
pub fn new(connection: Connection, roots: Vec<std::path::PathBuf>) -> Server {
|
||||
let mut workspace = Workspace::default();
|
||||
workspace.open_roots(roots);
|
||||
Server { connection, workspace }
|
||||
}
|
||||
|
||||
/// Receive until the client shuts us down or the channel closes.
|
||||
pub fn run(&mut self) -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
while let Ok(message) = self.connection.receiver.recv() {
|
||||
match message {
|
||||
Message::Request(request) => {
|
||||
if self.connection.handle_shutdown(&request)? {
|
||||
return Ok(());
|
||||
}
|
||||
let response = self.request(request);
|
||||
self.connection.sender.send(Message::Response(response))?;
|
||||
}
|
||||
Message::Notification(notification) => self.notification(notification),
|
||||
// Nothing is requested *of* the client except the messages
|
||||
// below, which want no answer.
|
||||
Message::Response(_) => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// requests
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn request(&mut self, request: Request) -> Response {
|
||||
let id = request.id.clone();
|
||||
let method = request.method.clone();
|
||||
let result = match method.as_str() {
|
||||
Formatting::METHOD => decode(request).and_then(|p| self.formatting(p)),
|
||||
HoverRequest::METHOD => decode(request).and_then(|p: HoverParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
self.offset(&uri, position)
|
||||
.map(|offset| hover::hover(&self.workspace, &uri, offset))
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
}),
|
||||
GotoDefinition::METHOD => decode(request).and_then(|p: GotoDefinitionParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
let locations = self
|
||||
.offset(&uri, position)
|
||||
.map(|offset| nav::definition(&self.workspace, &uri, offset))
|
||||
.unwrap_or_default();
|
||||
to_value(GotoDefinitionResponse::Array(locations))
|
||||
}),
|
||||
References::METHOD => decode(request).and_then(|p: ReferenceParams| {
|
||||
let include = p.context.include_declaration;
|
||||
let at = p.text_document_position;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
let locations = self
|
||||
.offset(&uri, position)
|
||||
.map(|offset| nav::references(&self.workspace, &uri, offset, include))
|
||||
.unwrap_or_default();
|
||||
to_value(locations)
|
||||
}),
|
||||
SemanticTokensFullRequest::METHOD => {
|
||||
decode(request).and_then(|p: SemanticTokensParams| {
|
||||
match self.workspace.document(&p.text_document.uri) {
|
||||
Some(doc) => {
|
||||
to_value(SemanticTokensResult::Tokens(tokens::semantic_tokens(doc)))
|
||||
}
|
||||
None => Ok(Value::Null),
|
||||
}
|
||||
})
|
||||
}
|
||||
DocumentSymbolRequest::METHOD => decode(request).and_then(|p: DocumentSymbolParams| {
|
||||
match self.workspace.document(&p.text_document.uri) {
|
||||
Some(doc) => {
|
||||
to_value(DocumentSymbolResponse::Nested(symbols::document_symbols(doc)))
|
||||
}
|
||||
None => Ok(Value::Null),
|
||||
}
|
||||
}),
|
||||
WorkspaceSymbolRequest::METHOD => {
|
||||
decode(request).and_then(|p: WorkspaceSymbolParams| {
|
||||
to_value(WorkspaceSymbolResponse::Flat(symbols::workspace_symbols(
|
||||
&self.workspace,
|
||||
&p.query,
|
||||
)))
|
||||
})
|
||||
}
|
||||
_ => Err(Failure::MethodNotFound(method)),
|
||||
};
|
||||
match result {
|
||||
Ok(value) => Response::new_ok(id, value),
|
||||
Err(failure) => failure.into_response(id),
|
||||
}
|
||||
}
|
||||
|
||||
fn formatting(&mut self, params: DocumentFormattingParams) -> Result<Value, Failure> {
|
||||
let uri = params.text_document.uri;
|
||||
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
||||
match format::formatting(doc, ¶ms.options) {
|
||||
// A whole-document edit, or none when nothing changed.
|
||||
Ok(Some(edit)) => to_value(vec![edit]),
|
||||
Ok(None) => to_value(Vec::<lsp_types::TextEdit>::new()),
|
||||
// The formatter refused. It never emits partial output (CLAUDE.md
|
||||
// invariant #1), so neither do we: no edit, and the reason goes to
|
||||
// the user as a message. Diagnostics are not used for this — they
|
||||
// belong to the parse pass and are cleared on the next keystroke,
|
||||
// which would erase an explicit format failure the user asked for.
|
||||
Err(message) => {
|
||||
self.show_message(MessageType::ERROR, format!("vfmt: cannot format — {message}"));
|
||||
to_value(Vec::<lsp_types::TextEdit>::new())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// notifications
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn notification(&mut self, notification: Notification) {
|
||||
let method = notification.method.clone();
|
||||
match method.as_str() {
|
||||
DidOpenTextDocument::METHOD => {
|
||||
if let Ok(p) = extract::<DidOpenTextDocumentParams>(notification) {
|
||||
let uri = p.text_document.uri;
|
||||
self.workspace.set_document(uri.clone(), p.text_document.text);
|
||||
self.publish(&uri);
|
||||
}
|
||||
}
|
||||
DidChangeTextDocument::METHOD => {
|
||||
if let Ok(p) = extract::<DidChangeTextDocumentParams>(notification) {
|
||||
// Full-text sync: the last change carries the whole buffer.
|
||||
if let Some(change) = p.content_changes.into_iter().next_back() {
|
||||
let uri = p.text_document.uri;
|
||||
self.workspace.set_document(uri.clone(), change.text);
|
||||
self.publish(&uri);
|
||||
}
|
||||
}
|
||||
}
|
||||
DidSaveTextDocument::METHOD => {
|
||||
if let Ok(p) = extract::<DidSaveTextDocumentParams>(notification) {
|
||||
if let Some(text) = p.text {
|
||||
self.workspace.set_document(p.text_document.uri.clone(), text);
|
||||
}
|
||||
// The index is rebuilt on save and nowhere else; the
|
||||
// staleness window that opens is in the feature README.
|
||||
self.workspace.rebuild_index();
|
||||
for uri in self.workspace.open_uris() {
|
||||
self.publish(&uri);
|
||||
}
|
||||
}
|
||||
}
|
||||
DidCloseTextDocument::METHOD => {
|
||||
if let Ok(p) = extract::<DidCloseTextDocumentParams>(notification) {
|
||||
let uri = p.text_document.uri;
|
||||
self.workspace.close_document(&uri);
|
||||
// Clear what we drew: the buffer is gone.
|
||||
self.send_diagnostics(uri, Vec::new());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// outgoing
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn publish(&self, uri: &Uri) {
|
||||
let Some(doc) = self.workspace.document(uri) else { return };
|
||||
self.send_diagnostics(uri.clone(), diagnostics::diagnostics(doc));
|
||||
}
|
||||
|
||||
fn send_diagnostics(&self, uri: Uri, diagnostics: Vec<lsp_types::Diagnostic>) {
|
||||
let params = PublishDiagnosticsParams { uri, diagnostics, version: None };
|
||||
self.notify(PublishDiagnostics::METHOD, params);
|
||||
}
|
||||
|
||||
fn show_message(&self, typ: MessageType, message: String) {
|
||||
self.notify(ShowMessage::METHOD, ShowMessageParams { typ, message: message.clone() });
|
||||
self.notify(LogMessage::METHOD, LogMessageParams { typ, message });
|
||||
}
|
||||
|
||||
fn notify(&self, method: &str, params: impl serde::Serialize) {
|
||||
let notification = Notification::new(method.to_string(), params);
|
||||
// A closed channel means the client is gone; there is nobody left to
|
||||
// report the failure to.
|
||||
let _ = self.connection.sender.send(Message::Notification(notification));
|
||||
}
|
||||
|
||||
/// The byte offset an LSP position names in an open document.
|
||||
fn offset(&self, uri: &Uri, position: Position) -> Option<u32> {
|
||||
self.workspace.document(uri).map(|doc| doc.positions().offset(position))
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// decoding and failures
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// Why a request could not be answered, in the protocol's own terms.
|
||||
enum Failure {
|
||||
MethodNotFound(String),
|
||||
InvalidParams(String),
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
impl Failure {
|
||||
fn into_response(self, id: RequestId) -> Response {
|
||||
let (code, message) = match self {
|
||||
Failure::MethodNotFound(method) => (
|
||||
lsp_server::ErrorCode::MethodNotFound as i32,
|
||||
format!("unhandled method: {method}"),
|
||||
),
|
||||
Failure::InvalidParams(message) => {
|
||||
(lsp_server::ErrorCode::InvalidParams as i32, message)
|
||||
}
|
||||
Failure::Internal(message) => (lsp_server::ErrorCode::InternalError as i32, message),
|
||||
};
|
||||
Response::new_err(id, code, message)
|
||||
}
|
||||
}
|
||||
|
||||
fn decode<P: DeserializeOwned>(request: Request) -> Result<P, Failure> {
|
||||
serde_json::from_value(request.params).map_err(|e| Failure::InvalidParams(e.to_string()))
|
||||
}
|
||||
|
||||
fn to_value(value: impl serde::Serialize) -> Result<Value, Failure> {
|
||||
serde_json::to_value(value).map_err(|e| Failure::Internal(e.to_string()))
|
||||
}
|
||||
|
||||
/// A notification's params, or `Err` when they do not parse — a malformed
|
||||
/// notification is dropped, because there is no id to answer it on.
|
||||
fn extract<P: DeserializeOwned>(
|
||||
notification: Notification,
|
||||
) -> Result<P, ExtractError<Notification>> {
|
||||
let method = notification.method.clone();
|
||||
notification.extract(&method)
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
//! What the server remembers: one analysis per open buffer, one index for the
|
||||
//! workspace. The invalidation rules are in
|
||||
//! `docs/features/vfmt-server/README.md`; the short version is that a buffer's
|
||||
//! analysis is rebuilt on every change and the index only on save.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lsp_types::Uri;
|
||||
use vlog_parser::defines::{collect_defines, DefineTable};
|
||||
use vlog_parser::token::Token;
|
||||
use vlog_parser::{parse_source_tolerant, tokenize, LineIndex, ParseDiagnostic};
|
||||
use vlog_semantic::{analyze, resolve_external, ExternalResolutions, Semantics, WorkspaceIndex};
|
||||
|
||||
use crate::convert::Positions;
|
||||
use crate::uri::uri_to_path;
|
||||
|
||||
/// How deep the workspace walk descends. A plain recursive walk has no cycle
|
||||
/// detection; a cap is the cheap way to survive a symlink loop.
|
||||
const MAX_WALK_DEPTH: u32 = 64;
|
||||
|
||||
/// The file extensions a Verilog workspace is made of.
|
||||
const SOURCE_EXTENSIONS: [&str; 4] = ["v", "sv", "vh", "svh"];
|
||||
|
||||
/// How many `workspace/symbol` hits are returned. Each one costs a file read
|
||||
/// to turn its byte span into a line, so an unbounded answer to the empty
|
||||
/// query would read the whole workspace.
|
||||
pub const WORKSPACE_SYMBOL_LIMIT: usize = 256;
|
||||
|
||||
/// One open buffer, fully analyzed. Every field is derived from `text`, so a
|
||||
/// change throws the whole thing away and builds a new one.
|
||||
pub struct Document {
|
||||
/// The buffer's path, absent for a `untitled:` document.
|
||||
pub path: Option<PathBuf>,
|
||||
pub text: String,
|
||||
pub line_index: LineIndex,
|
||||
/// Empty when the file does not lex — the lexer is all-or-nothing.
|
||||
pub tokens: Vec<Token>,
|
||||
pub diagnostics: Vec<ParseDiagnostic>,
|
||||
pub semantics: Semantics,
|
||||
pub defines: DefineTable,
|
||||
/// The workspace layer's answers for this file's external candidates.
|
||||
pub external: ExternalResolutions,
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// Analyze a buffer from scratch against the current workspace index.
|
||||
pub fn new(path: Option<PathBuf>, text: String, index: &WorkspaceIndex) -> Document {
|
||||
let tokens = tokenize(&text).unwrap_or_default();
|
||||
let defines = collect_defines(&tokens);
|
||||
let (tree, diagnostics) = parse_source_tolerant(&text);
|
||||
let semantics = analyze(&tree, &text);
|
||||
let external = resolve_external(&semantics, index);
|
||||
let line_index = LineIndex::new(&text);
|
||||
Document { path, text, line_index, tokens, diagnostics, semantics, defines, external }
|
||||
}
|
||||
|
||||
/// This document's position converter.
|
||||
pub fn positions(&self) -> Positions<'_> {
|
||||
Positions::new(&self.text, &self.line_index)
|
||||
}
|
||||
|
||||
/// Re-run only the workspace overlay, after the index was rebuilt. The
|
||||
/// single-file analysis is unaffected by other files, by construction.
|
||||
pub fn refresh_overlay(&mut self, index: &WorkspaceIndex) {
|
||||
self.external = resolve_external(&self.semantics, index);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every open buffer plus the workspace index they are resolved against.
|
||||
#[derive(Default)]
|
||||
pub struct Workspace {
|
||||
docs: HashMap<Uri, Document>,
|
||||
roots: Vec<PathBuf>,
|
||||
index: WorkspaceIndex,
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
/// Adopt the workspace roots and build the index for the first time.
|
||||
pub fn open_roots(&mut self, roots: Vec<PathBuf>) {
|
||||
self.roots = roots;
|
||||
self.rebuild_index();
|
||||
}
|
||||
|
||||
pub fn index(&self) -> &WorkspaceIndex {
|
||||
&self.index
|
||||
}
|
||||
|
||||
pub fn document(&self, uri: &Uri) -> Option<&Document> {
|
||||
self.docs.get(uri)
|
||||
}
|
||||
|
||||
/// Replace a buffer's contents and re-analyze it.
|
||||
pub fn set_document(&mut self, uri: Uri, text: String) {
|
||||
let path = uri_to_path(&uri);
|
||||
let doc = Document::new(path, text, &self.index);
|
||||
self.docs.insert(uri, doc);
|
||||
}
|
||||
|
||||
pub fn close_document(&mut self, uri: &Uri) {
|
||||
self.docs.remove(uri);
|
||||
}
|
||||
|
||||
/// Every open buffer's URI, for republishing diagnostics after a rebuild.
|
||||
pub fn open_uris(&self) -> Vec<Uri> {
|
||||
self.docs.keys().cloned().collect()
|
||||
}
|
||||
|
||||
/// Re-scan the roots and rebuild the index, then refresh every open
|
||||
/// buffer's overlay. Called on `initialize` and on every `didSave`.
|
||||
pub fn rebuild_index(&mut self) {
|
||||
let mut sources: Vec<(PathBuf, String)> = Vec::new();
|
||||
for path in self.source_files() {
|
||||
if let Ok(text) = fs::read_to_string(&path) {
|
||||
sources.push((path, text));
|
||||
}
|
||||
}
|
||||
// Open buffers override what is on disk, and contribute themselves
|
||||
// when they are not on disk at all.
|
||||
for doc in self.docs.values() {
|
||||
let Some(path) = doc.path.clone() else { continue };
|
||||
sources.retain(|(p, _)| p != &path);
|
||||
sources.push((path, doc.text.clone()));
|
||||
}
|
||||
self.index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
||||
for doc in self.docs.values_mut() {
|
||||
doc.refresh_overlay(&self.index);
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of a workspace file: the open buffer if there is one, else
|
||||
/// what is on disk. Same precedence the index rebuild uses, so a location
|
||||
/// is never computed against text the index did not see.
|
||||
pub fn text_of(&self, path: &Path) -> Option<String> {
|
||||
let open = self.docs.values().find(|d| d.path.as_deref() == Some(path));
|
||||
match open {
|
||||
Some(doc) => Some(doc.text.clone()),
|
||||
None => fs::read_to_string(path).ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every source file under the roots, walked plainly — no `.gitignore`,
|
||||
/// no excludes (see the feature README's Handshakes).
|
||||
fn source_files(&self) -> Vec<PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
for root in &self.roots {
|
||||
walk(root, 0, &mut out);
|
||||
}
|
||||
out.sort();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn walk(dir: &Path, depth: u32, out: &mut Vec<PathBuf>) {
|
||||
if depth > MAX_WALK_DEPTH {
|
||||
return;
|
||||
}
|
||||
let Ok(entries) = fs::read_dir(dir) else { return };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
match entry.file_type() {
|
||||
Ok(t) if t.is_dir() => walk(&path, depth + 1, out),
|
||||
Ok(t) if t.is_file() && is_source(&path) => out.push(path),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_source(path: &Path) -> bool {
|
||||
path.extension().and_then(|e| e.to_str()).is_some_and(|e| SOURCE_EXTENSIONS.contains(&e))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::str::FromStr;
|
||||
|
||||
fn uri(s: &str) -> Uri {
|
||||
Uri::from_str(s).expect("test uri parses")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_analyzes_a_clean_file() {
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire a;\nendmodule\n".into());
|
||||
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
|
||||
assert!(doc.diagnostics.is_empty());
|
||||
assert_eq!(doc.path.as_deref(), Some(Path::new("/rtl/m.sv")));
|
||||
assert!(doc.semantics.symbols().iter().any(|s| s.name == "m"));
|
||||
assert!(!doc.tokens.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_file_still_analyzes() {
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire ;\nendmodule\n".into());
|
||||
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
|
||||
assert!(!doc.diagnostics.is_empty(), "a broken buffer must report");
|
||||
assert!(doc.semantics.symbols().iter().any(|s| s.name == "m"), "and still bind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_lex_has_no_tokens_but_has_a_diagnostic() {
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire a; /* unterminated\n".into());
|
||||
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
|
||||
assert!(doc.tokens.is_empty());
|
||||
assert_eq!(doc.diagnostics.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untitled_buffer_has_no_path() {
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri("untitled:Untitled-1"), "module m;\nendmodule\n".into());
|
||||
let doc = ws.document(&uri("untitled:Untitled-1")).expect("open");
|
||||
assert_eq!(doc.path, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_overrides_disk_in_the_index() {
|
||||
let dir = std::env::temp_dir().join(format!("vfmt_server_state_{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).expect("temp dir");
|
||||
let path = dir.join("pkg.sv");
|
||||
fs::write(&path, "package p;\n localparam ON_DISK = 1;\nendpackage\n").expect("write");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![dir.clone()]);
|
||||
assert_eq!(ws.index().member("p", "ON_DISK").len(), 1);
|
||||
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 0);
|
||||
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri, "package p;\n localparam IN_BUFFER = 1;\nendpackage\n".into());
|
||||
ws.rebuild_index();
|
||||
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 1, "buffer must win");
|
||||
assert_eq!(ws.index().member("p", "ON_DISK").len(), 0, "disk must lose");
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_walk_finds_only_source_extensions() {
|
||||
assert!(is_source(Path::new("/a/b.sv")));
|
||||
assert!(is_source(Path::new("/a/b.v")));
|
||||
assert!(is_source(Path::new("/a/b.svh")));
|
||||
assert!(is_source(Path::new("/a/b.vh")));
|
||||
assert!(!is_source(Path::new("/a/b.txt")));
|
||||
assert!(!is_source(Path::new("/a/b")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
//! `textDocument/documentSymbol` and `workspace/symbol`, plus the
|
||||
//! `SymbolKind` mapping the rest of the crate shares.
|
||||
|
||||
use lsp_types::{Location, SymbolInformation, SymbolKind as LspKind};
|
||||
use vlog_semantic::{Symbol, SymbolKind};
|
||||
|
||||
use crate::locate::location;
|
||||
use crate::state::{Document, Workspace, WORKSPACE_SYMBOL_LIMIT};
|
||||
|
||||
/// How a declaration reads in hover text.
|
||||
pub fn kind_label(kind: SymbolKind) -> &'static str {
|
||||
match kind {
|
||||
SymbolKind::Module => "module",
|
||||
SymbolKind::Package => "package",
|
||||
SymbolKind::Port => "port",
|
||||
SymbolKind::Net => "net",
|
||||
SymbolKind::Var => "variable",
|
||||
SymbolKind::Param => "parameter",
|
||||
SymbolKind::Genvar => "genvar",
|
||||
SymbolKind::Typedef => "type",
|
||||
SymbolKind::EnumVariant => "enum variant",
|
||||
SymbolKind::Function => "function",
|
||||
SymbolKind::Task => "task",
|
||||
SymbolKind::TfArg => "argument",
|
||||
SymbolKind::Instance => "instance",
|
||||
SymbolKind::Block => "block",
|
||||
SymbolKind::StructMember => "struct member",
|
||||
}
|
||||
}
|
||||
|
||||
/// The LSP icon a declaration gets. Verilog's kinds do not all have an exact
|
||||
/// LSP counterpart; these are the closest ones editors render sensibly.
|
||||
pub fn lsp_kind(kind: SymbolKind) -> LspKind {
|
||||
match kind {
|
||||
SymbolKind::Module => LspKind::CLASS,
|
||||
SymbolKind::Package => LspKind::NAMESPACE,
|
||||
SymbolKind::Port | SymbolKind::Net | SymbolKind::Var | SymbolKind::Genvar => {
|
||||
LspKind::VARIABLE
|
||||
}
|
||||
SymbolKind::Param | SymbolKind::TfArg => LspKind::CONSTANT,
|
||||
SymbolKind::Typedef => LspKind::TYPE_PARAMETER,
|
||||
SymbolKind::EnumVariant => LspKind::ENUM_MEMBER,
|
||||
SymbolKind::Function | SymbolKind::Task => LspKind::FUNCTION,
|
||||
SymbolKind::Instance => LspKind::OBJECT,
|
||||
SymbolKind::Block => LspKind::MODULE,
|
||||
SymbolKind::StructMember => LspKind::FIELD,
|
||||
}
|
||||
}
|
||||
|
||||
/// The file's outline, hierarchically.
|
||||
pub fn document_symbols(doc: &Document) -> Vec<lsp_types::DocumentSymbol> {
|
||||
doc.semantics.document_symbols().iter().filter_map(|d| convert(doc, d)).collect()
|
||||
}
|
||||
|
||||
fn convert(
|
||||
doc: &Document,
|
||||
node: &vlog_semantic::DocumentSymbol,
|
||||
) -> Option<lsp_types::DocumentSymbol> {
|
||||
let symbol: &Symbol = doc.semantics.symbol(node.symbol)?;
|
||||
if symbol.name_span.is_empty() {
|
||||
// An editor must never be sent to a zero-width range; the single-file
|
||||
// layer uses an empty span for "I could not locate this name".
|
||||
return None;
|
||||
}
|
||||
let positions = doc.positions();
|
||||
let selection = positions.range(symbol.name_span);
|
||||
// LSP requires the selection range to be contained in the full range.
|
||||
let full = if symbol.decl_span.start <= symbol.name_span.start
|
||||
&& symbol.name_span.end <= symbol.decl_span.end
|
||||
{
|
||||
positions.range(symbol.decl_span)
|
||||
} else {
|
||||
selection
|
||||
};
|
||||
let children: Vec<_> = node.children.iter().filter_map(|c| convert(doc, c)).collect();
|
||||
// `deprecated` is deprecated in the protocol itself but is still a
|
||||
// non-optional field of the struct, so it has to be named.
|
||||
#[allow(deprecated)]
|
||||
Some(lsp_types::DocumentSymbol {
|
||||
name: symbol.name.clone(),
|
||||
detail: Some(kind_label(symbol.kind).to_string()),
|
||||
kind: lsp_kind(symbol.kind),
|
||||
tags: None,
|
||||
deprecated: None,
|
||||
range: full,
|
||||
selection_range: selection,
|
||||
children: if children.is_empty() { None } else { Some(children) },
|
||||
})
|
||||
}
|
||||
|
||||
/// Workspace-wide symbol search, capped at [`WORKSPACE_SYMBOL_LIMIT`].
|
||||
pub fn workspace_symbols(ws: &Workspace, query: &str) -> Vec<SymbolInformation> {
|
||||
let index = ws.index();
|
||||
index
|
||||
.workspace_symbols(query)
|
||||
.into_iter()
|
||||
.take(WORKSPACE_SYMBOL_LIMIT)
|
||||
.filter_map(|hit| {
|
||||
let path = index.path(hit.def.file)?;
|
||||
let location: Location = location(ws, path, hit.def.name_span)?;
|
||||
// `deprecated` is a deprecated protocol field that is still a
|
||||
// named field of the struct.
|
||||
#[allow(deprecated)]
|
||||
Some(SymbolInformation {
|
||||
name: hit.name.to_string(),
|
||||
kind: lsp_kind(hit.def.kind),
|
||||
tags: None,
|
||||
deprecated: None,
|
||||
location,
|
||||
container_name: hit.container.map(|c| c.to_string()),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lsp_types::Uri;
|
||||
use std::str::FromStr;
|
||||
|
||||
fn document(text: &str) -> (Workspace, Uri) {
|
||||
let uri = Uri::from_str("file:///rtl/m.sv").expect("uri");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_and_its_contents_nest() {
|
||||
let (ws, uri) = document(
|
||||
"module top;\n wire a;\n localparam W = 8;\nendmodule\n\npackage p;\nendpackage\n",
|
||||
);
|
||||
let symbols = document_symbols(ws.document(&uri).expect("open"));
|
||||
assert_eq!(symbols.len(), 2, "the module and the package");
|
||||
assert_eq!(symbols[0].name, "top");
|
||||
assert_eq!(symbols[0].kind, LspKind::CLASS);
|
||||
let children = symbols[0].children.as_ref().expect("module contents");
|
||||
let names: Vec<_> = children.iter().map(|c| c.name.as_str()).collect();
|
||||
assert!(names.contains(&"a"), "got {names:?}");
|
||||
assert!(names.contains(&"W"), "got {names:?}");
|
||||
assert_eq!(symbols[1].name, "p");
|
||||
assert_eq!(symbols[1].kind, LspKind::NAMESPACE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selection_range_is_always_inside_the_full_range() {
|
||||
let (ws, uri) = document("module top;\n wire [7:0] wide;\nendmodule\n");
|
||||
let symbols = document_symbols(ws.document(&uri).expect("open"));
|
||||
fn check(s: &lsp_types::DocumentSymbol) {
|
||||
assert!(s.range.start <= s.selection_range.start, "{}", s.name);
|
||||
assert!(s.selection_range.end <= s.range.end, "{}", s.name);
|
||||
for c in s.children.iter().flatten() {
|
||||
check(c);
|
||||
}
|
||||
}
|
||||
for s in &symbols {
|
||||
check(s);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_positions_are_utf16() {
|
||||
let (ws, uri) = document("// é 🎉\nmodule top;\nendmodule\n");
|
||||
let symbols = document_symbols(ws.document(&uri).expect("open"));
|
||||
assert_eq!(symbols[0].selection_range.start.line, 1);
|
||||
assert_eq!(symbols[0].selection_range.start.character, 7, "`top` after `module `");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_symbols_find_declarations_across_files() {
|
||||
let dir = std::env::temp_dir().join(format!("vfmt_server_wsym_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
std::fs::write(dir.join("a.sv"), "module alpha;\nendmodule\n").expect("write");
|
||||
std::fs::write(dir.join("b.sv"), "package beta;\n localparam ALPHA_W = 8;\nendpackage\n")
|
||||
.expect("write");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![dir.clone()]);
|
||||
|
||||
let hits = workspace_symbols(&ws, "alpha");
|
||||
let names: Vec<_> = hits.iter().map(|h| h.name.as_str()).collect();
|
||||
assert!(names.contains(&"alpha"), "the module: got {names:?}");
|
||||
assert!(names.contains(&"ALPHA_W"), "matching is substring-y: got {names:?}");
|
||||
|
||||
let module = hits.iter().find(|h| h.name == "alpha").expect("alpha");
|
||||
assert_eq!(module.kind, LspKind::CLASS);
|
||||
// The location is resolved against the file's own text, which the
|
||||
// index does not retain — this is the read-on-demand path.
|
||||
assert_eq!(module.location.range.start.line, 0);
|
||||
assert_eq!(module.location.range.start.character, 7);
|
||||
|
||||
let member = hits.iter().find(|h| h.name == "ALPHA_W").expect("ALPHA_W");
|
||||
assert_eq!(member.container_name.as_deref(), Some("beta"));
|
||||
assert_eq!(member.location.range.start.line, 1);
|
||||
|
||||
assert!(workspace_symbols(&ws, "nothing_matches_this").is_empty());
|
||||
assert!(
|
||||
workspace_symbols(&ws, "").len() <= WORKSPACE_SYMBOL_LIMIT,
|
||||
"the empty query must stay capped"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_buffer_still_has_an_outline() {
|
||||
let (ws, uri) = document("module top;\n wire ;\n wire ok;\nendmodule\n");
|
||||
let symbols = document_symbols(ws.document(&uri).expect("open"));
|
||||
assert_eq!(symbols.len(), 1);
|
||||
assert_eq!(symbols[0].name, "top");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
//! `textDocument/semanticTokens/full`.
|
||||
//!
|
||||
//! Classification comes from the lexer's token stream, refined for plain
|
||||
//! identifiers by `vlog_semantic`. The full mapping table is in
|
||||
//! `docs/features/vfmt-server/README.md`.
|
||||
|
||||
use lsp_types::{SemanticToken, SemanticTokenModifier, SemanticTokenType, SemanticTokens};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{Semantics, SymbolKind};
|
||||
|
||||
use crate::state::Document;
|
||||
|
||||
/// The legend the server advertises. The index into this array is what the
|
||||
/// wire format carries, so the order is part of the protocol contract and
|
||||
/// must match [`Highlight`].
|
||||
pub fn token_types() -> Vec<SemanticTokenType> {
|
||||
vec![
|
||||
SemanticTokenType::NAMESPACE,
|
||||
SemanticTokenType::CLASS,
|
||||
SemanticTokenType::TYPE,
|
||||
SemanticTokenType::ENUM_MEMBER,
|
||||
SemanticTokenType::PARAMETER,
|
||||
SemanticTokenType::VARIABLE,
|
||||
SemanticTokenType::PROPERTY,
|
||||
SemanticTokenType::FUNCTION,
|
||||
SemanticTokenType::MACRO,
|
||||
SemanticTokenType::KEYWORD,
|
||||
SemanticTokenType::COMMENT,
|
||||
SemanticTokenType::STRING,
|
||||
SemanticTokenType::NUMBER,
|
||||
SemanticTokenType::DECORATOR,
|
||||
]
|
||||
}
|
||||
|
||||
/// The modifiers the server advertises; bit 0 is `declaration`.
|
||||
pub fn token_modifiers() -> Vec<SemanticTokenModifier> {
|
||||
vec![SemanticTokenModifier::DECLARATION]
|
||||
}
|
||||
|
||||
/// A highlight class, as its index in [`token_types`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[repr(u32)]
|
||||
enum Highlight {
|
||||
Namespace = 0,
|
||||
Class = 1,
|
||||
Type = 2,
|
||||
EnumMember = 3,
|
||||
Parameter = 4,
|
||||
Variable = 5,
|
||||
Property = 6,
|
||||
Function = 7,
|
||||
Macro = 8,
|
||||
Keyword = 9,
|
||||
Comment = 10,
|
||||
String = 11,
|
||||
Number = 12,
|
||||
Decorator = 13,
|
||||
}
|
||||
|
||||
/// Bit 0 of the modifier set.
|
||||
const DECLARATION: u32 = 1;
|
||||
|
||||
/// One classified piece of source, before line splitting and delta encoding.
|
||||
struct Piece {
|
||||
span: TextRange,
|
||||
ty: Highlight,
|
||||
modifiers: u32,
|
||||
}
|
||||
|
||||
/// Classify and encode the whole buffer.
|
||||
///
|
||||
/// A buffer that does not lex has no tokens, so this is empty — the user sees
|
||||
/// the editor's own grammar highlighting plus the parse diagnostic, which is
|
||||
/// the honest answer while the file is unlexable.
|
||||
pub fn semantic_tokens(doc: &Document) -> SemanticTokens {
|
||||
let mut pieces = Vec::new();
|
||||
for token in &doc.tokens {
|
||||
collect_trivia(token, &mut pieces);
|
||||
if let Some(ty) = classify(token, &doc.semantics) {
|
||||
pieces.push(Piece {
|
||||
span: token.span,
|
||||
ty,
|
||||
modifiers: modifiers(token, &doc.semantics),
|
||||
});
|
||||
}
|
||||
}
|
||||
encode(pieces, doc)
|
||||
}
|
||||
|
||||
/// Comments live as trivia on the token that follows (or, for a trailing
|
||||
/// comment, precedes) them — including on the EOF token, which is what makes
|
||||
/// a comment at the end of the file reachable.
|
||||
fn collect_trivia(token: &Token, out: &mut Vec<Piece>) {
|
||||
for comment in &token.leading {
|
||||
out.push(Piece { span: comment.span, ty: Highlight::Comment, modifiers: 0 });
|
||||
}
|
||||
if let Some(comment) = &token.trailing {
|
||||
out.push(Piece { span: comment.span, ty: Highlight::Comment, modifiers: 0 });
|
||||
}
|
||||
}
|
||||
|
||||
/// What a token is, or `None` for the ones this server does not colour.
|
||||
fn classify(token: &Token, semantics: &Semantics) -> Option<Highlight> {
|
||||
match token.kind {
|
||||
TokenKind::Keyword => Some(Highlight::Keyword),
|
||||
TokenKind::Number => Some(Highlight::Number),
|
||||
TokenKind::String => Some(Highlight::String),
|
||||
TokenKind::Directive => Some(Highlight::Macro),
|
||||
TokenKind::Attribute => Some(Highlight::Decorator),
|
||||
TokenKind::SystemIdent => Some(Highlight::Function),
|
||||
// A macro *usage* lexes as an identifier whose text starts with a
|
||||
// backtick; `is_macro` is the lexer's own public test for it.
|
||||
TokenKind::Ident if token.is_macro() => Some(Highlight::Macro),
|
||||
TokenKind::Ident => Some(identifier_type(token.span.start, semantics)),
|
||||
// Punctuation: deliberately not emitted, see the feature README.
|
||||
TokenKind::Symbol | TokenKind::Eof => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a token is the name of a declaration.
|
||||
fn modifiers(token: &Token, semantics: &Semantics) -> u32 {
|
||||
let is_declaration = token.kind == TokenKind::Ident
|
||||
&& !token.is_macro()
|
||||
&& semantics.symbol_at(token.span.start).is_some();
|
||||
if is_declaration {
|
||||
DECLARATION
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
/// A plain identifier, classified through the symbol table: its own
|
||||
/// declaration, the declaration it resolves to, or `variable` when nothing in
|
||||
/// this file knows (an external candidate, or a name a macro would produce).
|
||||
fn identifier_type(offset: u32, semantics: &Semantics) -> Highlight {
|
||||
let symbol = semantics
|
||||
.symbol_at(offset)
|
||||
.or_else(|| semantics.reference_at(offset).and_then(|r| r.resolved()))
|
||||
.and_then(|id| semantics.symbol(id));
|
||||
match symbol {
|
||||
Some(symbol) => symbol_type(symbol.kind),
|
||||
None => Highlight::Variable,
|
||||
}
|
||||
}
|
||||
|
||||
fn symbol_type(kind: SymbolKind) -> Highlight {
|
||||
match kind {
|
||||
SymbolKind::Module => Highlight::Class,
|
||||
SymbolKind::Package => Highlight::Namespace,
|
||||
SymbolKind::Typedef => Highlight::Type,
|
||||
SymbolKind::EnumVariant => Highlight::EnumMember,
|
||||
SymbolKind::Param | SymbolKind::TfArg => Highlight::Parameter,
|
||||
SymbolKind::Function | SymbolKind::Task => Highlight::Function,
|
||||
SymbolKind::StructMember => Highlight::Property,
|
||||
SymbolKind::Port
|
||||
| SymbolKind::Net
|
||||
| SymbolKind::Var
|
||||
| SymbolKind::Genvar
|
||||
| SymbolKind::Instance
|
||||
| SymbolKind::Block => Highlight::Variable,
|
||||
}
|
||||
}
|
||||
|
||||
/// Split every piece at line boundaries, sort, and delta-encode.
|
||||
///
|
||||
/// The spec forbids a token from spanning a line break, and Verilog has three
|
||||
/// shapes that would: a block comment, a continued `` `define`` and a
|
||||
/// multi-line macro invocation.
|
||||
fn encode(pieces: Vec<Piece>, doc: &Document) -> SemanticTokens {
|
||||
let positions = doc.positions();
|
||||
let mut flat: Vec<(u32, u32, u32, u32, u32)> = Vec::new();
|
||||
for piece in pieces {
|
||||
for line_span in split_lines(&doc.text, piece.span) {
|
||||
let start = positions.position(line_span.start);
|
||||
let end = positions.position(line_span.end);
|
||||
if end.character <= start.character {
|
||||
continue;
|
||||
}
|
||||
flat.push((
|
||||
start.line,
|
||||
start.character,
|
||||
end.character - start.character,
|
||||
piece.ty as u32,
|
||||
piece.modifiers,
|
||||
));
|
||||
}
|
||||
}
|
||||
flat.sort_by_key(|&(line, start, ..)| (line, start));
|
||||
|
||||
let mut data = Vec::with_capacity(flat.len());
|
||||
let (mut prev_line, mut prev_start) = (0u32, 0u32);
|
||||
for (line, start, length, ty, modifiers) in flat {
|
||||
let delta_line = line - prev_line;
|
||||
let delta_start = if delta_line == 0 { start - prev_start } else { start };
|
||||
data.push(SemanticToken {
|
||||
delta_line,
|
||||
delta_start,
|
||||
length,
|
||||
token_type: ty,
|
||||
token_modifiers_bitset: modifiers,
|
||||
});
|
||||
prev_line = line;
|
||||
prev_start = start;
|
||||
}
|
||||
SemanticTokens { result_id: None, data }
|
||||
}
|
||||
|
||||
/// One span per line the span touches, each stopping before the `\n`.
|
||||
fn split_lines(text: &str, span: TextRange) -> Vec<TextRange> {
|
||||
let Some(slice) = text.get(span.as_range()) else { return Vec::new() };
|
||||
if !slice.contains('\n') {
|
||||
return vec![span];
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut start = span.start;
|
||||
for (offset, _) in slice.char_indices().filter(|&(_, c)| c == '\n') {
|
||||
let end = span.start + offset as u32;
|
||||
out.push(TextRange::new(start, end));
|
||||
start = end + 1;
|
||||
}
|
||||
if start < span.end {
|
||||
out.push(TextRange::new(start, span.end));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::state::Workspace;
|
||||
use lsp_types::Uri;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// Decode the delta encoding back to absolute (line, start, len, type).
|
||||
fn decoded(text: &str) -> Vec<(u32, u32, u32, u32, u32)> {
|
||||
let uri = Uri::from_str("file:///rtl/m.sv").expect("uri");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
let tokens = semantic_tokens(ws.document(&uri).expect("open"));
|
||||
let (mut line, mut start) = (0u32, 0u32);
|
||||
tokens
|
||||
.data
|
||||
.iter()
|
||||
.map(|t| {
|
||||
line += t.delta_line;
|
||||
start = if t.delta_line == 0 { start + t.delta_start } else { t.delta_start };
|
||||
(line, start, t.length, t.token_type, t.token_modifiers_bitset)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keywords_numbers_and_strings_are_classified() {
|
||||
let out = decoded("module m;\n localparam W = 8;\n wire a = \"s\";\nendmodule\n");
|
||||
assert!(out
|
||||
.iter()
|
||||
.any(|&(l, c, _, t, _)| l == 0 && c == 0 && t == Highlight::Keyword as u32));
|
||||
assert!(out.iter().any(|&(.., t, _)| t == Highlight::Number as u32));
|
||||
assert!(out.iter().any(|&(.., t, _)| t == Highlight::String as u32));
|
||||
// Punctuation is never emitted.
|
||||
assert!(out.iter().all(|&(_, _, len, ..)| len > 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_name_is_a_class_and_carries_the_declaration_modifier() {
|
||||
let out = decoded("module top;\nendmodule\n");
|
||||
let name = out.iter().find(|&&(l, c, ..)| l == 0 && c == 7).expect("the name `top`");
|
||||
assert_eq!(name.2, 3);
|
||||
assert_eq!(name.3, Highlight::Class as u32);
|
||||
assert_eq!(name.4, DECLARATION, "a declaration is marked as one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_use_takes_its_declarations_type() {
|
||||
let out = decoded("module m;\n localparam W = 8;\n wire [W-1:0] a;\nendmodule\n");
|
||||
let uses: Vec<_> =
|
||||
out.iter().filter(|&&(.., t, _)| t == Highlight::Parameter as u32).copied().collect();
|
||||
assert_eq!(uses.len(), 2, "the declaration and the use");
|
||||
assert_eq!(uses[0].4, DECLARATION);
|
||||
assert_eq!(uses[1].4, 0, "a use is not a declaration");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_usage_and_a_directive_are_both_macro() {
|
||||
let out = decoded("`define W 8\nmodule m;\n wire [`W-1:0] a;\nendmodule\n");
|
||||
let macros: Vec<_> =
|
||||
out.iter().filter(|&&(.., t, _)| t == Highlight::Macro as u32).copied().collect();
|
||||
assert_eq!(macros.len(), 2, "the `define line and the `W usage");
|
||||
assert_eq!(macros[0].0, 0, "the directive");
|
||||
assert_eq!(macros[1].0, 2, "the usage");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_are_emitted_including_the_last_one_in_the_file() {
|
||||
let out = decoded("// first\nmodule m;\nendmodule\n// last\n");
|
||||
let comments: Vec<_> =
|
||||
out.iter().filter(|&&(.., t, _)| t == Highlight::Comment as u32).copied().collect();
|
||||
assert_eq!(comments.len(), 2, "a trailing comment rides the EOF token");
|
||||
assert_eq!(comments[0].0, 0);
|
||||
assert_eq!(comments[1].0, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_token_ever_spans_a_line_break() {
|
||||
let text = "/* a\n b\n c */\nmodule m;\nendmodule\n";
|
||||
let out = decoded(text);
|
||||
let comments: Vec<_> =
|
||||
out.iter().filter(|&&(.., t, _)| t == Highlight::Comment as u32).copied().collect();
|
||||
assert_eq!(comments.len(), 3, "one piece per line of the block comment");
|
||||
assert_eq!(comments.iter().map(|c| c.0).collect::<Vec<_>>(), vec![0, 1, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_continued_define_is_split_per_line_too() {
|
||||
let out = decoded(
|
||||
"`define FF(q, d) \\\n always_ff @(posedge clk) q <= d;\nmodule m;\nendmodule\n",
|
||||
);
|
||||
let macros: Vec<_> =
|
||||
out.iter().filter(|&&(.., t, _)| t == Highlight::Macro as u32).copied().collect();
|
||||
assert_eq!(macros.len(), 2, "two physical lines, two pieces");
|
||||
assert_eq!(macros[0].0, 0);
|
||||
assert_eq!(macros[1].0, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lengths_are_utf16_units_not_bytes() {
|
||||
// The comment is `// é 🎉` — 2 + 1 + 1 + 1 + 2 = 7 UTF-16 units, but
|
||||
// 3 + 2 + 1 + 4 = 10 bytes. A byte-based server reports 10 and the
|
||||
// highlight bleeds past the end of the line.
|
||||
let out = decoded("// é 🎉\nmodule m;\nendmodule\n");
|
||||
let comment =
|
||||
out.iter().find(|&&(.., t, _)| t == Highlight::Comment as u32).expect("comment");
|
||||
assert_eq!(comment.1, 0);
|
||||
assert_eq!(comment.2, 7, "UTF-16 units");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_come_out_sorted_so_the_deltas_are_never_negative() {
|
||||
let out = decoded("module m; // trailing\n wire a; /* mid */ wire b;\nendmodule\n");
|
||||
for pair in out.windows(2) {
|
||||
let (a, b) = (pair[0], pair[1]);
|
||||
assert!((a.0, a.1) <= (b.0, b.1), "out of order: {a:?} then {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_lex_yields_no_tokens() {
|
||||
let out = decoded("module m; /* unterminated\n");
|
||||
assert!(out.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splitting_a_span_with_no_newline_is_the_span() {
|
||||
assert_eq!(split_lines("abc", TextRange::new(0, 3)), vec![TextRange::new(0, 3)]);
|
||||
assert_eq!(
|
||||
split_lines("a\nb", TextRange::new(0, 3)),
|
||||
vec![TextRange::new(0, 1), TextRange::new(2, 3)]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
//! `file:` URI ↔ filesystem path.
|
||||
//!
|
||||
//! `lsp-types` 0.97 models a URI as a `fluent_uri::Uri`, which parses and
|
||||
//! validates but does not know about file paths. The alternative was an
|
||||
//! `lsp-types` old enough to use `url::Url` (five more packages, see the
|
||||
//! feature README), so the ~40 lines live here instead.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::str::FromStr;
|
||||
|
||||
use lsp_types::Uri;
|
||||
|
||||
/// The `file:` URI naming an absolute path, or `None` if the path is not
|
||||
/// valid UTF-8 or does not parse back as a URI.
|
||||
pub fn path_to_uri(path: &Path) -> Option<Uri> {
|
||||
let path = path.to_str()?;
|
||||
let mut out = String::from("file://");
|
||||
// A Windows path starts at a drive letter; a POSIX one already starts
|
||||
// with the `/` that separates the (empty) authority from the path.
|
||||
if !path.starts_with('/') {
|
||||
out.push('/');
|
||||
}
|
||||
for byte in path.bytes() {
|
||||
match byte {
|
||||
b'/' | b'-' | b'.' | b'_' | b'~' => out.push(byte as char),
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' => out.push(byte as char),
|
||||
// Windows separators become the URI's own.
|
||||
b'\\' => out.push('/'),
|
||||
_ => out.push_str(&format!("%{byte:02X}")),
|
||||
}
|
||||
}
|
||||
Uri::from_str(&out).ok()
|
||||
}
|
||||
|
||||
/// The path a `file:` URI names, or `None` for any other scheme.
|
||||
pub fn uri_to_path(uri: &Uri) -> Option<PathBuf> {
|
||||
let rest = uri.as_str().strip_prefix("file://")?;
|
||||
// An authority (`file://host/path`) is skipped; the path starts at the
|
||||
// first `/`. `file:///path` leaves `rest` already starting with one.
|
||||
let path = match rest.strip_prefix('/') {
|
||||
Some(_) => rest,
|
||||
None => &rest[rest.find('/')?..],
|
||||
};
|
||||
let decoded = String::from_utf8(percent_decode(path)).ok()?;
|
||||
// `file:///C:/x` names `C:/x`, not `/C:/x`. Guarded, because `/C:` is a
|
||||
// legal POSIX directory name.
|
||||
if cfg!(windows) {
|
||||
if let Some(tail) = drive_letter_tail(&decoded) {
|
||||
return Some(PathBuf::from(tail));
|
||||
}
|
||||
}
|
||||
Some(PathBuf::from(decoded))
|
||||
}
|
||||
|
||||
/// `/C:/x` → `C:/x`, when the leading `/` is a URI artifact and not a root.
|
||||
fn drive_letter_tail(path: &str) -> Option<&str> {
|
||||
let tail = path.strip_prefix('/')?;
|
||||
let mut chars = tail.chars();
|
||||
match (chars.next(), chars.next()) {
|
||||
(Some(c), Some(':')) if c.is_ascii_alphabetic() => Some(tail),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Undo percent-encoding. A `%` not followed by two hex digits is kept as
|
||||
/// written rather than rejected — an editor's URI is not a place to be strict.
|
||||
fn percent_decode(s: &str) -> Vec<u8> {
|
||||
let bytes = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
match (bytes[i], bytes.get(i + 1), bytes.get(i + 2)) {
|
||||
(b'%', Some(&hi), Some(&lo)) => match (hex(hi), hex(lo)) {
|
||||
(Some(hi), Some(lo)) => {
|
||||
out.push(hi * 16 + lo);
|
||||
i += 3;
|
||||
}
|
||||
_ => {
|
||||
out.push(b'%');
|
||||
i += 1;
|
||||
}
|
||||
},
|
||||
(byte, _, _) => {
|
||||
out.push(byte);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn hex(byte: u8) -> Option<u8> {
|
||||
match byte {
|
||||
b'0'..=b'9' => Some(byte - b'0'),
|
||||
b'a'..=b'f' => Some(byte - b'a' + 10),
|
||||
b'A'..=b'F' => Some(byte - b'A' + 10),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn round_trip(path: &str) {
|
||||
let uri = path_to_uri(Path::new(path)).expect("encodable");
|
||||
assert_eq!(uri_to_path(&uri).as_deref(), Some(Path::new(path)), "for {path}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_path_round_trips() {
|
||||
round_trip("/home/u/rtl/top.sv");
|
||||
assert_eq!(
|
||||
path_to_uri(Path::new("/home/u/rtl/top.sv")).map(|u| u.as_str().to_string()),
|
||||
Some("file:///home/u/rtl/top.sv".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spaces_and_specials_are_percent_encoded() {
|
||||
let uri = path_to_uri(Path::new("/a b/c#d?e/f.sv")).expect("encodable");
|
||||
assert_eq!(uri.as_str(), "file:///a%20b/c%23d%3Fe/f.sv");
|
||||
round_trip("/a b/c#d?e/f.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_byte_path_components_round_trip() {
|
||||
round_trip("/rtl/münchen/✓/top.sv");
|
||||
let uri = path_to_uri(Path::new("/rtl/é.sv")).expect("encodable");
|
||||
assert_eq!(uri.as_str(), "file:///rtl/%C3%A9.sv");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_file_scheme_is_rejected() {
|
||||
let uri = Uri::from_str("untitled:Untitled-1").expect("parses");
|
||||
assert_eq!(uri_to_path(&uri), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_authority_is_skipped() {
|
||||
let uri = Uri::from_str("file://localhost/rtl/top.sv").expect("parses");
|
||||
assert_eq!(uri_to_path(&uri).as_deref(), Some(Path::new("/rtl/top.sv")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stray_percent_is_kept_rather_than_rejected() {
|
||||
assert_eq!(percent_decode("100%/x"), b"100%/x".to_vec());
|
||||
assert_eq!(percent_decode("%zz"), b"%zz".to_vec());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
//! One end-to-end smoke test: spawn the real binary and speak framed
|
||||
//! JSON-RPC at it over stdio.
|
||||
//!
|
||||
//! Everything else in this crate is tested by calling handlers directly with
|
||||
//! constructed state, which is faster and pins behavior more precisely. This
|
||||
//! test exists to catch the things those cannot: that the binary starts, that
|
||||
//! the `Content-Length` framing works in both directions, that the
|
||||
//! initialize/initialized/shutdown/exit handshake completes, and that a
|
||||
//! notification the server *pushes* (diagnostics) actually reaches the wire.
|
||||
//!
|
||||
//! The framing is hand-rolled here on purpose — a test that reused the
|
||||
//! server's own transport could not catch a framing bug.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
/// Frame one JSON payload the way LSP wants it.
|
||||
fn frame(payload: &str) -> String {
|
||||
format!("Content-Length: {}\r\n\r\n{payload}", payload.len())
|
||||
}
|
||||
|
||||
/// Split a stdout dump into its JSON payloads.
|
||||
fn unframe(mut input: impl BufRead) -> Vec<serde_json::Value> {
|
||||
let mut out = Vec::new();
|
||||
loop {
|
||||
let mut length = None;
|
||||
// Headers, terminated by an empty line.
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
if input.read_line(&mut line).unwrap_or(0) == 0 {
|
||||
return out;
|
||||
}
|
||||
let trimmed = line.trim_end_matches(['\r', '\n']);
|
||||
if trimmed.is_empty() {
|
||||
break;
|
||||
}
|
||||
if let Some(value) = trimmed.strip_prefix("Content-Length: ") {
|
||||
length = value.parse::<usize>().ok();
|
||||
}
|
||||
}
|
||||
let Some(length) = length else { return out };
|
||||
let mut body = vec![0u8; length];
|
||||
if input.read_exact(&mut body).is_err() {
|
||||
return out;
|
||||
}
|
||||
match serde_json::from_slice(&body) {
|
||||
Ok(value) => out.push(value),
|
||||
Err(_) => return out,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn temp_dir() -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("vfmt_server_e2e_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
dir
|
||||
}
|
||||
|
||||
/// A buffer that is broken *and* still has a resolvable reference: error
|
||||
/// recovery is what makes both true at once, and the LSP depends on it.
|
||||
const SOURCE: &str = "module top;\n wire a;\n assign a = 1;\n wire ;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn the_binary_serves_a_whole_session_over_stdio() {
|
||||
let dir = temp_dir();
|
||||
let file = dir.join("top.sv");
|
||||
std::fs::write(&file, SOURCE).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
// Every message is written before anything is read: the server processes
|
||||
// them in order and exits on `exit`, so stdout closes and the test can
|
||||
// never deadlock waiting on a message that is not coming.
|
||||
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(SOURCE).expect("json")
|
||||
)),
|
||||
// The `a` of `assign a` — line 2, character 9.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":9}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","id":3,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_vfmt-server"))
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.expect("the server binary starts");
|
||||
|
||||
child.stdin.take().expect("stdin").write_all(session.as_bytes()).expect("write session");
|
||||
let stdout = child.stdout.take().expect("stdout");
|
||||
let messages = unframe(BufReader::new(stdout));
|
||||
let status = child.wait().expect("the server exits");
|
||||
assert!(status.success(), "clean exit, got {status:?}");
|
||||
|
||||
// 1. The initialize response advertises what we implement.
|
||||
let initialize = messages
|
||||
.iter()
|
||||
.find(|m| m["id"] == 1)
|
||||
.unwrap_or_else(|| panic!("no initialize response in {messages:#?}"));
|
||||
let capabilities = &initialize["result"]["capabilities"];
|
||||
assert_eq!(capabilities["positionEncoding"], "utf-16");
|
||||
assert_eq!(capabilities["documentFormattingProvider"], true);
|
||||
assert_eq!(capabilities["definitionProvider"], true);
|
||||
assert!(capabilities["semanticTokensProvider"].is_object());
|
||||
assert_eq!(initialize["result"]["serverInfo"]["name"], "vfmt-server");
|
||||
|
||||
// 2. Diagnostics were pushed for the broken buffer.
|
||||
let published = messages
|
||||
.iter()
|
||||
.find(|m| m["method"] == "textDocument/publishDiagnostics")
|
||||
.unwrap_or_else(|| panic!("no diagnostics in {messages:#?}"));
|
||||
assert_eq!(published["params"]["uri"], uri.as_str());
|
||||
let diagnostics = published["params"]["diagnostics"].as_array().expect("an array");
|
||||
assert_eq!(diagnostics.len(), 1, "one error for `wire ;`");
|
||||
assert_eq!(diagnostics[0]["severity"], 1, "an error");
|
||||
assert_eq!(diagnostics[0]["source"], "vfmt");
|
||||
assert_eq!(diagnostics[0]["range"]["start"]["line"], 3, "the `wire ;` line");
|
||||
|
||||
// 3. Definition jumped to the declaration, in the same file.
|
||||
let definition = messages
|
||||
.iter()
|
||||
.find(|m| m["id"] == 2)
|
||||
.unwrap_or_else(|| panic!("no definition response in {messages:#?}"));
|
||||
let locations = definition["result"].as_array().expect("an array of locations");
|
||||
assert_eq!(locations.len(), 1, "got {locations:#?}");
|
||||
assert_eq!(locations[0]["uri"], uri.as_str());
|
||||
assert_eq!(locations[0]["range"]["start"]["line"], 1, "the `wire a;` line");
|
||||
assert_eq!(locations[0]["range"]["start"]["character"], 7);
|
||||
|
||||
// 4. Shutdown was acknowledged.
|
||||
let shutdown = messages
|
||||
.iter()
|
||||
.find(|m| m["id"] == 3)
|
||||
.unwrap_or_else(|| panic!("no shutdown response in {messages:#?}"));
|
||||
assert!(shutdown["error"].is_null(), "shutdown must succeed");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "vlog_linter"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "Syntactic lint rules for Verilog/SystemVerilog, in the spirit of ruff and Verible"
|
||||
|
||||
[dependencies]
|
||||
vlog_parser = { path = "../vlog_parser" }
|
||||
@@ -0,0 +1,153 @@
|
||||
//! Everything a rule is given to look at: text, tokens, tree, positions.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::ast::SourceFile;
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::{Comment, Token, TokenKind};
|
||||
use vlog_parser::{parse_source_tolerant, tokenize, LineIndex};
|
||||
|
||||
/// The default tab stop used when a fix expands a tab, matching vfmt's
|
||||
/// default indent. `LintContext::with_tab_width` follows `--indent`.
|
||||
const DEFAULT_TAB_WIDTH: usize = 2;
|
||||
|
||||
/// One file, prepared once and shared by every rule in the run.
|
||||
///
|
||||
/// The parse is the **tolerant** one: a file that does not fully parse still
|
||||
/// gets linted, with the parts that failed sitting in the tree as
|
||||
/// `ItemKind::Error` / `StmtKind::Error` leaves that AST rules simply do not
|
||||
/// match. Token- and text-level rules are unaffected by parse errors.
|
||||
pub struct LintContext {
|
||||
source: String,
|
||||
tokens: Vec<Token>,
|
||||
file: SourceFile,
|
||||
line_index: LineIndex,
|
||||
path: Option<PathBuf>,
|
||||
tab_width: usize,
|
||||
/// Byte ranges of string literals, ascending — the one place text rules
|
||||
/// must not rewrite, because there whitespace is data.
|
||||
strings: Vec<TextRange>,
|
||||
}
|
||||
|
||||
impl LintContext {
|
||||
/// Prepare `source` for linting. `path` is the file the text came from,
|
||||
/// or `None` for a buffer (stdin) — rules that need a filename skip.
|
||||
pub fn new(source: &str, path: Option<PathBuf>) -> LintContext {
|
||||
// A lex error leaves no tokens (the lexer is all-or-nothing), and
|
||||
// the tolerant parse turns the whole file into one error leaf. Text
|
||||
// rules still work, which is the point of not failing here.
|
||||
let tokens = tokenize(source).unwrap_or_default();
|
||||
let (file, _diagnostics) = parse_source_tolerant(source);
|
||||
let strings = tokens
|
||||
.iter()
|
||||
.filter(|t| t.kind == TokenKind::String)
|
||||
.map(|t| t.span)
|
||||
.collect::<Vec<_>>();
|
||||
LintContext {
|
||||
source: source.to_string(),
|
||||
tokens,
|
||||
file,
|
||||
line_index: LineIndex::new(source),
|
||||
path,
|
||||
tab_width: DEFAULT_TAB_WIDTH,
|
||||
strings,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the tab stop a fix expands a tab to (the run's indent width).
|
||||
pub fn with_tab_width(mut self, tab_width: usize) -> LintContext {
|
||||
self.tab_width = tab_width.max(1);
|
||||
self
|
||||
}
|
||||
|
||||
/// The source text being linted.
|
||||
pub fn source(&self) -> &str {
|
||||
&self.source
|
||||
}
|
||||
|
||||
/// The token stream, comments attached as leading/trailing trivia.
|
||||
pub fn tokens(&self) -> &[Token] {
|
||||
&self.tokens
|
||||
}
|
||||
|
||||
/// The tolerant parse of the source.
|
||||
pub fn file(&self) -> &SourceFile {
|
||||
&self.file
|
||||
}
|
||||
|
||||
/// Offset ↔ line:column for this file.
|
||||
pub fn line_index(&self) -> &LineIndex {
|
||||
&self.line_index
|
||||
}
|
||||
|
||||
/// The file this text came from, if it came from one.
|
||||
pub fn path(&self) -> Option<&Path> {
|
||||
self.path.as_deref()
|
||||
}
|
||||
|
||||
/// Spaces a fix writes in place of one tab.
|
||||
pub fn tab_width(&self) -> usize {
|
||||
self.tab_width
|
||||
}
|
||||
|
||||
/// The text of a 1-based line, without its newline.
|
||||
pub fn line_text(&self, line: u32) -> &str {
|
||||
match self.line_index.line_range(line) {
|
||||
Some(range) => self.source.get(range.as_range()).unwrap_or(""),
|
||||
None => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `range` touches a string literal. Whitespace inside one is
|
||||
/// data, so text rules neither report nor rewrite it.
|
||||
pub fn touches_string(&self, range: TextRange) -> bool {
|
||||
self.strings.iter().any(|s| s.start < range.end && range.start < s.end)
|
||||
}
|
||||
|
||||
/// Every comment in the file, in source order. Comments live on the
|
||||
/// tokens they were attached to, which is where the waiver scanner and
|
||||
/// any comment-shaped rule finds them.
|
||||
pub fn comments(&self) -> Vec<&Comment> {
|
||||
let mut out: Vec<&Comment> = Vec::new();
|
||||
for token in &self.tokens {
|
||||
out.extend(token.leading.iter());
|
||||
out.extend(token.trailing.iter());
|
||||
}
|
||||
out.sort_by_key(|c| (c.span.start, c.span.end));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_parse_still_has_text_and_tokens() {
|
||||
let ctx = LintContext::new("module m;\n @@@\nendmodule\n", None);
|
||||
assert!(!ctx.tokens().is_empty());
|
||||
assert_eq!(ctx.line_text(2), " @@@");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_come_back_in_source_order() {
|
||||
let ctx = LintContext::new("// a\nmodule m; // b\n// c\nendmodule\n", None);
|
||||
let texts: Vec<&str> = ctx.comments().iter().map(|c| c.text.as_str()).collect();
|
||||
assert_eq!(texts, vec!["// a", "// b", "// c"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn string_literals_are_recognized() {
|
||||
let ctx = LintContext::new("module m;\n string s = \"a\tb\";\nendmodule\n", None);
|
||||
let tab = ctx.source().find('\t').unwrap_or(0) as u32;
|
||||
assert!(ctx.touches_string(TextRange::new(tab, tab + 1)));
|
||||
assert!(!ctx.touches_string(TextRange::new(0, 6)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_width_follows_the_run() {
|
||||
assert_eq!(LintContext::new("", None).tab_width(), 2);
|
||||
assert_eq!(LintContext::new("", None).with_tab_width(4).tab_width(), 4);
|
||||
assert_eq!(LintContext::new("", None).with_tab_width(0).tab_width(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
//! Syntactic lint rules for Verilog/SystemVerilog — the engine behind
|
||||
//! `vfmt check`.
|
||||
//!
|
||||
//! This crate plays the role of `ruff_linter` in ruff's architecture: a
|
||||
//! registry of named rules, each handed a prepared file ([`LintContext`]) and
|
||||
//! returning [`Violation`]s that may carry a [`Fix`] classified as
|
||||
//! [`Applicability::Safe`] or [`Applicability::Unsafe`]. Rule ergonomics —
|
||||
//! stable kebab-case names, a style-guide rationale per rule, inline waivers —
|
||||
//! follow Verible.
|
||||
//!
|
||||
//! ```
|
||||
//! use vlog_linter::{run, default_rules};
|
||||
//!
|
||||
//! let violations = run("module m;\n\twire a;\nendmodule\n", None, &default_rules());
|
||||
//! assert_eq!(violations[0].rule, "no-tabs");
|
||||
//! ```
|
||||
//!
|
||||
//! The parse is error-tolerant, so a file that does not fully parse is still
|
||||
//! linted — the parts that failed are `Error` leaves no AST rule matches, and
|
||||
//! the text- and token-level rules do not care. See
|
||||
//! `docs/features/linter-core/README.md`.
|
||||
|
||||
mod context;
|
||||
mod registry;
|
||||
mod rules;
|
||||
mod violation;
|
||||
mod visit;
|
||||
mod waiver;
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub use context::LintContext;
|
||||
pub use registry::{all_rules, default_rules, rule_by_name, select_rules, Rule};
|
||||
pub use violation::{apply_fixes, Applicability, Fix, Fixed, Violation};
|
||||
pub use waiver::UNUSED_WAIVER;
|
||||
|
||||
use waiver::Waivers;
|
||||
|
||||
/// Lints one source text with `enabled`, in one step.
|
||||
///
|
||||
/// `path` is the file the text came from; `None` (a stdin buffer) only makes
|
||||
/// the rules that need a file name go quiet.
|
||||
pub fn run(source: &str, path: Option<PathBuf>, enabled: &[&'static dyn Rule]) -> Vec<Violation> {
|
||||
lint(&LintContext::new(source, path), enabled)
|
||||
}
|
||||
|
||||
/// Lints a prepared file with `enabled`, applying waivers.
|
||||
///
|
||||
/// 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> {
|
||||
let names: Vec<&'static str> = enabled.iter().map(|rule| rule.name()).collect();
|
||||
let mut waivers = Waivers::collect(ctx);
|
||||
|
||||
let mut found = Vec::new();
|
||||
for rule in enabled {
|
||||
found.extend(rule.check(ctx));
|
||||
}
|
||||
let mut kept = waivers.filter(ctx, found);
|
||||
|
||||
if names.contains(&UNUSED_WAIVER) {
|
||||
// `unused-waiver` findings are themselves waivable, which is circular:
|
||||
// waiving one marks another waiver used, and that one must then stop
|
||||
// being reported. Usage only ever grows, so re-deriving the findings
|
||||
// until no further waiver is used terminates — in practice after one
|
||||
// extra round.
|
||||
loop {
|
||||
let before = waivers.used_count();
|
||||
let unused = waivers.unused(&names);
|
||||
let surviving = waivers.filter(ctx, unused);
|
||||
if waivers.used_count() == before {
|
||||
kept.extend(surviving);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
kept.sort_by(|a, b| {
|
||||
(a.span.start, a.span.end, a.rule).cmp(&(b.span.start, b.span.end, b.rule))
|
||||
});
|
||||
kept
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn names(violations: &[Violation]) -> Vec<&str> {
|
||||
violations.iter().map(|v| v.rule).collect()
|
||||
}
|
||||
|
||||
fn lint_all(src: &str) -> Vec<Violation> {
|
||||
run(src, None, &default_rules())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn findings_come_back_in_source_order() {
|
||||
let src = "module m;\n wire a; \n\twire b;\nendmodule\n";
|
||||
assert_eq!(names(&lint_all(src)), vec!["no-trailing-whitespace", "no-tabs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_same_line_waiver_suppresses_that_line_only() {
|
||||
let src = "module m;\n\twire a; // vfmt: waive no-tabs\n\twire b;\nendmodule\n";
|
||||
let found = lint_all(src);
|
||||
assert_eq!(names(&found), vec!["no-tabs"]);
|
||||
assert_eq!(found[0].span.start as usize, src.find("\twire b").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_waiver_on_its_own_line_covers_the_next_one() {
|
||||
let src = "module m;\n // vfmt: waive no-tabs\n\twire a;\n\twire b;\nendmodule\n";
|
||||
let found = lint_all(src);
|
||||
assert_eq!(names(&found), vec!["no-tabs"], "only the second tab line survives");
|
||||
assert_eq!(found[0].span.start as usize, src.find("\twire b").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_verible_spelling_is_accepted() {
|
||||
let src = "module m;\n\twire a; // verilog_lint: waive no-tabs\nendmodule\n";
|
||||
assert!(lint_all(src).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_start_stop_range_covers_its_markers_and_everything_between() {
|
||||
let src = "module m;\n\
|
||||
// vfmt: waive-start no-tabs\n\
|
||||
\twire a;\n\
|
||||
\twire b;\n\
|
||||
// vfmt: waive-stop no-tabs\n\
|
||||
\twire c;\n\
|
||||
endmodule\n";
|
||||
let found = lint_all(src);
|
||||
assert_eq!(names(&found), vec!["no-tabs"]);
|
||||
assert_eq!(found[0].span.start as usize, src.find("\twire c").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unclosed_range_runs_to_the_end_of_the_file() {
|
||||
let src = "module m;\n// vfmt: waive-start no-tabs\n\twire a;\n\twire b;\nendmodule\n";
|
||||
assert!(lint_all(src).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_waiver_that_suppresses_nothing_is_reported() {
|
||||
let src = "module m;\n wire a; // vfmt: waive no-tabs\nendmodule\n";
|
||||
let found = lint_all(src);
|
||||
assert_eq!(names(&found), vec![UNUSED_WAIVER]);
|
||||
assert!(found[0].message.contains("no-tabs"), "{}", found[0].message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_or_malformed_waiver_is_reported() {
|
||||
let src = "module m;\n // vfmt: waive no-such-rule\n // vfmt: waive\nendmodule\n";
|
||||
let found = lint_all(src);
|
||||
assert_eq!(names(&found), vec![UNUSED_WAIVER, UNUSED_WAIVER]);
|
||||
assert!(found[0].message.contains("unknown rule"), "{}", found[0].message);
|
||||
assert!(found[1].message.contains("malformed"), "{}", found[1].message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_verible_waiver_for_a_rule_vfmt_does_not_have_is_ignored() {
|
||||
// Real corpus RTL is annotated for Verible. Waivers naming rules vfmt
|
||||
// has not implemented are that codebase's, not typos, so they are
|
||||
// neither honored nor reported.
|
||||
let src = "module m;\n // verilog_lint: waive macro-name-style\n wire a;\nendmodule\n";
|
||||
assert!(lint_all(src).is_empty());
|
||||
|
||||
// vfmt's own spelling gets no such benefit of the doubt.
|
||||
let src = "module m;\n // vfmt: waive macro-name-style\n wire a;\nendmodule\n";
|
||||
assert_eq!(names(&lint_all(src)), vec![UNUSED_WAIVER]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_waive_stop_without_a_start_is_reported() {
|
||||
let src = "module m;\n // vfmt: waive-stop no-tabs\nendmodule\n";
|
||||
let found = lint_all(src);
|
||||
assert_eq!(names(&found), vec![UNUSED_WAIVER]);
|
||||
assert!(found[0].message.contains("no matching"), "{}", found[0].message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_waiver_for_a_rule_this_run_did_not_enable_is_silent() {
|
||||
let src = "module m;\n wire a; // vfmt: waive no-tabs\nendmodule\n";
|
||||
let enabled = select_rules(&[], &["no-tabs".to_string()]).unwrap();
|
||||
assert!(run(src, None, &enabled).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unused_waiver_findings_can_themselves_be_waived() {
|
||||
let src = "module m;\n\
|
||||
// vfmt: waive unused-waiver\n\
|
||||
wire a; // vfmt: waive no-tabs\n\
|
||||
endmodule\n";
|
||||
assert!(lint_all(src).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabling_the_pseudo_rule_silences_unused_reporting() {
|
||||
let src = "module m;\n wire a; // vfmt: waive no-tabs\nendmodule\n";
|
||||
let enabled = select_rules(&[], &[UNUSED_WAIVER.to_string()]).unwrap();
|
||||
assert!(run(src, None, &enabled).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_parse_still_gets_its_text_rules() {
|
||||
let src = "module m;\n\t@@@ this is not verilog\nendmodule\n";
|
||||
assert_eq!(names(&lint_all(src)), vec!["no-tabs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixing_leaves_the_file_clean_for_the_fixed_rules() {
|
||||
// A tab that is also trailing whitespace needs two rounds: the two
|
||||
// fixes overlap, so the first pass applies one and the second the
|
||||
// other. This is the loop `vfmt check --fix` runs.
|
||||
let mut src = "module m;\n\twire a;\t\n wire b; \nendmodule\n".to_string();
|
||||
for _ in 0..10 {
|
||||
let found = run(&src, None, &default_rules());
|
||||
let fixed = apply_fixes(&src, &found, false);
|
||||
if fixed.applied == 0 {
|
||||
break;
|
||||
}
|
||||
src = fixed.output;
|
||||
}
|
||||
assert_eq!(src, "module m;\n wire a;\n wire b;\nendmodule\n");
|
||||
assert!(run(&src, None, &default_rules()).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
//! The rule trait and the table of rules that exist.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::rules;
|
||||
use crate::violation::Violation;
|
||||
|
||||
/// One lint rule.
|
||||
///
|
||||
/// A rule is a stateless value in a static table: it is handed the prepared
|
||||
/// file and returns what it found. Verible links each of its rules to a
|
||||
/// section of a style guide; [`Rule::doc`] plays that part here and is the
|
||||
/// text a future `--explain` / generated rule reference prints.
|
||||
pub trait Rule: Sync {
|
||||
/// Stable kebab-case identifier, used in diagnostics and waivers.
|
||||
fn name(&self) -> &'static str;
|
||||
|
||||
/// One line, imperative, no trailing period.
|
||||
fn summary(&self) -> &'static str;
|
||||
|
||||
/// Why the rule exists — the style-guide rationale, in prose.
|
||||
fn doc(&self) -> &'static str;
|
||||
|
||||
/// Everything this rule finds in one file.
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation>;
|
||||
}
|
||||
|
||||
/// Every rule that exists, in a stable order.
|
||||
pub fn all_rules() -> Vec<&'static dyn Rule> {
|
||||
vec![
|
||||
&rules::always_comb_blocking::AlwaysCombBlocking,
|
||||
&rules::always_ff_non_blocking::AlwaysFfNonBlocking,
|
||||
&rules::case_missing_default::CaseMissingDefault,
|
||||
&rules::explicit_parameter_storage_type::ExplicitParameterStorageType,
|
||||
&rules::module_filename::ModuleFilename,
|
||||
&rules::no_tabs::NoTabs,
|
||||
&rules::no_trailing_whitespace::NoTrailingWhitespace,
|
||||
&rules::unused_waiver::UnusedWaiver,
|
||||
]
|
||||
}
|
||||
|
||||
/// The rules a plain `vfmt check` runs. Today that is all of them; the split
|
||||
/// exists so a rule can be added in an off-by-default state without changing
|
||||
/// any caller.
|
||||
pub fn default_rules() -> Vec<&'static dyn Rule> {
|
||||
all_rules()
|
||||
}
|
||||
|
||||
/// The rule with this name, if there is one.
|
||||
pub fn rule_by_name(name: &str) -> Option<&'static dyn Rule> {
|
||||
all_rules().into_iter().find(|rule| rule.name() == name)
|
||||
}
|
||||
|
||||
/// The rules a run should use: `select` replaces the default set (empty means
|
||||
/// keep it), then `ignore` removes from whatever is left. An unknown name on
|
||||
/// either list is an error rather than a silent no-op — a typo'd `--select`
|
||||
/// that quietly ran everything would be worse than a failed run.
|
||||
pub fn select_rules(
|
||||
select: &[String],
|
||||
ignore: &[String],
|
||||
) -> Result<Vec<&'static dyn Rule>, String> {
|
||||
let mut chosen = if select.is_empty() {
|
||||
default_rules()
|
||||
} else {
|
||||
let mut chosen = Vec::new();
|
||||
for name in select {
|
||||
let rule = rule_by_name(name).ok_or_else(|| unknown(name))?;
|
||||
if !chosen.iter().any(|r: &&'static dyn Rule| r.name() == rule.name()) {
|
||||
chosen.push(rule);
|
||||
}
|
||||
}
|
||||
chosen
|
||||
};
|
||||
for name in ignore {
|
||||
rule_by_name(name).ok_or_else(|| unknown(name))?;
|
||||
chosen.retain(|rule| rule.name() != name);
|
||||
}
|
||||
Ok(chosen)
|
||||
}
|
||||
|
||||
fn unknown(name: &str) -> String {
|
||||
let known = all_rules().iter().map(|r| r.name()).collect::<Vec<_>>().join(", ");
|
||||
format!("unknown rule: {name} (known rules: {known})")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn names_are_kebab_case_and_unique() {
|
||||
let mut names: Vec<&str> = all_rules().iter().map(|r| r.name()).collect();
|
||||
let count = names.len();
|
||||
names.sort_unstable();
|
||||
names.dedup();
|
||||
assert_eq!(names.len(), count, "rule names must be unique");
|
||||
for name in names {
|
||||
assert!(
|
||||
name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'),
|
||||
"not kebab-case: {name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_rule_documents_itself() {
|
||||
for rule in all_rules() {
|
||||
assert!(!rule.summary().is_empty(), "{}: empty summary", rule.name());
|
||||
assert!(!rule.summary().ends_with('.'), "{}: summary ends in a period", rule.name());
|
||||
assert!(rule.doc().len() > 40, "{}: doc too thin to be a rationale", rule.name());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_are_listed_alphabetically() {
|
||||
let names: Vec<&str> = all_rules().iter().map(|r| r.name()).collect();
|
||||
let mut sorted = names.clone();
|
||||
sorted.sort_unstable();
|
||||
assert_eq!(names, sorted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_defaults_to_the_default_set() {
|
||||
let chosen = select_rules(&[], &[]).unwrap();
|
||||
assert_eq!(chosen.len(), default_rules().len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_narrows_and_ignore_subtracts() {
|
||||
let only = select_rules(&["no-tabs".to_string()], &[]).unwrap();
|
||||
assert_eq!(only.iter().map(|r| r.name()).collect::<Vec<_>>(), vec!["no-tabs"]);
|
||||
|
||||
let without = select_rules(&[], &["no-tabs".to_string()]).unwrap();
|
||||
assert!(!without.iter().any(|r| r.name() == "no-tabs"));
|
||||
assert_eq!(without.len(), default_rules().len() - 1);
|
||||
|
||||
let both = select_rules(
|
||||
&["no-tabs".to_string(), "no-trailing-whitespace".to_string()],
|
||||
&["no-tabs".to_string()],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
both.iter().map(|r| r.name()).collect::<Vec<_>>(),
|
||||
vec!["no-trailing-whitespace"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_name_is_an_error_on_either_list() {
|
||||
assert!(select_rules(&["nope".to_string()], &[]).is_err());
|
||||
assert!(select_rules(&[], &["nope".to_string()]).is_err());
|
||||
let message = select_rules(&["nope".to_string()], &[]).err().unwrap_or_default();
|
||||
assert!(message.contains("no-tabs"), "the error must list what is known: {message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_by_name_finds_every_rule_and_nothing_else() {
|
||||
for rule in all_rules() {
|
||||
assert_eq!(rule_by_name(rule.name()).map(|r| r.name()), Some(rule.name()));
|
||||
}
|
||||
assert!(rule_by_name("no-such-rule").is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
//! `always-comb-blocking` — combinational logic assigns with `=`.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::{walk_items, walk_stmts};
|
||||
use vlog_parser::ast::{ItemKind, StmtKind};
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct AlwaysCombBlocking;
|
||||
|
||||
const NAME: &str = "always-comb-blocking";
|
||||
|
||||
impl Rule for AlwaysCombBlocking {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"assign with `=` inside always_comb"
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A non-blocking assignment in a combinational block schedules its \
|
||||
update for the end of the time step, so a value read later in the same \
|
||||
block sees the stale one and the process may need a second evaluation \
|
||||
to settle — a simulation artifact the synthesized logic does not have. \
|
||||
The mirror image of `always-ff-non-blocking`, and the other half of the \
|
||||
same style-guide rule: `<=` for sequential blocks, `=` for \
|
||||
combinational ones. No automatic fix, for the same reason."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_items(ctx.file(), &mut |item| {
|
||||
let ItemKind::Always { kw, stmt } = &item.kind else { return };
|
||||
if kw != "always_comb" {
|
||||
return;
|
||||
}
|
||||
walk_stmts(stmt, &mut |inner| {
|
||||
if let StmtKind::Assign { op, .. } = &inner.kind {
|
||||
if op == "<=" {
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
"non-blocking assignment `<=` in `always_comb`; use `=`",
|
||||
inner.span,
|
||||
));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
AlwaysCombBlocking.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn wrap(body: &str) -> String {
|
||||
format!("module m;\n always_comb begin\n{body} end\nendmodule\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_nonblocking_assignment() {
|
||||
let found = violations(&wrap(" x <= y;\n"));
|
||||
assert_eq!(found.len(), 1);
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocking_is_clean() {
|
||||
assert!(violations(&wrap(" x = y;\n")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_less_than_or_equal_comparison_is_not_an_assignment() {
|
||||
assert!(violations(&wrap(" x = (a <= b);\n")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_branches_are_reached() {
|
||||
let src = wrap(" if (c) x <= 1;\n else case (s)\n 0: x <= 2;\n default: x = 3;\n endcase\n");
|
||||
assert_eq!(violations(&src).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn always_ff_is_left_to_its_own_rule() {
|
||||
let src = "module m;\n always_ff @(posedge clk) q <= d;\nendmodule\n";
|
||||
assert!(violations(src).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
//! `always-ff-non-blocking` — clocked logic assigns with `<=`.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::{walk_items, walk_stmts};
|
||||
use vlog_parser::ast::{ItemKind, StmtKind};
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct AlwaysFfNonBlocking;
|
||||
|
||||
const NAME: &str = "always-ff-non-blocking";
|
||||
|
||||
impl Rule for AlwaysFfNonBlocking {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"assign with `<=` inside always_ff"
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A blocking assignment in a clocked block updates immediately, so two \
|
||||
flops written in one `always_ff` can see each other's new value in \
|
||||
simulation while the synthesized netlist shows the old one — the \
|
||||
canonical simulation/synthesis mismatch. Verible's style guide, like \
|
||||
every RTL guide since Cummings' paper, asks for `<=` in sequential \
|
||||
blocks and `=` in combinational ones. No automatic fix: swapping the \
|
||||
operator changes what the circuit does, which is exactly the kind of \
|
||||
edit a human has to make."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_items(ctx.file(), &mut |item| {
|
||||
let ItemKind::Always { kw, stmt } = &item.kind else { return };
|
||||
if kw != "always_ff" {
|
||||
return;
|
||||
}
|
||||
walk_stmts(stmt, &mut |inner| {
|
||||
if let StmtKind::Assign { op, .. } = &inner.kind {
|
||||
if op != "<=" {
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!("blocking assignment `{op}` in `always_ff`; use `<=`"),
|
||||
inner.span,
|
||||
));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
AlwaysFfNonBlocking.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn wrap(body: &str) -> String {
|
||||
format!("module m;\n always_ff @(posedge clk) begin\n{body} end\nendmodule\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_blocking_assignment() {
|
||||
let found = violations(&wrap(" q = d;\n"));
|
||||
assert_eq!(found.len(), 1);
|
||||
assert!(found[0].message.contains("`=`"), "{}", found[0].message);
|
||||
assert!(found[0].fix.is_none(), "changing the operator changes the circuit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compound_assignments_are_blocking_too() {
|
||||
assert_eq!(violations(&wrap(" q += 1;\n")).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonblocking_is_clean() {
|
||||
assert!(violations(&wrap(" q <= d;\n")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_loop_variable_is_not_an_assignment_statement() {
|
||||
// `for (int i = 0; i < 4; i++)` is loop syntax, not a procedural
|
||||
// assignment, so it must not be flagged.
|
||||
let src = wrap(" for (int i = 0; i < 4; i++) q[i] <= d[i];\n");
|
||||
assert!(violations(&src).is_empty(), "{:?}", violations(&src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_process_kinds_are_left_to_their_own_rules() {
|
||||
let src = "module m;\n always_comb q = d;\n initial q = 0;\nendmodule\n";
|
||||
assert!(violations(src).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//! `case-missing-default` — every case statement needs a `default` branch.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::{walk_all_stmts, walk_items};
|
||||
use vlog_parser::ast::{CaseItem, GenCaseItem, ItemKind, StmtKind};
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct CaseMissingDefault;
|
||||
|
||||
const NAME: &str = "case-missing-default";
|
||||
|
||||
impl Rule for CaseMissingDefault {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"give every case statement a default branch"
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A case statement with no `default` infers a latch in combinational \
|
||||
logic and leaves the unlisted patterns unspecified in simulation — the \
|
||||
classic source of a synthesis/simulation mismatch. Verible's style \
|
||||
guide asks for an explicit `default`, even one that only assigns X or \
|
||||
repeats the reset value, so the intent is written down rather than \
|
||||
inferred. Fixing this is a design decision, so no automatic fix is \
|
||||
offered. `unique`/`priority` case statements are flagged too: the \
|
||||
qualifier is a promise to the tools, not a branch."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_all_stmts(ctx.file(), &mut |stmt| {
|
||||
if let StmtKind::Case { kw, items, .. } = &stmt.kind {
|
||||
if !items.iter().any(CaseItem::is_default) {
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!("`{kw}` statement has no `default` branch"),
|
||||
stmt.span,
|
||||
));
|
||||
}
|
||||
}
|
||||
});
|
||||
walk_items(ctx.file(), &mut |item| {
|
||||
if let ItemKind::GenCase(case) = &item.kind {
|
||||
if !case.items.iter().any(GenCaseItem::is_default) {
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
"generate `case` has no `default` branch",
|
||||
item.span,
|
||||
));
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// A case item with no labels is the `default` one — the AST spells it that
|
||||
/// way for both statement and generate cases.
|
||||
trait IsDefault {
|
||||
fn is_default(&self) -> bool;
|
||||
}
|
||||
|
||||
impl IsDefault for CaseItem {
|
||||
fn is_default(&self) -> bool {
|
||||
self.labels.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl IsDefault for GenCaseItem {
|
||||
fn is_default(&self) -> bool {
|
||||
self.labels.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
CaseMissingDefault.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
fn wrap(body: &str) -> String {
|
||||
format!("module m;\n always_comb begin\n{body} end\nendmodule\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_case_without_default() {
|
||||
let found = violations(&wrap(" case (s)\n 0: x = 1;\n endcase\n"));
|
||||
assert_eq!(found.len(), 1);
|
||||
assert!(found[0].message.contains("`case`"), "{}", found[0].message);
|
||||
assert!(found[0].fix.is_none(), "adding a default is a design decision");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_default_branch_satisfies_it() {
|
||||
let src = wrap(" case (s)\n 0: x = 1;\n default: x = 0;\n endcase\n");
|
||||
assert!(violations(&src).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn casex_and_casez_count_too() {
|
||||
let found = violations(&wrap(" casez (s)\n 2'b1?: x = 1;\n endcase\n"));
|
||||
assert_eq!(found.len(), 1);
|
||||
assert!(found[0].message.contains("`casez`"), "{}", found[0].message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_qualifier_is_not_a_branch() {
|
||||
let src = wrap(" unique case (s)\n 0: x = 1;\n endcase\n");
|
||||
assert_eq!(violations(&src).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generate_case_is_covered() {
|
||||
let src = "module m;\n\
|
||||
generate\n\
|
||||
case (WIDTH)\n\
|
||||
1: begin : g\n wire a;\n end\n\
|
||||
endcase\n\
|
||||
endgenerate\n\
|
||||
endmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].message.contains("generate"), "{}", found[0].message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
//! `explicit-parameter-storage-type` — every parameter names its type.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::violation::Violation;
|
||||
use crate::visit::{walk_all_stmts, walk_items};
|
||||
use vlog_parser::ast::{ItemKind, ParamDecl, StmtKind};
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct ExplicitParameterStorageType;
|
||||
|
||||
const NAME: &str = "explicit-parameter-storage-type";
|
||||
|
||||
impl Rule for ExplicitParameterStorageType {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"declare a storage type on every parameter"
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A parameter with no declared type takes its type from whatever it is \
|
||||
assigned — and an override at instantiation can change that type, not \
|
||||
just the value, so `parameter WIDTH = 8` silently becomes signed, or \
|
||||
wider, depending on the caller. Verible's style guide asks for an \
|
||||
explicit `int` / `logic [N-1:0]` / typedef so the width and signedness \
|
||||
are fixed by the declaration. No automatic fix: only the author knows \
|
||||
which type was meant. Continuation parameters (`parameter int A = 1, \
|
||||
B = 2`) are not flagged separately — they inherit the type of the \
|
||||
declaration that opened the list."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
walk_items(ctx.file(), &mut |item| match &item.kind {
|
||||
ItemKind::ParamDecl(decl) => untyped_decl(decl, &mut out),
|
||||
ItemKind::Module(module) => {
|
||||
for port in module.param_ports.iter().flatten() {
|
||||
// Only an entry that writes the keyword opens a
|
||||
// declaration; the rest continue the previous one's type.
|
||||
let Some(kw) = &port.kw else { continue };
|
||||
if port.is_type || !port.ty.name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!("`{kw}` has no storage type: `{}`", port.name),
|
||||
port.name_span,
|
||||
));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
walk_all_stmts(ctx.file(), &mut |stmt| {
|
||||
if let StmtKind::ParamDecl(decl) = &stmt.kind {
|
||||
untyped_decl(decl, &mut out);
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Reports every name of a `parameter`/`localparam` declaration that wrote no
|
||||
/// storage type.
|
||||
fn untyped_decl(decl: &ParamDecl, out: &mut Vec<Violation>) {
|
||||
if !decl.ty.name.is_empty() {
|
||||
return;
|
||||
}
|
||||
for declarator in &decl.declarators {
|
||||
out.push(Violation::new(
|
||||
NAME,
|
||||
format!("`{}` has no storage type: `{}`", decl.kw, declarator.name),
|
||||
declarator.name_span,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
ExplicitParameterStorageType.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_an_untyped_parameter_port() {
|
||||
let found = violations("module m #(parameter WIDTH = 8) ();\nendmodule\n");
|
||||
assert_eq!(found.len(), 1);
|
||||
assert!(found[0].message.contains("WIDTH"), "{}", found[0].message);
|
||||
assert!(found[0].fix.is_none(), "only the author knows the intended type");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typed_parameter_port_is_clean() {
|
||||
assert!(violations("module m #(parameter int WIDTH = 8) ();\nendmodule\n").is_empty());
|
||||
assert!(violations("module m #(parameter my_t W = 8) ();\nendmodule\n").is_empty());
|
||||
assert!(violations("module m #(parameter type T = int) ();\nendmodule\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_continuation_parameter_inherits_and_is_not_flagged_twice() {
|
||||
let found = violations("module m #(parameter int A = 1, B = 2) ();\nendmodule\n");
|
||||
assert!(found.is_empty(), "{found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn item_level_parameters_and_localparams_are_covered() {
|
||||
let src = "module m;\n parameter A = 1;\n localparam B = 2;\n\
|
||||
localparam int C = 3;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 2, "{found:?}");
|
||||
assert!(found[0].message.contains("parameter"), "{}", found[0].message);
|
||||
assert!(found[1].message.contains("localparam"), "{}", found[1].message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packed_dimensions_alone_are_not_a_storage_type() {
|
||||
assert_eq!(violations("module m;\n parameter [7:0] A = 1;\nendmodule\n").len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_name_of_a_multi_declarator_line_is_pointed_at() {
|
||||
let found = violations("module m;\n parameter A = 1, B = 2;\nendmodule\n");
|
||||
assert_eq!(found.len(), 2);
|
||||
assert_ne!(found[0].span.start, found[1].span.start);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
//! The rules themselves, one module each.
|
||||
//!
|
||||
//! Every rule in this round is **syntactic** — text, tokens or tree shape —
|
||||
//! per TODO.md §7: semantic rules wait for `vlog_semantic` to be wired in.
|
||||
|
||||
pub mod always_comb_blocking;
|
||||
pub mod always_ff_non_blocking;
|
||||
pub mod case_missing_default;
|
||||
pub mod explicit_parameter_storage_type;
|
||||
pub mod module_filename;
|
||||
pub mod no_tabs;
|
||||
pub mod no_trailing_whitespace;
|
||||
pub mod unused_waiver;
|
||||
@@ -0,0 +1,95 @@
|
||||
//! `module-filename` — a one-module file is named after its module.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::ast::ItemKind;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct ModuleFilename;
|
||||
|
||||
const NAME: &str = "module-filename";
|
||||
|
||||
impl Rule for ModuleFilename {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"name a one-module file after its module"
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"Every Verilog tool that finds a module by searching a library \
|
||||
directory — simulators, synthesis `-y` paths, most build systems — \
|
||||
looks for `<module>.sv`, and humans grep the same way. Verible's style \
|
||||
guide makes the file name match the module it declares. The rule only \
|
||||
speaks when the file declares exactly one module: a package of small \
|
||||
modules, or a file with none, is a deliberate choice it has nothing to \
|
||||
say about. It is silent for input with no file name (stdin), and \
|
||||
offers no fix — renaming a file is not the linter's business."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let Some(path) = ctx.path() else { return Vec::new() };
|
||||
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { return Vec::new() };
|
||||
let mut modules = ctx.file().items.iter().filter_map(|item| match &item.kind {
|
||||
ItemKind::Module(module) => Some(module),
|
||||
_ => None,
|
||||
});
|
||||
let (Some(module), None) = (modules.next(), modules.next()) else { return Vec::new() };
|
||||
if module.name == stem {
|
||||
return Vec::new();
|
||||
}
|
||||
let file_name = path.file_name().and_then(|s| s.to_str()).unwrap_or(stem);
|
||||
vec![Violation::new(
|
||||
NAME,
|
||||
format!("module `{}` does not match file name `{file_name}`", module.name),
|
||||
module.name_span,
|
||||
)]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn violations(src: &str, path: Option<&str>) -> Vec<Violation> {
|
||||
let ctx = LintContext::new(src, path.map(PathBuf::from));
|
||||
ModuleFilename.check(&ctx)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_a_mismatch() {
|
||||
let found = violations("module foo;\nendmodule\n", Some("rtl/bar.sv"));
|
||||
assert_eq!(found.len(), 1);
|
||||
assert!(found[0].message.contains("bar.sv"), "{}", found[0].message);
|
||||
assert!(found[0].fix.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_matching_name_is_clean() {
|
||||
assert!(violations("module foo;\nendmodule\n", Some("rtl/foo.sv")).is_empty());
|
||||
assert!(violations("module foo;\nendmodule\n", Some("rtl/foo.v")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silent_without_a_file_name() {
|
||||
assert!(violations("module foo;\nendmodule\n", None).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silent_unless_the_file_declares_exactly_one_module() {
|
||||
let two = "module foo;\nendmodule\nmodule baz;\nendmodule\n";
|
||||
assert!(violations(two, Some("rtl/bar.sv")).is_empty());
|
||||
assert!(violations("package p;\nendpackage\n", Some("rtl/bar.sv")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_points_at_the_module_name() {
|
||||
let src = "module foo;\nendmodule\n";
|
||||
let found = violations(src, Some("bar.sv"));
|
||||
assert_eq!(&src[found[0].span.as_range()], "foo");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
//! `no-tabs` — indent and align with spaces, never tabs.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::violation::{Fix, Violation};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct NoTabs;
|
||||
|
||||
const NAME: &str = "no-tabs";
|
||||
|
||||
impl Rule for NoTabs {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"use spaces, not tabs"
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A tab renders at a width nobody agrees on, so a file mixing tabs and \
|
||||
spaces looks aligned in the editor that wrote it and ragged everywhere \
|
||||
else — and code review diffs inherit the mess. Verible's style guide \
|
||||
(and vfmt's own output) indents with spaces only. The fix expands each \
|
||||
tab to the run's indent width; tabs inside string literals are left \
|
||||
alone, because there the whitespace is data."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
for line in 1..=ctx.line_index().line_count() {
|
||||
let Some(range) = ctx.line_index().line_range(line) else { continue };
|
||||
let text = ctx.line_text(line);
|
||||
let tabs = tab_runs(text, range.start)
|
||||
.filter(|run| !ctx.touches_string(*run))
|
||||
.collect::<Vec<_>>();
|
||||
let Some(first) = tabs.first() else { continue };
|
||||
// One finding per line, but the fix covers every tab on it:
|
||||
// reporting each tab separately buries a tab-indented file in
|
||||
// diagnostics that all say the same thing.
|
||||
let spaces = " ".repeat(ctx.tab_width());
|
||||
let edits = tabs
|
||||
.iter()
|
||||
.map(|run| (*run, spaces.repeat(run.len() as usize)))
|
||||
.collect::<Vec<_>>();
|
||||
out.push(
|
||||
Violation::new(NAME, "tab character; indent with spaces", *first)
|
||||
.with_fix(Fix::safe(edits)),
|
||||
);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The byte ranges of each run of consecutive tabs in `text`, which starts at
|
||||
/// `offset` in the file.
|
||||
fn tab_runs(text: &str, offset: u32) -> impl Iterator<Item = TextRange> + '_ {
|
||||
let mut start = 0usize;
|
||||
std::iter::from_fn(move || {
|
||||
let rest = text.get(start..)?;
|
||||
let at = start + rest.find('\t')?;
|
||||
let end = text[at..].find(|c| c != '\t').map_or(text.len(), |n| at + n);
|
||||
start = end;
|
||||
Some(TextRange::new(offset + at as u32, offset + end as u32))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::violation::apply_fixes;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
NoTabs.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_one_finding_per_line_and_fixes_every_tab() {
|
||||
let src = "module m;\n\twire\ta;\n wire b;\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 1);
|
||||
assert_eq!(found[0].rule, NAME);
|
||||
let fixed = apply_fixes(src, &found, false);
|
||||
assert_eq!(fixed.applied, 1);
|
||||
assert_eq!(fixed.output, "module m;\n wire a;\n wire b;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tab_run_expands_per_tab() {
|
||||
let src = "module m;\n\t\twire a;\nendmodule\n";
|
||||
let ctx = LintContext::new(src, None).with_tab_width(4);
|
||||
let found = NoTabs.check(&ctx);
|
||||
let fixed = apply_fixes(src, &found, false);
|
||||
assert_eq!(fixed.output, "module m;\n wire a;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tab_inside_a_string_is_data_and_is_left_alone() {
|
||||
let src = "module m;\n initial $display(\"a\tb\");\nendmodule\n";
|
||||
assert!(violations(src).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clean_file_is_clean() {
|
||||
assert!(violations("module m;\n wire a;\nendmodule\n").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//! `no-trailing-whitespace` — no spaces or tabs at the end of a line.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::violation::{Fix, Violation};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct NoTrailingWhitespace;
|
||||
|
||||
const NAME: &str = "no-trailing-whitespace";
|
||||
|
||||
impl Rule for NoTrailingWhitespace {
|
||||
fn name(&self) -> &'static str {
|
||||
NAME
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"no whitespace at the end of a line"
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"Trailing whitespace is invisible, so it survives review and then shows \
|
||||
up as diff noise the day somebody's editor strips it — a one-character \
|
||||
change that touches every line of the file. Verible's style guide \
|
||||
forbids it and vfmt's formatter never emits it. The fix deletes the \
|
||||
run; a run inside a string literal is left alone, because there the \
|
||||
whitespace is data."
|
||||
}
|
||||
|
||||
fn check(&self, ctx: &LintContext) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
for line in 1..=ctx.line_index().line_count() {
|
||||
let Some(range) = ctx.line_index().line_range(line) else { continue };
|
||||
let text = ctx.line_text(line);
|
||||
let trimmed = text.trim_end_matches([' ', '\t']);
|
||||
if trimmed.len() == text.len() {
|
||||
continue;
|
||||
}
|
||||
let span = TextRange::new(range.start + trimmed.len() as u32, range.end);
|
||||
if ctx.touches_string(span) {
|
||||
continue;
|
||||
}
|
||||
out.push(
|
||||
Violation::new(NAME, "trailing whitespace", span)
|
||||
.with_fix(Fix::safe(vec![(span, String::new())])),
|
||||
);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::violation::apply_fixes;
|
||||
|
||||
fn violations(src: &str) -> Vec<Violation> {
|
||||
NoTrailingWhitespace.check(&LintContext::new(src, None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_and_deletes_the_run() {
|
||||
let src = "module m; \n wire a;\t\nendmodule\n";
|
||||
let found = violations(src);
|
||||
assert_eq!(found.len(), 2);
|
||||
let fixed = apply_fixes(src, &found, false);
|
||||
assert_eq!(fixed.applied, 2);
|
||||
assert_eq!(fixed.output, "module m;\n wire a;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whitespace_only_line_is_flagged() {
|
||||
let src = "module m;\n \nendmodule\n";
|
||||
assert_eq!(violations(src).len(), 1);
|
||||
assert_eq!(apply_fixes(src, &violations(src), false).output, "module m;\n\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_without_a_newline_at_eof_is_covered() {
|
||||
assert_eq!(violations("module m;\nendmodule ").len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clean_file_is_clean() {
|
||||
assert!(violations("module m;\n wire a;\nendmodule\n").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//! `unused-waiver` — the waiver engine's own findings.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::Rule;
|
||||
use crate::violation::Violation;
|
||||
use crate::waiver::UNUSED_WAIVER;
|
||||
|
||||
/// See [`Rule::doc`].
|
||||
pub struct UnusedWaiver;
|
||||
|
||||
impl Rule for UnusedWaiver {
|
||||
fn name(&self) -> &'static str {
|
||||
UNUSED_WAIVER
|
||||
}
|
||||
|
||||
fn summary(&self) -> &'static str {
|
||||
"remove waivers that no longer suppress anything"
|
||||
}
|
||||
|
||||
fn doc(&self) -> &'static str {
|
||||
"A `// vfmt: waive` comment outlives the problem it was written for: \
|
||||
the code is fixed, the waiver stays, and the next reader believes the \
|
||||
line is still exempt. ruff's experience is that suppressions only stay \
|
||||
honest if the linter reports the dead ones, so vfmt does it from day \
|
||||
one. Reported for a waiver that suppressed nothing, one that names a \
|
||||
rule that does not exist, and one that is malformed. A waiver for a \
|
||||
rule this run did not enable is *not* reported — it never had a \
|
||||
chance to fire. It is a registry entry so `--select` / `--ignore` and \
|
||||
waivers can name it, but its findings come from the waiver engine \
|
||||
rather than from a pass over the file, so `check` here is empty."
|
||||
}
|
||||
|
||||
fn check(&self, _ctx: &LintContext) -> Vec<Violation> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
//! What a rule reports, and what it offers to change.
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// One rule finding: which rule, what is wrong, where, and — sometimes —
|
||||
/// how to repair it.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Violation {
|
||||
/// The reporting rule's stable kebab-case name.
|
||||
pub rule: &'static str,
|
||||
/// One sentence, lower case, no trailing period — the diagnostic line.
|
||||
pub message: String,
|
||||
/// Byte range the diagnostic points at.
|
||||
pub span: TextRange,
|
||||
/// An automatic repair, when the rule can offer one.
|
||||
pub fix: Option<Fix>,
|
||||
}
|
||||
|
||||
impl Violation {
|
||||
/// A finding with no automatic repair.
|
||||
pub fn new(rule: &'static str, message: impl Into<String>, span: TextRange) -> Violation {
|
||||
Violation { rule, message: message.into(), span, fix: None }
|
||||
}
|
||||
|
||||
/// The same finding, carrying a repair.
|
||||
pub fn with_fix(mut self, fix: Fix) -> Violation {
|
||||
self.fix = Some(fix);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A repair for one violation: replace each range with the given text.
|
||||
///
|
||||
/// The edits are applied as a set — either all of them or none — so a rule
|
||||
/// may split one logical repair across several places in the file.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Fix {
|
||||
/// `(range, replacement)` pairs; a replacement of `""` is a deletion.
|
||||
pub edits: Vec<(TextRange, String)>,
|
||||
/// Whether applying this without review can change behavior.
|
||||
pub applicability: Applicability,
|
||||
}
|
||||
|
||||
impl Fix {
|
||||
/// A repair that cannot change what the code means.
|
||||
pub fn safe(edits: Vec<(TextRange, String)>) -> Fix {
|
||||
Fix { edits, applicability: Applicability::Safe }
|
||||
}
|
||||
|
||||
/// A repair that may change what the code means; `--unsafe-fixes` only.
|
||||
pub fn unsafe_fix(edits: Vec<(TextRange, String)>) -> Fix {
|
||||
Fix { edits, applicability: Applicability::Unsafe }
|
||||
}
|
||||
}
|
||||
|
||||
/// ruff's fix-safety classification, adopted verbatim: `--fix` applies
|
||||
/// [`Safe`](Applicability::Safe) fixes, `--unsafe-fixes` widens that to all.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Applicability {
|
||||
/// Preserves meaning and intent — whitespace, spelling of a keyword.
|
||||
Safe,
|
||||
/// Preserves meaning as far as the rule can tell, but the author may
|
||||
/// have meant what they wrote (`=` → `<=` in a clocked block).
|
||||
Unsafe,
|
||||
}
|
||||
|
||||
impl Applicability {
|
||||
/// The word used for this level in `--output-format json`.
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Applicability::Safe => "safe",
|
||||
Applicability::Unsafe => "unsafe",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of rewriting a source text with the fixes it had.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Fixed {
|
||||
/// The rewritten text.
|
||||
pub output: String,
|
||||
/// How many violations' fixes were applied.
|
||||
pub applied: usize,
|
||||
}
|
||||
|
||||
/// Applies the fixes of `violations` to `source`.
|
||||
///
|
||||
/// Fixes are applied left to right; one that overlaps an already-applied fix
|
||||
/// is skipped, so a single pass never produces garbled text. Running the
|
||||
/// linter again picks the skipped ones up — this is why the CLI's `--fix`
|
||||
/// loops until nothing changes.
|
||||
pub fn apply_fixes(source: &str, violations: &[Violation], include_unsafe: bool) -> Fixed {
|
||||
let mut fixes: Vec<Vec<(TextRange, String)>> = Vec::new();
|
||||
for violation in violations {
|
||||
let Some(fix) = &violation.fix else { continue };
|
||||
if fix.applicability == Applicability::Unsafe && !include_unsafe {
|
||||
continue;
|
||||
}
|
||||
let mut edits = fix.edits.clone();
|
||||
edits.sort_by_key(|(range, _)| (range.start, range.end));
|
||||
if edits.is_empty() || overlaps_itself(&edits) {
|
||||
continue;
|
||||
}
|
||||
fixes.push(edits);
|
||||
}
|
||||
fixes.sort_by_key(|edits| edits.first().map_or(0, |(range, _)| range.start));
|
||||
|
||||
let mut output = String::with_capacity(source.len());
|
||||
let mut cursor = 0usize;
|
||||
let mut applied = 0usize;
|
||||
for edits in fixes {
|
||||
let start = edits[0].0.start as usize;
|
||||
if start < cursor {
|
||||
continue; // Overlaps a fix already applied; next round gets it.
|
||||
}
|
||||
for (range, replacement) in &edits {
|
||||
let (start, end) = (range.start as usize, range.end as usize);
|
||||
if start < cursor || end > source.len() || !source.is_char_boundary(start) {
|
||||
continue;
|
||||
}
|
||||
output.push_str(&source[cursor..start]);
|
||||
output.push_str(replacement);
|
||||
cursor = end;
|
||||
}
|
||||
applied += 1;
|
||||
}
|
||||
output.push_str(&source[cursor.min(source.len())..]);
|
||||
Fixed { output, applied }
|
||||
}
|
||||
|
||||
/// True when two edits of one fix cover the same byte — a rule bug, and a
|
||||
/// reason to drop that fix rather than produce nonsense.
|
||||
fn overlaps_itself(edits: &[(TextRange, String)]) -> bool {
|
||||
edits.windows(2).any(|pair| pair[0].0.end > pair[1].0.start)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn violation(fix: Fix) -> Violation {
|
||||
Violation::new("t", "m", TextRange::new(0, 0)).with_fix(fix)
|
||||
}
|
||||
|
||||
fn edit(start: u32, end: u32, text: &str) -> (TextRange, String) {
|
||||
(TextRange::new(start, end), text.to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applies_edits_in_order() {
|
||||
let v = vec![
|
||||
violation(Fix::safe(vec![edit(6, 11, "there")])),
|
||||
violation(Fix::safe(vec![edit(0, 5, "howdy")])),
|
||||
];
|
||||
let fixed = apply_fixes("hello world", &v, false);
|
||||
assert_eq!(fixed.output, "howdy there");
|
||||
assert_eq!(fixed.applied, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsafe_fixes_need_asking_for() {
|
||||
let v = vec![violation(Fix::unsafe_fix(vec![edit(0, 5, "howdy")]))];
|
||||
assert_eq!(apply_fixes("hello", &v, false).applied, 0);
|
||||
assert_eq!(apply_fixes("hello", &v, true).output, "howdy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_overlapping_fix_is_skipped_not_garbled() {
|
||||
let v = vec![
|
||||
violation(Fix::safe(vec![edit(0, 5, "howdy")])),
|
||||
violation(Fix::safe(vec![edit(3, 8, "XX")])),
|
||||
];
|
||||
let fixed = apply_fixes("hello world", &v, false);
|
||||
assert_eq!(fixed.output, "howdy world");
|
||||
assert_eq!(fixed.applied, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_edit_fix_is_all_or_nothing() {
|
||||
let v = vec![violation(Fix::safe(vec![edit(0, 1, "H"), edit(6, 7, "W")]))];
|
||||
let fixed = apply_fixes("hello world", &v, false);
|
||||
assert_eq!(fixed.output, "Hello World");
|
||||
assert_eq!(fixed.applied, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_self_overlapping_fix_is_dropped() {
|
||||
let v = vec![violation(Fix::safe(vec![edit(0, 4, "a"), edit(2, 6, "b")]))];
|
||||
assert_eq!(apply_fixes("hello world", &v, false).applied, 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
//! Tree walks shared by the AST rules.
|
||||
//!
|
||||
//! Deliberately dumb: every walk visits every node of its kind, and the rule
|
||||
//! decides what it cares about. `Error` leaves from a tolerant parse hold raw
|
||||
//! text and no children, so they are visited and matched by nothing.
|
||||
|
||||
use vlog_parser::ast::{GenBlock, GenElse, Item, ItemKind, SourceFile, Stmt, StmtKind};
|
||||
|
||||
/// Calls `f` on every item in the file, nested items included.
|
||||
pub(crate) fn walk_items(file: &SourceFile, f: &mut dyn FnMut(&Item)) {
|
||||
items(&file.items, f);
|
||||
}
|
||||
|
||||
fn items(list: &[Item], f: &mut dyn FnMut(&Item)) {
|
||||
for item in list {
|
||||
f(item);
|
||||
match &item.kind {
|
||||
ItemKind::Module(m) => items(&m.items, f),
|
||||
ItemKind::Package { items: inner, .. } => items(inner, f),
|
||||
ItemKind::GenerateRegion { items: inner, .. } => items(inner, f),
|
||||
ItemKind::GenIf(gen_if) => {
|
||||
gen_block(&gen_if.then, f);
|
||||
let mut els = gen_if.els.as_deref();
|
||||
while let Some(branch) = els {
|
||||
match branch {
|
||||
GenElse::If(_, nested) => {
|
||||
gen_block(&nested.then, f);
|
||||
els = nested.els.as_deref();
|
||||
}
|
||||
GenElse::Block(block) => {
|
||||
gen_block(block, f);
|
||||
els = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::GenFor(gen_for) => gen_block(&gen_for.body, f),
|
||||
ItemKind::GenCase(gen_case) => {
|
||||
for case_item in &gen_case.items {
|
||||
gen_block(&case_item.body, f);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_block(block: &GenBlock, f: &mut dyn FnMut(&Item)) {
|
||||
items(&block.items, f);
|
||||
}
|
||||
|
||||
/// Calls `f` on every statement of the file, nested statements included.
|
||||
pub(crate) fn walk_all_stmts(file: &SourceFile, f: &mut dyn FnMut(&Stmt)) {
|
||||
walk_items(file, &mut |item| match &item.kind {
|
||||
ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => {
|
||||
walk_stmts(stmt, f)
|
||||
}
|
||||
ItemKind::Function(decl) => stmts(&decl.stmts, f),
|
||||
ItemKind::Task(decl) => stmts(&decl.stmts, f),
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
|
||||
/// Calls `f` on `stmt` and every statement inside it.
|
||||
pub(crate) fn walk_stmts(stmt: &Stmt, f: &mut dyn FnMut(&Stmt)) {
|
||||
f(stmt);
|
||||
match &stmt.kind {
|
||||
StmtKind::Block { stmts: inner, .. } | StmtKind::ForkJoin { stmts: inner, .. } => {
|
||||
stmts(inner, f)
|
||||
}
|
||||
StmtKind::If { then, els, .. } => {
|
||||
walk_stmts(then, f);
|
||||
if let Some(els) = els {
|
||||
walk_stmts(els, f);
|
||||
}
|
||||
}
|
||||
StmtKind::Case { items, .. } => {
|
||||
for case_item in items {
|
||||
walk_stmts(&case_item.stmt, f);
|
||||
}
|
||||
}
|
||||
StmtKind::For { body, .. }
|
||||
| StmtKind::While { body, .. }
|
||||
| StmtKind::DoWhile { body, .. }
|
||||
| StmtKind::Repeat { body, .. }
|
||||
| StmtKind::Forever { body }
|
||||
| StmtKind::Foreach { body, .. } => walk_stmts(body, f),
|
||||
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
|
||||
walk_stmts(inner, f)
|
||||
}
|
||||
StmtKind::Assert { then, els, .. } => {
|
||||
if let Some(then) = then {
|
||||
walk_stmts(then, f);
|
||||
}
|
||||
if let Some(els) = els {
|
||||
walk_stmts(els, f);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn stmts(list: &[Stmt], f: &mut dyn FnMut(&Stmt)) {
|
||||
for stmt in list {
|
||||
walk_stmts(stmt, f);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
|
||||
fn count_assignments(src: &str) -> usize {
|
||||
let (file, _) = parse_source_tolerant(src);
|
||||
let mut n = 0;
|
||||
walk_all_stmts(&file, &mut |stmt| {
|
||||
if matches!(stmt.kind, StmtKind::Assign { .. }) {
|
||||
n += 1;
|
||||
}
|
||||
});
|
||||
n
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reaches_statements_through_every_nesting() {
|
||||
let src = "module m;\n\
|
||||
always_ff @(posedge clk) begin\n\
|
||||
if (a) x <= 1; else x <= 2;\n\
|
||||
case (y)\n\
|
||||
0: for (int i = 0; i < 2; i++) z <= i;\n\
|
||||
default: z <= 0;\n\
|
||||
endcase\n\
|
||||
end\n\
|
||||
endmodule\n";
|
||||
assert_eq!(count_assignments(src), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reaches_items_inside_generate() {
|
||||
let src = "module m;\n\
|
||||
generate\n\
|
||||
if (A) begin : g\n\
|
||||
always_comb x = 1;\n\
|
||||
end else begin\n\
|
||||
always_comb x = 2;\n\
|
||||
end\n\
|
||||
endgenerate\n\
|
||||
endmodule\n";
|
||||
assert_eq!(count_assignments(src), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unparsable_region_is_visited_but_holds_nothing() {
|
||||
let (file, diagnostics) = parse_source_tolerant("module m;\n @@@;\nendmodule\n");
|
||||
assert!(!diagnostics.is_empty());
|
||||
let mut errors = 0;
|
||||
walk_items(&file, &mut |item| {
|
||||
if matches!(item.kind, ItemKind::Error(_)) {
|
||||
errors += 1;
|
||||
}
|
||||
});
|
||||
assert!(errors > 0, "the error leaf must be reachable");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
//! Inline waivers: `// vfmt: waive <rule>` and friends.
|
||||
//!
|
||||
//! Grammar (Verible's, with a `vfmt:` alias — `verilog_lint:` is what
|
||||
//! existing RTL is annotated with, so both spellings are accepted):
|
||||
//!
|
||||
//! ```text
|
||||
//! // vfmt: waive <rule> this line, or the next if written alone
|
||||
//! // vfmt: waive-start <rule> from this line ...
|
||||
//! // vfmt: waive-stop <rule> ... to this one, both included
|
||||
//! ```
|
||||
//!
|
||||
//! A waiver that suppresses nothing is itself reported, under the
|
||||
//! `unused-waiver` rule — ruff's lesson that dead suppressions accumulate
|
||||
//! forever unless the linter complains about them.
|
||||
|
||||
use crate::context::LintContext;
|
||||
use crate::registry::rule_by_name;
|
||||
use crate::violation::Violation;
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// The name reported for waiver problems. It is a real registry entry (so
|
||||
/// `--select` / `--ignore` / waivers can name it), but the findings are
|
||||
/// produced here rather than by a syntactic check.
|
||||
pub const UNUSED_WAIVER: &str = "unused-waiver";
|
||||
|
||||
/// Every waiver in one file.
|
||||
pub(crate) struct Waivers {
|
||||
entries: Vec<Entry>,
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
/// The rule waived; empty when the comment did not parse.
|
||||
rule: String,
|
||||
/// Written with the `vfmt:` spelling. A `verilog_lint:` waiver naming a
|
||||
/// rule vfmt does not have is Verible's, not a typo, so it is ignored
|
||||
/// rather than reported — that is what makes a Verible-annotated
|
||||
/// codebase lintable by vfmt without editing it first.
|
||||
ours: bool,
|
||||
scope: Scope,
|
||||
/// The waiver comment itself — where an `unused-waiver` points.
|
||||
span: TextRange,
|
||||
/// Set when the waiver is broken rather than merely unused.
|
||||
problem: Option<String>,
|
||||
used: bool,
|
||||
}
|
||||
|
||||
enum Scope {
|
||||
/// One line.
|
||||
Line(u32),
|
||||
/// Lines `start..=end`, both markers included.
|
||||
Range(u32, u32),
|
||||
}
|
||||
|
||||
impl Scope {
|
||||
fn covers(&self, line: u32) -> bool {
|
||||
match *self {
|
||||
Scope::Line(l) => l == line,
|
||||
Scope::Range(start, end) => start <= line && line <= end,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Directive {
|
||||
Waive(String),
|
||||
Start(String),
|
||||
Stop(String),
|
||||
/// Recognizably a waiver, but not a well-formed one.
|
||||
Malformed,
|
||||
}
|
||||
|
||||
impl Waivers {
|
||||
/// Reads every waiver comment in the file.
|
||||
pub(crate) fn collect(ctx: &LintContext) -> Waivers {
|
||||
let mut entries = Vec::new();
|
||||
// (rule, opening line, opening comment span), innermost last.
|
||||
let mut open: Vec<(String, bool, u32, TextRange)> = Vec::new();
|
||||
|
||||
for comment in ctx.comments() {
|
||||
let Some((directive, ours)) = parse_directive(&comment.text) else { continue };
|
||||
match directive {
|
||||
Directive::Waive(rule) => {
|
||||
let line = if alone_on_its_line(ctx, comment.span) {
|
||||
comment.line + 1
|
||||
} else {
|
||||
comment.line
|
||||
};
|
||||
entries.push(Entry::new(rule, ours, Scope::Line(line), comment.span));
|
||||
}
|
||||
Directive::Start(rule) => open.push((rule, ours, comment.line, comment.span)),
|
||||
Directive::Stop(rule) => match take_open(&mut open, &rule) {
|
||||
Some((ours, start_line, start_span)) => entries.push(Entry::new(
|
||||
rule,
|
||||
ours,
|
||||
Scope::Range(start_line, comment.line),
|
||||
start_span,
|
||||
)),
|
||||
None => entries.push(Entry::broken(
|
||||
comment.span,
|
||||
format!("`waive-stop {rule}` has no matching `waive-start`"),
|
||||
)),
|
||||
},
|
||||
Directive::Malformed => entries.push(Entry::broken(
|
||||
comment.span,
|
||||
"malformed waiver: expected `// vfmt: waive <rule-name>`".to_string(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
// An unclosed range runs to the end of the file, the same way an
|
||||
// unclosed format fence does.
|
||||
for (rule, ours, line, span) in open {
|
||||
entries.push(Entry::new(rule, ours, Scope::Range(line, u32::MAX), span));
|
||||
}
|
||||
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()
|
||||
}
|
||||
|
||||
/// How many waivers have suppressed something so far. Grows only, which
|
||||
/// is what makes the caller's re-derivation loop terminate.
|
||||
pub(crate) fn used_count(&self) -> usize {
|
||||
self.entries.iter().filter(|entry| entry.used).count()
|
||||
}
|
||||
|
||||
/// The `unused-waiver` findings: waivers that suppressed nothing, plus
|
||||
/// waivers that are broken outright. A waiver for a rule this run did
|
||||
/// not enable is silent — it never had a chance to fire.
|
||||
pub(crate) fn unused(&self, enabled: &[&'static str]) -> Vec<Violation> {
|
||||
let mut out = Vec::new();
|
||||
for entry in &self.entries {
|
||||
if let Some(problem) = &entry.problem {
|
||||
out.push(Violation::new(UNUSED_WAIVER, problem.clone(), entry.span));
|
||||
} else if rule_by_name(&entry.rule).is_none() {
|
||||
if entry.ours {
|
||||
out.push(Violation::new(
|
||||
UNUSED_WAIVER,
|
||||
format!("waiver names unknown rule `{}`", entry.rule),
|
||||
entry.span,
|
||||
));
|
||||
}
|
||||
} else if !entry.used && enabled.contains(&entry.rule.as_str()) {
|
||||
out.push(Violation::new(
|
||||
UNUSED_WAIVER,
|
||||
format!("unused waiver for `{}`", entry.rule),
|
||||
entry.span,
|
||||
));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
fn new(rule: String, ours: bool, scope: Scope, span: TextRange) -> Entry {
|
||||
Entry { rule, ours, scope, span, problem: None, used: false }
|
||||
}
|
||||
|
||||
fn broken(span: TextRange, problem: String) -> Entry {
|
||||
Entry {
|
||||
rule: String::new(),
|
||||
ours: true,
|
||||
scope: Scope::Line(0),
|
||||
span,
|
||||
problem: Some(problem),
|
||||
used: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Closes the innermost open range for `rule`.
|
||||
fn take_open(
|
||||
open: &mut Vec<(String, bool, u32, TextRange)>,
|
||||
rule: &str,
|
||||
) -> Option<(bool, u32, TextRange)> {
|
||||
let index = open.iter().rposition(|(name, _, _, _)| name == rule)?;
|
||||
let (_, ours, line, span) = open.remove(index);
|
||||
Some((ours, line, span))
|
||||
}
|
||||
|
||||
/// True when nothing but whitespace precedes the comment on its line, which
|
||||
/// is what makes it a waiver for the *next* line rather than for its own.
|
||||
fn alone_on_its_line(ctx: &LintContext, span: TextRange) -> bool {
|
||||
let (line, _) = ctx.line_index().line_col(span.start);
|
||||
let Some(range) = ctx.line_index().line_range(line) else { return true };
|
||||
let before = span.start.saturating_sub(range.start) as usize;
|
||||
ctx.line_text(line).get(..before).is_none_or(|text| text.trim().is_empty())
|
||||
}
|
||||
|
||||
/// Reads one comment as a waiver directive plus whether it was written with
|
||||
/// vfmt's own prefix, or `None` if it is not a waiver at all.
|
||||
fn parse_directive(text: &str) -> Option<(Directive, bool)> {
|
||||
let body = strip_markers(text).trim();
|
||||
let (rest, ours) = match body.strip_prefix("vfmt:") {
|
||||
Some(rest) => (rest, true),
|
||||
None => (body.strip_prefix("verilog_lint:")?, false),
|
||||
};
|
||||
let mut words = rest.split_whitespace();
|
||||
let keyword = words.next()?;
|
||||
if !matches!(keyword, "waive" | "waive-start" | "waive-stop") {
|
||||
return None;
|
||||
}
|
||||
// Exactly one rule name, nothing after it: a waiver that does not say
|
||||
// precisely what it waives is a typo, and typos here are silent bugs.
|
||||
let (Some(rule), None) = (words.next(), words.next()) else {
|
||||
return Some((Directive::Malformed, ours));
|
||||
};
|
||||
let directive = match keyword {
|
||||
"waive-start" => Directive::Start(rule.to_string()),
|
||||
"waive-stop" => Directive::Stop(rule.to_string()),
|
||||
_ => Directive::Waive(rule.to_string()),
|
||||
};
|
||||
Some((directive, ours))
|
||||
}
|
||||
|
||||
/// Strips `//` or `/* */` from a comment's text.
|
||||
fn strip_markers(text: &str) -> &str {
|
||||
if let Some(rest) = text.strip_prefix("//") {
|
||||
return rest;
|
||||
}
|
||||
match text.strip_prefix("/*") {
|
||||
Some(rest) => rest.strip_suffix("*/").unwrap_or(rest),
|
||||
None => text,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn directive_of(text: &str) -> Option<&'static str> {
|
||||
parse_directive(text).map(|(d, _)| match d {
|
||||
Directive::Waive(_) => "waive",
|
||||
Directive::Start(_) => "start",
|
||||
Directive::Stop(_) => "stop",
|
||||
Directive::Malformed => "malformed",
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_spellings_are_accepted() {
|
||||
assert_eq!(directive_of("// vfmt: waive no-tabs"), Some("waive"));
|
||||
assert_eq!(directive_of("// verilog_lint: waive no-tabs"), Some("waive"));
|
||||
assert_eq!(directive_of("/* vfmt: waive-start no-tabs */"), Some("start"));
|
||||
assert_eq!(directive_of("//verilog_lint:waive-stop no-tabs"), Some("stop"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_comments_and_format_fences_are_not_waivers() {
|
||||
assert_eq!(directive_of("// a note"), None);
|
||||
assert_eq!(directive_of("// vfmt: off"), None);
|
||||
assert_eq!(directive_of("// verilog_format: off"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_waiver_without_exactly_one_rule_is_malformed() {
|
||||
assert_eq!(directive_of("// vfmt: waive"), Some("malformed"));
|
||||
assert_eq!(directive_of("// vfmt: waive no-tabs and more"), Some("malformed"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
//! Rule tests in Verible's `RunLintTestCases` style: the expected findings
|
||||
//! are written into the source itself, and the match is **exact** — an
|
||||
//! unexpected finding fails the test just as a missing one does.
|
||||
//!
|
||||
//! A line whose trimmed text is `//~ <rule-name>` asserts one finding of that
|
||||
//! rule on the nearest preceding non-marker line. Marker lines are ordinary
|
||||
//! comments to the linter, so the source stays valid Verilog.
|
||||
//!
|
||||
//! Every rule gets the same four cases: it fires, it stays quiet, a waiver
|
||||
//! silences it, and a waiver that silences nothing is itself reported.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use vlog_linter::{default_rules, run};
|
||||
|
||||
/// Asserts that linting `src` (as `path`) finds exactly what its markers say.
|
||||
#[track_caller]
|
||||
fn assert_lint(path: Option<&str>, src: &str) {
|
||||
let violations = run(src, path.map(PathBuf::from), &default_rules());
|
||||
let index = vlog_parser::LineIndex::new(src);
|
||||
|
||||
let mut actual: Vec<(u32, String)> =
|
||||
violations.iter().map(|v| (index.line_col(v.span.start).0, v.rule.to_string())).collect();
|
||||
let mut expected = expectations(src);
|
||||
actual.sort();
|
||||
expected.sort();
|
||||
|
||||
assert_eq!(
|
||||
expected, actual,
|
||||
"\nexpected (line, rule) findings on the left, got the right\nsource:\n{src}\nmessages: {:#?}",
|
||||
violations.iter().map(|v| format!("{}: {}", v.rule, v.message)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
/// The `(line, rule)` pairs the markers in `src` ask for.
|
||||
fn expectations(src: &str) -> Vec<(u32, String)> {
|
||||
let mut out = Vec::new();
|
||||
let mut code_line = 0u32;
|
||||
for (i, text) in src.lines().enumerate() {
|
||||
match text.trim().strip_prefix("//~") {
|
||||
Some(rule) => out.push((code_line, rule.trim().to_string())),
|
||||
None => code_line = i as u32 + 1,
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- harness
|
||||
|
||||
#[test]
|
||||
fn the_harness_notices_a_missing_marker() {
|
||||
let src = "module m;\n\twire a;\nendmodule\n";
|
||||
let violations = run(src, None, &default_rules());
|
||||
assert_eq!(violations.len(), 1, "fixture must violate exactly one rule");
|
||||
assert!(expectations(src).is_empty(), "and the unmarked source must expect none");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- no-tabs
|
||||
|
||||
#[test]
|
||||
fn no_tabs_fires() {
|
||||
assert_lint(None, "module m;\n\twire a;\n//~ no-tabs\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_tabs_is_quiet_on_spaces() {
|
||||
assert_lint(None, "module m;\n wire a;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_tabs_is_waived() {
|
||||
assert_lint(None, "module m;\n// vfmt: waive no-tabs\n\twire a;\nendmodule\n");
|
||||
assert_lint(None, "module m;\n\twire a; // vfmt: waive no-tabs\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_tabs_waiver_that_waives_nothing_is_reported() {
|
||||
assert_lint(
|
||||
None,
|
||||
"module m;\n wire a; // vfmt: waive no-tabs\n//~ unused-waiver\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------- no-trailing-whitespace
|
||||
|
||||
#[test]
|
||||
fn no_trailing_whitespace_fires() {
|
||||
assert_lint(None, "module m;\n wire a; \n//~ no-trailing-whitespace\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_trailing_whitespace_is_quiet_on_a_clean_line() {
|
||||
assert_lint(None, "module m;\n wire a;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_trailing_whitespace_is_waived() {
|
||||
assert_lint(None, "module m;\n// vfmt: waive no-trailing-whitespace\n wire a; \nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_trailing_whitespace_waiver_that_waives_nothing_is_reported() {
|
||||
assert_lint(
|
||||
None,
|
||||
"module m;\n wire a; // vfmt: waive no-trailing-whitespace\n//~ unused-waiver\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------- case-missing-default
|
||||
|
||||
#[test]
|
||||
fn case_missing_default_fires() {
|
||||
assert_lint(
|
||||
None,
|
||||
"module m;\n always_comb begin\n case (s)\n//~ case-missing-default\n 0: x = 1;\n endcase\n end\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn case_missing_default_is_quiet_with_a_default() {
|
||||
assert_lint(
|
||||
None,
|
||||
"module m;\n always_comb begin\n case (s)\n 0: x = 1;\n default: x = 0;\n endcase\n end\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn case_missing_default_is_waived() {
|
||||
assert_lint(
|
||||
None,
|
||||
"module m;\n always_comb begin\n // vfmt: waive case-missing-default\n case (s)\n 0: x = 1;\n endcase\n end\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn case_missing_default_waiver_that_waives_nothing_is_reported() {
|
||||
assert_lint(
|
||||
None,
|
||||
"module m;\n always_comb begin\n case (s)\n 0: x = 1;\n default: x = 0;\n endcase // vfmt: waive case-missing-default\n//~ unused-waiver\n end\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
// -------------------------------------------------- always-ff-non-blocking
|
||||
|
||||
#[test]
|
||||
fn always_ff_non_blocking_fires() {
|
||||
assert_lint(
|
||||
None,
|
||||
"module m;\n always_ff @(posedge clk) q = d;\n//~ always-ff-non-blocking\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn always_ff_non_blocking_is_quiet_on_nonblocking() {
|
||||
assert_lint(None, "module m;\n always_ff @(posedge clk) q <= d;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn always_ff_non_blocking_is_waived() {
|
||||
assert_lint(
|
||||
None,
|
||||
"module m;\n always_ff @(posedge clk) q = d; // vfmt: waive always-ff-non-blocking\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn always_ff_non_blocking_waiver_that_waives_nothing_is_reported() {
|
||||
assert_lint(
|
||||
None,
|
||||
"module m;\n always_ff @(posedge clk) q <= d; // vfmt: waive always-ff-non-blocking\n//~ unused-waiver\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------- always-comb-blocking
|
||||
|
||||
#[test]
|
||||
fn always_comb_blocking_fires() {
|
||||
assert_lint(None, "module m;\n always_comb x <= y;\n//~ always-comb-blocking\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn always_comb_blocking_is_quiet_on_blocking() {
|
||||
assert_lint(None, "module m;\n always_comb x = y;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn always_comb_blocking_is_waived() {
|
||||
assert_lint(
|
||||
None,
|
||||
"module m;\n// verilog_lint: waive always-comb-blocking\n always_comb x <= y;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn always_comb_blocking_waiver_that_waives_nothing_is_reported() {
|
||||
assert_lint(
|
||||
None,
|
||||
"module m;\n always_comb x = y; // vfmt: waive always-comb-blocking\n//~ unused-waiver\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
// -------------------------------------- explicit-parameter-storage-type
|
||||
|
||||
#[test]
|
||||
fn explicit_parameter_storage_type_fires() {
|
||||
assert_lint(
|
||||
None,
|
||||
"module m;\n parameter WIDTH = 8;\n//~ explicit-parameter-storage-type\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_parameter_storage_type_is_quiet_when_typed() {
|
||||
assert_lint(None, "module m;\n parameter int WIDTH = 8;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_parameter_storage_type_is_waived() {
|
||||
assert_lint(
|
||||
None,
|
||||
"module m;\n parameter WIDTH = 8; // vfmt: waive explicit-parameter-storage-type\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_parameter_storage_type_waiver_that_waives_nothing_is_reported() {
|
||||
assert_lint(
|
||||
None,
|
||||
"module m;\n parameter int WIDTH = 8; // vfmt: waive explicit-parameter-storage-type\n//~ unused-waiver\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------- module-filename
|
||||
|
||||
#[test]
|
||||
fn module_filename_fires() {
|
||||
assert_lint(Some("rtl/bar.sv"), "module foo;\n//~ module-filename\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_filename_is_quiet_when_it_matches_or_has_no_path() {
|
||||
assert_lint(Some("rtl/foo.sv"), "module foo;\nendmodule\n");
|
||||
assert_lint(None, "module foo;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_filename_is_waived() {
|
||||
assert_lint(Some("rtl/bar.sv"), "module foo; // vfmt: waive module-filename\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_filename_waiver_that_waives_nothing_is_reported() {
|
||||
assert_lint(
|
||||
Some("rtl/foo.sv"),
|
||||
"module foo; // vfmt: waive module-filename\n//~ unused-waiver\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- mixed file
|
||||
|
||||
#[test]
|
||||
fn several_rules_on_one_file_report_independently() {
|
||||
assert_lint(
|
||||
Some("rtl/top.sv"),
|
||||
"module foo #(parameter W = 1) ();\n\
|
||||
//~ module-filename\n\
|
||||
//~ explicit-parameter-storage-type\n\
|
||||
\talways_comb x <= 1;\n\
|
||||
//~ no-tabs\n\
|
||||
//~ always-comb-blocking\n\
|
||||
endmodule\n",
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,566 @@
|
||||
# linter-core
|
||||
|
||||
## Goal
|
||||
|
||||
Give vfmt a linter — the `vlog_linter` crate and the `vfmt check` subcommand —
|
||||
built ruff-style from day one (a rule registry over a shared parse, violations
|
||||
that may carry fixes classified *safe* or *unsafe*, `--select`/`--ignore`, JSON
|
||||
output) with Verible's rule ergonomics (stable kebab-case names, a style-guide
|
||||
rationale per rule, inline waivers). This round ships the engine, seven seed
|
||||
rules and the CLI wiring; the rules deliberately stay **syntactic**, per
|
||||
TODO.md §7, because semantic rules wait on `vlog_semantic`. The formatter is
|
||||
untouched: a bare `vfmt <paths>` behaves exactly as it did before subcommands
|
||||
existed.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Tolerant parse, partial results.** `LintContext` parses with
|
||||
`parse_source_tolerant`, so a file the formatter would refuse is still
|
||||
linted. Unparsable regions become `Error` leaves that no AST rule matches —
|
||||
findings from a broken file are a subset of what a fixed file would report,
|
||||
never a superset. Text/token rules are unaffected.
|
||||
- **A lex error leaves no tokens.** The lexer is all-or-nothing, so an
|
||||
unterminated block comment means no waivers are seen in that file (they live
|
||||
on tokens). Text rules still run. This is rare enough not to warrant a
|
||||
tolerant lexer.
|
||||
- **Waivers key on the line a diagnostic points at**, not on the whole extent
|
||||
of a multi-line construct. Waiving a `case-missing-default` therefore goes on
|
||||
the `case` line.
|
||||
- **`case-missing-default` flags `unique`/`priority` case statements too.** The
|
||||
qualifier is a promise to the tools, not a branch. Documented rather than
|
||||
configurable; a waiver is the escape hatch.
|
||||
- **`always-comb-blocking` only looks at `always_comb`**, not at `always @*`,
|
||||
and `always-ff-non-blocking` only at `always_ff`. The SystemVerilog keywords
|
||||
declare intent; `always @(posedge clk)` does not.
|
||||
- **Whitespace inside a string literal is data.** `no-tabs` and
|
||||
`no-trailing-whitespace` neither report nor rewrite a range that touches a
|
||||
`TokenKind::String` span.
|
||||
- **A tab expands to the run's indent width** (`--indent`, or the `indent` key
|
||||
of the governing `vfmt.toml`, default 2) — one tab, one indent level.
|
||||
- **`module-filename` speaks only for a file with exactly one top-level
|
||||
module**, and never without a file name (stdin without `--stdin-filename`).
|
||||
- **Verible waivers naming rules vfmt does not have are ignored, not
|
||||
reported.** See Work log 2026-08-19 — this came out of the corpus baseline.
|
||||
- **`// verilog_format: off` regions are reported but never auto-fixed.**
|
||||
See "Fences" below; the linter reads fenced ranges through
|
||||
`vlog_formatter::fence`, so what counts as fenced is the formatter's answer,
|
||||
widened by a conservative line scan for files that do not parse.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed**
|
||||
|
||||
- `vlog_parser`: `parse_source_tolerant`, `tokenize`, `LineIndex`, `TextRange`,
|
||||
`ast::*`, `token::{Token, Comment, TokenKind}`. The linter reads the AST and
|
||||
the token stream and mutates neither. It relies on: node/`Meta` spans being
|
||||
code extents (`docs/features/spans/README.md`), name spans matching the text
|
||||
(`name-spans`), comments being reachable from tokens as leading/trailing
|
||||
trivia, and `Error` leaves being opaque (`error-recovery`).
|
||||
- `vlog_formatter::Config`: only `indent_width`, and only as the tab-expansion
|
||||
width. The linter does not format.
|
||||
- `vlog_formatter::fence` (`collect`, `fence_of`, `Fence`, `Region` and its
|
||||
fields) — read by `crates/vfmt/src/lint.rs` to keep `--fix` out of fenced
|
||||
regions. All of it was **already `pub`**, so no visibility change was needed
|
||||
in `vlog_formatter`; nothing in that crate was modified. If `fence::collect`
|
||||
ever narrows its region for the formatter's own reasons, `--fix` narrows
|
||||
with it — that coupling is deliberate: one answer to "what is fenced", not
|
||||
two. Note the linter passes a **tolerant** tree to `collect`, which handles
|
||||
`Error` leaves without panicking (verified live, and by the fences QA round).
|
||||
- `crates/vfmt`: the walk, `--exclude`, `.gitignore` and config discovery are
|
||||
reused unchanged — `check` is handed the same `(path, Config)` job list
|
||||
`format` builds, and the same worker pool.
|
||||
|
||||
**Promised**
|
||||
|
||||
- `vlog_linter`'s public API is `Rule`, `LintContext`, `Violation`, `Fix`,
|
||||
`Applicability`, `Fixed`, `run`, `lint`, `apply_fixes`, `all_rules`,
|
||||
`default_rules`, `rule_by_name`, `select_rules`, `UNUSED_WAIVER`. Rule
|
||||
*names* are the stable part: they appear in waivers in user source, so a
|
||||
rename is a breaking change to other people's files.
|
||||
- `run(source, path, enabled)` never panics on any input and never writes
|
||||
anything; `LintContext::new` never fails.
|
||||
- Findings come back sorted by `(span.start, span.end, rule)`.
|
||||
- The exit-code contract of `vfmt check` mirrors the frozen formatter one:
|
||||
0 clean, 1 violations remain, 2 error.
|
||||
|
||||
**Requested of others (not done here)**
|
||||
|
||||
- *config-discovery's owner*: a `lint = [...]` / `[lint]` section in
|
||||
`vfmt.toml` (selected rules, per-rule settings) is out of scope this round —
|
||||
rule selection is CLI-only (`--select` / `--ignore`). When that key lands,
|
||||
`Options::select`/`ignore` should gain the same "CLI flag > config file"
|
||||
precedence the formatter settings have, and `select_rules` already takes the
|
||||
two lists it would feed.
|
||||
- *whoever unifies the pipelines*: `check` re-parses. TODO §4's "one parse, two
|
||||
tools" is **not** done; `check` and `format` each call the parser. Nothing in
|
||||
this crate's API prevents sharing a parse later — `LintContext` is the only
|
||||
thing that would need to accept a pre-built tree.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Crate `crates/vlog_linter` (deps: `vlog_parser` + std only).
|
||||
- [x] `Rule` trait: `name` / `summary` / `doc` / `check(&LintContext)`.
|
||||
- [x] `LintContext`: source, tokens, tolerant AST, `LineIndex`,
|
||||
`Option<PathBuf>`, tab width, string-literal spans.
|
||||
- [x] `Violation { rule, message, span, fix: Option<Fix> }`,
|
||||
`Fix { edits, applicability }`, `Applicability::{Safe, Unsafe}`.
|
||||
- [x] `apply_fixes` — left-to-right, overlapping fixes skipped, all-or-nothing
|
||||
per fix.
|
||||
- [x] Registry: `all_rules`, `default_rules`, `rule_by_name`, `select_rules`.
|
||||
- [x] Inline waivers: `waive`, `waive-start`/`waive-stop`, `vfmt:` and
|
||||
`verilog_lint:` spellings.
|
||||
- [x] `unused-waiver` pseudo-rule (unused, unknown-rule, malformed,
|
||||
unmatched `waive-stop`), itself waivable and ignorable.
|
||||
- [x] Seed rules: `no-tabs`, `no-trailing-whitespace`, `case-missing-default`,
|
||||
`always-ff-non-blocking`, `always-comb-blocking`,
|
||||
`explicit-parameter-storage-type`, `module-filename`.
|
||||
- [x] `vfmt check` wiring, `vfmt format` alias, backward-compatible bare
|
||||
invocation.
|
||||
- [x] `--output-format json`, `--select`, `--ignore`, `--fix`,
|
||||
`--unsafe-fixes` (plumbed; no unsafe fix exists yet).
|
||||
- [x] Inline-marker rule tests + CLI integration tests + corpus baseline.
|
||||
- [x] `--fix` never edits bytes inside a `// verilog_format: off` region
|
||||
(QA finding, 2026-08-19).
|
||||
- [ ] External waiver files (`waive --rule=X --line=N --location=glob`) — out
|
||||
of scope this round; needs a file format, a discovery rule and a
|
||||
precedence story against inline waivers.
|
||||
- [ ] `lint` config key in `vfmt.toml` — handshake above.
|
||||
- [ ] One parse shared by `check` and `format` — handshake above.
|
||||
- [ ] Naming rules by regex, `--generate_markdown` rule reference, `--explain`
|
||||
(`Rule::doc` exists so these can be generated, but nothing generates
|
||||
them yet).
|
||||
|
||||
## Rules and the corpus baseline
|
||||
|
||||
Run over the 860-file corpus (`corpus/`: ibex, opentitan, picorv32,
|
||||
common_cells), read-only, 0.09 s wall on 10 cores:
|
||||
|
||||
| Rule | Fix | Violations | Files |
|
||||
|---|---|---|---|
|
||||
| `no-tabs` | Safe | 7527 | 45 |
|
||||
| `explicit-parameter-storage-type` | — | 107 | 51 |
|
||||
| `no-trailing-whitespace` | Safe | 85 | 7 |
|
||||
| `case-missing-default` | — | 66 | 22 |
|
||||
| `module-filename` | — | 17 | 17 |
|
||||
| `always-ff-non-blocking` | — | 4 | 1 |
|
||||
| `always-comb-blocking` | — | 0 | 0 |
|
||||
| `unused-waiver` | — | 0 | 0 |
|
||||
| **total** | | **7806** | **93** |
|
||||
|
||||
Honest reading of that table:
|
||||
|
||||
- `no-tabs` dominates exactly as expected, and it is concentrated, not spread:
|
||||
2590 of the 7527 are one file (`picorv32/picorv32.v`), and 45 of 860 files
|
||||
account for all of them. `--fix` clears the whole category.
|
||||
- `always-comb-blocking` scoring zero is not suspicious — `<=` in an
|
||||
`always_comb` is a real bug, and this corpus is good code.
|
||||
- `unused-waiver` scored **14 before** the Verible-spelling decision below and
|
||||
0 after; every one was `// verilog_lint: waive macro-name-style` in ibex's
|
||||
vendored lowRISC code.
|
||||
- No file errored: the tolerant parse means even the 40 % of the corpus vfmt
|
||||
cannot fully parse still gets linted for what it can see. That is also the
|
||||
caveat — AST-rule counts above are a **lower bound**.
|
||||
|
||||
## Waiver semantics as implemented
|
||||
|
||||
```systemverilog
|
||||
wire a; // vfmt: waive no-tabs suppresses that rule on this line
|
||||
// vfmt: waive no-tabs alone on its line: suppresses the NEXT line
|
||||
// vfmt: waive-start no-tabs ... from this line
|
||||
// vfmt: waive-stop no-tabs ... through this one, both included
|
||||
```
|
||||
|
||||
- `verilog_lint:` is accepted everywhere `vfmt:` is.
|
||||
- Exactly one rule name per waiver; anything else is `unused-waiver:
|
||||
malformed`. A comment that does not start with one of the two prefixes plus
|
||||
a `waive*` keyword is an ordinary comment (`// vfmt: off` stays a format
|
||||
fence).
|
||||
- Ranges nest per rule; the innermost open `waive-start` for a rule is what a
|
||||
`waive-stop` closes. An unclosed `waive-start` runs to the end of the file
|
||||
(the format fences' rule). A `waive-stop` with nothing open is reported.
|
||||
- A waiver whose rule this run did not enable is silent — with `--select
|
||||
no-tabs`, waivers for other rules are not "unused", they simply had no
|
||||
chance to fire.
|
||||
- A `verilog_lint:` waiver naming a rule vfmt does not implement is ignored
|
||||
silently; the same waiver written `vfmt:` is reported as naming an unknown
|
||||
rule. A codebase annotated for Verible is lintable by vfmt without editing
|
||||
it first, while typos in vfmt's own waivers still surface.
|
||||
- `unused-waiver` findings can themselves be waived, and the derivation loops
|
||||
until the used-set stops growing so waiving one does not leave the waiver
|
||||
that did it reported as unused.
|
||||
- **External waiver files are not implemented.**
|
||||
|
||||
## Fences: reported, never auto-fixed
|
||||
|
||||
A `// verilog_format: off` / `// vfmt: off` region is emitted by the formatter
|
||||
as the exact source bytes it was written with — hand-aligned tables are the
|
||||
reason the fence exists. `vfmt check` therefore **reports** violations inside a
|
||||
fenced region (a finding is information, and `--select`/`--ignore`/waivers are
|
||||
the ways to silence one) but **never fixes** them: `--fix` drops any fix whose
|
||||
edits intersect a fenced range, leaving those violations reported and the exit
|
||||
code at 1. "Off" means hands-off for both tools, not just the formatter.
|
||||
|
||||
Fenced ranges come from two sources, unioned:
|
||||
|
||||
1. `vlog_formatter::fence::collect` — the formatter's own item-scoped answer,
|
||||
authoritative wherever the tree is good. The protected range is the whole
|
||||
`Region::start .. Region::end` the formatter would emit verbatim, the fence
|
||||
line's own indentation included.
|
||||
2. A line scan using `fence::fence_of` (the same grammar), pairing each `off`
|
||||
with the next `on` or the end of the file. This is the backstop for the
|
||||
files only the linter sees: error recovery can swallow the item structure a
|
||||
region hangs on, and `collect` then reports nothing at all — measured, not
|
||||
assumed. It can protect slightly more than the formatter emits verbatim,
|
||||
and would be fooled by a fence spelled inside a block comment; both err
|
||||
toward declining a fix, which is the harmless direction.
|
||||
|
||||
An insertion (an empty edit range) inside a region is blocked too, so nothing
|
||||
can be spliced in. A fix is all-or-nothing, so one edit landing inside a fence
|
||||
blocks that whole fix — never half of it.
|
||||
|
||||
## Fix model
|
||||
|
||||
ruff's, verbatim in spirit:
|
||||
|
||||
- `Fix { edits: Vec<(TextRange, String)>, applicability: Safe | Unsafe }`.
|
||||
Safe = cannot change what the code means (whitespace); Unsafe = may.
|
||||
- `--fix` applies Safe fixes; `--unsafe-fixes` (with `--fix`) widens to both.
|
||||
**No rule ships an Unsafe fix yet** — the flag is plumbed and tested so the
|
||||
first one does not have to touch the CLI. `always-*-blocking` are the
|
||||
obvious candidates and were deliberately left fixless: swapping `=` for `<=`
|
||||
changes the circuit.
|
||||
- A fix is all-or-nothing; its edits are applied together or not at all.
|
||||
- Within one pass, a fix overlapping one already applied is skipped rather
|
||||
than merged, so a pass can never garble text. `vfmt check --fix` therefore
|
||||
loops (fix → re-lint) until nothing changes, capped at 10 rounds. The
|
||||
everyday case needing two rounds is a line ending in a tab: `no-tabs` and
|
||||
`no-trailing-whitespace` both want those bytes.
|
||||
- A fix inside a `// verilog_format: off` region is never applied — see
|
||||
Fences above.
|
||||
- Fixed output re-lints clean for the fixed rules — asserted in
|
||||
`crates/vlog_linter/src/lib.rs` (`fixing_leaves_the_file_clean_for_the_fixed_rules`)
|
||||
and end to end in `crates/vfmt/tests/cli.rs`
|
||||
(`check_fix_rewrites_the_file_and_the_result_relints_clean`).
|
||||
|
||||
## CLI surface
|
||||
|
||||
```
|
||||
vfmt check [OPTIONS] <file|dir>... lint
|
||||
vfmt format [OPTIONS] <file|dir>... format (alias for the bare invocation)
|
||||
vfmt [OPTIONS] <file|dir>... format — unchanged
|
||||
```
|
||||
|
||||
The subcommand word is read **only as the first argument**. Everything else is
|
||||
inputs and flags exactly as before, so `vfmt --check rtl/` is still the
|
||||
formatter's check mode. A file named `check` can be formatted as
|
||||
`vfmt format check`.
|
||||
|
||||
`check`-only flags: `--select RULES`, `--ignore RULES` (comma-separated,
|
||||
repeatable), `--output-format text|json`, `--fix`, `--unsafe-fixes`. Using one
|
||||
of them without `check` is an error, as is `--check`/`--diff`/`--stdout` with
|
||||
it. `--indent`, `--exclude`, `--threads`, `--no-config`, `--no-gitignore`,
|
||||
`--stdin-filename` and `-` work for both.
|
||||
|
||||
Text output is Verible's line, sorted by file then position:
|
||||
|
||||
```
|
||||
rtl/bar.sv:2:1: tab character; indent with spaces [no-tabs]
|
||||
```
|
||||
|
||||
JSON is one array on stdout (errors stay on stderr, so the array is always
|
||||
parsable), each element:
|
||||
|
||||
```json
|
||||
{"filename":"rtl/bar.sv","rule":"no-tabs","message":"...",
|
||||
"location":{"line":2,"column":1},"end_location":{"line":2,"column":2},
|
||||
"range":{"start":11,"end":12},
|
||||
"fix":{"applicability":"safe","edits":[{"start":11,"end":12,"content":" "}]}}
|
||||
```
|
||||
|
||||
`fix` is `null` when the rule offers none. Serialization is hand-rolled (~30
|
||||
lines): the shape is three fields deep, and no serialization crate is a
|
||||
dependency of this crate or of `vfmt`.
|
||||
|
||||
Exit codes: **0** clean (or everything fixed), **1** violations remain, **2**
|
||||
error (bad arguments, unknown rule, unreadable file). An error outranks
|
||||
violations, as in the formatter.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-19 — dev
|
||||
|
||||
- Created `crates/vlog_linter` (files first, workspace member after — the
|
||||
ordering that bit a previous round) with `vlog_parser` + std only. Added
|
||||
`crates/vlog_linter` to the root `members` list additively, leaving the
|
||||
concurrent `vfmt_server` entries and workspace deps untouched.
|
||||
- Modules: `violation` (Violation/Fix/Applicability/apply_fixes), `context`
|
||||
(LintContext), `visit` (item/statement walks), `registry` (Rule trait +
|
||||
tables + selection), `waiver`, `rules/` (one file per rule).
|
||||
- **Design decisions**
|
||||
- `all_rules()` returns `Vec<&'static dyn Rule>` over unit structs. Boring,
|
||||
no macro, no inventory crate; the cost is one `Vec` allocation per call.
|
||||
- `unused-waiver` is a **registry entry with an empty `check`** rather than
|
||||
a special case outside the rule set. That way `--select`/`--ignore`,
|
||||
waivers and the rule reference all treat it like any other rule; the
|
||||
findings come from the waiver engine.
|
||||
- One `no-tabs` finding per *line*, not per tab, with the fix covering every
|
||||
tab on that line — otherwise a tab-indented file reports thousands of
|
||||
identical diagnostics (picorv32.v alone would have been far noisier).
|
||||
- The tab-expansion width is `Config::indent_width`, so `--indent 4` fixes
|
||||
tabs to four spaces. This is the only thing the linter takes from the
|
||||
formatter's config.
|
||||
- Rules skip ranges touching a string literal. Rewriting a tab inside
|
||||
`"a\tb"` would change data, which no "safe" fix may do.
|
||||
- `apply_fixes` skips overlapping fixes instead of trying to merge them, and
|
||||
the CLI loops. Simpler to reason about and provably non-garbling.
|
||||
- **Corpus finding that changed a decision.** The first baseline reported 14
|
||||
`unused-waiver` violations, all of them `// verilog_lint: waive
|
||||
macro-name-style` in vendored lowRISC code — i.e. correct Verible waivers
|
||||
for a rule vfmt has not implemented. Reporting those punishes exactly the
|
||||
codebases the `verilog_lint:` spelling exists to welcome. Changed so that an
|
||||
unknown rule name is reported only for the `vfmt:` spelling; a
|
||||
`verilog_lint:` waiver for a rule vfmt lacks is ignored. Corpus
|
||||
`unused-waiver` count went 14 → 0, and a typo'd `// vfmt: waive` is still
|
||||
caught. Tested by `a_verible_waiver_for_a_rule_vfmt_does_not_have_is_ignored`.
|
||||
- CLI: `args.rs` gained `Command`/`OutputFormat`, the five check-only flags and
|
||||
a scope check that rejects a flag used with the wrong tool; the subcommand is
|
||||
only read as the first argument, which is what keeps every old command line
|
||||
meaning what it did. New `crates/vfmt/src/lint.rs` holds the check driver
|
||||
and reuses `gather`, `build_pool` and `catch_panic` from `main.rs`.
|
||||
- Tests: 71 unit + 30 inline-marker integration tests in `vlog_linter`;
|
||||
16 new CLI tests in `crates/vfmt/tests/cli.rs` (exit codes, JSON shape,
|
||||
`--fix` round trip in a temp dir, waivers, stdin, walk reuse, and four
|
||||
backward-compatibility tests including a byte-for-byte comparison of
|
||||
`vfmt --check` against `vfmt format --check`).
|
||||
- Gates: `cargo test -p vlog_linter` 71+30+1 green, `cargo test -p vfmt` 46
|
||||
green, `cargo clippy -p vlog_linter -p vfmt --all-targets` silent,
|
||||
`cargo fmt --all --check` clean. The workspace has three failing tests and
|
||||
one clippy warning in `crates/vfmt_server`, which belongs to another agent's
|
||||
concurrent round and does not depend on this crate.
|
||||
- TODO.md §4: checked the rule trait/registry item, the diagnostic-format +
|
||||
JSON item, the fix-applicability item, the waiver item (with the external
|
||||
waiver files caveat spelled out) and the seed-rules item. Left "one parse,
|
||||
two tools", naming rules and `--generate_markdown` unchecked.
|
||||
|
||||
### 2026-08-19 — dev (QA follow-up)
|
||||
|
||||
- **QA should-fix: `--fix` rewrote bytes inside `// vfmt: off` fences.** Fixed
|
||||
per the lead's ruling: violations inside a fenced region are still reported,
|
||||
but no fix that touches those bytes is applied. Implemented in
|
||||
`crates/vfmt/src/lint.rs` (`fixable_outside_fences` / `touches_fence`), not
|
||||
in `vlog_linter` — `vfmt` already depends on `vlog_formatter`, and doing it
|
||||
here keeps the linter crate's dependency list at `vlog_parser` + std, which
|
||||
is the property QA verified with `cargo tree`.
|
||||
- **No visibility change was needed.** `fence::{collect, fence_of, Fence,
|
||||
Region}` and `Region`'s fields are already `pub`; `crates/vlog_formatter`
|
||||
was not modified at all. The lead's authorization went unused.
|
||||
- **Verified the tolerant-parse question rather than assuming it.**
|
||||
`fence::collect` takes the tolerant tree without panicking, as expected —
|
||||
but on a file with a parse error *before* the fence, error recovery swallows
|
||||
the item structure the region hangs on and `collect` returns **no region**,
|
||||
so the first implementation still rewrote fenced bytes in exactly the files
|
||||
only the linter sees. Added a second source: a line scan built on
|
||||
`fence::fence_of` (the formatter's own grammar, so the fence spelling is not
|
||||
duplicated), pairing `off` with the next `on` or EOF. The two are unioned;
|
||||
the scan can protect marginally more than the formatter emits verbatim,
|
||||
which only ever declines a fix.
|
||||
- The protected range is `Region::start..Region::end` — the whole byte range
|
||||
the formatter emits verbatim, not `region_at`'s `fence..end` — so the fence
|
||||
line's own indentation is protected too. Empty (insertion) edit ranges are
|
||||
treated as covering the byte they precede, so nothing can be spliced in.
|
||||
- Tests: the QA repro as a CLI test
|
||||
(`check_reports_inside_a_fence_but_never_fixes_there`: fenced line
|
||||
byte-identical including tab and trailing run, unfenced line still fixed,
|
||||
exit 1, and the two surviving findings both point into the fence),
|
||||
`a_fence_holds_even_in_a_file_that_does_not_parse` (which also re-asserts
|
||||
the formatter still exits 2 on it), plus six unit tests in `lint.rs`
|
||||
covering the boundary cases the lead asked for — first byte inside, last
|
||||
byte inside, adjacent-outside at both ends, straddling either edge,
|
||||
insertions, multi-edit fixes, unclosed fences and non-fence comments.
|
||||
- Corpus baseline re-run after the change: **7806 violations over 93 files**,
|
||||
per-rule counts byte-identical to the table above (the corpus contains no
|
||||
fences, so the filter is a no-op there — confirmed, not assumed).
|
||||
- Gates after the change: `cargo test -p vlog_linter` 71+30+1,
|
||||
`cargo test -p vfmt` 58 unit + 48 CLI, workspace green, clippy silent, fmt
|
||||
clean.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-19 — QA
|
||||
|
||||
Verified every claim in this README against the code, the gates, and a
|
||||
live corpus run. All PASS unless noted; one should-fix finding below.
|
||||
|
||||
**Gates.** `cargo tree -p vlog_linter`: only `vlog_parser` (+ std),
|
||||
matching the dependency claim. `cargo fmt --all --check` clean.
|
||||
`cargo clippy -p vlog_linter -p vfmt --all-targets` silent on a forced
|
||||
rebuild (touched `lib.rs` first to rule out a stale cache). No `unsafe`,
|
||||
no `#[allow]`, and every `.unwrap()`/`.expect()` in the crate is inside a
|
||||
`#[cfg(test)]` module (checked `crates/vlog_linter/src/**` and
|
||||
`crates/vfmt/src/lint.rs` by hand) — CLAUDE.md's Rust standards hold.
|
||||
`cargo test -p vlog_linter`: 71 unit + 30 integration + 1 doctest, green.
|
||||
`cargo test -p vfmt`: 46 green. Counts match the work log exactly.
|
||||
|
||||
**Corpus baseline.** Release build, `vfmt check corpus/ --output-format
|
||||
json`: **7806** violations over **93** files, byte-identical across
|
||||
repeated runs and across `--threads 1` vs the default pool (fully
|
||||
deterministic). Per-rule breakdown parsed from the JSON matches the
|
||||
table exactly: no-tabs 7527/45, explicit-parameter-storage-type 107/51,
|
||||
no-trailing-whitespace 85/7, case-missing-default 66/22,
|
||||
module-filename 17/17, always-ff-non-blocking 4/1,
|
||||
always-comb-blocking 0/0, unused-waiver 0/0. Wall time on this machine
|
||||
was ~0.26s (vs. the documented 0.09s/10-cores) — different hardware, not
|
||||
a discrepancy; determinism and counts are what matter and both check out.
|
||||
|
||||
**Rule attacks (crafted probes, not just the corpus).** All PASS:
|
||||
- `no-tabs`: a tab inside a string is neither reported nor fixed; a tab
|
||||
inside a *comment* is still reported (README only exempts string
|
||||
literals — code and doc agree).
|
||||
- `case-missing-default`: fires on plain `case`, `casez`, `priority
|
||||
case`; silent when a `default` exists (including `unique case`); fires
|
||||
on generate `case`; a `casez` nested inside an `always_comb` inside a
|
||||
generate `begin` block is reached and flagged correctly.
|
||||
- `always-ff-non-blocking` / `always-comb-blocking`: correctly flag a
|
||||
blocking/non-blocking assignment 3 `begin` levels deep; a `for`-loop
|
||||
header's `i++`/init is not mistaken for a flagged assignment, while a
|
||||
real assignment inside the loop body is still caught; reached through
|
||||
nested `generate if` blocks.
|
||||
- `explicit-parameter-storage-type`: `parameter type T = int` and a
|
||||
packed-dims-only `parameter [7:0] A` are both handled as documented
|
||||
(the former clean, the latter flagged).
|
||||
- `module-filename`: silent on a two-module file, silent on stdin with
|
||||
no `--stdin-filename`, and a case-mismatch (`Foo.sv` vs `module foo`)
|
||||
is flagged — reasonable default, not previously spelled out in the
|
||||
README but not a bug.
|
||||
- An all-garbage file (no valid tokens/syntax) and a file with an
|
||||
unterminated block comment (lex failure) both lint without panicking;
|
||||
the garbage file still catches a stray tab via the text rule.
|
||||
|
||||
**Waiver attacks.** All PASS, including the trickier ones:
|
||||
- Two nested `waive-start no-tabs` followed by two `waive-stop no-tabs`:
|
||||
the first stop closes the *inner* range, the second closes the outer
|
||||
one, and a line covered only by the outer range (between the two
|
||||
stops) stays suppressed — matches "innermost open start is what a
|
||||
stop closes."
|
||||
- `waive-stop` with no matching start → reported, message contains "no
|
||||
matching".
|
||||
- A waiver for a rule dropped by `--ignore` is silent (0 findings, exit
|
||||
0) — confirmed with `--ignore no-tabs --select no-tabs,unused-waiver`.
|
||||
- `verilog_lint: waive <rule vfmt lacks>` → silent; the same spelled
|
||||
`vfmt:` → reported unknown-rule. Both confirmed live via the CLI, not
|
||||
just the unit tests.
|
||||
- `unused-waiver` waiving itself → no findings at all (fixed-point
|
||||
derivation works). `--select unused-waiver` alone still catches an
|
||||
unknown-rule waiver with no other rules running.
|
||||
|
||||
**Fix engine.** All PASS:
|
||||
- A line with a tab that is also trailing whitespace (`\twire a;\t\n`)
|
||||
needs the documented two rounds; `--fix` converges and the result
|
||||
relints clean for `no-tabs`/`no-trailing-whitespace`.
|
||||
- `--fix` on a file that also has an unfixable violation
|
||||
(`module-filename`) fixes what it can, leaves the rest reported, exits
|
||||
1.
|
||||
- `check --fix --check` is rejected (`--check is not valid for
|
||||
\`vfmt check\``), confirming `--check` stays a formatter-only flag.
|
||||
- A second `--fix` run on an already-fixed-as-far-as-possible file is a
|
||||
no-op for fixing (0 additional applied) and exit code reflects only
|
||||
the remaining unfixable violation.
|
||||
- No rule in `crates/vlog_linter/src/rules/*.rs` calls
|
||||
`Fix::unsafe_fix`/uses `Applicability::Unsafe` — confirmed by grep —
|
||||
so `--unsafe-fixes` changing nothing today is accurate, not just
|
||||
claimed.
|
||||
|
||||
**Should-fix finding — `--fix` does not respect `// vfmt: off` fences.**
|
||||
`crates/vfmt/src/lint.rs` (`run_rules`/`fix_source`) builds a
|
||||
`LintContext` straight from the raw source and never consults
|
||||
`fence.rs`; `crate::vlog_linter` has no notion of fences at all (its
|
||||
`Cargo.toml` doesn't even depend on `vlog_formatter` beyond the
|
||||
`Config::indent_width` handshake noted in this README). Repro: a file
|
||||
with `// vfmt: off` around a tab-and-trailing-whitespace line — `vfmt
|
||||
check` reports `no-tabs` and `no-trailing-whitespace` *inside* the
|
||||
fenced region, and `vfmt check --fix` rewrites it, while `vfmt format`
|
||||
(the formatter) leaves the same region byte-for-byte untouched by
|
||||
design. This does not corrupt code (the rewrite is a Safe,
|
||||
meaning-preserving one) and does not break any hard invariant, but it
|
||||
violates the fence's whole premise — a user who wrote `// vfmt: off`
|
||||
expecting hands-off code gets it silently edited by `check --fix`. Not
|
||||
mentioned anywhere in this README (the one `// vfmt: off` reference,
|
||||
lines 162–163, only says the waiver *parser* treats it as an ordinary
|
||||
comment, which is correct and unrelated to this). Recommend either (a)
|
||||
`LintContext`/the fix/report path skip fenced ranges, matching the
|
||||
formatter's contract, or (b) if the fenceless behavior is intentional,
|
||||
document it explicitly in Assumptions and the CLI surface section so
|
||||
users aren't surprised. Left unfixed by me — this is a design decision,
|
||||
not a typo, and out of my QA-log-only write scope.
|
||||
|
||||
**JSON.** Valid per `python3 -c json.load` on every run above, including
|
||||
a path with non-ASCII characters, embedded double quotes, and a space
|
||||
in a directory name — round-tripped correctly. Empty-array case (`[]`)
|
||||
confirmed on a clean file, exit 0.
|
||||
|
||||
**Backward compatibility.** Built the pre-round binary from a `git
|
||||
worktree` at HEAD (`1ac9746`, before this round's uncommitted changes)
|
||||
and compared `vfmt --check` over the full corpus against the new
|
||||
binary: stdout byte-identical, stderr byte-identical (including the
|
||||
same 359 parse-error lines and the same "488 files would be
|
||||
reformatted, 13 files left unchanged, 359 files failed to format"
|
||||
summary), same exit code (2). Also reconfirmed live that `vfmt --check`
|
||||
and `vfmt format --check` are byte-identical on the new binary. The
|
||||
linter changes did not perturb the formatter at all, as the README
|
||||
promises.
|
||||
|
||||
**CLAUDE.md / TODO.md honesty.** `git diff HEAD -- TODO.md` shows §4's
|
||||
sub-items checked/unchecked exactly as the work log claims: rule
|
||||
trait/registry, diagnostic format, fix-applicability and the inline-
|
||||
waiver sub-item are checked; the external-waiver-files sub-item, the
|
||||
wire/reg-mixup sub-item, and "one parse, two tools" are left unchecked
|
||||
with explanatory `→` notes rather than silently marked done. Top-level
|
||||
`README.md`'s new Linting section matches this feature README's
|
||||
behavior exactly, including the `--unsafe-fixes` "changes nothing yet"
|
||||
caveat and the external-waiver-files gap. No files outside
|
||||
`crates/vlog_linter`, the CLI wiring named in the task, and this QA log
|
||||
were touched.
|
||||
|
||||
**Verdict.** No BLOCKING findings — no rule false-positive/negative on
|
||||
any of the attacked shapes, no `--fix` corruption, no backward-compat
|
||||
break. One should-fix finding (fences vs. `--fix`, above).
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-19 — lead. Verdict: accepted after one directed fix; commits
|
||||
jointly with vfmt-server (round 11). `vfmt check` completes the ruff
|
||||
analog.**
|
||||
|
||||
Points reviewed and accepted:
|
||||
|
||||
1. **The Verible-waiver asymmetry** is the round's best judgment call:
|
||||
`verilog_lint:` waivers naming rules vfmt lacks are ignored, not
|
||||
reported, because punishing them punishes exactly the vendored
|
||||
codebases the compatibility spelling exists to welcome — while
|
||||
typo'd `vfmt:` waivers still get caught. A design decision changed
|
||||
by corpus evidence, recorded with the evidence.
|
||||
2. **The fix engine's conservatism** (Safe/Unsafe from day one,
|
||||
overlaps skipped not merged, fix→re-lint loop with a cap,
|
||||
`always-*-blocking` deliberately fixless because swapping `=`/`<=`
|
||||
changes the circuit) is the right posture for a tool whose sibling
|
||||
formatter promises never to corrupt.
|
||||
3. **The fence ruling** (violations reported inside `// vfmt: off`,
|
||||
fixes never applied there) was implemented better than directed:
|
||||
the dev discovered that `fence::collect` yields no regions on files
|
||||
with a parse error before the fence — exactly the tolerant-parse
|
||||
population only the linter sees — and built a union of the
|
||||
authoritative tree regions and a scan backstop sharing the
|
||||
formatter's own `fence_of` grammar, so the spelling can't drift.
|
||||
Erring toward protecting more than the formatter emits verbatim
|
||||
only ever declines a fix. Verified by the boundary test matrix and
|
||||
a live lead probe (fenced bytes byte-identical, unfenced fix
|
||||
applied, exit 1).
|
||||
4. Backward compatibility proven at the byte level against a HEAD
|
||||
worktree binary, and the corpus baseline (7806/93) reproduced
|
||||
deterministically before and after the fence fix.
|
||||
|
||||
Honest remainders stay on TODO §4: external waiver files, naming
|
||||
rules, markdown rule docs, wire/reg mixup (needs a SystemVerilog-ness
|
||||
decision), and one-parse-two-tools (check re-parses today; only
|
||||
LintContext changes when unified). The LSP server should surface lint
|
||||
diagnostics in a future round — filed there as a natural follow-up.
|
||||
@@ -0,0 +1,652 @@
|
||||
# vfmt-server
|
||||
|
||||
## Goal
|
||||
|
||||
`crates/vfmt_server` is the analog of ruff's `ruff_server`: one binary,
|
||||
`vfmt-server`, that speaks LSP over stdio and serves both VS Code and
|
||||
Vim/Neovim with no editor-specific logic below the protocol layer (TODO.md
|
||||
§6). Every engine it needs already exists — the tolerant parser, the span and
|
||||
line-index utilities, the `` `define`` table, `vlog_semantic` and the
|
||||
workspace index — so this crate owns **only the protocol layer**: message
|
||||
loop, document state, position arithmetic, and one small handler per
|
||||
capability. It deliberately contains no analysis of its own; anything that
|
||||
looks like language knowledge in here is a bug or a `Handshake` request.
|
||||
|
||||
## Capabilities as shipped
|
||||
|
||||
| LSP request | Engine it consumes | Notes |
|
||||
|---|---|---|
|
||||
| `textDocument/formatting` | `vlog_formatter::format_source` | One whole-document `TextEdit`, and only when the text actually changed |
|
||||
| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, full-text sync |
|
||||
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries |
|
||||
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex` | Macro body, or declaration kind + snippet |
|
||||
| `textDocument/definition` | `Semantics` then `ExternalResolutions` | `Ambiguous` returns every location |
|
||||
| `textDocument/references` | `Semantics::references_of` | In-file only this round |
|
||||
| `textDocument/documentSymbol` | `Semantics::document_symbols` | Hierarchical |
|
||||
| `workspace/symbol` | `WorkspaceIndex::workspace_symbols` | Capped at 256 hits |
|
||||
|
||||
Deferred, deliberately, and named in Status/TODO below: range formatting
|
||||
(waits on TODO.md §2 `--lines`), lint diagnostics (waits on `vlog_linter`),
|
||||
completion / rename / signature help, cross-file references, and `vfmt.toml`
|
||||
discovery.
|
||||
|
||||
## Dependencies, and the justification CLAUDE.md asks for
|
||||
|
||||
Four direct dependencies, all exact-pinned in the root `[workspace.dependencies]`:
|
||||
|
||||
| crate | version | why it is not std, and not hand-rolled |
|
||||
|---|---|---|
|
||||
| `lsp-server` | `=0.10.0` | rust-analyzer's own transport: stdio framing, the `Content-Length` header dance, the initialize/shutdown/exit state machine. Synchronous — a `crossbeam-channel` pair and two I/O threads, **no `tokio`**. This is the whole reason it was picked over `tower-lsp`, which drags an async runtime into a program whose work is CPU-bound and single-file. |
|
||||
| `lsp-types` | `=0.97.0` | The protocol's data model — several hundred structs whose field names and `serde` attributes are the wire format. Hand-writing them is hand-rolling JSON by another name, which the brief forbids and which would rot at every spec revision. |
|
||||
| `serde` | `=1.0.229` | Only for the `DeserializeOwned` bound on the one generic request-decoding helper. Arrives transitively via `lsp-types` regardless. |
|
||||
| `serde_json` | `=1.0.140` | `Value` is `lsp-server`'s params/result type; `from_value`/`to_value` are the only JSON this crate touches. Arrives transitively regardless. |
|
||||
|
||||
**Transitive audit**, measured on this workspace's own lock file (diffing
|
||||
`Cargo.lock` against `HEAD`, so the number is what the repo actually gained,
|
||||
not what a standalone crate would):
|
||||
|
||||
**18 new packages.** `bitflags`, `crossbeam-channel`, `fluent-uri`, `itoa`,
|
||||
`log`, `lsp-server`, `lsp-types`, `memchr`, `proc-macro2`, `quote`, `ryu`,
|
||||
`serde`, `serde_core`, `serde_derive`, `serde_json`, `serde_repr`, `syn`,
|
||||
`unicode-ident`. **Twelve of the eighteen are the `serde`/JSON stack** and its
|
||||
proc-macro toolchain (`serde*`, `proc-macro2`, `quote`, `syn`,
|
||||
`unicode-ident`, `itoa`, `ryu`, `memchr`) — a cost any JSON handling at all
|
||||
would have paid. The other six are the protocol proper: `lsp-server`,
|
||||
`lsp-types`, `crossbeam-channel`, `fluent-uri`, `bitflags`, `log`.
|
||||
`crossbeam-utils` was already in the lock via
|
||||
`rayon` and is shared, not added. Exactly one `syn` is resolved (3.0.3) —
|
||||
worth checking, because `lsp-types`' `serde_repr` and `serde_derive` can
|
||||
easily land on different major versions and double the proc-macro build.
|
||||
|
||||
**Build scripts: five** — `proc-macro2`, `quote`, `serde`, `serde_core`,
|
||||
`serde_json`. All five were read. Every one is a toolchain probe: four shell
|
||||
out to `rustc --version` and all five emit only `cargo:rustc-cfg` /
|
||||
`cargo:rustc-check-cfg` lines. None compiles native code, links a system
|
||||
library, or touches the network. No `cc`, no `bindgen`, no vendored C.
|
||||
|
||||
**Versions considered and rejected.** `lsp-types` `0.94.x` models a URI as
|
||||
`url::Url`, which would give us `Url::from_file_path` for free but costs the
|
||||
`url` → `idna` → `unicode-bidi`/`unicode-normalization`/`tinyvec` subtree —
|
||||
five extra packages to avoid writing the ~40 lines in `src/uri.rs`. `0.97.0`
|
||||
uses `fluent-uri` (one package, one shared `bitflags`) and gives us a `Uri`
|
||||
with `FromStr` and `as_str()`, so path↔URI conversion is ours. That trade —
|
||||
five packages against forty tested lines — went the way CLAUDE.md's "standard
|
||||
library first" points. The cost is recorded honestly: `fluent-uri` 0.1.4 is a
|
||||
zero-copy parser with ~144 `unsafe` occurrences. CLAUDE.md's no-`unsafe` rule
|
||||
governs our code, and this crate has none.
|
||||
|
||||
## The byte ↔ UTF-16 conversion (`src/convert.rs`)
|
||||
|
||||
**This is the classic LSP bug, so it is the one piece of this crate with a
|
||||
design section.** Everything below the protocol speaks **UTF-8 byte offsets**
|
||||
(`TextRange`, `LineIndex`, every span the engines produce). LSP `Position`
|
||||
speaks **UTF-16 code units** within a line. The two agree only on ASCII, which
|
||||
is exactly why the bug survives to production: it is invisible until a comment
|
||||
contains `é` or an emoji.
|
||||
|
||||
`Positions<'a> { text: &'a str, index: &'a LineIndex }` is built per request
|
||||
from the document's own text and line table — it borrows, so there is no
|
||||
cached copy to invalidate.
|
||||
|
||||
**Byte offset → `Position`:**
|
||||
|
||||
1. `LineIndex::line_col(offset)` gives the 1-based line; LSP wants 0-based.
|
||||
2. The character is `text[line_start..offset]` measured in UTF-16 code units
|
||||
(`chars().map(char::len_utf16).sum()`), **not** in bytes and **not** in
|
||||
`char`s.
|
||||
3. `offset` is floored to a UTF-8 character boundary first. An offset landing
|
||||
inside a multi-byte character cannot slice; clamping down is the only
|
||||
answer that neither panics nor invents a position.
|
||||
4. A trailing `\r` in that slice is dropped. `LineIndex` deliberately treats
|
||||
`\r` as an ordinary byte of its line (`docs/features/spans/README.md`), but
|
||||
LSP line content excludes the whole `\r\n` terminator, so a span ending at
|
||||
the `\n` of a CRLF line would otherwise report one character too many.
|
||||
|
||||
**`Position` → byte offset:** walk the line's characters from its start,
|
||||
accumulating UTF-16 units, and stop when the accumulated count reaches the
|
||||
requested character. Consequences, both deliberate:
|
||||
|
||||
- A character that lands **inside a surrogate pair** (an astral character
|
||||
counts 2; the client asks for the midpoint) resolves to the offset *after*
|
||||
that character. There is no byte there to point at; rounding forward keeps
|
||||
the result a valid char boundary.
|
||||
- A character past the end of its line clamps to the line's end (`\r`
|
||||
excluded), never wrapping onto the next line — the same clamping rule
|
||||
`LineIndex::offset` already documents for byte columns.
|
||||
- A line past the end of the file clamps to the file's length.
|
||||
|
||||
**The one place the round-trip is not the identity, found by the test that
|
||||
tried to assert it was.** Both bytes of a `\r\n` are "the end of this line's
|
||||
content", and LSP has a single position for that, so `position(\r)` and
|
||||
`position(\n)` are equal and the `\n` cannot round-trip back to itself. The
|
||||
alternative — letting the `\r` count as a character — would report a position
|
||||
one past the line content the client believes it has, which every client then
|
||||
clamps anyway. The collapse is the correct behavior, so it is pinned by a test
|
||||
of its own (`a_crlf_terminator_is_the_one_place_the_round_trip_collapses`)
|
||||
rather than papered over, and the exhaustive round-trip test skips exactly
|
||||
that one byte class.
|
||||
|
||||
**An empty span is not a drawable range.** A diagnostic whose span is empty —
|
||||
which is every lex error, since the lexer reports the point it gave up —
|
||||
would underline nothing. `diagnostic_range` widens an empty span to the whole
|
||||
line it sits on, and, when *that* line is empty, to the line before it. The
|
||||
second rule is not hypothetical: an unterminated block comment is reported at
|
||||
end-of-file, and a file ending in a newline has an empty last line, so without
|
||||
the fallback the single most common lex error draws nothing at all. Found by
|
||||
the handler test, not predicted.
|
||||
|
||||
The server advertises `position_encoding: utf-16`, the protocol default, so
|
||||
the conversion is always on. Negotiating UTF-8 with capable clients would make
|
||||
this module a no-op for them; it is not worth a second code path until
|
||||
somebody measures the cost.
|
||||
|
||||
Tested in `convert.rs`'s own unit tests (14 of them): pure ASCII, 2-byte (`é`)
|
||||
and 3-byte (`✓`) characters, an astral emoji (`🎉`, one `char`, two UTF-16
|
||||
units, four UTF-8 bytes), a position landing *inside* a surrogate pair, an
|
||||
offset landing inside a multi-byte character, CRLF line ends, out-of-range
|
||||
positions in both directions, the empty document, and a full round-trip over
|
||||
every character boundary of a document mixing all of those.
|
||||
|
||||
## State and staleness
|
||||
|
||||
Single-threaded request loop — `lsp-server`'s model. Two I/O threads (its
|
||||
own) read and write stdio; this crate's loop receives one message, handles it
|
||||
to completion, and sends the response before looking at the next. No shared
|
||||
mutable state, no locks, no cancellation. Verilog files are small and every
|
||||
handler is milliseconds; the complexity of a worker pool buys nothing yet.
|
||||
|
||||
**Two layers, invalidated by different events** — exactly the split
|
||||
`docs/features/workspace-index/README.md` designed for:
|
||||
|
||||
| layer | rebuilt when | cost |
|
||||
|---|---|---|
|
||||
| a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` | one file, full recompute |
|
||||
| the `WorkspaceIndex` | `initialize`, and every `didSave` | full re-scan of the roots |
|
||||
|
||||
**Per-file recompute on every keystroke** is the strategy TODO.md §6 states
|
||||
("per-file recompute is fine at Verilog file sizes"); salsa is explicitly
|
||||
deferred there.
|
||||
|
||||
**Open buffers override disk** in every index rebuild: the roots are walked,
|
||||
each file read, and then every open document with a path replaces the disk
|
||||
copy (adding itself if it exists only in the editor). So the index never
|
||||
disagrees with a buffer the user is looking at.
|
||||
|
||||
**The staleness window, stated plainly.** The index is rebuilt on save, not on
|
||||
change. Between editing file A and saving it, file B's cross-file answers
|
||||
(`definition` into A, `workspace/symbol` hits in A, hover falling back to A's
|
||||
defines) reflect A **as it was at its last save** — except for A's own buffer,
|
||||
which the override above keeps current. Rebuilding on every keystroke would
|
||||
re-parse the whole workspace per character; rebuilding on save is the cheapest
|
||||
point where the answer is expected to change anyway. Measured cost of a
|
||||
rebuild: 0.68 s for the 860-file corpus (the workspace index's own baseline),
|
||||
plus the file reads.
|
||||
|
||||
**Definition targets in other files need that file's text** to turn a
|
||||
`TextRange` into a `Range`, and the index deliberately keeps no file contents.
|
||||
The server resolves a target by taking the **open buffer's text if that path
|
||||
is open, else reading the file from disk** — the same precedence the index
|
||||
rebuild uses, so a location can never be computed against text the index did
|
||||
not see.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Full-text document sync only.** The server advertises
|
||||
`TextDocumentSyncKind::FULL`, so a `didChange` carries the whole buffer and
|
||||
there is no incremental-edit application to get wrong. At Verilog file sizes
|
||||
the wire cost is irrelevant.
|
||||
- **Every document URI is a `file:` URI.** `untitled:` buffers are accepted
|
||||
and served for everything single-file (diagnostics, tokens, formatting,
|
||||
symbols), but they have no path, so they never enter the workspace index.
|
||||
- **Percent-encoding, not a URI library, converts paths.** `src/uri.rs`
|
||||
encodes everything outside the unreserved set plus `/`, and decodes `%XX`.
|
||||
Non-UTF-8 paths are rejected rather than guessed at. The Windows
|
||||
drive-letter rule (`file:///C:/x` → `C:\x`) is written and compiled but
|
||||
**untested on Windows** — it is behind `cfg!(windows)` so it cannot misfire
|
||||
on a POSIX path legitimately named `/C:`.
|
||||
- **The workspace walk is plain.** `initialize`'s `workspace_folders` (falling
|
||||
back to `root_uri`) are walked recursively for `*.v`/`*.sv`/`*.vh`/`*.svh`.
|
||||
`.gitignore` and `--exclude` are **not** honored — `crates/vfmt` owns that
|
||||
logic (`walk.rs`) and it is not public. Recorded as a Handshake below. A
|
||||
depth cap of 64 directories keeps a symlink cycle from spinning.
|
||||
- **A file that does not lex has no tokens.** The lexer is all-or-nothing
|
||||
(`docs/features/error-recovery/README.md`), so `semanticTokens` returns an
|
||||
empty set and hover's macro lookup finds nothing for such a buffer. The
|
||||
tolerant parser still yields one file-wide diagnostic, which is what the
|
||||
user needs to see anyway.
|
||||
- **A broken *header* distorts the tree**, as error-recovery's Assumptions
|
||||
warn: the module body re-parses at file scope and an orphaned `endmodule`
|
||||
becomes a second error item. Symbols and diagnostics in that state are
|
||||
oddly-placed but never wrong about their spans. This is the documented
|
||||
shape, not a bug in this crate.
|
||||
- **`vfmt.toml` is not discovered.** Config discovery lives in `crates/vfmt`
|
||||
(`config.rs`) and is not exposed as a library. The server uses
|
||||
`Config::default()` (100 columns, 2-space indent) with the client's tab
|
||||
size overriding the indent when it is sane. Handshake filed below.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `vlog_parser`:** `tokenize`, `parse_source_tolerant`,
|
||||
`ParseDiagnostic { message, line, col, span }`, `TextRange`, `LineIndex`
|
||||
(`line_col` / `offset` / `line_range` / `line_count`), `token::{Token,
|
||||
TokenKind, Comment}` including the `leading`/`trailing` trivia and their
|
||||
spans, and `defines::{collect_defines, Define, DefineTable}`.
|
||||
|
||||
**Consumed from `vlog_semantic`:** `analyze`, `Semantics::{symbol_at,
|
||||
reference_at, references_of, document_symbols, symbol, symbols, references,
|
||||
reference_id_at}`, `Symbol { name, kind, name_span, decl_span, child_scope }`,
|
||||
`SymbolKind`, `Resolution`, `DocumentSymbol`, and the workspace layer —
|
||||
`WorkspaceIndex::{build, path, find_define, workspace_symbols}`,
|
||||
`resolve_external`, `ExternalResolutions::definition_of`, `Definition`, `Def`.
|
||||
|
||||
**Consumed from `vlog_formatter`:** `format_source(&str, &Config) ->
|
||||
Result<String, FormatError>` and `Config { max_width, indent_width }`.
|
||||
|
||||
**Promised to nobody yet.** This crate is a leaf: it has no library target and
|
||||
nothing depends on it. The editor packaging round (TODO.md §6) will consume
|
||||
the binary's name and its stdio contract, nothing else.
|
||||
|
||||
**Requested of other modules** — none of these block this round, and none was
|
||||
done here:
|
||||
|
||||
1. **`crates/vfmt`: make config discovery reusable.** `vfmt.toml` search,
|
||||
parsing and precedence live in `crates/vfmt/src/config.rs`, inside a binary
|
||||
crate, so the server cannot call it. The LSP needs exactly the same
|
||||
answer the CLI gives for the same file, and duplicating the search rule is
|
||||
how the two silently diverge. The ask: lift `config.rs` into a small
|
||||
library (its own crate, or a `lib.rs` beside `main.rs`) with a
|
||||
`discover(path) -> Config`-shaped entry point. Until then the server
|
||||
formats with defaults, which is wrong for any project that sets
|
||||
`line-length`.
|
||||
2. **`crates/vfmt`: make the ignore-aware walk reusable.** Same shape of
|
||||
problem for `walk.rs` (`.gitignore` + `--exclude`). The server's plain walk
|
||||
will index generated netlists a `vfmt` run would skip.
|
||||
3. **`vlog_parser`: token-kind detail the lexer folds away.** Two spellings
|
||||
are indistinguishable in `TokenKind` today and are therefore classified
|
||||
coarsely by `semanticTokens` rather than reached for privately: an operator
|
||||
and a bracket are both `Symbol` (this crate emits neither, see the mapping
|
||||
table), and a macro *usage* is a `TokenKind::Ident` whose text starts with
|
||||
a backtick, distinguished by the existing public `Token::is_macro()` —
|
||||
which is enough, so this is a note, not a request.
|
||||
4. **`vlog_semantic`: nothing.** The queries needed for all six navigation
|
||||
capabilities existed exactly as documented.
|
||||
|
||||
## The `semanticTokens` mapping
|
||||
|
||||
Legend advertised, in index order:
|
||||
|
||||
`0 namespace`, `1 class`, `2 type`, `3 enumMember`, `4 parameter`,
|
||||
`5 variable`, `6 property`, `7 function`, `8 macro`, `9 keyword`,
|
||||
`10 comment`, `11 string`, `12 number`, `13 decorator`.
|
||||
Modifiers: `0 declaration`.
|
||||
|
||||
| source | token type |
|
||||
|---|---|
|
||||
| `TokenKind::Keyword` | `keyword` |
|
||||
| `TokenKind::Number` | `number` |
|
||||
| `TokenKind::String` | `string` |
|
||||
| `TokenKind::Directive` (`` `define``, `` `ifdef``, `` `include``) | `macro` |
|
||||
| `TokenKind::Ident` where `Token::is_macro()` (`` `NAME ``) | `macro` |
|
||||
| `TokenKind::SystemIdent` (`$display`) | `function` |
|
||||
| `TokenKind::Attribute` (`(* ... *)`) | `decorator` |
|
||||
| `Comment` trivia (leading and trailing, incl. on the EOF token) | `comment` |
|
||||
| `TokenKind::Symbol` | **not emitted** |
|
||||
| `TokenKind::Ident`, otherwise | from `Semantics`, below |
|
||||
|
||||
A plain identifier is looked up in the file's `Semantics` at its start offset:
|
||||
a declaration (`symbol_at`) gets its symbol's type **plus the `declaration`
|
||||
modifier**; a use (`reference_at`) that resolved in-file gets the resolved
|
||||
symbol's type; anything else — an external candidate, a not-found name, a name
|
||||
a macro would have produced — falls back to `variable`.
|
||||
|
||||
`SymbolKind` → type: `Module`→`class`, `Package`→`namespace`,
|
||||
`Typedef`→`type`, `EnumVariant`→`enumMember`, `Param`/`TfArg`→`parameter`,
|
||||
`Function`/`Task`→`function`, `StructMember`→`property`, and
|
||||
`Port`/`Net`/`Var`/`Genvar`/`Instance`/`Block`→`variable`.
|
||||
|
||||
Two rules that are easy to get wrong and are tested:
|
||||
|
||||
- **Punctuation is not emitted.** Every editor already colors brackets from
|
||||
its TextMate grammar, and emitting one token per `;` roughly triples the
|
||||
payload for no visible gain.
|
||||
- **No token ever spans a line break.** The spec requires it, and Verilog has
|
||||
three multi-line token shapes that would violate it — a block comment, a
|
||||
continued `` `define``, and a multi-line macro invocation. Every span is
|
||||
split at `\n` before encoding, and the pieces are sorted by (line, start)
|
||||
before the delta encoding runs.
|
||||
|
||||
## Hover, and the order it tries things
|
||||
|
||||
1. **A macro usage** (`` `NAME `` / `` `NAME(...) ``, and the name inside a
|
||||
`` `ifdef``-style directive is *not* included): the file's own
|
||||
`DefineTable::latest` wins, rendered as the joined body plus the
|
||||
definition's own source lines. If this file does not define it,
|
||||
`WorkspaceIndex::find_define` supplies every workspace definition — **all
|
||||
of them, each with its file and line**, because the index models no
|
||||
`` `include`` graph and picking one silently would be a guess
|
||||
(`docs/features/workspace-index/README.md` makes the same call).
|
||||
2. **A reference** resolved in-file: the symbol's kind, its name, and the
|
||||
source lines its `decl_span` covers.
|
||||
3. **A reference** answered only by the workspace overlay: the kind and name,
|
||||
plus each target's file and line.
|
||||
4. **A declaration** the cursor is sitting on: its own kind, name and
|
||||
snippet.
|
||||
|
||||
The snippet is `decl_span` widened to whole lines, so a declaration reads as
|
||||
it was written rather than starting mid-line.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Crate skeleton compiling **before** the root `members` entry (the
|
||||
ordering lesson from the previous round).
|
||||
- [x] `src/convert.rs`: byte ↔ UTF-16 `Position`, `TextRange` ↔ `Range`.
|
||||
- [x] `src/uri.rs`: `file:` URI ↔ path, percent-encoded.
|
||||
- [x] `src/state.rs`: `Document` (text, line index, tokens, diagnostics,
|
||||
`Semantics`, `DefineTable`, overlay), workspace walk, index rebuild.
|
||||
- [x] `textDocument/formatting`.
|
||||
- [x] Diagnostics on `didOpen`/`didChange`/`didSave`.
|
||||
- [x] `textDocument/semanticTokens/full`.
|
||||
- [x] `textDocument/hover`.
|
||||
- [x] `textDocument/definition`.
|
||||
- [x] `textDocument/references`.
|
||||
- [x] `textDocument/documentSymbol` + `workspace/symbol`.
|
||||
- [x] Unit tests for the position conversion, including surrogate pairs.
|
||||
- [x] Handler-level tests against constructed state, no process spawned.
|
||||
- [x] One end-to-end smoke test that spawns the built binary and speaks
|
||||
framed JSON-RPC.
|
||||
- [x] TODO.md §6 `vfmt_server` checkbox, annotated with what shipped.
|
||||
- [ ] **Not done, deliberately:** `rangeFormatting`. It reuses TODO.md §2's
|
||||
`--lines`, which does not exist yet; advertising the capability before
|
||||
the engine does is how an editor learns to distrust a server.
|
||||
- [ ] **Not done:** lint diagnostics. `vlog_linter` is a concurrent round;
|
||||
when it lands, the diagnostic publisher gains a second source and
|
||||
nothing else changes.
|
||||
- [ ] **Not done:** completion, rename, signature help (TODO.md §6's "then"
|
||||
list).
|
||||
- [ ] **Not done:** cross-file references. `references_of` is per-file, and
|
||||
answering across the workspace means resolving every other file's
|
||||
references *into* this one — an inverted index the workspace layer does
|
||||
not build. It is a real feature, not a small addition.
|
||||
- [ ] **Not done:** `vfmt.toml` discovery, `.gitignore`-aware indexing — both
|
||||
blocked on the two Handshake requests above.
|
||||
- [ ] **Not done:** editor packaging (the VS Code extension and the
|
||||
`lspconfig` snippet are their own TODO.md §6 item).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-19 — dev agent
|
||||
|
||||
- Read `CLAUDE.md`, `README.md`, TODO.md §6 in full, and the Handshakes/API
|
||||
sections of `spans`, `error-recovery`, `define-table`, `vlog-semantic` and
|
||||
`workspace-index` before writing anything. Every query this crate needed
|
||||
existed already; **no change was required in any engine crate**, which is
|
||||
the outcome the two-layer design in `workspace-index` was aiming for.
|
||||
- **Took the ordering lesson literally.** `crates/vfmt_server/` was created
|
||||
with a `Cargo.toml` and a `fn main() {}` and *built* before the root
|
||||
`members` entry was added, then the entry, then a build, then the
|
||||
dependencies, then a build. A members line pointing at nothing breaks the
|
||||
workspace for every other agent in the tree; this cost four extra builds and
|
||||
was worth it.
|
||||
- **Dependency choice measured, not assumed.** Resolved the tree in a scratch
|
||||
crate first: `lsp-types` 0.97 (`fluent-uri`) against 0.94 (`url`). 0.94
|
||||
would have handed us `Url::from_file_path`; it also costs `idna`,
|
||||
`unicode-bidi`, `unicode-normalization`, `tinyvec` and `percent-encoding`.
|
||||
Chose 0.97 and wrote `src/uri.rs` (~40 lines, 6 tests) instead. Also
|
||||
confirmed the workspace resolves exactly one `syn`, which the scratch crate
|
||||
had *not* — worth re-measuring in place rather than trusting the sandbox.
|
||||
- **`serde` is a direct dependency for exactly one reason** and it is stated
|
||||
at the manifest line: the `DeserializeOwned` bound on `decode`. Without it
|
||||
the request dispatcher becomes eight copies of the same four lines. It
|
||||
arrives transitively anyway, so this costs nothing but honesty.
|
||||
- **Wrote the UTF-16 conversion first, and its tests before the handlers.**
|
||||
This is the bug the brief called out, and two of its rules were established
|
||||
by failing tests rather than by design: the CRLF round-trip collapse and the
|
||||
empty-diagnostic-range fallback (both written up in the conversion section
|
||||
above). In both cases my first *test expectation* was wrong and the code was
|
||||
right, which is the good direction for that to happen — but it means the
|
||||
behavior is now pinned by a test that understands why, instead of by one
|
||||
that happened to pass.
|
||||
- **`semanticTokens` line-splitting was designed in, not discovered.** The
|
||||
spec forbids a token spanning a line break and Verilog has three shapes that
|
||||
would (block comment, continued `` `define``, multi-line macro call). All
|
||||
three have a test. Punctuation is deliberately not emitted — every editor
|
||||
colours brackets from its own grammar and emitting `;` roughly triples the
|
||||
payload.
|
||||
- **Formatting failures go to `showMessage`, not to diagnostics**, and the
|
||||
reason is in a comment at the call site: the diagnostic list belongs to the
|
||||
parse pass and is cleared on the next keystroke, which would silently erase
|
||||
the explanation for a format the user explicitly asked for. The handler
|
||||
returns an empty edit list in that case — never a partial edit, per CLAUDE.md
|
||||
invariant #1.
|
||||
- **Definition/hover into other files read that file's text on demand**, with
|
||||
open-buffer-beats-disk precedence, because the index deliberately keeps no
|
||||
file contents. Holding the whole workspace in memory to avoid a
|
||||
microsecond-scale file read would double what a server already spends on
|
||||
buffers.
|
||||
- **Three warnings were fixed by deleting code, not by allowing it**: an
|
||||
unused `Uri` import, a `text_range` helper with no consumer (it would be
|
||||
range formatting's, which is deferred), and a `tree` field on `Document`
|
||||
that nothing read once `Semantics` was built. The two `#[allow(deprecated)]`
|
||||
that remain are on `DocumentSymbol.deprecated` / `SymbolInformation.
|
||||
deprecated` / `InitializeParams.root_uri` — protocol fields deprecated by
|
||||
the spec that are still non-optional struct fields — and each carries the
|
||||
comment CLAUDE.md requires.
|
||||
- **The e2e test writes the whole session before reading a byte.** Interleaving
|
||||
writes and reads against a subprocess is how a smoke test turns into an
|
||||
intermittent hang; the session is under 4 KB, well inside a pipe buffer, and
|
||||
the server exits on `exit` so stdout closes and the read terminates on its
|
||||
own. No timeouts, no reader thread, and it cannot deadlock.
|
||||
- Did not touch `vlog_parser`, `vlog_formatter`, `vlog_semantic`,
|
||||
`vlog_linter` or `crates/vfmt`. Did not run `git commit`/`git push`.
|
||||
- **Concurrency note:** another agent's `vlog_linter` round is live in the same
|
||||
tree and added its own `members` line to the root `Cargo.toml` mid-round;
|
||||
left alone, as expected. Something in that round also ran `cargo fmt --all`
|
||||
across the tree, which reflowed a few of this crate's lines — harmless, and
|
||||
the final `cargo fmt --all --check` is clean.
|
||||
|
||||
**Results.** `cargo test -p vfmt_server`: **76 passed, 0 failed** (75 unit +
|
||||
1 e2e; counts trued up by the lead per the QA log — the workspace total
|
||||
below also moved as the concurrent linter round landed). `cargo test
|
||||
--workspace`: **494+ passed, 0 failed**. `cargo clippy
|
||||
--workspace --all-targets`: silent, 0 warnings. `cargo fmt --all --check`:
|
||||
clean. Files added: `crates/vfmt_server/{Cargo.toml,src/{main,server,state,
|
||||
convert,uri,locate,diagnostics,format,tokens,hover,nav,symbols}.rs,
|
||||
tests/e2e.rs}`, this README. Files edited: root `Cargo.toml` (one `members`
|
||||
entry, four `[workspace.dependencies]` lines — additive only), `TODO.md`
|
||||
(§6 checkbox).
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-19 — QA agent
|
||||
|
||||
Scope: `-p vfmt_server` only. Did not touch `vlog_linter`, `crates/vfmt`, or
|
||||
`docs/features/linter-core` (a concurrent QA round owns those). No source was
|
||||
edited; this entry is the only write.
|
||||
|
||||
**Gates.** `cargo fmt -p vfmt_server -- --check`: clean. `cargo clippy -p
|
||||
vfmt_server --all-targets`: 0 warnings. `cargo test -p vfmt_server`: **76
|
||||
passed, 0 failed (75 unit + 1 e2e)** — stable across two runs. `cargo test
|
||||
--workspace`: green (503 passed at the instant measured; the concurrent
|
||||
`vlog_linter` round is landing tests live in the same tree, so this number
|
||||
moves independently of anything here — `-p vfmt_server`'s own 76 is the
|
||||
number that matters for this feature and is not moving).
|
||||
|
||||
**Dependency audit, independently reproduced.** `git diff HEAD -- Cargo.lock`
|
||||
adds exactly the 18 named packages, plus two *local* workspace crates
|
||||
(`vfmt_server` itself and `vlog_linter`, the concurrent round — not part of
|
||||
the transitive count). Exactly one `syn` resolves, `3.0.3`. Exact-pin lines
|
||||
in root `Cargo.toml` confirmed: `lsp-server = "=0.10.0"`, `lsp-types =
|
||||
"=0.97.0"`, `serde = "=1.0.229"`, `serde_json = "=1.0.140"`. Read all five
|
||||
build scripts in full (not spot-read): `proc-macro2-1.0.107`,
|
||||
`quote-1.0.47`, `serde-1.0.229`, `serde_core-1.0.229`, `serde_json-1.0.140`
|
||||
(paths under `~/.cargo/registry/src/…`, resolved via `cargo metadata`).
|
||||
Every one only shells out to `rustc --version` and emits
|
||||
`cargo:rustc-cfg`/`cargo:rustc-check-cfg` lines (`proc-macro2`'s also
|
||||
compiles a tiny local probe file through `rustc` to detect a stable-API
|
||||
cutoff — still no network, no linking, no `cc`/`bindgen`). Confirms the
|
||||
README's claim exactly.
|
||||
|
||||
**No `unwrap`/`expect`/`panic!`/`unsafe` outside `#[cfg(test)]`.** Checked
|
||||
every line match against each file's `mod tests` boundary in all 12
|
||||
`src/*.rs` files — zero hits above the boundary. Three `#[allow(deprecated)]`
|
||||
found (`main.rs:98`, `symbols.rs:78`, `symbols.rs:103`), each with an
|
||||
explanatory comment.
|
||||
|
||||
**Real-binary end-to-end session, driven directly over stdio** (own
|
||||
hand-rolled Python framing client extending the `tests/e2e.rs` pattern, not
|
||||
reusing it — scripts left in the scratchpad, not the repo). Scratch project:
|
||||
`A.sv` (`` `include``s `defs.vh`, `import P::K`, instantiates `B`), `B.sv`,
|
||||
`pkg.sv` (`package P; localparam K = 4;`), `defs.vh` (`` `define WIDTH 8``).
|
||||
All PASS:
|
||||
|
||||
- Capabilities JSON on `initialize`: every shipped capability present
|
||||
(`documentFormattingProvider`, `definitionProvider`, `referencesProvider`,
|
||||
`hoverProvider`, `documentSymbolProvider`, `workspaceSymbolProvider`,
|
||||
`semanticTokensProvider` with the 14-type/1-modifier legend,
|
||||
`positionEncoding: "utf-16"`, `textDocumentSync: 1` i.e. Full). Deferred
|
||||
capabilities (`documentRangeFormattingProvider`, `completionProvider`,
|
||||
`renameProvider`, `signatureHelpProvider`) absent from the JSON, not just
|
||||
falsy.
|
||||
- `definition` on `B u_b` → `B.sv` at the correct declaration span.
|
||||
- `hover` on `` `WIDTH`` → macro body `` `define WIDTH 8``; `hover` on `K`
|
||||
(reached via `import P::K`) → `**parameter** — declared in pkg.sv:2`.
|
||||
- `didChange` introducing `localparam int ;` → two diagnostics, non-empty
|
||||
sane ranges (`severity: 1`, `source: "vfmt"`).
|
||||
- `didChange` reverting the fix → **diagnostics array published empty** —
|
||||
the classic forgotten-clear case, verified actually clearing.
|
||||
- `textDocument/formatting` on the unformatted file → one edit whose
|
||||
`newText` is **byte-for-byte identical** to `target/debug/vfmt --stdout`
|
||||
on the same source.
|
||||
- `textDocument/formatting` on the already-formatted output → `result: []`.
|
||||
- `semanticTokens/full` on `B.sv` → decoded the delta stream by hand (12
|
||||
tokens), spot-checked against the source; correct.
|
||||
- `documentSymbol` on `A.sv` → module `A` nests 5 children (`clk`, `out`,
|
||||
the `u_b` instance, `WIDTH2`, `K2`).
|
||||
- `workspace/symbol` substring `"WIDTH2"` → 1 correctly located hit.
|
||||
- Renamed `B`→`B2` in `B.sv`, `didChange` + `didSave` → `definition` from
|
||||
`A`'s still-open buffer (referencing the old name `B`) now resolves to
|
||||
`[]`. Staleness model confirmed: the index only rebuilds on save, and did.
|
||||
- `shutdown`/`exit` → clean ack, exit code 0.
|
||||
|
||||
**Position torture.** All PASS. `initialize` with **no** `workspaceFolders`
|
||||
and **no** `rootUri` → succeeds (single-file mode works). A file with an
|
||||
emoji (`🎉`) in a `//` comment on the line before a module declaration:
|
||||
`hover` and `documentSymbol.selectionRange` on the module name land at the
|
||||
correct UTF-16 column on the following (pure-ASCII) line. `hover` at the
|
||||
character offset landing *inside* the emoji's own surrogate pair (comment
|
||||
line itself) → graceful `null`, no crash. A CRLF file with a `wire ;` parse
|
||||
error → diagnostic range end character is `8`, matching the 8-char line
|
||||
content, not bleeding into the `\r`. `hover`/`definition` at
|
||||
character-past-end-of-line, line-past-end-of-file, and both-past-end → all
|
||||
six combinations return graceful `null`/`[]`, no protocol error, no crash;
|
||||
server process survived and later exited cleanly (code 0). `textDocumentSync`
|
||||
confirmed `1` (Full) in the capabilities JSON, so the "stale/overlapping
|
||||
`didChange`" scenario is moot as documented.
|
||||
|
||||
**Robustness.** All PASS. Malformed `Content-Length: notanumber` header, and
|
||||
a well-framed-but-garbage JSON body → in both cases the process does **not**
|
||||
panic (no `panicked at` in stderr); `lsp-server`'s own transport reports
|
||||
`ProtocolError("disconnected channel", true)` and the process exits (code
|
||||
1) — "exits cleanly" per the acceptance criterion. Every capability request
|
||||
(`hover`, `definition`, `references`, `documentSymbol`,
|
||||
`semanticTokens/full`, `formatting`) against a URI that was never opened →
|
||||
graceful `null`/`[]`, never a protocol error. A `file:` URI built from a
|
||||
path with spaces, `&`, `#`, and a non-ASCII directory component
|
||||
(`münchen`) → round-trips correctly through `didOpen`/`publishDiagnostics`
|
||||
and `documentSymbol` (probing `src/uri.rs` through the real binary, not just
|
||||
its own unit tests).
|
||||
|
||||
**Index scale.** PASS, and a QA-tooling note worth recording. Pointed
|
||||
`initialize` at `corpus/` (860 files, read-only, untouched). A full session
|
||||
— `initialize` + `workspace/symbol("")` + `workspace/symbol("clk")` +
|
||||
`workspace/symbol("uart_core")` + `shutdown`/`exit` — completes in **0.79 s**
|
||||
wall time (`/usr/bin/time -l`: 29.5 MB max RSS). The 256 cap is honored
|
||||
exactly: `""` (matches everything, per `vlog_semantic`'s own doc comment)
|
||||
and `"clk"` (a common substring almost certainly matching far more than 256
|
||||
declarations across a real 860-file corpus) both return exactly 256 hits;
|
||||
`"uart_core"` returns the correct single hit.
|
||||
|
||||
*Tooling note, not a vfmt_server defect:* an earlier attempt at this same
|
||||
check, using a persistent bidirectional-threaded Python client (a reader
|
||||
thread continuously draining stdout while the main thread issues requests —
|
||||
the natural way to extend the e2e pattern for an interactive multi-request
|
||||
session), appeared to hang indefinitely specifically on `workspace/symbol
|
||||
("clk")` against the real corpus — confirmed *not* CPU-bound via `sample`
|
||||
(macOS) on the server process: all four of its threads (main loop, reader,
|
||||
writer, message-dropper) sat blocked on `recv()`/`read()` the entire time,
|
||||
CPU time flat at 0.76 s across a 3-minute wait. Root-caused by replacing the
|
||||
persistent client with a write-the-whole-session-then-read-all-of-stdout
|
||||
script (`subprocess.run(..., input=session)`) — the exact pattern
|
||||
`tests/e2e.rs` itself uses, with the exact rationale given in its own
|
||||
top-of-file comment ("interleaving writes and reads against a subprocess is
|
||||
how a smoke test turns into an intermittent hang"). That version returned
|
||||
the correct, capped, sub-second result every time. I did not chase the
|
||||
harness bug further since the server's correctness is independently proven;
|
||||
flagging it so nobody mistakes the interactive-client hang for a server
|
||||
issue if they re-run a similar probe.
|
||||
|
||||
**CLAUDE.md / TODO.md compliance.** README has all seven required sections.
|
||||
TODO.md §6's `vfmt_server` checkbox (`TODO.md:330`) is checked and its
|
||||
shipped/not-shipped annotation matches the README's Capabilities table and
|
||||
Status/TODO checklist exactly — no over-claiming. Both filed Handshakes
|
||||
(`config.rs` and `walk.rs` lifting requests, README.md:370-371) are
|
||||
recorded; confirmed independently that `crates/vfmt` is `[[bin]]`-only (no
|
||||
`[lib]` target in its `Cargo.toml`), so the Handshake's premise — that
|
||||
`vfmt_server` genuinely cannot call into them today — holds.
|
||||
|
||||
**Minor, non-blocking:** the Work log's "Results" paragraph
|
||||
(README.md:447-448) says "75 passed, 0 failed (74 unit + 1 e2e)" and "493
|
||||
passed" workspace-wide. Current actual counts are 76 (75 unit + 1 e2e) and
|
||||
503 workspace-wide (the latter net of concurrent work). The `-p vfmt_server`
|
||||
count is off by exactly one unit test from what's written — likely a test
|
||||
added after that paragraph was written. Not fixed here since it's prose in
|
||||
another agent's Work log entry, not a code or test defect; flagging so the
|
||||
dev agent can true it up.
|
||||
|
||||
**Summary: no BLOCKING findings.** No panic, no dropped/never-cleared
|
||||
diagnostic, no position off-by-one, on ASCII or non-ASCII content, in any
|
||||
scenario tried. All five claims verified against the real binary, not just
|
||||
its own unit tests.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-19 — lead. Verdict: accepted; commits jointly with linter-core
|
||||
(round 11). The owner's LSP requirement is now a running binary.**
|
||||
|
||||
What earned it:
|
||||
|
||||
1. **Protocol layer only.** Not one engine crate was modified — the
|
||||
ten rounds of foundations were sufficient exactly as documented,
|
||||
which is the strongest validation the feature-README discipline has
|
||||
produced. Where the CLI's config/gitignore behavior couldn't be
|
||||
reached (they live in the vfmt binary), the dev filed Handshakes
|
||||
instead of duplicating logic — those two lifts are round-12 work.
|
||||
2. **Honest capability advertising**: deferred features are absent
|
||||
from the initialize result, so no editor is lied to. rangeFormatting
|
||||
waits on §2 `--lines`; lint diagnostics wait on wiring vlog_linter
|
||||
in — both natural follow-ups.
|
||||
3. **The two test-produced findings** (CRLF's one-position collapse
|
||||
pinned rather than papered over; empty EOF diagnostic spans widened
|
||||
to drawable lines) are the UTF-16/position class of bug that ruins
|
||||
language servers, caught before any editor saw them. QA's
|
||||
position-torture (emoji, surrogates, six past-end combinations) and
|
||||
robustness runs (malformed frames, unopened URIs, percent-encoded
|
||||
paths) all came back clean, and the diagnostics-actually-clear case
|
||||
was verified through a real stdio session.
|
||||
4. **Dependency discipline held under the biggest temptation**: 4
|
||||
exact-pinned direct deps, 18 packages, all 5 build scripts read.
|
||||
The lsp-types 0.97-over-0.94 choice traded ~40 tested URI lines for
|
||||
5 fewer packages — the right direction.
|
||||
5. Index scale: 860 files in 0.79s / 29.5MB through a real session.
|
||||
Per-file recompute with didSave index rebuild is the documented,
|
||||
deliberately boring staleness model; salsa stays deferred until it
|
||||
hurts.
|
||||
|
||||
Lead fix on acceptance: the stale test counts in the work log trued up
|
||||
per QA. QA's harness-hang investigation (profiled the server before
|
||||
blaming it; found its own threading at fault; matched the e2e test's
|
||||
own documented write-then-read pattern) is preserved in the QA log as
|
||||
the reference for anyone scripting against the server.
|
||||
|
||||
Round 12: editor packaging (VS Code extension + Neovim lspconfig) and
|
||||
the config/walk library lifts, closing TODO §6.
|
||||
Reference in new issue
Block a user