Templates 0.4.0: context-gated statement/item snippet completion

A template tier between index names and keywords: if / if-else / else-if
(gated on the line head, so it appears after end but not after an
identifier), case and casez with default, loops, always_ff (plain and
reset variants), always_comb, always @(...), initial, and declaration
templates - logic/localparam/parameter in .sv, wire/reg/integer twins in
.v; pathless buffers get the conservative Verilog set. One renderer
spells each body as snippet and plain text so the two cannot drift, and a
registry-wide test parses every untouched expansion. Nine overlapping
static VS Code snippets moved server-side; file-level ones stay static.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-24 17:28:31 -07:00
1 parent ab89152264
commit e9b7510ca4
18 files changed
+1872 -149

No files matched your search

+29
View File
@@ -4,6 +4,35 @@ All notable changes to vfmt are recorded here. Versions follow
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
(see `README.md`) are the only frozen contract.
## 0.4.0 — 2026-08-24
Completion now offers **templates**, not just words. Typing `if` inside an
`always` block offers `if begin/end` above the bare keyword, and accepting it
writes `if (cond) begin` / body / `end` at the line's own indentation with the
condition selected and TAB moving into the body; `if/else`, `else if`, `case`
and `casez` with a `default` arm, `for`, `while`, `always_ff` (with and without
an async reset), `always_comb`, `always @(...)`, `initial` and the everyday
declarations (`logic`, `reg`/`wire`, `localparam`, `parameter`) are all there
too. Every template is **gated by position** — a statement is only offered
where a statement may be written, an `always` block only at module-item
position, a declaration at both — and **by dialect**: a `.sv` file is offered
`logic` and `always_ff`, a `.v` file `reg`/`wire` and `always @(posedge clk)`,
so nothing on the list is code the buffer's own compiler would reject. A client
that does not understand snippets gets the same skeleton with its defaults
filled in rather than a buffer full of `${1:…}`. Every template's untouched
expansion is parsed by vfmt's own parser in the test suite, which is what keeps
the list honest. Details:
[completion-templates](docs/features/completion-templates/README.md).
Because these come from the server, both editors get them, and the VS Code
extension's own static snippets shed the nine that would otherwise have been
offered twice (`always_ff`, `always_comb`, `case` and `initial` from the
SystemVerilog file; `always`, `alwayscomb`, `case`, `for` and `initial` from
the Verilog one). The file-level templates it is actually good at —
`module`, `tb`, `fsm`, `interface`, `function`, `task`, `genfor`, `guard` and
the rest — stay exactly where they were, and still work with no server running.
Details: [editor-snippets](docs/features/editor-snippets/README.md).
## 0.3.1 — 2026-08-24
A fix for the `begin`/`end` rainbow, which could make the keywords it was
Generated
+8 -8
View File
@@ -217,7 +217,7 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vfmt"
version = "0.3.1"
version = "0.4.0"
dependencies = [
"rayon",
"vfmt_core",
@@ -228,11 +228,11 @@ dependencies = [
[[package]]
name = "vfmt_core"
version = "0.3.1"
version = "0.4.0"
[[package]]
name = "vfmt_server"
version = "0.3.1"
version = "0.4.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +248,14 @@ dependencies = [
[[package]]
name = "vlog_formatter"
version = "0.3.1"
version = "0.4.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.3.1"
version = "0.4.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -263,11 +263,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.3.1"
version = "0.4.0"
[[package]]
name = "vlog_refactor"
version = "0.3.1"
version = "0.4.0"
dependencies = [
"vlog_parser",
"vlog_semantic",
@@ -275,7 +275,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.3.1"
version = "0.4.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.3.1"
version = "0.4.0"
edition = "2021"
license = "MIT"
+1 -1
View File
@@ -581,7 +581,7 @@ registering the file types and starting the server:
```bash
tools/release.sh # builds dist/vfmt-<version>.vsix
code --install-extension dist/vfmt-0.3.1.vsix
code --install-extension dist/vfmt-0.4.0.vsix
```
Sideloading that `.vsix` is the supported install; the extension is not on any
+3
View File
@@ -593,5 +593,8 @@ section only tracks the milestones.
- [x] **M5 `completion-core`** — keyword + project-wide identifier
completion (token-harvested, comments/strings excluded), merged with
M4's module snippets; version 0.3.0.
- [x] **M6 `completion-templates`** — context-gated statement/item snippet
completion from the server (if/else, case, always, loops, declarations),
reconciled with the static VS Code snippets; version 0.4.0.
- [ ] Backlog (extract module, inline, `.*` expansion, ANSI conversion,
organize imports, …) — triaged in the umbrella README after M5.
+443 -20
View File
@@ -1,7 +1,7 @@
//! `textDocument/completion` — module hinting, keywords, and every name the
//! project uses.
//! `textDocument/completion` — module hinting, templates, keywords, and every
//! name the project uses.
//!
//! One response, five tiers, ordered by `sortText`:
//! One response, six tiers, ordered by `sortText`:
//!
//! 0. **module skeletons** — at module-item position only, the whole
//! instantiation generated from the definition (M4, unchanged);
@@ -9,16 +9,19 @@
//! cursor binds, from this file's `Semantics`;
//! 2. **what the project declares** — packages, their members, typedefs,
//! classes, modules and `` `define`` names, from the workspace index;
//! 3. **keywords** — every reserved word `vlog_parser` knows;
//! 4. **project words** — every identifier the in-scope files' *token
//! 3. **templates** — `if`/`case`/`always_ff`/declaration skeletons with
//! tabstops, offered only where the construct may be written;
//! 4. **keywords** — every reserved word `vlog_parser` knows;
//! 5. **project words** — every identifier the in-scope files' *token
//! streams* contain, the rope/VS Code word-completion tier.
//!
//! A name is offered once, by the highest tier that claims it. Nothing is
//! offered inside a comment or a string literal, and nothing that only ever
//! appears inside one is ever a candidate — see `candidates.rs`.
//!
//! See `docs/features/completion-core/README.md` and, for tier 0,
//! `docs/features/refactor-instantiate/README.md`.
//! See `docs/features/completion-core/README.md`, for tier 0
//! `docs/features/refactor-instantiate/README.md`, and for tier 3
//! `docs/features/completion-templates/README.md`.
use std::collections::HashSet;
@@ -35,6 +38,7 @@ use crate::candidates::starts_with_ignore_case;
use crate::pairs;
use crate::state::{Document, Workspace};
use crate::symbols::kind_label;
use crate::templates::{self, Gate, Template};
/// How many items one response carries, over every tier.
///
@@ -59,8 +63,9 @@ const MODULE_LIMIT: usize = 64;
const TIER_MODULE: char = '0';
const TIER_SCOPE: char = '1';
const TIER_INDEX: char = '2';
const TIER_KEYWORD: char = '3';
const TIER_WORD: char = '4';
const TIER_TEMPLATE: char = '3';
const TIER_KEYWORD: char = '4';
const TIER_WORD: char = '5';
/// The scopes a module instantiation may be written directly inside.
const ITEM_SCOPES: &[&str] =
@@ -86,6 +91,17 @@ const NOT_ITEM_SCOPES: &[&str] = &[
"randcase",
];
/// The scopes a *statement* may be written directly inside. A `begin` or a
/// `fork` qualifies only when it is procedural (see [`at_statement`]); a
/// `function`/`task` body always does.
const STATEMENT_SCOPES: &[&str] = &["begin", "fork", "function", "task"];
/// What may stand between the start of a line and a statement: the `end` of
/// the block before it and the `else` that chains onto it. Anything else on
/// the line means the word being typed is part of an expression, not the start
/// of a statement.
const STATEMENT_HEADS: &[&str] = &["end", "else", "end else"];
/// Keywords that make the `begin` after them procedural, so nothing inside it
/// is a module item. `@` is on the list because it is the whole of what stands
/// between `always` and its `begin`.
@@ -138,10 +154,22 @@ pub fn completions(
return items.finish();
}
// Both position gates read the same scope chain, and neither can be true
// unless the word starts a line — so a keystroke in the middle of an
// expression pays for neither.
let starts_a_line = word.at_line_start || word.statement_head;
let chain = match starts_a_line {
true => enclosing_scopes(&doc.tokens, word.start),
false => Vec::new(),
};
let at_item = word.at_line_start && at_module_item(doc, &chain, word.start);
let at_statement = starts_a_line && at_statement(doc, &chain, word.start);
let mut items = Items::new(doc, word.range(offset));
module_tier(&mut items, ws, doc, &word, offset, snippets);
module_tier(&mut items, ws, doc, &word, offset, snippets, at_item);
scope_tier(&mut items, doc, &word);
index_tier(&mut items, ws, &word);
template_tier(&mut items, ws, doc, &word, snippets, at_item, at_statement);
keyword_tier(&mut items, &word);
word_tier(&mut items, ws, doc, &word);
items.finish()
@@ -155,12 +183,12 @@ fn module_tier(
word: &Word,
cursor: u32,
snippets: bool,
at_item: bool,
) {
if !word.at_line_start || !at_module_item(doc, word.start) {
if !at_item {
return;
}
let step = " ".repeat(ws.client_settings().indent.unwrap_or(2));
let layout = Layout { base: line_indent(&doc.text, word.start), step };
let layout = layout(ws, doc, word);
let site = Site { semantics: &doc.semantics, offset: word.start };
let names = vlog_refactor::module_names(ws.index(), &word.text);
@@ -223,7 +251,59 @@ fn index_tier(items: &mut Items, ws: &Workspace, word: &Word) {
}
}
/// Tier 3: every reserved word the lexer knows.
/// Tier 3: the statement, item and declaration templates.
///
/// Above the keywords because a user who typed `if` almost always wants
/// `if (…) begin … end` rather than the three letters they already typed, and
/// below both semantic tiers because a name the code actually declares beats a
/// skeleton every time. The templates a *position* rules out never reach the
/// list at all, so the ranking argument only has to hold where they do.
fn template_tier(
items: &mut Items,
ws: &Workspace,
doc: &Document,
word: &Word,
snippets: bool,
at_item: bool,
at_statement: bool,
) {
if !at_item && !at_statement {
return;
}
let layout = layout(ws, doc, word);
let dialect = templates::dialect(doc.path.as_deref());
for template in templates::for_dialect(dialect) {
if items.full() {
break;
}
if !offered(template, at_item, at_statement) {
continue;
}
if !starts_with_ignore_case(template.prefix, &word.text) {
continue;
}
items.template(template, &layout, snippets);
}
}
/// Whether a template's gate lets it be written where the cursor is.
fn offered(template: &Template, at_item: bool, at_statement: bool) -> bool {
match template.gate {
Gate::Statement | Gate::ElseTail => at_statement,
Gate::Item => at_item,
// A declaration is a module item and a block item both.
Gate::Declaration => at_item || at_statement,
}
}
/// How generated text is indented here: the line's own indentation, and one
/// step as `vfmt.indent` spells it.
fn layout(ws: &Workspace, doc: &Document, word: &Word) -> Layout {
let step = " ".repeat(ws.client_settings().indent.unwrap_or(2));
Layout { base: line_indent(&doc.text, word.start), step }
}
/// Tier 4: every reserved word the lexer knows.
fn keyword_tier(items: &mut Items, word: &Word) {
for keyword in KEYWORDS.iter().filter(|kw| starts_with_ignore_case(kw, &word.text)) {
if items.full() {
@@ -233,7 +313,7 @@ fn keyword_tier(items: &mut Items, word: &Word) {
}
}
/// Tier 4: identifiers used anywhere in the project scope.
/// Tier 5: identifiers used anywhere in the project scope.
///
/// The prebuilt table is as of the last index rebuild, which is `didSave`; the
/// buffer being typed in is harvested afresh from its own token stream, so an
@@ -324,6 +404,42 @@ impl Items {
self.push(item);
}
/// One template: the skeleton it inserts, the word it is reached by, and
/// the shape it expands to.
///
/// A client that never said it understands snippets gets the same text
/// with every hole filled in rather than nothing at all — the M4 ruling,
/// applied to a body whose defaults were chosen so that the result parses.
fn template(&mut self, template: &Template, layout: &Layout, snippets: bool) {
if self.full() || self.seen.contains(template.label) {
return;
}
let item = CompletionItem {
label: template.label.to_string(),
kind: Some(CompletionItemKind::SNIPPET),
detail: Some(format!("{} — template", template.detail)),
documentation: Some(Documentation::MarkupContent(MarkupContent {
kind: MarkupKind::Markdown,
value: format!("```systemverilog\n{}\n```", template.expansion()),
})),
// The label is prose, so the client must be told what the user
// types to reach the item — otherwise `if` would not match
// `if begin/end` at all.
filter_text: Some(template.prefix.to_string()),
sort_text: Some(format!("{TIER_TEMPLATE}{}", template.label)),
insert_text_format: Some(match snippets {
true => InsertTextFormat::SNIPPET,
false => InsertTextFormat::PLAIN_TEXT,
}),
text_edit: Some(CompletionTextEdit::Edit(TextEdit {
range: self.range,
new_text: template.render(layout, snippets),
})),
..Default::default()
};
self.push(item);
}
fn finish(self) -> Option<CompletionResponse> {
if self.items.is_empty() {
return None;
@@ -550,6 +666,13 @@ struct Word {
/// instantiation in the middle of an expression. Every other tier ignores
/// it: a name is a name wherever it is written.
at_line_start: bool,
/// Whether the only thing before the run on its line is [`STATEMENT_HEADS`]
/// — the `end` a statement follows, or the `else` it hangs off.
///
/// Half of the *template* gate, and the reason `end else if` completes: a
/// statement is written at the start of a line or right after one of those
/// two words, and nowhere else.
statement_head: bool,
}
impl Word {
@@ -572,12 +695,18 @@ fn typed_word(doc: &Document, cursor: u32) -> Option<Word> {
false => head,
};
let line_start = bare.rfind('\n').map_or(0, |newline| newline + 1);
let at_line_start = !backtick && bare.get(line_start..)?.chars().all(|c| c == ' ' || c == '\t');
let head = bare.get(line_start..)?;
let at_line_start = !backtick && head.chars().all(|c| c == ' ' || c == '\t');
// `end else` and `end else` are the same head; nothing else is compared,
// so one `split_whitespace` join is the whole normalization needed.
let words = head.split_whitespace().collect::<Vec<&str>>().join(" ");
let statement_head = !backtick && STATEMENT_HEADS.contains(&words.as_str());
Some(Word {
text: text.get(start..)?.to_string(),
start: start as u32,
backtick,
at_line_start,
statement_head,
})
}
@@ -608,12 +737,11 @@ fn line_indent(text: &str, offset: u32) -> String {
///
/// Parentheses close the door too: an item never starts inside one, which is
/// what keeps a port list and a connection list out.
fn at_module_item(doc: &Document, at: u32) -> bool {
fn at_module_item(doc: &Document, chain: &[(&'static str, TextRange)], at: u32) -> bool {
let tokens = &doc.tokens;
if tokens.is_empty() {
return false;
}
let chain = enclosing_scopes(tokens, at);
let Some(&(innermost, opener)) = chain.first() else { return false };
if !ITEM_SCOPES.contains(&innermost) {
return false;
@@ -630,6 +758,42 @@ fn at_module_item(doc: &Document, at: u32) -> bool {
balanced(tokens, opener.end, at)
}
/// Whether `at` is somewhere a *statement* could be written, judged over the
/// same scope chain [`at_module_item`] reads.
///
/// Two ways to qualify, and they are the only two this asks about:
///
/// 1. the innermost open scope is a `function` or a `task`, whose body is
/// statements all the way down; or
/// 2. it is a `begin`/`fork` whose outermost `begin` is a procedural one — the
/// exact inverse of the test that keeps module items out of an `always`.
///
/// Everything else is refused, `case` arms included: a bare `if` is not a
/// legal case item, and a gate that guesses at one would offer a template that
/// does not compile. Parentheses close the door here too.
fn at_statement(doc: &Document, chain: &[(&'static str, TextRange)], at: u32) -> bool {
let tokens = &doc.tokens;
if tokens.is_empty() {
return false;
}
let Some(&(innermost, opener)) = chain.first() else { return false };
if !STATEMENT_SCOPES.contains(&innermost) {
return false;
}
if innermost == "begin" || innermost == "fork" {
let in_subprogram = chain.iter().any(|(kw, _)| *kw == "function" || *kw == "task");
let outermost_begin = chain.iter().rev().find(|(keyword, _)| *keyword == "begin");
let procedural = match outermost_begin {
Some(&(_, span)) => is_procedural(tokens, span.start),
None => false,
};
if !in_subprogram && !procedural {
return false;
}
}
balanced(tokens, opener.end, at)
}
/// The scopes open at `at`, innermost first, as `(keyword, opener span)`.
fn enclosing_scopes(tokens: &[Token], at: u32) -> Vec<(&'static str, TextRange)> {
let analysis = pairs::analyze(tokens);
@@ -744,7 +908,18 @@ endmodule
/// The same, with whatever `tree` already holds and no `sub.sv` implied.
fn opened(tree: Tree, top: &str, needle: &str) -> (Tree, Workspace, Uri, Position) {
let path = tree.write("top.sv", top);
opened_named(tree, "top.sv", top, needle)
}
/// The same again, with the buffer's file name spelled out — which is what
/// decides its dialect.
fn opened_named(
tree: Tree,
file: &str,
top: &str,
needle: &str,
) -> (Tree, Workspace, Uri, Position) {
let path = tree.write(file, top);
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
let uri = path_to_uri(&path).expect("uri");
@@ -982,7 +1157,255 @@ endmodule
}
// ------------------------------------------------------------------
// tier 3 — keywords
// tier 3 — templates
// ------------------------------------------------------------------
/// Only the templates — tier 3.
fn template_labels(items: &[CompletionItem]) -> Vec<&str> {
items
.iter()
.filter(|item| tier(item) == TIER_TEMPLATE)
.map(|item| item.label.as_str())
.collect()
}
/// The items offered at `needle`'s end in a buffer named `file`.
fn offering(name: &str, file: &str, top: &str, needle: &str) -> Vec<CompletionItem> {
let (_tree, ws, uri, position) = opened_named(Tree::new(name), file, top, needle);
items(completions(&ws, &uri, position, true))
}
#[test]
fn a_statement_template_expands_where_a_statement_may_be_written() {
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let items = offering("stmt", "top.sv", top, " if");
let item = find(&items, "if begin/end").expect("the if template");
assert_eq!(item.kind, Some(CompletionItemKind::SNIPPET));
assert_eq!(item.insert_text_format, Some(InsertTextFormat::SNIPPET));
assert_eq!(item.filter_text.as_deref(), Some("if"), "the client filters on what is typed");
assert_eq!(
inserted(item),
"if (${1:cond}) begin\n $0\n end",
"the site's own indentation, the condition first and the body last"
);
assert!(template_labels(&items).contains(&"if/else"), "{:?}", template_labels(&items));
}
#[test]
fn a_template_never_swallows_the_keyword_it_is_reached_by() {
// Dedup is by label, so the labels are prose on purpose: `if` the
// keyword and `if begin/end` the template are two items, in that
// order of specificity.
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let items = offering("both", "top.sv", top, " if");
let keyword = find(&items, "if").expect("the bare keyword");
let template = find(&items, "if begin/end").expect("the template");
assert_eq!(tier(keyword), TIER_KEYWORD);
assert_eq!(tier(template), TIER_TEMPLATE);
assert!(template.sort_text < keyword.sort_text, "a template outranks the bare word");
}
#[test]
fn a_template_ranks_below_a_name_the_code_declares() {
let top = "\
module top;
logic if_enable;
always_comb begin
if
end
endmodule
";
let items = offering("rank", "top.sv", top, " if");
let symbol = find(&items, "if_enable").expect("a declaration in scope");
let template = find(&items, "if begin/end").expect("the template");
assert_eq!(tier(symbol), TIER_SCOPE);
assert!(symbol.sort_text < template.sort_text, "a real name beats a skeleton");
}
#[test]
fn statement_templates_and_item_templates_swap_places_with_the_position() {
// One prefix, `i`, reaching `if` in one place and `initial` in the
// other — so this is the gate and not the filter.
let inside = offering(
"posstmt",
"top.sv",
"module top;\n always_comb begin\n i\n end\nendmodule\n",
" i",
);
assert!(template_labels(&inside).contains(&"if begin/end"));
assert!(
!template_labels(&inside).contains(&"initial begin/end"),
"an initial block is not a statement: {:?}",
template_labels(&inside)
);
let at_item = offering("positem", "top.sv", "module top;\n i\nendmodule\n", " i");
assert!(template_labels(&at_item).contains(&"initial begin/end"));
assert!(
!template_labels(&at_item).contains(&"if begin/end"),
"a bare if is not a module item: {:?}",
template_labels(&at_item)
);
}
#[test]
fn an_always_template_is_a_module_item_and_nothing_else() {
let at_item = offering("alwitem", "top.sv", "module top;\n alw\nendmodule\n", " alw");
assert_eq!(
template_labels(&at_item),
["always_ff @(posedge clk)", "always_ff with reset", "always_comb begin/end"],
"and `alw` finds every one of them"
);
let inside = offering(
"alwstmt",
"top.sv",
"module top;\n always_comb begin\n alw\n end\nendmodule\n",
" alw",
);
assert!(template_labels(&inside).is_empty(), "{:?}", template_labels(&inside));
}
#[test]
fn a_declaration_template_is_offered_as_an_item_and_as_a_block_item() {
let at_item = offering("declitem", "top.sv", "module top;\n log\nendmodule\n", " log");
assert_eq!(template_labels(&at_item), ["logic name;", "logic [N:0] name;"]);
let inside = offering(
"declstmt",
"top.sv",
"module top;\n always_comb begin\n log\n end\nendmodule\n",
" log",
);
assert_eq!(template_labels(&inside), ["logic name;", "logic [N:0] name;"]);
}
#[test]
fn the_file_name_decides_which_dialect_is_offered() {
let sv = offering("dialectsv", "top.sv", "module top;\n l\nendmodule\n", " l");
assert!(template_labels(&sv).contains(&"logic name;"));
assert!(template_labels(&sv).contains(&"localparam int NAME = 0;"));
let v = offering("dialectv", "top.v", "module top;\n l\nendmodule\n", " l");
assert!(!template_labels(&v).contains(&"logic name;"), "`logic` is not Verilog");
assert!(template_labels(&v).contains(&"localparam integer NAME = 0;"));
let reg = offering("dialectreg", "top.v", "module top;\n r\nendmodule\n", " r");
assert_eq!(template_labels(&reg), ["reg name;", "reg [N:0] name;"]);
let sv_reg = offering("dialectsvreg", "top.sv", "module top;\n r\nendmodule\n", " r");
assert!(template_labels(&sv_reg).is_empty(), "no `reg` template in a .sv file");
let always = offering("dialectalw", "top.v", "module top;\n alw\nendmodule\n", " alw");
assert_eq!(
template_labels(&always),
["always @(posedge clk)", "always @(posedge clk or negedge rst_n)", "always @(*)"],
"and no always_ff, which a .v file's compiler would reject"
);
}
#[test]
fn an_else_template_follows_an_end_on_the_same_line() {
let top = "\
module top;
always_comb begin
if (a) begin
end el
end
endmodule
";
let items = offering("elsetail", "top.sv", top, "end el");
assert_eq!(template_labels(&items), ["else if", "else begin/end"]);
assert_eq!(
inserted(find(&items, "else if").expect("the else-if template")),
"else if (${1:cond}) begin\n $0\n end"
);
}
#[test]
fn a_word_in_the_middle_of_a_line_starts_no_statement() {
// The other half of the same rule: `x = if` is an expression, not a
// place a template belongs — and the general tiers still answer there.
let top = "module top;\n always_comb begin\n x = if\n end\nendmodule\n";
let items = offering("midline", "top.sv", top, "x = if");
assert!(template_labels(&items).is_empty(), "{:?}", template_labels(&items));
assert!(find(&items, "if").is_some(), "the keyword tier still answers");
}
#[test]
fn no_template_is_offered_where_a_statement_cannot_go() {
for (name, top, needle) in [
// A generate block is item position, not statement position.
("generate", "module top;\n generate\n if\n endgenerate\nendmodule\n", " if"),
// A `case` arm wants `label:`, not a bare statement.
(
"casearm",
"module top;\n always_comb begin\n case (s)\n if\n endcase\n end\nendmodule\n",
" if",
),
// Nothing at all is open here.
("toplevel", "if\nmodule top;\nendmodule\n", "if"),
// A port list is not a statement, however much it starts a line.
("ports", "module top (\n if\n);\nendmodule\n", " if"),
] {
let items = offering(name, "top.sv", top, needle);
assert!(template_labels(&items).is_empty(), "{name}: {:?}", template_labels(&items));
}
}
#[test]
fn a_subprogram_body_is_statement_position() {
for (name, top, needle) in [
("function", "module top;\n function int f();\n if\n endfunction\nendmodule\n", " if"),
("task", "module top;\n task t();\n if\n endtask\nendmodule\n", " if"),
(
"fnbegin",
"module top;\n function int f();\n begin\n if\n end\n endfunction\nendmodule\n",
" if",
),
] {
let items = offering(name, "top.sv", top, needle);
assert!(template_labels(&items).contains(&"if begin/end"), "{name}");
}
}
#[test]
fn nothing_templated_is_offered_inside_a_comment() {
let top = "module top;\n always_comb begin\n // if\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("tmplcomment", top, "// if");
assert!(completions(&ws, &uri, position, true).is_none());
}
#[test]
fn a_client_without_snippet_support_gets_the_template_filled_in() {
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let (_tree, ws, uri, position) = asking("tmplplain", top, " if");
let items = items(completions(&ws, &uri, position, false));
let item = find(&items, "if begin/end").expect("the if template");
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
let text = inserted(item);
assert!(!text.contains('$'), "no tabstop syntax may reach a plain client: {text}");
assert_eq!(text, "if (cond) begin\n\n end");
let probe = format!("module p;\n always_comb begin\n {text}\n end\nendmodule\n");
assert!(
vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
"the inserted text must parse: {text}"
);
}
#[test]
fn a_templates_documentation_shows_what_it_expands_to() {
let top = "module top;\n alw\nendmodule\n";
let items = offering("tmpldocs", "top.sv", top, " alw");
let item = find(&items, "always_comb begin/end").expect("the always_comb template");
let Some(Documentation::MarkupContent(docs)) = &item.documentation else {
panic!("markdown documentation");
};
assert!(docs.value.contains("always_comb begin\n\nend"), "{}", docs.value);
assert_eq!(item.detail.as_deref(), Some("combinational block — template"));
}
// ------------------------------------------------------------------
// tier 4 — keywords
// ------------------------------------------------------------------
#[test]
+1
View File
@@ -24,6 +24,7 @@ mod settings;
mod signature;
mod state;
mod symbols;
mod templates;
mod tokens;
mod uri;
+596
View File
@@ -0,0 +1,596 @@
//! The template registry — the skeletons `if`, `case`, `always_ff` and a
//! declaration expand to, with tabstops.
//!
//! A template is data: a label, the prefix the user types to reach it, the
//! position it may be offered at, and a body written as indented lines. The
//! only code here is the renderer, which spells one body two ways — with the
//! tabstops for a client that understands snippets, and with every hole
//! replaced by the text the editor would have preselected for one that does
//! not. Both spellings go through the same function, so they cannot drift, and
//! the plain one is exactly what the registry-wide "every expansion parses"
//! test feeds to the parser.
//!
//! See `docs/features/completion-templates/README.md`; the tier that offers
//! these lives in `completion.rs`.
use std::path::Path;
use vlog_refactor::Layout;
/// Which set of templates a buffer gets.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Dialect {
/// `reg`/`wire`, `always @(...)` — legal in both dialects.
Verilog,
/// `logic`, `always_ff`/`always_comb`, `int` loop variables.
SystemVerilog,
}
/// The dialect a file's templates come from, decided by its extension exactly
/// as the `wire-reg-mixup` lint rule decides whether a file is SystemVerilog.
///
/// A buffer with no path — `untitled:`, or stdin — gets the Verilog set,
/// because every Verilog template is also legal SystemVerilog and no
/// SystemVerilog template is legal Verilog. Guessing wrong the other way hands
/// the user code their compiler rejects.
pub fn dialect(path: Option<&Path>) -> Dialect {
let Some(extension) = path.and_then(|p| p.extension()).and_then(|e| e.to_str()) else {
return Dialect::Verilog;
};
match extension.to_ascii_lowercase().as_str() {
"sv" | "svh" => Dialect::SystemVerilog,
_ => Dialect::Verilog,
}
}
/// Where a template may be offered.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Gate {
/// Anywhere a statement may be written: inside a procedural block, a
/// `function` or a `task`.
Statement,
/// The same place, but the text only makes sense after an `if`'s `end` —
/// which is why the parse check plants one in front of it.
ElseTail,
/// Module-item position: where an `always` block or an instantiation goes.
Item,
/// A declaration, legal both as a module item and as a block item.
Declaration,
}
/// One line of a body: how many indent steps it sits in, and its text.
type Line = (u8, &'static str);
/// One template.
pub struct Template {
/// What the completion list shows. Deliberately never a bare keyword, so
/// the keyword tier's own item survives beside it.
pub label: &'static str,
/// What the user types to reach it, and what the client filters on.
pub prefix: &'static str,
pub gate: Gate,
/// The one-line summary beside the label.
pub detail: &'static str,
body: &'static [Line],
}
impl Template {
/// The body, laid out at `layout`.
///
/// With `snippets`, the tabstops are left where they are — `${1:cond}` for
/// the editor to preselect, `$0` for where the cursor ends up. Without
/// them, every hole becomes the text it defaults to (a mirror included:
/// `$1` after `${1:i}` is `i`, which is what the editor would have shown),
/// and a line that is nothing but indentation loses it, because a plain
/// client has no cursor to park there.
pub fn render(&self, layout: &Layout, snippets: bool) -> String {
let mut defaults = Defaults::default();
let mut lines: Vec<String> = Vec::with_capacity(self.body.len());
for (index, (level, text)) in self.body.iter().enumerate() {
let mut line = String::new();
// The first line starts at the cursor, which is already indented.
if index > 0 {
line.push_str(&layout.base);
for _ in 0..*level {
line.push_str(&layout.step);
}
}
match snippets {
true => line.push_str(text),
false => line.push_str(&defaults.substitute(text)),
}
if !snippets {
line.truncate(line.trim_end().len());
}
lines.push(line);
}
lines.join("\n")
}
/// What the documentation panel shows: the shape the user is accepting,
/// at column zero, with every default filled in.
pub fn expansion(&self) -> String {
self.render(&Layout::default(), false)
}
}
/// Every template offered in `dialect`, the shared ones first.
pub fn for_dialect(dialect: Dialect) -> impl Iterator<Item = &'static Template> {
let dialect_only = match dialect {
Dialect::SystemVerilog => SYSTEMVERILOG,
Dialect::Verilog => VERILOG,
};
COMMON.iter().chain(dialect_only)
}
/// The templates whose text is legal in both dialects.
const COMMON: &[Template] = &[
Template {
label: "if begin/end",
prefix: "if",
gate: Gate::Statement,
detail: "if with a begin/end body",
body: &[(0, "if (${1:cond}) begin"), (1, "$0"), (0, "end")],
},
Template {
label: "if/else",
prefix: "if",
gate: Gate::Statement,
detail: "if/else, both arms with begin/end bodies",
body: &[
(0, "if (${1:cond}) begin"),
(1, "$2"),
(0, "end else begin"),
(1, "$0"),
(0, "end"),
],
},
Template {
label: "else if",
prefix: "else",
gate: Gate::ElseTail,
detail: "another else-if arm",
body: &[(0, "else if (${1:cond}) begin"), (1, "$0"), (0, "end")],
},
Template {
label: "else begin/end",
prefix: "else",
gate: Gate::ElseTail,
detail: "a final else arm",
body: &[(0, "else begin"), (1, "$0"), (0, "end")],
},
Template {
label: "case/endcase",
prefix: "case",
gate: Gate::Statement,
detail: "case with a default arm",
body: &[(0, "case (${1:sel})"), (1, "${2:value}: $0;"), (1, "default: ;"), (0, "endcase")],
},
Template {
label: "casez/endcase",
prefix: "casez",
gate: Gate::Statement,
detail: "casez with a default arm",
body: &[(0, "casez (${1:sel})"), (1, "${2:value}: $0;"), (1, "default: ;"), (0, "endcase")],
},
Template {
label: "while begin/end",
prefix: "while",
gate: Gate::Statement,
detail: "while loop with a begin/end body",
body: &[(0, "while (${1:cond}) begin"), (1, "$0"), (0, "end")],
},
Template {
label: "initial begin/end",
prefix: "initial",
gate: Gate::Item,
detail: "initial block",
body: &[(0, "initial begin"), (1, "$0"), (0, "end")],
},
];
/// The SystemVerilog spellings.
const SYSTEMVERILOG: &[Template] = &[
Template {
label: "for loop",
prefix: "for",
gate: Gate::Statement,
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")],
},
Template {
label: "always_ff with reset",
prefix: "always_ff",
gate: Gate::Item,
detail: "synchronous block with an async active-low reset",
body: &[
(0, "always_ff @(posedge ${1:clk} or negedge ${2:rst_n}) begin"),
(1, "if (!$2) begin"),
(2, "${3:q} <= '0;"),
(1, "end else begin"),
(2, "$0"),
(1, "end"),
(0, "end"),
],
},
Template {
label: "always_comb begin/end",
prefix: "always_comb",
gate: Gate::Item,
detail: "combinational block",
body: &[(0, "always_comb begin"), (1, "$0"), (0, "end")],
},
Template {
label: "logic name;",
prefix: "logic",
gate: Gate::Declaration,
detail: "one-bit variable",
body: &[(0, "logic ${1:name};")],
},
Template {
label: "logic [N:0] name;",
prefix: "logic",
gate: Gate::Declaration,
detail: "packed variable",
body: &[(0, "logic [${1:7}:0] ${2:name};")],
},
Template {
label: "localparam int NAME = 0;",
prefix: "localparam",
gate: Gate::Declaration,
detail: "typed local parameter",
body: &[(0, "localparam int ${1:NAME} = ${2:0};")],
},
Template {
label: "parameter int NAME = 0;",
prefix: "parameter",
gate: Gate::Declaration,
detail: "typed parameter",
body: &[(0, "parameter int ${1:NAME} = ${2:0};")],
},
];
/// The Verilog spellings. Every one of them is legal SystemVerilog too, which
/// is why they are also what a buffer with no file name gets.
const VERILOG: &[Template] = &[
Template {
label: "for loop",
prefix: "for",
gate: Gate::Statement,
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")],
},
Template {
label: "always @(posedge clk or negedge rst_n)",
prefix: "always",
gate: Gate::Item,
detail: "synchronous block with an async active-low reset",
body: &[
(0, "always @(posedge ${1:clk} or negedge ${2:rst_n}) begin"),
(1, "if (!$2) begin"),
(2, "${3:q} <= ${4:1'b0};"),
(1, "end else begin"),
(2, "$0"),
(1, "end"),
(0, "end"),
],
},
Template {
label: "always @(*)",
prefix: "always",
gate: Gate::Item,
detail: "combinational block",
body: &[(0, "always @(*) begin"), (1, "$0"), (0, "end")],
},
Template {
label: "reg name;",
prefix: "reg",
gate: Gate::Declaration,
detail: "one-bit variable",
body: &[(0, "reg ${1:name};")],
},
Template {
label: "reg [N:0] name;",
prefix: "reg",
gate: Gate::Declaration,
detail: "vector variable",
body: &[(0, "reg [${1:7}:0] ${2:name};")],
},
Template {
label: "wire name;",
prefix: "wire",
gate: Gate::Declaration,
detail: "one-bit net",
body: &[(0, "wire ${1:name};")],
},
Template {
label: "wire [N:0] name;",
prefix: "wire",
gate: Gate::Declaration,
detail: "vector net",
body: &[(0, "wire [${1:7}:0] ${2:name};")],
},
Template {
label: "localparam integer NAME = 0;",
prefix: "localparam",
gate: Gate::Declaration,
detail: "typed local parameter",
body: &[(0, "localparam integer ${1:NAME} = ${2:0};")],
},
Template {
label: "parameter integer NAME = 0;",
prefix: "parameter",
gate: Gate::Declaration,
detail: "typed parameter",
body: &[(0, "parameter integer ${1:NAME} = ${2:0};")],
},
];
/// The defaults the holes of one body have declared so far, so a mirror can
/// find the text its placeholder was given.
#[derive(Default)]
struct Defaults {
seen: Vec<(u32, String)>,
}
impl Defaults {
/// `text` with every tabstop replaced by what the editor would preselect:
/// `${1:i}` → `i`, a later `$1` → `i` as well, and `$0` or a hole with no
/// default → nothing at all.
///
/// The grammar read here is the subset the registry uses — `$n`, `${n}`
/// and `${n:default}`, with no nesting and no escapes. A `$` that starts
/// none of those is copied through, and
/// `every_hole_is_a_tabstop_the_snippet_grammar_reads` proves the registry
/// contains no other shape.
fn substitute(&mut self, text: &str) -> String {
let mut out = String::new();
let mut rest = text;
while let Some(at) = rest.find('$') {
out.push_str(&rest[..at]);
rest = &rest[at + 1..];
match self.hole(rest) {
Some((filled, tail)) => {
out.push_str(&filled);
rest = tail;
}
None => out.push('$'),
}
}
out.push_str(rest);
out
}
/// The hole `rest` begins with — what it fills in and what follows it.
fn hole<'a>(&mut self, rest: &'a str) -> Option<(String, &'a str)> {
if let Some(braced) = rest.strip_prefix('{') {
let close = braced.find('}')?;
let (number, default) = match braced[..close].split_once(':') {
Some((number, default)) => (number, default),
None => (&braced[..close], ""),
};
let number: u32 = number.parse().ok()?;
return Some((self.fill(number, default), &braced[close + 1..]));
}
let digits = rest.len() - rest.trim_start_matches(|c: char| c.is_ascii_digit()).len();
if digits == 0 {
return None;
}
let number: u32 = rest[..digits].parse().ok()?;
Some((self.fill(number, ""), &rest[digits..]))
}
/// What hole `number` inserts: its own default if it has one, else the
/// default the same number was declared with earlier — a mirror.
fn fill(&mut self, number: u32, default: &str) -> String {
if !default.is_empty() {
self.seen.push((number, default.to_string()));
return default.to_string();
}
self.seen
.iter()
.find(|(n, _)| *n == number)
.map(|(_, text)| text.clone())
.unwrap_or_default()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
/// Every template in the registry, both dialects, with its dialect.
fn every() -> Vec<(Dialect, &'static Template)> {
[Dialect::Verilog, Dialect::SystemVerilog]
.into_iter()
.flat_map(|d| for_dialect(d).map(move |t| (d, t)))
.collect()
}
/// `text` planted where its gate says it may be written, so a fragment can
/// be handed to a whole-file parser.
fn planted(gate: Gate, text: &str) -> Vec<String> {
let statement =
format!("module vfmt_probe;\n always @(*) begin\n{text}\n end\nendmodule\n");
let tail = format!(
"module vfmt_probe;\n always @(*) begin\n if (1) begin\n end\n{text}\n end\nendmodule\n"
);
let item = format!("module vfmt_probe;\n{text}\nendmodule\n");
match gate {
Gate::Statement => vec![statement],
Gate::ElseTail => vec![tail],
Gate::Item => vec![item],
// A declaration is offered at both, so it is checked at both.
Gate::Declaration => vec![item, statement],
}
}
#[test]
fn every_untouched_expansion_parses() {
for (dialect, template) in every() {
let text = template.render(&Layout { base: " ".into(), step: " ".into() }, false);
let text = format!(" {text}");
for probe in planted(template.gate, &text) {
let (_, diagnostics) = vlog_parser::parse_source_tolerant(&probe);
assert!(
diagnostics.is_empty(),
"{dialect:?} `{}` does not parse:\n{probe}\n{diagnostics:#?}",
template.label
);
}
}
}
#[test]
fn every_hole_is_a_tabstop_the_snippet_grammar_reads() {
// The editor-snippets lesson, restated for generated text: 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 (_, template) in every() {
for (_, line) in template.body {
let mut rest = *line;
while let Some(at) = rest.find('$') {
rest = &rest[at + 1..];
let hole =
rest.starts_with('{') || rest.starts_with(|c: char| c.is_ascii_digit());
assert!(
hole,
"`{}`: `${}` is not a tabstop — escape it as `\\$`, and teach \
`Defaults::substitute` to read the escape",
template.label,
rest.chars().next().unwrap_or(' ')
);
}
}
}
}
#[test]
fn a_default_carries_no_snippet_punctuation() {
// `Defaults::hole` reads to the first `}` and splits on the first `:`,
// which is exactly right for the registry and wrong for anything that
// nests. Keep the registry flat.
for (_, template) in every() {
for (_, line) in template.body {
let mut rest = *line;
while let Some(at) = rest.find("${") {
rest = &rest[at + 2..];
let close = rest.find('}').expect("a hole is closed");
let hole = &rest[..close];
assert!(
!hole.contains('{') && !hole.contains('\\') && !hole.contains('$'),
"`{}`: `${{{hole}}}` nests",
template.label
);
rest = &rest[close..];
}
}
}
}
#[test]
fn no_label_is_a_bare_keyword_and_no_label_repeats() {
// The keyword tier must survive beside the templates: dedup is by
// label, so a template labelled `if` would swallow the word `if`.
let mut seen = HashSet::new();
for dialect in [Dialect::Verilog, Dialect::SystemVerilog] {
seen.clear();
for template in for_dialect(dialect) {
assert!(
!vlog_parser::KEYWORDS.contains(&template.label),
"`{}` is a keyword",
template.label
);
assert!(seen.insert(template.label), "`{}` twice in {dialect:?}", template.label);
assert!(
vlog_parser::KEYWORDS.contains(&template.prefix),
"`{}`'s prefix `{}` is not a word the user would be typing",
template.label,
template.prefix
);
}
}
}
#[test]
fn the_two_spellings_of_a_body_are_the_same_text() {
// What a plain client gets is the snippet with its holes filled in —
// not a second body that could drift from the first.
let layout = Layout::default();
for (_, template) in every() {
let mut defaults = Defaults::default();
let snippet = template.render(&layout, true);
let stripped: Vec<String> = snippet
.lines()
.map(|line| defaults.substitute(line).trim_end().to_string())
.collect();
assert_eq!(stripped.join("\n"), template.render(&layout, false), "{}", template.label);
}
}
#[test]
fn a_mirror_repeats_the_text_its_placeholder_was_given() {
let mut defaults = Defaults::default();
assert_eq!(
defaults.substitute("for (int ${1:i} = 0; $1 < ${2:N}; $1++)"),
"for (int i = 0; i < N; i++)"
);
let mut defaults = Defaults::default();
assert_eq!(defaults.substitute("${1:a}$0$2${3}"), "a");
let mut defaults = Defaults::default();
assert_eq!(defaults.substitute("costs $5 and ${x} more"), "costs and ${x} more");
}
#[test]
fn the_layout_indents_every_line_but_the_first() {
let layout = Layout { base: " ".into(), step: "\t".into() };
let template = for_dialect(Dialect::SystemVerilog)
.find(|t| t.label == "if begin/end")
.expect("the if template");
assert_eq!(template.render(&layout, true), "if (${1:cond}) begin\n \t$0\n end");
// The hole is gone, so the whitespace that only held it goes too.
assert_eq!(template.render(&layout, false), "if (cond) begin\n\n end");
}
#[test]
fn the_dialect_comes_from_the_extension_and_defaults_to_verilog() {
assert_eq!(dialect(Some(Path::new("/rtl/m.sv"))), Dialect::SystemVerilog);
assert_eq!(dialect(Some(Path::new("/rtl/m.SVH"))), Dialect::SystemVerilog);
assert_eq!(dialect(Some(Path::new("/rtl/m.v"))), Dialect::Verilog);
assert_eq!(dialect(Some(Path::new("/rtl/m.vh"))), Dialect::Verilog);
assert_eq!(dialect(Some(Path::new("/rtl/m"))), Dialect::Verilog);
assert_eq!(dialect(None), Dialect::Verilog);
}
#[test]
fn each_dialect_offers_its_own_declarations_and_blocks() {
let labels = |d| for_dialect(d).map(|t| t.label).collect::<Vec<_>>();
let sv = labels(Dialect::SystemVerilog);
let v = labels(Dialect::Verilog);
assert!(sv.contains(&"logic name;") && !v.contains(&"logic name;"));
assert!(v.contains(&"reg name;") && !sv.contains(&"reg name;"));
assert!(v.contains(&"wire name;") && !sv.contains(&"wire name;"));
assert!(sv.contains(&"always_comb begin/end") && !v.contains(&"always_comb begin/end"));
assert!(v.contains(&"always @(*)") && !sv.contains(&"always @(*)"));
// The statement templates are the same text in both.
for shared in ["if begin/end", "if/else", "case/endcase", "while begin/end"] {
assert!(sv.contains(&shared) && v.contains(&shared), "{shared}");
}
}
}
+84 -1
View File
@@ -1389,7 +1389,9 @@ fn keyword_and_project_completion_round_trip_over_the_wire() {
let elsewhere = labelled("widget_elsewhere").expect("a word used in the project");
assert_eq!(elsewhere["kind"], 1, "CompletionItemKind.Text");
assert!(elsewhere["sortText"].as_str().expect("sortText").starts_with('4'));
// `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'));
assert!(
!items.iter().any(|item| item["sortText"].as_str().is_some_and(|s| s.starts_with('0'))),
@@ -1402,3 +1404,84 @@ fn keyword_and_project_completion_round_trip_over_the_wire() {
let _ = std::fs::remove_dir_all(&dir);
}
/// The template tier over the wire, accept-shaped: what the client is handed
/// for `if` inside an `always_comb`, and what a `.v` buffer gets instead.
#[test]
fn a_template_completion_round_trips_over_the_wire() {
let dir = temp_dir("templates");
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
let path = dir.join("top.sv");
std::fs::write(&path, top).expect("write");
let verilog = "module older;\n al\nendmodule\n";
let verilog_path = dir.join("older.v");
std::fs::write(&verilog_path, verilog).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", path.display());
let verilog_uri = format!("file://{}", verilog_path.display());
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(top).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{verilog_uri}","languageId":"verilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(verilog).expect("json")
)),
// End of `if` on line 2 of the SystemVerilog buffer.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":6}}}}}}"#
)),
// End of `al` on line 1 of the Verilog one, at module-item position.
frame(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{verilog_uri}"}},"position":{{"line":1,"character":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 completion = messages.iter().find(|m| m["id"] == 2).expect("completion response");
let items = completion["result"]["items"]
.as_array()
.unwrap_or_else(|| panic!("no completion list in {completion:#?}"));
let labelled = |items: &[serde_json::Value], label: &str| {
items.iter().find(|item| item["label"] == label).cloned()
};
let template = labelled(items, "if begin/end").expect("the if template");
assert_eq!(template["kind"], 15, "CompletionItemKind.Snippet");
assert_eq!(template["insertTextFormat"], 2, "InsertTextFormat.Snippet");
assert_eq!(template["filterText"], "if");
assert_eq!(
template["textEdit"]["newText"], "if (${1:cond}) begin\n $0\n end",
"{template:#?}"
);
// The replaced range is exactly the two letters typed.
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'));
// 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'));
// A `.v` buffer is offered Verilog's `always`, never `always_ff`.
let verilog = messages.iter().find(|m| m["id"] == 3).expect("completion response");
let items = verilog["result"]["items"].as_array().expect("a completion list");
assert!(labelled(items, "always @(posedge clk)").is_some(), "{items:#?}");
assert!(
labelled(items, "always_ff @(posedge clk)").is_none(),
"a .v file has no always_ff: {items:#?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
@@ -0,0 +1,618 @@
# completion-templates
M6 of the refactoring plan (`docs/features/refactor/README.md`): **statement
and item templates** in the server's completion response, plus the **0.4.0
version bump**.
## Goal
Make the completion list finish the *construct*, not the word. Typing `if`
inside an `always` block should offer `if begin/end` and, on accept, write
```systemverilog
if (cond) begin
end
```
at the line's own indentation, with `cond` selected and TAB moving into the
body — and the same for `if/else`, `else if`, `case`, the loops, the `always`
family, `initial` and the everyday declarations. This is M5's completion
machinery with one tier added: the templates are a sixth source of items,
ranked between what the code declares and the bare keywords, and gated by two
questions the server can already answer from the token stream — *may a
statement be written here?* and *may a module item?* Nothing is offered that
the buffer's own dialect would reject, and every template's untouched expansion
is fed to vfmt's own parser by the test suite, because a template that hands
the user a red squiggle from our own server is worse than no template.
Because this lives in the server, Vim gets it too — which is the reason it is
here rather than in `editors/vscode/snippets/*.json`, where nine of these
templates used to live. Those are gone; see *Reconciliation* below.
## Assumptions
- **A label that is not a keyword is a feature, not a workaround.** Dedup in
`Items` is by label, so a template labelled `if` would have swallowed the
keyword `if`. Every label is prose (`if begin/end`, `always_ff with reset`,
`logic [N:0] name;`) and `filterText` carries the word the user actually
types, so both items appear and the client still matches the template on
`if`. `no_label_is_a_bare_keyword_and_no_label_repeats` pins it.
- **Position is judged over the token stream, not a parse.** The statement gate
reuses M4's `pairs::analyze` scope chain — the same heuristic
`at_module_item` has always run on — so a half-typed buffer costs nothing
extra and an unbalanced one still answers. Both gates are wrong in the same
directions the M4 README already records; the failure mode is a template not
offered, never a template offered inside a port list.
- **A template's defaults are chosen so the untouched expansion parses.**
`if (${1:cond})`, not `if ($1)`: a hole with no default expands to nothing,
and `if () begin` is not Verilog. This is the editor-snippets assumption
restated for generated text, and it is verified rather than assumed —
`every_untouched_expansion_parses` plants every template where its gate says
it may be written and asserts `parse_source_tolerant` reports nothing.
- **`$` in a body is snippet syntax, not Verilog.** The other
editor-snippets lesson: VS Code substitutes an unknown `$NAME` with the empty
string and says nothing, so an unescaped `$finish` in a body would vanish
invisibly. No system task appears in any body today, and
`every_hole_is_a_tabstop_the_snippet_grammar_reads` fails the build if one is
added without an escape.
- **`vfmt.indent` (default 2) is the indent step**, and the line's own leading
whitespace is the base — the same `Layout` M4's skeletons use, resolved the
same way and with the same deviation from `vfmt.toml` recorded there.
- **A template is offered on prefix, not on fuzzy match.** The server filters
with `starts_with_ignore_case` on the template's prefix exactly as the other
tiers filter on a name, so `alw` finds every `always*` template and `wh`
finds `while`. What the *client* does with the list on top of that is the
client's business (M5's "`sortText` is a nudge" assumption, unchanged).
## Handshakes
- **New module `crates/vfmt_server/src/templates.rs`** — the registry, the
dialect rule and the renderer. It is data plus one function; nothing in it
knows about LSP. `completion.rs` owns the tier, the gates and the items.
- **Consumes `vlog_refactor::Layout`** — M4's `{ base, step }`, reused rather
than re-declared, so a skeleton and a template are indented by the same type.
Nothing in `vlog_refactor` was touched.
- **Consumes `vfmt_server::pairs`** through `completion::enclosing_scopes`,
exactly as M4 does. No change to `pairs.rs`.
- **Changed inside `completion.rs`, for other tiers to know about:**
- **The tier digits moved.** Templates are tier `3`; keywords are now `4`
and project words `5`. The only assertion outside this module that reads a
digit is `e2e.rs`'s word-tier check, updated with a comment saying why.
- `at_module_item` now takes the scope chain instead of computing it, so the
two gates share one `pairs::analyze` call; its logic is unchanged.
- `Word` grew `statement_head` (see *The gates*).
- **`editors/vscode`**: nine static snippets removed (below). No manifest
change, no `extension.js` change, no new setting, no new capability —
`snippetSupport` is read exactly where M4 read it.
- **No new dependency.**
## The templates
`label` is what the list shows, `prefix` is what the user types, and the body
is written as indented lines that the renderer lays out at the site's own
indentation. `$0` is where the cursor lands, which is the empty body line in
every block template.
**Both dialects:**
| Label | Prefix | Gate | Body |
|---|---|---|---|
| `if begin/end` | `if` | statement | `if (${1:cond}) begin` / `$0` / `end` |
| `if/else` | `if` | statement | `if (${1:cond}) begin` / `$2` / `end else begin` / `$0` / `end` |
| `else if` | `else` | statement (else-tail) | `else if (${1:cond}) begin` / `$0` / `end` |
| `else begin/end` | `else` | statement (else-tail) | `else begin` / `$0` / `end` |
| `case/endcase` | `case` | statement | `case (${1:sel})` / `${2:value}: $0;` / `default: ;` / `endcase` |
| `casez/endcase` | `casez` | statement | as `case`, with `casez` |
| `while begin/end` | `while` | statement | `while (${1:cond}) begin` / `$0` / `end` |
| `initial begin/end` | `initial` | item | `initial begin` / `$0` / `end` |
**SystemVerilog only (`.sv`, `.svh`):**
| Label | Prefix | Gate | Body |
|---|---|---|---|
| `for loop` | `for` | statement | `for (int ${1:i} = 0; $1 < ${2:N}; $1++) begin` / `$0` / `end` |
| `always_ff @(posedge clk)` | `always_ff` | item | `always_ff @(posedge ${1:clk}) begin` / `$0` / `end` |
| `always_ff with reset` | `always_ff` | item | `always_ff @(posedge ${1:clk} or negedge ${2:rst_n}) begin` / `if (!$2) begin` / `${3:q} <= '0;` / `end else begin` / `$0` / `end` / `end` |
| `always_comb begin/end` | `always_comb` | item | `always_comb begin` / `$0` / `end` |
| `logic name;` | `logic` | declaration | `logic ${1:name};` |
| `logic [N:0] name;` | `logic` | declaration | `logic [${1:7}:0] ${2:name};` |
| `localparam int NAME = 0;` | `localparam` | declaration | `localparam int ${1:NAME} = ${2:0};` |
| `parameter int NAME = 0;` | `parameter` | declaration | `parameter int ${1:NAME} = ${2:0};` |
**Verilog only (`.v`, `.vh`, and any buffer with no file name):**
| Label | Prefix | Gate | Body |
|---|---|---|---|
| `for loop` | `for` | statement | `for (${1:i} = 0; $1 < ${2:N}; $1 = $1 + 1) begin` / `$0` / `end` |
| `always @(posedge clk)` | `always` | item | `always @(posedge ${1:clk}) begin` / `$0` / `end` |
| `always @(posedge clk or negedge rst_n)` | `always` | item | the reset flavour, `${4:1'b0}` instead of `'0` |
| `always @(*)` | `always` | item | `always @(*) begin` / `$0` / `end` |
| `reg name;` | `reg` | declaration | `reg ${1:name};` |
| `reg [N:0] name;` | `reg` | declaration | `reg [${1:7}:0] ${2:name};` |
| `wire name;` | `wire` | declaration | `wire ${1:name};` |
| `wire [N:0] name;` | `wire` | declaration | `wire [${1:7}:0] ${2:name};` |
| `localparam integer NAME = 0;` | `localparam` | declaration | `localparam integer ${1:NAME} = ${2:0};` |
| `parameter integer NAME = 0;` | `parameter` | declaration | `parameter integer ${1:NAME} = ${2:0};` |
Sixteen templates in a `.sv` file, eighteen in a `.v` one.
Two deliberate details in that table. **The parameter templates name a type**
(`int` / `integer`) because vfmt's own `explicit-parameter-storage-type` rule
flags `localparam NAME = 0;` — a template that trips our own linter on insert
is not a template worth shipping, and it was the untouched-expansion check that
surfaced it. **`casez` but not `casex`**: `casez` costs one registry entry and
is what a decoder is actually written with, while `casex` is the one most style
guides tell you not to use, and an unused item is noise in the list.
## The gates
Three gates, all decided before any item is built, so a request at a position
where no template belongs costs one `pairs::analyze` and nothing else — and a
request in the middle of an expression does not even cost that, because neither
gate can be true unless the word starts a statement.
**Item position** is M4's `at_module_item`, unchanged: the innermost open scope
is a `module`/`interface`/`program`/`generate`/`begin`, no `function`/`class`/
`case`/`fork` is in the chain, the outermost `begin` is not procedural, and the
parentheses are balanced. An `always_ff` inside an `always_comb` is exactly what
that gate already refuses.
**Statement position** is its mirror image, new in `at_statement`: the innermost
open scope is a `function`/`task` — whose body is statements all the way down —
or a `begin`/`fork` whose outermost `begin` *is* procedural. Everything else is
refused, `case` arms included: a bare `if` is not a legal case item, and a gate
that guessed at one would offer a template that does not compile.
**Declaration position** is either of the two: a `logic`/`reg`/`wire`/
`localparam` declaration is a module item and a block item both, and
IEEE 1800's `block_item_declaration` includes the parameter forms as well.
On top of the scope chain, a template is only offered where a statement can
*start* on the line: nothing but whitespace before the typed word, or nothing
but `end`, `else` or `end else` — the two words a statement legitimately
follows on one line. That is what makes `end else if` complete, and what keeps
a template out of `x = if`. It is `Word::statement_head`, a list of three
strings, and it is deliberately the whole of the rule: anything else on the
line means the word is part of an expression.
One honesty note about the owner's phrasing ("typing `if(` then accepting a
suggestion"): the list appears while the word `if` is being typed, and the
template is accepted from *there*. Once the `(` is typed, the word being
completed is empty and no longer starts a line, so the templates are gone — the
user is inside an expression by then, and the item they wanted was on screen
one keystroke earlier. Offering `if (…) begin` as a replacement for text that
already contains `if(` would mean editing backwards over punctuation the user
typed, which is the same line M5's backtick ruling drew.
Comments and strings need no new gate at all. M5's `in_comment_or_string`
returns `None` for the whole request before any tier runs, so a `// if` offers
nothing, and the same is true of a buffer that does not lex.
## Ranking
`sortText` is `<tier digit><label>`, so the six tiers are:
| Tier | What |
|---|---|
| `0` | module instantiation skeletons (M4) |
| `1` | declarations the scope chain binds |
| `2` | what the project declares |
| `3` | **templates** |
| `4` | keywords |
| `5` | project words |
**Above the keywords** because a user who typed `if` almost always wants
`if (…) begin … end` rather than the two letters they already have; the bare
keyword is one arrow-key away and is still there. **Below both semantic tiers**
because a name the code actually declares — a signal called `if_enable`, a
package called `case_pkg` — is a fact about this project, and a template is a
guess about intent; facts win. That the templates sit *below* tier 2 rather
than between 1 and 2 is the one judgment call: tier 2 is names the workspace
index resolved, which is the same kind of evidence as tier 1, so the two stay
adjacent.
Both orderings are asserted (`a_template_never_swallows_the_keyword_it_is_
reached_by`, `a_template_ranks_below_a_name_the_code_declares`), and — as M5
recorded — the tests assert what the server sends, not what a client draws.
## Dialect
`templates::dialect` reads the buffer's file extension, the same question
`wire-reg-mixup` asks: `.sv`/`.svh` (case-insensitively) is SystemVerilog,
**everything else is Verilog** — a `.v`, a `.vh`, an unknown extension, and a
buffer with no path at all (`untitled:`, stdin).
The default is Verilog rather than SystemVerilog on purpose, and it is the
opposite of what "newer is better" would suggest. Every Verilog template is
also legal SystemVerilog: guessing Verilog for an SV buffer costs the user
`reg` where they wanted `logic`, one keystroke to fix. Guessing SystemVerilog
for a Verilog buffer hands them `always_ff` and `logic`, which their compiler
rejects. The asymmetric cost decides it. Consequence worth naming: an *untitled*
buffer in VS Code gets the Verilog set even when the user picked the
SystemVerilog language mode, because the server is told a URI, not a language
id, and inventing a second source of truth for one rare case is not worth it.
The moment the buffer is saved as `.sv` it gets the SystemVerilog set.
## Plain-text clients
A client that never advertised `completionItem.snippetSupport` gets **the same
template with every hole filled in**, as `InsertTextFormat::PLAIN_TEXT` — the
M4 ruling for skeletons, applied here. `if` inserts
```systemverilog
if (cond) begin
end
```
and the cursor lands wherever the client puts it, which is the end of the
insertion. Skipping the tier entirely was the alternative and is worse: the
text is useful, it parses (it is the exact string the expansion test feeds the
parser), and the defaults were chosen for this case as much as for the
preselection. A line that held nothing but `$0` loses its indentation in this
spelling, since there is no cursor to park on it.
The two spellings go through one renderer — `Template::render(layout,
snippets)` — so they cannot drift, and
`the_two_spellings_of_a_body_are_the_same_text` asserts that stripping the
tabstops out of the snippet gives the plain text back.
## Reconciliation with the static VS Code snippets
Nine snippets were deleted from `editors/vscode/snippets/*.json` because the
server now offers the same construct under the same typing. The list, the
reasoning and the verification are in
`docs/features/editor-snippets/README.md`'s work log (2026-08-24, M2); in
brief: `always_ff`, `always_comb`, `case`, `initial` from
`systemverilog.json`, and `always`, `alwayscomb`, `case`, `for`, `initial`
from `verilog.json`. `alwayscomb` is the only one whose prefix does not collide
outright — VS Code matches a typed `always` against it as a subsequence and it
had a byte-identical body to the server's `always @(*)`.
Everything **file-level stays static**, because a file template is worth having
before the server has started and is not position-dependent: `module`,
`modulep`, `fsm`, `enum`, `struct`, `function`, `task`, `interface`, `package`,
`class`, `assertp`, `genfor`, `uniquecase`, `tb`, `guard`. `uniquecase` and
`genfor` are kept deliberately — `unique case` is a different construct from
`case`, and a generate loop is a module item, not the procedural `for` the
server offers.
## Version 0.4.0
Every place `tools/RELEASING.md` names, plus the install examples it does not:
- [x] `Cargo.toml` `[workspace.package] version` → `0.4.0` (all eight crates
inherit it)
- [x] `Cargo.lock` regenerated by `cargo check --workspace` — eight entries
- [x] `editors/vscode/package.json` `"version"`
- [x] `editors/vscode/package-lock.json` `"version"` in **both** places
- [x] `README.md` — the `dist/vfmt-0.4.0.vsix` install example
- [x] `editors/vscode/README.md` — both install examples
- [x] `tools/RELEASING.md` — the `dist/` listing, the install commands, the
`git tag v0.4.0` example and the appendix's publish commands
- [x] `CHANGELOG.md` — a `0.4.0 — 2026-08-24` section in the existing voice
- [x] Verified: `target/debug/vfmt --version` → `vfmt 0.4.0`
- [x] Verified: `node editors/vscode/smoke.js target/debug/vfmt-server` →
`smoke: OK`
Deliberately not touched: the historical `0.3.x` mentions in `CHANGELOG.md` and
in the feature READMEs that record what happened at those versions.
## Status / TODO
- [x] `templates.rs`: registry, dialect rule, one renderer for both spellings
- [x] Tier 3 in `completion.rs`, above keywords and below the semantic tiers
- [x] Statement gate (`at_statement`), reusing M4's scope chain
- [x] Item and declaration gates
- [x] `Word::statement_head`, so `end else if` completes
- [x] Dialect selection by extension, documented for the pathless buffer
- [x] Plain-text fallback with the defaults filled in
- [x] Registry-wide "every untouched expansion parses" test, both harnesses
- [x] Registry-wide `$`-escaping and flat-default tests
- [x] Gate tests: statement vs item vs declaration, subprogram bodies, case
arms, generate blocks, port lists, mid-line words, comments
- [x] Dialect tests over `.sv` and `.v` buffers
- [x] Ranking and dedup tests against the keyword and scope tiers
- [x] e2e stdio round trip: the `if` template's exact snippet text, its
replaced range, the keyword beside it, and a `.v` buffer's `always`
- [x] Nine static snippets removed, both READMEs' prefix tables updated
- [x] Version 0.4.0 across the workspace, the extension and the docs
- [x] `cargo fmt --all -- --check`, `cargo clippy --all-targets`,
`cargo test --workspace` clean; `node --check` on both JS files;
`smoke.js` OK; `vsce ls` still accepts the manifest
- [ ] Not done, deliberately: no `casex`, no `forever`/`repeat`, no `fork/join`
template, no UVM anything. Each is a template somebody wants and nobody
agrees on the shape of, and an unused item is noise in the list — the
same ruling editor-snippets made for `covergroup` and `sequence`.
- [ ] Not done: no template for `generate`/`endgenerate` or `genvar` loops.
The static `genfor` snippet covers it and is not position-dependent.
## Work log
- **2026-08-24 (dev)** — implemented.
**Registry (`crates/vfmt_server/src/templates.rs`, new).** A `Template` is
five fields: label, prefix, gate, detail, and a body written as
`(indent level, text)` lines. `for_dialect` chains the eight shared templates
onto the dialect's own, so the statement set cannot drift between `.sv` and
`.v`. `render` is the only code: it lays the lines out at a
`vlog_refactor::Layout` and either leaves the tabstops alone or replaces each
one with the text the editor would have preselected — mirrors included, so
`$1` after `${1:i}` is `i`, which is what makes the `for` loop's expansion
parse.
**Tier (`completion.rs`).** `template_tier` between `index_tier` and
`keyword_tier`, `TIER_TEMPLATE = '3'`; the keyword and word tiers moved to
`'4'` and `'5'`. `Items::template` builds the item — `CompletionItemKind::
SNIPPET`, `filterText` = the prefix, `documentation` = the expansion in a
fenced block — and goes through the same `push` as everything else, so the
cap and the dedup are unchanged.
**Gates.** `completions` now computes the scope chain **once**, guarded by
"does this word start a statement at all", and passes it to both
`at_module_item` (whose body is otherwise untouched) and the new
`at_statement`. The guard matters: before M6 a mid-expression keystroke never
ran `pairs::analyze`, and it still does not.
**Decisions worth flagging to the lead:**
1. **The tier digits shifted.** Templates had to rank above keywords, and
there is no character between `'2'` and `'3'`, so keywords became `'4'`
and project words `'5'`. One assertion outside `completion.rs` reads a
digit — `e2e.rs`'s word-tier check — and it is updated with a comment.
Every in-module test reads the `TIER_*` constants and needed no change.
2. **A pathless buffer gets the Verilog set**, not the SystemVerilog one.
Reasoning under *Dialect*; it is the conservative direction, and it is
also the one `wire-reg-mixup` already takes.
3. **`end`, `else` and `end else` are statement starts**, so `end else if`
completes. Three strings, an explicit list, and the test that pins it also
pins that `x = if` is not one.
4. **The parameter templates name a type** (`int`/`integer`) so that the
untouched expansion does not trip vfmt's own
`explicit-parameter-storage-type` rule. Found by running the expansions
through `vfmt check` while choosing the bodies.
5. **`alwayscomb` was removed from `verilog.json`** although its prefix does
not collide with anything the server offers. It is a subsequence match on
`always` with a body identical to the server's `always @(*)`, so it would
have shown as a duplicate — but it is the one reconciliation entry that is
a judgment call rather than a prefix collision.
**Performance.** M5's corpus guard, re-run in release against the 860-file
corpus: `worst request 284 µs typed / 242 µs empty`, against M5's measured
297 µs / 223 µs — unchanged inside the run-to-run noise, which is what the
single shared `pairs::analyze` and the "no gate unless the word starts a
statement" guard were for. The template path itself formats at most eighteen
short strings and touches no table.
**Suite**: 1 268 → 1 292 workspace tests (24 new: 9 in `templates.rs`, 14 in
`completion.rs`, 1 e2e), all green. `cargo fmt --all -- --check` and
`cargo clippy --all-targets` clean; `node --check` on `extension.js` and
`smoke.js`; `node editors/vscode/smoke.js target/debug/vfmt-server` →
`smoke: OK`; `npx --no-install @vscode/vsce ls` still lists both snippet
files. No new dependency.
## QA log
**2026-08-24 — QA agent.**
### Gates
- `cargo fmt --all -- --check` — clean.
- `cargo clippy --all-targets --workspace` — clean, zero warnings (re-ran
after `touch`ing `completion.rs` to defeat the cache; still clean).
- `cargo test --workspace` — green. Summed every `test result:` line myself
rather than trusting the total: **1292**, matching the Work log's
`1268 → 1292` claim exactly.
- `node --check` on `extension.js` and `smoke.js` — clean.
- `node editors/vscode/smoke.js target/debug/vfmt-server` — `smoke: OK`.
- `cd editors/vscode && npx --no-install @vscode/vsce ls` — accepts the
manifest; filtering the `node_modules/**` noise out of the listing (as the
M1 QA pass for editor-snippets also did — `.vscodeignore` does not touch
`node_modules`, so `vsce ls` prints it regardless) leaves exactly
`package.json`, `extension.js`, `README.md`, `LICENSE`,
`snippets/verilog.json`, `snippets/systemverilog.json`.
- `cargo build -p vfmt` → `target/debug/vfmt --version` → `vfmt 0.4.0`.
- `cargo test --release -p vfmt_server a_keystroke_over_the_whole_corpus_stays_in_budget -- --nocapture`
— `worst request 225.875µs typed / 182.792µs empty` against the claimed
284µs/242µs; faster, inside run-to-run noise. Budget test passes.
All gates: **pass, claims confirmed.**
### Priority — the real UX, driven live over stdio
Not trusting the e2e test alone: wrote a standalone Python LSP-stdio client
(`/tmp/vfmt_qa/driver.py`, `ux_check.py`, `edge_check.py`, `untitled_check.py`
— scratch, not committed) and drove `target/debug/vfmt-server` directly,
independent of the test suite.
- `.sv` buffer, `if` typed inside an `always_comb` body: `if begin/end`
(kind Snippet=15) and `if/else` both offered, `filterText: "if"`,
`textEdit.newText` = `"if (${1:cond}) begin\n $0\n end"`
(tabstops, correct indentation at the site). The bare keyword `if` (kind
Keyword=14) is present at one tier below (`sortText` `3…` vs `4if`).
**Confirmed exactly as claimed.**
- `case`/`casez` inside a begin block: both offered, correct bodies.
- `always_ff`/`always_comb` at SV item position: all three always_ff/comb
templates offered.
- `logic name;` / `logic [N:0] name;` at SV declaration position: both
offered.
- `.v` buffer, `always` at item position: `always @(posedge clk)`,
`always @(posedge clk or negedge rst_n)`, `always @(*)` offered;
`always_ff`/`always_comb` templates **not** offered (the bare keywords
`always_ff`/`always_comb` still show, correctly, at the keyword tier —
templates are dialect-gated, keywords are not).
- `.v` buffer: `wire`/`reg` declaration templates offered; `logic` template
**not** offered anywhere in a `.v` buffer (checked at declaration position
with prefix `lo`: only `localparam integer NAME = 0;` came back).
- Untitled buffer (`untitled:Untitled-1`, `languageId: "systemverilog"`,
no path) with prefix `l`: only `localparam integer NAME = 0;` — the
**Verilog** set, confirmed live, exactly as *Dialect* documents (and
despite the client-declared language id, which the server correctly never
consults for this).
**Confirmed exactly as claimed** — the plan's exact UX ("type `if` inside a
module + inside an always/initial body", "the bare keyword `if` ALSO present
at a lower tier", "`.v` buffer: `always_ff` NOT, `logic` NOT") all hold live,
not just in the unit/e2e suite.
### Attacks — gates
All driven live over stdio, independent scripts, not just re-running the
existing tests:
| Attack | Result |
|---|---|
| `if` at module-item position (not inside a block) | **not offered** |
| `always_ff` inside a begin block (`always_comb`) | **not offered** |
| statement template inside `fork`/`join` | **offered** (fork is a statement scope, correctly) |
| statement template inside a `function` body | **offered** |
| statement template inside a `generate`/`endgenerate` block | **not offered** (item position, not statement) |
| `case` arm (`case (s) if`) | **not offered** |
| template inside a port list (`module top (\n if\n)`) | **not offered** |
| template inside a parameter list (`module top #(\n if\n)`) | **not offered** |
| template inside a connection list (`.a(if`) | **not offered** |
| cursor in a `// if` comment | **no completions at all** (whole response declines) |
| cursor inside an open string (`$display("if`) | **no completions at all** |
| `end el` (else-tail after `end` on the same line) | **offered** (`else if`, `else begin/end`) |
| `x = if` (bare identifier before `if`, mid-expression) | **not offered**; keyword tier still answers |
| `end el` (double space between `end` and `else`) | **offered** — `Word::statement_head`'s `split_whitespace().join(" ")` normalizes it |
| `end foo el` (garbage between `end` and `else`) | **not offered** — correctly refused |
Every one of the plan's specific break attempts held. No corruption risk:
`verify.rs` is untouched by this feature (confirmed by `git diff` — no
changes outside the stated scope), so hard invariant 4 does not apply here;
the "attack" surface for this milestone is *wrong completions*, not corrupted
formatter output, and none were found.
### Expansion validity — re-derived independently, not trusted from the test
Extracted all 26 `Template` entries straight out of `templates.rs`'s source
text with a standalone regex parser (not importing or calling
`Defaults::substitute`), wrote a **second, independent** tabstop-stripping
implementation in Python, planted each stripped body in the same probe shapes
the registry's own test uses, and fed every probe to a throwaway Rust binary
(`/tmp/vfmt_qa/probe_checker`, a 10-line `main.rs` depending on `vlog_parser`
by path) that calls `vlog_parser::parse_source_tolerant` directly — no vfmt
code from this feature involved in the check at all.
Result: **26/26 parse clean**, independently. Count matches the claim (8
shared + 8 SV-only = 16 SV templates; 8 shared + 10 V-only = 18 V templates).
**On "does it test `.v` templates against Verilog parsing settings?"** — no,
and it can't: `vlog_parser` has no dialect concept anywhere
(`grep -rn "Dialect\|dialect" crates/vlog_parser/src/*.rs` — zero hits).
`parse_source_tolerant` is one grammar, a syntactic superset of both
dialects; dialect-specific rejection (e.g. `always_ff` being illegal in a
`.v` file) is enforced only by *this feature's own gate* (`templates::
dialect`), never by the parser. So the registry test is exactly as strong as
it can be — there is no stricter parsing mode to test `.v` templates against
anywhere in vfmt today. Worth recording, not a finding: a reader could
otherwise assume "parses" implies "parses under Verilog-2001 rules
specifically", which nothing in vfmt currently checks for *any* file.
`$`-escaping: grepped the body text for `$` followed by a letter
(`grep -oE '"\$[a-zA-Z_]+' templates.rs`) — zero hits; every `$NAME`/`$n` in
the file is inside a doc comment, not a body. No system task in any template
body today, consistent with the claim.
Mirrors: the independent stripper resolves `$1` after `${1:i}` to `i` the
same way `Defaults::substitute` does (verified by the same 26/26 pass,
including both `for` loop templates, whose bodies are the only ones with
three mirrored tabstops).
### Dialect
`.svh`/`.vh` — covered by the registry's own
`the_dialect_comes_from_the_extension_and_defaults_to_verilog` test
(`.SVH` case-insensitive → SystemVerilog, `.vh` → Verilog); re-read the
assertions, they match the README's claim. Documented in *Dialect* and (see
above) reconfirmed live for the untitled-buffer case, including the
`languageId` red herring the README calls out by name.
### Reconciliation
Parsed both snippet JSONs directly (`python3 -c 'json.load(...)'`) rather
than trusting the diff: `systemverilog.json` 19 → **15** entries, `verilog.json`
11 → **6**, matching the claim. `git diff` on the two files' removed
`"prefix"` lines gives exactly the 9 named in the feature README's
*Reconciliation* section (4 SV: `always_ff`, `always_comb`, `case`,
`initial`; 5 V: `always`, `alwayscomb`, `case`, `for`, `initial`) — none
missing, none extra.
Keeper prefixes: SV = `module`, `modulep`, `uniquecase`, `fsm`, `enum`,
`struct`, `function`, `task`, `interface`, `package`, `class`, `assertp`,
`genfor`, `tb`, `guard`; V = `module`, `function`, `task`, `genfor`, `tb`,
`guard`. Cross-checked against every server template prefix in the matching
dialect (`if`, `else`, `case`, `casez`, `while`, `initial`/`for`,
`always_ff`/`always_comb` or `always`, `logic`/`reg`/`wire`, `localparam`,
`parameter`) — **no exact string collision** in either dialect.
Near-misses, as the plan asked to check by name: `genfor` vs `for` and
`uniquecase` vs `case` both contain the server's word as a literal
substring, so a client that fuzzy-matches by subsequence (VS Code's
completion filter does) can surface both for the same keystrokes — exactly
what the feature README's own *Reconciliation* section already discloses for
`alwayscomb` vs `always`. Not a new finding: the labels (`Generate for` /
`for loop`, `Unique case` / `case/endcase`) are distinct in the list, so a
user reading labels — which is the whole reason every template label is
prose, not a keyword, per this feature's own first Assumption — can always
tell them apart. No undisclosed near-miss found beyond what the README
already names.
### Tier digits
`grep -rln "sortText\|sort_text\|TIER_" crates editors` — exactly two hits,
`completion.rs` and `e2e.rs`, both already inspected in the diff above and
both consistent with the new scheme (`0`=module, `1`=scope, `2`=index,
`3`=template, `4`=keyword, `5`=word). `candidates.rs` has no tier-digit
literals at all. No straggler found.
### Version
- `Cargo.toml`, all 8 `Cargo.lock` package entries, `package.json`,
`package-lock.json` (both places), `README.md`, `editors/vscode/README.md`,
`tools/RELEASING.md` — all `0.4.0`, checked directly (not by grep-and-eyeball
alone; the 8 `Cargo.lock` entries were extracted programmatically with
`awk`).
- `grep -rn "0\.3\.1"` outside `CHANGELOG.md` — zero hits. The `0.3.1`
section of `CHANGELOG.md` itself is correctly left as history.
- **Finding, fixed directly (small, unambiguous):** `CHANGELOG.md`'s 0.4.0
entry said the static snippets "shed the **eight** that would otherwise
have been offered twice (`always`, `always_ff`, `always_comb`, `case`,
`for`, `initial` and their Verilog twins)". The actual count, verified
against `git diff` on both snippet JSONs and against this feature's own
*Reconciliation* section and Work log ("Nine static snippets removed" /
"9 static snippets removed"), is **nine**: 4 from `systemverilog.json`
(`always_ff`, `always_comb`, `case`, `initial`) + 5 from `verilog.json`
(`always`, `alwayscomb`, `case`, `for`, `initial`). The old wording also
never named `alwayscomb` and left its count ambiguous under "and their
Verilog twins". Reworded to name all nine explicitly and state the correct
count — see `CHANGELOG.md`'s 0.4.0 section. This is a release-note
accuracy issue only; nothing in code or tests was affected.
### Verdict
**Ship.** Every dev claim checked out exactly as stated, including the ones
phrased as UX promises rather than test assertions — verified live over
stdio with independent scripts, not just by re-running the shipped suite.
The one finding (CHANGELOG miscount) was cosmetic, unambiguous, and fixed
in place. No gate, attack, or reconciliation check turned up anything that
needs dev rework.
## Review
**2026-08-24 — lead.** Reviewed after QA's ship verdict — second clean
first-pass in a row; gates run independently (1292 tests, 0 failures,
clippy silent). The registry-as-data with one renderer for both spellings
is the right shape, and `Word::statement_head` is a neat, honest gate for
`else if` (offered after `end`, refused after an identifier). QA
independently re-derived and re-parsed all 26 template expansions with its
own stripper — exactly the level of distrust the expansion-parses promise
deserves. Dev's three judgment calls approved: the tier-digit shift (all
call sites audited), the conservative Verilog set for pathless buffers
(every Verilog template is legal SV), and removing `alwayscomb` from the
static set. QA's CHANGELOG miscount fix (eight → nine, `alwayscomb` named)
accepted. Lead post-review fix: the extension README's relative link to
this doc broke `vsce package` (no repository URL to resolve it against) —
demoted to plain-text path. M6 checked off in the umbrella plan and
TODO.md §8; ships as 0.4.0.
+47
View File
@@ -87,6 +87,10 @@ SystemVerilog.
- [x] Register both files in `package.json` → `contributes.snippets`.
- [x] Verify the packaged `.vsix` includes them (`vsce ls`).
- [x] Feature README.
- [x] **2026-08-24, M6:** hand the statement- and block-level templates to the
server and keep only the file-level ones here — nine snippets removed,
the two READMEs' prefix tables updated. See the work-log entry below and
`docs/features/completion-templates/README.md`.
- [ ] Not done, deliberately: no snippets for UVM (`uvm_component_utils`,
factory registration) — they belong with a UVM-aware feature, not in a
base file the whole ecosystem sees. No `always_latch`, no `covergroup`,
@@ -175,6 +179,49 @@ no snippets item to check off — §6's shipped-capabilities list mentions
"declaration snippets" only as part of `hover`, which is a different thing —
so it was left alone.
### 2026-08-24 — M2: nine templates moved server-side in M6
`completion-templates` (M6) makes the server offer the statement and block
templates itself, gated by where the cursor actually is and by the file's
dialect — something a static `contributes.snippets` entry cannot do, since VS
Code offers a snippet on prefix alone, anywhere in the file. Two lists offering
the same prefix would have meant two near-identical items in one completion
list, so the overlapping snippets were **removed here** rather than duplicated:
| File | Snippet | Prefix | Replaced by |
|---|---|---|---|
| `systemverilog.json` | always_ff | `always_ff` | server `always_ff with reset` |
| `systemverilog.json` | always_comb | `always_comb` | server `always_comb begin/end` |
| `systemverilog.json` | Case with default | `case` | server `case/endcase` |
| `systemverilog.json` | Initial block | `initial` | server `initial begin/end` |
| `verilog.json` | Clocked always block | `always` | server `always @(posedge clk or negedge rst_n)` |
| `verilog.json` | Combinational always block | `alwayscomb` | server `always @(*)` |
| `verilog.json` | Case with default | `case` | server `case/endcase` |
| `verilog.json` | For loop | `for` | server `for loop` |
| `verilog.json` | Initial block | `initial` | server `initial begin/end` |
`alwayscomb` is the one removal whose prefix does *not* collide: VS Code
matches a typed `always` against it as a subsequence, so it appeared beside the
server's `always @(*)` with a byte-identical body. Removing it is a judgment
call and is flagged as one.
**Everything file-level stays**, and stays static, so it still works with no
server on `PATH`: `module`, `modulep`, `fsm`, `enum`, `struct`, `function`,
`task`, `interface`, `package`, `class`, `assertp`, `genfor`, `uniquecase`,
`tb`, `guard`. `uniquecase` is kept deliberately — `unique case` is a different
construct from `case`, not a second spelling of it, and the server offers no
template for it. `genfor` is kept for the same reason: a `generate` loop is a
module item, not the procedural `for` the server offers.
**Verified.** Both files re-parsed as JSON; prefixes unique within each file;
the `$`-escaping check re-run over what remains (`\$display`, `\$finish`,
`\$error` in the two `tb` snippets and `assertp` — the three occurrences the
*Assumptions* section names, all still escaped, none of them in a removed
snippet). `npx --no-install @vscode/vsce ls` still accepts the manifest and
still lists both `snippets/*.json`. Counts: `systemverilog.json` 19 → 15,
`verilog.json` 11 → 6. `editors/vscode/README.md`'s two prefix tables were
rewritten to match and now say where the statement templates went.
## QA log
_(empty — no QA pass yet)_
+12 -1
View File
@@ -108,6 +108,16 @@ the work is reviewed**. Owner-priority items first (2026-08-24).
- [x] **Version 0.3.0** — workspace + extension bump with a CHANGELOG entry
covering the whole refactoring layer (M1–M5) → M5
### Templates (owner request, 2026-08-24 night)
- [x] **Statement/item template completion** — context-gated snippet items
from the server (both editors): `if`/`if-else`/`else-if`, `case` with
`default`, `always_ff`/`always_comb`/`always @(...)`, `for`/`while`,
`initial`, declarations (`logic x;`-style), each with tabstops (condition
first, then body) → `docs/features/completion-templates/README.md` (M6)
- [x] **Reconcile with the static VS Code snippets** — no prefix offered
twice; file-level templates (module, tb, FSM) stay static → M6
- [x] **Version 0.4.0** → M6
### Structural refactorings (backlog, post-M4)
- [ ] **Extract module** from a selected statement range (infer ports from
read/driven sets) — the flagship, hardest one
@@ -198,7 +208,8 @@ commit — in order:
- [x] M3 refactor-ports — done, QA clean after one rework round, reviewed
- [x] M4 refactor-instantiate — done, QA clean after one rework round, reviewed
- [x] M5 completion-core — done, QA clean first pass, reviewed
- [ ] Backlog triage after M5
- [x] M6 completion-templates — done, QA clean first pass, reviewed
- [ ] Backlog triage after M6
## Work log
+16 -13
View File
@@ -46,14 +46,14 @@ catches "the binary moved" or "the handshake broke" without launching VS Code.
```bash
npm ci # installs vscode-languageclient (the only dependency)
npx @vscode/vsce package
code --install-extension vfmt-0.3.1.vsix
code --install-extension vfmt-0.4.0.vsix
```
Then reload VS Code and open a `.v`/`.sv`/`.vh`/`.svh` file.
`tools/release.sh` from the repo root does all of the above (plus the release
binaries and checksums) and drops the `.vsix` in `dist/`, so
`code --install-extension dist/vfmt-0.3.1.vsix` is the one-command path.
`code --install-extension dist/vfmt-0.4.0.vsix` is the one-command path.
`editors/vscode/LICENSE` is a copy of the repo's MIT license and is what lets
`vsce package` run without `--skip-license`. If you are packaging a fork that
dropped `package.json`'s `repository` field, add `--allow-missing-repository`.
@@ -148,27 +148,31 @@ immediately. Cursor on a `begin` also highlights its matching `end` — that is
## Snippets
Type a prefix and pick the snippet from the completion list; `Tab` walks the
placeholders. These are a static manifest contribution, so they work with no
server on `PATH` and before the extension has activated. Bodies are
dialect-specific — `module` gives `input wire` in a `.v` file and `input logic`
in a `.sv` one.
placeholders. These are the **file-level** templates, a static manifest
contribution, so they work with no server on `PATH` and before the extension
has activated. Bodies are dialect-specific — `module` gives `input wire` in a
`.v` file and `input logic` in a `.sv` one.
The everyday statement and block templates — `if`, `if/else`, `else if`,
`case`, `for`, `while`, `always_ff`, `always_comb`, `always @(...)`, `initial`
and the `logic`/`reg`/`wire`/`parameter` declarations — come from the **server**
instead, since 0.4.0: they are offered only where the construct may actually be
written, and they were removed from the lists below so no prefix offers the
same thing twice. See
`docs/features/completion-templates/README.md` in the repository.
| Verilog (`.v`, `.vh`) | |
|---|---|
| `module` | module with a port list |
| `always` / `alwayscomb` | clocked block with async active-low reset / `always @(*)` |
| `case` | `case` with a `default` arm |
| `function` / `task` | Verilog-2001 declaration with an ANSI argument list |
| `genfor` / `for` | `generate`+`genvar` loop with a named block / plain loop |
| `initial` | `initial begin … end` |
| `genfor` | `generate`+`genvar` loop with a named block |
| `tb` | testbench module: clock, reset, `$display`, `$finish` |
| `guard` | `` `ifndef ``/`` `define `` include guard from the file name |
| SystemVerilog (`.sv`, `.svh`) | |
|---|---|
| `module` / `modulep` | module with ports / with a parameter list too |
| `always_ff` / `always_comb` | clocked block with async active-low reset / combinational |
| `case` / `uniquecase` | `case` with a `default` arm / `unique case` |
| `uniquecase` | `unique case` with a `default` arm |
| `fsm` | two-process state machine: enum, next-state logic, state register |
| `enum` / `struct` | `typedef enum` / `typedef struct packed` |
| `function` / `task` | `automatic` declaration |
@@ -176,7 +180,6 @@ in a `.sv` one.
| `package` / `class` | package named after the file / class with a constructor |
| `assertp` | labelled concurrent assertion with `disable iff` and `$error` |
| `genfor` | `for (genvar …)` with a named block |
| `initial` | `initial begin … end` |
| `tb` | testbench module: clock, reset, `$finish` |
| `guard` | `` `ifndef ``/`` `define `` include guard from the file name |
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "vfmt",
"version": "0.3.1",
"version": "0.4.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "vfmt",
"version": "0.3.1",
"version": "0.4.0",
"license": "MIT",
"dependencies": {
"vscode-languageclient": "9.0.1"
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "vfmt",
"displayName": "vfmt — Verilog/SystemVerilog",
"description": "Formatting, diagnostics, navigation and semantic highlighting for Verilog and SystemVerilog, served by the vfmt language server.",
"version": "0.3.1",
"version": "0.4.0",
"publisher": "REPLACE-ME",
"license": "MIT",
"repository": {
@@ -25,38 +25,6 @@
],
"description": "Module with parameters and ports"
},
"always_ff": {
"prefix": "always_ff",
"body": [
"always_ff @(posedge ${1:clk} or negedge ${2:rst_n}) begin",
" if (!$2) begin",
" ${3:q} <= '0;",
" end else begin",
" $0",
" end",
"end"
],
"description": "Sequential block with async active-low reset"
},
"always_comb": {
"prefix": "always_comb",
"body": [
"always_comb begin",
" $0",
"end"
],
"description": "Combinational always_comb block"
},
"Case with default": {
"prefix": "case",
"body": [
"case (${1:sel})",
" ${2:value}: ${3:statement};",
" default: ${4:statement};",
"endcase"
],
"description": "Case statement with a default branch"
},
"Unique case": {
"prefix": "uniquecase",
"body": [
@@ -182,15 +150,6 @@
],
"description": "Generate for loop with a named block"
},
"Initial block": {
"prefix": "initial",
"body": [
"initial begin",
" $0",
"end"
],
"description": "Initial block"
},
"Testbench skeleton": {
"prefix": "tb",
"body": [
-50
View File
@@ -11,38 +11,6 @@
],
"description": "Module with a port list"
},
"Clocked always block": {
"prefix": "always",
"body": [
"always @(posedge ${1:clk} or negedge ${2:rst_n}) begin",
" if (!$2) begin",
" ${3:q} <= ${4:1'b0};",
" end else begin",
" $0",
" end",
"end"
],
"description": "Sequential always block with async active-low reset"
},
"Combinational always block": {
"prefix": "alwayscomb",
"body": [
"always @(*) begin",
" $0",
"end"
],
"description": "Combinational always @(*) block"
},
"Case with default": {
"prefix": "case",
"body": [
"case (${1:sel})",
" ${2:value}: ${3:statement};",
" default: ${4:statement};",
"endcase"
],
"description": "Case statement with a default branch"
},
"Function": {
"prefix": "function",
"body": [
@@ -77,24 +45,6 @@
],
"description": "Generate for loop with a named block"
},
"For loop": {
"prefix": "for",
"body": [
"for (${1:i} = 0; $1 < ${2:N}; $1 = $1 + 1) begin",
" $0",
"end"
],
"description": "For loop"
},
"Initial block": {
"prefix": "initial",
"body": [
"initial begin",
" $0",
"end"
],
"description": "Initial block"
},
"Testbench skeleton": {
"prefix": "tb",
"body": [
+10 -10
View File
@@ -61,9 +61,9 @@ recreated on every run.
```
dist/
vfmt-0.3.1-aarch64-apple-darwin
vfmt-server-0.3.1-aarch64-apple-darwin
vfmt-0.3.1.vsix
vfmt-0.4.0-aarch64-apple-darwin
vfmt-server-0.4.0-aarch64-apple-darwin
vfmt-0.4.0.vsix
SHA256SUMS
```
@@ -111,11 +111,11 @@ npx @vscode/vsce package --out ../../dist/vfmt-<version>.vsix
```bash
# the CLI and the server: anywhere on PATH
install -m 755 dist/vfmt-0.3.1-aarch64-apple-darwin ~/.local/bin/vfmt
install -m 755 dist/vfmt-server-0.3.1-aarch64-apple-darwin ~/.local/bin/vfmt-server
install -m 755 dist/vfmt-0.4.0-aarch64-apple-darwin ~/.local/bin/vfmt
install -m 755 dist/vfmt-server-0.4.0-aarch64-apple-darwin ~/.local/bin/vfmt-server
# the editor extension: sideload, no marketplace involved
code --install-extension dist/vfmt-0.3.1.vsix
code --install-extension dist/vfmt-0.4.0.vsix
```
Publishing the artifacts is a matter of attaching `dist/`'s contents plus
@@ -123,8 +123,8 @@ Publishing the artifacts is a matter of attaching `dist/`'s contents plus
gate is green:
```bash
git tag -a v0.3.1 -m 'vfmt 0.3.1'
git push origin v0.3.1
git tag -a v0.4.0 -m 'vfmt 0.4.0'
git push origin v0.4.0
```
## Appendix — if the owner ever publishes to a marketplace
@@ -151,10 +151,10 @@ The commands themselves, once those exist:
# VS Code Marketplace: needs an Azure DevOps PAT for the publisher
npx @vscode/vsce publish -p "$VSCE_TOKEN"
# ... or publish an already-built package
npx @vscode/vsce publish --packagePath dist/vfmt-0.3.1.vsix -p "$VSCE_TOKEN"
npx @vscode/vsce publish --packagePath dist/vfmt-0.4.0.vsix -p "$VSCE_TOKEN"
# Open VSX (VSCodium, Gitpod, Cursor): needs an Eclipse Foundation account
npx ovsx publish dist/vfmt-0.3.1.vsix -p "$OVSX_TOKEN"
npx ovsx publish dist/vfmt-0.4.0.vsix -p "$OVSX_TOKEN"
```
Both tokens are secrets. Neither belongs in this repo, in a shell history, or