250 lines
9.7 KiB
Rust
250 lines
9.7 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`.
|
|
|
|
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, 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 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
|
|
}
|
|
|
|
/// 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 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")]);
|
|
}
|
|
}
|