diff --git a/CHANGELOG.md b/CHANGELOG.md index c4f39d3..c61afdb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/Cargo.lock b/Cargo.lock index c728a7e..497b86f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", ] diff --git a/Cargo.toml b/Cargo.toml index eb95054..a8119a9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ members = [ ] [workspace.package] -version = "0.3.1" +version = "0.4.0" edition = "2021" license = "MIT" diff --git a/README.md b/README.md index 5efc528..9c09755 100644 --- a/README.md +++ b/README.md @@ -581,7 +581,7 @@ registering the file types and starting the server: ```bash tools/release.sh # builds dist/vfmt-.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 diff --git a/TODO.md b/TODO.md index 332c32b..e4ae61f 100644 --- a/TODO.md +++ b/TODO.md @@ -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. diff --git a/crates/vfmt_server/src/completion.rs b/crates/vfmt_server/src/completion.rs index 2c7d091..379169a 100644 --- a/crates/vfmt_server/src/completion.rs +++ b/crates/vfmt_server/src/completion.rs @@ -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 { 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 { 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::>().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 { + let (_tree, ws, uri, position) = opened_named(Tree::new(name), file, top, needle); + items(completions(&ws, &uri, position, true)) + } + + #[test] + fn a_statement_template_expands_where_a_statement_may_be_written() { + let top = "module top;\n always_comb begin\n if\n end\nendmodule\n"; + let items = offering("stmt", "top.sv", top, " if"); + let item = find(&items, "if begin/end").expect("the if template"); + assert_eq!(item.kind, Some(CompletionItemKind::SNIPPET)); + assert_eq!(item.insert_text_format, Some(InsertTextFormat::SNIPPET)); + assert_eq!(item.filter_text.as_deref(), Some("if"), "the client filters on what is typed"); + assert_eq!( + inserted(item), + "if (${1:cond}) begin\n $0\n end", + "the site's own indentation, the condition first and the body last" + ); + assert!(template_labels(&items).contains(&"if/else"), "{:?}", template_labels(&items)); + } + + #[test] + fn a_template_never_swallows_the_keyword_it_is_reached_by() { + // Dedup is by label, so the labels are prose on purpose: `if` the + // keyword and `if begin/end` the template are two items, in that + // order of specificity. + let top = "module top;\n always_comb begin\n if\n end\nendmodule\n"; + let items = offering("both", "top.sv", top, " if"); + let keyword = find(&items, "if").expect("the bare keyword"); + let template = find(&items, "if begin/end").expect("the template"); + assert_eq!(tier(keyword), TIER_KEYWORD); + assert_eq!(tier(template), TIER_TEMPLATE); + assert!(template.sort_text < keyword.sort_text, "a template outranks the bare word"); + } + + #[test] + fn a_template_ranks_below_a_name_the_code_declares() { + let top = "\ +module top; + logic if_enable; + always_comb begin + if + end +endmodule +"; + let items = offering("rank", "top.sv", top, " if"); + let symbol = find(&items, "if_enable").expect("a declaration in scope"); + let template = find(&items, "if begin/end").expect("the template"); + assert_eq!(tier(symbol), TIER_SCOPE); + assert!(symbol.sort_text < template.sort_text, "a real name beats a skeleton"); + } + + #[test] + fn statement_templates_and_item_templates_swap_places_with_the_position() { + // One prefix, `i`, reaching `if` in one place and `initial` in the + // other — so this is the gate and not the filter. + let inside = offering( + "posstmt", + "top.sv", + "module top;\n always_comb begin\n i\n end\nendmodule\n", + " i", + ); + assert!(template_labels(&inside).contains(&"if begin/end")); + assert!( + !template_labels(&inside).contains(&"initial begin/end"), + "an initial block is not a statement: {:?}", + template_labels(&inside) + ); + + let at_item = offering("positem", "top.sv", "module top;\n i\nendmodule\n", " i"); + assert!(template_labels(&at_item).contains(&"initial begin/end")); + assert!( + !template_labels(&at_item).contains(&"if begin/end"), + "a bare if is not a module item: {:?}", + template_labels(&at_item) + ); + } + + #[test] + fn an_always_template_is_a_module_item_and_nothing_else() { + let at_item = offering("alwitem", "top.sv", "module top;\n alw\nendmodule\n", " alw"); + assert_eq!( + template_labels(&at_item), + ["always_ff @(posedge clk)", "always_ff with reset", "always_comb begin/end"], + "and `alw` finds every one of them" + ); + + let inside = offering( + "alwstmt", + "top.sv", + "module top;\n always_comb begin\n alw\n end\nendmodule\n", + " alw", + ); + assert!(template_labels(&inside).is_empty(), "{:?}", template_labels(&inside)); + } + + #[test] + fn a_declaration_template_is_offered_as_an_item_and_as_a_block_item() { + let at_item = offering("declitem", "top.sv", "module top;\n log\nendmodule\n", " log"); + assert_eq!(template_labels(&at_item), ["logic name;", "logic [N:0] name;"]); + + let inside = offering( + "declstmt", + "top.sv", + "module top;\n always_comb begin\n log\n end\nendmodule\n", + " log", + ); + assert_eq!(template_labels(&inside), ["logic name;", "logic [N:0] name;"]); + } + + #[test] + fn the_file_name_decides_which_dialect_is_offered() { + let sv = offering("dialectsv", "top.sv", "module top;\n l\nendmodule\n", " l"); + assert!(template_labels(&sv).contains(&"logic name;")); + assert!(template_labels(&sv).contains(&"localparam int NAME = 0;")); + + let v = offering("dialectv", "top.v", "module top;\n l\nendmodule\n", " l"); + assert!(!template_labels(&v).contains(&"logic name;"), "`logic` is not Verilog"); + assert!(template_labels(&v).contains(&"localparam integer NAME = 0;")); + + let reg = offering("dialectreg", "top.v", "module top;\n r\nendmodule\n", " r"); + assert_eq!(template_labels(®), ["reg name;", "reg [N:0] name;"]); + let sv_reg = offering("dialectsvreg", "top.sv", "module top;\n r\nendmodule\n", " r"); + assert!(template_labels(&sv_reg).is_empty(), "no `reg` template in a .sv file"); + + let always = offering("dialectalw", "top.v", "module top;\n alw\nendmodule\n", " alw"); + assert_eq!( + template_labels(&always), + ["always @(posedge clk)", "always @(posedge clk or negedge rst_n)", "always @(*)"], + "and no always_ff, which a .v file's compiler would reject" + ); + } + + #[test] + fn an_else_template_follows_an_end_on_the_same_line() { + let top = "\ +module top; + always_comb begin + if (a) begin + end el + end +endmodule +"; + let items = offering("elsetail", "top.sv", top, "end el"); + assert_eq!(template_labels(&items), ["else if", "else begin/end"]); + assert_eq!( + inserted(find(&items, "else if").expect("the else-if template")), + "else if (${1:cond}) begin\n $0\n end" + ); + } + + #[test] + fn a_word_in_the_middle_of_a_line_starts_no_statement() { + // The other half of the same rule: `x = if` is an expression, not a + // place a template belongs — and the general tiers still answer there. + let top = "module top;\n always_comb begin\n x = if\n end\nendmodule\n"; + let items = offering("midline", "top.sv", top, "x = if"); + assert!(template_labels(&items).is_empty(), "{:?}", template_labels(&items)); + assert!(find(&items, "if").is_some(), "the keyword tier still answers"); + } + + #[test] + fn no_template_is_offered_where_a_statement_cannot_go() { + for (name, top, needle) in [ + // A generate block is item position, not statement position. + ("generate", "module top;\n generate\n if\n endgenerate\nendmodule\n", " if"), + // A `case` arm wants `label:`, not a bare statement. + ( + "casearm", + "module top;\n always_comb begin\n case (s)\n if\n endcase\n end\nendmodule\n", + " if", + ), + // Nothing at all is open here. + ("toplevel", "if\nmodule top;\nendmodule\n", "if"), + // A port list is not a statement, however much it starts a line. + ("ports", "module top (\n if\n);\nendmodule\n", " if"), + ] { + let items = offering(name, "top.sv", top, needle); + assert!(template_labels(&items).is_empty(), "{name}: {:?}", template_labels(&items)); + } + } + + #[test] + fn a_subprogram_body_is_statement_position() { + for (name, top, needle) in [ + ("function", "module top;\n function int f();\n if\n endfunction\nendmodule\n", " if"), + ("task", "module top;\n task t();\n if\n endtask\nendmodule\n", " if"), + ( + "fnbegin", + "module top;\n function int f();\n begin\n if\n end\n endfunction\nendmodule\n", + " if", + ), + ] { + let items = offering(name, "top.sv", top, needle); + assert!(template_labels(&items).contains(&"if begin/end"), "{name}"); + } + } + + #[test] + fn nothing_templated_is_offered_inside_a_comment() { + let top = "module top;\n always_comb begin\n // if\n end\nendmodule\n"; + let (_tree, ws, uri, position) = asking("tmplcomment", top, "// if"); + assert!(completions(&ws, &uri, position, true).is_none()); + } + + #[test] + fn a_client_without_snippet_support_gets_the_template_filled_in() { + let top = "module top;\n always_comb begin\n if\n end\nendmodule\n"; + let (_tree, ws, uri, position) = asking("tmplplain", top, " if"); + let items = items(completions(&ws, &uri, position, false)); + let item = find(&items, "if begin/end").expect("the if template"); + assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT)); + let text = inserted(item); + assert!(!text.contains('$'), "no tabstop syntax may reach a plain client: {text}"); + assert_eq!(text, "if (cond) begin\n\n end"); + let probe = format!("module p;\n always_comb begin\n {text}\n end\nendmodule\n"); + assert!( + vlog_parser::parse_source_tolerant(&probe).1.is_empty(), + "the inserted text must parse: {text}" + ); + } + + #[test] + fn a_templates_documentation_shows_what_it_expands_to() { + let top = "module top;\n alw\nendmodule\n"; + let items = offering("tmpldocs", "top.sv", top, " alw"); + let item = find(&items, "always_comb begin/end").expect("the always_comb template"); + let Some(Documentation::MarkupContent(docs)) = &item.documentation else { + panic!("markdown documentation"); + }; + 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] diff --git a/crates/vfmt_server/src/main.rs b/crates/vfmt_server/src/main.rs index 2bd1a26..925019a 100644 --- a/crates/vfmt_server/src/main.rs +++ b/crates/vfmt_server/src/main.rs @@ -24,6 +24,7 @@ mod settings; mod signature; mod state; mod symbols; +mod templates; mod tokens; mod uri; diff --git a/crates/vfmt_server/src/templates.rs b/crates/vfmt_server/src/templates.rs new file mode 100644 index 0000000..ef4cb1c --- /dev/null +++ b/crates/vfmt_server/src/templates.rs @@ -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 = 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 { + 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 { + 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 = 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::>(); + 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}"); + } + } +} diff --git a/crates/vfmt_server/tests/e2e.rs b/crates/vfmt_server/tests/e2e.rs index bb9d406..3b45e85 100644 --- a/crates/vfmt_server/tests/e2e.rs +++ b/crates/vfmt_server/tests/e2e.rs @@ -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); +} diff --git a/docs/features/completion-templates/README.md b/docs/features/completion-templates/README.md new file mode 100644 index 0000000..941422d --- /dev/null +++ b/docs/features/completion-templates/README.md @@ -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 `