Files
lucisv/crates/lucisv_server/src/inline.rs
T
lucioandClaude Mythos 5.2 c1076f9405 TODO §68.1: begin+Enter writes the end, clock+reset templates, this file's names first, keyword ghosts, port items that write .name()
Server (lucisv_server only): on_type/auto_end.rs — the newline answer
adds the owed end at the owning statement's indentation (lucisv.autoEnd);
always_ff @( / always @( ghosts and popup templates lead with posedge clk
or negedge rst_n; completion tiers put names declared and used in this
buffer ahead of the index, templates and keywords (completion/buffer.rs);
inline/keywords.rs ghosts the rest of a keyword and follows the popup's
selected entry (lucisv.inlineKeywords); connection items keep connected
ports as a second group marked 'connected' and insert name($1), pre-filled
with a same-named signal (completion/connection.rs).
Extension: typing.js sends the newline on-type request itself when
editor.formatOnType is off and restores the cursor; the inline-completion
context is converted to LSP shapes.
Dev + QA (Opus 5.5) + one fix round; unit 1823, e2e 102, node 9 files,
smoke OK. Not yet seen in a running VS Code.
docs/features/completion-ux.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-17 14:39:32 -08:00

2312 lines
101 KiB
Rust

//! `textDocument/inlineCompletion` — the ghost text that finishes a block as
//! you open it, and the instantiation that follows a module's name.
//!
//! Type `if (` and grey `) begin … end` follows the cursor; type `begin` at the
//! end of a line and its `end` does. Accepting one is a snippet insertion, so
//! the tabstops land the cursor inside the parens first and on the indented
//! body line second.
//!
//! Type the whole name of a module the workspace declares **and a space**,
//! somewhere an instantiation may be written, and the rest of the
//! instantiation follows the same way: every parameter, every port, each a
//! tabstop. That is the second level of the two the completion popup's module
//! tier is the first of — the popup offers *names*, cheaply, and exactly one
//! name is ever planned. The space is what says the name is finished: `aes`
//! alone may still be growing into `aes_dft` (owner ruling, 2026-08-30). See
//! `docs/features/inline-instantiation/README.md`.
//!
//! Three things here are deliberate. The **triggers are data** — a keyword, the
//! punctuation that must follow it, the dialect it belongs to, the check that
//! says the construct is still unfinished, and one body per item in
//! `templates.rs`'s `(steps, text)` form. The **response types are
//! hand-rolled**: `lsp_types`' `InlineCompletionItem` is the old 3.18 draft
//! (`insertText: String`), while the client in use implements the newer one,
//! where only `insertText: {"kind": "snippet", "value": …}` becomes a snippet
//! and a bare string is inserted as plain text — tabstops and all. And the
//! bodies are **indented relative to the trigger line, one `\t` per step**,
//! because the editor prepends that line's own indentation when it inserts the
//! snippet; see `render`. See `docs/features/inline-templates/README.md`.
use lsp_types::{Position, Range, SelectedCompletionInfo, Uri};
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::TextRange;
use vlog_refactor::{Layout, Site};
use crate::completion;
use crate::on_type;
use crate::pairs;
use crate::state::{Document, Workspace};
use crate::templates::{self, Dialect};
mod keywords;
/// One line of a body: how many indent steps it sits in, and its text. The
/// same shape `templates.rs` writes its skeletons in.
type Line = (u8, &'static str);
/// What must still be unfinished before a trigger offers anything.
///
/// None of these is a parse, and none can see inside a `` `ifdef `` arm or a
/// macro body. Being wrong costs one grey suggestion the user ignores: nothing
/// is written to the buffer until Tab.
#[derive(Clone, Copy)]
enum Unclosed {
/// The `(` just typed is never closed. The snippet writes the `)`, so it
/// may only be offered when one is owed.
Paren,
/// `pairs::analyze` reports *this* keyword — matched by its own span, not
/// by a global count — as an opener that never closed.
Scope,
/// Both, for a body that writes a `)` *and* a scope closer: `case (`
/// finishes with `endcase`, so a `case` that already has one must not be
/// given a second.
ParenAndScope,
}
/// One inline template: what the user must have just typed, and what appears
/// behind the cursor when they have.
struct Trigger {
/// The keyword that opens the construct.
keyword: &'static str,
/// The punctuation that must follow the keyword, in order. `if (` needs the
/// open paren — it is what says the user has committed to the `if` rather
/// than to an identifier starting with those letters — `always @(` needs
/// both of its symbols, and `begin` stands alone.
opener: &'static [&'static str],
/// The dialect this body belongs to, when it is not legal in both.
dialect: Option<Dialect>,
gate: Unclosed,
/// One skeleton per item offered, in the order the client cycles them.
/// Each is written exactly as a `templates.rs` body is: the first line
/// starts at the cursor and every later one is indented.
bodies: &'static [&'static [Line]],
}
/// The opener of a construct whose header is parenthesised.
const PAREN: &[&str] = &["("];
/// The opener of an `always`-family block: the event-control `@(`.
const EVENT: &[&str] = &["@", "("];
/// What `case (`, `casez (` and `casex (` all finish with — the user has
/// already typed the keyword, so one body serves the three.
const CASE_BODY: &[Line] =
&[(0, "${1:sel})"), (1, "${2:value}: $0;"), (1, "default: ;"), (0, "endcase")];
/// The bodies of the keywords that stand alone. Everything each offers goes on
/// the lines *after* the word the user just typed, so the first line is empty.
const BEGIN_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "end")];
const FORK_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "join")];
const GENERATE_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "endgenerate")];
/// The event control of a flop with an async active-low reset, both edges a
/// tabstop. First in both `always` families (TODO §68.1): the commoner flop.
const CLOCK_AND_RESET: &[Line] =
&[(0, "posedge ${1:clk} or negedge ${2:rst_n}) begin"), (1, "$0"), (0, "end")];
/// The clock-only event control, one cycle away.
const CLOCK_ONLY: &[Line] = &[(0, "posedge ${1:clk}) begin"), (1, "$0"), (0, "end")];
/// Every construct that offers ghost text.
///
/// The order is the order `triggered` tries them, which only matters when two
/// entries could match the same tokens: the two `for` bodies are told apart by
/// their dialect, and nothing else overlaps.
const TRIGGERS: &[Trigger] = &[
Trigger {
keyword: "if",
opener: PAREN,
dialect: None,
gate: Unclosed::Paren,
bodies: &[&[(0, "${1:cond}) begin"), (1, "$0"), (0, "end")]],
},
Trigger {
keyword: "while",
opener: PAREN,
dialect: None,
gate: Unclosed::Paren,
bodies: &[&[(0, "${1:cond}) begin"), (1, "$0"), (0, "end")]],
},
Trigger {
keyword: "for",
opener: PAREN,
dialect: Some(Dialect::SystemVerilog),
gate: Unclosed::Paren,
bodies: &[&[(0, "int ${1:i} = 0; $1 < ${2:N}; $1++) begin"), (1, "$0"), (0, "end")]],
},
Trigger {
keyword: "for",
opener: PAREN,
dialect: Some(Dialect::Verilog),
gate: Unclosed::Paren,
bodies: &[&[(0, "${1:i} = 0; $1 < ${2:N}; $1 = $1 + 1) begin"), (1, "$0"), (0, "end")]],
},
Trigger {
keyword: "case",
opener: PAREN,
dialect: None,
gate: Unclosed::ParenAndScope,
bodies: &[CASE_BODY],
},
Trigger {
keyword: "casez",
opener: PAREN,
dialect: None,
gate: Unclosed::ParenAndScope,
bodies: &[CASE_BODY],
},
Trigger {
keyword: "casex",
opener: PAREN,
dialect: None,
gate: Unclosed::ParenAndScope,
bodies: &[CASE_BODY],
},
Trigger {
keyword: "always_ff",
opener: EVENT,
dialect: Some(Dialect::SystemVerilog),
gate: Unclosed::Paren,
bodies: &[CLOCK_AND_RESET, CLOCK_ONLY],
},
Trigger {
keyword: "always",
opener: EVENT,
dialect: None,
gate: Unclosed::Paren,
// Three items, clocked first: `always @(` is overwhelmingly a flop,
// and the client cycles to the next with one keystroke.
bodies: &[CLOCK_AND_RESET, CLOCK_ONLY, &[(0, "*) begin"), (1, "$0"), (0, "end")]],
},
Trigger {
keyword: "begin",
opener: &[],
dialect: None,
gate: Unclosed::Scope,
bodies: &[BEGIN_BODY],
},
Trigger {
keyword: "fork",
opener: &[],
dialect: None,
gate: Unclosed::Scope,
bodies: &[FORK_BODY],
},
Trigger {
keyword: "generate",
opener: &[],
dialect: None,
gate: Unclosed::Scope,
bodies: &[GENERATE_BODY],
},
Trigger {
keyword: "module",
opener: &[],
dialect: None,
gate: Unclosed::Scope,
// The leading space and the `;` are what make the accepted text parse:
// a module header needs a name, and a placeholder cannot supply one
// after the fact.
bodies: &[&[(0, " ${1:name};"), (1, "$0"), (0, "endmodule")]],
},
];
/// The LSP 3.18 `StringValue` — the only spelling of an inline completion's
/// text that a client turns into a snippet with working tabstops.
#[derive(serde::Serialize)]
pub struct SnippetValue {
/// Always `"snippet"`. Spelled as a field rather than inferred, because
/// the client's check is `typeof insertText === 'string'` and the object
/// arm is what carries the contract.
kind: &'static str,
value: String,
}
/// One inline completion item on the wire.
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InlineItem {
insert_text: SnippetValue,
/// What the item replaces. Always empty and always at the cursor: this
/// inserts, it never replaces, and the protocol requires a range to begin
/// and end on one line.
range: Range,
}
/// The `textDocument/inlineCompletion` result. The list form rather than a
/// bare array, so a later round can add a field beside `items`.
#[derive(serde::Serialize)]
pub struct InlineItems {
pub items: Vec<InlineItem>,
}
/// The ghost text to show at a position, or nothing.
///
/// `None` rather than an empty list wherever there is nothing to say: an
/// editor treats both the same, and `null` is the cheaper answer to a request
/// that arrives on every keystroke.
///
/// `selected` is the request's `context.selectedCompletionInfo` — the popup's
/// selected entry, when one is showing. Only the keyword ghost reads it.
pub fn inline_completions_in_context(
ws: &Workspace,
uri: &Uri,
position: Position,
selected: Option<&SelectedCompletionInfo>,
) -> Option<InlineItems> {
let doc = ws.document(uri)?;
// No token stream, no answer — the same trade `completion.rs` makes. A
// half-typed string or block comment is what breaks the lexer, and those
// are exactly the places a ghost `end` would be wrong.
if doc.tokens.is_empty() {
return None;
}
let offset = doc.positions().offset(position);
if !rest_of_line_is_blank(&doc.text, offset) {
return None;
}
let at = Range { start: position, end: position };
// Two ghosts, told apart by the shape of the text just before the cursor.
// An identifier followed by exactly one space may be a module name the
// user has committed to; a token ending *at* the cursor may open a
// construct. No keystroke reaches both — a space is not a token, so
// nothing ends at the cursor when one was just typed — and each carries
// its own setting, so a user who turned one off still has the other.
if let Some(name) = name_then_space(doc, offset) {
return instantiation(ws, doc, name, at);
}
let last = last_token(doc, offset)?;
// A name with nothing after it is not an instantiation offer (owner
// ruling, 2026-08-30): `aes` may still be growing into `aes_dft`, and the
// space is the user saying that it is not. No trigger's own last token is
// an `Ident` either, so only the keyword ghost is asked about one.
if doc.tokens.get(last)?.kind != TokenKind::Ident {
if let Some(items) = template(ws, doc, last, at) {
return Some(items);
}
}
// The fallback: the rest of a keyword the word is a proper prefix of.
keywords::keyword_ghost(ws, doc, last, position, selected)
}
/// [`inline_completions_in_context`] with no popup open — what every test
/// that is not about the popup asks.
#[cfg(test)]
pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Option<InlineItems> {
inline_completions_in_context(ws, uri, position, None)
}
/// The identifier the user has just finished and armed with a space: the token
/// ending exactly at `offset - 1`, when that byte is a space and the byte
/// before it is not.
///
/// **One space, and the one just typed.** Two of them is not "you have just
/// finished the name" — it is a cursor parked in whitespace — and the crisp
/// rule is what keeps the ghost from appearing at every idle position on a
/// blank-ish line. A tab is not a space either: only the character a user types
/// after a module name arms this.
fn name_then_space(doc: &Document, offset: u32) -> Option<usize> {
let space = offset.checked_sub(1)?;
let bytes = doc.text.as_bytes();
if bytes.get(space as usize) != Some(&b' ') {
return None;
}
if space > 0 && bytes.get(space as usize - 1) == Some(&b' ') {
return None;
}
let index = last_token(doc, space)?;
(doc.tokens.get(index)?.kind == TokenKind::Ident).then_some(index)
}
/// The block-opening ghost: the trigger table, its gate, and one item per
/// body.
fn template(ws: &Workspace, doc: &Document, last: usize, at: Range) -> Option<InlineItems> {
if !ws.client_settings().inline_templates.unwrap_or(true) {
return None;
}
let (trigger, opened) = triggered(doc, last)?;
if !unfinished(doc, trigger, opened, last) {
return None;
}
Some(InlineItems {
items: trigger
.bodies
.iter()
.map(|body| InlineItem {
insert_text: SnippetValue { kind: "snippet", value: render(body) },
range: at,
})
.collect(),
})
}
/// The instantiation ghost: everything but the name of the module the user has
/// just finished spelling, and the space they armed it with.
///
/// The order of the questions is the feature. A keystroke that is not an exact
/// module name — which is nearly every keystroke — costs one binary search in
/// a table (`Candidates::has_module`) and stops there: no scope chain is built,
/// no file is opened, nothing is parsed. Only an exact match pays for the
/// position gate, and only a gated exact match pays for a plan.
///
/// The gate is asked at the **name's own start**, not at the cursor: the space
/// is the arming keystroke, and the instantiation would still be written where
/// the name begins.
fn instantiation(ws: &Workspace, doc: &Document, last: usize, at: Range) -> Option<InlineItems> {
if !ws.client_settings().inline_instantiation.unwrap_or(true) {
return None;
}
let name = doc.tokens.get(last)?;
if !ws.candidates().has_module(&name.text) {
return None;
}
if !completion::at_instantiation_site(doc, name.span.start) {
return None;
}
let value = instantiation_ghost(ws, doc, &name.text, name.span.start).ok()?;
Some(InlineItems {
items: vec![InlineItem { insert_text: SnippetValue { kind: "snippet", value }, range: at }],
})
}
/// Why a module the workspace really declares has no ghost behind it.
///
/// **The residue, enumerated.** Since round 2 the ghost no longer declines
/// because a name is declared twice — `completion::nearest_definition` chooses
/// — so what is left is this list and nothing else, and a sweep over a whole
/// workspace can bucket its misses by reason instead of shrugging at them.
/// `the_only_residue_over_a_workspace_is_the_escaped_identifier` is that sweep
/// in miniature.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NoGhost {
/// The index names no module by this name whose declaring file it can
/// place — the caller's `has_module` probe and the index disagreeing,
/// which only a scope change mid-request can produce.
Undeclared,
/// The declaring file could not be read.
Unreadable,
/// Neither the header slice nor the whole file planned: the definition is
/// written in syntax this parser does not read as a module header.
Unplannable,
/// The plan carries an **escaped identifier**, which may legally contain
/// `$`, `}` and `\` — the snippet grammar's own punctuation — written by
/// the layout where no per-hole escaping can reach it. The popup's answer
/// to that was a plain-text item; an inline completion has no plain-text
/// spelling to fall back to (there is no `snippetSupport` to negotiate on
/// this request), so the honest answer is no ghost at all.
EscapedIdentifier,
/// The rendered skeleton did not begin with the module's name and exactly
/// one space, so there is nothing to cut off its front. Unreachable with
/// today's layout and pinned as such
/// (`the_rendered_skeleton_really_does_put_one_space_after_the_name`); it
/// is here so a change to `vlog_refactor`'s spelling fails loudly in a
/// sweep rather than silently truncating a ghost.
UnexpectedLayout,
}
/// The instantiation of `module` as it appears behind the cursor: the
/// skeleton `completion.rs` plans, laid out **relatively**, with the name the
/// user has already typed *and the space after it* cut off the front.
fn instantiation_ghost(
ws: &Workspace,
doc: &Document,
module: &str,
at: u32,
) -> Result<String, NoGhost> {
let path = completion::nearest_definition(ws.index(), module, doc.path.as_deref())
.ok_or(NoGhost::Undeclared)?;
let site = Site { semantics: &doc.semantics, offset: at };
// A closed file goes through the view cache, so holding the cursor on a
// name — every keystroke of which re-asks this question — reads the disk
// once. An open one has no view by design: its buffer is the authority.
let plan = match ws.file_view(path) {
Some(view) => completion::plan_for(ws.index(), module, &view.text, site),
None => {
let text = ws.text_of(path).ok_or(NoGhost::Unreadable)?;
completion::plan_for(ws.index(), module, &text, site)
}
}
.map_err(|_| NoGhost::Unplannable)?;
if plan.has_escaped_identifier() {
return Err(NoGhost::EscapedIdentifier);
}
let skeleton = plan.render_with(&relative(), &mut completion::snippet_hole);
// The user typed the name and the space; the ghost is what follows both.
// The same "cut off what is already there" rule every trigger above
// follows — the layout writes exactly one space between the module's name
// and whatever comes next, whether that is a `#(` or an instance name.
skeleton
.strip_prefix(module)
.and_then(|rest| rest.strip_prefix(' '))
.map(str::to_string)
.ok_or(NoGhost::UnexpectedLayout)
}
/// The layout an inline completion is written in: no base at all, one `\t` per
/// step.
///
/// The [`render`] contract, in the shape `vlog_refactor` renders a plan
/// through. A `base` here would be the site's own indentation baked in, which
/// is exactly the double-indentation bug `render`'s doc comment describes; a
/// step of anything but `\t` would be this server deciding how wide the user's
/// tab stops are, which the editor re-spells anyway.
fn relative() -> Layout {
Layout { base: String::new(), step: "\t".to_string() }
}
/// The two tokens a gate can ask about: the keyword that opens the construct,
/// and the last token the user typed — the `(` whenever the trigger has one.
#[derive(Clone, Copy)]
struct Opened {
keyword: TextRange,
last: TextRange,
}
/// The token the user has just finished typing: the last one that is not the
/// `Eof` sentinel, and only when it ends **exactly** at the cursor.
///
/// That equality is the crisp "you just typed this" rule, and it is what keeps
/// a body's first character from landing after stray spaces. It is also what
/// makes a comment or a string safe without a single check of its own — a
/// comment is lexer trivia and never a token, and `"if ("` is one `String`
/// token whose text is not a keyword.
fn last_token(doc: &Document, offset: u32) -> Option<usize> {
// `Eof` is a zero-width sentinel `tokenize` appends at `text.len()`, so
// when the buffer's very last byte is the trigger's own last character —
// no trailing newline, nothing typed after it yet — it shares the
// trigger token's `span.end`. Skipping it here is what lets a trigger at
// the true end of the file still fire (QA find, 2026-08-25).
//
// Token ends rise across the vector, so the tokens ending at or before
// `offset` are a prefix of it: no token outside that prefix could have
// satisfied the reverse sweep this replaced, and inside it the sweep's
// remaining condition is the `Eof` test alone.
let reached = doc.tokens.partition_point(|token| token.span.end <= offset);
let index = doc.tokens[..reached].iter().rposition(|token| token.kind != TokenKind::Eof)?;
(doc.tokens.get(index)?.span.end == offset).then_some(index)
}
/// The trigger the token at `index` and its neighbours spell, and the spans
/// its gate needs.
fn triggered(doc: &Document, index: usize) -> Option<(&'static Trigger, Opened)> {
let last = doc.tokens.get(index)?;
let dialect = templates::dialect(doc.path.as_deref());
for trigger in TRIGGERS {
if matches!(trigger.dialect, Some(only) if only != dialect) {
continue;
}
let Some(at) = index.checked_sub(trigger.opener.len()) else { continue };
let spelled = trigger
.opener
.iter()
.enumerate()
.all(|(i, sym)| doc.tokens.get(at + 1 + i).is_some_and(|t| t.is_sym(sym)));
if !spelled {
continue;
}
let Some(keyword) = doc.tokens.get(at) else { continue };
if keyword.kind == TokenKind::Keyword && keyword.text == trigger.keyword {
return Some((trigger, Opened { keyword: keyword.span, last: last.span }));
}
}
None
}
/// Whether the construct the user opened really is still waiting to be closed.
///
/// `last` is the index of the token just typed — for `begin`, the keyword
/// itself, which is asked the auto-`end` question (`on_type::auto_end`)
/// rather than "is this span unmatched": a `begin` typed inside a balanced
/// block steals that block's `end` in the stack matcher, and would otherwise
/// get no ghost (`completion-ux` fix round, 2026-11-17).
fn unfinished(doc: &Document, trigger: &Trigger, opened: Opened, last: usize) -> bool {
let paren = || !paren_is_closed(&doc.tokens, opened.last);
let scope = || {
pairs::analyze(&doc.tokens).unmatched_open.iter().any(|open| open.span == opened.keyword)
};
match trigger.gate {
Unclosed::Paren => paren(),
Unclosed::Scope if trigger.keyword == "begin" => on_type::begin_owes_an_end(doc, last),
Unclosed::Scope => scope(),
// The paren check first: it is a flat pass over the tokens, and
// skipping `pairs::analyze` when it already says no is what keeps this
// cheap on a keystroke.
Unclosed::ParenAndScope => paren() && scope(),
}
}
/// Whether the `(` at `open` is ever popped by a `)`.
///
/// A stack rather than a count, for the same reason `pairs::analyze` is one: a
/// `)` further down the buffer usually belongs to a `(` of its own, and a
/// running total would let `x = f(1);` on the next line cancel the paren the
/// user just typed.
fn paren_is_closed(tokens: &[Token], open: TextRange) -> bool {
let mut stack: Vec<TextRange> = Vec::new();
for token in tokens {
if token.is_sym("(") {
stack.push(token.span);
} else if token.is_sym(")") && stack.pop() == Some(open) {
return true;
}
}
false
}
/// Whether everything after `offset` on its line is whitespace.
///
/// A trailing `)` or `;` means the line is already finished and the user is
/// editing inside it, not opening a block.
fn rest_of_line_is_blank(text: &str, offset: u32) -> bool {
let Some(tail) = text.get(offset as usize..) else { return false };
let line = tail.split('\n').next().unwrap_or("");
line.chars().all(char::is_whitespace)
}
/// A body as a snippet: **relative** indentation, one `\t` per step, and no
/// trace of where in the file it is going.
///
/// This is not the layout `templates.rs` renders, and the difference is the
/// whole of the 0.6.0 misalignment bug. VS Code inserts an accepted inline
/// completion through `SnippetController2.insert`, whose `adjustWhitespace`
/// option defaults to `true`, and `SnippetSession.adjustWhitespace` then does
/// two things to the snippet text: it prepends the insertion line's own
/// leading whitespace to every line after the first, and it runs each result
/// through `TextModel.normalizeIndentation`, which rewrites the leading
/// whitespace run in the editor's own tabs-or-spaces. A body that had already
/// baked the line's indentation in came out at *twice* it, with the `end` two
/// levels left of the body instead of level with its opener.
///
/// So the server says "one step in" and the editor says where and how wide:
/// `\t` is the one character `normalizeIndentation` re-spells as the user's
/// own `editor.tabSize`/`insertSpaces`. The consequence is that `lucisv.indent`
/// does **not** decide the width of an accepted snippet — the editor's
/// settings do, which is the more correct answer for text the editor is
/// writing. There is no plain-text spelling here: unlike a completion item, an
/// inline completion has no `snippetSupport` to negotiate.
fn render(body: &[Line]) -> String {
let mut lines: Vec<String> = Vec::with_capacity(body.len());
for (index, (level, text)) in body.iter().enumerate() {
let mut line = String::new();
// The first line starts at the cursor, which the editor has already
// indented and which `adjustWhitespace` leaves alone.
if index > 0 {
for _ in 0..*level {
line.push('\t');
}
}
line.push_str(text);
lines.push(line);
}
lines.join("\n")
}
#[cfg(test)]
mod tests {
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 }
}
}]
})
);
}
}