Compare commits
No files matched your search
@@ -14,6 +14,12 @@
|
||||
# The release fails, deliberately, when the tag does not match the
|
||||
# workspace version or CHANGELOG.md has no section for it: every release
|
||||
# ships with real, written notes (see tools/RELEASING.md).
|
||||
#
|
||||
# It is gated: tools/gates.sh (fmt, clippy, every crate's suites, the doc
|
||||
# tests, the corpus gate, the extension's node tests) runs first, and a red
|
||||
# gate means nothing is built or published. The ci workflow runs on the
|
||||
# branch push, not the tag, so without this step a tag published whatever
|
||||
# it pointed at (0.65.0 went out while its ci run was still stuck).
|
||||
name: release
|
||||
on:
|
||||
push:
|
||||
@@ -25,6 +31,15 @@ jobs:
|
||||
runs-on: macos-arm64
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
# The corpus is pinned-rev clones cached on the runner host, as in
|
||||
# ci.yml; gates.sh skips its corpus step when the cache is absent, so
|
||||
# fetch it here rather than release without that gate.
|
||||
- name: Ensure the cached corpus
|
||||
run: |
|
||||
corpus="$HOME/.cache/lucisv-corpus"
|
||||
[ -d "$corpus" ] || tools/corpus_fetch.sh "$corpus"
|
||||
- name: Gate the release
|
||||
run: tools/gates.sh
|
||||
- name: Build release artifacts for every target
|
||||
run: tools/release.sh --cross
|
||||
- name: Audit the cross-built artifacts
|
||||
|
||||
+310
@@ -4,6 +4,316 @@ All notable changes to lucisv are recorded here. Versions follow
|
||||
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
|
||||
(see `README.md`) are the only frozen contract.
|
||||
|
||||
## 0.65.5 — 2026-11-19
|
||||
|
||||
### Named formatting styles
|
||||
|
||||
(`docs/features/format-styles`; TODO §71.5.)
|
||||
|
||||
- **One setting picks a house layout.** `[format] style = "<name>"` in
|
||||
`lucisv.toml`, `--style <name>` on the command line, or the new
|
||||
`lucisv.format.style` drop-down in VS Code. Seven layout rules, one row per
|
||||
style, in one table in `crates/vlog_formatter/src/style.rs`:
|
||||
|
||||
| style | indent / width | `begin` | `else` | lists | list indent | alignment |
|
||||
|---|---|---|---|---|---|---|
|
||||
| `lucisv` (default) | 2 / 100 | same line | same line | fit | 1 level | keep |
|
||||
| `google` | 2 / 100 | same line | same line | one per line | 2 levels | keep |
|
||||
| `lowrisc` | 2 / 100 | same line | same line | one per line | 1 level | always |
|
||||
| `ansi` | 4 / 80 | own line | own line | fit | 1 level | keep |
|
||||
| `microsoft` | 4 / 120 | own line | own line | one per line | 1 level | keep |
|
||||
| `nxp` | 2 / 80 | same line | own line | one per line | 1 level | always |
|
||||
|
||||
- **Where the styles come from.** `google` follows the Google Verilog Style
|
||||
Guide and `lowrisc` the lowRISC (OpenTitan) guide, both read for this
|
||||
release, including `else` on its own line after a labelled `end`. **`ansi`,
|
||||
`microsoft` and `nxp` are lucisv's educated guesses** — Allman-style
|
||||
`begin`/`else` after iStyle's and clang-format's styles of those names, and
|
||||
a conservative aligned RTL style — not rules those organisations publish
|
||||
for Verilog.
|
||||
- **The default does not move a byte.** `lucisv` output is identical to
|
||||
0.65.4 on all 4 921 files of the corpus and OpenTitan's `hw` tree, checked
|
||||
against an independently rebuilt 0.65.4. An explicit `indent` or
|
||||
`line-length` still wins over a style's.
|
||||
- **Every style goes through the same safety net.** Each was formatted three
|
||||
times over those 4 921 files: no verification error, no crash, no token or
|
||||
comment difference (checked with a lexer that is not the formatter's), and
|
||||
no change on a second or third run. `verify.rs` is untouched.
|
||||
- **`style = "auto"` keeps a file in the layout it is already closest to.**
|
||||
It formats with each preset and keeps the result that changes the fewest
|
||||
lines, so a file written the Google way stays that way. It picks a layout
|
||||
for the configured indent and width and **never infers them** — set
|
||||
`indent` to match the file first, or a 4-space file formatted at the
|
||||
default 2 comes out in the default layout. Small edits do not flip a file:
|
||||
over 500 files and ten kinds of edit, none rewrote more than 12 lines
|
||||
outside the edit. `auto` costs a search — 2.4 s against 0.4 s on a
|
||||
42 000-line file for a whole-document format — so the language server
|
||||
remembers each document's layout, and selection and on-type formatting stay
|
||||
at 0.1 s after the first request.
|
||||
- **Known limits.** A declaration with several instances in one statement
|
||||
gets the older hanging layout under the one-per-line styles. The language
|
||||
server's `line-length` lint still assumes 100 columns under `ansi`,
|
||||
`microsoft` and `nxp` (the CLI's `check` follows the style). Switching from
|
||||
one keep-alignment style to another and back is not always a round trip:
|
||||
alignment a style added stays.
|
||||
|
||||
## 0.65.4 — 2026-11-19
|
||||
|
||||
### `` `ifdef `` blocks fold, and pin in sticky scroll
|
||||
|
||||
(`docs/features/ifdef-folding`; TODO §71.4.)
|
||||
|
||||
- **Every conditional-compilation branch folds on its own.** `` `ifdef ``,
|
||||
`` `ifndef ``, `` `elsif `` and `` `else `` each fold from their own line to
|
||||
the line before the next branch (or before `` `endif ``). Collapse the
|
||||
`` `ifdef `` branch and the `` `else `` line stays visible and separately
|
||||
collapsible; `` `endif `` stays visible too, the way `end` does for a
|
||||
`begin` fold. Nesting works to any depth.
|
||||
- **They pin in sticky scroll.** The floating header lines already follow the
|
||||
server's folds, so while you scroll inside a long branch its `` `ifdef `` or
|
||||
`` `else `` line stays at the top with the module and blocks around it.
|
||||
- **Only real directives count.** The folds are built from the lexer's own
|
||||
directive tokens, so a directive-looking line inside a comment, a string or
|
||||
a `` `define `` body is not folded (35 such lines in OpenTitan). An
|
||||
unterminated `` `ifdef `` folds the branches it finished and never runs to
|
||||
the end of the file; a stray `` `else `` or `` `endif `` is ignored.
|
||||
- **No existing fold is lost or changed.** On OpenTitan's `hw` tree (4 061
|
||||
files) and the 860-file corpus every fold the previous release returned is
|
||||
still returned, byte for byte, with the 1 061 and 511 branch folds added.
|
||||
Where a branch would share its start line with an existing fold — a
|
||||
directive written after code on the same line — the existing fold is sent
|
||||
first and keeps its place; that never occurs in either tree.
|
||||
- **Cost:** one extra pass over the tokens: folding all of OpenTitan goes from
|
||||
29.9 ms to about 34 ms, and a 50 000-branch file answers in 0.2 s.
|
||||
- **Limits.** Files over the large-file threshold (4 MiB) return no folds, as
|
||||
before. Not yet seen in a running editor by a human.
|
||||
|
||||
## 0.65.3 — 2026-11-19
|
||||
|
||||
### Comment keywords, and the brackets in comments explained
|
||||
|
||||
(`docs/features/comment-highlighting`; TODO §71.8.)
|
||||
|
||||
- **`TODO`, `FIXME`, `FIX_ME` and `TBD` stand out inside comments.** In `//`
|
||||
and `/* */` comments they are drawn bold in a new theme colour,
|
||||
`lucisv.commentKeyword` — as whole words only (`TODO_reg` and `$TODO` are
|
||||
left alone), and never in strings or code.
|
||||
- **Your own words too.** `lucisv.commentKeywords.custom` adds words that are
|
||||
highlighted the same way and only in comments (matched literally, up to 50
|
||||
words of 1–40 characters); `lucisv.commentKeywords.builtIn: false` turns the
|
||||
four built-ins off, and `lucisv.commentKeywords.caseSensitive: false`
|
||||
ignores case. Every change applies at once, with no reload.
|
||||
- **It follows what the editor draws as a comment.** The extension finds
|
||||
comments with the grammar's own comment and string rules; against VS Code's
|
||||
real tokenizer that agreed on every one of the 1 185 823 lines of
|
||||
OpenTitan's `hw` tree. It is client-side, so it paints while the language
|
||||
server is still starting.
|
||||
- **Cheap on big files.** Only the lines on screen (and 50 either side) are
|
||||
searched for words; an edit above the screen re-reads the lines from the
|
||||
edit down to it (7.9 ms at worst on a 100 000-line file). A file VS Code
|
||||
itself does not tokenize (over 20 MiB or 300 000 lines) is not painted.
|
||||
- **Brackets coloured inside comments: explained, not changed.** The `[]` of
|
||||
a `signal[]` that sometimes lights up in a comment is VS Code's bracket-pair
|
||||
colourisation, which ignores comments until it has finished tokenizing a
|
||||
newly opened file in the background and then removes the colour itself.
|
||||
lucisv's grammar and semantic tokens were measured to colour nothing inside
|
||||
a comment (309 OpenTitan files, and the large-file path). An extension
|
||||
cannot change that behaviour short of switching bracket colours off for the
|
||||
whole language, code included — which stays your choice
|
||||
(`editor.bracketPairColorization.enabled`, or `colorizedBracketPairs`
|
||||
under `[systemverilog]`).
|
||||
- **Not yet seen in a running editor by a human**: the tests are headless.
|
||||
|
||||
## 0.65.2 — 2026-11-19
|
||||
|
||||
### The Hierarchy pane shows where you are
|
||||
|
||||
(`docs/features/hierarchy-current-path`; TODO §71.6.)
|
||||
|
||||
- **The rows leading to the file you are editing are lit.** Every instance of
|
||||
the module the open file declares gets a light, bright orange tint with a
|
||||
solid bar at its left edge and a bold label; each row above it is one shade
|
||||
dimmer with a narrower bar, down to a faint floor for distant ancestors. A
|
||||
module instantiated in several places lights every copy, and where two
|
||||
chains meet the nearer one wins. It works on a closed tree and on DUT
|
||||
sections: a section header is tinted when the section holds the file or its
|
||||
parents.
|
||||
- **Switching files repaints, it does not reload.** There is no request to the
|
||||
language server and no rebuild of the tree; only the rows whose shade
|
||||
changed are touched, so nothing collapses (about 5 ms on a 6 000-module
|
||||
design).
|
||||
- **Readable in every built-in theme.** The default tints keep label text at
|
||||
4.5:1 or better on every lit level in the dark, light and high-contrast
|
||||
themes, hovered rows included — a test computes that from the shipped
|
||||
defaults — and the bar's width and style change with the level, so the
|
||||
grading does not rest on colour alone.
|
||||
- **Yours to restyle or switch off.** The shades and the bar are theme colours
|
||||
(`lucisv.hierarchyCurrent`, `lucisv.hierarchyParent1`–`3`,
|
||||
`lucisv.hierarchyAncestor`, `lucisv.hierarchyCurrentBar`) for
|
||||
`workbench.colorCustomizations`; `lucisv.hierarchy.highlightCurrent: false`
|
||||
turns the highlighting off.
|
||||
- **Known limits.** Nothing lights when a folder name's letter case differs
|
||||
between the filelist and the editor, or on Windows network-share paths; in a
|
||||
recursive design a row can be lit with nothing lit beneath it. Not yet seen
|
||||
in a running editor by a human: the tests are headless.
|
||||
|
||||
## 0.65.1 — 2026-11-19
|
||||
|
||||
### Releases are gated
|
||||
|
||||
No change to the formatter, the linter, the language server or the editor
|
||||
extension: the packages are 0.65.0 rebuilt. What changed is how a release is
|
||||
made (`tools/RELEASING.md`).
|
||||
|
||||
- **A tag no longer publishes unless every gate is green.** The release
|
||||
workflow now runs `tools/gates.sh` — `cargo fmt`, `cargo clippy`, each
|
||||
crate's test suites, the doc tests, the corpus gate and the extension's node
|
||||
tests — before it builds anything, and a failing gate stops the release.
|
||||
Until now only the branch push was checked, by a separate workflow the
|
||||
release did not wait for, so 0.65.0 was published while its checks had not
|
||||
finished.
|
||||
- **The build is clean on Rust 1.100.** An unused import in the language
|
||||
server's test module, which that toolchain's clippy rejects under
|
||||
`-D warnings`, is gone. It is what turned 0.65.0's checks red after the
|
||||
fact; the released binaries were never affected.
|
||||
|
||||
## 0.65.0 — 2026-11-19
|
||||
|
||||
### Module instantiation syntax highlighting
|
||||
|
||||
(`docs/features/instantiation-highlighting`; TODO §69.)
|
||||
|
||||
- **Every part of a module instantiation gets its own colour.** Module names,
|
||||
instance names, `.PARAM` overrides, `.port` names and connected signals used
|
||||
to collapse to the same default foreground colour whenever the instantiated
|
||||
module lived in another file or a theme left bare semantic tokens unstyled.
|
||||
The language server now layers AST-guided semantic token overrides (and
|
||||
cross-file `ExternalResolutions` lookups) over the existing 14-type legend:
|
||||
- **Module / interface names** (`uart_core`, `pkg::uart_core` with `pkg` as
|
||||
`namespace`, and lone `bind` targets) highlight as `class`.
|
||||
- **`#` and parameters share one colour** (`parameter`), distinct from `()`:
|
||||
the `#` introducing a module, class, `extends`, instantiation or
|
||||
parameterized-type parameter list, every `.PARAM` override (`.` and name),
|
||||
and parameter values inside `#(...)` all carry `parameter`. Delay `#`
|
||||
tokens (`#5`, `#(1:2:3)`) are left unemitted.
|
||||
- **Instance names** (`u_uart`, gate instances, `bind` instance lists, and
|
||||
hierarchical uses like `u_uart.sig`) highlight as `function`.
|
||||
- **Port names** (`.clk_i` dot and name, implicit `.rst_ni`, and wildcard
|
||||
`.*`), including unfinished entries being typed, highlight as `property`.
|
||||
- **Port connections** (`clk`, `data_q`) stay `variable` so signals keep one
|
||||
consistent colour across the file.
|
||||
- **VS Code: semantic highlighting on by default with theme-safe scope maps.**
|
||||
`configurationDefaults` enables `editor.semanticHighlighting.enabled` for
|
||||
`[verilog]` and `[systemverilog]` (user settings still win), and
|
||||
`contributes.semanticTokenScopes` maps the language's semantic token types to
|
||||
distinct TextMate scopes so every role renders in colour across Dark+, Dark
|
||||
Modern, Light+, GitHub Dark, One Dark Pro and Visual Studio Dark.
|
||||
|
||||
## 0.64.0 — 2026-11-17
|
||||
|
||||
### Completion that keeps up with typing
|
||||
|
||||
(`docs/features/completion-ux`, `docs/features/port-entry-grace`; TODO §68.)
|
||||
|
||||
- **`begin` + Enter writes the `end`.** The newline on-type answer, when
|
||||
the line above ends in `begin` (or `begin : label`) and a block is still
|
||||
open, also inserts `end` on the line after the new one, at the
|
||||
indentation of the statement that owns the `begin`; the cursor stays on
|
||||
the new, indented line. Nothing is added when the blocks already balance
|
||||
(an `end` under the owner or under a `begin` on its own line counts), nor
|
||||
for a `begin` left open inside an `ifdef` region that has an `else`.
|
||||
Setting `lucisv.autoEnd` (default on). The VS Code extension sends the
|
||||
request itself when `editor.formatOnType` is off.
|
||||
- **`always_ff @(` and `always @(` expand with clock and reset**:
|
||||
`posedge clk or negedge rst_n`, both names tab stops, as the ghost text
|
||||
and as the first popup template. The clock-only forms follow.
|
||||
- **This file's names rank first.** The popup's order is now: the scope at
|
||||
the cursor, names declared anywhere in this buffer, words used in it,
|
||||
then the workspace index, templates, keywords and project words.
|
||||
- **Keyword ghosts.** Two or more letters of a keyword show the rest as
|
||||
grey inline text (Tab accepts); with the popup open the ghost follows its
|
||||
selected entry. A word that is exactly a name the buffer declares gets
|
||||
none. A `.v` file is offered Verilog-2005 keywords only. Setting
|
||||
`lucisv.inlineKeywords` (default on). The `begin` ghost now also appears
|
||||
for a `begin` typed inside a block that already balances.
|
||||
- **Port suggestions.** After `.` in an instance, unconnected ports come
|
||||
first and already-connected ones follow, marked `connected`; they used to
|
||||
be left out. Accepting a port inserts `name()` with the cursor inside,
|
||||
pre-filled with a same-named signal when one is visible; parameter lists
|
||||
(`#(.`) behave the same.
|
||||
- **An unfinished connection stays in its own entry.** In the editor's
|
||||
tolerant parse, a lone `.`, a `.name(` still open at the end of its line
|
||||
and a trailing `,` are each recovered inside their entry — always with a
|
||||
diagnostic — so the rest of the list and the file still parse, colour and
|
||||
lint. Strict parsing, and so the formatter and the CLI, are unchanged.
|
||||
- **Errors on the connection being typed wait.** Diagnostics that start
|
||||
inside the entry the last edit touched, in a named-connection list of an
|
||||
instance, are withheld and published after 1.5 s without typing, on an
|
||||
edit elsewhere, or on save. A client that pulls diagnostics and supports
|
||||
it is sent `workspace/diagnostic/refresh`. Nothing outside that entry is
|
||||
ever withheld.
|
||||
- **Changed: a trailing `,` in a named connection list (`.a(x),)`) is now
|
||||
reported in the editor.** The formatter and the CLI always refused it;
|
||||
the editor's tolerant parse used to accept it silently. Format Selection
|
||||
elsewhere in such a file now works instead of refusing the whole file.
|
||||
|
||||
## 0.63.1 — 2026-11-11
|
||||
|
||||
### Sticky scroll shows every layer
|
||||
|
||||
(TODO §67.)
|
||||
|
||||
- **VS Code: sticky scroll pins the first line of every block you are
|
||||
inside.** Only the module header used to stay at the top of the editor,
|
||||
because sticky scroll follows the document outline by default and the
|
||||
outline stops at declarations. The extension now defaults
|
||||
`editor.stickyScroll.defaultModel` to `foldingProviderModel` for Verilog
|
||||
and SystemVerilog, so the pinned lines come from the server's folding
|
||||
ranges — the module, the `always`, the `case`, the case item, the `if` —
|
||||
and raises `editor.stickyScroll.maxLineCount` to 10 for those languages
|
||||
(VS Code's 5 fits exactly that example and nothing deeper). Your own
|
||||
settings still win.
|
||||
- Known limit: a layer without `begin` (a one-statement `if`, a case item
|
||||
with no `begin`) has no fold and so no pinned line; a `begin` on its own
|
||||
line pins that line, not the `always` above it.
|
||||
- No engine change: the server, formatter and linter are 0.63.0's.
|
||||
|
||||
## 0.63.0 — 2026-11-09
|
||||
|
||||
### Format Selection that fits where it stands; comment toggling in VS Code
|
||||
|
||||
(`docs/features/selection-formatting`; TODO §66.)
|
||||
|
||||
- **Format Selection lays out only the block you selected.** Selecting an
|
||||
`always` block, a `case` statement or a few statements used to re-lay the
|
||||
whole enclosing module-level item — at the formatter's own depth, so a
|
||||
block in a 4-space or tab-indented file moved, and the blank lines at the
|
||||
selection's edges were eaten. The new engine
|
||||
(`vlog_formatter::format_selection`) finds the smallest run of sibling
|
||||
items or statements the selected lines cover, lays out that run alone and
|
||||
puts it back starting at the leading whitespace it already has (tabs
|
||||
kept). The parent is not touched. `textDocument/rangeFormatting`,
|
||||
`rangesFormatting` and the on-type `;` all run on it.
|
||||
- **A parse error elsewhere in the file no longer refuses the request.** The
|
||||
selection is formatted when the error lies outside it, and refused only
|
||||
when it lies inside.
|
||||
- **How a selection picks its block.** Touching a block's first line takes
|
||||
the whole block; a selection that starts inside it takes only the
|
||||
statements it covers, even when it reaches the closing `end`; the `end`
|
||||
line alone takes the block it closes. A selection of whole module-level
|
||||
items behaves as before.
|
||||
- **Still verified.** Every result passes the whole-file equivalence check
|
||||
and a convergence replay, or the buffer is left unchanged; the verifier
|
||||
itself is unchanged. CRLF files keep every line ending.
|
||||
- The on-type `;` now tidies its statement in a buffer whose error is
|
||||
elsewhere, and no longer adds a final newline to a file without one.
|
||||
- The reply is still one whole-document edit; the CLI's `--lines` is
|
||||
unchanged (whole module-level items).
|
||||
- **VS Code: `Ctrl+/` toggles comments.** The extension now declares the
|
||||
language's `//` and `/* */` comments, bracket pairs and auto-closing
|
||||
pairs for Verilog and SystemVerilog, so Toggle Line Comment and Toggle
|
||||
Block Comment work on one line or a selection.
|
||||
|
||||
## 0.62.0 — 2026-10-19
|
||||
|
||||
### Paths rooted at a top-level module; a dependable release gate
|
||||
|
||||
@@ -139,6 +139,19 @@ Rules:
|
||||
|
||||
## Workflow
|
||||
|
||||
- **Agent models**: the lead plans and reviews; coding goes to one dev
|
||||
agent and verification to one QA agent, **both Claude Opus 5.5**
|
||||
(`model: "opus"`). This holds for a single lane and for each of two
|
||||
parallel lanes.
|
||||
- **Refactor lanes** (pure moves, decompositions): the dev is **Claude
|
||||
Fable 5.2 at high reasoning effort** — the `refactor-dev` agent in
|
||||
`.claude/agents/`. Its brief says: no new tests beyond what the move
|
||||
forces, the gates are the proof, spend the effort on module
|
||||
boundaries, naming and readability. QA is unchanged (Opus 5.5).
|
||||
- **Escalation**: a first QA failure gets a normal Opus 5.5 fix round.
|
||||
When a fix round fails QA a **second** time on the same feature, redo
|
||||
the round with **Claude Fable 5.2 as both dev and QA**
|
||||
(`model: "fable"`).
|
||||
- Do **not** run `git commit` or `git push` — the lead reviews and
|
||||
commits all work.
|
||||
- Do not touch files outside your feature's stated scope. If you need a
|
||||
@@ -187,8 +200,9 @@ proven independent and run serially. Rules for a parallel wave:
|
||||
while lanes are in flight; the lead merges each lane back only after
|
||||
that lane's QA verdict and lead review, and re-runs the full gates on
|
||||
the merged tree before pushing.
|
||||
- **Roles per lane are unchanged**: one dev (Opus), then one QA
|
||||
(Sonnet) in the same worktree, then the lead's review — so at most
|
||||
- **Roles per lane are unchanged**: one dev, then one QA — **both
|
||||
Claude Opus 5.5** (owner, 2026-11-09; QA was Sonnet before) — in the
|
||||
same worktree, then the lead's review — so at most
|
||||
2 devs + 2 QA agents exist at once, and a lane's QA starts only when
|
||||
its own dev is done. A QA rework loops inside its lane without
|
||||
blocking the other lane.
|
||||
|
||||
Generated
+9
-9
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.62.0"
|
||||
version = "0.65.5"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.62.0"
|
||||
version = "0.65.5"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_mcp"
|
||||
version = "0.62.0"
|
||||
version = "0.65.5"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"serde",
|
||||
@@ -126,7 +126,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.62.0"
|
||||
version = "0.65.5"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.62.0"
|
||||
version = "0.65.5"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.62.0"
|
||||
version = "0.65.5"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"vlog_formatter",
|
||||
@@ -279,11 +279,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.62.0"
|
||||
version = "0.65.5"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.62.0"
|
||||
version = "0.65.5"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -292,7 +292,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.62.0"
|
||||
version = "0.65.5"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -13,7 +13,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.62.0"
|
||||
version = "0.65.5"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -144,6 +144,9 @@ indent = 2 # 1..8, same as --indent
|
||||
exclude = [ "*_gen.sv", "build" ] # added to --exclude patterns
|
||||
filelist = "rtl/files.f" # an EDA `.f` filelist, relative to this file
|
||||
|
||||
[format]
|
||||
style = "google" # a named layout, same as --style (see Named styles)
|
||||
|
||||
[lint]
|
||||
select = ["no-tabs", "unused-signal"] # optional replacement for defaults
|
||||
ignore = ["module-filename"] # removed after selection
|
||||
@@ -173,11 +176,20 @@ error (exit 2) and nothing is processed. Details:
|
||||
**Precedence: CLI flag > config file > default**, per setting (`--indent 4`
|
||||
with a file that sets only `line-length` uses both). `exclude` is the
|
||||
exception: config patterns are *added* to `--exclude`, not replaced by it.
|
||||
`[format] style` (flag `--style`, editor `lucisv.format.style`) picks one of
|
||||
the [named styles](#named-styles). The style is resolved first and supplies
|
||||
the starting indent and line length; an explicit `indent` or `line-length` —
|
||||
from a flag or from the file — then wins over the preset's, so
|
||||
`style = "microsoft"` with `indent = 2` is Microsoft's layout at 2 spaces. An
|
||||
unknown style name is the same hard error as an unknown key, and lists the
|
||||
valid names. In the editor, `lucisv.toml` outranks the editor settings as for
|
||||
every formatting key, and a chosen style (other than `lucisv` or `auto`) also
|
||||
outranks the editor's tab size.
|
||||
`[format] uvm-utils-indent = true` (editor: `lucisv.format.uvmUtilsIndent`),
|
||||
off by default, indents the `` `uvm_field_* `` macros written between
|
||||
`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; it is the one
|
||||
formatting choice lucisv leaves to the project, because it changes bytes
|
||||
in existing UVM code (21 of the 860 corpus files).
|
||||
`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; like `style`,
|
||||
it is a formatting choice lucisv leaves to the project, because it changes
|
||||
bytes in existing UVM code (21 of the 860 corpus files).
|
||||
|
||||
An unknown key, a bad value, an out-of-range number, or any TOML beyond the
|
||||
supported subset (tables other than `[format]`, `[lint]` and `[lint.<rule>]`, multi-line
|
||||
@@ -512,7 +524,8 @@ Key ideas carried over from ruff/prettier:
|
||||
|
||||
Defaults follow Verible: **2-space indent**, **100-column lines** (both
|
||||
configurable via `--indent` / `--line-length` or a `lucisv.toml`, see
|
||||
[Configuration](#configuration)).
|
||||
[Configuration](#configuration)). The list below is the default `lucisv`
|
||||
style; the [named styles](#named-styles) change some of it.
|
||||
|
||||
- One port / parameter / connection per line once a header doesn't fit
|
||||
- Cuddled `begin`/`end` (`end else begin`)
|
||||
@@ -521,6 +534,49 @@ configurable via `--indent` / `--line-length` or a `lucisv.toml`, see
|
||||
- `` `define``/`` `ifdef``/`` `include`` and `(* attributes *)` passed
|
||||
through verbatim
|
||||
|
||||
### Named styles
|
||||
|
||||
`[format] style`, `--style` and the editor's `lucisv.format.style` drop-down
|
||||
pick one of a handful of house layouts. Every style moves whitespace only —
|
||||
which line a token starts on and how many spaces precede it — so the same
|
||||
token-equivalence check guards all of them, and each one is a fixed point of
|
||||
itself (proved over the 860-file corpus and OpenTitan's 4 061 `hw/` files for
|
||||
every preset; `docs/features/format-styles/README.md`).
|
||||
|
||||
| style | indent | width | `begin` | `else` after `end` | after `end : label` | header & connection lists | list indent | columns |
|
||||
|---|---|---|---|---|---|---|---|---|
|
||||
| `lucisv` (default) | 2 | 100 | same line | `end else` | `end : l else` | on one line if it fits | 1 level | kept where you wrote them |
|
||||
| `google` | 2 | 100 | same line | `end else` | own line | one entry per line | 2 levels | kept where you wrote them |
|
||||
| `lowrisc` | 2 | 100 | same line | `end else` | own line | one entry per line | 1 level | always aligned |
|
||||
| `ansi` | 4 | 80 | own line | own line | own line | on one line if it fits | 1 level | kept where you wrote them |
|
||||
| `microsoft` | 4 | 120 | own line | own line | own line | one entry per line | 1 level | kept where you wrote them |
|
||||
| `nxp` | 2 | 80 | same line | own line | own line | one entry per line | 1 level | always aligned |
|
||||
| `auto` | — | — | the preset the file is already closest to | | | | | |
|
||||
|
||||
`google` follows the [Google Verilog Style Guide](https://google.github.io/styleguide/verilogguide.html)
|
||||
and `lowrisc` the [lowRISC Verilog Coding Style Guide](https://github.com/lowRISC/style-guides/blob/master/VerilogCodingStyle.md)
|
||||
(OpenTitan's). **`ansi`, `microsoft` and `nxp` are lucisv's educated guesses**
|
||||
at what those names suggest — C formatters' ANSI/Allman layout, clang-format's
|
||||
`Microsoft` base style carried over to `begin`/`end`, a conservative RTL house
|
||||
style — not rules those organisations publish; none of them publishes a Verilog
|
||||
style that we could find. A `case` item's and a `do`'s `begin` stays on its
|
||||
own line's end in every style. "Header & connection lists" are module
|
||||
headers' parameter and port lists and instances' *named* overrides and
|
||||
connections — not `#(16)`, ordered connections or function ports. `lowrisc`
|
||||
differs from its guide in two places: the widest aligned connection keeps one
|
||||
space before its `(`, and a comment line ends an aligned table.
|
||||
|
||||
`auto` formats the file once per preset, at the configured indent and width,
|
||||
and keeps the output that changes the fewest lines (indentation included, so
|
||||
a one-line edit does not flip a whole file to another preset); it never
|
||||
guesses an indent or a width, and it is idempotent by construction.
|
||||
**`auto` picks a layout for the configured indent and width; it never infers them — set `indent` to match the file first.** Because every re-indented line counts as changed, a file written at another indent is closest to whichever preset changes the fewest of its lines once they are all re-indented: a 4-space Allman file (formatted with `--style ansi`) run through `--style auto` at the default indent 2 comes out in the cuddled `lucisv` layout, while with `indent = 4` it stays Allman (and with `line-length = 80` as well, byte for byte). Under
|
||||
`auto`, range and selection formatting use the style of the whole file, not
|
||||
of the selected lines; the language server remembers each document's preset
|
||||
from its last whole-file format, so a keystroke or a selection does not
|
||||
search again, and a buffer with a parse error keeps its preset. One that has
|
||||
never resolved — no memory, and it does not parse — gets the default layout.
|
||||
|
||||
### Alignment is inferred, not imposed
|
||||
|
||||
Hand-aligned columns are how RTL is read, so lucisv reads the spacing you
|
||||
|
||||
@@ -7127,3 +7127,280 @@ completion should offer `tb.`'s hierarchical members, answering `None` when
|
||||
the index has no unit of that name. `docs/features/top-rooted-paths`.
|
||||
|
||||
- [ ] owner/lead decision; if yes, `completion/member.rs` + tests
|
||||
|
||||
## 66. Format Selection that fits where it stands (planned 2026-11-09, owner's order)
|
||||
|
||||
Owner's report: *Format Selection* "fails more than half of the time". The
|
||||
usual selection is one whole `always` block or one whole `case` statement,
|
||||
often nested inside blocks the selection does not cover. Reproduced on trunk
|
||||
(`lucisv --lines`, the engine `textDocument/rangeFormatting` shares): selecting
|
||||
a `case` re-lays the whole `always` around it; the block is re-indented to the
|
||||
formatter's own depth × width, so in a file indented any other way it no
|
||||
longer lines up with its neighbours; a selection inside `generate` re-lays the
|
||||
whole region; and a file with a parse error anywhere is refused outright.
|
||||
Owner's rule: do not worry about the parent — the selected block keeps the
|
||||
indentation level it starts at, and stays functionally the same.
|
||||
|
||||
### 66.1 VS Code language configuration (lead, done 2026-11-09)
|
||||
|
||||
- [x] `editors/vscode/language-configuration.json` (comment tokens, brackets,
|
||||
auto-closing and surrounding pairs) wired to both language ids in
|
||||
`editors/vscode/package.json` — Toggle Line/Block Comment (Ctrl+/) works
|
||||
without another Verilog extension installed.
|
||||
|
||||
### 66.2 Selection formatting (one lane: dev, then QA)
|
||||
|
||||
Feature README: `docs/features/selection-formatting/README.md`. Files:
|
||||
`crates/vlog_formatter/src/selection.rs` (+ a `selection/` split if it nears
|
||||
600 lines), `crates/vlog_formatter/src/{lib.rs,printer.rs,format/mod.rs}`,
|
||||
`crates/vlog_formatter/tests/selection.rs`, `crates/lucisv_server/src/format.rs`,
|
||||
`crates/lucisv_server/src/server/tests/formatting.rs`,
|
||||
`crates/lucisv_server/tests/e2e.rs`. `verify.rs`, `range.rs`, `fence.rs`, the
|
||||
parser and the CLI's `--lines` are not touched.
|
||||
|
||||
- [x] `format_selection`: the smallest run of sibling items/statements the
|
||||
selected lines cover, laid out alone at the indentation it was written
|
||||
at, spliced into otherwise untouched bytes.
|
||||
- [x] Verified whole-file (`verify_equivalence`, unchanged) and converged by
|
||||
replaying the located target, not the line numbers.
|
||||
- [x] Fences outrank the selection; a module/package-level target defers to
|
||||
`format_range` (header/footer splitting).
|
||||
- [x] A file that does not parse: the target is located in the tolerant tree
|
||||
and refused when a diagnostic falls inside it.
|
||||
- [x] `textDocument/rangeFormatting` / `rangesFormatting` call it.
|
||||
- [x] Tests: the owner's shapes (whole `always`, whole `case`, inside
|
||||
`generate`, inside a function), off-grid and tab indentation, partial
|
||||
selections, comments, fences, broken files, masked-corruption attacks on
|
||||
the splice.
|
||||
|
||||
## 67. Sticky scroll shows every layer (planned 2026-11-11, owner's order)
|
||||
|
||||
VS Code pinned only the module header, because sticky scroll follows the
|
||||
document-symbol outline by default and the outline stops at declarations.
|
||||
The server's folding ranges already carry every `begin`/`end`, `case`,
|
||||
`fork`, `generate` and function — one fold per layer, starting on its header
|
||||
line.
|
||||
|
||||
- [x] `editors/vscode/package.json` `configurationDefaults` for both language
|
||||
ids: `editor.stickyScroll.defaultModel` = `foldingProviderModel` and
|
||||
`editor.stickyScroll.maxLineCount` = 10 (VS Code's default of 5 is the
|
||||
owner's example exactly, with nothing to spare). A user's own setting
|
||||
still wins.
|
||||
- [x] `crates/lucisv_server/src/folding.rs`: a test pinning that each layer
|
||||
of the owner's example (module, `always`, `case`, case item, `if`)
|
||||
starts a fold on its header line.
|
||||
- [ ] Seen in a running VS Code (owner).
|
||||
- Known limit: a layer with no `begin` (a one-statement `if`, a case item
|
||||
without `begin`) has no fold and so no pinned line; a `begin` written on
|
||||
its own line pins that `begin` line, not the `always` above it.
|
||||
|
||||
## 68. Completion that keeps up with typing (planned 2026-11-17, owner's order)
|
||||
|
||||
Five asks from the owner, about the VS Code extension. Two serial lanes
|
||||
(`lucisv_server` depends on `vlog_parser`, so they are not independent):
|
||||
68.1 first, then 68.2. Each lane: one dev, then one QA, both Opus 5.5.
|
||||
|
||||
### 68.1 Lane A — auto-`end`, templates, ranking, keyword ghosts, port items
|
||||
|
||||
Feature README: `docs/features/completion-ux/README.md`. Files:
|
||||
`crates/lucisv_server/src/{on_type.rs,inline.rs,templates.rs,pairs.rs,settings.rs,main.rs}`,
|
||||
`crates/lucisv_server/src/completion/*`, new modules beside them where a
|
||||
file is near 600 production lines, `crates/lucisv_server/tests/e2e.rs`,
|
||||
`editors/vscode/{extension.js,package.json,smoke.js,README.md}` and a new
|
||||
`editors/vscode/*_test.js` if the extension logic is factored out. No
|
||||
parser, formatter, linter or semantic crate change.
|
||||
|
||||
- [x] **`begin` + Enter writes the `end`** (owner: "more like begin +
|
||||
<return>, the cursor should be the next line of begin, at the correct
|
||||
indentation, and ready for the first statement"). The newline on-type
|
||||
answer, when the line above ends in `begin` (or `begin : label`) and
|
||||
the file has an unclosed `begin`, also inserts `end` on the line after
|
||||
the new one, at the indentation of the statement the `begin` belongs
|
||||
to; the cursor stays on the new, indented line. No `end` when the
|
||||
blocks already balance. Setting `lucisv.autoEnd` (default on). The
|
||||
extension sends the request itself when `editor.formatOnType` is off
|
||||
and puts the cursor back.
|
||||
- [x] **`always_ff @(` / `always @(` expand with clock and reset**:
|
||||
`posedge ${1:clk} or negedge ${2:rst_n}`, both tab stops, in the ghost
|
||||
and as the first popup template; the clock-only form stays available
|
||||
second.
|
||||
- [x] **Names from the current file rank first** in the popup: declared
|
||||
anywhere in this buffer, then words used in it, ahead of other files'
|
||||
names and of keywords.
|
||||
- [x] **Keyword ghosts**: a typed prefix of a keyword shows the rest of it
|
||||
as grey inline text (Tab accepts), following the popup's selected item
|
||||
when the popup is open. Setting `lucisv.inlineKeywords` (default on).
|
||||
- [x] **Port items**: unconnected ports first; already-connected ports
|
||||
listed after them, marked `connected` in the dimmed detail; accepting
|
||||
a port writes `.name($1)` with the cursor inside the parentheses.
|
||||
|
||||
### 68.2 Lane B — no rushed errors on the connection being typed
|
||||
|
||||
Feature README: `docs/features/port-entry-grace/README.md`. Files:
|
||||
`crates/vlog_parser/src/parser/instance.rs` (+ its tests),
|
||||
`crates/lucisv_server/src/{diagnostics.rs,server/diagnostics.rs,state/*}`.
|
||||
|
||||
- [x] Parser recovery keeps an unfinished connection (`.`, `.name(` open to
|
||||
the end of its line, a missing `,` before the next `.name`) inside its
|
||||
own entry — still a diagnostic, never silent — so the rest of the file
|
||||
parses, colours and lints as if the entry were complete.
|
||||
- [x] The server withholds the diagnostics that fall inside the entry the
|
||||
last edit touched, and releases them after a quiet period or when the
|
||||
next edit lands elsewhere.
|
||||
|
||||
## 69. Module instantiation syntax highlighting (2026-11-17, owner's order)
|
||||
|
||||
Feature README: `docs/features/instantiation-highlighting/README.md`. Files:
|
||||
`crates/lucisv_server/src/{tokens.rs,tokens/instantiation.rs}`,
|
||||
`editors/vscode/{package.json,.vscodeignore,semanticTokens_test.js}`,
|
||||
`docs/features/{lucisv-server,large-file-mode}/README.md`.
|
||||
|
||||
- [x] Distinct semantic highlights across module instantiations (14-type wire
|
||||
legend unchanged): module name (`class`), `#` + `.PARAM` overrides +
|
||||
parameter values (`parameter`, distinct from `()`), instance name
|
||||
(`function`), `.port`/`.*` (`property`), and port connections
|
||||
(`variable`), including unfinished entries while typing.
|
||||
- [x] `configurationDefaults` enables `editor.semanticHighlighting.enabled` and
|
||||
`semanticTokenScopes` maps `verilog`/`systemverilog` roles to distinct,
|
||||
non-white TextMate scopes across themes.
|
||||
|
||||
## 70. The tests pass on Linux, and one cleaning round (2026-11-19, owner's order)
|
||||
|
||||
Every suite had only ever run on macOS arm64; the Linux and Windows binaries
|
||||
ship unexecuted. A `linux-x64` Actions runner now exists (`luhpe-linux-x64`,
|
||||
a resource-capped Docker-in-Docker container on the Gitea host), and the
|
||||
first trial of the suite in its job image found: clippy red on three unused
|
||||
imports in `lucisv_server` test modules (their only users are tests compiled
|
||||
on macOS/Windows alone), and 11 distinct failing tests out of ~5 300 — eight
|
||||
that set up an unreadable/unwritable path and so cannot fail as root (the
|
||||
job image's user), one that assumes a case-insensitive filesystem, two
|
||||
`…_in_linear_time` timing assertions. No product failure among them as far
|
||||
as the trial shows. One lane, `docs/features/linux-test-portability`;
|
||||
`tools/linux_check.sh` runs the working tree in that image without a push.
|
||||
|
||||
- [x] `cargo clippy --all-targets -- -D warnings` clean on Linux and on
|
||||
macOS (`crates/lucisv_server/src/hover.rs`, `includes.rs` test modules,
|
||||
and whatever else the Linux build names).
|
||||
- [x] The permission-denied tests (`crates/lucisv/tests/cli.rs`,
|
||||
`crates/lucisv_core/src/walk.rs`, `crates/lucisv_mcp/src/apply.rs` and
|
||||
`tests/cache.rs`, `tests/qa_m6.rs`, `crates/lucisv_server/src/state/tests/filelist.rs`)
|
||||
pass both as root and as an unprivileged user: where the platform does
|
||||
not enforce the permission the test says so and stops, it does not
|
||||
assert the opposite.
|
||||
- [x] `crates/lucisv_server/src/file_ops.rs`
|
||||
`a_case_mismatched_include_spelling_still_narrows_in_and_rewrites`
|
||||
holds on a case-sensitive filesystem or is scoped to the insensitive
|
||||
ones, with the reason written at the test.
|
||||
- [x] `crates/lucisv_server/src/large.rs` — the two `…_in_linear_time`
|
||||
tests pass on the runner **and still fail when the conversion is
|
||||
quadratic** (shown, not asserted).
|
||||
- [x] The cleaning round: test code only, driven by what the tools report on
|
||||
either platform — unused imports and dead helpers, platform assumptions
|
||||
left implicit, assertions on wall-clock or environment that the runner
|
||||
shows to be fragile. No test is deleted and the test count does not
|
||||
drop; no production code and nothing in `verify.rs` changes.
|
||||
- [ ] `cargo test --workspace` green on Linux as root and with `--user`,
|
||||
and `tools/gates.sh` green on macOS.
|
||||
- [ ] (lead) `.gitea/workflows/ci.yml` gains a `linux` job on `linux-x64`;
|
||||
`docs/topo.md` and `tools/RELEASING.md` updated.
|
||||
|
||||
## 71. The overnight queue (2026-11-19, owner's order) — eight features, one release each
|
||||
|
||||
Ordered by the owner on 2026-11-19, to be done unattended after §70 lands:
|
||||
each item goes through the dev → QA → lead-review loop, is committed, and
|
||||
ships as its own release — `0.65.2`, `0.65.3`, … `0.65.n` in the order they
|
||||
finish — and once all are done, `0.66.0`. The lead has the owner's standing
|
||||
go-ahead to commit, tag and push for this queue. Every feature is tried on
|
||||
the OpenTitan tree (not only on unit fixtures) before it is called done.
|
||||
The items are the owner's words, lightly condensed; each gets its own
|
||||
subsection, plan and `docs/features/<name>/README.md` when its turn comes.
|
||||
|
||||
- [ ] **71.1 An edit does not re-index the whole database.** Today every
|
||||
file edit re-indexes everything. A change to a `define` may have to;
|
||||
a typical, localized edit must not.
|
||||
- [ ] **71.2 Actions stay fast on a huge, heavily-dependent tree.** Do the
|
||||
work dynamically: answer first from what is already in the same file
|
||||
(hover to a definition in this file), and use the relationship map to
|
||||
load completion candidates on demand.
|
||||
- [ ] **71.3 Highlighting does not wait for the index.** Always run a
|
||||
localized, viewport-only highlight; it may be imperfect and be
|
||||
corrected later, but basic colours must not wait for the whole
|
||||
database.
|
||||
- [x] **71.4 `` `ifdef `` / `` `else `` blocks fold** (0.65.4, `docs/features/ifdef-folding`), and take part in the
|
||||
sticky-scroll ("floating") bars.
|
||||
- [x] **71.5 The formatter adapts to the file's own style** (0.65.5, `docs/features/format-styles`: six named styles and `auto`)
|
||||
— where lines
|
||||
break, what is grouped, how ports align. If inferring that is too
|
||||
ambiguous, a setting with a drop-down of named styles instead (ANSI,
|
||||
Google, Microsoft, NXP — educated guesses), with the rules easy to
|
||||
read in the source.
|
||||
- [x] **71.6 The module view shows where you are.** (0.65.2, `docs/features/hierarchy-current-path`; not yet seen in a running editor.)
|
||||
Highlight the open
|
||||
file's instance and its parents in different shades — bright light
|
||||
orange for the instance, dimmer the further up — or anything in that
|
||||
spirit that makes the hierarchy easy to read.
|
||||
- [ ] **71.7 Find References sometimes answers "not found"** on a
|
||||
port/signal, then works after clicking elsewhere and back. VS Code or
|
||||
the server? Investigate, then fix what is ours.
|
||||
- [x] **71.8 Comments: no code colours inside them** (0.65.3, `docs/features/comment-highlighting`; the bracket colour is VS Code's, explained not changed)
|
||||
(the `[]` of
|
||||
`signal[]` gets highlighted today), **but do highlight `TODO`,
|
||||
`FIXME`, `FIX_ME`, `TBD`**, plus a user setting for custom words that
|
||||
are highlighted only in comments.
|
||||
- [ ] **71.9 Release `0.66.0`** once 71.1–71.8 have each shipped.
|
||||
|
||||
### 71 — wave 1 (lead, 2026-11-19): 71.6 runs beside §70
|
||||
|
||||
The owner asked not to wait for §70's Linux runs. §70 is test code in the
|
||||
Rust crates and touches no contract; 71.6 is the extension's hierarchy view
|
||||
(`editors/vscode/hierarchy*.js`, `package.json`, the extension README and
|
||||
changelog). Disjoint file sets, and the one edge between the two areas
|
||||
(`editors/vscode ◀──▶ lucisv_server`, the spawn contract) is touched by
|
||||
neither — so they run as two lanes: §70 on trunk's tree (already in flight
|
||||
there), 71.6 in the worktree `../lucisv-wt/71.6` on `lane/71.6-module-view`,
|
||||
branched from `88546c8`. 71.1–71.3 all live in `lucisv_server`'s state and
|
||||
indexing, collide with each other and with §70's test files, and wait for
|
||||
§70 to merge.
|
||||
|
||||
- Lane 71.6 owns: `editors/vscode/hierarchyView.js`, `hierarchyModel.js`,
|
||||
`hierarchySections.js` and their `_test.js` files, new
|
||||
`editors/vscode/*.js` modules it adds, `editors/vscode/package.json`
|
||||
(`contributes` only — not `version`), `editors/vscode/.vscodeignore`,
|
||||
`tools/release.sh`'s runtime-module checks if a new module needs listing,
|
||||
`docs/features/hierarchy-current-path/README.md`.
|
||||
|
||||
- Wave 2 (lead, 2026-11-19): 71.6 shipped as 0.65.2 (`e9f5090`). §70 is still
|
||||
in flight on trunk's tree, so the next lane is again one that stays out of
|
||||
the Rust test files: **71.8** (comments), in `../lucisv-wt/71.8` on
|
||||
`lane/71.8-comments` from `e9f5090`. It owns
|
||||
`editors/vscode/syntaxes/*`, `language-configuration.json`, new
|
||||
`editors/vscode/*.js` modules and tests, `extension.js` wiring,
|
||||
`package.json` `contributes`, `.vscodeignore`, the extension README, and —
|
||||
only if the stray colour turns out to come from the server's semantic
|
||||
tokens — `crates/lucisv_server/src/tokens.rs` and `tokens/`, which §70
|
||||
does not touch. `docs/features/comment-highlighting/README.md`.
|
||||
|
||||
- Wave 3 (lead, 2026-11-19): 71.8 shipped as 0.65.3 (`948f8a0`) and 71.4 as
|
||||
0.65.4 (`d574969`), each from its own worktree; both tagged locally and
|
||||
**not pushed** — the owner's ssh key left the agent at about 05:00 (its
|
||||
`AddKeysToAgent 1h`), which also stops `tools/linux_check.sh`. §70 is
|
||||
committed on macOS evidence with its Linux line left open. 71.5 (formatter
|
||||
styles) runs in `../lucisv-wt/71.5` from `d574969`. Owed once ssh is back,
|
||||
in this order: push master and the tags one at a time; re-run §70 on Linux
|
||||
(root twice, `--user`); add the `linux` job to `ci.yml`.
|
||||
|
||||
- Wave 4 (lead, 2026-11-19): 71.5 shipped as 0.65.5 from `../lucisv-wt/71.5`,
|
||||
rebased onto §70's commit. 71.1 (localized re-index) is with QA in
|
||||
`../lucisv-wt/71.1`. Found on the way by 71.5's QA, all present in 0.65.4
|
||||
and filed here, not fixed:
|
||||
- [ ] A comment between a generate `end` and `else` (also a trailing `// c`
|
||||
after a labelled generate `end` before `else`) is a verification
|
||||
error: the file is left unformatted. The safety net works; the
|
||||
formatter should not need it.
|
||||
- [ ] `` `ifdef `` between `end` and `else` is a parse error.
|
||||
- [ ] An attribute on an ANSI port (`(* keep *) input a`) is a parse error.
|
||||
- [ ] The server's `line-length` lint falls back to 100 columns under the
|
||||
`ansi`/`microsoft`/`nxp` styles (`lucisv_server/src/lint.rs`); taken
|
||||
when 71.1 merges.
|
||||
- [ ] One-per-line styles give multi-instance declarations
|
||||
(`p1 u8 (...), u9 (...)`) the hanging layout.
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Hand-rolled command line parsing for the `lucisv` binary.
|
||||
|
||||
use lucisv_core::cache;
|
||||
use lucisv_core::config::FileConfig;
|
||||
use lucisv_core::config::{self, FileConfig};
|
||||
use vlog_formatter::{Config, LineRanges};
|
||||
|
||||
/// Which tool this invocation runs.
|
||||
@@ -58,6 +58,8 @@ pub struct Options {
|
||||
pub line_length: Option<usize>,
|
||||
/// `--indent`, if given; otherwise the config file decides.
|
||||
pub indent: Option<usize>,
|
||||
/// `--style`, if given; otherwise the config file decides.
|
||||
pub style: Option<&'static str>,
|
||||
/// `--lines`: format only the constructs meeting these lines. `None` is a
|
||||
/// whole-file run.
|
||||
pub lines: Option<LineRanges>,
|
||||
@@ -98,8 +100,13 @@ impl Options {
|
||||
}
|
||||
|
||||
/// Formatter settings for one file: CLI flag > config file > default.
|
||||
///
|
||||
/// The style is resolved first and supplies the starting indent and line
|
||||
/// length; an explicit `indent`/`line-length`, from the flag or the file,
|
||||
/// is then written over the preset's, whichever rung named the style.
|
||||
pub fn config_with(&self, file: &FileConfig) -> Config {
|
||||
let mut config = Config::default();
|
||||
let name = self.style.or(file.format_style);
|
||||
let mut config = name.and_then(Config::named).unwrap_or_default();
|
||||
if let Some(n) = self.line_length.or(file.line_length) {
|
||||
config.max_width = n;
|
||||
}
|
||||
@@ -196,6 +203,12 @@ OPTIONS:
|
||||
filelist, and neither reads nor writes the cache
|
||||
--line-length <N> maximum line length (default 100)
|
||||
--indent <N> indent width in spaces (default 2)
|
||||
--style <NAME> layout preset: lucisv (the default), google,
|
||||
lowrisc, ansi, microsoft or nxp. It sets the indent
|
||||
and line length too; --indent/--line-length (or the
|
||||
config file's keys) still win over the preset's.
|
||||
`auto` lays each file out in the preset it is
|
||||
already closest to, at the default indent/width
|
||||
--no-config ignore lucisv.toml / .lucisv.toml files
|
||||
-h, --help show this help
|
||||
-V, --version show version
|
||||
@@ -275,7 +288,7 @@ FILELISTS:
|
||||
|
||||
CACHE:
|
||||
A file whose exact content lucisv has already verified is formatted — under
|
||||
the same line-length, indent and lucisv version — is skipped on the next run
|
||||
the same line-length, indent, style and lucisv version — is skipped on the next run
|
||||
and reported as `N files from cache`. Only that \"already formatted\"
|
||||
verdict is ever cached: a file that would be reformatted, or that failed,
|
||||
is re-checked every run. The cache is one text file under `.lucisv_cache/`;
|
||||
@@ -288,10 +301,12 @@ CONFIGURATION:
|
||||
optional: `line-length` (40-400), `indent` (1-8), `exclude` (array of
|
||||
patterns, added to `--exclude`), `filelist` (path to an EDA `.f` file,
|
||||
read by lucisv-server only — the CLI reads a filelist only when `-f` names
|
||||
one, so `lucisv rtl/` always means the directory it was given). One table
|
||||
is recognized, `[lint]`, with `select` and `ignore` (arrays of rule names,
|
||||
`--select`/`--ignore` semantics) and `waivers` (an array of waiver file
|
||||
paths, resolved against the config file's own directory). A command line
|
||||
one, so `lucisv rtl/` always means the directory it was given). The
|
||||
`[format]` table takes `style` (a preset name, as `--style`) and
|
||||
`uvm-utils-indent` (true/false). The `[lint]` table takes `select` and
|
||||
`ignore` (arrays of rule names, `--select`/`--ignore` semantics) and
|
||||
`waivers` (an array of waiver file paths, resolved against the config
|
||||
file's own directory). A command line
|
||||
flag overrides the file's corresponding key; the other keys still apply —
|
||||
`--waiver-file` is the exception, and adds to `waivers` rather than
|
||||
replacing it.
|
||||
@@ -335,6 +350,7 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
exclude: Vec::new(),
|
||||
line_length: None,
|
||||
indent: None,
|
||||
style: None,
|
||||
lines: None,
|
||||
output_format: OutputFormat::Text,
|
||||
fix: false,
|
||||
@@ -400,6 +416,10 @@ 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}"))?);
|
||||
}
|
||||
"--style" => {
|
||||
let v = args.next().ok_or("--style requires a value")?;
|
||||
opts.style = Some(config::parse_style(&v)?);
|
||||
}
|
||||
"--lines" => {
|
||||
let v = args.next().ok_or("--lines requires a value")?;
|
||||
line_specs.push(v);
|
||||
@@ -526,6 +546,7 @@ fn check_flag_scopes(opts: &Options) -> Result<(), String> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_formatter::style;
|
||||
|
||||
fn parse(args: &[&str]) -> Result<Options, String> {
|
||||
parse_from(args.iter().map(|s| s.to_string()))
|
||||
@@ -568,6 +589,52 @@ mod tests {
|
||||
assert_eq!(opts.config_with(&FileConfig::default()).indent_width, default.indent_width);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_style_sets_the_starting_values_and_explicit_ones_win() {
|
||||
let none = FileConfig::default();
|
||||
let opts = parse(&["--style", "microsoft", "rtl"]).unwrap();
|
||||
let config = opts.config_with(&none);
|
||||
assert_eq!(config.style, style::MICROSOFT);
|
||||
assert_eq!((config.indent_width, config.max_width), (4, 120));
|
||||
// The file's explicit keys beat the flag's preset...
|
||||
let file = FileConfig { indent: Some(3), ..Default::default() };
|
||||
assert_eq!(opts.config_with(&file).indent_width, 3);
|
||||
assert_eq!(opts.config_with(&file).max_width, 120);
|
||||
// ...and the flag beats the file's style.
|
||||
let google = FileConfig { format_style: Some("google"), ..Default::default() };
|
||||
assert_eq!(opts.config_with(&google).style, style::MICROSOFT);
|
||||
let opts = parse(&["--indent", "2", "rtl"]).unwrap();
|
||||
let config = opts.config_with(&google);
|
||||
assert_eq!((config.style, config.indent_width), (style::GOOGLE, 2));
|
||||
// No style anywhere is exactly the old default.
|
||||
let config = parse(&["rtl"]).unwrap().config_with(&none);
|
||||
assert_eq!(config.style, style::LUCISV);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_style_names_the_styles() {
|
||||
let Err(message) = parse(&["--style", "allman", "rtl"]) else { panic!("accepted") };
|
||||
assert!(message.contains("unknown style `allman`"), "{message}");
|
||||
assert!(
|
||||
message.contains("lucisv, google, lowrisc, ansi, microsoft, nxp, auto"),
|
||||
"{message}"
|
||||
);
|
||||
assert!(parse(&["--style"]).is_err());
|
||||
}
|
||||
|
||||
/// `lucisv_core` keeps its own copy of the names so it can reject a bad
|
||||
/// `[format] style` without depending on the formatter; this is the test
|
||||
/// that keeps the copy honest.
|
||||
#[test]
|
||||
fn the_core_style_names_are_the_formatter_presets() {
|
||||
let mut names: Vec<&str> = style::names().collect();
|
||||
names.push("auto");
|
||||
assert_eq!(names, config::STYLE_NAMES);
|
||||
for name in config::STYLE_NAMES {
|
||||
assert_eq!(Config::named(name).map(|c| c.style_name()), Some(name));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_excludes_are_appended_to_cli_excludes() {
|
||||
let file = FileConfig { exclude: Some(vec!["gen".to_string()]), ..Default::default() };
|
||||
|
||||
@@ -338,6 +338,7 @@ fn entry_for(content: u64, config: &Config) -> Entry {
|
||||
line_length: config.max_width,
|
||||
indent: config.indent_width,
|
||||
uvm_utils_indent: config.uvm_utils_indent,
|
||||
style: config.style_name(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1268,7 +1268,8 @@ impl TempDir {
|
||||
}
|
||||
|
||||
/// One hand-written cache line, for the tests that forge entries. The
|
||||
/// fields are the store's, in order; `uvm` is `[format] uvm-utils-indent`.
|
||||
/// fields are the store's, in order; `uvm` is `[format] uvm-utils-indent`,
|
||||
/// and the style is always the default, `lucisv`.
|
||||
fn cache_line(
|
||||
path: &str,
|
||||
content: &str,
|
||||
@@ -1278,7 +1279,7 @@ fn cache_line(
|
||||
version: &str,
|
||||
) -> String {
|
||||
let hash = lucisv_core::cache::content_hash(content.as_bytes());
|
||||
format!("{hash:016x}\t{line_length}\t{indent}\t{uvm}\t{version}\t{path}\n")
|
||||
format!("{hash:016x}\t{line_length}\t{indent}\t{uvm}\tlucisv\t{version}\t{path}\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2241,11 +2242,33 @@ fn unlock(dir: &TempDir) {
|
||||
std::fs::set_permissions(dir.path.join("locked"), std::fs::Permissions::from_mode(0o755));
|
||||
}
|
||||
|
||||
/// Whether file modes bind this process: a mode-000 directory refuses to be
|
||||
/// listed. Root lists it anyway (Linux CI jobs run as root), and there a
|
||||
/// directory the walk cannot read cannot be built, so the tests below say so
|
||||
/// and stop instead of asserting a warning that cannot happen.
|
||||
#[cfg(unix)]
|
||||
fn listing_is_refused() -> bool {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let probe = TempDir::new("mode-probe");
|
||||
let shut = probe.path.join("shut");
|
||||
std::fs::create_dir(&shut).expect("probe dir");
|
||||
std::fs::set_permissions(&shut, std::fs::Permissions::from_mode(0o000)).expect("chmod");
|
||||
let refused = std::fs::read_dir(&shut).is_err();
|
||||
let _ = std::fs::set_permissions(&shut, std::fs::Permissions::from_mode(0o755));
|
||||
if !refused {
|
||||
eprintln!("skipped: a mode-000 directory is readable by this user (root?)");
|
||||
}
|
||||
refused
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_unreadable_directory_is_a_warning_and_the_rest_of_the_tree_is_formatted() {
|
||||
// The finding TODO §45.2 closes: one permission-denied directory used to
|
||||
// propagate `read_dir`'s error and fail the whole run.
|
||||
if !listing_is_refused() {
|
||||
return;
|
||||
}
|
||||
let dir = unwalkable_tree("walk-warn");
|
||||
let out = run(&[&dir.root()]);
|
||||
unlock(&dir);
|
||||
@@ -2262,6 +2285,9 @@ fn an_unreadable_directory_is_a_warning_and_the_rest_of_the_tree_is_formatted()
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn the_walks_warnings_leave_check_modes_exit_code_alone() {
|
||||
if !listing_is_refused() {
|
||||
return;
|
||||
}
|
||||
let dir = unwalkable_tree("walk-warn-check");
|
||||
let out = run(&["--check", &dir.root()]);
|
||||
unlock(&dir);
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
//! `--style` and `[format] style` through the real `lucisv` binary: the
|
||||
//! flag, the config key, their precedence over each other and under the
|
||||
//! explicit `indent`/`line-length`, the error for a name that is not a
|
||||
//! preset, and the format cache keyed on the style.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Output};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
const LUCISV: &str = env!("CARGO_BIN_EXE_lucisv");
|
||||
|
||||
/// One `if`/`else` whose layout every switch of `ansi` changes.
|
||||
const SOURCE: &str =
|
||||
"module m;\n initial if (a) begin x = 1; end else begin x = 2; end\nendmodule\n";
|
||||
const LUCISV_OUT: &str = "\
|
||||
module m;
|
||||
initial
|
||||
if (a) begin
|
||||
x = 1;
|
||||
end else begin
|
||||
x = 2;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
const ANSI_OUT: &str = "\
|
||||
module m;
|
||||
initial
|
||||
if (a)
|
||||
begin
|
||||
x = 1;
|
||||
end
|
||||
else
|
||||
begin
|
||||
x = 2;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A throwaway directory under the system temp dir, removed on drop.
|
||||
struct TempDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> TempDir {
|
||||
static COUNTER: AtomicUsize = AtomicUsize::new(0);
|
||||
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("lucisv-style-{}-{tag}-{n}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(&path).expect("create temp dir");
|
||||
// Discovery stops at a `.git`, so no config above the temp dir leaks in.
|
||||
std::fs::write(path.join(".git"), "gitdir: nowhere\n").expect("write .git");
|
||||
TempDir { path }
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, contents: &str) -> String {
|
||||
let path = self.path.join(rel);
|
||||
std::fs::write(&path, contents).expect("write fixture");
|
||||
path.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn read(&self, rel: &str) -> String {
|
||||
std::fs::read_to_string(self.path.join(rel)).expect("read fixture")
|
||||
}
|
||||
|
||||
fn cache(&self) -> String {
|
||||
self.path.join("cache").to_string_lossy().into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
fn run(args: &[&str]) -> Output {
|
||||
Command::new(LUCISV).args(args).output().expect("run lucisv")
|
||||
}
|
||||
|
||||
fn code(out: &Output) -> i32 {
|
||||
out.status.code().expect("exit code")
|
||||
}
|
||||
|
||||
fn stdout(out: &Output) -> String {
|
||||
String::from_utf8_lossy(&out.stdout).into_owned()
|
||||
}
|
||||
|
||||
fn stderr(out: &Output) -> String {
|
||||
String::from_utf8_lossy(&out.stderr).into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_flag_picks_a_preset() {
|
||||
let dir = TempDir::new("flag");
|
||||
let path = dir.write("a.sv", SOURCE);
|
||||
let out = run(&["--no-cache", "--stdout", "--style", "ansi", &path]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(stdout(&out), ANSI_OUT);
|
||||
let out = run(&["--no-cache", "--stdout", &path]);
|
||||
assert_eq!(stdout(&out), LUCISV_OUT, "no style is the default layout");
|
||||
let out = run(&["--no-cache", "--stdout", "--style", "lucisv", &path]);
|
||||
assert_eq!(stdout(&out), LUCISV_OUT, "and `lucisv` is that same layout");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_config_key_picks_a_preset_and_the_flag_beats_it() {
|
||||
let dir = TempDir::new("toml");
|
||||
dir.write("lucisv.toml", "[format]\nstyle = \"ansi\"\n");
|
||||
let path = dir.write("a.sv", SOURCE);
|
||||
assert_eq!(code(&run(&["--no-cache", &path])), 0);
|
||||
assert_eq!(dir.read("a.sv"), ANSI_OUT);
|
||||
let out = run(&["--no-cache", "--stdout", "--style", "lucisv", &path]);
|
||||
assert_eq!(stdout(&out), LUCISV_OUT, "CLI flag > config file");
|
||||
let out = run(&["--no-cache", "--stdout", "--no-config", &path]);
|
||||
assert_eq!(stdout(&out), LUCISV_OUT, "--no-config drops the style with the file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_indent_wins_over_the_presets() {
|
||||
let dir = TempDir::new("indent");
|
||||
let path = dir.write("a.sv", SOURCE);
|
||||
let out = run(&["--no-cache", "--stdout", "--style", "ansi", "--indent", "2", &path]);
|
||||
assert_eq!(stdout(&out), ANSI_OUT.replace(" ", " "));
|
||||
// The file's `indent` beats the flag's preset too: an explicit value is
|
||||
// explicit wherever it was written.
|
||||
dir.write("lucisv.toml", "indent = 2\n");
|
||||
let out = run(&["--no-cache", "--stdout", "--style", "ansi", &path]);
|
||||
assert_eq!(stdout(&out), ANSI_OUT.replace(" ", " "));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_style_is_an_error_that_lists_the_presets() {
|
||||
let dir = TempDir::new("unknown");
|
||||
let path = dir.write("a.sv", SOURCE);
|
||||
let out = run(&["--no-cache", "--style", "allman", &path]);
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(stderr(&out).contains("unknown style `allman`"), "{}", stderr(&out));
|
||||
assert!(
|
||||
stderr(&out).contains("lucisv, google, lowrisc, ansi, microsoft, nxp"),
|
||||
"{}",
|
||||
stderr(&out)
|
||||
);
|
||||
// The same in `lucisv.toml`, naming the file and the line; nothing written.
|
||||
let config = dir.write("lucisv.toml", "indent = 2\n[format]\nstyle = \"allman\"\n");
|
||||
let out = run(&["--no-cache", &path]);
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(stderr(&out).contains(&format!("{config}:3:")), "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("unknown style `allman`"), "{}", stderr(&out));
|
||||
assert_eq!(dir.read("a.sv"), SOURCE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_the_style_invalidates_the_cache_entry() {
|
||||
let dir = TempDir::new("cache");
|
||||
let path = dir.write("a.sv", LUCISV_OUT);
|
||||
let cache = dir.cache();
|
||||
let out = run(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
let out = run(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
// The same bytes are not clean under another style, cache or no cache.
|
||||
let out = run(&["--check", "--style", "ansi", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 1, "the style is part of the key: {}", stderr(&out));
|
||||
// And a clean verdict under `ansi` is not one under the default.
|
||||
dir.write("a.sv", ANSI_OUT);
|
||||
assert_eq!(code(&run(&["--check", "--style", "ansi", &path, "--cache-dir", &cache])), 0);
|
||||
let out = run(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 1, "{}", stderr(&out));
|
||||
}
|
||||
@@ -12,6 +12,8 @@ use std::collections::HashMap;
|
||||
use std::fmt::Write as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::config::STYLE_NAMES;
|
||||
|
||||
/// The default cache directory, resolved against the current directory.
|
||||
pub const DEFAULT_DIR: &str = ".lucisv_cache";
|
||||
|
||||
@@ -35,6 +37,10 @@ pub struct Entry {
|
||||
/// The `[format] uvm-utils-indent` that verdict was reached under: it
|
||||
/// changes the output of a UVM class, so it is part of the key.
|
||||
pub uvm_utils_indent: bool,
|
||||
/// The `[format] style` that verdict was reached under, one of
|
||||
/// [`crate::config::STYLE_NAMES`]: every preset lays files out
|
||||
/// differently, so it is part of the key.
|
||||
pub style: &'static str,
|
||||
}
|
||||
|
||||
/// The cache for one run: loaded once at startup, written once at exit.
|
||||
@@ -107,8 +113,8 @@ impl Cache {
|
||||
let entry = &self.entries[path];
|
||||
let _ = writeln!(
|
||||
text,
|
||||
"{:016x}\t{}\t{}\t{}\t{VERSION}\t{path}",
|
||||
entry.content, entry.line_length, entry.indent, entry.uvm_utils_indent
|
||||
"{:016x}\t{}\t{}\t{}\t{}\t{VERSION}\t{path}",
|
||||
entry.content, entry.line_length, entry.indent, entry.uvm_utils_indent, entry.style
|
||||
);
|
||||
}
|
||||
text
|
||||
@@ -154,28 +160,39 @@ fn prefix(content: &str, line_length: &str, indent: &str) -> Option<(u64, usize,
|
||||
fn parse(text: &str) -> Option<HashMap<String, Entry>> {
|
||||
let mut entries = HashMap::new();
|
||||
for line in text.lines() {
|
||||
let fields: Vec<&str> = line.splitn(6, '\t').collect();
|
||||
let fields: Vec<&str> = line.splitn(7, '\t').collect();
|
||||
match fields[..] {
|
||||
[content, line_length, indent, uvm, version, path] => {
|
||||
[content, line_length, indent, uvm, style, version, path] => {
|
||||
let (content, line_length, indent) = prefix(content, line_length, indent)?;
|
||||
let uvm_utils_indent = uvm.parse().ok()?;
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if version == VERSION {
|
||||
// A style this build does not know is another build's
|
||||
// entry: stale, not corrupt.
|
||||
let known = STYLE_NAMES.into_iter().find(|n| *n == style);
|
||||
if let (Some(style), true) = (known, version == VERSION) {
|
||||
entries.insert(
|
||||
path.to_string(),
|
||||
Entry { content, line_length, indent, uvm_utils_indent },
|
||||
Entry { content, line_length, indent, uvm_utils_indent, style },
|
||||
);
|
||||
}
|
||||
}
|
||||
// A store written before `uvm-utils-indent` joined the key: a
|
||||
// well-formed line of that older shape says nothing about the
|
||||
// option, so it is dropped individually, exactly like another
|
||||
// version's entry. (The version field alone already makes such
|
||||
// a store miss; the codec stays self-describing anyway.)
|
||||
// Anything else on five fields is corruption and discards the
|
||||
// file like any other malformed line.
|
||||
// A store written before `style` joined the key: a well-formed
|
||||
// line of that older shape says nothing about the style, so it is
|
||||
// dropped individually, exactly like another version's entry.
|
||||
[content, line_length, indent, uvm, _version, path] => {
|
||||
prefix(content, line_length, indent)?;
|
||||
uvm.parse::<bool>().ok()?;
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
// And the same for the shape before `uvm-utils-indent` joined it.
|
||||
// (The version field alone already makes such a store miss; the
|
||||
// codec stays self-describing anyway.) Anything else on five or
|
||||
// six fields is corruption and discards the file like any other
|
||||
// malformed line.
|
||||
[content, line_length, indent, _version, path] => {
|
||||
prefix(content, line_length, indent)?;
|
||||
if path.is_empty() {
|
||||
@@ -228,7 +245,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn entry(content: u64) -> Entry {
|
||||
Entry { content, line_length: 100, indent: 2, uvm_utils_indent: false }
|
||||
Entry { content, line_length: 100, indent: 2, uvm_utils_indent: false, style: "lucisv" }
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -262,6 +279,7 @@ mod tests {
|
||||
assert!(!reloaded.is_clean(&file, Entry { line_length: 80, ..entry(0xdead) }));
|
||||
assert!(!reloaded.is_clean(&file, Entry { indent: 4, ..entry(0xdead) }));
|
||||
assert!(!reloaded.is_clean(&file, Entry { uvm_utils_indent: true, ..entry(0xdead) }));
|
||||
assert!(!reloaded.is_clean(&file, Entry { style: "google", ..entry(0xdead) }));
|
||||
assert!(!reloaded.is_clean(Path::new("other.sv"), entry(0xdead)));
|
||||
}
|
||||
|
||||
@@ -276,7 +294,7 @@ mod tests {
|
||||
let mut cache = Cache::load(&dir.path);
|
||||
cache.record(&file, on);
|
||||
cache.store();
|
||||
assert!(dir.cache_text().contains("\t100\t2\ttrue\t"), "{}", dir.cache_text());
|
||||
assert!(dir.cache_text().contains("\t100\t2\ttrue\tlucisv\t"), "{}", dir.cache_text());
|
||||
|
||||
let reloaded = Cache::load(&dir.path);
|
||||
assert!(reloaded.is_clean(&file, on));
|
||||
@@ -291,7 +309,7 @@ mod tests {
|
||||
let old = dir.file("old.sv");
|
||||
let mine = dir.file("mine.sv");
|
||||
let text = format!(
|
||||
"{:016x}\t100\t2\t{VERSION}\t{}\n{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
|
||||
"{:016x}\t100\t2\t{VERSION}\t{}\n{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n",
|
||||
1,
|
||||
old.to_string_lossy(),
|
||||
2,
|
||||
@@ -308,6 +326,37 @@ mod tests {
|
||||
assert!(!dir.cache_text().contains("old.sv"), "{}", dir.cache_text());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_without_the_style_or_with_an_unknown_one_is_dropped_but_not_fatal() {
|
||||
// The six-field shape lucisv wrote before `style` joined the key, and
|
||||
// a style this build does not know: both stale, never corruption.
|
||||
let dir = TempDir::new("nostyle");
|
||||
let old = dir.file("old.sv");
|
||||
let other = dir.file("other.sv");
|
||||
let mine = dir.file("mine.sv");
|
||||
let text = format!(
|
||||
"{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n\
|
||||
{:016x}\t100\t2\tfalse\tbespoke\t{VERSION}\t{}\n\
|
||||
{:016x}\t100\t2\tfalse\tnxp\t{VERSION}\t{}\n",
|
||||
1,
|
||||
old.to_string_lossy(),
|
||||
2,
|
||||
other.to_string_lossy(),
|
||||
3,
|
||||
mine.to_string_lossy()
|
||||
);
|
||||
std::fs::write(dir.path.join(FILE), text).unwrap();
|
||||
|
||||
let cache = Cache::load(&dir.path);
|
||||
assert!(!cache.is_clean(&old, entry(1)), "a line without the style must not be trusted");
|
||||
assert!(!cache.is_clean(&other, Entry { style: "lucisv", ..entry(2) }));
|
||||
assert!(cache.is_clean(&mine, Entry { style: "nxp", ..entry(3) }));
|
||||
assert!(!cache.is_clean(&mine, entry(3)), "the style is part of the key");
|
||||
cache.store();
|
||||
assert!(!dir.cache_text().contains("old.sv"), "{}", dir.cache_text());
|
||||
assert!(!dir.cache_text().contains("other.sv"), "{}", dir.cache_text());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_is_sorted_and_carries_the_version() {
|
||||
let dir = TempDir::new("format");
|
||||
@@ -325,7 +374,7 @@ mod tests {
|
||||
assert!(lines[1].ends_with("b.sv"), "sorted by path: {text}");
|
||||
assert_eq!(
|
||||
lines[0],
|
||||
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}", 1, a.to_string_lossy()),
|
||||
format!("{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}", 1, a.to_string_lossy()),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
@@ -350,13 +399,19 @@ mod tests {
|
||||
"0000000000000001\t100\t2\t0.2.0\t\n",
|
||||
"0000000000000001\t100\t2\tyes\t0.2.0\t/a.sv\n",
|
||||
"0000000000000001\t100\t2\tfalse\t0.2.0\t\n",
|
||||
"0000000000000001\t100\t2\tyes\tlucisv\t0.2.0\t/a.sv\n",
|
||||
"0000000000000001\t100\twide\tfalse\tlucisv\t0.2.0\t/a.sv\n",
|
||||
"0000000000000001\t100\t2\tfalse\tlucisv\t0.2.0\t\n",
|
||||
"\0\0\0\n",
|
||||
] {
|
||||
let dir = TempDir::new("corrupt");
|
||||
let file = dir.file("a.sv");
|
||||
// A good line first: a bad one anywhere discards all of them.
|
||||
let good =
|
||||
format!("{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n", 1, file.to_string_lossy());
|
||||
let good = format!(
|
||||
"{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n",
|
||||
1,
|
||||
file.to_string_lossy()
|
||||
);
|
||||
std::fs::write(dir.path.join(FILE), format!("{good}{corrupt}")).unwrap();
|
||||
let cache = Cache::load(&dir.path);
|
||||
assert!(!cache.is_clean(&file, entry(1)), "should have been discarded: {corrupt:?}");
|
||||
@@ -369,8 +424,8 @@ mod tests {
|
||||
let old = dir.file("old.sv");
|
||||
let mine = dir.file("mine.sv");
|
||||
let text = format!(
|
||||
"{:016x}\t100\t2\tfalse\t0.0.0-not-this-one\t{}\n\
|
||||
{:016x}\t100\t2\tfalse\t{VERSION}\t{}\n",
|
||||
"{:016x}\t100\t2\tfalse\tlucisv\t0.0.0-not-this-one\t{}\n\
|
||||
{:016x}\t100\t2\tfalse\tlucisv\t{VERSION}\t{}\n",
|
||||
1,
|
||||
old.to_string_lossy(),
|
||||
2,
|
||||
|
||||
@@ -11,7 +11,14 @@ use std::collections::HashMap;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
/// Config file names, in the order a directory is probed.
|
||||
const NAMES: [&str; 2] = ["lucisv.toml", ".lucisv.toml"];
|
||||
pub const NAMES: [&str; 2] = ["lucisv.toml", ".lucisv.toml"];
|
||||
|
||||
/// The names `[format] style` accepts: the formatter's presets, in its
|
||||
/// `style::PRESETS` order, then `auto`. This crate knows no Verilog and so
|
||||
/// does not depend on the formatter; the two lists are held equal by a test
|
||||
/// in the `lucisv` crate, which sees both.
|
||||
pub const STYLE_NAMES: [&str; 7] =
|
||||
["lucisv", "google", "lowrisc", "ansi", "microsoft", "nxp", "auto"];
|
||||
|
||||
/// The settings one config file carries. Every key is optional; an unset
|
||||
/// key leaves the CLI flag (or the built-in default) in charge.
|
||||
@@ -34,6 +41,9 @@ pub struct FileConfig {
|
||||
/// statements written between `` `uvm_*_utils_begin `` and
|
||||
/// `` `uvm_*_utils_end ``. Off for the same reason.
|
||||
pub format_uvm_utils_indent: Option<bool>,
|
||||
/// `[format] style`: the named layout preset, one of [`STYLE_NAMES`].
|
||||
/// Checked here, so a misspelt name fails the run like a misspelt key.
|
||||
pub format_style: Option<&'static str>,
|
||||
/// `[lint] select`: run exactly these rules, replacing the default set.
|
||||
/// The names are **not** validated here — this crate does not know the
|
||||
/// rule registry; `lucisv check` validates them the moment it resolves the
|
||||
@@ -176,23 +186,30 @@ fn parse_entry(
|
||||
}
|
||||
_ => Err(format!(
|
||||
"unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \
|
||||
uvm-utils-indent under `[format]`; \
|
||||
style, uvm-utils-indent under `[format]`; \
|
||||
select, ignore, waivers under `[lint]`; and a rule's own options \
|
||||
under `[lint.<rule-name>]`)"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// One key of the `[format]` table: a boolean that defaults to off, because
|
||||
/// it changes how already-clean files are laid out and a project has to opt
|
||||
/// in before anything of its moves.
|
||||
/// One key of the `[format]` table: the named `style`, or a boolean that
|
||||
/// defaults to off, because it changes how already-clean files are laid out
|
||||
/// and a project has to opt in before anything of its moves.
|
||||
fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> {
|
||||
if key == "style" {
|
||||
if config.format_style.is_some() {
|
||||
return Err(format!("duplicate key `{key}`"));
|
||||
}
|
||||
config.format_style = Some(parse_style(&parse_string(value)?)?);
|
||||
return Ok(());
|
||||
}
|
||||
let slot = match key {
|
||||
"uvm-utils-indent" => &mut config.format_uvm_utils_indent,
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"unknown key `{key}` under `[format]` \
|
||||
(the only key is uvm-utils-indent)"
|
||||
(known keys: style, uvm-utils-indent)"
|
||||
))
|
||||
}
|
||||
};
|
||||
@@ -203,6 +220,13 @@ fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One of [`STYLE_NAMES`], exactly as spelt there.
|
||||
pub fn parse_style(name: &str) -> Result<&'static str, String> {
|
||||
STYLE_NAMES.into_iter().find(|n| *n == name).ok_or_else(|| {
|
||||
format!("unknown style `{name}` (the styles are {})", STYLE_NAMES.join(", "))
|
||||
})
|
||||
}
|
||||
|
||||
/// `true` or `false`, and nothing else — a misspelling is a typo the user
|
||||
/// wants to hear about, not a silent `false`.
|
||||
fn parse_bool(key: &str, value: &str) -> Result<bool, String> {
|
||||
@@ -614,6 +638,32 @@ exclude = [ \"build\", \"*_gen.sv\", ]
|
||||
assert_eq!(mixed.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..]));
|
||||
}
|
||||
|
||||
/// `[format] style` names a preset; anything else is an error that lists
|
||||
/// the presets, the way an unknown key lists the keys.
|
||||
#[test]
|
||||
fn the_format_table_carries_a_style() {
|
||||
assert_eq!(ok("[format]\nstyle = \"google\"").format_style, Some("google"));
|
||||
assert_eq!(ok("[format]\nstyle = \"lucisv\" # the default").format_style, Some("lucisv"));
|
||||
assert_eq!(ok("indent = 4").format_style, None);
|
||||
for name in STYLE_NAMES {
|
||||
assert_eq!(ok(&format!("[format]\nstyle = \"{name}\"")).format_style, Some(name));
|
||||
}
|
||||
let unknown = err("[format]\nstyle = \"gogle\"");
|
||||
assert!(unknown.contains("unknown style `gogle`"), "{unknown}");
|
||||
assert!(
|
||||
unknown.contains("lucisv, google, lowrisc, ansi, microsoft, nxp, auto"),
|
||||
"{unknown}"
|
||||
);
|
||||
assert!(err("[format]\nstyle = \"Google\"").contains("unknown style `Google`"));
|
||||
assert!(err("[format]\nstyle = google").contains("expected a quoted string"));
|
||||
assert!(
|
||||
err("[format]\nstyle = \"ansi\"\nstyle = \"nxp\"").contains("duplicate key `style`")
|
||||
);
|
||||
// Like `uvm-utils-indent`, it lives in `[format]` and nowhere else.
|
||||
assert!(err("style = \"google\"").contains("unknown key `style`"));
|
||||
assert!(err("[lint]\nstyle = \"google\"").contains("unknown key `style` under `[lint]`"));
|
||||
}
|
||||
|
||||
/// Everything about the table's shape, the way the `[lint]` table's is
|
||||
/// pinned: an unknown key is named, a non-boolean value is refused, and a
|
||||
/// repeated key is an error rather than a last-one-wins.
|
||||
|
||||
@@ -731,6 +731,13 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl Drop for TempTree {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_directory_linking_to_itself_is_entered_once() {
|
||||
@@ -794,12 +801,41 @@ mod tests {
|
||||
assert_eq!(warnings, ["a/gone.sv: broken symbolic link"]);
|
||||
}
|
||||
|
||||
/// Whether file modes bind this process: a mode-000 `rel` (a directory
|
||||
/// when `rel` ends in `/`, else a file) refuses to be read. Root reads it
|
||||
/// anyway (Linux CI jobs run as root), so the unreadable-path tests below
|
||||
/// cannot build their path there; they say so and stop.
|
||||
#[cfg(unix)]
|
||||
fn reading_is_refused(rel: &str) -> bool {
|
||||
let probe = TempTree::new("mode-probe");
|
||||
let path = probe.path.join(rel);
|
||||
if rel.ends_with('/') {
|
||||
std::fs::create_dir(&path).expect("probe dir");
|
||||
} else {
|
||||
probe.write(rel, "");
|
||||
}
|
||||
probe.chmod(rel, 0o000);
|
||||
let refused = if rel.ends_with('/') {
|
||||
std::fs::read_dir(&path).is_err()
|
||||
} else {
|
||||
std::fs::File::open(&path).is_err()
|
||||
};
|
||||
probe.chmod(rel, 0o755);
|
||||
if !refused {
|
||||
eprintln!("skipped: a mode-000 `{rel}` is readable by this user (root?)");
|
||||
}
|
||||
refused
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_unreadable_directory_is_skipped_and_the_walk_goes_on() {
|
||||
// The finding this channel exists for: one permission-denied directory
|
||||
// used to propagate `read_dir`'s error out of the whole walk, dropping
|
||||
// every file already found and failing the run.
|
||||
if !reading_is_refused("shut/") {
|
||||
return;
|
||||
}
|
||||
let tree = TempTree::new("unreadable");
|
||||
tree.source("a.sv");
|
||||
tree.source("locked/hidden.sv");
|
||||
@@ -815,6 +851,9 @@ mod tests {
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_unreadable_ignore_file_is_said_and_the_directory_is_still_walked() {
|
||||
if !reading_is_refused("shut") {
|
||||
return;
|
||||
}
|
||||
let tree = TempTree::new("lockedignore");
|
||||
tree.write(".gitignore", "build\n");
|
||||
tree.source("keep.sv");
|
||||
|
||||
@@ -274,6 +274,25 @@ mod tests {
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// Whether file modes bind this process: a mode-555 directory under `dir`
|
||||
/// refuses a new file. Root writes it anyway (Linux CI jobs run as root),
|
||||
/// so there the half of the test below that needs a directory refusing
|
||||
/// the temp file cannot be built; it says so and stops.
|
||||
#[cfg(unix)]
|
||||
fn creating_is_refused(dir: &Path) -> bool {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let shut = dir.join("mode-probe");
|
||||
fs::create_dir(&shut).unwrap();
|
||||
fs::set_permissions(&shut, fs::Permissions::from_mode(0o555)).unwrap();
|
||||
let refused = fs::write(shut.join("x"), "").is_err();
|
||||
fs::set_permissions(&shut, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
fs::remove_dir_all(&shut).unwrap();
|
||||
if !refused {
|
||||
eprintln!("skipped: a mode-555 directory takes new files from this user (root?)");
|
||||
}
|
||||
refused
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_write_that_fails_after_another_landed_says_what_was_written() {
|
||||
@@ -290,6 +309,10 @@ mod tests {
|
||||
let refused = commit(&[&first, &second], name).unwrap_err();
|
||||
assert_eq!(refused, "`b.sv` is read-only; nothing written.");
|
||||
assert_eq!(fs::read_to_string(&a).unwrap(), "a\n");
|
||||
if !creating_is_refused(&dir) {
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
return;
|
||||
}
|
||||
// … but a directory that will not take the temp file fails only at
|
||||
// the write, after `a.sv` landed: said, not hidden.
|
||||
fs::set_permissions(&b, fs::Permissions::from_mode(0o644)).unwrap();
|
||||
|
||||
@@ -161,7 +161,9 @@ impl Runs {
|
||||
}
|
||||
waivers.absorb(file);
|
||||
}
|
||||
let format = vlog_formatter::Config::default();
|
||||
// The width and indent the file would be formatted with, its style's
|
||||
// included, so the linter and the formatter cannot disagree.
|
||||
let format = super::format::formatter_config(config);
|
||||
Ok(Run {
|
||||
rules,
|
||||
options,
|
||||
|
||||
@@ -119,9 +119,10 @@ fn fixed_and_formatted(
|
||||
}
|
||||
|
||||
/// The formatter settings a file's `lucisv.toml` resolves to — the CLI's
|
||||
/// `Options::config_with` with no command-line flags.
|
||||
fn formatter_config(file: &FileConfig) -> Config {
|
||||
let mut config = Config::default();
|
||||
/// `Options::config_with` with no command-line flags: the style first, then
|
||||
/// the explicit keys over the preset's indent and width.
|
||||
pub(super) fn formatter_config(file: &FileConfig) -> Config {
|
||||
let mut config = file.format_style.and_then(Config::named).unwrap_or_default();
|
||||
if let Some(width) = file.line_length {
|
||||
config.max_width = width;
|
||||
}
|
||||
@@ -195,3 +196,25 @@ fn touches_fence(fix: &Fix, regions: &[Region]) -> bool {
|
||||
.iter()
|
||||
.any(|(range, _)| fence::is_protected(regions, range.start as usize, range.end as usize))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_formatter::style;
|
||||
|
||||
/// The MCP `format` tool resolves a `lucisv.toml` the way `lucisv` with no
|
||||
/// flags does: the style first, the explicit keys over its numbers.
|
||||
#[test]
|
||||
fn the_style_comes_first_and_explicit_keys_win() {
|
||||
let none = formatter_config(&FileConfig::default());
|
||||
assert_eq!((none.style, none.indent_width, none.max_width), (style::LUCISV, 2, 100));
|
||||
let ansi = FileConfig { format_style: Some("ansi"), ..Default::default() };
|
||||
let config = formatter_config(&ansi);
|
||||
assert_eq!((config.style, config.indent_width, config.max_width), (style::ANSI, 4, 80));
|
||||
let narrowed = FileConfig { indent: Some(2), line_length: Some(90), ..ansi };
|
||||
let config = formatter_config(&narrowed);
|
||||
assert_eq!((config.style, config.indent_width, config.max_width), (style::ANSI, 2, 90));
|
||||
let auto = FileConfig { format_style: Some("auto"), ..Default::default() };
|
||||
assert!(formatter_config(&auto).auto_style);
|
||||
}
|
||||
}
|
||||
@@ -242,11 +242,32 @@ fn a_missing_directory_starts_cold_and_its_own_store_serves_the_next_start() {
|
||||
assert!(stderr.contains(&reused(0, FILES - 1)), "{stderr}");
|
||||
}
|
||||
|
||||
/// Whether file modes bind this process: a mode-555 directory refuses a new
|
||||
/// file. Root writes it anyway (Linux CI jobs run as root), so there an
|
||||
/// unwritable cache directory cannot be built; the test says so and stops.
|
||||
#[cfg(unix)]
|
||||
fn creating_is_refused(scratch: &Scratch) -> bool {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let shut = scratch.0.join("mode-probe");
|
||||
fs::create_dir_all(&shut).unwrap();
|
||||
fs::set_permissions(&shut, fs::Permissions::from_mode(0o555)).unwrap();
|
||||
let refused = fs::write(shut.join("x"), "").is_err();
|
||||
fs::set_permissions(&shut, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
fs::remove_dir_all(&shut).unwrap();
|
||||
if !refused {
|
||||
eprintln!("skipped: a mode-555 directory takes new files from this user (root?)");
|
||||
}
|
||||
refused
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn an_unwritable_cache_directory_still_answers_and_says_so_on_exit() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let scratch = Scratch::new();
|
||||
if !creating_is_refused(&scratch) {
|
||||
return;
|
||||
}
|
||||
fs::create_dir_all(scratch.cache()).unwrap();
|
||||
fs::set_permissions(scratch.cache(), fs::Permissions::from_mode(0o555)).unwrap();
|
||||
let stderr = whole_session(&scratch);
|
||||
|
||||
@@ -444,6 +444,24 @@ fn qa_index_cache_naming_a_file_answers_and_leaves_the_file_alone() {
|
||||
assert_eq!(fs::read_to_string(&file).unwrap(), "keep me\n");
|
||||
}
|
||||
|
||||
/// Whether file modes bind this process: a mode-000 directory refuses to be
|
||||
/// listed. Root lists it anyway (Linux CI jobs run as root), so there a cache
|
||||
/// directory without permission cannot be built; the test says so and stops.
|
||||
#[cfg(unix)]
|
||||
fn listing_is_refused(scratch: &Scratch) -> bool {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let shut = scratch.0.join("mode-probe");
|
||||
fs::create_dir_all(&shut).unwrap();
|
||||
fs::set_permissions(&shut, fs::Permissions::from_mode(0o000)).unwrap();
|
||||
let refused = fs::read_dir(&shut).is_err();
|
||||
fs::set_permissions(&shut, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
fs::remove_dir_all(&shut).unwrap();
|
||||
if !refused {
|
||||
eprintln!("skipped: a mode-000 directory is readable by this user (root?)");
|
||||
}
|
||||
refused
|
||||
}
|
||||
|
||||
/// A cache directory with no permissions at all (mode 000, holding a whole
|
||||
/// honest editor store): nothing can be read, so the start is cold; the
|
||||
/// answers are right; the exit says it could not write, once; the store in
|
||||
@@ -453,6 +471,9 @@ fn qa_index_cache_naming_a_file_answers_and_leaves_the_file_alone() {
|
||||
fn qa_a_cache_directory_without_permission_is_a_cold_start_that_answers() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let scratch = Scratch::new();
|
||||
if !listing_is_refused(&scratch) {
|
||||
return;
|
||||
}
|
||||
let (cold, _) = probe(&scratch, None);
|
||||
scratch.write_editor_store(&honest_store(&scratch));
|
||||
let before = hash_file(&scratch.editor_store());
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
//! The preset `style = "auto"` last settled on, per document.
|
||||
//!
|
||||
//! Under `auto`, every formatting request needs a concrete preset, and
|
||||
//! finding one means formatting the whole buffer once per preset. That is
|
||||
//! fine for a whole-document format, which formats the whole buffer anyway,
|
||||
//! but not for an on-type `;` or a selection, which would pay it on every
|
||||
//! keystroke — and on a buffer that does not parse (exactly when on-type
|
||||
//! runs), no preset can be found at all.
|
||||
//!
|
||||
//! So a whole-document format remembers the preset it used, and the range,
|
||||
//! selection and on-type requests reuse it. Without a memory they resolve
|
||||
//! once from the buffer — when it parses — and remember that. Without a
|
||||
//! memory and without a parse they lay out in the default preset's layout,
|
||||
//! as the formatter itself does. The memory is a small most-recent list.
|
||||
//!
|
||||
//! A remembered preset is only right while the buffer is still the text it
|
||||
//! was resolved from, edited by hand. So it is **forgotten** whenever that
|
||||
//! may no longer be true: the document is opened, closed, renamed or deleted;
|
||||
//! it is formatted or laid out under a named style; and — for every document
|
||||
//! — whenever the settings change or a `lucisv.toml` change is seen.
|
||||
//! Forgetting costs one search on the next request; remembering wrongly would
|
||||
//! lay the file out in a preset it no longer uses.
|
||||
//!
|
||||
//! A change that replaces the **whole** buffer (a reload from disk, an
|
||||
//! external formatter, or every change of a full-sync client) marks the
|
||||
//! entry *replaced* rather than dropping it: the next request resolves
|
||||
//! afresh from the new text, and only if that text does not parse — so there
|
||||
//! is nothing to resolve from — does it fall back to the old preset, which is
|
||||
//! still a better guess than the default layout. A full-sync client's every
|
||||
//! keystroke is such a change, and a half-typed buffer is exactly when
|
||||
//! on-type runs; dropping the entry there would lose the file's preset at the
|
||||
//! moment the memory exists for.
|
||||
//! See `docs/features/format-styles/README.md`.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use lsp_server::Notification;
|
||||
use lsp_types::notification::{
|
||||
DidChangeWatchedFiles, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument,
|
||||
DidRenameFiles, Notification as _,
|
||||
};
|
||||
use lsp_types::{
|
||||
DeleteFilesParams, DidChangeWatchedFilesParams, DidCloseTextDocumentParams,
|
||||
DidOpenTextDocumentParams, RenameFilesParams, TextDocumentContentChangeEvent, TextEdit, Uri,
|
||||
};
|
||||
use vlog_formatter::{format_auto, style, Config, Style};
|
||||
|
||||
use crate::format;
|
||||
use crate::state::Document;
|
||||
|
||||
/// How many documents' presets are remembered.
|
||||
const CAPACITY: usize = 64;
|
||||
|
||||
/// The presets of the most recently formatted documents, newest last.
|
||||
#[derive(Default)]
|
||||
pub struct AutoStyles {
|
||||
recent: VecDeque<Entry>,
|
||||
}
|
||||
|
||||
/// One remembered document.
|
||||
struct Entry {
|
||||
uri: Uri,
|
||||
preset: Style,
|
||||
/// A change replaced the whole buffer since `preset` was resolved, so it
|
||||
/// is only a fallback: resolve again when the buffer parses.
|
||||
replaced: bool,
|
||||
}
|
||||
|
||||
impl AutoStyles {
|
||||
/// Format a whole buffer. Under `auto` this resolves afresh and
|
||||
/// remembers the preset it used; under a named style it is
|
||||
/// [`format::formatting`].
|
||||
pub fn format_document(
|
||||
&mut self,
|
||||
uri: &Uri,
|
||||
doc: &Document,
|
||||
config: &Config,
|
||||
) -> Result<Option<TextEdit>, String> {
|
||||
if !config.auto_style {
|
||||
// Formatted under a named style, the buffer may now be in it.
|
||||
self.forget(uri);
|
||||
return format::formatting(doc, config);
|
||||
}
|
||||
let (formatted, preset) = format_auto(&doc.text, config).map_err(|e| e.to_string())?;
|
||||
self.remember(uri, preset);
|
||||
Ok(format::whole_document_edit(doc, formatted))
|
||||
}
|
||||
|
||||
/// `config` made concrete for a range, selection or on-type request on
|
||||
/// `doc`: unchanged under a named style; under `auto`, the remembered
|
||||
/// preset, else the one the buffer resolves to (then remembered), else —
|
||||
/// the buffer does not parse — the default preset's layout.
|
||||
pub fn concrete(&mut self, uri: &Uri, doc: &Document, config: Config) -> Config {
|
||||
if !config.auto_style {
|
||||
self.forget(uri);
|
||||
return config;
|
||||
}
|
||||
let held = self.recall(uri);
|
||||
let preset = match held {
|
||||
Some((preset, false)) => preset,
|
||||
// Nothing trustworthy held: resolve from the buffer when it
|
||||
// parses; otherwise the old preset if there is one, else the
|
||||
// default layout. A fallback is never stored as fresh.
|
||||
_ => match format_auto(&doc.text, &config) {
|
||||
Ok((_, preset)) => {
|
||||
self.remember(uri, preset);
|
||||
preset
|
||||
}
|
||||
Err(_) => held.map_or(style::LUCISV, |(preset, _)| preset),
|
||||
},
|
||||
};
|
||||
Config { style: preset, auto_style: false, ..config }
|
||||
}
|
||||
|
||||
/// Whether nothing is remembered yet.
|
||||
#[cfg(test)]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.recent.is_empty()
|
||||
}
|
||||
|
||||
/// Forget what a notification may have made stale: the document a
|
||||
/// `didOpen`/`didClose` names, the old and new names of a renamed file,
|
||||
/// a deleted file, and every document when a watched-file event names a
|
||||
/// `lucisv.toml` or `.lucisv.toml`. Anything else is ignored.
|
||||
pub fn notice(&mut self, notification: &Notification) {
|
||||
let params = || notification.params.clone();
|
||||
match notification.method.as_str() {
|
||||
DidOpenTextDocument::METHOD => {
|
||||
if let Ok(p) = serde_json::from_value::<DidOpenTextDocumentParams>(params()) {
|
||||
self.forget(&p.text_document.uri);
|
||||
}
|
||||
}
|
||||
DidCloseTextDocument::METHOD => {
|
||||
if let Ok(p) = serde_json::from_value::<DidCloseTextDocumentParams>(params()) {
|
||||
self.forget(&p.text_document.uri);
|
||||
}
|
||||
}
|
||||
DidRenameFiles::METHOD => {
|
||||
if let Ok(p) = serde_json::from_value::<RenameFilesParams>(params()) {
|
||||
self.forget_named(p.files.iter().flat_map(|f| [&f.old_uri, &f.new_uri]));
|
||||
}
|
||||
}
|
||||
DidDeleteFiles::METHOD => {
|
||||
if let Ok(p) = serde_json::from_value::<DeleteFilesParams>(params()) {
|
||||
self.forget_named(p.files.iter().map(|f| &f.uri));
|
||||
}
|
||||
}
|
||||
DidChangeWatchedFiles::METHOD => {
|
||||
if let Ok(p) = serde_json::from_value::<DidChangeWatchedFilesParams>(params()) {
|
||||
if p.changes.iter().any(|c| names_a_config(c.uri.as_str())) {
|
||||
self.forget_all();
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark `uri`'s entry replaced when a `didChange` replaced its whole
|
||||
/// text: a change with no range (full sync), or one that starts at the
|
||||
/// top and leaves nothing of the old text after it — `result` is exactly
|
||||
/// its text.
|
||||
pub fn changed(&mut self, uri: &Uri, changes: &[TextDocumentContentChangeEvent], result: &str) {
|
||||
let rangeless = changes.iter().any(|c| c.range.is_none());
|
||||
let from_the_top = changes.last().is_some_and(|c| {
|
||||
c.range.is_some_and(|r| r.start.line == 0 && r.start.character == 0) && c.text == result
|
||||
});
|
||||
if rangeless || from_the_top {
|
||||
if let Some(entry) = self.recent.iter_mut().find(|e| e.uri == *uri) {
|
||||
entry.replaced = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Forget every document: the settings, or a `lucisv.toml`, changed.
|
||||
pub fn forget_all(&mut self) {
|
||||
self.recent.clear();
|
||||
}
|
||||
|
||||
fn forget(&mut self, uri: &Uri) {
|
||||
self.recent.retain(|e| e.uri != *uri);
|
||||
}
|
||||
|
||||
fn forget_named<'a>(&mut self, uris: impl Iterator<Item = &'a String>) {
|
||||
for uri in uris {
|
||||
self.recent.retain(|e| e.uri.as_str() != uri);
|
||||
}
|
||||
}
|
||||
|
||||
/// The remembered preset, and whether it has been marked replaced.
|
||||
fn recall(&self, uri: &Uri) -> Option<(Style, bool)> {
|
||||
self.recent.iter().find(|e| e.uri == *uri).map(|e| (e.preset, e.replaced))
|
||||
}
|
||||
|
||||
fn remember(&mut self, uri: &Uri, preset: Style) {
|
||||
self.forget(uri);
|
||||
if self.recent.len() == CAPACITY {
|
||||
self.recent.pop_front();
|
||||
}
|
||||
self.recent.push_back(Entry { uri: uri.clone(), preset, replaced: false });
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a URI names a config file: `lucisv.toml` or `.lucisv.toml`.
|
||||
fn names_a_config(uri: &str) -> bool {
|
||||
let name = uri.rsplit('/').next().unwrap_or(uri);
|
||||
lucisv_core::config::NAMES.contains(&name)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::state::Workspace;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// A google-formatted module: one port per line at a 4-space list indent.
|
||||
const GOOGLE: &str = "\
|
||||
module m (
|
||||
input logic a,
|
||||
output logic b
|
||||
);
|
||||
sub u_sub (
|
||||
.a(a),
|
||||
.b(b)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
fn open(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 auto() -> Config {
|
||||
Config::named("auto").expect("auto")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_document_format_remembers_the_preset_it_used() {
|
||||
let (ws, uri) = open(GOOGLE);
|
||||
let mut styles = AutoStyles::default();
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
assert_eq!(styles.format_document(&uri, doc, &auto()), Ok(None), "already formatted");
|
||||
assert_eq!(styles.recall(&uri), Some((style::GOOGLE, false)));
|
||||
let concrete = styles.concrete(&uri, doc, auto());
|
||||
assert_eq!((concrete.style, concrete.auto_style), (style::GOOGLE, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_style_is_left_alone_and_nothing_is_remembered() {
|
||||
let (ws, uri) = open(GOOGLE);
|
||||
let mut styles = AutoStyles::default();
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let ansi = Config::styled(style::ANSI);
|
||||
assert_eq!(styles.concrete(&uri, doc, ansi.clone()).style, style::ANSI);
|
||||
assert!(styles.format_document(&uri, doc, &ansi).is_ok());
|
||||
assert_eq!(styles.recall(&uri), None);
|
||||
}
|
||||
|
||||
/// The memory is what lets a half-typed buffer keep its file's preset:
|
||||
/// without it, a buffer that does not parse gets the default's layout.
|
||||
#[test]
|
||||
fn a_buffer_that_does_not_parse_uses_the_remembered_preset() {
|
||||
let broken = GOOGLE.replace("endmodule", " assign x = ;\nendmodule");
|
||||
let (ws, uri) = open(&broken);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let mut styles = AutoStyles::default();
|
||||
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::LUCISV, "no memory, no parse");
|
||||
assert_eq!(styles.recall(&uri), None, "and a fallback is not remembered");
|
||||
styles.remember(&uri, style::GOOGLE);
|
||||
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::GOOGLE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_memory_a_buffer_that_parses_resolves_once() {
|
||||
let (ws, uri) = open(GOOGLE);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let mut styles = AutoStyles::default();
|
||||
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::GOOGLE);
|
||||
assert_eq!(styles.recall(&uri), Some((style::GOOGLE, false)), "resolved, then remembered");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_memory_is_bounded_and_keeps_the_most_recent() {
|
||||
let mut styles = AutoStyles::default();
|
||||
let uri = |n: usize| Uri::from_str(&format!("file:///rtl/m{n}.sv")).expect("uri");
|
||||
for n in 0..CAPACITY + 10 {
|
||||
styles.remember(&uri(n), style::NXP);
|
||||
}
|
||||
assert_eq!(styles.recent.len(), CAPACITY);
|
||||
assert_eq!(styles.recall(&uri(0)), None, "the oldest is forgotten");
|
||||
assert_eq!(styles.recall(&uri(CAPACITY + 9)), Some((style::NXP, false)));
|
||||
// Remembering again moves a document to the back and replaces its preset.
|
||||
styles.remember(&uri(10), style::ANSI);
|
||||
styles.remember(&uri(10), style::GOOGLE);
|
||||
assert_eq!(styles.recall(&uri(10)), Some((style::GOOGLE, false)));
|
||||
assert_eq!(styles.recent.len(), CAPACITY);
|
||||
}
|
||||
|
||||
fn notification(method: &str, params: serde_json::Value) -> Notification {
|
||||
Notification { method: method.to_string(), params }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_close_rename_and_delete_forget_the_document() {
|
||||
let mut styles = AutoStyles::default();
|
||||
let (a, b) = (
|
||||
Uri::from_str("file:///rtl/a.sv").expect("uri"),
|
||||
Uri::from_str("file:///rtl/b.sv").expect("uri"),
|
||||
);
|
||||
let doc = |uri: &Uri| {
|
||||
serde_json::json!({ "textDocument": {
|
||||
"uri": uri, "languageId": "systemverilog", "version": 1, "text": "" } })
|
||||
};
|
||||
for method in [DidOpenTextDocument::METHOD, DidCloseTextDocument::METHOD] {
|
||||
styles.remember(&a, style::GOOGLE);
|
||||
styles.notice(¬ification(method, doc(&a)));
|
||||
assert_eq!(styles.recall(&a), None, "{method}");
|
||||
}
|
||||
styles.remember(&a, style::GOOGLE);
|
||||
styles.remember(&b, style::NXP);
|
||||
styles.notice(¬ification(
|
||||
DidRenameFiles::METHOD,
|
||||
serde_json::json!({ "files": [{ "oldUri": a.as_str(), "newUri": b.as_str() }] }),
|
||||
));
|
||||
assert!(styles.is_empty(), "both names of a renamed file are forgotten");
|
||||
styles.remember(&a, style::GOOGLE);
|
||||
styles.notice(¬ification(
|
||||
DidDeleteFiles::METHOD,
|
||||
serde_json::json!({ "files": [{ "uri": a.as_str() }] }),
|
||||
));
|
||||
assert_eq!(styles.recall(&a), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_config_file_change_or_a_settings_change_forgets_everything() {
|
||||
let mut styles = AutoStyles::default();
|
||||
let a = Uri::from_str("file:///rtl/a.sv").expect("uri");
|
||||
let watched = |name: &str| {
|
||||
notification(
|
||||
DidChangeWatchedFiles::METHOD,
|
||||
serde_json::json!({ "changes": [{ "uri": format!("file:///rtl/{name}"), "type": 2 }] }),
|
||||
)
|
||||
};
|
||||
styles.remember(&a, style::GOOGLE);
|
||||
styles.notice(&watched("other.sv"));
|
||||
assert!(!styles.is_empty(), "a source file changing on disk says nothing about presets");
|
||||
for name in ["lucisv.toml", ".lucisv.toml"] {
|
||||
styles.remember(&a, style::GOOGLE);
|
||||
styles.notice(&watched(name));
|
||||
assert!(styles.is_empty(), "{name}");
|
||||
}
|
||||
styles.remember(&a, style::GOOGLE);
|
||||
styles.forget_all();
|
||||
assert!(styles.is_empty());
|
||||
}
|
||||
|
||||
/// A whole-buffer change makes the entry a fallback: the next request
|
||||
/// resolves from the new text if it parses, and keeps the old preset
|
||||
/// only if it does not. A partial edit leaves the entry alone.
|
||||
#[test]
|
||||
fn a_whole_buffer_replacement_resolves_again_when_it_can() {
|
||||
let lucisv =
|
||||
"module m (input logic a, output logic b);\n sub u_sub (.a(a), .b(b));\nendmodule\n";
|
||||
let (ws, uri) = open(lucisv);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let mut styles = AutoStyles::default();
|
||||
styles.remember(&uri, style::GOOGLE);
|
||||
let edit: TextDocumentContentChangeEvent =
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"range": { "start": { "line": 1, "character": 0 }, "end": { "line": 1, "character": 2 } },
|
||||
"text": " " })).expect("change");
|
||||
styles.changed(&uri, &[edit], lucisv);
|
||||
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::GOOGLE, "a partial edit");
|
||||
let whole: TextDocumentContentChangeEvent =
|
||||
serde_json::from_value(serde_json::json!({ "text": lucisv })).expect("change");
|
||||
styles.changed(&uri, std::slice::from_ref(&whole), lucisv);
|
||||
assert_eq!(styles.recall(&uri), Some((style::GOOGLE, true)));
|
||||
assert_eq!(styles.concrete(&uri, doc, auto()).style, style::LUCISV, "resolved afresh");
|
||||
assert_eq!(styles.recall(&uri), Some((style::LUCISV, false)));
|
||||
// A full range from the top counts as a whole replacement too.
|
||||
let ranged: TextDocumentContentChangeEvent =
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"range": { "start": { "line": 0, "character": 0 }, "end": { "line": 3, "character": 0 } },
|
||||
"text": lucisv })).expect("change");
|
||||
styles.changed(&uri, &[ranged], lucisv);
|
||||
assert_eq!(styles.recall(&uri), Some((style::LUCISV, true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_style_request_forgets_the_document() {
|
||||
let (ws, uri) = open(GOOGLE);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let mut styles = AutoStyles::default();
|
||||
styles.remember(&uri, style::GOOGLE);
|
||||
styles.concrete(&uri, doc, Config::styled(style::LUCISV));
|
||||
assert_eq!(styles.recall(&uri), None, "a range under a named style");
|
||||
styles.remember(&uri, style::GOOGLE);
|
||||
let _ = styles.format_document(&uri, doc, &Config::styled(style::LUCISV));
|
||||
assert_eq!(styles.recall(&uri), None, "a whole-document format under a named style");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
//! Tiers 2 and 3: what the buffer being typed in declares, and the words it
|
||||
//! uses (TODO §68.1, `completion-ux`).
|
||||
//!
|
||||
//! The current file first: a name this buffer declares anywhere — in another
|
||||
//! module, a sibling block, a function three screens down — and then a word
|
||||
//! it merely uses, both ahead of what other files declare and ahead of the
|
||||
//! templates and keywords. Both are read from the buffer's own `Semantics`
|
||||
//! and token stream, recomputed on every change, so an unsaved declaration
|
||||
//! ranks as soon as it is typed. Tier 1 (the scope chain) still comes first:
|
||||
//! what is visible at the cursor is a better answer than what is merely in
|
||||
//! the file.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use lsp_types::CompletionItemKind;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_semantic::Symbol;
|
||||
|
||||
use super::word::Word;
|
||||
use super::{completion_kind, declaration_detail, Items, TIER_BUFFER_WORD, TIER_DECLARED};
|
||||
use crate::candidates::{rank_cmp, starts_with_ignore_case, Query};
|
||||
use crate::state::Document;
|
||||
|
||||
/// Tier 2: every declaration in the buffer, whatever scope holds it.
|
||||
pub(super) fn declared_tier(items: &mut Items, doc: &Document, word: &Word, fuzzy: Option<&Query>) {
|
||||
let symbols: Vec<&Symbol> = doc.semantics.symbols().iter().collect();
|
||||
for symbol in matching(symbols, |symbol| symbol.name.as_str(), word, fuzzy) {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(
|
||||
&symbol.name,
|
||||
completion_kind(symbol.kind),
|
||||
TIER_DECLARED,
|
||||
declaration_detail(doc, symbol),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Tier 3: every identifier the buffer's token stream holds, except the one
|
||||
/// being typed — offering the user their own half-word back is noise.
|
||||
pub(super) fn buffer_word_tier(
|
||||
items: &mut Items,
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
fuzzy: Option<&Query>,
|
||||
) {
|
||||
if items.full() {
|
||||
return;
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
let words: Vec<&str> =
|
||||
buffer_words(doc, word.start).filter(|name| seen.insert(*name)).collect();
|
||||
for name in matching(words, |name| name, word, fuzzy) {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(name, CompletionItemKind::TEXT, TIER_BUFFER_WORD, "used in this file".into());
|
||||
}
|
||||
}
|
||||
|
||||
/// The candidates `word` reaches, in the order they are offered: by prefix
|
||||
/// below the fuzzy floor (in the buffer's own order), ranked by subsequence
|
||||
/// score from it up — the house rule every tier applies.
|
||||
fn matching<'a, T: Copy + 'a>(
|
||||
candidates: Vec<T>,
|
||||
name: impl Fn(T) -> &'a str,
|
||||
word: &Word,
|
||||
fuzzy: Option<&Query>,
|
||||
) -> Vec<T> {
|
||||
match fuzzy {
|
||||
None => candidates
|
||||
.into_iter()
|
||||
.filter(|c| starts_with_ignore_case(name(*c), &word.text))
|
||||
.collect(),
|
||||
Some(query) => {
|
||||
let mut hits: Vec<(T, _)> =
|
||||
candidates.into_iter().filter_map(|c| Some((c, query.score(name(c))?))).collect();
|
||||
hits.sort_by(|a, b| rank_cmp((name(a.0), a.1), (name(b.0), b.1)));
|
||||
hits.into_iter().map(|(c, _)| c).collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every identifier the buffer holds, as the project-word tier counts one —
|
||||
/// `Ident` and `SystemIdent` only, neither a macro usage nor an escaped
|
||||
/// identifier — but not the token starting at `typing`, the word under the
|
||||
/// cursor.
|
||||
fn buffer_words(doc: &Document, typing: u32) -> impl Iterator<Item = &str> {
|
||||
doc.tokens
|
||||
.iter()
|
||||
.filter(move |token| token.span.start != typing)
|
||||
.filter(|token| matches!(token.kind, TokenKind::Ident | TokenKind::SystemIdent))
|
||||
.map(|token| token.text.as_str())
|
||||
.filter(|text| !text.starts_with('`') && !text.starts_with('\\'))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::completion::harness::*;
|
||||
use crate::completion::*;
|
||||
|
||||
const TOP: &str = "\
|
||||
module top;
|
||||
logic data_q;
|
||||
always_comb begin
|
||||
da
|
||||
end
|
||||
endmodule
|
||||
module other;
|
||||
logic data_other;
|
||||
assign data_word = 1;
|
||||
always_comb al_used = 0;
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn this_files_declarations_and_words_rank_after_the_scope_and_before_other_files() {
|
||||
let (_tree, ws, uri, position) = asking("bufferrank", TOP, " da");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let tier_of = |label: &str| tier(find(&items, label).unwrap_or_else(|| panic!("{label}")));
|
||||
assert_eq!(tier_of("data_q"), TIER_SCOPE, "visible at the cursor");
|
||||
assert_eq!(tier_of("data_other"), TIER_DECLARED, "declared in another module of this file");
|
||||
assert_eq!(tier_of("data_word"), TIER_BUFFER_WORD, "only used in this file");
|
||||
assert_eq!(tier_of("data"), TIER_INDEX, "a port only `sub.sv` declares");
|
||||
assert!(TIER_SCOPE < TIER_DECLARED && TIER_DECLARED < TIER_BUFFER_WORD);
|
||||
assert!(TIER_BUFFER_WORD < TIER_INDEX && TIER_INDEX < TIER_TEMPLATE);
|
||||
assert!(TIER_TEMPLATE < TIER_KEYWORD && TIER_KEYWORD < TIER_WORD);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_word_this_file_uses_sorts_ahead_of_the_keywords() {
|
||||
let top = TOP.replace(" da\n", " al\n");
|
||||
let (_tree, ws, uri, position) = asking("bufferkw", &top, " al");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let sort = |label: &str| {
|
||||
find(&items, label)
|
||||
.and_then(|i| i.sort_text.clone())
|
||||
.unwrap_or_else(|| panic!("{label}"))
|
||||
};
|
||||
assert!(sort("al_used") < sort("always"), "{items:#?}");
|
||||
assert!(sort("al_used") < sort("always_ff"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
//! What a connection-list entry inserts (TODO §68.1, `completion-ux`).
|
||||
//!
|
||||
//! After the `.` of `sub u_sub (.cl|` or `sub #(.WI|`, accepting a port or a
|
||||
//! parameter writes the whole entry — `.clk(|)` with the cursor inside the
|
||||
//! parentheses — rather than the bare name. When the instantiating scope can
|
||||
//! see a net, variable or port of the same name (a parameter, for the
|
||||
//! parameter list), it is pre-filled as the placeholder: `.clk(${1:clk})`,
|
||||
//! one Tab to keep it, one keystroke to replace it.
|
||||
//!
|
||||
//! The bare name stays the answer where the snippet would be wrong: a client
|
||||
//! that never said it reads snippets, a `(` already written after the word
|
||||
//! being replaced (re-editing `.clk(x)`'s name), and a name the snippet
|
||||
//! grammar would have to escape (an escaped identifier).
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use vlog_semantic::SymbolKind;
|
||||
|
||||
use super::snippet_hole;
|
||||
use super::tiers::visible_symbols;
|
||||
use super::word::Word;
|
||||
use crate::signature;
|
||||
use crate::state::Document;
|
||||
|
||||
/// A connection-list entry, beyond its name.
|
||||
pub(super) struct Connection {
|
||||
/// Whether the list already connects this port elsewhere — it sorts after
|
||||
/// the rest and is marked `connected`.
|
||||
pub(super) connected: bool,
|
||||
/// The snippet accepting it writes, or `None` for the bare name.
|
||||
pub(super) snippet: Option<String>,
|
||||
}
|
||||
|
||||
/// Everything about the cursor's entry that every candidate's insertion
|
||||
/// shares: whether to write the parentheses, and the names a placeholder may
|
||||
/// be pre-filled with.
|
||||
pub(super) struct EntrySite<'a> {
|
||||
wrap: bool,
|
||||
visible: HashSet<&'a str>,
|
||||
}
|
||||
|
||||
impl<'a> EntrySite<'a> {
|
||||
/// The entry being typed at `word`, in a list of `kind`.
|
||||
pub(super) fn new(
|
||||
doc: &'a Document,
|
||||
word: &Word,
|
||||
kind: signature::Kind,
|
||||
snippets: bool,
|
||||
) -> EntrySite<'a> {
|
||||
let wrap = snippets && !paren_follows(&doc.text, word.start);
|
||||
let admits = |symbol_kind: SymbolKind| match kind {
|
||||
signature::Kind::Ports => {
|
||||
matches!(symbol_kind, SymbolKind::Net | SymbolKind::Var | SymbolKind::Port)
|
||||
}
|
||||
signature::Kind::Params => {
|
||||
matches!(symbol_kind, SymbolKind::Param | SymbolKind::LocalParam)
|
||||
}
|
||||
};
|
||||
let visible = match wrap {
|
||||
true => visible_symbols(&doc.semantics, word.start)
|
||||
.into_iter()
|
||||
.filter(|symbol| admits(symbol.kind))
|
||||
.map(|symbol| symbol.name.as_str())
|
||||
.collect(),
|
||||
false => HashSet::new(),
|
||||
};
|
||||
EntrySite { wrap, visible }
|
||||
}
|
||||
|
||||
/// The entry for the port or parameter `name`.
|
||||
pub(super) fn connection(&self, name: &str, connected: bool) -> Connection {
|
||||
let plain = name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
|
||||
let snippet = (self.wrap && plain).then(|| {
|
||||
let fill = if self.visible.contains(name) { name } else { "" };
|
||||
format!("{name}({})", snippet_hole(1, fill))
|
||||
});
|
||||
Connection { connected, snippet }
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a `(` follows the identifier run that starts at `start`, past any
|
||||
/// spaces or tabs — the entry is already written and only its name is being
|
||||
/// re-edited.
|
||||
fn paren_follows(text: &str, start: u32) -> bool {
|
||||
let Some(rest) = text.get(start as usize..) else { return false };
|
||||
let rest = rest.trim_start_matches(|c: char| c.is_ascii_alphanumeric() || c == '_' || c == '$');
|
||||
rest.trim_start_matches([' ', '\t']).starts_with('(')
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_paren_after_the_word_means_the_entry_is_already_written() {
|
||||
assert!(paren_follows(".clk(x)", 1));
|
||||
assert!(paren_follows(".cl (x)", 1));
|
||||
assert!(!paren_follows(".cl", 1));
|
||||
assert!(!paren_follows(".cl\n (x)", 1), "only on the same line");
|
||||
assert!(!paren_follows(".cl, .b(x)", 1));
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ use lsp_types::CompletionResponse;
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_semantic::{MemberSite, Semantics, Surface, SymbolKind, WorkspaceIndex};
|
||||
|
||||
use super::connection::{self, Connection};
|
||||
use super::site::balanced;
|
||||
use super::tiers::innermost_scope;
|
||||
use super::word::{Sep, Word};
|
||||
@@ -54,6 +55,7 @@ pub(super) fn member_answer(
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
offset: u32,
|
||||
snippets: bool,
|
||||
) -> Option<CompletionResponse> {
|
||||
let members = match word.spine.as_ref() {
|
||||
Some(spine) => {
|
||||
@@ -69,7 +71,7 @@ pub(super) fn member_answer(
|
||||
// question, and it is the commonest completion position in RTL there
|
||||
// is: a `.` opening a connection or a parameter override.
|
||||
None => match word.sep? {
|
||||
Sep::Dot => connection_members(ws, doc, word)?,
|
||||
Sep::Dot => connection_members(ws, doc, word, snippets)?,
|
||||
Sep::Scope => return None,
|
||||
},
|
||||
};
|
||||
@@ -77,7 +79,7 @@ pub(super) fn member_answer(
|
||||
// Prefix below [`FUZZY_MIN`], subsequence from it up — the house rule, on
|
||||
// the same `Query` every other tier scores with.
|
||||
let fuzzy = (word.text.len() >= FUZZY_MIN).then(|| Query::new(&word.text));
|
||||
let matched: Vec<Member> = match &fuzzy {
|
||||
let mut matched: Vec<Member> = match &fuzzy {
|
||||
None => members
|
||||
.into_iter()
|
||||
.filter(|member| starts_with_ignore_case(&member.name, &word.text))
|
||||
@@ -95,12 +97,20 @@ pub(super) fn member_answer(
|
||||
}
|
||||
};
|
||||
|
||||
// A connection list's already-connected ports go after the rest, each
|
||||
// group in the order it was matched in (`completion-ux`, TODO §68.1).
|
||||
matched.sort_by_key(|member| member.connection.as_ref().is_some_and(|c| c.connected));
|
||||
|
||||
let mut items = Items::new(doc, word.range(offset));
|
||||
for member in matched {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(&member.name, completion_kind(member.kind), TIER_MEMBER, member.detail);
|
||||
let kind = completion_kind(member.kind);
|
||||
match member.connection {
|
||||
Some(connection) => items.connection(&member.name, kind, member.detail, connection),
|
||||
None => items.simple(&member.name, kind, TIER_MEMBER, member.detail),
|
||||
}
|
||||
}
|
||||
// **The `isIncomplete` trap, in its member form.** The request that
|
||||
// matters is the one the trigger character fires, with nothing typed
|
||||
@@ -132,6 +142,9 @@ struct Member {
|
||||
name: String,
|
||||
kind: SymbolKind,
|
||||
detail: String,
|
||||
/// What a connection list's entry carries beyond its name; `None` for
|
||||
/// every other member.
|
||||
connection: Option<Connection>,
|
||||
}
|
||||
|
||||
/// What a member declared **in another file** shows beside its name.
|
||||
@@ -225,10 +238,17 @@ fn members_at(
|
||||
/// list to what may legally be written; it never offers a name the
|
||||
/// resolution could not find.
|
||||
///
|
||||
/// Ports already connected earlier in the same list are dropped. `None` — no
|
||||
/// Ports already connected elsewhere in the same list stay on offer, marked
|
||||
/// (`completion-ux`, 2026-11-17 — they used to be dropped), and every entry
|
||||
/// carries the `.name($1)` snippet [`connection::entry`] spells. `None` — no
|
||||
/// popup — when the cursor is not in such a list at all, or is inside a
|
||||
/// connected *expression* (`.clk(` opens a paren of its own).
|
||||
fn connection_members(ws: &Workspace, doc: &Document, word: &Word) -> Option<Vec<Member>> {
|
||||
fn connection_members(
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
snippets: bool,
|
||||
) -> Option<Vec<Member>> {
|
||||
let dot = word.start.checked_sub(1)?;
|
||||
let list = signature::enclosing_list(&doc.tokens, word.start)?;
|
||||
let open = doc.tokens.get(list.open)?.span.end;
|
||||
@@ -250,27 +270,33 @@ fn connection_members(ws: &Workspace, doc: &Document, word: &Word) -> Option<Vec
|
||||
signature::Kind::Ports => SymbolKind::Port,
|
||||
};
|
||||
let taken = connected_names(&doc.tokens, list.open, dot);
|
||||
let entry = connection::EntrySite::new(doc, word, list.kind, snippets);
|
||||
let mut members = Members::new();
|
||||
let mut push = |name: &str, kind: SymbolKind, detail: String| {
|
||||
let connection = entry.connection(name, taken.contains(name));
|
||||
members.push_member(Member {
|
||||
name: name.to_string(),
|
||||
kind,
|
||||
detail,
|
||||
connection: Some(connection),
|
||||
});
|
||||
};
|
||||
match doc.semantics.instantiable_scope(&list.module) {
|
||||
// This file declares the module: its own scope is the whole answer,
|
||||
// and no other file's module of the same name may override it.
|
||||
Some(scope) => {
|
||||
let scope = doc.semantics.scope(scope)?;
|
||||
for symbol in scope.symbols.iter().filter_map(|&id| doc.semantics.symbol(id)) {
|
||||
if symbol.kind == wanted && !taken.contains(symbol.name.as_str()) {
|
||||
members.push(&symbol.name, symbol.kind, declaration_detail(doc, symbol));
|
||||
if symbol.kind == wanted {
|
||||
push(&symbol.name, symbol.kind, declaration_detail(doc, symbol));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
for (name, defs) in ws.index().members_of(&list.module) {
|
||||
let Some(def) = defs.first() else { continue };
|
||||
if def.kind == wanted && !taken.contains(name) {
|
||||
members.push(
|
||||
name,
|
||||
def.kind,
|
||||
indexed_detail(def.kind, def.type_name.as_deref()),
|
||||
);
|
||||
if def.kind == wanted {
|
||||
push(name, def.kind, indexed_detail(def.kind, def.type_name.as_deref()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -282,12 +308,11 @@ fn connection_members(ws: &Workspace, doc: &Document, word: &Word) -> Option<Vec
|
||||
/// token at `open`, except the one whose `.` sits at `skip` — the entry being
|
||||
/// typed, which must stay on offer.
|
||||
///
|
||||
/// Dropping them is the friendlier half of a choice the other way round would
|
||||
/// be simpler: in a sixty-port instantiation the fifty-five already connected
|
||||
/// are the ones the user is *not* looking for, and a popup that keeps offering
|
||||
/// them is a popup they scroll past. It cannot mislead — a name dropped here
|
||||
/// is one the buffer already spells two lines up — and a re-edited entry is
|
||||
/// still offered, because its own dot is the one `skip` names.
|
||||
/// In a sixty-port instantiation the fifty-five already connected are the ones
|
||||
/// the user is *not* looking for, so they sort after the rest and say so; they
|
||||
/// are not dropped (`completion-ux`, 2026-11-17), because a port connected
|
||||
/// twice by mistake is exactly the one a user goes looking for. A re-edited
|
||||
/// entry is not marked, because its own dot is the one `skip` names.
|
||||
fn connected_names(tokens: &[Token], open: usize, skip: u32) -> HashSet<&str> {
|
||||
let mut taken = HashSet::new();
|
||||
let mut depth = 0i32;
|
||||
@@ -328,8 +353,12 @@ impl Members {
|
||||
}
|
||||
|
||||
fn push(&mut self, name: &str, kind: SymbolKind, detail: String) {
|
||||
if self.seen.insert(name.to_string()) {
|
||||
self.out.push(Member { name: name.to_string(), kind, detail });
|
||||
self.push_member(Member { name: name.to_string(), kind, detail, connection: None });
|
||||
}
|
||||
|
||||
fn push_member(&mut self, member: Member) {
|
||||
if self.seen.insert(member.name.clone()) {
|
||||
self.out.push(member);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -823,28 +852,55 @@ endmodule
|
||||
assert_eq!(wiring_labels("conn_typed", ".cl"), vec!["clk"]);
|
||||
}
|
||||
|
||||
/// The answer against [`WIRING`] in the order the client shows it — by
|
||||
/// `sortText` — as `(label, marked connected)` pairs.
|
||||
fn wiring_order(name: &str, hole: &str) -> Vec<(String, bool)> {
|
||||
let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n"));
|
||||
let (_tree, ws, uri, position) = opened(Tree::new(name), &top, hole);
|
||||
let mut found = items(completions(&ws, &uri, position, true));
|
||||
found.sort_by(|a, b| a.sort_text.cmp(&b.sort_text));
|
||||
found
|
||||
.into_iter()
|
||||
.map(|item| {
|
||||
let marked = item
|
||||
.label_details
|
||||
.as_ref()
|
||||
.and_then(|d| d.description.as_deref())
|
||||
.is_some_and(|d| d == "connected");
|
||||
(item.label, marked)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn pairs(list: &[(&str, bool)]) -> Vec<(String, bool)> {
|
||||
list.iter().map(|(name, marked)| (name.to_string(), *marked)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_connection_list_answers_after_a_comma_and_across_a_newline() {
|
||||
assert_eq!(wiring_labels("comma", ".clk(clk), ."), vec!["data", "ready"]);
|
||||
let expected = pairs(&[("data", false), ("ready", false), ("clk", true)]);
|
||||
assert_eq!(wiring_order("comma", ".clk(clk), ."), expected);
|
||||
assert_eq!(
|
||||
wiring_labels("newline", ".clk(clk),\n ."),
|
||||
vec!["data", "ready"],
|
||||
wiring_order("newline", ".clk(clk),\n ."),
|
||||
expected,
|
||||
"an indented continuation line is the ordinary way this is written",
|
||||
);
|
||||
}
|
||||
|
||||
/// Already-connected ports are dropped: in a sixty-port instantiation the
|
||||
/// ones still to wire are the whole of what the user is looking for.
|
||||
/// Already-connected ports sort after the ones still to wire and say so
|
||||
/// (`completion-ux`, 2026-11-17 — they used to be dropped): in a
|
||||
/// sixty-port instantiation the ones still to wire are what the user is
|
||||
/// looking for, but a port connected twice by mistake is findable.
|
||||
#[test]
|
||||
fn a_port_already_connected_is_not_offered_again() {
|
||||
fn a_port_already_connected_is_offered_last_and_marked() {
|
||||
assert_eq!(
|
||||
wiring_labels("taken", ".clk(clk), .data(d), ."),
|
||||
vec!["ready"],
|
||||
"two written, one left",
|
||||
wiring_order("taken", ".clk(clk), .data(d), ."),
|
||||
pairs(&[("ready", false), ("clk", true), ("data", true)]),
|
||||
"two written, one left, and the two after it",
|
||||
);
|
||||
// …and the entry being *re-typed* is still offered, because the dot
|
||||
// the cursor follows is the one that is skipped.
|
||||
assert_eq!(wiring_labels("retype", ".clk(clk), .data(d), .re"), vec!["ready"]);
|
||||
// …and the entry being *re-typed* is not marked, because the dot the
|
||||
// cursor follows is the one that is skipped.
|
||||
assert_eq!(wiring_order("retype", ".clk(clk), .data(d), .re"), pairs(&[("ready", false)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -945,17 +1001,21 @@ endmodule
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_item_inserts_the_bare_name_and_shows_its_declaration() {
|
||||
fn a_port_item_writes_the_whole_entry_and_shows_its_declaration() {
|
||||
let top = WIRING.replace(" HOLE\n", " .\n");
|
||||
let tree = Tree::new("portitem");
|
||||
let (_tree, ws, uri, position) = opened(tree, &top, " .");
|
||||
let answer = items(completions(&ws, &uri, position, true));
|
||||
let data = find(&answer, "data").expect("the port");
|
||||
assert_eq!(data.kind, Some(CompletionItemKind::FIELD));
|
||||
// The user types the `(` themselves; inventing it would be guessing
|
||||
// at what is connected.
|
||||
assert_eq!(inserted(data), "data");
|
||||
assert_eq!(data.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
|
||||
// `.data(|)`: the parentheses come with it, the cursor inside
|
||||
// (`completion-ux`, 2026-11-17). Nothing named `data` is visible in
|
||||
// `wiring_top`, so the placeholder is empty…
|
||||
assert_eq!(inserted(data), "data(${1})");
|
||||
assert_eq!(data.insert_text_format, Some(InsertTextFormat::SNIPPET));
|
||||
// …while `clk` is, so it is pre-filled.
|
||||
let clk = find(&answer, "clk").expect("the clock");
|
||||
assert_eq!(inserted(clk), "clk(${1:clk})");
|
||||
// The declaration line carries the direction and the width, which is
|
||||
// the whole of what a connection list needs to know.
|
||||
assert_eq!(data.detail.as_deref(), Some("input logic [WIDTH-1:0] data,"));
|
||||
@@ -965,6 +1025,33 @@ endmodule
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_item_is_the_bare_name_where_a_snippet_would_be_wrong() {
|
||||
// A `(` already after the word: only the name is being re-edited.
|
||||
let top = WIRING.replace(" HOLE\n", " .da(d)\n");
|
||||
let (_tree, ws, uri, position) = opened(Tree::new("portparen"), &top, " .da");
|
||||
let answer = items(completions(&ws, &uri, position, true));
|
||||
assert_eq!(inserted(find(&answer, "data").expect("the port")), "data");
|
||||
// A client without snippet support gets the name, as before.
|
||||
let top = WIRING.replace(" HOLE\n", " .\n");
|
||||
let (_tree, ws, uri, position) = opened(Tree::new("portplain"), &top, " .");
|
||||
let answer = items(completions(&ws, &uri, position, false));
|
||||
let data = find(&answer, "data").expect("the port");
|
||||
assert_eq!(inserted(data), "data");
|
||||
assert_eq!(data.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_item_is_pre_filled_from_a_visible_parameter() {
|
||||
let top = WIRING
|
||||
.replace("module wiring_top;\n", "module wiring_top;\n localparam int WIDTH = 16;\n")
|
||||
.replace("wiring_sub u_sub (", "wiring_sub #(.) u_sub (");
|
||||
let (_tree, ws, uri, position) = opened(Tree::new("paramfill"), &top, "#(.");
|
||||
let answer = items(completions(&ws, &uri, position, true));
|
||||
assert_eq!(inserted(find(&answer, "WIDTH").expect("the parameter")), "WIDTH(${1:WIDTH})");
|
||||
assert_eq!(inserted(find(&answer, "DEPTH").expect("the other")), "DEPTH(${1})");
|
||||
}
|
||||
|
||||
/// A **non-ANSI** port list writes its directions in the module body, so
|
||||
/// the header alone names the ports and the body types them. Both halves
|
||||
/// bind a `Port`, so the list is the same.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! `textDocument/completion` — module hinting, templates, keywords, and every
|
||||
//! name the project uses.
|
||||
//!
|
||||
//! One response, six tiers, ordered by `sortText`:
|
||||
//! One response, eight tiers, ordered by `sortText`:
|
||||
//!
|
||||
//! 0. **module names** — at module-item position only, every module the
|
||||
//! workspace declares whose name contains what is typed. The item inserts
|
||||
@@ -10,12 +10,15 @@
|
||||
//! 2026-08-30);
|
||||
//! 1. **what is visible here** — the declarations the scope chain at the
|
||||
//! cursor binds, from this file's `Semantics`;
|
||||
//! 2. **what the project declares** — packages, their members, typedefs,
|
||||
//! 2. **what this file declares** — every declaration in the buffer, in any
|
||||
//! scope (`buffer.rs`, `completion-ux` 2026-11-17);
|
||||
//! 3. **what this file uses** — every identifier its token stream holds;
|
||||
//! 4. **what the project declares** — packages, their members, typedefs,
|
||||
//! classes, modules and `` `define`` names, from the workspace index;
|
||||
//! 3. **templates** — `if`/`case`/`always_ff`/declaration skeletons with
|
||||
//! 5. **templates** — `if`/`case`/`always_ff`/declaration skeletons with
|
||||
//! tabstops, offered only where the construct may be written;
|
||||
//! 4. **keywords** — every reserved word `vlog_parser` knows;
|
||||
//! 5. **project words** — every identifier the in-scope files' *token
|
||||
//! 6. **keywords** — every reserved word `vlog_parser` knows;
|
||||
//! 7. **project words** — every identifier the in-scope files' *token
|
||||
//! streams* contain, the rope/VS Code word-completion tier.
|
||||
//!
|
||||
//! A name is offered once, by the highest tier that claims it. Nothing is
|
||||
@@ -47,8 +50,9 @@
|
||||
//! list included;
|
||||
//! * `module` — tier 0, and the instantiation planning `inline.rs` and
|
||||
//! `instantiate.rs` share;
|
||||
//! * `tiers` — tiers 1 to 5, the five ordinary tiers in the order they fill
|
||||
//! the response.
|
||||
//! * `buffer` — tiers 2 and 3, the current file's declarations and words;
|
||||
//! * `tiers` — the other ordinary tiers, in the order they fill the
|
||||
//! response.
|
||||
//!
|
||||
//! Functions a sibling file calls are `pub(super)`; the four `pub(crate)`
|
||||
//! entry points other modules of the crate use keep their paths through the
|
||||
@@ -58,9 +62,9 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use lsp_types::{
|
||||
CompletionItem, CompletionItemKind, CompletionList, CompletionResponse, CompletionTextEdit,
|
||||
Documentation, InsertTextFormat, InsertTextMode, MarkupContent, MarkupKind, Position, Range,
|
||||
TextEdit, Uri,
|
||||
CompletionItem, CompletionItemKind, CompletionItemLabelDetails, CompletionList,
|
||||
CompletionResponse, CompletionTextEdit, Documentation, InsertTextFormat, InsertTextMode,
|
||||
MarkupContent, MarkupKind, Position, Range, TextEdit, Uri,
|
||||
};
|
||||
use vlog_parser::token::{Comment, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
@@ -71,6 +75,8 @@ use crate::candidates::Query;
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::symbols::kind_label;
|
||||
use crate::templates::Template;
|
||||
use buffer::{buffer_word_tier, declared_tier};
|
||||
use connection::Connection;
|
||||
use member::member_answer;
|
||||
use module::module_tier;
|
||||
use site::{at_module_item, at_statement, enclosing_scopes};
|
||||
@@ -85,6 +91,8 @@ pub(crate) use module::module_header;
|
||||
pub(crate) use site::at_instantiation_site;
|
||||
pub(crate) use tiers::layout_at;
|
||||
|
||||
mod buffer;
|
||||
mod connection;
|
||||
#[cfg(test)]
|
||||
mod harness;
|
||||
mod member;
|
||||
@@ -134,11 +142,19 @@ const TIER_MODULE: char = '0';
|
||||
/// would say there is a ranking against the other tiers to express, and there
|
||||
/// is not.
|
||||
const TIER_MEMBER: char = '0';
|
||||
/// A connection list's already-connected ports: after every port still to
|
||||
/// connect, inside the same exclusive answer (`completion-ux`).
|
||||
const TIER_CONNECTED: char = '1';
|
||||
const TIER_SCOPE: char = '1';
|
||||
const TIER_INDEX: char = '2';
|
||||
const TIER_TEMPLATE: char = '3';
|
||||
const TIER_KEYWORD: char = '4';
|
||||
const TIER_WORD: char = '5';
|
||||
/// What this buffer declares anywhere, and then the words it uses — the
|
||||
/// current file ahead of every other file and of the templates and keywords
|
||||
/// (`completion-ux`, TODO §68.1).
|
||||
const TIER_DECLARED: char = '2';
|
||||
const TIER_BUFFER_WORD: char = '3';
|
||||
const TIER_INDEX: char = '4';
|
||||
const TIER_TEMPLATE: char = '5';
|
||||
const TIER_KEYWORD: char = '6';
|
||||
const TIER_WORD: char = '7';
|
||||
|
||||
/// What a multi-line item tells the client about its own whitespace.
|
||||
///
|
||||
@@ -203,7 +219,7 @@ pub fn completions(
|
||||
// A `.` or a `::` admits exactly one kind of name too — a member of what
|
||||
// stands before it — so the answer is only those. See [`member_answer`].
|
||||
if word.sep.is_some() {
|
||||
return member_answer(ws, doc, &word, offset);
|
||||
return member_answer(ws, doc, &word, offset, snippets);
|
||||
}
|
||||
|
||||
// Both position gates read the same scope chain, and neither can be true
|
||||
@@ -225,10 +241,12 @@ pub fn completions(
|
||||
let mut items = Items::new(doc, word.range(offset));
|
||||
module_tier(&mut items, ws, doc, &word, at_item);
|
||||
scope_tier(&mut items, doc, &word, fuzzy.as_ref());
|
||||
declared_tier(&mut items, doc, &word, fuzzy.as_ref());
|
||||
buffer_word_tier(&mut items, doc, &word, fuzzy.as_ref());
|
||||
index_tier(&mut items, ws, &word, fuzzy.as_ref());
|
||||
template_tier(&mut items, ws, doc, &word, snippets, at_item, at_statement);
|
||||
keyword_tier(&mut items, &word);
|
||||
word_tier(&mut items, ws, doc, &word, fuzzy.as_ref());
|
||||
word_tier(&mut items, ws, &word, fuzzy.as_ref());
|
||||
// **The `isIncomplete` trap.** VS Code asks the server again on the next
|
||||
// keystroke *only* when the last answer said it was incomplete; otherwise
|
||||
// it filters the list it already holds. A complete two-character prefix
|
||||
@@ -307,13 +325,54 @@ impl Items {
|
||||
self.push(item);
|
||||
}
|
||||
|
||||
/// A port or parameter after a connection list's `.`: the bare name, or
|
||||
/// the `name($1)` entry when the connection carries one, and a dimmed
|
||||
/// `connected` beside the label when the list already connects it.
|
||||
fn connection(
|
||||
&mut self,
|
||||
name: &str,
|
||||
kind: CompletionItemKind,
|
||||
detail: String,
|
||||
connection: Connection,
|
||||
) {
|
||||
if self.full() || self.seen.contains(name) {
|
||||
return;
|
||||
}
|
||||
let tier = if connection.connected { TIER_CONNECTED } else { TIER_MEMBER };
|
||||
let format = match connection.snippet {
|
||||
Some(_) => InsertTextFormat::SNIPPET,
|
||||
None => InsertTextFormat::PLAIN_TEXT,
|
||||
};
|
||||
let item = CompletionItem {
|
||||
label: name.to_string(),
|
||||
kind: Some(kind),
|
||||
detail: Some(detail),
|
||||
label_details: connection.connected.then(|| CompletionItemLabelDetails {
|
||||
detail: None,
|
||||
description: Some("connected".to_string()),
|
||||
}),
|
||||
sort_text: Some(format!("{tier}{name}")),
|
||||
insert_text_format: Some(format),
|
||||
text_edit: Some(CompletionTextEdit::Edit(TextEdit {
|
||||
range: self.range,
|
||||
new_text: connection.snippet.unwrap_or_else(|| name.to_string()),
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
self.push(item);
|
||||
}
|
||||
|
||||
/// One template: the skeleton it inserts, the word it is reached by, and
|
||||
/// the shape it expands to.
|
||||
///
|
||||
/// A client that never said it understands snippets gets the same text
|
||||
/// with every hole filled in rather than nothing at all — the M4 ruling,
|
||||
/// applied to a body whose defaults were chosen so that the result parses.
|
||||
fn template(&mut self, template: &Template, layout: &Layout, snippets: bool) {
|
||||
///
|
||||
/// `rank` is the template's place in the registry, which is what orders the
|
||||
/// templates among themselves: the label alone would put `always @(*)`
|
||||
/// before the clocked blocks.
|
||||
fn template(&mut self, template: &Template, rank: usize, layout: &Layout, snippets: bool) {
|
||||
if self.full() || self.seen.contains(template.label) {
|
||||
return;
|
||||
}
|
||||
@@ -329,7 +388,7 @@ impl Items {
|
||||
// types to reach the item — otherwise `if` would not match
|
||||
// `if begin/end` at all.
|
||||
filter_text: Some(template.prefix.to_string()),
|
||||
sort_text: Some(format!("{TIER_TEMPLATE}{}", template.label)),
|
||||
sort_text: Some(format!("{TIER_TEMPLATE}{rank:03}{}", template.label)),
|
||||
insert_text_format: Some(match snippets {
|
||||
true => InsertTextFormat::SNIPPET,
|
||||
false => InsertTextFormat::PLAIN_TEXT,
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use lsp_types::CompletionItemKind;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::KEYWORDS;
|
||||
use vlog_refactor::Layout;
|
||||
use vlog_semantic::{Semantics, Symbol};
|
||||
@@ -66,7 +65,7 @@ pub(super) fn scope_tier(items: &mut Items, doc: &Document, word: &Word, fuzzy:
|
||||
/// Every declaration the scope chain covering `offset` binds, innermost scope
|
||||
/// first, each name only once — the inner declaration shadows the outer one,
|
||||
/// which is the rule `vlog_semantic`'s own lookup follows.
|
||||
fn visible_symbols(semantics: &Semantics, offset: u32) -> Vec<&Symbol> {
|
||||
pub(super) fn visible_symbols(semantics: &Semantics, offset: u32) -> Vec<&Symbol> {
|
||||
let mut out = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
let mut at = innermost_scope(semantics, offset);
|
||||
@@ -158,7 +157,7 @@ pub(super) fn template_tier(
|
||||
}
|
||||
let layout = layout_at(ws, doc, word.start);
|
||||
let dialect = templates::dialect(doc.path.as_deref());
|
||||
for template in templates::for_dialect(dialect) {
|
||||
for (rank, template) in templates::for_dialect(dialect).enumerate() {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
@@ -168,7 +167,7 @@ pub(super) fn template_tier(
|
||||
if !starts_with_ignore_case(template.prefix, &word.text) {
|
||||
continue;
|
||||
}
|
||||
items.template(template, &layout, snippets);
|
||||
items.template(template, rank, &layout, snippets);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,45 +204,26 @@ pub(super) fn keyword_tier(items: &mut Items, word: &Word) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tier 5: identifiers used anywhere in the project scope.
|
||||
/// Tier 7: identifiers used anywhere in the project scope.
|
||||
///
|
||||
/// The prebuilt table is as of the last index rebuild, which is `didSave`; the
|
||||
/// buffer being typed in is harvested afresh from its own token stream, so an
|
||||
/// unsaved edit contributes to its own file's completions immediately.
|
||||
pub(super) fn word_tier(
|
||||
items: &mut Items,
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
fuzzy: Option<&Query>,
|
||||
) {
|
||||
/// The prebuilt table is as of the last index rebuild, which is `didSave`. The
|
||||
/// buffer being typed in is harvested afresh from its own token stream by
|
||||
/// tier 3 (`buffer.rs`), so an unsaved edit still contributes immediately.
|
||||
pub(super) fn word_tier(items: &mut Items, ws: &Workspace, word: &Word, fuzzy: Option<&Query>) {
|
||||
// Gathering and sorting the names is the one tier whose *setup* costs
|
||||
// something, so a response that is already full skips it outright.
|
||||
if items.full() {
|
||||
return;
|
||||
}
|
||||
// The buffer's own words were offered by tier 3 already, so only the
|
||||
// prebuilt table is read here; a name in both is offered once anyway,
|
||||
// because `Items` drops a repeated label.
|
||||
let names: Vec<&str> = match fuzzy {
|
||||
None => {
|
||||
let mut names: Vec<&str> =
|
||||
ws.candidates().words(&word.text).iter().map(String::as_str).collect();
|
||||
names
|
||||
.extend(buffer_words(doc).filter(|text| starts_with_ignore_case(text, &word.text)));
|
||||
names.sort_unstable();
|
||||
names.dedup();
|
||||
names
|
||||
}
|
||||
None => ws.candidates().words(&word.text).iter().map(String::as_str).collect(),
|
||||
Some(query) => {
|
||||
// The table's hits come back ranked; the buffer's own words are
|
||||
// scored here and the two are ranked together, so a name the user
|
||||
// typed a moment ago sits where its match deserves rather than
|
||||
// after everything the table knows.
|
||||
let mut hits = ws.candidates().words_fuzzy(query, LIMIT);
|
||||
let hits = ws.candidates().words_fuzzy(query, LIMIT);
|
||||
// A full return is a truncation; see `index_tier`.
|
||||
items.incomplete |= hits.len() >= LIMIT;
|
||||
hits.extend(buffer_words(doc).filter_map(|name| Some((name, query.score(name)?))));
|
||||
hits.sort_by(|a, b| rank_cmp(*a, *b));
|
||||
// A name in both lists is offered once: `Items` drops the second
|
||||
// by label, so no dedup is needed here.
|
||||
hits.into_iter().map(|(name, _)| name).collect()
|
||||
}
|
||||
};
|
||||
@@ -255,21 +235,6 @@ pub(super) fn word_tier(
|
||||
}
|
||||
}
|
||||
|
||||
/// Every identifier the buffer being typed in holds, as tier 5 counts one.
|
||||
///
|
||||
/// The live half of the tier: the prebuilt table is as of the last index
|
||||
/// rebuild, and this is the buffer's own token stream, recomputed on every
|
||||
/// change. The filter is `candidates::is_word`'s, in the other direction —
|
||||
/// `Ident` and `SystemIdent` only, and neither a macro usage nor an escaped
|
||||
/// identifier.
|
||||
fn buffer_words(doc: &Document) -> impl Iterator<Item = &str> {
|
||||
doc.tokens
|
||||
.iter()
|
||||
.filter(|token| matches!(token.kind, TokenKind::Ident | TokenKind::SystemIdent))
|
||||
.map(|token| token.text.as_str())
|
||||
.filter(|text| !text.starts_with('`') && !text.starts_with('\\'))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -374,7 +339,7 @@ endmodule
|
||||
let at_item = offering("alwitem", "top.sv", "module top;\n alw\nendmodule\n", " alw");
|
||||
assert_eq!(
|
||||
template_labels(&at_item),
|
||||
["always_ff @(posedge clk)", "always_ff with reset", "always_comb begin/end"],
|
||||
["always_ff with reset", "always_ff @(posedge clk)", "always_comb begin/end"],
|
||||
"and `alw` finds every one of them"
|
||||
);
|
||||
|
||||
@@ -419,7 +384,7 @@ endmodule
|
||||
let always = offering("dialectalw", "top.v", "module top;\n alw\nendmodule\n", " alw");
|
||||
assert_eq!(
|
||||
template_labels(&always),
|
||||
["always @(posedge clk)", "always @(posedge clk or negedge rst_n)", "always @(*)"],
|
||||
["always @(posedge clk or negedge rst_n)", "always @(posedge clk)", "always @(*)"],
|
||||
"and no always_ff, which a .v file's compiler would reject"
|
||||
);
|
||||
}
|
||||
@@ -637,7 +602,8 @@ endmodule
|
||||
#[test]
|
||||
fn only_what_the_scope_chain_reaches_is_in_the_semantic_tier() {
|
||||
// `inner` is declared in a block the cursor is not in, so it may only
|
||||
// arrive as a project word — never as a visible declaration.
|
||||
// arrive as one of this file's declarations (tier 2, `completion-ux`)
|
||||
// — never as a visible declaration.
|
||||
let top = "\
|
||||
module top;
|
||||
initial begin : b
|
||||
@@ -650,8 +616,8 @@ endmodule
|
||||
";
|
||||
let (_tree, ws, uri, position) = asking("scopewalk", top, "x = inner");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let item = find(&items, "inner_only").expect("known as a word at least");
|
||||
assert_eq!(tier(item), TIER_WORD, "{item:#?}");
|
||||
let item = find(&items, "inner_only").expect("known as a declaration at least");
|
||||
assert_eq!(tier(item), TIER_DECLARED, "{item:#?}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -750,12 +716,13 @@ endmodule
|
||||
fn the_short_answers_are_what_they_always_were() {
|
||||
let (_tree, mut ws, uri) = typing("fuzzygolden");
|
||||
for (typed, expected) in [
|
||||
// `c` itself is in the list because the buffer being typed in
|
||||
// holds it as an `Ident` token — behaviour this round did not
|
||||
// touch, pinned here because a golden that quietly lost it would
|
||||
// be a change.
|
||||
("c", vec!["c", "c_l_k_scatter", "celsius", "clk_osc_en_q"]),
|
||||
("ce", vec!["ce", "celsius"]),
|
||||
// `c` itself used to be in the list, because the buffer being
|
||||
// typed in holds it as an `Ident` token. `completion-ux`
|
||||
// (2026-11-17) dropped it on purpose: the buffer-word tier skips
|
||||
// the token under the cursor, and offering the user their own
|
||||
// half-word back is noise.
|
||||
("c", vec!["c_l_k_scatter", "celsius", "clk_osc_en_q"]),
|
||||
("ce", vec!["celsius"]),
|
||||
] {
|
||||
let found = items(after_typing(&mut ws, &uri, typed));
|
||||
let named: Vec<&str> = found
|
||||
|
||||
@@ -708,10 +708,19 @@ mod tests {
|
||||
/// therefore in `includers()`/`include_sources()` — the narrowing must not
|
||||
/// accidentally depend on the include's target spelling matching the
|
||||
/// disk's.
|
||||
///
|
||||
/// Only a case-insensitive filesystem (macOS, Windows by default) resolves
|
||||
/// the mismatched spelling at all; on a case-sensitive one (Linux) there
|
||||
/// is no include to narrow in, so the test checks which it is on and stops
|
||||
/// there, saying so.
|
||||
#[test]
|
||||
fn a_case_mismatched_include_spelling_still_narrows_in_and_rewrites() {
|
||||
let tree = Tree::new("case_mismatch");
|
||||
tree.write("rtl/defs.svh", "`define W 8\n");
|
||||
if !tree.path.join("rtl/DEFS.svh").is_file() {
|
||||
eprintln!("skipped: this filesystem is case-sensitive; `DEFS.svh` names no file");
|
||||
return;
|
||||
}
|
||||
let top = tree.write("rtl/top.sv", "`include \"DEFS.svh\"\nmodule t;\nendmodule\n");
|
||||
tree.write("files.f", "rtl/top.sv\nrtl/defs.svh\n");
|
||||
let ws = tree.workspace();
|
||||
|
||||
@@ -4,7 +4,17 @@
|
||||
//! `pairs::analyze` already computes for the rainbow and the missing-closer
|
||||
//! warnings, or a block comment, which the lexer already attached as trivia.
|
||||
//! This module is the fourth consumer of the first and the second of the
|
||||
//! second. See `docs/features/references-nav/README.md`.
|
||||
//! second. See `docs/features/references-nav/README.md`. The third source,
|
||||
//! the branches of `` `ifdef `` regions, is [`directives`]
|
||||
//! (`docs/features/ifdef-folding/README.md`).
|
||||
|
||||
mod directives;
|
||||
#[cfg(test)]
|
||||
mod ifdef_tests;
|
||||
#[cfg(test)]
|
||||
mod opentitan_sweep;
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use lsp_types::{FoldingRange, FoldingRangeKind};
|
||||
use vlog_parser::token::Comment;
|
||||
@@ -13,8 +23,9 @@ use vlog_parser::TextRange;
|
||||
use crate::pairs::analyze;
|
||||
use crate::state::Document;
|
||||
|
||||
/// Every foldable region in a buffer: one per matched scope pair, plus every
|
||||
/// block comment that spans more than one line.
|
||||
/// Every foldable region in a buffer: one per matched scope pair, one per
|
||||
/// branch of a closed `` `ifdef `` region, plus every block comment that spans
|
||||
/// more than one line.
|
||||
///
|
||||
/// A keyword whose counterpart never arrived is **not** foldable — `analyze`
|
||||
/// leaves it out of `pairs`, and folding to the end of the file because an
|
||||
@@ -22,6 +33,15 @@ use crate::state::Document;
|
||||
/// off. Nothing is capped: a fold list is one range per block, and an editor
|
||||
/// that asked for it wants all of them.
|
||||
pub fn folding_ranges(doc: &Document) -> Vec<FoldingRange> {
|
||||
let scopes = scope_and_comment_folds(doc);
|
||||
let branches = branch_folds(doc, &scopes);
|
||||
in_answer_order(scopes, branches)
|
||||
}
|
||||
|
||||
/// The scope-pair and block-comment folds, exactly as they were before
|
||||
/// branch folds existed: sorted by `(start, end)`, one per pair of lines (a
|
||||
/// scope pair wins over a comment on the same two lines).
|
||||
fn scope_and_comment_folds(doc: &Document) -> Vec<FoldingRange> {
|
||||
let mut out: Vec<FoldingRange> = Vec::new();
|
||||
for pair in analyze(&doc.tokens).pairs {
|
||||
// The closing keyword's own line stays visible: LSP hides
|
||||
@@ -43,6 +63,46 @@ pub fn folding_ranges(doc: &Document) -> Vec<FoldingRange> {
|
||||
out
|
||||
}
|
||||
|
||||
/// One fold per branch of every closed `` `ifdef `` region, sorted by start
|
||||
/// line. Conditional-compilation branches follow the scope rule: the next
|
||||
/// directive's line (`else`, `endif`) stays visible. A branch whose two lines
|
||||
/// are exactly an existing fold's is left out, so that fold keeps its kind
|
||||
/// (a `/* */` opened on the directive line stays a `comment`).
|
||||
fn branch_folds(doc: &Document, existing: &[FoldingRange]) -> Vec<FoldingRange> {
|
||||
let taken: HashSet<(u32, u32)> = existing.iter().map(|r| (r.start_line, r.end_line)).collect();
|
||||
let mut out = Vec::new();
|
||||
for (start, through) in directives::branch_spans(&doc.tokens, |t| line(doc, t.span.start)) {
|
||||
if !taken.contains(&(start, through)) {
|
||||
push(&mut out, start, through, FoldingRangeKind::Region);
|
||||
}
|
||||
}
|
||||
out.sort_by_key(|range| range.start_line);
|
||||
out
|
||||
}
|
||||
|
||||
/// The one place the answer's order is defined: by start line; on a shared
|
||||
/// start line, every scope or comment fold (in their own `(start, end)`
|
||||
/// order) before any branch fold.
|
||||
///
|
||||
/// The order is load-bearing. VS Code keeps only the *first* range it
|
||||
/// receives for a start line (`sanitizeRanges`), so whatever comes first is
|
||||
/// the fold the user gets and the line sticky scroll pins. Putting existing
|
||||
/// folds first means a branch fold never costs the user a fold they had
|
||||
/// before — on `module m; `ifdef A` the `module` fold survives and the branch
|
||||
/// yields. See `docs/features/ifdef-folding/README.md`.
|
||||
fn in_answer_order(existing: Vec<FoldingRange>, branches: Vec<FoldingRange>) -> Vec<FoldingRange> {
|
||||
let mut out = Vec::with_capacity(existing.len() + branches.len());
|
||||
let mut branches = branches.into_iter().peekable();
|
||||
for range in existing {
|
||||
while let Some(branch) = branches.next_if(|b| b.start_line < range.start_line) {
|
||||
out.push(branch);
|
||||
}
|
||||
out.push(range);
|
||||
}
|
||||
out.extend(branches);
|
||||
out
|
||||
}
|
||||
|
||||
/// Add one range, unless there is nothing between its two lines to hide.
|
||||
fn push(out: &mut Vec<FoldingRange>, start_line: u32, end_line: u32, kind: FoldingRangeKind) {
|
||||
if end_line <= start_line {
|
||||
@@ -148,6 +208,39 @@ mod tests {
|
||||
assert_eq!(folds(text), vec![(0, 5, "region"), (1, 4, "region"), (2, 3, "region")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_layer_a_reader_is_inside_starts_a_fold_on_its_header_line() {
|
||||
// VS Code's sticky scroll is told (the extension's
|
||||
// `editor.stickyScroll.defaultModel`) to pin the first line of every
|
||||
// fold around the top of the viewport. So the header of each layer —
|
||||
// module, `always`, `case`, the case item, the `if` — must be a fold's
|
||||
// start line, and each fold must reach the innermost statement.
|
||||
let text = concat!(
|
||||
"module m (\n", // 0
|
||||
" input a\n", // 1
|
||||
");\n", // 2
|
||||
" always @(*) begin\n", // 3
|
||||
" case (st)\n", // 4
|
||||
" st_1: begin\n", // 5
|
||||
" if (cond_1) begin\n", // 6
|
||||
" x = 1;\n", // 7
|
||||
" y = 2;\n", // 8
|
||||
" end\n", // 9
|
||||
" end\n", // 10
|
||||
" endcase\n", // 11
|
||||
" end\n", // 12
|
||||
"endmodule\n", // 13
|
||||
);
|
||||
let ranges = folds(text);
|
||||
for header in [0, 3, 4, 5, 6] {
|
||||
let fold = ranges.iter().find(|(start, _, _)| *start == header);
|
||||
let Some((_, end, _)) = fold else {
|
||||
panic!("no fold starts on line {header}: {ranges:?}")
|
||||
};
|
||||
assert!(*end >= 8, "the fold from line {header} must cover line 8, got {ranges:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scope_that_opens_and_closes_on_one_line_folds_nothing() {
|
||||
// `end_line <= start_line` means there is no hidden line to gain.
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
//! Folding for conditional compilation: one range per branch of every
|
||||
//! `` `ifdef `` / `` `ifndef `` … `` `endif `` region.
|
||||
//!
|
||||
//! No new scan. The lexer already turns each of the five directives into one
|
||||
//! [`TokenKind::Directive`] token that runs to the end of its line, and only
|
||||
//! where they really are directives: never in a comment or a string (those are
|
||||
//! trivia and literals), never inside a `` `define `` body (the whole body,
|
||||
//! continuation lines included, is the `` `define `` token's own text). A
|
||||
//! token's first word is all this module reads.
|
||||
//! See `docs/features/ifdef-folding/README.md`.
|
||||
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
|
||||
/// What one conditional-compilation directive does to the branch structure.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Conditional {
|
||||
/// `` `ifdef `` / `` `ifndef ``: a region, and its first branch, begin.
|
||||
Open,
|
||||
/// `` `elsif `` / `` `else ``: the current branch ends, the next begins.
|
||||
Next,
|
||||
/// `` `endif ``: the last branch, and the region, end.
|
||||
Close,
|
||||
}
|
||||
|
||||
/// `(directive line, last line)` of every branch whose region is closed, in
|
||||
/// 0-based lines, given the line each token starts on.
|
||||
///
|
||||
/// A branch runs from its own directive's line through the line *before*
|
||||
/// the next directive of the same region, so the `` `else `` and the
|
||||
/// `` `endif `` stay visible when the branch above them is collapsed — the
|
||||
/// same rule as `end` under `begin`. Branches with nothing between their two
|
||||
/// lines come back too (`last <= first`); the caller drops them.
|
||||
///
|
||||
/// A region that never closes contributes the branches it *did* finish
|
||||
/// (an `` `ifdef `` … `` `else `` … end-of-file still folds its first
|
||||
/// branch) and nothing for the one still open, rather than folding to the end
|
||||
/// of the file. A stray `` `else `` or `` `endif `` with no region open is
|
||||
/// ignored.
|
||||
pub(super) fn branch_spans(tokens: &[Token], line_of: impl Fn(&Token) -> u32) -> Vec<(u32, u32)> {
|
||||
// The directive line of the branch that is open at each nesting depth.
|
||||
let mut open: Vec<u32> = Vec::new();
|
||||
let mut out = Vec::new();
|
||||
for token in tokens {
|
||||
let Some(directive) = conditional(token) else { continue };
|
||||
let at = line_of(token);
|
||||
match directive {
|
||||
Conditional::Open => open.push(at),
|
||||
Conditional::Next => {
|
||||
if let Some(first) = open.last_mut() {
|
||||
out.push((*first, at.saturating_sub(1)));
|
||||
*first = at;
|
||||
}
|
||||
}
|
||||
Conditional::Close => {
|
||||
if let Some(first) = open.pop() {
|
||||
out.push((first, at.saturating_sub(1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The conditional-compilation directive a token is, if it is one.
|
||||
fn conditional(token: &Token) -> Option<Conditional> {
|
||||
if token.kind != TokenKind::Directive {
|
||||
return None;
|
||||
}
|
||||
match directive_word(&token.text) {
|
||||
"ifdef" | "ifndef" => Some(Conditional::Open),
|
||||
"elsif" | "else" => Some(Conditional::Next),
|
||||
"endif" => Some(Conditional::Close),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The word a directive's text spells, without its backtick or argument:
|
||||
/// `` `ifndef FOO `` is `"ifndef"`. The parser keeps the same rule private
|
||||
/// (`vlog_parser/src/parser/directive.rs`); it is four lines, so it is
|
||||
/// repeated here rather than widened into the parser's public surface.
|
||||
fn directive_word(text: &str) -> &str {
|
||||
let rest = text.strip_prefix('`').unwrap_or("");
|
||||
let end = rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_').unwrap_or(rest.len());
|
||||
rest.get(..end).unwrap_or("")
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
//! `` `ifdef `` branch folds, through the whole [`folding_ranges`] answer so
|
||||
//! every test also sees how they sit beside the scope and comment folds.
|
||||
|
||||
use lsp_types::FoldingRangeKind;
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
use super::folding_ranges;
|
||||
use crate::state::Document;
|
||||
|
||||
fn doc_of(text: &str) -> Document {
|
||||
Document::new(None, text.to_string(), &WorkspaceIndex::default())
|
||||
}
|
||||
|
||||
/// Every fold as `(start line, end line, kind)`, kinds spelled short, after
|
||||
/// checking the one ordering promise every answer keeps: by start line.
|
||||
fn folds(text: &str) -> Vec<(u32, u32, &'static str)> {
|
||||
let ranges = folding_ranges(&doc_of(text));
|
||||
assert!(ranges.windows(2).all(|w| w[0].start_line <= w[1].start_line), "{ranges:?}");
|
||||
ranges
|
||||
.into_iter()
|
||||
.map(|range| {
|
||||
let kind = match range.kind {
|
||||
Some(FoldingRangeKind::Comment) => "comment",
|
||||
Some(FoldingRangeKind::Region) => "region",
|
||||
other => panic!("unexpected kind {other:?}"),
|
||||
};
|
||||
(range.start_line, range.end_line, kind)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The folds as `(start, end)` alone, for tests about lines rather than kinds.
|
||||
fn lines(text: &str) -> Vec<(u32, u32)> {
|
||||
folds(text).into_iter().map(|(start, end, _)| (start, end)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_branch_folds_from_its_directive_to_the_line_before_the_next() {
|
||||
// Collapsing the `ifdef` branch leaves `else` on screen and separately
|
||||
// collapsible; collapsing the `else` branch leaves `endif` on screen.
|
||||
let text = concat!(
|
||||
"module m;\n", // 0
|
||||
"`ifdef A\n", // 1
|
||||
" wire a;\n", // 2
|
||||
" wire b;\n", // 3
|
||||
"`else\n", // 4
|
||||
" wire c;\n", // 5
|
||||
"`endif\n", // 6
|
||||
"endmodule\n", // 7
|
||||
);
|
||||
assert_eq!(folds(text), vec![(0, 6, "region"), (1, 3, "region"), (4, 5, "region")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_elsif_chain_gives_every_arm_its_own_fold() {
|
||||
let text = concat!(
|
||||
"`ifndef A\n", // 0
|
||||
" wire a;\n", // 1
|
||||
"`elsif B\n", // 2
|
||||
" wire b;\n", // 3
|
||||
"`elsif C\n", // 4
|
||||
" wire c;\n", // 5
|
||||
"`else\n", // 6
|
||||
" wire d;\n", // 7
|
||||
"`endif\n", // 8
|
||||
);
|
||||
assert_eq!(lines(text), vec![(0, 1), (2, 3), (4, 5), (6, 7)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_regions_fold_at_every_depth() {
|
||||
let text = concat!(
|
||||
"`ifdef A\n", // 0
|
||||
" `ifdef B\n", // 1
|
||||
" `ifndef C\n", // 2
|
||||
" wire c;\n", // 3
|
||||
" `endif\n", // 4
|
||||
" `else\n", // 5
|
||||
" wire nb;\n", // 6
|
||||
" `endif\n", // 7
|
||||
"`else\n", // 8
|
||||
" `ifdef D\n", // 9
|
||||
" wire d;\n", // 10
|
||||
" `endif\n", // 11
|
||||
"`endif\n", // 12
|
||||
);
|
||||
assert_eq!(
|
||||
lines(text),
|
||||
vec![(0, 7), (1, 4), (2, 3), (5, 6), (8, 11), (9, 10)],
|
||||
"A, B, C, B's else, A's else, D"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_branch_with_nothing_in_it_folds_nothing() {
|
||||
let text = concat!(
|
||||
"`ifdef A\n", // 0
|
||||
"`else\n", // 1
|
||||
" wire b;\n", // 2
|
||||
"`endif\n", // 3
|
||||
"`ifdef C\n", // 4
|
||||
"`endif\n", // 5
|
||||
);
|
||||
assert_eq!(lines(text), vec![(1, 2)], "only the else branch holds a line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_one_line_region_is_one_token_and_folds_nothing() {
|
||||
// A directive runs to the end of its line, so the `endif` here is the
|
||||
// `ifdef` token's text, not a directive of its own.
|
||||
let text = "module m;\n`ifdef A wire a; `else wire b; `endif\nendmodule\n";
|
||||
let doc = doc_of(text);
|
||||
let directives = doc.tokens.iter().filter(|t| t.text.starts_with("`ifdef")).count();
|
||||
assert_eq!(directives, 1);
|
||||
assert_eq!(lines(text), vec![(0, 1)], "the module only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unterminated_region_folds_only_the_branches_it_finished() {
|
||||
// Same policy as an unclosed `begin`: never fold to the end of the file.
|
||||
let text = concat!(
|
||||
"`ifdef A\n", // 0
|
||||
" wire a;\n", // 1
|
||||
"`else\n", // 2
|
||||
" wire b;\n", // 3
|
||||
" wire c;\n", // 4
|
||||
);
|
||||
assert_eq!(lines(text), vec![(0, 1)]);
|
||||
assert!(lines("`ifdef A\n wire a;\n wire b;\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stray_else_and_endif_are_ignored_without_disturbing_what_follows() {
|
||||
let text = concat!(
|
||||
"`else\n", // 0
|
||||
" wire x;\n", // 1
|
||||
"`endif\n", // 2
|
||||
"`endif\n", // 3
|
||||
"`ifdef A\n", // 4
|
||||
" wire a;\n", // 5
|
||||
"`endif\n", // 6
|
||||
"`elsif B\n", // 7
|
||||
" wire b;\n", // 8
|
||||
);
|
||||
assert_eq!(lines(text), vec![(4, 5)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directives_between_ports_fold() {
|
||||
let text = concat!(
|
||||
"module m (\n", // 0
|
||||
" input a,\n", // 1
|
||||
"`ifdef B\n", // 2
|
||||
" input b,\n", // 3
|
||||
" input c,\n", // 4
|
||||
"`endif\n", // 5
|
||||
" input d\n", // 6
|
||||
");\n", // 7
|
||||
"endmodule\n", // 8
|
||||
);
|
||||
assert!(lines(text).contains(&(2, 4)), "got {:?}", lines(text));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directives_inside_case_and_generate_fold() {
|
||||
let text = concat!(
|
||||
"module m;\n", // 0
|
||||
" generate\n", // 1
|
||||
"`ifdef G\n", // 2
|
||||
" if (A) begin : g\n", // 3
|
||||
" wire a;\n", // 4
|
||||
" end\n", // 5
|
||||
"`endif\n", // 6
|
||||
" endgenerate\n", // 7
|
||||
" always_comb begin\n", // 8
|
||||
" case (s)\n", // 9
|
||||
" 0: x = 0;\n", // 10
|
||||
"`ifdef C\n", // 11
|
||||
" 1: x = 1;\n", // 12
|
||||
"`else\n", // 13
|
||||
" 1: x = 2;\n", // 14
|
||||
"`endif\n", // 15
|
||||
" endcase\n", // 16
|
||||
" end\n", // 17
|
||||
"endmodule\n", // 18
|
||||
);
|
||||
assert_eq!(
|
||||
lines(text),
|
||||
vec![(0, 17), (1, 6), (2, 5), (3, 4), (8, 16), (9, 15), (11, 12), (13, 14)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directive_inside_a_define_body_is_text_not_a_fold() {
|
||||
let text = concat!(
|
||||
"`define M \\\n", // 0
|
||||
" `ifdef X \\\n", // 1
|
||||
" a = 1; \\\n", // 2
|
||||
" `else \\\n", // 3
|
||||
" a = 2; \\\n", // 4
|
||||
" `endif\n", // 5
|
||||
"module m;\n", // 6
|
||||
" wire a;\n", // 7
|
||||
"endmodule\n", // 8
|
||||
);
|
||||
assert_eq!(lines(text), vec![(6, 7)], "the module only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directive_in_a_comment_or_a_string_is_not_one() {
|
||||
let text = concat!(
|
||||
"module m;\n", // 0
|
||||
" // `ifdef A\n", // 1
|
||||
" /* `ifdef B\n", // 2
|
||||
" `endif */\n", // 3
|
||||
" initial $display(\"`ifdef\");\n", // 4
|
||||
" // `endif\n", // 5
|
||||
"endmodule\n", // 6
|
||||
);
|
||||
assert_eq!(folds(text), vec![(0, 5, "region"), (2, 3, "comment")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leading_whitespace_trailing_comments_and_crlf_change_nothing() {
|
||||
let plain = concat!(
|
||||
"module m;\n", // 0
|
||||
" `ifdef A // why\n", // 1
|
||||
" wire a;\n", // 2
|
||||
"\t`else /* other */\n", // 3
|
||||
" wire b;\n", // 4
|
||||
" `endif // A\n", // 5
|
||||
"endmodule\n", // 6
|
||||
);
|
||||
assert_eq!(lines(plain), vec![(0, 5), (1, 2), (3, 4)]);
|
||||
assert_eq!(lines(&plain.replace('\n', "\r\n")), lines(plain));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_region_crossing_a_begin_keeps_both_sets_of_folds() {
|
||||
// Real RTL opens one `begin` in each arm and closes it once below the
|
||||
// `endif`. The branch folds cross the `begin` folds; VS Code keeps
|
||||
// crossing ranges (`sanitizeRanges` adds them at the level of the range
|
||||
// they cross; see the feature README), so nothing is dropped here and
|
||||
// nothing is invented either.
|
||||
let text = concat!(
|
||||
"module m;\n", // 0
|
||||
" always_comb begin\n", // 1
|
||||
"`ifdef A\n", // 2
|
||||
" if (a) begin\n", // 3
|
||||
"`else\n", // 4
|
||||
" if (b) begin\n", // 5
|
||||
"`endif\n", // 6
|
||||
" x = 1;\n", // 7
|
||||
" end\n", // 8
|
||||
" end\n", // 9
|
||||
"endmodule\n", // 10
|
||||
);
|
||||
// The scope pairing sees three `begin`s and two `end`s, matches the inner
|
||||
// two (`(5, 7)`, `(3, 8)`) and leaves the `always_comb` one out — that is
|
||||
// `pairs::analyze`, unchanged by this feature. The branches are added
|
||||
// beside it: `(2, 3)` crosses `(3, 8)`, `(4, 5)` crosses `(5, 7)`.
|
||||
assert_eq!(lines(text), vec![(0, 9), (2, 3), (3, 8), (4, 5), (5, 7)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn branch_folds_are_regions() {
|
||||
let text = "`ifdef A\n wire a;\n`endif\n";
|
||||
assert_eq!(folds(text), vec![(0, 1, "region")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn back_to_back_regions_each_fold() {
|
||||
let text = concat!(
|
||||
"`ifdef A\n", // 0
|
||||
" wire a;\n", // 1
|
||||
"`endif\n", // 2
|
||||
"`ifdef B\n", // 3
|
||||
" wire b;\n", // 4
|
||||
"`endif\n", // 5
|
||||
);
|
||||
assert_eq!(lines(text), vec![(0, 1), (3, 4)]);
|
||||
}
|
||||
|
||||
// A shared start line. VS Code keeps only the first range it receives for a
|
||||
// start line, so a fold that existed before branch folds must come first and
|
||||
// the branch fold is the one that yields (QA findings 1 and 2, 2026-11-19).
|
||||
|
||||
#[test]
|
||||
fn a_module_header_sharing_its_line_with_an_ifdef_keeps_its_fold_first() {
|
||||
let text = "module m; `ifdef A\n a;\n`endif\nendmodule\n";
|
||||
assert_eq!(lines(text), vec![(0, 2), (0, 1)], "the module first, the branch after it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_begin_sharing_its_line_with_an_ifdef_keeps_its_fold_first() {
|
||||
let text = concat!(
|
||||
"module m;\n", // 0
|
||||
"initial begin `ifdef X\n", // 1
|
||||
" a;\n", // 2
|
||||
" b;\n", // 3
|
||||
" `endif\n", // 4
|
||||
" c;\n", // 5
|
||||
"end\n", // 6
|
||||
"endmodule\n", // 7
|
||||
);
|
||||
assert_eq!(lines(text), vec![(0, 6), (1, 5), (1, 3)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_opened_on_a_directive_line_keeps_its_fold_first() {
|
||||
// The comment is the shorter range but the older fold, so it is first,
|
||||
// and in VS Code the branch from line 0 is the one that yields.
|
||||
let text = concat!(
|
||||
"`ifdef A /* c1\n", // 0
|
||||
" c2 */\n", // 1
|
||||
" x;\n", // 2
|
||||
"`else\n", // 3
|
||||
" b;\n", // 4
|
||||
"`endif\n", // 5
|
||||
);
|
||||
assert_eq!(folds(text), vec![(0, 1, "comment"), (0, 2, "region"), (3, 4, "region")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_spanning_exactly_a_branch_stays_a_comment() {
|
||||
// Same two lines as the branch: one range, and it keeps the kind it had
|
||||
// before branch folds existed, so *Fold All Block Comments* still folds it.
|
||||
let text = concat!(
|
||||
"`ifdef A /* c1\n", // 0
|
||||
" c2\n", // 1
|
||||
" c3 */\n", // 2
|
||||
"`else\n", // 3
|
||||
" b;\n", // 4
|
||||
"`endif\n", // 5
|
||||
);
|
||||
assert_eq!(folds(text), vec![(0, 2, "comment"), (3, 4, "region")]);
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
//! The real-world proof for `` `ifdef `` folding: every `.sv`/`.svh`/`.v`
|
||||
//! file under an OpenTitan `hw` tree, through [`folding_ranges`], with the
|
||||
//! ranges checked against the file and the directives counted independently.
|
||||
//!
|
||||
//! `#[ignore]`: it parses four thousand files. Run with
|
||||
//! `LUCISV_OPENTITAN_HW=/path/to/opentitan/hw tools/guard.sh -- cargo test
|
||||
//! --release -p lucisv_server opentitan_sweep -- --ignored --nocapture`;
|
||||
//! without the variable it reads `~/.cache/lucisv-opentitan-full/hw`, and it
|
||||
//! skips (passing, with a line on stderr) when that is not there.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
use lsp_types::FoldingRange;
|
||||
|
||||
use super::{branch_folds, directives, folding_ranges, line, scope_and_comment_folds};
|
||||
use crate::state::Document;
|
||||
|
||||
/// The tree: `LUCISV_OPENTITAN_HW`, else the full-tree cache.
|
||||
fn tree() -> Option<PathBuf> {
|
||||
let root = std::env::var_os("LUCISV_OPENTITAN_HW").map(PathBuf::from).or_else(|| {
|
||||
std::env::var_os("HOME")
|
||||
.map(|home| PathBuf::from(home).join(".cache/lucisv-opentitan-full/hw"))
|
||||
})?;
|
||||
root.is_dir().then_some(root)
|
||||
}
|
||||
|
||||
/// Every Verilog source under `dir`, sorted so a run is reproducible.
|
||||
fn sources(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
sources(&path, out);
|
||||
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "svh" | "v")) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The five words, counted on the token stream by a rule written apart from
|
||||
/// the one under test.
|
||||
fn word(token: &Token) -> Option<&'static str> {
|
||||
if token.kind != TokenKind::Directive {
|
||||
return None;
|
||||
}
|
||||
let mut first = token.text.split(|c: char| !c.is_ascii_alphanumeric() && c != '`' && c != '_');
|
||||
match first.next()? {
|
||||
"`ifdef" => Some("ifdef"),
|
||||
"`ifndef" => Some("ifndef"),
|
||||
"`elsif" => Some("elsif"),
|
||||
"`else" => Some("else"),
|
||||
"`endif" => Some("endif"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The same five, counted on the raw text: a line whose first non-blank
|
||||
/// characters spell one. Differs from the token count wherever the lexer knows
|
||||
/// better — a comment, a `` `define `` body.
|
||||
fn text_count(text: &str) -> usize {
|
||||
text.lines()
|
||||
.filter(|l| {
|
||||
let l = l.trim_start();
|
||||
["`ifdef", "`ifndef", "`elsif", "`else", "`endif"].iter().any(|d| {
|
||||
l.strip_prefix(d).is_some_and(|rest| {
|
||||
!rest.starts_with(|c: char| c.is_alphanumeric() || c == '_')
|
||||
})
|
||||
})
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
struct Tally {
|
||||
files: usize,
|
||||
unlexed: usize,
|
||||
tokens: usize,
|
||||
text_lines: usize,
|
||||
opens: usize,
|
||||
nexts: usize,
|
||||
closes: usize,
|
||||
/// `else`/`elsif` and `endif` that found a region open — what
|
||||
/// [`directives::branch_spans`] should emit one span for each of.
|
||||
nexts_matched: usize,
|
||||
closes_matched: usize,
|
||||
/// Regions still open at end of file.
|
||||
unclosed: usize,
|
||||
spans: usize,
|
||||
ranges: usize,
|
||||
not_first_on_line: usize,
|
||||
/// Branch folds left out because an existing fold has the same two lines.
|
||||
same_lines_as_existing: usize,
|
||||
/// Branch folds that share their start line with an existing fold.
|
||||
shared_start: usize,
|
||||
folding: Duration,
|
||||
branches: Duration,
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "reads an OpenTitan checkout; see the module comment"]
|
||||
fn every_opentitan_file_folds_its_ifdef_branches_validly() {
|
||||
let Some(root) = tree() else {
|
||||
eprintln!("opentitan_sweep: no OpenTitan hw tree; skipped");
|
||||
return;
|
||||
};
|
||||
let mut files = Vec::new();
|
||||
sources(&root, &mut files);
|
||||
files.sort();
|
||||
let mut tally = Tally::default();
|
||||
let mut slowest: Vec<(Duration, Duration, PathBuf)> = Vec::new();
|
||||
for path in &files {
|
||||
let Ok(text) = std::fs::read_to_string(path) else { continue };
|
||||
let (folding, branches) = sweep_one(path, text, &mut tally);
|
||||
slowest.push((folding, branches, path.clone()));
|
||||
}
|
||||
slowest.sort_by_key(|entry| std::cmp::Reverse(entry.0));
|
||||
eprintln!("opentitan_sweep: {tally:#?}");
|
||||
for (folding, branches, path) in slowest.iter().take(5) {
|
||||
eprintln!(" {folding:?} (branches {branches:?}) {}", path.display());
|
||||
}
|
||||
assert!(tally.files > 0);
|
||||
assert_eq!(tally.spans, tally.nexts_matched + tally.closes_matched, "{tally:#?}");
|
||||
}
|
||||
|
||||
/// Fold one file, check its ranges, and add it to `tally`. Returns the time
|
||||
/// the whole answer took and the time the branch pass alone took.
|
||||
fn sweep_one(path: &Path, text: String, tally: &mut Tally) -> (Duration, Duration) {
|
||||
tally.files += 1;
|
||||
let by_text = text_count(&text);
|
||||
tally.text_lines += by_text;
|
||||
let doc = Document::new(None, text, &WorkspaceIndex::default());
|
||||
if doc.tokens.is_empty() {
|
||||
tally.unlexed += 1;
|
||||
eprintln!(" does not lex: {}", path.display());
|
||||
}
|
||||
let lines = doc.line_index.line_col(doc.text.len() as u32).0;
|
||||
|
||||
let started = Instant::now();
|
||||
let ranges = folding_ranges(&doc);
|
||||
let folding = started.elapsed();
|
||||
let started = Instant::now();
|
||||
let spans = directives::branch_spans(&doc.tokens, |t| line(&doc, t.span.start));
|
||||
let branches = started.elapsed();
|
||||
tally.folding += folding;
|
||||
tally.branches += branches;
|
||||
|
||||
for range in &ranges {
|
||||
assert!(range.start_line < range.end_line, "{}: {range:?}", path.display());
|
||||
assert!(range.end_line < lines, "{}: {range:?} past line {lines}", path.display());
|
||||
}
|
||||
check_existing_unchanged(&doc, &ranges, path, tally);
|
||||
let before = tally.tokens;
|
||||
let directive_lines = check_directives(&doc, path, tally);
|
||||
if tally.tokens - before != by_text {
|
||||
let tokens = tally.tokens - before;
|
||||
eprintln!(" {by_text} by text, {tokens} by token: {}", path.display());
|
||||
}
|
||||
tally.spans += spans.len();
|
||||
for &(start, end) in spans.iter().filter(|(s, e)| e > s) {
|
||||
tally.ranges += 1;
|
||||
assert!(directive_lines.contains(&start), "{}: fold at {start}", path.display());
|
||||
assert!(
|
||||
ranges.iter().any(|r| r.start_line == start && r.end_line == end),
|
||||
"{}: branch {start}..{end} missing from the answer",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
(folding, branches)
|
||||
}
|
||||
|
||||
/// Count the directive tokens into `tally` and return the lines they start on.
|
||||
fn check_directives(doc: &Document, path: &Path, tally: &mut Tally) -> Vec<u32> {
|
||||
let mut at = Vec::new();
|
||||
let mut depth = 0usize;
|
||||
for (i, token) in doc.tokens.iter().enumerate() {
|
||||
let Some(word) = word(token) else { continue };
|
||||
tally.tokens += 1;
|
||||
match word {
|
||||
"ifdef" | "ifndef" => {
|
||||
tally.opens += 1;
|
||||
depth += 1;
|
||||
}
|
||||
"elsif" | "else" => {
|
||||
tally.nexts += 1;
|
||||
tally.nexts_matched += usize::from(depth > 0);
|
||||
}
|
||||
_ => {
|
||||
tally.closes += 1;
|
||||
tally.closes_matched += usize::from(depth > 0);
|
||||
depth = depth.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
let start = line(doc, token.span.start);
|
||||
let previous = i.checked_sub(1).map(|p| &doc.tokens[p]);
|
||||
if previous.is_some_and(|p| line(doc, p.span.end.saturating_sub(1)) == start) {
|
||||
tally.not_first_on_line += 1;
|
||||
eprintln!(" not first on line {}: {}:{}", start + 1, path.display(), token.text);
|
||||
}
|
||||
at.push(start);
|
||||
}
|
||||
tally.unclosed += depth;
|
||||
at
|
||||
}
|
||||
|
||||
/// The answer with its branch folds taken out is exactly the scope and
|
||||
/// comment folds alone — same ranges, kinds and order — so no fold that
|
||||
/// existed before this feature is lost, changed or moved.
|
||||
fn check_existing_unchanged(
|
||||
doc: &Document,
|
||||
ranges: &[FoldingRange],
|
||||
path: &Path,
|
||||
tally: &mut Tally,
|
||||
) {
|
||||
let existing = scope_and_comment_folds(doc);
|
||||
let branches = branch_folds(doc, &existing);
|
||||
let rest: Vec<&FoldingRange> = ranges.iter().filter(|r| !branches.contains(r)).collect();
|
||||
assert_eq!(rest, existing.iter().collect::<Vec<_>>(), "{}", path.display());
|
||||
assert_eq!(ranges.len(), existing.len() + branches.len(), "{}", path.display());
|
||||
let spans = directives::branch_spans(&doc.tokens, |t| line(doc, t.span.start));
|
||||
let kept = spans.iter().filter(|(s, e)| e > s).count();
|
||||
tally.same_lines_as_existing += kept - branches.len();
|
||||
for branch in &branches {
|
||||
if existing.iter().any(|r| r.start_line == branch.start_line) {
|
||||
tally.shared_start += 1;
|
||||
eprintln!(" shared start line {}: {}", branch.start_line + 1, path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,13 +6,16 @@
|
||||
//! output, or no edit at all and an error for the user to read. That holds for
|
||||
//! the range requests too — their output is verified over the whole buffer,
|
||||
//! and what makes a request a *range* format is which constructs it laid out,
|
||||
//! not which bytes it was allowed to replace.
|
||||
//! not which bytes it was allowed to replace. The range requests go through
|
||||
//! `format_selection`: the smallest run of sibling items or statements the
|
||||
//! selection covers, laid out at the indentation it was written at — see
|
||||
//! `docs/features/selection-formatting/README.md`.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_types::{FormattingOptions, Range, TextDocumentIdentifier, TextEdit};
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use vlog_formatter::{format_range, format_source, Config, LineRanges};
|
||||
use vlog_formatter::{format_selection, format_source, style, Config, LineRanges, Style};
|
||||
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::state::Document;
|
||||
@@ -52,6 +55,16 @@ pub struct Settings {
|
||||
/// Each rung applies only where every rung above it is silent, so a project
|
||||
/// with no `lucisv.toml` and no `lucisv.*` settings behaves exactly as it did
|
||||
/// before either existed.
|
||||
///
|
||||
/// **The style** (`[format] style`, `lucisv.format.style`) climbs rungs 1, 2
|
||||
/// and 4 first, and supplies the indent and width the other keys then
|
||||
/// overwrite. A style that was chosen on rung 1 or 2 also outranks rung 3:
|
||||
/// `tabSize` is sent whether or not anyone chose it, and the editor's own
|
||||
/// default of 4 silently undoing `google`'s 2 is not what choosing a style
|
||||
/// asked for. With no style chosen — or `lucisv`, which is what VS Code sends
|
||||
/// when nobody touched the drop-down, and which means exactly "what lucisv
|
||||
/// always did", or `auto`, which chooses a layout but no size — rung 3
|
||||
/// behaves exactly as it always has.
|
||||
pub fn settings_for(
|
||||
doc: &Document,
|
||||
client: &ClientSettings,
|
||||
@@ -83,10 +96,16 @@ pub fn settings_without_editor_options(doc: &Document, client: &ClientSettings)
|
||||
/// invent an edit from it.
|
||||
pub fn formatting(doc: &Document, config: &Config) -> Result<Option<TextEdit>, String> {
|
||||
let formatted = format_source(&doc.text, config).map_err(|e| e.to_string())?;
|
||||
Ok(whole_document_edit(doc, formatted))
|
||||
}
|
||||
|
||||
/// The one edit that turns `doc` into `formatted`, or none when they are
|
||||
/// already the same text.
|
||||
pub fn whole_document_edit(doc: &Document, formatted: String) -> Option<TextEdit> {
|
||||
if formatted == doc.text {
|
||||
return Ok(None);
|
||||
return None;
|
||||
}
|
||||
Ok(Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted }))
|
||||
Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted })
|
||||
}
|
||||
|
||||
/// `textDocument/rangesFormatting`, the LSP 3.18 multi-range request.
|
||||
@@ -122,10 +141,12 @@ pub fn range_formatting(
|
||||
///
|
||||
/// The ranges are a *set*: they are sorted and merged by `LineRanges::new`
|
||||
/// before the engine sees them, so overlapping, adjacent, repeated and
|
||||
/// unsorted input from the client all reach the same answer. No range is
|
||||
/// formatted on its own — one `format_range` call lays out the union, which is
|
||||
/// what keeps the all-or-nothing contract (CLAUDE.md invariant #1) whole
|
||||
/// rather than making it a promise per range.
|
||||
/// unsorted input from the client all reach the same answer. Each merged span
|
||||
/// selects its own target (targets that overlap are re-selected from the hull
|
||||
/// of their spans), but no range is formatted on its own — one
|
||||
/// `format_selection` call lays out and verifies them all, which is what keeps
|
||||
/// the all-or-nothing contract (CLAUDE.md invariant #1) whole rather than
|
||||
/// making it a promise per range.
|
||||
///
|
||||
/// The reply is still one whole-document edit: the engine's contract is
|
||||
/// all-or-nothing over the file, and a partial run's output differs from the
|
||||
@@ -140,7 +161,7 @@ pub fn ranges_formatting(
|
||||
return Ok(None);
|
||||
}
|
||||
let lines = LineRanges::new(ranges.iter().copied().map(lines_of))?;
|
||||
let formatted = format_range(&doc.text, config, &lines).map_err(|e| e.to_string())?;
|
||||
let formatted = format_selection(&doc.text, config, &lines).map_err(|e| e.to_string())?;
|
||||
if formatted == doc.text {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -179,7 +200,16 @@ fn lines_of(range: Range) -> (u32, u32) {
|
||||
/// lightbulb the editor requests on every cursor move would be noise.
|
||||
pub fn indent_width(path: Option<&Path>, client: &ClientSettings) -> usize {
|
||||
let (file, _problem) = discover(path);
|
||||
file.indent.or(client.indent).unwrap_or(Config::default().indent_width)
|
||||
file.indent
|
||||
.or(client.indent)
|
||||
.unwrap_or(chosen_style(&file, client).unwrap_or(style::LUCISV).indent)
|
||||
}
|
||||
|
||||
/// The preset a project or a user picked for this buffer, `lucisv.toml`
|
||||
/// first; `None` when neither did, or when the pick is `auto`, which names
|
||||
/// no preset and so no indent.
|
||||
fn chosen_style(file: &FileConfig, client: &ClientSettings) -> Option<Style> {
|
||||
file.format_style.or(client.style).and_then(style::preset)
|
||||
}
|
||||
|
||||
/// The config file governing `path`, by the CLI's own discovery rule, or the
|
||||
@@ -208,8 +238,12 @@ fn discover(path: Option<&Path>) -> (FileConfig, Option<String>) {
|
||||
/// protocol carries no line-length option — so before it existed there was no
|
||||
/// way to set a width from an editor without a `lucisv.toml`.
|
||||
fn config_from(file: &FileConfig, client: &ClientSettings, options: &FormattingOptions) -> Config {
|
||||
let mut config = Config::default();
|
||||
if options.insert_spaces && INDENT_RANGE.contains(&options.tab_size) {
|
||||
let named = file.format_style.or(client.style).and_then(Config::named);
|
||||
// `auto` picks a layout and no size, so it leaves the editor's rung alone
|
||||
// exactly as "no style" and `lucisv` do.
|
||||
let editor_rung = chosen_style(file, client).is_none_or(|s| s == style::LUCISV);
|
||||
let mut config = named.unwrap_or_default();
|
||||
if editor_rung && options.insert_spaces && INDENT_RANGE.contains(&options.tab_size) {
|
||||
config.indent_width = options.tab_size as usize;
|
||||
}
|
||||
if let Some(indent) = client.indent {
|
||||
@@ -549,6 +583,68 @@ mod tests {
|
||||
assert!(settings.config.uvm_utils_indent);
|
||||
}
|
||||
|
||||
/// The style climbs rungs 1, 2 and 4, supplies the starting indent and
|
||||
/// width, and — once someone actually chose one — outranks `tabSize`.
|
||||
#[test]
|
||||
fn a_style_sets_the_starting_values_and_outranks_tab_size() {
|
||||
let styled = |name| ClientSettings { style: Some(name), ..Default::default() };
|
||||
let (ws, uri) = document("module m;\nendmodule\n");
|
||||
let config = |client: &ClientSettings, tab| {
|
||||
settings_with(&ws, &uri, client, &options(tab, true)).config
|
||||
};
|
||||
// No style, and `lucisv` — what VS Code sends by default — are the
|
||||
// same thing: `tabSize` is the indent, exactly as before styles.
|
||||
assert_eq!((config(&none(), 4).indent_width, config(&none(), 4).style), (4, style::LUCISV));
|
||||
assert_eq!(config(&styled("lucisv"), 4).indent_width, 4);
|
||||
// A chosen style outranks `tabSize`...
|
||||
let google = config(&styled("google"), 4);
|
||||
assert_eq!((google.style, google.indent_width, google.max_width), (style::GOOGLE, 2, 100));
|
||||
// ...but not an explicit `lucisv.indent`, and the width stays the style's.
|
||||
let both =
|
||||
ClientSettings { style: Some("microsoft"), indent: Some(2), ..Default::default() };
|
||||
let microsoft = config(&both, 8);
|
||||
assert_eq!((microsoft.indent_width, microsoft.max_width), (2, 120));
|
||||
// A misspelt editor value never got this far: it is dropped on arrival.
|
||||
assert_eq!(
|
||||
crate::settings::from_payload(&serde_json::json!({
|
||||
"lucisv": { "format": { "style": "gogle" } }
|
||||
}))
|
||||
.style,
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lucisv_toml_names_the_style_over_the_editor() {
|
||||
let styled = |name| ClientSettings { style: Some(name), ..Default::default() };
|
||||
let nxp = Tree::new("[format]\nstyle = \"nxp\"\n");
|
||||
let (ws, uri) = nxp.document("module m;\nendmodule\n");
|
||||
let settings = settings_with(&ws, &uri, &styled("microsoft"), &options(4, true));
|
||||
assert_eq!(settings.problem, None);
|
||||
let c = settings.config;
|
||||
assert_eq!((c.style, c.indent_width, c.max_width), (style::NXP, 2, 80));
|
||||
// The project's `lucisv` beats the editor's `google`, and with it the
|
||||
// editor's `tabSize` is back in play.
|
||||
let plain = Tree::new("[format]\nstyle = \"lucisv\"\n");
|
||||
let (ws, uri) = plain.document("module m;\nendmodule\n");
|
||||
let c = settings_with(&ws, &uri, &styled("google"), &options(4, true)).config;
|
||||
assert_eq!((c.style, c.indent_width), (style::LUCISV, 4));
|
||||
// The lint-fix width follows the style too, below the explicit keys.
|
||||
let ansi = Tree::new("[format]\nstyle = \"ansi\"\n");
|
||||
let path = ansi.path.join("m.sv");
|
||||
assert_eq!(indent_width(Some(&path), &none()), 4);
|
||||
assert_eq!(indent_width(None, &styled("microsoft")), 4);
|
||||
let pushed = ClientSettings { indent: Some(3), ..styled("microsoft") };
|
||||
assert_eq!(indent_width(Some(&path), &pushed), 3);
|
||||
// A bad name in `lucisv.toml` is the config problem every bad key is.
|
||||
let bad = Tree::new("[format]\nstyle = \"gogle\"\n");
|
||||
let (ws, uri) = bad.document("module m;\nendmodule\n");
|
||||
let settings = settings_with(&ws, &uri, &none(), &options(2, true));
|
||||
let problem = settings.problem.expect("a problem");
|
||||
assert!(problem.contains("unknown style `gogle`"), "{problem}");
|
||||
assert_eq!(settings.config.style, style::LUCISV);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_key_climbs_the_ladder_independently() {
|
||||
// A `lucisv.toml` naming only `indent` must not also claim the width:
|
||||
@@ -700,6 +796,39 @@ mod tests {
|
||||
assert!(edit.new_text.contains("é ✓ 🎉"), "comments are never dropped");
|
||||
}
|
||||
|
||||
/// A file indented four spaces with a `case` nested in an `always`: the
|
||||
/// shape VS Code's "Format Selection" most often sends.
|
||||
const NESTED: &str = "module m;\n always @* begin\n case (s)\n 0: y=a;\n default:y=b;\n endcase\n z = 1;\n end\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn a_selected_case_is_laid_out_alone_at_the_indentation_it_starts_at() {
|
||||
let edit = ranged(NESTED, at(2, 0, 6, 0)).expect("formats").expect("changed");
|
||||
assert_eq!(
|
||||
edit.new_text,
|
||||
"module m;\n always @* begin\n case (s)\n 0: y = a;\n default: y = b;\n endcase\n z = 1;\n end\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tab_indented_selection_keeps_its_tabs() {
|
||||
let text = "module m;\n\talways @* begin\n\t\tx=1;\n\tend\nendmodule\n";
|
||||
let edit = ranged(text, at(2, 0, 2, 4)).expect("formats").expect("changed");
|
||||
assert_eq!(edit.new_text, "module m;\n\talways @* begin\n\t\tx = 1;\n\tend\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parse_error_outside_the_selection_does_not_block_it() {
|
||||
let text = "module m;\n always @* begin\n x=1;\n end\n assign y = ;\nendmodule\n";
|
||||
let edit = ranged(text, at(2, 0, 2, 4)).expect("formats").expect("changed");
|
||||
assert_eq!(
|
||||
edit.new_text,
|
||||
"module m;\n always @* begin\n x = 1;\n end\n assign y = ;\nendmodule\n"
|
||||
);
|
||||
// Inside it, the request is refused with a message to read.
|
||||
let message = ranged(text, at(4, 0, 4, 4)).expect_err("must refuse");
|
||||
assert!(message.contains("syntax error"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unparsable_buffer_produces_no_range_edit_either() {
|
||||
// Range formatting cannot rescue broken input; the strict parse still
|
||||
@@ -802,7 +931,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_refused_buffer_is_refused_identically_whichever_range_request_asked() {
|
||||
// No partial output on either path (CLAUDE.md invariant #1), and the
|
||||
// same message: both are one `format_range` call away from the engine.
|
||||
// same message: both are one `format_selection` call away from the engine.
|
||||
let broken = "module m;\n wire ;\nendmodule\n";
|
||||
let one = ranged(broken, at(0, 0, 0, 9));
|
||||
let many = multi(broken, &[at(0, 0, 0, 9), at(2, 0, 2, 9)]);
|
||||
|
||||
@@ -1572,6 +1572,8 @@ mod qa_hover_declarations {
|
||||
use crate::uri::path_to_uri;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
// Its one user is the case-insensitive-filesystem test below.
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
use std::str::FromStr;
|
||||
|
||||
fn temp_dir(tag: &str) -> PathBuf {
|
||||
|
||||
@@ -952,7 +952,10 @@ mod qa_scope_probe {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
/// Both probes need `is_file` to succeed for a spelling the file does not
|
||||
/// have, which only a case-insensitive filesystem does — macOS's and
|
||||
/// Windows' defaults — so the module is scoped to them.
|
||||
#[cfg(all(test, any(target_os = "macos", target_os = "windows")))]
|
||||
mod qa_round2 {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
@@ -963,7 +966,6 @@ mod qa_round2 {
|
||||
/// unconditionally once a collision exists, so a third colliding entry is
|
||||
/// a no-op over an already-`None` slot rather than something that could
|
||||
/// re-arm it — confirmed here rather than only read off the source.
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
#[test]
|
||||
fn three_files_colliding_on_one_folded_spelling_stay_ambiguous() {
|
||||
let dir =
|
||||
@@ -995,7 +997,6 @@ mod qa_round2 {
|
||||
/// must come back exactly as before this fix — `folded` only ever learns
|
||||
/// about in-scope files, so an out-of-scope collision has no entry to
|
||||
/// find and falls through to the "no match" arm, unchanged.
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
#[test]
|
||||
fn a_case_mismatch_on_a_file_outside_the_graphs_scope_is_unchanged() {
|
||||
let dir =
|
||||
|
||||
@@ -27,16 +27,19 @@
|
||||
//! because the editor prepends that line's own indentation when it inserts the
|
||||
//! snippet; see `render`. See `docs/features/inline-templates/README.md`.
|
||||
|
||||
use lsp_types::{Position, Range, Uri};
|
||||
use lsp_types::{Position, Range, SelectedCompletionInfo, Uri};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_refactor::{Layout, Site};
|
||||
|
||||
use crate::completion;
|
||||
use crate::on_type;
|
||||
use crate::pairs;
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::templates::{self, Dialect};
|
||||
|
||||
mod keywords;
|
||||
|
||||
/// One line of a body: how many indent steps it sits in, and its text. The
|
||||
/// same shape `templates.rs` writes its skeletons in.
|
||||
type Line = (u8, &'static str);
|
||||
@@ -96,6 +99,13 @@ const BEGIN_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "end")];
|
||||
const FORK_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "join")];
|
||||
const GENERATE_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "endgenerate")];
|
||||
|
||||
/// The event control of a flop with an async active-low reset, both edges a
|
||||
/// tabstop. First in both `always` families (TODO §68.1): the commoner flop.
|
||||
const CLOCK_AND_RESET: &[Line] =
|
||||
&[(0, "posedge ${1:clk} or negedge ${2:rst_n}) begin"), (1, "$0"), (0, "end")];
|
||||
/// The clock-only event control, one cycle away.
|
||||
const CLOCK_ONLY: &[Line] = &[(0, "posedge ${1:clk}) begin"), (1, "$0"), (0, "end")];
|
||||
|
||||
/// Every construct that offers ghost text.
|
||||
///
|
||||
/// The order is the order `triggered` tries them, which only matters when two
|
||||
@@ -156,19 +166,16 @@ const TRIGGERS: &[Trigger] = &[
|
||||
opener: EVENT,
|
||||
dialect: Some(Dialect::SystemVerilog),
|
||||
gate: Unclosed::Paren,
|
||||
bodies: &[&[(0, "posedge ${1:clk}) begin"), (1, "$0"), (0, "end")]],
|
||||
bodies: &[CLOCK_AND_RESET, CLOCK_ONLY],
|
||||
},
|
||||
Trigger {
|
||||
keyword: "always",
|
||||
opener: EVENT,
|
||||
dialect: None,
|
||||
gate: Unclosed::Paren,
|
||||
// Two items, clocked first: `always @(` is overwhelmingly a flop, and
|
||||
// the client cycles to the second with one keystroke.
|
||||
bodies: &[
|
||||
&[(0, "posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
|
||||
&[(0, "*) begin"), (1, "$0"), (0, "end")],
|
||||
],
|
||||
// Three items, clocked first: `always @(` is overwhelmingly a flop,
|
||||
// and the client cycles to the next with one keystroke.
|
||||
bodies: &[CLOCK_AND_RESET, CLOCK_ONLY, &[(0, "*) begin"), (1, "$0"), (0, "end")]],
|
||||
},
|
||||
Trigger {
|
||||
keyword: "begin",
|
||||
@@ -237,7 +244,15 @@ pub struct InlineItems {
|
||||
/// `None` rather than an empty list wherever there is nothing to say: an
|
||||
/// editor treats both the same, and `null` is the cheaper answer to a request
|
||||
/// that arrives on every keystroke.
|
||||
pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Option<InlineItems> {
|
||||
///
|
||||
/// `selected` is the request's `context.selectedCompletionInfo` — the popup's
|
||||
/// selected entry, when one is showing. Only the keyword ghost reads it.
|
||||
pub fn inline_completions_in_context(
|
||||
ws: &Workspace,
|
||||
uri: &Uri,
|
||||
position: Position,
|
||||
selected: Option<&SelectedCompletionInfo>,
|
||||
) -> Option<InlineItems> {
|
||||
let doc = ws.document(uri)?;
|
||||
// No token stream, no answer — the same trade `completion.rs` makes. A
|
||||
// half-typed string or block comment is what breaks the lexer, and those
|
||||
@@ -260,14 +275,24 @@ pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Opti
|
||||
return instantiation(ws, doc, name, at);
|
||||
}
|
||||
let last = last_token(doc, offset)?;
|
||||
match doc.tokens.get(last)?.kind {
|
||||
// A name with nothing after it is not an offer (owner ruling,
|
||||
// 2026-08-30): `aes` may still be growing into `aes_dft`, and the
|
||||
// space is the user saying that it is not. No trigger's own last token
|
||||
// is an `Ident` either, so nothing is lost by stopping here.
|
||||
TokenKind::Ident => None,
|
||||
_ => template(ws, doc, last, at),
|
||||
// A name with nothing after it is not an instantiation offer (owner
|
||||
// ruling, 2026-08-30): `aes` may still be growing into `aes_dft`, and the
|
||||
// space is the user saying that it is not. No trigger's own last token is
|
||||
// an `Ident` either, so only the keyword ghost is asked about one.
|
||||
if doc.tokens.get(last)?.kind != TokenKind::Ident {
|
||||
if let Some(items) = template(ws, doc, last, at) {
|
||||
return Some(items);
|
||||
}
|
||||
}
|
||||
// The fallback: the rest of a keyword the word is a proper prefix of.
|
||||
keywords::keyword_ghost(ws, doc, last, position, selected)
|
||||
}
|
||||
|
||||
/// [`inline_completions_in_context`] with no popup open — what every test
|
||||
/// that is not about the popup asks.
|
||||
#[cfg(test)]
|
||||
pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Option<InlineItems> {
|
||||
inline_completions_in_context(ws, uri, position, None)
|
||||
}
|
||||
|
||||
/// The identifier the user has just finished and armed with a space: the token
|
||||
@@ -299,7 +324,7 @@ fn template(ws: &Workspace, doc: &Document, last: usize, at: Range) -> Option<In
|
||||
return None;
|
||||
}
|
||||
let (trigger, opened) = triggered(doc, last)?;
|
||||
if !unfinished(doc, trigger, opened) {
|
||||
if !unfinished(doc, trigger, opened, last) {
|
||||
return None;
|
||||
}
|
||||
Some(InlineItems {
|
||||
@@ -487,13 +512,20 @@ fn triggered(doc: &Document, index: usize) -> Option<(&'static Trigger, Opened)>
|
||||
}
|
||||
|
||||
/// Whether the construct the user opened really is still waiting to be closed.
|
||||
fn unfinished(doc: &Document, trigger: &Trigger, opened: Opened) -> bool {
|
||||
///
|
||||
/// `last` is the index of the token just typed — for `begin`, the keyword
|
||||
/// itself, which is asked the auto-`end` question (`on_type::auto_end`)
|
||||
/// rather than "is this span unmatched": a `begin` typed inside a balanced
|
||||
/// block steals that block's `end` in the stack matcher, and would otherwise
|
||||
/// get no ghost (`completion-ux` fix round, 2026-11-17).
|
||||
fn unfinished(doc: &Document, trigger: &Trigger, opened: Opened, last: usize) -> bool {
|
||||
let paren = || !paren_is_closed(&doc.tokens, opened.last);
|
||||
let scope = || {
|
||||
pairs::analyze(&doc.tokens).unmatched_open.iter().any(|open| open.span == opened.keyword)
|
||||
};
|
||||
match trigger.gate {
|
||||
Unclosed::Paren => paren(),
|
||||
Unclosed::Scope if trigger.keyword == "begin" => on_type::begin_owes_an_end(doc, last),
|
||||
Unclosed::Scope => scope(),
|
||||
// The paren check first: it is a flat pass over the tokens, and
|
||||
// skipping `pairs::analyze` when it already says no is what keeps this
|
||||
@@ -822,15 +854,16 @@ endmodule
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_always_at_offers_the_clocked_block_first_and_the_star_second() {
|
||||
fn an_always_at_offers_clock_and_reset_first_then_clock_only_then_the_star() {
|
||||
let text = "module top;\n always @(\nendmodule\n";
|
||||
assert_eq!(
|
||||
all_offered(text, "always @("),
|
||||
vec![
|
||||
"posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend".to_string(),
|
||||
"posedge ${1:clk}) begin\n\t$0\nend".to_string(),
|
||||
"*) begin\n\t$0\nend".to_string(),
|
||||
],
|
||||
"clocked first: `always @(` is overwhelmingly a flop"
|
||||
"clocked first: `always @(` is overwhelmingly a flop, and most flops reset"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -839,7 +872,10 @@ endmodule
|
||||
let text = "module top;\n always_ff @(\nendmodule\n";
|
||||
assert_eq!(
|
||||
offered_in("/rtl/top.sv", text, "always_ff @("),
|
||||
vec!["posedge ${1:clk}) begin\n\t$0\nend"]
|
||||
vec![
|
||||
"posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend",
|
||||
"posedge ${1:clk}) begin\n\t$0\nend"
|
||||
]
|
||||
);
|
||||
assert!(
|
||||
offered_in("/rtl/top.v", text, "always_ff @(").is_empty(),
|
||||
@@ -930,6 +966,15 @@ endmodule
|
||||
assert!(offered(text, "initial begin").is_some(), "this one lost its end");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_begin_typed_inside_a_balanced_block_still_offers_its_end() {
|
||||
// The new `begin` steals the `always_comb` block's `end` in the stack
|
||||
// matcher; the gate asks the auto-`end` question instead
|
||||
// (`completion-ux` fix round, 2026-11-17).
|
||||
let text = "module top;\n always_comb begin\n if (x) begin\n end\nendmodule\n";
|
||||
assert_eq!(offered(text, "if (x) begin").as_deref(), Some("\n\t$0\nend"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scope_keyword_that_already_has_its_closer_offers_nothing() {
|
||||
// The same rule as `begin`, for the three keywords that joined it.
|
||||
@@ -1019,8 +1064,10 @@ endmodule
|
||||
fn an_always_without_its_event_control_offers_nothing() {
|
||||
// The opener is a *sequence*: both `@` and `(` must be there, in that
|
||||
// order, or the user has not committed to an event-controlled block.
|
||||
// A bare `always` grows no block — only the keyword ghost's `_ff`,
|
||||
// which is a different feature with its own setting.
|
||||
let text = "module top;\n always\nendmodule\n";
|
||||
assert_eq!(offered(text, " always"), None);
|
||||
assert_eq!(offered(text, " always").as_deref(), Some("_ff"));
|
||||
let text = "module top;\n always @\nendmodule\n";
|
||||
assert_eq!(offered(text, "always @"), None);
|
||||
let text = "module top;\n always (\nendmodule\n";
|
||||
@@ -1140,7 +1187,7 @@ endmodule
|
||||
assert_eq!(offered(text, " if(").as_deref(), Some("${1:cond}) begin\n\t$0\nend"));
|
||||
// ...and the same for a two-symbol opener written tight.
|
||||
let text = "module top;\n always@(\nendmodule\n";
|
||||
assert_eq!(all_offered(text, "always@(").len(), 2);
|
||||
assert_eq!(all_offered(text, "always@(").len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1532,7 +1579,7 @@ endmodule
|
||||
// `no_space_between_the_keyword_and_the_paren_still_triggers`, this
|
||||
// pins the opposite spacing.
|
||||
let text = "module top;\n always @ (\nendmodule\n";
|
||||
assert_eq!(all_offered(text, "always @ (").len(), 2);
|
||||
assert_eq!(all_offered(text, "always @ (").len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1588,7 +1635,7 @@ endmodule
|
||||
// counterpart — both must still offer.
|
||||
let text = "module top;\n if (\n always @(\nendmodule\n";
|
||||
assert!(offered(text, " if (").is_some());
|
||||
assert_eq!(all_offered(text, " always @(").len(), 2);
|
||||
assert_eq!(all_offered(text, " always @(").len(), 3);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -1629,6 +1676,16 @@ endmodule
|
||||
serde_json::to_value(&items).expect("serializes"),
|
||||
serde_json::json!({
|
||||
"items": [
|
||||
{
|
||||
"insertText": {
|
||||
"kind": "snippet",
|
||||
"value": "posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend"
|
||||
},
|
||||
"range": {
|
||||
"start": { "line": 1, "character": 11 },
|
||||
"end": { "line": 1, "character": 11 }
|
||||
}
|
||||
},
|
||||
{
|
||||
"insertText": {
|
||||
"kind": "snippet",
|
||||
|
||||
@@ -0,0 +1,519 @@
|
||||
//! Keyword ghosts (TODO §68.1): a typed proper prefix of a keyword shows the
|
||||
//! rest of it as grey text — `alw` grows `ays_ff`, Tab accepts.
|
||||
//!
|
||||
//! The fallback ghost: asked only where no template trigger answered, and
|
||||
//! only for an identifier-like word of two characters or more that ends
|
||||
//! exactly at the cursor. Three rules decide which keyword, in order:
|
||||
//!
|
||||
//! 1. **The popup's choice.** While VS Code's suggest widget is open it shows
|
||||
//! an inline item only if it extends the selected entry over the selected
|
||||
//! entry's range (LSP 3.18 `selectedCompletionInfo`). So with a selection,
|
||||
//! the ghost is exactly that keyword when it is one, and nothing otherwise.
|
||||
//! 2. **A fixed priority list** of the words an RTL designer types all day.
|
||||
//! 3. **Shortest, then alphabetical**, over every keyword of the buffer's
|
||||
//! dialect.
|
||||
//!
|
||||
//! A word that is already a keyword is only extended across an underscore:
|
||||
//! `always` grows `_ff`, but `for` stays `for` and `end` stays `end` — the
|
||||
//! keystroke after a finished keyword is a space or a newline far more often
|
||||
//! than another letter, and a ghost there is noise a stray Tab accepts.
|
||||
//! See `docs/features/completion-ux/README.md`.
|
||||
|
||||
use lsp_types::{Position, Range, SelectedCompletionInfo};
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::KEYWORDS;
|
||||
|
||||
use super::{InlineItem, InlineItems, SnippetValue};
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::templates::{self, Dialect};
|
||||
|
||||
/// The shortest word worth a ghost. One letter is a prefix of half the
|
||||
/// keyword list, and the ghost would change on every keystroke.
|
||||
const MIN_WORD: usize = 2;
|
||||
|
||||
/// The keywords tried first, in this order, whenever more than one extends
|
||||
/// the typed word. Everything else falls back to shortest-then-alphabetical.
|
||||
const PRIORITY: &[&str] = &[
|
||||
"always_ff",
|
||||
"always_comb",
|
||||
"always",
|
||||
"assign",
|
||||
"begin",
|
||||
"logic",
|
||||
"input",
|
||||
"output",
|
||||
"inout",
|
||||
"module",
|
||||
"endmodule",
|
||||
"parameter",
|
||||
"localparam",
|
||||
"function",
|
||||
"endfunction",
|
||||
"task",
|
||||
"endtask",
|
||||
"generate",
|
||||
"endgenerate",
|
||||
"genvar",
|
||||
"case",
|
||||
"endcase",
|
||||
"default",
|
||||
"initial",
|
||||
"integer",
|
||||
"posedge",
|
||||
"negedge",
|
||||
"typedef",
|
||||
"struct",
|
||||
"enum",
|
||||
"package",
|
||||
"endpackage",
|
||||
"interface",
|
||||
"endinterface",
|
||||
"foreach",
|
||||
"forever",
|
||||
"return",
|
||||
"automatic",
|
||||
"unique",
|
||||
"wire",
|
||||
"reg",
|
||||
];
|
||||
|
||||
/// The IEEE 1364-2005 reserved words: what a `.v` buffer may be offered. The
|
||||
/// lexer's list is one list for both dialects, and `logic` grown in a file a
|
||||
/// Verilog compiler reads is a ghost that hands the user an error.
|
||||
const VERILOG: &[&str] = &[
|
||||
"always",
|
||||
"and",
|
||||
"assign",
|
||||
"automatic",
|
||||
"begin",
|
||||
"buf",
|
||||
"bufif0",
|
||||
"bufif1",
|
||||
"case",
|
||||
"casex",
|
||||
"casez",
|
||||
"cell",
|
||||
"cmos",
|
||||
"config",
|
||||
"deassign",
|
||||
"default",
|
||||
"defparam",
|
||||
"design",
|
||||
"disable",
|
||||
"edge",
|
||||
"else",
|
||||
"end",
|
||||
"endcase",
|
||||
"endconfig",
|
||||
"endfunction",
|
||||
"endgenerate",
|
||||
"endmodule",
|
||||
"endprimitive",
|
||||
"endspecify",
|
||||
"endtable",
|
||||
"endtask",
|
||||
"event",
|
||||
"for",
|
||||
"force",
|
||||
"forever",
|
||||
"fork",
|
||||
"function",
|
||||
"generate",
|
||||
"genvar",
|
||||
"highz0",
|
||||
"highz1",
|
||||
"if",
|
||||
"ifnone",
|
||||
"incdir",
|
||||
"include",
|
||||
"initial",
|
||||
"inout",
|
||||
"input",
|
||||
"instance",
|
||||
"integer",
|
||||
"join",
|
||||
"large",
|
||||
"liblist",
|
||||
"library",
|
||||
"localparam",
|
||||
"macromodule",
|
||||
"medium",
|
||||
"module",
|
||||
"nand",
|
||||
"negedge",
|
||||
"nmos",
|
||||
"nor",
|
||||
"noshowcancelled",
|
||||
"not",
|
||||
"notif0",
|
||||
"notif1",
|
||||
"or",
|
||||
"output",
|
||||
"parameter",
|
||||
"pmos",
|
||||
"posedge",
|
||||
"primitive",
|
||||
"pull0",
|
||||
"pull1",
|
||||
"pulldown",
|
||||
"pullup",
|
||||
"pulsestyle_ondetect",
|
||||
"pulsestyle_onevent",
|
||||
"rcmos",
|
||||
"real",
|
||||
"realtime",
|
||||
"reg",
|
||||
"release",
|
||||
"repeat",
|
||||
"rnmos",
|
||||
"rpmos",
|
||||
"rtran",
|
||||
"rtranif0",
|
||||
"rtranif1",
|
||||
"scalared",
|
||||
"showcancelled",
|
||||
"signed",
|
||||
"small",
|
||||
"specify",
|
||||
"specparam",
|
||||
"strong0",
|
||||
"strong1",
|
||||
"supply0",
|
||||
"supply1",
|
||||
"table",
|
||||
"task",
|
||||
"time",
|
||||
"tran",
|
||||
"tranif0",
|
||||
"tranif1",
|
||||
"tri",
|
||||
"tri0",
|
||||
"tri1",
|
||||
"triand",
|
||||
"trior",
|
||||
"trireg",
|
||||
"unsigned",
|
||||
"use",
|
||||
"uwire",
|
||||
"vectored",
|
||||
"wait",
|
||||
"wand",
|
||||
"weak0",
|
||||
"weak1",
|
||||
"while",
|
||||
"wire",
|
||||
"wor",
|
||||
"xnor",
|
||||
"xor",
|
||||
];
|
||||
|
||||
/// The keyword ghost for the word ending at `position`, or `None`.
|
||||
///
|
||||
/// `last` is the index of the token ending exactly at the cursor — the
|
||||
/// caller's `last_token` — and `selected` the popup's selected entry, when
|
||||
/// the client said one is showing.
|
||||
pub(super) fn keyword_ghost(
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
last: usize,
|
||||
position: Position,
|
||||
selected: Option<&SelectedCompletionInfo>,
|
||||
) -> Option<InlineItems> {
|
||||
if !ws.client_settings().inline_keywords.unwrap_or(true) {
|
||||
return None;
|
||||
}
|
||||
let (word, start) = typed_word(doc, last)?;
|
||||
// A name this buffer declares is what the user is typing, not the front
|
||||
// of a keyword: `in`, `re`, `out` as signals stay quiet (fix round).
|
||||
if doc.semantics.symbols().iter().any(|symbol| symbol.name == word) {
|
||||
return None;
|
||||
}
|
||||
let dialect = templates::dialect(doc.path.as_deref());
|
||||
// A selection that does not cover exactly the typed word is about some
|
||||
// other text, and is read as no selection at all — never echoed back.
|
||||
let word_range = Range { start: doc.positions().position(start), end: position };
|
||||
let selected = selected.filter(|info| info.range == word_range);
|
||||
let (keyword, range) = match selected {
|
||||
// An explicit selection wins over the finished-keyword rule: `end`
|
||||
// with `endmodule` selected ghosts `endmodule`.
|
||||
Some(info) => {
|
||||
let text = info.text.as_str();
|
||||
(reserved_extension(word, text, dialect).then_some(text)?, info.range)
|
||||
}
|
||||
None => (best_keyword(word, dialect)?, Range { start: position, end: position }),
|
||||
};
|
||||
// Without a selection the item inserts at the cursor, as every other
|
||||
// ghost here does; with one it must replace the selection's range with
|
||||
// the whole word, which is the shape the client compares against.
|
||||
let value = match selected {
|
||||
Some(_) => keyword.to_string(),
|
||||
None => keyword[word.len()..].to_string(),
|
||||
};
|
||||
Some(InlineItems {
|
||||
items: vec![InlineItem { insert_text: SnippetValue { kind: "snippet", value }, range }],
|
||||
})
|
||||
}
|
||||
|
||||
/// The word a keyword ghost may extend: the token at `last` when it is a
|
||||
/// plain identifier or a keyword, at least [`MIN_WORD`] long, spelled with
|
||||
/// identifier characters only, and not a member name after a `.` or `::`.
|
||||
///
|
||||
/// A macro use (`` `alw ``), an escaped identifier and a `$system` name all
|
||||
/// fail the character test or the kind test; a comment and a string never
|
||||
/// produce a token ending at the cursor at all.
|
||||
fn typed_word(doc: &Document, last: usize) -> Option<(&str, u32)> {
|
||||
let token = doc.tokens.get(last)?;
|
||||
if !matches!(token.kind, TokenKind::Ident | TokenKind::Keyword) {
|
||||
return None;
|
||||
}
|
||||
let text = token.text.as_str();
|
||||
let plain = text.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
|
||||
&& text.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
|
||||
if !plain || text.len() < MIN_WORD {
|
||||
return None;
|
||||
}
|
||||
let after_separator = last
|
||||
.checked_sub(1)
|
||||
.and_then(|i| doc.tokens.get(i))
|
||||
.is_some_and(|prev| prev.is_sym(".") || prev.is_sym("::") || prev.is_sym("`"));
|
||||
(!after_separator).then_some((text, token.span.start))
|
||||
}
|
||||
|
||||
/// The keyword to ghost behind `word` with no popup selection to follow.
|
||||
fn best_keyword(word: &str, dialect: Dialect) -> Option<&'static str> {
|
||||
if let Some(first) = PRIORITY.iter().copied().find(|kw| extends(word, kw, dialect)) {
|
||||
return Some(first);
|
||||
}
|
||||
KEYWORDS
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|kw| extends(word, kw, dialect))
|
||||
.min_by(|a, b| a.len().cmp(&b.len()).then(a.cmp(b)))
|
||||
}
|
||||
|
||||
/// Whether `keyword` is a reserved word of `dialect` that properly extends
|
||||
/// `word` — across an underscore only, when `word` is already a keyword.
|
||||
fn extends(word: &str, keyword: &str, dialect: Dialect) -> bool {
|
||||
reserved_extension(word, keyword, dialect)
|
||||
&& (!KEYWORDS.contains(&word) || keyword.as_bytes()[word.len()] == b'_')
|
||||
}
|
||||
|
||||
/// Whether `keyword` is a reserved word of `dialect` that properly extends
|
||||
/// `word` — the whole test for a keyword the popup has selected.
|
||||
fn reserved_extension(word: &str, keyword: &str, dialect: Dialect) -> bool {
|
||||
keyword.len() > word.len()
|
||||
&& keyword.starts_with(word)
|
||||
&& KEYWORDS.contains(&keyword)
|
||||
&& (dialect == Dialect::SystemVerilog || VERILOG.contains(&keyword))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::inline::inline_completions_in_context;
|
||||
use crate::settings::ClientSettings;
|
||||
use lsp_types::Uri;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// The ghosts at the end of `needle` in `text`, opened as `/rtl/top.sv`,
|
||||
/// as `(value, range)` pairs.
|
||||
fn ghosts(
|
||||
text: &str,
|
||||
needle: &str,
|
||||
selected: Option<SelectedCompletionInfo>,
|
||||
settings: ClientSettings,
|
||||
) -> Vec<(String, Range)> {
|
||||
let uri = Uri::from_str("file:///rtl/top.sv").expect("uri");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(settings);
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let offset = (text.find(needle).expect("needle") + needle.len()) as u32;
|
||||
let position = doc.positions().position(offset);
|
||||
inline_completions_in_context(&ws, &uri, position, selected.as_ref())
|
||||
.map(|found| {
|
||||
found.items.into_iter().map(|item| (item.insert_text.value, item.range)).collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn plain(text: &str, needle: &str) -> Vec<String> {
|
||||
ghosts(text, needle, None, ClientSettings::default())
|
||||
.into_iter()
|
||||
.map(|(value, _)| value)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn at(line: u32, character: u32) -> Position {
|
||||
Position { line, character }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_keyword_prefix_grows_the_rest_of_the_keyword_at_the_cursor() {
|
||||
let text = "module top;\n alw\nendmodule\n";
|
||||
let found = ghosts(text, " alw", None, ClientSettings::default());
|
||||
let cursor = at(1, 5);
|
||||
assert_eq!(found, vec![("ays_ff".to_string(), Range { start: cursor, end: cursor })]);
|
||||
assert_eq!(
|
||||
plain("module top;\n logic a;\n assign a = 1;\n endm\n", " endm"),
|
||||
["odule"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_popups_selection_is_followed_over_its_own_range() {
|
||||
let text = "module top;\n alw\nendmodule\n";
|
||||
let range = Range { start: at(1, 2), end: at(1, 5) };
|
||||
let selected = SelectedCompletionInfo { range, text: "always_comb".to_string() };
|
||||
let found = ghosts(text, " alw", Some(selected), ClientSettings::default());
|
||||
assert_eq!(found, vec![("always_comb".to_string(), range)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_that_is_not_a_keyword_extension_silences_the_ghost() {
|
||||
let text = "module top;\n logic alw_q;\n alw\nendmodule\n";
|
||||
let range = Range { start: at(2, 2), end: at(2, 5) };
|
||||
let selected = SelectedCompletionInfo { range, text: "alw_q".to_string() };
|
||||
assert!(ghosts(text, "\n alw", Some(selected), ClientSettings::default()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_ghost_after_a_separator_in_a_comment_or_for_one_letter() {
|
||||
assert!(plain("module top;\n assign x = s.al\nendmodule\n", "s.al").is_empty());
|
||||
assert!(plain("module top;\n import p::al\nendmodule\n", "p::al").is_empty());
|
||||
assert!(plain("module top;\n // alw\nendmodule\n", "// alw").is_empty());
|
||||
assert!(plain("module top;\n a\nendmodule\n", " a").is_empty());
|
||||
assert!(plain("module top;\n `alw\nendmodule\n", "`alw").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_ghost_when_the_rest_of_the_line_is_written() {
|
||||
assert!(plain("module top;\n alw x;\nendmodule\n", " alw").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_setting_turns_keyword_ghosts_off_and_leaves_templates_on() {
|
||||
let off = ClientSettings { inline_keywords: Some(false), ..Default::default() };
|
||||
let text = "module top;\n alw\nendmodule\n";
|
||||
assert!(ghosts(text, " alw", None, off.clone()).is_empty());
|
||||
let text = "module top;\n always_comb begin\n if (\n end\nendmodule\n";
|
||||
assert_eq!(ghosts(text, "if (", None, off).len(), 1, "the template ghost is untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_template_trigger_wins_over_the_keyword_ghost() {
|
||||
// `begin` is a finished keyword and a trigger: its ghost is the block.
|
||||
let text = "module top;\n initial begin\nendmodule\n";
|
||||
assert_eq!(plain(text, "initial begin"), ["\n\t$0\nend"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_priority_list_picks_among_several_extensions() {
|
||||
let sv = Dialect::SystemVerilog;
|
||||
assert_eq!(best_keyword("al", sv), Some("always_ff"));
|
||||
assert_eq!(best_keyword("always_c", sv), Some("always_comb"));
|
||||
assert_eq!(best_keyword("as", sv), Some("assign"));
|
||||
assert_eq!(best_keyword("lo", sv), Some("logic"));
|
||||
assert_eq!(best_keyword("endm", sv), Some("endmodule"));
|
||||
assert_eq!(best_keyword("par", sv), Some("parameter"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outside_the_list_the_shortest_then_alphabetical_keyword_wins() {
|
||||
assert_eq!(best_keyword("tr", Dialect::SystemVerilog), Some("tri"), "tri before tran");
|
||||
assert_eq!(best_keyword("tri", Dialect::SystemVerilog), None, "`tri` is finished");
|
||||
assert_eq!(best_keyword("xn", Dialect::SystemVerilog), Some("xnor"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finished_keyword_only_grows_across_an_underscore() {
|
||||
let sv = Dialect::SystemVerilog;
|
||||
assert_eq!(best_keyword("always", sv), Some("always_ff"));
|
||||
assert_eq!(best_keyword("end", sv), None, "`end` is finished");
|
||||
assert_eq!(best_keyword("for", sv), None, "`for` is finished");
|
||||
assert_eq!(best_keyword("case", sv), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_verilog_buffer_is_only_offered_verilog_words() {
|
||||
let v = Dialect::Verilog;
|
||||
assert_eq!(best_keyword("al", v), Some("always"));
|
||||
assert_eq!(best_keyword("lo", v), Some("localparam"), "no `logic` in a .v file");
|
||||
assert_eq!(best_keyword("always", v), None, "no `always_ff` either");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_listed_word_is_a_reserved_word_the_lexer_knows() {
|
||||
for word in PRIORITY {
|
||||
assert!(KEYWORDS.contains(word), "{word}");
|
||||
}
|
||||
}
|
||||
|
||||
/// QA (2026-11-17): the shape an unbridged client sends — VS Code's
|
||||
/// `Range` serialized by its `toJSON` as `[start, end]`, trigger kind 0 —
|
||||
/// still decodes (serde reads a struct from a sequence), so the
|
||||
/// extension's middleware is a spelling fix, not what keeps the request
|
||||
/// alive.
|
||||
#[test]
|
||||
fn qa_an_array_shaped_range_and_a_zero_trigger_kind_still_decode() {
|
||||
let params: lsp_types::InlineCompletionParams = serde_json::from_value(serde_json::json!({
|
||||
"textDocument": { "uri": "file:///rtl/top.sv" },
|
||||
"position": { "line": 1, "character": 5 },
|
||||
"context": {
|
||||
"triggerKind": 0,
|
||||
"selectedCompletionInfo": {
|
||||
"range": [{ "line": 1, "character": 2 }, { "line": 1, "character": 5 }],
|
||||
"text": "always_comb"
|
||||
}
|
||||
}
|
||||
}))
|
||||
.expect("decodes");
|
||||
let selected = params.context.selected_completion_info.expect("kept");
|
||||
assert_eq!(selected.range, Range { start: at(1, 2), end: at(1, 5) });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_extends_a_word_that_is_no_keyword_prefix() {
|
||||
assert_eq!(best_keyword("clk", Dialect::SystemVerilog), None);
|
||||
assert!(extends("al", "always", Dialect::SystemVerilog));
|
||||
assert!(!extends("Al", "always", Dialect::SystemVerilog), "case matters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_this_buffer_declares_grows_no_keyword() {
|
||||
let text = "module top;\n logic re, in;\n assign x = re\nendmodule\n";
|
||||
assert!(plain(text, "= re").is_empty(), "`re` is a signal here, not `return`");
|
||||
// An undeclared word still ghosts, expression position or not.
|
||||
let text = "module top;\n assign x = ou\nendmodule\n";
|
||||
assert_eq!(plain(text, "= ou"), ["tput"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicit_selection_wins_over_the_finished_keyword_rule() {
|
||||
let text = "module top;\n logic a;\n end\nendmodule\n";
|
||||
assert!(plain(text, "\n end").is_empty(), "no popup: `end` is finished");
|
||||
let range = Range { start: at(2, 2), end: at(2, 5) };
|
||||
let selected = SelectedCompletionInfo { range, text: "endmodule".to_string() };
|
||||
let found = ghosts(text, "\n end", Some(selected), ClientSettings::default());
|
||||
assert_eq!(found, vec![("endmodule".to_string(), range)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_over_some_other_range_is_read_as_no_selection() {
|
||||
let text = "module top;\n alw\nendmodule\n";
|
||||
let cursor = at(1, 5);
|
||||
for range in [
|
||||
Range { start: at(1, 2), end: at(1, 4) },
|
||||
Range { start: at(1, 3), end: cursor },
|
||||
Range { start: at(0, 0), end: at(0, 6) },
|
||||
] {
|
||||
let selected = SelectedCompletionInfo { range, text: "always_comb".to_string() };
|
||||
let found = ghosts(text, " alw", Some(selected), ClientSettings::default());
|
||||
assert_eq!(
|
||||
found,
|
||||
vec![("ays_ff".to_string(), Range { start: cursor, end: cursor })],
|
||||
"{range:?} is never echoed back"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -354,6 +354,7 @@ mod tests {
|
||||
use super::*;
|
||||
use lsp_types::{Position, Range};
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// A fast-path document over `text`.
|
||||
fn large(text: &str) -> Document {
|
||||
@@ -793,51 +794,44 @@ mod tests {
|
||||
/// on it. The same four sizes are **1.7 / 3.3 / 6.4 / 13.2 ms** — 2x for
|
||||
/// 2x, and 596x faster at the top.
|
||||
///
|
||||
/// The bound is wall-clock, loose, and in debug (this test runs in the
|
||||
/// normal suite): ~4x the measured debug cost of the largest size, which
|
||||
/// the quadratic version overshoots by more than two orders of magnitude.
|
||||
/// A regression in *kind* fails it; a slow CI box does not.
|
||||
/// The bound is on the **shape** of the cost, not its size: the fastest
|
||||
/// of five timings at each size, and the largest size (8x the tokens of
|
||||
/// the smallest) may cost at most [`GROWTH_SLACK`] times 8x the smallest.
|
||||
/// Linear is ~8x; the quadratic version is ~64x (73x in the release
|
||||
/// numbers above). A wall-clock ceiling was here first and failed on the
|
||||
/// CPU-capped Linux runner in debug, where everything is ~15x slower but
|
||||
/// still 2x for 2x; a ratio holds on any machine. Shown to trip, with the
|
||||
/// per-call converter put back into `tokens::flatten`, in
|
||||
/// `docs/features/linux-test-portability/README.md`.
|
||||
#[test]
|
||||
fn a_window_of_many_tokens_on_one_line_colours_in_linear_time() {
|
||||
use std::time::Instant;
|
||||
for count in [5_000u32, 10_000, 20_000, 40_000] {
|
||||
// One line: `module m; wire a0,a1,...,last;` — realistic in shape
|
||||
// (a wide declaration), synthetic only in how wide.
|
||||
let mut text = String::from("module m; wire ");
|
||||
for n in 0..count {
|
||||
text.push_str(&format!("a{n},"));
|
||||
}
|
||||
text.push_str("last;\nendmodule\n");
|
||||
let doc = large(&text);
|
||||
let clock = Instant::now();
|
||||
let window = window(&doc, range(0, 1));
|
||||
let lex_elapsed = clock.elapsed();
|
||||
assert!(!window.tokens.is_empty());
|
||||
let clock2 = Instant::now();
|
||||
let data = crate::tokens::semantic_tokens_in_window(&doc, range(0, 1));
|
||||
let colour_elapsed = clock2.elapsed();
|
||||
eprintln!(
|
||||
"{count} tokens, {}-byte line: lex {lex_elapsed:?}, colour {colour_elapsed:?}, \
|
||||
{} tokens answered",
|
||||
text.len(),
|
||||
data.len() / 5
|
||||
);
|
||||
assert!(!data.is_empty(), "the window really did colour something");
|
||||
assert!(
|
||||
colour_elapsed.as_millis() < COLOUR_BUDGET_MS,
|
||||
"colouring {count} tokens on one line cost {colour_elapsed:?} — \
|
||||
the quadratic conversion is back"
|
||||
);
|
||||
let sizes = [5_000u32, 10_000, 20_000, 40_000];
|
||||
let docs: Vec<Document> = sizes
|
||||
.iter()
|
||||
.map(|&count| {
|
||||
// One line: `module m; wire a0,a1,...,last;` — realistic in
|
||||
// shape (a wide declaration), synthetic only in how wide.
|
||||
let mut text = String::from("module m; wire ");
|
||||
for n in 0..count {
|
||||
text.push_str(&format!("a{n},"));
|
||||
}
|
||||
text.push_str("last;\nendmodule\n");
|
||||
large(&text)
|
||||
})
|
||||
.collect();
|
||||
for doc in &docs {
|
||||
assert!(!window(doc, range(0, 1)).tokens.is_empty());
|
||||
}
|
||||
let costs = fastest_of_five(&docs, |doc| {
|
||||
let clock = Instant::now();
|
||||
let data = crate::tokens::semantic_tokens_in_window(doc, range(0, 1));
|
||||
let elapsed = clock.elapsed();
|
||||
assert!(!data.is_empty(), "the window really did colour something");
|
||||
elapsed
|
||||
});
|
||||
assert_grows_linearly(&sizes, &costs, "colouring tokens on one line");
|
||||
}
|
||||
|
||||
/// The wall-clock ceiling the test above holds the colourer to, in a
|
||||
/// **debug** build: 4.5x the slowest of the four sizes as measured on the
|
||||
/// machine this was written on (77 ms at 40,000 tokens, ±0.5 ms over
|
||||
/// four runs), where the quadratic version this replaced would need tens
|
||||
/// of seconds.
|
||||
const COLOUR_BUDGET_MS: u128 = 350;
|
||||
|
||||
/// **QA finding 1 (2026-08-27), fixed and now a gate**, on the *other*
|
||||
/// fast-path consumer of `Positions`: `references`' hits still have to
|
||||
/// become `lsp_types::Location`s (`Server::large_scan`, `server.rs`), one
|
||||
@@ -848,50 +842,82 @@ mod tests {
|
||||
///
|
||||
/// `large_scan` now walks the hits with one `Positions::walker`, which
|
||||
/// they are already in ascending order for. This runs at an eighth of the
|
||||
/// original probe's line lengths so it can live in the normal suite; the
|
||||
/// bound is debug wall-clock and ~4x the measured cost, which a return of
|
||||
/// the per-hit rescan overshoots by two orders of magnitude.
|
||||
/// original probe's line lengths so it can live in the normal suite. The
|
||||
/// hits and the line both grow with `width`, so the walker's work (each
|
||||
/// byte of the line once) is linear in it and the per-hit rescan's (the
|
||||
/// line once per hit) quadratic; the bound is the same shape check as the
|
||||
/// colour test's above, and shown to trip the same way.
|
||||
#[test]
|
||||
fn references_on_one_giant_line_locate_their_hits_in_linear_time() {
|
||||
use std::time::Instant;
|
||||
for width in [100u32, 200, 400, 800] {
|
||||
// One line: `wire sig;` filler `sig` filler `sig` ... — `width`
|
||||
// occurrences of the needle spread over one line, all comfortably
|
||||
// under REFERENCE_LIMIT so the cap is not what is being timed.
|
||||
let mut text = String::from("wire sig;");
|
||||
for _ in 0..width {
|
||||
text.push_str(&" filler_word ".repeat(250));
|
||||
text.push_str("sig");
|
||||
}
|
||||
text.push('\n');
|
||||
let doc = large(&text);
|
||||
let clock = Instant::now();
|
||||
let hits = references(&doc, 5, true);
|
||||
let scan_elapsed = clock.elapsed();
|
||||
assert_eq!(hits.len() as u32, width + 1, "the declaration plus every use");
|
||||
let sizes = [100u32, 200, 400, 800];
|
||||
let docs: Vec<(Document, Vec<TextRange>)> = sizes
|
||||
.iter()
|
||||
.map(|&width| {
|
||||
// One line: `wire sig;` filler `sig` filler `sig` ... —
|
||||
// `width` occurrences of the needle spread over one line, all
|
||||
// comfortably under REFERENCE_LIMIT so the cap is not what is
|
||||
// being timed.
|
||||
let mut text = String::from("wire sig;");
|
||||
for _ in 0..width {
|
||||
text.push_str(&" filler_word ".repeat(250));
|
||||
text.push_str("sig");
|
||||
}
|
||||
text.push('\n');
|
||||
let doc = large(&text);
|
||||
let hits = references(&doc, 5, true);
|
||||
assert_eq!(hits.len() as u32, width + 1, "the declaration plus every use");
|
||||
(doc, hits)
|
||||
})
|
||||
.collect();
|
||||
let costs = fastest_of_five(&docs, |(doc, hits)| {
|
||||
let positions = doc.positions();
|
||||
let clock2 = Instant::now();
|
||||
let clock = Instant::now();
|
||||
// Exactly what `Server::large_scan` does with them.
|
||||
let mut walker = positions.walker();
|
||||
for hit in &hits {
|
||||
for hit in hits {
|
||||
std::hint::black_box(walker.range(*hit));
|
||||
}
|
||||
let locate_elapsed = clock2.elapsed();
|
||||
eprintln!(
|
||||
"{width} hits on one {}-byte line: scan {scan_elapsed:?}, locate {locate_elapsed:?}",
|
||||
text.len()
|
||||
);
|
||||
assert!(
|
||||
locate_elapsed.as_millis() < LOCATE_BUDGET_MS,
|
||||
"locating {width} hits on one line cost {locate_elapsed:?} — \
|
||||
the per-hit line rescan is back"
|
||||
);
|
||||
}
|
||||
clock.elapsed()
|
||||
});
|
||||
assert_grows_linearly(&sizes, &costs, "locating hits on one line");
|
||||
}
|
||||
|
||||
/// The wall-clock ceiling for the locator above, in a **debug** build:
|
||||
/// 4.7x the slowest of the four sizes as measured on the machine this was
|
||||
/// written on (32 ms at 800 hits on a 2.6 MB line, ±0.2 ms over four
|
||||
/// runs).
|
||||
const LOCATE_BUDGET_MS: u128 = 150;
|
||||
/// How much faster than its input a linear-time test's cost may grow
|
||||
/// before it fails: 3x, so 24x for an 8x input, where linear measures
|
||||
/// ~8x (macOS and the Linux runner alike) and quadratic ~64x.
|
||||
const GROWTH_SLACK: f64 = 3.0;
|
||||
|
||||
/// The fastest of five timings of `run` on each input. The rounds go over
|
||||
/// all the inputs in turn, so a burst of load from the tests running
|
||||
/// beside this one slows one sample of each size rather than every sample
|
||||
/// of one. Five, not three: QA saw 18.2x of the 24x limit at three under
|
||||
/// 2x CPU oversubscription, and more rounds is the margin that does not
|
||||
/// loosen what the test can see.
|
||||
fn fastest_of_five<T>(inputs: &[T], mut run: impl FnMut(&T) -> Duration) -> Vec<Duration> {
|
||||
let mut fastest = vec![Duration::MAX; inputs.len()];
|
||||
for _ in 0..5 {
|
||||
for (best, input) in fastest.iter_mut().zip(inputs) {
|
||||
*best = (*best).min(run(input));
|
||||
}
|
||||
}
|
||||
fastest
|
||||
}
|
||||
|
||||
/// Fails unless the cost at the largest size is within [`GROWTH_SLACK`]
|
||||
/// of linear growth from the smallest.
|
||||
#[track_caller]
|
||||
fn assert_grows_linearly(sizes: &[u32], costs: &[Duration], what: &str) {
|
||||
for (size, cost) in sizes.iter().zip(costs) {
|
||||
eprintln!("{what}: {size} → {cost:?}");
|
||||
}
|
||||
let (first, last) = (sizes[0], sizes[sizes.len() - 1]);
|
||||
let input = f64::from(last) / f64::from(first);
|
||||
let growth =
|
||||
costs[costs.len() - 1].as_secs_f64() / costs[0].as_secs_f64().max(f64::MIN_POSITIVE);
|
||||
assert!(
|
||||
growth <= GROWTH_SLACK * input,
|
||||
"{what}: {input}x the input cost {growth:.1}x the time ({costs:?}) — \
|
||||
more than {GROWTH_SLACK}x linear, the quadratic conversion is back"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
//! `vlog_parser`, `vlog_semantic` or `vlog_formatter`. See
|
||||
//! `docs/features/lucisv-server/README.md`.
|
||||
|
||||
mod auto_style;
|
||||
mod candidates;
|
||||
mod code_action;
|
||||
mod completion;
|
||||
@@ -117,6 +118,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
// capabilities have no field for it and drop it on the floor — see
|
||||
// `ranges_formatting_support`.
|
||||
let ranges_formatting = ranges_formatting_support(¶ms);
|
||||
let diagnostic_refresh = diagnostic_refresh_support(¶ms);
|
||||
// Read from the raw params for the same reason, and because it is not a
|
||||
// capability at all: `initializationOptions` is whatever the client's
|
||||
// extension put there.
|
||||
@@ -133,6 +135,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
pull_diagnostics: pull_diagnostics_support(¶ms),
|
||||
work_done_progress: work_done_progress_support(¶ms),
|
||||
code_lens_refresh: code_lens_refresh_support(¶ms),
|
||||
diagnostic_refresh,
|
||||
show_document: show_document_support(¶ms),
|
||||
configuration: configuration_support(¶ms),
|
||||
token_server_cancel: token_server_cancel_support(¶ms),
|
||||
@@ -645,6 +648,21 @@ fn code_lens_refresh_support(params: &InitializeParams) -> bool {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the client can be asked to pull its diagnostics again
|
||||
/// (`workspace/diagnostic/refresh`), read from the **raw** `initialize`
|
||||
/// params.
|
||||
///
|
||||
/// Server-initiated, so the spec makes this capability the gate, exactly as
|
||||
/// for the code-lens refresh. It has to be the raw JSON: the protocol's key is
|
||||
/// `workspace.diagnostics`, and `lsp-types` 0.97 spells its field
|
||||
/// `diagnostic` with no rename, so the typed decode never sees what VS Code
|
||||
/// sends. Anything but a literal `true` means no. Sent when a connection entry
|
||||
/// held back while it was typed is released
|
||||
/// (`docs/features/port-entry-grace/README.md`).
|
||||
fn diagnostic_refresh_support(params: &serde_json::Value) -> bool {
|
||||
params["capabilities"]["workspace"]["diagnostics"]["refreshSupport"] == true
|
||||
}
|
||||
|
||||
/// Whether the client opens a document the server asks it to.
|
||||
///
|
||||
/// This is what makes the instantiation lens actually navigate: an
|
||||
@@ -1352,6 +1370,28 @@ mod tests {
|
||||
assert!(!code_lens_refresh_support(&saying(None)), "an empty `codeLens` is not a yes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostic_refresh_support_is_read_from_the_raw_params_and_only_when_literally_true() {
|
||||
let saying = |refresh: serde_json::Value| {
|
||||
serde_json::json!({
|
||||
"processId": null,
|
||||
"capabilities": { "workspace": { "diagnostics": { "refreshSupport": refresh } } }
|
||||
})
|
||||
};
|
||||
assert!(diagnostic_refresh_support(&saying(serde_json::json!(true))));
|
||||
assert!(!diagnostic_refresh_support(&saying(serde_json::json!(false))));
|
||||
assert!(!diagnostic_refresh_support(&saying(serde_json::json!("yes"))));
|
||||
assert!(!diagnostic_refresh_support(&saying(serde_json::Value::Null)));
|
||||
assert!(!diagnostic_refresh_support(&serde_json::json!({ "capabilities": {} })));
|
||||
assert!(!diagnostic_refresh_support(&serde_json::Value::Null));
|
||||
// The protocol's key is plural; `lsp-types`' singular field name is
|
||||
// not what any client sends, and is not read.
|
||||
let singular = serde_json::json!({
|
||||
"capabilities": { "workspace": { "diagnostic": { "refreshSupport": true } } }
|
||||
});
|
||||
assert!(!diagnostic_refresh_support(&singular));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_document_support_is_read_from_the_clients_own_capabilities() {
|
||||
use lsp_types::{
|
||||
|
||||
@@ -28,6 +28,10 @@ use crate::format;
|
||||
use crate::pairs;
|
||||
use crate::state::{first_token_from, first_token_reaching, Document};
|
||||
|
||||
mod auto_end;
|
||||
|
||||
pub(crate) use auto_end::begin_owes_an_end;
|
||||
|
||||
/// The character the client is told to trigger on. A newline is the one
|
||||
/// keystroke that opens a line whose indentation nobody has chosen yet.
|
||||
pub const NEWLINE: &str = "\n";
|
||||
@@ -40,12 +44,21 @@ pub const SEMICOLON: &str = ";";
|
||||
///
|
||||
/// Never an `Err`: every refusal on this path — an unknown trigger, a client
|
||||
/// out of step, a buffer the formatter will not touch — is the empty answer.
|
||||
///
|
||||
/// `auto_end` is `lucisv.autoEnd`: whether a newline typed after a `begin`
|
||||
/// that still owes its `end` also writes that `end` (see `auto_end.rs`).
|
||||
pub fn on_type_formatting(
|
||||
doc: &Document,
|
||||
position: Position,
|
||||
typed: &str,
|
||||
config: &Config,
|
||||
auto_end: bool,
|
||||
) -> Vec<TextEdit> {
|
||||
if auto_end && typed == NEWLINE {
|
||||
if let Some(edits) = auto_end::begin_newline_edits(doc, position, config.indent_width) {
|
||||
return edits;
|
||||
}
|
||||
}
|
||||
let edit = match typed {
|
||||
NEWLINE => indent_edit(doc, position, config.indent_width),
|
||||
SEMICOLON => statement_edit(doc, position, config),
|
||||
@@ -61,9 +74,9 @@ pub fn on_type_formatting(
|
||||
/// Lay out the statement the `;` just ended, through the range engine.
|
||||
///
|
||||
/// The range asked for is the `;`'s **own line** and nothing else. That is not
|
||||
/// a narrower request than "the statement's lines": `format_range` selects by
|
||||
/// *unit*, so any line of a statement selects the whole statement (see
|
||||
/// `docs/features/range-formatting/README.md`). It is, however, a much safer
|
||||
/// a narrower request than "the statement's lines": `format_selection` selects
|
||||
/// by *unit*, so any line of a statement selects the whole statement (see
|
||||
/// `docs/features/selection-formatting/README.md`). It is, however, a much safer
|
||||
/// one — the `;` closing `module m (\n input a\n);` ends no statement at all,
|
||||
/// and naming its enclosing node's lines there would ask for the whole module
|
||||
/// back on a keystroke.
|
||||
@@ -715,7 +728,7 @@ mod tests {
|
||||
|
||||
fn newline_with(text: &str, line: u32, indent_width: usize) -> Vec<TextEdit> {
|
||||
let at = Position { line, character: 0 };
|
||||
with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(indent_width)))
|
||||
with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(indent_width), false))
|
||||
}
|
||||
|
||||
/// The `new_text` of the single edit a newline produced, or `None` when it
|
||||
@@ -732,7 +745,7 @@ mod tests {
|
||||
let content = source[line as usize].trim_end_matches('\n');
|
||||
let character = content.rfind(';').expect("the line ends a statement") as u32 + 1;
|
||||
let at = Position { line, character };
|
||||
with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)))
|
||||
with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false))
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -793,7 +806,7 @@ mod tests {
|
||||
// it means the client is not talking about a newline it just typed.
|
||||
let text = "module m;\nwire a;\nendmodule\n";
|
||||
let at = Position { line: 1, character: 4 };
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(2)));
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(2), false));
|
||||
assert_eq!(edits, Vec::new());
|
||||
}
|
||||
|
||||
@@ -955,7 +968,7 @@ mod tests {
|
||||
with(text, |doc| {
|
||||
for line in 1..text.lines().count() as u32 {
|
||||
let at = Position { line, character: 0 };
|
||||
for edit in on_type_formatting(doc, at, NEWLINE, &config(2)) {
|
||||
for edit in on_type_formatting(doc, at, NEWLINE, &config(2), false) {
|
||||
assert_eq!(edit.range.start, at, "always column zero of the asked-for line");
|
||||
assert_eq!(edit.range.end.line, line, "and never past that line");
|
||||
let source = doc.text.lines().nth(line as usize).unwrap_or("");
|
||||
@@ -1174,13 +1187,25 @@ mod tests {
|
||||
#[test]
|
||||
fn a_semicolon_in_a_buffer_the_engine_refuses_answers_nothing_at_all() {
|
||||
// Half-typed code is the normal case on this trigger, not a failure.
|
||||
assert_eq!(semicolon("module m;\n wire a;\n wire ;\nendmodule\n", 1), Vec::new());
|
||||
// The error is on the keystroke's own line: one elsewhere in the
|
||||
// buffer no longer refuses (selection-formatting, TODO §66.2).
|
||||
let text = "module m;\n wire a = ;\nendmodule\n";
|
||||
let at = Position { line: 1, character: 13 };
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
|
||||
assert_eq!(edits, Vec::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_semicolon_still_lays_out_its_statement_when_the_error_is_elsewhere() {
|
||||
let edits = semicolon("module m;\n wire a;\n wire ;\nendmodule\n", 1);
|
||||
assert_eq!(edits.len(), 1, "{edits:#?}");
|
||||
assert_eq!(edits[0].new_text, "module m;\n wire a;\n wire ;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_semicolon_that_is_not_where_the_client_said_answers_nothing() {
|
||||
let at = Position { line: 1, character: 3 };
|
||||
let edits = with(MESSY, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
|
||||
let edits = with(MESSY, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
|
||||
assert_eq!(edits, Vec::new());
|
||||
}
|
||||
|
||||
@@ -1191,7 +1216,7 @@ mod tests {
|
||||
assert_eq!(semicolon(text, 1), Vec::new());
|
||||
let text = "module m;\n string s = \"a;\";\n wire a;\nendmodule\n";
|
||||
let at = Position { line: 1, character: 16 };
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
|
||||
assert_eq!(edits, Vec::new(), "the `;` inside the quotes");
|
||||
}
|
||||
|
||||
@@ -1202,12 +1227,12 @@ mod tests {
|
||||
// the whole document.
|
||||
let text = "module m;\n wire a;\nendmodule";
|
||||
let at = Position { line: 1, character: 11 };
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
|
||||
assert_eq!(edits.len(), 1, "{edits:#?}");
|
||||
// The engine's own canonicalization adds the missing final newline —
|
||||
// exactly what `textDocument/rangeFormatting` would also do here, and
|
||||
// not a moved byte this path invented on its own.
|
||||
assert_eq!(edits[0].new_text, "module m;\n wire a;\nendmodule\n");
|
||||
// Only the statement moves: the file's tail is outside the splice, so
|
||||
// the missing final newline stays missing — exactly what
|
||||
// `textDocument/rangeFormatting` answers here too.
|
||||
assert_eq!(edits[0].new_text, "module m;\n wire a;\nendmodule");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1241,7 +1266,7 @@ mod tests {
|
||||
// inside a string or a comment.
|
||||
let text = "`define FOO x = 1;\nmodule m;\nendmodule\n";
|
||||
let at = Position { line: 0, character: 19 };
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
|
||||
assert_eq!(edits, Vec::new(), "no Symbol(;) token ends inside a Directive");
|
||||
}
|
||||
|
||||
@@ -1269,7 +1294,7 @@ mod tests {
|
||||
// guess at what it meant.
|
||||
let at = Position { line: 1, character: 9 };
|
||||
for typed in ["}", ")", "\t", ""] {
|
||||
let edits = with(MESSY, |doc| on_type_formatting(doc, at, typed, &config(2)));
|
||||
let edits = with(MESSY, |doc| on_type_formatting(doc, at, typed, &config(2), false));
|
||||
assert_eq!(edits, Vec::new(), "trigger {typed:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,581 @@
|
||||
//! `begin` + Enter writes the `end` (TODO §68.1).
|
||||
//!
|
||||
//! The newline answer's second half. When the line above the one a `\n` just
|
||||
//! opened ends in `begin` (or `begin : label`) and that block still owes an
|
||||
//! `end`, the answer is two edits instead of one: the new line's body
|
||||
//! indentation, as the plain newline answer would give it, and a line after
|
||||
//! it holding `end` at the indentation of the statement the `begin` belongs
|
||||
//! to. The cursor's line stays blank, so the user types the first statement
|
||||
//! where they already are.
|
||||
//!
|
||||
//! **Which `begin` owes an `end`.** `pairs::analyze` is a stack matcher, so a
|
||||
//! `begin` typed inside a block that already balances *steals* that block's
|
||||
//! `end`: the new inner `begin` comes out matched, and the outer one is
|
||||
//! reported unclosed. "Is *this* `begin` unmatched" is therefore the wrong
|
||||
//! question. The one asked here is: is any `begin` at or before this one
|
||||
//! unclosed — unless this `begin` is matched by an `end` that starts its line
|
||||
//! at exactly the indentation this answer would have written, which is the
|
||||
//! block the user already closed. See `docs/features/completion-ux/README.md`.
|
||||
|
||||
use lsp_types::{Position, Range, TextEdit};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
use super::level_at;
|
||||
use crate::pairs;
|
||||
use crate::state::{first_token_from, Document};
|
||||
|
||||
/// The keywords whose header a `begin` may be the body of. Reading backwards,
|
||||
/// one of these is where the header starts.
|
||||
const HEADER_KEYWORDS: &[&str] = &[
|
||||
"if",
|
||||
"for",
|
||||
"foreach",
|
||||
"while",
|
||||
"repeat",
|
||||
"forever",
|
||||
"always",
|
||||
"always_ff",
|
||||
"always_comb",
|
||||
"always_latch",
|
||||
"initial",
|
||||
"final",
|
||||
];
|
||||
|
||||
/// The words that may stand in front of a header on the same statement:
|
||||
/// `else if`, `unique case`-style qualifiers, and a bare `else` before its
|
||||
/// `begin`.
|
||||
const QUALIFIERS: &[&str] = &["else", "unique", "unique0", "priority"];
|
||||
|
||||
/// The edits for a newline typed right after a `begin` that still owes its
|
||||
/// `end`, or `None` when this newline is not that — the caller then answers
|
||||
/// the plain indentation question instead.
|
||||
pub(super) fn begin_newline_edits(
|
||||
doc: &Document,
|
||||
position: Position,
|
||||
indent_width: usize,
|
||||
) -> Option<Vec<TextEdit>> {
|
||||
let line = NewLine::at(doc, position)?;
|
||||
let begin = begin_ending_line_above(doc, line.range.start)?;
|
||||
let end_indent = owner_indent(doc, begin);
|
||||
if !owes_an_end(doc, begin, &end_indent) {
|
||||
return None;
|
||||
}
|
||||
let body = body_indent(level_at(doc, line.content), &end_indent, indent_width);
|
||||
Some(edits(doc, &line, &body, &end_indent))
|
||||
}
|
||||
|
||||
/// The blank line a `\n` just opened, as far as this answer needs it.
|
||||
struct NewLine {
|
||||
/// The whole line, its `\r` included when the file has one.
|
||||
range: TextRange,
|
||||
/// The end of its leading whitespace.
|
||||
content: u32,
|
||||
/// The line ending the file writes, read off the newline just typed.
|
||||
eol: &'static str,
|
||||
}
|
||||
|
||||
impl NewLine {
|
||||
/// The line at `position`, when a newline opened it, the cursor sits in
|
||||
/// its leading whitespace, and nothing but whitespace is on it — Enter
|
||||
/// pressed in the middle of a line carries text down, and a body that is
|
||||
/// already written owes nothing.
|
||||
fn at(doc: &Document, position: Position) -> Option<NewLine> {
|
||||
let range = doc.line_index.line_range(position.line.checked_add(1)?)?;
|
||||
let bytes = doc.text.as_bytes();
|
||||
if range.start == 0 || bytes.get(range.start as usize - 1) != Some(&b'\n') {
|
||||
return None;
|
||||
}
|
||||
let text = doc.text.get(range.start as usize..range.end as usize)?;
|
||||
let rest = text.trim_start_matches([' ', '\t']);
|
||||
if !rest.trim_end_matches('\r').is_empty() {
|
||||
return None;
|
||||
}
|
||||
let content = range.start + (text.len() - rest.len()) as u32;
|
||||
if doc.positions().offset(position) > content {
|
||||
return None;
|
||||
}
|
||||
let crlf = range.start >= 2 && bytes.get(range.start as usize - 2) == Some(&b'\r');
|
||||
Some(NewLine { range, content, eol: if crlf { "\r\n" } else { "\n" } })
|
||||
}
|
||||
}
|
||||
|
||||
/// The index of the `begin` the line above `line_start` ends with — the last
|
||||
/// token on it, or the one before a `: label` — when it does.
|
||||
///
|
||||
/// Comments are trivia, not tokens, so `begin // why` ends in `begin` here
|
||||
/// without a check of its own.
|
||||
fn begin_ending_line_above(doc: &Document, line_start: u32) -> Option<usize> {
|
||||
let last = first_token_from(&doc.tokens, line_start).checked_sub(1)?;
|
||||
let above = doc.line_index.line_col(line_start).0.checked_sub(1)?;
|
||||
let on_line_above =
|
||||
|index: usize| doc.tokens.get(index).is_some_and(|token| line_of(doc, token) == above);
|
||||
let token = doc.tokens.get(last)?;
|
||||
let begin = match token.kind {
|
||||
TokenKind::Ident if last >= 2 && doc.tokens.get(last - 1)?.is_sym(":") => last - 2,
|
||||
_ => last,
|
||||
};
|
||||
(doc.tokens.get(begin)?.is_kw("begin") && on_line_above(begin) && on_line_above(last))
|
||||
.then_some(begin)
|
||||
}
|
||||
|
||||
/// The leading whitespace of the line the statement owning the `begin` at
|
||||
/// `begin` starts on, as written — tabs stay tabs.
|
||||
///
|
||||
/// Read backwards from the `begin` over what may stand between a statement's
|
||||
/// first token and its body: a parenthesised header, an `@`/`#` control and
|
||||
/// its operand, and [`HEAD_KEYWORDS`]. Anything else — a `;`, an `end`, a
|
||||
/// case item's `:` — is where the statement starts. A header with no `(` to
|
||||
/// match leaves the `begin`'s own line as the answer.
|
||||
fn owner_indent(doc: &Document, begin: usize) -> String {
|
||||
let tokens = &doc.tokens;
|
||||
let mut first = begin;
|
||||
// Once a header keyword is read, only a qualifier may still precede it:
|
||||
// `always_comb` on the line above an `if` is the `if`'s *owner*, not part
|
||||
// of its header.
|
||||
let mut keyword_seen = false;
|
||||
while let Some(prev) = first.checked_sub(1) {
|
||||
let token = &tokens[prev];
|
||||
let step = match keyword_seen {
|
||||
true => is_keyword_in(token, QUALIFIERS).then_some(prev),
|
||||
false => header_step(tokens, prev),
|
||||
};
|
||||
let Some(step) = step else { break };
|
||||
keyword_seen |= is_keyword_in(token, HEADER_KEYWORDS) || is_keyword_in(token, QUALIFIERS);
|
||||
first = step;
|
||||
}
|
||||
line_indent(doc, tokens[first].span.start)
|
||||
}
|
||||
|
||||
/// Where reading a header backwards goes from the token at `prev`: over a
|
||||
/// parenthesised group to its `(`, onto a header keyword, a qualifier, an
|
||||
/// `@`/`#`, or the operand right after one — or nowhere, when `prev` is
|
||||
/// already outside the header.
|
||||
fn header_step(tokens: &[Token], prev: usize) -> Option<usize> {
|
||||
let token = &tokens[prev];
|
||||
if token.is_sym(")") {
|
||||
return matching_open(tokens, prev);
|
||||
}
|
||||
let after_control = prev
|
||||
.checked_sub(1)
|
||||
.and_then(|i| tokens.get(i))
|
||||
.is_some_and(|t| t.is_sym("@") || t.is_sym("#"));
|
||||
let in_header = is_keyword_in(token, HEADER_KEYWORDS)
|
||||
|| is_keyword_in(token, QUALIFIERS)
|
||||
|| token.is_sym("@")
|
||||
|| token.is_sym("#")
|
||||
|| after_control;
|
||||
in_header.then_some(prev)
|
||||
}
|
||||
|
||||
fn is_keyword_in(token: &Token, words: &[&str]) -> bool {
|
||||
token.kind == TokenKind::Keyword && words.contains(&token.text.as_str())
|
||||
}
|
||||
|
||||
/// The `(` the `)` at `close` closes, counting parentheses only.
|
||||
fn matching_open(tokens: &[Token], close: usize) -> Option<usize> {
|
||||
let mut depth = 0u32;
|
||||
for index in (0..=close).rev() {
|
||||
let token = &tokens[index];
|
||||
if token.is_sym(")") {
|
||||
depth += 1;
|
||||
} else if token.is_sym("(") {
|
||||
depth = depth.checked_sub(1)?;
|
||||
if depth == 0 {
|
||||
return Some(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether the block the `begin` at `begin` opens still needs an `end`
|
||||
/// written for it. See the module comment for why this is not "is this
|
||||
/// `begin` unmatched".
|
||||
///
|
||||
/// Two layouts count as "already closed": the `end` under the statement (the
|
||||
/// formatter's own layout) and the `end` under the `begin`'s own line (the GNU
|
||||
/// layout, `begin` on a line of its own — QA finding 1, fix round
|
||||
/// 2026-11-17). And an unmatched `begin` inside a `` `ifdef `` that has an
|
||||
/// `` `else ``/`` `elsif `` arms nothing: two branches each opening a block
|
||||
/// closed by one shared `end` are an unmatched `begin` to the stack matcher
|
||||
/// and complete code to the compiler.
|
||||
fn owes_an_end(doc: &Document, begin: usize, end_indent: &str) -> bool {
|
||||
let span = doc.tokens[begin].span;
|
||||
let own_indent = line_indent(doc, span.start);
|
||||
let analysis = pairs::analyze(&doc.tokens);
|
||||
let closed_here = analysis.pairs.iter().any(|pair| {
|
||||
pair.open == span
|
||||
&& (starts_line_at(doc, pair.close, end_indent)
|
||||
|| starts_line_at(doc, pair.close, &own_indent))
|
||||
});
|
||||
if closed_here {
|
||||
return false;
|
||||
}
|
||||
let branched = branched_regions(&doc.tokens);
|
||||
analysis.unmatched_open.iter().any(|open| {
|
||||
open.keyword == "begin"
|
||||
&& open.span.start <= span.start
|
||||
&& !branched.iter().any(|region| region.contains(&open.span.start))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the `begin` at token index `begin` opens a block that still needs
|
||||
/// an `end` — [`owes_an_end`] with the `end` at its owner's indentation. The
|
||||
/// inline `begin` ghost asks the same question.
|
||||
pub(crate) fn begin_owes_an_end(doc: &Document, begin: usize) -> bool {
|
||||
owes_an_end(doc, begin, &owner_indent(doc, begin))
|
||||
}
|
||||
|
||||
/// The byte ranges of every `` `ifdef ``/`` `ifndef `` … `` `endif `` region
|
||||
/// that holds an `` `else `` or `` `elsif `` of its own. A region never closed
|
||||
/// runs to the end of the buffer.
|
||||
fn branched_regions(tokens: &[Token]) -> Vec<std::ops::Range<u32>> {
|
||||
let mut open: Vec<(u32, bool)> = Vec::new();
|
||||
let mut out = Vec::new();
|
||||
for token in tokens {
|
||||
match conditional(token) {
|
||||
Some("`ifdef" | "`ifndef") => open.push((token.span.start, false)),
|
||||
Some("`else" | "`elsif") => {
|
||||
if let Some(last) = open.last_mut() {
|
||||
last.1 = true;
|
||||
}
|
||||
}
|
||||
Some("`endif") => {
|
||||
if let Some((start, true)) = open.pop() {
|
||||
out.push(start..token.span.end);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let end = tokens.last().map_or(0, |token| token.span.end);
|
||||
out.extend(open.into_iter().filter(|(_, branched)| *branched).map(|(start, _)| start..end));
|
||||
out
|
||||
}
|
||||
|
||||
/// The conditional-compilation directive a token spells, by its first word.
|
||||
fn conditional(token: &Token) -> Option<&str> {
|
||||
let word = token.text.split_whitespace().next()?;
|
||||
matches!(word, "`ifdef" | "`ifndef" | "`else" | "`elsif" | "`endif").then_some(word)
|
||||
}
|
||||
|
||||
/// Whether `span` is the first thing on its line and that line is indented
|
||||
/// by exactly `indent`.
|
||||
fn starts_line_at(doc: &Document, span: TextRange, indent: &str) -> bool {
|
||||
let line = doc.line_index.line_col(span.start).0;
|
||||
let Some(range) = doc.line_index.line_range(line) else { return false };
|
||||
doc.text.get(range.start as usize..span.start as usize) == Some(indent)
|
||||
}
|
||||
|
||||
/// The body line's indentation: the nesting model's answer when it has one
|
||||
/// that sits inside the `end`, else one step in from the `end`. A file
|
||||
/// indented with tabs gets one more tab — the model speaks spaces, and mixing
|
||||
/// the two on adjacent lines would be worse than either.
|
||||
fn body_indent(level: Option<usize>, end_indent: &str, indent_width: usize) -> String {
|
||||
if end_indent.contains('\t') {
|
||||
return format!("{end_indent}\t");
|
||||
}
|
||||
match level {
|
||||
Some(level) if level * indent_width > end_indent.len() => " ".repeat(level * indent_width),
|
||||
_ => format!("{end_indent}{}", " ".repeat(indent_width)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The edits themselves: re-indent the new line when it needs it, and write
|
||||
/// the `end` line after it.
|
||||
///
|
||||
/// The `end` goes in at the **start of the following line** whenever there is
|
||||
/// one, so no edit touches the cursor's own position and an editor applying
|
||||
/// them leaves the cursor on the body line. The new line being the file's last
|
||||
/// is the one case with nowhere else to put it, and there the two are one
|
||||
/// edit.
|
||||
fn edits(doc: &Document, line: &NewLine, body: &str, end_indent: &str) -> Vec<TextEdit> {
|
||||
let positions = doc.positions();
|
||||
let start = positions.position(line.range.start);
|
||||
let indent = Range { start, end: positions.position(line.content) };
|
||||
let end_line = format!("{end_indent}end");
|
||||
if line.range.end as usize >= doc.text.len() {
|
||||
let new_text = format!("{body}{}{end_line}", line.eol);
|
||||
return vec![TextEdit {
|
||||
range: Range { start, end: positions.position(line.range.end) },
|
||||
new_text,
|
||||
}];
|
||||
}
|
||||
let mut edits = Vec::new();
|
||||
if doc.text.get(line.range.start as usize..line.content as usize) != Some(body) {
|
||||
edits.push(TextEdit { range: indent, new_text: body.to_string() });
|
||||
}
|
||||
let next = positions.position(line.range.end + 1);
|
||||
edits.push(TextEdit {
|
||||
range: Range { start: next, end: next },
|
||||
new_text: format!("{end_line}{}", line.eol),
|
||||
});
|
||||
edits
|
||||
}
|
||||
|
||||
/// The 1-based line a token starts on.
|
||||
fn line_of(doc: &Document, token: &Token) -> u32 {
|
||||
doc.line_index.line_col(token.span.start).0
|
||||
}
|
||||
|
||||
/// The leading whitespace of the line holding `offset`.
|
||||
fn line_indent(doc: &Document, offset: u32) -> String {
|
||||
let line = doc.line_index.line_col(offset).0;
|
||||
let Some(range) = doc.line_index.line_range(line) else { return String::new() };
|
||||
let text = doc.text.get(range.start as usize..range.end as usize).unwrap_or("");
|
||||
text[..text.len() - text.trim_start_matches([' ', '\t']).len()].to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::on_type::{on_type_formatting, NEWLINE};
|
||||
use crate::state::Workspace;
|
||||
use lsp_types::Uri;
|
||||
use std::str::FromStr;
|
||||
use vlog_formatter::Config;
|
||||
|
||||
/// The buffer after the newline answer for a `\n` that opened `line`
|
||||
/// (0-based), with `lucisv.autoEnd` as given — and the edits themselves.
|
||||
fn typed(text: &str, line: u32, auto_end: bool) -> (String, Vec<TextEdit>) {
|
||||
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 doc = ws.document(&uri).expect("open");
|
||||
let at = Position { line, character: 0 };
|
||||
let config = Config { indent_width: 2, ..Config::default() };
|
||||
let edits = on_type_formatting(doc, at, NEWLINE, &config, auto_end);
|
||||
(apply(doc, &edits), edits)
|
||||
}
|
||||
|
||||
/// `edits` applied to the buffer, last first so the offsets stay true.
|
||||
fn apply(doc: &Document, edits: &[TextEdit]) -> String {
|
||||
let mut spans: Vec<(usize, usize, &str)> = edits
|
||||
.iter()
|
||||
.map(|edit| {
|
||||
let start = doc.positions().offset(edit.range.start) as usize;
|
||||
let end = doc.positions().offset(edit.range.end) as usize;
|
||||
(start, end, edit.new_text.as_str())
|
||||
})
|
||||
.collect();
|
||||
spans.sort_by_key(|(start, _, _)| std::cmp::Reverse(*start));
|
||||
let mut text = doc.text.to_string();
|
||||
for (start, end, new_text) in spans {
|
||||
text.replace_range(start..end, new_text);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_newline_after_an_unclosed_begin_writes_the_end_under_its_statement() {
|
||||
let text = "module m;\n always_ff @(posedge clk) begin\n\nendmodule\n";
|
||||
let (after, edits) = typed(text, 2, true);
|
||||
assert_eq!(after, "module m;\n always_ff @(posedge clk) begin\n \n end\nendmodule\n");
|
||||
// Nothing lands on the cursor's own position: the `end` goes in at the
|
||||
// start of the line after it, so the cursor stays on the body line.
|
||||
assert!(edits
|
||||
.iter()
|
||||
.all(|edit| edit.range.start.line != 2 || edit.range.end.character == 0));
|
||||
assert_eq!(
|
||||
edits.last().map(|edit| edit.range.start),
|
||||
Some(Position { line: 3, character: 0 })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_begin_typed_inside_a_balanced_block_still_gets_its_end() {
|
||||
// The new `if`'s `begin` steals the `always_comb` block's `end` in the
|
||||
// stack matcher, and the *outer* `begin` is what comes out unclosed.
|
||||
let text =
|
||||
"module m;\n always_comb begin\n x = 1;\n if (x) begin\n\n end\nendmodule\n";
|
||||
let (after, _) = typed(text, 4, true);
|
||||
assert_eq!(
|
||||
after,
|
||||
"module m;\n always_comb begin\n x = 1;\n if (x) begin\n \n end\n end\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_begin_whose_blocks_already_balance_gets_no_end() {
|
||||
let text = "module m;\n always_comb begin\n\n end\nendmodule\n";
|
||||
let (after, edits) = typed(text, 2, true);
|
||||
assert_eq!(after, "module m;\n always_comb begin\n \n end\nendmodule\n");
|
||||
assert_eq!(edits.len(), 1, "the indentation alone: {edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_inner_block_with_an_outer_end_missing_gets_no_second_end() {
|
||||
// The outer `begin` is the unclosed one, but this `begin` already has
|
||||
// its `end`, at exactly the indentation the answer would write.
|
||||
let text = "module m;\n always_comb begin\n if (x) begin\n\n end\nendmodule\n";
|
||||
let (_, edits) = typed(text, 3, true);
|
||||
assert!(edits.iter().all(|edit| !edit.new_text.contains("end")), "{edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_labelled_begin_and_a_trailing_comment_both_count() {
|
||||
let text = "module m;\n initial begin : boot // first\n\nendmodule\n";
|
||||
let (after, _) = typed(text, 2, true);
|
||||
assert_eq!(after, "module m;\n initial begin : boot // first\n \n end\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_lines_up_with_the_first_line_of_a_wrapped_header() {
|
||||
let text = "module m;\n always_comb\n if (a &&\n b) begin\n\nendmodule\n";
|
||||
let (after, _) = typed(text, 4, true);
|
||||
assert!(after.contains(" b) begin\n \n end\nendmodule"), "{after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_else_branch_ends_under_the_line_that_holds_the_else() {
|
||||
let text = "module m;\n always_comb begin\n if (a) begin\n x = 1;\n end else begin\n\n end\nendmodule\n";
|
||||
let (after, _) = typed(text, 5, true);
|
||||
assert!(after.contains(" end else begin\n \n end\n end\n"), "{after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_case_item_ends_under_the_item() {
|
||||
let text = "module m;\n always_comb begin\n case (s)\n 2'b01: begin\n\n endcase\n end\nendmodule\n";
|
||||
let (after, _) = typed(text, 4, true);
|
||||
assert!(after.contains(" 2'b01: begin\n \n end\n endcase"), "{after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tabs_stay_tabs() {
|
||||
let text = "module m;\n\talways_comb begin\n\nendmodule\n";
|
||||
let (after, _) = typed(text, 2, true);
|
||||
assert_eq!(after, "module m;\n\talways_comb begin\n\t\t\n\tend\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crlf_file_gets_a_crlf_end_line() {
|
||||
let text = "module m;\r\n initial begin\r\n\r\nendmodule\r\n";
|
||||
let (after, _) = typed(text, 2, true);
|
||||
assert_eq!(after, "module m;\r\n initial begin\r\n \r\n end\r\nendmodule\r\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_last_line_of_the_file_gets_one_edit() {
|
||||
let text = "module m;\n initial begin\n";
|
||||
let (after, edits) = typed(text, 2, true);
|
||||
assert_eq!(after, "module m;\n initial begin\n \n end");
|
||||
assert_eq!(edits.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_but_the_indent_when_the_setting_is_off() {
|
||||
let text = "module m;\n always_ff @(posedge clk) begin\n\nendmodule\n";
|
||||
let (after, _) = typed(text, 2, false);
|
||||
assert_eq!(after, "module m;\n always_ff @(posedge clk) begin\n \nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_end_where_the_line_above_does_not_end_in_begin() {
|
||||
for text in [
|
||||
"module m;\n initial begin x = 1;\n\nendmodule\n",
|
||||
"module m;\n initial // begin\n\nendmodule\n",
|
||||
"module m;\n initial $display(\"begin\");\n\nendmodule\n",
|
||||
"module m;\n initial fork\n\nendmodule\n",
|
||||
] {
|
||||
let (_, edits) = typed(text, 2, true);
|
||||
assert!(edits.iter().all(|edit| !edit.new_text.contains("end")), "{text:?}: {edits:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_end_when_enter_carried_text_down_to_the_new_line() {
|
||||
let text = "module m;\n initial begin\n x = 1;\nendmodule\n";
|
||||
let (_, edits) = typed(text, 2, true);
|
||||
assert!(edits.iter().all(|edit| !edit.new_text.contains("end")), "{edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_begin_two_lines_up_is_not_the_line_above() {
|
||||
let text = "module m;\n initial begin\n\n\nendmodule\n";
|
||||
let (_, edits) = typed(text, 3, true);
|
||||
assert!(edits.iter().all(|edit| !edit.new_text.contains("end")), "{edits:?}");
|
||||
}
|
||||
|
||||
/// QA (2026-11-17): buffers just after an Enter on `line`, each of which
|
||||
/// gets an `end`.
|
||||
const QA_ARMED: &[(&str, u32)] = &[
|
||||
("module m;\n always_comb begin\n x = 1;\n if (x) begin\n\n end\nendmodule\n", 4),
|
||||
("module m;\n generate\n if (P) begin : g\n\n endgenerate\nendmodule\n", 3),
|
||||
("module m;\n initial fork\n begin\n\n join\nendmodule\n", 3),
|
||||
("module m;\n initial `MY_MACRO begin\n\nendmodule\n", 2),
|
||||
("module m;\n initial #5 begin\n\nendmodule\n", 2),
|
||||
("module m;\n always @* begin\n\nendmodule\n", 2),
|
||||
("class c;\n function void f();\n if (a) begin\n\n endfunction\nendclass\n", 3),
|
||||
("module m;\r\n always_comb begin\r\n\r\nendmodule\r\n", 2),
|
||||
("module m;\n initial begin\n", 2),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn qa_asking_again_after_the_answer_is_applied_adds_no_second_end() {
|
||||
for &(text, line) in QA_ARMED {
|
||||
let (after, edits) = typed(text, line, true);
|
||||
assert!(edits.iter().any(|edit| edit.new_text.contains("end")), "{text:?}: {edits:?}");
|
||||
let (again, second) = typed(&after, line, true);
|
||||
assert!(
|
||||
second.iter().all(|edit| !edit.new_text.contains("end")),
|
||||
"{after:?}: {second:?}"
|
||||
);
|
||||
assert_eq!(again, after, "the second answer changes nothing: {text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_declined_newline_is_exactly_the_plain_indent_answer() {
|
||||
for (text, line) in [
|
||||
("module m;\n always_comb begin\n\n end\nendmodule\n", 2),
|
||||
("`define OPEN begin\n\nmodule m;\nendmodule\n", 1),
|
||||
("`define BLK(x) if (x) begin \\\n\nmodule m;\nendmodule\n", 1),
|
||||
("module m;\n initial $display(\"begin\n\nendmodule\n", 2),
|
||||
("module m;\n`ifdef A\n always_ff @(posedge clk) begin\n`else\n always_ff @(posedge clk or negedge rst_n) begin\n\n`endif\n x <= 1;\n end\nendmodule\n", 5),
|
||||
("module m;\n always_comb begin\n\nend\nendmodule\n", 2),
|
||||
("module m;\n initial begin end\n\nendmodule\n", 2),
|
||||
("module m;\n wire \\begin \n\nendmodule\n", 2),
|
||||
("module m;\n initial begin\nfoo = 1;\nendmodule\n", 2),
|
||||
] {
|
||||
let (_, with) = typed(text, line, true);
|
||||
let (_, without) = typed(text, line, false);
|
||||
assert_eq!(with, without, "{text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether any edit writes an `end`.
|
||||
fn wrote_an_end(edits: &[TextEdit]) -> bool {
|
||||
edits.iter().any(|edit| edit.new_text.contains("end"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gnu_style_begin_already_closed_under_itself_gets_no_end() {
|
||||
// Another `begin` above is unclosed (mid-edit), and this block's `end`
|
||||
// sits under the `begin`'s own line rather than under the `if`.
|
||||
let text = "module m;\n initial begin\n always_comb\n if (x)\n begin\n\n y = 1;\n end\nendmodule\n";
|
||||
let (_, edits) = typed(text, 5, true);
|
||||
assert!(!wrote_an_end(&edits), "{edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_ifdef_branches_sharing_one_end_get_no_second_end() {
|
||||
// QA finding 1: two `ifdef` branches each open the `always` block and
|
||||
// one `end` after the `endif` closes whichever was compiled.
|
||||
let shared = "module m;\n`ifdef A\n always @(posedge clk) begin\n`else\n always @(posedge clk or negedge rst) begin\n`endif\n if (x)\n begin\n\n y <= 1;\n end\n end\nendmodule\n";
|
||||
let (_, edits) = typed(shared, 8, true);
|
||||
assert!(!wrote_an_end(&edits), "after the GNU-style begin: {edits:?}");
|
||||
// The cursor after the *first* branch's `begin`: that block's `end`
|
||||
// is the shared one after the `endif`, so writing one would be wrong.
|
||||
let first = "module m;\n`ifdef A\n always @(posedge clk) begin\n\n`else\n always @(posedge clk or negedge rst) begin\n`endif\n y <= 1;\n end\nendmodule\n";
|
||||
let (_, edits) = typed(first, 3, true);
|
||||
assert!(!wrote_an_end(&edits), "inside the first branch: {edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ifdef_with_no_else_still_arms_the_answer() {
|
||||
let text = "module m;\n`ifdef A\n initial begin\n\n`endif\nendmodule\n";
|
||||
let (_, edits) = typed(text, 3, true);
|
||||
assert!(wrote_an_end(&edits), "{edits:?}");
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,7 @@ impl Server {
|
||||
let buffers = self.dirty.len();
|
||||
for (uri, text) in std::mem::take(&mut self.dirty) {
|
||||
self.set_document(uri.clone(), text);
|
||||
self.workspace.locate_port_entry(&uri);
|
||||
crate::lint_trace::rebuild(crate::lint_trace::Rebuild::Publish, || self.publish(&uri));
|
||||
}
|
||||
self.timed(started, |took| {
|
||||
@@ -100,7 +101,48 @@ impl Server {
|
||||
// (`docs/features/semantic-lints-on/`).
|
||||
let run = crate::lint::LintRun::for_document(&self.workspace, doc);
|
||||
self.report_config_problems(&run);
|
||||
diagnostics::all_in(doc, &run)
|
||||
// Except what the connection being typed would say, while it is being
|
||||
// typed (`docs/features/port-entry-grace/README.md`).
|
||||
self.workspace.port_grace().withhold(uri, doc, diagnostics::all_in(doc, &run))
|
||||
}
|
||||
|
||||
/// Say everything again about each buffer whose connection entry is no
|
||||
/// longer being typed: its quiet period ran out, or an edit landed in
|
||||
/// another buffer.
|
||||
///
|
||||
/// The generation moves first, so a pulling client's next pull gets the
|
||||
/// full list rather than "unchanged" against the withheld one; a pulling
|
||||
/// client that accepts `workspace/diagnostic/refresh` is asked — once per
|
||||
/// release, however many buffers it covers — to make that pull now. Its
|
||||
/// answer is ignorable and rides `response`'s fall-through. A pulling
|
||||
/// client without the capability sees the release at its own next pull.
|
||||
pub(super) fn release_port_entries(&mut self) {
|
||||
let due = self.workspace.port_grace_mut().due(std::time::Instant::now());
|
||||
if due.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.generation += 1;
|
||||
for uri in &due {
|
||||
self.publish(uri);
|
||||
}
|
||||
if self.abilities.pull_diagnostics && self.abilities.diagnostic_refresh {
|
||||
use lsp_types::request::{Request as _, WorkspaceDiagnosticRefresh};
|
||||
self.send_request(WorkspaceDiagnosticRefresh::METHOD, ());
|
||||
}
|
||||
}
|
||||
|
||||
/// How long the loop may wait for a message before it owes something: a
|
||||
/// dirty buffer's quiet period, or the end of a connection entry's grace,
|
||||
/// whichever comes first. `None` is "nothing is owed; wait for ever".
|
||||
pub(super) fn quiet_wait(&self) -> Option<std::time::Duration> {
|
||||
let debounce = (!self.dirty.is_empty()).then_some(super::CHANGE_DEBOUNCE);
|
||||
let now = std::time::Instant::now();
|
||||
let grace =
|
||||
self.workspace.port_grace().deadline().map(|at| at.saturating_duration_since(now));
|
||||
match (debounce, grace) {
|
||||
(Some(a), Some(b)) => Some(a.min(b)),
|
||||
(a, b) => a.or(b),
|
||||
}
|
||||
}
|
||||
|
||||
/// Say, once, what this buffer's `lucisv.toml` asked for and did not get.
|
||||
|
||||
@@ -568,7 +568,8 @@ impl Server {
|
||||
decode(request).and_then(|p: InlineCompletionParams| {
|
||||
let at = p.text_document_position;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
inline::inline_completions(&self.workspace, &uri, position)
|
||||
let selected = p.context.selected_completion_info.as_ref();
|
||||
inline::inline_completions_in_context(&self.workspace, &uri, position, selected)
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ impl Server {
|
||||
let uri = params.text_document.uri;
|
||||
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
||||
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
||||
let result = format::formatting(doc, &settings.config);
|
||||
let result = self.auto_styles.format_document(&uri, doc, &settings.config);
|
||||
// A broken `lucisv.toml` is a warning, not a failure: the CLI exits 2 on
|
||||
// one, but an editor that refuses to format because of a typo in a
|
||||
// config file is an editor the user turns off. The buffer is formatted
|
||||
@@ -45,7 +45,8 @@ impl Server {
|
||||
let uri = params.text_document.uri;
|
||||
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
||||
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
||||
let result = format::range_formatting(doc, &settings.config, params.range);
|
||||
let config = self.auto_styles.concrete(&uri, doc, settings.config);
|
||||
let result = format::range_formatting(doc, &config, params.range);
|
||||
self.warn_about_config(&uri, settings.problem);
|
||||
self.edits(result)
|
||||
}
|
||||
@@ -65,7 +66,8 @@ impl Server {
|
||||
let uri = params.text_document.uri;
|
||||
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
||||
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
||||
let result = format::ranges_formatting(doc, &settings.config, ¶ms.ranges);
|
||||
let config = self.auto_styles.concrete(&uri, doc, settings.config);
|
||||
let result = format::ranges_formatting(doc, &config, ¶ms.ranges);
|
||||
self.warn_about_config(&uri, settings.problem);
|
||||
self.edits(result)
|
||||
}
|
||||
@@ -98,7 +100,16 @@ impl Server {
|
||||
return to_value(Vec::<lsp_types::TextEdit>::new());
|
||||
};
|
||||
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
||||
let edits = on_type::on_type_formatting(doc, at.position, ¶ms.ch, &settings.config);
|
||||
// Only a `;` lays anything out; a newline needs no preset, so it must
|
||||
// not pay for finding one.
|
||||
let config = match params.ch.as_str() {
|
||||
on_type::SEMICOLON => {
|
||||
self.auto_styles.concrete(&at.text_document.uri, doc, settings.config)
|
||||
}
|
||||
_ => settings.config,
|
||||
};
|
||||
let auto_end = self.workspace.client_settings().auto_end.unwrap_or(true);
|
||||
let edits = on_type::on_type_formatting(doc, at.position, ¶ms.ch, &config, auto_end);
|
||||
to_value(edits)
|
||||
}
|
||||
|
||||
@@ -131,7 +142,7 @@ impl Server {
|
||||
// so the ladder runs without its `tabSize` rung.
|
||||
let settings =
|
||||
format::settings_without_editor_options(doc, self.workspace.client_settings());
|
||||
let result = format::formatting(doc, &settings.config);
|
||||
let result = self.auto_styles.format_document(&uri, doc, &settings.config);
|
||||
self.warn_about_config(&uri, settings.problem);
|
||||
self.edits(result)
|
||||
}
|
||||
|
||||
@@ -88,6 +88,12 @@ pub struct ClientAbilities {
|
||||
/// that said nothing is never asked, and keeps the instantiation counts it
|
||||
/// last requested until it asks again for its own reasons.
|
||||
pub code_lens_refresh: bool,
|
||||
/// Whether the client accepts a `workspace/diagnostic/refresh` — what
|
||||
/// makes a pulling client pull again when a connection entry held back
|
||||
/// while it was typed is released
|
||||
/// (`docs/features/port-entry-grace/README.md`). A client that said
|
||||
/// nothing sees the release at its own next pull.
|
||||
pub diagnostic_refresh: bool,
|
||||
/// Whether the client opens a document the server asks it to
|
||||
/// (`window/showDocument`). This is what lets the instantiation lens
|
||||
/// navigate; a client without it still gets the sites back as the
|
||||
@@ -129,6 +135,11 @@ pub struct Server {
|
||||
/// for a document whenever its text changes, so the warning is said once
|
||||
/// per file change rather than once per format-on-save.
|
||||
config_warnings: HashSet<Uri>,
|
||||
/// The preset `style = "auto"` last settled on for each recently
|
||||
/// formatted document, so range, selection and on-type requests neither
|
||||
/// search every preset again nor lose the file's preset while the buffer
|
||||
/// does not parse (`auto_style.rs`).
|
||||
auto_styles: crate::auto_style::AutoStyles,
|
||||
/// Which `[lint]` entries of which `lucisv.toml` have already been
|
||||
/// reported (§42.2). Interior-mutable because a lint pass runs behind
|
||||
/// `&self` — the pull models compute diagnostics inside a `map` over the
|
||||
@@ -316,7 +327,9 @@ impl Server {
|
||||
///
|
||||
/// A buffer sitting dirty past [`CHANGE_DEBOUNCE`] with nothing arriving is
|
||||
/// flushed here rather than left waiting for a request that may never
|
||||
/// come — diagnostics are the one answer the client never asks for.
|
||||
/// come — diagnostics are the one answer the client never asks for. The
|
||||
/// same wake-up releases a connection entry whose diagnostics were held
|
||||
/// back while it was typed, once its grace has run out.
|
||||
pub fn run(&mut self) -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
use std::sync::mpsc::RecvTimeoutError;
|
||||
loop {
|
||||
@@ -338,20 +351,24 @@ impl Server {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let message = if self.dirty.is_empty() {
|
||||
match self.queue.recv() {
|
||||
// A connection entry whose grace ran out while messages kept
|
||||
// arriving is released here, not only when the wait below times
|
||||
// out (`docs/features/port-entry-grace/README.md`).
|
||||
self.release_port_entries();
|
||||
let message = match self.quiet_wait() {
|
||||
None => match self.queue.recv() {
|
||||
Ok(message) => message,
|
||||
Err(_) => return Ok(()),
|
||||
}
|
||||
} else {
|
||||
match self.queue.recv_timeout(CHANGE_DEBOUNCE) {
|
||||
},
|
||||
Some(wait) => match self.queue.recv_timeout(wait) {
|
||||
Ok(message) => message,
|
||||
Err(RecvTimeoutError::Timeout) => {
|
||||
self.flush_dirty();
|
||||
self.release_port_entries();
|
||||
continue;
|
||||
}
|
||||
Err(RecvTimeoutError::Disconnected) => return Ok(()),
|
||||
}
|
||||
},
|
||||
};
|
||||
let batch = burst(&self.queue, message);
|
||||
if self.process_batch(batch)? {
|
||||
|
||||
@@ -51,6 +51,11 @@ impl Server {
|
||||
self.dirty.retain(|(pending, _)| *pending != uri);
|
||||
}
|
||||
}
|
||||
// A buffer saved, closed or opened afresh holds nothing back any more
|
||||
// (`docs/features/port-entry-grace/README.md`). Forgotten before the
|
||||
// flush, so the flush below already publishes everything.
|
||||
let released = self.forget_port_entry(&method, ¬ification);
|
||||
self.auto_styles.notice(¬ification);
|
||||
// Everything but a `didChange` needs the buffers' analyses current —
|
||||
// a `didSave` rebuilds the index on top of them — so the same flush a
|
||||
// request gets happens here, with the one exception that *is* the
|
||||
@@ -58,6 +63,14 @@ impl Server {
|
||||
if method != DidChangeTextDocument::METHOD {
|
||||
self.flush_dirty();
|
||||
}
|
||||
// A save of a buffer that was not dirty: nothing above said the full
|
||||
// list, so it is said here, under a new generation for a pulling
|
||||
// client. (The rescan the save starts says it again; that is the same
|
||||
// list twice, never a stale one.)
|
||||
if let Some(uri) = released {
|
||||
self.generation += 1;
|
||||
self.publish(&uri);
|
||||
}
|
||||
match method.as_str() {
|
||||
DidOpenTextDocument::METHOD => {
|
||||
if let Ok(p) = extract::<DidOpenTextDocumentParams>(notification) {
|
||||
@@ -103,7 +116,7 @@ impl Server {
|
||||
return;
|
||||
}
|
||||
let uri = p.text_document.uri;
|
||||
let text = {
|
||||
let (text, end) = {
|
||||
let base = self
|
||||
.dirty
|
||||
.iter()
|
||||
@@ -111,8 +124,13 @@ impl Server {
|
||||
.map(|(_, text)| text.as_str())
|
||||
.or_else(|| self.workspace.document(&uri).map(|doc| doc.text.as_str()))
|
||||
.unwrap_or("");
|
||||
sync::apply_changes(base, &p.content_changes)
|
||||
sync::apply_changes_at(base, &p.content_changes)
|
||||
};
|
||||
self.auto_styles.changed(&uri, &p.content_changes, &text);
|
||||
// Where the edit ended is where someone is typing: the
|
||||
// flush looks it up for a connection entry to hold back.
|
||||
let now = std::time::Instant::now();
|
||||
self.workspace.port_grace_mut().edited(&uri, end, now);
|
||||
self.mark_dirty(uri, text);
|
||||
}
|
||||
}
|
||||
@@ -243,6 +261,7 @@ impl Server {
|
||||
/// about what a setting *does* any more than `settings::from_payload` and
|
||||
/// `from_section` can disagree about what it says.
|
||||
pub(super) fn apply_settings(&mut self, settings: settings::ClientSettings) {
|
||||
self.auto_styles.forget_all();
|
||||
let watched = self.workspace.filelist_path();
|
||||
let linted = self.lint_selection();
|
||||
// A `lucisv.lint.options` entry the registry refused is dropped, not
|
||||
@@ -315,6 +334,23 @@ impl Server {
|
||||
}
|
||||
}
|
||||
|
||||
/// Forget the connection entry a `didOpen`, `didSave` or `didClose` names,
|
||||
/// answering the buffer whose full list a save now owes the client. An
|
||||
/// open publishes on its own and a close clears, so only a save asks.
|
||||
fn forget_port_entry(&mut self, method: &str, notification: &Notification) -> Option<Uri> {
|
||||
let ends_typing = [
|
||||
DidOpenTextDocument::METHOD,
|
||||
DidSaveTextDocument::METHOD,
|
||||
DidCloseTextDocument::METHOD,
|
||||
];
|
||||
if !ends_typing.contains(&method) {
|
||||
return None;
|
||||
}
|
||||
let uri = document_uri(notification)?;
|
||||
let held = self.workspace.port_grace_mut().forget(&uri);
|
||||
(held && method == DidSaveTextDocument::METHOD).then_some(uri)
|
||||
}
|
||||
|
||||
/// The rule selection in force, as a value two settings pushes can be
|
||||
/// compared by.
|
||||
///
|
||||
@@ -346,6 +382,13 @@ fn closing_uri(notification: &Notification) -> Option<Uri> {
|
||||
.map(|p| p.text_document.uri)
|
||||
}
|
||||
|
||||
/// The `textDocument.uri` a document notification names, read without
|
||||
/// consuming it; `None` when the params carry none that parses.
|
||||
fn document_uri(notification: &Notification) -> Option<Uri> {
|
||||
let uri = notification.params.get("textDocument")?.get("uri")?.as_str()?;
|
||||
uri.parse().ok()
|
||||
}
|
||||
|
||||
/// The paths behind a `didChangeWorkspaceFolders` list.
|
||||
///
|
||||
/// A folder whose URI is not a `file:` URI — or is not valid UTF-8 once
|
||||
|
||||
@@ -146,6 +146,7 @@ impl Server {
|
||||
connection,
|
||||
workspace: Workspace::default(),
|
||||
config_warnings: HashSet::new(),
|
||||
auto_styles: Default::default(),
|
||||
lint_config_problems: std::cell::RefCell::default(),
|
||||
said_lint_names: Vec::new(),
|
||||
abilities,
|
||||
|
||||
@@ -135,6 +135,27 @@ fn a_ranges_request_lays_out_every_range_it_names_in_one_answer() {
|
||||
assert!(session.shown().is_empty(), "a clean config says nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_inside_a_nested_block_lays_out_only_that_block() {
|
||||
// The owner's report (TODO §66.2): a `case` selected inside an `always`
|
||||
// in a four-space file. Only the `case` moves, and it stays where it
|
||||
// starts; the statement after it and the parent keep their bytes.
|
||||
let tree = Tree::new("rangesnested");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let text = "module m;\n always @* begin\n case (s)\n 0: y=a;\n endcase\n z = 1;\n end\nendmodule\n";
|
||||
let uri = session.open(&tree.path.join("m.sv"), text);
|
||||
|
||||
let one = range_result(&mut session, &uri, json_range(2, 0, 5, 0));
|
||||
assert_eq!(
|
||||
one[0]["newText"],
|
||||
"module m;\n always @* begin\n case (s)\n 0: y = a;\n endcase\n z = 1;\n end\nendmodule\n",
|
||||
"{one:#?}"
|
||||
);
|
||||
// The multi-range method gives the same answer for the same selection.
|
||||
assert_eq!(ranges_result(&mut session, &uri, vec![json_range(2, 0, 5, 0)]), one);
|
||||
assert!(session.shown().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_range_through_the_new_method_answers_what_the_old_method_answers() {
|
||||
// The two requests are the same engine, and a client must never have
|
||||
@@ -250,9 +271,11 @@ fn a_keystroke_the_engine_refuses_is_answered_with_silence_and_not_a_popup() {
|
||||
// user cannot type past would arrive on every semicolon.
|
||||
let tree = Tree::new("ontypequiet");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\n wire ;\n");
|
||||
// The error sits on the keystroke's own line: since selection formatting
|
||||
// (TODO §66.2) an error on *another* line no longer refuses the request.
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a = ;\n");
|
||||
|
||||
assert_eq!(on_type(&mut session, &uri, ";", 1, 11), serde_json::json!([]));
|
||||
assert_eq!(on_type(&mut session, &uri, ";", 1, 13), serde_json::json!([]));
|
||||
assert!(session.shown().is_empty(), "not one word: {:?}", session.shown());
|
||||
// ...and the whole-document request on the same buffer still does say
|
||||
// something, so the silence is this path's decision and not a
|
||||
@@ -626,3 +649,188 @@ fn a_reformatting_save_re_arms_the_broken_config_warning_on_the_very_next_save()
|
||||
assert_eq!(third, serde_json::json!([]));
|
||||
assert!(session.shown().is_empty(), "only now does the warning stop repeating");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `lucisv.format.style = "auto"`: the preset the server remembers
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A google-formatted buffer: one connection per line at a 4-space indent.
|
||||
const GOOGLE_BUFFER: &str = "\
|
||||
module m (
|
||||
input logic a,
|
||||
output logic b
|
||||
);
|
||||
sub u_sub (
|
||||
.a(a),
|
||||
.b(b)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
fn push_auto(session: &mut Session) {
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "format": { "style": "auto" } } } }),
|
||||
);
|
||||
}
|
||||
|
||||
fn format_whole(session: &mut Session, uri: &Uri) -> Value {
|
||||
session.result(
|
||||
Formatting::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"options": { "tabSize": 2, "insertSpaces": true },
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// After a whole-document format under `auto`, a range in the same buffer
|
||||
/// keeps the buffer's preset even once a half-typed line elsewhere stops it
|
||||
/// from parsing — which a fresh search could not do.
|
||||
#[test]
|
||||
fn auto_ranges_keep_the_remembered_preset_while_the_buffer_does_not_parse() {
|
||||
let tree = Tree::new("autorange");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
push_auto(&mut session);
|
||||
let uri = session.open(&tree.path.join("m.sv"), GOOGLE_BUFFER);
|
||||
assert_eq!(format_whole(&mut session, &uri), serde_json::json!([]), "already google");
|
||||
|
||||
let edited = GOOGLE_BUFFER
|
||||
.replace("endmodule", " sub u_two (.a(a), .b(b));\n assign c = ;\nendmodule");
|
||||
change(&mut session, &uri, 2, serde_json::json!([{ "text": edited }]));
|
||||
let ranged = range_result(&mut session, &uri, json_range(8, 0, 8, 0));
|
||||
let text = ranged[0]["newText"].as_str().expect("an edit");
|
||||
assert!(text.contains(" sub u_two (\n .a(a),\n .b(b)\n );\n"), "{text}");
|
||||
// And the `;` path agrees with it, byte for byte.
|
||||
let typed = on_type(&mut session, &uri, ";", 8, 27);
|
||||
assert_eq!(typed, ranged);
|
||||
}
|
||||
|
||||
/// With no memory and a buffer that does not parse there is nothing to
|
||||
/// resolve from, so the default preset's layout answers — the documented
|
||||
/// fallback — and nothing is remembered.
|
||||
#[test]
|
||||
fn auto_without_a_memory_and_without_a_parse_uses_the_default_layout() {
|
||||
let tree = Tree::new("autofallback");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
push_auto(&mut session);
|
||||
let text = GOOGLE_BUFFER
|
||||
.replace("endmodule", " sub u_two (.a(a), .b(b));\n assign c = ;\nendmodule");
|
||||
let uri = session.open(&tree.path.join("m.sv"), &text);
|
||||
let ranged = range_result(&mut session, &uri, json_range(8, 0, 8, 0));
|
||||
assert_eq!(ranged, serde_json::json!([]), "the default layout already holds that line");
|
||||
assert!(session.server.auto_styles.is_empty(), "a fallback is not remembered");
|
||||
}
|
||||
|
||||
/// With no memory and a buffer that parses, the first range request
|
||||
/// resolves the preset once and remembers it for the next.
|
||||
#[test]
|
||||
fn auto_without_a_memory_resolves_from_a_buffer_that_parses() {
|
||||
let tree = Tree::new("autoresolve");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
push_auto(&mut session);
|
||||
let text = GOOGLE_BUFFER.replace("endmodule", " sub u_two (.a(a), .b(b));\nendmodule");
|
||||
let uri = session.open(&tree.path.join("m.sv"), &text);
|
||||
let ranged = range_result(&mut session, &uri, json_range(8, 0, 8, 0));
|
||||
let out = ranged[0]["newText"].as_str().expect("an edit");
|
||||
assert!(out.contains(" sub u_two (\n .a(a),\n .b(b)\n );\n"), "{out}");
|
||||
assert!(!session.server.auto_styles.is_empty());
|
||||
}
|
||||
|
||||
/// The google buffer re-laid out lucisv-style, with one unformatted
|
||||
/// instance on line 3 that the two presets lay out differently.
|
||||
const LUCISV_BUFFER: &str = "\
|
||||
module m (input logic a, output logic b);
|
||||
sub u_sub (.a(a), .b(b));
|
||||
endmodule
|
||||
";
|
||||
|
||||
fn lucisv_with_instance() -> String {
|
||||
LUCISV_BUFFER.replace("endmodule", "sub u_two (.a(a), .b(b));\nendmodule")
|
||||
}
|
||||
|
||||
/// The range answer for line 2 (0-based) of the lucisv buffer. A selection
|
||||
/// keeps the indentation its line was written at, so lucisv's layout of the
|
||||
/// one-line instance is the line itself — no edit — where google's would
|
||||
/// break it into four (`auto_without_a_memory_resolves_from_a_buffer_that_parses`).
|
||||
fn assert_lucisv_layout(session: &mut Session, uri: &Uri) {
|
||||
let ranged = range_result(session, uri, json_range(2, 0, 2, 0));
|
||||
assert_eq!(ranged, serde_json::json!([]), "laid out lucisv-style, not google-style");
|
||||
}
|
||||
|
||||
/// R2-1 (a): the buffer replaced wholesale by text in another preset — a
|
||||
/// reload from disk — is resolved again, not served the old preset.
|
||||
#[test]
|
||||
fn auto_a_replaced_buffer_is_resolved_again() {
|
||||
let tree = Tree::new("autoreplaced");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
push_auto(&mut session);
|
||||
let uri = session.open(&tree.path.join("m.sv"), GOOGLE_BUFFER);
|
||||
format_whole(&mut session, &uri);
|
||||
assert!(!session.server.auto_styles.is_empty(), "google remembered");
|
||||
change(&mut session, &uri, 2, serde_json::json!([{ "text": lucisv_with_instance() }]));
|
||||
assert_lucisv_layout(&mut session, &uri);
|
||||
}
|
||||
|
||||
/// R2-1 (b): auto → a whole-document format under a named style → auto.
|
||||
#[test]
|
||||
fn auto_after_a_named_style_format_does_not_reuse_the_old_preset() {
|
||||
let tree = Tree::new("autonamed");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
push_auto(&mut session);
|
||||
let uri = session.open(&tree.path.join("m.sv"), GOOGLE_BUFFER);
|
||||
format_whole(&mut session, &uri);
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "format": { "style": "lucisv" } } } }),
|
||||
);
|
||||
assert!(session.server.auto_styles.is_empty(), "a settings change forgets everything");
|
||||
format_whole(&mut session, &uri);
|
||||
push_auto(&mut session);
|
||||
// An incremental edit, so only the settings change and the named format
|
||||
// can be what made the memory forget.
|
||||
let text = lucisv_with_instance();
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([{ "range": { "start": { "line": 0, "character": 0 },
|
||||
"end": { "line": 9, "character": 0 } },
|
||||
"text": text }]),
|
||||
);
|
||||
assert_lucisv_layout(&mut session, &uri);
|
||||
}
|
||||
|
||||
/// R2-1 (c): close, then reopen the same URI with other content.
|
||||
#[test]
|
||||
fn auto_a_reopened_document_starts_with_no_memory() {
|
||||
let tree = Tree::new("autoreopen");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
push_auto(&mut session);
|
||||
let path = tree.path.join("m.sv");
|
||||
let uri = session.open(&path, GOOGLE_BUFFER);
|
||||
format_whole(&mut session, &uri);
|
||||
session.notify(
|
||||
DidCloseTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
);
|
||||
assert!(session.server.auto_styles.is_empty(), "closing forgets");
|
||||
let uri = session.open(&path, &lucisv_with_instance());
|
||||
assert_lucisv_layout(&mut session, &uri);
|
||||
}
|
||||
|
||||
/// R2-1 (d): a renamed file's old name is forgotten with it.
|
||||
#[test]
|
||||
fn auto_a_rename_forgets_both_names() {
|
||||
let tree = Tree::new("autorename");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
push_auto(&mut session);
|
||||
let uri = session.open(&tree.path.join("m.sv"), GOOGLE_BUFFER);
|
||||
format_whole(&mut session, &uri);
|
||||
let new = crate::uri::path_to_uri(&tree.path.join("n.sv")).expect("uri");
|
||||
session.notify(
|
||||
DidRenameFiles::METHOD,
|
||||
serde_json::json!({ "files": [{ "oldUri": uri.as_str(), "newUri": new.as_str() }] }),
|
||||
);
|
||||
assert!(session.server.auto_styles.is_empty());
|
||||
}
|
||||
@@ -16,8 +16,7 @@ use lsp_server::{Notification, Request, Response};
|
||||
use lsp_types::notification::{
|
||||
DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles,
|
||||
DidChangeWorkspaceFolders, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument,
|
||||
DidRenameFiles, DidSaveTextDocument, LogMessage, Notification as _, Progress,
|
||||
PublishDiagnostics, ShowMessage,
|
||||
DidRenameFiles, DidSaveTextDocument, LogMessage, Progress, PublishDiagnostics, ShowMessage,
|
||||
};
|
||||
use lsp_types::request::{
|
||||
ApplyWorkspaceEdit, CallHierarchyPrepare, CodeActionRequest, CodeActionResolveRequest,
|
||||
|
||||
@@ -128,10 +128,29 @@ fn the_stages_add_up_to_the_scan_they_describe() {
|
||||
// the progress callbacks, the per-file word `Vec`, the staging pushes —
|
||||
// which is deliberately unattributed rather than silently folded into a
|
||||
// neighbouring stage.
|
||||
//
|
||||
// That slack is about a third of an unloaded scan, so one stall landing in
|
||||
// it (the 4-CPU Linux runner throttles for tens of ms; QA caught 0.43 on
|
||||
// macOS beside a looping suite) grows `total` and no stage. The upper
|
||||
// bound is structural — the stages are disjoint pieces of the scan — and
|
||||
// holds on every scan; the lower bound is a claim about an undisturbed
|
||||
// scan, so it is asserted on the best of three: a stall spoils one
|
||||
// sample, not all of them.
|
||||
let tree = trace_tree("tracesums", 40);
|
||||
let session = Session::verbose_wide(vec![tree.path.clone()], None);
|
||||
let stages = line_of(&scan_lines(&session), "stages");
|
||||
let total = number(&stages, "total");
|
||||
let mut best = 0.0f64;
|
||||
for _ in 0..3 {
|
||||
let session = Session::verbose_wide(vec![tree.path.clone()], None);
|
||||
let stages = line_of(&scan_lines(&session), "stages");
|
||||
let (sum, total) = (named_stage_sum(&stages), number(&stages, "total"));
|
||||
assert!(total > 0.0, "a scan of 40 files takes measurable time: {stages}");
|
||||
assert!(sum <= total * 1.02, "the stages cannot exceed the scan: {sum} of {total}");
|
||||
best = best.max(sum / total);
|
||||
}
|
||||
assert!(best >= 0.5, "the stages must account for most of it: at best {best:.2} of the scan");
|
||||
}
|
||||
|
||||
/// The sum of every stage a scan's `stages` line names, `total` aside.
|
||||
fn named_stage_sum(stages: &str) -> f64 {
|
||||
let named = [
|
||||
"discovery",
|
||||
"order",
|
||||
@@ -157,10 +176,7 @@ fn the_stages_add_up_to_the_scan_they_describe() {
|
||||
"includes",
|
||||
"overlay",
|
||||
];
|
||||
let sum: f64 = named.iter().map(|key| number(&stages, key)).sum();
|
||||
assert!(total > 0.0, "a scan of 40 files takes measurable time: {stages}");
|
||||
assert!(sum <= total * 1.02, "the stages cannot exceed the scan: {sum} of {total}");
|
||||
assert!(sum >= total * 0.5, "the stages must account for most of it: {sum} of {total}");
|
||||
named.iter().map(|key| number(stages, key)).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -112,6 +112,11 @@ pub struct ClientSettings {
|
||||
/// declares — the key changes bytes in files that already format cleanly,
|
||||
/// so nothing turns it on for a user who did not ask.
|
||||
pub uvm_utils_indent: Option<bool>,
|
||||
/// `lucisv.format.style`: the named layout preset, one of
|
||||
/// `lucisv_core::config::STYLE_NAMES`. Unset — and any name that is not
|
||||
/// one of them — means "no opinion", so a `lucisv.toml` or the built-in
|
||||
/// default decides.
|
||||
pub style: Option<&'static str>,
|
||||
/// `lucisv.inlineTemplates`: whether `if (` and `begin` grow ghost text.
|
||||
/// Unset means on, which is what the VS Code default declares — see
|
||||
/// `docs/features/inline-templates/README.md`.
|
||||
@@ -121,6 +126,14 @@ pub struct ClientSettings {
|
||||
/// followed by a space. Unset means on, the same way `inline_templates`
|
||||
/// does — see `docs/features/inline-instantiation/README.md`.
|
||||
pub inline_instantiation: Option<bool>,
|
||||
/// `lucisv.inlineKeywords`: whether a typed proper prefix of a keyword
|
||||
/// grows the rest of it as ghost text. Unset means on, independent of
|
||||
/// `inline_templates` — see `docs/features/completion-ux/README.md`.
|
||||
pub inline_keywords: Option<bool>,
|
||||
/// `lucisv.autoEnd`: whether a newline typed after `begin` also writes
|
||||
/// the `end` the block still owes. Unset means on — see
|
||||
/// `docs/features/completion-ux/README.md`.
|
||||
pub auto_end: Option<bool>,
|
||||
/// `lucisv.formatOnSave`: whether `textDocument/willSaveWaitUntil` formats
|
||||
/// the buffer. A plain `bool` rather than an `Option`, because unset and
|
||||
/// off are the same answer here: an editor with a format-on-save of its
|
||||
@@ -244,8 +257,11 @@ impl Default for ClientSettings {
|
||||
exclude: Vec::new(),
|
||||
filelist: None,
|
||||
uvm_utils_indent: None,
|
||||
style: None,
|
||||
inline_templates: None,
|
||||
inline_instantiation: None,
|
||||
inline_keywords: None,
|
||||
auto_end: None,
|
||||
format_on_save: false,
|
||||
max_file_size: DEFAULT_MAX_FILE_SIZE,
|
||||
log_files: true,
|
||||
@@ -343,8 +359,11 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
||||
exclude: strings(lucisv.get("exclude")),
|
||||
filelist: path(lucisv.get("filelist")),
|
||||
uvm_utils_indent: flag(lucisv.get("format").and_then(|f| f.get("uvmUtilsIndent"))),
|
||||
style: style(lucisv.get("format").and_then(|f| f.get("style"))),
|
||||
inline_templates: flag(lucisv.get("inlineTemplates")),
|
||||
inline_instantiation: flag(lucisv.get("inlineInstantiation")),
|
||||
inline_keywords: flag(lucisv.get("inlineKeywords")),
|
||||
auto_end: flag(lucisv.get("autoEnd")),
|
||||
// Anything that is not `true` leaves the hook declining, wrong-typed
|
||||
// values included: the safe direction for a setting that rewrites the
|
||||
// user's buffer on every save is the one that does nothing.
|
||||
@@ -569,6 +588,13 @@ fn path(value: Option<&Value>) -> Option<String> {
|
||||
(!text.is_empty()).then(|| text.to_string())
|
||||
}
|
||||
|
||||
/// A preset name `lucisv.toml`'s `[format] style` would accept, or nothing.
|
||||
/// VS Code's drop-down cannot send anything else; another editor's
|
||||
/// hand-written misspelling is dropped like every wrong-typed value here.
|
||||
fn style(value: Option<&Value>) -> Option<&'static str> {
|
||||
lucisv_core::config::parse_style(value?.as_str()?).ok()
|
||||
}
|
||||
|
||||
/// A JSON integer inside `range`, or nothing.
|
||||
///
|
||||
/// `as_u64` rejects null, strings, booleans, negatives and fractions in one
|
||||
@@ -623,6 +649,8 @@ mod tests {
|
||||
"filelist": "",
|
||||
"inlineTemplates": true,
|
||||
"inlineInstantiation": true,
|
||||
"inlineKeywords": true,
|
||||
"autoEnd": true,
|
||||
"formatOnSave": false,
|
||||
"index": {
|
||||
"maxFileSize": 1048576, "logFiles": true,
|
||||
@@ -814,6 +842,31 @@ mod tests {
|
||||
assert_eq!(settings(json!({ "lucisv": {} })).filelist, None, "and so must its absence");
|
||||
}
|
||||
|
||||
/// The style drop-down offers exactly the names `[format] style` takes,
|
||||
/// one description each, defaulting to the default style; and each one
|
||||
/// arrives here as itself, while a name that is not one is dropped.
|
||||
#[test]
|
||||
fn the_style_drop_down_is_the_style_names() {
|
||||
let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../editors/vscode/package.json");
|
||||
let text = std::fs::read_to_string(&path).expect("the extension manifest");
|
||||
let manifest: Value = serde_json::from_str(&text).expect("valid json");
|
||||
let style = &manifest["contributes"]["configuration"]["properties"]["lucisv.format.style"];
|
||||
assert_eq!(style["enum"], json!(lucisv_core::config::STYLE_NAMES));
|
||||
let descriptions = style["enumDescriptions"].as_array().expect("descriptions");
|
||||
assert_eq!(descriptions.len(), lucisv_core::config::STYLE_NAMES.len());
|
||||
assert_eq!(style["default"], json!("lucisv"));
|
||||
for name in lucisv_core::config::STYLE_NAMES {
|
||||
let pushed = settings(json!({ "lucisv": { "format": { "style": name } } }));
|
||||
assert_eq!(pushed.style, Some(name));
|
||||
}
|
||||
for junk in [json!("Google"), json!(""), json!(4), json!(null)] {
|
||||
let pushed = settings(json!({ "lucisv": { "format": { "style": junk } } }));
|
||||
assert_eq!(pushed.style, None, "{junk}");
|
||||
}
|
||||
assert_eq!(settings(json!({ "lucisv": {} })).style, None);
|
||||
}
|
||||
|
||||
/// [`vscode_payload`] above is a hand-written copy of what the extension
|
||||
/// declares, and a copy that drifts proves nothing. The extension's own
|
||||
/// `package.json` is the thing a user's settings UI reads, so the two
|
||||
@@ -838,7 +891,13 @@ mod tests {
|
||||
// The two ghost-text settings are the ones whose absence resolves to
|
||||
// `true` here, so a `false` default in the manifest would make the
|
||||
// settings UI and the server disagree about a feature being on.
|
||||
for ghost in ["lucisv.inlineTemplates", "lucisv.inlineInstantiation"] {
|
||||
// `autoEnd` is the same kind of switch: absent means on.
|
||||
for ghost in [
|
||||
"lucisv.inlineTemplates",
|
||||
"lucisv.inlineInstantiation",
|
||||
"lucisv.inlineKeywords",
|
||||
"lucisv.autoEnd",
|
||||
] {
|
||||
assert_eq!(properties[ghost]["default"], json!(true), "{ghost}");
|
||||
assert_eq!(properties[ghost]["type"], json!("boolean"), "{ghost}");
|
||||
}
|
||||
@@ -1103,6 +1162,8 @@ mod tests {
|
||||
ClientSettings {
|
||||
inline_templates: Some(true),
|
||||
inline_instantiation: Some(true),
|
||||
inline_keywords: Some(true),
|
||||
auto_end: Some(true),
|
||||
..Default::default()
|
||||
},
|
||||
"the only difference from silence must be the settings whose \
|
||||
@@ -1141,6 +1202,24 @@ mod tests {
|
||||
assert_eq!(found.inline_templates, None, "the templates setting is untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_keywords_and_auto_end_are_booleans_and_nothing_else() {
|
||||
let found = settings(json!({ "lucisv": { "inlineKeywords": false, "autoEnd": false } }));
|
||||
assert_eq!((found.inline_keywords, found.auto_end), (Some(false), Some(false)));
|
||||
let found = settings(json!({ "lucisv": { "inlineKeywords": true, "autoEnd": true } }));
|
||||
assert_eq!((found.inline_keywords, found.auto_end), (Some(true), Some(true)));
|
||||
// Absence is not `false`: both are on unless a client says no.
|
||||
let found = settings(json!({ "lucisv": {} }));
|
||||
assert_eq!((found.inline_keywords, found.auto_end), (None, None));
|
||||
for bad in [json!("false"), json!(0), json!(null), json!([false])] {
|
||||
let found = settings(json!({ "lucisv": { "inlineKeywords": bad, "autoEnd": bad } }));
|
||||
assert_eq!((found.inline_keywords, found.auto_end), (None, None), "{bad} ignored");
|
||||
}
|
||||
// Independent of the template ghosts: one off leaves the other alone.
|
||||
let found = settings(json!({ "lucisv": { "inlineKeywords": false } }));
|
||||
assert_eq!(found.inline_templates, None, "the templates setting is untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_on_save_is_off_until_a_client_asks_for_it() {
|
||||
assert!(settings(json!({ "lucisv": { "formatOnSave": true } })).format_on_save);
|
||||
|
||||
@@ -30,6 +30,7 @@ mod buffers;
|
||||
pub(crate) mod discover;
|
||||
mod document;
|
||||
mod incremental;
|
||||
mod port_grace;
|
||||
mod rescan;
|
||||
mod scan;
|
||||
mod scope;
|
||||
@@ -39,6 +40,7 @@ mod views;
|
||||
#[cfg(test)]
|
||||
pub use document::mixed_buffer;
|
||||
pub use document::{first_token_from, first_token_reaching, Document};
|
||||
pub use port_grace::PortGrace;
|
||||
pub use scan::{IndexEvent, Scan};
|
||||
pub use views::FileView;
|
||||
|
||||
@@ -118,6 +120,10 @@ pub struct Workspace {
|
||||
/// How many scans this workspace has run, so a session's lines can be
|
||||
/// told apart — a `workspace` scope pays two (`docs/features/perf5-p4`).
|
||||
scans: u32,
|
||||
/// Where each buffer's last edit ended and the connection-list entry it
|
||||
/// is in, while that entry's diagnostics are held back
|
||||
/// (`docs/features/port-entry-grace/README.md`).
|
||||
grace: PortGrace,
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
@@ -150,6 +156,24 @@ impl Workspace {
|
||||
pub fn includes(&self) -> &IncludeGraph {
|
||||
&self.includes
|
||||
}
|
||||
|
||||
/// The edits whose connection-list entries are being held back.
|
||||
pub fn port_grace(&self) -> &PortGrace {
|
||||
&self.grace
|
||||
}
|
||||
|
||||
/// The same, to note an edit, forget a buffer or release what is due.
|
||||
pub fn port_grace_mut(&mut self) -> &mut PortGrace {
|
||||
&mut self.grace
|
||||
}
|
||||
|
||||
/// Look `uri`'s last edit up in the analysis just built for it, finding
|
||||
/// the connection-list entry it is in, if any.
|
||||
pub fn locate_port_entry(&mut self, uri: &Uri) {
|
||||
if let Some(doc) = self.docs.get(uri) {
|
||||
self.grace.locate(uri, doc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
//! The connection being typed: where each buffer's last edit ended, the
|
||||
//! connection-list entry around it, and the diagnostics held back from that
|
||||
//! entry while the typing goes on (`docs/features/port-entry-grace/README.md`).
|
||||
//!
|
||||
//! Someone typing `.po` into `sub u0 (…)` passes through a lone `.`, a `.p`
|
||||
//! that names no port, a `.po(` with nothing closed — and every one of those
|
||||
//! keystrokes used to draw a squiggle. While the last edit sits inside an
|
||||
//! instantiation's port or parameter list, the diagnostics whose range starts
|
||||
//! inside the entry around it are withheld from what is published or pulled.
|
||||
//! Nothing outside that entry is ever withheld, and the entry is released —
|
||||
//! the full list said again — when the next edit lands outside it, when
|
||||
//! [`PORT_ENTRY_GRACE`] passes with no edit at all, or when the buffer is
|
||||
//! saved, closed or reopened.
|
||||
//!
|
||||
//! The lookup is a token scan of the buffer just analyzed, no extra parse.
|
||||
//! The parser's half — keeping the unfinished entry inside its own entry so
|
||||
//! the rest of the file parses as if it were complete — is in
|
||||
//! `vlog_parser`'s `recover_list.rs`, and the two agree on where an entry
|
||||
//! ends: a `,` or the list's `)` at the list's own level, or the end of the
|
||||
//! line when the next line opens a new `.` entry.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use lsp_types::{Diagnostic, Uri};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
use super::Document;
|
||||
use crate::signature::enclosing_list;
|
||||
|
||||
/// How long the diagnostics of the entry being typed are held back after the
|
||||
/// last edit. Long enough to finish typing a port name and its connection,
|
||||
/// short enough that a real mistake left behind is shown before the eye has
|
||||
/// moved on.
|
||||
pub const PORT_ENTRY_GRACE: Duration = Duration::from_millis(1500);
|
||||
|
||||
/// Every buffer's last edit, while it may still be withholding something.
|
||||
#[derive(Default)]
|
||||
pub struct PortGrace {
|
||||
edits: HashMap<Uri, LastEdit>,
|
||||
}
|
||||
|
||||
/// One buffer's last edit.
|
||||
struct LastEdit {
|
||||
/// Where the edit ended, in the buffer's newest text.
|
||||
offset: u32,
|
||||
/// When it arrived.
|
||||
at: Instant,
|
||||
/// Where it stands in the analysis of that text.
|
||||
state: Located,
|
||||
/// An edit has since landed in another buffer: release at the next
|
||||
/// chance rather than when the quiet period ends.
|
||||
released: bool,
|
||||
}
|
||||
|
||||
/// Whether a buffer's last edit has been looked up in its analysis yet.
|
||||
enum Located {
|
||||
/// The buffer is dirty; its analysis is not the text the edit is in.
|
||||
Pending,
|
||||
/// The edit is inside this connection-list entry.
|
||||
Entry(TextRange),
|
||||
}
|
||||
|
||||
impl PortGrace {
|
||||
/// Note a buffer's edit, `end` being where the last of its changes ended
|
||||
/// in the new text — `None` for a full-document replacement, which says
|
||||
/// nothing about where anyone is typing and so withholds nothing.
|
||||
///
|
||||
/// An edit is "elsewhere" for every other buffer, so whatever those are
|
||||
/// withholding is released at the next chance.
|
||||
pub fn edited(&mut self, uri: &Uri, end: Option<u32>, now: Instant) {
|
||||
for (other, edit) in self.edits.iter_mut() {
|
||||
if other != uri {
|
||||
edit.released = true;
|
||||
}
|
||||
}
|
||||
match end {
|
||||
Some(offset) => {
|
||||
let edit = LastEdit { offset, at: now, state: Located::Pending, released: false };
|
||||
self.edits.insert(uri.clone(), edit);
|
||||
}
|
||||
None => {
|
||||
self.edits.remove(uri);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Look a buffer's pending edit up in `doc`, its freshly analyzed text.
|
||||
/// An edit outside every connection list is forgotten on the spot: it
|
||||
/// withholds nothing and needs no release.
|
||||
pub fn locate(&mut self, uri: &Uri, doc: &Document) {
|
||||
let Some(edit) = self.edits.get_mut(uri) else { return };
|
||||
if !matches!(edit.state, Located::Pending) {
|
||||
return;
|
||||
}
|
||||
match entry_around(doc, edit.offset) {
|
||||
Some(entry) => edit.state = Located::Entry(entry),
|
||||
None => {
|
||||
self.edits.remove(uri);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `diagnostics` without the ones whose range starts inside the entry
|
||||
/// `uri`'s last edit is in. Everything, when there is no such entry.
|
||||
pub fn withhold(
|
||||
&self,
|
||||
uri: &Uri,
|
||||
doc: &Document,
|
||||
diagnostics: Vec<Diagnostic>,
|
||||
) -> Vec<Diagnostic> {
|
||||
let Some(entry) = self.entry_of(uri) else { return diagnostics };
|
||||
let positions = doc.positions();
|
||||
diagnostics
|
||||
.into_iter()
|
||||
.filter(|d| !inside(entry, positions.offset(d.range.start)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The entry `uri`'s last edit is in, while it is withholding.
|
||||
pub fn entry_of(&self, uri: &Uri) -> Option<TextRange> {
|
||||
match self.edits.get(uri)?.state {
|
||||
Located::Entry(entry) => Some(entry),
|
||||
Located::Pending => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop a buffer's edit — it was saved, closed or opened afresh — and say
|
||||
/// whether it was withholding anything, i.e. whether its full list is
|
||||
/// owed now.
|
||||
pub fn forget(&mut self, uri: &Uri) -> bool {
|
||||
matches!(self.edits.remove(uri), Some(LastEdit { state: Located::Entry(_), .. }))
|
||||
}
|
||||
|
||||
/// When the next release is due: the end of the earliest quiet period,
|
||||
/// or right away for an entry an edit elsewhere released.
|
||||
pub fn deadline(&self) -> Option<Instant> {
|
||||
self.edits.values().filter_map(LastEdit::due_at).min()
|
||||
}
|
||||
|
||||
/// Take every buffer whose release is due at `now`: their full lists are
|
||||
/// owed to the client.
|
||||
pub fn due(&mut self, now: Instant) -> Vec<Uri> {
|
||||
let due: Vec<Uri> = self
|
||||
.edits
|
||||
.iter()
|
||||
.filter(|(_, edit)| edit.due_at().is_some_and(|at| at <= now))
|
||||
.map(|(uri, _)| uri.clone())
|
||||
.collect();
|
||||
for uri in &due {
|
||||
self.edits.remove(uri);
|
||||
}
|
||||
due
|
||||
}
|
||||
}
|
||||
|
||||
impl LastEdit {
|
||||
/// When this edit's entry is to be released; `None` while it has no
|
||||
/// entry yet.
|
||||
fn due_at(&self) -> Option<Instant> {
|
||||
if !matches!(self.state, Located::Entry(_)) {
|
||||
return None;
|
||||
}
|
||||
if self.released {
|
||||
return Some(self.at);
|
||||
}
|
||||
Some(self.at.checked_add(PORT_ENTRY_GRACE).unwrap_or(self.at))
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `offset` lies in `entry`, both ends included: a diagnostic on the
|
||||
/// token that ends the entry (the `,` of `.b(y),)`, the `.` that proves a
|
||||
/// comma missing) is the entry's own news.
|
||||
fn inside(entry: TextRange, offset: u32) -> bool {
|
||||
entry.start <= offset && offset <= entry.end
|
||||
}
|
||||
|
||||
/// The extent of the connection-list entry around `offset`, or `None` when
|
||||
/// `offset` is not inside an instantiation's port or parameter list.
|
||||
///
|
||||
/// The entry starts at the last separator before `offset` at the list's own
|
||||
/// level — a `,`, which it includes, or the list's `(`, which it does not —
|
||||
/// or at a `.` that opens its own line, which is where the parser ends an
|
||||
/// entry left open on the line above. It ends at the first `,`, `;` or
|
||||
/// closing bracket after `offset` at the level `offset` is at, or at the end
|
||||
/// of `offset`'s line — reaching on to the next line's first token when that
|
||||
/// is a `.`, the token that proves a `,` is missing. A `;` ends it at any
|
||||
/// level: no connection list holds one.
|
||||
pub fn entry_around(doc: &Document, offset: u32) -> Option<TextRange> {
|
||||
let tokens = &doc.tokens;
|
||||
let list = enclosing_list(tokens, offset)?;
|
||||
let next = tokens.partition_point(|t| t.span.start < offset);
|
||||
// The bracket count above takes a value left open (`.po(`) for the list
|
||||
// never closing, so a list "around" an edit three items further down is
|
||||
// only believed when no `;` stands between them: a connection list never
|
||||
// holds one, and every item after it ends in one.
|
||||
if tokens.get(list.open + 1..next)?.iter().any(|t| t.is_sym(";")) {
|
||||
return None;
|
||||
}
|
||||
// Only an instance's *named* list: `enclosing_list` also accepts a
|
||||
// header's `name #(`, a positional list, a call after a block label and a
|
||||
// function whose return type is a name, and none of those is typed the
|
||||
// way a `.name(…)` connection is.
|
||||
if !holds_a_named_entry(tokens, list.open) || in_a_declaration_header(tokens, list.open) {
|
||||
return None;
|
||||
}
|
||||
let (start, depth) = entry_start(tokens, list.open, next);
|
||||
let (line, _) = doc.line_index.line_col(offset);
|
||||
let end = entry_end(&tokens[next..], depth, offset, line);
|
||||
Some(TextRange::new(start, end.max(start)))
|
||||
}
|
||||
|
||||
/// Walk from the list's `(` up to the token at `next`: where the entry there
|
||||
/// starts, and how many brackets are open inside it at that point.
|
||||
fn entry_start(tokens: &[Token], open: usize, next: usize) -> (u32, u32) {
|
||||
let mut start = tokens[open].span.end;
|
||||
let mut depth = 0u32;
|
||||
for i in open + 1..next {
|
||||
let t = &tokens[i];
|
||||
if t.is_sym(".") && tokens[i - 1].line != t.line {
|
||||
// A `.` opening its line starts an entry even inside a bracket:
|
||||
// the parser ends a value left open on the line above here.
|
||||
start = t.span.start;
|
||||
depth = 0;
|
||||
} else if is_open(t) {
|
||||
depth += 1;
|
||||
} else if is_close(t) {
|
||||
depth = depth.saturating_sub(1);
|
||||
} else if depth == 0 && t.is_sym(",") {
|
||||
start = t.span.start;
|
||||
}
|
||||
}
|
||||
(start, depth)
|
||||
}
|
||||
|
||||
/// Walk on from `offset` (`after` being the tokens from there on, `depth`
|
||||
/// the brackets open inside the entry, `line` 1-based): where the entry ends.
|
||||
fn entry_end(after: &[Token], mut depth: u32, offset: u32, line: u32) -> u32 {
|
||||
let mut end = offset;
|
||||
for t in after {
|
||||
if t.kind == TokenKind::Eof {
|
||||
break;
|
||||
}
|
||||
if t.line != line {
|
||||
return if t.is_sym(".") { t.span.start } else { end };
|
||||
}
|
||||
if is_close(t) {
|
||||
if depth == 0 {
|
||||
return t.span.start;
|
||||
}
|
||||
depth -= 1;
|
||||
} else if is_open(t) {
|
||||
depth += 1;
|
||||
} else if t.is_sym(";") || (depth == 0 && t.is_sym(",")) {
|
||||
return t.span.start;
|
||||
}
|
||||
end = t.span.end;
|
||||
}
|
||||
end
|
||||
}
|
||||
|
||||
/// The keywords whose header lists (`name #(`, `name (`) are declarations,
|
||||
/// never an instance's connections.
|
||||
const DECLARATION_HEADERS: &[&str] = &[
|
||||
"module",
|
||||
"macromodule",
|
||||
"interface",
|
||||
"program",
|
||||
"class",
|
||||
"package",
|
||||
"primitive",
|
||||
"function",
|
||||
"task",
|
||||
"checker",
|
||||
];
|
||||
|
||||
/// Whether the list opened at `open` holds an entry, at its own level, that
|
||||
/// starts with `.` — the entry being typed counts. A `.` opening its own line
|
||||
/// counts at any depth, as it does for [`entry_start`]: the parser ends a
|
||||
/// value left open on the line above there. The walk ends at the list's `)`,
|
||||
/// a `;`, or the end of the file.
|
||||
fn holds_a_named_entry(tokens: &[Token], open: usize) -> bool {
|
||||
let mut depth = 0u32;
|
||||
for i in open + 1..tokens.len() {
|
||||
let t = &tokens[i];
|
||||
let prev = &tokens[i - 1];
|
||||
if t.kind == TokenKind::Eof || t.is_sym(";") {
|
||||
return false;
|
||||
}
|
||||
if t.is_sym(".") {
|
||||
let entry_start = i == open + 1
|
||||
|| prev.line != t.line
|
||||
|| (depth == 0 && (prev.is_sym(",") || prev.kind == TokenKind::Attribute));
|
||||
if entry_start {
|
||||
return true;
|
||||
}
|
||||
} else if is_open(t) {
|
||||
depth += 1;
|
||||
} else if is_close(t) {
|
||||
if depth == 0 {
|
||||
return false;
|
||||
}
|
||||
depth -= 1;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether the list opened at `open` belongs to a declaration's header: a
|
||||
/// [`DECLARATION_HEADERS`] keyword stands between it and the `;` that ended
|
||||
/// the item before.
|
||||
fn in_a_declaration_header(tokens: &[Token], open: usize) -> bool {
|
||||
tokens[..open]
|
||||
.iter()
|
||||
.rev()
|
||||
.take_while(|t| !t.is_sym(";"))
|
||||
.any(|t| t.kind == TokenKind::Keyword && DECLARATION_HEADERS.contains(&t.text.as_str()))
|
||||
}
|
||||
|
||||
/// True on `(`, `[` or `{`.
|
||||
fn is_open(t: &Token) -> bool {
|
||||
t.is_sym("(") || t.is_sym("[") || t.is_sym("{")
|
||||
}
|
||||
|
||||
/// True on `)`, `]` or `}`.
|
||||
fn is_close(t: &Token) -> bool {
|
||||
t.is_sym(")") || t.is_sym("]") || t.is_sym("}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,350 @@
|
||||
//! The entry bounds, the withhold/release state machine with time injected,
|
||||
//! and what the parser's half buys the editor: the tokens and the findings
|
||||
//! after an unfinished entry are those of the completed one.
|
||||
|
||||
use std::str::FromStr;
|
||||
|
||||
use lsp_types::{DiagnosticSeverity, SemanticToken};
|
||||
|
||||
use super::*;
|
||||
use crate::state::Workspace;
|
||||
|
||||
fn uri(name: &str) -> Uri {
|
||||
Uri::from_str(&format!("file:///rtl/{name}")).expect("uri")
|
||||
}
|
||||
|
||||
/// A workspace holding `text` as `m.sv`.
|
||||
fn open(text: &str) -> (Workspace, Uri) {
|
||||
let uri = uri("m.sv");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
(ws, uri)
|
||||
}
|
||||
|
||||
/// `text` with the `|` marking the cursor taken out, and the cursor's offset.
|
||||
fn cursor(marked: &str) -> (String, u32) {
|
||||
let at = marked.find('|').expect("a `|` marks the cursor");
|
||||
(marked.replacen('|', "", 1), at as u32)
|
||||
}
|
||||
|
||||
/// The text of the entry around the `|` in `marked`, or `None`.
|
||||
fn entry_text(marked: &str) -> Option<String> {
|
||||
let (text, at) = cursor(marked);
|
||||
let (ws, uri) = open(&text);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
entry_around(doc, at).map(|r| text[r.as_range()].to_string())
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Entry bounds
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_entry_runs_from_the_comma_before_to_the_close_after() {
|
||||
let got = entry_text("module m;\n sub u0 (.a(x), .p|);\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(", .p"));
|
||||
let got = entry_text("module m;\n sub u0 (.p|, .a(x));\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(".p"), "the list's own `(` is not the entry's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cursor_inside_a_value_takes_the_whole_entry() {
|
||||
let got = entry_text("module m;\n sub u0 (.a(x), .b(y|), .c(z));\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(", .b(y)"));
|
||||
let got = entry_text("module m;\n sub u0 (.a(x), .b({p, q|}), .c(z));\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(", .b({p, q})"), "a `,` inside a bracket is the value's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entry_left_open_ends_with_its_line_and_reaches_the_next_dot() {
|
||||
// The parser's diagnostic is on the `(`; the next line opens a new entry,
|
||||
// whose `.` the entry reaches to.
|
||||
let got = entry_text("module m;\n sub u0 (.a(x), .po(|\n .b(y));\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(", .po(\n "));
|
||||
// Typing on the line below an entry left open: the entry is that line's.
|
||||
let got = entry_text("module m;\n sub u0 (.a(x), .po(\n .b(y|));\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(".b(y)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_comma_is_inside_the_entry_typed_on_either_side_of_it() {
|
||||
// Typed below: the entry starts at its own line's `.`, which is where the
|
||||
// parser reports the missing `,`.
|
||||
let got = entry_text("module m;\n sub u0 (.a(x)\n .b(y|));\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(".b(y)"));
|
||||
// Typed above: the entry reaches the next line's `.`.
|
||||
let got = entry_text("module m;\n sub u0 (.a(x), .po|\n .b(y));\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(", .po\n "));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trailing_comma_is_inside_the_entry_after_it() {
|
||||
let got = entry_text("module m;\n sub u0 (.a(x),|\n );\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(","));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_list_has_entries_too() {
|
||||
let got = entry_text("module m;\n sub #(.W(8), .D|) u0 (.a(x));\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(", .D"));
|
||||
let got = entry_text("module m;\n sub #(.W(|\n u0 (.a(x));\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(".W("), "an override typed open");
|
||||
}
|
||||
|
||||
/// The entry being typed is enough to make a list a named one, and so is
|
||||
/// any other named entry when the one being typed is still empty.
|
||||
#[test]
|
||||
fn a_named_list_is_recognised_from_any_named_entry() {
|
||||
let got = entry_text("module m;\n sub u0 (.po|);\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(".po"));
|
||||
let got = entry_text("module m;\n sub u0 (.|);\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some("."));
|
||||
let got = entry_text("module m;\n sub u0 (.a(x), |);\nendmodule\n");
|
||||
assert_eq!(got.as_deref(), Some(", "), "a fresh entry after a `,`");
|
||||
}
|
||||
|
||||
/// QA's list (2026-11-17): every list `enclosing_list` accepts that is not
|
||||
/// an instance's named list withholds nothing.
|
||||
#[test]
|
||||
fn lists_that_are_not_named_connections_withhold_nothing() {
|
||||
for marked in [
|
||||
// A module header's parameter list.
|
||||
"module hm #(parameter W = |) (input logic a);\nendmodule\n",
|
||||
"interface hi #(parameter W = 1|);\nendinterface\n",
|
||||
"class hc #(type T = int|);\nendclass\n",
|
||||
// A positional instance list.
|
||||
"module m;\n sub u0 (x, y|, z);\nendmodule\n",
|
||||
// A function declaration with a user-type return.
|
||||
"module m;\n function automatic my_t f(input a|);\n endfunction\nendmodule\n",
|
||||
// A call right after a block label.
|
||||
"module m;\n initial begin : blk\n my_task(a, b|);\n end\nendmodule\n",
|
||||
// A fresh, still empty instance list: nothing named in it yet.
|
||||
"module m;\n sub u0 (|);\nendmodule\n",
|
||||
] {
|
||||
assert_eq!(entry_text(marked), None, "{marked}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_outside_a_connection_list_is_an_entry() {
|
||||
for marked in [
|
||||
"module m;\n wire w|;\nendmodule\n",
|
||||
"module m;\n sub u0| (.a(x));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x));|\nendmodule\n",
|
||||
"module m;\n initial f(a, b|);\nendmodule\n",
|
||||
"module m (input a|, input b);\nendmodule\n",
|
||||
// A value left open makes the list's bracket look unclosed to the
|
||||
// end of the file; the `;` after it says the list is over.
|
||||
"module m;\n sub u0 (.a(x), .po(\n .b(y));\n wire w|;\nendmodule\n",
|
||||
] {
|
||||
assert_eq!(entry_text(marked), None, "{marked}");
|
||||
}
|
||||
// The next instance's own list is still found, and is its own.
|
||||
let marked = "module m;\n sub u0 (.a(x), .po(\n .b(y));\n sub u1 (.c|(z));\nendmodule\n";
|
||||
assert_eq!(entry_text(marked).as_deref(), Some(".c(z)"));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Withholding
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// A module whose port list is fine, so only the instance's entries say
|
||||
/// anything, plus one unrelated parse error far from the list.
|
||||
const TYPING: &str =
|
||||
"module m;\n logic x, y;\n sub u0 (.a(x),\n .po(\n .b(y));\n wire ;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn only_the_entry_being_typed_is_withheld() {
|
||||
let (mut ws, uri) = open(TYPING);
|
||||
let at = TYPING.find(".po(").expect("entry") as u32 + 4;
|
||||
let now = Instant::now();
|
||||
ws.port_grace_mut().edited(&uri, Some(at), now);
|
||||
ws.locate_port_entry(&uri);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let all = crate::diagnostics::all(doc);
|
||||
let errors: Vec<_> =
|
||||
all.iter().filter(|d| d.severity == Some(DiagnosticSeverity::ERROR)).collect();
|
||||
assert_eq!(errors.len(), 2, "the open `(` and the `wire ;`: {all:#?}");
|
||||
let shown = ws.port_grace().withhold(&uri, doc, all.clone());
|
||||
assert_eq!(shown.len(), all.len() - 1, "exactly the entry's one: {shown:#?}");
|
||||
assert!(shown.iter().any(|d| d.range.start.line == 5), "the `wire ;` is still said");
|
||||
assert!(shown.iter().all(|d| d.range.start.line != 3), "{shown:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_outside_every_list_withholds_nothing() {
|
||||
let (mut ws, uri) = open(TYPING);
|
||||
let at = TYPING.find("wire ;").expect("wire") as u32 + 4;
|
||||
ws.port_grace_mut().edited(&uri, Some(at), Instant::now());
|
||||
ws.locate_port_entry(&uri);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let all = crate::diagnostics::all(doc);
|
||||
assert_eq!(ws.port_grace().withhold(&uri, doc, all.clone()), all);
|
||||
assert_eq!(ws.port_grace().deadline(), None, "no release is owed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_document_change_withholds_nothing() {
|
||||
let (mut ws, uri) = open(TYPING);
|
||||
let at = TYPING.find(".po(").expect("entry") as u32 + 4;
|
||||
ws.port_grace_mut().edited(&uri, Some(at), Instant::now());
|
||||
ws.port_grace_mut().edited(&uri, None, Instant::now());
|
||||
ws.locate_port_entry(&uri);
|
||||
assert_eq!(ws.port_grace().entry_of(&uri), None);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The release, with time injected
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// A grace with one located entry in `uri`, edited at `t0`.
|
||||
fn held(ws: &mut Workspace, uri: &Uri, t0: Instant) {
|
||||
let at = TYPING.find(".po(").expect("entry") as u32 + 4;
|
||||
ws.port_grace_mut().edited(uri, Some(at), t0);
|
||||
ws.locate_port_entry(uri);
|
||||
assert!(ws.port_grace().entry_of(uri).is_some(), "premise: the edit is in an entry");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_entry_is_released_when_the_quiet_period_ends() {
|
||||
let (mut ws, uri) = open(TYPING);
|
||||
let t0 = Instant::now();
|
||||
held(&mut ws, &uri, t0);
|
||||
assert_eq!(ws.port_grace().deadline(), Some(t0 + PORT_ENTRY_GRACE));
|
||||
let almost = t0 + PORT_ENTRY_GRACE - Duration::from_millis(1);
|
||||
assert!(ws.port_grace_mut().due(almost).is_empty(), "not a moment early");
|
||||
assert_eq!(ws.port_grace_mut().due(t0 + PORT_ENTRY_GRACE), vec![uri.clone()]);
|
||||
assert_eq!(ws.port_grace().entry_of(&uri), None, "released means withholding nothing");
|
||||
assert_eq!(ws.port_grace().deadline(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_edit_restarts_the_quiet_period() {
|
||||
let (mut ws, uri) = open(TYPING);
|
||||
let t0 = Instant::now();
|
||||
held(&mut ws, &uri, t0);
|
||||
let t1 = t0 + Duration::from_millis(1000);
|
||||
held(&mut ws, &uri, t1);
|
||||
assert!(ws.port_grace_mut().due(t0 + PORT_ENTRY_GRACE).is_empty());
|
||||
assert_eq!(ws.port_grace_mut().due(t1 + PORT_ENTRY_GRACE), vec![uri]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unanalyzed_edit_is_not_due() {
|
||||
let (mut ws, uri) = open(TYPING);
|
||||
let t0 = Instant::now();
|
||||
ws.port_grace_mut().edited(&uri, Some(3), t0);
|
||||
assert_eq!(ws.port_grace().deadline(), None, "pending: the flush has not looked yet");
|
||||
assert!(ws.port_grace_mut().due(t0 + PORT_ENTRY_GRACE).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_in_another_buffer_releases_at_once() {
|
||||
let (mut ws, a) = open(TYPING);
|
||||
let b = uri("other.sv");
|
||||
let t0 = Instant::now();
|
||||
held(&mut ws, &a, t0);
|
||||
let t1 = t0 + Duration::from_millis(100);
|
||||
ws.port_grace_mut().edited(&b, Some(0), t1);
|
||||
assert_eq!(ws.port_grace().deadline(), Some(t0), "due already");
|
||||
assert_eq!(ws.port_grace_mut().due(t1), vec![a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forgetting_says_whether_anything_was_held() {
|
||||
let (mut ws, uri) = open(TYPING);
|
||||
assert!(!ws.port_grace_mut().forget(&uri), "nothing to forget");
|
||||
ws.port_grace_mut().edited(&uri, Some(3), Instant::now());
|
||||
assert!(!ws.port_grace_mut().forget(&uri), "pending withholds nothing");
|
||||
held(&mut ws, &uri, Instant::now());
|
||||
assert!(ws.port_grace_mut().forget(&uri));
|
||||
assert_eq!(ws.port_grace().entry_of(&uri), None);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The parser's half, as the editor sees it
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The module `sub` and an instance of it with `entry` as its second
|
||||
/// connection, on a line of its own (line 4, 0-based), then more after it.
|
||||
fn with_entry(entry: &str) -> String {
|
||||
format!(
|
||||
"module sub (input logic a, input logic po, output logic b);\nendmodule\n\
|
||||
module m;\n logic x, y;\n sub u0 (.a(x),\n {entry}\n .b(y));\n \
|
||||
assign x = y;\n sub u1 (.a(y), .po(x), .b());\nendmodule\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// Semantic tokens as absolute `(line, start, length, type, modifiers)`.
|
||||
fn absolute(tokens: &[SemanticToken]) -> Vec<(u32, u32, u32, u32, u32)> {
|
||||
let (mut line, mut start) = (0u32, 0u32);
|
||||
tokens
|
||||
.iter()
|
||||
.map(|t| {
|
||||
if t.delta_line > 0 {
|
||||
start = 0;
|
||||
}
|
||||
line += t.delta_line;
|
||||
start += t.delta_start;
|
||||
(line, start, t.length, t.token_type, t.token_modifiers_bitset)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What the editor shows after the entry's line: the semantic tokens and the
|
||||
/// diagnostics, the latter as `(line, character, message)`.
|
||||
type After = (Vec<(u32, u32, u32, u32, u32)>, Vec<(u32, u32, String)>);
|
||||
|
||||
fn after_entry(text: &str) -> After {
|
||||
let (ws, uri) = open(text);
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let entry_line = 5;
|
||||
let tokens = absolute(&crate::tokens::semantic_tokens(doc))
|
||||
.into_iter()
|
||||
.filter(|t| t.0 > entry_line)
|
||||
.collect();
|
||||
let diags = crate::diagnostics::all(doc)
|
||||
.into_iter()
|
||||
.filter(|d| d.range.start.line > entry_line)
|
||||
.map(|d| (d.range.start.line, d.range.start.character, d.message))
|
||||
.collect();
|
||||
(tokens, diags)
|
||||
}
|
||||
|
||||
/// The owner's ask: the rest of the file colours and lints as the
|
||||
/// auto-completed version (`.po` → `.po()`) would.
|
||||
#[test]
|
||||
fn after_an_unfinished_entry_the_file_reads_as_with_the_entry_completed() {
|
||||
// An entry the parser had to recover reads on to the next `.` as though
|
||||
// its `,` had been typed too.
|
||||
let done = after_entry(&with_entry(".po(),"));
|
||||
assert!(!done.0.is_empty(), "premise: there are tokens after the entry");
|
||||
assert!(done.1.is_empty(), "premise: the completed file says nothing: {:?}", done.1);
|
||||
for unfinished in [".po(", ".", ".po(x"] {
|
||||
assert_eq!(after_entry(&with_entry(unfinished)), done, "after `{unfinished}`");
|
||||
}
|
||||
// `.po` is already a whole (implicit) connection; what it still lacks is
|
||||
// the `,`, and so does its completion — the same one diagnostic, on the
|
||||
// `.` of the line after, in both.
|
||||
let done = after_entry(&with_entry(".po()"));
|
||||
assert_eq!(done.1.len(), 1, "{:?}", done.1);
|
||||
for unfinished in [".po", ".p"] {
|
||||
assert_eq!(after_entry(&with_entry(unfinished)), done, "after `{unfinished}`");
|
||||
}
|
||||
}
|
||||
|
||||
/// The unfinished entry is one parse error and nothing else: the entries
|
||||
/// written after it still resolve, so nothing about them is reported.
|
||||
#[test]
|
||||
fn an_unfinished_entry_costs_one_error_and_no_cascade() {
|
||||
for unfinished in [".po(", "."] {
|
||||
let (ws, uri) = open(&with_entry(unfinished));
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let errors: Vec<_> = crate::diagnostics::all(doc)
|
||||
.into_iter()
|
||||
.filter(|d| d.severity == Some(DiagnosticSeverity::ERROR))
|
||||
.collect();
|
||||
assert_eq!(errors.len(), 1, "`{unfinished}`: {errors:#?}");
|
||||
assert_eq!(errors[0].range.start.line, 5, "on the entry's own line");
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,24 @@ fn a_filelist_that_cannot_be_read_falls_back_to_the_walk_and_says_so() {
|
||||
assert!(warnings[0].contains("indexing the workspace instead"), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// Whether file modes bind this process: a mode-000 directory refuses to be
|
||||
/// listed. Root lists it anyway (Linux CI jobs run as root), so there the
|
||||
/// directory the scan cannot read cannot be built; the test says so and stops.
|
||||
#[cfg(unix)]
|
||||
fn listing_is_refused() -> bool {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let probe = Tree::new("modeprobe");
|
||||
let shut = probe.path.join("shut");
|
||||
fs::create_dir(&shut).expect("probe dir");
|
||||
fs::set_permissions(&shut, fs::Permissions::from_mode(0o000)).expect("chmod");
|
||||
let refused = fs::read_dir(&shut).is_err();
|
||||
let _ = fs::set_permissions(&shut, fs::Permissions::from_mode(0o755));
|
||||
if !refused {
|
||||
eprintln!("skipped: a mode-000 directory is readable by this user (root?)");
|
||||
}
|
||||
refused
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_unreadable_directory_is_said_once_per_scan_and_the_rest_is_indexed() {
|
||||
@@ -69,6 +87,9 @@ fn an_unreadable_directory_is_said_once_per_scan_and_the_rest_is_indexed() {
|
||||
// existed the walk returned an error the index simply dropped, so a
|
||||
// permission-denied directory cost every file after it silently.
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if !listing_is_refused() {
|
||||
return;
|
||||
}
|
||||
let tree = Tree::new("walkwarn");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/z.sv", "z");
|
||||
|
||||
@@ -18,13 +18,31 @@ use crate::convert::Positions;
|
||||
///
|
||||
/// A change with no range replaces the whole document — what a full-sync
|
||||
/// client sends, and what still works if one arrives mid-batch.
|
||||
///
|
||||
/// `#[cfg(test)]` since the server reads where the edit ended too
|
||||
/// ([`apply_changes_at`]); the tests, and the cross-check against the
|
||||
/// reference implementation, come in by this door.
|
||||
#[cfg(test)]
|
||||
pub fn apply_changes(text: &str, changes: &[TextDocumentContentChangeEvent]) -> String {
|
||||
apply_changes_at(text, changes).0
|
||||
}
|
||||
|
||||
/// `apply_changes`, and where the last change ended in the text that
|
||||
/// results: the byte offset just past what it inserted. `None` when the last
|
||||
/// change replaced the whole document — that says nothing about where anyone
|
||||
/// is typing (`docs/features/port-entry-grace/README.md`).
|
||||
pub fn apply_changes_at(
|
||||
text: &str,
|
||||
changes: &[TextDocumentContentChangeEvent],
|
||||
) -> (String, Option<u32>) {
|
||||
let mut text = text.to_string();
|
||||
let mut edit_end = None;
|
||||
for change in changes {
|
||||
let Some(range) = change.range else {
|
||||
// The whole document. This also resets the state that the ranges
|
||||
// after it in the same batch are positioned against.
|
||||
text.clone_from(&change.text);
|
||||
edit_end = None;
|
||||
continue;
|
||||
};
|
||||
// A fresh line table per change: each range is positioned against the
|
||||
@@ -46,8 +64,9 @@ pub fn apply_changes(text: &str, changes: &[TextDocumentContentChangeEvent]) ->
|
||||
continue;
|
||||
};
|
||||
text = format!("{before}{}{after}", change.text);
|
||||
edit_end = u32::try_from(start + change.text.len()).ok();
|
||||
}
|
||||
text
|
||||
(text, edit_end)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -84,6 +103,31 @@ mod tests {
|
||||
assert_eq!(after, "module m;\n wire ab;\nendmodule\n");
|
||||
}
|
||||
|
||||
/// Where the last change ended is the offset just past what it inserted,
|
||||
/// in the text that results — the cursor's place after typing it.
|
||||
#[test]
|
||||
fn the_edit_end_is_just_past_the_inserted_text() {
|
||||
let text = "module m;\n wire a;\nendmodule\n";
|
||||
let (after, end) = apply_changes_at(text, &[edit((1, 8), (1, 8), "bc")]);
|
||||
assert_eq!(after, "module m;\n wire abc;\nendmodule\n");
|
||||
assert_eq!(end, Some(20), "just past the `bc`");
|
||||
assert_eq!(&after[..20], "module m;\n wire abc");
|
||||
let (_, end) = apply_changes_at(text, &[edit((1, 7), (1, 8), "")]);
|
||||
assert_eq!(end, Some(17), "a delete ends where it started");
|
||||
}
|
||||
|
||||
/// The last change of a batch decides, and a rangeless one — a whole
|
||||
/// document — says nothing about where anyone is typing.
|
||||
#[test]
|
||||
fn the_edit_end_follows_the_last_change_and_a_whole_document_has_none() {
|
||||
let text = "module m;\nendmodule\n";
|
||||
let (_, end) = apply_changes_at(text, &[edit((0, 0), (0, 0), "x"), whole("module n;\n")]);
|
||||
assert_eq!(end, None);
|
||||
let (_, end) = apply_changes_at(text, &[whole("module n;\n"), edit((0, 9), (0, 9), "\n")]);
|
||||
assert_eq!(end, Some(10));
|
||||
assert_eq!(apply_changes_at(text, &[]), (text.to_string(), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delete_removes_exactly_the_range() {
|
||||
let text = "module m;\n wire aaa;\nendmodule\n";
|
||||
|
||||
@@ -115,6 +115,11 @@ impl Template {
|
||||
}
|
||||
|
||||
/// Every template offered in `dialect`, the shared ones first.
|
||||
///
|
||||
/// The order is the popup's order among templates: the tier writes each one's
|
||||
/// position here into its `sortText` (`completion-ux`, 2026-11-17), so two
|
||||
/// templates reached by the same prefix show in registry order rather than by
|
||||
/// label.
|
||||
pub fn for_dialect(dialect: Dialect) -> impl Iterator<Item = &'static Template> {
|
||||
let dialect_only = match dialect {
|
||||
Dialect::SystemVerilog => SYSTEMVERILOG,
|
||||
@@ -198,13 +203,8 @@ const SYSTEMVERILOG: &[Template] = &[
|
||||
detail: "for loop with a local loop variable",
|
||||
body: &[(0, "for (int ${1:i} = 0; $1 < ${2:N}; $1++) begin"), (1, "$0"), (0, "end")],
|
||||
},
|
||||
Template {
|
||||
label: "always_ff @(posedge clk)",
|
||||
prefix: "always_ff",
|
||||
gate: Gate::Item,
|
||||
detail: "synchronous block, no reset",
|
||||
body: &[(0, "always_ff @(posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
|
||||
},
|
||||
// With-reset before clock-only (TODO §68.1): a flop with an async reset is
|
||||
// the commoner one to write, and the registry order is the popup order.
|
||||
Template {
|
||||
label: "always_ff with reset",
|
||||
prefix: "always_ff",
|
||||
@@ -220,6 +220,13 @@ const SYSTEMVERILOG: &[Template] = &[
|
||||
(0, "end"),
|
||||
],
|
||||
},
|
||||
Template {
|
||||
label: "always_ff @(posedge clk)",
|
||||
prefix: "always_ff",
|
||||
gate: Gate::Item,
|
||||
detail: "synchronous block, no reset",
|
||||
body: &[(0, "always_ff @(posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
|
||||
},
|
||||
Template {
|
||||
label: "always_comb begin/end",
|
||||
prefix: "always_comb",
|
||||
@@ -267,13 +274,7 @@ const VERILOG: &[Template] = &[
|
||||
detail: "for loop over an existing variable",
|
||||
body: &[(0, "for (${1:i} = 0; $1 < ${2:N}; $1 = $1 + 1) begin"), (1, "$0"), (0, "end")],
|
||||
},
|
||||
Template {
|
||||
label: "always @(posedge clk)",
|
||||
prefix: "always",
|
||||
gate: Gate::Item,
|
||||
detail: "synchronous block, no reset",
|
||||
body: &[(0, "always @(posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
|
||||
},
|
||||
// With-reset first, as in the SystemVerilog list above.
|
||||
Template {
|
||||
label: "always @(posedge clk or negedge rst_n)",
|
||||
prefix: "always",
|
||||
@@ -289,6 +290,13 @@ const VERILOG: &[Template] = &[
|
||||
(0, "end"),
|
||||
],
|
||||
},
|
||||
Template {
|
||||
label: "always @(posedge clk)",
|
||||
prefix: "always",
|
||||
gate: Gate::Item,
|
||||
detail: "synchronous block, no reset",
|
||||
body: &[(0, "always @(posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
|
||||
},
|
||||
Template {
|
||||
label: "always @(*)",
|
||||
prefix: "always",
|
||||
|
||||
@@ -1,24 +1,30 @@
|
||||
//! `textDocument/semanticTokens/full`, `/range` and `/full/delta`.
|
||||
//!
|
||||
//! Classification comes from the lexer's token stream, refined for plain
|
||||
//! identifiers by `vlog_semantic`. The full mapping table is in
|
||||
//! `docs/features/lucisv-server/README.md`; the range and delta rules are in
|
||||
//! `docs/features/semantic-tokens-delta/README.md`.
|
||||
//! identifiers by `vlog_semantic` + `ExternalResolutions` and for module
|
||||
//! instantiations / `#(...)` parameter lists by `Document.tree`
|
||||
//! (`docs/features/instantiation-highlighting/README.md`). The full mapping
|
||||
//! table is in `docs/features/lucisv-server/README.md`; the range and delta
|
||||
//! rules are in `docs/features/semantic-tokens-delta/README.md`.
|
||||
//!
|
||||
//! One tokenizer and one encoder serve all three requests: classification
|
||||
//! produces [`Absolute`] tokens (line, column, length — the coordinates the
|
||||
//! protocol thinks in), a range answer drops the ones it does not want, and
|
||||
//! `encode` delta-encodes whatever is left from the start of the document.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use lsp_types::{
|
||||
Position, Range, SemanticToken, SemanticTokenModifier, SemanticTokenType, SemanticTokensEdit,
|
||||
};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{Semantics, SymbolKind};
|
||||
use vlog_semantic::{Definition, ExternalResolutions, Semantics, SymbolKind};
|
||||
|
||||
use crate::state::Document;
|
||||
|
||||
mod instantiation;
|
||||
|
||||
/// 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`].
|
||||
@@ -133,6 +139,7 @@ pub fn semantic_tokens_in_range(doc: &Document, range: Range) -> Vec<SemanticTok
|
||||
/// See `docs/features/large-file-mode/README.md`.
|
||||
pub fn semantic_tokens_in_window(doc: &Document, range: Range) -> Vec<SemanticToken> {
|
||||
let window = crate::large::window(doc, range);
|
||||
let overrides = HashMap::new();
|
||||
let mut pieces = Vec::new();
|
||||
// The comment spans the lexer never saw go in first; `flatten` sorts, so
|
||||
// the order they are collected in cannot reach the wire.
|
||||
@@ -140,16 +147,17 @@ pub fn semantic_tokens_in_window(doc: &Document, range: Range) -> Vec<SemanticTo
|
||||
pieces.push(Piece { span: *span, ty: Highlight::Comment, modifiers: 0 });
|
||||
}
|
||||
for token in &window.tokens {
|
||||
collect(token, &doc.semantics, &mut pieces);
|
||||
collect(token, doc, &overrides, &mut pieces);
|
||||
}
|
||||
encode(&within(flatten(pieces, doc), range))
|
||||
}
|
||||
|
||||
/// Classify the whole buffer, split at line boundaries, in wire order.
|
||||
fn absolute(doc: &Document) -> Vec<Absolute> {
|
||||
let overrides = instantiation::overrides(doc);
|
||||
let mut pieces = Vec::new();
|
||||
for token in &doc.tokens {
|
||||
collect(token, &doc.semantics, &mut pieces);
|
||||
collect(token, doc, &overrides, &mut pieces);
|
||||
}
|
||||
flatten(pieces, doc)
|
||||
}
|
||||
@@ -177,12 +185,17 @@ fn within(tokens: Vec<Absolute>, range: Range) -> Vec<Absolute> {
|
||||
/// after it on the same line — because [`flatten`] converts the offsets with a
|
||||
/// single forward cursor. Ordering is otherwise invisible: `flatten` sorts,
|
||||
/// and no two pieces here can start at the same byte.
|
||||
fn collect(token: &Token, semantics: &Semantics, out: &mut Vec<Piece>) {
|
||||
fn collect(
|
||||
token: &Token,
|
||||
doc: &Document,
|
||||
overrides: &HashMap<u32, Highlight>,
|
||||
out: &mut Vec<Piece>,
|
||||
) {
|
||||
for comment in &token.leading {
|
||||
out.push(Piece { span: comment.span, ty: Highlight::Comment, modifiers: 0 });
|
||||
}
|
||||
if let Some(ty) = classify(token, semantics) {
|
||||
out.push(Piece { span: token.span, ty, modifiers: modifiers(token, semantics) });
|
||||
if let Some(ty) = classify(token, doc, overrides) {
|
||||
out.push(Piece { span: token.span, ty, modifiers: modifiers(token, &doc.semantics) });
|
||||
}
|
||||
if let Some(comment) = &token.trailing {
|
||||
out.push(Piece { span: comment.span, ty: Highlight::Comment, modifiers: 0 });
|
||||
@@ -190,7 +203,14 @@ fn collect(token: &Token, semantics: &Semantics, out: &mut Vec<Piece>) {
|
||||
}
|
||||
|
||||
/// What a token is, or `None` for the ones this server does not colour.
|
||||
fn classify(token: &Token, semantics: &Semantics) -> Option<Highlight> {
|
||||
fn classify(
|
||||
token: &Token,
|
||||
doc: &Document,
|
||||
overrides: &HashMap<u32, Highlight>,
|
||||
) -> Option<Highlight> {
|
||||
if let Some(&ty) = overrides.get(&token.span.start) {
|
||||
return Some(ty);
|
||||
}
|
||||
match token.kind {
|
||||
TokenKind::Keyword => Some(Highlight::Keyword),
|
||||
TokenKind::Number => Some(Highlight::Number),
|
||||
@@ -201,8 +221,8 @@ fn classify(token: &Token, semantics: &Semantics) -> Option<Highlight> {
|
||||
// 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::Ident => Some(identifier_type(token.span.start, &doc.semantics, &doc.external)),
|
||||
// Punctuation outside `overrides`: deliberately not emitted, see the feature README.
|
||||
TokenKind::Symbol | TokenKind::Eof => None,
|
||||
}
|
||||
}
|
||||
@@ -219,16 +239,28 @@ fn modifiers(token: &Token, semantics: &Semantics) -> u32 {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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),
|
||||
/// What symbol kind `offset` resolves to across the file and workspace overlay.
|
||||
fn resolved_kind(
|
||||
offset: u32,
|
||||
semantics: &Semantics,
|
||||
external: &ExternalResolutions,
|
||||
) -> Option<SymbolKind> {
|
||||
match external.definition_of(semantics, offset)? {
|
||||
Definition::Local(symbol) => Some(symbol.kind),
|
||||
Definition::External(defs) => defs.first().map(|def| def.kind),
|
||||
}
|
||||
}
|
||||
|
||||
/// A plain identifier, classified through the symbol table and workspace
|
||||
/// overlay: its own declaration, the declaration it resolves to, or `variable`
|
||||
/// when nothing resolves it.
|
||||
fn identifier_type(
|
||||
offset: u32,
|
||||
semantics: &Semantics,
|
||||
external: &ExternalResolutions,
|
||||
) -> Highlight {
|
||||
match resolved_kind(offset, semantics, external) {
|
||||
Some(kind) => symbol_type(kind),
|
||||
None => Highlight::Variable,
|
||||
}
|
||||
}
|
||||
@@ -248,7 +280,7 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
|
||||
SymbolKind::Typedef => Highlight::Type,
|
||||
SymbolKind::EnumVariant => Highlight::EnumMember,
|
||||
SymbolKind::Param | SymbolKind::LocalParam | SymbolKind::TfArg => Highlight::Parameter,
|
||||
SymbolKind::Function | SymbolKind::Task => Highlight::Function,
|
||||
SymbolKind::Function | SymbolKind::Task | SymbolKind::Instance => Highlight::Function,
|
||||
SymbolKind::StructMember
|
||||
| SymbolKind::Constraint
|
||||
| SymbolKind::Coverpoint
|
||||
@@ -260,7 +292,6 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
|
||||
| SymbolKind::Net
|
||||
| SymbolKind::Var
|
||||
| SymbolKind::Genvar
|
||||
| SymbolKind::Instance
|
||||
| SymbolKind::Clocking
|
||||
| SymbolKind::Block => Highlight::Variable,
|
||||
// A property and a sequence are named, instantiated by name and take
|
||||
@@ -728,9 +759,19 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Decoded tokens with the identifier refinement folded away.
|
||||
fn coarsely(data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32)> {
|
||||
decode(data).into_iter().map(|(l, c, len, ty, _)| (l, c, len, coarse(ty))).collect()
|
||||
/// Decoded tokens with identifier refinement and AST-only punctuation
|
||||
/// (`#`, `.`, `*`) folded away so the unparsed window lexer can be compared
|
||||
/// against the full pipeline.
|
||||
fn coarsely(full: &Document, data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32)> {
|
||||
let positions = full.positions();
|
||||
decode(data)
|
||||
.into_iter()
|
||||
.filter(|&(line, character, ..)| {
|
||||
let at = positions.offset(Position { line, character });
|
||||
!full.token_at(at).is_some_and(|t| t.kind == TokenKind::Symbol)
|
||||
})
|
||||
.map(|(l, c, len, ty, _)| (l, c, len, coarse(ty)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether any construct in `doc` crosses `offset` — a block comment, a
|
||||
@@ -792,8 +833,8 @@ mod tests {
|
||||
continue;
|
||||
}
|
||||
assert_eq!(
|
||||
coarsely(&semantic_tokens_in_window(&fast, window)),
|
||||
coarsely(&semantic_tokens_in_range(&full, window)),
|
||||
coarsely(&full, &semantic_tokens_in_window(&fast, window)),
|
||||
coarsely(&full, &semantic_tokens_in_range(&full, window)),
|
||||
"{}: lines {from}..{to}",
|
||||
path.display()
|
||||
);
|
||||
@@ -889,7 +930,8 @@ mod tests {
|
||||
// Punctuation (`,`, `;`) is deliberately not classified at all, so it
|
||||
// never reaches `pieces` — only the tokens `classify` keeps are
|
||||
// expected on the wire.
|
||||
for token in window.tokens.iter().filter(|t| classify(t, &doc.semantics).is_some()) {
|
||||
let empty = HashMap::new();
|
||||
for token in window.tokens.iter().filter(|t| classify(t, &doc, &empty).is_some()) {
|
||||
let expected = positions.position(token.span.start);
|
||||
let found = decoded
|
||||
.iter()
|
||||
@@ -1291,4 +1333,129 @@ mod tests {
|
||||
let data = ranged(FOUR_LINES, range((3, 0), (1, 0)));
|
||||
assert!(decode(&data).is_empty(), "{:?}", decode(&data));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// module instantiation and `#(...)` parameter-list highlighting
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn named_tokens(text: &str) -> Vec<(String, u32, u32)> {
|
||||
with_document(text, |doc| {
|
||||
let pos = doc.positions();
|
||||
decode(&semantic_tokens(doc))
|
||||
.into_iter()
|
||||
.map(|(line, character, len, ty, mods)| {
|
||||
let start = pos.offset(Position { line, character }) as usize;
|
||||
let end = pos.offset(Position { line, character: character + len }) as usize;
|
||||
(doc.text[start..end].to_string(), ty, mods)
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_instantiation_distinguishes_module_params_instance_ports_and_connections() {
|
||||
let src = "\
|
||||
module top #(
|
||||
parameter int DATA_W = 32
|
||||
) (
|
||||
input logic clk,
|
||||
input logic rst_ni
|
||||
);
|
||||
logic [DATA_W-1:0] data_q;
|
||||
pkg::uart_core #(
|
||||
.BAUD_DIV (EXT_DIV),
|
||||
.WIDTH (DATA_W),
|
||||
.DEPTH (16)
|
||||
) u_uart (
|
||||
.clk_i (clk),
|
||||
.rst_ni,
|
||||
.data_o (data_q),
|
||||
.*
|
||||
);
|
||||
assign data_q = u_uart.tx_data;
|
||||
endmodule
|
||||
";
|
||||
let out = named_tokens(src);
|
||||
let find_nth = |word: &str, n: usize| {
|
||||
out.iter()
|
||||
.filter(|(w, ..)| w == word)
|
||||
.nth(n)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| panic!("{word} #{n} missing in {out:?}"))
|
||||
};
|
||||
|
||||
// Both `#` tokens (header parameter port list and instantiation overrides)
|
||||
// share `Parameter`, while `(` and `)` are never emitted.
|
||||
assert_eq!(find_nth("#", 0), ("#".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth("#", 1), ("#".into(), Highlight::Parameter as u32, 0));
|
||||
assert!(!out.iter().any(|(w, ..)| w == "(" || w == ")"));
|
||||
|
||||
// Scoped module name: `pkg` is Namespace, `uart_core` is Class.
|
||||
assert_eq!(find_nth("pkg", 0), ("pkg".into(), Highlight::Namespace as u32, 0));
|
||||
assert_eq!(find_nth("uart_core", 0), ("uart_core".into(), Highlight::Class as u32, 0));
|
||||
|
||||
// Parameter overrides: `.` and parameter names share `Parameter` with `#`,
|
||||
// as do local (`DATA_W`) and external (`EXT_DIV`) parameter values; `16` stays Number.
|
||||
assert_eq!(find_nth(".", 0), (".".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth("BAUD_DIV", 0), ("BAUD_DIV".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth("EXT_DIV", 0), ("EXT_DIV".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth(".", 1), (".".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth("WIDTH", 0), ("WIDTH".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth("DATA_W", 2), ("DATA_W".into(), Highlight::Parameter as u32, 0));
|
||||
assert_eq!(find_nth("16", 0), ("16".into(), Highlight::Number as u32, 0));
|
||||
|
||||
// Instance declaration and hierarchical use both highlight as `Function`.
|
||||
let fn_ty = Highlight::Function as u32;
|
||||
assert_eq!(find_nth("u_uart", 0), ("u_uart".into(), fn_ty, DECLARATION));
|
||||
assert_eq!(find_nth("u_uart", 1), ("u_uart".into(), fn_ty, 0));
|
||||
|
||||
// Port names (`.clk_i`, implicit `.rst_ni`, `.data_o`, wildcard `.*`) are `Property`,
|
||||
// while connected signals (`clk`, `data_q`) stay `Variable`.
|
||||
assert_eq!(find_nth(".", 3), (".".into(), Highlight::Property as u32, 0));
|
||||
assert_eq!(find_nth("clk_i", 0), ("clk_i".into(), Highlight::Property as u32, 0));
|
||||
assert_eq!(find_nth("clk", 1), ("clk".into(), Highlight::Variable as u32, 0));
|
||||
assert_eq!(find_nth("rst_ni", 1), ("rst_ni".into(), Highlight::Property as u32, 0));
|
||||
assert_eq!(find_nth("data_o", 0), ("data_o".into(), Highlight::Property as u32, 0));
|
||||
assert_eq!(find_nth("data_q", 1), ("data_q".into(), Highlight::Variable as u32, 0));
|
||||
assert_eq!(find_nth("*", 0), ("*".into(), Highlight::Property as u32, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delay_hashes_are_never_classified_as_parameters() {
|
||||
let src = "\
|
||||
module m;
|
||||
wire #5 a;
|
||||
assign #(1:2:3) a = 1'b0;
|
||||
and #(2, 3) g0 (y, a, a);
|
||||
initial #10 $finish;
|
||||
endmodule
|
||||
";
|
||||
let out = named_tokens(src);
|
||||
assert!(!out.iter().any(|(w, ..)| w == "#"), "delays keep `#` unemitted: {out:?}");
|
||||
assert!(out.contains(&("g0".into(), Highlight::Function as u32, DECLARATION)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unfinished_port_and_param_entries_keep_their_highlights_while_typing() {
|
||||
let src = "\
|
||||
module m;
|
||||
sub #(
|
||||
.WIDTH(
|
||||
) u0 (
|
||||
.clk_i(
|
||||
.rst_ni(rst_n)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
let out = named_tokens(src);
|
||||
assert!(out.contains(&("sub".into(), Highlight::Class as u32, 0)));
|
||||
assert!(out.contains(&("#".into(), Highlight::Parameter as u32, 0)));
|
||||
assert!(out.contains(&("WIDTH".into(), Highlight::Parameter as u32, 0)));
|
||||
assert!(out.contains(&("u0".into(), Highlight::Function as u32, DECLARATION)));
|
||||
assert!(out.contains(&("clk_i".into(), Highlight::Property as u32, 0)));
|
||||
assert!(out.contains(&("rst_ni".into(), Highlight::Property as u32, 0)));
|
||||
assert!(out.contains(&("rst_n".into(), Highlight::Variable as u32, 0)));
|
||||
reconstructs(MODULE, src);
|
||||
reconstructs(src, MODULE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
//! AST-guided semantic token overrides for module instantiations and `#(...)`
|
||||
//! parameter lists.
|
||||
//!
|
||||
//! Plain lexical + symbol-table classification leaves an external module's
|
||||
//! name, its `#` parameter sigil, its `.PARAM` overrides and its `.port`
|
||||
//! connections as uncoloured punctuation or generic `variable`s. Walking
|
||||
//! [`Document::tree`] supplies the syntactic role of each token directly from
|
||||
//! the parsed AST, even before workspace indexing finishes or when the
|
||||
//! instantiated unit lives outside the indexed tree.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use vlog_parser::ast::{
|
||||
BindDirective, ClassDecl, ClassExtends, Connection, Connections, DataType, Expr,
|
||||
GateInstantiation, GenElse, Instantiation, Item, ItemKind, ListElem, Module, PortList, RawText,
|
||||
Typedef, TypedefKind,
|
||||
};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{ExternalResolutions, Semantics, SymbolKind};
|
||||
|
||||
use super::{resolved_kind, Highlight};
|
||||
use crate::state::{first_token_from, Document};
|
||||
|
||||
/// Token-start byte offset -> highlight overrides derived from `doc.tree`.
|
||||
pub(super) fn overrides(doc: &Document) -> HashMap<u32, Highlight> {
|
||||
let mut out = HashMap::new();
|
||||
if doc.tokens.is_empty() {
|
||||
return out;
|
||||
}
|
||||
let mut ctx = Ctx {
|
||||
tokens: &doc.tokens,
|
||||
semantics: &doc.semantics,
|
||||
external: &doc.external,
|
||||
out: &mut out,
|
||||
};
|
||||
ctx.items(&doc.tree.items);
|
||||
out
|
||||
}
|
||||
|
||||
struct Ctx<'a> {
|
||||
tokens: &'a [Token],
|
||||
semantics: &'a Semantics,
|
||||
external: &'a ExternalResolutions,
|
||||
out: &'a mut HashMap<u32, Highlight>,
|
||||
}
|
||||
|
||||
impl<'a> Ctx<'a> {
|
||||
fn items(&mut self, items: &[Item]) {
|
||||
for item in items {
|
||||
self.item(item);
|
||||
}
|
||||
}
|
||||
|
||||
fn item(&mut self, item: &Item) {
|
||||
match &item.kind {
|
||||
ItemKind::Module(m) => self.module(m, item.span.end),
|
||||
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => {
|
||||
self.items(items)
|
||||
}
|
||||
ItemKind::Class(c) => self.class(c, item.span.end),
|
||||
ItemKind::Instantiation(inst) => self.instantiation(inst, item.span.end),
|
||||
ItemKind::Bind(bind) => self.bind(bind, item.span.end),
|
||||
ItemKind::GateInstantiation(gate) => self.gate(gate),
|
||||
ItemKind::GenBlock(b) => self.items(&b.items),
|
||||
ItemKind::GenIf(g) => {
|
||||
self.items(&g.then.items);
|
||||
self.gen_else(g.els.as_deref());
|
||||
}
|
||||
ItemKind::GenFor(g) => self.items(&g.body.items),
|
||||
ItemKind::GenCase(g) => {
|
||||
for arm in &g.items {
|
||||
self.items(&arm.body.items);
|
||||
}
|
||||
}
|
||||
ItemKind::DataDecl(d) => self.data_type(&d.ty),
|
||||
ItemKind::PortDecl(p) => self.data_type(&p.ty),
|
||||
ItemKind::ParamDecl(p) => self.data_type(&p.ty),
|
||||
ItemKind::Typedef(t) => self.typedef(t),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_else(&mut self, els: Option<&GenElse>) {
|
||||
match els {
|
||||
Some(GenElse::If(_, inner)) => {
|
||||
self.items(&inner.then.items);
|
||||
self.gen_else(inner.els.as_deref());
|
||||
}
|
||||
Some(GenElse::Block(block)) => self.items(&block.items),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn module(&mut self, m: &Module, end: u32) {
|
||||
if m.param_ports.is_some() {
|
||||
let last = m.imports.last().and_then(|imp| imp.paths.last());
|
||||
let from = last.map_or(m.name_span.end, |p| p.item.span.end);
|
||||
self.param_hash(from, end);
|
||||
}
|
||||
for elem in m.param_ports.iter().flatten() {
|
||||
if let Some(port) = elem.ok() {
|
||||
self.data_type(&port.ty);
|
||||
}
|
||||
}
|
||||
if let PortList::Ansi(ports) = &m.ports {
|
||||
for elem in ports {
|
||||
if let Some(port) = elem.ok() {
|
||||
self.data_type(&port.ty);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.items(&m.items);
|
||||
}
|
||||
|
||||
fn class(&mut self, c: &ClassDecl, end: u32) {
|
||||
if c.param_ports.is_some() {
|
||||
self.param_hash(c.name_span.end, end);
|
||||
for elem in c.param_ports.iter().flatten() {
|
||||
if let Some(port) = elem.ok() {
|
||||
self.data_type(&port.ty);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(ext) = &c.extends {
|
||||
self.class_extends(ext);
|
||||
}
|
||||
self.items(&c.items);
|
||||
}
|
||||
|
||||
fn class_extends(&mut self, ext: &ClassExtends) {
|
||||
self.scoped_unit(ext.name_span);
|
||||
if let Some(params) = &ext.params {
|
||||
self.param_hash(ext.name_span.end, ext.span.end);
|
||||
self.param_overrides(params);
|
||||
}
|
||||
}
|
||||
|
||||
fn typedef(&mut self, t: &Typedef) {
|
||||
if let TypedefKind::Alias(ty) = &t.kind {
|
||||
self.data_type(ty);
|
||||
}
|
||||
}
|
||||
|
||||
fn data_type(&mut self, ty: &DataType) {
|
||||
if let Some(params) = ty.params() {
|
||||
self.param_hash(params.span.start, params.span.end);
|
||||
}
|
||||
}
|
||||
|
||||
fn instantiation(&mut self, inst: &Instantiation, end: u32) {
|
||||
self.scoped_unit(inst.module_span);
|
||||
if let Some(params) = &inst.params {
|
||||
self.param_hash(inst.module_span.end, end);
|
||||
self.param_overrides(params);
|
||||
}
|
||||
for instance in &inst.instances {
|
||||
self.ident_at(instance.name_span, Highlight::Function);
|
||||
self.port_connections(&instance.conns);
|
||||
}
|
||||
}
|
||||
|
||||
fn bind(&mut self, b: &BindDirective, end: u32) {
|
||||
if let [only] = &b.target[..] {
|
||||
let kind = resolved_kind(only.span.start, self.semantics, self.external);
|
||||
if only.index.is_none() && kind != Some(SymbolKind::Instance) {
|
||||
self.ident_at(only.span, Highlight::Class);
|
||||
}
|
||||
}
|
||||
for inst in &b.instances {
|
||||
self.ident_at(inst.span, Highlight::Function);
|
||||
}
|
||||
self.instantiation(&b.inst, end);
|
||||
}
|
||||
|
||||
fn gate(&mut self, g: &GateInstantiation) {
|
||||
for inst in &g.instances {
|
||||
if let Some(span) = inst.name_span {
|
||||
self.ident_at(span, Highlight::Function);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn param_overrides(&mut self, params: &[ListElem<Connection>]) {
|
||||
for elem in params {
|
||||
match elem {
|
||||
ListElem::Ok(conn) => {
|
||||
self.named_entry(conn, Highlight::Parameter);
|
||||
if let Some(expr) = &conn.expr {
|
||||
self.param_expr(expr);
|
||||
}
|
||||
}
|
||||
ListElem::Error(raw) => self.recovered_entry(raw, Highlight::Parameter),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn port_connections(&mut self, conns: &Connections) {
|
||||
let Connections::Named(list) = conns else { return };
|
||||
for elem in list {
|
||||
match elem {
|
||||
ListElem::Ok(conn) => self.named_entry(conn, Highlight::Property),
|
||||
ListElem::Error(raw) => self.recovered_entry(raw, Highlight::Property),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn named_entry(&mut self, conn: &Connection, ty: Highlight) {
|
||||
if conn.name_span.is_empty() {
|
||||
return;
|
||||
}
|
||||
for tok in self.tokens_in(TextRange::new(conn.span.start, conn.name_span.start)) {
|
||||
if tok.is_sym(".") {
|
||||
self.out.insert(tok.span.start, ty);
|
||||
}
|
||||
}
|
||||
for tok in self.tokens_in(conn.name_span) {
|
||||
if (tok.kind == TokenKind::Ident && !tok.is_macro()) || tok.is_sym("*") {
|
||||
self.out.insert(tok.span.start, ty);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn recovered_entry(&mut self, raw: &RawText, ty: Highlight) {
|
||||
let mut saw_dot = false;
|
||||
for tok in self.tokens_in(raw.span) {
|
||||
if tok.kind == TokenKind::Attribute {
|
||||
continue;
|
||||
}
|
||||
if !saw_dot && tok.is_sym(".") {
|
||||
self.out.insert(tok.span.start, ty);
|
||||
saw_dot = true;
|
||||
continue;
|
||||
}
|
||||
if saw_dot && ((tok.kind == TokenKind::Ident && !tok.is_macro()) || tok.is_sym("*")) {
|
||||
self.out.insert(tok.span.start, ty);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
fn param_expr(&mut self, expr: &Expr) {
|
||||
if expr.span.is_empty() {
|
||||
return;
|
||||
}
|
||||
let start = first_token_from(self.tokens, expr.span.start);
|
||||
let slice = self.tokens.get(start..).unwrap_or(&[]);
|
||||
let len = slice.partition_point(|t| t.span.end <= expr.span.end);
|
||||
for (idx, tok) in slice[..len].iter().enumerate() {
|
||||
if tok.kind != TokenKind::Ident || tok.is_macro() {
|
||||
continue;
|
||||
}
|
||||
if resolved_kind(tok.span.start, self.semantics, self.external).is_some() {
|
||||
continue;
|
||||
}
|
||||
let abs = start + idx;
|
||||
let next = self.tokens.get(abs + 1);
|
||||
let prev = abs.checked_sub(1).and_then(|i| self.tokens.get(i));
|
||||
let ty = if next.is_some_and(|t| t.is_sym("::")) {
|
||||
Highlight::Namespace
|
||||
} else if next.is_some_and(|t| t.is_sym("(")) && !prev.is_some_and(|t| t.is_sym(".")) {
|
||||
Highlight::Function
|
||||
} else {
|
||||
Highlight::Parameter
|
||||
};
|
||||
self.out.insert(tok.span.start, ty);
|
||||
}
|
||||
}
|
||||
|
||||
fn scoped_unit(&mut self, span: TextRange) {
|
||||
let idents: Vec<&Token> = self
|
||||
.tokens_in(span)
|
||||
.iter()
|
||||
.filter(|t| t.kind == TokenKind::Ident && !t.is_macro())
|
||||
.collect();
|
||||
let Some((&last, prefix)) = idents.split_last() else { return };
|
||||
for &seg in prefix {
|
||||
self.out.insert(seg.span.start, Highlight::Namespace);
|
||||
}
|
||||
self.out.insert(last.span.start, Highlight::Class);
|
||||
}
|
||||
|
||||
fn ident_at(&mut self, span: TextRange, ty: Highlight) {
|
||||
for tok in self.tokens_in(span) {
|
||||
if tok.kind == TokenKind::Ident && !tok.is_macro() {
|
||||
self.out.insert(tok.span.start, ty);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn param_hash(&mut self, from: u32, until: u32) {
|
||||
let start = first_token_from(self.tokens, from);
|
||||
for tok in self.tokens.get(start..).unwrap_or(&[]) {
|
||||
if tok.span.start >= until || tok.is_sym("(") || tok.is_sym(";") {
|
||||
break;
|
||||
}
|
||||
if tok.is_sym("#") {
|
||||
self.out.insert(tok.span.start, Highlight::Parameter);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn tokens_in(&self, span: TextRange) -> &'a [Token] {
|
||||
if span.is_empty() {
|
||||
return &[];
|
||||
}
|
||||
let start = first_token_from(self.tokens, span.start);
|
||||
let slice = self.tokens.get(start..).unwrap_or(&[]);
|
||||
let len = slice.partition_point(|t| t.span.end <= span.end);
|
||||
&slice[..len]
|
||||
}
|
||||
}
|
||||
@@ -278,6 +278,57 @@ fn range_formatting_is_advertised_and_formats_only_the_selection() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Tab-indented, with a parse error after the block: the shape of a buffer
|
||||
/// mid-edit that "Format Selection" (TODO §66.2) must still serve.
|
||||
const TABBED_BROKEN: &str = "module m;\n\talways @* begin\n\t\tif (a) x=1;\n\t\telse x=2;\n\tend\n\tassign y = ;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn range_formatting_lays_out_a_nested_selection_in_place_over_the_wire() {
|
||||
let dir = temp_dir("selectionfmt");
|
||||
let file = dir.join("m.sv");
|
||||
std::fs::write(&file, TABBED_BROKEN).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
let request = |id: u32, sl: u32, el: u32| {
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/rangeFormatting","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":{sl},"character":0}},"end":{{"line":{el},"character":0}}}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
|
||||
))
|
||||
};
|
||||
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(TABBED_BROKEN).expect("json")
|
||||
)),
|
||||
// The two statement lines inside the `always`.
|
||||
request(2, 2, 4),
|
||||
// The broken line itself: refused, no edit.
|
||||
request(3, 5, 6),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&session);
|
||||
assert_eq!(
|
||||
new_text(&messages, 2),
|
||||
"module m;\n\talways @* begin\n\t\tif (a) x = 1;\n\t\telse x = 2;\n\tend\n\tassign y = ;\nendmodule\n",
|
||||
"only the selected statement moves, tabs kept, error elsewhere ignored"
|
||||
);
|
||||
let refused = messages.iter().find(|m| m["id"] == 3).expect("response");
|
||||
assert!(
|
||||
refused.get("error").is_some()
|
||||
|| refused["result"].is_null()
|
||||
|| refused["result"] == serde_json::json!([]),
|
||||
"{refused}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Four items on four lines, so two ranges can straddle one they leave alone.
|
||||
const FOUR_ITEMS: &str = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n";
|
||||
|
||||
@@ -1040,6 +1091,64 @@ fn typing_a_newline_and_a_semicolon_round_trips_over_the_real_binary() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `begin` + Enter writes the `end` over the wire, and a pushed
|
||||
/// `lucisv.autoEnd: false` takes it back to the plain indent answer
|
||||
/// (`docs/features/completion-ux`).
|
||||
#[test]
|
||||
fn a_newline_after_begin_writes_the_end_unless_auto_end_is_off() {
|
||||
let dir = temp_dir("ontype_end");
|
||||
let file = dir.join("m.sv");
|
||||
let text = "module m;\n always_ff @(posedge clk) begin\n\nendmodule\n";
|
||||
std::fs::write(&file, text).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
let on_type = |id: u32| {
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/onTypeFormatting","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":0}},"ch":"\n","options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
|
||||
))
|
||||
};
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(text).expect("json")
|
||||
)),
|
||||
on_type(2),
|
||||
frame(
|
||||
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"autoEnd":false}}}}"#,
|
||||
),
|
||||
on_type(3),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&session);
|
||||
let edits = |id: u32| {
|
||||
let response = messages.iter().find(|m| m["id"] == id).expect("a response");
|
||||
response["result"].as_array().expect("an array of edits").clone()
|
||||
};
|
||||
|
||||
let with_end = edits(2);
|
||||
assert_eq!(with_end.len(), 2, "{with_end:#?}");
|
||||
assert_eq!(with_end[0]["newText"], " ", "the body line's indent");
|
||||
assert_eq!(with_end[1]["newText"], " end\n", "the `end` under its `always_ff`");
|
||||
assert_eq!(
|
||||
with_end[1]["range"]["start"],
|
||||
serde_json::json!({ "line": 3, "character": 0 }),
|
||||
"inserted at the start of the line after the cursor's"
|
||||
);
|
||||
|
||||
let without = edits(3);
|
||||
assert_eq!(without.len(), 1, "autoEnd off: the indent alone: {without:#?}");
|
||||
assert_eq!(without[0]["newText"], " ");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pushed_exclude_rebuilds_the_index_mid_session() {
|
||||
// The one link a unit test cannot check: that the notification handler
|
||||
@@ -2200,14 +2309,18 @@ fn inline_templates_round_trip_over_the_wire() {
|
||||
assert_eq!(item["insertText"]["value"], "${1:cond}) begin\n\t$0\nend");
|
||||
assert_eq!(item["range"]["start"], item["range"]["end"], "an insertion, not a replacement");
|
||||
|
||||
// `always @(` is the one trigger with a list: the clocked block first, the
|
||||
// combinational one second, both at the same empty range.
|
||||
let two = items(5);
|
||||
let two = two["items"].as_array().expect("a list");
|
||||
assert_eq!(two.len(), 2, "{two:#?}");
|
||||
assert_eq!(two[0]["insertText"]["value"], "posedge ${1:clk}) begin\n\t$0\nend");
|
||||
assert_eq!(two[1]["insertText"]["value"], "*) begin\n\t$0\nend");
|
||||
assert_eq!(two[0]["range"], two[1]["range"], "both insert at the cursor");
|
||||
// `always @(` is a trigger with a list: clock and reset first, clock only
|
||||
// second, the combinational block third, all at the same empty range.
|
||||
let three = items(5);
|
||||
let three = three["items"].as_array().expect("a list");
|
||||
assert_eq!(three.len(), 3, "{three:#?}");
|
||||
assert_eq!(
|
||||
three[0]["insertText"]["value"],
|
||||
"posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend"
|
||||
);
|
||||
assert_eq!(three[1]["insertText"]["value"], "posedge ${1:clk}) begin\n\t$0\nend");
|
||||
assert_eq!(three[2]["insertText"]["value"], "*) begin\n\t$0\nend");
|
||||
assert_eq!(three[0]["range"], three[2]["range"], "all insert at the cursor");
|
||||
|
||||
assert_eq!(items(4), serde_json::Value::Null, "nowhere near a trigger");
|
||||
|
||||
@@ -2377,14 +2490,16 @@ fn keyword_and_project_completion_round_trip_over_the_wire() {
|
||||
assert_eq!(local["kind"], 6, "CompletionItemKind.Variable");
|
||||
assert!(local["sortText"].as_str().expect("sortText").starts_with('1'), "{local:#?}");
|
||||
|
||||
// `4`, not `2`: `completion-ux` (2026-11-17) put this file's own
|
||||
// declarations (`2`) and words (`3`) ahead of what other files declare.
|
||||
let macro_name = labelled("WIDGET_MACRO").expect("a `define name");
|
||||
assert!(macro_name["sortText"].as_str().expect("sortText").starts_with('2'));
|
||||
assert!(macro_name["sortText"].as_str().expect("sortText").starts_with('4'));
|
||||
|
||||
let elsewhere = labelled("widget_elsewhere").expect("a word used in the project");
|
||||
assert_eq!(elsewhere["kind"], 1, "CompletionItemKind.Text");
|
||||
// `5`, not `4`: M6 inserted the template tier above the keywords, which
|
||||
// pushed the keyword and word tiers' digits down by one.
|
||||
assert!(elsewhere["sortText"].as_str().expect("sortText").starts_with('5'));
|
||||
// `7`: M6 inserted the template tier above the keywords, and
|
||||
// `completion-ux` the two current-file tiers above the index.
|
||||
assert!(elsewhere["sortText"].as_str().expect("sortText").starts_with('7'));
|
||||
|
||||
assert!(
|
||||
!items.iter().any(|item| item["sortText"].as_str().is_some_and(|s| s.starts_with('0'))),
|
||||
@@ -2560,12 +2675,12 @@ fn a_template_completion_round_trips_over_the_wire() {
|
||||
assert_eq!(template["textEdit"]["range"]["start"]["line"], 2);
|
||||
assert_eq!(template["textEdit"]["range"]["start"]["character"], 4);
|
||||
assert_eq!(template["textEdit"]["range"]["end"]["character"], 6);
|
||||
assert!(template["sortText"].as_str().expect("sortText").starts_with('3'));
|
||||
assert!(template["sortText"].as_str().expect("sortText").starts_with('5'));
|
||||
|
||||
// The keyword survives beside it, one tier down.
|
||||
let keyword = labelled(items, "if").expect("the keyword");
|
||||
assert_eq!(keyword["kind"], 14, "CompletionItemKind.Keyword");
|
||||
assert!(keyword["sortText"].as_str().expect("sortText").starts_with('4'));
|
||||
assert!(keyword["sortText"].as_str().expect("sortText").starts_with('6'));
|
||||
|
||||
// A `.v` buffer is offered Verilog's `always`, never `always_ff`.
|
||||
let verilog = messages.iter().find(|m| m["id"] == 3).expect("completion response");
|
||||
@@ -7247,8 +7362,16 @@ fn a_connection_list_completes_ports_over_the_wire() {
|
||||
assert_eq!(edit["range"]["start"], edit["range"]["end"], "an empty range at the cursor");
|
||||
}
|
||||
|
||||
// A port already connected is not offered again.
|
||||
assert_eq!(labels(3), vec!["data", "ready"]);
|
||||
// A port already connected is still offered, after the others and
|
||||
// marked (`completion-ux`, 2026-11-17 — it used to be dropped).
|
||||
assert_eq!(labels(3), vec!["clk", "data", "ready"]);
|
||||
let partly_items = response(3)["result"]["items"].as_array().expect("a list");
|
||||
let clk = partly_items.iter().find(|i| i["label"] == "clk").expect("clk");
|
||||
assert!(clk["sortText"].as_str().is_some_and(|s| s.starts_with('1')), "{clk:#?}");
|
||||
assert_eq!(clk["labelDetails"]["description"], "connected");
|
||||
let data = partly_items.iter().find(|i| i["label"] == "data").expect("data");
|
||||
assert!(data["sortText"].as_str().is_some_and(|s| s.starts_with('0')), "{data:#?}");
|
||||
assert!(data.get("labelDetails").is_none(), "{data:#?}");
|
||||
|
||||
// And `#(.` lists the parameters instead.
|
||||
assert_eq!(labels(4), vec!["WIRE_W"]);
|
||||
@@ -7256,6 +7379,94 @@ fn a_connection_list_completes_ports_over_the_wire() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `completion-ux` over the wire: a port item, asked by a client that reads
|
||||
/// snippets, writes `.name($1)` — pre-filled where the instantiating module
|
||||
/// has a same-named signal — and a typed keyword prefix grows a keyword
|
||||
/// ghost, following the popup's selected entry when one is sent.
|
||||
#[test]
|
||||
fn port_snippets_and_keyword_ghosts_round_trip_over_the_wire() {
|
||||
let dir = temp_dir("completionux");
|
||||
std::fs::write(
|
||||
dir.join("ux_sub.sv"),
|
||||
"module ux_sub (\n input logic clk,\n input logic data\n);\nendmodule\n",
|
||||
)
|
||||
.expect("write");
|
||||
let text = "module ux_top;\n logic clk;\n ux_sub u_sub (\n .\n );\n alw\nendmodule\n";
|
||||
let top = dir.join("ux_top.sv");
|
||||
std::fs::write(&top, text).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", top.display());
|
||||
let inline = |id: u32, selected: &str| {
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/inlineCompletion","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":5,"character":5}},"context":{{"triggerKind":2{selected}}}}}}}"#
|
||||
))
|
||||
};
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"completion":{{"completionItem":{{"snippetSupport":true}}}}}}}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(text).expect("json")
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":3,"character":5}},"context":{{"triggerKind":2,"triggerCharacter":"."}}}}}}"#
|
||||
)),
|
||||
inline(3, ""),
|
||||
inline(
|
||||
4,
|
||||
r#","selectedCompletionInfo":{"range":{"start":{"line":5,"character":2},"end":{"line":5,"character":5}},"text":"always_comb"}"#,
|
||||
),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&session);
|
||||
let result = |id: u32| {
|
||||
messages
|
||||
.iter()
|
||||
.find(|m| m["id"] == id)
|
||||
.unwrap_or_else(|| panic!("no response {id} in {messages:#?}"))["result"]
|
||||
.clone()
|
||||
};
|
||||
|
||||
let ports = result(2);
|
||||
let ports = ports["items"].as_array().expect("a list");
|
||||
let port = |name: &str| ports.iter().find(|i| i["label"] == name).expect("a port").clone();
|
||||
assert_eq!(port("clk")["textEdit"]["newText"], "clk(${1:clk})", "pre-filled from `logic clk`");
|
||||
assert_eq!(port("data")["textEdit"]["newText"], "data(${1})");
|
||||
assert_eq!(port("data")["insertTextFormat"], 2, "InsertTextFormat.Snippet");
|
||||
|
||||
let cursor = serde_json::json!({ "line": 5, "character": 5 });
|
||||
assert_eq!(
|
||||
result(3),
|
||||
serde_json::json!({
|
||||
"items": [{
|
||||
"insertText": { "kind": "snippet", "value": "ays_ff" },
|
||||
"range": { "start": cursor, "end": cursor }
|
||||
}]
|
||||
}),
|
||||
"the rest of the keyword, inserted at the cursor"
|
||||
);
|
||||
assert_eq!(
|
||||
result(4),
|
||||
serde_json::json!({
|
||||
"items": [{
|
||||
"insertText": { "kind": "snippet", "value": "always_comb" },
|
||||
"range": {
|
||||
"start": { "line": 5, "character": 2 },
|
||||
"end": { "line": 5, "character": 5 }
|
||||
}
|
||||
}]
|
||||
}),
|
||||
"the popup's selection, over the popup's range"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// constraint-bodies (TODO.md §20)
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -8745,3 +8956,245 @@ endmodule
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// The connection being typed (TODO §68.2, `docs/features/port-entry-grace`)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// `cargo test --release -p lucisv_server --test e2e a_keystroke_in_a_port_list -- --ignored --nocapture --test-threads=1`
|
||||
///
|
||||
/// The per-keystroke cost of finding the entry being typed, on the largest
|
||||
/// corpus file with instantiations in it: a character typed into a connection
|
||||
/// name in the middle of `ibex_core.sv` (2 026 lines). Prints, asserts nothing,
|
||||
/// exactly like `a_keystroke_round_trip_over_the_wire`; the before/after
|
||||
/// numbers are in the feature README.
|
||||
#[test]
|
||||
#[ignore = "perf measurement, not a correctness assertion — see docs/features/port-entry-grace"]
|
||||
fn a_keystroke_in_a_port_list_round_trip_over_the_wire() {
|
||||
let corpus = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/ibex/rtl/ibex_core.sv");
|
||||
let Ok(source) = std::fs::read_to_string(&corpus) else {
|
||||
eprintln!("no corpus checkout; nothing to measure");
|
||||
return;
|
||||
};
|
||||
let dir = temp_dir("portkeystroke");
|
||||
let file = dir.join("ibex_core.sv");
|
||||
std::fs::write(&file, &source).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
// The fourth `.clk_i` connection (line 781 of the file), just after `.c`.
|
||||
let line = 780u32;
|
||||
let column = " .c".len() as u32;
|
||||
|
||||
let mut live = Live::start();
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
||||
));
|
||||
live.wait_for(|m| m["id"] == 1);
|
||||
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(&source).expect("json")
|
||||
));
|
||||
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
|
||||
let started = std::time::Instant::now();
|
||||
live.send(&keystroke(&uri, 2, line, column));
|
||||
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
let single = started.elapsed();
|
||||
|
||||
let runs = 10u32;
|
||||
let started = std::time::Instant::now();
|
||||
for k in 0..runs {
|
||||
live.send(&keystroke(&uri, 3 + k, line, column + 1 + k));
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{},"method":"textDocument/documentHighlight","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":{line},"character":4}}}}}}"#,
|
||||
50 + k
|
||||
));
|
||||
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
live.wait_for(|m| m["id"] == 50 + k);
|
||||
}
|
||||
let requested = started.elapsed() / runs;
|
||||
live.finish();
|
||||
eprintln!(
|
||||
"port-list keystroke round trip, ibex_core.sv: one change alone {single:?}, \
|
||||
one change a request follows {requested:?}"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A module with an instance whose connection list has an empty line in it,
|
||||
/// for a connection to be typed on (line 3, 0-based).
|
||||
const PORT_TYPING: &str =
|
||||
"module m;\n logic x, y;\n sub u0 (.a(x),\n \n .b(y));\n assign x = y;\nendmodule\n";
|
||||
|
||||
/// Open [`PORT_TYPING`] in a fresh session (`capabilities` as the client's),
|
||||
/// returning the live session and the buffer's URI.
|
||||
fn port_typing_session(name: &str, capabilities: &str) -> (Live, String, PathBuf) {
|
||||
let dir = temp_dir(name);
|
||||
let file = dir.join("m.sv");
|
||||
std::fs::write(&file, PORT_TYPING).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
let mut live = Live::start();
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{capabilities}}}}}"#
|
||||
));
|
||||
live.wait_for(|m| m["id"] == 1);
|
||||
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(PORT_TYPING).expect("json")
|
||||
));
|
||||
(live, uri, dir)
|
||||
}
|
||||
|
||||
/// `text` typed at `(line, character)` of `uri`, as an incremental edit.
|
||||
fn typed(uri: &str, version: u32, line: u32, character: u32, text: &str) -> String {
|
||||
format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":{version}}},"contentChanges":[{{"range":{{"start":{{"line":{line},"character":{character}}},"end":{{"line":{line},"character":{character}}}}},"text":{}}}]}}}}"#,
|
||||
serde_json::to_string(text).expect("json")
|
||||
)
|
||||
}
|
||||
|
||||
/// The parse errors a publish or a pull report carries, as their start lines.
|
||||
fn error_lines(items: &serde_json::Value) -> Vec<u64> {
|
||||
items
|
||||
.as_array()
|
||||
.expect("diagnostics")
|
||||
.iter()
|
||||
.filter(|d| d["severity"] == 1)
|
||||
.filter_map(|d| d["range"]["start"]["line"].as_u64())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// TODO §68.2 over the wire: `.po(` typed into a connection list is not
|
||||
/// reported while it is the thing being typed, and is reported once the
|
||||
/// typing has stopped for the grace period (1.5 s) — with nothing else sent.
|
||||
#[test]
|
||||
fn a_connection_being_typed_is_reported_only_after_the_grace_period() {
|
||||
let (mut live, uri, dir) = port_typing_session("portgrace", "{}");
|
||||
let opened = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
assert!(error_lines(&opened["params"]["diagnostics"]).is_empty(), "{opened:#?}");
|
||||
|
||||
live.send(&typed(&uri, 2, 3, 4, ".po("));
|
||||
let typing = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
let withheld_at = std::time::Instant::now();
|
||||
assert!(
|
||||
error_lines(&typing["params"]["diagnostics"]).is_empty(),
|
||||
"the open `(` of the entry being typed is held back: {typing:#?}"
|
||||
);
|
||||
|
||||
let released = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
let waited = withheld_at.elapsed();
|
||||
assert_eq!(error_lines(&released["params"]["diagnostics"]), [3], "{released:#?}");
|
||||
assert!(waited >= std::time::Duration::from_millis(1000), "released after {waited:?}");
|
||||
|
||||
live.finish();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The other two releases: an edit landing outside the entry says everything
|
||||
/// at once, with no grace to wait for — and so does a save.
|
||||
#[test]
|
||||
fn a_connection_being_typed_is_reported_as_soon_as_the_typing_moves_on_or_saves() {
|
||||
let (mut live, uri, dir) = port_typing_session("portmoveon", "{}");
|
||||
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
|
||||
live.send(&typed(&uri, 2, 3, 4, ".po("));
|
||||
let typing = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
assert!(error_lines(&typing["params"]["diagnostics"]).is_empty(), "{typing:#?}");
|
||||
|
||||
// A space typed after `logic x, y;` — outside every connection list.
|
||||
let started = std::time::Instant::now();
|
||||
live.send(&typed(&uri, 3, 1, 13, " "));
|
||||
let moved = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
assert_eq!(error_lines(&moved["params"]["diagnostics"]), [3], "{moved:#?}");
|
||||
assert!(started.elapsed() < std::time::Duration::from_millis(1000), "no grace to wait for");
|
||||
|
||||
// Back into the entry: held back again; then saved: said again.
|
||||
live.send(&typed(&uri, 4, 3, 8, "x"));
|
||||
let again = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
assert!(error_lines(&again["params"]["diagnostics"]).is_empty(), "{again:#?}");
|
||||
let started = std::time::Instant::now();
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
|
||||
));
|
||||
let saved = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
|
||||
assert_eq!(error_lines(&saved["params"]["diagnostics"]), [3], "{saved:#?}");
|
||||
assert!(started.elapsed() < std::time::Duration::from_millis(1000), "no grace to wait for");
|
||||
|
||||
live.finish();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A pulling client: the pull made while typing leaves the entry out, and the
|
||||
/// first pull after the grace has a new `resultId` and the full list — never
|
||||
/// "unchanged" against the report that left it out.
|
||||
#[test]
|
||||
fn a_pulling_client_sees_the_entry_at_its_first_pull_after_the_grace() {
|
||||
let pulls = r#"{"textDocument":{"diagnostic":{}}}"#;
|
||||
let (mut live, uri, dir) = port_typing_session("portpull", pulls);
|
||||
live.send(&typed(&uri, 2, 3, 4, ".po("));
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv"}}}}"#
|
||||
));
|
||||
let typing = live.wait_for(|m| m["id"] == 2);
|
||||
assert!(error_lines(&typing["result"]["items"]).is_empty(), "{typing:#?}");
|
||||
let held = typing["result"]["resultId"].as_str().expect("a result id").to_string();
|
||||
|
||||
std::thread::sleep(std::time::Duration::from_millis(1700));
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv","previousResultId":"{held}"}}}}"#
|
||||
));
|
||||
// The release happened before this pull was sent, so a refresh request —
|
||||
// which this client never said it accepts — would arrive first.
|
||||
let after = live.wait_for(|m| {
|
||||
m["id"] == 3
|
||||
|| m["method"] == "textDocument/publishDiagnostics"
|
||||
|| m["method"] == "workspace/diagnostic/refresh"
|
||||
});
|
||||
assert_eq!(after["id"], 3, "neither pushed nor asked to refresh: {after:#?}");
|
||||
assert_eq!(after["result"]["kind"], "full", "{after:#?}");
|
||||
assert_eq!(error_lines(&after["result"]["items"]), [3], "{after:#?}");
|
||||
|
||||
live.finish();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A pulling client that accepts `workspace/diagnostic/refresh` — VS Code's
|
||||
/// `vscode-languageclient` does — is asked to pull again when the grace runs
|
||||
/// out, so the entry shows after the pause with nothing typed.
|
||||
#[test]
|
||||
fn a_pulling_client_that_can_refresh_is_asked_to_after_the_grace() {
|
||||
let pulls =
|
||||
r#"{"textDocument":{"diagnostic":{}},"workspace":{"diagnostics":{"refreshSupport":true}}}"#;
|
||||
let (mut live, uri, dir) = port_typing_session("portrefresh", pulls);
|
||||
live.send(&typed(&uri, 2, 3, 4, ".po("));
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv"}}}}"#
|
||||
));
|
||||
let typing = live.wait_for(|m| m["id"] == 2);
|
||||
assert!(error_lines(&typing["result"]["items"]).is_empty(), "{typing:#?}");
|
||||
let held = typing["result"]["resultId"].as_str().expect("a result id").to_string();
|
||||
let withheld_at = std::time::Instant::now();
|
||||
|
||||
let refresh = live.wait_for(|m| {
|
||||
m["method"] == "workspace/diagnostic/refresh"
|
||||
|| m["method"] == "textDocument/publishDiagnostics"
|
||||
});
|
||||
assert_eq!(refresh["method"], "workspace/diagnostic/refresh", "{refresh:#?}");
|
||||
let waited = withheld_at.elapsed();
|
||||
assert!(waited >= std::time::Duration::from_millis(1000), "asked after {waited:?}");
|
||||
live.send(&format!(r#"{{"jsonrpc":"2.0","id":{},"result":null}}"#, refresh["id"]));
|
||||
|
||||
// What the client does on the request: pull again, and get it all.
|
||||
live.send(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv","previousResultId":"{held}"}}}}"#
|
||||
));
|
||||
let after = live.wait_for(|m| m["id"] == 3);
|
||||
assert_eq!(after["result"]["kind"], "full", "{after:#?}");
|
||||
assert_eq!(error_lines(&after["result"]["items"]), [3], "{after:#?}");
|
||||
|
||||
live.finish();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
//! `` `ifdef `` branch folds over the wire: spawn the real binary, open a
|
||||
//! buffer, ask `textDocument/foldingRange`, and read back the exact ranges an
|
||||
//! editor (and VS Code's sticky scroll, which pins every fold's first line)
|
||||
//! receives. The shape itself is pinned by the unit tests beside
|
||||
//! `src/folding.rs`; this checks it survives serialisation and dispatch.
|
||||
//! See `docs/features/ifdef-folding/README.md`.
|
||||
//!
|
||||
//! The framing is repeated from `e2e.rs` rather than shared: an integration
|
||||
//! test file is its own crate, and the helpers are twenty lines.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
fn frame(payload: &str) -> String {
|
||||
format!("Content-Length: {}\r\n\r\n{payload}", payload.len())
|
||||
}
|
||||
|
||||
fn read_message(input: &mut impl BufRead) -> Option<Value> {
|
||||
let mut length = None;
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
if input.read_line(&mut line).unwrap_or(0) == 0 {
|
||||
return None;
|
||||
}
|
||||
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 mut body = vec![0u8; length?];
|
||||
input.read_exact(&mut body).ok()?;
|
||||
serde_json::from_slice(&body).ok()
|
||||
}
|
||||
|
||||
/// Run one session and return every message the server wrote. The OS cache
|
||||
/// directory is pointed into the temp dir, as `e2e.rs` does, so the index
|
||||
/// cache never lands in the developer's home.
|
||||
fn talk(dir: &std::path::Path, session: &str) -> Vec<Value> {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-server"))
|
||||
.env("HOME", dir)
|
||||
.env("XDG_CACHE_HOME", dir.join("cache"))
|
||||
.env("LOCALAPPDATA", dir.join("cache"))
|
||||
.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 mut stdout = BufReader::new(child.stdout.take().expect("stdout"));
|
||||
let mut out = Vec::new();
|
||||
while let Some(message) = read_message(&mut stdout) {
|
||||
out.push(message);
|
||||
}
|
||||
assert!(child.wait().expect("the server exits").success());
|
||||
out
|
||||
}
|
||||
|
||||
const SOURCE: &str = concat!(
|
||||
"module top;\n", // 0
|
||||
"`ifdef FAST\n", // 1
|
||||
" wire a;\n", // 2
|
||||
" wire b;\n", // 3
|
||||
"`elsif SLOW\n", // 4
|
||||
" wire c;\n", // 5
|
||||
"`else\n", // 6
|
||||
" `ifndef TINY\n", // 7
|
||||
" wire d;\n", // 8
|
||||
" `endif\n", // 9
|
||||
"`endif\n", // 10
|
||||
"endmodule\n", // 11
|
||||
);
|
||||
|
||||
#[test]
|
||||
fn ifdef_branches_come_back_as_region_folds_over_the_wire() {
|
||||
let dir = std::env::temp_dir().join(format!("lucisv_ifdef_folding_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", dir.join("top.sv").display());
|
||||
let open = json!({
|
||||
"jsonrpc": "2.0", "method": "textDocument/didOpen",
|
||||
"params": { "textDocument": {
|
||||
"uri": uri, "languageId": "systemverilog", "version": 1, "text": SOURCE
|
||||
} }
|
||||
});
|
||||
let ask = json!({
|
||||
"jsonrpc": "2.0", "id": 2, "method": "textDocument/foldingRange",
|
||||
"params": { "textDocument": { "uri": uri } }
|
||||
});
|
||||
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(&open.to_string()),
|
||||
frame(&ask.to_string()),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&dir, &session);
|
||||
let response = messages.iter().find(|m| m["id"] == 2).expect("a foldingRange response");
|
||||
let folds: Vec<(u64, u64, String)> = response["result"]
|
||||
.as_array()
|
||||
.expect("a folding list")
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let line = |key: &str| f[key].as_u64().expect("a line");
|
||||
(line("startLine"), line("endLine"), f["kind"].as_str().unwrap_or("").to_string())
|
||||
})
|
||||
.collect();
|
||||
let region = |start, end| (start, end, "region".to_string());
|
||||
assert_eq!(
|
||||
folds,
|
||||
vec![region(0, 10), region(1, 3), region(4, 5), region(6, 9), region(7, 8)],
|
||||
"the module, then `ifdef`, `elsif`, `else` and the nested `ifndef`"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! The `style = "auto"` proof sweep: for every source file under the given
|
||||
//! directories, format it with auto, then ask auto again about the output.
|
||||
//! Counts the files where the second or third format changed a byte (an
|
||||
//! idempotency violation) and where the second or third run *named* a
|
||||
//! different preset, and
|
||||
//! prints which preset auto picked how often.
|
||||
//!
|
||||
//! Run it through the runaway guard, in release:
|
||||
//! `tools/guard.sh -- cargo run --release -p vlog_formatter --example auto_sweep -- <dir>...`
|
||||
//! See docs/features/format-styles/README.md.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
|
||||
use vlog_formatter::{format_source, resolve_style, Config};
|
||||
|
||||
/// What one file came to.
|
||||
enum Outcome {
|
||||
/// Auto could not format it (a parse error, as under every preset).
|
||||
Refused,
|
||||
/// Formatted; the preset picked first and second, and whether the
|
||||
/// second format wrote the same bytes.
|
||||
Formatted { first: &'static str, second: &'static str, stable: bool },
|
||||
/// The formatter panicked.
|
||||
Crashed,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let dirs: Vec<PathBuf> = std::env::args().skip(1).map(PathBuf::from).collect();
|
||||
let mut files = Vec::new();
|
||||
for dir in &dirs {
|
||||
collect(dir, &mut files);
|
||||
}
|
||||
files.sort();
|
||||
let results = Mutex::new(Vec::new());
|
||||
let next = Mutex::new(0usize);
|
||||
let workers = std::thread::available_parallelism().map_or(4, |n| n.get());
|
||||
std::thread::scope(|scope| {
|
||||
for _ in 0..workers {
|
||||
let builder = std::thread::Builder::new().stack_size(vlog_parser::PARSE_STACK_SIZE);
|
||||
let spawned = builder.spawn_scoped(scope, || loop {
|
||||
let i = {
|
||||
let mut n = next.lock().expect("lock");
|
||||
*n += 1;
|
||||
*n - 1
|
||||
};
|
||||
let Some(path) = files.get(i) else { break };
|
||||
let outcome = sweep_one(path);
|
||||
results.lock().expect("lock").push((path.clone(), outcome));
|
||||
});
|
||||
spawned.expect("spawn a worker");
|
||||
}
|
||||
});
|
||||
report(results.into_inner().expect("results"));
|
||||
}
|
||||
|
||||
fn sweep_one(path: &Path) -> Outcome {
|
||||
let Ok(bytes) = std::fs::read(path) else { return Outcome::Refused };
|
||||
let source = String::from_utf8_lossy(&bytes).into_owned();
|
||||
let run = std::panic::catch_unwind(|| {
|
||||
let auto = Config::named("auto").expect("auto is a style");
|
||||
let Ok(once) = format_source(&source, &auto) else { return Outcome::Refused };
|
||||
let Ok(twice) = format_source(&once, &auto) else {
|
||||
return Outcome::Formatted { first: "", second: "?", stable: false };
|
||||
};
|
||||
let thrice = format_source(&twice, &auto).ok();
|
||||
let first = resolve_style(&source, &auto).style.name;
|
||||
let second = resolve_style(&once, &auto).style.name;
|
||||
let third = resolve_style(&twice, &auto).style.name;
|
||||
let stable = twice == once && thrice.as_ref() == Some(&once);
|
||||
// A third run naming another preset counts as a rename too.
|
||||
let second = if third == second { second } else { third };
|
||||
Outcome::Formatted { first, second, stable }
|
||||
});
|
||||
run.unwrap_or(Outcome::Crashed)
|
||||
}
|
||||
|
||||
fn report(results: Vec<(PathBuf, Outcome)>) {
|
||||
let (mut refused, mut crashed, mut unstable, mut renamed) = (0, 0, 0, 0);
|
||||
let mut picked: BTreeMap<&str, usize> = BTreeMap::new();
|
||||
for (path, outcome) in &results {
|
||||
match outcome {
|
||||
Outcome::Refused => refused += 1,
|
||||
Outcome::Crashed => {
|
||||
crashed += 1;
|
||||
println!("crash\t{}", path.display());
|
||||
}
|
||||
Outcome::Formatted { first, second, stable } => {
|
||||
*picked.entry(first).or_default() += 1;
|
||||
if !stable {
|
||||
unstable += 1;
|
||||
println!("not-idempotent\t{}", path.display());
|
||||
}
|
||||
if first != second {
|
||||
renamed += 1;
|
||||
println!("renamed\t{first}->{second}\t{}", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
println!("files\t{}", results.len());
|
||||
println!("refused (parse errors)\t{refused}");
|
||||
println!("crashes\t{crashed}");
|
||||
println!("not idempotent\t{unstable}");
|
||||
println!("second run named another preset\t{renamed}");
|
||||
for (name, n) in picked {
|
||||
println!("picked {name}\t{n}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every `.v`/`.sv`/`.vh`/`.svh` under `dir`, recursively.
|
||||
fn collect(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
if path.file_name().is_some_and(|n| n != ".git") {
|
||||
collect(&path, out);
|
||||
}
|
||||
} else if path
|
||||
.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.is_some_and(|e| ["v", "sv", "vh", "svh"].contains(&e))
|
||||
{
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
//! would disagree.
|
||||
|
||||
use crate::doc::{concat, text, Doc};
|
||||
use crate::style::Alignment;
|
||||
|
||||
/// Excess spaces before a column's token that read as "the author aligned
|
||||
/// this". Verible's threshold, and the one number this module hard-codes.
|
||||
@@ -67,7 +68,18 @@ pub struct Align {
|
||||
/// `None` means flush-left — today's layout — and is also the answer for
|
||||
/// anything the rule is not sure about: a group of one, a group with nothing
|
||||
/// to pad, a row whose column token starts its own line.
|
||||
pub fn plan(src: &str, rows: &[&Row], specs: &[ColSpec], budget: usize) -> Option<Align> {
|
||||
///
|
||||
/// `mode` is the style's choice: [`Alignment::Infer`] asks the source,
|
||||
/// [`Alignment::Always`] skips that one question and aligns every group the
|
||||
/// rest of the rule allows — a decision made from the AST alone, so the next
|
||||
/// pass makes it again.
|
||||
pub fn plan(
|
||||
src: &str,
|
||||
rows: &[&Row],
|
||||
specs: &[ColSpec],
|
||||
budget: usize,
|
||||
mode: Alignment,
|
||||
) -> Option<Align> {
|
||||
if rows.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
@@ -86,7 +98,7 @@ pub fn plan(src: &str, rows: &[&Row], specs: &[ColSpec], budget: usize) -> Optio
|
||||
if (0..cols).all(|k| rows.iter().all(|r| r.widths[k] == rows[0].widths[k])) {
|
||||
return None;
|
||||
}
|
||||
if !wants_alignment(src, rows, specs) {
|
||||
if mode == Alignment::Infer && !wants_alignment(src, rows, specs) {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -218,7 +230,7 @@ mod tests {
|
||||
// Five spaces where flush writes one: four excess, the threshold.
|
||||
let src = "aa x\nbbbb y\n";
|
||||
let rows = [row(&[2, 1], &[7], 0), row(&[4, 1], &[14], 0)];
|
||||
let plan = plan(src, &[&rows[0], &rows[1]], NAME, WIDE).expect("aligned");
|
||||
let plan = plan(src, &[&rows[0], &rows[1]], NAME, WIDE, Alignment::Infer).expect("aligned");
|
||||
assert_eq!(plan.targets, vec![5]);
|
||||
}
|
||||
|
||||
@@ -226,35 +238,35 @@ mod tests {
|
||||
fn three_excess_spaces_are_not_a_hint() {
|
||||
let src = "aa x\nbbbb y\n";
|
||||
let rows = [row(&[2, 1], &[6], 0), row(&[4, 1], &[13], 0)];
|
||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE).is_none());
|
||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE, Alignment::Infer).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_spaces_stay_flush() {
|
||||
let src = "aa x\nbbbb y\n";
|
||||
let rows = [row(&[2, 1], &[3], 0), row(&[4, 1], &[10], 0)];
|
||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE).is_none());
|
||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE, Alignment::Infer).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_common_column_stays_aligned() {
|
||||
let src = "aa x\nbbbb x\n";
|
||||
let rows = [row(&[2, 1], &[5], 0), row(&[4, 1], &[12], 0)];
|
||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE).is_some());
|
||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE, Alignment::Infer).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_widths_have_nothing_to_align() {
|
||||
let src = "aa x\naa y\n";
|
||||
let rows = [row(&[2, 1], &[6], 0), row(&[2, 1], &[14], 0)];
|
||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE).is_none());
|
||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE, Alignment::Infer).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_of_one_is_never_aligned() {
|
||||
let src = "aa x\n";
|
||||
let rows = [row(&[2, 1], &[6], 0)];
|
||||
assert!(plan(src, &[&rows[0]], NAME, WIDE).is_none());
|
||||
assert!(plan(src, &[&rows[0]], NAME, WIDE, Alignment::Infer).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -262,8 +274,34 @@ mod tests {
|
||||
let src = "aa x\nbbbb y\n";
|
||||
let rows = [row(&[2, 1], &[7], 0), row(&[4, 1], &[14], 0)];
|
||||
// Widest aligned line is 5 + 1 = 6 columns.
|
||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, 6).is_some());
|
||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, 5).is_none());
|
||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, 6, Alignment::Infer).is_some());
|
||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, 5, Alignment::Infer).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn always_aligns_what_the_source_never_padded() {
|
||||
let src = "aa x\nbbbb y\n";
|
||||
let rows = [row(&[2, 1], &[3], 0), row(&[4, 1], &[10], 0)];
|
||||
let aligned = plan(src, &[&rows[0], &rows[1]], NAME, WIDE, Alignment::Always);
|
||||
assert_eq!(aligned.expect("aligned").targets, vec![5]);
|
||||
// Even a row whose column token starts its own line: `Always` never
|
||||
// looks at the source at all.
|
||||
let src = "aa\nx\nbbbb y\n";
|
||||
let rows = [row(&[2, 1], &[3], 0), row(&[4, 1], &[10], 0)];
|
||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE, Alignment::Always).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn always_keeps_every_other_refusal() {
|
||||
let src = "aa x\nbbbb y\n";
|
||||
let rows = [row(&[2, 1], &[3], 0), row(&[4, 1], &[10], 0)];
|
||||
let same = [row(&[2, 1], &[3], 0), row(&[2, 1], &[10], 0)];
|
||||
let always = Alignment::Always;
|
||||
assert!(plan(src, &[&rows[0]], NAME, WIDE, always).is_none(), "a group of one");
|
||||
assert!(plan(src, &[&same[0], &same[1]], NAME, WIDE, always).is_none(), "nothing to pad");
|
||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, 5, always).is_none(), "too wide");
|
||||
let empty = [row(&[0, 1], &[3], 0), row(&[4, 1], &[10], 0)];
|
||||
assert!(plan(src, &[&empty[0], &empty[1]], NAME, WIDE, always).is_none(), "no prefix");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
//! `style = "auto"`: lay a file out in the preset it is already closest to.
|
||||
//!
|
||||
//! Rather than guess each layout switch from clues in the text, auto formats
|
||||
//! the file once per preset — every preset at the config's own indent and
|
||||
//! width, so only the layout switches compete — and keeps the output that
|
||||
//! changes the fewest lines, counting every line whose bytes change,
|
||||
//! indentation included (`distance`). Ties go to the earlier preset in
|
||||
//! [`PRESETS`], so a file the presets all agree on gets the default.
|
||||
//!
|
||||
//! Counting indentation is what keeps an edit local: a file already written
|
||||
//! in one preset keeps it when a line written in another preset's shape is
|
||||
//! added, because switching would re-indent every list the file already has.
|
||||
//!
|
||||
//! **Idempotent by construction.** Say the first run picked preset `s` and
|
||||
//! wrote `y`. Formatting under `s` succeeded, so its convergence check
|
||||
//! proved `s` leaves `y` exactly as it is: on the second run `s` is at
|
||||
//! distance zero, the smallest there is. Whichever preset the second run
|
||||
//! picks is therefore one that also leaves `y` exactly as it is, so the
|
||||
//! second run writes `y` again.
|
||||
//!
|
||||
//! **And it names the same preset twice** — when asked to name one
|
||||
//! ([`resolve_style`]). The second run picks the *earliest* preset that
|
||||
//! leaves `y` as it is, which need not be `s` — on `lowrisc`'s output,
|
||||
//! `lucisv` (which keeps alignment it finds) often agrees. So the name
|
||||
//! reported is that earliest preset (`canonical`). Formatting never needs
|
||||
//! the name, so only [`resolve_style`] pays for it.
|
||||
//! `docs/features/format-styles/README.md` has the sweep that checks both.
|
||||
|
||||
use crate::format::{format_styled, Config, FormatError};
|
||||
use crate::style::{Style, PRESETS};
|
||||
|
||||
/// The name the setting spells auto with.
|
||||
pub(crate) const NAME: &str = "auto";
|
||||
|
||||
/// The output of the preset closest to `source`, or — when no preset can
|
||||
/// format it — the first preset's error.
|
||||
pub(crate) fn format_closest(source: &str, config: &Config) -> Result<String, FormatError> {
|
||||
closest(source, config).map(|(_, output)| output)
|
||||
}
|
||||
|
||||
/// [`crate::format_source`] under auto, also handing back the preset whose
|
||||
/// output it is — so a caller can lay later ranges of the same buffer out in
|
||||
/// it without searching again (the language server does). The preset is the
|
||||
/// one that won, not [`resolve_style`]'s canonical name; both leave the
|
||||
/// output exactly as it is.
|
||||
pub fn format_auto(source: &str, config: &Config) -> Result<(String, Style), FormatError> {
|
||||
closest(source, config).map(|(index, output)| (output, PRESETS[index]))
|
||||
}
|
||||
|
||||
/// `config` made concrete for the range and selection formatters: unchanged
|
||||
/// unless it asks for auto, and then the closest preset of the *whole* file.
|
||||
/// A file no preset can format — one with a parse error — gets the default's
|
||||
/// layout. No naming pass: the output does not depend on the name.
|
||||
pub(crate) fn concrete(source: &str, config: &Config) -> Config {
|
||||
if !config.auto_style {
|
||||
return config.clone();
|
||||
}
|
||||
match closest(source, config) {
|
||||
Ok((index, _)) => fixed(config, PRESETS[index]),
|
||||
Err(_) => fixed(config, PRESETS[0]),
|
||||
}
|
||||
}
|
||||
|
||||
/// The preset auto *names* for this file, as a concrete config: the
|
||||
/// earliest preset that leaves auto's output exactly as it is, which is the
|
||||
/// one a second run names too. Unchanged when `config` does not ask for auto;
|
||||
/// the default's when no preset can format the file.
|
||||
pub fn resolve_style(source: &str, config: &Config) -> Config {
|
||||
if !config.auto_style {
|
||||
return config.clone();
|
||||
}
|
||||
match closest(source, config) {
|
||||
Ok((index, output)) => fixed(config, PRESETS[canonical(&output, config, index)]),
|
||||
Err(_) => fixed(config, PRESETS[0]),
|
||||
}
|
||||
}
|
||||
|
||||
/// The index of the closest preset and its output. Stops at the first
|
||||
/// preset that leaves `source` exactly as it is: nothing can be closer.
|
||||
fn closest(source: &str, config: &Config) -> Result<(usize, String), FormatError> {
|
||||
let mut best: Option<((usize, usize), usize, String)> = None;
|
||||
let mut first_error = None;
|
||||
for (index, preset) in PRESETS.into_iter().enumerate() {
|
||||
match format_styled(source, &fixed(config, preset)) {
|
||||
Ok(output) => {
|
||||
let d = distance(source, &output);
|
||||
if best.as_ref().is_none_or(|(least, _, _)| d < *least) {
|
||||
best = Some((d, index, output));
|
||||
}
|
||||
if d == (0, 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
first_error.get_or_insert(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
match (best, first_error) {
|
||||
(Some((_, index, output)), _) => Ok((index, output)),
|
||||
(None, Some(e)) => Err(e),
|
||||
// Only reachable with no presets at all; there is always one.
|
||||
(None, None) => format_styled(source, &fixed(config, PRESETS[0])).map(|out| (0, out)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The earliest preset, up to `chosen`, that leaves `output` exactly as it
|
||||
/// is — the one a second run over `output` picks. `chosen` itself always
|
||||
/// qualifies: its output is a fixed point of it by the convergence check.
|
||||
fn canonical(output: &str, config: &Config, chosen: usize) -> usize {
|
||||
(0..chosen)
|
||||
.find(|&i| {
|
||||
format_styled(output, &fixed(config, PRESETS[i])).is_ok_and(|again| again == output)
|
||||
})
|
||||
.unwrap_or(chosen)
|
||||
}
|
||||
|
||||
/// `config` under `preset`'s layout switches, keeping its indent and width.
|
||||
fn fixed(config: &Config, preset: Style) -> Config {
|
||||
Config { style: preset, auto_style: false, ..config.clone() }
|
||||
}
|
||||
|
||||
/// How far `output` is from `source`: the number of lines whose bytes
|
||||
/// change — lines either text has that the other lacks, indentation
|
||||
/// included — then, to break a tie, whether the texts differ at all. The
|
||||
/// pair is `(0, 0)` exactly when the two are equal, which is the whole of the
|
||||
/// idempotency argument above.
|
||||
fn distance(source: &str, output: &str) -> (usize, usize) {
|
||||
if source == output {
|
||||
return (0, 0);
|
||||
}
|
||||
(lines_apart(source.lines(), output.lines()), 1)
|
||||
}
|
||||
|
||||
/// The size of the multiset difference between two runs of lines: a line
|
||||
/// moved elsewhere costs nothing.
|
||||
fn lines_apart<'a>(a: impl Iterator<Item = &'a str>, b: impl Iterator<Item = &'a str>) -> usize {
|
||||
let mut counts: std::collections::HashMap<&str, isize> = std::collections::HashMap::new();
|
||||
for line in a {
|
||||
*counts.entry(line).or_default() += 1;
|
||||
}
|
||||
for line in b {
|
||||
*counts.entry(line).or_default() -= 1;
|
||||
}
|
||||
counts.values().map(|n| n.unsigned_abs()).sum()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn distance_is_zero_only_for_equal_texts() {
|
||||
assert_eq!(distance("a\nb\n", "a\nb\n"), (0, 0));
|
||||
assert_eq!(distance("a\nb\n", "b\na\n"), (0, 1), "reordered: still apart");
|
||||
assert_eq!(distance("a\nb\n", "a\nc\n"), (2, 1));
|
||||
assert_eq!(distance("a\n", "a"), (0, 1), "a final newline is a difference too");
|
||||
}
|
||||
|
||||
/// Re-indenting a line is a changed line like any other — the property
|
||||
/// that keeps a one-line edit from flipping a whole file's preset.
|
||||
#[test]
|
||||
fn indentation_counts_in_full() {
|
||||
assert_eq!(distance(" a\n", " a\n"), (2, 1));
|
||||
let reindented = distance(" a\n b\n c\n", " a\n b\n c\n");
|
||||
let one_line_rebroken = distance(" a\n b\n c\n", " a\n b c\n");
|
||||
assert!(one_line_rebroken < reindented);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
//! `if`/`else` chains — procedural and generate — and the two style
|
||||
//! switches that decide where their keywords go: a body's `begin`
|
||||
//! (`Style::begin`) and the `else` after an `end` (`Style::else_keyword`).
|
||||
//!
|
||||
//! Both switches only choose between a space and a line break in front of a
|
||||
//! keyword, so every style prints the same tokens in the same order.
|
||||
|
||||
use crate::doc::*;
|
||||
use crate::style::Placement;
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
use super::comment::trailing_ends_line;
|
||||
use super::Fmt;
|
||||
|
||||
/// What goes in front of a keyword the style places: one space, or a line
|
||||
/// break to the enclosing indentation.
|
||||
pub(super) fn before_keyword(placement: Placement) -> Doc {
|
||||
match placement {
|
||||
Placement::SameLine => text(" "),
|
||||
Placement::OwnLine => Doc::HardLine,
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Fmt<'a> {
|
||||
/// Whether an `else` may follow an `end` on the same line — an `end`
|
||||
/// with a `: label` after it asks `else_after_label` instead.
|
||||
fn else_cuddles(&self, labelled: bool) -> bool {
|
||||
let style = &self.cfg.style;
|
||||
let placement = if labelled { style.else_after_label } else { style.else_keyword };
|
||||
style.else_keyword == Placement::SameLine && placement == Placement::SameLine
|
||||
}
|
||||
|
||||
pub(super) fn if_stmt(
|
||||
&self,
|
||||
qualifier: &Option<String>,
|
||||
after_kw: &[Comment],
|
||||
cond: &Expr,
|
||||
then: &Stmt,
|
||||
else_comments: &[Comment],
|
||||
els: &Option<Box<Stmt>>,
|
||||
) -> Doc {
|
||||
let mut head = Vec::new();
|
||||
if let Some(q) = qualifier {
|
||||
head.push(text(format!("{q} ")));
|
||||
}
|
||||
self.word_then("if", after_kw, &mut head);
|
||||
let (parens, taken) = self.header_parens(cond, &then.meta);
|
||||
head.push(parens);
|
||||
let prefix = concat(head);
|
||||
// A line comment trailing the then-branch runs to end of line, so a
|
||||
// cuddled `else` would be swallowed into its text.
|
||||
let then_is_block =
|
||||
matches!(then.kind, StmtKind::Block { .. }) && !trailing_ends_line(&then.meta);
|
||||
let mut docs = vec![self.stmt_as_body_from(prefix, then, taken)];
|
||||
if let Some(els) = els {
|
||||
// A comment written before `else` prints before it, each on its
|
||||
// own line: it is where the source put it, and after the keyword
|
||||
// it would have crossed a token.
|
||||
if !else_comments.is_empty() {
|
||||
docs.push(Doc::HardLine);
|
||||
for c in else_comments {
|
||||
docs.push(self.comment(c));
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text("else"));
|
||||
} else if then_is_block && self.else_cuddles(ends_labelled(then)) {
|
||||
docs.push(text(" else"));
|
||||
} else {
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text("else"));
|
||||
}
|
||||
// `else if` chains stay flat.
|
||||
if let StmtKind::If {
|
||||
qualifier: eq,
|
||||
after_kw: ea,
|
||||
cond: ec,
|
||||
then: et,
|
||||
else_comments: ecm,
|
||||
els: ee,
|
||||
} = &els.kind
|
||||
{
|
||||
docs.push(text(" "));
|
||||
let mut meta_docs = self.leading(&els.meta);
|
||||
docs.append(&mut meta_docs);
|
||||
docs.push(self.if_stmt(eq, ea, ec, et, ecm, ee));
|
||||
docs.extend(self.trailing(&els.meta));
|
||||
} else {
|
||||
docs.push(self.stmt_as_body(text(""), els));
|
||||
}
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
pub(super) fn gen_if(&self, g: &GenIf, depth: usize) -> Doc {
|
||||
let mut docs = vec![text("if "), self.parens(&g.cond)];
|
||||
let begin = self.cfg.style.begin;
|
||||
let mut cuddle = self.gen_block(&mut docs, &g.then, depth, begin)
|
||||
&& self.else_cuddles(g.then.end_label.is_some());
|
||||
let mut els = &g.els;
|
||||
while let Some(e) = els {
|
||||
match e.as_ref() {
|
||||
GenElse::If(_meta, gi) => {
|
||||
if cuddle {
|
||||
docs.push(text(" else if "));
|
||||
} else {
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text("else if "));
|
||||
}
|
||||
docs.push(self.parens(&gi.cond));
|
||||
cuddle = self.gen_block(&mut docs, &gi.then, depth, begin)
|
||||
&& self.else_cuddles(gi.then.end_label.is_some());
|
||||
els = &gi.els;
|
||||
}
|
||||
GenElse::Block(b) => {
|
||||
if cuddle {
|
||||
docs.push(text(" else"));
|
||||
} else {
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text("else"));
|
||||
}
|
||||
self.gen_block(&mut docs, b, depth, begin);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a statement is a block closed by `end : label`.
|
||||
fn ends_labelled(s: &Stmt) -> bool {
|
||||
matches!(&s.kind, StmtKind::Block { end_label: Some(_), .. })
|
||||
}
|
||||
@@ -35,10 +35,12 @@ impl<'a> Fmt<'a> {
|
||||
})
|
||||
.collect();
|
||||
let items = self.list_entries(items, &inst.param_directives);
|
||||
let broken = !inst.param_directives.is_empty() || holds_verbatim_value(params);
|
||||
let broken = !inst.param_directives.is_empty()
|
||||
|| holds_verbatim_value(params)
|
||||
|| self.style_breaks(params.iter().any(is_named));
|
||||
docs.push(text(if on_fresh_line { "#" } else { " #" }));
|
||||
self.slot_comments(&inst.after_hash, &mut docs);
|
||||
docs.push(self.delimited("(", items, ")", broken));
|
||||
docs.push(self.header_list("(", items, &[], ")", broken));
|
||||
on_fresh_line = false;
|
||||
}
|
||||
if let [only] = &inst.instances[..] {
|
||||
@@ -108,8 +110,10 @@ impl<'a> Fmt<'a> {
|
||||
let mut broken = !directives.is_empty();
|
||||
let items: Vec<ListItem> = match conns {
|
||||
Connections::Named(list) => {
|
||||
let aligns = self.connection_aligns(list, directives, depth);
|
||||
broken |= aligns.iter().any(Option::is_some) || holds_verbatim_value(list);
|
||||
let aligns = self.connection_aligns(list, directives, self.list_depth(depth));
|
||||
broken |= aligns.iter().any(Option::is_some)
|
||||
|| holds_verbatim_value(list)
|
||||
|| self.style_breaks(!list.is_empty());
|
||||
list.iter()
|
||||
.zip(&aligns)
|
||||
.map(|(c, a)| {
|
||||
@@ -134,7 +138,7 @@ impl<'a> Fmt<'a> {
|
||||
.collect(),
|
||||
};
|
||||
let items = self.list_entries(items, directives);
|
||||
self.delimited("(", items, ")", broken)
|
||||
self.header_list("(", items, &[], ")", broken)
|
||||
}
|
||||
|
||||
/// The alignment plan for an instance's named connection list.
|
||||
@@ -439,6 +443,13 @@ fn holds_verbatim_value(list: &[ListElem<Connection>]) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a parameter override names what it sets (`.Width(8)`) rather
|
||||
/// than giving it by position (`#(8)`): only a named list is one the style's
|
||||
/// `OnePerLine` breaks.
|
||||
fn is_named(c: &ListElem<Connection>) -> bool {
|
||||
c.ok().is_some_and(|c| !c.name_span.is_empty())
|
||||
}
|
||||
|
||||
/// `(weak0, pull1)`, or the single-strength `(weak1)` a pull gate may write —
|
||||
/// with the comments written in any of its five gaps back where they stood.
|
||||
///
|
||||
|
||||
@@ -11,9 +11,11 @@
|
||||
use crate::align::Align;
|
||||
use crate::doc::*;
|
||||
use crate::range::Split;
|
||||
use crate::style::Placement;
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
use super::branch::before_keyword;
|
||||
use super::instance::drive_strength;
|
||||
use super::list::ListItem;
|
||||
use super::verbatim::Slot;
|
||||
@@ -485,44 +487,18 @@ impl<'a> Fmt<'a> {
|
||||
group(head)
|
||||
}
|
||||
|
||||
fn gen_if(&self, g: &GenIf, depth: usize) -> Doc {
|
||||
let mut docs = vec![text("if "), self.parens(&g.cond)];
|
||||
let mut cuddle = self.gen_block(&mut docs, &g.then, depth);
|
||||
let mut els = &g.els;
|
||||
while let Some(e) = els {
|
||||
match e.as_ref() {
|
||||
GenElse::If(_meta, gi) => {
|
||||
if cuddle {
|
||||
docs.push(text(" else if "));
|
||||
} else {
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text("else if "));
|
||||
}
|
||||
docs.push(self.parens(&gi.cond));
|
||||
cuddle = self.gen_block(&mut docs, &gi.then, depth);
|
||||
els = &gi.els;
|
||||
}
|
||||
GenElse::Block(b) => {
|
||||
if cuddle {
|
||||
docs.push(text(" else"));
|
||||
} else {
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text("else"));
|
||||
}
|
||||
self.gen_block(&mut docs, b, depth);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// Append a generate block; returns true if it ended with `end` (so
|
||||
/// `else` can cuddle).
|
||||
fn gen_block(&self, docs: &mut Vec<Doc>, b: &GenBlock, depth: usize) -> bool {
|
||||
/// Append a generate block, its `begin` placed as `begin` says; returns
|
||||
/// true if it ended with `end` (so `else` can cuddle).
|
||||
pub(super) fn gen_block(
|
||||
&self,
|
||||
docs: &mut Vec<Doc>,
|
||||
b: &GenBlock,
|
||||
depth: usize,
|
||||
begin: Placement,
|
||||
) -> bool {
|
||||
if b.is_block {
|
||||
if b.before_kw.is_empty() {
|
||||
docs.push(text(" "));
|
||||
docs.push(before_keyword(begin));
|
||||
} else {
|
||||
self.inline_comments_spaced(&b.before_kw, docs);
|
||||
}
|
||||
@@ -581,7 +557,7 @@ impl<'a> Fmt<'a> {
|
||||
self.slot_comments(&g.comments.before_close, &mut header);
|
||||
header.push(text(")"));
|
||||
let mut docs = vec![concat(header)];
|
||||
self.gen_block(&mut docs, &g.body, depth);
|
||||
self.gen_block(&mut docs, &g.body, depth, self.cfg.style.begin);
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
@@ -592,7 +568,8 @@ impl<'a> Fmt<'a> {
|
||||
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
body.extend(self.leading(&item.meta));
|
||||
let mut item_docs = vec![self.case_labels(&item.labels, &item.before_colon, item.span)];
|
||||
self.gen_block(&mut item_docs, &item.body, depth + 1);
|
||||
// A case item's `begin` stays on the label's line in every style.
|
||||
self.gen_block(&mut item_docs, &item.body, depth + 1, Placement::SameLine);
|
||||
body.push(concat(item_docs));
|
||||
body.extend(self.trailing(&item.meta));
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
|
||||
use crate::align::{self, Align, ColSpec, Row};
|
||||
use crate::doc::*;
|
||||
use crate::style::{ListIndent, PortLists};
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
@@ -125,6 +126,53 @@ impl<'a> Fmt<'a> {
|
||||
dangling: &[Comment],
|
||||
close: &str,
|
||||
force_break: bool,
|
||||
) -> Doc {
|
||||
self.delimited_at(open, items, dangling, close, force_break, ListIndent::Block)
|
||||
}
|
||||
|
||||
/// [`Fmt::delimited_dangling`] for a module header's lists and an
|
||||
/// instance's: the entries at the style's [`ListIndent`]. Whether the
|
||||
/// style also breaks the list regardless of width is the caller's
|
||||
/// question — [`Fmt::style_breaks`] — because only the caller knows
|
||||
/// whether the list is one the style governs.
|
||||
pub(super) fn header_list(
|
||||
&self,
|
||||
open: &str,
|
||||
items: Vec<ListItem>,
|
||||
dangling: &[Comment],
|
||||
close: &str,
|
||||
force_break: bool,
|
||||
) -> Doc {
|
||||
let indent = self.cfg.style.list_indent;
|
||||
self.delimited_at(open, items, dangling, close, force_break, indent)
|
||||
}
|
||||
|
||||
/// Whether the style lays a header or named-connection list out one
|
||||
/// entry per line whatever its width: `PortLists::OnePerLine`, and the
|
||||
/// list holds something.
|
||||
pub(super) fn style_breaks(&self, has_entries: bool) -> bool {
|
||||
has_entries && self.cfg.style.port_lists == PortLists::OnePerLine
|
||||
}
|
||||
|
||||
/// The nesting depth a header list's entries print at when the list
|
||||
/// itself opens at `depth` — one more under `ListIndent::Wrap`. The
|
||||
/// alignment budget is measured from it.
|
||||
pub(super) fn list_depth(&self, depth: usize) -> usize {
|
||||
match self.cfg.style.list_indent {
|
||||
ListIndent::Block => depth,
|
||||
ListIndent::Wrap => depth + 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// The bracketed layout behind both, entries `levels` deep.
|
||||
fn delimited_at(
|
||||
&self,
|
||||
open: &str,
|
||||
items: Vec<ListItem>,
|
||||
dangling: &[Comment],
|
||||
close: &str,
|
||||
force_break: bool,
|
||||
levels: ListIndent,
|
||||
) -> Doc {
|
||||
if items.is_empty() && dangling.is_empty() {
|
||||
return text(format!("{open}{close}"));
|
||||
@@ -136,7 +184,11 @@ impl<'a> Fmt<'a> {
|
||||
let close_needs_hardline = self.list_rows(items, dangling, &mut inner) || force_break;
|
||||
// Peek at blank_before flags is handled by leading comments already;
|
||||
// blank lines inside bracketed lists are dropped deliberately.
|
||||
let mut docs = vec![text(open), indent(inner)];
|
||||
let entries = match levels {
|
||||
ListIndent::Block => indent(inner),
|
||||
ListIndent::Wrap => indent(vec![indent(inner)]),
|
||||
};
|
||||
let mut docs = vec![text(open), entries];
|
||||
docs.push(if close_needs_hardline { Doc::HardLine } else { Doc::SoftLine });
|
||||
docs.push(text(close));
|
||||
group(docs)
|
||||
@@ -326,7 +378,8 @@ impl<'a> Fmt<'a> {
|
||||
j += 1;
|
||||
}
|
||||
let run: Vec<&Row> = rows[i..j].iter().flatten().collect();
|
||||
if let Some(plan) = align::plan(self.src, &run, specs, budget) {
|
||||
if let Some(plan) = align::plan(self.src, &run, specs, budget, self.cfg.style.alignment)
|
||||
{
|
||||
for slot in &mut out[i..j] {
|
||||
*slot = Some(plan.clone());
|
||||
}
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
//! Formatting rules: AST → Doc.
|
||||
//!
|
||||
//! Style follows Verible's defaults: 2-space indent, 100-column lines,
|
||||
//! one-element-per-line port/connection lists when a construct does not fit
|
||||
//! on a single line, cuddled `begin`/`end`.
|
||||
//! The default style follows Verible's defaults: 2-space indent,
|
||||
//! 100-column lines, one-element-per-line port/connection lists when a
|
||||
//! construct does not fit on a single line, cuddled `begin`/`end`. The other
|
||||
//! named styles (`crate::style`) move the same tokens to other lines.
|
||||
//!
|
||||
//! The rules are one `Fmt` whose methods are spread over the sibling
|
||||
//! modules by grammar domain — `item`, `module`, `instance`, `decl`,
|
||||
//! `routine`, `class`, `cover`, `sva`, `stmt`, `expr` — on top of the
|
||||
//! `routine`, `class`, `cover`, `sva`, `stmt`, `branch`, `expr` — on top of the
|
||||
//! shared machinery they all print through — `comment`, `verbatim`,
|
||||
//! `phrase`, `list`. This file holds what the crate exports (`Config`,
|
||||
//! `FormatError`, `format_source`, `format_range`), the `Fmt` state, and
|
||||
//! the name helpers every module writes an identifier through.
|
||||
|
||||
mod branch;
|
||||
mod class;
|
||||
mod comment;
|
||||
mod cover;
|
||||
@@ -28,16 +30,20 @@ mod stmt;
|
||||
mod sva;
|
||||
mod verbatim;
|
||||
|
||||
use crate::doc::{text, Doc};
|
||||
use crate::doc::{concat, text, Doc};
|
||||
use crate::fence::{self, Region};
|
||||
use crate::printer::Printer;
|
||||
use crate::range::{self, Split};
|
||||
use crate::style::{Style, LUCISV};
|
||||
use crate::verify::{verify_convergence, verify_equivalence, VerificationError};
|
||||
use vlog_parser::ast::*;
|
||||
|
||||
/// Everything a formatting run is configured with.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Config {
|
||||
/// The line limit the printer breaks at.
|
||||
pub max_width: usize,
|
||||
/// Spaces per indentation level.
|
||||
pub indent_width: usize,
|
||||
/// Indent the macro statements written between `` `uvm_object_utils_begin ``
|
||||
/// / `` `uvm_component_utils_begin `` and their `_end`, which are plain
|
||||
@@ -47,11 +53,53 @@ pub struct Config {
|
||||
/// cleanly, so a project opts in through `[format] uvm-utils-indent` and
|
||||
/// nobody else moves a byte.
|
||||
pub uvm_utils_indent: bool,
|
||||
/// The named style's layout switches. Its own `indent` and `line_length`
|
||||
/// are only the starting values [`Config::styled`] copies into the two
|
||||
/// fields above; the layout rules never read them.
|
||||
pub style: Style,
|
||||
/// `style = "auto"`: ignore `style` and lay the file out in the preset
|
||||
/// whose layout it is already closest to, at this config's own indent
|
||||
/// and width (`crate::auto`).
|
||||
pub auto_style: bool,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// The settings `style` asks for: its indent and line length, its layout.
|
||||
/// An explicit `indent` or `line-length` is written over the result.
|
||||
pub fn styled(style: Style) -> Config {
|
||||
Config {
|
||||
max_width: style.line_length,
|
||||
indent_width: style.indent,
|
||||
uvm_utils_indent: false,
|
||||
style,
|
||||
auto_style: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The settings a style *name* asks for: a preset, or `auto` — which
|
||||
/// starts from the default's indent and width, since it picks a layout,
|
||||
/// not a size. `None` for any other name.
|
||||
pub fn named(name: &str) -> Option<Config> {
|
||||
if name == crate::auto::NAME {
|
||||
return Some(Config { auto_style: true, ..Config::default() });
|
||||
}
|
||||
crate::style::preset(name).map(Config::styled)
|
||||
}
|
||||
|
||||
/// The name the setting spells this config's style with: `auto`, or the
|
||||
/// preset's.
|
||||
pub fn style_name(&self) -> &'static str {
|
||||
if self.auto_style {
|
||||
crate::auto::NAME
|
||||
} else {
|
||||
self.style.name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Config { max_width: 100, indent_width: 2, uvm_utils_indent: false }
|
||||
Config::styled(LUCISV)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,6 +110,10 @@ pub enum FormatError {
|
||||
Source(vlog_parser::Error),
|
||||
/// A safety check failed; the formatted text was discarded.
|
||||
Verification(VerificationError),
|
||||
/// A selection could not be laid out on its own — it reaches a parse
|
||||
/// error, or its target could not be found again in the output. Nothing
|
||||
/// was changed.
|
||||
Selection(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for FormatError {
|
||||
@@ -69,6 +121,7 @@ impl std::fmt::Display for FormatError {
|
||||
match self {
|
||||
FormatError::Source(e) => write!(f, "{e}"),
|
||||
FormatError::Verification(e) => write!(f, "{e}"),
|
||||
FormatError::Selection(e) => write!(f, "{e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -98,6 +151,14 @@ impl From<VerificationError> for FormatError {
|
||||
/// lets sufficiently nested input abort the process instead of returning
|
||||
/// `Err` (see `docs/features/recursion-limit/README.md`).
|
||||
pub fn format_source(source: &str, config: &Config) -> Result<String, FormatError> {
|
||||
if config.auto_style {
|
||||
return crate::auto::format_closest(source, config);
|
||||
}
|
||||
format_styled(source, config)
|
||||
}
|
||||
|
||||
/// [`format_source`] under exactly `config`'s style, `auto_style` ignored.
|
||||
pub(crate) fn format_styled(source: &str, config: &Config) -> Result<String, FormatError> {
|
||||
let output = format_once(source, config).map_err(FormatError::Source)?;
|
||||
verify_equivalence(source, &output)?;
|
||||
let again = format_once(&output, config).map_err(VerificationError::Reparse)?;
|
||||
@@ -114,6 +175,9 @@ pub fn format_source(source: &str, config: &Config) -> Result<String, FormatErro
|
||||
/// replaying the same per-item decisions against the output — see
|
||||
/// `docs/features/range-formatting/README.md`.
|
||||
///
|
||||
/// Under `style = "auto"` the style is the one the *whole* file is closest
|
||||
/// to, never the selected lines' alone.
|
||||
///
|
||||
/// Same stack requirement as [`format_source`]: needs a thread with at least
|
||||
/// `vlog_parser::PARSE_STACK_SIZE` of stack.
|
||||
pub fn format_range(
|
||||
@@ -121,6 +185,7 @@ pub fn format_range(
|
||||
config: &Config,
|
||||
lines: &range::LineRanges,
|
||||
) -> Result<String, FormatError> {
|
||||
let config = &crate::auto::concrete(source, config);
|
||||
let file = vlog_parser::parse_source(source).map_err(FormatError::Source)?;
|
||||
let selection = range::select(source, &file, lines);
|
||||
let output = format_selected(source, config, &selection).map_err(FormatError::Source)?;
|
||||
@@ -130,6 +195,41 @@ pub fn format_range(
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// A sibling run a selection lays out on its own: items at their AST depth,
|
||||
/// or statements.
|
||||
pub(crate) enum Run<'t> {
|
||||
Items(&'t [Item], usize),
|
||||
Stmts(&'t [Stmt]),
|
||||
}
|
||||
|
||||
/// Lay out one run of `file` (parsed from `source`) exactly as the
|
||||
/// whole-file printers would, every line starting with `base`.
|
||||
///
|
||||
/// No final-newline normalization and no trailing whitespace: the result
|
||||
/// replaces the run's own bytes and nothing else. Fenced regions inside the
|
||||
/// run are emitted as written, as in a whole-file run.
|
||||
pub(crate) fn print_run(
|
||||
source: &str,
|
||||
file: &SourceFile,
|
||||
config: &Config,
|
||||
run: Run<'_>,
|
||||
base: &str,
|
||||
) -> String {
|
||||
let regions = fence::collect(source, file);
|
||||
let fmt = Fmt { cfg: config, src: source, regions, splits: Vec::new() };
|
||||
let docs = match run {
|
||||
Run::Items(items, depth) => fmt.item_seq(items, depth),
|
||||
Run::Stmts(stmts) => fmt.stmt_seq(stmts),
|
||||
};
|
||||
let printer = Printer { max_width: config.max_width, indent_width: config.indent_width };
|
||||
let mut out = printer.print_at(&concat(docs), base);
|
||||
// Spaces and newlines only, exactly what `render` trims.
|
||||
while out.ends_with('\n') || out.ends_with(' ') {
|
||||
out.pop();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A single unverified formatting pass: parse, lay out, print.
|
||||
fn format_once(source: &str, config: &Config) -> Result<String, vlog_parser::Error> {
|
||||
let file = vlog_parser::parse_source(source)?;
|
||||
|
||||
@@ -74,10 +74,10 @@ impl<'a> Fmt<'a> {
|
||||
})
|
||||
.collect();
|
||||
let items = self.list_entries(items, &m.param_directives);
|
||||
let broken = !m.param_directives.is_empty();
|
||||
let broken = !m.param_directives.is_empty() || self.style_breaks(!items.is_empty());
|
||||
docs.push(text(if on_fresh_line { "#" } else { " #" }));
|
||||
self.slot_comments(&m.param_after_hash, &mut docs);
|
||||
docs.push(self.delimited_dangling("(", items, &m.param_dangling, ")", broken));
|
||||
docs.push(self.header_list("(", items, &m.param_dangling, ")", broken));
|
||||
on_fresh_line = false;
|
||||
}
|
||||
let on_fresh_line = self.bracket_comments(&m.port_comments, &mut docs, on_fresh_line);
|
||||
@@ -92,7 +92,8 @@ impl<'a> Fmt<'a> {
|
||||
PortList::Ansi(ports) => {
|
||||
// An aligned list is a broken list: alignment only
|
||||
// means anything one element per line.
|
||||
let aligns = self.ansi_port_aligns(ports, &m.port_directives, depth + 1);
|
||||
let at = self.list_depth(depth + 1);
|
||||
let aligns = self.ansi_port_aligns(ports, &m.port_directives, at);
|
||||
broken |= aligns.iter().any(Option::is_some);
|
||||
ports
|
||||
.iter()
|
||||
@@ -116,10 +117,11 @@ impl<'a> Fmt<'a> {
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let items = self.list_entries(items, &m.port_directives);
|
||||
broken |= self.style_breaks(!items.is_empty());
|
||||
if !on_fresh_line {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.delimited_dangling("(", items, &m.port_dangling, ")", broken));
|
||||
docs.push(self.header_list("(", items, &m.port_dangling, ")", broken));
|
||||
docs.push(self.semi(&m.before_semi));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +1,22 @@
|
||||
//! Statements: the `begin … end` block, a statement as the body of a
|
||||
//! header (a cuddled block or an indented line), the dispatch from
|
||||
//! `StmtKind` to its layout, `if`/`else` chains, `case` items, and the
|
||||
//! `StmtKind` to its layout, `case` items, and the
|
||||
//! timing controls and sensitivity lists that head an `always` block or
|
||||
//! a clocking event.
|
||||
//!
|
||||
//! `stmt_kind` is a dispatch table over `StmtKind` — one arm per
|
||||
//! statement form — and stays whole; the forms with a layout of their own
|
||||
//! (`if`, `case`) are the functions after it.
|
||||
//! statement form — and stays whole; `case` has a layout of its own in the
|
||||
//! functions after it, `if` in `branch.rs`.
|
||||
|
||||
use crate::doc::*;
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
use super::comment::{is_line_comment, trailing_ends_line};
|
||||
use super::branch::before_keyword;
|
||||
use super::comment::is_line_comment;
|
||||
use super::{join_paths, named, skip_trivia, Fmt};
|
||||
use crate::style::Placement;
|
||||
|
||||
/// The pieces of a `begin … end` block a printer needs, gathered so the
|
||||
/// two spellings (a statement, and a body cuddled onto a header) pass one
|
||||
@@ -86,7 +88,14 @@ impl<'a> Fmt<'a> {
|
||||
/// The same, skipping the body's first `skip` leading comments because
|
||||
/// `prefix` already printed them inside its parentheses. See
|
||||
/// [`Fmt::header_parens`].
|
||||
fn stmt_as_body_from(&self, prefix: Doc, s: &Stmt, skip: usize) -> Doc {
|
||||
pub(super) fn stmt_as_body_from(&self, prefix: Doc, s: &Stmt, skip: usize) -> Doc {
|
||||
self.body_after(prefix, s, skip, self.cfg.style.begin)
|
||||
}
|
||||
|
||||
/// The layout behind both: a block's `begin` goes where `begin` says —
|
||||
/// the style's choice for a statement header, always the label's line
|
||||
/// for a `case` item.
|
||||
fn body_after(&self, prefix: Doc, s: &Stmt, skip: usize, begin: Placement) -> Doc {
|
||||
match &s.kind {
|
||||
StmtKind::Block {
|
||||
label_comments,
|
||||
@@ -97,7 +106,7 @@ impl<'a> Fmt<'a> {
|
||||
end_label,
|
||||
..
|
||||
} => {
|
||||
let mut docs = vec![prefix, text(" ")];
|
||||
let mut docs = vec![prefix, before_keyword(begin)];
|
||||
docs.extend(self.leading_from(&s.meta, skip));
|
||||
docs.push(self.block_doc(BlockDoc {
|
||||
label_comments,
|
||||
@@ -115,7 +124,7 @@ impl<'a> Fmt<'a> {
|
||||
let mut docs = vec![prefix, text(" ")];
|
||||
docs.extend(self.leading_from(&s.meta, skip));
|
||||
let control_doc = self.timing_control(control);
|
||||
docs.push(self.stmt_as_body(control_doc, inner));
|
||||
docs.push(self.body_after(control_doc, inner, 0, begin));
|
||||
docs.extend(self.trailing(&s.meta));
|
||||
concat(docs)
|
||||
}
|
||||
@@ -539,67 +548,6 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn if_stmt(
|
||||
&self,
|
||||
qualifier: &Option<String>,
|
||||
after_kw: &[Comment],
|
||||
cond: &Expr,
|
||||
then: &Stmt,
|
||||
else_comments: &[Comment],
|
||||
els: &Option<Box<Stmt>>,
|
||||
) -> Doc {
|
||||
let mut head = Vec::new();
|
||||
if let Some(q) = qualifier {
|
||||
head.push(text(format!("{q} ")));
|
||||
}
|
||||
self.word_then("if", after_kw, &mut head);
|
||||
let (parens, taken) = self.header_parens(cond, &then.meta);
|
||||
head.push(parens);
|
||||
let prefix = concat(head);
|
||||
// A line comment trailing the then-branch runs to end of line, so a
|
||||
// cuddled `else` would be swallowed into its text.
|
||||
let then_is_block =
|
||||
matches!(then.kind, StmtKind::Block { .. }) && !trailing_ends_line(&then.meta);
|
||||
let mut docs = vec![self.stmt_as_body_from(prefix, then, taken)];
|
||||
if let Some(els) = els {
|
||||
// A comment written before `else` prints before it, each on its
|
||||
// own line: it is where the source put it, and after the keyword
|
||||
// it would have crossed a token.
|
||||
if !else_comments.is_empty() {
|
||||
docs.push(Doc::HardLine);
|
||||
for c in else_comments {
|
||||
docs.push(self.comment(c));
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text("else"));
|
||||
} else if then_is_block {
|
||||
docs.push(text(" else"));
|
||||
} else {
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text("else"));
|
||||
}
|
||||
// `else if` chains stay flat.
|
||||
if let StmtKind::If {
|
||||
qualifier: eq,
|
||||
after_kw: ea,
|
||||
cond: ec,
|
||||
then: et,
|
||||
else_comments: ecm,
|
||||
els: ee,
|
||||
} = &els.kind
|
||||
{
|
||||
docs.push(text(" "));
|
||||
let mut meta_docs = self.leading(&els.meta);
|
||||
docs.append(&mut meta_docs);
|
||||
docs.push(self.if_stmt(eq, ea, ec, et, ecm, ee));
|
||||
docs.extend(self.trailing(&els.meta));
|
||||
} else {
|
||||
docs.push(self.stmt_as_body(text(""), els));
|
||||
}
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// The `A, B:` head of a case item — `default:` when the list is empty.
|
||||
/// Labels normally share one line; as soon as any of them carries a
|
||||
/// comment they go one per line, so a comment written between two labels
|
||||
@@ -669,7 +617,8 @@ impl<'a> Fmt<'a> {
|
||||
{
|
||||
return text("default;");
|
||||
}
|
||||
self.stmt_as_body(self.case_labels(&item.labels, &item.before_colon, item.span), &item.stmt)
|
||||
let labels = self.case_labels(&item.labels, &item.before_colon, item.span);
|
||||
self.body_after(labels, &item.stmt, 0, Placement::SameLine)
|
||||
}
|
||||
|
||||
/// The items of a `case`/`randcase` body. `skip` is the number of leading
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
//! Formatter engine: document IR + printer + formatting rules.
|
||||
|
||||
pub mod align;
|
||||
mod auto;
|
||||
pub mod doc;
|
||||
pub mod fence;
|
||||
pub mod format;
|
||||
pub mod printer;
|
||||
pub mod range;
|
||||
mod selection;
|
||||
pub mod style;
|
||||
pub mod verify;
|
||||
|
||||
pub use auto::{format_auto, resolve_style};
|
||||
pub use format::{format_range, format_source, Config, FormatError};
|
||||
pub use range::LineRanges;
|
||||
pub use selection::format_selection;
|
||||
pub use style::Style;
|
||||
pub use verify::{verify_convergence, verify_equivalence, VerificationError};
|
||||
@@ -18,9 +18,22 @@ pub struct Printer {
|
||||
}
|
||||
|
||||
impl Printer {
|
||||
/// Render `doc` starting at column 0.
|
||||
pub fn print(&self, doc: &Doc) -> String {
|
||||
let mut out = String::new();
|
||||
let mut col = 0usize;
|
||||
self.print_at(doc, "")
|
||||
}
|
||||
|
||||
/// Render `doc` as if every line began with `base`: the text starts with
|
||||
/// `base`, every line break the printer writes repeats it before the
|
||||
/// indentation, and the width budget shrinks by it.
|
||||
///
|
||||
/// `base` is copied as written, tabs included, which is what lets a
|
||||
/// selection keep the indentation it was written at. Text that carries
|
||||
/// its own absolute indentation (`Doc::Verbatim`, `Doc::Inline`) is not
|
||||
/// shifted. With an empty `base` this is exactly [`Printer::print`].
|
||||
pub fn print_at(&self, doc: &Doc, base: &str) -> String {
|
||||
let mut out = base.to_string();
|
||||
let mut col = self.base_width(base);
|
||||
// Stack of (indent_level, mode, doc).
|
||||
let mut stack: Vec<(usize, Mode, &Doc)> = vec![(0, Mode::Break, doc)];
|
||||
|
||||
@@ -61,24 +74,22 @@ impl Printer {
|
||||
out.push(' ');
|
||||
col += 1;
|
||||
} else {
|
||||
self.newline(&mut out, &mut col, ind);
|
||||
self.newline(&mut out, &mut col, ind, base);
|
||||
}
|
||||
}
|
||||
Doc::SoftLine => {
|
||||
if mode == Mode::Break {
|
||||
self.newline(&mut out, &mut col, ind);
|
||||
self.newline(&mut out, &mut col, ind, base);
|
||||
}
|
||||
}
|
||||
Doc::HardLine => {
|
||||
self.newline(&mut out, &mut col, ind);
|
||||
self.newline(&mut out, &mut col, ind, base);
|
||||
}
|
||||
Doc::BlankLine => {
|
||||
// Trim trailing spaces from the current line, add a blank.
|
||||
while out.ends_with(' ') {
|
||||
out.pop();
|
||||
}
|
||||
trim_line_end(&mut out, base);
|
||||
out.push('\n');
|
||||
self.newline(&mut out, &mut col, ind);
|
||||
self.newline(&mut out, &mut col, ind, base);
|
||||
}
|
||||
Doc::IfBreak(s) => {
|
||||
if mode == Mode::Break {
|
||||
@@ -89,9 +100,7 @@ impl Printer {
|
||||
Doc::Verbatim(s) => {
|
||||
// Undo the indent the preceding line break wrote: these
|
||||
// bytes carry their own.
|
||||
while out.ends_with(' ') {
|
||||
out.pop();
|
||||
}
|
||||
trim_line_end(&mut out, base);
|
||||
out.push_str(s);
|
||||
col = s.rsplit('\n').next().map_or(0, |last| last.chars().count());
|
||||
}
|
||||
@@ -100,14 +109,20 @@ impl Printer {
|
||||
out
|
||||
}
|
||||
|
||||
fn newline(&self, out: &mut String, col: &mut usize, ind: usize) {
|
||||
while out.ends_with(' ') {
|
||||
out.pop();
|
||||
}
|
||||
fn newline(&self, out: &mut String, col: &mut usize, ind: usize, base: &str) {
|
||||
trim_line_end(out, base);
|
||||
out.push('\n');
|
||||
out.push_str(base);
|
||||
let spaces = ind * self.indent_width;
|
||||
out.extend(std::iter::repeat_n(' ', spaces));
|
||||
*col = spaces;
|
||||
*col = self.base_width(base) + spaces;
|
||||
}
|
||||
|
||||
/// The columns `base` occupies. A tab counts as one indent level: the
|
||||
/// printer cannot know the reader's tab stop, and the width only steers
|
||||
/// which groups break.
|
||||
fn base_width(&self, base: &str) -> usize {
|
||||
base.chars().map(|c| if c == '\t' { self.indent_width } else { 1 }).sum()
|
||||
}
|
||||
|
||||
/// Would `items` (flat) followed by the rest of the work stack fit on
|
||||
@@ -194,6 +209,23 @@ impl Printer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop the trailing spaces of the line being written. Under a non-empty
|
||||
/// `base` a line holding nothing but indentation is emptied entirely, so a
|
||||
/// blank line never keeps the base's tabs; with no base this is exactly the
|
||||
/// space trim the printer always did.
|
||||
fn trim_line_end(out: &mut String, base: &str) {
|
||||
while out.ends_with(' ') {
|
||||
out.pop();
|
||||
}
|
||||
if base.is_empty() {
|
||||
return;
|
||||
}
|
||||
let bol = out.rfind('\n').map_or(0, |i| i + 1);
|
||||
if out[bol..].chars().all(|c| c == ' ' || c == '\t') {
|
||||
out.truncate(bol);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn contains_hard_line(items: &[Doc]) -> bool {
|
||||
items.iter().any(|d| match d {
|
||||
Doc::HardLine | Doc::BlankLine | Doc::Verbatim(_) => true,
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
//! Finding the run of sibling units one selected line span names.
|
||||
//!
|
||||
//! The walk starts at the file scope and goes down while the selection sits
|
||||
//! inside a single unit below its first line and reaches into exactly one of
|
||||
//! its nested scopes; it then settles on the units met there. A run that cannot be cut
|
||||
//! out of its lines cleanly, or whose ends a fenced region covers, is trimmed
|
||||
//! or given up one level at a time. The result is a [`Target`]: a path of
|
||||
//! child indices plus a run, which is what lets the same units be found again
|
||||
//! in the formatted output.
|
||||
|
||||
use crate::fence::Region;
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
use super::scope::{Scope, Unit};
|
||||
|
||||
/// The units a selection lays out, by position in the tree.
|
||||
///
|
||||
/// `path` holds one `(unit index, child scope index)` step per scope the walk
|
||||
/// descended into; the run is `start..start + count` of the scope it ends in.
|
||||
/// Positions, not bytes, so the target can be replayed on a reformatted text
|
||||
/// whose tree is the same.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(super) struct Target {
|
||||
pub path: Vec<(usize, usize)>,
|
||||
pub start: usize,
|
||||
pub count: usize,
|
||||
}
|
||||
|
||||
/// What one selected line span comes to.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(super) enum Found {
|
||||
/// No unit to lay out: blank lines, or everything met is fenced.
|
||||
Nothing,
|
||||
/// The run holds a module or package, or no run is line-clean: the
|
||||
/// request goes to `format_range` whole.
|
||||
Defer,
|
||||
Target(Target),
|
||||
}
|
||||
|
||||
/// The finder over one text and the tree parsed from it.
|
||||
pub(super) struct Locator<'s> {
|
||||
src: &'s str,
|
||||
index: LineIndex,
|
||||
regions: Vec<Region>,
|
||||
}
|
||||
|
||||
impl<'s> Locator<'s> {
|
||||
pub(super) fn new(src: &'s str, regions: Vec<Region>) -> Locator<'s> {
|
||||
Locator { src, index: LineIndex::new(src), regions }
|
||||
}
|
||||
|
||||
/// Locate the run the 1-based inclusive lines `first..=last` select.
|
||||
pub(super) fn locate(&self, root: Scope<'_>, (first, last): (u32, u32)) -> Found {
|
||||
let mut trail = vec![root];
|
||||
let mut path = Vec::new();
|
||||
let mut scope = root;
|
||||
let Some((mut a, mut b)) = self.met(scope, first, last) else { return Found::Nothing };
|
||||
while a == b {
|
||||
let Some((k, child)) = self.descend(scope, a, first, last) else { break };
|
||||
let Some(run) = self.met(child, first, last) else { break };
|
||||
path.push((a, k));
|
||||
trail.push(child);
|
||||
scope = child;
|
||||
(a, b) = run;
|
||||
}
|
||||
loop {
|
||||
let Some((a2, b2)) = self.trim_fences(scope, a, b) else { return Found::Nothing };
|
||||
if self.clean(scope, a2, b2) {
|
||||
return self.target(scope, path, a2, b2);
|
||||
}
|
||||
// Not cut cleanly at its lines: the enclosing unit is.
|
||||
trail.pop();
|
||||
let (Some((i, _)), Some(&parent)) = (path.pop(), trail.last()) else {
|
||||
return Found::Defer;
|
||||
};
|
||||
(scope, a, b) = (parent, i, i);
|
||||
}
|
||||
}
|
||||
|
||||
fn target(&self, scope: Scope<'_>, path: Vec<(usize, usize)>, a: usize, b: usize) -> Found {
|
||||
let contains_container =
|
||||
(a..=b).filter_map(|i| scope.unit(i)).any(|unit| unit.is_container());
|
||||
if contains_container {
|
||||
return Found::Defer;
|
||||
}
|
||||
Found::Target(Target { path, start: a, count: b - a + 1 })
|
||||
}
|
||||
|
||||
/// The first and last units of `scope` whose lines meet `first..=last`.
|
||||
fn met(&self, scope: Scope<'_>, first: u32, last: u32) -> Option<(usize, usize)> {
|
||||
let mut hit: Option<(usize, usize)> = None;
|
||||
for i in 0..scope.len() {
|
||||
let Some(unit) = scope.unit(i) else { continue };
|
||||
let (l0, l1) = self.lines(unit);
|
||||
if l0 <= last && first <= l1 {
|
||||
hit = Some(hit.map_or((i, i), |(a, _)| (a, i)));
|
||||
}
|
||||
}
|
||||
hit
|
||||
}
|
||||
|
||||
/// The nested scope to descend into from unit `i`: only when the
|
||||
/// selection does not touch the unit's first line, and reaches into
|
||||
/// exactly one of its scopes.
|
||||
///
|
||||
/// The last line is deliberately not asked about. A selection dragged
|
||||
/// over the final statements of a block and its closing `end` means those
|
||||
/// statements; taking the whole enclosing unit for it re-laid hundreds of
|
||||
/// unselected lines (QA note 2, lead ruling 2026-11-09). The closing line
|
||||
/// alone meets no nested unit, so it still names the unit it closes.
|
||||
fn descend<'t>(
|
||||
&self,
|
||||
scope: Scope<'t>,
|
||||
i: usize,
|
||||
first: u32,
|
||||
last: u32,
|
||||
) -> Option<(usize, Scope<'t>)> {
|
||||
let unit = scope.unit(i)?;
|
||||
let (l0, _) = self.lines(unit);
|
||||
if first <= l0 {
|
||||
return None;
|
||||
}
|
||||
let mut reached = unit
|
||||
.children()
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter(|(_, child)| self.met(*child, first, last).is_some());
|
||||
let only = reached.next()?;
|
||||
reached.next().is_none().then_some(only)
|
||||
}
|
||||
|
||||
/// The 1-based first and last lines of a unit's extent.
|
||||
fn lines(&self, unit: Unit<'_>) -> (u32, u32) {
|
||||
let (start, end) = unit.extent(self.src);
|
||||
let first = self.index.line_col(start as u32).0;
|
||||
let last = self.index.line_col(end.saturating_sub(1).max(start) as u32).0;
|
||||
(first, last)
|
||||
}
|
||||
|
||||
/// Drop units a fenced region of this scope reaches from both ends of the
|
||||
/// run, so no region is ever half inside the splice. `None` when nothing
|
||||
/// is left.
|
||||
fn trim_fences(&self, scope: Scope<'_>, mut a: usize, mut b: usize) -> Option<(usize, usize)> {
|
||||
while a <= b && self.fenced(scope, a) {
|
||||
a += 1;
|
||||
}
|
||||
while b > a && self.fenced(scope, b) {
|
||||
b -= 1;
|
||||
}
|
||||
(a <= b).then_some((a, b))
|
||||
}
|
||||
|
||||
/// Whether a region opened in this scope — not one nested inside the
|
||||
/// unit's own code — overlaps unit `i`'s extent.
|
||||
fn fenced(&self, scope: Scope<'_>, i: usize) -> bool {
|
||||
let Some(unit) = scope.unit(i) else { return true };
|
||||
let (start, end) = unit.extent(self.src);
|
||||
let span = unit.span();
|
||||
let (code_start, code_end) = (span.start as usize, span.end as usize);
|
||||
self.regions.iter().any(|r| {
|
||||
let overlaps = r.start < end && start < r.end;
|
||||
let nested = r.start >= code_start && r.end <= code_end;
|
||||
overlaps && !nested
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether units `a..=b` can be replaced by whole lines: only indentation
|
||||
/// before the first, nothing after the last on its line, and no sibling
|
||||
/// or dangling comment of the scope inside the bytes between.
|
||||
fn clean(&self, scope: Scope<'_>, a: usize, b: usize) -> bool {
|
||||
let (Some(first), Some(last)) = (scope.unit(a), scope.unit(b)) else { return false };
|
||||
let (start, _) = first.extent(self.src);
|
||||
let (_, end) = last.extent(self.src);
|
||||
let bol = line_start(self.src, start);
|
||||
let indent_only = self.src.get(bol..start).is_some_and(|s| s.chars().all(is_indent));
|
||||
let eol =
|
||||
self.src.get(end..).map_or(end, |rest| end + rest.find('\n').unwrap_or(rest.len()));
|
||||
let rest_blank = self.src.get(end..eol).is_some_and(|s| s.chars().all(char::is_whitespace));
|
||||
let prev_clear = a == 0 || scope.unit(a - 1).is_some_and(|u| u.extent(self.src).1 <= start);
|
||||
let next_clear = scope.unit(b + 1).is_none_or(|u| u.extent(self.src).0 >= end);
|
||||
let dangling_clear = scope
|
||||
.dangling()
|
||||
.iter()
|
||||
.all(|c| c.span.end as usize <= start || c.span.start as usize >= end);
|
||||
indent_only && rest_blank && prev_clear && next_clear && dangling_clear
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes a resolved target replaces, and the run that replaces them.
|
||||
pub(super) struct Placed<'t> {
|
||||
pub run: crate::format::Run<'t>,
|
||||
/// Start of the first unit's line: where the splice begins.
|
||||
pub bol: usize,
|
||||
/// The base indentation every line of the layout starts with, as a byte
|
||||
/// range of the source: the leading whitespace of the run's first unit
|
||||
/// that is not a directive (see [`base_indent`]).
|
||||
pub base: (usize, usize),
|
||||
/// One past the last unit's last byte.
|
||||
pub end: usize,
|
||||
}
|
||||
|
||||
/// Find `target` again in a tree, and the bytes of `src` it occupies.
|
||||
pub(super) fn resolve<'t>(src: &str, root: Scope<'t>, target: &Target) -> Option<Placed<'t>> {
|
||||
let mut scope = root;
|
||||
for &(i, k) in &target.path {
|
||||
scope = scope.unit(i)?.children().into_iter().nth(k)?;
|
||||
}
|
||||
let first = scope.unit(target.start)?;
|
||||
let last = scope.unit(target.start + target.count.checked_sub(1)?)?;
|
||||
let start = first.extent(src).0;
|
||||
let end = last.extent(src).1;
|
||||
let run = scope.run(target.start, target.count)?;
|
||||
let base = base_indent(src, scope, target, start);
|
||||
Some(Placed { run, bol: line_start(src, start), base, end })
|
||||
}
|
||||
|
||||
/// The indentation the run is laid out at: that of its first unit, unless
|
||||
/// that unit is a compiler directive and a later one is not. Directives are
|
||||
/// commonly written at column 0 while the code they guard is indented, and
|
||||
/// the code is what says where the block stands; the directive is then
|
||||
/// indented with it, as a whole-file run would.
|
||||
fn base_indent(src: &str, scope: Scope<'_>, target: &Target, start: usize) -> (usize, usize) {
|
||||
let code = (target.start..target.start + target.count)
|
||||
.filter_map(|i| scope.unit(i))
|
||||
.find(|u| !u.is_directive())
|
||||
.map(|u| u.extent(src).0);
|
||||
let own_line = |at: usize| {
|
||||
let bol = line_start(src, at);
|
||||
src.get(bol..at).is_some_and(|s| s.chars().all(is_indent)).then_some((bol, at))
|
||||
};
|
||||
code.and_then(own_line).unwrap_or((line_start(src, start), start))
|
||||
}
|
||||
|
||||
/// Every unit of a resolved target and everything nested in it, for the
|
||||
/// error-node check of a tolerant parse.
|
||||
pub(super) fn any_error(root: Scope<'_>, target: &Target) -> bool {
|
||||
let mut scope = root;
|
||||
for &(i, k) in &target.path {
|
||||
let Some(next) = scope.unit(i).and_then(|u| u.children().into_iter().nth(k)) else {
|
||||
return true;
|
||||
};
|
||||
scope = next;
|
||||
}
|
||||
(target.start..target.start + target.count).any(|i| scope.unit(i).is_none_or(unit_has_error))
|
||||
}
|
||||
|
||||
fn unit_has_error(unit: Unit<'_>) -> bool {
|
||||
unit.is_error()
|
||||
|| unit
|
||||
.children()
|
||||
.into_iter()
|
||||
.any(|s| (0..s.len()).any(|i| s.unit(i).is_none_or(unit_has_error)))
|
||||
}
|
||||
|
||||
/// The start of the line `at` is on.
|
||||
pub(super) fn line_start(src: &str, at: usize) -> usize {
|
||||
src.get(..at).and_then(|s| s.rfind('\n')).map_or(0, |i| i + 1)
|
||||
}
|
||||
|
||||
fn is_indent(c: char) -> bool {
|
||||
c == ' ' || c == '\t'
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
//! Selection formatting: lay out the smallest run of sibling items or
|
||||
//! statements the selected lines cover, at the indentation it was written
|
||||
//! at, and splice it into otherwise untouched bytes.
|
||||
//!
|
||||
//! This is what an editor's "Format Selection" wants. `format_range` (the
|
||||
//! CLI's `--lines`) re-lays whole module-level items at formatter depth;
|
||||
//! here the unit is whatever sibling list the selection lands in — a `case`
|
||||
//! inside an `always`, two statements of a function — and the parent is not
|
||||
//! touched at all. The run keeps the leading whitespace of its first line,
|
||||
//! tabs and off-grid indentation included. Every other byte of the file stays
|
||||
//! as written, the file tail included.
|
||||
//!
|
||||
//! The safety net is the usual one over the whole file: equivalence of the
|
||||
//! token streams, then convergence by replaying the located *target* (a path
|
||||
//! in the tree, not line numbers) on the output. Full spec:
|
||||
//! `docs/features/selection-formatting/README.md`.
|
||||
|
||||
mod locate;
|
||||
mod scope;
|
||||
|
||||
use crate::fence;
|
||||
use crate::format::{format_range, print_run, Config, FormatError};
|
||||
use crate::range::LineRanges;
|
||||
use crate::verify::{verify_convergence, verify_equivalence, VerificationError};
|
||||
use locate::{any_error, resolve, Found, Locator, Target};
|
||||
use scope::Scope;
|
||||
use vlog_parser::ast::SourceFile;
|
||||
use vlog_parser::ParseDiagnostic;
|
||||
|
||||
/// Format the smallest runs of sibling items or statements `lines` covers,
|
||||
/// each at the indentation its first line was written at, leaving every other
|
||||
/// byte of `source` as it is.
|
||||
///
|
||||
/// A selection reaching a module or package item as a whole is handed to
|
||||
/// [`format_range`] unchanged. A file that does not parse is formatted only
|
||||
/// where the selection is clear of every parse error; otherwise, as on any
|
||||
/// failed check, the caller gets an error and must keep the original text.
|
||||
///
|
||||
/// Under `style = "auto"` the style is the one the *whole* file is closest
|
||||
/// to, so a selection lays out exactly as a whole-file format would.
|
||||
///
|
||||
/// Same stack requirement as [`crate::format_source`].
|
||||
pub fn format_selection(
|
||||
source: &str,
|
||||
config: &Config,
|
||||
lines: &LineRanges,
|
||||
) -> Result<String, FormatError> {
|
||||
let config = &crate::auto::concrete(source, config);
|
||||
let tree = Tree::parse(source).map_err(FormatError::Source)?;
|
||||
let Some(root) = Scope::root(&tree.file) else {
|
||||
return format_range(source, config, lines);
|
||||
};
|
||||
let locator = Locator::new(source, fence::collect(source, &tree.file));
|
||||
let Ok(targets) = select(&locator, root, source, lines) else {
|
||||
return format_range(source, config, lines);
|
||||
};
|
||||
if targets.is_empty() {
|
||||
return Ok(source.to_string());
|
||||
}
|
||||
tree.check_clear(source, root, &targets)?;
|
||||
let output = splice(source, &tree.file, root, config, &targets)
|
||||
.ok_or_else(|| lost("the selection could not be cut out of its lines"))?;
|
||||
verify_equivalence(source, &output)?;
|
||||
let again = replay(&output, config, &targets)?;
|
||||
verify_convergence(&output, &again)?;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// Format the output a second time with the same targets, found again by
|
||||
/// their position in its tree.
|
||||
fn replay(output: &str, config: &Config, targets: &[Target]) -> Result<String, FormatError> {
|
||||
let tree = Tree::parse(output).map_err(VerificationError::Reparse)?;
|
||||
let root = Scope::root(&tree.file).ok_or_else(|| lost("the output is not the same kind"))?;
|
||||
tree.check_clear(output, root, targets)?;
|
||||
splice(output, &tree.file, root, config, targets)
|
||||
.ok_or_else(|| lost("the selection could not be found again in the output"))
|
||||
}
|
||||
|
||||
fn lost(why: &str) -> FormatError {
|
||||
FormatError::Selection(format!("cannot format the selection: {why}"))
|
||||
}
|
||||
|
||||
/// A parsed text: strictly when it parses, tolerantly when it does not.
|
||||
struct Tree {
|
||||
file: SourceFile,
|
||||
/// The tolerant parse's diagnostics; empty for a strict parse.
|
||||
diagnostics: Vec<ParseDiagnostic>,
|
||||
}
|
||||
|
||||
impl Tree {
|
||||
fn parse(src: &str) -> Result<Tree, vlog_parser::Error> {
|
||||
match vlog_parser::parse_source(src) {
|
||||
Ok(file) => Ok(Tree { file, diagnostics: Vec::new() }),
|
||||
Err(e) => {
|
||||
let (file, diagnostics) = vlog_parser::parse_source_tolerant(src);
|
||||
// A tolerant parse that finds nothing wrong where the strict
|
||||
// one failed is not a tree to trust.
|
||||
if diagnostics.is_empty() {
|
||||
return Err(e);
|
||||
}
|
||||
Ok(Tree { file, diagnostics })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuse when a parse error lies inside any target: its layout would
|
||||
/// rest on error recovery's guess.
|
||||
fn check_clear(
|
||||
&self,
|
||||
src: &str,
|
||||
root: Scope<'_>,
|
||||
targets: &[Target],
|
||||
) -> Result<(), FormatError> {
|
||||
if self.diagnostics.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
for target in targets {
|
||||
let placed = resolve(src, root, target).ok_or_else(|| lost("internal: lost target"))?;
|
||||
let (lo, hi) = (placed.bol, placed.end);
|
||||
let hit = self
|
||||
.diagnostics
|
||||
.iter()
|
||||
.find(|d| (d.span.start as usize) <= hi && lo <= d.span.end as usize);
|
||||
if let Some(d) = hit {
|
||||
return Err(FormatError::Selection(format!(
|
||||
"cannot format the selection: it contains a syntax error at {}:{}: {}",
|
||||
d.line, d.col, d.message
|
||||
)));
|
||||
}
|
||||
if any_error(root, target) {
|
||||
return Err(lost("it contains text that does not parse"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The request goes to `format_range` whole.
|
||||
struct Defer;
|
||||
|
||||
/// Locate one target per selected span; targets whose bytes overlap are
|
||||
/// re-selected from the hull of their spans.
|
||||
fn select(
|
||||
locator: &Locator<'_>,
|
||||
root: Scope<'_>,
|
||||
src: &str,
|
||||
lines: &LineRanges,
|
||||
) -> Result<Vec<Target>, Defer> {
|
||||
let mut picked: Vec<Picked> = Vec::new();
|
||||
for &span in lines.spans() {
|
||||
picked.extend(pick(locator, root, src, span)?);
|
||||
}
|
||||
loop {
|
||||
picked.sort_by_key(|p| p.bytes.0);
|
||||
let Some(i) = (1..picked.len()).find(|&i| picked[i].bytes.0 < picked[i - 1].bytes.1) else {
|
||||
break;
|
||||
};
|
||||
let (a, b) = (picked.remove(i), picked.remove(i - 1));
|
||||
let hull = (a.span.0.min(b.span.0), a.span.1.max(b.span.1));
|
||||
picked.extend(pick(locator, root, src, hull)?);
|
||||
}
|
||||
Ok(picked.into_iter().map(|p| p.target).collect())
|
||||
}
|
||||
|
||||
/// One located target, with the line span that chose it and the bytes it
|
||||
/// replaces.
|
||||
struct Picked {
|
||||
span: (u32, u32),
|
||||
target: Target,
|
||||
bytes: (usize, usize),
|
||||
}
|
||||
|
||||
/// The target one span selects, if any.
|
||||
fn pick(
|
||||
locator: &Locator<'_>,
|
||||
root: Scope<'_>,
|
||||
src: &str,
|
||||
span: (u32, u32),
|
||||
) -> Result<Option<Picked>, Defer> {
|
||||
match locator.locate(root, span) {
|
||||
Found::Nothing => Ok(None),
|
||||
Found::Defer => Err(Defer),
|
||||
Found::Target(target) => {
|
||||
// Resolving a target in the tree it was found in cannot fail; if
|
||||
// it ever did, the conservative answer is the old engine.
|
||||
let placed = resolve(src, root, &target).ok_or(Defer)?;
|
||||
Ok(Some(Picked { span, target, bytes: (placed.bol, placed.end) }))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace every target's bytes with its layout, bottom-up so the earlier
|
||||
/// offsets stay valid. `None` when a target cannot be found or cut.
|
||||
fn splice(
|
||||
src: &str,
|
||||
file: &SourceFile,
|
||||
root: Scope<'_>,
|
||||
config: &Config,
|
||||
targets: &[Target],
|
||||
) -> Option<String> {
|
||||
let mut placed = targets.iter().map(|t| resolve(src, root, t)).collect::<Option<Vec<_>>>()?;
|
||||
placed.sort_by_key(|p| std::cmp::Reverse(p.bol));
|
||||
let mut out = src.to_string();
|
||||
let mut floor = src.len();
|
||||
for p in placed {
|
||||
let base = src.get(p.base.0..p.base.1)?;
|
||||
if p.end > floor || !base.chars().all(|c| c == ' ' || c == '\t') {
|
||||
return None;
|
||||
}
|
||||
let mut text = print_run(src, file, config, p.run, base);
|
||||
if uses_crlf(src, p.bol, p.end) {
|
||||
text = to_crlf(&text);
|
||||
}
|
||||
out = format!("{}{}{}", out.get(..p.bol)?, text, out.get(p.end..)?);
|
||||
floor = p.bol;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Whether the lines around a target end in `\r\n`: the line ending after
|
||||
/// it, or before it when it ends the file.
|
||||
fn uses_crlf(src: &str, bol: usize, end: usize) -> bool {
|
||||
match src.get(end..).and_then(|rest| rest.find('\n')) {
|
||||
Some(i) => src.get(..end + i).is_some_and(|s| s.ends_with('\r')),
|
||||
None => src.get(..bol).is_some_and(|s| s.ends_with("\r\n")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn every bare `\n` into `\r\n`; text copied from the source keeps the
|
||||
/// `\r\n` it already had.
|
||||
fn to_crlf(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len() + text.len() / 16);
|
||||
let mut prev = '\0';
|
||||
for c in text.chars() {
|
||||
if c == '\n' && prev != '\r' {
|
||||
out.push('\r');
|
||||
}
|
||||
out.push(c);
|
||||
prev = c;
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
//! The sibling lists a selection can land in, and the units they hold.
|
||||
//!
|
||||
//! A *scope* is a sibling list exactly as `fence.rs` defines one — an item
|
||||
//! list (file, module, package, generate region, generate `begin`…`end`,
|
||||
//! class) or a statement list (`begin`…`end`, `fork`…`join`, a function or
|
||||
//! task body). A *unit* is one item or statement of such a list. The match
|
||||
//! arms below mirror `fence::scan_nested` / `scan_nested_stmt` /
|
||||
//! `scan_gen_block`: a single-statement body or a block-less generate item is
|
||||
//! not a scope, so it is walked *through* to the scopes it reaches. An arm
|
||||
//! missing here only makes a selection coarser, never wrong.
|
||||
|
||||
use crate::fence;
|
||||
use crate::format::Run;
|
||||
use vlog_parser::ast::{
|
||||
GenBlock, GenElse, GenIf, Item, ItemKind, Meta, SourceFile, Stmt, StmtKind,
|
||||
};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
/// One sibling list. Items carry the AST depth `item_seq` lays them out at.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum Scope<'t> {
|
||||
Items(&'t [Item], &'t [Comment], usize),
|
||||
Stmts(&'t [Stmt], &'t [Comment]),
|
||||
}
|
||||
|
||||
/// One member of a scope.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum Unit<'t> {
|
||||
Item(&'t Item, usize),
|
||||
Stmt(&'t Stmt),
|
||||
}
|
||||
|
||||
impl<'t> Scope<'t> {
|
||||
/// The scope a whole file is, or `None` for a fragment whose elements
|
||||
/// are not items or statements (enum members, cover items).
|
||||
pub(super) fn root(file: &'t SourceFile) -> Option<Scope<'t>> {
|
||||
match &file.fragment {
|
||||
None => Some(Scope::Items(&file.items, &file.dangling, 0)),
|
||||
Some(vlog_parser::ast::Fragment::Statements(stmts)) => {
|
||||
Some(Scope::Stmts(stmts, &file.dangling))
|
||||
}
|
||||
Some(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn len(&self) -> usize {
|
||||
match self {
|
||||
Scope::Items(items, ..) => items.len(),
|
||||
Scope::Stmts(stmts, _) => stmts.len(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn unit(&self, i: usize) -> Option<Unit<'t>> {
|
||||
match *self {
|
||||
Scope::Items(items, _, depth) => items.get(i).map(|item| Unit::Item(item, depth)),
|
||||
Scope::Stmts(stmts, _) => stmts.get(i).map(Unit::Stmt),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn dangling(&self) -> &'t [Comment] {
|
||||
match *self {
|
||||
Scope::Items(_, dangling, _) | Scope::Stmts(_, dangling) => dangling,
|
||||
}
|
||||
}
|
||||
|
||||
/// The units `start..start + count` as something the printers take.
|
||||
pub(super) fn run(&self, start: usize, count: usize) -> Option<Run<'t>> {
|
||||
let end = start.checked_add(count)?;
|
||||
match *self {
|
||||
Scope::Items(items, _, depth) => items.get(start..end).map(|s| Run::Items(s, depth)),
|
||||
Scope::Stmts(stmts, _) => stmts.get(start..end).map(Run::Stmts),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'t> Unit<'t> {
|
||||
fn meta(&self) -> &'t Meta {
|
||||
match self {
|
||||
Unit::Item(item, _) => &item.meta,
|
||||
Unit::Stmt(stmt) => &stmt.meta,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn span(&self) -> TextRange {
|
||||
match self {
|
||||
Unit::Item(item, _) => item.span,
|
||||
Unit::Stmt(stmt) => stmt.span,
|
||||
}
|
||||
}
|
||||
|
||||
/// The unit's bytes: its first leading comment or attribute through the
|
||||
/// comments written after it on the same line.
|
||||
pub(super) fn extent(&self, src: &str) -> (usize, usize) {
|
||||
let meta = self.meta();
|
||||
let span = self.span();
|
||||
let mut start = span.start;
|
||||
if let Some(c) = meta.leading.first() {
|
||||
start = start.min(c.span.start);
|
||||
}
|
||||
if let Some(a) = meta.attrs.first() {
|
||||
start = start.min(a.span.start);
|
||||
}
|
||||
// In a CRLF file a trailing `//` comment's line ends `\r\n`, and the
|
||||
// scan above stops at the `\n`. The `\r` is the line ending, not the
|
||||
// unit: the layout does not write it, so the splice must not eat it.
|
||||
let mut end = fence::with_trailing_comments(src, span.end as usize);
|
||||
while end > span.end as usize && src.as_bytes().get(end - 1) == Some(&b'\r') {
|
||||
end -= 1;
|
||||
}
|
||||
(start as usize, end)
|
||||
}
|
||||
|
||||
/// Whether the unit is a construct `format_range` splits (a module or a
|
||||
/// package), which a selection defers to it.
|
||||
pub(super) fn is_container(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Unit::Item(Item { kind: ItemKind::Module(_) | ItemKind::Package { .. }, .. }, _)
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether the unit is a compiler directive (`` `ifdef `` and kin),
|
||||
/// which is often written at column 0 whatever the code around it does.
|
||||
pub(super) fn is_directive(&self) -> bool {
|
||||
match self {
|
||||
Unit::Item(item, _) => matches!(item.kind, ItemKind::Directive(_)),
|
||||
Unit::Stmt(stmt) => matches!(stmt.kind, StmtKind::Directive(_)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the unit is a node error recovery made of unparsable text.
|
||||
pub(super) fn is_error(&self) -> bool {
|
||||
match self {
|
||||
Unit::Item(item, _) => matches!(item.kind, ItemKind::Error(_)),
|
||||
Unit::Stmt(stmt) => matches!(stmt.kind, StmtKind::Error(_)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The scopes directly nested in this unit, in source order.
|
||||
pub(super) fn children(&self) -> Vec<Scope<'t>> {
|
||||
let mut out = Vec::new();
|
||||
match *self {
|
||||
Unit::Item(item, depth) => item_scopes(item, depth, &mut out),
|
||||
Unit::Stmt(stmt) => stmt_scopes(stmt, &mut out),
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The scopes nested in one item at `depth`, at the depth `item_kind` lays
|
||||
/// their items out at.
|
||||
fn item_scopes<'t>(item: &'t Item, depth: usize, out: &mut Vec<Scope<'t>>) {
|
||||
match &item.kind {
|
||||
ItemKind::Module(m) => out.push(Scope::Items(&m.items, &m.dangling, depth + 1)),
|
||||
ItemKind::Package { items, dangling, .. }
|
||||
| ItemKind::GenerateRegion { items, dangling } => {
|
||||
out.push(Scope::Items(items, dangling, depth + 1))
|
||||
}
|
||||
ItemKind::GenBlock(b) => gen_block_scopes(b, depth, out),
|
||||
ItemKind::GenIf(g) => gen_if_scopes(g, depth, out),
|
||||
ItemKind::GenFor(g) => gen_block_scopes(&g.body, depth, out),
|
||||
ItemKind::GenCase(g) => {
|
||||
for i in &g.items {
|
||||
gen_block_scopes(&i.body, depth + 1, out);
|
||||
}
|
||||
}
|
||||
ItemKind::Class(c) => out.push(Scope::Items(&c.items, &c.dangling, depth + 1)),
|
||||
ItemKind::Function(f) => out.push(Scope::Stmts(&f.stmts, &f.dangling)),
|
||||
ItemKind::Task(t) => out.push(Scope::Stmts(&t.stmts, &t.dangling)),
|
||||
ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => {
|
||||
stmt_scopes(stmt, out)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_if_scopes<'t>(g: &'t GenIf, depth: usize, out: &mut Vec<Scope<'t>>) {
|
||||
gen_block_scopes(&g.then, depth, out);
|
||||
match g.els.as_deref() {
|
||||
Some(GenElse::If(_, inner)) => gen_if_scopes(inner, depth, out),
|
||||
Some(GenElse::Block(b)) => gen_block_scopes(b, depth, out),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A generate `begin`…`end` is a scope one level in; a block-less body's
|
||||
/// one item is laid out one level in too, and walked through.
|
||||
fn gen_block_scopes<'t>(b: &'t GenBlock, depth: usize, out: &mut Vec<Scope<'t>>) {
|
||||
if b.is_block {
|
||||
out.push(Scope::Items(&b.items, &b.dangling, depth + 1));
|
||||
} else {
|
||||
for item in &b.items {
|
||||
item_scopes(item, depth + 1, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The statement lists one statement holds, walking through every
|
||||
/// single-statement body.
|
||||
fn stmt_scopes<'t>(stmt: &'t Stmt, out: &mut Vec<Scope<'t>>) {
|
||||
match &stmt.kind {
|
||||
StmtKind::Block { stmts, dangling, .. } | StmtKind::ForkJoin { stmts, dangling, .. } => {
|
||||
out.push(Scope::Stmts(stmts, dangling))
|
||||
}
|
||||
StmtKind::If { then, els, .. } => {
|
||||
stmt_scopes(then, out);
|
||||
if let Some(e) = els {
|
||||
stmt_scopes(e, out);
|
||||
}
|
||||
}
|
||||
StmtKind::Assert { then, els, .. } => {
|
||||
for s in then.iter().chain(els.iter()) {
|
||||
stmt_scopes(s, out);
|
||||
}
|
||||
}
|
||||
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
|
||||
for i in items {
|
||||
stmt_scopes(&i.stmt, out);
|
||||
}
|
||||
}
|
||||
StmtKind::For { body, .. }
|
||||
| StmtKind::While { body, .. }
|
||||
| StmtKind::DoWhile { body, .. }
|
||||
| StmtKind::Repeat { body, .. }
|
||||
| StmtKind::Forever { body }
|
||||
| StmtKind::Foreach { body, .. }
|
||||
| StmtKind::Labeled { stmt: body, .. } => stmt_scopes(body, out),
|
||||
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
|
||||
stmt_scopes(inner, out)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
//! Named formatting styles: the house layouts a project picks with
|
||||
//! `[format] style = "<name>"`, `--style <name>` or `lucisv.format.style`.
|
||||
//!
|
||||
//! A style is one plain [`Style`] value — numbers and two-way switches, no
|
||||
//! code — and every preset is one row of the [`PRESETS`] table in this file,
|
||||
//! so the presets can be compared by reading them side by side. Each switch only ever moves
|
||||
//! whitespace: which line a token starts on, and how many spaces precede
|
||||
//! it. The token stream is the same under every style, which is why the
|
||||
//! safety net in `verify.rs` needs no knowledge of styles at all.
|
||||
//!
|
||||
//! `lucisv` is the default and is exactly the layout lucisv has always
|
||||
//! produced. Only `google` and `lowrisc` follow a published guide; `ansi`,
|
||||
//! `microsoft` and `nxp` are lucisv's educated guesses at what those names
|
||||
//! suggest, **not** rules published by those organisations. Each preset's
|
||||
//! comment says what it is modelled on and how sure that is.
|
||||
//!
|
||||
//! The full rationale, the sources and the per-preset safety sweeps are in
|
||||
//! `docs/features/format-styles/README.md`.
|
||||
|
||||
/// Where a keyword goes relative to the code before it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Placement {
|
||||
/// On the same line, one space after it.
|
||||
SameLine,
|
||||
/// At the start of a line of its own, at the enclosing indentation.
|
||||
OwnLine,
|
||||
}
|
||||
|
||||
/// When a module header's lists and a named connection list are broken.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PortLists {
|
||||
/// On one line if the whole construct fits, one entry per line if not.
|
||||
Fit,
|
||||
/// One entry per line whenever the list holds anything.
|
||||
OnePerLine,
|
||||
}
|
||||
|
||||
/// How deep the entries of a broken header or connection list are indented.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ListIndent {
|
||||
/// One indentation level past the line that opens the list.
|
||||
Block,
|
||||
/// Two levels — a continuation indent, Verible's `wrap`.
|
||||
Wrap,
|
||||
}
|
||||
|
||||
/// Whether runs of ports, connections and `parameter` declarations are
|
||||
/// padded into columns.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Alignment {
|
||||
/// Keep the columns the author already lined up, add none
|
||||
/// (`docs/features/alignment/README.md`).
|
||||
Infer,
|
||||
/// Pad every run into columns, whatever the source did.
|
||||
Always,
|
||||
}
|
||||
|
||||
/// One house style: every layout choice that differs between presets.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Style {
|
||||
/// The name the setting spells it with.
|
||||
pub name: &'static str,
|
||||
/// Spaces per indentation level; an explicit `indent` overrides it.
|
||||
pub indent: usize,
|
||||
/// Line limit; an explicit `line-length` overrides it.
|
||||
pub line_length: usize,
|
||||
/// `begin` of a statement body: `if (a) begin` (`SameLine`) or
|
||||
/// `if (a)` / `begin` (`OwnLine`). Every header that owns a body moves
|
||||
/// with it — `always_comb`, `always_ff @(…)`, `initial`, `final`, `if`,
|
||||
/// `else`, `for`, `foreach`, `while`, `repeat`, `forever`, `wait`, and
|
||||
/// generate `if`/`for`. A `case` item and `do` keep theirs on the label's
|
||||
/// line either way.
|
||||
pub begin: Placement,
|
||||
/// `else` after a block's `end`: `end else begin` (`SameLine`) or `end` /
|
||||
/// `else begin` (`OwnLine`). Procedural and generate `if` only.
|
||||
pub else_keyword: Placement,
|
||||
/// `else` after a *labelled* `end`, when `else_keyword` is `SameLine`:
|
||||
/// `end : l1 else begin` (`SameLine`) or `end : l1` / `else begin`
|
||||
/// (`OwnLine`), the exception both Google's and lowRISC's guides make.
|
||||
pub else_after_label: Placement,
|
||||
/// `module m (input a, input b);` when it fits (`Fit`), or `module m (` /
|
||||
/// ` input a,` / ` input b` / `);` always (`OnePerLine`). Governs a
|
||||
/// module/interface/program header's parameter and port lists, and an
|
||||
/// instance's *named* parameter overrides and connections. Not positional
|
||||
/// overrides (`#(16)`), not ordered connections (`(a, b)`), not
|
||||
/// function/task ports, not expression lists.
|
||||
pub port_lists: PortLists,
|
||||
/// The entries of a header or instance list once broken: ` .clk(clk),`
|
||||
/// (`Block`) or ` .clk(clk),` (`Wrap`). The closing `)` stays at the
|
||||
/// opening line's column — except in a declaration of several instances
|
||||
/// (`sub u0 (…), u1 (…);`), whose instances hang one level in and close
|
||||
/// there.
|
||||
pub list_indent: ListIndent,
|
||||
/// `input a,` / `input [7:0] b` kept as written (`Infer`), or always
|
||||
/// `input a,` / `input [7:0] b` (`Always`). One switch for all three
|
||||
/// tables lucisv aligns: ANSI ports, named connections, and runs of
|
||||
/// `parameter`/`localparam` declarations.
|
||||
pub alignment: Alignment,
|
||||
}
|
||||
|
||||
/// One row of [`PRESETS`], in its column order.
|
||||
#[allow(clippy::too_many_arguments)] // a table row: the arguments *are* the columns
|
||||
const fn row(
|
||||
name: &'static str,
|
||||
indent: usize,
|
||||
line_length: usize,
|
||||
begin: Placement,
|
||||
else_keyword: Placement,
|
||||
else_after_label: Placement,
|
||||
port_lists: PortLists,
|
||||
list_indent: ListIndent,
|
||||
alignment: Alignment,
|
||||
) -> Style {
|
||||
Style {
|
||||
name,
|
||||
indent,
|
||||
line_length,
|
||||
begin,
|
||||
else_keyword,
|
||||
else_after_label,
|
||||
port_lists,
|
||||
list_indent,
|
||||
alignment,
|
||||
}
|
||||
}
|
||||
|
||||
use Alignment::{Always, Infer};
|
||||
use ListIndent::{Block, Wrap};
|
||||
use Placement::{OwnLine, SameLine};
|
||||
use PortLists::{Fit, OnePerLine};
|
||||
|
||||
/// Every preset, the default first — one row each, so the six can be read
|
||||
/// side by side. What each is modelled on, and how sure that is, is on its
|
||||
/// named constant below.
|
||||
///
|
||||
/// Kept by hand on one line per row with the columns lined up: rustfmt would
|
||||
/// break every row into eleven lines and the table would stop being one.
|
||||
#[rustfmt::skip]
|
||||
pub const PRESETS: [Style; 6] = [
|
||||
// name indent width begin else else after `end : l` lists list indent alignment
|
||||
row("lucisv", 2, 100, SameLine, SameLine, SameLine, Fit, Block, Infer),
|
||||
row("google", 2, 100, SameLine, SameLine, OwnLine, OnePerLine, Wrap, Infer),
|
||||
row("lowrisc", 2, 100, SameLine, SameLine, OwnLine, OnePerLine, Block, Always),
|
||||
row("ansi", 4, 80, OwnLine, OwnLine, OwnLine, Fit, Block, Infer),
|
||||
row("microsoft", 4, 120, OwnLine, OwnLine, OwnLine, OnePerLine, Block, Infer),
|
||||
row("nxp", 2, 80, SameLine, OwnLine, OwnLine, OnePerLine, Block, Always),
|
||||
];
|
||||
|
||||
/// lucisv's own layout, and the default: byte-for-byte what every release
|
||||
/// before styles existed produced. Verible-like — 2 spaces, 100 columns,
|
||||
/// cuddled `begin`/`end`, alignment read from the source.
|
||||
pub const LUCISV: Style = PRESETS[0];
|
||||
|
||||
/// The Google Verilog Style Guide (google.github.io/styleguide/verilogguide):
|
||||
/// "Line Length" 100, "Indentation" 2, "Eschatology" `begin` on the
|
||||
/// keyword's line and `end else begin` — but `else` on a new line after a
|
||||
/// labelled `end` — "Module Header Definition Examples" one port per line
|
||||
/// with the list at a 4-space continuation indent, "Use named ports" one
|
||||
/// connection per line. "Tabular Alignment" is only *recommended*, and the
|
||||
/// guide's own examples are not aligned, so alignment stays inferred.
|
||||
/// Confidence: high, from the published guide.
|
||||
pub const GOOGLE: Style = PRESETS[1];
|
||||
|
||||
/// The lowRISC Verilog Coding Style Guide (lowRISC/style-guides,
|
||||
/// VerilogCodingStyle.md), OpenTitan's house style, which extends Google's:
|
||||
/// the same 2 / 100 / `end else begin` (with the same labelled-`end`
|
||||
/// exception, "Begin / End"), one port per line at a 2-space indent ("Module
|
||||
/// Declaration"). "Module Instantiation" *requires* connections aligned in
|
||||
/// tabular style; declaration ports are aligned in the guide's examples but
|
||||
/// not required to be. lucisv has one alignment switch for ports,
|
||||
/// connections and parameters, so the row aligns all three. Two deviations:
|
||||
/// lucisv writes the widest connection `.clk (clk)`, the guide tight
|
||||
/// (`.clk(clk)`); and a comment line inside a table ends lucisv's alignment
|
||||
/// group, where the guide keeps aligning across it. Confidence: high, from
|
||||
/// the published guide, for everything but those two.
|
||||
pub const LOWRISC: Style = PRESETS[2];
|
||||
|
||||
/// "ANSI" as C formatters use the word (Artistic Style, and iStyle, its
|
||||
/// Verilog port: `--style=ansi`, 4-space default): Allman layout, `begin`
|
||||
/// and `else` on lines of their own. The 80 columns are lucisv's guess.
|
||||
/// Confidence: medium for `begin`/`else`, a guess for the rest.
|
||||
pub const ANSI: Style = PRESETS[3];
|
||||
|
||||
/// clang-format's `Microsoft` base style for C-family code — 4 spaces, 120
|
||||
/// columns, braces and `else` on their own lines — carried over to
|
||||
/// `begin`/`end` by analogy, with one connection per line as clang-format's
|
||||
/// `VerilogBreakBetweenInstancePorts` does. **lucisv's guess**: Microsoft
|
||||
/// publishes no Verilog style that we know of.
|
||||
pub const MICROSOFT: Style = PRESETS[4];
|
||||
|
||||
/// A conservative RTL house style of the kind long-lived ASIC teams write
|
||||
/// down: 80 columns, `end` and `else` on separate lines, every port on its
|
||||
/// own line and every port and connection table aligned. **lucisv's guess**:
|
||||
/// NXP publishes no Verilog style guide that we could find.
|
||||
pub const NXP: Style = PRESETS[5];
|
||||
|
||||
/// The preset called `name`, if there is one.
|
||||
pub fn preset(name: &str) -> Option<Style> {
|
||||
PRESETS.into_iter().find(|s| s.name == name)
|
||||
}
|
||||
|
||||
/// The preset names, in [`PRESETS`] order.
|
||||
pub fn names() -> impl Iterator<Item = &'static str> {
|
||||
PRESETS.iter().map(|s| s.name)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_default_is_first_and_names_are_unique() {
|
||||
assert_eq!(PRESETS[0], LUCISV);
|
||||
let mut names: Vec<_> = names().collect();
|
||||
names.sort_unstable();
|
||||
names.dedup();
|
||||
assert_eq!(names.len(), PRESETS.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presets_are_found_by_name_and_nothing_else() {
|
||||
assert_eq!(preset("google"), Some(GOOGLE));
|
||||
assert_eq!(preset("Google"), None);
|
||||
assert_eq!(preset(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_preset_differs_from_every_other() {
|
||||
for (i, a) in PRESETS.iter().enumerate() {
|
||||
for b in &PRESETS[i + 1..] {
|
||||
let same = Style { name: a.name, ..*b };
|
||||
assert_ne!(*a, same, "{} and {} lay out identically", a.name, b.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! The formatter still refuses every unfinished-connection shape the tolerant
|
||||
//! parser now keeps inside its own entry (TODO §68.2,
|
||||
//! `docs/features/port-entry-grace/README.md`).
|
||||
//!
|
||||
//! The recovery is the editor's: it makes the rest of a half-typed file
|
||||
//! colour and lint as if the entry were complete. The formatter never reads
|
||||
//! the tolerant tree, and these pin that a buffer with a half-typed entry in
|
||||
//! it is refused whole — never printed with the entry "completed".
|
||||
|
||||
use vlog_formatter::{format_source, Config};
|
||||
|
||||
const UNFINISHED: &[(&str, &str)] = &[
|
||||
(
|
||||
"lone dot before the next entry",
|
||||
"module m;\n sub u0 (.a(x),\n .\n .b(y));\nendmodule\n",
|
||||
),
|
||||
("lone dot before a comma", "module m;\n sub u0 (.a(x), ., .b(y));\nendmodule\n"),
|
||||
("lone dot before the close", "module m;\n sub u0 (.a(x), .);\nendmodule\n"),
|
||||
(
|
||||
"open value before the next entry",
|
||||
"module m;\n sub u0 (.a(x), .po(\n .b(y));\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"open value with a partial name",
|
||||
"module m;\n sub u0 (.a(x), .po(z\n .b(y));\nendmodule\n",
|
||||
),
|
||||
("open value before the close", "module m;\n sub u0 (.a(x), .po(\n );\nendmodule\n"),
|
||||
("open override value", "module m;\n sub #(.W(8), .D(\n .E(1)) u0 (.a(x));\nendmodule\n"),
|
||||
("missing comma across lines", "module m;\n sub u0 (.a(x)\n .b(y));\nendmodule\n"),
|
||||
("missing comma on one line", "module m;\n sub u0 (.a(x) .b(y));\nendmodule\n"),
|
||||
(
|
||||
"implicit entry missing its comma",
|
||||
"module m;\n sub u0 (.a(x), .po\n .b(y));\nendmodule\n",
|
||||
),
|
||||
("trailing comma", "module m;\n sub u0 (.a(x), .b(y),);\nendmodule\n"),
|
||||
("trailing comma in an override list", "module m;\n sub #(.W(1),) u0 (.a(x));\nendmodule\n"),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn every_unfinished_connection_is_still_refused() {
|
||||
for (name, src) in UNFINISHED {
|
||||
let got = format_source(src, &Config::default());
|
||||
assert!(got.is_err(), "{name}: the formatter printed a half-typed entry:\n{got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The completed spelling of the same entries formats — so the refusal above
|
||||
/// is about the unfinished entry and nothing else in these sources.
|
||||
#[test]
|
||||
fn the_completed_entries_format() {
|
||||
let src = "module m;\n sub u0 (.a(x), .po(), .b(y));\nendmodule\n";
|
||||
assert!(format_source(src, &Config::default()).is_ok());
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
//! Selection formatting (`format_selection`): the smallest run of sibling
|
||||
//! items or statements a selection covers is laid out at the indentation it
|
||||
//! was written at, and every other byte of the file stays as written.
|
||||
//!
|
||||
//! Spec: `docs/features/selection-formatting/README.md`.
|
||||
|
||||
use vlog_formatter::{format_range, format_selection, verify_equivalence, Config, LineRanges};
|
||||
|
||||
fn select_with(src: &str, spec: &str, config: &Config) -> Result<String, String> {
|
||||
let lines = LineRanges::parse(spec).expect("line spec");
|
||||
format_selection(src, config, &lines).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn select(src: &str, spec: &str) -> String {
|
||||
select_with(src, spec, &Config::default()).expect("formats")
|
||||
}
|
||||
|
||||
/// Format, then format the result again with the same lines: the second run
|
||||
/// must change nothing.
|
||||
fn fixed(src: &str, spec: &str) -> String {
|
||||
let out = select(src, spec);
|
||||
assert_eq!(select(&out, spec), out, "a second run must change nothing");
|
||||
out
|
||||
}
|
||||
|
||||
/// Lines `first..=last` (1-based) of `src` are the target: everything before
|
||||
/// and after must come back byte for byte, and the returned middle is what
|
||||
/// replaced them.
|
||||
fn middle<'a>(src: &str, out: &'a str, first: usize, last: usize) -> &'a str {
|
||||
let lines: Vec<&str> = src.split_inclusive('\n').collect();
|
||||
let head: String = lines[..first - 1].concat();
|
||||
let tail: String = lines[last..].concat();
|
||||
assert!(out.starts_with(&head), "bytes before the target changed:\n{out}");
|
||||
assert!(out.ends_with(&tail), "bytes after the target changed:\n{out}");
|
||||
assert!(out.len() >= head.len() + tail.len(), "target overlaps the kept bytes:\n{out}");
|
||||
&out[head.len()..out.len() - tail.len()]
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// The owner's shapes
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A file indented four spaces, as many hand-written files are.
|
||||
const FOUR: &str = "\
|
||||
module m;
|
||||
reg [3:0] q;
|
||||
always @(posedge clk) begin
|
||||
if (rst) q<=0;
|
||||
else begin
|
||||
case (sel)
|
||||
2'b00: q<=a;
|
||||
2'b01 : q <= b;
|
||||
default:q<=c;
|
||||
endcase
|
||||
end
|
||||
end
|
||||
assign y=q;
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn a_whole_always_keeps_its_indentation_in_a_four_space_file() {
|
||||
let out = fixed(FOUR, "3-12");
|
||||
let mid = middle(FOUR, &out, 3, 12);
|
||||
assert_eq!(
|
||||
mid,
|
||||
" always @(posedge clk) begin
|
||||
if (rst) q <= 0;
|
||||
else begin
|
||||
case (sel)
|
||||
2'b00: q <= a;
|
||||
2'b01: q <= b;
|
||||
default: q <= c;
|
||||
endcase
|
||||
end
|
||||
end
|
||||
"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_case_inside_an_always_is_the_only_thing_laid_out() {
|
||||
let out = fixed(FOUR, "6-10");
|
||||
let mid = middle(FOUR, &out, 6, 10);
|
||||
assert_eq!(
|
||||
mid,
|
||||
" case (sel)
|
||||
2'b00: q <= a;
|
||||
2'b01: q <= b;
|
||||
default: q <= c;
|
||||
endcase
|
||||
"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_always_inside_a_generate_for_is_laid_out_alone() {
|
||||
let src = "\
|
||||
module m;
|
||||
generate
|
||||
for (genvar i=0;i<4;i++) begin : g
|
||||
always @(posedge clk) q[i]<=d[i];
|
||||
assign w[i]=q[i];
|
||||
end
|
||||
endgenerate
|
||||
endmodule
|
||||
";
|
||||
let out = fixed(src, "4");
|
||||
let mid = middle(src, &out, 4, 4);
|
||||
assert_eq!(mid, " always @(posedge clk) q[i] <= d[i];\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn statements_inside_a_function_are_laid_out_without_the_function() {
|
||||
let src = "\
|
||||
module m;
|
||||
function automatic int f(input int a);
|
||||
int r;
|
||||
r=a+1;
|
||||
return r;
|
||||
endfunction
|
||||
endmodule
|
||||
";
|
||||
let out = fixed(src, "4-5");
|
||||
let mid = middle(src, &out, 4, 5);
|
||||
assert_eq!(mid, " r = a + 1;\n return r;\n");
|
||||
assert!(out.contains(" int r;\n"), "the unselected statement stays: {out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_inside_an_else_branch_is_laid_out_alone() {
|
||||
let src = "\
|
||||
module m;
|
||||
always @* begin
|
||||
if (a) x = 1;
|
||||
else begin
|
||||
y=2;
|
||||
z = 3;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let out = fixed(src, "5-6");
|
||||
let mid = middle(src, &out, 5, 6);
|
||||
assert_eq!(mid, " y = 2;\n z = 3;\n");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Indentation
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn tab_indentation_is_reproduced_as_written() {
|
||||
let src = "module m;\n\talways @* begin\n\t\tx=1;\n\t\tif (a) begin\n\t\t\ty=2;\n\t\tend\n\tend\nendmodule\n";
|
||||
let out = fixed(src, "2-7");
|
||||
let mid = middle(src, &out, 2, 7);
|
||||
assert_eq!(
|
||||
mid,
|
||||
"\talways @(*) begin\n\t x = 1;\n\t if (a) begin\n\t y = 2;\n\t end\n\tend\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn off_grid_indentation_is_kept() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n end\nendmodule\n";
|
||||
let out = fixed(src, "2-4");
|
||||
assert_eq!(middle(src, &out, 2, 4), " always @(*) begin\n x = 1;\n end\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_misindented_parent_does_not_move_the_selection() {
|
||||
let src = "module m;\nalways @* begin\n x=1;\n y = 2;\n end\nendmodule\n";
|
||||
let out = fixed(src, "3");
|
||||
assert_eq!(middle(src, &out, 3, 3), " x = 1;\n");
|
||||
assert!(out.contains("\n y = 2;\n"), "the sibling is untouched: {out}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Partial selections
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn one_line_inside_a_case_lays_out_the_case() {
|
||||
let out = fixed(FOUR, "8");
|
||||
let mid = middle(FOUR, &out, 6, 10);
|
||||
assert!(mid.starts_with(" case (sel)\n"), "{mid}");
|
||||
assert!(mid.contains(" 2'b01: q <= b;\n"), "{mid}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cursor_only_range_formats_the_statement_under_it() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\nendmodule\n";
|
||||
let out = fixed(src, "4");
|
||||
assert_eq!(out, "module m;\n always @* begin\n x=1;\n y = 2;\n end\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_ending_on_the_end_line_takes_only_the_statements_it_covers() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\n assign a=b;\nendmodule\n";
|
||||
let out = fixed(src, "4-5");
|
||||
assert_eq!(middle(src, &out, 4, 4), " y = 2;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_line_alone_takes_the_unit_it_closes() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\n assign a=b;\nendmodule\n";
|
||||
let out = fixed(src, "5");
|
||||
assert_eq!(middle(src, &out, 2, 5), " always @(*) begin\n x = 1;\n y = 2;\n end\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_starting_on_the_first_line_takes_the_whole_unit() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\n assign a=b;\nendmodule\n";
|
||||
let out = fixed(src, "2-3");
|
||||
assert_eq!(middle(src, &out, 2, 5), " always @(*) begin\n x = 1;\n y = 2;\n end\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_lines_alone_change_nothing() {
|
||||
let src = "module m;\n wire a;\n\n\n wire b;\nendmodule\n";
|
||||
assert_eq!(select(src, "3-4"), src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leading_and_trailing_comments_travel_with_their_unit() {
|
||||
let src = "module m;\n always @* begin\n // why\n x=1; // what\n y=2;\n end\nendmodule\n";
|
||||
let out = fixed(src, "4");
|
||||
assert_eq!(middle(src, &out, 3, 4), " // why\n x = 1; // what\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_after_begin_is_not_line_clean_and_the_parent_is_taken() {
|
||||
let src = "module m;\n always @* begin // note\n x=1;\n end\nendmodule\n";
|
||||
let out = fixed(src, "3");
|
||||
assert_eq!(middle(src, &out, 2, 4), " always @(*) begin\n // note\n x = 1;\n end\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_statements_on_one_line_are_taken_together() {
|
||||
let src = "module m;\n always @* begin\n x=1; y=2;\n z=3;\n end\nendmodule\n";
|
||||
let out = fixed(src, "3");
|
||||
assert_eq!(middle(src, &out, 3, 3), " x = 1;\n y = 2;\n");
|
||||
assert!(out.contains(" z=3;\n"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_across_two_branches_takes_the_whole_if() {
|
||||
let src = "module m;\n always @* begin\n if (a) begin\n x=1;\n end else begin\n y=2;\n end\n end\nendmodule\n";
|
||||
let out = fixed(src, "4-6");
|
||||
let mid = middle(src, &out, 3, 7);
|
||||
assert_eq!(mid, " if (a) begin\n x = 1;\n end else begin\n y = 2;\n end\n");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Fences
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_fence_inside_the_target_is_emitted_as_written() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n // lucisv: off\n y = 2;\n // lucisv: on\n z=3;\n end\nendmodule\n";
|
||||
let out = fixed(src, "2-8");
|
||||
assert!(out.contains(" y = 2;\n"), "{out}");
|
||||
assert!(out.contains(" x = 1;\n") && out.contains(" z = 3;\n"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fence_around_the_target_wins() {
|
||||
let src = "module m;\n // lucisv: off\n always @* begin\n x=1;\n end\n // lucisv: on\nendmodule\n";
|
||||
assert_eq!(select(src, "4"), src);
|
||||
assert_eq!(select(src, "3-5"), src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fence_straddling_the_target_trims_the_fenced_units() {
|
||||
let src = "module m;\n always @* begin\n a=1;\n b=2;\n // lucisv: off\n c = 3;\n // lucisv: on\n d=4;\n end\nendmodule\n";
|
||||
// Lines 3-6 meet a, b, and c (fenced): c is trimmed off the end.
|
||||
let out = fixed(src, "3-6");
|
||||
assert_eq!(middle(src, &out, 3, 4), " a = 1;\n b = 2;\n");
|
||||
assert!(out.ends_with(
|
||||
" // lucisv: off\n c = 3;\n // lucisv: on\n d=4;\n end\nendmodule\n"
|
||||
));
|
||||
// Lines 6-8 meet c (fenced) and d — whose extent starts at `on`: both go.
|
||||
assert_eq!(select(src, "6-8"), src);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Deferral to `format_range`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_module_header_or_whole_module_selection_is_format_range() {
|
||||
let src = "module m(input a,output b);\n wire x;\n assign x=a;\nendmodule\nmodule n;\nendmodule\n";
|
||||
for spec in ["1", "1-4", "1-6", "4", "2-5"] {
|
||||
let lines = LineRanges::parse(spec).expect("spec");
|
||||
let range = format_range(src, &Config::default(), &lines).expect("range formats");
|
||||
assert_eq!(select(src, spec), range, "spec {spec}");
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Files that do not parse
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
const BROKEN: &str = "\
|
||||
module m;
|
||||
always @* begin
|
||||
x=1;
|
||||
end
|
||||
assign y = ;
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn an_error_outside_the_target_does_not_stop_it() {
|
||||
let out = fixed(BROKEN, "3");
|
||||
assert_eq!(middle(BROKEN, &out, 3, 3), " x = 1;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_error_inside_the_target_refuses() {
|
||||
let err = select_with(BROKEN, "5", &Config::default()).expect_err("refused");
|
||||
assert!(err.contains("syntax error") || err.contains("parse"), "{err}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Idempotence and multiple ranges
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn formatting_the_same_target_twice_changes_nothing() {
|
||||
for spec in ["3-12", "6-10", "4", "8", "13"] {
|
||||
fixed(FOUR, spec);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_ranges_lay_out_two_targets_and_nothing_between() {
|
||||
let src = "module m;\n always @* begin\n x=1;\n y=2;\n z=3;\n end\nendmodule\n";
|
||||
let out = fixed(src, "3,5");
|
||||
assert_eq!(
|
||||
out,
|
||||
"module m;\n always @* begin\n x = 1;\n y=2;\n z = 3;\n end\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_targets_are_reselected_from_their_hull() {
|
||||
// `4` selects the inner statement, `2` the always holding it.
|
||||
let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\nendmodule\n";
|
||||
let out = fixed(src, "2,4");
|
||||
assert_eq!(out, "module m;\n always @(*) begin\n x = 1;\n y = 2;\n end\nendmodule\n");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Masked-corruption attacks on the splice
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Either a correct result (equivalent to the input, a fixed point) or a
|
||||
/// refusal — never silently wrong.
|
||||
fn correct_or_refused(src: &str, spec: &str) -> Option<String> {
|
||||
let out = select_with(src, spec, &Config::default()).ok()?;
|
||||
verify_equivalence(src, &out).expect("the result is equivalent to the input");
|
||||
assert_eq!(select(&out, spec), out, "and a fixed point");
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trailing_comment_on_the_last_line_survives() {
|
||||
let src = "module m;\n always @* begin\n x=1; /* a */ /* b */\n end\nendmodule\n";
|
||||
let out = correct_or_refused(src, "3").expect("formats");
|
||||
assert!(out.contains("/* a */") && out.contains("/* b */"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_line_endings_are_kept() {
|
||||
let src = "module m;\r\n always @* begin\r\n x=1;\r\n y=2;\r\n end\r\nendmodule\r\n";
|
||||
let out = correct_or_refused(src, "3-4").expect("formats");
|
||||
assert_eq!(
|
||||
out,
|
||||
"module m;\r\n always @* begin\r\n x = 1;\r\n y = 2;\r\n end\r\nendmodule\r\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_with_a_trailing_comment_on_the_last_line_keeps_every_line_ending() {
|
||||
// QA finding 1: the `\r` after a trailing `//` comment is the line
|
||||
// ending, not part of the unit, so the splice leaves it in place.
|
||||
let src = "module m;\r\n initial begin\r\n a = 1; // c\r\n b = 2; // d\r\n end\r\nendmodule\r\n";
|
||||
let out = correct_or_refused(src, "3-4").expect("formats");
|
||||
assert_eq!(out, src.replace("b = 2", "b = 2"));
|
||||
let out = correct_or_refused(src, "4").expect("formats");
|
||||
assert_eq!(out, src.replace("b = 2", "b = 2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_line_block_comment_inside_the_target_survives() {
|
||||
let src =
|
||||
"module m;\n always @* begin\n /* one\n two */\n x=1;\n end\nendmodule\n";
|
||||
let out = correct_or_refused(src, "2-6").expect("formats");
|
||||
assert!(out.contains("/* one\n two */"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_line_string_inside_the_target_is_kept_or_refused() {
|
||||
let src =
|
||||
"module m;\n initial begin\n $display(\"a\\\n b\");\n x=1;\n end\nendmodule\n";
|
||||
if let Some(out) = correct_or_refused(src, "2-6") {
|
||||
assert!(out.contains("\"a\\\n b\""), "{out}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_target_at_the_end_of_a_file_without_a_final_newline() {
|
||||
let src = "always @* begin\n x=1;\nend";
|
||||
let out = correct_or_refused(src, "2").expect("formats");
|
||||
assert_eq!(out, "always @* begin\n x = 1;\nend");
|
||||
let src = "wire a;\nassign b=a;";
|
||||
let out = correct_or_refused(src, "2").expect("formats");
|
||||
assert_eq!(out, "wire a;\nassign b = a;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_byte_characters_before_the_target_do_not_shift_it() {
|
||||
let src = "module m;\n // café — ünïcode\n wire a; // ß\n assign b=a;\nendmodule\n";
|
||||
let out = correct_or_refused(src, "4").expect("formats");
|
||||
assert_eq!(middle(src, &out, 4, 4), " assign b = a;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_safety_net_rejects_a_mis_spliced_output() {
|
||||
// An off-by-one at the end of the splice duplicates the `;`; at the
|
||||
// start it drops the trailing comment's first byte. Both must be caught.
|
||||
let src = "module m;\n always @* begin\n x=1; // c\n end\nendmodule\n";
|
||||
let duplicated = "module m;\n always @* begin\n x = 1;; // c\n end\nendmodule\n";
|
||||
assert!(verify_equivalence(src, duplicated).is_err());
|
||||
let dropped = "module m;\n always @* begin\n x = 1; c\n end\nendmodule\n";
|
||||
assert!(verify_equivalence(src, dropped).is_err());
|
||||
let crlf = "module m;\r\n always @* begin\r\n /* one\r\n two */\r\n x=1;\r\n end\r\nendmodule\r\n";
|
||||
let lost_comment_line =
|
||||
"module m;\r\n always @* begin\r\n /* one */\r\n x = 1;\r\n end\r\nendmodule\r\n";
|
||||
assert!(verify_equivalence(crlf, lost_comment_line).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_column_zero_directive_does_not_set_the_indentation_of_the_code_it_guards() {
|
||||
let src = "module m;\n`ifdef A\n wire a;\n`endif\n wire b;\nendmodule\n";
|
||||
let out = fixed(src, "2-4");
|
||||
// The code says where the block stands; the directives are indented with
|
||||
// it, as a whole-file run indents them.
|
||||
assert_eq!(middle(src, &out, 2, 4), " `ifdef A\n wire a;\n `endif\n");
|
||||
}
|
||||
@@ -0,0 +1,686 @@
|
||||
//! The named styles (`vlog_formatter::style`): one test per layout switch,
|
||||
//! each flipping that switch alone on top of the default, then every preset
|
||||
//! on one module.
|
||||
//!
|
||||
//! Every switch only moves whitespace, so each test also asserts the two
|
||||
//! properties that matter more than the layout itself: the output is a fixed
|
||||
//! point under the same style, and the default never moves a byte.
|
||||
|
||||
use vlog_formatter::style::{self, Alignment, ListIndent, Placement, PortLists, Style};
|
||||
use vlog_formatter::{
|
||||
format_range, format_selection, format_source, resolve_style, Config, LineRanges,
|
||||
};
|
||||
|
||||
fn format(src: &str, style: Style) -> String {
|
||||
let out = format_source(src, &Config::styled(style)).expect("formats");
|
||||
let again = format_source(&out, &Config::styled(style)).expect("formats again");
|
||||
assert_eq!(again, out, "not a fixed point under `{}`", style.name);
|
||||
out
|
||||
}
|
||||
|
||||
/// The default with one switch changed.
|
||||
fn with(change: impl FnOnce(&mut Style)) -> Style {
|
||||
let mut style = style::LUCISV;
|
||||
style.name = "test";
|
||||
change(&mut style);
|
||||
style
|
||||
}
|
||||
|
||||
const BRANCHES: &str = "\
|
||||
module m;
|
||||
always_ff @(posedge clk) begin
|
||||
if (a) begin
|
||||
x <= 1;
|
||||
end else if (b) begin
|
||||
x <= 2;
|
||||
end else begin
|
||||
x <= 3;
|
||||
end
|
||||
end
|
||||
always_comb begin
|
||||
case (s)
|
||||
0: begin
|
||||
y = 1;
|
||||
end
|
||||
default: y = 0;
|
||||
endcase
|
||||
end
|
||||
if (G) begin : gen_a
|
||||
assign z = 1;
|
||||
end else begin : gen_b
|
||||
assign z = 0;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn begin_on_its_own_line_leaves_case_items_alone() {
|
||||
let out = format(BRANCHES, with(|s| s.begin = Placement::OwnLine));
|
||||
assert_eq!(
|
||||
out,
|
||||
"\
|
||||
module m;
|
||||
always_ff @(posedge clk)
|
||||
begin
|
||||
if (a)
|
||||
begin
|
||||
x <= 1;
|
||||
end else if (b)
|
||||
begin
|
||||
x <= 2;
|
||||
end else
|
||||
begin
|
||||
x <= 3;
|
||||
end
|
||||
end
|
||||
always_comb
|
||||
begin
|
||||
case (s)
|
||||
0: begin
|
||||
y = 1;
|
||||
end
|
||||
default: y = 0;
|
||||
endcase
|
||||
end
|
||||
if (G)
|
||||
begin : gen_a
|
||||
assign z = 1;
|
||||
end else
|
||||
begin : gen_b
|
||||
assign z = 0;
|
||||
end
|
||||
endmodule
|
||||
"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn else_on_its_own_line() {
|
||||
let out = format(BRANCHES, with(|s| s.else_keyword = Placement::OwnLine));
|
||||
assert_eq!(
|
||||
out,
|
||||
"\
|
||||
module m;
|
||||
always_ff @(posedge clk) begin
|
||||
if (a) begin
|
||||
x <= 1;
|
||||
end
|
||||
else if (b) begin
|
||||
x <= 2;
|
||||
end
|
||||
else begin
|
||||
x <= 3;
|
||||
end
|
||||
end
|
||||
always_comb begin
|
||||
case (s)
|
||||
0: begin
|
||||
y = 1;
|
||||
end
|
||||
default: y = 0;
|
||||
endcase
|
||||
end
|
||||
if (G) begin : gen_a
|
||||
assign z = 1;
|
||||
end
|
||||
else begin : gen_b
|
||||
assign z = 0;
|
||||
end
|
||||
endmodule
|
||||
"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allman_is_both_switches_together() {
|
||||
let allman = with(|s| {
|
||||
s.begin = Placement::OwnLine;
|
||||
s.else_keyword = Placement::OwnLine;
|
||||
});
|
||||
let src = "module m;\n initial if (a) begin x = 1; end else begin x = 2; end\nendmodule\n";
|
||||
assert_eq!(
|
||||
format(src, allman),
|
||||
"\
|
||||
module m;
|
||||
initial
|
||||
if (a)
|
||||
begin
|
||||
x = 1;
|
||||
end
|
||||
else
|
||||
begin
|
||||
x = 2;
|
||||
end
|
||||
endmodule
|
||||
"
|
||||
);
|
||||
}
|
||||
|
||||
/// A comment written before `begin` or before `else` stays exactly where it
|
||||
/// was in the token stream, whichever line the keyword moves to.
|
||||
#[test]
|
||||
fn comments_around_moved_keywords_stay_put() {
|
||||
let src = "\
|
||||
module m;
|
||||
always_comb
|
||||
if (a) /* why */ begin
|
||||
x = 1;
|
||||
end
|
||||
// otherwise
|
||||
else begin
|
||||
x = 2;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let allman = with(|s| {
|
||||
s.begin = Placement::OwnLine;
|
||||
s.else_keyword = Placement::OwnLine;
|
||||
});
|
||||
let out = format(src, allman);
|
||||
assert!(out.contains("if (a)\n /* why */\n begin"), "{out}");
|
||||
assert!(out.contains("end\n // otherwise\n else\n begin"), "{out}");
|
||||
// And back: the default puts every keyword where it always did.
|
||||
assert_eq!(format(&out, style::LUCISV), format(src, style::LUCISV));
|
||||
}
|
||||
|
||||
const HEADER: &str = "\
|
||||
module m #(parameter int W = 8) (input logic clk, output logic [W-1:0] q);
|
||||
sub #(.W(W)) u_sub (.clk(clk), .q(q));
|
||||
sub #(8) u_pos (clk, q);
|
||||
sub u_wild (.*);
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn one_port_per_line_breaks_headers_and_named_lists_only() {
|
||||
let out = format(HEADER, with(|s| s.port_lists = PortLists::OnePerLine));
|
||||
assert_eq!(
|
||||
out,
|
||||
"\
|
||||
module m #(
|
||||
parameter int W = 8
|
||||
) (
|
||||
input logic clk,
|
||||
output logic [W-1:0] q
|
||||
);
|
||||
sub #(
|
||||
.W(W)
|
||||
) u_sub (
|
||||
.clk(clk),
|
||||
.q(q)
|
||||
);
|
||||
sub #(8) u_pos (clk, q);
|
||||
sub u_wild (
|
||||
.*
|
||||
);
|
||||
endmodule
|
||||
"
|
||||
);
|
||||
// An empty list has nothing to break.
|
||||
let empty = "module m ();\nendmodule\n";
|
||||
assert_eq!(format(empty, with(|s| s.port_lists = PortLists::OnePerLine)), empty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrapped_list_indents_its_entries_two_levels() {
|
||||
let style = with(|s| {
|
||||
s.port_lists = PortLists::OnePerLine;
|
||||
s.list_indent = ListIndent::Wrap;
|
||||
});
|
||||
assert_eq!(
|
||||
format(HEADER, style),
|
||||
"\
|
||||
module m #(
|
||||
parameter int W = 8
|
||||
) (
|
||||
input logic clk,
|
||||
output logic [W-1:0] q
|
||||
);
|
||||
sub #(
|
||||
.W(W)
|
||||
) u_sub (
|
||||
.clk(clk),
|
||||
.q(q)
|
||||
);
|
||||
sub #(8) u_pos (clk, q);
|
||||
sub u_wild (
|
||||
.*
|
||||
);
|
||||
endmodule
|
||||
"
|
||||
);
|
||||
// Wrap alone changes only lists that break anyway.
|
||||
assert_eq!(
|
||||
format(HEADER, with(|s| s.list_indent = ListIndent::Wrap)),
|
||||
format(HEADER, style::LUCISV)
|
||||
);
|
||||
}
|
||||
|
||||
/// Written without a single padding space, so the default keeps it flush.
|
||||
const FLUSH: &str = "\
|
||||
module m (input logic clk, input logic [7:0] data, output logic valid);
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
sub u_sub (.clk(clk), .data_in(data), .v(valid));
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn always_aligned_pads_ports_parameters_and_connections() {
|
||||
// The default reads the source and keeps this flush...
|
||||
assert_eq!(format(FLUSH, style::LUCISV), FLUSH);
|
||||
// ...and `Always` aligns it, which breaks the lists: a column only means
|
||||
// anything one entry per line.
|
||||
assert_eq!(
|
||||
format(FLUSH, with(|s| s.alignment = Alignment::Always)),
|
||||
"\
|
||||
module m (
|
||||
input logic clk,
|
||||
input logic [7:0] data,
|
||||
output logic valid
|
||||
);
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
sub u_sub (
|
||||
.clk (clk),
|
||||
.data_in (data),
|
||||
.v (valid)
|
||||
);
|
||||
endmodule
|
||||
"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn always_aligned_still_refuses_what_alignment_cannot_do() {
|
||||
let always = with(|s| s.alignment = Alignment::Always);
|
||||
// Nothing to pad: every row is the same width.
|
||||
let same = "module m;\n localparam int A = 1;\n localparam int B = 2;\nendmodule\n";
|
||||
assert_eq!(format(same, always), same);
|
||||
// Too wide for the line: the whole group stays flush.
|
||||
let wide = with(|s| {
|
||||
s.alignment = Alignment::Always;
|
||||
s.line_length = 40;
|
||||
});
|
||||
let src = "module m;\n localparam int A = 32'hFFFF_FFFF;\n localparam int LONGER_NAME_HERE = 2;\nendmodule\n";
|
||||
assert_eq!(format(src, wide), src);
|
||||
// A blank line still splits two tables.
|
||||
let two = "module m;\n localparam int A = 1;\n\n localparam int LONGER = 2;\nendmodule\n";
|
||||
assert_eq!(format(two, always), two);
|
||||
}
|
||||
|
||||
/// One module touching every switch, through every preset.
|
||||
const SAMPLE: &str = "\
|
||||
module top #(parameter int W = 8) (input logic clk, input logic [W-1:0] d, output logic [W-1:0] q);
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
always_ff @(posedge clk) begin
|
||||
if (d == 0) begin
|
||||
q <= '0;
|
||||
end else begin
|
||||
q <= d;
|
||||
end
|
||||
end
|
||||
sub #(.W(W)) u_sub (.clk(clk), .data_in(d));
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn the_lucisv_preset_is_the_default() {
|
||||
assert_eq!(style::preset("lucisv"), Some(style::LUCISV));
|
||||
let default = Config::default();
|
||||
let lucisv = Config::styled(style::LUCISV);
|
||||
assert_eq!((default.max_width, default.indent_width), (lucisv.max_width, lucisv.indent_width));
|
||||
assert_eq!(default.style, lucisv.style);
|
||||
assert!(!default.uvm_utils_indent);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_preset_formats_the_sample() {
|
||||
let expected = [
|
||||
(
|
||||
"lucisv",
|
||||
"\
|
||||
module top #(parameter int W = 8) (input logic clk, input logic [W-1:0] d, output logic [W-1:0] q);
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
always_ff @(posedge clk) begin
|
||||
if (d == 0) begin
|
||||
q <= '0;
|
||||
end else begin
|
||||
q <= d;
|
||||
end
|
||||
end
|
||||
sub #(.W(W)) u_sub (.clk(clk), .data_in(d));
|
||||
endmodule
|
||||
",
|
||||
),
|
||||
(
|
||||
"google",
|
||||
"\
|
||||
module top #(
|
||||
parameter int W = 8
|
||||
) (
|
||||
input logic clk,
|
||||
input logic [W-1:0] d,
|
||||
output logic [W-1:0] q
|
||||
);
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
always_ff @(posedge clk) begin
|
||||
if (d == 0) begin
|
||||
q <= '0;
|
||||
end else begin
|
||||
q <= d;
|
||||
end
|
||||
end
|
||||
sub #(
|
||||
.W(W)
|
||||
) u_sub (
|
||||
.clk(clk),
|
||||
.data_in(d)
|
||||
);
|
||||
endmodule
|
||||
",
|
||||
),
|
||||
(
|
||||
"lowrisc",
|
||||
"\
|
||||
module top #(
|
||||
parameter int W = 8
|
||||
) (
|
||||
input logic clk,
|
||||
input logic [W-1:0] d,
|
||||
output logic [W-1:0] q
|
||||
);
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
always_ff @(posedge clk) begin
|
||||
if (d == 0) begin
|
||||
q <= '0;
|
||||
end else begin
|
||||
q <= d;
|
||||
end
|
||||
end
|
||||
sub #(
|
||||
.W(W)
|
||||
) u_sub (
|
||||
.clk (clk),
|
||||
.data_in (d)
|
||||
);
|
||||
endmodule
|
||||
",
|
||||
),
|
||||
(
|
||||
"ansi",
|
||||
"\
|
||||
module top #(
|
||||
parameter int W = 8
|
||||
) (input logic clk, input logic [W-1:0] d, output logic [W-1:0] q);
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
always_ff @(posedge clk)
|
||||
begin
|
||||
if (d == 0)
|
||||
begin
|
||||
q <= '0;
|
||||
end
|
||||
else
|
||||
begin
|
||||
q <= d;
|
||||
end
|
||||
end
|
||||
sub #(.W(W)) u_sub (.clk(clk), .data_in(d));
|
||||
endmodule
|
||||
",
|
||||
),
|
||||
(
|
||||
"microsoft",
|
||||
"\
|
||||
module top #(
|
||||
parameter int W = 8
|
||||
) (
|
||||
input logic clk,
|
||||
input logic [W-1:0] d,
|
||||
output logic [W-1:0] q
|
||||
);
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
always_ff @(posedge clk)
|
||||
begin
|
||||
if (d == 0)
|
||||
begin
|
||||
q <= '0;
|
||||
end
|
||||
else
|
||||
begin
|
||||
q <= d;
|
||||
end
|
||||
end
|
||||
sub #(
|
||||
.W(W)
|
||||
) u_sub (
|
||||
.clk(clk),
|
||||
.data_in(d)
|
||||
);
|
||||
endmodule
|
||||
",
|
||||
),
|
||||
(
|
||||
"nxp",
|
||||
"\
|
||||
module top #(
|
||||
parameter int W = 8
|
||||
) (
|
||||
input logic clk,
|
||||
input logic [W-1:0] d,
|
||||
output logic [W-1:0] q
|
||||
);
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
always_ff @(posedge clk) begin
|
||||
if (d == 0) begin
|
||||
q <= '0;
|
||||
end
|
||||
else begin
|
||||
q <= d;
|
||||
end
|
||||
end
|
||||
sub #(
|
||||
.W(W)
|
||||
) u_sub (
|
||||
.clk (clk),
|
||||
.data_in (d)
|
||||
);
|
||||
endmodule
|
||||
",
|
||||
),
|
||||
];
|
||||
assert_eq!(expected.len(), style::PRESETS.len());
|
||||
for (name, want) in expected {
|
||||
let preset = style::preset(name).expect("a preset");
|
||||
assert_eq!(format(SAMPLE, preset), want, "preset `{name}`");
|
||||
}
|
||||
}
|
||||
|
||||
/// Formatting with A, then B, then A again lands where A alone did, for
|
||||
/// every pair — except where A *reads* the source's spacing (`Infer`) and B
|
||||
/// wrote columns into it, which A then faithfully keeps.
|
||||
#[test]
|
||||
fn a_round_trip_through_another_preset_comes_back() {
|
||||
for a in style::PRESETS {
|
||||
let once = format(SAMPLE, a);
|
||||
for b in style::PRESETS {
|
||||
let back = format(&format(&once, b), a);
|
||||
if a.alignment == Alignment::Infer && b.alignment == Alignment::Always {
|
||||
// The columns B wrote are now the author's; A keeps them.
|
||||
assert_eq!(back, format(&format(SAMPLE, b), a), "{} via {}", a.name, b.name);
|
||||
} else {
|
||||
assert_eq!(back, once, "{} via {}", a.name, b.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `--lines` and an editor selection lay their constructs out in the style
|
||||
/// and leave every other byte exactly as written.
|
||||
#[test]
|
||||
fn range_and_selection_formatting_follow_the_style() {
|
||||
let src = "\
|
||||
module m;
|
||||
always_comb if (a) begin x = 1; end
|
||||
always_comb if (b) begin y = 1; end
|
||||
endmodule
|
||||
";
|
||||
let ansi = Config::styled(style::ANSI);
|
||||
let lines = LineRanges::parse("2").expect("a range");
|
||||
let want = "\
|
||||
module m;
|
||||
always_comb
|
||||
if (a)
|
||||
begin
|
||||
x = 1;
|
||||
end
|
||||
always_comb if (b) begin y = 1; end
|
||||
endmodule
|
||||
";
|
||||
assert_eq!(format_range(src, &ansi, &lines).expect("formats"), want);
|
||||
let selected = format_selection(src, &ansi, &lines).expect("formats");
|
||||
assert!(selected.contains("\n always_comb\n if (a)\n begin\n"), "{selected}");
|
||||
assert!(selected.ends_with(" always_comb if (b) begin y = 1; end\nendmodule\n"), "{selected}");
|
||||
}
|
||||
|
||||
fn auto() -> Config {
|
||||
Config::named("auto").expect("auto is a style")
|
||||
}
|
||||
|
||||
fn format_auto(src: &str) -> String {
|
||||
let out = format_source(src, &auto()).expect("formats");
|
||||
assert_eq!(format_source(&out, &auto()).expect("formats again"), out, "auto is idempotent");
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_keeps_each_file_in_the_layout_it_already_has() {
|
||||
// Written Allman: auto keeps `begin` and `else` on their own lines...
|
||||
let allman = "\
|
||||
module m;
|
||||
always_comb
|
||||
if (a)
|
||||
begin
|
||||
x = 1;
|
||||
end
|
||||
else
|
||||
begin
|
||||
x = 2;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
assert_eq!(format_auto(allman), allman);
|
||||
assert_eq!(resolve_style(allman, &auto()).style.begin, Placement::OwnLine);
|
||||
// ...and cuddled stays cuddled, which is also what the default does.
|
||||
let cuddled = format(allman, style::LUCISV);
|
||||
assert_eq!(format_auto(&cuddled), cuddled);
|
||||
assert_eq!(resolve_style(&cuddled, &auto()).style, style::LUCISV);
|
||||
// A messy file moves to the nearest preset, not to an arbitrary one.
|
||||
let messy = "module m;\n always_comb\n if (a)\n begin x = 1; end\n else\n begin x = 2; end\nendmodule\n";
|
||||
assert_eq!(format_auto(messy), allman);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_picks_a_layout_never_a_size() {
|
||||
// An Allman file at 4 spaces keeps auto's 2: indent is the config's, and
|
||||
// auto only ever picks among layouts at that indent.
|
||||
let wide = format(BRANCHES, style::ANSI);
|
||||
let chosen = resolve_style(&wide, &auto());
|
||||
assert_eq!((chosen.indent_width, chosen.max_width), (2, 100));
|
||||
let four = Config { indent_width: 4, ..auto() };
|
||||
assert_eq!(resolve_style(&wide, &four).style.begin, Placement::OwnLine);
|
||||
let out = format_source(&wide, &four).expect("formats");
|
||||
assert_eq!(out, wide, "with indent 4 configured, the ansi file is already formatted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_with_nothing_to_tell_the_presets_apart_is_the_default() {
|
||||
let plain = "module m;\n assign a = b;\nendmodule\n";
|
||||
assert_eq!(format_auto(plain), plain);
|
||||
assert_eq!(resolve_style(plain, &auto()).style, style::LUCISV);
|
||||
assert_eq!(auto().style_name(), "auto");
|
||||
assert!(!resolve_style(plain, &auto()).auto_style);
|
||||
}
|
||||
|
||||
/// A range under auto lays its lines out in the style of the whole file, so
|
||||
/// a selection in an Allman file comes out Allman even when the selected
|
||||
/// lines themselves were written cuddled.
|
||||
#[test]
|
||||
fn auto_ranges_take_the_whole_files_style() {
|
||||
let src = "\
|
||||
module m;
|
||||
always_comb
|
||||
begin
|
||||
if (a)
|
||||
begin
|
||||
x = 1;
|
||||
end
|
||||
else
|
||||
begin
|
||||
x = 2;
|
||||
end
|
||||
end
|
||||
always_comb if (b) begin y = 1; end
|
||||
endmodule
|
||||
";
|
||||
let lines = LineRanges::parse("13").expect("a range");
|
||||
let out = format_range(src, &auto(), &lines).expect("formats");
|
||||
assert!(
|
||||
out.ends_with(" always_comb\n if (b)\n begin\n y = 1;\n end\nendmodule\n"),
|
||||
"{out}"
|
||||
);
|
||||
let selected = format_selection(src, &auto(), &lines).expect("formats");
|
||||
assert_eq!(selected, out);
|
||||
}
|
||||
|
||||
/// Google's "Eschatology" and lowRISC's "Begin / End": `end else begin` on
|
||||
/// one line, except after a labelled `end`, where `else` starts a new line.
|
||||
#[test]
|
||||
fn else_after_a_labelled_end_starts_its_own_line_in_the_guides() {
|
||||
let src = "\
|
||||
module m;
|
||||
always_comb
|
||||
if (a) begin : l1
|
||||
x = 1;
|
||||
end : l1 else begin
|
||||
x = 2;
|
||||
end
|
||||
if (G) begin : g1
|
||||
assign z = 1;
|
||||
end : g1 else begin : g2
|
||||
assign z = 0;
|
||||
end : g2
|
||||
endmodule
|
||||
";
|
||||
let guide = "\
|
||||
module m;
|
||||
always_comb
|
||||
if (a) begin : l1
|
||||
x = 1;
|
||||
end : l1
|
||||
else begin
|
||||
x = 2;
|
||||
end
|
||||
if (G) begin : g1
|
||||
assign z = 1;
|
||||
end : g1
|
||||
else begin : g2
|
||||
assign z = 0;
|
||||
end : g2
|
||||
endmodule
|
||||
";
|
||||
assert_eq!(format(src, style::GOOGLE), guide);
|
||||
assert_eq!(format(src, style::LOWRISC), guide);
|
||||
// The default keeps what it always printed.
|
||||
assert_eq!(format(src, style::LUCISV), src);
|
||||
// And an unlabelled `end` still cuddles in the guides.
|
||||
let plain = format(BRANCHES, style::GOOGLE);
|
||||
assert!(plain.contains(" end else if (b) begin\n"), "{plain}");
|
||||
}
|
||||
@@ -320,12 +320,13 @@ impl<'a> Parser<'a> {
|
||||
if !self.cur().is_sym(")") {
|
||||
loop {
|
||||
let at = self.pos;
|
||||
list.push(self.element_or_recover(|p| p.parse_connection())?);
|
||||
list.push(self.connection_or_recover()?);
|
||||
let recovered = list.last().is_some_and(ListElem::is_error);
|
||||
if let Some(ListElem::Ok(last)) = list.last_mut() {
|
||||
self.take_before_sep(&mut last.meta, ",");
|
||||
}
|
||||
let comma = self.eat_sym(",");
|
||||
self.note_trailing_comma(comma);
|
||||
if let Some(ListElem::Ok(last)) = list.last_mut() {
|
||||
last.comma = comma;
|
||||
if comma && last.meta.trailing.is_none() {
|
||||
@@ -338,7 +339,7 @@ impl<'a> Parser<'a> {
|
||||
// the list, and after a directive only the closing bracket
|
||||
// does — an `` `ifdef`` arm may end without a comma and
|
||||
// still be followed by an `` `else`` arm.
|
||||
if self.list_ends(at, comma, dirs.any, recovered) {
|
||||
if self.connection_list_ends(at, comma, dirs.any, recovered) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -437,12 +438,13 @@ impl<'a> Parser<'a> {
|
||||
let mut conns = Vec::new();
|
||||
loop {
|
||||
let at = self.pos;
|
||||
conns.push(self.element_or_recover(|p| p.parse_connection())?);
|
||||
conns.push(self.connection_or_recover()?);
|
||||
let recovered = conns.last().is_some_and(ListElem::is_error);
|
||||
if let Some(ListElem::Ok(last)) = conns.last_mut() {
|
||||
self.take_before_sep(&mut last.meta, ",");
|
||||
}
|
||||
let comma = self.eat_sym(",");
|
||||
self.note_trailing_comma(comma);
|
||||
if let Some(ListElem::Ok(last)) = conns.last_mut() {
|
||||
last.comma = comma;
|
||||
if comma && last.meta.trailing.is_none() {
|
||||
@@ -450,7 +452,7 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
let dirs = self.take_list_directives(directives, conns.len());
|
||||
if self.list_ends(at, comma, dirs.any, recovered) {
|
||||
if self.connection_list_ends(at, comma, dirs.any, recovered) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -560,8 +562,15 @@ impl<'a> Parser<'a> {
|
||||
// arguments — so the greedy parse swallows the instance and the
|
||||
// whole instantiation collapses into one error item. Failing the
|
||||
// element here costs the one connection and keeps everything
|
||||
// else. See `docs/features/small-items-3/README.md`.
|
||||
if self.tolerant && self.cur().is_sym("(") && self.value_runs_into_next_instance() {
|
||||
// else. See `docs/features/small-items-3/README.md`. The same
|
||||
// failure covers a `.NAME(` left open at the end of its line while
|
||||
// the next line goes on with the list (`.po(` ⏎ `.b(y));`): the
|
||||
// entry ends with its line, and the diagnostic is on its `(`
|
||||
// (`docs/features/port-entry-grace/README.md`).
|
||||
if self.tolerant
|
||||
&& self.cur().is_sym("(")
|
||||
&& (self.value_runs_into_next_instance() || self.value_left_open())
|
||||
{
|
||||
return self.error("unclosed `(` in a port or parameter connection");
|
||||
}
|
||||
let mut close_comments = Vec::new();
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
//! See `docs/features/header-recovery/README.md`.
|
||||
|
||||
use super::directive::{closes_conditional, continues_conditional, opens_conditional};
|
||||
use super::recover::is_sync_stop;
|
||||
use super::*;
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
@@ -102,6 +103,176 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// One entry of a port or parameter connection list, the unfinished ones
|
||||
/// included (`docs/features/port-entry-grace/README.md`).
|
||||
///
|
||||
/// A `.` with no name after it yet — `.a(x), .` ⏎ `.b(y)` — is the entry
|
||||
/// someone is typing. In tolerant mode it becomes an error element of its
|
||||
/// own, holding just the `.`, with its one diagnostic on the `.`: the
|
||||
/// generic recovery would report the token *after* it, which belongs to
|
||||
/// the next entry, and its skip would swallow a `.b(y)` written on the
|
||||
/// same line. Strict mode, and every other entry, is
|
||||
/// [`Parser::element_or_recover`] over [`Parser::parse_connection`].
|
||||
pub(super) fn connection_or_recover(&mut self) -> PResult<ListElem<Connection>> {
|
||||
if self.tolerant && self.at_lone_dot() {
|
||||
return Ok(ListElem::Error(self.take_lone_dot()));
|
||||
}
|
||||
self.element_or_recover(|p| p.parse_connection())
|
||||
}
|
||||
|
||||
/// True on a `.` that no name can follow: the next token ends the entry
|
||||
/// (`,` `)` `;`), ends the file or an enclosing construct, or — on a later
|
||||
/// line — is a keyword or the `.` of the next entry. A keyword or a `.` on
|
||||
/// the same line (`.input(x)`, `..z (p)`) is left to the generic recovery,
|
||||
/// whose skip takes the whole `.input(x)` / `..z (p)` with it: one error
|
||||
/// element, which is what `lucisv_mcp`'s refusal names (`qa_f1.rs`).
|
||||
fn at_lone_dot(&self) -> bool {
|
||||
if !self.cur().is_sym(".") {
|
||||
return false;
|
||||
}
|
||||
let next = self.nth(1);
|
||||
let later_line = next.line != self.cur().line;
|
||||
next.kind == TokenKind::Eof
|
||||
|| next.is_sym(",")
|
||||
|| next.is_sym(")")
|
||||
|| next.is_sym(";")
|
||||
|| is_sync_stop(next)
|
||||
|| (later_line && (next.kind == TokenKind::Keyword || next.is_sym(".")))
|
||||
}
|
||||
|
||||
/// Record the lone `.` at the cursor and take it as an error element.
|
||||
/// The comments written before it are left pending, so the next entry
|
||||
/// picks them up rather than the error leaf swallowing them.
|
||||
fn take_lone_dot(&mut self) -> RawText {
|
||||
let dot = self.cur();
|
||||
let (span, col) = (dot.span, dot.col);
|
||||
self.diagnostics.push(ParseDiagnostic {
|
||||
message: "expected a name after `.`".to_string(),
|
||||
line: dot.line,
|
||||
col,
|
||||
span,
|
||||
});
|
||||
self.skip();
|
||||
RawText { text: self.slice(span), col, span }
|
||||
}
|
||||
|
||||
/// [`Parser::list_ends`] for a connection list, which reads one shape on.
|
||||
///
|
||||
/// After an entry that had to be recovered, a missing `,` normally ends
|
||||
/// the list — what follows belongs to the enclosing construct. In a
|
||||
/// connection list a `.` there is the next connection instead: the entry
|
||||
/// above was abandoned mid-typing (`.po(` ⏎ `.b(y)`), and the list reads
|
||||
/// on. No second diagnostic: the recovered entry already has one, and it
|
||||
/// is the news. Strict mode never recovers, so this is `list_ends` there.
|
||||
pub(super) fn connection_list_ends(
|
||||
&mut self,
|
||||
start: usize,
|
||||
comma: bool,
|
||||
dirs_any: bool,
|
||||
recovered: bool,
|
||||
) -> bool {
|
||||
let next_entry = self.cur().is_sym(".");
|
||||
if self.tolerant && recovered && !comma && !dirs_any && self.pos != start && next_entry {
|
||||
return false;
|
||||
}
|
||||
self.list_ends(start, comma, dirs_any, recovered)
|
||||
}
|
||||
|
||||
/// In tolerant mode, report a connection list's `,` that only the closing
|
||||
/// `)` follows — `.b(y),)`, the separator typed before the next entry.
|
||||
/// Strict mode fails there on the empty entry; tolerant mode used to end
|
||||
/// the list on the `)` without a word. The diagnostic sits on the `,`.
|
||||
/// Called right after the `,` was consumed, so it is the token behind the
|
||||
/// cursor.
|
||||
pub(super) fn note_trailing_comma(&mut self, comma: bool) {
|
||||
if !(self.tolerant && comma && self.cur().is_sym(")")) {
|
||||
return;
|
||||
}
|
||||
let Some(sep) = self.pos.checked_sub(1).and_then(|i| self.tokens.get(i)) else { return };
|
||||
let diag = ParseDiagnostic {
|
||||
message: "expected a connection after `,`".to_string(),
|
||||
line: sep.line,
|
||||
col: sep.col,
|
||||
span: sep.span,
|
||||
};
|
||||
self.diagnostics.push(diag);
|
||||
}
|
||||
|
||||
/// True when the `(` at the cursor — the one that opens a connection's
|
||||
/// value — was left open mid-typing: still open at the end of its line,
|
||||
/// the next line starting something new (a `.` entry, a `)`, a `;`, a
|
||||
/// keyword, or end of file), **and** the bracket never closes the way a
|
||||
/// value's does.
|
||||
///
|
||||
/// The last clause is what keeps every file the strict parser reads
|
||||
/// untouched: in a valid list a value's matching `)` is followed by a
|
||||
/// `,`, the list's `)`, or a directive, so `.po(top` ⏎ `.sig)` — a legal
|
||||
/// path continued on the next line — is read as written. The line clause
|
||||
/// keeps the pinned ambiguous shape `.D(` ⏎ `u0 (.a(x)));` greedy
|
||||
/// (`docs/features/header-recovery/README.md`): an identifier opening the
|
||||
/// next line is [`Parser::value_runs_into_next_instance`]'s question.
|
||||
/// Tolerant mode only; the walk ends at the first `;` or construct keyword
|
||||
/// outside the value, so it is bounded by the item.
|
||||
pub(super) fn value_left_open(&self) -> bool {
|
||||
let open = self.pos;
|
||||
let line = self.cur().line;
|
||||
let mut depth = 0u32;
|
||||
let mut i = open + 1;
|
||||
while let Some(t) = self.tokens.get(i) {
|
||||
if t.line != line || t.kind == TokenKind::Eof {
|
||||
break;
|
||||
}
|
||||
if is_open_bracket(t) {
|
||||
depth += 1;
|
||||
} else if is_close_bracket(t) {
|
||||
if depth == 0 {
|
||||
return false;
|
||||
}
|
||||
depth -= 1;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
let Some(next) = self.tokens.get(i) else { return false };
|
||||
let starts_new = next.kind == TokenKind::Eof
|
||||
|| next.kind == TokenKind::Keyword
|
||||
|| next.is_sym(".")
|
||||
|| next.is_sym(")")
|
||||
|| next.is_sym(";");
|
||||
starts_new && !self.value_closes(open)
|
||||
}
|
||||
|
||||
/// Whether the bracket at token `open` is closed by a `)` that a valid
|
||||
/// connection list could have written next: anything but a `;`, end of
|
||||
/// file, a construct keyword, a `.` or a plain identifier after it. A
|
||||
/// `;` or construct keyword reached first, outside any bracket the value
|
||||
/// opened, means it is never closed at all.
|
||||
fn value_closes(&self, open: usize) -> bool {
|
||||
let mut depth = 0u32;
|
||||
let mut i = open + 1;
|
||||
while let Some(t) = self.tokens.get(i) {
|
||||
if t.kind == TokenKind::Eof {
|
||||
return false;
|
||||
}
|
||||
if is_open_bracket(t) {
|
||||
depth += 1;
|
||||
} else if is_close_bracket(t) {
|
||||
if depth == 0 {
|
||||
return self.tokens.get(i + 1).is_some_and(|after| !ends_a_value_badly(after));
|
||||
}
|
||||
depth -= 1;
|
||||
} else if depth == 0 && (t.is_sym(";") || is_sync_stop(t)) {
|
||||
return false;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// True on a token that opens a bracket.
|
||||
fn at_open_bracket(&self) -> bool {
|
||||
is_open_bracket(self.cur())
|
||||
}
|
||||
|
||||
/// True on a `` `ifdef `` / `` `ifndef `` / `` `else `` / `` `elsif `` /
|
||||
/// `` `endif ``: a directive that opens, continues or closes a
|
||||
/// conditional-compilation region.
|
||||
@@ -267,12 +438,6 @@ impl<'a> Parser<'a> {
|
||||
RawText { text: self.slice(span), col, span }
|
||||
}
|
||||
|
||||
/// True on a token that opens a bracket.
|
||||
fn at_open_bracket(&self) -> bool {
|
||||
let t = self.cur();
|
||||
t.is_sym("(") || t.is_sym("[") || t.is_sym("{")
|
||||
}
|
||||
|
||||
/// The extent a recovery covers: from `start` through the last token it
|
||||
/// took, or the empty range at `start` when it took none (the sync point
|
||||
/// was already under the cursor).
|
||||
@@ -340,3 +505,25 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// True on a `(`, `[` or `{`.
|
||||
fn is_open_bracket(t: &Token) -> bool {
|
||||
t.is_sym("(") || t.is_sym("[") || t.is_sym("{")
|
||||
}
|
||||
|
||||
/// True on a `)`, `]` or `}`.
|
||||
fn is_close_bracket(t: &Token) -> bool {
|
||||
t.is_sym(")") || t.is_sym("]") || t.is_sym("}")
|
||||
}
|
||||
|
||||
/// True on a token no valid connection list writes right after a value's
|
||||
/// closing `)`: the list was never closed (`;`, end of file, a construct
|
||||
/// keyword), or the next connection follows with no `,` (`.`, or a plain
|
||||
/// identifier — a macro invocation is a directive's business and allowed).
|
||||
fn ends_a_value_badly(t: &Token) -> bool {
|
||||
t.kind == TokenKind::Eof
|
||||
|| t.is_sym(";")
|
||||
|| t.is_sym(".")
|
||||
|| is_sync_stop(t)
|
||||
|| (t.kind == TokenKind::Ident && !t.is_macro())
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
//! An unfinished connection stays inside its own entry (TODO §68.2,
|
||||
//! `docs/features/port-entry-grace/README.md`).
|
||||
//!
|
||||
//! The four shapes someone typing a named connection leaves behind — a lone
|
||||
//! `.`, a `.name(` still open at the end of its line, a missing `,` between
|
||||
//! two entries, a `,` with only the `)` after it — each cost exactly one
|
||||
//! diagnostic, whose span lies inside the unfinished entry (or on the single
|
||||
//! token that proves it), and every other entry, the instance and the rest of
|
||||
//! the file parse as if the entry were complete. The strict parser refuses
|
||||
//! every one of them, as before; and no valid spelling of a list reads
|
||||
//! differently in tolerant mode.
|
||||
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::{parse_source, parse_source_tolerant, ParseDiagnostic};
|
||||
|
||||
/// The file's one module. Panics unless the file is exactly one module — the
|
||||
/// shapes below must never cost the module.
|
||||
fn the_module(file: &SourceFile) -> &Module {
|
||||
assert_eq!(file.items.len(), 1, "the file is still one item: {:?}", file.items);
|
||||
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected module m") };
|
||||
m
|
||||
}
|
||||
|
||||
/// The instantiations among `m`'s items, and how many items are anything
|
||||
/// else (error items included).
|
||||
fn instantiations(m: &Module) -> (Vec<&Instantiation>, usize) {
|
||||
let mut insts = Vec::new();
|
||||
let mut others = 0;
|
||||
for item in &m.items {
|
||||
match &item.kind {
|
||||
ItemKind::Instantiation(inst) => insts.push(inst),
|
||||
ItemKind::Error(raw) => panic!("an error item escaped the list: {:?}", raw.text),
|
||||
_ => others += 1,
|
||||
}
|
||||
}
|
||||
(insts, others)
|
||||
}
|
||||
|
||||
/// One entry, as the tests compare it: `Ok(name)` or `Err(raw text)`.
|
||||
fn entries(list: &[ListElem<Connection>]) -> Vec<Result<&str, &str>> {
|
||||
list.iter()
|
||||
.map(|e| match e {
|
||||
ListElem::Ok(c) => Ok(c.name.as_str()),
|
||||
ListElem::Error(raw) => Err(raw.text.as_str()),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The named connections of the first instance of the first instantiation.
|
||||
fn ports(m: &Module) -> Vec<Result<&str, &str>> {
|
||||
let (insts, _) = instantiations(m);
|
||||
let Connections::Named(conns) = &insts[0].instances[0].conns else { panic!("named list") };
|
||||
entries(conns)
|
||||
}
|
||||
|
||||
/// The one diagnostic `src` produces, and the source text its span covers.
|
||||
fn one_diag(src: &str, diags: &[ParseDiagnostic]) -> (String, String) {
|
||||
assert_eq!(diags.len(), 1, "exactly one diagnostic: {diags:?}");
|
||||
(diags[0].message.clone(), src[diags[0].span.as_range()].to_string())
|
||||
}
|
||||
|
||||
/// The strict parser — the formatter's — still refuses `src`.
|
||||
fn strict_refuses(src: &str) {
|
||||
assert!(parse_source(src).is_err(), "strict mode must still refuse:\n{src}");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// (a) a lone `.`
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_lone_dot_on_its_own_line_keeps_the_entries_after_it() {
|
||||
let src = "module m;\n sub u0 (.a(x),\n .\n .b(y));\n wire w;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
let (message, at) = one_diag(src, &diags);
|
||||
assert_eq!(at, ".", "on the dot itself, not on the `.b` after it");
|
||||
assert_eq!(message, "expected a name after `.`");
|
||||
assert_eq!(ports(m), [Ok("a"), Err("."), Ok("b")]);
|
||||
assert_eq!(instantiations(m).1, 1, "`wire w;` is still an item of the module");
|
||||
strict_refuses(src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lone_dot_before_a_comma_or_the_close() {
|
||||
for (src, want) in [
|
||||
("module m;\n sub u0 (.a(x), ., .b(y));\nendmodule\n", vec![Ok("a"), Err("."), Ok("b")]),
|
||||
("module m;\n sub u0 (.a(x), .);\nendmodule\n", vec![Ok("a"), Err(".")]),
|
||||
("module m;\n sub u0 (.);\nendmodule\n", vec![Err(".")]),
|
||||
] {
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
assert_eq!(one_diag(src, &diags).1, ".", "{src}");
|
||||
assert_eq!(ports(m), want, "{src}");
|
||||
strict_refuses(src);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lone_dot_in_a_parameter_override_list() {
|
||||
let src = "module m;\n sub #(.W(8), .\n .D(2)) u0 (.a(x));\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
assert_eq!(one_diag(src, &diags).1, ".");
|
||||
let (insts, _) = instantiations(m);
|
||||
assert_eq!(entries(insts[0].params.as_ref().expect("overrides")), [Ok("W"), Err("."), Ok("D")]);
|
||||
assert_eq!(insts[0].instances[0].name, "u0");
|
||||
strict_refuses(src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lone_dot_at_the_end_of_the_file_keeps_the_instance() {
|
||||
let src = "module m;\n sub u0 (.a(x), .\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
assert_eq!(one_diag(src, &diags).1, ".");
|
||||
assert_eq!(ports(m), [Ok("a"), Err(".")]);
|
||||
strict_refuses(src);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// (b) `.name(` still open at the end of its line
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_open_value_followed_by_the_next_entry_ends_with_its_line() {
|
||||
for (src, raw) in [
|
||||
("module m;\n sub u0 (.a(x), .po(\n .b(y));\n wire w;\nendmodule\n", ".po("),
|
||||
("module m;\n sub u0 (.a(x), .po(z\n .b(y));\n wire w;\nendmodule\n", ".po(z"),
|
||||
("module m;\n sub u0 (.a(x),\n .po(\n .b(y),\n .c(z)\n );\n wire w;\nendmodule\n", ".po("),
|
||||
] {
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
let (message, at) = one_diag(src, &diags);
|
||||
assert_eq!(at, "(", "on the entry's own `(`: {src}");
|
||||
assert!(message.starts_with("unclosed `(`"), "{message}");
|
||||
let got = ports(m);
|
||||
assert_eq!(got[0], Ok("a"));
|
||||
assert_eq!(got[1], Err(raw), "{src}");
|
||||
assert_eq!(got[2], Ok("b"), "the entry after it survives: {src}");
|
||||
assert_eq!(instantiations(m).1, 1, "`wire w;` is an item: {src}");
|
||||
strict_refuses(src);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_value_followed_by_the_lists_close() {
|
||||
let src = "module m;\n sub u0 (.a(x), .po(\n );\n wire w;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
assert_eq!(one_diag(src, &diags).1, "(");
|
||||
assert_eq!(ports(m), [Ok("a"), Err(".po(")]);
|
||||
assert_eq!(instantiations(m).1, 1);
|
||||
strict_refuses(src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_value_at_the_end_of_the_module() {
|
||||
let src = "module m;\n sub u0 (.a(x), .po(\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
assert_eq!(one_diag(src, &diags).1, "(");
|
||||
assert_eq!(ports(m), [Ok("a"), Err(".po(")]);
|
||||
strict_refuses(src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_override_value_keeps_the_overrides_after_it_and_the_instance() {
|
||||
let src = "module m;\n sub #(.W(8), .D(\n .E(1)) u0 (.a(x));\n wire w;\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
assert_eq!(one_diag(src, &diags).1, "(");
|
||||
let (insts, others) = instantiations(m);
|
||||
assert_eq!(
|
||||
entries(insts[0].params.as_ref().expect("overrides")),
|
||||
[Ok("W"), Err(".D("), Ok("E")]
|
||||
);
|
||||
assert_eq!(insts[0].instances[0].name, "u0");
|
||||
assert_eq!(others, 1);
|
||||
strict_refuses(src);
|
||||
}
|
||||
|
||||
/// The two pinned shapes of `error_recovery.rs` keep their old answers: an
|
||||
/// identifier opening the next line is the next-instance lookahead's, and
|
||||
/// the balanced `.D(` ⏎ `u0 (.a(x)));` stays ambiguous and greedy.
|
||||
#[test]
|
||||
fn an_identifier_on_the_next_line_is_not_this_rule() {
|
||||
let src = "module m;\n sub #(.D(\n u0 (.a(x)));\nendmodule\n";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert!(diags.iter().all(|d| !d.message.contains("unclosed")), "{diags:?}");
|
||||
let ItemKind::Module(m) = &file.items[0].kind else { panic!("module") };
|
||||
assert!(matches!(m.items[0].kind, ItemKind::Error(_)), "still one error item");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// (c) a missing `,` between two entries
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_missing_comma_keeps_both_entries() {
|
||||
for src in [
|
||||
"module m;\n sub u0 (.a(x)\n .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x) .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po\n .b(y));\nendmodule\n",
|
||||
] {
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
let (message, at) = one_diag(src, &diags);
|
||||
assert!(message.starts_with("expected `,`"), "{message}");
|
||||
assert_eq!(at, ".", "on the `.` that proves the comma missing: {src}");
|
||||
assert!(ports(m).iter().all(Result::is_ok), "{:?}", ports(m));
|
||||
assert_eq!(ports(m).last(), Some(&Ok("b")));
|
||||
strict_refuses(src);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// (d) a trailing `,`
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_trailing_comma_is_reported_on_the_comma() {
|
||||
for src in [
|
||||
"module m;\n sub u0 (.a(x), .b(y),);\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .b(y),\n );\nendmodule\n",
|
||||
"module m;\n sub #(.W(1),) u0 (.a(x));\nendmodule\n",
|
||||
"module m;\n sub #(1,) u0 (.a(x));\nendmodule\n",
|
||||
] {
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
let (message, at) = one_diag(src, &diags);
|
||||
assert_eq!(at, ",", "{src}");
|
||||
assert_eq!(message, "expected a connection after `,`");
|
||||
assert_eq!(instantiations(m).0.len(), 1);
|
||||
strict_refuses(src);
|
||||
}
|
||||
}
|
||||
|
||||
/// A positional list may end in an omitted connection — `u (a, b,)` is legal
|
||||
/// — so the trailing-comma report is a named-list and override-list rule only.
|
||||
#[test]
|
||||
fn a_positional_lists_trailing_comma_is_still_legal() {
|
||||
let src = "module m;\n sub u0 (a, b,);\nendmodule\n";
|
||||
assert!(parse_source(src).is_ok());
|
||||
assert!(parse_source_tolerant(src).1.is_empty());
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Valid input is untouched
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// Spellings that come close to every shape above and are legal: each parses
|
||||
/// strictly, reports nothing tolerantly, and builds the identical tree.
|
||||
#[test]
|
||||
fn valid_lists_read_the_same_in_both_modes() {
|
||||
for src in [
|
||||
// A path continued on the next line: `(` open at the line's end and a
|
||||
// `.` opening the next — the one valid shape rule (b) has to leave be.
|
||||
"module m;\n sub u0 (.a(x),\n .po(top\n .sig), .q(r));\nendmodule\n",
|
||||
"module m;\n sub u0 (.po(top\n .sig));\nendmodule\n",
|
||||
// A value written over several lines, its `)` alone on the last one.
|
||||
"module m;\n sub u0 (.po(\n x\n ), .q(r));\nendmodule\n",
|
||||
"module m;\n sub u0 (.po(f(x\n )));\nendmodule\n",
|
||||
"module m;\n sub #(.DEPTH(\n f(1)\n )) u0 (.a(x));\nendmodule\n",
|
||||
// The implicit `.name` form, a `.*`, an empty `.name()`.
|
||||
"module m;\n sub u0 (.a,\n .b(),\n .*);\nendmodule\n",
|
||||
// A directive between entries and a macro after a value.
|
||||
"module m;\n sub u0 (.a(x),\n`ifdef B\n .b(y),\n`endif\n .c(z));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x) `COMMA_B\n );\nendmodule\n",
|
||||
// Attributes on an entry.
|
||||
"module m;\n sub u0 ((* keep *) .a(x),\n (* keep *)\n .b(y));\nendmodule\n",
|
||||
] {
|
||||
let strict = match parse_source(src) {
|
||||
Ok(tree) => tree,
|
||||
Err(e) => panic!("premise: {src:?} is valid, got {e}"),
|
||||
};
|
||||
let (tolerant, diags) = parse_source_tolerant(src);
|
||||
assert!(diags.is_empty(), "{src}: {diags:?}");
|
||||
assert_eq!(format!("{strict:?}"), format!("{tolerant:?}"), "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A `.` followed by another `.` on the same line is not a lone dot: the
|
||||
/// generic recovery keeps `..z (p)` as one error element, whose text is what
|
||||
/// a refusal downstream names (`lucisv_mcp`'s `qa_f1.rs`).
|
||||
#[test]
|
||||
fn two_dots_on_one_line_stay_one_error_element() {
|
||||
for (src, want) in [
|
||||
("module m;\n sub u0 (.a(x), ..z (p));\nendmodule\n", vec![Ok("a"), Err("..z (p)")]),
|
||||
("module m;\n sub u0 (.a(x), . .b(y));\nendmodule\n", vec![Ok("a"), Err(". .b(y)")]),
|
||||
] {
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
let m = the_module(&file);
|
||||
assert_eq!(diags.len(), 1, "{src}: {diags:?}");
|
||||
assert_eq!(ports(m), want, "{src}");
|
||||
strict_refuses(src);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
//! QA, TODO §68.2 (`docs/features/port-entry-grace/README.md`): the tolerant
|
||||
//! parser's new connection-list recovery against a wider sweep than the dev's
|
||||
//! own tests — multi-line connection values that are legal (each must read
|
||||
//! exactly as the strict parser reads it, with no diagnostic) and unfinished
|
||||
//! entries in every position QA could think of (each must stay refused by the
|
||||
//! strict parser and cost at least one tolerant diagnostic, none of them
|
||||
//! outside the source).
|
||||
|
||||
use vlog_parser::{parse_source, parse_source_tolerant};
|
||||
|
||||
/// Legal multi-line connections: an operand on the line after `(`, a
|
||||
/// keyword-led operand, a macro, a comment line, a dotted name, overrides,
|
||||
/// `.*`, attributes, generate loops, instance arrays, gates, `bind`, UDPs,
|
||||
/// conditional compilation.
|
||||
const VALID: &[&str] = &[
|
||||
"module m;\n sub u0 (.a(\n foo\n ), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a({\n x, y\n }), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x ?\n y : z), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n signed'(x)), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n this.x), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n null), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n super.x), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n $bits(x)), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n `MACRO(x)), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n // comment\n x), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n intf.sig), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(intf\n .sig), .b(y));\nendmodule\n",
|
||||
"module m;\n sub #(.W(\n 8)) u0 (.a(x));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x)\n );\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n ));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .*);\nendmodule\n",
|
||||
"module m;\n sub u0 ((* keep *) .a(\n x), .b(y));\nendmodule\n",
|
||||
"module m;\n for (genvar i = 0; i < 4; i++) begin : g\n sub u (.a(\n x[i]), .b(y));\n end\nendmodule\n",
|
||||
"module m;\n sub u [3:0] (.a(\n x), .b(y));\nendmodule\n",
|
||||
"module m;\n and g1 (o,\n a, b);\nendmodule\n",
|
||||
"module m;\n bind sub chk u_chk (.a(\n x), .b(y));\nendmodule\n",
|
||||
"module m;\n intf u_if (.clk(\n clk));\n prog u_p (.a(\n x));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x)\n`ifdef FOO\n , .b(y)\n`endif\n );\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x)\n `ifdef FOO , .b(y) `endif\n );\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x[\n 3:0]), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(f(\n x)), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x\n ), .b(\n y\n ));\nendmodule\n",
|
||||
"module m;\n sub u0 (x,\n y, z);\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n new));\nendmodule\n",
|
||||
"module m;\n sub #(\n .W(8),\n .T(\n logic [3:0])\n ) u0 (.a(x));\nendmodule\n",
|
||||
"module m;\n sub #(.T(\n int)) u0 (.a(x));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n 1'b0), .b(\n '0));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n {8{1'b0}}), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x)) ;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x)), u1 (.a(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x)) /* c */;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x)\n // trailing\n );\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n std::randomize(x)), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x inside {1, 2}), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n pkg::x), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n (x)), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n ), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n\n x), .b(y));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x\n ), .b(y\n ));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .b(\n y\n )\n );\n sub u1 (.a(x));\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x)\n `ifdef FOO\n ,.b(y)\n `endif\n );\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x));\n checker_t c0 (.a(\n x));\nendmodule\n",
|
||||
"module m;\n myudp u (out,\n in1, in2);\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x), .b(y)); sub u1 (.a(\n x));\nendmodule\n",
|
||||
"module m;\n sub #(\n .A(\n 1\n )\n ) u0 ();\nendmodule\n",
|
||||
// Not here: "sub #(8,\n 16) u0 (x,\n y,);" — a positional list's
|
||||
// trailing omitted connection. Strict keeps it as an empty entry and
|
||||
// tolerant drops it, at c1076f9 already (QA log 2026-11-17, NOTE).
|
||||
"module m;\n sub #(8,\n 16) u0 (x,\n y, z);\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(\n x)\n ) ;\nendmodule\nmodule n;\nendmodule\n",
|
||||
];
|
||||
|
||||
/// Unfinished entries: first, last, only, repeated, at end of file, in `#(`,
|
||||
/// in generate and `` `ifdef `` regions, with nested open brackets, a comma
|
||||
/// inside an open value, trailing commas, keywords after the `(`.
|
||||
const UNFINISHED: &[&str] = &[
|
||||
"module m;\n sub u0 (.\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .);\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.);\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .\n .\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .pq(\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .",
|
||||
"module m;\n sub u0 (.a(x),\n .po(",
|
||||
"module m;\n sub #(.W(\n .D(1)) u0 (.a(x));\n wire w;\nendmodule\n",
|
||||
"module m;\n generate if (1) begin : g\n sub u0 (.a(x),\n .po(\n .b(y));\n end endgenerate\n wire w;\nendmodule\n",
|
||||
"module m;\n`ifdef FOO\n sub u0 (.a(x),\n .po(\n .b(y));\n`endif\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(f(\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(x[\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po({\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(a,\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .\n );\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),",
|
||||
"module m;\n sub u0 (.a(x), .b(y),\n );\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),,.b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x) .b(y) .c(z));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.po(\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n );\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\nendmodule\nmodule n;\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .b(y)\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .b(y),\n .c(\n .d(z));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po(z\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po(z)\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po(\n );\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po(\n ;\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .input(\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .\n input w2;\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po(\n u1 (.a(x)));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po((\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .b(y)), u1 (.a(x));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .b(y)) /*c*/;\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), // c1\n . // c2\n .b(y)); // c3\n wire w;\nendmodule\n",
|
||||
"module m;\n sub #(.W(1),) u0 (.a(x),);\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n`ifdef X\n .b(y)\n`endif\n );\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .b(y))\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .b(y)) .c(z);\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .b(y)) foo;\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .b(y)) `M;\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po(\n .b(y)), .c(z));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .b(\n .c(\n .d(\n .e(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .\n .\n .\n .\n .\n .\n .\n .\n .\n .\n .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po(\n endmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po(\n end\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x), .po( .b(y));\n wire w;\nendmodule\n",
|
||||
"module m;\n sub u0 (.a(x),\n .po(\n .b(y));\n sub u1 (.a(x),\n .\n .b(y));\n assign q = ;\nendmodule\n",
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn qa_legal_multi_line_connections_read_the_same_in_both_modes() {
|
||||
for src in VALID {
|
||||
let strict = match parse_source(src) {
|
||||
Ok(tree) => tree,
|
||||
Err(e) => panic!("premise: {src:?} is valid, got {e}"),
|
||||
};
|
||||
let (tolerant, diags) = parse_source_tolerant(src);
|
||||
assert!(diags.is_empty(), "{src}: {diags:?}");
|
||||
assert_eq!(format!("{strict:?}"), format!("{tolerant:?}"), "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_every_unfinished_entry_is_refused_strictly_and_reported_tolerantly() {
|
||||
for src in UNFINISHED {
|
||||
assert!(parse_source(src).is_err(), "strict mode must refuse:\n{src}");
|
||||
let (_, diags) = parse_source_tolerant(src);
|
||||
assert!(!diags.is_empty(), "never silent:\n{src}");
|
||||
let lines = src.lines().count();
|
||||
assert!(diags.len() <= lines, "no diagnostic explosion ({}):\n{src}", diags.len());
|
||||
for d in &diags {
|
||||
assert!(d.span.end as usize <= src.len(), "{d:?} outside the source:\n{src}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,630 @@
|
||||
# comment-highlighting
|
||||
|
||||
## Goal
|
||||
|
||||
The owner (TODO §71.8): "Sometimes there is syntax highlighting in the
|
||||
comment. Like a signal with bracket like signal[]. I saw the [] are getting
|
||||
highlighted. Not needed. But there is one thing that is needed: please
|
||||
highlight the TODO, FIXME, FIX_ME, TBD in the comment. Also give the user an
|
||||
option to highlight a custom word that is specifically in the comment."
|
||||
|
||||
Two parts. **Part 1** finds out why `[]` inside a comment is ever coloured, and
|
||||
fixes whatever of that is lucisv's. **Part 2** paints `TODO`, `FIXME`, `FIX_ME`
|
||||
and `TBD` — and any words the user lists in `lucisv.commentKeywords.custom` — in
|
||||
a bold theme colour wherever they appear as whole words inside `//` or `/* */`
|
||||
comments, and nowhere else.
|
||||
|
||||
### Part 1 — why `[]` inside a comment gets coloured
|
||||
|
||||
The colour on `[]` is VS Code's **bracket pair colourisation**
|
||||
(`editor.bracketPairColorization.enabled`, on by default), which colours every
|
||||
pair from `language-configuration.json`'s `brackets` — unless the token under
|
||||
the bracket is not `StandardTokenType.Other`. Three candidate causes were
|
||||
checked; **neither lucisv's server nor its grammar is the cause. The colour
|
||||
comes from one VS Code state in which the grammar's comment scopes are not
|
||||
consulted at all**, which an extension cannot change. **Part 1 is an
|
||||
explanation, not a fix: there is no fix in the extension's power** that does
|
||||
not also take bracket colours away from code (see the mitigations below).
|
||||
|
||||
**How VS Code decides (verified against `microsoft/vscode` `main`, 2026-11-19).**
|
||||
|
||||
- `bracketPairsTree/tokenizer.ts`, `NonPeekableTextBufferTokenizer.read()`:
|
||||
a bracket is a bracket only when
|
||||
`TokenMetadata.getTokenType(tokenMetadata) === StandardTokenType.Other` and
|
||||
the token's balanced-bracket bit is set; the metadata comes from
|
||||
`textModel.tokenization.getLineTokens(...)`. A comment token
|
||||
(`comment.*` scope → `StandardTokenType.Comment`) never yields a bracket.
|
||||
`FastTokenizer`, in the same file, reads **no token metadata**: it runs one
|
||||
regex over the whole text and treats every match as a bracket.
|
||||
- `bracketPairsTree/bracketPairsTree.ts`, constructor: when the model has no
|
||||
tokens yet it builds `initialAstWithoutTokens` with `FastTokenizer`; when
|
||||
background tokenization is still in progress it builds it from the buffer's
|
||||
current tokens (untokenized lines are one `Other` token each). Every
|
||||
colourising query reads `this.initialAstWithoutTokens || this.astWithTokens`,
|
||||
token-only changes **never update** `initialAstWithoutTokens`
|
||||
(`handleEdits(…, tokenChange)` skips it), and it is cleared only in
|
||||
`handleDidChangeBackgroundTokenizationState` once the state is
|
||||
`BackgroundTokenizationState.Completed`.
|
||||
- `TextMateTokenizationSupport.tokenizeEncoded` (read from VS Code 1.145.2's
|
||||
shipped `workbench.desktop.main.js` and its tokenization worker):
|
||||
`line.length >= maxTokenizationLineLength ? nullTokenizeEncoded(languageId,
|
||||
state) : …` — a line at least `editor.maxTokenizationLineLength` (default
|
||||
20 000) characters long is one `Other` token and carries the state across
|
||||
unchanged. **That token has no balanced-bracket bit** (`nullTokenize.ts`;
|
||||
QA's reading of the 1.145.2 bundle: `(s<<0|0|0|32768|2<<24)>>>0`, no `1024`,
|
||||
where the store default for a not-yet-tokenized line has it), so once such a
|
||||
line is tokenized its brackets are not colourised at all — in code or in
|
||||
comments.
|
||||
- `semanticTokensProviderStyling.ts`, `getMetadata`: semantic tokens set only
|
||||
font-style and foreground bits (plus the matching `SEMANTIC_USE_*` flags);
|
||||
**never the token-type bits**. So no semantic token can make a bracket
|
||||
in a comment coloured, or one in code uncoloured.
|
||||
|
||||
**So `[]` in a comment is coloured exactly when the file was just opened,
|
||||
until background tokenization finishes.** The first AST is token-blind, and
|
||||
stays in charge until the whole file has been tokenized — on a multi-megabyte
|
||||
file that takes visibly long, which matches "sometimes". Then the colours in
|
||||
comments disappear by themselves. (A variant of the same mechanism, from QA:
|
||||
after an edit opens or closes a `/*` above, the lines below keep their old
|
||||
tokens until the background tokenizer reaches them again, so their brackets may
|
||||
briefly keep or lose colour.)
|
||||
|
||||
*Corrected after QA F1:* the first version of this README named a second case,
|
||||
lines of `editor.maxTokenizationLineLength` or more. That was wrong: such a
|
||||
line's null token lacks the balanced-bracket bit, so after tokenization its
|
||||
brackets are not coloured at all; it is coloured only during the same
|
||||
token-blind phase as every other line.
|
||||
|
||||
Bracket colourisation is off entirely above 5 000 000 characters
|
||||
(`bracketPairsImpl.ts`, `canBuildAST`), and tokenization above 20 MiB or
|
||||
300 000 lines (`textModel.ts`, `_isTooLargeForTokenization`), so neither of
|
||||
those is another case.
|
||||
|
||||
**Mitigations considered, none adopted:**
|
||||
|
||||
- `balancedBracketScopes`/`unbalancedBracketScopes` on the grammar
|
||||
contribution: no help — they only set the balanced-bracket bit on TextMate
|
||||
tokens, and the token-blind tree reads no tokens.
|
||||
- `colorizedBracketPairs: []` in `language-configuration.json` (QA's note):
|
||||
it would remove the colouring in comments, but it also removes every
|
||||
bracket-pair colour in code, for every user. A net loss, and the owner's
|
||||
call, not this lane's. A user who wants it can set
|
||||
`"[systemverilog]": { "editor.language.colorizedBracketPairs": [] }` (and the
|
||||
same for `[verilog]`) themselves.
|
||||
- Decorations repainting brackets in comments with the comment colour: there
|
||||
is no theme colour for the theme's comment token colour, and it would
|
||||
compete with VS Code's own bracket decorations.
|
||||
- `editor.bracketPairColorization.enabled` via `configurationDefaults`: the
|
||||
user's switch, not ours to flip. lucisv cannot shorten VS Code's background
|
||||
tokenization either.
|
||||
|
||||
**What was ruled out, with evidence (one-off scripts, 2026-11-19).**
|
||||
|
||||
- **The TextMate grammar.** Run through the real `vscode-textmate` 9.3.2 and
|
||||
`vscode-oniguruma` 1.7.0 that VS Code 1.145.2 ships (extracted from its
|
||||
`node_modules.asar` into a scratch directory; not a dependency of anything
|
||||
here), compared per character against the server's own `comment` semantic
|
||||
tokens, on 309 OpenTitan files (every 13th of `hw/`, 69 249 lines):
|
||||
**0 characters the lexer calls comment that the grammar does not**, so in the
|
||||
steady state every bracket the lexer considers commented-out is uncoloured.
|
||||
The other direction has 39 lines — comments inside a `` `define `` body or
|
||||
inside a macro call's arguments (`` `DV_SPINWAIT(… // …) ``), which the lexer
|
||||
keeps as macro text and the grammar (rightly, visually) shows as comment.
|
||||
Neither direction colours a bracket in something that looks like a comment.
|
||||
Every comment form the brief named is scoped: `//` after a macro or a
|
||||
`` `ifdef ``, `/* */` across lines, comments after directives; `(* *)` is
|
||||
correctly *not* a comment (it is an attribute, and its parentheses are code).
|
||||
- **Server semantic tokens.** In the same run (`semanticTokens/full`): **0
|
||||
non-`comment` semantic tokens start inside a comment**, by the lexer's spans
|
||||
or by the grammar's. Repeated through the large-file window path
|
||||
(`semanticTokens/range` on one 12 MB, 357 172-line concatenation of 1 500
|
||||
OpenTitan files, so `semantic_tokens_in_window` answers): again 0. The
|
||||
server only ever emits tokens from lexer tokens, whose comments are trivia,
|
||||
and from `instantiation::overrides`, keyed by syntax-tree token starts.
|
||||
Nothing to fix in `crates/lucisv_server/src/tokens*`, so no Rust changed.
|
||||
- **lucisv's own rainbow.** It paints only `begin`/`end`/`fork`/`join` ranges
|
||||
from `pairs.rs`, computed over `Document.tokens` (comments excluded) — never
|
||||
a bracket.
|
||||
|
||||
One divergence between the grammar and the lexer was found and is **not** the
|
||||
reported problem: an escaped identifier containing `//` (`\a//b `) is an
|
||||
identifier to the lexer and a line comment to the grammar. It is filed under
|
||||
Status / TODO as a follow-up.
|
||||
|
||||
### Part 2 — mechanism, and why
|
||||
|
||||
**Editor decorations for every word** (option (b) of the brief), in two new
|
||||
modules: `commentScan.js` (pure — where the comments are, which words match)
|
||||
and `commentKeywords.js` (the VS Code wiring). Considered and rejected:
|
||||
|
||||
- *(a) TextMate patterns for the built-ins, decorations for custom words.* Two
|
||||
mechanisms painting the same thing in two different ways: a TextMate scope is
|
||||
coloured by the theme's `tokenColors`, which most themes do not define for a
|
||||
TODO scope, so the built-ins would look different from the custom words, and
|
||||
a `contributes.colors` default cannot reach a TextMate scope. Turning the
|
||||
built-ins off would also need a grammar the user cannot edit.
|
||||
- *(c) A server-side semantic-token modifier.* Splits every comment token,
|
||||
colours through `semanticTokenColors`/`semanticTokenScopes` rather than a
|
||||
contributed colour (so no guaranteed visible default), is Rust outside this
|
||||
lane's mandate, and the server would have to learn the words.
|
||||
|
||||
Decorations give one colour id (`lucisv.commentKeyword`, contributed with
|
||||
opaque defaults for all four theme kinds), apply to built-in and custom words
|
||||
identically, and re-read settings in the extension host without a round trip.
|
||||
|
||||
**Comment detection agrees with the grammar, by construction and by
|
||||
measurement.** The grammar decides "comment" with exactly two rules
|
||||
(`//.*`; `/\*` … `\*/`, multi-line) and hides them with one (a string, `"` …
|
||||
`"` or end of line, `\\.` escapes). Every other top-level rule (directives,
|
||||
macros, system tasks, numbers, keywords) is built only of characters that can
|
||||
never be `/` or `"`, so it can neither swallow nor reveal a comment start —
|
||||
`commentScan.js` mirrors those three rules and nothing else, and
|
||||
`commentScan_test.js` pins them: the comment and string rules must deep-equal
|
||||
what the scanner mirrors, and no other top-level rule may contain `/`, `"`,
|
||||
`.`, `[^`, `\S`, `\W`, `\D` or `\N`. Measured against the real tokenizer
|
||||
(the extracted `vscode-textmate`, as above) over **all 4 029 OpenTitan `hw`
|
||||
files, 1 185 823 lines, 39.3 M characters, 8.39 M of them comment: 0 lines
|
||||
where the scan and the grammar disagree on a single character**, plus a table
|
||||
of 20 hand-written edge lines (strings holding `//` and `/*`, escaped quotes,
|
||||
an escaped backslash before the closing quote, a backslash at end of line, an
|
||||
unterminated string, `/*/`, `/**/`, `/***/`, `` `define `` with a trailing
|
||||
comment, `` `ifdef `` with one, `(* *)`, an escaped identifier). The pictures
|
||||
in the scanner test's comment table are copied from that tokenizer's output,
|
||||
not hand-counted.
|
||||
|
||||
Why the grammar's notion and not the lexer's: the keyword is meant to stand out
|
||||
where the user *sees* a comment, and what they see is the grammar (the server's
|
||||
`comment` semantic token covers a subset of it — see Part 1). Matching the
|
||||
lexer instead would leave a `TODO` inside a `` `define `` body's `//` comment
|
||||
unpainted although it is drawn as a comment.
|
||||
|
||||
**Cheap on big files.** Only the visible ranges plus 50 lines either side are
|
||||
scanned for words. Whether a line starts inside a block comment is kept per
|
||||
document (`LineStates`), computed lazily from the top and truncated from the
|
||||
first edited line down — so typing re-scans nothing above the edit, scrolling
|
||||
re-scans nothing it has already passed, and the first paint at the bottom of a
|
||||
file reads each line above it once (`indexOf`-driven, no tokenizer). **An edit
|
||||
above the viewport does re-walk every line from the edit down to the
|
||||
viewport** (state only, no word matching): QA measured, on a fake
|
||||
100 000-line document, first paint at the bottom 12.3 ms / 100 000 reads,
|
||||
repaint 0.17 ms / 110 reads, edit at the top while viewing the bottom
|
||||
7.9 ms / 100 000 reads, edit in the middle 3.3 ms / 50 000 reads, edit inside
|
||||
the viewport 0.10 ms / 110 reads (the fake understates `lineAt`'s real cost).
|
||||
Edits are debounced 100 ms. A line of `editor.maxTokenizationLineLength` or
|
||||
more — read with the document as scope, so a `[systemverilog]` override counts
|
||||
— is skipped and carries the state across, exactly as VS Code does, and a
|
||||
megabyte-long netlist line is never scanned. A file VS Code does not tokenize
|
||||
at all (with `editor.largeFileOptimizations` on: more than 20 MiB of text or
|
||||
more than 300 000 lines) is not painted at all; VS Code makes that decision
|
||||
once per model and so does this, on a document's first paint. So the
|
||||
highlight appears only where VS Code draws comment colour.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- The grammar file is the one in `syntaxes/` and no other extension's grammar
|
||||
replaces it for `verilog`/`systemverilog`. With another grammar active, the
|
||||
scan may disagree with what is drawn.
|
||||
- VS Code draws a decoration's `color` over the token colour (both semantic and
|
||||
TextMate). This is how decoration colours have always rendered; not verified
|
||||
in a running editor here.
|
||||
- "Whole word" means `\b`-style boundaries with `$` counted as a word character
|
||||
(Verilog identifiers contain `$`): a word that starts with `[A-Za-z0-9_$]`
|
||||
must not have one just before it, and one that ends with one must not have
|
||||
one just after. So `TODO` skips `TODO_reg`, `myTODO`, `$TODO`, `TODO1`, and
|
||||
`REVIEW:` matches in `REVIEW:x`. The word characters are **ASCII only**
|
||||
(`[A-Za-z0-9_$]`, Verilog's identifier set): a custom word that starts or
|
||||
ends with a non-ASCII letter has no boundary on that side, so `ÄNDERN` lights
|
||||
inside `fooÄNDERN` (QA F5; as designed, not changed).
|
||||
- A string continued with backslash-newline ends, to the grammar, at the end
|
||||
of its line (`"|$`), so the continuation line is code and a `// TODO` on it
|
||||
is painted — which matches what is drawn (QA F7; by design).
|
||||
- Words are matched only in a comment's **body** — never across its own `//`,
|
||||
`/*` or `*/` — so a custom word made of `*` or `/` cannot light up a
|
||||
delimiter.
|
||||
- Editor background colours of the built-in themes used for the contrast test:
|
||||
Dark Modern `#1F1F1F`, Dark+ `#1E1E1E`, Light Modern/Light+ `#FFFFFF`, HC Dark
|
||||
`#000000`, HC Light `#FFFFFF`. A comment line with the current-line highlight
|
||||
or a selection behind it is not measured.
|
||||
|
||||
### Decisions the brief asked for
|
||||
|
||||
- **Can the built-in four be removed?** All together, yes:
|
||||
`lucisv.commentKeywords.builtIn: false`. Individually, no — that is a list
|
||||
edit with no use case named; anyone who wants two of them turns the built-ins
|
||||
off and lists those two in `custom`. The custom list is **additive** (default
|
||||
`[]`), so adding a word never silently loses the built-ins — which is what
|
||||
would happen if the four were the array's default, because VS Code replaces
|
||||
an array setting rather than merging it.
|
||||
- **Regex metacharacters** are matched literally: every word goes through
|
||||
`escapeRegExp` before it joins the alternation; nothing a user types is ever
|
||||
interpreted as a pattern.
|
||||
- **No catastrophic patterns**: the matcher is an alternation of escaped
|
||||
literals, longest first, each wrapped in at most one one-character lookbehind
|
||||
and one one-character lookahead — no quantifiers at all. The test runs the
|
||||
worst the caps allow (50 near-identical 40-character words of `a`) over a
|
||||
19 993-character comment of `a` and requires it under 2 s; it takes ~4 ms.
|
||||
- **Caps**: at most 50 custom words (entries past the 50th are ignored), each
|
||||
1–40 characters with no whitespace. An unusable entry — empty, too long,
|
||||
containing whitespace, not a string — is skipped, and one line
|
||||
(`lucisv: lucisv.commentKeywords.custom: ignored N entries (…)`) goes to the
|
||||
lucisv output channel. The `package.json` schema says the same
|
||||
(`minLength`, `maxLength`, `pattern: ^\S+$`, `maxItems`, `uniqueItems`), so
|
||||
the settings editor warns before the extension has to.
|
||||
- **Case**: case-sensitive by default (`todo` in prose stays plain); a boolean,
|
||||
`lucisv.commentKeywords.caseSensitive`, makes it insensitive — it costs one
|
||||
regex flag, so it is offered. Duplicates are dropped case-insensitively then.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes** `syntaxes/systemverilog.tmLanguage.json`'s `comments` and
|
||||
`strings` rules and the shape of every other top-level rule. **Promise to
|
||||
whoever edits the grammar:** `commentScan_test.js` fails on any change to
|
||||
those two rules, on a reordering that moves them off the top, and on any
|
||||
other top-level rule that could match `/` or `"`; update `commentScan.js` in
|
||||
the same change. The Rust keyword test (`crates/lucisv_server/tests/grammar.rs`)
|
||||
is untouched — the grammar did not change.
|
||||
- **Consumes** `editor.maxTokenizationLineLength` (per document, language
|
||||
overrides included) and `editor.largeFileOptimizations` (read, never
|
||||
written).
|
||||
- **Provides** the settings `lucisv.commentKeywords.builtIn`,
|
||||
`lucisv.commentKeywords.custom`, `lucisv.commentKeywords.caseSensitive` and
|
||||
the colour `lucisv.commentKeyword`. The server receives them in
|
||||
`workspace/didChangeConfiguration` with the rest of `lucisv` and ignores them
|
||||
(it only reads named keys; checked in `settings.rs`).
|
||||
- **extension.js**: one `require` and one construction in `activate`, after the
|
||||
rainbow's decoration types; the module pushes its decoration type and every
|
||||
listener (including `onDidOpenTextDocument`, for language-mode changes) into
|
||||
`context.subscriptions`. It needs nothing from the server.
|
||||
- **Packaging**: `commentKeywords.js` and `commentScan.js` are runtime modules
|
||||
(listed in `tools/RELEASING.md`'s runtime-module sentence and the
|
||||
`.vscodeignore` header); their two `*_test.js` files are excluded.
|
||||
- No Handshake requests to other lanes: nothing outside this lane's file list
|
||||
needed changing.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Part 1: find the cause of the bracket colouring, with evidence
|
||||
(VS Code's token-blind first AST and over-long lines; server and grammar
|
||||
cleared, measured).
|
||||
- [x] Part 1: fix what is lucisv's — nothing is; no grammar or Rust change.
|
||||
- [x] `commentScan.js`: grammar-equivalent comment scan, literal whole-word
|
||||
matcher, settings normalization with caps, incremental line states.
|
||||
- [x] `commentKeywords.js`: decorations on visible ranges, debounced edits,
|
||||
immediate setting changes, `maxTokenizationLineLength` honoured.
|
||||
- [x] `package.json`: three settings, one colour (one dot in its id).
|
||||
- [x] Tests: `commentScan_test.js` (14), `commentKeywords_test.js` (11 after
|
||||
the QA round, incl. the contrast check).
|
||||
- [x] Agreement with the real `vscode-textmate` over all of OpenTitan `hw`
|
||||
(one-off; recorded above).
|
||||
- [x] README (extension), `.vscodeignore`, `tools/RELEASING.md`.
|
||||
- [ ] Follow-up, not in this lane: the grammar has no rule for escaped
|
||||
identifiers, so `\a//b ` is drawn as a comment from `//` on, and —
|
||||
worse — `\a/*b ` opens a block comment that runs to the next `*/`,
|
||||
possibly many lines down (QA F6). A `\\\S+` rule ahead of `#comments`
|
||||
would fix both — but it changes the scan's mirrored rules too, so it goes
|
||||
with a `commentScan.js` change.
|
||||
- [x] QA fix round (F1–F7), see work log.
|
||||
- [ ] Seen in a running VS Code (cannot be done by the dev agent — see the QA
|
||||
checklist in the work log).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-11-19 — dev (Opus 5.5)
|
||||
|
||||
- Read the grammar, `language-configuration.json`, `tokens.rs`, the rainbow
|
||||
wiring. The rainbow only paints `begin`/`end`/`fork`/`join`; the server's
|
||||
semantic tokens never include punctuation except the instantiation `#`
|
||||
overrides.
|
||||
- Verified VS Code's bracket colourisation against `microsoft/vscode` `main`
|
||||
(`bracketPairsTree/tokenizer.ts`, `bracketPairsTree.ts`,
|
||||
`bracketPairsImpl.ts`, `textModel.ts`, `semanticTokensProviderStyling.ts`)
|
||||
and the installed 1.145.2 bundle (`maxTokenizationLineLength`, `>=`).
|
||||
- Built `lucisv-server` (debug) in this worktree and wrote two one-off scripts
|
||||
in the session scratchpad (not shipped): `compare.js` (grammar via the real
|
||||
`vscode-textmate` vs the server's semantic tokens, over LSP stdio) and
|
||||
`agree.js` (`commentScan.js` vs the real tokenizer). Numbers in Goal. Every
|
||||
run went through `tools/guard.sh`.
|
||||
- Decision: no grammar change, no Rust change (Part 1 found nothing of
|
||||
lucisv's to fix). Decorations for all words (Part 2), detection mirroring the
|
||||
grammar rather than the lexer, explained in Goal.
|
||||
- Words match in a comment's body only, after a test showed a custom `*/` word
|
||||
lighting the comment's own delimiter. Word boundaries changed from "neither
|
||||
neighbour is a word character" to `\b`-style per word edge, so a word ending
|
||||
in punctuation (`REVIEW:`) still matches before a letter.
|
||||
- The window scan records each line's successor state while it scans it, so a
|
||||
paint reads each window line once (the visible-range test counts reads:
|
||||
450 above + 121 in the window, then 121 on a repaint).
|
||||
- **What a human should look at in VS Code** (the dev cannot see a running
|
||||
editor):
|
||||
1. A `.sv` file with `// TODO: x`, `/* FIXME */`, `// FIX_ME TBD`, a
|
||||
three-line `/* … TODO … */`, `"// TODO"` in a string, `TODO_reg` in code:
|
||||
the four in comments are bold orange (Dark Modern and Light Modern), the
|
||||
string and the identifier are not.
|
||||
2. Add `"lucisv.commentKeywords.custom": ["XXX", "a.b"]` in settings.json:
|
||||
`XXX` lights at once, `a.b` lights but `axb` does not — no reload.
|
||||
`"builtIn": false` removes the four at once; `"caseSensitive": false`
|
||||
lights `todo`.
|
||||
3. Type `/*` at the top of a file: every TODO below lights up after a beat;
|
||||
delete it: they go back.
|
||||
4. Open a multi-MB OpenTitan-sized file and scroll to the end: the keywords
|
||||
appear as you scroll, typing stays smooth.
|
||||
5. Part 1, the cause: open a large `.sv` (a few MB) with `x[3:0]` in
|
||||
comments and watch the brackets inside comments lose their colour once
|
||||
tokenization finishes (a few seconds). If they **stay** coloured on a
|
||||
normal-length line after that, Part 1's conclusion is wrong — check
|
||||
*Developer: Inspect Editor Tokens and Scopes* on the bracket and report the
|
||||
scope and which extension provides the grammar.
|
||||
6. `workbench.colorCustomizations: { "lucisv.commentKeyword": "#FF0000" }`
|
||||
recolours them.
|
||||
|
||||
### 2026-11-19 — dev (Opus 5.5), QA fix round
|
||||
|
||||
- **F1**: Part 1 now names one cause only (the token-blind tree until
|
||||
background tokenization completes); the long-line case is struck with the
|
||||
reason (null token, no balanced-bracket bit) and a "corrected after QA"
|
||||
note. Stated plainly that Part 1 is an explanation with no fix in the
|
||||
extension's power; mitigations listed, including QA's
|
||||
`colorizedBracketPairs: []` (not adopted: it removes bracket colour in code
|
||||
too). Changelog paragraph corrected.
|
||||
- **F2**: `commentKeywords.js` reads `editor.maxTokenizationLineLength` with
|
||||
the document as scope; each document's record keeps the cutoff its states
|
||||
were computed with and starts over when it changes (so the configuration
|
||||
handler no longer clears a global cache). Test: a `[systemverilog]` override
|
||||
applies to the `.sv` document and not to a `verilog` one, and dropping it
|
||||
recomputes.
|
||||
- **F3**: verified in `src/vscode-dts/vscode.d.ts` (`main`, 2026-11-19):
|
||||
`onDidOpenTextDocument`/`onDidCloseTextDocument` fire "when the language id of
|
||||
a text document has been changed", `setTextDocumentLanguage` "will trigger the
|
||||
onDidCloseTextDocument event followed by the onDidOpenTextDocument event",
|
||||
and the open "is emitted before the document is updated in the active text
|
||||
editor" — so the open handler repaints on the next tick. A non-Verilog editor
|
||||
this module painted is cleared; one it never painted is never touched. Test
|
||||
with the stub: `.sv` → plaintext clears, back → paints without scroll/edit.
|
||||
The rainbow in `extension.js` has the same pre-existing gap (QA noted it);
|
||||
not changed here — it is outside this feature.
|
||||
- **F4**: wording fixed (here and in the extension README). Files VS Code does
|
||||
not tokenize (`editor.largeFileOptimizations` on and > 20 MiB of text —
|
||||
`offsetAt` of the end, UTF-16 units, as `getValueLength` counts — or
|
||||
> 300 000 lines) are not painted; decided once per document. Tests: 300 001
|
||||
lines, 20 MiB + 1, exactly 20 MiB (painted), and the option off (painted).
|
||||
- **F5, F7**: documented as by design under Assumptions. **F6**: the
|
||||
escaped-identifier follow-up names `\a/*b`.
|
||||
|
||||
### Changelog paragraph (for the lead)
|
||||
|
||||
**Comment keywords.** `TODO`, `FIXME`, `FIX_ME` and `TBD` inside `//` and
|
||||
`/* */` comments are now bold, in a new `lucisv.commentKeyword` theme colour —
|
||||
as whole words, never in strings or code. `lucisv.commentKeywords.custom` adds
|
||||
your own words (matched literally, up to 50), `lucisv.commentKeywords.builtIn`
|
||||
turns the four off and `lucisv.commentKeywords.caseSensitive` makes matching
|
||||
case-insensitive; every change applies immediately. Only the lines on screen
|
||||
are searched for the words (an edit above the screen re-reads the lines down
|
||||
to it), and a file too large for VS Code to tokenize is not painted. Brackets
|
||||
that are sometimes coloured inside comments come from VS Code's bracket-pair
|
||||
colourisation while a newly opened file has not finished tokenizing, not from
|
||||
lucisv — its grammar and semantic tokens were measured to colour nothing
|
||||
inside a comment — and the colours go once tokenization completes; there is no
|
||||
extension-side fix that would not also remove bracket colours in code.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-11-19 — QA (Opus 5.5)
|
||||
|
||||
**Verdict: PASS WITH FINDINGS.** Part 2 (the code) holds up under every
|
||||
attack below. One Part 1 claim (case 2, over-long lines) is wrong against
|
||||
VS Code's source and the shipped 1.145.2 bundle (F1, documentation only: the
|
||||
code does the right thing anyway). Three low findings, three informational.
|
||||
|
||||
**Commands and results**
|
||||
|
||||
- `node --test editors/vscode/*_test.js`: 34 files, 34 pass, 0 fail.
|
||||
`commentScan_test.js` has 14 tests and `commentKeywords_test.js` 8, as
|
||||
claimed. `node --check` is clean on `commentScan.js`, `commentKeywords.js`,
|
||||
`extension.js` and both tests. `package.json` parses, `version` is `0.65.2`.
|
||||
- Scope: `git status --untracked-files=all` lists only `editors/vscode/*`,
|
||||
`tools/RELEASING.md` and `docs/features/comment-highlighting/`.
|
||||
- `npx --no-install @vscode/vsce ls --no-dependencies`: ships
|
||||
`commentKeywords.js` and `commentScan.js`; nothing matching `_test` or
|
||||
`smoke` ships.
|
||||
- Reproduced the dev's full-corpus number myself:
|
||||
`tools/guard.sh -m 4 -t 600 -- node agree.js … all.txt` printed
|
||||
`{"docs":4029,"lines":1185823,"chars":39294203,"commentChars":8391566,"mismatchedLines":0}`.
|
||||
On the scripts: `agree.js` is a sound per-character comparison of
|
||||
`scanLine` chained across lines against the real `vscode-textmate`, so it
|
||||
does prove agreement with the grammar on OpenTitan. It does not exercise
|
||||
`LineStates`, edits or `maxLineLength`; my `prop_edit.js` covers those.
|
||||
`compare.js` (server vs grammar) checks only where non-comment semantic
|
||||
tokens *start*. That is enough, because semantic tokens can never change
|
||||
a bracket's token type anyway (confirmed: `getMetadata` sets only
|
||||
font/foreground bits). Its usage line says `--window` but the code reads
|
||||
`--range`. That is cosmetic.
|
||||
- QA scripts (scratchpad `qa71/`, not shipped): `scan_attack.js` (82 crafted
|
||||
lines vs `vscode-textmate`), `kw_attack.js` (matcher, settings, wiring,
|
||||
perf), `prop_edit.js` (3 000 random edit/scroll rounds).
|
||||
|
||||
**Part 1: VS Code source, checked independently** (`microsoft/vscode`
|
||||
`main`, fetched 2026-11-19, plus the installed 1.145.2
|
||||
`workbench.desktop.main.js`).
|
||||
|
||||
- Confirmed: `bracketPairsTree/tokenizer.ts:203-208` treats a bracket as a
|
||||
bracket only if `getTokenType === StandardTokenType.Other` **and**
|
||||
`containsBalancedBrackets(metadata)`. `FastTokenizer` (`:282`) reads no
|
||||
tokens. `bracketPairsTree.ts:65-79` builds the token-blind
|
||||
`initialAstWithoutTokens` when the model has no tokens yet, or from the
|
||||
current tokens while background tokenization is in progress.
|
||||
`:84-93` clears it only on `BackgroundTokenizationState.Completed`. Token
|
||||
changes never update it (`:121`). Lines that are not tokenized yet get
|
||||
`getDefaultMetadata` (`tokens/contiguousTokensStore.ts:247-256`), which
|
||||
**does** set `BALANCED_BRACKETS_MASK`, so they produce brackets. Case 1 is
|
||||
right.
|
||||
- **F1 (medium, documentation): case 2 is wrong.** A line of
|
||||
`maxTokenizationLineLength` or more is tokenized by `nullTokenizeEncoded`
|
||||
(`tokenizationSupportWithLineLimit.ts:40-41`; the worker uses the same
|
||||
wrapper, `textMateWorkerTokenizer.ts:108`). `nullTokenizeEncoded`
|
||||
(`languages/nullTokenize.ts:22-31`) sets **no** `BALANCED_BRACKETS_MASK`.
|
||||
The 1.145.2 bundle agrees: the long-line token is
|
||||
`(s<<0|0|0|32768|2<<24)>>>0` with no `1024` bit, while the store default is
|
||||
`…|2<<24|1024`. So once tokenization is complete, brackets on such a line
|
||||
are **not colourised at all**, in code or in comments. They are coloured
|
||||
only while case 1 applies, like every other line. Wrong text:
|
||||
Goal/Part 1 items "2." (lines 63-65), "case 2 has none" (line 72), and the
|
||||
changelog's "(or on a line too long to tokenize)" (line 323). The code is
|
||||
unaffected: skipping those lines in `commentKeywords.js` still matches what
|
||||
VS Code draws (no comment colour there). Suggested fix: drop case 2 and say
|
||||
over-long lines get no bracket colours once tokenized.
|
||||
- Missed transient (info): after an edit that opens or closes a `/*` above,
|
||||
the lines below keep their old tokens until the background tokenizer
|
||||
re-reaches them, so brackets there may briefly keep or lose colour.
|
||||
This is the same mechanism as case 1, and transient.
|
||||
- Mitigations in the extension's power:
|
||||
- `balancedBracketScopes`/`unbalancedBracketScopes`: no help. They only set
|
||||
the bit on TextMate tokens, and case 1 reads none. I agree with the dev.
|
||||
- `colorizedBracketPairs: []` in `language-configuration.json`: it would
|
||||
remove case 1's colouring in comments, but it also removes bracket-pair
|
||||
colours in code for every user. That is a net loss and the owner's call,
|
||||
not this lane's. (I did not read in detail how `FastTokenizer` derives
|
||||
its pairs from `colorizedBracketPairs`. A user can get the same effect
|
||||
with a `[systemverilog]` `editor.language.colorizedBracketPairs: []`
|
||||
override.)
|
||||
- Painting brackets inside comments with a decoration: not viable. There
|
||||
is no ThemeColor for the theme's comment token colour, and it would
|
||||
compete with the bracket decorations' CSS.
|
||||
- `contributes.configurationDefaults`: not ours to flip
|
||||
(`bracketPairColorization.enabled`).
|
||||
|
||||
**Part 2: commentScan.js vs the real tokenizer** (`scan_attack.js`):
|
||||
**82/82 lines agree**. Cases covered: `"//"` and `"/*"` in strings, `\"`,
|
||||
`"a\\"`, a backslash at end of line (the string ends at `$`, so the next
|
||||
line's `// TODO` is a comment, as the grammar draws it), a 32-line block,
|
||||
`/*/`, `/**/`, `/***/`, `/* /* */`, `//` inside a block, `/*` inside `//`,
|
||||
tabs, an unterminated block to EOF, `\a//b` and `\a/*b`, `` `define `` bodies
|
||||
with both comment kinds, `(* *)`, `@(*)`, `@ (*)`, `(*)`, `a/ *b`, `a*/b`,
|
||||
`a/*c*/d`, `a=b//c`, emoji and accents (UTF-16 columns line up), `"` inside
|
||||
comments, `""`, `"\""`, `"\\""`, a stray `*/`, and the bare `//` `/*` `*/` `/`
|
||||
`"` `\`. CRLF: VS Code hands `lineAt().text` without the EOL, so it is not a
|
||||
case for the scanner (`agree.js` splits on `\r?\n` too).
|
||||
|
||||
**Part 2: commentKeywords / matcher** (`kw_attack.js`):
|
||||
|
||||
- Boundaries all as documented: `TODO:` `TODO(` `(TODO)` `TODO.` `//TODO`
|
||||
`/*TODO*/` `\TODO` and `😀TODO😀` match. `TODOs` `TODO_x` `xTODO` `$TODO`
|
||||
`TODO$` `TODO1` `FIX_ME_LATER` and `todo` (case-sensitive) do not.
|
||||
`TODO` in a string or in code is not painted.
|
||||
- Overlaps: the longest word wins at the same start (`FIX_ME` over `FIX`,
|
||||
`TBD` over `TB`, `!!!` over `!!`). `FIX` alone never lights inside
|
||||
`FIX_ME`. Matches never overlap (`a.b`/`b.c` on `a.b.c` gives `a.b`).
|
||||
- Metacharacters are literal: `a.b` (not `axb`), `(x`, `[`, `\`, `^$`, `.*`
|
||||
(not `hello`), `|`, `?`, `+`, `{2}`, `$`, `/`, `*`. The words `*/`, `*` and
|
||||
`/` never light a delimiter.
|
||||
- Junk: `''`, `'a b'`, `5`, `null`, 41 characters and an object are skipped
|
||||
(6 counted). 40 characters is kept. Duplicates and a built-in repeated in
|
||||
`custom` are dropped. 60 words give 50 used and 10 skipped. A non-array
|
||||
`custom` gives the built-ins only (silently, with no log line: fine).
|
||||
`caseSensitive:false` matches `todo`/`Todo` and dedupes case-insensitively.
|
||||
- Wiring with a fake `vscode`: split views of one document each paint their
|
||||
own ranges from shared states. Plain-text editors are untouched.
|
||||
`builtIn:false` with an empty `custom` clears the decorations, and custom
|
||||
words apply live. Disposing every subscription removes all five listeners
|
||||
and disposes the decoration type (timer cleared).
|
||||
- **Edit invalidation property** (`prop_edit.js`): 3 000 rounds of 1–3
|
||||
changes (replace, insert or delete lines made of `/*` `*/` `//` `"` `\`
|
||||
`TODO` `(*` `😀` …) anywhere in a 400-line document, then a random
|
||||
viewport, with `maxTokenizationLineLength` forced to 30 so the long-line
|
||||
carry is exercised. Every paint was compared with a scan from line 0:
|
||||
**0 mismatches**.
|
||||
- **100 000-line document** (fake document, so `lineAt` cost is
|
||||
understated). First paint at the bottom: 12.3 ms, 100 000 reads. Repaint:
|
||||
0.17 ms, 110 reads. Edit at top, viewing the bottom: 7.9 ms, 100 000 reads.
|
||||
Edit in the middle: 3.3 ms, 50 000 reads. Edit in the viewport: 0.10 ms,
|
||||
110 reads. Edit at top, viewing the top: 0.12 ms, 111 reads. So word
|
||||
matching is bounded by the viewport, but the state walk is bounded by
|
||||
*(viewport bottom − first edited line)*, not by the viewport. That cost is
|
||||
fine, but see F4.
|
||||
- Contrast, computed independently (WCAG relative luminance): dark
|
||||
`#FF9E3D` scores 8.01 on `#1F1F1F`, 8.11 on `#1E1E1E`, 7.45 on `#252526`
|
||||
and 7.30 on `#002B36` (Solarized Dark). Light `#A85000` scores 5.51 on
|
||||
white, 4.96 on `#F3F3F3` and 5.11 on `#FDF6E3`. HC `#FFA500` on black:
|
||||
10.63. HC-light `#9C4A00` on white: 6.19. All are ≥ 4.5. `lucisv.commentKeyword`
|
||||
is spelled identically in `package.json:491`, `commentKeywords.js:15` and
|
||||
the README.
|
||||
|
||||
**Findings**
|
||||
|
||||
- **F1 (medium, doc)**: see Part 1 above.
|
||||
- **F2 (low)**: `commentKeywords.js:75` reads
|
||||
`getConfiguration('editor').get('maxTokenizationLineLength')` with no
|
||||
language scope. VS Code reads it per language
|
||||
(`textMateTokenizationFeatureImpl.ts:305-310`,
|
||||
`observableConfigValue('editor.maxTokenizationLineLength', languageId, …)`).
|
||||
Repro: `"[systemverilog]": { "editor.maxTokenizationLineLength": 100 }`.
|
||||
VS Code then stops drawing comments on lines of 100+ characters, but lucisv
|
||||
still paints keywords there. A long line that opens `/*` also carries
|
||||
a different block state below, so keywords below can be painted in code or
|
||||
missed in comments. Fix: read it with the document as scope
|
||||
(`getConfiguration('editor', document)`) and keep the cutoff per document's
|
||||
states.
|
||||
- **F3 (low)**: there is no handling of a language-mode change
|
||||
(`commentKeywords.js:51-55`, `:110`). VS Code reports it as
|
||||
close+open of the document, not as a visible-editors change. Switching a
|
||||
Verilog editor to Plain Text leaves its keyword decorations in place
|
||||
(`paintEditor` returns before clearing). Switching a `.txt` to
|
||||
SystemVerilog paints nothing until the next scroll or edit. Reproduced with
|
||||
the fake in `kw_attack.js`. The rainbow (`extension.js` `repaintVisible`)
|
||||
has the same pre-existing gap. Fix: `onDidOpenTextDocument` → `paintVisible`,
|
||||
and clear (`setDecorations([])`) for a non-target editor rather than
|
||||
returning.
|
||||
- **F4 (low, doc)**: two claims overstate. (a) "so the highlight never
|
||||
appears where VS Code shows no comment" (Goal, line 163) does not hold for
|
||||
files VS Code does not tokenize at all (> 20 MiB or > 300 000 lines,
|
||||
confirmed in the 1.145.2 bundle, `LARGE_FILE_SIZE_THRESHOLD=20*1024*1024`,
|
||||
`LARGE_FILE_LINE_COUNT_THRESHOLD=300*1e3`). There, lucisv paints keywords
|
||||
in text drawn without comment colour, and the first paint walks every line
|
||||
above the viewport. (b) The extension README's "Only the lines on screen
|
||||
are scanned" leaves out that an edit above the viewport re-walks every line
|
||||
from the edit down to the viewport (numbers above). Arguably both are
|
||||
harmless behaviour, but the text should say it.
|
||||
- **F5 (info)**: `WORD_CHAR` is ASCII, so a custom word starting or ending in
|
||||
a non-ASCII letter has no boundary there (`ÄNDERN` lights inside
|
||||
`fooÄNDERN`). This is consistent with the documented rule.
|
||||
- **F6 (info)**: the escaped-identifier follow-up should also name `\a/*b`.
|
||||
The grammar (and the scan) open a block comment there that runs to the next
|
||||
`*/`, possibly many lines, which is worse than the `\a//b` case filed.
|
||||
- **F7 (info)**: in a string continued with backslash-newline, the
|
||||
continuation line is code to the grammar (the string ends at `$`), so a
|
||||
`// TODO` on it is painted. It matches what is drawn, by design.
|
||||
|
||||
**Fixed by QA**: `editors/vscode/commentScan_test.js`, the "no other
|
||||
top-level grammar rule can match …" test. The banned escapes now also
|
||||
include `\H` (Oniguruma non-hex, matches `/`), `\O`, `\X`, `\R`, `\P`, `\p`,
|
||||
`\x`/`\u`/`\0` (code-point escapes that can spell `/` or `"`) and POSIX
|
||||
`[[:`. None occurs in the grammar today (14/14 still pass). A mutated
|
||||
grammar with `` `[a-zA-Z_\x2F]* `` now fails the test (checked in a scratch
|
||||
copy).
|
||||
|
||||
**Not verifiable without a running VS Code**: the decoration colour drawn
|
||||
over semantic and TextMate colours, bold rendering, the real ext-host
|
||||
`lineAt` cost on a multi-MB file, the language-change event sequence behind
|
||||
F3 (inferred from the API, not observed), and the dev's QA checklist items
|
||||
1–6 (especially 5: watching comment brackets lose colour once tokenization
|
||||
completes).
|
||||
|
||||
## Review
|
||||
|
||||
**Lead, 2026-11-19.** Accepted for 0.65.3.
|
||||
|
||||
- Half of the owner's item is an explanation, not a change, and the changelog
|
||||
says so in those words. QA's F1 mattered: the dev's second cause was wrong
|
||||
and I had already repeated it to the owner; corrected with them and here.
|
||||
`colorizedBracketPairs: []` is not adopted — it would take bracket colours
|
||||
out of code for everyone to fix a transient in comments.
|
||||
- Decorations for all words (one colour, one switch) is the boring choice and
|
||||
the right one. The scanner copies three grammar rules and a test pins that
|
||||
no other rule can match `/` or `"`; QA tightened that pin. The corpus
|
||||
agreement run (4 029 files, 0 lines) was reproduced by QA, not just quoted.
|
||||
- Fix round verified by re-running the suite: 37 tests, 37 pass. `extension.js`
|
||||
wiring read: the client exists before the closure can be called.
|
||||
- Owed to a human: that the decoration draws over the comment colour, and the
|
||||
Part 1 observation itself (work log checklist, item 5).
|
||||
- Follow-ups left open on purpose: the escaped-identifier grammar mismatch
|
||||
(`\a//b `, `\a/*b`), and the same language-mode gap in the `begin`/`end`
|
||||
rainbow in `extension.js`.
|
||||
@@ -0,0 +1,448 @@
|
||||
# completion-ux
|
||||
|
||||
## Goal
|
||||
|
||||
Completion that keeps up with typing (TODO §68.1, owner's order 2026-11-17).
|
||||
Five changes to the editing loop the VS Code extension drives, all served by
|
||||
`lucisv-server` so other LSP clients get them too:
|
||||
|
||||
1. **`begin` + Enter writes the `end`.** The newline on-type answer, when the
|
||||
line above ends in `begin` / `begin : label` and the block still owes an
|
||||
`end`, also writes `end` on the line after the new one, at the owning
|
||||
statement's indentation; the cursor stays on the indented body line. The
|
||||
extension sends that request itself when `editor.formatOnType` is off.
|
||||
2. **Clock and reset in the `always` templates.** `always_ff @(` and
|
||||
`always @(` ghost `posedge ${1:clk} or negedge ${2:rst_n}) begin … end`
|
||||
first; the clock-only form stays as the second choice, in the ghost and in
|
||||
the popup.
|
||||
3. **Current-file names rank first** in the popup: what this buffer declares
|
||||
(any scope), then the words it uses, ahead of other files' names, the
|
||||
templates and the keywords.
|
||||
4. **Keyword ghosts.** A typed proper prefix of a keyword shows the rest as
|
||||
grey inline text, following the popup's selected item while the popup is
|
||||
open.
|
||||
5. **Port items.** After the `.` of a connection, unconnected ports first,
|
||||
connected ones after them marked `connected`; accepting one writes
|
||||
`.name($1)` with the cursor inside the parentheses, pre-filled with a
|
||||
same-named signal when the instantiating scope has one.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Auto-`end` — which `begin` owes an `end`.** `pairs::analyze` is a stack
|
||||
matcher, so a `begin` typed inside a balanced block steals that block's
|
||||
`end` and the *outer* `begin` comes out unmatched. The rule
|
||||
(`on_type/auto_end.rs::owes_an_end`): no `end` if this `begin` is matched by
|
||||
an `end` that is first on its line at exactly the indentation the answer
|
||||
would write; otherwise an `end` iff any `begin` at or before this one is in
|
||||
`unmatched_open`. Fix round: the `begin` also counts as closed when its
|
||||
matched `end` starts its line at the `begin`'s **own** line's indentation
|
||||
(GNU layout, `begin` on its own line), and an unmatched `begin` inside a
|
||||
`` `ifdef ``/`` `ifndef `` region that has an `` `else ``/`` `elsif ``
|
||||
arms nothing. Consequence: an unrelated unclosed `begin` earlier in the
|
||||
file still arms it (accepted heuristic, lead's ruling); a hand-mis-indented
|
||||
`end` belonging to an outer block at either column disarms it.
|
||||
- **Auto-`end` and `` `ifdef `` branches (QA finding 1).** Two branches that
|
||||
each open the same block (`` `ifdef A always … begin `else always … begin
|
||||
`endif `` and one shared `end`) are complete code that the stack matcher
|
||||
reads as one unmatched `begin`. What is right after the *first* branch's
|
||||
`begin` is **no `end`**: the block's `end` is the shared one after the
|
||||
`` `endif ``, and a second would break the other branch. The cheap rule —
|
||||
an unmatched `begin` inside a branched conditional region never arms the
|
||||
answer — gets that right. Known limit it buys: a genuinely new `begin`
|
||||
typed inside such a region whose only unmatched `begin` is itself gets no
|
||||
`end` (the plain indent answer instead). The region scan is by directive
|
||||
word over the token stream; a region never closed runs to end of buffer.
|
||||
- **Auto-`end` — the owner line.** Read backwards from the `begin` over a
|
||||
parenthesised header, `@`/`#` and its operand, one header keyword (`if`,
|
||||
`for`, `foreach`, `while`, `repeat`, `forever`, the `always` family,
|
||||
`initial`, `final`) and the qualifiers in front of it (`else`, `unique`,
|
||||
`unique0`, `priority`). Anything else ends the walk. The `end` takes that
|
||||
line's leading whitespace *as written* (tabs stay tabs). An unmatched `)`
|
||||
leaves the `begin`'s own line as the answer.
|
||||
- **Auto-`end` — the body line.** The nesting model's level (spaces, as the
|
||||
plain newline answer) when it lies deeper than the `end`; else the `end`'s
|
||||
indent plus one `lucisv.indent`-width step; a tab-indented `end` gets one
|
||||
more tab.
|
||||
- **Auto-`end` — only on a blank new line.** Enter pressed mid-line carries
|
||||
text down, and that line gets the plain indent answer only. The previous
|
||||
line must *end* in `begin` / `begin : label`; comments are trivia and do not
|
||||
count. Only `begin` — not `fork`, `case`, `module`.
|
||||
- **Auto-`end` edit shape.** Two edits: the new line's leading whitespace
|
||||
(omitted when already right) and an insertion of `<indent>end<eol>` at
|
||||
column 0 of the line *after* the new one, so no edit touches the cursor
|
||||
position. When the new line is the file's last line there is nowhere else to
|
||||
put it: one edit replaces the new line with `body<eol><indent>end`. The
|
||||
line ending is the one just typed (`\r\n` files stay `\r\n`).
|
||||
- **Extension path.** `editors/vscode/typing.js` acts on an
|
||||
`onDidChangeTextDocument` event with exactly one content change, no
|
||||
`reason` (undo/redo are skipped), `rangeLength` 0, text matching
|
||||
`^\r?\n[ \t]*$`, a line before it ending in `begin`/`begin : label`
|
||||
(a `//` comment stripped), `editor.formatOnType` **not** on for the
|
||||
document (language overrides honoured via `getConfiguration('editor',
|
||||
document)`), and `lucisv.autoEnd` not `false`. The request goes out on the
|
||||
next tick (`setTimeout 0`) so the language client's own `didChange` for the
|
||||
same event is sent first. The answer is applied only if the document
|
||||
version is unchanged and the answer writes an `end` (an indent-only answer
|
||||
is formatting the user never turned on). Applied with `editor.edit(…,
|
||||
{ undoStopBefore: false, undoStopAfter: true })`, then the cursor is put at
|
||||
the end of the new line.
|
||||
- **Undo.** The edit has no undo stop before it, so VS Code should fold it
|
||||
into the Enter's own undo step: one `Ctrl+Z` removes the `end`, the indent
|
||||
and the newline together. Not verified in a running VS Code (see QA).
|
||||
- **Templates.** Popup template `sortText` is now `5` + three-digit registry
|
||||
rank + label, so templates reached by the same prefix show in registry order;
|
||||
the with-reset `always_ff` / Verilog `always @(posedge … or negedge …)` were
|
||||
moved ahead of the clock-only ones. Labels unchanged.
|
||||
- **Ranking — the final tier table** (`completion/mod.rs`; the first
|
||||
character of every `sortText`, a label follows, so the order is total):
|
||||
|
||||
| digit | tier | source |
|
||||
|---|---|---|
|
||||
| `0` | module names (item position) / members (exclusive answer) | index / site |
|
||||
| `1` | visible at the cursor (scope chain); in a connection list: already-connected ports | `Semantics` |
|
||||
| `2` | declared anywhere in this buffer | `Semantics::symbols()` |
|
||||
| `3` | identifiers used in this buffer (not the token under the cursor) | token stream |
|
||||
| `4` | what the project declares (units, members, `` `define ``s) | index |
|
||||
| `5` | templates (`5` + rank + label) | `templates.rs` |
|
||||
| `6` | keywords | `vlog_parser::KEYWORDS` |
|
||||
| `7` | project words | candidate tables |
|
||||
|
||||
Dedup by label is unchanged: the first (best) tier wins. VS Code sorts by
|
||||
its own fuzzy score first and uses `sortText` among equal scores, so the
|
||||
tier order decides between equally good matches only.
|
||||
- **Ranking — the typed word itself.** The buffer-word tier skips the token
|
||||
starting at the cursor's word, so a half-typed `c` is no longer offered
|
||||
back as `c` (it used to be, by the old word tier). A saved copy of the same
|
||||
file still contributes it through the project-word table.
|
||||
- **Keyword ghosts.** `inline/keywords.rs`. Asked only when no template
|
||||
trigger answered and the rest of the line is blank (the existing ghost rule).
|
||||
The word: the token ending exactly at the cursor, `Ident` or `Keyword`,
|
||||
ASCII identifier characters starting with a letter, length ≥ 2, not after
|
||||
`.`/`::`, and not exactly a name this buffer declares (fix round: `in`,
|
||||
`re`, `out` as signals stay quiet; an undeclared word ghosts in any
|
||||
position, expressions included). A word that is already a keyword only
|
||||
extends across `_`
|
||||
(`always` → `always_ff`; `end`, `for`, `case` get nothing — a ghost after a
|
||||
finished keyword is noise a stray Tab accepts) — unless the popup has
|
||||
that keyword selected: an explicit selection wins (`end` with `endmodule`
|
||||
selected ghosts `endmodule`). Choice: the popup's
|
||||
`selectedCompletionInfo.text` when present and its range is exactly the
|
||||
typed word (start of the word to the cursor; any other range is read as no
|
||||
selection and never echoed back) — ghost exactly it, over that range, if
|
||||
it is a reserved word of the dialect extending the word, otherwise no
|
||||
ghost, since VS Code would hide a disagreeing one; else the first of a fixed priority
|
||||
list (`PRIORITY`); else shortest-then-alphabetical over `KEYWORDS`. A `.v`
|
||||
buffer is limited to the IEEE 1364-2005 reserved words. Item shape: with
|
||||
no selection, empty range at the cursor and the suffix as a snippet value
|
||||
(the existing ghosts' shape); with a selection, the selection's range and
|
||||
the whole keyword (LSP 3.18: "must extend the text of the selected item and
|
||||
use the same range").
|
||||
- **Extension bridge (corrected in the fix round, QA finding 2).**
|
||||
`vscode-languageclient` 9 passes VS Code's `selectedCompletionInfo` through
|
||||
unconverted, so a `vscode.Range` goes out in its `toJSON` array shape and
|
||||
the trigger kind as VS Code's 0/1 rather than LSP's 1/2. **Nothing was
|
||||
broken by this**: serde decodes the server's `Range` struct from a
|
||||
two-element sequence and the trigger kind is an `i32` newtype, so the
|
||||
request decoded and the template ghosts kept working (pinned by
|
||||
`qa_an_array_shaped_range_and_a_zero_trigger_kind_still_decode`). The
|
||||
`middleware.provideInlineCompletionItems` re-spelling both
|
||||
(`typing.protocolInlineContext`) is correctness hygiene: the spec's
|
||||
spelling on the wire, and correct trigger kinds for any server that reads
|
||||
them.
|
||||
- **Port items.** `completion/connection.rs`. Applies to both connection
|
||||
lists — ports after `inst (` and parameters after `#(`. Connected entries
|
||||
are those `connected_names` finds (the entry being re-typed excluded); they
|
||||
get `sortText` `1<name>` and `labelDetails.description = "connected"`.
|
||||
Within each group the order is the match order, as before (`sortText` is
|
||||
alphabetical by name within a digit, also as before). Snippet
|
||||
`name(${1:fill})` / `name(${1})` only for a client with snippet support, no
|
||||
`(` after the identifier run being replaced (same line, spaces/tabs
|
||||
skipped), and a plain-identifier name. Pre-fill when the scope chain at the
|
||||
cursor binds a `Net`/`Var`/`Port` (ports) or `Param`/`LocalParam`
|
||||
(parameters) of the same name. **An auto-closed `)` is not handled**: the
|
||||
popup is reached after a `.`, where no paren has been typed yet; if the user
|
||||
had typed `.cl(` and gone back, the `(` check already gives the bare name.
|
||||
|
||||
- **Known limits accepted by the lead (QA notes 6–11).**
|
||||
- *LIMIT starvation moved* (6): with ≥ 512 names in this file matching a
|
||||
one-letter prefix (a synthetic 600-`logic aN;` buffer), templates and
|
||||
keywords fall out of the one-letter answer; `isIncomplete` is true, so
|
||||
the second letter re-asks and gets them. Largest real case seen: 220
|
||||
items (`r` in `ibex_core.sv`).
|
||||
- *Token under the cursor* (7): tier 3 skips it even mid-word, so a word
|
||||
this file uses exactly once and declares nowhere drops out while the
|
||||
cursor is inside it.
|
||||
- *Body indent inside `fork`* (8): the body line's indent is the existing
|
||||
nesting model's answer (identical to the plain newline answer), so
|
||||
`initial fork\n begin` + Enter gives an 8-space body over a 4-space
|
||||
`end`.
|
||||
- *Pre-fill* (9) accepts a same-named signal declared after the instance —
|
||||
the scope chain binds it either way.
|
||||
- *Last line under formatOnType* (11): there the answer is one edit whose
|
||||
range contains the cursor, so VS Code probably leaves the cursor after
|
||||
the `end`; the extension path puts it back itself.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes** `pairs::analyze` (unchanged), `on_type::level_at` (unchanged,
|
||||
called from the child module), `Semantics::symbols()` / `scopes()`,
|
||||
`signature::enclosing_list`, `candidates::{Query, rank_cmp}`.
|
||||
- **Changed, crate-internal:** `on_type::on_type_formatting` takes a fifth
|
||||
argument `auto_end: bool` (one caller, `server/formatting.rs`). The inline
|
||||
entry point is now `inline::inline_completions_in_context(ws, uri,
|
||||
position, selected)`; the old three-argument `inline_completions` survives
|
||||
as a `#[cfg(test)]` wrapper so `instantiate.rs`'s test (outside this lane's
|
||||
files) compiles unchanged. `completion::member_answer` takes `snippets`.
|
||||
`tiers::visible_symbols` is `pub(super)`. Fix round: `on_type::begin_owes_an_end(doc, begin_index)`
|
||||
(`pub(crate)`, re-exported from `on_type/auto_end.rs`) is what
|
||||
`inline.rs`'s `begin` ghost gate now asks.
|
||||
- **Changed, protocol-visible:** popup `sortText` digits (table above) — any
|
||||
client or test that pinned `2`/`3`/`4`/`5` for index/template/keyword/word
|
||||
sees `4`/`5`/`6`/`7`; template `sortText` gains a rank; connection items
|
||||
gain `labelDetails` and snippet `textEdit`s. Settings `lucisv.autoEnd`,
|
||||
`lucisv.inlineKeywords` (both boolean, default true, absent = on).
|
||||
- **Outside the file list, flagged:** `editors/vscode/.vscodeignore` gained
|
||||
`typing_test.js` (and `typing.js` in its comment), as the lane brief's
|
||||
pointer to the restart.js/.vscodeignore pattern implied.
|
||||
- No request to the parser, semantic or formatter crates.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] auto-`end` on Enter: server (`on_type/auto_end.rs`, setting, wire) and
|
||||
extension (`typing.js`, `extension.js`, `package.json`)
|
||||
- [x] clock+reset templates (ghost + popup order)
|
||||
- [x] current-file ranking (`completion/buffer.rs`, tier table)
|
||||
- [x] keyword ghosts (`inline/keywords.rs`, setting, extension bridge fix)
|
||||
- [x] port items (`completion/connection.rs`, `member.rs`)
|
||||
- [x] unit, e2e and node tests; VS Code README; TODO §68.1 ticked
|
||||
- [ ] confirmed in a running VS Code (see QA log — nobody has seen it yet)
|
||||
|
||||
## Work log
|
||||
|
||||
- **2026-11-17 (dev, Opus 5.5).** All five deliverables.
|
||||
- `on_type/auto_end.rs` (new child module of `on_type.rs`): the begin-newline
|
||||
answer; `on_type_formatting` tries it first when `auto_end` and falls back
|
||||
to the unchanged indent answer. Old on-type tests pass `false`, so their
|
||||
pins are untouched; 15 new tests (steal case, balanced, inner-closed with
|
||||
outer missing, label + comment, wrapped header, `end else begin`, case
|
||||
item, tabs, CRLF, last line, setting off, non-begin lines, text carried
|
||||
down, begin two lines up).
|
||||
- `templates.rs`/`inline.rs`/`completion`: with-reset first; template
|
||||
`sortText` by registry rank (the label alone sorted `always @(*)` first).
|
||||
- `completion/buffer.rs` (new): tiers 2 and 3; `word_tier` reads only the
|
||||
table now. Decision: the typed token itself is not offered back (golden
|
||||
`the_short_answers_are_what_they_always_were` updated, reasoned in place).
|
||||
- `inline/keywords.rs` (new): keyword ghosts. Deviation from the brief's
|
||||
"proper prefix of a keyword": a finished keyword only extends across `_`.
|
||||
Found and fixed the `selectedCompletionInfo`/trigger-kind serialization
|
||||
gap in the client bridge.
|
||||
- `completion/connection.rs` (new) + `member.rs`: connected ports kept and
|
||||
marked, snippet entries, pre-fill; parameters treated the same way.
|
||||
- Extension: `typing.js` + `typing_test.js` (35 checks), wired in
|
||||
`extension.js` (middleware + change listener), two settings in
|
||||
`package.json`, README feature table and settings.
|
||||
- `smoke.js` not changed: no existing probe's expectation moved (smoke run
|
||||
recorded in the report).
|
||||
|
||||
- **2026-11-17 — fix round 2026-11-17 (dev, Opus 5.5)**, after QA and the
|
||||
lead's rulings:
|
||||
1. `owes_an_end`: closed also when the matched `end` sits at the `begin`'s
|
||||
own line's indentation; an unmatched `begin` in a branched `` `ifdef ``
|
||||
region arms nothing (`branched_regions`). Tests:
|
||||
`a_gnu_style_begin_already_closed_under_itself_gets_no_end`,
|
||||
`qa_ifdef_branches_sharing_one_end_get_no_second_end` (both QA repro
|
||||
cases), `an_ifdef_with_no_else_still_arms_the_answer`.
|
||||
2. "Extension bridge" assumption reworded: nothing was broken.
|
||||
3. Keyword ghost: none for a word that is exactly a name the buffer
|
||||
declares (`Semantics::symbols()` scan).
|
||||
4. An explicit popup selection skips the finished-keyword rule
|
||||
(`reserved_extension`).
|
||||
5. A selection whose range is not exactly the typed word is read as absent.
|
||||
6. `typing.js` strips trailing `/* … */` comments too (4 new checks).
|
||||
7. The inline `begin` ghost gate asks `on_type::begin_owes_an_end` (new
|
||||
`pub(crate)` re-export), so the stealing case ghosts its `end`; test
|
||||
`a_begin_typed_inside_a_balanced_block_still_offers_its_end`.
|
||||
Known limits 6–11 written into Assumptions.
|
||||
|
||||
## QA log
|
||||
|
||||
- **2026-11-17 (QA, Opus 5.5).** Verdict: **pass with findings** — no
|
||||
MUST-FIX. Two SHOULD-FIX, the rest NOTEs for the lead.
|
||||
|
||||
**Gates (re-run by QA).** `cargo fmt --check` clean. Guarded `cargo clippy
|
||||
-p lucisv_server --all-targets`: 0 warnings. Guarded `cargo test -p
|
||||
lucisv_server`: 1813 unit passed / 36 ignored, e2e 102 / 2 ignored, grammar
|
||||
3, opentitan_references 0 / 2 ignored (guard exit 0); after the QA tests
|
||||
below, 1816 unit. `node --test editors/vscode/*_test.js`: 9 files pass
|
||||
(typing_test 35 checks, 48 with QA's). Release build +
|
||||
`node editors/vscode/smoke.js target/release/lucisv-server`: OK, 67
|
||||
messages.
|
||||
|
||||
**Scope.** Diff touches only the §68.1 file list plus the flagged
|
||||
`.vscodeignore` line; no parser/formatter/linter/semantic change.
|
||||
(`gemini_review.md` at the root is untracked but dated 2026-10-19 — not
|
||||
this lane's.) Production lines (before `mod tests`): `auto_end.rs` 184,
|
||||
`keywords.rs` 242 (125 of them the Verilog word table), `buffer.rs` 68,
|
||||
`connection.rs` 55, `inline.rs` 331 (was 319), `on_type.rs` 361 (354),
|
||||
`completion/mod.rs` 287 (245), `member.rs` 209 (187), `tiers.rs` 162 (186),
|
||||
`settings.rs` 240 (234), `templates.rs` 326 — none near 600; no new
|
||||
function over 80 lines. No `unwrap`/`expect`/`panic!` in added non-test
|
||||
code; `auto_end.rs` indexes `tokens[...]` with indices bounded by
|
||||
construction (`prev < first <= begin < len`).
|
||||
|
||||
**How.** A Python stdio LSP driver against the release binary, and the same
|
||||
driver against a release build of `HEAD` (exported with `git archive`, own
|
||||
target dir) for before/after; sabotage-free throwaway copy for the corpus
|
||||
sweep. Scripts and outputs: the QA scratchpad `qaA/` (`autoend.py`,
|
||||
`ghosts.py`, `ports.py`, `perf.py`, `labels.py`, `starve.py`).
|
||||
|
||||
**Auto-`end`.** 46 hand cases applied to the buffer and read: nested
|
||||
stealing inside a balanced `always_comb`, case items, generate `if`/nested
|
||||
`for … begin : g`, function/task/class method, `fork … join`, `begin :
|
||||
label` (any spacing), `begin // c`, `begin /* c */`, `else begin`, `end
|
||||
else begin`, wrapped `else if (b &&\n c) begin`, `@*`, `@(*)`, `#5 begin`,
|
||||
`assert … else begin`, `unique if`, `blk: begin`, header on the line above
|
||||
the `begin`, tabs, CRLF, last line with and without a final newline,
|
||||
whitespace-only new line with the cursor mid-indent — all write the right
|
||||
`end` at the right column. Declines (and **the declined answer is
|
||||
byte-identical to `HEAD`'s indent answer** in every case): balanced block,
|
||||
`begin` in a comment / string / escaped identifier / attribute, `` `define
|
||||
`` line (with and without `\` continuation), `begin end` on one line, text
|
||||
carried down, two blank lines, a buffer that does not lex. `autoEnd=false`
|
||||
equals `HEAD` in all 46. Idempotence: applying each answer and asking again
|
||||
at the same spot never writes a second `end`. **Corpus sweep** (860 files,
|
||||
every one of 8 235 lines ending in `begin`, Enter simulated after it):
|
||||
**0 spurious `end`s**; positive control (file truncated after its first
|
||||
`begin`): 512/525 armed; 0 corpus files have a permanently unmatched
|
||||
`begin`. Timing: < 1 ms per answer.
|
||||
|
||||
**Ghost/popup templates.** `always_ff @(` ghosts with-reset then clock-only;
|
||||
`always @(` with-reset, clock-only, `*`; popup `alw` in `.sv`: `always_ff
|
||||
with reset`, `always_ff @(posedge clk)`, `always_comb begin/end`; in `.v`:
|
||||
with-reset, clock-only, `@(*)`. Snippet syntax well-formed, tab stops 1, 2
|
||||
(mirrored `$2` in the popup body), 3/4, `$0`.
|
||||
|
||||
**Ranking.** Tier digits match the table; dedup by first push. Labels
|
||||
offered at 68 positions in `ibex_core.sv` (mid-word and word-end): **none
|
||||
lost** against `HEAD`. Timing per completion (20 requests, minus an empty
|
||||
session; two runs each), HEAD → NEW: `picorv32.v` `a` 0.25/0.29 →
|
||||
0.43/0.35 ms, `r` 0.36/0.33 → 0.50/0.58; `ibex_core.sv` `a` 0.09/0.22 →
|
||||
0.27/0.33, `r` 0.65/0.63 → 0.71/0.74. Sub-millisecond either way.
|
||||
|
||||
**Keyword ghosts.** None in a line/block comment, an unterminated string,
|
||||
after `.`/`::`/backtick, for `$dis`, or mid-word; `.v` gets `always` /
|
||||
`localparam` (no `logic`); each setting off independently. Selection
|
||||
present with a keyword → that keyword over its range; with a non-keyword →
|
||||
nothing. **The extension bridge is real**: `vscode-languageclient` 9.0.1
|
||||
`asInlineCompletionParams` passes `context` through
|
||||
(`InlineCompletionContext.create(triggerKind, selectedCompletionInfo)`),
|
||||
and `middleware.provideInlineCompletionItems(document, position, context,
|
||||
token, next)` is the hook it calls.
|
||||
|
||||
**Port items.** Unconnected first, connected after with `connected`
|
||||
(including a port connected *after* the cursor and a port connected twice);
|
||||
`.name(${1})`, pre-filled only from a visible net/var/port (a same-named
|
||||
`localparam` is not used for a port; a `clk` in a named block or another
|
||||
module of the file is not used); `#(.` pre-fills from a `localparam`;
|
||||
escaped port → bare name; `.*` present → fine; unknown module → empty;
|
||||
`.cl|(x)` → bare; no snippet support → bare everywhere.
|
||||
|
||||
**Findings.**
|
||||
1. **SHOULD-FIX — a second `end` in complete code when the file holds
|
||||
another unmatched `begin` and this block's `end` is not at the owner's
|
||||
column.** The accepted heuristic, but the GNU layout makes it reachable
|
||||
in valid code: `` module m;\n`ifdef A\n always @(posedge clk) begin\n`else\n always @(posedge clk or negedge rst) begin\n`endif\n if (x)\n begin\n|\n y <= 1;\n end\n end\nendmodule `` → ` end` written under the `if`, so the file
|
||||
now has one `end` too many. Same with the cursor after the *first*
|
||||
`` `ifdef `` branch's `begin` (an `end` lands inside branch A). Any
|
||||
mid-edit unmatched `begin` above has the same effect on a GNU-style
|
||||
block below. Corpus exposure measured at 0 (no corpus file is
|
||||
permanently unbalanced). Suggested: also treat the `begin` as closed
|
||||
when its matched `end` starts its line at the `begin`'s own line
|
||||
indentation. Lead to rule.
|
||||
2. **SHOULD-FIX (docs) — the "Extension bridge" assumption overstates the
|
||||
bug it fixes.** The server *does* decode VS Code's array-shaped range and
|
||||
trigger kind 0 (serde reads a struct from a sequence); before the bridge
|
||||
the request did not fail and the template ghosts did not die. The bridge
|
||||
is still right (spec spelling, correct trigger kinds). Pinned by
|
||||
`qa_an_array_shaped_range_and_a_zero_trigger_kind_still_decode`. The
|
||||
README paragraph should say so.
|
||||
3. NOTE — keyword ghosts with no popup open fire on declared names and in
|
||||
expression position: `assign out = in` → `put`, `x = re` → `turn`
|
||||
(`return` is ahead of `reg` in `PRIORITY`; `.sv` only), `x = ou` →
|
||||
`tput`, `x = al` → `ways_ff`. With the popup open VS Code's selection
|
||||
is normally the exact-match signal, which silences the ghost. Lead to
|
||||
rule whether an exact declared name or a non-statement position should
|
||||
suppress it.
|
||||
4. NOTE — the finished-keyword rule also applies to an explicit popup
|
||||
selection: typed `end` with `endmodule` selected → no ghost (spec says
|
||||
the ghost follows the selected item). Preview only; the popup accepts
|
||||
it anyway.
|
||||
5. NOTE — a `selectedCompletionInfo` whose range is elsewhere is echoed
|
||||
back as the item range (VS Code would drop it); one missing `text`
|
||||
fails the whole request with -32602 (pre-existing decode behaviour).
|
||||
6. NOTE — `LIMIT` starvation moved: with ≥ 512 names in *this file*
|
||||
matching a one-letter prefix (synthetic: 600 `logic aN;` in another
|
||||
module), templates and keywords fall out of the answer (`HEAD` kept
|
||||
them; `isIncomplete` is true, so the second letter re-asks). Not seen on
|
||||
real files (largest: 220 items for `r` in `ibex_core.sv`).
|
||||
7. NOTE — the typed token itself is skipped by tier 3 even mid-word, so a
|
||||
word the file uses exactly once and declares nowhere drops out while the
|
||||
cursor is inside it (68-position check found no case in `ibex_core.sv`).
|
||||
8. NOTE — `fork … join` body: `initial fork\n begin` + Enter gives an
|
||||
8-space body over a 4-space `end`; the body indent is the nesting
|
||||
model's (identical to `HEAD`'s plain answer), not the lane's.
|
||||
9. NOTE — pre-fill accepts a signal declared *after* the instance
|
||||
(`sub u (.);\n logic clk;` → `clk(${1:clk})`).
|
||||
10. NOTE — `typing.js` strips `//` comments only: `begin /* c */` + Enter
|
||||
gets an `end` with `editor.formatOnType` on (server answers) but not
|
||||
with it off (extension never asks).
|
||||
11. NOTE (unverifiable here) — the last-line answer is one edit whose
|
||||
range contains the cursor; with `editor.formatOnType` on, VS Code will
|
||||
likely leave the cursor after the `end`, not on the body line (the
|
||||
extension path puts it back itself). Needs a running VS Code, as do:
|
||||
the one-step undo, the extension's `didChange`-before-request ordering
|
||||
(reading `vscode-languageclient` 9.0.1 it holds: the incremental
|
||||
`didChange` is sent from microtasks before the `setTimeout(0)` task),
|
||||
and the ghost following the popup.
|
||||
|
||||
**QA tests added.** `on_type/auto_end.rs`:
|
||||
`qa_asking_again_after_the_answer_is_applied_adds_no_second_end` (9
|
||||
armed shapes), `qa_a_declined_newline_is_exactly_the_plain_indent_answer`
|
||||
(9 declining shapes, incl. `` `define ``, `` `ifdef `` both branches,
|
||||
string, escaped `\begin`). `inline/keywords.rs`:
|
||||
`qa_an_array_shaped_range_and_a_zero_trigger_kind_still_decode`.
|
||||
`editors/vscode/typing_test.js`: `qaEdges` (13 checks: multi-cursor, redo,
|
||||
no editor, refused edit, CRLF position, pastes, context without a range).
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-11-17 — lead (after dev, QA, one fix round)
|
||||
|
||||
Accepted. QA found no corruption, crash or spec violation; both SHOULD-FIX
|
||||
items and the rulings below went into the fix round, and the dev's gates
|
||||
after it are green (unit 1 823, e2e 102, node 9 files, smoke OK).
|
||||
|
||||
Rulings recorded:
|
||||
|
||||
- **Auto-`end` is armed by any unclosed `begin` at or before this one**, not
|
||||
by this `begin`'s own span (the stack matcher lets a new inner `begin`
|
||||
steal the outer `end`). Closed means: matched by an `end` that starts its
|
||||
line at the indentation the answer would write, or at the `begin`'s own
|
||||
line's (GNU layout). A `begin` unclosed inside an `ifdef` region with an
|
||||
`else`/`elsif` arms nothing — the shared `end` after `endif` is its `end`.
|
||||
- **No keyword ghost for a word that is exactly a name this buffer
|
||||
declares** (`in`, `re`, `out` as signals stay quiet). Anything else that
|
||||
is a keyword prefix ghosts, in any position — the owner asked for
|
||||
"always".
|
||||
- **An explicit popup selection wins** over the "finished keyword only
|
||||
extends across `_`" rule; a selection whose range is not the typed word
|
||||
is ignored.
|
||||
- Accepted limits (in Assumptions): LIMIT 512 can drop templates/keywords
|
||||
in a 600-same-prefix buffer; the token under the cursor is not offered
|
||||
back; port pre-fill accepts a later declaration; the last-line answer is
|
||||
one edit that contains the cursor.
|
||||
|
||||
**Not verified by anyone:** every behaviour in a running VS Code — the
|
||||
cursor after `begin` + Enter (formatOnType on and off), one-step undo, the
|
||||
ghost following the popup selection, the dimmed `connected` detail. The
|
||||
list is in the dev's report and the QA log; it is the owner's acceptance.
|
||||
@@ -282,6 +282,10 @@ signatures.
|
||||
costs 1 and 1. `docs/features/header-recovery/README.md` is the feature;
|
||||
the mechanism in *this* README — item and statement lists — is
|
||||
unchanged and still handles everything outside a header.
|
||||
- [x] **2026-11-17, `docs/features/port-entry-grace/README.md`:** an
|
||||
unfinished connection (`.`, a `.name(` left open at the end of its line,
|
||||
a trailing `,`) costs one diagnostic inside its own entry and the list
|
||||
reads on to the entries after it.
|
||||
|
||||
## Work log
|
||||
|
||||
|
||||
@@ -0,0 +1,953 @@
|
||||
# format-styles
|
||||
|
||||
## Goal
|
||||
|
||||
Let a project pick a house layout by name instead of living with lucisv's
|
||||
one: `[format] style = "<name>"` in `lucisv.toml`, `--style <name>` on the
|
||||
command line, and a `lucisv.format.style` drop-down in VS Code. The owner
|
||||
asked for the formatter to "adapt to the current file's way of handling when
|
||||
to start newline / what to group / how to align the ports", with a drop-down
|
||||
of common styles (ANSI, Google, Microsoft, NXP) as the fallback if adapting
|
||||
is too ambiguous, and for the rules to be easy to read in the source. So
|
||||
this ships both: six named presets, each one row of a table in
|
||||
`crates/vlog_formatter/src/style.rs`, and `auto`, which lays each file out in
|
||||
the preset it is already closest to. The default, `lucisv`, is byte-for-byte
|
||||
the layout every earlier release produced — proven over the corpus and
|
||||
OpenTitan, not asserted.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A style only moves whitespace.** Every switch chooses between a space and
|
||||
a line break in front of a token, a deeper or shallower indent, or padding.
|
||||
The token stream is identical under every style, which is why `verify.rs`
|
||||
is untouched (CLAUDE.md invariant 4: nothing was widened).
|
||||
- **An explicit `indent`/`line-length` beats the preset's**, from whichever
|
||||
rung it came. A preset is a starting point; a number someone wrote down is a
|
||||
decision. `--style ansi` with a `lucisv.toml` that says `indent = 2` is ANSI
|
||||
at 2 spaces.
|
||||
- **`lucisv` and `auto` do not count as "a chosen style" for the editor's
|
||||
`tabSize` rung.** VS Code sends `lucisv` when nobody touched the drop-down,
|
||||
and `auto` picks a layout but no size, so both leave today's
|
||||
`tabSize`-beats-default behaviour exactly as it was. Any other style
|
||||
outranks `tabSize` (an editor default of 4 must not silently undo
|
||||
`google`'s 2).
|
||||
- **`case` items and `do` keep `begin` on their own line's end in every
|
||||
style** — `0: begin`, `do begin`. clang-format's Microsoft style does the
|
||||
same (`AfterCaseLabel: false`), and an Allman `0:` / `begin` reads as a
|
||||
label with nothing under it.
|
||||
- **The `else` switches govern `if`/`else` statements and generate `if`/`else`
|
||||
only.** An immediate assertion's `else` (`assert (a) … else …`), a
|
||||
constraint's `else` and `randsequence`'s keep the layout they always had.
|
||||
`else_after_label` is the guides' one exception: after `end : label`,
|
||||
`google` and `lowrisc` start `else` on a new line (Google "Eschatology",
|
||||
lowRISC "Begin / End"); `lucisv` keeps `end : l1 else begin`, as it always
|
||||
printed.
|
||||
- **"One entry per line" governs module/interface/program headers (parameter
|
||||
and port lists, whenever non-empty) and instances' *named* parameter and
|
||||
connection lists.** A positional override `#(16)` and an ordered connection
|
||||
list `(a, b)` keep fitting on one line, as both guides show. `(.*)` alone
|
||||
is broken like any other named list.
|
||||
- **`Wrap` (two-level list indent) applies to the same lists**, header and
|
||||
instance; function/task port lists and expression lists are untouched.
|
||||
- **`Alignment::Always` reuses the alignment planner unchanged** except for
|
||||
one question it skips — "did the author pad this?". Every other refusal
|
||||
(a group of one, nothing to pad, a group too wide for the line, a row with
|
||||
a comment in it, a blank line or comment between tables) still applies.
|
||||
Its connection spelling is Verible's (`.clk (clk)`, one space before the
|
||||
widest row's `(`); lowRISC's guide writes the widest row tight
|
||||
(`.req_ready_o(req_ready)`). Not modelled: one more axis for one guide's
|
||||
one column. A second lowRISC deviation: a comment line inside a table ends
|
||||
lucisv's alignment group (both layouts are fixed points only because the
|
||||
groups are drawn the same on every pass), where lowRISC keeps aligning
|
||||
across it.
|
||||
- **Known limit — a declaration of several instances under `OnePerLine`.**
|
||||
`p1 u8 (.a(a)), u9 (.a(b));` breaks into the hanging layout every style
|
||||
has always used for several instances: under `google` the connections land
|
||||
at 8, `u9` and each `)` at 4, the opening line at 2 (`microsoft`: 4/12/8).
|
||||
The `)` of each instance is at its instance's column, not the opening
|
||||
line's. Fixing it means a new multi-instance layout for every style, the
|
||||
default included; not done here.
|
||||
- **`auto` never guesses an indent or a width.** It competes the presets'
|
||||
layout switches at the config's own indent and width. Guessing an indent
|
||||
from a file whose formatted output has a different indent is exactly the
|
||||
kind of detector whose second run disagrees with its first. Its measure is
|
||||
the number of lines whose bytes change, indentation included — see
|
||||
"auto" below for why the first round's indentation-blind measure was wrong.
|
||||
- **Under `auto`, a buffer that does not parse and has no remembered preset
|
||||
is laid out in the default (`lucisv`) layout** by range, selection and
|
||||
on-type formatting — the formatter has nothing to resolve from. The
|
||||
language server remembers the preset of each recently formatted document
|
||||
(the 64 most recent), so this only happens before the first successful
|
||||
resolve of a buffer. The CLI's `--lines` has no memory and refuses a file
|
||||
that does not parse anyway.
|
||||
|
||||
## The axes
|
||||
|
||||
Surveyed against what `format/` actually decides today (2026-11-19):
|
||||
|
||||
| candidate | verdict | why |
|
||||
|---|---|---|
|
||||
| indent width | **kept** (`indent`) | already a `Config` field; a preset supplies the default |
|
||||
| line length | **kept** (`line_length`) | same |
|
||||
| `begin` same line / own line | **kept** (`begin`) | one choke point (`Fmt::body_after`, `Fmt::gen_block`): a space or a `HardLine` before `begin` |
|
||||
| `else` after `end` | **kept** (`else_keyword`) | one condition in `if_stmt` and in `gen_if` |
|
||||
| `else` after a labelled `end` | **kept** (`else_after_label`) | the same condition, asked of `end : label` — both guides' exception |
|
||||
| header/connection lists: fit vs one per line | **kept** (`port_lists`) | the lists already had a `force_break` flag (`Fmt::style_breaks`) |
|
||||
| list entries at 1 or 2 levels | **kept** (`list_indent`) | Google's guide and Verible's `wrap` both indent header lists 4; one `Indent` more in `delimited_at`, and the alignment budget follows (`Fmt::list_depth`) |
|
||||
| alignment of ports, connections, `parameter`s | **kept** (`alignment`: `Infer` / `Always`) | one skipped question in `align::plan`; `Never` was dropped — no preset needed it |
|
||||
| closing `);` hugging the last port | rejected | no guide wants it; every guide found puts `)` on its own line |
|
||||
| space before `(` in instances / calls | rejected | every source agrees: space after the instance name, none after a function name — already lucisv's |
|
||||
| spaces around `:` in ranges | rejected | both guides want `[7:0]` tight — already lucisv's |
|
||||
| consecutive blank lines kept | rejected | the parser records `blank_before: bool`, not a count; would need a parser change outside this lane, and no guide asks for more than one |
|
||||
| `case` item indentation | rejected | both guides indent items one level — already lucisv's |
|
||||
| net/variable declaration alignment, assignment alignment | rejected | lucisv has no such alignment group today; building one is a feature of its own, not a style switch |
|
||||
|
||||
## The presets
|
||||
|
||||
The same table is the `PRESETS` constant in `style.rs`, one row per preset.
|
||||
|
||||
| style | indent | width | `begin` | `else` | `else` after `end : l` | lists | list indent | columns | modelled on | confidence |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| `lucisv` | 2 | 100 | same line | same line | same line | fit | block | infer | lucisv itself | exact (byte identity) |
|
||||
| `google` | 2 | 100 | same line | same line | own line | one per line | wrap | infer | Google Verilog Style Guide | high |
|
||||
| `lowrisc` | 2 | 100 | same line | same line | own line | one per line | block | always | lowRISC Verilog Coding Style Guide | high (two deviations, above) |
|
||||
| `ansi` | 4 | 80 | own line | own line | own line | fit | block | infer | Artistic Style / iStyle `--style=ansi` (Allman) | medium for `begin`/`else`; width a guess |
|
||||
| `microsoft` | 4 | 120 | own line | own line | own line | one per line | block | infer | clang-format `Microsoft` base style | guess |
|
||||
| `nxp` | 2 | 80 | same line | own line | own line | one per line | block | always | a conservative RTL house style | guess |
|
||||
|
||||
Sources consulted (2026-11-19):
|
||||
|
||||
- **Google Verilog Style Guide** (google.github.io/styleguide/verilogguide.html,
|
||||
read from the `google/styleguide` gh-pages `verilogguide.md`): "Line
|
||||
Length" (100), "Indentation" (2, no tabs), "Eschatology" (`begin` on the
|
||||
keyword's line, `end else begin`, but `else` on a new line after a labelled
|
||||
`end`), "Line Wrapping" (4-space continuation),
|
||||
"Module Header Definition Examples" and "Use named ports" (one entry per
|
||||
line, entries at 4 spaces, closing paren at column zero), "Tabular
|
||||
Alignment" (alignment *recommended* "where it is reasonable"; the guide's
|
||||
own header examples are not name-aligned — hence `infer`).
|
||||
- **lowRISC Verilog Coding Style Guide** (lowRISC/style-guides,
|
||||
VerilogCodingStyle.md), whose summary says it defaults to "being consistent
|
||||
with Google's C++ Style Guide": "Line Length" 100, "Indentation" 2,
|
||||
"Begin / End" `end else begin` (and the same labelled-`end` exception),
|
||||
"Module Declaration" one port per line, `);` at column zero, its examples
|
||||
aligned in columns (shown, not required), "Module Instantiation"
|
||||
connections *required* "aligned in tabular style", at 2 spaces. lucisv has
|
||||
one alignment switch for ports, connections and parameters, so the row
|
||||
says `always` for all three: the requirement for connections, the examples
|
||||
for ports.
|
||||
- **ANSI**: the iStyle Verilog formatter's README (a port of Artistic Style)
|
||||
lists `--style=ansi` and describes its bracket-breaking mode as "ANSI C/C++
|
||||
style", default indent 4. No Verilog guide by that name exists that we
|
||||
found; 80 columns is our guess.
|
||||
- **Microsoft**: no Microsoft Verilog/SystemVerilog guide found. clang-format's
|
||||
`getMicrosoftStyle` (llvm-project `clang/lib/Format/Format.cpp`):
|
||||
`ColumnLimit = 120`, `IndentWidth = 4`, braces after control statements and
|
||||
before `else` on their own lines; LLVM's base sets
|
||||
`VerilogBreakBetweenInstancePorts = true`. Whether clang-format's own
|
||||
Verilog mode wraps `begin` like a brace was not verified.
|
||||
- **NXP**: no public NXP Verilog style guide found (searched 2026-11-19).
|
||||
The preset is lucisv's guess at a conservative ASIC house style, and the
|
||||
source and the docs say so.
|
||||
|
||||
## Safety sweeps
|
||||
|
||||
Trees: the 860-file corpus (`~/.cache/lucisv-corpus`) and OpenTitan's `hw/`
|
||||
(`~/.cache/lucisv-opentitan-full/hw`, 4 061 files with symlinks followed) —
|
||||
4 921 `.v`/`.sv`/`.vh`/`.svh` files, copied to scratch (the trees are never
|
||||
written). Commands: `tools/style_sweep.sh -b <lucisv> -w <scratch> <trees>`
|
||||
(the CLI, in place, `--no-cache --no-config --no-gitignore`, every run under
|
||||
`tools/guard.sh`) and `cargo run --release -p vlog_formatter --example
|
||||
auto_sweep -- <trees>` (under `guard.sh`). 2026-11-19, final binaries.
|
||||
|
||||
**Default byte identity.** Both trees formatted with the 0.65.4 binary
|
||||
(`d574969`, built before any edit) and with this lane's binary, no flag and
|
||||
`--style lucisv`: `diff -r` is empty both ways (0 lines over 4 921 files;
|
||||
identical summaries, 4 817 reformatted / 90 unchanged / 14 failed, the 14 the
|
||||
same parse errors). The snapshot + idempotency suite is unchanged and green.
|
||||
|
||||
| style | files | parse errors | verification errors | crashes | not idempotent |
|
||||
|---|---|---|---|---|---|
|
||||
| `lucisv` | 4 921 | 14 | 0 | 0 | 0 |
|
||||
| `google` | 4 921 | 14 | 0 | 0 | 0 |
|
||||
| `lowrisc` | 4 921 | 14 | 0 | 0 | 0 |
|
||||
| `ansi` | 4 921 | 14 | 0 | 0 | 0 |
|
||||
| `microsoft` | 4 921 | 14 | 0 | 0 | 0 |
|
||||
| `nxp` | 4 921 | 14 | 0 | 0 | 0 |
|
||||
| `auto` | 4 921 | 14 | 0 | 0 | 0 |
|
||||
|
||||
"Not idempotent" is `--check` with the same style over the formatted copy
|
||||
(files it would reformat). The 14 parse errors are the baseline's own, under
|
||||
every style.
|
||||
|
||||
**`auto` proof sweep** (`auto_sweep`, fix-round binary): 4 921 files, 14
|
||||
refused (the parse errors), 0 crashes, **0 files whose second or third auto
|
||||
format changed a byte, 0 files whose second or third run named a different
|
||||
preset**. Picked: `lucisv` 4 050, `lowrisc` 645, `google` 92, `microsoft` 92,
|
||||
`nxp` 24, `ansi` 4. (First round, indentation-blind measure: `lucisv` 3 875,
|
||||
`lowrisc` 484, `google` 465, `microsoft` 46, `nxp` 29, `ansi` 8; before
|
||||
`canonical` existed that sweep showed 47 renames, all `lowrisc` → `lucisv`,
|
||||
identical bytes.)
|
||||
|
||||
**Cost of `auto`**: see the latency table under "auto".
|
||||
|
||||
The tables above are from the fix-round binaries (2026-11-19): the per-style
|
||||
table, the default byte identity and the cross-preset matrix below were all
|
||||
re-run after the fix round and came out the same, except the `auto` row of
|
||||
the matrix.
|
||||
|
||||
## auto
|
||||
|
||||
**The measure.** `auto` formats the file with every preset (at the
|
||||
configured indent and width) and keeps the output with the fewest lines whose
|
||||
bytes change — the multiset difference of lines, **indentation included** —
|
||||
ties to the earlier preset. The first round compared lines with indentation
|
||||
stripped and used indentation only to break ties; QA showed that lets a
|
||||
preset that saves three layout lines beat one that keeps 741 lines'
|
||||
indentation (F1). Counting every changed line is also simply what the docs
|
||||
always said.
|
||||
|
||||
**`auto` picks a layout for the configured indent and width; it never infers them — set `indent` to match the file first.** Because every re-indented line counts as changed, a file written at another indent is closest to whichever preset changes the fewest of its lines once they are all re-indented: a 4-space Allman file (formatted with `--style ansi`) run through `--style auto` at the default indent 2 comes out in the cuddled `lucisv` layout, while with `indent = 4` it stays Allman (and with `line-length = 80` as well, byte for byte). (In VS Code the editor's `tabSize` rung supplies the
|
||||
indent when nothing else does, which often matches the file; the CLI has no
|
||||
such rung.) QA measured that 426 of the 4 921 files' auto output changed
|
||||
between the two measures.
|
||||
|
||||
**F1 experiment** (QA's driver, `qa_auto edit`, rebuilt against this tree):
|
||||
200 sampled files (198 with an `endmodule`), each formatted with auto, one
|
||||
construct inserted before `endmodule`, formatted with auto again. "Flips":
|
||||
the named preset changed; "rewritten": lines of the first output no longer
|
||||
present in the second.
|
||||
|
||||
| inserted construct | flips before → after | files with rewritten lines before → after | worst rewrite before → after |
|
||||
|---|---|---|---|
|
||||
| `assign qa_x=qa_y ;` | 0 → 0 | 0 → 0 | 0 → 0 |
|
||||
| cuddled `always_comb if … begin … end else begin … end` | 4 → 0 | 4 → 0 | 741 → 0 |
|
||||
| Allman `begin`/`else` block | 81 → 1 | 21 → 1 | 140 → 3 |
|
||||
| one-line instance `qa_mod qa_u (.a(qa_a), .b(qa_b));` | 14 → 0 | 14 → 0 | 37 → 0 |
|
||||
|
||||
The remaining flip rewrites 3 lines, so no stabiliser beyond the measure was
|
||||
added. ("Before" is QA's run on the first-round binary; "after" re-runs the
|
||||
same driver, so each column starts from its own binary's auto output.) Every
|
||||
second format in both runs was idempotent.
|
||||
|
||||
**Naming costs a pass; formatting does not need it.** `format_source` under
|
||||
auto and `format_auto` (the server's whole-document path) format once per
|
||||
preset until one leaves the file unchanged, and return the winner.
|
||||
`resolve_style`, which *names* the preset, additionally finds the earliest
|
||||
preset that leaves the output as it is (`canonical`), so a second run names
|
||||
the same one; only it pays that pass. Range and selection formatting resolve
|
||||
through the internal `concrete`, which does not name.
|
||||
|
||||
**The server remembers each document's preset** (`lucisv_server/src/
|
||||
auto_style.rs`, owned by the `Server` struct; the 64 most recent documents,
|
||||
no `didClose` hook). Whole-document formatting and the save hook resolve and
|
||||
remember. Range, multi-range and `;` on-type formatting use the remembered
|
||||
preset; with none, they resolve once from the buffer when it parses and
|
||||
remember that; with none and no parse, they use the default layout (F3's
|
||||
case, now confined to a buffer that has never resolved). A typed newline
|
||||
needs no preset and never searches.
|
||||
|
||||
The memory is invalidated (QA R2-1): a document's entry is **forgotten** on
|
||||
`didOpen`, `didClose`, `didRenameFiles` (old and new name),
|
||||
`didDeleteFiles`, and on any request or whole-document format under a named
|
||||
style; **every** entry is forgotten when settings are applied (pushed or
|
||||
pulled) and when a watched-file event names `lucisv.toml`/`.lucisv.toml`. A
|
||||
`didChange` that replaces the whole buffer — rangeless, or one change from
|
||||
the top whose text is the whole result — marks the entry *replaced*: the next
|
||||
request resolves afresh when the buffer parses, and uses the old preset only
|
||||
when it does not (the lead asked for "forget"; marking instead keeps QA's
|
||||
case 8 — a full-sync client's every keystroke is a whole replacement, and
|
||||
forgetting there would drop the preset of a half-typed buffer, the case the
|
||||
memory exists for). QA's `memattack.py`, re-run against this tree's release
|
||||
binaries: cases 1–9 and 11's eviction check OK; case 10 is a request the
|
||||
server rejects as invalid params (`v x.sv`: a raw space is not a valid URI —
|
||||
a driver issue, not the memory); case 11's last check expected the *old*
|
||||
stale preset after a full-text change ("stale by design") and now gets the
|
||||
re-resolved one, which is the R2-1 fix.
|
||||
|
||||
**Latency** on `pinmux_reg_top.sv` (42 192 lines; auto picks `lowrisc`),
|
||||
release, `qa_auto time2`, two runs agreeing within 5 %:
|
||||
|
||||
| request | before (QA) | after |
|
||||
|---|---|---|
|
||||
| whole-document format, unformatted | 2.30 s | 2.40 s (unchanged: it must search) |
|
||||
| selection / on-type `;` on the formatted buffer | 1.36 s | 0.07 s remembered; 1.24 s for the first request with no memory |
|
||||
| selection / on-type `;` on the unformatted buffer | 3.0 s | 0.10 s remembered; 2.55 s for the first request with no memory |
|
||||
| (selection under a named preset, for scale) | 0.094 s | 0.064 s |
|
||||
|
||||
## Cross-preset stability
|
||||
|
||||
Formatting with A, then B, then A again lands exactly where A alone did —
|
||||
`A(B(A(x))) == A(x)` — **for every pair where A aligns by rule
|
||||
(`lowrisc`, `nxp`)**. Where A *reads* alignment from the source (`Infer`:
|
||||
`lucisv`, `google`, `ansi`, `microsoft`), the identity can fail, and for
|
||||
one root cause: B changed which runs are aligned, and A then faithfully keeps
|
||||
what it finds. B either *wrote* columns (B is `Always`) or *dropped* a table
|
||||
whose padded width no longer fit B's narrower line or deeper indent (an
|
||||
aligned group that overflows falls back to flush as a whole) — e.g. `lucisv`
|
||||
via `ansi` (80 columns, 4 spaces), `microsoft` via `lucisv` (100 < 120). Every
|
||||
other decision is a function of the AST and the config, so it comes back.
|
||||
|
||||
The differences are alignment **plus its knock-on**, not alignment alone.
|
||||
QA classified every differing hunk in 20 files per pair (QA log, F5):
|
||||
`microsoft` via `lucisv` and `ansi` via `nxp` are all padding or the list
|
||||
breaks alignment forces; in `lucisv` via `lowrisc`, 261 of 265 hunks are, and
|
||||
the other 4 (18 lines, e.g. `flash_phy_core.sv:230`, `kmac_entropy.sv:297`)
|
||||
are a named parameter override `#(.Width(HashCntW))` that was broken in
|
||||
`lucisv(x)` and comes back joined once its instance's connection list is
|
||||
aligned — the existing coupling between an instance's head and its
|
||||
connection list, set off by the alignment. This is the alignment feature's
|
||||
design — "a file written without alignment never grows any" — not a style
|
||||
bug.
|
||||
|
||||
Measured (files of 4 921 where `A(B(A(x))) != A(x)`; rows A, columns B):
|
||||
|
||||
| A \ B | lucisv | google | lowrisc | ansi | microsoft | nxp | auto |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| `lucisv` | — | 0 | 1 288 | 106 | 0 | 1 281 | 0 |
|
||||
| `google` | 0 | — | 1 288 | 106 | 0 | 1 281 | 0 |
|
||||
| `lowrisc` | 0 | 0 | — | 0 | 0 | 0 | 0 |
|
||||
| `ansi` | 0 | 0 | 1 244 | — | 0 | 1 244 | 0 |
|
||||
| `microsoft` | 20 | 20 | 1 296 | 119 | — | 1 290 | 20 |
|
||||
| `nxp` | 0 | 0 | 0 | 0 | 0 | — | 0 |
|
||||
| `auto` | 857 | 1 987 | 1 192 | 1 832 | 1 844 | 2 315 | — |
|
||||
|
||||
The `Always` rows are all zero; every non-zero `Infer` cell is in a column
|
||||
that writes columns (`lowrisc`, `nxp`) or is narrower/deeper than the row
|
||||
(`ansi` for the 100-column rows; 100-column `lucisv`/`google`/`auto` for
|
||||
`microsoft`'s 120). The `auto` row is non-zero by definition: auto keeps the
|
||||
layout it finds, and B just changed it — `auto(B(auto(x)))` is `B`'s layout
|
||||
(or the nearest preset to it), which is the feature working. What holds for
|
||||
auto is the idempotency above.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes `align::plan`** (own crate): gained a `mode: Alignment`
|
||||
parameter. `Infer` is exactly the old function; the one call site passes
|
||||
the style's mode.
|
||||
- **Promises `vlog_formatter::Config`**: new fields `style: Style` and
|
||||
`auto_style: bool`; `Config::styled(Style)`, `Config::named(&str)`,
|
||||
`Config::style_name()`. `Config::default()` is `Config::styled(LUCISV)` and
|
||||
lays out byte-identically to before. Every external `Config { .., ..Default }`
|
||||
literal keeps compiling.
|
||||
- **Promises `vlog_formatter::resolve_style(source, &Config) -> Config`**: the
|
||||
preset `auto` *names* for a whole file (the canonical one — stable across
|
||||
runs), and **`vlog_formatter::format_auto(source, &Config) ->
|
||||
Result<(String, Style), FormatError>`**: auto's output and the preset that
|
||||
produced it, for a caller that will format ranges of the same buffer
|
||||
later (the server's memory).
|
||||
- **`lucisv_core::config`**: `FileConfig::format_style: Option<&'static str>`,
|
||||
`STYLE_NAMES` (the presets plus `auto`; pinned equal to the formatter's by
|
||||
`args::tests::the_core_style_names_are_the_formatter_presets` in `lucisv`),
|
||||
`parse_style` (the one error message, reused by `--style` and the server).
|
||||
`lucisv_core` still depends on nothing.
|
||||
- **`lucisv_core::cache::Entry`** gained `style: &'static str`; the store line
|
||||
has seven fields (`…\tuvm\tstyle\tversion\tpath`). A six-field line (0.65.x)
|
||||
and a line naming a style this build does not know are dropped
|
||||
individually, like another version's entry. **One edit outside the new
|
||||
test file:** `crates/lucisv/tests/cli.rs`'s `cache_line` helper (which
|
||||
forges store lines) writes the new `lucisv` field — two existing cache
|
||||
tests failed on the old six-field shape otherwise. The lead lifted the
|
||||
ban on that file mid-lane; the edit is two lines.
|
||||
- **Request to the `server-lint`/71.1 lane (`crates/lucisv_server/src/lint.rs`,
|
||||
owned by lane 71.1, not edited here):** `lint.rs:307` resolves the
|
||||
`line-length` rule's width as `file.line_length.or(client.line_length)
|
||||
.unwrap_or(100)`. Under a style with another width (`ansi` 80, `microsoft`
|
||||
120, `nxp` 80) the editor's `line-length` finding and the formatter now
|
||||
disagree. Wanted: fall back to the chosen style's width —
|
||||
`file.format_style.or(client.style).and_then(vlog_formatter::style::preset)
|
||||
.map_or(100, |s| s.line_length)` — the same ladder `format::indent_width`
|
||||
now walks (that one is fixed here, and lint's `tab_width` already calls it).
|
||||
The CLI's `lucisv check` and the MCP `diagnostics` tool already use the
|
||||
style's width.
|
||||
- **Note for the alignment README (not in this lane's scope):** its rule is
|
||||
now the `Infer` mode; `Always` is documented here.
|
||||
- **`editors/vscode/package.json`**: `lucisv.format.style` (enum with one
|
||||
description per entry, default `lucisv`). `extension.js` forwards the whole
|
||||
`lucisv` section already, so it is unchanged.
|
||||
|
||||
- **`crates/lucisv_server/src/server/notification.rs` (lane 71.1's file;
|
||||
allowed by the lead for these lines only, one call each into
|
||||
`auto_style.rs`, nothing else touched):**
|
||||
1. in `handle_notification`, after `let released = self.forget_port_entry(&method, ¬ification);`:
|
||||
`self.auto_styles.notice(¬ification);`
|
||||
2. in the `DidChangeTextDocument` arm, after the `let (text, end) = { … };` block:
|
||||
`self.auto_styles.changed(&uri, &p.content_changes, &text);`
|
||||
3. first line of `apply_settings`: `self.auto_styles.forget_all();`
|
||||
- **`lucisv_core::config::NAMES`** is now `pub` (the two config file names),
|
||||
so the memory recognises a `lucisv.toml` event without a second copy.
|
||||
- **Server (this lane, formatting handlers only):** `auto_style.rs` (new),
|
||||
a field on `Server` (`server/mod.rs`, constructed in `server/startup.rs`),
|
||||
`server/formatting.rs` routing the five entries through it, and
|
||||
`format::whole_document_edit`. Nothing in `state/` or
|
||||
`server/{index,notification,diagnostics}.rs` (lane 71.1's) was touched.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Survey the axes; keep five layout switches plus indent and width
|
||||
- [x] `style.rs`: one `Style` struct, six presets as `const` rows, sources in comments
|
||||
- [x] Axes: `begin`, `else`, lists one-per-line, list indent, alignment
|
||||
- [x] `lucisv` preset byte-identical to 0.65.4 over corpus + OpenTitan
|
||||
- [x] `[format] style`, `--style`, `lucisv.format.style`, MCP; cache key
|
||||
- [x] Per-preset sweeps: no verification errors, no crashes, idempotent
|
||||
- [x] Cross-preset stability measured and explained
|
||||
- [x] Phase 2: `auto`, proof sweep, range/selection use the whole file's style
|
||||
- [x] Docs: root README (Configuration, Named styles), VS Code README
|
||||
- [x] Fix round (QA F1–F8): auto measure counts indentation; server remembers
|
||||
the preset per document; labelled-`end` `else` for google/lowrisc; presets
|
||||
as one table; doc corrections
|
||||
- [ ] Lane 71.1: `lint.rs` line-length width from the style (Handshake request above)
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-11-19 — dev.**
|
||||
|
||||
- Baseline first: built 0.65.4 (`d574969`) before any edit and formatted
|
||||
scratch copies of both trees with it; every "byte-identical" claim below is
|
||||
a `diff -r` against that tree.
|
||||
- `style.rs` holds the whole vocabulary: `Placement`, `PortLists`,
|
||||
`ListIndent`, `Alignment`, the `Style` struct, the six `const` presets and
|
||||
`PRESETS`. Each field's doc has its before/after; each preset's comment says
|
||||
what it is modelled on and how sure.
|
||||
- `format/branch.rs` (new): `if_stmt` moved out of `stmt.rs` and `gen_if` out
|
||||
of `item.rs`, plus `before_keyword` (the space-or-break helper) and
|
||||
`else_cuddles`. `stmt.rs` drops from 604 to 556 production lines, `item.rs`
|
||||
from 472 to 449; the move changed no output (snapshot suite and both tree
|
||||
identities green).
|
||||
- `Fmt::stmt_as_body_from` now calls `body_after(prefix, s, skip, begin)`;
|
||||
`case_item` passes `SameLine`. `gen_block` takes the placement, `gen_case`
|
||||
passes `SameLine`.
|
||||
- `list.rs`: `delimited_dangling` is `delimited_at(.., Block)`; `header_list`
|
||||
uses the style's indent; `style_breaks` and `list_depth` are the two style
|
||||
questions the header and instance code ask.
|
||||
- `align::plan(.., mode)`: `Always` skips `wants_alignment` and nothing else.
|
||||
- Plumbing follows `uvm-utils-indent` everywhere it flows. The CLI and MCP
|
||||
resolve the style first and write explicit `indent`/`line-length` over it;
|
||||
the server's ladder is documented on `format::settings_for`.
|
||||
- **Phase 2.** A per-axis detector (vote on `begin`/`else` placement, port
|
||||
list shape) was designed first and dropped before coding: the formatter
|
||||
itself writes `begin`/`else` in places no switch governs (case items, `do`,
|
||||
after comments, immediate assertions), so votes on the *output* are
|
||||
contaminated by construction and "detect(output) == detect(input)" could
|
||||
only ever be measured, not argued. `auto` instead formats once per preset
|
||||
at the configured indent/width and keeps the output with the least
|
||||
line-multiset difference from the input, indentation compared last; ties go
|
||||
to `PRESETS` order. That is idempotent by construction (argument in
|
||||
`auto.rs`), and naming the *earliest* preset that leaves the output as it is
|
||||
(`canonical`) makes the second run name the same preset too. A first sweep
|
||||
without `canonical` showed 0 byte violations and 47 files whose second run
|
||||
named `lucisv` instead of `lowrisc` (identical bytes) — that is what
|
||||
`canonical` removes.
|
||||
- Cost: `auto` formats a file up to six times (stopping at the first preset
|
||||
that leaves it unchanged, which on an already-formatted file is usually
|
||||
the first); range/selection/on-type formatting under `auto` pay that over
|
||||
the whole buffer to pick the style.
|
||||
|
||||
**2026-11-19 — dev, fix round (QA: PASS WITH FINDINGS).**
|
||||
|
||||
- **F1.** `auto.rs` `distance` is now `(lines whose bytes change, texts
|
||||
differ)`, indentation included; `(0, 0)` still means equal, so the
|
||||
idempotency argument is unchanged. QA's 200-file × 4-construct experiment
|
||||
re-run with QA's own driver: flips 0/4/81/14 → 0/0/1/0, worst rewrite
|
||||
741 → 3 lines (table under "auto"). No stabiliser added: the one remaining
|
||||
flip changes 3 lines. The test that relied on indentation being ignored
|
||||
(`auto_picks_a_layout_never_a_size`) now configures the indent, which is
|
||||
the documented contract.
|
||||
- **F3/F4.** `lucisv_server/src/auto_style.rs`: a 64-entry most-recent list
|
||||
of (URI, preset), on the `Server`. Whole-document format and the save hook
|
||||
resolve (`vlog_formatter::format_auto`) and remember; range, multi-range
|
||||
and `;` on-type use the memory, resolve-and-remember when the buffer
|
||||
parses, else fall back to the default layout (documented). A newline never
|
||||
resolves. `resolve_style` keeps the naming pass; the formatter's own
|
||||
range/selection path (`auto::concrete`) and `format_auto` drop it.
|
||||
Five unit tests and three end-to-end tests (`server/tests/formatting.rs`).
|
||||
- **F2.** New style column `else_after_label`: `OwnLine` for google and
|
||||
lowrisc (and ansi/microsoft/nxp, where `else` is already on its own line),
|
||||
`SameLine` for lucisv. One condition in `branch.rs` (`else_cuddles`), for
|
||||
procedural and generate `if`. Test
|
||||
`else_after_a_labelled_end_starts_its_own_line_in_the_guides`.
|
||||
- **F5–F7.** Cross-preset text now says "alignment plus its knock-on" with
|
||||
QA's 261/265 numbers; lowRISC's ports-required claim corrected (row
|
||||
unchanged: the one alignment switch covers connections, which the guide
|
||||
requires); the comment-line deviation listed; the multi-instance hanging
|
||||
layout recorded as a known limit and the `list_indent` doc corrected.
|
||||
- **F8.** `style.rs`: the presets are one `PRESETS` table, a `row(..)` per
|
||||
preset, columns aligned by hand under `#[rustfmt::skip]` (reason in the
|
||||
comment); the named constants are `PRESETS[i]` and carry the provenance.
|
||||
`port_lists` names exactly the lists it governs; `begin` lists the headers
|
||||
that move with it.
|
||||
|
||||
**2026-11-19 — dev, round 3 (QA round 2: PASS WITH FINDINGS).**
|
||||
|
||||
- **R2-1.** `auto_style.rs` forgets as listed under "auto" (open, close,
|
||||
rename, delete, named-style requests and formats; everything on a settings
|
||||
change or a seen `lucisv.toml` event) and marks an entry *replaced* on a
|
||||
whole-buffer `didChange`, re-resolving on the next request when the buffer
|
||||
parses. Deviation from the brief, reasoned under "auto": marked, not
|
||||
forgotten, so a full-sync client's half-typed buffer keeps its preset.
|
||||
The three one-line calls in `notification.rs` are listed under Handshakes.
|
||||
Tests: four new unit tests (open/close/rename/delete; config file and
|
||||
settings; whole-buffer replacement, partial edit and full-range-from-top;
|
||||
named-style forgetting) and four new end-to-end tests (replaced buffer,
|
||||
auto → named format → auto, close + reopen, rename). QA's `memattack.py`
|
||||
run against this tree: see "auto".
|
||||
- **R2-2.** "`auto` picks a layout for the configured indent and width; it
|
||||
never infers them — set `indent` to match the file first", with the
|
||||
4-space Allman example (checked on the CLI: indent 2 → lucisv layout;
|
||||
`--indent 4 --line-length 80` → unchanged), in this README, the root
|
||||
README, the extension README and the `lucisv.format.style` `auto`
|
||||
description.
|
||||
|
||||
## Changelog paragraph (for the lead)
|
||||
|
||||
**Named formatting styles.** `[format] style = "<name>"` in `lucisv.toml`,
|
||||
`--style <name>` on the command line, or the new `lucisv.format.style`
|
||||
drop-down in VS Code picks a house layout: `lucisv` (the default, unchanged
|
||||
byte for byte), `google` (the Google Verilog Style Guide: one port and
|
||||
connection per line at a 4-space continuation indent), `lowrisc` (OpenTitan's
|
||||
guide: the same with every port and connection table aligned), and `ansi`,
|
||||
`microsoft` and `nxp` — lucisv's educated guesses at those names (Allman
|
||||
`begin`/`else`, 4 spaces and 80 or 120 columns; a conservative aligned RTL
|
||||
style), not rules those companies publish. `auto` keeps each file in the
|
||||
preset it is already closest to, and the language server remembers each
|
||||
document's preset so on-type and selection formatting stay fast. Every style only moves whitespace and runs
|
||||
through the same safety check; each was swept over the 860-file corpus and
|
||||
OpenTitan's `hw/` tree with no verification error, crash or idempotency
|
||||
failure. An explicit `indent`/`line-length` still wins over a preset's.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-11-19 — QA (Opus 5.5).** Verdict: **PASS WITH FINDINGS.** None of the
|
||||
four invariants broke anywhere I looked, and the default output is
|
||||
byte-identical. The findings are about how `auto` behaves, how honest the
|
||||
presets are and how accurate the docs are. Scratch:
|
||||
`/private/tmp/claude-501/-Users-lucio-repo-lucisv/d043c274-11ff-4de2-ab0f-45daa8a877f0/scratchpad/qa715/`
|
||||
(`bin/` holds my drivers). No source edits were made.
|
||||
|
||||
*Baseline.* `cargo fmt --all -- --check` clean. `cargo clippy --all-targets
|
||||
-- -D warnings` clean; the one manifest warning (`workspace.package.authors`)
|
||||
is already on the base. Every test run went through guard.sh: vlog_formatter
|
||||
374/0, lucisv 151/0, lucisv_core 119/0, lucisv_server 1980/0, lucisv_mcp
|
||||
384/0, node 37/0. `tools/gates.sh` was run on its own (no guard.sh wrapper)
|
||||
and printed **PASS**, every step green. `git diff d574969 -- '**/verify.rs'`
|
||||
is empty. No test was deleted: every test name in d574969 still exists. The
|
||||
only `-assert` lines are the `align::plan` calls that gained
|
||||
`Alignment::Infer`, and the two cache-format assertions that gained the
|
||||
`lucisv` field. The `cli.rs` `cache_line` change is the two lines described,
|
||||
and it weakens nothing. Production sizes: `stmt.rs` and `item.rs` shrank, and
|
||||
every changed file stays under its threshold.
|
||||
|
||||
*Default byte identity, rebuilt independently.* Base built from `git archive
|
||||
d574969` with its own target dir. 4 921 files (corpus + OpenTitan `hw`,
|
||||
scratch copies) were formatted four ways: base vs new with no flag, new
|
||||
`--style lucisv`, and base vs new with a `lucisv.toml` setting only
|
||||
`line-length = 90` / `indent = 3`. `diff -r` gives **0 lines** for all three
|
||||
comparisons, and stderr is identical too. Sanity check: the toml tree differs
|
||||
from the default tree in 4 690 files.
|
||||
|
||||
*Invariants per style, using my own driver* (`bin/sweep.sh` plus
|
||||
`bin/lexcmp.py`). lexcmp is an independent Python lexer: maximal-munch
|
||||
words, strings and escaped identifiers kept whole, based numbers and `@*`
|
||||
normalised as `verify.rs` already does, `` `define `` lines compared whole,
|
||||
and comments compared by count and per-line-stripped text. I mutation-tested
|
||||
it on five crafted corruptions and it caught all five. Run against the base
|
||||
binary's output it reports zero problems. Each style was formatted three
|
||||
times over the full tree.
|
||||
|
||||
| style | files | parse err | verif err | crash/guard kill | partial output on failure | token diffs | comment diffs | run2≠run1 | run3≠run2 |
|
||||
|---|---|---|---|---|---|---|---|---|---|
|
||||
| lucisv | 4 921 | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| google | 4 921 | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| lowrisc | 4 921 | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| ansi | 4 921 | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| microsoft | 4 921 | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| nxp | 4 921 | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| auto | 4 921 | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
|
||||
*Hand attacks* (`hand/src`, 12 files) were run under all seven styles, at
|
||||
the default size and at `--line-length 40` with `--indent 8` and with
|
||||
`--indent 1`. The inputs covered:
|
||||
|
||||
- comments after a header, after `end`, between `end` and `else`, and
|
||||
between `)` and `begin`
|
||||
- labelled blocks, `else if` chains, generate `if`/`for`/`case`,
|
||||
`fork…join_none`, `do…while`, `case` items, macros as statements,
|
||||
`assert … else`, `@*`, nested `if` without `begin`
|
||||
- an empty port list, a single port, unpacked dimensions and defaults,
|
||||
`.*`, positional connections, `#(16)`
|
||||
- `` `ifdef `` inside port and connection lists and inside an aligned group
|
||||
- multi-instance declarations, `(* *)` on an instance
|
||||
- 80- and 120-column expressions
|
||||
- tabs plus CRLF, no trailing newline, non-ASCII text
|
||||
- a fence, an empty file, a comment-only file, a parse error
|
||||
|
||||
Results: 0 token diffs, 0 comment diffs, every file idempotent, and the
|
||||
parse-error file was refused with its bytes unchanged. Three inputs failed
|
||||
identically on the d574969 binary, so they are bugs that predate this lane:
|
||||
|
||||
- a comment between a generate `end` and `else` gives a verification error;
|
||||
the safety net caught it and nothing was written
|
||||
- `` `ifdef `` between `end` and `else` is a parse error
|
||||
- `(* keep *)` on an ANSI port is a parse error
|
||||
|
||||
Each layout matched its row, with the exception in F2.
|
||||
|
||||
*Plumbing.* All checked by hand, all as documented:
|
||||
|
||||
- toml with a valid style; unknown, wrong-case, empty and trailing-space
|
||||
names, each giving exit 2 with `file:line` and the list of names
|
||||
- wrong types (`1`, `true`, an array), giving "expected a quoted string"
|
||||
- `style` outside `[format]`
|
||||
- `--style` with `--indent`/`--line-length`, flag over toml, and a toml
|
||||
`indent` over the flag's preset
|
||||
- nested configs: the nearest one wins with no merging
|
||||
- `check --select line-length` under each style (80, 100 and 120 columns,
|
||||
auto 100)
|
||||
- MCP `format` live over stdio, ansi + `indent = 3`, byte-equal to the CLI
|
||||
- the cache: A → B → A is never served stale; a corrupt 7th field, a
|
||||
6-field line and a garbage line are each dropped without error; the base
|
||||
binary reading the new store re-checks the file and rewrites it
|
||||
- the `lucisv.format.style` drop-down matches `STYLE_NAMES` (a test pins
|
||||
this)
|
||||
|
||||
*auto.*
|
||||
|
||||
- **Determinism:** `--threads 1` vs the default thread count over all
|
||||
4 921 files: 0 diff lines.
|
||||
- **Ties:** I built a file where `lucisv` and `nxp` tie exactly at 15/16.
|
||||
It went to `lucisv`, the earlier preset, three runs gave the same bytes,
|
||||
and the result is idempotent.
|
||||
- **Edge cases:** an empty file, a comment-only file, a fence region and a
|
||||
parse error all behave as under a fixed preset.
|
||||
- **Range:** `--lines` under auto changed nothing outside the range, and the
|
||||
result was stable.
|
||||
- **Stability and cost:** findings F1, F3 and F4.
|
||||
|
||||
**Findings.**
|
||||
|
||||
- **F1 — medium-high (user-visible, not an invariant): under `auto`, a
|
||||
one-line edit can rewrite most of a file.** `auto.rs` `distance` compares
|
||||
layout lines first and indentation only to break ties. A preset that saves
|
||||
3 layout lines therefore beats one that keeps 741 lines' indentation.
|
||||
Repro (`qa_auto/` probe, scratch):
|
||||
1. Take `hw/top_earlgrey/rtl/autogen/chip_earlgrey_asic.sv`.
|
||||
2. Auto picks `microsoft`, at distance (626, …) against `google` (626, …).
|
||||
3. Insert `always_comb if(qa) begin qa_x=1; end else begin qa_x=0; end`
|
||||
before `endmodule` and run auto again.
|
||||
4. It now picks `google`, and `ListIndent::Wrap` re-indents **741 of 1 314
|
||||
lines**.
|
||||
|
||||
Measured on 200 random files with `endmodule`, comparing the auto output
|
||||
before and after one inserted construct. The `--style auto` column counts
|
||||
files whose pre-existing lines changed.
|
||||
|
||||
| inserted construct | preset changed | pre-existing lines changed | >20 lines changed |
|
||||
|---|---|---|---|
|
||||
| `assign qa_x=qa_y ;` | 0 | 0 | 0 |
|
||||
| the cuddled if/else line above | 4 | 4 | 2 (741, 194 lines) |
|
||||
| an Allman if/else block | 81 | 21 | 2 (140 lines max) |
|
||||
| a one-line instance `qa_mod qa_u (.a(qa_a), .b(qa_b));` | 14 | 14 | 2 (37 lines max) |
|
||||
|
||||
In the last row, typing one ordinary instance into a google-style file
|
||||
flips it to `lucisv` and un-breaks every short header. Idempotency still
|
||||
holds in every case. Possible cheap mitigations, for the lead to decide:
|
||||
- compare total changed lines instead of lexicographically
|
||||
- add hysteresis: keep the preset the input is already a fixed point of
|
||||
unless another wins by a margin
|
||||
- in the editor, pin the preset per document
|
||||
- **F2 — medium (preset honesty): `google` and `lowrisc` cuddle `else`
|
||||
after a labelled `end`.** Both cited guides make an exception: after a
|
||||
labelled `end`, the `else` goes on a new line (Google "Eschatology";
|
||||
lowRISC "Begin / End"). Repro: `if (a) begin : l1 … end : l1` / `else
|
||||
begin` with `--style google` or `--style lowrisc` prints `end : l1 else
|
||||
begin`. The preset comments in `style.rs` (GOOGLE, LOWRISC) leave this
|
||||
exception out.
|
||||
- **F3 — medium (functional): under `auto`, range, selection and on-type
|
||||
formatting fall back to `lucisv` whenever the buffer has a parse error
|
||||
anywhere.** `auto.rs` `resolve_style` does this in its `Err(_) =>
|
||||
PRESETS[0]` arm. A half-typed buffer is exactly when on-type runs, and
|
||||
selection formatting otherwise works around parse errors. Repro: take the
|
||||
google-formatted `common_cells/src/stream_throttle.sv`, insert an
|
||||
unindented 4-line broken instance at line 48, and run `format_selection`
|
||||
lines 48–51 with auto:
|
||||
- with no parse error elsewhere, it lays the instance out google-style
|
||||
(one connection per line)
|
||||
- with ` assign qa = ;` added near the end, it joins the instance onto
|
||||
one line, lucisv-style
|
||||
|
||||
This is documented in a code comment, but not in either README.
|
||||
- **F4 — medium (cost; the README is optimistic).** Release build, on a
|
||||
busy machine, 10 largest files:
|
||||
|
||||
| file | auto, unformatted | lucisv, unformatted | auto selection, formatted file | lucisv selection | auto selection, unformatted file |
|
||||
|---|---|---|---|---|---|
|
||||
| `pinmux_reg_top.sv`, 42 192 lines | 2.30 s | 0.37 s | 1.36 s | 0.094 s | 3.0 s |
|
||||
| `rv_plic_reg_top.sv`, 20 021 lines | 0.45 s | — | 0.25 s | — | — |
|
||||
| `ac_range_check_reg_top.sv`, 14 418 lines | 0.32 s | — | 0.28 s | — | — |
|
||||
|
||||
The README says an already-formatted file costs "0.41 s vs 0.40 s (the
|
||||
first preset leaves it unchanged)". That holds only when the file's preset
|
||||
is `lucisv`. pinmux's auto output resolves to `google`, so every selection
|
||||
pays three whole-file formats: `lucisv`, then `google`, then `canonical`'s
|
||||
`lucisv` again. Selection does not need `canonical`, which only names the
|
||||
preset. Caching the resolved preset per document version would remove the
|
||||
whole cost from on-type. Whether 1–3 s per on-type keystroke on 20k–42k
|
||||
line files is acceptable is the lead's call.
|
||||
- **F5 — low (docs): the cross-preset claim "every other decision … comes
|
||||
back" is slightly overstated.** I reproduced the counts for lucisv via
|
||||
lowrisc (1 288), microsoft via lucisv (20) and ansi via nxp (1 244). I then
|
||||
classified every differing hunk in 20 files per pair (`bin/classify.py`):
|
||||
- microsoft via lucisv and ansi via nxp: all padding, or lists broken by
|
||||
alignment
|
||||
- lucisv via lowrisc: 261 of 265 hunks are padding or alignment-forced
|
||||
breaks; 4 hunks (18 lines) are something else. Examples:
|
||||
`flash_phy_core.sv:230` and `kmac_entropy.sv:297`. A named parameter
|
||||
override `#(.Width(HashCntW))`, broken in `lucisv(x)`, comes back
|
||||
joined in `lucisv(lowrisc(lucisv(x)))` once its connection list is
|
||||
aligned.
|
||||
|
||||
This is the pre-existing coupling between the head and the connection
|
||||
list, and it is a knock-on effect of alignment rather than a new bug. The
|
||||
README should say so instead of "only alignment".
|
||||
- **F6 — low (docs):**
|
||||
- `style.rs` LOWRISC says the guide's "Module Declaration" section
|
||||
*requires* aligned ports. The guide requires alignment only for
|
||||
instantiation port expressions; for declarations it is just shown in
|
||||
the examples. The feature README's "aligned in columns" has the same
|
||||
issue.
|
||||
- lowRISC keeps a comment line without a blank line before it inside the
|
||||
same alignment block. lucisv breaks the group at the comment. This
|
||||
deviation is not listed beside the widest-row-tight one in Assumptions.
|
||||
- **F7 — low (cosmetic; the layout predates the lane but is now common):**
|
||||
`OnePerLine` breaks every multi-instance declaration (`p1 u8 (.a(a)), u9
|
||||
(.a(b));`) into the old hanging layout. Under `google`, entries land at
|
||||
8, `)` and `u9` at 4, and the opening line is at 2. Same under
|
||||
`microsoft` at 4/12/8. `style.rs` `list_indent` says the closing `)`
|
||||
stays at the opening line's column, which is false here.
|
||||
- **F8 — low (readability, concrete gaps in `style.rs`):**
|
||||
- The module doc says "every preset is a table row in this file", but the
|
||||
presets are six separate 9-line struct literals. Only the README has the
|
||||
side-by-side table.
|
||||
- `port_lists`' doc does not say which lists it governs (not positional
|
||||
connections, not function/task ports, not `#(16)`). That is in the
|
||||
README's Assumptions only.
|
||||
- `begin`'s doc does not say it also moves `always_comb`/`initial`/`for`
|
||||
`begin` (ansi prints `always_comb` / `begin`).
|
||||
|
||||
Confirmed honest: in every user-facing place `ansi`, `microsoft` and `nxp`
|
||||
appear (root README, extension README, package.json `enumDescriptions` and
|
||||
`markdownDescription`, `style.rs` comments), they are labelled as lucisv's
|
||||
guesses, and no citation is made up. Both guides were fetched
|
||||
(google/styleguide `verilogguide.md` up to character 100 000;
|
||||
lowRISC/style-guides `VerilogCodingStyle.md`). Indent 2, width 100,
|
||||
`begin` on the keyword's line, `end else begin`, one entry per line, Google's
|
||||
4-space list indent, lowRISC's 2-space list indent, and Google's
|
||||
recommended-only alignment all match the text, apart from F2 and F6.
|
||||
|
||||
Not verified:
|
||||
- a live VS Code or LSP session (the server's style ladder is covered only
|
||||
by unit tests, which I read against the README)
|
||||
- the dev's per-preset pick counts (lucisv 3 875, …)
|
||||
- the rest of Google's guide beyond character 100 000
|
||||
- lint.rs line-length under ansi/microsoft/nxp in the server (owned by
|
||||
lane 71.1; the Handshake request stands)
|
||||
|
||||
**2026-11-19 — QA round 2 (Opus 5.5), on the fix round.** Verdict:
|
||||
**PASS WITH FINDINGS.** No invariant violation, and the default output is
|
||||
still byte-identical. F1, F2, F4 and F8 are fixed. F3 is fixed for the case
|
||||
it named, but the new per-document memory can serve a stale preset (R2-1).
|
||||
Binaries were rebuilt from the worktree (`bins/new2`, `bins/server2`).
|
||||
Drivers are in scratch `bin/`: `sweep2.sh`, `identity2.sh`, `lexcmp.py`,
|
||||
`lsp.py`, `memattack.py`, plus the `qa_auto` probe's `edit2` mode.
|
||||
|
||||
*Baseline.*
|
||||
- `cargo fmt --check` clean; `clippy --all-targets -D warnings` clean.
|
||||
- node tests 37/0.
|
||||
- `tools/gates.sh` **PASS**, with every suite run through guard.sh:
|
||||
vlog_formatter 376/0, lucisv 151/0, lucisv_core 119/0, lucisv_server
|
||||
1988/0, lucisv_mcp 384/0; corpus step 814/6, the same as round 1.
|
||||
- `git diff d574969 -- '**/verify.rs'` is empty.
|
||||
- No test name from d574969 is missing.
|
||||
- The one rewritten test, `auto_picks_a_layout_never_a_size`, now
|
||||
configures indent 4 and asserts Allman output. It does not hide a
|
||||
regression, but it reflects a behaviour change (R2-2).
|
||||
- Sizes: unchanged hot spots. `auto_style.rs` is 184 lines with its tests;
|
||||
no production file grew past a threshold.
|
||||
|
||||
*Default byte identity* against the d574969 build, over all 4 921 files: no
|
||||
flag, `--style lucisv`, and a toml with only `line-length`/`indent` each
|
||||
give **0 diff lines** in output and in stderr.
|
||||
|
||||
*Invariants, independent lexer, three runs per style, all 4 921 files.* For
|
||||
every one of the seven styles: 14 parse errors (the base's own), 0
|
||||
verification errors, 0 crashes or guard kills, 0 partial outputs, 0 token
|
||||
diffs, 0 comment diffs, and 0 files changed by the 2nd or the 3rd run.
|
||||
|
||||
*a. Edits under auto.*
|
||||
|
||||
On the numbers that need reconciling: both are right; they are different
|
||||
columns of my round-1 table. For the own-line block, 81 is "preset
|
||||
changed" and 21 is "pre-existing lines changed".
|
||||
|
||||
Round 2, same 200 files, same four constructs, measured as preset changes
|
||||
(and maximum lines rewritten):
|
||||
|
||||
| inserted construct | round 1 | round 2 |
|
||||
|---|---|---|
|
||||
| `assign` | 0 | 0 |
|
||||
| cuddled if/else line | 4 | 0 |
|
||||
| own-line block | 81 | 1 (3 lines) |
|
||||
| one-line instance | 14 | 0 |
|
||||
|
||||
This matches the dev's figures.
|
||||
|
||||
Wider set: 500 new random files with `endmodule`. "Rewritten" counts
|
||||
original lines changed outside the edit; for `delete_block` the deleted
|
||||
lines are taken out of the baseline first.
|
||||
|
||||
| edit | n | preset changed | 0 lines | 1–3 | 4–20 | >20 | max |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| `assign` line | 499 | 0 | 499 | 0 | 0 | 0 | 0 |
|
||||
| cuddled if/else line | 499 | 3 | 496 | 3 | 0 | 0 | 2 |
|
||||
| Allman if/else block | 499 | 6 | 493 | 6 | 0 | 0 | 2 |
|
||||
| one-line instance | 499 | 1 | 498 | 1 | 0 | 0 | 2 |
|
||||
| new port in the header | 419 | 20 | 399 | 16 | 4 | 0 | 6 |
|
||||
| instance, 3 connections one per line | 499 | 25 | 474 | 25 | 0 | 0 | 3 |
|
||||
| `always_ff`, cuddled | 499 | 6 | 493 | 6 | 0 | 0 | 2 |
|
||||
| `always_ff`, Allman | 499 | 6 | 493 | 6 | 0 | 0 | 2 |
|
||||
| `always_ff`, nxp layout | 499 | 6 | 493 | 6 | 0 | 0 | 2 |
|
||||
| delete the last `always … begin` block | 185 | 0 | 85 | 100 | 0 | 0 | 1 |
|
||||
| paste a 37–42-line module in another preset | 499 | 161 | 339 | 29 | 131 | 0 | 12 |
|
||||
| paste a module in the same preset | 499 | 12 | 487 | 4 | 8 | 0 | 6 |
|
||||
|
||||
- No edit rewrote more than 12 unrelated lines, so none crossed the
|
||||
~20-line flag, and every result was idempotent.
|
||||
- The `delete_block` 1-line cases are the blank line left behind,
|
||||
collapsed. Example: `spid_fifo2sram_adapter.sv`.
|
||||
- Pasting a whole google-formatted module into a lucisv file flips the file
|
||||
in 101 of 298 cases and re-lays up to 12 of its own header lines. Majority
|
||||
rule by line count is a defensible outcome.
|
||||
|
||||
*c. The per-document memory, live over stdio against `lucisv-server`.*
|
||||
Setup: auto via `didChangeConfiguration`. "Google file" means a
|
||||
google-formatted module; the range format target is one unindented
|
||||
one-line instance. Ground truth is the CLI's auto on the same buffer.
|
||||
|
||||
| case | expected | got | result |
|
||||
|---|---|---|---|
|
||||
| 1. First range on a google file | resolves google | google; edits confined to the range; second range returns no edits | OK |
|
||||
| 2. Buffer replaced by a lucisv-layout text (external reformat / reload) | lucisv | **google** | FAIL, R2-1 |
|
||||
| 3. Whole-document format with a remembered preset | searches afresh | equals CLI auto | OK |
|
||||
| 4. Range after that format | lucisv | lucisv | OK |
|
||||
| 5. Named `lucisv` / `google` while a preset is remembered | memory ignored | memory ignored | OK |
|
||||
| 6. auto → whole-document format under `lucisv` → auto, then a range | lucisv | **google** | FAIL, R2-1 |
|
||||
| 7. Close, then reopen the same URI with lucisv content | lucisv | **google** | FAIL, R2-1 |
|
||||
| 8. Buffer stops parsing after a preset is remembered | remembered google | google, for range and for `;` on-type | OK |
|
||||
| 9. Buffer never parsed | default layout (documented) | default layout | OK |
|
||||
| 10. Same file under `c%6Dx.sv`, `cmx.sv`, `CMX.sv` | independent entries, none inherits | independent | OK |
|
||||
| 11. 70 documents | oldest evicted and resolved afresh, newest kept, list bounded at 64 | as expected | OK |
|
||||
|
||||
- Range locality held in every case, stale ones included. So R2-1 is
|
||||
layout-only and safe.
|
||||
- Latency, 42 192-line pinmux file, live: the first range costs 1.49 s
|
||||
formatted and 2.90 s unformatted (one search). Each later range costs
|
||||
0.06 s, and a named-style range costs 0.067 s. F4 is fixed after the
|
||||
first request per document.
|
||||
- didRename was not run live. By the code, the new URI has no entry
|
||||
(it searches), and the old URI keeps its entry, which is case 7 again if
|
||||
a file reappears under the old URI.
|
||||
|
||||
*d. `else_after_label`.* I wrote new inputs (`hand2/`):
|
||||
- procedural `end : l` followed by `else`, `else if`, `else begin : l`, a
|
||||
trailing `//`, a `/* */` between, a plain `else` statement, and
|
||||
`` `ifdef `` inside the block;
|
||||
- an unlabelled `end` before a labelled `else` block;
|
||||
- `unique if`;
|
||||
- generate `if`/`else if`/`else` chains with labels, including inside a
|
||||
labelled `for`.
|
||||
|
||||
Under all seven styles: token-equal, comments intact, idempotent.
|
||||
|
||||
The cited sections, re-fetched today:
|
||||
- Google "Eschatology": "if `end` has a label, a following `else` must be
|
||||
on a new line".
|
||||
- lowRISC "Begin / End": the same rule, with an `end : a` / `else begin : b`
|
||||
example at the same column.
|
||||
|
||||
google and lowrisc now print exactly that, and `end else begin : t9` (no
|
||||
end label) stays cuddled. lucisv still cuddles, and its byte identity
|
||||
holds. One older bug, already present in d574969, showed up here: a
|
||||
trailing `// c` after a generate `end : g4` followed by `else` is a
|
||||
verification error under every style. The safety net catches it. It is the
|
||||
round-1 generate-comment-before-else bug again.
|
||||
|
||||
*e. Table attributes.* `#[allow(clippy::too_many_arguments)]` at
|
||||
`style.rs:102` and `#[rustfmt::skip]` at `style.rs:138` each carry a reason.
|
||||
The table is column-aligned with a header comment and reads side by side.
|
||||
`cargo fmt --check` passes.
|
||||
|
||||
**Findings, round 2.**
|
||||
- **R2-1 — medium (wrong preset served; layout only, safe).**
|
||||
`crates/lucisv_server/src/auto_style.rs`, `concrete` → `recall`: the
|
||||
memory is keyed by URI alone and never invalidated. Nothing clears it:
|
||||
not `didChange`, `didOpen`, `didClose`, a settings change, nor a whole
|
||||
document format under a named style. Repro: cases 2, 6 and 7 above
|
||||
(`bin/memattack.py`).
|
||||
- In case 6, the user formats the whole file under `lucisv`, switches
|
||||
back to auto, and the next selection or on-type `;` is laid out
|
||||
google-style in a file that is entirely lucisv.
|
||||
- It stays that way until the next whole-document format or save.
|
||||
- Cheap fixes: drop the entry on `didOpen`/`didClose` and on any
|
||||
settings change, and on a whole-document format under a named style;
|
||||
or key the entry by the document version it was resolved on, and
|
||||
re-resolve only on a full-text replacement.
|
||||
- **R2-2 — low-medium (behaviour change from F1, undocumented in the
|
||||
README).** Now that indentation counts in full, a file whose indent
|
||||
differs from the configured one loses its layout under auto. Repro:
|
||||
`lucisv --style auto` with default indent 2 on a 4-space Allman file
|
||||
(`hand/src/a01` formatted `--style ansi`) prints cuddled lucisv layout;
|
||||
round 1 kept it Allman. The dev's test documents this as "indent is the
|
||||
config's". In VS Code the editor `tabSize` rung softens it; on the CLI it
|
||||
does not. Between rounds, 426 of 4 921 files' auto output changed.
|
||||
Worth a sentence in the README's `auto` paragraph.
|
||||
- Round-1 F5–F7 doc fixes were read and are accurate. F7's hanging
|
||||
multi-instance layout is recorded as a known limit.
|
||||
|
||||
Not verified in round 2:
|
||||
- a real VS Code session
|
||||
- `didRename` live
|
||||
- a lucisv.toml style change while a preset is remembered: by the code it
|
||||
behaves like case 6, since `concrete` checks only `config.auto_style`
|
||||
- the dev's pick counts
|
||||
- Google's guide past character 100 000
|
||||
|
||||
## Review
|
||||
|
||||
**Lead, 2026-11-19.** Accepted for 0.65.5, after two QA rounds and three dev rounds.
|
||||
|
||||
- The owner asked for adaptation to the file, with named styles as the
|
||||
fallback if that was too ambiguous. Both shipped, and the order they were
|
||||
built in was the right one: presets first, each proven on 4 921 files, then
|
||||
`auto` as a search over them rather than a detector — the dev dropped the
|
||||
voting detector before writing it because its stability could only be
|
||||
measured, never argued. `auto`'s idempotency is argued (a preset's own
|
||||
output is its fixed point) and then measured.
|
||||
- QA earned its keep twice. Round 1 found that `auto` could re-indent 741
|
||||
lines after a one-line edit; round 2 found the fix's per-document memory
|
||||
could go stale. Both are fixed and both are the kind of thing only an
|
||||
adversarial run finds. The invariant table (seven styles, three runs,
|
||||
independent lexer, mutation-tested) is the evidence I am accepting this on.
|
||||
- I allowed three one-line calls in `server/notification.rs`, another lane's
|
||||
file, for the memory's invalidation; they are listed under Handshakes and I
|
||||
resolve that merge.
|
||||
- The dev departed from my wording on whole-buffer replacement (re-resolve,
|
||||
not forget) and was right: a full-sync client would otherwise lose the
|
||||
preset of every half-typed buffer.
|
||||
- Not done, recorded: the server's `line-length` lint still falls back to 100
|
||||
under the 80- and 120-column styles (`lint.rs`, lane 71.1's file — I take
|
||||
it at that merge); multi-instance declarations under one-per-line styles;
|
||||
the three pre-existing bugs QA met on the way (comment between a generate
|
||||
`end` and `else`: verification error; `` `ifdef `` between `end` and `else`
|
||||
and an attribute on an ANSI port: parse errors) go to the backlog.
|
||||
- Owed to a human: the drop-down in a running VS Code. `ansi`, `microsoft`
|
||||
and `nxp` are guesses and say so wherever a user meets them.
|
||||
@@ -0,0 +1,567 @@
|
||||
# hierarchy-current-path
|
||||
|
||||
## Goal
|
||||
|
||||
The owner (TODO §71.6): "In the module view, always highlight the current open
|
||||
file and its parents, in different shade. Light bright orange for the instance,
|
||||
and getting dimmer the further it goes … I just want easy understanding of the
|
||||
hierarchical view." The Hierarchy pane now lights every row whose module is
|
||||
declared in the active editor's file (level 0, a light bright orange) and every
|
||||
row whose module is above it in the design, one shade dimmer per
|
||||
instantiation level, down to a floor that stays distinguishable from an unlit
|
||||
row. A module instantiated in several places lights every instance and each
|
||||
instance's chain; where chains meet, the nearer distance wins. It works on a
|
||||
closed tree (the root, or a section header, says the file is in there), costs
|
||||
no snapshot request, and repaints only the rows whose level changed. A boolean
|
||||
setting, `lucisv.hierarchy.highlightCurrent` (default on), turns it off.
|
||||
|
||||
### Mechanism, and why
|
||||
|
||||
The brief assumed a `TreeView`, where a row's background cannot be painted and
|
||||
the candidates are a `FileDecorationProvider` (label colour + badge), a
|
||||
`ThemeIcon` colour or label highlights. **The Hierarchy pane is not a
|
||||
`TreeView`: it is a `WebviewView`** (`registerWebviewViewProvider` in
|
||||
`hierarchyView.js`, rows drawn by `media/hierarchy.js`). A webview can paint a
|
||||
row's whole background with CSS, which is the most legible of all the options,
|
||||
so that is what this does. The colours are still real theme colours:
|
||||
|
||||
- They are contributed through `contributes.colors` (five ids, with `dark`,
|
||||
`light`, `highContrast` and `highContrastLight` defaults), so a user or a
|
||||
theme overrides them with `workbench.colorCustomizations`.
|
||||
- **Verified, 2026-11-19:** the contribution handler
|
||||
(`src/vs/workbench/services/themes/common/colorExtensionPoint.ts`, VS Code
|
||||
`main`) calls `colorRegistry.registerColor` for every contributed id (id
|
||||
pattern `^\w+[.\w+]*$`; `highContrastLight` falls back to `light`,
|
||||
`highContrast` to `dark`); the webview theming
|
||||
(`src/vs/workbench/contrib/webview/browser/themeing.ts`) iterates
|
||||
`getColorRegistry().getColors()` and exports each resolved colour as
|
||||
`'vscode-' + entry.id.replace('.', '-')`. So a contributed colour reaches the
|
||||
webview as a CSS variable — **with only the first dot replaced** (a plain
|
||||
string `replace`). Every id here therefore has exactly one dot
|
||||
(`lucisv.hierarchyCurrent` → `--vscode-lucisv-hierarchyCurrent`), and a test
|
||||
pins that. The public guides (code.visualstudio.com/api/extension-guides/webview,
|
||||
…/references/contribution-points) document the `--vscode-` naming and the
|
||||
`contributes.colors` shape but say nothing about contributed colours inside
|
||||
webviews; the source is the authority used.
|
||||
- The same source lists the body classes `vscode-light`, `vscode-dark`,
|
||||
`vscode-high-contrast`, `vscode-high-contrast-light`; the high-contrast rule
|
||||
adds the theme's `contrastActiveBorder` around the current row (not on a
|
||||
bookmarked one, whose border is the bookmark's).
|
||||
|
||||
**Two layers per lit row, both `background-image`s**, so they sit over whatever
|
||||
the row already has — hover, the opaque sticky section header — instead of
|
||||
replacing it:
|
||||
|
||||
1. **A translucent tint**, kept light enough that the label stays at or above
|
||||
WCAG AA (4.5:1) on every level, hovered or not, in Dark Modern, Dark+, Light
|
||||
Modern, Light+, HC dark and HC light. `hierarchyPalette_test.js` blends the
|
||||
`package.json` defaults over those themes' sidebar and hover colours and
|
||||
fails under 4.5:1, or when neighbouring levels are closer than ΔE76 3.
|
||||
2. **A bar at the left edge** (`lucisv.hierarchyCurrentBar`, opaque) that
|
||||
carries the "brightest" the tint gave up for legibility. On the current row
|
||||
it is a solid 4px light bright orange, fully opaque. Each level up it gets
|
||||
narrower and fainter: 3px at 80 %, 2px at 65 %, then 2px dashed at 55 %,
|
||||
then 1px dashed at 45 %. Width and dash are the cue that does not depend on
|
||||
colour, which is what high-contrast themes need for levels 1–4 (QA F3). The
|
||||
current row's label is also bold. The test asserts the opaque bar is at
|
||||
least 3:1 against the sidebar (WCAG 1.4.11, non-text contrast).
|
||||
|
||||
*Why this and not a darker tint per theme kind:* a tint dark enough to keep
|
||||
light text readable on a dark sidebar stops reading as "light bright orange".
|
||||
The bar can be that orange at full strength, because no text sits on it. So the
|
||||
tint does legibility and the bar does brightness.
|
||||
|
||||
**A bookmark wins:** a bookmarked row keeps its yellow fill and border and drops
|
||||
the tint. The bar stays, so a bookmarked current row still says it is current.
|
||||
|
||||
**Forced colours** (Windows High Contrast / `forced-colors: active`) drop every
|
||||
background image, so the tint and the bar are gone and **levels 1–4 have no
|
||||
cue there**. The current row keeps a dashed `CanvasText` *border* and its bold
|
||||
label. It is a border rather than an outline, so the focus ring and the
|
||||
bookmark's 2px outline stay as they were (QA F4).
|
||||
|
||||
| level | colour id | meaning | dark | light | HC dark | HC light |
|
||||
|---|---|---|---|---|---|---|
|
||||
| 0 | `lucisv.hierarchyCurrent` | module declared in the active file | `#FFB34745` | `#FFC26661` | `#FFB34780` | `#FF8C0099` |
|
||||
| 1 | `lucisv.hierarchyParent1` | one level above | `#FFB34730` | `#FFC2664F` | `#FFB34761` | `#FF8C0073` |
|
||||
| 2 | `lucisv.hierarchyParent2` | two levels above | `#FFB34721` | `#FFC2663B` | `#FFB34745` | `#FF8C0052` |
|
||||
| 3 | `lucisv.hierarchyParent3` | three levels above | `#FFB34716` | `#FFC26629` | `#FFB3472B` | `#FF8C0033` |
|
||||
| 4 | `lucisv.hierarchyAncestor` | four or more (the floor) | `#FFB3470D` | `#FFC26615` | `#FFB34717` | `#FF8C001A` |
|
||||
| bar | `lucisv.hierarchyCurrentBar` | left-edge bar, every level | `#FFB347` | `#C86400` | `#FFB347` | `#B35900` |
|
||||
|
||||
Light themes use a paler orange (`#FFC266`) than dark ones. Light+ is the
|
||||
tightest theme: its list foreground `#616161` is only about 5.0:1 on its hover
|
||||
colour to begin with. Searching the hue showed `#FFC266` gives the widest steps
|
||||
under that limit among the oranges (ΔE ≥ 3.9). `#FFBF00` does better, but it is
|
||||
amber and too close to the yellow bookmark.
|
||||
|
||||
### What "distance" means
|
||||
|
||||
A row's distance is a property of its **module**: how many instantiation levels
|
||||
it sits above the nearest module declared in the active file (0 for that
|
||||
module). The level below a row is its module's own instance list wherever the
|
||||
row sits, so every row of a module has the same answer, and one breadth-first
|
||||
walk *up* the module graph from all current modules at once (the reverse index
|
||||
`hierarchySections.parentIndex` already builds) answers it for every module.
|
||||
|
||||
- **Plain tree and a DUT's forward section:** the lit rows are exactly the
|
||||
paths from the root down to every current instance, brightest at the bottom.
|
||||
A forward row that cannot open (leaf, `recursive` repeat, unresolved or
|
||||
ambiguous type) is lit only when it is itself current — what it would lead
|
||||
to is not under it on screen.
|
||||
- **"Parents of <DUT>" (upward tree):** the same rule — the rows lit are the
|
||||
active file's own parents among the DUT's parents, dimmer the further up the
|
||||
design, which on that tree is further *down* the page. With `leaf.sv` active
|
||||
under `tb → dut → leaf`, it shows `dut` at 1 and `tb` at 2. An upward row is
|
||||
always its own module, so a `recursive` repeat there is still lit.
|
||||
- **Section headers** light one step dimmer than the nearest module the section
|
||||
holds, shown or not: a forward section that holds the current module lights
|
||||
its header at 1; an upward section lights at 1 + the nearest distance in the
|
||||
DUT's ancestor closure. That is what tells the user a *closed* section holds
|
||||
the file (or its parents).
|
||||
- **Search results are not lit**: a flat hit has no path to light.
|
||||
|
||||
### Cost
|
||||
|
||||
Per active-file change, with M modules, E resolved instances, R rows on screen:
|
||||
|
||||
- one URI comparison per distinct definition file (≤ M), then the upward BFS —
|
||||
O(M + E), and in practice only the current module's ancestor closure is
|
||||
visited;
|
||||
- per upward section header, one walk of the DUT's ancestor closure, memoized
|
||||
on the path for the life of that (snapshot, file) pair;
|
||||
- one map lookup per row on screen — O(R);
|
||||
- a `lit` message carrying only the `[id, level | null]` pairs that changed;
|
||||
the webview sets `data-lit` on those buttons, looked up in an id → button map
|
||||
it builds at render. **No snapshot request, no row rebuild, no re-render.**
|
||||
|
||||
A render (opening a row, a refresh) reuses the cached path for the same
|
||||
(snapshot, file) pair, so it adds only the O(R) lookups. Ids are untouched, so
|
||||
expansion state survives every relight.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **"Declared in the active file" is `module.definition.uri` equal to the
|
||||
editor's URI** after both go through `vscode.Uri.parse(...).toString()`
|
||||
(the server and VS Code may percent-encode a path differently). The
|
||||
comparison is asked once per distinct file. A module declared in a file the
|
||||
snapshot reaches only through `` `include`` is attributed to whichever URI the
|
||||
server put in its definition.
|
||||
- **What that comparison does and does not fold.** `Uri.parse` + `toString`
|
||||
lowercases a Windows drive letter and encodes `:` as `%3A`, so the server's
|
||||
`file:///C:/x/top.sv` matches VS Code's `file:///c%3A/x/top.sv`. It does
|
||||
**not** fold the case of directory or file names: on a case-insensitive file
|
||||
system (win32, default darwin), a filelist that spells `C:\Proj\rtl` where
|
||||
the editor opened `c:\proj\rtl` lights nothing. **UNC paths do not light
|
||||
either**: the server writes `\\srv\share\a.sv` as `file:////srv/share/a.sv`
|
||||
and VS Code as `file://srv/share/a.sv` (see Handshakes, note for the lead).
|
||||
Both read from source by QA, not executed.
|
||||
- **An ambiguous or unresolved instance names no one module**, so it is never
|
||||
current and never leads anywhere: the declaration rows themselves (roots) are
|
||||
still lit.
|
||||
- **In a recursive component a forward row may be lit with nothing lit below
|
||||
it**: the shortest path in the module graph can run through a module the tree
|
||||
cuts as `recursive` on that particular path. Documented rather than fixed —
|
||||
it needs a per-path walk, which is what this design avoids. It is not rare in
|
||||
dense cycles: QA's property run over 1 500 random cyclic graphs of 3–6
|
||||
modules found 1 165 lit open rows with no child one level brighter (e.g.
|
||||
`m0:[m1,m2] m1:[m3,m5] m2:[m1] m3:[m2,m4] m4:[m1,m3] m5:[m0,m4]`, `m3`
|
||||
current: `m0 › m1 › m3 › u (m2)` is lit at 2 and its only child is a cut
|
||||
`m1`). Acyclic designs, and a self-instantiating module, never show it.
|
||||
- **Focus moving to a panel or a webview is not a new file.**
|
||||
`onDidChangeActiveTextEditor(undefined)` with editors still visible keeps the
|
||||
current lighting; with none visible it clears. An `output`-scheme editor (the
|
||||
Output panel) is ignored. Any other non-HDL file (a README, a diff side) lights
|
||||
nothing.
|
||||
- **A bookmark beats the tint** on the same row; the bar and the current row's
|
||||
bold label still show.
|
||||
- **The theme table in `hierarchyPalette_test.js` is representative, not
|
||||
exhaustive**: the built-in Dark Modern, Dark+, Light Modern, Light+, HC dark
|
||||
and HC light sidebar, foreground and hover colours. A third-party theme with
|
||||
a very different sidebar is not measured; its author or the user can override
|
||||
the six colours.
|
||||
|
||||
## Handshakes
|
||||
|
||||
### Consumed
|
||||
|
||||
- `hierarchySections.parentIndex(model)` — the module → instantiating edges
|
||||
index, memoized on the model. Unchanged.
|
||||
- `hierarchySections.headerId(section)` — **now exported** (additive; it was
|
||||
module-private). Used to find a header row's section.
|
||||
- Tree nodes from `hierarchyModel.rootNode`/`instanceNode` and
|
||||
`hierarchySections.upNode`/`upRootNode`: reads `definition`, `moduleId`,
|
||||
`hasChildren`, `up`. Unchanged.
|
||||
|
||||
### `hierarchyCurrent.js` → `hierarchyView.js`
|
||||
|
||||
- `matchingFiles(model, sameFile)` → the model's spellings of the active file.
|
||||
- `currentPath(model, files)` → the distance state, or `undefined`.
|
||||
- `rowLevels(rows, nodes, list, path)` → `Map<rowId, level>` for lit rows only.
|
||||
- `levelChanges(before, after)` → `[id, level | null][]`.
|
||||
- `LIT_COLORS`, `litLevel`, `cssVariableFor` — the level ↔ colour contract.
|
||||
|
||||
### `hierarchyView.js` → `media/hierarchy.js` (the wire inside the extension)
|
||||
|
||||
- A `render` row carries `lit: <0..4>` **only when lit**; an unlit pane's rows
|
||||
are byte-identical to before this feature (the existing "unstar restores the
|
||||
pane exactly" assertion still holds).
|
||||
- New message `{ type: 'lit', changes: [[id, level | null], …] }`, tree rows
|
||||
only. The renderer sets or removes `data-lit` on the matching buttons.
|
||||
- `treeOrSections` now returns `{ rows, nodes, bookmarkId, list }` (`list` is
|
||||
the section list, `[]` for the plain tree). Internal to the view.
|
||||
|
||||
### Scope deviation, flagged for the lead
|
||||
|
||||
The brief's file list did not name `editors/vscode/media/hierarchy.js` and
|
||||
`media/hierarchy.css`, because it assumed a `TreeView`. The pane is a webview
|
||||
and those two files *are* its rows; nothing is visible without them. The edits
|
||||
are small and additive (a `lit` message handler, `data-lit` per row, the CSS
|
||||
block for five levels). The dut-hierarchy lane edited the same renderer under
|
||||
the same reasoning. Please confirm the other lane does not own them.
|
||||
|
||||
`extension.js` needed **no** change: the view subscribes to
|
||||
`onDidChangeActiveTextEditor` and the setting itself.
|
||||
|
||||
### Note for the lead — UNC URIs (not a request; nothing acted on)
|
||||
|
||||
`crates/lucisv_server/src/uri.rs:20-28` turns `\\srv\share\a.sv` into
|
||||
`file:////srv/share/a.sv` (four slashes, empty authority), where VS Code uses
|
||||
`file://srv/share/a.sv` (authority `srv`). This predates this feature and is
|
||||
outside its scope. Here it means a module declared on a UNC path never lights,
|
||||
and it probably affects any other client-side comparison against server URIs.
|
||||
QA F6, from reading the source, not executed.
|
||||
|
||||
### The server — nothing
|
||||
|
||||
The snapshot already carries each module's declaring file
|
||||
(`definition.file` in the schema-2 file table). No request or schema change.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Pure module `hierarchyCurrent.js`: distance per module (BFS up),
|
||||
per-row levels, header levels, changes diff, colour contract.
|
||||
- [x] Headless tests `hierarchyCurrent_test.js` (18 checks: 15 by the dev,
|
||||
3 added by QA).
|
||||
- [x] Palette regression test `hierarchyPalette_test.js` (4 checks over 6
|
||||
themes): label ≥ 4.5:1 on every level, hovered too; neighbours ΔE ≥ 3;
|
||||
brightest first; bar ≥ 3:1.
|
||||
- [x] QA fix round: F1 contrast, F2 distinct levels, F3 HC bookmark + non-colour
|
||||
cue, F4 forced colours, F7 renderer guard, F8 count, F5/F6 documented.
|
||||
- [x] View wiring: active-editor tracking, cached path per (snapshot, file),
|
||||
`lit` on render rows, in-place `lit` message, setting.
|
||||
- [x] View test: relight posts only changed rows, no request, no render;
|
||||
ignores unchanged file / focus loss / Output; setting off and on;
|
||||
closing all editors clears.
|
||||
- [x] Renderer and CSS (`media/`): `data-lit`, gradient tint, bookmark wins,
|
||||
high-contrast border, forced-colors outline.
|
||||
- [x] `package.json`: five tints and the bar colour, `lucisv.hierarchy.highlightCurrent`.
|
||||
- [x] `.vscodeignore` excludes `hierarchyCurrent_test.js` and
|
||||
`hierarchyPalette_test.js`; `RELEASING.md`
|
||||
lists `hierarchyCurrent.js` as a runtime module (`release.sh` has no
|
||||
such list).
|
||||
- [x] Extension README: feature row and setting row.
|
||||
- [ ] Visual check in a running VS Code (cannot be done by the dev agent; see
|
||||
the work log).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-11-19 — dev (Opus 5.5)
|
||||
|
||||
- Read the sidebar, dut-hierarchy and hierarchy feature docs and the view code.
|
||||
Found the pane is a `WebviewView`, not a `TreeView`, which removes the
|
||||
premise of the mechanism question: row backgrounds are paintable. Chose CSS
|
||||
backgrounds driven by contributed theme colours; verified in VS Code's source
|
||||
that contributed colours reach webviews and that only the first dot of the id
|
||||
becomes a dash (see Goal → Mechanism).
|
||||
- First design lit the upward "Parents of" tree by *tree* direction (a row lit
|
||||
when the current file is below it on the page). Its own test showed the flaw:
|
||||
with `leaf.sv` open, that section shows `dut` and `tb` — leaf's parents — and
|
||||
lit neither. Switched to one meaning everywhere: distance = instantiation
|
||||
levels above the current module. Dropped the second (downward) BFS that the
|
||||
first design needed.
|
||||
- Headers: first cut was "root distance + 1"; replaced by "one dimmer than the
|
||||
nearest module the section holds", which is the only version that means the
|
||||
same thing for forward and upward sections.
|
||||
- Tests before: 10 files under `node --test editors/vscode/*_test.js`, all
|
||||
passing. After: 11 files, all passing (`hierarchyCurrent_test.js` is new, 15
|
||||
checks; `hierarchyView_test.js` gained one scenario).
|
||||
- **Not verified:** the rendered colours in a real VS Code (no editor access);
|
||||
the `.vsix` contents (`vsce` is not installed in this tree). Human check:
|
||||
1. Open a design, open the Hierarchy pane, open a leaf module's file: the
|
||||
root row is tinted even while closed; open it — each level brighter to the
|
||||
leaf, which is bold and brightest orange.
|
||||
2. Open a module instantiated twice: both instance rows and both chains lit.
|
||||
3. Switch files: the tint moves without the "Loading hierarchy…" status and
|
||||
without collapsing anything.
|
||||
4. Star a DUT: the DUT section and the "Parents of" section light; close
|
||||
them — the headers stay tinted when they hold the file.
|
||||
5. Bookmark a lit row: yellow wins. Hover a lit row: tint over hover.
|
||||
6. Light, dark, high-contrast dark and light themes: the floor (level 4,
|
||||
use a design ≥ 5 levels deep) is still visible against the sidebar.
|
||||
7. `"lucisv.hierarchy.highlightCurrent": false` clears it live; `true`
|
||||
restores it.
|
||||
8. `workbench.colorCustomizations` with `"lucisv.hierarchyCurrent": "#00ff0080"`
|
||||
recolours the current row.
|
||||
9. After packaging: `unzip -l dist/lucisv-<v>.vsix | grep hierarchyCurrent`
|
||||
prints `extension/hierarchyCurrent.js` and no `_test`.
|
||||
|
||||
### 2026-11-19 — dev (QA fix round, Opus 5.5)
|
||||
|
||||
- **F1 contrast.** The tints are now lighter, and the brightness moved to a new
|
||||
opaque left-edge bar (`lucisv.hierarchyCurrentBar`). Reasons are under Goal →
|
||||
Mechanism. The tint alphas were placed from measurements: for each theme
|
||||
kind, the most tint that keeps label text ≥ 4.55:1 on both the sidebar and
|
||||
the hover colour, then five levels spread evenly in ΔE between that and an
|
||||
unlit row. Light themes moved to `#FFC266` after a hue search (Light+ is
|
||||
the binding constraint). Ratios of label text on the level-0 row:
|
||||
|
||||
| theme | before (QA) | after | after, hovered | after, levels 1–4 |
|
||||
|---|---|---|---|---|
|
||||
| Dark Modern | 3.68 | **5.91** | 4.72 | 7.39 8.51 9.42 10.09 |
|
||||
| Dark+ | 3.32 | **5.14** | 4.72 | 6.25 7.25 7.98 8.62 |
|
||||
| Light Modern | 7.61 | **8.99** | 8.72 | 9.26 9.62 9.85 10.23 |
|
||||
| Light+ | 4.09 | **4.83** | 4.56 | 4.98 5.13 5.25 5.41 |
|
||||
| HC dark | 4.67 | **6.17** | — | 8.93 12.46 16.23 18.86 |
|
||||
| HC light | 8.14 | **8.64** | — | 9.82 11.00 12.24 13.30 |
|
||||
|
||||
Every level, hovered or not, is now ≥ 4.56:1 (hovered levels 1–4 are in
|
||||
the `LUCISV_PALETTE_TABLE=1` output). The bar against the sidebar: Dark
|
||||
Modern 9.97, Dark+ 8.60, Light Modern 3.75, Light+ 3.59, HC dark 11.79,
|
||||
HC light 4.83 (all ≥ 3:1).
|
||||
- **F2 distinct levels.** ΔE76 between neighbours, as 0/1, 1/2, 2/3, 3/4 and
|
||||
floor/unlit:
|
||||
|
||||
| theme | before (QA) | after |
|
||||
|---|---|---|
|
||||
| Dark Modern | 14.5 10.7 5.8 **3.0** 14.2 | 9.0 6.2 5.1 3.7 6.4 |
|
||||
| Dark+ | 13.9 10.4 5.3 **2.7** 13.2 | 8.0 6.4 4.6 4.0 5.3 |
|
||||
| Light Modern | 14.5 7.6 4.4 **1.8** 9.0 | 4.4 4.0 4.5 3.9 4.6 |
|
||||
| Light+ | 14.4 7.6 4.3 **1.8** 9.0 | 3.9 4.3 4.0 4.2 4.6 |
|
||||
| HC dark | 19.8 10.7 12.0 7.2 16.0 | 12.6 12.1 12.7 11.3 7.4 |
|
||||
| HC light | 15.7 8.4 6.2 3.7 10.4 | 15.2 12.8 11.6 9.1 9.1 |
|
||||
|
||||
So five levels stay: every neighbour pair is ≥ 3.7, where the old palette
|
||||
had pairs at 1.8. The steps are smaller than before because the whole range
|
||||
is smaller (the price of legible text), but they are now even. On top of the
|
||||
tint, the bar's width and dash differ at every level.
|
||||
- **Regression test** `editors/vscode/hierarchyPalette_test.js` (new, listed
|
||||
in `.vscodeignore`). It computes all of the above from `package.json`'s
|
||||
defaults and fails under 4.5:1 text, under ΔE 3 between neighbours, if the
|
||||
levels are not brightest-first, or under 3:1 for the bar. Proven to bite:
|
||||
pointed at a copy of the manifest with the old level-0 defaults, it fails
|
||||
with "Dark Modern: label on level 0 is 3.68:1, under 4.5".
|
||||
`LUCISV_PALETTE_TABLE=1` prints the table.
|
||||
- **F3.** The HC border rule is now `:not(.bookmarked)`, so a bookmarked
|
||||
current row keeps the bookmark's border. Levels 1–4 get a cue that is not
|
||||
colour in every theme: bar width and style (4 solid, 3 solid, 2 solid,
|
||||
2 dashed, 1 dashed). A bookmarked lit row keeps its bar too
|
||||
(`.row.bookmarked[data-lit]`), so "bookmark wins" now means fill and border.
|
||||
- **F4.** Forced colours: the current row's cue is a dashed `CanvasText`
|
||||
border instead of an outline, so focus and bookmark outlines are no longer
|
||||
overridden. The dropped tint and bar are written down under Goal.
|
||||
- **F7.** `media/hierarchy.js` `relight` skips a non-array entry.
|
||||
- **F8.** Status corrected (18 + 4 checks).
|
||||
- **F5, F6.** Stated under Assumptions, with QA's numbers and examples. The
|
||||
UNC note is under Handshakes, for the lead, with nothing acted on.
|
||||
- `hierarchyCurrent.js` exports `BAR_COLOR`. The manifest test now expects the
|
||||
five tints plus the bar, and checks the bar is opaque in all four kinds and
|
||||
that the CSS uses its variable.
|
||||
- Tests: `node --test editors/vscode/*_test.js` gives 12 files, 12 pass, 0 fail
|
||||
(11 before this round; `hierarchyPalette_test.js` is new). `node --check`
|
||||
is clean on `hierarchyCurrent.js`, `hierarchyCurrent_test.js`,
|
||||
`hierarchyPalette_test.js` and `media/hierarchy.js`. `package.json` parses.
|
||||
- **Still unverified:**
|
||||
- Any of it in a running VS Code.
|
||||
- Whether `color-mix()` with a `var()` percentage and the dashed
|
||||
`repeating-linear-gradient` bar render as intended. The webview's Chromium
|
||||
supports both, and `color-mix` was already used for the bookmark.
|
||||
- Forced-colors behaviour (it follows the spec, but nobody has run it).
|
||||
- The theme table is the built-in themes' published colours, not a capture
|
||||
from a live window.
|
||||
|
||||
### Changelog paragraph (for the lead)
|
||||
|
||||
**The Hierarchy pane shows where you are.** The rows leading to the file you
|
||||
are editing are lit: every instance of the module it declares in a bright
|
||||
orange with a solid bar at its edge, each row above one shade dimmer with a
|
||||
narrower bar, down to a faint floor; labels stay readable at every level. It works on a
|
||||
closed tree and on DUT sections — a header is tinted when its section holds
|
||||
the file or its parents — and switching files repaints only the rows that
|
||||
changed, with no reload of the hierarchy. The shades and the bar are theme
|
||||
colours (`lucisv.hierarchyCurrent`, `lucisv.hierarchyParent1`–`3`,
|
||||
`lucisv.hierarchyAncestor`, `lucisv.hierarchyCurrentBar`) you can override; set
|
||||
`lucisv.hierarchy.highlightCurrent` to `false` to turn it off.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-11-19 — QA (Opus 5.5)
|
||||
|
||||
**Verdict: PASS WITH FINDINGS.** The distance logic, the wiring, the renderer and
|
||||
packaging all check out. One medium finding: text contrast on the current row
|
||||
in dark themes. The rest are low or informational.
|
||||
|
||||
**Commands and results** (worktree `lucisv-wt/71.6`, Node v26.13.0):
|
||||
|
||||
- `node --test editors/vscode/*_test.js`: 11 files, 11 pass, 0 fail (before and
|
||||
after the QA additions).
|
||||
- `node --check` on `hierarchyCurrent.js`, `hierarchyCurrent_test.js`,
|
||||
`hierarchyView.js`, `hierarchyView_test.js`, `hierarchySections.js` and
|
||||
`media/hierarchy.js`: all clean.
|
||||
- `package.json` parses, and `version` is still `0.65.1`.
|
||||
`git diff --name-only 88546c8` plus the untracked files touch only
|
||||
`editors/vscode/**`, `tools/RELEASING.md` and this folder. The `media/` edits
|
||||
only add the `lit` handler, `setLit` and `treeButtons`, and the CSS block for
|
||||
the five levels plus the high-contrast and forced-colors rules. All of it
|
||||
belongs to this feature.
|
||||
- `npx --no-install @vscode/vsce ls --no-dependencies` ran offline (vsce 4.1.1
|
||||
from the npx cache). It lists `hierarchyCurrent.js`, `media/hierarchy.css`
|
||||
and `media/hierarchy.js`, and no `*_test.js` or `smoke` file. `package.json`
|
||||
has no `files` field, so `.vscodeignore` decides what ships.
|
||||
- I checked the VS Code source on `main` myself. In `themeing.ts` the variable
|
||||
name is `'vscode-' + entry.id.replace('.', '-')`, so only the first dot
|
||||
becomes a dash. `colorExtensionPoint.ts` uses the pattern `^\w+[.\w+]*$`, and
|
||||
`highContrast ?? dark` / `highContrastLight ?? light` as fallbacks. The
|
||||
README's account is accurate. All five ids have exactly one dot, the CSS uses
|
||||
`--vscode-lucisv-hierarchy{Current,Parent1,Parent2,Parent3,Ancestor}`, and
|
||||
every id has all four defaults.
|
||||
|
||||
**Attacks on `hierarchyCurrent.js`** (scratch scripts outside the repo; the
|
||||
plain missing assertions were added to `hierarchyCurrent_test.js`):
|
||||
|
||||
- Passed:
|
||||
- an empty snapshot, including in DUT sections
|
||||
- a file that declares no module
|
||||
- one file declaring several modules, two of them on one chain (both are
|
||||
level 0)
|
||||
- an unequal diamond (`top→a→b→c→leaf` plus `top→leaf`): top is lit at 1
|
||||
and the long chain at 3, 2, 1
|
||||
- 50 instances of one module: all lit at 0
|
||||
- a self-instantiating module
|
||||
- a pure cycle with no root
|
||||
- DUT sections over a cycle
|
||||
- a 300-deep chain: 296 rows at the floor, no level outside 0..4
|
||||
- `litLevel(NaN)` and `litLevel(Infinity)` both return `undefined`
|
||||
- Timing, 6 000 modules (a fan-out-3 DAG with cross links):
|
||||
- `matchingFiles` + `currentPath`: 4.9 ms including the first `parentIndex`
|
||||
build, 1.8 ms on a fresh model
|
||||
- `rowLevels` over 176 open rows: 1.6 ms
|
||||
- Property test over 1 500 random DAGs: every lit forward row that is open and
|
||||
not current has a child exactly one level brighter, with 0 violations. See F5
|
||||
for the cyclic case.
|
||||
|
||||
**`media/hierarchy.js`, executed** with a hand-rolled fake `document` and
|
||||
`acquireVsCodeApi` loaded through `vm` (scratch `dom.js`):
|
||||
|
||||
- A render paints `data-lit`.
|
||||
- A `lit` message changes only the rows it names, and the button objects stay
|
||||
the same, so nothing is rebuilt.
|
||||
- Unknown ids and invalid levels (`-1`, `1.5`, missing) are ignored or cleared.
|
||||
- `changes` set to a non-array, or missing, is ignored.
|
||||
- A later full render shows whatever the host sends.
|
||||
- While search is active, the hidden tree still relights and a search row
|
||||
named in a `lit` message is not touched.
|
||||
- Setting off (all-null changes, then a render without `lit`) leaves no lit
|
||||
row.
|
||||
- A `lit` message after an error status does not throw.
|
||||
|
||||
**Findings**
|
||||
|
||||
- **F1 (medium): body text on the level-0 row is below WCAG AA in dark and
|
||||
Light+ themes.** Source: `editors/vscode/package.json`, the
|
||||
`lucisv.hierarchyCurrent` defaults (`dark` `#FFB34773`, `light`
|
||||
`#FF8C0066`). Blended onto typical sidebar backgrounds, the foreground
|
||||
contrast is:
|
||||
|
||||
| theme | foreground | level-0 background | contrast | unlit |
|
||||
|---|---|---|---|---|
|
||||
| Dark Modern | `#CCCCCC` | `#805E2D` | 3.68:1 | 11.06 |
|
||||
| Dark+ | `#CCCCCC` | `#876535` | 3.32:1 | 9.54 |
|
||||
| Light+ | `#616161` | `#F8CA92` | 4.09:1 | 5.58 |
|
||||
| HC dark | `#FFFFFF` | — | 4.67:1 | — |
|
||||
|
||||
The row the user most needs to read is the hardest one to read.
|
||||
Reproduction: `node contrast.js` (scratch). This is a palette decision for
|
||||
the lead and owner. I did not change it.
|
||||
- **F2 (low): level 3 and the floor are close to indistinguishable.** In light
|
||||
themes they differ by ΔE76 1.8 (`#FF8C001F` against `#FF8C001A`), which is
|
||||
under the ≈2.3 just-noticeable difference. Dark+ is at 2.7 and Dark Modern at
|
||||
3.0. The steps between the other levels are 4.3 to 15.7. The floor against an
|
||||
unlit row is ΔE 9.0 to 16.0, which is fine. In practice the user sees about
|
||||
four shades, not five.
|
||||
- **F3 (low): in high-contrast themes a bookmarked current row loses its yellow
|
||||
border.** Source: `media/hierarchy.css:77-80`. The selector
|
||||
`body.vscode-high-contrast .row[data-lit="0"]` (specificity 0,3,1) sets
|
||||
`border-color` and beats the `.row.bookmarked` border (0,2,0). That
|
||||
contradicts "a bookmark wins". The yellow background is kept. In HC only
|
||||
level 0 gets a cue other than colour (the border, plus the bold label every
|
||||
theme gets). Levels 1 to 4 are colour only.
|
||||
- **F4 (low): in `forced-colors`, the focus ring and the bookmark outline are
|
||||
lost on the current row.** Source: `media/hierarchy.css:115`. The rule
|
||||
`.row[data-lit="0"] { outline: 1px dashed Highlight }` comes later and has the
|
||||
same specificity, so it replaces the `.row:focus` outline (line 48) and the
|
||||
bookmark's 2px outline (line 114). That leaves a focused current row without
|
||||
its focus ring. Under forced colors the gradient tint is also dropped (CSS
|
||||
Color Adjust forces `background-image` to `none`), so levels 1 to 4 are
|
||||
invisible there. That is expected, but it is not written down.
|
||||
- **F5 (low, documented): the recursive-design limitation is real and common
|
||||
in dense cycles.** Over 1 500 random cyclic graphs of 3 to 6 modules, 1 165
|
||||
lit open rows had no child one level brighter. Example: with
|
||||
`m0:[m1,m2] m1:[m3,m5] m2:[m1] m3:[m2,m4] m4:[m1,m3] m5:[m0,m4]` and `m3`
|
||||
current, the row `m0 › m1 › m3 › u (m2)` is lit at 2 and its only child,
|
||||
`m1`, is cut as `recursive`. A self-instantiating module does not show this.
|
||||
Assumptions describes it accurately.
|
||||
- **F6 (low, not executed): files are compared exactly after `vscode.Uri`
|
||||
normalization.** From `uri.ts` on `main`, `parse` followed by `toString`
|
||||
lowercases the drive letter and encodes `:` as `%3A`. So
|
||||
`file:///C:/x/top.sv` from the server matches VS Code's
|
||||
`file:///c%3A/x/top.sv`. Two cases do not match:
|
||||
- Directory case is not folded. If a filelist spells the path differently
|
||||
from how the editor opens it (`C:\Proj` against `c:\proj`, on
|
||||
case-insensitive win32 or darwin), nothing lights.
|
||||
- UNC paths: `crates/lucisv_server/src/uri.rs:20-28` turns `\\srv\share\a.sv`
|
||||
into `file:////srv/share/a.sv`, while VS Code uses `file://srv/share/a.sv`.
|
||||
This is a pre-existing server encoding and outside this scope, but here it
|
||||
means nothing lights.
|
||||
|
||||
`vscode-uri` is not available offline, so this comes from reading the source.
|
||||
- **F7 (info): `media/hierarchy.js:157` throws a TypeError on an entry that is
|
||||
not an array** (`changes: [null]`). Only a malformed host message triggers
|
||||
it, and the host never sends one.
|
||||
- **F8 (doc):** Status said "15 checks". It is 18 now, with the QA additions.
|
||||
|
||||
**QA changes:** I added three tests to `hierarchyCurrent_test.js`:
|
||||
`anEmptySnapshotLightsNothing`, `theShorterOfTwoUnequalChainsWins` and
|
||||
`aSelfInstantiatingModuleTerminates`.
|
||||
|
||||
**Still to check in a running VS Code (by a human):**
|
||||
|
||||
- The dev's nine checks in the Work log.
|
||||
- The `onDidChangeActiveTextEditor(undefined)` ordering against
|
||||
`visibleTextEditors` when the last editor closes, and when focus moves to a
|
||||
webview editor such as a Markdown preview.
|
||||
- That contributed colours with alpha really reach the webview (`toString` of
|
||||
a translucent `Color`).
|
||||
- F1 and F2 judged by eye in real themes.
|
||||
- Windows: a drive-letter workspace, and a filelist with path case that
|
||||
differs from the editor's.
|
||||
|
||||
## Review
|
||||
|
||||
**Lead, 2026-11-19.** Accepted for 0.65.2.
|
||||
|
||||
- The brief assumed a TreeView; the pane is a webview, and the dev was right
|
||||
to paint rows with CSS and to take `media/hierarchy.{js,css}` into scope —
|
||||
no other lane owns them. Ruled in.
|
||||
- QA's F1–F4, F7, F8 are fixed in the fix round and I re-ran the suite on the
|
||||
result: 12 test files, 12 pass. The palette test is the part I value most:
|
||||
the contrast claim is computed from the shipped defaults, not asserted.
|
||||
- Read the stylesheet: `--bar-alpha`/`--lit` are set by the per-level rules on
|
||||
the same element the `[data-lit]` rule reads them on, so they resolve; a
|
||||
bookmarked row keeps its fill and border and only adds the bar.
|
||||
- Not verified by anyone: the look in a running VS Code (tint, bar, dashes,
|
||||
forced-colours). I tried to render the stylesheet in a browser from this
|
||||
session and could not. The owner's eye is still owed; the changelog says so.
|
||||
- Left open, recorded under Assumptions: case-differing folder names and UNC
|
||||
paths do not light (the UNC spelling is the server's, `uri.rs:20-28` — a
|
||||
candidate for a later round), and the recursive-design gap.
|
||||
@@ -0,0 +1,408 @@
|
||||
# ifdef-folding
|
||||
|
||||
## Goal
|
||||
|
||||
Owner: "ifdef and else block should support collapsing. It should also be part
|
||||
of the floating bars." Every branch of a `` `ifdef `` / `` `ifndef `` …
|
||||
`` `endif `` region becomes a `textDocument/foldingRange`, so each branch
|
||||
collapses on its own and — because the extension sets
|
||||
`editor.stickyScroll.defaultModel: foldingProviderModel` for both languages
|
||||
(TODO §67) — the branch's directive line is pinned by VS Code's sticky scroll
|
||||
("floating bars") while the reader is inside it. Server-side only: no new
|
||||
setting, no extension code.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Directives are what the lexer says they are.** `vlog_parser::lexer`
|
||||
makes each of the five directives one `TokenKind::Directive` token running
|
||||
to the end of its line (`is_line_directive`, `lexer.rs:899`; capture at
|
||||
`lexer.rs:187-260`). Consequences, all tested:
|
||||
- in a `//` or `/* */` comment → trivia, never a fold;
|
||||
- in a string → part of the string literal;
|
||||
- inside a `` `define `` body (backslash continuations) → text of the
|
||||
`` `define `` token, never a fold;
|
||||
- `` `ifdef A … `else … `endif `` on **one line** is a single token (the rest
|
||||
of the line is its text), so there is nothing to fold — correct;
|
||||
- leading whitespace, trailing `//`/`/* */` comments (the lexer stops before
|
||||
them) and CRLF change nothing.
|
||||
- A directive written after code on its line (`module m; `ifdef A`,
|
||||
`initial begin `ifdef X`) is still a directive, and its branch fold starts
|
||||
on that code line — but that line already starts the `module`/`begin`
|
||||
fold, which is sent first, so **in VS Code such a branch gets no fold of
|
||||
its own** (the existing fold and its sticky-scroll header win; see the
|
||||
ordering rule below). Zero such lines in OpenTitan (4 061 files) or the
|
||||
corpus (860 files): `not_first_on_line: 0`, `shared_start: 0`.
|
||||
- **No existing fold is lost or changed by this feature** (lead's ruling,
|
||||
2026-11-19). Two rules, both in `folding.rs`:
|
||||
- a branch fold with exactly the same two lines as an existing scope or
|
||||
comment fold is not added — the existing fold keeps its kind, so a
|
||||
`/* */` opened on the directive line and ending on the line before the
|
||||
next directive stays a `comment` fold;
|
||||
- the answer's order is defined in one place, `in_answer_order`: by start
|
||||
line; on a shared start line every scope/comment fold (in its own
|
||||
`(start, end)` order, byte-identical to before) comes before any branch
|
||||
fold. Because VS Code keeps only the first range it receives for a start
|
||||
line, the branch fold is the one that yields.
|
||||
- **Fold shape — a branch runs from its directive's line to the line before
|
||||
the next directive of the same region.** `` `ifdef `` line L0, `` `else ``
|
||||
L5, `` `endif `` L9 → `(0, 4)` and `(5, 8)`. Collapsing the first branch
|
||||
leaves `` `else `` visible and separately collapsible; collapsing the last
|
||||
leaves `` `endif `` visible. Chosen to match the existing `begin`/`end` rule
|
||||
in `folding.rs` (the closer stays on screen). For C, VS Code itself ships
|
||||
no `#ifdef` folding — `extensions/cpp/language-configuration.json` folding
|
||||
markers are `#pragma region`/`#pragma endregion` only (checked in the VS
|
||||
Code repo, main branch, 2026-11-19); `#if` folding comes from the C/C++
|
||||
extension's provider, whose exact shape I did **not** verify. The shape
|
||||
here is the one where every directive line stays visible, which is the
|
||||
only one that lets each branch collapse independently.
|
||||
- **Kind: `region`.** Same as every scope-pair fold. LSP 3.17 defines only
|
||||
`comment`, `imports`, `region`; VS Code's *Fold All Regions*
|
||||
(`editor.foldAllMarkerRegions`) folds kind `region`
|
||||
(`folding.ts` `FoldAllRegionsAction` → `setCollapseStateForType(Region)`),
|
||||
which already includes every `begin` fold, so branches joining it is
|
||||
consistent. `imports` would be wrong (and would auto-collapse under
|
||||
`editor.foldingImportsByDefault`).
|
||||
- **Degraded input** (all tested, none panic):
|
||||
- a region still open at end of file folds the branches it *finished*
|
||||
(`` `ifdef `` … `` `else `` … EOF folds the `ifdef` branch) and nothing for
|
||||
the open one — the same "never fold to EOF" policy as an unclosed `begin`;
|
||||
- a stray `` `else ``/`` `elsif ``/`` `endif `` with no region open is
|
||||
ignored and does not disturb later regions;
|
||||
- a branch with no line between its directive and the next yields no range
|
||||
(`push` drops `end <= start`).
|
||||
- **A file that does not lex** has no tokens and folds nothing, as before.
|
||||
|
||||
### VS Code facts this relies on (verified in source, `microsoft/vscode` main, 2026-11-19)
|
||||
|
||||
- `syntaxRangeProvider.ts` `collectSyntaxRanges` keeps a provider range only
|
||||
if `start > 0 && end > start && end <= lineCount` (1-based there) — every
|
||||
range we send satisfies it (pinned by the OpenTitan sweep).
|
||||
- `sanitizeRanges` sorts by start line (then provider rank, a stable sort)
|
||||
and **keeps crossing ranges**: an entry that starts inside the current top
|
||||
and ends after it is added at the top's nesting level without becoming the
|
||||
top. **Ranges sharing a start line: the first in our order survives**
|
||||
(`entry.start > top.start` guard) — with one nuance QA found: the guard
|
||||
compares against `top`, and a crossing entry never becomes `top`, so if
|
||||
the first range on a line was itself added as a crossing entry, a second
|
||||
same-start range that also crosses is kept as well (harmless). A branch
|
||||
fold shares a start line with an existing fold in two ways: a directive
|
||||
after code on its line (`module m; `ifdef A`), or a multi-line `/* */`
|
||||
opened after the directive (`` `ifdef A /* … ``). Existing folds are sent
|
||||
first, so in both cases the existing fold survives and the branch yields.
|
||||
- Parent/child (what sticky scroll nests by) is recomputed by **containment**
|
||||
in `foldingRanges.ts` `ensureParentIndices`, and the sticky model is built
|
||||
from those `FoldingRegions` (`stickyScrollModelProvider.ts`
|
||||
`_fromFoldingRegions`, range end + 1). So a crossing branch is a child of
|
||||
the nearest fold that contains it, and sticky scroll still shows a sane
|
||||
stack.
|
||||
- When the count exceeds `editor.foldingMaximumRegions` (default 5000) the
|
||||
collector keeps shallow levels first. Not new; branches add ~0.26 ranges
|
||||
per OpenTitan file on average.
|
||||
- LSP 3.17 (`foldingRange.md`): validity is per range (lines within the
|
||||
document); the spec says nothing against overlap, and "clients are free to
|
||||
ignore invalid ranges".
|
||||
|
||||
### Crossing structure
|
||||
|
||||
Real RTL opens a `begin` in each arm and closes it once below the `endif`
|
||||
(test `a_region_crossing_a_begin_keeps_both_sets_of_folds`). The result is
|
||||
`[(0,9) module, (2,3) ifdef, (3,8) begin, (4,5) else, (5,7) begin]`: the scope
|
||||
folds are whatever `pairs::analyze` already made of the unbalanced
|
||||
`begin`s (unchanged by this feature), and the branch folds are added beside
|
||||
them, crossing. Per the facts above VS Code keeps all five; sticky scroll at
|
||||
line 7 shows module → `if (a) begin` → `if (b) begin`.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes** `vlog_parser::token::{Token, TokenKind::Directive}` and the
|
||||
lexer's directive capture, read-only. No parser change: the representation
|
||||
is sufficient. The directive-word rule (backtick, then the identifier
|
||||
prefix) is private in `vlog_parser/src/parser/directive.rs:15-28`; it is four
|
||||
lines and is repeated in `folding/directives.rs` rather than widened into
|
||||
the parser's public surface. (A third copy, by first whitespace word, lives
|
||||
in `on_type/auto_end.rs:258`.) If a public `Token::directive_word` is ever
|
||||
added, all three should use it — a request, not a blocker.
|
||||
- **Promises** `folding::folding_ranges` (the only caller is
|
||||
`server/dispatch.rs`, unchanged): sorted by start line (tie-break in
|
||||
`in_answer_order`: existing folds, in their old `(start, end)` order,
|
||||
before branch folds), de-duplicated by `(start, end)` with the existing
|
||||
fold winning, every range `start < end`, branch folds kind `region`. With
|
||||
the branch folds removed the answer is exactly the old answer — asserted
|
||||
per file by the sweep (`check_existing_unchanged`).
|
||||
- **Large-file path: unchanged.** A buffer over the threshold is
|
||||
`Document::large` (`state/document.rs:103`), whose `tokens` are empty, so
|
||||
`folding_ranges` answers `[]` for it exactly as before — pinned already by
|
||||
`server/tests/large_file.rs` (`FoldingRangeRequest` → empty). Supporting
|
||||
branch folds there would need a line scan of the raw text in or beside
|
||||
`large.rs`, which this lane does not own; not requested.
|
||||
- **Scope note for the lead**: the end-to-end test is a new file,
|
||||
`crates/lucisv_server/tests/ifdef_folding.rs` (a new integration test, not
|
||||
an edit to `e2e.rs`), repeating `e2e.rs`'s twenty lines of framing.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Find how directives are represented (one `Directive` token per line).
|
||||
- [x] `folding/directives.rs`: one linear pass → branch spans.
|
||||
- [x] Wire into `folding_ranges` (kind `region`).
|
||||
- [x] Unit tests for every edge case in `folding/ifdef_tests.rs` (15).
|
||||
- [x] Wire test `tests/ifdef_folding.rs`.
|
||||
- [x] OpenTitan sweep `folding/opentitan_sweep.rs` (`#[ignore]`, skips when absent).
|
||||
- [x] Timing before/after.
|
||||
- [x] VS Code README feature rows (Folding, Sticky scroll).
|
||||
- [x] Fix round: existing folds win identical lines and shared start lines
|
||||
(QA findings 1–2); `in_answer_order` defines the order; sweep asserts the
|
||||
non-branch answer is unchanged.
|
||||
- [ ] Human check in a running VS Code (cannot be done by the agent):
|
||||
collapse an `ifdef` branch (the `else` stays visible), collapse the `else`
|
||||
branch (the `endif` stays visible), nested regions, sticky scroll pinning
|
||||
the `` `ifdef ``/`` `else `` line while scrolling inside a long branch, and a
|
||||
crossing `begin` (e.g. one `if … begin` per arm, one `end`).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-11-19 — dev
|
||||
|
||||
- Directives: the lexer's `Directive` tokens are exactly the right
|
||||
representation (comments/strings/define bodies already excluded), so the
|
||||
new pass reads only `token.kind` and the first word. Built
|
||||
`crates/lucisv_server/src/folding/directives.rs` (`branch_spans`, ~90
|
||||
lines): a stack of open-branch start lines; `Open` pushes, `Next` emits the
|
||||
current branch and restarts it, `Close` pops and emits. Line numbers come
|
||||
from the caller (`folding::line`, the same `LineIndex` conversion as the
|
||||
other folds). `folding.rs` gained one loop and the module declarations.
|
||||
- Tests: `folding/ifdef_tests.rs` — shape, `elsif` chain, three-deep nesting,
|
||||
empty branch, one-line region, unterminated, stray directives, port list,
|
||||
`case` + `generate`, `define` body, comment/string, whitespace/trailing
|
||||
comments/CRLF, crossing `begin` (exact list pinned), kind, back-to-back.
|
||||
All passed on the first run. `tests/ifdef_folding.rs` checks the same over
|
||||
the wire (elsif/else/nested ifndef).
|
||||
- **OpenTitan sweep** (`LUCISV_OPENTITAN_HW` or
|
||||
`~/.cache/lucisv-opentitan-full/hw`, 4 061 `.sv`/`.svh`/`.v` files, release
|
||||
build, through `tools/guard.sh`): no panic; every range `start < end` and
|
||||
`end < line count`; every branch fold starts on a line holding a
|
||||
conditional directive token, and that token is the first on its line in
|
||||
every case (`not_first_on_line: 0`); every non-empty branch is present in
|
||||
the answer. Counts: 1 839 directive tokens (772 `ifdef`/`ifndef`, 295
|
||||
`elsif`/`else`, 772 `endif`), all matched, 0 unclosed → 1 067 branch spans
|
||||
= 295 + 772, of which 1 061 are ranges (6 empty branches). A naive text
|
||||
count of lines starting with a directive finds 1 874: the 35 extra are in
|
||||
block comments (`prim_macros.svh:35-46`) and `` `define `` bodies
|
||||
(`prim_assert*.sv*`, `prim_flop_macros.sv`, `dv_defines.svh`, ibex
|
||||
`check/top.sv:181`) — correctly not folded. One file does not lex
|
||||
(`riscv_core_setting.tpl.sv`, a template) and folds nothing, as before.
|
||||
- **Timing** (`folding_ranges` per file, release, same machine, warm):
|
||||
before — whole tree 29.9 ms, slowest `top_darjeeling/.../pinmux_reg_top.sv`
|
||||
(1.3 MB) 0.84 ms; after — whole tree 34.4–35.0 ms, slowest the same file
|
||||
1.09 ms, of which the branch pass is ~0.25 ms (it touches every token
|
||||
once: ~1.5 ns/token). Two after-runs agreed within 2%.
|
||||
- Not touched: `vlog_parser`, `vlog_formatter`, `large.rs`, dispatch,
|
||||
`package.json`.
|
||||
|
||||
### 2026-11-19 — dev, fix round (QA findings 1 and 2, lead's ruling)
|
||||
|
||||
- `folding.rs` split into `scope_and_comment_folds` (the old body, verbatim:
|
||||
pairs + comments, sort `(start, end)`, dedup), `branch_folds` (drops a
|
||||
branch whose `(start, end)` an existing fold already has, so that fold
|
||||
keeps its kind) and `in_answer_order` (the one place the order is defined:
|
||||
a merge by start line, existing folds first on a tie).
|
||||
- **Deviation from the brief's wording, flagged for the lead:** the ruling
|
||||
said "send the LONGER one first" and also "an existing fold is never lost
|
||||
or changed". These disagree in QA's third repro (`` `ifdef A /* c1\n c2 */ ``):
|
||||
the comment `(0,1)` is the existing fold and the *shorter* one. Longer-first
|
||||
would put the branch `(0,2)` first and VS Code would drop the comment fold.
|
||||
Longer-first applied to *all* folds would also reorder existing
|
||||
same-start pairs (e.g. a `begin /* … */` line), so non-directive folds
|
||||
would no longer be byte-identical to base. I implemented "existing first"
|
||||
instead. It gives the same answer as longer-first for both QA repros where
|
||||
the existing fold is longer (`module m; `ifdef A`, `initial begin `ifdef X`),
|
||||
keeps the comment in the third, and leaves every non-branch fold in its old
|
||||
order. If longer-first really is wanted for the comment case, it is a
|
||||
one-line change in `in_answer_order`.
|
||||
- Tests added to `folding/ifdef_tests.rs`: the three QA repros and the
|
||||
comment-kind case (19 tests now); the `folds` helper asserts every answer
|
||||
is sorted by start line.
|
||||
- Sweep: new per-file assertion `check_existing_unchanged` (answer minus
|
||||
branch folds == the scope/comment folds exactly, same order and kinds;
|
||||
answer length == both added together) and two counts. OpenTitan: as
|
||||
before (1 839 tokens, 1 067 spans, 1 061 ranges), `same_lines_as_existing:
|
||||
0`, `shared_start: 0`, tree 33.8 ms, slowest file 1.09 ms. Corpus
|
||||
(`~/.cache/lucisv-corpus`, 860 files, via `LUCISV_OPENTITAN_HW`): 923
|
||||
tokens, 511 spans, 511 ranges, `shared_start: 0`, `same_lines_as_existing:
|
||||
0`, `not_first_on_line: 0`, passed.
|
||||
|
||||
## Changelog paragraph (for the lead)
|
||||
|
||||
**`` `ifdef `` branches fold, and stick.** Every branch of a
|
||||
`` `ifdef ``/`` `ifndef `` region now folds on its own, from its directive to
|
||||
the line before the next `` `elsif ``/`` `else ``/`` `endif `` — which stays
|
||||
visible, so the `else` branch can be collapsed separately — and, because
|
||||
sticky scroll follows the folds, the directive of the branch you are in is
|
||||
pinned at the top of the editor with the module and blocks around it. Nested
|
||||
regions fold at every depth; directives inside comments, strings and
|
||||
`` `define `` bodies are left alone; an unterminated region never folds to the
|
||||
end of the file. Buffers over the large-file threshold still fold nothing.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-11-19 — QA (Opus 5.5)
|
||||
|
||||
**Verdict: PASS WITH FINDINGS** (two low-severity findings, two info notes;
|
||||
nothing fixed by QA, no source file touched). The machine was heavily loaded
|
||||
throughout (another QA lane's cargo jobs, load average 19–21), so the
|
||||
timings below are upper bounds.
|
||||
|
||||
**Gates** (worktree, uncommitted diff on 948f8a0):
|
||||
- `cargo fmt --all -- --check` clean; `cargo clippy --all-targets -- -D
|
||||
warnings` clean (the one cargo-level `workspace.package.authors` manifest
|
||||
warning is pre-existing and not a lint).
|
||||
- `tools/guard.sh -- cargo test -p lucisv_server`: 1 973 passed, 0 failed
|
||||
(lib 1 863 + 37 ignored; e2e 106; grammar 3; `ifdef_folding` 1;
|
||||
opentitan_references 0 + 2 ignored). `tools/guard.sh -- cargo test -p
|
||||
vlog_formatter`: all green. `node --test editors/vscode/*_test.js`: 37/37.
|
||||
- Ignored sweep, `tools/guard.sh -t 1500 -- cargo test --release -p
|
||||
lucisv_server opentitan_sweep -- --ignored --nocapture`: ok; 4 061 files,
|
||||
1 unlexed, 1 839 tokens (772/295/772), 1 067 spans, 1 061 ranges, 0
|
||||
unclosed, `not_first_on_line: 0`; whole-tree `folding_ranges` 33.4 ms
|
||||
(branch pass 4.7 ms), slowest `top_darjeeling/.../pinmux_reg_top.sv`
|
||||
1.07 ms (branches 0.24 ms) — consistent with the work log.
|
||||
- Scope: `git status` shows only `folding.rs` (modified, purely additive:
|
||||
module decls, doc, one loop), `folding/{directives,ifdef_tests,
|
||||
opentitan_sweep}.rs`, `tests/ifdef_folding.rs`, `editors/vscode/README.md`,
|
||||
this README. Sizes: `folding.rs` 296 lines incl. tests (~85 production),
|
||||
`directives.rs` 85 — well under CLAUDE.md thresholds.
|
||||
|
||||
**Attack inputs over LSP** (release and debug `lucisv-server`, one
|
||||
`didOpen` + `textDocument/foldingRange` per buffer; script kept in the QA
|
||||
scratchpad, `qa714/cases.py`). Hand-computed expectation matched every one:
|
||||
10-deep nesting `(i, 19-i)` for i=0..9; `elsif` chains; empty first branch
|
||||
(`ifdef`/`else` adjacent → only the `else` fold); `else` directly before
|
||||
`endif`; two `else` in one region and `elsif` after `else` (each treated as
|
||||
"next branch", three folds, no panic); `endif // c`; `endif /* multi-line */`
|
||||
(comment folds separately, branch unaffected); spaces/tabs before
|
||||
directives; CRLF; no trailing newline ending in `` `endif ``; directives in
|
||||
`/* */`, `//`, a string inside a live region (`$display("`endif `else")`),
|
||||
a `` `define `` body with `\` continuations (LF and CRLF), a `` `define `` with
|
||||
a trailing `\` at EOF (both after a region and alone); mid-line
|
||||
`assign a = b; `ifdef X` and `end `ifdef A` (lexed as a directive, fold
|
||||
starts on that code line — sensible); region crossing `begin…end`,
|
||||
crossing a module boundary, wrapping a whole module, inside a port list,
|
||||
inside a `case`; `` `ifdef_helper ``/`` `elseif ``/`` `endif_x ``/`` `IFDEF ``/
|
||||
`` `ENDIF `` (no folds); `` `include ``/`` `timescale `` between branches;
|
||||
one-line region; stray `else`/`endif`; unterminated region.
|
||||
|
||||
**Fuzz** (`qa714/fuzz.py`, 2 × 5 000 random buffers through one server
|
||||
session each, through `tools/guard.sh`): half well-nested generated regions
|
||||
up to 7 deep, half random directive/code/comment/`define`/string/look-alike
|
||||
line soup, 30 % CRLF, 20 % no trailing newline. Checked against an
|
||||
independent line-model (my own scan: directive first on a line, outside block
|
||||
comments and `define` bodies): every answer present, sorted, `start < end <
|
||||
line count`, region folds == model's non-empty branch spans exactly, every
|
||||
fold on a directive line, no crossing branch folds in well-nested input.
|
||||
**0 failures** in 10 000. Sanity: the same checker against the base binary
|
||||
fails 1 673/2 000, so it is not vacuous.
|
||||
|
||||
**Scale** (`qa714/big.py`): 50 000-branch `elsif` chain (1.4 MB), 25 000
|
||||
back-to-back `ifdef/else` regions, and 50 000-deep nesting (1.7 MB): 0.20 s,
|
||||
0.22 s, 0.24 s round-trip vs base 0.17/0.18/0.20 s; 12.5k → 25k → 50k
|
||||
doubles cleanly (linear, no quadratic term, no stack overflow at 50 000
|
||||
deep). VS Code's 5 000 cap (`RangesCollector.toIndentRanges`) keeps shallow
|
||||
levels first and, within the cut level, the first in order — for a flat chain
|
||||
the module plus the first 4 999 branches; nothing harmful. Note only that a
|
||||
branch fold adds one nesting level to what it contains, so in a file already
|
||||
over 5 000 folds a few deep `begin` folds may now fall past the cut instead of
|
||||
a branch. Not new behaviour, no real file near it.
|
||||
|
||||
**Regression of existing folds** — done by **building the base**, not by
|
||||
reading the diff: `git archive 948f8a0` into the QA scratchpad, own
|
||||
`CARGO_TARGET_DIR`, release build; both binaries over the full OpenTitan
|
||||
`hw` tree (4 061 files) and `~/.cache/lucisv-corpus` (860 files) via LSP.
|
||||
Result: every base fold (start, end, kind) is still present in the new
|
||||
answer (0 lost in 4 921 files), and new − base equals the independent model's
|
||||
non-empty branch spans exactly in every file (0 mismatches). So on real code
|
||||
the non-directive fold set is identical to 948f8a0. Independent recount
|
||||
(own scan, not the lexer): OpenTitan 1 839 directives (772 open / 295 next /
|
||||
772 close), 1 067 spans, 1 061 non-empty, 0 unclosed — matches the dev
|
||||
exactly; corpus 923 directives, 511 spans, 511 non-empty.
|
||||
|
||||
**VS Code source** (`microsoft/vscode` main, fetched 2026-11-19:
|
||||
`folding/browser/syntaxRangeProvider.ts`, `foldingRanges.ts`, `folding.ts`,
|
||||
`stickyScroll/browser/stickyScrollModelProvider.ts`,
|
||||
`stickyScrollProvider.ts`, `stickyScrollController.ts`). Confirmed: the
|
||||
`start > 0 && end > start && end <= nLines` filter; `sanitizeRanges` sorts by
|
||||
start then provider rank (stable, so our order), drops any entry whose start
|
||||
equals the current `top`'s start, and adds crossing entries at `top`'s level
|
||||
without making them `top`; `ensureParentIndices` assigns parents by
|
||||
containment (popping a non-containing parent); sticky scroll builds its tree
|
||||
from those parents (`_fromFoldingRegions`, end + 1) and walks it;
|
||||
`FoldAllRegionsAction` → `setCollapseStateForType(Region)`. Nuance to the
|
||||
README's "only the first survives": that holds when the first becomes `top`;
|
||||
if the first was itself a crossing entry (not `top`), a second range with the
|
||||
same start that also crosses is kept as well — harmless. With a crossing
|
||||
fold, sticky scroll gets sibling roots at the same depth (e.g. `module a` and
|
||||
an `ifdef` that runs into `module b` are both depth-0 candidates), so both
|
||||
lines are pinned; exact pixel layout needs a running VS Code.
|
||||
|
||||
**Findings**
|
||||
|
||||
1. **Low — a block-comment fold can lose its `comment` kind.**
|
||||
`crates/lucisv_server/src/folding.rs:55-56`: branch spans are pushed
|
||||
before comments and the dedup keeps the first of an equal `(start, end)`,
|
||||
so when a multi-line `/* */` starts on a directive line and ends on the
|
||||
line before the next directive, the base `comment` fold becomes a
|
||||
`region`. Repro: `` "`ifdef A /* c1\n c2\n c3 */\n`else\n b;\n`endif\n" ``
|
||||
— base `[(0,2,comment)]`, new `[(0,2,region),(3,4,region)]`. Effect: *Fold
|
||||
All Block Comments* no longer folds it (*Fold All Regions* now does); the
|
||||
hidden lines are the same. 0 occurrences in OpenTitan + corpus.
|
||||
2. **Low — same-start-line collisions keep the shorter fold, which can drop
|
||||
an existing one in VS Code.** Sorting `(start, end)` ascending puts the
|
||||
shorter range first, and VS Code keeps only that one. Repros (LSP):
|
||||
`"module m; `ifdef A\n a;\n`endif\nendmodule\n"` → `[(0,1) ifdef,
|
||||
(0,2) module]`: VS Code drops the **module** fold that base showed (and
|
||||
sticky scroll no longer pins `module m;` past line 1);
|
||||
`"module m;\ninitial begin `ifdef X\n a;\n b;\n `endif\n c;\nend\nendmodule\n"`
|
||||
→ `(1,3)` ifdef before `(1,5)` begin: the `initial begin` fold is
|
||||
dropped. Conversely `"`ifdef A /* c1\n c2 */\n x;\n`else\n b;\n`endif\n"`
|
||||
→ `(0,1) comment` before `(0,2) region`: the **branch** is the one
|
||||
dropped. The README (Assumptions → VS Code facts) says a shared start line
|
||||
happens "only when a directive follows code on its line"; the comment case
|
||||
shows it is also a multi-line block comment *after* the directive. 0
|
||||
occurrences in 4 921 real files (only directive-after-text lines found are
|
||||
inside `//` comments, `prim_flop_2sync.sv:33,37`). Whether equal-start
|
||||
ranges should be ordered longer-first (keeps base folds, loses the branch)
|
||||
is a design choice for the lead, not a QA fix.
|
||||
3. **Info — lone-CR files fold nothing**, base and new alike (the lexer and
|
||||
line index only break on `\n`). Pre-existing, unchanged.
|
||||
4. **Info — README accuracy**: line references checked and correct
|
||||
(`lexer.rs:187-260`, `:899`; `parser/directive.rs:15-28`;
|
||||
`on_type/auto_end.rs:258`; `state/document.rs:103`). Corrections: see
|
||||
finding 2 (the same-start condition) and the `sanitizeRanges` nuance
|
||||
above. The "not verified" list (C/C++ extension's `#if` shape, the human
|
||||
VS Code check) is honest and remains unverified.
|
||||
|
||||
**Unverifiable without a running VS Code**: the visual result of collapsing
|
||||
each branch, the sticky-scroll stack and its layout for crossing folds
|
||||
(two depth-0 siblings), and which fold the user actually sees for the
|
||||
same-start cases above (derived from source, not observed).
|
||||
|
||||
## Review
|
||||
|
||||
**Lead, 2026-11-19.** Accepted for 0.65.4.
|
||||
|
||||
- Built on the lexer's directive tokens with no parser change: the right
|
||||
foundation, and it is why the 35 look-alike lines in OpenTitan are skipped
|
||||
without a special case. The three copies of the directive-word rule are a
|
||||
fair follow-up (`Token::directive_word`), not this round's business.
|
||||
- My fix-round instruction said "longer first"; the dev was right to depart
|
||||
from it. The principle I gave — an existing fold is never lost or changed —
|
||||
and "longer first" disagree when a short comment fold shares a start line
|
||||
with a longer branch, and the principle is the one that matters.
|
||||
"Existing first" is what ships, defined in one place (`in_answer_order`).
|
||||
- QA's regression check is the proof I wanted: base built from `git archive`,
|
||||
both binaries over 4 921 real files, non-directive folds byte-identical; a
|
||||
10 000-case fuzz against an independent model whose checker demonstrably
|
||||
fails on the base binary.
|
||||
- Owed to a human: the collapse and sticky-scroll behaviour in a running
|
||||
editor, in particular crossing regions (an `ifdef` that spans two modules
|
||||
pins both headers as siblings, by QA's reading of VS Code's source).
|
||||
- Open, recorded: no folds on the large-file path; lone-CR files fold nothing
|
||||
(as before).
|
||||
@@ -0,0 +1,126 @@
|
||||
# instantiation-highlighting
|
||||
|
||||
## Goal
|
||||
|
||||
Give module and interface instantiations distinct, recognizable syntax colours
|
||||
instead of painting every part of an instantiation with the default variable
|
||||
foreground. Borrowing the roles other languages assign to constructor and
|
||||
component calls (C++, Rust, TypeScript/JSX), each syntactic piece of an
|
||||
instantiation takes its own semantic token class and theme-safe TextMate scope:
|
||||
|
||||
1. **Module / interface name** (`uart_core` in `uart_core #(...) u_uart (...)`,
|
||||
`pkg::uart_core` with `pkg` as `namespace`, and lone `bind` targets) →
|
||||
`class` (`entity.name.type.class`).
|
||||
2. **`#` sign and parameters** (`#` before parameter port or override lists,
|
||||
`.BAUD_DIV` dot + parameter-port name, `parameter`/`localparam` symbols, and
|
||||
unresolved constant identifiers inside `#(...)`) → `parameter`
|
||||
(`keyword.control` / `constant.language` / `variable.parameter`), sharing
|
||||
one colour that stays distinct from bracket-pair-coloured `()`.
|
||||
3. **Instance name** (`u_uart`, gate instances, `bind` target instances, and
|
||||
uses of `SymbolKind::Instance` such as `u_uart.sig`) → `function`
|
||||
(`entity.name.function`).
|
||||
4. **Port name** (`.clk_i` dot + port name, implicit `.clk_i`, and wildcard
|
||||
`.*` in an instance's connection list) → `property`
|
||||
(`entity.name.tag.css` / `entity.other.attribute-name` /
|
||||
`variable.other.property`).
|
||||
5. **Port connection** (`clk` inside `.clk_i(clk)` or positional `(clk)`) →
|
||||
`variable` (`support.variable` / `entity.other.attribute-name` /
|
||||
`variable.other.readwrite`), keeping signal colouring consistent across the
|
||||
file and non-white in themes that leave bare `variable` uncoloured.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The 14-type wire legend is unchanged.** Every role above maps onto the
|
||||
existing `SemanticTokenType` indices (`namespace`, `class`, `parameter`,
|
||||
`variable`, `property`, `function`), so `token_types().len() == 14` and
|
||||
`token_modifiers().len() == 1` stay untouched on the wire.
|
||||
- **AST spans decide instantiation structure; single-file + overlay semantics
|
||||
decide expressions.** A buffer opened before workspace indexing finishes, a
|
||||
standalone file, or an instantiation of an unindexed vendor macro still
|
||||
highlights its module name, `#`, `.PARAM`, instance name, and `.port` from
|
||||
`Document.tree` alone. Identifiers that resolve through `Document.external`
|
||||
also take their cross-file `SymbolKind` instead of degrading to `variable`.
|
||||
- **Parameter `#` only, never delay `#`.** Only the `#` introducing a parameter
|
||||
port list, parameter override list, or parameterized `DataType` receives
|
||||
`Highlight::Parameter`; `#5` and `#(1:2:3)` net, assignment, gate, and
|
||||
procedural delays remain unemitted punctuation.
|
||||
- **Large-file fast path (`Document::large`) stays lexer-only.** Because the
|
||||
fast path builds no AST or symbol table, AST-driven `#`, `.`, and `.*` tokens
|
||||
are emitted only by the full pipeline, alongside identifier refinement.
|
||||
- **Editor defaults remain user-overridable.** Setting
|
||||
`editor.semanticHighlighting.enabled = true` in `configurationDefaults` for
|
||||
`[verilog]` and `[systemverilog]` activates semantic tokens in themes whose
|
||||
own `semanticHighlighting` flag is unset or `false`, while any explicit user
|
||||
or workspace setting still wins.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumed from `vlog_parser`:** `SourceFile`, `Item`/`ItemKind`, `Module`,
|
||||
`Instantiation`, `Instance`, `Connections`, `Connection`, `BindDirective`,
|
||||
`GateInstantiation`, `ClassDecl`, `ClassExtends`, `DataType::params`,
|
||||
`ListElem`, `RawText`, `Token`, `TokenKind`, `TextRange`. No parser changes.
|
||||
- **Consumed from `vlog_semantic`:** `Semantics`, `SymbolKind`,
|
||||
`ExternalResolutions::definition_of`, `Definition`. No semantic changes.
|
||||
- **Promised to LSP clients (`crates/lucisv_server/src/tokens.rs`):** identical
|
||||
14-entry `token_types` legend and 1-entry `token_modifiers` legend; sorted,
|
||||
non-overlapping single-line UTF-16 tokens; exact `full/delta` round-trip.
|
||||
- **Shared with `editors/vscode/package.json`:** `contributes.semanticTokenScopes`
|
||||
keys for `verilog` and `systemverilog` are a subset of `tokens::token_types()`,
|
||||
checked by `editors/vscode/semanticTokens_test.js`.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Add `crates/lucisv_server/src/tokens/instantiation.rs` for AST-guided
|
||||
instantiation and parameter-header highlight overrides.
|
||||
- [x] Update `crates/lucisv_server/src/tokens.rs` to apply overrides, consult
|
||||
`Document.external` via `definition_of`, map `SymbolKind::Instance` to
|
||||
`Highlight::Function`, and add unit tests covering instantiation shapes,
|
||||
delay `#` exclusion, recovered entries, and `large-file-mode` window
|
||||
agreement.
|
||||
- [x] Configure `editor.semanticHighlighting.enabled` and
|
||||
`contributes.semanticTokenScopes` for `verilog` and `systemverilog` in
|
||||
`editors/vscode/package.json`, with headless verification in
|
||||
`editors/vscode/semanticTokens_test.js` (and `.vscodeignore` exclusion).
|
||||
- [x] Update `docs/features/lucisv-server/README.md` and
|
||||
`docs/features/large-file-mode/README.md` for the refined mapping.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-11-17 — dev
|
||||
|
||||
- Audited `tokens.rs`, `editors/vscode/package.json`, and VS Code theme scope
|
||||
tables across Dark Modern/Dark+, Light Modern/Light+, GitHub Dark, One Dark
|
||||
Pro, Monokai, and Visual Studio Dark. Found two root causes for flat white
|
||||
instantiations: (1) `tokens.rs` consulted only single-file `Semantics`
|
||||
(leaving external module names, `.PARAM` overrides, `.port` names, and
|
||||
`SymbolKind::Instance` all on `Highlight::Variable`, and leaving `#`
|
||||
unemitted); (2) `package.json` neither defaulted
|
||||
`editor.semanticHighlighting.enabled` on nor mapped semantic token types to
|
||||
distinct TextMate scopes for themes where `variable`/`parameter`/`property`
|
||||
collapse to white or one shared colour.
|
||||
- Added `crates/lucisv_server/src/tokens/instantiation.rs` (~280 total lines)
|
||||
and wired `crates/lucisv_server/src/tokens.rs` without changing the 14-type
|
||||
wire legend:
|
||||
- Module/interface/`extends` names → `Highlight::Class` (`pkg::` prefixes →
|
||||
`Highlight::Namespace`);
|
||||
- Parameter-list `#` (headers, instantiations, parameterized `DataType`s,
|
||||
never delays), `.PARAM` overrides (`.` + name), and unresolved constant
|
||||
identifiers inside `#(...)` → `Highlight::Parameter`;
|
||||
- `SymbolKind::Instance`, `Instance.name_span`, gate instances, and `bind`
|
||||
instance lists → `Highlight::Function`;
|
||||
- Named port connections (`.` + name, implicit `.name`, wildcard `.*`),
|
||||
including recovered unfinished entries while typing → `Highlight::Property`;
|
||||
- Port connection expressions stay on `identifier_type` (`Highlight::Variable`
|
||||
for signals), now backed by `ExternalResolutions::definition_of`.
|
||||
- Added `editor.semanticHighlighting.enabled: true` under
|
||||
`configurationDefaults` and `semanticTokenScopes` for `verilog` and
|
||||
`systemverilog` in `editors/vscode/package.json`; added
|
||||
`editors/vscode/semanticTokens_test.js` (75 checks, all green under `node`)
|
||||
and listed it in `editors/vscode/.vscodeignore`.
|
||||
- Cargo/Rust toolchain is not installed on this Windows host; Rust formatting
|
||||
(`use_small_heuristics = "Max"`, ≤100 cols), clippy rules, and test
|
||||
invariants were audited manually for Gitea CI execution.
|
||||
|
||||
## QA log
|
||||
|
||||
## Review
|
||||
@@ -184,11 +184,12 @@ documented difference below.
|
||||
|
||||
### What it gets wrong, honestly
|
||||
|
||||
- **A plain identifier is always `variable`, with no `declaration` modifier.**
|
||||
There is no `Semantics` to refine it with, so a module name is not a `class`
|
||||
and a parameter is not a `parameter`. Keywords, numbers, strings, comments,
|
||||
directives, macro uses, `$system` tasks and attributes are all exactly what
|
||||
the full pipeline says.
|
||||
- **A plain identifier is always `variable`, with no `declaration` modifier, and
|
||||
AST-only instantiation punctuation (`#`, `.`, `.*`) is unemitted.** There is
|
||||
no `Semantics` or `Document.tree` to refine them with, so a module name is
|
||||
not a `class` and a parameter or `#` is not a `parameter`. Keywords, numbers,
|
||||
strings, comments, directives, macro uses, `$system` tasks and attributes are
|
||||
all exactly what the full pipeline says.
|
||||
- **A `/*` inside a string or after a `//` fools the backward scan**, and so
|
||||
does a block comment whose opener is more than 64 KiB back — the documented
|
||||
answer there is "code", so a multi-megabyte block comment mis-highlights.
|
||||
|
||||
@@ -0,0 +1,449 @@
|
||||
# linux-test-portability
|
||||
|
||||
## Goal
|
||||
|
||||
Every suite had only ever run on macOS arm64. Make `cargo clippy --all-targets
|
||||
-- -D warnings` and `cargo test --workspace` pass on Linux x86-64 — in the CI
|
||||
job image, as root (how the runner's jobs run) and as an unprivileged user —
|
||||
while staying green on macOS, and do one cleaning round on the test code that
|
||||
the Linux runs drive (TODO §70). Test code only: where a platform or user
|
||||
genuinely cannot exercise what a test is about, the test detects it at run
|
||||
time and stops with a message; it never asserts the opposite and never weakens
|
||||
the assertion where it *can* run.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- Root (CAP_DAC_OVERRIDE / CAP_DAC_READ_SEARCH) ignores file modes, so the
|
||||
unreadable- and unwritable-path tests cannot build their path as root.
|
||||
Not assumed from the uid: each test probes the exact behaviour it needs
|
||||
(a mode-000 directory refuses `read_dir`, a mode-000 file refuses `open`,
|
||||
a mode-555 directory refuses a new file) in a scratch path of its own,
|
||||
then restores the mode.
|
||||
- Case sensitivity is a property of the filesystem, not the OS. The one
|
||||
runtime-probed case test (`file_ops.rs`) asks the filesystem
|
||||
(`DEFS.svh` is a file when only `defs.svh` was written); the existing
|
||||
`#[cfg(any(target_os = "macos", target_os = "windows"))]` case tests keep
|
||||
their compile-time scope, whose reason is written at each.
|
||||
- A skipped test still reports `ok` in `cargo test`; the `skipped: …` line
|
||||
on stderr (visible with `--nocapture`) is how a run says so. std has no
|
||||
runtime-skip outcome, and no dependency is added for one.
|
||||
- The linear-time tests' bound is a ratio between sizes measured in the
|
||||
same process moments apart, so it does not depend on the machine's speed;
|
||||
it does assume load from the tests running beside it does not inflate the
|
||||
largest size's *fastest of five* by more than ~3x relative to the
|
||||
smallest's.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- Consumes nothing new from production code. No production file, no
|
||||
`verify.rs`, no workflow, version file or changelog changes.
|
||||
- `tools/linux_check.sh` (the lead's): used as written in round 1; changed
|
||||
in the fix round (QA finding 5, see the work log). Its usage line gained
|
||||
`--dry-run`; the single-string form is unchanged.
|
||||
- Scope extension granted by the lead in the fix round:
|
||||
`crates/lucisv_server/src/server/tests/scan_trace.rs` (test file only).
|
||||
- Requests: none.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Clippy clean on Linux and macOS: the three unused imports were the
|
||||
only reports.
|
||||
- [x] The eight permission-denied tests probe whether modes bind and stop
|
||||
with a message when they do not.
|
||||
- [x] The case-mismatch test probes the filesystem's case sensitivity.
|
||||
- [x] The two linear-time tests bound growth, not wall-clock; shown to trip
|
||||
on the quadratic conversion on macOS and on the Linux runner.
|
||||
- [x] Cleaning round (see work log).
|
||||
- [ ] Linux suite green as root (twice) and as `--user`. Observed: root
|
||||
once green; `--user` once with one failure, the new flake
|
||||
`scan_trace::the_stages_add_up_to_the_scan_they_describe` (open, see
|
||||
the work log); the second root run and the flake's diagnosis were cut
|
||||
off when ssh to luhpe stopped working.
|
||||
- [x] `tools/gates.sh` green on macOS (see the work log for each run).
|
||||
- [x] Fix round: `scan_trace` lower bound on the best of three sessions;
|
||||
linear-time tests best of five; `tools/linux_check.sh` hardened.
|
||||
- [ ] Open follow-up (QA finding 4, not changed on purpose):
|
||||
`large.rs` `references_on_one_giant_line_locate_their_hits_in_linear_time`
|
||||
times a copy of the `Server::large_scan` loop, not the production loop
|
||||
at `server/large_file.rs:151`, so a per-hit rescan reintroduced there
|
||||
would not be caught. Needs a test that drives the production path.
|
||||
- [ ] Re-run on Linux once ssh to luhpe is back: everything in the fix round
|
||||
and everything since 0.65.2 is unverified there (list in the work log).
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-11-19 (dev).**
|
||||
|
||||
Baselines at 88546c8 (before any change). macOS `cargo test --workspace`:
|
||||
93 result lines, **5307 passed, 0 failed, 57 ignored** (5364). Linux as uid
|
||||
1001 (`tools/linux_check.sh --user`): **5298 passed, 3 failed, 57 ignored** —
|
||||
the case-mismatch test and the two linear-time tests; every permission test
|
||||
passed, which confirms the lead's hypothesis 1 (they fail only as root). The
|
||||
Linux total is 6 lower than macOS's because six tests are compiled only on
|
||||
macOS/Windows.
|
||||
|
||||
Causes, per failure:
|
||||
|
||||
1. *Clippy, three unused imports* (`hover.rs` `qa_hover_declarations`:
|
||||
`FromStr`; `includes.rs` `qa_round2`: `super::*`, `fs`): their only users
|
||||
are `#[cfg(any(target_os = "macos", target_os = "windows"))]` tests.
|
||||
`qa_round2` holds nothing else, so the cfg moved onto the module (with the
|
||||
reason as its doc comment) and off its two tests; in `hover.rs` the
|
||||
`FromStr` import carries the same cfg as its one user.
|
||||
2. *Eight permission tests* (hypothesis 1, confirmed): root opens, lists and
|
||||
writes whatever the mode says. Each gets a probe of the behaviour it
|
||||
relies on and returns early, saying `skipped: …`, when the probe is not
|
||||
refused:
|
||||
- `crates/lucisv/tests/cli.rs` — `listing_is_refused()` (mode-000 dir),
|
||||
used by both walk-warning tests.
|
||||
- `crates/lucisv_core/src/walk.rs` — `reading_is_refused(rel)` (mode-000
|
||||
directory or file), used by the unreadable-directory and
|
||||
unreadable-`.gitignore` tests.
|
||||
- `crates/lucisv_mcp/src/apply.rs` — `creating_is_refused(dir)` (mode-555
|
||||
dir). Only the *second* half of
|
||||
`a_write_that_fails_after_another_landed_says_what_was_written` needs it:
|
||||
the read-only-file refusal before it is decided from the mode bits
|
||||
(`Permissions::readonly`), holds as root, and is still asserted there.
|
||||
The same file is compiled into `tests/qa_m3.rs` via `#[path]`, so the
|
||||
fix covers both targets.
|
||||
- `crates/lucisv_mcp/tests/cache.rs` — `creating_is_refused` (mode 555,
|
||||
the unwritable cache directory).
|
||||
- `crates/lucisv_mcp/tests/qa_m6.rs` — `listing_is_refused` (mode 000).
|
||||
- `crates/lucisv_server/src/state/tests/filelist.rs` —
|
||||
`listing_is_refused()` (mode 000).
|
||||
3. *Case-mismatch include* (hypothesis 2, confirmed: "must narrow in: []" on
|
||||
Linux): on a case-sensitive filesystem `DEFS.svh` names no file, so there
|
||||
is nothing to narrow in. The test now writes `defs.svh`, asks whether
|
||||
`DEFS.svh` is a file, and stops with a message when it is not; the reason
|
||||
is in its doc comment. On macOS it runs in full as before.
|
||||
4. *Two `…_in_linear_time` tests* (hypothesis 3, confirmed, with a
|
||||
correction). Not superlinear product code: run alone on the Linux runner
|
||||
both are exactly 2x per 2x (locate 13.5 / 27.0 / 54.3 / 108.7 ms, colour
|
||||
22.1 / 44.2 / 89.5 / 182.1 ms; three runs within 3%), and on macOS the
|
||||
same (locate 3.4 / 6.7 / 13.6 / 26.2 ms, colour 5.6 / 11.0 / 22.6 /
|
||||
44.7 ms). The trial's 4x for 100 → 200 hits (20.6 → 81.4 ms) and its
|
||||
781 ms colour sample came from the full suite: the tests ran beside ~1 900
|
||||
others on a 4-CPU cap, and a single sample per size took whatever load it
|
||||
landed on. Alone on the runner they would even have met the old budgets
|
||||
(108 < 150, 182 < 350 ms); in the suite they do not. The references test's
|
||||
input grows hits *and* line length together, so the walker's work (each
|
||||
byte once) is linear in `width` and the per-hit rescan's quadratic — the
|
||||
test bounds the right thing.
|
||||
|
||||
Rewrite (`crates/lucisv_server/src/large.rs`): the fixtures are built
|
||||
first; `fastest_of_three` times every size in three interleaved rounds and
|
||||
keeps each size's minimum (load slows one sample of each size, not every
|
||||
sample of one); `assert_grows_linearly` fails when the largest size (8x the
|
||||
input) costs more than `GROWTH_SLACK` (3) × 8 = 24x the smallest. The
|
||||
absolute `COLOUR_BUDGET_MS`/`LOCATE_BUDGET_MS` constants are gone. The
|
||||
per-size `eprintln!` stays (the lex timing it also printed is dropped —
|
||||
it was never asserted).
|
||||
|
||||
**Shown to trip.** Temporarily put the per-call converter back —
|
||||
`positions.position(..)` for `walker.position(..)` at both sites in
|
||||
`tokens::flatten` (`tokens.rs`), and `positions.range(*hit)` for
|
||||
`walker.range(*hit)` in the references test's loop — and ran
|
||||
`cargo test -p lucisv_server --bin lucisv-server large::tests:: -- --nocapture`:
|
||||
- macOS: both FAILED — locate 6.3 / 24.9 / 99.1 / 395.8 ms, **62.8x**;
|
||||
colour 34.3 / 129.2 / 511.9 / 2 060 ms, **60.0x** (limit 24x).
|
||||
- Linux runner (root): both FAILED — locate 87.1 / 346.6 / 1 368.5 /
|
||||
5 507.7 ms, **63.2x**; colour 383.9 / 1 539.2 / 6 503.1 / 27 667.6 ms,
|
||||
**72.1x**.
|
||||
Then restored both files from copies taken before the edit;
|
||||
`git status` shows `tokens.rs` unmodified. With the walker: 8.0x / 8.0x on
|
||||
macOS, 8.0x / 8.2x on Linux. Margin: ~3x on each side of the limit.
|
||||
|
||||
Cleaning round (test code only, driven by the tool reports):
|
||||
- The unused imports above were everything clippy reported on either
|
||||
platform; `cargo build`/`cargo test` reported no other test warnings.
|
||||
- `walk.rs`'s `TempTree` was documented "removed on drop" but had no `Drop`
|
||||
impl, so every walk test left its tree in the temp dir; added the
|
||||
three-line `Drop` the comment describes (the test trees restore their
|
||||
modes before returning, so removal succeeds).
|
||||
- The other wall-clock assertions in the suites (`server/tests/startup.rs`,
|
||||
`tests/e2e.rs`'s grace checks, `vlog_semantic/tests/workspace.rs`'s 5 s
|
||||
build bound) passed on every Linux run here and are left as they are;
|
||||
`large.rs`'s hundred-megabyte probe is `#[ignore]`d.
|
||||
|
||||
Final runs, all against the finished tree (every change above, including
|
||||
`#[track_caller]` on `assert_grows_linearly`; nothing in `crates/` changed
|
||||
after them, only this README and TODO.md):
|
||||
- macOS `cargo test --workspace` (guarded): 93 result lines, **5307 passed,
|
||||
0 failed, 57 ignored** — the baseline's count exactly.
|
||||
- Linux root, then `--user` (2026-11-19, both finished before the ~05:00 ssh
|
||||
outage), root: `cargo clippy --all-targets -- -D warnings`
|
||||
exit 0, no diagnostics; `cargo test --workspace --no-fail-fast`: 93
|
||||
result lines, **5301 passed, 0 failed, 57 ignored**.
|
||||
- Linux `--user` (right after): clippy exit 0, no diagnostics; tests **5300
|
||||
passed, 1 failed, 57 ignored** — the failure is
|
||||
`server::tests::scan_trace::the_stages_add_up_to_the_scan_they_describe`
|
||||
at `crates/lucisv_server/src/server/tests/scan_trace.rs:163`, the
|
||||
`sum >= total * 0.5` assertion (the stages a `--verbose` scan's trace
|
||||
names must cover at least half its wall-clock total). It passed in the
|
||||
root run, in the lead's 88546c8 `--user` run, and 15 times out of 15 run
|
||||
alone as `--user`; a repeat of the whole `lucisv_server` binary to catch
|
||||
its numbers was cut off by the ssh outage (exit 137 from the ssh side, not
|
||||
a guard kill). Reading: a wall-clock ratio over a ~20 ms scan, where a
|
||||
preemption landing in the deliberately unattributed loop time (progress
|
||||
callbacks, staging pushes) on the 4-CPU runner under the full suite's load
|
||||
can tip it below half. **Open, not changed**: without its failing numbers
|
||||
any change to the 0.5 would be a weakening without evidence.
|
||||
- Not done: the second Linux root run the brief asks for.
|
||||
- macOS after trunk's fast-forward to 0.65.2 (e9f5090; touched no file
|
||||
this lane edits): `cargo fmt --all -- --check` exit 0, clippy clean,
|
||||
`tools/gates.sh` **PASS** (`target/gates/20261119-050602/`: every step
|
||||
pass; suites vlog_parser 521, vlog_semantic 418, vlog_refactor 743,
|
||||
vlog_formatter 352, vlog_linter 672, lucisv_core 117, lucisv 143,
|
||||
lucisv_server 1957, lucisv_mcp 383, all 0 failed; corpus 814/6, node
|
||||
12/0). An earlier gates run (03:58) was cut off mid-`lucisv_mcp` when the
|
||||
session restarted — not a guard kill — and is not counted. The Linux runs
|
||||
above were against 88546c8 + this lane, not against 0.65.2.
|
||||
|
||||
**2026-11-19 (dev, fix round after QA's PASS WITH FINDINGS).** Tree: trunk
|
||||
948f8a0 (0.65.3) + this lane. ssh to luhpe is down, so nothing in this
|
||||
round ran on Linux.
|
||||
|
||||
1. *scan_trace flake* (QA finding 2). `the_stages_add_up_to_the_scan_they_describe`
|
||||
now runs three verbose sessions over the same 40-file tree. It asserts
|
||||
`total > 0` and `sum <= total * 1.02` on **every** session (structural:
|
||||
the stages are disjoint pieces of the scan), and `sum/total >= 0.5` on
|
||||
the **best** of the three (a stall in the ~35% unattributed loop time
|
||||
spoils one sample, not all three). The reason is in the test's comment.
|
||||
The stage list moved to a helper, `named_stage_sum`.
|
||||
- Unmutated, macOS: 3 sample ratios 0.64 / 0.68 / 0.69.
|
||||
- *Does it still bite?* Temporary production mutations, each built into a
|
||||
copied test binary and then restored from a copy (`git status` clean for
|
||||
both files after):
|
||||
- `scan_trace.rs:321`, the `read` stage not recorded: 30/30 runs of the
|
||||
copied binary FAILED (best 0.41–0.47). Of 3 runs through cargo, one
|
||||
passed: the first, run just after the build.
|
||||
- `state/rescan.rs:358`, the `parse` stage not recorded: **27/30** FAILED
|
||||
(best 0.38–0.49), 3 passed. A per-sample count of the same mutant
|
||||
(what the old single-session assertion would have checked):
|
||||
87/90 samples under 0.5. So best of three trades some sensitivity to
|
||||
one dropped mid-sized stage (~97% → 90% for `parse`, about a fifth of
|
||||
the scan) for not flaking under load. A dropped stage under ~17% of
|
||||
the scan is invisible to a 0.5 bound either way, as before.
|
||||
- *Under load*, the way QA did it (guarded; the test binary looped 200x
|
||||
while the whole `lucisv_server` binary looped beside it): 0/200 failed;
|
||||
a second 200x run, with 8 full-suite iterations counted alongside: 0/200.
|
||||
2. *`tools/linux_check.sh`* (QA finding 5).
|
||||
- `set -o pipefail`, and tar's stderr is no longer hidden.
|
||||
- One argument is a command line as before. Several are quoted with
|
||||
`printf '%q '`, so `linux_check.sh grep -rn "two words" crates` keeps
|
||||
`two words` whole.
|
||||
- A fixed container name, `--name lucisv-linux-check`, so a second
|
||||
concurrent run is refused by Docker; exit 125 prints a hint.
|
||||
- The header says that untracked non-ignored files are sent and that
|
||||
runs are one at a time.
|
||||
- New `--dry-run`: builds the archive locally, prints its size and the
|
||||
remote command, and contacts nothing.
|
||||
|
||||
Tested locally:
|
||||
- `bash -n` ok (shellcheck is not installed).
|
||||
- `--help` prints the whole header.
|
||||
- `--dry-run` with one string and with several arguments: the remote
|
||||
`CMD` shows the quoting kept.
|
||||
- `LUCISV_LINUX_HOST=nonexistent.invalid`: exit 255, ssh's error shown.
|
||||
- In a throwaway git repo with a tracked file deleted: `--dry-run` exit 1
|
||||
and the real path exit non-zero, with `tar: b.txt: Cannot stat` shown;
|
||||
restoring the file makes the dry run pass.
|
||||
|
||||
**The remote half is untested since this change**: the `--name`
|
||||
refusal, the 125 hint, and the multi-argument `CMD` reaching
|
||||
`bash -c` on luhpe.
|
||||
3. *Linear-time headroom* (QA finding 3). `fastest_of_three` → `fastest_of_five`;
|
||||
`GROWTH_SLACK` unchanged. QA's loaded loop (30 runs, 36 busy loops on 18
|
||||
CPUs, load average ~40, guarded): 30/30 passed. Worst ratios: colour
|
||||
**10.8x**, locate **8.5x** (limit 24x; QA saw 18.2x at three rounds).
|
||||
Cost: on the quadratic code a failing run now takes 5/3 as long (Linux
|
||||
root colour ~3 min, from the round-1 measurements).
|
||||
|
||||
Checks this round (macOS, tree 948f8a0 + lane):
|
||||
- `cargo fmt --all -- --check` exit 0.
|
||||
- `cargo clippy --all-targets -- -D warnings` exit 0.
|
||||
- `tools/guard.sh -- cargo test -p lucisv_server`: 1848 + 106 + 3 + 0
|
||||
passed, 0 failed (36 + 3 + 0 + 2 ignored).
|
||||
- `tools/gates.sh` **PASS** (`target/gates/20261119-053236/`): every step
|
||||
pass; suites 521/418/743/352/672/117/143/1957/383, all 0 failed; corpus
|
||||
814/6; node 37/0.
|
||||
|
||||
Unverified on Linux (all of it rests on round 1, against 88546c8 + lane):
|
||||
- the `scan_trace.rs` rewrite;
|
||||
- best of five in `large.rs`;
|
||||
- the new `linux_check.sh`;
|
||||
- QA's `qa_m6.rs` doc-comment move;
|
||||
- everything trunk added in 0.65.2 and 0.65.3;
|
||||
- the second root run, which never happened in round 1 either.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-11-19 (QA, macOS arm64, 18 CPUs; tree = 948f8a0 + this lane).**
|
||||
Verdict: **PASS WITH FINDINGS.** Linux was **not** independently verified.
|
||||
|
||||
*Scope.* Every hunk of `git diff -- crates/` is inside a `#[cfg(test)]`
|
||||
module or a `tests/` file: `cli.rs`, `cache.rs`, `qa_m6.rs` (integration
|
||||
tests), `walk.rs`/`apply.rs`/`file_ops.rs`/`large.rs` (inside `mod tests`),
|
||||
`filelist.rs` (under `state/tests/`), `hover.rs` (an import in the
|
||||
`#[cfg(test)] mod qa_hover_declarations`), `includes.rs` (the
|
||||
`#[cfg(test)] mod qa_round2` attribute widened to
|
||||
`all(test, any(macos, windows))`, the two per-test cfgs dropped — same
|
||||
compiled set). `walk.rs`'s new `Drop for TempTree` sits in `mod tests`
|
||||
(the struct is test-only). No `verify.rs`, no production line, `tokens.rs`
|
||||
and `convert.rs` unmodified.
|
||||
|
||||
*No skip on macOS.* All 11 tests (plus `apply`'s copy in `tests/qa_m3.rs`
|
||||
and `--bin lucisv-mcp`) run with `--nocapture`: all `ok`, no `skipped:`
|
||||
line.
|
||||
|
||||
*Mutations* (copies in the scratchpad, restored with `cp`; `git diff --stat`
|
||||
and the full `git diff` compared byte-for-byte with the pre-mutation
|
||||
capture: identical):
|
||||
|
||||
| test | mutation | failed? | restored |
|
||||
|---|---|---|---|
|
||||
| cli `an_unreadable_directory_is_a_warning…` | `walk.rs` `entries`: `Err(_) => return` (no warning) | yes, cli.rs:2277 | yes |
|
||||
| cli `the_walks_warnings_leave_check_modes…` | same | yes, cli.rs:2296 | yes |
|
||||
| walk `an_unreadable_directory_is_skipped…` | same | yes, walk.rs:847 | yes |
|
||||
| filelist `an_unreadable_directory_is_said_once…` | same | yes, filelist.rs:106 | yes |
|
||||
| walk `an_unreadable_ignore_file_is_said…` | `walk.rs` `push_ignore`: drop the `say` | yes, walk.rs:864 | yes |
|
||||
| apply `a_write_that_fails_after…` (bin + qa_m3) | `apply.rs:192` message `written`→`wrote` | yes, both targets, apply.rs:322 (the post-probe half) | yes |
|
||||
| cache `an_unwritable_cache_directory…` | asserted count 1→2 | yes, cache.rs:276 | yes |
|
||||
| qa_m6 `qa_a_cache_directory_without_permission…` | asserted count 1→2 | yes, qa_m6.rs:485 | yes |
|
||||
| file_ops `a_case_mismatched_include…` | `read.contains` inverted | yes, file_ops.rs:729 | yes |
|
||||
| large colour / locate | own mutation: a fresh walker per piece in `tokens::flatten`, a fresh walker per hit in the test's loop | yes: **74.0x** and **64.5x** (limit 24x) | yes; `tokens.rs` no diff; pass again at 8.1x/8.1x |
|
||||
|
||||
*Probe attacks.* No false skip found: every probe builds its scratch path
|
||||
next to (same filesystem as) the test's own, under a pid(+counter)-unique
|
||||
name (`filelist.rs`'s `modeprobe` is pid-only but has one caller); a setup
|
||||
failure panics (`expect`/`unwrap`) instead of returning "not refused"; a
|
||||
spurious error can only read as "refused", which runs the test (a loud
|
||||
failure, not a masked one); there is no panic path between the chmod and
|
||||
its restore; probes remove their paths (Drop or `remove_dir_all`). Root
|
||||
with DAC capabilities gets "not refused" (dev-observed on Linux, not
|
||||
re-run). 20 loops of the eight affected targets (cli walk, core walk,
|
||||
mcp bin + qa_m3 apply, cache, qa_m6, server filelist, server file_ops):
|
||||
**0/160 failures**, and no `lucisv*` temp dir or mode-000/555 path left
|
||||
behind (walk.rs's new `Drop` works; before it, 18 walk dirs per run were
|
||||
left in `$TMPDIR`).
|
||||
|
||||
*Linear-time tests.* Under load, best of three interleaved: 30 runs while
|
||||
a release `cargo build` ran: 0/30 failed, ratios 7.9–8.5x; 30 runs with 36
|
||||
busy loops on 18 CPUs (load ~30) as well: 0/30 failed, ratios **up to 18.2x
|
||||
(colour) and 13.9x (locate)**, so only ~1.3x left under the 24x limit at
|
||||
2x oversubscription. Judgement: a constant-factor regression of any size
|
||||
(2.9x or 100x) passes by design: the ratio cannot see it, and the old
|
||||
absolute budgets that could were dropped on purpose. n·log n passes
|
||||
(~9.9x). A mixed cost slips through when its quadratic part is under ~28%
|
||||
of the smallest size's cost (`8(1-q)+64q ≤ 24`). That is acceptable for a
|
||||
test named "linear time" that guards against the per-call converter
|
||||
coming back (60–74x).
|
||||
|
||||
*scan_trace flake (dev's open item) — reproduced on macOS.* I built an
|
||||
instrumented test binary (a temporary `eprintln!` of sum/total, source
|
||||
restored at once, `git diff` clean) and ran the test 200x under 36 busy
|
||||
loops: 0/200 failed, sum/total 0.62–0.69, total 2.1–4.4 ms. Then 200x while
|
||||
the whole `lucisv_server` suite looped beside it: **1/200 failed**: stages
|
||||
**2.21 ms of total 5.10 ms (0.43)**. Two more runs came in at 0.54 and 0.67
|
||||
with totals of 4.8 and 2.7 ms. Analysis: `total_ms` runs from
|
||||
`ScanTrace::new` in `begin_scan` to `landed`. The named stages are disjoint
|
||||
sub-intervals of it, so `sum ≤ total` is deterministic (up to `{:.2}`
|
||||
rounding, 19 × 0.005 ms). But ~35% of an unloaded scan is deliberately
|
||||
unattributed: the server's per-step `watching` callbacks, progress/log
|
||||
sends and loop overhead in `server/index.rs` `scan_once`. A stall that
|
||||
lands there grows `total` and no stage. The failing sample is exactly that:
|
||||
the stage sum is normal (2.21 ms) and the 2.9 ms extra sits outside every
|
||||
stage. With U≈0.35·T, one stall longer than ~0.3·T in unattributed code
|
||||
trips the bound: ~0.75 ms on macOS, ~6 ms on the Linux runner's ~20 ms
|
||||
scan, where CFS quota throttling under `--cpus` gives stalls of tens of
|
||||
ms. So the lower bound is a statistical claim and is unsound under load on
|
||||
any machine. **Recommended change** (outside this lane's files, not made
|
||||
here): keep `sum <= total * 1.02` per scan, and assert the lower bound on
|
||||
the best of three sessions. Run `Session::verbose_wide` three times and
|
||||
require `max(sum/total) >= 0.5`, the same "load slows one sample, not
|
||||
every sample" argument as `fastest_of_three`. The alternative is to drop
|
||||
the lower bound and assert only that the CPU-bound stages (`discovery`,
|
||||
`read`, `parse`) are each > 0.
|
||||
|
||||
*Gates (macOS, `tools/gates.sh`, `target/gates/20261119-052309/`):* PASS —
|
||||
fmt, clippy, build, docs pass; suites vlog_parser 521/0, vlog_semantic
|
||||
418/0, vlog_refactor 743/0, vlog_formatter 352/0, vlog_linter 672/0,
|
||||
lucisv_core 117/0, lucisv 143/0, lucisv_server 1957/0, lucisv_mcp 383/0;
|
||||
corpus 814/6; node 37/0. Separately `cargo fmt --all -- --check` exit 0,
|
||||
`cargo clippy --all-targets -- -D warnings` exit 0 (only cargo's
|
||||
pre-existing manifest `authors` notice), guarded `cargo test --workspace
|
||||
--no-fail-fast`: 93 result lines, **5307 passed, 0 failed, 57 ignored**,
|
||||
the dev's count exactly.
|
||||
|
||||
*Linux: NOT verified by QA.* `tools/linux_check.sh 'echo ok'` (once):
|
||||
`Permission denied (publickey)`, exit 255; not retried. These results rest
|
||||
on the dev's word alone: root clippy clean and 5301 passed/0 failed;
|
||||
`--user` clippy clean and 5300 passed/1 failed (the scan_trace flake,
|
||||
which is now reproduced on macOS). The second root run was never done.
|
||||
Nothing here has run on Linux since the 0.65.2/0.65.3 fast-forwards.
|
||||
|
||||
*Findings.*
|
||||
1. (low, fixed by QA) `crates/lucisv_mcp/tests/qa_m6.rs:447`: the new
|
||||
helper was inserted between the test's doc comment and the test, so
|
||||
`qa_a_cache_directory_without_permission…`'s four-line doc comment had
|
||||
become the head of `listing_is_refused`'s doc. I moved it back above the
|
||||
test; the diff now only adds the helper and the guard.
|
||||
2. (medium, open, outside scope) `server/tests/scan_trace.rs:163`: the
|
||||
flake above, with its reproduction and the recommended change.
|
||||
3. (low) `large.rs` linear-time margin under heavy oversubscription:
|
||||
18.2x of 24x seen. Watch it on the 4-CPU runner; if it flakes, raise
|
||||
the number of rounds, not `GROWTH_SLACK`.
|
||||
4. (low, pre-existing) `large.rs` `references_on_one_giant_line…` times a
|
||||
copy of the `Server::large_scan` loop (`server/large_file.rs:151`), not
|
||||
the production code, so a regression there is not caught. The mutation
|
||||
had to go into the test's own loop.
|
||||
5. (low) `tools/linux_check.sh` review:
|
||||
- The pipeline has no `pipefail`, and tar's stderr goes to
|
||||
`/dev/null`. A local `git ls-files`/tar failure, or a file that
|
||||
vanished, gives a silently partial tree, and the run is judged on it.
|
||||
A missing archive does fail remotely (`tar xzf` under `set -e`).
|
||||
- `cmd=$*` drops argument quoting (`linux_check.sh grep "a b" f` runs
|
||||
`grep a b f`). The documented single-string form is fine.
|
||||
- `--others --exclude-standard` ships any untracked, non-ignored file
|
||||
(a stray `.env`, key or dump) to luhpe, though only into a `--rm`
|
||||
container, not the volume. Today that is just this README and the
|
||||
script itself (16 KiB).
|
||||
- Not safe to run concurrently: two runs share the
|
||||
`lucisv-linux-check` volume, so they race on a cold rustup install
|
||||
into `/cache`. A `--user` run's `chown -R /cache` flips ownership
|
||||
under a running root build, and one run can execute test binaries
|
||||
the other rebuilt from a different tree. A host-side `flock`, or a
|
||||
fixed `docker run --name` so a second run fails fast, would close
|
||||
this.
|
||||
- The remote quoting is right: one `%q` for the one shell level on the
|
||||
host, and `docker exec`/`docker run` pass argv with no shell. Exit
|
||||
status propagates through ssh → docker → `bash -c`.
|
||||
|
||||
*Fixed by QA:* finding 1 only. *Unverified:* everything on Linux, as
|
||||
above.
|
||||
|
||||
## Review
|
||||
|
||||
**Lead, 2026-11-19.** Accepted on macOS evidence; Linux line left open.
|
||||
|
||||
- Test code only, and QA checked every hunk for that. The risk in a lane like
|
||||
this is a test that passes by no longer testing: QA's mutation table (every
|
||||
modified test made to fail, every file restored byte-identically) and the
|
||||
"none prints `skipped:` on macOS" run are what make it acceptable.
|
||||
- I was wrong about the references test: I read 100→200 hits costing 4x as a
|
||||
possible superlinear product bug and told the dev so. Measured alone it
|
||||
doubles per doubling on both platforms; the 4x was the parallel suite. The
|
||||
ratio assertion that replaced the wall-clock budget is the better test, and
|
||||
it was shown to trip at ~60–74x on a quadratic implementation by dev and QA
|
||||
independently.
|
||||
- `scan_trace` was a pre-existing fragile test that Linux exposed and QA then
|
||||
reproduced on macOS (2.21 ms of 5.10 ms). I extended scope to fix it. The
|
||||
best-of-three lower bound costs sensitivity (the dev measured ~97% → ~90%
|
||||
on a dropped `parse` stage) — accepted and written down, not hidden.
|
||||
- **Not verified on Linux**: everything since round 1 — the `scan_trace`
|
||||
rewrite, best-of-five in `large.rs`, the rewritten `tools/linux_check.sh`
|
||||
(its remote half has never run), and all of 0.65.2–0.65.4. The owner's ssh
|
||||
key expired mid-lane. TODO §70's Linux line and the `ci.yml` job stay
|
||||
unticked until that run happens; the Linux job is not added blind.
|
||||
- Open follow-up, recorded under Status: the references linear-time test
|
||||
times a copy of `Server::large_scan`'s loop, not the production code.
|
||||
@@ -573,25 +573,35 @@ Modifiers: `0 declaration`.
|
||||
| `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 |
|
||||
| `TokenKind::Symbol` (`#` before parameter lists; `.` / `.*` on named connections) | `parameter` / `property` |
|
||||
| `TokenKind::Symbol`, otherwise | **not emitted** |
|
||||
| `TokenKind::Ident`, otherwise | from `Document.tree` + `Semantics` + `ExternalResolutions`, 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`.
|
||||
A plain identifier first checks the AST overrides built by
|
||||
`tokens/instantiation.rs` (`docs/features/instantiation-highlighting/README.md`):
|
||||
an instantiated module or `extends` base takes `class` (`pkg::` prefixes take
|
||||
`namespace`), an instance name takes `function`, a `.PARAM` override and any
|
||||
unresolved constant identifier inside `#(...)` take `parameter` alongside `#`,
|
||||
and a `.port` connection takes `property`. Otherwise it is looked up through
|
||||
`ExternalResolutions::definition_of` (`Semantics` first, then the workspace
|
||||
overlay): a declaration (`symbol_at`) carries the `declaration` modifier, a
|
||||
resolved local or external reference takes its target's `SymbolKind`, and
|
||||
anything else 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`.
|
||||
`SymbolKind` → type: `Module`/`Interface`/`Modport`/`Class`/`Covergroup`→`class`,
|
||||
`Package`→`namespace`, `Typedef`→`type`, `EnumVariant`→`enumMember`,
|
||||
`Param`/`LocalParam`/`TfArg`→`parameter`,
|
||||
`Function`/`Task`/`Instance`/`Property`/`Sequence`→`function`,
|
||||
`StructMember`/`Constraint`/`Coverpoint`/`Cross`→`property`, and
|
||||
`Port`/`Net`/`Var`/`Genvar`/`Clocking`/`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.
|
||||
- **Ordinary punctuation (including `()`) is not emitted.** Every editor
|
||||
already colours brackets from its bracket-pair colorizer or TextMate grammar,
|
||||
and emitting one token per `;` roughly triples the payload for no visible
|
||||
gain; only the parameter-list `#` and named-connection `.`/`.*` carry AST
|
||||
highlights.
|
||||
- **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
|
||||
|
||||
@@ -0,0 +1,538 @@
|
||||
# port-entry-grace
|
||||
|
||||
## Goal
|
||||
|
||||
The owner (TODO §68.2): "don't rush to show the syntax error when the user is
|
||||
editing the port, help auto complete the port syntax, like `.po...()`, and use
|
||||
the auto-completed, syntax correct version to run syntax highlighting and
|
||||
lint." Lane A (§68.1) makes accepting a port write `.name()`. This lane makes
|
||||
the editor calm while a named connection is being typed inside an instance's
|
||||
port list or `#(` parameter list. Two halves:
|
||||
|
||||
1. **Parser recovery** (`vlog_parser`, tolerant mode only): an unfinished
|
||||
entry — a lone `.`, a `.name(` left open at the end of its line, a missing
|
||||
`,`, a trailing `,` — stays inside its own entry. It still costs exactly one
|
||||
diagnostic, whose span lies inside the entry (or on the one token that
|
||||
proves it), and the rest of the list, the instance and the file parse,
|
||||
colour and lint as if the entry were complete.
|
||||
2. **The server withholds the entry being typed** (`lucisv_server`): while the
|
||||
last edit of a buffer sits inside a connection list, the diagnostics
|
||||
(parse *and* lint) whose range starts inside the entry around it are left
|
||||
out of what is published or pulled, and said again when the next edit lands
|
||||
outside the entry, when `PORT_ENTRY_GRACE` (1500 ms) passes with no edit, or
|
||||
when the buffer is saved, closed or reopened.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Tolerant mode only.** The whole-file formatter parses strictly, so every
|
||||
shape here is refused by `format_source` exactly as before
|
||||
(`crates/vlog_formatter/tests/port_entry_refusal.rs`), and no file the
|
||||
strict parser accepts reads differently in tolerant mode
|
||||
(`valid_lists_read_the_same_in_both_modes`,
|
||||
`tolerant_parse_equals_strict_parse_on_valid_sources`; QA: 911 repo files
|
||||
identical). **Corrected after QA:** the formatter *does* read the tolerant
|
||||
tree in two places — Format Selection (`vlog_formatter/src/selection/mod.rs`,
|
||||
`Tree::parse` falls back to it) and fences (`fence.rs`) — and the tolerant
|
||||
diagnostic count is compared before/after by `vlog_refactor`'s check
|
||||
(`check/mod.rs`) and the MCP placement check (`place/verify.rs`). The one
|
||||
rule that changes what they see is (d), the trailing `,` now being
|
||||
reported. QA measured the consequence (accepted by the lead): Format
|
||||
Selection over 673 single-line selections in 113 files — 55
|
||||
refused→formatted (selections clear of the instance in files whose only
|
||||
fault is a trailing `,`, which used to be "not a tree to trust"), 0
|
||||
formatted→refused, 0 changed outputs; the refactor check and the MCP
|
||||
placement check now catch an edit that leaves `.a(x),)`; corpus
|
||||
`picorv32/scripts/smtbmc/mulcmp.v` (two named lists ending in `,`, which
|
||||
yosys accepts) is now flagged in the editor.
|
||||
- **The unfinished entry is an error element, not a fabricated connection.**
|
||||
`ListElem::Error` with the entry's raw text — the marker header recovery
|
||||
already has. A synthesized `.po()` would make the tolerant tree claim a `)`
|
||||
the source never wrote, and the MCP placement check compares tolerant trees
|
||||
of two texts (`lucisv_mcp/src/tools/place/verify.rs`): `.po(` and `.po()`
|
||||
must not compare equal. No new AST variant.
|
||||
- **"The entry being typed" is where the last edit ended.** Incremental sync
|
||||
only: the byte offset just past the last change's inserted text, in the new
|
||||
text. A full-document sync (rangeless change) remembers nothing and
|
||||
withholds nothing.
|
||||
- **One buffer is being typed in at a time.** An edit in buffer B releases
|
||||
whatever buffer A was withholding at once, rather than after A's grace.
|
||||
- **1500 ms is a constant**, not a setting (same reasoning as
|
||||
`CHANGE_DEBOUNCE`): long enough to finish a port name and its connection,
|
||||
short enough that a real mistake left behind shows before attention moves.
|
||||
- **The withheld window rides the generation.** Every change of what
|
||||
`diagnostics_of` answers moves `generation` (the pull `resultId`): the edit
|
||||
itself (flush), the release (grace or edit elsewhere), the save. A pull
|
||||
answered while withholding can never be "unchanged" against a later full
|
||||
list.
|
||||
- **During a running scan the loop is the scan's**, so a grace that ends mid
|
||||
scan is released when the scan hands the loop back (the same holds for the
|
||||
change debounce today).
|
||||
|
||||
## The exact rules
|
||||
|
||||
### Half 1 — parser (`parser/recover_list.rs`, call sites in `parser/instance.rs`)
|
||||
|
||||
Applied in both the `#(` override list and a named connection list.
|
||||
|
||||
- **(a) lone `.`** — a `.` followed by `,` `)` `;` EOF, a construct
|
||||
keyword (`endmodule`…), or — on a later line — a keyword or a `.`. A `.`
|
||||
or keyword on the same line (`..z (p)`, `.input(x)`) keeps the generic
|
||||
recovery: one error element holding the whole of it. It becomes an error
|
||||
element holding just the `.`; diagnostic `expected a name after \`.\`` on
|
||||
the `.`. (A same-line keyword, `.input(x)`, keeps the generic recovery,
|
||||
whose skip takes the whole `.input(x)`.)
|
||||
- **(b) open value** — at a `.name(`'s `(`, the value is abandoned when all
|
||||
three hold: (1) the `(` is still open at the end of its line; (2) the next
|
||||
line begins with `.`, `)`, `;`, a keyword, or EOF; (3) the bracket is not
|
||||
closed the way a value's is — no matching `)` before a `;`/construct
|
||||
keyword/EOF, or the matching `)` is followed by `;`, EOF, a construct
|
||||
keyword, `.`, or a plain (non-macro) identifier. Valid lists always follow a
|
||||
value's `)` with `,`, `)` or a directive/macro, so (3) is false on every
|
||||
valid file — `.po(top` ⏎ `.sig), .q(r)` reads as written. The existing
|
||||
error `unclosed \`(\` in a port or parameter connection` is raised at the
|
||||
`(`, and the existing element recovery takes the `(` and skips to the end of
|
||||
its line — at the value's own level. A bracket opened *inside* the
|
||||
abandoned value (`.c(f(`, `.c(z[`, `.c({`, `.c((`) is skipped
|
||||
bracket-balanced, so the element swallows the entries below it and the
|
||||
list's `)` (`.c(f(\n .b(y))`). Same at c1076f9; a known limit. Condition (2) keeps the pinned ambiguous shape `.D(` ⏎
|
||||
`u0 (.a(x)));` exactly as it was (an identifier opening the next line is
|
||||
`value_runs_into_next_instance`'s question).
|
||||
- **List continuation after a recovered entry** — `connection_list_ends`: in
|
||||
tolerant mode, after an error element with no `,` behind it, a `.` at the
|
||||
cursor is the next connection and the list reads on, silently (the
|
||||
recovered entry already has its diagnostic). Any other token still ends the
|
||||
list as `list_ends` always did.
|
||||
- **(c) missing `,`** — unchanged from header recovery: both entries are
|
||||
`Ok`, one `expected \`,\`` on the `.` of the second entry — the token that
|
||||
proves the comma missing. After a recovered entry, (b) above applies
|
||||
instead (no second diagnostic).
|
||||
- **(d) trailing `,`** — a `,` that only the list's `)` follows, in a named
|
||||
list or an override list: `expected a connection after \`,\`` on the `,`.
|
||||
Tolerant mode used to end the list there *silently* while strict mode
|
||||
refused — a gap this closes. A positional list's trailing `,` is an omitted
|
||||
connection and stays legal.
|
||||
- `.name(z);` on one line (both `)` already typed, list unclosed) is
|
||||
unchanged: `Ok(.name(z))` plus `expected \`)\`` on the `;`.
|
||||
|
||||
### Half 2 — entry bounds (`state/port_grace.rs`, `entry_around`)
|
||||
|
||||
The list is `signature::enclosing_list`'s, but only believed when (1) no `;`
|
||||
stands between its `(` and the edit (the bracket count takes a value left open
|
||||
for the list never closing; a connection list never holds a `;`); (2) it is
|
||||
a **named** list — it holds an entry at its own level that starts with `.`
|
||||
(the one being typed counts; a `.` opening its own line counts at any depth);
|
||||
and (3) it is not a declaration header's — no `module`, `macromodule`,
|
||||
`interface`, `program`, `class`, `package`, `primitive`, `function`, `task`
|
||||
or `checker` keyword between it and the `;` before. So positional instance
|
||||
lists, call arguments, a function declaration with a user return type, a call
|
||||
after `begin : label` and every header `#(` withhold nothing. Then:
|
||||
|
||||
- **start** — walking from the list's `(` to the edit: the last `,` at the
|
||||
list's level (included), else the list's `(` (excluded); a `.` that opens
|
||||
its own line always starts an entry (depth reset) — where the parser ends a
|
||||
value left open on the line above.
|
||||
- **end** — walking on from the edit at the depth the edit is at: the first
|
||||
`,` at that level or any `;` (excluded, its start), the first closing
|
||||
bracket that would go below that level, or the end of the edit's line —
|
||||
reaching on to the next line's first token when that is a `.` (the token
|
||||
that proves a `,` missing).
|
||||
- A diagnostic is withheld iff its range **starts** in `[start, end]`, both
|
||||
ends included.
|
||||
|
||||
Agreement with Half 1: (a) on the `.` — inside; (b) on the `(` — inside;
|
||||
(c) on the next entry's `.` — inside whether the user typed the entry below
|
||||
(the entry starts at its line's `.`) or above (the entry reaches the next
|
||||
line's `.`), and on one line (no `,` between); (d) on the `,` — inside the
|
||||
entry after it (start includes the `,`).
|
||||
|
||||
### Half 2 — when (`state/port_grace.rs` `PortGrace`, `server/*`)
|
||||
|
||||
- `didChange` → `sync::apply_changes_at` gives the edit end →
|
||||
`PortGrace::edited` (pending; other buffers marked released).
|
||||
- flush (`flush_dirty`) → after `set_document`, `locate_port_entry` looks the
|
||||
edit up in the fresh tokens; outside any list it is forgotten.
|
||||
- `diagnostics_of` (push and both pulls) → `PortGrace::withhold`.
|
||||
- The loop (`Server::run`) waits `min(CHANGE_DEBOUNCE if dirty, time to the
|
||||
earliest grace deadline)`; on the timeout, and at the top of every
|
||||
iteration, `release_port_entries` bumps the generation and republishes each
|
||||
due buffer. No thread, no new wake-up mechanism.
|
||||
- `didSave` / `didClose` / `didOpen` forget the buffer's entry before the
|
||||
flush; a save of a non-dirty buffer that was withholding republishes it.
|
||||
- Formatting, semantic tokens, completion: untouched. The formatter refuses
|
||||
on the real parse; the tokens after an unfinished entry equal those with
|
||||
the entry completed (`after_an_unfinished_entry_the_file_reads_as_with_the_entry_completed`).
|
||||
|
||||
### Known limits (accepted by the lead, 2026-11-17)
|
||||
|
||||
- On a list that never closes, the entry runs on to the `;`, so a
|
||||
diagnostic on the same line after it (`sub u0 (.a(x), .b(y) assign q = ;`)
|
||||
waits out the grace too. The inclusive end also holds back an existing
|
||||
diagnostic on the next line's `.` while the line above is typed.
|
||||
- `.b(y)` ⏎ `.,` costs two diagnostics on one `.` (missing `,` and lone
|
||||
dot).
|
||||
- `.po(` before an `` `ifdef `` reports on the list's `;`, outside the
|
||||
entry.
|
||||
- A release republishes even when the entry held nothing back (one extra,
|
||||
identical publish ~1.5 s after a keystroke in a complete entry).
|
||||
- A nested bracket opened in an abandoned value swallows the rest of the
|
||||
list (above).
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes** `signature::enclosing_list` (unchanged) and
|
||||
`vlog_parser`'s tolerant tree. **Promises** to everything reading the
|
||||
tolerant tree: an unfinished connection is a `ListElem::Error` whose raw
|
||||
text is the entry's own source; the entries after it are ordinary `Ok`
|
||||
elements. `vlog_semantic`/`vlog_linter` already filter error elements
|
||||
(`filter_map(ListElem::ok)`); verified no panic and no cascade
|
||||
(`an_unfinished_entry_costs_one_error_and_no_cascade`).
|
||||
- **New parser diagnostics** (tolerant only): `expected a name after \`.\``,
|
||||
`expected a connection after \`,\``; the unclosed-`(` message is reused.
|
||||
- **`sync::apply_changes` is `#[cfg(test)]` now**; the server calls
|
||||
`apply_changes_at`, which also returns the edit end.
|
||||
- **GRANTED by the lead, 2026-11-17: `workspace/diagnostic/refresh`.**
|
||||
`ClientAbilities.diagnostic_refresh` (server/mod.rs), read in main.rs by
|
||||
`diagnostic_refresh_support` from the **raw** params at
|
||||
`capabilities.workspace.diagnostics.refreshSupport` — `lsp-types` 0.97
|
||||
names its typed field `diagnostic` (singular, no rename), so the typed
|
||||
decode never sees what VS Code sends. `release_port_entries` sends the
|
||||
request once per release (not per buffer) when the client pulls and
|
||||
accepts it; the answer is ignored (`response`'s fall-through).
|
||||
`vscode-languageclient` 9 advertises the capability and re-pulls visible
|
||||
documents on the request, so in VS Code the entry shows after the 1.5 s
|
||||
pause. A pulling client without it still sees the release at its own next
|
||||
pull, under a new generation.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Half 1: (a) lone `.`, (b) open value, list continuation, (d) trailing
|
||||
`,`; (c) already held. Unit tests + valid-unchanged + formatter-refuses.
|
||||
- [x] Half 2: edit end from incremental sync, entry bounds, withhold in push
|
||||
and pull, release on edit elsewhere / grace / save / close / reopen,
|
||||
generation bump on release.
|
||||
- [x] Server unit tests (bounds, state machine with injected time, tokens and
|
||||
findings after the entry) and e2e over stdio (grace, edit elsewhere,
|
||||
save, pull).
|
||||
- [x] Perf: didChange→publish before/after, two runs each.
|
||||
- [x] `workspace/diagnostic/refresh` for pulling clients that accept it —
|
||||
Handshake granted, main.rs read, e2e both ways.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-11-17 — dev agent (Opus 5.5)
|
||||
|
||||
- Surveyed today's tolerant parse of every shape with a scratch probe:
|
||||
`.` ⏎ `.b(y)` and `.po(` ⏎ `.b(y)` cost the rest of the list (the recovered
|
||||
entry with no `,` ended it; `.b(y));` became an error item, two
|
||||
diagnostics, the second on the next entry); `.po(z` ⏎ `.b(y))` read as
|
||||
`.po(z.b(y))` with the diagnostic on the `;`; `.b(y),)` was **silent** in
|
||||
tolerant mode though strict refuses it; the missing `,` already kept both
|
||||
entries.
|
||||
- Half 1 lives in `recover_list.rs` (the list-recovery module) rather than in
|
||||
`instance.rs`: `instance.rs` is at 564 production lines and CLAUDE.md sends
|
||||
new code near 600 to another module. `instance.rs` only changes its two
|
||||
list loops' calls (`connection_or_recover`, `note_trailing_comma`,
|
||||
`connection_list_ends`) and ORs `value_left_open` into the existing
|
||||
unclosed-`(` test. `at_open_bracket` became a wrapper over a free
|
||||
`is_open_bracket` shared with the new lookahead.
|
||||
- Half 2: the state lives in the `Workspace` (`state/port_grace.rs`, field
|
||||
`grace`), not in `Server`: `Server` is built by a struct literal in
|
||||
`startup.rs` and `ClientAbilities` by one in `main.rs`, neither this lane's
|
||||
file; `Workspace` is `Default`-built, so a field costs nothing outside
|
||||
`state/`. Same reason the new module is `state/port_grace.rs` and not a
|
||||
crate-root module (that would need a `mod` line in `main.rs`).
|
||||
- Found and fixed: `enclosing_list`'s naive bracket count reads a list as
|
||||
still open after an abandoned `.po(`, so an edit three items down was
|
||||
"inside" it and its `wire ;` error was withheld. A `;` between the list's
|
||||
`(` and the edit now rules the list out (unit-tested).
|
||||
- Pull mode: no refresh path exists (`docs/features/pull-diagnostics/README.md`
|
||||
says so explicitly), so per the brief nothing was invented; the generation
|
||||
bump makes the next pull full. Handshake request filed above.
|
||||
- Perf, `didChange` → `publishDiagnostics` over stdio, release build, two runs
|
||||
each (ms; "alone" includes the 150 ms debounce timer, "+request" is a
|
||||
keystroke a request follows, mean of ten):
|
||||
|
||||
| probe | before run 1 | before run 2 | after run 1 | after run 2 |
|
||||
|---|---|---|---|---|
|
||||
| ibex_core.sv (2 026 lines), keystroke in a `.clk_i` connection, alone | 170.5 | 158.8 | 165.2 | 157.6 |
|
||||
| same, + request | 4.87 | 4.25 | 5.05 | 4.26 |
|
||||
| generated 1 000 lines, alone | 168.5 | 165.9 | 164.6 | 164.7 |
|
||||
| generated 1 000 lines, + request | 3.85 | 4.14 | 3.97 | 3.71 |
|
||||
| generated 10 000 lines, alone | 200.0 | 202.3 | 204.8 | 198.7 |
|
||||
| generated 10 000 lines, + request | 37.5 | 38.1 | 37.9 | 37.1 |
|
||||
|
||||
Probe: `cargo test --release -p lucisv_server --test e2e a_keystroke --
|
||||
--ignored --nocapture --test-threads=1` (the new
|
||||
`a_keystroke_in_a_port_list_round_trip_over_the_wire` plus the existing
|
||||
`a_keystroke_round_trip_over_the_wire`). Flat within run-to-run noise:
|
||||
the entry lookup is one token walk per flush, no extra parse.
|
||||
- Gates: `cargo fmt`, clippy `--all-targets` (vlog_parser, lucisv_server)
|
||||
clean; suites green (vlog_parser 518, vlog_semantic 418, vlog_linter 673,
|
||||
vlog_formatter 352, vlog_refactor 743, lucisv_server 1 950, every guard
|
||||
exit 0); corpus gate 814/820 pass; release build + `smoke.js` OK.
|
||||
|
||||
- Handshake granted (lead): main.rs reads `refreshSupport` from the raw
|
||||
params (the typed field is misnamed in `lsp-types` 0.97 — found while
|
||||
wiring it); `release_port_entries` asks a capable pulling client to pull
|
||||
again, once per release. Tests: a unit test of the capability read
|
||||
(plural key only, literal `true` only), e2e
|
||||
`a_pulling_client_that_can_refresh_is_asked_to_after_the_grace`, and the
|
||||
no-capability pull test now proves no refresh is sent. VS Code README line
|
||||
restored to "after a short pause, or once you edit elsewhere or save".
|
||||
|
||||
### 2026-11-17 — fix round (dev agent, Opus 5.5)
|
||||
|
||||
- MUST-FIX 1: rule (a)'s `.` follower now counts only on a later line;
|
||||
`..z (p)` is one error element again, so `lucisv_mcp`'s `qa_f1`
|
||||
(unmodified) passes. Test `two_dots_on_one_line_stay_one_error_element`.
|
||||
- SHOULD-FIX 2: `entry_around` requires a named list
|
||||
(`holds_a_named_entry`) and rejects declaration headers
|
||||
(`in_a_declaration_header`). Tests for QA's cases (header `#(parameter W =
|
||||
|)`, interface and class headers, positional list, function declaration,
|
||||
call after a labelled begin, a fresh empty instance list) and the positive
|
||||
ones (`.po`, `.`, a fresh entry after `,`, `#(.W(|` on an instance).
|
||||
- README: the tolerant-tree claim rewritten with QA's measured consequence;
|
||||
the nested-bracket skip described as it is; known limits listed.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-11-17 — QA agent (Opus 5.5)
|
||||
|
||||
Verdict: **fail on one gate (MUST-FIX 1), otherwise pass with findings.**
|
||||
Experiments ran in throwaway copies under the session scratchpad (`base/` =
|
||||
`git archive c1076f9`, `copy/` = this working tree, each with its own target
|
||||
dir); nothing in the working tree was rewritten. Only added file:
|
||||
`crates/vlog_parser/tests/qa_port_entry_grace.rs`.
|
||||
|
||||
**A. Gates (re-run by QA, every suite through `tools/guard.sh -m 6 -t 1200`).**
|
||||
`cargo fmt --all --check` 0; clippy `--all-targets -p vlog_parser -p
|
||||
lucisv_server` 0, no warnings. Suites (passed/failed/ignored, guard exit):
|
||||
vlog_parser 518/0/2 (0), vlog_semantic 418/0/4 (0), vlog_linter 673/0/0 (0),
|
||||
vlog_formatter 352/0/0 (0), vlog_refactor 743/0/6 (0), lucisv_server
|
||||
1 952/0/41 (0), lucisv 143/0/0 (0), **lucisv_mcp 124/1/3 (101)**.
|
||||
`tools/gates.sh --only corpus`: PASS, 814/6. Release build 0;
|
||||
`smoke.js target/release/lucisv-server`: OK (67 messages). With the QA file:
|
||||
vlog_parser +2 tests, green.
|
||||
|
||||
**B. Scope / size.** verify.rs, formatter source, AST, semantic, linter
|
||||
untouched. Edited beyond TODO §68.2's file list: `parser/recover_list.rs`
|
||||
(reasoned in the work log), `server/notification.rs`, `sync.rs`,
|
||||
`tests/e2e.rs` (plus the granted main.rs / server/mod.rs). Production lines
|
||||
(non-blank, non-comment, before `mod tests`): recover_list.rs 169 → 287,
|
||||
instance.rs 564 → 569, port_grace.rs 162 (new), notification.rs 206 → 230,
|
||||
server/diagnostics.rs 158 → 183. No `unwrap`/`expect`/`panic!`/`unsafe` in
|
||||
new non-test code; slice indexing in `entry_start`/`entry_end` is bounded.
|
||||
|
||||
**C. Parser.** (1) 1 023 inputs — all 911 `.sv/.v/.svh/.vh` files in the repo
|
||||
(corpus + fixtures) + 60 QA legal shapes + 52 QA broken shapes — dumped as
|
||||
strict result + tolerant diagnostics + tolerant tree (`{:#?}`) by both
|
||||
binaries: **every strict result identical; every file the strict parser
|
||||
accepts reads identically**. The 43 differences are all strict-refused
|
||||
inputs (41 QA broken shapes, QA `v57`, and corpus
|
||||
`picorv32/scripts/smtbmc/mulcmp.v`, whose two named lists end in `,` — see
|
||||
C4). `lucisv --stdout` over all 1 023: byte-identical outputs and exit codes;
|
||||
`lucisv check`: identical except QA `b09` (a generate label lint now reached
|
||||
past the recovered entry — intended). (2) Legal multi-line connections
|
||||
(next-line operand, `signed'(…)`, `this.`, `super.`, `null`, `new`, `$bits`,
|
||||
`` `MACRO(x) ``, comment line, `intf.sig`, `.a(intf` ⏎ `.sig)`, `#(.W(` ⏎
|
||||
`8))`, `.*`, `(* *)`, generate-for, instance arrays, gates, `bind`, program /
|
||||
interface / checker instances, UDP, `` `ifdef `` arms, `{n{…}}`, `inside`,
|
||||
`tagged`, `pkg::`, `std::randomize`, two instances per item, …): zero
|
||||
diagnostics, tree == strict tree; pinned in `qa_port_entry_grace.rs`. A
|
||||
mutation dropping condition (3) (`starts_new && !self.value_closes(open)` →
|
||||
`starts_new`) is caught by `tolerant_parse_equals_strict_parse_on_valid_sources`
|
||||
and `valid_lists_read_the_same_in_both_modes`. (3) 50 unfinished shapes
|
||||
(first / last / only / repeated / at EOF / in `#(` / in generate / in
|
||||
`` `ifdef `` / nested open bracket / `.po(a,` / `.` ⏎ `);` / trailing `,` +
|
||||
EOF / keyword after `(` / ten lone dots): never silent, strict refuses all, no
|
||||
panic, no hang, at most one diagnostic per line; pinned in the same file
|
||||
(fails on c1076f9: the silent trailing comma). (4) Consumers of the new
|
||||
trailing-`,` diagnostic: see SHOULD-FIX 3. (5) `format_selection`, every
|
||||
single line of 113 files (the QA shapes + mulcmp.v), 673 selections, base vs
|
||||
new: 0 OK→refused, 0 OK with a different output, 55 refused→OK (all on
|
||||
files whose new tolerant parse now has a diagnostic: b17 b22 b33 b39 b41 b46
|
||||
mulcmp.v), every OK output keeps every non-whitespace character of the input;
|
||||
whole-file `format_source` refusal set identical.
|
||||
|
||||
**D. Server** (python stdio client against the release binary; scripts in
|
||||
the scratchpad `qaB/d2.py`). (1) A pre-existing lone `.` in another entry of
|
||||
the same list, an `assign q = ;` elsewhere and lints elsewhere publish while
|
||||
`.po(` is held. (2) Release: push +1 501–1 516 ms after the keystroke;
|
||||
pull + `refreshSupport`: one `workspace/diagnostic/refresh` at +1 501 ms,
|
||||
next pull full under a new resultId, no repeat refresh in 2 s; pull without
|
||||
it: no server message, next pull full (resultId 3 → 4); `workspace/diagnostic`
|
||||
likewise; edit elsewhere +162 ms (the debounce); edit in another buffer +1 ms;
|
||||
save +1 ms (also when sent before the debounce flush); close clears, reopen
|
||||
says everything. (3) No permanent hide found: hover + completion every 200 ms
|
||||
for 5 s → released at +1 507 ms; two changes in one notification (last one
|
||||
decides, both orders); full-document sync withholds nothing; undo; deleting
|
||||
the whole instance; lines inserted above (edit elsewhere → release).
|
||||
(5) `.b` → `.bx(y)` in a project: `unknown-port` withheld, shown at +1 507 ms;
|
||||
`.a(undef…)` likewise. (6) ibex_core.sv keystroke in `.clk_i`, two runs per
|
||||
arm: base 167.6 / 167.6 ms alone, 5.64 / 5.50 ms + request; new 168.5 /
|
||||
168.3, 5.64 / 5.64 — flat. CPU over 5 idle s after a release: 0.000 s.
|
||||
(7) Semantic tokens after the entry (`.po`, `.po(`, `.`, `.po(x`, `.po,` vs
|
||||
`.po(),`): identical (also on c1076f9 — tokens are lexical there).
|
||||
|
||||
**MUST-FIX**
|
||||
|
||||
1. **`lucisv_mcp` suite red**:
|
||||
`crates/lucisv_mcp/tests/qa_f1.rs:447`
|
||||
`qa_r_only_an_affected_instances_unreadable_connection_refuses` fails
|
||||
(passes on c1076f9). `..z (p)` is now a lone-`.` error element `.` plus an
|
||||
`Ok` connection `.z (p)` (rule (a) takes any `.` followed by `.`, same line
|
||||
included), so `add_port` still refuses and writes nothing, but says "holds
|
||||
`.`" instead of "holds `..z (p)`". Repro: `cargo test -p lucisv_mcp --test
|
||||
qa_f1`. The lane's gate list omitted lucisv_mcp. Either restrict (a)'s
|
||||
`.` follower to a later line, or (lead's ruling, file outside the lane)
|
||||
update the expectation.
|
||||
|
||||
**SHOULD-FIX**
|
||||
|
||||
2. **Module/class header `#(` lists are treated as instance lists.**
|
||||
`signature::list_at` reads `name #(` as an override list, so typing in
|
||||
`module hm #(parameter W = |) (input logic a);` withholds the header's
|
||||
diagnostics for 1.5 s (over the wire: `expected expression` at 0:26 shown
|
||||
only at +1 503 ms). The brief says a header must withhold nothing.
|
||||
`port_grace.rs:192` (`entry_around` takes `enclosing_list` as is).
|
||||
3. **README Assumption "the formatter … never reads the tolerant tree" is
|
||||
false.** `vlog_formatter/src/selection/mod.rs:87` (`Tree::parse`) falls
|
||||
back to the tolerant tree, and `fence.rs:110` reads it. Consequence of (d):
|
||||
a file whose only fault is a trailing `,` (corpus `mulcmp.v`) used to be
|
||||
refused whole by Format Selection (tolerant parse had no diagnostic → "not
|
||||
a tree to trust"); now selections clear of the instance format (verified
|
||||
output, text preserved — C5) and the instance itself is refused. Also
|
||||
new: the editor flags `mulcmp.v` (yosys accepts the trailing comma). Other
|
||||
consumers: `vlog_refactor` `check/mod.rs:324` and MCP `place/verify.rs:62`
|
||||
compare tolerant diagnostic *counts* before/after — an engine edit that
|
||||
leaves `.a(x),)` is now caught (tighter, no test changed); `lucisv check`
|
||||
does not print parse diagnostics (unchanged output). Correct behaviour as
|
||||
far as QA can tell; the README should say so.
|
||||
4. **Nested open bracket in the abandoned value swallows the rest of the
|
||||
list.** `.c(f(` / `.c(z[` / `.c({` / `.c((` ⏎ `.b(y));`: the error element
|
||||
is `.c(f(\n .b(y))` — the next entry and the list's `)` go with it (rule
|
||||
(b) fires, but the element recovery's skip is bracket-balanced, not "to
|
||||
the end of its line" as the README says). Over the wire a lint outside the
|
||||
entry (`` `y` is read but never driven `` at 1:11) appears at once while
|
||||
typing `.c(f(`, and not while typing `.c(`. Same as c1076f9, so not a
|
||||
regression, but the README's promise doesn't hold for it.
|
||||
|
||||
**NOTE**
|
||||
|
||||
5. Other lists `enclosing_list` accepts, withheld for 1.5 s: positional
|
||||
instance lists (`sub u0 (x, y|, z)` → `, y`); function declarations with a
|
||||
user-type return (`function automatic my_t f(input a|` → `input a`); a
|
||||
call right after a block label (`begin : blk` ⏎ `my_task(a, b|)` → `, b`).
|
||||
Not covered (nothing withheld): instance arrays `sub u0 [1:0] (…)`, gates.
|
||||
6. On an unclosed list, `entry_end` runs to the `;`: `sub u0 (.a(x), .b(y) |
|
||||
assign q = ;` withholds both `assign` diagnostics (1.5 s). The inclusive
|
||||
end also withholds a pre-existing diagnostic on the next line's `.` when
|
||||
typing on the line above it.
|
||||
7. "Exactly one diagnostic" has exceptions: `.b(y)` ⏎ `.,` costs two on one
|
||||
`.` (missing `,` + lone dot). `.po(` ⏎ `.b(y)), .c(z));` now loses the
|
||||
whole instance to an error item (c1076f9 kept it) — contrived, not a typing
|
||||
shape. `.po(` ⏎ `` `ifdef `` … → diagnostic on the list's `;`, outside the
|
||||
entry.
|
||||
8. Pre-existing, not this lane: a positional list's trailing omitted
|
||||
connection (`u0 (x, y,)`) is an empty `Ok` entry strictly and absent
|
||||
tolerantly — strict ≠ tolerant on valid input (same at c1076f9).
|
||||
9. A release republishes even when the entry held nothing back (one extra
|
||||
identical publish ~1.5 s after a keystroke in a complete entry). Harmless.
|
||||
10. Only a running VS Code confirms: the squiggle actually disappears and
|
||||
reappears with `vscode-languageclient` 9.0.1 pull + refresh (the
|
||||
capability is advertised: `diagnostic.js:784`), and how it feels.
|
||||
|
||||
### 2026-11-17 — QA re-check of the fix round (Opus 5.5)
|
||||
|
||||
Verdict: **pass.** MUST-FIX 1 and SHOULD-FIX 2 are fixed; nothing new found
|
||||
that blocks. Fresh scratch snapshot of the working tree; the old-vs-new
|
||||
comparison is against the same c1076f9 baseline.
|
||||
|
||||
- **Gates** (QA's own runs, each suite guarded, exit 0): `cargo fmt --check`
|
||||
clean; clippy `--all-targets -p vlog_parser -p lucisv_server` clean, 0
|
||||
warnings; vlog_parser 521/0/2 (includes `qa_port_entry_grace.rs`, 2/2),
|
||||
lucisv_server 1 954/0/41, **lucisv_mcp 383/0/4** (full suite;
|
||||
`git status crates/lucisv_mcp` empty), vlog_formatter 352/0/0;
|
||||
`gates.sh --only corpus` PASS 814/6.
|
||||
- **MUST-FIX 1.** `sub u0 (.a(x), ..z (p));` and `sub u0 (.a(x), . .b(y));`:
|
||||
one error element (`..z (p)`, `. .b(y)`) and one `expected identifier`
|
||||
diagnostic, the same tree and diagnostics as c1076f9. `.` ⏎ `.b(y)` still
|
||||
recovers: error `.`, one `expected a name after \`.\``, the list reads on.
|
||||
- **SHOULD-FIX 2, over the wire** (release binary, error typed, first
|
||||
publish vs ~1.5 s later). Withholding nothing; the error arrives with
|
||||
the debounce: the module `#(parameter W = |)` and interface headers, the
|
||||
class `#(type T = …)` header, a positional instance list, a function
|
||||
declaration with a user return type, and `my_task(a, |b)` after
|
||||
`begin : blk`. Still withheld, released at +1 502–1 512 ms: `.po(`, `.`,
|
||||
`.p(` after a `,`, `#(.W(|` on an instance, and `.` in a fresh empty
|
||||
`sub u0 (|)`. Attacks on `in_a_declaration_header`. Every instance below
|
||||
is still withheld, so none is wrongly taken for a header: after
|
||||
`function void f(); endfunction`, after `task t; endtask`, after
|
||||
`endclass` and after `endpackage`; after `always_comb begin end` and after
|
||||
`function int f(int a); return a; endfunction`; inside
|
||||
`generate if (X) begin`; after `else` and after `` `ifdef ``; after
|
||||
`(* keep *)`; in a `bind`; in interface and program bodies; as the first
|
||||
item after `module m (input a);`; on the header's own line
|
||||
(`module m; sub u0 (…`); and for checker and interface instances. Lists
|
||||
that might be wrongly included: none are withheld for
|
||||
`extern function my_t f(`, `import "DPI-C" function my_t f(`,
|
||||
`virtual intf vif(`, `new(.x(…))`, a modport or a clocking block. Two are
|
||||
withheld, both instance-shaped and both accepted per the brief:
|
||||
`t(.a(|=1))` after `begin : blk`, and `my_t v (.a(…))`, which is an
|
||||
instance.
|
||||
- **Valid-code identity** (1 026 inputs: the 1 023 from before plus the
|
||||
three two-dot shapes). Every strict result is identical. The tolerant
|
||||
trees differ only on strict-refused inputs: 41 QA broken shapes, `v57`
|
||||
and `mulcmp.v`. `lucisv --stdout` outputs and exit codes are
|
||||
byte-identical. `lucisv check` output is identical except QA `b09`, as
|
||||
before.
|
||||
- **README.** The tolerant-tree readers, the nested-bracket limit, the
|
||||
named-list and header rules and the known limits all match the code.
|
||||
|
||||
NOTE (new, minor):
|
||||
|
||||
11. In README rule (a), the sentence "It becomes an error element holding
|
||||
just the `.`…" now follows the same-line exception, so it reads as if
|
||||
it described the exception. The `.input(x)` parenthetical is repeated,
|
||||
and one line of rule (b) is not wrapped. Wording only.
|
||||
12. `holds_a_named_entry` counts a `.` that opens a line at any depth. A
|
||||
positional list that continues a hierarchical name on the next line
|
||||
(`sub u0 (top` ⏎ `.sig, b)`) therefore counts as named and is withheld
|
||||
for 1.5 s. Rare and harmless.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-11-17 — lead (after dev, QA fail on one gate, one fix round, QA re-check pass)
|
||||
|
||||
Accepted. The first QA verdict was a fail on one gate: `lucisv_mcp`'s
|
||||
`qa_f1` — rule (a) read `..z (p)` on one line as a lone dot. The lead's
|
||||
dev brief had left `lucisv_mcp` and `lucisv` out of the gate list; that
|
||||
omission is the lead's, and both crates are in every later list. One Opus
|
||||
fix round; the re-check passed (parser 521, server 1 954, mcp 383,
|
||||
formatter 352, corpus 814/6).
|
||||
|
||||
Rulings recorded:
|
||||
|
||||
- **A following `.` makes a lone dot only on a later line.** Two dots on
|
||||
one line keep the generic recovery, so the MCP refusal message is the one
|
||||
it was.
|
||||
- **Only a named-connection list of an instance withholds.** The list holds
|
||||
an entry at its own level that starts with `.`, and no declaration keyword
|
||||
stands between it and the `;` before it. Headers, positional lists, call
|
||||
arguments withhold nothing. A named-argument call and `my_t v (.a(…))`
|
||||
still do; accepted (same syntax as an instance).
|
||||
- **A trailing `,` in a named list is now a tolerant-mode diagnostic**, as it
|
||||
always was in strict mode. Consequences measured by QA and accepted:
|
||||
Format Selection away from that instance now formats (55 refused →
|
||||
formatted, none the other way, no output changed); the refactor check and
|
||||
the MCP placement check catch an edit that leaves one; one yosys-style
|
||||
corpus file is flagged in the editor.
|
||||
- **`workspace/diagnostic/refresh`** on release for a pulling client that
|
||||
advertises it (handshake granted to the dev: `main.rs`).
|
||||
- Valid code: 1 026 inputs old vs new, every strict result and every
|
||||
strictly-accepted tree identical, CLI output byte-identical.
|
||||
|
||||
Open, minor: QA notes 11 (rule (a) wording in this README) and 12 (a
|
||||
positional list continuing a hierarchical name on the next line counts as
|
||||
named). **Not verified by anyone:** the squiggle's timing in a running VS
|
||||
Code with the pull + refresh client, and whether 1.5 s feels right.
|
||||
@@ -364,6 +364,11 @@ is a leaf, as it was for fences.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- Editors' "Format Selection" no longer uses this engine: since TODO §66.2
|
||||
the LSP range requests call `format_selection`, which lays out the smallest
|
||||
sibling run in place — see `docs/features/selection-formatting/README.md`.
|
||||
The CLI's `--lines` still runs here, unchanged.
|
||||
|
||||
- [x] `range.rs`: `LineRanges` (`parse`/`new`, sorted+merged, reversed and
|
||||
zero refused, past-EOF clamped) with unit tests for every spelling.
|
||||
- [x] `range.rs`: `Pick`/`Selection`/`Plan`/`Split`, the `Planner` walk in
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
# selection-formatting
|
||||
|
||||
## Goal
|
||||
|
||||
VS Code's "Format Selection" (`textDocument/rangeFormatting`) failed more than
|
||||
half the time on the selections people actually make — one whole `always`
|
||||
block, one whole `case`, usually nested in blocks the selection does not
|
||||
cover. The request went to `format_range` (the CLI's `--lines`), whose unit is
|
||||
a whole module-level item laid out at formatter depth: selecting a `case`
|
||||
re-laid the whole `always`, a block in a four-space or tab-indented file came
|
||||
back re-indented to two spaces, a selection inside `generate` or a function
|
||||
re-laid the whole region, and any parse error anywhere refused the request.
|
||||
`format_selection` lays out **only the smallest run of sibling items or
|
||||
statements the selection covers**, at the indentation its first line was
|
||||
written at, and splices it into otherwise untouched bytes. The owner's rule:
|
||||
don't worry about the parent; the selected block keeps the indentation level
|
||||
it starts at; the result must be functionally the same.
|
||||
|
||||
## Semantics
|
||||
|
||||
### Scopes and units
|
||||
|
||||
A *scope* is a sibling list exactly as `fence.rs` defines one: item lists
|
||||
(file, module, package, generate region, generate `begin`…`end`, class) and
|
||||
statement lists (`begin`…`end`, `fork`…`join*`, function and task bodies). A
|
||||
single-statement body (`if (a) x = 1;`, `always @* x = 1;`) or a block-less
|
||||
generate item is not a scope; it is walked *through* to the scopes it reaches.
|
||||
A *unit* is one item or statement with its whole extent: first leading comment
|
||||
or attribute through the comments written after it on the same line.
|
||||
|
||||
### Locating the target (`selection/locate.rs`)
|
||||
|
||||
For one selected line span, starting at the file scope:
|
||||
|
||||
1. Take the units whose lines meet the span. Blank lines select nothing; a
|
||||
span meeting no unit changes nothing.
|
||||
2. If exactly one unit is met, the span touches neither its first line nor its
|
||||
last, and exactly **one** of its nested scopes has a unit the span meets,
|
||||
descend into that scope and repeat.
|
||||
*(Lead ruling 2026-11-09, QA note 2: only the unit's **first** line is
|
||||
asked about. A selection over a block's last statements and its closing
|
||||
`end` descends and lays out those statements; the closing line alone
|
||||
meets no nested unit and still names the unit it closes.)*
|
||||
3. Otherwise the target is the run of consecutive units met — a partial
|
||||
selection expands to whole units.
|
||||
4. **Fences outrank the selection.** Units a fenced region *of this scope*
|
||||
reaches (a region nested inside a unit's own code does not count) are
|
||||
trimmed from both ends of the run; an empty run changes nothing. A region is
|
||||
never half inside the splice.
|
||||
5. **Line-clean or one level up.** The run must be replaceable by whole lines:
|
||||
only spaces/tabs before its first byte on that line, only whitespace after
|
||||
its last byte on that line, no sibling unit's extent and no dangling comment
|
||||
of the scope inside it. If not (`begin // note` makes the first statement's
|
||||
leading comment start on the `begin` line; `x = 1; y = 2;` with only `x`
|
||||
selected is fine because both are met), the enclosing unit is the target,
|
||||
checked the same way. At the file scope there is nowhere to go up to, and
|
||||
the request is deferred.
|
||||
6. **Big containers defer.** A run holding a `module`/`interface`/`program`
|
||||
or `package` item goes to `format_range(source, config, lines)` unchanged —
|
||||
header/footer splitting and whole-file selections behave exactly as before.
|
||||
|
||||
The located target is recorded as a **path** — `(unit index, child scope
|
||||
index)` per descent, plus the run's start and length — not as bytes or lines.
|
||||
|
||||
### Layout and splice (`selection/mod.rs`, `format::print_run`)
|
||||
|
||||
- `print_run` builds the ordinary `Fmt` over the whole source (fenced regions
|
||||
from `fence::collect`, no range splits) and calls `item_seq(run, depth)` or
|
||||
`stmt_seq(run)` on the sub-slice. `depth` is the AST depth `item_kind`
|
||||
would pass down (it only feeds the alignment width budget).
|
||||
- The **base indentation** is the leading whitespace of the run's first unit's
|
||||
line, as written (tabs included) — or, when that unit is a compiler directive
|
||||
and a later unit is not, the later unit's: directives are commonly written at
|
||||
column 0 while the code they guard is indented, and the code says where the
|
||||
block stands. The directive is then indented with the block, as a whole-file
|
||||
run indents it.
|
||||
- `Printer::print_at(doc, base)` starts the text with `base`, writes it after
|
||||
every line break before the indentation, and charges its width against the
|
||||
line budget (a tab counts as one indent width). `Doc::Verbatim` and
|
||||
`Doc::Inline` keep their own absolute indentation, and a line holding nothing
|
||||
but indentation is emptied so blank lines never keep the base's tabs.
|
||||
`print` is `print_at(doc, "")`, byte for byte the old printer.
|
||||
- The splice replaces `line start of the first unit .. end of the last unit's
|
||||
extent` with the printed text and nothing else: blank lines at the boundary,
|
||||
the rest of the last line and the file tail (final newline or not) are
|
||||
untouched. In a file whose lines end in `\r\n` (judged at the target), every
|
||||
line break the printer wrote becomes `\r\n`; source text copied through
|
||||
keeps the `\r\n` it had.
|
||||
|
||||
### Several ranges
|
||||
|
||||
Each merged span of `LineRanges` selects its own target. Targets whose byte
|
||||
ranges overlap are replaced by the target of the hull of their spans, until
|
||||
none overlap. They are spliced bottom-up and verified together, so the
|
||||
all-or-nothing contract covers the whole request. If any span defers, the
|
||||
whole request goes to `format_range`.
|
||||
|
||||
### Safety net (unchanged)
|
||||
|
||||
`verify_equivalence(source, output)` over the whole file, then convergence by
|
||||
**replaying the targets**: the output is parsed the same way, each path is
|
||||
resolved in its tree, laid out and spliced again, and `verify_convergence`
|
||||
must find nothing to change. `verify.rs` is not touched. Any failure — a target
|
||||
that cannot be found again or cut cleanly in the output included — is an error
|
||||
and no edit (`FormatError::Selection` for the selection's own refusals).
|
||||
|
||||
### A file that does not parse
|
||||
|
||||
`parse_source` first. If it fails, `parse_source_tolerant` builds the tree and
|
||||
the target is located in it the same way. The request is refused when any
|
||||
parse diagnostic lies inside `line start .. end` of a target, or any unit of
|
||||
the target (at any depth reachable through the scope walk) is an `Error` node.
|
||||
The replay parses the output the same way and applies the same check.
|
||||
|
||||
**Verdict:** sound and useful. Sound because the layout is token-verified over
|
||||
the whole file like every other path: recovery can only mis-guess the *nesting*
|
||||
around a target (an `assign` after a missing `end` becomes a statement), which
|
||||
changes at most how a clean run is laid out, never its tokens — and the target
|
||||
itself is required to be free of diagnostics and error nodes. Useful because
|
||||
in the corpus sweep below, with a broken line injected in every file, 75 % of
|
||||
selections still answered.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- A tab in the base indentation is worth one indent width for the line budget.
|
||||
The printer cannot know the reader's tab stop; only group breaking depends
|
||||
on it, and the replay uses the same rule, so it cannot break convergence.
|
||||
- Comment `col` is a byte column with a tab counting 1, so `raw_lines`'
|
||||
dedent-by-column cancels a base containing tabs exactly as it cancels
|
||||
spaces (exercised by the tab tests).
|
||||
- A parse diagnostic's span is the token the parser gave up on, not the extent
|
||||
of what it swallowed; the `Error`-node walk covers the latter at list level.
|
||||
An error node nested in an expression or header list is assumed to come with
|
||||
a diagnostic inside it. The safety net backs both.
|
||||
- The alignment of a sub-slice is planned over the sub-slice only (a run
|
||||
holding half of an alignment group aligns that half). Stable under replay.
|
||||
- With `uvm-utils-indent` on, a run holding a `` `uvm_*_utils_begin `` without
|
||||
its `_end` indents what follows it inside the run, as a whole-file run would.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes** `fence::collect`, `fence::region_at`-shaped regions,
|
||||
`fence::with_trailing_comments` (already `pub(crate)`), `Fmt::item_seq` /
|
||||
`Fmt::stmt_seq` (already `pub(super)` within `format`), `format_range`,
|
||||
`verify_equivalence`, `verify_convergence`, `vlog_parser::parse_source`,
|
||||
`parse_source_tolerant`.
|
||||
- **Provides** `vlog_formatter::format_selection(source, config, lines)` and
|
||||
`Printer::print_at(doc, base)`; `format::print_run` / `format::Run`
|
||||
(`pub(crate)`); a new `FormatError::Selection(String)` variant (every match
|
||||
on `FormatError` in the workspace already has a catch-all arm).
|
||||
- **Changed for the server:** `lucisv_server::format::{range_formatting,
|
||||
ranges_formatting}` now call `format_selection`. `on_type.rs`'s
|
||||
semicolon trigger calls `format::range_formatting`, so it changes too.
|
||||
- **Request (not done — outside this lane's files): `crates/lucisv_server/src/on_type.rs`.**
|
||||
Two of its unit tests pin behaviour this design changes on purpose, and fail:
|
||||
1. `a_semicolon_in_a_buffer_the_engine_refuses_answers_nothing_at_all`
|
||||
(line ~1175) — its buffer's error (`wire ;`, line 3) is *outside* the
|
||||
keystroke's statement (line 2), so the request now formats line 2 (design
|
||||
step 7). Proposed fix: put the error on the keystroke's own line, e.g.
|
||||
`"module m;\n wire a = ;\nendmodule\n"` with the `;` at line 1,
|
||||
char 13 — the change made to the twin test in
|
||||
`server/tests/formatting.rs`.
|
||||
2. `a_semicolon_at_eof_with_no_trailing_newline_still_lays_out_its_line`
|
||||
(line ~1210) — the splice no longer adds a final newline (design step 5);
|
||||
the expected text becomes `"module m;\n wire a;\nendmodule"` and the
|
||||
comment above it should say the file tail is untouched.
|
||||
The module doc at line ~64 ("`format_range` selects by …") is also stale.
|
||||
- The CLI `--lines` keeps calling `format_range`; `range.rs` is unchanged.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `printer.rs`: `print_at(doc, base)`; `print` delegates with `""`.
|
||||
Whole-file output byte-identical (snapshot + idempotency suite green
|
||||
before any selection test existed).
|
||||
- [x] `format/mod.rs`: `Run`, `print_run`, `FormatError::Selection`.
|
||||
- [x] `selection/scope.rs`: scopes, units, extents, the nested-scope walk.
|
||||
- [x] `selection/locate.rs`: locate (descend, fences, line-clean, defer),
|
||||
path resolution, error-node walk, base indentation.
|
||||
- [x] `selection/mod.rs`: `format_selection`, multi-target hull merging,
|
||||
bottom-up splice, CRLF, tolerant path, replay.
|
||||
- [x] `tests/selection.rs` — 33 tests (incl. the directive-base test).
|
||||
- [x] Server: `ranges_formatting` → `format_selection`; 3 handler tests in
|
||||
`format.rs`, 1 dispatch test + 1 updated in `server/tests/formatting.rs`,
|
||||
1 e2e leg.
|
||||
- [x] `on_type.rs` test updates — Handshake request above (applied by the lead, 2026-11-09).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-11-09 — dev
|
||||
|
||||
- Built as designed, as a directory module (`selection/{mod,scope,locate}.rs`,
|
||||
each well under 300 production lines) rather than one file.
|
||||
- **Deviation 1 — multi-range lives in the engine.** The design put the
|
||||
per-span targets and hull re-selection in the LSP handler; `format_selection`
|
||||
takes a `LineRanges` anyway, so it does that itself and verifies all targets
|
||||
in one pass. The server only swaps `format_range` for `format_selection`.
|
||||
- **Deviation 2 — descent needs exactly one reached child scope.** A span
|
||||
covering both branches of an `if` reaches two scopes; it takes the `if`
|
||||
rather than one branch.
|
||||
- **Deviation 3 — directive base.** The base indentation is taken from the
|
||||
first non-directive unit of the run; found by a scratch run where a run
|
||||
starting at a column-0 `` `ifdef `` pulled the guarded code to column 0.
|
||||
- **Fence check** counts only regions opened in the run's own scope; a region
|
||||
nested in a unit's code is laid out verbatim by the printer as in a
|
||||
whole-file run, so it does not trim the unit.
|
||||
- **`FormatError::Selection(String)`** added for refusals that are neither a
|
||||
parse error nor a verification failure (a parse error inside the target, a
|
||||
target that cannot be found again).
|
||||
- **Server tests updated:** `a_keystroke_the_engine_refuses_is_answered_with_
|
||||
silence_and_not_a_popup` (`server/tests/formatting.rs`) — its buffer's error
|
||||
was on another line, which no longer refuses; the error now sits on the
|
||||
keystroke's own line. No `format.rs` test pinned over-reach: the existing
|
||||
range tests select whole module items and come out identical.
|
||||
- **Corpus sweep** (scratch test, release, under `tools/guard.sh`, not
|
||||
committed): 428 formattable files of `corpus/{common_cells,ibex,picorv32,
|
||||
opentitan/hw/ip}` (every ~2nd file), windows of 1, 2, 4 and 8 lines at a
|
||||
stride of 5+w: **33 438 calls, 21 473 changed, 11 965 unchanged, 0
|
||||
verification errors, 0 selection refusals, 0 source errors.** Same files
|
||||
with ` @@ broken = ;` injected at the middle line: 33 626 calls, 14 159
|
||||
changed, 10 954 unchanged, 4 281 refused because the target holds the
|
||||
error (or recovery swallowed the rest of the file into an error node), 4 232
|
||||
source errors (the span reached a module-level unit and was deferred to
|
||||
`format_range`, which parses strictly), 0 verification errors.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-11-09 — QA
|
||||
|
||||
**Gates (main checkout, all guarded, no guard kills):** `cargo fmt --all --check` clean;
|
||||
`cargo clippy --workspace --all-targets` 0 warnings; `cargo test`: `-p vlog_formatter`
|
||||
347 passed / 0 failed, `-p lucisv_server` 1881 passed / 0 failed / 40 ignored, `-p lucisv`
|
||||
143 passed / 0 failed. `verify.rs`, `range.rs`, `fence.rs`, `crates/lucisv` untouched
|
||||
(`git diff --stat`). No source or test files edited by QA; all experiments in a throwaway copy
|
||||
(deleted).
|
||||
|
||||
**Hand-written attack set:** 221 (source, selection) cases in 2/3/4-space and tab files
|
||||
(nested `generate for` / `always_ff` / `case`, mis-indented parents, `if`/`else` chains, `for`,
|
||||
`fork`/`join`, function and task bodies, case-item blocks, class methods, gen-if/gen-case),
|
||||
comments everywhere, `` `define `` with `\` continuations, `` `ifdef `` at run boundaries,
|
||||
escaped identifiers, attributes, labels, fences (enclosing / unmatched / straddling), CRLF, no
|
||||
final newline, multibyte, mixed whitespace, tabs, empty file, past-EOF, one-line/cursor-only,
|
||||
statements sharing a line, multi-range hulls, files with parse errors. Every window of each
|
||||
case was then run (24 719 calls): **0 panics, 0 token-nonequivalent outputs (independent
|
||||
`verify_equivalence`), 0 non-idempotent results, 0 verification errors except the CRLF finding
|
||||
below.** A "far" detector (changed lines not touching the selection) fired 573 times; every
|
||||
one inspected was the target growing to its whole unit (selection touching a unit's first/last
|
||||
line, a leading `///` comment line, or the module header deferral) as the spec says.
|
||||
|
||||
**Corpus sweep** (release, 409 files of `corpus/`, 12 random windows of 1-12 lines each,
|
||||
fixed seed): clean 4 908 calls: 3 611 changed / 1 265 unchanged / 32 refused / 0 verification
|
||||
errors / 0 panics / 0 non-equivalent. One random line replaced by ` @@ broken ( ;` (4 908
|
||||
calls): 1 005 changed / 617 unchanged / 3 286 refused (error inside target or swallowed by
|
||||
recovery) / 0 verification errors / 0 panics / 0 non-equivalent. CRLF-converted (818 calls): 594
|
||||
changed / 212 unchanged / 7 refused / **5 verification errors** and 1 mixed-EOL output (finding 1).
|
||||
(A shifted-window re-run flagged 18 "non-idempotent" calls; all were artifacts of the shifted
|
||||
window landing on the module header, i.e. a different target — not a defect.)
|
||||
|
||||
**Sabotage (copy only):** (A) splice tail skips the line after the target: 27 of 33
|
||||
`tests/selection.rs` tests fail; runtime net alone rejected 14 294 of 24 719 calls, 0 corrupted
|
||||
outputs returned. (B) base indentation prefixed onto every `Doc::Verbatim`: 1 test fails
|
||||
(`a_fence_inside_the_target_is_emitted_as_written`); runtime net (replay convergence)
|
||||
rejected 283 calls, 0 corrupted outputs returned; the whole-file suite cannot see it (empty
|
||||
base) — so one test is all that pins it. (C) fence trimming removed: 2 tests fail
|
||||
(`a_fence_around_the_target_wins`, `a_fence_straddling_the_target_trims_the_fenced_units`);
|
||||
net rejected 241 calls.
|
||||
|
||||
**Findings**
|
||||
|
||||
- SHOULD-FIX 1 — CRLF file + target whose last line ends in a `//` comment loses its `\r`.
|
||||
`print_run`'s `out.trim_end()` (`format/mod.rs`, `print_run`) strips the `\r` that the trailing
|
||||
comment's text carries while `Unit::extent` (`scope.rs`) includes it in the replaced
|
||||
bytes, so the line ends in a bare `\n`; the replay then often disagrees and the request is
|
||||
*refused* ("formatting is not idempotent; line N changed from "" to """), otherwise the file
|
||||
comes back with one bare-`\n` line. Repro: `"module m;\r\n initial begin\r\n a = 1; // c\r\n
|
||||
b = 2; // d\r\n end\r\nendmodule\r\n"`, lines `3-4` -> Err; `3-3` of a one-statement
|
||||
variant -> Err; corpus `opentitan/.../uart_tx_rx_vseq.sv` as CRLF, line `215-215` -> Ok with a
|
||||
bare `\n` on line 215. The LF twin of each is fine. Safe (no corruption) but Windows files
|
||||
with trailing comments cannot be range-formatted.
|
||||
- NOTE 2 — selecting interior statements together with the parent's closing `end` (e.g. the
|
||||
last statements of a generate `begin`…`end` plus its `end`) takes the whole parent: corpus
|
||||
`common_cells/src/rr_arb_tree.sv` lines `310-319` re-lays 116..292. By design (step 2/3)
|
||||
but it is the most common sloppy selection; consider whether the owner wants it.
|
||||
- NOTE 3 — inner indentation comes from `Config::indent_width` (2 for the library default),
|
||||
so the engine alone on a 4-space file gives a 4-space block with 2-space nesting inside
|
||||
(`gen-4sp` cases); the server passes the editor `tabSize`, so with `indent_width = 4` the
|
||||
owner's case comes out right (demo below). For tab files the nested levels are `\t…\t` plus
|
||||
spaces (`\t\t\t\t case`), same as the whole-file printer's no-tab model.
|
||||
- NOTE 4 — a selection spanning module-header ports and body items formats only the body
|
||||
items (the header lines are not units); header-only selections defer to `format_range`.
|
||||
- NOTE 5 — a column-0 directive in a run together with indented code is moved to the block's
|
||||
indentation (`` `endif `` + next statement selected -> `` `endif `` indented while `` `ifdef ``
|
||||
stays at column 0). Token-equivalent; cosmetic.
|
||||
- NOTE 6 — with a missing `end` the tolerant tree nests later statements into the open block, so
|
||||
they get laid out one level deeper than the (misplaced) `end` implies. Tokens identical.
|
||||
I could not construct a counterexample where a wrong parse changes meaning: only whitespace
|
||||
is chosen by layout, the token/comment stream is compared exactly, and line-sensitive
|
||||
tokens (`` `define ``, directives, line comments) are tokens whose text includes their line.
|
||||
|
||||
**Usability (owner's complaint)**, 4-space file, `generate for` -> `always_ff` -> `case`,
|
||||
`indent_width = 4`: selecting exactly the `case` lines (6-10), exactly the `always_ff` lines
|
||||
(5-11), one middle line (8) and the three case items (7-9) all yield the same correct result,
|
||||
and every byte outside the `case` is unchanged:
|
||||
|
||||
before after (selection 8-8)
|
||||
always_ff @(posedge clk) begin always_ff @(posedge clk) begin
|
||||
case (sel[i]) case (sel[i])
|
||||
2'b00: q[i]<=a; 2'b00: q[i] <= a;
|
||||
2'b01 : q[i] <= b; 2'b01: q[i] <= b;
|
||||
default:q[i]<=c; default: q[i] <= c;
|
||||
endcase endcase
|
||||
end end
|
||||
|
||||
**Not verified:** the editor (VS Code / Vim) end to end; opentitan sweep and the byte-identity
|
||||
corpus gates (the 347-test formatter suite incl. snapshots is green, which is the evidence for
|
||||
`print_at("")` == old `print`); files over 120 KB; non-ASCII-heavy corpora beyond the
|
||||
hand-written multibyte cases; `--release` gate script `tools/gates.sh`.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-11-09 — lead. Verdict: accepted, with two fixes of mine after QA.**
|
||||
|
||||
1. **The design is a splice, not a second inverted fence**, and that is what
|
||||
answers the owner's complaint: the target keeps the indentation it was
|
||||
written at because nothing above it is laid out at all. The safety
|
||||
argument is the old one, unchanged — whole-file `verify_equivalence`
|
||||
(`verify.rs` untouched, so invariant #4 does not apply) plus a replay of
|
||||
the located target. QA's three sabotages were each caught, with zero
|
||||
corrupted outputs returned in 24,719 hand-case calls and 10,634 corpus
|
||||
calls; no panic.
|
||||
2. **QA SHOULD-FIX 1 (CRLF), fixed by the lead.** `Unit::extent` counted the
|
||||
`\r` after a trailing `//` comment as part of the unit, so the splice ate
|
||||
it. The extent now stops before it (`selection/scope.rs`); `print_run`
|
||||
trims spaces and newlines only, as `render` does. Pinned by
|
||||
`crlf_with_a_trailing_comment_on_the_last_line_keeps_every_line_ending`.
|
||||
3. **QA NOTE 2, ruled: only the first line stops the descent.** A selection
|
||||
over a block's last statements and its `end` re-laid 177 unselected lines
|
||||
of `rr_arb_tree.sv`. It now lays out the statements it covers; the `end`
|
||||
line alone still names the unit it closes. Three tests pin the three
|
||||
cases.
|
||||
4. **`on_type.rs`** (the dev's Handshake request): accepted. The `;` trigger
|
||||
shares the engine, so an error elsewhere in the buffer no longer silences
|
||||
it and the file tail is not normalized; two tests updated, one added.
|
||||
5. **Accepted as they are**: the dev's four deviations; NOTE 3 (nested levels
|
||||
use `indent_width`, which the server takes from the editor's `tabSize`);
|
||||
NOTE 4 and NOTE 5 (cosmetic, token-equivalent).
|
||||
6. **Open**: the LSP reply is still one whole-document edit; the engine now
|
||||
knows the exact bytes it replaced, so a minimal edit is possible. Not
|
||||
verified in a running editor.
|
||||
+5
-2
@@ -151,7 +151,7 @@ what a change on the pointed-to side must not silently break.
|
||||
| `lucisv_server ◀──▶ vlog_semantic` | handshake | Three later additive performance surfaces: **`DeclLines` / `Def::lines`** record declaration and detail lines at index time (`FACTS_FORMAT` 3 → 4); **`WorkspaceIndex::absorb`** folds a scan batch with one merge rather than one merge per file; and **`WorkspaceIndex::files_spelling`** finds external uses by spelling, resolved or not, for rename's dangling-use refusal. The first feeds hover-line-index, the second scan-interleave, and the third refactor-rename's six-rung fan-out. Changing the facts codec, reference-fact census or merge semantics breaks those consumers. |
|
||||
| `lucisv_server ──▶ vlog_refactor` | depends | `prepare_rename`/`rename`, `find_references`, the port refactorings, `organize_imports`, `extract_module`, `inline_module`, `RefactorEdit::{edits,warnings,created}`, `rename_traced_with(files, known: &dyn KnownFacts, …)` (perf5r-scope-reuse, 2026-09-09: the engine may build its index from a caller's record for a file **only** when `known.facts_for(path, text)` answers for exactly these bytes — the server answers from the index cache's store entry, record and FNV-1a content hash read from one place, never from the workspace index's record; a reused file is parsed anyway if a later stage reads its `Semantics`; `rename_traced` is the door with nothing known), `rename_traced` + `RenameTrace`/`VerifyTrace`/`Stage` (perf5-p2: the rename with its stage timings and parse counts as an out parameter; `rename` is the same call with a trace nobody reads; the server logs one `timing: rename trace …` line under `--verbose` only), the parsed-input selectors `port_action_modules_in`/`imported_packages_in`/`extract_site_in`/`inline_site_in` (perf5-p1: the offer paths hand the document's own tolerant parse and diagnostics; the text forms are thin wrappers kept for standalone consumers and the every-offset parity test; a large-file buffer still takes the text form), `instantiation_plan`/`render_with`/`module_definition` (the inline instantiation ghost, signature help, inlay hints — the completion popup stopped consuming them 2026-08-30, names-only tier). Promise consumed: never a partial edit — `Ok` verified whole, `Err` is a sentence. |
|
||||
| `lucisv_server ◀──▶ vlog_refactor` | handshake | Request-scope selectors added for the performance wave: `prepare_rename_here` must produce the same answer/refusal text as whole-scope `prepare_rename`; `rename_name_at` must name the target that the rename engine acts on; `port_action_modules` and `enclosing_module` must name every module the corresponding port action/command can edit. The server uses those names to choose an index-derived file set; `extract_site`, `inline_site` and `imported_packages` also name source requirements. **`rename_preflight(semantics, offset, new_name)` (perf5r-preflight, 2026-09-08)** owes whole-scope `rename` the same *refusal* text one-directionally — it may always stand aside with `Ok(())` and never invents a refusal — and deliberately reads no workspace index (unlike `prepare_rename_here`): only refusals that are a pure function of the request buffer's own text (the new-name check, no symbol here, an unresolved or inherited-candidate reference, an unspelled declaration, the same name at a non-file-scope declaration); every index-answered refusal stays on the slow road. The engine remains the authority, and every selector must supply a superset of files needed for edits and refusals (inline gap: §2.9-33). |
|
||||
| `lucisv_server ──▶ vlog_formatter` | depends | `format_source`, `format_range`/`LineRanges` (range, ranges, on-type formatting), `Config`, `fence::protected_regions` (quick-fix filter). |
|
||||
| `lucisv_server ──▶ vlog_formatter` | depends | `format_source`, `format_selection`/`LineRanges` (range, ranges, on-type formatting — since TODO §66.2, 2026-11-09; `format_range` is now the CLI's `--lines` and the engine's own fallback for module/package-level selections), `Config`, `fence::protected_regions` (quick-fix filter). |
|
||||
| `lucisv_server ──▶ vlog_linter` | depends | `run`, `lint` + `LintContext::from_parse` (lints from the `Document`'s own parse — one-parse), `default_rules`, `apply_fixes`, `rule_by_name`. Same three promises the CLI relies on. |
|
||||
| `lucisv_mcp ──▶ lucisv_core, vlog_parser, vlog_semantic, vlog_refactor, vlog_formatter, vlog_linter` | depends | The MCP block (2026-09-23, `docs/mcp/PLAN.md`, `TODO-MCP.md`): `lucisv-mcp` composes the six libraries through their public APIs only — `Discovery`/`filelist`/`walk`/`content_hash`/`write_atomic` (core); `tokenize`, `parse_tolerant`, `parse_source` (strict, the structural edits' rule 1), `LineIndex`, `defines`, the AST (`Item`/`ItemKind`, `Meta::leading`, `Connections`), `PARSE_STACK_SIZE` (parser); `analyze`, `IndexBuilder::{add_file, add_facts}`, `WorkspaceIndex::{absorb, fingerprint, units, members_of, member_in, instantiations, workspace_symbols, find_define, files_mentioning, …}`, `resolve_external`, `FileFacts::{of, decode}`, `FACTS_FORMAT` (semantic); `rename`, `add_port`, `remove_port`, `find_references`, `instantiation_plan`, `module_definition`, `enclosing_module` (refactor); `format_source`/`fence` (formatter); `LintContext::from_parse`, `lint_with`, `select_rules`, `apply_fixes`, `rules_markdown`, `MentionOracle` (linter). **Never `lucisv_server`** (bin-only) and never `lsp-types`. Feature READMEs `docs/features/mcp-*`. **M7 (2026-09-23, the lean catalogue):** nine tools; `diff::unified`, `format_range` and the cursor refactorings (`expand_wildcard`, `convert_to_ansi`, `organize_imports`, `inline_module`, `propagate_ports`, `extract_module`) are no longer called — they stay in the CLI and the server. |
|
||||
| `lucisv_server ──▶ lsp-server / lsp-types` | depends | The transport (synchronous, no async runtime) and the protocol data model. Both pinned exactly. cancel-request additionally relies on `lsp-server 0.10.0`'s stdio transport being a **rendezvous channel** (its own forwarder queue exists because of it) — a version bump must re-read that crate's `stdio.rs`. |
|
||||
@@ -159,7 +159,7 @@ what a change on the pointed-to side must not silently break.
|
||||
| `editors/vscode ◀──▶ vlog_parser` | handshake | The TextMate grammar's keyword alternation is **hand-maintained and test-locked to `vlog_parser::KEYWORDS`**: `crates/lucisv_server/tests/grammar.rs` fails, naming the missing/extra words, when they diverge (there is no generator script). Adding a keyword to `token.rs`'s `keywords!` macro is therefore also a hand edit to `editors/vscode/syntaxes/systemverilog.tmLanguage.json`. |
|
||||
| `editors/nvim ──▶ lucisv_server` | depends | Documentation-only module: config snippets consuming the same spawn contract and settings shape. No code. |
|
||||
| `tools/ ◀──▶ crates + editors/vscode` | handshake | `release.sh` parses `lucisv --version` (field 2), runs `smoke.js` against the built server, stages `dist/lucisv[-server]-<version>-<triple>` names, packages seven `.vsix` files and asserts their `bin/` layouts. `audit_artifacts.sh` and `prune_release_assets.sh` key on those exact names. The version number lives in exactly four files (two `Cargo` files, two `package*.json`) and nowhere in Rust source. |
|
||||
| `CI (Gitea Actions) ──▶ tools/` | depends | `release.yml` is (almost) all `tools/` one-liners — `release.sh --cross`, `audit_artifacts.sh`, `prune_release_assets.sh`, `release_notes.sh`, `publish_release.sh` — so every release step runs by hand too; its only inline logic is the tag-vs-`lucisv --version` check. `ci.yml` is plain `cargo fmt`/`clippy`/`test` plus `scripts/corpus_gate.sh` (which reaches `tools/corpus_fetch.sh` on a cache miss). Tag `vX.Y.Z` must equal the workspace version; release notes come from `CHANGELOG.md`'s `## <version> — <date>` headings via `release_notes.sh`. |
|
||||
| `CI (Gitea Actions) ──▶ tools/` | depends | `release.yml` is (almost) all `tools/` one-liners — `gates.sh` first (the release is gated since 0.65.1), then `release.sh --cross`, `audit_artifacts.sh`, `prune_release_assets.sh`, `release_notes.sh`, `publish_release.sh` — so every release step runs by hand too; its only inline logic is the tag-vs-`lucisv --version` check. `ci.yml` is plain `cargo fmt`/`clippy`/`test` plus `scripts/corpus_gate.sh` (which reaches `tools/corpus_fetch.sh` on a cache miss). Tag `vX.Y.Z` must equal the workspace version; release notes come from `CHANGELOG.md`'s `## <version> — <date>` headings via `release_notes.sh`. |
|
||||
| `scripts/score.sh + tools/corpus_check.sh ──▶ lucisv` | depends | The frozen 0/1/2 exit-code contract, plus a **textual** dependency on the message prefixes `parse error:` / `lex error:` / `verification failed:` (a standing fragile coupling — rewording those means telling corpus-check; see §2.9). |
|
||||
|
||||
**Deliberately absent production edges** (also check shared file ownership):
|
||||
@@ -429,6 +429,9 @@ graph LR
|
||||
| `corpus-bugs ──▶ corpus-check` | depends | Fixes exactly the four root causes A–D the corpus check catalogued; measured back to 0 verification errors. |
|
||||
| `range-formatting ──▶ format-fences` | depends | A range is "an inverted fence": reuses `Doc::Verbatim`, `fence::collect`/`region_at`, and two helpers widened to `pub(crate)` (`line_start`, `with_trailing_comments`) — the only fence.rs change. |
|
||||
| `range-formatting ──▶ spans` | depends | The planner selects items by span/line. |
|
||||
| `selection-formatting ──▶ range-formatting / format-fences / lucisv-server` | depends | (2026-11-09, TODO §66.2) `format_selection` lays out the smallest run of sibling items/statements a line span covers at its written indentation and splices it in; defers to `format_range` for a module/package-level target; consumes `fence::collect`/`with_trailing_comments` and `Fmt::item_seq`/`stmt_seq`; adds `Printer::print_at` and `FormatError::Selection`. `verify.rs`, `range.rs`, `fence.rs` untouched. The server's range, ranges and on-type `;` requests all go through it. |
|
||||
| `completion-ux ──▶ on-type-formatting / inline-templates / completion-core / member-completion` | depends | (2026-11-17, TODO §68.1) the newline on-type answer writes an owed `end` (`on_type/auto_end.rs`, `begin_owes_an_end` shared with the `begin` ghost); keyword ghosts after the template triggers (`inline/keywords.rs`, follows `selectedCompletionInfo`); sortText tiers 2/3 are this buffer's declared names and used words (`completion/buffer.rs`); connection items keep connected ports and insert `name($1)` (`completion/connection.rs`). Extension `typing.js` sends the on-type request when `editor.formatOnType` is off. Server crate only. |
|
||||
| `port-entry-grace ──▶ header-recovery / pull-diagnostics / change-debounce` | depends | (2026-11-17, TODO §68.2) tolerant-mode recovery of an unfinished named connection in `parser/recover_list.rs` (lone `.`, value left open at its line end, trailing `,` — always a diagnostic inside the entry; strict mode and valid code unchanged); `state/port_grace.rs` withholds the diagnostics of the entry the last edit touched for `PORT_ENTRY_GRACE` (1.5 s) in a named-connection list of an instance, released by the main loop's timeout, an edit elsewhere, or a save; `workspace/diagnostic/refresh` for pulling clients. A trailing `,` in a named list is now a tolerant diagnostic — read by Format Selection, the refactor check and the MCP placement check. |
|
||||
| `alignment ──▶ spans` (+ name-spans) | depends | Anchor columns are derived from `name_span` byte offsets + the source text; deliberately **no** token-level representation of spacing. `doc.rs`/`printer.rs`/`verify.rs` untouched. |
|
||||
| `alignment ──▶ format-fences` | depends | `fence::region_at` (via `Fmt::is_fenced`) keeps fenced items out of alignment groups. |
|
||||
| `shared-fence-filter ◀──▶ linter-core / server-lint` | handshake | Closes server-lint Handshake 3: `fence::protected_regions` + `is_protected` become the **one** answer to "what may an automatic fix not touch"; CLI `--fix` and server quick fixes both call it; `vlog_linter` itself deliberately stays fence-blind. |
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
# The checks are pre-publish/developer checks, not part of the shipped
|
||||
# extension. `restart.js`, `mcp.js` and the `hierarchy*`/`references*` modules
|
||||
# themselves ARE shipped — `extension.js` requires them.
|
||||
# extension. `restart.js`, `typing.js`, `mcp.js` and the `hierarchy*`/`references*` modules
|
||||
# themselves ARE shipped — `extension.js` requires them. So are `commentKeywords.js`
|
||||
# and `commentScan.js`.
|
||||
smoke.js
|
||||
mcp_smoke.js
|
||||
mcp_test.js
|
||||
extract_test.js
|
||||
restart_test.js
|
||||
hierarchyCurrent_test.js
|
||||
hierarchyPalette_test.js
|
||||
hierarchyModel_test.js
|
||||
hierarchySections_test.js
|
||||
hierarchyView_test.js
|
||||
referencesModel_test.js
|
||||
referencesView_test.js
|
||||
typing_test.js
|
||||
semanticTokens_test.js
|
||||
commentScan_test.js
|
||||
commentKeywords_test.js
|
||||
.vscode/**
|
||||
.gitignore
|
||||
@@ -5,6 +5,110 @@ for you. The extension and its bundled language server share one version
|
||||
number; the full engineering notes live in the
|
||||
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
|
||||
|
||||
## 0.65.5 — 2026-11-19
|
||||
|
||||
- **Formatting styles, from a drop-down.** `lucisv.format.style` picks the
|
||||
layout: `lucisv` (the default, unchanged), `google`, `lowrisc`, `ansi`,
|
||||
`microsoft`, `nxp`, or `auto`. `google` and `lowrisc` follow those published
|
||||
guides; `ansi`, `microsoft` and `nxp` are lucisv's educated guesses, not
|
||||
published rules.
|
||||
- **`auto` keeps a file in the layout it is already closest to.** It never
|
||||
guesses indent or line length — set those to match the file. A checked-in
|
||||
`lucisv.toml` `[format] style` still outranks the editor setting.
|
||||
|
||||
## 0.65.4 — 2026-11-19
|
||||
|
||||
- **`` `ifdef `` / `` `else `` blocks fold.** Each branch of a
|
||||
conditional-compilation region (`` `ifdef ``, `` `ifndef ``, `` `elsif ``,
|
||||
`` `else ``) collapses on its own; the next branch's line and `` `endif ``
|
||||
stay visible.
|
||||
- **They show in sticky scroll.** Scroll inside a long branch and its
|
||||
`` `ifdef `` or `` `else `` line stays pinned with the enclosing module and
|
||||
blocks.
|
||||
|
||||
## 0.65.3 — 2026-11-19
|
||||
|
||||
- **`TODO`, `FIXME`, `FIX_ME` and `TBD` are highlighted inside comments** —
|
||||
bold, in the new `lucisv.commentKeyword` theme colour, as whole words, never
|
||||
in strings or code.
|
||||
- **Add your own comment words** with `lucisv.commentKeywords.custom`; turn the
|
||||
built-in four off with `lucisv.commentKeywords.builtIn`, ignore case with
|
||||
`lucisv.commentKeywords.caseSensitive`. Changes apply immediately.
|
||||
- **About brackets coloured inside comments:** that is VS Code's bracket-pair
|
||||
colouring while a freshly opened file is still being tokenized; it clears by
|
||||
itself, and lucisv colours nothing inside a comment.
|
||||
|
||||
## 0.65.2 — 2026-11-19
|
||||
|
||||
- **The Hierarchy pane shows where you are.** The rows leading to the file you
|
||||
are editing are lit: every instance of its module in a light, bright orange
|
||||
with a solid bar at the edge, each parent above one shade dimmer, down to a
|
||||
faint floor. Switching files repaints only the rows that changed — no reload,
|
||||
nothing collapses.
|
||||
- **Restyle it or turn it off.** Six theme colours (`lucisv.hierarchyCurrent`,
|
||||
`lucisv.hierarchyParent1`–`3`, `lucisv.hierarchyAncestor`,
|
||||
`lucisv.hierarchyCurrentBar`) and the setting
|
||||
`lucisv.hierarchy.highlightCurrent`.
|
||||
|
||||
## 0.65.1 — 2026-11-19
|
||||
|
||||
- **Nothing changes in the editor.** This is 0.65.0 rebuilt by a release
|
||||
process that now runs the full test gates before publishing.
|
||||
|
||||
## 0.65.0 — 2026-11-19
|
||||
|
||||
- **Module instantiations are now colour-coded by role.** Module names
|
||||
(`class`), instance names (`function`), port names (`.clk_i` and `.*`,
|
||||
`property`), and connected signals (`variable`) each take a distinct colour
|
||||
instead of blending together in white.
|
||||
- **`#` shares the parameter colour**, separate from `()`: the `#` before a
|
||||
parameter header or override list, `.PARAM` names, and parameter values
|
||||
highlight together as `parameter`, while `#5` delays stay untouched.
|
||||
- **Semantic highlighting works out of the box across themes.** The extension
|
||||
now enables `editor.semanticHighlighting.enabled` by default for Verilog and
|
||||
SystemVerilog and provides distinct TextMate fallback scopes for every role.
|
||||
|
||||
## 0.64.0 — 2026-11-17
|
||||
|
||||
- **`begin` + Enter writes the `end`.** The cursor lands on the indented
|
||||
line between them, ready for the first statement. Turn it off with
|
||||
`lucisv.autoEnd`.
|
||||
- **`always_ff @(` and `always @(` expand with clock and reset** —
|
||||
`posedge clk or negedge rst_n` — and Tab jumps between the two names.
|
||||
- **Suggestions put this file's names first**, ahead of names from other
|
||||
files and keywords.
|
||||
- **Keywords appear as grey ghost text** after two letters; Tab accepts.
|
||||
Turn it off with `lucisv.inlineKeywords`.
|
||||
- **Port suggestions list unconnected ports first**; ports you already
|
||||
connected follow, marked `connected`. Accepting one writes `.name()` with
|
||||
the cursor inside, filled in with a same-named signal when there is one.
|
||||
- **No rushed errors while you type a connection.** The error on a
|
||||
half-typed `.port` waits until you pause for a moment, edit elsewhere or
|
||||
save, and the rest of the file keeps its colours and lint meanwhile.
|
||||
- A trailing comma before the closing `)` of a named connection list is now
|
||||
flagged in the editor (the formatter always refused it).
|
||||
|
||||
## 0.63.1 — 2026-11-11
|
||||
|
||||
- **Sticky scroll shows where you are, layer by layer.** The first line of
|
||||
every block around the top of the editor stays pinned — the module, the
|
||||
`always`, the `case`, the case item, the `if` — up to ten lines deep. It
|
||||
used to pin the module header alone. To go back, set
|
||||
`editor.stickyScroll.defaultModel` to `outlineModel` for Verilog and
|
||||
SystemVerilog.
|
||||
|
||||
## 0.63.0 — 2026-11-09
|
||||
|
||||
- **Format Selection formats just what you selected.** Select an `always`
|
||||
block, a `case` statement or a few statements and only that block is laid
|
||||
out, starting at the indentation it already has; the code around it is
|
||||
left alone. It used to re-lay the whole enclosing module or top-level
|
||||
block.
|
||||
- **Format Selection works while another part of the file is broken.** A
|
||||
syntax error outside the selection no longer stops it.
|
||||
- **`Ctrl+/` (`Cmd+/`) toggles comments** on the current line or every
|
||||
selected line, and brackets and quotes auto-close.
|
||||
|
||||
## 0.62.0 — 2026-10-19
|
||||
|
||||
- **Find All References and Rename follow paths from a top-level module.**
|
||||
|
||||
@@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view,
|
||||
then open a Verilog or SystemVerilog file. There is no separate server or CLI
|
||||
setup.
|
||||
|
||||
The current release is **0.62.0**. Its platform packages include
|
||||
The current release is **0.65.5**. Its platform packages include
|
||||
`lucisv-server`, the `lucisv` command-line tool and `lucisv-mcp` (see
|
||||
[Agents (MCP)](#agents-mcp)):
|
||||
|
||||
@@ -80,7 +80,16 @@ Most features work as soon as a supported file opens:
|
||||
workspace-aware and verifies its target before opening the rename box.
|
||||
- Type `if (`, `case (`, `begin`, `fork`, `generate`, or `module` at the end of
|
||||
a line to get structural ghost text. Press `Tab` to accept it; use `Alt+]` to
|
||||
cycle when several shapes fit.
|
||||
cycle when several shapes fit. `always_ff @(` offers a clock-and-reset block
|
||||
first and the clock-only one second.
|
||||
- Press `Enter` after a `begin` that has no `end` yet and the `end` is written
|
||||
on the line below, lined up with its statement, with the cursor on the
|
||||
indented line in between.
|
||||
- Start typing a keyword (`alw`, `endm`) and the rest of it appears as grey
|
||||
text; `Tab` accepts it.
|
||||
- After the `.` of a port connection the ports still to connect come first;
|
||||
accepting one writes `.name()` with the cursor inside, pre-filled with a
|
||||
same-named signal when there is one.
|
||||
- Run **Format Document** or **Format Selection** through the standard VS Code
|
||||
commands.
|
||||
|
||||
@@ -106,11 +115,13 @@ enabling both paths formats twice.
|
||||
| Document formatting | Width-aware, deterministic formatting with inferred alignment for ports, connections, and parameter tables |
|
||||
| Range and multi-range formatting | Formats selected constructs while leaving the rest of the file byte-for-byte unchanged |
|
||||
| On-type formatting | Reindents after a newline and formats a completed statement after `;` when `editor.formatOnType` is enabled |
|
||||
| Auto `end` | `Enter` after an unclosed `begin` writes its `end` below the cursor at the statement's indentation, with or without `editor.formatOnType` (`lucisv.autoEnd`) |
|
||||
| Keyword ghosts | A typed prefix of a keyword shows the rest as grey text that follows the popup's selection (`lucisv.inlineKeywords`) |
|
||||
| Format on save | Works through VS Code's native format-on-save flow; a separate LSP save hook is available for other editors |
|
||||
| Safe output | Token equivalence, comment preservation, convergence checks, and all-or-nothing fallback protect source code |
|
||||
| Format fences | `// verilog_format: off` / `on` preserves deliberately hand-formatted regions |
|
||||
| Inline templates | Context-sensitive ghost text completes blocks, cases, processes, generate regions, and modules |
|
||||
| Smart completion | Context-aware statement/declaration templates plus complete module-instantiation snippets from the workspace index |
|
||||
| Smart completion | Context-aware statement/declaration templates plus complete module-instantiation snippets from the workspace index. Names from the current file rank first; after a connection's `.` the unconnected ports come first, connected ones follow marked `connected`, and accepting one writes `.name()` |
|
||||
| Static snippets | Dialect-specific file-level templates for modules, interfaces, packages, classes, functions, tasks, FSMs, assertions, testbenches, guards, and generate loops |
|
||||
| Signature help | Names active ports or parameters in named and ordered instantiations |
|
||||
| Linked editing | Keeps opening and closing labels synchronized for modules, classes, functions, tasks, blocks, forks, and other named scopes |
|
||||
@@ -121,6 +132,7 @@ enabling both paths formats twice.
|
||||
| Feature | What you get |
|
||||
|---|---|
|
||||
| Live parse diagnostics | Error-tolerant parsing keeps useful feedback flowing while code is half typed |
|
||||
| Quiet while you connect a port | The connection being typed (`.po(` in an instance's port or `#(` list) is not flagged while you type it, only after a short pause, or once you edit elsewhere or save; the rest of the file colours and lints as if it were finished |
|
||||
| Live lint diagnostics | The same lint registry as `lucisv check`, delivered through push or modern pull diagnostics |
|
||||
| Severity per rule | Every rule is `error`, `warning` or `style`, and the squiggle is painted red, yellow or blue to match |
|
||||
| Per-rule toggles | One setting per rule and one per severity class, all under `lucisv.lint.*`; changing any of them re-checks every open file immediately |
|
||||
@@ -141,11 +153,13 @@ enabling both paths formats twice.
|
||||
| Document highlights | Highlights symbol occurrences or the matching opener/closer under the cursor |
|
||||
| Document and workspace symbols | Hierarchical outline plus indexed symbol search across the design |
|
||||
| Include links | Resolvable `` `include`` paths become clickable using local and filelist `+incdir+` search rules |
|
||||
| Folding | Modules, classes, blocks, regions, and multiline comments fold on syntax-aware boundaries |
|
||||
| Folding | Modules, classes, blocks, regions, and multiline comments fold on syntax-aware boundaries; every branch of an `` `ifdef``/`` `ifndef`` region folds on its own, from its directive to the line before the next `` `elsif``/`` `else``/`` `endif``, which stays visible |
|
||||
| Sticky scroll | The first line of every block you are inside — the module, the `always`, the `case`, the case item, the `if`, the `` `ifdef``/`` `else`` branch — stays pinned at the top of the editor, up to ten lines deep |
|
||||
| Inlay hints | Adds port and parameter names to ordered instantiations without guessing at ambiguous sites |
|
||||
| Code lenses | Shows the workspace-wide instantiation count above every module/interface; click to jump to a site |
|
||||
| Call hierarchy | Incoming calls answer “who instantiates this?”; outgoing calls answer “what does this instantiate?” |
|
||||
| Design hierarchy sidebar | Alphabetical instance paths from every top-level module, collapsed until you open them, in-memory fuzzy module/instance search, exact instance/definition jumps, path copy, bookmark highlighting, and split-right opening |
|
||||
| Current-file path | The pane lights the rows that lead to the file you are editing: every instance of the module it declares in a bright orange with a solid bar at its edge, each row above one shade dimmer with a narrower bar, down to a faint floor — in the plain tree, in every DUT section, and on a closed section's header. Switching files repaints only the rows that changed. The shades are the `lucisv.hierarchyCurrent`, `lucisv.hierarchyParent1`–`3`, `lucisv.hierarchyAncestor` and `lucisv.hierarchyCurrentBar` theme colours; `lucisv.hierarchy.highlightCurrent` turns it off |
|
||||
| DUT sections | Star a module as DUT and the pane splits into its own subtree, an upward tree of everything that instantiates it, and every module in neither — two sections per DUT plus one. Stars are remembered per workspace; `lucisv.hierarchy.duts` is the checked-in list a team shares |
|
||||
| Type hierarchy | Walks class `extends` relationships to supertypes and workspace subtypes |
|
||||
|
||||
@@ -157,6 +171,7 @@ enabling both paths formats twice.
|
||||
| TextMate highlighting | Covers keywords, comments, strings, literals, system tasks, directives, and macros before the server starts and inside previews/hover cards |
|
||||
| Rainbow scopes | Six theme-aware colors distinguish nested `begin`/`end` and `fork`/`join` pairs; unmatched scopes use a seventh error color |
|
||||
| Matching scopes | Putting the cursor on an opener highlights the exact matching closer |
|
||||
| Comment keywords | `TODO`, `FIXME`, `FIX_ME` and `TBD` inside `//` and `/* */` comments are painted bold in the `lucisv.commentKeyword` theme colour — whole words only, never in strings or code. Add your own words with `lucisv.commentKeywords.custom` (matched literally, as whole words); `lucisv.commentKeywords.builtIn` turns the four off and `lucisv.commentKeywords.caseSensitive` turns case-insensitive matching on. Only the lines on screen (plus a margin) are searched for the words; an edit above the screen re-reads the lines from the edit down to it, and a file too large for VS Code to tokenize (over 20 MiB or 300 000 lines) is not painted |
|
||||
|
||||
### Refactoring
|
||||
|
||||
@@ -305,13 +320,20 @@ Server-side templates add `if`, `if/else`, `else if`, `case`, `for`, `while`,
|
||||
|---|---:|---|
|
||||
| `lucisv.references.fullLineView` | `true` | `Shift+Alt+F12` in a Verilog/SystemVerilog editor opens lucisv's full-line References view instead of VS Code's, whose previews start a few characters before the match. `false` gives the key back to the built-in command; the context-menu entry works either way, and `Shift+F12` peek is never changed |
|
||||
| `lucisv.rainbowBeginEnd` | `true` | Color nested block pairs and unmatched keywords; updates immediately |
|
||||
| `lucisv.commentKeywords.builtIn` | `true` | Highlight `TODO`, `FIXME`, `FIX_ME` and `TBD` inside comments; updates immediately |
|
||||
| `lucisv.commentKeywords.custom` | `[]` | More words to highlight inside comments, matched literally as whole words — up to 50, each 1–40 characters with no spaces; updates immediately |
|
||||
| `lucisv.commentKeywords.caseSensitive` | `true` | `false` highlights `todo`/`Todo` too, for the built-ins and the custom words alike |
|
||||
| `lucisv.inlineTemplates` | `true` | Show context-aware structural ghost text; requires `editor.inlineSuggest.enabled` |
|
||||
| `lucisv.inlineKeywords` | `true` | Ghost the rest of a keyword while its first letters are typed; follows the popup's selected entry; requires `editor.inlineSuggest.enabled` |
|
||||
| `lucisv.autoEnd` | `true` | Write the `end` when `Enter` is pressed after a `begin` that has none |
|
||||
| `lucisv.inlineInstantiation` | `true` | Ghost the full instantiation (parameters and ports) once a module's name is typed exactly and followed by a space; requires `editor.inlineSuggest.enabled` |
|
||||
| `lucisv.lineLength` | unset | Maximum formatter width, 40–400; built-in default is 100 |
|
||||
| `lucisv.indent` | unset | Indent width, 1–8; falls back to the editor tab size, then 2 |
|
||||
| `lucisv.format.style` | `lucisv` | A drop-down of layout presets — `lucisv`, `google`, `lowrisc`, `ansi`, `microsoft`, `nxp` — or `auto`, which keeps each file in the preset it is already closest to (remembered per document from its last full format, so on-type and selection formatting stay fast and keep the preset while the file has a syntax error). `auto` picks a layout for the configured indent and width and never infers them: set `lucisv.indent` (or the project's `indent`) to match the file first — a 4-space Allman file under `auto` at indent 2 comes out in the `lucisv` layout. A preset also sets the indent and line length, below `lucisv.indent`/`lucisv.lineLength`; `ansi`, `microsoft` and `nxp` are lucisv's guesses, not those organisations' rules. See the [style table](https://git.luci.ooo/lucio/lucisv/src/branch/master/README.md#named-styles) |
|
||||
| `lucisv.exclude` | `[]` | Extra index exclusions added to the project's own patterns |
|
||||
| `lucisv.filelist` | `""` | EDA `.f` filelist to index instead of walking the folder |
|
||||
| `lucisv.hierarchy.duts` | `[]` | Modules the Hierarchy pane treats as DUTs, by name — the checked-in list a team shares. Each one adds two sections ahead of "Other modules"; a DUT from this setting is shown locked and can only be removed here |
|
||||
| `lucisv.hierarchy.highlightCurrent` | `true` | Light the Hierarchy pane's rows leading to the active file, brightest on the file's own module and dimmer each level up |
|
||||
| `lucisv.index.scope` | `folder` | Index the folders your open files live in, or every workspace folder with `workspace`; answers stay scope-relative until the scope reaches a folder |
|
||||
| `lucisv.index.scopeDepth` | `0` | How many folders above an open file the `folder` scope starts from; `1` lets a file in `rtl/` index `include/` beside it |
|
||||
| `lucisv.index.maxFileSize` | `1 MiB` | Largest walked file the index reads, in bytes; `0` removes the cap, and a file you open is always indexed in full |
|
||||
@@ -383,8 +405,11 @@ The configuration ladder is:
|
||||
|
||||
1. The nearest `lucisv.toml` / `.lucisv.toml` discovered for the file.
|
||||
2. `lucisv.lineLength` and `lucisv.indent` editor settings.
|
||||
3. VS Code's tab size, for indentation only.
|
||||
4. Built-in defaults: 100 columns and 2 spaces.
|
||||
3. The indent and width of the style the file resolves to (`[format] style`
|
||||
in that `lucisv.toml`, else `lucisv.format.style`) — when one other than
|
||||
`lucisv` or `auto` was chosen, this outranks the tab size below.
|
||||
4. VS Code's tab size, for indentation only.
|
||||
5. Built-in defaults: 100 columns and 2 spaces.
|
||||
|
||||
`lucisv.filelist` is an explicit editor override for index scope. Open buffers
|
||||
are always layered over the chosen scope, even when a scratch file is not in
|
||||
@@ -406,6 +431,67 @@ Every nesting color is a proper VS Code theme color:
|
||||
}
|
||||
```
|
||||
|
||||
The comment keywords are one more, `lucisv.commentKeyword` (bold, orange by
|
||||
default):
|
||||
|
||||
```jsonc
|
||||
"workbench.colorCustomizations": {
|
||||
"lucisv.commentKeyword": "#FF9E3D"
|
||||
}
|
||||
```
|
||||
|
||||
## Release 0.65.5 highlights
|
||||
|
||||
Version 0.65.5 adds named formatting styles — `google`, `lowrisc`, `ansi`,
|
||||
`microsoft`, `nxp` and `auto` beside the unchanged default — chosen from the
|
||||
`lucisv.format.style` drop-down or `[format] style` in `lucisv.toml`.
|
||||
|
||||
## Release 0.65.4 highlights
|
||||
|
||||
Version 0.65.4 makes `` `ifdef `` regions foldable branch by branch, and pins
|
||||
the branch you are inside in sticky scroll.
|
||||
|
||||
## Release 0.65.3 highlights
|
||||
|
||||
Version 0.65.3 highlights `TODO`, `FIXME`, `FIX_ME` and `TBD` inside comments,
|
||||
and any words of your own you list in `lucisv.commentKeywords.custom` — in
|
||||
comments only, never in code or strings.
|
||||
|
||||
## Release 0.65.2 highlights
|
||||
|
||||
Version 0.65.2 lights your position in the Hierarchy pane: the instances of
|
||||
the module you are editing in a light, bright orange, and each parent above
|
||||
them a shade dimmer, so the path from the top of the design to the open file
|
||||
reads at a glance.
|
||||
|
||||
## Release 0.65.0 highlights
|
||||
|
||||
Version 0.65.0 gives module instantiations distinct syntax colours across
|
||||
themes: module names (`class`), instance names (`function`), port names
|
||||
(`.port` / `.*`, `property`), and connected signals (`variable`) each stand
|
||||
out, and parameter-list `#` signs share the `parameter` colour separately from
|
||||
parentheses.
|
||||
|
||||
## Release 0.64.0 highlights
|
||||
|
||||
Version 0.64.0 makes typing quicker: `begin` + Enter writes the `end`,
|
||||
`always_ff @(` expands with clock and reset, the suggestion list puts this
|
||||
file's names first, keywords appear as grey ghost text, and port suggestions
|
||||
list unconnected ports first and write `.name()` — while the errors on a
|
||||
connection you are still typing wait until you pause.
|
||||
|
||||
## Release 0.63.1 highlights
|
||||
|
||||
Version 0.63.1 makes sticky scroll pin the first line of every block you are
|
||||
inside — the module, the `always`, the `case`, the case item, the `if` —
|
||||
instead of the module header alone.
|
||||
|
||||
## Release 0.63.0 highlights
|
||||
|
||||
Version 0.63.0 makes **Format Selection** format just the block you selected,
|
||||
at the indentation it already has, and makes `Ctrl+/` (`Cmd+/`) toggle
|
||||
comments on the selected lines.
|
||||
|
||||
## Release 0.62.0 highlights
|
||||
|
||||
Version 0.62.0 lets references and rename follow a hierarchical path from a
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
// Highlight TODO, FIXME, FIX_ME, TBD and the user's own words inside comments
|
||||
// (docs/features/comment-highlighting). Editor decorations, painted only on
|
||||
// the lines an editor shows; where the comments are comes from
|
||||
// `commentScan.js`, which mirrors the TextMate grammar.
|
||||
//
|
||||
// `vscode` is passed in rather than required so the wiring is testable with a
|
||||
// fake (`commentKeywords_test.js`).
|
||||
|
||||
const { chooseWords, wordMatcher, LineStates, keywordRanges } = require('./commentScan');
|
||||
|
||||
/** The settings section this reads: `lucisv.commentKeywords.*`. */
|
||||
const SECTION = 'lucisv.commentKeywords';
|
||||
|
||||
/** The theme colour the words are painted in. One dot: see the README. */
|
||||
const COLOR_ID = 'lucisv.commentKeyword';
|
||||
|
||||
/** How long typing settles before the edited editor is repainted. */
|
||||
const EDIT_DEBOUNCE_MS = 100;
|
||||
|
||||
/** Lines painted beyond each visible range, so a short scroll shows no gap. */
|
||||
const MARGIN_LINES = 50;
|
||||
|
||||
/** VS Code's own default for `editor.maxTokenizationLineLength`. */
|
||||
const DEFAULT_MAX_LINE_LENGTH = 20000;
|
||||
|
||||
/**
|
||||
* VS Code never tokenizes a model above either size when
|
||||
* `editor.largeFileOptimizations` is on (`textModel.ts`,
|
||||
* `LARGE_FILE_SIZE_THRESHOLD` / `LARGE_FILE_LINE_COUNT_THRESHOLD`; the length
|
||||
* is in UTF-16 units). Such a file shows no comment colour, so none of it is
|
||||
* painted either.
|
||||
*/
|
||||
const UNTOKENIZED_LENGTH = 20 * 1024 * 1024;
|
||||
const UNTOKENIZED_LINES = 300 * 1000;
|
||||
|
||||
class CommentKeywords {
|
||||
/**
|
||||
* @param vscode the `vscode` module (or a fake of it)
|
||||
* @param isTarget which documents to paint (the Verilog ones)
|
||||
* @param log where a line about skipped custom words goes
|
||||
*/
|
||||
constructor(vscode, isTarget, log = () => {}) {
|
||||
this.vscode = vscode;
|
||||
this.isTarget = isTarget;
|
||||
this.log = log;
|
||||
/**
|
||||
* Per document object: `{ states, maxLineLength, untokenized }` — its
|
||||
* block-comment line states, the line-length cutoff they were computed
|
||||
* with, and whether VS Code tokenizes it at all.
|
||||
*/
|
||||
this.documents = new Map();
|
||||
/** Editors this has painted, so only those are ever cleared. */
|
||||
this.painted = new WeakSet();
|
||||
this.timer = undefined;
|
||||
this.decoration = vscode.window.createTextEditorDecorationType({
|
||||
color: new vscode.ThemeColor(COLOR_ID),
|
||||
fontWeight: 'bold',
|
||||
});
|
||||
this.readSettings();
|
||||
}
|
||||
|
||||
/** Subscribe to everything that can change what is painted. */
|
||||
activate(subscriptions) {
|
||||
const { window, workspace } = this.vscode;
|
||||
subscriptions.push(
|
||||
this.decoration,
|
||||
window.onDidChangeVisibleTextEditors(() => this.paintVisible()),
|
||||
window.onDidChangeTextEditorVisibleRanges((event) => this.paintEditor(event.textEditor)),
|
||||
workspace.onDidChangeTextDocument((event) => this.onEdit(event)),
|
||||
// A language-mode change is reported as close then open of the same
|
||||
// document (`languages.setTextDocumentLanguage`'s documentation), and
|
||||
// the open fires before the editor shows the new mode — hence the tick.
|
||||
workspace.onDidCloseTextDocument((document) => this.documents.delete(document)),
|
||||
workspace.onDidOpenTextDocument(() => setTimeout(() => this.paintVisible(), 0)),
|
||||
workspace.onDidChangeConfiguration((event) => this.onConfiguration(event)),
|
||||
{ dispose: () => clearTimeout(this.timer) },
|
||||
);
|
||||
this.paintVisible();
|
||||
}
|
||||
|
||||
/** Read the words and the case rule afresh. */
|
||||
readSettings() {
|
||||
const settings = this.vscode.workspace.getConfiguration(SECTION);
|
||||
const caseSensitive = settings.get('caseSensitive', true) !== false;
|
||||
const { words, skipped } = chooseWords({
|
||||
builtIn: settings.get('builtIn', true),
|
||||
custom: settings.get('custom', []),
|
||||
caseSensitive,
|
||||
});
|
||||
if (skipped.length) {
|
||||
this.log(`lucisv: ${SECTION}.custom: ignored ${skipped.length} entr${skipped.length === 1 ? 'y' : 'ies'} `
|
||||
+ '(each must be 1–40 characters with no spaces, at most 50 words)');
|
||||
}
|
||||
this.matcher = wordMatcher(words, caseSensitive);
|
||||
}
|
||||
|
||||
/**
|
||||
* `editor.maxTokenizationLineLength` as VS Code applies it to `document`:
|
||||
* read with the document as scope, so a `[systemverilog]` override counts.
|
||||
*/
|
||||
maxLineLength(document) {
|
||||
const max = this.vscode.workspace.getConfiguration('editor', document).get('maxTokenizationLineLength');
|
||||
return Number.isInteger(max) && max > 0 ? max : DEFAULT_MAX_LINE_LENGTH;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether VS Code tokenizes `document` at all. Decided once per document,
|
||||
* as VS Code decides it once per model, at creation.
|
||||
*/
|
||||
isUntokenized(document) {
|
||||
const editor = this.vscode.workspace.getConfiguration('editor', document);
|
||||
if (editor.get('largeFileOptimizations', true) === false) return false;
|
||||
if (document.lineCount > UNTOKENIZED_LINES) return true;
|
||||
const last = document.lineAt(document.lineCount - 1);
|
||||
return document.offsetAt(last.range.end) > UNTOKENIZED_LENGTH;
|
||||
}
|
||||
|
||||
/** The cached record for `document`, fresh if its cutoff changed. */
|
||||
recordOf(document) {
|
||||
const maxLineLength = this.maxLineLength(document);
|
||||
let record = this.documents.get(document);
|
||||
if (!record) {
|
||||
record = { states: new LineStates(), maxLineLength, untokenized: this.isUntokenized(document) };
|
||||
this.documents.set(document, record);
|
||||
} else if (record.maxLineLength !== maxLineLength) {
|
||||
// The cutoff decides which lines carry a block comment over, so every
|
||||
// cached state may be wrong.
|
||||
record.states = new LineStates();
|
||||
record.maxLineLength = maxLineLength;
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
/** A setting this depends on changed: honour it now, both ways. */
|
||||
onConfiguration(event) {
|
||||
const ours = event.affectsConfiguration(SECTION);
|
||||
const lineLength = event.affectsConfiguration('editor.maxTokenizationLineLength');
|
||||
if (!ours && !lineLength) return;
|
||||
// A changed cutoff is noticed per document by `recordOf`.
|
||||
if (ours) this.readSettings();
|
||||
this.paintVisible();
|
||||
}
|
||||
|
||||
/** Forget the states below the first edited line, then repaint soon. */
|
||||
onEdit(event) {
|
||||
if (!this.isTarget(event.document)) return;
|
||||
const record = this.documents.get(event.document);
|
||||
if (record && event.contentChanges.length) {
|
||||
const first = Math.min(...event.contentChanges.map((change) => change.range.start.line));
|
||||
record.states.invalidateFrom(first);
|
||||
}
|
||||
clearTimeout(this.timer);
|
||||
this.timer = setTimeout(() => this.paintVisible(), EDIT_DEBOUNCE_MS);
|
||||
}
|
||||
|
||||
paintVisible() {
|
||||
for (const editor of this.vscode.window.visibleTextEditors) this.paintEditor(editor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Paint the keywords on (and just around) the lines `editor` shows — or
|
||||
* clear them, when there is nothing to paint or the document stopped being
|
||||
* Verilog.
|
||||
*/
|
||||
paintEditor(editor) {
|
||||
const document = editor.document;
|
||||
if (!this.isTarget(document)) {
|
||||
if (this.painted.has(editor)) this.setRanges(editor, []);
|
||||
return;
|
||||
}
|
||||
if (!this.matcher) {
|
||||
this.setRanges(editor, []);
|
||||
return;
|
||||
}
|
||||
const { states, maxLineLength, untokenized } = this.recordOf(document);
|
||||
if (untokenized) {
|
||||
this.setRanges(editor, []);
|
||||
return;
|
||||
}
|
||||
const lineText = (line) => document.lineAt(line).text;
|
||||
const last = document.lineCount - 1;
|
||||
const ranges = [];
|
||||
for (const { from, to } of paddedLines(editor.visibleRanges, last)) {
|
||||
const found = keywordRanges({
|
||||
states, lineText, from, to, matcher: this.matcher, maxLineLength,
|
||||
});
|
||||
for (const { line, start, end } of found) ranges.push(new this.vscode.Range(line, start, line, end));
|
||||
}
|
||||
this.setRanges(editor, ranges);
|
||||
}
|
||||
|
||||
setRanges(editor, ranges) {
|
||||
editor.setDecorations(this.decoration, ranges);
|
||||
if (ranges.length) this.painted.add(editor);
|
||||
else this.painted.delete(editor);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The visible ranges as line spans, widened by `MARGIN_LINES`, clamped to the
|
||||
* document and merged where they overlap, so no line is scanned twice.
|
||||
*/
|
||||
function paddedLines(visibleRanges, lastLine) {
|
||||
const spans = visibleRanges
|
||||
.map((range) => ({
|
||||
from: Math.max(0, range.start.line - MARGIN_LINES),
|
||||
to: Math.min(lastLine, range.end.line + MARGIN_LINES),
|
||||
}))
|
||||
.sort((a, b) => a.from - b.from);
|
||||
const merged = [];
|
||||
for (const span of spans) {
|
||||
const previous = merged[merged.length - 1];
|
||||
if (previous && span.from <= previous.to + 1) previous.to = Math.max(previous.to, span.to);
|
||||
else merged.push({ ...span });
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
module.exports = { CommentKeywords, paddedLines, COLOR_ID, SECTION };
|
||||
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user