//! `textDocument/selectionRange` — expand-selection. //! //! No new analysis: everything the chain is built from is already computed for //! something else. The token stream gives the innermost step, the tolerant //! parse's item and statement spans give the middle ones, and `pairs::analyze` //! — the rainbow's own matcher — gives the scopes a broken parse would //! otherwise lose. The four sources are thrown into one list of byte ranges //! that cover the cursor, and the chain is whatever nests. See //! `docs/features/selection-range/README.md`. use lsp_types::{Position, SelectionRange}; use vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind, Stmt, StmtKind}; use vlog_parser::TextRange; use crate::pairs::analyze; use crate::state::{first_token_reaching, Document}; /// One chain per requested position, in the order they were asked for. /// /// Each chain runs innermost first, every step strictly containing the one /// before it and the last one being the whole file. A position that resolves /// to nothing else — an empty buffer, a file that does not lex — still gets /// that last step, because the protocol wants exactly one answer per position. pub fn selection_ranges(doc: &Document, positions: &[Position]) -> Vec { let converter = doc.positions(); positions.iter().map(|position| chain(doc, converter.offset(*position))).collect() } /// The chain for one byte offset. fn chain(doc: &Document, offset: u32) -> SelectionRange { let positions = doc.positions(); let mut range: Option = None; // Widest first, so each step is built already holding its parent. for span in nested(enclosing(doc, offset)).into_iter().rev() { range = Some(SelectionRange { range: positions.range(span), parent: range.map(Box::new) }); } range.unwrap_or_else(|| SelectionRange { range: positions.whole_document(), parent: None }) } /// Every byte range this server can name that covers `offset`, from every /// source, unordered and possibly overlapping — [`nested`] sorts it out. fn enclosing(doc: &Document, offset: u32) -> Vec { let mut spans = Vec::new(); // The first token that reaches `offset` is the first that can cover it, // and — because the tokens after it all start no earlier — the only one // the sweep this replaced could ever have returned. Note that `covers` // takes `span.end` inclusively, so this is deliberately *not* // `Document::token_at`: at a byte two adjacent tokens share, the sweep // answered with the earlier one and so does this. if let Some(token) = doc .tokens .get(first_token_reaching(&doc.tokens, offset)) .filter(|token| covers(token.span, offset)) { spans.push(token.span); } items(&doc.tree.items, offset, &mut spans); // The scopes the AST does not model — an unclosed `begin` inside an // otherwise fine module, a `case` in a file that only half parsed — still // match over the token stream, and a user expanding a selection there is // exactly the user whose file is mid-edit. for pair in analyze(&doc.tokens).pairs { let span = TextRange::new(pair.open.start, pair.close.end); if covers(span, offset) { spans.push(span); } } spans.push(TextRange::new(0, doc.text.len() as u32)); spans } /// The subsequence that really nests, smallest first. /// /// Two ranges that both cover the cursor need not contain one another — an /// item span and a scope pair can overlap when a parse went wrong — and LSP /// requires every step to contain its child. So the list is walked smallest /// first and a range is kept only when it strictly contains what was kept /// before it; that also drops the duplicates the four sources produce for the /// same construct. fn nested(mut spans: Vec) -> Vec { // A zero-width step selects nothing, which is not a step a user can see. spans.retain(|span| !span.is_empty()); spans.sort_by_key(|span| (span.len(), span.start)); let mut out: Vec = Vec::new(); for span in spans { let keep = match out.last() { Some(inner) => { span.start <= inner.start && span.end >= inner.end && span.len() > inner.len() } None => true, }; if keep { out.push(span); } } out } /// Whether a span covers an offset. The end is **included**: a cursor sitting /// just after a word is still on that word, which is where an expand-selection /// keystroke is most often pressed. fn covers(span: TextRange, offset: u32) -> bool { span.start <= offset && offset <= span.end } /// The spans of every item that covers `offset`, descending only into the one /// that does — the walk is per-keystroke, and a whole-file walk would visit /// thousands of nodes to report a handful. fn items(list: &[Item], offset: u32, out: &mut Vec) { for item in list { if !covers(item.span, offset) { continue; } out.push(item.span); match &item.kind { ItemKind::Module(module) => items(&module.items, offset, out), ItemKind::Class(class) => items(&class.items, offset, out), ItemKind::Package { items: inner, .. } => items(inner, offset, out), ItemKind::GenerateRegion { items: inner, .. } => items(inner, offset, out), ItemKind::GenBlock(b) => items(&b.items, offset, out), ItemKind::GenIf(gen_if) => gen_if_blocks(gen_if, offset, out), ItemKind::GenFor(gen_for) => gen_block(&gen_for.body, offset, out), ItemKind::GenCase(gen_case) => { for case_item in &gen_case.items { if covers(case_item.span, offset) { out.push(case_item.span); gen_block(&case_item.body, offset, out); } } } ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => { statement(stmt, offset, out) } ItemKind::Function(decl) => statements(&decl.stmts, offset, out), ItemKind::Task(decl) => statements(&decl.stmts, offset, out), _ => {} } } } /// A generate `if`, its `else if` ladder and its final `else`. fn gen_if_blocks(gen_if: &GenIf, offset: u32, out: &mut Vec) { gen_block(&gen_if.then, offset, out); let mut els = gen_if.els.as_deref(); while let Some(branch) = els { match branch { GenElse::If(_, nested) => { gen_block(&nested.then, offset, out); els = nested.els.as_deref(); } GenElse::Block(block) => { gen_block(block, offset, out); els = None; } } } } fn gen_block(block: &GenBlock, offset: u32, out: &mut Vec) { if !covers(block.span, offset) { return; } out.push(block.span); items(&block.items, offset, out); } fn statements(list: &[Stmt], offset: u32, out: &mut Vec) { for stmt in list { statement(stmt, offset, out); } } /// The spans of `stmt` and of every statement inside it that covers `offset`. /// /// The recursion is bounded by the parser's own nesting limit /// (`docs/features/recursion-limit/README.md`): a tree this walks is a tree it /// built. fn statement(stmt: &Stmt, offset: u32, out: &mut Vec) { if !covers(stmt.span, offset) { return; } out.push(stmt.span); match &stmt.kind { StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => { statements(stmts, offset, out) } StmtKind::If { then, els, .. } => { statement(then, offset, out); if let Some(els) = els { statement(els, offset, out); } } StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => { for case_item in items { if covers(case_item.span, offset) { out.push(case_item.span); statement(&case_item.stmt, offset, out); } } } StmtKind::Labeled { stmt: inner, .. } => statement(inner, offset, out), StmtKind::For { body, .. } | StmtKind::While { body, .. } | StmtKind::DoWhile { body, .. } | StmtKind::Repeat { body, .. } | StmtKind::Forever { body } | StmtKind::Foreach { body, .. } => statement(body, offset, out), StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => { statement(inner, offset, out) } StmtKind::Assert { then, els, .. } => { if let Some(then) = then { statement(then, offset, out); } if let Some(els) = els { statement(els, offset, out); } } _ => {} } } #[cfg(test)] mod tests { use super::*; use lsp_types::Range; use vlog_semantic::WorkspaceIndex; fn doc_of(text: &str) -> Document { Document::new(None, text.to_string(), &WorkspaceIndex::default()) } /// The innermost step of a chain used to come from a sweep of the whole /// token vector; it now comes from a binary search. `covers` takes /// `span.end` inclusively, so at a byte two adjacent tokens share the /// sweep answered with the earlier of the two — this pins that the search /// answers with the earlier one too, at every byte of a buffer written to /// have plenty of them. #[test] fn the_innermost_step_is_the_token_the_sweep_returned_at_every_offset() { let text = crate::state::mixed_buffer(20); let doc = doc_of(&text); for offset in 0..=text.len() as u32 { let swept = doc.tokens.iter().find(|token| covers(token.span, offset)); let searched = doc .tokens .get(first_token_reaching(&doc.tokens, offset)) .filter(|token| covers(token.span, offset)); assert_eq!(swept.map(|t| t.span), searched.map(|t| t.span), "at offset {offset}"); } } /// The chain for the first occurrence of `needle`, as the source text of /// each step, innermost first. fn steps(text: &str, needle: &str) -> Vec { let doc = doc_of(text); let offset = text.find(needle).expect("the needle is in the text") as u32; let position = doc.positions().position(offset); let chains = selection_ranges(&doc, &[position]); assert_eq!(chains.len(), 1, "one chain per position"); let mut out = Vec::new(); let mut step = Some(&chains[0]); let positions = doc.positions(); while let Some(current) = step { let start = positions.offset(current.range.start) as usize; let end = positions.offset(current.range.end) as usize; out.push(text[start..end].to_string()); step = current.parent.as_deref(); } out } /// Every step of a chain, as `(start, end)` byte offsets. fn spans(doc: &Document, offset: u32) -> Vec<(u32, u32)> { let position = doc.positions().position(offset); let chains = selection_ranges(doc, &[position]); let positions = doc.positions(); let mut out = Vec::new(); let mut step = chains.first(); while let Some(current) = step { out.push((positions.offset(current.range.start), positions.offset(current.range.end))); step = current.parent.as_deref(); } out } #[test] fn the_chain_runs_from_the_token_out_to_the_whole_file() { let text = "module m;\n wire a;\nendmodule\n"; let steps = steps(text, "wire"); assert_eq!(steps.first().map(String::as_str), Some("wire"), "{steps:?}"); assert_eq!(steps.last().map(String::as_str), Some(text), "the whole file closes it"); assert!(steps.contains(&"wire a;".to_string()), "{steps:?}"); } #[test] fn a_statement_expands_through_its_block_and_its_process() { let text = concat!( "module m;\n", " initial begin\n", " if (a) begin\n", " x = 1;\n", " end\n", " end\n", "endmodule\n", ); let steps = steps(text, "x = 1"); assert_eq!(steps.first().map(String::as_str), Some("x")); assert!(steps.iter().any(|s| s == "x = 1;"), "the statement: {steps:?}"); assert!(steps.iter().any(|s| s.starts_with("if (a) begin")), "the if: {steps:?}"); assert!(steps.iter().any(|s| s.starts_with("initial begin")), "the process: {steps:?}"); assert!(steps.iter().any(|s| s.starts_with("module m;")), "the module: {steps:?}"); assert_eq!(steps.last().map(String::as_str), Some(text)); } #[test] fn every_step_strictly_contains_the_one_before_it() { // The protocol's own requirement, and the thing the four sources of // ranges could most easily break. let text = concat!( "module m;\n", " always_comb begin\n", " case (sel)\n", " 2'd0: y = a;\n", " default: y = b;\n", " endcase\n", " end\n", "endmodule\n", ); let doc = doc_of(text); for offset in 0..=text.len() as u32 { let spans = spans(&doc, offset); assert!(!spans.is_empty(), "every position gets a chain, at {offset}"); for pair in spans.windows(2) { let (inner, outer) = (pair[0], pair[1]); assert!( outer.0 <= inner.0 && outer.1 >= inner.1 && outer != inner, "at {offset}: {outer:?} must strictly contain {inner:?} — {spans:?}" ); } assert_eq!( spans.last(), Some(&(0, text.len() as u32)), "the file closes every chain, at {offset}" ); } } #[test] fn a_case_item_is_a_step_of_its_own() { let text = concat!( "module m;\n", " always_comb begin\n", " case (sel)\n", " 2'd0: y = a;\n", " endcase\n", " end\n", "endmodule\n", ); let steps = steps(text, "y = a"); assert!(steps.iter().any(|s| s == "2'd0: y = a;"), "{steps:?}"); assert!(steps.iter().any(|s| s.starts_with("case (sel)")), "{steps:?}"); } #[test] fn a_generate_block_is_a_step_of_its_own() { let text = concat!( "module m;\n", " generate\n", " if (A) begin : g\n", " wire a;\n", " end\n", " endgenerate\n", "endmodule\n", ); let steps = steps(text, "wire a"); assert!(steps.iter().any(|s| s == "wire a;"), "{steps:?}"); assert!(steps.iter().any(|s| s.starts_with("begin : g")), "the block: {steps:?}"); assert!(steps.iter().any(|s| s.starts_with("generate")), "the region: {steps:?}"); } #[test] fn several_positions_are_answered_position_for_position() { let text = "module m;\n wire a;\nendmodule\n"; let doc = doc_of(text); let positions = doc.positions(); let at = |needle: &str| positions.position(text.find(needle).expect("needle") as u32); let asked = vec![at("endmodule"), at("wire"), at("module")]; let chains = selection_ranges(&doc, &asked); assert_eq!(chains.len(), 3); for (chain, position) in chains.iter().zip(&asked) { assert!( chain.range.start <= *position && *position <= chain.range.end, "each answer is about its own position: {chain:?} vs {position:?}" ); } } #[test] fn no_positions_asked_means_no_chains_answered() { let doc = doc_of("module m;\nendmodule\n"); assert!(selection_ranges(&doc, &[]).is_empty()); } #[test] fn an_empty_file_still_answers_one_degenerate_chain() { let doc = doc_of(""); let chains = selection_ranges(&doc, &[Position { line: 0, character: 0 }]); assert_eq!(chains.len(), 1); assert_eq!(chains[0].range.start, chains[0].range.end, "there is nothing to select"); assert!(chains[0].parent.is_none(), "and nothing to expand to"); } #[test] fn a_file_that_does_not_lex_still_answers_the_file_range() { // `Document::new` leaves `tokens` empty and the tree an error leaf, so // this is the path where every source but the last one gives nothing. let text = "module m;\n wire a; /* unterminated\n"; let doc = doc_of(text); assert!(doc.tokens.is_empty(), "the premise"); let spans = spans(&doc, 12); assert_eq!(spans.last(), Some(&(0, text.len() as u32))); } #[test] fn an_unclosed_scope_still_expands_through_what_did_close() { // The mid-edit shape: the `begin` never closes, so the AST cannot // offer the statement — the module's own pair still can. let text = "module m;\n initial begin\n x = 1;\nendmodule\n"; let doc = doc_of(text); let offset = text.find("x = 1").expect("needle") as u32; let spans = spans(&doc, offset); assert!(spans.len() >= 2, "at least the token and the file: {spans:?}"); assert_eq!(spans.last(), Some(&(0, text.len() as u32))); } #[test] fn a_position_past_the_end_of_the_file_clamps_into_it() { let text = "module m;\nendmodule\n"; let doc = doc_of(text); let chains = selection_ranges(&doc, &[Position { line: 99, character: 99 }]); assert_eq!(chains.len(), 1); assert_eq!(chains[0].range.end, doc.positions().whole_document().end); } #[test] fn a_multibyte_line_keeps_the_columns_in_utf16() { // The chain is computed in bytes and answered in UTF-16 units; an // off-by-one here would select the wrong text in the editor only. let text = "module m;\n // é 🎉\n wire a;\nendmodule\n"; let steps = steps(text, "wire"); assert_eq!(steps.first().map(String::as_str), Some("wire"), "{steps:?}"); assert!(steps.iter().any(|s| s == "wire a;"), "{steps:?}"); } #[test] fn nesting_drops_a_range_that_does_not_contain_what_came_before() { // The guard for the overlapping-sources case: two ranges that both // cover the cursor but nest in neither direction. The wider-but-not- // enclosing one must be dropped, never emitted as a parent. let spans = vec![ TextRange::new(4, 6), TextRange::new(0, 8), TextRange::new(5, 20), // covers 5, contains neither of the above TextRange::new(0, 30), ]; let kept = nested(spans); assert_eq!( kept.iter().map(|s| (s.start, s.end)).collect::>(), vec![(4, 6), (0, 8), (0, 30)] ); } /// The strict-nesting invariant, on the real corpus rather than /// hand-written snippets. `every_step_strictly_contains_the_one_before_it` /// above proves the invariant on files this crate's author wrote to /// exercise it; a corpus file was written by nobody thinking about this /// walk at all, and is exactly what turns up a construct the four /// sources disagree about. Skipped when `corpus/` is not checked out, /// like every other corpus test in this crate. #[test] fn every_step_strictly_nests_over_the_real_corpus() { let corpus = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); if !corpus.is_dir() { eprintln!("corpus/ not checked out — skipping"); return; } let extensions = ["sv", "v", "svh", "vh"]; let mut files_checked = 0; let mut positions_checked = 0; for entry in walk(&corpus) { let Some(ext) = entry.extension().and_then(|e| e.to_str()) else { continue }; if !extensions.contains(&ext) { continue; } let Ok(text) = std::fs::read_to_string(&entry) else { continue }; if text.is_empty() { continue; } files_checked += 1; let doc = Document::new(Some(entry.clone()), text.clone(), &WorkspaceIndex::default()); let converter = doc.positions(); // A handful of evenly spaced offsets per file, not every byte: // the corpus is 800+ files, and the per-offset invariant is // already proven exhaustively on small files above. This is // about *coverage of real syntax*, not exhaustiveness per file. let len = text.len() as u32; let stride = (len / 7).max(1); let mut offset = 0; while offset <= len { positions_checked += 1; let position = converter.position(offset); let chains = selection_ranges(&doc, &[position]); assert_eq!(chains.len(), 1, "{}: offset {offset}", entry.display()); let mut step = Some(&chains[0]); let mut previous: Option = None; while let Some(current) = step { if let Some(inner) = previous { let widens = current.range.start <= inner.start && current.range.end >= inner.end && current.range != inner; assert!( widens, "{}: offset {offset}: {:?} does not strictly contain {:?}", entry.display(), current.range, inner ); } previous = Some(current.range); step = current.parent.as_deref(); } let whole = converter.whole_document(); assert_eq!( previous, Some(whole), "{}: offset {offset}: the file must close every chain", entry.display() ); offset += stride; } } assert!(files_checked > 100, "the corpus really is checked out: {files_checked} files"); eprintln!("selection ranges: {files_checked} files, {positions_checked} positions, no panics, every step strictly nested"); } /// Every regular file under `dir`, recursively — no filtering by anything /// but extension, which the caller does. Errors reading a directory are /// treated as "nothing here" rather than failing the whole sweep: a /// symlink loop or a permission-denied subtree in a third-party corpus /// checkout should not take the QA test down with it. fn walk(dir: &std::path::Path) -> Vec { let mut out = Vec::new(); let Ok(entries) = std::fs::read_dir(dir) else { return out }; for entry in entries.flatten() { let path = entry.path(); if path.is_dir() { out.extend(walk(&path)); } else { out.push(path); } } out } #[test] fn nesting_drops_duplicates_and_empty_ranges() { let spans = vec![ TextRange::new(3, 3), TextRange::new(2, 9), TextRange::new(2, 9), TextRange::new(0, 9), ]; let kept = nested(spans); assert_eq!(kept.iter().map(|s| (s.start, s.end)).collect::>(), vec![(2, 9), (0, 9)]); } }