Files
lucisv/crates/lucisv_server/src/completion.rs
T
lucioandClaude Fable 5 2734885f2b Covergroup bodies: coverpoints, bins, transitions and crosses are real code - 544 of 544 on opentitan, zero fallbacks
TODO section 21, round 2 of coverage_gaps C1, closing it. A covergroup
was a flat token scan into verbatim text; now ItemKind::Covergroup with
CoverItemKind::{Coverpoint, Cross, Option, Directive, Empty}, BinDecl
(wildcard, kind, array, spec: Values / Transitions / Default /
DefaultSequence / Select, with, iff) and SelectExpr for binsof ...
intersect ... && !binsof - behind the same Rewind fallback as
constraints (v0.27.0's scan re-run character for character on any
failure), no keywords reserved. The bin '(' ambiguity is settled by
position, the LRM's own rule, which replaced a lookahead scan and took
the fallback count to zero. Two guards in shared expression machinery -
an index cannot begin with *, -> or =; a bin's own with (...) filter is
not an array-method iterator argument - both attacked across the corpus
and the opentitan tree. Canonical layout, verify.rs untouched, thirteen
attack pairs. Every sampled expression binds to the class's properties;
cg_inst.cp resolves cross-file; FACTS_FORMAT 11 -> 12. The gap fuzzer
was built in from day one and its classification is asserted, not
claimed.

Opentitan: 544/544 structured, 87/87 DV covergroup files idempotent
with comment streams byte-identical, sweep and per-file diagnostics
identical. Corpus +1139 references, 1135 answered.

docs/features/covergroup-bodies/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 06:01:48 -07:00

