# selection-formatting ## Goal VS Code's "Format Selection" (`textDocument/rangeFormatting`) failed more than half the time on the selections people actually make — one whole `always` block, one whole `case`, usually nested in blocks the selection does not cover. The request went to `format_range` (the CLI's `--lines`), whose unit is a whole module-level item laid out at formatter depth: selecting a `case` re-laid the whole `always`, a block in a four-space or tab-indented file came back re-indented to two spaces, a selection inside `generate` or a function re-laid the whole region, and any parse error anywhere refused the request. `format_selection` lays out **only the smallest run of sibling items or statements the selection covers**, at the indentation its first line was written at, and splices it into otherwise untouched bytes. The owner's rule: don't worry about the parent; the selected block keeps the indentation level it starts at; the result must be functionally the same. ## Semantics ### Scopes and units A *scope* is a sibling list exactly as `fence.rs` defines one: item lists (file, module, package, generate region, generate `begin`…`end`, class) and statement lists (`begin`…`end`, `fork`…`join*`, function and task bodies). A single-statement body (`if (a) x = 1;`, `always @* x = 1;`) or a block-less generate item is not a scope; it is walked *through* to the scopes it reaches. A *unit* is one item or statement with its whole extent: first leading comment or attribute through the comments written after it on the same line. ### Locating the target (`selection/locate.rs`) For one selected line span, starting at the file scope: 1. Take the units whose lines meet the span. Blank lines select nothing; a span meeting no unit changes nothing. 2. If exactly one unit is met, the span touches neither its first line nor its last, and exactly **one** of its nested scopes has a unit the span meets, descend into that scope and repeat. *(Lead ruling 2026-11-09, QA note 2: only the unit's **first** line is asked about. A selection over a block's last statements and its closing `end` descends and lays out those statements; the closing line alone meets no nested unit and still names the unit it closes.)* 3. Otherwise the target is the run of consecutive units met — a partial selection expands to whole units. 4. **Fences outrank the selection.** Units a fenced region *of this scope* reaches (a region nested inside a unit's own code does not count) are trimmed from both ends of the run; an empty run changes nothing. A region is never half inside the splice. 5. **Line-clean or one level up.** The run must be replaceable by whole lines: only spaces/tabs before its first byte on that line, only whitespace after its last byte on that line, no sibling unit's extent and no dangling comment of the scope inside it. If not (`begin // note` makes the first statement's leading comment start on the `begin` line; `x = 1; y = 2;` with only `x` selected is fine because both are met), the enclosing unit is the target, checked the same way. At the file scope there is nowhere to go up to, and the request is deferred. 6. **Big containers defer.** A run holding a `module`/`interface`/`program` or `package` item goes to `format_range(source, config, lines)` unchanged — header/footer splitting and whole-file selections behave exactly as before. The located target is recorded as a **path** — `(unit index, child scope index)` per descent, plus the run's start and length — not as bytes or lines. ### Layout and splice (`selection/mod.rs`, `format::print_run`) - `print_run` builds the ordinary `Fmt` over the whole source (fenced regions from `fence::collect`, no range splits) and calls `item_seq(run, depth)` or `stmt_seq(run)` on the sub-slice. `depth` is the AST depth `item_kind` would pass down (it only feeds the alignment width budget). - The **base indentation** is the leading whitespace of the run's first unit's line, as written (tabs included) — or, when that unit is a compiler directive and a later unit is not, the later unit's: directives are commonly written at column 0 while the code they guard is indented, and the code says where the block stands. The directive is then indented with the block, as a whole-file run indents it. - `Printer::print_at(doc, base)` starts the text with `base`, writes it after every line break before the indentation, and charges its width against the line budget (a tab counts as one indent width). `Doc::Verbatim` and `Doc::Inline` keep their own absolute indentation, and a line holding nothing but indentation is emptied so blank lines never keep the base's tabs. `print` is `print_at(doc, "")`, byte for byte the old printer. - The splice replaces `line start of the first unit .. end of the last unit's extent` with the printed text and nothing else: blank lines at the boundary, the rest of the last line and the file tail (final newline or not) are untouched. In a file whose lines end in `\r\n` (judged at the target), every line break the printer wrote becomes `\r\n`; source text copied through keeps the `\r\n` it had. ### Several ranges Each merged span of `LineRanges` selects its own target. Targets whose byte ranges overlap are replaced by the target of the hull of their spans, until none overlap. They are spliced bottom-up and verified together, so the all-or-nothing contract covers the whole request. If any span defers, the whole request goes to `format_range`. ### Safety net (unchanged) `verify_equivalence(source, output)` over the whole file, then convergence by **replaying the targets**: the output is parsed the same way, each path is resolved in its tree, laid out and spliced again, and `verify_convergence` must find nothing to change. `verify.rs` is not touched. Any failure — a target that cannot be found again or cut cleanly in the output included — is an error and no edit (`FormatError::Selection` for the selection's own refusals). ### A file that does not parse `parse_source` first. If it fails, `parse_source_tolerant` builds the tree and the target is located in it the same way. The request is refused when any parse diagnostic lies inside `line start .. end` of a target, or any unit of the target (at any depth reachable through the scope walk) is an `Error` node. The replay parses the output the same way and applies the same check. **Verdict:** sound and useful. Sound because the layout is token-verified over the whole file like every other path: recovery can only mis-guess the *nesting* around a target (an `assign` after a missing `end` becomes a statement), which changes at most how a clean run is laid out, never its tokens — and the target itself is required to be free of diagnostics and error nodes. Useful because in the corpus sweep below, with a broken line injected in every file, 75 % of selections still answered. ## Assumptions - A tab in the base indentation is worth one indent width for the line budget. The printer cannot know the reader's tab stop; only group breaking depends on it, and the replay uses the same rule, so it cannot break convergence. - Comment `col` is a byte column with a tab counting 1, so `raw_lines`' dedent-by-column cancels a base containing tabs exactly as it cancels spaces (exercised by the tab tests). - A parse diagnostic's span is the token the parser gave up on, not the extent of what it swallowed; the `Error`-node walk covers the latter at list level. An error node nested in an expression or header list is assumed to come with a diagnostic inside it. The safety net backs both. - The alignment of a sub-slice is planned over the sub-slice only (a run holding half of an alignment group aligns that half). Stable under replay. - With `uvm-utils-indent` on, a run holding a `` `uvm_*_utils_begin `` without its `_end` indents what follows it inside the run, as a whole-file run would. ## Handshakes - **Consumes** `fence::collect`, `fence::region_at`-shaped regions, `fence::with_trailing_comments` (already `pub(crate)`), `Fmt::item_seq` / `Fmt::stmt_seq` (already `pub(super)` within `format`), `format_range`, `verify_equivalence`, `verify_convergence`, `vlog_parser::parse_source`, `parse_source_tolerant`. - **Provides** `vlog_formatter::format_selection(source, config, lines)` and `Printer::print_at(doc, base)`; `format::print_run` / `format::Run` (`pub(crate)`); a new `FormatError::Selection(String)` variant (every match on `FormatError` in the workspace already has a catch-all arm). - **Changed for the server:** `lucisv_server::format::{range_formatting, ranges_formatting}` now call `format_selection`. `on_type.rs`'s semicolon trigger calls `format::range_formatting`, so it changes too. - **Request (not done — outside this lane's files): `crates/lucisv_server/src/on_type.rs`.** Two of its unit tests pin behaviour this design changes on purpose, and fail: 1. `a_semicolon_in_a_buffer_the_engine_refuses_answers_nothing_at_all` (line ~1175) — its buffer's error (`wire ;`, line 3) is *outside* the keystroke's statement (line 2), so the request now formats line 2 (design step 7). Proposed fix: put the error on the keystroke's own line, e.g. `"module m;\n wire a = ;\nendmodule\n"` with the `;` at line 1, char 13 — the change made to the twin test in `server/tests/formatting.rs`. 2. `a_semicolon_at_eof_with_no_trailing_newline_still_lays_out_its_line` (line ~1210) — the splice no longer adds a final newline (design step 5); the expected text becomes `"module m;\n wire a;\nendmodule"` and the comment above it should say the file tail is untouched. The module doc at line ~64 ("`format_range` selects by …") is also stale. - The CLI `--lines` keeps calling `format_range`; `range.rs` is unchanged. ## Status / TODO - [x] `printer.rs`: `print_at(doc, base)`; `print` delegates with `""`. Whole-file output byte-identical (snapshot + idempotency suite green before any selection test existed). - [x] `format/mod.rs`: `Run`, `print_run`, `FormatError::Selection`. - [x] `selection/scope.rs`: scopes, units, extents, the nested-scope walk. - [x] `selection/locate.rs`: locate (descend, fences, line-clean, defer), path resolution, error-node walk, base indentation. - [x] `selection/mod.rs`: `format_selection`, multi-target hull merging, bottom-up splice, CRLF, tolerant path, replay. - [x] `tests/selection.rs` — 33 tests (incl. the directive-base test). - [x] Server: `ranges_formatting` → `format_selection`; 3 handler tests in `format.rs`, 1 dispatch test + 1 updated in `server/tests/formatting.rs`, 1 e2e leg. - [x] `on_type.rs` test updates — Handshake request above (applied by the lead, 2026-11-09). ## Work log ### 2026-11-09 — dev - Built as designed, as a directory module (`selection/{mod,scope,locate}.rs`, each well under 300 production lines) rather than one file. - **Deviation 1 — multi-range lives in the engine.** The design put the per-span targets and hull re-selection in the LSP handler; `format_selection` takes a `LineRanges` anyway, so it does that itself and verifies all targets in one pass. The server only swaps `format_range` for `format_selection`. - **Deviation 2 — descent needs exactly one reached child scope.** A span covering both branches of an `if` reaches two scopes; it takes the `if` rather than one branch. - **Deviation 3 — directive base.** The base indentation is taken from the first non-directive unit of the run; found by a scratch run where a run starting at a column-0 `` `ifdef `` pulled the guarded code to column 0. - **Fence check** counts only regions opened in the run's own scope; a region nested in a unit's code is laid out verbatim by the printer as in a whole-file run, so it does not trim the unit. - **`FormatError::Selection(String)`** added for refusals that are neither a parse error nor a verification failure (a parse error inside the target, a target that cannot be found again). - **Server tests updated:** `a_keystroke_the_engine_refuses_is_answered_with_ silence_and_not_a_popup` (`server/tests/formatting.rs`) — its buffer's error was on another line, which no longer refuses; the error now sits on the keystroke's own line. No `format.rs` test pinned over-reach: the existing range tests select whole module items and come out identical. - **Corpus sweep** (scratch test, release, under `tools/guard.sh`, not committed): 428 formattable files of `corpus/{common_cells,ibex,picorv32, opentitan/hw/ip}` (every ~2nd file), windows of 1, 2, 4 and 8 lines at a stride of 5+w: **33 438 calls, 21 473 changed, 11 965 unchanged, 0 verification errors, 0 selection refusals, 0 source errors.** Same files with ` @@ broken = ;` injected at the middle line: 33 626 calls, 14 159 changed, 10 954 unchanged, 4 281 refused because the target holds the error (or recovery swallowed the rest of the file into an error node), 4 232 source errors (the span reached a module-level unit and was deferred to `format_range`, which parses strictly), 0 verification errors. ## QA log ### 2026-11-09 — QA **Gates (main checkout, all guarded, no guard kills):** `cargo fmt --all --check` clean; `cargo clippy --workspace --all-targets` 0 warnings; `cargo test`: `-p vlog_formatter` 347 passed / 0 failed, `-p lucisv_server` 1881 passed / 0 failed / 40 ignored, `-p lucisv` 143 passed / 0 failed. `verify.rs`, `range.rs`, `fence.rs`, `crates/lucisv` untouched (`git diff --stat`). No source or test files edited by QA; all experiments in a throwaway copy (deleted). **Hand-written attack set:** 221 (source, selection) cases in 2/3/4-space and tab files (nested `generate for` / `always_ff` / `case`, mis-indented parents, `if`/`else` chains, `for`, `fork`/`join`, function and task bodies, case-item blocks, class methods, gen-if/gen-case), comments everywhere, `` `define `` with `\` continuations, `` `ifdef `` at run boundaries, escaped identifiers, attributes, labels, fences (enclosing / unmatched / straddling), CRLF, no final newline, multibyte, mixed whitespace, tabs, empty file, past-EOF, one-line/cursor-only, statements sharing a line, multi-range hulls, files with parse errors. Every window of each case was then run (24 719 calls): **0 panics, 0 token-nonequivalent outputs (independent `verify_equivalence`), 0 non-idempotent results, 0 verification errors except the CRLF finding below.** A "far" detector (changed lines not touching the selection) fired 573 times; every one inspected was the target growing to its whole unit (selection touching a unit's first/last line, a leading `///` comment line, or the module header deferral) as the spec says. **Corpus sweep** (release, 409 files of `corpus/`, 12 random windows of 1-12 lines each, fixed seed): clean 4 908 calls: 3 611 changed / 1 265 unchanged / 32 refused / 0 verification errors / 0 panics / 0 non-equivalent. One random line replaced by ` @@ broken ( ;` (4 908 calls): 1 005 changed / 617 unchanged / 3 286 refused (error inside target or swallowed by recovery) / 0 verification errors / 0 panics / 0 non-equivalent. CRLF-converted (818 calls): 594 changed / 212 unchanged / 7 refused / **5 verification errors** and 1 mixed-EOL output (finding 1). (A shifted-window re-run flagged 18 "non-idempotent" calls; all were artifacts of the shifted window landing on the module header, i.e. a different target — not a defect.) **Sabotage (copy only):** (A) splice tail skips the line after the target: 27 of 33 `tests/selection.rs` tests fail; runtime net alone rejected 14 294 of 24 719 calls, 0 corrupted outputs returned. (B) base indentation prefixed onto every `Doc::Verbatim`: 1 test fails (`a_fence_inside_the_target_is_emitted_as_written`); runtime net (replay convergence) rejected 283 calls, 0 corrupted outputs returned; the whole-file suite cannot see it (empty base) — so one test is all that pins it. (C) fence trimming removed: 2 tests fail (`a_fence_around_the_target_wins`, `a_fence_straddling_the_target_trims_the_fenced_units`); net rejected 241 calls. **Findings** - SHOULD-FIX 1 — CRLF file + target whose last line ends in a `//` comment loses its `\r`. `print_run`'s `out.trim_end()` (`format/mod.rs`, `print_run`) strips the `\r` that the trailing comment's text carries while `Unit::extent` (`scope.rs`) includes it in the replaced bytes, so the line ends in a bare `\n`; the replay then often disagrees and the request is *refused* ("formatting is not idempotent; line N changed from "" to """), otherwise the file comes back with one bare-`\n` line. Repro: `"module m;\r\n initial begin\r\n a = 1; // c\r\n b = 2; // d\r\n end\r\nendmodule\r\n"`, lines `3-4` -> Err; `3-3` of a one-statement variant -> Err; corpus `opentitan/.../uart_tx_rx_vseq.sv` as CRLF, line `215-215` -> Ok with a bare `\n` on line 215. The LF twin of each is fine. Safe (no corruption) but Windows files with trailing comments cannot be range-formatted. - NOTE 2 — selecting interior statements together with the parent's closing `end` (e.g. the last statements of a generate `begin`…`end` plus its `end`) takes the whole parent: corpus `common_cells/src/rr_arb_tree.sv` lines `310-319` re-lays 116..292. By design (step 2/3) but it is the most common sloppy selection; consider whether the owner wants it. - NOTE 3 — inner indentation comes from `Config::indent_width` (2 for the library default), so the engine alone on a 4-space file gives a 4-space block with 2-space nesting inside (`gen-4sp` cases); the server passes the editor `tabSize`, so with `indent_width = 4` the owner's case comes out right (demo below). For tab files the nested levels are `\t…\t` plus spaces (`\t\t\t\t case`), same as the whole-file printer's no-tab model. - NOTE 4 — a selection spanning module-header ports and body items formats only the body items (the header lines are not units); header-only selections defer to `format_range`. - NOTE 5 — a column-0 directive in a run together with indented code is moved to the block's indentation (`` `endif `` + next statement selected -> `` `endif `` indented while `` `ifdef `` stays at column 0). Token-equivalent; cosmetic. - NOTE 6 — with a missing `end` the tolerant tree nests later statements into the open block, so they get laid out one level deeper than the (misplaced) `end` implies. Tokens identical. I could not construct a counterexample where a wrong parse changes meaning: only whitespace is chosen by layout, the token/comment stream is compared exactly, and line-sensitive tokens (`` `define ``, directives, line comments) are tokens whose text includes their line. **Usability (owner's complaint)**, 4-space file, `generate for` -> `always_ff` -> `case`, `indent_width = 4`: selecting exactly the `case` lines (6-10), exactly the `always_ff` lines (5-11), one middle line (8) and the three case items (7-9) all yield the same correct result, and every byte outside the `case` is unchanged: before after (selection 8-8) always_ff @(posedge clk) begin always_ff @(posedge clk) begin case (sel[i]) case (sel[i]) 2'b00: q[i]<=a; 2'b00: q[i] <= a; 2'b01 : q[i] <= b; 2'b01: q[i] <= b; default:q[i]<=c; default: q[i] <= c; endcase endcase end end **Not verified:** the editor (VS Code / Vim) end to end; opentitan sweep and the byte-identity corpus gates (the 347-test formatter suite incl. snapshots is green, which is the evidence for `print_at("")` == old `print`); files over 120 KB; non-ASCII-heavy corpora beyond the hand-written multibyte cases; `--release` gate script `tools/gates.sh`. ## Review **2026-11-09 — lead. Verdict: accepted, with two fixes of mine after QA.** 1. **The design is a splice, not a second inverted fence**, and that is what answers the owner's complaint: the target keeps the indentation it was written at because nothing above it is laid out at all. The safety argument is the old one, unchanged — whole-file `verify_equivalence` (`verify.rs` untouched, so invariant #4 does not apply) plus a replay of the located target. QA's three sabotages were each caught, with zero corrupted outputs returned in 24,719 hand-case calls and 10,634 corpus calls; no panic. 2. **QA SHOULD-FIX 1 (CRLF), fixed by the lead.** `Unit::extent` counted the `\r` after a trailing `//` comment as part of the unit, so the splice ate it. The extent now stops before it (`selection/scope.rs`); `print_run` trims spaces and newlines only, as `render` does. Pinned by `crlf_with_a_trailing_comment_on_the_last_line_keeps_every_line_ending`. 3. **QA NOTE 2, ruled: only the first line stops the descent.** A selection over a block's last statements and its `end` re-laid 177 unselected lines of `rr_arb_tree.sv`. It now lays out the statements it covers; the `end` line alone still names the unit it closes. Three tests pin the three cases. 4. **`on_type.rs`** (the dev's Handshake request): accepted. The `;` trigger shares the engine, so an error elsewhere in the buffer no longer silences it and the file tail is not normalized; two tests updated, one added. 5. **Accepted as they are**: the dev's four deviations; NOTE 3 (nested levels use `indent_width`, which the server takes from the editor's `tabSize`); NOTE 4 and NOTE 5 (cosmetic, token-equivalent). 6. **Open**: the LSP reply is still one whole-document edit; the engine now knows the exact bytes it replaced, so a minimal edit is possible. Not verified in a running editor.