From d57496978fdf31daa63a327758a8f523025cc779 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Thu, 19 Nov 2026 05:30:49 -0800 Subject: [PATCH] Release 0.65.4: `ifdef blocks fold, and pin in sticky scroll MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TODO §71.4. Each conditional-compilation branch (`ifdef, `ifndef, `elsif, `else) is a folding range from its directive line to the line before the next branch or `endif, kind region, nested to any depth; sticky scroll, which already follows the server's folds, pins the branch line. Built on the lexer's directive tokens (folding/directives.rs), so directives in comments, strings and `define bodies are not folded; no parser or formatter change. An existing fold is never lost or changed: scope and comment folds are computed as before and sent first at a shared start line (folding::in_answer_order). Proven on OpenTitan hw (4 061 files, 1 061 branch folds) and the corpus (860 files, 511): non-directive folds byte-identical to 0.65.3 (QA, base built from git archive), 10 000-case fuzz against an independent model. Dev, QA (pass with findings, one fix round) and lead review are in docs/features/ifdef-folding/README.md. Not seen in a running editor. Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both package-lock.json spots); notes in CHANGELOG.md (## 0.65.4) and editors/vscode/CHANGELOG.md. Gates: tools/gates.sh PASS on this tree, lucisv_server 1977/0. Co-Authored-By: Claude Mythos 5.2 --- CHANGELOG.md | 31 ++ Cargo.lock | 18 +- Cargo.toml | 2 +- crates/lucisv_server/src/folding.rs | 66 ++- .../lucisv_server/src/folding/directives.rs | 85 ++++ .../lucisv_server/src/folding/ifdef_tests.rs | 337 +++++++++++++++ .../src/folding/opentitan_sweep.rs | 232 ++++++++++ crates/lucisv_server/tests/ifdef_folding.rs | 125 ++++++ docs/features/ifdef-folding/README.md | 408 ++++++++++++++++++ editors/vscode/CHANGELOG.md | 10 + editors/vscode/README.md | 11 +- editors/vscode/package-lock.json | 4 +- editors/vscode/package.json | 2 +- 13 files changed, 1312 insertions(+), 19 deletions(-) create mode 100644 crates/lucisv_server/src/folding/directives.rs create mode 100644 crates/lucisv_server/src/folding/ifdef_tests.rs create mode 100644 crates/lucisv_server/src/folding/opentitan_sweep.rs create mode 100644 crates/lucisv_server/tests/ifdef_folding.rs create mode 100644 docs/features/ifdef-folding/README.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 7863876..73294b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,37 @@ All notable changes to lucisv are recorded here. Versions follow [semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes (see `README.md`) are the only frozen contract. +## 0.65.4 — 2026-11-19 + +### `` `ifdef `` blocks fold, and pin in sticky scroll + +(`docs/features/ifdef-folding`; TODO §71.4.) + +- **Every conditional-compilation branch folds on its own.** `` `ifdef ``, + `` `ifndef ``, `` `elsif `` and `` `else `` each fold from their own line to + the line before the next branch (or before `` `endif ``). Collapse the + `` `ifdef `` branch and the `` `else `` line stays visible and separately + collapsible; `` `endif `` stays visible too, the way `end` does for a + `begin` fold. Nesting works to any depth. +- **They pin in sticky scroll.** The floating header lines already follow the + server's folds, so while you scroll inside a long branch its `` `ifdef `` or + `` `else `` line stays at the top with the module and blocks around it. +- **Only real directives count.** The folds are built from the lexer's own + directive tokens, so a directive-looking line inside a comment, a string or + a `` `define `` body is not folded (35 such lines in OpenTitan). An + unterminated `` `ifdef `` folds the branches it finished and never runs to + the end of the file; a stray `` `else `` or `` `endif `` is ignored. +- **No existing fold is lost or changed.** On OpenTitan's `hw` tree (4 061 + files) and the 860-file corpus every fold the previous release returned is + still returned, byte for byte, with the 1 061 and 511 branch folds added. + Where a branch would share its start line with an existing fold — a + directive written after code on the same line — the existing fold is sent + first and keeps its place; that never occurs in either tree. +- **Cost:** one extra pass over the tokens: folding all of OpenTitan goes from + 29.9 ms to about 34 ms, and a 50 000-branch file answers in 0.2 s. +- **Limits.** Files over the large-file threshold (4 MiB) return no folds, as + before. Not yet seen in a running editor by a human. + ## 0.65.3 — 2026-11-19 ### Comment keywords, and the brackets in comments explained diff --git a/Cargo.lock b/Cargo.lock index 7e25253..7183329 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -97,7 +97,7 @@ dependencies = [ [[package]] name = "lucisv" -version = "0.65.3" +version = "0.65.4" dependencies = [ "lucisv_core", "rayon", @@ -108,11 +108,11 @@ dependencies = [ [[package]] name = "lucisv_core" -version = "0.65.3" +version = "0.65.4" [[package]] name = "lucisv_mcp" -version = "0.65.3" +version = "0.65.4" dependencies = [ "lucisv_core", "serde", @@ -126,7 +126,7 @@ dependencies = [ [[package]] name = "lucisv_server" -version = "0.65.3" +version = "0.65.4" dependencies = [ "lsp-server", "lsp-types", @@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "vlog_formatter" -version = "0.65.3" +version = "0.65.4" dependencies = [ "vlog_parser", ] [[package]] name = "vlog_linter" -version = "0.65.3" +version = "0.65.4" dependencies = [ "lucisv_core", "vlog_formatter", @@ -279,11 +279,11 @@ dependencies = [ [[package]] name = "vlog_parser" -version = "0.65.3" +version = "0.65.4" [[package]] name = "vlog_refactor" -version = "0.65.3" +version = "0.65.4" dependencies = [ "vlog_formatter", "vlog_parser", @@ -292,7 +292,7 @@ dependencies = [ [[package]] name = "vlog_semantic" -version = "0.65.3" +version = "0.65.4" dependencies = [ "vlog_parser", ] diff --git a/Cargo.toml b/Cargo.toml index 189d997..e58b42f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ members = [ ] [workspace.package] -version = "0.65.3" +version = "0.65.4" authors = ["Guoliang Chen"] edition = "2021" license = "MIT" diff --git a/crates/lucisv_server/src/folding.rs b/crates/lucisv_server/src/folding.rs index d9abb55..7aaef5f 100644 --- a/crates/lucisv_server/src/folding.rs +++ b/crates/lucisv_server/src/folding.rs @@ -4,7 +4,17 @@ //! `pairs::analyze` already computes for the rainbow and the missing-closer //! warnings, or a block comment, which the lexer already attached as trivia. //! This module is the fourth consumer of the first and the second of the -//! second. See `docs/features/references-nav/README.md`. +//! second. See `docs/features/references-nav/README.md`. The third source, +//! the branches of `` `ifdef `` regions, is [`directives`] +//! (`docs/features/ifdef-folding/README.md`). + +mod directives; +#[cfg(test)] +mod ifdef_tests; +#[cfg(test)] +mod opentitan_sweep; + +use std::collections::HashSet; use lsp_types::{FoldingRange, FoldingRangeKind}; use vlog_parser::token::Comment; @@ -13,8 +23,9 @@ use vlog_parser::TextRange; use crate::pairs::analyze; use crate::state::Document; -/// Every foldable region in a buffer: one per matched scope pair, plus every -/// block comment that spans more than one line. +/// Every foldable region in a buffer: one per matched scope pair, one per +/// branch of a closed `` `ifdef `` region, plus every block comment that spans +/// more than one line. /// /// A keyword whose counterpart never arrived is **not** foldable — `analyze` /// leaves it out of `pairs`, and folding to the end of the file because an @@ -22,6 +33,15 @@ use crate::state::Document; /// off. Nothing is capped: a fold list is one range per block, and an editor /// that asked for it wants all of them. pub fn folding_ranges(doc: &Document) -> Vec { + let scopes = scope_and_comment_folds(doc); + let branches = branch_folds(doc, &scopes); + in_answer_order(scopes, branches) +} + +/// The scope-pair and block-comment folds, exactly as they were before +/// branch folds existed: sorted by `(start, end)`, one per pair of lines (a +/// scope pair wins over a comment on the same two lines). +fn scope_and_comment_folds(doc: &Document) -> Vec { let mut out: Vec = Vec::new(); for pair in analyze(&doc.tokens).pairs { // The closing keyword's own line stays visible: LSP hides @@ -43,6 +63,46 @@ pub fn folding_ranges(doc: &Document) -> Vec { out } +/// One fold per branch of every closed `` `ifdef `` region, sorted by start +/// line. Conditional-compilation branches follow the scope rule: the next +/// directive's line (`else`, `endif`) stays visible. A branch whose two lines +/// are exactly an existing fold's is left out, so that fold keeps its kind +/// (a `/* */` opened on the directive line stays a `comment`). +fn branch_folds(doc: &Document, existing: &[FoldingRange]) -> Vec { + let taken: HashSet<(u32, u32)> = existing.iter().map(|r| (r.start_line, r.end_line)).collect(); + let mut out = Vec::new(); + for (start, through) in directives::branch_spans(&doc.tokens, |t| line(doc, t.span.start)) { + if !taken.contains(&(start, through)) { + push(&mut out, start, through, FoldingRangeKind::Region); + } + } + out.sort_by_key(|range| range.start_line); + out +} + +/// The one place the answer's order is defined: by start line; on a shared +/// start line, every scope or comment fold (in their own `(start, end)` +/// order) before any branch fold. +/// +/// The order is load-bearing. VS Code keeps only the *first* range it +/// receives for a start line (`sanitizeRanges`), so whatever comes first is +/// the fold the user gets and the line sticky scroll pins. Putting existing +/// folds first means a branch fold never costs the user a fold they had +/// before — on `module m; `ifdef A` the `module` fold survives and the branch +/// yields. See `docs/features/ifdef-folding/README.md`. +fn in_answer_order(existing: Vec, branches: Vec) -> Vec { + let mut out = Vec::with_capacity(existing.len() + branches.len()); + let mut branches = branches.into_iter().peekable(); + for range in existing { + while let Some(branch) = branches.next_if(|b| b.start_line < range.start_line) { + out.push(branch); + } + out.push(range); + } + out.extend(branches); + out +} + /// Add one range, unless there is nothing between its two lines to hide. fn push(out: &mut Vec, start_line: u32, end_line: u32, kind: FoldingRangeKind) { if end_line <= start_line { diff --git a/crates/lucisv_server/src/folding/directives.rs b/crates/lucisv_server/src/folding/directives.rs new file mode 100644 index 0000000..9f00d14 --- /dev/null +++ b/crates/lucisv_server/src/folding/directives.rs @@ -0,0 +1,85 @@ +//! Folding for conditional compilation: one range per branch of every +//! `` `ifdef `` / `` `ifndef `` … `` `endif `` region. +//! +//! No new scan. The lexer already turns each of the five directives into one +//! [`TokenKind::Directive`] token that runs to the end of its line, and only +//! where they really are directives: never in a comment or a string (those are +//! trivia and literals), never inside a `` `define `` body (the whole body, +//! continuation lines included, is the `` `define `` token's own text). A +//! token's first word is all this module reads. +//! See `docs/features/ifdef-folding/README.md`. + +use vlog_parser::token::{Token, TokenKind}; + +/// What one conditional-compilation directive does to the branch structure. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Conditional { + /// `` `ifdef `` / `` `ifndef ``: a region, and its first branch, begin. + Open, + /// `` `elsif `` / `` `else ``: the current branch ends, the next begins. + Next, + /// `` `endif ``: the last branch, and the region, end. + Close, +} + +/// `(directive line, last line)` of every branch whose region is closed, in +/// 0-based lines, given the line each token starts on. +/// +/// A branch runs from its own directive's line through the line *before* +/// the next directive of the same region, so the `` `else `` and the +/// `` `endif `` stay visible when the branch above them is collapsed — the +/// same rule as `end` under `begin`. Branches with nothing between their two +/// lines come back too (`last <= first`); the caller drops them. +/// +/// A region that never closes contributes the branches it *did* finish +/// (an `` `ifdef `` … `` `else `` … end-of-file still folds its first +/// branch) and nothing for the one still open, rather than folding to the end +/// of the file. A stray `` `else `` or `` `endif `` with no region open is +/// ignored. +pub(super) fn branch_spans(tokens: &[Token], line_of: impl Fn(&Token) -> u32) -> Vec<(u32, u32)> { + // The directive line of the branch that is open at each nesting depth. + let mut open: Vec = Vec::new(); + let mut out = Vec::new(); + for token in tokens { + let Some(directive) = conditional(token) else { continue }; + let at = line_of(token); + match directive { + Conditional::Open => open.push(at), + Conditional::Next => { + if let Some(first) = open.last_mut() { + out.push((*first, at.saturating_sub(1))); + *first = at; + } + } + Conditional::Close => { + if let Some(first) = open.pop() { + out.push((first, at.saturating_sub(1))); + } + } + } + } + out +} + +/// The conditional-compilation directive a token is, if it is one. +fn conditional(token: &Token) -> Option { + if token.kind != TokenKind::Directive { + return None; + } + match directive_word(&token.text) { + "ifdef" | "ifndef" => Some(Conditional::Open), + "elsif" | "else" => Some(Conditional::Next), + "endif" => Some(Conditional::Close), + _ => None, + } +} + +/// The word a directive's text spells, without its backtick or argument: +/// `` `ifndef FOO `` is `"ifndef"`. The parser keeps the same rule private +/// (`vlog_parser/src/parser/directive.rs`); it is four lines, so it is +/// repeated here rather than widened into the parser's public surface. +fn directive_word(text: &str) -> &str { + let rest = text.strip_prefix('`').unwrap_or(""); + let end = rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_').unwrap_or(rest.len()); + rest.get(..end).unwrap_or("") +} diff --git a/crates/lucisv_server/src/folding/ifdef_tests.rs b/crates/lucisv_server/src/folding/ifdef_tests.rs new file mode 100644 index 0000000..f2570ce --- /dev/null +++ b/crates/lucisv_server/src/folding/ifdef_tests.rs @@ -0,0 +1,337 @@ +//! `` `ifdef `` branch folds, through the whole [`folding_ranges`] answer so +//! every test also sees how they sit beside the scope and comment folds. + +use lsp_types::FoldingRangeKind; +use vlog_semantic::WorkspaceIndex; + +use super::folding_ranges; +use crate::state::Document; + +fn doc_of(text: &str) -> Document { + Document::new(None, text.to_string(), &WorkspaceIndex::default()) +} + +/// Every fold as `(start line, end line, kind)`, kinds spelled short, after +/// checking the one ordering promise every answer keeps: by start line. +fn folds(text: &str) -> Vec<(u32, u32, &'static str)> { + let ranges = folding_ranges(&doc_of(text)); + assert!(ranges.windows(2).all(|w| w[0].start_line <= w[1].start_line), "{ranges:?}"); + ranges + .into_iter() + .map(|range| { + let kind = match range.kind { + Some(FoldingRangeKind::Comment) => "comment", + Some(FoldingRangeKind::Region) => "region", + other => panic!("unexpected kind {other:?}"), + }; + (range.start_line, range.end_line, kind) + }) + .collect() +} + +/// The folds as `(start, end)` alone, for tests about lines rather than kinds. +fn lines(text: &str) -> Vec<(u32, u32)> { + folds(text).into_iter().map(|(start, end, _)| (start, end)).collect() +} + +#[test] +fn each_branch_folds_from_its_directive_to_the_line_before_the_next() { + // Collapsing the `ifdef` branch leaves `else` on screen and separately + // collapsible; collapsing the `else` branch leaves `endif` on screen. + let text = concat!( + "module m;\n", // 0 + "`ifdef A\n", // 1 + " wire a;\n", // 2 + " wire b;\n", // 3 + "`else\n", // 4 + " wire c;\n", // 5 + "`endif\n", // 6 + "endmodule\n", // 7 + ); + assert_eq!(folds(text), vec![(0, 6, "region"), (1, 3, "region"), (4, 5, "region")]); +} + +#[test] +fn an_elsif_chain_gives_every_arm_its_own_fold() { + let text = concat!( + "`ifndef A\n", // 0 + " wire a;\n", // 1 + "`elsif B\n", // 2 + " wire b;\n", // 3 + "`elsif C\n", // 4 + " wire c;\n", // 5 + "`else\n", // 6 + " wire d;\n", // 7 + "`endif\n", // 8 + ); + assert_eq!(lines(text), vec![(0, 1), (2, 3), (4, 5), (6, 7)]); +} + +#[test] +fn nested_regions_fold_at_every_depth() { + let text = concat!( + "`ifdef A\n", // 0 + " `ifdef B\n", // 1 + " `ifndef C\n", // 2 + " wire c;\n", // 3 + " `endif\n", // 4 + " `else\n", // 5 + " wire nb;\n", // 6 + " `endif\n", // 7 + "`else\n", // 8 + " `ifdef D\n", // 9 + " wire d;\n", // 10 + " `endif\n", // 11 + "`endif\n", // 12 + ); + assert_eq!( + lines(text), + vec![(0, 7), (1, 4), (2, 3), (5, 6), (8, 11), (9, 10)], + "A, B, C, B's else, A's else, D" + ); +} + +#[test] +fn a_branch_with_nothing_in_it_folds_nothing() { + let text = concat!( + "`ifdef A\n", // 0 + "`else\n", // 1 + " wire b;\n", // 2 + "`endif\n", // 3 + "`ifdef C\n", // 4 + "`endif\n", // 5 + ); + assert_eq!(lines(text), vec![(1, 2)], "only the else branch holds a line"); +} + +#[test] +fn a_one_line_region_is_one_token_and_folds_nothing() { + // A directive runs to the end of its line, so the `endif` here is the + // `ifdef` token's text, not a directive of its own. + let text = "module m;\n`ifdef A wire a; `else wire b; `endif\nendmodule\n"; + let doc = doc_of(text); + let directives = doc.tokens.iter().filter(|t| t.text.starts_with("`ifdef")).count(); + assert_eq!(directives, 1); + assert_eq!(lines(text), vec![(0, 1)], "the module only"); +} + +#[test] +fn an_unterminated_region_folds_only_the_branches_it_finished() { + // Same policy as an unclosed `begin`: never fold to the end of the file. + let text = concat!( + "`ifdef A\n", // 0 + " wire a;\n", // 1 + "`else\n", // 2 + " wire b;\n", // 3 + " wire c;\n", // 4 + ); + assert_eq!(lines(text), vec![(0, 1)]); + assert!(lines("`ifdef A\n wire a;\n wire b;\n").is_empty()); +} + +#[test] +fn stray_else_and_endif_are_ignored_without_disturbing_what_follows() { + let text = concat!( + "`else\n", // 0 + " wire x;\n", // 1 + "`endif\n", // 2 + "`endif\n", // 3 + "`ifdef A\n", // 4 + " wire a;\n", // 5 + "`endif\n", // 6 + "`elsif B\n", // 7 + " wire b;\n", // 8 + ); + assert_eq!(lines(text), vec![(4, 5)]); +} + +#[test] +fn directives_between_ports_fold() { + let text = concat!( + "module m (\n", // 0 + " input a,\n", // 1 + "`ifdef B\n", // 2 + " input b,\n", // 3 + " input c,\n", // 4 + "`endif\n", // 5 + " input d\n", // 6 + ");\n", // 7 + "endmodule\n", // 8 + ); + assert!(lines(text).contains(&(2, 4)), "got {:?}", lines(text)); +} + +#[test] +fn directives_inside_case_and_generate_fold() { + let text = concat!( + "module m;\n", // 0 + " generate\n", // 1 + "`ifdef G\n", // 2 + " if (A) begin : g\n", // 3 + " wire a;\n", // 4 + " end\n", // 5 + "`endif\n", // 6 + " endgenerate\n", // 7 + " always_comb begin\n", // 8 + " case (s)\n", // 9 + " 0: x = 0;\n", // 10 + "`ifdef C\n", // 11 + " 1: x = 1;\n", // 12 + "`else\n", // 13 + " 1: x = 2;\n", // 14 + "`endif\n", // 15 + " endcase\n", // 16 + " end\n", // 17 + "endmodule\n", // 18 + ); + assert_eq!( + lines(text), + vec![(0, 17), (1, 6), (2, 5), (3, 4), (8, 16), (9, 15), (11, 12), (13, 14)] + ); +} + +#[test] +fn a_directive_inside_a_define_body_is_text_not_a_fold() { + let text = concat!( + "`define M \\\n", // 0 + " `ifdef X \\\n", // 1 + " a = 1; \\\n", // 2 + " `else \\\n", // 3 + " a = 2; \\\n", // 4 + " `endif\n", // 5 + "module m;\n", // 6 + " wire a;\n", // 7 + "endmodule\n", // 8 + ); + assert_eq!(lines(text), vec![(6, 7)], "the module only"); +} + +#[test] +fn a_directive_in_a_comment_or_a_string_is_not_one() { + let text = concat!( + "module m;\n", // 0 + " // `ifdef A\n", // 1 + " /* `ifdef B\n", // 2 + " `endif */\n", // 3 + " initial $display(\"`ifdef\");\n", // 4 + " // `endif\n", // 5 + "endmodule\n", // 6 + ); + assert_eq!(folds(text), vec![(0, 5, "region"), (2, 3, "comment")]); +} + +#[test] +fn leading_whitespace_trailing_comments_and_crlf_change_nothing() { + let plain = concat!( + "module m;\n", // 0 + " `ifdef A // why\n", // 1 + " wire a;\n", // 2 + "\t`else /* other */\n", // 3 + " wire b;\n", // 4 + " `endif // A\n", // 5 + "endmodule\n", // 6 + ); + assert_eq!(lines(plain), vec![(0, 5), (1, 2), (3, 4)]); + assert_eq!(lines(&plain.replace('\n', "\r\n")), lines(plain)); +} + +#[test] +fn a_region_crossing_a_begin_keeps_both_sets_of_folds() { + // Real RTL opens one `begin` in each arm and closes it once below the + // `endif`. The branch folds cross the `begin` folds; VS Code keeps + // crossing ranges (`sanitizeRanges` adds them at the level of the range + // they cross; see the feature README), so nothing is dropped here and + // nothing is invented either. + let text = concat!( + "module m;\n", // 0 + " always_comb begin\n", // 1 + "`ifdef A\n", // 2 + " if (a) begin\n", // 3 + "`else\n", // 4 + " if (b) begin\n", // 5 + "`endif\n", // 6 + " x = 1;\n", // 7 + " end\n", // 8 + " end\n", // 9 + "endmodule\n", // 10 + ); + // The scope pairing sees three `begin`s and two `end`s, matches the inner + // two (`(5, 7)`, `(3, 8)`) and leaves the `always_comb` one out — that is + // `pairs::analyze`, unchanged by this feature. The branches are added + // beside it: `(2, 3)` crosses `(3, 8)`, `(4, 5)` crosses `(5, 7)`. + assert_eq!(lines(text), vec![(0, 9), (2, 3), (3, 8), (4, 5), (5, 7)]); +} + +#[test] +fn branch_folds_are_regions() { + let text = "`ifdef A\n wire a;\n`endif\n"; + assert_eq!(folds(text), vec![(0, 1, "region")]); +} + +#[test] +fn back_to_back_regions_each_fold() { + let text = concat!( + "`ifdef A\n", // 0 + " wire a;\n", // 1 + "`endif\n", // 2 + "`ifdef B\n", // 3 + " wire b;\n", // 4 + "`endif\n", // 5 + ); + assert_eq!(lines(text), vec![(0, 1), (3, 4)]); +} + +// A shared start line. VS Code keeps only the first range it receives for a +// start line, so a fold that existed before branch folds must come first and +// the branch fold is the one that yields (QA findings 1 and 2, 2026-11-19). + +#[test] +fn a_module_header_sharing_its_line_with_an_ifdef_keeps_its_fold_first() { + let text = "module m; `ifdef A\n a;\n`endif\nendmodule\n"; + assert_eq!(lines(text), vec![(0, 2), (0, 1)], "the module first, the branch after it"); +} + +#[test] +fn a_begin_sharing_its_line_with_an_ifdef_keeps_its_fold_first() { + let text = concat!( + "module m;\n", // 0 + "initial begin `ifdef X\n", // 1 + " a;\n", // 2 + " b;\n", // 3 + " `endif\n", // 4 + " c;\n", // 5 + "end\n", // 6 + "endmodule\n", // 7 + ); + assert_eq!(lines(text), vec![(0, 6), (1, 5), (1, 3)]); +} + +#[test] +fn a_comment_opened_on_a_directive_line_keeps_its_fold_first() { + // The comment is the shorter range but the older fold, so it is first, + // and in VS Code the branch from line 0 is the one that yields. + let text = concat!( + "`ifdef A /* c1\n", // 0 + " c2 */\n", // 1 + " x;\n", // 2 + "`else\n", // 3 + " b;\n", // 4 + "`endif\n", // 5 + ); + assert_eq!(folds(text), vec![(0, 1, "comment"), (0, 2, "region"), (3, 4, "region")]); +} + +#[test] +fn a_comment_spanning_exactly_a_branch_stays_a_comment() { + // Same two lines as the branch: one range, and it keeps the kind it had + // before branch folds existed, so *Fold All Block Comments* still folds it. + let text = concat!( + "`ifdef A /* c1\n", // 0 + " c2\n", // 1 + " c3 */\n", // 2 + "`else\n", // 3 + " b;\n", // 4 + "`endif\n", // 5 + ); + assert_eq!(folds(text), vec![(0, 2, "comment"), (3, 4, "region")]); +} diff --git a/crates/lucisv_server/src/folding/opentitan_sweep.rs b/crates/lucisv_server/src/folding/opentitan_sweep.rs new file mode 100644 index 0000000..def04b7 --- /dev/null +++ b/crates/lucisv_server/src/folding/opentitan_sweep.rs @@ -0,0 +1,232 @@ +//! The real-world proof for `` `ifdef `` folding: every `.sv`/`.svh`/`.v` +//! file under an OpenTitan `hw` tree, through [`folding_ranges`], with the +//! ranges checked against the file and the directives counted independently. +//! +//! `#[ignore]`: it parses four thousand files. Run with +//! `LUCISV_OPENTITAN_HW=/path/to/opentitan/hw tools/guard.sh -- cargo test +//! --release -p lucisv_server opentitan_sweep -- --ignored --nocapture`; +//! without the variable it reads `~/.cache/lucisv-opentitan-full/hw`, and it +//! skips (passing, with a line on stderr) when that is not there. + +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +use vlog_parser::token::{Token, TokenKind}; +use vlog_semantic::WorkspaceIndex; + +use lsp_types::FoldingRange; + +use super::{branch_folds, directives, folding_ranges, line, scope_and_comment_folds}; +use crate::state::Document; + +/// The tree: `LUCISV_OPENTITAN_HW`, else the full-tree cache. +fn tree() -> Option { + let root = std::env::var_os("LUCISV_OPENTITAN_HW").map(PathBuf::from).or_else(|| { + std::env::var_os("HOME") + .map(|home| PathBuf::from(home).join(".cache/lucisv-opentitan-full/hw")) + })?; + root.is_dir().then_some(root) +} + +/// Every Verilog source under `dir`, sorted so a run is reproducible. +fn sources(dir: &Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + sources(&path, out); + } else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "svh" | "v")) { + out.push(path); + } + } +} + +/// The five words, counted on the token stream by a rule written apart from +/// the one under test. +fn word(token: &Token) -> Option<&'static str> { + if token.kind != TokenKind::Directive { + return None; + } + let mut first = token.text.split(|c: char| !c.is_ascii_alphanumeric() && c != '`' && c != '_'); + match first.next()? { + "`ifdef" => Some("ifdef"), + "`ifndef" => Some("ifndef"), + "`elsif" => Some("elsif"), + "`else" => Some("else"), + "`endif" => Some("endif"), + _ => None, + } +} + +/// The same five, counted on the raw text: a line whose first non-blank +/// characters spell one. Differs from the token count wherever the lexer knows +/// better — a comment, a `` `define `` body. +fn text_count(text: &str) -> usize { + text.lines() + .filter(|l| { + let l = l.trim_start(); + ["`ifdef", "`ifndef", "`elsif", "`else", "`endif"].iter().any(|d| { + l.strip_prefix(d).is_some_and(|rest| { + !rest.starts_with(|c: char| c.is_alphanumeric() || c == '_') + }) + }) + }) + .count() +} + +#[derive(Default, Debug)] +struct Tally { + files: usize, + unlexed: usize, + tokens: usize, + text_lines: usize, + opens: usize, + nexts: usize, + closes: usize, + /// `else`/`elsif` and `endif` that found a region open — what + /// [`directives::branch_spans`] should emit one span for each of. + nexts_matched: usize, + closes_matched: usize, + /// Regions still open at end of file. + unclosed: usize, + spans: usize, + ranges: usize, + not_first_on_line: usize, + /// Branch folds left out because an existing fold has the same two lines. + same_lines_as_existing: usize, + /// Branch folds that share their start line with an existing fold. + shared_start: usize, + folding: Duration, + branches: Duration, +} + +#[test] +#[ignore = "reads an OpenTitan checkout; see the module comment"] +fn every_opentitan_file_folds_its_ifdef_branches_validly() { + let Some(root) = tree() else { + eprintln!("opentitan_sweep: no OpenTitan hw tree; skipped"); + return; + }; + let mut files = Vec::new(); + sources(&root, &mut files); + files.sort(); + let mut tally = Tally::default(); + let mut slowest: Vec<(Duration, Duration, PathBuf)> = Vec::new(); + for path in &files { + let Ok(text) = std::fs::read_to_string(path) else { continue }; + let (folding, branches) = sweep_one(path, text, &mut tally); + slowest.push((folding, branches, path.clone())); + } + slowest.sort_by_key(|entry| std::cmp::Reverse(entry.0)); + eprintln!("opentitan_sweep: {tally:#?}"); + for (folding, branches, path) in slowest.iter().take(5) { + eprintln!(" {folding:?} (branches {branches:?}) {}", path.display()); + } + assert!(tally.files > 0); + assert_eq!(tally.spans, tally.nexts_matched + tally.closes_matched, "{tally:#?}"); +} + +/// Fold one file, check its ranges, and add it to `tally`. Returns the time +/// the whole answer took and the time the branch pass alone took. +fn sweep_one(path: &Path, text: String, tally: &mut Tally) -> (Duration, Duration) { + tally.files += 1; + let by_text = text_count(&text); + tally.text_lines += by_text; + let doc = Document::new(None, text, &WorkspaceIndex::default()); + if doc.tokens.is_empty() { + tally.unlexed += 1; + eprintln!(" does not lex: {}", path.display()); + } + let lines = doc.line_index.line_col(doc.text.len() as u32).0; + + let started = Instant::now(); + let ranges = folding_ranges(&doc); + let folding = started.elapsed(); + let started = Instant::now(); + let spans = directives::branch_spans(&doc.tokens, |t| line(&doc, t.span.start)); + let branches = started.elapsed(); + tally.folding += folding; + tally.branches += branches; + + for range in &ranges { + assert!(range.start_line < range.end_line, "{}: {range:?}", path.display()); + assert!(range.end_line < lines, "{}: {range:?} past line {lines}", path.display()); + } + check_existing_unchanged(&doc, &ranges, path, tally); + let before = tally.tokens; + let directive_lines = check_directives(&doc, path, tally); + if tally.tokens - before != by_text { + let tokens = tally.tokens - before; + eprintln!(" {by_text} by text, {tokens} by token: {}", path.display()); + } + tally.spans += spans.len(); + for &(start, end) in spans.iter().filter(|(s, e)| e > s) { + tally.ranges += 1; + assert!(directive_lines.contains(&start), "{}: fold at {start}", path.display()); + assert!( + ranges.iter().any(|r| r.start_line == start && r.end_line == end), + "{}: branch {start}..{end} missing from the answer", + path.display() + ); + } + (folding, branches) +} + +/// Count the directive tokens into `tally` and return the lines they start on. +fn check_directives(doc: &Document, path: &Path, tally: &mut Tally) -> Vec { + let mut at = Vec::new(); + let mut depth = 0usize; + for (i, token) in doc.tokens.iter().enumerate() { + let Some(word) = word(token) else { continue }; + tally.tokens += 1; + match word { + "ifdef" | "ifndef" => { + tally.opens += 1; + depth += 1; + } + "elsif" | "else" => { + tally.nexts += 1; + tally.nexts_matched += usize::from(depth > 0); + } + _ => { + tally.closes += 1; + tally.closes_matched += usize::from(depth > 0); + depth = depth.saturating_sub(1); + } + } + let start = line(doc, token.span.start); + let previous = i.checked_sub(1).map(|p| &doc.tokens[p]); + if previous.is_some_and(|p| line(doc, p.span.end.saturating_sub(1)) == start) { + tally.not_first_on_line += 1; + eprintln!(" not first on line {}: {}:{}", start + 1, path.display(), token.text); + } + at.push(start); + } + tally.unclosed += depth; + at +} + +/// The answer with its branch folds taken out is exactly the scope and +/// comment folds alone — same ranges, kinds and order — so no fold that +/// existed before this feature is lost, changed or moved. +fn check_existing_unchanged( + doc: &Document, + ranges: &[FoldingRange], + path: &Path, + tally: &mut Tally, +) { + let existing = scope_and_comment_folds(doc); + let branches = branch_folds(doc, &existing); + let rest: Vec<&FoldingRange> = ranges.iter().filter(|r| !branches.contains(r)).collect(); + assert_eq!(rest, existing.iter().collect::>(), "{}", path.display()); + assert_eq!(ranges.len(), existing.len() + branches.len(), "{}", path.display()); + let spans = directives::branch_spans(&doc.tokens, |t| line(doc, t.span.start)); + let kept = spans.iter().filter(|(s, e)| e > s).count(); + tally.same_lines_as_existing += kept - branches.len(); + for branch in &branches { + if existing.iter().any(|r| r.start_line == branch.start_line) { + tally.shared_start += 1; + eprintln!(" shared start line {}: {}", branch.start_line + 1, path.display()); + } + } +} diff --git a/crates/lucisv_server/tests/ifdef_folding.rs b/crates/lucisv_server/tests/ifdef_folding.rs new file mode 100644 index 0000000..07e8131 --- /dev/null +++ b/crates/lucisv_server/tests/ifdef_folding.rs @@ -0,0 +1,125 @@ +//! `` `ifdef `` branch folds over the wire: spawn the real binary, open a +//! buffer, ask `textDocument/foldingRange`, and read back the exact ranges an +//! editor (and VS Code's sticky scroll, which pins every fold's first line) +//! receives. The shape itself is pinned by the unit tests beside +//! `src/folding.rs`; this checks it survives serialisation and dispatch. +//! See `docs/features/ifdef-folding/README.md`. +//! +//! The framing is repeated from `e2e.rs` rather than shared: an integration +//! test file is its own crate, and the helpers are twenty lines. + +use std::io::{BufRead, BufReader, Write}; +use std::process::{Command, Stdio}; + +use serde_json::{json, Value}; + +fn frame(payload: &str) -> String { + format!("Content-Length: {}\r\n\r\n{payload}", payload.len()) +} + +fn read_message(input: &mut impl BufRead) -> Option { + let mut length = None; + loop { + let mut line = String::new(); + if input.read_line(&mut line).unwrap_or(0) == 0 { + return None; + } + let trimmed = line.trim_end_matches(['\r', '\n']); + if trimmed.is_empty() { + break; + } + if let Some(value) = trimmed.strip_prefix("Content-Length: ") { + length = value.parse::().ok(); + } + } + let mut body = vec![0u8; length?]; + input.read_exact(&mut body).ok()?; + serde_json::from_slice(&body).ok() +} + +/// Run one session and return every message the server wrote. The OS cache +/// directory is pointed into the temp dir, as `e2e.rs` does, so the index +/// cache never lands in the developer's home. +fn talk(dir: &std::path::Path, session: &str) -> Vec { + let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-server")) + .env("HOME", dir) + .env("XDG_CACHE_HOME", dir.join("cache")) + .env("LOCALAPPDATA", dir.join("cache")) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .expect("the server binary starts"); + child.stdin.take().expect("stdin").write_all(session.as_bytes()).expect("write session"); + let mut stdout = BufReader::new(child.stdout.take().expect("stdout")); + let mut out = Vec::new(); + while let Some(message) = read_message(&mut stdout) { + out.push(message); + } + assert!(child.wait().expect("the server exits").success()); + out +} + +const SOURCE: &str = concat!( + "module top;\n", // 0 + "`ifdef FAST\n", // 1 + " wire a;\n", // 2 + " wire b;\n", // 3 + "`elsif SLOW\n", // 4 + " wire c;\n", // 5 + "`else\n", // 6 + " `ifndef TINY\n", // 7 + " wire d;\n", // 8 + " `endif\n", // 9 + "`endif\n", // 10 + "endmodule\n", // 11 +); + +#[test] +fn ifdef_branches_come_back_as_region_folds_over_the_wire() { + let dir = std::env::temp_dir().join(format!("lucisv_ifdef_folding_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("temp dir"); + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", dir.join("top.sv").display()); + let open = json!({ + "jsonrpc": "2.0", "method": "textDocument/didOpen", + "params": { "textDocument": { + "uri": uri, "languageId": "systemverilog", "version": 1, "text": SOURCE + } } + }); + let ask = json!({ + "jsonrpc": "2.0", "id": 2, "method": "textDocument/foldingRange", + "params": { "textDocument": { "uri": uri } } + }); + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&open.to_string()), + frame(&ask.to_string()), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&dir, &session); + let response = messages.iter().find(|m| m["id"] == 2).expect("a foldingRange response"); + let folds: Vec<(u64, u64, String)> = response["result"] + .as_array() + .expect("a folding list") + .iter() + .map(|f| { + let line = |key: &str| f[key].as_u64().expect("a line"); + (line("startLine"), line("endLine"), f["kind"].as_str().unwrap_or("").to_string()) + }) + .collect(); + let region = |start, end| (start, end, "region".to_string()); + assert_eq!( + folds, + vec![region(0, 10), region(1, 3), region(4, 5), region(6, 9), region(7, 8)], + "the module, then `ifdef`, `elsif`, `else` and the nested `ifndef`" + ); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/features/ifdef-folding/README.md b/docs/features/ifdef-folding/README.md new file mode 100644 index 0000000..815ae74 --- /dev/null +++ b/docs/features/ifdef-folding/README.md @@ -0,0 +1,408 @@ +# 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::lexer` + makes each of the five directives one `TokenKind::Directive` token running + to the end of its line (`is_line_directive`, `lexer.rs:899`; capture at + `lexer.rs:187-260`). Consequences, all tested: + - in a `//` or `/* */` comment → trivia, never a fold; + - in a string → part of the string literal; + - inside a `` `define `` body (backslash continuations) → text of the + `` `define `` token, never a fold; + - `` `ifdef A … `else … `endif `` on **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 begin `ifdef X`) is still a directive, and its branch fold starts + on that code line — but that line already starts the `module`/`begin` + fold, 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`. +- **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 a `comment` fold; + - 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. +- **Fold shape — a branch runs from its directive's line to the line before + the next directive of the same region.** `` `ifdef `` line L0, `` `else `` + L5, `` `endif `` L9 → `(0, 4)` and `(5, 8)`. Collapsing the first branch + leaves `` `else `` visible and separately collapsible; collapsing the last + leaves `` `endif `` visible. Chosen to match the existing `begin`/`end` rule + in `folding.rs` (the closer stays on screen). For C, VS Code itself ships + no `#ifdef` folding — `extensions/cpp/language-configuration.json` folding + markers are `#pragma region`/`#pragma endregion` only (checked in the VS + Code repo, main branch, 2026-11-19); `#if` folding 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 only + `comment`, `imports`, `region`; VS Code's *Fold All Regions* + (`editor.foldAllMarkerRegions`) folds kind `region` + (`folding.ts` `FoldAllRegionsAction` → `setCollapseStateForType(Region)`), + which already includes every `begin` fold, so branches joining it is + consistent. `imports` would be wrong (and would auto-collapse under + `editor.foldingImportsByDefault`). +- **Degraded input** (all tested, none panic): + - a region still open at end of file folds the branches it *finished* + (`` `ifdef `` … `` `else `` … EOF folds the `ifdef` branch) and nothing for + the open one — the same "never fold to EOF" policy as an unclosed `begin`; + - a stray `` `else ``/`` `elsif ``/`` `endif `` with 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 + (`push` drops `end <= start`). +- **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.ts` `collectSyntaxRanges` keeps a provider range only + if `start > 0 && end > start && end <= lineCount` (1-based there) — every + range we send satisfies it (pinned by the OpenTitan sweep). +- `sanitizeRanges` sorts 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.start` guard) — with one nuance QA found: the guard + compares against `top`, and a crossing entry never becomes `top`, 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.ts` `ensureParentIndices`, and the sticky model is built + from those `FoldingRegions` (`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 +`begin`s (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 in `vlog_parser/src/parser/directive.rs:15-28`; it is four + lines and is repeated in `folding/directives.rs` rather than widened into + the parser's public surface. (A third copy, by first whitespace word, lives + in `on_type/auto_end.rs:258`.) If a public `Token::directive_word` is ever + added, all three should use it — a request, not a blocker. +- **Promises** `folding::folding_ranges` (the only caller is + `server/dispatch.rs`, unchanged): sorted by start line (tie-break in + `in_answer_order`: existing folds, in their old `(start, end)` order, + before branch folds), de-duplicated by `(start, end)` with the existing + fold winning, every range `start < end`, branch folds kind `region`. 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`), whose `tokens` are empty, so + `folding_ranges` answers `[]` for it exactly as before — pinned already by + `server/tests/large_file.rs` (`FoldingRangeRequest` → empty). Supporting + branch folds there would need a line scan of the raw text in or beside + `large.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 to `e2e.rs`), repeating `e2e.rs`'s twenty lines of framing. + +## Status / TODO + +- [x] Find how directives are represented (one `Directive` token per line). +- [x] `folding/directives.rs`: one linear pass → branch spans. +- [x] Wire into `folding_ranges` (kind `region`). +- [x] Unit tests for every edge case in `folding/ifdef_tests.rs` (15). +- [x] Wire test `tests/ifdef_folding.rs`. +- [x] OpenTitan sweep `folding/opentitan_sweep.rs` (`#[ignore]`, skips when absent). +- [x] Timing before/after. +- [x] VS Code README feature rows (Folding, Sticky scroll). +- [x] Fix round: existing folds win identical lines and shared start lines + (QA findings 1–2); `in_answer_order` defines 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 `ifdef` branch (the `else` stays visible), collapse the `else` + branch (the `endif` stays visible), nested regions, sticky scroll pinning + the `` `ifdef ``/`` `else `` line while scrolling inside a long branch, and a + crossing `begin` (e.g. one `if … begin` per arm, one `end`). + +## Work log + +### 2026-11-19 — dev + +- Directives: the lexer's `Directive` tokens are exactly the right + representation (comments/strings/define bodies already excluded), so the + new pass reads only `token.kind` and the first word. Built + `crates/lucisv_server/src/folding/directives.rs` (`branch_spans`, ~90 + lines): a stack of open-branch start lines; `Open` pushes, `Next` emits the + current branch and restarts it, `Close` pops and emits. Line numbers come + from the caller (`folding::line`, the same `LineIndex` conversion as the + other folds). `folding.rs` gained one loop and the module declarations. +- Tests: `folding/ifdef_tests.rs` — shape, `elsif` chain, three-deep nesting, + empty branch, one-line region, unterminated, stray directives, port list, + `case` + `generate`, `define` body, comment/string, whitespace/trailing + comments/CRLF, crossing `begin` (exact list pinned), kind, back-to-back. + All passed on the first run. `tests/ifdef_folding.rs` checks the same over + the wire (elsif/else/nested ifndef). +- **OpenTitan sweep** (`LUCISV_OPENTITAN_HW` or + `~/.cache/lucisv-opentitan-full/hw`, 4 061 `.sv`/`.svh`/`.v` files, release + build, through `tools/guard.sh`): no panic; every range `start < end` and + `end < 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 (772 `ifdef`/`ifndef`, 295 + `elsif`/`else`, 772 `endif`), 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 `` `define `` bodies + (`prim_assert*.sv*`, `prim_flop_macros.sv`, `dv_defines.svh`, ibex + `check/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_ranges` per file, release, same machine, warm): + before — whole tree 29.9 ms, slowest `top_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.rs` split into `scope_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) and `in_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. a `begin /* … */` 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 begin `ifdef 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 in `in_answer_order`. +- Tests added to `folding/ifdef_tests.rs`: the three QA repros and the + comment-kind case (19 tests now); the `folds` helper 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, via `LUCISV_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 -- --check` clean; `cargo clippy --all-targets -- -D + warnings` clean (the one cargo-level `workspace.package.authors` manifest + 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_folding` 1; + 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-tree `folding_ranges` 33.4 ms + (branch pass 4.7 ms), slowest `top_darjeeling/.../pinmux_reg_top.sv` + 1.07 ms (branches 0.24 ms) — consistent with the work log. +- Scope: `git status` shows only `folding.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.rs` 296 lines incl. tests (~85 production), + `directives.rs` 85 — 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 X` and `end `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** + +1. **Low — a block-comment fold can lose its `comment` kind.** + `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 base `comment` fold becomes a + `region`. 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. +2. **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;\n`endif\nendmodule\n"` → `[(0,1) ifdef, + (0,2) module]`: VS Code drops the **module** fold that base showed (and + sticky scroll no longer pins `module m;` past line 1); + `"module m;\ninitial begin `ifdef X\n a;\n b;\n `endif\n c;\nend\nendmodule\n"` + → `(1,3)` ifdef before `(1,5)` begin: the `initial begin` fold is + dropped. Conversely `"`ifdef A /* c1\n c2 */\n x;\n`else\n b;\n`endif\n"` + → `(0,1) comment` before `(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. +3. **Info — lone-CR files fold nothing**, base and new alike (the lexer and + line index only break on `\n`). Pre-existing, unchanged. +4. **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 the `sanitizeRanges` nuance + above. The "not verified" list (C/C++ extension's `#if` shape, 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 `ifdef` that 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). diff --git a/editors/vscode/CHANGELOG.md b/editors/vscode/CHANGELOG.md index bec4058..130efca 100644 --- a/editors/vscode/CHANGELOG.md +++ b/editors/vscode/CHANGELOG.md @@ -5,6 +5,16 @@ for you. The extension and its bundled language server share one version number; the full engineering notes live in the [project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md). +## 0.65.4 — 2026-11-19 + +- **`` `ifdef `` / `` `else `` blocks fold.** Each branch of a + conditional-compilation region (`` `ifdef ``, `` `ifndef ``, `` `elsif ``, + `` `else ``) collapses on its own; the next branch's line and `` `endif `` + stay visible. +- **They show in sticky scroll.** Scroll inside a long branch and its + `` `ifdef `` or `` `else `` line stays pinned with the enclosing module and + blocks. + ## 0.65.3 — 2026-11-19 - **`TODO`, `FIXME`, `FIX_ME` and `TBD` are highlighted inside comments** — diff --git a/editors/vscode/README.md b/editors/vscode/README.md index eba759e..5aced04 100644 --- a/editors/vscode/README.md +++ b/editors/vscode/README.md @@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view, then open a Verilog or SystemVerilog file. There is no separate server or CLI setup. -The current release is **0.65.3**. Its platform packages include +The current release is **0.65.4**. Its platform packages include `lucisv-server`, the `lucisv` command-line tool and `lucisv-mcp` (see [Agents (MCP)](#agents-mcp)): @@ -153,8 +153,8 @@ enabling both paths formats twice. | Document highlights | Highlights symbol occurrences or the matching opener/closer under the cursor | | Document and workspace symbols | Hierarchical outline plus indexed symbol search across the design | | Include links | Resolvable `` `include`` paths become clickable using local and filelist `+incdir+` search rules | -| Folding | Modules, classes, blocks, regions, and multiline comments fold on syntax-aware boundaries | -| Sticky scroll | The first line of every block you are inside — the module, the `always`, the `case`, the case item, the `if` — stays pinned at the top of the editor, up to ten lines deep | +| Folding | Modules, classes, blocks, regions, and multiline comments fold on syntax-aware boundaries; every branch of an `` `ifdef``/`` `ifndef`` region folds on its own, from its directive to the line before the next `` `elsif``/`` `else``/`` `endif``, which stays visible | +| Sticky scroll | The first line of every block you are inside — the module, the `always`, the `case`, the case item, the `if`, the `` `ifdef``/`` `else`` branch — stays pinned at the top of the editor, up to ten lines deep | | Inlay hints | Adds port and parameter names to ordered instantiations without guessing at ambiguous sites | | Code lenses | Shows the workspace-wide instantiation count above every module/interface; click to jump to a site | | Call hierarchy | Incoming calls answer “who instantiates this?”; outgoing calls answer “what does this instantiate?” | @@ -436,6 +436,11 @@ default): } ``` +## Release 0.65.4 highlights + +Version 0.65.4 makes `` `ifdef `` regions foldable branch by branch, and pins +the branch you are inside in sticky scroll. + ## Release 0.65.3 highlights Version 0.65.3 highlights `TODO`, `FIXME`, `FIX_ME` and `TBD` inside comments, diff --git a/editors/vscode/package-lock.json b/editors/vscode/package-lock.json index 38dbc1e..3515b2f 100644 --- a/editors/vscode/package-lock.json +++ b/editors/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "lucisv", - "version": "0.65.3", + "version": "0.65.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "lucisv", - "version": "0.65.3", + "version": "0.65.4", "license": "MIT", "dependencies": { "vscode-languageclient": "9.0.1" diff --git a/editors/vscode/package.json b/editors/vscode/package.json index 0526448..b7a7f1b 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -2,7 +2,7 @@ "name": "lucisv", "displayName": "lucisv — Verilog/SystemVerilog", "description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.", - "version": "0.65.3", + "version": "0.65.4", "publisher": "guoliangchen", "author": "Guoliang Chen", "license": "MIT",