From f280e511691e018c64cf8cb4ff6174bb4fe98a3e Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Mon, 24 Aug 2026 02:08:00 -0700 Subject: [PATCH] vfmt-server: begin/end pair engine, documentHighlight, missing-end warnings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New pairs.rs: a stack matcher over the token stream for begin/end and 16 relative pairs, with guards for every no-body construct that spells an opener keyword (extern/DPI prototypes, typedef class, virtual interface, assert property, covergroup with function sample, ...). Non-cascading mismatch recovery makes one missing end point at the exact unclosed begin. Feeds textDocument/documentHighlight (cursor on begin highlights its matching end) and WARNING diagnostics for unmatched openers/closers — gated on the parse already failing, so macro/ifdef keyword imbalance in working code can never warn. Corpus sweep: 840 clean-parsing files, 11,062 matched pairs, 0 false positives (reproduced independently by QA). Co-Authored-By: Claude Fable 5 --- crates/vfmt_server/src/diagnostics.rs | 5 + crates/vfmt_server/src/main.rs | 6 + crates/vfmt_server/src/pairs.rs | 903 ++++++++++++++++++++++++++ crates/vfmt_server/src/server.rs | 32 +- crates/vfmt_server/tests/e2e.rs | 103 +++ docs/features/editor-scopes/README.md | 327 ++++++++++ 6 files changed, 1369 insertions(+), 7 deletions(-) create mode 100644 crates/vfmt_server/src/pairs.rs create mode 100644 docs/features/editor-scopes/README.md diff --git a/crates/vfmt_server/src/diagnostics.rs b/crates/vfmt_server/src/diagnostics.rs index 1961c49..b10cb5d 100644 --- a/crates/vfmt_server/src/diagnostics.rs +++ b/crates/vfmt_server/src/diagnostics.rs @@ -19,8 +19,13 @@ pub const SOURCE: &str = "vfmt"; /// once. Each source is already in position order; they are not interleaved, /// because an error the user must fix reads better above an opinion about /// style. +/// +/// The missing-closer warnings sit between the two: they explain a parse +/// error rather than add an opinion, and they exist at all only when the parse +/// already failed (`pairs::missing_end_diagnostics`). pub fn all(doc: &Document) -> Vec { let mut all = diagnostics(doc); + all.extend(crate::pairs::missing_end_diagnostics(doc)); all.extend(crate::lint::diagnostics(doc)); all } diff --git a/crates/vfmt_server/src/main.rs b/crates/vfmt_server/src/main.rs index 4076c6e..71dd7ff 100644 --- a/crates/vfmt_server/src/main.rs +++ b/crates/vfmt_server/src/main.rs @@ -14,6 +14,7 @@ mod hover; mod lint; mod locate; mod nav; +mod pairs; mod server; mod state; mod symbols; @@ -62,6 +63,10 @@ fn capabilities() -> ServerCapabilities { document_range_formatting_provider: Some(OneOf::Left(true)), definition_provider: Some(OneOf::Left(true)), references_provider: Some(OneOf::Left(true)), + // The cursor on a `begin` highlights its own `end`, matched over the + // token stream. The handler declines anything that is not half of a + // pair, which leaves the editor's word highlighting in charge. + document_highlight_provider: Some(OneOf::Left(true)), hover_provider: Some(lsp_types::HoverProviderCapability::Simple(true)), document_symbol_provider: Some(OneOf::Left(true)), workspace_symbol_provider: Some(OneOf::Left(true)), @@ -125,6 +130,7 @@ mod tests { assert!(caps.document_range_formatting_provider.is_some()); assert!(caps.definition_provider.is_some()); assert!(caps.references_provider.is_some()); + assert!(caps.document_highlight_provider.is_some()); assert!(caps.hover_provider.is_some()); assert!(caps.document_symbol_provider.is_some()); assert!(caps.workspace_symbol_provider.is_some()); diff --git a/crates/vfmt_server/src/pairs.rs b/crates/vfmt_server/src/pairs.rs new file mode 100644 index 0000000..d764a2e --- /dev/null +++ b/crates/vfmt_server/src/pairs.rs @@ -0,0 +1,903 @@ +//! Scope pairs — `begin`/`end` and its sixteen relatives — matched with a +//! stack over the token stream. +//! +//! One engine, three consumers: `textDocument/documentHighlight` (below), +//! the missing-closer warnings (below), and the extension's rainbow colouring +//! (`vfmt/scopePairs`, next round). Matching runs over `Document.tokens` +//! rather than the text, so a `// end` in a comment or a `"begin"` in a string +//! cannot be mistaken for a keyword: the lexer has already thrown comments out +//! of the stream and made the string one `String` token. See +//! `docs/features/editor-scopes/README.md`. + +use lsp_types::{Diagnostic, DiagnosticSeverity, DocumentHighlight, DocumentHighlightKind}; +use vlog_parser::token::{Token, TokenKind}; +use vlog_parser::TextRange; + +use crate::diagnostics::SOURCE; +use crate::state::Document; + +/// One opener keyword and every keyword that can close it. +struct Rule { + open: &'static str, + /// The closers, most canonical first — the first is the one the warnings + /// name, so `fork` is reported as wanting a `join`. + close: &'static [&'static str], +} + +/// Every scope this server matches. Deliberately not exhaustive: see the +/// feature README for what is left out and why. +const RULES: &[Rule] = &[ + Rule { open: "begin", close: &["end"] }, + Rule { open: "fork", close: &["join", "join_any", "join_none"] }, + Rule { open: "case", close: &["endcase"] }, + Rule { open: "casex", close: &["endcase"] }, + Rule { open: "casez", close: &["endcase"] }, + Rule { open: "randcase", close: &["endcase"] }, + Rule { open: "module", close: &["endmodule"] }, + Rule { open: "macromodule", close: &["endmodule"] }, + Rule { open: "function", close: &["endfunction"] }, + Rule { open: "task", close: &["endtask"] }, + Rule { open: "generate", close: &["endgenerate"] }, + Rule { open: "interface", close: &["endinterface"] }, + Rule { open: "package", close: &["endpackage"] }, + Rule { open: "class", close: &["endclass"] }, + Rule { open: "program", close: &["endprogram"] }, + Rule { open: "property", close: &["endproperty"] }, + Rule { open: "sequence", close: &["endsequence"] }, + Rule { open: "clocking", close: &["endclocking"] }, + Rule { open: "covergroup", close: &["endgroup"] }, + Rule { open: "specify", close: &["endspecify"] }, + Rule { open: "primitive", close: &["endprimitive"] }, +]; + +/// Keywords that turn the rest of their statement into a declaration without a +/// body. `extern function f();` and `import "DPI-C" function void c();` spell +/// `function` and close nothing; so do `pure virtual`, `export "DPI-C"` and +/// `typedef class C;`. The flag they raise is dropped at the next `;`. +const PROTOTYPE_STARTERS: &[&str] = &["extern", "pure", "import", "export", "typedef"]; + +/// A matched pair of keywords. +pub struct Pair { + pub open: TextRange, + pub close: TextRange, + /// How many scopes were already open when this one opened; 0 is outermost. + // Computed and tested here, consumed by the extension: the rainbow picks + // its colour with `depth % 6`. The `vfmt/scopePairs` request that carries + // it to the client is the next milestone, so until then only the tests in + // this file read the field. + #[allow(dead_code)] + pub depth: u32, +} + +/// A keyword whose counterpart never arrived. +pub struct Unmatched { + /// The keyword's own span — what a diagnostic points at. + pub span: TextRange, + /// The keyword as written. + pub keyword: &'static str, + /// The counterpart that is missing: the closer for an unmatched opener, + /// the opener for an unmatched closer. + pub expected: &'static str, +} + +/// What the matcher made of a token stream. +#[derive(Default)] +pub struct ScopeAnalysis { + /// Matched pairs, in source order of their opener. + pub pairs: Vec, + /// Openers that were never closed, in source order. + pub unmatched_open: Vec, + /// Closers that closed nothing, in source order. + pub unmatched_close: Vec, +} + +/// An open scope, waiting for its closer. +struct Frame { + rule: &'static Rule, + span: TextRange, + depth: u32, +} + +/// Match every scope keyword in a token stream. +/// +/// Never panics and never gives up: a stream that is unbalanced in any +/// direction still yields every pair that *did* match, which is what keeps a +/// missing `end` halfway down a file from un-colouring everything below it. +pub fn analyze(tokens: &[Token]) -> ScopeAnalysis { + let mut analysis = ScopeAnalysis::default(); + let mut stack: Vec = Vec::new(); + // Raised by `PROTOTYPE_STARTERS`, dropped at the `;` that ends the + // statement. Everything between the two opens nothing. + let mut prototype = false; + + for (i, token) in tokens.iter().enumerate() { + if token.is_sym(";") { + prototype = false; + continue; + } + if token.kind != TokenKind::Keyword { + continue; + } + let text = token.text.as_str(); + if PROTOTYPE_STARTERS.contains(&text) { + prototype = true; + continue; + } + if let Some(rule) = opener_rule(text) { + if !prototype && opens_a_scope(tokens, i) { + let depth = stack.len() as u32; + stack.push(Frame { rule, span: token.span, depth }); + } + } else if let Some(closer) = closer_keyword(text) { + close(&mut analysis, &mut stack, closer, token.span); + } + } + + // Whatever is still open never closed. + for frame in stack { + analysis.unmatched_open.push(Unmatched { + span: frame.span, + keyword: frame.rule.open, + expected: frame.rule.close[0], + }); + } + analysis.pairs.sort_by_key(|p| p.open.start); + analysis.unmatched_open.sort_by_key(|u| u.span.start); + analysis.unmatched_close.sort_by_key(|u| u.span.start); + analysis +} + +/// Match one closer against the stack. +/// +/// The recovery rule is the whole reason a missing `end` points at the right +/// `begin`: a closer that matches a frame *below* the top closes that frame +/// and reports the frames above it as unclosed, and a closer that matches +/// nothing at all is reported on its own and leaves the stack untouched. +/// Popping blindly would make one missing `end` cascade into every enclosing +/// scope. +fn close( + analysis: &mut ScopeAnalysis, + stack: &mut Vec, + closer: &'static str, + span: TextRange, +) { + let Some(index) = stack.iter().rposition(|f| f.rule.close.contains(&closer)) else { + analysis.unmatched_close.push(Unmatched { + span, + keyword: closer, + expected: opener_of(closer), + }); + return; + }; + for frame in stack.drain(index + 1..) { + analysis.unmatched_open.push(Unmatched { + span: frame.span, + keyword: frame.rule.open, + expected: frame.rule.close[0], + }); + } + if let Some(frame) = stack.pop() { + analysis.pairs.push(Pair { open: frame.span, close: span, depth: frame.depth }); + } +} + +/// The rule an opener keyword names, if it is one. +fn opener_rule(text: &str) -> Option<&'static Rule> { + RULES.iter().find(|r| r.open == text) +} + +/// The closer keyword `text` is, as a `'static` string from the table. +fn closer_keyword(text: &str) -> Option<&'static str> { + RULES.iter().flat_map(|r| r.close).copied().find(|c| *c == text) +} + +/// The opener a closer belongs to, for "`end` has no matching `begin`". +fn opener_of(closer: &str) -> &'static str { + RULES.iter().find(|r| r.close.contains(&closer)).map_or("", |r| r.open) +} + +/// Whether the opener keyword at `i` really opens a scope. +/// +/// Every arm here is a construct that spells an opener keyword and opens +/// nothing. Getting one wrong costs a phantom unclosed scope, so each is +/// pinned by a test. +fn opens_a_scope(tokens: &[Token], i: usize) -> bool { + let prev = i.checked_sub(1).and_then(|p| tokens.get(p)); + let next = tokens.get(i + 1); + match tokens[i].text.as_str() { + // `virtual interface bus_if vif;` is a type, not a declaration; + // `interface class C; ... endclass` is closed by the `class` next to + // it, which opens on its own; and an `interface` after a `(` or a `,` + // is a generic interface port (`module m (interface bus);`). + "interface" => { + !is_keyword(prev, "virtual") + && !is_keyword(next, "class") + && !is_symbol(prev, "(") + && !is_symbol(prev, ",") + } + // A declaration names what it declares (`property p;`); the assertion + // forms — `assert property (...)`, `cover sequence (...)` — put a `(` + // there instead and close nothing. + "property" | "sequence" => matches!(next, Some(t) if t.kind == TokenKind::Ident), + // `default clocking cb;` names a block that already exists. A real + // block writes an event next: `clocking cb @(posedge clk);`. + "clocking" => !(is_ident(next) && is_symbol(tokens.get(i + 2), ";")), + // `disable fork;` and `wait fork;` talk about a fork, they do not + // start one. + "fork" => !is_keyword(prev, "disable") && !is_keyword(prev, "wait"), + // `covergroup cg with function sample(int x);` declares the sample + // method in the covergroup's *header*; the body is the covergroup's, + // and there is no `endfunction`. Every UVM coverage class writes this. + "function" => !is_keyword(prev, "with"), + _ => true, + } +} + +fn is_keyword(token: Option<&Token>, keyword: &str) -> bool { + matches!(token, Some(t) if t.is_kw(keyword)) +} + +fn is_symbol(token: Option<&Token>, symbol: &str) -> bool { + matches!(token, Some(t) if t.is_sym(symbol)) +} + +fn is_ident(token: Option<&Token>) -> bool { + matches!(token, Some(t) if t.kind == TokenKind::Ident) +} + +// ---------------------------------------------------------------------- +// textDocument/documentHighlight +// ---------------------------------------------------------------------- + +/// Both halves of the pair the cursor is on, or `None` when it is on neither. +/// +/// `None` matters: LSP lets the editor fall back to its own word-occurrence +/// highlighting when a server declines, and highlighting every `end` in the +/// file because the cursor happens to be on one would be worse than that +/// fallback. An unmatched keyword therefore highlights nothing — there is no +/// second range to point at, and inventing one would be a lie. +pub fn highlights(doc: &Document, offset: u32) -> Option> { + let analysis = analyze(&doc.tokens); + let pair = analysis.pairs.iter().find(|p| covers(p.open, offset) || covers(p.close, offset))?; + let positions = doc.positions(); + let highlight = |span| DocumentHighlight { + range: positions.range(span), + kind: Some(DocumentHighlightKind::TEXT), + }; + Some(vec![highlight(pair.open), highlight(pair.close)]) +} + +/// A keyword is under the cursor from its first byte to one past its last: an +/// editor leaves the caret *after* the word the user just finished typing, and +/// `end|` must highlight as surely as `|end` does. Keyword spans never touch, +/// so the extra byte cannot claim the neighbour. +fn covers(span: TextRange, offset: u32) -> bool { + offset >= span.start && offset <= span.end +} + +// ---------------------------------------------------------------------- +// missing-closer diagnostics +// ---------------------------------------------------------------------- + +/// How many missing-closer warnings one buffer is worth. A file that lost a +/// keyword early is unbalanced from there to the end; the twenty-first +/// squiggle says nothing the first twenty did not. +const MAX_WARNINGS: usize = 20; + +/// Warnings for keywords whose counterpart is missing — **only** for a buffer +/// the parser already complained about. +/// +/// The gate is the point. A token-stream matcher cannot see `` `ifdef `` arms +/// or what a macro expands to, so keyword counts in a perfectly good file can +/// be unbalanced for reasons that are none of our business. Warning on a file +/// the parser accepted would mean telling a user their working code is broken, +/// which is the one thing a linter may never do. When the parse *has* already +/// failed, the user is looking for the reason, and "this `begin` has no `end`" +/// is a far better answer than an error at the end of the file. +pub fn missing_end_diagnostics(doc: &Document) -> Vec { + if doc.diagnostics.is_empty() { + return Vec::new(); + } + let analysis = analyze(&doc.tokens); + let mut found: Vec<(TextRange, String)> = Vec::new(); + for open in &analysis.unmatched_open { + let (keyword, expected) = (open.keyword, open.expected); + found.push(( + open.span, + format!( + "`{keyword}` has no matching `{expected}` — is {} `{expected}` missing?", + article(expected) + ), + )); + } + for close in &analysis.unmatched_close { + let (keyword, expected) = (close.keyword, close.expected); + found.push((close.span, format!("`{keyword}` has no matching `{expected}`"))); + } + found.sort_by_key(|(span, _)| span.start); + found.truncate(MAX_WARNINGS); + + let positions = doc.positions(); + found + .into_iter() + .map(|(span, message)| Diagnostic { + range: positions.range(span), + severity: Some(DiagnosticSeverity::WARNING), + source: Some(SOURCE.to_string()), + message, + ..Default::default() + }) + .collect() +} + +/// "an `end`", "a `join`". Every closer we name starts with `end` or `join`, +/// but spelling the rule out costs one line and survives the next closer. +fn article(word: &str) -> &'static str { + match word.chars().next() { + Some('a' | 'e' | 'i' | 'o' | 'u') => "an", + _ => "a", + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::state::Workspace; + use lsp_types::Uri; + use std::str::FromStr; + use vlog_parser::tokenize; + use vlog_semantic::WorkspaceIndex; + + /// The analysis of a source string, straight off the lexer — no parser + /// involved, which is the point: the matcher must stand on its own. + fn scopes(text: &str) -> ScopeAnalysis { + let tokens = tokenize(text).expect("the fixtures all lex"); + analyze(&tokens) + } + + /// The source text of every matched pair, as `open..close`. + fn matched(text: &str) -> Vec { + let analysis = scopes(text); + analysis + .pairs + .iter() + .map(|p| { + format!( + "{}..{}", + &text[p.open.start as usize..p.open.end as usize], + &text[p.close.start as usize..p.close.end as usize] + ) + }) + .collect() + } + + /// The keyword of every unclosed opener, in source order. + fn unclosed(text: &str) -> Vec<&'static str> { + scopes(text).unmatched_open.iter().map(|u| u.keyword).collect() + } + + /// The keyword of every closer that closed nothing. + fn orphan_closers(text: &str) -> Vec<&'static str> { + scopes(text).unmatched_close.iter().map(|u| u.keyword).collect() + } + + fn doc_of(text: &str) -> Document { + Document::new(None, text.to_string(), &WorkspaceIndex::default()) + } + + /// The byte offset of `needle` in `text`. + fn at(text: &str, needle: &str) -> u32 { + text.find(needle).expect("needle present") as u32 + } + + // ------------------------------------------------------------------ + // the basics + // ------------------------------------------------------------------ + + #[test] + fn a_module_with_nested_begins_matches_every_pair() { + let text = "module m;\n initial begin\n if (x) begin\n y = 1;\n end\n end\nendmodule\n"; + let analysis = scopes(text); + assert_eq!(analysis.pairs.len(), 3); + assert!(analysis.unmatched_open.is_empty()); + assert!(analysis.unmatched_close.is_empty()); + // Depth counts every open frame, not just the begins: the module is + // outermost, so the first begin is already one deep. + let depths: Vec = analysis.pairs.iter().map(|p| p.depth).collect(); + assert_eq!(depths, vec![0, 1, 2], "module, outer begin, inner begin"); + } + + #[test] + fn a_comment_or_a_string_never_counts_as_a_keyword() { + // Hard invariant of the whole approach: the lexer detaches comments + // and makes the literal one token, so neither can push or pop. + let text = "module m;\n // end endmodule\n initial begin\n /* begin */\n $display(\"end begin endmodule\");\n end\nendmodule\n"; + let analysis = scopes(text); + assert_eq!(analysis.pairs.len(), 2, "the module and the one real begin"); + assert!(analysis.unmatched_open.is_empty()); + assert!(analysis.unmatched_close.is_empty()); + } + + #[test] + fn a_labeled_block_matches_on_the_keywords_alone() { + let text = "module m;\n initial begin : outer\n begin : inner\n x = 1;\n end : inner\n end : outer\nendmodule\n"; + let analysis = scopes(text); + assert_eq!(analysis.pairs.len(), 3); + assert!(analysis.unmatched_open.is_empty(), "labels are not part of the match"); + } + + #[test] + fn every_fork_flavour_joins() { + for closer in ["join", "join_any", "join_none"] { + let text = format!("module m;\n initial fork\n x = 1;\n {closer}\nendmodule\n"); + let analysis = scopes(&text); + assert_eq!(analysis.pairs.len(), 2, "module + fork, closed by {closer}"); + assert!(analysis.unmatched_open.is_empty(), "{closer} must close a fork"); + } + } + + #[test] + fn every_case_flavour_ends() { + for opener in ["case", "casex", "casez", "randcase"] { + let text = + format!("module m;\n initial {opener} (x)\n 1: y = 1;\n endcase\nendmodule\n"); + assert!(scopes(&text).unmatched_open.is_empty(), "{opener} must take endcase"); + } + } + + #[test] + fn the_named_scopes_all_pair_up() { + let cases = [ + ("module m;\nendmodule\n", "module"), + ("macromodule m;\nendmodule\n", "macromodule"), + ("package p;\nendpackage\n", "package"), + ("interface i;\nendinterface\n", "interface"), + ("program p;\nendprogram\n", "program"), + ("class c;\nendclass\n", "class"), + ("module m;\n function f;\n endfunction\nendmodule\n", "function"), + ("module m;\n task t;\n endtask\nendmodule\n", "task"), + ("module m;\n generate\n endgenerate\nendmodule\n", "generate"), + ("module m;\n specify\n endspecify\nendmodule\n", "specify"), + ("primitive p (o, i);\nendprimitive\n", "primitive"), + ("module m;\n property p;\n endproperty\nendmodule\n", "property"), + ("module m;\n sequence s;\n endsequence\nendmodule\n", "sequence"), + ("module m;\n clocking cb @(posedge clk);\n endclocking\nendmodule\n", "clocking"), + ("class c;\n covergroup cg;\n endgroup\nendclass\n", "covergroup"), + ]; + for (text, what) in cases { + let analysis = scopes(text); + assert!(analysis.unmatched_open.is_empty(), "{what} left something open"); + assert!(analysis.unmatched_close.is_empty(), "{what} left a stray closer"); + assert!(!analysis.pairs.is_empty(), "{what} matched nothing at all"); + } + } + + // ------------------------------------------------------------------ + // hazards: keywords that open nothing + // ------------------------------------------------------------------ + + #[test] + fn an_extern_prototype_opens_nothing() { + let text = "class c;\n extern function void f(int a);\n extern task t();\nendclass\n"; + assert!(unclosed(text).is_empty(), "prototypes have no body"); + assert_eq!(matched(text), vec!["class..endclass"]); + } + + #[test] + fn a_pure_virtual_method_opens_nothing() { + let text = "class c;\n pure virtual function int g();\nendclass\n"; + assert!(unclosed(text).is_empty()); + assert_eq!(matched(text), vec!["class..endclass"]); + } + + #[test] + fn a_dpi_import_or_export_opens_nothing() { + let text = "module m;\n import \"DPI-C\" function void c_init(input int a);\n import \"DPI-C\" context function int c_get();\n export \"DPI-C\" function f;\nendmodule\n"; + assert!(unclosed(text).is_empty(), "DPI declarations have no body"); + assert_eq!(matched(text), vec!["module..endmodule"]); + } + + #[test] + fn an_extern_module_header_opens_nothing() { + let text = "extern module m (input a);\nmodule m (input a);\nendmodule\n"; + assert!(unclosed(text).is_empty()); + assert_eq!(matched(text), vec!["module..endmodule"], "only the real one"); + } + + #[test] + fn a_package_import_does_not_swallow_the_next_declaration() { + // The prototype flag is dropped at the `;`, so an ordinary + // `import p::*;` must not suppress the function after it. + let text = "module m;\n import p::*;\n function f;\n endfunction\nendmodule\n"; + assert!(unclosed(text).is_empty()); + assert_eq!(matched(text), vec!["module..endmodule", "function..endfunction"]); + } + + #[test] + fn a_module_header_import_does_not_suppress_the_body() { + let text = "module m import p::*; (input a);\n initial begin\n end\nendmodule\n"; + assert!(unclosed(text).is_empty()); + assert_eq!(matched(text), vec!["module..endmodule", "begin..end"]); + } + + #[test] + fn a_typedef_class_is_a_forward_declaration() { + let text = "typedef class C;\nclass C;\n int x;\nendclass\n"; + assert!(unclosed(text).is_empty(), "the forward declaration opens nothing"); + assert_eq!(matched(text), vec!["class..endclass"], "only the real class"); + } + + #[test] + fn a_virtual_interface_member_is_a_type() { + let text = "class c;\n virtual interface bus_if vif;\n virtual bus_if v2;\nendclass\n"; + assert!(unclosed(text).is_empty(), "`virtual interface` is a type"); + assert_eq!(matched(text), vec!["class..endclass"]); + } + + #[test] + fn a_virtual_class_still_opens() { + let text = "virtual class C;\n int x;\nendclass\n"; + assert_eq!(matched(text), vec!["class..endclass"], "an abstract class has a body"); + } + + #[test] + fn an_interface_class_is_closed_by_endclass() { + // `interface class IC; ... endclass`: the `class` opens, the + // `interface` in front of it does not, or the `endclass` would find + // an `interface` frame on top of the stack and report both wrong. + let text = "interface class IC;\n pure virtual function void f();\nendclass\n"; + assert_eq!(matched(text), vec!["class..endclass"]); + assert!(unclosed(text).is_empty()); + assert!(orphan_closers(text).is_empty()); + } + + #[test] + fn a_generic_interface_port_opens_nothing() { + let text = "module m (interface bus, input logic clk);\nendmodule\n"; + assert_eq!(matched(text), vec!["module..endmodule"]); + assert!(unclosed(text).is_empty(), "a port is not a declaration"); + } + + #[test] + fn a_default_clocking_reference_opens_nothing() { + let text = "module m;\n clocking cb @(posedge clk);\n endclocking\n default clocking cb;\nendmodule\n"; + assert!(unclosed(text).is_empty(), "`default clocking cb;` names an existing block"); + assert_eq!(matched(text), vec!["module..endmodule", "clocking..endclocking"]); + } + + #[test] + fn an_unnamed_default_clocking_block_still_opens() { + let text = "module m;\n default clocking @(posedge clk);\n endclocking\nendmodule\n"; + assert!(unclosed(text).is_empty()); + assert_eq!(matched(text), vec!["module..endmodule", "clocking..endclocking"]); + } + + #[test] + fn an_assertion_does_not_open_a_property() { + let text = "module m;\n a1: assert property (@(posedge clk) a |-> b);\n cover property (@(posedge clk) c);\n assume property (@(posedge clk) d);\nendmodule\n"; + assert!(unclosed(text).is_empty(), "`assert property (` opens nothing"); + assert_eq!(matched(text), vec!["module..endmodule"]); + } + + #[test] + fn a_property_declaration_does_open() { + let text = + "module m;\n property p;\n @(posedge clk) a |-> b;\n endproperty\nendmodule\n"; + assert_eq!(matched(text), vec!["module..endmodule", "property..endproperty"]); + } + + #[test] + fn disable_fork_and_wait_fork_are_statements() { + let text = "module m;\n initial begin\n fork\n x = 1;\n join_any\n disable fork;\n wait fork;\n end\nendmodule\n"; + assert!(unclosed(text).is_empty(), "`disable fork;` starts no fork"); + assert_eq!(matched(text), vec!["module..endmodule", "begin..end", "fork..join_any"]); + } + + #[test] + fn a_covergroup_sample_method_opens_nothing() { + // Found by sweeping the corpus, not by reading the LRM: seven of the + // 840 files that parse cleanly write this, and every one of them is a + // UVM coverage class. `with function sample(...)` names the + // covergroup's sample method in its header; the `endgroup` closes the + // lot, and there is no `endfunction` anywhere. + let text = "class c;\n covergroup cg with function sample(int lvl, bit rst);\n cp: coverpoint lvl;\n endgroup\n function new();\n endfunction\nendclass\n"; + assert!(unclosed(text).is_empty(), "the sample method has no body of its own"); + assert_eq!( + matched(text), + vec!["class..endclass", "covergroup..endgroup", "function..endfunction"], + "and the real function next to it still pairs" + ); + } + + #[test] + fn a_macro_invocation_is_invisible_to_the_matcher() { + // A macro body is not in this token stream, so a macro that expands to + // a whole block must neither open nor close anything. This is why the + // diagnostics below are gated on the parser having already failed. + let text = + "class c;\n `uvm_component_utils(c)\n `uvm_do_with(item, { a == 1; })\nendclass\n"; + assert_eq!(matched(text), vec!["class..endclass"]); + assert!(unclosed(text).is_empty()); + assert!(orphan_closers(text).is_empty()); + } + + // ------------------------------------------------------------------ + // hazards: mismatch recovery + // ------------------------------------------------------------------ + + #[test] + fn a_missing_end_points_at_the_innermost_unclosed_begin() { + let text = "module m;\n initial begin\n if (x) begin\n y = 1;\n end\nendmodule\n"; + let analysis = scopes(text); + // The one `end` closes the inner begin; the outer one is left open. + assert_eq!(analysis.unmatched_open.len(), 1); + assert_eq!(analysis.unmatched_open[0].keyword, "begin"); + assert_eq!(analysis.unmatched_open[0].expected, "end"); + assert_eq!( + analysis.unmatched_open[0].span.start, + at(text, "begin"), + "the `initial begin` on line 2, not the module and not the inner begin" + ); + // And the module still matched, which is the whole point of the + // recovery rule: one missing `end` must not lose `endmodule`. + assert!(matched(text).contains(&"module..endmodule".to_string())); + } + + #[test] + fn two_missing_ends_are_both_reported_in_source_order() { + let text = "module m;\n initial begin\n if (x) begin\n y = 1;\nendmodule\n"; + let analysis = scopes(text); + let keywords: Vec<_> = analysis.unmatched_open.iter().map(|u| u.keyword).collect(); + assert_eq!(keywords, vec!["begin", "begin"]); + assert!(analysis.unmatched_open[0].span.start < analysis.unmatched_open[1].span.start); + assert_eq!(matched(text), vec!["module..endmodule"]); + } + + #[test] + fn a_stray_end_matches_nothing_and_disturbs_nothing() { + let text = "module m;\n initial begin\n x = 1;\n end\n end\nendmodule\n"; + let analysis = scopes(text); + assert_eq!(orphan_closers(text), vec!["end"], "the second `end` closes nothing"); + assert!(analysis.unmatched_open.is_empty(), "the stack must be left alone"); + assert_eq!(matched(text), vec!["module..endmodule", "begin..end"]); + } + + #[test] + fn a_wrong_closer_does_not_pop_the_frame_it_does_not_match() { + // `endmodule` while a `begin` is open: the begin is reported unclosed + // and the module still pairs. Popping blindly would pair `begin` with + // `endmodule` and then report the module unclosed — two lies for one + // missing keyword. + let text = "module m;\n initial begin\n x = 1;\nendmodule\n"; + let analysis = scopes(text); + assert_eq!(matched(text), vec!["module..endmodule"]); + assert_eq!(analysis.unmatched_open.len(), 1); + assert_eq!(analysis.unmatched_open[0].keyword, "begin"); + } + + #[test] + fn an_endcase_with_no_case_is_an_orphan_closer() { + let text = "module m;\n initial begin\n endcase\n end\nendmodule\n"; + let analysis = scopes(text); + assert_eq!(orphan_closers(text), vec!["endcase"]); + assert_eq!(analysis.unmatched_close[0].expected, "case", "it wanted a case"); + assert_eq!(matched(text), vec!["module..endmodule", "begin..end"], "nothing else moved"); + } + + #[test] + fn an_orphan_join_names_the_fork_it_wanted() { + let text = "module m;\n initial begin\n join_none\n end\nendmodule\n"; + let analysis = scopes(text); + assert_eq!(analysis.unmatched_close.len(), 1); + assert_eq!(analysis.unmatched_close[0].keyword, "join_none"); + assert_eq!(analysis.unmatched_close[0].expected, "fork"); + } + + #[test] + fn an_empty_stream_analyzes_to_nothing() { + let analysis = analyze(&[]); + assert!(analysis.pairs.is_empty()); + assert!(analysis.unmatched_open.is_empty()); + assert!(analysis.unmatched_close.is_empty()); + } + + #[test] + fn a_file_that_does_not_lex_has_no_tokens_and_no_pairs() { + // `Document::new` leaves `tokens` empty when the lexer gives up, so + // the matcher sees nothing rather than a truncated stream. + let doc = doc_of("module m;\n wire a; /* unterminated\n"); + assert!(doc.tokens.is_empty()); + assert!(analyze(&doc.tokens).pairs.is_empty()); + assert!(missing_end_diagnostics(&doc).is_empty(), "and says nothing about it"); + } + + // ------------------------------------------------------------------ + // documentHighlight + // ------------------------------------------------------------------ + + #[test] + fn the_cursor_on_begin_highlights_its_own_end() { + let text = "module m;\n initial begin\n if (x) begin\n y = 1;\n end\n end\nendmodule\n"; + let doc = doc_of(text); + let outer = at(text, "begin"); + let found = highlights(&doc, outer).expect("a pair"); + assert_eq!(found.len(), 2); + assert_eq!(found[0].range.start.line, 1, "the outer begin"); + assert_eq!(found[1].range.start.line, 5, "and the outer end, not the inner one"); + assert_eq!(found[0].kind, Some(DocumentHighlightKind::TEXT)); + } + + #[test] + fn the_cursor_on_end_highlights_its_own_begin() { + let text = "module m;\n initial begin\n if (x) begin\n y = 1;\n end\n end\nendmodule\n"; + let doc = doc_of(text); + let inner_end = at(text, " end"); + let found = highlights(&doc, inner_end + 4).expect("a pair"); + assert_eq!(found[0].range.start.line, 2, "the inner begin"); + assert_eq!(found[1].range.start.line, 4, "the inner end"); + } + + #[test] + fn the_cursor_at_either_edge_of_the_keyword_still_matches() { + let text = "module m;\n initial begin\n end\nendmodule\n"; + let doc = doc_of(text); + let begin = at(text, "begin"); + for (offset, where_) in [(begin, "first byte"), (begin + 5, "just past the last")] { + let found = highlights(&doc, offset).expect(where_); + assert_eq!(found.len(), 2, "cursor at the {where_}"); + } + assert!(highlights(&doc, begin - 1).is_none(), "the space before is not the keyword"); + } + + #[test] + fn a_multibyte_comment_before_the_keyword_does_not_shift_the_range() { + // The `é` is 2 bytes and 1 UTF-16 unit; a byte-based range would put + // the highlight one column late. + let text = "module m;\n // é\n initial begin\n end\nendmodule\n"; + let doc = doc_of(text); + let found = highlights(&doc, at(text, "begin")).expect("a pair"); + assert_eq!(found[0].range.start.line, 2); + assert_eq!(found[0].range.start.character, 10, "in UTF-16 units"); + assert_eq!(found[0].range.end.character, 15); + } + + #[test] + fn the_cursor_on_an_unmatched_keyword_highlights_nothing() { + // Not "everything that looks like an `end`" — `None` lets the editor + // fall back to its own word highlighting. + let text = "module m;\n initial begin\n x = 1;\nendmodule\n"; + let doc = doc_of(text); + assert!(highlights(&doc, at(text, "begin")).is_none(), "the begin never closed"); + let stray = "module m;\n end\nendmodule\n"; + let doc = doc_of(stray); + assert!(highlights(&doc, at(stray, "end\n")).is_none(), "the end opened nothing"); + } + + #[test] + fn the_cursor_somewhere_else_entirely_highlights_nothing() { + let text = "module m;\n wire a;\nendmodule\n"; + let doc = doc_of(text); + assert!(highlights(&doc, at(text, "wire")).is_none()); + } + + // ------------------------------------------------------------------ + // missing-closer diagnostics, and the gate + // ------------------------------------------------------------------ + + #[test] + fn a_missing_end_warns_at_the_begin_that_lost_it() { + let text = "module m;\n initial begin\n x = 1;\nendmodule\n"; + let doc = doc_of(text); + assert!(!doc.diagnostics.is_empty(), "premise: the parser must have failed"); + let warnings = missing_end_diagnostics(&doc); + assert_eq!(warnings.len(), 1); + assert_eq!(warnings[0].severity, Some(DiagnosticSeverity::WARNING)); + assert_eq!(warnings[0].source.as_deref(), Some("vfmt")); + assert_eq!(warnings[0].range.start.line, 1, "the `initial begin` line"); + assert_eq!(warnings[0].message, "`begin` has no matching `end` — is an `end` missing?"); + } + + #[test] + fn a_missing_join_names_join_and_not_end() { + let text = "module m;\n initial fork\n x = 1;\nendmodule\n"; + let doc = doc_of(text); + let warnings = missing_end_diagnostics(&doc); + assert_eq!(warnings.len(), 1); + assert_eq!(warnings[0].message, "`fork` has no matching `join` — is a `join` missing?"); + } + + #[test] + fn an_orphan_closer_warns_on_itself() { + let text = "module m;\n initial begin\n x = 1;\n end\n end\nendmodule\n"; + let doc = doc_of(text); + assert!(!doc.diagnostics.is_empty(), "premise: the stray end breaks the parse"); + let warnings = missing_end_diagnostics(&doc); + assert!( + warnings.iter().any(|w| w.message == "`end` has no matching `begin`"), + "got {warnings:#?}" + ); + } + + #[test] + fn the_gate_alone_suppresses_the_warnings() { + // The precise claim: the *only* reason a clean-parsing buffer stays + // quiet is the gate. Clearing the parse diagnostics on a buffer the + // matcher does find unbalanced must not change the answer. + let text = "module m;\n initial begin\n x = 1;\nendmodule\n"; + let mut doc = doc_of(text); + assert_eq!(missing_end_diagnostics(&doc).len(), 1, "premise: it warns"); + doc.diagnostics.clear(); + assert!(!analyze(&doc.tokens).unmatched_open.is_empty(), "still unbalanced"); + assert!(missing_end_diagnostics(&doc).is_empty(), "the gate must shut"); + } + + #[test] + fn a_file_that_parses_is_never_told_it_is_unbalanced() { + // Every hazard above, as a whole buffer the parser accepts. + let clean = [ + "module m;\n initial begin\n x = 1;\n end\nendmodule\n", + "class c;\n extern function void f(int a);\n pure virtual function int g();\nendclass\n", + "typedef class C;\nclass C;\n int x;\nendclass\n", + "class c;\n virtual interface bus_if vif;\nendclass\n", + "module m;\n import \"DPI-C\" function void c_init(input int a);\nendmodule\n", + "module m;\n clocking cb @(posedge clk);\n endclocking\n default clocking cb;\nendmodule\n", + "module m;\n a1: assert property (@(posedge clk) a |-> b);\nendmodule\n", + "module m;\n initial begin\n fork\n x = 1;\n join_any\n disable fork;\n end\nendmodule\n", + "class c;\n covergroup cg;\n coverpoint x;\n endgroup\nendclass\n", + "module m;\n initial begin : outer\n begin : inner\n x = 1;\n end : inner\n end : outer\nendmodule\n", + ]; + for text in clean { + let doc = doc_of(text); + assert!(doc.diagnostics.is_empty(), "premise: this must parse — {text}"); + assert!(missing_end_diagnostics(&doc).is_empty(), "warned about {text}"); + // Stronger than the gate: the matcher itself must agree. + let analysis = analyze(&doc.tokens); + assert!(analysis.unmatched_open.is_empty(), "phantom unclosed scope in {text}"); + assert!(analysis.unmatched_close.is_empty(), "phantom stray closer in {text}"); + } + } + + #[test] + fn a_lint_warning_does_not_open_the_gate() { + // The gate reads the *parse* diagnostics. A file that only violates a + // lint rule parses fine and must stay quiet. + let doc = doc_of("module m;\n\twire a;\nendmodule\n"); + assert!(doc.diagnostics.is_empty(), "premise: a tab is not a parse error"); + assert!(missing_end_diagnostics(&doc).is_empty()); + } + + #[test] + fn the_warnings_are_capped() { + // Twenty-five stray `end`s. Flat on purpose: nesting them instead + // would charge the *parser's* recursion, and a test thread's 2 MiB + // stack is not the 8 MiB `docs/features/recursion-limit/README.md` + // requires — the cap under test here is this module's, not that one's. + let mut text = String::from("module m;\n initial begin\n x = 1;\n end\n"); + for _ in 0..25 { + text.push_str(" end\n"); + } + text.push_str("endmodule\n"); + let doc = doc_of(&text); + assert!(!doc.diagnostics.is_empty(), "premise: stray `end`s do not parse"); + assert_eq!(analyze(&doc.tokens).unmatched_close.len(), 25, "the matcher sees them all"); + assert_eq!(missing_end_diagnostics(&doc).len(), MAX_WARNINGS, "the publish is capped"); + } + + #[test] + fn the_published_list_carries_the_pair_warning() { + // The wiring, not the engine: `diagnostics::all` must include these. + let uri = Uri::from_str("file:///rtl/m.sv").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), "module m;\n initial begin\n x = 1;\nendmodule\n".into()); + let published = crate::diagnostics::all(ws.document(&uri).expect("open")); + assert!( + published.iter().any(|d| d.message.contains("has no matching `end`")), + "got {published:#?}" + ); + assert_eq!( + published[0].severity, + Some(DiagnosticSeverity::ERROR), + "the parse error still leads" + ); + } +} diff --git a/crates/vfmt_server/src/server.rs b/crates/vfmt_server/src/server.rs index af0684a..0eda79e 100644 --- a/crates/vfmt_server/src/server.rs +++ b/crates/vfmt_server/src/server.rs @@ -14,22 +14,24 @@ use lsp_types::notification::{ LogMessage, Notification as _, PublishDiagnostics, ShowMessage, }; use lsp_types::request::{ - CodeActionRequest, DocumentSymbolRequest, Formatting, GotoDefinition, HoverRequest, - RangeFormatting, References, Request as _, SemanticTokensFullRequest, WorkspaceSymbolRequest, + CodeActionRequest, DocumentHighlightRequest, DocumentSymbolRequest, Formatting, GotoDefinition, + HoverRequest, RangeFormatting, References, Request as _, SemanticTokensFullRequest, + WorkspaceSymbolRequest, }; use lsp_types::{ CodeActionParams, DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams, DidSaveTextDocumentParams, DocumentFormattingParams, - DocumentRangeFormattingParams, DocumentSymbolParams, DocumentSymbolResponse, - GotoDefinitionParams, GotoDefinitionResponse, HoverParams, LogMessageParams, MessageType, - Position, PublishDiagnosticsParams, ReferenceParams, SemanticTokensParams, - SemanticTokensResult, ShowMessageParams, Uri, WorkspaceSymbolParams, WorkspaceSymbolResponse, + DocumentHighlightParams, DocumentRangeFormattingParams, DocumentSymbolParams, + DocumentSymbolResponse, GotoDefinitionParams, GotoDefinitionResponse, HoverParams, + LogMessageParams, MessageType, Position, PublishDiagnosticsParams, ReferenceParams, + SemanticTokensParams, SemanticTokensResult, ShowMessageParams, Uri, WorkspaceSymbolParams, + WorkspaceSymbolResponse, }; use serde::de::DeserializeOwned; use serde_json::Value; use crate::state::Workspace; -use crate::{code_action, diagnostics, format, hover, nav, symbols, tokens}; +use crate::{code_action, diagnostics, format, hover, nav, pairs, symbols, tokens}; /// Everything the server owns. pub struct Server { @@ -104,6 +106,22 @@ impl Server { .unwrap_or_default(); to_value(locations) }), + // A cursor that is not on half of a matched pair answers `null` + // rather than an empty list: an empty list means "no occurrences + // anywhere", which suppresses the editor's own word highlighting, + // and losing that everywhere except on `begin` would be a poor + // trade for gaining it on `begin`. + DocumentHighlightRequest::METHOD => { + decode(request).and_then(|p: DocumentHighlightParams| { + let at = p.text_document_position_params; + let (uri, position) = (at.text_document.uri, at.position); + let found = self.offset(&uri, position).and_then(|offset| { + let doc = self.workspace.document(&uri)?; + pairs::highlights(doc, offset) + }); + found.map_or(Ok(Value::Null), to_value) + }) + } SemanticTokensFullRequest::METHOD => { decode(request).and_then(|p: SemanticTokensParams| { match self.workspace.document(&p.text_document.uri) { diff --git a/crates/vfmt_server/tests/e2e.rs b/crates/vfmt_server/tests/e2e.rs index c447bd9..5ae1c8f 100644 --- a/crates/vfmt_server/tests/e2e.rs +++ b/crates/vfmt_server/tests/e2e.rs @@ -493,3 +493,106 @@ fn the_binary_serves_a_whole_session_over_stdio() { let _ = std::fs::remove_dir_all(&dir); } + +/// Nested blocks, plus a `begin` that never closes. Both halves of the scope +/// feature have something to say about this buffer: `documentHighlight` pairs +/// the two `end`s that *are* closed, and the missing-closer warning points at +/// the `initial begin` on line 1 rather than at the `endmodule` the parser +/// choked on. +const UNBALANCED: &str = + "module m;\n initial begin\n if (x) begin\n y = 1;\n end\nendmodule\n"; + +#[test] +fn scope_highlights_and_the_missing_end_warning_round_trip_over_the_wire() { + let dir = temp_dir("scopes"); + let file = dir.join("m.sv"); + std::fs::write(&file, UNBALANCED).expect("write"); + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", file.display()); + + let highlight = |id: u32, line: u32, character: u32| { + frame(&format!( + r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/documentHighlight","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":{line},"character":{character}}}}}}}"# + )) + }; + 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(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(UNBALANCED).expect("json") + )), + // The inner `begin` on line 2, which does close. + highlight(2, 2, 11), + // The `end` on line 4, the other half of that same pair. + highlight(3, 4, 4), + // The unclosed `begin` on line 1: no pair, so no answer. + highlight(4, 1, 10), + // Not a keyword at all. + highlight(5, 3, 6), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + + let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); + assert_eq!( + initialize["result"]["capabilities"]["documentHighlightProvider"], + serde_json::json!(true), + "the capability must be advertised" + ); + + let ranges = |id: u32| -> Vec<(u64, u64)> { + let response = messages + .iter() + .find(|m| m["id"] == id) + .unwrap_or_else(|| panic!("no response {id} in {messages:#?}")); + response["result"] + .as_array() + .unwrap_or_else(|| panic!("response {id} is not a list: {response:#?}")) + .iter() + .map(|h| { + ( + h["range"]["start"]["line"].as_u64().expect("line"), + h["range"]["start"]["character"].as_u64().expect("character"), + ) + }) + .collect() + }; + assert_eq!(ranges(2), vec![(2, 11), (4, 4)], "the inner begin pairs with the inner end"); + assert_eq!(ranges(3), vec![(2, 11), (4, 4)], "and the end pairs back"); + + for id in [4, 5] { + let response = messages.iter().find(|m| m["id"] == id).expect("a response"); + assert!(response["error"].is_null(), "declining is not an error: {response:#?}"); + assert!( + response["result"].is_null(), + "must be null so the editor keeps its word highlighting, got {response:#?}" + ); + } + + // The warning rides along with the parse error, in one publish. + let published = messages + .iter() + .find(|m| m["method"] == "textDocument/publishDiagnostics") + .expect("diagnostics"); + let diagnostics = published["params"]["diagnostics"].as_array().expect("an array"); + let warning = diagnostics + .iter() + .find(|d| d["severity"] == 2) + .unwrap_or_else(|| panic!("no warning in {diagnostics:#?}")); + assert_eq!(warning["message"], "`begin` has no matching `end` — is an `end` missing?"); + assert_eq!(warning["range"]["start"]["line"], 1, "the `initial begin`"); + assert_eq!(warning["range"]["start"]["character"], 10); + assert_eq!(warning["source"], "vfmt"); + assert!( + diagnostics.iter().any(|d| d["severity"] == 1), + "the parse error it explains is still there" + ); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/features/editor-scopes/README.md b/docs/features/editor-scopes/README.md new file mode 100644 index 0000000..d519d8b --- /dev/null +++ b/docs/features/editor-scopes/README.md @@ -0,0 +1,327 @@ +# editor-scopes + +## Goal + +Three of the owner's five editor requests are the same question asked three +ways — *which `end` belongs to this `begin`?* — so they get one answer: +`crates/vfmt_server/src/pairs.rs`, a stack matcher over the token stream the +document already caches. This milestone ships the engine and two of its three +consumers: `textDocument/documentHighlight`, so the cursor on a `begin` +highlights its own `end` (real matching, not a text search for the word), and a +**missing-closer warning** that points at the `begin` which lost its `end` +instead of leaving the user with one parse error at the bottom of the file. The +third consumer, the extension's rainbow colouring, is the next milestone and +needs nothing from the engine that is not already here — `Pair::depth` is +computed and tested, it just has no wire to travel on yet. + +## Assumptions + +- **The token stream is the right substrate, not the text and not the AST.** + `Document.tokens` is already cached and already lexed, so a `// end` in a + comment and a `"begin"` in a string literal cannot be mistaken for keywords: + the lexer detached the comment and made the literal one `String` token before + the matcher ever sees the stream. The AST would be *more* precise and is the + wrong tool anyway — a file with a missing `end` is exactly a file with no + usable AST, and that is the file the user needs help with. +- **A macro's body is not in the stream, so the matcher cannot see into it.** + `` `uvm_do_with(...) `` is one `Ident` token however many `begin`s it + expands to, and a `` `define `` line is one `Directive` token. This is a + feature for false positives (a macro can never push or pop) and the reason + the diagnostics are gated (a macro that *does* supply an `end` makes a + perfectly good file look unbalanced). +- **Keyword-level matching means labels are free.** `begin : outer … end : + outer` matches on the two keywords; the label is tokens the matcher skips. + Nothing checks that the two labels agree — that is a linter's job, not this + one's. +- **`checker`/`endchecker` and `config`/`endconfig` are not in the pair set** + because `vlog_parser::token::is_keyword` does not list them: they lex as + plain identifiers, and matching identifiers named `checker` would be a + false-positive machine. `table`/`endtable` *are* keywords but are left out + too — they only occur inside a `primitive`, which is matched, and the plan + did not ask for them. All three are one line each in `RULES` the day the + lexer or the need arrives. +- **A prototype ends at the next `;`.** The flag `extern`, `pure`, `import`, + `export` and `typedef` raise is dropped at the next semicolon, wherever it + falls. A `typedef struct { logic a; } t;` therefore drops the flag at the + member's `;` rather than the declaration's — harmless, because nothing + between the two can open a scope, and far simpler than tracking brace depth. +- **Every guard in `opens_a_scope` is a construct that spells an opener and + opens nothing.** They are listed in *Handshakes* below because getting one + wrong is a phantom unclosed scope; each has a test, and the corpus sweep in + the work log is what says the list is complete rather than merely plausible. +- **Analysis is cheap enough to redo per request.** `analyze` is one pass over + the token vector with a small stack — microseconds on a Verilog file — so + nothing is cached and no invalidation rule can go stale. If a profile ever + says otherwise, the result belongs next to `tokens` in `Document`, computed + once per change like everything else there. + +## Handshakes + +**Consumed from `state.rs`:** `Document.tokens` (the cached lex; empty when the +file does not lex, which the matcher handles by finding nothing), +`Document.diagnostics` (the *parse* diagnostics — the gate reads these, and +only these), and `Document.positions()` for the byte→UTF-16 conversion. No new +field was added to `Document` and nothing in `state.rs` changed. + +**Consumed from `vlog_parser`:** `Token`, `TokenKind`, `TextRange`, and +`token::is_keyword`'s classification. If a keyword is ever added to or removed +from that table, `RULES` and the guards below must be re-checked: the matcher +only ever looks at `TokenKind::Keyword` tokens, so a word that stops being a +keyword silently stops being matched. + +**Promised to `diagnostics.rs`:** `pairs::missing_end_diagnostics(doc)`, called +from `diagnostics::all` between the parse errors and the lint warnings. It +returns an empty list whenever `doc.diagnostics` is empty — callers do not have +to check the gate themselves. + +**Promised to `server.rs` and `main.rs`:** `pairs::highlights(doc, offset) -> +Option>`, and the `documentHighlightProvider` capability +that advertises it. `None` means "decline", which the request loop turns into a +JSON `null` — deliberately not an empty array, because an empty array tells the +editor there are no occurrences anywhere and suppresses its own word +highlighting. + +**Promised to the next milestone:** `analyze(&[Token]) -> ScopeAnalysis`, with +`Pair { open, close, depth }`. `depth` counts every frame open at push time +(the module is 0, a `begin` under an `always` inside it is 1 or 2), which is +what `depth % 6` needs to pick a bracket colour. `Pair::depth` carries an +`#[allow(dead_code)]` until `vfmt/scopePairs` reads it. + +**The guards — the list that must stay correct.** Each is an opener keyword in +a construct with no closer: + +| Written | Why it opens nothing | +|---|---| +| `extern function f(); `, `pure virtual function g();` | prototype, body elsewhere | +| `import "DPI-C" function void c();`, `export "DPI-C" function f;` | foreign, no body here | +| `extern module m (...);` | header only | +| `typedef class C;` | forward declaration | +| `virtual interface bus_if vif;` | a type, not a declaration | +| `interface class IC; … endclass` | the `class` opens; the `interface` must not, or `endclass` finds the wrong frame | +| `module m (interface bus);` | generic interface port | +| `default clocking cb;` | names a block that already exists | +| `assert property (...)`, `cover sequence (...)` | only a *declaration* names what it declares | +| `disable fork;`, `wait fork;` | statements about a fork, not a new one | +| `covergroup cg with function sample(...);` | the covergroup's sample method; `endgroup` closes the lot | + +**Request to the lead (outside this feature's scope):** +`docs/features/vfmt-server/README.md` carries the server's capability list and +`TODO.md` §6 carries the shipped/not-shipped list; both now understate the +server by one capability (`textDocument/documentHighlight`) and one diagnostic +source. Neither file belongs to this feature, so neither was touched. + +## Status / TODO + +- [x] `pairs.rs`: `analyze`, the `RULES` table, the prototype flag, the + `opens_a_scope` guards, and mismatch recovery that does not cascade. +- [x] Unit tests for every hazard in the plan, plus labeled blocks, nested + depth counting, all three `join` flavours, all four `case` flavours. +- [x] `textDocument/documentHighlight` in `server.rs`, capability in + `main.rs`, `every_advertised_capability_is_implemented` updated. +- [x] Missing-closer WARNING diagnostics, gated on the parse having already + failed, capped at 20. +- [x] e2e coverage over the wire (`tests/e2e.rs`). +- [x] Corpus sweep for false positives (found one class; fixed). +- [ ] `vfmt/scopePairs` + the extension's rainbow — next milestone. +- [ ] Not done, deliberately: no check that a labeled `end : outer` agrees with + its `begin : outer`. That is a lint rule with its own fix and its own + opinion, not part of matching. +- [ ] Not done, deliberately: nothing is reported for an unbalanced file that + the parser accepts. See the gate, above and below. + +## Work log + +### 2026-08-24 — M2: the matcher, documentHighlight, missing-closer warnings + +**`pairs.rs`.** One pass over `Document.tokens`, one stack, no recursion (so +nothing here can join the parser in the stack-depth conversation) and no +`unwrap`. `RULES` is a flat table of 21 openers and their closers; `fork` is +the only one with more than one (`join`, `join_any`, `join_none`), and the +first entry is the one the warnings name. + +**Two decisions worth recording.** + +1. *Recovery does not cascade.* A closer searches the stack from the top down + for a frame it can close. If it finds one below the top, the frames above it + are reported as unclosed and it matches; if it finds nothing, it is reported + on its own and the stack is left completely alone. Popping the top blindly + would pair `begin` with `endmodule` and then report the module unclosed — + two wrong answers for one missing keyword, and the rainbow would lose every + colour below the mistake. `a_wrong_closer_does_not_pop_the_frame_it_does_not_match` + and `a_stray_end_matches_nothing_and_disturbs_nothing` pin both halves. +2. *`highlights` returns `Option`, and `None` becomes JSON `null`.* An empty + array is a positive claim — "no occurrences of this anywhere" — and VS Code + honours it by drawing nothing, so answering `[]` for every cursor that is + not on a `begin` would cost the user their ordinary word highlighting + everywhere in the file. Declining hands the editor back its own behaviour. + The cursor is treated as being on a keyword from its first byte to one past + its last, so `|end` and `end|` both match; keyword spans never touch, so the + extra byte cannot claim a neighbour. + +**The gate.** `missing_end_diagnostics` returns nothing at all unless +`doc.diagnostics` is non-empty. The rationale is in the module doc: a +token-stream matcher cannot see `` `ifdef `` arms or macro bodies, so telling a +user their *working* file is unbalanced is a failure mode this feature may not +have. `the_gate_alone_suppresses_the_warnings` proves the gate is load-bearing +rather than decorative — it takes a buffer the matcher genuinely finds +unbalanced, clears the parse diagnostics on it, and asserts the answer goes +empty while `analyze` still reports the unmatched opener. + +**Corpus sweep — the part that changed the code.** A temporary test (added, +run, removed; it is not in the committed file) ran `Document::new` + `analyze` +over all 860 corpus files and reported every file that parses cleanly yet looks +unbalanced to the matcher. First run: **7 false positives out of 840 +clean-parsing files**, every one of them a `function` reported unclosed, and +every one of them the same construct — + +```systemverilog +covergroup rx_fifo_level_cg with function sample(int lvl, bit rst); +``` + +`with function sample(...)` declares the covergroup's sample method in the +covergroup's own header. There is no `endfunction`; the `endgroup` closes +everything. It appears in every UVM coverage class in the corpus (uart, ibex +icache, the whole of `dv_base_reg`) and it is not in the plan's hazard list — +reading the LRM would not have caught it, running the corpus did. One guard +(`"function" => !is_keyword(prev, "with")`) plus +`a_covergroup_sample_method_opens_nothing`. Second run: **840 clean files, +11 062 matched pairs, max depth 13, 0 false positives.** + +**Deviations from the plan, all recorded above and each with a test.** + +- `checker`/`endchecker` **dropped** from the pair set: `vlog_parser` does not + lex them as keywords, so matching them would mean matching identifiers. +- Four guards added beyond the plan's list, three of them for constructs the + plan did not mention: `assert property (` / `cover sequence (` (an assertion + is not a declaration — this one is unavoidable, SV assertions are everywhere), + `disable fork;` / `wait fork;` (idiomatic UVM), `module m (interface bus)` + (generic interface port), and `covergroup … with function` (from the sweep). + Two of them — the generic interface port and `interface class` — cover + constructs `vlog_parser` cannot parse yet, so today they only matter for a + file that is already failing; they cost one condition each and stop the + matcher from adding a second, wrong complaint on top of the parser's. +- The plan's `clocking` fallback ("if this gets hairy, drop clocking") was not + needed: two tokens of lookahead separate `default clocking cb;` from + `clocking cb @(posedge clk);`, and both shapes are tested. +- `the_warnings_are_capped` uses 25 *flat* stray `end`s rather than 41 nested + `begin`s. The nested version overflowed the test thread's stack inside the + **parser** — `docs/features/recursion-limit/README.md` documents that the + parser's 64-level budget needs the 8 MiB main-thread stack and that a spawned + thread must be given one, and a `cargo test` thread gets 2 MiB. Nothing to do + with this module; the flat shape tests the same cap without inviting it. + +**Wiring.** `main.rs`: `document_highlight_provider` advertised, module +declared, capability test extended. `server.rs`: one arm in the request match. +`diagnostics.rs`: one line in `all()`, between the parse errors and the lint +warnings, with the reason in the doc comment. Nothing else in the crate moved, +and no file outside `crates/vfmt_server/` was touched. + +**Tests.** `cargo test -p vfmt_server`: 162 unit (was 130) + 7 e2e (was 6), all +green. Full workspace: 937 passed, 0 failed. `cargo fmt --all` clean, +`cargo clippy --all-targets` clean. The one `#[allow]` in the new code is on +`Pair::depth`, with a comment naming the milestone that removes it. + +## QA log + +### 2026-08-24 — QA round 1 (M2): pairs.rs, documentHighlight, missing-end gate + +Charter items 1–3 and 6 from `editor_features_plan.md` (4/5 are M1/M3, out of +scope this round). Verdict: **PASS**, no blocking findings. + +**Method.** Read `pairs.rs` end to end against the hazard list in the plan and +the guard table in *Handshakes* above; ran the dev's own 162 unit + 7 e2e +tests; then attacked with two throwaway additions to `pairs.rs`'s own +`#[cfg(test)] mod tests` (same crate access as the real code, since +`vfmt_server` is bin-only and has no lib target for an external test to link +against) — run, read, and **removed before this log was written**; nothing +below is in the committed tree. + +**1. Corpus sweep, reproduced independently.** Walked `corpus/` (the same +860-file, gitignored directory the dev used), tokenized each file, and for +every file whose `Document::new` produced zero parse diagnostics, ran +`pairs::analyze` and asserted zero unmatched opens/closes. Result: **860 files +scanned, 840 clean-parsing, 11 062 matched pairs, max depth 13, 0 false +positives** — exact match to the dev's reported numbers in the Work log above. + +**2. Targeted attacks beyond the dev's own test list**, each run as a single +probe printing `(parse_diags_empty, pairs.len(), unmatched_open, unmatched_close)`: + +| Probe | Result | Verdict | +|---|---|---| +| `virtual interface class IC; ... endclass` (plan mentions this combination but the dev's tests only cover `interface class` without `virtual`) | clean matcher: `class..endclass`, no unmatched. Parser itself does not yet accept this construct (`parse_diags_empty=false`) | correct — gate stays consistent with the parser's own limits, and even so the matcher reports nothing false | +| `assert property (...) begin ... end else begin ... end` — pass/fail action blocks, a common real-world idiom the plan/tests don't mention | parses clean, 3 pairs (module + both action blocks), 0 unmatched | correct — confirms the `property`-only guard doesn't leak into ordinary `begin`/`end` inside the assertion statement | +| `covergroup cg with function sample(int lvl) extends base_cg;` (the corpus-found guard, with `extends` appended) | parses clean, 0 unmatched | correct — guard checks only the token immediately before `function`, unaffected by what follows | +| `typedef class C;` forward decl followed by an unrelated `class D` before the real `class C` (package-scoped, three classes total) | parses clean, 3 pairs, 0 unmatched | correct — confirms the prototype flag clears at `;` and doesn't bleed into the next real declaration | +| `default clocking cb @(posedge clk); endclocking` — the body form written with `default` on the *same* line as a real event (not a bare reference) | parses clean, 2 pairs incl. `clocking..endclocking` | correct — the two-token lookahead (`ident` then `;`) correctly tells this apart from `default clocking cb;` | +| `` `define DO_BEGIN begin `` then invoking `` `DO_BEGIN `` in place of a real `begin`, leaving a real `end` orphaned | parser fails (as expected — the file really is broken without macro expansion); matcher: 1 pair (module), `end` correctly reported as the only unmatched closer, `begin` inside the `` `define `` line does **not** register as a keyword | correct — confirms directive lines are opaque in full, body text included, not just macro invocations | +| Same, mirrored (macro supplies the `end`, real `begin` left open) | parser fails; matcher reports `begin` as the sole unmatched opener | correct, symmetric to the above | +| `` `ifdef ``/`` `elsif `` arms with two `begin`s and one `end` (asymmetric arms, the literal hazard the charter names) | parser fails (the raw token stream really is unbalanced, since this server does not evaluate conditions — confirmed at `crates/vlog_parser/src/parser.rs:5482`); matcher correctly reports one `begin` unmatched, matching reality of the raw text | correct — this is not a case of "clean parse but matcher confused"; the file is genuinely malformed as written, both parser and matcher agree | +| `` `ifdef ``/`` `else `` arms where one arm uses `begin`/`end` for two statements and the other is a single bare statement (a very common real idiom) | parser fails — not because of `begin`/`end`, but because the second arm's statement lands illegally at module-item scope once both arms are read literally; matcher itself finds 0 unmatched | correct — the parse failure is a pre-existing, unrelated diagnostic-quality question (bare statement outside a procedural block), not a `pairs.rs` defect; no missing-end warning is produced either way | +| Labeled `begin : a ... end : totally_different_name` | parses clean, matches on keywords alone as designed | correct, matches the documented "labels are not part of the match" assumption | + +No probe produced a file that parses clean yet the matcher calls unbalanced — +the property under test in charter item 3 held in every case tried, not only +the ones the dev's own suite encodes. + +**3. Incidental, non-blocking finding (not a defect in this feature):** +`vlog_parser` does not yet accept `virtual interface class IC; ... endclass` +or `global clocking cb;` (only `default clocking cb;` was checked by the dev). +Both are pre-existing parser gaps, not `pairs.rs` bugs — the matcher behaves +correctly on both regardless, and the diagnostics gate means neither can ever +produce a wrong warning. Filed as an FYI for whoever next touches +`vlog_parser`'s grammar coverage, not a blocker here. (`global clocking` is +the one of the two the dev's guard table doesn't already list — worth a line +if the table is touched again, not worth blocking on.) + +**4. `crates/vfmt_server/src/server.rs:109-121`** (`DocumentHighlightRequest` +handler): `self.offset(&uri, position)` internally calls +`self.workspace.document(&uri)`, and the closure passed to `.and_then` calls +`self.workspace.document(&uri)` a second time. Harmless — `Document::new` +isn't re-run, it's a cheap map lookup, and correctness is unaffected either +way (the second call cannot see a different document than the first inside +one synchronous request handler) — but it is two lookups where one would do. +Non-blocking style nit, left as-is per "you verify, you don't redesign." + +**5. Invariants.** +- `cargo test --workspace`: every crate green, 0 failures (162 unit + 7 e2e in + `vfmt_server` alone, matching the Work log's count exactly). +- `cargo fmt --all -- --check`: clean. +- `cargo clippy --all-targets --workspace`: clean, no warnings. +- `git diff --stat` (working tree vs `HEAD`): only + `crates/vfmt_server/{diagnostics,main,server}.rs` and + `crates/vfmt_server/tests/e2e.rs`, plus the untracked new + `crates/vfmt_server/src/pairs.rs` and `docs/features/editor-scopes/`. No + formatter, `verify.rs`, or `vlog_parser` files touched, confirmed by listing + (`git status`) as well as the stat diff. +- No `unwrap()`/`expect()`/`panic!` in `pairs.rs`, `server.rs`, or + `diagnostics.rs` outside `#[cfg(test)]`, checked directly (grep over the + code above each file's test module). +- The one `#[allow(dead_code)]` (`Pair::depth`) carries an explanatory + comment, satisfying CLAUDE.md's rule. + +**Verdict: PASS.** No blocking findings. Two informational, non-blocking notes +recorded above (a pre-existing `vlog_parser` grammar gap unrelated to this +feature, and a redundant-but-harmless double document lookup in +`server.rs`). + +## Review + +### 2026-08-24 — lead review of M2 (after QA round 1) + +Read `pairs.rs` in full plus the four integration diffs. Approved and +committed. Notes: + +- The non-cascading recovery rule and the parse-error gate are the two + load-bearing decisions; both are stated in comments where they live and + both are pinned by tests that would fail if either were "simplified". + Good. +- The `covergroup ... with function sample` guard coming from a corpus + sweep rather than the plan is exactly why the sweep is worth its cost; + keep sweeping in future rounds. +- `randsequence` (LRM: closed by `endsequence`) is not in the pair set. + Acceptable today — the parser rejects those files anyway, so the gate + never lets a wrong warning out — but worth a line in Assumptions if the + parser ever learns it. +- QA's non-blocking note about the double `workspace.document` lookup in + the `documentHighlight` handler is real but matches the surrounding + handler style; not worth churn.