Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
10cb6e020f | ||
|
|
cc1e2c8b72 | ||
|
|
c1c1407498 | ||
|
|
a8c22dcab0 | ||
|
|
934d472af2 |
No files matched your search
+25
-2
@@ -1,7 +1,9 @@
|
||||
# CI: the three checks CLAUDE.md requires before any work is finished,
|
||||
# plus the extension's JavaScript tests and the corpus gate, enforced on
|
||||
# every push. Runs on the self-hosted mac-arm64 runner in host mode (no
|
||||
# containers), so the toolchain is the same one releases are built with.
|
||||
# every push. Runs on the self-hosted macOS runner in host mode (no
|
||||
# containers), so the toolchain is the same one releases are built with —
|
||||
# and, since 0.65.9, the same checks on Linux (the `linux` job below), where
|
||||
# the released Linux binaries had never been compiled-and-tested before.
|
||||
name: ci
|
||||
on:
|
||||
push:
|
||||
@@ -41,3 +43,24 @@ jobs:
|
||||
run: cargo build --release -p lucisv
|
||||
- name: Score and gate
|
||||
run: scripts/corpus_gate.sh "$CORPUS"
|
||||
|
||||
# The suite on Linux x86-64: the luhpe-linux-x64 runner starts each job in
|
||||
# the runner image (as root, 4 CPUs / 8 GB for the whole runner), with no
|
||||
# Rust in it, so the toolchain is installed per job and the build is cold
|
||||
# (a few minutes). Clippy is here as well as on macOS because code behind
|
||||
# cfg(unix)/cfg(target_os) is only compiled on the platform it names: the
|
||||
# first Linux trial failed clippy on imports macOS never saw. To run the
|
||||
# same thing from a working tree without a push: tools/linux_check.sh.
|
||||
linux:
|
||||
runs-on: linux-x64
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install the Rust toolchain
|
||||
run: |
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
|
||||
| sh -s -- -y --profile minimal -c clippy,rustfmt
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
- name: cargo clippy
|
||||
run: cargo clippy --all-targets -- -D warnings
|
||||
- name: cargo test
|
||||
run: cargo test --workspace
|
||||
+223
@@ -4,6 +4,229 @@ 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.66.0 — 2026-11-19
|
||||
|
||||
### The overnight queue, complete
|
||||
|
||||
0.66.0 closes TODO §71: eight owner-ordered features, each shipped as its own
|
||||
0.65.x release with a dev round, a QA round and the full gates. Nothing in
|
||||
the engine changed between 0.65.11 and this release; it adds the topology
|
||||
and size re-measurement (`docs/topo.md`, `CLAUDE.md`) and is the version to
|
||||
install. Each line names the release that carries the detail below.
|
||||
|
||||
- **Editing and saving no longer re-index the workspace** (0.65.6/0.65.7).
|
||||
A saved or changed file updates its own records and the files that depend
|
||||
on it; only a change that can reach everything (a config, a filelist)
|
||||
rescans.
|
||||
- **Actions on the open file do not wait for the workspace** (0.65.11).
|
||||
Hover, go-to-definition, highlights, the outline and folding for names the
|
||||
file declares answer in milliseconds during a scan or a rescan, and
|
||||
completion lists what the file can reach first.
|
||||
- **Highlighting does not wait for the index** (0.65.10). Colours come from
|
||||
the buffer at once, as a best guess for cross-file names, and are
|
||||
corrected by one refresh when the index settles.
|
||||
- **`` `ifdef `` / `` `else `` / `` `endif `` branches fold** and take part
|
||||
in sticky scroll (0.65.4).
|
||||
- **Formatter styles** (0.65.5): `auto` follows the file's own style, or
|
||||
choose `lucisv`, `ansi`, `google`, `lowrisc`, `microsoft` or `nxp`; the presets are one readable
|
||||
table in `vlog_formatter/src/style.rs`.
|
||||
- **The module view marks where you are** (0.65.2): the current file's
|
||||
module and its parents, in shades of orange.
|
||||
- **Find References next to a name** (0.65.8): a caret just past a name's
|
||||
last letter now finds it — the cause of "no references" that worked on a
|
||||
second try — and edits arriving during a rescan are applied in order.
|
||||
- **Comments are comments** (0.65.3): no bracket or code colouring inside
|
||||
them, and `TODO`, `FIXME`, `FIX_ME`, `TBD` and your own words
|
||||
(`lucisv.commentKeywords.custom`) are highlighted.
|
||||
|
||||
Also since 0.65.0: releases are gated by `tools/gates.sh`, which
|
||||
compile-checks Windows and Linux (0.65.1, 0.65.7); CI runs the suite on
|
||||
Linux as well as macOS, and `lucisv-mcp` no longer serves stale contents
|
||||
after a same-instant rewrite (0.65.9).
|
||||
|
||||
One test change in this release: 0.65.11's Linux CI run failed on a
|
||||
wall-clock test of the large-file path (24.9x measured against a 24x limit
|
||||
on a loaded runner; nothing in that path had changed). The test now
|
||||
re-measures up to three times before failing — a real quadratic regression
|
||||
measures ~64x every time.
|
||||
|
||||
**Not yet seen in a running editor by a human** — every feature above was
|
||||
verified through the server's protocol and the extension's tests, on
|
||||
OpenTitan's `hw` tree. Open follow-ups are listed in TODO §71.
|
||||
|
||||
## 0.65.11 — 2026-11-19
|
||||
|
||||
### Actions on the open file no longer wait for the workspace
|
||||
|
||||
(`docs/features/fast-actions`; TODO §71.2. Measured on OpenTitan's `hw` tree
|
||||
and on generated 20 000- and 40 000-file trees, with the server driven the
|
||||
way VS Code drives it.)
|
||||
|
||||
- **Same-file answers come from the file.** A hover, a go-to-definition, a
|
||||
type definition, highlights, a rename's first check or a signature help on
|
||||
a name the file itself declares — and the outline, folding and selection
|
||||
ranges — are answered from the open buffer at once, even while the index
|
||||
is being built or rebuilt. Anything that might live in another file still
|
||||
waits for the index it needs.
|
||||
|
||||
| hover on a local name (4 000 / 20 000 / 40 000 files) | 0.65.10 | now |
|
||||
|---|---:|---:|
|
||||
| during the startup scan | 547 / 665 / 831 ms | 2.4 / 1.5 / 1.9 ms |
|
||||
| a new file triggers a rescan, request 5 ms later | 1.2 / 6.0 / 12.3 s | 47 / 167 / 321 ms |
|
||||
| the same, request read together with the event | 1.2 / 6.0 / 12.3 s | 0.3 / 0.1 / 0.1 ms |
|
||||
| the same, server busy with a previous delete | 1.3 / 7.0 / 14.3 s | 0.17 / 0.99 / 2.2 s |
|
||||
|
||||
- **Every early answer is the settled answer.** A request goes ahead only
|
||||
when its buffer is open, every older message that could change the buffer
|
||||
has been applied, its analysis is current, no settings are still on their
|
||||
way, and the answer is the buffer's alone. 2.9 million early answers were
|
||||
compared with the answer the finished index gives; none differed.
|
||||
- **Completion keeps what the file can reach near the top.** Right after the
|
||||
file's own names it now offers the members of the packages the file
|
||||
imports, what its class inherits and the macros of the headers it
|
||||
includes, so a huge workspace no longer pushes them out of the list; such
|
||||
a name shows the icon and detail of the declaration the file actually
|
||||
reaches. Completion answers are half the size for VS Code.
|
||||
- **A new `lucisv.largeFile.threshold` applies to files already open,** the
|
||||
editor's first settings answer included — not at each file's next edit.
|
||||
- **Fixed on the way** (present since 0.65.8 and 0.65.10): the editor's
|
||||
answer to a settings request could be applied ahead of an older settings
|
||||
change or edit; colours answered while a file-watcher event was waiting
|
||||
were not refreshed afterwards.
|
||||
- **What it costs.** Until the editor has answered the server's first
|
||||
settings request, same-file requests wait (the threshold may change how
|
||||
the file is read): with an editor that takes 0.5 s to answer, the first
|
||||
outline arrives after 515 ms — it was 1 043 ms on 0.65.10.
|
||||
- **Still to come.** Not yet seen in a running editor by a human.
|
||||
|
||||
## 0.65.10 — 2026-11-19
|
||||
|
||||
### Highlighting no longer waits for the index
|
||||
|
||||
(`docs/features/viewport-highlight`; TODO §71.3. Measured on OpenTitan's `hw`
|
||||
tree with the server driven the way VS Code drives it.)
|
||||
|
||||
- **Colours arrive at once.** Building a file's colours takes 0.3–6.5 ms;
|
||||
nearly all of the wait before first colour was the server holding every
|
||||
request until the index was ready. A colouring request for a buffer whose
|
||||
text is current is now answered from that buffer alone, even while a scan
|
||||
or a widening of the index holds everything else.
|
||||
|
||||
| first colour after opening a file | before | now |
|
||||
|---|---:|---:|
|
||||
| cold start, whole-workspace scope | 660–685 ms | 3.5–39 ms |
|
||||
| cold start, folder scope (the default) | 38–74 ms | 3–32 ms |
|
||||
| a file opened after startup settled, folder scope | 611–641 ms | 2–32 ms |
|
||||
| a file in a folder not indexed yet, mid-session | 375 ms | 6 ms |
|
||||
| while a rescan runs | 325–791 ms | 70–159 ms |
|
||||
|
||||
The larger figure in each range is a 545 KB file, whose own parse is most
|
||||
of what remains.
|
||||
- **Imperfect first, then corrected — once.** Before the index settles,
|
||||
names that resolve through it (a module or package in another file, an
|
||||
inherited method) are coloured as local guesses: 96.8 % of tokens already
|
||||
match the final answer, and nothing is ever coloured as code inside a
|
||||
comment or a string. When the index settles the server sends one
|
||||
`workspace/semanticTokens/refresh` and the editor's next answer is the
|
||||
accurate one. This also fixes colours that used to stay wrong until the
|
||||
next edit: the first answer was built from a half-finished index and never
|
||||
revisited (2 745 tokens in one OpenTitan file).
|
||||
- **The viewport request costs the viewport.** `semanticTokens/range` built
|
||||
the whole file's tokens and filtered them; it now classifies only the
|
||||
visible lines (0.3 ms for 60 lines of a 4 000-module buffer, against 98 ms).
|
||||
- **What it will not do.** A buffer with edits the server has not applied
|
||||
yet still waits — its existing colours stay on screen. An editor that
|
||||
cannot be asked to refresh gets early viewport colours only, and its
|
||||
whole-file answer waits as before. Hover, go-to-definition and every other
|
||||
request still wait for the index they need; QA compared 978 such answers
|
||||
with 0.65.8's and they are identical.
|
||||
- **Still to come.** The file-discovery walk at the start of every scan
|
||||
answers nothing while it runs, which is what is left of the wait in
|
||||
whole-workspace scope (62–86 ms for a late open) and during rescans. Not
|
||||
yet seen in a running editor by a human.
|
||||
|
||||
## 0.65.9 — 2026-11-19
|
||||
|
||||
### `lucisv-mcp` no longer serves stale contents; the suite runs on Linux
|
||||
|
||||
(`docs/features/linux-test-portability`, Round 2; TODO §70.)
|
||||
|
||||
- **`lucisv-mcp` no longer answers from a file's old contents after a
|
||||
same-size rewrite that restores its old modification time.** The server
|
||||
decides whether a file changed from its size, mtime, change time and
|
||||
inode, and re-reads a file whose mtime is too fresh to trust — but it did
|
||||
not apply that caution to the change time. On Linux, where the change time
|
||||
moves in 1 ms ticks, a file rewritten at the same size with its mtime put
|
||||
back (`cp -p`, `rsync -t`, `touch -r`, a rename-over) inside the same tick
|
||||
as the server's read matched in every field, and index-based answers
|
||||
(`find`, `hierarchy`, `check`) came from the old text until the file
|
||||
changed again. `read` and `outline` were never affected. The rule now
|
||||
covers every timestamp the stamp trusts, its window is 3 s (2 s was too
|
||||
close to FAT's 2-second timestamps), and a wall clock stepped backwards
|
||||
since a read distrusts the stamp. Reproduced on purpose on 0.65.8 (every
|
||||
run with an identical stat was stale) and gone on this build across
|
||||
overlayfs, tmpfs and APFS; ordinary reads cause no extra re-read.
|
||||
- **What it still cannot see**, now written down in
|
||||
`docs/features/mcp-transport`: on Windows there is no change time or
|
||||
inode, so a same-size rewrite that restores the old mtime more than 3 s
|
||||
after a read goes unseen; and a store through a writable memory map that
|
||||
the kernel has not yet reflected in the file's timestamps. A tree whose
|
||||
files carry modification times in the future is re-read on every call.
|
||||
- **The test suite is stable on Linux, and CI runs it there.** It was green
|
||||
on Linux most of the time and failed about one run in three: two test
|
||||
helpers insisted that writing to a child's input succeed (a usage error
|
||||
exits before reading), one latency test used a fixed 200 ms budget (it now
|
||||
measures against a parse of the same buffer in the same process), and one
|
||||
MCP test could hang on macOS under load on a pipe inherited across
|
||||
threads. Ten consecutive green runs as root and ten as an unprivileged
|
||||
user, then six and six by QA. `ci.yml` has a `linux` job (clippy and the
|
||||
whole suite on Linux x86-64) beside the macOS one.
|
||||
|
||||
## 0.65.8 — 2026-11-19
|
||||
|
||||
### Find References next to a name, edits kept in order, and a startup that could take minutes
|
||||
|
||||
(`docs/features/scan-ordering`; TODO §71.7. Three bugs, all older than this
|
||||
series of releases.)
|
||||
|
||||
- **Find All References, Go to Definition, hover, highlight and rename work
|
||||
with the cursor just after a name.** A double-click, a click on the right
|
||||
half of a name's last letter, or a click on a row of lucisv's References
|
||||
view leaves the cursor there, and the server used to look at the character
|
||||
*after* the name — so VS Code said "No references found" until you clicked
|
||||
away and back. Nine requests now resolve the name the cursor touches
|
||||
(hover, definition, type definition, references, document highlight,
|
||||
prepare-rename, rename, and the call- and type-hierarchy prepares); the
|
||||
ones with boundary rules of their own (completion, signature help, linked
|
||||
editing, selection range) are unchanged. The References view now opens a
|
||||
row with the cursor at the start of the name. Checked on every identifier
|
||||
of 350 files: the answer at the end of a name equals the answer at its
|
||||
start, and a rename there never touches the neighbouring token.
|
||||
- **Edits made while the workspace is re-indexing are applied in order.**
|
||||
The server held requests during a scan but applied notifications at once,
|
||||
so a newer edit could overtake an older one still queued — and since the
|
||||
editor sends edits as differences, the server's copy of the file then
|
||||
differed from the editor's until the file was closed and reopened: wrong
|
||||
symbols, wrong diagnostics, wrong references. Edits, opens, closes, saves
|
||||
and the other notifications the editor sends are now applied in the order
|
||||
sent. QA's independent driver: 9 118 bursts, 87 % of them sent mid-scan,
|
||||
no wrong text, no lost or duplicated answer; the same check fails on
|
||||
0.65.7 at once.
|
||||
- **Opening a file while the first index is built no longer makes that index
|
||||
take minutes.** A request followed by a file open in the same batch was
|
||||
handed back and re-held at every file of the startup scan: about 300–400 s
|
||||
on OpenTitan instead of 2 s. Now a held batch is handed back at most once
|
||||
per file actually opened; the same sequence takes 2.6–3.3 s.
|
||||
- **Known and left for later**, all present before: a request held during a
|
||||
scan is answered against the newest text, so a position-based request can
|
||||
land on a different symbol if an edit moved the text under it (and rename
|
||||
edits carry no document version for the client to reject a stale one by);
|
||||
deleting a directory is not seen by the server (VS Code reports the folder,
|
||||
which the client's source-file filter drops); an excluded file stays in the
|
||||
index after it is closed; symlinked files can be held under two spellings;
|
||||
renaming a port of a module defined twice gives an edit or a refusal at
|
||||
random.
|
||||
|
||||
## 0.65.7 — 2026-11-19
|
||||
|
||||
### 0.65.6, built for every platform
|
||||
|
||||
@@ -89,6 +89,16 @@ Re-measured 2026-10-14 after TODO §55 (pure move, `docs/features/decomposition-
|
||||
files over 600 workspace-wide: `lucisv_server/src/perf.rs` 907 (reasoned),
|
||||
`vlog_parser/src/lexer.rs` 771, `vlog_formatter/src/format/stmt.rs` 604.
|
||||
|
||||
Re-measured 2026-11-19 at 0.66.0, after the overnight queue (TODO §71; non-blank,
|
||||
non-comment lines before `mod tests`): two files over 600 — `perf.rs` 907
|
||||
(reasoned) and `lexer.rs` 771 — then `vlog_semantic/src/resolve.rs` 587 and
|
||||
`vlog_parser/src/parser/item.rs` 582, both at the mark: the next addition to
|
||||
either goes in a new module. The queue's new modules are all small
|
||||
(`server/ahead.rs`, `same_file.rs`, `completion/related.rs`, `server/viewport.rs`,
|
||||
`server/caret.rs`, `state/watched.rs`, `folding/directives.rs`, formatter
|
||||
`style.rs` / `auto.rs`); `server/dispatch.rs` is 503 and `server/index.rs`
|
||||
is where four of the eight features met.
|
||||
|
||||
## Rust standards
|
||||
|
||||
- `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
|
||||
|
||||
Generated
+9
-9
@@ -97,7 +97,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv"
|
||||
version = "0.65.7"
|
||||
version = "0.66.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"rayon",
|
||||
@@ -108,11 +108,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_core"
|
||||
version = "0.65.7"
|
||||
version = "0.66.0"
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_mcp"
|
||||
version = "0.65.7"
|
||||
version = "0.66.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"serde",
|
||||
@@ -126,7 +126,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lucisv_server"
|
||||
version = "0.65.7"
|
||||
version = "0.66.0"
|
||||
dependencies = [
|
||||
"lsp-server",
|
||||
"lsp-types",
|
||||
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_formatter"
|
||||
version = "0.65.7"
|
||||
version = "0.66.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vlog_linter"
|
||||
version = "0.65.7"
|
||||
version = "0.66.0"
|
||||
dependencies = [
|
||||
"lucisv_core",
|
||||
"vlog_formatter",
|
||||
@@ -279,11 +279,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.65.7"
|
||||
version = "0.66.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_refactor"
|
||||
version = "0.65.7"
|
||||
version = "0.66.0"
|
||||
dependencies = [
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
@@ -292,7 +292,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.65.7"
|
||||
version = "0.66.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+1
-1
@@ -13,7 +13,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.65.7"
|
||||
version = "0.66.0"
|
||||
authors = ["Guoliang Chen"]
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
@@ -7299,9 +7299,9 @@ as the trial shows. One lane, `docs/features/linux-test-portability`;
|
||||
left implicit, assertions on wall-clock or environment that the runner
|
||||
shows to be fragile. No test is deleted and the test count does not
|
||||
drop; no production code and nothing in `verify.rs` changes.
|
||||
- [ ] `cargo test --workspace` green on Linux as root and with `--user`,
|
||||
- [x] `cargo test --workspace` green on Linux as root and with `--user`,
|
||||
and `tools/gates.sh` green on macOS.
|
||||
- [ ] (lead) `.gitea/workflows/ci.yml` gains a `linux` job on `linux-x64`;
|
||||
- [x] (lead) `.gitea/workflows/ci.yml` gains a `linux` job on `linux-x64`;
|
||||
`docs/topo.md` and `tools/RELEASING.md` updated.
|
||||
|
||||
## 71. The overnight queue (2026-11-19, owner's order) — eight features, one release each
|
||||
@@ -7319,11 +7319,12 @@ subsection, plan and `docs/features/<name>/README.md` when its turn comes.
|
||||
Today every
|
||||
file edit re-indexes everything. A change to a `define` may have to;
|
||||
a typical, localized edit must not.
|
||||
- [ ] **71.2 Actions stay fast on a huge, heavily-dependent tree.** Do the
|
||||
- [x] **71.2 Actions stay fast on a huge, heavily-dependent tree.** (0.65.11, `docs/features/fast-actions`) Do the
|
||||
work dynamically: answer first from what is already in the same file
|
||||
(hover to a definition in this file), and use the relationship map to
|
||||
load completion candidates on demand.
|
||||
- [ ] **71.3 Highlighting does not wait for the index.** Always run a
|
||||
- [x] **71.3 Highlighting does not wait for the index.** (0.65.10, `docs/features/viewport-highlight`)
|
||||
Always run a
|
||||
localized, viewport-only highlight; it may be imperfect and be
|
||||
corrected later, but basic colours must not wait for the whole
|
||||
database.
|
||||
@@ -7340,7 +7341,8 @@ subsection, plan and `docs/features/<name>/README.md` when its turn comes.
|
||||
file's instance and its parents in different shades — bright light
|
||||
orange for the instance, dimmer the further up — or anything in that
|
||||
spirit that makes the hierarchy easy to read.
|
||||
- [ ] **71.7 Find References sometimes answers "not found"** on a
|
||||
- [x] **71.7 Find References sometimes answers "not found"** (0.65.8, `docs/features/scan-ordering`: a server bug — the caret just past a name)
|
||||
on a
|
||||
port/signal, then works after clicking elsewhere and back. VS Code or
|
||||
the server? Investigate, then fix what is ours.
|
||||
- [x] **71.8 Comments: no code colours inside them** (0.65.3, `docs/features/comment-highlighting`; the bracket colour is VS Code's, explained not changed)
|
||||
@@ -7348,7 +7350,7 @@ subsection, plan and `docs/features/<name>/README.md` when its turn comes.
|
||||
`signal[]` gets highlighted today), **but do highlight `TODO`,
|
||||
`FIXME`, `FIX_ME`, `TBD`**, plus a user setting for custom words that
|
||||
are highlighted only in comments.
|
||||
- [ ] **71.9 Release `0.66.0`** once 71.1–71.8 have each shipped.
|
||||
- [x] **71.9 Release `0.66.0`** once 71.1–71.8 have each shipped.
|
||||
|
||||
### 71 — wave 1 (lead, 2026-11-19): 71.6 runs beside §70
|
||||
|
||||
@@ -7410,14 +7412,14 @@ indexing, collide with each other and with §70's test files, and wait for
|
||||
stale answers), a fix round, a QA pass and a last small round. What the
|
||||
QA rounds and a read-only investigation turned up, all present before this
|
||||
wave, becomes lane **71.7** (the owner's Find References item, widened):
|
||||
- [ ] A caret just past an identifier's last letter asks about the next
|
||||
- [x] A caret just past an identifier's last letter asks about the next
|
||||
character: references, definition, hover and highlight come back
|
||||
empty (`server/dispatch.rs` `Server::offset`). This is the owner's
|
||||
"not found, then works after clicking back".
|
||||
- [ ] A `didChange` arriving during a whole rescan can overtake an older
|
||||
- [x] A `didChange` arriving during a whole rescan can overtake an older
|
||||
one still queued (`server/mod.rs` `process_batch`): with incremental
|
||||
sync the server's buffer is corrupted until the file is reopened.
|
||||
- [ ] A burst `[request, didOpen]` during the startup scan is re-held at
|
||||
- [x] A burst `[request, didOpen]` during the startup scan is re-held at
|
||||
every file (`server/index.rs` `answer_what_is_waiting`): the scan
|
||||
takes ~300 s on OpenTitan instead of ~1.7 s.
|
||||
- [ ] A watcher event naming only a directory leaves stale state; an
|
||||
@@ -7435,3 +7437,64 @@ indexing, collide with each other and with §70's test files, and wait for
|
||||
line) and shipped as 0.65.7 with 0.65.6's notes; `tools/gates.sh` gains a
|
||||
`cross` step so the next one is caught before the tag. Seven of the eight
|
||||
§71 items therefore have releases 0.65.2–0.65.5 and 0.65.7.
|
||||
|
||||
- Wave 6 (lead, 2026-11-19): 71.7 shipped as 0.65.8. Left open from it and
|
||||
from its QA, all older than this series:
|
||||
- [ ] A request held during a scan is answered against the newest text; a
|
||||
position-based one can resolve a different symbol when an edit moved
|
||||
the text under it, and rename edits carry no document version.
|
||||
- [ ] An unheld buffer opened while a scan runs is never taken in
|
||||
afterwards; closing an unsaved in-scope buffer a rescan had indexed
|
||||
leaves its text in the index.
|
||||
- [ ] Renaming a port of a module defined twice gives an edit or a refusal
|
||||
at random (`qa717/drv/dup.py`).
|
||||
- [ ] Directory-only watcher events (needs a broader watcher
|
||||
registration — the owner's call), excluded buffers after close (a
|
||||
cheap fix belongs in the index layer: adding a file is a wide
|
||||
change), symlink spellings.
|
||||
|
||||
- §70 closed (lead, 2026-11-19), shipped with 0.65.9. Once ssh was back the
|
||||
suite proved flaky on Linux (3 of 9 runs): two test helpers that insisted
|
||||
a write to a child's stdin succeed, a 200 ms wall-clock bound, an MCP test
|
||||
that could hang on an inherited pipe — and one real bug, `lucisv-mcp`
|
||||
serving stale contents after a same-tick, same-size rewrite on Linux
|
||||
(`project/files.rs`, the racy rule covered the mtime alone). All fixed in
|
||||
lane 70b (`docs/features/linux-test-portability`, Round 2); Linux is green
|
||||
10/10 as root and as a user (dev) and 6/6 each (QA); `ci.yml` has its
|
||||
`linux` job. Left open:
|
||||
- [ ] A file with an mtime in the future is re-read by `lucisv-mcp` on
|
||||
every call, forever (67 ms against 7 ms per `find` on 4 000 files).
|
||||
- [ ] `crates/lucisv/tests/cli.rs:2149` asserts only an empty stdout, no
|
||||
exit code.
|
||||
- [ ] `crates/lucisv_mcp/tests/qa_m3.rs` uses unix-only APIs with no cfg:
|
||||
`cargo check --all-targets` for Windows fails there (tests only).
|
||||
- [ ] The release is still gated on macOS alone; Windows is compile-checked
|
||||
(`cross`), never executed.
|
||||
|
||||
- Wave 7 (lead, 2026-11-19): 71.3 shipped as 0.65.10, re-applied onto
|
||||
0.65.8's message loop by hand and re-validated by a second QA round. Left
|
||||
open from it:
|
||||
- [ ] The discovery walk at the start of every scan answers nothing while
|
||||
it runs: a late open in workspace scope still waits 62–86 ms for
|
||||
colour and a rescan holds colours 70–159 ms. Making the walk
|
||||
resumable needs its own identical-result proof (`state/discover.rs`).
|
||||
- [ ] A `range` answered during a rescan always counts as a guess and
|
||||
costs one refresh at settle even when nothing changed.
|
||||
- [ ] An edit in one file that changes how another OPEN file colours sends
|
||||
no refresh (as before this lane).
|
||||
|
||||
- Wave 8 (lead, 2026-11-19): 71.2 shipped as 0.65.11 after four dev rounds
|
||||
and four QA rounds — two QA failures, so the last round ran with Fable 5.2
|
||||
as dev and QA (`docs/features/fast-actions`, Review). Left open from it:
|
||||
- [ ] Inside the startup settings wait, the client's answer to the pull is
|
||||
applied ahead of an older settings push held with it
|
||||
(`server/startup.rs`, `take_the_answer_out_of_held`; predates the
|
||||
lane; needs a client whose push and answer disagree in one burst).
|
||||
- [ ] `tests/fast_actions_bursts.rs`'s oracle accepts an answer the
|
||||
reference gives after any later message of the round: 2–9 % of
|
||||
injected stale answers pass when a later message restores the state.
|
||||
- [ ] Whether a large open buffer is in the index depends on when it was
|
||||
opened, saved or scanned (predates the lane; 77–98 answers differ
|
||||
between a settled session and a fresh server on OpenTitan).
|
||||
- [ ] The 40 000-file rescan after a delete takes either 12.3 s or
|
||||
14.5–15.5 s, on 0.65.10 and on this tree alike; cause not found.
|
||||
+24
-10
@@ -92,16 +92,29 @@ fn run_in(dir: &TempDir, args: &[&str]) -> Output {
|
||||
Command::new(LUCISV).args(args).current_dir(&dir.path).output().expect("run lucisv")
|
||||
}
|
||||
|
||||
/// Runs lucisv with the cache switched off, `input` on its stdin.
|
||||
fn run_with_stdin(args: &[&str], input: &str) -> Output {
|
||||
let mut child = Command::new(LUCISV)
|
||||
.args(with_no_cache(args))
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn lucisv");
|
||||
child.stdin.as_mut().expect("stdin").write_all(input.as_bytes()).expect("write stdin");
|
||||
child.wait_with_output().expect("run lucisv")
|
||||
run_with_stdin_raw(&with_no_cache(args), input)
|
||||
}
|
||||
|
||||
/// Writes `input` to the child's stdin and closes it.
|
||||
///
|
||||
/// A child that exits without reading — a usage error refuses before it
|
||||
/// looks at stdin — is legitimate, and the write then races its exit: it
|
||||
/// fails with `BrokenPipe` when the child is already gone. That one error is
|
||||
/// not the test's business; the exit code and output the caller asserts on
|
||||
/// are. (A successful write never meant the child read anything either:
|
||||
/// every input here is far smaller than a pipe's buffer, so the write lands
|
||||
/// in the buffer whether or not the child ever reads it.) Any other error is
|
||||
/// a failure.
|
||||
fn feed(child: &mut std::process::Child, input: &str) {
|
||||
let mut stdin = child.stdin.take().expect("stdin");
|
||||
match stdin.write_all(input.as_bytes()) {
|
||||
Err(error) if error.kind() != std::io::ErrorKind::BrokenPipe => {
|
||||
panic!("write stdin: {error:?}")
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn code(out: &Output) -> i32 {
|
||||
@@ -1755,6 +1768,7 @@ fn lines_neither_reads_nor_writes_the_cache() {
|
||||
assert!(!fresh.cache_file().exists(), "a range run must not seed the cache");
|
||||
}
|
||||
|
||||
/// Runs lucisv exactly as given, cache and all, `input` on its stdin.
|
||||
fn run_with_stdin_raw(args: &[&str], input: &str) -> Output {
|
||||
let mut child = Command::new(LUCISV)
|
||||
.args(args)
|
||||
@@ -1763,7 +1777,7 @@ fn run_with_stdin_raw(args: &[&str], input: &str) -> Output {
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn lucisv");
|
||||
child.stdin.as_mut().expect("stdin").write_all(input.as_bytes()).expect("write stdin");
|
||||
feed(&mut child, input);
|
||||
child.wait_with_output().expect("run lucisv")
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime};
|
||||
use std::time::{Duration, Instant, SystemTime};
|
||||
|
||||
use lucisv_core::cache::content_hash;
|
||||
use lucisv_core::config::Discovery;
|
||||
@@ -16,11 +16,25 @@ use lucisv_core::walk::collect_files_with;
|
||||
/// something an agent wants summarised.
|
||||
pub const MAX_FILE_BYTES: u64 = 1024 * 1024;
|
||||
|
||||
/// A file whose mtime is this close to the moment it was read may have been
|
||||
/// written again within the filesystem's timestamp resolution, so its stamp
|
||||
/// proves nothing: it is re-read (and re-hashed) until it is older than
|
||||
/// this. Git's "racy clean" rule, for the same reason.
|
||||
const RACY: Duration = Duration::from_secs(2);
|
||||
/// A file whose mtime or ctime is this close to the moment it was read may
|
||||
/// have been written again within the filesystem's timestamp resolution, so
|
||||
/// its stamp proves nothing: it is re-read (and re-hashed) until it is older
|
||||
/// than this. Git's "racy clean" rule, for the same reason.
|
||||
///
|
||||
/// The window must outlast the coarsest timestamp a filesystem keeps plus
|
||||
/// how far its clock can lag the one `read_at` comes from. Linux stamps
|
||||
/// files from a clock that moves in 1–4 ms ticks; ext3 and many network
|
||||
/// mounts keep whole seconds, FAT two. Three seconds covers FAT's two with
|
||||
/// a second to spare. A just-changed file costs a few more re-reads; a
|
||||
/// window too short costs stale contents.
|
||||
const RACY: Duration = Duration::from_secs(3);
|
||||
|
||||
/// How far the wall clock may fall behind the monotonic one since a read
|
||||
/// before the stamp stops being trusted: a clock stepped back can give a
|
||||
/// later write the very timestamp the stamp holds. Large next to the
|
||||
/// microseconds between the paired clock reads, small next to the margin
|
||||
/// [`RACY`] keeps over the coarsest timestamps.
|
||||
const STEP_BACK: Duration = Duration::from_millis(100);
|
||||
|
||||
/// The files one discovery found, and what it had to say about the rest.
|
||||
#[derive(Debug, Default)]
|
||||
@@ -137,13 +151,16 @@ pub struct Stamp {
|
||||
pub mtime: Option<SystemTime>,
|
||||
/// `content_hash` of its bytes.
|
||||
pub hash: u64,
|
||||
/// When it was read.
|
||||
/// When it was read, by the wall clock file timestamps are compared with.
|
||||
pub read_at: SystemTime,
|
||||
/// The same moment by the monotonic clock: what tells a wall clock that
|
||||
/// was stepped back since the read.
|
||||
pub read_mono: Instant,
|
||||
/// Its ctime and inode — what still moves when a same-size rewrite puts
|
||||
/// the old mtime back (`cp -p`, `rsync -t`, `touch -r`), git's answer to
|
||||
/// the same problem. Zero off Unix, where size, mtime and the racy rule
|
||||
/// the same problem. `None` off Unix, where size, mtime and the racy rule
|
||||
/// are all there is.
|
||||
pub identity: (i64, i64, u64),
|
||||
pub identity: Option<Identity>,
|
||||
/// Whether its text spells `endprogram` — the cheap test that says a
|
||||
/// `Module`-kind unit in it might be a `program` (the semantic layer
|
||||
/// models both as a module).
|
||||
@@ -161,6 +178,42 @@ pub enum Change {
|
||||
Gone,
|
||||
}
|
||||
|
||||
/// A file's inode change time and inode number (Unix only).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Identity {
|
||||
/// The ctime, `None` when it does not fit a `SystemTime`.
|
||||
pub ctime: Option<SystemTime>,
|
||||
/// The inode number.
|
||||
pub ino: u64,
|
||||
}
|
||||
|
||||
/// What one `stat` says about a file, as far as a stamp is concerned.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
struct Seen {
|
||||
size: u64,
|
||||
mtime: Option<SystemTime>,
|
||||
identity: Option<Identity>,
|
||||
}
|
||||
|
||||
impl Seen {
|
||||
fn of(meta: &fs::Metadata) -> Seen {
|
||||
Seen { size: meta.len(), mtime: meta.modified().ok(), identity: identity(meta) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The two clocks, read back to back.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct Clocks {
|
||||
wall: SystemTime,
|
||||
mono: Instant,
|
||||
}
|
||||
|
||||
impl Clocks {
|
||||
fn now() -> Clocks {
|
||||
Clocks { wall: SystemTime::now(), mono: Instant::now() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Stamp {
|
||||
/// Compare the file on disk with this stamp, by one `stat`.
|
||||
pub fn check(&self, path: &Path) -> Change {
|
||||
@@ -170,18 +223,56 @@ impl Stamp {
|
||||
if !meta.is_file() || meta.len() > MAX_FILE_BYTES {
|
||||
return Change::Gone;
|
||||
}
|
||||
let mtime = meta.modified().ok();
|
||||
let racy = match mtime {
|
||||
Some(mtime) => mtime + RACY > self.read_at,
|
||||
None => true,
|
||||
};
|
||||
let moved = meta.len() != self.size || mtime != self.mtime;
|
||||
if moved || identity(&meta) != self.identity || racy {
|
||||
self.compare(Seen::of(&meta), Clocks::now())
|
||||
}
|
||||
|
||||
/// The decision [`Stamp::check`] makes, from what the `stat` saw and
|
||||
/// what the clocks say now.
|
||||
fn compare(&self, seen: Seen, now: Clocks) -> Change {
|
||||
let moved =
|
||||
seen.size != self.size || seen.mtime != self.mtime || seen.identity != self.identity;
|
||||
if moved || self.racy() || self.clock_stepped_back(now) {
|
||||
Change::Suspect
|
||||
} else {
|
||||
Change::Same
|
||||
}
|
||||
}
|
||||
|
||||
/// **Invariant: a stamp is trusted on a later match only if every
|
||||
/// timestamp it trusts (the mtime, and the ctime where there is one) is
|
||||
/// at least [`RACY`] older than the moment the stamp was taken** —
|
||||
/// otherwise a write inside the same timestamp tick, after the read,
|
||||
/// leaves every one of them as it was. A timestamp that is missing, or
|
||||
/// later than the read (a clock behind the filesystem's), is racy too.
|
||||
fn racy(&self) -> bool {
|
||||
let ctime = self.identity.map(|identity| identity.ctime);
|
||||
[Some(self.mtime), ctime].into_iter().flatten().any(|stamped| match stamped {
|
||||
Some(time) => time.checked_add(RACY).is_none_or(|settled| settled > self.read_at),
|
||||
None => true,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the wall clock is now more than [`STEP_BACK`] behind where
|
||||
/// the monotonic clock says it would be had it only run forward since
|
||||
/// the read. After such a step a new write can be stamped with an old
|
||||
/// time, so no timestamp match means anything until the file is re-read.
|
||||
fn clock_stepped_back(&self, now: Clocks) -> bool {
|
||||
let expected = match now.mono.checked_duration_since(self.read_mono) {
|
||||
Some(elapsed) => self.read_at.checked_add(elapsed),
|
||||
None => self.read_at.checked_sub(self.read_mono - now.mono),
|
||||
};
|
||||
match (expected, now.wall.checked_add(STEP_BACK)) {
|
||||
(Some(expected), Some(tolerated)) => tolerated < expected,
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// This stamp as if it had been taken `by` later, on both clocks: how a
|
||||
/// test ages a stamp past the racy window without waiting for it.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn taken_later(self, by: Duration) -> Stamp {
|
||||
Stamp { read_at: self.read_at + by, read_mono: self.read_mono + by, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
/// Read one source file and stamp it. `Err` for a file that is gone or is
|
||||
@@ -191,33 +282,43 @@ pub fn read_source(path: &Path) -> io::Result<(String, Stamp)> {
|
||||
// Stat before reading: a write that lands between the two leaves a stamp
|
||||
// older than the bytes, which the next sweep sees as a change.
|
||||
let meta = fs::metadata(path)?;
|
||||
let read_at = SystemTime::now();
|
||||
let read = Clocks::now();
|
||||
let bytes = fs::read(path)?;
|
||||
let hash = content_hash(&bytes);
|
||||
let text = String::from_utf8(bytes)
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "not UTF-8 text"))?;
|
||||
let seen = Seen::of(&meta);
|
||||
let stamp = Stamp {
|
||||
size: meta.len(),
|
||||
mtime: meta.modified().ok(),
|
||||
size: seen.size,
|
||||
mtime: seen.mtime,
|
||||
hash,
|
||||
read_at,
|
||||
identity: identity(&meta),
|
||||
read_at: read.wall,
|
||||
read_mono: read.mono,
|
||||
identity: seen.identity,
|
||||
program: text.contains("endprogram"),
|
||||
};
|
||||
Ok((text, stamp))
|
||||
}
|
||||
|
||||
/// A file's ctime (seconds, nanoseconds) and inode number.
|
||||
/// A file's ctime and inode number.
|
||||
#[cfg(unix)]
|
||||
fn identity(meta: &fs::Metadata) -> (i64, i64, u64) {
|
||||
fn identity(meta: &fs::Metadata) -> Option<Identity> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
(meta.ctime(), meta.ctime_nsec(), meta.ino())
|
||||
let nanos = Duration::from_nanos(u64::try_from(meta.ctime_nsec()).unwrap_or(0));
|
||||
let ctime = match u64::try_from(meta.ctime()) {
|
||||
Ok(secs) => SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(secs) + nanos),
|
||||
Err(_) => SystemTime::UNIX_EPOCH
|
||||
.checked_sub(Duration::from_secs(meta.ctime().unsigned_abs()))
|
||||
.and_then(|time| time.checked_add(nanos)),
|
||||
};
|
||||
Some(Identity { ctime, ino: meta.ino() })
|
||||
}
|
||||
|
||||
/// No ctime or inode off Unix: the stamp falls back to size and mtime.
|
||||
/// No ctime or inode off Unix (std has no change time on Windows): the
|
||||
/// stamp falls back to size and mtime, and the racy rule on the mtime.
|
||||
#[cfg(not(unix))]
|
||||
fn identity(_: &fs::Metadata) -> (i64, i64, u64) {
|
||||
(0, 0, 0)
|
||||
fn identity(_: &fs::Metadata) -> Option<Identity> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -273,7 +374,7 @@ mod tests {
|
||||
let (_, stamp) = read_source(&path).unwrap();
|
||||
// Just written: racy, so suspect even though nothing moved.
|
||||
assert_eq!(stamp.check(&path), Change::Suspect);
|
||||
let settled = Stamp { read_at: stamp.read_at + RACY + RACY, ..stamp };
|
||||
let settled = stamp.taken_later(RACY + RACY);
|
||||
assert_eq!(settled.check(&path), Change::Same);
|
||||
fs::write(&path, "module a2; endmodule\n").unwrap();
|
||||
assert_eq!(settled.check(&path), Change::Suspect);
|
||||
@@ -281,4 +382,129 @@ mod tests {
|
||||
assert_eq!(settled.check(&path), Change::Gone);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
// The racy rule, decided from values: no file, no waiting, no clock but
|
||||
// the ones given.
|
||||
|
||||
/// A stamp taken at `read` (wall) / `mono`, of a file whose mtime and
|
||||
/// ctime are `mtime_age` and `ctime_age` before the read.
|
||||
fn stamp_aged(
|
||||
read: SystemTime,
|
||||
mono: Instant,
|
||||
mtime_age: Duration,
|
||||
ctime_age: Duration,
|
||||
) -> Stamp {
|
||||
Stamp {
|
||||
size: 20,
|
||||
mtime: Some(read - mtime_age),
|
||||
hash: 7,
|
||||
read_at: read,
|
||||
read_mono: mono,
|
||||
identity: Some(Identity { ctime: Some(read - ctime_age), ino: 42 }),
|
||||
program: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a `stat` of the unchanged file sees.
|
||||
fn unchanged(stamp: &Stamp) -> Seen {
|
||||
Seen { size: stamp.size, mtime: stamp.mtime, identity: stamp.identity }
|
||||
}
|
||||
|
||||
/// The clocks a second after the read, both having run forward.
|
||||
fn a_second_later(stamp: &Stamp) -> Clocks {
|
||||
let second = Duration::from_secs(1);
|
||||
Clocks { wall: stamp.read_at + second, mono: stamp.read_mono + second }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_match_is_trusted_only_when_every_timestamp_was_settled_at_the_read() {
|
||||
let (read, mono) = (SystemTime::now(), Instant::now());
|
||||
let old = Duration::from_secs(3600);
|
||||
let fresh = Duration::from_millis(1);
|
||||
let cases = [
|
||||
("neither racy", old, old, Change::Same),
|
||||
("mtime racy", fresh, old, Change::Suspect),
|
||||
// The Linux hole: an old mtime put back, a ctime from this tick.
|
||||
("ctime racy", old, fresh, Change::Suspect),
|
||||
("both racy", fresh, fresh, Change::Suspect),
|
||||
("just inside the window", old, RACY - Duration::from_nanos(1), Change::Suspect),
|
||||
("exactly the window old", old, RACY, Change::Same),
|
||||
];
|
||||
for (what, mtime_age, ctime_age, expected) in cases {
|
||||
let stamp = stamp_aged(read, mono, mtime_age, ctime_age);
|
||||
assert_eq!(
|
||||
stamp.compare(unchanged(&stamp), a_second_later(&stamp)),
|
||||
expected,
|
||||
"{what}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_timestamp_later_than_the_read_or_missing_is_racy() {
|
||||
let (read, mono) = (SystemTime::now(), Instant::now());
|
||||
let old = Duration::from_secs(3600);
|
||||
let mut ahead = stamp_aged(read, mono, old, old);
|
||||
ahead.identity = Some(Identity { ctime: Some(read + Duration::from_secs(60)), ino: 42 });
|
||||
assert_eq!(ahead.compare(unchanged(&ahead), a_second_later(&ahead)), Change::Suspect);
|
||||
let mut no_ctime = stamp_aged(read, mono, old, old);
|
||||
no_ctime.identity = Some(Identity { ctime: None, ino: 42 });
|
||||
assert_eq!(
|
||||
no_ctime.compare(unchanged(&no_ctime), a_second_later(&no_ctime)),
|
||||
Change::Suspect
|
||||
);
|
||||
let mut no_mtime = stamp_aged(read, mono, old, old);
|
||||
no_mtime.mtime = None;
|
||||
assert_eq!(
|
||||
no_mtime.compare(unchanged(&no_mtime), a_second_later(&no_mtime)),
|
||||
Change::Suspect
|
||||
);
|
||||
// Off Unix there is no ctime to trust: the mtime alone decides.
|
||||
let mut off_unix = stamp_aged(read, mono, old, old);
|
||||
off_unix.identity = None;
|
||||
assert_eq!(off_unix.compare(unchanged(&off_unix), a_second_later(&off_unix)), Change::Same);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wall_clock_stepped_back_since_the_read_distrusts_the_stamp() {
|
||||
let (read, mono) = (SystemTime::now(), Instant::now());
|
||||
let old = Duration::from_secs(3600);
|
||||
let stamp = stamp_aged(read, mono, old, old);
|
||||
let ten = Duration::from_secs(10);
|
||||
// Ten seconds of real time, but the wall clock shows one: stepped back.
|
||||
let back = Clocks { wall: read + Duration::from_secs(1), mono: mono + ten };
|
||||
assert_eq!(stamp.compare(unchanged(&stamp), back), Change::Suspect);
|
||||
// Behind the read itself.
|
||||
let behind = Clocks { wall: read - ten, mono: mono + Duration::from_secs(1) };
|
||||
assert_eq!(stamp.compare(unchanged(&stamp), behind), Change::Suspect);
|
||||
// A wall clock that ran ahead (a suspend the monotonic clock slept
|
||||
// through) is no reason to doubt anything.
|
||||
let ahead = Clocks { wall: read + ten, mono: mono + Duration::from_secs(1) };
|
||||
assert_eq!(stamp.compare(unchanged(&stamp), ahead), Change::Same);
|
||||
// Jitter under the tolerance is not a step.
|
||||
let jitter = Clocks { wall: read + ten - STEP_BACK / 2, mono: mono + ten };
|
||||
assert_eq!(stamp.compare(unchanged(&stamp), jitter), Change::Same);
|
||||
// A stamp aged on both clocks at once is not a step either.
|
||||
let aged = stamp.taken_later(ten);
|
||||
assert_eq!(aged.compare(unchanged(&aged), a_second_later(&stamp)), Change::Same);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_moved_field_is_suspect_however_settled() {
|
||||
let (read, mono) = (SystemTime::now(), Instant::now());
|
||||
let old = Duration::from_secs(3600);
|
||||
let stamp = stamp_aged(read, mono, old, old);
|
||||
let now = a_second_later(&stamp);
|
||||
let same = unchanged(&stamp);
|
||||
let identity = stamp.identity.unwrap();
|
||||
let moved = [
|
||||
Seen { size: 21, ..same },
|
||||
Seen { mtime: Some(read), ..same },
|
||||
Seen { identity: Some(Identity { ino: 43, ..identity }), ..same },
|
||||
Seen { identity: Some(Identity { ctime: Some(read - old / 2), ..identity }), ..same },
|
||||
];
|
||||
for seen in moved {
|
||||
assert_eq!(stamp.compare(seen, now), Change::Suspect, "{seen:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime};
|
||||
use std::time::Duration;
|
||||
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
@@ -29,9 +29,8 @@ fn rebuilt(project: &Project) -> String {
|
||||
|
||||
/// Age every stamp past the racy window, so only a real change is suspect.
|
||||
fn settle(project: &mut Project) {
|
||||
let later = SystemTime::now() + Duration::from_secs(10);
|
||||
for stamp in project.files.values_mut() {
|
||||
stamp.read_at = later;
|
||||
*stamp = stamp.taken_later(Duration::from_secs(10));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -706,6 +706,15 @@ fn qa_lucisv_check_over_the_same_tree_while_the_server_formats() {
|
||||
copy_tree(&scratch.0, &reference.0);
|
||||
let status = Command::new(&cli).arg("--no-cache").arg(&reference.0).output().unwrap();
|
||||
assert!(status.status.success(), "{status:?}");
|
||||
// The server is spawned before the checker starts, never while it runs.
|
||||
// A spawn on one thread can inherit a pipe another thread is just
|
||||
// creating for its child: macOS has no `pipe2`, so close-on-exec is set
|
||||
// in a second step. Seen once under load (2026-11-19, `lsof`): the
|
||||
// server held the write end of a `lucisv --check`'s stdout. That
|
||||
// `output()` never saw EOF, `join` below waited on it, and the server,
|
||||
// which lives until this test ends, never let go, so the test hung.
|
||||
// Spawned first, the server cannot hold any of the checker's pipes.
|
||||
let mut server = Session::over(&scratch);
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let checker = {
|
||||
let (stop, cli, root) = (Arc::clone(&stop), cli.clone(), scratch.0.clone());
|
||||
@@ -719,7 +728,6 @@ fn qa_lucisv_check_over_the_same_tree_while_the_server_formats() {
|
||||
codes
|
||||
})
|
||||
};
|
||||
let mut server = Session::over(&scratch);
|
||||
for _ in 0..5 {
|
||||
for (name, text) in &messy {
|
||||
scratch.write(name, text);
|
||||
|
||||
@@ -113,7 +113,14 @@ fn run(args: &[&str], lines: &[Value]) -> Output {
|
||||
Value::String(raw) => raw.clone(),
|
||||
other => other.to_string(),
|
||||
};
|
||||
writeln!(stdin, "{text}").unwrap();
|
||||
// A refused argument list exits 2 before reading a byte, so the write
|
||||
// races that exit and can fail with `BrokenPipe`. That is the child
|
||||
// being gone, not the test failing: what it said and its exit code
|
||||
// are what the caller asserts on. Any other error is a failure.
|
||||
match writeln!(stdin, "{text}") {
|
||||
Err(error) if error.kind() == std::io::ErrorKind::BrokenPipe => break,
|
||||
result => result.unwrap(),
|
||||
}
|
||||
}
|
||||
drop(stdin);
|
||||
child.wait_with_output().unwrap()
|
||||
|
||||
@@ -843,7 +843,7 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
|
||||
}
|
||||
|
||||
/// One `` `define``'s completion entry.
|
||||
fn macro_of(define: &vlog_parser::defines::Define) -> Macro {
|
||||
pub(crate) fn macro_of(define: &vlog_parser::defines::Define) -> Macro {
|
||||
let args = match &define.params {
|
||||
Some(params) => format!("({})", params.join(", ")),
|
||||
None => String::new(),
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Which byte a "symbol under the cursor" request is about.
|
||||
//!
|
||||
//! An LSP position is a caret *between* two characters, and a span here is
|
||||
//! end-exclusive, so a caret just past an identifier's last letter names the
|
||||
//! character **after** the name. VS Code calls that caret "on the word" — a
|
||||
//! double-click, a click on the right half of the last letter, or a jump that
|
||||
//! selects the name all leave it there, and its own word highlight and the
|
||||
//! title of a references search both use the word before it. Asking about the
|
||||
//! next character instead answered `[]`, and VS Code said "No references
|
||||
//! found" for a name it was showing as selected
|
||||
//! (`docs/features/scan-ordering/README.md`, A1).
|
||||
//!
|
||||
//! The rule is VS Code's: a caret touching a name on its right edge is on
|
||||
//! that name — unless a name also starts at the caret, which then wins
|
||||
//! (`a|b` cannot happen; `a|.b` is on `a`, `a.|b` is on `b`).
|
||||
|
||||
/// The byte offset a request about the name under the cursor should resolve,
|
||||
/// given the caret's byte offset in `text`.
|
||||
///
|
||||
/// Moves one byte left when the caret is just past a name and not at the
|
||||
/// start of another; every other caret is returned unchanged. A name is an
|
||||
/// identifier, keyword, system task, macro or number written with
|
||||
/// [`is_name_byte`] — or an escaped identifier, `\` up to the whitespace that
|
||||
/// ends it, whose own characters can be anything.
|
||||
pub fn symbol_offset(text: &str, caret: u32) -> u32 {
|
||||
let bytes = text.as_bytes();
|
||||
let at = caret as usize;
|
||||
if at == 0 || at > bytes.len() || bytes.get(at).copied().is_some_and(is_name_byte) {
|
||||
return caret;
|
||||
}
|
||||
let before = bytes[at - 1];
|
||||
if is_name_byte(before) || ends_an_escaped_identifier(bytes, at) {
|
||||
return caret - 1;
|
||||
}
|
||||
caret
|
||||
}
|
||||
|
||||
/// Whether `byte` can be part of a simple identifier (IEEE 1800-2017 §5.6):
|
||||
/// a letter, a digit, `_` or `$`. A system task's leading `$` and a macro
|
||||
/// name after its backtick are covered by the same set.
|
||||
fn is_name_byte(byte: u8) -> bool {
|
||||
byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$'
|
||||
}
|
||||
|
||||
/// Whether the caret at `at` sits on the whitespace (or the end of the text)
|
||||
/// that terminates an escaped identifier — a `\` followed by at least one
|
||||
/// non-whitespace byte, all of it before the caret.
|
||||
fn ends_an_escaped_identifier(bytes: &[u8], at: usize) -> bool {
|
||||
if bytes.get(at).is_some_and(|b| !b.is_ascii_whitespace()) {
|
||||
return false;
|
||||
}
|
||||
let start = bytes[..at].iter().rposition(u8::is_ascii_whitespace).map_or(0, |ws| ws + 1);
|
||||
at - start >= 2 && bytes[start] == b'\\'
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::symbol_offset;
|
||||
|
||||
/// The offset `symbol_offset` picks for the caret written as `|` in
|
||||
/// `marked`, as the character it lands on (`None` past the end).
|
||||
fn lands_on(marked: &str) -> Option<char> {
|
||||
let caret = marked.find('|').expect("a caret") as u32;
|
||||
let text = marked.replacen('|', "", 1);
|
||||
let at = symbol_offset(&text, caret) as usize;
|
||||
text[at..].chars().next()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caret_just_past_a_name_is_on_its_last_letter() {
|
||||
assert_eq!(lands_on("logic tx|,"), Some('x'));
|
||||
assert_eq!(lands_on("assign y = tx|;"), Some('x'));
|
||||
assert_eq!(lands_on("tx|"), Some('x'), "at the end of the text");
|
||||
assert_eq!(lands_on("logic tx|\nwire w;"), Some('x'), "at the end of a line");
|
||||
assert_eq!(lands_on("logic tx|\r\nwire w;"), Some('x'), "before a CRLF");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caret_on_or_inside_a_name_is_left_alone() {
|
||||
assert_eq!(lands_on("logic |tx;"), Some('t'), "at the start");
|
||||
assert_eq!(lands_on("logic t|x;"), Some('x'), "in the middle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caret_touching_two_names_takes_the_one_that_starts_there() {
|
||||
// VS Code's word at `a|.b` is `a`; at `a.|b` it is `b`.
|
||||
assert_eq!(lands_on("u_a|.sig"), Some('a'), "before the dot: the instance");
|
||||
assert_eq!(lands_on("u_a.|sig"), Some('s'), "after the dot: the member");
|
||||
assert_eq!(lands_on(".clk|(clk_i)"), Some('k'), "a port name before its paren");
|
||||
assert_eq!(lands_on(".clk(|clk_i)"), Some('c'), "the signal after the paren");
|
||||
assert_eq!(lands_on("mem|[3]"), Some('m'), "a name before an index");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caret_after_anything_but_a_name_is_left_alone() {
|
||||
assert_eq!(lands_on("a = b;|"), None, "past a semicolon at the end");
|
||||
assert_eq!(lands_on("a = b; |"), None, "past whitespace");
|
||||
assert_eq!(lands_on("f(x)|;"), Some(';'), "past a paren");
|
||||
assert_eq!(lands_on("|"), None, "an empty text");
|
||||
assert_eq!(lands_on("|tx"), Some('t'), "the very start");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_tasks_macros_and_keywords_are_names_too() {
|
||||
assert_eq!(lands_on("$display|("), Some('y'));
|
||||
assert_eq!(lands_on("`WIDTH|-1"), Some('H'));
|
||||
assert_eq!(lands_on("begin|\n"), Some('n'), "so a keyword pair highlights");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escaped_identifier_ends_at_its_whitespace() {
|
||||
// `\a+b ` is one name whose last byte is not an identifier byte.
|
||||
assert_eq!(lands_on(r"assign \a+b+ |= 1;"), Some('='), "past the space: not on it");
|
||||
assert_eq!(lands_on(r"assign \a+b+| = 1;"), Some('+'), "on the space that ends it");
|
||||
assert_eq!(lands_on(r"\bus[0]|"), Some(']'), "at the end of the text");
|
||||
assert_eq!(lands_on(r"x = a \| b;"), Some(' '), "a lone backslash is not a name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_ascii_text_before_the_name_does_not_move_the_byte() {
|
||||
// The caret arrives as a byte offset already converted from UTF-16;
|
||||
// the rule reads bytes, and a multi-byte character is never a name.
|
||||
assert_eq!(lands_on("// é\nlogic tx|;"), Some('x'));
|
||||
assert_eq!(lands_on("é|tx"), Some('t'), "a name starting after a non-ASCII letter");
|
||||
assert_eq!(lands_on("é|;"), Some(';'), "a non-ASCII letter is not a name");
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,7 @@ use buffer::{buffer_word_tier, declared_tier};
|
||||
use connection::Connection;
|
||||
use member::member_answer;
|
||||
use module::module_tier;
|
||||
use related::{related_macros, related_tier};
|
||||
use site::{at_module_item, at_statement, enclosing_scopes};
|
||||
use tiers::{index_tier, keyword_tier, scope_tier, template_tier, word_tier};
|
||||
use word::typed_word;
|
||||
@@ -90,6 +91,7 @@ pub(crate) use module::{nearest_definition, plan_for};
|
||||
pub(crate) use module::module_header;
|
||||
pub(crate) use site::at_instantiation_site;
|
||||
pub(crate) use tiers::layout_at;
|
||||
pub(crate) use wire::{item_defaults_support, with_item_defaults};
|
||||
|
||||
mod buffer;
|
||||
mod connection;
|
||||
@@ -97,8 +99,10 @@ mod connection;
|
||||
mod harness;
|
||||
mod member;
|
||||
mod module;
|
||||
mod related;
|
||||
mod site;
|
||||
mod tiers;
|
||||
mod wire;
|
||||
mod word;
|
||||
|
||||
/// How many items one response carries, over every tier.
|
||||
@@ -151,10 +155,14 @@ const TIER_SCOPE: char = '1';
|
||||
/// (`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 the file is related to — the packages it imports, the classes its
|
||||
/// class extends, the headers it includes — below the file itself and above
|
||||
/// the rest of the workspace (`related.rs`).
|
||||
const TIER_RELATED: char = '4';
|
||||
const TIER_INDEX: char = '5';
|
||||
const TIER_TEMPLATE: char = '6';
|
||||
const TIER_KEYWORD: char = '7';
|
||||
const TIER_WORD: char = '8';
|
||||
|
||||
/// What a multi-line item tells the client about its own whitespace.
|
||||
///
|
||||
@@ -205,6 +213,7 @@ pub fn completions(
|
||||
// The backtick itself is replaced, so the item may carry its own.
|
||||
let replacing = TextRange::new(word.start.saturating_sub(1), offset);
|
||||
let mut items = Items::new(doc, replacing);
|
||||
related_macros(&mut items, ws, doc, &word.text);
|
||||
for entry in ws.candidates().macros(&word.text) {
|
||||
items.simple(
|
||||
&format!("`{}", entry.name),
|
||||
@@ -243,6 +252,7 @@ pub fn completions(
|
||||
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());
|
||||
related_tier(&mut items, ws, 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);
|
||||
@@ -273,6 +283,10 @@ struct Items {
|
||||
items: Vec<CompletionItem>,
|
||||
seen: HashSet<String>,
|
||||
incomplete: bool,
|
||||
/// How many of `items` the related tier added — which [`LIMIT`] does not
|
||||
/// count, so every other tier fills exactly as far as it would without
|
||||
/// them (`related.rs`).
|
||||
related: usize,
|
||||
}
|
||||
|
||||
impl Items {
|
||||
@@ -282,6 +296,7 @@ impl Items {
|
||||
items: Vec::new(),
|
||||
seen: HashSet::new(),
|
||||
incomplete: false,
|
||||
related: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,7 +304,7 @@ impl Items {
|
||||
/// only sets [`Items::incomplete`] — which is why the tiers ask first
|
||||
/// rather than building items nobody will see.
|
||||
fn full(&mut self) -> bool {
|
||||
if self.items.len() >= LIMIT {
|
||||
if self.items.len() - self.related >= LIMIT {
|
||||
self.incomplete = true;
|
||||
return true;
|
||||
}
|
||||
@@ -310,6 +325,14 @@ impl Items {
|
||||
if self.full() || self.seen.contains(name) {
|
||||
return;
|
||||
}
|
||||
self.unlimited(name, kind, tier, detail);
|
||||
}
|
||||
|
||||
/// [`Items::simple`] past the cap: the caller has its own.
|
||||
fn unlimited(&mut self, name: &str, kind: CompletionItemKind, tier: char, detail: String) {
|
||||
if !self.seen.insert(name.to_string()) {
|
||||
return;
|
||||
}
|
||||
let item = CompletionItem {
|
||||
label: name.to_string(),
|
||||
kind: Some(kind),
|
||||
@@ -322,7 +345,7 @@ impl Items {
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
self.push(item);
|
||||
self.items.push(item);
|
||||
}
|
||||
|
||||
/// A port or parameter after a connection list's `.`: the bare name, or
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
//! The **related** tier: what this file is related to through the workspace
|
||||
//! index, ranked above the rest of the workspace and below the file itself
|
||||
//! (`docs/features/fast-actions/README.md`, completion through the
|
||||
//! relationship map).
|
||||
//!
|
||||
//! The tier-5 table answers "every package member, typedef, class and module
|
||||
//! the workspace declares whose name matches", alphabetically, until the
|
||||
//! response is full — so in a workspace of tens of thousands of files the
|
||||
//! members of the one package this file actually imports were cut off behind
|
||||
//! names from files it has nothing to do with (measured: 46 of 47 matching
|
||||
//! `aes_pkg` names offered at `ae` in 4 000 files, 11 of 47 in 40 000). What a
|
||||
//! file is related to is known without reading anything: the packages its
|
||||
//! scope chain imports, the classes its enclosing class extends, the headers
|
||||
//! its `` `include``s reach. Those names come first.
|
||||
//!
|
||||
//! **No item is taken away.** A related item does not count against
|
||||
//! [`LIMIT`](super::LIMIT): the tiers after it fill exactly as far as they
|
||||
//! did before, and a name the related tier claimed is skipped by them
|
||||
//! without being counted, so every label of the old answer is still offered,
|
||||
//! with the same edit and format (the completion-equivalence test holds the
|
||||
//! server to that). **What does change** for a name the related tier claims
|
||||
//! is its icon and its detail: they now describe the declaration the file is
|
||||
//! related to — the member of the package it imports, the macro of the header
|
||||
//! it includes, the member of the class it extends — where the workspace tier
|
||||
//! described the first declaration of that name in the whole workspace
|
||||
//! (`NumRegs` of whichever register package sorts first; a module of the name
|
||||
//! where the imported package declares a function). The tier has its own
|
||||
//! cap, [`RELATED_LIMIT`], past which it says the answer is incomplete.
|
||||
|
||||
use lsp_types::CompletionItemKind;
|
||||
use vlog_parser::defines::DefineKind;
|
||||
use vlog_semantic::{Def, ScopeKind, Semantics, SymbolKind};
|
||||
|
||||
use super::tiers::innermost_scope;
|
||||
use super::word::Word;
|
||||
use super::{completion_kind, Items, TIER_RELATED};
|
||||
use crate::candidates::{rank_cmp, starts_with_ignore_case, Query, Score};
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::symbols::kind_label;
|
||||
|
||||
/// How many related names one response carries at most.
|
||||
///
|
||||
/// A package of a few hundred members is the large case (`aes_pkg` has 259
|
||||
/// on its connection surface); at an empty prefix the related tier would
|
||||
/// otherwise double a response that is already incomplete.
|
||||
pub(super) const RELATED_LIMIT: usize = 256;
|
||||
|
||||
/// One related name: what to show, and how it ranks.
|
||||
struct Related {
|
||||
name: String,
|
||||
kind: SymbolKind,
|
||||
detail: String,
|
||||
}
|
||||
|
||||
impl Items {
|
||||
/// Add a related item, unless a higher tier already offered that name or
|
||||
/// the tier is full. Not counted against [`LIMIT`](super::LIMIT).
|
||||
fn related(&mut self, name: &str, kind: CompletionItemKind, detail: String) {
|
||||
if self.seen.contains(name) {
|
||||
return;
|
||||
}
|
||||
if self.related >= RELATED_LIMIT {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
}
|
||||
self.related += 1;
|
||||
self.unlimited(name, kind, TIER_RELATED, detail);
|
||||
}
|
||||
}
|
||||
|
||||
/// The related tier for a name being typed: the members of every package
|
||||
/// the scope chain at the cursor imports, and of the classes the enclosing
|
||||
/// class extends.
|
||||
pub(super) fn related_tier(
|
||||
items: &mut Items,
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
fuzzy: Option<&Query>,
|
||||
) {
|
||||
let mut found = imported(ws, &doc.semantics, word.start);
|
||||
found.extend(inherited(ws, &doc.semantics, word.start));
|
||||
let mut matched: Vec<(Related, Option<Score>)> = found
|
||||
.into_iter()
|
||||
.filter_map(|related| match fuzzy {
|
||||
None => starts_with_ignore_case(&related.name, &word.text).then_some((related, None)),
|
||||
Some(query) => query.score(&related.name).map(|score| (related, Some(score))),
|
||||
})
|
||||
.collect();
|
||||
matched.sort_by(|(a, sa), (b, sb)| match (sa, sb) {
|
||||
(Some(sa), Some(sb)) => rank_cmp((&a.name, *sa), (&b.name, *sb)),
|
||||
_ => a.name.cmp(&b.name),
|
||||
});
|
||||
for (related, _) in matched {
|
||||
items.related(&related.name, completion_kind(related.kind), related.detail);
|
||||
}
|
||||
}
|
||||
|
||||
/// The related tier after a backtick: the macros the headers this buffer
|
||||
/// reaches through its `` `include``s define, ahead of every other macro in
|
||||
/// the workspace.
|
||||
pub(super) fn related_macros(items: &mut Items, ws: &Workspace, doc: &Document, prefix: &str) {
|
||||
let mut names: Vec<(String, String)> = Vec::new();
|
||||
for path in crate::includes::reachable_from(ws, doc) {
|
||||
let Some(table) = ws.index().file_id(&path).and_then(|file| ws.index().defines(file))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let defines = table.entries().iter().filter(|d| d.kind == DefineKind::Define);
|
||||
for define in defines.filter(|d| starts_with_ignore_case(&d.name, prefix)) {
|
||||
names.push((define.name.clone(), crate::candidates::macro_of(define).detail));
|
||||
}
|
||||
}
|
||||
names.sort();
|
||||
names.dedup_by(|a, b| a.0 == b.0);
|
||||
for (name, detail) in names {
|
||||
items.related(&format!("`{name}"), CompletionItemKind::CONSTANT, detail);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every member of every package imported by a scope enclosing `offset`,
|
||||
/// innermost scope first, a wildcard bringing all of a package's members and
|
||||
/// an explicit import the one it names.
|
||||
fn imported(ws: &Workspace, semantics: &Semantics, offset: u32) -> Vec<Related> {
|
||||
let mut out = Vec::new();
|
||||
let mut at = innermost_scope(semantics, offset).or(Some(semantics.file_scope()));
|
||||
while let Some(id) = at {
|
||||
let Some(scope) = semantics.scope(id) else { break };
|
||||
at = scope.parent;
|
||||
for import in &scope.imports {
|
||||
for (name, defs) in ws.index().members_of(&import.package) {
|
||||
if import.item.as_deref().is_some_and(|item| item != name) {
|
||||
continue;
|
||||
}
|
||||
let Some(def) = defs.first() else { continue };
|
||||
out.push(Related {
|
||||
name: name.to_string(),
|
||||
kind: def.kind,
|
||||
detail: format!("{} — {}::{name}", kind_label(def.kind), import.package),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Every member the enclosing class inherits, as the index's member chain for
|
||||
/// that class lists it — its own members included, which the scope tier has
|
||||
/// already claimed — each named after the class that **declares** it, the
|
||||
/// way the workspace tier names a member (`base_c::count`).
|
||||
fn inherited(ws: &Workspace, semantics: &Semantics, offset: u32) -> Vec<Related> {
|
||||
let mut at = innermost_scope(semantics, offset);
|
||||
while let Some(id) = at {
|
||||
let Some(scope) = semantics.scope(id) else { break };
|
||||
if scope.kind == ScopeKind::Class {
|
||||
let Some(key) = semantics.member_key(id) else { return Vec::new() };
|
||||
let index = ws.index();
|
||||
return index
|
||||
.members_of_chain(&key)
|
||||
.into_iter()
|
||||
.map(|(name, def)| {
|
||||
let owner = declaring_class(ws, &key, name, def).unwrap_or(&key);
|
||||
Related {
|
||||
name: name.to_string(),
|
||||
kind: def.kind,
|
||||
detail: format!("{} — {owner}::{name}", kind_label(def.kind)),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
at = scope.parent;
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Which class of `class`'s `extends` chain declares `def` as `name`: the
|
||||
/// class itself, then its base, then that base's base — each hop the one
|
||||
/// `vlog_semantic`'s `base_chain` takes, a recorded base or else the class a
|
||||
/// typedef aliases (`typedef mid_c alias_t; class leaf_c extends alias_t;`).
|
||||
/// `None` only for a chain the index cannot follow, and the caller then
|
||||
/// names the class it started from.
|
||||
fn declaring_class<'a>(
|
||||
ws: &'a Workspace,
|
||||
class: &'a str,
|
||||
name: &str,
|
||||
def: &Def,
|
||||
) -> Option<&'a str> {
|
||||
let index = ws.index();
|
||||
let mut hop = Some(class);
|
||||
let mut seen: Vec<&str> = Vec::new();
|
||||
while let Some(unit) = hop.filter(|unit| !seen.contains(unit)) {
|
||||
if index.members_of(unit).any(|(member, defs)| member == name && defs.first() == Some(def))
|
||||
{
|
||||
return Some(unit);
|
||||
}
|
||||
seen.push(unit);
|
||||
hop = index.base_of(unit).or_else(|| aliased_class(ws, unit)).map(last_segment);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The class a typedef names, when `unit` is a typedef the index holds once —
|
||||
/// the alias hop of `vlog_semantic`'s `base_chain` (`aliased_unit`), read
|
||||
/// through the index's public tables.
|
||||
fn aliased_class<'a>(ws: &'a Workspace, unit: &str) -> Option<&'a str> {
|
||||
match ws.index().units(unit) {
|
||||
[def] if def.kind == SymbolKind::Typedef => def.type_name.as_deref(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The last `::` segment of a possibly qualified class path — the name the
|
||||
/// member and inheritance tables are keyed by.
|
||||
fn last_segment(path: &str) -> &str {
|
||||
path.rsplit("::").next().unwrap_or(path)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::completion::harness::*;
|
||||
use crate::completion::*;
|
||||
|
||||
/// A package the buffer imports, and one it does not, both holding names
|
||||
/// that start alike.
|
||||
fn two_packages(name: &str) -> Tree {
|
||||
let tree = Tree::new(name);
|
||||
tree.write(
|
||||
"near.sv",
|
||||
"package near_pkg;\n localparam int ZED_NEAR = 1;\n typedef logic zed_t;\nendpackage\n",
|
||||
);
|
||||
tree.write("far.sv", "package far_pkg;\n localparam int ZED_FAR = 2;\nendpackage\n");
|
||||
tree
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_imported_packages_members_rank_above_the_rest_of_the_workspace() {
|
||||
let top = "module top;\n import near_pkg::*;\n assign x = ze\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(two_packages("rel_import"), top, "= ze");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let near = find(&items, "ZED_NEAR").expect("the imported member");
|
||||
let far = find(&items, "ZED_FAR").expect("the other package's member is still offered");
|
||||
assert_eq!(tier(near), TIER_RELATED);
|
||||
assert_eq!(tier(far), TIER_INDEX);
|
||||
assert!(near.sort_text < far.sort_text, "related above the workspace");
|
||||
assert_eq!(near.detail.as_deref(), Some("localparam — near_pkg::ZED_NEAR"));
|
||||
assert_eq!(tier(find(&items, "zed_t").expect("the typedef")), TIER_RELATED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicit_import_relates_the_one_name_it_imports() {
|
||||
let top = "module top;\n import near_pkg::zed_t;\n assign x = ze\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(two_packages("rel_explicit"), top, "= ze");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
// The binder makes an explicitly imported name a declaration of this
|
||||
// scope, so it is offered by the scope tier, above even this one.
|
||||
assert!(tier(find(&items, "zed_t").expect("imported")) <= TIER_RELATED);
|
||||
assert_eq!(tier(find(&items, "ZED_NEAR").expect("still offered")), TIER_INDEX);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn related_items_take_nothing_from_the_tiers_after_them() {
|
||||
// More project names than the cap, and an import whose members all
|
||||
// match too: the workspace tiers still fill the whole cap.
|
||||
let tree = two_packages("rel_cap");
|
||||
let mut many = String::from("package many_pkg;\n");
|
||||
for i in 0..LIMIT + 40 {
|
||||
many.push_str(&format!(" localparam int ZED_{i:04} = {i};\n"));
|
||||
}
|
||||
many.push_str("endpackage\n");
|
||||
tree.write("many.sv", &many);
|
||||
let top = "module top;\n import near_pkg::*;\n assign x = ZE\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "= ZE");
|
||||
let Some(CompletionResponse::List(list)) = completions(&ws, &uri, position, true) else {
|
||||
panic!("a list");
|
||||
};
|
||||
let related = list.items.iter().filter(|i| tier(i) == TIER_RELATED).count();
|
||||
assert_eq!(related, 2, "the two near_pkg names");
|
||||
assert_eq!(list.items.len() - related, LIMIT, "the cap counts the others only");
|
||||
assert!(list.is_incomplete);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_class_relates_what_it_inherits() {
|
||||
let tree = Tree::new("rel_class");
|
||||
tree.write(
|
||||
"base.sv",
|
||||
"class base_c;\n int zed_count;\n function void zed_reset();\n endfunction\nendclass\n",
|
||||
);
|
||||
let top = "class derived_c extends base_c;\n function void go();\n ze\n endfunction\nendclass\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, " ze");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let count = find(&items, "zed_count").expect("inherited");
|
||||
assert_eq!(tier(count), TIER_RELATED);
|
||||
assert_eq!(tier(find(&items, "zed_reset").expect("inherited")), TIER_RELATED);
|
||||
// Named after the class that declares it, as the workspace tier
|
||||
// names a member — not after the class that inherits it.
|
||||
assert_eq!(count.detail.as_deref(), Some("variable — base_c::zed_count"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_backtick_ranks_what_the_included_headers_define_first() {
|
||||
let tree = Tree::new("rel_macro");
|
||||
tree.write("near.svh", "`define ZED_NEAR 1\n");
|
||||
tree.write("far.svh", "`define ZED_FAR 2\n");
|
||||
let top = "`include \"near.svh\"\nmodule top;\n assign x = `ZE\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "`ZE");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let near = find(&items, "`ZED_NEAR").expect("the included header's macro");
|
||||
let far = find(&items, "`ZED_FAR").expect("every other macro is still offered");
|
||||
assert_eq!(tier(near), TIER_RELATED);
|
||||
assert!(near.sort_text < far.sort_text);
|
||||
assert_eq!(near.detail.as_deref(), Some("`define ZED_NEAR"), "the detail tier 5 gives");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_two_classes_up_names_the_class_that_declares_it() {
|
||||
let tree = Tree::new("rel_grand");
|
||||
tree.write("base.sv", "class root_c;\n int zed_deep;\nendclass\nclass mid_c extends root_c;\n int zed_mid;\nendclass\n");
|
||||
let top =
|
||||
"class leaf_c extends mid_c;\n function void go();\n ze\n endfunction\nendclass\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, " ze");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let detail = |label: &str| find(&items, label).and_then(|i| i.detail.clone());
|
||||
assert_eq!(detail("zed_deep").as_deref(), Some("variable — root_c::zed_deep"));
|
||||
assert_eq!(detail("zed_mid").as_deref(), Some("variable — mid_c::zed_mid"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_reached_through_a_typedef_alias_names_the_class_that_declares_it() {
|
||||
// QA R2: `leaf_c extends alias_t`, and `alias_t` is a typedef of
|
||||
// `mid_c` — the member is `mid_c`'s.
|
||||
let tree = Tree::new("rel_alias");
|
||||
tree.write("base.sv", "class mid_c;\n int zed_mid;\nendclass\ntypedef mid_c alias_t;\n");
|
||||
let top = "class leaf_c extends alias_t;\n function void go();\n ze\n endfunction\nendclass\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, " ze");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let mid = find(&items, "zed_mid").expect("inherited through the alias");
|
||||
assert_eq!(tier(mid), TIER_RELATED);
|
||||
assert_eq!(mid.detail.as_deref(), Some("variable — mid_c::zed_mid"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
//! What a completion answer costs on the wire, for a client that can take
|
||||
//! less (`docs/features/fast-actions/README.md`, "payload").
|
||||
//!
|
||||
//! Every item of one answer replaces the same range, and almost every item
|
||||
//! inserts its own label as plain text — so the `textEdit` each one carries
|
||||
//! (49 % of a 130 KB answer, measured) and its `insertTextFormat` (8 %) say
|
||||
//! the same thing five hundred times. LSP 3.17's `CompletionList.itemDefaults`
|
||||
//! says it once: an item with no `textEdit` replaces `editRange` with its
|
||||
//! `textEditText`, or with its label when it has none, in
|
||||
//! `insertTextFormat`. `vscode-languageclient` 9 applies exactly that rule
|
||||
//! (`protocolConverter.asCompletionInsertText`), and advertises both defaults.
|
||||
//!
|
||||
//! **The same edits, fewer bytes.** The rewrite is lossless by construction:
|
||||
//! an item keeps its own `textEdit` unless its range *is* the default, keeps
|
||||
//! its own format unless it *is* the default, and moves a `newText` that is
|
||||
//! not its label into `textEditText`. Done on the serialized answer because
|
||||
//! `lsp-types` 0.97 has neither field.
|
||||
|
||||
use lsp_types::InitializeParams;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
/// `insertTextFormat: PlainText`, the format nearly every item has.
|
||||
const PLAIN_TEXT: u64 = 1;
|
||||
|
||||
/// Whether the client applies `itemDefaults.editRange` and
|
||||
/// `itemDefaults.insertTextFormat` — `textDocument.completion.completionList
|
||||
/// .itemDefaults` listing both. A client that said nothing gets every item
|
||||
/// whole, which is what every client got before this was read.
|
||||
pub(crate) fn item_defaults_support(params: &InitializeParams) -> bool {
|
||||
let listed = params
|
||||
.capabilities
|
||||
.text_document
|
||||
.as_ref()
|
||||
.and_then(|text_document| text_document.completion.as_ref())
|
||||
.and_then(|completion| completion.completion_list.as_ref())
|
||||
.and_then(|list| list.item_defaults.as_ref());
|
||||
listed.is_some_and(|names| {
|
||||
["editRange", "insertTextFormat"].iter().all(|wanted| names.iter().any(|n| n == wanted))
|
||||
})
|
||||
}
|
||||
|
||||
/// Rewrite a serialized `CompletionList` so the range and the format every
|
||||
/// item shares are said once, in `itemDefaults`. Anything that is not a list
|
||||
/// with items comes back as it was.
|
||||
pub(crate) fn with_item_defaults(mut answer: Value) -> Value {
|
||||
let Some(list) = answer.as_object_mut() else { return answer };
|
||||
let Some(Value::Array(items)) = list.get_mut("items") else { return answer };
|
||||
let Some(range) = items.first().and_then(edit_range).cloned() else { return answer };
|
||||
for item in items.iter_mut().filter_map(Value::as_object_mut) {
|
||||
lift_edit(item, &range);
|
||||
if item.get("insertTextFormat").and_then(Value::as_u64) == Some(PLAIN_TEXT) {
|
||||
item.remove("insertTextFormat");
|
||||
}
|
||||
}
|
||||
let mut defaults = Map::new();
|
||||
defaults.insert("editRange".to_string(), range);
|
||||
defaults.insert("insertTextFormat".to_string(), Value::from(PLAIN_TEXT));
|
||||
list.insert("itemDefaults".to_string(), Value::Object(defaults));
|
||||
answer
|
||||
}
|
||||
|
||||
/// The range a plain `textEdit` replaces, if the item has one.
|
||||
fn edit_range(item: &Value) -> Option<&Value> {
|
||||
let edit = item.get("textEdit")?;
|
||||
edit.get("newText")?;
|
||||
edit.get("range")
|
||||
}
|
||||
|
||||
/// Drop `item`'s `textEdit` when it replaces `range`, keeping its text in
|
||||
/// `textEditText` unless that text is the label.
|
||||
fn lift_edit(item: &mut Map<String, Value>, range: &Value) {
|
||||
let Some(edit) = item.get("textEdit") else { return };
|
||||
if edit.get("range") != Some(range) {
|
||||
return;
|
||||
}
|
||||
let Some(Value::Object(mut edit)) = item.remove("textEdit") else { return };
|
||||
let new_text = edit.remove("newText").unwrap_or(Value::Null);
|
||||
if item.get("label") != Some(&new_text) {
|
||||
item.insert("textEditText".to_string(), new_text);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn range(line: u32) -> Value {
|
||||
json!({ "start": { "line": line, "character": 4 }, "end": { "line": line, "character": 6 } })
|
||||
}
|
||||
|
||||
/// The edit an item makes under the LSP 3.17 rule, defaults applied.
|
||||
fn effective(item: &Value, defaults: &Value) -> (Value, Value, Value) {
|
||||
let format = item.get("insertTextFormat").unwrap_or(&defaults["insertTextFormat"]).clone();
|
||||
match item.get("textEdit") {
|
||||
Some(edit) => (edit["range"].clone(), edit["newText"].clone(), format),
|
||||
None => (
|
||||
defaults["editRange"].clone(),
|
||||
item.get("textEditText").unwrap_or(&item["label"]).clone(),
|
||||
format,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_item_makes_the_same_edit_with_the_defaults_applied() {
|
||||
let before = json!({ "isIncomplete": true, "items": [
|
||||
{ "label": "sig", "insertTextFormat": 1,
|
||||
"textEdit": { "range": range(2), "newText": "sig" } },
|
||||
{ "label": "if begin/end", "insertTextFormat": 2,
|
||||
"textEdit": { "range": range(2), "newText": "if (${1:cond}) begin\n$0\nend" } },
|
||||
{ "label": "`W", "insertTextFormat": 1,
|
||||
"textEdit": { "range": range(2), "newText": "`W" } },
|
||||
{ "label": "odd", "insertTextFormat": 1,
|
||||
"textEdit": { "range": range(7), "newText": "odd" } },
|
||||
]});
|
||||
let after = with_item_defaults(before.clone());
|
||||
let defaults = &after["itemDefaults"];
|
||||
assert_eq!(defaults["editRange"], range(2));
|
||||
for (old, new) in
|
||||
before["items"].as_array().unwrap().iter().zip(after["items"].as_array().unwrap())
|
||||
{
|
||||
let old_effect = (
|
||||
old["textEdit"]["range"].clone(),
|
||||
old["textEdit"]["newText"].clone(),
|
||||
old["insertTextFormat"].clone(),
|
||||
);
|
||||
assert_eq!(effective(new, defaults), old_effect, "{new}");
|
||||
}
|
||||
assert!(after["items"][0].get("textEdit").is_none(), "the label is the text");
|
||||
assert!(after["items"][0].get("textEditText").is_none());
|
||||
assert_eq!(after["items"][1]["textEditText"], before["items"][1]["textEdit"]["newText"]);
|
||||
assert!(after["items"][3].get("textEdit").is_some(), "another range keeps its edit");
|
||||
assert!(after.to_string().len() < before.to_string().len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answer_that_is_not_a_list_of_edits_is_left_alone() {
|
||||
for answer in [
|
||||
Value::Null,
|
||||
json!([]),
|
||||
json!({ "isIncomplete": false, "items": [] }),
|
||||
json!({ "items": [{ "label": "x", "insertText": "x" }] }),
|
||||
] {
|
||||
assert_eq!(with_item_defaults(answer.clone()), answer);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -578,15 +578,21 @@ pub fn document_links(ws: &Workspace, uri: &Uri) -> Vec<DocumentLink> {
|
||||
/// The same computation the links use, so F12 and ctrl-click can never
|
||||
/// disagree about where a line goes.
|
||||
pub fn definition(ws: &Workspace, doc: &Document, offset: u32) -> Option<Location> {
|
||||
let include = include_at(doc, offset)?;
|
||||
let path = ws.includes().resolve(doc.path.as_deref(), &include)?;
|
||||
Some(Location { uri: path_to_uri(&path)?, range: Range::default() })
|
||||
}
|
||||
|
||||
/// The `` `include`` whose directive covers `offset`, read off the buffer's
|
||||
/// own line — the one question go-to-definition asks before any other, and
|
||||
/// the one `same_file` asks to know that the answer is a path to resolve.
|
||||
pub(crate) fn include_at(doc: &Document, offset: u32) -> Option<Include> {
|
||||
// Definition is a cursor request, so inspect only its line. `documentLink`
|
||||
// still scans the whole file because it must return every include.
|
||||
let (line, _) = doc.line_index.line_col(offset);
|
||||
let line = doc.line_index.line_range(line)?;
|
||||
let text = doc.text.get(line.as_range())?;
|
||||
let include =
|
||||
include_on_line(text, line.start).filter(|include| include.span.contains(offset))?;
|
||||
let path = ws.includes().resolve(doc.path.as_deref(), &include)?;
|
||||
Some(Location { uri: path_to_uri(&path)?, range: Range::default() })
|
||||
include_on_line(text, line.start).filter(|include| include.span.contains(offset))
|
||||
}
|
||||
|
||||
/// Every file this buffer reaches through `` `include``, transitively.
|
||||
|
||||
@@ -121,11 +121,7 @@ pub fn window(doc: &Document, range: lsp_types::Range) -> Window {
|
||||
/// Both ends land on a character boundary: a line start and a line end always
|
||||
/// do, and the cap is floored onto one.
|
||||
fn bounds(index: &LineIndex, len: u32, range: lsp_types::Range) -> (u32, u32) {
|
||||
let last = index.line_count();
|
||||
let first_line = (range.start.line + 1).min(last);
|
||||
let last_line = (range.end.line + 1).clamp(first_line, last);
|
||||
let start = index.line_range(first_line).map_or(0, |line| line.start);
|
||||
let mut end = index.line_range(last_line).map_or(len, |line| line.end);
|
||||
let (start, mut end) = line_window(index, len, range);
|
||||
if end.saturating_sub(start) > MAX_WINDOW {
|
||||
// Snapped to the line the cap lands in where that helps, and cut
|
||||
// mid-line where it does not: a single line longer than the cap is
|
||||
@@ -140,6 +136,20 @@ fn bounds(index: &LineIndex, len: u32, range: lsp_types::Range) -> (u32, u32) {
|
||||
(start, end.max(start))
|
||||
}
|
||||
|
||||
/// The byte range one `Range` asks about, snapped out to the whole lines it
|
||||
/// touches and **not** capped — the window an analyzed buffer's range answer
|
||||
/// selects its tokens from (`tokens::semantic_tokens_in_range`), and the first
|
||||
/// half of [`bounds`]. Both ends are line boundaries, so both are character
|
||||
/// boundaries; a range past the end of the file is the empty window there.
|
||||
pub fn line_window(index: &LineIndex, len: u32, range: lsp_types::Range) -> (u32, u32) {
|
||||
let last = index.line_count();
|
||||
let first_line = (range.start.line.saturating_add(1)).min(last);
|
||||
let last_line = (range.end.line.saturating_add(1)).clamp(first_line, last);
|
||||
let start = index.line_range(first_line).map_or(0, |line| line.start);
|
||||
let end = index.line_range(last_line).map_or(len, |line| line.end);
|
||||
(start, end.max(start))
|
||||
}
|
||||
|
||||
/// Whether the byte at `at` is inside a `/* ... */` comment, as far as a
|
||||
/// backwards scan of at most [`BACKSCAN`] bytes can tell.
|
||||
///
|
||||
@@ -822,14 +832,15 @@ mod tests {
|
||||
for doc in &docs {
|
||||
assert!(!window(doc, range(0, 1)).tokens.is_empty());
|
||||
}
|
||||
let costs = fastest_of_five(&docs, |doc| {
|
||||
let clock = Instant::now();
|
||||
let data = crate::tokens::semantic_tokens_in_window(doc, range(0, 1));
|
||||
let elapsed = clock.elapsed();
|
||||
assert!(!data.is_empty(), "the window really did colour something");
|
||||
elapsed
|
||||
assert_grows_linearly(&sizes, "colouring tokens on one line", || {
|
||||
fastest_of_five(&docs, |doc| {
|
||||
let clock = Instant::now();
|
||||
let data = crate::tokens::semantic_tokens_in_window(doc, range(0, 1));
|
||||
let elapsed = clock.elapsed();
|
||||
assert!(!data.is_empty(), "the window really did colour something");
|
||||
elapsed
|
||||
})
|
||||
});
|
||||
assert_grows_linearly(&sizes, &costs, "colouring tokens on one line");
|
||||
}
|
||||
|
||||
/// **QA finding 1 (2026-08-27), fixed and now a gate**, on the *other*
|
||||
@@ -869,17 +880,18 @@ mod tests {
|
||||
(doc, hits)
|
||||
})
|
||||
.collect();
|
||||
let costs = fastest_of_five(&docs, |(doc, hits)| {
|
||||
let positions = doc.positions();
|
||||
let clock = Instant::now();
|
||||
// Exactly what `Server::large_scan` does with them.
|
||||
let mut walker = positions.walker();
|
||||
for hit in hits {
|
||||
std::hint::black_box(walker.range(*hit));
|
||||
}
|
||||
clock.elapsed()
|
||||
assert_grows_linearly(&sizes, "locating hits on one line", || {
|
||||
fastest_of_five(&docs, |(doc, hits)| {
|
||||
let positions = doc.positions();
|
||||
let clock = Instant::now();
|
||||
// Exactly what `Server::large_scan` does with them.
|
||||
let mut walker = positions.walker();
|
||||
for hit in hits {
|
||||
std::hint::black_box(walker.range(*hit));
|
||||
}
|
||||
clock.elapsed()
|
||||
})
|
||||
});
|
||||
assert_grows_linearly(&sizes, &costs, "locating hits on one line");
|
||||
}
|
||||
|
||||
/// How much faster than its input a linear-time test's cost may grow
|
||||
@@ -903,21 +915,40 @@ mod tests {
|
||||
fastest
|
||||
}
|
||||
|
||||
/// How many times a measurement over [`GROWTH_SLACK`] is taken again
|
||||
/// before the test fails. Load from the tests running beside this one
|
||||
/// can stretch one whole measurement (the Linux runner read 24.9x of the
|
||||
/// 24x limit once, with 1.35x between two neighbouring sizes); a
|
||||
/// quadratic conversion measures ~64x every time, so asking again
|
||||
/// loosens nothing the test can see.
|
||||
const ATTEMPTS: usize = 3;
|
||||
|
||||
/// Fails unless the cost at the largest size is within [`GROWTH_SLACK`]
|
||||
/// of linear growth from the smallest.
|
||||
/// of linear growth from the smallest, in one of [`ATTEMPTS`] measurements.
|
||||
#[track_caller]
|
||||
fn assert_grows_linearly(sizes: &[u32], costs: &[Duration], what: &str) {
|
||||
for (size, cost) in sizes.iter().zip(costs) {
|
||||
eprintln!("{what}: {size} → {cost:?}");
|
||||
}
|
||||
fn assert_grows_linearly(
|
||||
sizes: &[u32],
|
||||
what: &str,
|
||||
mut measure: impl FnMut() -> Vec<Duration>,
|
||||
) {
|
||||
let (first, last) = (sizes[0], sizes[sizes.len() - 1]);
|
||||
let input = f64::from(last) / f64::from(first);
|
||||
let growth =
|
||||
costs[costs.len() - 1].as_secs_f64() / costs[0].as_secs_f64().max(f64::MIN_POSITIVE);
|
||||
assert!(
|
||||
growth <= GROWTH_SLACK * input,
|
||||
"{what}: {input}x the input cost {growth:.1}x the time ({costs:?}) — \
|
||||
more than {GROWTH_SLACK}x linear, the quadratic conversion is back"
|
||||
let mut seen = Vec::new();
|
||||
for _ in 0..ATTEMPTS {
|
||||
let costs = measure();
|
||||
for (size, cost) in sizes.iter().zip(&costs) {
|
||||
eprintln!("{what}: {size} → {cost:?}");
|
||||
}
|
||||
let growth = costs[costs.len() - 1].as_secs_f64()
|
||||
/ costs[0].as_secs_f64().max(f64::MIN_POSITIVE);
|
||||
if growth <= GROWTH_SLACK * input {
|
||||
return;
|
||||
}
|
||||
seen.push((growth, costs));
|
||||
}
|
||||
panic!(
|
||||
"{what}: {input}x the input cost more than {GROWTH_SLACK}x linear in each of \
|
||||
{ATTEMPTS} measurements ({seen:?}) — the quadratic conversion is back"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
mod auto_style;
|
||||
mod candidates;
|
||||
mod caret;
|
||||
mod code_action;
|
||||
mod completion;
|
||||
mod convert;
|
||||
@@ -44,6 +45,7 @@ mod perf;
|
||||
mod ports;
|
||||
mod rename;
|
||||
mod rename_trace;
|
||||
mod same_file;
|
||||
mod scan_order;
|
||||
mod scan_trace;
|
||||
mod selection;
|
||||
@@ -139,9 +141,11 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
show_document: show_document_support(¶ms),
|
||||
configuration: configuration_support(¶ms),
|
||||
token_server_cancel: token_server_cancel_support(¶ms),
|
||||
semantic_tokens_refresh: semantic_tokens_refresh_support(¶ms),
|
||||
hierarchy_view,
|
||||
code_action_resolve: code_action_resolve_support(¶ms),
|
||||
create_files: create_files_support(¶ms),
|
||||
completion_item_defaults: completion::item_defaults_support(¶ms),
|
||||
};
|
||||
connection.initialize_finish(id, initialize_value(ranges_formatting)?)?;
|
||||
|
||||
@@ -604,6 +608,21 @@ fn token_server_cancel_support(params: &InitializeParams) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the client can be asked to re-request its semantic tokens
|
||||
/// (`workspace/semanticTokens/refresh`), which is what replaces colours taken
|
||||
/// off a half-built index once it has settled
|
||||
/// (`docs/features/viewport-highlight/README.md`). Server-initiated, so the
|
||||
/// capability is the gate; silence means no.
|
||||
fn semantic_tokens_refresh_support(params: &InitializeParams) -> bool {
|
||||
params
|
||||
.capabilities
|
||||
.workspace
|
||||
.as_ref()
|
||||
.and_then(|workspace| workspace.semantic_tokens.as_ref())
|
||||
.and_then(|tokens| tokens.refresh_support)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the client pulls diagnostics (LSP 3.17).
|
||||
///
|
||||
/// Sending the capability at all is what says so; its two fields are about
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
//! Same file first: whether a request's **whole** answer comes from its own
|
||||
//! buffer, so that it need not wait for the workspace index
|
||||
//! (`docs/features/fast-actions/README.md`).
|
||||
//!
|
||||
//! The server answers a request so decided from the buffer while a scan holds
|
||||
//! everything else (`server/ahead.rs`). The answer is then the one the settled
|
||||
//! server gives, by construction: this file says yes only where the handler
|
||||
//! the dispatch runs reads nothing but the buffer's own analysis — its text,
|
||||
//! tokens, tree, `Semantics` and `` `define`` table, all of which are a
|
||||
//! function of the text alone (`Document::new`: "the single-file analysis is
|
||||
//! unaffected by other files"). The two things a buffer holds that are **not**
|
||||
//! its text's are the workspace overlay (`ExternalResolutions`) and every
|
||||
//! table behind `Workspace::index`; a yes here is a proof that the handler's
|
||||
//! path for this position reaches neither.
|
||||
//!
|
||||
//! **The locality rule**, the one question under most answers here: is the
|
||||
//! name under the cursor bound by this file? A *use* is when the single-file
|
||||
//! binder resolved it (`Reference::resolved`); an unresolved use is the
|
||||
//! overlay's to answer, and so is not. A cursor on a *declaration* or on no
|
||||
//! name at all is answered from the buffer alone. Three shapes look local and
|
||||
//! are not, each answered by waiting:
|
||||
//!
|
||||
//! * a use the binder left to the workspace — a name a wildcard `import`
|
||||
//! brings in, a package-qualified name, an instantiated module, an inherited
|
||||
//! class member (even one declared in this very file: the class hierarchy
|
||||
//! that finds it is the index's), a hierarchical path;
|
||||
//! * a macro use with no `` `define`` in this buffer — the header that defines
|
||||
//! it is found through the include graph and the index;
|
||||
//! * an `` `include`` line — its path is resolved against the include
|
||||
//! directories and the files the scan has found.
|
||||
//!
|
||||
//! A local binding that the language would let an import shadow is **not** in
|
||||
//! that list, deliberately: the dispatch's own answer is the local binding too
|
||||
//! (`ExternalResolutions::definition_of` asks the binder first), so the early
|
||||
//! answer is the settled answer — the contract here is "the same answer",
|
||||
//! which is the only one a differential test can hold the server to.
|
||||
|
||||
use lsp_types::request::{
|
||||
DocumentHighlightRequest, DocumentSymbolRequest, FoldingRangeRequest, GotoDefinition,
|
||||
GotoTypeDefinition, HoverRequest, LinkedEditingRange, PrepareRenameRequest, References,
|
||||
Request as _, SelectionRangeRequest, SignatureHelpRequest,
|
||||
};
|
||||
use lsp_types::Position;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::state::Document;
|
||||
use crate::{caret, hover, includes, nav, pairs, signature, type_def};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// The requests this file can ever say yes to. Everything else — completion,
|
||||
/// inlay hints, code lenses, document links, the workspace-wide requests —
|
||||
/// reads the index on every path and always waits.
|
||||
pub(crate) const METHODS: [&str; 12] = [
|
||||
DocumentSymbolRequest::METHOD,
|
||||
FoldingRangeRequest::METHOD,
|
||||
SelectionRangeRequest::METHOD,
|
||||
LinkedEditingRange::METHOD,
|
||||
pairs::SCOPE_PAIRS_METHOD,
|
||||
HoverRequest::METHOD,
|
||||
GotoDefinition::METHOD,
|
||||
GotoTypeDefinition::METHOD,
|
||||
DocumentHighlightRequest::METHOD,
|
||||
References::METHOD,
|
||||
PrepareRenameRequest::METHOD,
|
||||
SignatureHelpRequest::METHOD,
|
||||
];
|
||||
|
||||
/// Whether the dispatch's answer to `method` with `params` reads nothing but
|
||||
/// `doc`, the buffer the request names — see the module documentation.
|
||||
///
|
||||
/// A dispatch table over the methods above, each arm the mirror of the path
|
||||
/// its handler takes; an arm says yes only where every branch that handler
|
||||
/// can take from this position is a branch over the buffer.
|
||||
pub(crate) fn answered_by_the_buffer(doc: &Document, method: &str, params: &Value) -> bool {
|
||||
match method {
|
||||
// Whole-buffer answers: each handler takes the `Document` and nothing
|
||||
// else (`symbols::document_symbols`, `folding::folding_ranges`,
|
||||
// `selection::selection_ranges`, `linked::linked_editing_ranges`,
|
||||
// `pairs::scope_pairs`).
|
||||
DocumentSymbolRequest::METHOD
|
||||
| FoldingRangeRequest::METHOD
|
||||
| SelectionRangeRequest::METHOD
|
||||
| LinkedEditingRange::METHOD
|
||||
| pairs::SCOPE_PAIRS_METHOD => true,
|
||||
HoverRequest::METHOD => at_name(doc, params).is_some_and(|at| bound_here(doc, at)),
|
||||
GotoDefinition::METHOD => at_name(doc, params).is_some_and(|at| defined_here(doc, at)),
|
||||
GotoTypeDefinition::METHOD => at_name(doc, params).is_some_and(|at| {
|
||||
// The type name is found in the buffer; the jump is then exactly
|
||||
// a go-to-definition from it (`type_def::type_definition`).
|
||||
type_def::type_name(doc, at).is_none_or(|span| defined_here(doc, span.start))
|
||||
}),
|
||||
DocumentHighlightRequest::METHOD => {
|
||||
at_name(doc, params).is_some_and(|at| highlighted_here(doc, at))
|
||||
}
|
||||
References::METHOD => at_name(doc, params).is_some_and(|at| cannot_leave(doc, at)),
|
||||
PrepareRenameRequest::METHOD => {
|
||||
at_name(doc, params).is_some_and(|at| renamed_here(doc, at))
|
||||
}
|
||||
// Only outside an instantiation's lists: inside one, the signature is
|
||||
// the instantiated module's, read from its file.
|
||||
SignatureHelpRequest::METHOD => at_caret(doc, params)
|
||||
.is_some_and(|at| signature::enclosing_list(&doc.tokens, at).is_none()),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The byte offset the request's `position` names, as sent.
|
||||
fn at_caret(doc: &Document, params: &Value) -> Option<u32> {
|
||||
let position: Position = serde_json::from_value(params.get("position")?.clone()).ok()?;
|
||||
Some(doc.positions().offset(position))
|
||||
}
|
||||
|
||||
/// [`at_caret`] with the caret rule the dispatch applies to a request about
|
||||
/// the name under the cursor ([`caret::symbol_offset`]).
|
||||
fn at_name(doc: &Document, params: &Value) -> Option<u32> {
|
||||
at_caret(doc, params).map(|offset| caret::symbol_offset(&doc.text, offset))
|
||||
}
|
||||
|
||||
/// The locality rule: whether whatever is at `offset` — a macro use, a use
|
||||
/// of a name, a declaration, or nothing — is answered from this buffer.
|
||||
///
|
||||
/// Mirrors `hover::hover`: a macro use with a `` `define`` here is answered
|
||||
/// by it, one without is the workspace's; a use is this file's exactly when
|
||||
/// the binder resolved it; a declaration, or no name at all, reads nothing
|
||||
/// else.
|
||||
fn bound_here(doc: &Document, offset: u32) -> bool {
|
||||
if let Some(name) = doc.token_at(offset).filter(|t| t.is_macro()).and_then(hover::macro_name) {
|
||||
return doc.defines.latest(name).is_some();
|
||||
}
|
||||
doc.semantics.reference_at(offset).is_none_or(|use_| use_.resolved().is_some())
|
||||
}
|
||||
|
||||
/// [`bound_here`] for `nav::definition`, which asks one question first: an
|
||||
/// `` `include`` line is a path to resolve, never a name.
|
||||
fn defined_here(doc: &Document, offset: u32) -> bool {
|
||||
includes::include_at(doc, offset).is_none() && bound_here(doc, offset)
|
||||
}
|
||||
|
||||
/// Mirrors the highlight handler: a scope keyword pairs with its closer, a
|
||||
/// name this file binds lights its own occurrences, a cursor on no use lights
|
||||
/// nothing — and only an unresolved use asks the overlay
|
||||
/// (`nav::document_highlights`).
|
||||
fn highlighted_here(doc: &Document, offset: u32) -> bool {
|
||||
nav::symbol_at(&doc.semantics, offset).is_some()
|
||||
|| doc.semantics.reference_id_at(offset).is_none()
|
||||
|| pairs::highlights(doc, offset).is_some()
|
||||
}
|
||||
|
||||
/// Whether find-references here is the in-file answer whatever the index
|
||||
/// holds — a sufficient condition for `nav::references` never asking it.
|
||||
///
|
||||
/// `leaves_this_file` reads the index, so it cannot be asked early; what can
|
||||
/// be read off the buffer is that its answer cannot matter. An `untitled:`
|
||||
/// buffer is never looked up; a cursor on nothing is answered `[]`; and a
|
||||
/// name this file binds in a scope with no **member key** (an unnamed block,
|
||||
/// say) and not at file scope is one the index has no record of, so
|
||||
/// `indexed_def_in_file` finds none and the in-file answer stands. A
|
||||
/// module-level signal, a port, a function's local — each has a key a
|
||||
/// hierarchical path or a connection could reach it by, and waits.
|
||||
fn cannot_leave(doc: &Document, offset: u32) -> bool {
|
||||
if doc.path.is_none() {
|
||||
return true;
|
||||
}
|
||||
if doc.semantics.reference_at(offset).is_some_and(|use_| use_.resolved().is_none()) {
|
||||
return false;
|
||||
}
|
||||
let Some(symbol) =
|
||||
nav::symbol_at(&doc.semantics, offset).and_then(|id| doc.semantics.symbol(id))
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
symbol.scope != doc.semantics.file_scope() && doc.semantics.member_key(symbol.scope).is_none()
|
||||
}
|
||||
|
||||
/// Mirrors `vlog_refactor::prepare_rename_here`: a declaration, or a use the
|
||||
/// binder resolved, is judged on the buffer — except at file scope, where a
|
||||
/// second unit of the same name in the index makes it ambiguous. Any use the
|
||||
/// binder did not resolve waits, which keeps the refusals' wording the
|
||||
/// settled server's.
|
||||
fn renamed_here(doc: &Document, offset: u32) -> bool {
|
||||
if doc.path.is_none() {
|
||||
return true;
|
||||
}
|
||||
let declared = match doc.semantics.reference_at(offset) {
|
||||
Some(use_) => use_.resolved(),
|
||||
None => doc.semantics.symbol_at(offset),
|
||||
};
|
||||
let Some(symbol) = declared.and_then(|id| doc.semantics.symbol(id)) else {
|
||||
// An unresolved use waits; a cursor on nothing is refused alike.
|
||||
return doc.semantics.reference_at(offset).is_none();
|
||||
};
|
||||
symbol.scope != doc.semantics.file_scope()
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
//! The locality rule, shape by shape: each test is one position a user can
|
||||
//! put the cursor on, and whether the buffer alone answers it. The proof that
|
||||
//! a yes is the settled answer is the differential test
|
||||
//! (`server/tests/fast_actions_differential.rs`); these pin the rule.
|
||||
|
||||
use std::str::FromStr;
|
||||
|
||||
use lsp_types::request::{
|
||||
Completion, DocumentHighlightRequest, DocumentSymbolRequest, FoldingRangeRequest,
|
||||
GotoDefinition, GotoTypeDefinition, HoverRequest, InlayHintRequest, PrepareRenameRequest,
|
||||
References, SignatureHelpRequest,
|
||||
};
|
||||
use lsp_types::Uri;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use super::*;
|
||||
use crate::state::Workspace;
|
||||
|
||||
/// A workspace holding one buffer and an empty index — the cold start, and
|
||||
/// the only thing a rule here may read.
|
||||
fn buffer(text: &str) -> Workspace {
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri(), text.to_string());
|
||||
ws
|
||||
}
|
||||
|
||||
fn uri() -> Uri {
|
||||
Uri::from_str("file:///rtl/m.sv").expect("uri")
|
||||
}
|
||||
|
||||
/// The request params with the cursor at the start of the `nth` occurrence
|
||||
/// of `needle`, plus `skip` bytes.
|
||||
fn at(ws: &Workspace, needle: &str, skip: usize) -> Value {
|
||||
let doc = ws.document(&uri()).expect("open");
|
||||
let offset = doc.text.find(needle).expect("needle") + skip;
|
||||
let position = doc.positions().position(offset as u32);
|
||||
json!({ "textDocument": { "uri": uri() }, "position": position,
|
||||
"context": { "includeDeclaration": true } })
|
||||
}
|
||||
|
||||
fn local(ws: &Workspace, method: &str, params: &Value) -> bool {
|
||||
answered_by_the_buffer(ws.document(&uri()).expect("open"), method, params)
|
||||
}
|
||||
|
||||
const WITH_IMPORT: &str = "module m;\n import p::*;\n logic sig;\n state_t st;\n \
|
||||
assign sig = st == IDLE;\n sub u_sub (.a(sig));\n always_comb begin\n \
|
||||
logic tmp;\n tmp = sig;\n end\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn a_use_the_binder_resolved_is_local_for_hover_definition_and_highlight() {
|
||||
let ws = buffer(WITH_IMPORT);
|
||||
let params = at(&ws, "sig = st", 0);
|
||||
for method in [HoverRequest::METHOD, GotoDefinition::METHOD, DocumentHighlightRequest::METHOD] {
|
||||
assert!(local(&ws, method, ¶ms), "{method}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_a_wildcard_import_brings_in_waits() {
|
||||
let ws = buffer(WITH_IMPORT);
|
||||
let params = at(&ws, "IDLE", 0);
|
||||
for method in [HoverRequest::METHOD, GotoDefinition::METHOD, DocumentHighlightRequest::METHOD] {
|
||||
assert!(!local(&ws, method, ¶ms), "{method}: the import's package answers");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instantiated_module_and_its_port_wait() {
|
||||
let ws = buffer(WITH_IMPORT);
|
||||
assert!(!local(&ws, HoverRequest::METHOD, &at(&ws, "sub u_sub", 0)));
|
||||
assert!(!local(&ws, GotoDefinition::METHOD, &at(&ws, ".a(sig)", 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declaration_and_a_cursor_on_no_name_are_local() {
|
||||
let ws = buffer(WITH_IMPORT);
|
||||
assert!(local(&ws, HoverRequest::METHOD, &at(&ws, "sig;", 0)), "a declaration");
|
||||
assert!(local(&ws, HoverRequest::METHOD, &at(&ws, "always_comb", 2)), "a keyword");
|
||||
assert!(local(&ws, GotoDefinition::METHOD, &at(&ws, " logic sig", 0)), "whitespace");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_type_definition_follows_the_type_the_declaration_writes() {
|
||||
// `st` is declared with a type the import brings in; `tmp` with a
|
||||
// built-in one, which has no definition to jump to anywhere.
|
||||
let ws = buffer(WITH_IMPORT);
|
||||
assert!(!local(&ws, GotoTypeDefinition::METHOD, &at(&ws, "st;", 0)));
|
||||
assert!(local(&ws, GotoTypeDefinition::METHOD, &at(&ws, "tmp;", 0)));
|
||||
let typed = buffer("module m;\n typedef logic [3:0] nib_t;\n nib_t n;\nendmodule\n");
|
||||
assert!(local(&typed, GotoTypeDefinition::METHOD, &at(&typed, "n;", 0)), "a local typedef");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_is_local_only_where_this_buffer_defines_it() {
|
||||
let text = "`define HERE 1\nmodule m;\n logic a = `HERE;\n logic b = `THERE;\nendmodule\n";
|
||||
let ws = buffer(text);
|
||||
for method in [HoverRequest::METHOD, GotoDefinition::METHOD] {
|
||||
assert!(local(&ws, method, &at(&ws, "`HERE;", 1)), "{method}");
|
||||
assert!(!local(&ws, method, &at(&ws, "`THERE", 1)), "{method}: a header defines it");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_include_line_is_a_path_for_definition_and_nothing_for_hover() {
|
||||
let ws = buffer("`include \"defs.svh\"\nmodule m;\nendmodule\n");
|
||||
let params = at(&ws, "defs", 0);
|
||||
assert!(!local(&ws, GotoDefinition::METHOD, ¶ms), "resolved against the scan");
|
||||
assert!(local(&ws, HoverRequest::METHOD, ¶ms), "no name, no macro: `null` either way");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_go_ahead_only_where_nothing_can_reach_the_name() {
|
||||
let ws = buffer(WITH_IMPORT);
|
||||
// A module-level signal is reachable as `u_m.sig` from anywhere.
|
||||
assert!(!local(&ws, References::METHOD, &at(&ws, "sig;", 0)));
|
||||
// A declaration in an unnamed block has no member key at all.
|
||||
assert!(local(&ws, References::METHOD, &at(&ws, "tmp = sig", 0)));
|
||||
assert!(!local(&ws, References::METHOD, &at(&ws, "IDLE", 0)), "an unresolved use");
|
||||
assert!(local(&ws, References::METHOD, &at(&ws, "assign", 1)), "nothing here");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untitled_buffer_never_leaves_itself() {
|
||||
let mut ws = Workspace::default();
|
||||
let untitled = Uri::from_str("untitled:Untitled-1").expect("uri");
|
||||
ws.set_document(untitled.clone(), "module m;\n logic sig;\nendmodule\n".to_string());
|
||||
let doc = ws.document(&untitled).expect("open");
|
||||
let position = doc.positions().position(doc.text.find("sig").expect("needle") as u32);
|
||||
let params = json!({ "textDocument": { "uri": untitled }, "position": position });
|
||||
assert!(answered_by_the_buffer(doc, References::METHOD, ¶ms));
|
||||
assert!(answered_by_the_buffer(doc, PrepareRenameRequest::METHOD, ¶ms));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_rename_waits_at_file_scope_and_on_an_unresolved_use() {
|
||||
let ws = buffer(WITH_IMPORT);
|
||||
assert!(!local(&ws, PrepareRenameRequest::METHOD, &at(&ws, "m;", 0)), "a unit name");
|
||||
assert!(local(&ws, PrepareRenameRequest::METHOD, &at(&ws, "sig;", 0)));
|
||||
assert!(local(&ws, PrepareRenameRequest::METHOD, &at(&ws, "sig = st", 0)));
|
||||
assert!(!local(&ws, PrepareRenameRequest::METHOD, &at(&ws, "IDLE", 0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signature_help_waits_only_inside_an_instantiation() {
|
||||
let ws = buffer(WITH_IMPORT);
|
||||
assert!(!local(&ws, SignatureHelpRequest::METHOD, &at(&ws, "sig));", 0)));
|
||||
assert!(local(&ws, SignatureHelpRequest::METHOD, &at(&ws, "st == IDLE", 0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_buffer_requests_always_go_and_index_requests_never_do() {
|
||||
let ws = buffer(WITH_IMPORT);
|
||||
let params = at(&ws, "sig", 0);
|
||||
assert!(local(&ws, DocumentSymbolRequest::METHOD, ¶ms));
|
||||
assert!(local(&ws, FoldingRangeRequest::METHOD, ¶ms));
|
||||
for method in [Completion::METHOD, InlayHintRequest::METHOD, "textDocument/codeLens"] {
|
||||
assert!(!local(&ws, method, ¶ms), "{method} reads the index");
|
||||
assert!(!METHODS.contains(&method));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_position_the_request_does_not_carry_is_not_guessed_at() {
|
||||
let ws = buffer(WITH_IMPORT);
|
||||
let params = json!({ "textDocument": { "uri": uri() } });
|
||||
assert!(!local(&ws, HoverRequest::METHOD, ¶ms));
|
||||
}
|
||||
|
||||
/// The method an arm of the dispatch table answers, by the text of its
|
||||
/// pattern. A pattern this does not know is a new arm: write its row in the
|
||||
/// README's per-request table, then add it here.
|
||||
fn method_of(arm: &str) -> &'static str {
|
||||
use lsp_types::request::*;
|
||||
match arm {
|
||||
"Formatting::METHOD" => Formatting::METHOD,
|
||||
"RangeFormatting::METHOD" => RangeFormatting::METHOD,
|
||||
"format::RANGES_FORMATTING" => crate::format::RANGES_FORMATTING,
|
||||
"OnTypeFormatting::METHOD" => OnTypeFormatting::METHOD,
|
||||
"WillSaveWaitUntil::METHOD" => WillSaveWaitUntil::METHOD,
|
||||
"HoverRequest::METHOD" => HoverRequest::METHOD,
|
||||
"GotoDefinition::METHOD" => GotoDefinition::METHOD,
|
||||
"GotoTypeDefinition::METHOD" => GotoTypeDefinition::METHOD,
|
||||
"LinkedEditingRange::METHOD" => LinkedEditingRange::METHOD,
|
||||
"DocumentLinkRequest::METHOD" => DocumentLinkRequest::METHOD,
|
||||
"References::METHOD" => References::METHOD,
|
||||
"DocumentHighlightRequest::METHOD" => DocumentHighlightRequest::METHOD,
|
||||
"FoldingRangeRequest::METHOD" => FoldingRangeRequest::METHOD,
|
||||
"InlayHintRequest::METHOD" => InlayHintRequest::METHOD,
|
||||
"SemanticTokensFullRequest::METHOD" => SemanticTokensFullRequest::METHOD,
|
||||
"SemanticTokensFullDeltaRequest::METHOD" => SemanticTokensFullDeltaRequest::METHOD,
|
||||
"SemanticTokensRangeRequest::METHOD" => SemanticTokensRangeRequest::METHOD,
|
||||
"DocumentSymbolRequest::METHOD" => DocumentSymbolRequest::METHOD,
|
||||
"CodeActionRequest::METHOD" => CodeActionRequest::METHOD,
|
||||
"CodeActionResolveRequest::METHOD" => CodeActionResolveRequest::METHOD,
|
||||
"pairs::SCOPE_PAIRS_METHOD" => pairs::SCOPE_PAIRS_METHOD,
|
||||
"design_hierarchy::METHOD" => crate::design_hierarchy::METHOD,
|
||||
"PrepareRenameRequest::METHOD" => PrepareRenameRequest::METHOD,
|
||||
"Rename::METHOD" => Rename::METHOD,
|
||||
"CodeLensRequest::METHOD" => CodeLensRequest::METHOD,
|
||||
"ExecuteCommand::METHOD" => ExecuteCommand::METHOD,
|
||||
"DocumentDiagnosticRequest::METHOD" => DocumentDiagnosticRequest::METHOD,
|
||||
"WorkspaceDiagnosticRequest::METHOD" => WorkspaceDiagnosticRequest::METHOD,
|
||||
"SelectionRangeRequest::METHOD" => SelectionRangeRequest::METHOD,
|
||||
"Completion::METHOD" => Completion::METHOD,
|
||||
"InlineCompletionRequest::METHOD" => InlineCompletionRequest::METHOD,
|
||||
"SignatureHelpRequest::METHOD" => SignatureHelpRequest::METHOD,
|
||||
"CallHierarchyPrepare::METHOD" => CallHierarchyPrepare::METHOD,
|
||||
"CallHierarchyIncomingCalls::METHOD" => CallHierarchyIncomingCalls::METHOD,
|
||||
"CallHierarchyOutgoingCalls::METHOD" => CallHierarchyOutgoingCalls::METHOD,
|
||||
"TypeHierarchyPrepare::METHOD" => TypeHierarchyPrepare::METHOD,
|
||||
"TypeHierarchySupertypes::METHOD" => TypeHierarchySupertypes::METHOD,
|
||||
"TypeHierarchySubtypes::METHOD" => TypeHierarchySubtypes::METHOD,
|
||||
"WillRenameFiles::METHOD" => WillRenameFiles::METHOD,
|
||||
"WorkspaceSymbolRequest::METHOD" => WorkspaceSymbolRequest::METHOD,
|
||||
other => panic!("a new dispatch arm `{other}`: give it a row in the README table"),
|
||||
}
|
||||
}
|
||||
|
||||
/// QA Q3 and R3: the README's per-request table names exactly the requests
|
||||
/// the dispatch answers — no row missing, no row stale. Read off the
|
||||
/// dispatch's own source and off the table's first column, compared as sets.
|
||||
#[test]
|
||||
fn the_readme_table_names_every_request_the_dispatch_answers() {
|
||||
use std::collections::BTreeSet;
|
||||
let dispatch = include_str!("../server/dispatch.rs");
|
||||
let readme = include_str!("../../../../docs/features/fast-actions/README.md");
|
||||
let start = readme.find("## The rule per request").expect("the table's section");
|
||||
// Up to the next heading: the sections after it have tables of their own.
|
||||
let section = &readme[start..start + readme[start..].find("\n## ").expect("end")];
|
||||
let answered: BTreeSet<&str> = dispatch
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
let (pattern, _) = line.trim().split_once(" =>")?;
|
||||
(pattern.ends_with("METHOD") || pattern.ends_with("RANGES_FORMATTING"))
|
||||
.then_some(pattern)
|
||||
})
|
||||
.map(method_of)
|
||||
.collect();
|
||||
// The first cell of every row below the header: each request it names is
|
||||
// a backticked method, `group/name`.
|
||||
let tabled: BTreeSet<&str> = section
|
||||
.lines()
|
||||
.filter(|line| line.starts_with("| `"))
|
||||
.filter_map(|line| line.split('|').nth(1))
|
||||
.flat_map(|cell| cell.split('`').skip(1).step_by(2))
|
||||
.filter(|name| name.contains('/'))
|
||||
.collect();
|
||||
assert_eq!(tabled, answered, "the table and the dispatch disagree");
|
||||
for method in METHODS {
|
||||
assert!(answered.contains(method), "{method} is not a dispatch arm");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
//! Answering a request **ahead** of whatever holds the rest, from its buffer
|
||||
//! alone: the colours (`viewport.rs`) and every request whose whole answer the
|
||||
//! buffer gives (`crate::same_file`) — where in a burst, a held batch and a
|
||||
//! widen such a request is taken out, and when its buffer's text is the text
|
||||
//! the client asked about (`docs/features/fast-actions/README.md`).
|
||||
//!
|
||||
//! **What an exempted request reads, and why that is valid mid-scan.** The
|
||||
//! loop is one thread, so a request is only ever answered "during" a scan by
|
||||
//! being reached from inside it — the startup's configuration wait, the drain
|
||||
//! between two of a scan's files (`answer_what_is_waiting`), both through
|
||||
//! `process_batch`, or a widen's between-files drain — so the scan is between
|
||||
//! two files and every buffer is whole. The exemption is taken where the
|
||||
//! request would otherwise be held, and runs the ordinary dispatch arm for the
|
||||
//! method *without* the all-buffers flush (`answer_flushed`). A colouring arm
|
||||
//! reads the buffer and its overlay (`viewport.rs` says what and why a guess
|
||||
//! off the overlay is fine there); every other exempted arm reads only the
|
||||
//! part of the buffer that is a function of its text, which `same_file`
|
||||
//! proves position by position — so its answer **is** the settled answer.
|
||||
//!
|
||||
//! **When.** The whole precondition — the buffer open, every older message
|
||||
//! that could change its answer applied, its analysis current under the
|
||||
//! settings in force, no settings still awaited, the answer the buffer's
|
||||
//! alone — is stated once, on [`Server::answer_from_the_buffer`], the one
|
||||
//! function that decides. Everything else in this file is *where* a request
|
||||
//! is offered to it: at the moment the loop would hold it (`process_batch`),
|
||||
//! behind a held message of its own burst ([`Server::set_aside`]), behind a
|
||||
//! notification of its own burst that is about to be applied
|
||||
//! ([`Server::answer_ahead_of`]), behind a `didOpen` that has been applied
|
||||
//! and is about to widen ([`Server::open_then_widen`]), between
|
||||
//! two files of a widen ([`Server::answer_ahead_mid_widen`]) and when the
|
||||
//! startup's settings land ([`Server::answer_held_ahead`]).
|
||||
//!
|
||||
//! **Ahead of an older message only when that message cannot matter.** What
|
||||
//! is older than a request and still unapplied is in one of four places:
|
||||
//! `held`; the part of its burst being set aside in front of it (`ahead`);
|
||||
//! the next notification of its own burst, which the loop is about to apply
|
||||
//! ([`Server::answer_ahead_of`]); or the tail of a burst a scan is nested in
|
||||
//! ([`Server::behind`]). Clause (b) is one test for all of them — a request
|
||||
//! passes a waiting message only if [`REACH`] proves the message cannot
|
||||
//! change its buffer — where before the escalation round each place had its
|
||||
//! own, and the third let a request pass a settings push (QA's S1).
|
||||
//!
|
||||
//! **A widen** used to drain nothing. Its `didOpen` is applied first; the
|
||||
//! requests behind it in its burst that can go ahead are answered before the
|
||||
//! widen runs ([`Server::open_then_widen`]), and the ones that arrive while
|
||||
//! it runs between two of its files ([`Server::answer_ahead_mid_widen`]),
|
||||
//! everything else being held in arrival order — so the widen stays the
|
||||
//! effect of one applied message and no notification overtakes an older one.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::error::Error;
|
||||
|
||||
use lsp_server::{Message, Notification, Request, RequestId, Response};
|
||||
use lsp_types::notification::{
|
||||
Cancel, DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles,
|
||||
DidChangeWorkspaceFolders, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument,
|
||||
DidRenameFiles, DidSaveTextDocument, Notification as _,
|
||||
};
|
||||
use lsp_types::Uri;
|
||||
|
||||
use super::batch::{cancelled_in, cancelled_response};
|
||||
use super::dispatch::document_uri;
|
||||
use super::{Pending, Server};
|
||||
use crate::same_file;
|
||||
|
||||
/// What applying a client notification can change of what a request answered
|
||||
/// ahead reads: its buffer's `Document` (clause (b) of
|
||||
/// [`Server::answer_from_the_buffer`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum Reach {
|
||||
/// No buffer's `Document`.
|
||||
Nothing,
|
||||
/// The `Document` of the one buffer its `textDocument.uri` names.
|
||||
Named,
|
||||
/// Any buffer's — or nobody has proved otherwise.
|
||||
Any,
|
||||
}
|
||||
|
||||
/// Every notification the server handles — the arms of `handle_notification`,
|
||||
/// and the cancel the loop consumes — with what applying it can reach. A
|
||||
/// method that is not here reaches [`Reach::Any`]: the list says what is
|
||||
/// *proved* harmless, and a test holds it to the handler's arms
|
||||
/// (`tests/fast_actions_precondition.rs`), so a new arm cannot be let through
|
||||
/// by forgetting it.
|
||||
///
|
||||
/// What every notification does before its own arm is flush the dirty
|
||||
/// buffers (`handle_notification`) — the analysis of text already applied,
|
||||
/// under the settings in force, which is exactly what a request answered
|
||||
/// ahead does for its own buffer first. Past that:
|
||||
///
|
||||
/// * `didOpen`, `didChange`, `didSave`, `didClose` replace, dirty or drop the
|
||||
/// `Document` of the buffer they name and no other. What else they start —
|
||||
/// a widen, a rescan — moves the index and each buffer's overlay of it.
|
||||
/// * `didChangeWatchedFiles` moves the index, the include graph and the
|
||||
/// overlays (`reindex`, `reindex_watched`, `refresh_includes_naming`). A
|
||||
/// buffer's text is the client's whatever the disk says, so the event
|
||||
/// reaches no `Document` even when it names an open buffer's own file.
|
||||
/// * `$/cancelRequest` changes nothing the server holds.
|
||||
/// * `didChangeConfiguration` re-analyzes every open buffer the new
|
||||
/// `largeFile.threshold` classifies differently
|
||||
/// (`Server::reclassify_large_buffers`), and which buffers those are is not
|
||||
/// read off the wire here.
|
||||
/// * `didChangeWorkspaceFolders`, `didRenameFiles` and `didDeleteFiles` move
|
||||
/// the index only, like a watcher event. They are a user's occasional
|
||||
/// gesture, not what a rescan storm is made of, so holding an early answer
|
||||
/// behind one costs nothing and they are left unproved.
|
||||
pub(super) const REACH: [(&str, Reach); 10] = [
|
||||
(DidOpenTextDocument::METHOD, Reach::Named),
|
||||
(DidChangeTextDocument::METHOD, Reach::Named),
|
||||
(DidSaveTextDocument::METHOD, Reach::Named),
|
||||
(DidCloseTextDocument::METHOD, Reach::Named),
|
||||
(DidChangeWatchedFiles::METHOD, Reach::Nothing),
|
||||
(Cancel::METHOD, Reach::Nothing),
|
||||
(DidChangeConfiguration::METHOD, Reach::Any),
|
||||
(DidChangeWorkspaceFolders::METHOD, Reach::Any),
|
||||
(DidRenameFiles::METHOD, Reach::Any),
|
||||
(DidDeleteFiles::METHOD, Reach::Any),
|
||||
];
|
||||
|
||||
impl Server {
|
||||
/// Answer a request now, ahead of whatever holds the rest — `None` when
|
||||
/// it must wait like any other request.
|
||||
///
|
||||
/// **The precondition, whole.** For the buffer the request names:
|
||||
///
|
||||
/// * **(a) it is open**;
|
||||
/// * **(b) every older client message that can change what the handler
|
||||
/// reads has been applied** ([`Server::nothing_unapplied_for`]);
|
||||
/// * **(c) its analysis is current** for the text applied, under the
|
||||
/// settings in force. A dirty buffer is analyzed for a `same_file`
|
||||
/// request, that buffer alone, exactly as the flush would
|
||||
/// ([`Server::flush_buffer`]); for a colouring request it waits
|
||||
/// (`viewport.rs`, "A dirty buffer waits"). A clean one already is:
|
||||
/// `largeFile.threshold` is the one setting a `Document` reads, and the
|
||||
/// settings applier re-analyzes whatever a new value re-classifies
|
||||
/// (`Server::reclassify_large_buffers`);
|
||||
/// * **(d) no settings are awaited** ([`Server::settings_awaited`]) —
|
||||
/// they may re-classify any buffer the moment they land. What the
|
||||
/// startup held for them is offered here again when they do
|
||||
/// ([`Server::answer_held_ahead`]). The colours are exempt: a guess the
|
||||
/// refresh replaces, and a buffer that changes mode is refreshed;
|
||||
/// * **(e) the answer is the buffer's alone** — a colouring request by
|
||||
/// `viewport.rs`'s rule, any other by
|
||||
/// [`same_file::answered_by_the_buffer`], position by position.
|
||||
///
|
||||
/// Then the answer is the one a server taking one message at a time gives
|
||||
/// at this request's place in the client's stream — which is the claim
|
||||
/// `tests/fast_actions_bursts.rs` holds this function to.
|
||||
///
|
||||
/// `ahead` is what of its own burst is unapplied ahead of it and is not in
|
||||
/// `held`. A cancel the burst carries for it is honoured here,
|
||||
/// exactly as the loop would honour it.
|
||||
pub(super) fn answer_from_the_buffer(
|
||||
&mut self,
|
||||
request: &Request,
|
||||
ahead: &[Message],
|
||||
cancelled: &mut HashSet<RequestId>,
|
||||
) -> Option<Response> {
|
||||
let colours = match self.colours_may_go_ahead(&request.method) {
|
||||
Some(allowed) => allowed.then_some(true)?,
|
||||
None => same_file::METHODS.contains(&request.method.as_str()).then_some(false)?,
|
||||
};
|
||||
let uri = document_uri(&request.params)?;
|
||||
// (a) and (b).
|
||||
if !self.nothing_unapplied_for(&uri, ahead) {
|
||||
return None;
|
||||
}
|
||||
// (d), then (c), then (e).
|
||||
if !colours && self.settings_awaited() {
|
||||
return None;
|
||||
}
|
||||
if colours && self.is_dirty(&uri) {
|
||||
return None;
|
||||
}
|
||||
if !colours {
|
||||
self.flush_buffer(&uri);
|
||||
let doc = self.workspace.document(&uri)?;
|
||||
if !same_file::answered_by_the_buffer(doc, &request.method, &request.params) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if cancelled.remove(&request.id) {
|
||||
return Some(cancelled_response(request.id.clone()));
|
||||
}
|
||||
let started = self.timer();
|
||||
let unsettled = self.index_unsettled();
|
||||
let copy = Request::new(request.id.clone(), request.method.clone(), request.params.clone());
|
||||
let response = self.answer_flushed(copy);
|
||||
if colours {
|
||||
self.coloured_ahead(uri, &request.method, unsettled, &response);
|
||||
}
|
||||
self.timed(started, |took| {
|
||||
format!(
|
||||
"{} answered from the buffer ahead of a scan (held={}, settled={}) in {took}",
|
||||
request.method,
|
||||
self.held.len(),
|
||||
!unsettled
|
||||
)
|
||||
});
|
||||
Some(response)
|
||||
}
|
||||
|
||||
/// [`Server::answer_from_the_buffer`] for one message of a burst, the
|
||||
/// answer sent: whether it was a request the exemption took.
|
||||
pub(super) fn answered_ahead(
|
||||
&mut self,
|
||||
message: &Message,
|
||||
ahead: &[Message],
|
||||
cancelled: &mut HashSet<RequestId>,
|
||||
) -> Result<bool, Box<dyn Error + Sync + Send>> {
|
||||
let Message::Request(request) = message else { return Ok(false) };
|
||||
let Some(response) = self.answer_from_the_buffer(request, ahead, cancelled) else {
|
||||
return Ok(false);
|
||||
};
|
||||
#[cfg(test)]
|
||||
super::probe::went_ahead(&request.id);
|
||||
self.connection.sender.send(Message::Response(response))?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Move the rest of a burst into `rest`, behind a request that must wait
|
||||
/// — except a request the exemption can answer against everything ahead
|
||||
/// of it, which is answered now instead of being held.
|
||||
pub(super) fn set_aside(
|
||||
&mut self,
|
||||
rest: &mut Vec<Message>,
|
||||
behind: impl Iterator<Item = Message>,
|
||||
cancelled: &mut HashSet<RequestId>,
|
||||
) -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
for later in behind {
|
||||
if !self.answered_ahead(&later, rest, cancelled)? {
|
||||
rest.push(later);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Before `notification` is applied, answer the `same_file` requests
|
||||
/// behind it in its burst that need not wait for it. Returns the rest of
|
||||
/// the burst, those answers taken out, in order.
|
||||
///
|
||||
/// The precondition is [`Server::answer_from_the_buffer`]'s, unchanged:
|
||||
/// `notification` and whatever of the burst lies between it and the
|
||||
/// request are passed as what is unapplied ahead of the request, so the
|
||||
/// request goes only when clause (b) proves that none of them can change
|
||||
/// its buffer — a watcher event, another buffer's edit or save. Behind a
|
||||
/// settings push, or anything else [`REACH`] has no proof for, it stays
|
||||
/// where it is and is handled after the notification, in order.
|
||||
///
|
||||
/// What this buys: a request read in one burst with a rescan's trigger
|
||||
/// — the client wrote them together, or the server was busy when they
|
||||
/// arrived — is not carried through the whole rescan in the tail of the
|
||||
/// burst that started it, where no drain can reach it. A `didChange`
|
||||
/// starts nothing, so nothing is answered ahead of one.
|
||||
pub(super) fn answer_ahead_of(
|
||||
&mut self,
|
||||
notification: &Notification,
|
||||
rest: std::vec::IntoIter<Message>,
|
||||
cancelled: &mut HashSet<RequestId>,
|
||||
) -> Result<std::vec::IntoIter<Message>, Box<dyn Error + Sync + Send>> {
|
||||
let local = |m: &Message| matches!(m, Message::Request(r) if same_file::METHODS.contains(&r.method.as_str()));
|
||||
if notification.method == DidChangeTextDocument::METHOD
|
||||
|| !rest.as_slice().iter().any(local)
|
||||
{
|
||||
return Ok(rest);
|
||||
}
|
||||
// Everything unapplied in this burst is passed as what is ahead of
|
||||
// each request, so it is taken out of the count around this one.
|
||||
let around = self.behind;
|
||||
let rest: Vec<Message> = rest.collect();
|
||||
let in_rest = rest.iter().filter(|m| self.owes_a_state_change(m)).count();
|
||||
self.behind = around.saturating_sub(in_rest);
|
||||
let mut kept = vec![Message::Notification(notification.clone())];
|
||||
let mut answered = Ok(());
|
||||
for later in rest {
|
||||
match local(&later) {
|
||||
true => match self.answered_ahead(&later, &kept, cancelled) {
|
||||
Ok(true) => {}
|
||||
Ok(false) => kept.push(later),
|
||||
Err(gone) => {
|
||||
answered = Err(gone);
|
||||
kept.push(later);
|
||||
}
|
||||
},
|
||||
false => kept.push(later),
|
||||
}
|
||||
}
|
||||
self.behind = around;
|
||||
answered?;
|
||||
kept.remove(0);
|
||||
Ok(kept.into_iter())
|
||||
}
|
||||
|
||||
/// Apply one notification of a burst whose not-yet-handled tail is
|
||||
/// `rest`, returning that tail: a `didOpen` goes through
|
||||
/// [`Server::open_then_widen`], everything else straight to the handler.
|
||||
pub(super) fn apply_in_burst(
|
||||
&mut self,
|
||||
notification: Notification,
|
||||
rest: std::vec::IntoIter<Message>,
|
||||
cancelled: &mut HashSet<RequestId>,
|
||||
) -> Result<std::vec::IntoIter<Message>, Box<dyn Error + Sync + Send>> {
|
||||
if notification.method != DidOpenTextDocument::METHOD {
|
||||
self.notification(notification);
|
||||
return Ok(rest);
|
||||
}
|
||||
Ok(self.open_then_widen(notification, rest.collect(), cancelled)?.into_iter())
|
||||
}
|
||||
|
||||
/// Apply a `didOpen`, and when it widens the scope, answer the requests
|
||||
/// in `rest` — the burst behind it — that can go ahead **before** the
|
||||
/// widen runs, then run it. Returns what is left of `rest`, in order.
|
||||
///
|
||||
/// The buffer is applied by then and the answers need nothing from the
|
||||
/// index, so VS Code's `full`, which arrives in the same burst as its
|
||||
/// `didOpen`, colours at once instead of after the widen. Everything else
|
||||
/// in `rest` is untouched and runs after the widen exactly as before; the
|
||||
/// widen is still the effect of the applied `didOpen` and nothing else.
|
||||
fn open_then_widen(
|
||||
&mut self,
|
||||
notification: Notification,
|
||||
rest: Vec<Message>,
|
||||
cancelled: &mut HashSet<RequestId>,
|
||||
) -> Result<Vec<Message>, Box<dyn Error + Sync + Send>> {
|
||||
self.viewport.defer_widen = true;
|
||||
self.notification(notification);
|
||||
self.viewport.defer_widen = false;
|
||||
let Some(added) = self.viewport.owed_widen.take() else { return Ok(rest) };
|
||||
// `rest` is passed as what is ahead of each request, so it is taken
|
||||
// out of the count of unapplied notifications around this one.
|
||||
let around = self.behind;
|
||||
let in_rest = rest.iter().filter(|m| self.owes_a_state_change(m)).count();
|
||||
self.behind = around.saturating_sub(in_rest);
|
||||
self.viewport.widening = true;
|
||||
let mut kept = Vec::new();
|
||||
let answered = self.set_aside(&mut kept, rest.into_iter(), cancelled);
|
||||
self.behind = around;
|
||||
answered?;
|
||||
self.reindex_widened(added);
|
||||
Ok(kept)
|
||||
}
|
||||
|
||||
/// Once the settings have been applied: answer what staging held that its
|
||||
/// buffer now answers alone, and keep the rest held, in arrival order.
|
||||
///
|
||||
/// The same exemption the drains take, at the one moment the scan's first
|
||||
/// drain is not yet reachable: everything older than each held request is
|
||||
/// either applied or held ahead of it, which is what `set_aside` checks.
|
||||
pub(super) fn answer_held_ahead(&mut self) -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
let held = std::mem::take(&mut self.held);
|
||||
let mut cancelled = cancelled_in(&held);
|
||||
let mut kept = Vec::new();
|
||||
let answered = self.set_aside(&mut kept, held.into_iter(), &mut cancelled);
|
||||
self.held = kept;
|
||||
answered
|
||||
}
|
||||
|
||||
/// Between two files of a widen: answer the requests that have arrived
|
||||
/// and can be answered from their buffers, and hold everything else, in
|
||||
/// arrival order, behind whatever is already held.
|
||||
///
|
||||
/// Safe for the rest of the burst that carried the `didOpen`: it is older
|
||||
/// than anything arriving now, and while it holds a notification
|
||||
/// [`Server::behind`] is non-zero, which makes every buffer not current.
|
||||
pub(super) fn answer_ahead_mid_widen(&mut self) -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
let arrived: Vec<Message> = self.queue.try_iter().collect();
|
||||
if arrived.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut cancelled = cancelled_in(&arrived);
|
||||
let mut kept = Vec::new();
|
||||
self.set_aside(&mut kept, arrived.into_iter(), &mut cancelled)?;
|
||||
self.held.extend(kept);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Clauses (a) and (b) of [`Server::answer_from_the_buffer`]: whether
|
||||
/// `uri` is open and nothing older than the request being answered that
|
||||
/// can reach it is still unapplied.
|
||||
///
|
||||
/// Everything older is either applied or in one of three places
|
||||
/// (`docs/features/scan-ordering/README.md`): `held`; `ahead`, the part
|
||||
/// of the request's own burst that is unapplied in front of it — set
|
||||
/// aside, or about to be applied; and the tail of a burst whose message
|
||||
/// started the scan this request is answered inside. The first two are
|
||||
/// read message by message
|
||||
/// ([`Server::can_reach`]); the third is only a count
|
||||
/// ([`Server::behind`]), so any unapplied message in it is taken as
|
||||
/// reaching this buffer.
|
||||
fn nothing_unapplied_for(&self, uri: &Uri, ahead: &[Message]) -> bool {
|
||||
self.workspace.document(uri).is_some()
|
||||
&& self.behind == 0
|
||||
&& !self.held.iter().chain(ahead).any(|older| self.can_reach(older, uri))
|
||||
}
|
||||
|
||||
/// Whether applying `message` can change the `Document` of the buffer
|
||||
/// `uri` — the default for anything not proved otherwise.
|
||||
///
|
||||
/// A **request** changes no `Document`: the most one does on the way is
|
||||
/// the flush, the analysis of text already applied. A **response** does
|
||||
/// when it is the client's answer to a settings pull, which is applied as
|
||||
/// a settings push is; the server acts on no other answer in a way that
|
||||
/// touches a buffer (`Server::response`). A **notification** is read off
|
||||
/// [`REACH`]; one that should name a buffer and names none that parses is
|
||||
/// taken as naming this one.
|
||||
fn can_reach(&self, message: &Message, uri: &Uri) -> bool {
|
||||
let notification = match message {
|
||||
Message::Request(_) => return false,
|
||||
Message::Response(response) => {
|
||||
return match self.pending.get(&response.id) {
|
||||
Some(Pending::Configuration(_)) => true,
|
||||
Some(Pending::ApplyEdit(_)) | None => false,
|
||||
}
|
||||
}
|
||||
Message::Notification(notification) => notification,
|
||||
};
|
||||
match REACH.iter().find(|(method, _)| *method == notification.method) {
|
||||
Some((_, Reach::Nothing)) => false,
|
||||
Some((_, Reach::Named)) => {
|
||||
document_uri(¬ification.params).is_none_or(|named| named == *uri)
|
||||
}
|
||||
Some((_, Reach::Any)) | None => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Clause (d): whether settings the client has are still on their way —
|
||||
/// the startup's pull inside its wait ([`Server::staging`]), or a pull the
|
||||
/// client itself asked for by pushing nothing
|
||||
/// ([`Server::settings_announced`]). The startup's pull *after* its wait
|
||||
/// ran out is not: a client that never answers must not close this path
|
||||
/// for the session, and its late answer is applied as a push is.
|
||||
fn settings_awaited(&self) -> bool {
|
||||
self.staging || self.settings_announced.is_some()
|
||||
}
|
||||
|
||||
/// Whether `uri` has a change applied to its text and not yet analyzed.
|
||||
fn is_dirty(&self, uri: &Uri) -> bool {
|
||||
self.dirty.iter().any(|(pending, _)| pending == uri)
|
||||
}
|
||||
}
|
||||
@@ -4,20 +4,20 @@
|
||||
//! forwarder here moves them onto a queue of our own so that "everything the
|
||||
//! client has already sent" is a question with an answer. The rest of the
|
||||
//! file reads a burst without handling anything in it: which requests it
|
||||
//! cancels, which files it opens, and — for a `didOpen` — whether the index
|
||||
//! scope grew, stayed, or has to be rebuilt. The loop in `mod.rs` and the
|
||||
//! cancels and — for a `didOpen` — whether the index scope grew, stayed, or
|
||||
//! has to be rebuilt. (Which files a burst *opens* is not read here any more:
|
||||
//! a `didOpen` changes a scan's order when it is applied, never because a
|
||||
//! batch carries it — `docs/features/scan-ordering/README.md`.) The loop in `mod.rs` and the
|
||||
//! mid-scan drain in `index.rs` both read bursts through here, which is why
|
||||
//! this is its own file rather than part of either.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use lsp_server::{Connection, Message, RequestId, Response};
|
||||
use lsp_types::notification::{Cancel, DidOpenTextDocument, Notification as _};
|
||||
use lsp_types::notification::{Cancel, Notification as _};
|
||||
use lsp_types::request::{Request as _, Shutdown};
|
||||
use lsp_types::{CancelParams, NumberOrString};
|
||||
|
||||
use super::dispatch::document_uri;
|
||||
|
||||
/// Whether this message is the `shutdown` request. `lsp-server` keeps its own
|
||||
/// answer to that question private, so it is asked here by method name — the
|
||||
/// same name `handle_shutdown` matches on.
|
||||
@@ -167,22 +167,9 @@ pub(super) fn widen_of(before: &[std::path::PathBuf], after: &[std::path::PathBu
|
||||
Widen::Added(after.iter().filter(|dir| !before.contains(dir)).cloned().collect())
|
||||
}
|
||||
|
||||
/// The files a burst opened, in the order the client opened them.
|
||||
///
|
||||
/// Read off the raw messages rather than off the workspace afterwards,
|
||||
/// because the workspace holds its buffers in a `HashMap` and "which file did
|
||||
/// the user just open" is a question about order.
|
||||
pub(super) fn opened_in(batch: &[Message]) -> Vec<std::path::PathBuf> {
|
||||
batch
|
||||
.iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(notification)
|
||||
if notification.method == DidOpenTextDocument::METHOD =>
|
||||
{
|
||||
document_uri(¬ification.params)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.filter_map(|uri| crate::uri::uri_to_path(&uri))
|
||||
.collect()
|
||||
/// Whether a message changes what the server holds — any notification but a
|
||||
/// `$/cancelRequest`. These are the messages whose order is the order the
|
||||
/// client sent them in (`Server::must_hold`).
|
||||
pub(super) fn changes_state(message: &Message) -> bool {
|
||||
matches!(message, Message::Notification(n) if n.method != Cancel::METHOD)
|
||||
}
|
||||
@@ -50,9 +50,9 @@ impl Server {
|
||||
/// before this existed. No `scopeUri`: this server holds one set of
|
||||
/// settings for the whole session, not one per folder, so asking
|
||||
/// per-resource would be asking for answers it has nowhere to put.
|
||||
pub(super) fn request_configuration(&mut self) {
|
||||
pub(super) fn request_configuration(&mut self) -> Option<RequestId> {
|
||||
if !self.abilities.configuration {
|
||||
return;
|
||||
return None;
|
||||
}
|
||||
let params = ConfigurationParams {
|
||||
items: vec![ConfigurationItem {
|
||||
@@ -61,7 +61,8 @@ impl Server {
|
||||
}],
|
||||
};
|
||||
let id = self.send_request(WorkspaceConfiguration::METHOD, params);
|
||||
self.pending.insert(id, Pending::Configuration(std::time::Instant::now()));
|
||||
self.pending.insert(id.clone(), Pending::Configuration(std::time::Instant::now()));
|
||||
Some(id)
|
||||
}
|
||||
|
||||
/// Ask the client to watch the source files and the filelist for us,
|
||||
@@ -172,6 +173,9 @@ impl Server {
|
||||
/// those ids is ever in `pending`, so they all fall out here — in any
|
||||
/// arrival order, since the id is the whole of the lookup.
|
||||
pub(super) fn response(&mut self, response: Response) {
|
||||
if self.settings_announced.as_ref() == Some(&response.id) {
|
||||
self.settings_announced = None;
|
||||
}
|
||||
match self.pending.remove(&response.id) {
|
||||
Some(Pending::ApplyEdit(command)) => self.applied(command, response),
|
||||
Some(Pending::Configuration(asked)) => self.configured(asked, response),
|
||||
|
||||
@@ -52,15 +52,31 @@ impl Server {
|
||||
let started = self.timer();
|
||||
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.analyze_and_publish(uri, text);
|
||||
}
|
||||
self.timed(started, |took| {
|
||||
format!("flush of {buffers} dirty buffer{} took {took}", plural(buffers))
|
||||
});
|
||||
}
|
||||
|
||||
/// [`Server::flush_dirty`] for one buffer: analyze and republish `uri` if
|
||||
/// it is dirty, and leave every other dirty buffer, in its order, to the
|
||||
/// next flush. What a request answered from its buffer ahead of a scan
|
||||
/// does instead of flushing them all (`ahead.rs`).
|
||||
pub(super) fn flush_buffer(&mut self, uri: &Uri) {
|
||||
let Some(at) = self.dirty.iter().position(|(pending, _)| pending == uri) else { return };
|
||||
let (uri, text) = self.dirty.remove(at);
|
||||
self.analyze_and_publish(uri, text);
|
||||
}
|
||||
|
||||
/// One dirty buffer's share of a flush: its newest text analyzed, the
|
||||
/// connection being typed located, its diagnostics republished.
|
||||
pub(super) fn analyze_and_publish(&mut self, uri: Uri, text: String) {
|
||||
self.set_document(uri.clone(), text);
|
||||
self.workspace.locate_port_entry(&uri);
|
||||
crate::lint_trace::rebuild(crate::lint_trace::Rebuild::Publish, || self.publish(&uri));
|
||||
}
|
||||
|
||||
/// Say once, in the output channel, that a buffer is on the large-file
|
||||
/// fast path.
|
||||
///
|
||||
|
||||
@@ -44,9 +44,10 @@ use serde_json::Value;
|
||||
use super::client::ms;
|
||||
use super::Server;
|
||||
use crate::{
|
||||
code_action, completion, design_hierarchy, extract, file_ops, folding, format, hierarchy,
|
||||
hover, imports, includes, inlay, inline, inline_module, lens, linked, lint, lint_trace, nav,
|
||||
pairs, ports, rename, selection, signature, symbols, tokens, type_def, type_hierarchy,
|
||||
caret, code_action, completion, design_hierarchy, extract, file_ops, folding, format,
|
||||
hierarchy, hover, imports, includes, inlay, inline, inline_module, lens, linked, lint,
|
||||
lint_trace, nav, pairs, ports, rename, selection, signature, symbols, tokens, type_def,
|
||||
type_hierarchy,
|
||||
};
|
||||
|
||||
/// The requests whose empty answer may mean "this scan has not reached the
|
||||
@@ -166,6 +167,18 @@ impl Server {
|
||||
// burst is coalesced: the changes before this request all become one
|
||||
// `set_document` in `flush_dirty`.
|
||||
self.flush_dirty_traced();
|
||||
self.answer_flushed(request)
|
||||
}
|
||||
|
||||
/// [`Server::answer_request`] after the flush: the large-file gate, then
|
||||
/// the table.
|
||||
///
|
||||
/// Its own function for the one caller that must **not** flush — the
|
||||
/// viewport exemption, which answers a semantic-token request for a
|
||||
/// buffer that is not dirty while a scan holds everything else, and which
|
||||
/// must not analyze or publish any *other* buffer on the way
|
||||
/// (`viewport.rs`). Every other request goes through `answer_request`.
|
||||
pub(super) fn answer_flushed(&mut self, request: Request) -> Response {
|
||||
let id = request.id.clone();
|
||||
let method = request.method.clone();
|
||||
// The large-file fast path answers first, and for most methods it
|
||||
@@ -197,7 +210,7 @@ impl Server {
|
||||
HoverRequest::METHOD => decode(request).and_then(|p: HoverParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
self.offset(&uri, position)
|
||||
self.symbol_offset(&uri, position)
|
||||
.map(|offset| hover::hover(&self.workspace, &uri, offset))
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
}),
|
||||
@@ -205,7 +218,7 @@ impl Server {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
let locations = self
|
||||
.offset(&uri, position)
|
||||
.symbol_offset(&uri, position)
|
||||
.map(|offset| nav::definition(&self.workspace, &uri, offset))
|
||||
.unwrap_or_default();
|
||||
to_value(GotoDefinitionResponse::Array(locations))
|
||||
@@ -221,7 +234,7 @@ impl Server {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
let locations = self
|
||||
.offset(&uri, position)
|
||||
.symbol_offset(&uri, position)
|
||||
.map(|offset| type_def::type_definition(&self.workspace, &uri, offset))
|
||||
.unwrap_or_default();
|
||||
to_value(GotoTypeDefinitionResponse::Array(locations))
|
||||
@@ -255,7 +268,7 @@ impl Server {
|
||||
let at = p.text_document_position;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
let locations = self
|
||||
.offset(&uri, position)
|
||||
.symbol_offset(&uri, position)
|
||||
.map(|offset| nav::references(&self.workspace, &uri, offset, include))
|
||||
.unwrap_or_default();
|
||||
to_value(locations)
|
||||
@@ -271,7 +284,7 @@ impl Server {
|
||||
decode(request).and_then(|p: DocumentHighlightParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
let found = self.offset(&uri, position).and_then(|offset| {
|
||||
let found = self.symbol_offset(&uri, position).and_then(|offset| {
|
||||
let doc = self.workspace.document(&uri)?;
|
||||
pairs::highlights(doc, offset)
|
||||
.or_else(|| nav::document_highlights(doc, offset))
|
||||
@@ -444,7 +457,7 @@ impl Server {
|
||||
PrepareRenameRequest::METHOD => {
|
||||
decode(request).and_then(|at: TextDocumentPositionParams| {
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
let Some(offset) = self.offset(&uri, position) else {
|
||||
let Some(offset) = self.symbol_offset(&uri, position) else {
|
||||
return Ok(Value::Null);
|
||||
};
|
||||
match rename::prepare(&self.workspace, &uri, offset) {
|
||||
@@ -457,7 +470,7 @@ impl Server {
|
||||
let new_name = p.new_name;
|
||||
let at = p.text_document_position;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
let Some(offset) = self.offset(&uri, position) else {
|
||||
let Some(offset) = self.symbol_offset(&uri, position) else {
|
||||
return Ok(Value::Null);
|
||||
};
|
||||
// One `timing: rename trace …` line behind `--verbose`, and
|
||||
@@ -558,8 +571,19 @@ impl Server {
|
||||
Completion::METHOD => decode(request).and_then(|p: CompletionParams| {
|
||||
let at = p.text_document_position;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
completion::completions(&self.workspace, &uri, position, self.abilities.snippets)
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
let answer = completion::completions(
|
||||
&self.workspace,
|
||||
&uri,
|
||||
position,
|
||||
self.abilities.snippets,
|
||||
)
|
||||
.map_or(Ok(Value::Null), to_value)?;
|
||||
// The range every item replaces, said once for a client that
|
||||
// takes defaults — the same edits in half the bytes.
|
||||
Ok(match self.abilities.completion_item_defaults {
|
||||
true => completion::with_item_defaults(answer),
|
||||
false => answer,
|
||||
})
|
||||
}),
|
||||
// Ghost text. `null` for every position that is not one of the
|
||||
// two triggers, which is nearly all of them — the request arrives
|
||||
@@ -588,7 +612,7 @@ impl Server {
|
||||
decode(request).and_then(|p: CallHierarchyPrepareParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
self.offset(&uri, position)
|
||||
self.symbol_offset(&uri, position)
|
||||
.and_then(|offset| hierarchy::prepare(&self.workspace, &uri, offset))
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
})
|
||||
@@ -611,7 +635,7 @@ impl Server {
|
||||
decode(request).and_then(|p: TypeHierarchyPrepareParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
self.offset(&uri, position)
|
||||
self.symbol_offset(&uri, position)
|
||||
.and_then(|offset| type_hierarchy::prepare(&self.workspace, &uri, offset))
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
})
|
||||
@@ -660,6 +684,17 @@ impl Server {
|
||||
fn offset(&self, uri: &Uri, position: Position) -> Option<u32> {
|
||||
self.workspace.document(uri).map(|doc| doc.positions().offset(position))
|
||||
}
|
||||
|
||||
/// [`Server::offset`] for a request about the name under the cursor: a
|
||||
/// caret just past a name is on that name, as VS Code's own word rule
|
||||
/// says ([`caret::symbol_offset`]). Requests with a boundary rule of
|
||||
/// their own — completion, signature help, linked editing, on-type
|
||||
/// formatting — keep the caret as sent; the table is in
|
||||
/// `docs/features/scan-ordering/README.md`.
|
||||
fn symbol_offset(&self, uri: &Uri, position: Position) -> Option<u32> {
|
||||
let doc = self.workspace.document(uri)?;
|
||||
Some(caret::symbol_offset(&doc.text, doc.positions().offset(position)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a request could not be answered, in the protocol's own terms.
|
||||
|
||||
@@ -14,7 +14,6 @@ use std::path::Path;
|
||||
|
||||
use lsp_types::ProgressToken;
|
||||
|
||||
use super::batch::opened_in;
|
||||
use super::client::{notify_on, plural};
|
||||
use super::progress::IndexWatch;
|
||||
use super::{Server, INTERLEAVE_ABOVE};
|
||||
@@ -218,6 +217,12 @@ impl Server {
|
||||
self.rescan_wanted = true;
|
||||
return;
|
||||
}
|
||||
// Inside a burst, the widen waits until what can go ahead behind its
|
||||
// `didOpen` has been answered (`Server::open_then_widen`).
|
||||
if self.viewport.defers_widen(&added) {
|
||||
return;
|
||||
}
|
||||
self.viewport.widening = true;
|
||||
let started = self.timer();
|
||||
let since_start = self.since_start();
|
||||
if started.is_some() {
|
||||
@@ -236,10 +241,11 @@ impl Server {
|
||||
let mut scan =
|
||||
self.watching(bar.as_ref(), |ws, watch| ws.begin_widen(&added, watch, verbose));
|
||||
let total = scan.total();
|
||||
// No drain between the files: a widen is a rescan a message asked for,
|
||||
// and `must_wait` would hold every request queued behind it anyway. It
|
||||
// is also the point of the round that there is no longer a wait worth
|
||||
// interleaving — a widen indexes one folder, not the whole scope.
|
||||
// A widen is a rescan a message asked for, so every request queued
|
||||
// behind it waits for it — except what needs nothing from the index
|
||||
// (`ahead.rs`): between two files the queue is drained, the requests
|
||||
// that can be are answered from their buffers, and everything else is
|
||||
// held in arrival order exactly as `must_hold` would hold it.
|
||||
loop {
|
||||
let step = |workspace: &mut Workspace, watch: &mut dyn FnMut(IndexEvent)| {
|
||||
workspace.scan_step(&mut scan, watch)
|
||||
@@ -247,6 +253,11 @@ impl Server {
|
||||
if !self.watching(bar.as_ref(), step) {
|
||||
break;
|
||||
}
|
||||
if self.answer_ahead_mid_widen().is_err() {
|
||||
// The client has gone; nothing after this may speak to it.
|
||||
self.stopped = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
let (skipped, cached) = (scan.skipped(), scan.cached());
|
||||
let warnings = self.workspace.finish_scan(scan);
|
||||
@@ -258,6 +269,7 @@ impl Server {
|
||||
)
|
||||
});
|
||||
self.say_scan_trace(since_start);
|
||||
self.viewport.widening = false;
|
||||
self.refresh_code_lenses();
|
||||
self.hierarchy_index_changed();
|
||||
self.generation += 1;
|
||||
@@ -305,6 +317,7 @@ impl Server {
|
||||
self.scanning = false;
|
||||
// A neighbourhood can only be owed by a scan, and there is none now.
|
||||
self.head_owed = false;
|
||||
self.opened_mid_scan = false;
|
||||
self.answer_what_was_deferred();
|
||||
warnings
|
||||
}
|
||||
@@ -477,6 +490,8 @@ impl Server {
|
||||
while let Ok(message) = self.queue.try_recv() {
|
||||
arrived.push(message);
|
||||
}
|
||||
#[cfg(test)]
|
||||
super::probe::at_interleave_point(owed, &mut arrived);
|
||||
// A quiet scan pays nothing at all, and that is a promise: the cadence
|
||||
// is asked only when there is something for a publish to be *for*.
|
||||
if !owed && arrived.is_empty() && self.deferred.is_empty() {
|
||||
@@ -493,15 +508,22 @@ impl Server {
|
||||
if batch.is_empty() {
|
||||
return false;
|
||||
}
|
||||
// A `didOpen` in this burst names a folder the work list has not been
|
||||
// ordered around yet, so the requests behind it in the burst are owed
|
||||
// that ordering before they are answered — which is exactly what the
|
||||
// widen this `didOpen` used to trigger made them wait for. The flag is
|
||||
// set *before* the batch is applied, so `must_wait` holds them; it is
|
||||
// recomputed below once the new head segment is known.
|
||||
let opened = !opened_in(&batch).is_empty();
|
||||
self.head_owed |= opened;
|
||||
// A `didOpen` this burst *applies* names a folder the work list has
|
||||
// not been ordered around yet, so the requests behind it are owed that
|
||||
// ordering before they are answered — which is exactly what the widen
|
||||
// this `didOpen` used to trigger made them wait for. The `didOpen` arm
|
||||
// sets `head_owed` as it applies one, so `must_wait` holds what is
|
||||
// behind it; it is recomputed below once the new head is known.
|
||||
//
|
||||
// **Applied, not merely present.** Before 2026-11-19 the flag was read
|
||||
// off the batch before it was handled, so a `didOpen` the batch held
|
||||
// unapplied behind a request re-held that request, and the same batch
|
||||
// came back at every file — a five-minute startup scan on OpenTitan
|
||||
// (`docs/features/scan-ordering/README.md`, C). Only a message that
|
||||
// has been applied changes the scan's state, and each is applied once.
|
||||
self.opened_mid_scan = false;
|
||||
self.stopped = !matches!(self.process_batch(batch), Ok(false));
|
||||
let opened = std::mem::take(&mut self.opened_mid_scan);
|
||||
// The files the user has just opened, and the folders around them, are
|
||||
// what they are looking at, so they are indexed next rather than when
|
||||
// the alphabet reaches them — the open-first rule, for buffers opened
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
use lsp_types::request::{
|
||||
CodeActionRequest, DocumentLinkRequest, Formatting, GotoDefinition, HoverRequest,
|
||||
OnTypeFormatting, PrepareRenameRequest, RangeFormatting, References, Rename, Request as _,
|
||||
SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, WillSaveWaitUntil,
|
||||
SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, SemanticTokensRefresh,
|
||||
WillSaveWaitUntil,
|
||||
};
|
||||
use lsp_types::{GotoDefinitionResponse, Location, Position, Uri};
|
||||
use serde_json::Value;
|
||||
@@ -156,4 +157,42 @@ impl Server {
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Re-analyze every open buffer the large-file threshold now classifies
|
||||
/// differently from when it was analyzed — normal ↔ large — after the
|
||||
/// settings changed it from `before`; leave every other buffer alone.
|
||||
///
|
||||
/// The threshold is read where a `Document` is built, so without this a
|
||||
/// new value reached a buffer only at its next edit: one opened before
|
||||
/// the startup's settings answer kept the default's verdict, and a
|
||||
/// threshold changed mid-session did not move an open buffer at all
|
||||
/// (`docs/features/fast-actions/README.md`, R1). A flipped buffer goes
|
||||
/// through the flush's own path — analyzed, its connection located, its
|
||||
/// diagnostics republished once — and its colours are re-requested. A
|
||||
/// dirty buffer is skipped: its flush builds it under the new value
|
||||
/// anyway. Like an edit, this does not reindex: the index takes the new
|
||||
/// mode at the buffer's next save or rescan — and before the startup scan
|
||||
/// there is no index yet, so that scan reads every buffer in its settled
|
||||
/// mode. An unchanged threshold costs one comparison.
|
||||
pub(super) fn reclassify_large_buffers(&mut self, before: u64) {
|
||||
if self.workspace.client_settings().large_file_threshold == before {
|
||||
return;
|
||||
}
|
||||
let flipped: Vec<(Uri, String)> = self
|
||||
.workspace
|
||||
.open_documents()
|
||||
.filter(|(uri, _)| !self.dirty.iter().any(|(pending, _)| pending == *uri))
|
||||
.filter(|(_, doc)| self.workspace.is_large(&doc.text) != doc.large)
|
||||
.map(|(uri, doc)| (uri.clone(), doc.text.clone()))
|
||||
.collect();
|
||||
if flipped.is_empty() {
|
||||
return;
|
||||
}
|
||||
for (uri, text) in flipped {
|
||||
self.analyze_and_publish(uri, text);
|
||||
}
|
||||
if self.abilities.semantic_tokens_refresh {
|
||||
self.send_request(SemanticTokensRefresh::METHOD, ());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,11 @@
|
||||
//! * `formatting` — the five formatting entries and how a refusal is said;
|
||||
//! * `semantic_tokens` — the remembered answer a token delta is computed
|
||||
//! against;
|
||||
//! * `ahead` — the requests answered from their buffer alone while everything
|
||||
//! else waits for a scan: where in a burst they are taken out, and when the
|
||||
//! buffer is current (`crate::same_file` says which positions are local);
|
||||
//! * `viewport` — which colouring requests may go ahead, and the refresh that
|
||||
//! replaces those answers once the index has settled;
|
||||
//! * `diagnostics` — when a buffer is analyzed (the change debounce) and how
|
||||
//! what it says reaches the client, pushed or pulled;
|
||||
//! * `notification` — `handle_notification`, the table over notification
|
||||
@@ -46,9 +51,10 @@ use lsp_types::{SemanticToken, Uri};
|
||||
|
||||
use crate::state::Workspace;
|
||||
|
||||
use batch::{burst, cancelled_id, cancelled_in, cancelled_response};
|
||||
use batch::{burst, cancelled_id, cancelled_in, cancelled_response, changes_state};
|
||||
use dispatch::names_nowhere;
|
||||
|
||||
mod ahead;
|
||||
mod batch;
|
||||
mod client;
|
||||
mod diagnostics;
|
||||
@@ -57,11 +63,14 @@ mod formatting;
|
||||
mod index;
|
||||
mod large_file;
|
||||
mod notification;
|
||||
#[cfg(test)]
|
||||
mod probe;
|
||||
mod progress;
|
||||
mod semantic_tokens;
|
||||
mod startup;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod viewport;
|
||||
|
||||
/// What the client said it can do, read once at `initialize` because that is
|
||||
/// the only time those capabilities are sent.
|
||||
@@ -108,6 +117,12 @@ pub struct ClientAbilities {
|
||||
/// which error code declines `semanticTokens/full` on a large buffer —
|
||||
/// see `docs/features/large-file-mode/README.md`.
|
||||
pub token_server_cancel: bool,
|
||||
/// Whether the client accepts a `workspace/semanticTokens/refresh`
|
||||
/// (`workspace.semanticTokens.refreshSupport`). The refresh is what
|
||||
/// replaces the colours answered while the index was still being built
|
||||
/// (`docs/features/viewport-highlight/README.md`); a client that said
|
||||
/// nothing keeps them until its next edit asks again.
|
||||
pub semantic_tokens_refresh: bool,
|
||||
/// Whether the client hosts the custom lucisv hierarchy sidebar and wants
|
||||
/// a notification whenever the installed workspace index changes.
|
||||
pub hierarchy_view: bool,
|
||||
@@ -125,6 +140,12 @@ pub struct ClientAbilities {
|
||||
/// module it came from
|
||||
/// (`docs/features/extract-inline-module/README.md`).
|
||||
pub create_files: bool,
|
||||
/// Whether the client applies a completion list's `itemDefaults` —
|
||||
/// `editRange` and `insertTextFormat` both. Only then is the range every
|
||||
/// item replaces said once instead of per item; a client that said
|
||||
/// nothing gets every item whole, as before
|
||||
/// (`docs/features/fast-actions/README.md`).
|
||||
pub completion_item_defaults: bool,
|
||||
}
|
||||
|
||||
/// Everything the server owns.
|
||||
@@ -184,6 +205,10 @@ pub struct Server {
|
||||
/// client's `previousResultId` has to name the exact data it holds, and
|
||||
/// two buffers' answers are never comparable.
|
||||
token_results: u64,
|
||||
/// What the viewport exemption owes the client once the index settles:
|
||||
/// which buffers were coloured off an unsettled index, and which index
|
||||
/// revision the last refresh decision was taken at (`viewport.rs`).
|
||||
viewport: viewport::Viewport,
|
||||
/// Numbers the progress tokens the index rescans run under. One rescan is
|
||||
/// one token, and a token is never reused: a client keys the bar it is
|
||||
/// showing off it.
|
||||
@@ -222,6 +247,12 @@ pub struct Server {
|
||||
/// (`docs/features/perf5-p4/README.md`). False whenever no scan is
|
||||
/// running, and false during a scan with no neighbourhood to wait for.
|
||||
head_owed: bool,
|
||||
/// Whether a `didOpen` was **applied** while the scan now running had
|
||||
/// messages to answer — set where the `didOpen` is applied, and read by
|
||||
/// that scan's drain once the batch carrying it has been handled. Never
|
||||
/// read off a batch, which may hold the `didOpen` unapplied behind a
|
||||
/// request (`docs/features/scan-ordering/README.md`, C).
|
||||
opened_mid_scan: bool,
|
||||
/// A rescan asked for while a scan was running. Coalesced: any number of
|
||||
/// requests is one more scan when this one ends, whatever asked for them.
|
||||
rescan_wanted: bool,
|
||||
@@ -239,6 +270,21 @@ pub struct Server {
|
||||
/// [`Server::must_wait`] — this is the order contract, not a queue of its
|
||||
/// own.
|
||||
held: Vec<Message>,
|
||||
/// How many notifications older than the message being handled are still
|
||||
/// unapplied in the bursts it is nested inside — the tail of a burst
|
||||
/// whose message started a scan, while that scan answers newer ones. One
|
||||
/// of the two places an older notification can wait; `held` is the other
|
||||
/// ([`Server::must_hold`]). Cancels are not counted: they change nothing.
|
||||
/// The client's answer to a settings pull is: it is applied as a push is
|
||||
/// ([`Server::owes_a_state_change`]).
|
||||
behind: usize,
|
||||
/// The settings pull an **empty** `didChangeConfiguration` made the
|
||||
/// server send, until the client answers it. The client has said its
|
||||
/// settings changed and not yet what they are, so nothing is answered
|
||||
/// ahead of a scan from buffers those settings may re-classify
|
||||
/// (`ahead.rs`, clause (d)). Only the newest such pull is kept: its
|
||||
/// answer is the one that says what the settings are now.
|
||||
settings_announced: Option<RequestId>,
|
||||
/// Navigation requests a scan answered **empty** while it was still
|
||||
/// growing the index, to be asked again at its next publish.
|
||||
///
|
||||
@@ -355,6 +401,10 @@ impl Server {
|
||||
// arriving is released here, not only when the wait below times
|
||||
// out (`docs/features/port-entry-grace/README.md`).
|
||||
self.release_port_entries();
|
||||
// The index has settled and everything held behind it has been
|
||||
// answered: whatever was coloured off a half-built index is
|
||||
// re-requested now, at most once per index revision.
|
||||
self.refresh_tokens_if_stale();
|
||||
let message = match self.quiet_wait() {
|
||||
None => match self.queue.recv() {
|
||||
Ok(message) => message,
|
||||
@@ -398,52 +448,49 @@ impl Server {
|
||||
// The `$/cancelRequest`s this burst has already carried, kept only
|
||||
// long enough to put them back if a request behind them has to wait.
|
||||
let mut consumed_cancels: Vec<Message> = Vec::new();
|
||||
// The bursts this one is nested inside, and the notifications of them
|
||||
// still unapplied; restored on the way out (an `Err` is a client that
|
||||
// has gone, and nothing reads this after it).
|
||||
let outer = self.behind;
|
||||
let mut unapplied = batch.iter().filter(|m| self.owes_a_state_change(m)).count();
|
||||
let mut messages = batch.into_iter();
|
||||
while let Some(message) = messages.next() {
|
||||
// A request that must wait takes everything behind it with it, or
|
||||
// What is unapplied *older* than this message is only ever in the
|
||||
// bursts around this one — the rest of this burst is newer.
|
||||
self.behind = outer;
|
||||
// A message that must wait takes everything behind it with it, or
|
||||
// the burst's arrival order would not survive the wait —
|
||||
// `shutdown` included, because a request sent before a shutdown
|
||||
// is a request the client is still owed an answer to.
|
||||
if self.must_wait() && matches!(message, Message::Request(_)) {
|
||||
if self.must_hold(&message) {
|
||||
// The one exemption: a request whose buffer is current and
|
||||
// gives the answer alone — the colours, and whatever
|
||||
// `same_file` proves local — is answered from it now
|
||||
// (`ahead.rs` states what it reads and why that is safe).
|
||||
if self.answered_ahead(&message, &[], &mut cancelled)? {
|
||||
continue;
|
||||
}
|
||||
self.cancel_deferred(&message)?;
|
||||
self.say_held(&message);
|
||||
// The cancels this burst carried were consumed on the way
|
||||
// here, and `cancelled_in` runs again over the held batch — so
|
||||
// they go back in front of what they cancel rather than being
|
||||
// lost. A cancel naming nothing in the held batch is dropped
|
||||
// there exactly as it was dropped here.
|
||||
let mut rest: Vec<Message> = std::mem::take(&mut consumed_cancels);
|
||||
rest.push(message);
|
||||
rest.extend(messages);
|
||||
rest.extend(self.held.split_off(already_waiting));
|
||||
self.held.extend(rest);
|
||||
self.set_aside(&mut rest, messages, &mut cancelled)?;
|
||||
self.hold(rest, already_waiting);
|
||||
return Ok(false);
|
||||
}
|
||||
unapplied = unapplied.saturating_sub(usize::from(self.owes_a_state_change(&message)));
|
||||
// Whatever this message starts — a scan, whose drain answers the
|
||||
// client's newer messages — runs with the rest of this burst's
|
||||
// notifications still unapplied, and newer ones must not overtake
|
||||
// them.
|
||||
self.behind = outer + unapplied;
|
||||
match message {
|
||||
Message::Request(request) => {
|
||||
if self.connection.handle_shutdown(&request)? {
|
||||
self.behind = outer;
|
||||
return Ok(true);
|
||||
}
|
||||
// Removed as it is used: a second cancel for the same id
|
||||
// then finds nothing, and the set cannot outlive the burst.
|
||||
let response = if cancelled.remove(&request.id) {
|
||||
cancelled_response(request.id)
|
||||
} else {
|
||||
// A navigation request whose answer would be `[]` only
|
||||
// because the scan has not reached its target yet is
|
||||
// asked again at the next publish rather than answered
|
||||
// with nowhere ([`Server::deferred`]).
|
||||
let again = self.ask_again_if_empty(&request);
|
||||
let response = self.request(request);
|
||||
match again.filter(|_| names_nowhere(&response)) {
|
||||
Some(request) => {
|
||||
self.say_deferred(&request);
|
||||
self.deferred.push(Message::Request(request));
|
||||
continue;
|
||||
}
|
||||
None => response,
|
||||
}
|
||||
};
|
||||
self.connection.sender.send(Message::Response(response))?;
|
||||
self.answer_from_batch(request, &mut cancelled)?;
|
||||
}
|
||||
// The cancels themselves are consumed here — `notification`
|
||||
// has nothing to do with one, and everything it could do has
|
||||
@@ -459,13 +506,64 @@ impl Server {
|
||||
self.cancel_deferred(&cancel)?;
|
||||
consumed_cancels.push(cancel);
|
||||
}
|
||||
Message::Notification(notification) => self.notification(notification),
|
||||
// What behind it in this burst need not wait for it is
|
||||
// answered first; and an open can widen the scope, so what can
|
||||
// go ahead behind it is answered before the widen runs
|
||||
// (`ahead.rs`).
|
||||
Message::Notification(notification) => {
|
||||
messages = self.answer_ahead_of(¬ification, messages, &mut cancelled)?;
|
||||
messages = self.apply_in_burst(notification, messages, &mut cancelled)?;
|
||||
}
|
||||
Message::Response(response) => self.response(response),
|
||||
}
|
||||
}
|
||||
self.behind = outer;
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Answer one request a burst carried: `RequestCancelled` when the burst
|
||||
/// also carried its cancel, set aside for the next publish when it is a
|
||||
/// navigation request the scan has not reached the answer to yet, and
|
||||
/// computed otherwise.
|
||||
fn answer_from_batch(
|
||||
&mut self,
|
||||
request: lsp_server::Request,
|
||||
cancelled: &mut HashSet<RequestId>,
|
||||
) -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
// Removed as it is used: a second cancel for the same id then finds
|
||||
// nothing, and the set cannot outlive the burst.
|
||||
let response = if cancelled.remove(&request.id) {
|
||||
cancelled_response(request.id)
|
||||
} else {
|
||||
// A navigation request whose answer would be `[]` only because
|
||||
// the scan has not reached its target yet is asked again at the
|
||||
// next publish rather than answered with nowhere
|
||||
// ([`Server::deferred`]).
|
||||
let again = self.ask_again_if_empty(&request);
|
||||
let response = self.request(request);
|
||||
if let Some(request) = again.filter(|_| names_nowhere(&response)) {
|
||||
self.say_deferred(&request);
|
||||
self.deferred.push(Message::Request(request));
|
||||
return Ok(());
|
||||
}
|
||||
response
|
||||
};
|
||||
self.connection.sender.send(Message::Response(response))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Put `rest` — the cancels the burst already carried, the message that
|
||||
/// must wait, and the rest of its burst, in that order — into `held`: in
|
||||
/// front of whatever a scan this burst started has held since
|
||||
/// `already_waiting`, behind everything older. The cancels go back in
|
||||
/// front of what they cancel because `cancelled_in` runs again over the
|
||||
/// held batch; one naming nothing in it is dropped there, as it would
|
||||
/// have been here.
|
||||
fn hold(&mut self, mut rest: Vec<Message>, already_waiting: usize) {
|
||||
rest.extend(self.held.split_off(already_waiting));
|
||||
self.held.extend(rest);
|
||||
}
|
||||
|
||||
/// Honour a `$/cancelRequest` naming a request in [`Server::deferred`]:
|
||||
/// take it out and answer it cancelled. A cancel naming anything else is
|
||||
/// left to the batch's own rule.
|
||||
@@ -528,6 +626,68 @@ impl Server {
|
||||
|| self.head_owed
|
||||
}
|
||||
|
||||
/// Whether `message`, reaching `process_batch` right now, must be held
|
||||
/// instead of handled.
|
||||
///
|
||||
/// **No notification overtakes an older notification.** Only a
|
||||
/// notification changes what the server holds — a buffer's text, which
|
||||
/// buffers are open, the settings, the folders, what is on disk — so the
|
||||
/// order those are applied in is the order they were sent in, and nothing
|
||||
/// a request is later answered against can be a state the client never
|
||||
/// had. A notification waits while an older one is unapplied: in `held`,
|
||||
/// or in the tail of a burst whose message started the scan now draining
|
||||
/// ([`Server::behind`]). Before 2026-11-19 a `didChange` drained mid-scan
|
||||
/// was applied ahead of an older `didChange` still waiting, and an
|
||||
/// incremental edit landed on the wrong text
|
||||
/// (`docs/features/scan-ordering/README.md`, B).
|
||||
///
|
||||
/// **Not "no notification overtakes a request".** A request held by the
|
||||
/// contract above is answered against whatever was applied by the time
|
||||
/// it is replayed — as every request answered late always was — and a
|
||||
/// notification behind it with nothing older unapplied is applied at
|
||||
/// once. Holding it too would cost the startup its first `didOpen`
|
||||
/// (QA-3) and buy no state the client could see.
|
||||
///
|
||||
/// A **cancel** changes nothing the server holds, so it never makes a
|
||||
/// notification wait; it waits itself whenever anything is held, so that
|
||||
/// one naming a held request is replayed beside it and honoured. A
|
||||
/// **response** is never held: it answers a request the server made, and
|
||||
/// no ordering promise ties it to the editor's stream
|
||||
/// (`take_the_answer_out_of_held` in `startup.rs` makes the same
|
||||
/// argument) — with one exception. The client's **answer to a settings
|
||||
/// pull** is applied as a push is, so outside the startup's wait it is a
|
||||
/// state change like any notification
|
||||
/// ([`Server::owes_a_state_change`]): it waits behind an older
|
||||
/// unapplied one, and a newer one waits behind it. Before
|
||||
/// `fast-actions`' escalation round it was applied the moment it was
|
||||
/// read, ahead of an older push or edit a rescan was holding, and a
|
||||
/// newer push was applied ahead of one held — either way the server
|
||||
/// ended, or answered, in a state the client never had.
|
||||
fn must_hold(&self, message: &Message) -> bool {
|
||||
match message {
|
||||
Message::Request(_) => self.must_wait(),
|
||||
Message::Notification(_) if !changes_state(message) => !self.held.is_empty(),
|
||||
_ if self.owes_a_state_change(message) => {
|
||||
self.behind > 0 || self.held.iter().any(|older| self.owes_a_state_change(older))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `message`, still unapplied, is a state change the messages
|
||||
/// behind it are owed: any notification but a cancel
|
||||
/// ([`changes_state`]), and the client's answer to a settings pull —
|
||||
/// the one response the server applies as it applies a notification
|
||||
/// (`configured` → `apply_settings`). What [`Server::behind`] counts.
|
||||
fn owes_a_state_change(&self, message: &Message) -> bool {
|
||||
match message {
|
||||
Message::Response(response) => {
|
||||
matches!(self.pending.get(&response.id), Some(Pending::Configuration(_)))
|
||||
}
|
||||
_ => changes_state(message),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a scan is running or already owed — the two states in which a
|
||||
/// rescan trigger records that one more scan is wanted instead of running
|
||||
/// one itself.
|
||||
|
||||
@@ -96,6 +96,14 @@ impl Server {
|
||||
// rungs, which an open buffer cannot widen.
|
||||
let before = self.workspace.scope_dirs();
|
||||
self.set_document(uri.clone(), p.text_document.text);
|
||||
// Mid-scan, the work list is re-ordered round this buffer
|
||||
// once the batch carrying it is handled, and what is behind
|
||||
// it in that batch waits for the new order
|
||||
// (`Server::answer_what_is_waiting`).
|
||||
if self.scanning {
|
||||
self.head_owed = true;
|
||||
self.opened_mid_scan = true;
|
||||
}
|
||||
match widen_of(&before, &self.workspace.scope_dirs()) {
|
||||
Widen::Nothing => self.publish(&uri),
|
||||
Widen::Added(dirs) => self.reindex_widened(dirs),
|
||||
@@ -225,7 +233,9 @@ impl Server {
|
||||
DidChangeConfiguration::METHOD => {
|
||||
if let Ok(p) = extract::<DidChangeConfigurationParams>(notification) {
|
||||
if settings::says_nothing(&p.settings) && self.abilities.configuration {
|
||||
self.request_configuration();
|
||||
// Until that answer lands the settings in force are
|
||||
// known to be stale (`ahead.rs`, clause (d)).
|
||||
self.settings_announced = self.request_configuration();
|
||||
return;
|
||||
}
|
||||
self.apply_settings(settings::from_payload(&p.settings));
|
||||
@@ -337,7 +347,12 @@ impl Server {
|
||||
// Only `exclude` and `filelist` change which files exist as far as
|
||||
// this server is concerned; the other settings are read afresh by the
|
||||
// next request that wants them and need no invalidation.
|
||||
if self.workspace.set_client_settings(settings) {
|
||||
let threshold = self.workspace.client_settings().large_file_threshold;
|
||||
let rescan = self.workspace.set_client_settings(settings);
|
||||
// Before the rescan, so the index takes each buffer in the mode the
|
||||
// new threshold gives it.
|
||||
self.reclassify_large_buffers(threshold);
|
||||
if rescan {
|
||||
self.reindex();
|
||||
} else if self.lint_selection() != linted {
|
||||
// `lucisv.lint.select`/`ignore`, the class switches, the per-rule
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
//! A test's hand on the mid-scan drain: what the client "sends" at each
|
||||
//! interleave point, and how often a scan handed back what it was holding.
|
||||
//!
|
||||
//! Test-only. The real transport cannot be timed against a scan's files —
|
||||
//! the forwarder thread delivers whenever it likes — so a test that needs a
|
||||
//! burst to land *at the third file* scripts it here, and the drain appends it
|
||||
//! to what `try_recv` found, exactly where a real arrival would be. Thread
|
||||
//! local because every test drives its server on its own thread.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use lsp_server::{Message, RequestId};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Probe {
|
||||
/// Bursts to deliver, one per interleave point, oldest first.
|
||||
arrivals: VecDeque<Vec<Message>>,
|
||||
/// Interleave points reached since the last [`take_counts`].
|
||||
points: usize,
|
||||
/// How many of those handed messages the scan had been holding back to
|
||||
/// `process_batch` — what loops when a held batch is re-held at every file.
|
||||
handed_back: usize,
|
||||
/// How many scripted bursts a scan received.
|
||||
delivered: usize,
|
||||
/// The requests answered ahead of whatever held the rest (`ahead.rs`)
|
||||
/// since the last [`take_ahead`], in the order they were answered.
|
||||
ahead: Vec<RequestId>,
|
||||
}
|
||||
|
||||
/// What [`take_counts`] reports.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(super) struct Counts {
|
||||
/// Interleave points reached.
|
||||
pub(super) points: usize,
|
||||
/// Held batches handed back to `process_batch`.
|
||||
pub(super) handed_back: usize,
|
||||
/// Scripted bursts delivered mid-scan.
|
||||
pub(super) delivered: usize,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static PROBE: RefCell<Probe> = RefCell::default();
|
||||
}
|
||||
|
||||
/// Script `bursts` to arrive at the next interleave points, one each, behind
|
||||
/// anything already scripted.
|
||||
pub(super) fn script(bursts: impl IntoIterator<Item = Vec<Message>>) {
|
||||
PROBE.with(|probe| probe.borrow_mut().arrivals.extend(bursts));
|
||||
}
|
||||
|
||||
/// What is still scripted and has not arrived — the bursts a scan ended
|
||||
/// before reaching, which the test then delivers as `run` would.
|
||||
pub(super) fn unarrived() -> Vec<Vec<Message>> {
|
||||
PROBE.with(|probe| probe.borrow_mut().arrivals.drain(..).collect())
|
||||
}
|
||||
|
||||
/// What the scans did since the last call.
|
||||
pub(super) fn take_counts() -> Counts {
|
||||
PROBE.with(|probe| {
|
||||
let mut probe = probe.borrow_mut();
|
||||
Counts {
|
||||
points: std::mem::take(&mut probe.points),
|
||||
handed_back: std::mem::take(&mut probe.handed_back),
|
||||
delivered: std::mem::take(&mut probe.delivered),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Called by the drain at every interleave point: count it, and deliver the
|
||||
/// next scripted burst behind whatever the transport delivered.
|
||||
pub(super) fn at_interleave_point(handed_back: bool, arrived: &mut Vec<Message>) {
|
||||
PROBE.with(|probe| {
|
||||
let mut probe = probe.borrow_mut();
|
||||
probe.points += 1;
|
||||
probe.handed_back += usize::from(handed_back);
|
||||
if let Some(burst) = probe.arrivals.pop_front() {
|
||||
probe.delivered += 1;
|
||||
arrived.extend(burst);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Called where a request is answered ahead of what holds the rest.
|
||||
pub(super) fn went_ahead(id: &RequestId) {
|
||||
PROBE.with(|probe| probe.borrow_mut().ahead.push(id.clone()));
|
||||
}
|
||||
|
||||
/// The requests answered ahead since the last call — what a test compares
|
||||
/// with the answer a server taking one message at a time gives.
|
||||
pub(super) fn take_ahead() -> Vec<RequestId> {
|
||||
PROBE.with(|probe| std::mem::take(&mut probe.borrow_mut().ahead))
|
||||
}
|
||||
@@ -52,6 +52,10 @@ impl Server {
|
||||
/// is computed against. One buffer holds one answer: a client that asks
|
||||
/// again has moved on from the previous one.
|
||||
fn remember_tokens(&mut self, uri: &Uri, data: Vec<SemanticToken>) -> String {
|
||||
// A whole answer supersedes any viewport the client was painted with,
|
||||
// and it is remembered, so the refresh check compares *it* instead.
|
||||
let unsettled = self.index_unsettled();
|
||||
self.viewport.answered_whole(uri, unsettled);
|
||||
self.token_results += 1;
|
||||
let result_id = self.token_results.to_string();
|
||||
self.tokens.insert(uri.clone(), TokenAnswer { result_id: result_id.clone(), data });
|
||||
|
||||
@@ -158,16 +158,20 @@ impl Server {
|
||||
hierarchy_revision: 0,
|
||||
tokens: HashMap::new(),
|
||||
token_results: 0,
|
||||
viewport: Default::default(),
|
||||
indexings: 0,
|
||||
dirty: Vec::new(),
|
||||
queue,
|
||||
scanning: false,
|
||||
head_owed: false,
|
||||
opened_mid_scan: false,
|
||||
staging: false,
|
||||
rescan_wanted: false,
|
||||
answering_a_rescan: false,
|
||||
stopped: false,
|
||||
held: Vec::new(),
|
||||
behind: 0,
|
||||
settings_announced: None,
|
||||
deferred: Vec::new(),
|
||||
verbose,
|
||||
born: Instant::now(),
|
||||
@@ -253,7 +257,7 @@ impl Server {
|
||||
return;
|
||||
}
|
||||
self.staging = true;
|
||||
self.request_configuration();
|
||||
let _ = self.request_configuration();
|
||||
self.await_configuration(wait);
|
||||
// Inside the staging window, because it is the same window: every
|
||||
// request is still held, and the scan has still not begun.
|
||||
@@ -262,6 +266,12 @@ impl Server {
|
||||
}
|
||||
self.staging = false;
|
||||
self.rescan_wanted = false;
|
||||
// The settings have landed and every buffer is classified by them:
|
||||
// what its buffer alone answers is answered now, not after the head
|
||||
// phase of the scan about to run (`ahead.rs`).
|
||||
if !self.stopped && self.answer_held_ahead().is_err() {
|
||||
self.stopped = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait a bounded moment for the editor's first `didOpen`, when knowing
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
//! A caret just past a name is on that name, for every request about the
|
||||
//! symbol under the cursor (`docs/features/scan-ordering/README.md`, A1).
|
||||
//!
|
||||
//! The owner's report: Find All References said "No references found" for a
|
||||
//! port, and worked again after clicking away and back. A double-click, a
|
||||
//! click on the right half of the last letter, or a row of lucisv's own
|
||||
//! References view leaves the caret *after* the name; spans are
|
||||
//! end-exclusive, so the request used to ask about the next character.
|
||||
|
||||
use super::*;
|
||||
|
||||
const SOURCE: &str = "\
|
||||
module sub (input logic clk);
|
||||
endmodule
|
||||
module top;
|
||||
logic clk;
|
||||
sub u_sub (.clk(clk));
|
||||
typedef logic [3:0] nib_t;
|
||||
nib_t n;
|
||||
assign n = 4'd1;
|
||||
endmodule
|
||||
class base;
|
||||
endclass
|
||||
class child extends base;
|
||||
endclass
|
||||
";
|
||||
|
||||
/// A session with [`SOURCE`] open, and its uri.
|
||||
fn opened(tag: &str) -> (Tree, Session, Uri) {
|
||||
let tree = Tree::new(tag);
|
||||
tree.write("top.sv", SOURCE);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("top.sv"), SOURCE);
|
||||
let _ = session.drain();
|
||||
(tree, session, uri)
|
||||
}
|
||||
|
||||
/// The params every position request below sends, plus what `method` adds.
|
||||
fn at(method: &str, uri: &Uri, line: u32, character: u32) -> Value {
|
||||
let mut params = serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": line, "character": character },
|
||||
});
|
||||
if method == References::METHOD {
|
||||
params["context"] = serde_json::json!({ "includeDeclaration": true });
|
||||
}
|
||||
if method == Rename::METHOD {
|
||||
params["newName"] = serde_json::json!("renamed");
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
/// The answer, or the error's message — a declined rename is an answer too.
|
||||
fn answer(session: &mut Session, method: &str, params: Value) -> Value {
|
||||
match session.request(method, params).response_result {
|
||||
Ok(value) => value,
|
||||
Err(error) => Value::String(error.message),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an answer says nothing: `null`, `[]`, or a refusal.
|
||||
fn says_nothing(value: &Value) -> bool {
|
||||
value.is_null() || value.as_array().is_some_and(Vec::is_empty) || value.is_string()
|
||||
}
|
||||
|
||||
/// For `name` on `line`, the answer at the name's first column, just past
|
||||
/// its last character, and one column further right.
|
||||
fn around(session: &mut Session, uri: &Uri, method: &str, line: u32, name: &str) -> [Value; 3] {
|
||||
let text = SOURCE.lines().nth(line as usize).expect("the line");
|
||||
let start = find_word(text, name) as u32;
|
||||
let end = start + name.len() as u32;
|
||||
[start, end, end + 1].map(|column| answer(session, method, at(method, uri, line, column)))
|
||||
}
|
||||
|
||||
/// The byte column of `name` as a whole word on `text`.
|
||||
fn find_word(text: &str, name: &str) -> usize {
|
||||
let is_name = |c: char| c.is_ascii_alphanumeric() || c == '_';
|
||||
text.match_indices(name)
|
||||
.find(|(at, _)| {
|
||||
let before = text[..*at].chars().next_back().is_none_or(|c| !is_name(c));
|
||||
let after = text[at + name.len()..].chars().next().is_none_or(|c| !is_name(c));
|
||||
before && after
|
||||
})
|
||||
.map(|(at, _)| at)
|
||||
.expect("the name on its line")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_symbol_request_answers_the_same_just_past_a_name_as_at_its_start() {
|
||||
let (_tree, mut session, uri) = opened("caretend");
|
||||
// (method, line, name) — each followed by a character that is not part
|
||||
// of a name, so one column further right answers nothing. The two
|
||||
// hierarchy prepares are the exception: they answer for the whole
|
||||
// instantiation or declaration, so one further right is still the name.
|
||||
let cases = [
|
||||
(References::METHOD, 3, "clk"),
|
||||
(GotoDefinition::METHOD, 7, "n"),
|
||||
(HoverRequest::METHOD, 3, "clk"),
|
||||
(DocumentHighlightRequest::METHOD, 3, "clk"),
|
||||
(PrepareRenameRequest::METHOD, 3, "clk"),
|
||||
(Rename::METHOD, 3, "clk"),
|
||||
(GotoTypeDefinition::METHOD, 7, "n"),
|
||||
(CallHierarchyPrepare::METHOD, 4, "sub"),
|
||||
(TypeHierarchyPrepare::METHOD, 9, "base"),
|
||||
];
|
||||
for (method, line, name) in cases {
|
||||
let [start, end, beyond] = around(&mut session, &uri, method, line, name);
|
||||
assert!(!says_nothing(&start), "{method} at the start of {name} answers: {start}");
|
||||
assert_eq!(end, start, "{method} just past {name} answers as at its start");
|
||||
if ![CallHierarchyPrepare::METHOD, TypeHierarchyPrepare::METHOD].contains(&method) {
|
||||
assert!(says_nothing(&beyond), "{method} one further right: nothing, got {beyond}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caret_after_a_dot_is_on_the_member_and_before_it_on_the_instance() {
|
||||
// `u_sub.clk` is not in the fixture, but `.clk(` is: the caret between
|
||||
// `.` and `clk` is on `clk`, and just past `clk` (before `(`) too.
|
||||
let (_tree, mut session, uri) = opened("caretdot");
|
||||
let text = SOURCE.lines().nth(4).expect("line 4");
|
||||
let port = find_word(text, "clk") as u32;
|
||||
let refs = |s: &mut Session, column| {
|
||||
answer(s, References::METHOD, at(References::METHOD, &uri, 4, column))
|
||||
};
|
||||
let on_port = refs(&mut session, port);
|
||||
assert!(!says_nothing(&on_port));
|
||||
assert_eq!(refs(&mut session, port + 3), on_port, "before the paren: the port");
|
||||
let signal = refs(&mut session, port + 4);
|
||||
assert!(!says_nothing(&signal), "after the paren: the signal");
|
||||
assert_ne!(signal, on_port, "the signal's references are not the port's");
|
||||
assert_eq!(refs(&mut session, port + 7), signal, "before the closing paren: the signal");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_column_past_a_name_is_counted_in_utf16_after_non_ascii_text() {
|
||||
// `é` is two bytes and one UTF-16 unit: the caret arrives in units, is
|
||||
// converted to a byte offset, and only then moved back one byte.
|
||||
let text = "module m;\n /* é ü */ logic tx;\n assign tx = 1'b0;\nendmodule\n";
|
||||
let tree = Tree::new("caretutf16");
|
||||
tree.write("m.sv", text);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), text);
|
||||
let line = text.lines().nth(1).expect("line 1");
|
||||
let start = line[..line.find("tx").expect("tx")].encode_utf16().count() as u32;
|
||||
let refs = |s: &mut Session, column| {
|
||||
answer(s, References::METHOD, at(References::METHOD, &uri, 1, column))
|
||||
};
|
||||
let at_start = refs(&mut session, start);
|
||||
assert_eq!(at_start.as_array().map(Vec::len), Some(2), "the declaration and the use");
|
||||
assert_eq!(refs(&mut session, start + 2), at_start, "just past `tx`, in UTF-16 units");
|
||||
assert!(says_nothing(&refs(&mut session, start + 3)), "past the `;`");
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
//! Same file first, on the wire: each claim of `ahead.rs` about a request
|
||||
//! `same_file` proves local is one test. It goes ahead of what a scan holds;
|
||||
//! a cross-file one at the same moment waits, in order; a dirty buffer is
|
||||
//! analyzed for it — that buffer alone; a cancel is honoured. (When it must
|
||||
//! wait instead is `fast_actions_precondition.rs`, clause by clause.)
|
||||
|
||||
use lsp_types::notification::Cancel;
|
||||
|
||||
use super::*;
|
||||
|
||||
const PKG: &str = "package p;\n localparam int W = 4;\nendpackage\n";
|
||||
const TOP: &str = "module top;\n import p::*;\n logic sig;\n assign sig = W;\nendmodule\n";
|
||||
|
||||
/// A session over a package and a module that imports it, `top.sv` open.
|
||||
fn opened(name: &str) -> (Tree, Session, Uri) {
|
||||
let tree = Tree::new(name);
|
||||
tree.write("p.sv", PKG);
|
||||
tree.write("top.sv", TOP);
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
let uri = session.open(&tree.path.join("top.sv"), TOP);
|
||||
session.drain();
|
||||
(tree, session, uri)
|
||||
}
|
||||
|
||||
fn ask(id: &str, method: &str, params: Value) -> Message {
|
||||
Message::Request(lsp_server::Request::new(
|
||||
RequestId::from(id.to_string()),
|
||||
method.to_string(),
|
||||
params,
|
||||
))
|
||||
}
|
||||
|
||||
/// A hover at the first `needle` in `text`, `skip` bytes in.
|
||||
fn hover_at(id: &str, uri: &Uri, text: &str, needle: &str) -> Message {
|
||||
let offset = text.find(needle).expect("needle");
|
||||
let line = text[..offset].matches('\n').count();
|
||||
let column = offset - text[..offset].rfind('\n').map_or(0, |at| at + 1);
|
||||
ask(
|
||||
id,
|
||||
HoverRequest::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri },
|
||||
"position": { "line": line, "character": column } }),
|
||||
)
|
||||
}
|
||||
|
||||
/// A request about `uri` no buffer answers alone.
|
||||
fn lens(id: &str, uri: &Uri) -> Message {
|
||||
ask(id, CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }))
|
||||
}
|
||||
|
||||
fn rid(id: &str) -> RequestId {
|
||||
RequestId::from(id.to_string())
|
||||
}
|
||||
|
||||
/// One burst through the loop body with a rescan pretended to be running.
|
||||
fn mid_scan(session: &mut Session, burst: Vec<Message>) {
|
||||
session.server.scanning = true;
|
||||
session.server.answering_a_rescan = true;
|
||||
session.batch(burst);
|
||||
session.server.scanning = false;
|
||||
session.server.answering_a_rescan = false;
|
||||
}
|
||||
|
||||
fn answered(session: &Session) -> Vec<RequestId> {
|
||||
session.answers().into_iter().map(|r| r.id).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_local_hover_goes_ahead_and_a_cross_file_one_waits_in_order() {
|
||||
let (_tree, mut session, uri) = opened("fa_ahead");
|
||||
mid_scan(
|
||||
&mut session,
|
||||
vec![
|
||||
lens("l", &uri),
|
||||
hover_at("cross", &uri, TOP, "W;"),
|
||||
hover_at("local", &uri, TOP, "sig = W"),
|
||||
],
|
||||
);
|
||||
assert_eq!(answered(&session), vec![rid("local")], "the local hover alone goes ahead");
|
||||
let held: Vec<RequestId> = session
|
||||
.server
|
||||
.held
|
||||
.iter()
|
||||
.filter_map(|m| match m {
|
||||
Message::Request(r) => Some(r.id.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(held, vec![rid("l"), rid("cross")], "the rest waits, in arrival order");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_early_answer_is_the_answer_given_once_nothing_waits() {
|
||||
let (_tree, mut session, uri) = opened("fa_same");
|
||||
mid_scan(&mut session, vec![lens("l", &uri), hover_at("early", &uri, TOP, "sig = W")]);
|
||||
let early = session.answers();
|
||||
session.server.held.clear();
|
||||
let settled = session.batch(vec![hover_at("settled", &uri, TOP, "sig = W")]);
|
||||
assert!(!settled, "no shutdown");
|
||||
let settled = session.answers();
|
||||
assert_eq!(early.len(), 1);
|
||||
assert_eq!(
|
||||
format!("{:?}", early[0].response_result),
|
||||
format!("{:?}", settled[0].response_result)
|
||||
);
|
||||
assert!(
|
||||
early[0].response_result.as_ref().is_ok_and(|r| !r.is_null()),
|
||||
"a real card: {early:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dirty_buffer_is_analyzed_for_it_and_no_other_dirty_buffer_is() {
|
||||
let (tree, mut session, uri) = opened("fa_dirty");
|
||||
tree.write("other.sv", "module other;\nendmodule\n");
|
||||
let other = session.open(&tree.path.join("other.sv"), "module other;\nendmodule\n");
|
||||
session.drain();
|
||||
let edited = TOP.replace("logic sig;", "logic sig;\n logic fresh;");
|
||||
let other_edit = "module other;\n logic o;\nendmodule\n";
|
||||
session.batch(vec![changed(&other, 2, other_edit), changed(&uri, 2, &edited)]);
|
||||
assert_eq!(session.server.dirty.len(), 2, "premise: both buffers are dirty");
|
||||
mid_scan(&mut session, vec![lens("l", &uri), hover_at("h", &uri, &edited, "fresh")]);
|
||||
let answers = session.answers();
|
||||
assert_eq!(answers.len(), 1, "the hover on the new declaration goes ahead");
|
||||
let card = answers[0].response_result.as_ref().expect("a result").to_string();
|
||||
assert!(card.contains("fresh"), "answered from the newest text: {card}");
|
||||
let still: Vec<&Uri> = session.server.dirty.iter().map(|(u, _)| u).collect();
|
||||
assert_eq!(still, vec![&other], "the other buffer waits for the next flush");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_held_ahead_of_it_holds_it_too() {
|
||||
let (_tree, mut session, uri) = opened("fa_heldchange");
|
||||
let edited = TOP.replace("logic sig;", "logic sig2;");
|
||||
// The lens is held, and with it the change behind it; the hover is
|
||||
// behind the change, so its buffer is not current.
|
||||
mid_scan(
|
||||
&mut session,
|
||||
vec![lens("l", &uri), changed(&uri, 2, &edited), hover_at("h", &uri, TOP, "sig = W")],
|
||||
);
|
||||
assert!(answered(&session).is_empty(), "nothing goes ahead of an unapplied change");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_in_the_same_burst_is_honoured_for_a_request_that_goes_ahead() {
|
||||
let (_tree, mut session, uri) = opened("fa_cancel");
|
||||
let cancel = Message::Notification(lsp_server::Notification::new(
|
||||
Cancel::METHOD.to_string(),
|
||||
serde_json::json!({ "id": "h" }),
|
||||
));
|
||||
mid_scan(&mut session, vec![lens("l", &uri), hover_at("h", &uri, TOP, "sig = W"), cancel]);
|
||||
let answers = session.answers();
|
||||
assert_eq!(answers.len(), 1);
|
||||
assert!(answers[0]
|
||||
.response_result
|
||||
.as_ref()
|
||||
.is_err_and(|e| e.code == lsp_server::ErrorCode::RequestCanceled as i32));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_buffer_requests_go_ahead_and_completion_waits() {
|
||||
let (_tree, mut session, uri) = opened("fa_whole");
|
||||
let doc = serde_json::json!({ "textDocument": { "uri": uri } });
|
||||
let at = serde_json::json!({ "textDocument": { "uri": uri },
|
||||
"position": { "line": 3, "character": 15 } });
|
||||
mid_scan(
|
||||
&mut session,
|
||||
vec![
|
||||
lens("l", &uri),
|
||||
ask("sym", DocumentSymbolRequest::METHOD, doc.clone()),
|
||||
ask("fold", FoldingRangeRequest::METHOD, doc),
|
||||
ask("comp", Completion::METHOD, at),
|
||||
],
|
||||
);
|
||||
assert_eq!(answered(&session), vec![rid("sym"), rid("fold")]);
|
||||
assert_eq!(session.server.held.len(), 2, "the lens and the completion");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_takes_item_defaults_is_sent_the_range_once() {
|
||||
let tree = Tree::new("fa_defaults");
|
||||
tree.write("p.sv", PKG);
|
||||
let text = "module top;\n import p::*;\n logic sig;\n assign sig = s\nendmodule\n";
|
||||
tree.write("top.sv", text);
|
||||
let position = serde_json::json!({ "line": 3, "character": 16 });
|
||||
let mut answers = Vec::new();
|
||||
for item_defaults in [false, true] {
|
||||
let abilities =
|
||||
ClientAbilities { completion_item_defaults: item_defaults, ..Default::default() };
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
|
||||
let uri = session.open(&tree.path.join("top.sv"), text);
|
||||
let params = serde_json::json!({ "textDocument": { "uri": uri }, "position": position });
|
||||
answers.push(session.result(Completion::METHOD, params));
|
||||
}
|
||||
let (whole, compact) = (&answers[0], &answers[1]);
|
||||
assert!(whole.get("itemDefaults").is_none(), "a client that said nothing: {whole}");
|
||||
let range = &compact["itemDefaults"]["editRange"];
|
||||
assert_eq!(range, &whole["items"][0]["textEdit"]["range"]);
|
||||
let labels = |a: &Value| -> Vec<String> {
|
||||
a["items"].as_array().expect("items").iter().map(|i| i["label"].to_string()).collect()
|
||||
};
|
||||
assert_eq!(labels(whole), labels(compact), "the same items");
|
||||
assert!(compact["items"]
|
||||
.as_array()
|
||||
.expect("items")
|
||||
.iter()
|
||||
.all(|i| i.get("textEdit").is_none()));
|
||||
assert!(compact.to_string().len() < whole.to_string().len());
|
||||
}
|
||||
@@ -0,0 +1,499 @@
|
||||
//! **An answer given ahead is the answer a server taking one message at a
|
||||
//! time gives** — the randomized differential behind the precondition on
|
||||
//! `Server::answer_from_the_buffer` (`docs/features/fast-actions/README.md`).
|
||||
//!
|
||||
//! A seeded client sends rounds of bursts mixing every kind of message that
|
||||
//! can sit in front of a request: edits, opens, closes and saves of two
|
||||
//! buffers whose sizes straddle the large-file thresholds in play; settings
|
||||
//! pushes that move the threshold up or down or move something unrelated; an
|
||||
//! empty push (the pull model's "ask me") and the client's late answer to a
|
||||
//! pull; watcher events that cost a whole rescan; folder, rename and delete
|
||||
//! events; a notification the server does not know. Two servers hear it. The
|
||||
//! **early** one gets the round as the loop would — a first burst, the rest
|
||||
//! arriving at the interleave points of the rescan it starts, or held behind
|
||||
//! it — so the real gate decides what goes ahead. The **reference** gets the
|
||||
//! same messages one per burst, in the order sent. Then:
|
||||
//!
|
||||
//! * every request is answered exactly once by both;
|
||||
//! * every answer the early server gave *ahead* ([`probe::take_ahead`]) is
|
||||
//! an answer the reference gives to that request **at its place in the
|
||||
//! stream or after a later message of the round** — a state the client
|
||||
//! had, no older than the request. (A request that waited and went ahead
|
||||
//! later may rightly see what was applied meanwhile, as every request
|
||||
//! answered late always could; what it may never see is a state before
|
||||
//! its own, or one that never was.)
|
||||
//! * once the round has settled, both say the same about every open buffer.
|
||||
//!
|
||||
//! The ignored long run takes `LUCISV_FAST_ACTIONS_SEED` and
|
||||
//! `LUCISV_FAST_ACTIONS_ROUNDS`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use lsp_types::notification::Cancel;
|
||||
|
||||
use super::super::probe;
|
||||
use super::scan_ordering::{ask, closed, created, note, opened, ordering_tree, settle};
|
||||
use super::*;
|
||||
|
||||
/// The `largeFile.threshold` values in play: off, between the buffer sizes,
|
||||
/// and the default.
|
||||
const THRESHOLDS: [u64; 4] = [0, 200, 1000, 4 * 1024 * 1024];
|
||||
|
||||
/// The requests asked at the signal's declaration (line 1) or its use
|
||||
/// (line 2): each is early-eligible there, and each answer names the signal.
|
||||
const AT_THE_SIGNAL: [(&str, u32); 4] = [
|
||||
(HoverRequest::METHOD, 1),
|
||||
(GotoDefinition::METHOD, 2),
|
||||
(DocumentHighlightRequest::METHOD, 2),
|
||||
(PrepareRenameRequest::METHOD, 1),
|
||||
];
|
||||
|
||||
/// A buffer's text: one module, one signal named after `n`, and `padding`
|
||||
/// comment lines — about 80 bytes, 400 or 1.5 KB for 0, 12 and 55.
|
||||
fn text(doc: usize, n: u64, padding: usize) -> String {
|
||||
format!(
|
||||
"module m{doc};\n logic sig{n};\n assign sig{n} = 1'b0;\nendmodule\n{}",
|
||||
"// padding padding padding\n".repeat(padding)
|
||||
)
|
||||
}
|
||||
|
||||
/// One message of the client's stream, before it is put on a wire: the
|
||||
/// settings answer names a request id each server numbered for itself.
|
||||
#[derive(Clone)]
|
||||
enum Sent {
|
||||
Wire(Message),
|
||||
/// The client's answer to the pull outstanding when the round began.
|
||||
SettingsAnswer(u64),
|
||||
}
|
||||
|
||||
struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
|
||||
fn below(&mut self, n: usize) -> usize {
|
||||
(self.next() % n.max(1) as u64) as usize
|
||||
}
|
||||
}
|
||||
|
||||
struct Client {
|
||||
rng: Rng,
|
||||
root: PathBuf,
|
||||
docs: Vec<Uri>,
|
||||
/// Version, by document, of the buffers that are open.
|
||||
open: HashMap<usize, u32>,
|
||||
asked: Vec<i32>,
|
||||
next_id: i32,
|
||||
threshold: u64,
|
||||
/// Whether an empty push has gone unanswered so far.
|
||||
announced: bool,
|
||||
folder_added: bool,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
fn settings(&self, indent: usize) -> Value {
|
||||
serde_json::json!({ "index": { "scope": "workspace" }, "indent": indent,
|
||||
"largeFile": { "threshold": self.threshold } })
|
||||
}
|
||||
|
||||
fn new_text(&mut self, doc: usize) -> String {
|
||||
let padding = [0, 12, 55][self.rng.below(3)];
|
||||
text(doc, self.rng.next() % 1000, padding)
|
||||
}
|
||||
|
||||
/// The answer to whichever pull is outstanding (see [`Heard::wire`]).
|
||||
fn settings_answer(&mut self) -> Sent {
|
||||
self.announced = false;
|
||||
self.threshold = THRESHOLDS[self.rng.below(THRESHOLDS.len())];
|
||||
Sent::SettingsAnswer(self.threshold)
|
||||
}
|
||||
|
||||
/// One message, the client's own view updated as it is sent.
|
||||
fn message(&mut self) -> Sent {
|
||||
// A client that said "ask me" answers soon: the early path is shut
|
||||
// until it does, and a run of rounds with it shut tests little.
|
||||
if self.announced && self.rng.below(3) == 0 {
|
||||
return self.settings_answer();
|
||||
}
|
||||
let doc = self.rng.below(self.docs.len());
|
||||
let uri = self.docs[doc].clone();
|
||||
let roll = self.rng.below(100);
|
||||
Sent::Wire(match (roll, self.open.contains_key(&doc)) {
|
||||
(0..=11, true) => {
|
||||
let version = self.open.get_mut(&doc).map(|v| {
|
||||
*v += 1;
|
||||
*v
|
||||
});
|
||||
changed(&uri, version.unwrap_or(2), &self.new_text(doc))
|
||||
}
|
||||
(12..=13, true) => {
|
||||
self.open.remove(&doc);
|
||||
closed(&uri)
|
||||
}
|
||||
(14..=16, true) => {
|
||||
let with_text = self.rng.below(2) == 0;
|
||||
let text = with_text.then(|| self.new_text(doc));
|
||||
note(
|
||||
DidSaveTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri }, "text": text }),
|
||||
)
|
||||
}
|
||||
(0..=16, false) => {
|
||||
self.open.insert(doc, 1);
|
||||
opened(&uri, &self.new_text(doc))
|
||||
}
|
||||
(17..=22, _) => {
|
||||
self.threshold = THRESHOLDS[self.rng.below(THRESHOLDS.len())];
|
||||
push(self.settings(2))
|
||||
}
|
||||
// Nothing a buffer reads moves: the indent only.
|
||||
(23..=25, _) => {
|
||||
let indent = 2 + self.rng.below(3);
|
||||
push(self.settings(indent))
|
||||
}
|
||||
(26..=27, _) => {
|
||||
self.announced = true;
|
||||
note(DidChangeConfiguration::METHOD, serde_json::json!({ "settings": null }))
|
||||
}
|
||||
(28..=30, _) => return self.settings_answer(),
|
||||
(31..=33, _) => self.created_file(),
|
||||
(34, _) => self.folders(),
|
||||
(35, _) => self.file_operation(),
|
||||
(36, _) => note("$/setTrace", serde_json::json!({ "value": "off" })),
|
||||
(37, _) => note(Cancel::METHOD, serde_json::json!({ "id": 1_000_000 })),
|
||||
_ => self.request(doc),
|
||||
})
|
||||
}
|
||||
|
||||
/// A new package on disk and the watcher's word for it: a whole rescan.
|
||||
fn created_file(&mut self) -> Message {
|
||||
let name = format!("r{}_{}", self.next_id, self.rng.below(100_000));
|
||||
let path = self.root.join("z").join(format!("{name}.sv"));
|
||||
std::fs::write(&path, format!("package {name};\n localparam K = 1;\nendpackage\n"))
|
||||
.expect("write");
|
||||
created(&path)
|
||||
}
|
||||
|
||||
fn folders(&mut self) -> Message {
|
||||
let folder = serde_json::json!({
|
||||
"uri": path_to_uri(&self.root.join("more")).expect("uri"), "name": "more",
|
||||
});
|
||||
self.folder_added = !self.folder_added;
|
||||
let (added, removed) = match self.folder_added {
|
||||
true => (vec![folder], Vec::new()),
|
||||
false => (Vec::new(), vec![folder]),
|
||||
};
|
||||
note(
|
||||
DidChangeWorkspaceFolders::METHOD,
|
||||
serde_json::json!({ "event": { "added": added, "removed": removed } }),
|
||||
)
|
||||
}
|
||||
|
||||
fn file_operation(&mut self) -> Message {
|
||||
let gone = path_to_uri(&self.root.join("z/gone.sv")).expect("uri");
|
||||
match self.rng.below(2) {
|
||||
0 => note(DidDeleteFiles::METHOD, serde_json::json!({ "files": [{ "uri": gone }] })),
|
||||
_ => note(
|
||||
DidRenameFiles::METHOD,
|
||||
serde_json::json!({ "files": [{ "oldUri": gone, "newUri": gone }] }),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn request(&mut self, doc: usize) -> Message {
|
||||
let id = self.next_id;
|
||||
self.next_id += 1;
|
||||
self.asked.push(id);
|
||||
let whole = serde_json::json!({ "textDocument": { "uri": self.docs[doc] } });
|
||||
match self.rng.below(8) {
|
||||
// Never early: it holds the burst behind it.
|
||||
0 => ask(id, CodeLensRequest::METHOD, whole),
|
||||
1 => ask(id, DocumentSymbolRequest::METHOD, whole),
|
||||
2 => ask(id, FoldingRangeRequest::METHOD, whole),
|
||||
n => {
|
||||
let (method, line) = AT_THE_SIGNAL[n % AT_THE_SIGNAL.len()];
|
||||
let at = serde_json::json!({ "line": line, "character": 10 });
|
||||
let params = serde_json::json!({
|
||||
"textDocument": { "uri": self.docs[doc] }, "position": at,
|
||||
});
|
||||
ask(id, method, params)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One round: one to four bursts. Four rounds in five have a watcher
|
||||
/// event in the first, so the rest of the round meets a real rescan —
|
||||
/// usually as that burst's last message, sometimes with a tail behind it.
|
||||
fn round(&mut self) -> Vec<Vec<Sent>> {
|
||||
let bursts = 1 + self.rng.below(4);
|
||||
let mut round: Vec<Vec<Sent>> = (0..bursts)
|
||||
.map(|_| (0..1 + self.rng.below(5)).map(|_| self.message()).collect())
|
||||
.collect();
|
||||
if self.rng.below(5) < 4 {
|
||||
let end = round[0].len();
|
||||
let at = if self.rng.below(4) == 0 { self.rng.below(end + 1) } else { end };
|
||||
let event = Sent::Wire(self.created_file());
|
||||
round[0].insert(at, event);
|
||||
}
|
||||
round
|
||||
}
|
||||
}
|
||||
|
||||
fn push(section: Value) -> Message {
|
||||
note(DidChangeConfiguration::METHOD, serde_json::json!({ "settings": { "lucisv": section } }))
|
||||
}
|
||||
|
||||
/// One server and what the test knows of it.
|
||||
struct Heard {
|
||||
session: Session,
|
||||
/// The settings pull this server has outstanding, as of the last round.
|
||||
pull: Option<RequestId>,
|
||||
/// A newer pull it has made since: the one to answer from the next
|
||||
/// round on. Kept apart so that both servers start a round answering
|
||||
/// alike, however far through the round each has been listened to.
|
||||
newer_pull: Option<RequestId>,
|
||||
/// Its answers since they were last taken, by request.
|
||||
answers: HashMap<RequestId, Vec<Response>>,
|
||||
}
|
||||
|
||||
impl Heard {
|
||||
fn new(tree: &Tree) -> Heard {
|
||||
let abilities = ClientAbilities { configuration: true, ..watching_progress() };
|
||||
let session = Session::wide_with(vec![tree.path.clone()], abilities);
|
||||
let mut heard = Heard { session, pull: None, newer_pull: None, answers: HashMap::new() };
|
||||
let _ = heard.heard();
|
||||
heard
|
||||
}
|
||||
|
||||
/// A burst on this server's wire. A settings answer with no pull to
|
||||
/// answer is not sent — to either server, since both are asked alike.
|
||||
fn wire(&mut self, burst: &[Sent]) -> Vec<Message> {
|
||||
burst
|
||||
.iter()
|
||||
.filter_map(|sent| match sent {
|
||||
Sent::Wire(message) => Some(message.clone()),
|
||||
Sent::SettingsAnswer(threshold) => {
|
||||
let section = serde_json::json!({
|
||||
"index": { "scope": "workspace" },
|
||||
"largeFile": { "threshold": threshold },
|
||||
});
|
||||
let answer = Response::new_ok(self.pull.take()?, serde_json::json!([section]));
|
||||
Some(Message::Response(answer))
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Take in everything the server sent since the last call: its answers
|
||||
/// by id, and the newest settings pull among its requests.
|
||||
fn listen(&mut self) {
|
||||
for message in self.session.drain() {
|
||||
match message {
|
||||
Message::Response(r) => self.answers.entry(r.id.clone()).or_default().push(r),
|
||||
Message::Request(r) if r.method == WorkspaceConfiguration::METHOD => {
|
||||
self.newer_pull = Some(r.id);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The end of a round: the answers heard since the last one, and the
|
||||
/// newest pull made in it becomes the one a settings answer answers.
|
||||
fn heard(&mut self) -> HashMap<RequestId, Vec<Response>> {
|
||||
self.listen();
|
||||
if let Some(newer) = self.newer_pull.take() {
|
||||
self.pull = Some(newer);
|
||||
}
|
||||
std::mem::take(&mut self.answers)
|
||||
}
|
||||
|
||||
/// Ask now, with nothing waiting.
|
||||
fn says(&mut self, method: &str, params: &Value) -> String {
|
||||
let response = self.session.request(method, params);
|
||||
self.listen();
|
||||
rendered(&response)
|
||||
}
|
||||
}
|
||||
|
||||
/// One line per message of a round, for a failure's message.
|
||||
fn described(round: &[Vec<Sent>]) -> String {
|
||||
let line = |sent: &Sent| match sent {
|
||||
Sent::SettingsAnswer(threshold) => format!("settings answer, threshold {threshold}"),
|
||||
Sent::Wire(Message::Request(r)) => format!("{} {} {}", r.id, r.method, r.params),
|
||||
Sent::Wire(Message::Notification(n)) => {
|
||||
let mut params = n.params.to_string();
|
||||
params.truncate(160);
|
||||
format!("{} {params}", n.method)
|
||||
}
|
||||
Sent::Wire(Message::Response(r)) => format!("response {}", r.id),
|
||||
};
|
||||
let burst = |b: &Vec<Sent>| b.iter().map(line).collect::<Vec<_>>().join("\n ");
|
||||
round.iter().map(burst).collect::<Vec<_>>().join("\n --\n ")
|
||||
}
|
||||
|
||||
/// What a run compared.
|
||||
#[derive(Default)]
|
||||
struct Tally {
|
||||
asked: usize,
|
||||
ahead: usize,
|
||||
/// Answers given ahead that are a later state's, not the request's own.
|
||||
later: usize,
|
||||
settled: usize,
|
||||
}
|
||||
|
||||
fn rendered(response: &Response) -> String {
|
||||
format!("{:?}", response.response_result.clone().map_err(|e| (e.code, e.message)))
|
||||
}
|
||||
|
||||
fn run(seed: u64, rounds: usize) -> Tally {
|
||||
let tree = ordering_tree(&format!("fa_bursts_{seed}_{rounds}"));
|
||||
let docs: Vec<Uri> = ["a/a.sv", "b/b.sv"]
|
||||
.iter()
|
||||
.map(|rel| path_to_uri(&tree.path.join(rel)).expect("uri"))
|
||||
.collect();
|
||||
let mut client = Client {
|
||||
rng: Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1),
|
||||
root: tree.path.clone(),
|
||||
docs: docs.clone(),
|
||||
open: HashMap::new(),
|
||||
asked: Vec::new(),
|
||||
next_id: 1,
|
||||
threshold: THRESHOLDS[3],
|
||||
announced: false,
|
||||
folder_added: false,
|
||||
};
|
||||
let (mut early, mut reference) = (Heard::new(&tree), Heard::new(&tree));
|
||||
for (doc, uri) in docs.iter().enumerate() {
|
||||
client.open.insert(doc, 1);
|
||||
for heard in [&mut early, &mut reference] {
|
||||
heard.session.batch(vec![opened(uri, &text(doc, 0, 12))]);
|
||||
let _ = heard.heard();
|
||||
}
|
||||
}
|
||||
let _ = (probe::take_counts(), probe::take_ahead());
|
||||
let mut tally = Tally::default();
|
||||
for round in 0..rounds {
|
||||
let said = client.round();
|
||||
let asked = std::mem::take(&mut client.asked);
|
||||
let sent = described(&said);
|
||||
let context = |what: &str| format!("seed {seed}, round {round}: {what}\n {sent}");
|
||||
|
||||
// The early server: the first burst to the loop, the rest wherever a
|
||||
// rescan's interleave points — or the wait after it — puts them.
|
||||
let mut bursts: Vec<Vec<Message>> = said.iter().map(|b| early.wire(b)).collect();
|
||||
let first = bursts.remove(0);
|
||||
probe::script(bursts);
|
||||
assert!(!early.session.batch(first), "no shutdown");
|
||||
settle(&mut early.session);
|
||||
let ahead = probe::take_ahead();
|
||||
let early_answers = early.heard();
|
||||
|
||||
// The reference: the same stream, one message at a time. A request
|
||||
// the early server answered ahead is asked again after every later
|
||||
// state change of the round: the states it may rightly have seen.
|
||||
let mut gone_ahead: Vec<(RequestId, String, Value)> = Vec::new();
|
||||
let mut later: HashMap<RequestId, Vec<String>> = HashMap::new();
|
||||
for burst in &said {
|
||||
for message in reference.wire(burst) {
|
||||
let asked = match &message {
|
||||
Message::Request(r) if ahead.contains(&r.id) => {
|
||||
Some((r.id.clone(), r.method.clone(), r.params.clone()))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let changes = !matches!(message, Message::Request(_));
|
||||
assert!(!reference.session.batch(vec![message]), "no shutdown");
|
||||
settle(&mut reference.session);
|
||||
gone_ahead.extend(asked);
|
||||
for (id, method, params) in gone_ahead.iter().filter(|_| changes) {
|
||||
later.entry(id.clone()).or_default().push(reference.says(method, params));
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = probe::take_ahead();
|
||||
let reference_answers = reference.heard();
|
||||
|
||||
for id in asked.iter().map(|id| RequestId::from(*id)) {
|
||||
let (e, r) = (early_answers.get(&id), reference_answers.get(&id));
|
||||
let (Some([e]), Some([r])) = (e.map(Vec::as_slice), r.map(Vec::as_slice)) else {
|
||||
panic!("{}", context(&format!("{id} answered once by each: {e:?} / {r:?}")));
|
||||
};
|
||||
tally.asked += 1;
|
||||
if ahead.contains(&id) {
|
||||
tally.ahead += 1;
|
||||
let (e, at_its_place) = (rendered(e), rendered(r));
|
||||
let after = later.remove(&id).unwrap_or_default();
|
||||
tally.later += usize::from(e != at_its_place);
|
||||
assert!(
|
||||
e == at_its_place || after.contains(&e),
|
||||
"{}",
|
||||
context(&format!(
|
||||
"{id} went ahead with an answer the client's stream never gave it\n \
|
||||
early: {e}\n at its place: {at_its_place}\n later: {after:?}"
|
||||
))
|
||||
);
|
||||
}
|
||||
}
|
||||
// Settled, the two servers hold the same buffers in the same mode.
|
||||
for uri in &docs {
|
||||
let whole = serde_json::json!({ "textDocument": { "uri": uri } });
|
||||
let at = serde_json::json!({ "textDocument": { "uri": uri },
|
||||
"position": { "line": 1, "character": 10 } });
|
||||
for (method, params) in
|
||||
[(DocumentSymbolRequest::METHOD, &whole), (HoverRequest::METHOD, &at)]
|
||||
{
|
||||
tally.settled += 1;
|
||||
let (e, r) = (early.says(method, params), reference.says(method, params));
|
||||
assert_eq!(e, r, "{}", context(&format!("{method} once settled")));
|
||||
}
|
||||
}
|
||||
}
|
||||
tally
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn answers_given_ahead_equal_a_one_message_at_a_time_server() {
|
||||
let mut total = Tally::default();
|
||||
for seed in 1..=8 {
|
||||
let tally = run(seed, 40);
|
||||
total.asked += tally.asked;
|
||||
total.ahead += tally.ahead;
|
||||
total.later += tally.later;
|
||||
total.settled += tally.settled;
|
||||
}
|
||||
eprintln!(
|
||||
"fast actions, random bursts: {} requests, {} answered ahead ({} from a later state), \
|
||||
{} settled comparisons",
|
||||
total.asked, total.ahead, total.later, total.settled
|
||||
);
|
||||
assert!(
|
||||
total.ahead > 100,
|
||||
"the gate lets requests through: {} of {}",
|
||||
total.ahead,
|
||||
total.asked
|
||||
);
|
||||
assert!(total.asked > total.ahead * 2, "and holds others: {} of {}", total.ahead, total.asked);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "long: LUCISV_FAST_ACTIONS_SEED (default 7), LUCISV_FAST_ACTIONS_ROUNDS (default 3000)"]
|
||||
fn answers_given_ahead_equal_a_one_message_at_a_time_server_long_run() {
|
||||
let number = |name: &str, default: u64| {
|
||||
std::env::var(name).ok().and_then(|s| s.parse().ok()).unwrap_or(default)
|
||||
};
|
||||
let seed = number("LUCISV_FAST_ACTIONS_SEED", 7);
|
||||
let rounds = number("LUCISV_FAST_ACTIONS_ROUNDS", 3000) as usize;
|
||||
let tally = run(seed, rounds);
|
||||
eprintln!(
|
||||
"fast actions, random bursts, seed {seed}: {} requests, {} answered ahead \
|
||||
({} from a later state), {} settled comparisons, 0 differ",
|
||||
tally.asked, tally.ahead, tally.later, tally.settled
|
||||
);
|
||||
assert!(tally.ahead > rounds / 4, "{} of {}", tally.ahead, tally.asked);
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
//! **Early answers are settled answers** — the safety net of
|
||||
//! `docs/features/fast-actions/README.md`.
|
||||
//!
|
||||
//! Two servers. The *early* one has an empty index (its root is an empty
|
||||
//! directory, workspace scope, so opening a buffer widens nothing): the worst
|
||||
//! case a request answered ahead of a scan can meet. It is asked mid-scan,
|
||||
//! through the real loop body (`process_batch` with a rescan pretended to be
|
||||
//! running), so what goes ahead is decided by the real gate. The *settled* one
|
||||
//! has indexed the whole tree and answers through the ordinary dispatch. At
|
||||
//! every identifier (and a sample of the other tokens) of every sampled file,
|
||||
//! for every request kind the gate can let through: whenever the early server
|
||||
//! answered, its answer must **equal** the settled one, `null` and `[]`
|
||||
//! included. When it did not answer it held the request, which is always
|
||||
//! allowed — and is counted, so a gate that lets nothing through cannot pass.
|
||||
//!
|
||||
//! The fast subset runs over a fixture written for the shapes the locality
|
||||
//! rule names; the ignored long run over real trees named by
|
||||
//! `LUCISV_FAST_ACTIONS_TREES` (`:`-separated roots — scratch **copies**,
|
||||
//! never a cache), seeded by `LUCISV_FAST_ACTIONS_SEED`:
|
||||
//!
|
||||
//! ```text
|
||||
//! LUCISV_FAST_ACTIONS_TREES=/scratch/corpus:/scratch/ot-hw LUCISV_FAST_ACTIONS_SEED=7 \
|
||||
//! tools/guard.sh -- cargo test --release -p lucisv_server early_answers_equal_settled \
|
||||
//! -- --ignored --nocapture
|
||||
//! ```
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use lsp_server::Response;
|
||||
use lsp_types::request::{
|
||||
DocumentHighlightRequest, DocumentSymbolRequest, FoldingRangeRequest, GotoDefinition,
|
||||
GotoTypeDefinition, HoverRequest, LinkedEditingRange, PrepareRenameRequest, References,
|
||||
SelectionRangeRequest, SignatureHelpRequest,
|
||||
};
|
||||
use lsp_types::Position;
|
||||
use serde_json::json;
|
||||
use vlog_parser::token::TokenKind;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The request kinds asked at a position.
|
||||
const AT_A_POSITION: [&str; 8] = [
|
||||
HoverRequest::METHOD,
|
||||
GotoDefinition::METHOD,
|
||||
GotoTypeDefinition::METHOD,
|
||||
DocumentHighlightRequest::METHOD,
|
||||
References::METHOD,
|
||||
PrepareRenameRequest::METHOD,
|
||||
SignatureHelpRequest::METHOD,
|
||||
LinkedEditingRange::METHOD,
|
||||
];
|
||||
|
||||
/// The request kinds asked once per buffer.
|
||||
const WHOLE_BUFFER: [&str; 3] =
|
||||
[DocumentSymbolRequest::METHOD, FoldingRangeRequest::METHOD, pairs::SCOPE_PAIRS_METHOD];
|
||||
|
||||
/// What one comparison run saw, per method: answered early (and equal),
|
||||
/// waited, and every early answer that differed from the settled one.
|
||||
#[derive(Default)]
|
||||
struct Tally {
|
||||
early: BTreeMap<&'static str, usize>,
|
||||
waited: BTreeMap<&'static str, usize>,
|
||||
differed: Vec<String>,
|
||||
}
|
||||
|
||||
impl Tally {
|
||||
fn early_total(&self) -> usize {
|
||||
self.early.values().sum()
|
||||
}
|
||||
|
||||
fn waited_total(&self) -> usize {
|
||||
self.waited.values().sum()
|
||||
}
|
||||
|
||||
fn line(&self) -> String {
|
||||
let per = |method: &str| {
|
||||
let (e, w) = (self.early.get(method), self.waited.get(method));
|
||||
format!("{method}={}/{}", e.copied().unwrap_or(0), w.copied().unwrap_or(0))
|
||||
};
|
||||
let all: Vec<String> = AT_A_POSITION
|
||||
.iter()
|
||||
.chain(&WHOLE_BUFFER)
|
||||
.chain([&SelectionRangeRequest::METHOD])
|
||||
.map(|m| per(m))
|
||||
.collect();
|
||||
format!(
|
||||
"early={} waited={} differed={} (early/waited: {})",
|
||||
self.early_total(),
|
||||
self.waited_total(),
|
||||
self.differed.len(),
|
||||
all.join(" ")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The early server: nothing indexed, ever.
|
||||
fn early_session(empty: &Path) -> Session {
|
||||
Session::wide(vec![empty.to_path_buf()], false)
|
||||
}
|
||||
|
||||
/// Ask `early` mid-scan and `settled` settled, and tally the pair.
|
||||
fn compare(
|
||||
early: &mut Session,
|
||||
settled: &mut Session,
|
||||
method: &'static str,
|
||||
params: Value,
|
||||
tally: &mut Tally,
|
||||
) {
|
||||
let id = RequestId::from(format!("fa-{method}"));
|
||||
let asked = Message::Request(lsp_server::Request::new(id, method.to_string(), params.clone()));
|
||||
early.server.scanning = true;
|
||||
early.server.answering_a_rescan = true;
|
||||
early.batch(vec![asked]);
|
||||
early.server.scanning = false;
|
||||
early.server.answering_a_rescan = false;
|
||||
let answers = early.answers();
|
||||
if answers.is_empty() {
|
||||
assert_eq!(early.server.held.len(), 1, "{method}: neither answered nor held");
|
||||
early.server.held.clear();
|
||||
*tally.waited.entry(method).or_default() += 1;
|
||||
return;
|
||||
}
|
||||
assert_eq!(answers.len(), 1, "{method}: answered once");
|
||||
let settled_answer = settled.request(method, ¶ms);
|
||||
*tally.early.entry(method).or_default() += 1;
|
||||
if !same(&answers[0], &settled_answer) {
|
||||
tally.differed.push(format!(
|
||||
"{method} {params}\n early: {:?}\n settled: {:?}",
|
||||
answers[0].response_result, settled_answer.response_result
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Two responses say the same thing: the same result, or the same error.
|
||||
fn same(a: &Response, b: &Response) -> bool {
|
||||
match (&a.response_result, &b.response_result) {
|
||||
(Ok(x), Ok(y)) => x == y,
|
||||
(Err(x), Err(y)) => x.code == y.code && x.message == y.message,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every position in `text` worth asking at: the start of each token, the
|
||||
/// end of each identifier, macro use and keyword, and the middle of each
|
||||
/// directive and string — of the tokens `pick` keeps.
|
||||
fn positions(text: &str, mut pick: impl FnMut() -> bool) -> Vec<u32> {
|
||||
let Ok(tokens) = vlog_parser::tokenize(text) else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
for token in &tokens {
|
||||
let named = matches!(token.kind, TokenKind::Ident | TokenKind::Keyword);
|
||||
if !pick() {
|
||||
continue;
|
||||
}
|
||||
out.push(token.span.start);
|
||||
if named {
|
||||
out.push(token.span.end);
|
||||
}
|
||||
// Inside a directive or a string: an `` `include``'s path is there.
|
||||
if matches!(token.kind, TokenKind::Directive | TokenKind::String) {
|
||||
out.push(token.span.start + (token.span.end - token.span.start) / 2);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Open `path` in both servers, compare every request kind at `offsets`, and
|
||||
/// close it again.
|
||||
fn compare_file(
|
||||
early: &mut Session,
|
||||
settled: &mut Session,
|
||||
path: &Path,
|
||||
offsets: &[u32],
|
||||
tally: &mut Tally,
|
||||
) {
|
||||
let Ok(text) = std::fs::read_to_string(path) else { return };
|
||||
let uri = early.open(path, &text);
|
||||
settled.open(path, &text);
|
||||
let doc = early.server.workspace.document(&uri).expect("open");
|
||||
let lines = doc.positions();
|
||||
let at: Vec<Position> = offsets.iter().map(|&o| lines.position(o)).collect();
|
||||
for method in WHOLE_BUFFER {
|
||||
compare(early, settled, method, json!({ "textDocument": { "uri": uri } }), tally);
|
||||
}
|
||||
compare(
|
||||
early,
|
||||
settled,
|
||||
SelectionRangeRequest::METHOD,
|
||||
json!({ "textDocument": { "uri": uri }, "positions": at }),
|
||||
tally,
|
||||
);
|
||||
for position in &at {
|
||||
for method in AT_A_POSITION {
|
||||
let params = json!({ "textDocument": { "uri": uri }, "position": position,
|
||||
"context": { "includeDeclaration": true } });
|
||||
compare(early, settled, method, params, tally);
|
||||
}
|
||||
}
|
||||
for session in [early, settled] {
|
||||
session.notify(
|
||||
lsp_types::notification::DidCloseTextDocument::METHOD,
|
||||
json!({ "textDocument": { "uri": uri } }),
|
||||
);
|
||||
session.drain();
|
||||
}
|
||||
}
|
||||
|
||||
/// The fixture: one file per shape the locality rule names.
|
||||
fn shapes(tree: &Tree) {
|
||||
tree.write(
|
||||
"pkg.sv",
|
||||
"package p;\n typedef enum logic [1:0] {IDLE, RUN} state_t;\n localparam int W = 4;\n \
|
||||
function automatic int twice(int a);\n return a * 2;\n endfunction\nendpackage\n",
|
||||
);
|
||||
tree.write("inc/defs.svh", "`define WIDTH 8\n`define ADD(a, b) ((a) + (b))\n");
|
||||
// Found only through an include directory the scan derives.
|
||||
tree.write("inc/more.svh", "`define MORE 1\n");
|
||||
tree.write(
|
||||
"sub.sv",
|
||||
"module sub #(parameter int N = 1) (input logic a, output logic b);\n \
|
||||
assign b = a;\nendmodule\n",
|
||||
);
|
||||
tree.write(
|
||||
"top.sv",
|
||||
"`include \"inc/defs.svh\"\n`include \"more.svh\"\n`define LOCAL 3\nmodule top;\n import p::*;\n \
|
||||
state_t st;\n logic [`WIDTH-1:0] w;\n logic [`LOCAL:0] l;\n logic hit;\n \
|
||||
sub #(.N(2)) u_sub (.a(st == IDLE), .b(hit));\n \
|
||||
always_comb begin : named\n logic t;\n t = w[0];\n end\n \
|
||||
always_comb begin\n logic u;\n u = `ADD(1, 2);\n end\n \
|
||||
function automatic int g(int x);\n int y;\n y = twice(x) + p::W;\n \
|
||||
return y;\n endfunction\n \
|
||||
for (genvar i = 0; i < 2; i++) begin : gen_l\n logic q;\n assign q = w[i];\n end\n \
|
||||
assign l = p::W;\n wire from_sub = u_sub.b;\n initial $display(\"%0d\", g(1));\nendmodule\n",
|
||||
);
|
||||
tree.write(
|
||||
"cls.sv",
|
||||
"class base;\n int m;\n function void hi();\n endfunction\nendclass\n\
|
||||
class derived extends base;\n function void go();\n hi();\n m = 1;\n \
|
||||
endfunction\nendclass\n",
|
||||
);
|
||||
// One name declared twice: a rename of either is ambiguous, which only
|
||||
// the index can say.
|
||||
tree.write("dup_a.sv", "module dup;\nendmodule\n");
|
||||
tree.write("dup_b.sv", "module dup;\n logic d;\nendmodule\n");
|
||||
tree.write(
|
||||
"bus.sv",
|
||||
"interface bus_if;\n logic v;\n modport mp (input v);\nendinterface\n\
|
||||
module user (bus_if.mp b, output logic x);\n assign x = b.v;\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn early_answers_equal_settled_over_the_locality_shapes() {
|
||||
let tree = Tree::new("fastactions_shapes");
|
||||
shapes(&tree);
|
||||
let empty = Tree::new("fastactions_shapes_empty");
|
||||
// The settled server reads a filelist, whose `+incdir+` is the one way
|
||||
// `more.svh` resolves — something only a scan learns.
|
||||
tree.write(
|
||||
"files.f",
|
||||
"+incdir+inc\npkg.sv\nsub.sv\ntop.sv\ncls.sv\nbus.sv\ndup_a.sv\ndup_b.sv\n",
|
||||
);
|
||||
let listed = ClientSettings {
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
filelist: Some(tree.path.join("files.f").display().to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
let mut settled = Session::started(vec![tree.path.clone()], ClientAbilities::default(), listed);
|
||||
let mut early = early_session(&empty.path);
|
||||
let mut tally = Tally::default();
|
||||
for file in ["top.sv", "pkg.sv", "sub.sv", "cls.sv", "bus.sv", "dup_a.sv", "inc/defs.svh"] {
|
||||
let path = tree.path.join(file);
|
||||
let text = std::fs::read_to_string(&path).expect("fixture");
|
||||
compare_file(&mut early, &mut settled, &path, &positions(&text, || true), &mut tally);
|
||||
}
|
||||
eprintln!("fast actions over the shapes: {}", tally.line());
|
||||
assert!(tally.differed.is_empty(), "{}", tally.differed.join("\n"));
|
||||
assert!(
|
||||
tally.early_total() > 500,
|
||||
"the gate lets the local positions through: {}",
|
||||
tally.line()
|
||||
);
|
||||
assert!(tally.waited_total() > 50, "and holds the cross-file ones: {}", tally.line());
|
||||
for method in [HoverRequest::METHOD, GotoDefinition::METHOD, References::METHOD] {
|
||||
assert!(tally.early.get(method).is_some_and(|n| *n > 0), "{method} goes ahead somewhere");
|
||||
assert!(tally.waited.get(method).is_some_and(|n| *n > 0), "{method} waits somewhere");
|
||||
}
|
||||
}
|
||||
|
||||
/// A seeded generator, so a run can be repeated exactly.
|
||||
struct Lcg(u64);
|
||||
|
||||
impl Lcg {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
self.0 >> 33
|
||||
}
|
||||
|
||||
fn chance(&mut self, per_mille: u64) -> bool {
|
||||
self.next() % 1000 < per_mille
|
||||
}
|
||||
}
|
||||
|
||||
/// Every Verilog source under `root`, sorted, so a seed names the same files.
|
||||
fn sources(root: &Path) -> Vec<PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
let mut stack = vec![root.to_path_buf()];
|
||||
while let Some(dir) = stack.pop() {
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
stack.push(path);
|
||||
} else if path
|
||||
.extension()
|
||||
.is_some_and(|e| ["sv", "svh", "v", "vh"].iter().any(|x| e == *x))
|
||||
{
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "long: real trees named by LUCISV_FAST_ACTIONS_TREES; run in --release"]
|
||||
fn early_answers_equal_settled_over_real_trees() {
|
||||
let Ok(trees) = std::env::var("LUCISV_FAST_ACTIONS_TREES") else {
|
||||
eprintln!("LUCISV_FAST_ACTIONS_TREES not set — skipping");
|
||||
return;
|
||||
};
|
||||
let seed: u64 =
|
||||
std::env::var("LUCISV_FAST_ACTIONS_SEED").ok().and_then(|s| s.parse().ok()).unwrap_or(7);
|
||||
let files_per_tree: usize =
|
||||
std::env::var("LUCISV_FAST_ACTIONS_FILES").ok().and_then(|s| s.parse().ok()).unwrap_or(120);
|
||||
let mut rng = Lcg(seed);
|
||||
let empty = Tree::new("fastactions_real_empty");
|
||||
let mut total = Tally::default();
|
||||
for root in trees.split(':').filter(|r| !r.is_empty()) {
|
||||
let root = PathBuf::from(root);
|
||||
let all = sources(&root);
|
||||
let mut settled = Session::wide(vec![root.clone()], false);
|
||||
let mut early = early_session(&empty.path);
|
||||
let mut tally = Tally::default();
|
||||
let mut picked = 0;
|
||||
// Every file has the same chance, until the quota is met.
|
||||
let per_mille = (files_per_tree * 1000 / all.len().max(1)).clamp(1, 1000) as u64;
|
||||
for path in &all {
|
||||
if picked >= files_per_tree || !rng.chance(per_mille) {
|
||||
continue;
|
||||
}
|
||||
picked += 1;
|
||||
let Ok(text) = std::fs::read_to_string(path) else { continue };
|
||||
// A quarter of the tokens of a big file is plenty, every token of
|
||||
// a small one.
|
||||
let keep = if text.len() > 40_000 { 250 } else { 1000 };
|
||||
let offsets = positions(&text, || rng.chance(keep));
|
||||
compare_file(&mut early, &mut settled, path, &offsets, &mut tally);
|
||||
}
|
||||
eprintln!(
|
||||
"fast actions over {} ({picked} files, seed {seed}): {}",
|
||||
root.display(),
|
||||
tally.line()
|
||||
);
|
||||
total.differed.extend(tally.differed.iter().take(20).cloned());
|
||||
for (m, n) in tally.early {
|
||||
*total.early.entry(m).or_default() += n;
|
||||
}
|
||||
for (m, n) in tally.waited {
|
||||
*total.waited.entry(m).or_default() += n;
|
||||
}
|
||||
}
|
||||
eprintln!("fast actions, all trees: {}", total.line());
|
||||
assert!(total.differed.is_empty(), "{}", total.differed.join("\n"));
|
||||
}
|
||||
@@ -0,0 +1,545 @@
|
||||
//! The precondition for answering ahead, one clause at a time
|
||||
//! (`Server::answer_from_the_buffer`, `docs/features/fast-actions/README.md`,
|
||||
//! "When a request is answered early"). A request that breaks exactly one
|
||||
//! clause must **wait**, and is then answered exactly once, with what the
|
||||
//! settled server says; one that breaks none goes ahead with that same
|
||||
//! answer. The first tests are QA's S1 in the forms it was found in.
|
||||
|
||||
use lsp_types::notification::Cancel;
|
||||
|
||||
use super::super::ahead::{Reach, REACH};
|
||||
use super::super::probe;
|
||||
use super::scan_ordering::{created, ordering_tree};
|
||||
use super::*;
|
||||
|
||||
/// `a.sv` with a signal named `signal`, 1.5 KB: over a 1 000-byte
|
||||
/// `largeFile.threshold`, under the 4 MiB default.
|
||||
fn wide(signal: &str) -> String {
|
||||
let text = format!(
|
||||
"module qa_a;\n logic {signal};\nendmodule\n{}",
|
||||
"// padding padding padding\n".repeat(55)
|
||||
);
|
||||
assert!(text.len() > 1000 && text.len() < 2000);
|
||||
text
|
||||
}
|
||||
|
||||
fn threshold(bytes: u64) -> Value {
|
||||
serde_json::json!({ "index": { "scope": "workspace" }, "largeFile": { "threshold": bytes } })
|
||||
}
|
||||
|
||||
fn note(method: &str, params: Value) -> Message {
|
||||
Message::Notification(Notification::new(method.to_string(), params))
|
||||
}
|
||||
|
||||
/// A `didChangeConfiguration` carrying `section` as the `lucisv` settings.
|
||||
fn push(section: Value) -> Message {
|
||||
note(DidChangeConfiguration::METHOD, serde_json::json!({ "settings": { "lucisv": section } }))
|
||||
}
|
||||
|
||||
/// The client's answer to the settings pull `id`.
|
||||
fn settings_answer(id: &RequestId, section: Value) -> Message {
|
||||
Message::Response(Response::new_ok(id.clone(), serde_json::json!([section])))
|
||||
}
|
||||
|
||||
fn ask(id: i32, method: &str, params: Value) -> Message {
|
||||
Message::Request(Request::new(RequestId::from(id), method.to_string(), params))
|
||||
}
|
||||
|
||||
/// A hover on the signal `wide` declares.
|
||||
fn hover(id: i32, uri: &Uri) -> Message {
|
||||
let at = serde_json::json!({ "line": 1, "character": 10 });
|
||||
ask(
|
||||
id,
|
||||
HoverRequest::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri }, "position": at }),
|
||||
)
|
||||
}
|
||||
|
||||
/// A request no buffer answers alone: it is held, and the burst behind it.
|
||||
fn lens(id: i32, uri: &Uri) -> Message {
|
||||
ask(id, CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }))
|
||||
}
|
||||
|
||||
fn opened(uri: &Uri, text: &str) -> Message {
|
||||
note(
|
||||
DidOpenTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": {
|
||||
"uri": uri, "languageId": "systemverilog", "version": 1, "text": text,
|
||||
}}),
|
||||
)
|
||||
}
|
||||
|
||||
/// A session with `a.sv` (see [`wide`]) open, against a client that said
|
||||
/// `abilities`.
|
||||
fn session_with(name: &str, abilities: ClientAbilities) -> (Tree, Session, Uri) {
|
||||
let tree = Tree::new(name);
|
||||
tree.write("a.sv", &wide("sig_a"));
|
||||
tree.write("b.sv", "module qa_b;\nendmodule\n");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
|
||||
let uri = session.open(&tree.path.join("a.sv"), &wide("sig_a"));
|
||||
let _ = probe::take_ahead();
|
||||
(tree, session, uri)
|
||||
}
|
||||
|
||||
fn session(name: &str) -> (Tree, Session, Uri) {
|
||||
let (tree, session, uri) = session_with(name, ClientAbilities::default());
|
||||
session.drain();
|
||||
(tree, session, uri)
|
||||
}
|
||||
|
||||
/// One burst through the loop body with a rescan pretended to be running.
|
||||
fn mid_rescan(session: &mut Session, burst: Vec<Message>) {
|
||||
session.server.scanning = true;
|
||||
session.server.answering_a_rescan = true;
|
||||
session.batch(burst);
|
||||
session.server.scanning = false;
|
||||
session.server.answering_a_rescan = false;
|
||||
session.server.rescan_wanted = false;
|
||||
session.server.head_owed = false;
|
||||
session.server.opened_mid_scan = false;
|
||||
}
|
||||
|
||||
/// What `run` does once the rescan is over: replay what was held.
|
||||
fn settle(session: &mut Session) {
|
||||
while !session.server.held.is_empty() {
|
||||
let held = std::mem::take(&mut session.server.held);
|
||||
session.batch(held);
|
||||
}
|
||||
}
|
||||
|
||||
/// The result sent for request `id`, which must have been answered once.
|
||||
fn the_answer(sent: &[Message], id: i32) -> Value {
|
||||
let mine: Vec<&Response> = sent
|
||||
.iter()
|
||||
.filter_map(|m| match m {
|
||||
Message::Response(r) if r.id == RequestId::from(id) => Some(r),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(mine.len(), 1, "request {id} is answered exactly once: {sent:#?}");
|
||||
mine[0].response_result.clone().expect("a result")
|
||||
}
|
||||
|
||||
/// The hover asked again, with nothing waiting.
|
||||
fn asked_again(session: &mut Session, uri: &Uri) -> Value {
|
||||
session.batch(vec![hover(99, uri)]);
|
||||
the_answer(&session.drain(), 99)
|
||||
}
|
||||
|
||||
/// A rescan holds `[lens, older…, hover]`: whether the hover went ahead, and
|
||||
/// its one answer — which must be what the settled server then says.
|
||||
fn behind(session: &mut Session, uri: &Uri, older: Vec<Message>) -> (bool, Value) {
|
||||
let mut burst = vec![lens(1, uri)];
|
||||
burst.extend(older);
|
||||
burst.push(hover(2, uri));
|
||||
mid_rescan(session, burst);
|
||||
let early = probe::take_ahead().contains(&RequestId::from(2));
|
||||
settle(session);
|
||||
let first = the_answer(&session.drain(), 2);
|
||||
assert_eq!(first, asked_again(session, uri), "the answer the settled server gives");
|
||||
(early, first)
|
||||
}
|
||||
|
||||
fn waits_behind(session: &mut Session, uri: &Uri, older: Vec<Message>) -> Value {
|
||||
let (early, answer) = behind(session, uri, older);
|
||||
assert!(!early, "answered ahead of an older message that was not applied");
|
||||
answer
|
||||
}
|
||||
|
||||
fn goes_ahead_of(session: &mut Session, uri: &Uri, older: Vec<Message>) -> Value {
|
||||
let (early, answer) = behind(session, uri, older);
|
||||
assert!(early, "nothing ahead of it can change its buffer: it need not wait");
|
||||
answer
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// S1: a settings push ahead of the request, in one burst
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_hover_behind_an_edit_and_a_threshold_push_in_its_burst_is_answered_after_both() {
|
||||
// QA's `dirtypush2.py`: the edit used to be analyzed under the old
|
||||
// threshold for the hover, *before* the push behind it was applied.
|
||||
let (_tree, mut session, uri) = session("fa_pre_s1_dirty");
|
||||
session.batch(vec![changed(&uri, 2, &wide("sig_b")), push(threshold(1000)), hover(1, &uri)]);
|
||||
assert_eq!(the_answer(&session.drain(), 1), Value::Null, "the buffer is large by then");
|
||||
assert_eq!(asked_again(&mut session, &uri), Value::Null);
|
||||
assert!(probe::take_ahead().is_empty(), "nothing went ahead of an older notification");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hover_behind_a_threshold_push_in_its_burst_is_answered_after_it() {
|
||||
// The clean-buffer form.
|
||||
let (_tree, mut session, uri) = session("fa_pre_s1_clean");
|
||||
session.batch(vec![push(threshold(1000)), hover(1, &uri)]);
|
||||
assert_eq!(the_answer(&session.drain(), 1), Value::Null);
|
||||
assert_eq!(asked_again(&mut session, &uri), Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hover_goes_ahead_of_a_watcher_event_in_its_burst_but_not_of_a_push_beside_it() {
|
||||
// The same rule at the third place an older message can be unapplied:
|
||||
// the next notification of the request's own burst.
|
||||
let (tree, mut session, uri) = session_with("fa_pre_trigger", watching_progress());
|
||||
session.drain();
|
||||
let order = |session: &Session, id: i32| {
|
||||
let sent = session.drain();
|
||||
let at = |wanted: &dyn Fn(&Message) -> bool| sent.iter().position(wanted).expect("sent");
|
||||
let answered = at(&|m| matches!(m, Message::Response(r) if r.id == RequestId::from(id)));
|
||||
let bar = at(&|m| matches!(m, Message::Notification(n) if n.method == Progress::METHOD));
|
||||
(answered < bar, the_answer(&sent, id))
|
||||
};
|
||||
// A watcher event cannot change the buffer: the hover need not ride the
|
||||
// rescan it starts.
|
||||
tree.package("new1.sv", "fresh1");
|
||||
session.batch(vec![created(&tree.path.join("new1.sv")), hover(1, &uri)]);
|
||||
let (before_the_rescan, card) = order(&session, 1);
|
||||
assert!(before_the_rescan, "answered before the rescan began");
|
||||
assert_eq!(probe::take_ahead(), vec![RequestId::from(1)]);
|
||||
assert_eq!(card, asked_again(&mut session, &uri));
|
||||
assert_eq!(indexed(&session, "fresh1"), 1, "premise: the rescan ran");
|
||||
// A push between the two can: the hover is answered behind it.
|
||||
tree.package("new2.sv", "fresh2");
|
||||
let burst = vec![created(&tree.path.join("new2.sv")), push(threshold(1000)), hover(2, &uri)];
|
||||
session.batch(burst);
|
||||
let (before_the_rescan, answer) = order(&session, 2);
|
||||
assert!(!before_the_rescan && probe::take_ahead().is_empty());
|
||||
assert_eq!(answer, Value::Null, "large, as the push ahead of it said");
|
||||
// A push in front of the event is applied by then, and its effect seen.
|
||||
tree.package("new3.sv", "fresh3");
|
||||
let burst = vec![push(threshold(0)), created(&tree.path.join("new3.sv")), hover(3, &uri)];
|
||||
session.batch(burst);
|
||||
let (before_the_rescan, card) = order(&session, 3);
|
||||
assert!(before_the_rescan, "ahead of the event, behind the push");
|
||||
assert!(card.to_string().contains("sig_a"), "{card}");
|
||||
assert_eq!(card, asked_again(&mut session, &uri));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// (b) every older message that can change the buffer's answer is applied
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn it_waits_behind_a_held_threshold_push() {
|
||||
// The same hole S1 came through, by the other door: the push is held
|
||||
// behind a request, the hover behind the push.
|
||||
let (_tree, mut session, uri) = session("fa_pre_heldpush");
|
||||
assert_eq!(waits_behind(&mut session, &uri, vec![push(threshold(1000))]), Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_waits_behind_a_held_push_that_changes_nothing_it_reads() {
|
||||
// Which settings a push moves is not read off the wire: every push waits.
|
||||
let (_tree, mut session, uri) = session("fa_pre_heldsame");
|
||||
let card = waits_behind(&mut session, &uri, vec![push(threshold(4 * 1024 * 1024))]);
|
||||
assert!(card.to_string().contains("sig_a"), "{card}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_waits_behind_a_held_settings_answer() {
|
||||
// A client that answers the startup's pull late: the answer is a
|
||||
// response, never held on its own — but a burst behind a held request
|
||||
// takes it along.
|
||||
let pulling = ClientAbilities { configuration: true, ..Default::default() };
|
||||
let (_tree, mut session, uri) = session_with("fa_pre_heldanswer", pulling);
|
||||
let (pull, _) = configuration_request(&session);
|
||||
let answer = settings_answer(&pull, threshold(1000));
|
||||
assert_eq!(waits_behind(&mut session, &uri, vec![answer]), Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_waits_behind_a_settings_answer_in_the_tail_of_the_burst_that_started_the_rescan() {
|
||||
// `[created, settings answer]`: the rescan runs with the answer still
|
||||
// unapplied behind its trigger, and a hover arriving mid-scan is newer
|
||||
// than both.
|
||||
let tree = ordering_tree("fa_pre_tailanswer");
|
||||
tree.write("a/a.sv", &wide("sig_a"));
|
||||
let abilities = ClientAbilities { configuration: true, ..watching_progress() };
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
|
||||
let uri = session.open(&tree.path.join("a/a.sv"), &wide("sig_a"));
|
||||
let (pull, _) = configuration_request(&session);
|
||||
tree.package("z/new.sv", "new");
|
||||
let _ = (probe::take_counts(), probe::take_ahead());
|
||||
probe::script([vec![hover(2, &uri)]]);
|
||||
session
|
||||
.batch(vec![created(&tree.path.join("z/new.sv")), settings_answer(&pull, threshold(1000))]);
|
||||
assert!(probe::unarrived().is_empty(), "premise: the hover arrived mid-scan");
|
||||
assert!(probe::take_ahead().is_empty(), "not ahead of the unapplied answer");
|
||||
settle(&mut session);
|
||||
assert_eq!(the_answer(&session.drain(), 2), Value::Null);
|
||||
assert_eq!(asked_again(&mut session, &uri), Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_push_does_not_overtake_an_older_settings_answer_that_is_held() {
|
||||
// The answer is a state change like any notification: a newer push must
|
||||
// not be applied in front of it, or the older settings win.
|
||||
let pulling = ClientAbilities { configuration: true, ..Default::default() };
|
||||
let (_tree, mut session, uri) = session_with("fa_pre_order", pulling);
|
||||
let (pull, _) = configuration_request(&session);
|
||||
session.server.scanning = true;
|
||||
session.server.answering_a_rescan = true;
|
||||
session.batch(vec![lens(1, &uri), settings_answer(&pull, threshold(1000))]);
|
||||
session.batch(vec![push(threshold(0))]);
|
||||
session.server.scanning = false;
|
||||
session.server.answering_a_rescan = false;
|
||||
session.server.rescan_wanted = false;
|
||||
settle(&mut session);
|
||||
let card = asked_again(&mut session, &uri);
|
||||
assert!(card.to_string().contains("sig_a"), "the push was the client's last word: {card}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_settings_answer_does_not_overtake_an_older_push_that_is_held() {
|
||||
// The mirror image: the answer arrives in a burst of its own while a
|
||||
// rescan holds an older push. A response is not held as such — but this
|
||||
// one is a state change, and the push is older.
|
||||
let pulling = ClientAbilities { configuration: true, ..Default::default() };
|
||||
let (_tree, mut session, uri) = session_with("fa_pre_order2", pulling);
|
||||
let (pull, _) = configuration_request(&session);
|
||||
session.server.scanning = true;
|
||||
session.server.answering_a_rescan = true;
|
||||
session.batch(vec![lens(1, &uri), push(threshold(0))]);
|
||||
session.batch(vec![settings_answer(&pull, threshold(1000))]);
|
||||
session.server.scanning = false;
|
||||
session.server.answering_a_rescan = false;
|
||||
session.server.rescan_wanted = false;
|
||||
settle(&mut session);
|
||||
assert_eq!(asked_again(&mut session, &uri), Value::Null, "the answer was the last word");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_waits_while_the_settings_a_client_announced_have_not_been_answered() {
|
||||
// The pull model: an empty push says "ask me", and until the answer
|
||||
// lands the settings in force are known to be stale.
|
||||
let pulling = ClientAbilities { configuration: true, ..Default::default() };
|
||||
let (_tree, mut session, uri) = session_with("fa_pre_announced", pulling);
|
||||
session.drain();
|
||||
// The startup's pull was never answered; that alone holds nothing back.
|
||||
mid_rescan(&mut session, vec![lens(1, &uri), hover(2, &uri)]);
|
||||
assert_eq!(probe::take_ahead(), vec![RequestId::from(2)]);
|
||||
settle(&mut session);
|
||||
session.drain();
|
||||
|
||||
session
|
||||
.batch(vec![note(DidChangeConfiguration::METHOD, serde_json::json!({ "settings": null }))]);
|
||||
let (pull, _) = configuration_request(&session);
|
||||
// Only the pull's own answer ends the wait: an answer to anything else
|
||||
// the server asked says nothing about the settings (QA, escalation round).
|
||||
let stray = Response::new_ok(RequestId::from(987_654), Value::Null);
|
||||
session.batch(vec![Message::Response(stray)]);
|
||||
mid_rescan(&mut session, vec![lens(3, &uri), hover(4, &uri)]);
|
||||
assert!(probe::take_ahead().is_empty(), "the announced settings are still in flight");
|
||||
session.batch(vec![settings_answer(&pull, threshold(1000))]);
|
||||
settle(&mut session);
|
||||
assert_eq!(the_answer(&session.drain(), 4), Value::Null);
|
||||
assert_eq!(asked_again(&mut session, &uri), Value::Null);
|
||||
// Answered: the path is open again.
|
||||
mid_rescan(&mut session, vec![lens(5, &uri), hover(6, &uri)]);
|
||||
assert_eq!(probe::take_ahead(), vec![RequestId::from(6)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_waits_behind_a_held_change_close_reopen_or_save_of_its_own_buffer() {
|
||||
let doc = |uri: &Uri| serde_json::json!({ "textDocument": { "uri": uri } });
|
||||
let (_tree, mut session, uri) = session("fa_pre_own");
|
||||
let card = waits_behind(&mut session, &uri, vec![changed(&uri, 2, &wide("sig_b"))]);
|
||||
assert!(card.to_string().contains("sig_b"), "{card}");
|
||||
let reopened =
|
||||
vec![note(DidCloseTextDocument::METHOD, doc(&uri)), opened(&uri, &wide("sig_c"))];
|
||||
let card = waits_behind(&mut session, &uri, reopened);
|
||||
assert!(card.to_string().contains("sig_c"), "{card}");
|
||||
let saved = serde_json::json!({ "textDocument": { "uri": uri }, "text": wide("sig_d") });
|
||||
let card = waits_behind(&mut session, &uri, vec![note(DidSaveTextDocument::METHOD, saved)]);
|
||||
assert!(card.to_string().contains("sig_d"), "{card}");
|
||||
let closed = vec![note(DidCloseTextDocument::METHOD, doc(&uri))];
|
||||
assert_eq!(waits_behind(&mut session, &uri, closed), Value::Null, "(a): no longer open");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_waits_behind_every_held_notification_not_proven_to_leave_its_buffer_alone() {
|
||||
let (tree, mut session, uri) = session("fa_pre_any");
|
||||
let elsewhere = path_to_uri(&tree.path.join("gone.sv")).expect("uri");
|
||||
let folder = serde_json::json!({ "uri": path_to_uri(&tree.path.join("more")).expect("uri"),
|
||||
"name": "more" });
|
||||
let others = [
|
||||
note(
|
||||
DidChangeWorkspaceFolders::METHOD,
|
||||
serde_json::json!({ "event": { "added": [folder], "removed": [] } }),
|
||||
),
|
||||
note(
|
||||
DidRenameFiles::METHOD,
|
||||
serde_json::json!({ "files": [{ "oldUri": elsewhere, "newUri": elsewhere }] }),
|
||||
),
|
||||
note(DidDeleteFiles::METHOD, serde_json::json!({ "files": [{ "uri": elsewhere }] })),
|
||||
// A notification the server does not know is not known to be safe.
|
||||
note("$/setTrace", serde_json::json!({ "value": "off" })),
|
||||
// Nor is one that should name a buffer and does not.
|
||||
note(DidChangeTextDocument::METHOD, serde_json::json!({ "contentChanges": [] })),
|
||||
];
|
||||
for other in others {
|
||||
let card = waits_behind(&mut session, &uri, vec![other]);
|
||||
assert!(card.to_string().contains("sig_a"), "{card}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_goes_ahead_of_held_messages_that_cannot_change_its_buffer() {
|
||||
let (tree, mut session, uri) = session("fa_pre_other");
|
||||
let b = session.open(&tree.path.join("b.sv"), "module qa_b;\nendmodule\n");
|
||||
session.drain();
|
||||
tree.package("new.sv", "fresh_pkg");
|
||||
let others = [
|
||||
// Another buffer's edit, another buffer opened.
|
||||
changed(&b, 2, "module qa_b;\n logic x;\nendmodule\n"),
|
||||
opened(&path_to_uri(&tree.path.join("c.sv")).expect("uri"), "module qa_c;\nendmodule\n"),
|
||||
// What is on disk moves the index, never a buffer's own analysis —
|
||||
// not even when it names the buffer's own file.
|
||||
created(&tree.path.join("new.sv")),
|
||||
created(&tree.path.join("a.sv")),
|
||||
// A cancel for something else, and an answer the server acts on
|
||||
// without touching a buffer.
|
||||
note(Cancel::METHOD, serde_json::json!({ "id": 12345 })),
|
||||
Message::Response(Response::new_ok(RequestId::from("nobody".to_string()), Value::Null)),
|
||||
];
|
||||
for other in others {
|
||||
let card = goes_ahead_of(&mut session, &uri, vec![other]);
|
||||
assert!(card.to_string().contains("sig_a"), "{card}");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// (a) open, (c) analyzed under the settings in force, (d) not in staging
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_is_not_open_is_not_answered_ahead() {
|
||||
let (tree, mut session, _) = session("fa_pre_closed");
|
||||
let never = path_to_uri(&tree.path.join("b.sv")).expect("uri");
|
||||
mid_rescan(&mut session, vec![hover(2, &never)]);
|
||||
assert!(probe::take_ahead().is_empty());
|
||||
settle(&mut session);
|
||||
assert_eq!(the_answer(&session.drain(), 2), Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dirty_buffer_is_analyzed_for_it_under_the_settings_in_force() {
|
||||
let (_tree, mut session, uri) = session("fa_pre_inforce");
|
||||
session.batch(vec![push(threshold(1000))]);
|
||||
session.batch(vec![changed(&uri, 2, &wide("sig_b"))]);
|
||||
assert_eq!(session.server.dirty.len(), 1, "premise: the edit is not analyzed yet");
|
||||
assert_eq!(goes_ahead_of(&mut session, &uri, Vec::new()), Value::Null, "large, as pushed");
|
||||
session.batch(vec![push(threshold(0))]);
|
||||
session.batch(vec![changed(&uri, 3, &wide("sig_c"))]);
|
||||
let card = goes_ahead_of(&mut session, &uri, Vec::new());
|
||||
assert!(card.to_string().contains("sig_c"), "{card}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_staging_held_behind_a_push_is_not_released_ahead_of_it() {
|
||||
// `[open, lens, push, hover]`, then the pull's answer: the settings have
|
||||
// landed, but the hover is still behind a push nobody has applied.
|
||||
let tree = Tree::new("fa_pre_staged");
|
||||
tree.write("a.sv", &wide("sig_a"));
|
||||
let uri = path_to_uri(&tree.path.join("a.sv")).expect("uri");
|
||||
let pull = RequestId::from("lucisv-0".to_string());
|
||||
let queued = vec![
|
||||
opened(&uri, &wide("sig_a")),
|
||||
lens(1, &uri),
|
||||
push(threshold(1000)),
|
||||
hover(2, &uri),
|
||||
settings_answer(&pull, threshold(0)),
|
||||
];
|
||||
let abilities = ClientAbilities { configuration: true, ..Default::default() };
|
||||
let _ = probe::take_ahead();
|
||||
let mut session =
|
||||
Session::staged(vec![tree.path.clone()], abilities, false, CONFIGURATION_WAIT, queued);
|
||||
assert!(probe::take_ahead().is_empty(), "not ahead of the push it was sent behind");
|
||||
settle(&mut session);
|
||||
assert_eq!(the_answer(&session.drain(), 2), Value::Null);
|
||||
assert_eq!(asked_again(&mut session, &uri), Value::Null);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// the colours: a guess is always recorded as one
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn colours_answered_ahead_of_a_waiting_index_change_are_checked_once_it_has_landed() {
|
||||
// No scan is running, but something is held — as when a replayed message
|
||||
// started a rescan that held newer ones — so the burst waits, and a
|
||||
// `full` goes ahead of the watcher event that will give `W` a meaning.
|
||||
let tree = Tree::new("fa_pre_colours");
|
||||
let top = "module top;\n import p::*;\n logic [W-1:0] x;\nendmodule\n";
|
||||
tree.write("top.sv", top);
|
||||
let refreshing = ClientAbilities { semantic_tokens_refresh: true, ..Default::default() };
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], refreshing);
|
||||
let uri = session.open(&tree.path.join("top.sv"), top);
|
||||
session.server.refresh_tokens_if_stale();
|
||||
let full = |id: i32| {
|
||||
let params = serde_json::json!({ "textDocument": { "uri": uri } });
|
||||
ask(id, SemanticTokensFullRequest::METHOD, params)
|
||||
};
|
||||
let _ = (session.drain(), probe::take_ahead());
|
||||
tree.write("p.sv", "package p;\n localparam int W = 4;\nendpackage\n");
|
||||
session.server.held = vec![lens(7, &uri)];
|
||||
session.batch(vec![lens(1, &uri), created(&tree.path.join("p.sv")), full(2)]);
|
||||
assert_eq!(probe::take_ahead(), vec![RequestId::from(2)], "premise: the colours went ahead");
|
||||
let guess = the_answer(&session.drain(), 2);
|
||||
settle(&mut session);
|
||||
session.server.refresh_tokens_if_stale();
|
||||
let sent = session.drain();
|
||||
let refreshes = sent
|
||||
.iter()
|
||||
.filter(
|
||||
|m| matches!(m, Message::Request(r) if r.method == "workspace/semanticTokens/refresh"),
|
||||
)
|
||||
.count();
|
||||
session.batch(vec![full(3)]);
|
||||
let settled = the_answer(&session.drain(), 3);
|
||||
assert_ne!(guess["data"], settled["data"], "premise: the event changed the colours");
|
||||
assert_eq!(refreshes, 1, "so the client is asked to fetch them again");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// the table the rule is read from
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
/// The `X::METHOD =>` arms of `handle_notification`'s table.
|
||||
fn handled_notifications() -> Vec<String> {
|
||||
include_str!("../notification.rs")
|
||||
.lines()
|
||||
.filter_map(|line| line.trim().split_once("::METHOD =>"))
|
||||
.map(|(path, _)| path.rsplit("::").next().unwrap_or(path).to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_notification_the_server_handles_says_which_buffers_it_can_reach() {
|
||||
use lsp_types::notification::Notification as _;
|
||||
let named = |type_name: &str| match type_name {
|
||||
"DidOpenTextDocument" => DidOpenTextDocument::METHOD,
|
||||
"DidChangeTextDocument" => DidChangeTextDocument::METHOD,
|
||||
"DidSaveTextDocument" => DidSaveTextDocument::METHOD,
|
||||
"DidCloseTextDocument" => DidCloseTextDocument::METHOD,
|
||||
"DidChangeWatchedFiles" => DidChangeWatchedFiles::METHOD,
|
||||
"DidRenameFiles" => DidRenameFiles::METHOD,
|
||||
"DidDeleteFiles" => DidDeleteFiles::METHOD,
|
||||
"DidChangeConfiguration" => DidChangeConfiguration::METHOD,
|
||||
"DidChangeWorkspaceFolders" => DidChangeWorkspaceFolders::METHOD,
|
||||
other => panic!("a new notification arm, {other}: give it a row in `ahead::REACH`"),
|
||||
};
|
||||
let mut handled: Vec<&str> = handled_notifications().iter().map(|n| named(n)).collect();
|
||||
// The loop consumes a cancel itself, before the table.
|
||||
handled.push(Cancel::METHOD);
|
||||
handled.sort_unstable();
|
||||
let mut rows: Vec<&str> = REACH.iter().map(|(method, _)| *method).collect();
|
||||
rows.sort_unstable();
|
||||
assert_eq!(rows, handled, "one row per notification the server handles, and no other");
|
||||
assert!(handled.len() >= 10, "the arms were found: {handled:?}");
|
||||
// Only the four that replace one buffer's text may be judged by name.
|
||||
let by_name: Vec<&str> =
|
||||
REACH.iter().filter(|(_, reach)| *reach == Reach::Named).map(|(m, _)| *m).collect();
|
||||
assert_eq!(by_name.len(), 4, "{by_name:?}");
|
||||
assert!(by_name.iter().all(|m| m.starts_with("textDocument/did")), "{by_name:?}");
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
//! Same file first **around the settings answer** (QA Q1 and R1 of
|
||||
//! `docs/features/fast-actions/README.md`): the one setting a buffer's
|
||||
//! `Document` depends on is `largeFile.threshold`, read where the buffer is
|
||||
//! analyzed. A buffer analyzed before the startup's settings answer — opened
|
||||
//! then, or edited and flushed then — is re-analyzed when the answer
|
||||
//! classifies it differently, and so is every open buffer whenever the
|
||||
//! threshold changes later; whatever was asked meanwhile is answered as a
|
||||
//! server given the settings first answers it, and right after the answer.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The startup pull's answer (`lucisv-0`: the first request a staged session
|
||||
/// makes), carrying `section` as the `lucisv` settings.
|
||||
fn settings(section: Value) -> Message {
|
||||
Message::Response(Response::new_ok(
|
||||
RequestId::from("lucisv-0".to_string()),
|
||||
serde_json::json!([section]),
|
||||
))
|
||||
}
|
||||
|
||||
fn threshold(bytes: u64) -> Value {
|
||||
serde_json::json!({ "index": { "scope": "workspace" }, "largeFile": { "threshold": bytes } })
|
||||
}
|
||||
|
||||
fn opened(uri: &Uri, text: &str) -> Message {
|
||||
Message::Notification(lsp_server::Notification::new(
|
||||
DidOpenTextDocument::METHOD.to_string(),
|
||||
serde_json::json!({ "textDocument": {
|
||||
"uri": uri, "languageId": "systemverilog", "version": 1, "text": text,
|
||||
}}),
|
||||
))
|
||||
}
|
||||
|
||||
/// A hover on `sig_a`, line 1.
|
||||
fn hover(id: i32, uri: &Uri) -> Message {
|
||||
Message::Request(Request::new(
|
||||
RequestId::from(id),
|
||||
HoverRequest::METHOD.to_string(),
|
||||
serde_json::json!({ "textDocument": { "uri": uri },
|
||||
"position": { "line": 1, "character": 10 } }),
|
||||
))
|
||||
}
|
||||
|
||||
const SMALL: &str = "module qa_a;\n logic sig_a;\nendmodule\n";
|
||||
|
||||
/// The result a session sent for request `id`.
|
||||
fn answer(sent: &[Message], id: i32) -> Value {
|
||||
sent.iter()
|
||||
.find_map(|m| match m {
|
||||
Message::Response(r) if r.id == RequestId::from(id) => {
|
||||
Some(r.response_result.clone().expect("a result"))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| panic!("request {id} answered: {sent:#?}"))
|
||||
}
|
||||
|
||||
/// A staged session that has sent, in one burst before the settings answer:
|
||||
/// `before`, a hover, then the answer `section`. Returns the hover's answer,
|
||||
/// whether it was sent before anything the startup held was replayed, and a
|
||||
/// hover asked again once everything has settled.
|
||||
fn staged(tree: &Tree, before: Vec<Message>, section: Value) -> (Value, bool, Value) {
|
||||
let uri = path_to_uri(&tree.path.join("a.sv")).expect("uri");
|
||||
let mut queued = before;
|
||||
queued.push(hover(1, &uri));
|
||||
queued.push(settings(section));
|
||||
let abilities = ClientAbilities { configuration: true, ..Default::default() };
|
||||
let mut session =
|
||||
Session::staged(vec![tree.path.clone()], abilities, false, CONFIGURATION_WAIT, queued);
|
||||
let mut sent = session.drain();
|
||||
let at_once =
|
||||
sent.iter().any(|m| matches!(m, Message::Response(r) if r.id == RequestId::from(1)));
|
||||
// What `run` does next: replay whatever the startup held.
|
||||
let held = std::mem::take(&mut session.server.held);
|
||||
session.batch(held);
|
||||
sent.extend(session.drain());
|
||||
let first = answer(&sent, 1);
|
||||
session.batch(vec![hover(2, &uri)]);
|
||||
let again = answer(&session.drain(), 2);
|
||||
(first, at_once, again)
|
||||
}
|
||||
|
||||
/// What a session that had the settings first answers for the same buffer.
|
||||
fn fresh(tree: &Tree, bytes: u64, text: &str) -> Value {
|
||||
let settled = ClientSettings {
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
large_file_threshold: bytes,
|
||||
..Default::default()
|
||||
};
|
||||
let mut session =
|
||||
Session::started(vec![tree.path.clone()], ClientAbilities::default(), settled);
|
||||
let uri = session.open(&tree.path.join("a.sv"), text);
|
||||
session.batch(vec![hover(3, &uri)]);
|
||||
answer(&session.drain(), 3)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_edited_before_a_small_threshold_arrives_is_not_analyzed_for_an_early_answer() {
|
||||
// Default threshold 4 MiB, the user's 300 bytes: the edit makes the
|
||||
// buffer large under the user's settings and only under them.
|
||||
let tree = Tree::new("fa_stage_small");
|
||||
tree.write("a.sv", SMALL);
|
||||
let uri = path_to_uri(&tree.path.join("a.sv")).expect("uri");
|
||||
let big = format!("{SMALL}{}", "// padding padding padding\n".repeat(30));
|
||||
assert!(big.len() > 300 && big.len() < 4 * 1024 * 1024);
|
||||
let (first, _, again) =
|
||||
staged(&tree, vec![opened(&uri, SMALL), changed(&uri, 2, &big)], threshold(300));
|
||||
assert_eq!(first, Value::Null, "the large-file answer, not a card built under the defaults");
|
||||
assert_eq!(again, Value::Null, "and the buffer stays on the fast path");
|
||||
assert_eq!(first, fresh(&tree, 300, &big), "what a session given the settings first says");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_edited_before_a_large_threshold_arrives_is_not_put_on_the_fast_path() {
|
||||
// The other direction: the default calls a 5 MiB buffer large, the
|
||||
// user's 8 MiB threshold does not.
|
||||
let tree = Tree::new("fa_stage_large");
|
||||
tree.write("a.sv", SMALL);
|
||||
let uri = path_to_uri(&tree.path.join("a.sv")).expect("uri");
|
||||
let big = format!("{SMALL}/*{}*/\n", "x".repeat(5 * 1024 * 1024));
|
||||
let (first, _, again) = staged(
|
||||
&tree,
|
||||
vec![opened(&uri, SMALL), changed(&uri, 2, &big)],
|
||||
threshold(8 * 1024 * 1024),
|
||||
);
|
||||
let card = first.to_string();
|
||||
assert!(card.contains("sig_a"), "analyzed under the user's threshold: {card}");
|
||||
assert_eq!(first, again);
|
||||
assert_eq!(first, fresh(&tree, 8 * 1024 * 1024, &big));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_opened_before_a_small_threshold_arrives_answers_as_a_fresh_server_does() {
|
||||
// Opened in staging, it is analyzed under the 4 MiB default; the answer
|
||||
// says 10 bytes, so it is re-analyzed onto the fast path — and the hover
|
||||
// asked before the answer is answered right after it, from that.
|
||||
let tree = Tree::new("fa_stage_open");
|
||||
tree.write("a.sv", SMALL);
|
||||
let uri = path_to_uri(&tree.path.join("a.sv")).expect("uri");
|
||||
let (first, at_once, again) = staged(&tree, vec![opened(&uri, SMALL)], threshold(10));
|
||||
assert_eq!(first, fresh(&tree, 10, SMALL), "what a server given the settings first says");
|
||||
assert_eq!(first, Value::Null);
|
||||
assert_eq!(first, again);
|
||||
assert!(at_once, "answered when the settings landed, not after the scan's head phase");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_opened_before_a_large_threshold_arrives_leaves_the_fast_path() {
|
||||
let tree = Tree::new("fa_stage_open_big");
|
||||
let big = format!("{SMALL}/*{}*/\n", "x".repeat(5 * 1024 * 1024));
|
||||
tree.write("a.sv", &big);
|
||||
let uri = path_to_uri(&tree.path.join("a.sv")).expect("uri");
|
||||
let (first, _, again) = staged(&tree, vec![opened(&uri, &big)], threshold(8 * 1024 * 1024));
|
||||
assert!(first.to_string().contains("sig_a"), "analyzed in full: {first}");
|
||||
assert_eq!(first, again);
|
||||
assert_eq!(first, fresh(&tree, 8 * 1024 * 1024, &big));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_edited_and_flushed_by_another_open_before_the_settings_is_reclassified() {
|
||||
// QA's s6: the edit to `a.sv` is flushed — under the default threshold —
|
||||
// by the `didOpen` of `b.sv` applied during staging.
|
||||
let tree = Tree::new("fa_stage_flushed");
|
||||
tree.write("a.sv", SMALL);
|
||||
tree.write("b.sv", "module qa_b;\nendmodule\n");
|
||||
let uri = path_to_uri(&tree.path.join("a.sv")).expect("uri");
|
||||
let b = path_to_uri(&tree.path.join("b.sv")).expect("uri");
|
||||
let big = format!("{SMALL}{}", "// padding padding padding\n".repeat(30));
|
||||
let before =
|
||||
vec![opened(&uri, SMALL), changed(&uri, 2, &big), opened(&b, "module qa_b;\nendmodule\n")];
|
||||
let (first, _, again) = staged(&tree, before, threshold(300));
|
||||
assert_eq!(first, Value::Null);
|
||||
assert_eq!(again, Value::Null);
|
||||
assert_eq!(first, fresh(&tree, 300, &big));
|
||||
}
|
||||
|
||||
/// A settled session with `a.sv` open, and the hover on it after a
|
||||
/// `didChangeConfiguration` push of `section`; the parses the push cost.
|
||||
fn pushed(session: &mut Session, uri: &Uri, section: Value, id: i32) -> (Value, u64) {
|
||||
let parses = vlog_parser::stats::parses();
|
||||
session.notify(
|
||||
lsp_types::notification::DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": section } }),
|
||||
);
|
||||
let cost = vlog_parser::stats::parses() - parses;
|
||||
session.drain();
|
||||
session.batch(vec![hover(id, uri)]);
|
||||
(answer(&session.drain(), id), cost)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_threshold_changed_mid_session_moves_an_open_buffer_both_ways_and_nothing_else_does() {
|
||||
let tree = Tree::new("fa_stage_mid");
|
||||
tree.write("a.sv", SMALL);
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("a.sv"), SMALL);
|
||||
session.drain();
|
||||
let (card, _) = pushed(&mut session, &uri, threshold(4 * 1024 * 1024), 1);
|
||||
assert!(card.to_string().contains("sig_a"), "{card}");
|
||||
let (down, cost) = pushed(&mut session, &uri, threshold(10), 2);
|
||||
assert_eq!(down, Value::Null, "onto the fast path, as a fresh server says");
|
||||
assert_eq!(down, fresh(&tree, 10, SMALL));
|
||||
assert_eq!(cost, 1, "the one buffer that changed mode, re-analyzed once");
|
||||
let (up, cost) = pushed(&mut session, &uri, threshold(4 * 1024 * 1024), 3);
|
||||
assert_eq!(up, card, "back off it");
|
||||
assert_eq!(cost, 1, "the one buffer that changed mode, parsed once");
|
||||
let (same, cost) = pushed(&mut session, &uri, threshold(4 * 1024 * 1024), 4);
|
||||
assert_eq!(same, card);
|
||||
assert_eq!(cost, 0, "a push that leaves the threshold alone analyzes nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_changes_mode_has_its_colours_asked_for_again() {
|
||||
let tree = Tree::new("fa_stage_colours");
|
||||
tree.write("a.sv", SMALL);
|
||||
let refreshing = ClientAbilities { semantic_tokens_refresh: true, ..Default::default() };
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], refreshing);
|
||||
session.open(&tree.path.join("a.sv"), SMALL);
|
||||
session.drain();
|
||||
let refreshes = |session: &mut Session, section: Value| {
|
||||
session.notify(
|
||||
lsp_types::notification::DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": section } }),
|
||||
);
|
||||
let sent = session.drain();
|
||||
sent.iter()
|
||||
.filter(|m| matches!(m, Message::Request(r) if r.method == "workspace/semanticTokens/refresh"))
|
||||
.count()
|
||||
};
|
||||
assert_eq!(refreshes(&mut session, threshold(4 * 1024 * 1024)), 0, "nothing moved");
|
||||
assert_eq!(refreshes(&mut session, threshold(10)), 1, "the buffer went onto the fast path");
|
||||
assert_eq!(refreshes(&mut session, threshold(20)), 0, "still large: nothing moved");
|
||||
}
|
||||
@@ -341,7 +341,7 @@ fn a_large_buffer_is_present_in_workspace_diagnostics_with_an_empty_full_report(
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_threshold_arrives_by_push_and_by_pull_and_takes_effect_on_the_next_change() {
|
||||
fn the_threshold_arrives_by_push_and_by_pull_and_takes_effect_on_open_buffers_at_once() {
|
||||
let tree = Tree::new("largethreshold");
|
||||
let path = tree.path.join("net.v");
|
||||
tree.write("net.v", &big_source());
|
||||
@@ -351,21 +351,22 @@ fn the_threshold_arrives_by_push_and_by_pull_and_takes_effect_on_the_next_change
|
||||
let uri = session.open(&path, &big_source());
|
||||
assert!(!session.server.workspace.document(&uri).expect("open").large);
|
||||
|
||||
// Pushed. The buffer already open does not change mode on the spot —
|
||||
// the decision is taken where a document is built.
|
||||
// Pushed. Since fast-actions R1 the buffer already open changes mode on
|
||||
// the spot, as a server given the setting first would have built it —
|
||||
// it used to keep its mode until its next change.
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "largeFile": { "threshold": 100 } } } }),
|
||||
);
|
||||
assert_eq!(session.server.workspace.client_settings().large_file_threshold, 100);
|
||||
assert!(
|
||||
!session.server.workspace.document(&uri).expect("open").large,
|
||||
"the open buffer keeps the mode it was built in"
|
||||
session.server.workspace.document(&uri).expect("open").large,
|
||||
"the open buffer takes the fast path when the threshold says so"
|
||||
);
|
||||
change(&mut session, &uri, 2, serde_json::json!([{ "text": big_source() }]));
|
||||
assert!(
|
||||
session.server.workspace.document(&uri).expect("open").large,
|
||||
"and takes the fast path at its next change"
|
||||
"and keeps it through its next change"
|
||||
);
|
||||
|
||||
// Pulled: the same value through the other door.
|
||||
|
||||
@@ -47,7 +47,13 @@ use crate::{design_hierarchy, diagnostics, format, lens, pairs, ports};
|
||||
|
||||
mod apply_edit;
|
||||
mod cancel;
|
||||
mod caret_boundary;
|
||||
mod code_action;
|
||||
mod fast_actions;
|
||||
mod fast_actions_bursts;
|
||||
mod fast_actions_differential;
|
||||
mod fast_actions_precondition;
|
||||
mod fast_actions_staging;
|
||||
mod file_ops;
|
||||
mod folders;
|
||||
mod formatting;
|
||||
@@ -57,6 +63,7 @@ mod index;
|
||||
mod large_file;
|
||||
mod lint_snapshot;
|
||||
mod localized_reindex;
|
||||
mod ordering_random;
|
||||
mod progress;
|
||||
mod pull_diagnostics;
|
||||
mod qa_generate_label;
|
||||
@@ -68,6 +75,7 @@ mod rename_implicit;
|
||||
mod rename_top_rooted_scope;
|
||||
mod requests;
|
||||
mod scan;
|
||||
mod scan_ordering;
|
||||
mod scan_trace;
|
||||
mod settings;
|
||||
mod startup;
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
//! Random interleavings of the client's bursts against the real loop, mid-scan
|
||||
//! and between scans (`docs/features/scan-ordering/README.md`, B and C).
|
||||
//!
|
||||
//! A seeded client sends bursts of requests, full and incremental
|
||||
//! `didChange`s for three documents, opens, closes, cancels and watcher
|
||||
//! events that cost a whole rescan; some bursts land at a scan's interleave
|
||||
//! points ([`probe::script`]), the rest between scans. After every round the
|
||||
//! server must hold exactly the buffers the client holds, with exactly the
|
||||
//! client's text; every request must be answered exactly once; no scan may
|
||||
//! hand its held batch back more often than the `didOpen`s and scans it saw
|
||||
//! can explain; and at the end, the server must answer what a fresh server
|
||||
//! on the same files and buffers answers.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::super::probe;
|
||||
use super::scan_ordering::{ask, closed, created, note, opened, ordering_tree, settle, A_TEXT};
|
||||
use super::*;
|
||||
|
||||
/// A small deterministic generator — xorshift64, no dependency.
|
||||
struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
fn new(seed: u64) -> Rng {
|
||||
Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
|
||||
}
|
||||
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
|
||||
fn below(&mut self, n: usize) -> usize {
|
||||
(self.next() % n.max(1) as u64) as usize
|
||||
}
|
||||
|
||||
fn percent(&mut self, p: u64) -> bool {
|
||||
self.next() % 100 < p
|
||||
}
|
||||
}
|
||||
|
||||
/// The client: what it has open, with what text, and what it has asked.
|
||||
struct Client {
|
||||
rng: Rng,
|
||||
docs: Vec<(Uri, String)>,
|
||||
open: HashMap<Uri, (u32, String)>,
|
||||
asked: Vec<i32>,
|
||||
next_id: i32,
|
||||
created: Vec<PathBuf>,
|
||||
root: PathBuf,
|
||||
/// `didOpen`s sent this round — what may re-order a scan.
|
||||
opens: usize,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
fn new(seed: u64, tree: &Tree) -> Client {
|
||||
let docs = ["a/a.sv", "b/b.sv", "c/c.sv"]
|
||||
.iter()
|
||||
.map(|rel| {
|
||||
let path = tree.path.join(rel);
|
||||
let text = std::fs::read_to_string(&path).expect("a document");
|
||||
(path_to_uri(&path).expect("uri"), text)
|
||||
})
|
||||
.collect();
|
||||
Client {
|
||||
rng: Rng::new(seed),
|
||||
docs,
|
||||
open: HashMap::new(),
|
||||
asked: Vec::new(),
|
||||
next_id: 1,
|
||||
created: Vec::new(),
|
||||
root: tree.path.clone(),
|
||||
opens: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn doc(&mut self) -> Uri {
|
||||
let n = self.rng.below(self.docs.len());
|
||||
self.docs[n].0.clone()
|
||||
}
|
||||
|
||||
fn burst(&mut self) -> Vec<Message> {
|
||||
(0..1 + self.rng.below(4)).map(|_| self.message()).collect()
|
||||
}
|
||||
|
||||
/// One message, applied to the client's own view as it is sent.
|
||||
fn message(&mut self) -> Message {
|
||||
let uri = self.doc();
|
||||
let roll = self.rng.below(100);
|
||||
match (roll, self.open.contains_key(&uri)) {
|
||||
(0..=29, true) => self.change(&uri),
|
||||
(30..=39, true) => {
|
||||
self.open.remove(&uri);
|
||||
closed(&uri)
|
||||
}
|
||||
(0..=39, false) => self.reopen(&uri),
|
||||
(40..=49, _) => self.watcher_event(),
|
||||
(50..=57, _) if !self.asked.is_empty() => {
|
||||
let id = self.asked[self.rng.below(self.asked.len())];
|
||||
note(Cancel::METHOD, serde_json::json!({ "id": id }))
|
||||
}
|
||||
_ => self.request(&uri),
|
||||
}
|
||||
}
|
||||
|
||||
fn reopen(&mut self, uri: &Uri) -> Message {
|
||||
let disk = self.docs.iter().find(|(u, _)| u == uri).map(|(_, t)| t.clone());
|
||||
let text = disk.unwrap_or_default() + &format!("// opened {}\n", self.rng.below(1000));
|
||||
self.open.insert(uri.clone(), (1, text.clone()));
|
||||
self.opens += 1;
|
||||
opened(uri, &text)
|
||||
}
|
||||
|
||||
/// A full or an incremental `didChange`, ranges in the text the client
|
||||
/// holds right now — which is what makes a reordering visible.
|
||||
fn change(&mut self, uri: &Uri) -> Message {
|
||||
let n = self.rng.below(1000);
|
||||
let full = self.rng.percent(30);
|
||||
let lines = self.open[uri].1.split_inclusive('\n').count() as u32;
|
||||
let line = self.rng.below(lines as usize + 1) as u32;
|
||||
let (version, text) = self.open.get_mut(uri).expect("open");
|
||||
*version += 1;
|
||||
let mut kept: Vec<String> = text.split_inclusive('\n').map(str::to_string).collect();
|
||||
let change = if full {
|
||||
kept.push(format!("module m{n};\nendmodule\n"));
|
||||
serde_json::json!({ "text": kept.concat() })
|
||||
} else if lines > 3 && n.is_multiple_of(3) {
|
||||
kept.remove(line.min(lines - 1) as usize);
|
||||
let at = line.min(lines - 1);
|
||||
serde_json::json!({
|
||||
"range": { "start": { "line": at, "character": 0 },
|
||||
"end": { "line": at + 1, "character": 0 } },
|
||||
"text": "",
|
||||
})
|
||||
} else {
|
||||
kept.insert(line as usize, format!("// e{n}\n"));
|
||||
let at = serde_json::json!({ "line": line, "character": 0 });
|
||||
serde_json::json!({ "range": { "start": at, "end": at }, "text": format!("// e{n}\n") })
|
||||
};
|
||||
*text = kept.concat();
|
||||
note(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": *version },
|
||||
"contentChanges": [change],
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// A file created on disk, or one created earlier deleted, and the
|
||||
/// watcher's word for it. A creation costs a whole rescan.
|
||||
fn watcher_event(&mut self) -> Message {
|
||||
if !self.created.is_empty() && self.rng.percent(30) {
|
||||
let path = self.created.swap_remove(self.rng.below(self.created.len()));
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
return note(
|
||||
DidChangeWatchedFiles::METHOD,
|
||||
serde_json::json!({ "changes": [{ "uri": uri, "type": 3 }] }),
|
||||
);
|
||||
}
|
||||
self.created_file()
|
||||
}
|
||||
|
||||
/// A new package file on disk, and the watcher's word for it.
|
||||
fn created_file(&mut self) -> Message {
|
||||
let name = format!("r{}", self.next_id * 1000 + self.rng.below(1000) as i32);
|
||||
let path = self.root.join("z").join(format!("{name}.sv"));
|
||||
std::fs::write(&path, format!("package {name};\n localparam K = 1;\nendpackage\n"))
|
||||
.expect("write");
|
||||
self.created.push(path.clone());
|
||||
created(&path)
|
||||
}
|
||||
|
||||
fn request(&mut self, uri: &Uri) -> Message {
|
||||
let id = self.next_id;
|
||||
self.next_id += 1;
|
||||
self.asked.push(id);
|
||||
let at = serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": self.rng.below(4), "character": self.rng.below(12) },
|
||||
});
|
||||
match self.rng.below(4) {
|
||||
0 => ask(id, HoverRequest::METHOD, at),
|
||||
1 => ask(id, GotoDefinition::METHOD, at),
|
||||
2 => ask(id, WorkspaceSymbolRequest::METHOD, serde_json::json!({ "query": "p00" })),
|
||||
_ => ask(
|
||||
id,
|
||||
DocumentSymbolRequest::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What one round's messages from the server came to.
|
||||
#[derive(Default)]
|
||||
struct Heard {
|
||||
answers: HashMap<RequestId, usize>,
|
||||
scans: usize,
|
||||
}
|
||||
|
||||
fn hear(session: &Session, heard: &mut Heard) {
|
||||
for message in session.drain() {
|
||||
match message {
|
||||
Message::Response(response) => *heard.answers.entry(response.id).or_default() += 1,
|
||||
Message::Notification(n)
|
||||
if n.method == Progress::METHOD && n.params["value"]["kind"] == "begin" =>
|
||||
{
|
||||
heard.scans += 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The server holds exactly the client's buffers, with the client's text.
|
||||
fn same_buffers(session: &Session, client: &Client, at: &str) {
|
||||
let mut held: Vec<Uri> = session.server.workspace.open_uris();
|
||||
held.sort_by_key(|uri| uri.to_string());
|
||||
let mut wanted: Vec<Uri> = client.open.keys().cloned().collect();
|
||||
wanted.sort_by_key(|uri| uri.to_string());
|
||||
assert_eq!(held, wanted, "{at}: the open buffers");
|
||||
for (uri, (_, text)) in &client.open {
|
||||
assert_eq!(&buffer(session, uri), text, "{at}: the text of {uri:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The answers a fresh server is compared on: every open buffer's symbols,
|
||||
/// and the packages the watcher events created and deleted.
|
||||
///
|
||||
/// Not the modules a buffer's edits added: a whole rescan indexes an open
|
||||
/// buffer's text and a fresh server opened after its scan has not, which is
|
||||
/// the documented staleness of an unsaved buffer, not an ordering.
|
||||
fn battery(session: &mut Session, client: &Client) -> Vec<Value> {
|
||||
let mut uris: Vec<&Uri> = client.open.keys().collect();
|
||||
uris.sort_by_key(|uri| uri.to_string());
|
||||
let mut out: Vec<Value> = uris
|
||||
.into_iter()
|
||||
.map(|uri| {
|
||||
session.result(
|
||||
DocumentSymbolRequest::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let mut names: Vec<String> = session
|
||||
.result(WorkspaceSymbolRequest::METHOD, serde_json::json!({ "query": "r" }))
|
||||
.as_array()
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter_map(|s| s["name"].as_str().map(str::to_string))
|
||||
.collect();
|
||||
names.sort();
|
||||
out.push(serde_json::json!(names));
|
||||
out
|
||||
}
|
||||
|
||||
/// One seeded run: a startup scan with bursts landing in it, then `rounds`
|
||||
/// rounds of bursts landing between and inside rescans. Reports how many
|
||||
/// bursts landed mid-scan, so a run cannot pass by never interleaving.
|
||||
fn run_seed(seed: u64, rounds: usize) -> usize {
|
||||
let tree = ordering_tree(&format!("orderrand{seed}"));
|
||||
tree.write("c/c.sv", "module cmod;\n logic c;\nendmodule\n");
|
||||
let mut client = Client::new(seed, &tree);
|
||||
let a = client.docs[0].0.clone();
|
||||
client.open.insert(a.clone(), (1, A_TEXT.to_string()));
|
||||
let _ = probe::take_counts();
|
||||
let startup: Vec<Vec<Message>> = (0..1 + client.rng.below(5)).map(|_| client.burst()).collect();
|
||||
probe::script(startup);
|
||||
let mut session = Session::started_behind(
|
||||
vec![tree.path.clone()],
|
||||
watching_progress(),
|
||||
wide_ish(),
|
||||
Vec::new(),
|
||||
vec![opened(&a, A_TEXT)],
|
||||
);
|
||||
let mut heard = Heard::default();
|
||||
let mut mid_scan = 0;
|
||||
let mut opens = std::mem::take(&mut client.opens) + 1;
|
||||
for round in 0..=rounds {
|
||||
settle(&mut session);
|
||||
hear(&session, &mut heard);
|
||||
let counts = probe::take_counts();
|
||||
let handed_back = counts.handed_back;
|
||||
mid_scan += counts.delivered;
|
||||
let at = format!("seed {seed} round {round}");
|
||||
assert!(
|
||||
handed_back <= opens + heard.scans + 1,
|
||||
"{at}: a scan handed its held batch back {handed_back} times \
|
||||
for {opens} didOpens and {} scans",
|
||||
heard.scans
|
||||
);
|
||||
same_buffers(&session, &client, &at);
|
||||
if round == rounds {
|
||||
break;
|
||||
}
|
||||
heard.scans = 0;
|
||||
// Most rounds start a rescan, from anywhere in the burst — so the
|
||||
// burst's own tail is often still unapplied while the scan runs.
|
||||
let mut top = client.burst();
|
||||
if client.rng.percent(70) {
|
||||
let at = client.rng.below(top.len() + 1);
|
||||
let trigger = client.created_file();
|
||||
top.insert(at, trigger);
|
||||
}
|
||||
let inside: Vec<Vec<Message>> = (0..client.rng.below(7)).map(|_| client.burst()).collect();
|
||||
opens = std::mem::take(&mut client.opens);
|
||||
probe::script(inside);
|
||||
assert!(!session.batch(top), "no shutdown");
|
||||
}
|
||||
for id in &client.asked {
|
||||
let times = heard.answers.get(&RequestId::from(*id)).copied().unwrap_or(0);
|
||||
assert_eq!(times, 1, "seed {seed}: request {id} answered {times} times");
|
||||
}
|
||||
let mine = battery(&mut session, &client);
|
||||
let mut fresh = Session::wide(vec![tree.path.clone()], false);
|
||||
for (uri, (_, text)) in &client.open {
|
||||
let path = crate::uri::uri_to_path(uri).expect("a path");
|
||||
fresh.open(&path, text);
|
||||
}
|
||||
assert_eq!(mine, battery(&mut fresh, &client), "seed {seed}: a fresh server's answers");
|
||||
mid_scan
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_bursts_keep_every_buffer_and_answer_every_request_once() {
|
||||
let mid_scan: usize = (1..=12).map(|seed| run_seed(seed, 10)).sum();
|
||||
assert!(mid_scan >= 200, "only {mid_scan} bursts landed mid-scan");
|
||||
}
|
||||
|
||||
/// The long run: `cargo test -p lucisv_server -- --ignored ordering_random`.
|
||||
#[test]
|
||||
#[ignore = "a few minutes; the normal suite runs the twelve seeds above"]
|
||||
fn random_bursts_long_run() {
|
||||
let mid_scan: usize = (100..400).map(|seed| run_seed(seed, 40)).sum();
|
||||
assert!(mid_scan >= 10_000, "only {mid_scan} bursts landed mid-scan");
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
//! No client message overtakes an older one while a scan answers messages
|
||||
//! (`docs/features/scan-ordering/README.md`, B and C).
|
||||
//!
|
||||
//! Every test here scripts what the client sends *at* a given interleave
|
||||
//! point ([`probe::script`]) — the transport cannot be timed against a scan's
|
||||
//! files — and then lets the loop finish the way `run` does: the held batch
|
||||
//! first, then whatever the scan ended before receiving.
|
||||
|
||||
use super::super::probe;
|
||||
use super::*;
|
||||
|
||||
/// A tree with enough files that every whole scan interleaves, plus one
|
||||
/// file `a/a.sv` (and `b/b.sv`) that a test opens.
|
||||
pub(super) fn ordering_tree(tag: &str) -> Tree {
|
||||
let tree = Tree::new(tag);
|
||||
for n in 0..INTERLEAVE_ABOVE + 6 {
|
||||
tree.package(&format!("z/p{n:03}.sv"), &format!("p{n:03}"));
|
||||
}
|
||||
tree.write("a/a.sv", A_TEXT);
|
||||
tree.write("b/b.sv", "module bmod;\nendmodule\n");
|
||||
tree
|
||||
}
|
||||
|
||||
pub(super) const A_TEXT: &str = "module amod;\n logic s;\nendmodule\n";
|
||||
|
||||
/// A notification on the wire.
|
||||
pub(super) fn note(method: &str, params: Value) -> Message {
|
||||
Message::Notification(Notification::new(method.to_string(), params))
|
||||
}
|
||||
|
||||
/// A request on the wire.
|
||||
pub(super) fn ask(id: i32, method: &str, params: Value) -> Message {
|
||||
Message::Request(Request::new(RequestId::from(id), method.to_string(), params))
|
||||
}
|
||||
|
||||
/// A watcher event saying `path` was created — a file the index does not
|
||||
/// hold, which costs a whole rescan.
|
||||
pub(super) fn created(path: &Path) -> Message {
|
||||
note(
|
||||
DidChangeWatchedFiles::METHOD,
|
||||
serde_json::json!({ "changes": [{ "uri": path_to_uri(path).expect("uri"), "type": 1 }] }),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn opened(uri: &Uri, text: &str) -> Message {
|
||||
note(
|
||||
DidOpenTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": {
|
||||
"uri": uri, "languageId": "systemverilog", "version": 1, "text": text,
|
||||
} }),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn closed(uri: &Uri) -> Message {
|
||||
note(DidCloseTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }))
|
||||
}
|
||||
|
||||
/// An incremental `didChange` inserting `text` at the start of `line`.
|
||||
fn inserted(uri: &Uri, version: u32, line: u32, text: &str) -> Message {
|
||||
let at = serde_json::json!({ "line": line, "character": 0 });
|
||||
note(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": version },
|
||||
"contentChanges": [{ "range": { "start": at, "end": at }, "text": text }],
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// A request about `uri` that always waits for a scan: a code lens counts
|
||||
/// instantiations across the workspace, so no buffer answers it alone (a
|
||||
/// hover on a local name is answered ahead since `fast-actions`).
|
||||
fn lens(id: i32, uri: &Uri) -> Message {
|
||||
ask(id, CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }))
|
||||
}
|
||||
|
||||
/// Hand `burst` to the loop as `run` would, with every scripted burst
|
||||
/// arriving mid-scan, then everything the loop owes afterwards.
|
||||
fn deliver(session: &mut Session, burst: Vec<Message>) {
|
||||
assert!(!session.batch(burst), "no shutdown");
|
||||
let late = probe::unarrived();
|
||||
assert!(late.is_empty(), "the rescan ended before the script did: {late:#?}");
|
||||
settle(session);
|
||||
}
|
||||
|
||||
/// What `run` does between bursts: answer the held batch until none is
|
||||
/// left, then take the scripted bursts that arrived after every scan ended.
|
||||
pub(super) fn settle(session: &mut Session) {
|
||||
loop {
|
||||
while !session.server.held.is_empty() {
|
||||
let held = std::mem::take(&mut session.server.held);
|
||||
assert!(!session.batch(held), "no shutdown");
|
||||
}
|
||||
let late = probe::unarrived();
|
||||
if late.is_empty() {
|
||||
return;
|
||||
}
|
||||
for burst in late {
|
||||
assert!(!session.batch(burst), "no shutdown");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A workspace-scoped session showing a progress bar, with `a/a.sv` open,
|
||||
/// and that buffer's uri.
|
||||
pub(super) fn with_a_open(tree: &Tree) -> (Session, Uri) {
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
let a = session.open(&tree.path.join("a/a.sv"), A_TEXT);
|
||||
// What the watcher events in these tests say was created: on disk, and
|
||||
// not in the index the startup scan built, so each costs a whole rescan.
|
||||
for new in ["new", "x1", "x2"] {
|
||||
tree.package(&format!("z/{new}.sv"), new);
|
||||
}
|
||||
let _ = probe::take_counts();
|
||||
let _ = session.drain();
|
||||
(session, a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_drained_mid_rescan_waits_behind_an_older_change_held_with_a_request() {
|
||||
// QA F6, held form: the rescan holds `[lens, v2]`; `v3` arrives at the
|
||||
// next file and used to be applied at once — ahead of `v2`, which then
|
||||
// replaced it.
|
||||
let tree = ordering_tree("orderheldfull");
|
||||
let (mut session, a) = with_a_open(&tree);
|
||||
let v2 = format!("{A_TEXT}module v2;\nendmodule\n");
|
||||
let v3 = format!("{A_TEXT}module v3;\nendmodule\n");
|
||||
probe::script([vec![lens(1, &a), changed(&a, 2, &v2)], vec![changed(&a, 3, &v3)]]);
|
||||
deliver(&mut session, vec![created(&tree.path.join("z/new.sv"))]);
|
||||
assert_eq!(buffer(&session, &a), v3, "the client's last text is the server's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incremental_changes_held_mid_rescan_are_applied_in_the_order_they_were_sent() {
|
||||
// The same race under incremental sync is corruption, not staleness: each
|
||||
// edit is a range into the text the one before it produced.
|
||||
let tree = ordering_tree("orderheldincr");
|
||||
let (mut session, a) = with_a_open(&tree);
|
||||
let first = "// first\n";
|
||||
let second = " // second, inside the module\n";
|
||||
probe::script([vec![lens(1, &a), inserted(&a, 2, 1, first)], vec![inserted(&a, 3, 2, second)]]);
|
||||
deliver(&mut session, vec![created(&tree.path.join("z/new.sv"))]);
|
||||
let mut client: Vec<&str> = A_TEXT.split_inclusive('\n').collect();
|
||||
client.insert(1, first);
|
||||
client.insert(2, second);
|
||||
assert_eq!(buffer(&session, &a), client.concat());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_drained_mid_rescan_waits_behind_the_rest_of_the_burst_that_started_it() {
|
||||
// QA F6, tail form: the burst that asks for the rescan still carries
|
||||
// `v2` behind the watcher event while the scan answers `v3`.
|
||||
let tree = ordering_tree("ordertail");
|
||||
let (mut session, a) = with_a_open(&tree);
|
||||
let v2 = format!("{A_TEXT}module v2;\nendmodule\n");
|
||||
let v3 = format!("{A_TEXT}module v3;\nendmodule\n");
|
||||
probe::script([vec![changed(&a, 3, &v3)]]);
|
||||
let burst = vec![
|
||||
ask(1, WorkspaceSymbolRequest::METHOD, serde_json::json!({ "query": "p" })),
|
||||
created(&tree.path.join("z/new.sv")),
|
||||
changed(&a, 2, &v2),
|
||||
];
|
||||
deliver(&mut session, burst);
|
||||
assert_eq!(buffer(&session, &a), v3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reopen_behind_a_held_close_leaves_the_buffer_open_with_its_new_text() {
|
||||
// Nothing is lost either way round: a close held behind a request and a
|
||||
// reopen drained after it are applied close-then-open, so the buffer the
|
||||
// editor is showing is the one the server holds.
|
||||
let tree = ordering_tree("orderreopen");
|
||||
let (mut session, a) = with_a_open(&tree);
|
||||
let reopened = format!("{A_TEXT}// reopened\n");
|
||||
probe::script([vec![lens(1, &a), closed(&a)], vec![opened(&a, &reopened)]]);
|
||||
deliver(&mut session, vec![created(&tree.path.join("z/new.sv"))]);
|
||||
assert_eq!(buffer(&session, &a), reopened, "open, with the text it was reopened with");
|
||||
let answered: Vec<RequestId> = session.answers().into_iter().map(|r| r.id).collect();
|
||||
assert_eq!(answered, [RequestId::from(1)], "the held lens is answered once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_behind_only_a_held_request_applies_at_once_and_a_late_cancel_waits_with_it() {
|
||||
// The rule is about notifications overtaking notifications. A change
|
||||
// with nothing older unapplied but a held *request* is applied where it
|
||||
// lands — the request is answered later against it, as every late
|
||||
// request always was — while a cancel for that request waits beside it
|
||||
// and is honoured when the held batch is replayed.
|
||||
let tree = ordering_tree("ordernarrow");
|
||||
let (mut session, a) = with_a_open(&tree);
|
||||
let v2 = format!("{A_TEXT}// v2\n");
|
||||
let cancel = note(Cancel::METHOD, serde_json::json!({ "id": 1 }));
|
||||
probe::script([vec![lens(1, &a)], vec![changed(&a, 2, &v2)], vec![cancel]]);
|
||||
assert!(!session.batch(vec![created(&tree.path.join("z/new.sv"))]), "no shutdown");
|
||||
assert!(probe::unarrived().is_empty(), "all three landed mid-scan");
|
||||
assert_eq!(buffer(&session, &a), v2, "applied mid-scan, ahead of the held lens");
|
||||
let held: Vec<bool> = session.server.held.iter().map(changes_state_of).collect();
|
||||
assert_eq!(held, [false, false], "the lens and its cancel, nothing else");
|
||||
settle(&mut session);
|
||||
let answers = session.answers();
|
||||
assert_eq!(answers.len(), 1, "{answers:#?}");
|
||||
assert!(
|
||||
answers[0]
|
||||
.response_result
|
||||
.as_ref()
|
||||
.is_err_and(|e| e.code == lsp_server::ErrorCode::RequestCanceled as i32),
|
||||
"the late cancel was honoured: {answers:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
fn changes_state_of(message: &Message) -> bool {
|
||||
super::super::batch::changes_state(message)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rescans_trigger_alone_in_its_burst_still_lets_newer_changes_apply_at_once() {
|
||||
// The rule holds a notification only when something *older* is waiting.
|
||||
// With nothing behind the watcher event and nothing held, a change
|
||||
// drained mid-rescan is applied where it lands — so a burst of watcher
|
||||
// events during a rescan is still coalesced into exactly one more scan.
|
||||
let tree = ordering_tree("ordercoalesce");
|
||||
let (mut session, a) = with_a_open(&tree);
|
||||
let v2 = format!("{A_TEXT}// v2\n");
|
||||
probe::script([
|
||||
vec![changed(&a, 2, &v2)],
|
||||
vec![created(&tree.path.join("z/x1.sv"))],
|
||||
vec![created(&tree.path.join("z/x2.sv"))],
|
||||
]);
|
||||
deliver(&mut session, vec![created(&tree.path.join("z/new.sv"))]);
|
||||
assert_eq!(buffer(&session, &a), v2);
|
||||
let ends = session.drain().into_iter().filter_map(progress_step).filter(|(s, _)| *s == "end");
|
||||
assert_eq!(ends.count(), 2, "the rescan, and one more for both watcher events");
|
||||
}
|
||||
|
||||
/// The session the startup-scan tests below start: `a/a.sv` opened in the
|
||||
/// client's opening burst, so the scan leads with folder `a`, and `later`
|
||||
/// scripted to arrive once that folder is in.
|
||||
fn startup_with(tree: &Tree, later: Vec<Message>) -> Session {
|
||||
let a = path_to_uri(&tree.path.join("a/a.sv")).expect("uri");
|
||||
let _ = probe::take_counts();
|
||||
// The head is `a/a.sv` alone; three interleave points is well past it.
|
||||
probe::script([Vec::new(), Vec::new(), later]);
|
||||
Session::started_behind(
|
||||
vec![tree.path.clone()],
|
||||
watching_progress(),
|
||||
wide_ish(),
|
||||
Vec::new(),
|
||||
vec![opened(&a, A_TEXT)],
|
||||
)
|
||||
}
|
||||
|
||||
/// Where the response to `id` sits among `said`, and where the bar's end.
|
||||
fn answered_before_the_end(said: &[Message], id: i32) -> bool {
|
||||
let (ended, answered) = super::scan::positions(said, id);
|
||||
matches!((answered, ended), (Some(answered), Some(ended)) if answered < ended)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_ahead_of_a_didopen_mid_startup_is_answered_and_the_drain_runs_once() {
|
||||
// QA Q1: `[request, didOpen(B)]` during the startup scan. The `didOpen`
|
||||
// used to be read off the batch *before* it was applied, which held the
|
||||
// request with the `didOpen` unapplied behind it — and the next file
|
||||
// handed the same batch back, forced a publish, and held it again, at
|
||||
// every file to the end of the scan (~300 s on OpenTitan).
|
||||
let tree = ordering_tree("orderq1");
|
||||
let a = path_to_uri(&tree.path.join("a/a.sv")).expect("uri");
|
||||
let b = path_to_uri(&tree.path.join("b/b.sv")).expect("uri");
|
||||
let tokens_b = ask(
|
||||
8,
|
||||
SemanticTokensFullRequest::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": b } }),
|
||||
);
|
||||
let later = vec![lens(7, &a), opened(&b, "module bmod;\nendmodule\n"), tokens_b];
|
||||
let session = startup_with(&tree, later);
|
||||
let probe::Counts { points, handed_back, .. } = probe::take_counts();
|
||||
let _control = startup_with(&tree, Vec::new());
|
||||
let unloaded = probe::take_counts().points;
|
||||
let said = session.drain();
|
||||
assert!(answered_before_the_end(&said, 7), "the request ahead of the didOpen: {said:#?}");
|
||||
assert!(answered_before_the_end(&said, 8), "and the one behind it, mid-scan");
|
||||
assert!(session.server.held.is_empty(), "nothing is left held");
|
||||
assert!(handed_back <= 1, "one hand-back for one didOpen, not one per file: {handed_back}");
|
||||
assert_eq!(points, unloaded, "as many interleave points as the scan with nothing sent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_behind_a_didopen_mid_startup_still_waits_for_the_buffer_it_names() {
|
||||
// The ordering the old flag existed for is kept: a request *behind* the
|
||||
// `didOpen` sees the buffer, and the work list ordered round it.
|
||||
let tree = ordering_tree("orderq1behind");
|
||||
let b = path_to_uri(&tree.path.join("b/b.sv")).expect("uri");
|
||||
let symbols_b =
|
||||
ask(9, DocumentSymbolRequest::METHOD, serde_json::json!({ "textDocument": { "uri": b } }));
|
||||
let session = startup_with(&tree, vec![opened(&b, "module bmod;\nendmodule\n"), symbols_b]);
|
||||
let said = session.drain();
|
||||
assert!(answered_before_the_end(&said, 9), "answered mid-scan: {said:#?}");
|
||||
let answer = said.iter().find_map(|m| match m {
|
||||
Message::Response(r) if r.id == RequestId::from(9) => r.response_result.clone().ok(),
|
||||
_ => None,
|
||||
});
|
||||
let names: Vec<String> = answer
|
||||
.and_then(|v| v.as_array().cloned())
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter_map(|s| s["name"].as_str().map(str::to_string))
|
||||
.collect();
|
||||
assert_eq!(names, ["bmod"], "answered off the buffer the didOpen installed");
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
//! Colours that never wait for the index: the semantic-token requests
|
||||
//! answered from the buffer alone while a scan holds everything else, and the
|
||||
//! one `workspace/semanticTokens/refresh` that replaces them once the index
|
||||
//! has settled (`docs/features/viewport-highlight/README.md`).
|
||||
//!
|
||||
//! **What an exempted request reads, and why that is valid mid-scan.** The
|
||||
//! loop is one thread, so a request is only ever answered "during" a scan by
|
||||
//! being reached from inside it — the startup's configuration wait, or the
|
||||
//! drain between two of a scan's files (`answer_what_is_waiting`), both of
|
||||
//! which go through `process_batch`. The exemption is taken there, before the
|
||||
//! request would be held, and runs the ordinary dispatch arm for the method
|
||||
//! *without* the dirty-buffer flush (`answer_flushed`). Those three arms and
|
||||
//! the large-file gate in front of them read exactly:
|
||||
//!
|
||||
//! * the one `Document` the request names — its text, line index, tokens,
|
||||
//! tree, `Semantics` and `ExternalResolutions` overlay, all of which are
|
||||
//! replaced wholesale (`set_document`) or refreshed in place by a publish
|
||||
//! (`refresh_overlay`) and are never half-written when control is back in
|
||||
//! the loop;
|
||||
//! * `Workspace::has_large_documents` and `ClientAbilities::token_server_cancel`
|
||||
//! (the large-file decline);
|
||||
//! * `Server::tokens` / `token_results`, the remembered answer the next delta
|
||||
//! is computed against — the server's own record of what it sent.
|
||||
//!
|
||||
//! Never the workspace index, never another buffer, never a flush or a
|
||||
//! publish. The overlay is the buffer's own copy of the index's answers as of
|
||||
//! the last publish, so an answer off it is a coherent guess, and the refresh
|
||||
//! below is what replaces the guess.
|
||||
//!
|
||||
//! Which buffers are current, and how an exempted request is taken out of
|
||||
//! a burst ahead of what holds the rest, is `ahead.rs`.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use lsp_server::Response;
|
||||
use lsp_types::request::{
|
||||
Request as _, SemanticTokensFullDeltaRequest, SemanticTokensFullRequest,
|
||||
SemanticTokensRangeRequest, SemanticTokensRefresh,
|
||||
};
|
||||
use lsp_types::Uri;
|
||||
|
||||
use super::Server;
|
||||
use crate::tokens;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// The requests that may be answered ahead of a scan: the three that colour.
|
||||
const TOKEN_METHODS: [&str; 3] = [
|
||||
SemanticTokensRangeRequest::METHOD,
|
||||
SemanticTokensFullRequest::METHOD,
|
||||
SemanticTokensFullDeltaRequest::METHOD,
|
||||
];
|
||||
|
||||
/// What the exemption owes the client once the index settles.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Viewport {
|
||||
/// Buffers whose last answer was a **range** taken off an unsettled
|
||||
/// index. A range answer is not remembered, so it cannot be compared with
|
||||
/// what the settled index says; it is simply owed a refresh. A whole
|
||||
/// answer for the buffer takes it out again ([`Viewport::answered_whole`]).
|
||||
guessed: HashSet<Uri>,
|
||||
/// Buffers whose last **whole** answer (full or delta) was computed off an
|
||||
/// unsettled index. Only these, and `guessed`, are re-classified at the
|
||||
/// next refresh decision: an answer given once the index had settled is
|
||||
/// what the index said, and re-checking every open buffer on every index
|
||||
/// change cost 13 ms per save with 200 buffers open (QA Q6).
|
||||
early: HashSet<Uri>,
|
||||
/// The index revision (`Server::hierarchy_revision`) the last refresh
|
||||
/// decision was taken at. One decision per revision is the coalescing
|
||||
/// rule: however many publishes a scan made, its settling is one check.
|
||||
checked_at: u64,
|
||||
/// Set while `open_then_widen` applies a `didOpen`: a widen that open
|
||||
/// asks for is recorded in `owed_widen` instead of run, so the colours
|
||||
/// behind it in its burst can be answered first.
|
||||
pub(super) defer_widen: bool,
|
||||
/// The folders a deferred widen will add.
|
||||
pub(super) owed_widen: Option<Vec<PathBuf>>,
|
||||
/// Whether a widen is running: the index is unsettled, exactly as during
|
||||
/// a scan, so a range answered now is owed a refresh.
|
||||
pub(super) widening: bool,
|
||||
}
|
||||
|
||||
impl Viewport {
|
||||
/// Record a widen instead of running it, when an open inside a burst asked
|
||||
/// for it — reporting whether it was recorded.
|
||||
pub(super) fn defers_widen(&mut self, added: &[PathBuf]) -> bool {
|
||||
if !self.defer_widen {
|
||||
return false;
|
||||
}
|
||||
self.owed_widen.get_or_insert_with(Vec::new).extend_from_slice(added);
|
||||
true
|
||||
}
|
||||
|
||||
/// A full or delta answer was sent for `uri`, off an index that was or
|
||||
/// was not `unsettled`: it is remembered, so the refresh check compares
|
||||
/// it — when it may be stale — instead of assuming it stale.
|
||||
pub(super) fn answered_whole(&mut self, uri: &Uri, unsettled: bool) {
|
||||
self.guessed.remove(uri);
|
||||
match unsettled {
|
||||
true => self.early.insert(uri.clone()),
|
||||
false => self.early.remove(uri),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// Whether a colouring request may go ahead of a scan — `None` when
|
||||
/// `method` is not one of the three that colour.
|
||||
///
|
||||
/// A whole answer off an unsettled index is only worth giving a client
|
||||
/// that can be told to ask again; one that cannot keeps it until its next
|
||||
/// edit, so for it `full` and `full/delta` wait for the index as they
|
||||
/// always did, and only `range` goes ahead.
|
||||
pub(super) fn colours_may_go_ahead(&self, method: &str) -> Option<bool> {
|
||||
if !TOKEN_METHODS.contains(&method) {
|
||||
return None;
|
||||
}
|
||||
Some(method == SemanticTokensRangeRequest::METHOD || self.abilities.semantic_tokens_refresh)
|
||||
}
|
||||
|
||||
/// What answering a colouring request ahead of the index owes: a range
|
||||
/// answer is not remembered, so one taken off an unsettled index is
|
||||
/// marked for the refresh; a whole answer is remembered by
|
||||
/// `remember_tokens` and checked against the settled index anyway.
|
||||
pub(super) fn coloured_ahead(
|
||||
&mut self,
|
||||
uri: Uri,
|
||||
method: &str,
|
||||
unsettled: bool,
|
||||
response: &Response,
|
||||
) {
|
||||
let range = method == SemanticTokensRangeRequest::METHOD;
|
||||
if unsettled && range && response.response_result.is_ok() {
|
||||
self.viewport.guessed.insert(uri);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the index is still being built — a scan running or owed, or a
|
||||
/// widen running — or about to move: something is held, and whatever it
|
||||
/// is may ask for a rescan when it is applied (a watcher event a
|
||||
/// colouring request was answered ahead of, say). A token answer given
|
||||
/// now may then change once the index settles, and is recorded as a
|
||||
/// guess. Nothing is ever held while the loop answers in order, so this
|
||||
/// last clause only ever marks an answer given ahead.
|
||||
pub(super) fn index_unsettled(&self) -> bool {
|
||||
self.scanning || self.staging || self.viewport.widening || !self.held.is_empty()
|
||||
}
|
||||
|
||||
/// Ask the client to re-request its semantic tokens, once, when the index
|
||||
/// has moved since the last decision and some buffer's colours were taken
|
||||
/// off an index that has since changed.
|
||||
///
|
||||
/// **Never when nothing a token reads has changed.** Each open buffer
|
||||
/// whose remembered answer was computed off an unsettled index is
|
||||
/// re-classified and compared with what was sent; a buffer coloured only
|
||||
/// by a range answer off an unsettled index counts as changed. A buffer
|
||||
/// answered after the index settled is not re-checked: what it was sent
|
||||
/// is what the index said, and this check is not a second change-tracker
|
||||
/// for later edits elsewhere (which never refreshed before this lane). A dirty buffer is skipped — the client asks again
|
||||
/// after its own edit, and comparing against text it has moved past would
|
||||
/// say nothing. Silent for a client without `refreshSupport`.
|
||||
///
|
||||
/// **What one refresh costs.** `vscode-languageclient` fires every
|
||||
/// document-tokens provider's change event, and VS Code re-fetches tokens
|
||||
/// for every model attached to an editor — a `full/delta` each, which the
|
||||
/// prefix/suffix trim makes a few edits apiece.
|
||||
pub(super) fn refresh_tokens_if_stale(&mut self) {
|
||||
if self.viewport.checked_at == self.hierarchy_revision || self.must_wait() {
|
||||
return;
|
||||
}
|
||||
self.viewport.checked_at = self.hierarchy_revision;
|
||||
if !self.abilities.semantic_tokens_refresh {
|
||||
self.viewport.guessed.clear();
|
||||
self.viewport.early.clear();
|
||||
return;
|
||||
}
|
||||
let started = self.timer();
|
||||
let stale = self.stale_token_buffers();
|
||||
self.viewport.guessed.clear();
|
||||
self.viewport.early.clear();
|
||||
self.timed(started, |took| {
|
||||
format!("semantic tokens: {stale} stale buffer(s), checked in {took}")
|
||||
});
|
||||
if stale > 0 {
|
||||
self.send_request(SemanticTokensRefresh::METHOD, ());
|
||||
}
|
||||
}
|
||||
|
||||
/// How many open buffers the client is showing colours for that the
|
||||
/// buffer's current analysis would not give.
|
||||
fn stale_token_buffers(&self) -> usize {
|
||||
self.workspace
|
||||
.open_documents()
|
||||
.filter(|(uri, doc)| {
|
||||
!doc.large && !self.dirty.iter().any(|(pending, _)| pending == *uri)
|
||||
})
|
||||
.filter(|(uri, doc)| {
|
||||
self.viewport.guessed.contains(*uri)
|
||||
|| self.viewport.early.contains(*uri)
|
||||
&& self
|
||||
.tokens
|
||||
.get(*uri)
|
||||
.is_some_and(|sent| sent.data != tokens::semantic_tokens(doc))
|
||||
})
|
||||
.count()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,514 @@
|
||||
//! The viewport exemption and the refresh behind it, on the wire.
|
||||
//!
|
||||
//! Each claim of `viewport.rs` is one test: a colouring request is answered
|
||||
//! while a scan holds everything else, a request that is not colouring still
|
||||
//! waits, a buffer whose text is not current waits (dirty, a change held
|
||||
//! ahead of it, a change still behind the scan's own trigger), a cancel is
|
||||
//! honoured, a large buffer keeps its decline; and the refresh goes out once
|
||||
//! per index revision, only when something a token reads has changed, and
|
||||
//! only to a client that asked for it. The last test is the whole story: a
|
||||
//! staged cold start coloured at once, then sharpened by the refresh.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use lsp_server::{Connection, Message, Notification, Request, RequestId, Response};
|
||||
use lsp_types::notification::{
|
||||
Cancel, DidChangeTextDocument, DidOpenTextDocument, Notification as _,
|
||||
};
|
||||
use lsp_types::request::{
|
||||
CodeLensRequest, Request as _, SemanticTokensFullRequest, SemanticTokensRangeRequest,
|
||||
SemanticTokensRefresh,
|
||||
};
|
||||
use lsp_types::Uri;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use super::super::startup::Startup;
|
||||
use super::super::{ClientAbilities, Server};
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
/// A directory of its own, removed when dropped.
|
||||
struct Tree(PathBuf);
|
||||
|
||||
impl Tree {
|
||||
fn new(name: &str) -> Tree {
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("lucisv_viewport_{}_{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(&path).expect("temp dir");
|
||||
Tree(path)
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, text: &str) -> PathBuf {
|
||||
let path = self.0.join(rel);
|
||||
std::fs::write(&path, text).expect("write");
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A server and the client end of its connection.
|
||||
struct Lane {
|
||||
server: Server,
|
||||
client: Connection,
|
||||
}
|
||||
|
||||
/// A started session whose startup scan has run, against `abilities`.
|
||||
fn lane(root: &Path, abilities: ClientAbilities) -> Lane {
|
||||
let (server_end, client) = Connection::memory();
|
||||
let startup = Startup {
|
||||
abilities,
|
||||
client: ClientSettings::default(),
|
||||
storage: None,
|
||||
verbose: false,
|
||||
queued: Vec::new(),
|
||||
wait: Duration::ZERO,
|
||||
};
|
||||
Lane { server: Server::started(server_end, vec![root.to_path_buf()], startup), client }
|
||||
}
|
||||
|
||||
impl Lane {
|
||||
/// Everything the server has sent since the last drain.
|
||||
fn drain(&self) -> Vec<Message> {
|
||||
self.client.receiver.try_iter().collect()
|
||||
}
|
||||
|
||||
/// The ids of the responses sent since the last drain, in order.
|
||||
fn answered(&self) -> Vec<RequestId> {
|
||||
responses(self.drain()).into_iter().map(|r| r.id).collect()
|
||||
}
|
||||
|
||||
fn open(&mut self, path: &Path, text: &str) -> Uri {
|
||||
let uri = path_to_uri(path).expect("uri");
|
||||
self.server.notification(Notification::new(
|
||||
DidOpenTextDocument::METHOD.to_string(),
|
||||
json!({ "textDocument": {
|
||||
"uri": uri, "languageId": "systemverilog", "version": 1, "text": text,
|
||||
}}),
|
||||
));
|
||||
uri
|
||||
}
|
||||
|
||||
/// One burst through the loop body, with a scan pretended to be running
|
||||
/// — the state every mid-scan drain is in — and nothing settled.
|
||||
fn burst_mid_scan(&mut self, batch: Vec<Message>) {
|
||||
self.server.scanning = true;
|
||||
self.server.answering_a_rescan = true;
|
||||
self.server.process_batch(batch).expect("the burst is handled");
|
||||
self.server.scanning = false;
|
||||
self.server.answering_a_rescan = false;
|
||||
}
|
||||
|
||||
fn refreshes(&self) -> usize {
|
||||
self.drain()
|
||||
.iter()
|
||||
.filter(
|
||||
|m| matches!(m, Message::Request(r) if r.method == SemanticTokensRefresh::METHOD),
|
||||
)
|
||||
.count()
|
||||
}
|
||||
}
|
||||
|
||||
fn responses(messages: Vec<Message>) -> Vec<Response> {
|
||||
messages
|
||||
.into_iter()
|
||||
.filter_map(|m| match m {
|
||||
Message::Response(response) => Some(response),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn request(id: &str, method: &str, params: Value) -> Message {
|
||||
Message::Request(Request::new(RequestId::from(id.to_string()), method.to_string(), params))
|
||||
}
|
||||
|
||||
fn full(id: &str, uri: &Uri) -> Message {
|
||||
request(id, SemanticTokensFullRequest::METHOD, json!({ "textDocument": { "uri": uri } }))
|
||||
}
|
||||
|
||||
fn range(id: &str, uri: &Uri) -> Message {
|
||||
request(
|
||||
id,
|
||||
SemanticTokensRangeRequest::METHOD,
|
||||
json!({ "textDocument": { "uri": uri }, "range": {
|
||||
"start": { "line": 0, "character": 0 }, "end": { "line": 60, "character": 0 },
|
||||
}}),
|
||||
)
|
||||
}
|
||||
|
||||
/// A request about `uri` that always waits for a scan: a code lens counts
|
||||
/// instantiations across the workspace, so no buffer answers it alone. (A
|
||||
/// hover was the witness until `fast-actions` let a hover on a local name go
|
||||
/// ahead too.)
|
||||
fn lens(id: &str, uri: &Uri) -> Message {
|
||||
request(id, CodeLensRequest::METHOD, json!({ "textDocument": { "uri": uri } }))
|
||||
}
|
||||
|
||||
fn changed(uri: &Uri, text: &str) -> Message {
|
||||
Message::Notification(Notification::new(
|
||||
DidChangeTextDocument::METHOD.to_string(),
|
||||
json!({ "textDocument": { "uri": uri, "version": 2 }, "contentChanges": [{ "text": text }] }),
|
||||
))
|
||||
}
|
||||
|
||||
fn cancel(id: &str) -> Message {
|
||||
Message::Notification(Notification::new(Cancel::METHOD.to_string(), json!({ "id": id })))
|
||||
}
|
||||
|
||||
fn id(text: &str) -> RequestId {
|
||||
RequestId::from(text.to_string())
|
||||
}
|
||||
|
||||
/// A client that accepts `workspace/semanticTokens/refresh`, as VS Code does.
|
||||
fn refreshing() -> ClientAbilities {
|
||||
ClientAbilities { semantic_tokens_refresh: true, ..Default::default() }
|
||||
}
|
||||
|
||||
const MODULE: &str = "module m;\n localparam W = 8;\n wire [W-1:0] a;\nendmodule\n";
|
||||
|
||||
/// A lane with `m.sv` open and the client end drained.
|
||||
fn opened(name: &str, abilities: ClientAbilities) -> (Tree, Lane, Uri) {
|
||||
let tree = Tree::new(name);
|
||||
let path = tree.write("m.sv", MODULE);
|
||||
let mut lane = lane(&tree.0, abilities);
|
||||
let uri = lane.open(&path, MODULE);
|
||||
// What `run` does before it takes its first message: the refresh decision
|
||||
// for the index the startup built.
|
||||
lane.server.refresh_tokens_if_stale();
|
||||
lane.drain();
|
||||
(tree, lane, uri)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colouring_requests_are_answered_while_a_lens_ahead_of_them_waits() {
|
||||
let (_tree, mut lane, uri) = opened("ahead", refreshing());
|
||||
lane.burst_mid_scan(vec![lens("h", &uri), full("f", &uri), range("r", &uri)]);
|
||||
assert_eq!(lane.answered(), vec![id("f"), id("r")], "both colour now, the lens waits");
|
||||
assert_eq!(lane.server.held.len(), 1, "the lens alone is held");
|
||||
assert!(lane.server.viewport.guessed.contains(&uri), "a range off an unsettled index");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_exempt_answers_are_the_answers_the_dispatch_gives_once_nothing_waits() {
|
||||
let (_tree, mut lane, uri) = opened("same", refreshing());
|
||||
lane.burst_mid_scan(vec![lens("h", &uri), full("f", &uri), range("r", &uri)]);
|
||||
let early = responses(lane.drain());
|
||||
lane.server.held.clear();
|
||||
lane.server.process_batch(vec![full("f2", &uri), range("r2", &uri)]).expect("burst");
|
||||
let late = responses(lane.drain());
|
||||
let data = |r: &Response| r.response_result.as_ref().expect("ok")["data"].clone();
|
||||
assert_eq!(data(&early[0]), data(&late[0]), "full");
|
||||
assert_eq!(data(&early[1]), data(&late[1]), "range");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dirty_buffer_is_not_answered_from_text_the_client_has_moved_past() {
|
||||
let (_tree, mut lane, uri) = opened("dirty", ClientAbilities::default());
|
||||
lane.burst_mid_scan(vec![changed(&uri, "module m2;\nendmodule\n"), range("r", &uri)]);
|
||||
assert!(lane.answered().is_empty(), "held until the change is analyzed");
|
||||
assert_eq!(lane.server.held.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_held_ahead_of_the_request_holds_it_too_but_not_another_buffers() {
|
||||
let (tree, mut lane, uri) = opened("held", ClientAbilities::default());
|
||||
let other_path = tree.write("n.sv", "module n;\nendmodule\n");
|
||||
let other = lane.open(&other_path, "module n;\nendmodule\n");
|
||||
lane.drain();
|
||||
lane.burst_mid_scan(vec![
|
||||
lens("h", &uri),
|
||||
changed(&uri, "module m3;\nendmodule\n"),
|
||||
range("mine", &uri),
|
||||
range("theirs", &other),
|
||||
]);
|
||||
assert_eq!(lane.answered(), vec![id("theirs")], "only the untouched buffer colours");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_still_behind_the_scans_own_trigger_holds_the_request() {
|
||||
let (_tree, mut lane, uri) = opened("behind", ClientAbilities::default());
|
||||
lane.server.staging = true;
|
||||
// A scan started by a notification whose burst still has one
|
||||
// unapplied notification behind it (`Server::behind`).
|
||||
lane.server.behind = 1;
|
||||
let Message::Request(r) = range("r", &uri) else { unreachable!() };
|
||||
let mut none = HashSet::new();
|
||||
assert!(lane.server.answer_from_the_buffer(&r, &[], &mut none).is_none(), "owed the change");
|
||||
lane.server.behind = 0;
|
||||
assert!(lane.server.answer_from_the_buffer(&r, &[], &mut none).is_some(), "nothing owed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_in_the_same_burst_is_honoured_for_an_exempt_request() {
|
||||
let (_tree, mut lane, uri) = opened("cancel", refreshing());
|
||||
lane.burst_mid_scan(vec![lens("h", &uri), full("f", &uri), cancel("f")]);
|
||||
let answers = responses(lane.drain());
|
||||
assert_eq!(answers.len(), 1);
|
||||
let error = answers[0].response_result.as_ref().expect_err("cancelled");
|
||||
assert_eq!(error.code, lsp_server::ErrorCode::RequestCanceled as i32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_large_buffer_keeps_its_decline_and_its_lexed_window() {
|
||||
let (tree, mut lane, _) = opened("large", refreshing());
|
||||
let settings = ClientSettings { large_file_threshold: 16, ..Default::default() };
|
||||
let _ = lane.server.workspace.set_client_settings(settings);
|
||||
let path = tree.0.join("big.sv");
|
||||
let uri = lane.open(&path, MODULE);
|
||||
assert!(lane.server.workspace.document(&uri).is_some_and(|doc| doc.large));
|
||||
lane.drain();
|
||||
lane.burst_mid_scan(vec![lens("h", &uri), full("f", &uri), range("r", &uri)]);
|
||||
let answers = responses(lane.drain());
|
||||
assert_eq!(answers.len(), 2);
|
||||
assert!(answers[0].response_result.is_err(), "full is declined, as always");
|
||||
let data = &answers[1].response_result.as_ref().expect("a window")["data"];
|
||||
assert!(!data.as_array().expect("data").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_refresh_when_nothing_a_token_reads_has_changed() {
|
||||
let abilities = ClientAbilities { semantic_tokens_refresh: true, ..Default::default() };
|
||||
let (_tree, mut lane, uri) = opened("quiet", abilities);
|
||||
lane.burst_mid_scan(vec![full("f", &uri)]);
|
||||
lane.drain();
|
||||
lane.server.hierarchy_revision += 1;
|
||||
lane.server.refresh_tokens_if_stale();
|
||||
assert_eq!(lane.refreshes(), 0, "what was sent is what the index says");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_refresh_per_index_revision_when_what_was_sent_is_stale() {
|
||||
let abilities = ClientAbilities { semantic_tokens_refresh: true, ..Default::default() };
|
||||
let (_tree, mut lane, uri) = opened("stale", abilities);
|
||||
lane.burst_mid_scan(vec![full("f", &uri)]);
|
||||
lane.drain();
|
||||
// What the client holds, made different from what the buffer says.
|
||||
lane.server.tokens.get_mut(&uri).expect("remembered").data.pop();
|
||||
lane.server.refresh_tokens_if_stale();
|
||||
assert_eq!(lane.refreshes(), 0, "the index has not moved since the last decision");
|
||||
lane.server.hierarchy_revision += 1;
|
||||
lane.server.refresh_tokens_if_stale();
|
||||
lane.server.refresh_tokens_if_stale();
|
||||
assert_eq!(lane.refreshes(), 1, "coalesced to one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answer_given_once_the_index_had_settled_is_not_checked_again() {
|
||||
let (_tree, mut lane, uri) = opened("settled", refreshing());
|
||||
lane.server.process_batch(vec![full("f", &uri)]).expect("burst");
|
||||
lane.drain();
|
||||
lane.server.tokens.get_mut(&uri).expect("remembered").data.pop();
|
||||
lane.server.hierarchy_revision += 1;
|
||||
lane.server.refresh_tokens_if_stale();
|
||||
assert_eq!(lane.refreshes(), 0, "only answers taken off an unsettled index are owed one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_guessed_range_is_refreshed_and_a_client_that_cannot_be_asked_is_not() {
|
||||
for (refresh_support, expected) in [(true, 1), (false, 0)] {
|
||||
let abilities =
|
||||
ClientAbilities { semantic_tokens_refresh: refresh_support, ..Default::default() };
|
||||
let (_tree, mut lane, uri) = opened("guessed", abilities);
|
||||
lane.burst_mid_scan(vec![lens("h", &uri), range("r", &uri)]);
|
||||
lane.server.held.clear();
|
||||
lane.drain();
|
||||
lane.server.hierarchy_revision += 1;
|
||||
lane.server.refresh_tokens_if_stale();
|
||||
assert_eq!(lane.refreshes(), expected, "refreshSupport={refresh_support}");
|
||||
assert!(lane.server.viewport.guessed.is_empty(), "the debt is paid either way");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dirty_buffer_is_left_to_the_clients_own_next_request() {
|
||||
let abilities = ClientAbilities { semantic_tokens_refresh: true, ..Default::default() };
|
||||
let (_tree, mut lane, uri) = opened("dirtyrefresh", abilities);
|
||||
lane.burst_mid_scan(vec![full("f", &uri)]);
|
||||
lane.server.tokens.get_mut(&uri).expect("remembered").data.pop();
|
||||
lane.server.mark_dirty(uri.clone(), "module z;\nendmodule\n".to_string());
|
||||
lane.drain();
|
||||
lane.server.hierarchy_revision += 1;
|
||||
lane.server.refresh_tokens_if_stale();
|
||||
assert_eq!(lane.refreshes(), 0);
|
||||
}
|
||||
|
||||
/// The whole story, through a real staged startup: the buffer is opened and
|
||||
/// coloured before the settings answer lands — so before anything is
|
||||
/// indexed — with the package's type name a plain `variable`; once the scan
|
||||
/// has run, one refresh goes out and the next answer says `type`.
|
||||
#[test]
|
||||
fn a_cold_start_is_coloured_at_once_and_sharpened_by_one_refresh() {
|
||||
let tree = Tree::new("story");
|
||||
tree.write("p.sv", "package p;\n typedef logic [3:0] nib_t;\nendpackage\n");
|
||||
let text = "module m;\n p::nib_t a;\nendmodule\n";
|
||||
let path = tree.write("m.sv", text);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
let opened = Message::Notification(Notification::new(
|
||||
DidOpenTextDocument::METHOD.to_string(),
|
||||
json!({ "textDocument": {
|
||||
"uri": uri, "languageId": "systemverilog", "version": 1, "text": text,
|
||||
}}),
|
||||
));
|
||||
let (server_end, client) = Connection::memory();
|
||||
let abilities = ClientAbilities {
|
||||
configuration: true,
|
||||
semantic_tokens_refresh: true,
|
||||
..Default::default()
|
||||
};
|
||||
let startup = Startup {
|
||||
abilities,
|
||||
client: ClientSettings::default(),
|
||||
storage: None,
|
||||
verbose: false,
|
||||
queued: vec![opened, lens("h", &uri), full("f", &uri)],
|
||||
// The client never answers the pull: everything waits the bound,
|
||||
// and the colours must not.
|
||||
wait: Duration::from_millis(50),
|
||||
};
|
||||
let mut lane =
|
||||
Lane { server: Server::started(server_end, vec![tree.0.clone()], startup), client };
|
||||
let answers = responses(lane.drain());
|
||||
assert_eq!(answers[0].id, id("f"), "coloured first, ahead of the held lens: {answers:?}");
|
||||
let nib = |answer: &Value| -> u64 {
|
||||
// `p` `::` `nib_t` on line 1: the second identifier token of the line.
|
||||
let data: Vec<u64> =
|
||||
answer["data"].as_array().expect("data").iter().filter_map(Value::as_u64).collect();
|
||||
let (mut line, mut col) = (0, 0);
|
||||
for t in data.chunks(5) {
|
||||
line += t[0];
|
||||
col = if t[0] == 0 { col + t[1] } else { t[1] };
|
||||
if line == 1 && col == 5 {
|
||||
return t[3];
|
||||
}
|
||||
}
|
||||
panic!("no token at 1:5 in {data:?}");
|
||||
};
|
||||
let before = nib(answers[0].response_result.as_ref().expect("ok"));
|
||||
assert_eq!(
|
||||
before,
|
||||
crate::tokens::token_types().iter().position(|t| t.as_str() == "variable").expect("legend")
|
||||
as u64
|
||||
);
|
||||
// What `run` does next: answer what the scan held (the lens), then
|
||||
// take the refresh decision.
|
||||
let held = std::mem::take(&mut lane.server.held);
|
||||
lane.server.process_batch(held).expect("the held burst");
|
||||
assert_eq!(responses(lane.drain()).len(), 1, "the lens, answered at last");
|
||||
lane.server.refresh_tokens_if_stale();
|
||||
assert_eq!(lane.refreshes(), 1, "the index moved what the client was sent");
|
||||
lane.server.process_batch(vec![full("f2", &uri)]).expect("burst");
|
||||
let after = responses(lane.drain());
|
||||
let sharpened = nib(after[0].response_result.as_ref().expect("ok"));
|
||||
assert_eq!(
|
||||
sharpened,
|
||||
crate::tokens::token_types().iter().position(|t| t.as_str() == "type").expect("legend")
|
||||
as u64
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_cannot_be_refreshed_gets_early_ranges_but_waits_for_whole_answers() {
|
||||
let (_tree, mut lane, uri) = opened("norefresh", ClientAbilities::default());
|
||||
lane.burst_mid_scan(vec![lens("h", &uri), full("f", &uri), range("r", &uri)]);
|
||||
assert_eq!(lane.answered(), vec![id("r")], "only the range colours early");
|
||||
assert_eq!(lane.server.held.len(), 2, "the lens and the full wait for the index");
|
||||
}
|
||||
|
||||
/// Two blocks two folders apart, so that opening the second widens the
|
||||
/// default folder scope; the second uses a package only its own block holds.
|
||||
fn two_blocks(name: &str) -> (Tree, PathBuf, PathBuf) {
|
||||
let tree = Tree::new(name);
|
||||
for dir in ["a/b/c", "x/y/z", "x/y/pk"] {
|
||||
std::fs::create_dir_all(tree.0.join(dir)).expect("dirs");
|
||||
}
|
||||
let first = tree.write("a/b/c/m.sv", MODULE);
|
||||
tree.write("x/y/pk/p.sv", "package p;\n typedef logic [3:0] nib_t;\nendpackage\n");
|
||||
let second = tree.write("x/y/z/n.sv", USES_P);
|
||||
(tree, first, second)
|
||||
}
|
||||
|
||||
const USES_P: &str = "module n;\n p::nib_t a;\nendmodule\n";
|
||||
|
||||
fn opening(uri: &Uri, text: &str) -> Message {
|
||||
Message::Notification(Notification::new(
|
||||
DidOpenTextDocument::METHOD.to_string(),
|
||||
json!({ "textDocument": {
|
||||
"uri": uri, "languageId": "systemverilog", "version": 1, "text": text,
|
||||
}}),
|
||||
))
|
||||
}
|
||||
|
||||
/// Where in what the server sent the first diagnostics publish for `uri` is.
|
||||
fn first_publish(sent: &[Message], uri: &Uri) -> usize {
|
||||
sent.iter()
|
||||
.position(|m| {
|
||||
matches!(m, Message::Notification(n)
|
||||
if n.method == "textDocument/publishDiagnostics" && n.params["uri"] == json!(uri))
|
||||
})
|
||||
.expect("the widen publishes the new buffer")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_full_in_the_same_burst_as_a_widening_open_colours_before_the_widen() {
|
||||
let (_tree, first, second) = two_blocks("widen");
|
||||
let mut lane = lane(&_tree.0, refreshing());
|
||||
lane.open(&first, MODULE);
|
||||
lane.server.refresh_tokens_if_stale();
|
||||
lane.drain();
|
||||
let indexed = lane.server.workspace.index().files().len();
|
||||
let uri = path_to_uri(&second).expect("uri");
|
||||
lane.server
|
||||
.process_batch(vec![opening(&uri, USES_P), full("f", &uri), lens("h", &uri)])
|
||||
.expect("burst");
|
||||
assert!(lane.server.workspace.index().files().len() > indexed, "premise: it widened");
|
||||
let sent = lane.drain();
|
||||
let order: Vec<RequestId> = responses(sent.clone()).into_iter().map(|r| r.id).collect();
|
||||
assert_eq!(order, vec![id("f"), id("h")]);
|
||||
let coloured = sent
|
||||
.iter()
|
||||
.position(|m| matches!(m, Message::Response(r) if r.id == id("f")))
|
||||
.expect("the full");
|
||||
assert!(coloured < first_publish(&sent, &uri), "coloured before the widen finished");
|
||||
// The early answer could not see the package; the widen could, so the
|
||||
// index revision it made is owed exactly one refresh.
|
||||
lane.server.refresh_tokens_if_stale();
|
||||
assert_eq!(lane.refreshes(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colours_arriving_during_a_widen_are_answered_and_the_rest_waits_in_order() {
|
||||
let (_tree, first, second) = two_blocks("midwiden");
|
||||
let mut lane = lane(&_tree.0, refreshing());
|
||||
let first_uri = lane.open(&first, MODULE);
|
||||
lane.drain();
|
||||
let uri = path_to_uri(&second).expect("uri");
|
||||
// On the wire before the burst is taken: these are what the widen's own
|
||||
// drain finds, newer than the whole burst.
|
||||
for message in [lens("h2", &first_uri), range("r2", &first_uri)] {
|
||||
lane.client.sender.send(message).expect("the client's traffic");
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
lane.server.process_batch(vec![opening(&uri, USES_P)]).expect("burst");
|
||||
let sent = lane.drain();
|
||||
let answered: Vec<RequestId> = responses(sent.clone()).into_iter().map(|r| r.id).collect();
|
||||
assert_eq!(answered, vec![id("r2")], "the range colours, the lens waits");
|
||||
let held: Vec<&str> = lane
|
||||
.server
|
||||
.held
|
||||
.iter()
|
||||
.filter_map(|m| match m {
|
||||
Message::Request(r) => Some(r.method.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(held, vec![CodeLensRequest::METHOD]);
|
||||
assert!(lane.server.viewport.guessed.contains(&first_uri), "a range off a widening index");
|
||||
}
|
||||
@@ -37,8 +37,11 @@ impl Workspace {
|
||||
/// `lucisv.largeFile.threshold` is line-indexed and nothing more. Because
|
||||
/// the decision lives here it is re-taken on every `didOpen`, `didChange`
|
||||
/// and text-carrying `didSave`, which is what makes a buffer edited past
|
||||
/// the threshold — or back under it — change mode at that moment and not
|
||||
/// before (`docs/features/large-file-mode/README.md`).
|
||||
/// the threshold — or back under it — change mode at that moment. A
|
||||
/// *changed threshold* reaches the buffers already open through here too:
|
||||
/// the settings applier re-installs each one the new value classifies
|
||||
/// differently (`Server::reclassify_large_buffers`;
|
||||
/// `docs/features/large-file-mode/README.md`).
|
||||
pub fn set_document(&mut self, uri: Uri, text: String) {
|
||||
let path = uri_to_path(&uri);
|
||||
if let Some(dir) = path.as_deref().and_then(Path::parent) {
|
||||
@@ -63,7 +66,7 @@ impl Workspace {
|
||||
/// Whether a buffer of this text takes the fast path. `0` disables it, and
|
||||
/// the comparison is strict, so a buffer of exactly the threshold is still
|
||||
/// analyzed in full.
|
||||
fn is_large(&self, text: &str) -> bool {
|
||||
pub fn is_large(&self, text: &str) -> bool {
|
||||
let threshold = self.client.large_file_threshold;
|
||||
threshold != 0 && text.len() as u64 > threshold
|
||||
}
|
||||
|
||||
@@ -163,11 +163,11 @@ impl Workspace {
|
||||
/// does `index.logFiles`, which changes only how loudly the *next* rescan
|
||||
/// narrates itself.
|
||||
///
|
||||
/// `largeFile.threshold` asks for no rescan either, and deliberately: it
|
||||
/// is consulted where a `Document` is *built*, so a change to it reaches
|
||||
/// each open buffer at that buffer's next `didOpen`/`didChange` and not
|
||||
/// before. A rescan now would index by the mode each buffer is still in,
|
||||
/// which is the mode the index already reflects
|
||||
/// `largeFile.threshold` asks for no rescan either: it is consulted where
|
||||
/// a `Document` is *built*, and the server re-builds exactly the open
|
||||
/// buffers a new value classifies differently, the way an edit would
|
||||
/// (`Server::reclassify_large_buffers`, fast-actions R1); the index takes
|
||||
/// their new mode at their next save or rescan, as it does an edit's
|
||||
/// (`docs/features/large-file-mode/README.md`).
|
||||
pub fn set_client_settings(&mut self, settings: ClientSettings) -> bool {
|
||||
let rescan = self.client.exclude != settings.exclude
|
||||
|
||||
@@ -21,9 +21,13 @@ use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{Definition, ExternalResolutions, Semantics, SymbolKind};
|
||||
|
||||
use crate::state::Document;
|
||||
use crate::state::{first_token_from, first_token_reaching, Document};
|
||||
|
||||
mod instantiation;
|
||||
#[cfg(test)]
|
||||
mod viewport_sweep;
|
||||
#[cfg(test)]
|
||||
mod window_tests;
|
||||
|
||||
/// 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
|
||||
@@ -123,8 +127,41 @@ pub fn semantic_tokens(doc: &Document) -> Vec<SemanticToken> {
|
||||
/// exactly as a full answer's does, and only the tokens outside the range are
|
||||
/// missing. A token that merely overlaps the range is kept whole — the client
|
||||
/// asked which tokens to draw, not where to cut them.
|
||||
///
|
||||
/// **Costs the window, not the file** (`docs/features/viewport-highlight`):
|
||||
/// only the tokens on the lines the range touches are classified, and only the
|
||||
/// items overlapping those lines are walked for instantiation overrides. The
|
||||
/// answer is still exactly the full answer filtered to the range — the same
|
||||
/// pieces from the same tokens through the same `within` — which the tests
|
||||
/// below hold it to over the corpus.
|
||||
pub fn semantic_tokens_in_range(doc: &Document, range: Range) -> Vec<SemanticToken> {
|
||||
encode(&within(absolute(doc), range))
|
||||
if range.start >= range.end {
|
||||
return Vec::new();
|
||||
}
|
||||
let (start, end) = crate::large::line_window(&doc.line_index, doc.text.len() as u32, range);
|
||||
let tokens = window_tokens(&doc.tokens, start, end);
|
||||
let Some((first, last)) = tokens.first().zip(tokens.last()) else { return Vec::new() };
|
||||
let reach = TextRange::new(start.min(first.span.start), end.max(last.span.end));
|
||||
let overrides = instantiation::overrides_within(doc, Some(reach));
|
||||
let mut pieces = Vec::new();
|
||||
for token in tokens {
|
||||
collect(token, doc, &overrides, &mut pieces);
|
||||
}
|
||||
encode(&within(flatten(pieces, doc), range))
|
||||
}
|
||||
|
||||
/// The tokens whose pieces can reach the bytes `start..end`: every token
|
||||
/// touching the window, plus one on either side of it.
|
||||
///
|
||||
/// The neighbours are for their comments. A comment is trivia on the token
|
||||
/// after it (or, trailing, on the token before it), so the block comment that
|
||||
/// opens the window may hang off a token above it and the one that closes it
|
||||
/// off a token below — the EOF token included. One each is enough: trivia
|
||||
/// only ever sits between a token and its immediate neighbour.
|
||||
fn window_tokens(tokens: &[Token], start: u32, end: u32) -> &[Token] {
|
||||
let from = first_token_reaching(tokens, start).saturating_sub(1);
|
||||
let to = (first_token_from(tokens, end) + 1).min(tokens.len());
|
||||
tokens.get(from..to.max(from)).unwrap_or(&[])
|
||||
}
|
||||
|
||||
/// The tokens a range covers of a buffer nothing has lexed — the large-file
|
||||
|
||||
@@ -24,6 +24,22 @@ 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> {
|
||||
overrides_within(doc, None)
|
||||
}
|
||||
|
||||
/// [`overrides`] for the items that overlap `window` only, or for every item
|
||||
/// when there is none — what a viewport's range answer walks, so its cost is
|
||||
/// the items on screen and not the file's.
|
||||
///
|
||||
/// Exact for every token inside the window: each override this walk makes
|
||||
/// lands inside the span of the item that makes it, so an item that does not
|
||||
/// overlap the window has nothing to say about a token in it. The items that
|
||||
/// enclose the window (a module, a package, a generate region) are still
|
||||
/// entered, and only their children are filtered.
|
||||
pub(super) fn overrides_within(
|
||||
doc: &Document,
|
||||
window: Option<TextRange>,
|
||||
) -> HashMap<u32, Highlight> {
|
||||
let mut out = HashMap::new();
|
||||
if doc.tokens.is_empty() {
|
||||
return out;
|
||||
@@ -32,6 +48,7 @@ pub(super) fn overrides(doc: &Document) -> HashMap<u32, Highlight> {
|
||||
tokens: &doc.tokens,
|
||||
semantics: &doc.semantics,
|
||||
external: &doc.external,
|
||||
window,
|
||||
out: &mut out,
|
||||
};
|
||||
ctx.items(&doc.tree.items);
|
||||
@@ -42,13 +59,19 @@ struct Ctx<'a> {
|
||||
tokens: &'a [Token],
|
||||
semantics: &'a Semantics,
|
||||
external: &'a ExternalResolutions,
|
||||
/// The byte range whose tokens are wanted, or `None` for all of them.
|
||||
window: Option<TextRange>,
|
||||
out: &'a mut HashMap<u32, Highlight>,
|
||||
}
|
||||
|
||||
impl<'a> Ctx<'a> {
|
||||
fn items(&mut self, items: &[Item]) {
|
||||
for item in items {
|
||||
self.item(item);
|
||||
let wanted =
|
||||
self.window.is_none_or(|w| item.span.start < w.end && w.start < item.span.end);
|
||||
if wanted {
|
||||
self.item(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
//! The real-code proof for the viewport answer
|
||||
//! (`docs/features/viewport-highlight/README.md`): over every corpus file and
|
||||
//! a sample of OpenTitan, several windows per file, the **local** range answer
|
||||
//! — a buffer analyzed against an *empty* index, which is what a cold start
|
||||
//! colours off — is checked for validity and compared with the **accurate**
|
||||
//! full answer — the same text analyzed against the index of its whole tree —
|
||||
//! restricted to the window.
|
||||
//!
|
||||
//! `#[ignore]`: it indexes two trees and parses several thousand files. Run
|
||||
//! with `tools/guard.sh -- cargo test --release -p lucisv_server
|
||||
//! viewport_sweep -- --ignored --nocapture`. The trees are
|
||||
//! `LUCISV_CORPUS` (default `~/.cache/lucisv-corpus`) and `LUCISV_OPENTITAN_HW`
|
||||
//! (default `~/.cache/lucisv-opentitan-full/hw`); a missing one is skipped
|
||||
//! with a line on stderr.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lsp_types::{Position, Range, SemanticToken};
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{Definition, WorkspaceIndex};
|
||||
|
||||
use super::{semantic_tokens, semantic_tokens_in_range, semantic_tokens_in_window, within};
|
||||
use super::{Absolute, Highlight};
|
||||
use crate::state::{Document, Workspace};
|
||||
|
||||
/// A tree from `var`, else `default` under `$HOME`, when it is there.
|
||||
fn tree(var: &str, default: &str) -> Option<PathBuf> {
|
||||
let root = std::env::var_os(var)
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(default)))?;
|
||||
if !root.is_dir() {
|
||||
eprintln!("{} not there — skipping", root.display());
|
||||
}
|
||||
root.is_dir().then_some(root)
|
||||
}
|
||||
|
||||
/// Every Verilog source under `dir`, sorted so a run is reproducible.
|
||||
fn sources(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
let mut entries: Vec<PathBuf> = entries.flatten().map(|e| e.path()).collect();
|
||||
entries.sort();
|
||||
for path in entries {
|
||||
if path.is_dir() {
|
||||
sources(&path, out);
|
||||
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "svh" | "v")) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Decoded tokens, absolute: (line, start, length, type, modifiers).
|
||||
fn decode(data: &[SemanticToken]) -> Vec<Absolute> {
|
||||
let (mut line, mut start) = (0u32, 0u32);
|
||||
data.iter()
|
||||
.map(|t| {
|
||||
line += t.delta_line;
|
||||
start = if t.delta_line == 0 { start + t.delta_start } else { t.delta_start };
|
||||
Absolute {
|
||||
line,
|
||||
start,
|
||||
length: t.length,
|
||||
ty: t.token_type,
|
||||
modifiers: t.token_modifiers_bitset,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The comment and string spans of the whole file, from its own lex — the
|
||||
/// truth a window answer must never colour across.
|
||||
fn trivia(doc: &Document) -> (Vec<TextRange>, Vec<TextRange>) {
|
||||
let mut comments = Vec::new();
|
||||
let mut strings = Vec::new();
|
||||
for token in &doc.tokens {
|
||||
comments.extend(token.leading.iter().map(|c| c.span));
|
||||
comments.extend(token.trailing.iter().map(|c| c.span));
|
||||
if token.kind == TokenKind::String {
|
||||
strings.push(token.span);
|
||||
}
|
||||
}
|
||||
comments.sort_by_key(|s| s.start);
|
||||
(comments, strings)
|
||||
}
|
||||
|
||||
/// Whether `span` lies inside one of `spans` (sorted by start).
|
||||
fn inside(spans: &[TextRange], span: TextRange) -> bool {
|
||||
let at = spans.partition_point(|s| s.start <= span.start);
|
||||
at > 0 && spans[at - 1].end >= span.end && spans[at - 1].end > span.start
|
||||
}
|
||||
|
||||
/// Every validity rule of a range answer; returns a description of the first
|
||||
/// one broken.
|
||||
fn invalid(doc: &Document, data: &[SemanticToken], range: Range) -> Option<String> {
|
||||
let tokens = decode(data);
|
||||
let positions = doc.positions();
|
||||
let (comments, strings) = trivia(doc);
|
||||
for pair in tokens.windows(2) {
|
||||
let (a, b) = (pair[0], pair[1]);
|
||||
if (a.line, a.start + a.length) > (b.line, b.start) {
|
||||
return Some(format!("out of order or overlapping: {a:?} then {b:?}"));
|
||||
}
|
||||
}
|
||||
for t in &tokens {
|
||||
if t.length == 0 || !(t.from() < range.end && range.start < t.to()) {
|
||||
return Some(format!("empty or outside the range: {t:?}"));
|
||||
}
|
||||
let start = positions.offset(t.from());
|
||||
let end = positions.offset(t.to());
|
||||
if positions.position(end) != t.to()
|
||||
|| doc.text[start as usize..end as usize].contains('\n')
|
||||
{
|
||||
return Some(format!("past the end of its line: {t:?}"));
|
||||
}
|
||||
let span = TextRange::new(start, end);
|
||||
if t.ty != Highlight::Comment as u32 && inside(&comments, span) {
|
||||
return Some(format!("code colour inside a comment: {t:?}"));
|
||||
}
|
||||
if t.ty != Highlight::String as u32
|
||||
&& strings.iter().any(|s| s.start <= start && end <= s.end)
|
||||
{
|
||||
return Some(format!("non-string colour inside a string: {t:?}"));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// How the local answer and the accurate one compare on one window.
|
||||
#[derive(Default)]
|
||||
struct Tally {
|
||||
files: usize,
|
||||
windows: usize,
|
||||
agree: usize,
|
||||
index_resolved: usize,
|
||||
other: usize,
|
||||
examples: Vec<String>,
|
||||
}
|
||||
|
||||
impl Tally {
|
||||
/// Compare token by token, keyed by position. A token both answers carry
|
||||
/// with the same class agrees; a disagreement is **index-resolved** when
|
||||
/// the accurate buffer resolves that name through the index — almost
|
||||
/// always to another file, though an inherited method can resolve to
|
||||
/// this one — and "other" otherwise, the class that must stay empty.
|
||||
fn compare(&mut self, accurate: &Document, local: &[Absolute], truth: &[Absolute]) {
|
||||
let positions = accurate.positions();
|
||||
let mut local = local.iter().peekable();
|
||||
for t in truth {
|
||||
while local.next_if(|l| (l.line, l.start) < (t.line, t.start)).is_some() {
|
||||
self.other += 1;
|
||||
}
|
||||
let found = local.next_if(|l| (l.line, l.start) == (t.line, t.start));
|
||||
if found.is_some_and(|l| l == t) {
|
||||
self.agree += 1;
|
||||
continue;
|
||||
}
|
||||
let offset = positions.offset(t.from());
|
||||
let external = matches!(
|
||||
accurate.external.definition_of(&accurate.semantics, offset),
|
||||
Some(Definition::External(_))
|
||||
);
|
||||
match external {
|
||||
true => self.index_resolved += 1,
|
||||
false => {
|
||||
self.other += 1;
|
||||
if self.examples.len() < 12 {
|
||||
let text = &accurate.text[offset as usize..];
|
||||
let word: String = text.chars().take(24).collect();
|
||||
self.examples.push(format!("{t:?} local={found:?} at {word:?}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.other += local.count();
|
||||
}
|
||||
}
|
||||
|
||||
/// Windows over a file of `lines` lines: whole-line viewports of 60 lines at
|
||||
/// a few deterministic starts, plus one that starts and ends mid-line.
|
||||
fn windows(lines: u32, seed: u64) -> Vec<Range> {
|
||||
let at = |line: u32, character: u32| Position { line, character };
|
||||
let mut out = vec![Range { start: at(0, 0), end: at(60, 0) }];
|
||||
let mut x = seed | 1;
|
||||
for _ in 0..4 {
|
||||
x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
let from = ((x >> 33) % u64::from(lines.max(1))) as u32;
|
||||
out.push(Range { start: at(from, 0), end: at(from + 60, 0) });
|
||||
}
|
||||
out.push(Range { start: at(lines / 2, 7), end: at(lines / 2 + 20, 3) });
|
||||
out
|
||||
}
|
||||
|
||||
/// One tree: index it whole, then sweep `files` of it.
|
||||
fn sweep(root: &Path, every: usize, tally: &mut Tally) {
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![root.to_path_buf()]);
|
||||
let mut files = Vec::new();
|
||||
sources(root, &mut files);
|
||||
let empty = WorkspaceIndex::default();
|
||||
for (n, path) in files.iter().enumerate().filter(|(n, _)| n % every == 0) {
|
||||
let Ok(text) = std::fs::read_to_string(path) else { continue };
|
||||
let local = Document::new(Some(path.clone()), text.clone(), &empty);
|
||||
let accurate = Document::new(Some(path.clone()), text.clone(), ws.index());
|
||||
let fast = Document::large(Some(path.clone()), text);
|
||||
let local_full = super::absolute(&local);
|
||||
let truth_full = decode(&semantic_tokens(&accurate));
|
||||
tally.files += 1;
|
||||
for range in windows(local.line_index.line_count(), n as u64) {
|
||||
let answer = semantic_tokens_in_range(&local, range);
|
||||
if let Some(problem) = invalid(&local, &answer, range) {
|
||||
panic!("{}: {range:?}: {problem}", path.display());
|
||||
}
|
||||
let lexed = semantic_tokens_in_window(&fast, range);
|
||||
if let Some(problem) = invalid(&local, &lexed, range) {
|
||||
panic!("{}: fast path {range:?}: {problem}", path.display());
|
||||
}
|
||||
// The window is exact: it is the full answer filtered, always.
|
||||
let local_window = decode(&answer);
|
||||
assert_eq!(
|
||||
local_window,
|
||||
within(local_full.clone(), range),
|
||||
"{}: {range:?}: the window disagrees with the full answer filtered",
|
||||
path.display()
|
||||
);
|
||||
let truth = within(truth_full.clone(), range);
|
||||
tally.compare(&accurate, &local_window, &truth);
|
||||
tally.windows += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "indexes the corpus and OpenTitan; run with --release --ignored --nocapture"]
|
||||
fn viewport_sweep_local_answers_are_valid_and_agree_with_the_accurate_ones() {
|
||||
let mut tally = Tally::default();
|
||||
if let Some(corpus) = tree("LUCISV_CORPUS", ".cache/lucisv-corpus") {
|
||||
sweep(&corpus, 1, &mut tally);
|
||||
}
|
||||
if let Some(hw) = tree("LUCISV_OPENTITAN_HW", ".cache/lucisv-opentitan-full/hw") {
|
||||
sweep(&hw, 10, &mut tally);
|
||||
}
|
||||
let compared = tally.agree + tally.index_resolved + tally.other;
|
||||
eprintln!(
|
||||
"viewport sweep: {} files, {} windows, {compared} accurate tokens: {} agree ({:.3}%), \
|
||||
{} index-resolved, {} other",
|
||||
tally.files,
|
||||
tally.windows,
|
||||
tally.agree,
|
||||
100.0 * tally.agree as f64 / compared.max(1) as f64,
|
||||
tally.index_resolved,
|
||||
tally.other
|
||||
);
|
||||
for example in &tally.examples {
|
||||
eprintln!(" other: {example}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
//! The range answer's window (`semantic_tokens_in_range`): the shapes where
|
||||
//! selecting a window's tokens could lose a piece the full answer has — a
|
||||
//! comment hanging off a token outside the window — and the claim that its
|
||||
//! cost is the window's and not the file's.
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use lsp_types::{Position, Range};
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
use super::{absolute, semantic_tokens_in_range, within, Absolute};
|
||||
use crate::state::Document;
|
||||
|
||||
fn doc(text: &str) -> Document {
|
||||
Document::new(None, text.to_string(), &WorkspaceIndex::default())
|
||||
}
|
||||
|
||||
fn range(from: (u32, u32), to: (u32, u32)) -> Range {
|
||||
Range {
|
||||
start: Position { line: from.0, character: from.1 },
|
||||
end: Position { line: to.0, character: to.1 },
|
||||
}
|
||||
}
|
||||
|
||||
/// Decoded, for comparing with `within(absolute(..))`.
|
||||
fn decoded(doc: &Document, range: Range) -> Vec<Absolute> {
|
||||
let (mut line, mut start) = (0u32, 0u32);
|
||||
semantic_tokens_in_range(doc, range)
|
||||
.iter()
|
||||
.map(|t| {
|
||||
line += t.delta_line;
|
||||
start = if t.delta_line == 0 { start + t.delta_start } else { t.delta_start };
|
||||
Absolute {
|
||||
line,
|
||||
start,
|
||||
length: t.length,
|
||||
ty: t.token_type,
|
||||
modifiers: t.token_modifiers_bitset,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The window's answer is the full answer filtered, at every whole-line
|
||||
/// window and a few mid-line ones.
|
||||
#[track_caller]
|
||||
fn exact_everywhere(text: &str) {
|
||||
let doc = doc(text);
|
||||
let lines = doc.line_index.line_count();
|
||||
let full = absolute(&doc);
|
||||
for from in 0..=lines {
|
||||
for to in from..=lines + 1 {
|
||||
for r in [range((from, 0), (to, 0)), range((from, 3), (to, 2))] {
|
||||
assert_eq!(decoded(&doc, r), within(full.clone(), r), "{r:?} of {text:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_comment_trailing_a_token_above_the_window_is_still_coloured() {
|
||||
exact_everywhere("wire a; /* opens here\n still a comment\n */ wire b;\nwire c;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_leading_a_token_below_the_window_is_still_coloured() {
|
||||
exact_everywhere("wire a;\n// a line comment\n/* a block\n comment */\nwire b;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_riding_the_end_of_file_token_is_still_coloured() {
|
||||
exact_everywhere("module m;\nendmodule\n// the last word\n/* and a\n block */\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instantiations_continued_defines_and_wide_characters_window_exactly() {
|
||||
exact_everywhere(
|
||||
"`define FF(q, d) \\\n always_ff @(posedge clk) q <= d;\nmodule top;\n \
|
||||
sub #(.W(8)) u0 (\n .a(x), // é 🎉\n .*\n );\nendmodule\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_does_not_lex_and_an_empty_one_answer_nothing_without_panicking() {
|
||||
for text in ["module m; /* unterminated\n wire a;\n", "", "\n\n\n"] {
|
||||
let doc = doc(text);
|
||||
for r in [range((0, 0), (99, 0)), range((5, 0), (2, 0)), range((1, 1), (1, 1))] {
|
||||
assert!(semantic_tokens_in_range(&doc, r).is_empty(), "{r:?} of {text:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// **The cost claim.** The same 60-line viewport of buffers 8x apart in size:
|
||||
/// a window that classified the file would cost ~8x at the largest, a window
|
||||
/// that classifies the window costs about the same at every size. Asserted
|
||||
/// on the shape, fastest of five, with a slack of 3x — the same shape check
|
||||
/// `large.rs`'s linear-time gates use, for the same reason (a shared machine
|
||||
/// and a debug build move the absolute numbers, not the ratio).
|
||||
#[test]
|
||||
fn a_viewport_costs_the_window_not_the_file() {
|
||||
let block = "module m;\n localparam W = 8;\n logic [W-1:0] q;\n \
|
||||
sub #(.W(W)) u (.clk_i(clk), .q_o(q)); // tail\nendmodule\n";
|
||||
let sizes = [500usize, 4000];
|
||||
let docs: Vec<Document> = sizes.iter().map(|&n| doc(&block.repeat(n))).collect();
|
||||
let viewport = range((1000, 0), (1060, 0));
|
||||
let mut fastest = [Duration::MAX; 2];
|
||||
for _ in 0..5 {
|
||||
for (best, doc) in fastest.iter_mut().zip(&docs) {
|
||||
let clock = Instant::now();
|
||||
assert!(!semantic_tokens_in_range(doc, viewport).is_empty());
|
||||
*best = (*best).min(clock.elapsed());
|
||||
}
|
||||
}
|
||||
let growth = fastest[1].as_secs_f64() / fastest[0].as_secs_f64().max(f64::MIN_POSITIVE);
|
||||
eprintln!(
|
||||
"60-line viewport: {:?} (500 modules) vs {:?} (4000 modules)",
|
||||
fastest[0], fastest[1]
|
||||
);
|
||||
assert!(growth < 3.0, "8x the file cost {growth:.1}x the viewport: {fastest:?}");
|
||||
}
|
||||
@@ -77,7 +77,7 @@ pub fn type_definition(ws: &Workspace, uri: &Uri, offset: u32) -> Vec<Location>
|
||||
/// Case 2 is deliberately a use and never a declaration: the cursor on the
|
||||
/// `alias_t` of `typedef state_t alias_t;` is on a declaration whose own type
|
||||
/// is written beside it, and answering "itself" there would waste the hop.
|
||||
fn type_name(doc: &Document, offset: u32) -> Option<TextRange> {
|
||||
pub(crate) fn type_name(doc: &Document, offset: u32) -> Option<TextRange> {
|
||||
if let Some(site) = site_at(&doc.tree.items, offset) {
|
||||
if let Some(span) = type_span(&doc.semantics, &site) {
|
||||
if span.contains(offset) {
|
||||
|
||||
@@ -2490,16 +2490,18 @@ 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.
|
||||
// `5`, not `2`: `completion-ux` (2026-11-17) put this file's own
|
||||
// declarations (`2`) and words (`3`) ahead of what other files declare,
|
||||
// and `fast-actions` (2026-11-19) what the file is related to (`4`).
|
||||
let macro_name = labelled("WIDGET_MACRO").expect("a `define name");
|
||||
assert!(macro_name["sortText"].as_str().expect("sortText").starts_with('4'));
|
||||
assert!(macro_name["sortText"].as_str().expect("sortText").starts_with('5'));
|
||||
|
||||
let elsewhere = labelled("widget_elsewhere").expect("a word used in the project");
|
||||
assert_eq!(elsewhere["kind"], 1, "CompletionItemKind.Text");
|
||||
// `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'));
|
||||
// `8`: M6 inserted the template tier above the keywords,
|
||||
// `completion-ux` the two current-file tiers above the index, and
|
||||
// `fast-actions` the related tier.
|
||||
assert!(elsewhere["sortText"].as_str().expect("sortText").starts_with('8'));
|
||||
|
||||
assert!(
|
||||
!items.iter().any(|item| item["sortText"].as_str().is_some_and(|s| s.starts_with('0'))),
|
||||
@@ -2675,12 +2677,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('5'));
|
||||
assert!(template["sortText"].as_str().expect("sortText").starts_with('6'));
|
||||
|
||||
// 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('6'));
|
||||
assert!(keyword["sortText"].as_str().expect("sortText").starts_with('7'));
|
||||
|
||||
// A `.v` buffer is offered Verilog's `always`, never `always_ff`.
|
||||
let verilog = messages.iter().find(|m| m["id"] == 3).expect("completion response");
|
||||
@@ -8474,11 +8476,19 @@ fn indexed_neighbours(dir: &Path, files: usize) {
|
||||
/// leave the request behind it waiting.
|
||||
///
|
||||
/// **An upper bound, not a benchmark, and a debug-build one.** `cargo test`
|
||||
/// builds unoptimized, where one tolerant parse of 2 000 lines is ~53 ms all
|
||||
/// by itself — measured on this machine, and stable to a millisecond across
|
||||
/// runs. So the 200 ms here is that floor with room for a loaded CI box, not
|
||||
/// the ≤ 25 ms §46 asked for: **that figure is a release number**, and the
|
||||
/// release binary opens the same buffer in 2–4 ms.
|
||||
/// builds unoptimized, where one tolerant parse of 2 000 lines is 11–53 ms
|
||||
/// all by itself on the dev machines and 50–70 ms on the Linux runner. The
|
||||
/// ≤ 25 ms §46 asked for is **a release number** (the release binary opens
|
||||
/// the same buffer in 2–4 ms), so it is not what is asserted here.
|
||||
///
|
||||
/// **The budget is measured, not written down.** A fixed 200 ms was that
|
||||
/// floor with room on the dev machine, and nothing anywhere else: the Linux
|
||||
/// CI box (4 CPUs, under the whole suite) took 205 ms for its *best* of
|
||||
/// three. So the floor is measured in this process, next to every open: one
|
||||
/// tolerant parse of the same buffer, through the same parser in the same
|
||||
/// build. The open must cost at most [`OPEN_OVER_PARSE`] of those — which is
|
||||
/// what "bounded" means for an open that must parse its buffer anyway — and
|
||||
/// a machine or a moment that is slower slows both.
|
||||
///
|
||||
/// **What this test does and does not catch.** It catches an open that starts
|
||||
/// doing something *unbounded* — the shape §46 fixed. It cannot catch the
|
||||
@@ -8490,15 +8500,16 @@ fn indexed_neighbours(dir: &Path, files: usize) {
|
||||
/// which counts the questions instead of timing them
|
||||
/// (`docs/features/didopen-cost/README.md`).
|
||||
///
|
||||
/// Best of three distinct buffers: the first open of a process pays cold code
|
||||
/// paths that have nothing to do with the buffer, and a wall-clock assertion
|
||||
/// that cannot tolerate one scheduling hiccup is a flake, not a pin.
|
||||
/// Best of [`OPEN_ROUNDS`] distinct buffers, and the best of as many parses:
|
||||
/// the first open of a process pays cold code paths that have nothing to do
|
||||
/// with the buffer, and a wall-clock assertion that cannot tolerate one
|
||||
/// scheduling hiccup is a flake, not a pin.
|
||||
#[test]
|
||||
fn opening_a_two_thousand_line_buffer_does_not_delay_the_request_behind_it() {
|
||||
let dir = temp_dir("didopen_cost");
|
||||
indexed_neighbours(&dir, 40);
|
||||
let mut generated = Vec::new();
|
||||
for n in 0..3 {
|
||||
for n in 0..OPEN_ROUNDS {
|
||||
let name = format!("gen{n}");
|
||||
// The generator the perf tables use: a thousand declarations, every
|
||||
// one declared, driven and read — the cheap case for the *findings*
|
||||
@@ -8514,20 +8525,51 @@ fn opening_a_two_thousand_line_buffer_does_not_delay_the_request_behind_it() {
|
||||
let warm = format!("file://{}", dir.join("pkg0.sv").display());
|
||||
open_then_hover(&mut live, 10, &warm, "package pkg0;\n localparam int K0 = 0;\nendpackage\n");
|
||||
|
||||
let mut best = std::time::Duration::MAX;
|
||||
// Each round times the floor, then the open, so load that comes and goes
|
||||
// lands on both kinds of sample alike.
|
||||
let (mut open, mut parse) = (std::time::Duration::MAX, std::time::Duration::MAX);
|
||||
for (n, (path, text)) in generated.iter().enumerate() {
|
||||
parse = parse.min(one_tolerant_parse(text));
|
||||
let uri = format!("file://{}", path.display());
|
||||
best = best.min(open_then_hover(&mut live, 20 + n as u32, &uri, text));
|
||||
open = open.min(open_then_hover(&mut live, 20 + n as u32, &uri, text));
|
||||
}
|
||||
live.finish();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
let ratio = open.as_secs_f64() / parse.as_secs_f64();
|
||||
eprintln!("didOpen of 2 000 lines: best open {open:?}, best parse {parse:?}, {ratio:.2}x");
|
||||
assert!(
|
||||
best <= std::time::Duration::from_millis(200),
|
||||
"a didOpen of a 2 000-line buffer delayed the next request by {best:?}"
|
||||
ratio <= OPEN_OVER_PARSE,
|
||||
"a didOpen of a 2 000-line buffer delayed the next request by {open:?}, \
|
||||
{ratio:.2}x one parse of it ({parse:?}); the budget is {OPEN_OVER_PARSE}x"
|
||||
);
|
||||
}
|
||||
|
||||
/// Distinct 2 000-line buffers opened, and parses timed, by the test above.
|
||||
const OPEN_ROUNDS: usize = 5;
|
||||
|
||||
/// How many parses of its own buffer an open may cost, request included.
|
||||
///
|
||||
/// Measured 2026-11-19 (best of five each, debug build): the open costs
|
||||
/// 2.5–3.2 parses on the dev machine, quiet or under 36 busy loops on its 18
|
||||
/// CPUs; 2.3–3.6 on the 4-CPU Linux runner when quiet; and 2.5–3.3 there
|
||||
/// under 8 busy loops, where the open itself took ~1 s (the old fixed
|
||||
/// 200 ms would have failed every run there). The ratio holds still while the wall
|
||||
/// clock moves 6x. Six is ~1.7x over the worst ratio seen; an open made to
|
||||
/// parse its buffer four extra times fails it (6.9x on the dev machine,
|
||||
/// where the old 200 ms passed that at 84 ms), three extra times is ~5.9x
|
||||
/// (`docs/features/linux-test-portability/README.md`, round 2).
|
||||
const OPEN_OVER_PARSE: f64 = 6.0;
|
||||
|
||||
/// The wall clock of one tolerant parse of `text`, in this process.
|
||||
fn one_tolerant_parse(text: &str) -> std::time::Duration {
|
||||
let started = std::time::Instant::now();
|
||||
let (file, _) = vlog_parser::parse_source_tolerant(text);
|
||||
let took = started.elapsed();
|
||||
std::hint::black_box(file);
|
||||
took
|
||||
}
|
||||
|
||||
/// The other half of §46's contract: the request after an open is answered
|
||||
/// from the **buffer**, not from what is on disk.
|
||||
///
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -396,7 +396,10 @@ auto is the idempotency above.
|
||||
- [x] Fix round (QA F1–F8): auto measure counts indentation; server remembers
|
||||
the preset per document; labelled-`end` `else` for google/lowrisc; presets
|
||||
as one table; doc corrections
|
||||
- [ ] Lane 71.1: `lint.rs` line-length width from the style (Handshake request above)
|
||||
- [x] Lane 71.1: `lint.rs` line-length width from the style (Handshake request above)
|
||||
— delivered by localized-reindex (lane 71.1, round 3) and released in
|
||||
0.65.6: `crates/lucisv_server/src/lint.rs` falls back to the chosen style's
|
||||
width (`file.format_style.or(client.style)` → `style::preset`), else 100
|
||||
|
||||
## Work log
|
||||
|
||||
|
||||
@@ -200,6 +200,10 @@ expansion state survives every relight.
|
||||
- `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.
|
||||
- `BAR_COLOR` (`lucisv.hierarchyCurrentBar`, the lit row's left bar) and
|
||||
`nodeDistance(node, path)` (a node's distance, `undefined` when unlit) are
|
||||
exported too; `hierarchyView.js` reads neither (`BAR_COLOR` is read by
|
||||
`hierarchyCurrent_test.js` and `hierarchyPalette_test.js`).
|
||||
|
||||
### `hierarchyView.js` → `media/hierarchy.js` (the wire inside the extension)
|
||||
|
||||
|
||||
@@ -120,7 +120,8 @@ line 7 shows module → `if (a) begin` → `if (b) begin`.
|
||||
prefix) is private in `vlog_parser/src/parser/directive.rs:15-28`; it is four
|
||||
lines and is repeated in `folding/directives.rs` rather than widened into
|
||||
the parser's public surface. (A third copy, by first whitespace word, lives
|
||||
in `on_type/auto_end.rs:258`.) If a public `Token::directive_word` is ever
|
||||
in `on_type/auto_end.rs:258-261`, `conditional`; the first-word split is
|
||||
line 259.) If a public `Token::directive_word` is ever
|
||||
added, all three should use it — a request, not a blocker.
|
||||
- **Promises** `folding::folding_ranges` (the only caller is
|
||||
`server/dispatch.rs`, unchanged): sorted by start line (tie-break in
|
||||
|
||||
@@ -105,8 +105,15 @@ Because the decision lives in `set_document`, it is re-taken on every
|
||||
`didOpen`, every `didChange` and every text-carrying `didSave`. A buffer edited
|
||||
past the threshold switches to the fast path at that moment; one edited back
|
||||
under it is analyzed again in full. **A changed `lucisv.largeFile.threshold`
|
||||
therefore takes effect at each buffer's next change, not immediately** — the
|
||||
simplest rule that has no re-analysis storm in it, and the one the tests pin.
|
||||
takes effect on the open buffers at once** (since `fast-actions`, 2026-11-19;
|
||||
before it, at each buffer's next change): the settings applier re-analyzes
|
||||
exactly the open, clean buffers the new value classifies differently
|
||||
(`Server::reclassify_large_buffers`, called by `apply_settings` for the
|
||||
startup's settings answer and every later push), republishes each once and asks
|
||||
a capable client to re-request its colours. An unchanged threshold costs one
|
||||
comparison, a dirty buffer takes the new value at its flush, and like an edit
|
||||
this does not reindex — the index takes the buffer's new mode at its next save
|
||||
or rescan (`docs/features/fast-actions/README.md`, Handshake request 8).
|
||||
|
||||
## The dispatch table
|
||||
|
||||
@@ -324,9 +331,11 @@ rebuilds the buffer (O(file) per batch, and edits in a netlist are rare) and
|
||||
built-in LSP) asks for ranges.
|
||||
- **The buffer's text stays in memory.** 100 MB of `String` is the price of
|
||||
answering anything at all; the editor holds a copy too.
|
||||
- **The threshold is not consulted anywhere but `set_document`.** A setting
|
||||
changed while a buffer is open leaves that buffer in the mode it was built
|
||||
in until its next change.
|
||||
- **The threshold is consulted in `set_document`, and by the settings applier
|
||||
for the buffers already open** (`Workspace::is_large`). A setting changed
|
||||
while a buffer is open moves that buffer to the mode the new value gives it
|
||||
at once, by re-analyzing it through `set_document`
|
||||
(`Server::reclassify_large_buffers`).
|
||||
- **VS Code ≥ 1.134 behaves as the bundle read here says.** The two facts
|
||||
relied on — "complete tokens stop the viewport provider" and "an error is not
|
||||
a complete answer" — have been in VS Code for years, and the range provider
|
||||
|
||||
@@ -36,13 +36,52 @@ the assertion where it *can* run.
|
||||
## Handshakes
|
||||
|
||||
- Consumes nothing new from production code. No production file, no
|
||||
`verify.rs`, no workflow, version file or changelog changes.
|
||||
`verify.rs`, no workflow, version file or changelog changes — **except**
|
||||
the round 2 product fix the lead granted (2026-11-19):
|
||||
`crates/lucisv_mcp/src/project/files.rs` and its test fixture
|
||||
`project/tests.rs`. `Stamp`'s public shape changed (`identity` is now
|
||||
`Option<Identity>`, new `read_mono`); its only users are inside
|
||||
`lucisv_mcp::project`, nothing outside the crate sees it.
|
||||
- `tools/linux_check.sh` (the lead's): used as written in round 1; changed
|
||||
in the fix round (QA finding 5, see the work log). Its usage line gained
|
||||
`--dry-run`; the single-string form is unchanged.
|
||||
- Scope extension granted by the lead in the fix round:
|
||||
`crates/lucisv_server/src/server/tests/scan_trace.rs` (test file only).
|
||||
- Requests: none.
|
||||
- Requests: none (round 1).
|
||||
- **Round 2 request: a product bug, not a test flake. Owner: `lucisv_mcp`.**
|
||||
`crates/lucisv_mcp/src/project/files.rs:166-184`, `Stamp::check`. The
|
||||
racy rule (`mtime + RACY > read_at`, line 175) covers the mtime only. The
|
||||
ctime half of `identity` (line 214) has no racy rule. On Linux 6.8
|
||||
(luhpe: ext4 under overlayfs, `CONFIG_HZ=1000`) the kernel stamps ctime
|
||||
from the coarse clock, in 1 ms steps. Suppose a file's ctime moves (here a
|
||||
rename-over), the server stats and reads it, and the file is rewritten at
|
||||
the same size with its old mtime put back (`cp -p`, `rsync -t`,
|
||||
`touch -r`), all within the same 1 ms tick. Then size, mtime, ctime and
|
||||
inode all match the stamp. The check answers `Same`, and the stale
|
||||
contents are served **for good**, because every later stat says the same.
|
||||
- Reproduction:
|
||||
`tools/linux_check.sh 'for i in $(seq 150); do cargo test -q -p lucisv_mcp --test qa_m1 qa_rework_a_rename_over_with_an_old_mtime_and_the_same_size_is_seen -- --exact; done'`.
|
||||
Result: 12/150 failed as root with nothing else running, and 39/300 in
|
||||
an earlier loop. It also failed once in the full suite as `--user` before
|
||||
this round.
|
||||
- Instrumented, by printing `(ctime, ctime_nsec, ino)` of `c.sv` after the
|
||||
rename and after the rewrite (a temporary edit, since reverted). Every
|
||||
failure had the two identical to the nanosecond. In every pass (261
|
||||
printed) they were 1 or 2 ms apart, never 0. The `find` between them
|
||||
took 0.44–0.66 ms. The failing answer was
|
||||
``no declaration named `chyrlie`.``
|
||||
- macOS: APFS ctime comes from a fine clock, so it always moves, and the
|
||||
test has never failed there.
|
||||
- **Resolved in round 2 by the lead's scope extension** (work log,
|
||||
"the stamp fix"). The suggestion was: give ctime the racy
|
||||
rule mtime has. A stamp whose ctime is within `RACY` of `read_at` is
|
||||
`Suspect`, so it is re-read and re-hashed until it is older. The same
|
||||
argument as git's racily-clean entries.
|
||||
- The test was **left unchanged** on purpose, and still is. It is right,
|
||||
and making it wait for the clock to tick would hide the bug. Before the
|
||||
fix it failed about 1 in 10 runs alone on that box. Under load it fails less
|
||||
often, because the `find` then takes longer than a tick: 0/200 under
|
||||
8 busy loops.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
@@ -54,11 +93,13 @@ the assertion where it *can* run.
|
||||
- [x] The two linear-time tests bound growth, not wall-clock; shown to trip
|
||||
on the quadratic conversion on macOS and on the Linux runner.
|
||||
- [x] Cleaning round (see work log).
|
||||
- [ ] Linux suite green as root (twice) and as `--user`. Observed: root
|
||||
- [x] Linux suite green as root (twice) and as `--user`. Observed: root
|
||||
once green; `--user` once with one failure, the new flake
|
||||
`scan_trace::the_stages_add_up_to_the_scan_they_describe` (open, see
|
||||
the work log); the second root run and the flake's diagnosis were cut
|
||||
off when ssh to luhpe stopped working.
|
||||
off when ssh to luhpe stopped working. Done in Round 2: 10 of 10 green
|
||||
as root and 10 of 10 as `--user` (dev), 6 of 6 each (QA) — work log
|
||||
and QA log.
|
||||
- [x] `tools/gates.sh` green on macOS (see the work log for each run).
|
||||
- [x] Fix round: `scan_trace` lower bound on the best of three sessions;
|
||||
linear-time tests best of five; `tools/linux_check.sh` hardened.
|
||||
@@ -67,8 +108,31 @@ the assertion where it *can* run.
|
||||
times a copy of the `Server::large_scan` loop, not the production loop
|
||||
at `server/large_file.rs:151`, so a per-hit rescan reintroduced there
|
||||
would not be caught. Needs a test that drives the production path.
|
||||
- [ ] Re-run on Linux once ssh to luhpe is back: everything in the fix round
|
||||
and everything since 0.65.2 is unverified there (list in the work log).
|
||||
- [x] Re-run on Linux once ssh to luhpe is back. Done in round 2, against
|
||||
0.65.6 plus this round (see the round 2 work log).
|
||||
|
||||
### Round 2 (flakes on Linux)
|
||||
|
||||
- [x] Census: 2 090 single-test iterations on Linux (alone and under load)
|
||||
and 57 whole-suite runs (Linux root and `--user`, macOS under load).
|
||||
Every test that failed even once is in the table in the work log.
|
||||
- [x] stdin `BrokenPipe` on a child that exits before reading: `cli.rs`
|
||||
(both stdin helpers) and `qa_m8.rs` (`run`) tolerate that one error
|
||||
and still assert on the exit code and output.
|
||||
- [x] `e2e.rs` didOpen budget: a multiple of one parse of the same buffer
|
||||
measured in the same process, instead of a fixed 200 ms.
|
||||
- [x] `qa_m3.rs` CLI-while-formatting hang on macOS (an inherited pipe):
|
||||
the server is spawned before the checker thread starts.
|
||||
- [x] Every other wall-clock assertion reviewed; each left as it was, with
|
||||
the reason (work log).
|
||||
- [x] **Product bug, fixed (scope extended by the lead):** `qa_m1.rs`
|
||||
`qa_rework_a_rename_over_with_an_old_mtime_and_the_same_size_is_seen`
|
||||
failed on Linux about 1 run in 10 alone — a real staleness bug in
|
||||
`Stamp::check` (Handshakes). The racy rule now covers the ctime, the
|
||||
window is 3 s, and a wall clock stepped back distrusts every stamp;
|
||||
the test itself is unchanged.
|
||||
- [x] Audit of the other caches for the same hole: none has it (work log).
|
||||
- [x] Deterministic unit tests of the racy decision; mutations shown.
|
||||
|
||||
## Work log
|
||||
|
||||
@@ -276,6 +340,335 @@ Unverified on Linux (all of it rests on round 1, against 88546c8 + lane):
|
||||
- everything trunk added in 0.65.2 and 0.65.3;
|
||||
- the second root run, which never happened in round 1 either.
|
||||
|
||||
### Round 2
|
||||
|
||||
**2026-11-19 (dev, round 2: the Linux flakes).** Tree: 58d3db3 (0.65.6) plus
|
||||
this round, in `lucisv-wt/70b`. The brief reported master's record on Linux
|
||||
as 9 full runs, 3 with a failure, each from a different test. Linux means
|
||||
`tools/linux_check.sh` on luhpe: the CI job image, 4-CPU cap, kernel
|
||||
6.8.0, ext4 under overlayfs, `CONFIG_HZ=1000`, debug build. macOS means
|
||||
arm64 with 18 CPUs; another lane was running there too. Every macOS
|
||||
`cargo test` went through `tools/guard.sh`, and there was no guard kill.
|
||||
|
||||
*Method.*
|
||||
- Loops of the single test, in the job image, run alone and then under 8
|
||||
busy loops on the 4-CPU cap. The baseline was rebuilt in the same
|
||||
container with `git apply -R` of this round's patch, so before and after
|
||||
share one build cache and one box.
|
||||
- Whole-suite runs with `--no-fail-fast`. Each one keeps its result totals
|
||||
and every failing test's output.
|
||||
- Temporary instrumentation where the output was not enough. It was taken
|
||||
out again, and each touched file was restored from a copy and checked
|
||||
with `cmp`.
|
||||
|
||||
**Flake census**
|
||||
|
||||
| test | platform | before | cause | fix | after |
|
||||
|---|---|---|---|---|---|
|
||||
| `lucisv/tests/cli.rs` `stdin_and_lines_are_usage_errors_with_a_filelist` | Linux root | 2/9 master runs; 1/5 baseline runs; loop 0/200 alone, **42/200 loaded** | `run_with_stdin` `expect`ed the stdin write. A usage error exits before reading, so the write races the exit and gets `BrokenPipe`. | Both stdin helpers write through `feed`, which ignores `BrokenPipe` only; `run_with_stdin` is now `run_with_stdin_raw` plus `--no-cache`. | loop 0/200 alone, **0/200 loaded**; 0 in 30 Linux suite runs |
|
||||
| `lucisv_mcp/tests/qa_m8.rs` `qa_argument_order_and_repetition_cannot_undo_read_only` | Linux root | 1/5 baseline runs; loop 0/200 alone, **37/100 loaded** | Same race: `run` `unwrap`ped `writeln!` to a server that refuses `--read-only=false` and friends with exit 2. Found by the census; not in the brief. | `run` stops writing on `BrokenPipe` and `unwrap`s any other error. | loop 0/200 alone, **0/100 loaded**; 0 in 30 suite runs |
|
||||
| `lucisv_server/tests/e2e.rs` `opening_a_two_thousand_line_buffer_does_not_delay_the_request_behind_it` | Linux root | 2/9 master runs (205.15 ms against 200) | A fixed 200 ms against a measured floor of 146–179 ms best of three, quiet. Under 8 busy loops the open took 0.5–1.1 s, so the old bound would fail every time. | The budget is `OPEN_OVER_PARSE` (6) times the best of 5 in-process tolerant parses of the same buffer, interleaved with the 5 opens. | 0/20 alone, 0/20 loaded; 0 in 30 suite runs |
|
||||
| `lucisv_mcp/tests/qa_m1.rs` `qa_rework_a_rename_over_with_an_old_mtime_and_the_same_size_is_seen` | Linux | 1/9 master runs (`--user`); loop **39/300 and 12/150 alone**, 0/200 loaded | **A product bug** (Handshakes): ctime moves in 1 ms ticks, and a same-size rewrite with the old mtime put back inside the tick is invisible to `Stamp::check`. All 12 instrumented failures had identical `(ctime, nsec, ino)`; all 261 instrumented passes were 1–2 ms apart. | **None, on purpose.** The test is right. | unchanged: 0 in the last 30 Linux suite runs, but about 1 in 10 alone |
|
||||
| `lucisv_mcp/tests/qa_m3.rs` `qa_lucisv_check_over_the_same_tree_while_the_server_formats` | macOS, under 18 busy loops | **hung** once in 2 runs (still running after 9 min) | `sample` showed the checker thread in `Command::output` → `read`, with no `lucisv` child alive. `lsof` showed the test's `lucisv-mcp` server holding the other end of that pipe: it had inherited the pipe when it was spawned while the checker was making one (macOS has no `pipe2`). `join` waited on the checker, and the server lived until the test ended. Found by the census. | The server is spawned before the checker thread starts. | 0 hangs in 20 macOS runs under load; 0 in 20 Linux runs |
|
||||
|
||||
Nothing else failed in any run: Linux root 5 baseline runs, then 10 + 10 on
|
||||
the fixed tree; Linux `--user` 10; macOS 2 + 20 under load (the second
|
||||
batch under 9 busy loops, since 18 put one suite run over 20 min). Round 1's
|
||||
`scan_trace` and `large.rs` fixes ran on Linux in all of them and never
|
||||
failed.
|
||||
|
||||
**The wall-clock assertions** (an inventory of every test-code assertion on
|
||||
measured time):
|
||||
- **Changed:** e2e.rs didOpen (above).
|
||||
- **Ratios already:** `large.rs` `assert_grows_linearly` (round 1);
|
||||
`lens.rs:756` (`whole_file * 10 < walk`); `scan_trace.rs` (round 1).
|
||||
- **Algorithmic guards with absolute bounds, left as they are:**
|
||||
`pairs.rs:1159/1171/1190` (2 s, ~45x the honest 5–44 ms, against 7–17 s
|
||||
quadratic); `regex.rs:631` (500 ms against microseconds, exponential
|
||||
matcher far past it); `lexer.rs:1313` (5 s, "three orders of magnitude"
|
||||
in either build); `e2e.rs:5780` (10 s, 25x the measured 0.4 s). The
|
||||
regression each one guards is two or more orders of magnitude past its
|
||||
bound, and the honest cost is one or more below it, so a ratio would buy
|
||||
nothing. None failed in any run.
|
||||
- **"Nothing was waited for" bounds, left as they are:** `startup.rs:488`
|
||||
and `:1071` (< 1 s, against a 2 s bound and a 25 ms bound),
|
||||
`startup.rs:528` (< 5 s against a 30 s bound), `e2e.rs:9118/9130` (< 1 s
|
||||
against the 1.5 s grace). Each has to stay under the wait it proves was
|
||||
skipped, so raising it is not free, and none failed.
|
||||
- **Lower bounds** (`e2e.rs:9096/9193`, `startup.rs:182`): load can only
|
||||
make them pass.
|
||||
- **Corpus-only latency budgets**: `hierarchy.rs:1123`, `lens.rs:754`,
|
||||
`type_hierarchy.rs:1289/1291`, `completion/mod.rs:787-789/856`,
|
||||
`vlog_refactor/tests/corpus.rs:100/175`, `vlog_semantic/tests/workspace.rs:977`.
|
||||
These skip without `corpus/`, which the Linux tree does not have. They
|
||||
are budgets for a known machine. Not changed, and not exercised on
|
||||
Linux.
|
||||
- **`#[ignore]`d:** `large.rs:727-735`, `:764`.
|
||||
|
||||
**The mtime/sleep review.**
|
||||
- `set_modified` users:
|
||||
- `wire.rs:1250`, `qa_m6.rs:568` and `qa_f1.rs:666` set an hour-old mtime
|
||||
on purpose. They do not rely on it moving.
|
||||
- `qa_m1.rs:588`, a rename-then-recreate, gets a new inode.
|
||||
- `qa_m1.rs:605`, a same-mtime rewrite, rests on the racy rule.
|
||||
- `qa_m1.rs:617` restores an old mtime. Its ctime moves across a process
|
||||
spawn and two calls, far more than a tick.
|
||||
- `qa_m1.rs:936` is the product bug above.
|
||||
- Sleeps: `qa_m3.rs:598/622`, `e2e.rs:9151` (the 1.7 s that outlasts the
|
||||
1.5 s grace) and `cancel.rs:347`. None failed, so all are left.
|
||||
|
||||
**Stdin writers reviewed.** Every test that writes to a child's stdin was
|
||||
checked:
|
||||
- The interactive sessions (`cache`, `qa_m2/3/4/6`, `qa_f1/f2`, `attacks`,
|
||||
`read_only`, `wire`, `opentitan*`, `e2e`'s `Live`) only write to a server
|
||||
the test expects to be alive. A `BrokenPipe` there means the server died,
|
||||
which is a failure, so those writes stay strict.
|
||||
- The one-shot sessions write to a server that reads to EOF and exits only
|
||||
when told to, so the strict write stays: `e2e.rs` `talk_with`,
|
||||
`ifdef_folding.rs` `talk`, `qa_m7.rs`, `hierarchy_cap.rs`.
|
||||
- `qa_m1.rs` `one_shot` already ignored write errors.
|
||||
|
||||
**Evidence the stdin fixes neither hide anything nor weaken anything** (macOS):
|
||||
- With a 300 ms sleep before the write (the race made certain), the **old**
|
||||
helpers fail 1/1 with `BrokenPipe` (`cli.rs:104`, `qa_m8.rs:117`). The
|
||||
fixed ones pass, and so does the whole of `cli` (113/113) and `qa_m8`
|
||||
(6/6) with the sleep in. So no test needed the write to succeed. It never
|
||||
meant the child had read anything: every input is far smaller than a pipe
|
||||
buffer.
|
||||
- Sleeps removed; both files compared with `cmp` against copies.
|
||||
|
||||
**Mutation table** (production sabotage on macOS, restored from a copy and
|
||||
checked with `cmp` / `git status`):
|
||||
|
||||
| test | sabotage | failed? | restored |
|
||||
|---|---|---|---|
|
||||
| cli `stdin_and_lines_are_usage_errors_with_a_filelist` | `args.rs:486` `if false && …` (accept `-` with `-f`) | yes, cli.rs:1942 `left: 0, right: 2` | yes |
|
||||
| qa_m8 `qa_argument_order_and_repetition_cannot_undo_read_only` | `lucisv_mcp/src/main.rs:93` accept `--readonly` as `--read-only` | yes, qa_m8.rs:342 "started a server" | yes |
|
||||
| e2e didOpen | `server/notification.rs` didOpen: parse the buffer 4 extra times | yes, 3/3 at 6.94x (84 ms; the old 200 ms would pass) | yes |
|
||||
| e2e didOpen (sensitivity) | the same, 3 extra times | no, 3/3 passed at 5.82–5.97x | yes |
|
||||
| qa_m3 `qa_lucisv_check_over_the_same_tree_while_the_server_formats` | `apply.rs` `commit` writes `after` plus `"\n"` | yes, qa_m3.rs:745 `m00.sv` | yes; then 3/3 pass |
|
||||
|
||||
*The didOpen ratio, measured.*
|
||||
|
||||
| where | load | best open | best parse | ratio |
|
||||
|---|---|---|---|---|
|
||||
| macOS | quiet, 8 runs | 31 ms | 11 ms | 2.66–2.77x |
|
||||
| macOS | 36 busy loops on 18 CPUs, 15 runs | 34–41 ms | 12–14 ms | 2.48–3.15x |
|
||||
| Linux root | quiet, 20 runs | 146–179 ms | 50–73 ms | 2.29–3.55x |
|
||||
| Linux root | 8 busy loops on 4 CPUs, 20 runs | 0.50–1.12 s | 188–394 ms | 2.50–3.29x |
|
||||
|
||||
The wall clock moves 6x and the ratio stays in 2.3–3.6x, so 6 has about
|
||||
1.7x headroom over the worst ratio seen.
|
||||
- What it buys: on this Mac the new bound is *stricter* than the old one.
|
||||
Four extra parses fail it at 84 ms, where 200 ms needed about 15 extra.
|
||||
- What it costs: on the quiet Linux runner it is looser. There the old
|
||||
bound sat at the box's floor, which is why it flaked.
|
||||
- What it still cannot catch: the §46 defect itself, at this fixture's
|
||||
size, as the test's doc comment always said.
|
||||
|
||||
**Counts.**
|
||||
- `#[test]` attributes: 5 471 at HEAD and in this tree. No test was added
|
||||
or removed.
|
||||
- macOS whole suite: 97 result lines, **5413 passed, 0 failed, 64 ignored**
|
||||
on every run here.
|
||||
- Linux: **5407 passed, 0 failed, 64 ignored**. The six macOS/Windows-only
|
||||
tests are not compiled there.
|
||||
|
||||
**Final runs on the final tree** (Linux, all of the above changes):
|
||||
- root: `cargo clippy --all-targets -- -D warnings` exit 0; `cargo test
|
||||
--workspace --no-fail-fast` green **10 consecutive runs of 10**, each 97
|
||||
result lines, 5407 passed, 0 failed, 64 ignored.
|
||||
- `--user`: clippy exit 0; tests green **10 consecutive runs of 10**, the same
|
||||
totals.
|
||||
- macOS, after the last `crates/` edit: `tools/gates.sh` **PASS**
|
||||
(`target/gates/20261119-111810/`). That covers fmt, clippy, build and docs,
|
||||
suites 521/435/743/376/672/119/151/2011/384 all with 0 failed, corpus 814/6
|
||||
and node 37/0. The 20 loaded macOS runs above were also on this tree.
|
||||
- No guard kill anywhere. The `lucisv-wt/70b/.lane70b/` probe scripts the
|
||||
Linux runs used are deleted from the tree; copies are in the session
|
||||
scratchpad.
|
||||
|
||||
Not done or not verified:
|
||||
- The `qa_m1` product bug: reported, not fixed. Its test still fails about
|
||||
1 run in 10 on Linux when run alone.
|
||||
- The `qa_m3` fix is argued, and the `lsof` evidence shows the mechanism,
|
||||
but the hang has no deterministic reproduction.
|
||||
- The corpus-only budgets never ran on Linux.
|
||||
|
||||
**2026-11-19 (dev, round 2 continued: the stamp fix; scope extended by the
|
||||
lead to `lucisv_mcp/src/project/files.rs`).**
|
||||
|
||||
*How the stamp works.*
|
||||
- `read_source` stats a file, notes the time, reads it and hashes it. That
|
||||
gives the `Stamp`: size, mtime, hash, `read_at` and `identity`.
|
||||
`identity` was the `(ctime, ctime_nsec, ino)` triple on Unix and zeros
|
||||
elsewhere.
|
||||
- `Project::refresh` calls `check` on every file per tool call. `Same`
|
||||
means the file is skipped. `Suspect` means `reread`: read and hash it
|
||||
again, re-index only when the hash moved, and replace the stamp.
|
||||
- So an extra `Suspect` costs one read and one hash. A missed change costs
|
||||
stale answers, and stale *edit plans* in a tool agents use to write
|
||||
files.
|
||||
- The racy rule before: `current mtime + 2 s > read_at`. Nothing for the
|
||||
ctime.
|
||||
|
||||
*What git does.* An index entry whose mtime is not older than the index
|
||||
file itself is "racily clean": stat data cannot prove it unchanged, so it
|
||||
is compared by content. The same idea applies to every timestamp the stat
|
||||
comparison trusts.
|
||||
|
||||
*The fix* (`files.rs`, production lines ~150 → ~240):
|
||||
- **Invariant**, as it is written in `Stamp::racy`: a stamp is trusted on
|
||||
a later match only if every timestamp it trusts (the mtime, and the ctime
|
||||
where there is one) is at least `RACY` older than the moment the stamp
|
||||
was taken. A missing timestamp counts as racy, and so does one later than
|
||||
the read.
|
||||
- The test runs on the stamp's own values. On a match they equal the
|
||||
current ones; on a mismatch the answer is `Suspect` anyway. All the
|
||||
arithmetic is `checked_*`: the old `mtime + RACY` could panic on an
|
||||
absurd mtime.
|
||||
- **`RACY` 2 s → 3 s.** The window has to outlast the coarsest timestamp
|
||||
plus the filesystem clock's lag behind `read_at`'s clock:
|
||||
- Linux ticks (1–4 ms) and 1 s stamps (ext3, many NFS/SMB mounts) fit in
|
||||
2 s.
|
||||
- FAT's 2 s stamps do not. Take a timestamp `T` and a read at `T + 2 s`.
|
||||
A write a tick later, from a coarse clock that lags, can truncate to
|
||||
the same `T`. 3 s leaves a second of margin.
|
||||
- Cost: a just-changed file is re-read on every call for 3 s instead
|
||||
of 2.
|
||||
- Not covered: a file server whose clock is more than ~1 s *behind*
|
||||
ours. Git has the same assumption.
|
||||
- **A wall clock stepped back** (new): after the read, a step back can give
|
||||
a new write the very timestamp the stamp holds.
|
||||
- The stamp now also keeps `read_mono` (an `Instant` taken with
|
||||
`read_at`).
|
||||
- `check` distrusts any stamp whose wall clock is now more than
|
||||
`STEP_BACK` (100 ms) behind where the monotonic clock says it should
|
||||
be. That holds until the file is re-read.
|
||||
- A wall clock that ran *ahead*, as across a suspend the monotonic clock
|
||||
slept through, is not doubted.
|
||||
- A step back smaller than 100 ms stays inside `RACY`'s one-second
|
||||
margin.
|
||||
- **`identity` is `Option<Identity { ctime: Option<SystemTime>, ino }>`.**
|
||||
`None` off Unix; a ctime that does not fit a `SystemTime` is racy.
|
||||
- **The decision is a pure function**, `Stamp::compare(Seen, Clocks)`.
|
||||
`check` is one `stat`, then `compare(Seen::of(meta), Clocks::now())`.
|
||||
That is what lets the unit tests feed values without a file or a clock.
|
||||
- **Off Unix** (no ctime in std on Windows): the racy rule still applies to
|
||||
the mtime. The hole that remains there is old: a same-size rewrite that
|
||||
restores an old mtime *outside* the window is invisible. There is
|
||||
nothing else in the stat to see it with, as the `identity` doc says.
|
||||
- **Test fixtures**: `project/tests.rs` `settle` and the existing
|
||||
`a_stamp_sees_an_edit…` used to age a stamp by moving `read_at` alone.
|
||||
That now looks exactly like a clock stepped back. They use the new
|
||||
`#[cfg(test)] Stamp::taken_later`, which moves both clocks.
|
||||
|
||||
*New unit tests* (`project::files::tests`, deterministic, no file):
|
||||
- `a_match_is_trusted_only_when_every_timestamp_was_settled_at_the_read`:
|
||||
neither racy, mtime, ctime, both, `RACY − 1 ns` (suspect) and exactly
|
||||
`RACY` old (same).
|
||||
- `a_timestamp_later_than_the_read_or_missing_is_racy`: ctime after the
|
||||
read, ctime `None`, mtime `None`, and off-Unix `identity: None` (mtime
|
||||
decides).
|
||||
- `a_wall_clock_stepped_back_since_the_read_distrusts_the_stamp`: stepped
|
||||
back, behind the read, ahead (suspend), jitter under the tolerance, and a
|
||||
stamp aged on both clocks.
|
||||
- `any_moved_field_is_suspect_however_settled`: size, mtime, inode and
|
||||
ctime each moved on a settled stamp.
|
||||
|
||||
*Mutations* (copies restored, `cmp` clean):
|
||||
|
||||
| sabotage | result |
|
||||
|---|---|
|
||||
| ctime dropped from the trusted list (`[Some(self.mtime), None]`) | FAILED: `…every_timestamp_was_settled…` at "ctime racy" (`Same` ≠ `Suspect`), and `…later_than_the_read…` |
|
||||
| `clock_stepped_back` never consulted | FAILED: `a_wall_clock_stepped_back…` |
|
||||
|
||||
*The other caches, audited for the same hole* (none has it, so nothing was
|
||||
stopped on):
|
||||
- **Language server views** (`state/views.rs` `file_view`): no stamp at
|
||||
all. A view is dropped on `set_document`, `close_document`, `update_one`,
|
||||
`rebuild_index_with` and `begin_widen`, that is, on notifications. A disk
|
||||
change no one reports is stale by design, as its doc says, with `hover`'s
|
||||
`spells_exactly` guard. It never trusts a timestamp, so a same-tick
|
||||
rewrite does nothing worse to it than any unreported write.
|
||||
- **Persistent index cache** (`index_cache.rs`, `known_facts` →
|
||||
`facts_now`/`facts_for`): keyed by `content_hash` of the text about to be
|
||||
indexed. The bytes are always read, so there is no timestamp to fool.
|
||||
- **MCP own store** (`lucisv_mcp/src/cache.rs`, `Records::take(path,
|
||||
hash)`): by content hash, after `read_source` read the bytes. Its one
|
||||
`modified()` only ages temporary files for removal. `Project::analysis`
|
||||
reads the file every time and caches by hash.
|
||||
- **CLI format cache** (`lucisv_core/src/cache.rs`): `Entry.content` is the
|
||||
FNV-1a of the bytes, read on every run; no mtime.
|
||||
- No `modified()`/ctime freshness check exists anywhere else outside tests
|
||||
(`rg modified\(\)|mtime` over `lucisv_server`, `vlog_semantic`,
|
||||
`lucisv_core` and `lucisv` sources).
|
||||
|
||||
*Performance* (temporary `eprintln!` of stat checks and suspects per
|
||||
`refresh` in `project/mod.rs`, one binary before and one after, the source
|
||||
restored with `cmp`; driver `drive.py` in the session scratchpad, guarded):
|
||||
|
||||
| session | calls | stat checks | re-reads before | re-reads after |
|
||||
|---|---|---|---|---|
|
||||
| OpenTitan `hw/ip`, 37 read calls (find/outline ×18, hierarchy) | 37 | 78 498 | 0 | 0 |
|
||||
| copy of `hw/ip/uart`, 3 rounds of `format` then 8 reads | 33 | 1 120 | 120 | 120 |
|
||||
| copy of `hw/ip/uart`, `chmod` every file, 8 calls at once, 3.5 s pause, 4 calls | 13 | 420 | 35 | **315** |
|
||||
|
||||
- Ordinary reads never re-read. An edit already makes the mtime fresh, so
|
||||
it costs the same as before.
|
||||
- The extra re-reads come only from a file whose ctime moved while its
|
||||
mtime stayed old (`chmod`, `cp -p`, `touch -r`, rename-over). Each such
|
||||
file is re-read on every call for 3 s, then never again.
|
||||
- A re-read whose hash did not move re-indexes nothing.
|
||||
|
||||
*Checks, final tree.*
|
||||
- macOS:
|
||||
- `cargo fmt --all -- --check` exit 0.
|
||||
- `cargo clippy --all-targets -- -D warnings` clean.
|
||||
- `tools/guard.sh -- cargo test -p lucisv_mcp`: all pass, 388 tests, 4
|
||||
of them new.
|
||||
- `tools/gates.sh` **PASS** (`target/gates/20261119-114518/`): suites
|
||||
521/435/743/376/672/119/151/2011/388, all with 0 failed; corpus 814/6;
|
||||
node 37/0.
|
||||
- Cross-check, the lead's command, for `-p lucisv -p lucisv_mcp`, on both
|
||||
`x86_64-pc-windows-gnu` and `x86_64-unknown-linux-musl`, including
|
||||
`lucisv_mcp`'s unit tests (`--profile test --bin lucisv-mcp`): clean, no
|
||||
warning.
|
||||
- `-p lucisv_server` fails on Windows at `state/incremental.rs:161`
|
||||
(E0507, `dir_id` moved in a closure). That is the bug 0.65.7 fixed on
|
||||
master, in a file this lane does not touch.
|
||||
- `--all-targets` on Windows also fails in `tests/qa_m3.rs`, which uses
|
||||
`std::os::unix` without a cfg. That predates this lane, and gates'
|
||||
`cross` step does not build tests.
|
||||
- Linux:
|
||||
- the qa_m1 test alone: **0/300 failed as root and 0/300 as `--user`**
|
||||
(before the fix: 39/300 and 12/150 as root).
|
||||
- root: clippy exit 0; whole suite green **10 consecutive runs of 10**,
|
||||
each 97 result lines, 5411 passed, 0 failed, 64 ignored. That is 5407
|
||||
plus the 4 new unit tests.
|
||||
- `--user`: clippy exit 0; green **10 of 10**, the same totals.
|
||||
- The probe scripts are deleted from the tree again; copies are in the
|
||||
session scratchpad.
|
||||
|
||||
*Changelog paragraph (for the lead):*
|
||||
|
||||
> **lucisv-mcp no longer serves stale contents after a same-size rewrite
|
||||
> that restores an old mtime.** On Linux, ctime moves in 1 ms ticks. A
|
||||
> file whose ctime had just moved (a rename-over, say), read by the server
|
||||
> and then rewritten at the same size with its old mtime put back (`cp -p`,
|
||||
> `rsync -t`, `touch -r`) inside the same tick, matched its stamp in every
|
||||
> field. The server then answered from the old text until the file changed
|
||||
> again. The "racy" rule now covers every timestamp the stamp trusts,
|
||||
> ctime as well as mtime. Its window is 3 s (it was 2 s, too close to FAT's
|
||||
> 2-second timestamps). A wall clock stepped back since a read now
|
||||
> distrusts the stamp. Re-reads rise only for files whose metadata changed
|
||||
> in the last 3 s. **Tests:** the suite is now stable on Linux.
|
||||
> - Two stdin helpers tolerate a child that exits before reading.
|
||||
> - The didOpen latency test measures its budget against a parse of the
|
||||
> same buffer instead of a fixed 200 ms.
|
||||
> - A macOS-only hang in an MCP concurrency test (a pipe inherited across
|
||||
> threads) is fixed.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-11-19 (QA, macOS arm64, 18 CPUs; tree = 948f8a0 + this lane).**
|
||||
@@ -422,6 +815,200 @@ Nothing here has run on Linux since the 0.65.2/0.65.3 fast-forwards.
|
||||
*Fixed by QA:* finding 1 only. *Unverified:* everything on Linux, as
|
||||
above.
|
||||
|
||||
### Round 2 QA
|
||||
|
||||
**2026-11-19 (QA, round 2; tree = 934d472 + f910554 in `lucisv-wt/70b`;
|
||||
macOS arm64 18 CPUs, Linux = `tools/linux_check.sh` on luhpe).**
|
||||
Verdict: **PASS WITH FINDINGS.** No stale read that the invariant claims to
|
||||
prevent, no panic, no test that passes without testing, no Linux failure.
|
||||
|
||||
*Baseline (macOS).* `cargo fmt --all -- --check` exit 0. Guarded
|
||||
`cargo test -p lucisv_mcp -p lucisv -p lucisv_server`: 24 result lines,
|
||||
2569 passed, 0 failed, 53 ignored. Full `tools/gates.sh` **PASS** (fmt,
|
||||
clippy, build, suites 521/435/743/376/672/119/151/2030/388, docs, corpus
|
||||
814/6, node 37/0, cross). (`lucisv_server` is 2030 here, not the dev's 2011:
|
||||
the dev measured on 0.65.6; 934d472 adds 19.) `#[test]` counts vs 934d472:
|
||||
`cli.rs` 113→113, `e2e.rs` 109→109, `qa_m3.rs` 31→31, `qa_m8.rs` 6→6,
|
||||
`project/tests.rs` 3→3, `files.rs` 3→7. The only removed assertion is
|
||||
e2e's `best <= 200 ms`, replaced by the ratio. Cross, `--all-targets`, for
|
||||
`lucisv_mcp`: linux-musl clean. Windows fails only in `tests/qa_m3.rs`
|
||||
(12 errors, `std::os::unix` and `PermissionsExt` with no cfg). That is
|
||||
pre-existing: the same 8 `std::os::unix` uses are at 934d472. Every other
|
||||
target builds for Windows (`--bins --profile test` plus every `--test`
|
||||
except `qa_m3`), including `files.rs`'s unit tests.
|
||||
|
||||
*PART 2: the stamp.*
|
||||
- **Real files, the real binary.** A driver (`stale.py`, kept in the
|
||||
session scratchpad) speaks MCP stdio to `lucisv-mcp` and asks `find` for
|
||||
the new module name and then the old one. It covers 11 operations: in-place
|
||||
same-size rewrite plus `utime(old)`; the same with `touch -r`;
|
||||
rename-over of a same-size, old-mtime file; hard-link swap; `cp -p`-style
|
||||
`O_TRUNC` rewrite plus `utime` plus `chmod`; truncate-and-rewrite plus
|
||||
`utime`; mmap write plus msync, unmap and `utime`; vim-style
|
||||
write-beside, rename and `utime`; replacing the file with a symlink to a
|
||||
same-size file; `chmod` alone (expect the old content); and a directory
|
||||
rename that brings in another same-size, old-mtime `c.sv`. It runs each at
|
||||
delays of 0, 1 ms, 10 ms, 1 s, 2.9 s, 3.1 s and 10 s after the server's
|
||||
read, with two preparations: stamp settled (ctime > 4 s old) and the
|
||||
original hole (ctime made fresh by `utime(old)` just before the read).
|
||||
That is 154 cases per run.
|
||||
|
||||
| platform / fs | cases | stale |
|
||||
|---|---|---|
|
||||
| macOS APFS | 154 | 0 |
|
||||
| Linux root, overlayfs (`/w`) | 154 | 0 |
|
||||
| Linux root, overlayfs `/tmp` | 154 | 0 |
|
||||
| Linux root, tmpfs `/dev/shm` | 154 | 0 |
|
||||
| Linux `--user`, the same three | 3 × 154 | 0 |
|
||||
|
||||
- **The exact hole, hit on purpose.** A sequential loop does
|
||||
`utime(old)`, then `find` (the read), then a same-size rewrite plus
|
||||
`utime(old)` immediately. It counts the runs whose stat after the write
|
||||
equals the stat at the read: size, mtime, ctime and ino all identical.
|
||||
|
||||
| binary | fs | runs | stat-identical | stale |
|
||||
|---|---|---|---|---|
|
||||
| **934d472 (before)** | overlayfs | 300 | 65 | **65** |
|
||||
| **934d472 (before)** | tmpfs | 300 | 87 | **87** |
|
||||
| this lane, root | overlayfs | 300 | 65 | 0 |
|
||||
| this lane, root | tmpfs | 300 | 125 | 0 |
|
||||
| this lane, `--user` | overlayfs | 300 | 52 | 0 |
|
||||
| this lane, `--user` | tmpfs | 300 | 106 | 0 |
|
||||
| this lane, macOS | APFS | 100 | 0 | 0 |
|
||||
|
||||
So the driver does detect the bug. The old code is stale exactly when the
|
||||
stat is identical, and the fix is fresh in every one of those runs.
|
||||
- **Property test of `compare`.** I wrote my own xorshift generator and
|
||||
included it temporarily in `files.rs` by `#[path]` from the scratchpad.
|
||||
`files.rs` was restored from a copy and `cmp`-checked; `git status` is
|
||||
clean. It ran **3 000 000 cases**: moved 970 519, racy 2 449 889, clock
|
||||
step 677 250, and **232 760 cases where nothing doubted → all `Same`**
|
||||
(no needless re-read). No `Same` was returned for any moved, racy or
|
||||
stepped case. There was no panic, including at u64/i64 extremes, the
|
||||
epoch, times before 1970, `RACY ± 1 ns`, `STEP_BACK ± 1 ns` and an
|
||||
`Instant` behind the read. (Raw nsec ≥ 1e9 cannot be built as a
|
||||
`SystemTime`. By reading `identity()`: `i64::MAX` s plus `i64::MAX` ns
|
||||
fits a `Duration`, so the sum does not panic, and an out-of-range result
|
||||
becomes `None`, which counts as racy.) Each of these mutations fails it:
|
||||
ctime dropped, step check dropped, `>` → `>=`, identity ignored.
|
||||
- **Clocks.** From the std 1.100 docs: `Instant` is `CLOCK_UPTIME_RAW` on
|
||||
Darwin and `CLOCK_MONOTONIC` on Linux, both stopped in suspend; Windows
|
||||
uses QPC. Through `compare` with injected clocks:
|
||||
- 1 h suspend: `Same`, and also `Same` if `Instant` counts the suspend.
|
||||
- 5 s backwards step: `Suspect`. After that one re-read: `Same`. A file
|
||||
written 2 s before the step and read after it: `Suspect`.
|
||||
- 5 s forwards step: `Same`, which is safe locally because the next
|
||||
write is stamped after the step.
|
||||
- Drift: 99 ms → `Same`, 115 ms → `Suspect`.
|
||||
- On Linux NTP slews `CLOCK_MONOTONIC` along with the wall clock, so only
|
||||
steps diverge. On macOS `UPTIME_RAW` is not slewed. Measured here, the
|
||||
wall clock runs **ahead** of it by +6.37 ppm (stable over 300 s), so
|
||||
the step rule never fires. A Mac drifting the other way at that rate
|
||||
would distrust stamps older than ~4.4 h once: one re-read of each, with
|
||||
no re-index. Benign.
|
||||
- **TOCTOU.** The stat comes before `Clocks::now()`, which comes before the
|
||||
read. A write between the stat and the read leaves an old stat with new
|
||||
bytes, and the next stat differs, so this is safe. A write after the read
|
||||
in the same tick is covered by the racy rule. `read_at` is earlier than
|
||||
the read itself, which errs toward racy.
|
||||
- **Skew tolerance** (by arithmetic). A later write can only carry the
|
||||
stamp's timestamp if `RACY ≥ granularity + (local clock − file server
|
||||
clock)`. That gives FAT (2 s) 1 s, 1 s filesystems (HFS+, ext3,
|
||||
NFSv2/SMB1) 2 s, and ns filesystems ~3 s. Past that skew, an *ordinary*
|
||||
same-size edit inside one server tick is invisible, not only an
|
||||
mtime-restoring one. Not testable here (no FAT/NFS).
|
||||
- **Audit of the other caches: confirmed.** The server's `file_view`
|
||||
(`state/views.rs:74`) has no stamp. `index_cache.rs:226/298` is keyed by
|
||||
`content_hash`. MCP `Records::take(path, hash)` (`cache.rs:110`) is too.
|
||||
`Project::analysis` re-reads every call (`mod.rs:301`), so `read` and
|
||||
`outline` were never exposed; only index answers (`find`, hierarchy,
|
||||
names) were. The only other `metadata` uses outside tests are
|
||||
`walk.rs:194` `(dev, ino)` for cycles and MCP temp-file aging.
|
||||
Experiment: the CLI format cache with a formatted file, `--check` (from
|
||||
cache), then a same-size unformatted rewrite with the mtime restored, then
|
||||
`--check`. Result: "would reformat", exit 1. Correct.
|
||||
|
||||
*PART 1.*
|
||||
- None of the four tests skips on macOS (`--nocapture`). My own mutations
|
||||
(copies restored, `git status` clean):
|
||||
|
||||
| test | mutation | result |
|
||||
|---|---|---|
|
||||
| cli `stdin_and_lines…` | `args.rs:487` message reworded | FAILED cli.rs:1943 |
|
||||
| qa_m8 `qa_argument_order…` | `main.rs:94` "unknown flag" | FAILED qa_m8.rs:345 |
|
||||
| e2e didOpen | 100 ms sleep in the didOpen arm | FAILED 10.63x (142 ms; old 200 ms would pass) |
|
||||
| qa_m3 CLI-while-formatting | CLI `--check` exits 3 instead of 1 | FAILED qa_m3.rs:743 |
|
||||
|
||||
- **BrokenPipe callers.** There are 22 `run_with_stdin(_raw)` callers. Each
|
||||
asserts the exit code and/or output, except `cli.rs:2149-2150`, which
|
||||
asserts only `stdout == ""` (finding 4). `qa_m8` `run` has 5 callers.
|
||||
Each asserts the status or reads answers by id, so a server that died
|
||||
leaves a missing answer and the test fails.
|
||||
- **Ratio, 50× under load each.** macOS (36 busy loops): 0/50 failed,
|
||||
2.40–3.09x. Linux root (8 busy loops, opens ~1 s): 0/50 failed,
|
||||
**2.25–4.09x**. The worst is above the dev's 3.55; headroom to 6 is
|
||||
1.47x. The blind spot of three extra parses is acceptable for a test named
|
||||
for unbounded delay (see finding 5 for the machine dependence).
|
||||
- **qa_m3.** The `lsof`/`sample` evidence fits the mechanism. On macOS std
|
||||
creates pipes with `pipe()` and then sets `FD_CLOEXEC`. The fix removes
|
||||
the only intra-test overlap: the main thread spawns nothing while the
|
||||
checker runs. **100/100 green on macOS under 36 busy loops**, no hang.
|
||||
Grep: `qa_m3.rs:721` is the only test thread that spawns children in a
|
||||
loop; every other `thread::spawn` near a `Command` is a stdout pump.
|
||||
Parallel *tests* in one binary can still inherit each other's pipes on
|
||||
macOS, but the wait is bounded by the other test's lifetime, not a
|
||||
deadlock.
|
||||
|
||||
*Linux, independently.*
|
||||
- Root: clippy `--all-targets -D warnings` exit 0. Whole suite
|
||||
`--no-fail-fast` **6/6 green**, each 97 result lines, 5430 passed,
|
||||
0 failed, 65 ignored.
|
||||
- `--user`: clippy exit 0. **6/6 green**, the same totals.
|
||||
- `qa_m1` `qa_rework_a_rename_over…` alone, root: **0/300 failed**.
|
||||
- No guard kill anywhere on macOS.
|
||||
|
||||
*Findings* (none is a FAIL):
|
||||
1. (medium, documented-limit class) **A writable mmap kept open serves
|
||||
stale contents indefinitely on Linux.** Map the file, store into it
|
||||
(this sets mtime and ctime), wait 4 s, let the server read, then store
|
||||
into the same already-dirty page. The stat is unchanged after the
|
||||
store, after `msync` and after `munmap` (overlayfs and tmpfs, root and
|
||||
`--user`), and `find` stays stale. On macOS it is stale until `msync`.
|
||||
The kernel exposes nothing, so no stamp can see it (git has the same
|
||||
limit). Repro: `stale.py BIN DIR mmap`. Suggest stating it in
|
||||
Assumptions. Editors do not write through mmap.
|
||||
2. (low, perf) **A future mtime makes a file racy forever**, so it is
|
||||
re-read and re-hashed on every call (no re-index). Release binary,
|
||||
macOS:
|
||||
- 4 000 small files: 6.8 → **67.5 ms** median per `find`.
|
||||
- A copy of OpenTitan `hw/`: 21 → **126 ms**.
|
||||
- Fresh copy of `hw/` (every ctime new): burst median 58 ms against
|
||||
33 ms settled, for ~3 s only.
|
||||
|
||||
Usable, but the cost lasts for as long as the clock stays behind. The
|
||||
lead should decide whether a timestamp far in the future (> 1 day, say)
|
||||
should stop counting as racy.
|
||||
3. (low, docs) `docs/features/mcp-transport/README.md:53-58` still says
|
||||
the 2 s window and mtime-only racy, and that identity is "0" elsewhere.
|
||||
It is outside this lane's files: a Handshake request. The non-unix hole
|
||||
is real: a same-size rewrite that restores the mtime ≥ 3 s after the
|
||||
read is invisible, since std has no ctime and no stable `file_index`.
|
||||
It is stated only in `files.rs` and this README, not where a Windows
|
||||
user would see it (`docs/site/src/content/docs/guides/agents.md`).
|
||||
macOS `setattrlist(ATTR_CMN_CHGTIME)` returns 0 but leaves ctime
|
||||
unchanged, so an unprivileged ctime restore is not possible there.
|
||||
4. (low, pre-existing) `crates/lucisv/tests/cli.rs:2149-2150` asserts only
|
||||
that stdout is empty, so a child that crashes (before or after reading)
|
||||
passes. The BrokenPipe tolerance does not materially widen this: the
|
||||
inputs fit in the pipe buffer.
|
||||
5. (info) The ratio test's sensitivity depends on the machine. A 100 ms
|
||||
didOpen stall is 10.6x on this Mac but would be ~3–4x on the Linux
|
||||
runner (parse 50–70 ms), which passes.
|
||||
|
||||
*Fixed by QA:* nothing. *Unverified:* FAT, NFS and SMB (skew arithmetic
|
||||
only); Windows at run time (compile only); a real suspend or NTP step
|
||||
(injected clocks only).
|
||||
|
||||
## Review
|
||||
|
||||
**Lead, 2026-11-19.** Accepted on macOS evidence; Linux line left open.
|
||||
@@ -447,3 +1034,25 @@ above.
|
||||
unticked until that run happens; the Linux job is not added blind.
|
||||
- Open follow-up, recorded under Status: the references linear-time test
|
||||
times a copy of `Server::large_scan`'s loop, not the production code.
|
||||
|
||||
**Lead, 2026-11-19 — Round 2.** Accepted for 0.65.9; §70 closed.
|
||||
|
||||
- Round 1 was accepted on macOS evidence with the Linux line open, and the
|
||||
first Linux runs after ssh came back showed why that line mattered: clean
|
||||
once, then 3 failing runs in 9. The dev's census (57 whole-suite runs,
|
||||
2 090 loop iterations) is the right way to chase flakes — a ~10% flake does
|
||||
not show in three runs.
|
||||
- The dev stopped on the mtime test instead of loosening it, and it was a
|
||||
real bug: `lucisv-mcp` could serve stale contents indefinitely. I extended
|
||||
scope to fix it. QA reproduced the hole on purpose on the old binary
|
||||
(65/65 and 87/87 stale when the stat was identical) and got 0 on the new
|
||||
one across overlayfs, tmpfs and APFS, then property-tested `compare` with
|
||||
three million cases under four mutations. That is the evidence.
|
||||
- The `qa_m3` hang is the same test the guard killed in the 0.65.5 release
|
||||
gates and in 71.7's QA; it now has a cause (a pipe inherited across
|
||||
threads on macOS) and a fix, though no deterministic reproduction.
|
||||
- `ci.yml` gains the `linux` job in this change, as §70 planned. It installs
|
||||
Rust per job and builds cold — a few minutes; acceptable for now.
|
||||
- Open, filed in TODO: future-mtime trees re-read on every call; the mmap
|
||||
limit and the Windows gap are now written in `docs/features/mcp-transport`;
|
||||
a weak assertion in `cli.rs`; `qa_m3.rs` does not compile for Windows.
|
||||
@@ -223,10 +223,12 @@ from-scratch build.
|
||||
filelist is among them). `watch.rs` was touched for this only.
|
||||
- **Changed:** `IncludeGraph::update_file` removed; `update_held(path, text)`
|
||||
(this file's edges, nothing relearned), `add_known(path)` and
|
||||
`refresh_naming(path)` added (`includers_of`, added in the first cut, is
|
||||
`refresh_naming(path)` added, and `refresh_naming_all(&[PathBuf])` (round
|
||||
3: one walk for a batch of paths) (`includers_of`, added in the first cut, is
|
||||
gone). The graph holds every file's include lines; its test fingerprint
|
||||
renders them.
|
||||
- **New:** `Workspace::refresh_includes_naming(path)`; `watch::names_a_config`.
|
||||
- **New:** `Workspace::refresh_includes_naming(&[PathBuf])` (round 3 batched
|
||||
it; it was `(path)` before); `watch::names_a_config`.
|
||||
- **Changed:** `WorkspaceIndex::fingerprint` renders each ambiguity's count.
|
||||
- **Changed:** `Candidates::update_file`/`update_words` are `#[cfg(test)]`;
|
||||
`set_file_words` and `refresh_names` are the production halves.
|
||||
|
||||
@@ -50,13 +50,20 @@ arrived.
|
||||
a changed hash re-indexes it; a missing file is removed and triggers a
|
||||
re-walk; the roots are re-walked when the last walk is older than 5 s and
|
||||
on every `project_overview`, so new files appear. All changes go into the
|
||||
index with one `absorb` (one merge). A file modified within 2 s of being
|
||||
read is re-read on every sweep until it settles — git's "racy clean" rule —
|
||||
so an edit that keeps a file's size inside one mtime tick is still seen.
|
||||
On Unix the stamp also holds the file's ctime and inode (the same
|
||||
index with one `absorb` (one merge). A file any of whose trusted timestamps
|
||||
— its mtime, and on Unix its ctime — is within 3 s of the moment it was
|
||||
read is re-read on every sweep until it settles — git's "racy clean" rule,
|
||||
applied to every timestamp the stamp trusts since 0.65.9 (it covered the
|
||||
mtime alone before, and a same-tick rewrite on Linux was served stale) —
|
||||
so an edit that keeps a file's size inside one timestamp tick is still
|
||||
seen. On Unix the stamp also holds the file's ctime and inode (the same
|
||||
`stat`), so a same-size rewrite that puts the old mtime back (`cp -p`,
|
||||
`rsync -t`, `touch -r`) is seen too; elsewhere they are 0 and size, mtime
|
||||
and the racy rule are all there is. A by-name lookup that finds nothing
|
||||
`rsync -t`, `touch -r`) is seen too. Elsewhere (Windows) there is no ctime
|
||||
or inode: size, mtime and the racy rule are all there is, so a same-size
|
||||
rewrite that restores the old mtime more than 3 s after a read is NOT
|
||||
seen. Not seen anywhere: a store through a writable mmap that the kernel
|
||||
has not yet reflected in the file's timestamps
|
||||
(`docs/features/linux-test-portability`, Round 2). A by-name lookup that finds nothing
|
||||
(`unit_interface`, `list_units` with a `glob`, `search_symbols`) walks
|
||||
once more before it answers, unless this call already walked
|
||||
(`Project::ensure_walked_for_miss`) — so a file the agent wrote a moment
|
||||
|
||||
@@ -0,0 +1,894 @@
|
||||
# scan-ordering
|
||||
|
||||
## Goal
|
||||
|
||||
The owner's report: *"Sometimes when I find references on a port/signal, it
|
||||
shows not found. But if I click somewhere else and then click back to the same
|
||||
word, the find reference suddenly works again."* The investigation (TODO §71.7)
|
||||
found the cause and two worse bugs beside it. **A1:** a caret just past a
|
||||
name's last letter — where a double-click, a click on the right half of the
|
||||
last letter, or a row of lucisv's own References view leaves it — asked the
|
||||
server about the *next* character, and every "symbol under the cursor" request
|
||||
answered nothing there. **B:** while a whole rescan answered messages, a
|
||||
`didChange` drained mid-scan was applied ahead of an older `didChange` still
|
||||
waiting, so under incremental sync the server's copy of a buffer silently
|
||||
diverged from the editor's until the file was reopened. **C:** a burst
|
||||
`[request, didOpen]` during the startup scan re-held the request at every
|
||||
file, and the scan took ~300 s instead of ~1.7 s on OpenTitan. This round makes
|
||||
a caret touching a name's right edge mean that name, establishes "no
|
||||
notification overtakes an older notification" as the loop's rule, and makes
|
||||
"only applied messages change a scan's state" true. P1, P2 and P3 are
|
||||
documented, not changed (P2 was fixed in the first round and reverted in the
|
||||
fix round for its cost, QA-1).
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **VS Code's word rule is the one to match.** `getWordAtText`
|
||||
(`src/vs/editor/common/core/wordHelper.ts`) accepts a word whose end equals
|
||||
the caret, so VS Code titles a references search, highlights the word and
|
||||
shows "No references found" for the name *before* a caret that touches it
|
||||
on the right. Its default word pattern splits on `.`, `(`, `[`, `` ` `` and
|
||||
`$`, so in `u_a|.sig` the word is `u_a` and in `u_a.|sig` it is `sig`; the
|
||||
rule here agrees ([`caret::symbol_offset`]).
|
||||
- **A name byte** is ASCII alphanumeric, `_` or `$` (IEEE 1800-2017 §5.6). A
|
||||
macro after its backtick and a system task are covered by the same set; an
|
||||
escaped identifier (`\a+b `) is handled by its terminating whitespace. A
|
||||
number or keyword just before the caret is a "name" too: harmless for the
|
||||
requests that resolve nothing there, and right for `documentHighlight`'s
|
||||
keyword pairs (`begin|` now highlights its `end`, as VS Code's own word
|
||||
highlight already did).
|
||||
- **`vscode.open` puts the caret at a range's end.** Verified in VS Code's
|
||||
source (`extHostTypeConverters.ts` converts `selection` with `Range.from`,
|
||||
losing a `Selection`'s direction; `codeEditorWidget.ts`'s `setSelection(IRange)`
|
||||
makes the range's end the position). VS Code's own references view passes
|
||||
`range.with({ end: range.start })` and go to definition
|
||||
`Range.collapseToStart(range)`; lucisv's view now does the same.
|
||||
- **What is ordered (fix round, narrowed from "every client message"):**
|
||||
every notification other than `$/cancelRequest` — the only messages that
|
||||
change what the server holds — is applied in the order sent, across
|
||||
documents (a `didClose` of one file and a `didOpen` of another stay in
|
||||
order). A request is answered after every notification sent before it
|
||||
(`must_wait`, unchanged), but **may** be answered after a newer
|
||||
notification has been applied, when it was held and nothing older than
|
||||
that notification was: it is then answered against newer state, exactly as
|
||||
every request answered late on base was. Exempt altogether: **responses**
|
||||
(they answer a request the server made; `take_the_answer_out_of_held`
|
||||
relies on that) — **amended 2026-11-19 by fast-actions (0.65.11):** the
|
||||
client's answer to a settings pull is applied as a settings push is, so
|
||||
outside the startup wait it is ordered like a notification (`must_hold`,
|
||||
`behind`); every other response stays exempt — and the navigation requests the empty-answer rule set aside
|
||||
(`deferred`, re-asked at a later publish). A **cancel** waits whenever
|
||||
anything is held, so one naming a held request is honoured at replay; one
|
||||
naming a request in the unapplied tail of the burst a scan is nested in is
|
||||
dropped and the request computed, as on base.
|
||||
- **Why narrowing is sound.** Buffer text, open/closed state, settings,
|
||||
folders and watcher effects are changed only by non-cancel notifications.
|
||||
Such a notification is applied only when no older one is unapplied in
|
||||
`held` or in an enclosing burst's tail ([`Server::behind`]), `held` is
|
||||
replayed in order, and nothing else defers a notification — so the
|
||||
sequence of state changes is the client's. The broad rule's only extra
|
||||
effect was to keep a notification from overtaking a held *request*, which
|
||||
changes no state and cost the startup its first `didOpen` (QA-3). Checked
|
||||
by the randomized test, f6.py, QA's seeds and hand scenarios (Work log).
|
||||
- **Memory while holding is bounded by the scan's length times the client's
|
||||
rate.** Requests were already held this way; a `didChange` under incremental
|
||||
sync (what lucisv advertises) is a few hundred bytes. A full-sync client
|
||||
flooding whole-buffer changes during a long rescan holds one copy per change
|
||||
until the scan ends — the same order as the `dirty` text it would otherwise
|
||||
have kept, times the number of changes. Not coalesced: coalescing two held
|
||||
changes is only sound when nothing between them reads the buffer, which is
|
||||
the analysis this round avoids.
|
||||
- **P1 (directory-only watcher events) is a registration question, not a
|
||||
handler one** — see Handshakes; nothing arrives today for the case that
|
||||
matters.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed:** `Scan::neighbourhood_indexed` and `open_next` (unchanged),
|
||||
`sync::apply_changes_at` (unchanged). No `state/` file is touched after the
|
||||
fix round (in particular not `incremental.rs`'s `holds_another_spelling_of`).
|
||||
|
||||
**Promised to the rest of the server (changed, read this):**
|
||||
|
||||
1. **`process_batch` holds notifications too** (`Server::must_hold`, mod.rs).
|
||||
A non-cancel notification is held when an older one is still unapplied:
|
||||
in `held`, or in the tail of a burst whose message started the scan now
|
||||
draining (`Server::behind`, a count of those tails' non-cancel
|
||||
notifications, kept by `process_batch`). A cancel is held when anything
|
||||
is held. A request's rule is `must_wait`, unchanged. A response is never
|
||||
held, except the answer to a settings pull (fast-actions, 0.65.11), which
|
||||
is ordered like a notification. `batch::changes_state` names the messages that are ordered.
|
||||
Anything that adds a new caller of `process_batch` inherits the rule for
|
||||
free; anything that applies a client message *without* going through
|
||||
`process_batch` breaks it. **For lane 71.3 (viewport highlighting),
|
||||
rebasing onto this:** the `process_batch` diff is the `behind`
|
||||
bookkeeping (an `unapplied` counter), the `must_hold` call in place of
|
||||
`must_wait() && Request`, a `cancel_deferred` before holding, and the
|
||||
splice moved into `Server::hold` (which keeps `process_batch` under 80
|
||||
lines). Nothing else in the loop moved.
|
||||
2. **A `didOpen` changes a scan's order where it is applied.** The `didOpen`
|
||||
arm sets `head_owed` and `opened_mid_scan` when `scanning`;
|
||||
`answer_what_is_waiting` reads `opened_mid_scan` after the batch. `batch.rs`'s
|
||||
`opened_in` is gone — nothing may read a batch's `didOpen`s again.
|
||||
3. **Position → symbol requests resolve through `Server::symbol_offset`**
|
||||
(dispatch.rs), which is `Server::offset` plus [`caret::symbol_offset`]. A
|
||||
new request about the name under the cursor should use it; one with a
|
||||
boundary rule of its own keeps `offset`. The table is below.
|
||||
4. **Test-only:** `server/probe.rs` scripts bursts into a scan's interleave
|
||||
points and counts hand-backs; it is `#[cfg(test)]` and thread-local, and
|
||||
the one production line is `#[cfg(test)]` too.
|
||||
|
||||
**Requests to other modules / the lead (not done here):**
|
||||
|
||||
- **P1 needs a second watcher registration.** VS Code coalesces the deletes
|
||||
under a deleted folder into one event for the folder
|
||||
(`src/vs/platform/files/common/watcher.ts`, `EventCoalescer`: "remove all
|
||||
DELETE events up to the root folder that got deleted"; `vscode.d.ts`: "file
|
||||
events from deleting a folder may not include events for the contained
|
||||
files"), and `extHostFileSystemEventService.ts` then drops the folder event
|
||||
because its path does not match `**/*.{v,vh,sv,svh}`. So after `rm -rf dir`
|
||||
or a `git checkout` that removes a directory, **the server receives
|
||||
nothing** — no handler change can fix it. Created files are not coalesced:
|
||||
`mkdir d && cp x.svh d/` or a checkout that adds a directory arrives as
|
||||
per-file creates, which the server already handles; a directory *moved in*
|
||||
arrives as one folder event, dropped the same way. The fix is a second
|
||||
watcher, `**/*` with `kind: Create | Delete`, plus a handler that expands a
|
||||
folder path to the held files under it (delete) or a rescan (create). That
|
||||
changes the registration every client receives and the traffic it sends
|
||||
(every create/delete outside `files.watcherExclude`), which is a decision
|
||||
for the lead, so it is filed rather than done. QA's synthetic
|
||||
`r2attack.py dir-create` / `held-dir-delete` still diverge (unchanged).
|
||||
- **P3 (symlinked files held under one spelling or both)** is unchanged: the
|
||||
rule "one file, one spelling, whatever is open" needs the walk
|
||||
(`discover.rs`'s `Aliased`), the overlay and the one-file path changed
|
||||
together. Not small; filed.
|
||||
- **P2 (reverted, known, pre-existing — 0.65.6 behaviour).** An excluded or
|
||||
unlisted buffer the index took in (a whole scan takes every open buffer;
|
||||
the one-file path of a save or watcher event takes it too, QA F4 of
|
||||
`localized-reindex`) **stays in the index after `didClose`**, where a fresh
|
||||
server would not hold it: `oracle/r2attack.py excluded-close`, "closed" and
|
||||
"saved then closed", 20 answers differ. The first round fixed it by taking
|
||||
an unheld buffer in on `didOpen` and forgetting it on `didClose`; each is a
|
||||
one-file add/remove, which shifts file ids and rebuilds the completion
|
||||
tables and include naming — ~190 ms per open and ~225 ms per close on full
|
||||
OpenTitan, 2 000 outside files opened and closed 806 s vs 0.7 s
|
||||
(`qa717/drv/lat717.py`, `p2perf.py`, QA-1). Reverted. A fix must make the
|
||||
removal cheap (a tombstone the next scan or publish folds in, say) — it is
|
||||
an index-layer change, filed.
|
||||
- **QA-2 (known, pre-existing): an unheld buffer opened while a scan runs is
|
||||
not taken in by that scan**, and nothing takes it in when the scan ends;
|
||||
opened before the scan it is held. `qa717/drv/race717.py BIN <OpenTitan
|
||||
copy> 0.5`: an excluded file opened 0.5 s into the startup scan is still
|
||||
unheld after settle, base and new alike. The same final state answers
|
||||
differently depending on when the buffer was opened; QA's `QA_FRESH_SAVE`
|
||||
exists to hide exactly this on the fresh side.
|
||||
- **QA-7a (known, pre-existing): closing an unsaved in-scope buffer whose
|
||||
text a rescan took into the index leaves that text in the index** after
|
||||
the close; a fresh server holds the disk text. `qa717/drv/closeidx.py BIN
|
||||
rescan`: `qd_buf` survives the close, the fresh server holds `qd_disk`.
|
||||
Identical on base. Same root as P2: a close does not touch the index.
|
||||
- **Notes for the lead's backlog (QA, not this lane):** QA-6 — the
|
||||
`lucisv_mcp` test `qa_m3::qa_lucisv_check_over_the_same_tree_while_the_server_formats`
|
||||
(`crates/lucisv_mcp/tests/qa_m3.rs:687`) hung to the guard's 600 s limit
|
||||
once in QA's gate run (passed on the retry), also seen in the 0.65.5
|
||||
release gate log. QA-7b — `rand_run.py` full OpenTitan seed 301 ×100
|
||||
diverges at step 100 (13 answers, `top_earlgrey/ip/ast/rtl/usb_osc.sv`)
|
||||
identically on base. QA-7c — renaming a port of a module defined twice
|
||||
(`top_englishbreakfast/ip/ast/rtl/adc.sv:81` `rst_adc_ni`) gives an edit
|
||||
or a refusal at random across fresh servers, base too (`qa717/drv/dup.py`).
|
||||
- **lucisv_mcp** answers by name, not by caret position, so A1 does not
|
||||
apply to it.
|
||||
|
||||
### Every position-taking request and its boundary rule (A1)
|
||||
|
||||
| request | what the position names | rule now |
|
||||
|---|---|---|
|
||||
| `textDocument/hover` | the name under the cursor | **shifted** (`symbol_offset`) |
|
||||
| `textDocument/definition` | the name | **shifted** |
|
||||
| `textDocument/typeDefinition` | the name whose type is wanted | **shifted** |
|
||||
| `textDocument/references` | the name | **shifted** — the owner's bug |
|
||||
| `textDocument/documentHighlight` | the name, or a scope keyword of a pair | **shifted** |
|
||||
| `textDocument/prepareRename`, `textDocument/rename` | the name | **shifted** |
|
||||
| `textDocument/prepareCallHierarchy` | the module under the cursor | **shifted** (already answered for the whole instantiation, so it changes nothing there) |
|
||||
| `textDocument/prepareTypeHierarchy` | the class | **shifted** (already answered for the whole declaration) |
|
||||
| `textDocument/linkedEditingRange` | a closing label being typed | as sent — `linked.rs`'s `covers` is already end-inclusive (`offset <= span.end`), which typing at a label's end needs |
|
||||
| `textDocument/signatureHelp` | the call the caret is *in* | as sent — before `(` and after it are different answers on purpose |
|
||||
| `textDocument/completion`, `textDocument/inlineCompletion` | the insertion point | as sent — "just past a name" is where the text goes |
|
||||
| `textDocument/onTypeFormatting` | the character just typed | as sent |
|
||||
| `textDocument/selectionRange` | where expansion starts | as sent — VS Code merges its own word ranges in |
|
||||
| `textDocument/codeAction` (port refactorings, organize imports) | `range.start` as the cursor, resolved to the *instantiation* or *import* around it | as sent — the item's span contains a name's end |
|
||||
| `textDocument/codeAction` (extract, inline module) | a range | as sent |
|
||||
| `workspace/executeCommand` (port commands, lens) | positions the server itself issued | as sent |
|
||||
| `inlayHint`, `semanticTokens/range`, `foldingRange`, `documentLink`, `documentSymbol`, `lucisv/scopePairs`, the hierarchy snapshot | a range or the whole document | no caret |
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Reproduce A1, B, C on 58d3db3 with the investigation's drivers; record
|
||||
- [x] A1: `caret::symbol_offset`, `Server::symbol_offset`, nine requests
|
||||
- [x] A1: the References view puts the caret at the identifier's start
|
||||
- [x] B: `Server::must_hold` + `Server::behind`
|
||||
- [x] C: `opened_mid_scan`, set where a `didOpen` is applied; `opened_in` gone
|
||||
- [x] P2: fixed in round 1, **reverted** in the fix round (QA-1); documented
|
||||
- [x] Fix round: rule narrowed to notification-over-notification (QA-3);
|
||||
`process_batch` split (`Server::hold`); QA-4 measured; QA-5 wording
|
||||
- [ ] P1: filed (Handshakes) — needs a registration decision
|
||||
- [ ] P3: filed (Handshakes)
|
||||
- [x] Regression tests (fail on 58d3db3 + the probe, pass now)
|
||||
- [x] Randomized ordering test, fast and `#[ignore]`d long
|
||||
- [x] QA's seeds and hand scenarios against the binary
|
||||
- [x] Timings
|
||||
- [x] fmt, clippy `--all-targets -D warnings`, guarded `lucisv_server`
|
||||
(fix round: 1 920 unit + 106 integration, 44 + 3 ignored),
|
||||
`vlog_semantic` 435, `lucisv_mcp` 384, `node --test
|
||||
editors/vscode/*_test.js` 37; ignored release runs (both re-index
|
||||
sweeps, the 300-seed ordering run) pass
|
||||
- [x] full `tools/gates.sh`: PASS, every step (corpus 814/6, the same six
|
||||
known failures; `lucisv_server` 2 032/0)
|
||||
|
||||
**Not verified here (no VS Code on this machine):** double-click a port name
|
||||
and run Find All References — results, not "No references found"; F12 and
|
||||
hover with the caret just after a name; a row of lucisv's References view
|
||||
opens with the caret at the name's start, and Shift+F12 from there finds the
|
||||
same list; F2 with the caret just after a name opens the rename box.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-11-19 — dev agent
|
||||
|
||||
Base is 58d3db3 (release 0.65.6). Drivers are the investigation's
|
||||
(`scratchpad/inv717/drv`), QA's oracle (`scratchpad/qa711/oracle`) and the Q1
|
||||
driver (`scratchpad/qa713/drv/livelock2.py`), copied to `scratchpad/dev717/`
|
||||
with the guard pointed at this worktree; every tree they touch is a scratch
|
||||
copy, every index store is under `dev717/st`.
|
||||
|
||||
**Reproduced on base, then fixed (same drivers, release binaries):**
|
||||
|
||||
| | 58d3db3 | now |
|
||||
|---|---|---|
|
||||
| A1 `refpos.py` uart_core.sv `tx`, caret just past the name (col 27) | refs 0, def 0, highlight null, hover null | refs 3, def 1, highlight 2, hover yes (= col 25) |
|
||||
| A1 one column further right (col 28) | 0 / 0 / null / null | 0 / 0 / null / null (unchanged) |
|
||||
| B `f6.py held`, full sync | server holds v2, client v3 | v3 |
|
||||
| B `f6.py tail`, full / incremental | v2 / v3 lost (`{qa_v2_mod}` only) | v3 / both, in place |
|
||||
| B `f6.py held`, incremental | right by luck (the two inserts commute) | right |
|
||||
| C `livelock2.py hover`, cold full OpenTitan | hover and tokens answered at 318.6 s, scan ended 318.6 s | hover 0.68 s, tokens(B) 0.76 s, scan ends 1.70 s (median of 3; 4th run, `delta` variant: 0.67 / 0.76 / 1.70 s) |
|
||||
|
||||
**A1.** `caret.rs` is the rule (23 production lines): one byte left when the
|
||||
caret's byte is not a name byte and the byte before is, or when the caret sits
|
||||
on the whitespace that ends an escaped identifier. Applied after the UTF-16 →
|
||||
byte conversion, so a multi-byte character before the name changes nothing.
|
||||
`Server::symbol_offset` in dispatch.rs uses it for the nine requests in the
|
||||
table. Decided against shifting *inside* the feature modules (`nav.rs` etc.):
|
||||
one place, one rule, and the requests with their own boundary rule are visibly
|
||||
the ones still calling `offset`. The References view's rows now open with a
|
||||
collapsed selection at the identifier's start — `vscode.open` cannot carry a
|
||||
backwards `Selection`, so "select the name, caret at its start" is not
|
||||
expressible through it, and the start is where VS Code's own view and go to
|
||||
definition put the caret.
|
||||
|
||||
**B.** `Server::must_hold` is the rule, `Server::behind` the bookkeeping. The
|
||||
prototype held every notification while a rescan a message asked for was
|
||||
running (`answering_a_rescan`). That is a superset of what is needed and it
|
||||
cost something real: a watcher event arriving during a rescan was then
|
||||
applied *after* it, one scan each, instead of coalescing into one more scan.
|
||||
`behind` is exact: `process_batch` sets it, for the message it is handling, to
|
||||
"how many older messages are unapplied in the bursts around me", so a scan's
|
||||
drain holds a notification only if something older really is waiting. Pinned
|
||||
by `a_rescans_trigger_alone_in_its_burst_still_lets_newer_changes_apply_at_once`
|
||||
(two bars: the rescan, and one more for both watcher events). Cancels follow
|
||||
the same rule, so a cancel arriving after its held request now waits *with* it
|
||||
and is honoured when the batch is replayed (before, it was dropped and the
|
||||
request computed); a cancel naming a deferred request is still honoured where
|
||||
it lands.
|
||||
|
||||
Answers to the brief's questions:
|
||||
|
||||
- *Must didClose/didSave/watched/config keep order?* Yes, all of them: the
|
||||
rule is about the stream, not the method. A `didSave` held behind a held
|
||||
request is applied after it — as the cheap one-file update, where before it
|
||||
was folded into a whole rescan.
|
||||
- *Other documents?* Same stream, same rule — `didClose(a)` then `didOpen(b)`
|
||||
(a rename) cannot cross. `a_reopen_behind_a_held_close…` pins the one-
|
||||
document form, the randomized test the cross-document one.
|
||||
- *Starvation?* The scan drains exactly as before (the drain still reads, it
|
||||
only holds). Progress is the scan's and unaffected. `shutdown` was already
|
||||
held behind a rescan a message asked for and still is: measured with
|
||||
`dev717/drv/exitmid.py` (see Timings). `exit` is read by `handle_shutdown`
|
||||
off the connection, never queued.
|
||||
- *Memory?* Under Assumptions.
|
||||
- **One exemption, kept:** a navigation request the empty-answer rule
|
||||
deferred (`Server::deferred`, startup scan only) is re-asked at the next
|
||||
publish, and a `didChange` applied in between moves the text under its
|
||||
position. That is the perf5r-publication design, not a reordering of
|
||||
applied messages; the worst it gives is a stale or empty navigation answer,
|
||||
never a buffer change. Not changed.
|
||||
|
||||
**C.** As the prototype: the `didOpen` arm sets `head_owed` and
|
||||
`opened_mid_scan` when a scan is running; `answer_what_is_waiting` clears the
|
||||
flag before the batch and takes it after. **Bound:** a held batch is handed
|
||||
back only when `!answering && !rescan_wanted && !head_owed`; handling it
|
||||
re-holds something only behind a `didOpen` it *applied* (each message is
|
||||
applied once) or a rescan it asked for (one per scan), so hand-backs ≤
|
||||
applied `didOpen`s + scans + 1 — the randomized test asserts exactly that
|
||||
inequality every round, and base breaks it at seed 1, round 0 (37 hand-backs
|
||||
for 2 `didOpen`s and 1 scan).
|
||||
|
||||
**P2.** The index now holds every open buffer (a `didOpen` that moves no scope
|
||||
takes an unheld buffer in through `update_one_file`, the path F4 already
|
||||
used) and forgets a closed one that `scope_could_take` says no scan would
|
||||
hold. Both halves were needed: closing alone fixed `r2attack.py
|
||||
excluded-close` "closed" and "saved then closed" and broke "reopened". Mid-scan
|
||||
the open half does nothing (as before) and the close half asks for one more
|
||||
scan. One existing test changed fixture, not assertion:
|
||||
`sync::closing_a_dirty_buffer…` opened two files that were not on disk, which
|
||||
now costs an index change on close; the files are written to disk so the test
|
||||
asks what it always asked.
|
||||
|
||||
**P1, P3:** not changed — see Handshakes for what VS Code actually sends and
|
||||
why the fix is a registration decision.
|
||||
|
||||
**Tests** (new files; each failing test was run against 58d3db3 plus only the
|
||||
`probe` hook, in `scratchpad/dev717/basecopy`):
|
||||
|
||||
| test | 58d3db3 |
|
||||
|---|---|
|
||||
| `scan_ordering::a_change_drained_mid_rescan_waits_behind_an_older_change_held_with_a_request` | FAIL (holds v2) |
|
||||
| `scan_ordering::incremental_changes_held_mid_rescan_are_applied_in_the_order_they_were_sent` | FAIL (second insert one line off) |
|
||||
| `scan_ordering::a_change_drained_mid_rescan_waits_behind_the_rest_of_the_burst_that_started_it` | FAIL (holds v2) |
|
||||
| `scan_ordering::a_reopen_behind_a_held_close_leaves_the_buffer_open_with_its_new_text` | FAIL (buffer closed) |
|
||||
| `scan_ordering::a_request_ahead_of_a_didopen_mid_startup_is_answered_and_the_drain_runs_once` | FAIL (answered after the bar) |
|
||||
| `scan_ordering::a_request_behind_a_didopen_mid_startup_still_waits_for_the_buffer_it_names` | pass (kept behaviour) |
|
||||
| `scan_ordering::a_rescans_trigger_alone_in_its_burst_still_lets_newer_changes_apply_at_once` | pass (kept behaviour) |
|
||||
| `caret_boundary::every_symbol_request_answers_the_same_just_past_a_name_as_at_its_start` | FAIL (references `[]`) |
|
||||
| `caret_boundary::a_caret_after_a_dot_is_on_the_member_and_before_it_on_the_instance` | FAIL |
|
||||
| `caret_boundary::the_column_past_a_name_is_counted_in_utf16_after_non_ascii_text` | FAIL |
|
||||
| `outside_buffers::an_excluded_buffer_is_held_while_open_and_forgotten_when_closed` | FAIL |
|
||||
| `outside_buffers::a_buffer_not_on_disk_is_held_while_open_and_forgotten_when_closed` | FAIL |
|
||||
| `outside_buffers::closing_a_buffer_the_scope_takes_leaves_the_index_alone` | pass (kept behaviour) |
|
||||
| `ordering_random::random_bursts_keep_every_buffer_and_answer_every_request_once` | FAIL (C bound, seed 1 round 0; with that check disabled, B: seed 1 round 5, `a.sv` lost an edit) |
|
||||
| `caret::tests` (7, the rule itself) | — (new module) |
|
||||
|
||||
**Randomized test** (`ordering_random.rs`): a seeded xorshift client with three
|
||||
documents sends bursts of 1–4 messages — full and incremental `didChange`s
|
||||
(insert or delete a line, ranges in the client's own current text),
|
||||
`didOpen`/`didClose`, `$/cancelRequest` for a random earlier id, hover /
|
||||
definition / documentSymbol / workspace/symbol, and watcher create/delete
|
||||
events; 70 % of rounds put a rescan trigger at a random place in the round's
|
||||
first burst, and 0–6 more bursts land at the scan's interleave points through
|
||||
the probe. The startup scan gets 1–5 scripted bursts too (that is where C
|
||||
lives). After every round: the server's open buffers are the client's and
|
||||
their text is byte-equal; hand-backs ≤ `didOpen`s + scans + 1. At the end:
|
||||
every request answered exactly once, and documentSymbol of every open buffer
|
||||
plus the created packages equal a fresh server's on the same disk and
|
||||
buffers. Normal suite: seeds 1–12 × 10 rounds, ≥ 200 bursts must land
|
||||
mid-scan (300 do), 0.8 s debug. `#[ignore]`d long run: seeds 100–399 × 40
|
||||
rounds, ≥ 10 000 mid-scan bursts, 32 s in release — passes.
|
||||
|
||||
**QA's oracle against this binary** (logs `scratchpad/dev717/logs/`), none
|
||||
with `QA_REPAIR` (the "re-send buffers before each check" workaround):
|
||||
|
||||
| run | 58d3db3 / QA | now |
|
||||
|---|---|---|
|
||||
| `rand_run.py` corpus, push, seed 7 × 200 (every 25) | divergent at step 200 (F6) | 8 checks, 0 divergent |
|
||||
| `rand_run2.py` OpenTitan sample, seed 42 × 500 (every 25), `QA_FRESH_SAVE=1` as in QA's run | step 350 divergent (F6) | 20 checks, 0 divergent |
|
||||
| `rand_run.py` full OpenTitan `hw`, seed 21 × 50 (every 50) | 309 answers differ | 0 differ |
|
||||
| `small.py`, workspace + folder scope, pull and push | — | 94 + 94 ok; only `NEGCTL-silent` diverges (both scopes), as it must |
|
||||
| `outside.py`, pull and push | — | 14/14 and 14/14 ok (re-run on the final binary too) |
|
||||
| `r2attack.py` (all cases) | `directory-create`, `held-directory-deleted` (P1), `excluded-open-close` closed / saved-then-closed (P2) diverge | only the two P1 cases diverge |
|
||||
|
||||
Seed 42 run *without* `QA_FRESH_SAVE` diverged at step 50 on an excluded
|
||||
buffer (`qa_excl/qa_x0.sv`) the incremental server now holds while it is open
|
||||
and the fresh side does not — the fresh server's documented startup race (a
|
||||
buffer opened while its startup scan takes its work list is not taken in),
|
||||
which is what `QA_FRESH_SAVE` exists to remove; with it, 0 divergent over 500
|
||||
steps.
|
||||
|
||||
**Re-index lane sweeps** (release, `--ignored a_seeded_sweep`): corpus 3
|
||||
seeds and OpenTitan sample 2 seeds, both pass.
|
||||
|
||||
**Timings** (release, full OpenTitan `hw` 4 061 files, workspace scope; the
|
||||
machine is shared with another lane):
|
||||
|
||||
| | 58d3db3 | now |
|
||||
|---|---:|---:|
|
||||
| startup scan, cold (median of 3) | 2 104 ms | 2 077 ms |
|
||||
| startup scan, warm (median of 3) | 1 124 ms | 1 124 ms |
|
||||
| `perf.py`, median of 5, save → `reindex_one` line: uart_tx comment / uart_tx signal / prim_flop signal / prim_flop top / uart_reg_pkg member / prim_assert / prim_mubi member / prim_mubi top / tlul_pkg top / new `uvm_object` / new `` `define`` / clk_rst_if top | 0.04 / 8.2 / 8.1 / 67.3 / 22.8 / 3.5 / 97.9 / 98.8 / 85.4 / 13.4 / 9.5 / 28.6 | 0.04 / 8.6 / 8.4 / 67.1 / 23.5 / 3.4 / 106.5 / 103.2 / 84.3 / 10.5 / 14.6 / 30.0 |
|
||||
| watcher echo, every row | 0.03–0.35 ms | 0.02–0.33 ms |
|
||||
| C: `[hover, didOpen(B), tokens(B)]` in a cold startup (`livelock2.py`) | 318.6 s | 1.70 s scan, hover 0.68 s |
|
||||
| `didClose` of a held file (P2's scope check), median of 3: prim_assert (174-file dir) / top_earlgrey / uart_core / dv_base_env | 0.02 / 0.16 / 0.13 / 0.02 ms | 1.22 / 0.41 / 0.27 / 0.22 ms |
|
||||
| `didOpen` of the same four | 0.21 / 1.64 / 1.28 / 0.31 ms | 0.20 / 1.57 / 1.15 / 0.28 ms |
|
||||
| shutdown sent mid-rescan, behind a held hover and change (`exitmid.py`) | answered 0.75 s, exit 0.92 s later | answered 0.76 s, exit 0.87 s later |
|
||||
|
||||
The save rows move by noise either way except `prim_mubi_pkg` (+5–9 ms of
|
||||
~100) and the new `` `define`` (+5 ms), both single-digit and in rows whose
|
||||
work this round does not touch (nothing here runs on a save); a `didClose`
|
||||
now pays the scope walk of its directory, about a millisecond at worst.
|
||||
|
||||
**Test hook:** `server/probe.rs` (`#[cfg(test)]`, thread-local) — the
|
||||
transport cannot be timed against a scan's files, so a test scripts what
|
||||
arrives at each interleave point. One `#[cfg(test)]` line in
|
||||
`answer_what_is_waiting`.
|
||||
|
||||
**Files** (production lines, non-blank non-comment, before `mod tests`; base
|
||||
in parentheses): `server/mod.rs` 203 (186), `server/dispatch.rs` 491 (486),
|
||||
`server/index.rs` 292 (265), `server/notification.rs` 252 (244),
|
||||
`server/batch.rs` 74 (`opened_in` removed), `server/startup.rs` 173 (+2),
|
||||
`state/watched.rs` 95 (+3), `state/incremental.rs` 145 (+4), new
|
||||
`caret.rs` 23, new `server/probe.rs` 46 (test-only); `main.rs` +1;
|
||||
`editors/vscode/referencesView.js` +5. Tests: `server/tests/{scan_ordering,
|
||||
caret_boundary,ordering_random,outside_buffers}.rs` new, `tests/mod.rs`
|
||||
+4 module lines, `tests/sync.rs` fixture, `referencesView_test.js` one
|
||||
assertion.
|
||||
|
||||
### 2026-11-19 — dev agent: fix round (QA-1 … QA-5, the size note)
|
||||
|
||||
**QA-1 — P2 reverted.** `take_in_if_unheld`, `forget_if_outside`,
|
||||
`Workspace::holds_outside_the_scope` and `Workspace::forget_file` are gone;
|
||||
`state/watched.rs`, `state/incremental.rs` and `server/tests/sync.rs` are
|
||||
byte-identical to 58d3db3 again (the `sync` fixture change is undone —
|
||||
without P2 it is not needed), `server/tests/outside_buffers.rs` is deleted.
|
||||
Making open/close of an unheld file cost < 1 ms is not reachable at the
|
||||
server layer: adding or removing one file shifts ids and rebuilds the
|
||||
completion tables and the include naming (QA's `sample`), so it is filed as
|
||||
an index-layer change (Handshakes, with QA-2 and QA-7a). QA's drivers,
|
||||
full OpenTitan, before the other lane's load test started:
|
||||
|
||||
| `lat717.py` (median of 5), didOpen / didClose | 58d3db3 | round 1 (QA) | now |
|
||||
|---|---|---|---|
|
||||
| held files | 0.83–2.72 / 0.11–0.27 ms | 0.47–1.74 / 0.39–1.02 ms | 0.80–3.43 / 0.11–0.29 ms |
|
||||
| outside the root | 0.57–0.59 / 0.08–0.10 ms | 185–189 / 222–230 ms | 0.54–0.56 / 0.06–0.08 ms |
|
||||
| excluded | 0.55–0.59 / 0.07 ms | 188–190 / 222–225 ms | 0.44–0.81 / 0.07–0.08 ms |
|
||||
| outside / excluded, 200 buffers open | 0.47–0.60 / 0.07–0.08 ms | 201–228 / 258–279 ms | 0.52–0.58 / 0.06–0.08 ms |
|
||||
| `p2perf.py`: 2 000 outside files opened and closed | 0.7 s | 806 s | 0.7 s |
|
||||
| `p2perf.py`: didClose with ~200 open, in-scope / outside (median) | 0.13 / 0.09 ms | — | 0.11 / 0.09 ms |
|
||||
|
||||
**QA-3 — the rule narrowed** to "no notification overtakes an older
|
||||
notification" (`must_hold`; the soundness argument is under Assumptions).
|
||||
Chosen over a staging-only patch because it is the rule B actually needs and
|
||||
the broad rule bought no state the client could see; the staging case then
|
||||
needs nothing special. `live717.py staging`, first hover with a request ahead
|
||||
of the first `didOpen`: 58d3db3 0.111–0.133 s, round 1 0.151–0.160 s, now
|
||||
0.116–0.125 s (3 × 3 runs). Cancels: one waits whenever anything is held
|
||||
(so a late cancel of a held request is still honoured); `changes_state`
|
||||
excludes them from what makes a notification wait. New test
|
||||
`a_change_behind_only_a_held_request_applies_at_once_and_a_late_cancel_waits_with_it`
|
||||
pins both halves. Every earlier test, the randomized one (fast and the
|
||||
`#[ignore]`d 300-seed run) and f6.py's six variants pass unchanged.
|
||||
|
||||
**QA-4 — documented, not changed.** QA's `c717.py` (cold full OpenTitan, 16–18
|
||||
bursts `[request, didOpen×1–3]` in the first 0.2 s) on the narrowed rule:
|
||||
scan ends 3.74–4.17 s (5 seeds), answers 0.02–4.17 s, median 1.40–1.68 s; QA
|
||||
measured 2.8–4.2 s on round 1, the same 26 opens without requests 1.66–1.89 s.
|
||||
Each request behind an applied `didOpen` is held until the work list
|
||||
re-ordered round that buffer has indexed its neighbourhood, and the hand-back
|
||||
then forces a publish (a merge over the index so far) so the answer can see
|
||||
it — one per burst here. Coalescing hand-backs would mean answering a later
|
||||
burst's requests before *its* neighbourhood is in, which is the §P4b `[]`
|
||||
the head rule exists to prevent; cheaper publishes are the index layer's.
|
||||
So the cost stays: bounded (≤ one forced publish per applied `didOpen`),
|
||||
seconds, against ~400 s on base.
|
||||
|
||||
**QA-5 — the changelog** now names what is ordered: edits, opens, closes,
|
||||
saves and the other notifications (not responses, not deferred navigation
|
||||
requests).
|
||||
|
||||
**Size.** `process_batch` 95 → 69 lines: the splice into `held` is
|
||||
`Server::hold`, and answering one request (cancelled / deferred / computed)
|
||||
is `Server::answer_from_batch`. No behaviour moved.
|
||||
|
||||
**Fix-round checks against this binary** (`dev717/logs3`, none with
|
||||
`QA_REPAIR`). Another lane ran an 18-busy-loop load test on this machine from
|
||||
about 11:00 into the oracle runs, so the latency numbers below that window are
|
||||
not comparable and were re-taken after it eased.
|
||||
|
||||
| run | result |
|
||||
|---|---|
|
||||
| `refpos.py` (A1) | col 27 = col 25 (refs 3, def 1, highlight 2, hover), col 28 nothing — unchanged |
|
||||
| `f6.py` held / tail / control, full and incremental | all six: server holds v3, incremental inserts in place |
|
||||
| `livelock2.py hover` (C), after the load eased | hover 0.66–0.90 s, tokens(B) 0.74–0.99 s, scan ends 1.67–2.15 s (3 runs) |
|
||||
| `q1min.py` | answered 0.96 s, one progress cycle |
|
||||
| corpus push 7 × 200 | 8 checks, 0 divergent |
|
||||
| OpenTitan sample 42 × 500 (`QA_FRESH_SAVE=1`) | 20 checks, 0 divergent |
|
||||
| full OpenTitan 21 × 50 | 0 divergent |
|
||||
| new: corpus push 111 × 300 (`rand_run2.py`) | 12 checks, 0 divergent |
|
||||
| new: OpenTitan sample 211 × 300 (`QA_FRESH_SAVE=1`) | 12 checks, 0 divergent |
|
||||
| `small.py` pull and push, both scopes | 94 + 94 ok; only `NEGCTL-silent` diverges, as it must |
|
||||
| `outside.py` pull and push | 14/14 and 14/14 |
|
||||
| `r2attack.py` | P1's two cases and P2's two (excluded-open-close closed / saved then closed) diverge — 58d3db3's set, as the revert intends |
|
||||
| full `tools/gates.sh` | PASS every step; `lucisv_server` 2 030/0, corpus 814/6 |
|
||||
|
||||
**Production lines now** (as before, base in brackets): `server/mod.rs` 215
|
||||
(186), `server/index.rs` 267 (265), `server/notification.rs` 248 (244),
|
||||
`server/batch.rs` 77 (`opened_in` removed, `changes_state` added),
|
||||
`server/dispatch.rs` 491 (486), `server/startup.rs` +2, `caret.rs` 23,
|
||||
`server/probe.rs` 46 (test-only); `state/` untouched.
|
||||
|
||||
## Changelog paragraph (for the lead)
|
||||
|
||||
**Find All References, Go to Definition, hover, highlight and rename now work
|
||||
with the cursor just after a name.** A double-click, a click on the right half
|
||||
of the last letter, or a click on a row of lucisv's References view leaves the
|
||||
cursor there, and the server used to look at the character after the name —
|
||||
so VS Code said "No references found" until you clicked away and back. The
|
||||
References view now also puts the cursor at the start of the name it opens.
|
||||
**An edit typed while the workspace was re-indexing could be applied out of
|
||||
order**, leaving the server's copy of the file different from the editor's
|
||||
until it was closed and reopened; edits, opens, closes, saves and the other
|
||||
notifications the editor sends are now applied in the order it sent them. **A
|
||||
file opened while the first index of a session was being built could make
|
||||
that index take minutes instead of seconds** on a large workspace (about
|
||||
300 s instead of 2 s on OpenTitan); fixed.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-11-19 — QA agent (Opus 5.5)
|
||||
|
||||
**Verdict: PASS WITH FINDINGS.** No lost, duplicated or reordered message, no
|
||||
deadlock, no wrong buffer text and no wrong rename found in anything below. One
|
||||
**High** finding (QA-1, a P2 cost: opening or closing a file the index does not
|
||||
hold now blocks the loop ~0.2 s on OpenTitan) should be fixed before release;
|
||||
the rest are Low/Info or pre-existing. Everything ran against release binaries
|
||||
built here (`qa717/bin/new` from this worktree, `qa717/bin/base` from
|
||||
`git archive 58d3db3`, own `CARGO_TARGET_DIR`s). All drivers and logs are in
|
||||
`scratchpad/qa717/{drv,oracle,logs}`; every tree was a scratch copy, every
|
||||
index store under `qa717/st`; `~/.cache/lucisv-opentitan-full` `git status
|
||||
--short` empty and nothing under either cache newer than this QA's start.
|
||||
|
||||
**Baseline.** `tools/gates.sh` (full, logs `qa717/gates/`): PASS — fmt,
|
||||
clippy `-D warnings`, build, every suite (`lucisv_server` 2 032/0,
|
||||
`vlog_semantic` 435/0, `lucisv_mcp` 384/0), docs, corpus 814/6, node 37/0.
|
||||
One guard kill — see QA-6. Ignored release runs (`--ignored ordering_random
|
||||
sweep_over_the_corpus sweep_over_an_opentitan`, guarded, trees from scratch
|
||||
copies): 3/3 pass. Counts vs 58d3db3: `lucisv_server` unit 1 901 + 43 ignored →
|
||||
1 922 + 44 (+14 server tests, +1 ignored long run, +7 `caret` unit); integration
|
||||
106/3 unchanged; no pre-existing test removed or edited except `sync.rs`.
|
||||
**The changed fixture:** with the base fixture on the new code the test fails
|
||||
`generation 6 != 5` — P2's take-in/forget of two not-on-disk buffers is an extra
|
||||
index change and republish. Writing the files to disk keeps the test's subject
|
||||
(the closed buffer's dirty text is never analyzed, the other one flushes) and
|
||||
every assertion's meaning; accepted. **New tests on base:** grafted
|
||||
`probe.rs` + its one `#[cfg(test)]` call + the four test files onto the
|
||||
58d3db3 archive: exactly the 11 the README lists fail, the 3 "kept behaviour"
|
||||
tests pass. `probe` is `#[cfg(test)]` at `server/mod.rs:60` and
|
||||
`server/index.rs:522`, no other reference. Sizes: every touched file under 600;
|
||||
`process_batch` is 95 lines (78 on base), mostly comment — over the 80 line
|
||||
"investigate" mark (Info).
|
||||
|
||||
**B/C code read.** `must_hold`, `behind`, `process_batch`,
|
||||
`answer_what_is_waiting`, `waiting_for_this_scan`, `run`'s replay,
|
||||
`take_the_answer_out_of_held` and the staging loops: every message put in
|
||||
`held` is taken out by `run` (loop top) or by the startup scan's drain; `held`
|
||||
non-empty never outlives a scan, and nothing waits on a client response except
|
||||
staging's bounded waits (the only `recv_timeout`s). `behind` is restored on
|
||||
every exit of `process_batch` that the caller reads. No path found where a
|
||||
message is applied twice or dropped.
|
||||
|
||||
**B — ordering, own stdio driver** (`drv/ord717.py`, independent of the probe):
|
||||
4 synthetic documents in 4 folders, seeded bursts of 1–5 messages written in
|
||||
one `write()` — incremental single- and multi-change and full `didChange`s,
|
||||
`didOpen` (disk or new text), save-then-`didClose`, `didSave` (±text),
|
||||
documentSymbol / hover / definition / references / semanticTokens / highlight /
|
||||
workspace/symbol, `$/cancelRequest` of a recent id, watcher create/delete of
|
||||
package files, an unknown notification, a malformed `didChange` — while scans
|
||||
run: the startup scan, workspace-folder add/remove, a pushed and an *empty*
|
||||
(`workspace/configuration` pull) config change, a save of an unheld file,
|
||||
watcher creates. Checked: **every documentSymbol answer equals the client's
|
||||
text at the moment the request was sent** (the order contract, exact
|
||||
names/lines/columns); after each settle every buffer's text, open/closed state
|
||||
and the watcher/save effects; every id answered exactly once; a final battery
|
||||
(documentSymbol, semantic tokens, hover/references/definition at both ends of
|
||||
every name, workspace/symbol, push diagnostics) equal to a fresh server's.
|
||||
Runs: corpus seeds 1–3 ×30 and 10–17 ×60 (workspace), 20–23 ×60 (folder); full
|
||||
OpenTitan seeds 30–32 ×40 (workspace), 40–41 ×40 (folder): **≈ 8 700 bursts,
|
||||
≈ 27 000 messages, 85 % of bursts sent while a scan was running, ≈ 4 500
|
||||
at-send-time checks — 0 ordering/text/state failures, 0 duplicate or missing
|
||||
responses.** Fresh oracle: equal in every run once the driver saved dirty
|
||||
buffers before comparing (the 6 seeds that had differed, re-run, and the 5 that
|
||||
never had); the 12 runs that differed before that correction differed *only* in
|
||||
`workspace/symbol` for module names typed but not yet saved — the documented
|
||||
index staleness of unsaved text, not this lane. The same driver on **base fails at once** (seed 1: 22 failures,
|
||||
both scopes — stale documentSymbol answers, a buffer one edit behind).
|
||||
(Two driver corrections were needed, both *my* model: duplicate wire names
|
||||
collapse in documentSymbol; and unsaved buffer text reaches the index only at a
|
||||
scan or save, so the final oracle saves dirty buffers first. A third thing the
|
||||
driver found is pre-existing — QA-7.)
|
||||
|
||||
**Liveness / latency** (`drv/live717.py`, full OpenTitan, whole rescans of
|
||||
~0.6–1.8 s; base vs new):
|
||||
|
||||
| case | 58d3db3 | now |
|
||||
|---|---|---|
|
||||
| hover held mid-rescan, then its cancel: cancel → answer | 0.55–0.59 s, honoured 4/5 (once computed) | 0.58–0.62 s, honoured 5/5 |
|
||||
| shutdown behind a held hover + change mid-rescan: answer / exit | 0.65 s / 0.86 s; hover answered first | 0.66 s / 0.94 s; hover answered first |
|
||||
| `exit` alone mid-rescan with a held queue | exits 0.8–1.6 s | exits 1.0–1.6 s |
|
||||
| server's `workspace/configuration` (+ progress create, lens refresh) held by the client, answered mid-burst while notifications are held | no deadlock, final text right | no deadlock, final text right |
|
||||
| 20 000 incremental `didChange`s flooded behind a held request across rescans | settle 23 s, RSS peak 686 MB, **text wrong** | settle 27 s, RSS peak 679 MB, text right |
|
||||
| VS Code-like typing (change + tokens + highlight per key, 30 ms) through 5 rescans | scans 1.5–1.85 s, **text wrong at the end** | scans 1.6–1.86 s, text right |
|
||||
| request before the first `didOpen` during staging: first hover | 0.11–0.13 s | 0.15–0.18 s (QA-3) |
|
||||
|
||||
(The shutdown case exits with rc 1 in 2 of 3 runs on *both* binaries — pre-existing, Info.)
|
||||
|
||||
**C bound** (`drv/c717.py`: cold startup on full OpenTitan, 26 `didOpen`s in
|
||||
13–14 bursts `[request, didOpen×1–3]` every 2–10 ms): base — every answer at
|
||||
406.9 s, scan ends 406.9 s. Now — scan ends 2.8–4.2 s (5 seeds), answers
|
||||
0.03–4.15 s, no duplicate. Same 26 opens with no requests between them: scan
|
||||
1.66–1.89 s; plain cold startup 1.65 s. So C is fixed and bounded, but see QA-4.
|
||||
|
||||
**A1 sweep** (`drv/a1sweep.py`): 200 corpus files × 25 tokens and 150 OpenTitan
|
||||
files × 20 tokens (identifiers, keywords, macros, system tasks, numbers), all
|
||||
nine requests: **69 030 token×request pairs; end == start == middle on the new
|
||||
server in every one**; new == base at the start in all but 6 (all in
|
||||
OpenTitan's duplicated `top_*/ip/ast` modules — `rename` there is
|
||||
nondeterministic on base too: 4 edit / 4 refused in 8 fresh base servers; QA-7);
|
||||
**one column right of the name (40 158 cases) new == base in every one.**
|
||||
Edges (`drv/a1edge.py`, `drv/a1rename.py`): `\foo `/`\a+b ` (on the ending
|
||||
space: the name; after it: nothing), `$bits(a|)`, `` `FOO| ``, `` `BAR|(b) ``,
|
||||
`8'hFF|` / `8'hF|F` / `12|` (nothing — no `hFF`/`FF` signal resolved),
|
||||
`begin|`/`end|`, `u_a|.b`/`u_a.|b`/`u_a.b|`, `pkg|::x`/`pkg:|:x`/`pkg::|x`/`pkg::x|`,
|
||||
`a|+b`, `x|[i]`, `x[i|]`, `f|(a)`, `f(a|)`, end of line, `endmodule : d|` at EOF
|
||||
with and without newline, empty file, column 0, CRLF, tabs, non-ASCII and an
|
||||
astral character before the name, `ifdef`-out region: end-of-name == start
|
||||
everywhere. Comments, strings and a `` `define`` body: nothing at start and end.
|
||||
Rename/prepareRename at the end-of-name caret: placeholder and range are the
|
||||
whole name and the applied edit is byte-identical to the one from the start in
|
||||
all nine shapes — never the neighbour. A position past the end of a line now
|
||||
resolves the line's last name (VS Code never sends one; Info). **Request table:**
|
||||
every arm in `dispatch.rs` that reads a position is either one of the nine or in
|
||||
the "as sent" rows (linked editing, signature help, completion, inline
|
||||
completion, on-type, selection range, the two code-action uses of
|
||||
`range.start`, executeCommand); declaration/implementation/moniker are not
|
||||
served; nothing missed.
|
||||
|
||||
**P2** (`drv/p2.py`: excluded / outside-the-root / not-on-disk buffer ×
|
||||
open-close, open, close-reopen, save-close, change-close, open-mid-scan-close,
|
||||
close-mid-scan, open+close in one burst; fresh server with the same buffers
|
||||
opened before its scan): workspace scope **24/24 equal (base 12/24)**. Folder
|
||||
scope: the outside-the-root file stays held after close — the opened file's
|
||||
folder widened the scope, which never shrinks; base does the same in an
|
||||
isolated tree, by design. 2 000 distinct outside files opened and closed: RSS
|
||||
695 → 718 MB, none left in the index — but see QA-1 for the time it took.
|
||||
`QA_FRESH_SAVE` — see QA-2.
|
||||
|
||||
**Re-index oracle on this binary** (QA 71.1's scripts, no `QA_REPAIR`):
|
||||
`small.py` pull and push, both scopes: only `NEGCTL-silent` diverges, as it must;
|
||||
`outside.py` 14/14 both. Previously failing seeds: corpus push 7 ×200 — 8 checks,
|
||||
0 divergent; full OpenTitan 21 ×50 — 0 differ; OpenTitan sample 42 ×500 with
|
||||
`QA_FRESH_SAVE` — 20 checks, 0 divergent (without it: divergent at step 50, the
|
||||
QA-2 race). New seeds: corpus 101–103 ×500 and push/folder 104 ×500 — 0 divergent;
|
||||
OpenTitan sample 201–203 ×500 — 0 divergent with `QA_FRESH_SAVE`, divergent at
|
||||
step 150–200 without (every diff an excluded `qa_excl` buffer, QA-2); full
|
||||
OpenTitan 301 ×100 — 13 answers differ at step 100, **identically on base**
|
||||
(QA-7).
|
||||
|
||||
**References view.** VS Code's `TextEditorOpenOptions.from` converts
|
||||
`selection` with `Range.from` and `codeEditorWidget.setSelection(IRange)` makes
|
||||
the range's *end* the position — so base put the caret just past the name, the
|
||||
A1 spot; a collapsed range at `range.start` puts it at the name's start, where
|
||||
Shift+F12 works on a base server as well as this one (VS Code's own references
|
||||
view uses `range.with({ end: range.start })`). Cost: the row no longer
|
||||
*selects* the identifier. The test asserts the new collapsed range. The P1
|
||||
analysis checks out against `watcher.ts` (`coalesce`: deletes under a deleted
|
||||
parent dropped) and `extHostFileSystemEventService.ts` (each event filtered by
|
||||
the registered glob). The extension sets no `wordPattern`, so VS Code's default
|
||||
word rule is the one in play.
|
||||
|
||||
**Timings** (release, full OpenTitan, workspace scope, medians of 5, machine
|
||||
shared with this QA's own runs): cold startup 1 667 → 1 681 ms, warm 747 → 747
|
||||
ms. Open/close (`drv/lat717.py`, didOpen → its publish, didClose → its clearing
|
||||
publish):
|
||||
|
||||
| file | 58d3db3 open / close | now open / close |
|
||||
|---|---|---|
|
||||
| held (prim_assert, top_earlgrey, uart_core, dv_base_env) | 0.46–1.83 / 0.07–0.18 ms | 0.47–1.74 / 0.39–1.02 ms |
|
||||
| outside the root, 0 other buffers | 0.33–0.36 / 0.06–0.07 ms | **185–189 / 222–230 ms** |
|
||||
| excluded, 0 other buffers | 0.34–0.37 / 0.06–0.07 ms | **188–190 / 222–225 ms** |
|
||||
| outside / excluded, 200 buffers open | 0.31–0.38 / 0.05–0.07 ms | **201–228 / 258–279 ms** |
|
||||
|
||||
Saves (QA 71.1's `perf.py`, 5 reps, save → `reindex_one` line, base / now):
|
||||
uart_tx comment 0.05 / 0.04, uart_tx signal 5.4 / 4.2, prim_flop signal 4.4 /
|
||||
4.3, prim_flop top 49.6 / 48.8, uart_reg_pkg member 12.9 / 12.1, prim_assert
|
||||
1.4 / 1.5, prim_mubi member 93.5 / 91.2, prim_mubi top 90.3 / 85.1, tlul_pkg top
|
||||
69.9 / 67.1, new `uvm_object` 4.8 / 4.1, new `` `define`` 6.9 / 6.2, clk_rst_if
|
||||
top 16.6 / 26.2 ms; echoes 0.03–0.28 ms both. Unchanged within noise except
|
||||
clk_rst_if, the one row that moved (the dev measured it 28.6 / 30.0, so most
|
||||
likely noise; nothing in this lane runs on a save).
|
||||
|
||||
**Findings**
|
||||
|
||||
- **QA-1 (High, performance, P2).** `server/index.rs:212-224`
|
||||
(`take_in_if_unheld`) and `:189-202` (`forget_if_outside`), called from
|
||||
`notification.rs:109` and `:285`. Taking an unheld buffer in on `didOpen`
|
||||
and forgetting it on `didClose` each run a one-file index update plus lens
|
||||
refresh, hierarchy bump and `republish_all`, synchronously on the message
|
||||
loop. On full OpenTitan that is ~190 ms per open and ~225 ms per close (table
|
||||
above; ×500–3 000 vs base), with nothing else open; 2 000 outside files opened
|
||||
and closed took **806 s vs 0.7 s** (`drv/p2perf.py`). A `sample` of the server
|
||||
meanwhile sits in `Candidates::unit_tables`/`merge_words`/`take_index_tables`,
|
||||
`IncludeGraph::refresh_naming_all`, `dependents::note`,
|
||||
`WorkspaceIndex::push_records`. Every keystroke, hover and completion queued
|
||||
behind such an open/close waits for it. Repro:
|
||||
`python3 -I drv/lat717.py BIN <OpenTitan copy> 5`. The README's timing rows
|
||||
measured only *held* files. Correctness of P2 is fine; its cost is not.
|
||||
- **QA-2 (Low, P2 gap; on the `QA_FRESH_SAVE` question).** A buffer the index
|
||||
does not hold that is opened while a scan is running is not taken in, and
|
||||
nothing takes it in when that scan ends (`take_in_if_unheld` returns at
|
||||
`scan_owed()`): `drv/race717.py BIN <OpenTitan copy> 0.5` — an excluded file
|
||||
opened 0.5 s into the startup scan is still unheld after settle, base and new
|
||||
alike; opened before the scan it is held. So "the index holds every open
|
||||
buffer" (Handshakes 4) is true only for buffers opened outside a scan, and the
|
||||
same final state answers differently depending on when the buffer was opened.
|
||||
The dev's argument is sound as far as it goes — the divergence `QA_FRESH_SAVE`
|
||||
removes is the *fresh* server losing this race, not the incremental one
|
||||
getting anything wrong — but it is a real, user-visible nondeterminism of the
|
||||
server (pre-existing in kind), and `QA_FRESH_SAVE` hides it. Suggest taking in
|
||||
open unheld buffers when a scan finishes, or documenting the limit in
|
||||
Handshakes 4 rather than only in the code comment.
|
||||
- **QA-3 (Low, startup).** `startup.rs:283-296` (`await_opening_file`): a
|
||||
request that arrives before the first `didOpen` during staging is held
|
||||
(`staging`), and the `didOpen` behind it is now held too (`must_hold`:
|
||||
`held` non-empty), so the "wait for the first buffer" loop never sees it,
|
||||
waits its full 25 ms bound, and the startup scan does not lead with the user's
|
||||
folder. Measured first hover 0.15–0.18 s vs 0.11–0.13 s (`live717.py staging`).
|
||||
Harmless to correctness; not mentioned in the README.
|
||||
- **QA-4 (Low, C cost).** The C bound holds (≤ one hand-back per applied
|
||||
`didOpen` + 1), but each hand-back forces a `publish_scan`: 26 opens
|
||||
interleaved with requests stretch the cold OpenTitan startup scan from
|
||||
1.65–1.9 s to 2.8–4.2 s, and in 2 of 5 seeds a request is answered only at
|
||||
the scan's end (3.7–4.2 s). Five minutes → four seconds, so this is a note,
|
||||
not a blocker; the README's 1.70 s figure is for the 3-message `livelock2`
|
||||
burst.
|
||||
- **QA-5 (Info, docs).** The changelog's "every message is now handled in the
|
||||
order it was sent" overstates it: responses and deferred navigation requests
|
||||
are exempt (both explained in the Work log). Suggest "every edit".
|
||||
- **QA-6 (Info, pre-existing, outside this lane).** `tools/gates.sh`:
|
||||
`suite:lucisv_mcp` was KILLED by the guard at 600 s and passed on the retry;
|
||||
the hung test was `qa_m3::qa_lucisv_check_over_the_same_tree_while_the_server_formats`
|
||||
(`crates/lucisv_mcp/tests/qa_m3.rs:687`). `lucisv_mcp` does not depend on
|
||||
`lucisv_server`, and the 0.65.5 release gates log shows the same KILLED →
|
||||
retried. Not filed anywhere in `TODO.md`; reporting as CLAUDE.md asks.
|
||||
- **QA-7 (pre-existing, outside this lane — file for the backlog).** (a)
|
||||
Closing an **unsaved in-scope** buffer whose text a rescan took into the
|
||||
index leaves that text in the index after the close (`drv/closeidx.py BIN
|
||||
rescan`: `qd_buf` survives the close, a fresh server holds `qd_disk`) —
|
||||
identical on base; P2 covers excluded/unlisted files only. (b) `rand_run.py`
|
||||
full OpenTitan seed 301 ×100: 13 answers differ at step 100 (pull diagnostics,
|
||||
references, incoming calls in `top_earlgrey/ip/ast/rtl/usb_osc.sv`) —
|
||||
byte-identical divergence on base. (c) Rename of a port of a module defined
|
||||
twice in OpenTitan (`top_englishbreakfast/ip/ast/rtl/adc.sv:81`
|
||||
`rst_adc_ni`) is edit-or-refuse at random across fresh servers, base and new
|
||||
(`drv/dup.py`). All three involve state this lane did not touch.
|
||||
|
||||
**Fixed myself:** nothing. **Not verified (no VS Code here):** the four items
|
||||
under Status; that VS Code itself never sends a request ahead of its first
|
||||
`didOpen` during staging (QA-3's trigger).
|
||||
|
||||
### 2026-11-19 — QA agent (Opus 5.5), round 2 (f1d4492 on dbb2349)
|
||||
|
||||
**Verdict: PASS WITH FINDINGS** (one Info-level note on the narrowed rule,
|
||||
pre-existing in kind; nothing new). Binaries: `qa717/bin2/new` (this tree),
|
||||
`qa717/bin2/base` (`git archive dbb2349`), `qa717/bin2/r1` (round 1's binary,
|
||||
for comparison). Caches untouched as in round 1.
|
||||
|
||||
**Baseline.** Full `tools/gates.sh` (logs `qa717/gates2/`): PASS every step
|
||||
including `cross`; `lucisv_server` 2 030/0 (dbb2349: 1 901 + 106 + 4 = 2 011 →
|
||||
1 920 + 106 + 4, +19 and +1 ignored), `vlog_semantic` 435, `lucisv_mcp` 384 (no
|
||||
guard kill this time), corpus 814/6, node 37. Ignored release runs 3/3 pass.
|
||||
P2's revert is a clean one: no `state/` file and no `sync.rs` in
|
||||
`git diff dbb2349`. `caret.rs`, `dispatch.rs`, `referencesView.js` and
|
||||
`caret_boundary.rs` are byte-identical to round 1.
|
||||
|
||||
**What the narrowed rule promises, stated as checked** (`must_hold`,
|
||||
`server/mod.rs`): (i) after settle every open buffer's text, and which buffers
|
||||
are open, equal the client's; (ii) non-cancel notifications are applied in the
|
||||
order sent, across documents — a notification is applied only when no older one
|
||||
is in `held` or in an enclosing burst's unapplied tail; (iii) every request is
|
||||
answered exactly once; (iv) a request is answered against the state after every
|
||||
notification sent before it, and possibly after some sent after it — so its
|
||||
answer reflects *some* client state between sending and answering, never one the
|
||||
client did not have (each `didChange` is applied whole, in one handler call).
|
||||
|
||||
**Ordering driver** (`drv/ord3.py`: round 1's driver with check (iv) — every
|
||||
documentSymbol answer must equal the expected symbols of the client's state at
|
||||
send or of some later state the client had sent before the answer arrived, each
|
||||
state recorded per message): corpus seeds 510–519 ×60 (workspace), 520–523 ×60
|
||||
(folder); full OpenTitan 530–533 ×40 (workspace), 540–541 ×40 (folder);
|
||||
incremental single/multi-change and full-sync changes, scans in flight as in
|
||||
round 1. **20 runs, 9 118 bursts (≈ 87 % mid-scan), 28 663 messages, 4 693
|
||||
state checks: 0 failures, 0 duplicate or missing responses, every fresh oracle
|
||||
equal; 13 answers reflected a later state than at send, each one a state the
|
||||
client had.** The same check fails at once on dbb2349 (seed 501: answers
|
||||
matching no client state, a buffer an edit behind). An earlier run of my
|
||||
coarser `ord2.py` (states recorded per burst, not per message) flagged one
|
||||
answer (seed 514) that matched no burst-final state; with per-message states the
|
||||
same seed ran clean three times — a driver limitation, recorded.
|
||||
|
||||
**Harm hunt** (`drv/harm2.py`, `GAP=0.2`, full OpenTitan, index not persisted so
|
||||
the rescan really interleaves; a request sent against v1 is held, then a
|
||||
`didChange` to v2 that inserts a line above it is applied mid-scan):
|
||||
|
||||
| request held, then v2 applied | dbb2349 | round 1 | now |
|
||||
|---|---|---|---|
|
||||
| rename of `beta` at its v1 position | answered on v2: renames **`alpha`** (the name now at that position); edit consistent with v2 | answered on v1; applied to the client's v2 it **corrupts** (`logic qqa;`, `alpqq`) | **as dbb2349** |
|
||||
| hover / definition / references | about `alpha`, v2 ranges | about `beta`, v1 ranges | as dbb2349 |
|
||||
| formatting | edits for v2, applied to v2 = v2's own formatting | same | same |
|
||||
| hover held, then `didClose` applied | `null` | answered from the open buffer | `null` |
|
||||
| documentSymbol(A) held, then `didClose A` + `didOpen A2` | `null` | from A | `null` |
|
||||
| documentSymbol(B) sent before `didOpen B` | B's buffer | `null` | B's buffer |
|
||||
| `[documentSymbol, change v2]` in one burst, then v3 | answered on **v3** (B) | v1 | v1 |
|
||||
|
||||
So the narrowing restores dbb2349's late-request behaviour exactly — no harm
|
||||
that base did not already have — and keeps B fixed (last row). Rename edits are
|
||||
unversioned (`changes` map; `extract.rs:185` sends `version: None`), so a client
|
||||
cannot reject a stale one by version; VS Code drops a rename or format result
|
||||
when the buffer changed while it waited (its editor-state cancellation), so the
|
||||
practical exposure is a client without that guard. **QA-8 (Info, pre-existing):**
|
||||
a held position-taking request can resolve a *different* symbol when a newer
|
||||
edit moved the text under its position — identical on dbb2349. Round 1's
|
||||
strict rule had the opposite trade (right symbol, ranges for text the client no
|
||||
longer had).
|
||||
|
||||
**Liveness** (`live717.py`, dbb2349 / now): cancel of a held request mid-rescan
|
||||
answered 0.58–0.62 / 0.55–0.60 s, honoured 5/5 / 5/5; shutdown behind a held
|
||||
hover + change answered 0.70 / 0.70 s, hover first, exit < 1 s (rc 1 in 2 of 3
|
||||
on both, as round 1); `exit` alone 0.8–1.6 s on both; server→client requests
|
||||
held by the client and answered mid-burst: no deadlock, final text right on
|
||||
both; 20 000-change flood (now): settle 27.7 s, RSS peak 680 MB, text right;
|
||||
typing through 5 rescans: scans 1.67–1.90 / 1.69–1.93 s, **text wrong on
|
||||
dbb2349, right now**; staging (QA-3): first hover 0.13–0.15 / 0.13–0.14 s —
|
||||
fixed (round 1 was 0.15–0.18 s).
|
||||
|
||||
**C** (`c717.py`, 26 opens in 13–14 `[request, didOpen×1–3]` bursts, cold full
|
||||
OpenTitan): scan ends 2.59–3.32 s, answers 0.02–3.32 s (5 seeds), 0 duplicates;
|
||||
round 1 2.8–4.2 s; dbb2349-class base 407 s; plain cold startup 1.51 s
|
||||
(dbb2349 1.51 s, now 1.53 s; warm 0.71 / 0.70 s). QA-4 as documented.
|
||||
|
||||
**P2 revert confirmed.** `lat717.py`: outside/excluded didOpen 0.41–0.72 ms,
|
||||
didClose 0.07–0.12 ms (dbb2349 0.37–0.79 / 0.06–0.13 ms); held files as base.
|
||||
`p2perf.py`: 2 000 outside open+close 0.6 s (dbb2349 0.7 s), RSS flat.
|
||||
`r2attack.py`: the same four divergent cases on both binaries
|
||||
(directory-create, held-directory-deleted, excluded-open-close closed and
|
||||
saved-then-closed); `outside.py` 14/14 equal on both, push and pull.
|
||||
|
||||
**A1** (code byte-identical): sample sweep 60 corpus files × 15 tokens, 7 830
|
||||
token×request pairs — end = start = middle everywhere, start and end+1 = base
|
||||
everywhere; `a1edge.py` all end = start; `a1rename.py` 9/9 identical.
|
||||
|
||||
**Oracle (no repair workaround):** `small.py` push and pull — only
|
||||
`NEGCTL-silent` diverges (both scopes); corpus push seed 7 ×200 — 0 divergent;
|
||||
full OpenTitan 21 ×50 — 0; OpenTitan sample 42 ×500 (`QA_FRESH_SAVE`) — 0.
|
||||
New: corpus seed 601 ×500 — 10 checks, 0 divergent; OpenTitan sample 602 ×500
|
||||
(`QA_FRESH_SAVE`, for QA-2's race) — 10 checks, 0 divergent.
|
||||
|
||||
**Findings this round:** QA-8 above (Info, pre-existing). Round 1's QA-1 and
|
||||
QA-3 are fixed, QA-4 documented, QA-5 reworded; QA-2, QA-6, QA-7 stand as
|
||||
written (pre-existing, outside this lane). **Fixed myself:** nothing. **Not
|
||||
verified:** a real VS Code (the Status items, and whether VS Code's editor-state
|
||||
cancellation really sends `$/cancelRequest` for a held rename).
|
||||
|
||||
## Review
|
||||
|
||||
**Lead, 2026-11-19.** Accepted for 0.65.8, after two QA rounds.
|
||||
|
||||
- The owner asked whether it was VS Code or the server. It was the server,
|
||||
and it was not a race: an end-exclusive span met a caret VS Code considers
|
||||
to be on the word. The investigation's deterministic reproduction
|
||||
(`refpos.py`, column 27) settled that before any code was written, and
|
||||
ruled out the things I would have guessed first — cancellation, deferred
|
||||
answers, caching.
|
||||
- B and C were found by other lanes' QA and are worse than the reported bug:
|
||||
one corrupts the server's copy of a buffer, the other turns a 2 s startup
|
||||
into minutes. Both come from treating queued messages as applied. I kept
|
||||
them in this lane because they live in the same loop.
|
||||
- I asked for P2 "only if small"; the dev's attempt cost 190 ms per open of
|
||||
an outside file and QA caught it (806 s for 2 000 files). Reverted. The
|
||||
right fix is in the index layer and is filed.
|
||||
- The ordering rule was narrowed in the fix round from "no message overtakes
|
||||
an older message" to "no notification overtakes an older notification".
|
||||
That changes the invariant, so I sent it back to QA instead of accepting
|
||||
the dev's own run. QA's harm table is what decides it: under the narrow
|
||||
rule a held request behaves exactly as on 0.65.7; under the broad rule a
|
||||
held rename was answered on the old text and would have corrupted the
|
||||
client's newer one. Narrow is both faster and safer.
|
||||
- Not verified: a real VS Code, in particular whether it drops a rename or
|
||||
format result when the buffer changed while the request was held (QA-8
|
||||
rests on that for its "Info" grade).
|
||||
@@ -0,0 +1,827 @@
|
||||
# viewport-highlight
|
||||
|
||||
## Goal
|
||||
|
||||
Semantic highlighting must never wait for the workspace index. The owner's
|
||||
words: *"Syntax highlight should always be running a localized-only version on
|
||||
the viewport if possible. This highlight might not be 100% correct, but can be
|
||||
later fixed. I don't want to wait for the whole database to be indexed before
|
||||
the basic syntax highlight works."* So: a semantic-token request (`range`,
|
||||
`full`, `full/delta`) for a buffer whose text is current is answered **from
|
||||
that buffer alone, immediately**, even while a scan holds every other request;
|
||||
a range answer costs the window, not the file; and when the index settles in a
|
||||
way that changes what a buffer's colours would be, the server sends **one**
|
||||
`workspace/semanticTokens/refresh` so the client re-requests and gets the
|
||||
accurate answer.
|
||||
|
||||
## Measured first (2026-11-19, before any code)
|
||||
|
||||
Real binary (`target/release/lucisv-server --stdio --verbose`, 0.65.5 at
|
||||
`80017a5`) over LSP stdio against the full OpenTitan checkout
|
||||
(`~/.cache/lucisv-opentitan-full`, 4 058 indexable files under `hw/`), replaying
|
||||
what VS Code does on open: `initialize` (VS Code's capabilities: configuration,
|
||||
work-done progress, `semanticTokens` range + full/delta, `refreshSupport`),
|
||||
`initialized`, the settings answer, `didOpen`, then at once
|
||||
`semanticTokens/full`, `documentSymbol`, `foldingRange`, `codeLens`, and
|
||||
100 ms later (the viewport contribution's debounce) `semanticTokens/range` for
|
||||
lines 0–120 and `inlayHint`. Cold = empty `storagePath`, warm = the same store
|
||||
reused. Medians of 5 runs; the machine is shared with other lanes. Time from
|
||||
`didOpen`; "first colour" is the earlier of the full and range answers.
|
||||
|
||||
| scope | file | cold first colour | warm first colour | mid-session rescan: tokens held |
|
||||
|---|---|---|---|---|
|
||||
| workspace | `spi_device_reg_top.sv` (545 KB) | **679 ms** | 400 ms | 650 ms |
|
||||
| workspace | `aes_cipher_core.sv` (small) | **677 ms** | 365 ms | 646 ms |
|
||||
| folder (default) | `spi_device_reg_top.sv` | 55 ms | 84 ms | 263 ms |
|
||||
| folder (default) | `aes_cipher_core.sv` | 24 ms | 50 ms | 245 ms |
|
||||
|
||||
**Where the time goes** (verbose trace of a cold workspace run): configuration
|
||||
round trip 1 ms; `didOpen` 1–16 ms (the buffer's own parse); discovery walk
|
||||
78 ms; then **every request is HELD** (`head_owed`) until the user's
|
||||
neighbourhood is indexed at ~650 ms, while the scan runs on to 1.6 s. Building
|
||||
the tokens themselves costs **0.3 ms** (small file) and **6.5 ms** (545 KB) —
|
||||
the token build was never the problem; waiting was. The range request was a
|
||||
whole-file build plus a filter (5.7 ms for 545 KB). The mid-session rescan (a
|
||||
watched-file *create* for a file the index does not hold, so a whole rescan)
|
||||
holds `full/delta` and `range` for its whole length.
|
||||
|
||||
**Stale forever.** The held `full` was answered off the head prefix and never
|
||||
refreshed: in folder scope **2 745 tokens** of `spi_device_reg_top.sv`
|
||||
(26 in workspace scope) stayed different from what the settled index says
|
||||
until the user edited the file.
|
||||
|
||||
**A `didOpen` that widens the scope** (folder scope, `aes_cipher_core.sv`
|
||||
open, then `hw/top_earlgrey/rtl/autogen/top_earlgrey.sv`): the new file's
|
||||
`full` waits for the whole widen, **336 ms** — `reindex_widened` drains
|
||||
nothing.
|
||||
|
||||
### What VS Code does — read from source, not memory
|
||||
|
||||
From the VS Code 1.145.2 bundle on this machine
|
||||
(`/Applications/Visual Studio Code.app/.../workbench.desktop.main.js`) and
|
||||
`[email protected]` (`lib/common/semanticTokens.js`, unpkg):
|
||||
|
||||
1. **The range provider is asked only while the document has no complete
|
||||
tokens.** `ViewportSemanticTokensContribution._tokenizeViewportNow` returns
|
||||
at once on `model.tokenization.hasCompleteSemanticTokens()`; any answer of
|
||||
the full provider (data, null, an empty delta) marks the model complete
|
||||
(`setSemanticTokens(…, true)`); an error does not. So range is only the
|
||||
*first paint*, until the first full answer lands.
|
||||
2. **Both are asked at open.** The document feature schedules its first
|
||||
fetch at `0` ms; the viewport contribution debounces 100–500 ms
|
||||
(adaptive) and asks for `getVisibleRangesPlusViewportAboveBelow()`. It
|
||||
re-asks on scroll, content change and on a range provider's `onDidChange`.
|
||||
3. **Only one full request in flight per model**; edits made while it is
|
||||
pending are applied to its result when it lands, and then it re-fetches.
|
||||
The result is therefore assumed to be for the text at *request* time. The
|
||||
range result is dropped outright if the model's version moved.
|
||||
4. **Debounce adapts to response time** (300 ms min, 2 s max for the full
|
||||
provider): a request held for seconds slows every later re-fetch of that
|
||||
model.
|
||||
5. **Refresh** (`workspace/semanticTokens/refresh`): the language client
|
||||
fires the shared `onDidChangeSemanticTokens` emitter of the **document**
|
||||
provider; the range provider gets no `onDidChange`. VS Code then re-fetches
|
||||
full/delta for every model attached to an editor (`handleProviderDidChange`
|
||||
→ `schedule(0)`, or after the in-flight request if one is pending).
|
||||
6. **Capabilities** `vscode-languageclient` advertises: `requests: { range:
|
||||
true, full: { delta: true } }`, `multilineTokenSupport: false`,
|
||||
`overlappingTokenSupport: false`, `serverCancelSupport: true`,
|
||||
`augmentsSyntaxTokens: true`, and `workspace.semanticTokens.refreshSupport:
|
||||
true`. It registers both providers whenever the server advertises both. **No
|
||||
extension configuration is needed** — `editors/vscode/extension.js` is
|
||||
unchanged.
|
||||
|
||||
**What this decides.** VS Code does *not* use range only for "large"
|
||||
documents — it uses it for every document, but only until the full answer
|
||||
lands. So answering only `range` early would still leave the first full
|
||||
answer — the one that makes the model complete and stops all range requests —
|
||||
held behind the scan, and a held full also raises the adaptive debounce. The
|
||||
full request has to be answered early too, and the refresh is what reaches the
|
||||
full provider afterwards (it never reaches the range provider).
|
||||
|
||||
## Assumptions
|
||||
|
||||
- A buffer's `Document` (text, line index, tokens, tree, `Semantics`, overlay)
|
||||
is only ever replaced wholesale or refreshed in place between two messages,
|
||||
never left half-written when control returns to the loop. True today: the
|
||||
loop is one thread and the scan publishes (`publish_scan`, `finish_scan`)
|
||||
only between files.
|
||||
- The index's overlay on a buffer (`ExternalResolutions`) only ever grows more
|
||||
right during a scan: `publish_scan` absorbs records, it never takes the old
|
||||
index away mid-rescan (`state/rescan.rs`), so an answer off it is a coherent
|
||||
guess, never a regression to "nothing resolves".
|
||||
- `Server::hierarchy_revision` is bumped by every index mutation
|
||||
(`hierarchy_index_changed` in `reindex`, `reindex_one`, `reindex_widened` and
|
||||
the startup). The refresh decision keys off it.
|
||||
- A text-changing notification about a buffer carries that buffer in
|
||||
`textDocument.uri` (`didOpen`, `didChange`, `didClose`, `didSave`).
|
||||
- VS Code facts as quoted above; other clients may ask for range and full in
|
||||
any mix — every answer is valid on its own whatever the mix.
|
||||
|
||||
## Design
|
||||
|
||||
**One exemption from the order contract, taken where requests are held.**
|
||||
`process_batch` holds a message when `must_hold` says so (for a request:
|
||||
`must_wait`); just before that, a semantic-token request is offered to
|
||||
`answer_from_the_buffer` (`server/viewport.rs`). It is answered there and
|
||||
then — and so is any colouring request behind a held one in the same burst
|
||||
(`set_aside`) — when its buffer's text is **current**: the text the server
|
||||
holds is exactly what the client had sent for that document when it asked,
|
||||
i.e. no `didOpen`/`didChange`/`didClose` for it is queued unapplied.
|
||||
|
||||
**Rebuilt on the loop's own bookkeeping (2026-11-19, on 0.65.8).** Lane 71.7
|
||||
(`docs/features/scan-ordering/README.md`) made the loop keep exactly the
|
||||
fact this needs: a message older than the one being handled is either
|
||||
applied or (a) in `held`, or (b) in the tail of the burst whose message
|
||||
started the scan now draining, counted by `Server::behind` — the clause
|
||||
`must_hold` uses so that no notification overtakes an older one. The
|
||||
exemption reads the same two places, plus the two that are its own:
|
||||
|
||||
1. `held` — a notification naming the buffer there means its text is behind;
|
||||
2. `Server::behind > 0` — an unapplied older notification exists; it is a
|
||||
count and names no buffer, so it is taken to name this one (conservative:
|
||||
the request is then held exactly as before);
|
||||
3. `ahead` — the part of the request's own burst being set aside in front of
|
||||
it, not yet in `held`;
|
||||
4. `dirty` — a `didChange` applied to the text but not analyzed.
|
||||
|
||||
The first version kept its own stack of "buffers still behind this message"
|
||||
lists (`Viewport::behind`, `enter`/`leave`, `handle_before`); it overlapped
|
||||
`behind`/`must_hold` and is deleted. What that costs: a colouring request
|
||||
inside a scan that a notification started, while that notification's burst
|
||||
still has *any* unapplied notification, now waits — the old stack let it
|
||||
through when none of them named its buffer. That shape is a mid-session
|
||||
rescan with a second notification in the same write; it was not in any
|
||||
measured scenario.
|
||||
|
||||
**Clients without `refreshSupport` get early `range` only** (QA Q3). An early
|
||||
whole answer is cross-file-blind and only the refresh corrects it; a client
|
||||
that cannot be refreshed would keep it until its next edit, which is worse
|
||||
than waiting. So for such a client `full`/`full/delta` wait as they always
|
||||
did, and early `range` answers (painted over by the first `full`) still go.
|
||||
|
||||
**A widen drains** (QA Q2). In folder scope — the default — a `didOpen` after
|
||||
the settings answer, or any open in a folder not yet indexed, widens the
|
||||
scope, and `reindex_widened` used to drain nothing: ~650 ms with no colour.
|
||||
Now:
|
||||
|
||||
- `process_batch` hands a `didOpen` to `open_then_widen` with the rest of its
|
||||
burst. The `didOpen` is applied as always; a widen it asks for is recorded
|
||||
(`Viewport::defers_widen`) instead of run. Then the colouring requests in
|
||||
the rest of the burst are answered from their buffers — the just-opened one
|
||||
is applied, so VS Code's `full` in the same write colours at once — and the
|
||||
widen runs; the rest of the burst then proceeds exactly as before.
|
||||
- Between two of the widen's files, `answer_colours_mid_widen` drains the
|
||||
queue: colouring requests that can be are answered, everything else goes to
|
||||
`held` in arrival order (and `hold` splices the burst's own tail in front of
|
||||
it, as for a scan that holds).
|
||||
- `Viewport::widening` is set for the widen's length, so a range answered
|
||||
then is owed the refresh, and the widen's revision bump triggers it.
|
||||
|
||||
Within 71.7's invariants: the widen is still the effect of the one applied
|
||||
`didOpen` (only applied messages change scan state); nothing drained during a
|
||||
widen is applied during it (it is held), so no notification overtakes an
|
||||
older one; and while the burst's tail holds a notification, `behind > 0`
|
||||
makes every drained colouring request wait.
|
||||
|
||||
**What the exempted handler reads** — the ordinary dispatch arm for the
|
||||
method, run through `answer_flushed` (the dispatch *without*
|
||||
`flush_dirty`):
|
||||
|
||||
- the one `Document` the request names (text, line index, tokens, tree,
|
||||
`Semantics`, the `ExternalResolutions` overlay);
|
||||
- `Workspace::has_large_documents`, `Document::large`,
|
||||
`ClientAbilities::token_server_cancel` (the large-file decline);
|
||||
- `Server::tokens`/`token_results` (the remembered answer and its id).
|
||||
|
||||
Never the workspace index, never another buffer, never a flush or a publish.
|
||||
**Why that is valid mid-scan:** a request is only ever answered "during" a
|
||||
scan by being reached from inside it — the startup's configuration wait
|
||||
(`await_configuration`/`await_opening_file`), a scan's between-files drain
|
||||
(`answer_what_is_waiting`), both through `process_batch`, or a widen's
|
||||
between-files drain (`answer_colours_mid_widen`) — so the scan is between two
|
||||
files, the buffer's state is whole, and its overlay is the index's answer as
|
||||
of the last publish.
|
||||
|
||||
**A dirty buffer waits.** Answering it would need its analysis, i.e. a parse
|
||||
of the newest text — and either the index (forbidden) or a cross-file-blind
|
||||
re-analysis, which would flip every package type, imported enum and
|
||||
parameter to `variable` on each keystroke during a rescan and back at the end
|
||||
(right → wrong → right). Holding is the honest choice: VS Code keeps the
|
||||
colours it has (it shifts them through the edit), only text typed during the
|
||||
rescan waits for colour, and the rescan hold is now 70–156 ms (below; QA
|
||||
round 2's figure on the final binary).
|
||||
|
||||
**`full`/`full/delta` before the index is ready: answered locally, now** — for a client with `refreshSupport` (see above for one without).
|
||||
From the VS Code facts: the first full answer is the one that completes the
|
||||
model and ends range requests, so holding it holds the colours that matter;
|
||||
answering it early gives the whole file colour (scrolling needs no range
|
||||
round trips), keeps the adaptive debounce short, and costs one refresh later.
|
||||
The sequence the user sees is **local → accurate**, once: the overlay only
|
||||
grows during a scan, and the refresh decision is taken once, at settle — never
|
||||
at intermediate publishes, so there is no wrong → right → wrong. Once the
|
||||
index is ready, nothing is exempt (`must_wait` is false) and full/delta are
|
||||
exactly what they were.
|
||||
|
||||
**Delta consistency.** Every full/delta answer, local or accurate, goes
|
||||
through `remember_tokens`, which stamps a fresh `resultId` and keeps *that*
|
||||
data as the delta base. A client's `previousResultId` therefore always names
|
||||
the exact data it holds, whichever kind of answer that was; a mismatched id is
|
||||
answered with a full set, as before.
|
||||
|
||||
**The range answer costs the window** (`tokens::semantic_tokens_in_range`).
|
||||
The range is snapped to whole lines (`large::line_window`, the uncapped half of
|
||||
the large-file window's `bounds`), the tokens touching those lines plus one
|
||||
neighbour each side (for the comments that hang off them, the EOF token's
|
||||
included) are classified, and the instantiation-override AST walk visits only
|
||||
items overlapping the window (`instantiation::overrides_within`). The answer is
|
||||
still exactly the full answer filtered to the range. A buffer over the
|
||||
large-file threshold keeps its lexer-only window (`large::window`, with its
|
||||
block-comment back-scan) and its `full` decline, unchanged; the large window
|
||||
was generalised (`line_window`) rather than duplicated. What "local" uses: the
|
||||
lexer always (a large buffer's window lexes on demand); the buffer's own
|
||||
parse/semantics, which every non-large buffer already has for its current
|
||||
version (`didOpen` parses; the 4 MiB large-file threshold is the measured line
|
||||
above which nothing parses — `docs/features/large-file-mode`); the overlay as
|
||||
of the last publish; never the index.
|
||||
|
||||
**Refresh** (`refresh_tokens_if_stale`, called by `run` once `held` is empty,
|
||||
before it blocks for the next message). At most once per index revision: if
|
||||
`hierarchy_revision` moved since the last decision and nothing must wait, the
|
||||
open, non-large, non-dirty buffers whose last answer was taken off an
|
||||
**unsettled** index (a scan running or owed, or a widen running —
|
||||
`Server::index_unsettled`) are checked: a remembered whole answer
|
||||
(`Viewport::early`) is compared with a fresh classification, and a buffer last
|
||||
painted by a range answer (`Viewport::guessed`) counts as stale. Any stale
|
||||
buffer → one `workspace/semanticTokens/refresh`, gated on
|
||||
`workspace.semanticTokens.refreshSupport`; both sets are then cleared. An
|
||||
answer given once the index had settled is not checked again (QA Q6: checking
|
||||
every open buffer on every index change cost 13 ms per save with 200 open).
|
||||
**Cost:** one token build per buffer answered while unsettled, once (0.3–7 ms
|
||||
each on OpenTitan; 12.9 ms for 200 buffers opened at startup); on the client
|
||||
side, one `full/delta` per editor-attached model, which the prefix/suffix
|
||||
trim keeps to the tokens that changed. This also fixes the old "stale
|
||||
forever": a full answered off the head prefix mid-scan is unsettled, and so
|
||||
compared at settle like any early answer. What it does not do: a later edit
|
||||
in one file that changes another open file's colours (a package type
|
||||
renamed) refreshes nothing — exactly as before this lane.
|
||||
|
||||
## Results
|
||||
|
||||
### Fix round, on 0.65.8 (2026-11-19, QA's harness, medians of 5)
|
||||
|
||||
QA's driver (`qa713/drv/meas.py`, copied with its tree to the dev scratch
|
||||
dir), on a **copy** of OpenTitan `hw/` with every store under the scratch
|
||||
dir. "before" is master 0.65.8 (`934d472`, built from `git archive` with its
|
||||
own target dir); "after" is this lane. ms from `didOpen`; *late open* = the
|
||||
`didOpen` arrives 30 ms after `initialized`, i.e. after the settings answer —
|
||||
the ordering QA's Q2 is about. Rescan hold = a watcher *create* (whole
|
||||
rescan) with a `full/delta` and a `range` sent 5 ms after it.
|
||||
|
||||
| scope / file | cold first colour | warm | **late open, cold** | rescan hold | refresh lands (cold / warm) |
|
||||
|---|---|---|---|---|---|
|
||||
| workspace / aes_cipher_core | 700 → **3.5** | 384 → **3.5** | 631 → **64** | 778 → **120** | 1 614 / 827 |
|
||||
| workspace / spi_device_reg_top | 680 → **39** | 401 → **39** | 668 → **89** | 758 → **156** | 1 647 / 877 |
|
||||
| folder / aes_cipher_core | 39 → **3.3** | 66 → **3.3** | 614 → **2.4** | 325 → **70** | 638 / 352 |
|
||||
| folder / spi_device_reg_top | 71 → **38** | 100 → **38** | 643 → **32** | 341 → **87** | 680 / 352 |
|
||||
|
||||
Exactly one refresh in every "after" run (5/5 in every row), none in any
|
||||
"before" run. **Opening a file in a folder not yet indexed, mid-session**
|
||||
(folder scope, `aes_cipher_core.sv` settled, then `top_earlgrey.sv`): the new
|
||||
buffer's `full` **350 → 3 ms** (5 runs each: 357/350/350/351/351 →
|
||||
2.9/2.7/3.2/3.2/3.1).
|
||||
|
||||
**What remains, and why.** The 32–39 ms on `spi_device_reg_top.sv` is that
|
||||
buffer's own parse at `didOpen` (16 ms) plus the token build (6.5 ms) — the
|
||||
floor for a 545 KB file. The 64–89 ms of a late open in **workspace** scope is
|
||||
the startup scan's discovery walk (~80 ms on OpenTitan), which drains nothing
|
||||
(Handshake request 2, left documented). The rescan hold is the same walk at
|
||||
the front of the rescan. A second file opened in the same write as a
|
||||
request that is held during the startup's head phase colours at the head
|
||||
(~650 ms): the tail of a burst behind a held request is held whole by
|
||||
`process_batch` (71.7's rule), so its `didOpen` is not applied yet and its
|
||||
buffer has no text to colour from — the exemption correctly refuses it
|
||||
(QA's `livelock2.py hover`: `full(B)` at 658 ms, answered "from the buffer"
|
||||
the moment the `didOpen` is applied).
|
||||
|
||||
**Refresh check cost (QA Q6)**, verbose timing line, OpenTitan, buffers
|
||||
opened at startup and each sent a `full`, then five saves that each change
|
||||
the index (a module appended): before restricting, every index change
|
||||
re-tokenized every open buffer — **1.4–2.3 ms with 50 buffers (227 KiB),
|
||||
12.7–14.2 ms with 200 (2 MiB), per save**. Restricted to buffers whose last
|
||||
answer was taken off an unsettled index (`Viewport::early`/`guessed`): the
|
||||
one post-startup check is unchanged (1.4 ms / 12.9 ms — those buffers were
|
||||
answered mid-scan and are genuinely owed it), every later save **0.00 ms**.
|
||||
|
||||
### First round, on 0.65.5 (dev harness; superseded by the table above)
|
||||
|
||||
| scope | file | first colour cold: before → after | warm: before → after | rescan hold: before → after | refresh lands (cold / warm) | tokens recoloured by it |
|
||||
|---|---|---|---|---|---|---|
|
||||
| workspace | `spi_device_reg_top.sv` | 679 → **111 ms** | 400 → **174 ms** | 650 → **112 ms** | 1 594 / 779 ms | 2 771 |
|
||||
| workspace | `aes_cipher_core.sv` | 677 → **1.8 ms** | 365 → **1.8 ms** | 646 → **99 ms** | 1 568 / 729 ms | 114 |
|
||||
| folder | `spi_device_reg_top.sv` | 55 → 54 ms | 84 → 80 ms | 263 → **39 ms** | 648 / 307 ms | 2 745 |
|
||||
| folder | `aes_cipher_core.sv` | 24 → 26 ms | 50 → **2.0 ms** | 245 → **20 ms** | 611 / 309 ms | 114 |
|
||||
|
||||
In every run the refreshed answer was **identical** to a `full` asked after
|
||||
the scan had settled. (These runs passed a relative store path to a server
|
||||
whose cwd was the OpenTitan checkout, and so wrote forty stores into it —
|
||||
QA Q5; the fix round's numbers do not.)
|
||||
|
||||
## Correctness on real code
|
||||
|
||||
`tokens::viewport_sweep` (ignored; `tools/guard.sh -- cargo test --release -p
|
||||
lucisv_server viewport_sweep -- --ignored --nocapture`): all 860 corpus files
|
||||
and every 10th OpenTitan `hw` file (407), six windows each (five 60-line
|
||||
viewports, one mid-line), **7 602 windows**. The local answer is the buffer
|
||||
analyzed against an **empty** index (the cold start); the accurate one is the
|
||||
same text analyzed against its whole tree's index.
|
||||
|
||||
- **Valid, every window:** sorted, non-overlapping, non-empty, inside the
|
||||
range, never past its line's end, never a non-comment token inside a
|
||||
comment, never a non-string token inside a string — for the analyzed path
|
||||
and for the large-file lexer window on the same windows.
|
||||
- **Exact:** the window answer equals the full answer filtered to the range on
|
||||
every window (the windowing loses nothing).
|
||||
- **Agreement with the accurate answer:** 559 725 accurate tokens, **541 616
|
||||
agree (96.77 %)**, **18 109 disagree, and 0 "other"** — every disagreement
|
||||
is a name the accurate buffer resolves *through the index*: almost all to
|
||||
another file (package types, imported parameters and enum members,
|
||||
cross-file modules), but not all. QA's own checker (Q4) found 7 of 1 501
|
||||
that resolve to the **same** file — inherited class methods
|
||||
(`core_ibex_test_lib.sv:1101`, `stress_debug()` through `extends`), whose
|
||||
resolution goes through the index's class hierarchy even though the
|
||||
declaration is local. My sweep classifies by "the resolution is
|
||||
`Definition::External`", which those are, so it counted them as
|
||||
"cross-file"; the accurate word is *index-resolved*. All of them are
|
||||
exactly the colours the refresh replaces.
|
||||
|
||||
Mutation checks: dropping the "one token after the window" neighbour fails the
|
||||
sweep's exactness assertion; restoring the whole-file build fails
|
||||
`a_viewport_costs_the_window_not_the_file` (8.6× for 8× the file). Dropping the
|
||||
"one token before" neighbour is caught by no real file (no trailing multi-line
|
||||
comment reaches across a viewport edge in the corpus); it is kept because the
|
||||
trivia model allows the shape, and `window_tests` pin the comment shapes.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed:**
|
||||
- `Server::must_hold`/`must_wait`, `held`, `behind` (lane 71.7's count of
|
||||
unapplied notifications around a scan's trigger), `dirty`, `scanning`,
|
||||
`staging` (read-only) and `hierarchy_revision` (read-only, as "the index
|
||||
moved").
|
||||
- `reindex_widened` (`server/index.rs`, now this lane's to touch): it defers
|
||||
itself inside `open_then_widen`, drains colours between files, and sets
|
||||
`Viewport::widening`.
|
||||
- `Workspace::document`, `open_documents`; `Document` fields; `large::window`.
|
||||
- The dispatch arms for the three token methods, via `answer_flushed`
|
||||
(`answer_request` minus `flush_dirty`, a pure split).
|
||||
|
||||
**Promised:**
|
||||
- `ClientAbilities::semantic_tokens_refresh` (new field, read in `main.rs`).
|
||||
- `tokens::semantic_tokens_in_range` answers exactly what it did, at window
|
||||
cost; `large::line_window` is new and public to the crate.
|
||||
- A request answered ahead of held ones is a response sent out of arrival
|
||||
order — allowed by the spec, and only ever for the three colouring methods.
|
||||
|
||||
**Touched outside the first round's scope:** `server/startup.rs`, one line —
|
||||
`viewport: Default::default()` in `Server::empty`, because a `Server` field
|
||||
cannot exist without its initializer; `server/index.rs` (fix round, by the
|
||||
lead's ruling once the re-index lane had merged) for the widen.
|
||||
|
||||
**Requests.**
|
||||
|
||||
1. *Colours during a widen* — **done in this lane** (2026-11-19, after the
|
||||
re-index lane merged and `server/index.rs` became this lane's): the drain
|
||||
and the before-the-widen answers above. The original request missed the
|
||||
same-burst `full`; `open_then_widen` is what reaches it.
|
||||
2. *Drain during discovery* — **left documented.** The startup scan and every
|
||||
whole rescan begin with a discovery walk (25–80 ms on OpenTitan) that
|
||||
drains nothing; it is now the largest share of the cold first colour in
|
||||
workspace scope and of the rescan hold. It is not small: the walk runs in
|
||||
`state/discover.rs` with the `Workspace` borrowed mutably throughout
|
||||
(`first_scope` inside `begin_scan`), and answering a request needs the
|
||||
`Server` and a shared borrow of that same `Workspace`. A drain point means
|
||||
splitting the walk into resumable steps the way `scan_step` splits the
|
||||
indexing — a change to the scan's structure whose identical-result proof
|
||||
is a lane of its own, not a hook.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Step 1: measure cold/warm/rescan/widen on OpenTitan over LSP; VS Code
|
||||
client facts from source.
|
||||
- [x] Range answer at window cost, exactly the full answer filtered
|
||||
(`tokens.rs`, `tokens/instantiation.rs`, `large.rs`).
|
||||
- [x] Exemption from `must_wait` for the three colouring methods on a
|
||||
text-current buffer, without `flush_dirty` (`server/viewport.rs`,
|
||||
`server/mod.rs`, `server/dispatch.rs`).
|
||||
- [x] `workspace/semanticTokens/refresh`, coalesced per index revision, only
|
||||
when a token would change, gated on `refreshSupport` (`main.rs`,
|
||||
`server/viewport.rs`, hook in `run`).
|
||||
- [x] Tests: `server/viewport/tests.rs` (16 tests, incl. a staged cold
|
||||
start coloured at once and sharpened by one refresh, the widen's
|
||||
same-burst and mid-widen answers, and a client without
|
||||
`refreshSupport`),
|
||||
`tokens/window_tests.rs`, `tokens/viewport_sweep.rs` (ignored sweep).
|
||||
- [x] Before/after numbers (this README, `docs/perf/README.md`).
|
||||
- [x] Widen drain and before-the-widen answers (QA Q2).
|
||||
- [x] No early whole answers for a client without `refreshSupport` (QA Q3).
|
||||
- [ ] Discovery drain — Handshake request 2, documented, not done.
|
||||
- [ ] A dirty buffer during a rescan still waits (deliberate; see Design).
|
||||
- [ ] Not verifiable here: a running VS Code. What a human should watch: open
|
||||
a big file (`spi_device_reg_top.sv`) on a cold start with
|
||||
`lucisv.index.scope: workspace` — module names, parameters, ports and
|
||||
instance names colour at once; package types / imported names sharpen
|
||||
once when the indexing bar ends; no flicker back to plain. Type during a
|
||||
rescan (save a file in another folder): existing colours stay, new text
|
||||
takes colour when the bar ends.
|
||||
|
||||
## Work log
|
||||
|
||||
- **2026-11-19 (dev).** Measured first (above). Design decided from the VS
|
||||
Code source: answer full early as well as range, refresh once at settle.
|
||||
`semantic_tokens_in_range` re-implemented at window cost (token slice + one
|
||||
neighbour each side; item-filtered override walk; `large::line_window` split
|
||||
out of `bounds`). `answer_request` split into flush + `answer_flushed`.
|
||||
`server/viewport.rs`: the exemption (`answer_from_the_buffer`,
|
||||
`answered_ahead`, `set_aside`, `handle_before` with the `behind` frames),
|
||||
and `refresh_tokens_if_stale`. First cut only looked at the request at the
|
||||
head of a held burst; the server tests showed a colouring request *behind* a
|
||||
held hover in the same burst was still held — fixed with `set_aside`, which
|
||||
also needed the `ahead` slice in the currency check. `process_batch` grew
|
||||
77 → 86 lines (most of the growth is comments; the logic moved into
|
||||
`viewport.rs` helpers). Production lines: `tokens.rs` 267 → 288,
|
||||
`tokens/instantiation.rs` 278 → 290, `large.rs` 195 → 199,
|
||||
`server/viewport.rs` 0 → 169, `server/mod.rs` 186 → 216,
|
||||
`server/dispatch.rs` 486 → 489, `server/semantic_tokens.rs` 34 → 35,
|
||||
`server/startup.rs` 171 → 172, `main.rs` 377 → 387.
|
||||
|
||||
- **2026-11-19 (dev, fix round on 0.65.8).** Re-applied onto master 0.65.8
|
||||
(lead). Resolved the two `process_batch` conflict hunks by keeping 71.7's
|
||||
`must_hold`/`hold` structure and putting the exemption in front of the
|
||||
hold (`answered_ahead`, then `set_aside` for the rest of the burst, then
|
||||
`hold`). Deleted as redundant with `Server::behind`/`must_hold`:
|
||||
`Viewport::behind`, `enter`, `leave`, `owes` and `Server::handle_before`
|
||||
(master's plain notification/response arms are back); the currency check
|
||||
now reads `self.behind == 0` instead of its own per-buffer frames (the
|
||||
trade is in Design). QA Q2: `open_then_widen` (a `didOpen` arm in
|
||||
`process_batch`, 5 lines; the function is 74 lines) answers the burst's
|
||||
colouring requests before the widen, `reindex_widened` records a deferred
|
||||
widen (`Viewport::defers_widen`), drains between files
|
||||
(`answer_colours_mid_widen`) and sets `Viewport::widening`. QA Q3: early
|
||||
`full`/`full/delta` only for a client with `refreshSupport`. QA Q4: README
|
||||
corrected (index-resolved, not "cross-file"; the test count stated as it is).
|
||||
QA Q5: my harness passed a *relative* store path to a server whose cwd was
|
||||
the OpenTitan checkout, which is how forty stores landed there; this
|
||||
round measures on a copy under the scratch dir with absolute store paths.
|
||||
Handshake 2 (discovery drain) assessed and left documented (reason under
|
||||
Handshakes). QA Q6: measured 1.4–2.3 ms (50 buffers) and 12.7–14.2 ms
|
||||
(200) per index-changing save; restricted the check to answers taken off
|
||||
an unsettled index (`Viewport::early`), after which a later save costs
|
||||
0.00 ms. To keep `process_batch` under 80 lines (78) the notification arm
|
||||
calls `apply_in_burst`, which routes a `didOpen` to `open_then_widen`. Q1
|
||||
re-checked with QA's and 71.7's drivers: the startup scan settles in
|
||||
1.6–2.6 s with one progress cycle. Production lines (vs 0.65.8):
|
||||
`tokens.rs` 267 → 288, `tokens/instantiation.rs` 278 → 290, `large.rs`
|
||||
195 → 199, `server/viewport.rs` 0 → 208, `server/mod.rs` 215 → 224,
|
||||
`server/dispatch.rs` 491 → 494, `server/semantic_tokens.rs` 34 → 36,
|
||||
`server/startup.rs` 173 → 174, `server/index.rs` 267 → 276, `main.rs`
|
||||
378 → 388. Tests: `server/viewport/tests.rs` 16, `tokens/window_tests.rs`
|
||||
6, `tokens/viewport_sweep.rs` 1 (ignored).
|
||||
|
||||
## Changelog paragraph (for the lead)
|
||||
|
||||
Semantic highlighting no longer waits for indexing. A colouring request for a
|
||||
buffer whose text is current is answered from that buffer alone even while a
|
||||
scan or a widen holds every other request: on OpenTitan the first colours of
|
||||
a newly opened file arrive in 2–39 ms instead of 600–700 ms (cold start in
|
||||
either scope, opening a file in a folder not indexed yet), and a mid-session
|
||||
rescan holds them 70–156 ms instead of 325–778 ms. Names resolved through the
|
||||
index are coloured as local guesses until it settles; then the server sends
|
||||
one `workspace/semanticTokens/refresh` and the client's next answer is the
|
||||
accurate one (this also fixes colours that used to stay stale until the next
|
||||
edit). A client that cannot be refreshed gets early viewport colours only.
|
||||
Viewport (`range`) answers now cost the visible lines, not the file.
|
||||
|
||||
## QA log
|
||||
|
||||
- **2026-11-19 (QA, Opus 5.5).** Verdict **PASS WITH FINDINGS**. No corrupted
|
||||
or stale-unrecoverable token state, no duplicated response, no invalid
|
||||
encoding and no read of unsafe state found. The findings are one
|
||||
pre-existing scan livelock (Q1), a widen gap that leaves the default scope's
|
||||
common ordering where it was (Q2), and some smaller ones. The harness
|
||||
(Python LSP driver against the real release binaries, its own delta
|
||||
reconstruction and validity checker, nothing shared with the dev's sweep)
|
||||
is in the QA scratchpad (`qa713/drv/`).
|
||||
|
||||
**Baseline.** `tools/gates.sh`: all steps pass (fmt, clippy, build, every
|
||||
suite with lucisv_server at 2014/0, docs, corpus 814/6 as usual, node
|
||||
37/0). Ignored `viewport_sweep` in release: 1267 files, 7 602 windows, 96.765 %
|
||||
agree, 18 109 index-resolved, 0 other, which reproduces the dev's numbers. The
|
||||
`#[test]` count went from 5 433 to 5 452 (+19, the new files only). No
|
||||
existing test or assertion was removed or edited. None of the off-limits
|
||||
files differ from `80017a5`. `process_batch` is 86 lines, in the
|
||||
"investigate" band. It has no reason comment, but it reads top to bottom
|
||||
and the new logic lives in `viewport.rs` helpers. Acceptable.
|
||||
|
||||
**Safety review** (`viewport.rs`, `process_batch`, `answer_flushed`,
|
||||
`large_file_answer`, the three dispatch arms, `semantic_tokens.rs`,
|
||||
`tokens.rs` window code). The exempt path reads only these: the named
|
||||
`Document` (via `workspace.document`), `has_large_documents` and `doc.large`,
|
||||
`abilities.token_server_cancel`, `self.tokens` and `token_results`, `held`,
|
||||
`dirty`, `viewport.behind`, `scanning` and `staging`. It writes only
|
||||
`self.tokens`, `token_results` and `viewport.guessed`. None of that is
|
||||
half-written between two scan files. Scans start only from notification
|
||||
and response handlers (every `reindex*` caller is in `notification.rs` or
|
||||
the settings response), so the `behind` frames cover every outer burst. The
|
||||
`didChange`/cancel skip is sound. Documents are keyed by exact `Uri`, so a
|
||||
different spelling is a different document before and after the change;
|
||||
the exemption adds no new hole. Mid-scan `didClose`+`didOpen` in one
|
||||
burst answers from the new text. A never-opened document waits and gets
|
||||
`null` at settle.
|
||||
|
||||
**Scenarios on a full OpenTitan `hw/` copy** (workspace scope unless
|
||||
noted). Every answer was validated: 5-tuples, sorted, non-overlapping,
|
||||
UTF-16 widths, inside the legend, inside the range. The client array was
|
||||
rebuilt by applying deltas per spec and compared with a `full` from the
|
||||
same server and from a fresh server.
|
||||
|
||||
| scenario | result |
|
||||
|---|---|
|
||||
| cold start; open small, then big, then a third file mid-scan; type plus delta mid-scan | valid; 1 refresh; client equals the same server's full and a fresh server's full for all 3 |
|
||||
| warm start, same flow | same; 1 refresh |
|
||||
| folder scope, same flow | same; 0 or 1 refresh depending on ordering (Q2) |
|
||||
| client without refreshSupport | 0 refreshes ever; client keeps early colours (Q3) |
|
||||
| after settle: 20 keystrokes each followed by a delta; save after edits; no-op save; unrelated file and a dependency changed on disk | **0 refreshes** each (no storm) |
|
||||
| watcher *create* (whole rescan); range plus delta at once; hover; `full(B)` then `didClose(B)`; typing during the rescan | range/delta answered at 133 ms, hover held to 772 ms, typed delta held (dirty, by design), closed file's full answered once; 0 extra refreshes; client equals full |
|
||||
| `didChangeConfiguration` mid-scan | valid; client equals full |
|
||||
| cancel of a held token request, cancel in the same burst as an exempt request, delta against unknown id `999999`, `didClose`+`didOpen`+`full` in one burst, `full` for a never-opened document | -32800, -32800, full set, data for the new text, `null` at settle: one answer each |
|
||||
| two documents with interleaved edits and deltas while unsettled | client equals full for both |
|
||||
| 4.5 MiB generated buffer | full and delta declined -32802, range is the lexer window (640 ints, valid) |
|
||||
| alternative URI spelling (`%5F`) `didChange` | answers for the real URI unchanged (pre-existing phantom document for the other spelling) |
|
||||
|
||||
**Accuracy, own checker** (settings answer withheld so the index is
|
||||
*empty*; my own comment/string scanner; disagreements classified with a
|
||||
real `textDocument/definition` after settle). 1 678 windows: 992 corpus
|
||||
windows over 80 files and 686 OpenTitan windows over 60 files. Edge
|
||||
windows included: inside a block comment, macro continuation,
|
||||
`` `ifdef``, `(* *)`, instantiation edge, file start, past EOF, mid-line
|
||||
columns, empty, reversed, beyond EOF, one line with column 9999.
|
||||
Results:
|
||||
- early and settled answers: **0 invalid**;
|
||||
- settled window equals the full filtered to the range: **1 678/1 678**;
|
||||
- early vs settled: 43 070 agree, 1 501 disagree;
|
||||
- 1 494 of the disagreements resolve cross-file;
|
||||
- **7 resolve to the same file** (Q4).
|
||||
|
||||
The checker flagged 10 comment and 428 string hits. All are tokens of a
|
||||
`` `define``/`` `include``/macro-call directive whose text contains `//`
|
||||
or a string (for example `kmac_test_vectors_kmac_vseq.sv:31`,
|
||||
`dma_longer_transfer_vseq.sv:43`). The settled and base answers say the
|
||||
same, so this is a pre-existing directive classification, not an early-answer
|
||||
issue.
|
||||
|
||||
**Measured** (medians of 5, ms from `didOpen`, machine shared, load
|
||||
around 20). 80017a5 is built from `git archive` with its own target dir.
|
||||
"late open" means the `didOpen` arrives 30 ms after `initialized`, i.e.
|
||||
after the settings answer.
|
||||
|
||||
| scope / file | cold first colour before → after | warm before → after | late-open cold before → after | rescan hold before → after | refresh lands cold / warm |
|
||||
|---|---|---|---|---|---|
|
||||
| ws / aes_cipher_core | 716 → **2.2** | 384 → **2.2** | 669 → 68 | 769 → **127** | 1 706 / 865 |
|
||||
| ws / spi_device_reg_top | 736 → **39** | 433 → **36** | 687 → 99 | 781 → **163** | 1 673 / 945 |
|
||||
| folder / aes_cipher_core | 35 → **2.1** | 62 → **3.3** | 650 → **627** | 327 → **70** | 659 / 310 |
|
||||
| folder / spi_device_reg_top | 75 → **38** | 101 → **38** | 645 → **650** | 340 → **86** | 683 / 349 |
|
||||
|
||||
Exactly one refresh in every run that answered early; none in the
|
||||
late-open folder runs, which never answered early.
|
||||
|
||||
**Findings.**
|
||||
- **Q1 (HIGH, pre-existing in `80017a5`, `server/index.rs`
|
||||
`answer_what_is_waiting` — not this lane's file).** A `didOpen` set
|
||||
aside behind a held request makes `opened` true at every later
|
||||
interleave. So `head_owed` is set again, the whole held burst is held
|
||||
again, and each interleave publishes. The startup scan then takes
|
||||
**287–304 s instead of 1.7 s**, and every held request waits it out.
|
||||
*Repro:* cold workspace start on OpenTitan, open `aes_cipher_core.sv`
|
||||
plus `documentSymbol`; at 150 ms, in one write, send `didChange(A)`,
|
||||
`full/delta(A)`, `didOpen(uart_core.sv)` and `full(uart_core)`.
|
||||
Result: `documentSymbol` answered at 304 s on base and 287 s on this
|
||||
branch. This lane makes the trigger *more reachable*, because A now
|
||||
colours at 2 ms and a user can type and open a second file inside the
|
||||
head phase. My first VS Code-like replay hit it without being
|
||||
constructed to.
|
||||
- **Q2 (MEDIUM, goal gap and README accuracy).** In folder scope, the
|
||||
default, when the first `didOpen` arrives after the settings answer
|
||||
(VS Code with `onView:lucisv.hierarchy` activation, or any race), the
|
||||
startup scans 0 files and the `didOpen` then *widens*.
|
||||
`reindex_widened` drains nothing, so first colour is still **~630–650 ms**,
|
||||
unchanged from base. Opening any file in an un-indexed folder later
|
||||
behaves the same way. The README's results table shows only the
|
||||
race-won ordering. Handshake request 1 as written does **not** fix this:
|
||||
as the dev notes, it cannot reach the `full` in the same burst as the
|
||||
`didOpen`, which is exactly VS Code's case. The request should ask for
|
||||
the widen to run after the burst's exempt colour requests are answered,
|
||||
or for the exemption to run before `reindex_widened`.
|
||||
- **Q3 (LOW/MEDIUM, design trade-off).** A client without
|
||||
`refreshSupport` keeps the cross-file-blind colours of an early full
|
||||
until its next edit. `spi_device_reg_top.sv` and `uart_core.sv` stayed
|
||||
different from the settled full in the norefresh run. Before this
|
||||
change, workspace scope left ~26 stale tokens; now it can leave
|
||||
thousands. VS Code is not affected. The lead should decide whether
|
||||
non-refresh clients get the early `range` only.
|
||||
- **Q4 (LOW, doc).** "Every disagreement is a name resolved to another
|
||||
file" is not exact. 7 of 1 501 disagreements are inherited class
|
||||
methods resolved through the index to the *same* file, for example
|
||||
`ibex/dv/uvm/core_ibex/tests/core_ibex_test_lib.sv:1101` `stress_debug()`
|
||||
in `core_ibex_directed_test extends core_ibex_debug_intr_basic_test`.
|
||||
The refresh fixes them all the same. Also, Status says "13 claims on the
|
||||
wire", but `server/viewport/tests.rs` has 12 tests.
|
||||
- **Q5 (LOW, process).** Forty `st-before-*`/`st-after-*` index-store
|
||||
directories (1.3 GB) were written into the off-limits
|
||||
`~/.cache/lucisv-opentitan-full/` at 07:13–07:28. Their names match this
|
||||
lane's measurement harness. QA did not remove them; that is for the lead.
|
||||
- **Q6 (INFO).** `refresh_tokens_if_stale` re-tokenizes every open
|
||||
non-large buffer once per index revision, and every save is a revision.
|
||||
That is 0.3–7 ms per buffer on the `run` thread. It is not measured with
|
||||
many open buffers.
|
||||
|
||||
VS Code facts 1, 2, 3 (range dropped on version change) and 5 (refresh
|
||||
calls `schedule(0)` or waits for the in-flight request) check out against
|
||||
the 1.145.2 bundle (`_tokenizeViewportNow`, `_requestRange`,
|
||||
`handleProviderDidChange`). The `[email protected]` claims
|
||||
(fact 6) are unverified: no local copy, not fetched. A real VS Code was
|
||||
not observed. Nothing fixed by QA.
|
||||
|
||||
- **2026-11-19 (QA round 2, Opus 5.5; worktree 71.3b on `934d472`).**
|
||||
Verdict **PASS WITH FINDINGS** (minor findings only). Base `934d472` was
|
||||
built from `git archive` with its own target dir. Every store and tree
|
||||
lived under the QA scratch dir (`qa713b/`).
|
||||
`git -C ~/.cache/lucisv-opentitan-full status --short` is empty, the forty
|
||||
`st-*` stores are gone, and nothing in `~/.cache/lucisv-corpus` is newer
|
||||
than this round.
|
||||
|
||||
**Baseline.**
|
||||
- `tools/gates.sh`: every step passes, including `cross`. lucisv_server is
|
||||
2052/0 and corpus 814/6.
|
||||
- Ignored release runs, with the corpus and OpenTitan paths pointed at
|
||||
scratch copies, all pass:
|
||||
- `viewport_sweep`: 7 602 windows, 0 other;
|
||||
- `ordering_random` long run;
|
||||
- both `localized_reindex` sweeps.
|
||||
- `#[test]` count went from 5 491 to 5 514. Nothing was removed or edited.
|
||||
No file under `server/tests/`, `tests/`, `state/` or `vlog_semantic`
|
||||
differs from `934d472`, so 71.7's scan_ordering, caret_boundary and
|
||||
ordering_random tests and the re-index differential tests are untouched
|
||||
and pass.
|
||||
- `process_batch` is 79 lines and `open_then_widen` is 22.
|
||||
|
||||
**Safety on the new loop** (`process_batch`/`must_hold`/`hold`,
|
||||
`answered_ahead`, `set_aside`, `apply_in_burst`, `open_then_widen`,
|
||||
`answer_colours_mid_widen`, `reindex_widened`). Every place an unapplied
|
||||
older message can sit is covered by `text_is_current`:
|
||||
- this burst's older messages are applied, otherwise `process_batch` has
|
||||
already returned holding them;
|
||||
- `held` (a notification naming the buffer);
|
||||
- `behind`, set to `outer` at the head and to `around` while the widen
|
||||
runs, so the burst's unapplied tail makes every mid-widen colour request
|
||||
wait;
|
||||
- `ahead` (the set-aside part of its own burst);
|
||||
- `dirty`.
|
||||
|
||||
The four 71.7 invariants hold:
|
||||
- (i) No notification overtakes another. Messages drained mid-widen go to
|
||||
`held` unapplied, and `hold` splices the burst tail in front of them.
|
||||
- (ii) Scan state changes only through applied messages. The recorded
|
||||
widen is the applied `didOpen`'s, and between recording it and running
|
||||
it only colouring requests are answered; notifications are kept.
|
||||
- (iii) Held messages are handed back a bounded number of times. Q1 does
|
||||
not come back: on `livelock2.py` delta and hover the held requests are
|
||||
answered at 741 and 665 ms, against 667 ms on base. On `c717.py`, seeds
|
||||
1 and 2, the startup scan ends at 3.33 and 3.60 s, against 4.19 and
|
||||
3.70 s on base (machine loaded).
|
||||
- (iv) Exactly once: no request was lost or duplicated in any run.
|
||||
|
||||
One semantic note: a held settings notification does not stop an early
|
||||
colour answer, because it names no buffer. The answer can therefore use the
|
||||
previous settings' analysis. Colours only, and the early-answer refresh
|
||||
corrects it at settle.
|
||||
|
||||
**Attack campaigns** (exact text oracle: the generated documents' tokens
|
||||
are computed from the client's own text; deltas rebuilt as the LSP spec
|
||||
says; every answer has to match a state the client had sent at or after
|
||||
the request):
|
||||
|
||||
| campaign | runs | token answers checked | result |
|
||||
|---|---|---|---|
|
||||
| 71.7's `ord3.py` with range/full/delta mixed in, plus didOpen+full, didOpen+change+range/full, didOpen+didClose, change+delta (`ord3t.py`) | corpus 6 workspace + 4 folder, OT 2+2, corpus 2 without refresh: 16 runs, 26 refreshes | 6 918 (range 4 562, full 863, delta 1 493, 1 050 of them as edits) | **0 fails**; fresh-server oracle equal in every run; 0 stale at settle; 153 early answers |
|
||||
| `wid.py`: folder scope on a full OT copy, 24 docs in 12 disjoint scope folders, 12 widens per run, 1–3 widening didOpens per burst each with its `full`, settings change between the recorded widen and its run, didOpen+didClose before the widen, watcher creates (rescans) mixed in | 8 seeds × (new, base) + 3 shutdown+exit mid-widen + 2 without refresh | 3 047 on new | **0 fails** |
|
||||
|
||||
In `wid.py`:
|
||||
- **non-colouring requests in a widening burst were answered only after
|
||||
the widen ended (63/63);**
|
||||
- **all 978 non-colouring answers are identical to base, answer for
|
||||
answer**;
|
||||
- shutdown+exit mid-widen: the server exited in 0.1–0.9 s with `full` and
|
||||
`shutdown` both answered.
|
||||
|
||||
Other comparisons with base:
|
||||
- `f6.py` tail, held and control all report "server holds v3", the same
|
||||
as base.
|
||||
- `harm2.py` matches base. Base's first run gave one different
|
||||
`definition`, which did not reproduce in two reruns of either binary, so
|
||||
it is a pre-existing timing race.
|
||||
|
||||
**Re-index oracle** (qa711 `small.py`, `outside.py`):
|
||||
- `small.py` and `outside.py` (push and pull): only the negative controls
|
||||
diverge, as in 71.1.
|
||||
- `rand_run2.py`, two seeds per tree × 300 steps (`QA_FRESH_SAVE=1` as
|
||||
before): corpus 71/72 and otsample 73/74 all end with 0 divergent checks.
|
||||
|
||||
**Accuracy** (own checker, index empty): 726 windows (498 corpus, 228 OT).
|
||||
- 0 invalid answers;
|
||||
- windowed answer equals the full answer filtered to the range in 726/726;
|
||||
- all 437 disagreements resolve through the index (go-to-definition lands
|
||||
in another file);
|
||||
- the directive and attribute string/comment hits are pre-existing, as in
|
||||
round 1.
|
||||
|
||||
**Q3.** A client without refreshSupport gets `full` at 655 ms (held, as on
|
||||
base at 672 ms), `range` early at 107 ms, and no refresh. With
|
||||
refreshSupport: `full` at 2 ms and one refresh.
|
||||
|
||||
**Q6.**
|
||||
- Trade-off (`q6.py trade`): an edit plus save in package A that changes
|
||||
how open B colours sends no refresh, on base and on new, so "same as
|
||||
before" holds.
|
||||
- Check cost: with 50 or 200 buffers answered during the startup scan,
|
||||
the one settle check takes 5.2 and 32 ms (machine loaded; the dev
|
||||
measured 1.4/12.9 ms). Later saves run no check.
|
||||
|
||||
**Measured on the final binary** (medians of 5, ms from didOpen, OT copy;
|
||||
before = 934d472):
|
||||
|
||||
| scope / file | cold | warm | late open, cold | rescan hold | refresh lands cold / warm |
|
||||
|---|---|---|---|---|---|
|
||||
| ws / aes_cipher_core | 660 → **3.5** | 374 → **3.5** | 626 → **62** | 756 → **141** | 1 616 / 839 |
|
||||
| ws / spi_device_reg_top | 685 → **39** | 400 → **37** | 674 → **86** | 791 → **159** | 1 635 / 868 |
|
||||
| folder / aes_cipher_core | 38 → **3.2** | 66 → **3.2** | 611 → **2.3** | 325 → **70** | 636 / 348 |
|
||||
| folder / spi_device_reg_top | 74 → **32** | 98 → **31** | 641 → **32** | 344 → **70** | 699 / 372 |
|
||||
|
||||
Opening `top_earlgrey.sv` mid-session in folder scope: its `full` takes
|
||||
**375 → 5.6 ms**. Refresh counts per run, 5/5 runs each:
|
||||
- cold and late open: 1;
|
||||
- warm with the rescan, and mid-session open: 2, i.e. one more at the
|
||||
rescan's or widen's settle;
|
||||
- base: 0.
|
||||
|
||||
No storm, and no early answer that was left without a refresh when
|
||||
stale. The dev's table reproduces within noise.
|
||||
|
||||
**Findings.**
|
||||
- **R2-1 (LOW/INFO, `server/viewport.rs` `answer_from_the_buffer`
|
||||
`guessed.insert`).** A `range` answered during a rescan is always
|
||||
counted stale, so it buys one refresh at settle even when nothing
|
||||
changed. On `flick.py`, a `full` asked during the same rescan was
|
||||
identical to the settled answer and drew 0 refreshes. With the measured
|
||||
`range`, every warm run got a second refresh. VS Code asks for `range`
|
||||
only until the first `full`, so this rarely fires there.
|
||||
- **R2-2 (LOW, docs).**
|
||||
- Design ("A dirty buffer waits") still says "rescan hold is now
|
||||
20–112 ms"; it is 70–156 ms.
|
||||
- The work log says `open_then_widen` "is 74 lines"; it is 22.
|
||||
- The changelog says first colours arrive in "2–39 ms … cold start in
|
||||
either scope". Late open in workspace scope is still 62–86 ms
|
||||
(discovery walk), and the paragraph should say so.
|
||||
- Handshake 2 (discovery drain) is still open and correctly described.
|
||||
|
||||
Unverified: a real VS Code, and the vscode-languageclient facts. Nothing
|
||||
fixed by QA.
|
||||
|
||||
## Review
|
||||
|
||||
**Lead, 2026-11-19.** Accepted for 0.65.10, after two QA rounds and a re-application onto a changed loop.
|
||||
|
||||
- The owner asked for a viewport-only highlight. The dev's Step 1 found that
|
||||
VS Code asks for the viewport only until its first whole-file answer, so
|
||||
answering `range` early would not have been enough; `full` is answered
|
||||
early too and corrected by a refresh. Reading the client before designing
|
||||
is what made this work.
|
||||
- Round 1 passed QA but left the default scope's common ordering untouched
|
||||
(a file opened after settings arrive still waited ~630 ms) and I did not
|
||||
ship it. It also could not be finished then: the fix sits in
|
||||
`server/index.rs`, which the re-index lane held.
|
||||
- Lanes 71.1 and 71.7 then changed the loop underneath it. I re-applied the
|
||||
lane onto 0.65.8 by hand and had the dev rebuild the exemption on 71.7's
|
||||
`must_hold`/`behind` instead of beside it; its own per-buffer lists were
|
||||
deleted. One mechanism for "is anything for this buffer still queued",
|
||||
at the price of one narrow shape where a colour request now waits.
|
||||
- QA round 2 re-measured the whole table on the final binary (the dev had
|
||||
measured before its last refactor), rebuilt client token state from deltas
|
||||
for ~10 000 answers with no failure, and compared 978 non-colour answers
|
||||
with base, identical. That, and 71.7's invariants holding under `wid.py`,
|
||||
is what I accept this on.
|
||||
- QA's two README corrections: I fixed the rescan-hold figure in Design; the
|
||||
work log's "74 lines" is history and stays. The release notes state the
|
||||
workspace-scope late-open figure the dev's paragraph left out.
|
||||
- Not verified: a running VS Code; the `vscode-languageclient` facts (read
|
||||
from a fetched copy, not the pinned one).
|
||||
@@ -1468,3 +1468,66 @@ Details and the method: `docs/features/localized-reindex/README.md`.
|
||||
| mention census, one lint pass (average / worst file) | 51 µs / 2.8 ms | unchanged |
|
||||
|
||||
Probes: `tools/guard.sh -- cargo test --release -p lucisv_server reindex_perf -- --ignored --nocapture --test-threads=1`.
|
||||
|
||||
### 2026-11-19 — viewport highlight: colours that do not wait for the index (TODO §71.3)
|
||||
|
||||
Time from `didOpen` to the first semantic-token answer, real binary over LSP
|
||||
stdio, a copy of OpenTitan `hw/` (4 058 files), a VS Code-shaped opening
|
||||
burst (`full` at once, `range` for lines 0–120 after the viewport's 100 ms
|
||||
debounce). Medians of 5 runs, shared machine; before = 0.65.8 (`934d472`).
|
||||
*Late open* = the `didOpen` arrives after the settings answer (in folder
|
||||
scope the startup then scans nothing and the open widens). Harness and
|
||||
traces in `docs/features/viewport-highlight/README.md`.
|
||||
|
||||
| scope / file | cold | warm | late open (cold) | tokens held by a mid-session rescan |
|
||||
|---|---|---|---|---|
|
||||
| workspace / `aes_cipher_core.sv` | 700 → **3.5 ms** | 384 → **3.5 ms** | 631 → **64 ms** | 778 → **120 ms** |
|
||||
| workspace / `spi_device_reg_top.sv` (545 KB) | 680 → **39 ms** | 401 → **39 ms** | 668 → **89 ms** | 758 → **156 ms** |
|
||||
| folder / `aes_cipher_core.sv` | 39 → **3.3 ms** | 66 → **3.3 ms** | 614 → **2.4 ms** | 325 → **70 ms** |
|
||||
| folder / `spi_device_reg_top.sv` | 71 → **38 ms** | 100 → **38 ms** | 643 → **32 ms** | 341 → **87 ms** |
|
||||
|
||||
Opening a file in a folder not yet indexed, mid-session: the new buffer's
|
||||
first colour 350 → **3 ms** (the widen now answers colours before it runs and
|
||||
between its files). The token build itself was never the cost (0.3 ms small,
|
||||
6.5 ms for 545 KB); the wait was the order contract. What is left is the
|
||||
buffer's own parse at `didOpen` and the discovery walk at the front of every
|
||||
scan (~80 ms), which drains nothing. One `workspace/semanticTokens/refresh`
|
||||
lands when the scan settles; the check behind it costs 1.4 ms (50 open
|
||||
buffers) / 12.9 ms (200) once after startup and 0.00 ms per later
|
||||
index-changing save (only answers taken off an unsettled index are
|
||||
re-checked; unrestricted it was 1.4–2.3 / 12.7–14.2 ms per save). A 60-line
|
||||
`range` on a buffer of 4 000 modules costs 0.30 ms against 0.28 ms for 500 in
|
||||
a debug build (was 98 ms against 11 ms: the old answer built the whole file).
|
||||
|
||||
### 2026-11-19 — fast actions: same file first, completion through the relationship map (lane 71.2)
|
||||
|
||||
Real binary over LSP stdio with VS Code 1.145's client capabilities, against
|
||||
copies of OpenTitan `hw/` replicated 1 / 5 / 10 times (4 061 / 20 305 /
|
||||
40 610 files, unit names prefixed per copy), workspace scope, cold store,
|
||||
the open buffer `aes_cipher_core.sv`. Before = 0.65.10 (`c1c1407`); both
|
||||
binaries run back to back per tree on a shared machine. Medians: 3 runs for
|
||||
held requests, 20 calls settled. Harness and every table in
|
||||
`docs/features/fast-actions/README.md`.
|
||||
|
||||
| held during … (4k / 20k / 40k files) | before | after, a request the buffer answers | after, a cross-file one |
|
||||
|---|---|---|---|
|
||||
| a whole rescan (one watched *create*) | 939 / 4 712 / 9 781 ms | **195 / 1 110 / 2 435 ms** | unchanged |
|
||||
| the startup scan (local hover with the `didOpen`) | 637 / 752 / 908 ms | **2.3 / 1.9 / 2.1 ms** | unchanged |
|
||||
| a widen (folder scope) | 366 / 369 / 363 ms | **0.6 / 0.6 / 0.2 ms** | unchanged |
|
||||
|
||||
(Re-measured in the lane's escalation round: the rescan row's "after" is the
|
||||
harness's own previous step — a delete's one-file update, which drains
|
||||
nothing — and not the rescan. With the server idle when the watcher event
|
||||
arrives a buffer-local request sent 5 ms later takes **38 / 168 / 331 ms**,
|
||||
and 0.1–0.2 ms when it is written together with the event.)
|
||||
|
||||
Settled, nothing the buffer-local requests do scales with the workspace
|
||||
(every one under 1 ms at 40k files, unchanged by this lane). Completion,
|
||||
per answer, at every size: 129–155 KB → **62–84 KB** for a client that takes
|
||||
`itemDefaults` (the range and format said once), server time 1.4–1.6 →
|
||||
0.9–1.2 ms, and the members of the imported package all offered (at
|
||||
`ae`, 40k files: 10 of 34 → 34 of 34). What remains slow and is not this
|
||||
lane's: the rescan itself (whole, for one created file), its first ~0.5–2 s
|
||||
before any drain point, `workspace/symbol` (118 ms for one letter at 40k),
|
||||
the hierarchy snapshot (26 MB, 274 ms at 40k), and a 20k-line buffer's
|
||||
reparse per keystroke (~20–27 ms).
|
||||
+107
-25
@@ -22,7 +22,11 @@ their edges already tabled below; +§2.9-19); updated 2026-08-30 again
|
||||
for fuzzy-completion (107 feature READMEs); updated 2026-09-01 for
|
||||
null-items (108 feature READMEs); updated 2026-09-02 through v0.33.0 for the
|
||||
testbench grammar/semantics wave, comment slots, bind semantics, SVA bodies,
|
||||
and the four decomposition rounds (125 feature READMEs).
|
||||
and the four decomposition rounds (125 feature READMEs); updated 2026-11-19
|
||||
through v0.65.11 for release gating, hierarchy-current-path,
|
||||
comment-highlighting, ifdef-folding, format-styles, localized-reindex,
|
||||
scan-ordering, linux-test-portability (Round 2, the MCP stamp fix),
|
||||
viewport-highlight and fast-actions; open handshakes 44–66 from TODO §70/§71.
|
||||
|
||||
**Code audit refreshed 2026-09-07.** Latest release: **v0.49.0**
|
||||
(`4c2dae3`); committed snapshot: **`df4e714`**, clean at review start.
|
||||
@@ -159,7 +163,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 — `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`. |
|
||||
| `CI (Gitea Actions) ──▶ tools/` | depends | `release.yml` is (almost) all `tools/` one-liners — `gates.sh` first (the release is gated since 0.65.1: fmt, clippy, one `suite:<crate>` step per workspace member, docs, corpus — fetched first so it is not skipped —, node, cross; a red gate stops before anything is built), 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) on the macOS runner, and since 0.65.9 a `linux` job (`runs-on: linux-x64`, the luhpe runner, as root, 4 CPU / 8 GB, rustup per job, cold build) running `cargo clippy --all-targets -- -D warnings` and `cargo test --workspace`; `tools/linux_check.sh [--user] [--dry-run]` runs a command against the working tree in the same job image without a push (§2.8). `ci.yml` runs on the branch push and the release does not wait for it: a tag publishes only after `gates.sh` is green on macOS, so releases are gated on macOS alone (§2.9-57). Both jobs run `cargo test --workspace` bare, not through `tools/guard.sh` (§2.9-65). 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):
|
||||
@@ -215,7 +219,12 @@ server queue and `lsp-server` I/O threads are proven not to parse.
|
||||
`verify.rs` (the runtime safety net: token equivalence + convergence —
|
||||
CLAUDE.md invariant #4 territory, see §3.3); `fence.rs` (format-off regions +
|
||||
`protected_regions`, consumed by both front ends); `range.rs` (`--lines`);
|
||||
`align.rs` (alignment inference). `format_source` = parse → format → verify;
|
||||
`align.rs` (alignment inference; `align::plan` takes an `Alignment` mode,
|
||||
`Infer` = the old rule); `selection/` (`format_selection`, §66.2);
|
||||
`style.rs` (`Style`, the `PRESETS` table of six rows, `preset`, `names`;
|
||||
every switch moves whitespace only, so `verify.rs` knows nothing of styles);
|
||||
`auto.rs` (`format_auto`, `resolve_style`: format with each preset, keep the
|
||||
fewest changed lines). `format_source` = parse → format → verify;
|
||||
an error means emit nothing.
|
||||
|
||||
**`vlog_semantic`** — `bind/` (AST → scopes/symbols/references; since
|
||||
@@ -226,21 +235,27 @@ an error means emit nothing.
|
||||
`workspace/` (`mod` = the tables, `index` = queries and `build`, `update` =
|
||||
incremental update and `fingerprint`, `record` = the `FileFacts` read-off,
|
||||
`external` = the overlay, `reexport` = cycle-guarded package member traversal;
|
||||
`hierarchy` = tagged connection/hierarchical member tables; `WorkspaceIndex`: units, members, defines, instantiation and
|
||||
`hierarchy` = tagged connection/hierarchical member tables; `path_units`
|
||||
(§65.4); `dependents` = the readers table, which files' resolution read which
|
||||
merged-table key; `references` = postings built whole or re-done for a few
|
||||
files; `replace` = one record replaced, only the keys it reaches re-merged —
|
||||
the last three localized-reindex's; `WorkspaceIndex`: units, members, defines, instantiation and
|
||||
inheritance edge tables, incremental `update_file`/`remove_file`,
|
||||
reference postings, `files_spelling`, batch `absorb`, declaration `DeclLines`,
|
||||
`fingerprint`); `facts.rs` (`FileFacts` codec for the persistent cache;
|
||||
`FACTS_FORMAT` is **20**);
|
||||
`FACTS_FORMAT` is **22**, since §65.4);
|
||||
`instantiations.rs`, `classes.rs` (the shared walks, lifted from the server
|
||||
so the index census and the request handlers cannot drift); `imports.rs`
|
||||
(`import_usage`, `import_scopes`, `unused_imports`, `Exports`, `PackageExports`)
|
||||
is the shared usage judgement consumed by organize-imports and the linter.
|
||||
|
||||
**`lucisv_core`** — `config.rs` (`lucisv.toml` parsing + `Discovery`, the
|
||||
upward search with its per-instance cache), `walk.rs` (`collect_files`,
|
||||
upward search with its per-instance cache; `FileConfig::format_style`,
|
||||
`STYLE_NAMES`, `parse_style`, and `NAMES`, now `pub`), `walk.rs` (`collect_files`,
|
||||
`EXTENSIONS`, `.gitignore`/`--exclude` filtering), `filelist.rs` (the `.f`
|
||||
reader: files, `+incdir+`, defines, warnings), `cache.rs` (the format cache +
|
||||
`content_hash` — the one FNV-1a the server's index cache also reuses),
|
||||
`content_hash` — the one FNV-1a the server's index cache also reuses; an
|
||||
`Entry` carries its `style`, a seven-field store line),
|
||||
`atomic.rs` (shared replacement for CLI source writes and the format cache). Knows
|
||||
nothing of Verilog; depends on nothing. Config stores `LintOption` entries
|
||||
raw with source/line information; front ends validate them through
|
||||
@@ -295,10 +310,10 @@ spans two layers — the include graph *and* the `documentLink` handler;
|
||||
| layer | files | role |
|
||||
|---|---|---|
|
||||
| entry | `main.rs` | the no-argument / `--verbose`-only argument contract, capabilities advertisement, `InitializeParams` reading, wiring |
|
||||
| loop | `server/` (since 2026-09-02: `mod` = the loop; `dispatch`, `client`, `index`, `notification`, `progress`, `diagnostics`, `batch`, `formatting`, `large_file`, `semantic_tokens`; tests in `server/tests/`) | the message loop + queue/burst (cancel-request), dispatch, `Pending` map for server-initiated requests, stepped startup scans with mid-scan request drains, held-request ordering for rescans, reindex/widen orchestration, progress/log senders, optional `timing:` instrumentation |
|
||||
| state | `state.rs` | `Workspace` (roots, scope ladder, index, include graph, candidates, index cache, open `Document`s with overlay, bounded closed-file `FileView` cache), `Scan` (whole or additive widen), fan-out source selectors (`module_sources`, `rename_sources`, `include_sources`), and `Document` (text, tokens, tree, semantics, diagnostics, `large` flag) |
|
||||
| substrate | `convert.rs`, `uri.rs`, `locate.rs`, `pairs.rs`, `includes.rs`, `candidates.rs`, `index_cache.rs`, `watch.rs`, `settings.rs`, `templates.rs`, `sync.rs` | position math, URI↔path, location building, the begin/end scope matcher, the include graph, completion word/module tables and their scan-batch forms, the persistent index store, watcher registration, `lucisv.*` settings parsing, snippet registry, incremental text sync |
|
||||
| handlers | one file per capability: `format.rs`, `diagnostics.rs`, `lint.rs` (with `fences.rs`: the formatter's text-only fence answer memoized once per `Document` — perf5-p1; the shared-fence-filter contract is unamended; and `lint_snapshot.rs` + `lint_trace.rs` — perf5r-lint-snapshot, 2026-09-08: one `lint_with` pass per document revision shared by the diagnostics publish and quick-fix discovery, keyed by value on every input of that call — rule names, merged options, line width, tab width, oracle presence, external waiver *contents* — held in a `Slot` on the `Document` and cleared by `Document::refresh_overlay`, which every index mutation ends in; a `timing: codeaction … key=value` line under `--verbose`, parsed by `tools/perf/phases_r1.py`), `rename_trace.rs` (perf5-p2: `Rung`/`Wanted`/`SelectionTrace` — the path set the rename fan-out ladder fills, remembering which rung asked for each file; `Workspace::rename_sources_traced` is the ladder with that sink), `hover.rs`, `expand.rs`, `nav.rs`, `type_def.rs`, `type_hierarchy.rs`, `hierarchy.rs`, `design_hierarchy.rs`, `symbols.rs`, `tokens.rs`, `completion/` (`mod`, `member`, `module`, `tiers`, `word`, `site`; test harness in `harness`), `signature.rs`, `inlay.rs`, `inline.rs`, `lens.rs`, `code_action.rs`, `rename.rs`, `ports.rs`, `imports.rs`, `extract.rs`, `inline_module.rs`, `folding.rs`, `selection.rs`, `linked.rs`, `on_type.rs`, `includes.rs` (links), `file_ops.rs`, `instantiate.rs`, `large.rs` | each is a mostly-pure function over `Document`/`Workspace`; protocol only, no language analysis of its own (anything that looks like analysis in here is a bug or a Handshake request — lucisv-server README) |
|
||||
| loop | `server/` (since 2026-09-02: `mod` = the loop; `dispatch`, `client`, `index`, `notification`, `progress`, `diagnostics`, `batch`, `formatting`, `large_file`, `semantic_tokens`, `startup`; `ahead` = answering a request from its buffer ahead of whatever holds the rest — the one precondition (`answer_from_the_buffer`), `REACH`, every place a request is offered (fast-actions, 0.65.11); `viewport` = which colouring requests may go ahead, the range-guess record and the refresh (viewport-highlight; tests in `server/viewport/`); `probe` = `#[cfg(test)]` burst scripting and `went_ahead`; tests in `server/tests/`) | the message loop + queue/burst (cancel-request), dispatch, `Pending` map for server-initiated requests, stepped startup scans with mid-scan request drains, held-request ordering for rescans and for notifications (`must_hold`), the early-answer exemption, reindex/widen orchestration, progress/log senders, optional `timing:` instrumentation |
|
||||
| state | `state/` (a directory since TODO §55: `mod`, `document`, `buffers`, `views`, `scope`, `scan`, `rescan`, `discover`, `sources`, `port_grace`; localized-reindex added `incremental` — `OneFile`, `update_one_file` — and `watched` — `Watched`) | `Workspace` (roots, scope ladder, index, include graph, candidates, index cache, open `Document`s with overlay, bounded closed-file `FileView` cache), `Scan` (whole or additive widen), fan-out source selectors (`module_sources`, `rename_sources`, `include_sources`), and `Document` (text, tokens, tree, semantics, diagnostics, `large` flag) |
|
||||
| substrate | `convert.rs`, `uri.rs`, `locate.rs`, `pairs.rs`, `includes.rs`, `candidates.rs`, `index_cache.rs`, `watch.rs`, `settings.rs`, `templates.rs`, `sync.rs`, `caret.rs`, `auto_style.rs`, `same_file.rs` | position math, URI↔path, location building, the begin/end scope matcher, the include graph, completion word/module tables and their scan-batch forms, the persistent index store, watcher registration, `lucisv.*` settings parsing, snippet registry, incremental text sync, the byte a name-under-the-cursor request is about (`symbol_offset`), the per-document `auto` preset memory, whether a request's whole answer is its buffer's (`same_file::METHODS`, `answered_by_the_buffer`; tests in `same_file/`) |
|
||||
| handlers | one file per capability: `format.rs`, `diagnostics.rs`, `lint.rs` (with `fences.rs`: the formatter's text-only fence answer memoized once per `Document` — perf5-p1; the shared-fence-filter contract is unamended; and `lint_snapshot.rs` + `lint_trace.rs` — perf5r-lint-snapshot, 2026-09-08: one `lint_with` pass per document revision shared by the diagnostics publish and quick-fix discovery, keyed by value on every input of that call — rule names, merged options, line width, tab width, oracle presence, external waiver *contents* — held in a `Slot` on the `Document` and cleared by `Document::refresh_overlay`, which every index mutation ends in; a `timing: codeaction … key=value` line under `--verbose`, parsed by `tools/perf/phases_r1.py`), `rename_trace.rs` (perf5-p2: `Rung`/`Wanted`/`SelectionTrace` — the path set the rename fan-out ladder fills, remembering which rung asked for each file; `Workspace::rename_sources_traced` is the ladder with that sink), `hover.rs`, `expand.rs`, `nav.rs`, `type_def.rs`, `type_hierarchy.rs`, `hierarchy.rs`, `design_hierarchy.rs`, `symbols.rs`, `tokens.rs` (+ `tokens/`: `instantiation.rs`, window tests, ignored sweep), `completion/` (`mod`, `member`, `module`, `tiers`, `word`, `site`, `buffer`, `connection`; `related` = the related tier, sortText `4`, outside `LIMIT` with its own `RELATED_LIMIT`; `wire` = the `itemDefaults` payload rewrite — both fast-actions; test harness in `harness`), `signature.rs`, `inlay.rs`, `inline.rs`, `lens.rs`, `code_action.rs`, `rename.rs`, `ports.rs`, `imports.rs`, `extract.rs`, `inline_module.rs`, `folding.rs` (+ `folding/directives.rs`), `selection.rs`, `linked.rs`, `on_type.rs`, `includes.rs` (links), `file_ops.rs`, `instantiate.rs`, `large.rs` | each is a mostly-pure function over `Document`/`Workspace`; protocol only, no language analysis of its own (anything that looks like analysis in here is a bug or a Handshake request — lucisv-server README) |
|
||||
|
||||
**`editors/vscode`** — `extension.js` (spawn + rainbow decorations + storage
|
||||
path; ~everything else is `vscode-languageclient` driven off advertised
|
||||
@@ -308,12 +323,21 @@ colour ids), `syntaxes/` (hand-maintained grammar, test-locked to
|
||||
serialized start/restart chain, so a `lucisv.verbose` toggle cannot be lost to
|
||||
an in-flight start — shipped, shared by the extension restart paths),
|
||||
`hierarchyView.js`/`hierarchyModel.js`/`hierarchySections.js` (the indexed
|
||||
instance hierarchy sidebar and client-only DUT sections), `extract.js`
|
||||
instance hierarchy sidebar and client-only DUT sections), `hierarchyCurrent.js`
|
||||
(the current-path highlight; `media/hierarchy.{js,css}` set `data-lit`),
|
||||
`commentScan.js`/`commentKeywords.js` (the grammar-mirroring comment scan
|
||||
and its decorations), `referencesView.js`/`referencesModel.js`, `typing.js`,
|
||||
`mcp.js`, `extract.js`
|
||||
(the module-name input and extract command),
|
||||
`smoke.js` (headless handshake check) and `restart_test.js` (headless check of
|
||||
that chain, against a scripted fake client), `README.md` (the Marketplace
|
||||
Details page, owned by editor-marketplace-page).
|
||||
|
||||
**`tools/`** — besides the release and corpus scripts (§1.2), `gates.sh`
|
||||
(every gate as a guarded step; the release runs it first) and
|
||||
`linux_check.sh` (a command against the working tree in the Linux job image,
|
||||
over ssh, no push).
|
||||
|
||||
---
|
||||
|
||||
**`docs/site`** — Astro/Starlight content in `src/content/docs/`, sidebar and
|
||||
@@ -343,13 +367,23 @@ output after content changes, and keep historical measurements dated.
|
||||
| walk-cycles / small-items-4 | core directory identity set and warning sink ↔ CLI/server walk callers; parser delay-comment fields and `ExprKind::Type` → formatter and instance planning | Released in v0.43–0.44; warning paths continue without changing CLI status, direct missing inputs remain errors |
|
||||
| didopen-cost | `undriven-net` local guards → existing `MentionOracle` predicate; diagnostics equality → server publish/request ordering | Released in v0.44.0; no new async work or index API |
|
||||
| type-name-spans | parser `DataType::name_span`/`segments`, disable-target span → binder `exact_or_empty` and census | Released in v0.45.0; `scan.rs` deleted; source text remains the exact-span oracle |
|
||||
| package-reexports | binder export references → `FileFacts` RX group (introduced at codec 18, now 19) ↔ workspace `reexport.rs` and shared member queries | Released in v0.45.0; package exports add no local import; DPI-export names remain unbound |
|
||||
| package-reexports | binder export references → `FileFacts` RX group (introduced at codec 18; the codec is 22 now) ↔ workspace `reexport.rs` and shared member queries | Released in v0.45.0; package exports add no local import; DPI-export names remain unbound |
|
||||
| hierarchical-tail | `Surface` tags on declarations/references, codec 19 ↔ `workspace/hierarchy.rs`, member-tail resolution, completion and rename source selection | Released in v0.45.0; §2.9-23 closed; connection surface stays unchanged, instance tails read the hierarchical surface |
|
||||
| expand-wildcard / convert-to-ansi | `ports/{expand,ansi,merge}.rs` ↔ whole-edit verifier; server `ports.rs`, commands and action titles ↔ extension manifest; refactor → formatter test-only edge | Released in v0.46.0; explicit unmatched-port warnings and conservative merge/refusal rules |
|
||||
| organize-imports | semantic `imports.rs` → linter `unused-import` and refactor `imports.rs`; server `imports.rs` ↔ `source.organizeImports` / `lucisv.organizeImports` | Released in v0.47.0; 74 rules, new rule default off; package re-exports count as usage |
|
||||
| extract / inline module | refactor `extract/`, `inline/`, `check/ledger.rs`, `RefactorEdit::created` ↔ server `extract.rs`, `inline_module.rs`, source selectors and client resource capabilities; extension `extract.js` ↔ name prompt | Extract v0.47.0, inline v0.49.0; file copies/moves preserve protected pieces; open §2.9-32/33 |
|
||||
| dut-hierarchy | extension `hierarchySections.js` ↔ model/view, manifest commands, `lucisv.hierarchy.duts`, workspace state; consumes unchanged `lucisv/moduleHierarchy` snapshot | Delivered in v0.48.0, package corrected in v0.48.2; configured DUTs are locked, saved and configured names union |
|
||||
| coverage-gaps-l | new `randsequence` AST/parser/formatter modules and six grammar additions → all AST walkers and grammar keyword lock; `Config::uvm_utils_indent` ↔ core `[format]`, CLI config merge, server setting and extension manifest | Released in v0.49.0; default-off output option; cache-key omission open in §2.9-34 |
|
||||
| release-gates | `.gitea/workflows/release.yml` runs `tools/gates.sh` before `release.sh --cross`; `gates.sh` step list/limits ↔ `docs/features/release-gates`, `tools/RELEASING.md`; `cross` step ↔ the rustup toolchain `release.sh --cross` builds with | Released in v0.65.1 (gate) and v0.65.7 (`cross`); release still gated on macOS only (§2.9-57) |
|
||||
| hierarchy-current-path | extension `hierarchyCurrent.js` ↔ `hierarchyView.js` ↔ `media/hierarchy.{js,css}` (`lit` row field + `{type:'lit'}` message); `hierarchySections.headerId` now exported; manifest colours `lucisv.hierarchyCurrent`/`Parent1–3`/`Ancestor`/`CurrentBar` + `lucisv.hierarchy.highlightCurrent`; consumes the unchanged schema-2 snapshot | Released in v0.65.2; extension-only, no server change; not yet seen in a running editor |
|
||||
| comment-highlighting | extension `commentScan.js` mirrors the grammar's `comments`/`strings` rules (locked by `commentScan_test.js`) ↔ `commentKeywords.js` decorations ↔ manifest `lucisv.commentKeywords.{builtIn,custom,caseSensitive}` + colour `lucisv.commentKeyword`; `.vscodeignore`/`RELEASING.md` runtime-module list | Released in v0.65.3; grammar and server unchanged; bracket colour in comments is VS Code's (explained, not changed) |
|
||||
| ifdef-folding | server `folding/directives.rs::branch_spans` (reads lexer `Directive` tokens) → `folding.rs` (`scope_and_comment_folds` / `branch_folds` / `in_answer_order`) ↔ sticky scroll via the extension's `foldingProviderModel` (§67) | Released in v0.65.4; existing folds byte-identical and first on a shared start line; large buffers still fold nothing |
|
||||
| format-styles | formatter `style.rs` (`Style`, `PRESETS`, `preset`, `names`), `auto.rs` (`format_auto`, `resolve_style`), `align::plan(mode)`, `Config::{style, auto_style, styled, named, style_name}` ↔ core `STYLE_NAMES`/`parse_style`/`FileConfig::format_style`, cache `Entry::style` (seven-field line) ↔ CLI `--style`, MCP `format`/`diagnostics`, server `settings.rs` `lucisv.format.style`, `auto_style.rs`, `lint.rs` line-length ↔ manifest enum | Released in v0.65.5 (server lint width v0.65.6); default `lucisv` byte-identical; `verify.rs` untouched; open §2.9-44/47 |
|
||||
| localized-reindex | semantic `workspace/{dependents,references,replace}.rs` (readers table, in memory, in `fingerprint`), `update_file`/`update_facts -> bool`, `symbols_named`, `FileFacts::{declares_the_same, declared_names}` ↔ server `state/incremental.rs` (`OneFile`), `state/watched.rs` (`Watched`), `watch::{scope_files, names_a_config}`, `IncludeGraph::{update_held, add_known, refresh_naming}`, `Candidates::{set_file_words, refresh_names}`, `server/index.rs` `BURST_DIVISOR` | Released in v0.65.6, published as v0.65.7 (Windows fix); no `FACTS_FORMAT` change; open §2.9-48/49/51 |
|
||||
| scan-ordering | server `server/mod.rs` `must_hold`/`behind`/`hold`, `server/batch.rs::changes_state`, `opened_mid_scan` set in `notification.rs`'s `didOpen` arm and read in `index.rs::answer_what_is_waiting`; `caret.rs::symbol_offset` → `dispatch.rs` `Server::symbol_offset` (nine requests); extension `referencesView.js` opens rows at the name's start | Released in v0.65.8; amended in v0.65.11 (fast-actions: `owes_a_state_change` — the answer to a settings pull is ordered like a notification); open §2.9-50/52/53 |
|
||||
| linux-test-portability (Round 2) | `lucisv_mcp` `project/files.rs` `Stamp` (`identity: Option<Identity>`, `read_mono`, `RACY` 3 s over mtime and ctime, `Change::Suspect`) ↔ every index-based MCP tool; `ci.yml` `linux` job ↔ `tools/linux_check.sh` (same image, no push) | Released in v0.65.9; test code plus the one MCP product fix; open §2.9-54–57 |
|
||||
| viewport-highlight | server `server/viewport.rs` (`colours_may_go_ahead`, `coloured_ahead`, `index_unsettled`, `refresh_tokens_if_stale`, `Viewport::defers_widen`) and, since 0.65.11, `server/ahead.rs` (`answer_from_the_buffer`, `set_aside`, `open_then_widen`, `answer_ahead_mid_widen`) ↔ `must_hold`/`behind`/`held`/`dirty` (scan-ordering) ↔ `dispatch.rs::answer_flushed` ↔ `index.rs::reindex_widened`; `tokens::semantic_tokens_in_range` + `large::line_window` + `tokens/instantiation.rs::overrides_within`; `ClientAbilities::semantic_tokens_refresh` (`main.rs`) | Released in v0.65.10; non-colour answers unchanged (978 compared); the early-answer machinery moved to `ahead.rs` in v0.65.11 (pure move); open §2.9-58–60 |
|
||||
| fast-actions | server `server/ahead.rs` (`answer_from_the_buffer` — the one precondition —, `REACH`/`Reach`, `Server::can_reach`, `nothing_unapplied_for`, `settings_awaited`, `answer_ahead_of`, `answer_held_ahead`) ↔ `same_file.rs` (`METHODS`, `answered_by_the_buffer`; its README table pinned to the dispatch by `same_file/tests.rs`) ↔ `server/mod.rs` (`must_hold`, `owes_a_state_change`, `settings_announced`) ↔ `server/diagnostics.rs::flush_buffer` ↔ `server/large_file.rs::reclassify_large_buffers` ↔ `viewport.rs` (`index_unsettled` also while anything is held); `completion/related.rs` (sortText `4`, `RELATED_LIMIT`, tiers renumbered `4→5`…`7→8`, `tests/e2e.rs` digits) and `completion/wire.rs` ↔ `ClientAbilities::completion_item_defaults` (`main.rs`); `includes::include_at`, `type_def::type_name`, `candidates::macro_of` now `pub(crate)` | Released in v0.65.11 (TODO §71.2) after an escalation round; no `vlog_semantic` change; scan-ordering's response exemption amended; `completionItem/resolve` measured, not built; open §2.9-61–64; not seen in a running VS Code |
|
||||
|
||||
The lazy action resolves against current workspace state and rejects a stale
|
||||
or inapplicable action. Indexed definition locations bypass closed-file reads
|
||||
@@ -649,6 +683,18 @@ engine-lane features are listed above; this table is the server-internal web.
|
||||
| `vscode-hierarchy-sidebar ──▶ scan-interleave / cancel-request` | depends | `complete` is `Server::index_is_complete()` = `!scanning && !must_wait()`. It is false exactly during the startup scan: a request owed a rescan is *held* by `must_wait`, and `rescan_wanted` is only ever set while `scanning` is true, so no snapshot is ever answered `complete` off an index a queued message is about to rebuild. |
|
||||
| `code-lens ◀──▶ hierarchy` | handshake | code-lens split `incoming` into the batch primitive `callers_of_each` so lens and hierarchy share one census; `incoming` is a one-element call into it and its behavior (empty-name guard included) is pinned unchanged. Lens and hierarchy views can never disagree; refresh rides `reindex()` after the bar comes down. |
|
||||
| `server-lint / pull-diagnostics / editor-scopes ──▶ diagnostics.rs` | depends | One `diagnostics::all` composition: parse errors + missing-closer warnings + lint warnings, one publish (or one pull) per change; `send_diagnostics` is the single push gate so a pulling client is never served both models. |
|
||||
| `localized-reindex ◀──▶ incremental-index / workspace-index / include-nav / file-watching / completion-core` | handshake | (2026-11-19, TODO §71.1, 0.65.6) A save costs the file plus the readers of what moved. `vlog_semantic`: `update_file`/`update_facts` return whether the index moved; `workspace/dependents.rs` records, through a thread-local `note`, which files' resolution read which merged-table key; `replace.rs` re-merges only the keys either record names and `references.rs` re-does postings only for those keys' readers. In memory, no codec change, rendered in `fingerprint` so every equality test holds it to a rebuild. Server: `update_one_file -> OneFile { NotHeld, Unchanged, Changed }` — `Unchanged` sends no `codeLens/refresh` or `moduleHierarchyChanged` but still republishes every open buffer; `Workspace::watched -> Watched { Held, Outside, Unknown }` — `Outside` re-resolves the include lines naming it (`refresh_includes_naming(&[PathBuf])`) and starts no rescan, another spelling of a held file is one-file; a `lucisv.toml` event is now a whole rescan; a burst naming more than half the index (`BURST_DIVISOR`) keeps the one rescan. The amended fast-path table lives in the feature README; the invariant (any edit sequence answers as a fresh server) is its differential suite. Cost: the readers table on every whole merge, CLI and MCP included. |
|
||||
| `localized-reindex ◀──▶ format-styles` (`lint.rs`) | handshake | `line-length`'s width is `file.line_length.or(client.line_length)`, else the style's width (`file.format_style.or(client.style)` → `vlog_formatter::style::preset`), else 100 — the ladder `format::indent_width` and `lucisv check` walk; `auto` names no preset. Pinned rung by rung against the CLI's ladder. |
|
||||
| `scan-ordering ◀──▶ scan-interleave / cancel-request / change-debounce` | handshake | (2026-11-19, TODO §71.7, 0.65.8) **No notification overtakes an older notification.** `Server::must_hold(message)` replaces `must_wait() && Request` in `process_batch`: a request waits on `must_wait` (unchanged); a state-changing notification (`batch::changes_state`: any but `$/cancelRequest`) waits while an older one is unapplied — in `held`, or counted by `Server::behind` (the unapplied notifications in the tail of the burst whose message started the scan now draining); a cancel waits whenever anything is held; a response is never held — **amended in 0.65.11 (fast-actions)**: the client's answer to a `workspace/configuration` pull is applied by the same `apply_settings` a push is, so it is ordered like a notification (`Server::owes_a_state_change` = `changes_state` or an unapplied settings answer replaces `changes_state` in what `behind` counts and in both state-change clauses of `must_hold`); every other response stays exempt, and staging still takes the answer out of `held` first (`take_the_answer_out_of_held`). A held request is answered against whatever is applied when it is replayed (not "no notification overtakes a request"). A `didOpen` changes scan order where it is *applied* (`head_owed` + `opened_mid_scan` in `notification.rs`, read once per batch by `answer_what_is_waiting`; `batch::opened_in` deleted), so a held batch is handed back at most once per file opened. Any new caller of `process_batch` inherits the rule; anything applying a client message around it breaks it. |
|
||||
| `scan-ordering ──▶ hover / nav / references-nav / refactor-rename / hierarchy / type-hierarchy` (caret) | depends | `caret::symbol_offset(text, caret)` steps one byte left when the caret is just past a name (identifier, keyword, system task, macro, number, escaped identifier) and not at the start of another; `Server::symbol_offset` (`dispatch.rs`) applies it for hover, definition, typeDefinition, references, documentHighlight, prepareRename, rename and the two hierarchy prepares. Linked editing, signature help, completion/inline completion, on-type, selection range and code actions keep `Server::offset` on purpose; a new "name under the cursor" request should use `symbol_offset`. The feature README tables every position-taking request. Extension half: `referencesView.js` opens a row at the name's start. MCP answers by name and is unaffected. |
|
||||
| `viewport-highlight ◀──▶ scan-ordering / semantic-tokens-delta / large-file-mode` | handshake | (2026-11-19, TODO §71.3, 0.65.10) The first exemption from held-request order: before `process_batch` holds a `semanticTokens/{range,full,full/delta}` request, it is answered through `answer_flushed` (dispatch minus `flush_dirty`) when its buffer's text is current. **Since 0.65.11 the decision is fast-actions' `Server::answer_from_the_buffer` in `server/ahead.rs`** (moved there from `viewport.rs` as a pure move, with `set_aside` and `open_then_widen`), so clauses (a)/(b) are shared with every early answer: the buffer open, `behind == 0`, and nothing older in `held` or in the burst `ahead` of it that `REACH`/`Server::can_reach` cannot clear (a watcher event still does not hold a colour; a settings push now does — before, a notification naming no buffer passed for harmless, QA's S1). What stays the colours' own (`viewport.rs`): `colours_may_go_ahead` (without `refreshSupport` only `range` goes), a dirty buffer waits instead of being analyzed, they go during staging, never ahead of a notification about to be applied (`answer_ahead_of` takes `same_file` requests only), and `coloured_ahead` marks a range taken off an unsettled index. Reads that one `Document`, its overlay as of the last publish, `has_large_documents`/`Document::large`/`token_server_cancel`, and the remembered tokens — never the index, another buffer, a flush or a publish. Every whole answer goes through `remember_tokens`, so a `previousResultId` always names data the client holds. Responses leave out of arrival order for these three methods and fast-actions' `same_file::METHODS` only. |
|
||||
| `viewport-highlight ──▶ index-scope / scan-interleave` (widen and refresh) | depends | A `didOpen` that widens is applied through `open_then_widen`: `Viewport::defers_widen` records the widen, the burst's colouring requests are answered, then `reindex_widened` runs and `answer_ahead_mid_widen` (`server/ahead.rs`, 0.65.11; `answer_colours_mid_widen` before) drains between files (what can go ahead answered — colours and, since 0.65.11, `same_file` requests — everything else to `held`). `refresh_tokens_if_stale`, called by `run` once `held` is empty, sends at most one `workspace/semanticTokens/refresh` per `hierarchy_revision`, only if a buffer answered while `index_unsettled` (scan running/owed, `Viewport::widening`, or — since 0.65.11 — anything held) would colour differently (`early`) or was painted by a range (`guessed`). `semantic_tokens_in_range` classifies the range's lines (`large::line_window`, `overrides_within`) and still equals the full answer filtered. |
|
||||
| `ifdef-folding ──▶ references-nav (folding) / editor-scopes / large-file-mode` | depends | (2026-11-19, TODO §71.4, 0.65.4) `folding/directives.rs::branch_spans` reads the lexer's `TokenKind::Directive` tokens (so comments, strings and `` `define `` bodies never fold) and yields one `region` fold per `` `ifdef ``/`` `ifndef ``/`` `elsif ``/`` `else `` branch; `folding_ranges` = `scope_and_comment_folds` (the old answer, verbatim) + `branch_folds` (dropping any `(start, end)` an existing fold has), merged by `in_answer_order` (start line, existing first on a tie). Sticky scroll pins the branch line through the extension's `foldingProviderModel` (§67). A large buffer has no tokens and still answers `[]`. The directive-word rule is a private copy (also in `parser/directive.rs` and `on_type/auto_end.rs`). |
|
||||
| `comment-highlighting ◀──▶ editor-packaging` (grammar) | handshake | (2026-11-19, TODO §71.8, 0.65.3) Extension only: `commentScan.js` re-implements the grammar's `comments` and `strings` rules to find comment bodies; `commentScan_test.js` fails on any change to those two rules, on a reordering that moves them off the top, or on another top-level rule that could match `/` or `"` — a grammar edit updates `commentScan.js` in the same change (the `tests/grammar.rs` keyword lock is separate and untouched). `commentKeywords.js` paints visible lines ±50, honours `editor.maxTokenizationLineLength`. Server side: nothing — the three `lucisv.commentKeywords.*` keys arrive in `didChangeConfiguration` and `settings.rs` ignores them; semantic tokens were measured to colour nothing inside a comment. |
|
||||
| `format-styles ◀──▶ editor-settings / format-cache / selection-formatting / on-type-formatting` | handshake | (2026-11-19, TODO §71.5, 0.65.5) One name list, three pins: `PRESETS` (`vlog_formatter/src/style.rs`) + `auto` = `lucisv_core::config::STYLE_NAMES` (`args::tests::the_core_style_names_are_the_formatter_presets`) = the manifest's `lucisv.format.style` enum and descriptions (`settings::tests::the_style_drop_down_is_the_style_names`). Ladder: explicit `indent`/`line-length` over the style's numbers; `lucisv.toml` over the editor. Server: `auto_style.rs::AutoStyles` remembers per document the preset `format_auto` chose; whole-document formats set it, range/ranges/on-type/selection reuse it (`concrete`); forgotten on open/close/rename/delete, a whole-buffer replacement, a named-style format, any settings change and a `lucisv.toml` event — three call lines in `notification.rs` (`notice`, `changed`, `forget_all`). The cache entry carries the style, so changing it invalidates verdicts. |
|
||||
| `hierarchy-current-path ──▶ vscode-hierarchy-sidebar / dut-hierarchy` | depends | (2026-11-19, TODO §71.6, 0.65.2) Extension only, no server request: `hierarchyCurrent.js` (`matchingFiles`, `currentPath` — BFS up `hierarchySections.parentIndex`, nearer distance wins — `rowLevels`, `levelChanges`, `LIT_COLORS`/`litLevel`/`cssVariableFor`) reads the schema-2 snapshot's `definition.file`. `hierarchyView.js` follows `onDidChangeActiveTextEditor` and posts `{type:'lit', changes}`; a rendered row carries `lit: 0..4` only when lit, so an unlit pane's rows are byte-identical to before. `media/hierarchy.{js,css}` set `data-lit`. Matching compares the model's URIs, so a case-differing folder or a UNC path (server `uri.rs` writes `file:////srv/…`) never lights. |
|
||||
| `fast-actions ◀──▶ scan-ordering / viewport-highlight / large-file-mode / cancel-request` | handshake | (2026-11-19, TODO §71.2, 0.65.11) **A request whose whole answer is its buffer's is answered from it at once, even while a scan holds everything else, and its answer is the settled answer.** The precondition is stated once, on `Server::answer_from_the_buffer` (`server/ahead.rs`), the one function that decides: for the buffer the request names (a) it is open; (b) every older client message that can change what the handler reads is applied — `nothing_unapplied_for` reads `held` and the burst `ahead` through `Server::can_reach`, and requires `behind == 0`; (c) its analysis is current — a dirty buffer is analyzed for its own request alone (`Server::flush_buffer`, `server/diagnostics.rs`), a colouring request on a dirty buffer waits; (d) no settings are awaited (`settings_awaited` = `staging` or `Server::settings_announced`, the pull an empty `didChangeConfiguration` caused); (e) the answer is the buffer's alone — `same_file::answered_by_the_buffer` (`same_file.rs`, twelve `METHODS`; completion, inlay hints, code lenses, links and every workspace-wide request always wait) or `viewport.rs`'s rule for colours. Where a request is offered: `process_batch` → `answered_ahead`, `set_aside`, `answer_ahead_of` (behind the next notification of its own burst, `same_file` requests only), `open_then_widen`, `answer_ahead_mid_widen`, `answer_held_ahead` (when the startup's settings land) — the same function at each. **`ahead::REACH`** is one row per notification `handle_notification` handles (`Reach::{Nothing, Named, Any}`); a method without a row reaches `Any`, so **a new notification arm needs a `REACH` row — the default is wait** — and `every_notification_the_server_handles_says_which_buffers_it_can_reach` fails until it has one; a handler that starts changing a buffer it does not name must move its row to `Any`; a new `Pending` kind must be classified in `can_reach` (exhaustive `match`). **With viewport-highlight:** the early-answer path moved from `viewport.rs` to `ahead.rs` and the colours share it (row above). **With scan-ordering (amended):** the client's answer to a settings pull is ordered like a notification (`owes_a_state_change`); every other response stays exempt. **With large-file-mode:** `reclassify_large_buffers` (`server/large_file.rs`, called from `apply_settings`) re-analyzes every clean open buffer a new `largeFile.threshold` classifies differently and re-requests colours — a new threshold no longer waits for each buffer's next edit (large-file-mode's prose saying so is stale, its test renamed). Responses for the early kinds go out ahead of older held requests (allowed by the spec); a burst's cancel is honoured where it goes ahead. Proof: `server/tests/fast_actions_differential.rs` (early == settled), `fast_actions_bursts.rs` (the burst differential; its oracle's weakness is §2.9-62). |
|
||||
| `fast-actions (related tier, payload) ◀──▶ completion-core / fuzzy-completion / member-completion` | handshake | (2026-11-19, TODO §71.2, 0.65.11) `completion/related.rs`: a tier between the file's own (`1`–`3`) and the workspace's, sortText `4` (`TIER_RELATED`); index `4→5`, templates `5→6`, keywords `6→7`, project words `7→8` (`tests/e2e.rs`'s digits moved). Its sources: the members of every package the scope chain at the cursor imports (`WorkspaceIndex::members_of`; a wildcard all, an explicit import the one it names), the members the enclosing class inherits (`members_of_chain`), and after a backtick the `` `define``s of the headers the buffer's `` `include``s reach (`includes::reachable_from` → `WorkspaceIndex::defines`); prefix and fuzzy rules as the other tiers. **No item is taken away:** a related item does not count against `LIMIT` (`Items::related`) and a name it claims is skipped by later tiers without being counted, so every label of the 0.65.10 answer is still offered with the same edit and format; what changes for a claimed name is its icon and detail (the declaration the file is related to). Own cap `RELATED_LIMIT` (256), past which the answer is `isIncomplete`. `completion/wire.rs`: for a client listing `editRange` and `insertTextFormat` in `completionList.itemDefaults` (`ClientAbilities::completion_item_defaults`, read in `main.rs` by `completion::item_defaults_support`), `with_item_defaults` rewrites the serialized list — lossless, an item keeps its own edit or format when it differs; done on JSON because `lsp-types` 0.97 has neither field. Completion is never answered early (every path reads the index). `completionItem/resolve` is measured, not built. |
|
||||
|
||||
### 2.8 Packaging & release lane
|
||||
|
||||
@@ -666,6 +712,9 @@ engine-lane features are listed above; this table is the server-internal web.
|
||||
| `release-prep / editor-platform-vsix ──▶ lucisv-mcp` (mcp-packaging) | depends | `release.sh` builds `-p lucisv_mcp` for every triple and stages it as the THIRD `bin/` entry (fifteen in the `all` package); `expect_vsix_bins` and `audit_artifacts.sh` pin the name; the seven `.vsix` names are unchanged. `mcp_smoke.js` is the gate beside `smoke.js`. |
|
||||
| `lucisv-mcp ──▶ lucisv-server` (index cache, M6) | depends (read-only) | MCP reads the server's `index-cache` store read-only when `--index-cache DIR` names it (header `CACHE_FORMAT`/`FACTS_FORMAT`/version must match, else ignored) and writes its own `index-cache-mcp` beside it; it never writes the server's file. A codec change on the server side costs MCP its warm start, never its correctness. |
|
||||
| `editor-packaging ◀──▶ lucisv-mcp` (mcp-read-only, M8) | handshake | The read-only mode (2026-09-29, PLAN §11): setting `lucisv.mcp.mode` (`"full"` default / `"read-only"`) appends `--read-only` to the spawn args and labels the definition `lucisv read-only (<folder>)`; copy-config keys it `lucisv-ro`. The binary then lists exactly `hierarchy, find, outline, read, check` (≤ 1 800 model-visible bytes, instructions ≤ 300), answers the four edit names with `-32602` `unknown tool: NAME (the server runs --read-only)`, and writes nothing inside a root (`tests/read_only.rs`); full mode is byte-identical to 0.58.0. `mcp_smoke.js --read-only` is the second MCP gate in `release.sh`, host and embedded. |
|
||||
| `release-gates ──▶ release-prep` (`cross` step) | depends | (0.65.7) `cargo check --target x86_64-pc-windows-gnu --target x86_64-unknown-linux-musl -p lucisv -p lucisv_server -p lucisv_mcp`, with the rustup toolchain `release.sh --cross` uses (`~/.rustup/toolchains/stable-aarch64-apple-darwin`). Binaries only, not `--all-targets`, so test-only platform code is not checked (§2.9-56). **Skipped with a note, not failed, when that toolchain is absent** — a gate run on a machine without it does not prove the cross build (§2.9-66). |
|
||||
| `ci.yml linux job ◀──▶ tools/linux_check.sh` | handshake | (0.65.9, TODO §70) `ci.yml`'s `linux` job (`runs-on: linux-x64`, the luhpe runner, as root, 4 CPU / 8 GB, rustup per job, cold build) runs `cargo clippy --all-targets -- -D warnings` and `cargo test --workspace`. `tools/linux_check.sh [--user] [--dry-run]` runs a command against the working tree in the same job image without a push (tracked + unignored untracked files, one run at a time). The suite is root-safe: permission tests probe whether modes bind and say `skipped:` when not; growth tests bound ratios, not wall clock. Linux is tested on push, but releases are gated on macOS only (§2.9-57). |
|
||||
| `lucisv-mcp ──▶ filesystem` (`project/files.rs` stamp) | depends | (0.65.9) A held file is current when size, mtime and `identity` (ctime + inode, `Option` — `None` on Windows) match its `Stamp`; any trusted timestamp within `RACY` (3 s) of `read_at`, or a wall clock that stepped back since the read (`read_mono`), makes it `Change::Suspect` and it is re-read and re-hashed (git's racily-clean rule, now over ctime too). Known blind spots, in `docs/features/mcp-transport`: on Windows a same-size rewrite restoring an mtime > 3 s old; writes through a memory map not yet reflected in timestamps; future mtimes re-read on every call (§2.9-54). The server's index cache and the `index-cache-mcp` store contract are unchanged. |
|
||||
|
||||
### 2.9 Open handshakes (filed, not yet delivered — claim before working)
|
||||
|
||||
@@ -717,6 +766,29 @@ update the filing README(s) and this file.
|
||||
| 41 | **MCP-13 → `vlog_linter`:** a forced deletion of a non-ANSI body port leaves a header port with no direction and no lint reports it | mcp-structural-edits | vlog_linter |
|
||||
| 42 | **Parser leniency → `vlog_parser`:** a trailing `,` in a named connection list, an empty concatenation element `{d,, d}`, and `type(x)'(y)` in a connection parse without a diagnostic (the rename verifier's position rule covers the rename; every other splice contract is exposed) | refactor-rename (M3.5) | vlog_parser |
|
||||
| ~~43~~ | ~~**MCP-14 → `vlog_refactor`/`vlog_semantic`:** rename of a generate block label leaves hierarchical paths through it unrewritten and `find_references` does not report them — vlog_refactor/vlog_semantic; the MCP layer refuses the rename; the LSP still allows it~~ — **closed 2026-09-30 by generate-label-rename (TODO §65.1, 0.60.0):** the gap was resolution, not the rename — `vlog_semantic` now declares a `for` block's label in the enclosing scope (the genvar stays in the header), treats `generate … endgenerate` as no scope, gives a named block a member scope, walks an index in a path as the name it indexes, and puts blocks on a module's hierarchical surface with their members under the synthesized key `module.label` (`FACTS_FORMAT` 21; `Semantics::member_key`, which `lucisv_server/src/nav.rs` now asks with). Every segment — bare, indexed, nested, cross-file — and the closing label are ordinary references, so `find_references`, `rename` (LSP, CLI engine, MCP) and the verifier's unchanged resolution print all see them; no verifier normalization was added, eight attacks pin that (`check/qa_block_paths.rs`). `lucisv-mcp`'s `block` refusal is lifted. Also answers row 40's second half (`gen_l[0].z` is found). | mcp-lean-catalogue | vlog_refactor, vlog_semantic |
|
||||
| 44 | **A comment between a generate `end` and `else`** (also a trailing `// c` after a labelled generate `end` before `else`) is a verification error, so the file is left unformatted — the safety net works, the formatter should not need it. Present in 0.65.4 (TODO §71 wave 4) | format-styles (QA) | vlog_parser / vlog_formatter |
|
||||
| 45 | **`` `ifdef `` between `end` and `else` is a parse error** (TODO §71 wave 4) | format-styles (QA) | vlog_parser |
|
||||
| 46 | **An attribute on an ANSI port** (`(* keep *) input a`) is a parse error (TODO §71 wave 4) | format-styles (QA) | vlog_parser |
|
||||
| 47 | **Multi-instance declarations under one-per-line styles** (`p1 u8 (...), u9 (...)`) get the hanging layout instead of the style's (TODO §71 wave 4; CHANGELOG 0.65.5 known limit) | format-styles (QA) | vlog_formatter |
|
||||
| 48 | **Directory-only watcher events.** VS Code coalesces deletes under a removed folder into one folder event and the client's `**/*.{v,vh,sv,svh}` filter drops it, so the server receives nothing; a folder moved in is dropped likewise. Wanted: a second registration (`**/*`, `Create \| Delete`) and a handler expanding a folder to the held files and include lines under it — changes every client's registration and traffic, the owner's call (TODO §71 waves 5–6) | localized-reindex (QA P1); scan-ordering | owner decision, then lucisv_server (`main.rs`/`watch.rs`) |
|
||||
| 49 | **A buffer the scope would not take stays indexed after `didClose`** (excluded or unlisted, taken in by a scan or the one-file path), and **closing an unsaved in-scope buffer a rescan indexed leaves its text in the index** (QA-7a). One root: a close does not touch the index. A one-file remove costs ~225 ms on OpenTitan (fixed and reverted in scan-ordering); wanted: a cheap removal, e.g. a tombstone the next scan or publish folds in (TODO §71 waves 5–6) | localized-reindex (QA P2); scan-ordering (QA-1, QA-7a) | vlog_semantic (index removal) / lucisv_server (`state/`) |
|
||||
| 50 | **An unheld buffer opened while a scan runs is never taken in** by that scan or afterwards; opened before the scan it is held — the same final state answers differently by timing (TODO §71 wave 6) | scan-ordering (QA-2) | lucisv_server (`state/scan.rs`, `server/index.rs`) |
|
||||
| 51 | **Symlinked files are held under one spelling or both** depending on what was open at scan time (`discover.rs`'s `Aliased`); incremental and rebuild answers disagree in all six `filelink.py` variants. Rule to adopt: one file, one spelling, whatever is open — in the walk, the overlay and the one-file path together (TODO §71 waves 5–6) | localized-reindex (QA P3); scan-ordering | lucisv_server (`state/discover.rs`, `state/incremental.rs`) |
|
||||
| 52 | **A request held during a scan is answered against the newest text**, so a position-based request can resolve a different symbol when an edit moved the text under it; rename edits carry no document version for the client to reject (TODO §71 wave 6) | scan-ordering (QA) | lucisv_server (`server/`, `rename.rs`) |
|
||||
| 53 | **Renaming a port of a module defined twice** gives an edit or a refusal at random across fresh servers (`top_englishbreakfast/ip/ast/rtl/adc.sv:81`, `qa717/drv/dup.py`); not diagnosed (TODO §71 wave 6) | scan-ordering (QA-7c) | vlog_refactor / lucisv_server (`module_select.rs`) — undiagnosed |
|
||||
| 54 | **`lucisv-mcp` re-reads a file with a future mtime on every call**, forever (67 ms against 7 ms per `find` on 4 000 files) — the racy rule never settles (TODO §70) | linux-test-portability (Round 2) | lucisv_mcp (`project/files.rs`) |
|
||||
| 55 | `crates/lucisv/tests/cli.rs:2149` (`a_stdin_buffer_reads_the_rule_options_too`) asserts only an empty stdout, no exit code (TODO §70) | linux-test-portability (Round 2) | crates/lucisv (tests) |
|
||||
| 56 | `crates/lucisv_mcp/tests/qa_m3.rs` uses `std::os::unix` with no `cfg`, so `cargo check --all-targets` for Windows fails (tests only; the `cross` gate checks binaries only) (TODO §70) | linux-test-portability (Round 2) | lucisv_mcp (tests) |
|
||||
| 57 | **Releases are gated on macOS alone**: Linux runs the suite in `ci.yml` but the release does not wait for it, and Windows is compile-checked (`cross`), never executed (TODO §70) | linux-test-portability (Round 2) | tools/ + CI (lead) |
|
||||
| 58 | **The discovery walk at the start of every scan drains nothing** (25–80 ms on OpenTitan): what is left of the first-colour wait in workspace scope (62–86 ms late open) and the rescan hold (70–159 ms). Wanted: a resumable walk in `state/discover.rs` (it holds `&mut Workspace` throughout `begin_scan`), with its own identical-result proof (TODO §71 wave 7) | viewport-highlight (Handshake request 2) | lucisv_server (`state/discover.rs`) |
|
||||
| 59 | **A `range` answered during a rescan always counts as a guess** (`Viewport::guessed`) and costs one refresh at settle even when nothing changed (TODO §71 wave 7) | viewport-highlight (QA) | lucisv_server (`server/viewport.rs`) |
|
||||
| 60 | **An edit in one file that changes how another open file colours sends no refresh** (a package type renamed) — as before this lane (TODO §71 wave 7) | viewport-highlight | lucisv_server (`server/viewport.rs`) |
|
||||
| 61 | **Inside the startup settings wait, the client's answer to the pull is applied ahead of an older settings push held with it** (`server/startup.rs`, `take_the_answer_out_of_held`); predates fast-actions; needs a client whose push and answer disagree in one burst (TODO §71 wave 8; fast-actions QA F1) | fast-actions (QA) | lucisv_server (`server/startup.rs`) |
|
||||
| 62 | **`tests/fast_actions_bursts.rs`'s oracle accepts an answer the reference gives after any later message of the round**: 2–9 % of injected stale answers pass when a later message restores the state; every mutation is still caught and the directed tests lack the weakness (TODO §71 wave 8; fast-actions QA F4) | fast-actions (QA) | lucisv_server (tests) |
|
||||
| 63 | **Whether a large open buffer is in the index depends on when it was opened, saved or scanned** — a fast-path buffer contributes nothing when open at scan or save time but keeps its disk record when opened after the scan; 77–98 answers differ between a settled session and a fresh server on OpenTitan. Predates fast-actions; wanted: always keep, or always drop, the disk record of a fast-path buffer at open, save, flip and scan alike (TODO §71 wave 8; fast-actions QA S2, Handshake request 8) | fast-actions (QA) | lucisv_server (`state/`, the index lane) |
|
||||
| 64 | **The 40 000-file rescan after a delete takes either 12.3 s or 14.5–15.5 s**, on 0.65.10 and 0.65.11 alike; cause not found (TODO §71 wave 8) | fast-actions | undiagnosed (lucisv_server scan) |
|
||||
| 65 | **`ci.yml` runs `cargo test --workspace` bare in both jobs**, not through `tools/guard.sh` as CLAUDE.md's runaway guard asks of every `cargo test`; predates 0.65.9 for the macOS job, the Linux runner is resource-capped. Recorded, not judged (topo refresh 2026-11-19) | topo refresh (draft discrepancy 10) | CI (lead) |
|
||||
| 66 | **The `cross` gate step reports `SKIPPED (no toolchain)` rather than failing** when `~/.rustup/toolchains/stable-aarch64-apple-darwin` is absent, so a green `gates.sh` on another machine does not prove the cross build (topo refresh 2026-11-19) | topo refresh (draft discrepancy 11) | tools/ (`gates.sh`, lead) |
|
||||
|
||||
---
|
||||
|
||||
@@ -736,15 +808,16 @@ untouched, reusing existing arms.
|
||||
| module | features whose home it is |
|
||||
|---|---|
|
||||
| `vlog_parser` | spans, name-spans, recursion-limit, error-recovery, define-table, lexer-cleanup, decomposition-parser, and the grammar lane: *macro-items*, *classes*, *bind*, *dynamic-types*, *types-decls*, *item-misc*, *directives-in-lists*, *directives-in-instances*, *dpi-export*, *assertions*, *interfaces*, *expressions-2*, *dv-statements*, *mop-up-2*, *directive-split*, *ansi-first-port*, *null-items*, *constraint-bodies*, *covergroup-bodies*, *fragment-mode*, *vendor-formal-grammar*, *comment-slots*, *bind-semantics*, *sva-bodies* (most also add formatter arms — parser+formatter pairs by default; directive-split and ansi-first-port reused existing arms and left `vlog_formatter/src` untouched) |
|
||||
| `vlog_formatter` | safety-net (`verify.rs`), case-tables, formatter-bug-fixes, corpus-bugs, comments-round, comments-round-2, alignment (`align.rs`), format-fences (`fence.rs`), range-formatting (`range.rs`), shared-fence-filter, decomposition-formatter, and the layout halves of constraint-bodies, covergroup-bodies, comment-slots, bind-semantics and sva-bodies (`format/`) |
|
||||
| `vlog_semantic` | vlog-semantic (`bind/`, `resolve.rs`, `model.rs`), workspace-index (`workspace/`), decomposition-semantic, class-semantics, interface-semantics, class-member-access, struct-members, overlay-promotion, port-detail-spans (`Symbol`/`Def::detail_span` and `Semantics::symbols_named`), hover-line-index (`DeclLines`, facts codec), vscode-hierarchy-sidebar's declaration/instance positions, scan-interleave (`WorkspaceIndex::absorb`), semantic-lints-on's word census, bind-semantics and sva-bodies, refactor-rename's performance amendment (`files_spelling`), plus the index halves of indexing-ux (`index_order`/`IndexBuilder`), index-scope (order-insensitive `finish`, facts-from-analysis), incremental-index (`update_file`, edge/reference tables, `instantiations.rs`, `classes.rs`), index-persistence (`facts.rs`; `FACTS_FORMAT` 19; plus a small `vlog_parser::defines` touch — `DefineTable::from_entries`, `Eq` derives) |
|
||||
| `vlog_formatter` | safety-net (`verify.rs`), case-tables, formatter-bug-fixes, corpus-bugs, comments-round, comments-round-2, alignment (`align.rs`), format-fences (`fence.rs`), range-formatting (`range.rs`), shared-fence-filter, decomposition-formatter, and the layout halves of constraint-bodies, covergroup-bodies, comment-slots, bind-semantics and sva-bodies (`format/`), format-styles (`style.rs`, `auto.rs`, `align.rs` mode) |
|
||||
| `vlog_semantic` | vlog-semantic (`bind/`, `resolve.rs`, `model.rs`), workspace-index (`workspace/`), decomposition-semantic, class-semantics, interface-semantics, class-member-access, struct-members, overlay-promotion, port-detail-spans (`Symbol`/`Def::detail_span` and `Semantics::symbols_named`), hover-line-index (`DeclLines`, facts codec), vscode-hierarchy-sidebar's declaration/instance positions, scan-interleave (`WorkspaceIndex::absorb`), semantic-lints-on's word census, bind-semantics and sva-bodies, refactor-rename's performance amendment (`files_spelling`), plus the index halves of indexing-ux (`index_order`/`IndexBuilder`), index-scope (order-insensitive `finish`, facts-from-analysis), incremental-index (`update_file`, edge/reference tables, `instantiations.rs`, `classes.rs`), index-persistence (`facts.rs`; `FACTS_FORMAT` 22; plus a small `vlog_parser::defines` touch — `DefineTable::from_entries`, `Eq` derives), localized-reindex (`workspace/{dependents,references,replace}.rs`) |
|
||||
| `vlog_linter` | linter-core, lint-harness, lint-rules-2, semantic-lints (`signals.rs`), semantic-lints-on (workspace oracle), one-parse (`context.rs`) |
|
||||
| `vlog_refactor` | refactor (plan), refactor-rename (including `prepare_rename_here` / `rename_name_at` selector half), refactor-ports (including module-target selectors), refactor-instantiate, references-nav (whole-scope equivalence oracle), and the refactor half of decomposition-semantic; expand-wildcard and convert-to-ansi (`ports/`), organize-imports (`imports.rs`), extract-inline-module (`extract/`, `inline/`, `check/ledger.rs`) |
|
||||
| `lucisv_core` | lucisv-core-lift (`config.rs`, `walk.rs`), filelist (`filelist.rs`), format-cache (`cache.rs`) |
|
||||
| `lucisv` (CLI) | cli-polish, config-discovery (wiring), parallel-files, cli-filelist, linter-core (CLI half in `lint.rs`), one-parse (`lint.rs` parses once via `ParsedSource`), format-cache (wiring), release-prep (`--version` contract) |
|
||||
| `lucisv_server` | lucisv-server (trunk), decomposition-server (`server/`, `completion/`), and one or two modules per capability feature: editor-scopes→`pairs.rs`, filelist→scope ladder in `state.rs`, include-nav→`includes.rs`, completion-core/fuzzy-completion/member-completion→`completion/`+`candidates.rs`, completion-templates→`templates.rs`, inline-templates→`inline.rs`, inline-instantiation→`inline.rs`+`completion/`+`candidates.rs` (+`settings.rs` key), bind-semantics→`instantiate.rs`, macro-expansion→`expand.rs`, hierarchy→`hierarchy.rs`, vscode-hierarchy-sidebar→`design_hierarchy.rs`, type-hierarchy→`type_hierarchy.rs`, type-definition→`type_def.rs`, code-lens→`lens.rs`, inlay-hints→`inlay.rs`, server-lint→`lint.rs`+`lint/project.rs`+`code_action.rs`, one-parse→`lint.rs`+`state.rs` (`Document.tree`), refactor wiring/performance fan-outs→`rename.rs`/`ports.rs`+`state.rs`, apply-edit+folders-and-config+cancel-request+work-done-progress→`server/`, editor-settings+indexing-ux+index-scope+index-persistence→`settings.rs`+`state.rs`(+`index_cache.rs`), incremental-sync→`sync.rs`, file-watching→`watch.rs`, file-operations→`file_ops.rs` (+`include_sources` in `state.rs`), pull-diagnostics→`diagnostics.rs`+`server/`, semantic-tokens-delta→`tokens.rs`+`server/semantic_tokens.rs`, on-type-formatting→`on_type.rs`, will-save-wait-until→`format.rs` (+`settings.rs`/`main.rs`), selection-range→`selection.rs`, linked-editing→`linked.rs`, references-nav (server half)→`folding.rs`+`nav.rs`, large-file-mode→`large.rs`+`server/large_file.rs`, lsp-318-extras→`format.rs` (+`main.rs` capability), hover-declarations→`hover.rs`(+`nav.rs`), port-detail-spans (server half)→`hover.rs`+`nav.rs`, hover-line-index→`hover.rs`+`locate.rs`+`state.rs`, scan-interleave/change-debounce/verbose-timing→`server/`+`state.rs`, perf5-p1→`fences.rs` (+ the `_at` helpers in `ports.rs`/`imports.rs`/`extract.rs`/`inline_module.rs`), perf5-p2→`rename_trace.rs`+`module_select.rs`, perf5-p4→`scan_trace.rs`+`scan_order.rs`+`server/startup.rs`+`state/scan.rs`, perf5r-first-answer→`state/discover.rs` (+ counters and the compaction skip in `index_cache.rs`), perf measurements→`src/perf.rs` (`docs/perf/README.md`, not a feature README), interactive-latency→`state.rs` (the two token searches) + `selection.rs`/`on_type.rs`/`completion/`/`inline.rs` (their callers) + `src/perf.rs`/`tests/e2e.rs` (its measurements), editor-packaging (grammar test)→`tests/grammar.rs` |
|
||||
| `editors/vscode` | editor-packaging, editor-snippets, editor-settings (manifest half), editor-scopes (rainbow half), vscode-hierarchy-sidebar (`hierarchyView.js`/`hierarchyModel.js`), dut-hierarchy (`hierarchySections.js`), extract-inline-module (`extract.js`), editor-platform-vsix, editor-marketplace-page, index-persistence (`storagePath` line), verbose-timing (`lucisv.verbose`, spawn args and restart in `extension.js`) |
|
||||
| `tools/` + CI | corpus-check, release-prep, ci-release, editor-platform-vsix (staging), range-formatting (`lucisv-changed.sh`) |
|
||||
| `lucisv_core` | lucisv-core-lift (`config.rs`, `walk.rs`), filelist (`filelist.rs`), format-cache (`cache.rs`), format-styles (`STYLE_NAMES`, cache `style` field) |
|
||||
| `lucisv` (CLI) | cli-polish, config-discovery (wiring), parallel-files, cli-filelist, linter-core (CLI half in `lint.rs`), one-parse (`lint.rs` parses once via `ParsedSource`), format-cache (wiring), release-prep (`--version` contract), format-styles (`--style`) |
|
||||
| `lucisv_mcp` | the MCP block (`docs/features/mcp-*`), linux-test-portability Round 2 (`project/files.rs` stamp), format-styles (`format`/`diagnostics` take the style) |
|
||||
| `lucisv_server` | lucisv-server (trunk), decomposition-server (`server/`, `completion/`), and one or two modules per capability feature: editor-scopes→`pairs.rs`, filelist→scope ladder in `state.rs`, include-nav→`includes.rs`, completion-core/fuzzy-completion/member-completion→`completion/`+`candidates.rs`, completion-templates→`templates.rs`, inline-templates→`inline.rs`, inline-instantiation→`inline.rs`+`completion/`+`candidates.rs` (+`settings.rs` key), bind-semantics→`instantiate.rs`, macro-expansion→`expand.rs`, hierarchy→`hierarchy.rs`, vscode-hierarchy-sidebar→`design_hierarchy.rs`, type-hierarchy→`type_hierarchy.rs`, type-definition→`type_def.rs`, code-lens→`lens.rs`, inlay-hints→`inlay.rs`, server-lint→`lint.rs`+`lint/project.rs`+`code_action.rs`, one-parse→`lint.rs`+`state.rs` (`Document.tree`), refactor wiring/performance fan-outs→`rename.rs`/`ports.rs`+`state.rs`, apply-edit+folders-and-config+cancel-request+work-done-progress→`server/`, editor-settings+indexing-ux+index-scope+index-persistence→`settings.rs`+`state.rs`(+`index_cache.rs`), incremental-sync→`sync.rs`, file-watching→`watch.rs`, file-operations→`file_ops.rs` (+`include_sources` in `state.rs`), pull-diagnostics→`diagnostics.rs`+`server/`, semantic-tokens-delta→`tokens.rs`+`server/semantic_tokens.rs`, on-type-formatting→`on_type.rs`, will-save-wait-until→`format.rs` (+`settings.rs`/`main.rs`), selection-range→`selection.rs`, linked-editing→`linked.rs`, references-nav (server half)→`folding.rs`+`nav.rs`, large-file-mode→`large.rs`+`server/large_file.rs`, lsp-318-extras→`format.rs` (+`main.rs` capability), hover-declarations→`hover.rs`(+`nav.rs`), port-detail-spans (server half)→`hover.rs`+`nav.rs`, hover-line-index→`hover.rs`+`locate.rs`+`state.rs`, scan-interleave/change-debounce/verbose-timing→`server/`+`state.rs`, perf5-p1→`fences.rs` (+ the `_at` helpers in `ports.rs`/`imports.rs`/`extract.rs`/`inline_module.rs`), perf5-p2→`rename_trace.rs`+`module_select.rs`, perf5-p4→`scan_trace.rs`+`scan_order.rs`+`server/startup.rs`+`state/scan.rs`, perf5r-first-answer→`state/discover.rs` (+ counters and the compaction skip in `index_cache.rs`), perf measurements→`src/perf.rs` (`docs/perf/README.md`, not a feature README), interactive-latency→`state.rs` (the two token searches) + `selection.rs`/`on_type.rs`/`completion/`/`inline.rs` (their callers) + `src/perf.rs`/`tests/e2e.rs` (its measurements), editor-packaging (grammar test)→`tests/grammar.rs`, localized-reindex→`state/incremental.rs`+`state/watched.rs`+`watch.rs`+`includes.rs`+`candidates.rs`+`server/index.rs`, scan-ordering→`server/mod.rs`+`server/batch.rs`+`caret.rs`+`server/dispatch.rs`, viewport-highlight→`server/viewport.rs`+`tokens/`+`large.rs`+`server/index.rs`, ifdef-folding→`folding/directives.rs`, format-styles (server half)→`auto_style.rs`+`server/formatting.rs`+`settings.rs`+`lint.rs`, fast-actions→`server/ahead.rs`+`same_file.rs`+`completion/related.rs`+`completion/wire.rs` (+ `flush_buffer` in `server/diagnostics.rs`, `reclassify_large_buffers` in `server/large_file.rs`, `owes_a_state_change`/`settings_announced` in `server/mod.rs`) |
|
||||
| `editors/vscode` | editor-packaging, editor-snippets, editor-settings (manifest half), editor-scopes (rainbow half), vscode-hierarchy-sidebar (`hierarchyView.js`/`hierarchyModel.js`), dut-hierarchy (`hierarchySections.js`), extract-inline-module (`extract.js`), editor-platform-vsix, editor-marketplace-page, index-persistence (`storagePath` line), verbose-timing (`lucisv.verbose`, spawn args and restart in `extension.js`), hierarchy-current-path (`hierarchyCurrent.js`, `media/hierarchy.*`), comment-highlighting (`commentScan.js`, `commentKeywords.js`), format-styles (`lucisv.format.style`), scan-ordering (`referencesView.js`) |
|
||||
| `tools/` + CI | corpus-check, release-prep, ci-release, editor-platform-vsix (staging), range-formatting (`lucisv-changed.sh`), release-gates (`gates.sh`, `release.yml`), linux-test-portability (`linux_check.sh`, `ci.yml` `linux` job) |
|
||||
|
||||
### 3.2 The combined picture
|
||||
|
||||
@@ -828,18 +901,27 @@ ownership explicitly.
|
||||
| `vlog_formatter/src/verify.rs` | safety-net | every formatter feature; the CLI's exit-2 promise | CLAUDE.md invariant #4. Never widen a normalization without masked-corruption attack tests; the standing pattern is "untouched + rejection tests anyway". The single widening in history is macro-items' backtick-`Ident` arm in `normalize` — which produced lucisv's one real corruption; its repair, `trim_lines_outside_strings`, is a *narrowing*, and the pattern to copy: the widening shipped without attack tests, the fix shipped with them. `line_starts_inside_string` is the one definition of "which line breaks are data" — both `format/` and `verify.rs` must read it. |
|
||||
| `vlog_formatter/src/fence.rs` | format-fences | range-formatting, shared-fence-filter, CLI `--fix` (`lucisv/src/lint.rs`), server quick fixes (`lucisv_server/src/lint.rs`) | `protected_regions`/`is_protected` are the **only** supported way to ask "may an automatic edit touch these bytes". One answer, **two** front ends — and `vlog_linter` is deliberately not one of them (it stays fence-blind; the filter lives in each front end). Class and statement scopes are supported by statement-fences (§2.9-3 delivered); `range::plan` must merge these protected spans with unselected runs. Port and case-label lists remain outside independent fence scopes. |
|
||||
| `lucisv_server/src/pairs.rs` | editor-scopes | documentHighlight, missing-closer diagnostics, scopePairs rainbow, folding, completion gates, on-type indent, inline-templates, expand-selection (`selection.rs`) | The `RULES` table + no-closer guard list is shared truth. Any keyword added to/removed from `token.rs` requires re-checking it (a word that stops being a keyword silently stops being matched). |
|
||||
| `lucisv_server/src/server/` | lucisv-server; amended by cancel-request, change-debounce, scan-interleave, index-scope, verbose-timing | every request/notification and every rebuild trigger | One ordered loop owns all mutable server state. A startup scan may publish a prefix and answer queued work between files; a request queued behind a rescan trigger is held until that rescan lands, and its cancel travels with it. Never make the distinction time-based: machine load must not change which index a request sees. Verbose timing may observe each wrapper/lifecycle but must be entirely silent when off and must not move protocol ordering. The queue thread only forwards protocol messages and must never parse. |
|
||||
| `lucisv_server/src/state.rs` | lucisv-server; amended by filelist, index-scope, scan-interleave, indexing-ux, incremental-index, index-persistence, hover-line-index, large-file-mode, one-parse (`Document.tree`), editor-settings + folders-and-config (`set_client_settings`/`change_roots`), include-nav (the include graph), completion-core (candidates), file-watching, interactive-latency (`first_token_reaching`/`first_token_from`), refactor performance fan-outs | every handler | `Workspace` is immutable through request handlers except the interior-mutable four-entry/8 MiB `FileView` cache. The scope ladder (filelist > `index.scope: "workspace"` > folder-scope at shipped depth 2; a rootless session never climbs; it reads flat at depth 0 and walks descendants at positive depth (including the default 2)) and open-buffer overlay are contracts. `Scan` has whole/widen shapes but one step/finish path; index/candidate/include prefixes publish together. `module_sources`, `rename_sources`, and `include_sources` must remain supersets of what their engines can edit/refuse over; `rename_sources` falls back to `sources()` when an ambiguous posting prevents a proven bound. `update_one` and a completed scan must equal a fresh build (`fingerprint`). Handlers reading `doc.text` instead of tokens/tree must check `doc.large`. **(2026-09-12)** `Document::new`'s derivations are individually traced (`lint_trace::Rebuild`), so a stage added to or removed from that constructor wants a `Rebuild` variant beside it. |
|
||||
| `lucisv_server/src/server/` | lucisv-server; amended by cancel-request, change-debounce, scan-interleave, index-scope, verbose-timing, scan-ordering, viewport-highlight, fast-actions | every request/notification and every rebuild trigger | One ordered loop owns all mutable server state. A startup scan may publish a prefix and answer queued work between files; a request queued behind a rescan trigger is held until that rescan lands, and its cancel travels with it. Never make the distinction time-based: machine load must not change which index a request sees. Verbose timing may observe each wrapper/lifecycle but must be entirely silent when off and must not move protocol ordering. The queue thread only forwards protocol messages and must never parse. No notification overtakes an older notification (`must_hold`; the answer to a settings pull counts as one, `owes_a_state_change`). The only requests answered out of arrival order are those `Server::answer_from_the_buffer` (`server/ahead.rs`) lets go: a text-current colouring request, or a `same_file` request whose answer is its buffer's. |
|
||||
| `lucisv_server/src/server/mod.rs` (`process_batch`, `must_wait`, `must_hold`, `behind`, `hold`) | scan-interleave; amended by scan-ordering, viewport-highlight, fast-actions (`owes_a_state_change`, `settings_announced`) | every client message; the early-answer path (`server/ahead.rs`) reads `held`/`behind`/`dirty`/`staging`/`pending` | Every client message goes through `process_batch`; nothing applies one around it. `must_hold` is the one ordering rule and `behind` its count; a new exemption is taken where requests are held, reads only what the exempted handler proves it needs, and states why that is valid between two scan files. |
|
||||
| `lucisv_server/src/server/index.rs` (`reindex_*`, `answer_what_is_waiting`, `BURST_DIVISOR`) | scan-interleave / index-scope; amended by localized-reindex, scan-ordering, viewport-highlight, format-styles (no lines) | saves, watcher events, widens, startup | localized-reindex owns the one-file/outside/burst decisions; scan-ordering owns hand-back (`opened_mid_scan`, once per file opened); viewport owns the widen deferral (`defers_widen`) and fast-actions the drain (`answer_ahead_mid_widen` in `server/ahead.rs`, `answer_colours_mid_widen` until 0.65.11). Two of those in one wave are not parallel. |
|
||||
| `lucisv_server/src/server/notification.rs` | lucisv-server; amended by localized-reindex, scan-ordering (`didOpen` arm), format-styles (three `auto_styles` calls), viewport-highlight (reads), fast-actions (`settings_announced`, `reclassify_large_buffers` from `apply_settings`) | every notification; `ahead::REACH` (one row per arm, test-pinned) | A notification arm is where state changes are *applied*, so scan-order effects (`head_owed`, `opened_mid_scan`) and per-document memories (`auto_styles`) are set here, never read off a batch. A new arm needs a `REACH` row in `server/ahead.rs` or the precondition test fails; until it has one it reaches `Any` (early answers wait behind it). A lane needing a line here asks the owning lane (format-styles' three lines were granted). |
|
||||
| `lucisv_server/src/server/dispatch.rs` (`symbol_offset`, `answer_flushed`) | lucisv-server; amended by scan-ordering, viewport-highlight, fast-actions | every request handler | A name-under-the-cursor request resolves through `symbol_offset`; a request with its own boundary rule keeps `offset` and says so in scan-ordering's table. `answer_flushed` is dispatch minus `flush_dirty` and must stay a pure split. A new request arm needs a row in fast-actions' README table (`same_file/tests.rs` reads the arms and fails otherwise) and stays out of `same_file::METHODS` unless its handler reads only the buffer. |
|
||||
| `lucisv_server/src/server/ahead.rs` (`answer_from_the_buffer`, `REACH`, `can_reach`) + `same_file.rs` | fast-actions (viewport-highlight's colour exemption moved here) | `process_batch`, `set_aside`, `answer_ahead_of`, `open_then_widen`, `answer_ahead_mid_widen`, `answer_held_ahead`; `viewport.rs` (`colours_may_go_ahead`, `coloured_ahead`); every `same_file` handler (hover, nav, symbols, folding, selection, linked editing, highlights, references, prepareRename, signature help) | The precondition is stated once, on `answer_from_the_buffer`, and nowhere else; a new place that offers a request early calls it, never a copy. `REACH` lists what is **proved** harmless — a notification without a row waits, a handler that starts touching a buffer it does not name moves its row to `Any`, a new `Pending` kind is classified in `can_reach`. `same_file::answered_by_the_buffer` must change with any handler arm that starts reading the index or the overlay; `fast_actions_differential.rs` (early == settled) is the alarm. |
|
||||
| `lucisv_server/src/state/` (`state.rs` until TODO §55) | lucisv-server; amended by filelist, index-scope, scan-interleave, indexing-ux, incremental-index, index-persistence, hover-line-index, large-file-mode, one-parse (`Document.tree`), editor-settings + folders-and-config (`set_client_settings`/`change_roots`), include-nav (the include graph), completion-core (candidates), file-watching, interactive-latency (`first_token_reaching`/`first_token_from`), refactor performance fan-outs | every handler | `Workspace` is immutable through request handlers except the interior-mutable four-entry/8 MiB `FileView` cache. The scope ladder (filelist > `index.scope: "workspace"` > folder-scope at shipped depth 2; a rootless session never climbs; it reads flat at depth 0 and walks descendants at positive depth (including the default 2)) and open-buffer overlay are contracts. `Scan` has whole/widen shapes but one step/finish path; index/candidate/include prefixes publish together. `module_sources`, `rename_sources`, and `include_sources` must remain supersets of what their engines can edit/refuse over; `rename_sources` falls back to `sources()` when an ambiguous posting prevents a proven bound. `update_one` and a completed scan must equal a fresh build (`fingerprint`). Handlers reading `doc.text` instead of tokens/tree must check `doc.large`. **(2026-09-12)** `Document::new`'s derivations are individually traced (`lint_trace::Rebuild`), so a stage added to or removed from that constructor wants a `Rebuild` variant beside it. |
|
||||
| `lucisv_server/src/settings.rs` | editor-settings | folders-and-config, indexing-ux, index-scope, index-persistence, inline-templates, will-save-wait-until, filelist, large-file-mode | One parser for both doors (push and pull, via `from_section` re-wrapping). Every key drops garbage independently; defaults that are not "silence" (1 MiB cap, log on, persist on, 4 MiB large-file threshold) are hand-written in `Default`. `set_client_settings` returns whether a reindex is owed — new keys must decide that question explicitly. |
|
||||
| `vlog_semantic/src/workspace/` (+ `facts.rs`) | workspace-index; extended by incremental-index, index-persistence, index-scope, hover-line-index, scan-interleave, member semantics, semantic-lints-on, bind-semantics, SVA bodies and refactor-rename performance | server state, hierarchy/lens/type-hierarchy, refactor, completion, semantic lints | Determinism (same inputs → same index, any order), the `paths` spelling coupling with `resolve.rs`, `FACTS_FORMAT` bumped on any codec change (current 19), edge/posting tables built by the same lifted walks the engines use. `DeclLines` must round-trip and participate in `fingerprint`; `absorb` must equal one build over the resulting record set; `files_spelling` must continue to include unresolved non-empty external/inherited paths or rename loses its dangling-use refusal; `FileFacts::words` is the shared project mention/completion census. |
|
||||
| `vlog_semantic/src/workspace/` (+ `facts.rs`) | workspace-index; extended by incremental-index, index-persistence, index-scope, hover-line-index, scan-interleave, member semantics, semantic-lints-on, bind-semantics, SVA bodies and refactor-rename performance | server state, hierarchy/lens/type-hierarchy, refactor, completion, semantic lints | Determinism (same inputs → same index, any order), the `paths` spelling coupling with `resolve.rs`, `FACTS_FORMAT` bumped on any codec change (current 22), edge/posting tables built by the same lifted walks the engines use. `DeclLines` must round-trip and participate in `fingerprint`; `absorb` must equal one build over the resulting record set; `files_spelling` must continue to include unresolved non-empty external/inherited paths or rename loses its dangling-use refusal; `FileFacts::words` is the shared project mention/completion census. |
|
||||
| `vlog_refactor/src/rename/` | refactor-rename; shared by references-nav and the performance wave | server rename/prepareRename/references and port refactor verification | `Scope` remains the whole-scope authority and `collect_occurrences` the one rename/references walk. The fast `prepare_rename_here` answer/refusal and `rename_name_at` target are parity contracts, not alternate semantics. Any new refusal must be expressible on the fast path or force a deferral; any new occurrence shape must be reflected in the server fan-out or trigger its all-sources fallback. |
|
||||
| `vlog_parser/src/token.rs` keyword table | completion-core (`KEYWORDS` export) | lexer, pairs.rs, editor grammar (test-locked), completion | Adding a keyword = lexer change + `pairs.rs` re-check + a hand edit to the grammar (`tests/grammar.rs` names the missing word) + potentially `verify.rs`-adjacent behavior. dv-statements added `randcase`/`let` to `is_keyword` and recorded it as shared with the adjacent lexer-cleanup round — the precedent for treating this file as coordinated even between back-to-back rounds. |
|
||||
| `editors/vscode/package.json` | editor-packaging | editor-settings, editor-scopes (colour ids), editor-snippets, index-persistence, verbose-timing, platform-vsix, marketplace-page | Settings/colour/snippet ids referenced from `extension.js` or the server must move in lockstep; mismatches are *silent* (VS Code ignores unknown ids). `lucisv.verbose` is special: it changes a spawn argument and therefore restarts the server instead of flowing through the ordinary settings push. Version number is one of the four version files. |
|
||||
| `tools/release.sh` artifact names | release-prep / editor-platform-vsix | ci-release (`prune_release_assets.sh`), `audit_artifacts.sh`, extension `bin/` layouts | Renaming a `.vsix` is a two-file change (`release.sh` + `prune_release_assets.sh`'s suffix list); renaming a per-triple binary is a two-file change (`release.sh` + `audit_artifacts.sh`, which skips `.vsix` and hard-fails on an unknown binary name). Get the wrong pair and the release fails by name. |
|
||||
| The frozen CLI contract | cli-polish | corpus scripts, CI users, every new CLI mode | Exit codes 0/1/2 forever; stdout stays machine-readable (JSON mode prints exactly one array; warnings to stderr). |
|
||||
| `editors/vscode/syntaxes/systemverilog.tmLanguage.json` | editor-packaging | `tests/grammar.rs` (keyword lock), `commentScan.js` (comment/string rules, `commentScan_test.js`) | Two locks: a keyword edit is checked against `KEYWORDS`; a `comments`/`strings` edit, a reorder of top-level rules, or a new top-level rule matching `/` or `"` must update `commentScan.js` in the same change. |
|
||||
| style name list (`style.rs` `PRESETS` + `auto`) | format-styles | core `STYLE_NAMES`/`parse_style`, cache `Entry::style`, CLI `--style`, MCP, server `settings.rs`/`auto_style.rs`/`lint.rs`, manifest enum | A preset added or renamed moves all of these; two tests pin the chain (`args.rs`, `settings.rs`). Only the default may never move a byte (corpus + OpenTitan proof). Extends the existing `Config` → core → CLI/server → cache boundary noted under §3.3. |
|
||||
|
||||
The 2026-09-07 size measurement in `CLAUDE.md` puts `state.rs` at 958
|
||||
production lines; its decomposition is deferred to Loop 3 (TODO §55).
|
||||
The 2026-09-07 size measurement in `CLAUDE.md` put `state.rs` at 958
|
||||
production lines; TODO §55 decomposed it into `state/` (2026-10-14, pure
|
||||
move; `state/mod.rs` 63 lines), and localized-reindex added
|
||||
`state/incremental.rs` and `state/watched.rs`.
|
||||
Additional shared boundaries are `vlog_refactor/src/check/ledger.rs` (every
|
||||
move/copy planner), `vlog_semantic/src/imports.rs` (linter and refactor usage
|
||||
agreement), and `Config` → core config → CLI/server settings → format cache
|
||||
|
||||
@@ -5,6 +5,57 @@ 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.66.0 — 2026-11-19
|
||||
|
||||
- **Rolls up 0.65.2–0.65.11:** saving no longer re-indexes the workspace;
|
||||
hover, definition, outline and colours for the open file do not wait for
|
||||
indexing; `` `ifdef `` branches fold; formatter styles (`auto`, `ansi`,
|
||||
`google`, `lowrisc`, `microsoft`, `nxp`); the module view marks the current file and
|
||||
its parents; Find References works with the caret just past a name;
|
||||
`TODO`/`FIXME`/`TBD` and your own keywords are highlighted in comments.
|
||||
|
||||
## 0.65.11 — 2026-11-19
|
||||
|
||||
- **Hover, go-to-definition, the outline and folding answer immediately for
|
||||
names declared in the file you are in,** even while a large project is
|
||||
being indexed or re-scanned: milliseconds instead of up to a second at
|
||||
startup, and a fraction of a second instead of 1–12 s during a re-scan.
|
||||
- **Completion lists what the file can actually reach first** — imported
|
||||
package members, inherited class members and macros from included
|
||||
headers — instead of losing them among a huge workspace's names.
|
||||
- **Changing `lucisv.largeFile.threshold` takes effect on open files at
|
||||
once.**
|
||||
|
||||
## 0.65.10 — 2026-11-19
|
||||
|
||||
- **Syntax colours appear immediately,** without waiting for the workspace to
|
||||
be indexed: 2–39 ms after opening a file on a large project instead of
|
||||
600–700 ms, and they no longer freeze for most of a second while the
|
||||
project is re-scanned.
|
||||
- **They sharpen once when indexing finishes.** Names defined in other files
|
||||
start as a best guess and are corrected by one refresh — including colours
|
||||
that previously stayed wrong until you edited the file.
|
||||
|
||||
## 0.65.9 — 2026-11-19
|
||||
|
||||
- **The bundled MCP server (`lucisv-mcp`) no longer answers from a file's old
|
||||
contents** after a same-size rewrite that restores its old modification
|
||||
time (`cp -p`, `rsync -t`) — a Linux timing hole in its change detection.
|
||||
- Nothing changes in the editor itself.
|
||||
|
||||
## 0.65.8 — 2026-11-19
|
||||
|
||||
- **Find All References works with the cursor just after a name** — after a
|
||||
double-click, or a click on the last letter. So do Go to Definition, hover,
|
||||
highlight and rename. (It used to say "No references found" until you
|
||||
clicked away and back.) Rows in the References view now open with the
|
||||
cursor at the start of the name.
|
||||
- **Typing while the workspace is indexing can no longer scramble the
|
||||
server's view of your file** (wrong symbols and diagnostics until the file
|
||||
was reopened).
|
||||
- **Opening files during startup no longer stalls indexing** for minutes on
|
||||
a large workspace.
|
||||
|
||||
## 0.65.7 — 2026-11-19
|
||||
|
||||
- **0.65.6, now for every platform.** 0.65.6 was never published — it did not
|
||||
|
||||
@@ -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.65.7**. Its platform packages include
|
||||
The current release is **0.66.0**. Its platform packages include
|
||||
`lucisv-server`, the `lucisv` command-line tool and `lucisv-mcp` (see
|
||||
[Agents (MCP)](#agents-mcp)):
|
||||
|
||||
@@ -440,6 +440,38 @@ default):
|
||||
}
|
||||
```
|
||||
|
||||
## Release 0.66.0 highlights
|
||||
|
||||
Version 0.66.0 completes a round of eight editor features: no workspace
|
||||
re-index on save, same-file actions and colours that do not wait for
|
||||
indexing, `` `ifdef `` folding, formatter styles, a module view that marks
|
||||
where you are, a Find References fix and comment keywords.
|
||||
|
||||
## Release 0.65.11 highlights
|
||||
|
||||
Version 0.65.11 answers hover, go-to-definition, the outline and folding for
|
||||
names declared in the current file without waiting for the workspace index,
|
||||
and puts the names a file can reach at the top of completion.
|
||||
|
||||
## Release 0.65.10 highlights
|
||||
|
||||
Version 0.65.10 colours a file the moment it opens instead of after the
|
||||
workspace is indexed, then corrects cross-file names once when indexing
|
||||
finishes.
|
||||
|
||||
## Release 0.65.9 highlights
|
||||
|
||||
Version 0.65.9 fixes the bundled MCP server answering from a file's old
|
||||
contents after a same-size rewrite that restores its old modification time
|
||||
on Linux; the editor features are unchanged.
|
||||
|
||||
## Release 0.65.8 highlights
|
||||
|
||||
Version 0.65.8 fixes Find All References (and definition, hover, rename)
|
||||
answering "not found" when the cursor sits just after a name, keeps edits
|
||||
typed during indexing in order, and removes a startup stall that could last
|
||||
minutes on a large workspace.
|
||||
|
||||
## Release 0.65.7 highlights
|
||||
|
||||
Version 0.65.7 is 0.65.6 built for every platform (0.65.6 was never published:
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "lucisv",
|
||||
"version": "0.65.7",
|
||||
"version": "0.66.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "lucisv",
|
||||
"version": "0.65.7",
|
||||
"version": "0.66.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"vscode-languageclient": "9.0.1"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "lucisv",
|
||||
"displayName": "lucisv — Verilog/SystemVerilog",
|
||||
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
|
||||
"version": "0.65.7",
|
||||
"version": "0.66.0",
|
||||
"publisher": "guoliangchen",
|
||||
"author": "Guoliang Chen",
|
||||
"license": "MIT",
|
||||
@@ -710,7 +710,7 @@
|
||||
"type": "number",
|
||||
"default": 4194304,
|
||||
"minimum": 0,
|
||||
"markdownDescription": "Size in bytes above which an **opened file** is put on the fast path: it is line-counted and nothing else — never parsed, never analyzed, never indexed — so a 100 MB netlist opens instantly instead of hanging the editor. What you still get is **syntax colouring of what is on screen**, painted a screenful at a time, plus go-to-definition and find-references within that file by text search. Everything else — diagnostics, formatting, symbols, folding, rename, hover, completion — answers nothing at all for such a file, and formatting says so rather than doing nothing quietly. A file on the fast path is left out of the workspace index entirely, so its symbols do not exist for the rest of the project. Set to `0` to analyze every file you open however big it is. Takes effect the next time the file is opened or edited. Not to be confused with `#lucisv.index.maxFileSize#`, which is about files nobody opened."
|
||||
"markdownDescription": "Size in bytes above which an **opened file** is put on the fast path: it is line-counted and nothing else — never parsed, never analyzed, never indexed — so a 100 MB netlist opens instantly instead of hanging the editor. What you still get is **syntax colouring of what is on screen**, painted a screenful at a time, plus go-to-definition and find-references within that file by text search. Everything else — diagnostics, formatting, symbols, folding, rename, hover, completion — answers nothing at all for such a file, and formatting says so rather than doing nothing quietly. A file on the fast path is left out of the workspace index entirely, so its symbols do not exist for the rest of the project. Set to `0` to analyze every file you open however big it is. A change takes effect at once on the files already open. Not to be confused with `#lucisv.index.maxFileSize#`, which is about files nobody opened."
|
||||
},
|
||||
"lucisv.lint.select": {
|
||||
"type": "array",
|
||||
|
||||
@@ -95,7 +95,7 @@ function fileItem(group) {
|
||||
return item;
|
||||
}
|
||||
|
||||
/** A reference's row: the whole line, the identifier highlighted; a click selects it in its file. */
|
||||
/** A reference's row: the whole line, the identifier highlighted; a click puts the caret on it in its file. */
|
||||
function referenceItem(reference) {
|
||||
const label = reference.text === ''
|
||||
? { label: `line ${reference.line}` }
|
||||
@@ -105,10 +105,15 @@ function referenceItem(reference) {
|
||||
item.description = reference.declaration ? `declaration · line ${reference.line}` : `line ${reference.line}`;
|
||||
if (reference.declaration) item.iconPath = new vscode.ThemeIcon('symbol-key');
|
||||
item.tooltip = `${vscode.workspace.asRelativePath(uri)}:${reference.line}:${reference.character}`;
|
||||
// The caret goes to the identifier's start, as VS Code's own references
|
||||
// view and go to definition put it. `vscode.open` makes a range's *end* the
|
||||
// caret (a selection's direction does not survive it), and a Find All
|
||||
// References from just past a name used to ask about the next character.
|
||||
const { line, character } = range.start;
|
||||
item.command = {
|
||||
command: 'vscode.open',
|
||||
title: 'Open Reference',
|
||||
arguments: [uri, { selection: range, preserveFocus: false, preview: true }],
|
||||
arguments: [uri, { selection: new vscode.Range(line, character, line, character), preserveFocus: false, preview: true }],
|
||||
};
|
||||
return item;
|
||||
}
|
||||
|
||||
@@ -181,7 +181,10 @@ async function theCommandFillsGroupsAndRevealsTheView() {
|
||||
assert.equal(topRows[0].command.command, 'vscode.open');
|
||||
const [target, options] = topRows[0].command.arguments;
|
||||
assert.equal(target.toString(), 'file:///ws/top.sv');
|
||||
assert.deepEqual(options.selection, new Range(1, 27, 1, 28), 'a click selects exactly the identifier');
|
||||
// At the identifier's start, as VS Code's own references view and go to
|
||||
// definition put it: `vscode.open` makes a range's *end* the caret, and a
|
||||
// search started from there used to ask about the character after the name.
|
||||
assert.deepEqual(options.selection, new Range(1, 27, 1, 27), 'a click puts the caret on the identifier');
|
||||
|
||||
const crlfRow = labels(view.getChildren(groups[2]))[0];
|
||||
assert.deepEqual(crlfRow.label, { label: 'assign y = top.r;', highlights: [[15, 16]] }, 'tab and CRLF handled');
|
||||
|
||||
Reference in new issue
Block a user