vfmt-server: begin/end pair engine, documentHighlight, missing-end warnings

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 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-24 02:08:00 -07:00
1 parent de8a307e00
commit f280e51169
6 files changed
+1369 -7

No files matched your search

+5
View File
@@ -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<Diagnostic> {
let mut all = diagnostics(doc);
all.extend(crate::pairs::missing_end_diagnostics(doc));
all.extend(crate::lint::diagnostics(doc));
all
}
+6
View File
@@ -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());
+903
View File
@@ -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<Pair>,
/// Openers that were never closed, in source order.
pub unmatched_open: Vec<Unmatched>,
/// Closers that closed nothing, in source order.
pub unmatched_close: Vec<Unmatched>,
}
/// 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<Frame> = 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<Frame>,
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<Vec<DocumentHighlight>> {
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<Diagnostic> {
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<String> {
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<u32> = 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"
);
}
}
+25 -7
View File
@@ -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) {
+103
View File
@@ -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);
}