4175 lines
188 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! `textDocument/completion` — module hinting, templates, keywords, and every
//! name the project uses.
//!
//! One response, six tiers, ordered by `sortText`:
//!
//! 0. **module names** — at module-item position only, every module the
//! workspace declares whose name contains what is typed. The item inserts
//! the **name alone**; the instantiation follows as ghost text once the
//! name is spelled exactly and a space follows it (`inline.rs`,
//! 2026-08-30);
//! 1. **what is visible here** — the declarations the scope chain at the
//! cursor binds, from this file's `Semantics`;
//! 2. **what the project declares** — packages, their members, typedefs,
//! classes, modules and `` `define`` names, from the workspace index;
//! 3. **templates** — `if`/`case`/`always_ff`/declaration skeletons with
//! tabstops, offered only where the construct may be written;
//! 4. **keywords** — every reserved word `vlog_parser` knows;
//! 5. **project words** — every identifier the in-scope files' *token
//! streams* contain, the rope/VS Code word-completion tier.
//!
//! A name is offered once, by the highest tier that claims it. Nothing is
//! offered inside a comment or a string literal, and nothing that only ever
//! appears inside one is ever a candidate — see `candidates.rs`.
//!
//! **Every tier is a table lookup.** No request here reads a file or parses
//! one, which is what makes the answer affordable on a keystroke in a
//! workspace the size of opentitan. The planning half of the old tier 0 —
//! [`plan_for`] and [`module_header`], still here because they are still the
//! way an instantiation is planned — is now called by `inline.rs` for exactly
//! one module, once the user has spelled its whole name and typed the space
//! that says so.
//!
//! See `docs/features/completion-core/README.md`, for tier 0
//! `docs/features/inline-instantiation/README.md` and
//! `docs/features/refactor-instantiate/README.md`, and for tier 3
//! `docs/features/completion-templates/README.md`.
use std::cmp::Reverse;
use std::collections::HashSet;
use std::path::Path;
use lsp_types::{
CompletionItem, CompletionItemKind, CompletionList, CompletionResponse, CompletionTextEdit,
Documentation, InsertTextFormat, InsertTextMode, MarkupContent, MarkupKind, Position, Range,
TextEdit, Uri,
};
use vlog_parser::token::{Comment, Token, TokenKind};
use vlog_parser::{TextRange, KEYWORDS};
use vlog_refactor::{InstantiationPlan, Layout, Site};
use vlog_semantic::{MemberSite, Semantics, Symbol, SymbolKind, WorkspaceIndex};
use crate::candidates::{rank_cmp, starts_with_ignore_case, Candidate, Query, Score};
use crate::pairs;
use crate::signature;
use crate::state::{first_token_from, Document, Workspace};
use crate::symbols::kind_label;
use crate::templates::{self, Gate, Template};
/// How many items one response carries, over every tier.
///
/// Large enough that an *empty* prefix still reaches the last tier — 64
/// modules plus 181 keywords plus what one scope binds leaves room — and small
/// enough to bound the payload at a few tens of kilobytes. Tiers fill in
/// order, so a truncated list loses the least useful end of it and comes back
/// `isIncomplete`: the protocol's way of saying "ask me again when you have
/// typed more".
const LIMIT: usize = 512;
/// How many module names one response carries.
///
/// Its own cap, below [`LIMIT`], because tier 0 matches a *substring* and so
/// answers far more widely than the prefix tiers: an empty word at item
/// position matches all 1 544 modules of opentitan, and letting one tier fill
/// the whole response would starve the five below it. It no longer bounds any
/// *work* — the tier is a scan of a table and nothing else, where until
/// 2026-08-30 each item cost one file read and one header parse.
const MODULE_LIMIT: usize = 64;
/// How many characters must be typed before a name may match by
/// *subsequence* rather than by prefix.
///
/// **VS Code's own rule**, which is the whole policy of this round: below
/// three characters its widget filters what it holds by prefix, and so does
/// the server; from three up both match by subsequence, so `clkenq` reaches
/// `clk_osc_en_q`. Matching the client is the point — a server that went
/// fuzzy at one character would answer a question the widget then filtered the
/// answer to, and one that never went fuzzy is what this round is fixing.
///
/// The floor is not only manners. A one-character fuzzy query matches most of
/// a workspace, which is a list nobody can read, and it is the one query the
/// character-mask prefilter cannot help with at all — one bit wide, it rejects
/// nothing, so the whole table is scanned. Measured at 2.7 ms over the real
/// opentitan word list against the 0.05 ms `clkenq` costs.
///
/// See `docs/features/fuzzy-completion/README.md`.
const FUZZY_MIN: usize = 3;
/// How far past a module's name [`module_header`] reads looking for the end of
/// its header, smallest first.
///
/// A ladder rather than one bound because the lex is the whole cost of the
/// slice and it is linear in what it is handed, so every header would
/// otherwise pay for the widest one. The rungs come from measuring opentitan's
/// 344 RTL modules: **59% of headers end inside 256 bytes**, 90% inside 2 KB,
/// and the largest — `aes_control_fsm_n`, sixty commented ports — is 6.6 KB.
/// The top rung is well past that, because a rung that is too small is not a
/// wrong answer but a whole-file parse, and for those files that is 2–4 ms
/// against the 0.6 ms of lexing 16 KB.
const HEADER_WINDOWS: [usize; 3] = [256, 2 * 1024, 16 * 1024];
/// `sortText` prefixes. The client sorts on these, so they *are* the tier
/// order; the name follows so each tier is alphabetical within itself.
const TIER_MODULE: char = '0';
/// Members, after a `.` or a `::`.
///
/// The same digit as tier 0 and not a contradiction: the member answer is
/// **exclusive**, so no other tier's item is ever in the same response and
/// the digit orders members among themselves and nothing else. `'0'` because
/// these are not one tier of an answer but the whole of it. A sixth digit
/// would say there is a ranking against the other tiers to express, and there
/// is not.
const TIER_MEMBER: char = '0';
const TIER_SCOPE: char = '1';
const TIER_INDEX: char = '2';
const TIER_TEMPLATE: char = '3';
const TIER_KEYWORD: char = '4';
const TIER_WORD: char = '5';
/// What a multi-line item tells the client about its own whitespace.
///
/// Every skeleton here is laid out at the *site's* indentation already: a
/// `Layout`'s `base` is the trigger line's leading whitespace, and every line
/// after the first carries it. An editor that "helpfully" indents the
/// insertion again would double it — VS Code's `SnippetSession.adjustWhitespace`
/// prepends the insertion line's own indentation to every line after the first,
/// and it is on by default (`SuggestController._insertSuggestion` passes
/// `adjustWhitespace: !(insertTextRules & KeepWhitespace)`). `asIs` is the
/// protocol's way of saying "the text is already positioned, do not touch it",
/// and `vscode-languageclient` turns it into exactly the `keepWhitespace` flag
/// that clears the rule. Single-line items neither need it nor are harmed by
/// it; only the two tiers that write more than one line send it.
///
/// This is the sibling of the fix `inline.rs` had to make differently: an
/// inline completion has no such field, so its bodies are *relative* instead.
/// See `docs/features/inline-templates/README.md`, 2026-08-25.
const KEEP_MY_INDENTATION: InsertTextMode = InsertTextMode::AS_IS;
/// The scopes a module instantiation may be written directly inside.
const ITEM_SCOPES: &[&str] =
&["module", "macromodule", "interface", "program", "generate", "begin"];
/// Scopes that make everything inside them something other than a module item:
/// a subprogram body, a class body, a checker-ish declaration, a `case` arm's
/// interior, a `fork` block.
const NOT_ITEM_SCOPES: &[&str] = &[
"function",
"task",
"class",
"covergroup",
"property",
"sequence",
"clocking",
"specify",
"primitive",
"fork",
"case",
"casex",
"casez",
"randcase",
];
/// The scopes a *statement* may be written directly inside. A `begin` or a
/// `fork` qualifies only when it is procedural (see [`at_statement`]); a
/// `function`/`task` body always does.
const STATEMENT_SCOPES: &[&str] = &["begin", "fork", "function", "task"];
/// What may stand between the start of a line and a statement: the `end` of
/// the block before it and the `else` that chains onto it. Anything else on
/// the line means the word being typed is part of an expression, not the start
/// of a statement.
const STATEMENT_HEADS: &[&str] = &["end", "else", "end else"];
/// Keywords that make the `begin` after them procedural, so nothing inside it
/// is a module item. `@` is on the list because it is the whole of what stands
/// between `always` and its `begin`.
const PROCEDURAL: &[&str] =
&["always", "always_ff", "always_comb", "always_latch", "initial", "final", "@"];
/// Tokens that end whatever came before them, stopping the backward scan that
/// looks for a [`PROCEDURAL`] keyword.
const STATEMENT_END: &[&str] =
&["begin", "end", "endcase", "join", "join_any", "join_none", "generate", ";"];
/// The completions available at a position, or nothing when the cursor is
/// somewhere no name may be written.
///
/// `snippets` is what the client advertised: without it a module skeleton is
/// inserted as plain text, because a literal `${1:clk}` left in a buffer is
/// worse than no tabstops at all.
pub fn completions(
ws: &Workspace,
uri: &Uri,
position: Position,
snippets: bool,
) -> Option<CompletionResponse> {
let doc = ws.document(uri)?;
let offset = doc.positions().offset(position);
// A buffer that does not lex has no token stream, so nothing here can tell
// a comment from code — and the commonest way to break the lexer is to
// open a string or a block comment and keep typing. Declining is the safe
// half of that trade; the buffer lexes again as soon as it is closed.
if doc.tokens.is_empty() || in_comment_or_string(doc, offset) {
return None;
}
let word = typed_word(doc, offset)?;
// A backtick admits exactly one kind of name, so the answer is only that
// kind — and the backtick already typed is inside the replaced range, so
// it is never doubled.
if word.backtick {
// The backtick itself is replaced, so the item may carry its own.
let replacing = TextRange::new(word.start.saturating_sub(1), offset);
let mut items = Items::new(doc, replacing);
for entry in ws.candidates().macros(&word.text) {
items.simple(
&format!("`{}", entry.name),
CompletionItemKind::CONSTANT,
TIER_INDEX,
entry.detail.clone(),
);
}
return items.finish();
}
// A `.` or a `::` admits exactly one kind of name too — a member of what
// stands before it — so the answer is only those. See [`member_answer`].
if word.sep.is_some() {
return member_answer(ws, doc, &word, offset);
}
// Both position gates read the same scope chain, and neither can be true
// unless the word starts a line — so a keystroke in the middle of an
// expression pays for neither.
let starts_a_line = word.at_line_start || word.statement_head;
let chain = match starts_a_line {
true => enclosing_scopes(&doc.tokens, word.start),
false => Vec::new(),
};
let at_item = word.at_line_start && at_module_item(doc, &chain, word.start);
let at_statement = starts_a_line && at_statement(doc, &chain, word.start);
// Prefix below [`FUZZY_MIN`], subsequence from it up. One `Query` for the
// whole request: it folds the typed characters and computes their mask
// once, and every tier that scans a table reads the same prepared form.
let fuzzy = (word.text.len() >= FUZZY_MIN).then(|| Query::new(&word.text));
let mut items = Items::new(doc, word.range(offset));
module_tier(&mut items, ws, doc, &word, at_item);
scope_tier(&mut items, doc, &word, fuzzy.as_ref());
index_tier(&mut items, ws, &word, fuzzy.as_ref());
template_tier(&mut items, ws, doc, &word, snippets, at_item, at_statement);
keyword_tier(&mut items, &word);
word_tier(&mut items, ws, doc, &word, fuzzy.as_ref());
// **The `isIncomplete` trap.** VS Code asks the server again on the next
// keystroke *only* when the last answer said it was incomplete; otherwise
// it filters the list it already holds. A complete two-character prefix
// answer would therefore be filtered client-side for the rest of the word,
// and the third keystroke — the one that turns fuzzy on — would never
// reach here at all. So every answer below the floor says it is
// incomplete, whatever the cap did.
//
// Above the floor the ordinary rule stands, and is sound because the hit
// set only ever *shrinks* as characters are appended: if a name holds
// `clke` in order it holds `clk` in order, so a complete answer at three
// characters really does contain every answer to four.
if fuzzy.is_none() {
items.incomplete = true;
}
items.finish()
}
/// **The member answer**: after a `.` or a `::`, the members of what stands
/// before it and nothing else.
///
/// Exclusive, exactly as the backtick response is, and for the same reason: a
/// member name is the only thing that may be written here, so a keyword, a
/// template or an identifier used three files away is not a worse answer but
/// a wrong one. Until this round the cursor after a dot got the whole-index
/// dump — 512 items of everything — which is what this replaces.
///
/// **One resolution walk.** The site comes from
/// [`vlog_semantic::Semantics::member_site`] (or `unit_site` for a `::`),
/// which is literally the prefix `resolve::member_of` runs before looking a
/// tail up; the in-file `extends` chain comes from `member_scopes`, which is
/// literally the walk `member_in_chain` runs; the cross-file list comes from
/// `WorkspaceIndex::members_of_chain`, which is literally the hop chain
/// `member_chain` walks. So every name offered here is a name hover and
/// go-to-definition resolve, and there is no second resolver to disagree.
///
/// `None` — **no popup at all** — when the head cannot be read (a call, a
/// cast, whitespace in the spine) or cannot be resolved (an untyped head, a
/// type this crate knows has no members, a chain it cannot finish). A guess
/// after a dot is worse than silence. A site that *is* resolved always
/// answers with a list, even an empty one, because an empty list is itself
/// the answer here.
fn member_answer(
ws: &Workspace,
doc: &Document,
word: &Word,
offset: u32,
) -> Option<CompletionResponse> {
let members = match word.spine.as_ref() {
Some(spine) => {
let semantics = &doc.semantics;
let from = innermost_scope(semantics, word.start)?;
let site = match word.sep? {
Sep::Dot => semantics.member_site(from, &spine.head, &spine.mids),
Sep::Scope => semantics.unit_site(from, &spine.head),
}?;
members_at(semantics, doc, ws.index(), &site)
}
// Nothing readable before the dot. One shape is still a real
// question, and it is the commonest completion position in RTL there
// is: a `.` opening a connection or a parameter override.
None => match word.sep? {
Sep::Dot => connection_members(ws, doc, word)?,
Sep::Scope => return None,
},
};
// Prefix below [`FUZZY_MIN`], subsequence from it up — the house rule, on
// the same `Query` every other tier scores with.
let fuzzy = (word.text.len() >= FUZZY_MIN).then(|| Query::new(&word.text));
let matched: Vec<Member> = match &fuzzy {
None => members
.into_iter()
.filter(|member| starts_with_ignore_case(&member.name, &word.text))
.collect(),
Some(query) => {
let mut hits: Vec<(Member, Score)> = members
.into_iter()
.filter_map(|member| {
let score = query.score(&member.name)?;
Some((member, score))
})
.collect();
hits.sort_by(|a, b| rank_cmp((&a.0.name, a.1), (&b.0.name, b.1)));
hits.into_iter().map(|(member, _)| member).collect()
}
};
let mut items = Items::new(doc, word.range(offset));
for member in matched {
if items.full() {
break;
}
items.simple(&member.name, completion_kind(member.kind), TIER_MEMBER, member.detail);
}
// **The `isIncomplete` trap, in its member form.** The request that
// matters is the one the trigger character fires, with nothing typed
// after the separator: that answer is the whole member list, so it is
// complete, and VS Code filters it client-side for the rest of the name
// with its own subsequence matcher — which is the behaviour this feature
// wants. A 1- or 2-character answer is a *prefix* slice of that list, and
// the third keystroke would widen it to a subsequence match, so it must
// say so or the widening never reaches the client. Above the floor the
// ordinary rule stands: appending a character only shrinks a subsequence
// hit set, so only the cap can make the answer partial.
items.incomplete |= fuzzy.is_none() && !word.text.is_empty();
// An **empty** answer is always incomplete, whatever was typed. Two
// reasons, and the second is the one QA found (finding 2, 2026-09-02): an
// empty list is never a satisfying final answer, and a *cold* index — the
// scope ladder has not widened to the directory the declaring file is in
// yet — answers empty for a moment and correctly a moment later. Marked
// complete, VS Code would cache the emptiness and the user would have to
// retype the dot; marked incomplete, the next keystroke picks up the real
// list. It costs one extra request in the one case where the request is
// cheapest, because there was nothing to build.
items.incomplete |= items.items.is_empty();
Some(items.into_list())
}
/// One member of a site, as the list needs it: everything an item carries and
/// nothing that would cost a file read.
struct Member {
name: String,
kind: SymbolKind,
detail: String,
}
/// What a member declared **in another file** shows beside its name.
///
/// **Table-only, because it must be.** A `Def` in the index carries no text,
/// and reading the declaring file on a keystroke is the one thing no answer
/// here may do (completion-core, *Every tier is a table lookup*). So the card
/// is the kind label plus the declared type name, which is all the table
/// holds. A member of the **buffer being typed in** does better — see
/// [`declaration_detail`], which tier 1 has always used and which the in-file
/// half of every member list uses too.
fn indexed_detail(kind: SymbolKind, type_name: Option<&str>) -> String {
let label = kind_label(kind);
match type_name {
Some(ty) => format!("{label} — {ty}"),
None => label.to_string(),
}
}
/// Every member of a site, nearest declaration first, each name once.
///
/// A name declared in more than one place on the chain is offered by the
/// **nearest** — a subclass's override rather than the base's original, which
/// is the same first-hit-wins rule the lookup itself applies, so the item and
/// the declaration a lookup finds are the same declaration.
///
/// An in-file class whose `extends` leaves the file gets both halves: its own
/// scopes for as far as this file declares the chain, then the index's list
/// for the base and everything above it.
fn members_at(
semantics: &Semantics,
doc: &Document,
index: &WorkspaceIndex,
site: &MemberSite,
) -> Vec<Member> {
let mut members = Members::new();
let base = match site {
MemberSite::Scope(scope) => {
let (scopes, base) = semantics.member_scopes(*scope);
for id in scopes {
let Some(scope) = semantics.scope(id) else { continue };
for symbol in scope.symbols.iter().filter_map(|&id| semantics.symbol(id)) {
members.push(&symbol.name, symbol.kind, declaration_detail(doc, symbol));
}
}
// The index keys by the last `::` segment, exactly as the
// overlay's own inheritance chase does.
base.map(|path| last_segment(&path).to_string())
}
MemberSite::Unit(unit) => Some(unit.clone()),
};
if let Some(unit) = base {
for (name, def) in index.members_of_chain(&unit) {
members.push(name, def.kind, indexed_detail(def.kind, def.type_name.as_deref()));
}
}
members.into_vec()
}
/// The names that may be written after the `.` of a connection or a parameter
/// override: the instantiated module's **ports**, or its **parameters**.
///
/// This is the answer at the commonest completion position in RTL there is,
/// and until it existed the position got the whole-index dump. Three
/// deliberate choices:
///
/// * **The list is `signature.rs`'s.** [`signature::enclosing_list`] already
/// works out which module's `(…)` or `#(…)` the cursor sits in, for the
/// signature card that hangs above this very popup. A second answer to that
/// question would eventually disagree with the card.
/// * **The scope is `Target::Port`'s.** In-file it is
/// [`vlog_semantic::Semantics::instantiable_scope`], literally the call the
/// resolution makes; across files it is the module's member table, which
/// `member_chain` reads for the same use and which exports ports and
/// parameters and nothing else. Either/or, never merged — a module this
/// file declares has *answered*, exactly as the resolution has it.
/// * **Filtered to the kind the list admits.** A module scope also binds its
/// nets and its instances, and `.internal_sig(w)` is not a connection —
/// class-member-access's ruling, in the other direction. This narrows the
/// list to what may legally be written; it never offers a name the
/// resolution could not find.
///
/// Ports already connected earlier in the same list are dropped. `None` — no
/// popup — when the cursor is not in such a list at all, or is inside a
/// connected *expression* (`.clk(` opens a paren of its own).
fn connection_members(ws: &Workspace, doc: &Document, word: &Word) -> Option<Vec<Member>> {
let dot = word.start.checked_sub(1)?;
let list = signature::enclosing_list(&doc.tokens, word.start)?;
let open = doc.tokens.get(list.open)?.span.end;
// The dot has to stand directly in the list. Inside `.clk( … )` the
// parentheses since the list opened do not balance, and a port name is
// not what may be written there.
if !balanced(&doc.tokens, open, word.start) {
return None;
}
// `Param` and **not** `LocalParam`: this is the one place in the whole
// server where the two kinds part. A `localparam` in a header is derived
// inside the module and overriding it is illegal, so it may not be
// offered here — QA finding 1, 2026-09-02, on `prim_fifo_sync`'s
// `localparam int DepthW = prim_util_pkg::vbits(Depth+1)`. Everywhere
// else a localparam is a parameter: it is exported, hovered, iconed and
// highlighted the same, and `u_fifo.DepthW` resolves.
let wanted = match list.kind {
signature::Kind::Params => SymbolKind::Param,
signature::Kind::Ports => SymbolKind::Port,
};
let taken = connected_names(&doc.tokens, list.open, dot);
let mut members = Members::new();
match doc.semantics.instantiable_scope(&list.module) {
// This file declares the module: its own scope is the whole answer,
// and no other file's module of the same name may override it.
Some(scope) => {
let scope = doc.semantics.scope(scope)?;
for symbol in scope.symbols.iter().filter_map(|&id| doc.semantics.symbol(id)) {
if symbol.kind == wanted && !taken.contains(symbol.name.as_str()) {
members.push(&symbol.name, symbol.kind, declaration_detail(doc, symbol));
}
}
}
None => {
for (name, defs) in ws.index().members_of(&list.module) {
let Some(def) = defs.first() else { continue };
if def.kind == wanted && !taken.contains(name) {
members.push(
name,
def.kind,
indexed_detail(def.kind, def.type_name.as_deref()),
);
}
}
}
}
Some(members.into_vec())
}
/// Every `.name` already written at the top level of the list opened by the
/// token at `open`, except the one whose `.` sits at `skip` — the entry being
/// typed, which must stay on offer.
///
/// Dropping them is the friendlier half of a choice the other way round would
/// be simpler: in a sixty-port instantiation the fifty-five already connected
/// are the ones the user is *not* looking for, and a popup that keeps offering
/// them is a popup they scroll past. It cannot mislead — a name dropped here
/// is one the buffer already spells two lines up — and a re-edited entry is
/// still offered, because its own dot is the one `skip` names.
fn connected_names(tokens: &[Token], open: usize, skip: u32) -> HashSet<&str> {
let mut taken = HashSet::new();
let mut depth = 0i32;
let mut dot: Option<u32> = None;
for token in tokens.iter().skip(open + 1) {
if token.kind == TokenKind::Symbol {
match token.text.as_str() {
"(" => depth += 1,
")" if depth == 0 => break,
")" => depth -= 1,
"." if depth == 0 => {
dot = Some(token.span.start);
continue;
}
_ => {}
}
}
if let Some(at) = dot.take() {
if at != skip && token.kind == TokenKind::Ident {
taken.insert(token.text.as_str());
}
}
}
taken
}
/// The members gathered so far, each name kept once — the **nearest**
/// declaration of a shadowed name, which is the first-hit-wins rule every
/// lookup on the same chain applies.
struct Members {
out: Vec<Member>,
seen: HashSet<String>,
}
impl Members {
fn new() -> Members {
Members { out: Vec::new(), seen: HashSet::new() }
}
fn push(&mut self, name: &str, kind: SymbolKind, detail: String) {
if self.seen.insert(name.to_string()) {
self.out.push(Member { name: name.to_string(), kind, detail });
}
}
fn into_vec(self) -> Vec<Member> {
self.out
}
}
/// The last `::` segment of a possibly-qualified path — the name the
/// workspace index's member and inheritance tables are keyed by, and the same
/// cut `vlog_semantic`'s own overlay makes before asking them.
fn last_segment(path: &str) -> &str {
path.rsplit("::").next().unwrap_or(path)
}
/// Tier 0: the names of the modules that could be instantiated here, at
/// module-item position only.
///
/// **Names, not skeletons, since 2026-08-30** (owner ruling). Until then each
/// item carried the whole instantiation, which cost one `module_definition`
/// lookup, one file read and one header parse *per candidate* — up to
/// [`MODULE_LIMIT`] of each, on every keystroke, for a list the user reads one
/// line of. The instantiation is now offered by `inline.rs` as ghost text,
/// once the name before the cursor is spelled exactly and a space follows it,
/// and is planned once.
/// See `docs/features/inline-instantiation/README.md`.
///
/// What survives is the ranking, which is the tier's real job: at a position
/// where an instantiation may be written, a module name beats every other kind
/// of name, and it is matched as a *substring* so `reg_top` reaches
/// `aes_reg_top`.
fn module_tier(items: &mut Items, ws: &Workspace, doc: &Document, word: &Word, at_item: bool) {
if !at_item {
return;
}
// The same names `vlog_refactor::module_names` answers, off the table
// built with the index instead of off the index's whole symbol table —
// which the old call rebuilt and re-sorted on every keystroke.
let names = ws.candidates().modules(&word.text);
if names.len() > MODULE_LIMIT {
items.incomplete = true;
}
for name in names.into_iter().take(MODULE_LIMIT) {
items.simple(
name,
CompletionItemKind::MODULE,
TIER_MODULE,
module_detail(ws.index(), name, doc.path.as_deref()),
);
}
}
/// What a module item shows beside its name: where the module is declared.
///
/// A lookup in the index's unit table — no file is opened. The wording is tier
/// 2's, so a module offered by either tier reads the same.
///
/// **The file named is the one the ghost will read** ([`nearest_definition`]),
/// which since round 2 (2026-08-30) is an answer even for a name two files
/// declare: `ast_dft` under `top_earlgrey` and `ast_dft` under `top_darjeeling`
/// are two different headers, and the popup saying which one is coming is worth
/// more than the bare kind label it used to fall back to.
fn module_detail(index: &WorkspaceIndex, module: &str, from: Option<&Path>) -> String {
// An interface is instantiated exactly as a module is and rides this same
// list, so the label is read off what the index actually holds — a card
// that said "module" over an `interface` would be the wrong answer this
// round exists to remove.
let kind = index
.units(module)
.iter()
.find(|def| def.kind.is_instantiable())
.map_or(SymbolKind::Module, |def| def.kind);
let label = kind_label(kind);
let Some(path) = nearest_definition(index, module, from) else {
return label.to_string();
};
match path.file_name().and_then(|name| name.to_str()) {
Some(file) => format!("{label} — {file}"),
None => label.to_string(),
}
}
/// The file whose declaration of `module` a request made in `from` should be
/// planned from.
///
/// **This never refuses on multiplicity**, which is the whole of what parts it
/// from `vlog_refactor::module_definition`. That one errors when a name is
/// declared twice and will not guess; in opentitan `ast_dft` and `io_osc` are
/// each declared once under `hw/top_earlgrey/ip/ast/rtl` and once under
/// `hw/top_darjeeling/ip/ast/rtl`, so refusing meant two whole IP blocks with
/// no ghost at all. The owner's ruling of 2026-08-30 is that every indexed
/// module expands, so the server chooses instead of declining — and
/// `module_definition` keeps its refusal for its own callers, which want an
/// error message rather than a guess.
///
/// The rule is **nearest to the asker**: the declaration whose path shares the
/// longest run of leading *path components* with the document being typed in,
/// so a buffer under `hw/top_earlgrey/…` is offered top_earlgrey's copy. A tie
/// — and a buffer with no path at all — falls to the lexicographically smallest
/// path, so the answer never depends on the order the index happened to be
/// built in. Where the two declarations have different headers the user gets
/// the nearest one's; that is the accepted semantics, not an approximation.
///
/// A module only one file declares is chosen by exactly this path too, and
/// picks that one file — the same answer `module_definition` gives.
pub(crate) fn nearest_definition<'i>(
index: &'i WorkspaceIndex,
module: &str,
from: Option<&Path>,
) -> Option<&'i Path> {
index
.units(module)
.iter()
.filter(|def| def.kind.is_instantiable())
.filter_map(|def| index.path(def.file))
// Most shared leading components first; among those, the *shallowest*
// candidate — fewest components of its own past the shared prefix —
// then the lexicographically smallest path. The depth key is the QA
// round-2 fix: a copy in the asking buffer's own directory and one in
// a subdirectory of it share the same prefix with the buffer (the
// buffer's filename never matches a directory), and without the depth
// key the lexicographic tie-break could prefer the deeper, less
// related copy (`rstmgr/dv/rstmgr_cnsty_chk/tb.sv` over the direct
// sibling `rstmgr/dv/tb.sv`, because `'r' < 't'`).
.min_by_key(|path| {
let shared = shared_components(path, from);
(Reverse(shared), path.components().count() - shared, *path)
})
}
/// How many leading path components `path` and `from` spell the same way.
///
/// Components, not bytes: `hw/top_earlgrey` and `hw/top_darjeeling` share `hw`
/// and nothing else, where a byte-wise prefix would count `hw/top_` as shared
/// and rank two unrelated copies by a coincidence of spelling.
fn shared_components(path: &Path, from: Option<&Path>) -> usize {
let Some(from) = from else { return 0 };
path.components().zip(from.components()).take_while(|(ours, theirs)| ours == theirs).count()
}
/// One module's instantiation plan, off its header alone where that is the
/// whole of what the plan reads, and off its whole file otherwise.
///
/// The slice is an optimisation and never an answer of its own. Two things
/// send this back to the whole file, and both leave the answer exactly what it
/// was before the slice existed:
///
/// * the slice does not plan at all — [`module_header`] cut a header this
/// parser does not read as one;
/// * the plan it produced has a port with neither a direction nor a type,
/// which is what a **non-ANSI** port list looks like once its body is gone:
/// `module m (a); input wire a;` writes the direction below the header, and
/// the body is the part the slice drops.
///
/// `pub(crate)` for `inline.rs`, which plans the one module the user has
/// spelled out. One planner on purpose: a second answer to "what is this
/// module's instantiation" would eventually disagree with this one, and any
/// future non-ghost spelling of the skeleton (a command for clients without
/// `inlineCompletion`, say — filed in `docs/topo.md` §2.9) must come through
/// here too.
pub(crate) fn plan_for(
index: &WorkspaceIndex,
module: &str,
definition: &str,
site: Site<'_>,
) -> Result<InstantiationPlan, String> {
let whole = || vlog_refactor::instantiation_plan(module, definition, Some(site));
let Some(header) = module_header(index, module, definition) else { return whole() };
match vlog_refactor::instantiation_plan(module, &header, Some(site)) {
Ok(plan) if plan.ports.iter().all(|p| !p.dir.is_empty() || !p.ty.is_empty()) => Ok(plan),
_ => whole(),
}
}
/// The text one skeleton is planned from: the declaring file's header alone
/// where this function can find it, and the whole file where it cannot.
///
/// Tier 0 is the one tier that costs a *parse*, and until 2026-08-28 it parsed
/// the whole declaring file — three hundred lines of body to read a header a
/// few hundred bytes long, [`MODULE_LIMIT`] times per keystroke. A plan reads
/// nothing but the header, so nothing but the header needs to be parsed.
///
/// The prefix is kept **byte for byte**: every span the plan reads is an offset
/// into the text it was parsed from, so cutting the front off would move them
/// all. Only the body is dropped, and an `endmodule` is written in its place so
/// the declaration is closed.
///
/// **Every declaration of the name is tried, not just a lone one** (round 2,
/// 2026-08-30). Until then a name two files declared made this decline outright,
/// which cost `ast_dft` and `io_osc` their ghost; it now walks them, because
/// the index's span is only ever a *hint* here and the guard below is what
/// makes a hint safe. A span from the wrong file either does not spell the
/// module's name in this text — declined, and the caller parses the whole file
/// instead, exactly as it did before — or it does, in which case the slice is
/// taken from a real occurrence of the name in the text actually being read.
pub(crate) fn module_header(index: &WorkspaceIndex, module: &str, text: &str) -> Option<String> {
index
.units(module)
.iter()
.filter(|def| def.kind.is_instantiable())
.find_map(|def| header_from(module, def.name_span, text))
}
/// The header of the declaration `text` spells at `name`, or `None` when it
/// does not spell one there at all.
fn header_from(module: &str, name: TextRange, text: &str) -> Option<String> {
// The index's span is as of the last scan, and may belong to a sibling
// file that declares the same module. A file edited on disk since then has
// moved it, and a slice taken at a stale offset would be a different
// module's header — so the name has to still be there.
if text.get(name.start as usize..name.end as usize) != Some(module) {
return None;
}
let from = name.end as usize;
for size in HEADER_WINDOWS {
// A window that cuts a block comment or a string in half does not lex,
// and one that cuts the port list in half runs out of tokens before
// the `;`. Both answer "not in this window" and are asked again at the
// next rung; both answer `None` at the last one.
let window = text.get(from..text.len().min(from + size))?;
if let Ok(tokens) = vlog_parser::tokenize(window) {
if let Some(end) = header_end(&tokens) {
let head = text.get(..from + end as usize)?;
return Some(format!("{head}\nendmodule\n"));
}
}
if from + size >= text.len() {
break;
}
}
None
}
/// Where the header that begins just after a module's name ends: the offset
/// one past its terminating `;`, in the window's own coordinates.
///
/// A **whitelist**, not a scan for the first `;`: `module aes import
/// aes_pkg::*; #(...) (...);` writes three of them and only the last ends the
/// header. Anything this does not recognise — a compiler directive between the
/// name and the port list, a header longer than the window — answers `None`,
/// and the caller parses the whole file rather than guessing.
fn header_end(tokens: &[Token]) -> Option<u32> {
let mut at = 0;
loop {
let token = tokens.get(at)?;
match token.text.as_str() {
";" => return Some(token.span.end),
// A lifetime qualifier: `module automatic foo (...);`.
"static" | "automatic" => at += 1,
// A package import written into the header, whose own `;` is not
// the header's.
"import" => at = skip_to_semicolon(tokens, at + 1)?,
// The parameter list, the port list, and an attribute instance —
// each one parenthesised, each one skipped whole.
"#" | "(" => at = skip_parens(tokens, at)?,
_ => return None,
}
}
}
/// Past the parenthesised group starting at `at`, which a `#` may introduce.
fn skip_parens(tokens: &[Token], mut at: usize) -> Option<usize> {
while tokens.get(at)?.text == "#" {
at += 1;
}
if tokens.get(at)?.text != "(" {
return None;
}
let mut depth = 0i32;
loop {
match tokens.get(at)?.text.as_str() {
"(" => depth += 1,
")" if depth == 1 => return Some(at + 1),
")" => depth -= 1,
_ => {}
}
at += 1;
}
}
/// Past the next `;` written outside any parentheses.
fn skip_to_semicolon(tokens: &[Token], mut at: usize) -> Option<usize> {
let mut depth = 0i32;
loop {
match tokens.get(at)?.text.as_str() {
"(" => depth += 1,
")" => depth -= 1,
";" if depth == 0 => return Some(at + 1),
_ => {}
}
at += 1;
}
}
/// Tier 1: everything the scope chain at the cursor binds.
///
/// The one fuzzy tier with no mask table behind it, and deliberately so: what
/// a scope chain binds is tens of names computed per request, where a table of
/// masks would cost more to build than the scan it saved.
fn scope_tier(items: &mut Items, doc: &Document, word: &Word, fuzzy: Option<&Query>) {
let visible = visible_symbols(&doc.semantics, word.start);
let matched: Vec<&Symbol> = match fuzzy {
None => visible
.into_iter()
.filter(|symbol| starts_with_ignore_case(&symbol.name, &word.text))
.collect(),
Some(query) => {
let mut hits: Vec<(&Symbol, Score)> = visible
.into_iter()
.filter_map(|symbol| Some((symbol, query.score(&symbol.name)?)))
.collect();
hits.sort_by(|a, b| rank_cmp((&a.0.name, a.1), (&b.0.name, b.1)));
hits.into_iter().map(|(symbol, _)| symbol).collect()
}
};
for symbol in matched {
if items.full() {
break;
}
items.simple(
&symbol.name,
completion_kind(symbol.kind),
TIER_SCOPE,
declaration_detail(doc, symbol),
);
}
}
/// Tier 2: what the workspace index declares, `` `define`` names included.
///
/// The index names match fuzzily from [`FUZZY_MIN`] up; the macro names do
/// not. That is a deliberate split, not an oversight — see the feature
/// README's *What did not go fuzzy*.
fn index_tier(items: &mut Items, ws: &Workspace, word: &Word, fuzzy: Option<&Query>) {
let matched: Vec<&Candidate> = match fuzzy {
None => ws.candidates().units(&word.text).iter().collect(),
Some(query) => {
let hits = ws.candidates().units_fuzzy(query, LIMIT);
// A full return means the scan kept its best LIMIT and dropped the
// rest, so the response is a best-of and has to say so. `full()`
// below would only notice if every one of them reached the list,
// and a name a higher tier already claimed does not.
items.incomplete |= hits.len() >= LIMIT;
hits.into_iter().map(|(unit, _)| unit).collect()
}
};
for candidate in matched {
if items.full() {
break;
}
items.simple(
&candidate.name,
completion_kind(candidate.kind),
TIER_INDEX,
format!("{} — {}", kind_label(candidate.kind), candidate.detail),
);
}
// Bare, with no backtick invented. A macro *use* is spelled with one and
// the user types it (see the early return above); the places a macro name
// is written without one — `` `ifdef NAME ``, `` `undef NAME `` — are
// exactly where this item is the right text.
for entry in ws.candidates().macros(&word.text) {
if items.full() {
break;
}
items.simple(&entry.name, CompletionItemKind::CONSTANT, TIER_INDEX, entry.detail.clone());
}
}
/// Tier 3: the statement, item and declaration templates.
///
/// Above the keywords because a user who typed `if` almost always wants
/// `if (…) begin … end` rather than the three letters they already typed, and
/// below both semantic tiers because a name the code actually declares beats a
/// skeleton every time. The templates a *position* rules out never reach the
/// list at all, so the ranking argument only has to hold where they do.
fn template_tier(
items: &mut Items,
ws: &Workspace,
doc: &Document,
word: &Word,
snippets: bool,
at_item: bool,
at_statement: bool,
) {
if !at_item && !at_statement {
return;
}
let layout = layout_at(ws, doc, word.start);
let dialect = templates::dialect(doc.path.as_deref());
for template in templates::for_dialect(dialect) {
if items.full() {
break;
}
if !offered(template, at_item, at_statement) {
continue;
}
if !starts_with_ignore_case(template.prefix, &word.text) {
continue;
}
items.template(template, &layout, snippets);
}
}
/// Whether a template's gate lets it be written where the cursor is.
fn offered(template: &Template, at_item: bool, at_statement: bool) -> bool {
match template.gate {
Gate::Statement | Gate::ElseTail => at_statement,
Gate::Item => at_item,
// A declaration is a module item and a block item both.
Gate::Declaration => at_item || at_statement,
}
}
/// How generated text is indented at `offset`: the line's own indentation, and
/// one step as `lucisv.indent` spells it.
///
/// Private again as of 2026-08-25. `inline.rs` used to share it, so that ghost
/// text and the completion list could not indent the same body differently;
/// ghost text now emits *relative* indentation and lets the editor place it
/// (see `inline.rs`'s `render`), so there is no second caller left.
fn layout_at(ws: &Workspace, doc: &Document, offset: u32) -> Layout {
let step = " ".repeat(ws.client_settings().indent.unwrap_or(2));
Layout { base: line_indent(&doc.text, offset), step }
}
/// Tier 4: every reserved word the lexer knows.
fn keyword_tier(items: &mut Items, word: &Word) {
for keyword in KEYWORDS.iter().filter(|kw| starts_with_ignore_case(kw, &word.text)) {
if items.full() {
break;
}
items.simple(keyword, CompletionItemKind::KEYWORD, TIER_KEYWORD, "keyword".to_string());
}
}
/// Tier 5: identifiers used anywhere in the project scope.
///
/// The prebuilt table is as of the last index rebuild, which is `didSave`; the
/// buffer being typed in is harvested afresh from its own token stream, so an
/// unsaved edit contributes to its own file's completions immediately.
fn word_tier(
items: &mut Items,
ws: &Workspace,
doc: &Document,
word: &Word,
fuzzy: Option<&Query>,
) {
// Gathering and sorting the names is the one tier whose *setup* costs
// something, so a response that is already full skips it outright.
if items.full() {
return;
}
let names: Vec<&str> = match fuzzy {
None => {
let mut names: Vec<&str> =
ws.candidates().words(&word.text).iter().map(String::as_str).collect();
names
.extend(buffer_words(doc).filter(|text| starts_with_ignore_case(text, &word.text)));
names.sort_unstable();
names.dedup();
names
}
Some(query) => {
// The table's hits come back ranked; the buffer's own words are
// scored here and the two are ranked together, so a name the user
// typed a moment ago sits where its match deserves rather than
// after everything the table knows.
let mut hits = ws.candidates().words_fuzzy(query, LIMIT);
// A full return is a truncation; see `index_tier`.
items.incomplete |= hits.len() >= LIMIT;
hits.extend(buffer_words(doc).filter_map(|name| Some((name, query.score(name)?))));
hits.sort_by(|a, b| rank_cmp(*a, *b));
// A name in both lists is offered once: `Items` drops the second
// by label, so no dedup is needed here.
hits.into_iter().map(|(name, _)| name).collect()
}
};
for name in names {
if items.full() {
break;
}
items.simple(name, CompletionItemKind::TEXT, TIER_WORD, "used in this project".to_string());
}
}
/// Every identifier the buffer being typed in holds, as tier 5 counts one.
///
/// The live half of the tier: the prebuilt table is as of the last index
/// rebuild, and this is the buffer's own token stream, recomputed on every
/// change. The filter is `candidates::is_word`'s, in the other direction —
/// `Ident` and `SystemIdent` only, and neither a macro usage nor an escaped
/// identifier.
fn buffer_words(doc: &Document) -> impl Iterator<Item = &str> {
doc.tokens
.iter()
.filter(|token| matches!(token.kind, TokenKind::Ident | TokenKind::SystemIdent))
.map(|token| token.text.as_str())
.filter(|text| !text.starts_with('`') && !text.starts_with('\\'))
}
/// The response under construction: the items, the names already spoken for,
/// and whether the cap cut anything off.
struct Items {
/// The bytes every item replaces, as the client reads them.
range: Range,
items: Vec<CompletionItem>,
seen: HashSet<String>,
incomplete: bool,
}
impl Items {
fn new(doc: &Document, replacing: TextRange) -> Items {
Items {
range: doc.positions().range(replacing),
items: Vec::new(),
seen: HashSet::new(),
incomplete: false,
}
}
/// Whether the cap has been reached. Once it has, every further candidate
/// only sets [`Items::incomplete`] — which is why the tiers ask first
/// rather than building items nobody will see.
fn full(&mut self) -> bool {
if self.items.len() >= LIMIT {
self.incomplete = true;
return true;
}
false
}
/// Add an item, unless a higher tier already offered that name or the
/// response is full.
fn push(&mut self, item: CompletionItem) {
if self.full() || !self.seen.insert(item.label.clone()) {
return;
}
self.items.push(item);
}
/// A plain-text item that inserts exactly its own name.
fn simple(&mut self, name: &str, kind: CompletionItemKind, tier: char, detail: String) {
if self.full() || self.seen.contains(name) {
return;
}
let item = CompletionItem {
label: name.to_string(),
kind: Some(kind),
detail: Some(detail),
sort_text: Some(format!("{tier}{name}")),
insert_text_format: Some(InsertTextFormat::PLAIN_TEXT),
text_edit: Some(CompletionTextEdit::Edit(TextEdit {
range: self.range,
new_text: name.to_string(),
})),
..Default::default()
};
self.push(item);
}
/// One template: the skeleton it inserts, the word it is reached by, and
/// the shape it expands to.
///
/// A client that never said it understands snippets gets the same text
/// with every hole filled in rather than nothing at all — the M4 ruling,
/// applied to a body whose defaults were chosen so that the result parses.
fn template(&mut self, template: &Template, layout: &Layout, snippets: bool) {
if self.full() || self.seen.contains(template.label) {
return;
}
let item = CompletionItem {
label: template.label.to_string(),
kind: Some(CompletionItemKind::SNIPPET),
detail: Some(format!("{} — template", template.detail)),
documentation: Some(Documentation::MarkupContent(MarkupContent {
kind: MarkupKind::Markdown,
value: format!("```systemverilog\n{}\n```", template.expansion()),
})),
// The label is prose, so the client must be told what the user
// types to reach the item — otherwise `if` would not match
// `if begin/end` at all.
filter_text: Some(template.prefix.to_string()),
sort_text: Some(format!("{TIER_TEMPLATE}{}", template.label)),
insert_text_format: Some(match snippets {
true => InsertTextFormat::SNIPPET,
false => InsertTextFormat::PLAIN_TEXT,
}),
insert_text_mode: Some(KEEP_MY_INDENTATION),
text_edit: Some(CompletionTextEdit::Edit(TextEdit {
range: self.range,
new_text: template.render(layout, snippets),
})),
..Default::default()
};
self.push(item);
}
fn finish(self) -> Option<CompletionResponse> {
if self.items.is_empty() {
return None;
}
Some(self.into_list())
}
/// The response whether or not anything is in it.
///
/// [`Items::finish`]'s `None` means "this was not my question", which is
/// the right answer for a tiered response nobody filled. For the
/// **exclusive** member answer an empty list is the answer — the site
/// resolved and holds no matching member — and it has to be sent rather
/// than declined, because `None` carries no `isIncomplete` and so cannot
/// ask the client to come back with the third character.
fn into_list(self) -> CompletionResponse {
CompletionResponse::List(CompletionList {
is_incomplete: self.incomplete,
items: self.items,
})
}
}
/// The LSP icon a declaration gets in a completion list. The same choices
/// `symbols::lsp_kind` makes for the outline, in the other enum.
fn completion_kind(kind: SymbolKind) -> CompletionItemKind {
match kind {
SymbolKind::Module | SymbolKind::Package | SymbolKind::Block => CompletionItemKind::MODULE,
SymbolKind::Interface | SymbolKind::Modport => CompletionItemKind::INTERFACE,
SymbolKind::Clocking => CompletionItemKind::EVENT,
SymbolKind::Port | SymbolKind::StructMember => CompletionItemKind::FIELD,
SymbolKind::Net | SymbolKind::Var | SymbolKind::Genvar | SymbolKind::Instance => {
CompletionItemKind::VARIABLE
}
SymbolKind::Param | SymbolKind::LocalParam | SymbolKind::TfArg => {
CompletionItemKind::CONSTANT
}
SymbolKind::Typedef => CompletionItemKind::TYPE_PARAMETER,
SymbolKind::EnumVariant => CompletionItemKind::ENUM_MEMBER,
SymbolKind::Function | SymbolKind::Task => CompletionItemKind::FUNCTION,
SymbolKind::Class => CompletionItemKind::CLASS,
SymbolKind::Constraint | SymbolKind::Coverpoint | SymbolKind::Cross => {
CompletionItemKind::PROPERTY
}
SymbolKind::Covergroup => CompletionItemKind::CLASS,
}
}
/// What a visible declaration shows beside its name: the line it was declared
/// on, which is the cheapest honest summary there is.
fn declaration_detail(doc: &Document, symbol: &Symbol) -> String {
let line = doc.positions().whole_lines(symbol.decl_span).lines().next().unwrap_or("").trim();
match line.is_empty() {
true => kind_label(symbol.kind).to_string(),
false => shorten(line, 80),
}
}
/// `text`, cut to `max` characters on a character boundary.
fn shorten(text: &str, max: usize) -> String {
match text.char_indices().nth(max) {
Some((at, _)) => format!("{}…", &text[..at]),
None => text.to_string(),
}
}
/// Every declaration the scope chain covering `offset` binds, innermost scope
/// first, each name only once — the inner declaration shadows the outer one,
/// which is the rule `vlog_semantic`'s own lookup follows.
fn visible_symbols(semantics: &Semantics, offset: u32) -> Vec<&Symbol> {
let mut out = Vec::new();
let mut seen = HashSet::new();
let mut at = innermost_scope(semantics, offset);
while let Some(id) = at {
let Some(scope) = semantics.scope(id) else { break };
for symbol in scope.symbols.iter().filter_map(|&id| semantics.symbol(id)) {
if seen.insert(symbol.name.as_str()) {
out.push(symbol);
}
}
at = scope.parent;
}
out
}
/// The smallest scope whose span covers `offset`.
fn innermost_scope(semantics: &Semantics, offset: u32) -> Option<vlog_semantic::ScopeId> {
semantics
.scopes()
.iter()
.enumerate()
.filter(|(_, scope)| scope.span.contains(offset))
.min_by_key(|(_, scope)| scope.span.len())
.map(|(i, _)| vlog_semantic::ScopeId(i as u32))
}
/// Whether `offset` sits inside a comment or a string literal — the two places
/// a completion list has no business appearing.
///
/// Comments are lexer trivia hanging off the token that follows (or precedes)
/// them, so this reads both. A linear pass over the token stream: a scan of a
/// few tens of thousands of tokens is tens of microseconds, and a binary
/// search would have to reason about which token a comment attached to.
fn in_comment_or_string(doc: &Document, offset: u32) -> bool {
for token in &doc.tokens {
if token.kind == TokenKind::String && token.span.start < offset && offset < token.span.end {
return true;
}
if token.leading.iter().chain(token.trailing.as_ref()).any(|c| in_comment(c, offset)) {
return true;
}
}
false
}
/// Whether `offset` is inside `comment`. A `//` comment runs to the end of the
/// line, so a cursor at its last byte is still inside it; a `/* */` one ends
/// at its marker, and the byte after that is code again.
fn in_comment(comment: &Comment, offset: u32) -> bool {
if offset <= comment.span.start {
return false;
}
match comment.text.starts_with("//") {
true => offset <= comment.span.end,
false => offset < comment.span.end,
}
}
/// One tabstop: `${n:default}`, or a bare `${n}` when there is no default to
/// preselect. The default is escaped, because `$`, `}` and `\` are the snippet
/// grammar's own punctuation and a type like `logic [$bits(t)-1:0]` really
/// does contain one.
///
/// `pub(crate)` for `inline.rs`, whose ghost instantiation writes the same
/// holes: one spelling of a tabstop, one place to fix an escaping bug.
pub(crate) fn snippet_hole(n: usize, default: &str) -> String {
if default.is_empty() {
return format!("${{{n}}}");
}
let mut escaped = String::with_capacity(default.len());
for ch in default.chars() {
if matches!(ch, '$' | '}' | '\\') {
escaped.push('\\');
}
escaped.push(ch);
}
format!("${{{n}:{escaped}}}")
}
// ----------------------------------------------------------------------
// where the cursor is
// ----------------------------------------------------------------------
/// The identifier the user is part-way through typing, and what stands around
/// it.
struct Word {
/// The identifier run, backtick excluded. Empty when the cursor follows
/// something that is not an identifier character.
text: String,
/// Where the run starts — the byte after the backtick, when there is one.
start: u32,
/// Whether a `` ` `` immediately precedes the run, making this a macro
/// name being typed and nothing else.
backtick: bool,
/// Whether nothing but whitespace precedes the run on its line.
///
/// Half of the *module* gate, and deliberately blunt: an instantiation is
/// written at the start of a line, and a word that is not (`assign x =
/// fo|`, `logic fo|`, `.clk(cl|`) is somewhere a module name would be
/// wrong. It costs the rare user who writes two items on one line their
/// skeleton — a far better failure than offering a fifteen-line
/// instantiation in the middle of an expression. Every other tier ignores
/// it: a name is a name wherever it is written.
at_line_start: bool,
/// Whether the only thing before the run on its line is [`STATEMENT_HEADS`]
/// — the `end` a statement follows, or the `else` it hangs off.
///
/// Half of the *template* gate, and the reason `end else if` completes: a
/// statement is written at the start of a line or right after one of those
/// two words, and nowhere else.
statement_head: bool,
/// The `.` or `::` the run immediately follows, when it follows one.
///
/// Its presence alone decides the shape of the whole response: a
/// separator says the user is naming a **member** of what stands before
/// it, and nothing else may be written there — so the member answer is
/// exclusive, exactly as the backtick's is. A lone `:` (a case item, a
/// label, a ternary) is not a separator and is `None`.
sep: Option<Sep>,
/// What stands before the separator, when it is a spine this can read.
/// `None` with a `sep` set means the response is nothing at all: there is
/// a member question here and no head to answer it about.
spine: Option<Spine>,
}
/// The two separators that make the run after them a member name.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Sep {
/// `handle.`, `vif.cb.`, `this.` — a member of a *value*'s type.
Dot,
/// `pkg::`, `cls::` — a member of a named unit.
Scope,
}
/// The head of a member access as the buffer spells it: the first identifier
/// of the chain, and the names between it and the cursor.
///
/// `item.hdr.` is `head = "item"`, `mids = ["hdr"]` — exactly the two
/// arguments [`vlog_semantic::Semantics::member_site`] takes, because they
/// are exactly what `bind.rs`'s own `spine` records for the same expression.
/// For [`Sep::Scope`] the head is the whole `::` path (`pkg`, `pkg::cls`) and
/// `mids` is empty.
struct Spine {
head: String,
mids: Vec<String>,
}
impl Word {
/// The bytes a completion replaces: the word as typed.
fn range(&self, cursor: u32) -> TextRange {
TextRange::new(self.start, cursor)
}
}
/// The identifier run ending at the cursor, and the shape of the line it sits
/// on. `None` only when the cursor is not on a character boundary of the text
/// the server holds.
fn typed_word(doc: &Document, cursor: u32) -> Option<Word> {
let text = doc.text.get(..cursor as usize)?;
let head = text.trim_end_matches(is_ident_char);
let start = head.len();
let backtick = head.ends_with('`');
let bare = match backtick {
true => head.get(..head.len() - 1)?,
false => head,
};
let line_start = bare.rfind('\n').map_or(0, |newline| newline + 1);
let head = bare.get(line_start..)?;
let at_line_start = !backtick && line_head_is_blank(&doc.text, start as u32);
// `end else` and `end else` are the same head; nothing else is compared,
// so one `split_whitespace` join is the whole normalization needed.
let words = head.split_whitespace().collect::<Vec<&str>>().join(" ");
let statement_head = !backtick && STATEMENT_HEADS.contains(&words.as_str());
// A backtick admits only a macro name, and a macro name follows no
// separator, so the two questions never both apply.
let (sep, spine) = match backtick {
true => (None, None),
false => separator(bare),
};
Some(Word {
text: text.get(start..)?.to_string(),
start: start as u32,
backtick,
at_line_start,
statement_head,
sep,
spine,
})
}
/// The separator `before` ends with, and the head spine standing before that.
///
/// `::` is checked first, so a `pkg::` is never read as the lone `:` of a
/// case item, a block label or a ternary — that one is deliberately **not** a
/// separator, and a request there falls through to the ordinary six tiers
/// exactly as it always did.
fn separator(before: &str) -> (Option<Sep>, Option<Spine>) {
if let Some(rest) = before.strip_suffix("::") {
return (Some(Sep::Scope), scope_head(rest));
}
if let Some(rest) = before.strip_suffix('.') {
return (Some(Sep::Dot), dot_spine(rest));
}
(None, None)
}
/// The `::` path ending at `before`: `pkg`, `pkg::cls`.
fn scope_head(before: &str) -> Option<Spine> {
let mut segments = Vec::new();
let mut rest = before;
loop {
let (head, name) = split_ident(rest)?;
segments.push(name.to_string());
match head.strip_suffix("::") {
Some(next) => rest = next,
None => break,
}
}
segments.reverse();
Some(Spine { head: segments.join("::"), mids: Vec::new() })
}
/// The `.`-joined spine ending at `before`: `item`, `cfg.vif`, `q[i]`,
/// `this`, `super`.
///
/// **What it reads, and nothing else**: identifiers joined by `.`, each
/// optionally carrying balanced `[…]` index suffixes, which are stripped —
/// `q[i].` and `arr[3][k].` name a member of the element type, which is the
/// declared type name either way. Everything else answers `None`, and `None`
/// means the response is nothing at all rather than a guess: a call
/// (`f().b`), a cast, a concatenation, a macro invocation, a `::`-qualified
/// head (`pkg::cls.`, which is not how a class member is written anyway), and
/// whitespace anywhere in the spine (`a . b`, legal SystemVerilog nobody
/// writes — refusing it costs a popup, accepting it would mean deciding where
/// an expression ends by scanning backwards over arbitrary text).
fn dot_spine(before: &str) -> Option<Spine> {
let mut segments: Vec<String> = Vec::new();
let mut rest = before;
loop {
let (head, name) = split_ident(strip_indices(rest)?)?;
segments.push(name.to_string());
match head.strip_suffix('.') {
Some(next) => rest = next,
None => {
// A head reached through `::` is a unit, not a value, and
// `member_site` resolves the head on the lexical chain.
if head.ends_with(':') {
return None;
}
break;
}
}
}
segments.reverse();
let mut mids = segments;
let head = mids.remove(0);
Some(Spine { head, mids })
}
/// `text` split at the start of the identifier run it ends with, as
/// (what precedes it, the identifier). `None` when it does not end with one,
/// or when the run starts with a digit — that is a number, not a name.
fn split_ident(text: &str) -> Option<(&str, &str)> {
let head = text.trim_end_matches(is_ident_char);
let name = text.get(head.len()..)?;
if name.is_empty() || name.starts_with(|c: char| c.is_ascii_digit()) {
return None;
}
Some((head, name))
}
/// `text` with every balanced `[…]` it ends with removed. `None` when a `]`
/// has no matching `[` — an expression this cannot read, so nothing is
/// offered for it.
fn strip_indices(text: &str) -> Option<&str> {
let mut rest = text;
while rest.ends_with(']') {
let mut depth = 0usize;
let mut opened = None;
for (i, byte) in rest.bytes().enumerate().rev() {
match byte {
b']' => depth += 1,
b'[' => {
depth = depth.checked_sub(1)?;
if depth == 0 {
opened = Some(i);
break;
}
}
_ => {}
}
}
rest = rest.get(..opened?)?;
}
Some(rest)
}
fn is_ident_char(ch: char) -> bool {
ch.is_ascii_alphanumeric() || ch == '_' || ch == '$'
}
/// Whether nothing but indentation stands before `at` on its line — half of
/// the module gate, shared by [`typed_word`] and [`at_instantiation_site`].
fn line_head_is_blank(text: &str, at: u32) -> bool {
let Some(head) = text.get(..at as usize) else { return false };
let line_start = head.rfind('\n').map_or(0, |newline| newline + 1);
head.get(line_start..).is_some_and(|head| head.chars().all(|c| c == ' ' || c == '\t'))
}
/// Whether a module instantiation may be written starting at `at`.
///
/// **Tier 0's own gate**, factored out so `inline.rs`'s ghost instantiation
/// asks the identical question: the two features offer the same construct, and
/// a second answer to "may an instantiation go here" would eventually disagree
/// with this one. Both halves are here — the word must start its line, and the
/// scope chain covering it must be one an item belongs to (see
/// [`at_module_item`] for what that means and what it cannot see).
pub(crate) fn at_instantiation_site(doc: &Document, at: u32) -> bool {
if !line_head_is_blank(&doc.text, at) {
return false;
}
at_module_item(doc, &enclosing_scopes(&doc.tokens, at), at)
}
/// The whitespace the line holding `offset` begins with.
fn line_indent(text: &str, offset: u32) -> String {
let Some(head) = text.get(..offset as usize) else { return String::new() };
let line_start = head.rfind('\n').map_or(0, |newline| newline + 1);
head.get(line_start..).unwrap_or("").chars().take_while(|c| *c == ' ' || *c == '\t').collect()
}
/// Whether `at` is somewhere a module instantiation could be written, judged
/// over the token stream.
///
/// This is a **heuristic, not a parse**, and the README says exactly what it
/// gets wrong. It reuses `pairs::analyze` — the same scope matcher the
/// begin/end rainbow runs on — so a half-typed buffer costs nothing extra and
/// an unbalanced one still answers. Three conditions, all necessary:
///
/// 1. the innermost scope open here is one of [`ITEM_SCOPES`];
/// 2. no scope in the chain is one of [`NOT_ITEM_SCOPES`], so a `begin` inside
/// a `function` or a `case` arm is rejected however module-ish its parent;
/// 3. the outermost `begin` in the chain is not a procedural one — a
/// generate-`for`'s `begin` qualifies, an `always @(...)`'s does not.
///
/// Parentheses close the door too: an item never starts inside one, which is
/// what keeps a port list and a connection list out.
fn at_module_item(doc: &Document, chain: &[(&'static str, TextRange)], at: u32) -> bool {
let tokens = &doc.tokens;
if tokens.is_empty() {
return false;
}
let Some(&(innermost, opener)) = chain.first() else { return false };
if !ITEM_SCOPES.contains(&innermost) {
return false;
}
if chain.iter().any(|(keyword, _)| NOT_ITEM_SCOPES.contains(keyword)) {
return false;
}
let outermost_begin = chain.iter().rev().find(|(keyword, _)| *keyword == "begin");
if let Some(&(_, span)) = outermost_begin {
if is_procedural(tokens, span.start) {
return false;
}
}
balanced(tokens, opener.end, at)
}
/// Whether `at` is somewhere a *statement* could be written, judged over the
/// same scope chain [`at_module_item`] reads.
///
/// Two ways to qualify, and they are the only two this asks about:
///
/// 1. the innermost open scope is a `function` or a `task`, whose body is
/// statements all the way down; or
/// 2. it is a `begin`/`fork` whose outermost `begin` is a procedural one — the
/// exact inverse of the test that keeps module items out of an `always`.
///
/// Everything else is refused, `case` arms included: a bare `if` is not a
/// legal case item, and a gate that guesses at one would offer a template that
/// does not compile. Parentheses close the door here too.
fn at_statement(doc: &Document, chain: &[(&'static str, TextRange)], at: u32) -> bool {
let tokens = &doc.tokens;
if tokens.is_empty() {
return false;
}
let Some(&(innermost, opener)) = chain.first() else { return false };
if !STATEMENT_SCOPES.contains(&innermost) {
return false;
}
if innermost == "begin" || innermost == "fork" {
let in_subprogram = chain.iter().any(|(kw, _)| *kw == "function" || *kw == "task");
let outermost_begin = chain.iter().rev().find(|(keyword, _)| *keyword == "begin");
let procedural = match outermost_begin {
Some(&(_, span)) => is_procedural(tokens, span.start),
None => false,
};
if !in_subprogram && !procedural {
return false;
}
}
balanced(tokens, opener.end, at)
}
/// The scopes open at `at`, innermost first, as `(keyword, opener span)`.
fn enclosing_scopes(tokens: &[Token], at: u32) -> Vec<(&'static str, TextRange)> {
let analysis = pairs::analyze(tokens);
let mut out: Vec<(&'static str, TextRange)> = analysis
.pairs
.iter()
.filter(|pair| pair.open.end <= at && at <= pair.close.start)
.map(|pair| (pair.keyword, pair.open))
.chain(
analysis
.unmatched_open
.iter()
.filter(|open| open.span.end <= at)
.map(|open| (open.keyword, open.span)),
)
.collect();
// Innermost first: the scope that opened last is the one we are in.
out.sort_by_key(|(_, span)| std::cmp::Reverse(span.start));
out
}
/// Whether the `begin` starting at `offset` belongs to a procedural block.
///
/// Read backwards from the keyword: `always @(posedge clk) begin` reaches `@`
/// and then `always`, `initial begin` reaches `initial`, while a generate
/// `for (genvar i = 0; ...) begin` reaches the `;` inside its own header and a
/// `generate begin` reaches `generate`. Whichever comes first decides.
fn is_procedural(tokens: &[Token], offset: u32) -> bool {
// A token starting exactly at `offset` is the first one that starts at or
// after it: every earlier token starts before, every later token after.
let begin = first_token_from(tokens, offset);
if tokens.get(begin).map(|token| token.span.start) != Some(offset) {
return false;
}
for token in tokens[..begin].iter().rev() {
if PROCEDURAL.iter().any(|kw| token.text == *kw) {
return true;
}
if STATEMENT_END.iter().any(|kw| token.text == *kw) {
return false;
}
}
false
}
/// Whether every parenthesis opened between `from` and `at` was closed again.
fn balanced(tokens: &[Token], from: u32, at: u32) -> bool {
let mut depth = 0i32;
// The tokens whose start falls in `[from, at)` are a contiguous run,
// because starts rise across the vector — so the filter this replaced was
// reading the whole buffer to reach a window the two bounds name outright.
let window = first_token_from(tokens, from)..first_token_from(tokens, at);
for token in &tokens[window] {
if token.kind != TokenKind::Symbol {
continue;
}
match token.text.as_str() {
"(" => depth += 1,
")" => depth -= 1,
_ => {}
}
}
depth == 0
}
#[cfg(test)]
mod tests {
use super::*;
use crate::settings::ClientSettings;
use crate::uri::path_to_uri;
use std::fs;
use std::path::PathBuf;
const SUB: &str = "\
module sub #(
parameter int WIDTH = 8
) (
input logic clk,
input logic [WIDTH-1:0] data,
output logic ready
);
endmodule
";
/// Completion's own view of the three new kinds, and the detail card that
/// used to hard-code "module" over an interface — the C2 wrong answer
/// (`docs/features/interface-semantics/README.md`).
#[test]
fn an_interface_completes_as_an_interface() {
assert_eq!(completion_kind(SymbolKind::Interface), CompletionItemKind::INTERFACE);
assert_eq!(completion_kind(SymbolKind::Modport), CompletionItemKind::INTERFACE);
assert_eq!(completion_kind(SymbolKind::Clocking), CompletionItemKind::EVENT);
let index = vlog_semantic::WorkspaceIndex::build([
(PathBuf::from("/rtl/bus_if.sv"), "interface bus_if;\nendinterface\n"),
(PathBuf::from("/rtl/sub.sv"), SUB),
]);
assert!(module_detail(&index, "bus_if", None).starts_with("interface"));
assert!(module_detail(&index, "sub", None).starts_with("module"));
// The ghost-instantiation lookups reach an interface too.
assert_eq!(
nearest_definition(&index, "bus_if", None).map(|p| p.display().to_string()),
Some("/rtl/bus_if.sv".to_string())
);
}
/// [`is_procedural`] used to sweep the vector for the token starting at
/// the keyword, and [`balanced`] used to sweep all of it to reach a window
/// two offsets name. Both now binary-search; both must answer exactly what
/// the sweeps answered, at every byte and for every window.
#[test]
fn the_scope_gates_answer_what_their_sweeps_answered() {
let text = crate::state::mixed_buffer(20);
let doc = Document::new(None, text.clone(), &vlog_semantic::WorkspaceIndex::default());
let tokens = &doc.tokens;
for offset in 0..=text.len() as u32 {
let swept = tokens.iter().position(|token| token.span.start == offset);
let searched = {
let begin = first_token_from(tokens, offset);
tokens.get(begin).filter(|token| token.span.start == offset).map(|_| begin)
};
assert_eq!(swept, searched, "the token starting at {offset}");
}
// Every `begin`/`end` opener in the buffer against a spread of cursors
// after it: the two bounds are what pick the window out.
let openers: Vec<u32> = tokens
.iter()
.filter(|t| t.text == "begin" || t.text == "(")
.map(|t| t.span.end)
.collect();
assert!(openers.len() > 20, "premise: plenty of windows to check");
for from in openers {
for at in [from, from + 7, from + 60, from + 400, text.len() as u32] {
let mut depth = 0i32;
for token in tokens.iter().filter(|t| t.span.start >= from && t.span.start < at) {
if token.kind != TokenKind::Symbol {
continue;
}
match token.text.as_str() {
"(" => depth += 1,
")" => depth -= 1,
_ => {}
}
}
assert_eq!(depth == 0, balanced(tokens, from, at), "window {from}..{at}");
}
}
}
/// A scratch workspace root. Removed on drop.
struct Tree {
path: PathBuf,
}
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("lucisv_server_completion_{}_{name}", std::process::id()));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("temp dir");
Tree { path }
}
fn write(&self, rel: &str, text: &str) -> PathBuf {
let path = self.path.join(rel);
fs::write(&path, text).expect("write");
path
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
/// A two-file workspace with `top.sv` open, and the cursor at `needle`'s
/// end. `sub.sv` declares [`SUB`].
fn asking(name: &str, top: &str, needle: &str) -> (Tree, Workspace, Uri, Position) {
let tree = Tree::new(name);
tree.write("sub.sv", SUB);
opened(tree, top, needle)
}
/// The same, with whatever `tree` already holds and no `sub.sv` implied.
fn opened(tree: Tree, top: &str, needle: &str) -> (Tree, Workspace, Uri, Position) {
opened_named(tree, "top.sv", top, needle)
}
/// The same again, with the buffer's file name spelled out — which is what
/// decides its dialect.
fn opened_named(
tree: Tree,
file: &str,
top: &str,
needle: &str,
) -> (Tree, Workspace, Uri, Position) {
let path = tree.write(file, 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 doc = ws.document(&uri).expect("open");
let position = doc.positions().position(offset);
(tree, ws, uri, position)
}
fn items(response: Option<CompletionResponse>) -> Vec<CompletionItem> {
match response {
Some(CompletionResponse::List(list)) => list.items,
Some(CompletionResponse::Array(items)) => items,
None => Vec::new(),
}
}
fn inserted(item: &CompletionItem) -> String {
match item.text_edit.as_ref().expect("a text edit") {
CompletionTextEdit::Edit(edit) => edit.new_text.clone(),
CompletionTextEdit::InsertAndReplace(edit) => edit.new_text.clone(),
}
}
/// The tier an item was filed under, read off its `sortText`.
fn tier(item: &CompletionItem) -> char {
item.sort_text.as_ref().and_then(|s| s.chars().next()).expect("every item is sorted")
}
/// Only the module skeletons — tier 0, the M4 items.
fn skeletons(items: &[CompletionItem]) -> Vec<&CompletionItem> {
items.iter().filter(|item| tier(item) == TIER_MODULE).collect()
}
fn find<'a>(items: &'a [CompletionItem], label: &str) -> Option<&'a CompletionItem> {
items.iter().find(|item| item.label == label)
}
fn labels(items: &[CompletionItem]) -> Vec<&str> {
items.iter().map(|item| item.label.as_str()).collect()
}
// ------------------------------------------------------------------
// tier 0's header slice (2026-08-28) — it must change no answer
// ------------------------------------------------------------------
/// Every header shape the slice has to survive, as (file text, module).
///
/// The list is the argument that the slice changes nothing: each entry is
/// planned both ways below and the two plans are compared field by field.
const SHAPES: &[(&str, &str)] = &[
// The ordinary ANSI header, params and all.
(SUB, "sub"),
// No ports at all.
("module bare;\nendmodule\n", "bare"),
// An empty port list.
("module empty ();\n logic x;\nendmodule\n", "empty"),
// A package import written into the header: its `;` is not the
// header's, and a slice that stopped there would report no ports.
(
"package p;\n localparam int W = 4;\nendpackage\n\
module imported import p::*; #(\n parameter int W = 8\n) (\n \
input logic clk,\n output logic [W-1:0] q\n);\n \
assign q = '0;\nendmodule\n",
"imported",
),
// Two imports, then a parameter list.
(
"package p;\nendpackage\npackage q;\nendpackage\n\
module twice import p::*; import q::*; (input logic a);\nendmodule\n",
"twice",
),
// A **non-ANSI** port list: the directions live in the body, which is
// exactly what the slice drops.
(
"module old (a, b);\n input wire [7:0] a;\n output reg b;\n \
always @* b = |a;\nendmodule\n",
"old",
),
// Non-ANSI with nothing declaring the ports at all.
("module silent (a, b);\nendmodule\n", "silent"),
// A comment and an attribute inside the header.
(
"module noisy /* mid */ #(\n parameter int W = 2 // the width\n) (\n \
input logic clk\n);\nendmodule\n",
"noisy",
),
// A lifetime qualifier.
("module automatic lifetime (input logic a);\nendmodule\n", "lifetime"),
// A second module in the same file, after the one being planned.
(
"module first (input logic a);\nendmodule\n\
module second (output logic b);\nendmodule\n",
"first",
),
// …and before it, so the slice's prefix carries a whole module.
(
"module first (input logic a);\nendmodule\n\
module second (output logic b);\nendmodule\n",
"second",
),
// A compiler directive between the name and the port list, which the
// whitelist refuses outright.
("`define PORTS input logic clk\nmodule gated `PORTS ;\nendmodule\n", "gated"),
// A directive *inside* the port list, which carries a warning the two
// plans must both raise.
(
"module ifdefd (\n input logic clk\n`ifdef EXTRA\n , input logic more\n\
`endif\n);\nendmodule\n",
"ifdefd",
),
// An escaped identifier for the module and for a port.
("module \\odd-name ( input logic \\a-b );\nendmodule\n", "\\odd-name"),
// A header longer than the first rung of the window ladder.
(WIDE, "wide"),
// QA (performance wave Lane B, 2026-08-28): a genuine attribute
// instance, `(* ... *)`, right after the module name and before the
// parameter list — the one shape the "noisy" case above is commented
// as covering but does not (it has two comments, no attribute).
// **Finding, not a regression this round introduced**: a module with
// an attribute anywhere near its header is not indexed as a `Module`
// unit at all (see
// `a_module_with_an_attribute_near_its_header_is_not_indexed_at_all`),
// so this pins the safe side effect — `module_header` declines before
// its whitelist walk ever runs — rather than the whitelist's own
// handling of attributes, which this shape cannot reach.
(
"module attributed (* some_attr *) #(\n parameter int W = 2\n) (\n \
input logic clk\n);\nendmodule\n",
"attributed",
),
// An attribute instance *inside* the port list, attached to one port.
// Same finding as `attributed`: not indexed, so not reached either.
(
"module port_attributed (\n input logic clk,\n (* keep *) output logic q\n\
);\nendmodule\n",
"port_attributed",
),
// A single import declaration naming several packages, comma
// separated (`import a::*, b::*;`) — one statement, not two, and the
// whitelist's `skip_to_semicolon` must not stop at the first `::`.
(
"package p;\nendpackage\npackage q;\nendpackage\n\
module chained import p::*, q::*; (input logic a);\nendmodule\n",
"chained",
),
// A parameter default whose string literal carries the exact bytes
// the whitelist watches for — `;` and `)` — which must stay inside
// the `String` token and never be mistaken for header punctuation.
(
"module stringy #(\n parameter string S = \"a;b)c\"\n) (\n \
input logic clk\n);\nendmodule\n",
"stringy",
),
// CRLF line endings through the whole header.
("module crlf (\r\n input logic clk\r\n);\r\nendmodule\r\n", "crlf"),
];
/// A header wider than [`HEADER_WINDOWS`]`[0]`, so the ladder has to climb.
const WIDE: &str = "module wide (\n input logic port_number_zero_with_a_long_name,\n \
input logic port_number_one_with_a_long_name,\n \
input logic port_number_two_with_a_long_name,\n \
input logic port_number_three_with_a_long_name,\n \
input logic port_number_four_with_a_long_name,\n \
input logic port_number_five_with_a_long_name,\n \
output logic port_number_six_with_a_long_name\n);\n \
assign port_number_six_with_a_long_name = port_number_zero_with_a_long_name;\nendmodule\n";
/// The whole argument for the slice: for every shape above, the plan built
/// from the header alone is the plan built from the whole file. Where it
/// would not be — a non-ANSI list, a header the whitelist refuses — the
/// guard in [`plan_for`] sends the question back to the whole file, so the
/// comparison holds there too.
#[test]
fn the_header_slice_plans_exactly_what_the_whole_file_plans() {
for (text, module) in SHAPES {
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path.clone(), *text)]);
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let semantics = vlog_semantic::analyze(&tree, text);
let site = Site { semantics: &semantics, offset: 0 };
let whole = vlog_refactor::instantiation_plan(module, text, Some(site));
let ours = plan_for(&index, module, text, site);
assert_eq!(ours, whole, "{module}");
}
}
/// QA (performance wave Lane B, 2026-08-28): the equality above holds
/// trivially for a shape the whitelist declines — both sides parse the
/// whole file, so a wrong slice could hide behind that. These shapes must
/// actually slice, so the comparison exercises the whitelist walk it is
/// meant to pin: an `import a::*, b::*;` chain (one statement, several
/// packages — `skip_to_semicolon` must not stop at the first `::`), a
/// `;`/`)` sitting inside a string literal, and CRLF endings.
#[test]
fn the_attack_shapes_actually_slice_rather_than_passing_the_pin_vacuously() {
for module in ["chained", "stringy", "crlf", "twice", "imported"] {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
module_header(&index, module, text).is_some(),
"{module}: expected the header to actually slice, not fall back whole-file"
);
}
}
/// QA finding (performance wave Lane B, 2026-08-28), not a regression this
/// round introduced: a module with an attribute instance (`(* ... *)`)
/// anywhere near its header — right after its name, or on one of its
/// ports — is not indexed as a `Module` unit **at all**.
/// `WorkspaceIndex::units` comes back empty, so [`module_header`] declines
/// at the very first line (no `[def]` to anchor on) before the whitelist
/// walk ever runs, and completion's module tier — which sources its
/// candidate names from the same table — never offers the module in the
/// first place. This is a `vlog_semantic`/`vlog_parser` parsing gap, not a
/// completion-core one: it is filed in `docs/features/completion-core/
/// README.md`'s QA log rather than fixed here, because `vlog_semantic` is
/// outside this round's touched files. The two "attribute" shapes this QA
/// round added to [`SHAPES`] (`attributed`, `port_attributed`) still pass
/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] — but only
/// because both sides of that comparison fall back to the same whole-file
/// parse, which this test makes explicit rather than leaving it as an
/// unremarked side effect of the pin.
#[test]
fn a_module_with_an_attribute_near_its_header_is_not_indexed_at_all() {
for module in ["attributed", "port_attributed"] {
let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES");
let path = PathBuf::from("/rtl/shape.sv");
let index = WorkspaceIndex::build(vec![(path, *text)]);
assert!(
index.units(module).is_empty(),
"{module}: if this starts finding a unit, module_header should be re-audited \
for whether it now slices attributes correctly rather than by lucky fallback"
);
assert!(
module_header(&index, module, text).is_none(),
"{module}: no unit to anchor on"
);
}
}
/// The guard is not decoration: a non-ANSI module really does plan
/// differently off its header, and really is sent back to the whole file.
#[test]
fn a_non_ansi_port_list_is_planned_from_the_whole_file() {
let text = "module old (a, b);\n input wire [7:0] a;\n output reg b;\nendmodule\n";
let path = PathBuf::from("/rtl/old.sv");
let index = WorkspaceIndex::build(vec![(path, text)]);
let header = module_header(&index, "old", text).expect("the header slices");
let sliced = vlog_refactor::instantiation_plan("old", &header, None).expect("a plan");
assert!(
sliced.ports.iter().all(|p| p.dir.is_empty() && p.ty.is_empty()),
"premise: the header alone knows nothing about these ports"
);
let (tree, _) = vlog_parser::parse_source_tolerant(text);
let semantics = vlog_semantic::analyze(&tree, text);
let site = Site { semantics: &semantics, offset: 0 };
let guarded = plan_for(&index, "old", text, site).expect("a plan");
assert_eq!(guarded.ports[0].dir, "input");
assert_eq!(guarded.ports[0].ty, "wire [7:0]");
}
/// The whole answer, pinned at the prefixes the hot path is worst at — the
/// empty one and a one-character one, where every tier is at its widest.
/// Tier 0 answers with names, so the pin spells out every module item's
/// label *and* the text it inserts, which is now the label again.
#[test]
fn the_answer_is_pinned_at_the_prefixes_the_hot_path_is_worst_at() {
let tree = Tree::new("pinned");
tree.write("sub.sv", SUB);
tree.write("alpha.sv", "module alpha (\n input logic clk\n);\nendmodule\n");
tree.write("submarine.sv", "module submarine ();\nendmodule\n");
let (_tree, mut ws, uri, _) =
opened(tree, "module top;\n logic clk;\n \nendmodule\n", " ");
// Nothing typed, then one character — the two widest requests there
// are. `top` is in the answer because the buffer declares it and the
// index holds it like any other module.
let mut answer = |typed: &str| {
let text = format!("module top;\n logic clk;\n {typed}\nendmodule\n");
ws.set_document(uri.clone(), text.clone());
let offset = (text.find(&format!("\n {typed}\n")).expect("the line") + 3) as u32
+ typed.len() as u32;
let doc = ws.document(&uri).expect("open");
let position = doc.positions().position(offset);
items(completions(&ws, &uri, position, true))
};
for (typed, expected) in
[("", vec!["alpha", "sub", "submarine", "top"]), ("s", vec!["sub", "submarine"])]
{
let items = answer(typed);
let found: Vec<&str> =
skeletons(&items).iter().map(|item| item.label.as_str()).collect();
assert_eq!(found, expected, "module items after typing {typed:?}");
}
// …and the exact text each of them inserts, which is the name and
// nothing else however many ports the module has. The instantiation is
// `inline.rs`'s business now.
let items = answer("");
for name in ["sub", "alpha", "submarine"] {
let item = find(&items, name).expect("the module item");
assert_eq!(inserted(item), name, "the popup inserts the name alone");
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
assert_eq!(item.insert_text_mode, None, "there is no indentation to keep");
}
}
/// A file edited on disk since the index last read it has moved every span
/// the index holds, so the slice must not take one on trust.
#[test]
fn a_stale_index_span_declines_to_slice_rather_than_slicing_the_wrong_bytes() {
let text =
"module a (input logic p);\nendmodule\nmodule sliced (input logic q);\nendmodule\n";
let index = WorkspaceIndex::build(vec![(PathBuf::from("/rtl/a.sv"), text)]);
assert!(module_header(&index, "sliced", text).is_some(), "premise: it slices normally");
// The same index against a file whose text has shifted underneath it.
let moved = format!("// a line nobody told the index about\n{text}");
assert_eq!(module_header(&index, "sliced", &moved), None, "the name is no longer there");
}
// ------------------------------------------------------------------
// tier 0 — module names (level 1 of the instantiation wave, 2026-08-30)
// ------------------------------------------------------------------
#[test]
fn a_module_name_at_item_position_completes_to_the_name_alone() {
let top = "module top;\n logic clk;\n su\nendmodule\n";
let (_tree, ws, uri, position) = asking("nameonly", top, " su");
let items = items(completions(&ws, &uri, position, true));
let modules = skeletons(&items);
assert_eq!(modules.len(), 1, "{items:#?}");
let item = modules[0];
assert_eq!(item.label, "sub");
assert_eq!(item.kind, Some(CompletionItemKind::MODULE), "still a module icon");
assert_eq!(item.detail.as_deref(), Some("module — sub.sv"));
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
assert_eq!(inserted(item), "sub", "the name, and the ghost writes the rest");
assert_eq!(item.documentation, None, "no plan was read, so there is nothing to show");
}
#[test]
fn the_snippet_flag_no_longer_changes_the_module_item() {
// The M4 fallback — a plain-text spelling of the skeleton for a client
// that never advertised `snippetSupport` — has nothing left to fall
// back from: the item is a word either way.
let top = "module top;\n logic clk;\n su\nendmodule\n";
let (_tree, ws, uri, position) = asking("plain", top, " su");
for snippets in [true, false] {
let items = items(completions(&ws, &uri, position, snippets));
let item = skeletons(&items)[0];
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
assert_eq!(inserted(item), "sub", "snippets: {snippets}");
}
}
/// The whole point of level 1: the popup no longer reads the files it
/// offers names from. Proved by deleting the declaring file after the
/// index has been built — the old tier answered nothing at all here,
/// because every item needed that file's text.
#[test]
fn the_module_tier_reads_no_file_and_so_answers_one_that_is_gone() {
let tree = Tree::new("noread");
let sub = tree.write("sub.sv", SUB);
let (_tree, ws, uri, position) =
opened(tree, "module top;\n logic clk;\n su\nendmodule\n", " su");
fs::remove_file(&sub).expect("remove the declaring file");
let items = items(completions(&ws, &uri, position, true));
assert_eq!(
skeletons(&items).iter().map(|item| item.label.as_str()).collect::<Vec<_>>(),
["sub"],
"the name comes from the index's table, not from the file: {items:#?}"
);
}
#[test]
fn the_edit_replaces_exactly_the_typed_word() {
let top = "module top;\n su\nendmodule\n";
let (_tree, ws, uri, position) = asking("replace", top, " su");
let items = items(completions(&ws, &uri, position, true));
for item in &items {
let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
assert_eq!(edit.range.start, Position { line: 1, character: 2 }, "{item:#?}");
assert_eq!(edit.range.end, Position { line: 1, character: 4 });
}
}
#[test]
fn no_skeleton_is_offered_in_the_middle_of_an_expression() {
// The other tiers answer here — a name is a name wherever it is
// written — but a fifteen-line instantiation is not.
for (name, top, needle) in [
("assign", "module top;\n wire x;\n assign x = su\nendmodule\n", "= su"),
("decl", "module top;\n logic su\nendmodule\n", "logic su"),
("conn", "module top;\n sub u (.clk(su\nendmodule\n", ".clk(su"),
("header", "module top (su\n);\nendmodule\n", "top (su"),
] {
let (_tree, ws, uri, position) = asking(name, top, needle);
let items = items(completions(&ws, &uri, position, true));
assert!(skeletons(&items).is_empty(), "{name}: {top}\n{items:#?}");
}
}
#[test]
fn no_skeleton_is_offered_inside_a_procedural_block() {
let top = "module top;\n always_ff @(posedge clk) begin\n su\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("always", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
let top = "module top;\n initial begin\n su\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("initial", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn no_skeleton_is_offered_inside_a_function_or_a_class() {
let top = "module top;\n function int f();\n su\n endfunction\nendmodule\n";
let (_tree, ws, uri, position) = asking("function", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
let top = "package p;\n class c;\n su\n endclass\nendpackage\n";
let (_tree, ws, uri, position) = asking("class", top, " su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn a_generate_block_is_still_item_position() {
let top = "\
module top;
for (genvar i = 0; i < 4; i++) begin : g
su
end
endmodule
";
let (_tree, ws, uri, position) = asking("genfor", top, " su");
assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1, "{top}");
let top = "module top;\n generate\n su\n endgenerate\nendmodule\n";
let (_tree, ws, uri, position) = asking("generate", top, " su");
assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1);
}
#[test]
fn no_skeleton_is_offered_outside_a_design_unit() {
let top = "su\nmodule top;\nendmodule\n";
let (_tree, ws, uri, position) = asking("toplevel", top, "su");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn a_prefix_that_matches_no_module_offers_no_skeleton() {
let top = "module top;\n zzz\nendmodule\n";
let (_tree, ws, uri, position) = asking("nomatch", top, " zzz");
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
}
#[test]
fn a_module_declared_twice_is_offered_by_name_and_names_the_copy_it_will_ghost() {
// Until 2026-08-30 tier 0 skipped it: there is no single definition to
// build a *skeleton* from, and the skeleton was the item. A name needs
// no definition, so round 1 offered the name and left the detail
// blank. Round 2 (owner ruling, same day) makes the ghost choose a
// copy rather than decline, so the popup names the copy the ghost will
// read — `nearest_definition`'s answer, which for a buffer at the tree
// root is the lexicographically smaller path.
let tree = Tree::new("dup");
tree.write("a.sv", "module dup ();\nendmodule\n");
tree.write("b.sv", "module dup ();\nendmodule\n");
let (_tree, ws, uri, position) = opened(tree, "module top;\n du\nendmodule\n", " du");
let items = items(completions(&ws, &uri, position, true));
let item = find(&items, "dup").expect("the name is still known");
assert_eq!(tier(item), TIER_MODULE, "{items:#?}");
assert_eq!(item.detail.as_deref(), Some("module — a.sv"));
}
/// The nearest-definition chooser, at the level `inline.rs` consumes it.
///
/// The rule is components, not bytes: `top_earlgrey` and `top_darjeeling`
/// share `hw` and nothing more, and a byte-wise prefix would count the
/// `hw/top_` they spell alike and rank the copies by a coincidence.
#[test]
fn the_nearest_definition_is_the_one_sharing_the_most_path_components() {
let earlgrey = PathBuf::from("/hw/top_earlgrey/ip/ast/rtl/ast_dft.sv");
let darjeeling = PathBuf::from("/hw/top_darjeeling/ip/ast/rtl/ast_dft.sv");
let text = "module ast_dft ();\nendmodule\n";
let index =
WorkspaceIndex::build(vec![(earlgrey.clone(), text), (darjeeling.clone(), text)]);
let asking = |from: &str| {
nearest_definition(&index, "ast_dft", Some(&PathBuf::from(from)))
.expect("a definition")
.to_path_buf()
};
assert_eq!(asking("/hw/top_earlgrey/rtl/top_earlgrey.sv"), earlgrey);
assert_eq!(asking("/hw/top_darjeeling/rtl/top_darjeeling.sv"), darjeeling);
// Near neither, and no path at all: the tie falls to the smaller path
// rather than to whatever the index happens to hold first.
assert_eq!(asking("/hw/ip/uart/rtl/uart.sv"), darjeeling);
assert_eq!(
nearest_definition(&index, "ast_dft", None).expect("a definition"),
darjeeling.as_path()
);
}
/// QA round-2 finding, fixed at lead review: a copy in the asking
/// buffer's own directory and one in a subdirectory of it share the same
/// number of leading components with the buffer (its filename never
/// matches a directory), and the lexicographic tie-break alone could pick
/// the deeper, less related copy. The real shape is opentitan's 61-way
/// `tb`: `rstmgr/dv/tb.sv` must beat `rstmgr/dv/rstmgr_cnsty_chk/tb.sv`
/// for a buffer in `rstmgr/dv`, even though `'r' < 't'`.
#[test]
fn the_direct_sibling_beats_a_deeper_copy_that_ties_on_the_shared_prefix() {
let sibling = PathBuf::from("/hw/ip/rstmgr/dv/tb.sv");
let deeper = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_cnsty_chk/tb.sv");
let text = "module tb ();\nendmodule\n";
for sources in [
vec![(sibling.clone(), text), (deeper.clone(), text)],
vec![(deeper.clone(), text), (sibling.clone(), text)],
] {
let index = WorkspaceIndex::build(sources);
let from = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_env.sv");
assert_eq!(
nearest_definition(&index, "tb", Some(&from)).expect("a definition"),
sibling.as_path(),
"the shallower copy is the nearer one"
);
}
// …and depth only breaks a tie: a deeper copy that genuinely shares
// more of the asking path still wins.
let index = WorkspaceIndex::build(vec![(sibling.clone(), text), (deeper.clone(), text)]);
let from = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_cnsty_chk/checker.sv");
assert_eq!(
nearest_definition(&index, "tb", Some(&from)).expect("a definition"),
deeper.as_path(),
"sharing more components outranks being shallow"
);
}
/// The answer is a property of the paths, not of the order the index was
/// built in — which is what makes it the same answer twice in a row, and
/// the same answer in two editors.
#[test]
fn the_nearest_definition_does_not_depend_on_the_order_the_index_was_built_in() {
let earlgrey = PathBuf::from("/hw/top_earlgrey/ast_dft.sv");
let darjeeling = PathBuf::from("/hw/top_darjeeling/ast_dft.sv");
let text = "module ast_dft ();\nendmodule\n";
let forwards =
WorkspaceIndex::build(vec![(earlgrey.clone(), text), (darjeeling.clone(), text)]);
let backwards =
WorkspaceIndex::build(vec![(darjeeling.clone(), text), (earlgrey.clone(), text)]);
for index in [&forwards, &backwards] {
let from = PathBuf::from("/hw/top_earlgrey/rtl/top.sv");
assert_eq!(
nearest_definition(index, "ast_dft", Some(&from)).expect("a definition"),
earlgrey.as_path()
);
assert_eq!(
nearest_definition(index, "ast_dft", None).expect("a definition"),
darjeeling.as_path()
);
}
}
/// A module only one file declares goes through the same chooser and comes
/// back with the file `vlog_refactor::module_definition` picks — the
/// equivalence that says round 2 widened the twice-declared case and moved
/// nothing else.
#[test]
fn one_declaration_is_chosen_exactly_as_module_definition_chooses_it() {
let path = PathBuf::from("/rtl/sub.sv");
let index = WorkspaceIndex::build(vec![(path.clone(), SUB)]);
let expected = vlog_refactor::module_definition(&index, "sub").expect("one definition");
assert_eq!(expected, path.as_path());
for from in [None, Some(PathBuf::from("/rtl/top.sv")), Some(PathBuf::from("/other/x.sv"))] {
assert_eq!(
nearest_definition(&index, "sub", from.as_deref()).expect("a definition"),
expected,
"{from:?}"
);
}
// And a name nothing declares is `None` here where it is an `Err`
// there — the same "no answer", spelled the way each caller reads it.
assert!(nearest_definition(&index, "nope", None).is_none());
assert!(vlog_refactor::module_definition(&index, "nope").is_err());
}
#[test]
fn a_tabstop_default_is_escaped_so_the_snippet_grammar_cannot_read_it() {
assert_eq!(snippet_hole(1, ""), "${1}");
assert_eq!(snippet_hole(2, "8"), "${2:8}");
assert_eq!(snippet_hole(3, "$bits(t)"), "${3:\\$bits(t)}");
assert_eq!(snippet_hole(4, "a}b\\c"), "${4:a\\}b\\\\c}");
}
// ------------------------------------------------------------------
// tier 3 — templates
// ------------------------------------------------------------------
/// Only the templates — tier 3.
fn template_labels(items: &[CompletionItem]) -> Vec<&str> {
items
.iter()
.filter(|item| tier(item) == TIER_TEMPLATE)
.map(|item| item.label.as_str())
.collect()
}
/// The items offered at `needle`'s end in a buffer named `file`.
fn offering(name: &str, file: &str, top: &str, needle: &str) -> Vec<CompletionItem> {
let (_tree, ws, uri, position) = opened_named(Tree::new(name), file, top, needle);
items(completions(&ws, &uri, position, true))
}
#[test]
fn a_statement_template_expands_where_a_statement_may_be_written() {
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let items = offering("stmt", "top.sv", top, " if");
let item = find(&items, "if begin/end").expect("the if template");
assert_eq!(item.kind, Some(CompletionItemKind::SNIPPET));
assert_eq!(item.insert_text_format, Some(InsertTextFormat::SNIPPET));
assert_eq!(item.filter_text.as_deref(), Some("if"), "the client filters on what is typed");
assert_eq!(
inserted(item),
"if (${1:cond}) begin\n $0\n end",
"the site's own indentation, the condition first and the body last"
);
assert!(template_labels(&items).contains(&"if/else"), "{:?}", template_labels(&items));
}
#[test]
fn a_template_never_swallows_the_keyword_it_is_reached_by() {
// Dedup is by label, so the labels are prose on purpose: `if` the
// keyword and `if begin/end` the template are two items, in that
// order of specificity.
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let items = offering("both", "top.sv", top, " if");
let keyword = find(&items, "if").expect("the bare keyword");
let template = find(&items, "if begin/end").expect("the template");
assert_eq!(tier(keyword), TIER_KEYWORD);
assert_eq!(tier(template), TIER_TEMPLATE);
assert!(template.sort_text < keyword.sort_text, "a template outranks the bare word");
}
#[test]
fn a_template_ranks_below_a_name_the_code_declares() {
let top = "\
module top;
logic if_enable;
always_comb begin
if
end
endmodule
";
let items = offering("rank", "top.sv", top, " if");
let symbol = find(&items, "if_enable").expect("a declaration in scope");
let template = find(&items, "if begin/end").expect("the template");
assert_eq!(tier(symbol), TIER_SCOPE);
assert!(symbol.sort_text < template.sort_text, "a real name beats a skeleton");
}
#[test]
fn statement_templates_and_item_templates_swap_places_with_the_position() {
// One prefix, `i`, reaching `if` in one place and `initial` in the
// other — so this is the gate and not the filter.
let inside = offering(
"posstmt",
"top.sv",
"module top;\n always_comb begin\n i\n end\nendmodule\n",
" i",
);
assert!(template_labels(&inside).contains(&"if begin/end"));
assert!(
!template_labels(&inside).contains(&"initial begin/end"),
"an initial block is not a statement: {:?}",
template_labels(&inside)
);
let at_item = offering("positem", "top.sv", "module top;\n i\nendmodule\n", " i");
assert!(template_labels(&at_item).contains(&"initial begin/end"));
assert!(
!template_labels(&at_item).contains(&"if begin/end"),
"a bare if is not a module item: {:?}",
template_labels(&at_item)
);
}
#[test]
fn an_always_template_is_a_module_item_and_nothing_else() {
let at_item = offering("alwitem", "top.sv", "module top;\n alw\nendmodule\n", " alw");
assert_eq!(
template_labels(&at_item),
["always_ff @(posedge clk)", "always_ff with reset", "always_comb begin/end"],
"and `alw` finds every one of them"
);
let inside = offering(
"alwstmt",
"top.sv",
"module top;\n always_comb begin\n alw\n end\nendmodule\n",
" alw",
);
assert!(template_labels(&inside).is_empty(), "{:?}", template_labels(&inside));
}
#[test]
fn a_declaration_template_is_offered_as_an_item_and_as_a_block_item() {
let at_item = offering("declitem", "top.sv", "module top;\n log\nendmodule\n", " log");
assert_eq!(template_labels(&at_item), ["logic name;", "logic [N:0] name;"]);
let inside = offering(
"declstmt",
"top.sv",
"module top;\n always_comb begin\n log\n end\nendmodule\n",
" log",
);
assert_eq!(template_labels(&inside), ["logic name;", "logic [N:0] name;"]);
}
#[test]
fn the_file_name_decides_which_dialect_is_offered() {
let sv = offering("dialectsv", "top.sv", "module top;\n l\nendmodule\n", " l");
assert!(template_labels(&sv).contains(&"logic name;"));
assert!(template_labels(&sv).contains(&"localparam int NAME = 0;"));
let v = offering("dialectv", "top.v", "module top;\n l\nendmodule\n", " l");
assert!(!template_labels(&v).contains(&"logic name;"), "`logic` is not Verilog");
assert!(template_labels(&v).contains(&"localparam integer NAME = 0;"));
let reg = offering("dialectreg", "top.v", "module top;\n r\nendmodule\n", " r");
assert_eq!(template_labels(&reg), ["reg name;", "reg [N:0] name;"]);
let sv_reg = offering("dialectsvreg", "top.sv", "module top;\n r\nendmodule\n", " r");
assert!(template_labels(&sv_reg).is_empty(), "no `reg` template in a .sv file");
let always = offering("dialectalw", "top.v", "module top;\n alw\nendmodule\n", " alw");
assert_eq!(
template_labels(&always),
["always @(posedge clk)", "always @(posedge clk or negedge rst_n)", "always @(*)"],
"and no always_ff, which a .v file's compiler would reject"
);
}
#[test]
fn an_else_template_follows_an_end_on_the_same_line() {
let top = "\
module top;
always_comb begin
if (a) begin
end el
end
endmodule
";
let items = offering("elsetail", "top.sv", top, "end el");
assert_eq!(template_labels(&items), ["else if", "else begin/end"]);
assert_eq!(
inserted(find(&items, "else if").expect("the else-if template")),
"else if (${1:cond}) begin\n $0\n end"
);
}
#[test]
fn a_word_in_the_middle_of_a_line_starts_no_statement() {
// The other half of the same rule: `x = if` is an expression, not a
// place a template belongs — and the general tiers still answer there.
let top = "module top;\n always_comb begin\n x = if\n end\nendmodule\n";
let items = offering("midline", "top.sv", top, "x = if");
assert!(template_labels(&items).is_empty(), "{:?}", template_labels(&items));
assert!(find(&items, "if").is_some(), "the keyword tier still answers");
}
#[test]
fn no_template_is_offered_where_a_statement_cannot_go() {
for (name, top, needle) in [
// A generate block is item position, not statement position.
("generate", "module top;\n generate\n if\n endgenerate\nendmodule\n", " if"),
// A `case` arm wants `label:`, not a bare statement.
(
"casearm",
"module top;\n always_comb begin\n case (s)\n if\n endcase\n end\nendmodule\n",
" if",
),
// Nothing at all is open here.
("toplevel", "if\nmodule top;\nendmodule\n", "if"),
// A port list is not a statement, however much it starts a line.
("ports", "module top (\n if\n);\nendmodule\n", " if"),
] {
let items = offering(name, "top.sv", top, needle);
assert!(template_labels(&items).is_empty(), "{name}: {:?}", template_labels(&items));
}
}
#[test]
fn a_subprogram_body_is_statement_position() {
for (name, top, needle) in [
("function", "module top;\n function int f();\n if\n endfunction\nendmodule\n", " if"),
("task", "module top;\n task t();\n if\n endtask\nendmodule\n", " if"),
(
"fnbegin",
"module top;\n function int f();\n begin\n if\n end\n endfunction\nendmodule\n",
" if",
),
] {
let items = offering(name, "top.sv", top, needle);
assert!(template_labels(&items).contains(&"if begin/end"), "{name}");
}
}
#[test]
fn nothing_templated_is_offered_inside_a_comment() {
let top = "module top;\n always_comb begin\n // if\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("tmplcomment", top, "// if");
assert!(completions(&ws, &uri, position, true).is_none());
}
#[test]
fn a_client_without_snippet_support_gets_the_template_filled_in() {
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("tmplplain", top, " if");
let items = items(completions(&ws, &uri, position, false));
let item = find(&items, "if begin/end").expect("the if template");
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
let text = inserted(item);
assert!(!text.contains('$'), "no tabstop syntax may reach a plain client: {text}");
assert_eq!(text, "if (cond) begin\n\n end");
let probe = format!("module p;\n always_comb begin\n {text}\n end\nendmodule\n");
assert!(
vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
"the inserted text must parse: {text}"
);
}
#[test]
fn a_templates_documentation_shows_what_it_expands_to() {
let top = "module top;\n alw\nendmodule\n";
let items = offering("tmpldocs", "top.sv", top, " alw");
let item = find(&items, "always_comb begin/end").expect("the always_comb template");
let Some(Documentation::MarkupContent(docs)) = &item.documentation else {
panic!("markdown documentation");
};
// Fenced with the language id the extension's TextMate grammar is
// registered for, so the panel renders highlighted rather than grey.
assert!(docs.value.starts_with("```systemverilog\n"), "{}", docs.value);
assert!(docs.value.contains("always_comb begin\n\nend"), "{}", docs.value);
assert_eq!(item.detail.as_deref(), Some("combinational block — template"));
}
// ------------------------------------------------------------------
// tier 4 — keywords
// ------------------------------------------------------------------
#[test]
fn every_keyword_the_lexer_knows_is_offered() {
let top = "module top;\n assign x = alw\nendmodule\n";
let (_tree, ws, uri, position) = asking("keyword", top, "= alw");
let items = items(completions(&ws, &uri, position, true));
let keywords: Vec<&str> =
items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect();
assert_eq!(keywords, ["always", "always_comb", "always_ff", "always_latch"]);
let always = find(&items, "always").expect("`always`");
assert_eq!(always.kind, Some(CompletionItemKind::KEYWORD));
assert_eq!(inserted(always), "always");
}
#[test]
fn the_keyword_tier_is_exactly_the_lexers_list() {
let top = "module top;\n assign x = \nendmodule\n";
let (_tree, ws, uri, position) = asking("allkeywords", top, "= ");
let items = items(completions(&ws, &uri, position, true));
let offered: HashSet<&str> =
items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect();
let known: HashSet<&str> = KEYWORDS.iter().copied().collect();
assert_eq!(offered, known, "no keyword may be missing and none invented");
}
// ------------------------------------------------------------------
// comments and strings, both ways round
// ------------------------------------------------------------------
#[test]
fn nothing_is_offered_inside_a_comment_or_a_string() {
for (name, top, needle) in [
("line", "module top;\n // wid\nendmodule\n", "// wid"),
("block", "module top;\n /* wid */\nendmodule\n", "/* wid"),
("trailing", "module top;\n logic a; // wid\nendmodule\n", "// wid"),
("string", "module top;\n initial $display(\"wid\");\nendmodule\n", "\"wid"),
] {
let (_tree, ws, uri, position) = asking(&format!("in{name}"), top, needle);
assert!(completions(&ws, &uri, position, true).is_none(), "{name}: {top}");
}
}
#[test]
fn the_byte_after_a_block_comment_is_code_again() {
// The other half of the boundary: `/* x */w|` is not inside anything.
let top = "module top;\n /* c */ wid\nendmodule\n";
let (_tree, ws, uri, position) = asking("afterblock", top, "*/ wid");
assert!(completions(&ws, &uri, position, true).is_some());
}
#[test]
fn a_name_that_only_a_comment_or_a_string_holds_is_never_a_candidate() {
let tree = Tree::new("harvest");
tree.write(
"other.sv",
"module other;\n // widget_in_comment\n logic widget_in_code;\n\
initial $display(\"widget_in_string\");\nendmodule\n",
);
let top = "module top;\n assign x = widget\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= widget");
let items = items(completions(&ws, &uri, position, true));
let labels = labels(&items);
assert!(labels.contains(&"widget_in_code"), "{labels:?}");
assert!(!labels.contains(&"widget_in_comment"), "a comment is not code: {labels:?}");
assert!(!labels.contains(&"widget_in_string"), "a string is not code: {labels:?}");
}
#[test]
fn a_buffer_that_does_not_lex_is_declined_rather_than_guessed_at() {
let top = "module top;\n logic a; /* unterminated\n wid\n";
let (_tree, ws, uri, position) = asking("nolex", top, " wid");
assert!(completions(&ws, &uri, position, true).is_none());
}
// ------------------------------------------------------------------
// tiers, ordering and dedup
// ------------------------------------------------------------------
#[test]
fn the_tiers_are_ordered_scope_then_project_then_keywords_then_words() {
let tree = Tree::new("tiers");
tree.write("pkg.sv", "package w_pkg;\n localparam K = 1;\nendpackage\n");
tree.write("other.sv", "module other;\n logic w_elsewhere;\nendmodule\n");
let top = "module top;\n logic w_local;\n assign x = w\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= w");
let items = items(completions(&ws, &uri, position, true));
assert_eq!(tier(find(&items, "w_local").expect("in scope")), TIER_SCOPE);
assert_eq!(tier(find(&items, "w_pkg").expect("a package")), TIER_INDEX);
assert_eq!(tier(find(&items, "wire").expect("a keyword")), TIER_KEYWORD);
assert_eq!(tier(find(&items, "w_elsewhere").expect("a project word")), TIER_WORD);
let scope = find(&items, "w_local").expect("in scope");
let word = find(&items, "w_elsewhere").expect("a project word");
assert!(scope.sort_text < word.sort_text, "the client sorts scope above words");
}
#[test]
fn a_name_that_is_both_in_scope_and_a_project_word_is_offered_once() {
let tree = Tree::new("dedup");
// The same name, declared here and used elsewhere in the project.
tree.write("other.sv", "module other;\n logic shared_name;\nendmodule\n");
let top = "module top;\n logic shared_name;\n assign x = shared\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= shared");
let items = items(completions(&ws, &uri, position, true));
let hits: Vec<&CompletionItem> =
items.iter().filter(|i| i.label == "shared_name").collect();
assert_eq!(hits.len(), 1, "{hits:#?}");
assert_eq!(tier(hits[0]), TIER_SCOPE, "the semantic tier wins");
assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE), "and its real kind with it");
}
#[test]
fn a_visible_declaration_carries_its_kind_and_the_line_it_was_written_on() {
let top = "\
module top #(parameter int WIDTH = 8) (input logic clk);
typedef logic [1:0] pair_t;
logic [WIDTH-1:0] data;
function int f(); return 0; endfunction
assign x =
endmodule
";
let (_tree, ws, uri, position) = asking("kinds", top, "assign x =");
let items = items(completions(&ws, &uri, position, true));
let kind = |label: &str| find(&items, label).unwrap_or_else(|| panic!("{label}")).kind;
assert_eq!(kind("WIDTH"), Some(CompletionItemKind::CONSTANT));
assert_eq!(kind("clk"), Some(CompletionItemKind::FIELD));
assert_eq!(kind("pair_t"), Some(CompletionItemKind::TYPE_PARAMETER));
assert_eq!(kind("data"), Some(CompletionItemKind::VARIABLE));
assert_eq!(kind("f"), Some(CompletionItemKind::FUNCTION));
assert_eq!(
find(&items, "data").expect("data").detail.as_deref(),
Some("logic [WIDTH-1:0] data;"),
"the declaration as written"
);
}
#[test]
fn only_what_the_scope_chain_reaches_is_in_the_semantic_tier() {
// `inner` is declared in a block the cursor is not in, so it may only
// arrive as a project word — never as a visible declaration.
let top = "\
module top;
initial begin : b
integer inner_only;
end
initial begin
x = inner
end
endmodule
";
let (_tree, ws, uri, position) = asking("scopewalk", top, "x = inner");
let items = items(completions(&ws, &uri, position, true));
let item = find(&items, "inner_only").expect("known as a word at least");
assert_eq!(tier(item), TIER_WORD, "{item:#?}");
}
// ------------------------------------------------------------------
// `define names and the backtick
// ------------------------------------------------------------------
#[test]
fn a_backtick_offers_macro_names_and_only_macro_names() {
let tree = Tree::new("macro");
tree.write("defs.svh", "`define WIDTH 8\n`define MAX(a, b) 0\n");
tree.write("other.sv", "module other;\n logic WIDGET;\nendmodule\n");
let top = "module top;\n assign x = `WI\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "`WI");
let items = items(completions(&ws, &uri, position, true));
assert_eq!(labels(&items), ["`WIDTH"], "only a macro may follow a backtick");
assert_eq!(inserted(&items[0]), "`WIDTH");
let CompletionTextEdit::Edit(edit) = items[0].text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
assert_eq!(
edit.range.start,
Position { line: 1, character: 13 },
"the typed backtick is replaced, not doubled"
);
}
#[test]
fn a_macro_name_without_a_backtick_is_offered_bare() {
// Where a macro name is written without one: `` `ifdef NAME ``.
let tree = Tree::new("macrobare");
tree.write("defs.svh", "`define WIDTH 8\n");
let top = "module top;\n assign x = WID\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= WID");
let items = items(completions(&ws, &uri, position, true));
let item = find(&items, "WIDTH").expect("the macro name");
assert_eq!(inserted(item), "WIDTH", "no backtick is invented");
assert_eq!(item.detail.as_deref(), Some("`define WIDTH"));
}
// ------------------------------------------------------------------
// filtering, the cap, and the scope ladder
// ------------------------------------------------------------------
#[test]
fn the_prefix_filters_server_side() {
let tree = Tree::new("prefix");
tree.write("other.sv", "module other;\n logic aaa_one, bbb_two;\nendmodule\n");
let top = "module top;\n assign x = aaa\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "= aaa");
let items = items(completions(&ws, &uri, position, true));
assert!(!items.is_empty());
for item in &items {
assert!(
starts_with_ignore_case(&item.label, "aaa"),
"{} does not start with the typed prefix",
item.label
);
}
}
#[test]
fn a_full_response_is_truncated_and_says_it_is_incomplete() {
let mut top = String::from("module top;\n");
for i in 0..LIMIT + 40 {
top.push_str(&format!(" logic wsig{i:04};\n"));
}
top.push_str(" assign x = wsig\nendmodule\n");
let (_tree, ws, uri, position) = asking("cap", &top, "= wsig");
let Some(CompletionResponse::List(list)) = completions(&ws, &uri, position, true) else {
panic!("a completion list");
};
assert_eq!(list.items.len(), LIMIT);
assert!(list.is_incomplete, "a truncated list must say so");
}
#[test]
fn a_file_outside_the_filelist_contributes_no_words() {
// M1's ladder decides what "the project" is, and the word tier is
// built from exactly that list.
let tree = Tree::new("filelist");
tree.write("listed.sv", "module listed;\n logic word_listed;\nendmodule\n");
tree.write("unlisted.sv", "module unlisted;\n logic word_unlisted;\nendmodule\n");
tree.write("files.f", "listed.sv\n");
let top = "module top;\n assign x = word_\nendmodule\n";
let path = tree.write("top.sv", top);
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings {
filelist: Some("files.f".to_string()),
..Default::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());
ws.rebuild_index();
let offset = (top.find("= word_").expect("needle") + 7) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let items = items(completions(&ws, &uri, position, true));
let labels = labels(&items);
assert!(labels.contains(&"word_listed"), "{labels:?}");
assert!(!labels.contains(&"word_unlisted"), "outside the project: {labels:?}");
}
#[test]
fn an_unsaved_edit_contributes_its_own_words_at_once() {
// The buffer's own token stream is read per request, so a name typed
// a moment ago is a candidate before anything is saved.
let top = "module top;\n logic fresh_name;\n assign x = fre\nendmodule\n";
let (_tree, ws, uri, position) = asking("unsaved", top, "= fre");
// The file on disk is `top` too, so make the buffer differ from it.
let edited = "module top;\n logic fresher_name;\n assign x = fre\nendmodule\n";
let mut ws = ws;
ws.set_document(uri.clone(), edited.to_string());
let items = items(completions(&ws, &uri, position, true));
assert!(labels(&items).contains(&"fresher_name"), "{:?}", labels(&items));
}
// ------------------------------------------------------------------
// the performance claim, measured
// ------------------------------------------------------------------
/// What a keystroke costs over the real corpus, and what the tables cost
/// to build. Skipped when `corpus/` is not checked out
/// (`tools/corpus_fetch.sh`), exactly like the other corpus tests.
///
/// The budgets are deliberately loose — a debug build on a loaded machine
/// is the worst case this ever runs in — and exist to catch an *order of
/// magnitude* regression, not to pin a number. The numbers themselves are
/// in `docs/features/completion-core/README.md`.
#[test]
fn a_keystroke_over_the_whole_corpus_stays_in_budget() {
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let started = std::time::Instant::now();
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![corpus.clone()]);
let build = started.elapsed();
// A buffer that is not on disk: it overlays the walk, so the corpus is
// never written to.
let top = "module lucisv_probe;\n logic clk;\n assign x = pr\nendmodule\n";
let uri = path_to_uri(&corpus.join("lucisv_probe.sv")).expect("uri");
ws.set_document(uri.clone(), top.to_string());
let offset = (top.find("= pr").expect("needle") + 4) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
// Warm, then the measurement: ten requests, worst one reported. Twice
// — once for a typed prefix, once for the empty one, which is the
// worst case there is (every tier matches, and the cap does the work).
let empty = ws.document(&uri).expect("open").positions().position(offset - 2);
let mut worst = std::time::Duration::ZERO;
let mut worst_empty = std::time::Duration::ZERO;
for round in 0..11 {
let started = std::time::Instant::now();
let typed = items(completions(&ws, &uri, position, true));
let after_typed = started.elapsed();
let started = std::time::Instant::now();
let all = items(completions(&ws, &uri, empty, true));
let after_empty = started.elapsed();
assert!(!typed.is_empty());
assert_eq!(all.len(), LIMIT, "the empty prefix fills the response");
if round > 0 {
worst = worst.max(after_typed);
worst_empty = worst_empty.max(after_empty);
}
}
// …and the fuzzy path, which is a *scan* of the whole word table
// where the two above are a binary search into it. Six characters,
// the shape the round is named after.
let fuzzy = "module lucisv_probe;\n logic clk;\n assign x = clkenq\nendmodule\n";
ws.set_document(uri.clone(), fuzzy.to_string());
let offset = (fuzzy.find("= clkenq").expect("needle") + 8) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let mut worst_fuzzy = std::time::Duration::ZERO;
for round in 0..11 {
let started = std::time::Instant::now();
let found = items(completions(&ws, &uri, position, true));
let elapsed = started.elapsed();
assert!(!found.is_empty(), "the buffer's own `clk` matches at least");
if round > 0 {
worst_fuzzy = worst_fuzzy.max(elapsed);
}
}
eprintln!(
"corpus: {} files, {} words, {} index names; index+tables built in {build:?}; \
worst request {worst:?} typed / {worst_empty:?} empty / {worst_fuzzy:?} fuzzy",
ws.index().files().len(),
ws.candidates().words("").len(),
ws.candidates().units("").len(),
);
assert!(worst < std::time::Duration::from_millis(150), "a keystroke cost {worst:?}");
assert!(worst_empty < std::time::Duration::from_millis(150), "{worst_empty:?}");
assert!(worst_fuzzy < std::time::Duration::from_millis(150), "{worst_fuzzy:?}");
}
/// What a **member** request costs over the real corpus, against the
/// shapes the feature is named for: a generated register struct
/// (`uart_reg2hw_t`, eleven fields whose types are eleven more structs in
/// the same package), one of its inner registers reached by the
/// synthesized key, a package, and a connection list on a real wide
/// module.
///
/// The member answer is a table lookup like every other tier — one
/// `member_site` walk over one file's scopes, then one `BTreeMap` scan
/// per unit on the chain — so it should be *cheaper* than the tiered
/// answer, which scans three tables. Same loose budget, same reason: an
/// order of magnitude, not a number.
#[test]
fn a_member_request_over_the_whole_corpus_stays_in_budget() {
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![corpus.clone()]);
let uri = path_to_uri(&corpus.join("lucisv_member_probe.sv")).expect("uri");
let mut worst = Vec::new();
for (what, top, needle) in [
(
"reg2hw.",
"module lucisv_member_probe;\n uart_reg_pkg::uart_reg2hw_t reg2hw;\n initial begin\n reg2hw.\n end\nendmodule\n",
" reg2hw.",
),
(
"reg2hw.ctrl.",
"module lucisv_member_probe;\n uart_reg_pkg::uart_reg2hw_t reg2hw;\n initial begin\n reg2hw.ctrl.\n end\nendmodule\n",
" reg2hw.ctrl.",
),
(
"uart_reg_pkg::",
"module lucisv_member_probe;\n initial begin\n $display(uart_reg_pkg::);\n end\nendmodule\n",
"uart_reg_pkg::",
),
// The connection list, against a real wide module in another
// file — the position the 2026-09-02 rework exists for.
(
"uart_core (.",
"module lucisv_member_probe;\n uart_core u_core (\n .\n );\nendmodule\n",
" .",
),
] {
ws.set_document(uri.clone(), top.to_string());
let offset = (top.find(needle).expect("needle") + needle.len()) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let mut slowest = std::time::Duration::ZERO;
let mut count = 0;
for round in 0..11 {
let started = std::time::Instant::now();
let found = items(completions(&ws, &uri, position, true));
let elapsed = started.elapsed();
count = found.len();
if round > 0 {
slowest = slowest.max(elapsed);
}
}
assert!(count > 0, "{what} must list members over the corpus");
worst.push(format!("{what} {count} members in {slowest:?}"));
assert!(slowest < std::time::Duration::from_millis(150), "{what} cost {slowest:?}");
}
eprintln!("corpus member requests: {}", worst.join(" / "));
}
/// **QA's own reproduction, against the real file.** `prim_fifo_sync`
/// derives `localparam int DepthW = prim_util_pkg::vbits(Depth+1)` in its
/// header; six `parameter`s stand above it. A `#(.` list must offer the
/// six and not the seventh. Skipped when `corpus/` is not checked out,
/// like every other corpus test.
#[test]
fn the_opentitan_shape_that_found_the_localparam_bug() {
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
if !corpus.is_dir() {
eprintln!("corpus/ not checked out — skipping");
return;
}
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![corpus.clone()]);
let top = "module lucisv_param_probe;\n prim_fifo_sync #(.) u_fifo ();\nendmodule\n";
let uri = path_to_uri(&corpus.join("lucisv_param_probe.sv")).expect("uri");
ws.set_document(uri.clone(), top.to_string());
let offset = (top.find("#(.").expect("needle") + 3) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(
found,
vec!["Depth", "NeverClears", "OutputZeroIfEmpty", "Pass", "Secure", "Width"],
"the six overridable parameters, and not the derived `DepthW`",
);
// …and `DepthW` is still *there*: a hierarchical read of it is legal
// and still resolves, which is what the split deliberately preserved.
assert!(
ws.index().members_of_chain("prim_fifo_sync").iter().any(|(name, _)| *name == "DepthW"),
"the localparam is still exported",
);
}
// ------------------------------------------------------------------
// fuzzy matching (2026-08-30) — docs/features/fuzzy-completion/README.md
// ------------------------------------------------------------------
/// A workspace holding the name the whole round is about, a scatter to
/// rank it against, and a `ce…` name that only a prefix reaches.
fn typing(name: &str) -> (Tree, Workspace, Uri) {
let tree = Tree::new(name);
tree.write(
"ast.sv",
"module ast;\n logic clk_osc_en_q;\n logic c_l_k_scatter;\n logic celsius;\n\
endmodule\n",
);
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
(tree, ws, uri)
}
/// The response to `typed`, written mid-expression in `top.sv` — the
/// position where no tier is position-gated off.
fn after_typing(ws: &mut Workspace, uri: &Uri, typed: &str) -> Option<CompletionResponse> {
let text = format!("module top;\n assign x = {typed}\nendmodule\n");
ws.set_document(uri.clone(), text.clone());
let offset =
(text.find(&format!("= {typed}\n")).expect("the line") + 2 + typed.len()) as u32;
let position = ws.document(uri).expect("open").positions().position(offset);
completions(ws, uri, position, true)
}
/// The headline: three characters reach a name no prefix ever would.
#[test]
fn three_characters_reach_a_name_a_prefix_never_would() {
let (_tree, mut ws, uri) = typing("fuzzyhit");
for typed in ["clkenq", "clken", "cen", "coq", "CLKENQ"] {
let found = items(after_typing(&mut ws, &uri, typed));
let item = find(&found, "clk_osc_en_q")
.unwrap_or_else(|| panic!("{typed:?} found {:?}", labels(&found)));
assert_eq!(tier(item), TIER_WORD, "a name used elsewhere in the project");
assert_eq!(inserted(item), "clk_osc_en_q", "the whole name is inserted");
}
}
/// …and the edit still replaces exactly what was typed, which is the
/// whole reason a fuzzy hit is usable at all: `clkenq` becomes
/// `clk_osc_en_q`, not `clkenqclk_osc_en_q`.
#[test]
fn a_fuzzy_hit_replaces_exactly_the_typed_word() {
let (_tree, mut ws, uri) = typing("fuzzyedit");
let found = items(after_typing(&mut ws, &uri, "clkenq"));
let item = find(&found, "clk_osc_en_q").expect("the fuzzy hit");
let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
// ` assign x = clkenq` — the word starts at column 13 and the cursor
// is at its end.
assert_eq!(edit.range.start, Position { line: 1, character: 13 });
assert_eq!(edit.range.end, Position { line: 1, character: 19 });
assert_eq!(edit.new_text, "clk_osc_en_q");
assert_eq!(item.filter_text, None, "the client filters on the label, as it should");
}
/// Below the floor, nothing is fuzzy. `ce` holds `clk_osc_en_q`'s letters
/// in order and must still not reach it.
#[test]
fn two_characters_match_by_prefix_and_nothing_else() {
let (_tree, mut ws, uri) = typing("fuzzyfloor");
for typed in ["c", "ce"] {
let found = items(after_typing(&mut ws, &uri, typed));
assert!(!found.is_empty(), "premise: {typed:?} answers something");
for item in &found {
assert!(
starts_with_ignore_case(&item.label, typed),
"{:?} is not a prefix match for {typed:?}",
item.label
);
}
}
// The discriminator, spelled out: `ce` would reach it if it were fuzzy
// (`c` at 0, `e` at 8), and `cen` — one character more — does.
let two = items(after_typing(&mut ws, &uri, "ce"));
assert!(!labels(&two).contains(&"clk_osc_en_q"), "{:?}", labels(&two));
assert!(labels(&two).contains(&"celsius"), "{:?}", labels(&two));
let three = items(after_typing(&mut ws, &uri, "cen"));
assert!(labels(&three).contains(&"clk_osc_en_q"), "{:?}", labels(&three));
}
/// The 1- and 2-character answers, pinned against what they were before
/// fuzzy matching existed. The keyword tier is checked as a set rather
/// than listed, so adding a reserved word to the lexer does not break a
/// test about completion.
#[test]
fn the_short_answers_are_what_they_always_were() {
let (_tree, mut ws, uri) = typing("fuzzygolden");
for (typed, expected) in [
// `c` itself is in the list because the buffer being typed in
// holds it as an `Ident` token — behaviour this round did not
// touch, pinned here because a golden that quietly lost it would
// be a change.
("c", vec!["c", "c_l_k_scatter", "celsius", "clk_osc_en_q"]),
("ce", vec!["ce", "celsius"]),
] {
let found = items(after_typing(&mut ws, &uri, typed));
let named: Vec<&str> = found
.iter()
.filter(|item| tier(item) != TIER_KEYWORD)
.map(|item| item.label.as_str())
.collect();
assert_eq!(named, expected, "the names {typed:?} answers with");
let keywords: Vec<&str> = found
.iter()
.filter(|item| tier(item) == TIER_KEYWORD)
.map(|item| item.label.as_str())
.collect();
let expected_keywords: Vec<&str> =
KEYWORDS.iter().copied().filter(|kw| starts_with_ignore_case(kw, typed)).collect();
assert_eq!(keywords, expected_keywords, "the keywords {typed:?} answers with");
}
}
/// **The `isIncomplete` trap.** VS Code asks again on the next keystroke
/// only when the last answer said it was incomplete, so a complete
/// two-character answer would swallow the third keystroke and fuzzy would
/// never fire at all.
#[test]
fn a_short_answer_is_always_incomplete_so_the_third_keystroke_arrives() {
let (_tree, mut ws, uri) = typing("fuzzyincomplete");
for typed in ["", "c", "ce"] {
let Some(CompletionResponse::List(list)) = after_typing(&mut ws, &uri, typed) else {
panic!("a completion list for {typed:?}");
};
assert!(list.is_incomplete, "{typed:?} must ask to be asked again");
}
// From the floor up the ordinary rule stands: complete when the whole
// hit set fit, which is sound because appending a character can only
// ever shrink it.
let Some(CompletionResponse::List(list)) = after_typing(&mut ws, &uri, "cen") else {
panic!("a completion list");
};
assert!(!list.is_incomplete, "nothing was truncated: {} items", list.items.len());
}
/// A prefix match is the best subsequence match there is, and the list
/// says so — asserted on the order of the array, which is what the cap
/// cuts and what a client that does not re-rank shows.
#[test]
fn a_prefix_hit_outranks_a_scattered_one() {
let (_tree, mut ws, uri) = typing("fuzzyrank");
let found = items(after_typing(&mut ws, &uri, "clk"));
let at = |label: &str| {
found
.iter()
.position(|item| item.label == label)
.unwrap_or_else(|| panic!("{label} in {:?}", labels(&found)))
};
assert!(
at("clk_osc_en_q") < at("c_l_k_scatter"),
"the prefix hit leads: {:?}",
labels(&found)
);
}
/// Scoring the boundaries is visible in the order, not only in the score:
/// a run that starts after an underscore beats the same letters buried
/// mid-word.
#[test]
fn a_run_that_starts_at_a_boundary_leads_one_that_does_not() {
let tree = Tree::new("fuzzyboundary");
tree.write(
"ast.sv",
"module ast;\n logic osc_ena_ready;\n logic xxenaxx_ready;\nendmodule\n",
);
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
let found = items(after_typing(&mut ws, &uri, "ena"));
let at = |label: &str| {
found
.iter()
.position(|item| item.label == label)
.unwrap_or_else(|| panic!("{label} in {:?}", labels(&found)))
};
assert!(
at("osc_ena_ready") < at("xxenaxx_ready"),
"the boundary run leads: {:?}",
labels(&found)
);
drop(tree);
}
/// Dedup survives the change: a name two tiers can reach is offered once,
/// by the better tier, whichever way it was matched.
#[test]
fn a_fuzzy_name_two_tiers_reach_is_still_offered_once() {
let tree = Tree::new("fuzzydedup");
// The same name, declared in this buffer (tier 1) and used in the
// project (tier 5), reachable from `clkenq` by neither prefix.
tree.write("ast.sv", "module ast;\n logic clk_osc_en_q;\nendmodule\n");
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
let text = "module top;\n logic clk_osc_en_q;\n assign x = clkenq\nendmodule\n";
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find("= clkenq").expect("needle") + 8) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let found = items(completions(&ws, &uri, position, true));
let hits: Vec<&CompletionItem> =
found.iter().filter(|item| item.label == "clk_osc_en_q").collect();
assert_eq!(hits.len(), 1, "{hits:#?}");
assert_eq!(tier(hits[0]), TIER_SCOPE, "the declaration beats the word");
assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE));
drop(tree);
}
/// The tiers that did **not** go fuzzy, pinned so the split is a decision
/// and not a drift: keywords, templates and macro names still match by
/// prefix, and the module tier still matches by substring.
#[test]
fn the_keyword_template_macro_and_module_tiers_did_not_go_fuzzy() {
let tree = Tree::new("fuzzyunchanged");
tree.write("defs.svh", "`define CLK_OSC_EN_Q 1\n");
tree.write("sub.sv", "module clk_osc_en_q ();\nendmodule\n");
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
// Mid-expression: the macro name is offered bare by tier 2 and must
// not be reachable by subsequence, and neither is a keyword.
let found = items(after_typing(&mut ws, &uri, "clkenq"));
assert!(!labels(&found).contains(&"CLK_OSC_EN_Q"), "{:?}", labels(&found));
let found = items(after_typing(&mut ws, &uri, "alws"));
assert!(labels(&found).is_empty() || !labels(&found).contains(&"always"));
// A backtick still answers by prefix only.
let text = "module top;\n assign x = `CLKENQ\nendmodule\n";
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find("`CLKENQ").expect("needle") + 7) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
assert!(completions(&ws, &uri, position, true).is_none(), "no macro is spelled that way");
// …and the module tier is still a substring match, which is wider
// than a prefix and narrower than a subsequence.
let text = "module top;\n osc_en\nendmodule\n";
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find("osc_en").expect("needle") + 6) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
let found = items(completions(&ws, &uri, position, true));
let modules: Vec<&str> = skeletons(&found).iter().map(|i| i.label.as_str()).collect();
assert_eq!(modules, ["clk_osc_en_q"], "a substring reaches it");
drop(tree);
}
/// The scope tier goes fuzzy too, with no mask table behind it — it is
/// the one tier computed per request.
#[test]
fn a_declaration_in_scope_is_reached_by_subsequence() {
let top = "module top;\n logic clk_osc_en_q;\n assign x = clkenq\nendmodule\n";
let (_tree, ws, uri, position) = asking("fuzzyscope", top, "= clkenq");
let found = items(completions(&ws, &uri, position, true));
let item = find(&found, "clk_osc_en_q").expect("the declaration");
assert_eq!(tier(item), TIER_SCOPE);
assert_eq!(item.detail.as_deref(), Some("logic clk_osc_en_q;"));
}
/// The index tier goes fuzzy too — a package member is reached the same
/// way a project word is.
#[test]
fn a_project_declaration_is_reached_by_subsequence() {
let tree = Tree::new("fuzzyindex");
tree.write("pkg.sv", "package clkosc_pkg;\n localparam CLK_OSC_EN_Q = 1;\nendpackage\n");
let path = tree.write("top.sv", "module top;\nendmodule\n");
let mut ws = Workspace::default();
ws.open_whole_workspace(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
let found = items(after_typing(&mut ws, &uri, "clkenq"));
let item = find(&found, "CLK_OSC_EN_Q").expect("the package member");
assert_eq!(tier(item), TIER_INDEX);
assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT));
drop(tree);
}
#[test]
fn another_open_buffer_overlays_disk_once_the_index_is_rebuilt() {
let tree = Tree::new("overlay");
let other = tree.write("other.sv", "module other;\n logic on_disk_name;\nendmodule\n");
let top = "module top;\n assign x = ov\nendmodule\n";
let (_tree, mut ws, uri, position) = opened(tree, top, "= ov");
let other_uri = path_to_uri(&other).expect("uri");
ws.set_document(other_uri, "module other;\n logic ov_in_buffer;\nendmodule\n".to_string());
ws.rebuild_index();
let items = items(completions(&ws, &uri, position, true));
assert!(labels(&items).contains(&"ov_in_buffer"), "{:?}", labels(&items));
}
// ------------------------------------------------------------------
// the member answer (2026-09-02) — after a `.` or a `::`
// ------------------------------------------------------------------
/// The buffer most of these ask against: a class chain, a struct, an
/// interface with a modport and a clocking block, and a handle for each.
const MEMBERS: &str = "\
interface bus_if;
logic clk;
logic [7:0] data;
modport mp (input clk);
clocking cb @(posedge clk);
input data;
endclocking
endinterface
typedef struct packed { logic [7:0] addr; logic vld; } hdr_t;
class base_c;
bit from_base;
endclass
class item_c extends base_c;
bit user_id;
bit feature1;
hdr_t hdr;
function void run();
endfunction
endclass
module top;
virtual bus_if vif;
item_c item;
item_c queue[4];
hdr_t [3:0] hs;
hdr_t h;
initial begin
item.
end
endmodule
";
/// The names a member request against [`MEMBERS`] offers, **sorted** —
/// which is the order the client shows them in, because `sortText` is
/// `<tier digit><name>`. The array order is the cap's order and is pinned
/// separately by [`the_list_is_ordered_nearest_declaration_first`].
fn member_labels(name: &str, spine: &str) -> Vec<String> {
let mut found: Vec<String> =
items(member_response(name, spine)).iter().map(|item| item.label.clone()).collect();
found.sort();
found
}
/// The whole response, for the tests that read more than the labels.
fn member_response(name: &str, spine: &str) -> Option<CompletionResponse> {
let top = MEMBERS.replace(" item.\n", &format!(" {spine}\n"));
let tree = Tree::new(name);
let (_tree, ws, uri, position) = opened(tree, &top, spine);
completions(&ws, &uri, position, true)
}
#[test]
fn a_class_handle_lists_its_members_and_its_bases() {
assert_eq!(
member_labels("cls", "item."),
vec!["feature1", "from_base", "hdr", "run", "user_id"],
);
}
#[test]
fn the_member_answer_is_exclusive() {
let items = items(member_response("exclusive", "item."));
// No keyword, no template, no project word — every item is a member,
// and every one of them is filed under the member tier.
for item in &items {
assert_eq!(tier(item), TIER_MEMBER, "{item:#?}");
assert_ne!(item.kind, Some(CompletionItemKind::KEYWORD), "{item:#?}");
assert_ne!(item.kind, Some(CompletionItemKind::TEXT), "{item:#?}");
assert_ne!(item.kind, Some(CompletionItemKind::SNIPPET), "{item:#?}");
}
let found = labels(&items);
assert!(!found.contains(&"always_ff"), "no keywords");
assert!(!found.contains(&"top"), "no index names");
assert!(!found.contains(&"vif"), "not even what is visible at the cursor");
}
/// A member wins over a same-named local because the answer is exclusive:
/// the local is not a worse candidate here, it is not a candidate.
#[test]
fn a_local_of_the_same_name_is_not_offered_beside_the_member() {
let top = MEMBERS.replace(" item.\n", " bit user_id;\n item.\n");
let tree = Tree::new("shadow");
let (_tree, ws, uri, position) = opened(tree, &top, "item.");
let items = items(completions(&ws, &uri, position, true));
let user_id = find(&items, "user_id").expect("the member");
assert_eq!(user_id.kind, Some(CompletionItemKind::VARIABLE));
assert_eq!(items.iter().filter(|item| item.label == "user_id").count(), 1);
}
#[test]
fn a_nested_struct_field_lists_the_inner_fields() {
assert_eq!(member_labels("struct", "h."), vec!["addr", "vld"]);
assert_eq!(member_labels("struct2", "item.hdr."), vec!["addr", "vld"]);
}
#[test]
fn an_interface_handle_lists_its_signals_its_modports_and_its_clocking() {
let found = member_labels("iface", "vif.");
for wanted in ["clk", "data", "mp", "cb"] {
assert!(found.contains(&wanted.to_string()), "{wanted} missing from {found:?}");
}
}
/// A clocking block's `type_name` is the interface enclosing it
/// (interface-semantics, 2026-09-01), which is what makes `vif.cb.data`
/// resolve to the interface's own `data` declaration — correct
/// SystemVerilog, since a clocking block names a *view* of those signals
/// and declares nothing of its own. So the list after `vif.cb.` is the
/// interface's, exactly as the resolution is: one walk, one answer, wider
/// than the block's own item list and never wrong about a name.
#[test]
fn a_clocking_block_lists_the_enclosing_interfaces_signals() {
assert_eq!(member_labels("clocking", "vif.cb."), member_labels("clocking2", "vif."));
assert!(member_labels("clocking3", "vif.cb.").contains(&"data".to_string()));
}
/// A **packed** array head is indexed away and names its element type's
/// members: `hdr_t [3:0] hs; hs[1].` is a `hdr_t`.
#[test]
fn a_packed_array_head_is_indexed_away() {
assert_eq!(member_labels("indexed", "hs[1]."), vec!["addr", "vld"]);
assert_eq!(member_labels("indexed2", "hs[i][j]."), vec!["addr", "vld"], "and repeatedly");
}
/// An **unpacked** declarator answers nothing, and that is
/// `vlog_semantic`'s own ruling rather than this file's: `item_c q[4]`
/// names a container, not a value of `item_c`, so no `type_name` is
/// recorded and `q.size()` is an array method rather than a member
/// (`bind.rs::declare_typed`). Completion may not mint a type the
/// resolver refuses to mint — that would be the second resolver this
/// round exists to avoid. Filed as a follow-on in the feature README.
#[test]
fn an_unpacked_array_head_answers_nothing_because_it_has_no_declared_type() {
assert!(member_response("unpacked", "queue[0].").is_none());
}
/// The order of the `items` array is the order the cap keeps, and it is
/// **nearest declaration first**: a class's own members before its base's,
/// in declaration order within each. `sortText` still says the client
/// should draw them alphabetically.
#[test]
fn the_list_is_ordered_nearest_declaration_first() {
let items = items(member_response("order", "item."));
assert_eq!(labels(&items), vec!["user_id", "feature1", "hdr", "run", "from_base"]);
for item in &items {
assert_eq!(item.sort_text.as_deref(), Some(format!("0{}", item.label).as_str()));
}
}
#[test]
fn this_and_super_answer_from_inside_a_method() {
let top =
MEMBERS.replace(" function void run();\n", " function void run();\n this.\n");
let tree = Tree::new("this");
let (_tree, ws, uri, position) = opened(tree, &top, " this.");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["feature1", "from_base", "hdr", "run", "user_id"]);
let top =
MEMBERS.replace(" function void run();\n", " function void run();\n super.\n");
let tree = Tree::new("super");
let (_tree, ws, uri, position) = opened(tree, &top, " super.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["from_base"], "super is the base and not the class itself");
}
#[test]
fn the_kind_and_the_detail_come_off_the_declaration() {
let items = items(member_response("detail", "item."));
// In this buffer the declaration's own line is free, so that is the
// card — the same one tier 1 has always shown.
let hdr = find(&items, "hdr").expect("the struct-typed property");
assert_eq!(hdr.kind, Some(CompletionItemKind::VARIABLE));
assert_eq!(hdr.detail.as_deref(), Some("hdr_t hdr;"), "the declaration itself");
let run = find(&items, "run").expect("the method");
assert_eq!(run.kind, Some(CompletionItemKind::FUNCTION));
assert_eq!(run.detail.as_deref(), Some("function void run();"));
// A method inserts its bare name: the parentheses and the arguments
// are the user's to write, and a completion that invented them would
// be guessing at the call.
assert_eq!(inserted(run), "run");
assert_eq!(run.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
}
/// The edit is an **empty** range at the cursor, so accepting an item
/// writes the member name after the dot and touches nothing before it.
#[test]
fn the_edit_is_empty_at_the_cursor_after_a_separator() {
let items = items(member_response("range", "item."));
assert!(!items.is_empty());
for item in &items {
let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
assert_eq!(edit.range.start, edit.range.end, "{item:#?}");
assert_eq!(edit.new_text, item.label);
}
}
/// And with characters typed after the dot it replaces exactly those.
#[test]
fn the_edit_replaces_exactly_what_was_typed_after_the_separator() {
let items = items(member_response("range2", "item.us"));
assert_eq!(labels(&items), vec!["user_id"]);
let CompletionTextEdit::Edit(edit) = items[0].text_edit.as_ref().expect("edit") else {
panic!("a plain edit");
};
assert_eq!(edit.range.start.character + 2, edit.range.end.character);
}
#[test]
fn a_typed_prefix_filters_below_the_fuzzy_floor_and_a_subsequence_from_it_up() {
// One and two characters: a prefix, exactly as every other tier does
// below the floor. `fe` reaches `feature1` and not `from_base`.
assert_eq!(member_labels("prefix1", "item.f"), vec!["feature1", "from_base"]);
assert_eq!(member_labels("prefix2", "item.fe"), vec!["feature1"]);
// Three: a subsequence, so `fbs` reaches `from_base` — which no
// prefix match ever would.
assert_eq!(member_labels("fuzzy", "item.fbs"), vec!["from_base"]);
assert_eq!(member_labels("fuzzy2", "item.usr"), vec!["user_id"]);
}
/// **The `isIncomplete` rule.** The request that matters — the one the
/// trigger character fires, with nothing typed yet — is complete, so VS
/// Code filters the whole member list client-side. A 1- or 2-character
/// answer is a prefix slice that the third keystroke would *widen*, so it
/// must say it is incomplete or the widening never reaches the client.
#[test]
fn only_a_filtered_answer_below_the_fuzzy_floor_is_incomplete() {
let incomplete = |name: &str, spine: &str| match member_response(name, spine) {
Some(CompletionResponse::List(list)) => list.is_incomplete,
other => panic!("a list, not {other:#?}"),
};
assert!(!incomplete("inc0", "item."), "the whole list is the whole answer");
assert!(incomplete("inc1", "item.f"), "a prefix slice widens at the third character");
assert!(incomplete("inc2", "item.fe"));
assert!(!incomplete("inc3", "item.fea"), "a subsequence hit set only shrinks");
// Even a query nothing matches answers with a list, so the client is
// told to come back rather than left filtering an answer it has not
// got.
assert!(incomplete("inc4", "item.zz"));
let empty = items(member_response("inc5", "item.zz"));
assert!(empty.is_empty());
}
/// An **empty** answer is incomplete whatever was typed — including at
/// zero characters, where a non-empty list would be complete. QA finding
/// 2 (2026-09-02) is the reason: a cold index whose scope ladder has not
/// reached the declaring file's directory yet answers empty for one
/// request and correctly for the next, and a *complete* emptiness would
/// be cached by the client until the user retyped the dot.
#[test]
fn an_empty_answer_always_asks_the_client_to_come_back() {
let top = "class hollow_c;\nendclass\nmodule top;\n hollow_c h;\n initial begin\n h.\n end\nendmodule\n";
let tree = Tree::new("hollow");
let (_tree, ws, uri, position) = opened(tree, top, " h.");
match completions(&ws, &uri, position, true) {
Some(CompletionResponse::List(list)) => {
assert!(list.items.is_empty(), "a class with no members");
assert!(list.is_incomplete, "and the client is asked to come back");
}
other => panic!("a list, not {other:#?}"),
}
// The same for a connection list whose module nothing declares.
let top = "module top;\n no_such_module u (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = asking("hollowconn", top, " .");
match completions(&ws, &uri, position, true) {
Some(CompletionResponse::List(list)) => {
assert!(list.items.is_empty());
assert!(list.is_incomplete);
}
other => panic!("a list, not {other:#?}"),
}
}
#[test]
fn an_unresolvable_head_answers_nothing_at_all() {
for (name, spine) in [
("nohead", "no_such_handle."),
("call", "f()."),
("nothing", "."),
("space", "item ."),
("untyped", "vif.clk."),
] {
assert!(
member_response(name, spine).is_none(),
"{spine} must answer nothing, not a guess",
);
}
}
/// A lone `:` is a case item, a label or a ternary — not a separator. The
/// request there is the ordinary six-tier one it always was.
#[test]
fn a_lone_colon_falls_through_to_the_ordinary_tiers() {
let top = "module top;\n logic sig;\n initial\n case (1)\n 1: si\n endcase\nendmodule\n";
let tree = Tree::new("colon");
let (_tree, ws, uri, position) = opened(tree, top, "1: si");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert!(found.contains(&"sig"), "the scope tier still answers: {found:?}");
}
#[test]
fn a_package_lists_its_members_after_a_scope_separator() {
let tree = Tree::new("pkg");
tree.write(
"p.sv",
"package other_pkg;\n localparam int WIDTH = 8;\n typedef struct packed { logic a; } cfg_t;\nendpackage\n",
);
let top = "module top;\n initial $display(other_pkg::);\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "other_pkg::");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert!(found.contains(&"WIDTH"), "{found:?}");
assert!(found.contains(&"cfg_t"), "{found:?}");
assert!(!found.contains(&"always_ff"), "and nothing else: {found:?}");
}
#[test]
fn a_package_this_file_declares_lists_its_members_too() {
let top = "package p;\n localparam int W = 8;\n typedef int t_t;\nendpackage\nmodule top;\n initial $display(p::);\nendmodule\n";
let tree = Tree::new("pkg_local");
let (_tree, ws, uri, position) = opened(tree, top, "p::");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["W", "t_t"]);
}
/// The cross-file half: an in-file class extending a class in another
/// file lists both halves, its own scope first.
#[test]
fn a_base_in_another_file_contributes_its_members() {
let tree = Tree::new("crossfile");
tree.write("base.sv", "class remote_c;\n bit remote_field;\n bit shared;\nendclass\n");
let top = "class local_c extends remote_c;\n bit local_field;\n bit shared;\nendclass\nmodule top;\n local_c h;\n initial begin\n h.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " h.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["local_field", "shared", "remote_field"]);
// The subclass's `shared` is the one offered — the same first-hit-wins
// rule a lookup applies.
let items = items(completions(&ws, &uri, position, true));
let shared = find(&items, "shared").expect("the shadowed name");
assert_eq!(items.iter().filter(|i| i.label == "shared").count(), 1);
assert_eq!(shared.kind, Some(CompletionItemKind::VARIABLE));
}
/// A class whose base the workspace does not declare at all: the chain
/// stops there, and everything known still lists.
#[test]
fn an_absent_base_stops_the_chain_without_losing_what_is_known() {
let tree = Tree::new("nobase");
let top = "class local_c extends nowhere_c;\n bit local_field;\nendclass\nmodule top;\n local_c h;\n initial begin\n h.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " h.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["local_field"]);
}
/// The other half of the detail rule: a member the *index* holds carries
/// no text, so its card is the kind label plus the declared type — the
/// most a table can say, and no file is read to say it.
#[test]
fn a_cross_file_member_shows_the_kind_label_and_its_declared_type() {
let tree = Tree::new("xdetail");
tree.write(
"remote.sv",
"class remote_c;\n hdr_t typed_field;\n bit plain_field;\nendclass\n",
);
let top = "module top;\n remote_c h;\n initial begin\n h.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " h.");
let items = items(completions(&ws, &uri, position, true));
let typed = find(&items, "typed_field").expect("the typed property");
assert_eq!(typed.detail.as_deref(), Some("variable — hdr_t"));
let plain = find(&items, "plain_field").expect("the untyped property");
assert_eq!(plain.detail.as_deref(), Some("variable"), "no type name to add");
}
/// A type only another file declares: the whole list comes from the
/// index, inherited members included.
#[test]
fn a_handle_whose_type_is_another_files_lists_from_the_index() {
let tree = Tree::new("remote");
tree.write("base.sv", "class remote_base;\n bit inherited_field;\nendclass\n");
tree.write(
"item.sv",
"class remote_item extends remote_base;\n bit own_field;\nendclass\n",
);
let top = "module top;\n remote_item h;\n initial begin\n h.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " h.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["inherited_field", "own_field"]);
}
/// `reg2hw.ctrl.` — the generated-register shape, whose inner fields the
/// index holds under the synthesized `reg2hw_t.ctrl` key.
#[test]
fn a_nested_struct_in_another_file_lists_through_the_synthesized_key() {
let tree = Tree::new("reg2hw");
tree.write(
"regs.sv",
"package regs_pkg;\n typedef struct packed {\n struct packed { logic q; logic qe; } ctrl;\n struct packed { logic q; } status;\n } reg2hw_t;\nendpackage\n",
);
let top = "module top;\n reg2hw_t reg2hw;\n initial begin\n reg2hw.ctrl.\n end\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "reg2hw.ctrl.");
let answer = items(completions(&ws, &uri, position, true));
let found = labels(&answer);
assert_eq!(found, vec!["q", "qe"]);
}
// ------------------------------------------------------------------
// the connection list (2026-09-02 rework) — `.` inside `sub u (…)`
// ------------------------------------------------------------------
/// A module in the buffer, so the in-file half is exercised without the
/// index. Three ports and two parameters, in a shape a user really types.
const WIRING: &str = "\
module wiring_sub #(
parameter int WIDTH = 8,
parameter int DEPTH = 4
) (
input logic clk,
input logic [WIDTH-1:0] data,
output logic ready
);
endmodule
module wiring_top;
logic clk;
wiring_sub u_sub (
HOLE
);
endmodule
";
/// A connection-list request against [`WIRING`], `HOLE` replaced by what
/// is typed. Sorted, like every other member list here.
fn wiring_labels(name: &str, hole: &str) -> Vec<String> {
let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n"));
let tree = Tree::new(name);
let (_tree, ws, uri, position) = opened(tree, &top, hole);
let mut found: Vec<String> = items(completions(&ws, &uri, position, true))
.iter()
.map(|item| item.label.clone())
.collect();
found.sort();
found
}
/// **The regression this rework exists for.** `.cl` inside `sub u (` used
/// to get the 512-item whole-index dump; it now gets the port.
#[test]
fn a_dot_in_a_connection_list_lists_the_modules_ports() {
assert_eq!(wiring_labels("conn", "."), vec!["clk", "data", "ready"]);
assert_eq!(wiring_labels("conn_typed", ".cl"), vec!["clk"]);
}
#[test]
fn a_connection_list_answers_after_a_comma_and_across_a_newline() {
assert_eq!(wiring_labels("comma", ".clk(clk), ."), vec!["data", "ready"]);
assert_eq!(
wiring_labels("newline", ".clk(clk),\n ."),
vec!["data", "ready"],
"an indented continuation line is the ordinary way this is written",
);
}
/// Already-connected ports are dropped: in a sixty-port instantiation the
/// ones still to wire are the whole of what the user is looking for.
#[test]
fn a_port_already_connected_is_not_offered_again() {
assert_eq!(
wiring_labels("taken", ".clk(clk), .data(d), ."),
vec!["ready"],
"two written, one left",
);
// …and the entry being *re-typed* is still offered, because the dot
// the cursor follows is the one that is skipped.
assert_eq!(wiring_labels("retype", ".clk(clk), .data(d), .re"), vec!["ready"]);
}
#[test]
fn a_parameter_override_lists_the_parameters_not_the_ports() {
let top = WIRING.replace("wiring_sub u_sub (", "wiring_sub #(.) u_sub (");
let tree = Tree::new("params");
let (_tree, ws, uri, position) = opened(tree, &top, "#(.");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["DEPTH", "WIDTH"]);
for item in &answer {
assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT), "{item:#?}");
}
}
/// **QA finding 1, 2026-09-02.** The opentitan shape: `prim_fifo_sync`
/// derives its width with a header `localparam`, which is **not
/// overridable** — and until `vlog_semantic` learned
/// [`SymbolKind::LocalParam`] it was bound as a `Param` and offered here.
/// The keyword is sticky, so a continuation entry after `localparam` is
/// one too, and a body `localparam` is never a header entry at all.
#[test]
fn a_localparam_is_never_offered_as_an_override() {
let top = "\
module fifo #(
parameter int Depth = 4,
localparam int DepthW = 3,
DepthX = 4,
parameter int Again = 1
) (
input logic clk
);
localparam int Body = 7;
endmodule
module top;
fifo #(.) u_fifo ();
endmodule
";
let tree = Tree::new("localparam");
let (_tree, ws, uri, position) = opened(tree, top, "#(.");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(
found,
vec!["Again", "Depth"],
"only the two `parameter` entries may be overridden",
);
for item in &answer {
assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT), "{item:#?}");
}
}
/// The same, for a module the **index** answers for — the half QA
/// actually hit, since `prim_fifo_sync` is instantiated from another file.
#[test]
fn a_localparam_in_another_file_is_not_offered_either() {
let tree = Tree::new("xlocalparam");
tree.write(
"fifo.sv",
"module fifo #(\n parameter int Depth = 4,\n localparam int DepthW = 3\n) (\n input logic clk\n);\nendmodule\n",
);
let top = "module top;\n fifo #(.) u_fifo ();\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "#(.");
let answer = items(completions(&ws, &uri, position, true));
assert_eq!(labels(&answer), vec!["Depth"]);
// …and the localparam is still *there* to be read hierarchically —
// the split changes what may be offered, never what exists.
assert!(
ws.index().members_of_chain("fifo").iter().any(|(name, _)| *name == "DepthW"),
"a localparam is still exported",
);
}
/// The completion list and the **ghost instantiation** must agree about
/// what is overridable: two answers to "which parameters may be
/// overridden" would eventually offer a name the skeleton omits.
/// `vlog_refactor::instantiation_plan` reads the AST keyword and always
/// did; this pins the two against each other.
#[test]
fn the_override_list_and_the_instantiation_plan_agree() {
let fifo = "module fifo #(\n parameter int Depth = 4,\n localparam int DepthW = 3,\n parameter int Again = 1\n) (\n input logic clk\n);\nendmodule\n";
let tree = Tree::new("planagree");
tree.write("fifo.sv", fifo);
let top = "module top;\n fifo #(.) u_fifo ();\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, "#(.");
let mut offered = labels(&items(completions(&ws, &uri, position, true)))
.iter()
.map(|s| (*s).to_string())
.collect::<Vec<String>>();
offered.sort();
let plan = vlog_refactor::instantiation_plan("fifo", fifo, None).expect("a plan");
let mut planned: Vec<String> = plan.params.iter().map(|p| p.name.clone()).collect();
planned.sort();
assert_eq!(offered, planned, "the popup and the skeleton name one set");
}
#[test]
fn a_port_item_inserts_the_bare_name_and_shows_its_declaration() {
let top = WIRING.replace(" HOLE\n", " .\n");
let tree = Tree::new("portitem");
let (_tree, ws, uri, position) = opened(tree, &top, " .");
let answer = items(completions(&ws, &uri, position, true));
let data = find(&answer, "data").expect("the port");
assert_eq!(data.kind, Some(CompletionItemKind::FIELD));
// The user types the `(` themselves; inventing it would be guessing
// at what is connected.
assert_eq!(inserted(data), "data");
assert_eq!(data.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
// The declaration line carries the direction and the width, which is
// the whole of what a connection list needs to know.
assert_eq!(data.detail.as_deref(), Some("input logic [WIDTH-1:0] data,"));
// Exclusive, like every other member answer.
for item in &answer {
assert_eq!(tier(item), TIER_MEMBER, "{item:#?}");
}
}
/// A **non-ANSI** port list writes its directions in the module body, so
/// the header alone names the ports and the body types them. Both halves
/// bind a `Port`, so the list is the same.
#[test]
fn a_non_ansi_port_list_is_completed_too() {
let top = "module non_ansi (a, b);\n input wire a;\n output wire b;\nendmodule\nmodule top;\n non_ansi u (\n .\n );\nendmodule\n";
let tree = Tree::new("nonansi");
let (_tree, ws, uri, position) = opened(tree, top, " .");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["a", "b"]);
}
/// A module declared in another file: the ports come out of the index's
/// member table, which exports exactly ports and parameters.
#[test]
fn a_module_in_another_file_lists_its_ports_from_the_index() {
let top = "module top;\n sub u_sub (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = asking("xconn", top, " .");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["clk", "data", "ready"], "SUB's ports, not its parameter");
let clk = find(&answer, "clk").expect("a port");
assert_eq!(clk.kind, Some(CompletionItemKind::FIELD));
assert_eq!(clk.detail.as_deref(), Some("port"), "table-only across files");
}
#[test]
fn an_interface_instance_lists_its_ports_too() {
let tree = Tree::new("ifaceconn");
tree.write("bus.sv", "interface bus_if (input logic clk, input logic rst_n);\n logic [7:0] internal;\nendinterface\n");
let top = "module top;\n bus_if u_bus (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = opened(tree, top, " .");
let answer = items(completions(&ws, &uri, position, true));
let mut found = labels(&answer);
found.sort();
assert_eq!(found, vec!["clk", "rst_n"], "an interface's ports, not its signals");
}
/// A module nothing declares has no ports to name. The answer is an
/// **empty list** — the same shape a resolved site with no matching
/// member gets, and for the same reason: the question was this one, and
/// the honest answer to it is nothing. Never the whole-index dump.
#[test]
fn a_module_the_workspace_does_not_declare_answers_nothing() {
let top = "module top;\n no_such_module u (\n .\n );\nendmodule\n";
let (_tree, ws, uri, position) = asking("unknownconn", top, " .");
assert!(items(completions(&ws, &uri, position, true)).is_empty());
}
/// …and a `.` that is in no instantiation list at all answers `None`,
/// which is the other half of the same split: not "nothing to offer here"
/// but "this was not a question I can read".
#[test]
fn a_dot_outside_any_instantiation_list_answers_none() {
let top = "module top;\n initial begin\n (.\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("looseconn", top, " (.");
assert!(completions(&ws, &uri, position, true).is_none());
}
/// A `.` inside a *connected expression* is not a connection: `.clk(`
/// opens a paren of its own, and what may be written there is an
/// expression.
#[test]
fn a_dot_inside_a_connected_expression_is_not_a_connection() {
let top = WIRING.replace(" HOLE\n", " .clk(no_such_head.\n");
let tree = Tree::new("nested");
let (_tree, ws, uri, position) = opened(tree, &top, "no_such_head.");
assert!(completions(&ws, &uri, position, true).is_none());
}
#[test]
fn a_typed_prefix_in_a_connection_list_follows_the_same_filter_rule() {
// One and two characters: a prefix.
assert_eq!(wiring_labels("cprefix", ".d"), vec!["data"]);
// Three: a subsequence, so `rdy` reaches `ready`.
assert_eq!(wiring_labels("cfuzzy", ".rdy"), vec!["ready"]);
let incomplete = |name: &str, hole: &str| {
let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n"));
let tree = Tree::new(name);
let (_tree, ws, uri, position) = opened(tree, &top, hole);
match completions(&ws, &uri, position, true) {
Some(CompletionResponse::List(list)) => list.is_incomplete,
other => panic!("a list, not {other:#?}"),
}
};
assert!(!incomplete("cinc0", "."), "the whole port list is the whole answer");
assert!(incomplete("cinc1", ".d"), "a prefix slice widens at the third character");
assert!(!incomplete("cinc3", ".rdy"));
}
/// Nothing about an ordinary identifier request changed.
#[test]
fn a_plain_identifier_still_gets_every_tier() {
let top = "module top;\n logic sig_here;\n assign x = sig\nendmodule\n";
let (_tree, ws, uri, position) = asking("plain", top, "= sig");
let items = items(completions(&ws, &uri, position, true));
let found = labels(&items);
assert!(found.contains(&"sig_here"), "the scope tier: {found:?}");
assert!(items.iter().any(|i| tier(i) == TIER_WORD || tier(i) == TIER_KEYWORD));
}
}