Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
948f8a0b32 | ||
|
|
e9f5090632 | ||
|
|
88546c8b4e | ||
|
|
5c00b701fc | ||
|
|
464929262b | ||
|
|
e4db0ac1fc | ||
|
|
857b82d58a | ||
|
|
14213f6a93 | ||
|
|
c1076f9405 | ||
|
|
6844fbecb6 | ||
|
|
3132c24b21 | ||
|
|
ea586d29bc | ||
|
|
e115f9fc8f | ||
|
|
d8119aa9c6 | ||
|
|
2854bcaa2f | ||
|
|
3598a9145e | ||
|
|
a8c4a2ecf8 | ||
|
|
66bf27617e | ||
|
|
9dc567c72a | ||
|
|
92875e6c6d | ||
|
|
51b975bf68 | ||
|
|
ec492cdd86 |
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
|
||||
|
||||
+262
@@ -4,6 +4,268 @@ 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.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
|
||||
|
||||
(`docs/features/top-rooted-paths`, `docs/features/release-gates`,
|
||||
`docs/features/references-fanout-pd-main`.)
|
||||
|
||||
- **A hierarchical path that starts at a top-level module now resolves.**
|
||||
`tb.dut.u_core.sig` written in a file that does not declare `tb` used to
|
||||
stop at `tb`; now every segment is a reference — `find_references` and LSP
|
||||
references list it, and a rename of `dut`, `u_core`, `sig` or a generate
|
||||
label on the way rewrites the path. `$root.tb…` works; a local `tb`
|
||||
shadows. The LSP's rename also reads the files of the path's root and the
|
||||
modules it passes through. **Rooted only when lucisv can prove the head is
|
||||
a top-level module**: not when the name could come from a wildcard import
|
||||
(including `import uvm_pkg::*` with `uvm_pkg` outside the project), not
|
||||
inside a class, not beside a macro that stands where a declaration could,
|
||||
and not when the name is also a package or several modules share it —
|
||||
those paths are left unchanged and warned about exactly as before. The
|
||||
index cache format moves to 22, so a 0.61.0 cache is rebuilt once.
|
||||
- An unresolved path through the renamed name is warned about once (it was
|
||||
sometimes named twice).
|
||||
- **Find All References across blocks is relative to the index scope, by
|
||||
design.** On a default `folder` scope a module's references and rename
|
||||
reach only the folders the index covers; the `lucisv.index.scope` setting
|
||||
now says that a rename of a module instantiated outside the scope leaves
|
||||
those instantiations unchanged (use `workspace`, or open the file first).
|
||||
- **`tools/gates.sh`** is the release gate: fmt, clippy, the test build,
|
||||
each crate's suites, the doc-tests, the corpus gate and the extension
|
||||
tests, each a separately guarded step with its own log and a summary; a
|
||||
step the guard kills is retried once and reported as `KILLED → retried`.
|
||||
- **`tools/guard.sh` fixes:** its memory limit now sees every process in the
|
||||
tree (a pid-list bug hid everything three or more levels down, so builds
|
||||
and test-spawned servers were never capped), and a closed stdin no longer
|
||||
makes the command silently not run.
|
||||
|
||||
## 0.61.0 — 2026-10-14
|
||||
|
||||
### Call hierarchy from anywhere, functions and tasks as nodes; full-line references in VS Code
|
||||
|
||||
@@ -93,7 +93,10 @@ files over 600 workspace-wide: `lucisv_server/src/perf.rs` 907 (reasoned),
|
||||
|
||||
- `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
|
||||
without a comment explaining why), `cargo test` green — all three
|
||||
before declaring any work finished.
|
||||
before declaring any work finished. **Before a release, and whenever
|
||||
the whole workspace is gated, run `tools/gates.sh`** (every gate as a
|
||||
separate guarded step with kept logs; `--only`/`--skip` for a subset)
|
||||
instead of a bare `cargo test --workspace`.
|
||||
- No `unwrap()`/`expect()`/`panic!` in library code paths; return
|
||||
`Result`. Tests and `main.rs` argument handling may use them.
|
||||
- Public items get a one-line doc comment. Doc comments say what/why,
|
||||
@@ -136,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
|
||||
@@ -160,6 +176,9 @@ process tree when its resident set or wall clock exceeds the limits
|
||||
`tools/guard.sh`** — dev, QA and lead alike, foreground or background.
|
||||
- A guard kill is a finding: report the command and the limit it hit;
|
||||
do not raise the limit to make it pass.
|
||||
- The release gate is `tools/gates.sh`, which guards each step with its
|
||||
own limits and retries a killed step once (shown as `KILLED → retried`);
|
||||
do not wrap it in another `guard.sh`.
|
||||
|
||||
## Parallel lanes (the 2-agent loop)
|
||||
|
||||
@@ -181,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.61.0"
|
||||
version = "0.65.3"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.61.0"
|
||||
version = "0.65.3"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_mcp"
|
||||
version = "0.61.0"
|
||||
version = "0.65.3"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"serde",
|
||||
@@ -126,7 +126,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.61.0"
|
||||
version = "0.65.3"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.61.0"
|
||||
version = "0.65.3"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.61.0"
|
||||
version = "0.65.3"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"vlog_formatter",
|
||||
@@ -279,11 +279,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.61.0"
|
||||
version = "0.65.3"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.61.0"
|
||||
version = "0.65.3"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -292,7 +292,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.61.0"
|
||||
version = "0.65.3"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -13,7 +13,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.61.0"
|
||||
version = "0.65.3"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -1037,11 +1037,13 @@ expected; no PRs or review required.
|
||||
|
||||
```bash
|
||||
cargo build --release # binaries at target/release/{lucisv,lucisv-server}
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
tools/guard.sh -- cargo test --workspace # unit, integration, snapshots, doc tests
|
||||
tools/gates.sh # every gate: fmt, clippy, build, each crate's suites, doc tests, corpus, node
|
||||
tools/gates.sh --only suites # just the per-crate test suites
|
||||
```
|
||||
|
||||
`tools/gates.sh` runs each gate as its own guarded step with a kept log and
|
||||
prints a summary (`docs/features/release-gates/README.md`).
|
||||
|
||||
Snapshot tests live in `crates/vlog_formatter/tests/fixtures/`; regenerate
|
||||
expected outputs only for intentional formatting changes with
|
||||
`UPDATE_SNAPSHOTS=1 tools/guard.sh -- cargo test -p vlog_formatter`.
|
||||
|
||||
@@ -6950,7 +6950,10 @@ commit. Rules as §63/§64: every suite and sweep through `tools/guard.sh`,
|
||||
never piped (log to a file, check `guard exit` and the suite count); no
|
||||
`sleep` over 60 s; never `grep` without a path; opentitan read-only (the
|
||||
eval clone `~/.cache/lucisv-eval/ot` may be read and, for an edit test,
|
||||
restored with `git -C … checkout -- <file>`). Ships as 0.60.0.
|
||||
restored with `git -C … checkout -- <file>`). ~~Ships as 0.60.0.~~
|
||||
**Release targets (corrected 2026-10-19):** 65.1 shipped in **0.60.0**
|
||||
(2026-10-08); 65.2, 65.3 and 65.4 are open and target **0.62.0** (wave
|
||||
below, §65.7); 65.6 is unscheduled.
|
||||
|
||||
### 65.1 Rename and references through a generate block label (topo §2.9-43, MCP-14)
|
||||
|
||||
@@ -7007,18 +7010,18 @@ top-level instantiations in
|
||||
settle, so not an indexing race. Feature README
|
||||
`docs/features/references-fanout-pd-main`.
|
||||
|
||||
- [ ] root cause named (the fan-out/scope selection in `lucisv_server` —
|
||||
- [x] root cause named (the fan-out/scope selection in `lucisv_server` —
|
||||
`module_select`, `state/` scope widening, or the index's
|
||||
instantiation facts for those three files; they are large generated
|
||||
files, check the 1 MiB cap and the word census)
|
||||
- [ ] the LSP answer equals the whole-set engine's for the module name and
|
||||
- [x] ~~the LSP answer equals the whole-set engine's for the module name and
|
||||
for a port of it, from the declaration and from a use; a regression
|
||||
test with a fixture that reproduces the cause (not only opentitan)
|
||||
- [ ] an opentitan test (ignored by default, like `tests/opentitan.rs`)
|
||||
test with a fixture that reproduces the cause (not only opentitan)~~ — **closed by the owner's ruling 2026-10-19: scope-relative by design.** The LSP answer equals the engine over the same file set (pinned for both scopes in `server/tests/references_scope.rs`); the default `folder` scope does not reach the three tops, `workspace` does (14/12).
|
||||
- [x] an opentitan test (ignored by default, like `tests/opentitan.rs`)
|
||||
pinning the 14 and 12
|
||||
- [ ] QA: the same comparison for five other modules instantiated from a
|
||||
- [x] ~~QA: the same comparison for five other modules instantiated from a
|
||||
`*_pd_main.sv` top, and for `rename`'s fan-out (does rename see the
|
||||
three sites?)
|
||||
three sites?)~~ — not run: no production code changed under the ruling
|
||||
|
||||
### 65.3 The combined test command stalls entering the doc-tests
|
||||
|
||||
@@ -7028,16 +7031,16 @@ in `Doc-tests vlog_linter` until the guard cut it; on 2026-09-30 an
|
||||
independent session's run hit its 600 s guard "entering the final doc-test
|
||||
harness". `cargo test --workspace --doc` alone passes in under a minute.
|
||||
|
||||
- [ ] reproduce (how often, which doc-test, what the stuck process tree
|
||||
- [x] reproduce (how often, which doc-test, what the stuck process tree
|
||||
is — `rustdoc`, `rust_out`, stdin?) and name the cause; `guard.sh`
|
||||
runs the command with `0<&3` — check what the doc-test harness
|
||||
inherits as stdin when the gate runs in the background
|
||||
- [ ] fix at the cause (the harness, the doc-test, or the guard), and make
|
||||
- [x] fix at the cause (the harness, the doc-test, or the guard), and make
|
||||
the release gate a script (`tools/gates.sh`) that runs fmt, clippy,
|
||||
the test build, the suites, the doc-tests, the corpus gate and the
|
||||
node tests as separate guarded steps with logs kept and a summary
|
||||
that shows a kill — `tools/RELEASING.md` and CLAUDE.md point at it
|
||||
- [ ] ten consecutive green runs of the gate script recorded
|
||||
- [x] ten consecutive green runs of the gate script recorded
|
||||
|
||||
### 65.4 Resolve a hierarchical path rooted at a top-level module name (lead to schedule; from §65.1 QA F1)
|
||||
|
||||
@@ -7061,8 +7064,8 @@ tb.dut.gen_sw_assigns[i]…`) under `rename gen_sw_assigns`. Watch: a name
|
||||
that is both a local and a top module (the local wins), `$root.tb…`, and the
|
||||
index cost of the extra external candidates on every DV path.
|
||||
|
||||
- [ ] root lookup in `head_site`, the head recorded as a module use
|
||||
- [ ] QA's repro renames the path instead of warning; the §65.1 warning
|
||||
- [x] root lookup in `head_site`, the head recorded as a module use
|
||||
- [x] QA's repro renames the path instead of warning; the §65.1 warning
|
||||
still fires for a root the workspace does not declare
|
||||
|
||||
### 65.6 Rename inside included fragments (lead to schedule; from §65.1 QA final H4)
|
||||
@@ -7087,3 +7090,176 @@ modules is two bindings and must agree or be refused. QA's repro:
|
||||
binding agrees
|
||||
- [ ] QA's repro renames the fragment's use; the §65.1 warning remains for
|
||||
what cannot be bound
|
||||
|
||||
|
||||
### 65.7 Wave for 0.62.0 (planned 2026-10-19, owner's order: "fix those that are true")
|
||||
|
||||
Two parallel lanes first (disjoint files; neither touches `vlog_semantic`),
|
||||
then 65.4 serially (it changes `vlog_semantic` resolution, which §65.2's
|
||||
lane might also need — run after it merges).
|
||||
|
||||
**Lane A — §65.2 references fan-out** (Opus dev → QA → lead), files:
|
||||
`crates/lucisv_server/src/state/sources.rs`, `crates/lucisv_server/src/nav.rs`,
|
||||
new test files under `crates/lucisv_server/src/server/tests/`, a new
|
||||
ignored-by-default `crates/lucisv_server/tests/opentitan_references.rs`,
|
||||
`docs/features/references-fanout-pd-main/README.md`.
|
||||
|
||||
- [x] §65.2's checklist above (closed by ruling: scope-relative by design)
|
||||
|
||||
**Lane B — §65.3 gate script** (Opus dev → QA → lead), files:
|
||||
`tools/gates.sh` (new), `tools/guard.sh` (only if the cause is there),
|
||||
`tools/RELEASING.md`, `docs/features/release-gates/README.md` (new);
|
||||
CLAUDE.md's pointer is the lead's at merge.
|
||||
|
||||
- [x] §65.3's checklist above
|
||||
|
||||
**Then — §65.4 top-module-rooted paths** (serial, after lane A merges).
|
||||
|
||||
- [x] §65.4's checklist above (conservative by the owner's ruling: a head with an import candidate, inside a class, or beside a macro that could declare it is not rooted)
|
||||
|
||||
|
||||
### 65.8 Completion after a top-rooted path head (deferred from §65.4 H2, 2026-10-19)
|
||||
|
||||
`tb.` offers nothing in completion: the completion walk keeps "an unknown
|
||||
head answers nothing" (two `lucisv_server` completion tests pin it), while
|
||||
resolution now roots an unknown head at a top module. Decide whether
|
||||
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.
|
||||
@@ -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
|
||||
|
||||
@@ -148,6 +148,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.
|
||||
|
||||
@@ -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, Config, LineRanges};
|
||||
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::state::Document;
|
||||
@@ -122,10 +125,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 +145,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);
|
||||
}
|
||||
@@ -700,6 +705,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 +840,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)]);
|
||||
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -117,6 +117,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 +134,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 +647,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 +1369,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)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -98,7 +98,9 @@ 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);
|
||||
let auto_end = self.workspace.client_settings().auto_end.unwrap_or(true);
|
||||
let edits =
|
||||
on_type::on_type_formatting(doc, at.position, ¶ms.ch, &settings.config, auto_end);
|
||||
to_value(edits)
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -316,7 +322,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 +346,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,10 @@ 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);
|
||||
// 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 +62,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 +115,7 @@ impl Server {
|
||||
return;
|
||||
}
|
||||
let uri = p.text_document.uri;
|
||||
let text = {
|
||||
let (text, end) = {
|
||||
let base = self
|
||||
.dirty
|
||||
.iter()
|
||||
@@ -111,8 +123,12 @@ 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)
|
||||
};
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
@@ -315,6 +331,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 +379,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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
@@ -61,8 +60,11 @@ mod progress;
|
||||
mod pull_diagnostics;
|
||||
mod qa_generate_label;
|
||||
mod qa_rename_implicit;
|
||||
mod references_scope;
|
||||
mod references_top_rooted;
|
||||
mod rename_generate_label;
|
||||
mod rename_implicit;
|
||||
mod rename_top_rooted_scope;
|
||||
mod requests;
|
||||
mod scan;
|
||||
mod scan_trace;
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
//! TODO §65.2 over the wire: `references` from a testbench answers within
|
||||
//! the active index scope, and within an equal file set it answers exactly
|
||||
//! what the whole-set engine (`vlog_refactor::find_references`) answers.
|
||||
//! `docs/features/references-fanout-pd-main/README.md`.
|
||||
//!
|
||||
//! The fixture is opentitan's shape in miniature: an IP block with `rtl/`
|
||||
//! and `dv/tb/`, and a generated top two directories away that instantiates
|
||||
//! the block with a multi-line `blk #( … ) u_blk (`.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use super::*;
|
||||
|
||||
const BLK: &str = "module blk #(\n parameter int W = 1\n) (\n input logic clk_i,\n input logic rst_ni\n);\nendmodule\n";
|
||||
const TB: &str = "module tb;\n logic clk, rst_n;\n blk #(\n .W ( 2 )\n ) dut (\n .clk_i ( clk ),\n .rst_ni ( rst_n )\n );\nendmodule\n";
|
||||
const PD_MAIN: &str = "module top_pd_main (\n input logic clk_main_i,\n input logic rst_main_ni\n);\n blk #(\n .W ( 4 )\n ) u_blk (\n // Clock and reset connections\n .clk_i ( clk_main_i ),\n .rst_ni ( rst_main_ni )\n );\nendmodule\n";
|
||||
|
||||
/// The three files, at their opentitan-shaped paths.
|
||||
fn fixture(tag: &str) -> Tree {
|
||||
let tree = Tree::new(tag);
|
||||
tree.write("ip/blk/rtl/blk.sv", BLK);
|
||||
tree.write("ip/blk/dv/tb/tb.sv", TB);
|
||||
tree.write("top/rtl/autogen/top_pd_main.sv", PD_MAIN);
|
||||
tree
|
||||
}
|
||||
|
||||
/// `(path relative to the root, line)` of every location in an answer.
|
||||
fn answered(root: &Path, found: &Value) -> Vec<(String, u64)> {
|
||||
let mut out: Vec<(String, u64)> = found
|
||||
.as_array()
|
||||
.expect("an array")
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let uri = l["uri"].as_str().unwrap_or("?");
|
||||
let path =
|
||||
crate::uri::uri_to_path(&Uri::from_str(uri).expect("a uri")).expect("a path");
|
||||
let rel = path.strip_prefix(root).unwrap_or(&path).display().to_string();
|
||||
(rel, l["range"]["start"]["line"].as_u64().unwrap_or(0))
|
||||
})
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// What the whole-set engine answers over `files`, as [`answered`] spells it.
|
||||
fn engine(
|
||||
root: &Path,
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
) -> Vec<(String, u64)> {
|
||||
let found =
|
||||
vlog_refactor::find_references(files, file, offset, true).expect("the engine answers");
|
||||
let mut out: Vec<(String, u64)> = found
|
||||
.into_iter()
|
||||
.map(|(path, range)| {
|
||||
let text = &files.iter().find(|(p, _)| *p == path).expect("a read file").1;
|
||||
let line = text[..range.start as usize].matches('\n').count() as u64;
|
||||
let rel = path.strip_prefix(root).unwrap_or(&path).display().to_string();
|
||||
(rel, line)
|
||||
})
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// Every file under the tree — the set the MCP's `references` hands the engine.
|
||||
fn every_file(tree: &Tree) -> Vec<(PathBuf, String)> {
|
||||
["ip/blk/rtl/blk.sv", "ip/blk/dv/tb/tb.sv", "top/rtl/autogen/top_pd_main.sv"]
|
||||
.iter()
|
||||
.map(|rel| {
|
||||
let path = tree.path.join(rel);
|
||||
let text = std::fs::read_to_string(&path).expect("read");
|
||||
(path, text)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A references request at the first `needle` on line `line` of `text`, and
|
||||
/// the byte offset the engine is asked at.
|
||||
fn at(uri: &Uri, text: &str, line: usize, needle: &str) -> (Value, u32) {
|
||||
let row = text.lines().nth(line).expect("the line");
|
||||
let character = row.find(needle).expect("the needle on that line");
|
||||
let before: usize = text.lines().take(line).map(|l| l.len() + 1).sum();
|
||||
let params = serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": line, "character": character },
|
||||
"context": { "includeDeclaration": true },
|
||||
});
|
||||
(params, (before + character) as u32)
|
||||
}
|
||||
|
||||
/// The four positions the §65.2 checklist names: the module name and one of
|
||||
/// its ports, each from its declaration and from a use.
|
||||
fn positions(tree: &Tree) -> [(PathBuf, &'static str, usize, &'static str); 4] {
|
||||
let blk = tree.path.join("ip/blk/rtl/blk.sv");
|
||||
let tb = tree.path.join("ip/blk/dv/tb/tb.sv");
|
||||
[
|
||||
(blk.clone(), BLK, 0, "blk"),
|
||||
(tb.clone(), TB, 2, "blk"),
|
||||
(blk, BLK, 3, "clk_i"),
|
||||
(tb, TB, 5, "clk_i"),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn over_the_whole_workspace_references_equal_the_whole_set_engine() {
|
||||
let tree = fixture("refscope_wide");
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let all = every_file(&tree);
|
||||
for (path, text, line, needle) in positions(&tree) {
|
||||
let uri = session.open(&path, text);
|
||||
let (params, offset) = at(&uri, text, line, needle);
|
||||
let lsp = answered(&tree.path, &session.result(References::METHOD, params));
|
||||
let whole = engine(&tree.path, &all, &path, offset);
|
||||
assert_eq!(lsp, whole, "{needle} at {}:{line}", path.display());
|
||||
assert!(
|
||||
lsp.iter().any(|(file, _)| file.ends_with("top_pd_main.sv")),
|
||||
"the generated top is listed: {lsp:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The cause, pinned: under the shipped folder scope a testbench in
|
||||
/// `ip/blk/dv/tb/` raises to `ip/blk/`, the generated top is not in the
|
||||
/// index, and `references` answers what the engine answers over the scope —
|
||||
/// not over every file. Opening the top widens the scope, and the answer
|
||||
/// becomes the whole set's.
|
||||
#[test]
|
||||
fn under_the_folder_scope_references_equal_the_engine_over_the_scope() {
|
||||
let tree = fixture("refscope_folder");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let top = tree.path.join("top/rtl/autogen/top_pd_main.sv");
|
||||
for (path, text, line, needle) in positions(&tree) {
|
||||
let uri = session.open(&path, text);
|
||||
let in_index = session.server.workspace.index().files().contains(&top);
|
||||
assert!(!in_index, "the top is outside the folder scope");
|
||||
let (params, offset) = at(&uri, text, line, needle);
|
||||
let lsp = answered(&tree.path, &session.result(References::METHOD, params));
|
||||
let scoped = engine(&tree.path, &session.server.workspace.sources(), &path, offset);
|
||||
assert_eq!(lsp, scoped, "{needle} at {}:{line}", path.display());
|
||||
assert!(!lsp.iter().any(|(file, _)| file.ends_with("top_pd_main.sv")), "{lsp:?}");
|
||||
}
|
||||
|
||||
let _ = session.open(&top, PD_MAIN);
|
||||
let all = every_file(&tree);
|
||||
for (path, text, line, needle) in positions(&tree) {
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
let (params, offset) = at(&uri, text, line, needle);
|
||||
let lsp = answered(&tree.path, &session.result(References::METHOD, params));
|
||||
assert_eq!(lsp, engine(&tree.path, &all, &path, offset), "{needle}, widened");
|
||||
}
|
||||
}
|
||||
|
||||
/// `rename`'s fan-out has no gap of its own: over the whole workspace a
|
||||
/// module rename from the testbench edits the generated top too.
|
||||
#[test]
|
||||
fn over_the_whole_workspace_a_module_rename_edits_the_generated_top() {
|
||||
let tree = fixture("refscope_rename");
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let tb = tree.path.join("ip/blk/dv/tb/tb.sv");
|
||||
let uri = session.open(&tb, TB);
|
||||
let (mut params, _) = at(&uri, TB, 2, "blk");
|
||||
params["newName"] = serde_json::json!("blk2");
|
||||
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
|
||||
let changes = answer["changes"].as_object().expect("changes");
|
||||
let top = path_to_uri(&tree.path.join("top/rtl/autogen/top_pd_main.sv")).expect("uri");
|
||||
assert_eq!(changes.get(top.as_str()).and_then(Value::as_array).map_or(0, Vec::len), 1);
|
||||
assert_eq!(changes.len(), 3, "blk.sv, tb.sv and the top: {answer:#}");
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
//! A hierarchical path rooted at a top module another file declares, over
|
||||
//! the wire (TODO §65.4): `references` at a member of the DUT lists every
|
||||
//! segment of `tb.dut.g_sw[0].buf_q` in a DV file, whichever side is open,
|
||||
//! and `rename` rewrites them. `docs/features/top-rooted-paths/README.md`.
|
||||
|
||||
use super::*;
|
||||
|
||||
const DUT: &str = "module dut_a;\n for (genvar i = 0; i < 2; i++) begin : g_sw\n logic buf_q;\n end\nendmodule\n";
|
||||
const TB: &str = "module tb;\n dut_a dut ();\nendmodule\n";
|
||||
const PROBE: &str = "module probe (output logic o);\n assign o = tb.dut.g_sw[0].buf_q;\n initial force tb.dut.g_sw[1].buf_q = 1'b0;\nendmodule\n";
|
||||
|
||||
/// The LSP position of the first `name` on 0-based `line` of `text`.
|
||||
fn at(uri: &Uri, text: &str, line: usize, name: &str) -> Value {
|
||||
let row = text.lines().nth(line).expect("the line");
|
||||
let character = row.find(name).expect("the name on that line");
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": line, "character": character },
|
||||
})
|
||||
}
|
||||
|
||||
/// `(file name, 0-based line)` of every location in a `references` answer.
|
||||
fn places(found: &Value) -> Vec<(String, u64)> {
|
||||
let mut out: Vec<(String, u64)> = found
|
||||
.as_array()
|
||||
.expect("an array")
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let uri = l["uri"].as_str().unwrap_or("?");
|
||||
let name = uri.rsplit('/').next().unwrap_or("?").to_string();
|
||||
(name, l["range"]["start"]["line"].as_u64().unwrap_or(0))
|
||||
})
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// The three-file tree with the named files open; the uris of `dut_a.sv`
|
||||
/// and `probe.sv`.
|
||||
fn session_with(tag: &str, open: &[&str]) -> (Tree, Session, Uri, Uri) {
|
||||
let tree = Tree::new(tag);
|
||||
let files = [("dut_a.sv", DUT), ("tb.sv", TB), ("probe.sv", PROBE)];
|
||||
for (name, text) in files {
|
||||
tree.write(name, text);
|
||||
}
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
for (name, text) in files.into_iter().filter(|(name, _)| open.contains(name)) {
|
||||
session.open(&tree.path.join(name), text);
|
||||
}
|
||||
let uri = |name: &str| path_to_uri(&tree.path.join(name)).expect("a uri");
|
||||
let (dut, probe) = (uri("dut_a.sv"), uri("probe.sv"));
|
||||
(tree, session, dut, probe)
|
||||
}
|
||||
|
||||
fn expected() -> Vec<(String, u64)> {
|
||||
let place = |file: &str, line| (file.to_string(), line);
|
||||
vec![place("dut_a.sv", 2), place("probe.sv", 1), place("probe.sv", 2)]
|
||||
}
|
||||
|
||||
fn references(session: &mut Session, mut params: Value) -> Vec<(String, u64)> {
|
||||
params["context"] = serde_json::json!({ "includeDeclaration": true });
|
||||
places(&session.result(References::METHOD, params))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_at_the_member_list_the_path_in_the_closed_dv_file() {
|
||||
let (_tree, mut session, dut, _) = session_with("toproot_refs_decl", &["dut_a.sv"]);
|
||||
assert_eq!(references(&mut session, at(&dut, DUT, 2, "buf_q")), expected());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_at_the_paths_segment_reach_the_closed_declaration() {
|
||||
let (_tree, mut session, _, probe) = session_with("toproot_refs_path", &["probe.sv"]);
|
||||
assert_eq!(references(&mut session, at(&probe, PROBE, 2, "buf_q")), expected());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_with_both_files_open_are_the_same_set() {
|
||||
let (_tree, mut session, _, probe) =
|
||||
session_with("toproot_refs_both", &["dut_a.sv", "probe.sv"]);
|
||||
assert_eq!(references(&mut session, at(&probe, PROBE, 1, "buf_q")), expected());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_at_the_root_list_every_path_it_heads() {
|
||||
let (_tree, mut session, _, probe) = session_with("toproot_refs_root", &["probe.sv"]);
|
||||
let found = references(&mut session, at(&probe, PROBE, 1, "tb"));
|
||||
let tb = ("tb.sv".to_string(), 0);
|
||||
assert_eq!(found, vec![("probe.sv".to_string(), 1), ("probe.sv".to_string(), 2), tb]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_at_the_block_label_rewrites_the_paths_in_the_dv_file() {
|
||||
let (tree, mut session, dut, _) = session_with("toproot_rename", &["dut_a.sv"]);
|
||||
let mut params = at(&dut, DUT, 1, "g_sw");
|
||||
params["newName"] = serde_json::json!("g_hw");
|
||||
let answer = session.request(Rename::METHOD, params).response_result.expect("renames");
|
||||
let changes = answer["changes"].as_object().expect("changes");
|
||||
let count = |path: &str| {
|
||||
let uri = path_to_uri(&tree.path.join(path)).expect("a uri");
|
||||
changes.get(uri.as_str()).and_then(Value::as_array).map_or(0, Vec::len)
|
||||
};
|
||||
assert_eq!((count("dut_a.sv"), count("probe.sv"), count("tb.sv")), (1, 2, 0), "{answer:#}");
|
||||
let mut texts = changes.values().flat_map(|e| e.as_array().into_iter().flatten());
|
||||
assert!(texts.all(|e| e["newText"] == "g_hw"), "{answer:#}");
|
||||
}
|
||||
@@ -128,7 +128,8 @@ fn references_at_a_nested_blocks_member_reach_the_path_from_another_file() {
|
||||
|
||||
/// QA F1 over the wire: an open buffer is always in the rename's set, so its
|
||||
/// path through the label that resolves to nothing (`tb.u_x.…`, rooted at a
|
||||
/// top module this server cannot resolve) is shown as a warning, unedited.
|
||||
/// top module no file in the tree declares — TODO §65.4 resolves the root
|
||||
/// when one does) is shown as a warning, unedited.
|
||||
#[test]
|
||||
fn an_unresolved_path_in_an_open_buffer_is_shown_as_a_rename_warning() {
|
||||
const PROBE: &str =
|
||||
@@ -147,4 +148,5 @@ fn an_unresolved_path_in_an_open_buffer_is_shown_as_a_rename_warning() {
|
||||
shown.iter().any(|(_, m)| m.contains("probe.sv:2:") && m.contains("`g_lane`")),
|
||||
"{shown:?}"
|
||||
);
|
||||
assert!(!shown.iter().any(|(_, m)| m.contains("more")), "said once: {shown:?}");
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//! A rename through a hierarchical path rooted at a top module, under the
|
||||
//! shipped **folder** scope (top-rooted-paths QA F3): the rename's file set
|
||||
//! holds the files declaring every unit the path walks through — the root
|
||||
//! `tb` and each hop's type — so a three-hop `tb.dut.u_core.sig` is renamed
|
||||
//! exactly as the whole-set engine renames it, from the declaration or from
|
||||
//! the segment. A hop outside the scope leaves the path warned about, and a
|
||||
//! rename from its segment is refused with the accurate reason.
|
||||
|
||||
use super::*;
|
||||
|
||||
const CORE: &str = "module core;\n logic sig;\nendmodule\n";
|
||||
const DUT: &str = "module dut_a;\n core u_core ();\n logic top_sig;\n for (genvar i = 0; i < 2; i++) begin : g_sw\n logic buf_q;\n end\nendmodule\n";
|
||||
const TB: &str = "module tb;\n dut_a dut ();\nendmodule\n";
|
||||
const PROBE: &str = "module probe;\n initial force tb.dut.u_core.sig = 1'b0;\n initial force tb.dut.top_sig = 1'b0;\n initial force tb.dut.g_sw[1].buf_q = 1'b0;\nendmodule\n";
|
||||
|
||||
/// The opentitan shape: `ip/blk/{rtl,dv}`, with `tb.sv` at `tb_at`.
|
||||
fn fixture(tag: &str, tb_at: &str) -> Tree {
|
||||
let tree = Tree::new(tag);
|
||||
tree.write("ip/blk/rtl/core.sv", CORE);
|
||||
tree.write("ip/blk/rtl/dut_a.sv", DUT);
|
||||
tree.write(tb_at, TB);
|
||||
tree.write("ip/blk/dv/probe.sv", PROBE);
|
||||
tree
|
||||
}
|
||||
|
||||
/// The LSP position of the first `name` on 0-based `line` of `text`.
|
||||
fn at(uri: &Uri, text: &str, line: usize, name: &str) -> Value {
|
||||
let row = text.lines().nth(line).expect("the line");
|
||||
let character = row.find(name).expect("the name on that line");
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": line, "character": character },
|
||||
})
|
||||
}
|
||||
|
||||
/// The number of edits a rename answer makes in each of `files`.
|
||||
fn edits(tree: &Tree, answer: &Value, files: &[&str]) -> Vec<usize> {
|
||||
let changes = answer["changes"].as_object().expect("changes");
|
||||
files
|
||||
.iter()
|
||||
.map(|rel| {
|
||||
let uri = path_to_uri(&tree.path.join(rel)).expect("a uri");
|
||||
changes.get(uri.as_str()).and_then(Value::as_array).map_or(0, Vec::len)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn rename(session: &mut Session, mut params: Value, new: &str) -> Result<Value, String> {
|
||||
params["newName"] = serde_json::json!(new);
|
||||
session.request(Rename::METHOD, params).response_result.map_err(|e| format!("{e:?}"))
|
||||
}
|
||||
|
||||
const FILES: [&str; 2] = ["ip/blk/rtl/core.sv", "ip/blk/dv/probe.sv"];
|
||||
|
||||
#[test]
|
||||
fn a_three_hop_path_is_renamed_from_the_declaration() {
|
||||
let tree = fixture("toproot_scope_decl", "ip/blk/dv/tb.sv");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let core = session.open(&tree.path.join(FILES[0]), CORE);
|
||||
let answer = rename(&mut session, at(&core, CORE, 1, "sig"), "sig2").expect("renames");
|
||||
assert_eq!(edits(&tree, &answer, &FILES), vec![1, 1], "{answer:#}");
|
||||
assert!(session.shown().is_empty(), "nothing to warn about: {:?}", session.shown());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_three_hop_path_is_renamed_from_its_segment() {
|
||||
let tree = fixture("toproot_scope_seg", "ip/blk/dv/tb.sv");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let probe = session.open(&tree.path.join(FILES[1]), PROBE);
|
||||
let answer = rename(&mut session, at(&probe, PROBE, 1, "sig"), "sig2").expect("renames");
|
||||
assert_eq!(edits(&tree, &answer, &FILES), vec![1, 1], "{answer:#}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_of_a_generate_block_is_renamed_through_the_path() {
|
||||
let tree = fixture("toproot_scope_block", "ip/blk/dv/tb.sv");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let dut = session.open(&tree.path.join("ip/blk/rtl/dut_a.sv"), DUT);
|
||||
let answer = rename(&mut session, at(&dut, DUT, 4, "buf_q"), "buf_r").expect("renames");
|
||||
let files = ["ip/blk/rtl/dut_a.sv", "ip/blk/dv/probe.sv"];
|
||||
assert_eq!(edits(&tree, &answer, &files), vec![1, 1], "{answer:#}");
|
||||
}
|
||||
|
||||
/// The LSP rename equals the engine's over the scope's files.
|
||||
#[test]
|
||||
fn the_lsp_rename_equals_the_engine_over_the_scope() {
|
||||
let tree = fixture("toproot_scope_engine", "ip/blk/dv/tb.sv");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let core = session.open(&tree.path.join(FILES[0]), CORE);
|
||||
let answer = rename(&mut session, at(&core, CORE, 1, "sig"), "sig2").expect("renames");
|
||||
let sources = session.server.workspace.sources();
|
||||
let path = tree.path.join(FILES[0]);
|
||||
let offset = CORE.find("sig").expect("sig") as u32;
|
||||
let engine = vlog_refactor::rename(&sources, &path, offset, "sig2").expect("engine renames");
|
||||
let lsp = edits(&tree, &answer, &FILES);
|
||||
let whole: Vec<usize> =
|
||||
FILES.iter().map(|rel| engine.edits_for(&tree.path.join(rel)).len()).collect();
|
||||
assert_eq!(lsp, whole);
|
||||
}
|
||||
|
||||
/// `tb.sv` outside the folder scope: the index cannot resolve the root, so
|
||||
/// the open probe's path is left and warned about, and a rename asked from
|
||||
/// its segment is refused for what it is — an unresolved path.
|
||||
#[test]
|
||||
fn a_root_outside_the_scope_is_warned_and_refused_accurately() {
|
||||
let tree = fixture("toproot_scope_out", "top/dv/tb.sv");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let probe = session.open(&tree.path.join(FILES[1]), PROBE);
|
||||
let core = session.open(&tree.path.join(FILES[0]), CORE);
|
||||
let in_index =
|
||||
session.server.workspace.index().files().contains(&tree.path.join("top/dv/tb.sv"));
|
||||
assert!(!in_index, "premise: the root's file is outside the scope");
|
||||
let _ = session.drain();
|
||||
let answer = rename(&mut session, at(&core, CORE, 1, "sig"), "sig2").expect("renames");
|
||||
assert_eq!(edits(&tree, &answer, &FILES), vec![1, 0], "{answer:#}");
|
||||
let shown = session.shown();
|
||||
assert!(shown.iter().any(|(_, m)| m.contains("probe.sv:2:")), "{shown:?}");
|
||||
let why = rename(&mut session, at(&probe, PROBE, 1, "sig"), "sig3").expect_err("refused");
|
||||
assert!(why.contains("hierarchical path"), "{why}");
|
||||
assert!(!why.contains("declared outside"), "{why}");
|
||||
}
|
||||
@@ -121,6 +121,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
|
||||
@@ -246,6 +254,8 @@ impl Default for ClientSettings {
|
||||
uvm_utils_indent: 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,
|
||||
@@ -345,6 +355,8 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
||||
uvm_utils_indent: flag(lucisv.get("format").and_then(|f| f.get("uvmUtilsIndent"))),
|
||||
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.
|
||||
@@ -623,6 +635,8 @@ mod tests {
|
||||
"filelist": "",
|
||||
"inlineTemplates": true,
|
||||
"inlineInstantiation": true,
|
||||
"inlineKeywords": true,
|
||||
"autoEnd": true,
|
||||
"formatOnSave": false,
|
||||
"index": {
|
||||
"maxFileSize": 1048576, "logFiles": true,
|
||||
@@ -838,7 +852,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 +1123,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 +1163,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");
|
||||
}
|
||||
}
|
||||
@@ -281,6 +281,18 @@ impl Workspace {
|
||||
for site in self.index.references_to(def) {
|
||||
wanted.extend(self.index.path(site.file).map(Path::to_path_buf));
|
||||
}
|
||||
// A use written as a hierarchical path (`tb.dut.u_core.sig`) resolves
|
||||
// inside the engine's set only if the set declares every unit the
|
||||
// path walks through — the top module it is rooted at and each hop's
|
||||
// type — so their declaring files come too (top-rooted-paths QA F3).
|
||||
// Only files the index has: a unit outside the scope is not in it,
|
||||
// and the path stays unresolved and warned about.
|
||||
wanted.on(Rung::Declaration);
|
||||
for unit in self.index.path_units_to(def) {
|
||||
for unit_def in self.index.units(&unit) {
|
||||
wanted.extend(self.index.path(unit_def.file).map(Path::to_path_buf));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every file that instantiates a name — the census the reference postings
|
||||
|
||||
@@ -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,283 @@
|
||||
//! TODO §65.2 on a real checkout: `textDocument/references` at the `aes`
|
||||
//! instantiation in `hw/ip/aes/dv/tb/tb.sv` and at its `.clk_i` connection.
|
||||
//!
|
||||
//! Over the whole workspace (`lucisv.index.scope: "workspace"`) the server
|
||||
//! answers what the whole-set engine answers — 14 and 12, the three generated
|
||||
//! `*_pd_main.sv` tops included. Under the shipped folder scope it answers 11
|
||||
//! and 9: the testbench's folder raises two levels to `hw/ip/aes`, and the
|
||||
//! tops are not in the index. Both are pinned, because the difference *is*
|
||||
//! the finding (`docs/features/references-fanout-pd-main/README.md`).
|
||||
//!
|
||||
//! `#[ignore]`: it needs the checkout, which it only reads. Run with
|
||||
//! `LUCISV_OPENTITAN=/path/to/opentitan tools/guard.sh -- cargo test -p
|
||||
//! lucisv_server --test opentitan_references -- --ignored --nocapture`;
|
||||
//! without the variable it looks in `~/.cache/lucisv-eval/ot`, and it skips
|
||||
//! (passing, with a line on stderr) when neither holds the testbench.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::mpsc::{self, Receiver};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// The testbench, relative to the checkout.
|
||||
const TB: &str = "hw/ip/aes/dv/tb/tb.sv";
|
||||
|
||||
/// The three generated tops the folder scope does not reach.
|
||||
const TOPS: [&str; 3] = [
|
||||
"hw/top_darjeeling/rtl/autogen/darjeeling_pd_main.sv",
|
||||
"hw/top_earlgrey/rtl/autogen/earlgrey_pd_main.sv",
|
||||
"hw/top_englishbreakfast/rtl/autogen/englishbreakfast_pd_main.sv",
|
||||
];
|
||||
|
||||
/// The checkout: `LUCISV_OPENTITAN`, else the eval clone; `None` when the
|
||||
/// testbench is not there.
|
||||
fn checkout() -> Option<PathBuf> {
|
||||
let root = std::env::var_os("LUCISV_OPENTITAN").map(PathBuf::from).or_else(|| {
|
||||
std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".cache/lucisv-eval/ot"))
|
||||
})?;
|
||||
root.join(TB).is_file().then_some(root)
|
||||
}
|
||||
|
||||
/// One language server over `root/hw`, with `settings` as its `lucisv`
|
||||
/// section.
|
||||
struct Server {
|
||||
child: Child,
|
||||
stdin: ChildStdin,
|
||||
inbox: Receiver<Value>,
|
||||
settings: Value,
|
||||
next_id: i64,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
fn over(hw: &Path, settings: Value) -> Server {
|
||||
// The persistent cache falls back to the OS cache directory; point it
|
||||
// somewhere a test may write, as `tests/e2e.rs` does.
|
||||
let sandbox =
|
||||
std::env::temp_dir().join(format!("lucisv_server_ot_refs_{}", std::process::id()));
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-server"))
|
||||
.env("HOME", &sandbox)
|
||||
.env("XDG_CACHE_HOME", sandbox.join("cache"))
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.expect("the server binary starts");
|
||||
let stdin = child.stdin.take().expect("stdin");
|
||||
let stdout = BufReader::new(child.stdout.take().expect("stdout"));
|
||||
let (sender, inbox) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let mut stdout = stdout;
|
||||
while let Some(message) = read_message(&mut stdout) {
|
||||
if sender.send(message).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let mut server = Server { child, stdin, inbox, settings, next_id: 0 };
|
||||
let root = uri(hw);
|
||||
server.request(
|
||||
"initialize",
|
||||
json!({
|
||||
"processId": null, "rootUri": root,
|
||||
"workspaceFolders": [{ "uri": root, "name": "hw" }],
|
||||
"capabilities": {
|
||||
"window": { "workDoneProgress": true },
|
||||
"workspace": { "configuration": true },
|
||||
},
|
||||
}),
|
||||
);
|
||||
server.notify("initialized", json!({}));
|
||||
let lucisv = server.settings.clone();
|
||||
server.notify(
|
||||
"workspace/didChangeConfiguration",
|
||||
json!({ "settings": { "lucisv": lucisv } }),
|
||||
);
|
||||
server
|
||||
}
|
||||
|
||||
fn send(&mut self, message: Value) {
|
||||
let payload = message.to_string();
|
||||
write!(self.stdin, "Content-Length: {}\r\n\r\n{payload}", payload.len()).expect("write");
|
||||
self.stdin.flush().expect("flush");
|
||||
}
|
||||
|
||||
fn notify(&mut self, method: &str, params: Value) {
|
||||
self.send(json!({ "jsonrpc": "2.0", "method": method, "params": params }));
|
||||
}
|
||||
|
||||
/// The next message within `wait`, with every request the server makes
|
||||
/// of us answered on the way (`workspace/configuration` with our
|
||||
/// settings, everything else with `null`).
|
||||
fn next(&mut self, wait: Duration) -> Option<Value> {
|
||||
let message = self.inbox.recv_timeout(wait).ok()?;
|
||||
if let (Some(id), Some(method)) = (message.get("id"), message["method"].as_str()) {
|
||||
let result = if method == "workspace/configuration" {
|
||||
let items = message["params"]["items"].as_array().map_or(1, Vec::len);
|
||||
Value::Array(vec![self.settings.clone(); items])
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
let id = id.clone();
|
||||
self.send(json!({ "jsonrpc": "2.0", "id": id, "result": result }));
|
||||
}
|
||||
Some(message)
|
||||
}
|
||||
|
||||
fn request(&mut self, method: &str, params: Value) -> Value {
|
||||
self.next_id += 1;
|
||||
let id = self.next_id;
|
||||
self.send(json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }));
|
||||
let deadline = Instant::now() + Duration::from_secs(600);
|
||||
while Instant::now() < deadline {
|
||||
let Some(message) = self.next(Duration::from_secs(1)) else { continue };
|
||||
if message["id"] == id && message.get("method").is_none() {
|
||||
return message["result"].clone();
|
||||
}
|
||||
}
|
||||
panic!("{method} was not answered");
|
||||
}
|
||||
|
||||
/// Open the testbench and wait until every scan has ended: at least one
|
||||
/// progress `end` after the open, then five quiet seconds with no bar in
|
||||
/// flight (the startup scan, the settings push and the open's widen may
|
||||
/// each run one).
|
||||
fn open_and_settle(&mut self, path: &Path) {
|
||||
let text = std::fs::read_to_string(path).expect("read the testbench");
|
||||
self.notify(
|
||||
"textDocument/didOpen",
|
||||
json!({ "textDocument": {
|
||||
"uri": uri(path), "languageId": "systemverilog", "version": 1, "text": text,
|
||||
}}),
|
||||
);
|
||||
let deadline = Instant::now() + Duration::from_secs(600);
|
||||
let (mut ended, mut in_flight, mut quiet_since) = (false, 0i32, Instant::now());
|
||||
while Instant::now() < deadline {
|
||||
if ended && in_flight <= 0 && quiet_since.elapsed() > Duration::from_secs(5) {
|
||||
return;
|
||||
}
|
||||
let Some(message) = self.next(Duration::from_secs(1)) else { continue };
|
||||
if message["method"] != "$/progress" {
|
||||
continue;
|
||||
}
|
||||
quiet_since = Instant::now();
|
||||
match message["params"]["value"]["kind"].as_str() {
|
||||
Some("begin") => in_flight += 1,
|
||||
Some("end") => {
|
||||
in_flight -= 1;
|
||||
ended = true;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
panic!("the scan never settled");
|
||||
}
|
||||
|
||||
/// `references` at the first `needle` on 1-based `line` of `path`, as
|
||||
/// `file:line` relative to `root`, sorted.
|
||||
fn references(&mut self, root: &Path, path: &Path, line: usize, needle: &str) -> Vec<String> {
|
||||
let text = std::fs::read_to_string(path).expect("read");
|
||||
let row = text.lines().nth(line - 1).expect("the line");
|
||||
let character = row.find(needle).expect("the needle on that line");
|
||||
let found = self.request(
|
||||
"textDocument/references",
|
||||
json!({
|
||||
"textDocument": { "uri": uri(path) },
|
||||
"position": { "line": line - 1, "character": character },
|
||||
"context": { "includeDeclaration": true },
|
||||
}),
|
||||
);
|
||||
let prefix = format!("{}/", uri(root));
|
||||
let mut out: Vec<String> = found
|
||||
.as_array()
|
||||
.expect("an array")
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let file = l["uri"].as_str().unwrap_or("?").replace(&prefix, "");
|
||||
format!("{file}:{}", l["range"]["start"]["line"].as_u64().unwrap_or(0) + 1)
|
||||
})
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Server {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
fn uri(path: &Path) -> String {
|
||||
format!("file://{}", path.display())
|
||||
}
|
||||
|
||||
/// One framed message, or `None` when the stream ends.
|
||||
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()
|
||||
}
|
||||
|
||||
/// The `aes` and `.clk_i` answers of one server over `root/hw`.
|
||||
fn answers(root: &Path, settings: Value) -> (Vec<String>, Vec<String>) {
|
||||
let hw = root.join("hw");
|
||||
let tb = root.join(TB);
|
||||
let mut server = Server::over(&hw, settings);
|
||||
server.open_and_settle(&tb);
|
||||
let module = server.references(root, &tb, 45, "aes");
|
||||
let port = server.references(root, &tb, 50, "clk_i");
|
||||
println!("aes: {} {module:#?}\n.clk_i: {} {port:#?}", module.len(), port.len());
|
||||
(module, port)
|
||||
}
|
||||
|
||||
fn names_a_top(found: &[String], top: &str) -> bool {
|
||||
found.iter().any(|hit| hit.starts_with(&format!("{top}:")))
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs an opentitan checkout (LUCISV_OPENTITAN or ~/.cache/lucisv-eval/ot)"]
|
||||
fn over_the_whole_workspace_references_list_the_three_generated_tops() {
|
||||
let Some(root) = checkout() else {
|
||||
eprintln!("skipped: no opentitan checkout holding {TB}");
|
||||
return;
|
||||
};
|
||||
let (module, port) = answers(&root, json!({ "index": { "scope": "workspace" } }));
|
||||
assert_eq!(module.len(), 14, "aes: {module:#?}");
|
||||
assert_eq!(port.len(), 12, ".clk_i: {port:#?}");
|
||||
for top in TOPS {
|
||||
assert!(names_a_top(&module, top), "aes misses {top}");
|
||||
assert!(names_a_top(&port, top), ".clk_i misses {top}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs an opentitan checkout (LUCISV_OPENTITAN or ~/.cache/lucisv-eval/ot)"]
|
||||
fn under_the_folder_scope_references_stop_at_the_ip_block() {
|
||||
let Some(root) = checkout() else {
|
||||
eprintln!("skipped: no opentitan checkout holding {TB}");
|
||||
return;
|
||||
};
|
||||
let (module, port) = answers(&root, json!({}));
|
||||
assert_eq!(module.len(), 11, "aes: {module:#?}");
|
||||
assert_eq!(port.len(), 9, ".clk_i: {port:#?}");
|
||||
let in_block = |found: &[String]| found.iter().all(|hit| hit.starts_with("hw/ip/aes/"));
|
||||
assert!(in_block(&module) && in_block(&port), "only hw/ip/aes is in scope");
|
||||
}
|
||||
@@ -28,7 +28,7 @@ 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};
|
||||
@@ -62,6 +62,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 +73,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}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,6 +135,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)?;
|
||||
|
||||
@@ -6,8 +6,10 @@ pub mod fence;
|
||||
pub mod format;
|
||||
pub mod printer;
|
||||
pub mod range;
|
||||
mod selection;
|
||||
pub mod verify;
|
||||
|
||||
pub use format::{format_range, format_source, Config, FormatError};
|
||||
pub use range::LineRanges;
|
||||
pub use selection::format_selection;
|
||||
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,238 @@
|
||||
//! 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.
|
||||
///
|
||||
/// Same stack requirement as [`crate::format_source`].
|
||||
pub fn format_selection(
|
||||
source: &str,
|
||||
config: &Config,
|
||||
lines: &LineRanges,
|
||||
) -> Result<String, FormatError> {
|
||||
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,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");
|
||||
}
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,8 +49,8 @@ use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::{is_keyword, TokenKind};
|
||||
use vlog_parser::tokenize;
|
||||
use vlog_semantic::{
|
||||
Def, ExternalResolutions, ExternalTarget, ReferenceId, Resolution, Semantics, Symbol, SymbolId,
|
||||
WorkspaceIndex,
|
||||
Def, ExternalResolutions, ExternalTarget, ReferenceId, Resolution, Semantics, Surface, Symbol,
|
||||
SymbolId, WorkspaceIndex,
|
||||
};
|
||||
|
||||
use crate::trace::RenameTrace;
|
||||
@@ -130,6 +130,7 @@ pub fn prepare_rename_here(
|
||||
Ok(RenameTarget { range: cursor, name: reference.name.clone() })
|
||||
}
|
||||
Some(ExternalTarget::Ambiguous(_)) => Err(ambiguous(&reference.name)),
|
||||
_ if hierarchical(&reference.resolution) => Err(unresolved_path(&reference.name)),
|
||||
_ => Err(declared_outside(&reference.name)),
|
||||
},
|
||||
}
|
||||
@@ -366,7 +367,15 @@ impl<'a> Scope<'a> {
|
||||
return Err(from_base(&name, base))
|
||||
}
|
||||
Resolution::ExternalCandidate { .. } => {
|
||||
Found::Elsewhere(name, cursor, analysis.external.get(id).cloned())
|
||||
let answer = analysis.external.get(id).cloned();
|
||||
let answered = matches!(
|
||||
answer,
|
||||
Some(ExternalTarget::Resolved(_) | ExternalTarget::Ambiguous(_))
|
||||
);
|
||||
if !answered && hierarchical(&reference.resolution) {
|
||||
return Err(unresolved_path(&name));
|
||||
}
|
||||
Found::Elsewhere(name, cursor, answer)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -594,6 +603,22 @@ fn from_base(name: &str, base: &str) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether a use is a segment of a hierarchical path (its candidate reads a
|
||||
/// module's hierarchical surface) — the one external candidate whose miss is
|
||||
/// not "declared outside the indexed files" but "the path did not resolve".
|
||||
fn hierarchical(resolution: &Resolution) -> bool {
|
||||
matches!(resolution, Resolution::ExternalCandidate { surface: Surface::Hierarchical, .. })
|
||||
}
|
||||
|
||||
/// The refusal for a path segment the workspace could not walk to a
|
||||
/// declaration (top-rooted-paths QA F3): a unit the path passes through is
|
||||
/// not in the files lucisv reads, or several files declare it.
|
||||
fn unresolved_path(name: &str) -> String {
|
||||
format!(
|
||||
"`{name}` is a segment of a hierarchical path lucisv could not resolve to one declaration (a unit the path passes through is not among the files lucisv indexes, or is declared more than once); rename the declaration itself."
|
||||
)
|
||||
}
|
||||
|
||||
fn declared_outside(name: &str) -> String {
|
||||
format!(
|
||||
"`{name}` is declared outside the files lucisv indexes, so a rename here would only be half a rename."
|
||||
|
||||
@@ -2,12 +2,20 @@
|
||||
//! loud (generate-label-rename QA F1).
|
||||
//!
|
||||
//! [`Scope::unresolved_path_warnings`]: a segment spelling the renamed name,
|
||||
//! in *any* file of the set, that resolved to no declaration at all
|
||||
//! (`tb.dut.g_sw[0].q`, where `tb` is a top module another file declares and
|
||||
//! nothing resolves the root — TODO §65.4). The rename cannot know whether
|
||||
//! that path reaches the renamed declaration, so it is left unchanged and
|
||||
//! named. A segment that resolved to a *different* declaration is not news
|
||||
//! and is not reported. (The same-label arms are `arms.rs`.)
|
||||
//! in *any* file of the set, that resolved to no declaration at all — no
|
||||
//! reference, or `NotFound` (`tb.dut.g_sw[0].q` where a local `logic tb`
|
||||
//! shadows the top module, so the spine stops at a net). The rename cannot
|
||||
//! know whether that path reaches the renamed declaration, so it is left
|
||||
//! unchanged and named. A segment that resolved to a *different* declaration
|
||||
//! is not news and is not reported. (The same-label arms are `arms.rs`.)
|
||||
//!
|
||||
//! Since TODO §65.4 a path rooted at a top module another file declares
|
||||
//! (`tb.dut.g_sw[0].q`, `$root.tb.…`) resolves when the workspace can walk
|
||||
//! it, and every segment of it is renamed with its declaration. When the
|
||||
//! workspace cannot — the root is declared nowhere, or by several files
|
||||
//! (`tb` in seventy opentitan testbenches) — the segment is an external
|
||||
//! candidate the index left unanswered, and it is named here too: such a
|
||||
//! path is exactly what this scan was written for.
|
||||
//!
|
||||
//! Narrowed by the index's word census and then by a text test for a `.` or
|
||||
//! `[` beside the name, so a file is analysed only when it could hold such a
|
||||
@@ -16,9 +24,9 @@
|
||||
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::tokenize;
|
||||
use vlog_semantic::{Resolution, Semantics};
|
||||
use vlog_semantic::{ExternalResolutions, ExternalTarget, Resolution, Semantics, Surface};
|
||||
|
||||
use crate::scope::Scope;
|
||||
use crate::scope::{Analysis, Scope};
|
||||
|
||||
impl<'a> Scope<'a> {
|
||||
/// One warning per file listing the lines where a path segment spelling
|
||||
@@ -42,8 +50,7 @@ impl<'a> Scope<'a> {
|
||||
let Some(path) = self.path(i) else { continue };
|
||||
let Ok(tokens) = tokenize(text) else { continue };
|
||||
let Some(analysis) = self.analysis(i) else { continue };
|
||||
let lines =
|
||||
unresolved_segments(&analysis.semantics, &tokens, name, edited.contains(&i));
|
||||
let lines = unresolved_segments(analysis, &tokens, name, edited.contains(&i));
|
||||
if lines.is_empty() {
|
||||
continue;
|
||||
}
|
||||
@@ -58,9 +65,16 @@ impl<'a> Scope<'a> {
|
||||
}
|
||||
|
||||
/// The 1-based lines of `name` tokens that are a path segment and resolved to
|
||||
/// nothing: no reference at all (unless `edited`, see the caller), or a
|
||||
/// reference whose resolution is `NotFound`.
|
||||
fn unresolved_segments(sem: &Semantics, tokens: &[Token], name: &str, edited: bool) -> Vec<u32> {
|
||||
/// nothing: no reference at all (unless `edited`, see the caller), a
|
||||
/// reference whose resolution is `NotFound`, or a segment of a top-rooted
|
||||
/// path the workspace left unanswered ([`top_rooted_miss`]).
|
||||
fn unresolved_segments(
|
||||
analysis: &Analysis,
|
||||
tokens: &[Token],
|
||||
name: &str,
|
||||
edited: bool,
|
||||
) -> Vec<u32> {
|
||||
let sem = &analysis.semantics;
|
||||
let mut lines: Vec<u32> = Vec::new();
|
||||
for (i, token) in tokens.iter().enumerate() {
|
||||
if token.kind != TokenKind::Ident || token.text != name || !is_segment(tokens, i) {
|
||||
@@ -70,7 +84,13 @@ fn unresolved_segments(sem: &Semantics, tokens: &[Token], name: &str, edited: bo
|
||||
continue;
|
||||
}
|
||||
let unresolved = match sem.reference_at(token.span.start) {
|
||||
Some(r) if r.name_span == token.span => matches!(r.resolution, Resolution::NotFound),
|
||||
Some(r) if r.name_span == token.span => match r.resolution {
|
||||
Resolution::NotFound => true,
|
||||
Resolution::ExternalCandidate { surface: Surface::Hierarchical, .. } => {
|
||||
top_rooted_miss(sem, &analysis.external, tokens, i)
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
_ => !edited,
|
||||
};
|
||||
if unresolved && lines.last() != Some(&token.line) {
|
||||
@@ -80,6 +100,75 @@ fn unresolved_segments(sem: &Semantics, tokens: &[Token], name: &str, edited: bo
|
||||
lines
|
||||
}
|
||||
|
||||
/// Whether this scan names the use whose name starts at `offset`: a path
|
||||
/// segment of a top-rooted path the workspace left unanswered. Asked by
|
||||
/// `warnings.rs`'s unresolved-candidate scan, which skips such a use so each
|
||||
/// line is said once, in this scan's words (Handshake H1, lead-granted).
|
||||
pub(super) fn names_top_rooted_miss(analysis: &Analysis, tokens: &[Token], offset: u32) -> bool {
|
||||
let Ok(i) = tokens.binary_search_by_key(&offset, |t| t.span.start) else { return false };
|
||||
is_segment(tokens, i) && top_rooted_miss(&analysis.semantics, &analysis.external, tokens, i)
|
||||
}
|
||||
|
||||
/// Whether the segment at `i` is part of a path rooted at a top-level module
|
||||
/// — its head is `$root`, or a name this file does not declare, which the
|
||||
/// semantic layer records as a candidate for the unit table on the
|
||||
/// hierarchical surface — **and** the workspace answered the segment with
|
||||
/// nothing. An ambiguous answer is not this scan's: when it can name the
|
||||
/// renamed declaration the rename is refused outright, and when it cannot,
|
||||
/// the path is another declaration's.
|
||||
fn top_rooted_miss(
|
||||
sem: &Semantics,
|
||||
external: &ExternalResolutions,
|
||||
tokens: &[Token],
|
||||
i: usize,
|
||||
) -> bool {
|
||||
let answered = sem.reference_id_at(tokens[i].span.start).and_then(|id| external.get(id));
|
||||
if !matches!(answered, Some(ExternalTarget::StillUnresolved)) {
|
||||
return false;
|
||||
}
|
||||
let Some(head) = path_head(tokens, i) else { return false };
|
||||
if head.text == "$root" {
|
||||
return true;
|
||||
}
|
||||
match sem.reference_at(head.span.start) {
|
||||
Some(r) if r.name_span == head.span => matches!(
|
||||
&r.resolution,
|
||||
Resolution::ExternalCandidate { surface: Surface::Hierarchical, paths }
|
||||
if paths.last().is_some_and(|last| *last == head.text)
|
||||
),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The first token of the dotted path the identifier at `i` is a segment of:
|
||||
/// back over each `.` and the element selects before it (`g[0][k].x`).
|
||||
fn path_head(tokens: &[Token], mut i: usize) -> Option<&Token> {
|
||||
while i >= 2 && tokens[i - 1].is_sym(".") {
|
||||
let mut j = i - 2;
|
||||
while tokens[j].is_sym("]") {
|
||||
j = matching_open(tokens, j)?.checked_sub(1)?;
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
tokens.get(i)
|
||||
}
|
||||
|
||||
/// The `[` that opens the `]` at `close`.
|
||||
fn matching_open(tokens: &[Token], close: usize) -> Option<usize> {
|
||||
let mut depth = 0usize;
|
||||
for j in (0..=close).rev() {
|
||||
if tokens[j].is_sym("]") {
|
||||
depth += 1;
|
||||
} else if tokens[j].is_sym("[") {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
return Some(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether the identifier at `i` is one segment of a dotted path: a `.`
|
||||
/// before it, or a `.` after it past any element selects (`g[0][1].x`).
|
||||
fn is_segment(tokens: &[Token], i: usize) -> bool {
|
||||
|
||||
@@ -21,11 +21,12 @@ use vlog_parser::defines::DefineKind;
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::{tokenize, LineIndex};
|
||||
use vlog_semantic::{ExternalTarget, ReferenceId, Resolution};
|
||||
use vlog_semantic::{ExternalTarget, ReferenceId, Resolution, Surface};
|
||||
|
||||
use crate::TextEdit;
|
||||
|
||||
use super::carry::argument_position;
|
||||
use super::paths;
|
||||
use super::scoped::{binds_into, spellings, Scoping};
|
||||
use super::Target;
|
||||
use crate::scope::Scope;
|
||||
@@ -524,10 +525,9 @@ impl<'a> Scope<'a> {
|
||||
return Vec::new();
|
||||
}
|
||||
let where_ = self.name_of(path);
|
||||
let lines = scan.lines(text);
|
||||
let Some(analysis) = self.analysis(file) else { return Vec::new() };
|
||||
// Unit that could not be found → the lines it was named on.
|
||||
let mut groups: Vec<(String, Vec<u32>)> = Vec::new();
|
||||
// The unanswered candidates: (unit, offset, on the hierarchical surface).
|
||||
let mut hits: Vec<(String, u32, bool)> = Vec::new();
|
||||
for (i, reference) in analysis.semantics.references().iter().enumerate() {
|
||||
if reference.name != name {
|
||||
continue;
|
||||
@@ -542,7 +542,29 @@ impl<'a> Scope<'a> {
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
let line = lines.line_col(reference.name_span.start).0;
|
||||
let hierarchical = matches!(
|
||||
reference.resolution,
|
||||
Resolution::ExternalCandidate { surface: Surface::Hierarchical, .. }
|
||||
);
|
||||
hits.push((unit, reference.name_span.start, hierarchical));
|
||||
}
|
||||
// A segment of a top-rooted path is the §65.1 path scan's to name
|
||||
// (`paths.rs`); naming it here too would say the line twice. Lexed
|
||||
// only when a hierarchical candidate could be one.
|
||||
let (tokens, lines) = if hits.iter().any(|(_, _, h)| *h) {
|
||||
scan.tokens_and_lines(text)
|
||||
} else {
|
||||
(None, scan.lines(text))
|
||||
};
|
||||
// Unit that could not be found → the lines it was named on.
|
||||
let mut groups: Vec<(String, Vec<u32>)> = Vec::new();
|
||||
for (unit, offset, hierarchical) in hits {
|
||||
let path_line = hierarchical
|
||||
&& tokens.is_some_and(|t| paths::names_top_rooted_miss(analysis, t, offset));
|
||||
if path_line {
|
||||
continue;
|
||||
}
|
||||
let line = lines.line_col(offset).0;
|
||||
match groups.iter_mut().find(|(u, _)| *u == unit) {
|
||||
Some((_, at)) => at.push(line),
|
||||
None => groups.push((unit, vec![line])),
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
//! TODO §65.4 on a real checkout: `rename keymgr_dpe.gen_sw_assigns`, whose
|
||||
//! DV interface writes `force tb.dut.gen_sw_assigns[i]…` (a path rooted at a
|
||||
//! top module another file declares, IEEE 1800 §23.6).
|
||||
//!
|
||||
//! Two file sets, because the answer depends on how many `module tb` the set
|
||||
//! holds (`docs/features/top-rooted-paths/README.md`):
|
||||
//!
|
||||
//! * **the IP folder** `hw/ip/keymgr_dpe` — what the language server indexes
|
||||
//! under its shipped folder scope for a file there. One `tb`; but the
|
||||
//! interface imports `uvm_pkg::*` and `keymgr_dpe_env_pkg::*`, either of
|
||||
//! which could supply `tb` by the LRM (and `uvm_pkg` is not in the tree),
|
||||
//! so the head is not provably the top module and the path is left and
|
||||
//! named (the rework after QA, F2).
|
||||
//! * **the whole `hw` tree** — what `lucisv-mcp` hands the engine. Seventy
|
||||
//! files declare `module tb`, so `tb.dut` names seventy instances and the
|
||||
//! path resolves to nothing; the rename leaves it and says so.
|
||||
//!
|
||||
//! `#[ignore]`: it needs the checkout, which it only reads — the edit is
|
||||
//! computed, never applied. Run with `LUCISV_OPENTITAN=/path/to/opentitan
|
||||
//! tools/guard.sh -- cargo test -p vlog_refactor --test opentitan_top_rooted
|
||||
//! -- --ignored --nocapture`; without the variable it looks in
|
||||
//! `~/.cache/lucisv-eval/ot`, and it skips (passing, with a line on stderr)
|
||||
//! when neither holds the IP.
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Instant;
|
||||
|
||||
use vlog_refactor::rename;
|
||||
|
||||
const RTL: &str = "hw/ip/keymgr_dpe/rtl/keymgr_dpe.sv";
|
||||
const IF: &str = "hw/ip/keymgr_dpe/dv/env/keymgr_dpe_if.sv";
|
||||
|
||||
fn checkout() -> Option<PathBuf> {
|
||||
let root = std::env::var_os("LUCISV_OPENTITAN").map(PathBuf::from).or_else(|| {
|
||||
std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".cache/lucisv-eval/ot"))
|
||||
})?;
|
||||
root.join(RTL).is_file().then_some(root)
|
||||
}
|
||||
|
||||
/// Every `.sv`/`.svh`/`.v` file under `dir`, with its text, path-sorted.
|
||||
fn sources(dir: &Path) -> Vec<(PathBuf, String)> {
|
||||
let mut out = Vec::new();
|
||||
let mut stack = vec![dir.to_path_buf()];
|
||||
while let Some(d) = stack.pop() {
|
||||
let Ok(entries) = fs::read_dir(&d) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
stack.push(path);
|
||||
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "svh" | "v"))
|
||||
{
|
||||
if let Ok(text) = fs::read_to_string(&path) {
|
||||
out.push((path, text));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// The rename over one set: the 1-based lines it edits in the interface file,
|
||||
/// how many sites in how many files, and the warnings naming the interface.
|
||||
fn probe(root: &Path, set: &str) -> (Vec<usize>, usize, usize, Vec<String>) {
|
||||
let files = sources(&root.join(set));
|
||||
let rtl = root.join(RTL);
|
||||
let text = &files.iter().find(|(p, _)| *p == rtl).expect("the rtl is in the set").1;
|
||||
let offset = text.find("begin : gen_sw_assigns").expect("the label") + "begin : ".len();
|
||||
let started = Instant::now();
|
||||
let edit = rename(&files, &rtl, offset as u32, "gen_sw_asg").expect("renames");
|
||||
let took = started.elapsed();
|
||||
let iface = root.join(IF);
|
||||
let if_text = &files.iter().find(|(p, _)| *p == iface).expect("the interface").1;
|
||||
let lines: Vec<usize> = edit
|
||||
.edits_for(&iface)
|
||||
.iter()
|
||||
.map(|e| if_text[..e.range.start as usize].matches('\n').count() + 1)
|
||||
.collect();
|
||||
let touched: Vec<&PathBuf> =
|
||||
files.iter().map(|(p, _)| p).filter(|p| !edit.edits_for(p).is_empty()).collect();
|
||||
let sites: usize = touched.iter().map(|p| edit.edits_for(p).len()).sum();
|
||||
let warned: Vec<String> =
|
||||
edit.warnings.iter().filter(|w| w.contains("keymgr_dpe_if.sv")).cloned().collect();
|
||||
eprintln!(
|
||||
"{set}: {} files, {sites} sites in {} files, {} warnings ({} naming the interface), {took:.2?}",
|
||||
files.len(),
|
||||
touched.len(),
|
||||
edit.warnings.len(),
|
||||
warned.len()
|
||||
);
|
||||
for w in &edit.warnings {
|
||||
eprintln!(" warning: {w}");
|
||||
}
|
||||
(lines, sites, touched.len(), warned)
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs an opentitan checkout"]
|
||||
fn the_ip_folder_leaves_the_imported_head_and_says_so() {
|
||||
let Some(root) = checkout() else {
|
||||
eprintln!("skipped: no opentitan checkout");
|
||||
return;
|
||||
};
|
||||
let (lines, _, _, warned) = probe(&root, "hw/ip/keymgr_dpe");
|
||||
assert!(lines.is_empty(), "an import could supply `tb`: {lines:?}");
|
||||
let said: Vec<&String> = warned.iter().filter(|w| w.contains("514")).collect();
|
||||
assert_eq!(said.len(), 1, "the force lines are said once: {warned:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs an opentitan checkout"]
|
||||
fn the_whole_tree_leaves_the_ambiguous_root_and_says_so() {
|
||||
let Some(root) = checkout() else {
|
||||
eprintln!("skipped: no opentitan checkout");
|
||||
return;
|
||||
};
|
||||
let (lines, _, _, warned) = probe(&root, "hw");
|
||||
assert!(lines.is_empty(), "seventy `tb`s: the path names nothing: {lines:?}");
|
||||
let said: Vec<&String> = warned.iter().filter(|w| w.contains("514")).collect();
|
||||
assert_eq!(said.len(), 1, "the force lines are said once: {warned:?}");
|
||||
}
|
||||
|
||||
/// The index cost of the extra external references: the facts every file
|
||||
/// records (encoded bytes — the persistent store's size), the reference
|
||||
/// postings the merge resolves them into, and the wall time of the build,
|
||||
/// best of three. Prints only; the before/after is the feature README's.
|
||||
#[test]
|
||||
#[ignore = "needs an opentitan checkout"]
|
||||
fn index_cost_over_the_whole_tree() {
|
||||
let Some(root) = checkout() else {
|
||||
eprintln!("skipped: no opentitan checkout");
|
||||
return;
|
||||
};
|
||||
let files = sources(&root.join("hw"));
|
||||
let bytes: usize = files
|
||||
.iter()
|
||||
.map(|(p, t)| vlog_semantic::FileFacts::of(p.clone(), t).encode().map_or(0, |s| s.len()))
|
||||
.sum();
|
||||
let mut best: Option<std::time::Duration> = None;
|
||||
let mut sizes = None;
|
||||
for _ in 0..3 {
|
||||
let started = Instant::now();
|
||||
let index = vlog_semantic::WorkspaceIndex::build(
|
||||
files.iter().map(|(p, t)| (p.clone(), t.as_str())),
|
||||
);
|
||||
let took = started.elapsed();
|
||||
best = Some(best.map_or(took, |b| b.min(took)));
|
||||
sizes = Some(index.table_sizes());
|
||||
}
|
||||
eprintln!(
|
||||
"index over {} files: facts {bytes} bytes, {sizes:?}, build best of 3 {best:.2?}",
|
||||
files.len()
|
||||
);
|
||||
}
|
||||
@@ -529,15 +529,15 @@ endmodule
|
||||
let files = [("dut_a.sv", dut), ("tb.sv", tb), ("probe.sv", probe)];
|
||||
complete_or_loud(&renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw"), "g_sw");
|
||||
complete_or_loud(&renamed(&files, "dut_a.sv", "logic ", "buf_q", "buf_r"), "buf_q");
|
||||
// Lead's ruling on F1: the path rooted at another file's top module does
|
||||
// not resolve, so it is left unchanged — and said so, with its line.
|
||||
// TODO §65.4 (superseding the lead's F1 ruling, which warned): the root
|
||||
// `tb` is the top module `tb.sv` declares (IEEE 1800 §23.6), so the path
|
||||
// resolves and is renamed with the declaration — and nothing is warned.
|
||||
for (prefix, old, new) in [("begin : ", "g_sw", "g_hw"), ("logic ", "buf_q", "buf_r")] {
|
||||
let (texts, warnings) = renamed(&files, "dut_a.sv", prefix, old, new).expect("renames");
|
||||
assert_eq!(texts[0], dut.replace(old, new), "the declaration moves");
|
||||
assert_eq!((texts[1].as_str(), texts[2].as_str()), (tb, probe), "nothing else is edited");
|
||||
let said: Vec<&String> = warnings.iter().filter(|w| w.contains("probe.sv:2:")).collect();
|
||||
assert_eq!(said.len(), 1, "one warning for the unresolved path: {warnings:?}");
|
||||
assert!(said[0].contains(&format!("`{old}`")), "{said:?}");
|
||||
assert_eq!(texts[1], tb, "the testbench does not spell the name");
|
||||
assert_eq!(texts[2], probe.replace(old, new), "the path moves with it");
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -619,16 +619,48 @@ fn rc_files() -> Vec<(&'static str, &'static str)> {
|
||||
vec![("dut_a.sv", RC_DUT), ("dut_b.sv", RC_OTHER), ("tb.sv", RC_TB), ("probe.sv", RC_PROBE)]
|
||||
}
|
||||
|
||||
/// The set without `tb.sv`: nothing declares the root `tb`, so no path
|
||||
/// rooted at it can resolve (TODO §65.4 — with `tb.sv` in the set they do).
|
||||
fn rc_files_without_the_root() -> Vec<(&'static str, &'static str)> {
|
||||
rc_files().into_iter().filter(|(name, _)| *name != "tb.sv").collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recheck_every_unresolved_path_shape_is_named_once_with_its_lines() {
|
||||
let (texts, warnings) =
|
||||
renamed(&rc_files(), "dut_a.sv", "begin : ", "g_sw", "g_hw").expect("renames");
|
||||
assert_eq!(texts[3], RC_PROBE, "the probe is never edited");
|
||||
renamed(&rc_files_without_the_root(), "dut_a.sv", "begin : ", "g_sw", "g_hw")
|
||||
.expect("renames");
|
||||
assert_eq!(texts[2], RC_PROBE, "the probe is never edited");
|
||||
let said: Vec<&String> = warnings.iter().filter(|w| w.contains("probe.sv")).collect();
|
||||
assert_eq!(said.len(), 1, "one line for the file: {warnings:?}");
|
||||
assert!(said[0].starts_with("probe.sv:2,3,4,6:"), "{said:?}");
|
||||
}
|
||||
|
||||
/// TODO §65.4: with the root declared, every path shape is renamed and the
|
||||
/// comment, the string and the connection to an unknown module are not.
|
||||
#[test]
|
||||
fn every_path_shape_rooted_at_a_declared_top_module_is_renamed() {
|
||||
let (texts, warnings) =
|
||||
renamed(&rc_files(), "dut_a.sv", "begin : ", "g_sw", "g_hw").expect("renames");
|
||||
let code: Vec<&str> = RC_PROBE.lines().collect();
|
||||
let want: Vec<String> = code
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(
|
||||
|(i, l)| {
|
||||
if [1, 2, 3, 5].contains(&i) {
|
||||
l.replace("g_sw", "g_hw")
|
||||
} else {
|
||||
l.to_string()
|
||||
}
|
||||
},
|
||||
)
|
||||
.collect();
|
||||
assert_eq!(texts[3], want.join("\n") + "\n");
|
||||
assert_eq!(texts[1], RC_OTHER, "`dut_b`'s block is another declaration");
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recheck_a_path_that_resolves_to_another_declaration_is_not_warned_about() {
|
||||
let user = "module user (output logic o);
|
||||
@@ -646,11 +678,17 @@ endmodule
|
||||
fn recheck_an_included_fragment_is_scanned_like_any_file() {
|
||||
let frag = " initial force tb.dut.g_sw[0].buf_q = 1'b1;\n";
|
||||
let host = "module host;\n`include \"frag.svh\"\nendmodule\n";
|
||||
let mut files = rc_files();
|
||||
let mut files = rc_files_without_the_root();
|
||||
files.push(("frag.svh", frag));
|
||||
files.push(("host.sv", host));
|
||||
let (_, warnings) = renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw").expect("renames");
|
||||
assert!(warnings.iter().any(|w| w.starts_with("frag.svh:1:")), "{warnings:?}");
|
||||
// TODO §65.4: with the root declared, the fragment's path is renamed.
|
||||
let mut files = rc_files();
|
||||
files.push(("frag.svh", frag));
|
||||
files.push(("host.sv", host));
|
||||
let (texts, _) = renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw").expect("renames");
|
||||
assert_eq!(texts[4], frag.replace("g_sw", "g_hw"));
|
||||
}
|
||||
|
||||
/// The word census holds no escaped identifier (`words.rs`: "an escaped
|
||||
@@ -660,11 +698,17 @@ fn recheck_an_escaped_label_behind_an_unresolved_root_is_named() {
|
||||
let dut = "module dut_e;\n if (1) begin : \\g$sw \n logic q;\n end\nendmodule\n";
|
||||
let tb = "module tbe;\n dut_e dut ();\nendmodule\n";
|
||||
let probe = "module pe (output logic o);\n assign o = tbe.dut.\\g$sw .q;\nendmodule\n";
|
||||
let files = [("dut_e.sv", dut), ("tbe.sv", tb), ("pe.sv", probe)];
|
||||
// Without `tbe.sv` nothing declares the root, and the path is named.
|
||||
let files = [("dut_e.sv", dut), ("pe.sv", probe)];
|
||||
let result = renamed(&files, "dut_e.sv", "begin : ", "\\g$sw", "g_hw");
|
||||
complete_or_loud(&result, "\\g$sw");
|
||||
let (_, warnings) = result.expect("renames");
|
||||
assert!(warnings.iter().any(|w| w.starts_with("pe.sv:2:")), "{warnings:?}");
|
||||
// TODO §65.4: with it, the escaped segment is renamed.
|
||||
let files = [("dut_e.sv", dut), ("tbe.sv", tb), ("pe.sv", probe)];
|
||||
let (texts, warnings) =
|
||||
renamed(&files, "dut_e.sv", "begin : ", "\\g$sw", "g_hw").expect("renames");
|
||||
assert_eq!(texts[2], probe.replace("\\g$sw", "g_hw"), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -175,17 +175,16 @@ endmodule
|
||||
}
|
||||
|
||||
/// Rework 2, R1: three files named `probe.sv` at different depths, each with
|
||||
/// an unresolved path — each warning must name a findable file.
|
||||
/// an unresolved path — each warning must name a findable file. (Since TODO
|
||||
/// §65.4 a root some file declares resolves, so the set declares no `tb`.)
|
||||
#[test]
|
||||
fn recheck_three_same_named_files_are_each_named_by_their_path() {
|
||||
let dut = "module dut_a;\n for (genvar i = 0; i < 2; i++) begin : g_sw\n logic q;\n end\nendmodule\n";
|
||||
let tb = "module tb;\n dut_a dut ();\nendmodule\n";
|
||||
let probe = "module PROBE (output logic o);\n assign o = tb.dut.g_sw[0].q;\nendmodule\n";
|
||||
let (p1, p2, p3) =
|
||||
(probe.replace("PROBE", "p1"), probe.replace("PROBE", "p2"), probe.replace("PROBE", "p3"));
|
||||
let files = [
|
||||
("dut_a.sv", dut),
|
||||
("tb.sv", tb),
|
||||
("probe.sv", p1.as_str()),
|
||||
("x/probe.sv", p2.as_str()),
|
||||
("x/y/z/probe.sv", p3.as_str()),
|
||||
@@ -250,17 +249,22 @@ endmodule
|
||||
}
|
||||
}
|
||||
|
||||
/// Rework 2, R2: an escaped net and an escaped label behind an unresolved root.
|
||||
/// Rework 2, R2: an escaped net and an escaped label behind an unresolved root
|
||||
/// — no file declares `tbe` — and, since TODO §65.4, renamed behind one that
|
||||
/// is declared.
|
||||
#[test]
|
||||
fn recheck_escaped_net_and_label_paths_are_named() {
|
||||
let dut = "module dut_e;\n logic \\n$q ;\n if (1) begin : \\g$sw \n logic q;\n end\nendmodule\n";
|
||||
let tb = "module tbe;\n dut_e dut ();\nendmodule\n";
|
||||
let probe = "module pe (output logic o, output logic p);\n assign o = tbe.dut.\\g$sw .q;\n assign p = tbe.dut.\\n$q ;\nendmodule\n";
|
||||
let files = [("dut_e.sv", dut), ("tbe.sv", tb), ("pe.sv", probe)];
|
||||
let files = [("dut_e.sv", dut), ("pe.sv", probe)];
|
||||
let (_, warnings) = run(&files, "dut_e.sv", "begin : ", "\\g$sw", "g_hw").expect("label");
|
||||
assert!(warnings.iter().any(|w| w.starts_with("pe.sv:2:")), "{warnings:#?}");
|
||||
let (_, warnings) = run(&files, "dut_e.sv", "logic ", "\\n$q", "n_q").expect("net");
|
||||
assert!(warnings.iter().any(|w| w.starts_with("pe.sv:3:")), "{warnings:#?}");
|
||||
let files = [("dut_e.sv", dut), ("tbe.sv", tb), ("pe.sv", probe)];
|
||||
let (texts, warnings) = run(&files, "dut_e.sv", "logic ", "\\n$q", "n_q").expect("net");
|
||||
assert_eq!(texts[2], probe.replace("\\n$q", "n_q"), "{warnings:#?}");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -258,7 +258,9 @@ endmodule
|
||||
let files = workspace(&[("m.sv", text)]);
|
||||
let why =
|
||||
rename(&files, &path("m.sv"), at(text, "o = ", "genblk1"), "g_x").expect_err("refused");
|
||||
assert!(why.contains("not resolved"), "{why}");
|
||||
// Since TODO §65.4 `genblk1.` heads a path rooted at a top module no
|
||||
// file declares — refused all the same, never this file's unnamed block.
|
||||
assert!(why.contains("not resolved") || why.contains("hierarchical path"), "{why}");
|
||||
assert!(prepare_rename(&files, &path("m.sv"), at(text, "o = ", "genblk1")).is_err());
|
||||
}
|
||||
|
||||
@@ -351,6 +353,7 @@ fn an_unresolved_path_through_the_name_warns_and_a_path_to_another_declaration_d
|
||||
renamed(&files, "sub.sv", "logic ", "state_q", "state_r").expect("renames");
|
||||
assert_eq!(texts[2], top.replace("u_x.state_q", "u_x.state_r"));
|
||||
assert_eq!((texts[1].as_str(), texts[3].as_str()), (other, probe));
|
||||
// `tb` is declared nowhere (TODO §65.4 resolves it when it is).
|
||||
assert_eq!(warnings.len(), 1, "{warnings:?}");
|
||||
assert!(warnings[0].starts_with("probe.sv:2,3,4: "), "{warnings:?}");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,343 @@
|
||||
//! TODO §65.4: `find_references` and `rename` through a hierarchical path
|
||||
//! rooted at a top-level module another file declares (`tb.dut.g_sw[0].q`,
|
||||
//! the opentitan DV `force` shape; IEEE 1800 §23.6), and `$root.tb.…`.
|
||||
//! `docs/features/top-rooted-paths/README.md`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_refactor::{find_references, rename, RefactorEdit};
|
||||
|
||||
const DUT: &str = "module dut_a;
|
||||
for (genvar i = 0; i < 2; i++) begin : g_sw
|
||||
logic buf_q;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
const TB: &str = "module tb;
|
||||
dut_a dut ();
|
||||
endmodule
|
||||
";
|
||||
const PROBE: &str = "module probe (output logic o);
|
||||
assign o = tb.dut.g_sw[0].buf_q;
|
||||
initial force tb.dut.g_sw[1].buf_q = 1'b0;
|
||||
initial release $root.tb.dut.g_sw[1].buf_q;
|
||||
endmodule
|
||||
";
|
||||
|
||||
fn path(name: &str) -> PathBuf {
|
||||
PathBuf::from("/rtl").join(name)
|
||||
}
|
||||
|
||||
fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
|
||||
files.iter().map(|(name, text)| (path(name), text.to_string())).collect()
|
||||
}
|
||||
|
||||
/// The offset of the first `name` after `prefix`.
|
||||
fn at(text: &str, prefix: &str, name: &str) -> u32 {
|
||||
let from = text.find(prefix).unwrap_or_else(|| panic!("`{prefix}` is not in the text"));
|
||||
let from = from + prefix.len();
|
||||
(from + text[from..].find(name).expect("the name after the prefix")) as u32
|
||||
}
|
||||
|
||||
fn apply(text: &str, edit: &RefactorEdit, file: &Path) -> String {
|
||||
let mut out = String::new();
|
||||
let mut cursor = 0usize;
|
||||
for e in edit.edits_for(file) {
|
||||
out.push_str(&text[cursor..e.range.start as usize]);
|
||||
out.push_str(&e.new_text);
|
||||
cursor = e.range.end as usize;
|
||||
}
|
||||
out.push_str(&text[cursor..]);
|
||||
out
|
||||
}
|
||||
|
||||
/// Every file's text after renaming the `name` after `prefix` in `file`, and
|
||||
/// the warnings.
|
||||
fn renamed(
|
||||
files: &[(&str, &str)],
|
||||
file: &str,
|
||||
prefix: &str,
|
||||
name: &str,
|
||||
new: &str,
|
||||
) -> (Vec<String>, Vec<String>) {
|
||||
let text = files.iter().find(|(n, _)| *n == file).map(|(_, t)| *t).expect("the file");
|
||||
let edit = rename(&workspace(files), &path(file), at(text, prefix, name), new)
|
||||
.unwrap_or_else(|why| panic!("rename refused: {why}"));
|
||||
let texts = files.iter().map(|(n, t)| apply(t, &edit, &path(n))).collect();
|
||||
(texts, edit.warnings)
|
||||
}
|
||||
|
||||
/// `file:line` of every reference to the `name` after `prefix`, sorted.
|
||||
fn references(files: &[(&str, &str)], file: &str, prefix: &str, name: &str) -> Vec<String> {
|
||||
let text = files.iter().find(|(n, _)| *n == file).map(|(_, t)| *t).expect("the file");
|
||||
let found = find_references(&workspace(files), &path(file), at(text, prefix, name), true)
|
||||
.unwrap_or_else(|why| panic!("find_references refused: {why}"));
|
||||
let mut out: Vec<String> = found
|
||||
.iter()
|
||||
.map(|(p, span)| {
|
||||
let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("?");
|
||||
let text = files.iter().find(|(n, _)| *n == name).map(|(_, t)| *t).expect("file");
|
||||
assert_eq!(&text[span.as_range()], ident_at(text, span.start));
|
||||
format!("{name}:{}", text[..span.start as usize].matches('\n').count() + 1)
|
||||
})
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// The identifier starting at `start` — what a reference span must slice.
|
||||
fn ident_at(text: &str, start: u32) -> &str {
|
||||
let rest = &text[start as usize..];
|
||||
let end = rest.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).unwrap_or(rest.len());
|
||||
&rest[..end]
|
||||
}
|
||||
|
||||
fn files() -> Vec<(&'static str, &'static str)> {
|
||||
vec![("dut_a.sv", DUT), ("tb.sv", TB), ("probe.sv", PROBE)]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_references_lists_every_segment_of_a_top_rooted_path() {
|
||||
let files = files();
|
||||
let want = ["dut_a.sv:2", "probe.sv:2", "probe.sv:3", "probe.sv:4"];
|
||||
assert_eq!(references(&files, "dut_a.sv", "begin : ", "g_sw"), want);
|
||||
let want = ["dut_a.sv:3", "probe.sv:2", "probe.sv:3", "probe.sv:4"];
|
||||
assert_eq!(references(&files, "dut_a.sv", "logic ", "buf_q"), want);
|
||||
let want = ["probe.sv:2", "probe.sv:3", "probe.sv:4", "tb.sv:2"];
|
||||
assert_eq!(references(&files, "tb.sv", "dut_a ", "dut"), want);
|
||||
let want = ["probe.sv:2", "probe.sv:3", "probe.sv:4", "tb.sv:1"];
|
||||
assert_eq!(references(&files, "tb.sv", "module ", "tb"), want, "the root itself");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_a_member_rewrites_the_path_and_warns_about_nothing() {
|
||||
let files = files();
|
||||
for (prefix, old, new) in [("begin : ", "g_sw", "g_hw"), ("logic ", "buf_q", "buf_r")] {
|
||||
let (texts, warnings) = renamed(&files, "dut_a.sv", prefix, old, new);
|
||||
assert_eq!(texts[0], DUT.replace(old, new));
|
||||
assert_eq!(texts[1], TB);
|
||||
assert_eq!(texts[2], PROBE.replace(old, new));
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_the_instance_or_the_top_module_rewrites_its_segment() {
|
||||
let files = files();
|
||||
let (texts, warnings) = renamed(&files, "tb.sv", "dut_a ", "dut", "u_dut");
|
||||
assert_eq!(texts[1], TB.replace(" dut ", " u_dut "));
|
||||
assert_eq!(texts[2], PROBE.replace("tb.dut.", "tb.u_dut."));
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
let (texts, warnings) = renamed(&files, "tb.sv", "module ", "tb", "top_tb");
|
||||
assert_eq!(texts[1], TB.replace("module tb", "module top_tb"));
|
||||
assert_eq!(texts[2], PROBE.replace("tb.dut.", "top_tb.dut."));
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// The rename can be asked from the path itself, at any segment.
|
||||
#[test]
|
||||
fn a_rename_requested_on_a_segment_of_the_path_renames_the_declaration() {
|
||||
let files = files();
|
||||
let (texts, warnings) = renamed(&files, "probe.sv", "force tb.dut.", "g_sw", "g_hw");
|
||||
assert_eq!(texts[0], DUT.replace("g_sw", "g_hw"));
|
||||
assert_eq!(texts[2], PROBE.replace("g_sw", "g_hw"));
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// A local of the head's name wins (IEEE 1800 §23.8's upward search finds it
|
||||
/// first): the path is that net's, nothing is rewritten, and the segment no
|
||||
/// declaration answers is named — the §65.1 path warning, as before.
|
||||
#[test]
|
||||
fn a_local_that_shadows_the_top_module_is_not_renamed_through() {
|
||||
let shadow = "module probe2 (output logic o);
|
||||
logic tb;
|
||||
assign o = tb.dut.g_sw[0].buf_q;
|
||||
endmodule
|
||||
";
|
||||
let mut files = files();
|
||||
files.push(("probe2.sv", shadow));
|
||||
let (texts, warnings) = renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw");
|
||||
assert_eq!(texts[2], PROBE.replace("g_sw", "g_hw"), "the unshadowed paths move");
|
||||
assert_eq!(texts[3], shadow, "the shadowed path does not");
|
||||
let said: Vec<&String> = warnings.iter().filter(|w| w.contains("probe2.sv")).collect();
|
||||
assert_eq!(said.len(), 1, "{warnings:?}");
|
||||
assert!(said[0].starts_with("probe2.sv:3:"), "{said:?}");
|
||||
}
|
||||
|
||||
/// A root no file declares: the path is left and named, with its lines.
|
||||
#[test]
|
||||
fn a_root_the_workspace_does_not_declare_is_left_and_warned_about() {
|
||||
let files = [("dut_a.sv", DUT), ("probe.sv", PROBE)];
|
||||
let (texts, warnings) = renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw");
|
||||
assert_eq!(texts[1], PROBE, "nothing reaches `dut_a` from an unknown root");
|
||||
// Exactly one warning names these sites — the §65.1 path line; the
|
||||
// unresolved-candidate scan leaves them to it (Handshake H1).
|
||||
let said: Vec<&String> = warnings.iter().filter(|w| w.contains("probe.sv")).collect();
|
||||
assert_eq!(said.len(), 1, "one line for the file: {warnings:?}");
|
||||
assert!(said[0].starts_with("probe.sv:2,3,4:") && said[0].contains("`g_sw`"), "{said:?}");
|
||||
}
|
||||
|
||||
/// Two `module tb`: `tb.dut` names two instances, so nothing after it is
|
||||
/// renamed, and it is said.
|
||||
#[test]
|
||||
fn an_ambiguous_root_is_left_and_warned_about() {
|
||||
let dut_b = "module dut_b;\n logic x;\nendmodule\n";
|
||||
let tb2 = "module tb;\n dut_b dut ();\nendmodule\n";
|
||||
let mut files = files();
|
||||
files.push(("dut_b.sv", dut_b));
|
||||
files.push(("tb2.sv", tb2));
|
||||
let (texts, warnings) = renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw");
|
||||
assert_eq!(texts[2], PROBE);
|
||||
let said: Vec<&String> = warnings.iter().filter(|w| w.contains("probe.sv")).collect();
|
||||
assert_eq!(said.len(), 1, "one line for the file: {warnings:?}");
|
||||
assert!(said[0].starts_with("probe.sv:2,3,4:"), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// With two `module tb`, each `tb.` head could name either, so renaming one
|
||||
/// of them is refused rather than rewriting heads that may be the other's.
|
||||
#[test]
|
||||
fn renaming_one_of_two_same_named_tops_is_refused() {
|
||||
let tb2 = "module tb;\n dut_a dut ();\nendmodule\n";
|
||||
let mut files = files();
|
||||
files.push(("tb2.sv", tb2));
|
||||
let text = TB;
|
||||
let why = rename(&workspace(&files), &path("tb.sv"), at(text, "module ", "tb"), "top_tb")
|
||||
.expect_err("refused");
|
||||
assert!(why.contains("tb"), "{why}");
|
||||
}
|
||||
|
||||
/// Handshake H1: QA's repro (`probe.sv: assign o = tb.dut.g_sw[0].buf_q;`)
|
||||
/// with the root undeclared, and with three `module tb` (the opentitan
|
||||
/// shape): exactly one warning names the probe's line, the §65.1 path line,
|
||||
/// and the unresolved-candidate scan does not repeat it.
|
||||
#[test]
|
||||
fn an_unresolved_top_rooted_path_is_named_by_exactly_one_warning() {
|
||||
let probe = "module probe (output logic o);\n assign o = tb.dut.g_sw[0].buf_q;\nendmodule\n";
|
||||
let tb_b = "module tb;\n dut_b dut ();\nendmodule\n";
|
||||
let tb_c = "module tb;\n dut_c dut ();\nendmodule\n";
|
||||
let undeclared = vec![("dut_a.sv", DUT), ("probe.sv", probe)];
|
||||
let mut three = vec![("dut_a.sv", DUT), ("tb.sv", TB), ("probe.sv", probe)];
|
||||
three.extend([("tb_b.sv", tb_b), ("tb_c.sv", tb_c)]);
|
||||
for files in [undeclared, three] {
|
||||
for (prefix, old) in [("begin : ", "g_sw"), ("logic ", "buf_q")] {
|
||||
let (texts, warnings) = renamed(&files, "dut_a.sv", prefix, old, "renamed_x");
|
||||
let at_probe = files.iter().position(|(n, _)| *n == "probe.sv").expect("probe");
|
||||
assert_eq!(texts[at_probe], probe, "left unchanged");
|
||||
let said: Vec<&String> = warnings.iter().filter(|w| w.contains("probe.sv")).collect();
|
||||
assert_eq!(said.len(), 1, "{old}: {warnings:?}");
|
||||
assert!(said[0].starts_with("probe.sv:2:"), "{old}: {said:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Rework after QA (2026-10-19): rooting only when the head is provably a top
|
||||
// module or interface. Each case is QA's repro (`scratchpad/qa654/attack`);
|
||||
// each asserts the path is left unchanged and named, never silently renamed.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Rename the `name` after `prefix` in `file`; assert `left` is unchanged and
|
||||
/// a warning names `left`'s `line`.
|
||||
fn left_and_named(files: &[(&str, &str)], at_: (&str, &str, &str), left: &str, line: u32) {
|
||||
let (file, prefix, name) = at_;
|
||||
let (texts, warnings) = renamed(files, file, prefix, name, "renamed_x");
|
||||
let i = files.iter().position(|(n, _)| *n == left).expect("the left file");
|
||||
assert_eq!(texts[i], files[i].1, "{name}: `{left}` is not edited");
|
||||
let named = format!("{left}:{line}:");
|
||||
assert!(warnings.iter().any(|w| w.starts_with(&named)), "{name}: {warnings:?}");
|
||||
}
|
||||
|
||||
/// QA F1 (B12): a package `tb` beside the module `tb`. Renaming the package's
|
||||
/// `dut` used to rewrite `tb.dut.x`; renaming the module's instance used to
|
||||
/// miss it. Neither touches it now, and both name it.
|
||||
#[test]
|
||||
fn qa_f1_a_package_sharing_the_roots_name_lends_the_path_nothing() {
|
||||
let dut = "module dut_a;\n logic x;\nendmodule\n";
|
||||
let pkg = "package tb;\n logic dut;\nendpackage\n";
|
||||
let other = "module other;\n initial force tb.dut.x = 0;\nendmodule\n";
|
||||
let files = [("dut_a.sv", dut), ("tb.sv", TB), ("tb_pkg.sv", pkg), ("other.sv", other)];
|
||||
left_and_named(&files, ("tb_pkg.sv", "logic ", "dut"), "other.sv", 2);
|
||||
left_and_named(&files, ("tb.sv", "dut_a ", "dut"), "other.sv", 2);
|
||||
left_and_named(&files, ("dut_a.sv", "logic ", "x"), "other.sv", 2);
|
||||
}
|
||||
|
||||
/// QA A3/A4: `pk.x` (illegal) with a package `pk`, with and without a module
|
||||
/// `pk`: renaming the package's `x` leaves it.
|
||||
#[test]
|
||||
fn qa_f1_a_package_is_never_a_root() {
|
||||
let pkg = "package pk;\n logic x;\nendpackage\n";
|
||||
let module = "module pk;\n logic x;\nendmodule\n";
|
||||
let user = "module user (output logic o);\n assign o = pk.x;\nendmodule\n";
|
||||
let alone = [("p.sv", pkg), ("user.sv", user)];
|
||||
let (texts, _) = renamed(&alone, "p.sv", "logic ", "x", "y");
|
||||
assert_eq!(texts[1], user);
|
||||
let both = [("p.sv", pkg), ("m.sv", module), ("user.sv", user)];
|
||||
left_and_named(&both, ("p.sv", "logic ", "x"), "user.sv", 2);
|
||||
left_and_named(&both, ("m.sv", "logic ", "x"), "user.sv", 2);
|
||||
}
|
||||
|
||||
/// QA F2 (A1): `import p::*` supplies `cfg`, a package variable, and a module
|
||||
/// `cfg` exists too. The imported name is the head; renaming the module's
|
||||
/// `field` used to rewrite `cfg.field`.
|
||||
#[test]
|
||||
fn qa_f2_an_imported_head_is_never_rooted_at_a_same_named_module() {
|
||||
let pkg = "package p;\n typedef struct packed { logic field; } s_t;\n s_t cfg;\nendpackage\n";
|
||||
let module = "module cfg;\n logic field;\nendmodule\n";
|
||||
let user =
|
||||
"module user (output logic o);\n import p::*;\n assign o = cfg.field;\nendmodule\n";
|
||||
let files = [("p.sv", pkg), ("cfgm.sv", module), ("user.sv", user)];
|
||||
left_and_named(&files, ("cfgm.sv", "logic ", "field"), "user.sv", 3);
|
||||
}
|
||||
|
||||
/// QA F4: three heads the binder cannot see — a macro-declared member in a
|
||||
/// class (A11), a macro-declared struct in a module (A12) and a class in a
|
||||
/// package writing `tb.dut.x` (D2) — each used to be renamed through a
|
||||
/// same-named module.
|
||||
#[test]
|
||||
fn qa_f4_a_head_this_crate_cannot_see_is_never_rooted() {
|
||||
let cfg = "module cfg;\n logic en;\nendmodule\n";
|
||||
let class = "class env;\n `DECLARE_CFG\n task run(); if (cfg.en) $display(\"x\"); endtask\nendclass\n";
|
||||
left_and_named(&[("cm.sv", cfg), ("cls.sv", class)], ("cm.sv", "logic ", "en"), "cls.sv", 3);
|
||||
let st = "module st;\n logic a;\nendmodule\n";
|
||||
let user = "module user (output logic o);\n `DECL_STRUCT(st)\n assign o = st.a;\nendmodule\n";
|
||||
left_and_named(&[("cm.sv", st), ("user.sv", user)], ("cm.sv", "logic ", "a"), "user.sv", 3);
|
||||
let dut = "module dut_a;\n logic x;\nendmodule\n";
|
||||
let pkg = "package env_pkg;\n class seq;\n task body(); tb.dut.x = 1; endtask\n endclass\nendpackage\n";
|
||||
let files = [("dut_a.sv", dut), ("tb.sv", TB), ("pkg.sv", pkg)];
|
||||
left_and_named(&files, ("dut_a.sv", "logic ", "x"), "pkg.sv", 3);
|
||||
}
|
||||
|
||||
/// QA R1 (E1, E2, E6, E3): a macro statement in a `begin` block, a task or a
|
||||
/// function body, or a macro in the ANSI port list, may declare `st`/`bus`;
|
||||
/// renaming the same-named module's member leaves the path and names it.
|
||||
#[test]
|
||||
fn qa_r1_a_macro_where_a_declaration_could_stand_blocks_rooting() {
|
||||
let st = "module st;\n logic a;\nendmodule\n";
|
||||
for (user, line) in [
|
||||
("module user;\n initial begin\n `DECL_LOCAL(st)\n st.a = 1;\n end\nendmodule\n", 4),
|
||||
("module user;\n task automatic t();\n `DECL_LOCAL(st)\n st.a = 1;\n endtask\nendmodule\n", 4),
|
||||
("module user;\n function automatic void f();\n `DECL_LOCAL(st)\n begin st.a = 1; end\n endfunction\nendmodule\n", 4),
|
||||
] {
|
||||
left_and_named(&[("st.sv", st), ("user.sv", user)], ("st.sv", "logic ", "a"), "user.sv", line);
|
||||
}
|
||||
let bus = "module bus;\n logic data;\nendmodule\n";
|
||||
let user = "module user (`MY_PORTS, output logic o);\n assign o = bus.data;\nendmodule\n";
|
||||
let files = [("bus.sv", bus), ("user.sv", user)];
|
||||
let (texts, _) = renamed(&files, "bus.sv", "logic ", "data", "d2");
|
||||
assert_eq!(texts[1], user, "the macro port may declare `bus`");
|
||||
}
|
||||
|
||||
/// The held shapes (E7, E8): a macro in a sibling generate block, or used as
|
||||
/// a data type, declares no head on the path's scope chain — renamed.
|
||||
#[test]
|
||||
fn qa_r1_a_macro_off_the_scope_chain_or_as_a_type_still_renames() {
|
||||
let st = "module st;\n logic a;\nendmodule\n";
|
||||
for user in [
|
||||
"module user;\n if (1) begin : g1\n `DECL_LOCAL(st)\n end\n if (1) begin : g2\n initial st.a = 1;\n end\nendmodule\n",
|
||||
"module user;\n `MY_STRUCT_T other;\n initial st.a = 1;\nendmodule\n",
|
||||
] {
|
||||
let files = [("st.sv", st), ("user.sv", user)];
|
||||
let (texts, warnings) = renamed(&files, "st.sv", "logic ", "a", "b");
|
||||
assert_eq!(texts[1], user.replace("st.a", "st.b"), "{warnings:?}");
|
||||
}
|
||||
}
|
||||
@@ -74,8 +74,9 @@ impl<'a> Binder<'a> {
|
||||
self.bind_expr(lsb, scope);
|
||||
}
|
||||
// `a.b`, `a.b.c`, `tb.dut.u_core.sig`: every link is bound —
|
||||
// the head as an ordinary use, each `.name` as a tail against the
|
||||
// type of what precedes it (`Target::MemberOf`) — because the
|
||||
// the head as a path root (`Target::PathHead`), each `.name` as a
|
||||
// tail against the type of what precedes it (`Target::MemberOf`) —
|
||||
// because the
|
||||
// recursion below meets each `Member` node in turn. `this.b` and
|
||||
// `super.b` go to the enclosing class instead, and a spine that
|
||||
// starts at one of them stops there: `this.a.b` records `a` and
|
||||
@@ -92,7 +93,15 @@ impl<'a> Binder<'a> {
|
||||
self.use_member(scope, name, member_tail(e.span, name), Target::SuperMember)
|
||||
}
|
||||
_ => {
|
||||
self.bind_expr(base, scope);
|
||||
// A bare head is a path's root: a miss there names a
|
||||
// top-level module (`Target::PathHead`), where any other
|
||||
// bare identifier's miss names nothing.
|
||||
match &base.kind {
|
||||
ExprKind::Ident(head) => {
|
||||
self.use_name(scope, head, base.span, Target::PathHead)
|
||||
}
|
||||
_ => self.bind_expr(base, scope),
|
||||
}
|
||||
if let Some((head, mids)) = spine(base) {
|
||||
// The tail's range is derived from the whole
|
||||
// expression's, so it is verified before use: a
|
||||
|
||||
@@ -183,9 +183,11 @@ impl<'a> Binder<'a> {
|
||||
// `Verbatim` is a constraint or covergroup body — no symbol is
|
||||
// bound for its name and nothing inside it is scanned, the same
|
||||
// contract macro invocations have.
|
||||
// A macro invocation standing as an item may declare names this
|
||||
// crate never sees (`Binder::mark_macro_declarations`).
|
||||
ItemKind::MacroItem(_) => self.mark_macro_declarations(scope),
|
||||
ItemKind::Export(ExportDecl::Dpi(_))
|
||||
| ItemKind::Directive(_)
|
||||
| ItemKind::MacroItem(_)
|
||||
| ItemKind::Timeunit(_)
|
||||
| ItemKind::Error(_)
|
||||
// A null item (`;`) declares nothing and references nothing.
|
||||
@@ -212,6 +214,9 @@ impl<'a> Binder<'a> {
|
||||
}
|
||||
}
|
||||
self.bind_param_ports(m.param_ports.iter().flatten(), inner);
|
||||
if port_list_may_hide_declarations(&m.ports) {
|
||||
self.mark_macro_declarations(inner);
|
||||
}
|
||||
match &m.ports {
|
||||
// An error element — a port a tolerant parse could not read —
|
||||
// declares nothing, exactly as an `ItemKind::Error` does.
|
||||
@@ -568,3 +573,18 @@ fn bind_target_path(b: &BindDirective) -> Option<String> {
|
||||
}
|
||||
(!out.is_empty()).then_some(out)
|
||||
}
|
||||
|
||||
/// Whether a header's port list holds an entry this crate cannot read as a
|
||||
/// port: a macro invocation standing as one (`` module m (`MY_PORTS, …) ``,
|
||||
/// which the parser keeps as a port spelled `` `MY_PORTS ``) or an element a
|
||||
/// tolerant parse gave up on. Either may declare names this crate never sees.
|
||||
fn port_list_may_hide_declarations(ports: &PortList) -> bool {
|
||||
let macro_name = |name: &str| name.starts_with('`');
|
||||
match ports {
|
||||
PortList::Ansi(ports) => ports.iter().any(|p| p.ok().is_none_or(|p| macro_name(&p.name))),
|
||||
PortList::NonAnsi(ports) => {
|
||||
ports.iter().any(|p| p.ok().is_none_or(|p| macro_name(&p.name)))
|
||||
}
|
||||
PortList::None | PortList::Empty => false,
|
||||
}
|
||||
}
|
||||
@@ -113,6 +113,13 @@ pub(crate) enum Target {
|
||||
/// of `mids` walks one link further — the [`Target::MemberOf`] walk, with
|
||||
/// its start moved from the writing scope to the target's.
|
||||
BindMember { target: String, head: String, mids: Vec<String> },
|
||||
/// The **head** of a dotted path — the `tb` of `tb.dut.sig`: looked up
|
||||
/// exactly like [`Target::Lexical`], but a miss is a top-level module's
|
||||
/// name (IEEE 1800 §23.6: a top-level module name is the root of a
|
||||
/// hierarchical name), so it is handed to the workspace's unit table as
|
||||
/// [`Target::Module`] hands an instantiation's type. A local of the name
|
||||
/// still wins. `docs/features/top-rooted-paths/README.md`.
|
||||
PathHead,
|
||||
/// The `x` of `this.x`: the enclosing class's scope only.
|
||||
ThisMember,
|
||||
/// The `x` of `super.x`: always the base class's business.
|
||||
@@ -166,6 +173,7 @@ impl<'a> Binder<'a> {
|
||||
imports: Vec::new(),
|
||||
extends: None,
|
||||
names: HashMap::new(),
|
||||
macro_items: false,
|
||||
};
|
||||
Binder {
|
||||
src,
|
||||
@@ -183,6 +191,17 @@ impl<'a> Binder<'a> {
|
||||
ScopeId(0)
|
||||
}
|
||||
|
||||
/// Record that an unexpanded macro invocation stands in `scope` where a
|
||||
/// declaration could stand — an item, a statement or block item, a port —
|
||||
/// so it may declare names this crate never sees. A path head missing
|
||||
/// from `scope`, or from a scope inside it, is then not proven a top
|
||||
/// module (`resolve/root.rs`, top-rooted-paths QA F4 and R1).
|
||||
pub(super) fn mark_macro_declarations(&mut self, scope: ScopeId) {
|
||||
if let Some(s) = self.scopes.get_mut(scope.0 as usize) {
|
||||
s.macro_items = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn new_scope(&mut self, kind: ScopeKind, parent: ScopeId, span: TextRange) -> ScopeId {
|
||||
let id = ScopeId(self.scopes.len() as u32);
|
||||
self.scopes.push(Scope {
|
||||
@@ -195,6 +214,7 @@ impl<'a> Binder<'a> {
|
||||
imports: Vec::new(),
|
||||
extends: None,
|
||||
names: HashMap::new(),
|
||||
macro_items: false,
|
||||
});
|
||||
self.scopes[parent.0 as usize].children.push(id);
|
||||
id
|
||||
@@ -322,14 +342,16 @@ impl<'a> Binder<'a> {
|
||||
// with a head of its own already carries the right target and is left
|
||||
// alone.
|
||||
let target = match (&self.with_head, &self.bind_target, &target) {
|
||||
(Some((head, mids)), _, Target::Lexical) => {
|
||||
(Some((head, mids)), _, Target::Lexical | Target::PathHead) => {
|
||||
Target::InlineConstraint { head: head.clone(), mids: mids.clone() }
|
||||
}
|
||||
// Same funnel, same rule, for a `bind`'s connection expressions:
|
||||
// a bare name there is the target scope's before it is anything
|
||||
// else. A name written with a head of its own already carries the
|
||||
// right target and is left alone.
|
||||
(None, Some(scope), Target::Lexical) => Target::BindScope { target: scope.clone() },
|
||||
(None, Some(scope), Target::Lexical | Target::PathHead) => {
|
||||
Target::BindScope { target: scope.clone() }
|
||||
}
|
||||
// And the same rule for a hierarchical path in one: its head is a
|
||||
// name in the target's scope, so the whole spine is rooted there
|
||||
// rather than in the scope the directive is written in.
|
||||
|
||||
@@ -277,13 +277,15 @@ impl<'a> Binder<'a> {
|
||||
| StmtKind::Continue
|
||||
| StmtKind::WaitFork
|
||||
| StmtKind::Directive(_)
|
||||
| StmtKind::MacroStmt(_)
|
||||
| StmtKind::Null
|
||||
// Verbatim source: opaque to name resolution, exactly as the
|
||||
// item-level `ItemKind::Verbatim` is.
|
||||
| StmtKind::Verbatim(_)
|
||||
| StmtKind::Error(_) => {}
|
||||
StmtKind::Assertion(a) => self.bind_assertion(a, scope),
|
||||
// A macro standing as a statement may be a block-item declaration
|
||||
// (`Binder::mark_macro_declarations`, top-rooted-paths QA R1).
|
||||
StmtKind::MacroStmt(_) => self.mark_macro_declarations(scope),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -164,7 +164,15 @@ use crate::workspace::{
|
||||
/// nothing. A 0.59.0 store would answer find-references and the rename of a
|
||||
/// block label as though no other file named it. See
|
||||
/// `docs/features/generate-label-rename/README.md`.
|
||||
pub const FACTS_FORMAT: u32 = 21;
|
||||
/// 21 → 22 (2026-10-19, top-rooted-paths): no new field, but new records — a
|
||||
/// dotted path whose head this file does not declare (`tb.dut.sig`, rooted at
|
||||
/// a top module another file declares) records its head as a candidate for
|
||||
/// the unit table and every segment after it as an external reference on the
|
||||
/// hierarchical surface, where it recorded nothing. A 0.61.0 store would
|
||||
/// answer find-references and the rename of `dut`'s members as though no DV
|
||||
/// file's `force tb.dut.…` named them. See
|
||||
/// `docs/features/top-rooted-paths/README.md`.
|
||||
pub const FACTS_FORMAT: u32 = 22;
|
||||
|
||||
impl FileFacts {
|
||||
/// These facts as one line's worth of fields, tab-separated.
|
||||
|
||||
@@ -239,6 +239,10 @@ pub enum Resolution {
|
||||
/// which is a hierarchical path and reads the module's hierarchical
|
||||
/// surface. Carried here rather than worked out again at lookup time
|
||||
/// because only the file that wrote the path knows what its head was.
|
||||
/// A path rooted at a **top module** another file declares (`tb` of
|
||||
/// `tb.dut.sig`, TODO §65.4) reads the hierarchical surface too — its
|
||||
/// head as well, whose bare path the index then accepts only as a module
|
||||
/// or an interface.
|
||||
ExternalCandidate { paths: Vec<String>, surface: Surface },
|
||||
/// A use inside a class that nothing lexical binds, where the class's
|
||||
/// `extends` could: `base` is the base-class path as written
|
||||
@@ -420,6 +424,9 @@ pub struct Scope {
|
||||
/// rules). Kept separate from `symbols` so a redeclaration is still
|
||||
/// visible in the outline.
|
||||
pub(crate) names: HashMap<String, SymbolId>,
|
||||
/// Whether an unexpanded macro invocation stands as an item here — text
|
||||
/// that may declare names this crate cannot see.
|
||||
pub(crate) macro_items: bool,
|
||||
}
|
||||
|
||||
impl Scope {
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
use crate::bind::{Pending, Target};
|
||||
use crate::model::{MemberSite, Resolution, Scope, ScopeId, Surface, Symbol, SymbolId, SymbolKind};
|
||||
|
||||
mod root;
|
||||
|
||||
/// Resolve one pending use against the finished scope tree.
|
||||
///
|
||||
/// `None` means **record no reference at all**: the targets that can arrive
|
||||
@@ -21,6 +23,7 @@ pub(crate) fn resolve(scopes: &[Scope], symbols: &[Symbol], p: &Pending) -> Opti
|
||||
// which symbol that is, so there is nothing to look up.
|
||||
Target::Declaration(id) => Resolution::Resolved(*id),
|
||||
Target::Lexical => lexical(scopes, p.scope, &p.name, false),
|
||||
Target::PathHead => root::path_head(scopes, p.scope, &p.name),
|
||||
Target::Type => lexical(scopes, p.scope, &p.name, true),
|
||||
Target::Package => named_at_file_scope(scopes, symbols, &p.name, is_package),
|
||||
// An interface is instantiated, connected and hierarchically named
|
||||
@@ -222,7 +225,11 @@ fn member_of(
|
||||
mids: &[String],
|
||||
name: &str,
|
||||
) -> Option<Resolution> {
|
||||
let site = member_site(scopes, symbols, from, head, mids)?;
|
||||
if head == root::ROOT && mids.is_empty() {
|
||||
// `$root.tb`: the tail is the top module itself.
|
||||
return Some(root::top_module(scopes, symbols, name));
|
||||
}
|
||||
let site = spine_site(scopes, symbols, from, head, mids, HeadMiss::TopModule)?;
|
||||
member_at(scopes, symbols, site, name, mids.is_empty())
|
||||
}
|
||||
|
||||
@@ -288,6 +295,17 @@ fn member_at(
|
||||
/// keeps the two from drifting. `super` names the first hop of the `extends`
|
||||
/// chain — the base's scope when this file declares it, the base's *name*
|
||||
/// when it does not, which is the unit the overlay's own chase starts at.
|
||||
///
|
||||
/// **One difference from the resolution walk**, and only one: a head this
|
||||
/// file does not declare is *not* rooted at a top-level module here
|
||||
/// ([`HeadMiss::Nothing`]), where [`member_of`] roots it at one
|
||||
/// ([`HeadMiss::TopModule`], TODO §65.4). A popup after `no_such_handle.` has
|
||||
/// always answered nothing so the ordinary completion tiers run, and a
|
||||
/// workspace unit list after every unknown head would replace them with an
|
||||
/// empty one; offering a top module's members after `tb.` is a completion
|
||||
/// change the language server's member list must make knowingly
|
||||
/// (`docs/features/top-rooted-paths/README.md`, Handshakes). `$root.tb.` is
|
||||
/// rooted in both: it says what it is.
|
||||
pub(crate) fn member_site(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
@@ -295,7 +313,31 @@ pub(crate) fn member_site(
|
||||
head: &str,
|
||||
mids: &[String],
|
||||
) -> Option<MemberSite> {
|
||||
let mut here = head_site(scopes, symbols, from, head)?;
|
||||
spine_site(scopes, symbols, from, head, mids, HeadMiss::Nothing)
|
||||
}
|
||||
|
||||
/// What a spine's head that this file does not declare roots the spine at.
|
||||
#[derive(Clone, Copy)]
|
||||
enum HeadMiss {
|
||||
/// Nothing: the spine stops (the completion walk).
|
||||
Nothing,
|
||||
/// The top-level module of that name (the resolution walk).
|
||||
TopModule,
|
||||
}
|
||||
|
||||
/// [`member_site`]'s walk, with what a head miss means said by the caller.
|
||||
fn spine_site(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
from: ScopeId,
|
||||
head: &str,
|
||||
mids: &[String],
|
||||
miss: HeadMiss,
|
||||
) -> Option<MemberSite> {
|
||||
let (mut here, mids) = match (head, mids.split_first()) {
|
||||
(root::ROOT, Some((top, rest))) => (root::top_site(scopes, symbols, top), rest),
|
||||
_ => (head_site(scopes, symbols, from, head, miss)?, mids),
|
||||
};
|
||||
for mid in mids {
|
||||
here = descend(scopes, symbols, here, mid)?;
|
||||
}
|
||||
@@ -338,6 +380,7 @@ fn head_site(
|
||||
symbols: &[Symbol],
|
||||
from: ScopeId,
|
||||
head: &str,
|
||||
miss: HeadMiss,
|
||||
) -> Option<MemberSite> {
|
||||
match head {
|
||||
// Neither is a name this crate binds, so neither goes through
|
||||
@@ -354,12 +397,22 @@ fn head_site(
|
||||
}),
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let Resolution::Resolved(id) = lexical(scopes, from, head, false) else {
|
||||
return None;
|
||||
};
|
||||
link_type(scopes, symbols, id)
|
||||
}
|
||||
// `$root` alone, a system name, a macro: no unit to root a path at.
|
||||
_ if head.starts_with(['$', '`']) => None,
|
||||
_ => match lexical(scopes, from, head, false) {
|
||||
Resolution::Resolved(id) => link_type(scopes, symbols, id),
|
||||
// A plain miss where nothing unseen could declare the name is a
|
||||
// top-level module's name — the very rule `Target::PathHead`
|
||||
// applies to the head's own reference (`root::roots_at_top`), so
|
||||
// the head and the segments after it agree. Anything else is
|
||||
// doubt, and doubt roots nothing.
|
||||
Resolution::NotFound
|
||||
if matches!(miss, HeadMiss::TopModule) && root::roots_at_top(scopes, from) =>
|
||||
{
|
||||
Some(root::unit_root(head))
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -684,7 +737,9 @@ fn last_segment(path: &str) -> &str {
|
||||
/// in a *value* position: a name a `` `define`` would have produced, a typo, a
|
||||
/// signal declared somewhere this crate does not model. Nothing about it says
|
||||
/// "file-scope declaration", so it is not swept through the unit table, where a
|
||||
/// mere name collision would make `rename` rewrite an unrelated file.
|
||||
/// mere name collision would make `rename` rewrite an unrelated file. The one
|
||||
/// value position that does say it is the head of a dotted path, which is
|
||||
/// [`Target::PathHead`]'s and `root::path_head`'s, not this function's.
|
||||
fn lexical(scopes: &[Scope], from: ScopeId, name: &str, promote: bool) -> Resolution {
|
||||
let mut external = Vec::new();
|
||||
let mut current = Some(from);
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
//! A hierarchical path rooted at a **top-level module** (IEEE 1800 §23.6: a
|
||||
//! top-level module name is the root of a hierarchical name) — `tb.dut.sig`
|
||||
//! written in a file that does not declare `tb`, and `$root.tb.dut.sig`.
|
||||
//!
|
||||
//! The head's own reference ([`path_head`]) and the walk the segments after it
|
||||
//! take ([`unit_root`], via `head_site`) fall back to the same unit, so `tb`
|
||||
//! and `tb.dut` cannot name different modules.
|
||||
//!
|
||||
//! **A path is rooted only when this file shows the head can be nothing but a
|
||||
//! top-level module** ([`roots_at_top`]); in doubt it is not, and the path
|
||||
//! stays unresolved and warned about, as before §65.4. A local of the name
|
||||
//! wins (the LRM's upward search finds it first); so does a name an import
|
||||
//! could supply, whether or not the workspace can say it does; and a head
|
||||
//! written inside a class, or where an unexpanded macro stands as an item,
|
||||
//! may be a name this crate never sees. `docs/features/top-rooted-paths/README.md`.
|
||||
|
||||
use crate::model::{MemberSite, Resolution, Scope, ScopeId, ScopeKind, Surface, Symbol};
|
||||
|
||||
use super::{file_symbol, is_instantiable, lexical, owning_scope};
|
||||
|
||||
/// The system name that spells the root of the design hierarchy.
|
||||
pub(super) const ROOT: &str = "$root";
|
||||
|
||||
/// The head of a dotted path: the lexical answer, and on a plain miss that
|
||||
/// [`roots_at_top`] allows, the top-level module of that name. An import
|
||||
/// candidate stays exactly what `lexical` said (the imported name is the
|
||||
/// head, by the LRM), and so does every other answer.
|
||||
pub(super) fn path_head(scopes: &[Scope], from: ScopeId, name: &str) -> Resolution {
|
||||
match lexical(scopes, from, name, false) {
|
||||
Resolution::NotFound if roots_at_top(scopes, from) => top_candidate(name),
|
||||
found => found,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a head missing from the lexical chain of `from` may be taken for a
|
||||
/// top-level module: no scope on the chain, up to the file, is a class (a
|
||||
/// class member, inherited or macro-declared, is never a path into the design
|
||||
/// hierarchy lucisv could prove) or holds an unexpanded macro invocation as
|
||||
/// an item (it may declare the very name).
|
||||
pub(super) fn roots_at_top(scopes: &[Scope], from: ScopeId) -> bool {
|
||||
let mut current = Some(from);
|
||||
while let Some(id) = current {
|
||||
let Some(scope) = scopes.get(id.0 as usize) else { return false };
|
||||
if scope.kind == ScopeKind::Class || scope.macro_items {
|
||||
return false;
|
||||
}
|
||||
current = scope.parent;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Where a path whose head this file does not declare is rooted: the
|
||||
/// workspace unit of that name, read on its hierarchical surface — the
|
||||
/// surface an instance path reads, because the segments after a root are the
|
||||
/// same kind of names (`tb.dut` is an instance of `tb`).
|
||||
pub(super) fn unit_root(head: &str) -> MemberSite {
|
||||
MemberSite::Unit { path: head.to_string(), surface: Surface::Hierarchical }
|
||||
}
|
||||
|
||||
/// The `tb` of `$root.tb.…` as a site: the module this file declares at file
|
||||
/// scope, else the workspace unit. `$root` skips the lexical walk entirely —
|
||||
/// that is what it is for.
|
||||
pub(super) fn top_site(scopes: &[Scope], symbols: &[Symbol], top: &str) -> MemberSite {
|
||||
match owning_scope(scopes, symbols, top, is_instantiable) {
|
||||
Some(scope) => MemberSite::Scope(scope),
|
||||
None => unit_root(top),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `tb` of `$root.tb` as a reference: the file-scope module this file
|
||||
/// declares, else a candidate for the workspace's unit table.
|
||||
pub(super) fn top_module(scopes: &[Scope], symbols: &[Symbol], top: &str) -> Resolution {
|
||||
match file_symbol(scopes, symbols, top, is_instantiable) {
|
||||
Some(id) => Resolution::Resolved(id),
|
||||
None => top_candidate(top),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bare name on the hierarchical surface — which is also what tells the
|
||||
/// workspace layer to accept only a module or an interface for it
|
||||
/// (`external::follow_one`): a package or class sharing a top module's name
|
||||
/// is not a root a `.` can follow.
|
||||
fn top_candidate(name: &str) -> Resolution {
|
||||
Resolution::ExternalCandidate { paths: vec![name.to_string()], surface: Surface::Hierarchical }
|
||||
}
|
||||
@@ -246,15 +246,46 @@ pub(super) fn base_chain<'i>(index: &'i WorkspaceIndex, unit: &str) -> Vec<&'i s
|
||||
///
|
||||
/// The same fold [`follow_one`] runs before its own lookup — shared, so a
|
||||
/// list and a lookup of the same path cannot land in different units.
|
||||
///
|
||||
/// On the **hierarchical** surface every unit the fold stands in is checked
|
||||
/// ([`design_unit`]): a path through the design hierarchy starts at a module
|
||||
/// or an interface and never passes through a package, so a package sharing a
|
||||
/// module's name cannot lend the path its members (top-rooted-paths QA F1).
|
||||
pub(super) fn fold_path(index: &WorkspaceIndex, path: &str, surface: Surface) -> Option<String> {
|
||||
let mut segments = path.split("::");
|
||||
let mut unit = segments.next()?.to_string();
|
||||
let hierarchical = surface == Surface::Hierarchical;
|
||||
if hierarchical && !design_unit(index, &unit, true) {
|
||||
return None;
|
||||
}
|
||||
for segment in segments {
|
||||
unit = index.member_unit_in(&unit, segment, surface)?;
|
||||
if hierarchical && !design_unit(index, &unit, false) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(unit)
|
||||
}
|
||||
|
||||
/// Whether a hierarchical path may stand in `unit`. Its **first** unit must be
|
||||
/// declared, and only as modules or interfaces — the type of an instance, the
|
||||
/// target of a `bind`, or the top module a path is rooted at. A **later** unit
|
||||
/// (an instance's type, a block's synthesized key, a struct or class type a
|
||||
/// variable is declared with) may be any kind, but not a module and something
|
||||
/// else at once: the member table is keyed by name, so such a name's members
|
||||
/// are the two declarations' merged — which is how a package sharing a
|
||||
/// module's name would reach a later hop. A later unit that is *only* a
|
||||
/// package would need a declaration typed with a package's name, which is
|
||||
/// not code; no separate rule is kept for it (QA M7).
|
||||
fn design_unit(index: &WorkspaceIndex, unit: &str, first: bool) -> bool {
|
||||
let defs = index.units(unit);
|
||||
let modules = defs.iter().filter(|def| def.kind.is_instantiable()).count();
|
||||
if first {
|
||||
return !defs.is_empty() && modules == defs.len();
|
||||
}
|
||||
modules == 0 || modules == defs.len()
|
||||
}
|
||||
|
||||
/// The type a file-scope `typedef` names, when the workspace declares the name
|
||||
/// exactly once and as a typedef. Two declarations of the name are two
|
||||
/// answers, and this layer picks between candidates nowhere else either.
|
||||
@@ -327,7 +358,7 @@ fn follow_one<'i>(
|
||||
}
|
||||
if segments.len() < 2 {
|
||||
return if path == name {
|
||||
index.units(name)
|
||||
root_units(index.units(name), surface)
|
||||
} else {
|
||||
member_chain(index, path, name, surface)
|
||||
};
|
||||
@@ -342,6 +373,20 @@ fn follow_one<'i>(
|
||||
member_chain(index, &unit, name, surface)
|
||||
}
|
||||
|
||||
/// The units a bare name answers with. On the connection surface — an
|
||||
/// instantiation's type, an imported package, a type name — every unit of the
|
||||
/// name, as always. On the **hierarchical** surface the name is the root of a
|
||||
/// path (`tb` of `tb.dut.sig`, TODO §65.4), which only a module or an
|
||||
/// interface can be: units of any other kind answer nothing, and so does a
|
||||
/// name some file declares as a module and another as something else, rather
|
||||
/// than an answer with the stranger left in or quietly dropped.
|
||||
fn root_units(units: &[Def], surface: Surface) -> &[Def] {
|
||||
match surface {
|
||||
Surface::Hierarchical if !units.iter().all(|def| def.kind.is_instantiable()) => &[],
|
||||
_ => units,
|
||||
}
|
||||
}
|
||||
|
||||
impl ExternalResolutions {
|
||||
/// The answer for one reference, or `None` if it was not an external
|
||||
/// candidate.
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
mod external;
|
||||
mod hierarchy;
|
||||
mod index;
|
||||
mod path_units;
|
||||
mod record;
|
||||
mod reexport;
|
||||
mod update;
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//! The design units a hierarchical path to a declaration walks through —
|
||||
//! what a caller handing the refactoring engine a *subset* of the workspace
|
||||
//! must include for that path to resolve inside the subset as it does in the
|
||||
//! whole (top-rooted-paths QA F3).
|
||||
//!
|
||||
//! `tb.dut.u_core.sig` in a DV file names `sig` through `tb` (the top module
|
||||
//! it is rooted at), `dut_a` (the type of `tb.dut`) and `core` (the type of
|
||||
//! `u_core`). The index resolved it, so the use is in `sig`'s postings; but a
|
||||
//! rename handed only `sig`'s declaring file and that DV file cannot resolve
|
||||
//! the root, and would leave the path behind. The answer is read off the
|
||||
//! records the index already holds: no file is read.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
|
||||
use crate::model::Surface;
|
||||
|
||||
use super::record::ReferenceFact;
|
||||
use super::{Def, FileId, WorkspaceIndex};
|
||||
|
||||
impl WorkspaceIndex {
|
||||
/// Every unit an indexed use of `def` written as a hierarchical path
|
||||
/// passes through before its last segment: the path's first unit (an
|
||||
/// instance's type, a `bind` target, a top module) and the unit of each
|
||||
/// hop after it. Empty when no use of `def` is such a path.
|
||||
pub fn path_units_to(&self, def: &Def) -> BTreeSet<String> {
|
||||
let mut by_file: HashMap<FileId, HashSet<(u32, u32)>> = HashMap::new();
|
||||
for site in self.references_to(def) {
|
||||
let span = (site.name_span.start, site.name_span.end);
|
||||
by_file.entry(site.file).or_default().insert(span);
|
||||
}
|
||||
let mut out = BTreeSet::new();
|
||||
for (file, spans) in by_file {
|
||||
let Some(facts) = self.facts.get(file.0 as usize) else { continue };
|
||||
for fact in &facts.references {
|
||||
let ReferenceFact::External {
|
||||
paths,
|
||||
surface: Surface::Hierarchical,
|
||||
occurrence,
|
||||
..
|
||||
} = fact
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if spans.contains(&(occurrence.start, occurrence.end)) {
|
||||
for path in paths {
|
||||
self.collect_hops(path, &mut out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The units `path`'s segments before its last stand in, folded as
|
||||
/// `external::fold_path` folds them, as far as the fold goes.
|
||||
fn collect_hops(&self, path: &str, out: &mut BTreeSet<String>) {
|
||||
let mut segments: Vec<&str> = path.split("::").collect();
|
||||
segments.pop();
|
||||
let Some((first, hops)) = segments.split_first() else { return };
|
||||
let mut unit = first.to_string();
|
||||
out.insert(unit.clone());
|
||||
for hop in hops {
|
||||
match self.member_unit_in(&unit, hop, Surface::Hierarchical) {
|
||||
Some(next) => {
|
||||
unit = next;
|
||||
out.insert(unit.clone());
|
||||
}
|
||||
None => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -229,8 +229,20 @@ fn a_block_and_its_members_are_hierarchical_only_under_the_dotted_key() {
|
||||
fn an_unnamed_block_declares_nothing_a_path_can_name() {
|
||||
let src = "module u (output logic o);\n if (1) begin\n logic w;\n end\n assign o = genblk1.w;\nendmodule\n";
|
||||
let s = sem(src);
|
||||
assert_eq!(resolution(&s, at(src, "genblk1", 0, 0)), Resolution::NotFound);
|
||||
assert!(s.reference_at(at(src, "genblk1.w", 0, 8)).is_none());
|
||||
// Nothing here declares `genblk1`, so — as the head of a dotted path — it
|
||||
// can only be a top-level module some other file declares (TODO §65.4),
|
||||
// and `w` a member of that module: candidates for the workspace, which
|
||||
// holds no such module. Never this file's unnamed block.
|
||||
let top = Resolution::ExternalCandidate {
|
||||
paths: vec!["genblk1".to_string()],
|
||||
surface: Surface::Hierarchical,
|
||||
};
|
||||
assert_eq!(resolution(&s, at(src, "genblk1", 0, 0)), top);
|
||||
let member = Resolution::ExternalCandidate {
|
||||
paths: vec!["genblk1::w".to_string()],
|
||||
surface: Surface::Hierarchical,
|
||||
};
|
||||
assert_eq!(resolution(&s, at(src, "genblk1.w", 0, 8)), member);
|
||||
assert!(s.symbols_named("genblk1").next().is_none(), "no symbol is invented for it");
|
||||
}
|
||||
|
||||
|
||||
@@ -196,11 +196,21 @@ endmodule
|
||||
let s = sem(src);
|
||||
for (spelling, why) in [
|
||||
("x.bit_field", "a built-in type names no declaration"),
|
||||
("stranger.thing", "the head is not declared here"),
|
||||
("h.absent", "the class is known whole and has no such member"),
|
||||
] {
|
||||
assert!(s.reference_at(tail(src, spelling, 0)).is_none(), "{spelling}: {why}");
|
||||
}
|
||||
// `stranger.thing` was on the list above until TODO §65.4: a head nothing
|
||||
// here declares is the root of a hierarchical name — a top-level module
|
||||
// another file declares (IEEE 1800 §23.6) — so its tail is a candidate
|
||||
// for the workspace (`docs/features/top-rooted-paths/README.md`).
|
||||
assert_eq!(
|
||||
resolution_at(&s, tail(src, "stranger.thing", 0)),
|
||||
Resolution::ExternalCandidate {
|
||||
paths: vec!["stranger::thing".to_string()],
|
||||
surface: vlog_semantic::Surface::Hierarchical,
|
||||
}
|
||||
);
|
||||
// The one that does resolve, so the test is not vacuous.
|
||||
assert_eq!(
|
||||
resolution_at(&s, tail(src, "h.known", 0)),
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
//! Hierarchical paths rooted at a top-level module (TODO §65.4, IEEE 1800
|
||||
//! §23.6): `tb.dut.g_sw[0].buf_q` written in a file that does not declare
|
||||
//! `tb`, and `$root.tb.…`. The head is a candidate for the workspace's unit
|
||||
//! table, every segment after it a candidate on the hierarchical surface of
|
||||
//! the unit before it — and a local of the head's name still wins.
|
||||
//! `docs/features/top-rooted-paths/README.md`.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, ExternalTarget, MemberSite, Resolution, Semantics, Surface,
|
||||
WorkspaceIndex,
|
||||
};
|
||||
|
||||
fn sem(src: &str) -> Semantics {
|
||||
let (file, _) = parse_source_tolerant(src);
|
||||
analyze(&file, src)
|
||||
}
|
||||
|
||||
/// Offset of the `n`th (0-based) occurrence of `needle`, plus `skip` bytes.
|
||||
fn at(src: &str, needle: &str, n: usize, skip: usize) -> u32 {
|
||||
(src.match_indices(needle).nth(n).expect("occurrence must exist").0 + skip) as u32
|
||||
}
|
||||
|
||||
fn resolution(s: &Semantics, offset: u32) -> Resolution {
|
||||
s.reference_at(offset).unwrap_or_else(|| panic!("no reference at {offset}")).resolution.clone()
|
||||
}
|
||||
|
||||
fn candidate(paths: &[&str]) -> Resolution {
|
||||
Resolution::ExternalCandidate {
|
||||
paths: paths.iter().map(|p| p.to_string()).collect(),
|
||||
surface: Surface::Hierarchical,
|
||||
}
|
||||
}
|
||||
|
||||
const DUT: &str = "module dut_a;
|
||||
for (genvar i = 0; i < 2; i++) begin : g_sw
|
||||
logic buf_q;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
const TB: &str = "module tb;
|
||||
dut_a dut ();
|
||||
endmodule
|
||||
";
|
||||
const PROBE: &str = "module probe (output logic o);
|
||||
assign o = tb.dut.g_sw[0].buf_q;
|
||||
endmodule
|
||||
";
|
||||
|
||||
fn index(extra: &[(&str, &str)]) -> WorkspaceIndex {
|
||||
let mut files = vec![("dut_a.sv", DUT), ("tb.sv", TB), ("probe.sv", PROBE)];
|
||||
files.extend_from_slice(extra);
|
||||
WorkspaceIndex::build(files.into_iter().map(|(n, t)| (PathBuf::from("/rtl").join(n), t)))
|
||||
}
|
||||
|
||||
/// What the workspace answers for the reference at `offset`: the kind and
|
||||
/// name of the one declaration, or a description of a non-answer.
|
||||
fn external(s: &Semantics, ws: &WorkspaceIndex, offset: u32) -> String {
|
||||
let id = s.reference_id_at(offset).expect("a reference there");
|
||||
match resolve_external(s, ws).get(id) {
|
||||
Some(ExternalTarget::Resolved(def)) => format!("{:?}", def.kind),
|
||||
Some(ExternalTarget::Ambiguous(defs)) => format!("ambiguous {}", defs.len()),
|
||||
Some(ExternalTarget::StillUnresolved) => "unresolved".to_string(),
|
||||
None => "not a candidate".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_head_and_every_segment_are_candidates_rooted_at_the_head() {
|
||||
let s = sem(PROBE);
|
||||
assert_eq!(resolution(&s, at(PROBE, "tb.", 0, 0)), candidate(&["tb"]));
|
||||
assert_eq!(resolution(&s, at(PROBE, "dut.", 0, 0)), candidate(&["tb::dut"]));
|
||||
assert_eq!(resolution(&s, at(PROBE, "g_sw", 0, 0)), candidate(&["tb::dut::g_sw"]));
|
||||
assert_eq!(resolution(&s, at(PROBE, "buf_q", 0, 0)), candidate(&["tb::dut::g_sw::buf_q"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_workspace_walks_the_path_from_the_top_module() {
|
||||
let (ws, s) = (index(&[]), sem(PROBE));
|
||||
assert_eq!(external(&s, &ws, at(PROBE, "tb.", 0, 0)), "Module");
|
||||
assert_eq!(external(&s, &ws, at(PROBE, "dut.", 0, 0)), "Instance");
|
||||
assert_eq!(external(&s, &ws, at(PROBE, "g_sw", 0, 0)), "Block");
|
||||
assert_eq!(external(&s, &ws, at(PROBE, "buf_q", 0, 0)), "Var");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_root_the_workspace_does_not_declare_stays_unresolved() {
|
||||
let ws = WorkspaceIndex::build(
|
||||
[("dut_a.sv", DUT), ("probe.sv", PROBE)]
|
||||
.into_iter()
|
||||
.map(|(n, t)| (PathBuf::from("/rtl").join(n), t)),
|
||||
);
|
||||
let s = sem(PROBE);
|
||||
assert_eq!(external(&s, &ws, at(PROBE, "tb.", 0, 0)), "unresolved");
|
||||
assert_eq!(external(&s, &ws, at(PROBE, "g_sw", 0, 0)), "unresolved");
|
||||
assert_eq!(external(&s, &ws, at(PROBE, "buf_q", 0, 0)), "unresolved");
|
||||
}
|
||||
|
||||
/// Seventy opentitan testbenches are each `module tb`: `tb.dut` then names
|
||||
/// as many instances, and nothing after it can be told apart.
|
||||
#[test]
|
||||
fn two_top_modules_of_one_name_leave_the_path_unresolved() {
|
||||
let other_tb = "module tb;\n dut_b dut ();\nendmodule\n";
|
||||
let ws = index(&[("tb2.sv", other_tb)]);
|
||||
let s = sem(PROBE);
|
||||
assert_eq!(external(&s, &ws, at(PROBE, "tb.", 0, 0)), "ambiguous 2");
|
||||
assert_eq!(external(&s, &ws, at(PROBE, "dut.", 0, 0)), "ambiguous 2");
|
||||
assert_eq!(external(&s, &ws, at(PROBE, "g_sw", 0, 0)), "unresolved");
|
||||
}
|
||||
|
||||
/// A package or class is not a root a `.` can follow, and a name declared as
|
||||
/// a module in one file and a package in another is no root either.
|
||||
#[test]
|
||||
fn only_a_module_or_an_interface_is_a_root() {
|
||||
let pkg = "package tb;\n logic dut;\nendpackage\n";
|
||||
let ws = WorkspaceIndex::build(
|
||||
[("dut_a.sv", DUT), ("tb_pkg.sv", pkg), ("probe.sv", PROBE)]
|
||||
.into_iter()
|
||||
.map(|(n, t)| (PathBuf::from("/rtl").join(n), t)),
|
||||
);
|
||||
let s = sem(PROBE);
|
||||
assert_eq!(external(&s, &ws, at(PROBE, "tb.", 0, 0)), "unresolved");
|
||||
let ws = index(&[("tb_pkg.sv", pkg)]);
|
||||
assert_eq!(external(&s, &ws, at(PROBE, "tb.", 0, 0)), "unresolved", "module and package");
|
||||
let iface = "interface tb;\n dut_a dut ();\nendinterface\n";
|
||||
let ws = WorkspaceIndex::build(
|
||||
[("dut_a.sv", DUT), ("tb_if.sv", iface), ("probe.sv", PROBE)]
|
||||
.into_iter()
|
||||
.map(|(n, t)| (PathBuf::from("/rtl").join(n), t)),
|
||||
);
|
||||
assert_eq!(external(&s, &ws, at(PROBE, "tb.", 0, 0)), "Interface");
|
||||
assert_eq!(external(&s, &ws, at(PROBE, "buf_q", 0, 0)), "Var");
|
||||
}
|
||||
|
||||
/// The LRM's upward name resolution finds a local first: a `logic tb` makes
|
||||
/// `tb.dut` a select of a net this crate models no members of, and an
|
||||
/// instance named `tb` roots the path in *its* module.
|
||||
#[test]
|
||||
fn a_local_of_the_heads_name_wins() {
|
||||
let net = "module probe (output logic o);\n logic tb;\n assign o = tb.dut.g_sw[0].buf_q;\nendmodule\n";
|
||||
let s = sem(net);
|
||||
let local = s.symbol_at(at(net, "logic tb", 0, 6)).expect("the net");
|
||||
assert_eq!(resolution(&s, at(net, "tb.", 0, 0)), Resolution::Resolved(local));
|
||||
assert!(s.reference_at(at(net, "dut.", 0, 0)).is_none(), "a net has no members");
|
||||
let inst =
|
||||
"module probe (output logic o);\n other tb ();\n assign o = tb.dut.x;\nendmodule\n";
|
||||
let s = sem(inst);
|
||||
let local = s.symbol_at(at(inst, "other tb", 0, 6)).expect("the instance");
|
||||
assert_eq!(resolution(&s, at(inst, "tb.", 0, 0)), Resolution::Resolved(local));
|
||||
assert_eq!(resolution(&s, at(inst, "dut.", 0, 0)), candidate(&["other::dut"]));
|
||||
}
|
||||
|
||||
/// A module this file declares is found lexically, as it always was.
|
||||
#[test]
|
||||
fn a_top_module_declared_in_the_same_file_resolves_in_the_file() {
|
||||
let src = "module tb;\n logic sig;\nendmodule\nmodule probe (output logic o);\n assign o = tb.sig;\nendmodule\n";
|
||||
let s = sem(src);
|
||||
let tb = s.symbol_at(at(src, "module tb", 0, 7)).expect("tb");
|
||||
let sig = s.symbol_at(at(src, "logic sig", 0, 6)).expect("sig");
|
||||
assert_eq!(resolution(&s, at(src, "tb.sig", 0, 0)), Resolution::Resolved(tb));
|
||||
assert_eq!(resolution(&s, at(src, "tb.sig", 0, 3)), Resolution::Resolved(sig));
|
||||
}
|
||||
|
||||
/// QA F2: an import that could supply the head makes it the imported name
|
||||
/// (a local, by the LRM) whether or not the workspace can say so — doubt, so
|
||||
/// nothing is rooted: the head keeps the import's candidate and no segment
|
||||
/// after it is a reference.
|
||||
#[test]
|
||||
fn an_import_in_scope_wins_and_roots_nothing() {
|
||||
let src = "module probe (output logic o);\n import p::*;\n assign o = tb.dut.x;\nendmodule\n";
|
||||
let s = sem(src);
|
||||
let imported = Resolution::ExternalCandidate {
|
||||
paths: vec!["p::*".to_string()],
|
||||
surface: Surface::Connection,
|
||||
};
|
||||
assert_eq!(resolution(&s, at(src, "tb.", 0, 0)), imported);
|
||||
assert!(s.reference_at(at(src, "dut.", 0, 0)).is_none());
|
||||
}
|
||||
|
||||
/// QA F4: a head written inside a class (any class: a member, inherited or
|
||||
/// macro-declared, is never a path lucisv can prove), or in a scope where an
|
||||
/// unexpanded macro stands as an item, roots nothing.
|
||||
#[test]
|
||||
fn a_head_inside_a_class_or_beside_a_macro_item_roots_nothing() {
|
||||
for (src, head) in [
|
||||
// A11: a class with no base, `cfg` declared by a macro.
|
||||
("class env;\n `DECLARE_CFG\n task run(); if (cfg.en) $display(\"x\"); endtask\nendclass\n", "cfg."),
|
||||
// D2: a class in a package writing a hierarchical path (illegal).
|
||||
("package env_pkg;\n class seq;\n task body(); tb.dut.x = 1; endtask\n endclass\nendpackage\n", "tb."),
|
||||
// A12: a module whose `st` comes from a macro.
|
||||
("module user (output logic o);\n `DECL_STRUCT(st)\n assign o = st.a;\nendmodule\n", "st."),
|
||||
// The macro one scope out still casts its doubt inward.
|
||||
("module user (output logic o);\n `DECL_STRUCT(st)\n initial begin : b\n o = st.a;\n end\nendmodule\n", "st."),
|
||||
] {
|
||||
let s = sem(src);
|
||||
assert_eq!(resolution(&s, at(src, head, 0, 0)), Resolution::NotFound, "{src}");
|
||||
let tail = at(src, head, 0, head.len());
|
||||
assert!(s.reference_at(tail).is_none(), "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
/// QA F1: a package sharing the root's name lends the path nothing — neither
|
||||
/// the head nor any segment after it answers — and a package alone is never
|
||||
/// a root (`pk.x` is illegal).
|
||||
#[test]
|
||||
fn a_package_never_lends_a_top_rooted_path_its_members() {
|
||||
let pkg = "package tb;\n logic dut;\nendpackage\n";
|
||||
let other = "module other;\n initial force tb.dut.x = 0;\nendmodule\n";
|
||||
let dut = "module dut_a;\n logic x;\nendmodule\n";
|
||||
let both = WorkspaceIndex::build(
|
||||
[("dut_a.sv", dut), ("tb.sv", TB), ("tb_pkg.sv", pkg), ("other.sv", other)]
|
||||
.into_iter()
|
||||
.map(|(n, t)| (PathBuf::from("/rtl").join(n), t)),
|
||||
);
|
||||
let s = sem(other);
|
||||
for needle in ["tb.", "dut.", ".x"] {
|
||||
let skip = usize::from(needle.starts_with('.'));
|
||||
assert_eq!(external(&s, &both, at(other, needle, 0, skip)), "unresolved", "{needle}");
|
||||
}
|
||||
let user = "module user (output logic o);\n assign o = pk.x;\nendmodule\n";
|
||||
let only = WorkspaceIndex::build(
|
||||
[("pk.sv", "package pk;\n logic x;\nendpackage\n"), ("user.sv", user)]
|
||||
.into_iter()
|
||||
.map(|(n, t)| (PathBuf::from("/rtl").join(n), t)),
|
||||
);
|
||||
let s = sem(user);
|
||||
assert_eq!(external(&s, &only, at(user, "pk.", 0, 0)), "unresolved");
|
||||
assert_eq!(external(&s, &only, at(user, ".x", 0, 1)), "unresolved");
|
||||
}
|
||||
|
||||
/// Inside an extending class the base could supply the head, so it stays the
|
||||
/// base's candidate and no path is rooted at a module.
|
||||
#[test]
|
||||
fn inside_an_extending_class_the_head_is_the_bases() {
|
||||
let src = "class c extends base;\n function void f();\n cfg.dut.x = 1;\n endfunction\nendclass\n";
|
||||
let s = sem(src);
|
||||
assert!(matches!(resolution(&s, at(src, "cfg.", 0, 0)), Resolution::InheritedCandidate { .. }));
|
||||
assert!(s.reference_at(at(src, "dut.", 0, 0)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dollar_root_names_the_top_module_and_skips_the_lexical_walk() {
|
||||
let src = "module probe (output logic o);\n logic tb;\n assign o = $root.tb.dut.g_sw[0].buf_q;\nendmodule\n";
|
||||
let s = sem(src);
|
||||
// The local `tb` is not what `$root.tb` names.
|
||||
assert_eq!(resolution(&s, at(src, "tb.dut", 0, 0)), candidate(&["tb"]));
|
||||
assert_eq!(resolution(&s, at(src, "dut.", 0, 0)), candidate(&["tb::dut"]));
|
||||
assert_eq!(resolution(&s, at(src, "buf_q", 0, 0)), candidate(&["tb::dut::g_sw::buf_q"]));
|
||||
let ws = WorkspaceIndex::build(
|
||||
[("dut_a.sv", DUT), ("tb.sv", TB), ("p.sv", src)]
|
||||
.into_iter()
|
||||
.map(|(n, t)| (PathBuf::from("/rtl").join(n), t)),
|
||||
);
|
||||
assert_eq!(external(&s, &ws, at(src, "tb.dut", 0, 0)), "Module");
|
||||
assert_eq!(external(&s, &ws, at(src, "buf_q", 0, 0)), "Var");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dollar_root_reaches_a_top_module_this_file_declares() {
|
||||
let src = "module tb;\n logic sig;\nendmodule\nmodule probe (output logic o);\n logic tb;\n assign o = $root.tb.sig;\nendmodule\n";
|
||||
let s = sem(src);
|
||||
let tb = s.symbol_at(at(src, "module tb", 0, 7)).expect("tb");
|
||||
let sig = s.symbol_at(at(src, "logic sig", 0, 6)).expect("sig");
|
||||
assert_eq!(resolution(&s, at(src, "tb.sig", 0, 0)), Resolution::Resolved(tb));
|
||||
assert_eq!(resolution(&s, at(src, "tb.sig", 0, 3)), Resolution::Resolved(sig));
|
||||
}
|
||||
|
||||
/// The completion walk (`Semantics::member_site`) does not root an unknown
|
||||
/// head at a top module — a popup after an unknown head answers nothing, so
|
||||
/// the ordinary tiers run, until the language server's member list takes the
|
||||
/// change knowingly (README, Handshakes). `$root.tb.` says what it is and is
|
||||
/// rooted in both walks.
|
||||
#[test]
|
||||
fn the_completion_walk_roots_only_an_explicit_dollar_root() {
|
||||
let s = sem(PROBE);
|
||||
let scope = s.reference_at(at(PROBE, "tb.", 0, 0)).expect("tb").scope;
|
||||
assert_eq!(s.member_site(scope, "tb", &["dut".to_string()]), None);
|
||||
let rooted = s.member_site(scope, "$root", &["tb".to_string(), "dut".to_string()]);
|
||||
assert_eq!(
|
||||
rooted,
|
||||
Some(MemberSite::Unit { path: "tb::dut".to_string(), surface: Surface::Hierarchical })
|
||||
);
|
||||
assert_eq!(s.member_site(scope, "$root", &[]), None);
|
||||
assert_eq!(s.member_site(scope, "`MACRO", &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_system_name_or_a_macro_roots_nothing() {
|
||||
let src = "module probe (output logic o);\n assign o = `TOP.dut.x;\n assign o = $unit.x;\nendmodule\n";
|
||||
let s = sem(src);
|
||||
assert!(s.reference_at(at(src, "dut.", 0, 0)).is_none());
|
||||
assert!(s.reference_at(at(src, ".x;", 1, 1)).is_none());
|
||||
}
|
||||
|
||||
/// QA R1: a macro standing where a declaration could stand — a statement in
|
||||
/// a `begin`/`end`, a task or a function body, or an entry of the port list —
|
||||
/// may declare the head, so nothing is rooted from that scope (or one inside
|
||||
/// it).
|
||||
#[test]
|
||||
fn a_macro_where_a_declaration_could_stand_roots_nothing() {
|
||||
for src in [
|
||||
// E1
|
||||
"module user;\n initial begin\n `DECL_LOCAL(st)\n st.a = 1;\n end\nendmodule\n",
|
||||
// E2
|
||||
"module user;\n task automatic t();\n `DECL_LOCAL(st)\n st.a = 1;\n endtask\nendmodule\n",
|
||||
// E6
|
||||
"module user;\n function automatic void f();\n `DECL_LOCAL(st)\n begin st.a = 1; end\n endfunction\nendmodule\n",
|
||||
// E3, the parse is tolerant of the macro port
|
||||
"module user (`MY_PORTS, output logic o);\n assign o = st.a;\nendmodule\n",
|
||||
// E3, the macro after a port
|
||||
"module user (input logic i, `MY_PORTS);\n initial st.a = i;\nendmodule\n",
|
||||
] {
|
||||
let s = sem(src);
|
||||
let head = at(src, "st.a", 0, 0);
|
||||
assert!(
|
||||
matches!(s.reference_at(head).map(|r| &r.resolution), Some(Resolution::NotFound) | None),
|
||||
"{src}"
|
||||
);
|
||||
assert!(s.reference_at(at(src, "st.a", 0, 3)).is_none(), "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
/// …and the shapes that cannot declare the head keep rooting: a macro used
|
||||
/// as a data type, and a macro in a *sibling* generate block (E7, E8).
|
||||
#[test]
|
||||
fn a_macro_that_cannot_declare_the_head_still_roots() {
|
||||
for src in [
|
||||
"module user;\n `MY_STRUCT_T other;\n initial st.a = 1;\nendmodule\n",
|
||||
"module user;\n if (1) begin : g1\n `DECL_LOCAL(st)\n end\n if (1) begin : g2\n initial st.a = 1;\n end\nendmodule\n",
|
||||
"module user;\n initial st.a = $bits(`WIDTH);\nendmodule\n",
|
||||
] {
|
||||
let s = sem(src);
|
||||
assert_eq!(resolution(&s, at(src, "st.a", 0, 0)), candidate(&["st"]), "{src}");
|
||||
assert_eq!(resolution(&s, at(src, "st.a", 0, 3)), candidate(&["st::a"]), "{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,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,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.
|
||||
|
||||
@@ -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,140 @@
|
||||
# references-fanout-pd-main
|
||||
|
||||
## Goal
|
||||
|
||||
TODO §65.2 (topo §2.9-36, MCP-6): on opentitan, `textDocument/references` at
|
||||
the `aes` instantiation in `hw/ip/aes/dv/tb/tb.sv` and at its `.clk_i`
|
||||
connection answered 11 and 9 locations, while the whole-set engine
|
||||
(`vlog_refactor::find_references` over every file, as `lucisv-mcp`'s
|
||||
`references` runs it) answered 14 and 12 — the same plus the three generated
|
||||
tops `hw/top_{earlgrey,darjeeling,englishbreakfast}/rtl/autogen/*_pd_main.sv`.
|
||||
Find the cause, fix it at the cause, and pin the answer.
|
||||
|
||||
## Root cause
|
||||
|
||||
**It is the index scope, not the fan-out.** The language server runs on the
|
||||
shipped default `lucisv.index.scope: "folder"` with `scopeDepth: 2`
|
||||
(`settings.rs` `DEFAULT_SCOPE_DEPTH`, ladder in `state/scope.rs`). Opening
|
||||
`hw/ip/aes/dv/tb/tb.sv` raises its folder two levels to **`hw/ip/aes`**, and
|
||||
that is the whole index: the three `*_pd_main.sv` tops are never walked, so
|
||||
no index table (units, instantiations, reference postings, words) knows them.
|
||||
`lucisv-mcp` hands the engine every file under the root, which is the
|
||||
`"workspace"` rung's set. The two answers are over different file sets; over
|
||||
the same set they are identical.
|
||||
|
||||
This is the documented behaviour of `docs/features/index-scope` ("cross-file
|
||||
answers are scope-relative … `find_references` and a workspace rename all
|
||||
answer within the active scope"; migration line `"lucisv.index.scope":
|
||||
"workspace"`), chosen 2026-08-27/28 for scan cost.
|
||||
|
||||
Evidence (release `lucisv-server` built at ec492cd, LSP client driving it over
|
||||
stdio, root `ot/hw`, `tb.sv` opened, positions `45:3` `aes` and `50:6`
|
||||
`clk_i`, after the scan's progress end plus 5 s):
|
||||
|
||||
| scope | `aes` | `.clk_i` | files listed |
|
||||
|---|---|---|---|
|
||||
| default (`folder`, depth 2) | 11 | 9 | all under `hw/ip/aes/` |
|
||||
| `index.scope: "workspace"` | **14** | **12** | the 11/9 + `darjeeling_pd_main.sv:1521/1538`, `earlgrey_pd_main.sv:2069/2086`, `englishbreakfast_pd_main.sv:933/950` |
|
||||
|
||||
The workspace-scope answer is exactly MCP-6's 14/12 list. Ruled out, as the
|
||||
lead's pre-investigation suggested: the 1 MiB size cap (the tops are
|
||||
62–141 kB and are indexed under the workspace scope), `.gitignore`/the walk
|
||||
(`autogen` is walked under the workspace scope), and the multi-line
|
||||
`aes #( … ) u_aes (` shape (indexed and answered under the workspace scope).
|
||||
`state/sources.rs` (`module_sources`, `rename_sources_traced`, `fan_out_of`)
|
||||
and `nav.rs`'s indexed-references path are correct: within the scope they
|
||||
equal the engine over `Workspace::sources()`.
|
||||
|
||||
**Rename has the same scope relation and no gap of its own.** Probe over the
|
||||
same checkout: a rename of `aes` from `tb.sv:45` edits 14 sites in 9 files
|
||||
under the workspace scope (the three tops included) and 11 sites in 6 files
|
||||
under the folder scope. The latter is the sharper consequence: under the
|
||||
default scope a module rename from the testbench would leave the three tops
|
||||
instantiating a module that no longer exists. That is the index-scope
|
||||
README's stated trade-off, but it is a correctness hazard for a write, not
|
||||
only an incomplete read — flagged for the lead below.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- "The whole-set engine" means `vlog_refactor::find_references` over every
|
||||
file the client's root holds, as `lucisv-mcp` runs it; the server's answer
|
||||
is compared to it over the same file set.
|
||||
- The folder scope's documented behaviour stands until the lead rules
|
||||
(Handshakes); nothing in this lane changes which files are indexed.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Ruling request → lead (the fix is outside this lane's files).** The
|
||||
cause is the shipped default scope, which lives in
|
||||
`crates/lucisv_server/src/settings.rs` (`IndexScope::default`,
|
||||
`DEFAULT_SCOPE_DEPTH`) and `state/scope.rs`, and is a product decision
|
||||
recorded in `docs/features/index-scope`. Not edited. Options:
|
||||
1. **Keep the design; close §65.2 as scope-relative by design.** The tests
|
||||
below pin both halves. Optionally document it where users meet it (the
|
||||
VS Code setting's description, the README's LSP section).
|
||||
2. **Widen only for writes.** A cross-file rename (and port refactorings)
|
||||
on a unit whose instantiations may exist outside the folder scope runs
|
||||
against the workspace walk, or refuses with "outside the index scope —
|
||||
set `lucisv.index.scope: workspace`". Closes the hazard above without
|
||||
changing read latency. Touches `state/sources.rs` (`fan_out_of` /
|
||||
`rename_sources_traced`) and the rename handler.
|
||||
3. **Change the default to `"workspace"` when the client has roots.**
|
||||
Restores pre-2026-08-27 behaviour; costs the full scan the index-scope
|
||||
round removed (opentitan: ~4 000 files; the persistent cache and the
|
||||
interleaved scan now bound it). `settings.rs`, the index-scope README,
|
||||
release notes.
|
||||
- Consumed, unchanged: `Workspace::sources()`, `WorkspaceIndex::files()`,
|
||||
`vlog_refactor::find_references`. No handshake changed.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Reproduce at the LSP level (11/9 default scope; 14/12 workspace scope)
|
||||
- [x] Root cause named: the folder index scope (`hw/ip/aes`), not the fan-out
|
||||
- [x] Rename's fan-out checked: same scope relation, no separate gap
|
||||
- [x] Fixture regression tests (`server/tests/references_scope.rs`, 3 tests)
|
||||
- [x] Ignored opentitan test (`tests/opentitan_references.rs`, 2 tests)
|
||||
- [ ] Fix — pending the lead's ruling (Handshakes); no code fix was needed in
|
||||
`sources.rs`/`nav.rs`
|
||||
- [ ] QA
|
||||
|
||||
## Work log
|
||||
|
||||
- **2026-10-19 (dev).** Fast-forwarded the lane worktree from 75d2d37 to the
|
||||
wave's base ec492cd (TODO-only commit). Built release `lucisv-server` and
|
||||
drove it with a scratch stdio LSP client: default scope 11/9, all locations
|
||||
under `hw/ip/aes/`; `index.scope: "workspace"` 14/12, exactly MCP-6's list.
|
||||
So the gap is the scope, and the fan-out code is correct — nothing in
|
||||
`sources.rs` or `nav.rs` changed. Rename probe: 9 files/14 edits (workspace)
|
||||
vs 6 files/11 edits (folder) for `aes`; the `.clk_i` rename under the
|
||||
workspace scope refuses over an unrelated implicit `.clk_i` binding in
|
||||
`hw/ip/keymgr_dpe/dv/tb.sv` (the existing safety refusal), under the folder
|
||||
scope it edits 16 sites in 6 files.
|
||||
Tests: `server/tests/references_scope.rs` — opentitan's shape in miniature
|
||||
(`ip/blk/rtl/blk.sv`, `ip/blk/dv/tb/tb.sv`, `top/rtl/autogen/top_pd_main.sv`
|
||||
with a multi-line `blk #( … ) u_blk (`): (1) whole workspace: LSP ==
|
||||
engine over every file, for the module name and `clk_i`, each from its
|
||||
declaration and from a use, and the top is listed; (2) folder scope: the top
|
||||
is not in the index, LSP == engine over `Workspace::sources()` at the same
|
||||
four positions, the top absent; opening the top widens the scope and the
|
||||
answer becomes the whole set's; (3) whole workspace: a module rename from
|
||||
the testbench edits the top. `tests/opentitan_references.rs` (ignored, skips
|
||||
without the checkout): pins 14/12 with the three tops under the workspace
|
||||
scope, and 11/9 all-in-`hw/ip/aes` under the default. Ran both ignored tests
|
||||
against `~/.cache/lucisv-eval/ot`: pass (17.8 s, debug); with
|
||||
`LUCISV_OPENTITAN=/nonexistent` both skip and pass.
|
||||
|
||||
## QA log
|
||||
|
||||
## Review
|
||||
|
||||
**2026-10-19 — lead (owner's ruling).** The owner chose **keep as
|
||||
designed**: cross-file answers stay relative to the index scope, and §65.2
|
||||
is closed as scope-relative by design rather than as a defect. The lane's
|
||||
tests are merged as the pin of both halves (the workspace scope equals the
|
||||
whole-set engine, the folder scope equals the engine over the scope, the
|
||||
opentitan 14/12 vs 11/9). The rename consequence is now said in the
|
||||
`lucisv.index.scope` setting's description (a rename of a module
|
||||
instantiated outside the scope leaves those instantiations unchanged). No
|
||||
production code changed, so no QA lane was run; the lead reviewed the
|
||||
tests.
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
# release-gates — TODO §65.3: a dependable release gate script
|
||||
|
||||
## Goal
|
||||
|
||||
`cargo test --workspace` under `tools/guard.sh` kept hitting the guard's
|
||||
wall clock (2026-09-29 in `Doc-tests vlog_linter`, 2026-09-30 at the start
|
||||
of `tests/rename_implicit.rs`, 2026-10-07 launching
|
||||
`vlog_semantic/tests/struct_members`, 2026-10-14 in
|
||||
`vlog_refactor/tests/corpus.rs`), while every per-crate run passed. Name
|
||||
the cause, fix whatever part of it is ours, and replace the three-command
|
||||
gate in `tools/RELEASING.md` with `tools/gates.sh`: fmt, clippy, the test
|
||||
build, each crate's suites, the doc-tests, the corpus gate and the node
|
||||
tests as **separate guarded steps**, each with its own log, a kill retried
|
||||
once and shown as such, and a summary table — so a stall names the step it
|
||||
happened in instead of eating a 30-minute guard.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- The gates run on the release Mac (Apple Silicon, 10 cores, 64 GB), the
|
||||
same host the Gitea runner uses. The `-t`/`-m` limits are sized for it;
|
||||
a slower machine may need larger clocks (edit `limits()`).
|
||||
- No gate reads stdin; `gates.sh` gives every step `/dev/null`.
|
||||
- The corpus lives at `~/.cache/lucisv-corpus` as in CI
|
||||
(`.gitea/workflows/ci.yml`); `-c` points elsewhere. Absent → the step is
|
||||
skipped with a note, which does not fail the run (CI is where the corpus
|
||||
gate is mandatory).
|
||||
- The workspace `members` in the root `Cargo.toml` are all under
|
||||
`crates/`, one per line, and each member's first `name =` line is its
|
||||
package name. `gates.sh` reads the crate list from there.
|
||||
- A guard kill is identified by exit 137 **and** guard.sh's `killing` line
|
||||
in the step log; a 137 without that line (a test binary SIGKILLed by
|
||||
something else) is an ordinary failure and is not retried.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes** `tools/guard.sh` (`-t`, `-m`, exit 137 + `guard.sh: …
|
||||
killing: …` on stderr), `scripts/corpus_gate.sh <dir>` (needs
|
||||
`target/release/lucisv`, so the corpus step builds it first, as CI does),
|
||||
`node --test`, cargo.
|
||||
- **Changes `tools/guard.sh`** (two fixes, both ours, see Work log):
|
||||
a closed stdin no longer makes the command silently not run, and the
|
||||
memory limit now sees processes three or more levels down the tree.
|
||||
The second is a **behaviour change for every guarded command**: memory
|
||||
that was invisible (rustc/linker processes under cargo, binaries a test
|
||||
spawns, the corpus scorer's `lucisv` processes) is now summed, so a
|
||||
command whose real tree exceeded its `-m` and used to pass will now be
|
||||
killed. Measured peaks are below; a guard kill after this change is a
|
||||
finding, per CLAUDE.md, not a reason to raise the limit silently.
|
||||
- **Promises** `tools/gates.sh` exit 0 only if every selected step passed
|
||||
(or was the corpus step skipped for a missing corpus); logs kept under
|
||||
the log dir: `<step>.log`, `<step>.killed.log` for a first attempt the
|
||||
guard killed, `summary.txt`, `steps.tsv` (step, start, end epoch, result).
|
||||
- **CLAUDE.md request (the lead's file):** under "Rust standards", replace
|
||||
the first bullet's tail so it reads:
|
||||
|
||||
> - `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
|
||||
> without a comment explaining why), `cargo test` green — all three
|
||||
> before declaring any work finished. **Before a release, and whenever
|
||||
> the whole workspace is gated, run `tools/gates.sh`** (every gate as a
|
||||
> separate guarded step with kept logs; `--only`/`--skip` for a subset)
|
||||
> instead of a bare `cargo test --workspace`.
|
||||
|
||||
and in "Runaway guard", after the first bullet:
|
||||
|
||||
> - The release gate is `tools/gates.sh`, which guards each step with
|
||||
> its own limits; do not wrap it in another `guard.sh`.
|
||||
- **Request (root `README.md`, not this lane's file):** its build section
|
||||
(line ~1042) still shows `tools/guard.sh -- cargo test --workspace`; a
|
||||
pointer to `tools/gates.sh` there would match RELEASING.md.
|
||||
- **Request (lane A / `lucisv_server`, not this lane's file):** the
|
||||
wall-clock assertion in `crates/lucisv_server/src/large.rs:884`
|
||||
(`LOCATE_BUDGET_MS = 150`) flaked once under load (Work log); make it
|
||||
relative or widen it so the gate stays deterministic.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] investigate: stall reproduction attempt, syspolicyd, stuck tree
|
||||
- [x] doc-test stdin question: closed / `/dev/null` / pipe / tty / tty with
|
||||
job control, under the guard, in the background
|
||||
- [x] fix what is ours: guard.sh closed-stdin, guard.sh deep-tree memory
|
||||
- [x] `tools/gates.sh` with `--only`, `--skip`, `--list`, `-o`, `-c`, `--help`
|
||||
- [x] kill → retry path exercised (killed → pass, killed → killed, plain
|
||||
failure not retried, corpus skipped)
|
||||
- [x] two full runs recorded
|
||||
- [x] ten consecutive green runs (runs 3–12; thirteen green in all, no kills)
|
||||
- [x] `tools/RELEASING.md` step 3 points at `tools/gates.sh`
|
||||
- [ ] CLAUDE.md pointer (lead, at merge)
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-10-19 — investigation
|
||||
|
||||
Base: master ec492cd (the worktree was created one commit behind it, at
|
||||
75d2d37; fast-forwarded before any work). Lane A (§65.2) ran its own
|
||||
`lucisv_server` tests in another worktree throughout: load average 6–10 on
|
||||
10 cores for the whole session, so every timing below was taken under a
|
||||
second, unrelated workload — the 2026-10-14 condition.
|
||||
|
||||
**The stall did not reproduce.** The host had been up 1 h 13 min (rebooted
|
||||
that morning). `syspolicyd` sat at 0.0 % CPU at the start, never above 0.3 %
|
||||
in any 1 s sample across the twelve full gate runs, and showed nothing over
|
||||
1 % in 0.2 s samples during a freshly-linked suite's first run. Five freshly
|
||||
linked unique binaries (`rustc` of a one-line `main`, each with a distinct
|
||||
constant, i.e. a distinct cdhash as a doc-test's `rust_out` has) launched in
|
||||
10 ms the first time and 10 ms the second. `cargo clean -p lucisv_server`
|
||||
then a first and second run of its suites: 2.2 s and 2.2 s. So there was no
|
||||
stuck tree to inspect; the cause recorded on 2026-09-30 (syspolicyd stuck at
|
||||
~100 % CPU on notarization lookups, `-67062`, for hours, each first launch of
|
||||
a new unsigned executable waiting on it) stands unrefuted and unreproduced,
|
||||
and it fits every recorded stall: each one sat at the **first launch of a
|
||||
freshly linked binary** — a test binary just rebuilt
|
||||
(`rename_implicit`, `struct_members`, `corpus.rs`) or the doc-test phase,
|
||||
where `vlog_linter`'s `lib.rs` example is the **only runnable doc-test in the
|
||||
workspace** (`cargo test --workspace --doc`: 1 test), and rustdoc links it
|
||||
into a new `rust_out` with a new hash on every run, so it can never hit
|
||||
syspolicyd's cache. That is why "Doc-tests vlog_linter" is where 2026-09-29
|
||||
sat. Healthy after a reboot, sick after hours of uptime: the host fix (System
|
||||
Settings → Privacy & Security → Developer Tools: allow the terminal / Claude
|
||||
app, or restart syspolicyd) is the owner's, not the repo's. `DevToolsSecurity
|
||||
-status` reports developer mode disabled; `spctl --status`: assessments
|
||||
enabled.
|
||||
|
||||
**The doc-test stdin question — not the cause.** `cargo test --workspace
|
||||
--doc` under `tools/guard.sh`, backgrounded, with each kind of stdin (script
|
||||
kept in the session scratchpad; results):
|
||||
|
||||
| stdin | result |
|
||||
|---|---|
|
||||
| closed (`<&-`) | **exit 1 in 0 s, nothing ran** — `guard.sh: line 34: 0: Bad file descriptor`, then `3: Bad file descriptor` (a guard bug, fixed below) |
|
||||
| `/dev/null` | exit 0, 1 s, 1 passed |
|
||||
| a pipe whose writer never closes | exit 0, 1 s, 1 passed |
|
||||
| a pty (`script`), no job control | exit 0, 1 s, 1 passed |
|
||||
| a pty with job control (`set -m`: the job in a background process group, as `guard.sh … &` typed at a prompt) | exit 0, 1 s, 1 passed — no SIGTTIN stop |
|
||||
|
||||
The harness never reads stdin: rustdoc feeds each doc-test to `rustc` over a
|
||||
pipe of its own and runs `rust_out` with `Command::output()`, which gives it
|
||||
`/dev/null`. No test in the workspace spawns a child that inherits stdin and
|
||||
reads it (every `spawn()` in `crates/*/tests` pipes stdin; the one inherited
|
||||
`status()`, `lucisv_server/tests/e2e.rs:571`, runs `lucisv check --fix
|
||||
<file>`, which does not read it).
|
||||
|
||||
**Fixed — ours, both in `tools/guard.sh`:**
|
||||
|
||||
1. *Closed stdin*: `exec 3<&0` failed, then `"$@" <&3` failed, so the
|
||||
command silently never ran (exit 1). Now `{ exec 3<&0; } 2>/dev/null ||
|
||||
exec 3</dev/null`. `lucisv -` still reads stdin through the guard,
|
||||
foreground and backgrounded (checked: formatted output both ways); with a
|
||||
closed stdin it now reads an empty `/dev/null` instead of not running.
|
||||
2. *The memory limit was blind three levels down.* `tree()` appended
|
||||
`"$all $next"` where `next` ended in a space, so from the second level of
|
||||
descendants on the list had a doubled space, `tr ' ' ,` made `a,,b`, and
|
||||
macOS `ps -p` rejects the whole list on an empty element ("Invalid
|
||||
(zero-length) process id") — RSS summed to 0 and the limit could never
|
||||
fire. Every real guarded command is that deep: cargo → rustc → ld, cargo →
|
||||
test binary → spawned `lucisv-server`/`lucisv-mcp`, the corpus scorer's
|
||||
`lucisv` processes. Reproduction (a perl process holding 1.5 GB for 8 s,
|
||||
`-m 1`): at depth 1 and 2 killed in 3 s; at depth 3 **ran to completion,
|
||||
exit 0** before the fix; killed in 3 s after it. The awk now prints
|
||||
`" %s"` and the loop appends without a separator, so the list is single-
|
||||
spaced; the kill path uses the same list and was re-checked (depth-3 hog
|
||||
killed, nothing left behind). Not related to the stalls (it can only
|
||||
cause *fewer* kills), but it is the runaway guard CLAUDE.md relies on.
|
||||
|
||||
**Also observed, not ours to fix (lane A owns the crate):**
|
||||
`lucisv_server` `large::tests::references_on_one_giant_line_locate_their_hits_in_linear_time`
|
||||
failed once, on the first run after `cargo clean -p lucisv_server`, under
|
||||
lane A's load: "locating 800 hits on one line cost 185.450583ms" against
|
||||
`LOCATE_BUDGET_MS = 150` (`crates/lucisv_server/src/large.rs:884`, budget at
|
||||
:896); the 400-hit pass on the same run took 17 ms, so it was a scheduling
|
||||
hiccup, not the quadratic rescan. The immediate rerun passed and so did all
|
||||
thirteen gate runs. A wall-clock budget in a debug-build unit test is a
|
||||
flake source for any gate; filed here as a request for the lead (widen the
|
||||
budget or compare the 800-hit time against the 400-hit time instead of an
|
||||
absolute).
|
||||
|
||||
**Also observed: feature unification rebuilds.** `cargo test -p <crate>`
|
||||
after `cargo test --workspace --all-targets --no-run` recompiles a few crates
|
||||
(`crossbeam-utils`, `lsp-server`, `lucisv_server`: 16 s in run 1) because
|
||||
resolver 2 unifies features per selected package set; both variants are
|
||||
cached afterwards. The per-crate clocks allow for it.
|
||||
|
||||
### 2026-10-19 — `tools/gates.sh`
|
||||
|
||||
Steps, logs, retry and summary as in the header comment and Handshakes.
|
||||
Design points: the command for each step is a bash array (no `eval`); the
|
||||
crate list comes from the root `members`, each member's `name`; a guard
|
||||
kill is exit 137 *and* the guard's line, retried once with the first log
|
||||
kept as `<step>.killed.log`; every step gets `/dev/null` as stdin; node 22+
|
||||
prints `ℹ pass N` rather than TAP's `# pass N` and both are counted; the
|
||||
corpus step builds `target/release/lucisv` first, as CI does; unknown step
|
||||
names are a usage error (exit 2).
|
||||
|
||||
Exercised paths (a throwaway copy of the script with a 2 s clock on a
|
||||
`sleep 30`, deleted after): killed → retried → KILLED (exit 1), killed →
|
||||
retried → pass (a command that sleeps only on its first call; exit 0, first
|
||||
log kept), a plain failure (`node -e 'process.exit(3)'`) reported `fail` and
|
||||
not retried, the corpus step `SKIPPED (no corpus)` with `-c /nonexistent`
|
||||
and the run still green.
|
||||
|
||||
Limits (`limits()`; measured 2026-10-19 from a cold `target/`, peak tree RSS
|
||||
sampled each second over the whole step tree):
|
||||
|
||||
| step | measured cold | warm (runs 3–12) | peak RSS | `-t` / `-m` |
|
||||
|---|---|---|---|---|
|
||||
| fmt | 3 s | 2 s | 0.1 GB | 120 s / 2 GB |
|
||||
| clippy | 20 s | 1–2 s | 1.6 GB | 900 s / 6 GB |
|
||||
| build | 31 s | 1–2 s | 2.6 GB | 900 s / 8 GB |
|
||||
| suite: each small crate | ≤ 3 s | 1–4 s | ≤ 0.15 GB | 300 s / 4 GB |
|
||||
| suite:lucisv_server | 17–19 s (rebuild) | 2–4 s | 1.1 GB | 600 s / 4 GB |
|
||||
| suite:lucisv_mcp | 20–22 s | 12–15 s | 1.4 GB | 600 s / 4 GB |
|
||||
| docs | 1 s | 1 s | 0.1 GB | 300 s / 2 GB |
|
||||
| corpus (release build + score) | 30 s | 3–4 s | 1.2 GB | 900 s / 6 GB |
|
||||
| node | 1 s | 1 s | 0.3 GB | 120 s / 2 GB |
|
||||
|
||||
The clocks are the cold time times twelve (the CPU-bound slowdown a sick
|
||||
syspolicyd was measured to cost) rounded up, with a two-minute floor: a
|
||||
real hang costs at most that step's clock twice, not 30 minutes; a stall
|
||||
that clears on the retry shows as `KILLED → retried → pass`.
|
||||
|
||||
### 2026-10-19 — runs
|
||||
|
||||
Thirteen full runs, all `gates: PASS`, **zero kills, zero retries, zero
|
||||
failures**: run 1 (warm, before the deep-tree guard fix and with the first
|
||||
draft limits), run 2 (after `cargo clean`, limits as drafted), runs 3–12
|
||||
(final limits, back to back: 33–38 s each), run 13 (the final script, after
|
||||
a summary-alignment change; default log dir). Runs 3–12 are §65.3's ten
|
||||
consecutive green runs. Honest caveat: the host was healthy all session
|
||||
(syspolicyd ≤ 0.3 %), so these runs prove the script and the gates, not
|
||||
immunity to the host fault — that would show as a `KILLED → retried` row.
|
||||
|
||||
Run 2 (cold):
|
||||
|
||||
```
|
||||
step result seconds passed/failed
|
||||
fmt pass 3 -
|
||||
clippy pass 20 -
|
||||
build pass 31 -
|
||||
suite:vlog_parser pass 3 505/0
|
||||
suite:vlog_semantic pass 1 401/0
|
||||
suite:vlog_refactor pass 1 727/0
|
||||
suite:vlog_formatter pass 1 314/0
|
||||
suite:vlog_linter pass 1 672/0
|
||||
suite:lucisv_core pass 1 117/0
|
||||
suite:lucisv pass 2 143/0
|
||||
suite:lucisv_server pass 17 1862/0
|
||||
suite:lucisv_mcp pass 22 383/0
|
||||
docs pass 1 1/0
|
||||
corpus pass 30 814/6
|
||||
node pass 1 8/0
|
||||
gates: PASS
|
||||
```
|
||||
|
||||
Run 13 (final script, warm except clippy/build after `cargo clean -p
|
||||
lucisv_server`): fmt 2, clippy 9, build 14, suites 3/1/1/1/1/2/1/2/12,
|
||||
docs 1, corpus 3, node 1 s — the same counts, `gates: PASS`. The corpus
|
||||
"failed" column is total − passing (6 of 820, the documented ceiling).
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-10-19 — QA agent (Sonnet)
|
||||
|
||||
**Verdict: PASS, no blocking findings; no files fixed (log only).** Host load
|
||||
average 5 to 19 (lane A running suites) throughout. Bash: only `/bin/bash`
|
||||
3.2.57 exists (`which -a bash`), so `#!/usr/bin/env bash` runs 3.2; no
|
||||
bash-4 feature in either script (grep for `declare -A`, `mapfile`,
|
||||
`${v,,}`, `[[`, `+=`, `|&`: none).
|
||||
|
||||
**guard.sh** (diff read line by line: three changes, stdin fallback,
|
||||
awk `" %s"`, `all="$all$next"`; nothing else touched).
|
||||
- Memory depth proof (`nest.sh N`: N nested bash layers, python holding
|
||||
1.5 GB at the bottom, `-m 1 -t 40`; scratch `qaB65/nest.sh`):
|
||||
|
||||
| depth | master guard | new guard |
|
||||
|---|---|---|
|
||||
| 1 | 137, killed in 3 s | 137, 3 s |
|
||||
| 2 | 137, 3 s | 137, 3 s |
|
||||
| 3 | **exit 0 after 31 s, no guard line (missed)** | 137, 4 s, guard line |
|
||||
| 4 | **exit 0 after 31 s (missed)** | 137, 2 s, guard line |
|
||||
|
||||
No `nest.sh` survivors after any run.
|
||||
- Wall clock: `-t 3 -- sleep 30` gives 137 with the guard line in 6 s. TERM
|
||||
escalation: a script and a child both with `trap '' TERM`, `-t 3`: 137 in
|
||||
6 s (3 s + 2 s grace + KILL), no survivors.
|
||||
- Stdin: `echo ... | guard.sh -- lucisv -` formats (foreground); formatted in
|
||||
the background with stdin from a file, from a pipe in a subshell, and from
|
||||
a pipe inside `bash -c '... &'`. Closed stdin (`<&-`): new guard runs the
|
||||
command (`echo` ran, `cat` exits 0); master guard prints "Bad file
|
||||
descriptor" twice and exits 1 without running it (confirmed).
|
||||
- `exit 3` passes through as 3. A 400-subshell fork storm of short-lived
|
||||
children (exiting mid-poll) under `-m 2`: exit 0, stderr empty.
|
||||
macOS pids are at most 99999, so the awk `index()` token match has no
|
||||
prefix-collision risk.
|
||||
- Cosmetic (info): on a kill the shell prints `tools/guard.sh: line 57:
|
||||
<pid> Terminated: 15 "$@" 0<&3` to stderr (seen in the retry logs). It
|
||||
is harmless and gates.sh matches the `guard.sh: ... killing` line instead.
|
||||
|
||||
**gates.sh**
|
||||
- `--help` exit 0; `--list` prints the 15 steps; unknown flag exit 2;
|
||||
`--only nope`, `--skip suite:nope` exit 2 with "unknown step". `--only
|
||||
fmt,node`, `--only docs --skip corpus`, `--only corpus -c /nonexistent`
|
||||
(SKIPPED (no corpus), exit 0, note in corpus.log) all as documented.
|
||||
`-o "dir with space"` works (logs, summary.txt, steps.tsv created).
|
||||
- Scratch copies of the script: a failing node test gives `fail`, summary
|
||||
`gates: FAIL`, exit 1, and a single attempt (no `.killed.log`); a step
|
||||
killed twice (2 s clock on `sleep 30`) gives `KILLED → retried → KILLED`,
|
||||
exit 1, `node.killed.log` kept, `steps.tsv` row written; killed once then
|
||||
passing gives `KILLED → retried → pass`, exit 0, `.killed.log` kept.
|
||||
- Crate list: the real `members` (nine, one per line, no comments, no glob)
|
||||
parses to all nine and matches `--list`.
|
||||
- **Full gate, run once, not wrapped:** `tools/gates.sh` printed
|
||||
`gates: PASS`, 36 s wall, zero kills. Warm cache: fmt 2, clippy 1, build 1,
|
||||
suites 3/1/2/1/1/1/1/2/14 (parser, semantic, refactor, formatter, linter,
|
||||
core, lucisv, server, mcp), docs 1, corpus 3 (814/6), node 1 (8/0);
|
||||
counts identical to the dev's run 2 (505, 401, 727, 314, 672, 117, 143,
|
||||
1862, 383, 1 doc-test).
|
||||
|
||||
**Findings** (all low; none block)
|
||||
1. **Low-medium, silent shrink of coverage.** `crates()` at
|
||||
`tools/gates.sh:74-79` drops members it cannot parse and still reports
|
||||
PASS. Reproduced in a scratch workspace: a trailing comment on a member
|
||||
line (`"crates/a", # note`) loses that crate (plus one `sed: ...
|
||||
No such file` on stderr); `members = ["crates/a", "crates/b"]` on one
|
||||
line yields no crates; `"crates/*"` yields no crates. In the last two
|
||||
cases the whole suite phase vanishes and the run is green. The README
|
||||
assumption names the layout, but nothing enforces it. Suggest: fail
|
||||
(exit 2) when `crates` is empty or its count differs from
|
||||
`cargo metadata --no-deps` members. Not a risk with today's Cargo.toml.
|
||||
2. **Low.** `gates.sh:55-57` (`-o`, `-c`, `--only`, `--skip` as the last
|
||||
argument): `$2: unbound variable` under `set -u`, exit 1, not the
|
||||
documented usage error 2. Repro: `tools/gates.sh --only`.
|
||||
3. **Low.** `--only ''` means no filter (all steps run), and a selection
|
||||
that matches nothing (`--only suites --skip suites`) prints an empty
|
||||
table and `gates: PASS`, exit 0. A zero-step run being green is
|
||||
misleading; suggest exit 2 or a "no steps selected" line.
|
||||
4. **Info.** The corpus step is skipped green when `~/.cache/lucisv-corpus`
|
||||
is absent; documented, but a release run on a fresh host would pass
|
||||
without the corpus gate. `RELEASING.md` step 3 says so, which suffices.
|
||||
5. **Info / behaviour change (already in Handshakes).** After the guard fix,
|
||||
memory is now enforced for deep trees. The full gate's peaks stayed under
|
||||
all `-m` limits in this run (no kills), so the limits are sound at
|
||||
least on this host.
|
||||
|
||||
**Review of docs.** `tools/RELEASING.md` step 3 reads correctly and matches
|
||||
the script (steps, log names, retry wording, `--only`/`--skip`/`--list`).
|
||||
Minor: "a line in the release notes' working log" is vague (the repo has a
|
||||
CHANGELOG and README work logs). The proposed CLAUDE.md lines are sensible
|
||||
and consistent: `gates.sh` guards each step itself, so "do not wrap it in
|
||||
another guard.sh" is right (a nested guard would also hide per-step kills).
|
||||
|
||||
## Review
|
||||
|
||||
**2026-10-19 — lead.** Accepted. The two `guard.sh` bugs were the real
|
||||
find: the memory limit never saw a process three or more levels down the
|
||||
tree (every cargo → rustc → linker chain), and a closed stdin skipped the
|
||||
command; QA re-proved both against master's guard. The stall itself is the
|
||||
host's (syspolicyd on fresh unsigned binaries; the owner's Developer Tools
|
||||
setting), and `gates.sh` now survives it by retrying a killed step once and
|
||||
saying so. QA's three lows are fixed by the lead in the worktree before
|
||||
merge: the crate list drops comments and handles a one-line list and a
|
||||
glob, and an empty list is a usage error (exit 2) instead of a green run
|
||||
with no suites; a missing or empty option value is exit 2; a selection that
|
||||
runs no step is exit 2. Granted: the CLAUDE.md lines (Rust standards and
|
||||
Runaway guard) and the root README's Building section now point at
|
||||
`tools/gates.sh`. The ten green runs were on a healthy host — the first
|
||||
`KILLED → retried` row on a stalled one is the evidence still to come.
|
||||
|
||||
@@ -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.
|
||||
@@ -0,0 +1,683 @@
|
||||
# top-rooted-paths
|
||||
|
||||
TODO §65.4 (from §65.1 QA F1). Wave 0.62.0 (§65.7), serial after lane A.
|
||||
|
||||
## Goal
|
||||
|
||||
A hierarchical path whose head is a top-level module declared in another
|
||||
file — `tb.dut.u_x.sig`, the shape every opentitan DV `force`, `$deposit`
|
||||
and `uvm_hdl_*` path takes (IEEE 1800 §23.6: a top-level module name is the
|
||||
root of a hierarchical name) — resolved nothing: `tb` was a `Target::Lexical`
|
||||
use that missed in the writing file, `resolve::head_site` stopped the spine
|
||||
there, no segment after it was a reference, and a rename of `dut`'s
|
||||
declarations left the path behind (since §65.1 with a warning). The goal is
|
||||
that such a path resolves through the workspace exactly as an instance path
|
||||
does, so `find_references` and LSP references list its segments and `rename`
|
||||
rewrites them, while a root the workspace does not declare stays unchanged
|
||||
and is warned about.
|
||||
|
||||
## Design
|
||||
|
||||
- **The head is its own target.** `bind/expr.rs`: the bare identifier that
|
||||
heads a dotted path (`ExprKind::Member` whose base is an `Ident`) is bound
|
||||
as `Target::PathHead` instead of `Target::Lexical`. Only the head of a dotted
|
||||
path: a bare identifier anywhere else is unchanged, so a value-position miss
|
||||
is still never swept through the unit table (the reason `lexical`'s doc
|
||||
gives). The `with`/`bind` funnel in `bind/mod.rs::use_member` treats
|
||||
`PathHead` exactly as `Lexical`.
|
||||
- **`resolve/root.rs` (new)** holds the root rules. **The governing rule
|
||||
(lead, after QA): a path is rooted only when this file shows the head can
|
||||
be nothing but a top-level module or interface; in doubt it is not, and the
|
||||
path stays unresolved and warned about.**
|
||||
- `roots_at_top(scopes, from)`: false when any scope from the use up to
|
||||
the file is a class (a member, inherited or macro-declared, is never a
|
||||
provable path into the hierarchy; a class in a package may not reference
|
||||
it at all) or holds an unexpanded macro invocation where a declaration
|
||||
could stand (`Scope::macro_items`, set by `Binder::mark_macro_declarations`
|
||||
for an item, a statement or block item in any `begin`/`end`, `fork`, task
|
||||
or function body, and a port-list entry or an unreadable port element;
|
||||
it may declare the name). A macro inside an expression or used as a data
|
||||
type cannot declare a name and does not block.
|
||||
- `path_head`: the lexical answer; on a plain `NotFound` that
|
||||
`roots_at_top` allows, the candidate `ExternalCandidate { paths: [head],
|
||||
surface: Hierarchical }`. An import candidate (`import p::*` in scope,
|
||||
which by the LRM could supply the name) is left exactly as `lexical`
|
||||
gave it, whether or not the workspace can answer it; so is an
|
||||
`InheritedCandidate`.
|
||||
- `unit_root`: the site `MemberSite::Unit { path: head, surface:
|
||||
Hierarchical }`.
|
||||
- `$root.tb.…`: `top_site`/`top_module` look `tb` up at file scope only
|
||||
(an in-file module or interface), else the workspace unit. `$root` skips
|
||||
the lexical walk, so a local `tb` does not capture `$root.tb`.
|
||||
- **`resolve.rs::head_site`**: on a plain `NotFound` that `roots_at_top`
|
||||
allows (the same rule as the head's own reference) the resolution walk
|
||||
answers `root::unit_root(head)`, so the head reference and the segments
|
||||
after it are rooted in one unit; anything else roots nothing. The workspace's
|
||||
`fold_path` then walks `tb` → `dut`'s type → … exactly as for an instance
|
||||
path. A system name or a macro (`$unit`, `` `TOP``) roots nothing.
|
||||
- **The completion walk is unchanged.** `member_site` (what
|
||||
`Semantics::member_site` and the completion popup call) and the resolution
|
||||
walk share `spine_site`, parameterised by `HeadMiss`: `member_of` passes
|
||||
`TopModule`, `member_site` passes `Nothing`. A popup after an unknown head
|
||||
keeps answering `None` (so the ordinary tiers run), which the server's
|
||||
completion tests pin; offering `tb.`'s members is a server-side change
|
||||
(Handshake H2). `$root.tb.` is rooted in both walks.
|
||||
- **Only a module or an interface is a root, and a package is never a
|
||||
hop.** `workspace/external.rs`: a bare path equal to the name on the
|
||||
*hierarchical* surface (only a path head produces one) answers through
|
||||
`root_units` — all instantiable, else nothing. And `fold_path`, on the
|
||||
hierarchical surface, checks every unit it stands in (`design_unit`): the
|
||||
first must be declared and only as modules/interfaces; a later one may not
|
||||
be a module and something else at once (the member table is keyed by name
|
||||
and would merge the two). A later unit that is only a package would need a
|
||||
declaration typed with a package's name, which is not code; the separate
|
||||
"never a package" clause was dropped as unreachable (QA M7). So with a
|
||||
module and a package both named `tb` the head *and* every segment answer
|
||||
nothing, and `pk.x` with only a package `pk` resolves to nothing (QA F1).
|
||||
- **The rename's file set (LSP)**: `WorkspaceIndex::path_units_to(def)`
|
||||
(new, `workspace/path_units.rs`) lists every unit an indexed hierarchical
|
||||
use of `def` walks through — the root and each hop's type — read off the
|
||||
facts the index holds. `lucisv_server/src/state/sources.rs::
|
||||
want_declaration` adds those units' declaring files, so a three-hop
|
||||
`tb.dut.u_core.sig` resolves inside the rename's set as in the whole (QA
|
||||
F3; lead-granted). A unit outside the index scope adds nothing, and the
|
||||
path stays warned about.
|
||||
- **An accurate refusal** (`vlog_refactor/src/rename/mod.rs`): a rename asked
|
||||
at a path segment the workspace could not walk is refused with "`x` is a
|
||||
segment of a hierarchical path lucisv could not resolve to one
|
||||
declaration …", not "declared outside the files lucisv indexes".
|
||||
- **`FACTS_FORMAT` 21 → 22** (`facts.rs`, reason written there): no new
|
||||
field, but new records — a 0.61.0 store would answer as though no DV file's
|
||||
`force tb.dut.…` named anything.
|
||||
- **The §65.1 path warning** (`vlog_refactor/src/rename/paths.rs`): a segment
|
||||
of a top-rooted path (head is `$root`, or the head's reference is a root
|
||||
candidate) whose overlay answer is `StillUnresolved` counts as unresolved,
|
||||
so the warning still fires for a root the workspace does not declare, or
|
||||
declares several times. An `Ambiguous` answer is not flagged: when it can
|
||||
name the renamed declaration `collect_occurrences` already refuses the
|
||||
rename.
|
||||
- **Said once** (Handshake H1, lead-granted): `warnings.rs`'s
|
||||
`unresolved_candidate_warnings` skips a candidate that
|
||||
`paths::names_top_rooted_miss` says the path scan names, so such a line
|
||||
carries only the §65.1 path warning. The file is lexed for that check only
|
||||
when an unanswered candidate is on the hierarchical surface.
|
||||
|
||||
## What resolves now
|
||||
|
||||
- `tb.dut.g_sw[0].buf_q` in a file that does not declare `tb`, with exactly
|
||||
one `module tb` (or `interface tb`) in the set: `tb` → the module, `dut` →
|
||||
the instance, `g_sw` → the block, `buf_q` → the variable. Every segment is
|
||||
a reference: `find_references` lists it, `rename` of any of the four
|
||||
declarations (or from the segment itself) rewrites it, verified as usual.
|
||||
- `$root.tb.dut.…`, the same, and `$root.tb.x` against an in-file `tb`.
|
||||
- Not rooted, by the rule above, and left warned exactly as before §65.4: a
|
||||
head an import could supply, a head inside any class, a head in (or under)
|
||||
a scope holding an item-level macro invocation, a head named both a
|
||||
module and a package, and a package alone.
|
||||
|
||||
## Limits
|
||||
|
||||
- **Several `module tb` in the set** (opentitan: 70 files under `hw/`):
|
||||
`tb` is `Ambiguous`, `tb.dut` names 70 instances, and `member_unit_in`
|
||||
refuses an ambiguous hop, so nothing after the head resolves; the rename
|
||||
leaves the path and warns. Choosing the
|
||||
`tb` whose branch has the next member was considered and rejected: the
|
||||
whole-tree `gen_sw_assigns` case is ambiguous between `keymgr` and
|
||||
`keymgr_dpe` anyway, and an `Ambiguous` answer that can name the renamed
|
||||
declaration makes `collect_occurrences` refuse the whole rename — so
|
||||
branching would turn today's warnings into refusals for every common
|
||||
member name.
|
||||
- **A renamed top module's `tb` heads are references** to it. With several
|
||||
same-named tops a rename of one is refused as ambiguous (pinned:
|
||||
`renaming_one_of_two_same_named_tops_is_refused`); before, the heads were
|
||||
`NotFound` and only the declaration was renamed.
|
||||
- **Any wildcard import in scope stops rooting** — including the
|
||||
`import uvm_pkg::*;` nearly every opentitan DV interface starts with. By
|
||||
the LRM such an import could supply the head, and `uvm_pkg` is not in the
|
||||
tree for the index to rule it out, so the path is doubt. Measured: on
|
||||
opentitan `hw` (and in `hw/ip/keymgr_dpe`) the reference postings are
|
||||
exactly master's — no DV force path roots. Rooting when every supplying
|
||||
import is indexed and shown not to hold the head is possible future work;
|
||||
it would not change opentitan while `uvm_pkg` is outside the tree.
|
||||
- **Any macro where a declaration could stand blocks rooting** from its
|
||||
scope down (lead's R1 ruling): a `` `uvm_info `` statement in the block
|
||||
beside a `force` blocks it too, since the binder cannot tell a logging
|
||||
macro from a declaring one. A macro statement in an unnamed `begin` whose
|
||||
statements bind in the enclosing scope blocks that whole scope.
|
||||
- **Completion after `tb.`** answers nothing (H2, deferred by the lead).
|
||||
- `undeclared-identifier` no longer sees an unknown path head as `NotFound`
|
||||
(it is a root candidate now). Measured on opentitan `hw`: 7 findings
|
||||
before and after, identical.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- A bare identifier followed by `.` whose lexical lookup misses plainly —
|
||||
no import could supply it, no class or item-level macro on the scope
|
||||
chain — is a top-level module name (§23.6); a typo there is an unresolved
|
||||
candidate, not `NotFound`.
|
||||
- Only the head of a dotted path is a root; `tb[0].x` (an indexed head) is
|
||||
not modelled as one.
|
||||
- The surface tag on the head candidate is the only signal that a bare path
|
||||
must be instantiable; nothing else produces a bare hierarchical path.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes**: `WorkspaceIndex::member_unit_in` / `fold_path` (unchanged),
|
||||
`hierarchy::member` (unchanged), `Scope::analysis().external`.
|
||||
- **Promises (changed)**: `Resolution::ExternalCandidate` with
|
||||
`surface: Hierarchical` and a bare path is now produced for a path head;
|
||||
`follow_one` answers it with modules and interfaces only. `Semantics::
|
||||
member_site` is unchanged for every head except `$root`.
|
||||
- **H1 (granted by the lead 2026-10-19, done)**: `warnings.rs`
|
||||
`unresolved_candidate_warnings` skips a segment `paths.rs` names
|
||||
(`paths::names_top_rooted_miss`, `pub(super)`), so an unresolved
|
||||
top-rooted path is said once, in the §65.1 wording.
|
||||
- **F3 (granted by the lead, done)**: `lucisv_server/src/state/sources.rs`
|
||||
`want_declaration` adds the files of `WorkspaceIndex::path_units_to(def)`.
|
||||
**Promised to the server**: `path_units_to` is a pure read of the index's
|
||||
facts (no file is read); its cost is one pass over the reference records
|
||||
of each file holding a use of `def`.
|
||||
- **Outside the listed files, flagged**: `vlog_refactor/src/rename/mod.rs`
|
||||
gained `hierarchical`/`unresolved_path` so the refusal at an unresolved
|
||||
segment is the accurate one the lead's F3 ruling asks for (two call
|
||||
sites, the message only; no rename decision changes).
|
||||
- **H2 (deferred by lead → TODO; `lucisv_server/src/completion/member.rs` untouched)**: to offer
|
||||
`tb.`'s members, call a root-aware member site and answer `None` when the
|
||||
index holds no unit for the root (the server's
|
||||
`an_unresolvable_head_answers_nothing_at_all` must keep passing).
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] root lookup in `head_site`, the head recorded as a module use
|
||||
- [x] QA's repro renames the path instead of warning
|
||||
- [x] the §65.1 warning stays for an undeclared (or ambiguous) root
|
||||
- [x] `find_references` and LSP references list the path segments
|
||||
- [x] the local-shadows-top case
|
||||
- [x] `$root.` (cheap: done)
|
||||
- [x] opentitan index/scan cost before and after; `FACTS_FORMAT` bump reasoned
|
||||
- [x] H1: an unresolved top-rooted path is said once (lead-granted)
|
||||
- [x] rework after QA: F1 (no package root or hop), F2 (an import wins),
|
||||
F3 (LSP rename set holds the path's units; accurate refusal), F4 (no
|
||||
root in a class or beside an item-level macro)
|
||||
- [ ] H2: completion after `tb.` — deferred by lead → TODO
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-10-19 (dev, Opus).** Worktree fast-forwarded ec492cd → 51b975b.
|
||||
|
||||
- Implemented as designed above. `resolve.rs` 559 → 586 production lines
|
||||
(the walk split `spine_site`/`HeadMiss`); the root rules are the new
|
||||
`resolve/root.rs` (29).
|
||||
- Deviation: the planned single walk would have changed completion after an
|
||||
unknown head (two server tests), so completion keeps its walk (H2).
|
||||
- Deviation: rooting a head on an import miss as well as on `NotFound` —
|
||||
opentitan's DV interfaces import packages, so `NotFound`-only would leave
|
||||
the target shape unresolved.
|
||||
- QA's repro `a_path_rooted_at_another_files_top_module_is_never_silently_left_behind`
|
||||
flipped to assert the rename (granted). Other §65.1 tests that used a
|
||||
declared `tb` as the vehicle for an *unresolved* root now drop `tb.sv` from
|
||||
their set (so the root is genuinely undeclared) and gained the declared
|
||||
counterpart asserting the rename: `qa_generate_label.rs` (three rechecks),
|
||||
`qa_warning_scope.rs` (two), `rename_generate_label.rs` (two, wording),
|
||||
`generate_blocks.rs` / `member_access.rs` (an unknown head's tail is now a
|
||||
candidate, not absent), server `rename_generate_label.rs` (shown wording).
|
||||
- Invariant 4: `vlog_refactor/src/check/` untouched.
|
||||
- Tests: `vlog_semantic/tests/top_rooted_paths.rs` (13),
|
||||
`vlog_refactor/tests/top_rooted_paths.rs` (8), one declared-root
|
||||
counterpart in `qa_generate_label.rs`, `vlog_refactor/tests/
|
||||
opentitan_top_rooted.rs` (3, ignored), `lucisv_server/src/server/tests/
|
||||
references_top_rooted.rs` (5). Counts before → after: `vlog_semantic`
|
||||
401 → 414 (4 ignored), `vlog_refactor` 727 → 736 (3 → 6 ignored),
|
||||
`lucisv_server` 1 865 → 1 870 (40 ignored), `lucisv_mcp` 383 → 383;
|
||||
`vlog_linter` 673 → 673. Gates: fmt, clippy `-D warnings`, the four suites
|
||||
green. One `lucisv_server` run lost two `large::` linear-time tests to host
|
||||
load (load average 14–16, another lane's suites); the re-run was green.
|
||||
|
||||
*Opentitan* (eval clone `~/.cache/lucisv-eval/ot`, read-only; release;
|
||||
engine API, nothing written — `vlog_refactor/tests/opentitan_top_rooted.rs`,
|
||||
ignored by default):
|
||||
|
||||
| | before (51b975b) | after |
|
||||
|---|---|---|
|
||||
| `rename gen_sw_assigns`, set `hw/ip/keymgr_dpe` (23 files, the LSP folder scope) | 1 site in 1 file; warnings: `uvm_info` macro arg :523, path :514,515,517 | **4 sites in 2 files** (label + `keymgr_dpe_if.sv:514,515,517`); warning: `uvm_info` :523 only |
|
||||
| same, set `hw` (3 979 files, 70 `module tb`) | 1 site; 4 warnings (2 macro args, 2 path lines `keymgr_if.sv:468,469,471`, `keymgr_dpe_if.sv:514,515,517`) | 1 site; 4 warnings, the same 4 (6 before H1: the 2 candidate lines for the same sites) |
|
||||
| rename time, `hw` | 2.16 s | 2.23 s |
|
||||
| facts, `hw` (encoded) | 54 297 047 B | 54 465 816 B (+0.31 %) |
|
||||
| index postings `reference_sites` / keys | 528 532 / 60 559 | 528 719 / 60 573 |
|
||||
| `WorkspaceIndex::build`, `hw`, best of 3 | 1.65 s | 1.69 s |
|
||||
| `lucisv check hw` wall, two runs each | 1.050 / 1.051 s (re-run 1.059 / 1.063) | 1.064 / 1.065 s |
|
||||
| `lucisv check hw` findings | 1 158 | 1 158, byte-identical output |
|
||||
| `check --select undeclared-identifier hw` | 7 | 7, identical |
|
||||
|
||||
The host was shared with another lane's suites (load average 14–16), so the
|
||||
sub-2 % time deltas are within noise.
|
||||
|
||||
**2026-10-19 (dev, Opus) — H1.** Lead granted H1, deferred H2.
|
||||
`paths::names_top_rooted_miss` (`pub(super)`, wraps `is_segment` +
|
||||
`top_rooted_miss`) is asked by `warnings.rs::unresolved_candidate_warnings`
|
||||
for each unanswered hierarchical candidate; a hit is skipped. The tests that
|
||||
tolerated the duplicate now assert exactly one line again
|
||||
(`qa_generate_label.rs` recheck, `rename_generate_label.rs` back to
|
||||
`warnings.len() == 1`, `top_rooted_paths.rs` two, server
|
||||
`an_unresolved_path_in_an_open_buffer_is_shown_as_a_rename_warning` back to
|
||||
`probe.sv:2:` with no "more"), plus a new
|
||||
`an_unresolved_top_rooted_path_is_named_by_exactly_one_warning` (QA's repro
|
||||
undeclared, and with three `module tb`), and the opentitan whole-tree probe
|
||||
asserts the force lines are said once. Opentitan `rename gen_sw_assigns`
|
||||
over `hw`: **6 → 4 warnings** (2 macro arguments, 2 path lines), 1 site,
|
||||
2.16 s; IP folder unchanged (4 sites in 2 files, 1 warning). Counts:
|
||||
`vlog_refactor` 737 (6 ignored), `lucisv_server` 1 870 (40), `lucisv_mcp`
|
||||
383 (4) — its `a_rename_names_each_same_named_file_by_its_root_relative_path_once`
|
||||
passes with the two path lines and no candidate lines. fmt and clippy clean.
|
||||
|
||||
**2026-10-19 (dev, Opus) — rework after QA.** Governing rule (lead): root
|
||||
only when the engine can show the head is a top module or interface.
|
||||
|
||||
- **F1** (`workspace/external.rs`): `fold_path` checks every unit on the
|
||||
hierarchical surface (`design_unit`): first unit declared and all
|
||||
modules/interfaces; later units never a package nor mixed. Tests:
|
||||
semantic `a_package_never_lends_a_top_rooted_path_its_members`; refactor
|
||||
`qa_f1_a_package_sharing_the_roots_name_lends_the_path_nothing` (QA's
|
||||
B12: renaming the package's `dut`, the module's instance `dut`, or `x`
|
||||
leaves `tb.dut.x` and names it), `qa_f1_a_package_is_never_a_root`
|
||||
(A3/A4).
|
||||
- **F2** (`resolve/root.rs`, `resolve.rs::head_site`): an import candidate
|
||||
is never rooted, and the "bare name last" fallback is gone. Tests:
|
||||
semantic `an_import_in_scope_wins_and_roots_nothing` (replaces
|
||||
`an_import_in_scope_is_tried_before_the_top_module`); refactor
|
||||
`qa_f2_an_imported_head_is_never_rooted_at_a_same_named_module` (A1).
|
||||
- **F3** (`workspace/path_units.rs` new, `lucisv_server/src/state/sources.rs`,
|
||||
`vlog_refactor/src/rename/mod.rs` message): server tests
|
||||
`rename_top_rooted_scope.rs` (5, folder scope): three-hop rename from the
|
||||
declaration and from the segment, the generate-block `buf_q`, LSP equals
|
||||
engine over the scope, and a root outside the scope (warned; segment
|
||||
rename refused with "hierarchical path", not "declared outside"). With
|
||||
the `sources.rs` rung disabled four of the five fail.
|
||||
- **F4** (`Scope::macro_items`, `roots_at_top`): semantic
|
||||
`a_head_inside_a_class_or_beside_a_macro_item_roots_nothing` (A11, D2,
|
||||
A12, and a macro one scope out); refactor
|
||||
`qa_f4_a_head_this_crate_cannot_see_is_never_rooted`.
|
||||
- Mutations: `design_unit` and `roots_at_top` both forced true → both F1
|
||||
refactor tests and the F4 test fail; `head_site` rooting an import
|
||||
candidate again → the F2 test fails.
|
||||
- Changed tests: `rename_generate_label.rs` genblk1 refusal accepts the new
|
||||
message; the opentitan probe's IP-folder test is now
|
||||
`the_ip_folder_leaves_the_imported_head_and_says_so`.
|
||||
- Counts: `vlog_semantic` 416 (4 ignored), `vlog_refactor` 741 (6),
|
||||
`lucisv_server` 1 875 (40), `lucisv_mcp` 383 (4), `vlog_linter` 673 (0);
|
||||
fmt and clippy `-D warnings` clean; every suite through the guard, exit 0.
|
||||
- Opentitan: `lucisv check hw` stdout and stderr byte-identical to master's
|
||||
binary (1 158 lines); `--select undeclared-identifier` identical (7).
|
||||
`rename gen_sw_assigns`: IP folder 1 site, 2 warnings (`uvm_info` :523,
|
||||
path :514,515,517 — `keymgr_dpe_if.sv` imports `uvm_pkg::*`); whole `hw`
|
||||
1 site, 4 warnings, 2.13 s — both exactly master's. Index over `hw`:
|
||||
`reference_sites` 528 532 / keys 60 559, equal to master; facts
|
||||
54 333 266 B (+36 KB, the head candidates).
|
||||
|
||||
**2026-10-19 (dev, Opus) — rework 2 (R1, M7).**
|
||||
|
||||
- **R1**: `Binder::mark_macro_declarations(scope)` (`bind/mod.rs`) is now
|
||||
called for an item-level macro (`bind/item.rs`), a macro statement
|
||||
(`bind/stmt.rs`, `StmtKind::MacroStmt`, on the scope the statement binds
|
||||
in) and a header port list holding a `` ` ``-spelled port or an error
|
||||
element (`bind/item.rs::port_list_may_hide_declarations`, on the module's
|
||||
scope). Tests: semantic
|
||||
`a_macro_where_a_declaration_could_stand_roots_nothing` (E1, E2, E6, E3
|
||||
twice) and `a_macro_that_cannot_declare_the_head_still_roots` (data-type
|
||||
macro, sibling generate block E7, a macro inside an expression); refactor
|
||||
`qa_r1_a_macro_where_a_declaration_could_stand_blocks_rooting` (E1, E2,
|
||||
E6 left and named; E3 left) and
|
||||
`qa_r1_a_macro_off_the_scope_chain_or_as_a_type_still_renames` (E7, E8
|
||||
shape). With both new flag sites disabled the refactor R1 test fails.
|
||||
- **M7**: the later-hop "never a package" clause in `design_unit` dropped
|
||||
as unreachable (argued in its doc comment); the mixed module+package rule
|
||||
still refuses QA's B12, pinned by the F1 tests.
|
||||
- **QA's cases1–6 re-run** against this build (QA's harness
|
||||
`scratchpad/qa654/attack`, outputs in `scratchpad/p654/cases{1..6}.out`).
|
||||
Every rename either rewrites the correct sites or leaves the path and
|
||||
warns:
|
||||
- A1, A3, A4, A7, A8, A10, A11, A12: left and warned. A2: the package
|
||||
variable renamed with its use (correct). A5, A6, A9: the head is a local
|
||||
(clocking block, interface port, virtual interface handle), the path is
|
||||
another declaration, nothing to warn (correct).
|
||||
- B1, B7, B8, B10: renamed correctly (local `tb` elsewhere warned in B1).
|
||||
B2, B3: `$root` paths renamed; the local-`tb` line warned; two `tb`
|
||||
refused. B4: five colliding renames refused. B5: the instance-array
|
||||
path warned, the unpacked array and the instance array name renamed.
|
||||
B6 (bind) and B9 (forward local) warned. B11: warned. B12: both renames
|
||||
leave `tb.dut.x` and warn.
|
||||
- C1: renamed from the declaration, the segment and the label; refs list
|
||||
all three sites.
|
||||
- D1: the unshadowed module's path renamed, the shadowed one warned. D2,
|
||||
D3 (struct field), D6 (typo head): warned; D3's `acc` renamed. D4, D5:
|
||||
renamed correctly.
|
||||
- E1, E2, E3, E4, E5, E6: left and warned. E7 (sibling block) and E9
|
||||
(modport macro): renamed, correctly. E8 (data-type macro): the head is
|
||||
the local `st`, warned as an unresolved candidate.
|
||||
- F3 (`cases6`): each `sig` rename edits exactly its own references.
|
||||
- Counts: `vlog_semantic` 418 (4 ignored), `vlog_refactor` 743 (6),
|
||||
`lucisv_server` 1 875 (40), `lucisv_mcp` 383 (4), `vlog_linter` 673 (0);
|
||||
fmt and clippy `-D warnings` clean; every suite through the guard, exit 0.
|
||||
- Opentitan `lucisv check hw`: stdout and stderr byte-identical to master's
|
||||
binary (1 158 lines); `--select undeclared-identifier` identical (7).
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-10-19 — QA agent (Opus).**
|
||||
|
||||
**Verdict: conditional pass. F1 needs a fix before release, and the lead
|
||||
should rule on F2–F4.** Everything else held: the
|
||||
verifier, the shadow and `$root` rules, the cache bump, opentitan byte
|
||||
identity, and every guard mutated.
|
||||
|
||||
*Gates* (worktree as handed over, 51b975b + dev diff; every suite through
|
||||
`tools/guard.sh`, guard exit 0 each, logs kept):
|
||||
- `cargo fmt --all --check` clean, and `clippy --workspace --all-targets -D
|
||||
warnings` clean.
|
||||
- Suites: `vlog_semantic` 414 passed (4 ignored), `vlog_refactor` 737 (6),
|
||||
`lucisv_server` 1 870 (40), `lucisv_mcp` 383 (4), `vlog_linter` 673 (0).
|
||||
All 0 failed, and every count matches the work log. No host stall.
|
||||
|
||||
*Tests read.* The new semantic, refactor and server tests assert what their
|
||||
names say: exact `file:line` sets, the exact texts after the edit, and
|
||||
warning counts. Flipped tests:
|
||||
- `qa_generate_label.rs` and `qa_warning_scope.rs` now drop `tb.sv`, so the
|
||||
root is really undeclared, and each gained a declared counterpart. That is
|
||||
sound.
|
||||
- The server rename test covers only the block label `g_sw`, which is one hop
|
||||
below the root's child. That is exactly the case F3 does not hit.
|
||||
|
||||
*Mutations.* Each was applied in a scratch copy of the workspace
|
||||
(`scratchpad/qa654/ws`), never in this tree, and each ran the semantic,
|
||||
refactor and server suites:
|
||||
- M1: remove the module/interface-only rule in `root_units`. Caught by 1
|
||||
semantic test (`only_a_module_or_an_interface_is_a_root`); 0 refactor or
|
||||
server failures.
|
||||
- M2: a local of the head's name no longer shadows, in both `path_head` and
|
||||
`head_site`. Caught by 70 semantic and 37 refactor failures.
|
||||
- M3: `$root.tb` ignores an in-file `tb`, in `top_site` and `top_module`.
|
||||
Caught by 1 semantic test (`dollar_root_reaches_a_top_module_this_file_declares`).
|
||||
- M4: `$root.tb` goes through the lexical walk, so a local `tb` captures it.
|
||||
Caught by 2 semantic tests (`dollar_root_names_the_top_module_and_skips_the_lexical_walk`
|
||||
and the previous one).
|
||||
- All four are caught. M1 and M3 are each pinned by a single unit test, and
|
||||
nothing at the rename level pins them.
|
||||
|
||||
*Verifier (invariant 4; `check/` untouched).* 8 masked-corruption attacks
|
||||
went into a scratch-only `check/qa_top_rooted.rs` over `dut_a` / `tb` /
|
||||
`probe` (`tb.dut.buf_q` ×2 and `$root.tb.dut.buf_q`). All 8 behaved: three
|
||||
honest edit sets verify, and every corrupt one is refused:
|
||||
- a leaf rename missing each one of the 3 path segments, or missing the
|
||||
declaration;
|
||||
- a top-module rename missing each one of the 3 heads, or also renaming a
|
||||
local `logic tb`;
|
||||
- an instance rename missing each segment.
|
||||
|
||||
*Opentitan* (`~/.cache/lucisv-eval/ot`, read-only, `git status` clean before
|
||||
and after):
|
||||
- **`lucisv check --no-cache hw`.** Master 51b975b, built in a scratch `git
|
||||
worktree` that has since been removed, and this branch both print 1 158
|
||||
lines. stdout and stderr are byte-identical.
|
||||
- **`--select undeclared-identifier`.** Identical, 7 findings.
|
||||
- **`find_references` at 48 seeded random positions.** Half of them follow a
|
||||
`.`, over `hw/ip/{keymgr_dpe,aes,uart,i2c}`. Before and after are
|
||||
byte-identical.
|
||||
- **Targeted top-rooted positions.** These were `pwrmgr_if.sv:191`
|
||||
`tb.dut.u_slow_fsm…`, and `otp_ctrl_if.sv:169/287` and `tb.sv:248` under
|
||||
`top_earlgrey/ip_autogen/{pwrmgr,otp_ctrl}`. Every difference is a segment
|
||||
of a top-rooted path that now has references where it had none. For
|
||||
example, `gen_partitions` went from no symbol to 12 references (10 force
|
||||
and release lines, `tb.sv` and the RTL label), and `u_slow_fsm` went from
|
||||
none to 4.
|
||||
- **No other names changed.**
|
||||
|
||||
*`FACTS_FORMAT` 22.* The server ran over one fixture first with master's
|
||||
binary (format 21), then with this branch. The new server analysed every
|
||||
file afresh, with no `cached:` lines, and answered with the new references.
|
||||
A second run of the new server read its own cache. The unit tests
|
||||
`index_cache.rs:846` and `qa_m6.rs:367` already reject every older format.
|
||||
|
||||
*Code.*
|
||||
- No new `unwrap`, `expect` or `panic`. The index arithmetic in `paths.rs`
|
||||
`path_head` and `matching_open` is guarded.
|
||||
- Production lines: `resolve.rs` 586, which is under 600 but at the mark, so
|
||||
the next arm goes in a module. `resolve/root.rs` is 29, `paths.rs` 158,
|
||||
`warnings.rs` 555, `external.rs` 224.
|
||||
- `warnings.rs::unresolved_candidate_warnings` is now about 79 lines,
|
||||
including its doc comment. That is just under the 80-line investigate mark
|
||||
(Info).
|
||||
|
||||
*Findings*
|
||||
|
||||
- **F1 (High): silent wrong rename and silent miss when a module and a
|
||||
package share the root's name.** Location: `vlog_semantic/src/workspace/external.rs:337-342`
|
||||
(`follow_one`, the multi-segment branch).
|
||||
- What `root_units` guards: only the bare head path `tb`.
|
||||
- What it misses: the next segment's path `tb::dut` folds `tb` and asks
|
||||
`member_chain` on the hierarchical surface, which answers from the
|
||||
package.
|
||||
- Repro: `module tb; dut_a dut (); endmodule`, `package tb; logic dut;
|
||||
endpackage`, and `other.sv`: `initial force tb.dut.x = 0;`.
|
||||
- Renaming the package's `dut` to `d2` rewrites the path to
|
||||
`tb.d2.x`, which is wrong because the path names the module's
|
||||
instance. No warning.
|
||||
- Renaming the module's instance `dut` to `u_dut` leaves the path, also
|
||||
with no warning, because it resolved to a different declaration.
|
||||
- Before §65.4 neither edit touched the path, and the path was warned
|
||||
about.
|
||||
- The same root cause makes `pk.x`, with a package `pk` and no module
|
||||
(illegal code), resolve into the package, and renaming the package
|
||||
member rewrites it (A3/A4, Low on their own).
|
||||
- This contradicts the Design bullet "Only a module or an interface is a
|
||||
root".
|
||||
- Suggested direction, the dev's to choose: apply the instantiable check
|
||||
to the first hop of a hierarchical candidate rooted at a top. Then add a
|
||||
rename-level test, because M1 is caught only by the semantic suite.
|
||||
|
||||
- **F2 (Medium, a documented limit, but a silent wrong rename): an imported
|
||||
package variable used as a head, next to a same-named module.** Location:
|
||||
`vlog_semantic/src/resolve.rs:408` (`head_site` roots on
|
||||
`ExternalCandidate` as well as on `NotFound`).
|
||||
- Repro: `package p; typedef struct packed {logic field;} s_t; s_t cfg;
|
||||
endpackage`, `module cfg; logic field; endmodule`, and
|
||||
`user.sv`: `import p::*; assign o = cfg.field;`.
|
||||
- The head `cfg` resolves to `p::cfg`, the package variable, but the tail
|
||||
`field` resolves to the module's `field`.
|
||||
- Renaming the module's `field` to `fld2` rewrites `cfg.field` to
|
||||
`cfg.fld2` with no warning. Before, the tail had no reference.
|
||||
- The head and its tail disagree about the root, which is detectable. The
|
||||
tail could carry the head's import paths first (`p::cfg::field`, then
|
||||
`cfg::field`), or rooting could be refused when the head's own answer is
|
||||
not a unit.
|
||||
|
||||
- **F3 (Medium, loud): LSP rename misses the files of the path's middle
|
||||
hops.** Location: `lucisv_server/src/state/sources.rs:235-285`
|
||||
(`fan_out_of` / `want_declaration`; outside this lane's files, so this is a
|
||||
Handshake request).
|
||||
- The rename set holds the declaration, the reference postings and the
|
||||
instantiation sites of the container. It does not hold the root's file
|
||||
(`tb.sv`) or a middle hop's file. Inside the rename, the root is then
|
||||
undeclared.
|
||||
- Repro, fixture `ip/rtl/{core,dut_a}.sv`, `ip/dv/{tb,probe}.sv`, where
|
||||
`probe.sv` has `force tb.dut.u_core.sig = 1'b0;`, under the default
|
||||
folder scope:
|
||||
- LSP references on `core.sv`'s `sig` list `probe.sv:2`.
|
||||
- LSP rename of `sig` edits `core.sv` only and warns "probe.sv:2: a
|
||||
hierarchical path through `sig` was not resolved…".
|
||||
- Rename from the segment in `probe.sv` is refused with "`sig` is
|
||||
declared outside the files lucisv indexes", which is misleading.
|
||||
- The same happens for `buf_q` inside `g_sw`: references list
|
||||
`probe.sv:2,3`, and rename edits the declaration only.
|
||||
- `top_sig` (one hop) and `g_sw` (the label) rename fine.
|
||||
- The Goal's own shape `tb.dut.u_x.sig` is the failing one, and most
|
||||
opentitan force paths are deeper than one hop. The engine API (and so
|
||||
`lucisv-mcp`) renames them correctly over the whole set.
|
||||
- Not silent, because it is warned, but references and rename disagree
|
||||
over LSP.
|
||||
|
||||
- **F4 (Low–Medium, by the §23.6 assumption): a head the binder cannot see
|
||||
now roots silently.** Location: `vlog_semantic/src/resolve/root.rs:24`
|
||||
(`path_head`) with `resolve.rs:408`.
|
||||
- Before, these were the §65.1 path warning. Now each is renamed silently
|
||||
through a same-named module:
|
||||
- a class without `extends` whose `cfg` comes from a macro (A11:
|
||||
`` `DECLARE_CFG `` then `cfg.en`);
|
||||
- a module whose struct `st` comes from `` `DECL_STRUCT(st) `` (A12);
|
||||
- a class in a package writing `tb.dut.x` (D2). That is illegal (a
|
||||
package may not reference the hierarchy), but it is renamed anyway.
|
||||
- A cheap narrowing: do not root inside a class scope. Opentitan's DV
|
||||
classes all live in packages, where no head can legally be a top module.
|
||||
|
||||
- **F5 (Low, documented).** `undeclared-identifier` no longer reports an
|
||||
unknown path head (`tbb.dut.x`), which is now an unresolved candidate. The
|
||||
rename still warns, and the opentitan count is unchanged (7).
|
||||
|
||||
*Held (no finding).*
|
||||
- **Locals shadow.** A local `tb` net (same file or another) shadows and is
|
||||
warned. A forward-declared local instance `tb` shadows.
|
||||
- **Labels and other heads.** A named block `blk` beats `module blk`. A
|
||||
clocking block `cb.data`, a modport / interface port head and a `virtual
|
||||
bus_if vif` head all stay local. A genvar or parameter head, and `f().x`,
|
||||
are warned.
|
||||
- **Classes.** An extending class leaves the head alone and warns.
|
||||
- **`bind` and `$root`.** A `bind` head is warned (the BindScope funnel).
|
||||
`$root.tb` with a local `tb` reaches the top, and `$unit::` is unaffected.
|
||||
- **Renaming the root and its instance.** Renaming `tb` rewrites every head
|
||||
and `$root.tb`, and skips local `tb`s. Two `module tb` is refused. A
|
||||
colliding rename of a leaf, the instance or the top is refused (5 cases).
|
||||
`tb.dut.x = y` renamed `x` → `y` correctly.
|
||||
- **Arrays.** An instance array `u[2].x` is not descended and is warned.
|
||||
`mem[3]` and the instance array name itself rename. A struct field through
|
||||
`acc[1].rl` is warned.
|
||||
- **Interfaces and upward names.** An interface top works, and so does an
|
||||
upward module-name reference (`par.sig` from a child).
|
||||
- **LSP references.** Correct with the declaring file open or closed. Under
|
||||
`workspace` with two `tb`, they answer nothing and rename is refused.
|
||||
- **H1.** The dedupe predicate is equivalent to the path scan's, and the
|
||||
path scan's text prefilter trims newlines, so a multi-line path is not
|
||||
lost.
|
||||
|
||||
*Fixes made by QA:* none. Scratch harnesses: `scratchpad/qa654/attack`
|
||||
(case files `cases1–4.txt`), `refs_{new,base}`, `lspfx*`, `probe2.py`.
|
||||
|
||||
**2026-10-19 — QA agent (Opus), re-check after "rework after QA".**
|
||||
|
||||
**Verdict: pass for F1–F4 as reworked.** One new Medium finding needs the
|
||||
lead's ruling (R1: a macro that is not item-level can declare the head), and
|
||||
there are two Info notes. No QA fixes were made.
|
||||
|
||||
*Gates.* Every suite ran through the guard with exit 0.
|
||||
- `cargo fmt --all --check` and `clippy --workspace --all-targets -D
|
||||
warnings` are clean.
|
||||
- Suites: `vlog_semantic` 416 (4 ignored), `vlog_refactor` 741 (6),
|
||||
`lucisv_server` 1 875 (40), `lucisv_mcp` 383 (4), `vlog_linter` 673 (0).
|
||||
All 0 failed, and every count matches the work log.
|
||||
|
||||
*The old attacks, re-run against the new build* (`cases1–4`, plus LSP
|
||||
`lspfx`, `lspfx2`).
|
||||
- **F1 is fixed.** B12 (a module `tb` beside a package `tb`): renaming the
|
||||
package's `dut` or the module's instance `dut` now leaves `tb.dut.x` and
|
||||
warns about it, both ways. A3 and A4 (`pk.x` through a package) now warn,
|
||||
and the segment refuses.
|
||||
- **F2 is fixed.** A1: the imported `cfg` keeps its head. Renaming the
|
||||
module's `field` leaves `cfg.field` and warns, and the segment has no
|
||||
reference.
|
||||
- **F4 is fixed.** A11 (a class with a macro member), A12 (a macro item in a
|
||||
module) and D2 (a package class) are all warned again, as before §65.4.
|
||||
- **F3 is fixed.** The three-hop `tb.dut.u_core.sig` renames over LSP from
|
||||
the declaration and from the segment: 2 edits in 2 files, equal to the
|
||||
references. So does the generate-block `buf_q` (3 edits in 2 files). Under
|
||||
`workspace` scope with two `tb`, the segment refusal now says "segment of
|
||||
a hierarchical path…".
|
||||
- **Every other round-1 case is byte-identical to round 1.** That covers
|
||||
B1–B11, D1, D3–D6, `$root`, the shadows, the collisions and the arrays.
|
||||
|
||||
*New attacks.*
|
||||
- **F3's wider set (`lspfx4`).**
|
||||
- The fixture puts an unrelated `sig` in every hop file: `tb.sv` (a local
|
||||
`sig`, plus `dut.sig` and `dut.u_core.sig`), and `dut_a.sv` (its own
|
||||
`sig`, plus `module helper` with a `sig`).
|
||||
- Renaming `core`'s, `dut_a`'s or `tb`'s `sig` over LSP edits exactly the
|
||||
references, and the engine over the whole set gives the same edits.
|
||||
- `helper` is never touched, and neither is the unrelated `sig` in any
|
||||
hop file.
|
||||
- **A macro beside a head that is not item-level** (`cases5.txt`). These
|
||||
are the R1 cases:
|
||||
- E1: `` initial begin `DECL_LOCAL(st) st.a = 1; end `` beside `module st;
|
||||
logic a;`. Renaming `st.a`'s `a` to `b` rewrites `st.a` to `st.b`
|
||||
silently.
|
||||
- E2 and E6: the same inside a task body and a function body.
|
||||
- E3: `` module user (`MY_PORTS, output logic o); … bus.data `` beside
|
||||
`module bus`. The rename rewrites it silently.
|
||||
- **Macro shapes that hold or are warned.**
|
||||
- Held: a macro in a non-ANSI port region (E4), a macro at file scope
|
||||
(E5), and a macro used as a data type (E8).
|
||||
- Rooted, and correctly so: a macro in a *sibling* generate block (E7) is
|
||||
not in the head's lexical chain.
|
||||
- A macro inside a modport list (E9) still roots. A modport declares no
|
||||
variables, so this is no finding.
|
||||
|
||||
*Mutations* (scratch copy, re-synced):
|
||||
- M5: `roots_at_top` without its class check. Caught by 1 semantic test and
|
||||
`qa_f4_…`.
|
||||
- M6: `roots_at_top` without its macro check. Caught by the same two tests.
|
||||
- M7: `design_unit`'s later-hop "never a package" clause removed. **Not
|
||||
caught** by any of the three suites (Info). A later hop's unit is an
|
||||
instance's or a variable's type, and a module and package sharing a name
|
||||
is already refused by the mixed check. So the clause looks unreachable
|
||||
short of an instance of a package (malformed code). Either pin it with
|
||||
such a test or drop it.
|
||||
|
||||
*Opentitan* (read-only, `git status` clean):
|
||||
- **`lucisv check --no-cache hw`.** Against master 51b975b (scratch
|
||||
worktree, removed afterwards), stdout and stderr are byte-identical, 1 158
|
||||
lines each. `--select undeclared-identifier` is identical.
|
||||
- **`find_references` spot checks.** The 48 seeded positions are identical
|
||||
to master. The round-1 top-rooted positions (`pwrmgr_if.sv:191`,
|
||||
`otp_ctrl_if.sv:169/287`) now answer exactly as master, because those
|
||||
interfaces import `uvm_pkg::*` and the owner's conservative ruling applies.
|
||||
- **Info:** on opentitan's DV interfaces the feature is therefore dormant;
|
||||
every one imports a package.
|
||||
|
||||
*Code.*
|
||||
- No new `unwrap`, `expect` or `panic`.
|
||||
- Production lines: `resolve.rs` 587 (at the mark), `resolve/root.rs` 38,
|
||||
`external.rs` 240, `workspace/path_units.rs` 50, `state/sources.rs` 176.
|
||||
|
||||
*Findings*
|
||||
|
||||
- **R1 (Medium, silent wrong rename; the lead to rule): a macro that is not
|
||||
item-level can declare the head.**
|
||||
- Location: `vlog_semantic/src/resolve/root.rs:40` (`roots_at_top`) and
|
||||
`bind/item.rs` (only `ItemKind::MacroItem` sets `macro_items`).
|
||||
- What escapes it:
|
||||
- a macro statement in a `begin`/`end`, task or function body, where a
|
||||
block-item declaration is legal (E1, E2, E6);
|
||||
- a macro in an ANSI port list (E3).
|
||||
- These root the head at a same-named module and rename through it
|
||||
silently. Before §65.4 they were warned about.
|
||||
- Narrowing would follow the same rule as F4: a macro statement in any
|
||||
enclosing procedural scope, and a macro in the port list, also count as
|
||||
doubt.
|
||||
- The coordinator's brief says statement macros were left out by design.
|
||||
E1–E3 show that they can declare the head, so the trade-off is the
|
||||
lead's call. It needs a module sharing the head's name, which is rare
|
||||
in RTL.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-10-19 — lead.** Accepted after two reworks. QA (Opus) found four
|
||||
silent-wrong-rename shapes (F1 a package sharing the root's name; F2 an
|
||||
imported head beside a same-named module; F4 heads the binder cannot see)
|
||||
plus the LSP rename set missing the middle hops (F3); its re-check found R1
|
||||
(a statement-level or port-list macro declaring the head). All fixed with
|
||||
tests built from QA's repros; QA's cases1–6 re-run against the final build
|
||||
are each warned or correctly renamed. Owner's ruling: stay conservative —
|
||||
a head with an import candidate (e.g. `import uvm_pkg::*` with uvm_pkg not
|
||||
in the project) is doubt and not rooted, so opentitan's DV force paths stay
|
||||
warned exactly as before; the feature applies where the root is provable.
|
||||
`lucisv check hw` byte-identical to master. Granted handshakes: `rename/
|
||||
warnings.rs` (H1, said once), `lucisv_server/src/state/sources.rs` (F3),
|
||||
the message in `rename/mod.rs`. H2 (completion after `tb.`) deferred as
|
||||
TODO §65.8.
|
||||
|
||||
+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,101 @@ 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.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.**
|
||||
`tb.dut.u_core.sig` in a testbench file is now a reference to `sig`, and
|
||||
renaming `dut`, `u_core` or `sig` updates the path — whenever lucisv can
|
||||
tell for certain that `tb` is a top-level module. Where it can't (the
|
||||
name might come from a package the project doesn't contain, such as
|
||||
`uvm_pkg`), the path is left alone and the rename says so, as before.
|
||||
- The `lucisv.index.scope` setting now explains that renaming a module that
|
||||
is also instantiated outside the indexed folders leaves those
|
||||
instantiations unchanged.
|
||||
|
||||
## 0.61.0 — 2026-10-14
|
||||
|
||||
- **Show Call Hierarchy works from where your cursor is.** It used to answer
|
||||
|
||||
@@ -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.61.0**. Its platform packages include
|
||||
The current release is **0.65.3**. 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 |
|
||||
@@ -142,10 +154,12 @@ enabling both paths formats twice.
|
||||
| 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 |
|
||||
| Sticky scroll | The first line of every block you are inside — the module, the `always`, the `case`, the case item, the `if` — 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,19 @@ 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.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 |
|
||||
@@ -406,6 +427,62 @@ 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.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
|
||||
top-level module (`tb.dut.u_core.sig`) whenever the root is certain, and
|
||||
says so plainly where it is not.
|
||||
|
||||
## Release 0.61.0 highlights
|
||||
|
||||
Version 0.61.0 makes Show Call Hierarchy answer from wherever the cursor is
|
||||
|
||||
@@ -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 };
|
||||
@@ -0,0 +1,297 @@
|
||||
// commentKeywords.js against a fake `vscode`: it paints only Verilog editors,
|
||||
// only around the visible lines, honours every setting change at once, and
|
||||
// re-reads block-comment state below an edit. Plus the shipped colour's
|
||||
// contrast against the built-in editor backgrounds
|
||||
// (docs/features/comment-highlighting).
|
||||
//
|
||||
// node --test commentKeywords_test.js
|
||||
|
||||
const assert = require('assert/strict');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const test = require('node:test');
|
||||
const { CommentKeywords, paddedLines, COLOR_ID } = require('./commentKeywords');
|
||||
|
||||
/** A fake of the slice of `vscode` the module uses. */
|
||||
function fakeVscode(settings = {}) {
|
||||
const handlers = {};
|
||||
const on = (name) => (handler) => {
|
||||
handlers[name] = handler;
|
||||
return { dispose() {} };
|
||||
};
|
||||
const vscode = {
|
||||
settings,
|
||||
handlers,
|
||||
decorationOptions: undefined,
|
||||
Range: class {
|
||||
constructor(l1, c1, l2, c2) {
|
||||
Object.assign(this, { l1, c1, l2, c2 });
|
||||
}
|
||||
},
|
||||
ThemeColor: class {
|
||||
constructor(id) {
|
||||
this.id = id;
|
||||
}
|
||||
},
|
||||
window: {
|
||||
visibleTextEditors: [],
|
||||
createTextEditorDecorationType(options) {
|
||||
vscode.decorationOptions = options;
|
||||
return { dispose() {} };
|
||||
},
|
||||
onDidChangeVisibleTextEditors: on('visible'),
|
||||
onDidChangeTextEditorVisibleRanges: on('ranges'),
|
||||
},
|
||||
workspace: {
|
||||
// A language-scoped value (`"[systemverilog]": {...}`, keyed here as
|
||||
// `[systemverilog]editor.x`) wins when a document is the scope.
|
||||
getConfiguration(section, scope) {
|
||||
return {
|
||||
get: (key, fallback) => {
|
||||
const scoped = scope && settings[`[${scope.languageId}]${section}.${key}`];
|
||||
const value = scoped !== undefined ? scoped : settings[`${section}.${key}`];
|
||||
return value === undefined ? fallback : value;
|
||||
},
|
||||
};
|
||||
},
|
||||
onDidChangeTextDocument: on('edit'),
|
||||
onDidOpenTextDocument: on('open'),
|
||||
onDidCloseTextDocument: on('close'),
|
||||
onDidChangeConfiguration: on('config'),
|
||||
},
|
||||
};
|
||||
return vscode;
|
||||
}
|
||||
|
||||
function fakeEditor(lines, { languageId = 'systemverilog', visible = [[0, lines.length - 1]] } = {}) {
|
||||
const document = {
|
||||
languageId,
|
||||
lines,
|
||||
get lineCount() {
|
||||
return this.lines.length;
|
||||
},
|
||||
lineAt(line) {
|
||||
const text = this.lines[line];
|
||||
return { text, range: { end: { line, character: text.length } } };
|
||||
},
|
||||
offsetAt({ line, character }) {
|
||||
return this.lines.slice(0, line).reduce((sum, text) => sum + text.length + 1, 0) + character;
|
||||
},
|
||||
};
|
||||
return {
|
||||
document,
|
||||
visibleRanges: visible.map(([from, to]) => ({ start: { line: from }, end: { line: to } })),
|
||||
painted: undefined,
|
||||
setDecorations(_type, ranges) {
|
||||
this.painted = ranges.map((r) => `${r.l1}:${document.lines[r.l1].slice(r.c1, r.c2)}`);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const isVerilog = (document) => ['verilog', 'systemverilog'].includes(document.languageId);
|
||||
|
||||
function start(vscode, editors, log) {
|
||||
vscode.window.visibleTextEditors = editors;
|
||||
const subscriptions = [];
|
||||
const keywords = new CommentKeywords(vscode, isVerilog, log);
|
||||
keywords.activate(subscriptions);
|
||||
return { keywords, subscriptions };
|
||||
}
|
||||
|
||||
function configChange(vscode, ...sections) {
|
||||
vscode.handlers.config({ affectsConfiguration: (s) => sections.includes(s) });
|
||||
}
|
||||
|
||||
test('paints the built-ins bold in the contributed colour, in Verilog editors only', () => {
|
||||
const vscode = fakeVscode();
|
||||
const sv = fakeEditor(['wire TODO; // TODO and TBD']);
|
||||
const other = fakeEditor(['// TODO'], { languageId: 'plaintext' });
|
||||
const { subscriptions } = start(vscode, [sv, other]);
|
||||
assert.deepEqual(sv.painted, ['0:TODO', '0:TBD']);
|
||||
assert.equal(other.painted, undefined);
|
||||
assert.equal(vscode.decorationOptions.color.id, COLOR_ID);
|
||||
assert.equal(vscode.decorationOptions.fontWeight, 'bold');
|
||||
assert.ok(subscriptions.length >= 7, 'the decoration type and every listener are disposed with the extension');
|
||||
});
|
||||
|
||||
test('only the lines around the visible range are read', () => {
|
||||
const vscode = fakeVscode();
|
||||
const lines = Array.from({ length: 1000 }, (_, i) => `// TODO ${i}`);
|
||||
const editor = fakeEditor(lines, { visible: [[500, 520]] });
|
||||
let reads = 0;
|
||||
const lineAt = editor.document.lineAt.bind(editor.document);
|
||||
editor.document.lineAt = (line) => {
|
||||
reads += 1;
|
||||
return lineAt(line);
|
||||
};
|
||||
start(vscode, [editor]);
|
||||
assert.equal(editor.painted.length, 121, 'lines 450..570');
|
||||
assert.equal(editor.painted[0], '450:TODO');
|
||||
// The last line once (the size check), lines 0..449 once for the
|
||||
// block-comment state above the window, then each window line once: its
|
||||
// scan also gives the next line's state.
|
||||
assert.equal(reads, 1 + 450 + 121);
|
||||
reads = 0;
|
||||
vscode.handlers.ranges({ textEditor: editor });
|
||||
assert.equal(reads, 121, 'a repaint reuses the states above the window');
|
||||
});
|
||||
|
||||
test('setting changes take effect immediately, both ways', () => {
|
||||
const vscode = fakeVscode();
|
||||
const editor = fakeEditor(['// TODO XXX todo hack']);
|
||||
start(vscode, [editor]);
|
||||
assert.deepEqual(editor.painted, ['0:TODO']);
|
||||
vscode.settings['lucisv.commentKeywords.custom'] = ['XXX', 'hack'];
|
||||
configChange(vscode, 'lucisv.commentKeywords');
|
||||
assert.deepEqual(editor.painted, ['0:TODO', '0:XXX', '0:hack']);
|
||||
vscode.settings['lucisv.commentKeywords.builtIn'] = false;
|
||||
configChange(vscode, 'lucisv.commentKeywords');
|
||||
assert.deepEqual(editor.painted, ['0:XXX', '0:hack']);
|
||||
vscode.settings['lucisv.commentKeywords.caseSensitive'] = false;
|
||||
vscode.settings['lucisv.commentKeywords.builtIn'] = true;
|
||||
configChange(vscode, 'lucisv.commentKeywords');
|
||||
assert.deepEqual(editor.painted, ['0:TODO', '0:XXX', '0:todo', '0:hack']);
|
||||
vscode.settings['lucisv.commentKeywords.builtIn'] = false;
|
||||
vscode.settings['lucisv.commentKeywords.custom'] = [];
|
||||
configChange(vscode, 'lucisv.commentKeywords');
|
||||
assert.deepEqual(editor.painted, [], 'nothing left to highlight clears the decorations');
|
||||
editor.painted = 'untouched';
|
||||
configChange(vscode, 'lucisv.rainbowBeginEnd');
|
||||
assert.equal(editor.painted, 'untouched', 'an unrelated setting repaints nothing');
|
||||
});
|
||||
|
||||
test('unusable custom words are skipped with one line in the output channel', () => {
|
||||
const vscode = fakeVscode({ 'lucisv.commentKeywords.custom': ['ok', 'two words', ''] });
|
||||
const logged = [];
|
||||
const editor = fakeEditor(['// ok']);
|
||||
start(vscode, [editor], (line) => logged.push(line));
|
||||
assert.deepEqual(editor.painted, ['0:ok']);
|
||||
assert.equal(logged.length, 1);
|
||||
assert.match(logged[0], /ignored 2 entries/);
|
||||
});
|
||||
|
||||
test('an edit above re-reads the block-comment state below it', async () => {
|
||||
const vscode = fakeVscode();
|
||||
const editor = fakeEditor(['wire a;', 'TODO', '*/ // TBD']);
|
||||
start(vscode, [editor]);
|
||||
assert.deepEqual(editor.painted, ['2:TBD']);
|
||||
editor.document.lines[0] = 'wire a; /*';
|
||||
vscode.handlers.edit({ document: editor.document, contentChanges: [{ range: { start: { line: 0 } } }] });
|
||||
await new Promise((resolve) => setTimeout(resolve, 150));
|
||||
assert.deepEqual(editor.painted, ['1:TODO', '2:TBD']);
|
||||
});
|
||||
|
||||
test('maxTokenizationLineLength is honoured, and a change to it drops the cached states', () => {
|
||||
const vscode = fakeVscode({ 'editor.maxTokenizationLineLength': 20 });
|
||||
const editor = fakeEditor(['/* open', `${'x'.repeat(30)} */`, 'TODO */']);
|
||||
start(vscode, [editor]);
|
||||
assert.deepEqual(editor.painted, ['2:TODO'], 'the long line is not tokenized, so the block stays open');
|
||||
vscode.settings['editor.maxTokenizationLineLength'] = 1000;
|
||||
configChange(vscode, 'editor.maxTokenizationLineLength');
|
||||
assert.deepEqual(editor.painted, []);
|
||||
});
|
||||
|
||||
test('a [systemverilog] maxTokenizationLineLength override is the one honoured', () => {
|
||||
const vscode = fakeVscode({
|
||||
'editor.maxTokenizationLineLength': 20000,
|
||||
'[systemverilog]editor.maxTokenizationLineLength': 20,
|
||||
});
|
||||
const lines = ['/* open', `${'x'.repeat(30)} */ // TODO`, 'TODO */'];
|
||||
const sv = fakeEditor(lines);
|
||||
const v = fakeEditor([...lines], { languageId: 'verilog' });
|
||||
start(vscode, [sv, v]);
|
||||
assert.deepEqual(sv.painted, ['2:TODO'], 'the override applies to the systemverilog document');
|
||||
assert.deepEqual(v.painted, ['1:TODO'], 'and not to the verilog one');
|
||||
delete vscode.settings['[systemverilog]editor.maxTokenizationLineLength'];
|
||||
configChange(vscode, 'editor.maxTokenizationLineLength');
|
||||
assert.deepEqual(sv.painted, ['1:TODO'], 'dropping the override recomputes the states');
|
||||
});
|
||||
|
||||
test('a language-mode change clears or paints at once', async () => {
|
||||
const vscode = fakeVscode();
|
||||
const editor = fakeEditor(['// TODO']);
|
||||
start(vscode, [editor]);
|
||||
assert.deepEqual(editor.painted, ['0:TODO']);
|
||||
// What `setTextDocumentLanguage` reports: close, then open, of the document.
|
||||
const change = async (languageId) => {
|
||||
vscode.handlers.close(editor.document);
|
||||
editor.document.languageId = languageId;
|
||||
vscode.handlers.open(editor.document);
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
};
|
||||
await change('plaintext');
|
||||
assert.deepEqual(editor.painted, [], 'no longer Verilog: the decorations go');
|
||||
await change('systemverilog');
|
||||
assert.deepEqual(editor.painted, ['0:TODO'], 'Verilog again: painted without a scroll or edit');
|
||||
const foreign = fakeEditor(['// TODO'], { languageId: 'markdown' });
|
||||
vscode.window.visibleTextEditors.push(foreign);
|
||||
vscode.handlers.visible();
|
||||
assert.equal(foreign.painted, undefined, 'an editor this never painted is never touched');
|
||||
});
|
||||
|
||||
test('a file VS Code does not tokenize at all is not painted', () => {
|
||||
const big = Array.from({ length: 300001 }, () => '// TODO');
|
||||
const vscode = fakeVscode();
|
||||
const editor = fakeEditor(big, { visible: [[0, 10]] });
|
||||
start(vscode, [editor]);
|
||||
assert.deepEqual(editor.painted, [], 'over 300 000 lines');
|
||||
|
||||
const long = fakeEditor(['// TODO', 'x'.repeat(20 * 1024 * 1024)], { visible: [[0, 1]] });
|
||||
start(fakeVscode(), [long]);
|
||||
assert.deepEqual(long.painted, [], 'over 20 MiB');
|
||||
|
||||
const atLimit = fakeEditor(['// TODO', 'x'.repeat(20 * 1024 * 1024 - 8)], { visible: [[0, 1]] });
|
||||
start(fakeVscode({ 'editor.maxTokenizationLineLength': 1e9 }), [atLimit]);
|
||||
assert.deepEqual(atLimit.painted, ['0:TODO'], 'exactly 20 MiB is still tokenized');
|
||||
|
||||
const optOut = fakeEditor(big, { visible: [[0, 1]] });
|
||||
start(fakeVscode({ 'editor.largeFileOptimizations': false }), [optOut]);
|
||||
assert.equal(optOut.painted.length, 52, 'largeFileOptimizations off: VS Code tokenizes it, so it is painted');
|
||||
});
|
||||
|
||||
test('paddedLines widens, clamps and merges the visible ranges', () => {
|
||||
const range = (from, to) => ({ start: { line: from }, end: { line: to } });
|
||||
assert.deepEqual(paddedLines([range(0, 10)], 30), [{ from: 0, to: 30 }]);
|
||||
assert.deepEqual(paddedLines([range(300, 310), range(100, 110)], 1000),
|
||||
[{ from: 50, to: 160 }, { from: 250, to: 360 }]);
|
||||
assert.deepEqual(paddedLines([range(100, 110), range(150, 160)], 1000), [{ from: 50, to: 210 }]);
|
||||
});
|
||||
|
||||
// ---- The shipped colour is readable on the built-in editor backgrounds.
|
||||
|
||||
/** `editor.background` of the built-in themes, per theme kind. */
|
||||
const BACKGROUNDS = [
|
||||
{ kind: 'dark', name: 'Dark Modern', background: '#1F1F1F' },
|
||||
{ kind: 'dark', name: 'Dark+', background: '#1E1E1E' },
|
||||
{ kind: 'light', name: 'Light Modern', background: '#FFFFFF' },
|
||||
{ kind: 'light', name: 'Light+', background: '#FFFFFF' },
|
||||
{ kind: 'highContrast', name: 'HC Dark', background: '#000000' },
|
||||
{ kind: 'highContrastLight', name: 'HC Light', background: '#FFFFFF' },
|
||||
];
|
||||
|
||||
/** WCAG relative luminance of an opaque `#RRGGBB`. */
|
||||
function luminance(hex) {
|
||||
const [r, g, b] = [1, 3, 5].map((at) => {
|
||||
const c = parseInt(hex.slice(at, at + 2), 16) / 255;
|
||||
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
||||
});
|
||||
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
}
|
||||
|
||||
function contrast(a, b) {
|
||||
const [high, low] = [luminance(a), luminance(b)].sort((x, y) => y - x);
|
||||
return (high + 0.05) / (low + 0.05);
|
||||
}
|
||||
|
||||
test('lucisv.commentKeyword is opaque and at least 4.5:1 on every built-in theme', () => {
|
||||
const manifest = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
|
||||
const colour = manifest.contributes.colors.find(({ id }) => id === COLOR_ID);
|
||||
assert.ok(colour, `${COLOR_ID} is contributed`);
|
||||
assert.equal(COLOR_ID.split('.').length, 2, 'exactly one dot in the colour id');
|
||||
for (const { kind, name, background } of BACKGROUNDS) {
|
||||
const foreground = colour.defaults[kind];
|
||||
assert.match(foreground, /^#[0-9A-Fa-f]{6}$/, `${name}: opaque #RRGGBB`);
|
||||
const ratio = contrast(foreground, background);
|
||||
assert.ok(ratio >= 4.5, `${name}: ${foreground} on ${background} is ${ratio.toFixed(2)}:1`);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,236 @@
|
||||
// Where the comments are, and which words inside them to highlight — pure,
|
||||
// no `vscode`, so every rule here is tested with plain node
|
||||
// (docs/features/comment-highlighting).
|
||||
//
|
||||
// The comment rules are the TextMate grammar's, not the lexer's, on purpose:
|
||||
// a keyword is highlighted where the user *sees* comment colouring, and that
|
||||
// colouring is the grammar's. `commentScan_test.js` pins the grammar rules
|
||||
// this file mirrors, so an edit to one without the other fails the build.
|
||||
//
|
||||
// The grammar (`syntaxes/systemverilog.tmLanguage.json`) has exactly two rules
|
||||
// that decide what is comment: `//.*` and `/\*` … `\*/` (which may span
|
||||
// lines), and one that hides a `//` or `/*` from them — a string, `"` … `"`
|
||||
// or end of line, with `\\.` escapes. Every other top-level rule matches only
|
||||
// characters that can never begin those three (backtick names, `$` names,
|
||||
// numbers, keywords), so it can never swallow or reveal a comment start and
|
||||
// this scan can ignore it.
|
||||
|
||||
/** The words highlighted unless `lucisv.commentKeywords.builtIn` is off. */
|
||||
const BUILT_IN_WORDS = ['TODO', 'FIXME', 'FIX_ME', 'TBD'];
|
||||
|
||||
/** At most this many custom words are honoured; the rest are dropped. */
|
||||
const MAX_CUSTOM_WORDS = 50;
|
||||
|
||||
/** A custom word longer than this is dropped. */
|
||||
const MAX_WORD_LENGTH = 40;
|
||||
|
||||
/** An identifier character: a match may not have one on either side. */
|
||||
const WORD_CHAR = '[A-Za-z0-9_$]';
|
||||
|
||||
/** The next thing that can start a comment or a string. */
|
||||
const OPENER = /\/\/|\/\*|"/g;
|
||||
|
||||
/**
|
||||
* The comment spans of one line, given whether it starts inside a block
|
||||
* comment, and whether the next line does.
|
||||
*
|
||||
* Each span is `[start, end, bodyStart, bodyEnd]`: the whole comment with
|
||||
* its delimiters, then the text between them, all as `[start, end)` offsets in
|
||||
* UTF-16 units — VS Code's columns.
|
||||
*/
|
||||
function scanLine(text, inBlock) {
|
||||
const spans = [];
|
||||
let at = 0;
|
||||
if (inBlock) {
|
||||
const close = text.indexOf('*/');
|
||||
if (close < 0) return { spans: [[0, text.length, 0, text.length]], inBlock: true };
|
||||
spans.push([0, close + 2, 0, close]);
|
||||
at = close + 2;
|
||||
}
|
||||
for (;;) {
|
||||
OPENER.lastIndex = at;
|
||||
const opener = OPENER.exec(text);
|
||||
if (!opener) return { spans, inBlock: false };
|
||||
const start = opener.index;
|
||||
if (opener[0] === '//') {
|
||||
spans.push([start, text.length, start + 2, text.length]);
|
||||
return { spans, inBlock: false };
|
||||
}
|
||||
if (opener[0] === '/*') {
|
||||
const close = text.indexOf('*/', start + 2);
|
||||
if (close < 0) {
|
||||
spans.push([start, text.length, start + 2, text.length]);
|
||||
return { spans, inBlock: true };
|
||||
}
|
||||
spans.push([start, close + 2, start + 2, close]);
|
||||
at = close + 2;
|
||||
} else {
|
||||
at = stringEnd(text, start + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a string that opened just before `at` ends: after its closing quote,
|
||||
* or at the end of the line. A backslash escapes the next character, if the
|
||||
* line has one — the grammar's `\\.` cannot match the line break.
|
||||
*/
|
||||
function stringEnd(text, at) {
|
||||
while (at < text.length) {
|
||||
const c = text[at];
|
||||
if (c === '\\') at += 2;
|
||||
else if (c === '"') return at + 1;
|
||||
else at += 1;
|
||||
}
|
||||
return text.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* The words to highlight, from the settings: the built-ins (unless turned
|
||||
* off) and every usable custom word, without duplicates.
|
||||
*
|
||||
* A custom word is usable when it is a string of 1 to `MAX_WORD_LENGTH`
|
||||
* characters with no whitespace; anything else is skipped, as is everything
|
||||
* past the first `MAX_CUSTOM_WORDS`. Returns the words and the skipped
|
||||
* entries, so the caller can say what it ignored.
|
||||
*/
|
||||
function chooseWords({ builtIn = true, custom = [], caseSensitive = true } = {}) {
|
||||
const words = builtIn === false ? [] : [...BUILT_IN_WORDS];
|
||||
const skipped = [];
|
||||
const list = Array.isArray(custom) ? custom : [];
|
||||
for (const [index, entry] of list.entries()) {
|
||||
const usable = typeof entry === 'string' && entry.length > 0
|
||||
&& entry.length <= MAX_WORD_LENGTH && !/\s/.test(entry);
|
||||
if (usable && index < MAX_CUSTOM_WORDS) words.push(entry);
|
||||
else skipped.push(entry);
|
||||
}
|
||||
const seen = new Set();
|
||||
const unique = words.filter((word) => {
|
||||
const key = caseSensitive === false ? word.toLowerCase() : word;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
return { words: unique, skipped };
|
||||
}
|
||||
|
||||
/** `text` with every regular-expression metacharacter escaped. */
|
||||
function escapeRegExp(text) {
|
||||
return text.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
|
||||
}
|
||||
|
||||
/**
|
||||
* One global regular expression that finds any of `words` as a whole word,
|
||||
* or `null` when there are none.
|
||||
*
|
||||
* Whole word the way `\b` means it, with `$` counted as a word character
|
||||
* (Verilog's identifiers have it): a word that starts with a word character
|
||||
* may not have one just before it, and one that ends with a word character
|
||||
* may not have one just after. So `TODO` skips `TODO_reg` and `myTODO`, and
|
||||
* `REVIEW:` matches in `REVIEW:x`.
|
||||
*
|
||||
* Every word is matched literally — escaped, never interpreted — so a setting
|
||||
* cannot inject a pattern. The alternation is of plain literals, longest
|
||||
* first so a word wins over its own prefix, each between at most two
|
||||
* one-character lookarounds: no quantifier, nothing to backtrack
|
||||
* catastrophically on.
|
||||
*/
|
||||
function wordMatcher(words, caseSensitive = true) {
|
||||
if (!words.length) return null;
|
||||
const startsWord = new RegExp(`^${WORD_CHAR}`);
|
||||
const endsWord = new RegExp(`${WORD_CHAR}$`);
|
||||
const alternatives = [...words]
|
||||
.sort((a, b) => b.length - a.length)
|
||||
.map((word) => (startsWord.test(word) ? `(?<!${WORD_CHAR})` : '')
|
||||
+ escapeRegExp(word)
|
||||
+ (endsWord.test(word) ? `(?!${WORD_CHAR})` : ''));
|
||||
const flags = caseSensitive === false ? 'gi' : 'g';
|
||||
return new RegExp(alternatives.join('|'), flags);
|
||||
}
|
||||
|
||||
/**
|
||||
* The `[start, end)` matches of `matcher` inside the bodies of `spans` — never
|
||||
* across a comment's own delimiters, whatever a custom word holds.
|
||||
*/
|
||||
function wordsInSpans(text, spans, matcher) {
|
||||
const found = [];
|
||||
for (const [, , start, end] of spans) {
|
||||
const inside = text.slice(start, end);
|
||||
matcher.lastIndex = 0;
|
||||
for (const match of inside.matchAll(matcher)) {
|
||||
found.push([start + match.index, start + match.index + match[0].length]);
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per document: whether each line starts inside a block comment, computed
|
||||
* lazily from the top and kept until an edit above it invalidates it — so
|
||||
* scrolling or typing never rescans the lines above the edit.
|
||||
*
|
||||
* `maxLineLength` mirrors VS Code's `editor.maxTokenizationLineLength`: the
|
||||
* editor does not tokenize a line that long (`length >= max`) and carries the
|
||||
* state across it unchanged, so it shows no comment there and neither do we.
|
||||
*/
|
||||
class LineStates {
|
||||
constructor() {
|
||||
/** `starts[i]`: line `i` begins inside a block comment. Line 0 never does. */
|
||||
this.starts = [false];
|
||||
}
|
||||
|
||||
/** Lines from `line` on may have changed. */
|
||||
invalidateFrom(line) {
|
||||
this.starts.length = Math.max(1, Math.min(this.starts.length, line + 1));
|
||||
}
|
||||
|
||||
/** Whether `line` starts inside a block comment. */
|
||||
startOf(line, lineText, maxLineLength) {
|
||||
while (this.starts.length <= line) {
|
||||
const previous = this.starts.length - 1;
|
||||
const text = lineText(previous);
|
||||
const inBlock = this.starts[previous];
|
||||
this.starts.push(text.length >= maxLineLength ? inBlock : scanLine(text, inBlock).inBlock);
|
||||
}
|
||||
return this.starts[line];
|
||||
}
|
||||
|
||||
/** Record what a scan of `line` found for the next one, if that is new. */
|
||||
recordNext(line, inBlock) {
|
||||
if (this.starts.length === line + 1) this.starts.push(inBlock);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The keyword ranges `{ line, start, end }` on lines `from`..`to` (inclusive)
|
||||
* of a document read through `lineText`.
|
||||
*/
|
||||
function keywordRanges({ states, lineText, from, to, matcher, maxLineLength }) {
|
||||
const ranges = [];
|
||||
if (!matcher) return ranges;
|
||||
for (let line = from; line <= to; line += 1) {
|
||||
const text = lineText(line);
|
||||
const inBlock = states.startOf(line, lineText, maxLineLength);
|
||||
if (text.length >= maxLineLength) {
|
||||
states.recordNext(line, inBlock);
|
||||
continue;
|
||||
}
|
||||
const { spans, inBlock: next } = scanLine(text, inBlock);
|
||||
states.recordNext(line, next);
|
||||
for (const [start, end] of wordsInSpans(text, spans, matcher)) ranges.push({ line, start, end });
|
||||
}
|
||||
return ranges;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
BUILT_IN_WORDS,
|
||||
MAX_CUSTOM_WORDS,
|
||||
MAX_WORD_LENGTH,
|
||||
scanLine,
|
||||
chooseWords,
|
||||
escapeRegExp,
|
||||
wordMatcher,
|
||||
wordsInSpans,
|
||||
LineStates,
|
||||
keywordRanges,
|
||||
};
|
||||
@@ -0,0 +1,244 @@
|
||||
// commentScan.js: the comment rules it mirrors are the grammar's, the words
|
||||
// are matched literally and as whole words, and the incremental line states
|
||||
// always agree with a scan from the top (docs/features/comment-highlighting).
|
||||
//
|
||||
// node --test commentScan_test.js
|
||||
|
||||
const assert = require('assert/strict');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const test = require('node:test');
|
||||
const {
|
||||
BUILT_IN_WORDS, MAX_CUSTOM_WORDS, MAX_WORD_LENGTH, scanLine, chooseWords, escapeRegExp,
|
||||
wordMatcher, wordsInSpans, LineStates, keywordRanges,
|
||||
} = require('./commentScan');
|
||||
|
||||
const grammar = JSON.parse(
|
||||
fs.readFileSync(path.join(__dirname, 'syntaxes', 'systemverilog.tmLanguage.json'), 'utf8'),
|
||||
);
|
||||
|
||||
/** The comment columns of each line, as `.`/`#`, scanned top to bottom. */
|
||||
function picture(lines) {
|
||||
let inBlock = false;
|
||||
return lines.map((line) => {
|
||||
const result = scanLine(line, inBlock);
|
||||
inBlock = result.inBlock;
|
||||
const marks = Array.from(line, () => '.');
|
||||
for (const [start, end] of result.spans) marks.fill('#', start, end);
|
||||
return marks.join('');
|
||||
});
|
||||
}
|
||||
|
||||
/** The highlighted words of a whole document, as `line:text` strings. */
|
||||
function highlighted(lines, words = BUILT_IN_WORDS, options = {}) {
|
||||
const ranges = keywordRanges({
|
||||
states: new LineStates(),
|
||||
lineText: (line) => lines[line],
|
||||
from: 0,
|
||||
to: lines.length - 1,
|
||||
matcher: wordMatcher(words, options.caseSensitive),
|
||||
maxLineLength: options.maxLineLength || 20000,
|
||||
});
|
||||
return ranges.map(({ line, start, end }) => `${line}:${lines[line].slice(start, end)}`);
|
||||
}
|
||||
|
||||
test('the grammar still decides comments with exactly the rules this mirrors', () => {
|
||||
assert.deepEqual(grammar.repository.comments, {
|
||||
patterns: [
|
||||
{ name: 'comment.line.double-slash.systemverilog', match: '//.*' },
|
||||
{ name: 'comment.block.systemverilog', begin: '/\\*', end: '\\*/' },
|
||||
],
|
||||
});
|
||||
assert.deepEqual(grammar.repository.strings, {
|
||||
name: 'string.quoted.double.systemverilog',
|
||||
begin: '"',
|
||||
end: '"|$',
|
||||
patterns: [{ name: 'constant.character.escape.systemverilog', match: '\\\\.' }],
|
||||
});
|
||||
assert.deepEqual(grammar.patterns.slice(0, 2), [{ include: '#comments' }, { include: '#strings' }]);
|
||||
});
|
||||
|
||||
test('no other top-level grammar rule can match a "/" or a quote', () => {
|
||||
// If one could, it might swallow a comment opener or reveal one this scan
|
||||
// hides, and the scan would have to model it. A rule built only of literal
|
||||
// letters, `\b`, `\s`, digits and classes without `/` or `"` cannot.
|
||||
const others = grammar.patterns.slice(2).map(({ include }) => grammar.repository[include.slice(1)]);
|
||||
const regexes = others.flatMap((rule) => (rule.patterns || [rule]).map((r) => r.match));
|
||||
assert.ok(regexes.length >= 5);
|
||||
for (const source of regexes) {
|
||||
assert.equal(typeof source, 'string', 'every other rule is a single-line match');
|
||||
const unescaped = source.replace(/\\./g, '');
|
||||
for (const risky of ['/', '"', '.', '[^']) {
|
||||
assert.ok(!unescaped.includes(risky), `${source} contains ${risky}`);
|
||||
}
|
||||
// QA 2026-11-19: also Oniguruma's any-char/negated escapes (`\H` non-hex,
|
||||
// `\O`, `\X`, `\R`, `\P{…}`/`\p{…}`), code-point escapes that can spell
|
||||
// `/` or `"` (`\x2F`, `"`, octal `\057`), and POSIX classes.
|
||||
for (const escape of ['\\S', '\\W', '\\D', '\\N', '\\/', '\\H', '\\O', '\\X', '\\R',
|
||||
'\\P', '\\p', '\\x', '\\u', '\\0', '[[:']) {
|
||||
assert.ok(!source.includes(escape), `${source} contains ${escape}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('comments: line, block, strings that hide them, and blocks across lines', () => {
|
||||
const lines = [
|
||||
'assign s = "a // b"; // c',
|
||||
'x = "q\\" // still"; /* d */ y;',
|
||||
'unterminated "string // to the end',
|
||||
'/* opens',
|
||||
' " is not a string here',
|
||||
'closes */ z = "/*";',
|
||||
'/*/ not closed',
|
||||
'still */ q',
|
||||
'`define M(a) a // macro text',
|
||||
'(* full_case *) case (x)',
|
||||
'a = "back\\\\"; // after',
|
||||
'a = "slash at end \\',
|
||||
'/**/ b /***/ c',
|
||||
];
|
||||
// Copied from vscode-textmate's own tokenization of these lines with this
|
||||
// grammar (docs/features/comment-highlighting, "Agreement"), not hand-counted.
|
||||
assert.deepEqual(picture(lines), [
|
||||
'.....................####',
|
||||
'....................#######...',
|
||||
'..................................',
|
||||
'########',
|
||||
'#########################',
|
||||
'#########..........',
|
||||
'##############',
|
||||
'########..',
|
||||
'...............#############',
|
||||
'........................',
|
||||
'..............########',
|
||||
'...................',
|
||||
'####...#####..',
|
||||
]);
|
||||
});
|
||||
|
||||
test('spans carry their bodies, without the delimiters', () => {
|
||||
assert.deepEqual(scanLine('a /* b */ // c', false).spans, [[2, 9, 4, 7], [10, 14, 12, 14]]);
|
||||
assert.deepEqual(scanLine('x */ y', true).spans, [[0, 4, 0, 2]]);
|
||||
assert.deepEqual(scanLine('x', true), { spans: [[0, 1, 0, 1]], inBlock: true });
|
||||
});
|
||||
|
||||
test('the built-ins are highlighted in comments and nowhere else', () => {
|
||||
assert.deepEqual(
|
||||
highlighted([
|
||||
'// TODO: fix, FIXME, FIX_ME and TBD',
|
||||
'wire TODO_reg; // TODO_reg myTODO $TODO TODO$ TODO1 xTBD',
|
||||
'string s = "TODO // TODO"; // TODO',
|
||||
'TODO = 1; /* TBD */ FIXME',
|
||||
'/* block',
|
||||
' (TODO) [TBD] {FIX_ME}.',
|
||||
'*/ TODO',
|
||||
'//TODO//FIXME',
|
||||
'/*TODO*/',
|
||||
'todo Todo // todo Todo tbd',
|
||||
]),
|
||||
['0:TODO', '0:FIXME', '0:FIX_ME', '0:TBD', '2:TODO', '3:TBD', '5:TODO', '5:TBD', '5:FIX_ME',
|
||||
'7:TODO', '7:FIXME', '8:TODO'],
|
||||
);
|
||||
});
|
||||
|
||||
test('case-insensitive matching is opt-in', () => {
|
||||
assert.deepEqual(highlighted(['// todo Todo TODO todo_x'], BUILT_IN_WORDS, { caseSensitive: false }),
|
||||
['0:todo', '0:Todo', '0:TODO']);
|
||||
assert.deepEqual(highlighted(['// todo Todo'], BUILT_IN_WORDS, { caseSensitive: true }), []);
|
||||
});
|
||||
|
||||
test('custom words are literal: metacharacters mean themselves', () => {
|
||||
const words = ['a.b', '(.*)+', '[x]', '\\d', 'c|d', '^e$', 'f?', 'g{2}', '$h', 'i/j'];
|
||||
assert.deepEqual(
|
||||
highlighted(['// axb a.b (.*)+ aaa [x] x \\d 1 c|d c d ^e$ e f? f g{2} gg $h i/j'], words),
|
||||
['0:a.b', '0:(.*)+', '0:[x]', '0:\\d', '0:c|d', '0:^e$', '0:f?', '0:g{2}', '0:$h', '0:i/j'],
|
||||
);
|
||||
assert.equal(escapeRegExp('.*+?^${}()|[]\\/'), '\\.\\*\\+\\?\\^\\$\\{\\}\\(\\)\\|\\[\\]\\\\\\/');
|
||||
});
|
||||
|
||||
test('whole words follow \\b, with $ as a word character', () => {
|
||||
const words = ['REVIEW:', '@note', 'HACK'];
|
||||
assert.deepEqual(
|
||||
highlighted(['// REVIEW:x xREVIEW: a@note @notes HACK_mode HACK$ (HACK) HACK'], words),
|
||||
['0:REVIEW:', '0:@note', '0:HACK', '0:HACK'],
|
||||
);
|
||||
});
|
||||
|
||||
test('a word wins over its own prefix', () => {
|
||||
assert.deepEqual(highlighted(['// TODO! TODO'], ['TODO', 'TODO!']), ['0:TODO!', '0:TODO']);
|
||||
});
|
||||
|
||||
test('a custom word cannot reach into a comment delimiter', () => {
|
||||
assert.deepEqual(highlighted(['// x /* y */ z', 'a /** b **/'], ['//', '/*', '*/', '**', '*']),
|
||||
['0:/*', '0:*/', '1:*', '1:*'], 'inside a line comment, "/* y */" is only text');
|
||||
});
|
||||
|
||||
test('chooseWords: built-ins, caps, junk and duplicates', () => {
|
||||
assert.deepEqual(chooseWords().words, BUILT_IN_WORDS);
|
||||
assert.deepEqual(chooseWords({ builtIn: false }).words, []);
|
||||
assert.deepEqual(chooseWords({ builtIn: false, custom: ['XXX', 'XXX', 'HACK'] }).words, ['XXX', 'HACK']);
|
||||
const junk = ['', 'two words', 'tab\there', 'x'.repeat(MAX_WORD_LENGTH + 1), 7, null, { a: 1 }];
|
||||
const { words, skipped } = chooseWords({ custom: [...junk, 'OK'] });
|
||||
assert.deepEqual(words, [...BUILT_IN_WORDS, 'OK']);
|
||||
assert.deepEqual(skipped, junk);
|
||||
assert.deepEqual(chooseWords({ custom: 'TODO' }).words, BUILT_IN_WORDS, 'a non-array is no words');
|
||||
const many = Array.from({ length: MAX_CUSTOM_WORDS + 5 }, (_, i) => `W${i}`);
|
||||
const capped = chooseWords({ builtIn: false, custom: many });
|
||||
assert.equal(capped.words.length, MAX_CUSTOM_WORDS);
|
||||
assert.equal(capped.skipped.length, 5);
|
||||
assert.deepEqual(chooseWords({ custom: ['todo'], caseSensitive: false }).words, BUILT_IN_WORDS);
|
||||
assert.deepEqual(chooseWords({ custom: ['todo'] }).words, [...BUILT_IN_WORDS, 'todo']);
|
||||
assert.equal(wordMatcher([]), null);
|
||||
});
|
||||
|
||||
test('the worst words the caps allow stay fast on the longest line VS Code tokenizes', () => {
|
||||
const words = Array.from({ length: MAX_CUSTOM_WORDS }, (_, i) => 'a'.repeat(MAX_WORD_LENGTH - (i % 3)) + i % 3);
|
||||
const line = `// ${'a'.repeat(19990)}`;
|
||||
const started = process.hrtime.bigint();
|
||||
wordsInSpans(line, scanLine(line, false).spans, wordMatcher(words));
|
||||
const ms = Number(process.hrtime.bigint() - started) / 1e6;
|
||||
assert.ok(ms < 2000, `took ${ms.toFixed(0)} ms`);
|
||||
});
|
||||
|
||||
test('a line VS Code will not tokenize carries the state and highlights nothing', () => {
|
||||
const lines = ['/* open', `x ${'y'.repeat(50)} */ // TODO`, 'still open TODO */'];
|
||||
assert.deepEqual(highlighted(lines, BUILT_IN_WORDS, { maxLineLength: 40 }), ['2:TODO']);
|
||||
assert.deepEqual(highlighted(lines, BUILT_IN_WORDS, { maxLineLength: 1000 }), ['1:TODO']);
|
||||
});
|
||||
|
||||
/** A small deterministic PRNG, so a failure reproduces. */
|
||||
function prng(seed) {
|
||||
let state = seed;
|
||||
return () => {
|
||||
state = (state * 1103515245 + 12345) % 2147483648;
|
||||
return state / 2147483648;
|
||||
};
|
||||
}
|
||||
|
||||
test('incremental line states, painted or probed, always equal a scan from the top', () => {
|
||||
const random = prng(71);
|
||||
const pieces = ['/*', '*/', '//', '"', 'x', ' ', 'TODO', '\\'];
|
||||
const line = () => Array.from({ length: 1 + Math.floor(random() * 6) },
|
||||
() => pieces[Math.floor(random() * pieces.length)]).join('');
|
||||
const lines = Array.from({ length: 40 }, line);
|
||||
const states = new LineStates();
|
||||
const lineText = (at) => lines[at];
|
||||
for (let round = 0; round < 300; round += 1) {
|
||||
const at = Math.floor(random() * lines.length);
|
||||
const kind = random();
|
||||
if (kind < 0.4) lines[at] = line();
|
||||
else if (kind < 0.7) lines.splice(at, 0, line());
|
||||
else if (lines.length > 1) lines.splice(at, 1);
|
||||
states.invalidateFrom(at);
|
||||
if (random() < 0.5) {
|
||||
// A paint of some window, which records states as a side effect.
|
||||
const from = Math.floor(random() * lines.length);
|
||||
const to = Math.min(lines.length - 1, from + Math.floor(random() * 8));
|
||||
keywordRanges({ states, lineText, from, to, matcher: wordMatcher(['TODO']), maxLineLength: 20000 });
|
||||
}
|
||||
const probe = Math.floor(random() * lines.length);
|
||||
const fresh = new LineStates();
|
||||
assert.equal(states.startOf(probe, lineText, 20000), fresh.startOf(probe, lineText, 20000),
|
||||
`round ${round}, line ${probe}`);
|
||||
}
|
||||
});
|
||||
@@ -16,6 +16,8 @@ const { createRestarter } = require('./restart');
|
||||
const { executeCommand } = require('./extract');
|
||||
const { HierarchyView } = require('./hierarchyView');
|
||||
const { ReferencesView } = require('./referencesView');
|
||||
const typing = require('./typing');
|
||||
const { CommentKeywords } = require('./commentKeywords');
|
||||
const mcp = require('./mcp');
|
||||
|
||||
/** The single client, kept only so `deactivate` can stop it. */
|
||||
@@ -200,6 +202,11 @@ function activate(context) {
|
||||
// advertises, so a second registration of the same id would collide with
|
||||
// it at activation.
|
||||
middleware: {
|
||||
// `selectedCompletionInfo` as LSP spells it — the keyword ghost follows
|
||||
// the popup's selected entry, and the client would otherwise send VS
|
||||
// Code's own Range shape (docs/features/completion-ux, `typing.js`).
|
||||
provideInlineCompletionItems: (document, position, context, token, next) =>
|
||||
next(document, position, typing.protocolInlineContext(context), token),
|
||||
executeCommand: (command, args, next) =>
|
||||
executeCommand(
|
||||
{ showInputBox: (options) => vscode.window.showInputBox(options) },
|
||||
@@ -259,6 +266,12 @@ function activate(context) {
|
||||
|
||||
rainbowEnabled = readRainbowSetting();
|
||||
|
||||
// TODO/FIXME/FIX_ME/TBD and `lucisv.commentKeywords.custom` inside comments
|
||||
// (docs/features/comment-highlighting). Client-side only: it needs nothing
|
||||
// from the server, so it paints even while the server is starting.
|
||||
new CommentKeywords(vscode, isVerilog, (line) => client.outputChannel.appendLine(line))
|
||||
.activate(context.subscriptions);
|
||||
|
||||
context.subscriptions.push(
|
||||
// A new editor has no decorations of its own; paint it as it appears.
|
||||
vscode.window.onDidChangeActiveTextEditor(() => repaintVisible()),
|
||||
@@ -267,7 +280,12 @@ function activate(context) {
|
||||
// Typing moves every range after the cursor, so the answer is stale the
|
||||
// moment it arrives; debounce rather than ask on every keystroke.
|
||||
vscode.workspace.onDidChangeTextDocument((event) => {
|
||||
if (isVerilog(event.document)) scheduleRepaint();
|
||||
if (!isVerilog(event.document)) return;
|
||||
scheduleRepaint();
|
||||
// `begin` + Enter writes the `end` (docs/features/completion-ux). Next
|
||||
// tick, so the language client's own listener has sent this change
|
||||
// before the request about it goes out.
|
||||
setTimeout(() => typing.handleChange(autoEndDeps, event), 0);
|
||||
}),
|
||||
vscode.workspace.onDidChangeConfiguration((event) => {
|
||||
// A spawn argument can only change by spawning again, so this one
|
||||
@@ -310,6 +328,42 @@ function deactivate() {
|
||||
return restarter ? restarter.dispose() : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* What `typing.handleChange` needs from VS Code and the client. The edits are
|
||||
* applied with no undo stop before them, so they join the Enter's own undo
|
||||
* step where VS Code allows it.
|
||||
*/
|
||||
const autoEndDeps = {
|
||||
editorFor: (document) =>
|
||||
vscode.window.visibleTextEditors.find((editor) => editor.document === document),
|
||||
formatOnType: (document) =>
|
||||
vscode.workspace.getConfiguration('editor', document).get('formatOnType') === true,
|
||||
autoEnd: (document) => vscode.workspace.getConfiguration('lucisv', document).get('autoEnd') !== false,
|
||||
request: (document, position, editor) =>
|
||||
client.sendRequest('textDocument/onTypeFormatting', {
|
||||
textDocument: { uri: document.uri.toString() },
|
||||
position,
|
||||
ch: '\n',
|
||||
options: {
|
||||
tabSize: Number(editor.options.tabSize) || 2,
|
||||
insertSpaces: editor.options.insertSpaces !== false,
|
||||
},
|
||||
}),
|
||||
apply: async (editor, edits) => {
|
||||
const converted = await client.protocol2CodeConverter.asTextEdits(edits);
|
||||
return editor.edit(
|
||||
(builder) => {
|
||||
for (const edit of converted || []) builder.replace(edit.range, edit.newText);
|
||||
},
|
||||
{ undoStopBefore: false, undoStopAfter: true },
|
||||
);
|
||||
},
|
||||
placeCursor: (editor, line) => {
|
||||
const end = editor.document.lineAt(line).range.end;
|
||||
editor.selection = new vscode.Selection(end, end);
|
||||
},
|
||||
};
|
||||
|
||||
/** True for the documents this extension knows about. */
|
||||
function isVerilog(document) {
|
||||
return LANGUAGES.includes(document.languageId);
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
// Which hierarchy rows lead to the file being edited, and how far from it each
|
||||
// one is. No `vscode` dependency, so plain Node tests cover all of it. See
|
||||
// docs/features/hierarchy-current-path/README.md.
|
||||
//
|
||||
// **A row's distance is a property of its module, not of its path.** It is how
|
||||
// many instantiation levels the module sits above the nearest module declared
|
||||
// in the current file — 0 for that module itself. The level below a row is the
|
||||
// module's own instance list wherever the row sits, so the answer is the same
|
||||
// for every row of a module, and one breadth-first walk up the module graph
|
||||
// answers it for every module at once. A row then costs a map lookup, and
|
||||
// nothing below a closed row is ever built to find out whether to light it.
|
||||
//
|
||||
// In a forward tree the lit rows are exactly the path from the root down to
|
||||
// each current instance. In an upward "Parents of" tree the same rule lights
|
||||
// the current file's parents among the DUT's parents — dimmer the further up
|
||||
// the design they are, which on that tree is further *down* the page.
|
||||
|
||||
const { headerId, parentIndex } = require('./hierarchySections');
|
||||
|
||||
/** The contributed theme colours, brightest first; the last one is the floor
|
||||
* every ancestor four or more levels up shares. */
|
||||
const LIT_COLORS = [
|
||||
'lucisv.hierarchyCurrent',
|
||||
'lucisv.hierarchyParent1',
|
||||
'lucisv.hierarchyParent2',
|
||||
'lucisv.hierarchyParent3',
|
||||
'lucisv.hierarchyAncestor',
|
||||
];
|
||||
|
||||
/** The solid bar at a lit row's left edge. The tints stay light enough for the
|
||||
* label to keep 4.5:1, so the bar is what carries "brightest": widest, solid
|
||||
* and fully opaque on the current row, narrower and fainter each level up. */
|
||||
const BAR_COLOR = 'lucisv.hierarchyCurrentBar';
|
||||
|
||||
/** The level a distance is painted at: 0 is the current row itself. */
|
||||
function litLevel(distance) {
|
||||
if (!Number.isInteger(distance) || distance < 0) return undefined;
|
||||
return Math.min(distance, LIT_COLORS.length - 1);
|
||||
}
|
||||
|
||||
/** The CSS variable a webview sees a theme colour as. VS Code replaces only the
|
||||
* *first* dot (`themeing.ts`: `entry.id.replace('.', '-')`), which is why every
|
||||
* id above has exactly one. */
|
||||
function cssVariableFor(colorId) {
|
||||
return `--vscode-${colorId.replace('.', '-')}`;
|
||||
}
|
||||
|
||||
/// The model's own spellings of the active file: every distinct definition URI
|
||||
/// `sameFile` accepts. The server and VS Code may spell one file differently, so
|
||||
/// the comparison is the caller's; this asks it once per file, not per module.
|
||||
function matchingFiles(model, sameFile) {
|
||||
const files = new Set();
|
||||
const asked = new Set();
|
||||
for (const module of model.modules) {
|
||||
const uri = module.definition.uri;
|
||||
if (asked.has(uri)) continue;
|
||||
asked.add(uri);
|
||||
if (sameFile(uri)) files.add(uri);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/// Everything a render needs to light rows for one active file: the matching
|
||||
/// URIs, every module's distance, and a memo for the upward sections' headers.
|
||||
/// `undefined` when no module is declared there.
|
||||
function currentPath(model, files) {
|
||||
const current = model.modules.filter((module) => files.has(module.definition.uri));
|
||||
if (current.length === 0) return undefined;
|
||||
const parentsOf = (id) => (parentIndex(model).get(id) || []).map((edge) => edge.module);
|
||||
return { files, above: walk(current, parentsOf), parentsOf, sections: new Map() };
|
||||
}
|
||||
|
||||
/// Breadth-first from every current module at once, so where two chains meet
|
||||
/// the nearer one is the one recorded. Linear in modules plus instances.
|
||||
function walk(start, next) {
|
||||
const distance = new Map(start.map((module) => [module.id, 0]));
|
||||
let frontier = start;
|
||||
for (let step = 1; frontier.length > 0; step += 1) {
|
||||
const reached = [];
|
||||
for (const module of frontier) {
|
||||
for (const neighbour of next(module.id)) {
|
||||
if (distance.has(neighbour.id)) continue;
|
||||
distance.set(neighbour.id, step);
|
||||
reached.push(neighbour);
|
||||
}
|
||||
}
|
||||
frontier = reached;
|
||||
}
|
||||
return distance;
|
||||
}
|
||||
|
||||
/// The node's distance, or `undefined` when it is not lit. A forward row that
|
||||
/// cannot open (a leaf, a `recursive` repeat, an unresolved or ambiguous type)
|
||||
/// can only be current itself: what it would lead to is not under it on screen.
|
||||
/// An upward row is always its own module, so its module's distance is its own.
|
||||
function nodeDistance(node, path) {
|
||||
if (node.definition && path.files.has(node.definition.uri)) return 0;
|
||||
if (!node.moduleId || (!node.up && !node.hasChildren)) return undefined;
|
||||
return path.above.get(node.moduleId);
|
||||
}
|
||||
|
||||
/// A header lights one step dimmer than the nearest module its section holds,
|
||||
/// shown or not — which is what tells the user a *closed* section holds the
|
||||
/// current file, or the current file's parents.
|
||||
function sectionDistance(section, path) {
|
||||
const nearest = section.kind === 'parents' ? closureDistance(section, path) : forwardDistance(section, path);
|
||||
return nearest === undefined ? undefined : nearest + 1;
|
||||
}
|
||||
|
||||
/// A forward tree holds the current module exactly when one of its roots has
|
||||
/// a distance, and the current module is 0.
|
||||
function forwardDistance(section, path) {
|
||||
const roots = section.kind === 'others' ? section.roots.map(({ module }) => module)
|
||||
: (section.root ? [section.root] : []);
|
||||
return roots.some((root) => path.above.has(root.moduleId || root.id)) ? 0 : undefined;
|
||||
}
|
||||
|
||||
/// The upward tree holds the DUT and everything above it: the nearest of
|
||||
/// those, walked once per (path, section) and remembered on the path.
|
||||
function closureDistance(section, path) {
|
||||
if (!section.root) return undefined;
|
||||
const key = section.root.moduleId;
|
||||
if (path.sections.has(key)) return path.sections.get(key);
|
||||
let nearest;
|
||||
const seen = new Set([key]);
|
||||
const stack = [section.root.moduleId];
|
||||
while (stack.length > 0) {
|
||||
const id = stack.pop();
|
||||
const distance = path.above.get(id);
|
||||
if (distance !== undefined && (nearest === undefined || distance < nearest)) nearest = distance;
|
||||
for (const parent of path.parentsOf(id)) {
|
||||
if (!seen.has(parent.id)) {
|
||||
seen.add(parent.id);
|
||||
stack.push(parent.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
path.sections.set(key, nearest);
|
||||
return nearest;
|
||||
}
|
||||
|
||||
/// Row id → lit level for the rows on screen. `nodes` is the id → node map the
|
||||
/// tree builders return; `list` is the section list, empty for the plain tree.
|
||||
/// Only lit rows are in the answer.
|
||||
function rowLevels(rows, nodes, list, path) {
|
||||
const levels = new Map();
|
||||
if (!path) return levels;
|
||||
const headers = new Map(list.map((section) => [headerId(section), section]));
|
||||
for (const row of rows) {
|
||||
const node = nodes.get(row.id);
|
||||
let distance;
|
||||
if (node) distance = nodeDistance(node, path);
|
||||
else if (row.kind === 'section' && headers.has(row.id)) distance = sectionDistance(headers.get(row.id), path);
|
||||
const level = litLevel(distance);
|
||||
if (level !== undefined) levels.set(row.id, level);
|
||||
}
|
||||
return levels;
|
||||
}
|
||||
|
||||
/// What changed between two answers of `rowLevels`, as `[id, level | null]`
|
||||
/// pairs: the only rows a new active file repaints.
|
||||
function levelChanges(before, after) {
|
||||
const changes = [];
|
||||
for (const [id, level] of after) {
|
||||
if (before.get(id) !== level) changes.push([id, level]);
|
||||
}
|
||||
for (const id of before.keys()) {
|
||||
if (!after.has(id)) changes.push([id, null]);
|
||||
}
|
||||
return changes;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
BAR_COLOR,
|
||||
LIT_COLORS,
|
||||
cssVariableFor,
|
||||
currentPath,
|
||||
levelChanges,
|
||||
litLevel,
|
||||
matchingFiles,
|
||||
nodeDistance,
|
||||
rowLevels,
|
||||
};
|
||||
@@ -0,0 +1,322 @@
|
||||
const assert = require('assert/strict');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { buildHierarchy, treeRows } = require('./hierarchyModel');
|
||||
const { sectionRows, sections } = require('./hierarchySections');
|
||||
const {
|
||||
BAR_COLOR,
|
||||
LIT_COLORS,
|
||||
cssVariableFor,
|
||||
currentPath,
|
||||
levelChanges,
|
||||
litLevel,
|
||||
matchingFiles,
|
||||
rowLevels,
|
||||
} = require('./hierarchyCurrent');
|
||||
|
||||
/** A snapshot from `{ module: [instantiated type, …] }`, one file per module
|
||||
* (`file:///<module>.sv`), instance names `u_<type>` (`u_<type>_<n>` for a
|
||||
* repeat). A type naming no module is an unresolved instance. */
|
||||
function design(graph, extraDeclarations = []) {
|
||||
const names = Object.keys(graph);
|
||||
const files = [...names.map((name) => `file:///${name}.sv`),
|
||||
...extraDeclarations.map((name) => `file:///${name}_2.sv`)];
|
||||
const place = (file, line) => ({ file, range: [line, 0, line, 9], selectionRange: [line, 1, line, 5] });
|
||||
const modules = names.map((name, file) => {
|
||||
const counts = new Map();
|
||||
const instances = graph[name].map((type, line) => {
|
||||
const n = (counts.get(type) || 0) + 1;
|
||||
counts.set(type, n);
|
||||
return { instanceName: n === 1 ? `u_${type}` : `u_${type}_${n}`, moduleName: type, site: place(file, line + 1) };
|
||||
});
|
||||
return { moduleName: name, definition: place(file, 0), instances };
|
||||
});
|
||||
// A second declaration of an existing name, in its own file: ambiguous.
|
||||
extraDeclarations.forEach((name, at) => {
|
||||
modules.push({ moduleName: name, definition: place(names.length + at, 0), instances: [] });
|
||||
});
|
||||
return buildHierarchy({ schemaVersion: 2, revision: 1, complete: true, files, modules });
|
||||
}
|
||||
|
||||
/** The current-file path for one module's file. */
|
||||
function pathFor(model, name) {
|
||||
return currentPath(model, matchingFiles(model, (uri) => uri === `file:///${name}.sv`));
|
||||
}
|
||||
|
||||
/** Every row of the plain tree, every row opened. */
|
||||
function openTree(model) {
|
||||
const expanded = new Set();
|
||||
for (;;) {
|
||||
const tree = treeRows(model, expanded, '');
|
||||
const before = expanded.size;
|
||||
for (const row of tree.rows) if (row.hasChildren) expanded.add(row.id);
|
||||
if (expanded.size === before) return { ...tree, list: [] };
|
||||
}
|
||||
}
|
||||
|
||||
/** Label → level for the rows that are lit, in row order. */
|
||||
function lit(tree, pathValue) {
|
||||
const levels = rowLevels(tree.rows, tree.nodes, tree.list, pathValue);
|
||||
return tree.rows.filter((row) => levels.has(row.id))
|
||||
.map((row) => [`${' '.repeat(row.depth)}${row.label}`, levels.get(row.id)]);
|
||||
}
|
||||
|
||||
function distancesMapToLevelsWithAFloor() {
|
||||
assert.deepEqual([0, 1, 2, 3, 4, 5, 40].map(litLevel), [0, 1, 2, 3, 4, 4, 4]);
|
||||
assert.equal(litLevel(undefined), undefined);
|
||||
assert.equal(litLevel(-1), undefined);
|
||||
assert.equal(litLevel(1.5), undefined);
|
||||
assert.equal(LIT_COLORS.length, 5, 'one colour per level, the floor included');
|
||||
}
|
||||
|
||||
/** VS Code turns only the first dot into a dash (`themeing.ts`), so an id with
|
||||
* two dots would reach the webview under a name no stylesheet expects. */
|
||||
function colourIdsHaveOneDotAndTheCssUsesTheirVariables() {
|
||||
assert.equal(cssVariableFor('lucisv.hierarchyCurrent'), '--vscode-lucisv-hierarchyCurrent');
|
||||
assert.equal(cssVariableFor('a.b.c'), '--vscode-a-b.c', 'first dot only, as VS Code does');
|
||||
const css = fs.readFileSync(path.join(__dirname, 'media', 'hierarchy.css'), 'utf8');
|
||||
assert(css.includes(`var(${cssVariableFor(BAR_COLOR)},`), 'hierarchy.css paints the bar with its colour');
|
||||
assert.equal(BAR_COLOR.split('.').length, 2, `${BAR_COLOR} has exactly one dot`);
|
||||
LIT_COLORS.forEach((id, level) => {
|
||||
assert.equal(id.split('.').length, 2, `${id} has exactly one dot`);
|
||||
assert(css.includes(`.row[data-lit="${level}"] { --lit: var(${cssVariableFor(id)},`),
|
||||
`hierarchy.css paints level ${level} with ${id}`);
|
||||
});
|
||||
}
|
||||
|
||||
function packageJsonContributesTheColoursAndTheSetting() {
|
||||
const manifest = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
|
||||
const ours = manifest.contributes.colors.filter((colour) => colour.id.startsWith('lucisv.hierarchy'));
|
||||
assert.deepEqual(ours.map((colour) => colour.id), [...LIT_COLORS, BAR_COLOR], 'contributed exactly, in level order');
|
||||
const bar = ours.at(-1);
|
||||
for (const theme of ['dark', 'light', 'highContrast', 'highContrastLight']) {
|
||||
assert.match(bar.defaults[theme], /^#[0-9A-F]{6}$/, `the bar is opaque in ${theme}`);
|
||||
}
|
||||
const colours = ours.slice(0, -1);
|
||||
for (const colour of colours) {
|
||||
assert(colour.description, `${colour.id} has a description`);
|
||||
for (const theme of ['dark', 'light', 'highContrast', 'highContrastLight']) {
|
||||
assert.match(colour.defaults[theme], /^#[0-9A-F]{8}$/, `${colour.id} has a translucent ${theme} default`);
|
||||
}
|
||||
}
|
||||
// Dimmer each step: the alpha falls level by level in every theme.
|
||||
for (const theme of ['dark', 'light', 'highContrast', 'highContrastLight']) {
|
||||
const alphas = colours.map((colour) => parseInt(colour.defaults[theme].slice(7), 16));
|
||||
assert(alphas.every((alpha, at) => at === 0 || alpha < alphas[at - 1]), `${theme} dims level by level`);
|
||||
assert(alphas.at(-1) > 0, `${theme}'s floor is still visible`);
|
||||
}
|
||||
const setting = manifest.contributes.configuration.properties['lucisv.hierarchy.highlightCurrent'];
|
||||
assert.equal(setting.type, 'boolean');
|
||||
assert.equal(setting.default, true);
|
||||
}
|
||||
|
||||
function theCurrentRowAndEachAncestorAreLitByDistance() {
|
||||
const model = design({ tb: ['dut'], dut: ['leaf', 'other'], leaf: [], other: [], lonely: [] });
|
||||
assert.deepEqual(lit(openTree(model), pathFor(model, 'leaf')), [
|
||||
['tb', 2],
|
||||
[' u_dut (dut)', 1],
|
||||
[' u_leaf (leaf)', 0],
|
||||
], 'the sibling and the unrelated root stay unlit');
|
||||
assert.deepEqual(lit(openTree(model), pathFor(model, 'tb')), [['tb', 0]]);
|
||||
}
|
||||
|
||||
/** The point of the feature: a closed tree still says where the file is. */
|
||||
function aClosedTreeLightsTheRowsItShows() {
|
||||
const model = design({ tb: ['dut'], dut: ['leaf'], leaf: [] });
|
||||
const closed = { ...treeRows(model, new Set(), ''), list: [] };
|
||||
assert.deepEqual(lit(closed, pathFor(model, 'leaf')), [['tb', 2]]);
|
||||
}
|
||||
|
||||
function everyInstanceAndItsChainIsLitAndTheNearestDistanceWins() {
|
||||
// `shared` is under `top` directly and through `mid`, twice.
|
||||
const model = design({ top: ['mid', 'shared'], mid: ['shared', 'shared'], shared: [] });
|
||||
assert.deepEqual(lit(openTree(model), pathFor(model, 'shared')), [
|
||||
['top', 1],
|
||||
[' u_mid (mid)', 1],
|
||||
[' u_shared (shared)', 0],
|
||||
[' u_shared_2 (shared)', 0],
|
||||
[' u_shared (shared)', 0],
|
||||
], 'top is one level above its own instance, not two through mid');
|
||||
}
|
||||
|
||||
function deepAncestorsShareTheFloor() {
|
||||
const model = design({ a: ['b'], b: ['c'], c: ['d'], d: ['e'], e: ['f'], f: [] });
|
||||
assert.deepEqual(lit(openTree(model), pathFor(model, 'f')).map(([, level]) => level), [4, 4, 3, 2, 1, 0]);
|
||||
}
|
||||
|
||||
/** A file declaring two modules lights both, each with its own path. */
|
||||
function aFileDeclaringTwoModulesLightsBoth() {
|
||||
const model = design({ top: ['x', 'y'], x: [], y: [] });
|
||||
const both = currentPath(model, matchingFiles(model, (uri) => uri === 'file:///x.sv' || uri === 'file:///y.sv'));
|
||||
assert.deepEqual(lit(openTree(model), both), [['top', 1], [' u_x (x)', 0], [' u_y (y)', 0]]);
|
||||
}
|
||||
|
||||
/** A row that cannot open is lit only when it is itself current: an unresolved
|
||||
* or ambiguous type names no one module, and a `recursive` repeat leads
|
||||
* nowhere on screen. */
|
||||
function rowsThatCannotOpenAreOnlyEverCurrent() {
|
||||
const ambiguous = design({ top: ['dup', 'ghost'], dup: [] }, ['dup']);
|
||||
assert.deepEqual(lit(openTree(ambiguous), pathFor(ambiguous, 'dup')), [['dup', 0]],
|
||||
'the declaration in the file is lit; the ambiguous instance names no one module, so top is not above it');
|
||||
|
||||
const cycle = design({ top: ['a'], a: ['b'], b: ['a'] });
|
||||
assert.deepEqual(lit(openTree(cycle), pathFor(cycle, 'a')), [
|
||||
['top', 1],
|
||||
[' u_a (a)', 0],
|
||||
[' u_b (b)', 1],
|
||||
[' u_a (a)', 0],
|
||||
], 'the recursive repeat is current itself; b, between them, is one above it');
|
||||
const rows = lit(openTree(cycle), pathFor(cycle, 'b'));
|
||||
assert.deepEqual(rows, [['top', 2], [' u_a (a)', 1], [' u_b (b)', 0]],
|
||||
'the recursive `a` under b does not open, so it is not lit as b\'s parent');
|
||||
}
|
||||
|
||||
function aFileNoModuleIsDeclaredInLightsNothing() {
|
||||
const model = design({ top: ['leaf'], leaf: [] });
|
||||
assert.equal(currentPath(model, matchingFiles(model, () => false)), undefined);
|
||||
const tree = openTree(model);
|
||||
assert.equal(rowLevels(tree.rows, tree.nodes, tree.list, undefined).size, 0);
|
||||
}
|
||||
|
||||
function theFileComparisonIsAskedOncePerFile() {
|
||||
const model = design({ top: ['leaf', 'leaf'], leaf: [] });
|
||||
const asked = [];
|
||||
matchingFiles(model, (uri) => { asked.push(uri); return false; });
|
||||
assert.deepEqual(asked.sort(), ['file:///leaf.sv', 'file:///top.sv']);
|
||||
}
|
||||
|
||||
/** DUT sections: the forward section lights like the plain tree, the upward
|
||||
* "Parents of" tree lights the current file's parents by the same distance,
|
||||
* and every header is one level dimmer than the nearest module it holds. */
|
||||
function sectionsLightTheirTreesAndTheirHeaders() {
|
||||
const model = design({ tb: ['dut', 'mon'], dut: ['leaf'], leaf: [], mon: [], lonely: [] });
|
||||
const list = sections(model, ['dut']);
|
||||
const expanded = new Set(['sec:dut:dut', 'sec:parents:dut', 'sec:others']);
|
||||
for (let round = 0; round < 4; round += 1) {
|
||||
for (const row of sectionRows(model, list, expanded, '').rows) if (row.hasChildren) expanded.add(row.id);
|
||||
}
|
||||
const tree = { ...sectionRows(model, list, expanded, ''), list };
|
||||
|
||||
assert.deepEqual(lit(tree, pathFor(model, 'leaf')), [
|
||||
['DUT: dut', 1],
|
||||
[' dut', 1],
|
||||
[' u_leaf (leaf)', 0],
|
||||
['Parents of dut', 2],
|
||||
[' dut', 1],
|
||||
[' tb', 2],
|
||||
], "the forward section is the path down to leaf; the upward one is leaf's parents, dimmer going up the design");
|
||||
|
||||
assert.deepEqual(lit(tree, pathFor(model, 'tb')), [
|
||||
['Parents of dut', 1],
|
||||
[' tb', 0],
|
||||
], 'tb is current wherever it is shown; the DUT is below it, so it is not lit');
|
||||
|
||||
// mon is beside the DUT, not above it: the upward tree holds mon's parent tb,
|
||||
// and mon itself is re-rooted in "Other modules" (dut-hierarchy's rule).
|
||||
assert.deepEqual(lit(tree, pathFor(model, 'mon')), [
|
||||
['Parents of dut', 2],
|
||||
[' tb', 1],
|
||||
['Other modules', 1],
|
||||
[' mon', 0],
|
||||
]);
|
||||
|
||||
assert.deepEqual(lit(tree, pathFor(model, 'lonely')), [
|
||||
['Other modules', 1],
|
||||
[' lonely', 0],
|
||||
]);
|
||||
|
||||
// Closed sections still say which ones hold the file or its parents.
|
||||
const closed = { ...sectionRows(model, list, new Set(), ''), list };
|
||||
assert.deepEqual(lit(closed, pathFor(model, 'leaf')), [['DUT: dut', 1], ['Parents of dut', 2]]);
|
||||
assert.deepEqual(lit(closed, pathFor(model, 'lonely')), [['Other modules', 1]]);
|
||||
}
|
||||
|
||||
/** A recursive repeat in the upward tree is still its own module, so it is lit
|
||||
* as that module — the upward rule has no "cannot open" exception. */
|
||||
function anUpwardRepeatIsLitAsItsModule() {
|
||||
const model = design({ top: ['a'], a: ['b'], b: ['a', 'leaf'], leaf: [] });
|
||||
const list = sections(model, ['b']);
|
||||
const expanded = new Set(['sec:parents:b']);
|
||||
for (let round = 0; round < 5; round += 1) {
|
||||
for (const row of sectionRows(model, list, expanded, '').rows) if (row.hasChildren) expanded.add(row.id);
|
||||
}
|
||||
const tree = { ...sectionRows(model, list, expanded, ''), list };
|
||||
const levels = rowLevels(tree.rows, tree.nodes, tree.list, pathFor(model, 'leaf'));
|
||||
const upward = tree.rows.filter((row) => row.id === 'sec:parents:b' || row.id.startsWith('parents:'))
|
||||
.map((row) => [`${' '.repeat(row.depth)}${row.label}`, levels.get(row.id)]);
|
||||
assert.deepEqual(upward, [
|
||||
['Parents of b', 2],
|
||||
[' b', 1],
|
||||
[' a', 2],
|
||||
[' b', 1],
|
||||
[' top', 3],
|
||||
], 'the repeated b closes the cycle and does not open, but is still b, one above leaf');
|
||||
}
|
||||
|
||||
function changesNameOnlyTheRowsWhoseLevelMoved() {
|
||||
const before = new Map([['a', 0], ['b', 1], ['c', 2]]);
|
||||
const after = new Map([['a', 0], ['b', 2], ['d', 0]]);
|
||||
assert.deepEqual(levelChanges(before, after), [['b', 2], ['d', 0], ['c', null]]);
|
||||
assert.deepEqual(levelChanges(after, after), []);
|
||||
}
|
||||
|
||||
/** Ids are untouched: lighting is a separate answer, never part of a row's id. */
|
||||
function lightingNeverChangesRowIds() {
|
||||
const model = design({ tb: ['dut'], dut: ['leaf'], leaf: [] });
|
||||
const tree = openTree(model);
|
||||
const ids = tree.rows.map((row) => row.id);
|
||||
rowLevels(tree.rows, tree.nodes, tree.list, pathFor(model, 'leaf'));
|
||||
assert.deepEqual(openTree(model).rows.map((row) => row.id), ids);
|
||||
}
|
||||
|
||||
/** QA, 2026-11-19: edge cases the suite did not pin. */
|
||||
function anEmptySnapshotLightsNothing() {
|
||||
const model = buildHierarchy({ schemaVersion: 2, revision: 1, complete: true, files: [], modules: [] });
|
||||
assert.equal(currentPath(model, matchingFiles(model, () => true)), undefined);
|
||||
}
|
||||
|
||||
/** Two chains of different length to one ancestor: the shorter one is its
|
||||
* distance, and each row on the longer chain keeps its own. */
|
||||
function theShorterOfTwoUnequalChainsWins() {
|
||||
const model = design({ top: ['a', 'leaf'], a: ['b'], b: ['c'], c: ['leaf'], leaf: [] });
|
||||
assert.deepEqual(lit(openTree(model), pathFor(model, 'leaf')), [
|
||||
['top', 1],
|
||||
[' u_a (a)', 3],
|
||||
[' u_b (b)', 2],
|
||||
[' u_c (c)', 1],
|
||||
[' u_leaf (leaf)', 0],
|
||||
[' u_leaf (leaf)', 0],
|
||||
]);
|
||||
}
|
||||
|
||||
/** A module instantiating itself terminates, and its cut repeat is lit only
|
||||
* when it is the current module. */
|
||||
function aSelfInstantiatingModuleTerminates() {
|
||||
const model = design({ top: ['a'], a: ['a', 'leaf'], leaf: [] });
|
||||
assert.deepEqual(lit(openTree(model), pathFor(model, 'leaf')), [['top', 2], [' u_a (a)', 1], [' u_leaf (leaf)', 0]]);
|
||||
assert.deepEqual(lit(openTree(model), pathFor(model, 'a')), [['top', 1], [' u_a (a)', 0], [' u_a (a)', 0]]);
|
||||
}
|
||||
|
||||
const tests = [
|
||||
anEmptySnapshotLightsNothing,
|
||||
theShorterOfTwoUnequalChainsWins,
|
||||
aSelfInstantiatingModuleTerminates,
|
||||
distancesMapToLevelsWithAFloor,
|
||||
colourIdsHaveOneDotAndTheCssUsesTheirVariables,
|
||||
packageJsonContributesTheColoursAndTheSetting,
|
||||
theCurrentRowAndEachAncestorAreLitByDistance,
|
||||
aClosedTreeLightsTheRowsItShows,
|
||||
everyInstanceAndItsChainIsLitAndTheNearestDistanceWins,
|
||||
deepAncestorsShareTheFloor,
|
||||
aFileDeclaringTwoModulesLightsBoth,
|
||||
rowsThatCannotOpenAreOnlyEverCurrent,
|
||||
aFileNoModuleIsDeclaredInLightsNothing,
|
||||
theFileComparisonIsAskedOncePerFile,
|
||||
sectionsLightTheirTreesAndTheirHeaders,
|
||||
anUpwardRepeatIsLitAsItsModule,
|
||||
changesNameOnlyTheRowsWhoseLevelMoved,
|
||||
lightingNeverChangesRowIds,
|
||||
];
|
||||
for (const test of tests) test();
|
||||
|
||||
console.log(`hierarchy current path: OK — ${tests.length} checks: distances and the floor, colour ids and CSS variables, the manifest, every instance lit, nearest distance wins, closed trees and sections, the upward tree, cycles and unresolved rows`);
|
||||
@@ -0,0 +1,149 @@
|
||||
// The current-path palette, measured: the five tints and the bar contributed in
|
||||
// package.json, blended over representative sidebar colours of the built-in
|
||||
// themes, must keep the row label readable (WCAG AA, 4.5:1) at every level —
|
||||
// hovered too — and keep neighbouring levels visibly apart (ΔE76 ≥ 3). This is
|
||||
// what stops a palette tweak from silently making the brightest row the
|
||||
// hardest one to read (QA F1/F2, docs/features/hierarchy-current-path).
|
||||
const assert = require('assert/strict');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { BAR_COLOR, LIT_COLORS } = require('./hierarchyCurrent');
|
||||
|
||||
/** Sidebar background, list foreground, list hover background per theme. */
|
||||
const THEMES = [
|
||||
{ kind: 'dark', name: 'Dark Modern', background: '#181818', foreground: '#CCCCCC', hover: '#2A2D2E' },
|
||||
{ kind: 'dark', name: 'Dark+', background: '#252526', foreground: '#CCCCCC', hover: '#2A2D2E' },
|
||||
{ kind: 'light', name: 'Light Modern', background: '#F8F8F8', foreground: '#3B3B3B', hover: '#F2F2F2' },
|
||||
{ kind: 'light', name: 'Light+', background: '#F3F3F3', foreground: '#616161', hover: '#E8E8E8' },
|
||||
{ kind: 'highContrast', name: 'HC Dark', background: '#000000', foreground: '#FFFFFF' },
|
||||
{ kind: 'highContrastLight', name: 'HC Light', background: '#FFFFFF', foreground: '#292929' },
|
||||
];
|
||||
|
||||
const TEXT_CONTRAST = 4.5;
|
||||
const BAR_CONTRAST = 3;
|
||||
const NEIGHBOUR_DELTA_E = 3;
|
||||
|
||||
function rgba(hex) {
|
||||
const value = hex.replace('#', '');
|
||||
const channel = (at) => parseInt(value.slice(at, at + 2), 16);
|
||||
return { rgb: [channel(0), channel(2), channel(4)], alpha: value.length === 8 ? channel(6) / 255 : 1 };
|
||||
}
|
||||
|
||||
/** Source-over, rounded to 8 bits as the compositor does. */
|
||||
function over(hex, background) {
|
||||
const { rgb, alpha } = rgba(hex);
|
||||
const base = rgba(background).rgb;
|
||||
return rgb.map((c, at) => Math.round(c * alpha + base[at] * (1 - alpha)));
|
||||
}
|
||||
|
||||
function linear(channel) {
|
||||
const c = channel / 255;
|
||||
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
||||
}
|
||||
|
||||
function luminance(rgb) {
|
||||
const [r, g, b] = rgb.map(linear);
|
||||
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
}
|
||||
|
||||
function contrast(a, b) {
|
||||
const [high, low] = [luminance(a), luminance(b)].sort((x, y) => y - x);
|
||||
return (high + 0.05) / (low + 0.05);
|
||||
}
|
||||
|
||||
function lab(rgb) {
|
||||
const [r, g, b] = rgb.map(linear);
|
||||
const x = (r * 0.4124 + g * 0.3576 + b * 0.1805) / 0.95047;
|
||||
const y = r * 0.2126 + g * 0.7152 + b * 0.0722;
|
||||
const z = (r * 0.0193 + g * 0.1192 + b * 0.9505) / 1.08883;
|
||||
const f = (t) => (t > 0.008856 ? Math.cbrt(t) : 7.787 * t + 16 / 116);
|
||||
return [116 * f(y) - 16, 500 * (f(x) - f(y)), 200 * (f(y) - f(z))];
|
||||
}
|
||||
|
||||
function deltaE(a, b) {
|
||||
const [p, q] = [lab(a), lab(b)];
|
||||
return Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2]);
|
||||
}
|
||||
|
||||
const toHex = (rgb) => `#${rgb.map((c) => c.toString(16).padStart(2, '0')).join('')}`;
|
||||
|
||||
const manifest = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
|
||||
const byId = new Map(manifest.contributes.colors.map((colour) => [colour.id, colour]));
|
||||
const defaultsOf = (id) => {
|
||||
assert(byId.has(id), `${id} is contributed`);
|
||||
return byId.get(id).defaults;
|
||||
};
|
||||
|
||||
/** One table row per theme, printed so a palette change shows its numbers. */
|
||||
function measure(theme) {
|
||||
const levels = LIT_COLORS.map((id) => over(defaultsOf(id)[theme.kind], theme.background));
|
||||
const unlit = rgba(theme.background).rgb;
|
||||
const foreground = rgba(theme.foreground).rgb;
|
||||
return {
|
||||
levels,
|
||||
text: levels.map((level) => contrast(foreground, level)),
|
||||
hovered: theme.hover
|
||||
? LIT_COLORS.map((id) => contrast(foreground, over(defaultsOf(id)[theme.kind], theme.hover)))
|
||||
: [],
|
||||
// Neighbours from the brightest down, then the floor against an unlit row.
|
||||
steps: [...levels.slice(1).map((level, at) => deltaE(level, levels[at])), deltaE(levels.at(-1), unlit)],
|
||||
fromUnlit: levels.map((level) => deltaE(level, unlit)),
|
||||
bar: contrast(over(defaultsOf(BAR_COLOR)[theme.kind], theme.background), unlit),
|
||||
};
|
||||
}
|
||||
|
||||
function everyLevelKeepsTheLabelReadable() {
|
||||
for (const theme of THEMES) {
|
||||
const { text, hovered } = measure(theme);
|
||||
text.forEach((ratio, level) => assert(ratio >= TEXT_CONTRAST,
|
||||
`${theme.name}: label on level ${level} is ${ratio.toFixed(2)}:1, under ${TEXT_CONTRAST}`));
|
||||
hovered.forEach((ratio, level) => assert(ratio >= TEXT_CONTRAST,
|
||||
`${theme.name}: label on hovered level ${level} is ${ratio.toFixed(2)}:1, under ${TEXT_CONTRAST}`));
|
||||
}
|
||||
}
|
||||
|
||||
function neighbouringLevelsCanBeToldApart() {
|
||||
for (const theme of THEMES) {
|
||||
measure(theme).steps.forEach((step, at) => {
|
||||
const pair = at === LIT_COLORS.length - 1 ? `floor/unlit` : `${at}/${at + 1}`;
|
||||
assert(step >= NEIGHBOUR_DELTA_E, `${theme.name}: levels ${pair} differ by ΔE ${step.toFixed(1)}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function theCurrentRowIsTheBrightest() {
|
||||
for (const theme of THEMES) {
|
||||
const { fromUnlit } = measure(theme);
|
||||
assert(fromUnlit.every((distance, at) => at === 0 || distance < fromUnlit[at - 1]),
|
||||
`${theme.name}: each level is further from an unlit row than the next`);
|
||||
}
|
||||
}
|
||||
|
||||
/** The bar carries the brightness the tint gave up for legibility, so it must
|
||||
* itself be visible: WCAG 1.4.11 non-text contrast against the sidebar. */
|
||||
function theBarStandsOutFromTheSidebar() {
|
||||
for (const theme of THEMES) {
|
||||
const { bar } = measure(theme);
|
||||
assert(bar >= BAR_CONTRAST, `${theme.name}: the current-row bar is ${bar.toFixed(2)}:1, under ${BAR_CONTRAST}`);
|
||||
}
|
||||
}
|
||||
|
||||
function printTable() {
|
||||
for (const theme of THEMES) {
|
||||
const m = measure(theme);
|
||||
const fmt = (list, digits) => list.map((value) => value.toFixed(digits)).join(' ');
|
||||
console.log(` ${theme.name.padEnd(12)} text ${fmt(m.text, 2)}${m.hovered.length ? ` | hovered ${fmt(m.hovered, 2)}` : ''}`
|
||||
+ ` | ΔE 0/1..floor/unlit ${fmt(m.steps, 1)} | bar ${m.bar.toFixed(2)} | ${m.levels.map(toHex).join(' ')}`);
|
||||
}
|
||||
}
|
||||
|
||||
const tests = [
|
||||
everyLevelKeepsTheLabelReadable,
|
||||
neighbouringLevelsCanBeToldApart,
|
||||
theCurrentRowIsTheBrightest,
|
||||
theBarStandsOutFromTheSidebar,
|
||||
];
|
||||
for (const test of tests) test();
|
||||
if (process.env.LUCISV_PALETTE_TABLE) printTable();
|
||||
|
||||
console.log(`hierarchy palette: OK — ${tests.length} checks over ${THEMES.length} themes: label ≥ ${TEXT_CONTRAST}:1 on every level and hovered, neighbours ΔE ≥ ${NEIGHBOUR_DELTA_E}, brightest first, bar ≥ ${BAR_CONTRAST}:1`);
|
||||
Loaded 100 of 115 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user