# instance-folding ## Goal Owner: "only the module definition is floating. I want to extend this a little so that the module instance would be floating as well." VS Code's sticky scroll follows the server's `textDocument/foldingRange` answer (the extension sets `editor.stickyScroll.defaultModel: foldingProviderModel`, TODO §67) and pins the start line of every fold around the top of the viewport. Folds came from keyword pairs, block comments and `` `ifdef `` branches only, so a 200-line instance pinned nothing. This feature adds a fourth fold source, `crates/lucisv_server/src/folding/instances.rs`: one fold per multi-line instantiation statement from its module-type line, and one more per instance whose name sits on a later line (`) u_name (` under a `#(` list), so inside a connection list both `aes_control_fsm #(` and `) u_aes_control_fsm (` are pinned. Server-side only (TODO §72). ## Assumptions - **Fold shape.** Statement: from the line of the module-type name through the line before the `;` — the `);` stays visible, the rule every scope fold follows. Instance: from the line of its name through the line before its connection list's `)`. An instance fold is added only when its name is on a line this statement has not already started a non-empty fold on and when it hides at least one line, so `sub u (` (name on the type line) folds once and `) a (.x(x)), b (` gives `b` its own fold. Inside the `#( … )` list only the statement fold encloses the reader, so only the type line is pinned there. `aes_control_fsm_n.sv` (1-based): type `aes_control_fsm #(` 382, `) u_aes_control_fsm (` 385, `);` 486 → folds `382–485` and `385–485` (0-based `(381, 484)`, `(384, 484)`). The brief said 382–594; the statement ends at 486 in the checked-out tree (594 is a later `prim_buf #(`). - **What is an instantiation: the parse tree.** Found through `vlog_semantic::instantiations::sites`, the walk the call hierarchy, the inlay hints and the workspace index already share — no new visitor. It descends into modules, interfaces, programs (all `ItemKind::Module`), packages, `generate` regions, generate `if`/`else if`/`else`/`for`/`case` blocks, with or without `generate`. - **Not instances (tested):** task/function calls (statements, not items), macro calls (one `Ident` token with its arguments), declarations with an initialiser (`logic x = f(…)`), continuous assignments, gate primitives (`and g (…)` is `ItemKind::GateInstantiation`, which the shared walk excludes on purpose — it names no module). - **UDP instances fold.** `my_udp u (q, a, b);` is syntactically a module instantiation; nothing short of resolving the name tells them apart, and folding a multi-line UDP instance is harmless and arguably right. - **`bind` folds** (the shared walk includes the instantiation a `bind` carries). Its statement fold starts on the line of the bound module's type name, which is the `bind` line unless the bind is wrapped. Tested. - **Two-dimensional instance arrays** (`u [1:0][2] (`) are not an `Instantiation` in the tolerant tree (no site), so they fold nothing. Pinned by a test; a parser change that reads them will flip it. Not a request — none in OpenTitan. - **Where its lines are: the token stream.** The tolerant parser keeps an instantiation whose `)` or `;` is missing (`close_list` and `expect_after_recovery` accept the gap), and its spans then end wherever it gave up — on a nested `.a(b)`'s `)`, for instance. So `instances.rs` re-reads the statement from the tokens: from the token after the type name, `#` `(` … matched `)` when the tree has a parameter list, then per instance the name token at exactly `name_span.start`, any `[ … ]` dimensions, `(` … matched `)` whose end is exactly `Instance::span.end`, `,` between instances, and `;` right after the last. Anything else and the whole statement folds nothing. Bracket matching only looks at tokens that start before the construct's end as the tree has it (the first instance name for `#( … )`, `Instance::span.end` for a connection list), so a broken statement costs its own length and can never match a bracket past it — no fold to the end of the file, no `end < start` (`push` drops `end <= start` anyway). Comments are trivia and attributes `(* *)` are one token, so neither moves a line; a macro use carries its arguments in its own token. - **`` `ifdef `` inside a statement.** Directives are tokens. Inside a connection or parameter list they are skipped by the bracket matcher, so branch folds nest inside the instance fold (tested). An `` `ifdef `` that splits the head (`) dut (` / `` `else `` / `chip dut (` — OpenTitan `top_*/dv/tb/tb.sv`) does not have the shape and folds nothing: which arm's head is real is not knowable here. - **No existing fold is lost or changed** (the lead's rule from ifdef-folding, applied again): - an instance fold with exactly the two lines of a scope, comment or branch fold is not added — that fold keeps its kind (tested: `begin sub u (` … `); end`); - **order on a shared start line: scope/comment folds, then branch folds, then instance folds.** Branch folds were in the answer before this feature, so they are "existing" too and the instance fold yields to them as well. VS Code keeps only the first range per start line, so on `begin : g sub u (` the `begin` keeps its fold and its pin, and on `sub u ( `ifdef X` the branch keeps its fold (both tested). The instance fold is still sent, behind them; - two instance folds on one start line (only possible across two statements written on one line) keep only the longer, since VS Code would keep only one anyway. - **`in_answer_order` is still the one place the order is defined**, generalised from a two-way merge to a stable sort by start line over the sources laid end to end (`[scopes, branches, instances]`). For two sources that is exactly the old merge (equal starts keep the order they were laid down in; each source is already sorted). Proven, not asserted: the old two-way merge is kept verbatim as the oracle in `instance_tests.rs` (`previous_answer`, checked on every test text) and in the OpenTitan sweep (every file). - **Kind `region`**, like scope and branch folds (*Fold All Regions* folds them; `imports` would auto-collapse). - **Large-file fast path: unchanged.** A `Document::large` has no tokens and the empty file's tree, so the walk finds no site and the answer stays `[]` (tested; also `server/tests/large_file.rs`). ## Handshakes - **Consumes** (read-only, no change): `vlog_semantic::instantiations::sites` (the shared instantiation census; `Site::inst`), `vlog_parser::ast:: {Instantiation, Instance}` (`module_span`, `params.is_some()`, `instances[].name_span`, `instances[].span`), `vlog_parser::token::Token` (`is_sym`, `kind`, `span`), `crate::state::first_token_from`, `Document::{tree, tokens, line_index}`. No parser change. - **Promises** `folding::folding_ranges` (only caller `server/dispatch.rs`, unchanged): sorted by start line; on a tie scope/comment folds (old `(start, end)` order), then branch folds, then instance folds; every range `start < end` and inside the file; instance folds kind `region`; with the instance folds removed the answer is exactly the 0.66.0 answer, same order and kinds (asserted per test and per OpenTitan file). - **No requests.** (Noted, not requested: 2-D instance arrays are not an `Instantiation` in the tolerant tree.) ## Status / TODO - [x] Find how instantiations are reached (shared `sites` walk) and where the tree's spans can lie (tolerant recovery of `)`/`;`). - [x] `folding/instances.rs`: statement + per-instance spans, token-verified. - [x] `folding.rs`: `instance_folds` (drop same-lines, one per start), `in_answer_order` generalised to N sources. - [x] Unit tests `folding/instance_tests.rs` (25), with the old-answer oracle on every text. - [x] OpenTitan sweep extended: independent token-rule count, every owed fold present, no unexpected fold, old answer unchanged per file, aes example. - [x] Timing before/after. - [x] `editors/vscode/README.md` sticky-scroll row. - [ ] Seen in a running VS Code (owner): scroll into `aes_control_fsm_n.sv`'s connection list and see both header lines pinned; scroll into the parameter list and see only the type line. ## Work log ### 2026-11-19 — dev - Reused `vlog_semantic::instantiations::sites` for *what* (it already covers generate blocks, interfaces, programs, `bind`, and excludes gates); tokens for *where*, because the tolerant tree keeps a half-typed instantiation with spans ending at whatever it last consumed. `shape()` re-reads the whole statement; any disagreement with the tree → no fold. - `folding.rs`: `instance_folds` (same-lines check by binary search on the already-sorted scope and branch folds — a `HashSet` first, swapped after timing), `in_answer_order` = stable sort by start line over the concatenated sources. - Tests (`folding/instance_tests.rs`, 25): owner's shape exact; no `#(`; one-liners; `)` and `;` on separate lines; multi-instance; two names on one line; instance arrays (and the 2-D non-site); generate `if`/`for` with `begin`, `generate` region + `case` + `else`; interface and program; shared start with a `begin` (yields) and identical lines (dropped); shared start with an `` `ifdef `` branch (yields); `` `ifdef `` inside the list and around the instance; ordered connections; `.*`/`()`; comments everywhere incl. a multi-line one in the list; CRLF; cut off at EOF; missing `)`, missing `;`, half-typed `.a(`, missing `)` of `#(`; calls/macros/ declarations/gates/assigns; `bind`; large file. Every test text also goes through the invariant checks (sorted, `start < end`, region kind, answer minus instance folds == the old two-way merge verbatim). - First sweep run found the *token rule* (the sweep's independent count) too loose, not the code: `end : label` followed by `task_call();` and `endfunction`/`endtask` before an instantiation. Fixed the rule; then 2 remaining "missing" were the split heads in `top_*/dv/tb/tb.sv`, now classified (`split_heads`) and owed nothing. - **OpenTitan sweep** (`LUCISV_OPENTITAN_HW=/Users/lucio/repo/opentitan/hw tools/guard.sh -- cargo test --release -p lucisv_server opentitan_sweep -- --ignored --nocapture`, 4 047 files, passed): token rule finds 18 724 instantiation statements, 18 200 multi-line, 164 of 50+ lines, 2 split heads; 16 277 later-name instance folds owed; **34 450 owed folds, all present, 0 missing, 0 unexpected** (every instance fold the answer has is one the rule owed), 0 identical to an older fold, 0 sharing a start line with an older fold. Old answer unchanged on every file (the verbatim two-way merge as oracle), branch counts unchanged (1 852 directive tokens, 1 072 spans, 1 066 ranges). `aes_control_fsm_n.sv` lines 371–490 now answer exactly `[(382, 485), (385, 485)]` (1-based), asserted. - **Timing** (`folding_ranges`, release, same machine, load ~3): before (base tree, same sweep) whole tree 35.1 ms, slowest `top_earlgrey/.../ pinmux_reg_top.sv` 1.07 ms; after, two runs: whole tree 45.1–46.3 ms, slowest the same file 1.95–1.97 ms, of which the instance pass is 0.62–0.66 ms (the whole tree's instance pass: 7.1–7.3 ms). The rest of the growth is the bigger answer (≈ +8.5 folds per file on average) and its sort. - Test counts: `lucisv_server` lib 1 999 passed + 47 ignored before → 2 024 + 47 after (+25); e2e 106, grammar 3, ifdef_folding 1 unchanged. - Not touched: `vlog_parser`, `vlog_semantic`, dispatch, `large.rs`, versions, changelogs, `docs/topo.md`. ## QA log ### 2026-11-19 — QA (Opus 5.5) **Verdict: PASS.** No defect found; two info-level notes below. **Gates, run by QA** (all through `tools/guard.sh`, no kill): - `cargo fmt --all -- --check` clean; `cargo clippy --all-targets -- -D warnings` exit 0 (only the pre-existing `workspace.package.authors` manifest warning). - `cargo test -p lucisv_server`: lib 2 024 passed + 47 ignored as delivered (2 029 after QA's 5 tests), e2e 106, grammar 3, ifdef_folding 1, opentitan_references 0 + 2 ignored; all green. - OpenTitan sweep (release, `--ignored`): passed, 4 047 files; instances 18 724 statements, 18 200 multi-line, 16 277 later names, 34 450 present, 0 missing, 0 unexpected, 0 shared start, 2 split heads, 164 long. `aes_control_fsm_n.sv` → `[(382, 485), (385, 485)]` (1-based); checked by hand against the file (type 382, `) u_aes_control_fsm (` 385, `);` 486). **Old answer unchanged, independently of the dev's oracle.** Two temporary `git worktree`s in the scratchpad (HEAD = 0.66.0, and HEAD + this diff), each with a throwaway `#[ignore]` dumper (never in the real tree; worktrees removed after), release builds in separate target dirs. Dumped the full ordered answer for 4 933 files (OpenTitan `hw` 4 069 incl. `.vh`, `~/.cache/lucisv-corpus` 860, repo fixtures). New answer with the instance folds removed is **byte-identical, same order and kinds, to the 0.66.0 answer** on every file (75 256 old ranges). Across the new answer (111 226 ranges, 35 970 instance folds in 1 308 files): 0 unsorted, 0 `start >= end`, 0 past the last line, 0 instance folds sharing a start line with an older fold or with another instance fold, every instance fold `region`. **Is the sweep's count independent?** Mostly. It shares no code with `instances.rs` (own bracket matcher over all bracket kinds, own token walk, no `sites`), but it does share the lucisv lexer, `line()`, and it restates the fold-shape rule (`Counted::expected`) — so a lexer bug, or a wrong shape rule in the spec, would cancel out; and it was loosened/tightened after the first run to match. Cross-checked with QA's own counter (scratchpad `count_inst.py`: own comment/string/attribute stripper, own lexer, statements split on depth-0 `;` and block keywords, not lucisv's tokens): OpenTitan 18 679 statements, 18 173 multi-line, 164 long, 34 417 owed folds; **every fold it owes is in the answer**; the answer has 29 folds it does not own, every one inspected and a limitation of QA's script (hierarchical / macro / `: inst` `bind` targets, `` `ifdef `` lines in `top_*/dv/tb/tb.sv`), each fold correct against the source. Answer total on the 4 069 files 34 446 vs the sweep's 34 450: the sweep follows the one symlinked file (`hw/ip/tlul/rtl/tlul_adapter_shim.sv`), `find -type f` does not. **Attacks** (probe files dumped through the new build, each answer read against the source; no wrong fold, no panic anywhere): - Cut at every character and every token blanked to spaces of a text with most shapes (generate, `#(` with string/comment holding `)`/`;`, `` `ifdef `` in the list, array, second instance, `*/ sub v (`, nested call, `)`/`;` split, `` `M(x) sub w ( ``): every fold inside the file, start < end, old answer unchanged, and no instance fold the whole text does not have. Also every single character blanked (scratch only): 0 violations. Kept as a test. - Folds right: `` `MY_MOD u ( ``, `` `MY_MOD #( ``, macro with multi-line args inside `#(`, `(* attr *) sub #(`, `endgenerate sub y (`, `begin end sub k (`, `*/ sub v (`, `) ;; ;`, CRLF + tabs + UTF-8 in comments, nested generate with array + second instance, interface/program, `bind` plain and wrapped, UDP, `sub u8 ( … )\n ;`, `.a((b)\n ));`, `my_class #(.T(int)) obj (` in a module (syntactically an instantiation — right). - Fold nothing (right or harmless): `` `ifdef `` between `)` and the name and around `#( … )`; `foo #(int) x = new(`, `cg cg_i = new(`, `void'(h(`, multi-line task/function calls, typedef'd declaration with initialiser, labelled `assert property ( … ) else $error(`; `)),` and `)) u (` and `.W((8)` unbalanced; a statement after `garbage ( ( ( ;` and after a statement missing its `;` (recovery swallows them — under-fold only). - Same-line probes: on `generate if (A) begin : g sub u (` … `); end` the instance fold equals the `begin`'s and is dropped (as designed). **Timing** (release, same machine, two runs each, sweep's own clock): 0.66.0 whole tree 33.4 / 34.8 ms, slowest `pinmux_reg_top.sv` 1.05–1.10 ms; this tree 45.3 / 46.3 ms, slowest the same file 1.86–2.04 ms (instance pass 0.60–0.70 ms). Dev's 35.1 → ~46 ms and 1.07 → 1.96 ms hold. Per-edit worst case is that file (`pinmux_reg_top.sv`, the three tops), ~2 ms per request. **Standards.** No `unwrap`/`expect()`/`panic!` in library code (`expect` in `instances.rs` is a local helper's name; `panic!` only in `mod tests`), no `#[allow]`, doc comments present. Production lines (non-blank, non-comment, before `mod tests`): `folding.rs` ~86 (66 at 0.66.0), `instances.rs` 89. Longest new production function `instance_spans` 23 lines. README has every required section and matches the code. `in_answer_order`: inputs are sorted by start (scopes by `(start, end)`, branches by start, stable), so the stable sort equals the old merge — confirmed by the cross-build diff above. **Findings** (none blocking): 1. *Info — README claim / dead branch.* `folding.rs:108-109` (`sort_by_key` + `dedup_by_key` on start line) and the Assumptions line "two instance folds on one start line (only possible across two statements written on one line) keep only the longer": not reachable. A non-empty fold of one statement ends at least one line before its `)`/`;`, so the next statement's type line is always after every non-empty fold start of the previous one; within a statement `starts` already prevents it. The sweep and the cross-build dump agree (0 cases in 35 970). Harmless; the dev may reword the README or keep the code as a guard. 2. *Info — pre-existing, not this feature.* Code on the same line after `` `ifdef X `` or `` `endif `` (`` `ifdef X sub w ( `` …, `` `endif sub z ( ``) is not an instantiation in the tree, so it gets no instance fold (the branch fold is unchanged). Repro: probe `module top;\n`endif sub z (\n .a(a)\n );\nendmodule`. **Assumptions vs tests.** Previously untested README assumptions now tested by QA: UDP instances fold, a wrapped `bind` starts on its type line, attributes `(* *)` and a macro in type position do not move a line, brackets/`;` in strings and comments. All others were already covered by the dev's tests. **Fixed / added directly:** five tests appended to `folding/instance_tests.rs` (QA section): every cut / every blanked token of a rich text; macro type + attribute; strings/comments with closers; UDP and wrapped `bind`; class/procedural lookalikes. No production code touched. **Not verified:** behaviour in a running VS Code (owner's checkbox); the request path through `server/dispatch.rs` was not exercised beyond the existing e2e suite (QA called `folding_ranges` directly). ## Review - **2026-11-19 (lead).** Accepted. Read `folding/instances.rs` and the `folding.rs` diff: the tree says what is an instantiation, the tokens say where it closes, and a statement whose tokens are not exactly the tree's shape folds nothing — the right side to fail on. `in_answer_order` is still the one place order is defined. QA's independent 0.66.0-vs-tree dump (4 933 files, 75 256 ranges identical once instance folds are removed) is the proof that no earlier fold moved. `tools/gates.sh` on the tree: PASS, every step (`target/gates/20261119-230338`). QA note 1 (the same-start-line dedup can never fire) stays as a guard. Edge recorded in `docs/topo.md`. Open: seen in a running VS Code (owner); 2-D instance arrays need the parser to read them as instantiations first.