editor-packaging: a minimal VS Code extension (41-line plain JS on
vscode-languageclient =9.0.1, one setting vfmt.serverPath, languages
verilog/systemverilog) with a zero-dependency smoke.js that validates
the extension's exact spawn contract against the real binary, plus
Neovim/Vim/coc setup docs (including the load-bearing
vim.filetype.add — Vim maps *.v by content heuristic and *.vh not at
all). Everything headless-validatable was validated: the .vsix
builds, smoke passes with negative controls, npm ci reproduces.
vfmt-core-lift: config.rs and walk.rs moved to a new std-only
vfmt_core crate as byte-identical 100% renames (CLI suite untouched,
corpus TSV md5 equal from HEAD and lifted builds). The LSP server
now discovers vfmt.toml per document with precedence config > client
tabSize > built-in default (an editor default is not a deliberate
override), warns once per document change on a broken config while
formatting with defaults, and scans the workspace with the lifted
gitignore-aware walk. QA drove every claim live over stdio.
With these, every TODO §6 item is delivered: spans, tolerant
parsing, define table, single-file semantics, workspace index, the
server, and both editors. Lead trued up the caveats this round made
stale across five documents.
Dev: 2 Opus agents; QA: 2 Sonnet agents; reviews in
docs/features/{editor-packaging,vfmt-core-lift}/README.md.
Co-Authored-By: Claude Fable 5 <[email protected]>
663 lines
39 KiB
Markdown
663 lines
39 KiB
Markdown
# vfmt-server
|
|
|
|
## Goal
|
|
|
|
`crates/vfmt_server` is the analog of ruff's `ruff_server`: one binary,
|
|
`vfmt-server`, that speaks LSP over stdio and serves both VS Code and
|
|
Vim/Neovim with no editor-specific logic below the protocol layer (TODO.md
|
|
§6). Every engine it needs already exists — the tolerant parser, the span and
|
|
line-index utilities, the `` `define`` table, `vlog_semantic` and the
|
|
workspace index — so this crate owns **only the protocol layer**: message
|
|
loop, document state, position arithmetic, and one small handler per
|
|
capability. It deliberately contains no analysis of its own; anything that
|
|
looks like language knowledge in here is a bug or a `Handshake` request.
|
|
|
|
## Capabilities as shipped
|
|
|
|
| LSP request | Engine it consumes | Notes |
|
|
|---|---|---|
|
|
| `textDocument/formatting` | `vlog_formatter::format_source` | One whole-document `TextEdit`, and only when the text actually changed |
|
|
| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, full-text sync |
|
|
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries |
|
|
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex` | Macro body, or declaration kind + snippet |
|
|
| `textDocument/definition` | `Semantics` then `ExternalResolutions` | `Ambiguous` returns every location |
|
|
| `textDocument/references` | `Semantics::references_of` | In-file only this round |
|
|
| `textDocument/documentSymbol` | `Semantics::document_symbols` | Hierarchical |
|
|
| `workspace/symbol` | `WorkspaceIndex::workspace_symbols` | Capped at 256 hits |
|
|
|
|
Deferred, deliberately, and named in Status/TODO below: range formatting
|
|
(waits on TODO.md §2 `--lines`), lint diagnostics (waits on `vlog_linter`),
|
|
completion / rename / signature help, and cross-file references.
|
|
(`vfmt.toml` discovery and `.gitignore`-aware indexing, deferred when this
|
|
was written, were delivered by vfmt-core-lift the same day — lead note.)
|
|
|
|
## Dependencies, and the justification CLAUDE.md asks for
|
|
|
|
Four direct dependencies, all exact-pinned in the root `[workspace.dependencies]`:
|
|
|
|
| crate | version | why it is not std, and not hand-rolled |
|
|
|---|---|---|
|
|
| `lsp-server` | `=0.10.0` | rust-analyzer's own transport: stdio framing, the `Content-Length` header dance, the initialize/shutdown/exit state machine. Synchronous — a `crossbeam-channel` pair and two I/O threads, **no `tokio`**. This is the whole reason it was picked over `tower-lsp`, which drags an async runtime into a program whose work is CPU-bound and single-file. |
|
|
| `lsp-types` | `=0.97.0` | The protocol's data model — several hundred structs whose field names and `serde` attributes are the wire format. Hand-writing them is hand-rolling JSON by another name, which the brief forbids and which would rot at every spec revision. |
|
|
| `serde` | `=1.0.229` | Only for the `DeserializeOwned` bound on the one generic request-decoding helper. Arrives transitively via `lsp-types` regardless. |
|
|
| `serde_json` | `=1.0.140` | `Value` is `lsp-server`'s params/result type; `from_value`/`to_value` are the only JSON this crate touches. Arrives transitively regardless. |
|
|
|
|
**Transitive audit**, measured on this workspace's own lock file (diffing
|
|
`Cargo.lock` against `HEAD`, so the number is what the repo actually gained,
|
|
not what a standalone crate would):
|
|
|
|
**18 new packages.** `bitflags`, `crossbeam-channel`, `fluent-uri`, `itoa`,
|
|
`log`, `lsp-server`, `lsp-types`, `memchr`, `proc-macro2`, `quote`, `ryu`,
|
|
`serde`, `serde_core`, `serde_derive`, `serde_json`, `serde_repr`, `syn`,
|
|
`unicode-ident`. **Twelve of the eighteen are the `serde`/JSON stack** and its
|
|
proc-macro toolchain (`serde*`, `proc-macro2`, `quote`, `syn`,
|
|
`unicode-ident`, `itoa`, `ryu`, `memchr`) — a cost any JSON handling at all
|
|
would have paid. The other six are the protocol proper: `lsp-server`,
|
|
`lsp-types`, `crossbeam-channel`, `fluent-uri`, `bitflags`, `log`.
|
|
`crossbeam-utils` was already in the lock via
|
|
`rayon` and is shared, not added. Exactly one `syn` is resolved (3.0.3) —
|
|
worth checking, because `lsp-types`' `serde_repr` and `serde_derive` can
|
|
easily land on different major versions and double the proc-macro build.
|
|
|
|
**Build scripts: five** — `proc-macro2`, `quote`, `serde`, `serde_core`,
|
|
`serde_json`. All five were read. Every one is a toolchain probe: four shell
|
|
out to `rustc --version` and all five emit only `cargo:rustc-cfg` /
|
|
`cargo:rustc-check-cfg` lines. None compiles native code, links a system
|
|
library, or touches the network. No `cc`, no `bindgen`, no vendored C.
|
|
|
|
**Versions considered and rejected.** `lsp-types` `0.94.x` models a URI as
|
|
`url::Url`, which would give us `Url::from_file_path` for free but costs the
|
|
`url` → `idna` → `unicode-bidi`/`unicode-normalization`/`tinyvec` subtree —
|
|
five extra packages to avoid writing the ~40 lines in `src/uri.rs`. `0.97.0`
|
|
uses `fluent-uri` (one package, one shared `bitflags`) and gives us a `Uri`
|
|
with `FromStr` and `as_str()`, so path↔URI conversion is ours. That trade —
|
|
five packages against forty tested lines — went the way CLAUDE.md's "standard
|
|
library first" points. The cost is recorded honestly: `fluent-uri` 0.1.4 is a
|
|
zero-copy parser with ~144 `unsafe` occurrences. CLAUDE.md's no-`unsafe` rule
|
|
governs our code, and this crate has none.
|
|
|
|
## The byte ↔ UTF-16 conversion (`src/convert.rs`)
|
|
|
|
**This is the classic LSP bug, so it is the one piece of this crate with a
|
|
design section.** Everything below the protocol speaks **UTF-8 byte offsets**
|
|
(`TextRange`, `LineIndex`, every span the engines produce). LSP `Position`
|
|
speaks **UTF-16 code units** within a line. The two agree only on ASCII, which
|
|
is exactly why the bug survives to production: it is invisible until a comment
|
|
contains `é` or an emoji.
|
|
|
|
`Positions<'a> { text: &'a str, index: &'a LineIndex }` is built per request
|
|
from the document's own text and line table — it borrows, so there is no
|
|
cached copy to invalidate.
|
|
|
|
**Byte offset → `Position`:**
|
|
|
|
1. `LineIndex::line_col(offset)` gives the 1-based line; LSP wants 0-based.
|
|
2. The character is `text[line_start..offset]` measured in UTF-16 code units
|
|
(`chars().map(char::len_utf16).sum()`), **not** in bytes and **not** in
|
|
`char`s.
|
|
3. `offset` is floored to a UTF-8 character boundary first. An offset landing
|
|
inside a multi-byte character cannot slice; clamping down is the only
|
|
answer that neither panics nor invents a position.
|
|
4. A trailing `\r` in that slice is dropped. `LineIndex` deliberately treats
|
|
`\r` as an ordinary byte of its line (`docs/features/spans/README.md`), but
|
|
LSP line content excludes the whole `\r\n` terminator, so a span ending at
|
|
the `\n` of a CRLF line would otherwise report one character too many.
|
|
|
|
**`Position` → byte offset:** walk the line's characters from its start,
|
|
accumulating UTF-16 units, and stop when the accumulated count reaches the
|
|
requested character. Consequences, both deliberate:
|
|
|
|
- A character that lands **inside a surrogate pair** (an astral character
|
|
counts 2; the client asks for the midpoint) resolves to the offset *after*
|
|
that character. There is no byte there to point at; rounding forward keeps
|
|
the result a valid char boundary.
|
|
- A character past the end of its line clamps to the line's end (`\r`
|
|
excluded), never wrapping onto the next line — the same clamping rule
|
|
`LineIndex::offset` already documents for byte columns.
|
|
- A line past the end of the file clamps to the file's length.
|
|
|
|
**The one place the round-trip is not the identity, found by the test that
|
|
tried to assert it was.** Both bytes of a `\r\n` are "the end of this line's
|
|
content", and LSP has a single position for that, so `position(\r)` and
|
|
`position(\n)` are equal and the `\n` cannot round-trip back to itself. The
|
|
alternative — letting the `\r` count as a character — would report a position
|
|
one past the line content the client believes it has, which every client then
|
|
clamps anyway. The collapse is the correct behavior, so it is pinned by a test
|
|
of its own (`a_crlf_terminator_is_the_one_place_the_round_trip_collapses`)
|
|
rather than papered over, and the exhaustive round-trip test skips exactly
|
|
that one byte class.
|
|
|
|
**An empty span is not a drawable range.** A diagnostic whose span is empty —
|
|
which is every lex error, since the lexer reports the point it gave up —
|
|
would underline nothing. `diagnostic_range` widens an empty span to the whole
|
|
line it sits on, and, when *that* line is empty, to the line before it. The
|
|
second rule is not hypothetical: an unterminated block comment is reported at
|
|
end-of-file, and a file ending in a newline has an empty last line, so without
|
|
the fallback the single most common lex error draws nothing at all. Found by
|
|
the handler test, not predicted.
|
|
|
|
The server advertises `position_encoding: utf-16`, the protocol default, so
|
|
the conversion is always on. Negotiating UTF-8 with capable clients would make
|
|
this module a no-op for them; it is not worth a second code path until
|
|
somebody measures the cost.
|
|
|
|
Tested in `convert.rs`'s own unit tests (14 of them): pure ASCII, 2-byte (`é`)
|
|
and 3-byte (`✓`) characters, an astral emoji (`🎉`, one `char`, two UTF-16
|
|
units, four UTF-8 bytes), a position landing *inside* a surrogate pair, an
|
|
offset landing inside a multi-byte character, CRLF line ends, out-of-range
|
|
positions in both directions, the empty document, and a full round-trip over
|
|
every character boundary of a document mixing all of those.
|
|
|
|
## State and staleness
|
|
|
|
Single-threaded request loop — `lsp-server`'s model. Two I/O threads (its
|
|
own) read and write stdio; this crate's loop receives one message, handles it
|
|
to completion, and sends the response before looking at the next. No shared
|
|
mutable state, no locks, no cancellation. Verilog files are small and every
|
|
handler is milliseconds; the complexity of a worker pool buys nothing yet.
|
|
|
|
**Two layers, invalidated by different events** — exactly the split
|
|
`docs/features/workspace-index/README.md` designed for:
|
|
|
|
| layer | rebuilt when | cost |
|
|
|---|---|---|
|
|
| a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` | one file, full recompute |
|
|
| the `WorkspaceIndex` | `initialize`, and every `didSave` | full re-scan of the roots |
|
|
|
|
**Per-file recompute on every keystroke** is the strategy TODO.md §6 states
|
|
("per-file recompute is fine at Verilog file sizes"); salsa is explicitly
|
|
deferred there.
|
|
|
|
**Open buffers override disk** in every index rebuild: the roots are walked,
|
|
each file read, and then every open document with a path replaces the disk
|
|
copy (adding itself if it exists only in the editor). So the index never
|
|
disagrees with a buffer the user is looking at.
|
|
|
|
**The staleness window, stated plainly.** The index is rebuilt on save, not on
|
|
change. Between editing file A and saving it, file B's cross-file answers
|
|
(`definition` into A, `workspace/symbol` hits in A, hover falling back to A's
|
|
defines) reflect A **as it was at its last save** — except for A's own buffer,
|
|
which the override above keeps current. Rebuilding on every keystroke would
|
|
re-parse the whole workspace per character; rebuilding on save is the cheapest
|
|
point where the answer is expected to change anyway. Measured cost of a
|
|
rebuild: 0.68 s for the 860-file corpus (the workspace index's own baseline),
|
|
plus the file reads.
|
|
|
|
**Definition targets in other files need that file's text** to turn a
|
|
`TextRange` into a `Range`, and the index deliberately keeps no file contents.
|
|
The server resolves a target by taking the **open buffer's text if that path
|
|
is open, else reading the file from disk** — the same precedence the index
|
|
rebuild uses, so a location can never be computed against text the index did
|
|
not see.
|
|
|
|
## Assumptions
|
|
|
|
- **Full-text document sync only.** The server advertises
|
|
`TextDocumentSyncKind::FULL`, so a `didChange` carries the whole buffer and
|
|
there is no incremental-edit application to get wrong. At Verilog file sizes
|
|
the wire cost is irrelevant.
|
|
- **Every document URI is a `file:` URI.** `untitled:` buffers are accepted
|
|
and served for everything single-file (diagnostics, tokens, formatting,
|
|
symbols), but they have no path, so they never enter the workspace index.
|
|
- **Percent-encoding, not a URI library, converts paths.** `src/uri.rs`
|
|
encodes everything outside the unreserved set plus `/`, and decodes `%XX`.
|
|
Non-UTF-8 paths are rejected rather than guessed at. The Windows
|
|
drive-letter rule (`file:///C:/x` → `C:\x`) is written and compiled but
|
|
**untested on Windows** — it is behind `cfg!(windows)` so it cannot misfire
|
|
on a POSIX path legitimately named `/C:`.
|
|
- **The workspace walk is plain.** `initialize`'s `workspace_folders` (falling
|
|
back to `root_uri`) are walked recursively for `*.v`/`*.sv`/`*.vh`/`*.svh`.
|
|
~~`.gitignore` and `--exclude` are **not** honored~~ **Superseded by
|
|
vfmt-core-lift (lead note): the scan now uses the lifted `vfmt_core` walk —
|
|
`.gitignore` always on, workspace-root config excludes applied. The old
|
|
64-directory depth cap is gone for CLI parity (symlink-cycle exposure now
|
|
shared with the CLI, filed as a follow-up in that feature's README).**
|
|
- **A file that does not lex has no tokens.** The lexer is all-or-nothing
|
|
(`docs/features/error-recovery/README.md`), so `semanticTokens` returns an
|
|
empty set and hover's macro lookup finds nothing for such a buffer. The
|
|
tolerant parser still yields one file-wide diagnostic, which is what the
|
|
user needs to see anyway.
|
|
- **A broken *header* distorts the tree**, as error-recovery's Assumptions
|
|
warn: the module body re-parses at file scope and an orphaned `endmodule`
|
|
becomes a second error item. Symbols and diagnostics in that state are
|
|
oddly-placed but never wrong about their spans. This is the documented
|
|
shape, not a bug in this crate.
|
|
- ~~**`vfmt.toml` is not discovered.**~~ **Superseded by vfmt-core-lift
|
|
(lead note): discovery now runs per formatting request via `vfmt_core`,
|
|
with precedence config > client tabSize > built-in default, and a broken
|
|
config warns once and formats with defaults. See
|
|
`docs/features/vfmt-core-lift/README.md`.**
|
|
|
|
## Handshakes
|
|
|
|
**Consumed from `vlog_parser`:** `tokenize`, `parse_source_tolerant`,
|
|
`ParseDiagnostic { message, line, col, span }`, `TextRange`, `LineIndex`
|
|
(`line_col` / `offset` / `line_range` / `line_count`), `token::{Token,
|
|
TokenKind, Comment}` including the `leading`/`trailing` trivia and their
|
|
spans, and `defines::{collect_defines, Define, DefineTable}`.
|
|
|
|
**Consumed from `vlog_semantic`:** `analyze`, `Semantics::{symbol_at,
|
|
reference_at, references_of, document_symbols, symbol, symbols, references,
|
|
reference_id_at}`, `Symbol { name, kind, name_span, decl_span, child_scope }`,
|
|
`SymbolKind`, `Resolution`, `DocumentSymbol`, and the workspace layer —
|
|
`WorkspaceIndex::{build, path, find_define, workspace_symbols}`,
|
|
`resolve_external`, `ExternalResolutions::definition_of`, `Definition`, `Def`.
|
|
|
|
**Consumed from `vlog_formatter`:** `format_source(&str, &Config) ->
|
|
Result<String, FormatError>` and `Config { max_width, indent_width }`.
|
|
|
|
**Promised to nobody yet.** This crate is a leaf: it has no library target and
|
|
nothing depends on it. The editor packaging round (TODO.md §6) will consume
|
|
the binary's name and its stdio contract, nothing else.
|
|
|
|
**Requested of other modules** — none of these block this round, and none was
|
|
done here:
|
|
|
|
1. **DELIVERED** by `docs/features/vfmt-core-lift/README.md` (round 12):
|
|
`config.rs` now lives in `crates/vfmt_core`, and formatting discovers
|
|
`vfmt.toml` anchored at the document's own path. **`crates/vfmt`: make
|
|
config discovery reusable.** `vfmt.toml` search,
|
|
parsing and precedence live in `crates/vfmt/src/config.rs`, inside a binary
|
|
crate, so the server cannot call it. The LSP needs exactly the same
|
|
answer the CLI gives for the same file, and duplicating the search rule is
|
|
how the two silently diverge. The ask: lift `config.rs` into a small
|
|
library (its own crate, or a `lib.rs` beside `main.rs`) with a
|
|
`discover(path) -> Config`-shaped entry point. Until then the server
|
|
formats with defaults, which is wrong for any project that sets
|
|
`line-length`.
|
|
2. **DELIVERED** by `docs/features/vfmt-core-lift/README.md` (round 12):
|
|
`walk.rs` now lives in `crates/vfmt_core`, and the index scan uses it, so
|
|
the index skips what the CLI skips. **`crates/vfmt`: make the ignore-aware
|
|
walk reusable.** Same shape of
|
|
problem for `walk.rs` (`.gitignore` + `--exclude`). The server's plain walk
|
|
will index generated netlists a `vfmt` run would skip.
|
|
3. **`vlog_parser`: token-kind detail the lexer folds away.** Two spellings
|
|
are indistinguishable in `TokenKind` today and are therefore classified
|
|
coarsely by `semanticTokens` rather than reached for privately: an operator
|
|
and a bracket are both `Symbol` (this crate emits neither, see the mapping
|
|
table), and a macro *usage* is a `TokenKind::Ident` whose text starts with
|
|
a backtick, distinguished by the existing public `Token::is_macro()` —
|
|
which is enough, so this is a note, not a request.
|
|
4. **`vlog_semantic`: nothing.** The queries needed for all six navigation
|
|
capabilities existed exactly as documented.
|
|
|
|
## The `semanticTokens` mapping
|
|
|
|
Legend advertised, in index order:
|
|
|
|
`0 namespace`, `1 class`, `2 type`, `3 enumMember`, `4 parameter`,
|
|
`5 variable`, `6 property`, `7 function`, `8 macro`, `9 keyword`,
|
|
`10 comment`, `11 string`, `12 number`, `13 decorator`.
|
|
Modifiers: `0 declaration`.
|
|
|
|
| source | token type |
|
|
|---|---|
|
|
| `TokenKind::Keyword` | `keyword` |
|
|
| `TokenKind::Number` | `number` |
|
|
| `TokenKind::String` | `string` |
|
|
| `TokenKind::Directive` (`` `define``, `` `ifdef``, `` `include``) | `macro` |
|
|
| `TokenKind::Ident` where `Token::is_macro()` (`` `NAME ``) | `macro` |
|
|
| `TokenKind::SystemIdent` (`$display`) | `function` |
|
|
| `TokenKind::Attribute` (`(* ... *)`) | `decorator` |
|
|
| `Comment` trivia (leading and trailing, incl. on the EOF token) | `comment` |
|
|
| `TokenKind::Symbol` | **not emitted** |
|
|
| `TokenKind::Ident`, otherwise | from `Semantics`, below |
|
|
|
|
A plain identifier is looked up in the file's `Semantics` at its start offset:
|
|
a declaration (`symbol_at`) gets its symbol's type **plus the `declaration`
|
|
modifier**; a use (`reference_at`) that resolved in-file gets the resolved
|
|
symbol's type; anything else — an external candidate, a not-found name, a name
|
|
a macro would have produced — falls back to `variable`.
|
|
|
|
`SymbolKind` → type: `Module`→`class`, `Package`→`namespace`,
|
|
`Typedef`→`type`, `EnumVariant`→`enumMember`, `Param`/`TfArg`→`parameter`,
|
|
`Function`/`Task`→`function`, `StructMember`→`property`, and
|
|
`Port`/`Net`/`Var`/`Genvar`/`Instance`/`Block`→`variable`.
|
|
|
|
Two rules that are easy to get wrong and are tested:
|
|
|
|
- **Punctuation is not emitted.** Every editor already colors brackets from
|
|
its TextMate grammar, and emitting one token per `;` roughly triples the
|
|
payload for no visible gain.
|
|
- **No token ever spans a line break.** The spec requires it, and Verilog has
|
|
three multi-line token shapes that would violate it — a block comment, a
|
|
continued `` `define``, and a multi-line macro invocation. Every span is
|
|
split at `\n` before encoding, and the pieces are sorted by (line, start)
|
|
before the delta encoding runs.
|
|
|
|
## Hover, and the order it tries things
|
|
|
|
1. **A macro usage** (`` `NAME `` / `` `NAME(...) ``, and the name inside a
|
|
`` `ifdef``-style directive is *not* included): the file's own
|
|
`DefineTable::latest` wins, rendered as the joined body plus the
|
|
definition's own source lines. If this file does not define it,
|
|
`WorkspaceIndex::find_define` supplies every workspace definition — **all
|
|
of them, each with its file and line**, because the index models no
|
|
`` `include`` graph and picking one silently would be a guess
|
|
(`docs/features/workspace-index/README.md` makes the same call).
|
|
2. **A reference** resolved in-file: the symbol's kind, its name, and the
|
|
source lines its `decl_span` covers.
|
|
3. **A reference** answered only by the workspace overlay: the kind and name,
|
|
plus each target's file and line.
|
|
4. **A declaration** the cursor is sitting on: its own kind, name and
|
|
snippet.
|
|
|
|
The snippet is `decl_span` widened to whole lines, so a declaration reads as
|
|
it was written rather than starting mid-line.
|
|
|
|
## Status / TODO
|
|
|
|
- [x] Crate skeleton compiling **before** the root `members` entry (the
|
|
ordering lesson from the previous round).
|
|
- [x] `src/convert.rs`: byte ↔ UTF-16 `Position`, `TextRange` ↔ `Range`.
|
|
- [x] `src/uri.rs`: `file:` URI ↔ path, percent-encoded.
|
|
- [x] `src/state.rs`: `Document` (text, line index, tokens, diagnostics,
|
|
`Semantics`, `DefineTable`, overlay), workspace walk, index rebuild.
|
|
- [x] `textDocument/formatting`.
|
|
- [x] Diagnostics on `didOpen`/`didChange`/`didSave`.
|
|
- [x] `textDocument/semanticTokens/full`.
|
|
- [x] `textDocument/hover`.
|
|
- [x] `textDocument/definition`.
|
|
- [x] `textDocument/references`.
|
|
- [x] `textDocument/documentSymbol` + `workspace/symbol`.
|
|
- [x] Unit tests for the position conversion, including surrogate pairs.
|
|
- [x] Handler-level tests against constructed state, no process spawned.
|
|
- [x] One end-to-end smoke test that spawns the built binary and speaks
|
|
framed JSON-RPC.
|
|
- [x] TODO.md §6 `vfmt_server` checkbox, annotated with what shipped.
|
|
- [ ] **Not done, deliberately:** `rangeFormatting`. It reuses TODO.md §2's
|
|
`--lines`, which does not exist yet; advertising the capability before
|
|
the engine does is how an editor learns to distrust a server.
|
|
- [ ] **Not done:** lint diagnostics. `vlog_linter` is a concurrent round;
|
|
when it lands, the diagnostic publisher gains a second source and
|
|
nothing else changes.
|
|
- [ ] **Not done:** completion, rename, signature help (TODO.md §6's "then"
|
|
list).
|
|
- [ ] **Not done:** cross-file references. `references_of` is per-file, and
|
|
answering across the workspace means resolving every other file's
|
|
references *into* this one — an inverted index the workspace layer does
|
|
not build. It is a real feature, not a small addition.
|
|
- [x] ~~**Not done:**~~ `vfmt.toml` discovery, `.gitignore`-aware indexing —
|
|
delivered by vfmt-core-lift (both Handshakes below marked DELIVERED).
|
|
- [ ] **Not done:** editor packaging (the VS Code extension and the
|
|
`lspconfig` snippet are their own TODO.md §6 item).
|
|
|
|
## Work log
|
|
|
|
### 2026-08-19 — dev agent
|
|
|
|
- Read `CLAUDE.md`, `README.md`, TODO.md §6 in full, and the Handshakes/API
|
|
sections of `spans`, `error-recovery`, `define-table`, `vlog-semantic` and
|
|
`workspace-index` before writing anything. Every query this crate needed
|
|
existed already; **no change was required in any engine crate**, which is
|
|
the outcome the two-layer design in `workspace-index` was aiming for.
|
|
- **Took the ordering lesson literally.** `crates/vfmt_server/` was created
|
|
with a `Cargo.toml` and a `fn main() {}` and *built* before the root
|
|
`members` entry was added, then the entry, then a build, then the
|
|
dependencies, then a build. A members line pointing at nothing breaks the
|
|
workspace for every other agent in the tree; this cost four extra builds and
|
|
was worth it.
|
|
- **Dependency choice measured, not assumed.** Resolved the tree in a scratch
|
|
crate first: `lsp-types` 0.97 (`fluent-uri`) against 0.94 (`url`). 0.94
|
|
would have handed us `Url::from_file_path`; it also costs `idna`,
|
|
`unicode-bidi`, `unicode-normalization`, `tinyvec` and `percent-encoding`.
|
|
Chose 0.97 and wrote `src/uri.rs` (~40 lines, 6 tests) instead. Also
|
|
confirmed the workspace resolves exactly one `syn`, which the scratch crate
|
|
had *not* — worth re-measuring in place rather than trusting the sandbox.
|
|
- **`serde` is a direct dependency for exactly one reason** and it is stated
|
|
at the manifest line: the `DeserializeOwned` bound on `decode`. Without it
|
|
the request dispatcher becomes eight copies of the same four lines. It
|
|
arrives transitively anyway, so this costs nothing but honesty.
|
|
- **Wrote the UTF-16 conversion first, and its tests before the handlers.**
|
|
This is the bug the brief called out, and two of its rules were established
|
|
by failing tests rather than by design: the CRLF round-trip collapse and the
|
|
empty-diagnostic-range fallback (both written up in the conversion section
|
|
above). In both cases my first *test expectation* was wrong and the code was
|
|
right, which is the good direction for that to happen — but it means the
|
|
behavior is now pinned by a test that understands why, instead of by one
|
|
that happened to pass.
|
|
- **`semanticTokens` line-splitting was designed in, not discovered.** The
|
|
spec forbids a token spanning a line break and Verilog has three shapes that
|
|
would (block comment, continued `` `define``, multi-line macro call). All
|
|
three have a test. Punctuation is deliberately not emitted — every editor
|
|
colours brackets from its own grammar and emitting `;` roughly triples the
|
|
payload.
|
|
- **Formatting failures go to `showMessage`, not to diagnostics**, and the
|
|
reason is in a comment at the call site: the diagnostic list belongs to the
|
|
parse pass and is cleared on the next keystroke, which would silently erase
|
|
the explanation for a format the user explicitly asked for. The handler
|
|
returns an empty edit list in that case — never a partial edit, per CLAUDE.md
|
|
invariant #1.
|
|
- **Definition/hover into other files read that file's text on demand**, with
|
|
open-buffer-beats-disk precedence, because the index deliberately keeps no
|
|
file contents. Holding the whole workspace in memory to avoid a
|
|
microsecond-scale file read would double what a server already spends on
|
|
buffers.
|
|
- **Three warnings were fixed by deleting code, not by allowing it**: an
|
|
unused `Uri` import, a `text_range` helper with no consumer (it would be
|
|
range formatting's, which is deferred), and a `tree` field on `Document`
|
|
that nothing read once `Semantics` was built. The two `#[allow(deprecated)]`
|
|
that remain are on `DocumentSymbol.deprecated` / `SymbolInformation.
|
|
deprecated` / `InitializeParams.root_uri` — protocol fields deprecated by
|
|
the spec that are still non-optional struct fields — and each carries the
|
|
comment CLAUDE.md requires.
|
|
- **The e2e test writes the whole session before reading a byte.** Interleaving
|
|
writes and reads against a subprocess is how a smoke test turns into an
|
|
intermittent hang; the session is under 4 KB, well inside a pipe buffer, and
|
|
the server exits on `exit` so stdout closes and the read terminates on its
|
|
own. No timeouts, no reader thread, and it cannot deadlock.
|
|
- Did not touch `vlog_parser`, `vlog_formatter`, `vlog_semantic`,
|
|
`vlog_linter` or `crates/vfmt`. Did not run `git commit`/`git push`.
|
|
- **Concurrency note:** another agent's `vlog_linter` round is live in the same
|
|
tree and added its own `members` line to the root `Cargo.toml` mid-round;
|
|
left alone, as expected. Something in that round also ran `cargo fmt --all`
|
|
across the tree, which reflowed a few of this crate's lines — harmless, and
|
|
the final `cargo fmt --all --check` is clean.
|
|
|
|
**Results.** `cargo test -p vfmt_server`: **76 passed, 0 failed** (75 unit +
|
|
1 e2e; counts trued up by the lead per the QA log — the workspace total
|
|
below also moved as the concurrent linter round landed). `cargo test
|
|
--workspace`: **494+ passed, 0 failed**. `cargo clippy
|
|
--workspace --all-targets`: silent, 0 warnings. `cargo fmt --all --check`:
|
|
clean. Files added: `crates/vfmt_server/{Cargo.toml,src/{main,server,state,
|
|
convert,uri,locate,diagnostics,format,tokens,hover,nav,symbols}.rs,
|
|
tests/e2e.rs}`, this README. Files edited: root `Cargo.toml` (one `members`
|
|
entry, four `[workspace.dependencies]` lines — additive only), `TODO.md`
|
|
(§6 checkbox).
|
|
|
|
## QA log
|
|
|
|
### 2026-08-19 — QA agent
|
|
|
|
Scope: `-p vfmt_server` only. Did not touch `vlog_linter`, `crates/vfmt`, or
|
|
`docs/features/linter-core` (a concurrent QA round owns those). No source was
|
|
edited; this entry is the only write.
|
|
|
|
**Gates.** `cargo fmt -p vfmt_server -- --check`: clean. `cargo clippy -p
|
|
vfmt_server --all-targets`: 0 warnings. `cargo test -p vfmt_server`: **76
|
|
passed, 0 failed (75 unit + 1 e2e)** — stable across two runs. `cargo test
|
|
--workspace`: green (503 passed at the instant measured; the concurrent
|
|
`vlog_linter` round is landing tests live in the same tree, so this number
|
|
moves independently of anything here — `-p vfmt_server`'s own 76 is the
|
|
number that matters for this feature and is not moving).
|
|
|
|
**Dependency audit, independently reproduced.** `git diff HEAD -- Cargo.lock`
|
|
adds exactly the 18 named packages, plus two *local* workspace crates
|
|
(`vfmt_server` itself and `vlog_linter`, the concurrent round — not part of
|
|
the transitive count). Exactly one `syn` resolves, `3.0.3`. Exact-pin lines
|
|
in root `Cargo.toml` confirmed: `lsp-server = "=0.10.0"`, `lsp-types =
|
|
"=0.97.0"`, `serde = "=1.0.229"`, `serde_json = "=1.0.140"`. Read all five
|
|
build scripts in full (not spot-read): `proc-macro2-1.0.107`,
|
|
`quote-1.0.47`, `serde-1.0.229`, `serde_core-1.0.229`, `serde_json-1.0.140`
|
|
(paths under `~/.cargo/registry/src/…`, resolved via `cargo metadata`).
|
|
Every one only shells out to `rustc --version` and emits
|
|
`cargo:rustc-cfg`/`cargo:rustc-check-cfg` lines (`proc-macro2`'s also
|
|
compiles a tiny local probe file through `rustc` to detect a stable-API
|
|
cutoff — still no network, no linking, no `cc`/`bindgen`). Confirms the
|
|
README's claim exactly.
|
|
|
|
**No `unwrap`/`expect`/`panic!`/`unsafe` outside `#[cfg(test)]`.** Checked
|
|
every line match against each file's `mod tests` boundary in all 12
|
|
`src/*.rs` files — zero hits above the boundary. Three `#[allow(deprecated)]`
|
|
found (`main.rs:98`, `symbols.rs:78`, `symbols.rs:103`), each with an
|
|
explanatory comment.
|
|
|
|
**Real-binary end-to-end session, driven directly over stdio** (own
|
|
hand-rolled Python framing client extending the `tests/e2e.rs` pattern, not
|
|
reusing it — scripts left in the scratchpad, not the repo). Scratch project:
|
|
`A.sv` (`` `include``s `defs.vh`, `import P::K`, instantiates `B`), `B.sv`,
|
|
`pkg.sv` (`package P; localparam K = 4;`), `defs.vh` (`` `define WIDTH 8``).
|
|
All PASS:
|
|
|
|
- Capabilities JSON on `initialize`: every shipped capability present
|
|
(`documentFormattingProvider`, `definitionProvider`, `referencesProvider`,
|
|
`hoverProvider`, `documentSymbolProvider`, `workspaceSymbolProvider`,
|
|
`semanticTokensProvider` with the 14-type/1-modifier legend,
|
|
`positionEncoding: "utf-16"`, `textDocumentSync: 1` i.e. Full). Deferred
|
|
capabilities (`documentRangeFormattingProvider`, `completionProvider`,
|
|
`renameProvider`, `signatureHelpProvider`) absent from the JSON, not just
|
|
falsy.
|
|
- `definition` on `B u_b` → `B.sv` at the correct declaration span.
|
|
- `hover` on `` `WIDTH`` → macro body `` `define WIDTH 8``; `hover` on `K`
|
|
(reached via `import P::K`) → `**parameter** — declared in pkg.sv:2`.
|
|
- `didChange` introducing `localparam int ;` → two diagnostics, non-empty
|
|
sane ranges (`severity: 1`, `source: "vfmt"`).
|
|
- `didChange` reverting the fix → **diagnostics array published empty** —
|
|
the classic forgotten-clear case, verified actually clearing.
|
|
- `textDocument/formatting` on the unformatted file → one edit whose
|
|
`newText` is **byte-for-byte identical** to `target/debug/vfmt --stdout`
|
|
on the same source.
|
|
- `textDocument/formatting` on the already-formatted output → `result: []`.
|
|
- `semanticTokens/full` on `B.sv` → decoded the delta stream by hand (12
|
|
tokens), spot-checked against the source; correct.
|
|
- `documentSymbol` on `A.sv` → module `A` nests 5 children (`clk`, `out`,
|
|
the `u_b` instance, `WIDTH2`, `K2`).
|
|
- `workspace/symbol` substring `"WIDTH2"` → 1 correctly located hit.
|
|
- Renamed `B`→`B2` in `B.sv`, `didChange` + `didSave` → `definition` from
|
|
`A`'s still-open buffer (referencing the old name `B`) now resolves to
|
|
`[]`. Staleness model confirmed: the index only rebuilds on save, and did.
|
|
- `shutdown`/`exit` → clean ack, exit code 0.
|
|
|
|
**Position torture.** All PASS. `initialize` with **no** `workspaceFolders`
|
|
and **no** `rootUri` → succeeds (single-file mode works). A file with an
|
|
emoji (`🎉`) in a `//` comment on the line before a module declaration:
|
|
`hover` and `documentSymbol.selectionRange` on the module name land at the
|
|
correct UTF-16 column on the following (pure-ASCII) line. `hover` at the
|
|
character offset landing *inside* the emoji's own surrogate pair (comment
|
|
line itself) → graceful `null`, no crash. A CRLF file with a `wire ;` parse
|
|
error → diagnostic range end character is `8`, matching the 8-char line
|
|
content, not bleeding into the `\r`. `hover`/`definition` at
|
|
character-past-end-of-line, line-past-end-of-file, and both-past-end → all
|
|
six combinations return graceful `null`/`[]`, no protocol error, no crash;
|
|
server process survived and later exited cleanly (code 0). `textDocumentSync`
|
|
confirmed `1` (Full) in the capabilities JSON, so the "stale/overlapping
|
|
`didChange`" scenario is moot as documented.
|
|
|
|
**Robustness.** All PASS. Malformed `Content-Length: notanumber` header, and
|
|
a well-framed-but-garbage JSON body → in both cases the process does **not**
|
|
panic (no `panicked at` in stderr); `lsp-server`'s own transport reports
|
|
`ProtocolError("disconnected channel", true)` and the process exits (code
|
|
1) — "exits cleanly" per the acceptance criterion. Every capability request
|
|
(`hover`, `definition`, `references`, `documentSymbol`,
|
|
`semanticTokens/full`, `formatting`) against a URI that was never opened →
|
|
graceful `null`/`[]`, never a protocol error. A `file:` URI built from a
|
|
path with spaces, `&`, `#`, and a non-ASCII directory component
|
|
(`münchen`) → round-trips correctly through `didOpen`/`publishDiagnostics`
|
|
and `documentSymbol` (probing `src/uri.rs` through the real binary, not just
|
|
its own unit tests).
|
|
|
|
**Index scale.** PASS, and a QA-tooling note worth recording. Pointed
|
|
`initialize` at `corpus/` (860 files, read-only, untouched). A full session
|
|
— `initialize` + `workspace/symbol("")` + `workspace/symbol("clk")` +
|
|
`workspace/symbol("uart_core")` + `shutdown`/`exit` — completes in **0.79 s**
|
|
wall time (`/usr/bin/time -l`: 29.5 MB max RSS). The 256 cap is honored
|
|
exactly: `""` (matches everything, per `vlog_semantic`'s own doc comment)
|
|
and `"clk"` (a common substring almost certainly matching far more than 256
|
|
declarations across a real 860-file corpus) both return exactly 256 hits;
|
|
`"uart_core"` returns the correct single hit.
|
|
|
|
*Tooling note, not a vfmt_server defect:* an earlier attempt at this same
|
|
check, using a persistent bidirectional-threaded Python client (a reader
|
|
thread continuously draining stdout while the main thread issues requests —
|
|
the natural way to extend the e2e pattern for an interactive multi-request
|
|
session), appeared to hang indefinitely specifically on `workspace/symbol
|
|
("clk")` against the real corpus — confirmed *not* CPU-bound via `sample`
|
|
(macOS) on the server process: all four of its threads (main loop, reader,
|
|
writer, message-dropper) sat blocked on `recv()`/`read()` the entire time,
|
|
CPU time flat at 0.76 s across a 3-minute wait. Root-caused by replacing the
|
|
persistent client with a write-the-whole-session-then-read-all-of-stdout
|
|
script (`subprocess.run(..., input=session)`) — the exact pattern
|
|
`tests/e2e.rs` itself uses, with the exact rationale given in its own
|
|
top-of-file comment ("interleaving writes and reads against a subprocess is
|
|
how a smoke test turns into an intermittent hang"). That version returned
|
|
the correct, capped, sub-second result every time. I did not chase the
|
|
harness bug further since the server's correctness is independently proven;
|
|
flagging it so nobody mistakes the interactive-client hang for a server
|
|
issue if they re-run a similar probe.
|
|
|
|
**CLAUDE.md / TODO.md compliance.** README has all seven required sections.
|
|
TODO.md §6's `vfmt_server` checkbox (`TODO.md:330`) is checked and its
|
|
shipped/not-shipped annotation matches the README's Capabilities table and
|
|
Status/TODO checklist exactly — no over-claiming. Both filed Handshakes
|
|
(`config.rs` and `walk.rs` lifting requests, README.md:370-371) are
|
|
recorded; confirmed independently that `crates/vfmt` is `[[bin]]`-only (no
|
|
`[lib]` target in its `Cargo.toml`), so the Handshake's premise — that
|
|
`vfmt_server` genuinely cannot call into them today — holds.
|
|
|
|
**Minor, non-blocking:** the Work log's "Results" paragraph
|
|
(README.md:447-448) says "75 passed, 0 failed (74 unit + 1 e2e)" and "493
|
|
passed" workspace-wide. Current actual counts are 76 (75 unit + 1 e2e) and
|
|
503 workspace-wide (the latter net of concurrent work). The `-p vfmt_server`
|
|
count is off by exactly one unit test from what's written — likely a test
|
|
added after that paragraph was written. Not fixed here since it's prose in
|
|
another agent's Work log entry, not a code or test defect; flagging so the
|
|
dev agent can true it up.
|
|
|
|
**Summary: no BLOCKING findings.** No panic, no dropped/never-cleared
|
|
diagnostic, no position off-by-one, on ASCII or non-ASCII content, in any
|
|
scenario tried. All five claims verified against the real binary, not just
|
|
its own unit tests.
|
|
|
|
## Review
|
|
|
|
**2026-08-19 — lead. Verdict: accepted; commits jointly with linter-core
|
|
(round 11). The owner's LSP requirement is now a running binary.**
|
|
|
|
What earned it:
|
|
|
|
1. **Protocol layer only.** Not one engine crate was modified — the
|
|
ten rounds of foundations were sufficient exactly as documented,
|
|
which is the strongest validation the feature-README discipline has
|
|
produced. Where the CLI's config/gitignore behavior couldn't be
|
|
reached (they live in the vfmt binary), the dev filed Handshakes
|
|
instead of duplicating logic — those two lifts are round-12 work.
|
|
2. **Honest capability advertising**: deferred features are absent
|
|
from the initialize result, so no editor is lied to. rangeFormatting
|
|
waits on §2 `--lines`; lint diagnostics wait on wiring vlog_linter
|
|
in — both natural follow-ups.
|
|
3. **The two test-produced findings** (CRLF's one-position collapse
|
|
pinned rather than papered over; empty EOF diagnostic spans widened
|
|
to drawable lines) are the UTF-16/position class of bug that ruins
|
|
language servers, caught before any editor saw them. QA's
|
|
position-torture (emoji, surrogates, six past-end combinations) and
|
|
robustness runs (malformed frames, unopened URIs, percent-encoded
|
|
paths) all came back clean, and the diagnostics-actually-clear case
|
|
was verified through a real stdio session.
|
|
4. **Dependency discipline held under the biggest temptation**: 4
|
|
exact-pinned direct deps, 18 packages, all 5 build scripts read.
|
|
The lsp-types 0.97-over-0.94 choice traded ~40 tested URI lines for
|
|
5 fewer packages — the right direction.
|
|
5. Index scale: 860 files in 0.79s / 29.5MB through a real session.
|
|
Per-file recompute with didSave index rebuild is the documented,
|
|
deliberately boring staleness model; salsa stays deferred until it
|
|
hurts.
|
|
|
|
Lead fix on acceptance: the stale test counts in the work log trued up
|
|
per QA. QA's harness-hang investigation (profiled the server before
|
|
blaming it; found its own threading at fault; matched the e2e test's
|
|
own documented write-then-read pattern) is preserved in the QA log as
|
|
the reference for anyone scripting against the server.
|
|
|
|
Round 12: editor packaging (VS Code extension + Neovim lspconfig) and
|
|
the config/walk library lifts, closing TODO §6.
|