Files
lucisv/crates/lucisv_server/src/folding.rs
T
Guoliang ChenandClaude Mythos 5.2 d57496978f
release / build-and-publish (push) Successful in 5m44s
Release 0.65.4: `ifdef blocks fold, and pin in sticky scroll
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 <[email protected]>
2026-11-19 05:30:49 -08:00

343 lines
14 KiB
Rust

//! `textDocument/foldingRange`.
//!
//! No new analysis: a foldable region is a matched scope pair, which
//! `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`. 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;
use vlog_parser::TextRange;
use crate::pairs::analyze;
use crate::state::Document;
/// 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
/// `end` is missing is exactly the behaviour that makes users turn folding
/// 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<FoldingRange> {
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<FoldingRange> {
let mut out: Vec<FoldingRange> = Vec::new();
for pair in analyze(&doc.tokens).pairs {
// The closing keyword's own line stays visible: LSP hides
// `startLine + 1 ..= endLine`, so folding through the line *before*
// the closer leaves `end`/`endmodule` on screen, which is how a
// reader keeps track of what was collapsed.
let through = line(doc, pair.close.start).saturating_sub(1);
push(&mut out, line(doc, pair.open.start), through, FoldingRangeKind::Region);
}
for comment in comments(doc) {
// A comment has no closing construct worth keeping on screen, so the
// whole of it folds into its first line — what an editor does for
// `/* */` in every other language.
let through = line(doc, last_byte(comment.span));
push(&mut out, line(doc, comment.span.start), through, FoldingRangeKind::Comment);
}
out.sort_by_key(|range| (range.start_line, range.end_line));
out.dedup_by(|a, b| a.start_line == b.start_line && a.end_line == b.end_line);
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<FoldingRange> {
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<FoldingRange>, branches: Vec<FoldingRange>) -> Vec<FoldingRange> {
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<FoldingRange>, start_line: u32, end_line: u32, kind: FoldingRangeKind) {
if end_line <= start_line {
return;
}
out.push(FoldingRange { start_line, end_line, kind: Some(kind), ..Default::default() });
}
/// Every comment the lexer attached to this buffer's tokens, in no particular
/// order — trivia hangs off the token that follows it, or, for a trailing
/// comment, the one it follows.
fn comments(doc: &Document) -> impl Iterator<Item = &Comment> {
doc.tokens.iter().flat_map(|token| token.leading.iter().chain(token.trailing.iter()))
}
/// The 0-based line a byte offset falls on. `LineIndex` counts from 1; LSP
/// counts from 0.
fn line(doc: &Document, offset: u32) -> u32 {
doc.line_index.line_col(offset).0.saturating_sub(1)
}
/// The last byte of a span, so a comment's end line is the line its `*/` sits
/// on rather than whatever follows it.
fn last_byte(span: TextRange) -> u32 {
span.end.saturating_sub(1).max(span.start)
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_semantic::WorkspaceIndex;
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.
fn folds(text: &str) -> Vec<(u32, u32, &'static str)> {
folding_ranges(&doc_of(text))
.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()
}
#[test]
fn a_module_folds_from_its_header_to_the_line_before_endmodule() {
// The `endmodule` line itself stays visible, which is the whole point
// of stopping one line short of the closer.
let text = "module m;\n wire a;\n wire b;\nendmodule\n";
assert_eq!(folds(text), vec![(0, 2, "region")]);
}
#[test]
fn nested_begins_each_get_their_own_range() {
let text = concat!(
"module m;\n", // 0
" initial begin\n", // 1
" if (x) begin\n", // 2
" y = 1;\n", // 3
" end\n", // 4
" end\n", // 5
"endmodule\n", // 6
);
assert_eq!(
folds(text),
vec![(0, 5, "region"), (1, 4, "region"), (2, 3, "region")],
"module, outer begin, inner begin"
);
}
#[test]
fn a_generate_block_folds_like_any_other_scope() {
let text = concat!(
"module m;\n", // 0
" generate\n", // 1
" if (A) begin : g\n", // 2
" wire a;\n", // 3
" end\n", // 4
" endgenerate\n", // 5
"endmodule\n", // 6
);
assert_eq!(folds(text), vec![(0, 5, "region"), (1, 4, "region"), (2, 3, "region")]);
}
#[test]
fn a_function_and_a_case_fold_too() {
let text = concat!(
"module m;\n", // 0
" function int f;\n", // 1
" case (x)\n", // 2
" 1: f = 1;\n", // 3
" endcase\n", // 4
" endfunction\n", // 5
"endmodule\n", // 6
);
assert_eq!(folds(text), vec![(0, 5, "region"), (1, 4, "region"), (2, 3, "region")]);
}
#[test]
fn every_layer_a_reader_is_inside_starts_a_fold_on_its_header_line() {
// VS Code's sticky scroll is told (the extension's
// `editor.stickyScroll.defaultModel`) to pin the first line of every
// fold around the top of the viewport. So the header of each layer —
// module, `always`, `case`, the case item, the `if` — must be a fold's
// start line, and each fold must reach the innermost statement.
let text = concat!(
"module m (\n", // 0
" input a\n", // 1
");\n", // 2
" always @(*) begin\n", // 3
" case (st)\n", // 4
" st_1: begin\n", // 5
" if (cond_1) begin\n", // 6
" x = 1;\n", // 7
" y = 2;\n", // 8
" end\n", // 9
" end\n", // 10
" endcase\n", // 11
" end\n", // 12
"endmodule\n", // 13
);
let ranges = folds(text);
for header in [0, 3, 4, 5, 6] {
let fold = ranges.iter().find(|(start, _, _)| *start == header);
let Some((_, end, _)) = fold else {
panic!("no fold starts on line {header}: {ranges:?}")
};
assert!(*end >= 8, "the fold from line {header} must cover line 8, got {ranges:?}");
}
}
#[test]
fn a_scope_that_opens_and_closes_on_one_line_folds_nothing() {
// `end_line <= start_line` means there is no hidden line to gain.
let text = "module m;\n initial begin x = 1; end\nendmodule\n";
assert_eq!(folds(text), vec![(0, 1, "region")], "the module only");
}
#[test]
fn an_opener_that_never_closes_produces_no_range() {
// The failure this guards: folding an unclosed `begin` through the end
// of the file, which hides code the user is in the middle of writing.
let text = "module m;\n initial begin\n x = 1;\nendmodule\n";
assert_eq!(folds(text), vec![(0, 2, "region")], "the module matched; the begin did not");
}
#[test]
fn a_stray_closer_produces_no_range_either() {
// The `begin` that *did* close has nothing between its two lines, so
// the module is the only fold and the stray `end` adds none.
let text = "module m;\n initial begin\n end\n end\nendmodule\n";
assert_eq!(folds(text), vec![(0, 3, "region")]);
}
#[test]
fn a_multi_line_block_comment_folds_as_a_comment() {
let text = concat!(
"/* the header\n", // 0
" two lines */\n", // 1
"module m;\n", // 2
" wire a;\n", // 3
"endmodule\n", // 4
);
assert_eq!(folds(text), vec![(0, 1, "comment"), (2, 3, "region")]);
}
#[test]
fn a_one_line_comment_of_either_spelling_folds_nothing() {
let text = "// a line\n/* one line */\nmodule m;\n wire a;\nendmodule\n";
assert_eq!(folds(text), vec![(2, 3, "region")], "only the module");
}
#[test]
fn a_trailing_block_comment_is_reached_too() {
// Trivia hangs off the following token — except a trailing comment,
// which hangs off the preceding one. Missing that half would silently
// drop every comment written after code on its line.
let text = "module m;\n wire a; /* why\n this net exists */\nendmodule\n";
assert!(folds(text).contains(&(1, 2, "comment")), "got {:?}", folds(text));
}
#[test]
fn a_comment_at_the_end_of_the_file_is_reached_through_the_eof_token() {
let text = "module m;\nendmodule\n/* a tail\n comment */\n";
assert!(folds(text).contains(&(2, 3, "comment")), "got {:?}", folds(text));
}
#[test]
fn an_empty_file_folds_nothing() {
assert!(folds("").is_empty());
assert!(folds("\n\n\n").is_empty());
}
#[test]
fn a_file_that_does_not_lex_folds_nothing() {
// `Document::new` leaves `tokens` empty, so there is neither a pair
// nor a comment to report — not a truncated stream to guess from.
let doc = doc_of("module m;\n wire a; /* unterminated\n");
assert!(doc.tokens.is_empty());
assert!(folding_ranges(&doc).is_empty());
}
#[test]
fn the_ranges_come_back_sorted_and_without_duplicates() {
let text = concat!(
"module m;\n", // 0
" initial begin\n", // 1
" x = 1;\n", // 2
" end\n", // 3
" initial begin\n", // 4
" y = 1;\n", // 5
" end\n", // 6
"endmodule\n", // 7
);
let ranges = folds(text);
assert_eq!(ranges, vec![(0, 6, "region"), (1, 2, "region"), (4, 5, "region")]);
let mut sorted = ranges.clone();
sorted.sort();
assert_eq!(ranges, sorted, "an editor reads them in order");
}
#[test]
fn a_multibyte_comment_does_not_shift_a_line_number() {
// Lines are counted in bytes by `LineIndex` and in lines by LSP, so
// this is only a regression guard — but the folding math is the place
// an off-by-one would hide.
let text = "// é 🎉\nmodule m;\n wire a;\nendmodule\n";
assert_eq!(folds(text), vec![(1, 2, "region")]);
}
}