A hover, definition, type definition, highlight, prepare-rename or signature help on a name the file itself declares, and the outline, folding and selection ranges, are answered from the open buffer ahead of a scan, a rescan or a widen (server/ahead.rs, same_file.rs). The precondition is stated once, on Server::answer_from_the_buffer; ahead::REACH lists the notifications proved unable to change a buffer and everything else blocks. Completion offers what the file can reach (imported package members, inherited class members, included headers' macros) right after its own names (completion/related.rs), and its answers are half the size (completion/wire.rs). A new largeFile.threshold re-classifies buffers already open. The client's answer to a settings pull is now ordered like a notification (amends scan-ordering); colours answered while anything is held count as unsettled. TODO 71.2. Four dev rounds, four QA rounds; the last ran with Fable 5.2 as dev and QA after two QA failures. docs/features/fast-actions. Co-Authored-By: Claude Mythos 5.2 <[email protected]>
920 lines
41 KiB
Rust
920 lines
41 KiB
Rust
//! `textDocument/completion` — module hinting, templates, keywords, and every
|
|
//! name the project uses.
|
|
//!
|
|
//! One response, eight 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 this file declares** — every declaration in the buffer, in any
|
|
//! scope (`buffer.rs`, `completion-ux` 2026-11-17);
|
|
//! 3. **what this file uses** — every identifier its token stream holds;
|
|
//! 4. **what the project declares** — packages, their members, typedefs,
|
|
//! classes, modules and `` `define`` names, from the workspace index;
|
|
//! 5. **templates** — `if`/`case`/`always_ff`/declaration skeletons with
|
|
//! tabstops, offered only where the construct may be written;
|
|
//! 6. **keywords** — every reserved word `vlog_parser` knows;
|
|
//! 7. **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`](module::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`.
|
|
//!
|
|
//! The module is one directory: this file is the entry point, the response
|
|
//! under construction (`Items`) and the small helpers every tier shares; the
|
|
//! rest is one file per answer, in the order `completions` consults them:
|
|
//!
|
|
//! * `word` — what is typed: the identifier run at the cursor, the backtick
|
|
//! or the `.`/`::` before it, and the spine a separator follows;
|
|
//! * `site` — what may be written here: the module-item and statement gates
|
|
//! over the token stream's scope chain;
|
|
//! * `member` — the exclusive answer after a `.` or a `::`, the connection
|
|
//! list included;
|
|
//! * `module` — tier 0, and the instantiation planning `inline.rs` and
|
|
//! `instantiate.rs` share;
|
|
//! * `buffer` — tiers 2 and 3, the current file's declarations and words;
|
|
//! * `tiers` — the other ordinary tiers, in the order they fill the
|
|
//! response.
|
|
//!
|
|
//! Functions a sibling file calls are `pub(super)`; the four `pub(crate)`
|
|
//! entry points other modules of the crate use keep their paths through the
|
|
//! re-exports below. Each file's tests sit at its foot, on the harness in
|
|
//! `harness.rs`.
|
|
|
|
use std::collections::HashSet;
|
|
|
|
use lsp_types::{
|
|
CompletionItem, CompletionItemKind, CompletionItemLabelDetails, CompletionList,
|
|
CompletionResponse, CompletionTextEdit, Documentation, InsertTextFormat, InsertTextMode,
|
|
MarkupContent, MarkupKind, Position, Range, TextEdit, Uri,
|
|
};
|
|
use vlog_parser::token::{Comment, TokenKind};
|
|
use vlog_parser::TextRange;
|
|
use vlog_refactor::Layout;
|
|
use vlog_semantic::{Symbol, SymbolKind};
|
|
|
|
use crate::candidates::Query;
|
|
use crate::state::{Document, Workspace};
|
|
use crate::symbols::kind_label;
|
|
use crate::templates::Template;
|
|
use buffer::{buffer_word_tier, declared_tier};
|
|
use connection::Connection;
|
|
use member::member_answer;
|
|
use module::module_tier;
|
|
use related::{related_macros, related_tier};
|
|
use site::{at_module_item, at_statement, enclosing_scopes};
|
|
use tiers::{index_tier, keyword_tier, scope_tier, template_tier, word_tier};
|
|
use word::typed_word;
|
|
|
|
pub(crate) use module::{nearest_definition, plan_for};
|
|
// `perf.rs`, the one caller outside this module, is itself test-only; an
|
|
// unconditional re-export would be an unused import in every other build.
|
|
#[cfg(test)]
|
|
pub(crate) use module::module_header;
|
|
pub(crate) use site::at_instantiation_site;
|
|
pub(crate) use tiers::layout_at;
|
|
pub(crate) use wire::{item_defaults_support, with_item_defaults};
|
|
|
|
mod buffer;
|
|
mod connection;
|
|
#[cfg(test)]
|
|
mod harness;
|
|
mod member;
|
|
mod module;
|
|
mod related;
|
|
mod site;
|
|
mod tiers;
|
|
mod wire;
|
|
mod word;
|
|
|
|
/// 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 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;
|
|
|
|
/// `sortText` prefixes. The client sorts on these, so they *are* the tier
|
|
/// order; the name follows so each tier is alphabetical within itself.
|
|
const TIER_MODULE: char = '0';
|
|
/// Members, after a `.` or a `::`.
|
|
///
|
|
/// The same digit as tier 0 and not a contradiction: the member answer is
|
|
/// **exclusive**, so no other tier's item is ever in the same response and
|
|
/// the digit orders members among themselves and nothing else. `'0'` because
|
|
/// these are not one tier of an answer but the whole of it. A sixth digit
|
|
/// would say there is a ranking against the other tiers to express, and there
|
|
/// is not.
|
|
const TIER_MEMBER: char = '0';
|
|
/// A connection list's already-connected ports: after every port still to
|
|
/// connect, inside the same exclusive answer (`completion-ux`).
|
|
const TIER_CONNECTED: char = '1';
|
|
const TIER_SCOPE: char = '1';
|
|
/// What this buffer declares anywhere, and then the words it uses — the
|
|
/// current file ahead of every other file and of the templates and keywords
|
|
/// (`completion-ux`, TODO §68.1).
|
|
const TIER_DECLARED: char = '2';
|
|
const TIER_BUFFER_WORD: char = '3';
|
|
/// What the file is related to — the packages it imports, the classes its
|
|
/// class extends, the headers it includes — below the file itself and above
|
|
/// the rest of the workspace (`related.rs`).
|
|
const TIER_RELATED: char = '4';
|
|
const TIER_INDEX: char = '5';
|
|
const TIER_TEMPLATE: char = '6';
|
|
const TIER_KEYWORD: char = '7';
|
|
const TIER_WORD: char = '8';
|
|
|
|
/// 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 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);
|
|
related_macros(&mut items, ws, doc, &word.text);
|
|
for entry in ws.candidates().macros(&word.text) {
|
|
items.simple(
|
|
&format!("`{}", entry.name),
|
|
CompletionItemKind::CONSTANT,
|
|
TIER_INDEX,
|
|
entry.detail.clone(),
|
|
);
|
|
}
|
|
return items.finish();
|
|
}
|
|
|
|
// A `.` or a `::` admits exactly one kind of name too — a member of what
|
|
// stands before it — so the answer is only those. See [`member_answer`].
|
|
if word.sep.is_some() {
|
|
return member_answer(ws, doc, &word, offset, snippets);
|
|
}
|
|
|
|
// 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());
|
|
declared_tier(&mut items, doc, &word, fuzzy.as_ref());
|
|
buffer_word_tier(&mut items, doc, &word, fuzzy.as_ref());
|
|
related_tier(&mut items, ws, 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, &word, fuzzy.as_ref());
|
|
// **The `isIncomplete` trap.** VS Code asks the server again on the next
|
|
// keystroke *only* when the last answer said it was incomplete; otherwise
|
|
// it filters the list it already holds. A complete two-character prefix
|
|
// answer would therefore be filtered client-side for the rest of the word,
|
|
// and the third keystroke — the one that turns fuzzy on — would never
|
|
// reach here at all. So every answer below the floor says it is
|
|
// incomplete, whatever the cap did.
|
|
//
|
|
// Above the floor the ordinary rule stands, and is sound because the hit
|
|
// set only ever *shrinks* as characters are appended: if a name holds
|
|
// `clke` in order it holds `clk` in order, so a complete answer at three
|
|
// characters really does contain every answer to four.
|
|
if fuzzy.is_none() {
|
|
items.incomplete = true;
|
|
}
|
|
items.finish()
|
|
}
|
|
|
|
/// The 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,
|
|
/// How many of `items` the related tier added — which [`LIMIT`] does not
|
|
/// count, so every other tier fills exactly as far as it would without
|
|
/// them (`related.rs`).
|
|
related: usize,
|
|
}
|
|
|
|
impl Items {
|
|
fn new(doc: &Document, replacing: TextRange) -> Items {
|
|
Items {
|
|
range: doc.positions().range(replacing),
|
|
items: Vec::new(),
|
|
seen: HashSet::new(),
|
|
incomplete: false,
|
|
related: 0,
|
|
}
|
|
}
|
|
|
|
/// 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() - self.related >= 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;
|
|
}
|
|
self.unlimited(name, kind, tier, detail);
|
|
}
|
|
|
|
/// [`Items::simple`] past the cap: the caller has its own.
|
|
fn unlimited(&mut self, name: &str, kind: CompletionItemKind, tier: char, detail: String) {
|
|
if !self.seen.insert(name.to_string()) {
|
|
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.items.push(item);
|
|
}
|
|
|
|
/// A port or parameter after a connection list's `.`: the bare name, or
|
|
/// the `name($1)` entry when the connection carries one, and a dimmed
|
|
/// `connected` beside the label when the list already connects it.
|
|
fn connection(
|
|
&mut self,
|
|
name: &str,
|
|
kind: CompletionItemKind,
|
|
detail: String,
|
|
connection: Connection,
|
|
) {
|
|
if self.full() || self.seen.contains(name) {
|
|
return;
|
|
}
|
|
let tier = if connection.connected { TIER_CONNECTED } else { TIER_MEMBER };
|
|
let format = match connection.snippet {
|
|
Some(_) => InsertTextFormat::SNIPPET,
|
|
None => InsertTextFormat::PLAIN_TEXT,
|
|
};
|
|
let item = CompletionItem {
|
|
label: name.to_string(),
|
|
kind: Some(kind),
|
|
detail: Some(detail),
|
|
label_details: connection.connected.then(|| CompletionItemLabelDetails {
|
|
detail: None,
|
|
description: Some("connected".to_string()),
|
|
}),
|
|
sort_text: Some(format!("{tier}{name}")),
|
|
insert_text_format: Some(format),
|
|
text_edit: Some(CompletionTextEdit::Edit(TextEdit {
|
|
range: self.range,
|
|
new_text: connection.snippet.unwrap_or_else(|| 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.
|
|
///
|
|
/// `rank` is the template's place in the registry, which is what orders the
|
|
/// templates among themselves: the label alone would put `always @(*)`
|
|
/// before the clocked blocks.
|
|
fn template(&mut self, template: &Template, rank: usize, 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}{rank:03}{}", template.label)),
|
|
insert_text_format: Some(match snippets {
|
|
true => InsertTextFormat::SNIPPET,
|
|
false => InsertTextFormat::PLAIN_TEXT,
|
|
}),
|
|
insert_text_mode: Some(KEEP_MY_INDENTATION),
|
|
text_edit: Some(CompletionTextEdit::Edit(TextEdit {
|
|
range: self.range,
|
|
new_text: template.render(layout, snippets),
|
|
})),
|
|
..Default::default()
|
|
};
|
|
self.push(item);
|
|
}
|
|
|
|
fn finish(self) -> Option<CompletionResponse> {
|
|
if self.items.is_empty() {
|
|
return None;
|
|
}
|
|
Some(self.into_list())
|
|
}
|
|
|
|
/// The response whether or not anything is in it.
|
|
///
|
|
/// [`Items::finish`]'s `None` means "this was not my question", which is
|
|
/// the right answer for a tiered response nobody filled. For the
|
|
/// **exclusive** member answer an empty list is the answer — the site
|
|
/// resolved and holds no matching member — and it has to be sent rather
|
|
/// than declined, because `None` carries no `isIncomplete` and so cannot
|
|
/// ask the client to come back with the third character.
|
|
fn into_list(self) -> CompletionResponse {
|
|
CompletionResponse::List(CompletionList {
|
|
is_incomplete: self.incomplete,
|
|
items: self.items,
|
|
})
|
|
}
|
|
}
|
|
|
|
/// The LSP icon a declaration gets in a completion list. The same choices
|
|
/// `symbols::lsp_kind` makes for the outline, in the other enum.
|
|
fn completion_kind(kind: SymbolKind) -> CompletionItemKind {
|
|
match kind {
|
|
SymbolKind::Module | SymbolKind::Package | SymbolKind::Block => CompletionItemKind::MODULE,
|
|
SymbolKind::Interface | SymbolKind::Modport => CompletionItemKind::INTERFACE,
|
|
SymbolKind::Clocking => CompletionItemKind::EVENT,
|
|
SymbolKind::Port | SymbolKind::StructMember => CompletionItemKind::FIELD,
|
|
SymbolKind::Net | SymbolKind::Var | SymbolKind::Genvar | SymbolKind::Instance => {
|
|
CompletionItemKind::VARIABLE
|
|
}
|
|
SymbolKind::Param | SymbolKind::LocalParam | SymbolKind::TfArg => {
|
|
CompletionItemKind::CONSTANT
|
|
}
|
|
SymbolKind::Typedef => CompletionItemKind::TYPE_PARAMETER,
|
|
SymbolKind::EnumVariant => CompletionItemKind::ENUM_MEMBER,
|
|
SymbolKind::Function | SymbolKind::Task => CompletionItemKind::FUNCTION,
|
|
SymbolKind::Class => CompletionItemKind::CLASS,
|
|
SymbolKind::Constraint | SymbolKind::Coverpoint | SymbolKind::Cross => {
|
|
CompletionItemKind::PROPERTY
|
|
}
|
|
SymbolKind::Covergroup => CompletionItemKind::CLASS,
|
|
// A property and a sequence are named declarations a concurrent
|
|
// assertion calls by name, so they take the icon a function does.
|
|
SymbolKind::Property | SymbolKind::Sequence => CompletionItemKind::FUNCTION,
|
|
}
|
|
}
|
|
|
|
/// 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(),
|
|
}
|
|
}
|
|
|
|
/// 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}}}")
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::candidates::starts_with_ignore_case;
|
|
use crate::completion::harness::*;
|
|
use crate::settings::ClientSettings;
|
|
use crate::uri::path_to_uri;
|
|
use std::path::PathBuf;
|
|
|
|
#[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}");
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// 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());
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// `define names and the backtick
|
|
// ------------------------------------------------------------------
|
|
|
|
#[test]
|
|
fn a_backtick_offers_macro_names_and_only_macro_names() {
|
|
let tree = Tree::new("macro");
|
|
tree.write("defs.svh", "`define WIDTH 8\n`define MAX(a, b) 0\n");
|
|
tree.write("other.sv", "module other;\n logic WIDGET;\nendmodule\n");
|
|
let top = "module top;\n assign x = `WI\nendmodule\n";
|
|
let (_tree, ws, uri, position) = opened(tree, top, "`WI");
|
|
let items = items(completions(&ws, &uri, position, true));
|
|
assert_eq!(labels(&items), ["`WIDTH"], "only a macro may follow a backtick");
|
|
assert_eq!(inserted(&items[0]), "`WIDTH");
|
|
let CompletionTextEdit::Edit(edit) = items[0].text_edit.as_ref().expect("edit") else {
|
|
panic!("a plain edit");
|
|
};
|
|
assert_eq!(
|
|
edit.range.start,
|
|
Position { line: 1, character: 13 },
|
|
"the typed backtick is replaced, not doubled"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_macro_name_without_a_backtick_is_offered_bare() {
|
|
// Where a macro name is written without one: `` `ifdef NAME ``.
|
|
let tree = Tree::new("macrobare");
|
|
tree.write("defs.svh", "`define WIDTH 8\n");
|
|
let top = "module top;\n assign x = WID\nendmodule\n";
|
|
let (_tree, ws, uri, position) = opened(tree, top, "= WID");
|
|
let items = items(completions(&ws, &uri, position, true));
|
|
let item = find(&items, "WIDTH").expect("the macro name");
|
|
assert_eq!(inserted(item), "WIDTH", "no backtick is invented");
|
|
assert_eq!(item.detail.as_deref(), Some("`define WIDTH"));
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// filtering, the cap, and the scope ladder
|
|
// ------------------------------------------------------------------
|
|
|
|
#[test]
|
|
fn the_prefix_filters_server_side() {
|
|
let tree = Tree::new("prefix");
|
|
tree.write("other.sv", "module other;\n logic aaa_one, bbb_two;\nendmodule\n");
|
|
let top = "module top;\n assign x = aaa\nendmodule\n";
|
|
let (_tree, ws, uri, position) = opened(tree, top, "= aaa");
|
|
let items = items(completions(&ws, &uri, position, true));
|
|
assert!(!items.is_empty());
|
|
for item in &items {
|
|
assert!(
|
|
starts_with_ignore_case(&item.label, "aaa"),
|
|
"{} does not start with the typed prefix",
|
|
item.label
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_full_response_is_truncated_and_says_it_is_incomplete() {
|
|
let mut top = String::from("module top;\n");
|
|
for i in 0..LIMIT + 40 {
|
|
top.push_str(&format!(" logic wsig{i:04};\n"));
|
|
}
|
|
top.push_str(" assign x = wsig\nendmodule\n");
|
|
let (_tree, ws, uri, position) = asking("cap", &top, "= wsig");
|
|
let Some(CompletionResponse::List(list)) = completions(&ws, &uri, position, true) else {
|
|
panic!("a completion list");
|
|
};
|
|
assert_eq!(list.items.len(), LIMIT);
|
|
assert!(list.is_incomplete, "a truncated list must say so");
|
|
}
|
|
|
|
#[test]
|
|
fn a_file_outside_the_filelist_contributes_no_words() {
|
|
// M1's ladder decides what "the project" is, and the word tier is
|
|
// built from exactly that list.
|
|
let tree = Tree::new("filelist");
|
|
tree.write("listed.sv", "module listed;\n logic word_listed;\nendmodule\n");
|
|
tree.write("unlisted.sv", "module unlisted;\n logic word_unlisted;\nendmodule\n");
|
|
tree.write("files.f", "listed.sv\n");
|
|
let top = "module top;\n assign x = word_\nendmodule\n";
|
|
let path = tree.write("top.sv", top);
|
|
|
|
let mut ws = Workspace::default();
|
|
ws.set_client_settings(ClientSettings {
|
|
filelist: Some("files.f".to_string()),
|
|
..Default::default()
|
|
});
|
|
ws.open_whole_workspace(vec![tree.path.clone()]);
|
|
let uri = path_to_uri(&path).expect("uri");
|
|
ws.set_document(uri.clone(), top.to_string());
|
|
ws.rebuild_index();
|
|
let offset = (top.find("= word_").expect("needle") + 7) as u32;
|
|
let position = ws.document(&uri).expect("open").positions().position(offset);
|
|
|
|
let items = items(completions(&ws, &uri, position, true));
|
|
let labels = labels(&items);
|
|
assert!(labels.contains(&"word_listed"), "{labels:?}");
|
|
assert!(!labels.contains(&"word_unlisted"), "outside the project: {labels:?}");
|
|
}
|
|
|
|
#[test]
|
|
fn an_unsaved_edit_contributes_its_own_words_at_once() {
|
|
// The buffer's own token stream is read per request, so a name typed
|
|
// a moment ago is a candidate before anything is saved.
|
|
let top = "module top;\n logic fresh_name;\n assign x = fre\nendmodule\n";
|
|
let (_tree, ws, uri, position) = asking("unsaved", top, "= fre");
|
|
// The file on disk is `top` too, so make the buffer differ from it.
|
|
let edited = "module top;\n logic fresher_name;\n assign x = fre\nendmodule\n";
|
|
let mut ws = ws;
|
|
ws.set_document(uri.clone(), edited.to_string());
|
|
let items = items(completions(&ws, &uri, position, true));
|
|
assert!(labels(&items).contains(&"fresher_name"), "{:?}", labels(&items));
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// the performance claim, measured
|
|
// ------------------------------------------------------------------
|
|
|
|
/// What a keystroke costs over the real corpus, and what the tables cost
|
|
/// to build. Skipped when `corpus/` is not checked out
|
|
/// (`tools/corpus_fetch.sh`), exactly like the other corpus tests.
|
|
///
|
|
/// The budgets are deliberately loose — a debug build on a loaded machine
|
|
/// is the worst case this ever runs in — and exist to catch an *order of
|
|
/// magnitude* regression, not to pin a number. The numbers themselves are
|
|
/// in `docs/features/completion-core/README.md`.
|
|
#[test]
|
|
fn a_keystroke_over_the_whole_corpus_stays_in_budget() {
|
|
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
|
if !corpus.is_dir() {
|
|
eprintln!("corpus/ not checked out — skipping");
|
|
return;
|
|
}
|
|
let started = std::time::Instant::now();
|
|
let mut ws = Workspace::default();
|
|
ws.open_whole_workspace(vec![corpus.clone()]);
|
|
let build = started.elapsed();
|
|
|
|
// A buffer that is not on disk: it overlays the walk, so the corpus is
|
|
// never written to.
|
|
let top = "module lucisv_probe;\n logic clk;\n assign x = pr\nendmodule\n";
|
|
let uri = path_to_uri(&corpus.join("lucisv_probe.sv")).expect("uri");
|
|
ws.set_document(uri.clone(), top.to_string());
|
|
let offset = (top.find("= pr").expect("needle") + 4) as u32;
|
|
let position = ws.document(&uri).expect("open").positions().position(offset);
|
|
|
|
// Warm, then the measurement: ten requests, worst one reported. Twice
|
|
// — once for a typed prefix, once for the empty one, which is the
|
|
// worst case there is (every tier matches, and the cap does the work).
|
|
let empty = ws.document(&uri).expect("open").positions().position(offset - 2);
|
|
let mut worst = std::time::Duration::ZERO;
|
|
let mut worst_empty = std::time::Duration::ZERO;
|
|
for round in 0..11 {
|
|
let started = std::time::Instant::now();
|
|
let typed = items(completions(&ws, &uri, position, true));
|
|
let after_typed = started.elapsed();
|
|
let started = std::time::Instant::now();
|
|
let all = items(completions(&ws, &uri, empty, true));
|
|
let after_empty = started.elapsed();
|
|
assert!(!typed.is_empty());
|
|
assert_eq!(all.len(), LIMIT, "the empty prefix fills the response");
|
|
if round > 0 {
|
|
worst = worst.max(after_typed);
|
|
worst_empty = worst_empty.max(after_empty);
|
|
}
|
|
}
|
|
// …and the fuzzy path, which is a *scan* of the whole word table
|
|
// where the two above are a binary search into it. Six characters,
|
|
// the shape the round is named after.
|
|
let fuzzy = "module lucisv_probe;\n logic clk;\n assign x = clkenq\nendmodule\n";
|
|
ws.set_document(uri.clone(), fuzzy.to_string());
|
|
let offset = (fuzzy.find("= clkenq").expect("needle") + 8) as u32;
|
|
let position = ws.document(&uri).expect("open").positions().position(offset);
|
|
let mut worst_fuzzy = std::time::Duration::ZERO;
|
|
for round in 0..11 {
|
|
let started = std::time::Instant::now();
|
|
let found = items(completions(&ws, &uri, position, true));
|
|
let elapsed = started.elapsed();
|
|
assert!(!found.is_empty(), "the buffer's own `clk` matches at least");
|
|
if round > 0 {
|
|
worst_fuzzy = worst_fuzzy.max(elapsed);
|
|
}
|
|
}
|
|
|
|
eprintln!(
|
|
"corpus: {} files, {} words, {} index names; index+tables built in {build:?}; \
|
|
worst request {worst:?} typed / {worst_empty:?} empty / {worst_fuzzy:?} fuzzy",
|
|
ws.index().files().len(),
|
|
ws.candidates().words("").len(),
|
|
ws.candidates().units("").len(),
|
|
);
|
|
assert!(worst < std::time::Duration::from_millis(150), "a keystroke cost {worst:?}");
|
|
assert!(worst_empty < std::time::Duration::from_millis(150), "{worst_empty:?}");
|
|
assert!(worst_fuzzy < std::time::Duration::from_millis(150), "{worst_fuzzy:?}");
|
|
}
|
|
|
|
/// What a **member** request costs over the real corpus, against the
|
|
/// shapes the feature is named for: a generated register struct
|
|
/// (`uart_reg2hw_t`, eleven fields whose types are eleven more structs in
|
|
/// the same package), one of its inner registers reached by the
|
|
/// synthesized key, a package, and a connection list on a real wide
|
|
/// module.
|
|
///
|
|
/// The member answer is a table lookup like every other tier — one
|
|
/// `member_site` walk over one file's scopes, then one `BTreeMap` scan
|
|
/// per unit on the chain — so it should be *cheaper* than the tiered
|
|
/// answer, which scans three tables. Same loose budget, same reason: an
|
|
/// order of magnitude, not a number.
|
|
#[test]
|
|
fn a_member_request_over_the_whole_corpus_stays_in_budget() {
|
|
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
|
if !corpus.is_dir() {
|
|
eprintln!("corpus/ not checked out — skipping");
|
|
return;
|
|
}
|
|
let mut ws = Workspace::default();
|
|
ws.open_whole_workspace(vec![corpus.clone()]);
|
|
let uri = path_to_uri(&corpus.join("lucisv_member_probe.sv")).expect("uri");
|
|
|
|
let mut worst = Vec::new();
|
|
for (what, top, needle) in [
|
|
(
|
|
"reg2hw.",
|
|
"module lucisv_member_probe;\n uart_reg_pkg::uart_reg2hw_t reg2hw;\n initial begin\n reg2hw.\n end\nendmodule\n",
|
|
" reg2hw.",
|
|
),
|
|
(
|
|
"reg2hw.ctrl.",
|
|
"module lucisv_member_probe;\n uart_reg_pkg::uart_reg2hw_t reg2hw;\n initial begin\n reg2hw.ctrl.\n end\nendmodule\n",
|
|
" reg2hw.ctrl.",
|
|
),
|
|
(
|
|
"uart_reg_pkg::",
|
|
"module lucisv_member_probe;\n initial begin\n $display(uart_reg_pkg::);\n end\nendmodule\n",
|
|
"uart_reg_pkg::",
|
|
),
|
|
// The connection list, against a real wide module in another
|
|
// file — the position the 2026-09-02 rework exists for.
|
|
(
|
|
"uart_core (.",
|
|
"module lucisv_member_probe;\n uart_core u_core (\n .\n );\nendmodule\n",
|
|
" .",
|
|
),
|
|
] {
|
|
ws.set_document(uri.clone(), top.to_string());
|
|
let offset = (top.find(needle).expect("needle") + needle.len()) as u32;
|
|
let position = ws.document(&uri).expect("open").positions().position(offset);
|
|
let mut slowest = std::time::Duration::ZERO;
|
|
let mut count = 0;
|
|
for round in 0..11 {
|
|
let started = std::time::Instant::now();
|
|
let found = items(completions(&ws, &uri, position, true));
|
|
let elapsed = started.elapsed();
|
|
count = found.len();
|
|
if round > 0 {
|
|
slowest = slowest.max(elapsed);
|
|
}
|
|
}
|
|
assert!(count > 0, "{what} must list members over the corpus");
|
|
worst.push(format!("{what} {count} members in {slowest:?}"));
|
|
assert!(slowest < std::time::Duration::from_millis(150), "{what} cost {slowest:?}");
|
|
}
|
|
eprintln!("corpus member requests: {}", worst.join(" / "));
|
|
}
|
|
|
|
/// **QA's own reproduction, against the real file.** `prim_fifo_sync`
|
|
/// derives `localparam int DepthW = prim_util_pkg::vbits(Depth+1)` in its
|
|
/// header; six `parameter`s stand above it. A `#(.` list must offer the
|
|
/// six and not the seventh. Skipped when `corpus/` is not checked out,
|
|
/// like every other corpus test.
|
|
#[test]
|
|
fn the_opentitan_shape_that_found_the_localparam_bug() {
|
|
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
|
if !corpus.is_dir() {
|
|
eprintln!("corpus/ not checked out — skipping");
|
|
return;
|
|
}
|
|
let mut ws = Workspace::default();
|
|
ws.open_whole_workspace(vec![corpus.clone()]);
|
|
let top = "module lucisv_param_probe;\n prim_fifo_sync #(.) u_fifo ();\nendmodule\n";
|
|
let uri = path_to_uri(&corpus.join("lucisv_param_probe.sv")).expect("uri");
|
|
ws.set_document(uri.clone(), top.to_string());
|
|
let offset = (top.find("#(.").expect("needle") + 3) as u32;
|
|
let position = ws.document(&uri).expect("open").positions().position(offset);
|
|
|
|
let answer = items(completions(&ws, &uri, position, true));
|
|
let mut found = labels(&answer);
|
|
found.sort();
|
|
assert_eq!(
|
|
found,
|
|
vec!["Depth", "NeverClears", "OutputZeroIfEmpty", "Pass", "Secure", "Width"],
|
|
"the six overridable parameters, and not the derived `DepthW`",
|
|
);
|
|
// …and `DepthW` is still *there*: a hierarchical read of it is legal
|
|
// and still resolves, which is what the split deliberately preserved.
|
|
assert!(
|
|
ws.index().members_of_chain("prim_fifo_sync").iter().any(|(name, _)| *name == "DepthW"),
|
|
"the localparam is still exported",
|
|
);
|
|
}
|
|
}
|