Inline templates M15: ghost text finishes the block you open

textDocument/inlineCompletion (LSP 3.18): typing `if (` offers grey
`) begin … end` and a line-ending `begin` offers its `end`; Tab accepts
as a snippet, cursor in the condition first, indented body second.
Token-based triggers (comments/strings/identifiers never fire), offered
only while the construct is really unclosed (paren stack, pairs.rs for
begin/end). Response types hand-rolled: lsp-types 0.97's item is the old
draft, and vscode-languageclient 9 only makes a SnippetString from
insertText {kind:"snippet"} — shape pinned in unit, e2e and smoke tests.
vfmt.inlineTemplates (default on) turns it off; VS Code extension opts
into the proposed client feature. QA: Eof-sentinel fix so a trigger at
the true end of file still offers.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-25 13:30:43 -07:00
1 parent 382c114492
commit 9d47b6d02b
12 files changed
+1411 -20

No files matched your search

+6 -1
View File
@@ -32,7 +32,12 @@ rayon = "=1.12.0"
# count, build scripts and the versions considered are audited in
# docs/features/vfmt-server/README.md.
lsp-server = "=0.10.0"
lsp-types = "=0.97.0"
# `proposed` is what carries LSP 3.18's `textDocument/inlineCompletion` — the
# params, the client/server capability. Nothing else in the feature is used,
# and the *response* types are hand-rolled in `inline.rs` because 0.97's are
# an older draft than the client implements
# (docs/features/inline-templates/README.md).
lsp-types = { version = "=0.97.0", features = ["proposed"] }
serde = "=1.0.229"
serde_json = "=1.0.140"
+10 -6
View File
@@ -188,7 +188,7 @@ fn module_tier(
if !at_item {
return;
}
let layout = layout(ws, doc, word);
let layout = layout_at(ws, doc, word.start);
let site = Site { semantics: &doc.semantics, offset: word.start };
let names = vlog_refactor::module_names(ws.index(), &word.text);
@@ -270,7 +270,7 @@ fn template_tier(
if !at_item && !at_statement {
return;
}
let layout = layout(ws, doc, word);
let layout = layout_at(ws, doc, word.start);
let dialect = templates::dialect(doc.path.as_deref());
for template in templates::for_dialect(dialect) {
if items.full() {
@@ -296,11 +296,15 @@ fn offered(template: &Template, at_item: bool, at_statement: bool) -> bool {
}
}
/// How generated text is indented here: the line's own indentation, and one
/// step as `vfmt.indent` spells it.
fn layout(ws: &Workspace, doc: &Document, word: &Word) -> Layout {
/// How generated text is indented at `offset`: the line's own indentation, and
/// one step as `vfmt.indent` spells it.
///
/// Shared with `inline.rs`, which offers the same skeletons as ghost text: two
/// features that lay out the same body must not be able to indent it
/// differently.
pub fn layout_at(ws: &Workspace, doc: &Document, offset: u32) -> Layout {
let step = " ".repeat(ws.client_settings().indent.unwrap_or(2));
Layout { base: line_indent(&doc.text, word.start), step }
Layout { base: line_indent(&doc.text, offset), step }
}
/// Tier 4: every reserved word the lexer knows.
+720
View File
@@ -0,0 +1,720 @@
//! `textDocument/inlineCompletion` — the ghost text that finishes a block as
//! you open it.
//!
//! Type `if (` and grey `) begin … end` follows the cursor; type `begin` at the
//! end of a line and its `end` does. Accepting one is a snippet insertion, so
//! the tabstops land the cursor inside the parens first and on the indented
//! body line second.
//!
//! Two things here are deliberate. The **triggers are data** — a keyword, the
//! punctuation that must follow it, the check that says the construct is still
//! unfinished, and a body in `templates.rs`'s `(steps, text)` form — so
//! `case`/`endcase` is one more entry and no more code. And the **response
//! types are hand-rolled**: `lsp_types`' `InlineCompletionItem` is the old 3.18
//! draft (`insertText: String`), while the client in use implements the newer
//! one, where only `insertText: {"kind": "snippet", "value": …}` becomes a
//! snippet and a bare string is inserted as plain text — tabstops and all. See
//! `docs/features/inline-templates/README.md`.
use lsp_types::{Position, Range, Uri};
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::TextRange;
use vlog_refactor::Layout;
use crate::completion::layout_at;
use crate::pairs;
use crate::state::{Document, Workspace};
/// One line of a body: how many indent steps it sits in, and its text. The
/// same shape `templates.rs` writes its skeletons in.
type Line = (u8, &'static str);
/// What must still be unfinished before a trigger offers anything.
///
/// Neither is a parse, and neither can see inside a `` `ifdef `` arm or a macro
/// body. Being wrong costs one grey suggestion the user ignores: nothing is
/// written to the buffer until Tab.
#[derive(Clone, Copy)]
enum Unclosed {
/// The `(` just typed has no `)` anywhere after it — counted over the
/// whole token stream. The snippet writes the `)`, so it may only be
/// offered when one is owed.
Paren,
/// `pairs::analyze` reports *this* keyword — matched by its own span, not
/// by a global count — as an opener that never closed.
Scope,
}
/// One inline template: what the user must have just typed, and what appears
/// behind the cursor when they have.
struct Trigger {
/// The keyword that opens the construct.
keyword: &'static str,
/// The punctuation that must follow the keyword, if any. `if (` needs the
/// open paren — it is what says the user has committed to the `if` rather
/// than to an identifier starting with those letters — and `begin` stands
/// alone.
opener: Option<&'static str>,
gate: Unclosed,
/// The skeleton, written exactly as a `templates.rs` body is: the first
/// line starts at the cursor and every later one is indented.
body: &'static [Line],
}
/// Every construct that offers ghost text.
///
/// Deliberately two. `case`/`endcase` and `module`/`endmodule` fit the table
/// unchanged, and neither was asked for yet.
const TRIGGERS: &[Trigger] = &[
Trigger {
keyword: "if",
opener: Some("("),
gate: Unclosed::Paren,
body: &[(0, "${1:cond}) begin"), (1, "$0"), (0, "end")],
},
Trigger {
keyword: "begin",
opener: None,
gate: Unclosed::Scope,
// The first line is empty: everything this offers goes on the lines
// *after* the `begin` the user just typed.
body: &[(0, ""), (1, "$0"), (0, "end")],
},
];
/// The LSP 3.18 `StringValue` — the only spelling of an inline completion's
/// text that a client turns into a snippet with working tabstops.
#[derive(serde::Serialize)]
pub struct SnippetValue {
/// Always `"snippet"`. Spelled as a field rather than inferred, because
/// the client's check is `typeof insertText === 'string'` and the object
/// arm is what carries the contract.
kind: &'static str,
value: String,
}
/// One inline completion item on the wire.
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InlineItem {
insert_text: SnippetValue,
/// What the item replaces. Always empty and always at the cursor: this
/// inserts, it never replaces, and the protocol requires a range to begin
/// and end on one line.
range: Range,
}
/// The `textDocument/inlineCompletion` result. The list form rather than a
/// bare array, so a later round can add a field beside `items`.
#[derive(serde::Serialize)]
pub struct InlineItems {
pub items: Vec<InlineItem>,
}
/// The ghost text to show at a position, or nothing.
///
/// `None` rather than an empty list wherever there is nothing to say: an
/// editor treats both the same, and `null` is the cheaper answer to a request
/// that arrives on every keystroke.
pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Option<InlineItems> {
if !ws.client_settings().inline_templates.unwrap_or(true) {
return None;
}
let doc = ws.document(uri)?;
// No token stream, no answer — the same trade `completion.rs` makes. A
// half-typed string or block comment is what breaks the lexer, and those
// are exactly the places a ghost `end` would be wrong.
if doc.tokens.is_empty() {
return None;
}
let offset = doc.positions().offset(position);
if !rest_of_line_is_blank(&doc.text, offset) {
return None;
}
let (trigger, opened) = triggered(doc, offset)?;
if !unfinished(doc, trigger, opened) {
return None;
}
let layout = layout_at(ws, doc, offset);
let at = Range { start: position, end: position };
Some(InlineItems {
items: vec![InlineItem {
insert_text: SnippetValue { kind: "snippet", value: render(trigger.body, &layout) },
range: at,
}],
})
}
/// The trigger the tokens ending at `offset` spell, and the span of the one
/// token that must still be waiting for its counterpart: the `(` for a paren
/// gate, the keyword itself for a scope one.
///
/// The cursor must sit *exactly* at the last token's end: that is the crisp
/// "you just typed this" rule, and it is what keeps the body's first character
/// from landing after stray spaces. It is also what makes a comment or a
/// string safe without a single check of its own — a comment is lexer trivia
/// and never a token, and `"if ("` is one `String` token whose text is not a
/// keyword.
fn triggered(doc: &Document, offset: u32) -> Option<(&'static Trigger, TextRange)> {
// `Eof` is a zero-width sentinel `tokenize` appends at `text.len()`, so
// when the buffer's very last byte is the trigger's own last character —
// no trailing newline, nothing typed after it yet — it shares the
// trigger token's `span.end`. Skipping it here is what lets a trigger at
// the true end of the file still fire (QA find, 2026-08-25).
let index = doc
.tokens
.iter()
.rposition(|token| token.kind != TokenKind::Eof && token.span.end <= offset)?;
let last = doc.tokens.get(index)?;
if last.span.end != offset {
return None;
}
for trigger in TRIGGERS {
let keyword = match trigger.opener {
None => last,
Some(punctuation) => {
if !last.is_sym(punctuation) {
continue;
}
let Some(before) = index.checked_sub(1).and_then(|i| doc.tokens.get(i)) else {
continue;
};
before
}
};
if keyword.kind == TokenKind::Keyword && keyword.text == trigger.keyword {
return Some((
trigger,
match trigger.gate {
Unclosed::Paren => last.span,
Unclosed::Scope => keyword.span,
},
));
}
}
None
}
/// Whether the token at `opened` really is still waiting for its counterpart.
fn unfinished(doc: &Document, trigger: &Trigger, opened: TextRange) -> bool {
match trigger.gate {
Unclosed::Paren => !paren_is_closed(&doc.tokens, opened),
Unclosed::Scope => {
pairs::analyze(&doc.tokens).unmatched_open.iter().any(|open| open.span == opened)
}
}
}
/// Whether the `(` at `open` is ever popped by a `)`.
///
/// A stack rather than a count, for the same reason `pairs::analyze` is one: a
/// `)` further down the buffer usually belongs to a `(` of its own, and a
/// running total would let `x = f(1);` on the next line cancel the paren the
/// user just typed.
fn paren_is_closed(tokens: &[Token], open: TextRange) -> bool {
let mut stack: Vec<TextRange> = Vec::new();
for token in tokens {
if token.is_sym("(") {
stack.push(token.span);
} else if token.is_sym(")") && stack.pop() == Some(open) {
return true;
}
}
false
}
/// Whether everything after `offset` on its line is whitespace.
///
/// A trailing `)` or `;` means the line is already finished and the user is
/// editing inside it, not opening a block.
fn rest_of_line_is_blank(text: &str, offset: u32) -> bool {
let Some(tail) = text.get(offset as usize..) else { return false };
let line = tail.split('\n').next().unwrap_or("");
line.chars().all(char::is_whitespace)
}
/// A body laid out at `layout`, tabstops left where they are.
///
/// The first line starts at the cursor, which the editor has already indented,
/// so only the lines after it carry `base`. There is no plain-text spelling
/// here — unlike a completion item, an inline completion has no
/// `snippetSupport` to negotiate.
fn render(body: &[Line], layout: &Layout) -> String {
let mut lines: Vec<String> = Vec::with_capacity(body.len());
for (index, (level, text)) in body.iter().enumerate() {
let mut line = String::new();
if index > 0 {
line.push_str(&layout.base);
for _ in 0..*level {
line.push_str(&layout.step);
}
}
line.push_str(text);
lines.push(line);
}
lines.join("\n")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::settings::ClientSettings;
use crate::uri::path_to_uri;
use std::path::PathBuf;
/// A one-file workspace with `top.sv` open and the cursor at `needle`'s
/// end. No files on disk: nothing here reads the index.
fn asking(text: &str, needle: &str) -> (Workspace, Uri, Position) {
let path = PathBuf::from("/rtl/top.sv");
let uri = path_to_uri(&path).expect("uri");
let mut ws = Workspace::default();
ws.set_document(uri.clone(), text.to_string());
let offset = (text.find(needle).expect("needle present") + needle.len()) as u32;
let position = ws.document(&uri).expect("open").positions().position(offset);
(ws, uri, position)
}
/// The snippet offered at `needle`'s end, if any.
fn offered(text: &str, needle: &str) -> Option<String> {
let (ws, uri, position) = asking(text, needle);
let items = inline_completions(&ws, &uri, position)?;
assert_eq!(items.items.len(), 1, "one ghost or none");
Some(items.items[0].insert_text.value.clone())
}
/// `snippet` with every hole filled in the way the editor would preselect
/// it — the plain text a Tab really produces. The registry's grammar is
/// `${n:default}` and `$n` and nothing else, which
/// `every_hole_is_a_tabstop` pins.
fn filled(snippet: &str) -> String {
let mut out = String::new();
let mut rest = snippet;
while let Some(at) = rest.find('$') {
out.push_str(&rest[..at]);
rest = &rest[at + 1..];
if let Some(braced) = rest.strip_prefix('{') {
let close = braced.find('}').expect("a hole is closed");
let hole = &braced[..close];
out.push_str(hole.split_once(':').map_or("", |(_, default)| default));
rest = &braced[close + 1..];
continue;
}
rest = rest.trim_start_matches(|c: char| c.is_ascii_digit());
}
out.push_str(rest);
out
}
// ------------------------------------------------------------------
// the triggers
// ------------------------------------------------------------------
#[test]
fn an_open_if_paren_offers_the_rest_of_the_block() {
let text = "module top;\n always_comb begin\n if (\n end\nendmodule\n";
assert_eq!(
offered(text, " if (").as_deref(),
Some("${1:cond}) begin\n $0\n end"),
"the site's own indentation, the condition first and the body last"
);
}
#[test]
fn an_else_if_offers_the_same_block() {
let text = "\
module top;
always_comb begin
if (a) begin
end else if (
end
endmodule
";
assert_eq!(
offered(text, "else if (").as_deref(),
Some("${1:cond}) begin\n $0\n end")
);
}
#[test]
fn a_fresh_begin_offers_its_end() {
let text = "module top;\n always_comb begin\nendmodule\n";
assert_eq!(offered(text, "always_comb begin").as_deref(), Some("\n $0\n end"));
}
#[test]
fn the_indent_step_is_the_one_the_client_asked_for() {
let text = "module top;\n always_comb begin\nendmodule\n";
let (mut ws, uri, position) = asking(text, "always_comb begin");
ws.set_client_settings(ClientSettings { indent: Some(4), ..Default::default() });
let items = inline_completions(&ws, &uri, position).expect("a ghost");
assert_eq!(items.items[0].insert_text.value, "\n $0\n end", "base 2 + step 4");
}
#[test]
fn a_tab_indented_line_keeps_its_own_tabs() {
// `base` is the line's leading whitespace as written, not a rebuild of
// it: a buffer indented with tabs must not gain spaces from a ghost.
let text = "module top;\n\talways_comb begin\nendmodule\n";
assert_eq!(offered(text, "always_comb begin").as_deref(), Some("\n\t $0\n\tend"));
}
// ------------------------------------------------------------------
// the negatives
// ------------------------------------------------------------------
#[test]
fn a_comment_or_a_string_never_triggers() {
// Neither is a token: a comment is lexer trivia, and the literal is one
// `String` token whose text is not a keyword.
for (text, needle, what) in [
("module top;\n // if (\nendmodule\n", "// if (", "a line comment"),
("module top;\n /* if ( */\nendmodule\n", "/* if (", "a block comment"),
(
"module top;\n initial $display(\"if (\");\nendmodule\n",
"\"if (",
"inside a string",
),
("module top;\n initial $display(\"begin\");\nendmodule\n", "\"begin", "ditto"),
("module top;\n // begin\nendmodule\n", "// begin", "a commented begin"),
] {
assert_eq!(offered(text, needle), None, "{what}: {text}");
}
}
#[test]
fn an_identifier_that_merely_ends_in_the_keyword_never_triggers() {
let text = "module top;\n always_comb begin\n my_if (\n end\nendmodule\n";
assert_eq!(offered(text, "my_if ("), None, "`my_if` is an identifier");
let text = "module top;\n logic my_begin;\n assign my_begin\nendmodule\n";
assert_eq!(offered(text, "assign my_begin"), None);
}
#[test]
fn a_line_with_anything_after_the_cursor_never_triggers() {
let text =
"module top;\n always_comb begin\n if (a) begin\n end\n end\nendmodule\n";
assert_eq!(offered(text, " if ("), None, "the condition is already written");
let text = "module top;\n always_comb begin ; end\nendmodule\n";
assert_eq!(offered(text, "always_comb begin"), None);
}
#[test]
fn whitespace_between_the_keyword_and_the_cursor_never_triggers() {
// The cursor must be exactly at the token's end — "you just typed
// this", and nothing looser.
let text = "module top;\n always_comb begin \nendmodule\n";
assert_eq!(offered(text, "always_comb begin "), None);
let text = "module top;\n always_comb begin\n if ( \n end\nendmodule\n";
assert_eq!(offered(text, "if ( "), None);
}
#[test]
fn a_begin_that_already_has_its_end_offers_nothing() {
// The `end` below belongs to the `begin` just typed — `pairs::analyze`
// matches them — so a second one would break the file.
let text = "\
module top;
always_comb begin
begin
end
end
endmodule
";
assert_eq!(offered(text, " begin"), None, "the inner begin is matched");
// ...and the one that really is unclosed still offers.
let text = "module top;\n always_comb begin\n end\n initial begin\nendmodule\n";
assert!(offered(text, "initial begin").is_some(), "this one lost its end");
}
#[test]
fn an_if_paren_that_is_already_closed_offers_nothing() {
// A `)` further down the buffer is the one this `(` will pair with;
// writing a second would leave the file unbalanced the other way.
let text = "module top;\n always_comb begin\n if (\n a) begin\n end\n end\nendmodule\n";
assert_eq!(offered(text, " if ("), None);
}
#[test]
fn a_later_call_does_not_cancel_the_paren_just_typed() {
// A running `(` minus `)` count would see the `)` of `f(1)` below and
// decide this `(` was already closed. It is a stack, so the call's own
// paren pairs with its own closer and the `if (` stays open.
let text = "\
module top;
always_comb begin
if (
x = f(1);
end
endmodule
";
assert_eq!(
offered(text, " if (").as_deref(),
Some("${1:cond}) begin\n $0\n end")
);
}
#[test]
fn a_paren_the_line_below_closes_still_counts_as_closed() {
// The mirror of the test above: when the `)` really is this `(`'s own,
// no ghost — even though a plain "is anything unbalanced" check on the
// rest of the file would say yes because of the `f(` beside it.
let text = "\
module top;
always_comb begin
if (
f(1) > 0) begin
end
end
endmodule
";
assert_eq!(offered(text, " if ("), None);
}
#[test]
fn a_buffer_that_does_not_lex_is_declined() {
let text = "module top;\n /* unterminated\n always_comb begin\n";
let (ws, uri, position) = asking(text, "always_comb begin");
assert!(ws.document(&uri).expect("open").tokens.is_empty(), "premise: no tokens");
assert!(inline_completions(&ws, &uri, position).is_none());
}
#[test]
fn a_trigger_at_the_true_end_of_file_still_offers_a_ghost() {
// QA find, 2026-08-25: `tokenize` appends a zero-width `Eof` token
// whose span starts and ends at `text.len()`. When the file's very
// last byte is the trigger's own last character — no trailing
// newline, nothing typed after it yet — that `Eof` token shares the
// trigger token's `span.end`, and `rposition` (searching from the
// back) finds the `Eof` first. `triggered` then compares a
// `TokenKind::Eof` against `TokenKind::Keyword` and silently declines
// — exactly the moment a user typing at the end of a growing file
// most wants the ghost text to appear.
let text = "module top;\n always_comb begin";
let (ws, uri, position) = asking(text, "always_comb begin");
assert!(
inline_completions(&ws, &uri, position).is_some(),
"the file ends right after `begin`, with no Eof-adjacency confusion"
);
let text = "module top;\n always_comb begin\n if (";
let (ws, uri, position) = asking(text, " if (");
assert!(
inline_completions(&ws, &uri, position).is_some(),
"same for `if (` at true end of file"
);
}
#[test]
fn a_deeply_nested_file_neither_crashes_nor_misses_the_trigger() {
// History: the one recursion-depth bug this codebase had was in the
// *parser*'s AST (TODO.md §1, fixed by `MAX_NESTING_DEPTH`). This
// module never walks that tree — `triggered`/`unfinished` read
// `doc.tokens` and `pairs::analyze`, both flat loops over the token
// stream, so neither can overflow the stack the way the parser once
// did. QA find, 2026-08-25: those flat loops are not all *linear*,
// though — `pairs::analyze` is quadratic in the depth of rainbow
// nesting (`pairs.rs:157`), which this module now calls on every
// keystroke inside an unclosed `begin`. 3,000 is past where that
// shows up in a debug build (tens of ms) without making this test
// itself slow; see the QA log for the full characterization.
let depth = 3_000;
let mut text = String::from("module top;\n");
for _ in 0..depth {
text.push_str(" begin\n");
}
// A trailing newline, so this test isolates depth from the separate
// true-end-of-file `Eof`-adjacency case pinned above.
text.push_str("initial begin\n");
let (ws, uri, position) = asking(&text, "initial begin");
assert!(!ws.document(&uri).expect("open").tokens.is_empty(), "the lexer never recurses");
let items = inline_completions(&ws, &uri, position);
assert!(items.is_some(), "the innermost, truly unclosed `begin` still offers its `end`");
}
#[test]
fn an_empty_file_at_zero_zero_offers_nothing_and_does_not_panic() {
let mut ws = Workspace::default();
let uri = path_to_uri(&PathBuf::from("/rtl/empty.sv")).expect("uri");
ws.set_document(uri.clone(), String::new());
assert!(inline_completions(&ws, &uri, Position { line: 0, character: 0 }).is_none());
}
#[test]
fn a_position_past_the_end_of_its_line_clamps_rather_than_panics() {
// Clients do send these — a keystroke can outrun the position the
// client had in hand. `convert.rs`'s `offset` clamps it to the line's
// real content end, which here happens to land exactly on the
// trigger, so the ghost still appears rather than nothing panicking
// but nothing offered either.
let text = "module top;\n always_comb begin\nendmodule\n";
let (ws, uri, _) = asking(text, "always_comb begin");
let items = inline_completions(&ws, &uri, Position { line: 1, character: 9_999 });
assert!(items.is_some(), "clamped to right after `begin`, same as the exact position");
// (0, 0) on a non-empty file: nowhere near a trigger, not a panic.
assert!(inline_completions(&ws, &uri, Position { line: 0, character: 0 }).is_none());
}
#[test]
fn no_space_between_the_keyword_and_the_paren_still_triggers() {
// Token spans carry no inter-token whitespace of their own, so `if(`
// and `if (` must be indistinguishable to `triggered`.
let text = "module top;\n always_comb begin\n if(\n end\nendmodule\n";
assert_eq!(
offered(text, " if(").as_deref(),
Some("${1:cond}) begin\n $0\n end")
);
}
#[test]
fn crlf_line_endings_still_trigger_and_indent_correctly() {
// `rest_of_line_is_blank` splits on `\n` alone, so a CRLF file's `\r`
// rides along in the slice — `char::is_whitespace('\r')` is `true`,
// so it still reads as "nothing after the cursor".
let text = "module top;\r\n always_comb begin\r\nendmodule\r\n";
assert_eq!(offered(text, "always_comb begin").as_deref(), Some("\n $0\n end"));
let text = "module top;\r\n always_comb begin\r\n if (\r\n end\r\nendmodule\r\n";
assert_eq!(
offered(text, " if (").as_deref(),
Some("${1:cond}) begin\n $0\n end")
);
}
#[test]
fn an_unknown_document_is_declined() {
let ws = Workspace::default();
let uri = path_to_uri(&PathBuf::from("/rtl/gone.sv")).expect("uri");
assert!(inline_completions(&ws, &uri, Position { line: 0, character: 0 }).is_none());
}
#[test]
fn the_setting_turns_the_whole_feature_off() {
let text = "module top;\n always_comb begin\nendmodule\n";
let (mut ws, uri, position) = asking(text, "always_comb begin");
assert!(inline_completions(&ws, &uri, position).is_some(), "premise: on by default");
ws.set_client_settings(ClientSettings {
inline_templates: Some(false),
..Default::default()
});
assert!(inline_completions(&ws, &uri, position).is_none());
ws.set_client_settings(ClientSettings {
inline_templates: Some(true),
..Default::default()
});
assert!(inline_completions(&ws, &uri, position).is_some(), "and back on again");
}
// ------------------------------------------------------------------
// the registry's own hygiene
// ------------------------------------------------------------------
#[test]
fn every_hole_is_a_tabstop() {
// The editor-snippets lesson: VS Code substitutes an unknown `$NAME`
// with nothing and says nothing, so a system task written into a body
// would vanish silently. None is written today; this is what stops one
// being added unescaped.
for trigger in TRIGGERS {
for (_, line) in trigger.body {
let mut rest = *line;
while let Some(at) = rest.find('$') {
rest = &rest[at + 1..];
assert!(
rest.starts_with('{') || rest.starts_with(|c: char| c.is_ascii_digit()),
"`{}`: `${}` is not a tabstop",
trigger.keyword,
rest.chars().next().unwrap_or(' ')
);
}
}
}
}
#[test]
fn every_accepted_ghost_parses() {
// What Tab really writes, planted where the trigger fires, handed to
// the parser. A body that did not parse would be a formatter that
// refuses the file the moment the user accepts a suggestion.
let layout = Layout { base: " ".into(), step: " ".into() };
for trigger in TRIGGERS {
let typed = match trigger.opener {
Some(punctuation) => format!("{} {punctuation}", trigger.keyword),
None => trigger.keyword.to_string(),
};
let text = filled(&render(trigger.body, &layout));
let probe = format!(
"module vfmt_probe;\n always_comb begin\n {typed}{text}\n end\nendmodule\n"
);
let (_, diagnostics) = vlog_parser::parse_source_tolerant(&probe);
assert!(
diagnostics.is_empty(),
"`{}` does not parse:\n{probe}\n{diagnostics:#?}",
trigger.keyword
);
}
}
#[test]
fn every_trigger_word_is_a_keyword_the_lexer_knows() {
// The detection compares against `TokenKind::Keyword`, so a trigger
// naming a word the lexer calls an identifier could never fire.
for trigger in TRIGGERS {
assert!(
vlog_parser::KEYWORDS.contains(&trigger.keyword),
"`{}` is not a keyword",
trigger.keyword
);
}
}
// ------------------------------------------------------------------
// the wire
// ------------------------------------------------------------------
#[test]
fn the_wire_shape_is_what_the_client_reads() {
// The whole reason these types are hand-rolled. `lsp-types` 0.97 spells
// `insertText` as a bare `String`, and `vscode-languageclient`'s
// `asInlineCompletionItem` inserts a bare string as **plain text** —
// every `${1:cond}` would appear literally in the buffer. Only the
// `{"kind": "snippet"}` object becomes a `SnippetString`. If a future
// `lsp-types` bump tempts anyone to use its item type, this fails.
let text = "module top;\n always_comb begin\nendmodule\n";
let (ws, uri, position) = asking(text, "always_comb begin");
let items = inline_completions(&ws, &uri, position).expect("a ghost");
assert_eq!(
serde_json::to_value(&items).expect("serializes"),
serde_json::json!({
"items": [{
"insertText": { "kind": "snippet", "value": "\n $0\n end" },
"range": {
"start": { "line": 1, "character": 19 },
"end": { "line": 1, "character": 19 }
}
}]
})
);
}
#[test]
fn the_range_is_empty_and_at_the_cursor() {
// The protocol requires a range to begin and end on one line, and this
// item inserts rather than replaces — so the only honest range is the
// caret itself.
let text = "module top;\n always_comb begin\nendmodule\n";
let (ws, uri, position) = asking(text, "always_comb begin");
let items = inline_completions(&ws, &uri, position).expect("a ghost");
assert_eq!(items.items[0].range.start, position);
assert_eq!(items.items[0].range.end, position);
}
#[test]
fn a_multibyte_line_puts_the_range_where_the_cursor_really_is() {
// The `é` is 2 bytes and 1 UTF-16 unit; a byte-based position would
// put the ghost one column late.
let text = "module top;\n // é\n always_comb begin\nendmodule\n";
let (ws, uri, position) = asking(text, "always_comb begin");
let items = inline_completions(&ws, &uri, position).expect("a ghost");
assert_eq!(items.items[0].range.start, Position { line: 2, character: 19 });
}
}
+12
View File
@@ -18,6 +18,7 @@ mod hierarchy;
mod hover;
mod includes;
mod inlay;
mod inline;
mod instantiations;
mod lint;
mod locate;
@@ -164,6 +165,13 @@ fn capabilities() -> ServerCapabilities {
// instantiation is the call. Every item is complete when it is
// returned, and the client drives the expansion one hop at a time.
call_hierarchy_provider: Some(CallHierarchyServerCapability::Simple(true)),
// Ghost text for `if (` and `begin`, LSP 3.18. `true` rather than
// options: there is nothing to configure on the server side, and the
// one thing a user can say — `vfmt.inlineTemplates` — is a setting the
// handler reads, not a registration option. The VS Code client only
// sends the request after opting into `ProposedFeatures`, so an
// extension older than this server simply never asks.
inline_completion_provider: Some(OneOf::Left(true)),
semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensOptions(
SemanticTokensOptions {
work_done_progress_options: WorkDoneProgressOptions::default(),
@@ -186,6 +194,9 @@ fn initialize_result() -> lsp_types::InitializeResult {
name: "vfmt-server".to_string(),
version: Some(env!("CARGO_PKG_VERSION").to_string()),
}),
// `lsp-types`' `proposed` feature adds an `offsetEncoding` field here
// (clangd's unofficial extension). It is not ours to send.
..Default::default()
}
}
@@ -243,6 +254,7 @@ mod tests {
assert!(caps.signature_help_provider.is_some());
assert!(caps.inlay_hint_provider.is_some());
assert!(caps.call_hierarchy_provider.is_some());
assert!(caps.inline_completion_provider.is_some());
}
#[test]
+20 -9
View File
@@ -18,9 +18,9 @@ use lsp_types::request::{
CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls, CallHierarchyPrepare,
CodeActionRequest, Completion, DocumentHighlightRequest, DocumentLinkRequest,
DocumentSymbolRequest, ExecuteCommand, FoldingRangeRequest, Formatting, GotoDefinition,
HoverRequest, InlayHintRequest, PrepareRenameRequest, RangeFormatting, References,
RegisterCapability, Rename, Request as _, SemanticTokensFullRequest, SignatureHelpRequest,
UnregisterCapability, WorkspaceSymbolRequest,
HoverRequest, InlayHintRequest, InlineCompletionRequest, PrepareRenameRequest, RangeFormatting,
References, RegisterCapability, Rename, Request as _, SemanticTokensFullRequest,
SignatureHelpRequest, UnregisterCapability, WorkspaceSymbolRequest,
};
use lsp_types::{
CallHierarchyIncomingCallsParams, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams,
@@ -29,10 +29,10 @@ use lsp_types::{
DidOpenTextDocumentParams, DidSaveTextDocumentParams, DocumentFormattingParams,
DocumentHighlightParams, DocumentLinkParams, DocumentRangeFormattingParams,
DocumentSymbolParams, DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams,
GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams, LogMessageParams,
MessageType, Position, PublishDiagnosticsParams, ReferenceParams, RegistrationParams,
RenameParams, SemanticTokensParams, SemanticTokensResult, ShowMessageParams,
SignatureHelpParams, TextDocumentPositionParams, UnregistrationParams, Uri,
GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams,
InlineCompletionParams, LogMessageParams, MessageType, Position, PublishDiagnosticsParams,
ReferenceParams, RegistrationParams, RenameParams, SemanticTokensParams, SemanticTokensResult,
ShowMessageParams, SignatureHelpParams, TextDocumentPositionParams, UnregistrationParams, Uri,
WorkspaceSymbolParams, WorkspaceSymbolResponse,
};
use serde::de::DeserializeOwned;
@@ -40,8 +40,8 @@ use serde_json::Value;
use crate::state::Workspace;
use crate::{
code_action, completion, diagnostics, folding, format, hierarchy, hover, includes, inlay, nav,
pairs, ports, rename, settings, signature, symbols, tokens, watch,
code_action, completion, diagnostics, folding, format, hierarchy, hover, includes, inlay,
inline, nav, pairs, ports, rename, settings, signature, symbols, tokens, watch,
};
/// What the client said it can do, read once at `initialize` because that is
@@ -295,6 +295,17 @@ impl Server {
completion::completions(&self.workspace, &uri, position, self.abilities.snippets)
.map_or(Ok(Value::Null), to_value)
}),
// Ghost text. `null` for every position that is not one of the
// two triggers, which is nearly all of them — the request arrives
// on every keystroke, so the decline has to be the cheap path.
InlineCompletionRequest::METHOD => {
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)
.map_or(Ok(Value::Null), to_value)
})
}
SignatureHelpRequest::METHOD => decode(request).and_then(|p: SignatureHelpParams| {
let at = p.text_document_position_params;
let (uri, position) = (at.text_document.uri, at.position);
+37 -2
View File
@@ -42,6 +42,10 @@ pub struct ClientSettings {
/// or relative to the workspace root. Empty means "unset", which is what
/// the VS Code default is — see `docs/features/filelist/README.md`.
pub filelist: Option<String>,
/// `vfmt.inlineTemplates`: whether `if (` and `begin` grow ghost text.
/// Unset means on, which is what the VS Code default declares — see
/// `docs/features/inline-templates/README.md`.
pub inline_templates: Option<bool>,
}
/// Read the `vfmt` section out of a `workspace/didChangeConfiguration` payload.
@@ -65,9 +69,18 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
indent: bounded(vfmt.get("indent"), INDENT_RANGE),
exclude: strings(vfmt.get("exclude")),
filelist: path(vfmt.get("filelist")),
inline_templates: flag(vfmt.get("inlineTemplates")),
}
}
/// A JSON boolean, or nothing. `as_bool` rejects the string `"false"` and the
/// number `0` along with everything else that is not a boolean: a wrong-typed
/// value is dropped here exactly as it is everywhere else in this module, and
/// the setting falls back to its own default rather than to a guess.
fn flag(value: Option<&Value>) -> Option<bool> {
value?.as_bool()
}
/// A non-empty JSON string, or nothing. The empty string is `vfmt.filelist`'s
/// default and means "no filelist", not "the filelist named by the empty
/// path"; anything that is not a string is dropped like every other
@@ -118,7 +131,8 @@ mod tests {
"lineLength": line_length,
"indent": indent,
"exclude": exclude,
"filelist": ""
"filelist": "",
"inlineTemplates": true
}
})
}
@@ -150,8 +164,29 @@ mod tests {
fn the_default_vscode_payload_is_no_opinion_about_anything() {
// Every setting at its `package.json` default: nulls and an empty
// list, which must leave today's behaviour exactly unchanged.
// `inlineTemplates` is the one default that is not "no opinion" — it
// defaults to `true`, and `None` resolves to the same thing.
let found = settings(vscode_payload(json!(null), json!(null), json!([])));
assert_eq!(found, ClientSettings::default());
assert_eq!(
found,
ClientSettings { inline_templates: Some(true), ..Default::default() },
"the only difference from silence must be the one setting whose \
default is not null"
);
}
#[test]
fn inline_templates_is_a_boolean_and_nothing_else() {
let found = settings(json!({ "vfmt": { "inlineTemplates": false } }));
assert_eq!(found.inline_templates, Some(false));
let found = settings(json!({ "vfmt": { "inlineTemplates": true } }));
assert_eq!(found.inline_templates, Some(true));
// Absence is not `false`: the feature is on unless a client says no.
assert_eq!(settings(json!({ "vfmt": {} })).inline_templates, None);
for bad in [json!("false"), json!(0), json!(null), json!([false]), json!({ "on": false })] {
let found = settings(json!({ "vfmt": { "inlineTemplates": bad } }));
assert_eq!(found.inline_templates, None, "inlineTemplates {bad} must be ignored");
}
}
#[test]
+134
View File
@@ -1336,6 +1336,140 @@ fn a_client_without_snippet_support_gets_the_skeleton_as_plain_text() {
let _ = std::fs::remove_dir_all(&dir);
}
/// Ghost text over the wire: the capability, the two triggers, and the shape
/// of the item — which is the whole contract, because a `lsp-types` bump that
/// changed `InlineCompletionItem` would turn a working snippet into a literal
/// `${1:cond}` in the user's buffer.
#[test]
fn inline_templates_round_trip_over_the_wire() {
let dir = temp_dir("inline");
// Line 1 ends in a `begin` with no `end`; line 2 is an `if (` with nothing
// after it, inside the block that begin opened.
let top = "module top;\n always_comb begin\n if (\nendmodule\n";
let path = dir.join("top.sv");
std::fs::write(&path, top).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", path.display());
let ask = |id: u32, line: u32, character: u32| {
frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/inlineCompletion","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":{line},"character":{character}}},"context":{{"triggerKind":2}}}}}}"#
))
};
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"inlineCompletion":{{"dynamicRegistration":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(top).expect("json")
)),
// Just after the `begin` on line 1, and just after the `(` on line 2.
ask(2, 1, 19),
ask(3, 2, 8),
// ...and in the middle of the `always_comb` keyword, where there is
// nothing to offer at all.
ask(4, 1, 8),
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 capabilities = &messages.iter().find(|m| m["id"] == 1).expect("initialize response")
["result"]["capabilities"];
assert_eq!(capabilities["inlineCompletionProvider"], serde_json::json!(true));
let items = |id: u32| {
let response = messages.iter().find(|m| m["id"] == id).expect("a response");
response["result"].clone()
};
// The `begin` trigger: a newline, an indented tabstop, and the `end`
// aligned with the line the `begin` sits on.
assert_eq!(
items(2),
serde_json::json!({
"items": [{
"insertText": { "kind": "snippet", "value": "\n $0\n end" },
"range": {
"start": { "line": 1, "character": 19 },
"end": { "line": 1, "character": 19 }
}
}]
}),
"the exact wire shape the client turns into a SnippetString"
);
// The `if (` trigger, from inside the same block.
let item = &items(3)["items"][0];
assert_eq!(item["insertText"]["kind"], "snippet");
assert_eq!(item["insertText"]["value"], "${1:cond}) begin\n $0\n end");
assert_eq!(item["range"]["start"], item["range"]["end"], "an insertion, not a replacement");
assert_eq!(items(4), serde_json::Value::Null, "nowhere near a trigger");
let _ = std::fs::remove_dir_all(&dir);
}
/// `vfmt.inlineTemplates` really suppresses the request handler when pushed
/// over the wire — the link a unit test cannot check, since
/// `inline.rs`'s own tests call `Workspace::set_client_settings` directly
/// rather than going through `workspace/didChangeConfiguration`.
#[test]
fn the_inline_templates_setting_is_honoured_over_the_wire() {
let dir = temp_dir("inline_setting");
let top = "module top;\n always_comb begin\nendmodule\n";
let path = dir.join("top.sv");
std::fs::write(&path, top).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", path.display());
let ask = |id: u32| {
frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/inlineCompletion","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":19}},"context":{{"triggerKind":2}}}}}}"#
))
};
let push = |setting: &str| {
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"vfmt":{{"inlineTemplates":{setting}}}}}}}}}"#
))
};
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(top).expect("json")
)),
// No push yet: the VS Code default is on.
ask(2),
push("false"),
ask(3),
// Mid-session, no restart, flips back on.
push("true"),
ask(4),
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 items = |id: u32| {
let response = messages.iter().find(|m| m["id"] == id).expect("a response");
response["result"].clone()
};
assert_ne!(items(2), serde_json::Value::Null, "on by default, nothing pushed yet");
assert_eq!(items(3), serde_json::Value::Null, "inlineTemplates: false suppresses it");
assert_ne!(items(4), serde_json::Value::Null, "inlineTemplates: true turns it back on");
let _ = std::fs::remove_dir_all(&dir);
}
/// The general tiers over the wire: keywords, project words and the two
/// places a completion list must not appear.
#[test]
+422
View File
@@ -0,0 +1,422 @@
# inline-templates
## Goal
Ghost text that finishes a block as you open it. Type `if (` and grey
`) begin … end` appears after the cursor; press Tab and the snippet is
inserted with the cursor inside the parens, a second Tab jumping to the
indented body line. Type `begin` at the end of a line and the matching
`end` appears the same way. This is LSP 3.18's
`textDocument/inlineCompletion`, served by `vfmt-server` and opted into by
the VS Code extension. It is the completion-templates tier without the
completion widget: the same skeletons, offered at the moment the user has
already committed to the construct, so accepting one costs a single key.
## Assumptions
- **The client understands snippet inline completions.** LSP 3.18 gives no
way to negotiate that, unlike `completionItem.snippetSupport`: the
`InlineCompletionClientCapabilities` the protocol defines carries only
`dynamicRegistration`. Every item is therefore sent as
`insertText: { "kind": "snippet", "value": … }`, the 3.18 `StringValue`
shape, which is the only spelling `vscode-languageclient` turns into a
working `SnippetString`. A client that ignored the object and rendered it
as text would show literal `${1:cond}` — no client in use does, and the
request is only ever sent by a client that registered for it.
- **Trigger detection reads the token stream, never the raw text.** A
buffer that does not lex has no tokens, so it is silently declined —
the same trade `completion.rs` makes, and for the same reason (an open
string or block comment is the commonest way to break the lexer while
typing).
- **The suppression heuristic is a token-stream match, not a parse.** See
Handshakes below for the exact rule and what it cannot see (`` `ifdef ``
arms, macro bodies). Being wrong costs one unwanted grey suggestion the
user ignores, never a buffer edit — nothing is inserted until Tab.
- **There is no position gate**, unlike the completion tier's
`at_statement` / `at_item`. Having just typed `if (` or `begin` at the
end of a line is already a far stronger signal than a two-letter prefix
in a completion list, and both bodies are legal at *both* positions
anyway: `if (…) begin … end` is a statement inside a procedural block
and a conditional generate construct at module scope, and a bare
`begin … end` is a block in either. Adding the gate would only cost
correct suggestions in the places the heuristic misreads.
- **`vfmt.inlineTemplates` unset means on.** Every other `vfmt.*` setting
is "no opinion until a client says otherwise"; this one's absence
resolves to `true`, which is what the VS Code default declares.
- The indent step is `vfmt.indent`, falling back to 2 — exactly what the
template tier of `completion.rs` uses. The server does not read
`vfmt.toml` for this (it does not read it for completion either).
## Handshakes
**Consumed**
- `vlog_parser::token::{Token, TokenKind}` — the lexed buffer on
`Document.tokens`. Keyword identity is `kind == Keyword && text == …`,
so `my_if (`, `// if (` and `"if ("` cannot trigger: an identifier is
`Ident`, a comment is trivia and never a token, and a string literal is
one `String` token.
- `crate::pairs::analyze` — the scope matcher. The `begin` trigger fires
only when `analyze` reports *this* `begin` (matched by its own span) in
`unmatched_open`. That is stricter and more honest than a global count:
`always_comb begin` / freshly typed `begin` / `end` leaves the *new*
`begin` matched by the existing `end`, and no ghost appears.
- `crate::completion::layout_at` — **new, exported for this module.** It is
the body of what used to be `completion.rs`'s private `layout`, taken by
offset instead of by `Word`, so the ghost body and the completion-list
template are indented by one function and cannot drift. `completion.rs`
now calls it too.
- `crate::settings::ClientSettings::inline_templates` — **new field**,
`Option<bool>` from `vfmt.inlineTemplates`. Nothing else reads it;
`Workspace::set_client_settings` does not treat it as a scope change, so
toggling it rebuilds no index.
- `vlog_refactor::Layout` — `{ base, step }`, rendered exactly as
`templates.rs` renders a body.
**Promised**
- `textDocument/inlineCompletion` (LSP 3.18, proposed in `lsp-types`),
advertised as `inlineCompletionProvider: true`. The result is
`{"items": [ { "insertText": {"kind": "snippet", "value": … },
"range": … } ]}` or `null`. The `range` is always empty and always at
the cursor: the item inserts, it never replaces, and the protocol
requires a range to begin and end on one line.
`the_wire_shape_is_what_the_client_reads` pins that JSON, so a future
`lsp-types` bump that changes `InlineCompletionItem` cannot silently
turn the snippet into plain text.
- Root `Cargo.toml`: `lsp-types` gains `features = ["proposed"]`. That
feature also adds `offset_encoding` fields to `ClientCapabilities`,
`InitializeResult` and `TextDocumentClientCapabilities` — all
`Option`, all `skip_serializing_if`, so nothing on the wire changes.
`main.rs`'s `InitializeResult` literal gained a `..Default::default()`
for it.
## Status / TODO
- [x] `crates/vfmt_server/src/inline.rs`: the data-driven trigger table,
detection over the token stream, the suppression check, the renderer
and the hand-rolled wire types
- [x] `if (` trigger (and `else if (`, which is the same two tokens)
- [x] `begin` trigger
- [x] Suppression: unclosed `(` for the paren trigger, `pairs.rs` says
"this opener never closed" for the scope trigger
- [x] `vfmt.inlineTemplates` in `settings.rs` and in the extension's
`package.json`
- [x] Capability in `main.rs`, dispatch in `server.rs`
- [x] VS Code opt-in: `client.registerFeatures(ProposedFeatures.createAll(client))`
- [x] `editors/nvim/README.md` note
- [x] Unit tests: triggers, negatives, indentation, the serialized shape
- [x] End-to-end test in `crates/vfmt_server/tests/e2e.rs`
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test` green
## Work log
**2026-08-25 — dev**
- Read `templates.rs`, `completion.rs`, `pairs.rs`, `settings.rs`, the
vendored `[email protected]` and `[email protected]`'s
`inline_completion.rs` before writing anything.
- **Confirmed the protocol trap the lead flagged.** `lsp-types` 0.97's
`InlineCompletionItem` is the *old* 3.18 draft (`insert_text: String` +
`insert_text_format`), while `protocolConverter.js`'s
`asInlineCompletionItem` implements the *new* one: a string `insertText`
becomes plain text and only `insertText.value` becomes a
`SnippetString`. So the response types are hand-rolled serde structs in
`inline.rs` and only `InlineCompletionParams` / `InlineCompletionOptions`
come from `lsp-types`. `the_wire_shape_is_what_the_client_reads` asserts
the exact JSON.
- **The trigger table is data.** One `Trigger` is a keyword, an optional
punctuation token that must follow it, which kind of "still unfinished"
check gates it, and a body in `templates.rs`'s `(steps, text)` form.
Adding `case` → `endcase` or `module` → `endmodule` later is one entry
and nothing else; only the two the round asked for ship.
- **Cursor contract: exactly at the last token's end.** Whitespace between
the trigger token and the cursor is not accepted, so `begin |` offers
nothing. It is the crisp "you just typed this" rule, and it keeps the
rendered body's first character from landing after stray spaces.
- **Suppression.** Two checks, one per trigger kind, and both ask the same
question: *is the token the user just typed ever given its counterpart?*
`Unclosed::Scope` asks `pairs::analyze` whether the very keyword just
typed is in `unmatched_open`. `Unclosed::Paren` runs the same shape of
stack over `(`/`)` and asks whether this `(` is ever popped.
**A running count was wrong** and was replaced before shipping: with
`if (` on one line and `x = f(1);` on the next, a `(` minus `)` total is
zero and the ghost would vanish, because the call's closer cancelled the
user's opener. `a_later_call_does_not_cancel_the_paren_just_typed` and
`a_paren_the_line_below_closes_still_counts_as_closed` pin both sides.
- **Rendering.** A local 10-line renderer rather than reaching into
`templates::Template`: the bodies here are this module's own const, only
the snippet spelling is ever needed (there is no plain-text negotiation
to fall back to), and `Template::render`'s second spelling and its
`Defaults` machinery would be dead weight. The layout itself *is*
shared — `completion::layout_at` — so the two features cannot indent
differently.
- Guard tests carried over from `templates.rs` in spirit: every trigger's
body, with its holes filled in, is planted in a module and must parse;
every `$` in every body must start a tabstop.
- `node editors/vscode/smoke.js` run and green against both the debug and
the release binary. It now asserts `inlineCompletionProvider` is
advertised, sends a real `textDocument/inlineCompletion` at the `begin`
of its already-existing "lost its `end`" buffer, and checks the
`{kind:"snippet"}` object and its value — the pre-publish check now
covers this feature end to end from a plain node client. The
extension's `registerFeatures` line itself is exercised only by review:
it needs a running VS Code.
- **`TODO.md` untouched** — no existing item covers this. The nearest
match, "Backlog (extract module, **inline**, …)", is the *inline
function* refactoring, not ghost text; the M1–M14 milestone list has no
entry to check off.
- Final: `cargo fmt --all -- --check` clean, `cargo clippy --all-targets`
zero warnings, `cargo test` 1607 passed / 0 failed across the
workspace.
## QA log
**2026-08-25 — QA**
**Verdict: pass, with one bug found and fixed, and one out-of-scope
performance finding filed separately.** Build/lint/test all clean; the wire
contract matches the vendored client exactly; the trigger heuristics hold up
under adversarial input except for one true-EOF edge case, fixed below.
**Build / lint / test**
- `cargo fmt --all -- --check`: clean.
- `cargo clippy --all-targets --workspace -- -D warnings`: zero warnings.
- `cargo test --workspace`: 1614 passed / 0 failed / 0 ignored-unexpectedly
(up from the dev's 1607 — this log's new tests). Full tail at the bottom.
- `node editors/vscode/smoke.js <path>`: OK against both a fresh debug and a
fresh release build. **Caveat, not a code defect:** running it with no
argument picks up whatever `vfmt-server` is on `$PATH` — on this machine an
Aug-24 build predating this feature, which fails with `capability missing:
inlineCompletionProvider`. Anyone re-running the dev's "smoke.js against
debug and release" claim should pass the binary path explicitly, the way
the dev's own work log implies they did.
**Wire contract (item 2)** — read
`editors/vscode/node_modules/vscode-languageclient/lib/common/protocolConverter.js:1039`
(`asInlineCompletionItem`) directly:
- `typeof item.insertText === 'string'` → plain text; the object arm →
`new code.SnippetString(item.insertText.value)`. Confirmed the server's
`SnippetValue.kind` field is *never actually read* by this code path — only
`typeof insertText` decides — so `kind` documents intent rather than being
load-bearing, which is exactly what `inline.rs:89-93`'s comment already
says. Not a bug, just confirming the claim.
- `item.filterText` and `item.command` are read only if truthy; `InlineItem`
sends neither, so both branches are skipped — no crash, matches
`the_wire_shape_is_what_the_client_reads`'s pinned JSON.
- `ProposedFeatures` is exported end-to-end:
`lib/common/client.js:1591` defines it and gates `createAll` to exactly
`[new InlineCompletionItemFeature(_client)]`; `lib/common/api.js:27`
re-exports `client.js`; `lib/node/main.js:34` re-exports `common/api.js`.
So `require('vscode-languageclient/node').ProposedFeatures` in
`extension.js` really does resolve to it.
- `lib/common/inlineCompletion.js:16-19`: `fillClientCapabilities` sets
`textDocument.inlineCompletion.dynamicRegistration = true` — matches the
`initialize` request body the new e2e test sends.
- `lib/common/features.js:230-235`: `getRegistrationOptions` accepts a bare
boolean capability (`Is.boolean(capability) && capability === true`), so
`main.rs`'s `inline_completion_provider: Some(OneOf::Left(true))` registers
correctly without an options object — verified this is the same pattern
`call_hierarchy_provider` already uses.
- `extension.js:79` (`registerFeatures`) runs before `:126` (`start()`) —
correct order; features must register before initialize.
**Trigger-logic attacks (item 3)** — everything on the requested list was
tried; results:
- `if (` / `begin` in a line comment, a block comment, inside a string: all
declined (dev's own tests, verified still passing).
- `my_if (`: declined (identifier, not `Keyword`).
- `if (` / `begin` with text after the cursor on the line: declined.
- `if(` **no space**: added `no_space_between_the_keyword_and_the_paren_still_triggers`
(`inline.rs`) — triggers correctly; token spans carry no inter-token
whitespace so this was never actually at risk, but it was untested.
- `else if (`: offers the same block (dev's test).
- Nested `begin`s, only the innermost unmatched: dev's
`a_begin_that_already_has_its_end_offers_nothing` covers both directions.
- Every `begin`/`end` balanced: offers nothing (implied by the same test;
the matched inner `begin` gets nothing).
- `begin` mid-line with code after: declined
(`a_line_with_anything_after_the_cursor_never_triggers`).
- Cursor one char before/after an unclosed `begin`'s end: the `span.end ==
offset` equality check in `triggered` makes this structurally impossible to
get wrong — a token not ending exactly at the cursor is never `last`.
`whitespace_between_the_keyword_and_the_cursor_never_triggers` covers the
"one char after" case directly.
- **CRLF line endings**: untested by the dev. Added
`crlf_line_endings_still_trigger_and_indent_correctly` — both triggers fire
correctly; `rest_of_line_is_blank` splits on `\n` alone, so the `\r` rides
along in the tail slice, and `char::is_whitespace('\r')` is `true`, so it
reads as "nothing after the cursor" by luck of that being true rather than
by a check that means to handle it. Passes, but fragile enough that a
future change narrowing that whitespace check should re-run this test.
- **Position past end of line**: untested by the dev. Added
`a_position_past_the_end_of_its_line_clamps_rather_than_panics` —
`convert.rs`'s existing clamp handles it; no panic, and it clamps to
exactly the trigger position here.
- **Empty file, position (0,0)**: untested by the dev. Added
`an_empty_file_at_zero_zero_offers_nothing_and_does_not_panic`.
- **Huge deeply-nested file** (the TODO.md §1 history item): this module
itself never walks the parse tree (`triggered`/`unfinished` are flat loops
over `doc.tokens`), so no stack overflow is possible here regardless of
nesting depth — confirmed by `parse_source_tolerant` benchmarking as
effectively linear (`MAX_NESTING_DEPTH = 64` in `vlog_parser::parser`
bounds the tree walk; the lexer that builds `doc.tokens` is a flat loop,
never recursive). **But this surfaced a real quadratic-time hazard one hop
away — see Finding 2 below**, which is not a defect in this feature's own
code and is out of this feature's file list, so it is filed rather than
fixed here.
- **Multi-byte UTF-8 on the trigger line**: dev's
`a_multibyte_line_puts_the_range_where_the_cursor_really_is` covers a
multi-byte character *before* the trigger line; `convert.rs` (shared,
exhaustively tested independently — astral/surrogate cases included) is
the only UTF-16 conversion path either `completion.rs` or `inline.rs` uses,
confirmed by reading `inline.rs:130` (`doc.positions().offset(position)`).
**Finding 1 (fixed directly) — true-end-of-file trigger silently declined.**
`crates/vfmt_server/src/inline.rs:159` (before fix):
`doc.tokens.iter().rposition(|token| token.span.end <= offset)`. `tokenize`
(`vlog_parser::lexer::tokenize`) appends a zero-width `Eof` sentinel token
whose span starts *and* ends at `text.len()`. When the buffer's very last
byte is the trigger's own last character — e.g. a brand new file where the
user's first keystrokes are literally `... always_comb begin` with no
trailing newline yet — that `Eof` token shares the trigger token's
`span.end`, and `rposition` (searching back-to-front) hits the `Eof` first.
`triggered` then compares `TokenKind::Eof` against `TokenKind::Keyword` and
declines, exactly the moment the ghost text is most wanted.
Repro (pre-fix): `inline_completions` on `"module top;\n always_comb
begin"` (nothing after `begin`) returned `None`; the identical text with a
trailing `"\nendmodule\n"` returned `Some(..)`. Same for `if (` at true EOF.
This is small, unambiguous, and entirely inside the feature's own file, so I
fixed it directly rather than filing it: `triggered` now skips `Eof` tokens
when scanning for `last` (`inline.rs:158-166`). Added
`a_trigger_at_the_true_end_of_file_still_offers_a_ghost` to pin it. Full
suite re-run clean after the fix (fmt/clippy/`cargo test --workspace`).
**Finding 2 (filed, not fixed — out of scope for this feature) — `pairs::analyze`
is O(depth²) in nesting depth, and this feature is a new caller that hits it
per keystroke.** `crates/vfmt_server/src/pairs.rs:157`:
`let depth = stack.iter().filter(|f| is_rainbow(f.rule.open)).count() as u32;`
runs once per opener *push*, scanning the whole current stack every time. For
`n` consecutively nested rainbow openers (`begin`/`fork`) with none closed,
total work is `1+2+...+n = O(n²)`. The comment right above it (`pairs.rs:153-156`)
states the assumption this breaks: "a dozen frames deep at worst on the whole
corpus."
Measured directly (debug build, `analyze` alone, text = `n` consecutive
`begin\n` lines): depth 1000 → 19ms, 2000 → 49ms, 4000 → 155ms, 8000 →
619ms — the ~4× growth per doubling is the quadratic signature. Through the
full `inline_completions` path at depth 50,000 this measured **24 seconds**
for one request (isolated with `Instant` timers around `asking()` vs
`inline_completions()`; the document-setup half was 63ms, all 24s was inside
`inline_completions`, i.e. inside the `Unclosed::Scope` gate's call to
`pairs::analyze`).
This bug predates this feature and lives entirely in `pairs.rs`, which is not
on this feature's file list (`crates/vfmt_server/src/pairs.rs` — CLAUDE.md
scope rule), so I have not touched it; `git diff --stat` confirms it is
untouched by this change. What *is* this feature's business: `inline.rs`'s
`Unclosed::Scope` gate (`inline.rs:190-198`) is a **new caller** of
`pairs::analyze` that runs it fresh on every `textDocument/inlineCompletion`
request — i.e., potentially every keystroke — where the existing callers
(`documentHighlight`, the missing-closer diagnostic, `vfmt/scopePairs`) fire
on click, on save/open, and on hover respectively, all far less frequently.
So this feature doesn't introduce the bug but does meaningfully raise its
real-world exposure. Filed as a background task (see below) rather than
fixed, since the fix belongs in `pairs.rs` and is a design choice (a running
counter instead of a scan, most likely) outside this feature's scope.
`inline.rs`'s own regression test for deep nesting
(`a_deeply_nested_file_neither_crashes_nor_misses_the_trigger`) uses depth
3,000 rather than 50,000 to stay fast while still exercising the same code
path; its comment cross-references this log entry rather than re-deriving
the finding.
**Indentation (item 4)** — all pass, dev's tests plus nothing new needed:
tabs preserved verbatim as `base` (`a_tab_indented_line_keeps_its_own_tabs`),
configured step honored (`the_indent_step_is_the_one_the_client_asked_for`),
ghost `end` aligns with the trigger line's own leading whitespace by
construction (`layout_at` reads it from the buffer, not from a config
value).
**Setting (item 5)** — unit-level was already covered
(`the_setting_turns_the_whole_feature_off`), but every other `vfmt.*`
setting's e2e coverage in `tests/e2e.rs` goes over the wire via
`workspace/didChangeConfiguration`
(`pushed_settings_reach_the_formatter_and_can_change_mid_session`,
`a_pushed_exclude_rebuilds_the_index_mid_session`), and this one didn't have
that. Added `the_inline_templates_setting_is_honoured_over_the_wire` to
`tests/e2e.rs`: default-on with nothing pushed, `false` suppresses mid-session
with no restart, `true` turns it back on — all over real
`workspace/didChangeConfiguration` notifications against a spawned server.
`package.json`'s `vfmt.inlineTemplates` (default `true`) and `settings.rs`'s
`vfmt.get("inlineTemplates")` spell the same key.
**Capability / registration (item 6)** — see wire-contract section above;
all confirmed by reading the vendored client source, not just by running the
tests.
**Scope check (item 7)** — `git diff --stat` / `git status --porcelain`
against the stated file list: exact match
(`Cargo.toml`, `completion.rs`, `main.rs`, `server.rs`, `settings.rs`,
`tests/e2e.rs`, `editors/nvim/README.md`, `editors/vscode/{extension.js,
package.json, smoke.js}`, new `crates/vfmt_server/src/inline.rs`, new
`docs/features/inline-templates/`). `crates/vlog_formatter/` and
`verify.rs` untouched — confirmed by their absence from the diff. (An
unrelated `.DS_Store` sits untracked in the repo root; not this feature's
concern.)
**No `unwrap`/`expect`/`panic!` in new non-test library code (item 8)** —
checked every line of `inline.rs` above its `#[cfg(test)]` boundary and the
`+` lines of every other diffed file: none found.
**What I changed**
- Fixed directly: `crates/vfmt_server/src/inline.rs` — `triggered` now
excludes the lexer's `Eof` sentinel from the "last token ending at the
cursor" scan (Finding 1).
- Tests added, all in `crates/vfmt_server/src/inline.rs` unless noted:
`a_trigger_at_the_true_end_of_file_still_offers_a_ghost`,
`a_deeply_nested_file_neither_crashes_nor_misses_the_trigger`,
`an_empty_file_at_zero_zero_offers_nothing_and_does_not_panic`,
`a_position_past_the_end_of_its_line_clamps_rather_than_panics`,
`crlf_line_endings_still_trigger_and_indent_correctly`,
`no_space_between_the_keyword_and_the_paren_still_triggers`, and
`the_inline_templates_setting_is_honoured_over_the_wire` in
`crates/vfmt_server/tests/e2e.rs`.
- Filed, not fixed (out of scope): a `spawn_task` chip for Finding 2
(`pairs.rs:157`'s O(depth²) scan).
- Nothing else touched. No commit, no push.
**Final test-suite tail** (after the fix, `cargo test --workspace`):
```
test result: ok. 527 passed; 0 failed; 4 ignored; 0 measured; 0 filtered out; finished in 2.04s
...
test result: ok. 20 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 3.29s
```
1614 passed / 0 failed across the workspace (up from the dev's 1607: +6
`inline.rs` tests, +1 `e2e.rs` test). `cargo fmt --all -- --check` and
`cargo clippy --all-targets --workspace -- -D warnings` both clean.
`node editors/vscode/smoke.js <debug-binary>` and `<release-binary>` both
OK.
## Review
**2026-08-25 — lead.** Approved and committed.
- Read `inline.rs` in full plus every other diff. The two deliberate choices —
the data-driven trigger table and the hand-rolled `{"kind": "snippet"}`
response types — are right, and the wire shape is pinned three times
(unit, e2e, smoke), which is what protects it from a future `lsp-types` bump.
- The dev's deviation from the brief (a paren *stack* instead of a running
count for the `if (` gate) is correct and is pinned in both directions
(`a_later_call_does_not_cancel_the_paren_just_typed` and its mirror).
- QA's Eof-sentinel find was real and the fix is minimal and tested.
- The `pairs::analyze` O(depth²) exposure QA filed stays out of this change —
`pairs.rs` is another feature's file — and is tracked as its own task.
- Gates re-run by the lead: fmt clean, clippy clean, full workspace suite
green, `smoke.js` exercised by QA against debug and release.
+9
View File
@@ -101,6 +101,15 @@ applies those on top of its treesitter/syntax highlighting with no extra setup.
Not advertised by the server, so your client will correctly refuse them: range
formatting, completion, rename, signature help, and cross-file references.
**Inline completion (ghost text) needs a client that speaks it.** The server
advertises `inlineCompletionProvider` — grey `) begin … end` after an `if (`,
a matching `end` after a `begin` — but that is `textDocument/inlineCompletion`,
still proposed in LSP 3.18, and Neovim's built-in LSP client does not implement
it yet. Nothing is lost: the same skeletons are in the completion list, where
they have been since `docs/features/completion-templates`. Turn the server side
off with `vfmt.inlineTemplates = false` in your `settings` table if you would
rather it never answered.
Two behaviors worth knowing before you file a bug:
- **The workspace index rebuilds on save, not on keystroke.** Cross-file
+9 -1
View File
@@ -9,7 +9,7 @@
// driven from the client side (docs/features/editor-scopes).
const vscode = require('vscode');
const { LanguageClient, TransportKind } = require('vscode-languageclient/node');
const { LanguageClient, ProposedFeatures, TransportKind } = require('vscode-languageclient/node');
/** The single client, kept only so `deactivate` can stop it. */
let client;
@@ -69,6 +69,14 @@ function activate(context) {
};
client = new LanguageClient('vfmt', 'vfmt', serverOptions, clientOptions);
// `textDocument/inlineCompletion` is LSP 3.18 and still proposed, so
// vscode-languageclient 9 does not register its client feature by default —
// without this, the server's `inlineCompletionProvider` capability is read
// and then ignored, and the request is never sent. The feature itself uses
// only stable VS Code API (`languages.registerInlineCompletionItemProvider`),
// so nothing here needs an API proposal (docs/features/inline-templates).
// Must happen before `start()`: features are registered at initialize time.
client.registerFeatures(ProposedFeatures.createAll(client));
context.subscriptions.push(client);
// Every colour is one this extension contributes, so every one of them has
+5
View File
@@ -163,6 +163,11 @@
"default": true,
"markdownDescription": "Colour each nesting level of `begin`/`end` and `fork`/`join` a different colour, and a keyword whose counterpart is missing in an error colour. Every colour is a `vfmt.rainbow*` theme colour you can override in `workbench.colorCustomizations`. Takes effect immediately."
},
"vfmt.inlineTemplates": {
"type": "boolean",
"default": true,
"markdownDescription": "Show grey ghost text that finishes a block as you open it: `if (` suggests `) begin … end`, and a `begin` at the end of a line suggests its `end`. Tab accepts it as a snippet, so the cursor lands in the condition first and in the body second. Requires `editor.inlineSuggest.enabled`."
},
"vfmt.lineLength": {
"type": [
"number",
+27 -1
View File
@@ -93,6 +93,16 @@ server.stdin.end(
params: { textDocument: { uri: brokenUri, languageId: 'systemverilog', version: 1, text: BROKEN } },
}),
frame({ jsonrpc: '2.0', id: 5, method: 'vfmt/scopePairs', params: { textDocument: { uri: brokenUri } } }),
// Ghost text, just after the `begin` on line 2 of the buffer that lost its
// `end`. The extension only ever sends this after opting into
// `ProposedFeatures`, so an "unhandled method" here is the same kind of
// mismatch the scopePairs check above exists to catch.
frame({
jsonrpc: '2.0',
id: 6,
method: 'textDocument/inlineCompletion',
params: { textDocument: { uri: brokenUri }, position: { line: 2, character: 15 }, context: { triggerKind: 2 } },
}),
// The settings push, in exactly the shape `synchronize.configurationSection:
// 'vfmt'` produces — the whole section, defaults included.
frame({
@@ -100,7 +110,7 @@ server.stdin.end(
method: 'workspace/didChangeConfiguration',
params: {
settings: {
vfmt: { serverPath: 'vfmt-server', rainbowBeginEnd: true, lineLength: null, indent: 4, exclude: [] },
vfmt: { serverPath: 'vfmt-server', rainbowBeginEnd: true, inlineTemplates: true, lineLength: null, indent: 4, exclude: [] },
},
},
}),
@@ -132,6 +142,7 @@ server.on('close', (code) => {
}
if (!capabilities.documentHighlightProvider) fail('capability missing: documentHighlightProvider');
if (!capabilities.inlineCompletionProvider) fail('capability missing: inlineCompletionProvider');
const diagnostics = messages.find((m) => m.method === 'textDocument/publishDiagnostics');
if (!diagnostics) fail('the server pushed no diagnostics for the opened document');
@@ -184,6 +195,21 @@ server.on('close', (code) => {
fail(`expected the unclosed begin at 2:10, got ${JSON.stringify(unmatched[0])}`);
}
// Ghost text: the `begin` that lost its `end` gets one offered, spelled the
// one way the language client turns into a working snippet. A bare-string
// `insertText` would be inserted as plain text, tabstops and all.
const ghost = messages.find((m) => m.id === 6);
if (!ghost) fail('no textDocument/inlineCompletion response');
if (ghost.error) fail(`textDocument/inlineCompletion failed: ${JSON.stringify(ghost.error)}`);
const suggestion = ghost.result && ghost.result.items && ghost.result.items[0];
if (!suggestion) fail(`expected one inline completion, got ${JSON.stringify(ghost.result)}`);
if (!suggestion.insertText || suggestion.insertText.kind !== 'snippet') {
fail(`insertText must be a {kind:"snippet"} object, got ${JSON.stringify(suggestion.insertText)}`);
}
if (suggestion.insertText.value !== '\n $0\n end') {
fail(`unexpected ghost text: ${JSON.stringify(suggestion.insertText.value)}`);
}
// The settings the extension pushes actually reach the formatter.
const formatting = messages.find((m) => m.id === 4);
if (!formatting) fail('no textDocument/formatting response');