Every tracked file that can carry a comment (880 of them) now opens with "Author: Guoliang Chen, a Senior Digital Design Engineer" and closes with "Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com", in the file's own comment syntax. No behaviour change: the diff outside the version bump and changelogs is comment lines only. - tools/stamp_author.py: writes the lines; idempotent, `--check` lists what is missing. Headers go under a shebang and under Markdown front matter. - Left alone: test fixtures, cases and snapshots (byte-exact inputs), JSON and JSONL, logs, images, lockfiles, docs/site/dist (regenerated) and the LICENSE files (already carry the copyright line). - tools/linux_check.sh: --help reads its header from line 3, now that the author line sits under the shebang. - tools/gates.sh green on this tree: 5 545 tests, corpus 814/6 as before. Co-Authored-By: Claude Mythos 5.2 <[email protected]>
918 lines
39 KiB
Rust
918 lines
39 KiB
Rust
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
|
|
|
//! `textDocument/linkedEditingRange`: a closing label edits with the name it
|
|
//! repeats.
|
|
//!
|
|
//! SystemVerilog writes a declaration's name twice whenever it closes with a
|
|
//! label — `module m ... endmodule : m`, `function f ... endfunction : f`,
|
|
//! `begin : blk ... end : blk`. Linked editing is the protocol's answer to
|
|
//! exactly that shape: the server hands back the set of ranges holding the
|
|
//! same name, and the editor applies every keystroke to all of them, so the
|
|
//! two halves cannot drift apart while the user types.
|
|
//!
|
|
//! **The pair is a node, never a text match.** Every construct served below
|
|
//! records both spans on one AST node (`name_span` and `end_label_span`), so
|
|
//! the answer is a lookup and not a search. That is what makes
|
|
//! `begin : x begin : x ... end : x end : x` — four byte-identical names —
|
|
//! resolve to the *syntactic* partner rather than to the nearest one.
|
|
//!
|
|
//! **Two refusals, both `null`.** A closing label is optional in SV, so a bare
|
|
//! `endmodule` has nothing to co-edit and gets no ranges: this feature never
|
|
//! offers to create a label. And a *mismatched* label
|
|
//! (`module m ... endmodule : wrong`) is declined too, because the spec
|
|
//! requires the linked ranges to contain identical text — linking them would
|
|
//! silently rewrite one half into the other on the user's next keystroke,
|
|
//! which is an edit nobody asked for. Rules and the constructs the tree cannot
|
|
//! reach: `docs/features/linked-editing/README.md`.
|
|
|
|
use lsp_types::LinkedEditingRanges;
|
|
use vlog_parser::ast::{
|
|
ClassDecl, ClockingDecl, FunctionDecl, GenBlock, GenElse, GenIf, Item, ItemKind, Module, Stmt,
|
|
StmtKind, TaskDecl,
|
|
};
|
|
use vlog_parser::TextRange;
|
|
|
|
use crate::state::Document;
|
|
|
|
/// What a client may type into a linked range and keep the link.
|
|
///
|
|
/// Sent rather than left to the client's own language word pattern: an SV
|
|
/// identifier admits `$` after its first character (IEEE 1800 §5.6), and an
|
|
/// editor's default word pattern for an unknown language id does not — so a
|
|
/// user typing `foo$bar` would watch the link drop halfway. The pattern is
|
|
/// anchored at both ends and deliberately says nothing about escaped
|
|
/// identifiers, which [`is_simple_identifier`] declines outright.
|
|
const WORD_PATTERN: &str = "^[A-Za-z_][A-Za-z0-9_$]*$";
|
|
|
|
/// The header name and the closing label that repeats it, when the cursor is
|
|
/// on either of them.
|
|
///
|
|
/// `None` — which the handler sends as `null` — for every other position, for
|
|
/// a construct that wrote no closing label, and for the two shapes that must
|
|
/// not be linked: a label that does not match its header, and a name that is
|
|
/// not a plain identifier.
|
|
pub fn linked_editing_ranges(doc: &Document, offset: u32) -> Option<LinkedEditingRanges> {
|
|
let mut pairs = Vec::new();
|
|
items_pairs(&doc.tree.items, &mut pairs);
|
|
let pair = pairs.into_iter().find(|pair| pair.covers(offset))?;
|
|
if !pair.is_linkable(&doc.text) {
|
|
return None;
|
|
}
|
|
let positions = doc.positions();
|
|
Some(LinkedEditingRanges {
|
|
ranges: vec![positions.range(pair.open), positions.range(pair.close)],
|
|
word_pattern: Some(WORD_PATTERN.to_string()),
|
|
})
|
|
}
|
|
|
|
/// One construct's two name occurrences, in source order.
|
|
struct Pair {
|
|
/// The name in the header: `m` of `module m`, `blk` of `begin : blk`.
|
|
open: TextRange,
|
|
/// The same name after the closer's `:`.
|
|
close: TextRange,
|
|
}
|
|
|
|
impl Pair {
|
|
/// Whether the cursor is on either name.
|
|
///
|
|
/// One byte past the end counts, as it does for
|
|
/// [`crate::pairs::highlights`]: an editor leaves the caret after the
|
|
/// character just typed, and a link that switched off at `m|` would be
|
|
/// gone exactly while the user is renaming. Two label occurrences are
|
|
/// always separated by at least a keyword, so the extra byte can never
|
|
/// claim a neighbouring name.
|
|
fn covers(&self, offset: u32) -> bool {
|
|
let touches = |span: TextRange| offset >= span.start && offset <= span.end;
|
|
touches(self.open) || touches(self.close)
|
|
}
|
|
|
|
/// Whether these two ranges may be edited as one.
|
|
///
|
|
/// Both conditions are the protocol's: the ranges must hold identical
|
|
/// text, and what the user types into them must stay describable by
|
|
/// [`WORD_PATTERN`].
|
|
fn is_linkable(&self, text: &str) -> bool {
|
|
let (Some(open), Some(close)) =
|
|
(text.get(self.open.as_range()), text.get(self.close.as_range()))
|
|
else {
|
|
return false;
|
|
};
|
|
open == close && is_simple_identifier(open)
|
|
}
|
|
}
|
|
|
|
/// Whether a name is a plain SV identifier — the charset [`WORD_PATTERN`]
|
|
/// describes.
|
|
///
|
|
/// This is what excludes an escaped identifier (`\my$odd.name `), whose extent
|
|
/// depends on a trailing space that no word pattern can express. Rather than
|
|
/// send a pattern a client could use to corrupt the escape, such a pair is
|
|
/// simply not offered.
|
|
fn is_simple_identifier(name: &str) -> bool {
|
|
let mut chars = name.chars();
|
|
match chars.next() {
|
|
Some(first) if first == '_' || first.is_ascii_alphabetic() => {}
|
|
_ => return false,
|
|
}
|
|
chars.all(|c| c == '_' || c == '$' || c.is_ascii_alphanumeric())
|
|
}
|
|
|
|
/// Push a pair when the construct wrote both halves. An absent closing label
|
|
/// is the common case and means there is nothing to link.
|
|
fn push(open: Option<TextRange>, close: Option<TextRange>, out: &mut Vec<Pair>) {
|
|
if let (Some(open), Some(close)) = (open, close) {
|
|
if !open.is_empty() && !close.is_empty() {
|
|
out.push(Pair { open, close });
|
|
}
|
|
}
|
|
}
|
|
|
|
fn items_pairs(items: &[Item], out: &mut Vec<Pair>) {
|
|
for item in items {
|
|
item_pairs(item, out);
|
|
}
|
|
}
|
|
|
|
fn item_pairs(item: &Item, out: &mut Vec<Pair>) {
|
|
match &item.kind {
|
|
ItemKind::Module(m) => module_pairs(m, out),
|
|
ItemKind::Package { name_span, end_label_span, items, .. } => {
|
|
push(Some(*name_span), *end_label_span, out);
|
|
items_pairs(items, out);
|
|
}
|
|
ItemKind::Class(c) => class_pairs(c, out),
|
|
ItemKind::Function(f) => function_pairs(f, out),
|
|
ItemKind::Task(t) => task_pairs(t, out),
|
|
ItemKind::Clocking(c) => clocking_pairs(c, out),
|
|
ItemKind::GenerateRegion { items, .. } => items_pairs(items, out),
|
|
ItemKind::GenBlock(b) => items_pairs(&b.items, out),
|
|
ItemKind::GenIf(g) => gen_if_pairs(g, out),
|
|
ItemKind::GenFor(g) => gen_block_pairs(&g.body, out),
|
|
ItemKind::GenCase(g) => {
|
|
for arm in &g.items {
|
|
gen_block_pairs(&arm.body, out);
|
|
}
|
|
}
|
|
ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => {
|
|
stmt_pairs(stmt, out);
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
fn module_pairs(m: &Module, out: &mut Vec<Pair>) {
|
|
push(Some(m.name_span), m.end_label_span, out);
|
|
items_pairs(&m.items, out);
|
|
}
|
|
|
|
fn class_pairs(c: &ClassDecl, out: &mut Vec<Pair>) {
|
|
push(Some(c.name_span), c.end_label_span, out);
|
|
items_pairs(&c.items, out);
|
|
}
|
|
|
|
fn function_pairs(f: &FunctionDecl, out: &mut Vec<Pair>) {
|
|
push(Some(f.name_span), f.end_label_span, out);
|
|
stmts_pairs(&f.stmts, out);
|
|
}
|
|
|
|
fn task_pairs(t: &TaskDecl, out: &mut Vec<Pair>) {
|
|
push(Some(t.name_span), t.end_label_span, out);
|
|
stmts_pairs(&t.stmts, out);
|
|
}
|
|
|
|
/// `clocking cb @(posedge clk); ... endclocking : cb`. The anonymous
|
|
/// `default clocking @(...)` form has no name at all, so it pairs nothing.
|
|
fn clocking_pairs(c: &ClockingDecl, out: &mut Vec<Pair>) {
|
|
push(c.name.as_ref().map(|n| n.span), c.end_label_span, out);
|
|
}
|
|
|
|
fn gen_if_pairs(gen_if: &GenIf, out: &mut Vec<Pair>) {
|
|
gen_block_pairs(&gen_if.then, out);
|
|
let mut els = gen_if.els.as_deref();
|
|
while let Some(branch) = els {
|
|
match branch {
|
|
GenElse::If(_, nested) => {
|
|
gen_block_pairs(&nested.then, out);
|
|
els = nested.els.as_deref();
|
|
}
|
|
GenElse::Block(block) => {
|
|
gen_block_pairs(block, out);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn gen_block_pairs(block: &GenBlock, out: &mut Vec<Pair>) {
|
|
push(block.label_span, block.end_label_span, out);
|
|
items_pairs(&block.items, out);
|
|
}
|
|
|
|
fn stmts_pairs(list: &[Stmt], out: &mut Vec<Pair>) {
|
|
for stmt in list {
|
|
stmt_pairs(stmt, out);
|
|
}
|
|
}
|
|
|
|
/// The statement half of the walk.
|
|
///
|
|
/// The recursion is bounded by the parser's own nesting limit
|
|
/// (`docs/features/recursion-limit/README.md`): a tree this walks is a tree it
|
|
/// built.
|
|
fn stmt_pairs(stmt: &Stmt, out: &mut Vec<Pair>) {
|
|
match &stmt.kind {
|
|
StmtKind::Block { label_span, end_label_span, stmts, .. }
|
|
| StmtKind::ForkJoin { label_span, end_label_span, stmts, .. } => {
|
|
push(*label_span, *end_label_span, out);
|
|
stmts_pairs(stmts, out);
|
|
}
|
|
// `blk : begin ... end : blk` (IEEE 1800 §9.3.5): the name is written
|
|
// before the keyword, so the parser puts it on this node and leaves
|
|
// the block's own label empty. Still one syntactic pair — the LRM
|
|
// requires the end label to name this statement — but only when the
|
|
// block wrote no label of its own. Writing both is illegal, and the
|
|
// block's own pair has already been pushed by the recursion below.
|
|
StmtKind::Labeled { name_span, stmt: inner, .. } => {
|
|
if let Some(close) = prefix_labelled_end(inner) {
|
|
push(Some(*name_span), Some(close), out);
|
|
}
|
|
stmt_pairs(inner, out);
|
|
}
|
|
StmtKind::If { then, els, .. } => {
|
|
stmt_pairs(then, out);
|
|
if let Some(els) = els.as_deref() {
|
|
stmt_pairs(els, out);
|
|
}
|
|
}
|
|
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
|
|
for item in items {
|
|
stmt_pairs(&item.stmt, out);
|
|
}
|
|
}
|
|
StmtKind::For { body, .. }
|
|
| StmtKind::While { body, .. }
|
|
| StmtKind::DoWhile { body, .. }
|
|
| StmtKind::Repeat { body, .. }
|
|
| StmtKind::Forever { body }
|
|
| StmtKind::Foreach { body, .. } => stmt_pairs(body, out),
|
|
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
|
|
stmt_pairs(inner, out)
|
|
}
|
|
StmtKind::Assert { then, els, .. } => {
|
|
if let Some(then) = then.as_deref() {
|
|
stmt_pairs(then, out);
|
|
}
|
|
if let Some(els) = els.as_deref() {
|
|
stmt_pairs(els, out);
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
/// The closing label of a block named *before* its keyword, or `None` when the
|
|
/// statement is not such a block.
|
|
fn prefix_labelled_end(stmt: &Stmt) -> Option<TextRange> {
|
|
match &stmt.kind {
|
|
StmtKind::Block { label: None, end_label_span, .. }
|
|
| StmtKind::ForkJoin { label: None, end_label_span, .. } => *end_label_span,
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use vlog_semantic::WorkspaceIndex;
|
|
|
|
fn doc_of(text: &str) -> Document {
|
|
Document::new(None, text.to_string(), &WorkspaceIndex::default())
|
|
}
|
|
|
|
/// The byte offset of `needle`'s first occurrence.
|
|
fn at(text: &str, needle: &str) -> u32 {
|
|
text.find(needle).expect("needle present") as u32
|
|
}
|
|
|
|
/// The byte offset just past `prefix` — how a fixture points at a name
|
|
/// whose own spelling occurs earlier in the text (`m` of `module m`).
|
|
fn at_after(text: &str, prefix: &str) -> u32 {
|
|
at(text, prefix) + prefix.len() as u32
|
|
}
|
|
|
|
/// The byte offset just past the *last* `prefix`. Every fixture below
|
|
/// writes its closing label as the file's last `": "`, so this is where
|
|
/// that label starts.
|
|
fn at_last_after(text: &str, prefix: &str) -> u32 {
|
|
text.rfind(prefix).expect("needle present") as u32 + prefix.len() as u32
|
|
}
|
|
|
|
/// The answer's ranges as `(line, start character, end character)`, which
|
|
/// is enough to say which occurrence each one is.
|
|
fn linked(text: &str, offset: u32) -> Option<Vec<(u32, u32, u32)>> {
|
|
let doc = doc_of(text);
|
|
let answer = linked_editing_ranges(&doc, offset)?;
|
|
assert_eq!(
|
|
answer.word_pattern.as_deref(),
|
|
Some(WORD_PATTERN),
|
|
"every answer carries the SV word pattern"
|
|
);
|
|
Some(
|
|
answer
|
|
.ranges
|
|
.iter()
|
|
.map(|r| (r.start.line, r.start.character, r.end.character))
|
|
.collect(),
|
|
)
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// every construct that ships
|
|
// ------------------------------------------------------------------
|
|
|
|
#[test]
|
|
fn every_labeled_construct_links_its_two_names() {
|
|
// Each fixture writes its name twice and nowhere else, and its closing
|
|
// label is the last `": "` in the text.
|
|
let cases = [
|
|
("module m;\nendmodule : m\n", "module ", "module"),
|
|
("macromodule m;\nendmodule : m\n", "macromodule ", "macromodule"),
|
|
("interface bus_if;\nendinterface : bus_if\n", "interface ", "interface"),
|
|
("package p;\nendpackage : p\n", "package ", "package"),
|
|
("class c;\nendclass : c\n", "class ", "class"),
|
|
("module m;\n function f;\n endfunction : f\nendmodule\n", "function ", "function"),
|
|
("module m;\n task t;\n endtask : t\nendmodule\n", "task ", "task"),
|
|
(
|
|
"module m;\n initial begin : blk\n end : blk\nendmodule\n",
|
|
"begin : ",
|
|
"named begin",
|
|
),
|
|
("module m;\n initial fork : frk\n join : frk\nendmodule\n", "fork : ", "named fork"),
|
|
(
|
|
concat!(
|
|
"module m;\n",
|
|
" generate\n",
|
|
" for (genvar i = 0; i < 2; i++) begin : g\n",
|
|
" wire w;\n",
|
|
" end : g\n",
|
|
" endgenerate\n",
|
|
"endmodule\n",
|
|
),
|
|
"begin : ",
|
|
"generate block",
|
|
),
|
|
(
|
|
"interface i;\n clocking cb @(posedge clk);\n endclocking : cb\nendinterface\n",
|
|
"clocking ",
|
|
"clocking",
|
|
),
|
|
(
|
|
"module m;\n initial pre : begin\n end : pre\nendmodule\n",
|
|
"initial ",
|
|
"prefix-labelled begin",
|
|
),
|
|
];
|
|
for (text, header, what) in cases {
|
|
let from_label = linked(text, at_last_after(text, ": "))
|
|
.unwrap_or_else(|| panic!("{what}: the closing label answered nothing at all"));
|
|
assert_eq!(from_label.len(), 2, "{what}: exactly two ranges");
|
|
let from_header = linked(text, at_after(text, header))
|
|
.unwrap_or_else(|| panic!("{what}: the header name answered nothing"));
|
|
assert_eq!(from_label, from_header, "{what}: both directions answer the same pair");
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// where the cursor is
|
|
// ------------------------------------------------------------------
|
|
|
|
#[test]
|
|
fn the_cursor_may_sit_anywhere_in_either_name() {
|
|
let text = "module wide;\nendmodule : wide\n";
|
|
let header = at_after(text, "module ");
|
|
let label = at_last_after(text, ": ");
|
|
let expected = linked(text, header).expect("the header answers");
|
|
assert_eq!(expected, vec![(0, 7, 11), (1, 12, 16)]);
|
|
for (offset, what) in [
|
|
(header, "header start"),
|
|
(header + 2, "header middle"),
|
|
(header + 4, "header end, one past the last byte"),
|
|
(label, "label start"),
|
|
(label + 2, "label middle"),
|
|
(label + 4, "label end, one past the last byte"),
|
|
] {
|
|
assert_eq!(linked(text, offset).as_ref(), Some(&expected), "{what}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_position_beside_the_names_answers_nothing() {
|
|
let text = "module m;\nendmodule : m\n";
|
|
assert!(linked(text, 0).is_none(), "the `module` keyword itself");
|
|
assert!(linked(text, at(text, " m;")).is_none(), "the space before the name");
|
|
assert!(linked(text, at(text, ";") + 1).is_none(), "past the semicolon");
|
|
assert!(linked(text, at(text, "endmodule")).is_none(), "the closing keyword");
|
|
}
|
|
|
|
#[test]
|
|
fn a_position_past_the_end_of_the_file_answers_nothing() {
|
|
let text = "module m;\nendmodule : m\n";
|
|
assert!(linked(text, text.len() as u32).is_none());
|
|
assert!(linked(text, text.len() as u32 + 1_000).is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn an_empty_buffer_answers_nothing() {
|
|
assert!(linked("", 0).is_none());
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// the two refusals
|
|
// ------------------------------------------------------------------
|
|
|
|
#[test]
|
|
fn an_unlabeled_closer_links_nothing() {
|
|
// The label is optional in SV, and its absence is not an invitation to
|
|
// create one: there is no second range, so there is no answer.
|
|
for (text, header) in [
|
|
("module m;\nendmodule\n", "module "),
|
|
("package p;\nendpackage\n", "package "),
|
|
("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 initial begin : blk\n end\nendmodule\n", "begin : "),
|
|
] {
|
|
assert!(linked(text, at_after(text, header)).is_none(), "{text:?} must link nothing");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_mismatched_label_links_nothing() {
|
|
// Broken code. Linking the two would rewrite one half into the other
|
|
// on the next keystroke — an edit the user never asked for — and the
|
|
// spec requires the ranges to hold identical text anyway.
|
|
let text = "module m;\nendmodule : wrong\n";
|
|
assert!(linked(text, at_after(text, "module ")).is_none(), "from the header");
|
|
assert!(linked(text, at(text, "wrong")).is_none(), "and from the label");
|
|
}
|
|
|
|
#[test]
|
|
fn a_label_differing_only_in_case_links_nothing() {
|
|
let text = "module Data;\nendmodule : data\n";
|
|
assert!(linked(text, at(text, "Data")).is_none());
|
|
assert!(linked(text, at(text, "data")).is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn an_escaped_identifier_links_nothing() {
|
|
// `\odd.name ` is an identifier whose extent depends on a trailing
|
|
// space, which no word pattern can describe. Both halves matching does
|
|
// not make it safe to hand a client.
|
|
let text = "module \\odd.name ;\nendmodule : \\odd.name \n";
|
|
let doc = doc_of(text);
|
|
let mut pairs = Vec::new();
|
|
items_pairs(&doc.tree.items, &mut pairs);
|
|
assert_eq!(pairs.len(), 1, "premise: the tree really did record the pair");
|
|
assert!(linked(text, at(text, "\\odd.name")).is_none(), "from the header");
|
|
assert!(
|
|
linked(text, text.rfind("\\odd.name").expect("label") as u32).is_none(),
|
|
"and back"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn is_simple_identifier_accepts_exactly_the_word_pattern() {
|
|
for good in ["m", "_x", "a1", "foo$bar", "A_b$9", "_"] {
|
|
assert!(is_simple_identifier(good), "{good} is a plain SV identifier");
|
|
}
|
|
for bad in ["", "1a", "$x", "\\odd.name", "a b", "a.b", "é"] {
|
|
assert!(!is_simple_identifier(bad), "{bad:?} is not");
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// nesting — the pair must be the syntactic one
|
|
// ------------------------------------------------------------------
|
|
|
|
#[test]
|
|
fn nested_blocks_answer_their_own_pair() {
|
|
let text = concat!(
|
|
"module m;\n",
|
|
" initial begin : outer\n",
|
|
" begin : inner\n",
|
|
" x = 1;\n",
|
|
" end : inner\n",
|
|
" end : outer\n",
|
|
"endmodule\n",
|
|
);
|
|
let outer = linked(text, at(text, "outer")).expect("the outer header answers");
|
|
assert_eq!(outer, vec![(1, 18, 23), (5, 8, 13)], "line 1 header, line 5 label");
|
|
let inner = linked(text, at(text, "inner")).expect("the inner header answers");
|
|
assert_eq!(inner, vec![(2, 12, 17), (4, 10, 15)], "line 2 header, line 4 label");
|
|
}
|
|
|
|
#[test]
|
|
fn identical_names_at_different_nesting_pair_syntactically() {
|
|
// The evil fixture: four byte-identical names, two pairs. A
|
|
// nearest-same-text rule would pair the outer header with the *inner*
|
|
// label, because that one is nearer. The pair comes off the AST node,
|
|
// so it cannot.
|
|
let text = concat!(
|
|
"module m;\n",
|
|
" initial begin : x\n",
|
|
" begin : x\n",
|
|
" y = 1;\n",
|
|
" end : x\n",
|
|
" end : x\n",
|
|
"endmodule\n",
|
|
);
|
|
let outer_header = at_after(text, "begin : ");
|
|
let inner_header =
|
|
text.match_indices("begin : ").nth(1).expect("the inner block").0 as u32 + 8;
|
|
let outer = linked(text, outer_header).expect("the outer header answers");
|
|
assert_eq!(outer, vec![(1, 18, 19), (5, 8, 9)], "outer header pairs with the OUTER end");
|
|
let inner = linked(text, inner_header).expect("the inner header answers");
|
|
assert_eq!(inner, vec![(2, 12, 13), (4, 10, 11)], "inner header pairs with the INNER end");
|
|
assert_ne!(outer, inner);
|
|
// And from each closing label, back to the same two pairs.
|
|
let inner_label = text.match_indices("end : ").next().expect("the inner end").0 as u32 + 6;
|
|
let outer_label = at_last_after(text, "end : ");
|
|
assert_eq!(linked(text, inner_label), Some(inner));
|
|
assert_eq!(linked(text, outer_label), Some(outer));
|
|
}
|
|
|
|
#[test]
|
|
fn a_module_and_the_function_inside_it_are_separate_pairs() {
|
|
// The function is deliberately named `m` too.
|
|
let text = "module m;\n function m;\n endfunction : m\nendmodule : m\n";
|
|
let module = linked(text, at_after(text, "module ")).expect("the module header answers");
|
|
assert_eq!(module, vec![(0, 7, 8), (3, 12, 13)], "module header, endmodule label");
|
|
let function =
|
|
linked(text, at_after(text, "function ")).expect("the function header answers");
|
|
assert_eq!(function, vec![(1, 11, 12), (2, 16, 17)], "function header, endfunction label");
|
|
assert_ne!(module, function);
|
|
}
|
|
|
|
#[test]
|
|
fn a_class_method_pairs_inside_its_class() {
|
|
let text = "class c;\n function void f();\n endfunction : f\nendclass : c\n";
|
|
let class = linked(text, at_after(text, "class ")).expect("the class answers");
|
|
assert_eq!(class, vec![(0, 6, 7), (3, 11, 12)]);
|
|
let method = linked(text, at(text, "f()")).expect("the method answers");
|
|
assert_eq!(method, vec![(1, 16, 17), (2, 16, 17)]);
|
|
}
|
|
|
|
#[test]
|
|
fn a_named_block_inside_a_generate_for_pairs() {
|
|
let text = concat!(
|
|
"module m;\n",
|
|
" generate\n",
|
|
" for (genvar i = 0; i < 2; i++) begin : g\n",
|
|
" initial begin : inner\n",
|
|
" end : inner\n",
|
|
" end : g\n",
|
|
" endgenerate\n",
|
|
"endmodule\n",
|
|
);
|
|
let gen = linked(text, at(text, "g\n")).expect("the generate label answers");
|
|
assert_eq!(gen, vec![(2, 43, 44), (5, 10, 11)]);
|
|
let inner = linked(text, at(text, "inner")).expect("the inner block answers");
|
|
assert_eq!(inner, vec![(3, 22, 27), (4, 12, 17)]);
|
|
assert_ne!(gen, inner);
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// UTF-16 positions
|
|
// ------------------------------------------------------------------
|
|
|
|
#[test]
|
|
fn a_multibyte_comment_before_the_name_does_not_shift_it() {
|
|
// SV identifiers are ASCII, but everything around them need not be.
|
|
// The characters are counted in UTF-16 units, so `é` (2 bytes, 1 unit)
|
|
// and `🎉` (4 bytes, 2 units) must not move the name's column.
|
|
let text = "// café 🎉\nmodule m;\nendmodule : m\n";
|
|
let ranges = linked(text, at_after(text, "module ")).expect("the header answers");
|
|
assert_eq!(ranges, vec![(1, 7, 8), (2, 12, 13)]);
|
|
}
|
|
|
|
#[test]
|
|
fn a_multibyte_comment_on_the_same_line_keeps_the_columns_honest() {
|
|
let text = "module m; // 🎉 party\nendmodule : m // café\n";
|
|
let ranges = linked(text, at_last_after(text, ": ")).expect("the label answers");
|
|
assert_eq!(ranges, vec![(0, 7, 8), (1, 12, 13)]);
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// buffers that do not parse
|
|
// ------------------------------------------------------------------
|
|
|
|
#[test]
|
|
fn a_buffer_that_does_not_lex_answers_nothing() {
|
|
let text = "module m;\n wire a; /* unterminated\n";
|
|
let doc = doc_of(text);
|
|
assert!(doc.tokens.is_empty(), "premise: the lexer gave up");
|
|
assert!(linked_editing_ranges(&doc, at_after(text, "module ")).is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn a_half_typed_construct_answers_nothing_rather_than_guessing() {
|
|
let text = "module m;\n initial begin : blk\nendmodule\n";
|
|
assert!(linked(text, at(text, "blk")).is_none(), "no closing label was written");
|
|
}
|
|
|
|
#[test]
|
|
fn a_pair_written_after_a_broken_item_still_answers() {
|
|
// Error recovery keeps the items it could parse, so a mistake early in
|
|
// the file must not un-link everything below it.
|
|
let text = "module a;\n @@@ ;\nendmodule\nmodule b;\nendmodule : b\n";
|
|
let ranges = linked(text, at_after(text, "module b")).expect("the second module answers");
|
|
assert_eq!(ranges.len(), 2);
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// the answer's own shape
|
|
// ------------------------------------------------------------------
|
|
|
|
#[test]
|
|
fn the_two_ranges_hold_identical_text_and_never_overlap() {
|
|
let text = "module top;\n initial begin : blk\n end : blk\nendmodule : top\n";
|
|
let doc = doc_of(text);
|
|
for offset in [at(text, "top") + 1, at(text, "blk") + 1] {
|
|
let answer = linked_editing_ranges(&doc, offset).expect("a pair");
|
|
assert_eq!(answer.ranges.len(), 2);
|
|
let (first, second) = (answer.ranges[0], answer.ranges[1]);
|
|
assert!(
|
|
(first.end.line, first.end.character) < (second.start.line, second.start.character),
|
|
"the header comes first and the two do not overlap: {answer:?}"
|
|
);
|
|
assert_eq!(
|
|
first.end.character - first.start.character,
|
|
second.end.character - second.start.character,
|
|
"identical length"
|
|
);
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// QA (2026-08-26) — the prefix-label gate, and the ranges' exact bytes
|
|
// ------------------------------------------------------------------
|
|
|
|
/// Every offset in `0..=text.len()` answers without panicking, and every
|
|
/// `Some` answer holds two identical-text, non-overlapping ranges. The
|
|
/// blanket check the targeted tests below narrow in on one fixture at a
|
|
/// time — kept here because a tolerant-parser fixture is exactly the kind
|
|
/// of input where a hand-picked offset can miss what a sweep finds.
|
|
fn assert_total_and_sane(text: &str) {
|
|
let doc = doc_of(text);
|
|
for offset in 0..=text.len() as u32 {
|
|
let Some(answer) = linked_editing_ranges(&doc, offset) else { continue };
|
|
assert_eq!(answer.ranges.len(), 2, "{text:?} at {offset}: {answer:?}");
|
|
assert_eq!(
|
|
answer.word_pattern.as_deref(),
|
|
Some(WORD_PATTERN),
|
|
"{text:?} at {offset}: word pattern missing"
|
|
);
|
|
let (a, b) = (answer.ranges[0], answer.ranges[1]);
|
|
let (before, after) =
|
|
if (a.start.line, a.start.character) <= (b.start.line, b.start.character) {
|
|
(a, b)
|
|
} else {
|
|
(b, a)
|
|
};
|
|
assert!(
|
|
(before.end.line, before.end.character)
|
|
<= (after.start.line, after.start.character),
|
|
"{text:?} at {offset}: ranges overlap: {answer:?}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_block_named_both_ways_answers_only_the_blocks_own_pair() {
|
|
// `x : begin : y ... end : y` is illegal SV (IEEE 1800 §9.3.5: a block
|
|
// is named one way or the other), but the tolerant parser accepts it
|
|
// — the block wrote its own label, so `Labeled`'s prefix-label gate
|
|
// (`prefix_labelled_end`, only fires when the block wrote no label of
|
|
// its own) must stay silent and the block's own (y, y) pair, not a
|
|
// fabricated (x, y), must be what answers.
|
|
let text = "module m;\n initial x : begin : y\n z = 1;\n end : y\nendmodule\n";
|
|
assert_total_and_sane(text);
|
|
let y_pair = linked(text, at(text, "y")).expect("the block's own label pairs");
|
|
assert_eq!(y_pair.len(), 2);
|
|
assert_eq!(linked(text, text.rfind('y').expect("closing y") as u32), Some(y_pair));
|
|
// `x` is not part of any pair: the prefix label was correctly not
|
|
// linked to anything.
|
|
assert!(linked(text, at(text, "x")).is_none(), "the unused prefix label links nothing");
|
|
}
|
|
|
|
#[test]
|
|
fn a_prefix_label_whose_only_close_belongs_to_an_unnamed_block_is_mismatched() {
|
|
// `x : begin ... end : y` — the block wrote no label of its own, so
|
|
// the prefix-label gate does fire and pushes (x, y). The two names
|
|
// differ, so this must still answer null, the same as any other
|
|
// mismatch — the gate firing is not itself a promise of a match.
|
|
let text = "module m;\n initial x : begin\n z = 1;\n end : y\nendmodule\n";
|
|
assert_total_and_sane(text);
|
|
assert!(linked(text, at(text, "x")).is_none(), "mismatched prefix pair: from x");
|
|
assert!(linked(text, at(text, "y")).is_none(), "mismatched prefix pair: from y");
|
|
}
|
|
|
|
#[test]
|
|
fn a_stray_second_end_label_after_the_block_already_closed_is_inert() {
|
|
// Two `end : x` for one `begin : x`. The first one closes the block;
|
|
// the second is leftover tokens the item-level recovery has to make
|
|
// sense of on its own. Whatever it becomes, it must not create a
|
|
// second, wrong pairing, and it must not make the walk panic.
|
|
let text = "module m;\n initial begin : x\n z = 1;\n end : x\n end : x\nendmodule\n";
|
|
assert_total_and_sane(text);
|
|
let doc = doc_of(text);
|
|
let mut pairs = Vec::new();
|
|
items_pairs(&doc.tree.items, &mut pairs);
|
|
assert_eq!(pairs.len(), 1, "the stray `end : x` must not mint a second pair");
|
|
// The pair that does exist closes on the FIRST `end : x`, not the
|
|
// second — the leftover tokens answer nothing at all.
|
|
let first_end = text.find("end : x").expect("first end");
|
|
let second_end = text.rfind("end : x").expect("second end");
|
|
assert_ne!(first_end, second_end);
|
|
assert!(
|
|
linked(text, second_end as u32 + 6).is_none(),
|
|
"the leftover end : x links nothing"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn broken_and_unclosed_labeled_constructs_never_panic() {
|
|
for text in [
|
|
"module m;\n initial begin : blk\n z = 1;\nendmodule\n", // `end` missing
|
|
"module m;\n initial begin : blk\n z = 1;\n", // no closer at all, EOF
|
|
"module m;\n initial begin : \n end : \nendmodule\n", // label written, no name
|
|
"module m;\n initial begin :\n end\nendmodule\n", // colon, no name, no close label
|
|
] {
|
|
assert_total_and_sane(text);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn adjacent_closing_labels_never_bleed_into_each_other() {
|
|
// `endfunction : f` immediately followed by `endmodule : m` on the
|
|
// next line: the "name spans never touch" claim, checked at the exact
|
|
// boundary a lexer could in principle blur.
|
|
let text = "module m;\n function f;\n endfunction : f\nendmodule : m\n";
|
|
assert_total_and_sane(text);
|
|
let f = linked(text, at(text, "f;")).expect("the function pairs");
|
|
let m = linked(text, at_after(text, "module ")).expect("the module pairs");
|
|
assert_ne!(f, m);
|
|
}
|
|
|
|
/// The ranges cover exactly the identifier's bytes — never the `:`, never
|
|
/// the surrounding whitespace or a comment written between them. An
|
|
/// off-by-one here would let a client's keystroke land on the colon.
|
|
#[test]
|
|
fn ranges_cover_exactly_the_identifier_never_the_colon_or_comment() {
|
|
let cases: [(&str, &str, &str); 3] = [
|
|
("module m;\nendmodule : /*c*/ m\n", "module ", "m"),
|
|
("module m;\n initial begin:x\n end:x\nendmodule\n", "begin:", "x"),
|
|
("module m;\n initial begin :\n x\n end :\n x\nendmodule\n", "begin :\n ", "x"),
|
|
];
|
|
for (text, header_prefix, want) in cases {
|
|
let doc = doc_of(text);
|
|
let answer = linked_editing_ranges(&doc, at_after(text, header_prefix))
|
|
.unwrap_or_else(|| panic!("{text:?}: the header answers"));
|
|
let positions = doc.positions();
|
|
// Decode each `Range` back to a byte span via the same
|
|
// `Positions::offset` the server itself uses to turn a client
|
|
// position into an offset, and check it covers exactly the name
|
|
// — not the colon, not a space, not the comment beside it.
|
|
for range in &answer.ranges {
|
|
let start = positions.offset(range.start) as usize;
|
|
let end = positions.offset(range.end) as usize;
|
|
assert_eq!(&text[start..end], want, "{text:?}: range {range:?}");
|
|
}
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// corpus sweep — real RTL, every offset, machine-checked invariants
|
|
// ------------------------------------------------------------------
|
|
|
|
/// Every offset of a handful of real corpus files that write closing
|
|
/// labels: totality (no panic), and every `Some` answer's two ranges hold
|
|
/// identical text and do not overlap. Skipped when `corpus/` is not
|
|
/// checked out, like every other corpus test in this crate.
|
|
#[test]
|
|
fn a_corpus_sweep_of_labeled_constructs_is_total_and_sane() {
|
|
let corpus = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
|
if !corpus.is_dir() {
|
|
eprintln!("corpus/ not checked out — skipping");
|
|
return;
|
|
}
|
|
let files = [
|
|
"common_cells/src/lzc.sv",
|
|
"common_cells/src/rr_arb_tree.sv",
|
|
"common_cells/src/popcount.sv",
|
|
"common_cells/src/cdc_reset_ctrlr.sv",
|
|
"common_cells/src/deprecated/rrarbiter.sv",
|
|
"common_cells/src/deprecated/prioarbiter.sv",
|
|
"common_cells/src/stream_fifo_optimal_wrap.sv",
|
|
"common_cells/src/stream_throttle.sv",
|
|
"ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_vseq.sv",
|
|
"ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_monitor.sv",
|
|
"opentitan/hw/ip/uart/dv/env/seq_lib/uart_base_vseq.sv",
|
|
];
|
|
let mut files_checked = 0;
|
|
let mut pairs_found = 0;
|
|
for name in files {
|
|
let path = corpus.join(name);
|
|
let Ok(text) = std::fs::read_to_string(&path) else {
|
|
eprintln!("{} not checked out — skipping", path.display());
|
|
continue;
|
|
};
|
|
assert!(
|
|
text.contains("end") && text.contains(':'),
|
|
"{}: premise, this file should write a closing label",
|
|
path.display()
|
|
);
|
|
let doc = doc_of(&text);
|
|
let mut file_pairs = Vec::new();
|
|
items_pairs(&doc.tree.items, &mut file_pairs);
|
|
pairs_found += file_pairs.len();
|
|
let positions = doc.positions();
|
|
for offset in 0..=text.len() as u32 {
|
|
let Some(answer) = linked_editing_ranges(&doc, offset) else { continue };
|
|
assert_eq!(answer.ranges.len(), 2, "{}: {answer:?}", path.display());
|
|
let (a, b) = (answer.ranges[0], answer.ranges[1]);
|
|
let a_text =
|
|
&text[positions.offset(a.start) as usize..positions.offset(a.end) as usize];
|
|
let b_text =
|
|
&text[positions.offset(b.start) as usize..positions.offset(b.end) as usize];
|
|
assert_eq!(
|
|
a_text,
|
|
b_text,
|
|
"{}: at {offset}, ranges hold different text",
|
|
path.display()
|
|
);
|
|
assert!(
|
|
is_simple_identifier(a_text),
|
|
"{}: at {offset}, {a_text:?} is not a plain identifier",
|
|
path.display()
|
|
);
|
|
assert!(
|
|
(a.end.line, a.end.character) <= (b.start.line, b.start.character)
|
|
|| (b.end.line, b.end.character) <= (a.start.line, a.start.character),
|
|
"{}: at {offset}, ranges overlap: {answer:?}",
|
|
path.display()
|
|
);
|
|
}
|
|
files_checked += 1;
|
|
}
|
|
assert!(files_checked > 5, "the corpus really is checked out: {files_checked} files");
|
|
assert!(
|
|
pairs_found > 10,
|
|
"these files really do write closing labels: {pairs_found} pairs"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_cursor_on_the_colon_or_in_the_labels_whitespace_answers_nothing() {
|
|
let text = "module m;\n initial begin : blk\n end : blk\nendmodule\n";
|
|
for (offset, what) in [
|
|
(at(text, ": blk"), "the colon before the header's `blk`"),
|
|
(at(text, ": blk") + 1, "the space after that colon"),
|
|
(at(text, " end"), "the indentation before `end`, between the two names"),
|
|
] {
|
|
// A position strictly on the colon or on whitespace — never on a
|
|
// letter of `blk` itself — answers nothing, even with `blk`
|
|
// close by on both sides.
|
|
assert!(linked(text, offset).is_none(), "{what}: {offset}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_walk_of_a_whole_file_finds_every_construct_once() {
|
|
let text = concat!(
|
|
"package p;\n",
|
|
"endpackage : p\n",
|
|
"module m;\n",
|
|
" function f;\n",
|
|
" endfunction : f\n",
|
|
" task t;\n",
|
|
" endtask : t\n",
|
|
" initial begin : blk\n",
|
|
" end : blk\n",
|
|
"endmodule : m\n",
|
|
);
|
|
let doc = doc_of(text);
|
|
let mut pairs = Vec::new();
|
|
items_pairs(&doc.tree.items, &mut pairs);
|
|
assert_eq!(pairs.len(), 5, "package, module, function, task, named begin");
|
|
// And every one of them is reachable from either of its own names.
|
|
for pair in &pairs {
|
|
assert!(linked_editing_ranges(&doc, pair.open.start).is_some());
|
|
assert!(linked_editing_ranges(&doc, pair.close.start).is_some());
|
|
}
|
|
}
|
|
}
|
|
|
|
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|