Files
lucisv/crates/lucisv_server/src/inline/tests.rs
T
Guoliang ChenandClaude Mythos 5.2 aa2259bfe1 Round 12: pure-move splits and hygiene
Splits resolve.rs, parser/item.rs, parser/instance.rs, format/stmt.rs and
lexer.rs (really 771 lines); moves 23 inline test modules of lucisv_server
to their own files; reasons on all 12 bare #[ignore]; the giant-line
references test times the real request; sites.py default root.
Output over 4,046 OpenTitan files byte-identical to a479faf.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-26 20:39:56 -08:00

1673 lines
69 KiB
Rust

// Author: Guoliang Chen, a Senior Digital Design Engineer
use super::*;
use crate::settings::ClientSettings;
use crate::uri::path_to_uri;
use std::path::PathBuf;
use std::str::FromStr;
use vlog_parser::PARSE_STACK_SIZE;
/// A one-file workspace with `path` open and the cursor at `needle`'s end.
/// No files on disk: nothing here reads the index.
fn asking_in(path: &str, text: &str, needle: &str) -> (Workspace, Uri, Position) {
let uri = path_to_uri(&PathBuf::from(path)).expect("uri");
let mut ws = Workspace::default();
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find(needle).expect("needle present") + needle.len()) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
(ws, uri, position)
}
/// [`triggered`] used to sweep the token vector backwards from its end for
/// the last non-`Eof` token ending at or before the cursor. It now bounds
/// that sweep with a binary search; the token it lands on must be the same
/// one at every byte.
#[test]
fn the_last_token_before_the_cursor_is_the_one_the_reverse_sweep_found() {
let text = crate::state::mixed_buffer(20);
let uri = path_to_uri(&PathBuf::from("/rtl/top.sv")).expect("uri");
let mut ws = Workspace::default();
ws.set_document(uri.clone(), text.clone());
let doc = ws.document(&uri).expect("open");
for offset in 0..=text.len() as u32 {
let swept = doc
.tokens
.iter()
.rposition(|token| token.kind != TokenKind::Eof && token.span.end <= offset);
let reached = doc.tokens.partition_point(|token| token.span.end <= offset);
let searched = doc.tokens[..reached].iter().rposition(|token| token.kind != TokenKind::Eof);
assert_eq!(swept, searched, "at offset {offset}");
}
}
/// The same, in a SystemVerilog buffer.
fn asking(text: &str, needle: &str) -> (Workspace, Uri, Position) {
asking_in("/rtl/top.sv", text, needle)
}
/// Every snippet offered at `needle`'s end, in order.
fn all_offered(text: &str, needle: &str) -> Vec<String> {
offered_in("/rtl/top.sv", text, needle)
}
/// Every snippet offered at `needle`'s end in a buffer called `path`.
fn offered_in(path: &str, text: &str, needle: &str) -> Vec<String> {
let (ws, uri, position) = asking_in(path, text, needle);
match inline_completions(&ws, &uri, position) {
None => Vec::new(),
Some(items) => items.items.iter().map(|i| i.insert_text.value.clone()).collect(),
}
}
/// The one snippet offered at `needle`'s end, if any.
fn offered(text: &str, needle: &str) -> Option<String> {
let mut items = all_offered(text, needle);
assert!(items.len() <= 1, "one ghost or none, got {items:?}");
items.pop()
}
/// `snippet` as VS Code really writes it into the buffer.
///
/// `SnippetSession.adjustWhitespace` prepends the insertion line's own
/// leading whitespace — `base` — to every line after the first, then
/// `TextModel.normalizeIndentation` re-spells the whole leading run in the
/// editor's tabs-or-spaces, which is what turns each `\t` the server sent
/// into one `step`.
fn accepted(snippet: &str, base: &str, step: &str) -> String {
let mut out: Vec<String> = Vec::new();
for (index, line) in snippet.split('\n').enumerate() {
if index == 0 {
out.push(line.to_string());
continue;
}
let steps = line.chars().take_while(|c| *c == '\t').count();
out.push(format!("{base}{}{}", step.repeat(steps), &line[steps..]));
}
out.join("\n")
}
/// `snippet` with every hole filled in the way the editor would preselect
/// it — the plain text a Tab really produces. The registry's grammar is
/// `${n:default}` and `$n` and nothing else, which
/// `every_hole_is_a_tabstop` pins.
fn filled(snippet: &str) -> String {
let mut out = String::new();
let mut rest = snippet;
let mut mirrors: Vec<(&str, &str)> = Vec::new();
while let Some(at) = rest.find('$') {
out.push_str(&rest[..at]);
rest = &rest[at + 1..];
if let Some(braced) = rest.strip_prefix('{') {
let close = braced.find('}').expect("a hole is closed");
let hole = &braced[..close];
if let Some((number, default)) = hole.split_once(':') {
mirrors.push((number, default));
out.push_str(default);
}
rest = &braced[close + 1..];
continue;
}
let digits = rest.len() - rest.trim_start_matches(|c: char| c.is_ascii_digit()).len();
let number = &rest[..digits];
// A bare `$n` repeats what `${n:…}` was given, the way the editor
// mirrors a placeholder; `$0` was never declared and is nothing.
if let Some((_, default)) = mirrors.iter().find(|(n, _)| *n == number) {
out.push_str(default);
}
rest = &rest[digits..];
}
out.push_str(rest);
out
}
// ------------------------------------------------------------------
// the emission contract: relative, not absolute
// ------------------------------------------------------------------
#[test]
fn a_snippet_is_indented_relative_to_the_trigger_line() {
// The 0.6.0 bug: the body used to carry the trigger line's own
// indentation, and VS Code prepends it *again* on insert, so the `end`
// landed a level deeper than the `begin` it closes. One `\t` per step
// and nothing else is what the editor can place correctly.
let text = "module top;\n always_comb begin\nendmodule\n";
assert_eq!(offered(text, "always_comb begin").as_deref(), Some("\n\t$0\nend"));
}
#[test]
fn the_editor_puts_the_end_level_with_its_opener() {
// What the user actually sees after Tab, with the two things VS Code
// does to the text modelled: the base prepended, one `\t` widened to
// the editor's indent.
let text = "module top;\n always_comb begin\nendmodule\n";
let snippet = offered(text, "always_comb begin").expect("a ghost");
assert_eq!(accepted(&snippet, " ", " "), "\n $0\n end");
// ...at any depth, and in tabs as readily as in spaces.
assert_eq!(accepted(&snippet, "\t\t", "\t"), "\n\t\t\t$0\n\t\tend");
}
#[test]
fn the_line_indentation_never_reaches_the_snippet() {
// The same three lines however deep the trigger sits and however the
// buffer spells its indentation: the server has stopped having an
// opinion about either.
for line in ["always_comb begin", " always_comb begin", "\t\talways_comb begin"] {
let text = format!("module top;\n{line}\nendmodule\n");
assert_eq!(offered(&text, "always_comb begin").as_deref(), Some("\n\t$0\nend"));
}
}
#[test]
fn the_indent_setting_no_longer_reaches_a_snippet() {
// `lucisv.indent` still decides what the *formatter* writes and what the
// completion popup inserts; an accepted inline snippet is laid out by
// the editor's own tab settings, because the editor re-spells the
// leading whitespace on insert whatever the server sent.
let text = "module top;\n always_comb begin\nendmodule\n";
let (mut ws, uri, position) = asking(text, "always_comb begin");
ws.set_client_settings(ClientSettings { indent: Some(4), ..Default::default() });
let items = inline_completions(&ws, &uri, position).expect("a ghost");
assert_eq!(items.items[0].insert_text.value, "\n\t$0\nend");
}
// ------------------------------------------------------------------
// the triggers
// ------------------------------------------------------------------
#[test]
fn an_open_if_paren_offers_the_rest_of_the_block() {
let text = "module top;\n always_comb begin\n if (\n end\nendmodule\n";
assert_eq!(
offered(text, " if (").as_deref(),
Some("${1:cond}) begin\n\t$0\nend"),
"the condition first and the body last"
);
}
#[test]
fn an_else_if_offers_the_same_block() {
let text = "\
module top;
always_comb begin
if (a) begin
end else if (
end
endmodule
";
assert_eq!(offered(text, "else if (").as_deref(), Some("${1:cond}) begin\n\t$0\nend"));
}
#[test]
fn a_fresh_begin_offers_its_end() {
let text = "module top;\n always_comb begin\nendmodule\n";
assert_eq!(offered(text, "always_comb begin").as_deref(), Some("\n\t$0\nend"));
}
#[test]
fn a_while_offers_the_same_block_as_an_if() {
let text = "module top;\n initial begin\n while (\n end\nendmodule\n";
assert_eq!(offered(text, "while (").as_deref(), Some("${1:cond}) begin\n\t$0\nend"));
}
#[test]
fn a_for_loop_follows_the_buffers_dialect() {
// The same two bodies `templates.rs` offers in the popup, minus the
// `for (` the user has already typed.
let text = "module top;\n initial begin\n for (\n end\nendmodule\n";
assert_eq!(
offered_in("/rtl/top.sv", text, "for ("),
vec!["int ${1:i} = 0; $1 < ${2:N}; $1++) begin\n\t$0\nend"],
"SystemVerilog declares the loop variable in the header"
);
assert_eq!(
offered_in("/rtl/top.v", text, "for ("),
vec!["${1:i} = 0; $1 < ${2:N}; $1 = $1 + 1) begin\n\t$0\nend"],
"Verilog has no `++` and no local loop variable"
);
}
#[test]
fn every_case_flavour_offers_the_same_arms_and_an_endcase() {
for keyword in ["case", "casez", "casex"] {
let text = format!("module top;\n always_comb begin\n {keyword} (\n end\nendmodule\n");
assert_eq!(
offered(&text, &format!("{keyword} (")).as_deref(),
Some("${1:sel})\n\t${2:value}: $0;\n\tdefault: ;\nendcase"),
"{keyword}"
);
}
}
#[test]
fn casex_is_offered_here_although_the_popup_does_not_list_it() {
// `templates.rs` leaves `casex` out on purpose: it is the flavour most
// style guides warn against, and an unused entry is noise in a list.
// Ghost text is not a list — it only ever appears once the user has
// typed `casex (` and committed to it — so the noise argument does not
// apply and refusing to finish the construct would just be unhelpful.
let text = "module top;\n always_comb begin\n casex (\n end\nendmodule\n";
assert!(offered(text, "casex (").is_some());
}
#[test]
fn an_always_at_offers_clock_and_reset_first_then_clock_only_then_the_star() {
let text = "module top;\n always @(\nendmodule\n";
assert_eq!(
all_offered(text, "always @("),
vec![
"posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend".to_string(),
"posedge ${1:clk}) begin\n\t$0\nend".to_string(),
"*) begin\n\t$0\nend".to_string(),
],
"clocked first: `always @(` is overwhelmingly a flop, and most flops reset"
);
}
#[test]
fn always_ff_is_systemverilog_only() {
let text = "module top;\n always_ff @(\nendmodule\n";
assert_eq!(
offered_in("/rtl/top.sv", text, "always_ff @("),
vec![
"posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend",
"posedge ${1:clk}) begin\n\t$0\nend"
]
);
assert!(
offered_in("/rtl/top.v", text, "always_ff @(").is_empty(),
"a `.v` compiler rejects `always_ff`"
);
}
#[test]
fn fork_generate_and_module_offer_their_own_closers() {
let text = "module top;\n initial begin\n fork\n end\nendmodule\n";
assert_eq!(offered(text, " fork").as_deref(), Some("\n\t$0\njoin"));
let text = "module top;\n generate\nendmodule\n";
assert_eq!(offered(text, " generate").as_deref(), Some("\n\t$0\nendgenerate"));
// A module needs a name before its `;`, so the body writes one — the
// leading space is deliberate, the user's cursor sits right after the
// `e` of `module`.
assert_eq!(offered("module", "module").as_deref(), Some(" ${1:name};\n\t$0\nendmodule"));
}
// ------------------------------------------------------------------
// the negatives
// ------------------------------------------------------------------
#[test]
fn a_comment_or_a_string_never_triggers() {
// Neither is a token: a comment is lexer trivia, and the literal is one
// `String` token whose text is not a keyword.
for (text, needle, what) in [
("module top;\n // if (\nendmodule\n", "// if (", "a line comment"),
("module top;\n /* if ( */\nendmodule\n", "/* if (", "a block comment"),
("module top;\n initial $display(\"if (\");\nendmodule\n", "\"if (", "inside a string"),
("module top;\n initial $display(\"begin\");\nendmodule\n", "\"begin", "ditto"),
("module top;\n // begin\nendmodule\n", "// begin", "a commented begin"),
("module top;\n // case (\nendmodule\n", "// case (", "a commented case"),
] {
assert_eq!(offered(text, needle), None, "{what}: {text}");
}
}
#[test]
fn an_identifier_that_merely_ends_in_the_keyword_never_triggers() {
let text = "module top;\n always_comb begin\n my_if (\n end\nendmodule\n";
assert_eq!(offered(text, "my_if ("), None, "`my_if` is an identifier");
let text = "module top;\n logic my_begin;\n assign my_begin\nendmodule\n";
assert_eq!(offered(text, "assign my_begin"), None);
}
#[test]
fn a_line_with_anything_after_the_cursor_never_triggers() {
let text = "module top;\n always_comb begin\n if (a) begin\n end\n end\nendmodule\n";
assert_eq!(offered(text, " if ("), None, "the condition is already written");
let text = "module top;\n always_comb begin ; end\nendmodule\n";
assert_eq!(offered(text, "always_comb begin"), None);
}
#[test]
fn whitespace_between_the_keyword_and_the_cursor_never_triggers() {
// The cursor must be exactly at the token's end — "you just typed
// this", and nothing looser.
let text = "module top;\n always_comb begin \nendmodule\n";
assert_eq!(offered(text, "always_comb begin "), None);
let text = "module top;\n always_comb begin\n if ( \n end\nendmodule\n";
assert_eq!(offered(text, "if ( "), None);
}
#[test]
fn a_begin_that_already_has_its_end_offers_nothing() {
// The `end` below belongs to the `begin` just typed — `pairs::analyze`
// matches them — so a second one would break the file.
let text = "\
module top;
always_comb begin
begin
end
end
endmodule
";
assert_eq!(offered(text, " begin"), None, "the inner begin is matched");
// ...and the one that really is unclosed still offers.
let text = "module top;\n always_comb begin\n end\n initial begin\nendmodule\n";
assert!(offered(text, "initial begin").is_some(), "this one lost its end");
}
#[test]
fn a_begin_typed_inside_a_balanced_block_still_offers_its_end() {
// The new `begin` steals the `always_comb` block's `end` in the stack
// matcher; the gate asks the auto-`end` question instead
// (`completion-ux` fix round, 2026-11-17).
let text = "module top;\n always_comb begin\n if (x) begin\n end\nendmodule\n";
assert_eq!(offered(text, "if (x) begin").as_deref(), Some("\n\t$0\nend"));
}
#[test]
fn a_scope_keyword_that_already_has_its_closer_offers_nothing() {
// The same rule as `begin`, for the three keywords that joined it.
let text = "module top;\n initial begin\n fork\n join\n end\nendmodule\n";
assert_eq!(offered(text, " fork"), None);
let text = "module top;\n generate\n endgenerate\nendmodule\n";
assert_eq!(offered(text, " generate"), None);
let text = "module\nendmodule\n";
assert_eq!(offered(text, "module"), None);
// `disable fork;` names a fork rather than opening one — `pairs.rs`
// knows, and the gate inherits that.
let text = "module top;\n initial begin\n disable fork\n end\nendmodule\n";
assert_eq!(offered(text, "disable fork"), None);
}
#[test]
fn a_case_that_already_has_its_endcase_offers_nothing() {
// Both halves of the `case (` gate matter. Here the `endcase` below is
// this `case`'s own, so a second one would leave the file unbalanced —
// even though the `(` really is unclosed.
let text = "\
module top;
always_comb begin
case (
endcase
end
endmodule
";
assert_eq!(offered(text, " case ("), None, "the endcase is already there");
// ...and when the `endcase` below belongs to a nested, complete `case`,
// the one just typed still owes its own.
let text = "\
module top;
always_comb begin
case (
case (b)
default: ;
endcase
end
endmodule
";
assert!(offered(text, " case (").is_some(), "this case is genuinely unclosed");
}
#[test]
fn an_if_paren_that_is_already_closed_offers_nothing() {
// A `)` further down the buffer is the one this `(` will pair with;
// writing a second would leave the file unbalanced the other way.
let text =
"module top;\n always_comb begin\n if (\n a) begin\n end\n end\nendmodule\n";
assert_eq!(offered(text, " if ("), None);
}
#[test]
fn a_later_call_does_not_cancel_the_paren_just_typed() {
// A running `(` minus `)` count would see the `)` of `f(1)` below and
// decide this `(` was already closed. It is a stack, so the call's own
// paren pairs with its own closer and the `if (` stays open.
let text = "\
module top;
always_comb begin
if (
x = f(1);
end
endmodule
";
assert_eq!(offered(text, " if (").as_deref(), Some("${1:cond}) begin\n\t$0\nend"));
}
#[test]
fn a_paren_the_line_below_closes_still_counts_as_closed() {
// The mirror of the test above: when the `)` really is this `(`'s own,
// no ghost — even though a plain "is anything unbalanced" check on the
// rest of the file would say yes because of the `f(` beside it.
let text = "\
module top;
always_comb begin
if (
f(1) > 0) begin
end
end
endmodule
";
assert_eq!(offered(text, " if ("), None);
}
#[test]
fn an_always_without_its_event_control_offers_nothing() {
// The opener is a *sequence*: both `@` and `(` must be there, in that
// order, or the user has not committed to an event-controlled block.
// A bare `always` grows no block — only the keyword ghost's `_ff`,
// which is a different feature with its own setting.
let text = "module top;\n always\nendmodule\n";
assert_eq!(offered(text, " always").as_deref(), Some("_ff"));
let text = "module top;\n always @\nendmodule\n";
assert_eq!(offered(text, "always @"), None);
let text = "module top;\n always (\nendmodule\n";
assert_eq!(offered(text, "always ("), None, "`(` alone is not `@(`");
}
#[test]
fn a_buffer_that_does_not_lex_is_declined() {
let text = "module top;\n /* unterminated\n always_comb begin\n";
let (ws, uri, position) = asking(text, "always_comb begin");
assert!(ws.document(&uri).expect("open").tokens.is_empty(), "premise: no tokens");
assert!(inline_completions(&ws, &uri, position).is_none());
}
#[test]
fn a_trigger_at_the_true_end_of_file_still_offers_a_ghost() {
// QA find, 2026-08-25: `tokenize` appends a zero-width `Eof` token
// whose span starts and ends at `text.len()`. When the file's very
// last byte is the trigger's own last character — no trailing
// newline, nothing typed after it yet — that `Eof` token shares the
// trigger token's `span.end`, and `rposition` (searching from the
// back) finds the `Eof` first. `triggered` then compares a
// `TokenKind::Eof` against `TokenKind::Keyword` and silently declines
// — exactly the moment a user typing at the end of a growing file
// most wants the ghost text to appear.
let text = "module top;\n always_comb begin";
let (ws, uri, position) = asking(text, "always_comb begin");
assert!(
inline_completions(&ws, &uri, position).is_some(),
"the file ends right after `begin`, with no Eof-adjacency confusion"
);
let text = "module top;\n always_comb begin\n if (";
let (ws, uri, position) = asking(text, " if (");
assert!(
inline_completions(&ws, &uri, position).is_some(),
"same for `if (` at true end of file"
);
}
#[test]
fn a_deeply_nested_file_neither_crashes_nor_misses_the_trigger() {
// History: the one recursion-depth bug this codebase had was in the
// *parser*'s AST (TODO.md §1, fixed by `MAX_NESTING_DEPTH`). This
// module never walks that tree — `triggered`/`unfinished` read
// `doc.tokens` and `pairs::analyze`, both flat loops over the token
// stream, so neither can overflow the stack the way the parser once
// did. QA find, 2026-08-25: `pairs::analyze` was quadratic in the
// depth of rainbow nesting back then, which mattered because this
// module calls it on every keystroke inside an unclosed `begin`. It
// is linear now — `Stack`'s running counts in `pairs.rs`, whose own
// tests pin the scaling — and this depth stands guard on the caller's
// side of that contract.
let depth = 3_000;
let mut text = String::from("module top;\n");
for _ in 0..depth {
text.push_str(" begin\n");
}
// A trailing newline, so this test isolates depth from the separate
// true-end-of-file `Eof`-adjacency case pinned above.
text.push_str("initial begin\n");
// Opening the document *parses* it, and since §36.1 a bare `begin` at
// item scope is a generate block the tolerant parser descends into —
// so this text nests the parser to `MAX_NESTING_DEPTH` and costs ~4
// MiB of stack in a debug build. That is exactly what
// `PARSE_STACK_SIZE` is for; every production thread that may reach a
// parse is given it (`main.rs`), libtest's own thread is not, so the
// body runs on one of its own. Nothing here is about the inline path,
// which still never recurses.
std::thread::Builder::new()
.stack_size(PARSE_STACK_SIZE)
.spawn(move || {
let (ws, uri, position) = asking(&text, "initial begin");
assert!(
!ws.document(&uri).expect("open").tokens.is_empty(),
"the lexer never recurses"
);
let items = inline_completions(&ws, &uri, position);
assert!(
items.is_some(),
"the innermost, truly unclosed `begin` still offers its `end`"
);
})
.expect("spawn")
.join()
.expect("the inline path crashed");
}
#[test]
fn an_empty_file_at_zero_zero_offers_nothing_and_does_not_panic() {
let mut ws = Workspace::default();
let uri = path_to_uri(&PathBuf::from("/rtl/empty.sv")).expect("uri");
ws.set_document(uri.clone(), String::new());
assert!(inline_completions(&ws, &uri, Position { line: 0, character: 0 }).is_none());
}
#[test]
fn a_position_past_the_end_of_its_line_clamps_rather_than_panics() {
// Clients do send these — a keystroke can outrun the position the
// client had in hand. `convert.rs`'s `offset` clamps it to the line's
// real content end, which here happens to land exactly on the
// trigger, so the ghost still appears rather than nothing panicking
// but nothing offered either.
let text = "module top;\n always_comb begin\nendmodule\n";
let (ws, uri, _) = asking(text, "always_comb begin");
let items = inline_completions(&ws, &uri, Position { line: 1, character: 9_999 });
assert!(items.is_some(), "clamped to right after `begin`, same as the exact position");
// (0, 0) on a non-empty file: nowhere near a trigger, not a panic.
assert!(inline_completions(&ws, &uri, Position { line: 0, character: 0 }).is_none());
}
#[test]
fn no_space_between_the_keyword_and_the_paren_still_triggers() {
// Token spans carry no inter-token whitespace of their own, so `if(`
// and `if (` must be indistinguishable to `triggered`.
let text = "module top;\n always_comb begin\n if(\n end\nendmodule\n";
assert_eq!(offered(text, " if(").as_deref(), Some("${1:cond}) begin\n\t$0\nend"));
// ...and the same for a two-symbol opener written tight.
let text = "module top;\n always@(\nendmodule\n";
assert_eq!(all_offered(text, "always@(").len(), 3);
}
#[test]
fn crlf_line_endings_still_trigger() {
// `rest_of_line_is_blank` splits on `\n` alone, so a CRLF file's `\r`
// rides along in the slice — `char::is_whitespace('\r')` is `true`,
// so it still reads as "nothing after the cursor".
let text = "module top;\r\n always_comb begin\r\nendmodule\r\n";
assert_eq!(offered(text, "always_comb begin").as_deref(), Some("\n\t$0\nend"));
let text = "module top;\r\n always_comb begin\r\n if (\r\n end\r\nendmodule\r\n";
assert_eq!(offered(text, " if (").as_deref(), Some("${1:cond}) begin\n\t$0\nend"));
}
#[test]
fn an_unknown_document_is_declined() {
let ws = Workspace::default();
let uri = path_to_uri(&PathBuf::from("/rtl/gone.sv")).expect("uri");
assert!(inline_completions(&ws, &uri, Position { line: 0, character: 0 }).is_none());
}
#[test]
fn the_setting_turns_the_whole_feature_off() {
let text = "module top;\n always_comb begin\nendmodule\n";
let (mut ws, uri, position) = asking(text, "always_comb begin");
assert!(inline_completions(&ws, &uri, position).is_some(), "premise: on by default");
ws.set_client_settings(ClientSettings { inline_templates: Some(false), ..Default::default() });
assert!(inline_completions(&ws, &uri, position).is_none());
ws.set_client_settings(ClientSettings { inline_templates: Some(true), ..Default::default() });
assert!(inline_completions(&ws, &uri, position).is_some(), "and back on again");
}
// ------------------------------------------------------------------
// the registry's own hygiene
// ------------------------------------------------------------------
/// Every body in the table, with the trigger it belongs to.
fn every() -> Vec<(&'static Trigger, &'static [Line])> {
TRIGGERS.iter().flat_map(|t| t.bodies.iter().map(move |body| (t, *body))).collect()
}
/// What the user has typed by the time `trigger` fires.
fn typed(trigger: &Trigger) -> String {
let mut out = trigger.keyword.to_string();
for symbol in trigger.opener {
out.push_str(symbol);
}
out
}
/// `text` planted where its construct may legally be written.
///
/// The default is statement position, so a trigger added without a thought
/// for this list either parses there — which is the common case — or fails
/// loudly.
fn planted(trigger: &Trigger, text: &str) -> String {
match trigger.keyword {
"module" => format!("{text}\n"),
"generate" | "always" | "always_ff" => {
format!("module lucisv_probe;\n {text}\nendmodule\n")
}
_ => {
format!("module lucisv_probe;\n always @(*) begin\n {text}\n end\nendmodule\n")
}
}
}
#[test]
fn every_hole_is_a_tabstop() {
// The editor-snippets lesson: VS Code substitutes an unknown `$NAME`
// with nothing and says nothing, so a system task written into a body
// would vanish silently. None is written today; this is what stops one
// being added unescaped.
for (trigger, body) in every() {
for (_, line) in body {
let mut rest = *line;
while let Some(at) = rest.find('$') {
rest = &rest[at + 1..];
assert!(
rest.starts_with('{') || rest.starts_with(|c: char| c.is_ascii_digit()),
"`{}`: `${}` is not a tabstop",
trigger.keyword,
rest.chars().next().unwrap_or(' ')
);
}
}
}
}
#[test]
fn every_accepted_ghost_parses() {
// What Tab really writes — the snippet as the *editor* lays it out,
// with every hole filled in — planted where the trigger fires and
// handed to the parser. A body that did not parse would be a formatter
// that refuses the file the moment the user accepts a suggestion.
for (trigger, body) in every() {
let text = filled(&accepted(&render(body), " ", " "));
let probe = planted(trigger, &format!("{}{text}", typed(trigger)));
let (_, diagnostics) = vlog_parser::parse_source_tolerant(&probe);
assert!(
diagnostics.is_empty(),
"`{}` does not parse:\n{probe}\n{diagnostics:#?}",
trigger.keyword
);
}
}
#[test]
fn every_trigger_word_is_a_keyword_the_lexer_knows() {
// The detection compares against `TokenKind::Keyword`, so a trigger
// naming a word the lexer calls an identifier could never fire.
for trigger in TRIGGERS {
assert!(
vlog_parser::KEYWORDS.contains(&trigger.keyword),
"`{}` is not a keyword",
trigger.keyword
);
}
}
#[test]
fn every_accepted_ghost_is_scope_balanced() {
// What the user typed plus what Tab writes closes exactly what it
// opens: no dangling `begin`, no orphan `endcase`. The same matcher
// the gates ask, run over the result rather than over the buffer.
for (trigger, body) in every() {
let text = format!("{}{}", typed(trigger), filled(&render(body)));
let tokens = vlog_parser::tokenize(&text).expect("a body lexes");
let analysis = pairs::analyze(&tokens);
assert!(
analysis.unmatched_open.is_empty() && analysis.unmatched_close.is_empty(),
"`{}` does not balance:\n{text}",
trigger.keyword
);
}
}
#[test]
fn every_gate_is_the_one_the_body_needs() {
// The rule behind the three `Unclosed` variants, derived from the
// bodies rather than restated: a body that writes a closer for a scope
// it did not open — `end` after a bare `begin`, `endcase` after
// `case (` — is finishing the *user's* keyword, so the gate must ask
// whether that keyword is still open. A body whose own `begin` its
// `end` closes needs no such question. And a trigger whose opener ends
// in `(` writes the `)`, so it must ask about the paren.
for trigger in TRIGGERS {
let closes_the_users_keyword = trigger.bodies.iter().any(|body| {
let tokens = vlog_parser::tokenize(&filled(&render(body))).expect("a body lexes");
!pairs::analyze(&tokens).unmatched_close.is_empty()
});
let writes_a_closing_paren = trigger.opener.last() == Some(&"(");
let (scope, paren) = match trigger.gate {
Unclosed::Paren => (false, true),
Unclosed::Scope => (true, false),
Unclosed::ParenAndScope => (true, true),
};
assert_eq!(
closes_the_users_keyword, scope,
"`{}`: the scope half of the gate does not match the body",
trigger.keyword
);
assert_eq!(
writes_a_closing_paren, paren,
"`{}`: the paren half of the gate does not match the opener",
trigger.keyword
);
}
}
#[test]
fn every_trigger_offers_at_least_one_body() {
for trigger in TRIGGERS {
assert!(!trigger.bodies.is_empty(), "`{}` offers nothing", trigger.keyword);
}
}
// ------------------------------------------------------------------
// round 2 QA: `accepted()` cross-checked against VS Code's own algorithm
// ------------------------------------------------------------------
//
// `accepted()` above is a shortcut: it prepends `base` verbatim and only
// re-spells the `\t`s the body added. The real
// `SnippetSession.adjustWhitespace` re-derives the *whole* leading run —
// base included — from column counts (`TextModel.normalizeIndentation`),
// and normalizes the snippet's first line too. The shortcut is exact only
// when the trigger line's own indentation is already spelled the way the
// editor is configured — the ordinary case, and the only one these two
// tests assume — but "ordinary" was itself an assumption worth checking
// rather than trusting, so it is checked here against a second,
// independent model built straight off the quoted source rather than off
// `accepted`'s shortcut.
/// `TextModel.normalizeIndentationFromWhitespace`. `ws` is assumed to be
/// entirely leading whitespace: every `\t` counts as `indent_size`
/// columns, every other character as one, and the whole run is re-spelled
/// as tabs-then-spaces (`insert_spaces: false`) or all spaces (`true`).
fn normalize_indentation_from_whitespace(
ws: &str,
indent_size: usize,
insert_spaces: bool,
) -> String {
let columns: usize = ws.chars().map(|c| if c == '\t' { indent_size } else { 1 }).sum();
let mut out = String::new();
let mut spaces = columns;
if !insert_spaces {
out.extend(std::iter::repeat_n('\t', columns / indent_size));
spaces = columns % indent_size;
}
out.extend(std::iter::repeat_n(' ', spaces));
out
}
/// `TextModel.normalizeIndentation`: only the leading run of spaces and
/// tabs is touched; everything from the first other character on is left
/// alone.
fn normalize_indentation(line: &str, indent_size: usize, insert_spaces: bool) -> String {
let split = line.find(|c: char| c != ' ' && c != '\t').unwrap_or(line.len());
let (ws, rest) = line.split_at(split);
format!("{}{rest}", normalize_indentation_from_whitespace(ws, indent_size, insert_spaces))
}
/// `snippet` as `SnippetSession.adjustWhitespace` really writes it,
/// modelled directly off the quoted source: the first line is normalized
/// *alone* — `lines[0] = model.normalizeIndentation(lines[0])`, no
/// prepend, because `snippet.offset(marker) === 0` — and every later line
/// gets the trigger line's own leading whitespace prepended before
/// normalizing: `model.normalizeIndentation(lineLeadingWhitespace +
/// lines[i])`.
fn accepted_faithful(
snippet: &str,
trigger_line_indent: &str,
indent_size: usize,
insert_spaces: bool,
) -> String {
snippet
.split('\n')
.enumerate()
.map(|(i, line)| match i {
0 => normalize_indentation(line, indent_size, insert_spaces),
_ => normalize_indentation(
&format!("{trigger_line_indent}{line}"),
indent_size,
insert_spaces,
),
})
.collect::<Vec<_>>()
.join("\n")
}
#[test]
fn the_accepted_helper_matches_vscodes_own_algorithm_for_a_self_consistent_buffer() {
// A buffer whose own indentation already matches the editor's current
// `tabSize`/`insertSpaces` — spaces at 2, spaces at 4, tabs — at
// several depths, for every trigger's every body.
for (indent_size, insert_spaces, unit) in
[(2usize, true, " ".repeat(2)), (4, true, " ".repeat(4)), (4, false, "\t".to_string())]
{
let step = if insert_spaces { unit.clone() } else { "\t".to_string() };
for depth in [0usize, 1, 2, 5] {
let base = unit.repeat(depth);
for (trigger, body) in every() {
let snippet = render(body);
let shortcut = accepted(&snippet, &base, &step);
let faithful = accepted_faithful(&snippet, &base, indent_size, insert_spaces);
assert_eq!(
shortcut, faithful,
"`{}` at depth {depth}, indent_size {indent_size}, insert_spaces {insert_spaces}: \
the shortcut `accepted()` every other test uses disagrees with VS Code's own \
normalizeIndentation",
trigger.keyword
);
}
}
}
}
#[test]
fn every_bodys_first_line_is_stable_under_normalization() {
// `accepted()`'s line-0 shortcut (`out.push(line.to_string())`, no
// normalization at all) is only correct because every body's first
// line today has either no leading whitespace or exactly one leading
// space, and a single space normalizes to itself at every indent_size
// VS Code allows. A future body whose first line picked up two or
// more leading spaces (or a leading tab) would make the shortcut
// silently wrong, and nothing else in this file would notice, because
// `every_accepted_ghost_parses` and its siblings only ever call
// `accepted`, never `accepted_faithful`.
for (trigger, body) in every() {
let (_, first_line) = body[0];
for (indent_size, insert_spaces) in [(2usize, true), (4, true), (4, false), (8, false)] {
assert_eq!(
normalize_indentation(first_line, indent_size, insert_spaces),
first_line,
"`{}`'s first line {first_line:?} is not stable at indent_size {indent_size}, \
insert_spaces {insert_spaces} — `accepted()`'s line-0 shortcut would now be wrong",
trigger.keyword
);
}
}
}
#[test]
fn every_bodys_closer_lands_level_with_the_trigger_and_its_interior_one_step_in() {
// The user's exact report: "the end lands deeper than its opener."
// Checked against the table's own `(level, text)` metadata rather
// than by re-deriving it, at several depths, in both indent styles,
// and for every trigger — not just the one construct the round-1
// suite happened to cover.
let configs: &[(&str, &str)] = &[(" ", " "), (" ", " "), ("\t", "\t")];
for (unit, step) in configs {
for depth in [0usize, 1, 2, 5] {
let base = unit.repeat(depth);
for (trigger, body) in every() {
let got = accepted(&render(body), &base, step);
let got_lines: Vec<&str> = got.split('\n').collect();
assert_eq!(got_lines.len(), body.len(), "`{}`: line count", trigger.keyword);
for (i, (level, text)) in body.iter().enumerate() {
let expected = if i == 0 {
text.to_string()
} else {
format!("{base}{}{text}", step.repeat(*level as usize))
};
assert_eq!(
got_lines[i], expected,
"`{}`: line {i} at depth {depth}, base {unit:?}",
trigger.keyword
);
}
// The closer is always the body's last line, and it must
// sit at level 0 — exactly the trigger line's own
// indentation, never a step deeper.
let (closer_level, _) = *body.last().expect("a body has a closer");
assert_eq!(closer_level, 0, "`{}`: closer is not level 0", trigger.keyword);
}
}
}
}
// ------------------------------------------------------------------
// round 2 QA: attacking the new triggers
// ------------------------------------------------------------------
#[test]
fn casez_triggers_in_a_verilog_file_too() {
// `case`/`casez`/`casex` are `dialect: None` — a Verilog buffer gets
// the same ghost a SystemVerilog one does.
let text = "module top;\n always @(*) begin\n casez (\n end\nendmodule\n";
assert!(!offered_in("/rtl/top.v", text, "casez (").is_empty());
}
#[test]
fn a_for_loop_in_a_pathless_buffer_gets_the_verilog_body() {
// `templates::dialect` resolves a pathless buffer to Verilog — the
// same default the completion tier documents — so an `untitled:`
// buffer (no path at all, unlike a `.v` or a `.sv` one) gets the loop
// with no local variable declaration and no `++`.
//
// `offered_in` goes through `path_to_uri`, which always mints a
// `file://` URI, so it cannot produce a genuinely pathless document —
// this builds the `untitled:` URI directly, the way `state.rs`'s own
// `an_untitled_buffer_has_no_path` does.
let uri = Uri::from_str("untitled:Untitled-1").expect("uri");
let text = "module top;\n initial begin\n for (\n end\nendmodule\n";
let mut ws = Workspace::default();
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find("for (").expect("needle present") + "for (".len()) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let items = inline_completions(&ws, &uri, position).expect("a ghost");
assert_eq!(
items.items.iter().map(|i| i.insert_text.value.clone()).collect::<Vec<_>>(),
vec!["${1:i} = 0; $1 < ${2:N}; $1 = $1 + 1) begin\n\t$0\nend"]
);
}
#[test]
fn always_at_space_paren_still_offers_both_items() {
// The lexer does not tokenize whitespace, so `@` and `(` end up
// adjacent in `doc.tokens` whether or not the user left a space
// between them; the opener sequence match is on tokens, not text —
// the tight `always@(` is already pinned by
// `no_space_between_the_keyword_and_the_paren_still_triggers`, this
// pins the opposite spacing.
let text = "module top;\n always @ (\nendmodule\n";
assert_eq!(all_offered(text, "always @ (").len(), 3);
}
#[test]
fn module_mid_file_above_an_existing_closed_module_still_offers() {
// `pairs::analyze` reports the *new* `module`'s own span in
// `unmatched_open` — an earlier, already-closed module does not
// cancel it out, the same rule
// `a_case_that_already_has_its_endcase_offers_nothing` proves for
// `case`.
let text = "module first;\nendmodule\n\nmodule";
assert!(offered(text, "\nmodule").is_some());
}
#[test]
fn generate_offers_even_when_an_earlier_generate_is_balanced() {
let text = "module top;\n generate\n endgenerate\n generate\nendmodule\n";
assert!(
offered(text, "endgenerate\n generate").is_some(),
"the second generate is genuinely open"
);
}
#[test]
fn fork_offers_in_both_dialects() {
let text = "module top;\n initial begin\n fork\n end\nendmodule\n";
assert!(!offered_in("/rtl/top.sv", text, " fork").is_empty());
assert!(!offered_in("/rtl/top.v", text, " fork").is_empty());
}
#[test]
fn a_casex_whose_paren_is_closed_two_lines_down_offers_nothing() {
// Same rule `a_paren_the_line_below_closes_still_counts_as_closed`
// pins for `if (`, attacked on the trigger whose gate also asks about
// a scope: the paren half alone is enough to decline.
let text = "\
module top;
always_comb begin
casex (
sel)
1: ;
endcase
end
endmodule
";
assert_eq!(offered(text, "casex ("), None, "the `)` two lines down still closes the paren");
}
#[test]
fn nested_unclosed_parens_each_see_their_own_gate() {
// `if (` on one line and `always @(` on the next: two different
// unclosed parens. `paren_is_closed` is a stack keyed by the exact
// span passed in, so neither paren can be mistaken for the other's
// counterpart — both must still offer.
let text = "module top;\n if (\n always @(\nendmodule\n";
assert!(offered(text, " if (").is_some());
assert_eq!(all_offered(text, " always @(").len(), 3);
}
// ------------------------------------------------------------------
// the wire
// ------------------------------------------------------------------
#[test]
fn the_wire_shape_is_what_the_client_reads() {
// The whole reason these types are hand-rolled. `lsp-types` 0.97 spells
// `insertText` as a bare `String`, and `vscode-languageclient`'s
// `asInlineCompletionItem` inserts a bare string as **plain text** —
// every `${1:cond}` would appear literally in the buffer. Only the
// `{"kind": "snippet"}` object becomes a `SnippetString`. If a future
// `lsp-types` bump tempts anyone to use its item type, this fails.
let text = "module top;\n always_comb begin\nendmodule\n";
let (ws, uri, position) = asking(text, "always_comb begin");
let items = inline_completions(&ws, &uri, position).expect("a ghost");
assert_eq!(
serde_json::to_value(&items).expect("serializes"),
serde_json::json!({
"items": [{
"insertText": { "kind": "snippet", "value": "\n\t$0\nend" },
"range": {
"start": { "line": 1, "character": 19 },
"end": { "line": 1, "character": 19 }
}
}]
})
);
}
#[test]
fn a_multi_item_response_repeats_the_range_and_nothing_else() {
let text = "module top;\n always @(\nendmodule\n";
let (ws, uri, position) = asking(text, "always @(");
let items = inline_completions(&ws, &uri, position).expect("two ghosts");
assert_eq!(
serde_json::to_value(&items).expect("serializes"),
serde_json::json!({
"items": [
{
"insertText": {
"kind": "snippet",
"value": "posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend"
},
"range": {
"start": { "line": 1, "character": 11 },
"end": { "line": 1, "character": 11 }
}
},
{
"insertText": {
"kind": "snippet",
"value": "posedge ${1:clk}) begin\n\t$0\nend"
},
"range": {
"start": { "line": 1, "character": 11 },
"end": { "line": 1, "character": 11 }
}
},
{
"insertText": { "kind": "snippet", "value": "*) begin\n\t$0\nend" },
"range": {
"start": { "line": 1, "character": 11 },
"end": { "line": 1, "character": 11 }
}
}
]
})
);
}
#[test]
fn the_range_is_empty_and_at_the_cursor() {
// The protocol requires a range to begin and end on one line, and this
// item inserts rather than replaces — so the only honest range is the
// caret itself.
let text = "module top;\n always_comb begin\nendmodule\n";
let (ws, uri, position) = asking(text, "always_comb begin");
let items = inline_completions(&ws, &uri, position).expect("a ghost");
assert_eq!(items.items[0].range.start, position);
assert_eq!(items.items[0].range.end, position);
}
#[test]
fn a_multibyte_line_puts_the_range_where_the_cursor_really_is() {
// The `é` is 2 bytes and 1 UTF-16 unit; a byte-based position would
// put the ghost one column late.
let text = "module top;\n // é\n always_comb begin\nendmodule\n";
let (ws, uri, position) = asking(text, "always_comb begin");
let items = inline_completions(&ws, &uri, position).expect("a ghost");
assert_eq!(items.items[0].range.start, Position { line: 2, character: 19 });
}
// ------------------------------------------------------------------
// the instantiation ghost (2026-08-30)
// ------------------------------------------------------------------
/// A scratch workspace root, removed on drop. The instantiation ghost is
/// the one path here that reads the index, so its tests need real files.
struct Tree {
path: PathBuf,
}
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("lucisv_server_inline_{}_{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).expect("temp dir");
Tree { path }
}
fn write(&self, rel: &str, text: &str) -> PathBuf {
let path = self.path.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("temp dir");
}
std::fs::write(&path, text).expect("write");
path
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
/// The module every ghost below instantiates: parameters *and* ports, one
/// of which (`clk`) the buffer declares and so binds itself.
const SUB: &str = "\
module sub #(
parameter int WIDTH = 8
) (
input logic clk,
input logic [WIDTH-1:0] data,
output logic ready
);
endmodule
";
/// The ghost `SUB`'s header produces, with the name the user typed *and
/// the space that armed it* already cut off the front. Written out once,
/// because half the tests below are about whether it appears at all rather
/// than about what it says.
const SUB_GHOST: &str = "#(\n\t.WIDTH(${1:8})\n) ${2:u_sub} (\n\t.clk(clk),\n\t\
.data(${3:data}),\n\t.ready(${4:ready})\n);";
/// A workspace holding `files` plus an open `top.sv`, with the cursor at
/// `needle`'s end.
fn workspace(
name: &str,
files: &[(&str, &str)],
top: &str,
needle: &str,
) -> (Tree, Workspace, Uri, Position) {
workspace_at(name, files, "top.sv", top, needle)
}
/// The same, with the open buffer written at `top_rel` — which is what the
/// nearest-definition rule reads, so a test about *which* copy is chosen
/// has to be able to say where the asking buffer lives.
fn workspace_at(
name: &str,
files: &[(&str, &str)],
top_rel: &str,
top: &str,
needle: &str,
) -> (Tree, Workspace, Uri, Position) {
let tree = Tree::new(name);
for (rel, text) in files {
tree.write(rel, text);
}
let path = tree.write(top_rel, top);
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), top.to_string());
let offset = (top.find(needle).expect("needle present") + needle.len()) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
(tree, ws, uri, position)
}
/// The one ghost offered at `needle`'s end in a workspace declaring `SUB`.
///
/// `needle` names the text the cursor sits after, and every caller here
/// spells the arming space into it: since 2026-08-30 the ghost answers
/// `sub ` and never `sub`, because `sub` alone may still be growing into
/// `sub_dft`.
fn ghosted(name: &str, top: &str, needle: &str) -> Option<String> {
ghosted_among(name, &[("sub.sv", SUB)], top, needle)
}
/// The same, over a workspace spelled out by the caller.
fn ghosted_among(name: &str, files: &[(&str, &str)], top: &str, needle: &str) -> Option<String> {
ghosted_at(name, files, "top.sv", top, needle)
}
/// The same again, with the asking buffer's own path spelled out.
fn ghosted_at(
name: &str,
files: &[(&str, &str)],
top_rel: &str,
top: &str,
needle: &str,
) -> Option<String> {
let (_tree, ws, uri, position) = workspace_at(name, files, top_rel, top, needle);
let items = inline_completions(&ws, &uri, position)?;
assert_eq!(items.items.len(), 1, "an instantiation is one offer, not a menu");
Some(items.items[0].insert_text.value.clone())
}
#[test]
fn an_exactly_spelled_module_name_and_a_space_ghost_the_whole_instantiation() {
let top = "module top;\n logic clk;\n sub \nendmodule\n";
assert_eq!(ghosted("exact", top, " sub ").as_deref(), Some(SUB_GHOST));
}
/// The owner's ruling of 2026-08-30, both halves in one place: the space is
/// what arms the ghost, and without it there is nothing — *even though*
/// `sub` is a module the workspace really declares and the cursor really is
/// at a legal site. `aes` is not a commitment while `aes_dft` may still be
/// coming; `aes ` is.
#[test]
fn the_name_alone_offers_nothing_and_the_name_and_a_space_offer_everything() {
let top = "module top;\n logic clk;\n sub \nendmodule\n";
assert_eq!(ghosted("armed_no", top, " sub"), None, "the name alone is not a commitment");
assert_eq!(ghosted("armed_yes", top, " sub ").as_deref(), Some(SUB_GHOST));
}
/// One space, and the one just typed. Two of them is a cursor parked in
/// whitespace rather than a name just finished, and a tab is not the
/// character this rule is about at all.
#[test]
fn only_a_single_space_arms_the_ghost() {
let top = "module top;\n logic clk;\n sub \nendmodule\n";
assert_eq!(ghosted("twospaces", top, " sub "), None, "two spaces is not `just typed`");
let top = "module top;\n logic clk;\n sub\t\nendmodule\n";
assert_eq!(ghosted("tab", top, " sub\t"), None, "a tab does not arm it");
// …and the first of the two spaces still does, which is the same rule
// read from the other side: the byte before the cursor is a space and
// the byte before that is not.
let top = "module top;\n logic clk;\n sub \nendmodule\n";
assert_eq!(ghosted("firstspace", top, " sub ").as_deref(), Some(SUB_GHOST));
}
/// A name that is not a module, followed by a space, is the overwhelmingly
/// common keystroke on this path — it must cost the binary search and stop.
#[test]
fn a_space_after_a_name_that_is_not_a_module_ghosts_nothing() {
let top = "module top;\n logic clk;\n widget \nendmodule\n";
assert_eq!(ghosted("notamodule", top, " widget "), None);
}
/// The layout `vlog_refactor` renders really does put exactly one space
/// between a module's name and whatever follows it, in both shapes: a
/// parameterised header (`sub #(`) and a bare one (`bare u_bare`). The cut
/// in `instantiation_ghost` asserts this rather than assuming it — see
/// [`NoGhost::UnexpectedLayout`] — and this is what would fail first if the
/// spelling ever changed.
#[test]
fn the_rendered_skeleton_really_does_put_one_space_after_the_name() {
for (name, module, files) in [
("layout_params", "sub", &[("sub.sv", SUB)][..]),
("layout_bare", "bare", &[("bare.sv", "module bare;\nendmodule\n")][..]),
] {
let top = format!("module top;\n logic clk;\n {module} \nendmodule\n");
let ghost = ghosted_among(name, files, &top, &format!(" {module} ")).expect("a ghost");
assert!(
!ghost.starts_with(char::is_whitespace),
"{module}: the arming space is the ghost's, not the user's: {ghost:?}"
);
}
}
/// The accepted text is what the popup's skeleton used to insert, byte for
/// byte — which is the argument that level 2 gives up nothing level 1 gave
/// away. The layout the server sends is relative; the editor supplies the
/// site's own indentation and the width of a step.
#[test]
fn the_accepted_ghost_is_the_skeleton_the_popup_used_to_insert() {
let top = "module top;\n logic clk;\n sub \nendmodule\n";
let ghost = ghosted("accepted", top, " sub ").expect("a ghost");
assert_eq!(
format!("sub {}", accepted(&ghost, " ", " ")),
"\
sub #(
.WIDTH(${1:8})
) ${2:u_sub} (
.clk(clk),
.data(${3:data}),
.ready(${4:ready})
);"
);
// …and it follows the editor's tabs, not `lucisv.indent`, at any depth.
assert!(accepted(&ghost, "\t\t", "\t").contains("\n\t\t\t.clk(clk),"), "{ghost}");
}
/// What the user ends up with must parse. The typed name, the accepted
/// body, every hole filled in the way the editor preselects it, planted at
/// the item position the gate insisted on.
#[test]
fn the_accepted_ghost_parses_where_it_was_offered() {
for (name, module, files, holes) in [
("ports", "sub", &[("sub.sv", SUB)][..], 4),
("bare", "bare", &[("bare.sv", "module bare;\nendmodule\n")][..], 1),
(
"portless",
"empty",
&[("empty.sv", "module empty #(\n parameter int W = 2\n) ();\nendmodule\n")][..],
2,
),
] {
let top = format!("module top;\n logic clk;\n {module} \nendmodule\n");
let ghost = ghosted_among(name, files, &top, &format!(" {module} ")).expect("a ghost");
assert_eq!(
ghost.matches("${").count(),
holes,
"{module}: every fill-in is a tabstop: {ghost}"
);
// The name, the space that armed the ghost, and the ghost itself —
// which is exactly what the buffer holds after Tab.
let written = filled(&format!("{module} {}", accepted(&ghost, " ", " ")));
let probe = format!("module lucisv_probe;\n logic clk;\n {written}\nendmodule\n");
assert!(
vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
"the accepted text must parse:\n{probe}"
);
}
}
/// The premise the "the accepted text must parse" probe above rests on:
/// the probe can still fail. Header recovery (TODO §32) widened what a
/// tolerant parse reads — a half-typed connection list is now a recovered
/// instantiation rather than a dead item — so the probe is only worth
/// asking while text that does not parse still says so.
#[test]
fn the_accepted_text_probe_still_reports_text_that_does_not_parse() {
let probe = "module lucisv_probe;\n logic clk;\n sub u_sub (.clk(\nendmodule\n";
assert!(
!vlog_parser::parse_source_tolerant(probe).1.is_empty(),
"recovery must not make a broken instantiation look clean"
);
}
#[test]
fn a_module_with_no_ports_ghosts_a_sane_instantiation() {
let top = "module top;\n bare \nendmodule\n";
assert_eq!(
ghosted_among("bareports", &[("bare.sv", "module bare;\nendmodule\n")], top, " bare ")
.as_deref(),
Some("${1:u_bare} ();")
);
}
#[test]
fn a_half_typed_name_ghosts_nothing() {
// The popup is what answers here — with the *name*, which is the whole
// division of labour between the two levels.
let top = "module top;\n logic clk;\n su \nendmodule\n";
assert_eq!(ghosted("partial", top, " su "), None);
// …and one character past the name is not the name either.
let top = "module top;\n logic clk;\n subs \nendmodule\n";
assert_eq!(ghosted("past", top, " subs "), None);
}
#[test]
fn a_case_mismatched_name_ghosts_nothing() {
// The popup's substring match folds case; this one must not. `SUB` is
// not a module any Verilog tool would find.
for typed in ["SUB", "Sub", "sUb"] {
let top = format!("module top;\n logic clk;\n {typed} \nendmodule\n");
assert_eq!(ghosted("case", &top, &format!(" {typed} ")), None, "{typed}");
}
}
#[test]
fn a_name_the_workspace_does_not_declare_as_a_module_ghosts_nothing() {
let files = &[("sub.sv", SUB), ("p.sv", "package pkg;\n localparam int W = 1;\nendpackage\n")];
for typed in ["pkg", "W", "clk", "nothing_at_all"] {
let top = format!("module top;\n logic clk;\n {typed} \nendmodule\n");
assert_eq!(
ghosted_among("nonmodule", files, &top, &format!(" {typed} ")),
None,
"{typed} is not a module"
);
}
}
#[test]
fn anything_after_the_cursor_on_the_line_ghosts_nothing() {
// The rest-of-line rule the templates already live by: a name with a
// `;` after it is code the user has finished writing.
let top = "module top;\n logic clk;\n sub u_sub ();\nendmodule\n";
assert_eq!(ghosted("after", top, " sub "), None);
}
#[test]
fn a_name_that_is_not_at_item_position_ghosts_nothing() {
// Every one of these spells `sub` exactly and none of them is a place
// an instantiation may be written. The gate is `completion.rs`'s own,
// so this is the ghost inheriting the popup's answer rather than
// inventing a second one.
for (name, top, needle) in [
("connection", "module top;\n other u (.aes(sub \nendmodule\n", ".aes(sub "),
("assign", "module top;\n wire x;\n assign x = sub \nendmodule\n", "= sub "),
("declaration", "module top;\n logic sub \nendmodule\n", "logic sub "),
("procedural", "module top;\n initial begin\n sub \n end\nendmodule\n", " sub "),
(
"function",
"module top;\n function int f();\n sub \n endfunction\nendmodule\n",
" sub ",
),
("file scope", "sub \nmodule top;\nendmodule\n", "sub "),
("port list", "module top (sub \n);\nendmodule\n", "top (sub "),
] {
assert_eq!(ghosted("position", top, needle), None, "{name}: {top}");
}
}
#[test]
fn a_generate_block_is_still_item_position_for_the_ghost() {
let top = "module top;\n logic clk;\n generate\n sub \n endgenerate\nendmodule\n";
assert_eq!(ghosted("gen", top, " sub ").as_deref(), Some(SUB_GHOST));
}
#[test]
fn a_module_name_in_a_comment_or_a_string_ghosts_nothing() {
// A token property, not a check of this module's own: a comment is
// lexer trivia and never a token, and a string literal is one `String`
// token whose kind is not `Ident`.
let top = "module top;\n // sub \nendmodule\n";
assert_eq!(ghosted("comment", top, "// sub "), None);
let top = "module top;\n initial $display(\"sub \nendmodule\n";
assert_eq!(ghosted("string", top, "\"sub "), None);
}
#[test]
fn a_buffer_that_does_not_lex_ghosts_nothing() {
let top = "module top;\n /* unterminated\n sub \n";
let (_tree, ws, uri, position) = workspace("nolex", &[("sub.sv", SUB)], top, " sub ");
assert!(ws.document(&uri).expect("open").tokens.is_empty(), "premise: no tokens");
assert!(inline_completions(&ws, &uri, position).is_none());
}
#[test]
fn an_exact_name_at_the_true_end_of_the_file_still_ghosts() {
// The `Eof` sentinel shares the last real token's end, so the same
// skip the templates needed (QA find, 2026-08-25) is what lets a name
// typed as the buffer's very last bytes answer.
// True EOF is now the buffer ending with the *space*: the name plus
// the keystroke that arms it, with nothing after either.
let top = "module top;\n logic clk;\n sub ";
assert_eq!(ghosted("eof", top, " sub ").as_deref(), Some(SUB_GHOST));
}
/// opentitan's `ast_dft` and `io_osc` in miniature: one module, one copy
/// under each of two tops, with headers that differ so the ghost says which
/// copy it read.
const TWO_TOPS: &[(&str, &str)] = &[
("top_earlgrey/ast_dft.sv", "module ast_dft (input logic clk_earlgrey);\nendmodule\n"),
("top_darjeeling/ast_dft.sv", "module ast_dft (input logic clk_darjeeling);\nendmodule\n"),
];
/// What each copy of `ast_dft` ghosts. Neither port is declared in the
/// asking buffer, so neither auto-connects and the port name is visible in
/// the hole — which is how these tests tell the two copies apart.
const EARLGREY_GHOST: &str = "${1:u_ast_dft} (\n\t.clk_earlgrey(${2:clk_earlgrey})\n);";
const DARJEELING_GHOST: &str = "${1:u_ast_dft} (\n\t.clk_darjeeling(${2:clk_darjeeling})\n);";
#[test]
fn a_module_declared_twice_ghosts_the_copy_nearest_the_buffer() {
// Round 1 gave a twice-declared module no ghost at all:
// `module_definition` refuses to guess which file to read, and the
// ghost inherited the refusal. In opentitan that silenced `ast_dft`
// and `io_osc`, each declared once under `hw/top_earlgrey/ip/ast/rtl`
// and once under `hw/top_darjeeling/ip/ast/rtl` — two whole IP blocks.
// Owner ruling, 2026-08-30: every indexed module expands, so the
// server chooses the copy whose path shares the longest run of leading
// path components with the buffer asking.
let top = "module top;\n ast_dft \nendmodule\n";
assert_eq!(
ghosted_at("earlgrey", TWO_TOPS, "top_earlgrey/top.sv", top, " ast_dft ").as_deref(),
Some(EARLGREY_GHOST),
"a buffer under top_earlgrey gets top_earlgrey's copy"
);
assert_eq!(
ghosted_at("darjeeling", TWO_TOPS, "top_darjeeling/top.sv", top, " ast_dft ").as_deref(),
Some(DARJEELING_GHOST),
"…and one under top_darjeeling gets the other"
);
}
#[test]
fn a_buffer_near_neither_copy_gets_the_lexicographically_smaller_path() {
// No shared prefix to rank by, so the tie-break decides — and it is a
// property of the paths rather than of the order the index was built
// in, which is what makes it reproducible. `top_darjeeling` sorts
// before `top_earlgrey`.
let top = "module top;\n ast_dft \nendmodule\n";
assert_eq!(
ghosted_at("neither", TWO_TOPS, "elsewhere/top.sv", top, " ast_dft ").as_deref(),
Some(DARJEELING_GHOST)
);
}
#[test]
fn the_two_copies_may_have_different_headers_and_the_nearest_one_wins() {
// The accepted semantics, written down: the copies are not required to
// agree, and the user gets the one their own file is nearest to. Here
// one copy has a parameter the other has not, so the two ghosts do not
// even have the same shape.
let files = &[
("top_a/dup.sv", "module dup #(\n parameter int W = 4\n) (input logic a);\nendmodule\n"),
("top_b/dup.sv", "module dup (input logic b);\nendmodule\n"),
];
let top = "module top;\n dup \nendmodule\n";
assert_eq!(
ghosted_at("hdr_a", files, "top_a/top.sv", top, " dup ").as_deref(),
Some("#(\n\t.W(${1:4})\n) ${2:u_dup} (\n\t.a(${3:a})\n);")
);
assert_eq!(
ghosted_at("hdr_b", files, "top_b/top.sv", top, " dup ").as_deref(),
Some("${1:u_dup} (\n\t.b(${2:b})\n);")
);
}
#[test]
fn a_plan_with_an_escaped_identifier_gets_no_ghost() {
// An escaped identifier may legally contain `$`, `}` and `\` — the
// snippet grammar's own punctuation — and the names are written by the
// layout, outside every hole, where no escaping can reach them. The
// popup answered this with a plain-text item; an inline completion has
// no plain-text spelling, so it answers with nothing.
let files =
&[("odd.sv", "module odd (input logic \\my-port$1 , input logic clk);\nendmodule\n")];
let top = "module top;\n logic clk;\n odd \nendmodule\n";
assert_eq!(ghosted_among("escaped", files, top, " odd "), None);
}
#[test]
fn a_module_may_ghost_itself() {
// Cursor inside `top`, typing `top`. The plan is real — `top` is a
// module the workspace declares and the instantiation is legal
// Verilog — so it is offered. Whether instantiating yourself is a good
// idea is the user's business; an elaborator will tell them soon
// enough, and refusing would be this server having an opinion about
// recursion that it cannot back up (a `generate` guarded by a
// parameter is a legitimate recursive structure).
let top = "module top (input logic clk);\n top \nendmodule\n";
assert_eq!(ghosted("self", top, " top ").as_deref(), Some("${1:u_top} (\n\t.clk(clk)\n);"));
}
#[test]
fn the_setting_turns_the_instantiation_ghost_off_and_leaves_the_templates_on() {
let top = "module top;\n logic clk;\n sub \nendmodule\n";
let (_tree, mut ws, uri, position) = workspace("setting", &[("sub.sv", SUB)], top, " sub ");
assert!(inline_completions(&ws, &uri, position).is_some(), "premise: on by default");
ws.set_client_settings(ClientSettings {
inline_instantiation: Some(false),
..Default::default()
});
assert!(inline_completions(&ws, &uri, position).is_none());
ws.set_client_settings(ClientSettings {
inline_instantiation: Some(true),
..Default::default()
});
assert!(inline_completions(&ws, &uri, position).is_some(), "and back on again");
// The two settings are independent in both directions: the templates
// answer with the instantiation off, and the reverse.
let (_tree, mut ws, uri, position) =
workspace("both", &[("sub.sv", SUB)], "module top;\n always_comb begin\n", "begin");
ws.set_client_settings(ClientSettings {
inline_instantiation: Some(false),
..Default::default()
});
assert!(
inline_completions(&ws, &uri, position).is_some(),
"a template is not an offer \
the instantiation setting governs"
);
let top = "module top;\n logic clk;\n sub \nendmodule\n";
let (_tree, mut ws, uri, position) = workspace("tmploff", &[("sub.sv", SUB)], top, " sub ");
ws.set_client_settings(ClientSettings { inline_templates: Some(false), ..Default::default() });
assert!(inline_completions(&ws, &uri, position).is_some(), "…and the other way round");
}
#[test]
fn the_only_residue_over_a_workspace_is_the_escaped_identifier() {
// Round 2, part C: after the space-armed trigger and the
// nearest-definition chooser, the reasons an indexed module does *not*
// ghost have to be enumerable — so a sweep over every module a
// workspace declares can bucket its misses by reason instead of
// shrugging at them. This is that sweep in miniature, over a workspace
// carrying one of every shape the planner meets: parameters and ports,
// neither, parameters only, a non-ANSI port list, a name two files
// declare, and the one shape that genuinely cannot be ghosted.
let files = &[
("sub.sv", SUB),
("bare.sv", "module bare;\nendmodule\n"),
("empty.sv", "module empty #(\n parameter int W = 2\n) ();\nendmodule\n"),
("nonansi.sv", "module nonansi (a, b);\n input wire a;\n output wire b;\nendmodule\n"),
("odd.sv", "module odd (input logic \\my-port$1 , input logic clk);\nendmodule\n"),
("top_a/dup.sv", "module dup (input logic a);\nendmodule\n"),
("top_b/dup.sv", "module dup (input logic b);\nendmodule\n"),
];
let top = "module top;\n logic clk;\n probe \nendmodule\n";
let (_tree, ws, uri, _) = workspace("residue", files, top, " probe ");
let doc = ws.document(&uri).expect("open");
let at = top.find(" probe").expect("the probe line") as u32 + 2;
let modules: Vec<String> =
ws.candidates().modules("").iter().map(|name| name.to_string()).collect();
assert!(modules.len() >= 7, "premise: the sweep really covers the workspace: {modules:?}");
let refused: Vec<(&str, NoGhost)> = modules
.iter()
.filter_map(|module| {
instantiation_ghost(&ws, doc, module, at).err().map(|why| (module.as_str(), why))
})
.collect();
assert_eq!(
refused,
vec![("odd", NoGhost::EscapedIdentifier)],
"the residue is the escaped identifier and nothing else"
);
}
#[test]
fn the_instantiation_wire_shape_is_one_snippet_item_at_the_cursor() {
let top = "module top;\n logic clk;\n sub \nendmodule\n";
let (_tree, ws, uri, position) = workspace("wire", &[("sub.sv", SUB)], top, " sub ");
let items = inline_completions(&ws, &uri, position).expect("a ghost");
assert_eq!(
serde_json::to_value(&items).expect("serializes"),
serde_json::json!({
"items": [{
"insertText": { "kind": "snippet", "value": SUB_GHOST },
"range": {
"start": { "line": 2, "character": 6 },
"end": { "line": 2, "character": 6 }
}
}]
})
);
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com