Prefix matching below three typed characters, subsequence from three up — the owner's ruling, which is VS Code's own rule. The scope, index-name and word tiers match by case-insensitive subsequence at 3+, ranked prefix-first then by a three-pass greedy-tighten scorer (boundary and contiguity bonuses, gap penalties); module, keyword, template and macro tiers unchanged, and the instantiation ghost's exact-match probe deliberately stays exact. The scan is affordable because every word and unit name carries a 32-bit character mask beside it, written in exactly two places so table and mask cannot desync: a clkenq keystroke rejects 99.6% of opentitan's 100k-word table with one AND each (+0.05 ms); the pathological class is three very common letters (aes +0.8 ms, QA's ena ~3-4 ms answered-in), accepted at lead review as imperceptible in a popup. Responses below the floor are always isIncomplete — a complete two-character answer would be client-filtered and the third keystroke, the one that turns fuzzy on, would never reach the server. QA verified clkenq -> clk_osc_en_q live in a real opentitan buffer (gfr_clk_mux2.sv) and the 2-to-3 transition over the wire; ten adversarial matcher attacks all passed. docs/features/fuzzy-completion/README.md; TODO.md section 13. Co-Authored-By: Claude Fable 5 <[email protected]>
2828 lines
127 KiB
Rust
2828 lines
127 KiB
Rust
//! `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::{Semantics, Symbol, SymbolKind, WorkspaceIndex};
|
||
|
||
use crate::candidates::{rank_cmp, starts_with_ignore_case, Candidate, Query, Score};
|
||
use crate::pairs;
|
||
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';
|
||
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();
|
||
}
|
||
|
||
// 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()
|
||
}
|
||
|
||
/// 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 {
|
||
let label = kind_label(SymbolKind::Module);
|
||
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 == SymbolKind::Module)
|
||
.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 == SymbolKind::Module)
|
||
.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(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::Port | SymbolKind::StructMember => CompletionItemKind::FIELD,
|
||
SymbolKind::Net | SymbolKind::Var | SymbolKind::Genvar | SymbolKind::Instance => {
|
||
CompletionItemKind::VARIABLE
|
||
}
|
||
SymbolKind::Param | SymbolKind::TfArg => CompletionItemKind::CONSTANT,
|
||
SymbolKind::Typedef => CompletionItemKind::TYPE_PARAMETER,
|
||
SymbolKind::EnumVariant => CompletionItemKind::ENUM_MEMBER,
|
||
SymbolKind::Function | SymbolKind::Task => CompletionItemKind::FUNCTION,
|
||
SymbolKind::Class => 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,
|
||
}
|
||
|
||
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());
|
||
Some(Word {
|
||
text: text.get(start..)?.to_string(),
|
||
start: start as u32,
|
||
backtick,
|
||
at_line_start,
|
||
statement_head,
|
||
})
|
||
}
|
||
|
||
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
|
||
";
|
||
|
||
/// [`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 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:?}");
|
||
}
|
||
|
||
// ------------------------------------------------------------------
|
||
// 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));
|
||
}
|
||
}
|