Closes TODO §71: eight owner-ordered features shipped as 0.65.2–0.65.11. No engine change since 0.65.11. - docs/topo.md refreshed through 0.65.11: contracts, server-lane edges, packaging rows, open handshakes 44–66, new modules, choke points; stale FACTS_FORMAT and state.rs references corrected. - CLAUDE.md: file sizes re-measured. - Feature READMEs: five stale facts corrected. - large.rs: the two linear-time tests re-measure up to three times before failing (0.65.11's Linux CI run read 24.9x against a 24x limit under load). Co-Authored-By: Claude Mythos 5.2 <[email protected]>
ifdef-folding
Goal
Owner: "ifdef and else block should support collapsing. It should also be part
of the floating bars." Every branch of a `ifdef / `ifndef …
`endif region becomes a textDocument/foldingRange, so each branch
collapses on its own and — because the extension sets
editor.stickyScroll.defaultModel: foldingProviderModel for both languages
(TODO §67) — the branch's directive line is pinned by VS Code's sticky scroll
("floating bars") while the reader is inside it. Server-side only: no new
setting, no extension code.
Assumptions
- Directives are what the lexer says they are.
vlog_parser::lexermakes each of the five directives oneTokenKind::Directivetoken running to the end of its line (is_line_directive,lexer.rs:899; capture atlexer.rs:187-260). Consequences, all tested:- in a
//or/* */comment → trivia, never a fold; - in a string → part of the string literal;
- inside a
`definebody (backslash continuations) → text of the`definetoken, never a fold; `ifdef A … `else … `endifon one line is a single token (the rest of the line is its text), so there is nothing to fold — correct;- leading whitespace, trailing
////* */comments (the lexer stops before them) and CRLF change nothing. - A directive written after code on its line (
module m;ifdef A,initial beginifdef X) is still a directive, and its branch fold starts on that code line — but that line already starts themodule/beginfold, which is sent first, so in VS Code such a branch gets no fold of its own (the existing fold and its sticky-scroll header win; see the ordering rule below). Zero such lines in OpenTitan (4 061 files) or the corpus (860 files):not_first_on_line: 0,shared_start: 0.
- in a
- No existing fold is lost or changed by this feature (lead's ruling,
2026-11-19). Two rules, both in
folding.rs:- a branch fold with exactly the same two lines as an existing scope or
comment fold is not added — the existing fold keeps its kind, so a
/* */opened on the directive line and ending on the line before the next directive stays acommentfold; - the answer's order is defined in one place,
in_answer_order: by start line; on a shared start line every scope/comment fold (in its own(start, end)order, byte-identical to before) comes before any branch fold. Because VS Code keeps only the first range it receives for a start line, the branch fold is the one that yields.
- a branch fold with exactly the same two lines as an existing scope or
comment fold is not added — the existing fold keeps its kind, so a
- Fold shape — a branch runs from its directive's line to the line before
the next directive of the same region.
`ifdefline L0,`elseL5,`endifL9 →(0, 4)and(5, 8). Collapsing the first branch leaves`elsevisible and separately collapsible; collapsing the last leaves`endifvisible. Chosen to match the existingbegin/endrule infolding.rs(the closer stays on screen). For C, VS Code itself ships no#ifdeffolding —extensions/cpp/language-configuration.jsonfolding markers are#pragma region/#pragma endregiononly (checked in the VS Code repo, main branch, 2026-11-19);#iffolding comes from the C/C++ extension's provider, whose exact shape I did not verify. The shape here is the one where every directive line stays visible, which is the only one that lets each branch collapse independently. - Kind:
region. Same as every scope-pair fold. LSP 3.17 defines onlycomment,imports,region; VS Code's Fold All Regions (editor.foldAllMarkerRegions) folds kindregion(folding.tsFoldAllRegionsAction→setCollapseStateForType(Region)), which already includes everybeginfold, so branches joining it is consistent.importswould be wrong (and would auto-collapse undereditor.foldingImportsByDefault). - Degraded input (all tested, none panic):
- a region still open at end of file folds the branches it finished
(
`ifdef…`else… EOF folds theifdefbranch) and nothing for the open one — the same "never fold to EOF" policy as an unclosedbegin; - a stray
`else/`elsif/`endifwith no region open is ignored and does not disturb later regions; - a branch with no line between its directive and the next yields no range
(
pushdropsend <= start).
- a region still open at end of file folds the branches it finished
(
- A file that does not lex has no tokens and folds nothing, as before.
VS Code facts this relies on (verified in source, microsoft/vscode main, 2026-11-19)
syntaxRangeProvider.tscollectSyntaxRangeskeeps a provider range only ifstart > 0 && end > start && end <= lineCount(1-based there) — every range we send satisfies it (pinned by the OpenTitan sweep).sanitizeRangessorts by start line (then provider rank, a stable sort) and keeps crossing ranges: an entry that starts inside the current top and ends after it is added at the top's nesting level without becoming the top. Ranges sharing a start line: the first in our order survives (entry.start > top.startguard) — with one nuance QA found: the guard compares againsttop, and a crossing entry never becomestop, so if the first range on a line was itself added as a crossing entry, a second same-start range that also crosses is kept as well (harmless). A branch fold shares a start line with an existing fold in two ways: a directive after code on its line (module m;ifdef A), or a multi-line/* /opened after the directive (``ifdef A / … ``). Existing folds are sent first, so in both cases the existing fold survives and the branch yields.- Parent/child (what sticky scroll nests by) is recomputed by containment
in
foldingRanges.tsensureParentIndices, and the sticky model is built from thoseFoldingRegions(stickyScrollModelProvider.ts_fromFoldingRegions, range end + 1). So a crossing branch is a child of the nearest fold that contains it, and sticky scroll still shows a sane stack. - When the count exceeds
editor.foldingMaximumRegions(default 5000) the collector keeps shallow levels first. Not new; branches add ~0.26 ranges per OpenTitan file on average. - LSP 3.17 (
foldingRange.md): validity is per range (lines within the document); the spec says nothing against overlap, and "clients are free to ignore invalid ranges".
Crossing structure
Real RTL opens a begin in each arm and closes it once below the endif
(test a_region_crossing_a_begin_keeps_both_sets_of_folds). The result is
[(0,9) module, (2,3) ifdef, (3,8) begin, (4,5) else, (5,7) begin]: the scope
folds are whatever pairs::analyze already made of the unbalanced
begins (unchanged by this feature), and the branch folds are added beside
them, crossing. Per the facts above VS Code keeps all five; sticky scroll at
line 7 shows module → if (a) begin → if (b) begin.
Handshakes
- Consumes
vlog_parser::token::{Token, TokenKind::Directive}and the lexer's directive capture, read-only. No parser change: the representation is sufficient. The directive-word rule (backtick, then the identifier prefix) is private invlog_parser/src/parser/directive.rs:15-28; it is four lines and is repeated infolding/directives.rsrather than widened into the parser's public surface. (A third copy, by first whitespace word, lives inon_type/auto_end.rs:258-261,conditional; the first-word split is line 259.) If a publicToken::directive_wordis ever added, all three should use it — a request, not a blocker. - Promises
folding::folding_ranges(the only caller isserver/dispatch.rs, unchanged): sorted by start line (tie-break inin_answer_order: existing folds, in their old(start, end)order, before branch folds), de-duplicated by(start, end)with the existing fold winning, every rangestart < end, branch folds kindregion. With the branch folds removed the answer is exactly the old answer — asserted per file by the sweep (check_existing_unchanged). - Large-file path: unchanged. A buffer over the threshold is
Document::large(state/document.rs:103), whosetokensare empty, sofolding_rangesanswers[]for it exactly as before — pinned already byserver/tests/large_file.rs(FoldingRangeRequest→ empty). Supporting branch folds there would need a line scan of the raw text in or besidelarge.rs, which this lane does not own; not requested. - Scope note for the lead: the end-to-end test is a new file,
crates/lucisv_server/tests/ifdef_folding.rs(a new integration test, not an edit toe2e.rs), repeatinge2e.rs's twenty lines of framing.
Status / TODO
- Find how directives are represented (one
Directivetoken per line). folding/directives.rs: one linear pass → branch spans.- Wire into
folding_ranges(kindregion). - Unit tests for every edge case in
folding/ifdef_tests.rs(15). - Wire test
tests/ifdef_folding.rs. - OpenTitan sweep
folding/opentitan_sweep.rs(#[ignore], skips when absent). - Timing before/after.
- VS Code README feature rows (Folding, Sticky scroll).
- Fix round: existing folds win identical lines and shared start lines
(QA findings 1–2);
in_answer_orderdefines the order; sweep asserts the non-branch answer is unchanged. - Human check in a running VS Code (cannot be done by the agent):
collapse an
ifdefbranch (theelsestays visible), collapse theelsebranch (theendifstays visible), nested regions, sticky scroll pinning the`ifdef/`elseline while scrolling inside a long branch, and a crossingbegin(e.g. oneif … beginper arm, oneend).
Work log
2026-11-19 — dev
- Directives: the lexer's
Directivetokens are exactly the right representation (comments/strings/define bodies already excluded), so the new pass reads onlytoken.kindand the first word. Builtcrates/lucisv_server/src/folding/directives.rs(branch_spans, ~90 lines): a stack of open-branch start lines;Openpushes,Nextemits the current branch and restarts it,Closepops and emits. Line numbers come from the caller (folding::line, the sameLineIndexconversion as the other folds).folding.rsgained one loop and the module declarations. - Tests:
folding/ifdef_tests.rs— shape,elsifchain, three-deep nesting, empty branch, one-line region, unterminated, stray directives, port list,case+generate,definebody, comment/string, whitespace/trailing comments/CRLF, crossingbegin(exact list pinned), kind, back-to-back. All passed on the first run.tests/ifdef_folding.rschecks the same over the wire (elsif/else/nested ifndef). - OpenTitan sweep (
LUCISV_OPENTITAN_HWor~/.cache/lucisv-opentitan-full/hw, 4 061.sv/.svh/.vfiles, release build, throughtools/guard.sh): no panic; every rangestart < endandend < line count; every branch fold starts on a line holding a conditional directive token, and that token is the first on its line in every case (not_first_on_line: 0); every non-empty branch is present in the answer. Counts: 1 839 directive tokens (772ifdef/ifndef, 295elsif/else, 772endif), all matched, 0 unclosed → 1 067 branch spans = 295 + 772, of which 1 061 are ranges (6 empty branches). A naive text count of lines starting with a directive finds 1 874: the 35 extra are in block comments (prim_macros.svh:35-46) and`definebodies (prim_assert*.sv*,prim_flop_macros.sv,dv_defines.svh, ibexcheck/top.sv:181) — correctly not folded. One file does not lex (riscv_core_setting.tpl.sv, a template) and folds nothing, as before. - Timing (
folding_rangesper file, release, same machine, warm): before — whole tree 29.9 ms, slowesttop_darjeeling/.../pinmux_reg_top.sv(1.3 MB) 0.84 ms; after — whole tree 34.4–35.0 ms, slowest the same file 1.09 ms, of which the branch pass is ~0.25 ms (it touches every token once: ~1.5 ns/token). Two after-runs agreed within 2%. - Not touched:
vlog_parser,vlog_formatter,large.rs, dispatch,package.json.
2026-11-19 — dev, fix round (QA findings 1 and 2, lead's ruling)
folding.rssplit intoscope_and_comment_folds(the old body, verbatim: pairs + comments, sort(start, end), dedup),branch_folds(drops a branch whose(start, end)an existing fold already has, so that fold keeps its kind) andin_answer_order(the one place the order is defined: a merge by start line, existing folds first on a tie).- Deviation from the brief's wording, flagged for the lead: the ruling
said "send the LONGER one first" and also "an existing fold is never lost
or changed". These disagree in QA's third repro (
`ifdef A /* c1\n c2 */): the comment(0,1)is the existing fold and the shorter one. Longer-first would put the branch(0,2)first and VS Code would drop the comment fold. Longer-first applied to all folds would also reorder existing same-start pairs (e.g. abegin /* … */line), so non-directive folds would no longer be byte-identical to base. I implemented "existing first" instead. It gives the same answer as longer-first for both QA repros where the existing fold is longer (module m;ifdef A,initial beginifdef X), keeps the comment in the third, and leaves every non-branch fold in its old order. If longer-first really is wanted for the comment case, it is a one-line change inin_answer_order. - Tests added to
folding/ifdef_tests.rs: the three QA repros and the comment-kind case (19 tests now); thefoldshelper asserts every answer is sorted by start line. - Sweep: new per-file assertion
check_existing_unchanged(answer minus branch folds == the scope/comment folds exactly, same order and kinds; answer length == both added together) and two counts. OpenTitan: as before (1 839 tokens, 1 067 spans, 1 061 ranges),same_lines_as_existing: 0,shared_start: 0, tree 33.8 ms, slowest file 1.09 ms. Corpus (~/.cache/lucisv-corpus, 860 files, viaLUCISV_OPENTITAN_HW): 923 tokens, 511 spans, 511 ranges,shared_start: 0,same_lines_as_existing: 0,not_first_on_line: 0, passed.
Changelog paragraph (for the lead)
`ifdef branches fold, and stick. Every branch of a
`ifdef/`ifndef region now folds on its own, from its directive to
the line before the next `elsif/`else/`endif — which stays
visible, so the else branch can be collapsed separately — and, because
sticky scroll follows the folds, the directive of the branch you are in is
pinned at the top of the editor with the module and blocks around it. Nested
regions fold at every depth; directives inside comments, strings and
`define bodies are left alone; an unterminated region never folds to the
end of the file. Buffers over the large-file threshold still fold nothing.
QA log
2026-11-19 — QA (Opus 5.5)
Verdict: PASS WITH FINDINGS (two low-severity findings, two info notes; nothing fixed by QA, no source file touched). The machine was heavily loaded throughout (another QA lane's cargo jobs, load average 19–21), so the timings below are upper bounds.
Gates (worktree, uncommitted diff on 948f8a0):
cargo fmt --all -- --checkclean;cargo clippy --all-targets -- -D warningsclean (the one cargo-levelworkspace.package.authorsmanifest warning is pre-existing and not a lint).tools/guard.sh -- cargo test -p lucisv_server: 1 973 passed, 0 failed (lib 1 863 + 37 ignored; e2e 106; grammar 3;ifdef_folding1; opentitan_references 0 + 2 ignored).tools/guard.sh -- cargo test -p vlog_formatter: all green.node --test editors/vscode/*_test.js: 37/37.- Ignored sweep,
tools/guard.sh -t 1500 -- cargo test --release -p lucisv_server opentitan_sweep -- --ignored --nocapture: ok; 4 061 files, 1 unlexed, 1 839 tokens (772/295/772), 1 067 spans, 1 061 ranges, 0 unclosed,not_first_on_line: 0; whole-treefolding_ranges33.4 ms (branch pass 4.7 ms), slowesttop_darjeeling/.../pinmux_reg_top.sv1.07 ms (branches 0.24 ms) — consistent with the work log. - Scope:
git statusshows onlyfolding.rs(modified, purely additive: module decls, doc, one loop),folding/{directives,ifdef_tests, opentitan_sweep}.rs,tests/ifdef_folding.rs,editors/vscode/README.md, this README. Sizes:folding.rs296 lines incl. tests (~85 production),directives.rs85 — well under CLAUDE.md thresholds.
Attack inputs over LSP (release and debug lucisv-server, one
didOpen + textDocument/foldingRange per buffer; script kept in the QA
scratchpad, qa714/cases.py). Hand-computed expectation matched every one:
10-deep nesting (i, 19-i) for i=0..9; elsif chains; empty first branch
(ifdef/else adjacent → only the else fold); else directly before
endif; two else in one region and elsif after else (each treated as
"next branch", three folds, no panic); endif // c; endif /* multi-line */
(comment folds separately, branch unaffected); spaces/tabs before
directives; CRLF; no trailing newline ending in `endif; directives in
/* */, //, a string inside a live region ($display("endif else")),
a `define body with \ continuations (LF and CRLF), a `define with
a trailing \ at EOF (both after a region and alone); mid-line
assign a = b; ifdef Xandend ifdef A (lexed as a directive, fold
starts on that code line — sensible); region crossing begin…end,
crossing a module boundary, wrapping a whole module, inside a port list,
inside a case; `ifdef_helper/`elseif/`endif_x/`IFDEF/
`ENDIF (no folds); `include/`timescale between branches;
one-line region; stray else/endif; unterminated region.
Fuzz (qa714/fuzz.py, 2 × 5 000 random buffers through one server
session each, through tools/guard.sh): half well-nested generated regions
up to 7 deep, half random directive/code/comment/define/string/look-alike
line soup, 30 % CRLF, 20 % no trailing newline. Checked against an
independent line-model (my own scan: directive first on a line, outside block
comments and define bodies): every answer present, sorted, start < end < line count, region folds == model's non-empty branch spans exactly, every
fold on a directive line, no crossing branch folds in well-nested input.
0 failures in 10 000. Sanity: the same checker against the base binary
fails 1 673/2 000, so it is not vacuous.
Scale (qa714/big.py): 50 000-branch elsif chain (1.4 MB), 25 000
back-to-back ifdef/else regions, and 50 000-deep nesting (1.7 MB): 0.20 s,
0.22 s, 0.24 s round-trip vs base 0.17/0.18/0.20 s; 12.5k → 25k → 50k
doubles cleanly (linear, no quadratic term, no stack overflow at 50 000
deep). VS Code's 5 000 cap (RangesCollector.toIndentRanges) keeps shallow
levels first and, within the cut level, the first in order — for a flat chain
the module plus the first 4 999 branches; nothing harmful. Note only that a
branch fold adds one nesting level to what it contains, so in a file already
over 5 000 folds a few deep begin folds may now fall past the cut instead of
a branch. Not new behaviour, no real file near it.
Regression of existing folds — done by building the base, not by
reading the diff: git archive 948f8a0 into the QA scratchpad, own
CARGO_TARGET_DIR, release build; both binaries over the full OpenTitan
hw tree (4 061 files) and ~/.cache/lucisv-corpus (860 files) via LSP.
Result: every base fold (start, end, kind) is still present in the new
answer (0 lost in 4 921 files), and new − base equals the independent model's
non-empty branch spans exactly in every file (0 mismatches). So on real code
the non-directive fold set is identical to 948f8a0. Independent recount
(own scan, not the lexer): OpenTitan 1 839 directives (772 open / 295 next /
772 close), 1 067 spans, 1 061 non-empty, 0 unclosed — matches the dev
exactly; corpus 923 directives, 511 spans, 511 non-empty.
VS Code source (microsoft/vscode main, fetched 2026-11-19:
folding/browser/syntaxRangeProvider.ts, foldingRanges.ts, folding.ts,
stickyScroll/browser/stickyScrollModelProvider.ts,
stickyScrollProvider.ts, stickyScrollController.ts). Confirmed: the
start > 0 && end > start && end <= nLines filter; sanitizeRanges sorts by
start then provider rank (stable, so our order), drops any entry whose start
equals the current top's start, and adds crossing entries at top's level
without making them top; ensureParentIndices assigns parents by
containment (popping a non-containing parent); sticky scroll builds its tree
from those parents (_fromFoldingRegions, end + 1) and walks it;
FoldAllRegionsAction → setCollapseStateForType(Region). Nuance to the
README's "only the first survives": that holds when the first becomes top;
if the first was itself a crossing entry (not top), a second range with the
same start that also crosses is kept as well — harmless. With a crossing
fold, sticky scroll gets sibling roots at the same depth (e.g. module a and
an ifdef that runs into module b are both depth-0 candidates), so both
lines are pinned; exact pixel layout needs a running VS Code.
Findings
- Low — a block-comment fold can lose its
commentkind.crates/lucisv_server/src/folding.rs:55-56: branch spans are pushed before comments and the dedup keeps the first of an equal(start, end), so when a multi-line/* */starts on a directive line and ends on the line before the next directive, the basecommentfold becomes aregion. Repro:"`ifdef A /* c1\n c2\n c3 */\n`else\n b;\n`endif\n"— base[(0,2,comment)], new[(0,2,region),(3,4,region)]. Effect: Fold All Block Comments no longer folds it (Fold All Regions now does); the hidden lines are the same. 0 occurrences in OpenTitan + corpus. - Low — same-start-line collisions keep the shorter fold, which can drop
an existing one in VS Code. Sorting
(start, end)ascending puts the shorter range first, and VS Code keeps only that one. Repros (LSP):"module m;ifdef A\n a;\nendif\nendmodule\n"→[(0,1) ifdef, (0,2) module]: VS Code drops the module fold that base showed (and sticky scroll no longer pinsmodule m;past line 1);"module m;\ninitial beginifdef X\n a;\n b;\nendif\n c;\nend\nendmodule\n"→(1,3)ifdef before(1,5)begin: theinitial beginfold is dropped. Conversely"ifdef A /* c1\n c2 */\n x;\nelse\n b;\nendif\n"→(0,1) commentbefore(0,2) region: the **branch** is the one dropped. The README (Assumptions → VS Code facts) says a shared start line happens "only when a directive follows code on its line"; the comment case shows it is also a multi-line block comment *after* the directive. 0 occurrences in 4 921 real files (only directive-after-text lines found are inside//comments,prim_flop_2sync.sv:33,37`). Whether equal-start ranges should be ordered longer-first (keeps base folds, loses the branch) is a design choice for the lead, not a QA fix. - Info — lone-CR files fold nothing, base and new alike (the lexer and
line index only break on
\n). Pre-existing, unchanged. - Info — README accuracy: line references checked and correct
(
lexer.rs:187-260,:899;parser/directive.rs:15-28;on_type/auto_end.rs:258;state/document.rs:103). Corrections: see finding 2 (the same-start condition) and thesanitizeRangesnuance above. The "not verified" list (C/C++ extension's#ifshape, the human VS Code check) is honest and remains unverified.
Unverifiable without a running VS Code: the visual result of collapsing each branch, the sticky-scroll stack and its layout for crossing folds (two depth-0 siblings), and which fold the user actually sees for the same-start cases above (derived from source, not observed).
Review
Lead, 2026-11-19. Accepted for 0.65.4.
- Built on the lexer's directive tokens with no parser change: the right
foundation, and it is why the 35 look-alike lines in OpenTitan are skipped
without a special case. The three copies of the directive-word rule are a
fair follow-up (
Token::directive_word), not this round's business. - My fix-round instruction said "longer first"; the dev was right to depart
from it. The principle I gave — an existing fold is never lost or changed —
and "longer first" disagree when a short comment fold shares a start line
with a longer branch, and the principle is the one that matters.
"Existing first" is what ships, defined in one place (
in_answer_order). - QA's regression check is the proof I wanted: base built from
git archive, both binaries over 4 921 real files, non-directive folds byte-identical; a 10 000-case fuzz against an independent model whose checker demonstrably fails on the base binary. - Owed to a human: the collapse and sticky-scroll behaviour in a running
editor, in particular crossing regions (an
ifdefthat spans two modules pins both headers as siblings, by QA's reading of VS Code's source). - Open, recorded: no folds on the large-file path; lone-CR files fold nothing (as before).