TODO §68.1: begin+Enter writes the end, clock+reset templates, this file's names first, keyword ghosts, port items that write .name()
Server (lucisv_server only): on_type/auto_end.rs — the newline answer adds the owed end at the owning statement's indentation (lucisv.autoEnd); always_ff @( / always @( ghosts and popup templates lead with posedge clk or negedge rst_n; completion tiers put names declared and used in this buffer ahead of the index, templates and keywords (completion/buffer.rs); inline/keywords.rs ghosts the rest of a keyword and follows the popup's selected entry (lucisv.inlineKeywords); connection items keep connected ports as a second group marked 'connected' and insert name($1), pre-filled with a same-named signal (completion/connection.rs). Extension: typing.js sends the newline on-type request itself when editor.formatOnType is off and restores the cursor; the inline-completion context is converted to LSP shapes. Dev + QA (Opus 5.5) + one fix round; unit 1823, e2e 102, node 9 files, smoke OK. Not yet seen in a running VS Code. docs/features/completion-ux. Co-Authored-By: Claude Mythos 5.2 <[email protected]>
This commit is contained in:
1 parent
6844fbecb6
commit
c1076f9405
22 files changed
+2845
-187
No files matched your search
@@ -7193,3 +7193,57 @@ line.
|
||||
- Known limit: a layer with no `begin` (a one-statement `if`, a case item
|
||||
without `begin`) has no fold and so no pinned line; a `begin` written on
|
||||
its own line pins that `begin` line, not the `always` above it.
|
||||
|
||||
## 68. Completion that keeps up with typing (planned 2026-11-17, owner's order)
|
||||
|
||||
Five asks from the owner, about the VS Code extension. Two serial lanes
|
||||
(`lucisv_server` depends on `vlog_parser`, so they are not independent):
|
||||
68.1 first, then 68.2. Each lane: one dev, then one QA, both Opus 5.5.
|
||||
|
||||
### 68.1 Lane A — auto-`end`, templates, ranking, keyword ghosts, port items
|
||||
|
||||
Feature README: `docs/features/completion-ux/README.md`. Files:
|
||||
`crates/lucisv_server/src/{on_type.rs,inline.rs,templates.rs,pairs.rs,settings.rs,main.rs}`,
|
||||
`crates/lucisv_server/src/completion/*`, new modules beside them where a
|
||||
file is near 600 production lines, `crates/lucisv_server/tests/e2e.rs`,
|
||||
`editors/vscode/{extension.js,package.json,smoke.js,README.md}` and a new
|
||||
`editors/vscode/*_test.js` if the extension logic is factored out. No
|
||||
parser, formatter, linter or semantic crate change.
|
||||
|
||||
- [x] **`begin` + Enter writes the `end`** (owner: "more like begin +
|
||||
<return>, the cursor should be the next line of begin, at the correct
|
||||
indentation, and ready for the first statement"). The newline on-type
|
||||
answer, when the line above ends in `begin` (or `begin : label`) and
|
||||
the file has an unclosed `begin`, also inserts `end` on the line after
|
||||
the new one, at the indentation of the statement the `begin` belongs
|
||||
to; the cursor stays on the new, indented line. No `end` when the
|
||||
blocks already balance. Setting `lucisv.autoEnd` (default on). The
|
||||
extension sends the request itself when `editor.formatOnType` is off
|
||||
and puts the cursor back.
|
||||
- [x] **`always_ff @(` / `always @(` expand with clock and reset**:
|
||||
`posedge ${1:clk} or negedge ${2:rst_n}`, both tab stops, in the ghost
|
||||
and as the first popup template; the clock-only form stays available
|
||||
second.
|
||||
- [x] **Names from the current file rank first** in the popup: declared
|
||||
anywhere in this buffer, then words used in it, ahead of other files'
|
||||
names and of keywords.
|
||||
- [x] **Keyword ghosts**: a typed prefix of a keyword shows the rest of it
|
||||
as grey inline text (Tab accepts), following the popup's selected item
|
||||
when the popup is open. Setting `lucisv.inlineKeywords` (default on).
|
||||
- [x] **Port items**: unconnected ports first; already-connected ports
|
||||
listed after them, marked `connected` in the dimmed detail; accepting
|
||||
a port writes `.name($1)` with the cursor inside the parentheses.
|
||||
|
||||
### 68.2 Lane B — no rushed errors on the connection being typed
|
||||
|
||||
Feature README: `docs/features/port-entry-grace/README.md`. Files:
|
||||
`crates/vlog_parser/src/parser/instance.rs` (+ its tests),
|
||||
`crates/lucisv_server/src/{diagnostics.rs,server/diagnostics.rs,state/*}`.
|
||||
|
||||
- [ ] Parser recovery keeps an unfinished connection (`.`, `.name(` open to
|
||||
the end of its line, a missing `,` before the next `.name`) inside its
|
||||
own entry — still a diagnostic, never silent — so the rest of the file
|
||||
parses, colours and lints as if the entry were complete.
|
||||
- [ ] The server withholds the diagnostics that fall inside the entry the
|
||||
last edit touched, and releases them after a quiet period or when the
|
||||
next edit lands elsewhere.
|
||||
@@ -0,0 +1,144 @@
|
||||
//! Tiers 2 and 3: what the buffer being typed in declares, and the words it
|
||||
//! uses (TODO §68.1, `completion-ux`).
|
||||
//!
|
||||
//! The current file first: a name this buffer declares anywhere — in another
|
||||
//! module, a sibling block, a function three screens down — and then a word
|
||||
//! it merely uses, both ahead of what other files declare and ahead of the
|
||||
//! templates and keywords. Both are read from the buffer's own `Semantics`
|
||||
//! and token stream, recomputed on every change, so an unsaved declaration
|
||||
//! ranks as soon as it is typed. Tier 1 (the scope chain) still comes first:
|
||||
//! what is visible at the cursor is a better answer than what is merely in
|
||||
//! the file.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use lsp_types::CompletionItemKind;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_semantic::Symbol;
|
||||
|
||||
use super::word::Word;
|
||||
use super::{completion_kind, declaration_detail, Items, TIER_BUFFER_WORD, TIER_DECLARED};
|
||||
use crate::candidates::{rank_cmp, starts_with_ignore_case, Query};
|
||||
use crate::state::Document;
|
||||
|
||||
/// Tier 2: every declaration in the buffer, whatever scope holds it.
|
||||
pub(super) fn declared_tier(items: &mut Items, doc: &Document, word: &Word, fuzzy: Option<&Query>) {
|
||||
let symbols: Vec<&Symbol> = doc.semantics.symbols().iter().collect();
|
||||
for symbol in matching(symbols, |symbol| symbol.name.as_str(), word, fuzzy) {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(
|
||||
&symbol.name,
|
||||
completion_kind(symbol.kind),
|
||||
TIER_DECLARED,
|
||||
declaration_detail(doc, symbol),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Tier 3: every identifier the buffer's token stream holds, except the one
|
||||
/// being typed — offering the user their own half-word back is noise.
|
||||
pub(super) fn buffer_word_tier(
|
||||
items: &mut Items,
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
fuzzy: Option<&Query>,
|
||||
) {
|
||||
if items.full() {
|
||||
return;
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
let words: Vec<&str> =
|
||||
buffer_words(doc, word.start).filter(|name| seen.insert(*name)).collect();
|
||||
for name in matching(words, |name| name, word, fuzzy) {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(name, CompletionItemKind::TEXT, TIER_BUFFER_WORD, "used in this file".into());
|
||||
}
|
||||
}
|
||||
|
||||
/// The candidates `word` reaches, in the order they are offered: by prefix
|
||||
/// below the fuzzy floor (in the buffer's own order), ranked by subsequence
|
||||
/// score from it up — the house rule every tier applies.
|
||||
fn matching<'a, T: Copy + 'a>(
|
||||
candidates: Vec<T>,
|
||||
name: impl Fn(T) -> &'a str,
|
||||
word: &Word,
|
||||
fuzzy: Option<&Query>,
|
||||
) -> Vec<T> {
|
||||
match fuzzy {
|
||||
None => candidates
|
||||
.into_iter()
|
||||
.filter(|c| starts_with_ignore_case(name(*c), &word.text))
|
||||
.collect(),
|
||||
Some(query) => {
|
||||
let mut hits: Vec<(T, _)> =
|
||||
candidates.into_iter().filter_map(|c| Some((c, query.score(name(c))?))).collect();
|
||||
hits.sort_by(|a, b| rank_cmp((name(a.0), a.1), (name(b.0), b.1)));
|
||||
hits.into_iter().map(|(c, _)| c).collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every identifier the buffer holds, as the project-word tier counts one —
|
||||
/// `Ident` and `SystemIdent` only, neither a macro usage nor an escaped
|
||||
/// identifier — but not the token starting at `typing`, the word under the
|
||||
/// cursor.
|
||||
fn buffer_words(doc: &Document, typing: u32) -> impl Iterator<Item = &str> {
|
||||
doc.tokens
|
||||
.iter()
|
||||
.filter(move |token| token.span.start != typing)
|
||||
.filter(|token| matches!(token.kind, TokenKind::Ident | TokenKind::SystemIdent))
|
||||
.map(|token| token.text.as_str())
|
||||
.filter(|text| !text.starts_with('`') && !text.starts_with('\\'))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::completion::harness::*;
|
||||
use crate::completion::*;
|
||||
|
||||
const TOP: &str = "\
|
||||
module top;
|
||||
logic data_q;
|
||||
always_comb begin
|
||||
da
|
||||
end
|
||||
endmodule
|
||||
module other;
|
||||
logic data_other;
|
||||
assign data_word = 1;
|
||||
always_comb al_used = 0;
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn this_files_declarations_and_words_rank_after_the_scope_and_before_other_files() {
|
||||
let (_tree, ws, uri, position) = asking("bufferrank", TOP, " da");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let tier_of = |label: &str| tier(find(&items, label).unwrap_or_else(|| panic!("{label}")));
|
||||
assert_eq!(tier_of("data_q"), TIER_SCOPE, "visible at the cursor");
|
||||
assert_eq!(tier_of("data_other"), TIER_DECLARED, "declared in another module of this file");
|
||||
assert_eq!(tier_of("data_word"), TIER_BUFFER_WORD, "only used in this file");
|
||||
assert_eq!(tier_of("data"), TIER_INDEX, "a port only `sub.sv` declares");
|
||||
assert!(TIER_SCOPE < TIER_DECLARED && TIER_DECLARED < TIER_BUFFER_WORD);
|
||||
assert!(TIER_BUFFER_WORD < TIER_INDEX && TIER_INDEX < TIER_TEMPLATE);
|
||||
assert!(TIER_TEMPLATE < TIER_KEYWORD && TIER_KEYWORD < TIER_WORD);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_word_this_file_uses_sorts_ahead_of_the_keywords() {
|
||||
let top = TOP.replace(" da\n", " al\n");
|
||||
let (_tree, ws, uri, position) = asking("bufferkw", &top, " al");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let sort = |label: &str| {
|
||||
find(&items, label)
|
||||
.and_then(|i| i.sort_text.clone())
|
||||
.unwrap_or_else(|| panic!("{label}"))
|
||||
};
|
||||
assert!(sort("al_used") < sort("always"), "{items:#?}");
|
||||
assert!(sort("al_used") < sort("always_ff"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
//! What a connection-list entry inserts (TODO §68.1, `completion-ux`).
|
||||
//!
|
||||
//! After the `.` of `sub u_sub (.cl|` or `sub #(.WI|`, accepting a port or a
|
||||
//! parameter writes the whole entry — `.clk(|)` with the cursor inside the
|
||||
//! parentheses — rather than the bare name. When the instantiating scope can
|
||||
//! see a net, variable or port of the same name (a parameter, for the
|
||||
//! parameter list), it is pre-filled as the placeholder: `.clk(${1:clk})`,
|
||||
//! one Tab to keep it, one keystroke to replace it.
|
||||
//!
|
||||
//! The bare name stays the answer where the snippet would be wrong: a client
|
||||
//! that never said it reads snippets, a `(` already written after the word
|
||||
//! being replaced (re-editing `.clk(x)`'s name), and a name the snippet
|
||||
//! grammar would have to escape (an escaped identifier).
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use vlog_semantic::SymbolKind;
|
||||
|
||||
use super::snippet_hole;
|
||||
use super::tiers::visible_symbols;
|
||||
use super::word::Word;
|
||||
use crate::signature;
|
||||
use crate::state::Document;
|
||||
|
||||
/// A connection-list entry, beyond its name.
|
||||
pub(super) struct Connection {
|
||||
/// Whether the list already connects this port elsewhere — it sorts after
|
||||
/// the rest and is marked `connected`.
|
||||
pub(super) connected: bool,
|
||||
/// The snippet accepting it writes, or `None` for the bare name.
|
||||
pub(super) snippet: Option<String>,
|
||||
}
|
||||
|
||||
/// Everything about the cursor's entry that every candidate's insertion
|
||||
/// shares: whether to write the parentheses, and the names a placeholder may
|
||||
/// be pre-filled with.
|
||||
pub(super) struct EntrySite<'a> {
|
||||
wrap: bool,
|
||||
visible: HashSet<&'a str>,
|
||||
}
|
||||
|
||||
impl<'a> EntrySite<'a> {
|
||||
/// The entry being typed at `word`, in a list of `kind`.
|
||||
pub(super) fn new(
|
||||
doc: &'a Document,
|
||||
word: &Word,
|
||||
kind: signature::Kind,
|
||||
snippets: bool,
|
||||
) -> EntrySite<'a> {
|
||||
let wrap = snippets && !paren_follows(&doc.text, word.start);
|
||||
let admits = |symbol_kind: SymbolKind| match kind {
|
||||
signature::Kind::Ports => {
|
||||
matches!(symbol_kind, SymbolKind::Net | SymbolKind::Var | SymbolKind::Port)
|
||||
}
|
||||
signature::Kind::Params => {
|
||||
matches!(symbol_kind, SymbolKind::Param | SymbolKind::LocalParam)
|
||||
}
|
||||
};
|
||||
let visible = match wrap {
|
||||
true => visible_symbols(&doc.semantics, word.start)
|
||||
.into_iter()
|
||||
.filter(|symbol| admits(symbol.kind))
|
||||
.map(|symbol| symbol.name.as_str())
|
||||
.collect(),
|
||||
false => HashSet::new(),
|
||||
};
|
||||
EntrySite { wrap, visible }
|
||||
}
|
||||
|
||||
/// The entry for the port or parameter `name`.
|
||||
pub(super) fn connection(&self, name: &str, connected: bool) -> Connection {
|
||||
let plain = name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
|
||||
let snippet = (self.wrap && plain).then(|| {
|
||||
let fill = if self.visible.contains(name) { name } else { "" };
|
||||
format!("{name}({})", snippet_hole(1, fill))
|
||||
});
|
||||
Connection { connected, snippet }
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a `(` follows the identifier run that starts at `start`, past any
|
||||
/// spaces or tabs — the entry is already written and only its name is being
|
||||
/// re-edited.
|
||||
fn paren_follows(text: &str, start: u32) -> bool {
|
||||
let Some(rest) = text.get(start as usize..) else { return false };
|
||||
let rest = rest.trim_start_matches(|c: char| c.is_ascii_alphanumeric() || c == '_' || c == '$');
|
||||
rest.trim_start_matches([' ', '\t']).starts_with('(')
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_paren_after_the_word_means_the_entry_is_already_written() {
|
||||
assert!(paren_follows(".clk(x)", 1));
|
||||
assert!(paren_follows(".cl (x)", 1));
|
||||
assert!(!paren_follows(".cl", 1));
|
||||
assert!(!paren_follows(".cl\n (x)", 1), "only on the same line");
|
||||
assert!(!paren_follows(".cl, .b(x)", 1));
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ use lsp_types::CompletionResponse;
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_semantic::{MemberSite, Semantics, Surface, SymbolKind, WorkspaceIndex};
|
||||
|
||||
use super::connection::{self, Connection};
|
||||
use super::site::balanced;
|
||||
use super::tiers::innermost_scope;
|
||||
use super::word::{Sep, Word};
|
||||
@@ -54,6 +55,7 @@ pub(super) fn member_answer(
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
offset: u32,
|
||||
snippets: bool,
|
||||
) -> Option<CompletionResponse> {
|
||||
let members = match word.spine.as_ref() {
|
||||
Some(spine) => {
|
||||
@@ -69,7 +71,7 @@ pub(super) fn member_answer(
|
||||
// question, and it is the commonest completion position in RTL there
|
||||
// is: a `.` opening a connection or a parameter override.
|
||||
None => match word.sep? {
|
||||
Sep::Dot => connection_members(ws, doc, word)?,
|
||||
Sep::Dot => connection_members(ws, doc, word, snippets)?,
|
||||
Sep::Scope => return None,
|
||||
},
|
||||
};
|
||||
@@ -77,7 +79,7 @@ pub(super) fn member_answer(
|
||||
// Prefix below [`FUZZY_MIN`], subsequence from it up — the house rule, on
|
||||
// the same `Query` every other tier scores with.
|
||||
let fuzzy = (word.text.len() >= FUZZY_MIN).then(|| Query::new(&word.text));
|
||||
let matched: Vec<Member> = match &fuzzy {
|
||||
let mut matched: Vec<Member> = match &fuzzy {
|
||||
None => members
|
||||
.into_iter()
|
||||
.filter(|member| starts_with_ignore_case(&member.name, &word.text))
|
||||
@@ -95,12 +97,20 @@ pub(super) fn member_answer(
|
||||
}
|
||||
};
|
||||
|
||||
// A connection list's already-connected ports go after the rest, each
|
||||
// group in the order it was matched in (`completion-ux`, TODO §68.1).
|
||||
matched.sort_by_key(|member| member.connection.as_ref().is_some_and(|c| c.connected));
|
||||
|
||||
let mut items = Items::new(doc, word.range(offset));
|
||||
for member in matched {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(&member.name, completion_kind(member.kind), TIER_MEMBER, member.detail);
|
||||
let kind = completion_kind(member.kind);
|
||||
match member.connection {
|
||||
Some(connection) => items.connection(&member.name, kind, member.detail, connection),
|
||||
None => items.simple(&member.name, kind, TIER_MEMBER, member.detail),
|
||||
}
|
||||
}
|
||||
// **The `isIncomplete` trap, in its member form.** The request that
|
||||
// matters is the one the trigger character fires, with nothing typed
|
||||
@@ -132,6 +142,9 @@ struct Member {
|
||||
name: String,
|
||||
kind: SymbolKind,
|
||||
detail: String,
|
||||
/// What a connection list's entry carries beyond its name; `None` for
|
||||
/// every other member.
|
||||
connection: Option<Connection>,
|
||||
}
|
||||
|
||||
/// What a member declared **in another file** shows beside its name.
|
||||
@@ -225,10 +238,17 @@ fn members_at(
|
||||
/// list to what may legally be written; it never offers a name the
|
||||
/// resolution could not find.
|
||||
///
|
||||
/// Ports already connected earlier in the same list are dropped. `None` — no
|
||||
/// Ports already connected elsewhere in the same list stay on offer, marked
|
||||
/// (`completion-ux`, 2026-11-17 — they used to be dropped), and every entry
|
||||
/// carries the `.name($1)` snippet [`connection::entry`] spells. `None` — no
|
||||
/// popup — when the cursor is not in such a list at all, or is inside a
|
||||
/// connected *expression* (`.clk(` opens a paren of its own).
|
||||
fn connection_members(ws: &Workspace, doc: &Document, word: &Word) -> Option<Vec<Member>> {
|
||||
fn connection_members(
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
snippets: bool,
|
||||
) -> Option<Vec<Member>> {
|
||||
let dot = word.start.checked_sub(1)?;
|
||||
let list = signature::enclosing_list(&doc.tokens, word.start)?;
|
||||
let open = doc.tokens.get(list.open)?.span.end;
|
||||
@@ -250,27 +270,33 @@ fn connection_members(ws: &Workspace, doc: &Document, word: &Word) -> Option<Vec
|
||||
signature::Kind::Ports => SymbolKind::Port,
|
||||
};
|
||||
let taken = connected_names(&doc.tokens, list.open, dot);
|
||||
let entry = connection::EntrySite::new(doc, word, list.kind, snippets);
|
||||
let mut members = Members::new();
|
||||
let mut push = |name: &str, kind: SymbolKind, detail: String| {
|
||||
let connection = entry.connection(name, taken.contains(name));
|
||||
members.push_member(Member {
|
||||
name: name.to_string(),
|
||||
kind,
|
||||
detail,
|
||||
connection: Some(connection),
|
||||
});
|
||||
};
|
||||
match doc.semantics.instantiable_scope(&list.module) {
|
||||
// This file declares the module: its own scope is the whole answer,
|
||||
// and no other file's module of the same name may override it.
|
||||
Some(scope) => {
|
||||
let scope = doc.semantics.scope(scope)?;
|
||||
for symbol in scope.symbols.iter().filter_map(|&id| doc.semantics.symbol(id)) {
|
||||
if symbol.kind == wanted && !taken.contains(symbol.name.as_str()) {
|
||||
members.push(&symbol.name, symbol.kind, declaration_detail(doc, symbol));
|
||||
if symbol.kind == wanted {
|
||||
push(&symbol.name, symbol.kind, declaration_detail(doc, symbol));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
for (name, defs) in ws.index().members_of(&list.module) {
|
||||
let Some(def) = defs.first() else { continue };
|
||||
if def.kind == wanted && !taken.contains(name) {
|
||||
members.push(
|
||||
name,
|
||||
def.kind,
|
||||
indexed_detail(def.kind, def.type_name.as_deref()),
|
||||
);
|
||||
if def.kind == wanted {
|
||||
push(name, def.kind, indexed_detail(def.kind, def.type_name.as_deref()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -282,12 +308,11 @@ fn connection_members(ws: &Workspace, doc: &Document, word: &Word) -> Option<Vec
|
||||
/// token at `open`, except the one whose `.` sits at `skip` — the entry being
|
||||
/// typed, which must stay on offer.
|
||||
///
|
||||
/// Dropping them is the friendlier half of a choice the other way round would
|
||||
/// be simpler: in a sixty-port instantiation the fifty-five already connected
|
||||
/// are the ones the user is *not* looking for, and a popup that keeps offering
|
||||
/// them is a popup they scroll past. It cannot mislead — a name dropped here
|
||||
/// is one the buffer already spells two lines up — and a re-edited entry is
|
||||
/// still offered, because its own dot is the one `skip` names.
|
||||
/// In a sixty-port instantiation the fifty-five already connected are the ones
|
||||
/// the user is *not* looking for, so they sort after the rest and say so; they
|
||||
/// are not dropped (`completion-ux`, 2026-11-17), because a port connected
|
||||
/// twice by mistake is exactly the one a user goes looking for. A re-edited
|
||||
/// entry is not marked, because its own dot is the one `skip` names.
|
||||
fn connected_names(tokens: &[Token], open: usize, skip: u32) -> HashSet<&str> {
|
||||
let mut taken = HashSet::new();
|
||||
let mut depth = 0i32;
|
||||
@@ -328,8 +353,12 @@ impl Members {
|
||||
}
|
||||
|
||||
fn push(&mut self, name: &str, kind: SymbolKind, detail: String) {
|
||||
if self.seen.insert(name.to_string()) {
|
||||
self.out.push(Member { name: name.to_string(), kind, detail });
|
||||
self.push_member(Member { name: name.to_string(), kind, detail, connection: None });
|
||||
}
|
||||
|
||||
fn push_member(&mut self, member: Member) {
|
||||
if self.seen.insert(member.name.clone()) {
|
||||
self.out.push(member);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -823,28 +852,55 @@ endmodule
|
||||
assert_eq!(wiring_labels("conn_typed", ".cl"), vec!["clk"]);
|
||||
}
|
||||
|
||||
/// The answer against [`WIRING`] in the order the client shows it — by
|
||||
/// `sortText` — as `(label, marked connected)` pairs.
|
||||
fn wiring_order(name: &str, hole: &str) -> Vec<(String, bool)> {
|
||||
let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n"));
|
||||
let (_tree, ws, uri, position) = opened(Tree::new(name), &top, hole);
|
||||
let mut found = items(completions(&ws, &uri, position, true));
|
||||
found.sort_by(|a, b| a.sort_text.cmp(&b.sort_text));
|
||||
found
|
||||
.into_iter()
|
||||
.map(|item| {
|
||||
let marked = item
|
||||
.label_details
|
||||
.as_ref()
|
||||
.and_then(|d| d.description.as_deref())
|
||||
.is_some_and(|d| d == "connected");
|
||||
(item.label, marked)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn pairs(list: &[(&str, bool)]) -> Vec<(String, bool)> {
|
||||
list.iter().map(|(name, marked)| (name.to_string(), *marked)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_connection_list_answers_after_a_comma_and_across_a_newline() {
|
||||
assert_eq!(wiring_labels("comma", ".clk(clk), ."), vec!["data", "ready"]);
|
||||
let expected = pairs(&[("data", false), ("ready", false), ("clk", true)]);
|
||||
assert_eq!(wiring_order("comma", ".clk(clk), ."), expected);
|
||||
assert_eq!(
|
||||
wiring_labels("newline", ".clk(clk),\n ."),
|
||||
vec!["data", "ready"],
|
||||
wiring_order("newline", ".clk(clk),\n ."),
|
||||
expected,
|
||||
"an indented continuation line is the ordinary way this is written",
|
||||
);
|
||||
}
|
||||
|
||||
/// Already-connected ports are dropped: in a sixty-port instantiation the
|
||||
/// ones still to wire are the whole of what the user is looking for.
|
||||
/// Already-connected ports sort after the ones still to wire and say so
|
||||
/// (`completion-ux`, 2026-11-17 — they used to be dropped): in a
|
||||
/// sixty-port instantiation the ones still to wire are what the user is
|
||||
/// looking for, but a port connected twice by mistake is findable.
|
||||
#[test]
|
||||
fn a_port_already_connected_is_not_offered_again() {
|
||||
fn a_port_already_connected_is_offered_last_and_marked() {
|
||||
assert_eq!(
|
||||
wiring_labels("taken", ".clk(clk), .data(d), ."),
|
||||
vec!["ready"],
|
||||
"two written, one left",
|
||||
wiring_order("taken", ".clk(clk), .data(d), ."),
|
||||
pairs(&[("ready", false), ("clk", true), ("data", true)]),
|
||||
"two written, one left, and the two after it",
|
||||
);
|
||||
// …and the entry being *re-typed* is still offered, because the dot
|
||||
// the cursor follows is the one that is skipped.
|
||||
assert_eq!(wiring_labels("retype", ".clk(clk), .data(d), .re"), vec!["ready"]);
|
||||
// …and the entry being *re-typed* is not marked, because the dot the
|
||||
// cursor follows is the one that is skipped.
|
||||
assert_eq!(wiring_order("retype", ".clk(clk), .data(d), .re"), pairs(&[("ready", false)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -945,17 +1001,21 @@ endmodule
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_item_inserts_the_bare_name_and_shows_its_declaration() {
|
||||
fn a_port_item_writes_the_whole_entry_and_shows_its_declaration() {
|
||||
let top = WIRING.replace(" HOLE\n", " .\n");
|
||||
let tree = Tree::new("portitem");
|
||||
let (_tree, ws, uri, position) = opened(tree, &top, " .");
|
||||
let answer = items(completions(&ws, &uri, position, true));
|
||||
let data = find(&answer, "data").expect("the port");
|
||||
assert_eq!(data.kind, Some(CompletionItemKind::FIELD));
|
||||
// The user types the `(` themselves; inventing it would be guessing
|
||||
// at what is connected.
|
||||
assert_eq!(inserted(data), "data");
|
||||
assert_eq!(data.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
|
||||
// `.data(|)`: the parentheses come with it, the cursor inside
|
||||
// (`completion-ux`, 2026-11-17). Nothing named `data` is visible in
|
||||
// `wiring_top`, so the placeholder is empty…
|
||||
assert_eq!(inserted(data), "data(${1})");
|
||||
assert_eq!(data.insert_text_format, Some(InsertTextFormat::SNIPPET));
|
||||
// …while `clk` is, so it is pre-filled.
|
||||
let clk = find(&answer, "clk").expect("the clock");
|
||||
assert_eq!(inserted(clk), "clk(${1:clk})");
|
||||
// The declaration line carries the direction and the width, which is
|
||||
// the whole of what a connection list needs to know.
|
||||
assert_eq!(data.detail.as_deref(), Some("input logic [WIDTH-1:0] data,"));
|
||||
@@ -965,6 +1025,33 @@ endmodule
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_port_item_is_the_bare_name_where_a_snippet_would_be_wrong() {
|
||||
// A `(` already after the word: only the name is being re-edited.
|
||||
let top = WIRING.replace(" HOLE\n", " .da(d)\n");
|
||||
let (_tree, ws, uri, position) = opened(Tree::new("portparen"), &top, " .da");
|
||||
let answer = items(completions(&ws, &uri, position, true));
|
||||
assert_eq!(inserted(find(&answer, "data").expect("the port")), "data");
|
||||
// A client without snippet support gets the name, as before.
|
||||
let top = WIRING.replace(" HOLE\n", " .\n");
|
||||
let (_tree, ws, uri, position) = opened(Tree::new("portplain"), &top, " .");
|
||||
let answer = items(completions(&ws, &uri, position, false));
|
||||
let data = find(&answer, "data").expect("the port");
|
||||
assert_eq!(inserted(data), "data");
|
||||
assert_eq!(data.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_item_is_pre_filled_from_a_visible_parameter() {
|
||||
let top = WIRING
|
||||
.replace("module wiring_top;\n", "module wiring_top;\n localparam int WIDTH = 16;\n")
|
||||
.replace("wiring_sub u_sub (", "wiring_sub #(.) u_sub (");
|
||||
let (_tree, ws, uri, position) = opened(Tree::new("paramfill"), &top, "#(.");
|
||||
let answer = items(completions(&ws, &uri, position, true));
|
||||
assert_eq!(inserted(find(&answer, "WIDTH").expect("the parameter")), "WIDTH(${1:WIDTH})");
|
||||
assert_eq!(inserted(find(&answer, "DEPTH").expect("the other")), "DEPTH(${1})");
|
||||
}
|
||||
|
||||
/// A **non-ANSI** port list writes its directions in the module body, so
|
||||
/// the header alone names the ports and the body types them. Both halves
|
||||
/// bind a `Port`, so the list is the same.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! `textDocument/completion` — module hinting, templates, keywords, and every
|
||||
//! name the project uses.
|
||||
//!
|
||||
//! One response, six tiers, ordered by `sortText`:
|
||||
//! 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
|
||||
@@ -10,12 +10,15 @@
|
||||
//! 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,
|
||||
//! 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;
|
||||
//! 3. **templates** — `if`/`case`/`always_ff`/declaration skeletons with
|
||||
//! 5. **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
|
||||
//! 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
|
||||
@@ -47,8 +50,9 @@
|
||||
//! list included;
|
||||
//! * `module` — tier 0, and the instantiation planning `inline.rs` and
|
||||
//! `instantiate.rs` share;
|
||||
//! * `tiers` — tiers 1 to 5, the five ordinary tiers in the order they fill
|
||||
//! the response.
|
||||
//! * `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
|
||||
@@ -58,9 +62,9 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use lsp_types::{
|
||||
CompletionItem, CompletionItemKind, CompletionList, CompletionResponse, CompletionTextEdit,
|
||||
Documentation, InsertTextFormat, InsertTextMode, MarkupContent, MarkupKind, Position, Range,
|
||||
TextEdit, Uri,
|
||||
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;
|
||||
@@ -71,6 +75,8 @@ 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 site::{at_module_item, at_statement, enclosing_scopes};
|
||||
@@ -85,6 +91,8 @@ pub(crate) use module::module_header;
|
||||
pub(crate) use site::at_instantiation_site;
|
||||
pub(crate) use tiers::layout_at;
|
||||
|
||||
mod buffer;
|
||||
mod connection;
|
||||
#[cfg(test)]
|
||||
mod harness;
|
||||
mod member;
|
||||
@@ -134,11 +142,19 @@ const TIER_MODULE: char = '0';
|
||||
/// 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';
|
||||
const TIER_INDEX: char = '2';
|
||||
const TIER_TEMPLATE: char = '3';
|
||||
const TIER_KEYWORD: char = '4';
|
||||
const TIER_WORD: char = '5';
|
||||
/// 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';
|
||||
const TIER_INDEX: char = '4';
|
||||
const TIER_TEMPLATE: char = '5';
|
||||
const TIER_KEYWORD: char = '6';
|
||||
const TIER_WORD: char = '7';
|
||||
|
||||
/// What a multi-line item tells the client about its own whitespace.
|
||||
///
|
||||
@@ -203,7 +219,7 @@ pub fn completions(
|
||||
// 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);
|
||||
return member_answer(ws, doc, &word, offset, snippets);
|
||||
}
|
||||
|
||||
// Both position gates read the same scope chain, and neither can be true
|
||||
@@ -225,10 +241,12 @@ pub fn completions(
|
||||
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());
|
||||
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());
|
||||
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
|
||||
@@ -307,13 +325,54 @@ impl Items {
|
||||
self.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.
|
||||
fn template(&mut self, template: &Template, layout: &Layout, snippets: bool) {
|
||||
///
|
||||
/// `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;
|
||||
}
|
||||
@@ -329,7 +388,7 @@ impl Items {
|
||||
// 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)),
|
||||
sort_text: Some(format!("{TIER_TEMPLATE}{rank:03}{}", template.label)),
|
||||
insert_text_format: Some(match snippets {
|
||||
true => InsertTextFormat::SNIPPET,
|
||||
false => InsertTextFormat::PLAIN_TEXT,
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use lsp_types::CompletionItemKind;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::KEYWORDS;
|
||||
use vlog_refactor::Layout;
|
||||
use vlog_semantic::{Semantics, Symbol};
|
||||
@@ -66,7 +65,7 @@ pub(super) fn scope_tier(items: &mut Items, doc: &Document, word: &Word, fuzzy:
|
||||
/// 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> {
|
||||
pub(super) 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);
|
||||
@@ -158,7 +157,7 @@ pub(super) fn template_tier(
|
||||
}
|
||||
let layout = layout_at(ws, doc, word.start);
|
||||
let dialect = templates::dialect(doc.path.as_deref());
|
||||
for template in templates::for_dialect(dialect) {
|
||||
for (rank, template) in templates::for_dialect(dialect).enumerate() {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
@@ -168,7 +167,7 @@ pub(super) fn template_tier(
|
||||
if !starts_with_ignore_case(template.prefix, &word.text) {
|
||||
continue;
|
||||
}
|
||||
items.template(template, &layout, snippets);
|
||||
items.template(template, rank, &layout, snippets);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,45 +204,26 @@ pub(super) fn keyword_tier(items: &mut Items, word: &Word) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tier 5: identifiers used anywhere in the project scope.
|
||||
/// Tier 7: 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.
|
||||
pub(super) fn word_tier(
|
||||
items: &mut Items,
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
fuzzy: Option<&Query>,
|
||||
) {
|
||||
/// 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 by
|
||||
/// tier 3 (`buffer.rs`), so an unsaved edit still contributes immediately.
|
||||
pub(super) fn word_tier(items: &mut Items, ws: &Workspace, 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;
|
||||
}
|
||||
// The buffer's own words were offered by tier 3 already, so only the
|
||||
// prebuilt table is read here; a name in both is offered once anyway,
|
||||
// because `Items` drops a repeated label.
|
||||
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
|
||||
}
|
||||
None => ws.candidates().words(&word.text).iter().map(String::as_str).collect(),
|
||||
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);
|
||||
let 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()
|
||||
}
|
||||
};
|
||||
@@ -255,21 +235,6 @@ pub(super) fn word_tier(
|
||||
}
|
||||
}
|
||||
|
||||
/// 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('\\'))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -374,7 +339,7 @@ endmodule
|
||||
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"],
|
||||
["always_ff with reset", "always_ff @(posedge clk)", "always_comb begin/end"],
|
||||
"and `alw` finds every one of them"
|
||||
);
|
||||
|
||||
@@ -419,7 +384,7 @@ endmodule
|
||||
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 @(*)"],
|
||||
["always @(posedge clk or negedge rst_n)", "always @(posedge clk)", "always @(*)"],
|
||||
"and no always_ff, which a .v file's compiler would reject"
|
||||
);
|
||||
}
|
||||
@@ -637,7 +602,8 @@ endmodule
|
||||
#[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.
|
||||
// arrive as one of this file's declarations (tier 2, `completion-ux`)
|
||||
// — never as a visible declaration.
|
||||
let top = "\
|
||||
module top;
|
||||
initial begin : b
|
||||
@@ -650,8 +616,8 @@ 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:#?}");
|
||||
let item = find(&items, "inner_only").expect("known as a declaration at least");
|
||||
assert_eq!(tier(item), TIER_DECLARED, "{item:#?}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -750,12 +716,13 @@ endmodule
|
||||
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"]),
|
||||
// `c` itself used to be in the list, because the buffer being
|
||||
// typed in holds it as an `Ident` token. `completion-ux`
|
||||
// (2026-11-17) dropped it on purpose: the buffer-word tier skips
|
||||
// the token under the cursor, and offering the user their own
|
||||
// half-word back is noise.
|
||||
("c", vec!["c_l_k_scatter", "celsius", "clk_osc_en_q"]),
|
||||
("ce", vec!["celsius"]),
|
||||
] {
|
||||
let found = items(after_typing(&mut ws, &uri, typed));
|
||||
let named: Vec<&str> = found
|
||||
|
||||
@@ -27,16 +27,19 @@
|
||||
//! because the editor prepends that line's own indentation when it inserts the
|
||||
//! snippet; see `render`. See `docs/features/inline-templates/README.md`.
|
||||
|
||||
use lsp_types::{Position, Range, Uri};
|
||||
use lsp_types::{Position, Range, SelectedCompletionInfo, Uri};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_refactor::{Layout, Site};
|
||||
|
||||
use crate::completion;
|
||||
use crate::on_type;
|
||||
use crate::pairs;
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::templates::{self, Dialect};
|
||||
|
||||
mod keywords;
|
||||
|
||||
/// One line of a body: how many indent steps it sits in, and its text. The
|
||||
/// same shape `templates.rs` writes its skeletons in.
|
||||
type Line = (u8, &'static str);
|
||||
@@ -96,6 +99,13 @@ const BEGIN_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "end")];
|
||||
const FORK_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "join")];
|
||||
const GENERATE_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "endgenerate")];
|
||||
|
||||
/// The event control of a flop with an async active-low reset, both edges a
|
||||
/// tabstop. First in both `always` families (TODO §68.1): the commoner flop.
|
||||
const CLOCK_AND_RESET: &[Line] =
|
||||
&[(0, "posedge ${1:clk} or negedge ${2:rst_n}) begin"), (1, "$0"), (0, "end")];
|
||||
/// The clock-only event control, one cycle away.
|
||||
const CLOCK_ONLY: &[Line] = &[(0, "posedge ${1:clk}) begin"), (1, "$0"), (0, "end")];
|
||||
|
||||
/// Every construct that offers ghost text.
|
||||
///
|
||||
/// The order is the order `triggered` tries them, which only matters when two
|
||||
@@ -156,19 +166,16 @@ const TRIGGERS: &[Trigger] = &[
|
||||
opener: EVENT,
|
||||
dialect: Some(Dialect::SystemVerilog),
|
||||
gate: Unclosed::Paren,
|
||||
bodies: &[&[(0, "posedge ${1:clk}) begin"), (1, "$0"), (0, "end")]],
|
||||
bodies: &[CLOCK_AND_RESET, CLOCK_ONLY],
|
||||
},
|
||||
Trigger {
|
||||
keyword: "always",
|
||||
opener: EVENT,
|
||||
dialect: None,
|
||||
gate: Unclosed::Paren,
|
||||
// Two items, clocked first: `always @(` is overwhelmingly a flop, and
|
||||
// the client cycles to the second with one keystroke.
|
||||
bodies: &[
|
||||
&[(0, "posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
|
||||
&[(0, "*) begin"), (1, "$0"), (0, "end")],
|
||||
],
|
||||
// Three items, clocked first: `always @(` is overwhelmingly a flop,
|
||||
// and the client cycles to the next with one keystroke.
|
||||
bodies: &[CLOCK_AND_RESET, CLOCK_ONLY, &[(0, "*) begin"), (1, "$0"), (0, "end")]],
|
||||
},
|
||||
Trigger {
|
||||
keyword: "begin",
|
||||
@@ -237,7 +244,15 @@ pub struct InlineItems {
|
||||
/// `None` rather than an empty list wherever there is nothing to say: an
|
||||
/// editor treats both the same, and `null` is the cheaper answer to a request
|
||||
/// that arrives on every keystroke.
|
||||
pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Option<InlineItems> {
|
||||
///
|
||||
/// `selected` is the request's `context.selectedCompletionInfo` — the popup's
|
||||
/// selected entry, when one is showing. Only the keyword ghost reads it.
|
||||
pub fn inline_completions_in_context(
|
||||
ws: &Workspace,
|
||||
uri: &Uri,
|
||||
position: Position,
|
||||
selected: Option<&SelectedCompletionInfo>,
|
||||
) -> Option<InlineItems> {
|
||||
let doc = ws.document(uri)?;
|
||||
// No token stream, no answer — the same trade `completion.rs` makes. A
|
||||
// half-typed string or block comment is what breaks the lexer, and those
|
||||
@@ -260,14 +275,24 @@ pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Opti
|
||||
return instantiation(ws, doc, name, at);
|
||||
}
|
||||
let last = last_token(doc, offset)?;
|
||||
match doc.tokens.get(last)?.kind {
|
||||
// A name with nothing after it is not an offer (owner ruling,
|
||||
// 2026-08-30): `aes` may still be growing into `aes_dft`, and the
|
||||
// space is the user saying that it is not. No trigger's own last token
|
||||
// is an `Ident` either, so nothing is lost by stopping here.
|
||||
TokenKind::Ident => None,
|
||||
_ => template(ws, doc, last, at),
|
||||
// A name with nothing after it is not an instantiation offer (owner
|
||||
// ruling, 2026-08-30): `aes` may still be growing into `aes_dft`, and the
|
||||
// space is the user saying that it is not. No trigger's own last token is
|
||||
// an `Ident` either, so only the keyword ghost is asked about one.
|
||||
if doc.tokens.get(last)?.kind != TokenKind::Ident {
|
||||
if let Some(items) = template(ws, doc, last, at) {
|
||||
return Some(items);
|
||||
}
|
||||
}
|
||||
// The fallback: the rest of a keyword the word is a proper prefix of.
|
||||
keywords::keyword_ghost(ws, doc, last, position, selected)
|
||||
}
|
||||
|
||||
/// [`inline_completions_in_context`] with no popup open — what every test
|
||||
/// that is not about the popup asks.
|
||||
#[cfg(test)]
|
||||
pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Option<InlineItems> {
|
||||
inline_completions_in_context(ws, uri, position, None)
|
||||
}
|
||||
|
||||
/// The identifier the user has just finished and armed with a space: the token
|
||||
@@ -299,7 +324,7 @@ fn template(ws: &Workspace, doc: &Document, last: usize, at: Range) -> Option<In
|
||||
return None;
|
||||
}
|
||||
let (trigger, opened) = triggered(doc, last)?;
|
||||
if !unfinished(doc, trigger, opened) {
|
||||
if !unfinished(doc, trigger, opened, last) {
|
||||
return None;
|
||||
}
|
||||
Some(InlineItems {
|
||||
@@ -487,13 +512,20 @@ fn triggered(doc: &Document, index: usize) -> Option<(&'static Trigger, Opened)>
|
||||
}
|
||||
|
||||
/// Whether the construct the user opened really is still waiting to be closed.
|
||||
fn unfinished(doc: &Document, trigger: &Trigger, opened: Opened) -> bool {
|
||||
///
|
||||
/// `last` is the index of the token just typed — for `begin`, the keyword
|
||||
/// itself, which is asked the auto-`end` question (`on_type::auto_end`)
|
||||
/// rather than "is this span unmatched": a `begin` typed inside a balanced
|
||||
/// block steals that block's `end` in the stack matcher, and would otherwise
|
||||
/// get no ghost (`completion-ux` fix round, 2026-11-17).
|
||||
fn unfinished(doc: &Document, trigger: &Trigger, opened: Opened, last: usize) -> bool {
|
||||
let paren = || !paren_is_closed(&doc.tokens, opened.last);
|
||||
let scope = || {
|
||||
pairs::analyze(&doc.tokens).unmatched_open.iter().any(|open| open.span == opened.keyword)
|
||||
};
|
||||
match trigger.gate {
|
||||
Unclosed::Paren => paren(),
|
||||
Unclosed::Scope if trigger.keyword == "begin" => on_type::begin_owes_an_end(doc, last),
|
||||
Unclosed::Scope => scope(),
|
||||
// The paren check first: it is a flat pass over the tokens, and
|
||||
// skipping `pairs::analyze` when it already says no is what keeps this
|
||||
@@ -822,15 +854,16 @@ endmodule
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_always_at_offers_the_clocked_block_first_and_the_star_second() {
|
||||
fn an_always_at_offers_clock_and_reset_first_then_clock_only_then_the_star() {
|
||||
let text = "module top;\n always @(\nendmodule\n";
|
||||
assert_eq!(
|
||||
all_offered(text, "always @("),
|
||||
vec![
|
||||
"posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend".to_string(),
|
||||
"posedge ${1:clk}) begin\n\t$0\nend".to_string(),
|
||||
"*) begin\n\t$0\nend".to_string(),
|
||||
],
|
||||
"clocked first: `always @(` is overwhelmingly a flop"
|
||||
"clocked first: `always @(` is overwhelmingly a flop, and most flops reset"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -839,7 +872,10 @@ endmodule
|
||||
let text = "module top;\n always_ff @(\nendmodule\n";
|
||||
assert_eq!(
|
||||
offered_in("/rtl/top.sv", text, "always_ff @("),
|
||||
vec!["posedge ${1:clk}) begin\n\t$0\nend"]
|
||||
vec![
|
||||
"posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend",
|
||||
"posedge ${1:clk}) begin\n\t$0\nend"
|
||||
]
|
||||
);
|
||||
assert!(
|
||||
offered_in("/rtl/top.v", text, "always_ff @(").is_empty(),
|
||||
@@ -930,6 +966,15 @@ endmodule
|
||||
assert!(offered(text, "initial begin").is_some(), "this one lost its end");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_begin_typed_inside_a_balanced_block_still_offers_its_end() {
|
||||
// The new `begin` steals the `always_comb` block's `end` in the stack
|
||||
// matcher; the gate asks the auto-`end` question instead
|
||||
// (`completion-ux` fix round, 2026-11-17).
|
||||
let text = "module top;\n always_comb begin\n if (x) begin\n end\nendmodule\n";
|
||||
assert_eq!(offered(text, "if (x) begin").as_deref(), Some("\n\t$0\nend"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scope_keyword_that_already_has_its_closer_offers_nothing() {
|
||||
// The same rule as `begin`, for the three keywords that joined it.
|
||||
@@ -1019,8 +1064,10 @@ endmodule
|
||||
fn an_always_without_its_event_control_offers_nothing() {
|
||||
// The opener is a *sequence*: both `@` and `(` must be there, in that
|
||||
// order, or the user has not committed to an event-controlled block.
|
||||
// A bare `always` grows no block — only the keyword ghost's `_ff`,
|
||||
// which is a different feature with its own setting.
|
||||
let text = "module top;\n always\nendmodule\n";
|
||||
assert_eq!(offered(text, " always"), None);
|
||||
assert_eq!(offered(text, " always").as_deref(), Some("_ff"));
|
||||
let text = "module top;\n always @\nendmodule\n";
|
||||
assert_eq!(offered(text, "always @"), None);
|
||||
let text = "module top;\n always (\nendmodule\n";
|
||||
@@ -1140,7 +1187,7 @@ endmodule
|
||||
assert_eq!(offered(text, " if(").as_deref(), Some("${1:cond}) begin\n\t$0\nend"));
|
||||
// ...and the same for a two-symbol opener written tight.
|
||||
let text = "module top;\n always@(\nendmodule\n";
|
||||
assert_eq!(all_offered(text, "always@(").len(), 2);
|
||||
assert_eq!(all_offered(text, "always@(").len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1532,7 +1579,7 @@ endmodule
|
||||
// `no_space_between_the_keyword_and_the_paren_still_triggers`, this
|
||||
// pins the opposite spacing.
|
||||
let text = "module top;\n always @ (\nendmodule\n";
|
||||
assert_eq!(all_offered(text, "always @ (").len(), 2);
|
||||
assert_eq!(all_offered(text, "always @ (").len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1588,7 +1635,7 @@ endmodule
|
||||
// counterpart — both must still offer.
|
||||
let text = "module top;\n if (\n always @(\nendmodule\n";
|
||||
assert!(offered(text, " if (").is_some());
|
||||
assert_eq!(all_offered(text, " always @(").len(), 2);
|
||||
assert_eq!(all_offered(text, " always @(").len(), 3);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -1629,6 +1676,16 @@ endmodule
|
||||
serde_json::to_value(&items).expect("serializes"),
|
||||
serde_json::json!({
|
||||
"items": [
|
||||
{
|
||||
"insertText": {
|
||||
"kind": "snippet",
|
||||
"value": "posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend"
|
||||
},
|
||||
"range": {
|
||||
"start": { "line": 1, "character": 11 },
|
||||
"end": { "line": 1, "character": 11 }
|
||||
}
|
||||
},
|
||||
{
|
||||
"insertText": {
|
||||
"kind": "snippet",
|
||||
|
||||
@@ -0,0 +1,519 @@
|
||||
//! Keyword ghosts (TODO §68.1): a typed proper prefix of a keyword shows the
|
||||
//! rest of it as grey text — `alw` grows `ays_ff`, Tab accepts.
|
||||
//!
|
||||
//! The fallback ghost: asked only where no template trigger answered, and
|
||||
//! only for an identifier-like word of two characters or more that ends
|
||||
//! exactly at the cursor. Three rules decide which keyword, in order:
|
||||
//!
|
||||
//! 1. **The popup's choice.** While VS Code's suggest widget is open it shows
|
||||
//! an inline item only if it extends the selected entry over the selected
|
||||
//! entry's range (LSP 3.18 `selectedCompletionInfo`). So with a selection,
|
||||
//! the ghost is exactly that keyword when it is one, and nothing otherwise.
|
||||
//! 2. **A fixed priority list** of the words an RTL designer types all day.
|
||||
//! 3. **Shortest, then alphabetical**, over every keyword of the buffer's
|
||||
//! dialect.
|
||||
//!
|
||||
//! A word that is already a keyword is only extended across an underscore:
|
||||
//! `always` grows `_ff`, but `for` stays `for` and `end` stays `end` — the
|
||||
//! keystroke after a finished keyword is a space or a newline far more often
|
||||
//! than another letter, and a ghost there is noise a stray Tab accepts.
|
||||
//! See `docs/features/completion-ux/README.md`.
|
||||
|
||||
use lsp_types::{Position, Range, SelectedCompletionInfo};
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::KEYWORDS;
|
||||
|
||||
use super::{InlineItem, InlineItems, SnippetValue};
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::templates::{self, Dialect};
|
||||
|
||||
/// The shortest word worth a ghost. One letter is a prefix of half the
|
||||
/// keyword list, and the ghost would change on every keystroke.
|
||||
const MIN_WORD: usize = 2;
|
||||
|
||||
/// The keywords tried first, in this order, whenever more than one extends
|
||||
/// the typed word. Everything else falls back to shortest-then-alphabetical.
|
||||
const PRIORITY: &[&str] = &[
|
||||
"always_ff",
|
||||
"always_comb",
|
||||
"always",
|
||||
"assign",
|
||||
"begin",
|
||||
"logic",
|
||||
"input",
|
||||
"output",
|
||||
"inout",
|
||||
"module",
|
||||
"endmodule",
|
||||
"parameter",
|
||||
"localparam",
|
||||
"function",
|
||||
"endfunction",
|
||||
"task",
|
||||
"endtask",
|
||||
"generate",
|
||||
"endgenerate",
|
||||
"genvar",
|
||||
"case",
|
||||
"endcase",
|
||||
"default",
|
||||
"initial",
|
||||
"integer",
|
||||
"posedge",
|
||||
"negedge",
|
||||
"typedef",
|
||||
"struct",
|
||||
"enum",
|
||||
"package",
|
||||
"endpackage",
|
||||
"interface",
|
||||
"endinterface",
|
||||
"foreach",
|
||||
"forever",
|
||||
"return",
|
||||
"automatic",
|
||||
"unique",
|
||||
"wire",
|
||||
"reg",
|
||||
];
|
||||
|
||||
/// The IEEE 1364-2005 reserved words: what a `.v` buffer may be offered. The
|
||||
/// lexer's list is one list for both dialects, and `logic` grown in a file a
|
||||
/// Verilog compiler reads is a ghost that hands the user an error.
|
||||
const VERILOG: &[&str] = &[
|
||||
"always",
|
||||
"and",
|
||||
"assign",
|
||||
"automatic",
|
||||
"begin",
|
||||
"buf",
|
||||
"bufif0",
|
||||
"bufif1",
|
||||
"case",
|
||||
"casex",
|
||||
"casez",
|
||||
"cell",
|
||||
"cmos",
|
||||
"config",
|
||||
"deassign",
|
||||
"default",
|
||||
"defparam",
|
||||
"design",
|
||||
"disable",
|
||||
"edge",
|
||||
"else",
|
||||
"end",
|
||||
"endcase",
|
||||
"endconfig",
|
||||
"endfunction",
|
||||
"endgenerate",
|
||||
"endmodule",
|
||||
"endprimitive",
|
||||
"endspecify",
|
||||
"endtable",
|
||||
"endtask",
|
||||
"event",
|
||||
"for",
|
||||
"force",
|
||||
"forever",
|
||||
"fork",
|
||||
"function",
|
||||
"generate",
|
||||
"genvar",
|
||||
"highz0",
|
||||
"highz1",
|
||||
"if",
|
||||
"ifnone",
|
||||
"incdir",
|
||||
"include",
|
||||
"initial",
|
||||
"inout",
|
||||
"input",
|
||||
"instance",
|
||||
"integer",
|
||||
"join",
|
||||
"large",
|
||||
"liblist",
|
||||
"library",
|
||||
"localparam",
|
||||
"macromodule",
|
||||
"medium",
|
||||
"module",
|
||||
"nand",
|
||||
"negedge",
|
||||
"nmos",
|
||||
"nor",
|
||||
"noshowcancelled",
|
||||
"not",
|
||||
"notif0",
|
||||
"notif1",
|
||||
"or",
|
||||
"output",
|
||||
"parameter",
|
||||
"pmos",
|
||||
"posedge",
|
||||
"primitive",
|
||||
"pull0",
|
||||
"pull1",
|
||||
"pulldown",
|
||||
"pullup",
|
||||
"pulsestyle_ondetect",
|
||||
"pulsestyle_onevent",
|
||||
"rcmos",
|
||||
"real",
|
||||
"realtime",
|
||||
"reg",
|
||||
"release",
|
||||
"repeat",
|
||||
"rnmos",
|
||||
"rpmos",
|
||||
"rtran",
|
||||
"rtranif0",
|
||||
"rtranif1",
|
||||
"scalared",
|
||||
"showcancelled",
|
||||
"signed",
|
||||
"small",
|
||||
"specify",
|
||||
"specparam",
|
||||
"strong0",
|
||||
"strong1",
|
||||
"supply0",
|
||||
"supply1",
|
||||
"table",
|
||||
"task",
|
||||
"time",
|
||||
"tran",
|
||||
"tranif0",
|
||||
"tranif1",
|
||||
"tri",
|
||||
"tri0",
|
||||
"tri1",
|
||||
"triand",
|
||||
"trior",
|
||||
"trireg",
|
||||
"unsigned",
|
||||
"use",
|
||||
"uwire",
|
||||
"vectored",
|
||||
"wait",
|
||||
"wand",
|
||||
"weak0",
|
||||
"weak1",
|
||||
"while",
|
||||
"wire",
|
||||
"wor",
|
||||
"xnor",
|
||||
"xor",
|
||||
];
|
||||
|
||||
/// The keyword ghost for the word ending at `position`, or `None`.
|
||||
///
|
||||
/// `last` is the index of the token ending exactly at the cursor — the
|
||||
/// caller's `last_token` — and `selected` the popup's selected entry, when
|
||||
/// the client said one is showing.
|
||||
pub(super) fn keyword_ghost(
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
last: usize,
|
||||
position: Position,
|
||||
selected: Option<&SelectedCompletionInfo>,
|
||||
) -> Option<InlineItems> {
|
||||
if !ws.client_settings().inline_keywords.unwrap_or(true) {
|
||||
return None;
|
||||
}
|
||||
let (word, start) = typed_word(doc, last)?;
|
||||
// A name this buffer declares is what the user is typing, not the front
|
||||
// of a keyword: `in`, `re`, `out` as signals stay quiet (fix round).
|
||||
if doc.semantics.symbols().iter().any(|symbol| symbol.name == word) {
|
||||
return None;
|
||||
}
|
||||
let dialect = templates::dialect(doc.path.as_deref());
|
||||
// A selection that does not cover exactly the typed word is about some
|
||||
// other text, and is read as no selection at all — never echoed back.
|
||||
let word_range = Range { start: doc.positions().position(start), end: position };
|
||||
let selected = selected.filter(|info| info.range == word_range);
|
||||
let (keyword, range) = match selected {
|
||||
// An explicit selection wins over the finished-keyword rule: `end`
|
||||
// with `endmodule` selected ghosts `endmodule`.
|
||||
Some(info) => {
|
||||
let text = info.text.as_str();
|
||||
(reserved_extension(word, text, dialect).then_some(text)?, info.range)
|
||||
}
|
||||
None => (best_keyword(word, dialect)?, Range { start: position, end: position }),
|
||||
};
|
||||
// Without a selection the item inserts at the cursor, as every other
|
||||
// ghost here does; with one it must replace the selection's range with
|
||||
// the whole word, which is the shape the client compares against.
|
||||
let value = match selected {
|
||||
Some(_) => keyword.to_string(),
|
||||
None => keyword[word.len()..].to_string(),
|
||||
};
|
||||
Some(InlineItems {
|
||||
items: vec![InlineItem { insert_text: SnippetValue { kind: "snippet", value }, range }],
|
||||
})
|
||||
}
|
||||
|
||||
/// The word a keyword ghost may extend: the token at `last` when it is a
|
||||
/// plain identifier or a keyword, at least [`MIN_WORD`] long, spelled with
|
||||
/// identifier characters only, and not a member name after a `.` or `::`.
|
||||
///
|
||||
/// A macro use (`` `alw ``), an escaped identifier and a `$system` name all
|
||||
/// fail the character test or the kind test; a comment and a string never
|
||||
/// produce a token ending at the cursor at all.
|
||||
fn typed_word(doc: &Document, last: usize) -> Option<(&str, u32)> {
|
||||
let token = doc.tokens.get(last)?;
|
||||
if !matches!(token.kind, TokenKind::Ident | TokenKind::Keyword) {
|
||||
return None;
|
||||
}
|
||||
let text = token.text.as_str();
|
||||
let plain = text.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
|
||||
&& text.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
|
||||
if !plain || text.len() < MIN_WORD {
|
||||
return None;
|
||||
}
|
||||
let after_separator = last
|
||||
.checked_sub(1)
|
||||
.and_then(|i| doc.tokens.get(i))
|
||||
.is_some_and(|prev| prev.is_sym(".") || prev.is_sym("::") || prev.is_sym("`"));
|
||||
(!after_separator).then_some((text, token.span.start))
|
||||
}
|
||||
|
||||
/// The keyword to ghost behind `word` with no popup selection to follow.
|
||||
fn best_keyword(word: &str, dialect: Dialect) -> Option<&'static str> {
|
||||
if let Some(first) = PRIORITY.iter().copied().find(|kw| extends(word, kw, dialect)) {
|
||||
return Some(first);
|
||||
}
|
||||
KEYWORDS
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|kw| extends(word, kw, dialect))
|
||||
.min_by(|a, b| a.len().cmp(&b.len()).then(a.cmp(b)))
|
||||
}
|
||||
|
||||
/// Whether `keyword` is a reserved word of `dialect` that properly extends
|
||||
/// `word` — across an underscore only, when `word` is already a keyword.
|
||||
fn extends(word: &str, keyword: &str, dialect: Dialect) -> bool {
|
||||
reserved_extension(word, keyword, dialect)
|
||||
&& (!KEYWORDS.contains(&word) || keyword.as_bytes()[word.len()] == b'_')
|
||||
}
|
||||
|
||||
/// Whether `keyword` is a reserved word of `dialect` that properly extends
|
||||
/// `word` — the whole test for a keyword the popup has selected.
|
||||
fn reserved_extension(word: &str, keyword: &str, dialect: Dialect) -> bool {
|
||||
keyword.len() > word.len()
|
||||
&& keyword.starts_with(word)
|
||||
&& KEYWORDS.contains(&keyword)
|
||||
&& (dialect == Dialect::SystemVerilog || VERILOG.contains(&keyword))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::inline::inline_completions_in_context;
|
||||
use crate::settings::ClientSettings;
|
||||
use lsp_types::Uri;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// The ghosts at the end of `needle` in `text`, opened as `/rtl/top.sv`,
|
||||
/// as `(value, range)` pairs.
|
||||
fn ghosts(
|
||||
text: &str,
|
||||
needle: &str,
|
||||
selected: Option<SelectedCompletionInfo>,
|
||||
settings: ClientSettings,
|
||||
) -> Vec<(String, Range)> {
|
||||
let uri = Uri::from_str("file:///rtl/top.sv").expect("uri");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(settings);
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let offset = (text.find(needle).expect("needle") + needle.len()) as u32;
|
||||
let position = doc.positions().position(offset);
|
||||
inline_completions_in_context(&ws, &uri, position, selected.as_ref())
|
||||
.map(|found| {
|
||||
found.items.into_iter().map(|item| (item.insert_text.value, item.range)).collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn plain(text: &str, needle: &str) -> Vec<String> {
|
||||
ghosts(text, needle, None, ClientSettings::default())
|
||||
.into_iter()
|
||||
.map(|(value, _)| value)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn at(line: u32, character: u32) -> Position {
|
||||
Position { line, character }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_keyword_prefix_grows_the_rest_of_the_keyword_at_the_cursor() {
|
||||
let text = "module top;\n alw\nendmodule\n";
|
||||
let found = ghosts(text, " alw", None, ClientSettings::default());
|
||||
let cursor = at(1, 5);
|
||||
assert_eq!(found, vec![("ays_ff".to_string(), Range { start: cursor, end: cursor })]);
|
||||
assert_eq!(
|
||||
plain("module top;\n logic a;\n assign a = 1;\n endm\n", " endm"),
|
||||
["odule"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_popups_selection_is_followed_over_its_own_range() {
|
||||
let text = "module top;\n alw\nendmodule\n";
|
||||
let range = Range { start: at(1, 2), end: at(1, 5) };
|
||||
let selected = SelectedCompletionInfo { range, text: "always_comb".to_string() };
|
||||
let found = ghosts(text, " alw", Some(selected), ClientSettings::default());
|
||||
assert_eq!(found, vec![("always_comb".to_string(), range)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_that_is_not_a_keyword_extension_silences_the_ghost() {
|
||||
let text = "module top;\n logic alw_q;\n alw\nendmodule\n";
|
||||
let range = Range { start: at(2, 2), end: at(2, 5) };
|
||||
let selected = SelectedCompletionInfo { range, text: "alw_q".to_string() };
|
||||
assert!(ghosts(text, "\n alw", Some(selected), ClientSettings::default()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_ghost_after_a_separator_in_a_comment_or_for_one_letter() {
|
||||
assert!(plain("module top;\n assign x = s.al\nendmodule\n", "s.al").is_empty());
|
||||
assert!(plain("module top;\n import p::al\nendmodule\n", "p::al").is_empty());
|
||||
assert!(plain("module top;\n // alw\nendmodule\n", "// alw").is_empty());
|
||||
assert!(plain("module top;\n a\nendmodule\n", " a").is_empty());
|
||||
assert!(plain("module top;\n `alw\nendmodule\n", "`alw").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_ghost_when_the_rest_of_the_line_is_written() {
|
||||
assert!(plain("module top;\n alw x;\nendmodule\n", " alw").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_setting_turns_keyword_ghosts_off_and_leaves_templates_on() {
|
||||
let off = ClientSettings { inline_keywords: Some(false), ..Default::default() };
|
||||
let text = "module top;\n alw\nendmodule\n";
|
||||
assert!(ghosts(text, " alw", None, off.clone()).is_empty());
|
||||
let text = "module top;\n always_comb begin\n if (\n end\nendmodule\n";
|
||||
assert_eq!(ghosts(text, "if (", None, off).len(), 1, "the template ghost is untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_template_trigger_wins_over_the_keyword_ghost() {
|
||||
// `begin` is a finished keyword and a trigger: its ghost is the block.
|
||||
let text = "module top;\n initial begin\nendmodule\n";
|
||||
assert_eq!(plain(text, "initial begin"), ["\n\t$0\nend"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_priority_list_picks_among_several_extensions() {
|
||||
let sv = Dialect::SystemVerilog;
|
||||
assert_eq!(best_keyword("al", sv), Some("always_ff"));
|
||||
assert_eq!(best_keyword("always_c", sv), Some("always_comb"));
|
||||
assert_eq!(best_keyword("as", sv), Some("assign"));
|
||||
assert_eq!(best_keyword("lo", sv), Some("logic"));
|
||||
assert_eq!(best_keyword("endm", sv), Some("endmodule"));
|
||||
assert_eq!(best_keyword("par", sv), Some("parameter"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outside_the_list_the_shortest_then_alphabetical_keyword_wins() {
|
||||
assert_eq!(best_keyword("tr", Dialect::SystemVerilog), Some("tri"), "tri before tran");
|
||||
assert_eq!(best_keyword("tri", Dialect::SystemVerilog), None, "`tri` is finished");
|
||||
assert_eq!(best_keyword("xn", Dialect::SystemVerilog), Some("xnor"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finished_keyword_only_grows_across_an_underscore() {
|
||||
let sv = Dialect::SystemVerilog;
|
||||
assert_eq!(best_keyword("always", sv), Some("always_ff"));
|
||||
assert_eq!(best_keyword("end", sv), None, "`end` is finished");
|
||||
assert_eq!(best_keyword("for", sv), None, "`for` is finished");
|
||||
assert_eq!(best_keyword("case", sv), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_verilog_buffer_is_only_offered_verilog_words() {
|
||||
let v = Dialect::Verilog;
|
||||
assert_eq!(best_keyword("al", v), Some("always"));
|
||||
assert_eq!(best_keyword("lo", v), Some("localparam"), "no `logic` in a .v file");
|
||||
assert_eq!(best_keyword("always", v), None, "no `always_ff` either");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_listed_word_is_a_reserved_word_the_lexer_knows() {
|
||||
for word in PRIORITY {
|
||||
assert!(KEYWORDS.contains(word), "{word}");
|
||||
}
|
||||
}
|
||||
|
||||
/// QA (2026-11-17): the shape an unbridged client sends — VS Code's
|
||||
/// `Range` serialized by its `toJSON` as `[start, end]`, trigger kind 0 —
|
||||
/// still decodes (serde reads a struct from a sequence), so the
|
||||
/// extension's middleware is a spelling fix, not what keeps the request
|
||||
/// alive.
|
||||
#[test]
|
||||
fn qa_an_array_shaped_range_and_a_zero_trigger_kind_still_decode() {
|
||||
let params: lsp_types::InlineCompletionParams = serde_json::from_value(serde_json::json!({
|
||||
"textDocument": { "uri": "file:///rtl/top.sv" },
|
||||
"position": { "line": 1, "character": 5 },
|
||||
"context": {
|
||||
"triggerKind": 0,
|
||||
"selectedCompletionInfo": {
|
||||
"range": [{ "line": 1, "character": 2 }, { "line": 1, "character": 5 }],
|
||||
"text": "always_comb"
|
||||
}
|
||||
}
|
||||
}))
|
||||
.expect("decodes");
|
||||
let selected = params.context.selected_completion_info.expect("kept");
|
||||
assert_eq!(selected.range, Range { start: at(1, 2), end: at(1, 5) });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_extends_a_word_that_is_no_keyword_prefix() {
|
||||
assert_eq!(best_keyword("clk", Dialect::SystemVerilog), None);
|
||||
assert!(extends("al", "always", Dialect::SystemVerilog));
|
||||
assert!(!extends("Al", "always", Dialect::SystemVerilog), "case matters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_this_buffer_declares_grows_no_keyword() {
|
||||
let text = "module top;\n logic re, in;\n assign x = re\nendmodule\n";
|
||||
assert!(plain(text, "= re").is_empty(), "`re` is a signal here, not `return`");
|
||||
// An undeclared word still ghosts, expression position or not.
|
||||
let text = "module top;\n assign x = ou\nendmodule\n";
|
||||
assert_eq!(plain(text, "= ou"), ["tput"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicit_selection_wins_over_the_finished_keyword_rule() {
|
||||
let text = "module top;\n logic a;\n end\nendmodule\n";
|
||||
assert!(plain(text, "\n end").is_empty(), "no popup: `end` is finished");
|
||||
let range = Range { start: at(2, 2), end: at(2, 5) };
|
||||
let selected = SelectedCompletionInfo { range, text: "endmodule".to_string() };
|
||||
let found = ghosts(text, "\n end", Some(selected), ClientSettings::default());
|
||||
assert_eq!(found, vec![("endmodule".to_string(), range)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_over_some_other_range_is_read_as_no_selection() {
|
||||
let text = "module top;\n alw\nendmodule\n";
|
||||
let cursor = at(1, 5);
|
||||
for range in [
|
||||
Range { start: at(1, 2), end: at(1, 4) },
|
||||
Range { start: at(1, 3), end: cursor },
|
||||
Range { start: at(0, 0), end: at(0, 6) },
|
||||
] {
|
||||
let selected = SelectedCompletionInfo { range, text: "always_comb".to_string() };
|
||||
let found = ghosts(text, " alw", Some(selected), ClientSettings::default());
|
||||
assert_eq!(
|
||||
found,
|
||||
vec![("ays_ff".to_string(), Range { start: cursor, end: cursor })],
|
||||
"{range:?} is never echoed back"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,10 @@ use crate::format;
|
||||
use crate::pairs;
|
||||
use crate::state::{first_token_from, first_token_reaching, Document};
|
||||
|
||||
mod auto_end;
|
||||
|
||||
pub(crate) use auto_end::begin_owes_an_end;
|
||||
|
||||
/// The character the client is told to trigger on. A newline is the one
|
||||
/// keystroke that opens a line whose indentation nobody has chosen yet.
|
||||
pub const NEWLINE: &str = "\n";
|
||||
@@ -40,12 +44,21 @@ pub const SEMICOLON: &str = ";";
|
||||
///
|
||||
/// Never an `Err`: every refusal on this path — an unknown trigger, a client
|
||||
/// out of step, a buffer the formatter will not touch — is the empty answer.
|
||||
///
|
||||
/// `auto_end` is `lucisv.autoEnd`: whether a newline typed after a `begin`
|
||||
/// that still owes its `end` also writes that `end` (see `auto_end.rs`).
|
||||
pub fn on_type_formatting(
|
||||
doc: &Document,
|
||||
position: Position,
|
||||
typed: &str,
|
||||
config: &Config,
|
||||
auto_end: bool,
|
||||
) -> Vec<TextEdit> {
|
||||
if auto_end && typed == NEWLINE {
|
||||
if let Some(edits) = auto_end::begin_newline_edits(doc, position, config.indent_width) {
|
||||
return edits;
|
||||
}
|
||||
}
|
||||
let edit = match typed {
|
||||
NEWLINE => indent_edit(doc, position, config.indent_width),
|
||||
SEMICOLON => statement_edit(doc, position, config),
|
||||
@@ -715,7 +728,7 @@ mod tests {
|
||||
|
||||
fn newline_with(text: &str, line: u32, indent_width: usize) -> Vec<TextEdit> {
|
||||
let at = Position { line, character: 0 };
|
||||
with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(indent_width)))
|
||||
with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(indent_width), false))
|
||||
}
|
||||
|
||||
/// The `new_text` of the single edit a newline produced, or `None` when it
|
||||
@@ -732,7 +745,7 @@ mod tests {
|
||||
let content = source[line as usize].trim_end_matches('\n');
|
||||
let character = content.rfind(';').expect("the line ends a statement") as u32 + 1;
|
||||
let at = Position { line, character };
|
||||
with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)))
|
||||
with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false))
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -793,7 +806,7 @@ mod tests {
|
||||
// it means the client is not talking about a newline it just typed.
|
||||
let text = "module m;\nwire a;\nendmodule\n";
|
||||
let at = Position { line: 1, character: 4 };
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(2)));
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(2), false));
|
||||
assert_eq!(edits, Vec::new());
|
||||
}
|
||||
|
||||
@@ -955,7 +968,7 @@ mod tests {
|
||||
with(text, |doc| {
|
||||
for line in 1..text.lines().count() as u32 {
|
||||
let at = Position { line, character: 0 };
|
||||
for edit in on_type_formatting(doc, at, NEWLINE, &config(2)) {
|
||||
for edit in on_type_formatting(doc, at, NEWLINE, &config(2), false) {
|
||||
assert_eq!(edit.range.start, at, "always column zero of the asked-for line");
|
||||
assert_eq!(edit.range.end.line, line, "and never past that line");
|
||||
let source = doc.text.lines().nth(line as usize).unwrap_or("");
|
||||
@@ -1178,7 +1191,7 @@ mod tests {
|
||||
// buffer no longer refuses (selection-formatting, TODO §66.2).
|
||||
let text = "module m;\n wire a = ;\nendmodule\n";
|
||||
let at = Position { line: 1, character: 13 };
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
|
||||
assert_eq!(edits, Vec::new());
|
||||
}
|
||||
|
||||
@@ -1192,7 +1205,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_semicolon_that_is_not_where_the_client_said_answers_nothing() {
|
||||
let at = Position { line: 1, character: 3 };
|
||||
let edits = with(MESSY, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
|
||||
let edits = with(MESSY, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
|
||||
assert_eq!(edits, Vec::new());
|
||||
}
|
||||
|
||||
@@ -1203,7 +1216,7 @@ mod tests {
|
||||
assert_eq!(semicolon(text, 1), Vec::new());
|
||||
let text = "module m;\n string s = \"a;\";\n wire a;\nendmodule\n";
|
||||
let at = Position { line: 1, character: 16 };
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
|
||||
assert_eq!(edits, Vec::new(), "the `;` inside the quotes");
|
||||
}
|
||||
|
||||
@@ -1214,7 +1227,7 @@ mod tests {
|
||||
// the whole document.
|
||||
let text = "module m;\n wire a;\nendmodule";
|
||||
let at = Position { line: 1, character: 11 };
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
|
||||
assert_eq!(edits.len(), 1, "{edits:#?}");
|
||||
// Only the statement moves: the file's tail is outside the splice, so
|
||||
// the missing final newline stays missing — exactly what
|
||||
@@ -1253,7 +1266,7 @@ mod tests {
|
||||
// inside a string or a comment.
|
||||
let text = "`define FOO x = 1;\nmodule m;\nendmodule\n";
|
||||
let at = Position { line: 0, character: 19 };
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
|
||||
assert_eq!(edits, Vec::new(), "no Symbol(;) token ends inside a Directive");
|
||||
}
|
||||
|
||||
@@ -1281,7 +1294,7 @@ mod tests {
|
||||
// guess at what it meant.
|
||||
let at = Position { line: 1, character: 9 };
|
||||
for typed in ["}", ")", "\t", ""] {
|
||||
let edits = with(MESSY, |doc| on_type_formatting(doc, at, typed, &config(2)));
|
||||
let edits = with(MESSY, |doc| on_type_formatting(doc, at, typed, &config(2), false));
|
||||
assert_eq!(edits, Vec::new(), "trigger {typed:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,581 @@
|
||||
//! `begin` + Enter writes the `end` (TODO §68.1).
|
||||
//!
|
||||
//! The newline answer's second half. When the line above the one a `\n` just
|
||||
//! opened ends in `begin` (or `begin : label`) and that block still owes an
|
||||
//! `end`, the answer is two edits instead of one: the new line's body
|
||||
//! indentation, as the plain newline answer would give it, and a line after
|
||||
//! it holding `end` at the indentation of the statement the `begin` belongs
|
||||
//! to. The cursor's line stays blank, so the user types the first statement
|
||||
//! where they already are.
|
||||
//!
|
||||
//! **Which `begin` owes an `end`.** `pairs::analyze` is a stack matcher, so a
|
||||
//! `begin` typed inside a block that already balances *steals* that block's
|
||||
//! `end`: the new inner `begin` comes out matched, and the outer one is
|
||||
//! reported unclosed. "Is *this* `begin` unmatched" is therefore the wrong
|
||||
//! question. The one asked here is: is any `begin` at or before this one
|
||||
//! unclosed — unless this `begin` is matched by an `end` that starts its line
|
||||
//! at exactly the indentation this answer would have written, which is the
|
||||
//! block the user already closed. See `docs/features/completion-ux/README.md`.
|
||||
|
||||
use lsp_types::{Position, Range, TextEdit};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
use super::level_at;
|
||||
use crate::pairs;
|
||||
use crate::state::{first_token_from, Document};
|
||||
|
||||
/// The keywords whose header a `begin` may be the body of. Reading backwards,
|
||||
/// one of these is where the header starts.
|
||||
const HEADER_KEYWORDS: &[&str] = &[
|
||||
"if",
|
||||
"for",
|
||||
"foreach",
|
||||
"while",
|
||||
"repeat",
|
||||
"forever",
|
||||
"always",
|
||||
"always_ff",
|
||||
"always_comb",
|
||||
"always_latch",
|
||||
"initial",
|
||||
"final",
|
||||
];
|
||||
|
||||
/// The words that may stand in front of a header on the same statement:
|
||||
/// `else if`, `unique case`-style qualifiers, and a bare `else` before its
|
||||
/// `begin`.
|
||||
const QUALIFIERS: &[&str] = &["else", "unique", "unique0", "priority"];
|
||||
|
||||
/// The edits for a newline typed right after a `begin` that still owes its
|
||||
/// `end`, or `None` when this newline is not that — the caller then answers
|
||||
/// the plain indentation question instead.
|
||||
pub(super) fn begin_newline_edits(
|
||||
doc: &Document,
|
||||
position: Position,
|
||||
indent_width: usize,
|
||||
) -> Option<Vec<TextEdit>> {
|
||||
let line = NewLine::at(doc, position)?;
|
||||
let begin = begin_ending_line_above(doc, line.range.start)?;
|
||||
let end_indent = owner_indent(doc, begin);
|
||||
if !owes_an_end(doc, begin, &end_indent) {
|
||||
return None;
|
||||
}
|
||||
let body = body_indent(level_at(doc, line.content), &end_indent, indent_width);
|
||||
Some(edits(doc, &line, &body, &end_indent))
|
||||
}
|
||||
|
||||
/// The blank line a `\n` just opened, as far as this answer needs it.
|
||||
struct NewLine {
|
||||
/// The whole line, its `\r` included when the file has one.
|
||||
range: TextRange,
|
||||
/// The end of its leading whitespace.
|
||||
content: u32,
|
||||
/// The line ending the file writes, read off the newline just typed.
|
||||
eol: &'static str,
|
||||
}
|
||||
|
||||
impl NewLine {
|
||||
/// The line at `position`, when a newline opened it, the cursor sits in
|
||||
/// its leading whitespace, and nothing but whitespace is on it — Enter
|
||||
/// pressed in the middle of a line carries text down, and a body that is
|
||||
/// already written owes nothing.
|
||||
fn at(doc: &Document, position: Position) -> Option<NewLine> {
|
||||
let range = doc.line_index.line_range(position.line.checked_add(1)?)?;
|
||||
let bytes = doc.text.as_bytes();
|
||||
if range.start == 0 || bytes.get(range.start as usize - 1) != Some(&b'\n') {
|
||||
return None;
|
||||
}
|
||||
let text = doc.text.get(range.start as usize..range.end as usize)?;
|
||||
let rest = text.trim_start_matches([' ', '\t']);
|
||||
if !rest.trim_end_matches('\r').is_empty() {
|
||||
return None;
|
||||
}
|
||||
let content = range.start + (text.len() - rest.len()) as u32;
|
||||
if doc.positions().offset(position) > content {
|
||||
return None;
|
||||
}
|
||||
let crlf = range.start >= 2 && bytes.get(range.start as usize - 2) == Some(&b'\r');
|
||||
Some(NewLine { range, content, eol: if crlf { "\r\n" } else { "\n" } })
|
||||
}
|
||||
}
|
||||
|
||||
/// The index of the `begin` the line above `line_start` ends with — the last
|
||||
/// token on it, or the one before a `: label` — when it does.
|
||||
///
|
||||
/// Comments are trivia, not tokens, so `begin // why` ends in `begin` here
|
||||
/// without a check of its own.
|
||||
fn begin_ending_line_above(doc: &Document, line_start: u32) -> Option<usize> {
|
||||
let last = first_token_from(&doc.tokens, line_start).checked_sub(1)?;
|
||||
let above = doc.line_index.line_col(line_start).0.checked_sub(1)?;
|
||||
let on_line_above =
|
||||
|index: usize| doc.tokens.get(index).is_some_and(|token| line_of(doc, token) == above);
|
||||
let token = doc.tokens.get(last)?;
|
||||
let begin = match token.kind {
|
||||
TokenKind::Ident if last >= 2 && doc.tokens.get(last - 1)?.is_sym(":") => last - 2,
|
||||
_ => last,
|
||||
};
|
||||
(doc.tokens.get(begin)?.is_kw("begin") && on_line_above(begin) && on_line_above(last))
|
||||
.then_some(begin)
|
||||
}
|
||||
|
||||
/// The leading whitespace of the line the statement owning the `begin` at
|
||||
/// `begin` starts on, as written — tabs stay tabs.
|
||||
///
|
||||
/// Read backwards from the `begin` over what may stand between a statement's
|
||||
/// first token and its body: a parenthesised header, an `@`/`#` control and
|
||||
/// its operand, and [`HEAD_KEYWORDS`]. Anything else — a `;`, an `end`, a
|
||||
/// case item's `:` — is where the statement starts. A header with no `(` to
|
||||
/// match leaves the `begin`'s own line as the answer.
|
||||
fn owner_indent(doc: &Document, begin: usize) -> String {
|
||||
let tokens = &doc.tokens;
|
||||
let mut first = begin;
|
||||
// Once a header keyword is read, only a qualifier may still precede it:
|
||||
// `always_comb` on the line above an `if` is the `if`'s *owner*, not part
|
||||
// of its header.
|
||||
let mut keyword_seen = false;
|
||||
while let Some(prev) = first.checked_sub(1) {
|
||||
let token = &tokens[prev];
|
||||
let step = match keyword_seen {
|
||||
true => is_keyword_in(token, QUALIFIERS).then_some(prev),
|
||||
false => header_step(tokens, prev),
|
||||
};
|
||||
let Some(step) = step else { break };
|
||||
keyword_seen |= is_keyword_in(token, HEADER_KEYWORDS) || is_keyword_in(token, QUALIFIERS);
|
||||
first = step;
|
||||
}
|
||||
line_indent(doc, tokens[first].span.start)
|
||||
}
|
||||
|
||||
/// Where reading a header backwards goes from the token at `prev`: over a
|
||||
/// parenthesised group to its `(`, onto a header keyword, a qualifier, an
|
||||
/// `@`/`#`, or the operand right after one — or nowhere, when `prev` is
|
||||
/// already outside the header.
|
||||
fn header_step(tokens: &[Token], prev: usize) -> Option<usize> {
|
||||
let token = &tokens[prev];
|
||||
if token.is_sym(")") {
|
||||
return matching_open(tokens, prev);
|
||||
}
|
||||
let after_control = prev
|
||||
.checked_sub(1)
|
||||
.and_then(|i| tokens.get(i))
|
||||
.is_some_and(|t| t.is_sym("@") || t.is_sym("#"));
|
||||
let in_header = is_keyword_in(token, HEADER_KEYWORDS)
|
||||
|| is_keyword_in(token, QUALIFIERS)
|
||||
|| token.is_sym("@")
|
||||
|| token.is_sym("#")
|
||||
|| after_control;
|
||||
in_header.then_some(prev)
|
||||
}
|
||||
|
||||
fn is_keyword_in(token: &Token, words: &[&str]) -> bool {
|
||||
token.kind == TokenKind::Keyword && words.contains(&token.text.as_str())
|
||||
}
|
||||
|
||||
/// The `(` the `)` at `close` closes, counting parentheses only.
|
||||
fn matching_open(tokens: &[Token], close: usize) -> Option<usize> {
|
||||
let mut depth = 0u32;
|
||||
for index in (0..=close).rev() {
|
||||
let token = &tokens[index];
|
||||
if token.is_sym(")") {
|
||||
depth += 1;
|
||||
} else if token.is_sym("(") {
|
||||
depth = depth.checked_sub(1)?;
|
||||
if depth == 0 {
|
||||
return Some(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether the block the `begin` at `begin` opens still needs an `end`
|
||||
/// written for it. See the module comment for why this is not "is this
|
||||
/// `begin` unmatched".
|
||||
///
|
||||
/// Two layouts count as "already closed": the `end` under the statement (the
|
||||
/// formatter's own layout) and the `end` under the `begin`'s own line (the GNU
|
||||
/// layout, `begin` on a line of its own — QA finding 1, fix round
|
||||
/// 2026-11-17). And an unmatched `begin` inside a `` `ifdef `` that has an
|
||||
/// `` `else ``/`` `elsif `` arms nothing: two branches each opening a block
|
||||
/// closed by one shared `end` are an unmatched `begin` to the stack matcher
|
||||
/// and complete code to the compiler.
|
||||
fn owes_an_end(doc: &Document, begin: usize, end_indent: &str) -> bool {
|
||||
let span = doc.tokens[begin].span;
|
||||
let own_indent = line_indent(doc, span.start);
|
||||
let analysis = pairs::analyze(&doc.tokens);
|
||||
let closed_here = analysis.pairs.iter().any(|pair| {
|
||||
pair.open == span
|
||||
&& (starts_line_at(doc, pair.close, end_indent)
|
||||
|| starts_line_at(doc, pair.close, &own_indent))
|
||||
});
|
||||
if closed_here {
|
||||
return false;
|
||||
}
|
||||
let branched = branched_regions(&doc.tokens);
|
||||
analysis.unmatched_open.iter().any(|open| {
|
||||
open.keyword == "begin"
|
||||
&& open.span.start <= span.start
|
||||
&& !branched.iter().any(|region| region.contains(&open.span.start))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the `begin` at token index `begin` opens a block that still needs
|
||||
/// an `end` — [`owes_an_end`] with the `end` at its owner's indentation. The
|
||||
/// inline `begin` ghost asks the same question.
|
||||
pub(crate) fn begin_owes_an_end(doc: &Document, begin: usize) -> bool {
|
||||
owes_an_end(doc, begin, &owner_indent(doc, begin))
|
||||
}
|
||||
|
||||
/// The byte ranges of every `` `ifdef ``/`` `ifndef `` … `` `endif `` region
|
||||
/// that holds an `` `else `` or `` `elsif `` of its own. A region never closed
|
||||
/// runs to the end of the buffer.
|
||||
fn branched_regions(tokens: &[Token]) -> Vec<std::ops::Range<u32>> {
|
||||
let mut open: Vec<(u32, bool)> = Vec::new();
|
||||
let mut out = Vec::new();
|
||||
for token in tokens {
|
||||
match conditional(token) {
|
||||
Some("`ifdef" | "`ifndef") => open.push((token.span.start, false)),
|
||||
Some("`else" | "`elsif") => {
|
||||
if let Some(last) = open.last_mut() {
|
||||
last.1 = true;
|
||||
}
|
||||
}
|
||||
Some("`endif") => {
|
||||
if let Some((start, true)) = open.pop() {
|
||||
out.push(start..token.span.end);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let end = tokens.last().map_or(0, |token| token.span.end);
|
||||
out.extend(open.into_iter().filter(|(_, branched)| *branched).map(|(start, _)| start..end));
|
||||
out
|
||||
}
|
||||
|
||||
/// The conditional-compilation directive a token spells, by its first word.
|
||||
fn conditional(token: &Token) -> Option<&str> {
|
||||
let word = token.text.split_whitespace().next()?;
|
||||
matches!(word, "`ifdef" | "`ifndef" | "`else" | "`elsif" | "`endif").then_some(word)
|
||||
}
|
||||
|
||||
/// Whether `span` is the first thing on its line and that line is indented
|
||||
/// by exactly `indent`.
|
||||
fn starts_line_at(doc: &Document, span: TextRange, indent: &str) -> bool {
|
||||
let line = doc.line_index.line_col(span.start).0;
|
||||
let Some(range) = doc.line_index.line_range(line) else { return false };
|
||||
doc.text.get(range.start as usize..span.start as usize) == Some(indent)
|
||||
}
|
||||
|
||||
/// The body line's indentation: the nesting model's answer when it has one
|
||||
/// that sits inside the `end`, else one step in from the `end`. A file
|
||||
/// indented with tabs gets one more tab — the model speaks spaces, and mixing
|
||||
/// the two on adjacent lines would be worse than either.
|
||||
fn body_indent(level: Option<usize>, end_indent: &str, indent_width: usize) -> String {
|
||||
if end_indent.contains('\t') {
|
||||
return format!("{end_indent}\t");
|
||||
}
|
||||
match level {
|
||||
Some(level) if level * indent_width > end_indent.len() => " ".repeat(level * indent_width),
|
||||
_ => format!("{end_indent}{}", " ".repeat(indent_width)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The edits themselves: re-indent the new line when it needs it, and write
|
||||
/// the `end` line after it.
|
||||
///
|
||||
/// The `end` goes in at the **start of the following line** whenever there is
|
||||
/// one, so no edit touches the cursor's own position and an editor applying
|
||||
/// them leaves the cursor on the body line. The new line being the file's last
|
||||
/// is the one case with nowhere else to put it, and there the two are one
|
||||
/// edit.
|
||||
fn edits(doc: &Document, line: &NewLine, body: &str, end_indent: &str) -> Vec<TextEdit> {
|
||||
let positions = doc.positions();
|
||||
let start = positions.position(line.range.start);
|
||||
let indent = Range { start, end: positions.position(line.content) };
|
||||
let end_line = format!("{end_indent}end");
|
||||
if line.range.end as usize >= doc.text.len() {
|
||||
let new_text = format!("{body}{}{end_line}", line.eol);
|
||||
return vec![TextEdit {
|
||||
range: Range { start, end: positions.position(line.range.end) },
|
||||
new_text,
|
||||
}];
|
||||
}
|
||||
let mut edits = Vec::new();
|
||||
if doc.text.get(line.range.start as usize..line.content as usize) != Some(body) {
|
||||
edits.push(TextEdit { range: indent, new_text: body.to_string() });
|
||||
}
|
||||
let next = positions.position(line.range.end + 1);
|
||||
edits.push(TextEdit {
|
||||
range: Range { start: next, end: next },
|
||||
new_text: format!("{end_line}{}", line.eol),
|
||||
});
|
||||
edits
|
||||
}
|
||||
|
||||
/// The 1-based line a token starts on.
|
||||
fn line_of(doc: &Document, token: &Token) -> u32 {
|
||||
doc.line_index.line_col(token.span.start).0
|
||||
}
|
||||
|
||||
/// The leading whitespace of the line holding `offset`.
|
||||
fn line_indent(doc: &Document, offset: u32) -> String {
|
||||
let line = doc.line_index.line_col(offset).0;
|
||||
let Some(range) = doc.line_index.line_range(line) else { return String::new() };
|
||||
let text = doc.text.get(range.start as usize..range.end as usize).unwrap_or("");
|
||||
text[..text.len() - text.trim_start_matches([' ', '\t']).len()].to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::on_type::{on_type_formatting, NEWLINE};
|
||||
use crate::state::Workspace;
|
||||
use lsp_types::Uri;
|
||||
use std::str::FromStr;
|
||||
use vlog_formatter::Config;
|
||||
|
||||
/// The buffer after the newline answer for a `\n` that opened `line`
|
||||
/// (0-based), with `lucisv.autoEnd` as given — and the edits themselves.
|
||||
fn typed(text: &str, line: u32, auto_end: bool) -> (String, Vec<TextEdit>) {
|
||||
let uri = Uri::from_str("file:///rtl/m.sv").expect("uri");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let at = Position { line, character: 0 };
|
||||
let config = Config { indent_width: 2, ..Config::default() };
|
||||
let edits = on_type_formatting(doc, at, NEWLINE, &config, auto_end);
|
||||
(apply(doc, &edits), edits)
|
||||
}
|
||||
|
||||
/// `edits` applied to the buffer, last first so the offsets stay true.
|
||||
fn apply(doc: &Document, edits: &[TextEdit]) -> String {
|
||||
let mut spans: Vec<(usize, usize, &str)> = edits
|
||||
.iter()
|
||||
.map(|edit| {
|
||||
let start = doc.positions().offset(edit.range.start) as usize;
|
||||
let end = doc.positions().offset(edit.range.end) as usize;
|
||||
(start, end, edit.new_text.as_str())
|
||||
})
|
||||
.collect();
|
||||
spans.sort_by_key(|(start, _, _)| std::cmp::Reverse(*start));
|
||||
let mut text = doc.text.to_string();
|
||||
for (start, end, new_text) in spans {
|
||||
text.replace_range(start..end, new_text);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_newline_after_an_unclosed_begin_writes_the_end_under_its_statement() {
|
||||
let text = "module m;\n always_ff @(posedge clk) begin\n\nendmodule\n";
|
||||
let (after, edits) = typed(text, 2, true);
|
||||
assert_eq!(after, "module m;\n always_ff @(posedge clk) begin\n \n end\nendmodule\n");
|
||||
// Nothing lands on the cursor's own position: the `end` goes in at the
|
||||
// start of the line after it, so the cursor stays on the body line.
|
||||
assert!(edits
|
||||
.iter()
|
||||
.all(|edit| edit.range.start.line != 2 || edit.range.end.character == 0));
|
||||
assert_eq!(
|
||||
edits.last().map(|edit| edit.range.start),
|
||||
Some(Position { line: 3, character: 0 })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_begin_typed_inside_a_balanced_block_still_gets_its_end() {
|
||||
// The new `if`'s `begin` steals the `always_comb` block's `end` in the
|
||||
// stack matcher, and the *outer* `begin` is what comes out unclosed.
|
||||
let text =
|
||||
"module m;\n always_comb begin\n x = 1;\n if (x) begin\n\n end\nendmodule\n";
|
||||
let (after, _) = typed(text, 4, true);
|
||||
assert_eq!(
|
||||
after,
|
||||
"module m;\n always_comb begin\n x = 1;\n if (x) begin\n \n end\n end\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_begin_whose_blocks_already_balance_gets_no_end() {
|
||||
let text = "module m;\n always_comb begin\n\n end\nendmodule\n";
|
||||
let (after, edits) = typed(text, 2, true);
|
||||
assert_eq!(after, "module m;\n always_comb begin\n \n end\nendmodule\n");
|
||||
assert_eq!(edits.len(), 1, "the indentation alone: {edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_inner_block_with_an_outer_end_missing_gets_no_second_end() {
|
||||
// The outer `begin` is the unclosed one, but this `begin` already has
|
||||
// its `end`, at exactly the indentation the answer would write.
|
||||
let text = "module m;\n always_comb begin\n if (x) begin\n\n end\nendmodule\n";
|
||||
let (_, edits) = typed(text, 3, true);
|
||||
assert!(edits.iter().all(|edit| !edit.new_text.contains("end")), "{edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_labelled_begin_and_a_trailing_comment_both_count() {
|
||||
let text = "module m;\n initial begin : boot // first\n\nendmodule\n";
|
||||
let (after, _) = typed(text, 2, true);
|
||||
assert_eq!(after, "module m;\n initial begin : boot // first\n \n end\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_lines_up_with_the_first_line_of_a_wrapped_header() {
|
||||
let text = "module m;\n always_comb\n if (a &&\n b) begin\n\nendmodule\n";
|
||||
let (after, _) = typed(text, 4, true);
|
||||
assert!(after.contains(" b) begin\n \n end\nendmodule"), "{after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_else_branch_ends_under_the_line_that_holds_the_else() {
|
||||
let text = "module m;\n always_comb begin\n if (a) begin\n x = 1;\n end else begin\n\n end\nendmodule\n";
|
||||
let (after, _) = typed(text, 5, true);
|
||||
assert!(after.contains(" end else begin\n \n end\n end\n"), "{after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_case_item_ends_under_the_item() {
|
||||
let text = "module m;\n always_comb begin\n case (s)\n 2'b01: begin\n\n endcase\n end\nendmodule\n";
|
||||
let (after, _) = typed(text, 4, true);
|
||||
assert!(after.contains(" 2'b01: begin\n \n end\n endcase"), "{after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tabs_stay_tabs() {
|
||||
let text = "module m;\n\talways_comb begin\n\nendmodule\n";
|
||||
let (after, _) = typed(text, 2, true);
|
||||
assert_eq!(after, "module m;\n\talways_comb begin\n\t\t\n\tend\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crlf_file_gets_a_crlf_end_line() {
|
||||
let text = "module m;\r\n initial begin\r\n\r\nendmodule\r\n";
|
||||
let (after, _) = typed(text, 2, true);
|
||||
assert_eq!(after, "module m;\r\n initial begin\r\n \r\n end\r\nendmodule\r\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_last_line_of_the_file_gets_one_edit() {
|
||||
let text = "module m;\n initial begin\n";
|
||||
let (after, edits) = typed(text, 2, true);
|
||||
assert_eq!(after, "module m;\n initial begin\n \n end");
|
||||
assert_eq!(edits.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_but_the_indent_when_the_setting_is_off() {
|
||||
let text = "module m;\n always_ff @(posedge clk) begin\n\nendmodule\n";
|
||||
let (after, _) = typed(text, 2, false);
|
||||
assert_eq!(after, "module m;\n always_ff @(posedge clk) begin\n \nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_end_where_the_line_above_does_not_end_in_begin() {
|
||||
for text in [
|
||||
"module m;\n initial begin x = 1;\n\nendmodule\n",
|
||||
"module m;\n initial // begin\n\nendmodule\n",
|
||||
"module m;\n initial $display(\"begin\");\n\nendmodule\n",
|
||||
"module m;\n initial fork\n\nendmodule\n",
|
||||
] {
|
||||
let (_, edits) = typed(text, 2, true);
|
||||
assert!(edits.iter().all(|edit| !edit.new_text.contains("end")), "{text:?}: {edits:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_end_when_enter_carried_text_down_to_the_new_line() {
|
||||
let text = "module m;\n initial begin\n x = 1;\nendmodule\n";
|
||||
let (_, edits) = typed(text, 2, true);
|
||||
assert!(edits.iter().all(|edit| !edit.new_text.contains("end")), "{edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_begin_two_lines_up_is_not_the_line_above() {
|
||||
let text = "module m;\n initial begin\n\n\nendmodule\n";
|
||||
let (_, edits) = typed(text, 3, true);
|
||||
assert!(edits.iter().all(|edit| !edit.new_text.contains("end")), "{edits:?}");
|
||||
}
|
||||
|
||||
/// QA (2026-11-17): buffers just after an Enter on `line`, each of which
|
||||
/// gets an `end`.
|
||||
const QA_ARMED: &[(&str, u32)] = &[
|
||||
("module m;\n always_comb begin\n x = 1;\n if (x) begin\n\n end\nendmodule\n", 4),
|
||||
("module m;\n generate\n if (P) begin : g\n\n endgenerate\nendmodule\n", 3),
|
||||
("module m;\n initial fork\n begin\n\n join\nendmodule\n", 3),
|
||||
("module m;\n initial `MY_MACRO begin\n\nendmodule\n", 2),
|
||||
("module m;\n initial #5 begin\n\nendmodule\n", 2),
|
||||
("module m;\n always @* begin\n\nendmodule\n", 2),
|
||||
("class c;\n function void f();\n if (a) begin\n\n endfunction\nendclass\n", 3),
|
||||
("module m;\r\n always_comb begin\r\n\r\nendmodule\r\n", 2),
|
||||
("module m;\n initial begin\n", 2),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn qa_asking_again_after_the_answer_is_applied_adds_no_second_end() {
|
||||
for &(text, line) in QA_ARMED {
|
||||
let (after, edits) = typed(text, line, true);
|
||||
assert!(edits.iter().any(|edit| edit.new_text.contains("end")), "{text:?}: {edits:?}");
|
||||
let (again, second) = typed(&after, line, true);
|
||||
assert!(
|
||||
second.iter().all(|edit| !edit.new_text.contains("end")),
|
||||
"{after:?}: {second:?}"
|
||||
);
|
||||
assert_eq!(again, after, "the second answer changes nothing: {text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_declined_newline_is_exactly_the_plain_indent_answer() {
|
||||
for (text, line) in [
|
||||
("module m;\n always_comb begin\n\n end\nendmodule\n", 2),
|
||||
("`define OPEN begin\n\nmodule m;\nendmodule\n", 1),
|
||||
("`define BLK(x) if (x) begin \\\n\nmodule m;\nendmodule\n", 1),
|
||||
("module m;\n initial $display(\"begin\n\nendmodule\n", 2),
|
||||
("module m;\n`ifdef A\n always_ff @(posedge clk) begin\n`else\n always_ff @(posedge clk or negedge rst_n) begin\n\n`endif\n x <= 1;\n end\nendmodule\n", 5),
|
||||
("module m;\n always_comb begin\n\nend\nendmodule\n", 2),
|
||||
("module m;\n initial begin end\n\nendmodule\n", 2),
|
||||
("module m;\n wire \\begin \n\nendmodule\n", 2),
|
||||
("module m;\n initial begin\nfoo = 1;\nendmodule\n", 2),
|
||||
] {
|
||||
let (_, with) = typed(text, line, true);
|
||||
let (_, without) = typed(text, line, false);
|
||||
assert_eq!(with, without, "{text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether any edit writes an `end`.
|
||||
fn wrote_an_end(edits: &[TextEdit]) -> bool {
|
||||
edits.iter().any(|edit| edit.new_text.contains("end"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gnu_style_begin_already_closed_under_itself_gets_no_end() {
|
||||
// Another `begin` above is unclosed (mid-edit), and this block's `end`
|
||||
// sits under the `begin`'s own line rather than under the `if`.
|
||||
let text = "module m;\n initial begin\n always_comb\n if (x)\n begin\n\n y = 1;\n end\nendmodule\n";
|
||||
let (_, edits) = typed(text, 5, true);
|
||||
assert!(!wrote_an_end(&edits), "{edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_ifdef_branches_sharing_one_end_get_no_second_end() {
|
||||
// QA finding 1: two `ifdef` branches each open the `always` block and
|
||||
// one `end` after the `endif` closes whichever was compiled.
|
||||
let shared = "module m;\n`ifdef A\n always @(posedge clk) begin\n`else\n always @(posedge clk or negedge rst) begin\n`endif\n if (x)\n begin\n\n y <= 1;\n end\n end\nendmodule\n";
|
||||
let (_, edits) = typed(shared, 8, true);
|
||||
assert!(!wrote_an_end(&edits), "after the GNU-style begin: {edits:?}");
|
||||
// The cursor after the *first* branch's `begin`: that block's `end`
|
||||
// is the shared one after the `endif`, so writing one would be wrong.
|
||||
let first = "module m;\n`ifdef A\n always @(posedge clk) begin\n\n`else\n always @(posedge clk or negedge rst) begin\n`endif\n y <= 1;\n end\nendmodule\n";
|
||||
let (_, edits) = typed(first, 3, true);
|
||||
assert!(!wrote_an_end(&edits), "inside the first branch: {edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ifdef_with_no_else_still_arms_the_answer() {
|
||||
let text = "module m;\n`ifdef A\n initial begin\n\n`endif\nendmodule\n";
|
||||
let (_, edits) = typed(text, 3, true);
|
||||
assert!(wrote_an_end(&edits), "{edits:?}");
|
||||
}
|
||||
}
|
||||
@@ -568,7 +568,8 @@ impl Server {
|
||||
decode(request).and_then(|p: InlineCompletionParams| {
|
||||
let at = p.text_document_position;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
inline::inline_completions(&self.workspace, &uri, position)
|
||||
let selected = p.context.selected_completion_info.as_ref();
|
||||
inline::inline_completions_in_context(&self.workspace, &uri, position, selected)
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -98,7 +98,9 @@ impl Server {
|
||||
return to_value(Vec::<lsp_types::TextEdit>::new());
|
||||
};
|
||||
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
||||
let edits = on_type::on_type_formatting(doc, at.position, ¶ms.ch, &settings.config);
|
||||
let auto_end = self.workspace.client_settings().auto_end.unwrap_or(true);
|
||||
let edits =
|
||||
on_type::on_type_formatting(doc, at.position, ¶ms.ch, &settings.config, auto_end);
|
||||
to_value(edits)
|
||||
}
|
||||
|
||||
|
||||
@@ -121,6 +121,14 @@ pub struct ClientSettings {
|
||||
/// followed by a space. Unset means on, the same way `inline_templates`
|
||||
/// does — see `docs/features/inline-instantiation/README.md`.
|
||||
pub inline_instantiation: Option<bool>,
|
||||
/// `lucisv.inlineKeywords`: whether a typed proper prefix of a keyword
|
||||
/// grows the rest of it as ghost text. Unset means on, independent of
|
||||
/// `inline_templates` — see `docs/features/completion-ux/README.md`.
|
||||
pub inline_keywords: Option<bool>,
|
||||
/// `lucisv.autoEnd`: whether a newline typed after `begin` also writes
|
||||
/// the `end` the block still owes. Unset means on — see
|
||||
/// `docs/features/completion-ux/README.md`.
|
||||
pub auto_end: Option<bool>,
|
||||
/// `lucisv.formatOnSave`: whether `textDocument/willSaveWaitUntil` formats
|
||||
/// the buffer. A plain `bool` rather than an `Option`, because unset and
|
||||
/// off are the same answer here: an editor with a format-on-save of its
|
||||
@@ -246,6 +254,8 @@ impl Default for ClientSettings {
|
||||
uvm_utils_indent: None,
|
||||
inline_templates: None,
|
||||
inline_instantiation: None,
|
||||
inline_keywords: None,
|
||||
auto_end: None,
|
||||
format_on_save: false,
|
||||
max_file_size: DEFAULT_MAX_FILE_SIZE,
|
||||
log_files: true,
|
||||
@@ -345,6 +355,8 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
|
||||
uvm_utils_indent: flag(lucisv.get("format").and_then(|f| f.get("uvmUtilsIndent"))),
|
||||
inline_templates: flag(lucisv.get("inlineTemplates")),
|
||||
inline_instantiation: flag(lucisv.get("inlineInstantiation")),
|
||||
inline_keywords: flag(lucisv.get("inlineKeywords")),
|
||||
auto_end: flag(lucisv.get("autoEnd")),
|
||||
// Anything that is not `true` leaves the hook declining, wrong-typed
|
||||
// values included: the safe direction for a setting that rewrites the
|
||||
// user's buffer on every save is the one that does nothing.
|
||||
@@ -623,6 +635,8 @@ mod tests {
|
||||
"filelist": "",
|
||||
"inlineTemplates": true,
|
||||
"inlineInstantiation": true,
|
||||
"inlineKeywords": true,
|
||||
"autoEnd": true,
|
||||
"formatOnSave": false,
|
||||
"index": {
|
||||
"maxFileSize": 1048576, "logFiles": true,
|
||||
@@ -838,7 +852,13 @@ mod tests {
|
||||
// The two ghost-text settings are the ones whose absence resolves to
|
||||
// `true` here, so a `false` default in the manifest would make the
|
||||
// settings UI and the server disagree about a feature being on.
|
||||
for ghost in ["lucisv.inlineTemplates", "lucisv.inlineInstantiation"] {
|
||||
// `autoEnd` is the same kind of switch: absent means on.
|
||||
for ghost in [
|
||||
"lucisv.inlineTemplates",
|
||||
"lucisv.inlineInstantiation",
|
||||
"lucisv.inlineKeywords",
|
||||
"lucisv.autoEnd",
|
||||
] {
|
||||
assert_eq!(properties[ghost]["default"], json!(true), "{ghost}");
|
||||
assert_eq!(properties[ghost]["type"], json!("boolean"), "{ghost}");
|
||||
}
|
||||
@@ -1103,6 +1123,8 @@ mod tests {
|
||||
ClientSettings {
|
||||
inline_templates: Some(true),
|
||||
inline_instantiation: Some(true),
|
||||
inline_keywords: Some(true),
|
||||
auto_end: Some(true),
|
||||
..Default::default()
|
||||
},
|
||||
"the only difference from silence must be the settings whose \
|
||||
@@ -1141,6 +1163,24 @@ mod tests {
|
||||
assert_eq!(found.inline_templates, None, "the templates setting is untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_keywords_and_auto_end_are_booleans_and_nothing_else() {
|
||||
let found = settings(json!({ "lucisv": { "inlineKeywords": false, "autoEnd": false } }));
|
||||
assert_eq!((found.inline_keywords, found.auto_end), (Some(false), Some(false)));
|
||||
let found = settings(json!({ "lucisv": { "inlineKeywords": true, "autoEnd": true } }));
|
||||
assert_eq!((found.inline_keywords, found.auto_end), (Some(true), Some(true)));
|
||||
// Absence is not `false`: both are on unless a client says no.
|
||||
let found = settings(json!({ "lucisv": {} }));
|
||||
assert_eq!((found.inline_keywords, found.auto_end), (None, None));
|
||||
for bad in [json!("false"), json!(0), json!(null), json!([false])] {
|
||||
let found = settings(json!({ "lucisv": { "inlineKeywords": bad, "autoEnd": bad } }));
|
||||
assert_eq!((found.inline_keywords, found.auto_end), (None, None), "{bad} ignored");
|
||||
}
|
||||
// Independent of the template ghosts: one off leaves the other alone.
|
||||
let found = settings(json!({ "lucisv": { "inlineKeywords": false } }));
|
||||
assert_eq!(found.inline_templates, None, "the templates setting is untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_on_save_is_off_until_a_client_asks_for_it() {
|
||||
assert!(settings(json!({ "lucisv": { "formatOnSave": true } })).format_on_save);
|
||||
|
||||
@@ -115,6 +115,11 @@ impl Template {
|
||||
}
|
||||
|
||||
/// Every template offered in `dialect`, the shared ones first.
|
||||
///
|
||||
/// The order is the popup's order among templates: the tier writes each one's
|
||||
/// position here into its `sortText` (`completion-ux`, 2026-11-17), so two
|
||||
/// templates reached by the same prefix show in registry order rather than by
|
||||
/// label.
|
||||
pub fn for_dialect(dialect: Dialect) -> impl Iterator<Item = &'static Template> {
|
||||
let dialect_only = match dialect {
|
||||
Dialect::SystemVerilog => SYSTEMVERILOG,
|
||||
@@ -198,13 +203,8 @@ const SYSTEMVERILOG: &[Template] = &[
|
||||
detail: "for loop with a local loop variable",
|
||||
body: &[(0, "for (int ${1:i} = 0; $1 < ${2:N}; $1++) begin"), (1, "$0"), (0, "end")],
|
||||
},
|
||||
Template {
|
||||
label: "always_ff @(posedge clk)",
|
||||
prefix: "always_ff",
|
||||
gate: Gate::Item,
|
||||
detail: "synchronous block, no reset",
|
||||
body: &[(0, "always_ff @(posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
|
||||
},
|
||||
// With-reset before clock-only (TODO §68.1): a flop with an async reset is
|
||||
// the commoner one to write, and the registry order is the popup order.
|
||||
Template {
|
||||
label: "always_ff with reset",
|
||||
prefix: "always_ff",
|
||||
@@ -220,6 +220,13 @@ const SYSTEMVERILOG: &[Template] = &[
|
||||
(0, "end"),
|
||||
],
|
||||
},
|
||||
Template {
|
||||
label: "always_ff @(posedge clk)",
|
||||
prefix: "always_ff",
|
||||
gate: Gate::Item,
|
||||
detail: "synchronous block, no reset",
|
||||
body: &[(0, "always_ff @(posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
|
||||
},
|
||||
Template {
|
||||
label: "always_comb begin/end",
|
||||
prefix: "always_comb",
|
||||
@@ -267,13 +274,7 @@ const VERILOG: &[Template] = &[
|
||||
detail: "for loop over an existing variable",
|
||||
body: &[(0, "for (${1:i} = 0; $1 < ${2:N}; $1 = $1 + 1) begin"), (1, "$0"), (0, "end")],
|
||||
},
|
||||
Template {
|
||||
label: "always @(posedge clk)",
|
||||
prefix: "always",
|
||||
gate: Gate::Item,
|
||||
detail: "synchronous block, no reset",
|
||||
body: &[(0, "always @(posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
|
||||
},
|
||||
// With-reset first, as in the SystemVerilog list above.
|
||||
Template {
|
||||
label: "always @(posedge clk or negedge rst_n)",
|
||||
prefix: "always",
|
||||
@@ -289,6 +290,13 @@ const VERILOG: &[Template] = &[
|
||||
(0, "end"),
|
||||
],
|
||||
},
|
||||
Template {
|
||||
label: "always @(posedge clk)",
|
||||
prefix: "always",
|
||||
gate: Gate::Item,
|
||||
detail: "synchronous block, no reset",
|
||||
body: &[(0, "always @(posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
|
||||
},
|
||||
Template {
|
||||
label: "always @(*)",
|
||||
prefix: "always",
|
||||
|
||||
@@ -1091,6 +1091,64 @@ fn typing_a_newline_and_a_semicolon_round_trips_over_the_real_binary() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `begin` + Enter writes the `end` over the wire, and a pushed
|
||||
/// `lucisv.autoEnd: false` takes it back to the plain indent answer
|
||||
/// (`docs/features/completion-ux`).
|
||||
#[test]
|
||||
fn a_newline_after_begin_writes_the_end_unless_auto_end_is_off() {
|
||||
let dir = temp_dir("ontype_end");
|
||||
let file = dir.join("m.sv");
|
||||
let text = "module m;\n always_ff @(posedge clk) begin\n\nendmodule\n";
|
||||
std::fs::write(&file, text).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
let on_type = |id: u32| {
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/onTypeFormatting","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":0}},"ch":"\n","options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
|
||||
))
|
||||
};
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(text).expect("json")
|
||||
)),
|
||||
on_type(2),
|
||||
frame(
|
||||
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"autoEnd":false}}}}"#,
|
||||
),
|
||||
on_type(3),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&session);
|
||||
let edits = |id: u32| {
|
||||
let response = messages.iter().find(|m| m["id"] == id).expect("a response");
|
||||
response["result"].as_array().expect("an array of edits").clone()
|
||||
};
|
||||
|
||||
let with_end = edits(2);
|
||||
assert_eq!(with_end.len(), 2, "{with_end:#?}");
|
||||
assert_eq!(with_end[0]["newText"], " ", "the body line's indent");
|
||||
assert_eq!(with_end[1]["newText"], " end\n", "the `end` under its `always_ff`");
|
||||
assert_eq!(
|
||||
with_end[1]["range"]["start"],
|
||||
serde_json::json!({ "line": 3, "character": 0 }),
|
||||
"inserted at the start of the line after the cursor's"
|
||||
);
|
||||
|
||||
let without = edits(3);
|
||||
assert_eq!(without.len(), 1, "autoEnd off: the indent alone: {without:#?}");
|
||||
assert_eq!(without[0]["newText"], " ");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pushed_exclude_rebuilds_the_index_mid_session() {
|
||||
// The one link a unit test cannot check: that the notification handler
|
||||
@@ -2251,14 +2309,18 @@ fn inline_templates_round_trip_over_the_wire() {
|
||||
assert_eq!(item["insertText"]["value"], "${1:cond}) begin\n\t$0\nend");
|
||||
assert_eq!(item["range"]["start"], item["range"]["end"], "an insertion, not a replacement");
|
||||
|
||||
// `always @(` is the one trigger with a list: the clocked block first, the
|
||||
// combinational one second, both at the same empty range.
|
||||
let two = items(5);
|
||||
let two = two["items"].as_array().expect("a list");
|
||||
assert_eq!(two.len(), 2, "{two:#?}");
|
||||
assert_eq!(two[0]["insertText"]["value"], "posedge ${1:clk}) begin\n\t$0\nend");
|
||||
assert_eq!(two[1]["insertText"]["value"], "*) begin\n\t$0\nend");
|
||||
assert_eq!(two[0]["range"], two[1]["range"], "both insert at the cursor");
|
||||
// `always @(` is a trigger with a list: clock and reset first, clock only
|
||||
// second, the combinational block third, all at the same empty range.
|
||||
let three = items(5);
|
||||
let three = three["items"].as_array().expect("a list");
|
||||
assert_eq!(three.len(), 3, "{three:#?}");
|
||||
assert_eq!(
|
||||
three[0]["insertText"]["value"],
|
||||
"posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend"
|
||||
);
|
||||
assert_eq!(three[1]["insertText"]["value"], "posedge ${1:clk}) begin\n\t$0\nend");
|
||||
assert_eq!(three[2]["insertText"]["value"], "*) begin\n\t$0\nend");
|
||||
assert_eq!(three[0]["range"], three[2]["range"], "all insert at the cursor");
|
||||
|
||||
assert_eq!(items(4), serde_json::Value::Null, "nowhere near a trigger");
|
||||
|
||||
@@ -2428,14 +2490,16 @@ fn keyword_and_project_completion_round_trip_over_the_wire() {
|
||||
assert_eq!(local["kind"], 6, "CompletionItemKind.Variable");
|
||||
assert!(local["sortText"].as_str().expect("sortText").starts_with('1'), "{local:#?}");
|
||||
|
||||
// `4`, not `2`: `completion-ux` (2026-11-17) put this file's own
|
||||
// declarations (`2`) and words (`3`) ahead of what other files declare.
|
||||
let macro_name = labelled("WIDGET_MACRO").expect("a `define name");
|
||||
assert!(macro_name["sortText"].as_str().expect("sortText").starts_with('2'));
|
||||
assert!(macro_name["sortText"].as_str().expect("sortText").starts_with('4'));
|
||||
|
||||
let elsewhere = labelled("widget_elsewhere").expect("a word used in the project");
|
||||
assert_eq!(elsewhere["kind"], 1, "CompletionItemKind.Text");
|
||||
// `5`, not `4`: M6 inserted the template tier above the keywords, which
|
||||
// pushed the keyword and word tiers' digits down by one.
|
||||
assert!(elsewhere["sortText"].as_str().expect("sortText").starts_with('5'));
|
||||
// `7`: M6 inserted the template tier above the keywords, and
|
||||
// `completion-ux` the two current-file tiers above the index.
|
||||
assert!(elsewhere["sortText"].as_str().expect("sortText").starts_with('7'));
|
||||
|
||||
assert!(
|
||||
!items.iter().any(|item| item["sortText"].as_str().is_some_and(|s| s.starts_with('0'))),
|
||||
@@ -2611,12 +2675,12 @@ fn a_template_completion_round_trips_over_the_wire() {
|
||||
assert_eq!(template["textEdit"]["range"]["start"]["line"], 2);
|
||||
assert_eq!(template["textEdit"]["range"]["start"]["character"], 4);
|
||||
assert_eq!(template["textEdit"]["range"]["end"]["character"], 6);
|
||||
assert!(template["sortText"].as_str().expect("sortText").starts_with('3'));
|
||||
assert!(template["sortText"].as_str().expect("sortText").starts_with('5'));
|
||||
|
||||
// The keyword survives beside it, one tier down.
|
||||
let keyword = labelled(items, "if").expect("the keyword");
|
||||
assert_eq!(keyword["kind"], 14, "CompletionItemKind.Keyword");
|
||||
assert!(keyword["sortText"].as_str().expect("sortText").starts_with('4'));
|
||||
assert!(keyword["sortText"].as_str().expect("sortText").starts_with('6'));
|
||||
|
||||
// A `.v` buffer is offered Verilog's `always`, never `always_ff`.
|
||||
let verilog = messages.iter().find(|m| m["id"] == 3).expect("completion response");
|
||||
@@ -7298,8 +7362,16 @@ fn a_connection_list_completes_ports_over_the_wire() {
|
||||
assert_eq!(edit["range"]["start"], edit["range"]["end"], "an empty range at the cursor");
|
||||
}
|
||||
|
||||
// A port already connected is not offered again.
|
||||
assert_eq!(labels(3), vec!["data", "ready"]);
|
||||
// A port already connected is still offered, after the others and
|
||||
// marked (`completion-ux`, 2026-11-17 — it used to be dropped).
|
||||
assert_eq!(labels(3), vec!["clk", "data", "ready"]);
|
||||
let partly_items = response(3)["result"]["items"].as_array().expect("a list");
|
||||
let clk = partly_items.iter().find(|i| i["label"] == "clk").expect("clk");
|
||||
assert!(clk["sortText"].as_str().is_some_and(|s| s.starts_with('1')), "{clk:#?}");
|
||||
assert_eq!(clk["labelDetails"]["description"], "connected");
|
||||
let data = partly_items.iter().find(|i| i["label"] == "data").expect("data");
|
||||
assert!(data["sortText"].as_str().is_some_and(|s| s.starts_with('0')), "{data:#?}");
|
||||
assert!(data.get("labelDetails").is_none(), "{data:#?}");
|
||||
|
||||
// And `#(.` lists the parameters instead.
|
||||
assert_eq!(labels(4), vec!["WIRE_W"]);
|
||||
@@ -7307,6 +7379,94 @@ fn a_connection_list_completes_ports_over_the_wire() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `completion-ux` over the wire: a port item, asked by a client that reads
|
||||
/// snippets, writes `.name($1)` — pre-filled where the instantiating module
|
||||
/// has a same-named signal — and a typed keyword prefix grows a keyword
|
||||
/// ghost, following the popup's selected entry when one is sent.
|
||||
#[test]
|
||||
fn port_snippets_and_keyword_ghosts_round_trip_over_the_wire() {
|
||||
let dir = temp_dir("completionux");
|
||||
std::fs::write(
|
||||
dir.join("ux_sub.sv"),
|
||||
"module ux_sub (\n input logic clk,\n input logic data\n);\nendmodule\n",
|
||||
)
|
||||
.expect("write");
|
||||
let text = "module ux_top;\n logic clk;\n ux_sub u_sub (\n .\n );\n alw\nendmodule\n";
|
||||
let top = dir.join("ux_top.sv");
|
||||
std::fs::write(&top, text).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", top.display());
|
||||
let inline = |id: u32, selected: &str| {
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/inlineCompletion","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":5,"character":5}},"context":{{"triggerKind":2{selected}}}}}}}"#
|
||||
))
|
||||
};
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"completion":{{"completionItem":{{"snippetSupport":true}}}}}}}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(text).expect("json")
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":3,"character":5}},"context":{{"triggerKind":2,"triggerCharacter":"."}}}}}}"#
|
||||
)),
|
||||
inline(3, ""),
|
||||
inline(
|
||||
4,
|
||||
r#","selectedCompletionInfo":{"range":{"start":{"line":5,"character":2},"end":{"line":5,"character":5}},"text":"always_comb"}"#,
|
||||
),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&session);
|
||||
let result = |id: u32| {
|
||||
messages
|
||||
.iter()
|
||||
.find(|m| m["id"] == id)
|
||||
.unwrap_or_else(|| panic!("no response {id} in {messages:#?}"))["result"]
|
||||
.clone()
|
||||
};
|
||||
|
||||
let ports = result(2);
|
||||
let ports = ports["items"].as_array().expect("a list");
|
||||
let port = |name: &str| ports.iter().find(|i| i["label"] == name).expect("a port").clone();
|
||||
assert_eq!(port("clk")["textEdit"]["newText"], "clk(${1:clk})", "pre-filled from `logic clk`");
|
||||
assert_eq!(port("data")["textEdit"]["newText"], "data(${1})");
|
||||
assert_eq!(port("data")["insertTextFormat"], 2, "InsertTextFormat.Snippet");
|
||||
|
||||
let cursor = serde_json::json!({ "line": 5, "character": 5 });
|
||||
assert_eq!(
|
||||
result(3),
|
||||
serde_json::json!({
|
||||
"items": [{
|
||||
"insertText": { "kind": "snippet", "value": "ays_ff" },
|
||||
"range": { "start": cursor, "end": cursor }
|
||||
}]
|
||||
}),
|
||||
"the rest of the keyword, inserted at the cursor"
|
||||
);
|
||||
assert_eq!(
|
||||
result(4),
|
||||
serde_json::json!({
|
||||
"items": [{
|
||||
"insertText": { "kind": "snippet", "value": "always_comb" },
|
||||
"range": {
|
||||
"start": { "line": 5, "character": 2 },
|
||||
"end": { "line": 5, "character": 5 }
|
||||
}
|
||||
}]
|
||||
}),
|
||||
"the popup's selection, over the popup's range"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// constraint-bodies (TODO.md §20)
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,448 @@
|
||||
# completion-ux
|
||||
|
||||
## Goal
|
||||
|
||||
Completion that keeps up with typing (TODO §68.1, owner's order 2026-11-17).
|
||||
Five changes to the editing loop the VS Code extension drives, all served by
|
||||
`lucisv-server` so other LSP clients get them too:
|
||||
|
||||
1. **`begin` + Enter writes the `end`.** The newline on-type answer, when the
|
||||
line above ends in `begin` / `begin : label` and the block still owes an
|
||||
`end`, also writes `end` on the line after the new one, at the owning
|
||||
statement's indentation; the cursor stays on the indented body line. The
|
||||
extension sends that request itself when `editor.formatOnType` is off.
|
||||
2. **Clock and reset in the `always` templates.** `always_ff @(` and
|
||||
`always @(` ghost `posedge ${1:clk} or negedge ${2:rst_n}) begin … end`
|
||||
first; the clock-only form stays as the second choice, in the ghost and in
|
||||
the popup.
|
||||
3. **Current-file names rank first** in the popup: what this buffer declares
|
||||
(any scope), then the words it uses, ahead of other files' names, the
|
||||
templates and the keywords.
|
||||
4. **Keyword ghosts.** A typed proper prefix of a keyword shows the rest as
|
||||
grey inline text, following the popup's selected item while the popup is
|
||||
open.
|
||||
5. **Port items.** After the `.` of a connection, unconnected ports first,
|
||||
connected ones after them marked `connected`; accepting one writes
|
||||
`.name($1)` with the cursor inside the parentheses, pre-filled with a
|
||||
same-named signal when the instantiating scope has one.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Auto-`end` — which `begin` owes an `end`.** `pairs::analyze` is a stack
|
||||
matcher, so a `begin` typed inside a balanced block steals that block's
|
||||
`end` and the *outer* `begin` comes out unmatched. The rule
|
||||
(`on_type/auto_end.rs::owes_an_end`): no `end` if this `begin` is matched by
|
||||
an `end` that is first on its line at exactly the indentation the answer
|
||||
would write; otherwise an `end` iff any `begin` at or before this one is in
|
||||
`unmatched_open`. Fix round: the `begin` also counts as closed when its
|
||||
matched `end` starts its line at the `begin`'s **own** line's indentation
|
||||
(GNU layout, `begin` on its own line), and an unmatched `begin` inside a
|
||||
`` `ifdef ``/`` `ifndef `` region that has an `` `else ``/`` `elsif ``
|
||||
arms nothing. Consequence: an unrelated unclosed `begin` earlier in the
|
||||
file still arms it (accepted heuristic, lead's ruling); a hand-mis-indented
|
||||
`end` belonging to an outer block at either column disarms it.
|
||||
- **Auto-`end` and `` `ifdef `` branches (QA finding 1).** Two branches that
|
||||
each open the same block (`` `ifdef A always … begin `else always … begin
|
||||
`endif `` and one shared `end`) are complete code that the stack matcher
|
||||
reads as one unmatched `begin`. What is right after the *first* branch's
|
||||
`begin` is **no `end`**: the block's `end` is the shared one after the
|
||||
`` `endif ``, and a second would break the other branch. The cheap rule —
|
||||
an unmatched `begin` inside a branched conditional region never arms the
|
||||
answer — gets that right. Known limit it buys: a genuinely new `begin`
|
||||
typed inside such a region whose only unmatched `begin` is itself gets no
|
||||
`end` (the plain indent answer instead). The region scan is by directive
|
||||
word over the token stream; a region never closed runs to end of buffer.
|
||||
- **Auto-`end` — the owner line.** Read backwards from the `begin` over a
|
||||
parenthesised header, `@`/`#` and its operand, one header keyword (`if`,
|
||||
`for`, `foreach`, `while`, `repeat`, `forever`, the `always` family,
|
||||
`initial`, `final`) and the qualifiers in front of it (`else`, `unique`,
|
||||
`unique0`, `priority`). Anything else ends the walk. The `end` takes that
|
||||
line's leading whitespace *as written* (tabs stay tabs). An unmatched `)`
|
||||
leaves the `begin`'s own line as the answer.
|
||||
- **Auto-`end` — the body line.** The nesting model's level (spaces, as the
|
||||
plain newline answer) when it lies deeper than the `end`; else the `end`'s
|
||||
indent plus one `lucisv.indent`-width step; a tab-indented `end` gets one
|
||||
more tab.
|
||||
- **Auto-`end` — only on a blank new line.** Enter pressed mid-line carries
|
||||
text down, and that line gets the plain indent answer only. The previous
|
||||
line must *end* in `begin` / `begin : label`; comments are trivia and do not
|
||||
count. Only `begin` — not `fork`, `case`, `module`.
|
||||
- **Auto-`end` edit shape.** Two edits: the new line's leading whitespace
|
||||
(omitted when already right) and an insertion of `<indent>end<eol>` at
|
||||
column 0 of the line *after* the new one, so no edit touches the cursor
|
||||
position. When the new line is the file's last line there is nowhere else to
|
||||
put it: one edit replaces the new line with `body<eol><indent>end`. The
|
||||
line ending is the one just typed (`\r\n` files stay `\r\n`).
|
||||
- **Extension path.** `editors/vscode/typing.js` acts on an
|
||||
`onDidChangeTextDocument` event with exactly one content change, no
|
||||
`reason` (undo/redo are skipped), `rangeLength` 0, text matching
|
||||
`^\r?\n[ \t]*$`, a line before it ending in `begin`/`begin : label`
|
||||
(a `//` comment stripped), `editor.formatOnType` **not** on for the
|
||||
document (language overrides honoured via `getConfiguration('editor',
|
||||
document)`), and `lucisv.autoEnd` not `false`. The request goes out on the
|
||||
next tick (`setTimeout 0`) so the language client's own `didChange` for the
|
||||
same event is sent first. The answer is applied only if the document
|
||||
version is unchanged and the answer writes an `end` (an indent-only answer
|
||||
is formatting the user never turned on). Applied with `editor.edit(…,
|
||||
{ undoStopBefore: false, undoStopAfter: true })`, then the cursor is put at
|
||||
the end of the new line.
|
||||
- **Undo.** The edit has no undo stop before it, so VS Code should fold it
|
||||
into the Enter's own undo step: one `Ctrl+Z` removes the `end`, the indent
|
||||
and the newline together. Not verified in a running VS Code (see QA).
|
||||
- **Templates.** Popup template `sortText` is now `5` + three-digit registry
|
||||
rank + label, so templates reached by the same prefix show in registry order;
|
||||
the with-reset `always_ff` / Verilog `always @(posedge … or negedge …)` were
|
||||
moved ahead of the clock-only ones. Labels unchanged.
|
||||
- **Ranking — the final tier table** (`completion/mod.rs`; the first
|
||||
character of every `sortText`, a label follows, so the order is total):
|
||||
|
||||
| digit | tier | source |
|
||||
|---|---|---|
|
||||
| `0` | module names (item position) / members (exclusive answer) | index / site |
|
||||
| `1` | visible at the cursor (scope chain); in a connection list: already-connected ports | `Semantics` |
|
||||
| `2` | declared anywhere in this buffer | `Semantics::symbols()` |
|
||||
| `3` | identifiers used in this buffer (not the token under the cursor) | token stream |
|
||||
| `4` | what the project declares (units, members, `` `define ``s) | index |
|
||||
| `5` | templates (`5` + rank + label) | `templates.rs` |
|
||||
| `6` | keywords | `vlog_parser::KEYWORDS` |
|
||||
| `7` | project words | candidate tables |
|
||||
|
||||
Dedup by label is unchanged: the first (best) tier wins. VS Code sorts by
|
||||
its own fuzzy score first and uses `sortText` among equal scores, so the
|
||||
tier order decides between equally good matches only.
|
||||
- **Ranking — the typed word itself.** The buffer-word tier skips the token
|
||||
starting at the cursor's word, so a half-typed `c` is no longer offered
|
||||
back as `c` (it used to be, by the old word tier). A saved copy of the same
|
||||
file still contributes it through the project-word table.
|
||||
- **Keyword ghosts.** `inline/keywords.rs`. Asked only when no template
|
||||
trigger answered and the rest of the line is blank (the existing ghost rule).
|
||||
The word: the token ending exactly at the cursor, `Ident` or `Keyword`,
|
||||
ASCII identifier characters starting with a letter, length ≥ 2, not after
|
||||
`.`/`::`, and not exactly a name this buffer declares (fix round: `in`,
|
||||
`re`, `out` as signals stay quiet; an undeclared word ghosts in any
|
||||
position, expressions included). A word that is already a keyword only
|
||||
extends across `_`
|
||||
(`always` → `always_ff`; `end`, `for`, `case` get nothing — a ghost after a
|
||||
finished keyword is noise a stray Tab accepts) — unless the popup has
|
||||
that keyword selected: an explicit selection wins (`end` with `endmodule`
|
||||
selected ghosts `endmodule`). Choice: the popup's
|
||||
`selectedCompletionInfo.text` when present and its range is exactly the
|
||||
typed word (start of the word to the cursor; any other range is read as no
|
||||
selection and never echoed back) — ghost exactly it, over that range, if
|
||||
it is a reserved word of the dialect extending the word, otherwise no
|
||||
ghost, since VS Code would hide a disagreeing one; else the first of a fixed priority
|
||||
list (`PRIORITY`); else shortest-then-alphabetical over `KEYWORDS`. A `.v`
|
||||
buffer is limited to the IEEE 1364-2005 reserved words. Item shape: with
|
||||
no selection, empty range at the cursor and the suffix as a snippet value
|
||||
(the existing ghosts' shape); with a selection, the selection's range and
|
||||
the whole keyword (LSP 3.18: "must extend the text of the selected item and
|
||||
use the same range").
|
||||
- **Extension bridge (corrected in the fix round, QA finding 2).**
|
||||
`vscode-languageclient` 9 passes VS Code's `selectedCompletionInfo` through
|
||||
unconverted, so a `vscode.Range` goes out in its `toJSON` array shape and
|
||||
the trigger kind as VS Code's 0/1 rather than LSP's 1/2. **Nothing was
|
||||
broken by this**: serde decodes the server's `Range` struct from a
|
||||
two-element sequence and the trigger kind is an `i32` newtype, so the
|
||||
request decoded and the template ghosts kept working (pinned by
|
||||
`qa_an_array_shaped_range_and_a_zero_trigger_kind_still_decode`). The
|
||||
`middleware.provideInlineCompletionItems` re-spelling both
|
||||
(`typing.protocolInlineContext`) is correctness hygiene: the spec's
|
||||
spelling on the wire, and correct trigger kinds for any server that reads
|
||||
them.
|
||||
- **Port items.** `completion/connection.rs`. Applies to both connection
|
||||
lists — ports after `inst (` and parameters after `#(`. Connected entries
|
||||
are those `connected_names` finds (the entry being re-typed excluded); they
|
||||
get `sortText` `1<name>` and `labelDetails.description = "connected"`.
|
||||
Within each group the order is the match order, as before (`sortText` is
|
||||
alphabetical by name within a digit, also as before). Snippet
|
||||
`name(${1:fill})` / `name(${1})` only for a client with snippet support, no
|
||||
`(` after the identifier run being replaced (same line, spaces/tabs
|
||||
skipped), and a plain-identifier name. Pre-fill when the scope chain at the
|
||||
cursor binds a `Net`/`Var`/`Port` (ports) or `Param`/`LocalParam`
|
||||
(parameters) of the same name. **An auto-closed `)` is not handled**: the
|
||||
popup is reached after a `.`, where no paren has been typed yet; if the user
|
||||
had typed `.cl(` and gone back, the `(` check already gives the bare name.
|
||||
|
||||
- **Known limits accepted by the lead (QA notes 6–11).**
|
||||
- *LIMIT starvation moved* (6): with ≥ 512 names in this file matching a
|
||||
one-letter prefix (a synthetic 600-`logic aN;` buffer), templates and
|
||||
keywords fall out of the one-letter answer; `isIncomplete` is true, so
|
||||
the second letter re-asks and gets them. Largest real case seen: 220
|
||||
items (`r` in `ibex_core.sv`).
|
||||
- *Token under the cursor* (7): tier 3 skips it even mid-word, so a word
|
||||
this file uses exactly once and declares nowhere drops out while the
|
||||
cursor is inside it.
|
||||
- *Body indent inside `fork`* (8): the body line's indent is the existing
|
||||
nesting model's answer (identical to the plain newline answer), so
|
||||
`initial fork\n begin` + Enter gives an 8-space body over a 4-space
|
||||
`end`.
|
||||
- *Pre-fill* (9) accepts a same-named signal declared after the instance —
|
||||
the scope chain binds it either way.
|
||||
- *Last line under formatOnType* (11): there the answer is one edit whose
|
||||
range contains the cursor, so VS Code probably leaves the cursor after
|
||||
the `end`; the extension path puts it back itself.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes** `pairs::analyze` (unchanged), `on_type::level_at` (unchanged,
|
||||
called from the child module), `Semantics::symbols()` / `scopes()`,
|
||||
`signature::enclosing_list`, `candidates::{Query, rank_cmp}`.
|
||||
- **Changed, crate-internal:** `on_type::on_type_formatting` takes a fifth
|
||||
argument `auto_end: bool` (one caller, `server/formatting.rs`). The inline
|
||||
entry point is now `inline::inline_completions_in_context(ws, uri,
|
||||
position, selected)`; the old three-argument `inline_completions` survives
|
||||
as a `#[cfg(test)]` wrapper so `instantiate.rs`'s test (outside this lane's
|
||||
files) compiles unchanged. `completion::member_answer` takes `snippets`.
|
||||
`tiers::visible_symbols` is `pub(super)`. Fix round: `on_type::begin_owes_an_end(doc, begin_index)`
|
||||
(`pub(crate)`, re-exported from `on_type/auto_end.rs`) is what
|
||||
`inline.rs`'s `begin` ghost gate now asks.
|
||||
- **Changed, protocol-visible:** popup `sortText` digits (table above) — any
|
||||
client or test that pinned `2`/`3`/`4`/`5` for index/template/keyword/word
|
||||
sees `4`/`5`/`6`/`7`; template `sortText` gains a rank; connection items
|
||||
gain `labelDetails` and snippet `textEdit`s. Settings `lucisv.autoEnd`,
|
||||
`lucisv.inlineKeywords` (both boolean, default true, absent = on).
|
||||
- **Outside the file list, flagged:** `editors/vscode/.vscodeignore` gained
|
||||
`typing_test.js` (and `typing.js` in its comment), as the lane brief's
|
||||
pointer to the restart.js/.vscodeignore pattern implied.
|
||||
- No request to the parser, semantic or formatter crates.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] auto-`end` on Enter: server (`on_type/auto_end.rs`, setting, wire) and
|
||||
extension (`typing.js`, `extension.js`, `package.json`)
|
||||
- [x] clock+reset templates (ghost + popup order)
|
||||
- [x] current-file ranking (`completion/buffer.rs`, tier table)
|
||||
- [x] keyword ghosts (`inline/keywords.rs`, setting, extension bridge fix)
|
||||
- [x] port items (`completion/connection.rs`, `member.rs`)
|
||||
- [x] unit, e2e and node tests; VS Code README; TODO §68.1 ticked
|
||||
- [ ] confirmed in a running VS Code (see QA log — nobody has seen it yet)
|
||||
|
||||
## Work log
|
||||
|
||||
- **2026-11-17 (dev, Opus 5.5).** All five deliverables.
|
||||
- `on_type/auto_end.rs` (new child module of `on_type.rs`): the begin-newline
|
||||
answer; `on_type_formatting` tries it first when `auto_end` and falls back
|
||||
to the unchanged indent answer. Old on-type tests pass `false`, so their
|
||||
pins are untouched; 15 new tests (steal case, balanced, inner-closed with
|
||||
outer missing, label + comment, wrapped header, `end else begin`, case
|
||||
item, tabs, CRLF, last line, setting off, non-begin lines, text carried
|
||||
down, begin two lines up).
|
||||
- `templates.rs`/`inline.rs`/`completion`: with-reset first; template
|
||||
`sortText` by registry rank (the label alone sorted `always @(*)` first).
|
||||
- `completion/buffer.rs` (new): tiers 2 and 3; `word_tier` reads only the
|
||||
table now. Decision: the typed token itself is not offered back (golden
|
||||
`the_short_answers_are_what_they_always_were` updated, reasoned in place).
|
||||
- `inline/keywords.rs` (new): keyword ghosts. Deviation from the brief's
|
||||
"proper prefix of a keyword": a finished keyword only extends across `_`.
|
||||
Found and fixed the `selectedCompletionInfo`/trigger-kind serialization
|
||||
gap in the client bridge.
|
||||
- `completion/connection.rs` (new) + `member.rs`: connected ports kept and
|
||||
marked, snippet entries, pre-fill; parameters treated the same way.
|
||||
- Extension: `typing.js` + `typing_test.js` (35 checks), wired in
|
||||
`extension.js` (middleware + change listener), two settings in
|
||||
`package.json`, README feature table and settings.
|
||||
- `smoke.js` not changed: no existing probe's expectation moved (smoke run
|
||||
recorded in the report).
|
||||
|
||||
- **2026-11-17 — fix round 2026-11-17 (dev, Opus 5.5)**, after QA and the
|
||||
lead's rulings:
|
||||
1. `owes_an_end`: closed also when the matched `end` sits at the `begin`'s
|
||||
own line's indentation; an unmatched `begin` in a branched `` `ifdef ``
|
||||
region arms nothing (`branched_regions`). Tests:
|
||||
`a_gnu_style_begin_already_closed_under_itself_gets_no_end`,
|
||||
`qa_ifdef_branches_sharing_one_end_get_no_second_end` (both QA repro
|
||||
cases), `an_ifdef_with_no_else_still_arms_the_answer`.
|
||||
2. "Extension bridge" assumption reworded: nothing was broken.
|
||||
3. Keyword ghost: none for a word that is exactly a name the buffer
|
||||
declares (`Semantics::symbols()` scan).
|
||||
4. An explicit popup selection skips the finished-keyword rule
|
||||
(`reserved_extension`).
|
||||
5. A selection whose range is not exactly the typed word is read as absent.
|
||||
6. `typing.js` strips trailing `/* … */` comments too (4 new checks).
|
||||
7. The inline `begin` ghost gate asks `on_type::begin_owes_an_end` (new
|
||||
`pub(crate)` re-export), so the stealing case ghosts its `end`; test
|
||||
`a_begin_typed_inside_a_balanced_block_still_offers_its_end`.
|
||||
Known limits 6–11 written into Assumptions.
|
||||
|
||||
## QA log
|
||||
|
||||
- **2026-11-17 (QA, Opus 5.5).** Verdict: **pass with findings** — no
|
||||
MUST-FIX. Two SHOULD-FIX, the rest NOTEs for the lead.
|
||||
|
||||
**Gates (re-run by QA).** `cargo fmt --check` clean. Guarded `cargo clippy
|
||||
-p lucisv_server --all-targets`: 0 warnings. Guarded `cargo test -p
|
||||
lucisv_server`: 1813 unit passed / 36 ignored, e2e 102 / 2 ignored, grammar
|
||||
3, opentitan_references 0 / 2 ignored (guard exit 0); after the QA tests
|
||||
below, 1816 unit. `node --test editors/vscode/*_test.js`: 9 files pass
|
||||
(typing_test 35 checks, 48 with QA's). Release build +
|
||||
`node editors/vscode/smoke.js target/release/lucisv-server`: OK, 67
|
||||
messages.
|
||||
|
||||
**Scope.** Diff touches only the §68.1 file list plus the flagged
|
||||
`.vscodeignore` line; no parser/formatter/linter/semantic change.
|
||||
(`gemini_review.md` at the root is untracked but dated 2026-10-19 — not
|
||||
this lane's.) Production lines (before `mod tests`): `auto_end.rs` 184,
|
||||
`keywords.rs` 242 (125 of them the Verilog word table), `buffer.rs` 68,
|
||||
`connection.rs` 55, `inline.rs` 331 (was 319), `on_type.rs` 361 (354),
|
||||
`completion/mod.rs` 287 (245), `member.rs` 209 (187), `tiers.rs` 162 (186),
|
||||
`settings.rs` 240 (234), `templates.rs` 326 — none near 600; no new
|
||||
function over 80 lines. No `unwrap`/`expect`/`panic!` in added non-test
|
||||
code; `auto_end.rs` indexes `tokens[...]` with indices bounded by
|
||||
construction (`prev < first <= begin < len`).
|
||||
|
||||
**How.** A Python stdio LSP driver against the release binary, and the same
|
||||
driver against a release build of `HEAD` (exported with `git archive`, own
|
||||
target dir) for before/after; sabotage-free throwaway copy for the corpus
|
||||
sweep. Scripts and outputs: the QA scratchpad `qaA/` (`autoend.py`,
|
||||
`ghosts.py`, `ports.py`, `perf.py`, `labels.py`, `starve.py`).
|
||||
|
||||
**Auto-`end`.** 46 hand cases applied to the buffer and read: nested
|
||||
stealing inside a balanced `always_comb`, case items, generate `if`/nested
|
||||
`for … begin : g`, function/task/class method, `fork … join`, `begin :
|
||||
label` (any spacing), `begin // c`, `begin /* c */`, `else begin`, `end
|
||||
else begin`, wrapped `else if (b &&\n c) begin`, `@*`, `@(*)`, `#5 begin`,
|
||||
`assert … else begin`, `unique if`, `blk: begin`, header on the line above
|
||||
the `begin`, tabs, CRLF, last line with and without a final newline,
|
||||
whitespace-only new line with the cursor mid-indent — all write the right
|
||||
`end` at the right column. Declines (and **the declined answer is
|
||||
byte-identical to `HEAD`'s indent answer** in every case): balanced block,
|
||||
`begin` in a comment / string / escaped identifier / attribute, `` `define
|
||||
`` line (with and without `\` continuation), `begin end` on one line, text
|
||||
carried down, two blank lines, a buffer that does not lex. `autoEnd=false`
|
||||
equals `HEAD` in all 46. Idempotence: applying each answer and asking again
|
||||
at the same spot never writes a second `end`. **Corpus sweep** (860 files,
|
||||
every one of 8 235 lines ending in `begin`, Enter simulated after it):
|
||||
**0 spurious `end`s**; positive control (file truncated after its first
|
||||
`begin`): 512/525 armed; 0 corpus files have a permanently unmatched
|
||||
`begin`. Timing: < 1 ms per answer.
|
||||
|
||||
**Ghost/popup templates.** `always_ff @(` ghosts with-reset then clock-only;
|
||||
`always @(` with-reset, clock-only, `*`; popup `alw` in `.sv`: `always_ff
|
||||
with reset`, `always_ff @(posedge clk)`, `always_comb begin/end`; in `.v`:
|
||||
with-reset, clock-only, `@(*)`. Snippet syntax well-formed, tab stops 1, 2
|
||||
(mirrored `$2` in the popup body), 3/4, `$0`.
|
||||
|
||||
**Ranking.** Tier digits match the table; dedup by first push. Labels
|
||||
offered at 68 positions in `ibex_core.sv` (mid-word and word-end): **none
|
||||
lost** against `HEAD`. Timing per completion (20 requests, minus an empty
|
||||
session; two runs each), HEAD → NEW: `picorv32.v` `a` 0.25/0.29 →
|
||||
0.43/0.35 ms, `r` 0.36/0.33 → 0.50/0.58; `ibex_core.sv` `a` 0.09/0.22 →
|
||||
0.27/0.33, `r` 0.65/0.63 → 0.71/0.74. Sub-millisecond either way.
|
||||
|
||||
**Keyword ghosts.** None in a line/block comment, an unterminated string,
|
||||
after `.`/`::`/backtick, for `$dis`, or mid-word; `.v` gets `always` /
|
||||
`localparam` (no `logic`); each setting off independently. Selection
|
||||
present with a keyword → that keyword over its range; with a non-keyword →
|
||||
nothing. **The extension bridge is real**: `vscode-languageclient` 9.0.1
|
||||
`asInlineCompletionParams` passes `context` through
|
||||
(`InlineCompletionContext.create(triggerKind, selectedCompletionInfo)`),
|
||||
and `middleware.provideInlineCompletionItems(document, position, context,
|
||||
token, next)` is the hook it calls.
|
||||
|
||||
**Port items.** Unconnected first, connected after with `connected`
|
||||
(including a port connected *after* the cursor and a port connected twice);
|
||||
`.name(${1})`, pre-filled only from a visible net/var/port (a same-named
|
||||
`localparam` is not used for a port; a `clk` in a named block or another
|
||||
module of the file is not used); `#(.` pre-fills from a `localparam`;
|
||||
escaped port → bare name; `.*` present → fine; unknown module → empty;
|
||||
`.cl|(x)` → bare; no snippet support → bare everywhere.
|
||||
|
||||
**Findings.**
|
||||
1. **SHOULD-FIX — a second `end` in complete code when the file holds
|
||||
another unmatched `begin` and this block's `end` is not at the owner's
|
||||
column.** The accepted heuristic, but the GNU layout makes it reachable
|
||||
in valid code: `` module m;\n`ifdef A\n always @(posedge clk) begin\n`else\n always @(posedge clk or negedge rst) begin\n`endif\n if (x)\n begin\n|\n y <= 1;\n end\n end\nendmodule `` → ` end` written under the `if`, so the file
|
||||
now has one `end` too many. Same with the cursor after the *first*
|
||||
`` `ifdef `` branch's `begin` (an `end` lands inside branch A). Any
|
||||
mid-edit unmatched `begin` above has the same effect on a GNU-style
|
||||
block below. Corpus exposure measured at 0 (no corpus file is
|
||||
permanently unbalanced). Suggested: also treat the `begin` as closed
|
||||
when its matched `end` starts its line at the `begin`'s own line
|
||||
indentation. Lead to rule.
|
||||
2. **SHOULD-FIX (docs) — the "Extension bridge" assumption overstates the
|
||||
bug it fixes.** The server *does* decode VS Code's array-shaped range and
|
||||
trigger kind 0 (serde reads a struct from a sequence); before the bridge
|
||||
the request did not fail and the template ghosts did not die. The bridge
|
||||
is still right (spec spelling, correct trigger kinds). Pinned by
|
||||
`qa_an_array_shaped_range_and_a_zero_trigger_kind_still_decode`. The
|
||||
README paragraph should say so.
|
||||
3. NOTE — keyword ghosts with no popup open fire on declared names and in
|
||||
expression position: `assign out = in` → `put`, `x = re` → `turn`
|
||||
(`return` is ahead of `reg` in `PRIORITY`; `.sv` only), `x = ou` →
|
||||
`tput`, `x = al` → `ways_ff`. With the popup open VS Code's selection
|
||||
is normally the exact-match signal, which silences the ghost. Lead to
|
||||
rule whether an exact declared name or a non-statement position should
|
||||
suppress it.
|
||||
4. NOTE — the finished-keyword rule also applies to an explicit popup
|
||||
selection: typed `end` with `endmodule` selected → no ghost (spec says
|
||||
the ghost follows the selected item). Preview only; the popup accepts
|
||||
it anyway.
|
||||
5. NOTE — a `selectedCompletionInfo` whose range is elsewhere is echoed
|
||||
back as the item range (VS Code would drop it); one missing `text`
|
||||
fails the whole request with -32602 (pre-existing decode behaviour).
|
||||
6. NOTE — `LIMIT` starvation moved: with ≥ 512 names in *this file*
|
||||
matching a one-letter prefix (synthetic: 600 `logic aN;` in another
|
||||
module), templates and keywords fall out of the answer (`HEAD` kept
|
||||
them; `isIncomplete` is true, so the second letter re-asks). Not seen on
|
||||
real files (largest: 220 items for `r` in `ibex_core.sv`).
|
||||
7. NOTE — the typed token itself is skipped by tier 3 even mid-word, so a
|
||||
word the file uses exactly once and declares nowhere drops out while the
|
||||
cursor is inside it (68-position check found no case in `ibex_core.sv`).
|
||||
8. NOTE — `fork … join` body: `initial fork\n begin` + Enter gives an
|
||||
8-space body over a 4-space `end`; the body indent is the nesting
|
||||
model's (identical to `HEAD`'s plain answer), not the lane's.
|
||||
9. NOTE — pre-fill accepts a signal declared *after* the instance
|
||||
(`sub u (.);\n logic clk;` → `clk(${1:clk})`).
|
||||
10. NOTE — `typing.js` strips `//` comments only: `begin /* c */` + Enter
|
||||
gets an `end` with `editor.formatOnType` on (server answers) but not
|
||||
with it off (extension never asks).
|
||||
11. NOTE (unverifiable here) — the last-line answer is one edit whose
|
||||
range contains the cursor; with `editor.formatOnType` on, VS Code will
|
||||
likely leave the cursor after the `end`, not on the body line (the
|
||||
extension path puts it back itself). Needs a running VS Code, as do:
|
||||
the one-step undo, the extension's `didChange`-before-request ordering
|
||||
(reading `vscode-languageclient` 9.0.1 it holds: the incremental
|
||||
`didChange` is sent from microtasks before the `setTimeout(0)` task),
|
||||
and the ghost following the popup.
|
||||
|
||||
**QA tests added.** `on_type/auto_end.rs`:
|
||||
`qa_asking_again_after_the_answer_is_applied_adds_no_second_end` (9
|
||||
armed shapes), `qa_a_declined_newline_is_exactly_the_plain_indent_answer`
|
||||
(9 declining shapes, incl. `` `define ``, `` `ifdef `` both branches,
|
||||
string, escaped `\begin`). `inline/keywords.rs`:
|
||||
`qa_an_array_shaped_range_and_a_zero_trigger_kind_still_decode`.
|
||||
`editors/vscode/typing_test.js`: `qaEdges` (13 checks: multi-cursor, redo,
|
||||
no editor, refused edit, CRLF position, pastes, context without a range).
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-11-17 — lead (after dev, QA, one fix round)
|
||||
|
||||
Accepted. QA found no corruption, crash or spec violation; both SHOULD-FIX
|
||||
items and the rulings below went into the fix round, and the dev's gates
|
||||
after it are green (unit 1 823, e2e 102, node 9 files, smoke OK).
|
||||
|
||||
Rulings recorded:
|
||||
|
||||
- **Auto-`end` is armed by any unclosed `begin` at or before this one**, not
|
||||
by this `begin`'s own span (the stack matcher lets a new inner `begin`
|
||||
steal the outer `end`). Closed means: matched by an `end` that starts its
|
||||
line at the indentation the answer would write, or at the `begin`'s own
|
||||
line's (GNU layout). A `begin` unclosed inside an `ifdef` region with an
|
||||
`else`/`elsif` arms nothing — the shared `end` after `endif` is its `end`.
|
||||
- **No keyword ghost for a word that is exactly a name this buffer
|
||||
declares** (`in`, `re`, `out` as signals stay quiet). Anything else that
|
||||
is a keyword prefix ghosts, in any position — the owner asked for
|
||||
"always".
|
||||
- **An explicit popup selection wins** over the "finished keyword only
|
||||
extends across `_`" rule; a selection whose range is not the typed word
|
||||
is ignored.
|
||||
- Accepted limits (in Assumptions): LIMIT 512 can drop templates/keywords
|
||||
in a 600-same-prefix buffer; the token under the cursor is not offered
|
||||
back; port pre-fill accepts a later declaration; the last-line answer is
|
||||
one edit that contains the cursor.
|
||||
|
||||
**Not verified by anyone:** every behaviour in a running VS Code — the
|
||||
cursor after `begin` + Enter (formatOnType on and off), one-step undo, the
|
||||
ghost following the popup selection, the dimmed `connected` detail. The
|
||||
list is in the dev's report and the QA log; it is the owner's acceptance.
|
||||
@@ -1,5 +1,5 @@
|
||||
# The checks are pre-publish/developer checks, not part of the shipped
|
||||
# extension. `restart.js`, `mcp.js` and the `hierarchy*`/`references*` modules
|
||||
# extension. `restart.js`, `typing.js`, `mcp.js` and the `hierarchy*`/`references*` modules
|
||||
# themselves ARE shipped — `extension.js` requires them.
|
||||
smoke.js
|
||||
mcp_smoke.js
|
||||
@@ -11,5 +11,6 @@ hierarchySections_test.js
|
||||
hierarchyView_test.js
|
||||
referencesModel_test.js
|
||||
referencesView_test.js
|
||||
typing_test.js
|
||||
.vscode/**
|
||||
.gitignore
|
||||
@@ -80,7 +80,16 @@ Most features work as soon as a supported file opens:
|
||||
workspace-aware and verifies its target before opening the rename box.
|
||||
- Type `if (`, `case (`, `begin`, `fork`, `generate`, or `module` at the end of
|
||||
a line to get structural ghost text. Press `Tab` to accept it; use `Alt+]` to
|
||||
cycle when several shapes fit.
|
||||
cycle when several shapes fit. `always_ff @(` offers a clock-and-reset block
|
||||
first and the clock-only one second.
|
||||
- Press `Enter` after a `begin` that has no `end` yet and the `end` is written
|
||||
on the line below, lined up with its statement, with the cursor on the
|
||||
indented line in between.
|
||||
- Start typing a keyword (`alw`, `endm`) and the rest of it appears as grey
|
||||
text; `Tab` accepts it.
|
||||
- After the `.` of a port connection the ports still to connect come first;
|
||||
accepting one writes `.name()` with the cursor inside, pre-filled with a
|
||||
same-named signal when there is one.
|
||||
- Run **Format Document** or **Format Selection** through the standard VS Code
|
||||
commands.
|
||||
|
||||
@@ -106,11 +115,13 @@ enabling both paths formats twice.
|
||||
| Document formatting | Width-aware, deterministic formatting with inferred alignment for ports, connections, and parameter tables |
|
||||
| Range and multi-range formatting | Formats selected constructs while leaving the rest of the file byte-for-byte unchanged |
|
||||
| On-type formatting | Reindents after a newline and formats a completed statement after `;` when `editor.formatOnType` is enabled |
|
||||
| Auto `end` | `Enter` after an unclosed `begin` writes its `end` below the cursor at the statement's indentation, with or without `editor.formatOnType` (`lucisv.autoEnd`) |
|
||||
| Keyword ghosts | A typed prefix of a keyword shows the rest as grey text that follows the popup's selection (`lucisv.inlineKeywords`) |
|
||||
| Format on save | Works through VS Code's native format-on-save flow; a separate LSP save hook is available for other editors |
|
||||
| Safe output | Token equivalence, comment preservation, convergence checks, and all-or-nothing fallback protect source code |
|
||||
| Format fences | `// verilog_format: off` / `on` preserves deliberately hand-formatted regions |
|
||||
| Inline templates | Context-sensitive ghost text completes blocks, cases, processes, generate regions, and modules |
|
||||
| Smart completion | Context-aware statement/declaration templates plus complete module-instantiation snippets from the workspace index |
|
||||
| Smart completion | Context-aware statement/declaration templates plus complete module-instantiation snippets from the workspace index. Names from the current file rank first; after a connection's `.` the unconnected ports come first, connected ones follow marked `connected`, and accepting one writes `.name()` |
|
||||
| Static snippets | Dialect-specific file-level templates for modules, interfaces, packages, classes, functions, tasks, FSMs, assertions, testbenches, guards, and generate loops |
|
||||
| Signature help | Names active ports or parameters in named and ordered instantiations |
|
||||
| Linked editing | Keeps opening and closing labels synchronized for modules, classes, functions, tasks, blocks, forks, and other named scopes |
|
||||
@@ -307,6 +318,8 @@ Server-side templates add `if`, `if/else`, `else if`, `case`, `for`, `while`,
|
||||
| `lucisv.references.fullLineView` | `true` | `Shift+Alt+F12` in a Verilog/SystemVerilog editor opens lucisv's full-line References view instead of VS Code's, whose previews start a few characters before the match. `false` gives the key back to the built-in command; the context-menu entry works either way, and `Shift+F12` peek is never changed |
|
||||
| `lucisv.rainbowBeginEnd` | `true` | Color nested block pairs and unmatched keywords; updates immediately |
|
||||
| `lucisv.inlineTemplates` | `true` | Show context-aware structural ghost text; requires `editor.inlineSuggest.enabled` |
|
||||
| `lucisv.inlineKeywords` | `true` | Ghost the rest of a keyword while its first letters are typed; follows the popup's selected entry; requires `editor.inlineSuggest.enabled` |
|
||||
| `lucisv.autoEnd` | `true` | Write the `end` when `Enter` is pressed after a `begin` that has none |
|
||||
| `lucisv.inlineInstantiation` | `true` | Ghost the full instantiation (parameters and ports) once a module's name is typed exactly and followed by a space; requires `editor.inlineSuggest.enabled` |
|
||||
| `lucisv.lineLength` | unset | Maximum formatter width, 40–400; built-in default is 100 |
|
||||
| `lucisv.indent` | unset | Indent width, 1–8; falls back to the editor tab size, then 2 |
|
||||
|
||||
@@ -16,6 +16,7 @@ const { createRestarter } = require('./restart');
|
||||
const { executeCommand } = require('./extract');
|
||||
const { HierarchyView } = require('./hierarchyView');
|
||||
const { ReferencesView } = require('./referencesView');
|
||||
const typing = require('./typing');
|
||||
const mcp = require('./mcp');
|
||||
|
||||
/** The single client, kept only so `deactivate` can stop it. */
|
||||
@@ -200,6 +201,11 @@ function activate(context) {
|
||||
// advertises, so a second registration of the same id would collide with
|
||||
// it at activation.
|
||||
middleware: {
|
||||
// `selectedCompletionInfo` as LSP spells it — the keyword ghost follows
|
||||
// the popup's selected entry, and the client would otherwise send VS
|
||||
// Code's own Range shape (docs/features/completion-ux, `typing.js`).
|
||||
provideInlineCompletionItems: (document, position, context, token, next) =>
|
||||
next(document, position, typing.protocolInlineContext(context), token),
|
||||
executeCommand: (command, args, next) =>
|
||||
executeCommand(
|
||||
{ showInputBox: (options) => vscode.window.showInputBox(options) },
|
||||
@@ -267,7 +273,12 @@ function activate(context) {
|
||||
// Typing moves every range after the cursor, so the answer is stale the
|
||||
// moment it arrives; debounce rather than ask on every keystroke.
|
||||
vscode.workspace.onDidChangeTextDocument((event) => {
|
||||
if (isVerilog(event.document)) scheduleRepaint();
|
||||
if (!isVerilog(event.document)) return;
|
||||
scheduleRepaint();
|
||||
// `begin` + Enter writes the `end` (docs/features/completion-ux). Next
|
||||
// tick, so the language client's own listener has sent this change
|
||||
// before the request about it goes out.
|
||||
setTimeout(() => typing.handleChange(autoEndDeps, event), 0);
|
||||
}),
|
||||
vscode.workspace.onDidChangeConfiguration((event) => {
|
||||
// A spawn argument can only change by spawning again, so this one
|
||||
@@ -310,6 +321,42 @@ function deactivate() {
|
||||
return restarter ? restarter.dispose() : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* What `typing.handleChange` needs from VS Code and the client. The edits are
|
||||
* applied with no undo stop before them, so they join the Enter's own undo
|
||||
* step where VS Code allows it.
|
||||
*/
|
||||
const autoEndDeps = {
|
||||
editorFor: (document) =>
|
||||
vscode.window.visibleTextEditors.find((editor) => editor.document === document),
|
||||
formatOnType: (document) =>
|
||||
vscode.workspace.getConfiguration('editor', document).get('formatOnType') === true,
|
||||
autoEnd: (document) => vscode.workspace.getConfiguration('lucisv', document).get('autoEnd') !== false,
|
||||
request: (document, position, editor) =>
|
||||
client.sendRequest('textDocument/onTypeFormatting', {
|
||||
textDocument: { uri: document.uri.toString() },
|
||||
position,
|
||||
ch: '\n',
|
||||
options: {
|
||||
tabSize: Number(editor.options.tabSize) || 2,
|
||||
insertSpaces: editor.options.insertSpaces !== false,
|
||||
},
|
||||
}),
|
||||
apply: async (editor, edits) => {
|
||||
const converted = await client.protocol2CodeConverter.asTextEdits(edits);
|
||||
return editor.edit(
|
||||
(builder) => {
|
||||
for (const edit of converted || []) builder.replace(edit.range, edit.newText);
|
||||
},
|
||||
{ undoStopBefore: false, undoStopAfter: true },
|
||||
);
|
||||
},
|
||||
placeCursor: (editor, line) => {
|
||||
const end = editor.document.lineAt(line).range.end;
|
||||
editor.selection = new vscode.Selection(end, end);
|
||||
},
|
||||
};
|
||||
|
||||
/** True for the documents this extension knows about. */
|
||||
function isVerilog(document) {
|
||||
return LANGUAGES.includes(document.languageId);
|
||||
|
||||
@@ -392,6 +392,16 @@
|
||||
"default": true,
|
||||
"markdownDescription": "Show grey ghost text that finishes a module instantiation once you have typed the module's whole name **followed by a space**, somewhere an instantiation may be written: every parameter override and every port connection, with a port that matches a signal already in scope connected for you. Tab accepts it as a snippet and steps through the values left to fill in. The space is what says the name is finished — `aes` alone offers nothing, because `aes_dft` may still be coming — and the name must match an indexed module exactly, capitals included; the completion popup is what helps you get there. A module two files declare expands from the copy nearest your own file. The accepted text is indented with the editor's own `editor.tabSize`/`editor.insertSpaces`, not with `#lucisv.indent#`. Requires `editor.inlineSuggest.enabled`."
|
||||
},
|
||||
"lucisv.inlineKeywords": {
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
"markdownDescription": "Show the rest of a keyword as grey ghost text while you type its first letters: `alw` suggests `always_ff`, `endm` suggests `endmodule`; Tab accepts it. While the completion popup is open the ghost follows the popup's selected entry. A word that is already a keyword only grows across an underscore (`always` → `always_ff`), so `end` and `for` stay as typed. A `.v` file is only offered Verilog-2005 keywords. Independent of `#lucisv.inlineTemplates#`. Requires `editor.inlineSuggest.enabled`."
|
||||
},
|
||||
"lucisv.autoEnd": {
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
"markdownDescription": "When you press Enter after a line ending in `begin` (or `begin : label`) and that block has no `end` yet, write the `end` on the line below, lined up with the statement the `begin` belongs to, and leave the cursor on the indented line in between. Works whether or not `#editor.formatOnType#` is on. A block that already has its `end` gets none."
|
||||
},
|
||||
"lucisv.formatOnSave": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
// Two things the extension does while the user types (TODO §68.1,
|
||||
// docs/features/completion-ux):
|
||||
//
|
||||
// 1. **`begin` + Enter writes the `end`** even with `editor.formatOnType` off,
|
||||
// which is VS Code's default. The server answers the ordinary
|
||||
// `textDocument/onTypeFormatting` request for "\n" with the body line's
|
||||
// indent and the `end` line; VS Code only sends that request itself when
|
||||
// `editor.formatOnType` is on. So when it is off, this watches for the one
|
||||
// change that matters — a single newline typed after a line ending in
|
||||
// `begin` / `begin : label` — sends the request itself, and applies the
|
||||
// answer only if it writes an `end` and the buffer has not moved on since.
|
||||
// When `editor.formatOnType` is on, VS Code sends the request and this does
|
||||
// nothing, so the request is never sent twice.
|
||||
// 2. **The inline-completion context, made serializable.** The language
|
||||
// client passes VS Code's `selectedCompletionInfo` through as it is, and a
|
||||
// `vscode.Range` serializes as a two-element array — not the LSP `Range` the
|
||||
// server decodes — and VS Code's trigger kinds are numbered from 0 where
|
||||
// LSP's start at 1. `protocolInlineContext` re-spells both.
|
||||
//
|
||||
// Nothing here requires `vscode`: the decisions are pure functions and the
|
||||
// flow takes its dependencies as an object, so `typing_test.js` drives all of
|
||||
// it headlessly.
|
||||
|
||||
/** A line that ends in `begin` or `begin : label`, comments aside. */
|
||||
const ENDS_IN_BEGIN = /(^|[^A-Za-z0-9_$`])begin(\s*:\s*[A-Za-z_][A-Za-z0-9_$]*)?$/;
|
||||
|
||||
/** The text a single Enter inserts: one newline and the indent after it. */
|
||||
const NEWLINE_ONLY = /^\r?\n[ \t]*$/;
|
||||
|
||||
/**
|
||||
* Whether one content change is a newline typed right after `begin`.
|
||||
*
|
||||
* `lineBefore` is the text of the line the newline was typed on, as it reads
|
||||
* *after* the change — everything left of the insertion point, since Enter
|
||||
* carries whatever followed the cursor down to the new line.
|
||||
*/
|
||||
function isBeginNewline(change, lineBefore) {
|
||||
if (!change || change.rangeLength !== 0 || !NEWLINE_ONLY.test(change.text)) return false;
|
||||
return ENDS_IN_BEGIN.test(withoutTrailingComments(lineBefore));
|
||||
}
|
||||
|
||||
/**
|
||||
* A line with its `//` comment and any trailing `/* … *\/` comments cut off,
|
||||
* so `begin /* why *\/` counts as ending in `begin` here exactly as it does
|
||||
* in the server, which reads tokens (the formatOnType-on path).
|
||||
*/
|
||||
function withoutTrailingComments(line) {
|
||||
let code = String(line).replace(/\/\/.*$/, '').trimEnd();
|
||||
while (code.endsWith('*/')) {
|
||||
const open = code.lastIndexOf('/*');
|
||||
if (open < 0) break;
|
||||
code = code.slice(0, open).trimEnd();
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
/**
|
||||
* The position the server is asked about: the new line, at the end of the
|
||||
* indent the editor itself wrote there.
|
||||
*/
|
||||
function newLinePosition(change) {
|
||||
const indent = change.text.slice(change.text.lastIndexOf('\n') + 1);
|
||||
return { line: change.range.start.line + 1, character: indent.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the server's answer writes an `end`. Without one it is only the new
|
||||
* line's indentation — on-type formatting the user has not turned on, so it is
|
||||
* not applied.
|
||||
*/
|
||||
function writesAnEnd(edits) {
|
||||
return Array.isArray(edits) && edits.some((edit) => /(^|\s)end\r?\n?$/.test(edit.newText || ''));
|
||||
}
|
||||
|
||||
/** An LSP range from anything with `start`/`end` positions. */
|
||||
function plainRange(range) {
|
||||
const position = (p) => ({ line: p.line, character: p.character });
|
||||
return { start: position(range.start), end: position(range.end) };
|
||||
}
|
||||
|
||||
/**
|
||||
* The inline-completion context as LSP 3.18 spells it: trigger kinds 1/2
|
||||
* rather than VS Code's 0/1, and the selected popup entry's range as a plain
|
||||
* `Range` object.
|
||||
*/
|
||||
function protocolInlineContext(context) {
|
||||
const out = { triggerKind: (context && context.triggerKind === 0) ? 1 : 2 };
|
||||
const selected = context && context.selectedCompletionInfo;
|
||||
if (selected && selected.range) {
|
||||
out.selectedCompletionInfo = { range: plainRange(selected.range), text: String(selected.text) };
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle one `onDidChangeTextDocument` event. Resolves to `true` when an `end`
|
||||
* was written.
|
||||
*
|
||||
* `deps`:
|
||||
* - `editorFor(document)` — the visible editor showing it, or `undefined`;
|
||||
* - `formatOnType(document)` / `autoEnd(document)` — the two settings;
|
||||
* - `request(document, position, editor)` — the on-type request, resolving to
|
||||
* LSP `TextEdit[]` or `null`;
|
||||
* - `apply(editor, edits)` — apply them as one edit, resolving to a boolean;
|
||||
* - `placeCursor(editor, line)` — put the cursor at the end of that line.
|
||||
*/
|
||||
async function handleChange(deps, event) {
|
||||
// An undo or a redo replays a newline the user already had answered.
|
||||
if (event.reason !== undefined && event.reason !== null) return false;
|
||||
const changes = event.contentChanges || [];
|
||||
if (changes.length !== 1) return false;
|
||||
const document = event.document;
|
||||
const change = changes[0];
|
||||
if (deps.formatOnType(document) || !deps.autoEnd(document)) return false;
|
||||
const lineBefore = document.lineAt(change.range.start.line).text;
|
||||
if (!isBeginNewline(change, lineBefore)) return false;
|
||||
const editor = deps.editorFor(document);
|
||||
if (!editor) return false;
|
||||
const version = document.version;
|
||||
const position = newLinePosition(change);
|
||||
let edits;
|
||||
try {
|
||||
edits = await deps.request(document, position, editor);
|
||||
} catch {
|
||||
return false; // a server restarting or gone: Enter stays a plain Enter
|
||||
}
|
||||
// The answer is about the buffer as it was; one more keystroke and every
|
||||
// offset in it may be wrong.
|
||||
if (document.version !== version || !writesAnEnd(edits)) return false;
|
||||
if (!(await deps.apply(editor, edits))) return false;
|
||||
deps.placeCursor(editor, position.line);
|
||||
return true;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
isBeginNewline,
|
||||
newLinePosition,
|
||||
writesAnEnd,
|
||||
protocolInlineContext,
|
||||
handleChange,
|
||||
};
|
||||
@@ -0,0 +1,204 @@
|
||||
// Checks for `typing.js`: the begin-newline decision, the auto-`end` flow and
|
||||
// the inline-completion context the server is sent.
|
||||
//
|
||||
// node typing_test.js
|
||||
//
|
||||
// Exits 0 on success, 1 on any failure. Plain node, no dependencies and no
|
||||
// test runner — the same style as `restart_test.js` next to it. The fakes
|
||||
// script only what `typing.js` depends on; nothing here re-implements VS Code.
|
||||
// See docs/features/completion-ux/README.md.
|
||||
|
||||
const {
|
||||
isBeginNewline,
|
||||
newLinePosition,
|
||||
writesAnEnd,
|
||||
protocolInlineContext,
|
||||
handleChange,
|
||||
} = require('./typing');
|
||||
|
||||
let checks = 0;
|
||||
|
||||
function ok(condition, what) {
|
||||
checks += 1;
|
||||
if (!condition) fail(what);
|
||||
}
|
||||
|
||||
function equal(got, want, what) {
|
||||
checks += 1;
|
||||
const a = JSON.stringify(got);
|
||||
const b = JSON.stringify(want);
|
||||
if (a !== b) fail(`${what}\n got: ${a}\n want: ${b}`);
|
||||
}
|
||||
|
||||
function fail(what) {
|
||||
console.error(`FAIL: ${what}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
/** A newline typed at the end of line `line`, column `character`. */
|
||||
function enter(line, character, text = '\n') {
|
||||
return { range: { start: { line, character }, end: { line, character } }, rangeLength: 0, text };
|
||||
}
|
||||
|
||||
// --- the decision ----------------------------------------------------------
|
||||
|
||||
ok(isBeginNewline(enter(1, 20), ' always_comb begin'), 'a bare begin');
|
||||
ok(isBeginNewline(enter(1, 20, '\n '), ' if (x) begin'), 'auto-indent may ride along');
|
||||
ok(isBeginNewline(enter(1, 20, '\r\n'), ' if (x) begin'), 'a CRLF newline');
|
||||
ok(isBeginNewline(enter(1, 20), 'begin : blk'), 'a labelled begin');
|
||||
ok(isBeginNewline(enter(1, 20), ' end else begin // why'), 'a comment after it');
|
||||
ok(!isBeginNewline(enter(1, 20), ' x = 1;'), 'not after a statement');
|
||||
ok(isBeginNewline(enter(1, 20), ' if (x) begin /* why */'), 'a block comment after it');
|
||||
ok(isBeginNewline(enter(1, 20), ' begin /* a */ /* b */ '), 'two block comments after it');
|
||||
ok(!isBeginNewline(enter(1, 20), ' begin /* a */ x /* b */'), 'code between the comments');
|
||||
ok(!isBeginNewline(enter(1, 20), ' x = 1; /* begin */'), 'a begin inside the comment');
|
||||
ok(!isBeginNewline(enter(1, 20), ' my_begin'), 'not a word ending in begin');
|
||||
ok(!isBeginNewline(enter(1, 20), ' `begin'), 'not a macro');
|
||||
ok(!isBeginNewline(enter(1, 20, 'x'), ' begin'), 'not a letter');
|
||||
ok(!isBeginNewline(enter(1, 20, '\n\n'), ' begin'), 'not two newlines (a paste)');
|
||||
ok(!isBeginNewline({ ...enter(1, 20), rangeLength: 3 }, ' begin'), 'not a replacement');
|
||||
|
||||
equal(newLinePosition(enter(4, 13, '\n ')), { line: 5, character: 4 }, 'the new line, past its indent');
|
||||
equal(newLinePosition(enter(4, 13)), { line: 5, character: 0 }, 'an unindented new line');
|
||||
|
||||
ok(writesAnEnd([{ newText: ' ' }, { newText: ' end\n' }]), 'the two-edit answer');
|
||||
ok(writesAnEnd([{ newText: ' \n end' }]), 'the last-line answer');
|
||||
ok(!writesAnEnd([{ newText: ' ' }]), 'the indent alone is not applied');
|
||||
ok(!writesAnEnd(null), 'no answer');
|
||||
|
||||
// --- the inline context ----------------------------------------------------
|
||||
|
||||
equal(protocolInlineContext({ triggerKind: 1 }), { triggerKind: 2 }, 'automatic is 2 on the wire');
|
||||
equal(protocolInlineContext({ triggerKind: 0 }), { triggerKind: 1 }, 'invoked is 1 on the wire');
|
||||
// A `vscode.Range`-alike whose JSON form is an array, as the real one's is.
|
||||
const vsRange = {
|
||||
start: { line: 3, character: 2, extra: true },
|
||||
end: { line: 3, character: 5 },
|
||||
toJSON() {
|
||||
return [this.start, this.end];
|
||||
},
|
||||
};
|
||||
equal(
|
||||
protocolInlineContext({ triggerKind: 1, selectedCompletionInfo: { range: vsRange, text: 'always_ff' } }),
|
||||
{
|
||||
triggerKind: 2,
|
||||
selectedCompletionInfo: {
|
||||
range: { start: { line: 3, character: 2 }, end: { line: 3, character: 5 } },
|
||||
text: 'always_ff',
|
||||
},
|
||||
},
|
||||
'the selected entry as a plain LSP range',
|
||||
);
|
||||
|
||||
// --- the flow --------------------------------------------------------------
|
||||
|
||||
function documentWith(lines, version = 7) {
|
||||
return { version, lineAt: (line) => ({ text: lines[line] }) };
|
||||
}
|
||||
|
||||
function deps(overrides = {}) {
|
||||
const log = [];
|
||||
const base = {
|
||||
editorFor: () => ({ id: 'editor' }),
|
||||
formatOnType: () => false,
|
||||
autoEnd: () => true,
|
||||
request: async (_document, position) => {
|
||||
log.push(['request', position]);
|
||||
return [{ newText: ' ' }, { newText: ' end\n' }];
|
||||
},
|
||||
apply: async (_editor, edits) => {
|
||||
log.push(['apply', edits.length]);
|
||||
return true;
|
||||
},
|
||||
placeCursor: (_editor, line) => log.push(['cursor', line]),
|
||||
};
|
||||
return { deps: { ...base, ...overrides }, log };
|
||||
}
|
||||
|
||||
async function flow() {
|
||||
const document = documentWith(['module m;', ' always_comb begin', '']);
|
||||
const event = { document, contentChanges: [enter(1, 19)] };
|
||||
|
||||
let { deps: d, log } = deps();
|
||||
equal(await handleChange(d, event), true, 'the end is written');
|
||||
equal(
|
||||
log,
|
||||
[['request', { line: 2, character: 0 }], ['apply', 2], ['cursor', 2]],
|
||||
'asked about the new line, applied, cursor put back on it',
|
||||
);
|
||||
|
||||
({ deps: d, log } = deps({ formatOnType: () => true }));
|
||||
equal(await handleChange(d, event), false, 'formatOnType on: VS Code asks, not us');
|
||||
equal(log, [], 'and nothing is sent twice');
|
||||
|
||||
({ deps: d, log } = deps({ autoEnd: () => false }));
|
||||
equal(await handleChange(d, event), false, 'lucisv.autoEnd off');
|
||||
equal(log, [], 'nothing sent');
|
||||
|
||||
({ deps: d, log } = deps());
|
||||
equal(await handleChange(d, { ...event, reason: 1 }), false, 'an undo is not typing');
|
||||
equal(log, [], 'nothing sent on undo');
|
||||
|
||||
({ deps: d, log } = deps({ request: async () => [{ newText: ' ' }] }));
|
||||
equal(await handleChange(d, event), false, 'an indent-only answer');
|
||||
equal(log, [], 'is not applied');
|
||||
|
||||
// The user typed again while the request was in flight.
|
||||
const moving = documentWith(['module m;', ' always_comb begin', '']);
|
||||
({ deps: d, log } = deps({
|
||||
request: async () => {
|
||||
moving.version += 1;
|
||||
return [{ newText: ' end\n' }];
|
||||
},
|
||||
}));
|
||||
equal(await handleChange(d, { document: moving, contentChanges: [enter(1, 19)] }), false, 'stale');
|
||||
equal(log, [], 'a stale answer is dropped');
|
||||
|
||||
({ deps: d, log } = deps({
|
||||
request: async () => {
|
||||
throw new Error('server gone');
|
||||
},
|
||||
}));
|
||||
equal(await handleChange(d, event), false, 'a failed request is a plain Enter');
|
||||
|
||||
const plain = { document: documentWith(['module m;', ' x = 1;', '']), contentChanges: [enter(1, 8)] };
|
||||
({ deps: d, log } = deps());
|
||||
equal(await handleChange(d, plain), false, 'not after begin');
|
||||
equal(log, [], 'nothing sent for an ordinary Enter');
|
||||
}
|
||||
|
||||
// QA (completion-ux, 2026-11-17): the edges the dev's checks left open.
|
||||
async function qaEdges() {
|
||||
const document = documentWith(['module m;', ' always_comb begin', '', '']);
|
||||
let { deps: d, log } = deps();
|
||||
const two = { document, contentChanges: [enter(1, 19), enter(2, 0)] };
|
||||
equal(await handleChange(d, two), false, 'QA: multi-cursor Enter is left alone');
|
||||
equal(log, [], 'QA: nothing sent for several changes');
|
||||
|
||||
({ deps: d, log } = deps());
|
||||
equal(await handleChange(d, { document, contentChanges: [enter(1, 19)], reason: 2 }), false, 'QA: a redo');
|
||||
equal(log, [], 'QA: nothing sent on redo');
|
||||
|
||||
({ deps: d, log } = deps({ editorFor: () => undefined }));
|
||||
equal(await handleChange(d, { document, contentChanges: [enter(1, 19)] }), false, 'QA: no visible editor');
|
||||
equal(log, [], 'QA: nothing sent without an editor');
|
||||
|
||||
({ deps: d, log } = deps({ apply: async () => false }));
|
||||
equal(await handleChange(d, { document, contentChanges: [enter(1, 19)] }), false, 'QA: a refused edit');
|
||||
ok(!log.some((entry) => entry[0] === 'cursor'), 'QA: the cursor is not moved after a refused edit');
|
||||
|
||||
equal(newLinePosition(enter(4, 13, '\r\n ')), { line: 5, character: 2 }, 'QA: CRLF newline position');
|
||||
ok(!isBeginNewline(enter(1, 20, '\nfoo;'), ' begin'), 'QA: a pasted line is not Enter');
|
||||
ok(!isBeginNewline(enter(1, 20, '\n \n'), ' begin'), 'QA: a pasted blank pair is not Enter');
|
||||
equal(protocolInlineContext(undefined), { triggerKind: 2 }, 'QA: no context at all');
|
||||
equal(
|
||||
protocolInlineContext({ triggerKind: 0, selectedCompletionInfo: { text: 'x' } }),
|
||||
{ triggerKind: 1 },
|
||||
'QA: a selection without a range is dropped, not sent malformed',
|
||||
);
|
||||
}
|
||||
|
||||
flow()
|
||||
.then(qaEdges)
|
||||
.then(() => console.log(`typing_test: ${checks} checks passed`))
|
||||
.catch((error) => fail(error && error.stack));
|
||||
Reference in new issue
Block a user